mtcs 0.3.1

Offline verification of Merkle Tree Certificates (draft-ietf-plants-merkle-tree-certs)
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
//! End-to-end verification against the PLANTS WG demo corpus
//! (ietf-plants-wg/merkle-tree-certs, demo/mtc.json, "plants-07").
//! The demo's own `verify` subcommand agrees with the expectations below.

use mtcs::{
    CaTrust, CosignerGroup, CosignerInfo, Error, SignatureAlgorithm, TrustAnchorId, TrustStore,
    TrustedSubtree, VerificationKind, verify_certificate, verify_certificate_ignoring_validity,
};

mod keys;

const STANDALONE: &[u8] = include_bytes!("fixtures/standalone.der");
const STANDALONE_CA_ONLY: &[u8] = include_bytes!("fixtures/standalone_ca_only.der");
const UNUSED_BIT_BAD: &[u8] = include_bytes!("fixtures/unused_bit_bad.der");
const BITFLIP_BAD: &[u8] = include_bytes!("fixtures/bitflip_bad.der");
const LANDMARK_32: &[u8] = include_bytes!("fixtures/landmark_32.der");
const LANDMARK_2121: &[u8] = include_bytes!("fixtures/landmark_2121.der");
const CA: &[u8] = include_bytes!("fixtures/ca.der");

const NOT_BEFORE: i64 = 1577836800; // 2020-01-01T00:00:00Z
const NOT_AFTER: i64 = 1924991999; // 2030-12-31T23:59:59Z
const NOW: i64 = 1735689600; // 2025-01-01T00:00:00Z

fn id(dotted: &str) -> TrustAnchorId {
    TrustAnchorId::from_dotted(dotted).unwrap()
}

fn cosigner(dotted: &str, algorithm: SignatureAlgorithm, spki_hex: &str) -> CosignerInfo {
    CosignerInfo {
        id: id(dotted),
        algorithm,
        spki_der: hex::decode(spki_hex).unwrap(),
    }
}

fn store() -> TrustStore {
    let mut store = TrustStore::new();
    store.add_ca(CaTrust::from_ca_certificate(CA).unwrap());
    store
}

fn hash(hex_str: &str) -> [u8; 32] {
    hex::decode(hex_str).unwrap().try_into().unwrap()
}

#[test]
fn standalone_certificate_verifies_with_ca_cosignature_only() {
    let store = store();
    let verification = verify_certificate(&store, STANDALONE, NOW).unwrap();
    assert_eq!(verification.kind, VerificationKind::Standalone);
    assert_eq!(verification.ca_id, id("32473.1"));
    assert_eq!((verification.log_number, verification.entry_index), (1, 10));
    assert!(verification.satisfied_cosigners.contains(&id("32473.1")));
    // The certificate also carries 32473.2.1 (P-256) and 32473.2.2 (ML-DSA-65),
    // which are unrecognized by this trust store and therefore ignored.
    assert_eq!(verification.satisfied_cosigners.len(), 1);

    let verification = verify_certificate(&store, STANDALONE_CA_ONLY, NOW).unwrap();
    assert_eq!(verification.kind, VerificationKind::Standalone);
    assert_eq!(verification.satisfied_cosigners, [id("32473.1")]);
}

#[test]
fn additional_required_cosigners_are_enforced() {
    let mut ca = CaTrust::from_ca_certificate(CA).unwrap();
    ca.require_cosigner(cosigner(
        "32473.2.1",
        SignatureAlgorithm::EcdsaP256Sha256,
        keys::C_32473_2_1,
    ))
    .unwrap();
    ca.require_cosigner(cosigner(
        "32473.2.2",
        SignatureAlgorithm::MlDsa65,
        keys::C_32473_2_2,
    ))
    .unwrap();
    let mut with_extras = TrustStore::new();
    with_extras.add_ca(ca);

    // cert_10_0 carries CA + 32473.2.1 + 32473.2.2: satisfied.
    let verification = verify_certificate(&with_extras, STANDALONE, NOW).unwrap();
    assert_eq!(verification.satisfied_cosigners.len(), 3);
    // cert_10_3 carries only the CA cosignature: the two extra requirements fail.
    assert!(matches!(
        verify_certificate(&with_extras, STANDALONE_CA_ONLY, NOW),
        Err(Error::PolicyUnsatisfied { .. })
    ));

    // A global requirement applies across CAs.
    let mut strict = store();
    strict.required_for_all.push(CosignerGroup::single(cosigner(
        "32473.2.1",
        SignatureAlgorithm::EcdsaP256Sha256,
        keys::C_32473_2_1,
    )));
    assert!(verify_certificate(&strict, STANDALONE, NOW).is_ok());
    assert!(matches!(
        verify_certificate(&strict, STANDALONE_CA_ONLY, NOW),
        Err(Error::PolicyUnsatisfied { .. })
    ));
}

