dpp-domain 0.22.0

EU Digital Product Passport domain types, port traits, and per-field disclosure policy
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
//! Behaviour of the registration request builder and the granularity mapping.

use super::*;
use crate::{
    passport::{ManufacturerInfo, Passport},
    status::PassportStatus,
};
use chrono::Utc;

fn make_published_passport() -> Passport {
    Passport {
        product_name: "Test".into(),
        manufacturer: ManufacturerInfo {
            name: "ACME".into(),
            address: "Berlin".into(),
            country: None,
            did_web_url: None,
            registered_trade_name: None,
            electronic_address: None,
        },
        status: PassportStatus::Published,
        qr_code_url: Some("https://id.odal-node.io/01/09506000134352".into()),
        jws_signature: Some("eyJ0eXAiOiJKV1QifQ.payload.sig".into()),
        published_at: Some(Utc::now()),
        placed_on_market_date: None,
        schema_version: "1.1.0".into(),
        retention_locked: true,
        operator_identifier: Some("did:web:acme.example.com".into()),
        product_group_data: Some(crate::product_group::ProductGroupData::Textile(Box::new(
            crate::test_support::sample_textile_data(),
        ))),
        facility: Some(crate::passport::FacilitySnapshot {
            scheme: "national".into(),
            value: "FAC-DE-001".into(),
            name: "Acme Plant".into(),
            country: "DE".into(),
            address: None,
        }),
        ..crate::test_support::sample_passport()
    }
}

/// The operator identity a test registration is filed under.
fn acme() -> RegisteringOperator<'static> {
    RegisteringOperator {
        legal_name: "Acme GmbH",
        country: "DE",
        identifier_scheme: "did",
    }
}

#[test]
fn from_published_passport_maps_all_fields() {
    let passport = make_published_passport();
    let req = RegistrationRequest::from_published_passport(
        &passport,
        acme(),
        RegistrationGranularity::Item,
    )
    .expect("the fixture passport is complete");

    assert_eq!(req.passport_id, passport.id);
    assert_eq!(req.operator_identifier, "did:web:acme.example.com");
    assert_eq!(req.facility_identifier, "FAC-DE-001");
    // The full facility descriptor is carried, not just the bare identifier.
    assert_eq!(
        req.facility.as_ref().map(|f| f.name.as_str()),
        Some("Acme Plant")
    );
    assert_eq!(
        req.facility.as_ref().map(|f| f.country.as_str()),
        Some("DE")
    );
    assert_eq!(req.product_category, "textile");
    assert_eq!(
        req.data_carrier_uri,
        "https://id.odal-node.io/01/09506000134352"
    );
    assert_eq!(req.schema_version, "1.1.0");
    assert!(req.jws_signature.is_some());
    assert!(req.published_at.is_some());
    assert_eq!(req.country_code, "DE");
    // The operator's legal name comes from operator config, never from the
    // passport's manufacturer block.
    assert_eq!(req.operator_name, "Acme GmbH");
    assert_ne!(
        req.operator_name, passport.manufacturer.name,
        "operator and manufacturer are distinct legal persons"
    );
    assert_eq!(req.granularity, RegistrationGranularity::Item);
}

/// 🚨 An incomplete passport is refused, naming **every** field it lacks.
///
/// This test used to be called `from_published_passport_empty_optionals_produce_empty_strings`
/// and asserted the opposite: that a passport with no operator identifier, no
/// facility and no carrier URL produced a request with `""` in all three. It
/// carried no reason, and the behaviour it pinned was the defect — a request
/// that looks complete, refused downstream by an error naming the scheme it was
/// given rather than the absence it was not.
///
/// All three at once, not the first: nothing has been sent yet, so the caller is
/// fixing their own passport and a round-trip per missing field is a worse
/// answer than a list.
#[test]
fn an_incomplete_passport_is_refused_with_every_missing_field_named() {
    let mut passport = make_published_passport();
    passport.operator_identifier = None;
    passport.facility = None;
    passport.qr_code_url = None;

    let refused = RegistrationRequest::from_published_passport(
        &passport,
        RegisteringOperator {
            legal_name: "",
            country: "",
            identifier_scheme: "",
        },
        RegistrationGranularity::Item,
    )
    .expect_err("a passport carrying none of the three cannot be registered");

    let fields: Vec<&str> = refused.errors.iter().map(|e| e.field.as_str()).collect();
    assert_eq!(
        fields,
        ["/operatorIdentifier", "/facility", "/qrCodeUrl"],
        "every missing field must be reported, not the first"
    );
}

