Skip to main content

matter_kit/
fabric.rs

1//! Fabrics: the ecosystems a node belongs to, and the identifiers derived from them
2//! (Core §2.5.1, §4.3.2.2, §4.17.2, §11.18).
3//!
4//! A **fabric** is a set of nodes that trust one certificate authority. A node belongs to
5//! several at once — five at minimum, by [`Config::FABRICS`] — and
6//! almost nothing it does means anything outside the context of one: an access-control
7//! entry, a group key, a subscription and a session are each scoped to a fabric.
8//!
9//! # Four derived values, and why each exists
10//!
11//! A full fabric reference is a 65-octet root public key plus a 64-bit Fabric ID, which is
12//! more than fits in a DNS-SD instance name. So Matter derives shorter things from it:
13//!
14//! | Value | Derived from | What it is for |
15//! |---|---|---|
16//! | [`CompressedFabricId`] | root key + fabric id | 8 octets; names the fabric in `_matter._tcp` |
17//! | [`operational_group_key`] | epoch key + compressed id | the key a group message is encrypted under |
18//! | [`destination_identifier`] | IPK + randoms + identity | tells a CASE responder *which* fabric, without naming it |
19//! | [`FabricIndex`] | nothing — a local counter | one octet; the same fabric has different indices on different nodes |
20//!
21//! The destination identifier is the subtle one. A CASE initiator has to say which fabric
22//! it means without revealing it to a passive observer, because "this device is on the
23//! Acme fabric" is exactly what a fabric would rather not broadcast. So it sends an HMAC
24//! under a key only fabric members hold, and the responder tries each of its own fabrics
25//! until one matches — or none does, and it answers `NO_SHARED_TRUST_ROOTS`.
26//!
27//! # Endianness, twice, differently
28//!
29//! The compressed fabric identifier salts with the Fabric ID **big-endian** and strips the
30//! public key's `0x04` prefix. The destination identifier uses the Fabric ID and Node ID
31//! **little-endian** and keeps the `0x04`. Both are quoted from the specification below.
32//! Getting either backwards produces a value that simply never matches, with no other
33//! symptom — which is why each has a test against the specification's own worked example.
34
35use core::marker::PhantomData;
36
37use heapless::{String, Vec};
38
39use crate::config::{AssertValid, Config};
40use crate::crypto::{
41    HASH_LEN_BYTES, KeyHandle, PUBLIC_KEY_SIZE_BYTES, PublicKey, SymmetricKey, ct_eq, hmac, kdf,
42    kdf_key,
43};
44use crate::error::{Error, ErrorCode, Result, bail};
45use crate::msg::{FabricId, FabricIndex, NodeId, VendorId};
46
47/// `CompressedFabricInfo` — the ASCII of `"CompressedFabric"` (§4.3.2.2).
48pub const COMPRESSED_FABRIC_INFO: &[u8] = b"CompressedFabric";
49
50/// The `Info` of the operational group key derivation (§4.17.2.1).
51pub const GROUP_KEY_INFO: &[u8] = b"GroupKey v1.0";
52
53/// The length of the `initiatorRandom` a destination identifier is computed over
54/// (§4.14.2.4.1).
55pub const INITIATOR_RANDOM_LEN: usize = 32;
56
57/// The longest `Label` a fabric entry carries — §11.18.4.5's `max 32`.
58pub const FABRIC_LABEL_MAX: usize = 32;
59
60/// The longest operational certificate the specification admits — §11.18.4.4's `max 400`,
61/// for `NOC`, `ICAC` and `VVSC` alike, and §11.18.6.13's `RootCACertificate`.
62///
63/// Fixed rather than a [`Config`] knob: a commissioner may legitimately send anything up to
64/// this, so a device that reserved less would refuse certificates it is required to accept.
65/// What it costs is real — three of these per fabric — and that is why [`Credentials`] holds
66/// the ICAC and the VVSC as `Option`s and why a node that never needs them still pays for
67/// the slot. Storing them in a [`KvStore`](crate::platform::KvStore) instead is the exchange
68/// a very small device would make; the table would then be a cache rather than the truth.
69pub const OPERATIONAL_CERT_MAX: usize = 400;
70
71/// The length of a `VIDVerificationStatement` — §11.18.4.5's `85`, which §6.4.10.2 fixes as
72/// `statement_version || vid_verification_signer_skid || signature` for the 1.0 cryptographic
73/// primitives.
74pub const VID_VERIFICATION_STATEMENT_LEN: usize = 85;
75
76/// `statement_version` for the 1.0 cryptographic primitives (§6.4.10.1 step 12.a.i.A: "the
77/// known value 0x21").
78pub const VID_VERIFICATION_STATEMENT_VERSION: u8 = 0x21;
79
80/// `fabric_binding_version` for the 1.0 cryptographic primitives (§11.18.6.16: "SHALL contain
81/// value 0x01 for version 1.0").
82pub const FABRIC_BINDING_VERSION: u8 = 0x01;
83
84/// One fabric's operational credential chain, as the `NOCs` and `TrustedRootCertificates`
85/// attributes serve it (§11.18.5.1, §11.18.5.5).
86///
87/// All three are Matter TLV certificates, not X.509 — §11.18.6.8 says "encoded using Matter
88/// Certificate Encoding" — and they are kept verbatim. A re-encoding would be a different
89/// octet string, and §6.5.2's signature rule means a round-tripped certificate is one whose
90/// signature a peer may no longer be able to check.
91#[derive(Debug, Clone, Default)]
92pub struct Credentials {
93    /// `NOC` — the node operational certificate for this fabric.
94    pub noc: Vec<u8, OPERATIONAL_CERT_MAX>,
95    /// `ICAC` — the intermediate, if the chain has one. §11.18.4.4: "If no ICAC is present in
96    /// the chain, this field SHALL be set to null."
97    pub icac: Option<Vec<u8, OPERATIONAL_CERT_MAX>>,
98    /// The trusted root, from `AddTrustedRootCertificate`. Served through
99    /// `TrustedRootCertificates` rather than through `NOCs`: §11.18.4.4 keeps it out of
100    /// `NOCStruct` deliberately, because several fabrics may share one root.
101    pub rcac: Vec<u8, OPERATIONAL_CERT_MAX>,
102    /// `VVSC` — the Vendor Verification Signer Certificate (§11.18.4.4 field 3).
103    ///
104    /// "The VVSC field is mutually exclusive with the ICAC field": it exists for
105    /// root-per-fabric deployments that have no intermediate to carry the signer, and
106    /// [`Credentials::is_valid`] enforces the exclusion.
107    pub vvsc: Option<Vec<u8, OPERATIONAL_CERT_MAX>>,
108}
109
110impl Credentials {
111    /// A chain with a NOC and a root, and no intermediate.
112    pub fn new(noc: &[u8], rcac: &[u8]) -> Result<Self> {
113        Ok(Self {
114            noc: copy_cert(noc)?,
115            icac: None,
116            rcac: copy_cert(rcac)?,
117            vvsc: None,
118        })
119    }
120
121    /// The same chain with an intermediate.
122    pub fn with_icac(mut self, icac: &[u8]) -> Result<Self> {
123        self.icac = Some(copy_cert(icac)?);
124        Ok(self)
125    }
126
127    /// Sets or erases the `VVSC` — `SetVIDVerificationStatement` (§11.18.6.14).
128    ///
129    /// "If the length of the field's value is exactly 0, then the VVSC field … SHALL be
130    /// erased and the field SHALL disappear from the NOCs entry."
131    pub fn set_vvsc(&mut self, vvsc: &[u8]) -> Result<()> {
132        if vvsc.is_empty() {
133            self.vvsc = None;
134            return Ok(());
135        }
136        if self.icac.is_some() {
137            // §11.18.6.14: "If the VVSC field is present, but the ICAC field is already
138            // present … the command SHALL fail with a status code of INVALID_COMMAND."
139            bail!(InvalidArgument)
140        }
141        self.vvsc = Some(copy_cert(vvsc)?);
142        Ok(())
143    }
144
145    /// Whether §11.18.4.4's mutual exclusion holds.
146    #[must_use]
147    pub fn is_valid(&self) -> bool {
148        !self.noc.is_empty()
149            && !self.rcac.is_empty()
150            && !(self.icac.is_some() && self.vvsc.is_some())
151    }
152}
153
154fn copy_cert(bytes: &[u8]) -> Result<Vec<u8, OPERATIONAL_CERT_MAX>> {
155    Vec::from_slice(bytes).map_err(|_| Error::new(ErrorCode::NoSpace))
156}
157
158/// A compressed fabric reference: 64 bits standing in for a root key and a Fabric ID
159/// (§4.3.2.2).
160#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
161pub struct CompressedFabricId(pub u64);
162
163impl CompressedFabricId {
164    /// The big-endian octets, which is the order the KDF produces and DNS-SD prints.
165    #[must_use]
166    pub const fn to_bytes(self) -> [u8; 8] {
167        self.0.to_be_bytes()
168    }
169
170    /// The sixteen uppercase hex characters a `_matter._tcp` instance name starts with
171    /// (§4.3.2.1).
172    #[must_use]
173    pub fn to_hex(self) -> String<16> {
174        let mut out = String::new();
175        push_hex(&mut out, &self.to_bytes());
176        out
177    }
178
179    /// The `_I<hhhh>` DNS-SD subtype that lets a browse be filtered to one fabric
180    /// (§4.3.2.3).
181    #[must_use]
182    pub fn subtype(self) -> String<18> {
183        let mut out = String::new();
184        let _ = out.push_str("_I");
185        let _ = out.push_str(&self.to_hex());
186        out
187    }
188}
189
190/// Appends the uppercase hex of `bytes`. Silently truncates if the string is too small,
191/// which cannot happen for the two callers here — both are exactly sized.
192fn push_hex<const N: usize>(out: &mut String<N>, bytes: &[u8]) {
193    const DIGITS: &[u8; 16] = b"0123456789ABCDEF";
194    for byte in bytes {
195        for nibble in [byte >> 4, byte & 0x0F] {
196            let digit = DIGITS.get(usize::from(nibble)).copied().unwrap_or(b'?');
197            let _ = out.push(char::from(digit));
198        }
199    }
200}
201
202/// Computes the Compressed Fabric Identifier (§4.3.2.2).
203///
204/// Two details are easy to get wrong, and produce a node nobody can find:
205///
206/// * the root public key goes in **without its format marker** — "after removing the first
207///   byte of the ec-pub-key field in the Operational Certificate's root";
208/// * the Fabric ID is the salt, "a 64-bit unsigned integer scalar in **big-endian** byte
209///   order", unlike most scalars in the protocol.
210pub fn compressed_fabric_id(
211    root_public_key: &PublicKey,
212    fabric_id: FabricId,
213) -> Result<CompressedFabricId> {
214    let Some(raw) = root_public_key.as_bytes().get(1..) else {
215        bail!(InvalidArgument)
216    };
217    let mut out = [0u8; 8];
218    kdf(
219        raw,
220        &fabric_id.0.to_be_bytes(),
221        COMPRESSED_FABRIC_INFO,
222        &mut out,
223    )?;
224    Ok(CompressedFabricId(u64::from_be_bytes(out)))
225}
226
227/// Derives an operational group key from an epoch key (§4.17.2).
228///
229/// "Group membership is enforced by limiting access to the epoch keys. Only Nodes that
230/// possess the input epoch key can derive a given operational key."
231///
232/// The Identity Protection Key is the group key of key set 0, so this is also how the IPK
233/// that CASE and the destination identifier need comes about.
234pub fn operational_group_key(
235    epoch_key: &SymmetricKey,
236    compressed: CompressedFabricId,
237) -> Result<SymmetricKey> {
238    kdf_key(epoch_key.as_bytes(), &compressed.to_bytes(), GROUP_KEY_INFO)
239}
240
241/// Computes a CASE destination identifier (§4.14.2.4.1).
242///
243/// `destinationMessage = initiatorRandom || rootPublicKey || fabricId || nodeId`, HMACed
244/// under the IPK. Here the root public key keeps its `0x04` marker — "as an uncompressed
245/// elliptic curve point as defined in section 2.3.3 of SEC 1" — and both 64-bit scalars are
246/// little-endian. Both differ from [`compressed_fabric_id`]; see the module documentation.
247pub fn destination_identifier(
248    ipk: &SymmetricKey,
249    initiator_random: &[u8; INITIATOR_RANDOM_LEN],
250    root_public_key: &PublicKey,
251    fabric_id: FabricId,
252    node_id: NodeId,
253) -> Result<[u8; HASH_LEN_BYTES]> {
254    const LEN: usize = INITIATOR_RANDOM_LEN + PUBLIC_KEY_SIZE_BYTES + 8 + 8;
255    let mut message = [0u8; LEN];
256    {
257        let mut at = 0usize;
258        let mut put = |src: &[u8]| -> Result<()> {
259            let end = at
260                .checked_add(src.len())
261                .ok_or_else(|| Error::new(ErrorCode::BufferTooSmall))?;
262            let Some(slot) = message.get_mut(at..end) else {
263                bail!(BufferTooSmall)
264            };
265            slot.copy_from_slice(src);
266            at = end;
267            Ok(())
268        };
269        put(initiator_random)?;
270        put(root_public_key.as_bytes())?;
271        put(&fabric_id.0.to_le_bytes())?;
272        put(&node_id.0.to_le_bytes())?;
273    }
274    hmac(ipk.as_bytes(), &message)
275}
276
277/// The longest `vendor_id_verification_tbs` this crate builds (§6.4.10.1 step 9).
278///
279/// `1 + 32 + 16 + 1` for the version, challenges and fabric index, `1 + 65 + 8 + 2` for the
280/// `vendor_fabric_binding_message`, and 85 for an optional statement.
281pub const VENDOR_ID_VERIFICATION_TBS_MAX: usize = 1
282    + 32
283    + crate::crypto::SYMMETRIC_KEY_LENGTH_BYTES
284    + 1
285    + (1 + PUBLIC_KEY_SIZE_BYTES + 8 + 2)
286    + VID_VERIFICATION_STATEMENT_LEN;
287
288/// `vendor_fabric_binding_message` (§6.4.10.1 step 8).
289///
290/// > For a fabric_binding_version version of 0x01, generate vendor_fabric_binding_message :=
291/// > fabric_binding_version (0x01) || root_public_key || fabric_id || vendor_id
292///
293/// Both identifiers are big-endian "without omitting leading zeroes" — the opposite of the
294/// destination identifier's little-endian encoding a few lines above, and the third
295/// endianness convention in this one module. Each is the specification's.
296pub fn vendor_fabric_binding_message(
297    root_public_key: &PublicKey,
298    fabric_id: FabricId,
299    vendor_id: VendorId,
300) -> [u8; 1 + PUBLIC_KEY_SIZE_BYTES + 8 + 2] {
301    let mut out = [0u8; 1 + PUBLIC_KEY_SIZE_BYTES + 8 + 2];
302    let mut at = 0usize;
303    let mut put = |bytes: &[u8]| {
304        if let Some(slot) = out.get_mut(at..at.saturating_add(bytes.len())) {
305            slot.copy_from_slice(bytes);
306        }
307        at = at.saturating_add(bytes.len());
308    };
309    put(&[FABRIC_BINDING_VERSION]);
310    put(root_public_key.as_bytes());
311    put(&fabric_id.0.to_be_bytes());
312    put(&vendor_id.0.to_be_bytes());
313    out
314}
315
316/// What the verification signature binds a fabric to (§6.4.10.1 step 8).
317///
318/// A view of four fields of one `Fabrics` entry, so a *verifier* — which has only the
319/// attribute values it read, not a [`Fabric`] — can build the same message the signer did.
320#[derive(Debug, Clone, Copy)]
321pub struct VendorIdBinding<'a> {
322    /// The `RootPublicKey` field.
323    pub root_public_key: &'a PublicKey,
324    /// The `FabricID` field.
325    pub fabric_id: FabricId,
326    /// The `VendorID` field — the value under verification.
327    pub vendor_id: VendorId,
328    /// The `VIDVerificationStatement` field, "if it was present".
329    pub statement: Option<&'a [u8; VID_VERIFICATION_STATEMENT_LEN]>,
330}
331
332/// `vendor_id_verification_tbs` (§6.4.10.1 step 9, §11.18.6.16).
333///
334/// > vendor_id_verification_tbs := fabric_binding_version || client_challenge ||
335/// > attestation_challenge || fabric_index || vendor_fabric_binding_message ||
336/// > &lt;vid_verification_statement&gt;
337///
338/// The `attestation_challenge` is what makes the signature mean something: it is the third
339/// key a session derives and "SHALL NOT be included in any of the payloads conveyed", so a
340/// response proves the signer is on *this* session rather than replaying one recorded from
341/// another. `vid_verification_statement` is appended only "if present" — an absent one is
342/// omitted, not zero-filled, which is a different message and therefore a different
343/// signature.
344///
345/// Writes into `out` and returns the filled prefix, so nothing is allocated and the caller
346/// controls where the challenge material lives.
347pub fn vendor_id_verification_tbs<'b>(
348    out: &'b mut [u8; VENDOR_ID_VERIFICATION_TBS_MAX],
349    challenges: (&[u8; 32], &SymmetricKey),
350    fabric_index: FabricIndex,
351    binding: &VendorIdBinding<'_>,
352) -> &'b [u8] {
353    let (client_challenge, attestation_challenge) = challenges;
354    let bound = vendor_fabric_binding_message(
355        binding.root_public_key,
356        binding.fabric_id,
357        binding.vendor_id,
358    );
359    let mut at = 0usize;
360    {
361        let mut put = |bytes: &[u8]| {
362            if let Some(slot) = out.get_mut(at..at.saturating_add(bytes.len())) {
363                slot.copy_from_slice(bytes);
364            }
365            at = at.saturating_add(bytes.len());
366        };
367        put(&[FABRIC_BINDING_VERSION]);
368        put(client_challenge);
369        put(attestation_challenge.as_bytes());
370        put(&[fabric_index.0]);
371        put(&bound);
372        if let Some(statement) = binding.statement {
373            put(statement);
374        }
375    }
376    out.get(..at).unwrap_or(&[])
377}
378
379/// Who a node is on one fabric — the part of a `Fabrics` entry that comes from the NOC and
380/// from `AddNOC`, as opposed to the parts derived from it.
381///
382/// A struct rather than four parameters because the four travel together everywhere: they
383/// come out of one certificate chain and one `AddNOC` invocation, and splitting them at a
384/// call site is how a Fabric ID ends up where a Node ID belongs.
385#[derive(Debug, Clone)]
386pub struct FabricIdentity {
387    /// The 64-bit identifier, from the NOC's `matter-fabric-id`.
388    pub fabric_id: FabricId,
389    /// This node's operational identity on the fabric, from the NOC's `matter-node-id`.
390    pub node_id: NodeId,
391    /// The root certificate authority's public key, uncompressed and 65 octets.
392    pub root_public_key: PublicKey,
393    /// The `AdminVendorID` of the administrator that commissioned this fabric.
394    pub admin_vendor_id: VendorId,
395}
396
397/// One fabric a node belongs to — the state behind §11.18's `Fabrics` attribute, plus the
398/// two derived values that attribute does not carry.
399#[derive(Debug, Clone)]
400pub struct Fabric {
401    /// This node's index for the fabric. Purely local: "the Local Fabric Index and Peer
402    /// Fabric Index … MAY differ in value, while still referring to the same Fabric."
403    pub index: FabricIndex,
404    /// The 64-bit identifier, from the NOC's `matter-fabric-id`.
405    pub fabric_id: FabricId,
406    /// This node's operational identity on the fabric, from the NOC's `matter-node-id`.
407    pub node_id: NodeId,
408    /// The root certificate authority's public key, uncompressed and 65 octets.
409    pub root_public_key: PublicKey,
410    /// The eight-octet name the fabric goes by in DNS-SD. Derived, not stored on the wire.
411    pub compressed: CompressedFabricId,
412    /// The Identity Protection Key — the operational group key of key set 0. Derived from
413    /// the `IPKValue` of `AddNOC`, which is *not* itself retained.
414    pub ipk: SymmetricKey,
415    /// The `AdminVendorID` of the administrator that commissioned this fabric. §11.18.4.5
416    /// warns clients to "consider the VendorID field value to be untrustworthy" until the
417    /// verification procedure has run against it.
418    pub admin_vendor_id: VendorId,
419    /// The user-visible label, `""` until `UpdateFabricLabel` sets one.
420    pub label: String<FABRIC_LABEL_MAX>,
421    /// A handle to this node's operational private key, held by the
422    /// [`KeyStore`](crate::crypto::KeyStore) — never the key itself.
423    pub operational_key: KeyHandle,
424    /// The certificate chain, as `NOCs` and `TrustedRootCertificates` serve it.
425    pub credentials: Credentials,
426    /// `VIDVerificationStatement` (§11.18.4.5 field 6), set by
427    /// `SetVIDVerificationStatement`. Absent until an administrator installs one, and then
428    /// exactly [`VID_VERIFICATION_STATEMENT_LEN`] octets.
429    pub vid_verification_statement: Option<[u8; VID_VERIFICATION_STATEMENT_LEN]>,
430}
431
432impl Fabric {
433    /// Builds a fabric entry, deriving the compressed identifier and the IPK.
434    ///
435    /// `ipk_epoch_key` is the value that arrives in `AddNOC`'s `IPKValue` field. What is
436    /// kept is the *operational* key derived from it, because that is what every later
437    /// computation uses and the epoch key has no further purpose here.
438    pub fn new(
439        index: FabricIndex,
440        identity: FabricIdentity,
441        ipk_epoch_key: &SymmetricKey,
442        operational_key: KeyHandle,
443        credentials: Credentials,
444    ) -> Result<Self> {
445        let FabricIdentity {
446            fabric_id,
447            node_id,
448            root_public_key,
449            admin_vendor_id,
450        } = identity;
451        if !index.is_some() {
452            // 0 means "no fabric" and 0xFF is reserved (§7.5).
453            bail!(InvalidArgument)
454        }
455        if fabric_id.0 == 0 {
456            // §6.5.6.3: "The matter-fabric-id … SHALL NOT be 0".
457            bail!(InvalidArgument)
458        }
459        if !node_id.is_operational() {
460            // §6.5.6.3: a NOC's node id is in the Operational Node ID range.
461            bail!(InvalidArgument)
462        }
463        if !credentials.is_valid() {
464            // §11.18.4.4's mutual exclusion, and a chain with no NOC or no root is not a
465            // chain: `NOCs` and `Fabrics` must have matching entries (§11.18.5.1).
466            bail!(InvalidArgument)
467        }
468        let compressed = compressed_fabric_id(&root_public_key, fabric_id)?;
469        let ipk = operational_group_key(ipk_epoch_key, compressed)?;
470        Ok(Self {
471            index,
472            fabric_id,
473            node_id,
474            root_public_key,
475            compressed,
476            ipk,
477            admin_vendor_id,
478            label: String::new(),
479            operational_key,
480            credentials,
481            vid_verification_statement: None,
482        })
483    }
484
485    /// Sets the user-visible label — `UpdateFabricLabel` (§11.18.6.9).
486    ///
487    /// Returns [`ErrorCode::InvalidArgument`] for a label longer than
488    /// [`FABRIC_LABEL_MAX`], which is the `CONSTRAINT_ERROR` that command answers with.
489    pub fn set_label(&mut self, label: &str) -> Result<()> {
490        let mut next = String::new();
491        next.push_str(label)
492            .map_err(|_| Error::new(ErrorCode::InvalidArgument))?;
493        self.label = next;
494        Ok(())
495    }
496
497    /// The DNS-SD operational instance name: `<CompressedFabricId>-<NodeId>`, each sixteen
498    /// uppercase hex characters (§4.3.2.1).
499    #[must_use]
500    pub fn instance_name(&self) -> String<33> {
501        let mut out = String::new();
502        let _ = out.push_str(&self.compressed.to_hex());
503        let _ = out.push('-');
504        push_hex(&mut out, &self.node_id.0.to_be_bytes());
505        out
506    }
507
508    /// The four fields `vendor_fabric_binding_message` binds (§6.4.10.1 step 8).
509    #[must_use]
510    pub fn vendor_id_binding(&self) -> VendorIdBinding<'_> {
511        VendorIdBinding {
512            root_public_key: &self.root_public_key,
513            fabric_id: self.fabric_id,
514            vendor_id: self.admin_vendor_id,
515            statement: self.vid_verification_statement.as_ref(),
516        }
517    }
518
519    /// The message `SignVIDVerificationRequest` signs with this fabric's operational key
520    /// (§11.18.6.16).
521    ///
522    /// The signature is made with the *operational* key, not the attestation key: the
523    /// procedure proves that whoever holds this fabric's NOC agrees to the `VendorID` it
524    /// claims, which is a statement about the fabric rather than about the hardware.
525    pub fn vendor_id_verification_tbs<'b>(
526        &self,
527        out: &'b mut [u8; VENDOR_ID_VERIFICATION_TBS_MAX],
528        client_challenge: &[u8; 32],
529        attestation_challenge: &SymmetricKey,
530    ) -> &'b [u8] {
531        vendor_id_verification_tbs(
532            out,
533            (client_challenge, attestation_challenge),
534            self.index,
535            &self.vendor_id_binding(),
536        )
537    }
538
539    /// The destination identifier a peer computes to reach *this* node on *this* fabric —
540    /// §4.14.2.3.5's `candidateDestinationId`.
541    pub fn destination_identifier(
542        &self,
543        initiator_random: &[u8; INITIATOR_RANDOM_LEN],
544    ) -> Result<[u8; HASH_LEN_BYTES]> {
545        destination_identifier(
546            &self.ipk,
547            initiator_random,
548            &self.root_public_key,
549            self.fabric_id,
550            self.node_id,
551        )
552    }
553}
554
555/// The fixed-capacity set of fabrics a node belongs to (§11.18).
556#[derive(Debug)]
557pub struct FabricTable<C: Config, const N: usize> {
558    fabrics: Vec<Fabric, N>,
559    /// The last index handed out, so the next one is monotonically greater (§11.18.6.8).
560    last_index: u8,
561    _config: PhantomData<C>,
562}
563
564impl<C: Config, const N: usize> Default for FabricTable<C, N> {
565    fn default() -> Self {
566        Self::new()
567    }
568}
569
570impl<C: Config, const N: usize> FabricTable<C, N> {
571    /// An empty table — what a factory-fresh node has.
572    #[must_use]
573    pub fn new() -> Self {
574        let () = AssertValid::<C>::CHECK;
575        Self {
576            fabrics: Vec::new(),
577            last_index: 0,
578            _config: PhantomData,
579        }
580    }
581
582    /// How many fabrics this node belongs to — the `CommissionedFabrics` attribute.
583    #[must_use]
584    pub fn len(&self) -> usize {
585        self.fabrics.len()
586    }
587
588    /// Whether the node is uncommissioned.
589    ///
590    /// This is what decides whether a device advertises itself as commissionable: an
591    /// uncommissioned node always does, a commissioned one only while a window is open.
592    #[must_use]
593    pub fn is_empty(&self) -> bool {
594        self.fabrics.is_empty()
595    }
596
597    /// The `SupportedFabrics` attribute. §11.18.5.3 constrains it to `5 to 254`, which
598    /// [`AssertValid`] checks at compile time against [`Config::FABRICS`].
599    #[must_use]
600    pub const fn capacity(&self) -> usize {
601        N
602    }
603
604    /// Allocates the next fabric index, `1..=254`.
605    ///
606    /// §11.18.6.8 step 1: "taking the next valid fabric-index value in **monotonically
607    /// incrementing order**, wrapping around from 254 (0xFE) to 1, since value 0 is reserved
608    /// and using 255 (0xFF) would prevent cluster specifications from using nullable
609    /// fabric-idx fields."
610    ///
611    /// Monotonic, *not* lowest-free, and the difference matters. A fabric index is what every
612    /// fabric-scoped thing on the node is keyed by — access-control entries, group keys,
613    /// bindings, subscriptions — and administrators cache it. Handing index 1 straight back
614    /// out after a `RemoveFabric` would silently point a stale reference at a different
615    /// administrator's fabric.
616    ///
617    /// Returns [`ErrorCode::NoSpace`] when every index is taken — unreachable while
618    /// `N <= 254`, but a table is not the place to assume that.
619    pub fn allocate_index(&mut self) -> Result<FabricIndex> {
620        let mut candidate = self.last_index;
621        for _ in 0..254u16 {
622            candidate = if candidate >= 254 {
623                1
624            } else {
625                candidate.saturating_add(1)
626            };
627            let index = FabricIndex(candidate);
628            if self.find(index).is_none() {
629                self.last_index = candidate;
630                return Ok(index);
631            }
632        }
633        Err(Error::new(ErrorCode::NoSpace))
634    }
635
636    /// Adds a fabric.
637    ///
638    /// Refuses a duplicate — the same compressed identifier *and* the same node id —
639    /// because §11.18's `AddNOC` answers `FabricConflict` there rather than creating a
640    /// second entry that peers cannot tell apart from the first.
641    pub fn insert(&mut self, fabric: Fabric) -> Result<FabricIndex> {
642        if self.find(fabric.index).is_some() {
643            bail!(InvalidState)
644        }
645        if self
646            .fabrics
647            .iter()
648            .any(|f| f.compressed == fabric.compressed && f.node_id == fabric.node_id)
649        {
650            bail!(AlreadyExists)
651        }
652        let index = fabric.index;
653        self.fabrics
654            .push(fabric)
655            .map_err(|_| Error::new(ErrorCode::NoSpace))?;
656        Ok(index)
657    }
658
659    /// The fabric with this index.
660    #[must_use]
661    pub fn find(&self, index: FabricIndex) -> Option<&Fabric> {
662        self.fabrics.iter().find(|f| f.index == index)
663    }
664
665    /// The fabric with this index, mutably — for `UpdateNOC` and `UpdateFabricLabel`.
666    pub fn find_mut(&mut self, index: FabricIndex) -> Option<&mut Fabric> {
667        self.fabrics.iter_mut().find(|f| f.index == index)
668    }
669
670    /// The fabric a compressed identifier names, which is how a DNS-SD record is attributed.
671    #[must_use]
672    pub fn find_by_compressed(&self, compressed: CompressedFabricId) -> Option<&Fabric> {
673        self.fabrics.iter().find(|f| f.compressed == compressed)
674    }
675
676    /// Finds the fabric a CASE `destinationId` refers to (§4.14.2.3.5).
677    ///
678    /// "The responder SHALL traverse all its installed Node Operational Certificates …
679    /// and SHALL generate a candidateDestinationId … The responder SHALL verify that the
680    /// incoming destinationId matches one of the candidateDestinationId generated above."
681    ///
682    /// Every fabric is tried and the comparison is constant-time, so neither the number of
683    /// iterations nor their duration tells an unauthenticated peer how close its guess was.
684    pub fn find_by_destination_identifier(
685        &self,
686        initiator_random: &[u8; INITIATOR_RANDOM_LEN],
687        destination_id: &[u8; HASH_LEN_BYTES],
688    ) -> Result<Option<&Fabric>> {
689        let mut found = None;
690        for fabric in &self.fabrics {
691            let candidate = fabric.destination_identifier(initiator_random)?;
692            if ct_eq(&candidate, destination_id) {
693                found = Some(fabric);
694            }
695        }
696        Ok(found)
697    }
698
699    /// Removes a fabric — `RemoveFabric` (§11.18.6.12).
700    ///
701    /// The caller must also tear down everything scoped to it: sessions, subscriptions,
702    /// access-control entries, group keys and bindings. The removed fabric is returned so
703    /// that its key handle can be destroyed in the key store — the step most easily
704    /// forgotten, and the one that matters most.
705    pub fn remove(&mut self, index: FabricIndex) -> Option<Fabric> {
706        let position = self.fabrics.iter().position(|f| f.index == index)?;
707        Some(self.fabrics.swap_remove(position))
708    }
709
710    /// Every fabric, in no particular order.
711    pub fn iter(&self) -> impl Iterator<Item = &Fabric> {
712        self.fabrics.iter()
713    }
714}
715
716/// The `IPKValue` an `AddNOC` command carries: a 16-octet group epoch key, from which the
717/// fabric's real IPK is derived.
718pub type IpkEpochKey = SymmetricKey;
719
720#[cfg(test)]
721mod tests {
722    use hex_literal::hex;
723
724    use super::*;
725    use crate::DefaultConfig;
726
727    /// The root public key of the specification's worked examples, uncompressed with its
728    /// `04` marker (§4.3.2.2, §4.14.2.4.1).
729    const ROOT_PUBLIC_KEY: [u8; 65] = hex!(
730        "044a9f42b1ca4840d37292bbc7f6a7e11e22200c976fc900dbc98a7a383a641c"
731        "b8254a2e56d4e295a847943b4e3897c4a773e930277b4d9fbede8a052686bfac"
732        "fa"
733    );
734
735    /// The Fabric ID of those examples.
736    const FABRIC: FabricId = FabricId(0x2906_C908_D115_D362);
737
738    /// The IPK epoch key of the §4.14.2.4.1 example.
739    const IPK_EPOCH: [u8; 16] = hex!("4a71cdd7b2a3ca9024f96f3c96a19dee");
740
741    fn root_key() -> PublicKey {
742        PublicKey::from_bytes(ROOT_PUBLIC_KEY)
743    }
744
745    #[test]
746    fn the_compressed_fabric_id_matches_the_specs_worked_example() {
747        // §4.3.2.2: "the CompressedFabricIdentifier to use in advertising would be
748        // 87E1B004E235A130".
749        let compressed = compressed_fabric_id(&root_key(), FABRIC).expect("derive");
750        assert_eq!(compressed.to_bytes(), hex!("87e1b004e235a130"));
751        assert_eq!(compressed.to_hex().as_str(), "87E1B004E235A130");
752        // §4.3.2.3's browse subtype.
753        assert_eq!(compressed.subtype().as_str(), "_I87E1B004E235A130");
754    }
755
756    #[test]
757    fn the_operational_group_key_matches_the_specs_worked_example() {
758        // §4.17.2: epoch key 235bf7e6…, compressed 87e1b004e235a130.
759        let epoch = SymmetricKey::new(hex!("235bf7e62823d358dca4ba50b1535f4b"));
760        let key =
761            operational_group_key(&epoch, CompressedFabricId(0x87E1_B004_E235_A130)).expect("kdf");
762        assert_eq!(key.as_bytes(), &hex!("a6f5306baf6d050af23ba4bd6b9dd960"));
763    }
764
765    #[test]
766    fn the_ipk_matches_the_specs_worked_example() {
767        // §4.14.2.4.1: the same derivation, applied to the IPK epoch key.
768        let compressed = compressed_fabric_id(&root_key(), FABRIC).expect("derive");
769        let ipk = operational_group_key(&SymmetricKey::new(IPK_EPOCH), compressed).expect("kdf");
770        assert_eq!(ipk.as_bytes(), &hex!("9bc61cd9c62a2df6d64dfcaa9dc472d4"));
771    }
772
773    #[test]
774    fn the_destination_identifier_matches_the_specs_worked_example() {
775        // §4.14.2.4.1, the whole chain: epoch key → IPK → HMAC over the destination
776        // message. This is the test that pins both endiannesses and the 04 marker.
777        let compressed = compressed_fabric_id(&root_key(), FABRIC).expect("derive");
778        let ipk = operational_group_key(&SymmetricKey::new(IPK_EPOCH), compressed).expect("kdf");
779
780        let initiator_random =
781            hex!("7e171231568dfa17206b3accf8faec2f4d21b580113196f47c7c4deb810a73dc");
782        let id = destination_identifier(
783            &ipk,
784            &initiator_random,
785            &root_key(),
786            FABRIC,
787            NodeId(0xCD55_44AA_7B13_EF14),
788        )
789        .expect("hmac");
790
791        assert_eq!(
792            id,
793            hex!("dc35dd5fc9134cc5544538c9c3fc4297c1ec3370c839136a80e10796451d4c53")
794        );
795    }
796
797    /// A minimal chain: the contents are opaque here, only their presence matters.
798    fn example_credentials() -> Credentials {
799        Credentials::new(b"noc", b"rcac").expect("fits")
800    }
801
802    fn example_fabric(index: u8, node: u64) -> Fabric {
803        Fabric::new(
804            FabricIndex(index),
805            FabricIdentity {
806                fabric_id: FABRIC,
807                node_id: NodeId(node),
808                root_public_key: root_key(),
809                admin_vendor_id: VendorId(0xFFF1),
810            },
811            &SymmetricKey::new(IPK_EPOCH),
812            KeyHandle(u32::from(index)),
813            example_credentials(),
814        )
815        .expect("fabric")
816    }
817
818    #[test]
819    fn a_fabric_derives_both_values_on_construction() {
820        let fabric = example_fabric(1, 0xCD55_44AA_7B13_EF14);
821        assert_eq!(fabric.compressed, CompressedFabricId(0x87E1_B004_E235_A130));
822        assert_eq!(
823            fabric.ipk.as_bytes(),
824            &hex!("9bc61cd9c62a2df6d64dfcaa9dc472d4")
825        );
826        assert_eq!(fabric.label.as_str(), "", "§11.18.4.5's fallback");
827    }
828
829    #[test]
830    fn the_instance_name_is_the_dns_sd_form() {
831        // §4.3.2.1's own example: compressed 2906C908D115D362 and node 8FC7772401CD0696
832        // give 2906C908D115D362-8FC7772401CD0696.
833        let mut fabric = example_fabric(1, 0x8FC7_7724_01CD_0696);
834        fabric.compressed = CompressedFabricId(0x2906_C908_D115_D362);
835        assert_eq!(
836            fabric.instance_name().as_str(),
837            "2906C908D115D362-8FC7772401CD0696"
838        );
839    }
840
841    #[test]
842    fn a_fabric_refuses_the_identities_6_5_6_3_forbids() {
843        let key = SymmetricKey::new([0; 16]);
844        let cases = [
845            ("fabric id 0", FabricIndex(1), FabricId(0), NodeId(1)),
846            (
847                "a group node id, not an operational one",
848                FabricIndex(1),
849                FabricId(1),
850                NodeId(0xFFFF_FFFF_FFFF_0001),
851            ),
852            (
853                "fabric index 0 means no fabric",
854                FabricIndex(0),
855                FabricId(1),
856                NodeId(1),
857            ),
858        ];
859        for (why, index, fabric_id, node_id) in cases {
860            let built = Fabric::new(
861                index,
862                FabricIdentity {
863                    fabric_id,
864                    node_id,
865                    root_public_key: root_key(),
866                    admin_vendor_id: VendorId(1),
867                },
868                &key,
869                KeyHandle(1),
870                example_credentials(),
871            );
872            assert_eq!(
873                built.map(|_| ()).unwrap_err().code(),
874                ErrorCode::InvalidArgument,
875                "{why}"
876            );
877        }
878    }
879
880    #[test]
881    fn a_label_longer_than_32_is_a_constraint_error() {
882        let mut fabric = example_fabric(1, 1);
883        fabric.set_label("Living room").expect("fits");
884        assert_eq!(fabric.label.as_str(), "Living room");
885        assert_eq!(
886            fabric.set_label(&"x".repeat(33)).unwrap_err().code(),
887            ErrorCode::InvalidArgument
888        );
889        assert_eq!(fabric.label.as_str(), "Living room", "and nothing changed");
890        fabric.set_label(&"x".repeat(32)).expect("exactly 32 fits");
891    }
892
893    type Table = FabricTable<DefaultConfig, 5>;
894
895    #[test]
896    fn indices_are_allocated_from_one_and_never_zero() {
897        let mut t = Table::new();
898        assert!(t.is_empty());
899        assert_eq!(t.allocate_index().expect("a"), FabricIndex(1));
900        t.insert(example_fabric(1, 1)).expect("insert");
901        assert_eq!(t.allocate_index().expect("b"), FabricIndex(2));
902        t.insert(example_fabric(2, 2)).expect("insert");
903
904        // §11.18.6.8 step 1 allocates "in monotonically incrementing order", so removing a
905        // fabric does *not* hand its index straight back out. An administrator's cached
906        // reference to fabric 1 must not silently come to mean somebody else's fabric.
907        t.remove(FabricIndex(1)).expect("removed");
908        assert_eq!(t.allocate_index().expect("c"), FabricIndex(3));
909    }
910
911    #[test]
912    fn fabric_indices_wrap_from_254_to_1_and_skip_what_is_in_use() {
913        // "wrapping around from 254 (0xFE) to 1, since value 0 is reserved and using 255
914        // (0xFF) would prevent cluster specifications from using nullable fabric-idx fields."
915        let mut t = Table::new();
916        t.insert(example_fabric(1, 1)).expect("insert");
917        for _ in 0..253 {
918            let index = t.allocate_index().expect("space");
919            assert_ne!(index, FabricIndex(0));
920            assert_ne!(index, FabricIndex(0xFF));
921        }
922        // Having walked all the way round, the next free index is the one *after* the
923        // occupied 1 — the counter wrapped and stepped over it.
924        assert_eq!(t.allocate_index().expect("wrapped"), FabricIndex(2));
925    }
926
927    #[test]
928    fn a_duplicate_fabric_is_refused() {
929        // Same root key, same fabric id, same node id: §11.18's FabricConflict.
930        let mut t = Table::new();
931        t.insert(example_fabric(1, 7)).expect("first");
932        assert_eq!(
933            t.insert(example_fabric(2, 7)).unwrap_err().code(),
934            ErrorCode::AlreadyExists
935        );
936        // A different node id on the same fabric is a different identity, and is fine.
937        t.insert(example_fabric(2, 8)).expect("different node");
938        assert_eq!(t.len(), 2);
939        // A reused index is a caller bug, and a different error.
940        assert_eq!(
941            t.insert(example_fabric(2, 9)).unwrap_err().code(),
942            ErrorCode::InvalidState
943        );
944    }
945
946    #[test]
947    fn a_full_table_is_a_value_not_an_abort() {
948        let mut t = Table::new();
949        for i in 1..=5u8 {
950            t.insert(example_fabric(i, u64::from(i))).expect("fits");
951        }
952        assert_eq!(
953            t.insert(example_fabric(6, 6)).unwrap_err().code(),
954            ErrorCode::NoSpace
955        );
956        assert_eq!(t.capacity(), 5);
957    }
958
959    #[test]
960    fn a_destination_identifier_finds_its_fabric_and_only_its_fabric() {
961        let mut t = Table::new();
962        for i in 1..=3u8 {
963            t.insert(example_fabric(i, u64::from(i))).expect("insert");
964        }
965        let random = [0x42u8; INITIATOR_RANDOM_LEN];
966
967        for i in 1..=3u8 {
968            let id = t
969                .find(FabricIndex(i))
970                .expect("fabric")
971                .destination_identifier(&random)
972                .expect("id");
973            let found = t
974                .find_by_destination_identifier(&random, &id)
975                .expect("search")
976                .expect("a match");
977            assert_eq!(found.index, FabricIndex(i));
978        }
979
980        // An identifier for a fabric this node is not on matches nothing — which is what
981        // makes the responder answer NO_SHARED_TRUST_ROOTS.
982        assert!(
983            t.find_by_destination_identifier(&random, &[0u8; HASH_LEN_BYTES])
984                .expect("search")
985                .is_none()
986        );
987    }
988
989    #[test]
990    fn a_different_initiator_random_gives_a_different_identifier() {
991        // The random is what stops a destination identifier being a stable, trackable name
992        // for a fabric — §4.14.2.4.1's "It hides which Fabric was chosen by the initiator".
993        let fabric = example_fabric(1, 1);
994        assert_ne!(
995            fabric.destination_identifier(&[1; 32]).expect("a"),
996            fabric.destination_identifier(&[2; 32]).expect("b")
997        );
998    }
999
1000    #[test]
1001    fn removing_a_fabric_hands_back_its_key_handle() {
1002        // So the caller can destroy the operational key, which RemoveFabric must do.
1003        let mut t = Table::new();
1004        t.insert(example_fabric(1, 1)).expect("insert");
1005        let removed = t.remove(FabricIndex(1)).expect("removed");
1006        assert_eq!(removed.operational_key, KeyHandle(1));
1007        assert!(t.is_empty());
1008        assert!(t.remove(FabricIndex(1)).is_none());
1009    }
1010
1011    #[test]
1012    fn different_roots_and_different_fabric_ids_compress_differently() {
1013        // The compressed id is what distinguishes fabrics in DNS-SD, so two ecosystems
1014        // colliding here would be indistinguishable on the network.
1015        let mut other = ROOT_PUBLIC_KEY;
1016        other[1] ^= 0xFF;
1017        let a = compressed_fabric_id(&root_key(), FabricId(1)).expect("a");
1018        let b = compressed_fabric_id(&PublicKey::from_bytes(other), FabricId(1)).expect("b");
1019        let c = compressed_fabric_id(&root_key(), FabricId(2)).expect("c");
1020        assert_ne!(a, b);
1021        assert_ne!(a, c);
1022    }
1023
1024    #[test]
1025    fn find_by_compressed_picks_the_right_fabric() {
1026        let mut t = Table::new();
1027        t.insert(example_fabric(1, 1)).expect("insert");
1028        let found = t
1029            .find_by_compressed(CompressedFabricId(0x87E1_B004_E235_A130))
1030            .expect("found");
1031        assert_eq!(found.index, FabricIndex(1));
1032        assert!(t.find_by_compressed(CompressedFabricId(0)).is_none());
1033    }
1034}