github.com/prebid/prebid-server/v2@v2.18.0/gdpr/consent_parser.go (about) 1 package gdpr 2 3 import ( 4 "errors" 5 "fmt" 6 7 "github.com/prebid/go-gdpr/api" 8 "github.com/prebid/go-gdpr/vendorconsent" 9 tcf2 "github.com/prebid/go-gdpr/vendorconsent/tcf2" 10 ) 11 12 // parsedConsent represents a parsed consent string containing notable version information and a convenient 13 // metadata object that allows easy examination of encoded purpose and vendor information 14 type parsedConsent struct { 15 encodingVersion uint8 16 listVersion uint16 17 specVersion uint16 18 consentMeta tcf2.ConsentMetadata 19 } 20 21 // parseConsent parses and validates the specified consent string returning an instance of parsedConsent 22 func parseConsent(consent string) (*parsedConsent, error) { 23 pc, err := vendorconsent.ParseString(consent) 24 if err != nil { 25 return nil, &ErrorMalformedConsent{ 26 Consent: consent, 27 Cause: err, 28 } 29 } 30 if err = validateVersions(pc); err != nil { 31 return nil, &ErrorMalformedConsent{ 32 Consent: consent, 33 Cause: err, 34 } 35 } 36 cm, ok := pc.(tcf2.ConsentMetadata) 37 if !ok { 38 err = errors.New("Unable to access TCF2 parsed consent") 39 return nil, err 40 } 41 return &parsedConsent{ 42 encodingVersion: pc.Version(), 43 listVersion: pc.VendorListVersion(), 44 specVersion: getSpecVersion(pc.TCFPolicyVersion()), 45 consentMeta: cm, 46 }, nil 47 } 48 49 // validateVersions ensures that certain version fields in the consent string contain valid values. 50 // An error is returned if at least one of them is invalid 51 func validateVersions(pc api.VendorConsents) (err error) { 52 version := pc.Version() 53 if version != 2 { 54 return fmt.Errorf("invalid encoding format version: %d", version) 55 } 56 return 57 } 58 59 // getSpecVersion looks at the TCF policy version and determines the corresponding GVL specification 60 // version that should be used to calculate legal basis. A zero value is returned if the policy version 61 // is invalid 62 func getSpecVersion(policyVersion uint8) uint16 { 63 if policyVersion >= 4 { 64 return 3 65 } 66 return 2 67 }