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 = 5> {
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> crate::config::Capacity for FabricTable<C, N> {
571    const TOTAL: usize = N;
572    /// A fabric table has no per-fabric share: one slot *is* one fabric.
573    const PER_FABRIC: usize = 1;
574}
575
576impl<C: Config, const N: usize> FabricTable<C, N> {
577    /// Compile-time proof that this table can hold the fabrics the node advertises.
578    ///
579    /// `SupportedFabrics` (§11.18.5.3) is answered from this table's real capacity, so a table
580    /// smaller than [`Config::FABRICS`] would quietly make the node
581    /// support fewer ecosystems than every other number it derives from that constant assumes.
582    pub const CHECK: () = {
583        let () = AssertValid::<C>::CHECK;
584        assert!(
585            N >= C::FABRICS,
586            "FabricTable: the table must hold Config::FABRICS fabrics — \
587             raise the table's N, or lower Config::FABRICS"
588        );
589        assert!(
590            N <= 254,
591            "FabricTable: Core §11.18.5.3 constrains SupportedFabrics to 5..=254"
592        );
593    };
594
595    /// An empty table — what a factory-fresh node has.
596    #[must_use]
597    pub fn new() -> Self {
598        let () = Self::CHECK;
599        Self {
600            fabrics: Vec::new(),
601            last_index: 0,
602            _config: PhantomData,
603        }
604    }
605
606    /// How many fabrics this node belongs to — the `CommissionedFabrics` attribute.
607    #[must_use]
608    pub fn len(&self) -> usize {
609        self.fabrics.len()
610    }
611
612    /// Whether the node is uncommissioned.
613    ///
614    /// This is what decides whether a device advertises itself as commissionable: an
615    /// uncommissioned node always does, a commissioned one only while a window is open.
616    #[must_use]
617    pub fn is_empty(&self) -> bool {
618        self.fabrics.is_empty()
619    }
620
621    /// The `SupportedFabrics` attribute. §11.18.5.3 constrains it to `5 to 254`, which
622    /// [`AssertValid`] checks at compile time against [`Config::FABRICS`].
623    #[must_use]
624    pub const fn capacity(&self) -> usize {
625        N
626    }
627
628    /// Allocates the next fabric index, `1..=254`.
629    ///
630    /// §11.18.6.8 step 1: "taking the next valid fabric-index value in **monotonically
631    /// incrementing order**, wrapping around from 254 (0xFE) to 1, since value 0 is reserved
632    /// and using 255 (0xFF) would prevent cluster specifications from using nullable
633    /// fabric-idx fields."
634    ///
635    /// Monotonic, *not* lowest-free, and the difference matters. A fabric index is what every
636    /// fabric-scoped thing on the node is keyed by — access-control entries, group keys,
637    /// bindings, subscriptions — and administrators cache it. Handing index 1 straight back
638    /// out after a `RemoveFabric` would silently point a stale reference at a different
639    /// administrator's fabric.
640    ///
641    /// Returns [`ErrorCode::NoSpace`] when every index is taken — unreachable while
642    /// `N <= 254`, but a table is not the place to assume that.
643    pub fn allocate_index(&mut self) -> Result<FabricIndex> {
644        let mut candidate = self.last_index;
645        for _ in 0..254u16 {
646            candidate = if candidate >= 254 {
647                1
648            } else {
649                candidate.saturating_add(1)
650            };
651            let index = FabricIndex(candidate);
652            if self.find(index).is_none() {
653                self.last_index = candidate;
654                return Ok(index);
655            }
656        }
657        Err(Error::new(ErrorCode::NoSpace))
658    }
659
660    /// Adds a fabric.
661    ///
662    /// Refuses a duplicate — the same compressed identifier *and* the same node id —
663    /// because §11.18's `AddNOC` answers `FabricConflict` there rather than creating a
664    /// second entry that peers cannot tell apart from the first.
665    pub fn insert(&mut self, fabric: Fabric) -> Result<FabricIndex> {
666        if self.find(fabric.index).is_some() {
667            bail!(InvalidState)
668        }
669        if self
670            .fabrics
671            .iter()
672            .any(|f| f.compressed == fabric.compressed && f.node_id == fabric.node_id)
673        {
674            bail!(AlreadyExists)
675        }
676        let index = fabric.index;
677        self.fabrics
678            .push(fabric)
679            .map_err(|_| Error::new(ErrorCode::NoSpace))?;
680        Ok(index)
681    }
682
683    /// The fabric with this index.
684    #[must_use]
685    pub fn find(&self, index: FabricIndex) -> Option<&Fabric> {
686        self.fabrics.iter().find(|f| f.index == index)
687    }
688
689    /// The fabric with this index, mutably — for `UpdateNOC` and `UpdateFabricLabel`.
690    pub fn find_mut(&mut self, index: FabricIndex) -> Option<&mut Fabric> {
691        self.fabrics.iter_mut().find(|f| f.index == index)
692    }
693
694    /// The fabric a compressed identifier names, which is how a DNS-SD record is attributed.
695    #[must_use]
696    pub fn find_by_compressed(&self, compressed: CompressedFabricId) -> Option<&Fabric> {
697        self.fabrics.iter().find(|f| f.compressed == compressed)
698    }
699
700    /// Finds the fabric a CASE `destinationId` refers to (§4.14.2.3.5).
701    ///
702    /// "The responder SHALL traverse all its installed Node Operational Certificates …
703    /// and SHALL generate a candidateDestinationId … The responder SHALL verify that the
704    /// incoming destinationId matches one of the candidateDestinationId generated above."
705    ///
706    /// Every fabric is tried and the comparison is constant-time, so neither the number of
707    /// iterations nor their duration tells an unauthenticated peer how close its guess was.
708    pub fn find_by_destination_identifier(
709        &self,
710        initiator_random: &[u8; INITIATOR_RANDOM_LEN],
711        destination_id: &[u8; HASH_LEN_BYTES],
712    ) -> Result<Option<&Fabric>> {
713        let mut found = None;
714        for fabric in &self.fabrics {
715            let candidate = fabric.destination_identifier(initiator_random)?;
716            if ct_eq(&candidate, destination_id) {
717                found = Some(fabric);
718            }
719        }
720        Ok(found)
721    }
722
723    /// Removes a fabric — `RemoveFabric` (§11.18.6.12).
724    ///
725    /// The caller must also tear down everything scoped to it: sessions, subscriptions,
726    /// access-control entries, group keys and bindings. The removed fabric is returned so
727    /// that its key handle can be destroyed in the key store — the step most easily
728    /// forgotten, and the one that matters most.
729    pub fn remove(&mut self, index: FabricIndex) -> Option<Fabric> {
730        let position = self.fabrics.iter().position(|f| f.index == index)?;
731        Some(self.fabrics.swap_remove(position))
732    }
733
734    /// Every fabric, in no particular order.
735    pub fn iter(&self) -> impl Iterator<Item = &Fabric> {
736        self.fabrics.iter()
737    }
738}
739
740/// The `IPKValue` an `AddNOC` command carries: a 16-octet group epoch key, from which the
741/// fabric's real IPK is derived.
742pub type IpkEpochKey = SymmetricKey;
743
744#[cfg(test)]
745mod tests {
746    use hex_literal::hex;
747
748    use super::*;
749    use crate::DefaultConfig;
750
751    /// The root public key of the specification's worked examples, uncompressed with its
752    /// `04` marker (§4.3.2.2, §4.14.2.4.1).
753    const ROOT_PUBLIC_KEY: [u8; 65] = hex!(
754        "044a9f42b1ca4840d37292bbc7f6a7e11e22200c976fc900dbc98a7a383a641c"
755        "b8254a2e56d4e295a847943b4e3897c4a773e930277b4d9fbede8a052686bfac"
756        "fa"
757    );
758
759    /// The Fabric ID of those examples.
760    const FABRIC: FabricId = FabricId(0x2906_C908_D115_D362);
761
762    /// The IPK epoch key of the §4.14.2.4.1 example.
763    const IPK_EPOCH: [u8; 16] = hex!("4a71cdd7b2a3ca9024f96f3c96a19dee");
764
765    fn root_key() -> PublicKey {
766        PublicKey::from_bytes(ROOT_PUBLIC_KEY)
767    }
768
769    #[test]
770    fn the_compressed_fabric_id_matches_the_specs_worked_example() {
771        // §4.3.2.2: "the CompressedFabricIdentifier to use in advertising would be
772        // 87E1B004E235A130".
773        let compressed = compressed_fabric_id(&root_key(), FABRIC).expect("derive");
774        assert_eq!(compressed.to_bytes(), hex!("87e1b004e235a130"));
775        assert_eq!(compressed.to_hex().as_str(), "87E1B004E235A130");
776        // §4.3.2.3's browse subtype.
777        assert_eq!(compressed.subtype().as_str(), "_I87E1B004E235A130");
778    }
779
780    #[test]
781    fn the_operational_group_key_matches_the_specs_worked_example() {
782        // §4.17.2: epoch key 235bf7e6…, compressed 87e1b004e235a130.
783        let epoch = SymmetricKey::new(hex!("235bf7e62823d358dca4ba50b1535f4b"));
784        let key =
785            operational_group_key(&epoch, CompressedFabricId(0x87E1_B004_E235_A130)).expect("kdf");
786        assert_eq!(key.as_bytes(), &hex!("a6f5306baf6d050af23ba4bd6b9dd960"));
787    }
788
789    #[test]
790    fn the_ipk_matches_the_specs_worked_example() {
791        // §4.14.2.4.1: the same derivation, applied to the IPK epoch key.
792        let compressed = compressed_fabric_id(&root_key(), FABRIC).expect("derive");
793        let ipk = operational_group_key(&SymmetricKey::new(IPK_EPOCH), compressed).expect("kdf");
794        assert_eq!(ipk.as_bytes(), &hex!("9bc61cd9c62a2df6d64dfcaa9dc472d4"));
795    }
796
797    #[test]
798    fn the_destination_identifier_matches_the_specs_worked_example() {
799        // §4.14.2.4.1, the whole chain: epoch key → IPK → HMAC over the destination
800        // message. This is the test that pins both endiannesses and the 04 marker.
801        let compressed = compressed_fabric_id(&root_key(), FABRIC).expect("derive");
802        let ipk = operational_group_key(&SymmetricKey::new(IPK_EPOCH), compressed).expect("kdf");
803
804        let initiator_random =
805            hex!("7e171231568dfa17206b3accf8faec2f4d21b580113196f47c7c4deb810a73dc");
806        let id = destination_identifier(
807            &ipk,
808            &initiator_random,
809            &root_key(),
810            FABRIC,
811            NodeId(0xCD55_44AA_7B13_EF14),
812        )
813        .expect("hmac");
814
815        assert_eq!(
816            id,
817            hex!("dc35dd5fc9134cc5544538c9c3fc4297c1ec3370c839136a80e10796451d4c53")
818        );
819    }
820
821    /// A minimal chain: the contents are opaque here, only their presence matters.
822    fn example_credentials() -> Credentials {
823        Credentials::new(b"noc", b"rcac").expect("fits")
824    }
825
826    fn example_fabric(index: u8, node: u64) -> Fabric {
827        Fabric::new(
828            FabricIndex(index),
829            FabricIdentity {
830                fabric_id: FABRIC,
831                node_id: NodeId(node),
832                root_public_key: root_key(),
833                admin_vendor_id: VendorId(0xFFF1),
834            },
835            &SymmetricKey::new(IPK_EPOCH),
836            KeyHandle(u32::from(index)),
837            example_credentials(),
838        )
839        .expect("fabric")
840    }
841
842    #[test]
843    fn a_fabric_derives_both_values_on_construction() {
844        let fabric = example_fabric(1, 0xCD55_44AA_7B13_EF14);
845        assert_eq!(fabric.compressed, CompressedFabricId(0x87E1_B004_E235_A130));
846        assert_eq!(
847            fabric.ipk.as_bytes(),
848            &hex!("9bc61cd9c62a2df6d64dfcaa9dc472d4")
849        );
850        assert_eq!(fabric.label.as_str(), "", "§11.18.4.5's fallback");
851    }
852
853    #[test]
854    fn the_instance_name_is_the_dns_sd_form() {
855        // §4.3.2.1's own example: compressed 2906C908D115D362 and node 8FC7772401CD0696
856        // give 2906C908D115D362-8FC7772401CD0696.
857        let mut fabric = example_fabric(1, 0x8FC7_7724_01CD_0696);
858        fabric.compressed = CompressedFabricId(0x2906_C908_D115_D362);
859        assert_eq!(
860            fabric.instance_name().as_str(),
861            "2906C908D115D362-8FC7772401CD0696"
862        );
863    }
864
865    #[test]
866    fn a_fabric_refuses_the_identities_6_5_6_3_forbids() {
867        let key = SymmetricKey::new([0; 16]);
868        let cases = [
869            ("fabric id 0", FabricIndex(1), FabricId(0), NodeId(1)),
870            (
871                "a group node id, not an operational one",
872                FabricIndex(1),
873                FabricId(1),
874                NodeId(0xFFFF_FFFF_FFFF_0001),
875            ),
876            (
877                "fabric index 0 means no fabric",
878                FabricIndex(0),
879                FabricId(1),
880                NodeId(1),
881            ),
882        ];
883        for (why, index, fabric_id, node_id) in cases {
884            let built = Fabric::new(
885                index,
886                FabricIdentity {
887                    fabric_id,
888                    node_id,
889                    root_public_key: root_key(),
890                    admin_vendor_id: VendorId(1),
891                },
892                &key,
893                KeyHandle(1),
894                example_credentials(),
895            );
896            assert_eq!(
897                built.map(|_| ()).unwrap_err().code(),
898                ErrorCode::InvalidArgument,
899                "{why}"
900            );
901        }
902    }
903
904    #[test]
905    fn a_label_longer_than_32_is_a_constraint_error() {
906        let mut fabric = example_fabric(1, 1);
907        fabric.set_label("Living room").expect("fits");
908        assert_eq!(fabric.label.as_str(), "Living room");
909        assert_eq!(
910            fabric.set_label(&"x".repeat(33)).unwrap_err().code(),
911            ErrorCode::InvalidArgument
912        );
913        assert_eq!(fabric.label.as_str(), "Living room", "and nothing changed");
914        fabric.set_label(&"x".repeat(32)).expect("exactly 32 fits");
915    }
916
917    type Table = FabricTable<DefaultConfig, 5>;
918
919    #[test]
920    fn indices_are_allocated_from_one_and_never_zero() {
921        let mut t = Table::new();
922        assert!(t.is_empty());
923        assert_eq!(t.allocate_index().expect("a"), FabricIndex(1));
924        t.insert(example_fabric(1, 1)).expect("insert");
925        assert_eq!(t.allocate_index().expect("b"), FabricIndex(2));
926        t.insert(example_fabric(2, 2)).expect("insert");
927
928        // §11.18.6.8 step 1 allocates "in monotonically incrementing order", so removing a
929        // fabric does *not* hand its index straight back out. An administrator's cached
930        // reference to fabric 1 must not silently come to mean somebody else's fabric.
931        t.remove(FabricIndex(1)).expect("removed");
932        assert_eq!(t.allocate_index().expect("c"), FabricIndex(3));
933    }
934
935    #[test]
936    fn fabric_indices_wrap_from_254_to_1_and_skip_what_is_in_use() {
937        // "wrapping around from 254 (0xFE) to 1, since value 0 is reserved and using 255
938        // (0xFF) would prevent cluster specifications from using nullable fabric-idx fields."
939        let mut t = Table::new();
940        t.insert(example_fabric(1, 1)).expect("insert");
941        for _ in 0..253 {
942            let index = t.allocate_index().expect("space");
943            assert_ne!(index, FabricIndex(0));
944            assert_ne!(index, FabricIndex(0xFF));
945        }
946        // Having walked all the way round, the next free index is the one *after* the
947        // occupied 1 — the counter wrapped and stepped over it.
948        assert_eq!(t.allocate_index().expect("wrapped"), FabricIndex(2));
949    }
950
951    #[test]
952    fn a_duplicate_fabric_is_refused() {
953        // Same root key, same fabric id, same node id: §11.18's FabricConflict.
954        let mut t = Table::new();
955        t.insert(example_fabric(1, 7)).expect("first");
956        assert_eq!(
957            t.insert(example_fabric(2, 7)).unwrap_err().code(),
958            ErrorCode::AlreadyExists
959        );
960        // A different node id on the same fabric is a different identity, and is fine.
961        t.insert(example_fabric(2, 8)).expect("different node");
962        assert_eq!(t.len(), 2);
963        // A reused index is a caller bug, and a different error.
964        assert_eq!(
965            t.insert(example_fabric(2, 9)).unwrap_err().code(),
966            ErrorCode::InvalidState
967        );
968    }
969
970    #[test]
971    fn a_full_table_is_a_value_not_an_abort() {
972        let mut t = Table::new();
973        for i in 1..=5u8 {
974            t.insert(example_fabric(i, u64::from(i))).expect("fits");
975        }
976        assert_eq!(
977            t.insert(example_fabric(6, 6)).unwrap_err().code(),
978            ErrorCode::NoSpace
979        );
980        assert_eq!(t.capacity(), 5);
981    }
982
983    #[test]
984    fn a_destination_identifier_finds_its_fabric_and_only_its_fabric() {
985        let mut t = Table::new();
986        for i in 1..=3u8 {
987            t.insert(example_fabric(i, u64::from(i))).expect("insert");
988        }
989        let random = [0x42u8; INITIATOR_RANDOM_LEN];
990
991        for i in 1..=3u8 {
992            let id = t
993                .find(FabricIndex(i))
994                .expect("fabric")
995                .destination_identifier(&random)
996                .expect("id");
997            let found = t
998                .find_by_destination_identifier(&random, &id)
999                .expect("search")
1000                .expect("a match");
1001            assert_eq!(found.index, FabricIndex(i));
1002        }
1003
1004        // An identifier for a fabric this node is not on matches nothing — which is what
1005        // makes the responder answer NO_SHARED_TRUST_ROOTS.
1006        assert!(
1007            t.find_by_destination_identifier(&random, &[0u8; HASH_LEN_BYTES])
1008                .expect("search")
1009                .is_none()
1010        );
1011    }
1012
1013    #[test]
1014    fn a_different_initiator_random_gives_a_different_identifier() {
1015        // The random is what stops a destination identifier being a stable, trackable name
1016        // for a fabric — §4.14.2.4.1's "It hides which Fabric was chosen by the initiator".
1017        let fabric = example_fabric(1, 1);
1018        assert_ne!(
1019            fabric.destination_identifier(&[1; 32]).expect("a"),
1020            fabric.destination_identifier(&[2; 32]).expect("b")
1021        );
1022    }
1023
1024    #[test]
1025    fn removing_a_fabric_hands_back_its_key_handle() {
1026        // So the caller can destroy the operational key, which RemoveFabric must do.
1027        let mut t = Table::new();
1028        t.insert(example_fabric(1, 1)).expect("insert");
1029        let removed = t.remove(FabricIndex(1)).expect("removed");
1030        assert_eq!(removed.operational_key, KeyHandle(1));
1031        assert!(t.is_empty());
1032        assert!(t.remove(FabricIndex(1)).is_none());
1033    }
1034
1035    #[test]
1036    fn different_roots_and_different_fabric_ids_compress_differently() {
1037        // The compressed id is what distinguishes fabrics in DNS-SD, so two ecosystems
1038        // colliding here would be indistinguishable on the network.
1039        let mut other = ROOT_PUBLIC_KEY;
1040        other[1] ^= 0xFF;
1041        let a = compressed_fabric_id(&root_key(), FabricId(1)).expect("a");
1042        let b = compressed_fabric_id(&PublicKey::from_bytes(other), FabricId(1)).expect("b");
1043        let c = compressed_fabric_id(&root_key(), FabricId(2)).expect("c");
1044        assert_ne!(a, b);
1045        assert_ne!(a, c);
1046    }
1047
1048    #[test]
1049    fn find_by_compressed_picks_the_right_fabric() {
1050        let mut t = Table::new();
1051        t.insert(example_fabric(1, 1)).expect("insert");
1052        let found = t
1053            .find_by_compressed(CompressedFabricId(0x87E1_B004_E235_A130))
1054            .expect("found");
1055        assert_eq!(found.index, FabricIndex(1));
1056        assert!(t.find_by_compressed(CompressedFabricId(0)).is_none());
1057    }
1058}