pixellint-core 0.11.0

Pixellint core: spec-backed validation engine and declarative rulepacks for pixels, postbacks, and tracking URLs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
//! Consent and privacy signal checks.
//!
//! These rules live in `core` rather than in a vendor pack because the signals
//! are vendor-neutral: IAB Tech Lab specifies them, every endpoint in the chain
//! is expected to carry them, and the failure modes are the same everywhere.
//!
//! Every rule here cites the spec that defines the parameter. Values carrying an
//! unexpanded macro are skipped, because `gdpr=${GDPR}` in a template is correct
//! trafficking, not a malformed signal.

use crate::manifest::{ParamStyle, RawParam, contains_macro, extract_params};
use crate::{RuleSource, RuleSourceLevel, Severity, Violation, ViolationTarget};

const TCF_SPEC: &str = "https://github.com/InteractiveAdvertisingBureau/GDPR-Transparency-and-Consent-Framework/blob/master/TCFv2/IAB%20Tech%20Lab%20-%20Consent%20string%20and%20vendor%20list%20formats%20v2.md";
const USP_SPEC: &str = "https://github.com/InteractiveAdvertisingBureau/USPrivacy/blob/master/CCPA/US%20Privacy%20String.md";
const GPP_SPEC: &str = "https://github.com/InteractiveAdvertisingBureau/Global-Privacy-Platform/blob/main/Core/Consent%20String%20Specification.md";

/// Parameters the specs say must appear at most once in a URL.
const SIGNAL_PARAMS: [&str; 5] = ["gdpr", "gdpr_consent", "us_privacy", "gpp", "gpp_sid"];

pub(crate) fn apply_privacy_rules(artifact: &str, violations: &mut Vec<Violation>) {
    // Consent signals ride in the query on most pixels and in the path on
    // Floodlight-style tags, so both styles have to be read.
    let mut params = extract_params(artifact, ParamStyle::Query);
    params.extend(extract_params(artifact, ParamStyle::Matrix));

    if params.is_empty() {
        return;
    }

    check_duplicates(&params, violations);
    check_tcf(artifact, &params, violations);
    check_us_privacy(&params, violations);
    check_gpp(artifact, &params, violations);
}

fn find<'a>(params: &'a [RawParam], name: &str) -> Option<&'a RawParam> {
    params.iter().find(|param| param.name == name)
}

fn source(name: &str, reference: &str) -> RuleSource {
    RuleSource {
        level: RuleSourceLevel::Normative,
        name: name.to_string(),
        reference: Some(reference.to_string()),
    }
}

fn violation(
    code: &str,
    message: String,
    severity: Severity,
    field: &str,
    fix_hint: &str,
    source: RuleSource,
    targets: Vec<ViolationTarget>,
) -> Violation {
    Violation {
        code: code.to_string(),
        message,
        severity,
        field: Some(field.to_string()),
        fix_hint: Some(fix_hint.to_string()),
        source,
        targets,
    }
}

/// Both the TCF and GPP specs tell URL creators to add each signal exactly once.
/// A repeated signal leaves the callee choosing which copy to believe.
fn check_duplicates(params: &[RawParam], violations: &mut Vec<Violation>) {
    for name in SIGNAL_PARAMS {
        let matches: Vec<&RawParam> = params.iter().filter(|param| param.name == name).collect();

        if matches.len() > 1 {
            violations.push(violation(
                "core.privacy.duplicate_signal",
                format!(
                    "`{name}` appears {} times. A privacy signal must appear once, or the callee has to guess which copy is authoritative.",
                    matches.len()
                ),
                Severity::Warning,
                &format!("param.{name}"),
                &format!("Keep one `{name}` parameter and drop the rest."),
                source("IAB Tech Lab TCF v2", TCF_SPEC),
                matches.iter().map(|param| param.target()).collect(),
            ));
        }
    }
}