#[test]
fn tampered_and_misencoded_certificates_fail() {
    let store = store();
    // A flipped bit in the inclusion proof changes the subtree hash, so the
    // CA cosignature no longer verifies.
    assert_eq!(
        verify_certificate(&store, BITFLIP_BAD, NOW),
        Err(Error::InvalidCosignature(id("32473.1")))
    );
    // A signature BIT STRING with a nonzero unused-bit count is not an MTCProof.
    assert!(matches!(
        verify_certificate(&store, UNUSED_BIT_BAD, NOW),
        Err(Error::Malformed(_))
    ));
}

#[test]
fn revocation_validity_and_ca_membership_are_checked() {
    let store = store();
    // Revoke entry 10's exact serial (log 1, index 10).
    let mut revoked = store.clone();
    revoked.cas[0].revoke_range(1 << 48 | 10, 1 << 48 | 10);
    assert_eq!(
        verify_certificate(&revoked, STANDALONE, NOW),
        Err(Error::Revoked)
    );
    // The CA certificate's own bounds revoke everything above log 5.
    let mut cert = STANDALONE.to_vec();
    // Bump the serial's log number byte (0x07 01 00... -> log 6).
    let pos = cert.windows(2).position(|w| w == [0x02, 0x07]).unwrap();
    assert_eq!(cert[pos + 2], 1);
    cert[pos + 2] = 6;
    assert_eq!(verify_certificate(&store, &cert, NOW), Err(Error::Revoked));
    // Validity is evaluated against the caller's timestamp.
    assert_eq!(
        verify_certificate(&store, STANDALONE, NOT_BEFORE - 1),
        Err(Error::TimeInvalid)
    );
    assert_eq!(
        verify_certificate(&store, STANDALONE, NOT_AFTER + 1),
        Err(Error::TimeInvalid)
    );
    assert!(verify_certificate_ignoring_validity(&store, STANDALONE).is_ok());
    assert_eq!(
        verify_certificate(&TrustStore::new(), STANDALONE, NOW),
        Err(Error::UnknownCa)
    );
}

#[test]
fn non_mtc_certificates_are_rejected() {
    // An ordinary directly-signed ECDSA certificate.
    let der = pem_der(include_bytes!("fixtures/plain.pem"));
    assert_eq!(verify_certificate(&store(), &der, NOW), Err(Error::NotMtc));
}

fn pem_der(pem: &[u8]) -> Vec<u8> {
    let text = core::str::from_utf8(pem).unwrap();
    let start = text.find("-----BEGIN CERTIFICATE-----").unwrap() + 27;
    let end = text.find("-----END CERTIFICATE-----").unwrap();
    let body: String = text[start..end]
        .chars()
        .filter(|c| !c.is_whitespace())
        .collect();
    use base64::Engine;
    base64::engine::general_purpose::STANDARD
        .decode(body)
        .unwrap()
}

