matter-commissioning 0.1.0

Matter commissioning state machine: setup payload, attestation, NOC issuance, network commissioning.
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
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
//! Certification Declaration verifier implementation.
//!
//! The verifier performs five checks in order:
//!
//! 1. CMS `SignedData` DER parse via the `cms` crate.
//! 2. Structural validation: a single `SignerInfo`, attached
//!    encapsulated content.
//! 3. ECDSA-P256 / SHA-256 signature verification against each
//!    trusted root's public key; accept on first match.
//! 4. Decode the inner CD TLV via `parse_inner_cd_tlv` (M6.4.3 T30
//!    fills the helper).
//! 5. Cross-check declared VID + PID against the expected pair
//!    supplied by the caller (typically sourced from the verified DAC
//!    subject).
//!
//! The trust store ([`CdSigningRoots`]) holds SEC1-uncompressed P-256
//! public keys for each trusted CSA signing root. Production callers
//! build the store via [`CdSigningRoots::from_pem`]; tests and
//! examples use the bundled CSA-test root via
//! [`CdSigningRoots::with_csa_test_roots`].

#![forbid(unsafe_code)]

use crate::attestation::{AttestationError, ProductId, VendorId};

/// Bundled PEM-encoded `SubjectPublicKeyInfo` for the synthetic
/// CSA-test CD signing root generated by `xtask capture-cd`. The
/// matching private key lives in `test-vectors/commissioning/cd/` and
/// signs the fixture CDs the verifier tests consume.
const CSA_TEST_CD_SIGNING_ROOT_PEM: &[u8] =
    include_bytes!("./csa_cd_signing_roots/csa-test-cd-signing-root.pem");

/// Trusted CSA Certification Declaration signing roots.
///
/// Built from production roots via [`Self::from_cert_der`] (X.509 CD
/// signing certificates, as published by the CSA DCL) or
/// [`Self::from_pem`] (bare `SubjectPublicKeyInfo` PEMs), or seeded with
/// the bundled synthetic CSA-test root via
/// [`Self::with_csa_test_roots`].
///
/// Internally stores each trusted root as a SEC1-uncompressed P-256
/// public key (65 bytes: `0x04 || X || Y`) so signature verification
/// can call `ring::signature::UnparsedPublicKey` directly without
/// re-parsing.
#[derive(Debug, Clone)]
pub struct CdSigningRoots {
    /// SEC1-uncompressed P-256 public keys (65 bytes each) for each
    /// trusted root.
    public_keys: Vec<Vec<u8>>,
}

impl CdSigningRoots {
    /// Build a trust store seeded with the bundled synthetic CSA-test
    /// CD signing root.
    ///
    /// **Tests and examples only — do not use in production.** Real
    /// commissioners supply CSA-published roots via
    /// [`Self::from_pem`].
    ///
    /// The bundled PEM is a compile-time constant, so parsing it should
    /// never fail at runtime; if it ever does (e.g. someone replaces
    /// the file with garbage), the store is returned empty rather than
    /// panicking, and the verifier will reject every signature with
    /// [`AttestationError::CertificationDeclarationSignatureInvalid`].
    #[must_use]
    pub fn with_csa_test_roots() -> Self {
        let pk = parse_pem_public_key(CSA_TEST_CD_SIGNING_ROOT_PEM).ok();
        Self {
            public_keys: pk.into_iter().collect(),
        }
    }

    /// Build a trust store from PEM-encoded P-256
    /// `SubjectPublicKeyInfo` blobs (one per trusted CSA signing
    /// root).
    ///
    /// # Errors
    ///
    /// Returns [`AttestationError::CertificationDeclarationMalformed`]
    /// if any input fails to parse. An empty slice returns an empty
    /// trust store.
    pub fn from_pem(pems: &[&[u8]]) -> Result<Self, AttestationError> {
        let mut public_keys = Vec::with_capacity(pems.len());
        for raw in pems {
            let pk = parse_pem_public_key(raw)?;
            public_keys.push(pk);
        }
        Ok(Self { public_keys })
    }

    /// Build a trust store from X.509 **certificate** DER blobs (one per
    /// trusted CSA CD signing root), extracting each certificate's P-256
    /// subject public key.
    ///
    /// This is the ingestion path for real-world CD signing roots: the CSA
    /// Distributed Compliance Ledger — and the `connectedhomeip`
    /// `credentials/production/cd-certs/` mirror of it — publish the roots as
    /// X.509 certificates, not as the bare `SubjectPublicKeyInfo` PEMs that
    /// [`Self::from_pem`] consumes. There are several distinct CSA CD signing
    /// keys, so a real commissioner typically loads the whole directory.
    ///
    /// The certificate is treated purely as a trust anchor: only its subject
    /// public key is extracted. No signature, validity-window, or chain checks
    /// are performed — the operator vouches for the roots by supplying them
    /// (exactly as [`Self::from_pem`] trusts the keys it is given).
    ///
    /// # Errors
    ///
    /// Returns [`AttestationError::CertificationDeclarationMalformed`] if any
    /// input fails to parse as an X.509 certificate, or does not carry a
    /// 65-byte SEC1-uncompressed P-256 public key.
    pub fn from_cert_der(certs: &[&[u8]]) -> Result<Self, AttestationError> {
        use x509_parser::prelude::{FromDer, X509Certificate};

        let mut public_keys = Vec::with_capacity(certs.len());
        for der in certs {
            let (_, cert) = X509Certificate::from_der(der)
                .map_err(|_| AttestationError::CertificationDeclarationMalformed)?;
            let pk = cert.public_key().subject_public_key.data.as_ref().to_vec();
            // CD signatures are ECDSA-P256; the trust root must carry a
            // SEC1-uncompressed P-256 point (`0x04` || X || Y, 65 bytes).
            if pk.len() != 65 || pk[0] != 0x04 {
                return Err(AttestationError::CertificationDeclarationMalformed);
            }
            public_keys.push(pk);
        }
        Ok(Self { public_keys })
    }