fn check_tcf(artifact: &str, params: &[RawParam], violations: &mut Vec<Violation>) {
    let gdpr = find(params, "gdpr");
    let consent = find(params, "gdpr_consent");

    // An empty signal is a template waiting to be filled by an ad server, which
    // is how Floodlight and VAST tags ship. Only a populated value is a claim.
    let applies = match gdpr {
        Some(param) if !contains_macro(&param.value) && !param.value.is_empty() => {
            match param.value.as_str() {
                "0" => Some(false),
                "1" => Some(true),
                other => {
                    violations.push(violation(
                        "core.privacy.gdpr_invalid",
                        format!(
                            "`gdpr` is `{other}`. The TCF specifies `0` when GDPR does not apply and `1` when it does."
                        ),
                        Severity::Error,
                        "param.gdpr",
                        "Send `gdpr=1` in scope of GDPR, `gdpr=0` outside it.",
                        source("IAB Tech Lab TCF v2", TCF_SPEC),
                        vec![param.target()],
                    ));
                    None
                }
            }
        }
        _ => None,
    };

    match (applies, consent) {
        (Some(true), None) => {
            violations.push(violation(
                "core.privacy.gdpr_consent_missing",
                "`gdpr=1` says GDPR applies, but the request carries no `gdpr_consent`. The callee has no TC String to check a legal basis against.".to_string(),
                Severity::Error,
                "param.gdpr_consent",
                "Add `gdpr_consent=${GDPR_CONSENT_XXXXX}` with the receiving vendor's GVL ID, and expand it before firing.",
                source("IAB Tech Lab TCF v2", TCF_SPEC),
                vec![whole_url_target(artifact)],
            ));
        }
        (Some(true), Some(param)) if param.value.is_empty() => {
            violations.push(violation(
                "core.privacy.gdpr_consent_missing",
                "`gdpr=1` says GDPR applies, but `gdpr_consent` is empty.".to_string(),
                Severity::Error,
                "param.gdpr_consent",
                "Populate `gdpr_consent` with the TC String obtained from the CMP.",
                source("IAB Tech Lab TCF v2", TCF_SPEC),
                vec![param.target()],
            ));
        }
        (Some(false), Some(param)) if !param.value.is_empty() && !contains_macro(&param.value) => {
            violations.push(violation(
                "core.privacy.gdpr_consent_ignored",
                "`gdpr=0` says GDPR does not apply, so the TC String in `gdpr_consent` is not meaningful for this call.".to_string(),
                Severity::Info,
                "param.gdpr_consent",
                "Leave `gdpr_consent` out when `gdpr=0`, or check that the flag is right.",
                source("IAB Tech Lab TCF v2", TCF_SPEC),
                vec![param.target()],
            ));
        }
        _ => {}
    }

    if let Some(param) = consent
        && !param.value.is_empty()
        && !contains_macro(&param.value)
    {
        if gdpr.is_none() {
            violations.push(violation(
                "core.privacy.gdpr_consent_without_flag",
                "`gdpr_consent` is present but `gdpr` is not, so the callee cannot tell whether GDPR applies to this call.".to_string(),
                Severity::Warning,
                "param.gdpr",
                "Send `gdpr=1` alongside the TC String, or `gdpr=0` when GDPR does not apply.",
                source("IAB Tech Lab TCF v2", TCF_SPEC),
                vec![param.target()],
            ));
        }

        if !is_tc_string(&param.value) {
            violations.push(violation(
                "core.privacy.gdpr_consent_malformed",
                format!(
                    "`gdpr_consent` is `{}`, which is not a URL-safe base64 TC String.",
                    truncate(&param.value)
                ),
                Severity::Warning,
                "param.gdpr_consent",
                "Pass the TC String from the CMP unmodified, without re-encoding it.",
                source("IAB Tech Lab TCF v2", TCF_SPEC),
                vec![param.target()],
            ));
        } else {
            check_tc_string_contents(param, violations);
        }
    }
}