#[test]
fn landmark_relative_certificates_verify_against_trusted_subtrees() {
    let mut ca = CaTrust::from_ca_certificate(CA).unwrap();
    ca.trust_subtree(TrustedSubtree {
        log_number: 1,
        start: 32,
        end: 34,
        hash: hash(keys::SUBTREE_32_34),
    });
    ca.trust_subtree(TrustedSubtree {
        log_number: 1,
        start: 2048,
        end: 2122,
        hash: hash(keys::SUBTREE_2048_2122),
    });
    let mut with_subtrees = TrustStore::new();
    with_subtrees.add_ca(ca);

    let verification = verify_certificate(&with_subtrees, LANDMARK_32, NOW).unwrap();
    assert_eq!(verification.kind, VerificationKind::LandmarkRelative);
    assert_eq!((verification.log_number, verification.entry_index), (1, 32));
    assert!(verification.satisfied_cosigners.is_empty());

    let verification = verify_certificate(&with_subtrees, LANDMARK_2121, NOW).unwrap();
    assert_eq!(verification.kind, VerificationKind::LandmarkRelative);
    assert_eq!(
        (verification.log_number, verification.entry_index),
        (1, 2121)
    );

    // A wrong trusted subtree hash fails verification outright (no fallback).
    let mut wrong = with_subtrees.clone();
    wrong.cas[0].trusted_subtrees[0].hash[0] ^= 1;
    assert_eq!(
        verify_certificate(&wrong, LANDMARK_32, NOW),
        Err(Error::ProofEvaluation)
    );
    // Without the trusted subtree, a signatureless certificate cannot verify.
    assert!(matches!(
        verify_certificate(&store(), LANDMARK_32, NOW),
        Err(Error::PolicyUnsatisfied { .. })
    ));
}

#[test]
fn ca_certificate_parses_into_trust_configuration() {
    let ca = CaTrust::from_ca_certificate(CA).unwrap();
    assert_eq!(ca.ca_id, id("32473.1"));
    assert_eq!(ca.ca_cosigner.algorithm, SignatureAlgorithm::MlDsa44);
    assert_eq!(ca.ca_cosigner.id, ca.ca_id);
    assert_eq!(
        ca.ca_cosigner.spki_der,
        hex::decode(keys::C_32473_1).unwrap()
    );
    // Bounds from the demo config: [0, 2^48) and ((5<<48)|(2^48-1), u64::MAX].
    assert_eq!(ca.revoked_ranges.len(), 2);
    assert_eq!(ca.revoked_ranges[0], 0..=(1 << 48) - 1);
    assert_eq!(
        ca.revoked_ranges[1],
        ((5 << 48) | 0xffff_ffff_ffff) + 1..=u64::MAX
    );
}

#[test]
fn cosigner_groups_support_k_of_n_quorums() {
    // The standalone fixture carries CA + 32473.2.1 (P-256) + 32473.2.2 (ML-DSA-65).
    let p256 = cosigner(
        "32473.2.1",
        SignatureAlgorithm::EcdsaP256Sha256,
        keys::C_32473_2_1,
    );
    let mldsa65 = cosigner("32473.2.2", SignatureAlgorithm::MlDsa65, keys::C_32473_2_2);
    let absent = cosigner("32473.2.3", SignatureAlgorithm::MlDsa87, keys::C_32473_2_3);

    // 1-of-2 over the two witnesses passes.
    let mut ca = CaTrust::from_ca_certificate(CA).unwrap();
    ca.require_group(CosignerGroup::new(vec![p256.clone(), mldsa65.clone()], 1).unwrap())
        .unwrap();
    // 2-of-2 over the two witnesses passes (both cosignatures are present).
    ca.require_group(CosignerGroup::new(vec![p256.clone(), mldsa65.clone()], 2).unwrap())
        .unwrap();
    let mut store = TrustStore::new();
    store.add_ca(ca);
    let verification = verify_certificate(&store, STANDALONE, NOW).unwrap();
    assert_eq!(verification.satisfied_cosigners.len(), 3);

    // 2-of-2 against the CA-only certificate fails, naming the absent members.
    let Err(Error::PolicyUnsatisfied { missing, invalid }) =
        verify_certificate(&store, STANDALONE_CA_ONLY, NOW)
    else {
        panic!("expected PolicyUnsatisfied")
    };
    assert!(missing.contains(&id("32473.2.1")) && missing.contains(&id("32473.2.2")));
    assert!(invalid.is_empty());

    // A group whose members are all absent from the certificate fails.
    let mut ca = CaTrust::from_ca_certificate(CA).unwrap();
    ca.require_group(CosignerGroup::new(vec![absent.clone()], 1).unwrap())
        .unwrap();
    let mut store = TrustStore::new();
    store.add_ca(ca);
    let Err(Error::PolicyUnsatisfied { missing, .. }) = verify_certificate(&store, STANDALONE, NOW)
    else {
        panic!("expected PolicyUnsatisfied")
    };
    assert_eq!(missing, [id("32473.2.3")]);
}