    /// Number of trusted roots in the store.
    #[must_use]
    pub fn len(&self) -> usize {
        self.public_keys.len()
    }

    /// Returns `true` if no trusted roots have been loaded.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.public_keys.is_empty()
    }

    /// Internal accessor — borrow the raw 65-byte SEC1 uncompressed
    /// public-key bytes for each trusted root, for the verifier's
    /// signature-check loop.
    fn keys(&self) -> &[Vec<u8>] {
        &self.public_keys
    }
}

/// Verify a Certification Declaration extracted from
/// `attestation_elements` (Matter Core Spec §6.3.1) against a trust
/// store and an expected VID / PID pair.
///
/// Performs five checks in order:
///
/// 1. CMS `SignedData` DER parse via the `cms` crate.
/// 2. Structural validation: a single `SignerInfo`, attached
///    encapsulated content.
/// 3. ECDSA-P256 / SHA-256 signature verification against each
///    trusted root in `trust`; accept on first match.
/// 4. Decode the inner CD TLV.
/// 5. Cross-check declared VID + PID against `expected_vid` /
///    `expected_pid` (sourced from the verified DAC chain by the
///    caller). Per Matter Core Spec §6.2.3, when the CD carries both
///    `dac_origin_vendor_id` (tag 9) and `dac_origin_product_id`
///    (tag 10), those override fields are compared instead of the CD's
///    own `vendor_id` / `product_id_array`.
///
/// # Errors
///
/// - [`AttestationError::CertificationDeclarationMalformed`] — the
///   CMS DER failed to parse or did not match the expected shape.
/// - [`AttestationError::CertificationDeclarationSignatureInvalid`] —
///   no trusted root accepts the signature.
/// - [`AttestationError::CertificationDeclarationTlvMalformed`] —
///   inner CD TLV missing required fields or malformed.
/// - [`AttestationError::CertificationDeclarationVidMismatch`] —
///   declared VID does not equal `expected_vid`.
/// - [`AttestationError::CertificationDeclarationPidMismatch`] —
///   declared PID list does not contain `expected_pid`.
#[allow(
    clippy::similar_names,
    reason = "the `expected_vid`/`expected_pid` pair mirrors the public-API \
     vocabulary used elsewhere in this crate (VendorId/ProductId); \
     renaming would obscure intent at the call site."
)]
pub fn verify_certification_declaration(
    cd_bytes: &[u8],
    expected_vid: VendorId,
    expected_pid: ProductId,
    trust: &CdSigningRoots,
) -> Result<(), AttestationError> {
    use cms::content_info::ContentInfo;
    use cms::signed_data::SignedData;
    use der::asn1::OctetString;
    use der::{Decode, DecodeValue, Encode, Header, SliceReader, Tag as DerTag};

    // 1. Parse the outer ContentInfo.
    let content_info = ContentInfo::from_der(cd_bytes)
        .map_err(|_| AttestationError::CertificationDeclarationMalformed)?;
    // ContentInfo.content is an Any wrapping SignedData; re-encode and
    // decode to convert.
    let signed_data_der = content_info
        .content
        .to_der()
        .map_err(|_| AttestationError::CertificationDeclarationMalformed)?;
    let signed_data = SignedData::from_der(&signed_data_der)
        .map_err(|_| AttestationError::CertificationDeclarationMalformed)?;

    // 2. Validate shape: exactly one SignerInfo and attached content.
    if signed_data.signer_infos.0.len() != 1 {
        return Err(AttestationError::CertificationDeclarationMalformed);
    }
    let signer = signed_data
        .signer_infos
        .0
        .iter()
        .next()
        .ok_or(AttestationError::CertificationDeclarationMalformed)?;

    // 3. Extract the signed content (the inner CD TLV bytes).
    //
    // `EncapsulatedContentInfo.econtent` is typed `Option<Any>` where
    // the Any wraps an OCTET STRING. We decode the OCTET STRING from
    // the Any's body and copy its bytes — this is the eContent value
    // (the inner CD TLV) the signer signed.
    let econtent = signed_data
        .encap_content_info
        .econtent
        .as_ref()
        .ok_or(AttestationError::CertificationDeclarationMalformed)?;
    // `Any` does not expose its raw value bytes directly; re-encode it
    // then peel off the OCTET STRING tag+length to read the inner
    // bytes via `OctetString::decode_value`.
    let econtent_der = econtent
        .to_der()
        .map_err(|_| AttestationError::CertificationDeclarationMalformed)?;
    let mut reader = SliceReader::new(&econtent_der)
        .map_err(|_| AttestationError::CertificationDeclarationMalformed)?;
    let header = Header::decode(&mut reader)
        .map_err(|_| AttestationError::CertificationDeclarationMalformed)?;
    if header.tag != DerTag::OctetString {
        return Err(AttestationError::CertificationDeclarationMalformed);
    }
    let octet_string = OctetString::decode_value(&mut reader, header)
        .map_err(|_| AttestationError::CertificationDeclarationMalformed)?;
    let content_bytes = octet_string.as_bytes().to_vec();

    // 4. Extract the signature bytes.
    let sig = signer.signature.as_bytes();

    // 5. Verify ECDSA-P256 / SHA-256 against each trusted root.
    let mut accepted = false;
    for key in trust.keys() {
        if verify_ecdsa_p256_sha256(key, &content_bytes, sig).is_ok() {
            accepted = true;
            break;
        }
    }
    if !accepted {
        return Err(AttestationError::CertificationDeclarationSignatureInvalid);
    }

    // 6. Decode the inner CD TLV and cross-check VID / PID.
    //
    // Matter Core Spec §6.2.3: when the CD carries the optional
    // `dac_origin_vendor_id` (tag 9) AND `dac_origin_product_id`
    // (tag 10), the commissioner MUST validate the DAC/PAI subject
    // VID/PID against THOSE origin fields, not the CD's own
    // `vendor_id` / `product_id_array`. This supports CDs issued for a
    // PAA/PAI scoped to a different vendor than the device's own VID
    // (e.g. white-label / contract-manufactured products).
    //
    // Decision on partial presence: the spec treats `dac_origin_*` as a
    // both-or-neither pair. We trigger the override only when BOTH are
    // present; if exactly one is present we ignore the override and fall
    // back to the standard fields (the safe, conservative reading — a
    // half-specified override is not a valid §6.2.3 override).
    let parsed = parse_inner_cd_tlv(&content_bytes)?;
    if let (Some(origin_vid), Some(origin_pid)) =
        (parsed.dac_origin_vendor_id, parsed.dac_origin_product_id)
    {
        // Override path: bind the DAC against the dac_origin_* fields.
        if origin_vid != expected_vid {
            return Err(AttestationError::CertificationDeclarationVidMismatch {
                declared: origin_vid,
                expected: expected_vid,
            });
        }
        if origin_pid != expected_pid {
            return Err(AttestationError::CertificationDeclarationPidMismatch(
                expected_pid,
            ));
        }
    } else {
        // Standard path: bind against vendor_id / product_id_array.
        if parsed.vendor_id != expected_vid {
            return Err(AttestationError::CertificationDeclarationVidMismatch {
                declared: parsed.vendor_id,
                expected: expected_vid,
            });
        }
        if !parsed.product_ids.contains(&expected_pid) {
            return Err(AttestationError::CertificationDeclarationPidMismatch(
                expected_pid,
            ));
        }
    }

    Ok(())
}

