dpp-domain 0.13.0

EU Digital Product Passport domain types, port traits, and open-core boundary
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
//! `SectorCatalog` load, gating, registration, and cross-artifact parity tests.

use super::*;

#[test]
fn loads_all_embedded_manifests() {
    let catalog = SectorCatalog::new();
    assert_eq!(catalog.len(), 11);
}

#[test]
fn exactly_three_sectors_are_in_force() {
    let catalog = SectorCatalog::new();
    let mut in_force: Vec<&str> = catalog.in_force().iter().map(|d| d.key.as_str()).collect();
    in_force.sort_unstable();
    assert_eq!(in_force, vec!["battery", "electronics", "unsold-goods"]);
}

#[test]
fn provisional_sectors_are_flagged_not_dropped() {
    let catalog = SectorCatalog::new();
    // All eight not-yet-adopted sectors are still present, just flagged.
    assert_eq!(catalog.provisional().len(), 8);
    assert!(!catalog.is_in_force("textile"));
    assert!(!catalog.is_in_force("steel"));
}

#[test]
fn battery_descriptor_is_complete() {
    let catalog = SectorCatalog::new();
    let battery = catalog.get("battery").expect("battery in catalog");
    assert_eq!(battery.status, RegulatoryStatus::InForce);
    assert_eq!(battery.dpp_applies_from.as_deref(), Some("2027-02-18"));
    assert_eq!(battery.retention_years, 10);
    assert!(battery.schema_versions.contains(&"2.0.0".to_string()));
    assert!(battery.schema_versions.contains(&"2.1.0".to_string()));
    assert!(battery.schema_versions.contains(&"2.2.0".to_string()));
    assert!(battery.schema_versions.contains(&"2.3.0".to_string()));
    assert!(battery.schema_versions.contains(&"2.4.0".to_string()));
    // Current version is v2.2.0, which adds the Annex VII Part A state-of-health
    // parameter sets. Older versions stay registered so passports already
    // validated against them remain verifiable.
    assert_eq!(battery.current_schema_version, "2.4.0");
    assert_eq!(battery.plugin.as_deref(), Some("sector-battery"));
}

#[test]
fn resolve_schema_version_new_vs_existing() {
    let catalog = SectorCatalog::new();
    // New passport (stored = None) → catalog current version.
    assert_eq!(
        catalog.resolve_schema_version("battery", None).as_deref(),
        Some("2.4.0")
    );
    // Existing passport → its stored version is authoritative, even if old.
    assert_eq!(
        catalog
            .resolve_schema_version("battery", Some("1.0.0"))
            .as_deref(),
        Some("1.0.0")
    );
    // Unknown sector, new passport → None.
    assert_eq!(catalog.resolve_schema_version("unknown", None), None);
}

#[test]
fn in_force_gating_is_status_driven() {
    let catalog = SectorCatalog::new();
    assert!(catalog.is_in_force("battery"));
    assert!(catalog.is_in_force("unsold-goods"));
    assert!(catalog.is_in_force("electronics"));
    assert!(!catalog.is_in_force("detergent")); // partial → flagged
    assert!(!catalog.is_in_force("nonexistent"));
}

#[test]
fn allows_determination_matches_status() {
    assert!(RegulatoryStatus::InForce.allows_determination());
    assert!(!RegulatoryStatus::Provisional.allows_determination());
}

#[test]
fn register_runtime_sector() {
    let mut catalog = SectorCatalog::new();
    let descriptor = SectorDescriptor {
        key: "plastics".into(),
        title: "Plastics".into(),
        status: RegulatoryStatus::Provisional,
        regime: Regime::Espr,
        legal_basis: vec!["ESPR Working Plan".into()],
        dpp_applies_from: None,
        retention_years: 10,
        schema_versions: vec!["1.0.0".into()],
        current_schema_version: "1.0.0".into(),
        product_categories: vec![],
        disclosure: std::collections::HashMap::new(),
        plugin: None,
        notes: None,
    };
    assert!(catalog.register(descriptor.clone()).is_ok());
    assert_eq!(catalog.len(), 12);
    assert!(matches!(
        catalog.register(descriptor),
        Err(CatalogError::AlreadyExists(_))
    ));
}