#[test]
fn cosigner_groups_validate_their_threshold() {
    let member = cosigner(
        "32473.2.1",
        SignatureAlgorithm::EcdsaP256Sha256,
        keys::C_32473_2_1,
    );
    assert!(matches!(
        CosignerGroup::new(vec![member.clone()], 0),
        Err(Error::Configuration(_))
    ));
    assert!(matches!(
        CosignerGroup::new(vec![member.clone()], 2),
        Err(Error::Configuration(_))
    ));
    assert!(matches!(
        CosignerGroup::new(vec![], 1),
        Err(Error::Configuration(_))
    ));
    assert!(CosignerGroup::new(vec![member], 1).is_ok());
}

#[test]
fn trust_store_and_cosignature_failures_are_distinguished() {
    // A malformed SPKI is a trust-store misconfiguration, not a bad certificate.
    let mut ca = CaTrust::from_ca_certificate(CA).unwrap();
    ca.require_cosigner(CosignerInfo {
        id: id("32473.2.1"),
        algorithm: SignatureAlgorithm::EcdsaP256Sha256,
        spki_der: vec![0x30, 0x03, 0x06, 0x01, 0x00], // truncated SPKI
    })
    .unwrap();
    let mut store = TrustStore::new();
    store.add_ca(ca);
    assert!(matches!(
        verify_certificate(&store, STANDALONE, NOW),
        Err(Error::UnsupportedKey(_))
    ));

    // A present-but-invalid cosignature lands in `invalid`, not `missing`.
    let mut wrong_spki = hex::decode(keys::C_32473_2_2).unwrap();
    let last = wrong_spki.len() - 1;
    wrong_spki[last] ^= 1; // Same length, wrong ML-DSA-65 key material.
    let mut ca = CaTrust::from_ca_certificate(CA).unwrap();
    ca.require_cosigner(CosignerInfo {
        id: id("32473.2.2"),
        algorithm: SignatureAlgorithm::MlDsa65,
        spki_der: wrong_spki,
    })
    .unwrap();
    let mut store = TrustStore::new();
    store.add_ca(ca);
    let Err(Error::PolicyUnsatisfied { missing, invalid }) =
        verify_certificate(&store, STANDALONE, NOW)
    else {
        panic!("expected PolicyUnsatisfied")
    };
    assert_eq!(invalid, [id("32473.2.2")]);
    assert!(!missing.contains(&id("32473.2.2")));
}

#[test]
fn cosigner_lookup_resolves_per_ca_groups_before_global_groups() {
    // An ID present in both a per-CA group and a global group resolves through
    // the per-CA group first (verify.rs consults ca.cosigner(), which searches
    // required_groups in insertion order, and only then required_for_all), so
    // the per-CA key decides. fuzz_policy's oracle relies on this order.
    let clean = cosigner(
        "32473.2.1",
        SignatureAlgorithm::EcdsaP256Sha256,
        keys::C_32473_2_1,
    );
    let mut corrupted = clean.clone();
    let last = corrupted.spki_der.len() - 1;
    corrupted.spki_der[last] ^= 1; // Same length, wrong key material.

    // Per-CA clean, global corrupted: the clean per-CA key wins.
    let mut ca = CaTrust::from_ca_certificate(CA).unwrap();
    ca.require_group(CosignerGroup::single(clean.clone()))
        .unwrap();
    let mut store = TrustStore::new();
    store.add_ca(ca);
    store.require_group_for_all(CosignerGroup::single(corrupted.clone()));
    let verification = verify_certificate(&store, STANDALONE, NOW).unwrap();
    assert!(verification.satisfied_cosigners.contains(&id("32473.2.1")));

    // Per-CA corrupted, global clean: the corrupted per-CA key still wins, so
    // the cosignature lands in `invalid`.
    let mut ca = CaTrust::from_ca_certificate(CA).unwrap();
    ca.require_group(CosignerGroup::single(corrupted.clone()))
        .unwrap();
    let mut store = TrustStore::new();
    store.add_ca(ca);
    store.require_group_for_all(CosignerGroup::single(clean));
    let Err(Error::PolicyUnsatisfied { invalid, .. }) = verify_certificate(&store, STANDALONE, NOW)
    else {
        panic!("expected PolicyUnsatisfied")
    };
    assert_eq!(invalid, [id("32473.2.1")]);

    // Within per-CA groups, insertion order decides: first group wins.
    let mut ca = CaTrust::from_ca_certificate(CA).unwrap();
    ca.require_group(CosignerGroup::single(corrupted)).unwrap();
    ca.require_group(CosignerGroup::single(cosigner(
        "32473.2.1",
        SignatureAlgorithm::EcdsaP256Sha256,
        keys::C_32473_2_1,
    )))
    .unwrap();
    let mut store = TrustStore::new();
    store.add_ca(ca);
    let Err(Error::PolicyUnsatisfied { invalid, .. }) = verify_certificate(&store, STANDALONE, NOW)
    else {
        panic!("expected PolicyUnsatisfied")
    };
    assert_eq!(invalid, [id("32473.2.1")]);
}