/// Decoded view of the inner Certification Declaration TLV — the
/// subset the verifier cross-checks today. T30 fleshes out the parser.
#[derive(Debug)]
struct ParsedCd {
    /// Vendor ID (Matter Core Spec §6.3.1 tag 1).
    vendor_id: VendorId,
    /// Product ID list (tag 2 — at least one element required).
    product_ids: Vec<ProductId>,
    /// `dac_origin_vendor_id` (Matter Core Spec §6.3.1 tag 9, optional).
    ///
    /// When present (together with [`Self::dac_origin_product_id`]), the
    /// commissioner MUST validate the DAC/PAI subject VID against THIS
    /// value rather than [`Self::vendor_id`] (Matter Core Spec §6.2.3).
    dac_origin_vendor_id: Option<VendorId>,
    /// `dac_origin_product_id` (Matter Core Spec §6.3.1 tag 10, optional).
    ///
    /// The PID counterpart to [`Self::dac_origin_vendor_id`]; see its docs.
    dac_origin_product_id: Option<ProductId>,
}

/// Decode the inner CD TLV per Matter Core Spec §6.3.1: an anonymous
/// outer structure with context-tagged fields including tag 1
/// (`vendor_id`, u16), tag 2 (`product_id_array`, array of u16), and the
/// optional override fields tag 9 (`dac_origin_vendor_id`, u16) and tag
/// 10 (`dac_origin_product_id`, u16).
///
/// All other context-tagged fields (`format_version`, `device_type_id`,
/// `certificate_id`, `security_level`, `security_information`,
/// `version_number`, `certification_type`, `authorized_paa_list`) and
/// any future-extension fields are forward-compat ignored — the verifier
/// only needs VID + PID (and the optional `dac_origin_*` overrides) for
/// cross-checking against the DAC subject.
fn parse_inner_cd_tlv(tlv: &[u8]) -> Result<ParsedCd, AttestationError> {
    use matter_codec::{ContainerKind, Element, Tag, TlvReader, Value};

    let mut reader = TlvReader::new(tlv);
    match reader
        .next()
        .map_err(|_| AttestationError::CertificationDeclarationTlvMalformed)?
    {
        Some(Element::ContainerStart {
            tag: Tag::Anonymous,
            kind: ContainerKind::Structure,
        }) => {}
        _ => return Err(AttestationError::CertificationDeclarationTlvMalformed),
    }

    let mut vid: Option<VendorId> = None;
    let mut pids: Vec<ProductId> = Vec::new();
    let mut origin_vendor: Option<VendorId> = None;
    let mut origin_product: Option<ProductId> = None;

    loop {
        match reader
            .next()
            .map_err(|_| AttestationError::CertificationDeclarationTlvMalformed)?
        {
            None => return Err(AttestationError::CertificationDeclarationTlvMalformed),
            Some(Element::ContainerEnd) => break,
            Some(Element::Scalar {
                tag: Tag::Context(1),
                value: Value::Uint(v),
            }) => {
                if vid.is_some() {
                    return Err(AttestationError::CertificationDeclarationTlvMalformed);
                }
                let v16 = u16::try_from(v)
                    .map_err(|_| AttestationError::CertificationDeclarationTlvMalformed)?;
                vid = Some(VendorId::new(v16));
            }
            Some(Element::ContainerStart {
                tag: Tag::Context(2),
                kind: ContainerKind::Array,
            }) => {
                if !pids.is_empty() {
                    return Err(AttestationError::CertificationDeclarationTlvMalformed);
                }
                loop {
                    match reader
                        .next()
                        .map_err(|_| AttestationError::CertificationDeclarationTlvMalformed)?
                    {
                        None => return Err(AttestationError::CertificationDeclarationTlvMalformed),
                        Some(Element::ContainerEnd) => break,
                        Some(Element::Scalar {
                            tag: Tag::Anonymous,
                            value: Value::Uint(p),
                        }) => {
                            let p16 = u16::try_from(p).map_err(|_| {
                                AttestationError::CertificationDeclarationTlvMalformed
                            })?;
                            pids.push(ProductId::new(p16));
                        }
                        // Inside the array, unknown shapes are a structural error
                        // (the spec says product IDs are u16). But be lenient on
                        // tagged-not-anonymous in case future M6.x extensions land.
                        Some(_) => {}
                    }
                }
            }
            // dac_origin_vendor_id (tag 9) — optional override; see §6.2.3.
            Some(Element::Scalar {
                tag: Tag::Context(9),
                value: Value::Uint(v),
            }) => {
                if origin_vendor.is_some() {
                    return Err(AttestationError::CertificationDeclarationTlvMalformed);
                }
                let v16 = u16::try_from(v)
                    .map_err(|_| AttestationError::CertificationDeclarationTlvMalformed)?;
                origin_vendor = Some(VendorId::new(v16));
            }
            // dac_origin_product_id (tag 10) — optional override; see §6.2.3.
            Some(Element::Scalar {
                tag: Tag::Context(10),
                value: Value::Uint(p),
            }) => {
                if origin_product.is_some() {
                    return Err(AttestationError::CertificationDeclarationTlvMalformed);
                }
                let p16 = u16::try_from(p)
                    .map_err(|_| AttestationError::CertificationDeclarationTlvMalformed)?;
                origin_product = Some(ProductId::new(p16));
            }
            // Forward-compat: ignore other context-tagged scalars / containers.
            Some(_) => {}
        }
    }

    let vendor_id = vid.ok_or(AttestationError::CertificationDeclarationTlvMalformed)?;
    if pids.is_empty() {
        // product_id_array required to be non-empty per spec §6.3.1.
        return Err(AttestationError::CertificationDeclarationTlvMalformed);
    }
    Ok(ParsedCd {
        vendor_id,
        product_ids: pids,
        dac_origin_vendor_id: origin_vendor,
        dac_origin_product_id: origin_product,
    })
}