/// Reads the fields the TC String spec fixes, once the value is known to be
/// base64.
///
/// The alphabet check above passes anything spelled with base64 characters, and
/// plenty of things are: `gdpr_consent=1` is a well-formed base64 segment that
/// decodes to nothing resembling consent. What separates a TC String from a
/// string is the Version field the spec pins to 2, and enough length to hold the
/// fields it lists as mandatory.
fn check_tc_string_contents(param: &RawParam, violations: &mut Vec<Violation>) {
    // Only the core segment is fixed. Optional segments follow a dot and carry
    // their own layout.
    let core = param.value.split('.').next().unwrap_or_default();

    match read_bits(core, 0, 6) {
        Some(2) => {}
        Some(1) => {
            violations.push(violation(
                "core.privacy.tc_string_version",
                "`gdpr_consent` carries a TCF v1 TC String. IAB Tech Lab sunset v1 on 15 August 2020, and v2 vendors cannot read it."
                    .to_string(),
                Severity::Error,
                "param.gdpr_consent",
                "Take the TC String from a TCF v2 CMP.",
                source("IAB Tech Lab TCF v2", TCF_SPEC),
                vec![param.target()],
            ));
            return;
        }
        Some(version) => {
            violations.push(violation(
                "core.privacy.tc_string_version",
                format!(
                    "`gdpr_consent` is `{}`, whose first six bits decode to version {version}. The TC String spec fixes the version to 2, so this is not a TC String.",
                    truncate(&param.value)
                ),
                Severity::Error,
                "param.gdpr_consent",
                "Pass the TC String from the CMP. A placeholder such as `1` is base64-shaped but carries no consent.",
                source("IAB Tech Lab TCF v2", TCF_SPEC),
                vec![param.target()],
            ));
            return;
        }
        None => return,
    }

    if core.len() < TC_CORE_MIN_CHARS {
        violations.push(violation(
            "core.privacy.tc_string_truncated",
            format!(
                "`gdpr_consent` has a {}-character core segment. The mandatory fields through PublisherCC need {TC_CORE_MANDATORY_BITS} bits, so a TC String cannot be shorter than {TC_CORE_MIN_CHARS} characters.",
                core.len()
            ),
            Severity::Error,
            "param.gdpr_consent",
            "Pass the whole TC String. Truncation usually comes from a length limit on a macro or a database column.",
            source("IAB Tech Lab TCF v2", TCF_SPEC),
            vec![param.target()],
        ));
    }
}

fn check_us_privacy(params: &[RawParam], violations: &mut Vec<Violation>) {
    let Some(param) = find(params, "us_privacy") else {
        return;
    };

    if contains_macro(&param.value) || param.value.is_empty() {
        return;
    }

    violations.push(violation(
        "core.privacy.us_privacy_deprecated",
        "`us_privacy` carries the US Privacy signal, which IAB Tech Lab deprecated on 31 January 2024 in favor of the Global Privacy Platform.".to_string(),
        Severity::Warning,
        "param.us_privacy",
        "Move to `gpp` and `gpp_sid`. Sending both during a migration is fine.",
        source("IAB Tech Lab US Privacy String", USP_SPEC),
        vec![param.target()],
    ));

    if !is_us_privacy_string(&param.value) {
        violations.push(violation(
            "core.privacy.us_privacy_malformed",
            format!(
                "`us_privacy` is `{}`. The string is a version digit followed by three characters, each `Y`, `N`, or `-`, for notice, opt-out of sale, and LSPA coverage.",
                truncate(&param.value)
            ),
            Severity::Error,
            "param.us_privacy",
            "Send a value such as `1YNN`, or `1---` when no US privacy jurisdiction applies.",
            source("IAB Tech Lab US Privacy String", USP_SPEC),
            vec![param.target()],
        ));
    } else if !param.value.starts_with('1') {
        // The shape is right, so the leading character is a version claim rather
        // than noise. Only version 1 was ever published.
        violations.push(violation(
            "core.privacy.us_privacy_version",
            format!(
                "`us_privacy` claims specification version `{}`. Only version 1 was published before the signal was deprecated.",
                &param.value[..1]
            ),
            Severity::Warning,
            "param.us_privacy",
            "Send `1` as the first character, or move to `gpp` and `gpp_sid`.",
            source("IAB Tech Lab US Privacy String", USP_SPEC),
            vec![param.target()],
        ));
    }
}