#[test]
fn verification_exposes_the_subtree_and_its_hash() {
    let mut ca = CaTrust::from_ca_certificate(CA).unwrap();
    ca.trust_subtree(TrustedSubtree {
        log_number: 1,
        start: 32,
        end: 34,
        hash: hash(keys::SUBTREE_32_34),
    });
    let mut store = TrustStore::new();
    store.add_ca(ca);
    let verification = verify_certificate(&store, LANDMARK_32, NOW).unwrap();
    assert_eq!(verification.subtree, mtcs::Subtree { start: 32, end: 34 });
    assert_eq!(verification.subtree_hash, hash(keys::SUBTREE_32_34));
}

#[test]
fn ca_certificate_profile_is_enforced() {
    // Section 5.5: critical MTC CA extension, cA = TRUE, keyCertSign asserted.
    let mut not_critical = CA.to_vec();
    let needle = hex::decode("06082b0601050507012601 01ff".replace(' ', "")).unwrap();
    let pos = not_critical
        .windows(needle.len())
        .position(|w| w == needle.as_slice())
        .unwrap();
    let last = pos + needle.len() - 1;
    not_critical[last] = 0x00; // critical: FALSE
    assert!(CaTrust::from_ca_certificate(&not_critical).is_err());

    let mut not_ca = CA.to_vec();
    let needle = hex::decode("0603551d13").unwrap();
    let pos = not_ca
        .windows(needle.len())
        .position(|w| w == needle.as_slice())
        .unwrap();
    // The cA BOOLEAN is the last 01 01 ff within this extension.
    let window_end = pos + 20;
    let inner = not_ca[pos..window_end]
        .windows(3)
        .rposition(|w| w == [0x01, 0x01, 0xff])
        .unwrap();
    not_ca[pos + inner + 2] = 0x00; // cA = FALSE
    assert!(CaTrust::from_ca_certificate(&not_ca).is_err());

    let mut no_cert_sign = CA.to_vec();
    let needle = hex::decode("0603551d0f").unwrap();
    let pos = no_cert_sign
        .windows(needle.len())
        .position(|w| w == needle.as_slice())
        .unwrap();
    let window_end = pos + 20;
    let inner = no_cert_sign[pos..window_end]
        .windows(4)
        .position(|w| w == [0x03, 0x02, 0x02, 0x04])
        .unwrap();
    no_cert_sign[pos + inner + 3] = 0x40; // nonRepudiation instead of keyCertSign
    assert!(CaTrust::from_ca_certificate(&no_cert_sign).is_err());
}

#[test]
fn ca_cosigner_cannot_join_transparency_groups() {
    // Section 7.3 separates authenticity (CA cosigner) from transparency
    // (additional cosigners): the CA cosigner is rejected from groups.
    let ca_key = CosignerInfo {
        id: id("32473.1"),
        algorithm: SignatureAlgorithm::MlDsa44,
        spki_der: hex::decode(keys::C_32473_1).unwrap(),
    };
    let mut ca = CaTrust::from_ca_certificate(CA).unwrap();
    assert!(ca.require_cosigner(ca_key.clone()).is_err());
    assert!(
        ca.require_group(CosignerGroup::new(vec![ca_key.clone()], 1).unwrap())
            .is_err()
    );

    // Evaluation enforces it too: the CA signature never counts toward a
    // threshold, so a group {CA, 32473.2.1} at threshold 2 is short even on a
    // certificate carrying both signatures. (Built bypassing CaTrust to pin
    // the evaluation rule; the constructor rejects it as shown above.)
    let mut ca = CaTrust::from_ca_certificate(CA).unwrap();
    ca.required_groups.push(
        CosignerGroup::new(
            vec![
                ca_key.clone(),
                cosigner(
                    "32473.2.1",
                    SignatureAlgorithm::EcdsaP256Sha256,
                    keys::C_32473_2_1,
                ),
            ],
            2,
        )
        .unwrap(),
    );
    let mut store = TrustStore::new();
    store.add_ca(ca);
    assert!(matches!(
        verify_certificate(&store, STANDALONE, NOW),
        Err(Error::PolicyUnsatisfied { .. })
    ));
}