fn provisional_descriptor(current: &str, versions: Vec<String>) -> SectorDescriptor {
    SectorDescriptor {
        key: "plastics".into(),
        title: "Plastics".into(),
        status: RegulatoryStatus::Provisional,
        regime: Regime::Espr,
        legal_basis: vec!["ESPR Working Plan".into()],
        dpp_applies_from: None,
        retention_years: 10,
        schema_versions: versions,
        current_schema_version: current.into(),
        product_categories: vec![],
        disclosure: std::collections::HashMap::new(),
        plugin: None,
        notes: None,
    }
}

#[test]
fn register_rejects_invalid_current_schema_version() {
    let mut catalog = SectorCatalog::new();
    let descriptor = provisional_descriptor("not-semver", vec!["not-semver".into()]);
    assert!(matches!(
        catalog.register(descriptor),
        Err(CatalogError::InvalidSchemaVersion { .. })
    ));
    // A rejected descriptor must never reach the catalog — otherwise every
    // passport in that sector silently skips schema validation.
    assert_eq!(catalog.len(), 11);
}

#[test]
fn register_rejects_current_version_not_in_list() {
    let mut catalog = SectorCatalog::new();
    // Valid semver, but not one of the declared schema_versions.
    let descriptor = provisional_descriptor("2.0.0", vec!["1.0.0".into()]);
    assert!(matches!(
        catalog.register(descriptor),
        Err(CatalogError::CurrentVersionNotListed { .. })
    ));
    assert_eq!(catalog.len(), 11);
}

/// Parity guard: the closed [`Sector`](crate::domain::sector::Sector) enum
/// and the open [`SectorCatalog`] must describe the same set of
/// *compile-time* sectors. Runtime-registered sectors degrade to
/// `SectorData::Other`, but every typed `Sector` variant (except `Other`)
/// must have an embedded catalog entry, and the embedded catalog must not
/// carry a key with no corresponding variant. This stops the "four spellings
/// of a sector" drift from reappearing across the enum ↔ catalog boundary.
#[test]
fn sector_enum_and_catalog_agree() {
    use crate::domain::sector::Sector;

    let catalog = SectorCatalog::new();

    // Every typed Sector variant (except Other) must be in the catalog.
    let typed = [
        Sector::Battery,
        Sector::Textile,
        Sector::UnsoldGoods,
        Sector::Steel,
        Sector::Electronics,
        Sector::Construction,
        Sector::Tyre,
        Sector::Toy,
        Sector::Aluminium,
        Sector::Furniture,
        Sector::Detergent,
    ];
    for sector in &typed {
        let key = sector.catalog_key();
        assert!(
            catalog.get(key).is_some(),
            "Sector::{sector:?} (key '{key}') has no embedded catalog entry"
        );
    }

    // No catalog entry without a typed Sector variant.
    let typed_keys: std::collections::HashSet<&str> =
        typed.iter().map(Sector::catalog_key).collect();
    for key in catalog.keys() {
        assert!(
            typed_keys.contains(key),
            "catalog key '{key}' has no corresponding typed Sector variant"
        );
    }
}

/// Every catalog entry declares a retention period.
///
/// Retention used to have two homes — this field and a hardcoded match on the
/// `Sector` enum — kept in step by a drift-guard test. The enum method was what
/// production actually applied, while this field was documented as
/// authoritative. The enum method is gone and this is the only source, so what
/// needs guarding is no longer agreement between two values but that the one
/// remaining value is always present: a sector that reaches publish without a
/// retention period has no obligation the code can enforce.
#[test]
fn every_sector_declares_a_retention_period() {
    let catalog = SectorCatalog::new();
    for descriptor in catalog.all() {
        let key = descriptor.key.as_str();
        assert_eq!(
            catalog.retention_years(key),
            Some(descriptor.retention_years),
            "retention_years() disagrees with the descriptor for '{key}'"
        );
        assert!(
            descriptor.retention_years > 0,
            "sector '{key}' declares no retention period"
        );
    }

    // A sector with no catalog entry yields None, so callers must fail closed
    // rather than substitute a default for an unknown legal obligation.
    assert_eq!(catalog.retention_years("packaging"), None);
}