/// Parse a PEM-encoded `SubjectPublicKeyInfo` for a P-256 public key
/// and return the SEC1 uncompressed point (65 bytes:
/// `0x04 || X || Y`) suitable for `ring`'s
/// `UnparsedPublicKey<ECDSA_P256_SHA256_FIXED>`.
///
/// Strips the `-----BEGIN PUBLIC KEY-----` / `-----END PUBLIC KEY-----`
/// armor, base64-decodes the body, and slices the trailing 65 bytes of
/// the DER (the SEC1 uncompressed point inside the SPKI's `BIT
/// STRING`). The point's `0x04` marker byte is checked here; ring's
/// `UnparsedPublicKey` rejects any malformed point at signature-verify
/// time as a second line of defense.
fn parse_pem_public_key(pem: &[u8]) -> Result<Vec<u8>, AttestationError> {
    use base64::Engine;

    const HEADER: &str = "-----BEGIN PUBLIC KEY-----";
    const FOOTER: &str = "-----END PUBLIC KEY-----";

    let pem_str = std::str::from_utf8(pem)
        .map_err(|_| AttestationError::CertificationDeclarationMalformed)?;

    let header_start = pem_str
        .find(HEADER)
        .ok_or(AttestationError::CertificationDeclarationMalformed)?;
    let body_start = header_start + HEADER.len();
    let footer_start = pem_str
        .find(FOOTER)
        .ok_or(AttestationError::CertificationDeclarationMalformed)?;
    if footer_start <= body_start {
        return Err(AttestationError::CertificationDeclarationMalformed);
    }

    // Strip all whitespace from the base64 body.
    let body: String = pem_str[body_start..footer_start]
        .chars()
        .filter(|c| !c.is_whitespace())
        .collect();

    let der = base64::engine::general_purpose::STANDARD
        .decode(body.as_bytes())
        .map_err(|_| AttestationError::CertificationDeclarationMalformed)?;

    // Extract the SEC1 uncompressed point from the SubjectPublicKeyInfo.
    // The structure for a P-256 SPKI is exactly 91 bytes:
    //   30 59                        SEQUENCE (89)
    //   30 13                          SEQUENCE (19)
    //     06 07 2A 86 48 CE 3D 02 01   OID ecPublicKey
    //     06 08 2A 86 48 CE 3D 03 01 07 OID prime256v1
    //   03 42 00                       BIT STRING (66 bytes, 0 unused bits)
    //   04 XX...XX                     SEC1 uncompressed point (65 bytes)
    //                                  starting with 0x04
    //
    // The SEC1 point is the last 65 bytes. We validate the marker byte
    // and let `ring::UnparsedPublicKey::new` reject malformed bytes
    // later if the prefix is corrupt.
    if der.len() < 65 {
        return Err(AttestationError::CertificationDeclarationMalformed);
    }
    let point = &der[der.len() - 65..];
    if point[0] != 0x04 {
        return Err(AttestationError::CertificationDeclarationMalformed);
    }
    Ok(point.to_vec())
}

