Skip to main content

matter_kit/attestation/
x509.rs

1//! Reading the X.509 certificates of the Device Attestation PKI (Core §6.2.2).
2//!
3//! The DAC chain is the one place Matter uses certificates it cannot re-encode. An
4//! operational certificate is Matter TLV that *stands for* an X.509 certificate
5//! ([`cert`](crate::cert)); a DAC, PAI and PAA are X.509 certificates and nothing else,
6//! burned in at manufacture by a CA this crate has no influence over. So they are read, not
7//! modelled: [`X509Certificate`] borrows its fields from the DER and keeps the `tbsCertificate`
8//! verbatim, because that is what the signature covers and re-encoding it would be a
9//! guess about a CA's choices.
10//!
11//! The parser is deliberately narrow. §6.2.2.3 rule 12e permits "any other extension allowed
12//! in RFC 5280 … These extensions insofar not defined in this specification SHALL be ignored
13//! by commissioners", so unknown extensions are skipped rather than refused — but everything
14//! the specification does constrain is checked, and anything structurally ambiguous is an
15//! error.
16//!
17//! # Vendor ID and Product ID, two ways
18//!
19//! §6.2.2.2 allows a CA to put the VID and PID either in Matter-specific RDN attributes (the
20//! "preferred method") or as `Mvid:FFF1` / `Mpid:8000` substrings inside the `commonName`
21//! (the "fallback method", "present to support less flexible CA infrastructure").
22//!
23//! The two never mix within one field, and the rule for which applies is not "try both": if
24//! either Matter OID appears anywhere in a field, "the presence of either of these OIDs …
25//! SHALL cause the 'fallback method' to be skipped altogether for that field". So a
26//! certificate with a Matter VID OID and a `Mpid:` substring has a VID and **no** PID, which
27//! is a different certificate from one where both were read. [`VidPid::from_name`]
28//! implements that, field by field.
29
30use crate::crypto::{PublicKey, Signature, verify};
31use crate::der::{
32    DerReader, Element, OID_COMMON_NAME, OID_EC_PUBLIC_KEY, OID_ECDSA_WITH_SHA256,
33    OID_MATTER_ATTESTATION_PREFIX, OID_PRIME256V1, TAG_BIT_STRING, TAG_BOOLEAN, TAG_INTEGER,
34    TAG_OCTET_STRING, TAG_OID, TAG_SEQUENCE, context_constructed, ecdsa_sig_value_to_raw,
35    read_time,
36};
37use crate::error::{Error, ErrorCode, Result};
38use crate::msg::VendorId;
39
40/// `version \[0\] EXPLICIT`.
41const TAG_VERSION: u8 = context_constructed(0);
42/// `extensions \[3\] EXPLICIT`.
43const TAG_EXTENSIONS: u8 = context_constructed(3);
44
45/// `1.3.6.1.4.1.37244.2.1` — `matter-oid-vid` (§6.2.2.2, Table 85).
46const OID_MATTER_VID_ARC: u8 = 1;
47/// `1.3.6.1.4.1.37244.2.2` — `matter-oid-pid`.
48const OID_MATTER_PID_ARC: u8 = 2;
49
50/// The `Mvid:` prefix of the fallback method.
51pub const FALLBACK_VID_PREFIX: &[u8] = b"Mvid:";
52/// The `Mpid:` prefix of the fallback method.
53pub const FALLBACK_PID_PREFIX: &[u8] = b"Mpid:";
54
55/// "All certificates SHALL NOT be longer than 600 bytes in their uncompressed DER format …
56/// This constraint SHALL apply to the entire DAC chain" (§6.1.3).
57pub const MAX_DER_LEN: usize = 600;
58
59/// A key identifier is 20 octets (§6.1.2).
60pub const KEY_ID_LEN: usize = 20;
61
62fn malformed() -> Error {
63    Error::new(ErrorCode::DerMalformed)
64}
65
66fn invalid() -> Error {
67    Error::new(ErrorCode::CertInvalid)
68}
69
70// --- Vendor ID and Product ID --------------------------------------------------------------
71
72/// The Vendor ID and Product ID read out of one distinguished name (§6.2.2.2).
73#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
74pub struct VidPid {
75    /// The Vendor ID, if the field carries one.
76    pub vendor_id: Option<VendorId>,
77    /// The Product ID, if the field carries one.
78    pub product_id: Option<u16>,
79}
80
81impl VidPid {
82    /// Reads the VID and PID out of a `Name`'s DER, applying §6.2.2.2's method rules.
83    ///
84    /// A field either uses the Matter OIDs or the `commonName` fallback, never both: the
85    /// presence of *either* Matter OID disables the fallback for the whole field.
86    ///
87    /// Returns [`ErrorCode::CertInvalid`] where the specification says a field is
88    /// "incorrectly formatted" — a Matter OID whose value is not the exact hex width
89    /// §6.1.1 requires, or an `Mvid:`/`Mpid:` prefix with no well-formed match anywhere in
90    /// the `commonName`. Refusing rather than reporting absence matters: a commissioner that
91    /// read "no PID" from a certificate whose PID is merely malformed would compare against
92    /// the wrong thing.
93    pub fn from_name(name: &[u8]) -> Result<Self> {
94        let mut out = Self::default();
95        let mut saw_matter_oid = false;
96        let mut common_name: Option<&[u8]> = None;
97
98        let mut rdns = DerReader::new(name);
99        while !rdns.is_empty() {
100            let mut rdn = rdns.expect_set()?;
101            while !rdn.is_empty() {
102                let mut atv = rdn.expect_sequence()?;
103                let oid = atv.expect(TAG_OID)?.content;
104                let value = atv.next_element()?;
105                atv.finish()?;
106
107                if let Some(arc) = matter_attestation_arc(oid) {
108                    saw_matter_oid = true;
109                    // §6.1.1: "encoded in network byte order as exactly twice their
110                    // specified maximum octet length … without omitting any leading zeroes",
111                    // so a VID or PID is exactly four uppercase hex characters.
112                    let scalar = parse_hex4(value.content).ok_or_else(invalid)?;
113                    match arc {
114                        OID_MATTER_VID_ARC => out.vendor_id = Some(VendorId(scalar)),
115                        OID_MATTER_PID_ARC => out.product_id = Some(scalar),
116                        _ => {}
117                    }
118                } else if oid == OID_COMMON_NAME {
119                    common_name = Some(value.content);
120                }
121            }
122        }
123
124        if saw_matter_oid {
125            // "the presence of either of these OIDs as the type for any AttributeTypeAndValue
126            // within any RelativeDistinguishedName of that field SHALL cause the 'fallback
127            // method' to be skipped altogether for that field."
128            return Ok(out);
129        }
130        if let Some(cn) = common_name {
131            out.vendor_id = fallback_scalar(cn, FALLBACK_VID_PREFIX)?.map(VendorId);
132            out.product_id = fallback_scalar(cn, FALLBACK_PID_PREFIX)?;
133        }
134        Ok(out)
135    }
136}
137
138/// The final arc of a `1.3.6.1.4.1.37244.2.x` OID, if `oid` is one.
139fn matter_attestation_arc(oid: &[u8]) -> Option<u8> {
140    let rest = oid.strip_prefix(OID_MATTER_ATTESTATION_PREFIX)?;
141    match rest {
142        [arc] => Some(*arc),
143        _ => None,
144    }
145}
146
147/// Parses exactly four uppercase hex characters into a `u16`.
148fn parse_hex4(text: &[u8]) -> Option<u16> {
149    let [a, b, c, d] = <[u8; 4]>::try_from(text).ok()?;
150    let mut value = 0u16;
151    for byte in [a, b, c, d] {
152        let digit = match byte {
153            b'0'..=b'9' => byte.checked_sub(b'0')?,
154            // Uppercase only: §6.2.2.2's own example calls `Mvid:fff1` invalid.
155            b'A'..=b'F' => byte.checked_sub(b'A')?.checked_add(10)?,
156            _ => return None,
157        };
158        value = value.checked_mul(16)?.checked_add(u16::from(digit))?;
159    }
160    Some(value)
161}
162
163/// Applies the fallback method to a `commonName` (§6.2.2.2).
164///
165/// "The leftmost match having a correct encoding SHALL be used, with other correct matches
166/// discarded" — and, crucially, "if the prefix string is found on its own anywhere within
167/// the commonName, but there is no fully correct match anywhere in the commonName, the field
168/// SHALL be considered incorrectly formatted."
169///
170/// So this cannot simply return `None` when nothing parses: the specification's own example
171/// `"… Mpid: Mvid:FFF1"` is an error, not a certificate without a product id.
172fn fallback_scalar(common_name: &[u8], prefix: &[u8]) -> Result<Option<u16>> {
173    let mut saw_prefix = false;
174    let mut at = 0usize;
175    while let Some(slice) = common_name.get(at..) {
176        if slice.len() < prefix.len() {
177            break;
178        }
179        if slice.starts_with(prefix) {
180            saw_prefix = true;
181            if let Some(digits) = slice.get(prefix.len()..prefix.len().saturating_add(4))
182                && let Some(value) = parse_hex4(digits)
183            {
184                // The leftmost correct match wins; later ones are discarded.
185                return Ok(Some(value));
186            }
187        }
188        at = at.checked_add(1).ok_or_else(invalid)?;
189    }
190    if saw_prefix { Err(invalid()) } else { Ok(None) }
191}
192
193// --- The certificate --------------------------------------------------------------------------
194
195bitflags::bitflags! {
196    /// X.509's `KeyUsage` bits, numbered from the most significant bit of the first octet
197    /// (RFC 5280 §4.2.1.3) — the *reverse* of Matter's own `key-usage-flag` numbering.
198    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
199    pub struct KeyUsage: u16 {
200        /// `digitalSignature`.
201        const DIGITAL_SIGNATURE = 1 << 0;
202        /// `nonRepudiation`.
203        const NON_REPUDIATION = 1 << 1;
204        /// `keyEncipherment`.
205        const KEY_ENCIPHERMENT = 1 << 2;
206        /// `dataEncipherment`.
207        const DATA_ENCIPHERMENT = 1 << 3;
208        /// `keyAgreement`.
209        const KEY_AGREEMENT = 1 << 4;
210        /// `keyCertSign`.
211        const KEY_CERT_SIGN = 1 << 5;
212        /// `cRLSign`.
213        const CRL_SIGN = 1 << 6;
214        /// `encipherOnly`.
215        const ENCIPHER_ONLY = 1 << 7;
216        /// `decipherOnly`.
217        const DECIPHER_ONLY = 1 << 8;
218    }
219}
220
221/// `BasicConstraints ::= SEQUENCE { cA BOOLEAN DEFAULT FALSE, pathLenConstraint INTEGER
222/// OPTIONAL }`.
223#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
224pub struct BasicConstraints {
225    /// Whether the subject is a CA.
226    pub is_ca: bool,
227    /// The maximum number of intermediates below this one.
228    pub path_len: Option<u8>,
229}
230
231/// A parsed attestation certificate: a DAC, PAI or PAA.
232#[derive(Debug, Clone, PartialEq, Eq)]
233pub struct X509Certificate<'a> {
234    /// The `tbsCertificate`, verbatim — the bytes the signature covers.
235    pub tbs: &'a [u8],
236    /// The `serialNumber`'s magnitude.
237    pub serial_number: &'a [u8],
238    /// The `issuer` `Name`, as DER. §6.2.2.3 rule 6 requires a byte-for-byte match against
239    /// the issuer's `subject`, so it is kept encoded rather than parsed into a model.
240    pub issuer: &'a [u8],
241    /// The `subject` `Name`, as DER.
242    pub subject: &'a [u8],
243    /// The VID and PID of the issuer field.
244    pub issuer_vid_pid: VidPid,
245    /// The VID and PID of the subject field.
246    pub subject_vid_pid: VidPid,
247    /// `notBefore`, as a Matter `epoch-s`.
248    pub not_before: u32,
249    /// `notAfter`, or `None` for `99991231235959Z`.
250    pub not_after: Option<u32>,
251    /// The subject's P-256 public key.
252    pub public_key: PublicKey,
253    /// `basicConstraints`, absent in neither a DAC nor a CA here but optional in X.509.
254    pub basic_constraints: Option<BasicConstraints>,
255    /// `keyUsage`.
256    pub key_usage: Option<KeyUsage>,
257    /// `subjectKeyIdentifier`.
258    pub subject_key_id: Option<[u8; KEY_ID_LEN]>,
259    /// `authorityKeyIdentifier`'s `keyIdentifier`.
260    pub authority_key_id: Option<[u8; KEY_ID_LEN]>,
261    /// Whether the certificate carries an `extendedKeyUsage`, which §6.2.2 permits but does
262    /// not constrain.
263    pub has_extended_key_usage: bool,
264    /// The signature, as the `r || s` of §3.5.3.
265    pub signature: Signature,
266}
267
268impl<'a> X509Certificate<'a> {
269    /// Parses an attestation certificate.
270    pub fn parse(der: &'a [u8]) -> Result<Self> {
271        if der.len() > MAX_DER_LEN {
272            // §6.1.3, which is what keeps a DAC chain inside a `CertificateChainResponse`.
273            return Err(invalid());
274        }
275        let mut outer = DerReader::new(der);
276        let mut cert = outer.expect_sequence()?;
277        outer.finish()?;
278
279        let tbs_element = cert.expect(TAG_SEQUENCE)?;
280        let mut tbs = tbs_element.content_reader();
281
282        // version [0] EXPLICIT INTEGER. "The version field SHALL be set to 2 to indicate v3."
283        let version = tbs.expect(TAG_VERSION)?;
284        let mut version_reader = version.content_reader();
285        if version_reader.expect_uint()? != 2 {
286            return Err(invalid());
287        }
288        version_reader.finish()?;
289
290        let serial_number = tbs.expect_unsigned()?;
291
292        // signature AlgorithmIdentifier: "SHALL contain the identifier for signatureAlgorithm
293        // ecdsa-with-SHA256".
294        let mut signature_algo = tbs.expect_sequence()?;
295        signature_algo.expect_oid(OID_ECDSA_WITH_SHA256)?;
296
297        let issuer = tbs.expect(TAG_SEQUENCE)?.content;
298
299        let mut validity = tbs.expect_sequence()?;
300        let not_before = read_time(&validity.next_element()?)?.ok_or_else(invalid)?;
301        let not_after = read_time(&validity.next_element()?)?;
302        validity.finish()?;
303
304        let subject = tbs.expect(TAG_SEQUENCE)?.content;
305
306        // subjectPublicKeyInfo. "The algorithm field … SHALL be the object identifier for
307        // prime256v1."
308        let mut spki = tbs.expect_sequence()?;
309        let mut key_algo = spki.expect_sequence()?;
310        key_algo.expect_oid(OID_EC_PUBLIC_KEY)?;
311        key_algo.expect_oid(OID_PRIME256V1)?;
312        key_algo.finish()?;
313        let public_key = PublicKey::from_slice(spki.expect(TAG_BIT_STRING)?.bit_string_octets()?)?;
314        spki.finish()?;
315
316        // issuerUniqueID [1] and subjectUniqueID [2] are v2 fields RFC 5280 deprecates; a
317        // Matter attestation certificate has none, and skipping them keeps the extensions
318        // lookup honest if one ever appears.
319        let _ = tbs.take_if(context_constructed(1))?;
320        let _ = tbs.take_if(context_constructed(2))?;
321
322        let mut parsed = Extensions::default();
323        if let Some(extensions) = tbs.take_if(TAG_EXTENSIONS)? {
324            let mut explicit = extensions.content_reader();
325            let mut list = explicit.expect_sequence()?;
326            explicit.finish()?;
327            while !list.is_empty() {
328                parsed.absorb(&mut list.expect_sequence()?)?;
329            }
330        }
331        tbs.finish()?;
332
333        let mut sig_algo = cert.expect_sequence()?;
334        sig_algo.expect_oid(OID_ECDSA_WITH_SHA256)?;
335        sig_algo.finish()?;
336
337        let signature_der = cert.expect(TAG_BIT_STRING)?.bit_string_octets()?;
338        cert.finish()?;
339        let mut raw = [0u8; 64];
340        ecdsa_sig_value_to_raw(signature_der, &mut raw)?;
341
342        Ok(Self {
343            tbs: tbs_element.raw,
344            serial_number,
345            issuer,
346            subject,
347            issuer_vid_pid: VidPid::from_name(issuer)?,
348            subject_vid_pid: VidPid::from_name(subject)?,
349            not_before,
350            not_after,
351            public_key,
352            basic_constraints: parsed.basic_constraints,
353            key_usage: parsed.key_usage,
354            subject_key_id: parsed.subject_key_id,
355            authority_key_id: parsed.authority_key_id,
356            has_extended_key_usage: parsed.has_extended_key_usage,
357            signature: Signature::from_bytes(raw),
358        })
359    }
360
361    /// Whether `at` (a Matter `epoch-s`) falls inside the validity window.
362    #[must_use]
363    pub const fn is_valid_at(&self, at: u32) -> bool {
364        at >= self.not_before
365            && match self.not_after {
366                Some(end) => at <= end,
367                None => true,
368            }
369    }
370
371    /// Whether this certificate is a CA.
372    #[must_use]
373    pub fn is_ca(&self) -> bool {
374        self.basic_constraints.is_some_and(|b| b.is_ca)
375    }
376
377    /// Verifies `subject`'s signature against this certificate's public key.
378    pub fn verify_signature_of(&self, subject: &Self) -> Result<bool> {
379        verify(&self.public_key, subject.tbs, &subject.signature)
380    }
381}
382
383/// The extensions this module understands, gathered as they are walked.
384#[derive(Debug, Default)]
385struct Extensions {
386    basic_constraints: Option<BasicConstraints>,
387    key_usage: Option<KeyUsage>,
388    subject_key_id: Option<[u8; KEY_ID_LEN]>,
389    authority_key_id: Option<[u8; KEY_ID_LEN]>,
390    has_extended_key_usage: bool,
391    /// Which `2.5.29.x` extensions have been seen, so a second instance is refused.
392    ///
393    /// RFC 5280 §4.2: "A certificate MUST NOT include more than one instance of a particular
394    /// extension." Overwriting silently would let a second `keyUsage` mask the first, so two
395    /// implementations could read the same certificate differently.
396    seen: u64,
397}
398
399impl Extensions {
400    /// Reads one `Extension ::= SEQUENCE { extnID OID, critical BOOLEAN DEFAULT FALSE,
401    /// extnValue OCTET STRING }`.
402    fn absorb(&mut self, extension: &mut DerReader<'_>) -> Result<()> {
403        let oid = extension.expect(TAG_OID)?.content;
404        // `critical` is a DEFAULT FALSE boolean, so it is present only when TRUE.
405        let critical = match extension.take_if(TAG_BOOLEAN)? {
406            Some(element) => element.content == [0xFF],
407            None => false,
408        };
409        let value = extension.expect(TAG_OCTET_STRING)?.content;
410        extension.finish()?;
411
412        // 2.5.29.x.
413        let Some([arc]) = oid.strip_prefix(crate::der::OID_CE_PREFIX) else {
414            // Not a standard extension — an authorityInfoAccess, say. §6.2.2.3 rule 12e:
415            // "These extensions insofar not defined in this specification SHALL be ignored."
416            return Ok(());
417        };
418        if let Some(bit) = 1u64.checked_shl(u32::from(*arc)) {
419            if self.seen & bit != 0 {
420                return Err(invalid());
421            }
422            self.seen |= bit;
423        }
424
425        let mut reader = DerReader::new(value);
426        match *arc {
427            14 => {
428                // subjectKeyIdentifier ::= OCTET STRING
429                self.subject_key_id = Some(key_id(&reader.expect(TAG_OCTET_STRING)?)?);
430            }
431            15 => {
432                // keyUsage ::= BIT STRING, and §6.2.2.3 requires it critical.
433                if !critical {
434                    return Err(invalid());
435                }
436                self.key_usage = Some(read_key_usage(&reader.expect(TAG_BIT_STRING)?)?);
437            }
438            19 => {
439                // basicConstraints, which §6.2.2.3 also requires critical.
440                if !critical {
441                    return Err(invalid());
442                }
443                let mut seq = reader.expect_sequence()?;
444                let is_ca = match seq.take_if(TAG_BOOLEAN)? {
445                    Some(element) => element.content == [0xFF],
446                    None => false,
447                };
448                let path_len = match seq.take_if(TAG_INTEGER)? {
449                    // `pathLenConstraint` is a small non-negative integer; anything wider
450                    // than one octet is not a path length a Matter chain could satisfy.
451                    Some(element) => match element.content {
452                        [len] if *len < 0x80 => Some(*len),
453                        _ => return Err(malformed()),
454                    },
455                    None => None,
456                };
457                seq.finish()?;
458                // RFC 5280 §4.2.1.9: "CAs MUST NOT include the pathLenConstraint field
459                // unless the cA boolean is asserted". A path length on a leaf is a
460                // certificate nobody meant to issue.
461                if !is_ca && path_len.is_some() {
462                    return Err(invalid());
463                }
464                self.basic_constraints = Some(BasicConstraints { is_ca, path_len });
465            }
466            35 => {
467                // authorityKeyIdentifier ::= SEQUENCE { keyIdentifier [0] OPTIONAL, ... }
468                let mut seq = reader.expect_sequence()?;
469                if let Some(element) = seq.take_if(crate::der::context_primitive(0))? {
470                    self.authority_key_id = Some(key_id(&element)?);
471                }
472                // authorityCertIssuer [1] and authorityCertSerialNumber [2] are optional and
473                // "not supported by Matter certificates"; their presence changes nothing.
474            }
475            37 => self.has_extended_key_usage = true,
476            _ => {}
477        }
478        Ok(())
479    }
480}
481
482fn key_id(element: &Element<'_>) -> Result<[u8; KEY_ID_LEN]> {
483    // §6.1.2: "the associated Key Identifier SHALL be of a length of 20 octets".
484    <[u8; KEY_ID_LEN]>::try_from(element.content).map_err(|_| invalid())
485}
486
487/// Reads a `KeyUsage` BIT STRING into Matter's bit numbering.
488///
489/// X.509 numbers named bits from the most significant bit of the first octet; this crate's
490/// flags are `1 << n` for bit `n`. So each octet is bit-reversed, which is the same
491/// transformation [`cert::der`](crate::cert::der) applies in the writing direction.
492fn read_key_usage(element: &Element<'_>) -> Result<KeyUsage> {
493    let content = element.content;
494    let (unused, octets) = content.split_first().ok_or_else(malformed)?;
495    if *unused > 7 || octets.len() > 2 {
496        return Err(malformed());
497    }
498    // DER requires the unused trailing bits to be zero. A non-zero one would read as a named
499    // bit that is not really set — a `keyUsage` of `digitalSignature` that also claims
500    // `encipherOnly`, say — so two parsers could disagree about what a CA authorised.
501    if *unused > 0 {
502        let last = octets.last().copied().unwrap_or(0);
503        let mask = 0xFFu8
504            .checked_shr(8u32.saturating_sub(u32::from(*unused)))
505            .unwrap_or(0);
506        if last & mask != 0 {
507            return Err(malformed());
508        }
509    }
510    let mut bits = 0u16;
511    if let Some(first) = octets.first() {
512        bits |= u16::from(first.reverse_bits());
513    }
514    if let Some(second) = octets.get(1) {
515        bits |= u16::from(second.reverse_bits()) << 8;
516    }
517    KeyUsage::from_bits(bits).ok_or_else(invalid)
518}
519
520#[cfg(test)]
521mod tests {
522    use super::*;
523
524    /// Wraps a `keyUsage` BIT STRING body in enough DER to read it.
525    fn key_usage_element(unused: u8, octets: &[u8]) -> heapless::Vec<u8, 8> {
526        let mut out = heapless::Vec::new();
527        let _ = out.push(TAG_BIT_STRING);
528        let _ = out.push(u8::try_from(octets.len().saturating_add(1)).unwrap_or(0));
529        let _ = out.push(unused);
530        let _ = out.extend_from_slice(octets);
531        out
532    }
533
534    fn read_usage(unused: u8, octets: &[u8]) -> Result<KeyUsage> {
535        let bytes = key_usage_element(unused, octets);
536        let element = DerReader::new(&bytes).next_element()?;
537        read_key_usage(&element)
538    }
539
540    #[test]
541    fn key_usage_bits_are_numbered_from_the_most_significant_bit() {
542        // RFC 5280 §4.2.1.3 numbers named bits from the MSB of the first octet, which is the
543        // reverse of Matter's own key-usage-flag numbering. Getting this backwards turns a
544        // `digitalSignature` leaf into something claiming `encipherOnly`.
545        assert_eq!(
546            read_usage(7, &[0x80]).expect("ds"),
547            KeyUsage::DIGITAL_SIGNATURE
548        );
549        assert_eq!(
550            read_usage(1, &[0x06]).expect("ca"),
551            KeyUsage::KEY_CERT_SIGN | KeyUsage::CRL_SIGN
552        );
553        // decipherOnly is bit 8, so it needs a second octet.
554        assert_eq!(
555            read_usage(7, &[0x00, 0x80]).expect("do"),
556            KeyUsage::DECIPHER_ONLY
557        );
558    }
559
560    #[test]
561    fn a_bit_string_with_non_zero_unused_bits_is_refused() {
562        // DER requires them zero. A parser that ignored them would read a named bit that is
563        // not really set, so two implementations could disagree about what a CA authorised.
564        assert!(
565            read_usage(7, &[0x81]).is_err(),
566            "bit 7 is not an unused zero"
567        );
568        assert!(read_usage(1, &[0x07]).is_err());
569        // The same octets with the right unused count are fine.
570        assert!(read_usage(0, &[0x81]).is_ok());
571    }
572
573    #[test]
574    fn an_over_wide_key_usage_is_refused() {
575        // Nine named bits fit in two octets; a third is not a KeyUsage.
576        assert!(read_usage(0, &[0x00, 0x00, 0x00]).is_err());
577        assert!(
578            read_usage(8, &[0x00]).is_err(),
579            "8 unused bits is not a thing"
580        );
581    }
582
583    /// The `Name` DER for a single `commonName`, for the fallback-method tests.
584    fn common_name(cn: &str) -> heapless::Vec<u8, 128> {
585        let mut atv = heapless::Vec::<u8, 128>::new();
586        let _ = atv.extend_from_slice(&[0x06, 0x03, 0x55, 0x04, 0x03, 0x0C]);
587        let _ = atv.push(u8::try_from(cn.len()).unwrap_or(0));
588        let _ = atv.extend_from_slice(cn.as_bytes());
589
590        let mut seq = heapless::Vec::<u8, 128>::new();
591        let _ = seq.push(TAG_SEQUENCE);
592        let _ = seq.push(u8::try_from(atv.len()).unwrap_or(0));
593        let _ = seq.extend_from_slice(&atv);
594
595        let mut set = heapless::Vec::<u8, 128>::new();
596        let _ = set.push(crate::der::TAG_SET);
597        let _ = set.push(u8::try_from(seq.len()).unwrap_or(0));
598        let _ = set.extend_from_slice(&seq);
599        set
600    }
601
602    #[test]
603    fn the_leftmost_correct_match_wins_and_earlier_malformed_ones_do_not_count() {
604        // §6.2.2.2: "The leftmost match having a correct encoding SHALL be used, with other
605        // correct matches discarded." A malformed occurrence before a correct one is passed
606        // over, not treated as the answer.
607        let name = common_name("Mvid:zzzz and Mvid:ABCD");
608        let parsed = VidPid::from_name(&name).expect("parse");
609        assert_eq!(parsed.vendor_id, Some(VendorId(0xABCD)));
610    }
611
612    #[test]
613    fn a_prefix_with_no_correct_match_anywhere_is_an_error_not_an_absence() {
614        // "if the prefix string is found on its own anywhere within the commonName, but
615        // there is no fully correct match anywhere … the field SHALL be considered
616        // incorrectly formatted." Answering "no vendor id" would let a commissioner compare
617        // against the wrong thing rather than refuse.
618        let name = common_name("Mvid:zzzz");
619        assert_eq!(
620            VidPid::from_name(&name).map(|_| ()).unwrap_err().code(),
621            ErrorCode::CertInvalid
622        );
623    }
624
625    #[test]
626    fn hex_must_be_exactly_four_uppercase_digits() {
627        assert_eq!(parse_hex4(b"FFF1"), Some(0xFFF1));
628        assert_eq!(parse_hex4(b"002A"), Some(0x002A));
629        assert_eq!(parse_hex4(b"0000"), Some(0));
630        // Lowercase is explicitly invalid per §6.2.2.2's own example.
631        assert_eq!(parse_hex4(b"fff1"), None);
632        assert_eq!(parse_hex4(b"FFF"), None);
633        assert_eq!(parse_hex4(b"FFF12"), None);
634        assert_eq!(parse_hex4(b"FFG1"), None);
635    }
636
637    #[test]
638    fn the_matter_arc_is_matched_exactly() {
639        // `1.3.6.1.4.1.37244.2.1` and `.2.2` are the attestation attributes; the operational
640        // DN attributes live under `.1.x` and must not be mistaken for them.
641        let mut vid = heapless::Vec::<u8, 16>::new();
642        let _ = vid.extend_from_slice(OID_MATTER_ATTESTATION_PREFIX);
643        let _ = vid.push(1);
644        assert_eq!(matter_attestation_arc(&vid), Some(OID_MATTER_VID_ARC));
645
646        // One arc too long is not one of these.
647        let mut deeper = vid.clone();
648        let _ = deeper.push(9);
649        assert_eq!(matter_attestation_arc(&deeper), None);
650
651        // And the operational prefix is a different arc entirely.
652        assert_eq!(
653            matter_attestation_arc(crate::der::OID_MATTER_DN_PREFIX),
654            None
655        );
656    }
657
658    #[test]
659    fn a_field_using_the_matter_oids_ignores_a_common_name_fallback() {
660        // §6.2.2.2: the presence of either Matter OID "SHALL cause the 'fallback method' to
661        // be skipped altogether for that field". So this name has a vendor id and *no*
662        // product id, even though `Mpid:` is right there.
663        let mut atv = heapless::Vec::<u8, 128>::new();
664        let _ = atv.push(TAG_OID);
665        let _ = atv
666            .push(u8::try_from(OID_MATTER_ATTESTATION_PREFIX.len().saturating_add(1)).unwrap_or(0));
667        let _ = atv.extend_from_slice(OID_MATTER_ATTESTATION_PREFIX);
668        let _ = atv.push(OID_MATTER_VID_ARC);
669        let _ = atv.extend_from_slice(&[0x0C, 0x04, b'F', b'F', b'F', b'1']);
670
671        let mut seq = heapless::Vec::<u8, 128>::new();
672        let _ = seq.push(TAG_SEQUENCE);
673        let _ = seq.push(u8::try_from(atv.len()).unwrap_or(0));
674        let _ = seq.extend_from_slice(&atv);
675        let mut rdn = heapless::Vec::<u8, 128>::new();
676        let _ = rdn.push(crate::der::TAG_SET);
677        let _ = rdn.push(u8::try_from(seq.len()).unwrap_or(0));
678        let _ = rdn.extend_from_slice(&seq);
679
680        // Append a second RDN carrying a commonName with an Mpid: substring.
681        let cn = common_name("Matter Test Mpid:8000");
682        let mut name = heapless::Vec::<u8, 256>::new();
683        let _ = name.extend_from_slice(&rdn);
684        let _ = name.extend_from_slice(&cn);
685
686        let parsed = VidPid::from_name(&name).expect("parse");
687        assert_eq!(parsed.vendor_id, Some(VendorId(0xFFF1)));
688        assert_eq!(
689            parsed.product_id, None,
690            "the fallback is skipped for this field"
691        );
692    }
693}