Skip to main content

matter_kit/clusters/
operational_credentials.rs

1//! Operational Credentials cluster `0x003E` (Core §11.18) — joining and leaving fabrics.
2//!
3//! > This cluster is used to add or remove Node Operational credentials on a Commissionee or
4//! > already-configured Node, as well as manage the associated Fabrics.
5//!
6//! It is the cluster commissioning exists to reach. Everything before it — discovery, PASE,
7//! the fail-safe, the regulatory configuration — is setup; this is where a device acquires an
8//! identity it did not have.
9//!
10//! # The order is not a suggestion
11//!
12//! A commissioner must issue, inside one fail-safe period:
13//!
14//! 1. `AttestationRequest` — prove the device is a certified product (§6.2).
15//! 2. `CertificateChainRequest` ×2 — fetch the DAC and PAI to check that proof against.
16//! 3. `CSRRequest` — have the device generate an operational key it has never had before.
17//! 4. `AddTrustedRootCertificate` — install the fabric's root.
18//! 5. `AddNOC` — install the certificate the commissioner minted from the CSR.
19//!
20//! §11.18.6.8 makes each step's precondition explicit, and each one refuses rather than
21//! improvises: no fail-safe is `FAILSAFE_REQUIRED`, a second `AddNOC` in one period is
22//! `CONSTRAINT_ERROR`, a missing CSR is `MissingCsr`, a missing root is `InvalidNOC`. The
23//! last is worth reading twice — "**AddNOC always requires that the client provides the root
24//! of trust certificate within the same Fail-Safe context** as the rest of the new fabric's
25//! operational credentials, **even if some other fabric already uses the exact same root**".
26//! A device that reused an installed root would let an administrator graft a new fabric onto
27//! a root it never presented.
28//!
29//! # Two secrets that never move
30//!
31//! The operational private key is generated by the device and leaves only as a public key in
32//! a CSR; it lives in the [`KeyStore`](crate::crypto::KeyStore) as a handle. The `AttestationChallenge` is the
33//! third key the session derived and "SHALL NOT be included in any of the payloads conveyed"
34//! — it is what makes an `AttestationResponse` unreplayable, because a signature over it
35//! proves the signer was on *this* session.
36//!
37//! # What this cluster does not own
38//!
39//! §11.18.6.8's effect on receipt reaches well past the fabric table: step 6 re-advertises
40//! the node over DNS-SD, step 7 adds an Access Control entry for `CaseAdminSubject`, step 10
41//! binds the accessing PASE session to the new fabric. None of those belong to a cluster, so
42//! `AddNOC` reports a `FabricChange` and the device applies it — the same arrangement as
43//! the fail-safe's [`Cleanup`](crate::commissioning::failsafe::Cleanup), and for the same
44//! reason: the work is outside a cluster's reach, so the cluster reports it rather than
45//! reaching for it.
46//!
47//! # Revision 2
48//!
49//! | Revision | Change |
50//! |---|---|
51//! | 1 | Initial revision |
52//! | 2 | The Fabric Table Vendor ID Verification Procedure (§6.4.10) |
53
54use core::cell::{Cell, RefCell};
55
56use crate::attestation::{self, AttestationElements};
57use crate::cert::MatterCertificate;
58use crate::config::Config;
59use crate::crypto::{KeyHandle, KeyStore, PublicKey, SymmetricKey};
60use crate::dm::access::{Access, AccessQualities, Privilege};
61use crate::dm::meta::{
62    AttributeDescriptor, AttributeQualities, ClusterDescriptor, CommandDescriptor, Reporting,
63};
64use crate::dm::{Resolved, ResolvedCommand};
65use crate::fabric::{
66    Credentials, Fabric, FabricIdentity, FabricTable, OPERATIONAL_CERT_MAX,
67    VENDOR_ID_VERIFICATION_TBS_MAX, VID_VERIFICATION_STATEMENT_LEN,
68};
69use crate::im::{
70    AttributeId, ClusterHandler, ClusterId, CommandId, InteractionContext, Status, StatusIb,
71};
72use crate::msg::{FabricIndex, NodeId, SessionId, VendorId};
73use crate::platform::Rng;
74use crate::tlv::{ContainerKind, Tag, TlvReader, TlvWriter, set_once};
75
76use super::Cluster;
77
78/// `0x003E` (§11.18.3).
79pub const ID: ClusterId = 0x003E;
80
81/// The highest revision in §11.18.1's table.
82pub const REVISION: u16 = 2;
83
84/// The largest `NOCs` value a node with `fabrics` fabrics can produce, in octets.
85///
86/// A read builds one whole attribute value in a scratch buffer before the server decides
87/// whether it fits a message or has to be split across several (§10.6.4.3.1) — so the scratch
88/// is sized by the largest *value* a node can produce, which is not the largest *message* it
89/// can send. Those are different numbers, and a value larger than a message is precisely the
90/// case list chunking exists for.
91///
92/// This is the largest of them for most nodes: a non-fabric-filtered `NOCs` read carries every
93/// fabric's NOC and ICAC, each capped at [`OPERATIONAL_CERT_MAX`] by §6.1.3, plus the
94/// `NOCStruct` and array framing. Five fabrics is over four kilobytes — more than three times
95/// a datagram — which a node that sized its scratch by "the biggest constant I had" discovers
96/// as `ResourceExhausted` from its own cluster, with nothing on the wire to explain it.
97#[must_use]
98pub const fn max_nocs_len(fabrics: usize) -> usize {
99    // Per entry: two certificates, their octet-string headers, the `FabricIndex` and the
100    // structure's own control and end-of-container octets. Sixteen is generous for the
101    // framing and keeps the arithmetic obvious.
102    let per_fabric = OPERATIONAL_CERT_MAX.saturating_mul(2).saturating_add(16);
103    // Plus the array's own control octet and end-of-container.
104    per_fabric.saturating_mul(fabrics).saturating_add(8)
105}
106
107/// `RESP_MAX` (§11.18.4.1) — "SHALL be 900 bytes".
108///
109/// "chosen to accommodate the maximum size of IPv6 frames, transport headers, message layer
110/// headers and integrity protection and Interaction Model protocol encoding, while
111/// accounting for sufficient remaining space for signatures".
112pub const RESP_MAX: usize = 900;
113
114/// `NOCs` (§11.18.5.1) — `list[NOCStruct]`, `CN`, `RAF`, mandatory.
115pub const NOCS: AttributeId = 0x0000;
116/// `Fabrics` (§11.18.5.2) — `list[FabricDescriptorStruct]`, `N`, `RVF`, mandatory.
117pub const FABRICS: AttributeId = 0x0001;
118/// `SupportedFabrics` (§11.18.5.3) — `uint8` `5 to 254`, `F`, `RV`, mandatory.
119pub const SUPPORTED_FABRICS: AttributeId = 0x0002;
120/// `CommissionedFabrics` (§11.18.5.4) — `uint8`, `N`, `RV`, mandatory.
121pub const COMMISSIONED_FABRICS: AttributeId = 0x0003;
122/// `TrustedRootCertificates` (§11.18.5.5) — `list[octstr]`, `CN`, `RV`, mandatory.
123pub const TRUSTED_ROOT_CERTIFICATES: AttributeId = 0x0004;
124/// `CurrentFabricIndex` (§11.18.5.6) — `uint8`, `RV`, mandatory.
125pub const CURRENT_FABRIC_INDEX: AttributeId = 0x0005;
126
127/// `AttestationRequest` (§11.18.6.1) — access `A`.
128pub const ATTESTATION_REQUEST: CommandId = 0x00;
129/// `AttestationResponse` (§11.18.6.2).
130pub const ATTESTATION_RESPONSE: CommandId = 0x01;
131/// `CertificateChainRequest` (§11.18.6.3) — access `A`.
132pub const CERTIFICATE_CHAIN_REQUEST: CommandId = 0x02;
133/// `CertificateChainResponse` (§11.18.6.4).
134pub const CERTIFICATE_CHAIN_RESPONSE: CommandId = 0x03;
135/// `CSRRequest` (§11.18.6.5) — access `A`.
136pub const CSR_REQUEST: CommandId = 0x04;
137/// `CSRResponse` (§11.18.6.6).
138pub const CSR_RESPONSE: CommandId = 0x05;
139/// `AddNOC` (§11.18.6.8) — access `A`. Not `F`: it runs over PASE, before a fabric exists.
140pub const ADD_NOC: CommandId = 0x06;
141/// `UpdateNOC` (§11.18.6.9) — access `AF`, and CASE only.
142pub const UPDATE_NOC: CommandId = 0x07;
143/// `NOCResponse` (§11.18.6.10).
144pub const NOC_RESPONSE: CommandId = 0x08;
145/// `UpdateFabricLabel` (§11.18.6.11) — access `AF`.
146pub const UPDATE_FABRIC_LABEL: CommandId = 0x09;
147/// `RemoveFabric` (§11.18.6.12) — access `A`: an administrator may remove *another* fabric.
148pub const REMOVE_FABRIC: CommandId = 0x0A;
149/// `AddTrustedRootCertificate` (§11.18.6.13) — access `A`, no response command.
150pub const ADD_TRUSTED_ROOT_CERTIFICATE: CommandId = 0x0B;
151/// `SetVIDVerificationStatement` (§11.18.6.14) — access `AF`, no response command.
152pub const SET_VID_VERIFICATION_STATEMENT: CommandId = 0x0C;
153/// `SignVIDVerificationRequest` (§11.18.6.15) — access `A`.
154pub const SIGN_VID_VERIFICATION_REQUEST: CommandId = 0x0D;
155/// `SignVIDVerificationResponse` (§11.18.6.16).
156pub const SIGN_VID_VERIFICATION_RESPONSE: CommandId = 0x0E;
157
158/// `CertificateChainTypeEnum` (§11.18.4.2).
159#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
160#[repr(u8)]
161pub enum CertificateChainType {
162    /// `1` — "Request the DER-encoded DAC certificate".
163    Dac = 1,
164    /// `2` — "Request the DER-encoded PAI certificate".
165    Pai = 2,
166}
167
168impl CertificateChainType {
169    /// Decodes a wire value. §11.18.6.3: "If the CertificateType is not a valid value per
170    /// CertificateChainTypeEnum then the command SHALL fail with a Status Code of
171    /// INVALID_COMMAND" — note the *status*, not a response command, which is why this
172    /// returns `None` rather than a third variant. Zero is not a value: the enumeration
173    /// starts at one.
174    #[must_use]
175    pub const fn from_value(value: u8) -> Option<Self> {
176        match value {
177            1 => Some(Self::Dac),
178            2 => Some(Self::Pai),
179            _ => None,
180        }
181    }
182}
183
184/// `NodeOperationalCertStatusEnum` (§11.18.4.3).
185///
186/// Values 7 and 8 are absent from the specification's table, so they are absent here: a gap
187/// in an enumeration is information, and filling it in would invent a status.
188#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
189#[repr(u8)]
190#[non_exhaustive]
191pub enum NocStatus {
192    /// `0` — OK, no error.
193    Ok = 0,
194    /// `1` — "Public Key in the NOC does not match the public key in the NOCSR".
195    InvalidPublicKey = 1,
196    /// `2` — "The Node Operational ID in the NOC is not formatted correctly."
197    InvalidNodeOpId = 2,
198    /// `3` — "Any other validation error in NOC chain".
199    InvalidNoc = 3,
200    /// `4` — "No record of prior CSR for which this NOC could match".
201    MissingCsr = 4,
202    /// `5` — "NOCs table full, cannot add another one".
203    TableFull = 5,
204    /// `6` — "Invalid CaseAdminSubject field for an AddNOC command."
205    InvalidAdminSubject = 6,
206    /// `9` — "Trying to AddNOC instead of UpdateNOC against an existing Fabric."
207    FabricConflict = 9,
208    /// `10` — "Label already exists on another Fabric."
209    LabelConflict = 10,
210    /// `11` — "FabricIndex argument is invalid."
211    InvalidFabricIndex = 11,
212}
213
214impl NocStatus {
215    /// The value the enum encodes as.
216    #[must_use]
217    pub const fn value(self) -> u8 {
218        self as u8
219    }
220
221    /// Whether this is [`NocStatus::Ok`].
222    #[must_use]
223    pub const fn is_ok(self) -> bool {
224        matches!(self, Self::Ok)
225    }
226}
227
228/// The device's attestation material — what §6.2's chain and §6.3's declaration are, for
229/// this product.
230///
231/// Borrowed `&'static` in practice: the DAC and PAI are DER in flash, put there at
232/// manufacture, and the Certification Declaration is the CMS blob the CSA signed.
233#[derive(Debug, Clone, Copy)]
234pub struct DeviceAttestation<'a> {
235    /// The Device Attestation Certificate, DER-encoded (§6.2.2).
236    pub dac: &'a [u8],
237    /// The Product Attestation Intermediate, DER-encoded.
238    pub pai: &'a [u8],
239    /// The Certification Declaration — a CMS `SignedData`, DER-encoded (§6.3).
240    pub certification_declaration: &'a [u8],
241    /// A handle to the Device Attestation private key. Never the key.
242    pub dac_key: KeyHandle,
243    /// `firmware_information` (§6.3.2), if the product publishes one.
244    pub firmware_information: Option<&'a [u8]>,
245}
246
247/// What an `AddNOC`, `UpdateNOC` or `RemoveFabric` left for the device to do.
248///
249/// Every variant is work outside a cluster's reach: the session table, the access-control
250/// list, the DNS-SD advertisement. Reporting it keeps §11.18.6.8's eleven-step "Effect on
251/// Receipt" checkable against the specification rather than scattered.
252#[derive(Debug, Clone, Copy, PartialEq, Eq)]
253pub enum FabricChange {
254    /// `AddNOC` succeeded (§11.18.6.8).
255    Added {
256        /// The index allocated for the new fabric.
257        index: FabricIndex,
258        /// Step 7: add an Access Control entry `{Privilege: Administer, AuthMode: CASE,
259        /// Subjects: [this], Targets: []}` scoped to `index`.
260        ///
261        /// [`Acl::add_admin_for_fabric`](crate::acl::Acl::add_admin_for_fabric) builds exactly
262        /// that entry — **do not skip it, and do not hand-build it**. §11.18.6.8: "Unless such
263        /// an Access Control Entry is added atomically as described here, there would be no
264        /// way for the caller on its given Fabric to eventually add another Access Control
265        /// Entry for CASE authentication mode." The failure is silent and total: the fabric is
266        /// joined, the node advertises itself, and the instant the PASE session closes nobody
267        /// can administer it ever again.
268        case_admin_subject: u64,
269        /// Step 10a: whether the command arrived over PASE, in which case the session must be
270        /// "augment … with the FabricIndex generated above, such that subsequent
271        /// interactions have the proper accessing fabric".
272        bind_pase_session: bool,
273    },
274    /// `UpdateNOC` succeeded (§11.18.6.9): re-advertise, and revoke everything tied to the
275    /// previous operational identity — "except for the ongoing CASE session context, which
276    /// SHALL temporarily remain valid until the NOCResponse has been successfully delivered".
277    Updated {
278        /// The fabric whose identity changed.
279        index: FabricIndex,
280    },
281    /// `RemoveFabric` succeeded (§11.18.6.12).
282    Removed {
283        /// The fabric removed.
284        index: FabricIndex,
285        /// Whether it was the last one: "the device SHALL delete all Matter related data on
286        /// the node which was created since it was commissioned" — a factory reset in all but
287        /// name.
288        was_last: bool,
289        /// Whether it was the accessing fabric, in which case the session carrying this very
290        /// response is among the things to be torn down.
291        was_accessing: bool,
292    },
293}
294
295/// A key pair generated by `CSRRequest` and not yet used by a NOC command (§11.18.6.5).
296#[derive(Debug, Clone, Copy)]
297struct PendingCsr {
298    /// The session it was generated on. §11.18.6.7 scopes the record to a session, so one
299    /// administrator's CSR cannot be consumed by another's `AddNOC`.
300    session: Option<SessionId>,
301    key: KeyHandle,
302    public: PublicKey,
303    /// `IsForUpdateNOC`: which of the two commands this key may be used by. Mixing them is
304    /// `CONSTRAINT_ERROR` in both directions (§11.18.6.8, §11.18.6.9).
305    for_update: bool,
306}
307
308const fn fixed(id: AttributeId) -> AttributeDescriptor {
309    AttributeDescriptor::read_only(id).with_qualities(AttributeQualities::FIXED)
310}
311
312/// §11.18.5's attribute table.
313///
314/// `NOCs` is `RAF` — Administer to read, and fabric-scoped; `Fabrics` is `RVF` — View, and
315/// fabric-scoped. The difference is deliberate: a fabric's *existence* and label are public
316/// to anyone with View, and its certificates are not.
317const ATTRIBUTES: &[AttributeDescriptor] = &[
318    // `CN`: changes are omitted from reports as well as persisted. §11.18.5.1's contents
319    // change only through `AddNOC`, `UpdateNOC` and `RemoveFabric` — each of which the client
320    // that cares has just performed — so there is nothing a subscription would tell it.
321    AttributeDescriptor::read_only(NOCS)
322        .with_access(
323            Access::read_only(Privilege::Administer).with_qualities(AccessQualities::FABRIC_SCOPED),
324        )
325        .with_qualities(AttributeQualities::NON_VOLATILE)
326        .with_reporting(Reporting::ChangesOmitted),
327    AttributeDescriptor::read_only(FABRICS)
328        .with_access(
329            Access::read_only(Privilege::View).with_qualities(AccessQualities::FABRIC_SCOPED),
330        )
331        .with_qualities(AttributeQualities::NON_VOLATILE),
332    fixed(SUPPORTED_FABRICS),
333    AttributeDescriptor::read_only(COMMISSIONED_FABRICS)
334        .with_qualities(AttributeQualities::NON_VOLATILE),
335    AttributeDescriptor::read_only(TRUSTED_ROOT_CERTIFICATES)
336        .with_qualities(AttributeQualities::NON_VOLATILE)
337        .with_reporting(Reporting::ChangesOmitted),
338    AttributeDescriptor::read_only(CURRENT_FABRIC_INDEX),
339];
340
341/// §11.18.6's command table.
342///
343/// All are Administer. `UpdateNOC`, `UpdateFabricLabel` and `SetVIDVerificationStatement` add
344/// `F`, so §8.8.2.3 step b.v refuses them over a session with no accessing fabric. `AddNOC`
345/// and `RemoveFabric` deliberately do not: the first runs over PASE before any fabric exists,
346/// and the second may target a fabric other than the caller's.
347const COMMANDS: &[CommandDescriptor] = &[
348    CommandDescriptor::new(ATTESTATION_REQUEST)
349        .with_access(Access::invoke(Privilege::Administer))
350        .with_response(ATTESTATION_RESPONSE),
351    CommandDescriptor::new(CERTIFICATE_CHAIN_REQUEST)
352        .with_access(Access::invoke(Privilege::Administer))
353        .with_response(CERTIFICATE_CHAIN_RESPONSE),
354    CommandDescriptor::new(CSR_REQUEST)
355        .with_access(Access::invoke(Privilege::Administer))
356        .with_response(CSR_RESPONSE),
357    CommandDescriptor::new(ADD_NOC)
358        .with_access(Access::invoke(Privilege::Administer))
359        .with_response(NOC_RESPONSE),
360    CommandDescriptor::new(UPDATE_NOC)
361        .with_access(
362            Access::invoke(Privilege::Administer).with_qualities(AccessQualities::FABRIC_SCOPED),
363        )
364        .with_response(NOC_RESPONSE),
365    CommandDescriptor::new(UPDATE_FABRIC_LABEL)
366        .with_access(
367            Access::invoke(Privilege::Administer).with_qualities(AccessQualities::FABRIC_SCOPED),
368        )
369        .with_response(NOC_RESPONSE),
370    CommandDescriptor::new(REMOVE_FABRIC)
371        .with_access(Access::invoke(Privilege::Administer))
372        .with_response(NOC_RESPONSE),
373    CommandDescriptor::new(ADD_TRUSTED_ROOT_CERTIFICATE)
374        .with_access(Access::invoke(Privilege::Administer)),
375    CommandDescriptor::new(SET_VID_VERIFICATION_STATEMENT).with_access(
376        Access::invoke(Privilege::Administer).with_qualities(AccessQualities::FABRIC_SCOPED),
377    ),
378    CommandDescriptor::new(SIGN_VID_VERIFICATION_REQUEST)
379        .with_access(Access::invoke(Privilege::Administer))
380        .with_response(SIGN_VID_VERIFICATION_RESPONSE),
381];
382
383/// The cluster descriptor.
384#[must_use]
385pub const fn cluster() -> ClusterDescriptor<'static> {
386    ClusterDescriptor {
387        id: ID,
388        revision: REVISION,
389        feature_map: 0,
390        attributes: ATTRIBUTES,
391        accepted_commands: COMMANDS,
392        generated_commands: &[],
393        events: &[],
394    }
395}
396
397/// The Operational Credentials cluster.
398///
399/// Holds nothing itself: the fabric table, the key store and the fail-safe are all node state
400/// this cluster manipulates on the wire's behalf. That is what makes it shareable with CASE
401/// (which needs the same fabric table) and with General Commissioning (which arms the same
402/// fail-safe).
403pub struct OperationalCredentials<'a, C: Config, K: KeyStore, R: Rng, const N: usize> {
404    /// The fabric table — the `Fabrics`, `NOCs` and `TrustedRootCertificates` attributes.
405    pub fabrics: &'a RefCell<FabricTable<C, N>>,
406    /// Key custody. `CSRRequest` generates into it and `RemoveFabric` destroys from it.
407    pub keys: &'a RefCell<K>,
408    /// The node's one source of entropy, for `CSRRequest`'s key generation.
409    ///
410    /// A trait rather than raw bytes, because this is driven by the interaction model rather
411    /// than called directly — and it is still a *parameter*, so a test installs a
412    /// deterministic generator and gets a reproducible key.
413    pub rng: &'a RefCell<R>,
414    /// The fail-safe every credential-changing command runs inside (§11.10.7.2).
415    pub fail_safe: &'a RefCell<crate::commissioning::failsafe::FailSafe>,
416    /// This product's attestation material.
417    pub attestation: DeviceAttestation<'a>,
418    /// The root certificate installed by `AddTrustedRootCertificate` in the current fail-safe
419    /// period, awaiting the `AddNOC` that will adopt it.
420    pending_root: RefCell<Option<heapless::Vec<u8, OPERATIONAL_CERT_MAX>>>,
421    /// The key pair generated by `CSRRequest` in this session, awaiting a NOC command.
422    pending_csr: Cell<Option<PendingCsr>>,
423    /// What the last credential-changing command left for the device.
424    change: Cell<Option<FabricChange>>,
425    /// The identity `UpdateNOC` replaced, held until the fail-safe resolves.
426    ///
427    /// §11.10.7.2.2 step 6: "If an UpdateNOC command had been successfully invoked, revert the
428    /// state of operational key pair, NOC and ICAC for that Fabric to the state prior to the
429    /// Fail-Safe timer being armed". A revert needs the prior key, so the key is held here rather
430    /// than destroyed — and nothing reaches it here: it is not on the fabric, so CASE cannot use
431    /// it, which is what §11.18.6.9 step 1.c's "revoked and removed, to an outcome equivalent to
432    /// the disappearance of the prior Node" asks of it. [`Self::commit_update`] destroys it once
433    /// the update is permanent; [`Self::revert_update`] puts it back. One slot, because a second
434    /// `UpdateNOC` inside one fail-safe is already `CONSTRAINT_ERROR`.
435    replaced: RefCell<Option<Replaced>>,
436}
437
438/// What [`OperationalCredentials`] keeps of an identity `UpdateNOC` replaced.
439#[derive(Debug)]
440struct Replaced {
441    index: FabricIndex,
442    node_id: NodeId,
443    credentials: Credentials,
444    operational_key: KeyHandle,
445}
446
447impl<'a, C: Config, K: KeyStore, R: Rng, const N: usize> OperationalCredentials<'a, C, K, R, N> {
448    /// The cluster over a device's fabric table, key store and fail-safe.
449    #[must_use]
450    pub fn new(
451        fabrics: &'a RefCell<FabricTable<C, N>>,
452        keys: &'a RefCell<K>,
453        rng: &'a RefCell<R>,
454        fail_safe: &'a RefCell<crate::commissioning::failsafe::FailSafe>,
455        attestation: DeviceAttestation<'a>,
456    ) -> Self {
457        Self {
458            fabrics,
459            keys,
460            rng,
461            fail_safe,
462            attestation,
463            pending_root: RefCell::new(None),
464            pending_csr: Cell::new(None),
465            change: Cell::new(None),
466            replaced: RefCell::new(None),
467        }
468    }
469
470    /// Reverts an `UpdateNOC` (§11.10.7.2.2 step 6), restoring the fabric's previous NOC, ICAC,
471    /// node id and operational key, and destroying the key the update installed.
472    ///
473    /// Returns whether there was an update to revert. Idempotent, and a no-op for any other
474    /// fabric — `Cleanup::revert_noc_for` names the one to call it with.
475    pub fn revert_update(&self, index: FabricIndex) -> bool {
476        let Some(replaced) = self.take_replaced(index) else {
477            return false;
478        };
479        let mut table = self.fabrics.borrow_mut();
480        let Some(fabric) = table.find_mut(index) else {
481            // The fabric went in the same rollback; its keys went with it, apart from this one.
482            drop(table);
483            let _ = self.keys.borrow_mut().remove(replaced.operational_key);
484            return false;
485        };
486        let installed = core::mem::replace(&mut fabric.operational_key, replaced.operational_key);
487        fabric.node_id = replaced.node_id;
488        fabric.credentials = replaced.credentials;
489        drop(table);
490        let _ = self.keys.borrow_mut().remove(installed);
491        true
492    }
493
494    /// Makes an `UpdateNOC` permanent, destroying the key it replaced (§11.18.6.9 step 1.c).
495    ///
496    /// What `CommissioningComplete` does for an update (§11.10.7.6); also reached through
497    /// [`Lifecycle::CommissioningComplete`](crate::im::Lifecycle). Idempotent.
498    pub fn commit_update(&self) {
499        if let Some(replaced) = self.replaced.borrow_mut().take() {
500            let _ = self.keys.borrow_mut().remove(replaced.operational_key);
501        }
502    }
503
504    fn take_replaced(&self, index: FabricIndex) -> Option<Replaced> {
505        let mut slot = self.replaced.borrow_mut();
506        if slot.as_ref().is_some_and(|r| r.index == index) {
507            slot.take()
508        } else {
509            None
510        }
511    }
512
513    /// Takes the work the last credential-changing command left behind.
514    ///
515    /// A device calls this after every invoke against this cluster. Forgetting to means a
516    /// fabric is joined with no administrator able to reach it (§11.18.6.8 step 7), or a
517    /// removed fabric's sessions stay open.
518    #[must_use]
519    pub fn take_change(&self) -> Option<FabricChange> {
520        self.change.take()
521    }
522
523    /// Discards any fail-safe-scoped state, destroying the operational key a `CSRRequest`
524    /// generated and nothing used.
525    ///
526    /// Call this when the fail-safe expires — it is §11.10.7.2.2 step 8, "the new operational
527    /// key pair temporarily generated for the purposes of NOC addition or update … SHALL be
528    /// removed as it is no longer needed" — and it is idempotent.
529    pub fn discard_pending(&self) {
530        *self.pending_root.borrow_mut() = None;
531        if let Some(pending) = self.pending_csr.take() {
532            let _ = self.keys.borrow_mut().remove(pending.key);
533        }
534    }
535
536    /// Drops fail-safe-scoped state that belongs to a context which has since ended.
537    ///
538    /// The fail-safe's own [`Progress`](crate::commissioning::failsafe::Progress) is reset
539    /// when a new context is armed, so a `csr_requested` that is no longer set means this
540    /// cluster's pending key belongs to a period that is over. Checking it here is what keeps
541    /// a stale key from being adopted by the *next* commissioner's `AddNOC`.
542    fn reap(&self, now: crate::platform::Instant) {
543        let progress = self
544            .fail_safe
545            .borrow()
546            .armed(now)
547            .map(|armed| armed.progress);
548        let Some(progress) = progress else {
549            self.discard_pending();
550            return;
551        };
552        if !progress.csr_requested
553            && let Some(pending) = self.pending_csr.take()
554        {
555            let _ = self.keys.borrow_mut().remove(pending.key);
556        }
557        if !progress.added_trusted_root {
558            *self.pending_root.borrow_mut() = None;
559        }
560    }
561
562    /// The fail-safe's progress, or `FAILSAFE_REQUIRED` when nothing is armed.
563    ///
564    /// Every credential-changing command starts here: §11.18.6.5, §11.18.6.8, §11.18.6.9 and
565    /// §11.18.6.13 all say "If this command is received without an armed fail-safe context …
566    /// then this command SHALL fail with a FAILSAFE_REQUIRED status code".
567    fn require_fail_safe(
568        &self,
569        now: crate::platform::Instant,
570    ) -> Result<crate::commissioning::failsafe::Progress, Status> {
571        self.fail_safe
572            .borrow()
573            .armed(now)
574            .map(|armed| armed.progress)
575            .ok_or(Status::FailsafeRequired)
576    }
577}
578
579// --- The commands ------------------------------------------------------------------------------
580
581impl<C: Config, K: KeyStore, R: Rng, const N: usize> OperationalCredentials<'_, C, K, R, N> {
582    /// `AttestationRequest` (§11.18.6.1) → `AttestationResponse` (§11.18.6.2).
583    ///
584    /// Writes `AttestationElements [0]` and `AttestationSignature [1]` under `tag`.
585    ///
586    /// The signature is over `attestation_elements_message || attestation_challenge`, and the
587    /// elements are signed **exactly as they will be sent** — not re-encoded. A device whose
588    /// encoder differed from its signer's by one octet would produce a response no
589    /// commissioner could verify, and the failure would look like a bad key.
590    pub fn attestation_response(
591        &self,
592        nonce: &[u8; attestation::ATTESTATION_NONCE_LEN],
593        timestamp: u32,
594        challenge: &SymmetricKey,
595        w: &mut TlvWriter<'_>,
596        tag: Tag,
597    ) -> Result<(), Status> {
598        let elements = AttestationElements {
599            certification_declaration: self.attestation.certification_declaration,
600            attestation_nonce: *nonce,
601            timestamp,
602            firmware_information: self.attestation.firmware_information,
603        };
604        let mut buf = [0u8; RESP_MAX];
605        let encoded = elements.encode(&mut buf).map_err(|_| Status::Failure)?;
606        let signature = attestation::sign_attestation(
607            &*self.keys.borrow(),
608            self.attestation.dac_key,
609            encoded,
610            challenge,
611        )
612        .map_err(|_| Status::Failure)?;
613
614        let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
615        full(w.start_structure(tag))?;
616        full(w.octets(Tag::Context(0), encoded))?;
617        full(w.octets(Tag::Context(1), signature.as_bytes()))?;
618        full(w.end_container())
619    }
620
621    /// `CSRRequest` (§11.18.6.5) → `CSRResponse` (§11.18.6.6).
622    ///
623    /// Generates a fresh operational key pair, builds a PKCS#10 CSR over it, and signs the
624    /// whole `nocsr_elements_message` with the *attestation* key. Two signatures over two
625    /// different things: the CSR's own proves possession of the new operational key, and the
626    /// outer one binds the request to the attested device and the live session.
627    pub fn csr_response(
628        &self,
629        nonce: &[u8; attestation::CSR_NONCE_LEN],
630        for_update: bool,
631        ctx: &InteractionContext<'_>,
632        random: &[u8; 32],
633        w: &mut TlvWriter<'_>,
634        tag: Tag,
635    ) -> Result<(), Status> {
636        let progress = self.require_fail_safe(ctx.now)?;
637        // "If a prior UpdateNOC or AddNOC command was successfully executed within the
638        // fail-safe timer period, then this command SHALL fail with a CONSTRAINT_ERROR."
639        if progress.added_noc || progress.updated_noc {
640            return Err(Status::ConstraintError);
641        }
642        // "If the IsForUpdateNOC field is present and set to true, but the command was
643        // received over a PASE session, the command SHALL fail with an INVALID_COMMAND status
644        // code, as it would never be possible to use a resulting subsequent certificate …
645        // with the UpdateNOC command, which is forbidden over PASE sessions."
646        if for_update && ctx.fabric_index.is_none() {
647            return Err(Status::InvalidCommand);
648        }
649        let challenge = ctx.attestation_challenge.ok_or(Status::UnsupportedAccess)?;
650
651        // A CSRRequest that replaces an earlier one in the same period must not leak the
652        // earlier key: there is exactly one candidate operational key at a time.
653        if let Some(previous) = self.pending_csr.take() {
654            let _ = self.keys.borrow_mut().remove(previous.key);
655        }
656
657        let (key, public) = self
658            .keys
659            .borrow_mut()
660            .generate(crate::crypto::KeyPurpose::Operational, random)
661            .map_err(|_| Status::Failure)?;
662
663        let mut csr_buf = [0u8; attestation::nocsr::MAX_CSR_LEN];
664        let csr = crate::attestation::nocsr::build_csr(&*self.keys.borrow(), key, &mut csr_buf)
665            .map_err(|_| Status::Failure)?;
666        let elements = crate::attestation::nocsr::NocsrElements::new(csr, *nonce);
667        let mut elements_buf = [0u8; RESP_MAX];
668        let encoded = elements
669            .encode(&mut elements_buf)
670            .map_err(|_| Status::Failure)?;
671        let signature = crate::attestation::nocsr::sign_nocsr(
672            &*self.keys.borrow(),
673            self.attestation.dac_key,
674            encoded,
675            challenge,
676        )
677        .map_err(|_| Status::Failure)?;
678
679        self.pending_csr.set(Some(PendingCsr {
680            session: ctx.session,
681            key,
682            public,
683            for_update,
684        }));
685        self.fail_safe
686            .borrow_mut()
687            .record(ctx.now, |p| p.csr_requested = true)
688            .map_err(|_| Status::FailsafeRequired)?;
689
690        let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
691        full(w.start_structure(tag))?;
692        full(w.octets(Tag::Context(0), encoded))?;
693        full(w.octets(Tag::Context(1), signature.as_bytes()))?;
694        full(w.end_container())
695    }
696
697    /// `AddTrustedRootCertificate` (§11.18.6.13).
698    ///
699    /// No response command: success is a plain `SUCCESS` status. The certificate is *pending*
700    /// until an `AddNOC` adopts it — §11.18.6.13 is explicit that the only way to remove a
701    /// trusted root is to remove the fabric that uses it, so one installed by a fail-safe
702    /// that then expired must never have been installed at all.
703    pub fn add_trusted_root(
704        &self,
705        rcac: &[u8],
706        ctx: &InteractionContext<'_>,
707    ) -> Result<(), Status> {
708        let progress = self.require_fail_safe(ctx.now)?;
709        // "If a prior AddTrustedRootCertificate command was successfully invoked within the
710        // fail-safe timer period, which would cause the new invocation to add a second root
711        // certificate within a given fail-safe timer period, then this command SHALL fail
712        // with a CONSTRAINT_ERROR."
713        if progress.added_trusted_root {
714            return Err(Status::ConstraintError);
715        }
716        if progress.added_noc || progress.updated_noc {
717            return Err(Status::ConstraintError);
718        }
719        // "If the certificate … fails any validity checks, not fulfilling all the
720        // requirements for a valid Matter Certificate Encoding representation, including a
721        // truncated or oversize value, then this command SHALL fail with an INVALID_COMMAND."
722        let parsed = MatterCertificate::decode(rcac).map_err(|_| Status::InvalidCommand)?;
723        parsed
724            .validate_as(crate::cert::CertType::Rcac)
725            .map_err(|_| Status::InvalidCommand)?;
726        // "fails any validity checks" covers the signature, and this is the only moment it can
727        // be checked. §6.4.5.3 trusts a root by *provenance* rather than by its signature, so
728        // nothing downstream ever verifies it: `verify_chain` checks the NOC and the ICAC
729        // against this root's public key and takes the root itself as given. A root with a
730        // corrupt or forged signature that is accepted here is therefore accepted for the
731        // lifetime of the fabric, and every certificate under it verifies perfectly.
732        //
733        // A self-signature proves only that whoever produced the certificate held the key
734        // inside it, which is exactly the claim a root makes about itself. Rejecting one that
735        // fails costs an administrator nothing it did not already have.
736        if !crate::cert::verify_self_signed(&parsed).unwrap_or(false) {
737            return Err(Status::InvalidCommand);
738        }
739        let stored = heapless::Vec::from_slice(rcac).map_err(|_| Status::ResourceExhausted)?;
740
741        *self.pending_root.borrow_mut() = Some(stored);
742        self.fail_safe
743            .borrow_mut()
744            .record(ctx.now, |p| p.added_trusted_root = true)
745            .map_err(|_| Status::FailsafeRequired)?;
746        Ok(())
747    }
748}
749
750/// `AddNOC`'s fields (§11.18.6.8).
751#[derive(Debug, Clone, Copy)]
752pub struct AddNocRequest<'a> {
753    /// `NOCValue [0]` — the node operational certificate, Matter TLV, max 400.
754    pub noc: &'a [u8],
755    /// `ICACValue [1]` — the intermediate, if the chain has one.
756    pub icac: Option<&'a [u8]>,
757    /// `IPKValue [2]` — the epoch key for the Identity Protection Key, 16 octets.
758    ///
759    /// "This is needed to bootstrap a necessary configuration value for subsequent CASE to
760    /// succeed", and having provided it is equivalent to a `KeySetWrite` of group key set 0.
761    pub ipk: [u8; crate::crypto::SYMMETRIC_KEY_LENGTH_BYTES],
762    /// `CaseAdminSubject [3]` — the subject that gets Administer over the new fabric.
763    pub case_admin_subject: u64,
764    /// `AdminVendorId [4]` — "the Vendor ID of the entity issuing the AddNOC command".
765    pub admin_vendor_id: VendorId,
766}
767
768impl<C: Config, K: KeyStore, R: Rng, const N: usize> OperationalCredentials<'_, C, K, R, N> {
769    /// `AddNOC` (§11.18.6.8) — join a fabric.
770    ///
771    /// Returns the `StatusCode` for the `NOCResponse`, and on success records a
772    /// [`FabricChange::Added`] for [`OperationalCredentials::take_change`].
773    ///
774    /// Every failure here "SHALL leave all non-volatile state of the device untouched, as if
775    /// the AddNOC command had never been received. **The information about the last CSR state
776    /// associated with this session SHALL also be untouched** in this case, so that a valid
777    /// AddNOC command MAY still be issued later that would match that CSR state." So the
778    /// pending key is consumed only on the success path — a commissioner that sent a
779    /// malformed NOC gets to try again without another `CSRRequest`.
780    pub fn add_noc(
781        &self,
782        request: &AddNocRequest<'_>,
783        ctx: &InteractionContext<'_>,
784    ) -> Result<NocStatus, Status> {
785        let progress = self.require_fail_safe(ctx.now)?;
786        // These three are *status codes*, not NOCResponse error codes: the command never runs.
787        if progress.added_noc || progress.updated_noc {
788            return Err(Status::ConstraintError);
789        }
790        let Some(pending) = self.pending_csr.get() else {
791            return Ok(NocStatus::MissingCsr);
792        };
793        if pending.session != ctx.session {
794            // §11.18.6.7: the CSR record is scoped to "the same secure session". A key
795            // generated for one administrator must not be adopted by another's AddNOC.
796            return Ok(NocStatus::MissingCsr);
797        }
798        // "If the prior CSRRequest state that preceded AddNOC had the IsForUpdateNOC field
799        // indicated as true, then this command SHALL fail with a CONSTRAINT_ERROR."
800        if pending.for_update {
801            return Err(Status::ConstraintError);
802        }
803
804        // "If no prior AddTrustedRootCertificate command was successfully executed within the
805        // fail-safe timer period, then … InvalidNOC … even if some other fabric already uses
806        // the exact same root of trust certificate."
807        let pending_root = self.pending_root.borrow();
808        let Some(rcac_bytes) = pending_root
809            .as_deref()
810            .filter(|_| progress.added_trusted_root)
811        else {
812            return Ok(NocStatus::InvalidNoc);
813        };
814
815        // §11.18.6.7's validation comes first: it is described as happening "Upon receipt",
816        // before any of AddNOC's own preconditions, and it is what turns the certificate into
817        // an identity the rules below can talk about.
818        let identity = match validate_chain(request.noc, request.icac, rcac_bytes, &pending.public)
819        {
820            Ok(identity) => identity,
821            Err(status) => return Ok(status),
822        };
823
824        let mut table = self.fabrics.borrow_mut();
825        // "If the NOC provided in the NOCValue encodes an Operational Identifier for a <Root
826        // Public Key, FabricID> pair already present on the device … FabricConflict."
827        //
828        // Before `TableFull`, which is the order §11.18.6.8 lists them in: an administrator
829        // that should have sent `UpdateNOC` is told so even on a full device, which is the
830        // more useful of the two answers.
831        let compressed =
832            crate::fabric::compressed_fabric_id(&identity.root_public_key, identity.fabric_id)
833                .map_err(|_| Status::Failure)?;
834        if table.find_by_compressed(compressed).is_some() {
835            return Ok(NocStatus::FabricConflict);
836        }
837        // "If the device already has the CommissionedFabrics attribute equal to the
838        // SupportedFabrics attribute … TableFull."
839        if table.len() >= table.capacity() {
840            return Ok(NocStatus::TableFull);
841        }
842        // "If the CaseAdminSubject field is not a valid ACL subject in the context of AuthMode
843        // set to CASE, such as not being in either the Operational or CASE Authenticated Tag
844        // range … InvalidAdminSubject."
845        if !is_case_subject(request.case_admin_subject) {
846            return Ok(NocStatus::InvalidAdminSubject);
847        }
848
849        let mut credentials = match Credentials::new(request.noc, rcac_bytes) {
850            Ok(credentials) => credentials,
851            Err(_) => return Ok(NocStatus::InvalidNoc),
852        };
853        if let Some(icac) = request.icac {
854            credentials = match credentials.with_icac(icac) {
855                Ok(credentials) => credentials,
856                Err(_) => return Ok(NocStatus::InvalidNoc),
857            };
858        }
859
860        let index = table.allocate_index().map_err(|_| Status::Failure)?;
861        let fabric = Fabric::new(
862            index,
863            FabricIdentity {
864                fabric_id: identity.fabric_id,
865                node_id: identity.node_id,
866                root_public_key: identity.root_public_key,
867                admin_vendor_id: request.admin_vendor_id,
868            },
869            &SymmetricKey::new(request.ipk),
870            pending.key,
871            credentials,
872        );
873        let Ok(fabric) = fabric else {
874            return Ok(NocStatus::InvalidNoc);
875        };
876        if table.insert(fabric).is_err() {
877            return Ok(NocStatus::FabricConflict);
878        }
879        drop(table);
880        drop(pending_root);
881
882        // Only now is the pending state consumed: every path above left it intact.
883        self.pending_csr.set(None);
884        *self.pending_root.borrow_mut() = None;
885
886        // Step 9: "The Fabric Index associated with the armed fail-safe context SHALL be
887        // updated to match the Fabric Index just allocated." Without it, the
888        // `CommissioningComplete` that follows over CASE on the new fabric would not match.
889        let mut fail_safe = self.fail_safe.borrow_mut();
890        fail_safe
891            .record(ctx.now, |p| p.added_noc = true)
892            .map_err(|_| Status::FailsafeRequired)?;
893        fail_safe
894            .adopt_fabric(index, ctx.now)
895            .map_err(|_| Status::FailsafeRequired)?;
896        drop(fail_safe);
897
898        self.change.set(Some(FabricChange::Added {
899            index,
900            case_admin_subject: request.case_admin_subject,
901            bind_pase_session: ctx.fabric_index.is_none(),
902        }));
903        Ok(NocStatus::Ok)
904    }
905
906    /// `UpdateNOC` (§11.18.6.9) — rotate the operational key and certificate on a fabric
907    /// this node already belongs to.
908    pub fn update_noc(
909        &self,
910        noc: &[u8],
911        icac: Option<&[u8]>,
912        ctx: &InteractionContext<'_>,
913    ) -> Result<NocStatus, Status> {
914        let progress = self.require_fail_safe(ctx.now)?;
915        if progress.added_noc || progress.updated_noc {
916            return Err(Status::ConstraintError);
917        }
918        // "If a prior AddTrustedRootCertificate command was successfully invoked within the
919        // fail-safe timer period, then this command SHALL fail with a CONSTRAINT_ERROR …
920        // since the only valid following logical operation is invoking the AddNOC command."
921        if progress.added_trusted_root {
922            return Err(Status::ConstraintError);
923        }
924        let Some(pending) = self.pending_csr.get() else {
925            return Ok(NocStatus::MissingCsr);
926        };
927        if pending.session != ctx.session {
928            return Ok(NocStatus::MissingCsr);
929        }
930        // "If the prior CSRRequest state that preceded UpdateNOC had the IsForUpdateNOC field
931        // indicated as false, then this command SHALL fail with a CONSTRAINT_ERROR."
932        if !pending.for_update {
933            return Err(Status::ConstraintError);
934        }
935        // The command is `AF`, so §8.8.2.3 step b.v has already refused it without a fabric.
936        let accessing = ctx.fabric_index.ok_or(Status::UnsupportedAccess)?;
937
938        let mut table = self.fabrics.borrow_mut();
939        let Some(existing) = table.find(accessing) else {
940            return Ok(NocStatus::InvalidFabricIndex);
941        };
942        let rcac = existing.credentials.rcac.clone();
943        let existing_fabric_id = existing.fabric_id;
944
945        let identity = match validate_chain(noc, icac, &rcac, &pending.public) {
946            Ok(identity) => identity,
947            Err(status) => return Ok(status),
948        };
949        // "The NOC provided in the NOCValue does not refer in its subject to the FabricID
950        // associated with the accessing fabric" — and the same for the ICAC.
951        if identity.fabric_id != existing_fabric_id {
952            return Ok(NocStatus::InvalidNoc);
953        }
954
955        let mut credentials = match Credentials::new(noc, &rcac) {
956            Ok(credentials) => credentials,
957            Err(_) => return Ok(NocStatus::InvalidNoc),
958        };
959        if let Some(icac) = icac {
960            credentials = match credentials.with_icac(icac) {
961                Ok(credentials) => credentials,
962                Err(_) => return Ok(NocStatus::InvalidNoc),
963            };
964        }
965
966        let Some(fabric) = table.find_mut(accessing) else {
967            return Ok(NocStatus::InvalidFabricIndex);
968        };
969        let previous = Replaced {
970            index: accessing,
971            node_id: fabric.node_id,
972            credentials: core::mem::replace(&mut fabric.credentials, credentials),
973            operational_key: core::mem::replace(&mut fabric.operational_key, pending.key),
974        };
975        fabric.node_id = identity.node_id;
976        drop(table);
977
978        // Step 1.c: "All internal data reflecting the prior operational identifier … SHALL be
979        // revoked and removed." The fabric no longer carries the previous identity, so nothing
980        // can use it; its key is held only until the fail-safe decides between §11.10.7.2.2
981        // step 6's revert and §11.10.7.6's commit (see `replaced`).
982        if let Some(stale) = self.replaced.borrow_mut().replace(previous) {
983            let _ = self.keys.borrow_mut().remove(stale.operational_key);
984        }
985        self.pending_csr.set(None);
986
987        self.fail_safe
988            .borrow_mut()
989            .record(ctx.now, |p| p.updated_noc = true)
990            .map_err(|_| Status::FailsafeRequired)?;
991        self.change
992            .set(Some(FabricChange::Updated { index: accessing }));
993        Ok(NocStatus::Ok)
994    }
995
996    /// `UpdateFabricLabel` (§11.18.6.11).
997    pub fn update_fabric_label(
998        &self,
999        label: &str,
1000        ctx: &InteractionContext<'_>,
1001    ) -> Result<NocStatus, Status> {
1002        let accessing = ctx.fabric_index.ok_or(Status::UnsupportedAccess)?;
1003        let mut table = self.fabrics.borrow_mut();
1004        // "If the Label field is identical to a Label already in use by a Fabric within the
1005        // Fabrics list **that is not the accessing fabric** … LabelConflict."
1006        if table
1007            .iter()
1008            .any(|f| f.index != accessing && f.label.as_str() == label && !label.is_empty())
1009        {
1010            return Ok(NocStatus::LabelConflict);
1011        }
1012        let Some(fabric) = table.find_mut(accessing) else {
1013            return Ok(NocStatus::InvalidFabricIndex);
1014        };
1015        // "max 32" — longer is a constraint error, not a truncation.
1016        fabric
1017            .set_label(label)
1018            .map_err(|_| Status::ConstraintError)?;
1019        Ok(NocStatus::Ok)
1020    }
1021
1022    /// `RemoveFabric` (§11.18.6.12) — leave a fabric, and delete everything scoped to it.
1023    ///
1024    /// The index is a *parameter*, not the accessing fabric: an administrator may remove a
1025    /// fabric other than its own, which is why the command is `A` rather than `AF`. The three
1026    /// outcomes §11.18.6.12 distinguishes differ only in what else goes with it, and
1027    /// [`FabricChange::Removed`] carries which one happened.
1028    pub fn remove_fabric(
1029        &self,
1030        index: FabricIndex,
1031        ctx: &InteractionContext<'_>,
1032    ) -> Result<NocStatus, Status> {
1033        let mut table = self.fabrics.borrow_mut();
1034        // "If the FabricIndex field does not match the FabricIndex of any entry within the
1035        // Fabrics list, then an NOCResponse with a StatusCode of InvalidFabricIndex SHALL be
1036        // returned … and there SHALL NOT be any permanent changes to any device data."
1037        let Some(removed) = table.remove(index) else {
1038            return Ok(NocStatus::InvalidFabricIndex);
1039        };
1040        let was_last = table.is_empty();
1041        drop(table);
1042
1043        // The operational key has to actually be destroyed, not merely forgotten: a fabric
1044        // whose key survived removal could still be impersonated by anything that reaches the
1045        // key store.
1046        let _ = self.keys.borrow_mut().remove(removed.operational_key);
1047
1048        self.change.set(Some(FabricChange::Removed {
1049            index,
1050            was_last,
1051            was_accessing: ctx.fabric_index == Some(index),
1052        }));
1053        Ok(NocStatus::Ok)
1054    }
1055
1056    /// `SetVIDVerificationStatement` (§11.18.6.14).
1057    ///
1058    /// All three fields are optional and at least one must be present (`O.a+`). The command
1059    /// "SHALL only operate against the Fabrics and NOCs attribute entries associated with the
1060    /// accessing fabric index", which is what `AF` enforces before it reaches here.
1061    pub fn set_vid_verification_statement(
1062        &self,
1063        vendor_id: Option<VendorId>,
1064        statement: Option<&[u8]>,
1065        vvsc: Option<&[u8]>,
1066        ctx: &InteractionContext<'_>,
1067    ) -> Result<(), Status> {
1068        if vendor_id.is_none() && statement.is_none() && vvsc.is_none() {
1069            // `O.a+`: "at least one of the marked fields SHALL be present".
1070            return Err(Status::InvalidCommand);
1071        }
1072        let accessing = ctx.fabric_index.ok_or(Status::UnsupportedAccess)?;
1073        let mut table = self.fabrics.borrow_mut();
1074        let Some(fabric) = table.find_mut(accessing) else {
1075            return Err(Status::ConstraintError);
1076        };
1077
1078        if let Some(statement) = statement {
1079            match statement.len() {
1080                // "If the length of the field's value is exactly 0, then the
1081                // VIDVerificationStatement field … SHALL be erased."
1082                0 => fabric.vid_verification_statement = None,
1083                VID_VERIFICATION_STATEMENT_LEN => {
1084                    let mut value = [0u8; VID_VERIFICATION_STATEMENT_LEN];
1085                    value.copy_from_slice(statement);
1086                    fabric.vid_verification_statement = Some(value);
1087                }
1088                // "If the length … is neither exactly 0 nor exactly 85, then the command
1089                // SHALL fail with a status code of CONSTRAINT_ERROR."
1090                _ => return Err(Status::ConstraintError),
1091            }
1092        }
1093        if let Some(vvsc) = vvsc {
1094            // A VVSC alongside an ICAC is INVALID_COMMAND, which `set_vvsc` reports as an
1095            // argument error (§11.18.4.4's mutual exclusion).
1096            fabric
1097                .credentials
1098                .set_vvsc(vvsc)
1099                .map_err(|_| Status::InvalidCommand)?;
1100        }
1101        if let Some(vendor_id) = vendor_id {
1102            fabric.admin_vendor_id = vendor_id;
1103        }
1104        Ok(())
1105    }
1106
1107    /// `SignVIDVerificationRequest` (§11.18.6.15) → `SignVIDVerificationResponse`
1108    /// (§11.18.6.16).
1109    ///
1110    /// Signs §6.4.10's `vendor_id_verification_tbs` with the *operational* key of the fabric
1111    /// under verification — not the attestation key. The procedure proves that whoever holds
1112    /// that fabric's NOC stands behind the `VendorID` the fabric claims, which is a statement
1113    /// about the fabric rather than about the hardware.
1114    pub fn sign_vid_verification(
1115        &self,
1116        index: FabricIndex,
1117        client_challenge: &[u8; 32],
1118        ctx: &InteractionContext<'_>,
1119        w: &mut TlvWriter<'_>,
1120        tag: Tag,
1121    ) -> Result<(), Status> {
1122        let challenge = ctx.attestation_challenge.ok_or(Status::UnsupportedAccess)?;
1123        let table = self.fabrics.borrow();
1124        // "If the FabricIndex field contains a fabric index which does not have an associated
1125        // entry in the Fabrics attribute, then the command SHALL fail with a status code of
1126        // CONSTRAINT_ERROR."
1127        let fabric = table.find(index).ok_or(Status::ConstraintError)?;
1128
1129        let mut tbs_buf = [0u8; VENDOR_ID_VERIFICATION_TBS_MAX];
1130        let tbs = fabric.vendor_id_verification_tbs(&mut tbs_buf, client_challenge, challenge);
1131        let signature = self
1132            .keys
1133            .borrow()
1134            .sign(fabric.operational_key, tbs)
1135            .map_err(|_| Status::Failure)?;
1136
1137        let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
1138        full(w.start_structure(tag))?;
1139        full(w.unsigned(Tag::Context(0), u64::from(index.0)))?;
1140        full(w.unsigned(
1141            Tag::Context(1),
1142            u64::from(crate::fabric::FABRIC_BINDING_VERSION),
1143        ))?;
1144        full(w.octets(Tag::Context(2), signature.as_bytes()))?;
1145        full(w.end_container())
1146    }
1147}
1148
1149/// Whether a value is a valid access-control subject for `AuthMode: CASE` (§6.6.2.1.1).
1150///
1151/// §11.18.6.8: "not being in either the Operational or CASE Authenticated Tag range" is
1152/// `InvalidAdminSubject`. A group node id or a zero would name something that can never
1153/// authenticate over CASE, leaving the new fabric joined and unadministrable.
1154fn is_case_subject(subject: u64) -> bool {
1155    let node = NodeId(subject);
1156    matches!(
1157        node.kind(),
1158        crate::msg::NodeIdKind::Operational | crate::msg::NodeIdKind::CaseAuthenticatedTag
1159    )
1160}
1161
1162/// The identity a validated chain attests to.
1163struct ChainIdentity {
1164    fabric_id: crate::msg::FabricId,
1165    node_id: NodeId,
1166    root_public_key: PublicKey,
1167}
1168
1169/// §11.18.6.7's three validation steps, in the order the specification numbers them.
1170fn validate_chain(
1171    noc: &[u8],
1172    icac: Option<&[u8]>,
1173    rcac: &[u8],
1174    expected_public_key: &PublicKey,
1175) -> Result<ChainIdentity, NocStatus> {
1176    let noc_cert = MatterCertificate::decode(noc).map_err(|_| NocStatus::InvalidNoc)?;
1177    let icac_cert = match icac {
1178        Some(bytes) => Some(MatterCertificate::decode(bytes).map_err(|_| NocStatus::InvalidNoc)?),
1179        None => None,
1180    };
1181    let root = MatterCertificate::decode(rcac).map_err(|_| NocStatus::InvalidNoc)?;
1182
1183    // Step 3, hoisted: "The DN Encoding Rules SHALL be validated for every certificate in the
1184    // chain, including valid value range checks for identifiers such as Fabric ID and Node
1185    // ID … the error status SHALL be InvalidNodeOpId if the matter-node-id attribute in the
1186    // subject DN of the NOC has a value outside the Operational Node ID range". That check
1187    // has to come before the chain verification, because a NOC with no node id at all would
1188    // otherwise fail as a generic InvalidNOC and hide what was actually wrong.
1189    let node_id = noc_cert.node_id().ok_or(NocStatus::InvalidNodeOpId)?;
1190    if !node_id.is_operational() {
1191        return Err(NocStatus::InvalidNodeOpId);
1192    }
1193
1194    // Step 1: Crypto_VerifyChain over the whole chain. `at = None` — a commissionee has no
1195    // wall clock during commissioning, and §6.4.5 only requires the validity window to be
1196    // checked when the node knows the time.
1197    let verified = crate::cert::verify_chain(&noc_cert, icac_cert.as_ref(), &root, None)
1198        .map_err(|_| NocStatus::InvalidNoc)?;
1199
1200    // Step 2: "The public key of the NOC SHALL match the last generated operational public
1201    // key on this session … If this check fails, the error status SHALL be InvalidPublicKey."
1202    //
1203    // This is the step that ties the certificate to a key the *device* made. Without it an
1204    // administrator could install a NOC over a key pair it generated itself and then
1205    // impersonate the node.
1206    if noc_cert.public_key.as_bytes() != expected_public_key.as_bytes() {
1207        return Err(NocStatus::InvalidPublicKey);
1208    }
1209
1210    Ok(ChainIdentity {
1211        fabric_id: verified.fabric_id,
1212        node_id,
1213        root_public_key: root.public_key,
1214    })
1215}
1216
1217// --- The attributes ----------------------------------------------------------------------------
1218
1219/// The global `FabricIndex` field of a fabric-scoped struct (§7.19.1.9).
1220///
1221/// > A fabric-scoped struct SHALL support the global FabricIndex field of type fabric-index,
1222/// > which indicates the associated fabric of the struct … The table that defines fields of a
1223/// > fabric-scoped struct SHALL NOT list the global FabricIndex field, which is a global field
1224/// > and defined implicitly.
1225///
1226/// Which is why it is not in §11.18.4.4's or §11.18.4.5's tables and must still be emitted.
1227pub const FABRIC_INDEX_FIELD: u8 = 254;
1228
1229impl<C: Config, K: KeyStore, R: Rng, const N: usize> OperationalCredentials<'_, C, K, R, N> {
1230    /// Whether a fabric's entries belong in this read (§7.19.1.8.2).
1231    ///
1232    /// > For a read interaction on a list, with fabric-filtering disabled, the list SHALL be
1233    /// > reported as a full list with all entries.
1234    ///
1235    /// With filtering enabled, only the accessing fabric's. A request with filtering on and
1236    /// *no* accessing fabric — a PASE session — matches nothing, which is right: there is no
1237    /// fabric whose entries it is asking for.
1238    fn visible(ctx: &InteractionContext<'_>, index: FabricIndex) -> bool {
1239        !ctx.fabric_filtered || ctx.fabric_index == Some(index)
1240    }
1241
1242    fn write_nocs(
1243        &self,
1244        ctx: &InteractionContext<'_>,
1245        w: &mut TlvWriter<'_>,
1246        tag: Tag,
1247    ) -> Result<(), Status> {
1248        let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
1249        let table = self.fabrics.borrow();
1250        full(w.start_array(tag))?;
1251        for fabric in table.iter().filter(|f| Self::visible(ctx, f.index)) {
1252            let credentials = &fabric.credentials;
1253            full(w.start_structure(Tag::Anonymous))?;
1254            full(w.octets(Tag::Context(1), &credentials.noc))?;
1255            // §11.18.4.4: "If no ICAC is present in the chain, this field SHALL be set to
1256            // null" — present-and-null, not absent.
1257            match &credentials.icac {
1258                Some(icac) => full(w.octets(Tag::Context(2), icac))?,
1259                None => full(w.null(Tag::Context(2)))?,
1260            }
1261            // "If no VVSC is needed, this field SHALL be omitted (in that there SHALL NOT be
1262            // a value present, not even an empty octet string)." The opposite convention from
1263            // the ICAC, in the same structure.
1264            if let Some(vvsc) = &credentials.vvsc {
1265                full(w.octets(Tag::Context(3), vvsc))?;
1266            }
1267            full(w.unsigned(Tag::Context(FABRIC_INDEX_FIELD), u64::from(fabric.index.0)))?;
1268            full(w.end_container())?;
1269        }
1270        full(w.end_container())
1271    }
1272
1273    fn write_fabrics(
1274        &self,
1275        ctx: &InteractionContext<'_>,
1276        w: &mut TlvWriter<'_>,
1277        tag: Tag,
1278    ) -> Result<(), Status> {
1279        let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
1280        let table = self.fabrics.borrow();
1281        full(w.start_array(tag))?;
1282        for fabric in table.iter().filter(|f| Self::visible(ctx, f.index)) {
1283            full(w.start_structure(Tag::Anonymous))?;
1284            full(w.octets(Tag::Context(1), fabric.root_public_key.as_bytes()))?;
1285            full(w.unsigned(Tag::Context(2), u64::from(fabric.admin_vendor_id.0)))?;
1286            full(w.unsigned(Tag::Context(3), fabric.fabric_id.0))?;
1287            full(w.unsigned(Tag::Context(4), fabric.node_id.0))?;
1288            full(w.utf8(Tag::Context(5), fabric.label.as_str()))?;
1289            if let Some(statement) = &fabric.vid_verification_statement {
1290                full(w.octets(Tag::Context(6), statement))?;
1291            }
1292            full(w.unsigned(Tag::Context(FABRIC_INDEX_FIELD), u64::from(fabric.index.0)))?;
1293            full(w.end_container())?;
1294        }
1295        full(w.end_container())
1296    }
1297
1298    /// `TrustedRootCertificates` (§11.18.5.5) — a plain `list[octstr]`, *not* fabric-scoped.
1299    ///
1300    /// "Depending on the method of storage employed by the server, either shared storage for
1301    /// identical root certificates shared by many fabrics, or individually stored root
1302    /// certificate per fabric, **multiple identical root certificates MAY legally appear
1303    /// within the list**." This implementation stores one per fabric, so duplicates do
1304    /// appear — and §11.18.5.5's own advice is how a client copes: "To match a root with a
1305    /// given fabric, the root certificate's subject and subject public key need to be
1306    /// cross-referenced with the NOC or ICAC certificates".
1307    fn write_roots(
1308        &self,
1309        w: &mut TlvWriter<'_>,
1310        tag: Tag,
1311        now: crate::platform::Instant,
1312    ) -> Result<(), Status> {
1313        let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
1314        let table = self.fabrics.borrow();
1315        full(w.start_array(tag))?;
1316        for fabric in table.iter() {
1317            full(w.octets(Tag::Anonymous, &fabric.credentials.rcac))?;
1318        }
1319        // §11.18.6.13: `AddTrustedRootCertificate` "SHALL add a Trusted Root CA Certificate …
1320        // **to the TrustedRootCertificates Attribute list**". Present tense, and the list is
1321        // the attribute — so the root appears the moment the command succeeds, not when
1322        // `AddNOC` commits it to a fabric. An administrator adds the root, reads the attribute
1323        // back to confirm the node took it, and only then sends `AddNOC`; a node that lists
1324        // committed roots only answers that read with the root missing, having just said
1325        // SUCCESS.
1326        //
1327        // It cannot be counted twice: `AddNOC` clears the pending root as it commits it, and
1328        // so does the fail-safe's rollback.
1329        //
1330        // Only while the fail-safe that added it is armed. §11.10.7.2.2 step 9 removes trusted
1331        // roots no fabric references when the fail-safe ends, so a pending root outside a
1332        // fail-safe period is not pending — it is garbage waiting for `reap`, which runs on
1333        // the next *invoke*. A read that arrives first would otherwise report a root the node
1334        // has already promised to have dropped, which is what `TC_OPCREDS_3_1` checks
1335        // immediately after `ArmFailSafe(0)`.
1336        // …and only while the fail-safe that added it is *the one still armed*, which is
1337        // exactly the condition `reap` applies: `progress.added_trusted_root` is true only for
1338        // the context that accepted this root. Asking merely whether *some* fail-safe is armed
1339        // is not enough — the next `ArmFailSafe` would bring the abandoned root back from the
1340        // dead, and `ArmFailSafe` belongs to General Commissioning, so no invoke against this
1341        // cluster need happen in between to reap it.
1342        if self
1343            .fail_safe
1344            .borrow()
1345            .armed(now)
1346            .is_some_and(|armed| armed.progress.added_trusted_root)
1347            && let Some(pending) = self.pending_root.borrow().as_ref()
1348        {
1349            full(w.octets(Tag::Anonymous, pending))?;
1350        }
1351        full(w.end_container())
1352    }
1353}
1354
1355impl<C: Config, K: KeyStore, R: Rng, const N: usize> ClusterHandler
1356    for OperationalCredentials<'_, C, K, R, N>
1357{
1358    fn read(
1359        &self,
1360        resolved: &Resolved<'_>,
1361        ctx: &InteractionContext<'_>,
1362        w: &mut TlvWriter<'_>,
1363        tag: Tag,
1364    ) -> Result<(), Status> {
1365        let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
1366        match resolved.attribute {
1367            NOCS => self.write_nocs(ctx, w, tag),
1368            FABRICS => self.write_fabrics(ctx, w, tag),
1369            // Both are `uint8`, and `AssertValid` holds `Config::FABRICS` to §11.18.5.3's
1370            // `5 to 254` at compile time — so the conversion cannot lose anything, and
1371            // saturating rather than panicking is the right way to say so on a device.
1372            SUPPORTED_FABRICS => {
1373                let capacity = u8::try_from(self.fabrics.borrow().capacity()).unwrap_or(u8::MAX);
1374                full(w.unsigned(tag, u64::from(capacity)))
1375            }
1376            COMMISSIONED_FABRICS => {
1377                let len = u8::try_from(self.fabrics.borrow().len()).unwrap_or(u8::MAX);
1378                full(w.unsigned(tag, u64::from(len)))
1379            }
1380            TRUSTED_ROOT_CERTIFICATES => self.write_roots(w, tag, ctx.now),
1381            // §11.18.5.6: "This attribute SHALL indicate the accessing fabric index", whose
1382            // fallback is 0 — the value that means "no fabric", which is exactly what a PASE
1383            // session has.
1384            CURRENT_FABRIC_INDEX => {
1385                full(w.unsigned(tag, u64::from(ctx.fabric_index.unwrap_or(FabricIndex(0)).0)))
1386            }
1387            _ => Err(Status::UnsupportedAttribute),
1388        }
1389    }
1390
1391    fn invoke(
1392        &self,
1393        resolved: &ResolvedCommand<'_>,
1394        fields: Option<&[u8]>,
1395        ctx: &InteractionContext<'_>,
1396        w: &mut TlvWriter<'_>,
1397        tag: Tag,
1398    ) -> Result<Option<CommandId>, StatusIb> {
1399        self.run(resolved.command.id, fields, ctx, w, tag)
1400            .map_err(StatusIb::from)
1401    }
1402
1403    fn on_lifecycle(&self, event: crate::im::Lifecycle) {
1404        match event {
1405            crate::im::Lifecycle::CommissioningComplete(_) => self.commit_update(),
1406            crate::im::Lifecycle::FailSafeExpired { .. } => {
1407                let replaced = self.replaced.borrow().as_ref().map(|r| r.index);
1408                if let Some(index) = replaced {
1409                    self.revert_update(index);
1410                }
1411                self.discard_pending();
1412            }
1413            crate::im::Lifecycle::FabricRemoved(index) => {
1414                if let Some(replaced) = self.take_replaced(index) {
1415                    let _ = self.keys.borrow_mut().remove(replaced.operational_key);
1416                }
1417            }
1418        }
1419    }
1420}
1421
1422impl<C: Config, K: KeyStore, R: Rng, const N: usize> Cluster
1423    for OperationalCredentials<'_, C, K, R, N>
1424{
1425    const ID: ClusterId = ID;
1426}
1427
1428// --- Command decoding --------------------------------------------------------------------------
1429
1430/// Reads the members of a `CommandFields` structure, one at a time.
1431///
1432/// `CommandFields` is the `CommandDataIB`'s context-1 member (§10.6.11), so it arrives
1433/// *tagged*: a fragment of a structure rather than a TLV document, and reading it with
1434/// [`TlvReader::new`] would reject exactly the bytes that are correct.
1435///
1436/// Only the structure's own end-of-container ends the walk. A short buffer and a malformed
1437/// element are both `INVALID_COMMAND`: treating either as an end of input would let a
1438/// truncated `AddNOC` be read as one with fields absent.
1439fn walk_fields<'a>(
1440    fields: Option<&'a [u8]>,
1441    mut on_field: impl FnMut(u8, &crate::tlv::Element<'a>) -> Result<bool, Status>,
1442) -> Result<(), Status> {
1443    let fields = fields.ok_or(Status::InvalidCommand)?;
1444    let mut reader = TlvReader::new_in(fields, ContainerKind::Structure);
1445    let element = reader
1446        .next_element()
1447        .map_err(|_| Status::InvalidCommand)?
1448        .ok_or(Status::InvalidCommand)?;
1449    if element.value.container() != Some(ContainerKind::Structure) {
1450        return Err(Status::InvalidCommand);
1451    }
1452    let start_depth = reader.depth();
1453    loop {
1454        let Some(field) = reader.next_element().map_err(|_| Status::InvalidCommand)? else {
1455            return Err(Status::InvalidCommand);
1456        };
1457        if reader.depth() < start_depth {
1458            break;
1459        }
1460        let number = match field.tag {
1461            Tag::Context(number) => number,
1462            // A fully-qualified tag is a vendor extension; §11.18 has none, and §10.6.11's
1463            // forward-compatibility rule is to ignore what is not understood.
1464            _ => {
1465                reader
1466                    .skip_value(&field)
1467                    .map_err(|_| Status::InvalidCommand)?;
1468                continue;
1469            }
1470        };
1471        if !on_field(number, &field)? {
1472            reader
1473                .skip_value(&field)
1474                .map_err(|_| Status::InvalidCommand)?;
1475        }
1476    }
1477    Ok(())
1478}
1479
1480fn decode_nonce<const L: usize>(element: &crate::tlv::Element<'_>) -> Result<[u8; L], Status> {
1481    let bytes = element.octets().map_err(|_| Status::InvalidCommand)?;
1482    // §11.18.6.1: "If the AttestationNonce that is provided in the command is malformed, a
1483    // recipient SHALL fail the command with a Status Code of INVALID_COMMAND." A nonce of the
1484    // wrong length is malformed, not merely constrained: it would change what is signed.
1485    let mut out = [0u8; L];
1486    if bytes.len() != L {
1487        return Err(Status::InvalidCommand);
1488    }
1489    out.copy_from_slice(bytes);
1490    Ok(out)
1491}
1492
1493impl<C: Config, K: KeyStore, R: Rng, const N: usize> OperationalCredentials<'_, C, K, R, N> {
1494    /// Answers a `NOCResponse` (§11.18.6.10): `StatusCode [0]`, `FabricIndex [1]`,
1495    /// `DebugText [2]`.
1496    ///
1497    /// `FabricIndex` is present only on success — its conformance is `StatusCode == OK, O` —
1498    /// and `DebugText` is omitted entirely: it is optional, and a device that filled it would
1499    /// leak its internals to anyone who can invoke the command.
1500    fn noc_response(
1501        status: NocStatus,
1502        index: Option<FabricIndex>,
1503        w: &mut TlvWriter<'_>,
1504        tag: Tag,
1505    ) -> Result<(), Status> {
1506        let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
1507        full(w.start_structure(tag))?;
1508        full(w.unsigned(Tag::Context(0), u64::from(status.value())))?;
1509        if status.is_ok()
1510            && let Some(index) = index
1511        {
1512            full(w.unsigned(Tag::Context(1), u64::from(index.0)))?;
1513        }
1514        full(w.end_container())
1515    }
1516}
1517
1518impl<C: Config, K: KeyStore, R: Rng, const N: usize> OperationalCredentials<'_, C, K, R, N> {
1519    /// Runs one command of §11.18.6.
1520    ///
1521    /// This is what [`ClusterHandler::invoke`] forwards to; it is public because the
1522    /// commands are worth driving directly from a test or a controller-side harness.
1523    pub fn run(
1524        &self,
1525        command: CommandId,
1526        fields: Option<&[u8]>,
1527        ctx: &InteractionContext<'_>,
1528        w: &mut TlvWriter<'_>,
1529        tag: Tag,
1530    ) -> Result<Option<CommandId>, Status> {
1531        // Anything left over from a fail-safe period that has ended must not be adopted by
1532        // this one.
1533        self.reap(ctx.now);
1534
1535        match command {
1536            ATTESTATION_REQUEST => {
1537                let mut nonce = None;
1538                walk_fields(fields, |number, element| match number {
1539                    0 => {
1540                        set_once(
1541                            &mut nonce,
1542                            decode_nonce::<{ attestation::ATTESTATION_NONCE_LEN }>(element)?,
1543                        )
1544                        .map_err(|_| Status::InvalidCommand)?;
1545                        Ok(true)
1546                    }
1547                    _ => Ok(false),
1548                })?;
1549                let nonce = nonce.ok_or(Status::InvalidCommand)?;
1550                let challenge = ctx.attestation_challenge.ok_or(Status::UnsupportedAccess)?;
1551                // §11.18.4.7: "The timestamp field SHALL be in epoch-s." A node with no
1552                // wall clock reports zero, which is what `Clock::utc` returning `None` means
1553                // and what every commissioner already tolerates.
1554                self.attestation_response(&nonce, 0, challenge, w, tag)?;
1555                Ok(Some(ATTESTATION_RESPONSE))
1556            }
1557            CERTIFICATE_CHAIN_REQUEST => {
1558                let mut kind = None;
1559                walk_fields(fields, |number, element| match number {
1560                    0 => {
1561                        let value = element.unsigned().map_err(|_| Status::InvalidCommand)?;
1562                        let value = u8::try_from(value).map_err(|_| Status::InvalidCommand)?;
1563                        let kind_value = CertificateChainType::from_value(value)
1564                            .ok_or(Status::InvalidCommand)?;
1565                        set_once(&mut kind, kind_value).map_err(|_| Status::InvalidCommand)?;
1566                        Ok(true)
1567                    }
1568                    _ => Ok(false),
1569                })?;
1570                let certificate = match kind.ok_or(Status::InvalidCommand)? {
1571                    CertificateChainType::Dac => self.attestation.dac,
1572                    CertificateChainType::Pai => self.attestation.pai,
1573                };
1574                let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
1575                full(w.start_structure(tag))?;
1576                full(w.octets(Tag::Context(0), certificate))?;
1577                full(w.end_container())?;
1578                Ok(Some(CERTIFICATE_CHAIN_RESPONSE))
1579            }
1580            CSR_REQUEST => {
1581                let mut nonce = None;
1582                let mut for_update = None;
1583                walk_fields(fields, |number, element| match number {
1584                    0 => {
1585                        set_once(
1586                            &mut nonce,
1587                            decode_nonce::<{ attestation::CSR_NONCE_LEN }>(element)?,
1588                        )
1589                        .map_err(|_| Status::InvalidCommand)?;
1590                        Ok(true)
1591                    }
1592                    1 => {
1593                        let value = element.bool().map_err(|_| Status::InvalidCommand)?;
1594                        set_once(&mut for_update, value).map_err(|_| Status::InvalidCommand)?;
1595                        Ok(true)
1596                    }
1597                    _ => Ok(false),
1598                })?;
1599                let nonce = nonce.ok_or(Status::InvalidCommand)?;
1600                // `IsForUpdateNOC` is optional with a fallback of false.
1601                let mut random = [0u8; 32];
1602                self.rng
1603                    .borrow_mut()
1604                    .fill(&mut random)
1605                    .map_err(|_| Status::Failure)?;
1606                self.csr_response(&nonce, for_update.unwrap_or(false), ctx, &random, w, tag)?;
1607                Ok(Some(CSR_RESPONSE))
1608            }
1609            ADD_NOC => {
1610                let mut noc = None;
1611                let mut icac = None;
1612                let mut ipk = None;
1613                let mut subject = None;
1614                let mut vendor = None;
1615                walk_fields(fields, |number, element| {
1616                    match number {
1617                        0 => set_once(
1618                            &mut noc,
1619                            element.octets().map_err(|_| Status::InvalidCommand)?,
1620                        ),
1621                        1 => set_once(
1622                            &mut icac,
1623                            element.octets().map_err(|_| Status::InvalidCommand)?,
1624                        ),
1625                        2 => set_once(
1626                            &mut ipk,
1627                            decode_nonce::<{ crate::crypto::SYMMETRIC_KEY_LENGTH_BYTES }>(element)?,
1628                        ),
1629                        3 => set_once(
1630                            &mut subject,
1631                            element.unsigned().map_err(|_| Status::InvalidCommand)?,
1632                        ),
1633                        4 => {
1634                            let value = element.unsigned().map_err(|_| Status::InvalidCommand)?;
1635                            let value =
1636                                u16::try_from(value).map_err(|_| Status::ConstraintError)?;
1637                            set_once(&mut vendor, VendorId(value))
1638                        }
1639                        _ => return Ok(false),
1640                    }
1641                    .map_err(|_| Status::InvalidCommand)?;
1642                    Ok(true)
1643                })?;
1644                let request = AddNocRequest {
1645                    noc: noc.ok_or(Status::InvalidCommand)?,
1646                    icac,
1647                    ipk: ipk.ok_or(Status::InvalidCommand)?,
1648                    case_admin_subject: subject.ok_or(Status::InvalidCommand)?,
1649                    admin_vendor_id: vendor.ok_or(Status::InvalidCommand)?,
1650                };
1651                let status = self.add_noc(&request, ctx)?;
1652                Self::noc_response(status, self.changed_index(), w, tag)?;
1653                Ok(Some(NOC_RESPONSE))
1654            }
1655            UPDATE_NOC => {
1656                let mut noc = None;
1657                let mut icac = None;
1658                walk_fields(fields, |number, element| {
1659                    match number {
1660                        0 => set_once(
1661                            &mut noc,
1662                            element.octets().map_err(|_| Status::InvalidCommand)?,
1663                        ),
1664                        1 => set_once(
1665                            &mut icac,
1666                            element.octets().map_err(|_| Status::InvalidCommand)?,
1667                        ),
1668                        _ => return Ok(false),
1669                    }
1670                    .map_err(|_| Status::InvalidCommand)?;
1671                    Ok(true)
1672                })?;
1673                let status = self.update_noc(noc.ok_or(Status::InvalidCommand)?, icac, ctx)?;
1674                Self::noc_response(status, self.changed_index(), w, tag)?;
1675                Ok(Some(NOC_RESPONSE))
1676            }
1677            UPDATE_FABRIC_LABEL => {
1678                let mut label = None;
1679                walk_fields(fields, |number, element| match number {
1680                    0 => {
1681                        set_once(
1682                            &mut label,
1683                            element.utf8().map_err(|_| Status::InvalidCommand)?,
1684                        )
1685                        .map_err(|_| Status::InvalidCommand)?;
1686                        Ok(true)
1687                    }
1688                    _ => Ok(false),
1689                })?;
1690                let status = self.update_fabric_label(label.ok_or(Status::InvalidCommand)?, ctx)?;
1691                Self::noc_response(status, ctx.fabric_index, w, tag)?;
1692                Ok(Some(NOC_RESPONSE))
1693            }
1694            REMOVE_FABRIC => {
1695                let mut index = None;
1696                walk_fields(fields, |number, element| match number {
1697                    0 => {
1698                        let value = element.unsigned().map_err(|_| Status::InvalidCommand)?;
1699                        let value = u8::try_from(value).map_err(|_| Status::ConstraintError)?;
1700                        set_once(&mut index, FabricIndex(value))
1701                            .map_err(|_| Status::InvalidCommand)?;
1702                        Ok(true)
1703                    }
1704                    _ => Ok(false),
1705                })?;
1706                let index = index.ok_or(Status::InvalidCommand)?;
1707                let status = self.remove_fabric(index, ctx)?;
1708                Self::noc_response(status, Some(index), w, tag)?;
1709                Ok(Some(NOC_RESPONSE))
1710            }
1711            ADD_TRUSTED_ROOT_CERTIFICATE => {
1712                let mut rcac = None;
1713                walk_fields(fields, |number, element| match number {
1714                    0 => {
1715                        set_once(
1716                            &mut rcac,
1717                            element.octets().map_err(|_| Status::InvalidCommand)?,
1718                        )
1719                        .map_err(|_| Status::InvalidCommand)?;
1720                        Ok(true)
1721                    }
1722                    _ => Ok(false),
1723                })?;
1724                self.add_trusted_root(rcac.ok_or(Status::InvalidCommand)?, ctx)?;
1725                // No response command: §11.18.6's table gives `Y`, so success is a plain
1726                // SUCCESS status.
1727                Ok(None)
1728            }
1729            SET_VID_VERIFICATION_STATEMENT => {
1730                let mut vendor = None;
1731                let mut statement = None;
1732                let mut vvsc = None;
1733                walk_fields(fields, |number, element| {
1734                    match number {
1735                        0 => {
1736                            let value = element.unsigned().map_err(|_| Status::InvalidCommand)?;
1737                            let value =
1738                                u16::try_from(value).map_err(|_| Status::ConstraintError)?;
1739                            set_once(&mut vendor, VendorId(value))
1740                        }
1741                        1 => set_once(
1742                            &mut statement,
1743                            element.octets().map_err(|_| Status::InvalidCommand)?,
1744                        ),
1745                        2 => set_once(
1746                            &mut vvsc,
1747                            element.octets().map_err(|_| Status::InvalidCommand)?,
1748                        ),
1749                        _ => return Ok(false),
1750                    }
1751                    .map_err(|_| Status::InvalidCommand)?;
1752                    Ok(true)
1753                })?;
1754                self.set_vid_verification_statement(vendor, statement, vvsc, ctx)?;
1755                Ok(None)
1756            }
1757            SIGN_VID_VERIFICATION_REQUEST => {
1758                let mut index = None;
1759                let mut challenge = None;
1760                walk_fields(fields, |number, element| {
1761                    match number {
1762                        0 => {
1763                            let value = element.unsigned().map_err(|_| Status::InvalidCommand)?;
1764                            let value = u8::try_from(value).map_err(|_| Status::ConstraintError)?;
1765                            set_once(&mut index, FabricIndex(value))
1766                        }
1767                        1 => set_once(&mut challenge, decode_nonce::<32>(element)?),
1768                        _ => return Ok(false),
1769                    }
1770                    .map_err(|_| Status::InvalidCommand)?;
1771                    Ok(true)
1772                })?;
1773                self.sign_vid_verification(
1774                    index.ok_or(Status::InvalidCommand)?,
1775                    &challenge.ok_or(Status::InvalidCommand)?,
1776                    ctx,
1777                    w,
1778                    tag,
1779                )?;
1780                Ok(Some(SIGN_VID_VERIFICATION_RESPONSE))
1781            }
1782            _ => Err(Status::UnsupportedCommand),
1783        }
1784    }
1785
1786    /// The index the change just recorded touched, without consuming it.
1787    fn changed_index(&self) -> Option<FabricIndex> {
1788        match self.change.get()? {
1789            FabricChange::Added { index, .. }
1790            | FabricChange::Updated { index }
1791            | FabricChange::Removed { index, .. } => Some(index),
1792        }
1793    }
1794}