/// Verify an ECDSA-P256 / SHA-256 signature against a SEC1-uncompressed
/// P-256 public key.
///
/// CMS `SignerInfo.signature` carries ECDSA signatures as a DER
/// `ECDSA-Sig-Value` (SEQUENCE of r, s) — confirmed against a real
/// CSA-signed CD (Tapo P110M, M6.6.5 validation), and matching chip's
/// `CMS_Sign`. A raw fixed-form (r||s, exactly 64 bytes) signature is
/// also accepted for compatibility with the historical local test
/// fixtures generated by `xtask capture-cd`.
///
/// Maps any verification failure to
/// [`AttestationError::CertificationDeclarationSignatureInvalid`] —
/// the caller (the per-root loop in
/// [`verify_certification_declaration`]) only cares whether *some*
/// trusted root accepted the signature, not which one rejected it.
fn verify_ecdsa_p256_sha256(
    public_key: &[u8],
    msg: &[u8],
    sig: &[u8],
) -> Result<(), AttestationError> {
    use ring::signature::{UnparsedPublicKey, ECDSA_P256_SHA256_ASN1, ECDSA_P256_SHA256_FIXED};
    let asn1 = UnparsedPublicKey::new(&ECDSA_P256_SHA256_ASN1, public_key);
    if asn1.verify(msg, sig).is_ok() {
        return Ok(());
    }
    if sig.len() == 64 {
        let fixed = UnparsedPublicKey::new(&ECDSA_P256_SHA256_FIXED, public_key);
        if fixed.verify(msg, sig).is_ok() {
            return Ok(());
        }
    }
    Err(AttestationError::CertificationDeclarationSignatureInvalid)
}

#[cfg(test)]
mod tests {
    // The CD test helpers pair `dac_origin_vid`/`dac_origin_pid` and
    // `origin_vid`/`origin_pid` (and VendorId/ProductId locals) by design —
    // the near-identical names mirror the spec field pairs. Same carve-out
    // as `tests/support/mod.rs`.
    #![allow(clippy::similar_names)]

    use super::*;

    #[test]
    #[allow(clippy::unwrap_used, clippy::expect_used)] // Test-code carve-out: see CLAUDE.md.
    fn verify_accepts_der_encoded_ecdsa_signature() {
        // CMS `SignerInfo.signature` carries ECDSA signatures as a DER
        // `ECDSA-Sig-Value` (SEQUENCE of r, s) — confirmed on a real
        // CSA-signed CD (Tapo P110M, M6.6.5 validation: 70-byte `0x30 44 …`).
        // chip's `CMS_Sign` emits the same (`ConvertECDSASignatureRawToDER`).
        use ring::rand::SystemRandom;
        use ring::signature::{EcdsaKeyPair, KeyPair, ECDSA_P256_SHA256_ASN1_SIGNING};

        let rng = SystemRandom::new();
        let pkcs8 = EcdsaKeyPair::generate_pkcs8(&ECDSA_P256_SHA256_ASN1_SIGNING, &rng).unwrap();
        let kp = EcdsaKeyPair::from_pkcs8(&ECDSA_P256_SHA256_ASN1_SIGNING, pkcs8.as_ref(), &rng)
            .unwrap();
        let msg = b"certification declaration content";
        let sig = kp.sign(&rng, msg).unwrap(); // DER-encoded ECDSA-Sig-Value
        let pk = kp.public_key().as_ref();

        verify_ecdsa_p256_sha256(pk, msg, sig.as_ref())
            .expect("DER-encoded CMS signature must verify");
    }

    #[test]
    fn with_csa_test_roots_loads_bundled_root() {
        let trust = CdSigningRoots::with_csa_test_roots();
        assert_eq!(trust.len(), 1);
        assert!(!trust.is_empty());
    }

    #[test]
    #[allow(clippy::expect_used)] // Test-code carve-out: see CLAUDE.md.
    fn parse_pem_public_key_extracts_65_byte_sec1_point() {
        const PEM: &[u8] = include_bytes!("./csa_cd_signing_roots/csa-test-cd-signing-root.pem");
        let key = parse_pem_public_key(PEM).expect("happy path parses");
        assert_eq!(key.len(), 65, "SEC1 uncompressed P-256 point");
        assert_eq!(key[0], 0x04, "uncompressed-point marker byte");
    }

    #[test]
    #[allow(clippy::expect_used)] // Test-code carve-out: see CLAUDE.md.
    fn parse_pem_public_key_rejects_garbage() {
        let err = parse_pem_public_key(b"not a PEM").expect_err("garbage rejected");
        assert!(matches!(
            err,
            AttestationError::CertificationDeclarationMalformed
        ));
    }

    #[test]
    #[allow(clippy::unwrap_used)] // Test-code carve-out: see CLAUDE.md.
    fn from_pem_empty_input_yields_empty_trust_store() {
        let trust = CdSigningRoots::from_pem(&[]).unwrap();
        assert!(trust.is_empty());
        assert_eq!(trust.len(), 0);
    }

    #[test]
    #[allow(clippy::unwrap_used, clippy::expect_used)] // Test-code carve-out: see CLAUDE.md.
    fn from_cert_der_extracts_p256_pubkey_from_x509_cert() {
        // Real-world CD signing roots (CSA DCL / connectedhomeip
        // `credentials/production/cd-certs/`) are X.509 certificates, not bare
        // SubjectPublicKeyInfo PEMs. `from_cert_der` must extract the cert's
        // P-256 subject public key. We synthesise a self-signed P-256 cert with
        // a known key and assert the extracted SEC1 point matches it byte-for-byte.
        use matter_cert::test_support::{build_x509_der, TestCertFields};
        use matter_cert::{
            DistinguishedName, DnAttribute, Extensions, MatterTime, PublicKey, Signature,
        };
        use ring::rand::SystemRandom;
        use ring::signature::{EcdsaKeyPair, KeyPair, ECDSA_P256_SHA256_ASN1_SIGNING};

        let rng = SystemRandom::new();
        let pkcs8 = EcdsaKeyPair::generate_pkcs8(&ECDSA_P256_SHA256_ASN1_SIGNING, &rng).unwrap();
        let kp = EcdsaKeyPair::from_pkcs8(&ECDSA_P256_SHA256_ASN1_SIGNING, pkcs8.as_ref(), &rng)
            .unwrap();
        let expected = kp.public_key().as_ref().to_vec(); // 65-byte SEC1 uncompressed
        let pk = PublicKey::from_slice(&expected).unwrap();

        let dn = DistinguishedName::new(vec![DnAttribute::CommonName(
            "Test CD Signing Key (synthetic)".into(),
        )]);
        let der = build_x509_der(
            TestCertFields {
                serial: vec![0x01],
                issuer: dn.clone(),
                not_before: MatterTime::from_unix_secs(1_700_000_000),
                not_after: MatterTime::NO_EXPIRY,
                subject: dn,
                public_key: pk,
                extensions: Extensions::default(),
                signature: Signature::new([0u8; 64]),
            },
            pkcs8.as_ref(), // self-signed
        )
        .expect("synthetic CD signing cert builds");

        let trust = CdSigningRoots::from_cert_der(&[&der]).expect("cert parses");
        assert_eq!(trust.len(), 1);
        assert_eq!(
            trust.public_keys[0], expected,
            "extracted SEC1 public key must match the cert's subject key"
        );
    }

