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}
426
427impl<'a, C: Config, K: KeyStore, R: Rng, const N: usize> OperationalCredentials<'a, C, K, R, N> {
428    /// The cluster over a device's fabric table, key store and fail-safe.
429    #[must_use]
430    pub fn new(
431        fabrics: &'a RefCell<FabricTable<C, N>>,
432        keys: &'a RefCell<K>,
433        rng: &'a RefCell<R>,
434        fail_safe: &'a RefCell<crate::commissioning::failsafe::FailSafe>,
435        attestation: DeviceAttestation<'a>,
436    ) -> Self {
437        Self {
438            fabrics,
439            keys,
440            rng,
441            fail_safe,
442            attestation,
443            pending_root: RefCell::new(None),
444            pending_csr: Cell::new(None),
445            change: Cell::new(None),
446        }
447    }
448
449    /// Takes the work the last credential-changing command left behind.
450    ///
451    /// A device calls this after every invoke against this cluster. Forgetting to means a
452    /// fabric is joined with no administrator able to reach it (§11.18.6.8 step 7), or a
453    /// removed fabric's sessions stay open.
454    #[must_use]
455    pub fn take_change(&self) -> Option<FabricChange> {
456        self.change.take()
457    }
458
459    /// Discards any fail-safe-scoped state, destroying the operational key a `CSRRequest`
460    /// generated and nothing used.
461    ///
462    /// Call this when the fail-safe expires — it is §11.10.7.2.2 step 8, "the new operational
463    /// key pair temporarily generated for the purposes of NOC addition or update … SHALL be
464    /// removed as it is no longer needed" — and it is idempotent.
465    pub fn discard_pending(&self) {
466        *self.pending_root.borrow_mut() = None;
467        if let Some(pending) = self.pending_csr.take() {
468            let _ = self.keys.borrow_mut().remove(pending.key);
469        }
470    }
471
472    /// Drops fail-safe-scoped state that belongs to a context which has since ended.
473    ///
474    /// The fail-safe's own [`Progress`](crate::commissioning::failsafe::Progress) is reset
475    /// when a new context is armed, so a `csr_requested` that is no longer set means this
476    /// cluster's pending key belongs to a period that is over. Checking it here is what keeps
477    /// a stale key from being adopted by the *next* commissioner's `AddNOC`.
478    fn reap(&self, now: crate::platform::Instant) {
479        let progress = self
480            .fail_safe
481            .borrow()
482            .armed(now)
483            .map(|armed| armed.progress);
484        let Some(progress) = progress else {
485            self.discard_pending();
486            return;
487        };
488        if !progress.csr_requested
489            && let Some(pending) = self.pending_csr.take()
490        {
491            let _ = self.keys.borrow_mut().remove(pending.key);
492        }
493        if !progress.added_trusted_root {
494            *self.pending_root.borrow_mut() = None;
495        }
496    }
497
498    /// The fail-safe's progress, or `FAILSAFE_REQUIRED` when nothing is armed.
499    ///
500    /// Every credential-changing command starts here: §11.18.6.5, §11.18.6.8, §11.18.6.9 and
501    /// §11.18.6.13 all say "If this command is received without an armed fail-safe context …
502    /// then this command SHALL fail with a FAILSAFE_REQUIRED status code".
503    fn require_fail_safe(
504        &self,
505        now: crate::platform::Instant,
506    ) -> Result<crate::commissioning::failsafe::Progress, Status> {
507        self.fail_safe
508            .borrow()
509            .armed(now)
510            .map(|armed| armed.progress)
511            .ok_or(Status::FailsafeRequired)
512    }
513}
514
515// --- The commands ------------------------------------------------------------------------------
516
517impl<C: Config, K: KeyStore, R: Rng, const N: usize> OperationalCredentials<'_, C, K, R, N> {
518    /// `AttestationRequest` (§11.18.6.1) → `AttestationResponse` (§11.18.6.2).
519    ///
520    /// Writes `AttestationElements [0]` and `AttestationSignature [1]` under `tag`.
521    ///
522    /// The signature is over `attestation_elements_message || attestation_challenge`, and the
523    /// elements are signed **exactly as they will be sent** — not re-encoded. A device whose
524    /// encoder differed from its signer's by one octet would produce a response no
525    /// commissioner could verify, and the failure would look like a bad key.
526    pub fn attestation_response(
527        &self,
528        nonce: &[u8; attestation::ATTESTATION_NONCE_LEN],
529        timestamp: u32,
530        challenge: &SymmetricKey,
531        w: &mut TlvWriter<'_>,
532        tag: Tag,
533    ) -> Result<(), Status> {
534        let elements = AttestationElements {
535            certification_declaration: self.attestation.certification_declaration,
536            attestation_nonce: *nonce,
537            timestamp,
538            firmware_information: self.attestation.firmware_information,
539        };
540        let mut buf = [0u8; RESP_MAX];
541        let encoded = elements.encode(&mut buf).map_err(|_| Status::Failure)?;
542        let signature = attestation::sign_attestation(
543            &*self.keys.borrow(),
544            self.attestation.dac_key,
545            encoded,
546            challenge,
547        )
548        .map_err(|_| Status::Failure)?;
549
550        let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
551        full(w.start_structure(tag))?;
552        full(w.octets(Tag::Context(0), encoded))?;
553        full(w.octets(Tag::Context(1), signature.as_bytes()))?;
554        full(w.end_container())
555    }
556
557    /// `CSRRequest` (§11.18.6.5) → `CSRResponse` (§11.18.6.6).
558    ///
559    /// Generates a fresh operational key pair, builds a PKCS#10 CSR over it, and signs the
560    /// whole `nocsr_elements_message` with the *attestation* key. Two signatures over two
561    /// different things: the CSR's own proves possession of the new operational key, and the
562    /// outer one binds the request to the attested device and the live session.
563    pub fn csr_response(
564        &self,
565        nonce: &[u8; attestation::CSR_NONCE_LEN],
566        for_update: bool,
567        ctx: &InteractionContext<'_>,
568        random: &[u8; 32],
569        w: &mut TlvWriter<'_>,
570        tag: Tag,
571    ) -> Result<(), Status> {
572        let progress = self.require_fail_safe(ctx.now)?;
573        // "If a prior UpdateNOC or AddNOC command was successfully executed within the
574        // fail-safe timer period, then this command SHALL fail with a CONSTRAINT_ERROR."
575        if progress.added_noc || progress.updated_noc {
576            return Err(Status::ConstraintError);
577        }
578        // "If the IsForUpdateNOC field is present and set to true, but the command was
579        // received over a PASE session, the command SHALL fail with an INVALID_COMMAND status
580        // code, as it would never be possible to use a resulting subsequent certificate …
581        // with the UpdateNOC command, which is forbidden over PASE sessions."
582        if for_update && ctx.fabric_index.is_none() {
583            return Err(Status::InvalidCommand);
584        }
585        let challenge = ctx.attestation_challenge.ok_or(Status::UnsupportedAccess)?;
586
587        // A CSRRequest that replaces an earlier one in the same period must not leak the
588        // earlier key: there is exactly one candidate operational key at a time.
589        if let Some(previous) = self.pending_csr.take() {
590            let _ = self.keys.borrow_mut().remove(previous.key);
591        }
592
593        let (key, public) = self
594            .keys
595            .borrow_mut()
596            .generate(crate::crypto::KeyPurpose::Operational, random)
597            .map_err(|_| Status::Failure)?;
598
599        let mut csr_buf = [0u8; attestation::nocsr::MAX_CSR_LEN];
600        let csr = crate::attestation::nocsr::build_csr(&*self.keys.borrow(), key, &mut csr_buf)
601            .map_err(|_| Status::Failure)?;
602        let elements = crate::attestation::nocsr::NocsrElements::new(csr, *nonce);
603        let mut elements_buf = [0u8; RESP_MAX];
604        let encoded = elements
605            .encode(&mut elements_buf)
606            .map_err(|_| Status::Failure)?;
607        let signature = crate::attestation::nocsr::sign_nocsr(
608            &*self.keys.borrow(),
609            self.attestation.dac_key,
610            encoded,
611            challenge,
612        )
613        .map_err(|_| Status::Failure)?;
614
615        self.pending_csr.set(Some(PendingCsr {
616            session: ctx.session,
617            key,
618            public,
619            for_update,
620        }));
621        self.fail_safe
622            .borrow_mut()
623            .record(ctx.now, |p| p.csr_requested = true)
624            .map_err(|_| Status::FailsafeRequired)?;
625
626        let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
627        full(w.start_structure(tag))?;
628        full(w.octets(Tag::Context(0), encoded))?;
629        full(w.octets(Tag::Context(1), signature.as_bytes()))?;
630        full(w.end_container())
631    }
632
633    /// `AddTrustedRootCertificate` (§11.18.6.13).
634    ///
635    /// No response command: success is a plain `SUCCESS` status. The certificate is *pending*
636    /// until an `AddNOC` adopts it — §11.18.6.13 is explicit that the only way to remove a
637    /// trusted root is to remove the fabric that uses it, so one installed by a fail-safe
638    /// that then expired must never have been installed at all.
639    pub fn add_trusted_root(
640        &self,
641        rcac: &[u8],
642        ctx: &InteractionContext<'_>,
643    ) -> Result<(), Status> {
644        let progress = self.require_fail_safe(ctx.now)?;
645        // "If a prior AddTrustedRootCertificate command was successfully invoked within the
646        // fail-safe timer period, which would cause the new invocation to add a second root
647        // certificate within a given fail-safe timer period, then this command SHALL fail
648        // with a CONSTRAINT_ERROR."
649        if progress.added_trusted_root {
650            return Err(Status::ConstraintError);
651        }
652        if progress.added_noc || progress.updated_noc {
653            return Err(Status::ConstraintError);
654        }
655        // "If the certificate … fails any validity checks, not fulfilling all the
656        // requirements for a valid Matter Certificate Encoding representation, including a
657        // truncated or oversize value, then this command SHALL fail with an INVALID_COMMAND."
658        let parsed = MatterCertificate::decode(rcac).map_err(|_| Status::InvalidCommand)?;
659        parsed
660            .validate_as(crate::cert::CertType::Rcac)
661            .map_err(|_| Status::InvalidCommand)?;
662        // "fails any validity checks" covers the signature, and this is the only moment it can
663        // be checked. §6.4.5.3 trusts a root by *provenance* rather than by its signature, so
664        // nothing downstream ever verifies it: `verify_chain` checks the NOC and the ICAC
665        // against this root's public key and takes the root itself as given. A root with a
666        // corrupt or forged signature that is accepted here is therefore accepted for the
667        // lifetime of the fabric, and every certificate under it verifies perfectly.
668        //
669        // A self-signature proves only that whoever produced the certificate held the key
670        // inside it, which is exactly the claim a root makes about itself. Rejecting one that
671        // fails costs an administrator nothing it did not already have.
672        if !crate::cert::verify_self_signed(&parsed).unwrap_or(false) {
673            return Err(Status::InvalidCommand);
674        }
675        let stored = heapless::Vec::from_slice(rcac).map_err(|_| Status::ResourceExhausted)?;
676
677        *self.pending_root.borrow_mut() = Some(stored);
678        self.fail_safe
679            .borrow_mut()
680            .record(ctx.now, |p| p.added_trusted_root = true)
681            .map_err(|_| Status::FailsafeRequired)?;
682        Ok(())
683    }
684}
685
686/// `AddNOC`'s fields (§11.18.6.8).
687#[derive(Debug, Clone, Copy)]
688pub struct AddNocRequest<'a> {
689    /// `NOCValue [0]` — the node operational certificate, Matter TLV, max 400.
690    pub noc: &'a [u8],
691    /// `ICACValue [1]` — the intermediate, if the chain has one.
692    pub icac: Option<&'a [u8]>,
693    /// `IPKValue [2]` — the epoch key for the Identity Protection Key, 16 octets.
694    ///
695    /// "This is needed to bootstrap a necessary configuration value for subsequent CASE to
696    /// succeed", and having provided it is equivalent to a `KeySetWrite` of group key set 0.
697    pub ipk: [u8; crate::crypto::SYMMETRIC_KEY_LENGTH_BYTES],
698    /// `CaseAdminSubject [3]` — the subject that gets Administer over the new fabric.
699    pub case_admin_subject: u64,
700    /// `AdminVendorId [4]` — "the Vendor ID of the entity issuing the AddNOC command".
701    pub admin_vendor_id: VendorId,
702}
703
704impl<C: Config, K: KeyStore, R: Rng, const N: usize> OperationalCredentials<'_, C, K, R, N> {
705    /// `AddNOC` (§11.18.6.8) — join a fabric.
706    ///
707    /// Returns the `StatusCode` for the `NOCResponse`, and on success records a
708    /// [`FabricChange::Added`] for [`OperationalCredentials::take_change`].
709    ///
710    /// Every failure here "SHALL leave all non-volatile state of the device untouched, as if
711    /// the AddNOC command had never been received. **The information about the last CSR state
712    /// associated with this session SHALL also be untouched** in this case, so that a valid
713    /// AddNOC command MAY still be issued later that would match that CSR state." So the
714    /// pending key is consumed only on the success path — a commissioner that sent a
715    /// malformed NOC gets to try again without another `CSRRequest`.
716    pub fn add_noc(
717        &self,
718        request: &AddNocRequest<'_>,
719        ctx: &InteractionContext<'_>,
720    ) -> Result<NocStatus, Status> {
721        let progress = self.require_fail_safe(ctx.now)?;
722        // These three are *status codes*, not NOCResponse error codes: the command never runs.
723        if progress.added_noc || progress.updated_noc {
724            return Err(Status::ConstraintError);
725        }
726        let Some(pending) = self.pending_csr.get() else {
727            return Ok(NocStatus::MissingCsr);
728        };
729        if pending.session != ctx.session {
730            // §11.18.6.7: the CSR record is scoped to "the same secure session". A key
731            // generated for one administrator must not be adopted by another's AddNOC.
732            return Ok(NocStatus::MissingCsr);
733        }
734        // "If the prior CSRRequest state that preceded AddNOC had the IsForUpdateNOC field
735        // indicated as true, then this command SHALL fail with a CONSTRAINT_ERROR."
736        if pending.for_update {
737            return Err(Status::ConstraintError);
738        }
739
740        // "If no prior AddTrustedRootCertificate command was successfully executed within the
741        // fail-safe timer period, then … InvalidNOC … even if some other fabric already uses
742        // the exact same root of trust certificate."
743        let pending_root = self.pending_root.borrow();
744        let Some(rcac_bytes) = pending_root
745            .as_deref()
746            .filter(|_| progress.added_trusted_root)
747        else {
748            return Ok(NocStatus::InvalidNoc);
749        };
750
751        // §11.18.6.7's validation comes first: it is described as happening "Upon receipt",
752        // before any of AddNOC's own preconditions, and it is what turns the certificate into
753        // an identity the rules below can talk about.
754        let identity = match validate_chain(request.noc, request.icac, rcac_bytes, &pending.public)
755        {
756            Ok(identity) => identity,
757            Err(status) => return Ok(status),
758        };
759
760        let mut table = self.fabrics.borrow_mut();
761        // "If the NOC provided in the NOCValue encodes an Operational Identifier for a <Root
762        // Public Key, FabricID> pair already present on the device … FabricConflict."
763        //
764        // Before `TableFull`, which is the order §11.18.6.8 lists them in: an administrator
765        // that should have sent `UpdateNOC` is told so even on a full device, which is the
766        // more useful of the two answers.
767        let compressed =
768            crate::fabric::compressed_fabric_id(&identity.root_public_key, identity.fabric_id)
769                .map_err(|_| Status::Failure)?;
770        if table.find_by_compressed(compressed).is_some() {
771            return Ok(NocStatus::FabricConflict);
772        }
773        // "If the device already has the CommissionedFabrics attribute equal to the
774        // SupportedFabrics attribute … TableFull."
775        if table.len() >= table.capacity() {
776            return Ok(NocStatus::TableFull);
777        }
778        // "If the CaseAdminSubject field is not a valid ACL subject in the context of AuthMode
779        // set to CASE, such as not being in either the Operational or CASE Authenticated Tag
780        // range … InvalidAdminSubject."
781        if !is_case_subject(request.case_admin_subject) {
782            return Ok(NocStatus::InvalidAdminSubject);
783        }
784
785        let mut credentials = match Credentials::new(request.noc, rcac_bytes) {
786            Ok(credentials) => credentials,
787            Err(_) => return Ok(NocStatus::InvalidNoc),
788        };
789        if let Some(icac) = request.icac {
790            credentials = match credentials.with_icac(icac) {
791                Ok(credentials) => credentials,
792                Err(_) => return Ok(NocStatus::InvalidNoc),
793            };
794        }
795
796        let index = table.allocate_index().map_err(|_| Status::Failure)?;
797        let fabric = Fabric::new(
798            index,
799            FabricIdentity {
800                fabric_id: identity.fabric_id,
801                node_id: identity.node_id,
802                root_public_key: identity.root_public_key,
803                admin_vendor_id: request.admin_vendor_id,
804            },
805            &SymmetricKey::new(request.ipk),
806            pending.key,
807            credentials,
808        );
809        let Ok(fabric) = fabric else {
810            return Ok(NocStatus::InvalidNoc);
811        };
812        if table.insert(fabric).is_err() {
813            return Ok(NocStatus::FabricConflict);
814        }
815        drop(table);
816        drop(pending_root);
817
818        // Only now is the pending state consumed: every path above left it intact.
819        self.pending_csr.set(None);
820        *self.pending_root.borrow_mut() = None;
821
822        // Step 9: "The Fabric Index associated with the armed fail-safe context SHALL be
823        // updated to match the Fabric Index just allocated." Without it, the
824        // `CommissioningComplete` that follows over CASE on the new fabric would not match.
825        let mut fail_safe = self.fail_safe.borrow_mut();
826        fail_safe
827            .record(ctx.now, |p| p.added_noc = true)
828            .map_err(|_| Status::FailsafeRequired)?;
829        fail_safe
830            .adopt_fabric(index, ctx.now)
831            .map_err(|_| Status::FailsafeRequired)?;
832        drop(fail_safe);
833
834        self.change.set(Some(FabricChange::Added {
835            index,
836            case_admin_subject: request.case_admin_subject,
837            bind_pase_session: ctx.fabric_index.is_none(),
838        }));
839        Ok(NocStatus::Ok)
840    }
841
842    /// `UpdateNOC` (§11.18.6.9) — rotate the operational key and certificate on a fabric
843    /// this node already belongs to.
844    pub fn update_noc(
845        &self,
846        noc: &[u8],
847        icac: Option<&[u8]>,
848        ctx: &InteractionContext<'_>,
849    ) -> Result<NocStatus, Status> {
850        let progress = self.require_fail_safe(ctx.now)?;
851        if progress.added_noc || progress.updated_noc {
852            return Err(Status::ConstraintError);
853        }
854        // "If a prior AddTrustedRootCertificate command was successfully invoked within the
855        // fail-safe timer period, then this command SHALL fail with a CONSTRAINT_ERROR …
856        // since the only valid following logical operation is invoking the AddNOC command."
857        if progress.added_trusted_root {
858            return Err(Status::ConstraintError);
859        }
860        let Some(pending) = self.pending_csr.get() else {
861            return Ok(NocStatus::MissingCsr);
862        };
863        if pending.session != ctx.session {
864            return Ok(NocStatus::MissingCsr);
865        }
866        // "If the prior CSRRequest state that preceded UpdateNOC had the IsForUpdateNOC field
867        // indicated as false, then this command SHALL fail with a CONSTRAINT_ERROR."
868        if !pending.for_update {
869            return Err(Status::ConstraintError);
870        }
871        // The command is `AF`, so §8.8.2.3 step b.v has already refused it without a fabric.
872        let accessing = ctx.fabric_index.ok_or(Status::UnsupportedAccess)?;
873
874        let mut table = self.fabrics.borrow_mut();
875        let Some(existing) = table.find(accessing) else {
876            return Ok(NocStatus::InvalidFabricIndex);
877        };
878        let rcac = existing.credentials.rcac.clone();
879        let existing_fabric_id = existing.fabric_id;
880
881        let identity = match validate_chain(noc, icac, &rcac, &pending.public) {
882            Ok(identity) => identity,
883            Err(status) => return Ok(status),
884        };
885        // "The NOC provided in the NOCValue does not refer in its subject to the FabricID
886        // associated with the accessing fabric" — and the same for the ICAC.
887        if identity.fabric_id != existing_fabric_id {
888            return Ok(NocStatus::InvalidNoc);
889        }
890
891        let mut credentials = match Credentials::new(noc, &rcac) {
892            Ok(credentials) => credentials,
893            Err(_) => return Ok(NocStatus::InvalidNoc),
894        };
895        if let Some(icac) = icac {
896            credentials = match credentials.with_icac(icac) {
897                Ok(credentials) => credentials,
898                Err(_) => return Ok(NocStatus::InvalidNoc),
899            };
900        }
901
902        let Some(fabric) = table.find_mut(accessing) else {
903            return Ok(NocStatus::InvalidFabricIndex);
904        };
905        let previous_key = fabric.operational_key;
906        fabric.node_id = identity.node_id;
907        fabric.credentials = credentials;
908        fabric.operational_key = pending.key;
909        drop(table);
910
911        // Step 1.c: "All internal data reflecting the prior operational identifier … SHALL be
912        // revoked and removed." The previous operational key is the first of those, and it is
913        // the one whose survival would silently keep the old identity usable.
914        let _ = self.keys.borrow_mut().remove(previous_key);
915        self.pending_csr.set(None);
916
917        self.fail_safe
918            .borrow_mut()
919            .record(ctx.now, |p| p.updated_noc = true)
920            .map_err(|_| Status::FailsafeRequired)?;
921        self.change
922            .set(Some(FabricChange::Updated { index: accessing }));
923        Ok(NocStatus::Ok)
924    }
925
926    /// `UpdateFabricLabel` (§11.18.6.11).
927    pub fn update_fabric_label(
928        &self,
929        label: &str,
930        ctx: &InteractionContext<'_>,
931    ) -> Result<NocStatus, Status> {
932        let accessing = ctx.fabric_index.ok_or(Status::UnsupportedAccess)?;
933        let mut table = self.fabrics.borrow_mut();
934        // "If the Label field is identical to a Label already in use by a Fabric within the
935        // Fabrics list **that is not the accessing fabric** … LabelConflict."
936        if table
937            .iter()
938            .any(|f| f.index != accessing && f.label.as_str() == label && !label.is_empty())
939        {
940            return Ok(NocStatus::LabelConflict);
941        }
942        let Some(fabric) = table.find_mut(accessing) else {
943            return Ok(NocStatus::InvalidFabricIndex);
944        };
945        // "max 32" — longer is a constraint error, not a truncation.
946        fabric
947            .set_label(label)
948            .map_err(|_| Status::ConstraintError)?;
949        Ok(NocStatus::Ok)
950    }
951
952    /// `RemoveFabric` (§11.18.6.12) — leave a fabric, and delete everything scoped to it.
953    ///
954    /// The index is a *parameter*, not the accessing fabric: an administrator may remove a
955    /// fabric other than its own, which is why the command is `A` rather than `AF`. The three
956    /// outcomes §11.18.6.12 distinguishes differ only in what else goes with it, and
957    /// [`FabricChange::Removed`] carries which one happened.
958    pub fn remove_fabric(
959        &self,
960        index: FabricIndex,
961        ctx: &InteractionContext<'_>,
962    ) -> Result<NocStatus, Status> {
963        let mut table = self.fabrics.borrow_mut();
964        // "If the FabricIndex field does not match the FabricIndex of any entry within the
965        // Fabrics list, then an NOCResponse with a StatusCode of InvalidFabricIndex SHALL be
966        // returned … and there SHALL NOT be any permanent changes to any device data."
967        let Some(removed) = table.remove(index) else {
968            return Ok(NocStatus::InvalidFabricIndex);
969        };
970        let was_last = table.is_empty();
971        drop(table);
972
973        // The operational key has to actually be destroyed, not merely forgotten: a fabric
974        // whose key survived removal could still be impersonated by anything that reaches the
975        // key store.
976        let _ = self.keys.borrow_mut().remove(removed.operational_key);
977
978        self.change.set(Some(FabricChange::Removed {
979            index,
980            was_last,
981            was_accessing: ctx.fabric_index == Some(index),
982        }));
983        Ok(NocStatus::Ok)
984    }
985
986    /// `SetVIDVerificationStatement` (§11.18.6.14).
987    ///
988    /// All three fields are optional and at least one must be present (`O.a+`). The command
989    /// "SHALL only operate against the Fabrics and NOCs attribute entries associated with the
990    /// accessing fabric index", which is what `AF` enforces before it reaches here.
991    pub fn set_vid_verification_statement(
992        &self,
993        vendor_id: Option<VendorId>,
994        statement: Option<&[u8]>,
995        vvsc: Option<&[u8]>,
996        ctx: &InteractionContext<'_>,
997    ) -> Result<(), Status> {
998        if vendor_id.is_none() && statement.is_none() && vvsc.is_none() {
999            // `O.a+`: "at least one of the marked fields SHALL be present".
1000            return Err(Status::InvalidCommand);
1001        }
1002        let accessing = ctx.fabric_index.ok_or(Status::UnsupportedAccess)?;
1003        let mut table = self.fabrics.borrow_mut();
1004        let Some(fabric) = table.find_mut(accessing) else {
1005            return Err(Status::ConstraintError);
1006        };
1007
1008        if let Some(statement) = statement {
1009            match statement.len() {
1010                // "If the length of the field's value is exactly 0, then the
1011                // VIDVerificationStatement field … SHALL be erased."
1012                0 => fabric.vid_verification_statement = None,
1013                VID_VERIFICATION_STATEMENT_LEN => {
1014                    let mut value = [0u8; VID_VERIFICATION_STATEMENT_LEN];
1015                    value.copy_from_slice(statement);
1016                    fabric.vid_verification_statement = Some(value);
1017                }
1018                // "If the length … is neither exactly 0 nor exactly 85, then the command
1019                // SHALL fail with a status code of CONSTRAINT_ERROR."
1020                _ => return Err(Status::ConstraintError),
1021            }
1022        }
1023        if let Some(vvsc) = vvsc {
1024            // A VVSC alongside an ICAC is INVALID_COMMAND, which `set_vvsc` reports as an
1025            // argument error (§11.18.4.4's mutual exclusion).
1026            fabric
1027                .credentials
1028                .set_vvsc(vvsc)
1029                .map_err(|_| Status::InvalidCommand)?;
1030        }
1031        if let Some(vendor_id) = vendor_id {
1032            fabric.admin_vendor_id = vendor_id;
1033        }
1034        Ok(())
1035    }
1036
1037    /// `SignVIDVerificationRequest` (§11.18.6.15) → `SignVIDVerificationResponse`
1038    /// (§11.18.6.16).
1039    ///
1040    /// Signs §6.4.10's `vendor_id_verification_tbs` with the *operational* key of the fabric
1041    /// under verification — not the attestation key. The procedure proves that whoever holds
1042    /// that fabric's NOC stands behind the `VendorID` the fabric claims, which is a statement
1043    /// about the fabric rather than about the hardware.
1044    pub fn sign_vid_verification(
1045        &self,
1046        index: FabricIndex,
1047        client_challenge: &[u8; 32],
1048        ctx: &InteractionContext<'_>,
1049        w: &mut TlvWriter<'_>,
1050        tag: Tag,
1051    ) -> Result<(), Status> {
1052        let challenge = ctx.attestation_challenge.ok_or(Status::UnsupportedAccess)?;
1053        let table = self.fabrics.borrow();
1054        // "If the FabricIndex field contains a fabric index which does not have an associated
1055        // entry in the Fabrics attribute, then the command SHALL fail with a status code of
1056        // CONSTRAINT_ERROR."
1057        let fabric = table.find(index).ok_or(Status::ConstraintError)?;
1058
1059        let mut tbs_buf = [0u8; VENDOR_ID_VERIFICATION_TBS_MAX];
1060        let tbs = fabric.vendor_id_verification_tbs(&mut tbs_buf, client_challenge, challenge);
1061        let signature = self
1062            .keys
1063            .borrow()
1064            .sign(fabric.operational_key, tbs)
1065            .map_err(|_| Status::Failure)?;
1066
1067        let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
1068        full(w.start_structure(tag))?;
1069        full(w.unsigned(Tag::Context(0), u64::from(index.0)))?;
1070        full(w.unsigned(
1071            Tag::Context(1),
1072            u64::from(crate::fabric::FABRIC_BINDING_VERSION),
1073        ))?;
1074        full(w.octets(Tag::Context(2), signature.as_bytes()))?;
1075        full(w.end_container())
1076    }
1077}
1078
1079/// Whether a value is a valid access-control subject for `AuthMode: CASE` (§6.6.2.1.1).
1080///
1081/// §11.18.6.8: "not being in either the Operational or CASE Authenticated Tag range" is
1082/// `InvalidAdminSubject`. A group node id or a zero would name something that can never
1083/// authenticate over CASE, leaving the new fabric joined and unadministrable.
1084fn is_case_subject(subject: u64) -> bool {
1085    let node = NodeId(subject);
1086    matches!(
1087        node.kind(),
1088        crate::msg::NodeIdKind::Operational | crate::msg::NodeIdKind::CaseAuthenticatedTag
1089    )
1090}
1091
1092/// The identity a validated chain attests to.
1093struct ChainIdentity {
1094    fabric_id: crate::msg::FabricId,
1095    node_id: NodeId,
1096    root_public_key: PublicKey,
1097}
1098
1099/// §11.18.6.7's three validation steps, in the order the specification numbers them.
1100fn validate_chain(
1101    noc: &[u8],
1102    icac: Option<&[u8]>,
1103    rcac: &[u8],
1104    expected_public_key: &PublicKey,
1105) -> Result<ChainIdentity, NocStatus> {
1106    let noc_cert = MatterCertificate::decode(noc).map_err(|_| NocStatus::InvalidNoc)?;
1107    let icac_cert = match icac {
1108        Some(bytes) => Some(MatterCertificate::decode(bytes).map_err(|_| NocStatus::InvalidNoc)?),
1109        None => None,
1110    };
1111    let root = MatterCertificate::decode(rcac).map_err(|_| NocStatus::InvalidNoc)?;
1112
1113    // Step 3, hoisted: "The DN Encoding Rules SHALL be validated for every certificate in the
1114    // chain, including valid value range checks for identifiers such as Fabric ID and Node
1115    // ID … the error status SHALL be InvalidNodeOpId if the matter-node-id attribute in the
1116    // subject DN of the NOC has a value outside the Operational Node ID range". That check
1117    // has to come before the chain verification, because a NOC with no node id at all would
1118    // otherwise fail as a generic InvalidNOC and hide what was actually wrong.
1119    let node_id = noc_cert.node_id().ok_or(NocStatus::InvalidNodeOpId)?;
1120    if !node_id.is_operational() {
1121        return Err(NocStatus::InvalidNodeOpId);
1122    }
1123
1124    // Step 1: Crypto_VerifyChain over the whole chain. `at = None` — a commissionee has no
1125    // wall clock during commissioning, and §6.4.5 only requires the validity window to be
1126    // checked when the node knows the time.
1127    let verified = crate::cert::verify_chain(&noc_cert, icac_cert.as_ref(), &root, None)
1128        .map_err(|_| NocStatus::InvalidNoc)?;
1129
1130    // Step 2: "The public key of the NOC SHALL match the last generated operational public
1131    // key on this session … If this check fails, the error status SHALL be InvalidPublicKey."
1132    //
1133    // This is the step that ties the certificate to a key the *device* made. Without it an
1134    // administrator could install a NOC over a key pair it generated itself and then
1135    // impersonate the node.
1136    if noc_cert.public_key.as_bytes() != expected_public_key.as_bytes() {
1137        return Err(NocStatus::InvalidPublicKey);
1138    }
1139
1140    Ok(ChainIdentity {
1141        fabric_id: verified.fabric_id,
1142        node_id,
1143        root_public_key: root.public_key,
1144    })
1145}
1146
1147// --- The attributes ----------------------------------------------------------------------------
1148
1149/// The global `FabricIndex` field of a fabric-scoped struct (§7.19.1.9).
1150///
1151/// > A fabric-scoped struct SHALL support the global FabricIndex field of type fabric-index,
1152/// > which indicates the associated fabric of the struct … The table that defines fields of a
1153/// > fabric-scoped struct SHALL NOT list the global FabricIndex field, which is a global field
1154/// > and defined implicitly.
1155///
1156/// Which is why it is not in §11.18.4.4's or §11.18.4.5's tables and must still be emitted.
1157pub const FABRIC_INDEX_FIELD: u8 = 254;
1158
1159impl<C: Config, K: KeyStore, R: Rng, const N: usize> OperationalCredentials<'_, C, K, R, N> {
1160    /// Whether a fabric's entries belong in this read (§7.19.1.8.2).
1161    ///
1162    /// > For a read interaction on a list, with fabric-filtering disabled, the list SHALL be
1163    /// > reported as a full list with all entries.
1164    ///
1165    /// With filtering enabled, only the accessing fabric's. A request with filtering on and
1166    /// *no* accessing fabric — a PASE session — matches nothing, which is right: there is no
1167    /// fabric whose entries it is asking for.
1168    fn visible(ctx: &InteractionContext<'_>, index: FabricIndex) -> bool {
1169        !ctx.fabric_filtered || ctx.fabric_index == Some(index)
1170    }
1171
1172    fn write_nocs(
1173        &self,
1174        ctx: &InteractionContext<'_>,
1175        w: &mut TlvWriter<'_>,
1176        tag: Tag,
1177    ) -> Result<(), Status> {
1178        let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
1179        let table = self.fabrics.borrow();
1180        full(w.start_array(tag))?;
1181        for fabric in table.iter().filter(|f| Self::visible(ctx, f.index)) {
1182            let credentials = &fabric.credentials;
1183            full(w.start_structure(Tag::Anonymous))?;
1184            full(w.octets(Tag::Context(1), &credentials.noc))?;
1185            // §11.18.4.4: "If no ICAC is present in the chain, this field SHALL be set to
1186            // null" — present-and-null, not absent.
1187            match &credentials.icac {
1188                Some(icac) => full(w.octets(Tag::Context(2), icac))?,
1189                None => full(w.null(Tag::Context(2)))?,
1190            }
1191            // "If no VVSC is needed, this field SHALL be omitted (in that there SHALL NOT be
1192            // a value present, not even an empty octet string)." The opposite convention from
1193            // the ICAC, in the same structure.
1194            if let Some(vvsc) = &credentials.vvsc {
1195                full(w.octets(Tag::Context(3), vvsc))?;
1196            }
1197            full(w.unsigned(Tag::Context(FABRIC_INDEX_FIELD), u64::from(fabric.index.0)))?;
1198            full(w.end_container())?;
1199        }
1200        full(w.end_container())
1201    }
1202
1203    fn write_fabrics(
1204        &self,
1205        ctx: &InteractionContext<'_>,
1206        w: &mut TlvWriter<'_>,
1207        tag: Tag,
1208    ) -> Result<(), Status> {
1209        let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
1210        let table = self.fabrics.borrow();
1211        full(w.start_array(tag))?;
1212        for fabric in table.iter().filter(|f| Self::visible(ctx, f.index)) {
1213            full(w.start_structure(Tag::Anonymous))?;
1214            full(w.octets(Tag::Context(1), fabric.root_public_key.as_bytes()))?;
1215            full(w.unsigned(Tag::Context(2), u64::from(fabric.admin_vendor_id.0)))?;
1216            full(w.unsigned(Tag::Context(3), fabric.fabric_id.0))?;
1217            full(w.unsigned(Tag::Context(4), fabric.node_id.0))?;
1218            full(w.utf8(Tag::Context(5), fabric.label.as_str()))?;
1219            if let Some(statement) = &fabric.vid_verification_statement {
1220                full(w.octets(Tag::Context(6), statement))?;
1221            }
1222            full(w.unsigned(Tag::Context(FABRIC_INDEX_FIELD), u64::from(fabric.index.0)))?;
1223            full(w.end_container())?;
1224        }
1225        full(w.end_container())
1226    }
1227
1228    /// `TrustedRootCertificates` (§11.18.5.5) — a plain `list[octstr]`, *not* fabric-scoped.
1229    ///
1230    /// "Depending on the method of storage employed by the server, either shared storage for
1231    /// identical root certificates shared by many fabrics, or individually stored root
1232    /// certificate per fabric, **multiple identical root certificates MAY legally appear
1233    /// within the list**." This implementation stores one per fabric, so duplicates do
1234    /// appear — and §11.18.5.5's own advice is how a client copes: "To match a root with a
1235    /// given fabric, the root certificate's subject and subject public key need to be
1236    /// cross-referenced with the NOC or ICAC certificates".
1237    fn write_roots(
1238        &self,
1239        w: &mut TlvWriter<'_>,
1240        tag: Tag,
1241        now: crate::platform::Instant,
1242    ) -> Result<(), Status> {
1243        let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
1244        let table = self.fabrics.borrow();
1245        full(w.start_array(tag))?;
1246        for fabric in table.iter() {
1247            full(w.octets(Tag::Anonymous, &fabric.credentials.rcac))?;
1248        }
1249        // §11.18.6.13: `AddTrustedRootCertificate` "SHALL add a Trusted Root CA Certificate …
1250        // **to the TrustedRootCertificates Attribute list**". Present tense, and the list is
1251        // the attribute — so the root appears the moment the command succeeds, not when
1252        // `AddNOC` commits it to a fabric. An administrator adds the root, reads the attribute
1253        // back to confirm the node took it, and only then sends `AddNOC`; a node that lists
1254        // committed roots only answers that read with the root missing, having just said
1255        // SUCCESS.
1256        //
1257        // It cannot be counted twice: `AddNOC` clears the pending root as it commits it, and
1258        // so does the fail-safe's rollback.
1259        //
1260        // Only while the fail-safe that added it is armed. §11.10.7.2.2 step 9 removes trusted
1261        // roots no fabric references when the fail-safe ends, so a pending root outside a
1262        // fail-safe period is not pending — it is garbage waiting for `reap`, which runs on
1263        // the next *invoke*. A read that arrives first would otherwise report a root the node
1264        // has already promised to have dropped, which is what `TC_OPCREDS_3_1` checks
1265        // immediately after `ArmFailSafe(0)`.
1266        // …and only while the fail-safe that added it is *the one still armed*, which is
1267        // exactly the condition `reap` applies: `progress.added_trusted_root` is true only for
1268        // the context that accepted this root. Asking merely whether *some* fail-safe is armed
1269        // is not enough — the next `ArmFailSafe` would bring the abandoned root back from the
1270        // dead, and `ArmFailSafe` belongs to General Commissioning, so no invoke against this
1271        // cluster need happen in between to reap it.
1272        if self
1273            .fail_safe
1274            .borrow()
1275            .armed(now)
1276            .is_some_and(|armed| armed.progress.added_trusted_root)
1277            && let Some(pending) = self.pending_root.borrow().as_ref()
1278        {
1279            full(w.octets(Tag::Anonymous, pending))?;
1280        }
1281        full(w.end_container())
1282    }
1283}
1284
1285impl<C: Config, K: KeyStore, R: Rng, const N: usize> ClusterHandler
1286    for OperationalCredentials<'_, C, K, R, N>
1287{
1288    fn read(
1289        &self,
1290        resolved: &Resolved<'_>,
1291        ctx: &InteractionContext<'_>,
1292        w: &mut TlvWriter<'_>,
1293        tag: Tag,
1294    ) -> Result<(), Status> {
1295        let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
1296        match resolved.attribute {
1297            NOCS => self.write_nocs(ctx, w, tag),
1298            FABRICS => self.write_fabrics(ctx, w, tag),
1299            // Both are `uint8`, and `AssertValid` holds `Config::FABRICS` to §11.18.5.3's
1300            // `5 to 254` at compile time — so the conversion cannot lose anything, and
1301            // saturating rather than panicking is the right way to say so on a device.
1302            SUPPORTED_FABRICS => {
1303                let capacity = u8::try_from(self.fabrics.borrow().capacity()).unwrap_or(u8::MAX);
1304                full(w.unsigned(tag, u64::from(capacity)))
1305            }
1306            COMMISSIONED_FABRICS => {
1307                let len = u8::try_from(self.fabrics.borrow().len()).unwrap_or(u8::MAX);
1308                full(w.unsigned(tag, u64::from(len)))
1309            }
1310            TRUSTED_ROOT_CERTIFICATES => self.write_roots(w, tag, ctx.now),
1311            // §11.18.5.6: "This attribute SHALL indicate the accessing fabric index", whose
1312            // fallback is 0 — the value that means "no fabric", which is exactly what a PASE
1313            // session has.
1314            CURRENT_FABRIC_INDEX => {
1315                full(w.unsigned(tag, u64::from(ctx.fabric_index.unwrap_or(FabricIndex(0)).0)))
1316            }
1317            _ => Err(Status::UnsupportedAttribute),
1318        }
1319    }
1320
1321    fn invoke(
1322        &self,
1323        resolved: &ResolvedCommand<'_>,
1324        fields: Option<&[u8]>,
1325        ctx: &InteractionContext<'_>,
1326        w: &mut TlvWriter<'_>,
1327        tag: Tag,
1328    ) -> Result<Option<CommandId>, StatusIb> {
1329        self.run(resolved.command.id, fields, ctx, w, tag)
1330            .map_err(StatusIb::from)
1331    }
1332}
1333
1334impl<C: Config, K: KeyStore, R: Rng, const N: usize> Cluster
1335    for OperationalCredentials<'_, C, K, R, N>
1336{
1337    const ID: ClusterId = ID;
1338}
1339
1340// --- Command decoding --------------------------------------------------------------------------
1341
1342/// Reads the members of a `CommandFields` structure, one at a time.
1343///
1344/// `CommandFields` is the `CommandDataIB`'s context-1 member (§10.6.11), so it arrives
1345/// *tagged*: a fragment of a structure rather than a TLV document, and reading it with
1346/// [`TlvReader::new`] would reject exactly the bytes that are correct.
1347///
1348/// Only the structure's own end-of-container ends the walk. A short buffer and a malformed
1349/// element are both `INVALID_COMMAND`: treating either as an end of input would let a
1350/// truncated `AddNOC` be read as one with fields absent.
1351fn walk_fields<'a>(
1352    fields: Option<&'a [u8]>,
1353    mut on_field: impl FnMut(u8, &crate::tlv::Element<'a>) -> Result<bool, Status>,
1354) -> Result<(), Status> {
1355    let fields = fields.ok_or(Status::InvalidCommand)?;
1356    let mut reader = TlvReader::new_in(fields, ContainerKind::Structure);
1357    let element = reader
1358        .next_element()
1359        .map_err(|_| Status::InvalidCommand)?
1360        .ok_or(Status::InvalidCommand)?;
1361    if element.value.container() != Some(ContainerKind::Structure) {
1362        return Err(Status::InvalidCommand);
1363    }
1364    let start_depth = reader.depth();
1365    loop {
1366        let Some(field) = reader.next_element().map_err(|_| Status::InvalidCommand)? else {
1367            return Err(Status::InvalidCommand);
1368        };
1369        if reader.depth() < start_depth {
1370            break;
1371        }
1372        let number = match field.tag {
1373            Tag::Context(number) => number,
1374            // A fully-qualified tag is a vendor extension; §11.18 has none, and §10.6.11's
1375            // forward-compatibility rule is to ignore what is not understood.
1376            _ => {
1377                reader
1378                    .skip_value(&field)
1379                    .map_err(|_| Status::InvalidCommand)?;
1380                continue;
1381            }
1382        };
1383        if !on_field(number, &field)? {
1384            reader
1385                .skip_value(&field)
1386                .map_err(|_| Status::InvalidCommand)?;
1387        }
1388    }
1389    Ok(())
1390}
1391
1392fn decode_nonce<const L: usize>(element: &crate::tlv::Element<'_>) -> Result<[u8; L], Status> {
1393    let bytes = element.octets().map_err(|_| Status::InvalidCommand)?;
1394    // §11.18.6.1: "If the AttestationNonce that is provided in the command is malformed, a
1395    // recipient SHALL fail the command with a Status Code of INVALID_COMMAND." A nonce of the
1396    // wrong length is malformed, not merely constrained: it would change what is signed.
1397    let mut out = [0u8; L];
1398    if bytes.len() != L {
1399        return Err(Status::InvalidCommand);
1400    }
1401    out.copy_from_slice(bytes);
1402    Ok(out)
1403}
1404
1405impl<C: Config, K: KeyStore, R: Rng, const N: usize> OperationalCredentials<'_, C, K, R, N> {
1406    /// Answers a `NOCResponse` (§11.18.6.10): `StatusCode [0]`, `FabricIndex [1]`,
1407    /// `DebugText [2]`.
1408    ///
1409    /// `FabricIndex` is present only on success — its conformance is `StatusCode == OK, O` —
1410    /// and `DebugText` is omitted entirely: it is optional, and a device that filled it would
1411    /// leak its internals to anyone who can invoke the command.
1412    fn noc_response(
1413        status: NocStatus,
1414        index: Option<FabricIndex>,
1415        w: &mut TlvWriter<'_>,
1416        tag: Tag,
1417    ) -> Result<(), Status> {
1418        let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
1419        full(w.start_structure(tag))?;
1420        full(w.unsigned(Tag::Context(0), u64::from(status.value())))?;
1421        if status.is_ok()
1422            && let Some(index) = index
1423        {
1424            full(w.unsigned(Tag::Context(1), u64::from(index.0)))?;
1425        }
1426        full(w.end_container())
1427    }
1428}
1429
1430impl<C: Config, K: KeyStore, R: Rng, const N: usize> OperationalCredentials<'_, C, K, R, N> {
1431    /// Runs one command of §11.18.6.
1432    ///
1433    /// This is what [`ClusterHandler::invoke`] forwards to; it is public because the
1434    /// commands are worth driving directly from a test or a controller-side harness.
1435    pub fn run(
1436        &self,
1437        command: CommandId,
1438        fields: Option<&[u8]>,
1439        ctx: &InteractionContext<'_>,
1440        w: &mut TlvWriter<'_>,
1441        tag: Tag,
1442    ) -> Result<Option<CommandId>, Status> {
1443        // Anything left over from a fail-safe period that has ended must not be adopted by
1444        // this one.
1445        self.reap(ctx.now);
1446
1447        match command {
1448            ATTESTATION_REQUEST => {
1449                let mut nonce = None;
1450                walk_fields(fields, |number, element| match number {
1451                    0 => {
1452                        set_once(
1453                            &mut nonce,
1454                            decode_nonce::<{ attestation::ATTESTATION_NONCE_LEN }>(element)?,
1455                        )
1456                        .map_err(|_| Status::InvalidCommand)?;
1457                        Ok(true)
1458                    }
1459                    _ => Ok(false),
1460                })?;
1461                let nonce = nonce.ok_or(Status::InvalidCommand)?;
1462                let challenge = ctx.attestation_challenge.ok_or(Status::UnsupportedAccess)?;
1463                // §11.18.4.7: "The timestamp field SHALL be in epoch-s." A node with no
1464                // wall clock reports zero, which is what `Clock::utc` returning `None` means
1465                // and what every commissioner already tolerates.
1466                self.attestation_response(&nonce, 0, challenge, w, tag)?;
1467                Ok(Some(ATTESTATION_RESPONSE))
1468            }
1469            CERTIFICATE_CHAIN_REQUEST => {
1470                let mut kind = None;
1471                walk_fields(fields, |number, element| match number {
1472                    0 => {
1473                        let value = element.unsigned().map_err(|_| Status::InvalidCommand)?;
1474                        let value = u8::try_from(value).map_err(|_| Status::InvalidCommand)?;
1475                        let kind_value = CertificateChainType::from_value(value)
1476                            .ok_or(Status::InvalidCommand)?;
1477                        set_once(&mut kind, kind_value).map_err(|_| Status::InvalidCommand)?;
1478                        Ok(true)
1479                    }
1480                    _ => Ok(false),
1481                })?;
1482                let certificate = match kind.ok_or(Status::InvalidCommand)? {
1483                    CertificateChainType::Dac => self.attestation.dac,
1484                    CertificateChainType::Pai => self.attestation.pai,
1485                };
1486                let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
1487                full(w.start_structure(tag))?;
1488                full(w.octets(Tag::Context(0), certificate))?;
1489                full(w.end_container())?;
1490                Ok(Some(CERTIFICATE_CHAIN_RESPONSE))
1491            }
1492            CSR_REQUEST => {
1493                let mut nonce = None;
1494                let mut for_update = None;
1495                walk_fields(fields, |number, element| match number {
1496                    0 => {
1497                        set_once(
1498                            &mut nonce,
1499                            decode_nonce::<{ attestation::CSR_NONCE_LEN }>(element)?,
1500                        )
1501                        .map_err(|_| Status::InvalidCommand)?;
1502                        Ok(true)
1503                    }
1504                    1 => {
1505                        let value = element.bool().map_err(|_| Status::InvalidCommand)?;
1506                        set_once(&mut for_update, value).map_err(|_| Status::InvalidCommand)?;
1507                        Ok(true)
1508                    }
1509                    _ => Ok(false),
1510                })?;
1511                let nonce = nonce.ok_or(Status::InvalidCommand)?;
1512                // `IsForUpdateNOC` is optional with a fallback of false.
1513                let mut random = [0u8; 32];
1514                self.rng
1515                    .borrow_mut()
1516                    .fill(&mut random)
1517                    .map_err(|_| Status::Failure)?;
1518                self.csr_response(&nonce, for_update.unwrap_or(false), ctx, &random, w, tag)?;
1519                Ok(Some(CSR_RESPONSE))
1520            }
1521            ADD_NOC => {
1522                let mut noc = None;
1523                let mut icac = None;
1524                let mut ipk = None;
1525                let mut subject = None;
1526                let mut vendor = None;
1527                walk_fields(fields, |number, element| {
1528                    match number {
1529                        0 => set_once(
1530                            &mut noc,
1531                            element.octets().map_err(|_| Status::InvalidCommand)?,
1532                        ),
1533                        1 => set_once(
1534                            &mut icac,
1535                            element.octets().map_err(|_| Status::InvalidCommand)?,
1536                        ),
1537                        2 => set_once(
1538                            &mut ipk,
1539                            decode_nonce::<{ crate::crypto::SYMMETRIC_KEY_LENGTH_BYTES }>(element)?,
1540                        ),
1541                        3 => set_once(
1542                            &mut subject,
1543                            element.unsigned().map_err(|_| Status::InvalidCommand)?,
1544                        ),
1545                        4 => {
1546                            let value = element.unsigned().map_err(|_| Status::InvalidCommand)?;
1547                            let value =
1548                                u16::try_from(value).map_err(|_| Status::ConstraintError)?;
1549                            set_once(&mut vendor, VendorId(value))
1550                        }
1551                        _ => return Ok(false),
1552                    }
1553                    .map_err(|_| Status::InvalidCommand)?;
1554                    Ok(true)
1555                })?;
1556                let request = AddNocRequest {
1557                    noc: noc.ok_or(Status::InvalidCommand)?,
1558                    icac,
1559                    ipk: ipk.ok_or(Status::InvalidCommand)?,
1560                    case_admin_subject: subject.ok_or(Status::InvalidCommand)?,
1561                    admin_vendor_id: vendor.ok_or(Status::InvalidCommand)?,
1562                };
1563                let status = self.add_noc(&request, ctx)?;
1564                Self::noc_response(status, self.changed_index(), w, tag)?;
1565                Ok(Some(NOC_RESPONSE))
1566            }
1567            UPDATE_NOC => {
1568                let mut noc = None;
1569                let mut icac = None;
1570                walk_fields(fields, |number, element| {
1571                    match number {
1572                        0 => set_once(
1573                            &mut noc,
1574                            element.octets().map_err(|_| Status::InvalidCommand)?,
1575                        ),
1576                        1 => set_once(
1577                            &mut icac,
1578                            element.octets().map_err(|_| Status::InvalidCommand)?,
1579                        ),
1580                        _ => return Ok(false),
1581                    }
1582                    .map_err(|_| Status::InvalidCommand)?;
1583                    Ok(true)
1584                })?;
1585                let status = self.update_noc(noc.ok_or(Status::InvalidCommand)?, icac, ctx)?;
1586                Self::noc_response(status, self.changed_index(), w, tag)?;
1587                Ok(Some(NOC_RESPONSE))
1588            }
1589            UPDATE_FABRIC_LABEL => {
1590                let mut label = None;
1591                walk_fields(fields, |number, element| match number {
1592                    0 => {
1593                        set_once(
1594                            &mut label,
1595                            element.utf8().map_err(|_| Status::InvalidCommand)?,
1596                        )
1597                        .map_err(|_| Status::InvalidCommand)?;
1598                        Ok(true)
1599                    }
1600                    _ => Ok(false),
1601                })?;
1602                let status = self.update_fabric_label(label.ok_or(Status::InvalidCommand)?, ctx)?;
1603                Self::noc_response(status, ctx.fabric_index, w, tag)?;
1604                Ok(Some(NOC_RESPONSE))
1605            }
1606            REMOVE_FABRIC => {
1607                let mut index = None;
1608                walk_fields(fields, |number, element| match number {
1609                    0 => {
1610                        let value = element.unsigned().map_err(|_| Status::InvalidCommand)?;
1611                        let value = u8::try_from(value).map_err(|_| Status::ConstraintError)?;
1612                        set_once(&mut index, FabricIndex(value))
1613                            .map_err(|_| Status::InvalidCommand)?;
1614                        Ok(true)
1615                    }
1616                    _ => Ok(false),
1617                })?;
1618                let index = index.ok_or(Status::InvalidCommand)?;
1619                let status = self.remove_fabric(index, ctx)?;
1620                Self::noc_response(status, Some(index), w, tag)?;
1621                Ok(Some(NOC_RESPONSE))
1622            }
1623            ADD_TRUSTED_ROOT_CERTIFICATE => {
1624                let mut rcac = None;
1625                walk_fields(fields, |number, element| match number {
1626                    0 => {
1627                        set_once(
1628                            &mut rcac,
1629                            element.octets().map_err(|_| Status::InvalidCommand)?,
1630                        )
1631                        .map_err(|_| Status::InvalidCommand)?;
1632                        Ok(true)
1633                    }
1634                    _ => Ok(false),
1635                })?;
1636                self.add_trusted_root(rcac.ok_or(Status::InvalidCommand)?, ctx)?;
1637                // No response command: §11.18.6's table gives `Y`, so success is a plain
1638                // SUCCESS status.
1639                Ok(None)
1640            }
1641            SET_VID_VERIFICATION_STATEMENT => {
1642                let mut vendor = None;
1643                let mut statement = None;
1644                let mut vvsc = None;
1645                walk_fields(fields, |number, element| {
1646                    match number {
1647                        0 => {
1648                            let value = element.unsigned().map_err(|_| Status::InvalidCommand)?;
1649                            let value =
1650                                u16::try_from(value).map_err(|_| Status::ConstraintError)?;
1651                            set_once(&mut vendor, VendorId(value))
1652                        }
1653                        1 => set_once(
1654                            &mut statement,
1655                            element.octets().map_err(|_| Status::InvalidCommand)?,
1656                        ),
1657                        2 => set_once(
1658                            &mut vvsc,
1659                            element.octets().map_err(|_| Status::InvalidCommand)?,
1660                        ),
1661                        _ => return Ok(false),
1662                    }
1663                    .map_err(|_| Status::InvalidCommand)?;
1664                    Ok(true)
1665                })?;
1666                self.set_vid_verification_statement(vendor, statement, vvsc, ctx)?;
1667                Ok(None)
1668            }
1669            SIGN_VID_VERIFICATION_REQUEST => {
1670                let mut index = None;
1671                let mut challenge = None;
1672                walk_fields(fields, |number, element| {
1673                    match number {
1674                        0 => {
1675                            let value = element.unsigned().map_err(|_| Status::InvalidCommand)?;
1676                            let value = u8::try_from(value).map_err(|_| Status::ConstraintError)?;
1677                            set_once(&mut index, FabricIndex(value))
1678                        }
1679                        1 => set_once(&mut challenge, decode_nonce::<32>(element)?),
1680                        _ => return Ok(false),
1681                    }
1682                    .map_err(|_| Status::InvalidCommand)?;
1683                    Ok(true)
1684                })?;
1685                self.sign_vid_verification(
1686                    index.ok_or(Status::InvalidCommand)?,
1687                    &challenge.ok_or(Status::InvalidCommand)?,
1688                    ctx,
1689                    w,
1690                    tag,
1691                )?;
1692                Ok(Some(SIGN_VID_VERIFICATION_RESPONSE))
1693            }
1694            _ => Err(Status::UnsupportedCommand),
1695        }
1696    }
1697
1698    /// The index the change just recorded touched, without consuming it.
1699    fn changed_index(&self) -> Option<FabricIndex> {
1700        match self.change.get()? {
1701            FabricChange::Added { index, .. }
1702            | FabricChange::Updated { index }
1703            | FabricChange::Removed { index, .. } => Some(index),
1704        }
1705    }
1706}