/// And one missing field is one error — the list is not all-or-nothing in the
/// other direction either.
#[test]
fn a_passport_missing_only_its_carrier_url_reports_only_that() {
    let mut passport = make_published_passport();
    passport.qr_code_url = None;

    let refused = RegistrationRequest::from_published_passport(
        &passport,
        acme(),
        RegistrationGranularity::Item,
    )
    .expect_err("the carrier URI is what a registration resolves to");

    assert_eq!(refused.errors.len(), 1);
    assert_eq!(refused.errors[0].field, "/qrCodeUrl");
}

#[test]
fn registry_status_serde_round_trip() {
    for (status, wire) in [
        (RegistryStatus::Registered, "REGISTERED"),
        (
            RegistryStatus::SuspendedByAuthority,
            "SUSPENDED_BY_AUTHORITY",
        ),
        (RegistryStatus::Deactivated, "DEACTIVATED"),
    ] {
        assert_eq!(serde_json::to_value(&status).unwrap(), wire);
        let back: RegistryStatus = serde_json::from_value(wire.into()).unwrap();
        assert_eq!(status, back);
    }
}

/// A record state nobody has named here reads as itself, not as a refusal.
///
/// `PENDING` and `REJECTED` are among them now: they were states of a
/// submission, which `SubmissionReport` carries.
#[test]
fn an_unnamed_record_state_is_kept() {
    for wire in ["VERIFICATION_LAPSED", "PENDING", "REJECTED"] {
        let status: RegistryStatus = serde_json::from_value(wire.into()).unwrap();
        assert_eq!(status, RegistryStatus::Unrecognised(wire.into()));
        assert_eq!(serde_json::to_value(&status).unwrap(), wire);
    }
}

/// Only a ruling ends polling, and an unrecognised state is not one.
#[test]
fn a_submission_report_is_terminal_only_once_ruled_on() {
    assert!(!SubmissionReport::Processing.is_terminal());
    assert!(
        !SubmissionReport::Unrecognised {
            state: "QUEUED".into()
        }
        .is_terminal()
    );
    assert!(
        SubmissionReport::Registered {
            registration_id: "URI-1".into()
        }
        .is_terminal()
    );
    assert!(
        SubmissionReport::Refused {
            reason: "The UPI URL is invalid.".into()
        }
        .is_terminal()
    );
}

/// Both handles survive a queue: a caller stores them between polls.
#[test]
fn the_acknowledgement_and_the_report_round_trip() {
    let accepted = SubmissionAcknowledgement::Accepted {
        correlation_id: "corr-1".into(),
    };
    let json = serde_json::to_value(&accepted).unwrap();
    assert_eq!(
        json,
        serde_json::json!({"kind": "accepted", "correlationId": "corr-1"})
    );
    assert_eq!(
        serde_json::from_value::<SubmissionAcknowledgement>(json).unwrap(),
        accepted
    );
    assert_eq!(
        serde_json::to_value(SubmissionAcknowledgement::AlreadyHeld).unwrap(),
        serde_json::json!({"kind": "alreadyHeld"})
    );

    let registered = SubmissionReport::Registered {
        registration_id: "URI-1".into(),
    };
    let json = serde_json::to_value(&registered).unwrap();
    assert_eq!(
        json,
        serde_json::json!({"outcome": "registered", "registrationId": "URI-1"})
    );
    assert_eq!(
        serde_json::from_value::<SubmissionReport>(json).unwrap(),
        registered
    );
}