fn check_gpp(artifact: &str, params: &[RawParam], violations: &mut Vec<Violation>) {
    let gpp = find(params, "gpp");
    let sid = find(params, "gpp_sid");

    if let Some(param) = gpp
        && !param.value.is_empty()
        && !contains_macro(&param.value)
    {
        if !is_gpp_string(&param.value) {
            violations.push(violation(
                "core.privacy.gpp_malformed",
                format!(
                    "`gpp` is `{}`, which is not a URL-safe base64 GPP string. Sections are separated by `~`.",
                    truncate(&param.value)
                ),
                Severity::Warning,
                "param.gpp",
                "Pass the GPP string from the CMP unmodified.",
                source("IAB Tech Lab GPP", GPP_SPEC),
                vec![param.target()],
            ));
        } else {
            check_gpp_header(param, violations);
        }

        if sid.is_none() {
            violations.push(violation(
                "core.privacy.gpp_sid_missing",
                "`gpp` is present without `gpp_sid`, so the callee does not know which section of the string is in force.".to_string(),
                Severity::Warning,
                "param.gpp_sid",
                "Add `gpp_sid=${GPP_SID}` next to the GPP string.",
                source("IAB Tech Lab GPP", GPP_SPEC),
                vec![whole_url_target(artifact)],
            ));
        }
    }

    if let Some(param) = sid
        && !param.value.is_empty()
        && !contains_macro(&param.value)
        && !is_gpp_sid(&param.value)
    {
        violations.push(violation(
            "core.privacy.gpp_sid_malformed",
            format!(
                "`gpp_sid` is `{}`. It carries the section IDs in force, normally one, at most two separated by a comma.",
                truncate(&param.value)
            ),
            Severity::Warning,
            "param.gpp_sid",
            "Send the section ID the CMP reports, such as `gpp_sid=2`.",
            source("IAB Tech Lab GPP", GPP_SPEC),
            vec![param.target()],
        ));
    }
}

/// Reads the GPP header, which the spec pins to a fixed type and version.
///
/// The header is the first section, and its first six bits are "fixed to 3 as
/// GPP Header field". That makes a value in `gpp` that is not a GPP string
/// cheap to spot: a TC String pasted into the wrong parameter decodes to type 2
/// and stops here.
fn check_gpp_header(param: &RawParam, violations: &mut Vec<Violation>) {
    let header = param.value.split('~').next().unwrap_or_default();

    match read_bits(header, 0, 6) {
        Some(3) => {}
        Some(kind) => {
            violations.push(violation(
                "core.privacy.gpp_header_type",
                format!(
                    "`gpp` is `{}`, whose header decodes to type {kind}. The GPP spec fixes the header type to 3, so this is not a GPP string.",
                    truncate(&param.value)
                ),
                Severity::Error,
                "param.gpp",
                "Send the GPP string from the CMP. A TC String belongs in `gdpr_consent`, not here.",
                source("IAB Tech Lab GPP", GPP_SPEC),
                vec![param.target()],
            ));
            return;
        }
        None => return,
    }

    if let Some(version) = read_bits(header, 6, 6)
        && version != 1
    {
        violations.push(violation(
            "core.privacy.gpp_header_version",
            format!(
                "`gpp` declares GPP specification version {version}. Version 1 is the published one, and a callee reading the header will stop at an unknown version."
            ),
            Severity::Warning,
            "param.gpp",
            "Send a version 1 GPP string, which starts `DB`.",
            source("IAB Tech Lab GPP", GPP_SPEC),
            vec![param.target()],
        ));
    }
}

fn whole_url_target(artifact: &str) -> ViolationTarget {
    ViolationTarget {
        component: crate::ViolationTargetComponent::WholeUrl,
        name: None,
        value: None,
        start: 0,
        end: artifact.len(),
    }
}