/// Compliance citation (domain Gap / watchlist 🔴): the ESPR unsold-goods
/// destruction ban is **Article 25 / Annex VII**, not Article 22. A wrong
/// citation in a compliance artifact erodes auditor trust.
/// Source: Regulation (EU) 2024/1781 (ESPR) Article 25, Annex VII.
#[test]
fn unsold_goods_cites_espr_article_25() {
    let catalog = SectorCatalog::new();
    let textile = catalog.get("unsold-goods").expect("unsold-goods present");
    let basis = textile.legal_basis.join(" ");
    assert!(
        basis.contains("Article 25"),
        "unsold-goods legal basis must cite ESPR Article 25, got: {basis}"
    );
    assert!(
        !basis.contains("Article 22"),
        "the incorrect Article 22 citation must be gone, got: {basis}"
    );
}

#[test]
fn descriptor_round_trips_camel_case() {
    let catalog = SectorCatalog::new();
    let battery = catalog.get("battery").unwrap();
    let json = serde_json::to_value(battery).unwrap();
    assert_eq!(json["dppAppliesFrom"], "2027-02-18");
    assert_eq!(json["status"], "in_force");
    let back: SectorDescriptor = serde_json::from_value(json).unwrap();
    assert_eq!(back.key, "battery");
}

// Drift guard: every key in a sector's disclosure manifest must correspond to
// a real JSON field in that sector's current schema. A key that doesn't match any
// schema property silently fails to gate any field — the redaction is a no-op.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn disclosure_keys_match_schema_properties() {
    use crate::schemas::VersionedSchemaRegistry;
    let catalog = SectorCatalog::new();
    let registry = VersionedSchemaRegistry::new();

    for descriptor in catalog.all() {
        if descriptor.disclosure.is_empty() {
            continue;
        }
        let version: semver::Version =
            descriptor
                .current_schema_version
                .parse()
                .unwrap_or_else(|_| {
                    panic!(
                        "sector '{}' currentSchemaVersion '{}' is not valid semver",
                        descriptor.key, descriptor.current_schema_version
                    )
                });
        let schema_json = registry.get(&descriptor.key, &version).unwrap_or_else(|| {
            panic!(
                "schema not found for sector '{}' v{}",
                descriptor.key, descriptor.current_schema_version
            )
        });
        let schema: serde_json::Value =
            serde_json::from_str(schema_json).expect("embedded schema must be valid JSON");
        let properties = schema
            .get("properties")
            .and_then(|p| p.as_object())
            .unwrap_or_else(|| {
                panic!(
                    "schema for sector '{}' has no top-level 'properties' object",
                    descriptor.key
                )
            });

        for key in descriptor.disclosure.keys() {
            assert!(
                properties.contains_key(key),
                "disclosure key '{}' in sector '{}' does not match any property in schema v{} \
                 (properties: {:?}). Either rename the key to match the serialised field name, \
                 or remove it — a mismatched key silently fails to gate the field.",
                key,
                descriptor.key,
                descriptor.current_schema_version,
                properties.keys().collect::<Vec<_>>()
            );
        }
    }
}