/// Art. 8(4)/(5): the batch is linked at batch and item level, and the item's
/// serial — the one its label prints, never the passport's id — at item level.
#[test]
fn the_batch_and_the_item_serial_follow_the_registration_level() {
    let mut passport = make_published_passport();
    passport.batch_id = Some("LOT-2026-07".into());
    passport.carrier_serial = Some("SN0001".into());

    let at = |granularity| {
        RegistrationRequest::from_published_passport(&passport, acme(), granularity)
            .expect("the fixture passport is complete")
    };

    let item = at(RegistrationGranularity::Item);
    assert_eq!(item.batch_id.as_deref(), Some("LOT-2026-07"));
    assert_eq!(item.item_serial.as_deref(), Some("SN0001"));
    assert_ne!(item.item_serial, Some(passport.id.to_string()));

    let batch = at(RegistrationGranularity::Batch);
    assert_eq!(batch.batch_id.as_deref(), Some("LOT-2026-07"));
    assert_eq!(batch.item_serial, None);

    let model = at(RegistrationGranularity::Model);
    assert_eq!(model.batch_id, None, "a model covers every batch");
    assert_eq!(model.item_serial, None);
}

/// No attributed serial: the item's serial is the one derived for its label,
/// and a blank batch is no batch.
#[test]
fn an_unattributed_serial_is_the_derived_one_and_a_blank_batch_is_none() {
    let mut passport = make_published_passport();
    passport.batch_id = Some("  ".into());
    passport.carrier_serial = None;

    let request = RegistrationRequest::from_published_passport(
        &passport,
        acme(),
        RegistrationGranularity::Item,
    )
    .expect("the fixture passport is complete");
    assert_eq!(request.batch_id, None);
    assert_eq!(
        request.item_serial.as_deref(),
        Some(passport.effective_carrier_serial().as_ref())
    );
}

/// Art. 8(4): an item-level registration links the model identifier where a
/// model design exists. It exists for batteries, and the registration must
/// carry it rather than claiming the product has none.
#[test]
fn the_model_identifier_reaches_the_registration() {
    use crate::product_group::ProductGroupData;

    let mut passport = make_published_passport();
    passport.product_group_data = Some(ProductGroupData::Battery(Box::new(
        crate::product_group::BatteryData {
            battery_model_id: Some("BM-4815".into()),
            ..crate::test_support::sample_battery_data()
        },
    )));

    let req = RegistrationRequest::from_published_passport(
        &passport,
        acme(),
        RegistrationGranularity::Item,
    )
    .expect("the fixture passport is complete");
    assert_eq!(req.model_id.as_deref(), Some("BM-4815"));
}

/// Absent is a substantive answer — the lawful "no model design exists" —
/// and must not be confused with a lookup that was never wired.
#[test]
fn a_product_group_without_a_model_identifier_reports_none() {
    // Textile: it identifies a product, and carries no model design. The case
    // used to be built by clearing `product_group_data` entirely, which now
    // refuses — a passport with no product group identifies nothing, which is a
    // different statement from "this product has no model".
    let passport = make_published_passport();
    assert!(
        RegistrationRequest::from_published_passport(
            &passport,
            acme(),
            RegistrationGranularity::Item,
        )
        .expect("the fixture passport is complete")
        .model_id
        .is_none()
    );
}

/// 🚨 The identifier reaches the port, whichever clause 5 scheme issued it.
///
/// Before this field the request carried nothing identifying the product, so an
/// adapter scraped a GTIN out of the carrier URI and fell back to the internal
/// passport UUID when there was none — which is every scheme 2 and 3 passport.
/// That registers a product with a public authority under a value meaningless
/// outside this node, and no structural check catches it.
#[test]
fn every_clause_5_scheme_reaches_the_request() {
    use crate::identifier::ProductIdentifier;
    use crate::product_group::ProductGroupData;

    for identifier in [
        ProductIdentifier::gs1(crate::identifier::Gtin::parse("09506000134352").unwrap()),
        ProductIdentifier::identification_link("https://id.acme.example.com/p/1").unwrap(),
        ProductIdentifier::did("did:web:acme.example.com:p:1").unwrap(),
    ] {
        let mut passport = make_published_passport();
        let mut textile = crate::test_support::sample_textile_data();
        textile.product_identifier = identifier.clone();
        passport.product_group_data = Some(ProductGroupData::Textile(Box::new(textile)));

        let req = RegistrationRequest::from_published_passport(
            &passport,
            acme(),
            RegistrationGranularity::Item,
        )
        .expect("a passport that identifies itself can be registered");

        assert_eq!(
            req.product_identifier.as_ref(),
            Some(&identifier),
            "the identifier must travel, not be re-derived from the carrier"
        );
    }
}

