pixellint-core 0.30.3

Pixellint core: spec-backed validation engine and declarative rulepacks for pixels, postbacks, conversion API payloads, 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
//! Vendor endpoint directory.
//!
//! The directory answers one question a rulepack cannot: whose pixel is this?
//! It maps hosts to vendors and nothing else. Entries carry no parameter
//! contracts and no rule text, so a directory hit never asserts that an
//! artifact is right or wrong; it says which vendor owns the endpoint and
//! whether Pixellint has a rulepack for it.
//!
//! That split is deliberate. Rules require a citable contract, and most vendors
//! never publish one. Attribution is a weaker claim that can be made honestly
//! for the long tail.

use std::error::Error;
use std::fmt;
use std::fs;
use std::path::Path;

use serde::{Deserialize, Serialize};

/// Pseudo-rulepack id used to include or exclude the directory in
/// [`ValidationOptions`](crate::ValidationOptions).
pub const DIRECTORY_ID: &str = "directory";

/// One vendor and the endpoints it serves.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct VendorEntry {
    /// Stable vendor slug, reported as `detected_vendor`.
    pub vendor: String,
    pub display_name: String,
    /// Broad function of the endpoint: social, programmatic, analytics, and so on.
    pub category: String,
    /// Hosts the vendor serves. A host also matches its subdomains.
    pub hosts: Vec<String>,
    /// First-party rulepack that covers some of this vendor's endpoints, if one
    /// exists.
    #[serde(default)]
    pub rulepack: Option<String>,
}

/// A set of vendor entries.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct VendorDirectory {
    entries: Vec<VendorEntry>,
}

/// Why a directory could not be loaded.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DirectoryError {
    Parse(String),
    Io(String),
    EmptyField {
        vendor: String,
        field: &'static str,
    },
    DuplicateHost {
        host: String,
        vendors: (String, String),
    },
}

impl fmt::Display for DirectoryError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Parse(error) => write!(f, "invalid vendor directory JSON: {error}"),
            Self::Io(error) => write!(f, "could not read vendor directory: {error}"),
            Self::EmptyField { vendor, field } => {
                write!(
                    f,
                    "vendor directory entry `{vendor}` has an empty `{field}`"
                )
            }
            Self::DuplicateHost {
                host,
                vendors: (first, second),
            } => write!(
                f,
                "host `{host}` is claimed by both `{first}` and `{second}` in the vendor directory"
            ),
        }
    }
}

impl Error for DirectoryError {}

impl VendorDirectory {
    /// The directory compiled into the crate.
    ///
    /// Parsing is proven by tests, so a malformed built-in directory is a build
    /// failure rather than a runtime surprise.
    pub fn builtin() -> Self {
        Self::from_json(crate::BUILTIN_VENDOR_DIRECTORY)
            .expect("built-in vendor directory should be valid")
    }

    pub fn from_json(json: &str) -> Result<Self, DirectoryError> {
        let directory: Self =
            serde_json::from_str(json).map_err(|error| DirectoryError::Parse(error.to_string()))?;
        directory.validate()?;
        Ok(directory)
    }

    pub fn from_path(path: impl AsRef<Path>) -> Result<Self, DirectoryError> {
        let path = path.as_ref();
        let json = fs::read_to_string(path)
            .map_err(|error| DirectoryError::Io(format!("{}: {error}", path.display())))?;
        Self::from_json(&json)
    }

    fn validate(&self) -> Result<(), DirectoryError> {
        let mut claimed: Vec<(String, &str)> = Vec::new();

        for entry in &self.entries {
            for (field, value) in [
                ("vendor", &entry.vendor),
                ("display_name", &entry.display_name),
                ("category", &entry.category),
            ] {
                if value.trim().is_empty() {
                    return Err(DirectoryError::EmptyField {
                        vendor: entry.vendor.clone(),
                        field,
                    });
                }
            }

            if entry.hosts.is_empty() {
                return Err(DirectoryError::EmptyField {
                    vendor: entry.vendor.clone(),
                    field: "hosts",
                });
            }

            for host in &entry.hosts {
                let host = host.to_ascii_lowercase();

                if let Some((_, owner)) = claimed.iter().find(|(claimed, _)| claimed == &host) {
                    return Err(DirectoryError::DuplicateHost {
                        host,
                        vendors: ((*owner).to_string(), entry.vendor.clone()),
                    });
                }

                claimed.push((host, entry.vendor.as_str()));
            }
        }

        Ok(())
    }