// The key enforcement: catalog ↔ schema registry must agree, so the
// "four spellings of a sector" problem cannot silently reappear.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn catalog_agrees_with_schema_registry() {
    use crate::schemas::VersionedSchemaRegistry;
    let catalog = SectorCatalog::new();
    let registry = VersionedSchemaRegistry::new();

    // Every schema version a sector declares must exist in the registry,
    // and its current version must be one of them.
    for d in catalog.all() {
        let reg_versions: Vec<String> = registry
            .versions_for(&d.key)
            .iter()
            .map(|v| v.to_string())
            .collect();
        for v in &d.schema_versions {
            assert!(
                reg_versions.contains(v),
                "catalog sector '{}' declares schema {v} not embedded in the registry (registry has {reg_versions:?})",
                d.key
            );
        }
        assert!(
            d.schema_versions.contains(&d.current_schema_version),
            "catalog sector '{}' currentSchemaVersion {} is not in its schemaVersions {:?}",
            d.key,
            d.current_schema_version,
            d.schema_versions
        );
    }

    // No orphan schemas: every registry sector must have a catalog entry.
    for sector in registry.sectors() {
        assert!(
            catalog.get(sector).is_some(),
            "schema registry has sector '{sector}' with no catalog entry"
        );
    }

    // Every in-force sector must declare a plugin binding.
    for d in catalog.in_force() {
        assert!(
            d.plugin.is_some(),
            "in-force sector '{}' must declare a plugin binding",
            d.key
        );
    }
}

// ── Regime axis ──────────────────────────────────────────────────────────────

#[test]
fn every_manifest_declares_a_regime() {
    for d in SectorCatalog::new().all().iter() {
        // `Regime::None` is documented as pairing with `RegulatoryStatus::Watch`
        // — a sector tracked before any DPP instrument exists. Forbidding it
        // outright contradicted the enum it was guarding, and would have blocked
        // the first Watch sector from ever being added.
        if d.status == RegulatoryStatus::Watch {
            continue;
        }
        assert_ne!(
            d.regime,
            Regime::None,
            "sector '{}' has status {:?} but no regime; Regime::None is reserved for              Watch sectors with no DPP instrument",
            d.key,
            d.status
        );
    }
}

#[test]
fn a_watch_sector_may_declare_no_regime() {
    // The pairing the guard above must allow. Asserted on a constructed
    // descriptor rather than a shipped manifest, so it holds whether or not any
    // sector is currently in Watch.
    let watch = r#"{
        "key": "w", "title": "W", "status": "watch", "regime": "none",
        "legalBasis": [], "retentionYears": 10,
        "schemaVersions": ["1.0.0"], "currentSchemaVersion": "1.0.0"
    }"#;
    let d: SectorDescriptor = serde_json::from_str(watch).expect("watch + none must parse");
    assert_eq!(d.regime, Regime::None);
    assert_eq!(d.status, RegulatoryStatus::Watch);
}

#[test]
fn manifest_without_regime_is_rejected() {
    // `regime` is required — a manifest omitting it must fail to deserialise
    // rather than silently defaulting to some instrument.
    let no_regime = r#"{
        "key": "x", "title": "X", "status": "provisional",
        "legalBasis": [], "retentionYears": 10,
        "schemaVersions": ["1.0.0"], "currentSchemaVersion": "1.0.0"
    }"#;
    assert!(serde_json::from_str::<SectorDescriptor>(no_regime).is_err());
}

#[test]
fn most_sectors_are_not_espr() {
    // Guards the assumption that ESPR is the only source of a DPP obligation.
    // Battery, toy, detergent, construction and electronics each derive from
    // their own instrument; if this ever collapses to all-ESPR, something has
    // been flattened wrongly.
    let catalog = SectorCatalog::new();
    let non_espr = catalog
        .all()
        .iter()
        .filter(|d| d.regime != Regime::Espr)
        .count();
    assert_eq!(
        non_espr, 5,
        "expected 5 non-ESPR sectors (battery, toy, detergent, construction, electronics)"
    );
}

#[test]
fn regime_does_not_affect_determination_gating() {
    // The two axes must be orthogonal: a Provisional sector gates identically
    // whatever instrument it derives from. If this fails, regime has leaked
    // into the determination path.
    let catalog = SectorCatalog::new();
    for d in catalog
        .all()
        .iter()
        .filter(|d| d.status == RegulatoryStatus::Provisional)
    {
        assert!(
            !d.status.allows_determination(),
            "provisional sector '{}' (regime {:?}) must not allow determinations",
            d.key,
            d.regime
        );
    }
}

// ── Watch status ─────────────────────────────────────────────────────────────

#[test]
fn watch_never_allows_determination() {
    assert!(!RegulatoryStatus::Watch.allows_determination());
}