    #[test]
    #[allow(clippy::expect_used)] // Test-code carve-out: see CLAUDE.md.
    fn from_cert_der_rejects_non_certificate_bytes() {
        let err = CdSigningRoots::from_cert_der(&[b"not a certificate"])
            .expect_err("garbage DER rejected");
        assert!(matches!(
            err,
            AttestationError::CertificationDeclarationMalformed
        ));
    }

    #[test]
    fn parse_inner_cd_tlv_extracts_vendor_id_and_pid_list() {
        // Test-code carve-out: see CLAUDE.md.
        #![allow(clippy::unwrap_used, clippy::expect_used)]
        use matter_codec::{Tag, TlvWriter};
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.start_structure(Tag::Anonymous).unwrap();
        w.put_uint(Tag::Context(0), 1).unwrap(); // format_version
        w.put_uint(Tag::Context(1), 0xFFF1).unwrap(); // vendor_id
        w.start_array(Tag::Context(2)).unwrap();
        w.put_uint(Tag::Anonymous, 0x8001).unwrap();
        w.put_uint(Tag::Anonymous, 0x8002).unwrap();
        w.end_container().unwrap(); // close array
        w.end_container().unwrap(); // close struct

        let parsed = parse_inner_cd_tlv(&buf).expect("happy path decodes");
        assert_eq!(parsed.vendor_id, VendorId::new(0xFFF1));
        assert_eq!(
            parsed.product_ids,
            vec![ProductId::new(0x8001), ProductId::new(0x8002)]
        );
    }

    #[test]
    fn parse_inner_cd_tlv_ignores_forward_compat_fields() {
        // Test-code carve-out: see CLAUDE.md.
        #![allow(clippy::unwrap_used, clippy::expect_used)]
        use matter_codec::{Tag, TlvWriter};
        // Hand-roll a CD with tag 0 (format_version), tag 1 (vid), tag 2 (pids),
        // tag 3 (device_type_id), tag 4 (certificate_id utf8), tag 5..8 (security_*,
        // version_number, certification_type), AND a fake tag 99 (future field).
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.start_structure(Tag::Anonymous).unwrap();
        w.put_uint(Tag::Context(0), 1).unwrap();
        w.put_uint(Tag::Context(1), 0xFFF1).unwrap();
        w.start_array(Tag::Context(2)).unwrap();
        w.put_uint(Tag::Anonymous, 0x8001).unwrap();
        w.end_container().unwrap();
        w.put_uint(Tag::Context(3), 0x0100).unwrap();
        w.put_utf8(Tag::Context(4), "CSA-ID").unwrap();
        w.put_uint(Tag::Context(5), 0).unwrap();
        w.put_uint(Tag::Context(6), 0).unwrap();
        w.put_uint(Tag::Context(7), 1).unwrap();
        w.put_uint(Tag::Context(8), 0).unwrap();
        w.put_uint(Tag::Context(99), 0xDEAD).unwrap(); // unknown future field
        w.end_container().unwrap();

        let parsed = parse_inner_cd_tlv(&buf).expect("forward-compat decode");
        assert_eq!(parsed.vendor_id, VendorId::new(0xFFF1));
        assert_eq!(parsed.product_ids, vec![ProductId::new(0x8001)]);
    }

    #[test]
    fn parse_inner_cd_tlv_rejects_missing_vid() {
        // Test-code carve-out: see CLAUDE.md.
        #![allow(clippy::unwrap_used, clippy::expect_used)]
        use matter_codec::{Tag, TlvWriter};
        let mut buf = Vec::new();
        let mut w = TlvWriter::new(&mut buf);
        w.start_structure(Tag::Anonymous).unwrap();
        // No tag 1 (vendor_id).
        w.start_array(Tag::Context(2)).unwrap();
        w.put_uint(Tag::Anonymous, 0x8001).unwrap();
        w.end_container().unwrap();
        w.end_container().unwrap();

        let err = parse_inner_cd_tlv(&buf).expect_err("missing vid rejected");
        assert!(matches!(
            err,
            AttestationError::CertificationDeclarationTlvMalformed
        ));
    }

    #[test]
    fn parse_inner_cd_tlv_rejects_garbage() {
        // Test-code carve-out: see CLAUDE.md.
        #![allow(clippy::unwrap_used, clippy::expect_used)]
        let err = parse_inner_cd_tlv(&[0xFF]).expect_err("garbage rejected");
        assert!(matches!(
            err,
            AttestationError::CertificationDeclarationTlvMalformed
        ));
    }