fn truncate(value: &str) -> String {
    if value.chars().count() <= 32 {
        return value.to_string();
    }

    let head: String = value.chars().take(32).collect();
    format!("{head}...")
}

fn is_base64url_segment(segment: &str) -> bool {
    !segment.is_empty()
        && segment.chars().all(|character| {
            character.is_ascii_alphanumeric() || character == '-' || character == '_'
        })
}

/// A TC String is URL-safe base64. Optional segments are appended after `.`.
fn is_tc_string(value: &str) -> bool {
    value.split('.').all(is_base64url_segment)
}

/// The value of one URL-safe base64 character, as the 6 bits it stands for.
fn base64url_bits(character: u8) -> Option<u32> {
    Some(match character {
        b'A'..=b'Z' => u32::from(character - b'A'),
        b'a'..=b'z' => u32::from(character - b'a') + 26,
        b'0'..=b'9' => u32::from(character - b'0') + 52,
        b'-' => 62,
        b'_' => 63,
        _ => return None,
    })
}

/// Reads a big-endian bit field out of a URL-safe base64 segment.
///
/// The consent specs describe their strings as bit fields that happen to be
/// base64 for transport, so reading a field means going back to the bits rather
/// than decoding to bytes.
fn read_bits(segment: &str, start: usize, length: usize) -> Option<u64> {
    if length == 0 || length > 64 {
        return None;
    }

    let bytes = segment.as_bytes();
    let mut value: u64 = 0;

    for offset in start..start + length {
        let character = *bytes.get(offset / 6)?;
        let bits = base64url_bits(character)?;
        let bit = (bits >> (5 - (offset % 6))) & 1;
        value = (value << 1) | u64::from(bit);
    }

    Some(value)
}

/// Bits the core segment needs for the fields the spec lists as mandatory, from
/// Version through PublisherCC. The segment carries more after that, so this is
/// a floor rather than a size.
const TC_CORE_MANDATORY_BITS: usize = 213;

/// Characters those bits take once encoded.
const TC_CORE_MIN_CHARS: usize = TC_CORE_MANDATORY_BITS.div_ceil(6);

/// A GPP string is URL-safe base64 with sections separated by `~`.
fn is_gpp_string(value: &str) -> bool {
    value
        .split('~')
        .all(|section| section.split('.').all(is_base64url_segment))
}

fn is_us_privacy_string(value: &str) -> bool {
    let bytes = value.as_bytes();

    bytes.len() == 4
        && bytes[0].is_ascii_digit()
        && bytes[1..]
            .iter()
            .all(|byte| matches!(byte.to_ascii_uppercase(), b'Y' | b'N' | b'-'))
}

fn is_gpp_sid(value: &str) -> bool {
    let sections: Vec<&str> = value.split(',').collect();

    sections.len() <= 2
        && sections
            .iter()
            .all(|section| !section.is_empty() && section.chars().all(|c| c.is_ascii_digit()))
}

#[cfg(test)]
mod tests {
    use crate::{ArtifactKind, Engine, ExpansionState, ValidationOptions, ValidationRequest};

    fn codes(artifact: &str) -> Vec<String> {
        let request = ValidationRequest {
            artifact_kind: ArtifactKind::Url,
            artifact: artifact.to_string(),
            claimed_vendor: None,
            expansion_state: ExpansionState::Unknown,
        };

        Engine::default()
            .validate(&request, &ValidationOptions::default())
            .expect("validate")
            .reports
            .iter()
            .flat_map(|report| report.violations.iter())
            .map(|violation| violation.code.clone())
            .filter(|code| code.starts_with("core.privacy."))
            .collect()
    }

    #[test]
    fn a_complete_tcf_signal_is_clean() {
        assert!(
            codes("https://example.com/px?gdpr=1&gdpr_consent=CPXxRfAPXxRfAAfKABENB-CgAAAAAAAAAAYgAAAAAAAAAAfKABENB-CgAAAAAAAAAAYgAAAAAAAA").is_empty()
        );
        assert!(codes("https://example.com/px?gdpr=0").is_empty());
    }