/// A product group that identifies no single product cannot be registered.
///
/// `UnsoldGoods` is the known case and is not a defect: an Art. 24–25 discard
/// disclosure covers a financial year across many products. Refused here rather
/// than allowed through with nothing in the field, so the case is named instead
/// of arriving at an adapter that has to invent something.
#[test]
fn a_product_group_that_identifies_nothing_is_refused() {
    use crate::product_group::ProductGroupData;

    let mut passport = make_published_passport();
    passport.product_group_data = Some(ProductGroupData::UnsoldGoods(
        crate::test_support::sample_unsold_goods_report(),
    ));

    let refused = RegistrationRequest::from_published_passport(
        &passport,
        acme(),
        RegistrationGranularity::Item,
    )
    .expect_err("a discard disclosure is not a product registration");

    assert_eq!(refused.errors.len(), 1);
    assert_eq!(
        refused.errors[0].field,
        "/productGroupData/productIdentifier"
    );
}

/// A passport for a product group this build has no typed variant for, with
/// `product_identifier` as its payload's `productIdentifier`.
fn untyped_passport(product_identifier: serde_json::Value) -> Passport {
    use crate::product_group::{ProductGroup, ProductGroupData};

    let mut passport = make_published_passport();
    passport.product_group = ProductGroup::Other("photovoltaic".into());
    passport.product_group_data = ProductGroupData::other(serde_json::json!({
        "productGroup": "photovoltaic",
        "productIdentifier": product_identifier,
    }));
    passport
}

/// The defect: an untyped product group carrying a valid identifier on the
/// wire was refused, because nothing read one out of untyped data — so a group
/// added to the catalog after this crate shipped needed a release to register.
#[test]
fn an_untyped_product_group_registers_on_the_identifier_it_carries() {
    let passport = untyped_passport(serde_json::json!({
        "scheme": "gs1",
        "gtin": "09506000134352",
    }));

    let req = RegistrationRequest::from_published_passport(
        &passport,
        acme(),
        RegistrationGranularity::Item,
    )
    .expect("a valid identifier registers whether or not the group is typed");

    let identifier = req.product_identifier.expect("carried");
    assert_eq!(identifier.as_str(), "09506000134352");
}

/// Reading the untyped payload does not make it lenient: an identifier that
/// fails EN 18219 clause 5 is refused exactly as an absent one is.
#[test]
fn an_untyped_product_group_with_a_malformed_identifier_is_refused() {
    let passport = untyped_passport(serde_json::json!({
        "scheme": "gs1",
        "gtin": "09506000134351",
    }));

    let refused = RegistrationRequest::from_published_passport(
        &passport,
        acme(),
        RegistrationGranularity::Item,
    )
    .expect_err("a bad check digit is no identifier");
    assert_eq!(
        refused.errors[0].field,
        "/productGroupData/productIdentifier"
    );
}

/// 🚨 `Some("")` is the same absence wearing an `Option::Some`.
///
/// `Passport`'s fields are public and it deserialises from stored documents, so
/// nothing stops a blank value being written where `None` belongs. Checking
/// presence alone would have left this constructor doing exactly what it was
/// changed to stop doing — producing a request that looks complete and carries
/// nothing — one layer in from where the defect was found.
///
/// Whitespace counts as blank: a value of `" "` identifies no more than `""`
/// does, and is the form a trimmed-input bug actually produces.
#[test]
fn a_present_but_blank_field_is_as_absent_as_a_missing_one() {
    let mut passport = make_published_passport();
    passport.operator_identifier = Some(String::new());
    passport.qr_code_url = Some("   ".into());
    if let Some(facility) = passport.facility.as_mut() {
        facility.value = String::new();
    }

    let refused = RegistrationRequest::from_published_passport(
        &passport,
        acme(),
        RegistrationGranularity::Item,
    )
    .expect_err("blank is not a value the passport carried");

    let fields: Vec<&str> = refused.errors.iter().map(|e| e.field.as_str()).collect();
    assert_eq!(fields, ["/operatorIdentifier", "/facility", "/qrCodeUrl"]);
}