    #[test]
    fn parse_inner_cd_tlv_captures_dac_origin_fields() {
        // Test-code carve-out: see CLAUDE.md.
        #![allow(clippy::unwrap_used, clippy::expect_used)]
        let tlv = build_inner_cd_tlv(0xFFF1, 0x8001, Some(0x1234), Some(0x5678), &[0x8001]);
        let parsed = parse_inner_cd_tlv(&tlv).expect("decodes with dac_origin");
        assert_eq!(parsed.vendor_id, VendorId::new(0xFFF1));
        assert_eq!(parsed.product_ids, vec![ProductId::new(0x8001)]);
        assert_eq!(parsed.dac_origin_vendor_id, Some(VendorId::new(0x1234)));
        assert_eq!(parsed.dac_origin_product_id, Some(ProductId::new(0x5678)));
    }

    // ── Fix B — CD dac_origin override binding (Matter §6.2.3) ──────────────
    //
    // These tests sign a synthetic CD with the bundled CSA-test signing key
    // (which `CdSigningRoots::with_csa_test_roots()` trusts) and run it
    // through the public `verify_certification_declaration`, exercising the
    // dac_origin override path end-to-end:
    //
    //   - CD with dac_origin set + DAC matching the ORIGIN VID/PID (but NOT
    //     the CD's own vendor_id) → accepted.
    //   - CD with dac_origin set + DAC matching neither → rejected.
    //   - CD WITHOUT dac_origin → unchanged: compares vendor_id /
    //     product_id_array.

    /// PKCS#8 private key for the bundled CSA-test CD signing root. The
    /// matching public key is bundled in
    /// `csa_cd_signing_roots/csa-test-cd-signing-root.pem` and trusted by
    /// `CdSigningRoots::with_csa_test_roots()`.
    const CSA_TEST_CD_SIGNING_KEY_PKCS8: &[u8] = include_bytes!(
        "../../../../../test-vectors/commissioning/cd/csa-test-cd-signing-root.pkcs8.der"
    );

    /// Build the inner CD TLV per Matter Core Spec §6.3.1, optionally
    /// including the `dac_origin_*` override fields (tags 9 / 10).
    ///
    /// Mirrors `xtask/src/capture_cd.rs::build_inner_cd_tlv` but adds the
    /// optional tags 9/10 so the Fix B override path can be exercised.
    #[allow(clippy::unwrap_used)] // Test-code carve-out: see CLAUDE.md.
    fn build_inner_cd_tlv(
        vendor_id: u16,
        product_id: u16,
        dac_origin_vid: Option<u16>,
        dac_origin_pid: Option<u16>,
        product_id_array: &[u16],
    ) -> Vec<u8> {
        use matter_codec::{Tag, TlvWriter};
        let mut buf = Vec::new();
        {
            let mut w = TlvWriter::new(&mut buf);
            w.start_structure(Tag::Anonymous).unwrap();
            w.put_uint(Tag::Context(0), 1).unwrap(); // format_version
            w.put_uint(Tag::Context(1), u64::from(vendor_id)).unwrap(); // vendor_id
            w.start_array(Tag::Context(2)).unwrap(); // product_id_array
            let pids: Vec<u16> = if product_id_array.is_empty() {
                vec![product_id]
            } else {
                product_id_array.to_vec()
            };
            for p in pids {
                w.put_uint(Tag::Anonymous, u64::from(p)).unwrap();
            }
            w.end_container().unwrap();
            w.put_uint(Tag::Context(3), 0x0100).unwrap(); // device_type_id
            w.put_utf8(Tag::Context(4), "CSA00000000000000").unwrap(); // certificate_id
            w.put_uint(Tag::Context(5), 0).unwrap(); // security_level
            w.put_uint(Tag::Context(6), 0).unwrap(); // security_information
            w.put_uint(Tag::Context(7), 1).unwrap(); // version_number
            w.put_uint(Tag::Context(8), 0).unwrap(); // certification_type
            if let Some(v) = dac_origin_vid {
                w.put_uint(Tag::Context(9), u64::from(v)).unwrap();
            }
            if let Some(p) = dac_origin_pid {
                w.put_uint(Tag::Context(10), u64::from(p)).unwrap();
            }
            w.end_container().unwrap();
        }
        buf
    }