    #[test]
    fn gdpr_flag_values_are_constrained() {
        assert_eq!(
            codes(
                "https://example.com/px?gdpr=true&gdpr_consent=CPXxRfAPXxRfAAfKABENB-CgAAAAAAAAAAYgAAAAAAAA"
            ),
            vec!["core.privacy.gdpr_invalid"]
        );
    }

    #[test]
    fn gdpr_applying_without_a_tc_string_is_an_error() {
        assert_eq!(
            codes("https://example.com/px?gdpr=1"),
            vec!["core.privacy.gdpr_consent_missing"]
        );
        assert_eq!(
            codes("https://example.com/px?gdpr=1&gdpr_consent="),
            vec!["core.privacy.gdpr_consent_missing"]
        );
    }

    #[test]
    fn a_tc_string_without_a_flag_is_ambiguous() {
        assert_eq!(
            codes(
                "https://example.com/px?gdpr_consent=CPXxRfAPXxRfAAfKABENB-CgAAAAAAAAAAYgAAAAAAAA"
            ),
            vec!["core.privacy.gdpr_consent_without_flag"]
        );
    }

    #[test]
    fn a_tc_string_outside_gdpr_is_informational() {
        assert_eq!(
            codes(
                "https://example.com/px?gdpr=0&gdpr_consent=CPXxRfAPXxRfAAfKABENB-CgAAAAAAAAAAYgAAAAAAAA"
            ),
            vec!["core.privacy.gdpr_consent_ignored"]
        );
    }

    #[test]
    fn a_placeholder_in_the_consent_slot_is_not_a_tc_string() {
        // Base64 characters, so the alphabet check passes it. The version field
        // is what gives it away.
        assert_eq!(
            codes("https://example.com/px?gdpr=1&gdpr_consent=1"),
            ["core.privacy.tc_string_version"]
        );
        assert_eq!(
            codes("https://example.com/px?gdpr=1&gdpr_consent=true"),
            ["core.privacy.tc_string_version"]
        );
    }

    #[test]
    fn a_tcf_v1_string_is_reported_as_sunset() {
        assert_eq!(
            codes("https://example.com/px?gdpr=1&gdpr_consent=BOxxRfAOxxRfAAfKABENAAAAAAAAoAAA"),
            ["core.privacy.tc_string_version"]
        );
    }

    #[test]
    fn a_truncated_tc_string_is_flagged() {
        // Right version, too short to hold the fields the spec makes mandatory.
        assert_eq!(
            codes("https://example.com/px?gdpr=1&gdpr_consent=CPXxRfAPXxRf"),
            ["core.privacy.tc_string_truncated"]
        );
    }

    #[test]
    fn a_us_privacy_version_other_than_one_is_flagged() {
        assert_eq!(
            codes("https://example.com/px?us_privacy=2YNN"),
            [
                "core.privacy.us_privacy_deprecated",
                "core.privacy.us_privacy_version"
            ]
        );
    }

    #[test]
    fn a_tc_string_in_the_gpp_slot_is_flagged() {
        // The commonest way to get this wrong is to put the right string in the
        // wrong parameter. The header type says so.
        assert_eq!(
            codes(
                "https://example.com/px?gpp=CPXxRfAPXxRfAAfKABENB-CgAAAAAAAAAAYgAAAAAAAA&gpp_sid=2"
            ),
            ["core.privacy.gpp_header_type"]
        );
    }

    #[test]
    fn an_unknown_gpp_version_is_flagged() {
        assert_eq!(
            codes("https://example.com/px?gpp=DCABMA&gpp_sid=2"),
            ["core.privacy.gpp_header_version"]
        );
    }