#[test]
fn missing_lists_candidates_not_all_required_cosigners() {
    // A 2-of-3 group with one valid signature reports the two unsatisfied
    // members as candidates; either would have sufficed (see the rustdoc on
    // Error::PolicyUnsatisfied).
    let mldsa65 = cosigner("32473.2.2", SignatureAlgorithm::MlDsa65, keys::C_32473_2_2);
    let absent1 = cosigner("32473.2.3", SignatureAlgorithm::MlDsa87, keys::C_32473_2_3);
    let absent2 = cosigner("32473.3.1", SignatureAlgorithm::MlDsa44, keys::C_32473_3_1);
    let mut ca = CaTrust::from_ca_certificate(CA).unwrap();
    ca.require_group(
        CosignerGroup::new(vec![mldsa65, absent1.clone(), absent2.clone()], 2).unwrap(),
    )
    .unwrap();
    let mut store = TrustStore::new();
    store.add_ca(ca);
    // standalone.der carries 32473.2.2, so the group has one of two needed.
    let Err(Error::PolicyUnsatisfied { missing, .. }) = verify_certificate(&store, STANDALONE, NOW)
    else {
        panic!("expected PolicyUnsatisfied")
    };
    assert_eq!(missing, [id("32473.2.3"), id("32473.3.1")]);
}

#[test]
fn truncated_and_tampered_certificates_never_panic() {
    // Verifiers face untrusted input: no parse path may panic. Every prefix of
    // every fixture must return an error (a certificate prefix is never valid),
    // and byte flips must produce an error or a verdict, never a panic.
    let store = store();
    let fixtures: [&[u8]; 7] = [
        STANDALONE,
        STANDALONE_CA_ONLY,
        UNUSED_BIT_BAD,
        BITFLIP_BAD,
        LANDMARK_32,
        LANDMARK_2121,
        CA,
    ];
    for fixture in fixtures {
        for end in 0..fixture.len() {
            assert!(
                verify_certificate(&store, &fixture[..end], NOW).is_err(),
                "prefix of {end} bytes unexpectedly verified"
            );
        }
        // Strided bit flips (the full sweep costs too much ML-DSA verification
        // time to no extra benefit).
        for position in (0..fixture.len()).step_by(17) {
            let mut tampered = fixture.to_vec();
            tampered[position] ^= 1;
            let _ = verify_certificate(&store, &tampered, NOW);
        }
    }
}

#[test]
fn trust_store_routes_between_multiple_cas() {
    // A second, unrelated CA in the store does not disturb the first.
    let fabricated = TrustAnchorId::from_dotted("32473.99").unwrap();
    let mut other = CaTrust::new(
        fabricated.clone(),
        CosignerInfo {
            id: fabricated,
            algorithm: SignatureAlgorithm::MlDsa44,
            spki_der: hex::decode(keys::C_32473_1).unwrap(),
        },
    );
    other.revoke_range(0, u64::MAX); // Everything revoked: it must not matter.
    let mut multi = store();
    multi.add_ca(other);
    assert!(verify_certificate(&multi, STANDALONE, NOW).is_ok());

    // The convenience wrapper behaves like pushing to required_for_all.
    let mut strict = store();
    strict.require_group_for_all(CosignerGroup::single(cosigner(
        "32473.2.1",
        SignatureAlgorithm::EcdsaP256Sha256,
        keys::C_32473_2_1,
    )));
    assert!(verify_certificate(&strict, STANDALONE, NOW).is_ok());
    assert!(matches!(
        verify_certificate(&strict, STANDALONE_CA_ONLY, NOW),
        Err(Error::PolicyUnsatisfied { .. })
    ));
}