#[test]
fn in_force_with_future_passport_date_still_determines() {
    // Regression guard. `dppAppliesFrom` is the passport-obligation date and is
    // NOT the determination gate. Battery's passport is required from
    // 2027-02-18, but its Art. 9 mercury/cadmium prohibitions have applied
    // since 2008 and are determinable today. Gating determinations on
    // `dppAppliesFrom` would suppress a legally valid non-compliance finding.
    let catalog = SectorCatalog::new();
    let battery = catalog.get("battery").expect("battery in catalog");
    assert_eq!(battery.status, RegulatoryStatus::InForce);
    assert_eq!(battery.dpp_applies_from.as_deref(), Some("2027-02-18"));
    assert!(battery.status.allows_determination());
}

#[test]
fn every_manifest_round_trips() {
    for d in SectorCatalog::new().all().iter() {
        let json = serde_json::to_string(d).expect("serialise");
        let back: SectorDescriptor = serde_json::from_str(&json).expect("deserialise");
        // SectorDescriptor is not PartialEq, and `disclosure` is a HashMap whose
        // serialised key order is not stable — compare as Value, which is
        // order-insensitive for maps.
        assert_eq!(
            serde_json::to_value(&back).expect("re-serialise"),
            serde_json::to_value(d).expect("serialise"),
            "round-trip changed sector '{}'",
            d.key
        );
    }
}

/// Sectors whose catalog `productCategories` mirror a schema enum, and the
/// property that enumerates them.
///
/// The correspondence is **not derivable** from the data — depending on sector
/// the categories live under `productCategory`, `productType`, `batteryType`,
/// `productFamily`, `productionRoute` or `tyreClass` — so it is declared here.
/// A sector absent from this table is simply not cross-checked; `textile`, for
/// example, declares categories but its schema has no enum for them.
const CATEGORY_ENUM_PROPERTY: &[(&str, &str)] = &[
    ("aluminium", "productionRoute"),
    ("battery", "batteryType"),
    ("construction", "productFamily"),
    ("detergent", "productType"),
    ("electronics", "productCategory"),
    ("furniture", "productType"),
    ("steel", "productCategory"),
    ("tyre", "tyreClass"),
    ("unsold-goods", "productCategory"),
];

/// Drift guard: a catalog product category that is not a legal value of the
/// corresponding schema enum is a value nothing can ever validate against.
///
/// This existed as two spellings of one concept — the catalog said `sli` and
/// `clothing_accessories` where the schemas said `starting-lighting-ignition`
/// and `accessories`. Neither was load-bearing, because
/// `SectorDescriptor::product_categories` has no reader in Rust today; both
/// would have become load-bearing the moment one appeared.
#[test]
fn product_categories_are_legal_values_of_their_schema_enum() {
    use crate::schemas::VersionedSchemaRegistry;

    let catalog = SectorCatalog::new();
    let registry = VersionedSchemaRegistry::new();

    for (sector_key, property) in CATEGORY_ENUM_PROPERTY {
        let descriptor = catalog
            .get(sector_key)
            .unwrap_or_else(|| panic!("sector '{sector_key}' is in the table but not the catalog"));
        let version: semver::Version = descriptor
            .current_schema_version
            .parse()
            .expect("currentSchemaVersion is valid semver");
        let schema_json = registry
            .get(sector_key, &version)
            .unwrap_or_else(|| panic!("no schema for '{sector_key}' v{version}"));
        let schema: serde_json::Value =
            serde_json::from_str(schema_json).expect("schema is valid JSON");

        let allowed: Vec<&str> = schema["properties"][property]["enum"]
            .as_array()
            .unwrap_or_else(|| {
                panic!("'{sector_key}' schema property '{property}' has no enum — stale table row")
            })
            .iter()
            .filter_map(serde_json::Value::as_str)
            .collect();

        for category in &descriptor.product_categories {
            assert!(
                allowed.contains(&category.as_str()),
                "sector '{sector_key}' lists product category '{category}', which is not a legal \
                 value of schema property '{property}' ({allowed:?})"
            );
        }
    }
}