    /// Adds entries from another directory. A host already claimed by a
    /// different vendor is rejected, so an overlay cannot steal attribution.
    pub fn merge(&mut self, other: Self) -> Result<(), DirectoryError> {
        self.entries.extend(other.entries);
        self.validate()?;
        Ok(())
    }

    pub fn entries(&self) -> &[VendorEntry] {
        &self.entries
    }

    pub fn len(&self) -> usize {
        self.entries.len()
    }

    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Total hosts across every entry.
    pub fn host_count(&self) -> usize {
        self.entries.iter().map(|entry| entry.hosts.len()).sum()
    }

    /// Finds the vendor that serves a host. A directory host also matches its
    /// subdomains, so `sc-static.net` covers `cdn.sc-static.net`.
    pub fn lookup_host(&self, host: &str) -> Option<&VendorEntry> {
        let host = host.to_ascii_lowercase();

        self.entries.iter().find(|entry| {
            entry.hosts.iter().any(|candidate| {
                let candidate = candidate.to_ascii_lowercase();
                host == candidate || host.ends_with(&format!(".{candidate}"))
            })
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const TEST_DIRECTORY: &str = r#"{
        "entries": [
            {
                "vendor": "acme",
                "display_name": "Acme",
                "category": "programmatic",
                "hosts": ["px.acme.example", "acme-static.example"],
                "rulepack": "vendor/acme"
            },
            {
                "vendor": "globex",
                "display_name": "Globex",
                "category": "analytics",
                "hosts": ["globex.example"]
            }
        ]
    }"#;

    #[test]
    fn lookup_matches_exact_hosts_and_subdomains() {
        let directory = VendorDirectory::from_json(TEST_DIRECTORY).expect("parse");

        assert_eq!(
            directory.lookup_host("px.acme.example").map(|e| &e.vendor),
            Some(&"acme".to_string())
        );
        assert_eq!(
            directory
                .lookup_host("cdn.acme-static.example")
                .map(|e| &e.vendor),
            Some(&"acme".to_string())
        );
        assert_eq!(
            directory.lookup_host("GLOBEX.EXAMPLE").map(|e| &e.vendor),
            Some(&"globex".to_string())
        );
        assert_eq!(directory.lookup_host("notglobex.example"), None);
        assert_eq!(directory.lookup_host("example.com"), None);
    }

    #[test]
    fn duplicate_hosts_are_rejected() {
        let json = TEST_DIRECTORY.replace(r#""globex.example""#, r#""px.acme.example""#);
        let error = VendorDirectory::from_json(&json).expect_err("duplicates are caught");
        assert!(
            matches!(error, DirectoryError::DuplicateHost { .. }),
            "{error}"
        );
    }

    #[test]
    fn merge_adds_new_hosts_and_rejects_stolen_ones() {
        let mut directory = VendorDirectory::from_json(TEST_DIRECTORY).expect("parse");
        let extra = VendorDirectory::from_json(
            r#"{
                "entries": [
                    {
                        "vendor": "initech",
                        "display_name": "Initech",
                        "category": "analytics",
                        "hosts": ["px.initech.example"]
                    }
                ]
            }"#,
        )
        .expect("overlay");
        directory.merge(extra).expect("new hosts merge");
        assert_eq!(
            directory
                .lookup_host("px.initech.example")
                .map(|entry| entry.vendor.as_str()),
            Some("initech")
        );

        let stolen = VendorDirectory::from_json(
            r#"{
                "entries": [
                    {
                        "vendor": "initech",
                        "display_name": "Initech",
                        "category": "analytics",
                        "hosts": ["px.acme.example"]
                    }
                ]
            }"#,
        )
        .expect("stolen overlay");
        let error = directory.merge(stolen).expect_err("cannot steal a host");
        assert!(
            matches!(error, DirectoryError::DuplicateHost { .. }),
            "{error}"
        );
    }

    #[test]
    fn entries_need_a_vendor_and_hosts() {
        let json = TEST_DIRECTORY.replace(r#""vendor": "globex""#, r#""vendor": """#);
        let error = VendorDirectory::from_json(&json).expect_err("empty vendor is caught");
        assert!(
            matches!(error, DirectoryError::EmptyField { .. }),
            "{error}"
        );

        let json = TEST_DIRECTORY.replace(r#""hosts": ["globex.example"]"#, r#""hosts": []"#);
        let error = VendorDirectory::from_json(&json).expect_err("empty hosts are caught");
        assert!(
            matches!(error, DirectoryError::EmptyField { .. }),
            "{error}"
        );
    }

    #[test]
    fn unknown_fields_are_rejected() {
        let json =
            TEST_DIRECTORY.replace(r#""vendor": "acme","#, r#""vendor": "acme", "oops": 1,"#);
        let error = VendorDirectory::from_json(&json).expect_err("unknown fields are caught");
        assert!(matches!(error, DirectoryError::Parse(_)), "{error}");
    }

    #[test]
    fn the_builtin_directory_loads_and_covers_the_shipped_packs() {
        let directory = VendorDirectory::builtin();

        assert!(
            directory.len() >= 80,
            "directory shrank to {}",
            directory.len()
        );
        assert!(directory.host_count() >= 200);

        for host in [
            "www.facebook.com",
            "analytics.tiktok.com",
            "ct.pinterest.com",
            "trc.taboola.com",
            "pixel.quantserve.com",
            "track.celtra.com",
            "tpsc-video-as.doubleverify.com",
            "tpsc-video-eu.doubleverify.com",
            "d9.flashtalking.com",
            "qa-xre.flashtalking.net",
            "s.update.3lift.com",
            "rtb-us-west.linkedin.com",
            "beacons.extremereach.io",
            "analytics.adcanvas.com",
            "stats.sxp.smartclip.net",
            "log.xpln.tech",
            "cs10.connected-stories.com",
            "postback.iqm.com",
            "tr.blismedia.com",
            "www.googletagmanager.com",
            "ad.doubleclick.net",
            "ade.googlesyndication.com",
            "pubads.g.doubleclick.net",
            "vfw.amazon-adsystem.com",
            "s.amazon-adsystem.com",
            "e-11428.adzerk.net",
            "eu-adsrv.rtbsuperhub.com",
            "event.havasedge.com",
            "beeswax-ipv4-prod.telemetry.vaultdcr.com",
        ] {
            assert!(
                directory.lookup_host(host).is_some(),
                "{host} is not in the directory"
            );
        }

        let gtm = directory
            .lookup_host("www.googletagmanager.com")
            .expect("gtm");
        assert_eq!(gtm.rulepack.as_deref(), Some("vendor/google-tag-manager"));

        let cm360 = directory.lookup_host("ad.doubleclick.net").expect("cm360");
        assert_eq!(cm360.rulepack.as_deref(), Some("vendor/floodlight"));

        let gam = directory
            .lookup_host("ade.googlesyndication.com")
            .expect("gam");
        assert_eq!(gam.display_name, "Google Ad Manager");
        assert_eq!(gam.rulepack.as_deref(), Some("vendor/google-ad-manager"));

        let firefly = directory
            .lookup_host("vfw.amazon-adsystem.com")
            .expect("vfw");
        assert_eq!(firefly.rulepack.as_deref(), Some("vendor/amazon-vfw"));

        let ad_tag = directory
            .lookup_host("s.amazon-adsystem.com")
            .expect("ad tag");
        assert_eq!(ad_tag.rulepack.as_deref(), Some("vendor/amazon-ads"));

        // Every rulepack an entry points at has to exist, and every first-party
        // pack's vendor has to point at some pack. Directory hits on a covered
        // vendor should say coverage exists elsewhere, not that the vendor is
        // unknown to the rulepacks. A vendor may have several directory rows
        // (Google Tag Manager vs Google Ad Manager); only one of them needs a
        // pointer.
        let pack_ids: Vec<&str> = crate::BUILTIN_VENDOR_MANIFESTS
            .iter()
            .map(|(id, _)| *id)
            .collect();
        for entry in directory.entries() {
            if let Some(rulepack) = &entry.rulepack {
                assert!(
                    pack_ids.contains(&rulepack.as_str()),
                    "directory entry `{}` points at unknown rulepack `{rulepack}`",
                    entry.vendor
                );
            }
        }

        for (id, json) in crate::BUILTIN_VENDOR_MANIFESTS {
            let manifest: serde_json::Value =
                serde_json::from_str(json).unwrap_or_else(|error| panic!("{id}: {error}"));
            let vendor = manifest["vendor"]
                .as_str()
                .unwrap_or_else(|| panic!("{id} is missing vendor"));
            let entries: Vec<_> = directory
                .entries()
                .iter()
                .filter(|entry| entry.vendor == vendor)
                .collect();
            assert!(
                !entries.is_empty(),
                "no directory entry for pack `{id}` vendor `{vendor}`"
            );
            assert!(
                entries.iter().any(|entry| entry.rulepack.is_some()),
                "directory vendor `{vendor}` has pack `{id}` but no rulepack pointer"
            );
        }
    }
}