    #[test]
    fn malformed_tc_strings_are_flagged() {
        assert_eq!(
            codes("https://example.com/px?gdpr=1&gdpr_consent=not a tc string"),
            vec!["core.privacy.gdpr_consent_malformed"]
        );
    }

    #[test]
    fn unexpanded_macros_are_left_to_the_macro_rules() {
        assert!(
            codes("https://example.com/px?gdpr=${GDPR}&gdpr_consent=${GDPR_CONSENT_123}")
                .is_empty()
        );
        assert!(codes("https://example.com/px?us_privacy=${US_PRIVACY}").is_empty());
        assert!(
            codes("https://example.com/px?gpp=${GPP_STRING_123}&gpp_sid=${GPP_SID}").is_empty()
        );
    }

    #[test]
    fn us_privacy_is_deprecated_and_format_checked() {
        assert_eq!(
            codes("https://example.com/px?us_privacy=1YNN"),
            vec!["core.privacy.us_privacy_deprecated"]
        );
        assert_eq!(
            codes("https://example.com/px?us_privacy=YES"),
            vec![
                "core.privacy.us_privacy_deprecated",
                "core.privacy.us_privacy_malformed"
            ]
        );
        assert_eq!(
            codes("https://example.com/px?us_privacy=1---"),
            vec!["core.privacy.us_privacy_deprecated"]
        );
    }

    #[test]
    fn gpp_needs_a_section_id() {
        assert_eq!(
            codes(
                "https://example.com/px?gpp=DBACNYA~CPXxRfAPXxRfAAfKABENB-CgAAAAAAAAAAYgAAAAAAAA~1YNN"
            ),
            vec!["core.privacy.gpp_sid_missing"]
        );
        assert!(codes("https://example.com/px?gpp=DBACNYA~CPXxRfAPXxRfAAfKABENB-CgAAAAAAAAAAYgAAAAAAAA~1YNN&gpp_sid=2").is_empty());
        assert!(codes("https://example.com/px?gpp=DBACNYA~CPXxRfAPXxRfAAfKABENB-CgAAAAAAAAAAYgAAAAAAAA&gpp_sid=2,6").is_empty());
    }

    #[test]
    fn gpp_values_are_format_checked() {
        assert_eq!(
            codes("https://example.com/px?gpp=not a gpp string&gpp_sid=2"),
            vec!["core.privacy.gpp_malformed"]
        );
        assert_eq!(
            codes(
                "https://example.com/px?gpp=DBACNYA~CPXxRfAPXxRfAAfKABENB-CgAAAAAAAAAAYgAAAAAAAA&gpp_sid=usnat"
            ),
            vec!["core.privacy.gpp_sid_malformed"]
        );
        assert_eq!(
            codes("https://example.com/px?gpp=DBACNYA&gpp_sid=2,6,8"),
            vec!["core.privacy.gpp_sid_malformed"]
        );
    }

    #[test]
    fn repeated_signals_are_flagged_once_per_parameter() {
        assert_eq!(
            codes(
                "https://example.com/px?gdpr=1&gdpr=0&gdpr_consent=CPXxRfAPXxRfAAfKABENB-CgAAAAAAAAAAYgAAAAAAAA"
            ),
            vec!["core.privacy.duplicate_signal"]
        );
    }

    #[test]
    fn signals_carried_on_the_path_are_checked_too() {
        assert_eq!(
            codes("https://ad.doubleclick.net/ddm/activity/src=123;type=a;cat=b;gdpr=1;ord=1?"),
            vec!["core.privacy.gdpr_consent_missing"]
        );
    }

    #[test]
    fn empty_signals_are_treated_as_unfilled_templates() {
        assert!(
            codes(
                "https://ad.doubleclick.net/ddm/activity/src=123;type=a;cat=b;dc_rdid=;tfua=;npa=;gdpr=;gdpr_consent=;ord=1?"
            )
            .is_empty()
        );
    }

    #[test]
    fn artifacts_without_privacy_signals_are_untouched() {
        assert!(codes("https://example.com/px?id=1&ev=PageView").is_empty());
    }
}