    /// Sign `content` (the inner CD TLV) into a CMS `SignedData`
    /// `ContentInfo` DER blob with the bundled CSA-test key, using the
    /// no-`signedAttrs` shape the verifier expects. Mirrors
    /// `xtask/src/capture_cd.rs::sign_into_cms`.
    #[allow(clippy::unwrap_used, clippy::expect_used)] // Test-code carve-out: see CLAUDE.md.
    fn sign_into_cms(content: &[u8]) -> Vec<u8> {
        use cms::cert::IssuerAndSerialNumber;
        use cms::content_info::{CmsVersion, ContentInfo};
        use cms::signed_data::{
            EncapsulatedContentInfo, SignedData, SignerIdentifier, SignerInfo, SignerInfos,
        };
        use const_oid::ObjectIdentifier;
        use der::asn1::{Any, AnyRef, OctetString, SetOfVec};
        use der::{Encode, Tag as DerTag};
        use ring::rand::SystemRandom;
        use ring::signature::{EcdsaKeyPair, ECDSA_P256_SHA256_FIXED_SIGNING};
        use spki::AlgorithmIdentifierOwned;
        use x509_cert::name::RdnSequence;
        use x509_cert::serial_number::SerialNumber;

        const ID_DATA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.7.1");
        const ID_SIGNED_DATA: ObjectIdentifier =
            ObjectIdentifier::new_unwrap("1.2.840.113549.1.7.2");
        const ID_SHA_256: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.2.1");
        const ECDSA_WITH_SHA_256: ObjectIdentifier =
            ObjectIdentifier::new_unwrap("1.2.840.10045.4.3.2");

        let rng = SystemRandom::new();
        let key = EcdsaKeyPair::from_pkcs8(
            &ECDSA_P256_SHA256_FIXED_SIGNING,
            CSA_TEST_CD_SIGNING_KEY_PKCS8,
            &rng,
        )
        .expect("bundled CSA-test CD signing key loads");
        let signature = key.sign(&rng, content).expect("sign eContent");

        let econtent_any =
            Any::new(DerTag::OctetString, content.to_vec()).expect("Any(OctetString)");
        let encap = EncapsulatedContentInfo {
            econtent_type: ID_DATA,
            econtent: Some(econtent_any),
        };
        let sha256 = AlgorithmIdentifierOwned {
            oid: ID_SHA_256,
            parameters: None,
        };
        let digest_algorithms =
            SetOfVec::try_from(vec![sha256.clone()]).expect("digest_algorithms");
        let serial = SerialNumber::new(&[0x01]).expect("serial");
        let sid = SignerIdentifier::IssuerAndSerialNumber(IssuerAndSerialNumber {
            issuer: RdnSequence::default(),
            serial_number: serial,
        });
        let signature_octets =
            OctetString::new(signature.as_ref().to_vec()).expect("signature octets");
        let signer_info = SignerInfo {
            version: CmsVersion::V1,
            sid,
            digest_alg: sha256,
            signed_attrs: None,
            signature_algorithm: AlgorithmIdentifierOwned {
                oid: ECDSA_WITH_SHA_256,
                parameters: None,
            },
            signature: signature_octets,
            unsigned_attrs: None,
        };
        let signer_infos = SignerInfos(SetOfVec::try_from(vec![signer_info]).expect("signer set"));
        let signed_data = SignedData {
            version: CmsVersion::V1,
            digest_algorithms,
            encap_content_info: encap,
            certificates: None,
            crls: None,
            signer_infos,
        };
        let signed_data_der = signed_data.to_der().expect("SignedData der");
        let signed_data_any =
            Any::from(AnyRef::try_from(signed_data_der.as_slice()).expect("AnyRef"));
        let content_info = ContentInfo {
            content_type: ID_SIGNED_DATA,
            content: signed_data_any,
        };
        content_info.to_der().expect("ContentInfo der")
    }

    #[test]
    #[allow(clippy::expect_used)] // Test-code carve-out: see CLAUDE.md.
    fn dac_origin_present_dac_matches_origin_is_accepted() {
        // CD's own vendor_id/product_id_array are 0xFFF1 / 0x8001, but
        // dac_origin says the DAC is scoped to 0x1234 / 0x5678. A DAC at
        // 0x1234 / 0x5678 must be accepted (bound to the origin fields),
        // even though it does NOT match the CD's own vendor_id.
        let tlv = build_inner_cd_tlv(0xFFF1, 0x8001, Some(0x1234), Some(0x5678), &[0x8001]);
        let cd = sign_into_cms(&tlv);
        let trust = CdSigningRoots::with_csa_test_roots();

        verify_certification_declaration(
            &cd,
            VendorId::new(0x1234),
            ProductId::new(0x5678),
            &trust,
        )
        .expect("DAC matching dac_origin VID/PID must be accepted");
    }

    #[test]
    #[allow(clippy::expect_used)] // Test-code carve-out: see CLAUDE.md.
    fn dac_origin_present_dac_matches_neither_is_rejected() {
        // dac_origin = 0x1234/0x5678. A DAC at 0xFFF1/0x8001 (the CD's own
        // vendor_id/pid) must be REJECTED, because the override path binds
        // against dac_origin, not the CD's own fields.
        let tlv = build_inner_cd_tlv(0xFFF1, 0x8001, Some(0x1234), Some(0x5678), &[0x8001]);
        let cd = sign_into_cms(&tlv);
        let trust = CdSigningRoots::with_csa_test_roots();

        let err = verify_certification_declaration(
            &cd,
            VendorId::new(0xFFF1),
            ProductId::new(0x8001),
            &trust,
        )
        .expect_err("DAC not matching dac_origin must be rejected");
        assert!(
            matches!(
                err,
                AttestationError::CertificationDeclarationVidMismatch {
                    declared,
                    expected,
                } if declared == VendorId::new(0x1234) && expected == VendorId::new(0xFFF1)
            ),
            "expected VID mismatch against the dac_origin VID, got {err:?}"
        );
    }

    #[test]
    #[allow(clippy::expect_used)] // Test-code carve-out: see CLAUDE.md.
    fn no_dac_origin_uses_vendor_id_and_pid_array() {
        // Without dac_origin, the standard path compares against the CD's
        // own vendor_id / product_id_array (unchanged behaviour).
        let tlv = build_inner_cd_tlv(0xFFF1, 0x8001, None, None, &[0x8001, 0x8002]);
        let cd = sign_into_cms(&tlv);
        let trust = CdSigningRoots::with_csa_test_roots();

        // A PID present in the array is accepted.
        verify_certification_declaration(
            &cd,
            VendorId::new(0xFFF1),
            ProductId::new(0x8002),
            &trust,
        )
        .expect("DAC matching vendor_id and a member of product_id_array accepted");

        // A PID NOT in the array is rejected (still the standard path).
        let err = verify_certification_declaration(
            &cd,
            VendorId::new(0xFFF1),
            ProductId::new(0x9999),
            &trust,
        )
        .expect_err("PID outside product_id_array rejected");
        assert!(
            matches!(err, AttestationError::CertificationDeclarationPidMismatch(p)
                if p == ProductId::new(0x9999)),
            "expected PID mismatch, got {err:?}"
        );
    }
}