Skip to main content

rs_matter_node_core/
failsafe.rs

1/*
2 *
3 *    Copyright (c) 2022-2026 Project CHIP Authors
4 *
5 *    Licensed under the Apache License, Version 2.0 (the "License");
6 *    you may not use this file except in compliance with the License.
7 *    You may obtain a copy of the License at
8 *
9 *        http://www.apache.org/licenses/LICENSE-2.0
10 *
11 *    Unless required by applicable law or agreed to in writing, software
12 *    distributed under the License is distributed on an "AS IS" BASIS,
13 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *    See the License for the specific language governing permissions and
15 *    limitations under the License.
16 */
17
18use core::num::NonZeroU8;
19
20use crate::cert::{CertRef, MAX_CERT_TLV_LEN};
21use crate::crypto::{
22    CanonAeadKeyRef, CanonPkcSecretKey, CanonPkcSecretKeyRef, Crypto, PublicKey, SecretKey,
23    SigningSecretKey, PKC_SECRET_KEY_ZEROED,
24};
25use crate::dm::ROOT_ENDPOINT_ID;
26use crate::dm::{ClusterId, EndptId, HandlerContext, LifecycleOp};
27use crate::error::{Error, ErrorCode};
28use crate::fabric::{Fabric, Fabrics};
29use crate::im::IMStatusCode;
30use crate::persist::KvBlobStoreAccess;
31use crate::session::SessionMode;
32use crate::tlv::TLVElement;
33use crate::utils::bitflags::bitflags;
34use crate::utils::epoch::UtcTime;
35use crate::utils::init::{init, Init};
36use crate::utils::storage::Vec;
37use crate::utils::timers::{Duration, Instant};
38
39bitflags! {
40    #[repr(transparent)]
41    #[derive(Default)]
42    #[cfg_attr(not(feature = "defmt"), derive(Debug, Copy, Clone, Eq, PartialEq, Hash))]
43    pub struct NocFlags: u8 {
44        const ADD_CSR_REQ_RECVD = 0x01;
45        const UPDATE_CSR_REQ_RECVD = 0x02;
46        const ADD_ROOT_CERT_RECVD = 0x04;
47        const ADD_NOC_RECVD = 0x08;
48        const UPDATE_NOC_RECVD = 0x10;
49    }
50}
51
52#[derive(PartialEq)]
53pub struct ArmedCtx {
54    armed_at: Instant,
55    timeout_secs: u16,
56    /// When the context ends regardless of re-arms: set when it is created,
57    /// `MaxCumulativeFailsafeSeconds` later, and never moved
58    cumulative_expires_at: Instant,
59    fab_idx: u8,
60    flags: NocFlags,
61}
62
63impl ArmedCtx {
64    fn new(timeout_secs: u16, max_cumulative_secs: u16, fab_idx: u8, flags: NocFlags) -> Self {
65        let now = Instant::now();
66
67        Self {
68            armed_at: now,
69            timeout_secs,
70            cumulative_expires_at: now
71                .saturating_add(Duration::from_secs(max_cumulative_secs as u64)),
72            fab_idx,
73            flags,
74        }
75    }
76
77    /// When the context expires: at the end of the armed timeout, or of its
78    /// cumulative lifetime, whichever comes first.
79    fn expires_at(&self) -> Instant {
80        self.armed_at
81            .saturating_add(Duration::from_secs(self.timeout_secs as u64))
82            .min(self.cumulative_expires_at)
83    }
84}
85
86#[derive(PartialEq)]
87pub enum State {
88    Idle,
89    Armed(ArmedCtx),
90}
91
92pub enum IMError {
93    Error(Error),
94    Status(IMStatusCode),
95}
96
97impl From<Error> for IMError {
98    fn from(e: Error) -> Self {
99        IMError::Error(e)
100    }
101}
102
103impl From<IMStatusCode> for IMError {
104    fn from(e: IMStatusCode) -> Self {
105        IMError::Status(e)
106    }
107}
108
109/// Default fail-safe expiry length used when the device implicitly arms the
110/// fail-safe (e.g. on PASE session establishment). Mirrors
111/// `CHIP_DEVICE_CONFIG_FAILSAFE_EXPIRY_LENGTH_SEC` from the reference SDK.
112pub const DEFAULT_FAILSAFE_EXPIRY_SECS: u16 = 60;
113
114/// Default `MaxCumulativeFailsafeSeconds`, the longest a fail-safe context
115/// lasts however often it is re-armed, until [`FailSafe::set_max_cumulative_secs`]
116/// sets the node's own.
117pub const DEFAULT_FAILSAFE_MAX_CUMULATIVE_SECS: u16 = 900;
118
119/// The ID of the Operational Credentials cluster.
120const OPERATIONAL_CREDENTIALS_CLUSTER_ID: ClusterId = 0x003E;
121
122/// The outcome of a fail-safe expiry.
123#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
124#[cfg_attr(feature = "defmt", derive(defmt::Format))]
125pub struct Expiry {
126    /// The fabric the rollback removed, if any.
127    pub removed_fabric: Option<NonZeroU8>,
128}
129
130impl Expiry {
131    /// Broadcast the expiry to the handlers of `ctx`: `LifecycleOp::FailSafeExpiry`,
132    /// then the removal of the fabric the rollback dropped, if any.
133    ///
134    /// The broadcasts run the handlers inline, so this must NOT be called
135    /// while holding the Matter state lock.
136    ///
137    /// The expiry removes the PASE sessions, so the caller also has to tell the
138    /// waiters on them, with `Transport::notify_session_removed`.
139    pub fn notify(&self, ctx: impl HandlerContext) {
140        if let Err(e) = ctx.broadcast_lifecycle(LifecycleOp::FailSafeExpiry) {
141            warn!("Failed to broadcast the fail-safe expiry: {:?}", e);
142        }
143
144        if let Some(fab_idx) = self.removed_fabric {
145            ctx.notify_fabric_removed(fab_idx);
146        }
147    }
148}
149
150pub struct FailSafe {
151    state: State,
152    secret_key: CanonPkcSecretKey,
153    root_ca: Vec<u8, { MAX_CERT_TLV_LEN }>,
154    breadcrumb: u64,
155    max_cumulative_secs: u16,
156}
157
158impl FailSafe {
159    #[inline(always)]
160    pub const fn new() -> Self {
161        Self {
162            state: State::Idle,
163            secret_key: PKC_SECRET_KEY_ZEROED,
164            root_ca: Vec::new(),
165            breadcrumb: 0,
166            max_cumulative_secs: DEFAULT_FAILSAFE_MAX_CUMULATIVE_SECS,
167        }
168    }
169
170    pub fn init() -> impl Init<Self> {
171        init!(Self {
172            state: State::Idle,
173            secret_key <- CanonPkcSecretKey::init(),
174            root_ca <- Vec::init(),
175            breadcrumb: 0,
176            max_cumulative_secs: DEFAULT_FAILSAFE_MAX_CUMULATIVE_SECS
177        })
178    }
179
180    /// Set `MaxCumulativeFailsafeSeconds`, the longest a fail-safe context
181    /// lasts however often it is re-armed. Applies to the contexts created
182    /// from now on: an armed one keeps its lifetime.
183    pub fn set_max_cumulative_secs(&mut self, secs: u16) {
184        self.max_cumulative_secs = secs;
185    }
186
187    /// Check if the fail-safe timer has expired and if so disarms and restores the state of the fabric as well as
188    /// the basic info settings.
189    ///
190    /// This should be called periodically to ensure that the fail-safe state is updated in a timely manner.
191    /// Ideally, it should also be called at the beginning of any API that requires the fail-safe to be armed to ensure that the state is up to date.
192    ///
193    /// Returns the outcome of the expiry, if the fail-safe did expire (see
194    /// [`FailSafe::expire`]).
195    pub fn check_failsafe_timeout<S>(
196        &mut self,
197        fabrics: &mut Fabrics,
198        remove_pase_sessions: impl FnOnce(),
199        kv: S,
200        mdns_notif: impl FnMut(),
201        notify_change: impl FnMut(EndptId, ClusterId),
202    ) -> Result<Option<Expiry>, Error>
203    where
204        S: KvBlobStoreAccess,
205    {
206        if let State::Armed(ctx) = &self.state {
207            if Instant::now() >= ctx.expires_at() {
208                // Timeout path: no caller exchange to preserve, so wipe
209                // every PASE session along with the fabric rollback.
210                return self.expire(fabrics, remove_pase_sessions, kv, mdns_notif, notify_change);
211            }
212        }
213
214        Ok(None)
215    }
216
217    /// Force the fail-safe context to expire immediately, rolling back any
218    /// fabric changes that the in-flight commissioning had staged and
219    /// resetting the breadcrumb to 0.
220    ///
221    /// `remove_pase_sessions` removes the PASE sessions, which are orphaned by
222    /// the rollback. When the trigger arrived over PASE, it should keep the
223    /// session of the triggering exchange alive (marked expired), so that the
224    /// response can still be sent before the slot is reclaimed.
225    ///
226    /// Returns `None` if the fail-safe was not armed. Otherwise, the caller
227    /// must broadcast `LifecycleOp::FailSafeExpiry` once the Matter state lock
228    /// is released, so that the handlers drop what they staged (networks and
229    /// the like), and `HandlerContext::notify_fabric_removed` for the
230    /// returned removed fabric. That is a fabric added by the in-flight
231    /// `AddNOC`, which has no persisted copy yet; a pre-existing fabric
232    /// mutated by `UpdateNOC` is resurrected from its persisted copy instead.
233    pub fn expire<S>(
234        &mut self,
235        fabrics: &mut Fabrics,
236        remove_pase_sessions: impl FnOnce(),
237        kv: S,
238        mut mdns_notif: impl FnMut(),
239        mut notify_change: impl FnMut(EndptId, ClusterId),
240    ) -> Result<Option<Expiry>, Error>
241    where
242        S: KvBlobStoreAccess,
243    {
244        let State::Armed(ctx) = &self.state else {
245            return Ok(None);
246        };
247
248        warn!(
249            "Fail-Safe timeout expired for fabric {}, disarming",
250            ctx.fab_idx
251        );
252
253        let fab_idx_raw = ctx.fab_idx;
254        let mut removed_fabric = None;
255
256        kv.access(|mut kv, buf| {
257            if let Some(fab_idx) = NonZeroU8::new(fab_idx_raw) {
258                fabrics.remove(fab_idx)?;
259                fabrics.add_load(fab_idx.get(), &mut kv, buf)?;
260
261                removed_fabric = fabrics.get(fab_idx).is_none().then_some(fab_idx);
262            }
263
264            Ok::<_, Error>(())
265        })?;
266
267        // Any PASE session that was in flight under this fail-safe is
268        // now orphaned: its commissioning attempt was rolled back, so the
269        // session has nothing to do and should not stick around to fill
270        // the session table (same leak class fixed for
271        // `CommissioningComplete`).
272        remove_pase_sessions();
273
274        self.state = State::Idle;
275        self.breadcrumb = 0;
276
277        mdns_notif();
278
279        // The rollback above restores attributes visible to subscribers —
280        // `OperationalCredentials::NOCs` / `Fabrics` (including `vvsc`,
281        // `VIDVerificationStatement`, `vendorID` mutated in-failsafe by
282        // `SetVIDVerificationStatement`) — to their persisted values. Notify
283        // so any active subscriptions re-report.
284        //
285        // TODO: this only flags subscriptions for re-reporting; it does
286        // *not* bump the affected clusters' data versions. `Failsafe`
287        // has no handle to the cluster meta needed to do that. Pre-existing
288        // limitation, not introduced by the timeout-vs-force-expiry path.
289        notify_change(ROOT_ENDPOINT_ID, OPERATIONAL_CREDENTIALS_CLUSTER_ID);
290
291        Ok(Some(Expiry { removed_fabric }))
292    }
293
294    pub fn arm(
295        &mut self,
296        timeout_secs: u16,
297        breadcrumb: u64,
298        session_mode: &SessionMode,
299        comm_window_open: bool,
300    ) -> Result<(), Error> {
301        if matches!(self.state, State::Idle) {
302            if matches!(session_mode, SessionMode::PlainText) {
303                // Only PASE and CASE sessions supported
304                return Err(ErrorCode::GennCommInvalidAuthentication.into());
305            }
306
307            if comm_window_open && matches!(session_mode, SessionMode::Case { .. }) {
308                // Cannot arm via CASE while there's an active window
309                return Err(ErrorCode::Busy.into());
310            }
311
312            // if !comm_window_open && !matches!(session_mode, SessionMode::Case { .. }) {
313            //     // Cannot arm via PASE if there is no active commissioning window
314            //     return Err(ErrorCode::GennCommInvalidAuthentication.into());
315            // }
316
317            if timeout_secs == 0 {
318                // Expiring a fail-safe which is not armed succeeds without side effects
319                return Ok(());
320            }
321
322            self.state = State::Armed(ArmedCtx::new(
323                timeout_secs,
324                self.max_cumulative_secs,
325                session_mode.fab_idx(),
326                NocFlags::empty(),
327            ));
328            self.breadcrumb = breadcrumb;
329
330            return Ok(());
331        }
332
333        // Re-arm
334
335        self.check_state(
336            session_mode,
337            NocFlags::empty(),
338            NocFlags::empty(),
339            NocFlags::empty(),
340        )?;
341
342        let State::Armed(ctx) = &mut self.state else {
343            // Impossible, as we checked for Idle above
344            unreachable!();
345        };
346
347        if timeout_secs > 0 {
348            ctx.armed_at = Instant::now();
349            ctx.timeout_secs = timeout_secs;
350            self.breadcrumb = breadcrumb;
351        } else {
352            // As per the spec, when timeout seconds is 0, we have to actually disarm
353            self.state = State::Idle;
354            self.breadcrumb = 0;
355        }
356
357        Ok(())
358    }
359
360    pub fn disarm<'a>(
361        &mut self,
362        session_mode: &SessionMode,
363        fabrics: &'a mut Fabrics,
364    ) -> Result<&'a mut Fabric, Error> {
365        self.disarm_with(session_mode, fabrics, |_| Ok(()))
366    }
367
368    /// Like [`Self::disarm`], running `commit` on the fabric first. If `commit`
369    /// fails, the fail-safe stays armed, for its expiry to revert the fabric.
370    pub fn disarm_with<'a, F>(
371        &mut self,
372        session_mode: &SessionMode,
373        fabrics: &'a mut Fabrics,
374        commit: F,
375    ) -> Result<&'a mut Fabric, Error>
376    where
377        F: FnOnce(&Fabric) -> Result<(), Error>,
378    {
379        if matches!(self.state, State::Idle) {
380            error!("Received Fail-Safe Disarm without it being armed");
381            return Err(ErrorCode::FailSafeRequired.into());
382        }
383
384        // Has to be a CASE session
385        let fab_idx = Self::get_case_fab_idx(session_mode)?;
386
387        self.check_state(
388            session_mode,
389            NocFlags::empty(),
390            NocFlags::empty(),
391            NocFlags::empty(),
392        )?;
393
394        let fabric = fabrics.fabric_mut(fab_idx)?;
395
396        commit(fabric)?;
397
398        self.state = State::Idle;
399        self.breadcrumb = 0;
400
401        Ok(fabric)
402    }
403
404    /// When the armed fail-safe expires, or `None` if it is not armed.
405    pub fn expires_at(&self) -> Option<Instant> {
406        match &self.state {
407            State::Armed(ctx) => Some(ctx.expires_at()),
408            _ => None,
409        }
410    }
411
412    pub fn is_armed(&self) -> bool {
413        matches!(self.state, State::Armed(_))
414    }
415
416    /// Return the trusted root certificate that has been staged via
417    /// `AddTrustedRootCertificate` while the fail-safe is armed but has not
418    /// yet been bound to a fabric via `AddNOC` / `UpdateNOC`.
419    ///
420    /// Once `AddNOC` or `UpdateNOC` is processed the root certificate is
421    /// owned by the (new or updated) fabric and is reported through the
422    /// fabric table; until then it has no fabric association but the spec
423    /// still requires it to appear in the `TrustedRootCertificates` list
424    /// (Matter Core spec, NodeOperationalCredentials cluster).
425    pub fn pending_root_ca(&self) -> Option<&[u8]> {
426        let State::Armed(ctx) = &self.state else {
427            return None;
428        };
429
430        if !ctx.flags.contains(NocFlags::ADD_ROOT_CERT_RECVD) {
431            return None;
432        }
433
434        if ctx
435            .flags
436            .intersects(NocFlags::ADD_NOC_RECVD | NocFlags::UPDATE_NOC_RECVD)
437        {
438            return None;
439        }
440
441        (!self.root_ca.is_empty()).then_some(self.root_ca.as_slice())
442    }
443
444    /// Drop the trusted root certificate staged via `AddTrustedRootCertificate`,
445    /// if no `AddNOC` / `UpdateNOC` has bound it to a fabric yet.
446    ///
447    /// For fabric removal: the root is then not referenced by any operational
448    /// certificate, so it must go. The fail-safe stays armed, and another
449    /// `AddTrustedRootCertificate` in it is still refused.
450    pub fn drop_pending_root_ca(&mut self) {
451        if self.pending_root_ca().is_some() {
452            self.root_ca.clear();
453        }
454    }
455
456    pub fn is_armed_for(&self, caller_fab_idx: u8) -> bool {
457        match self.state {
458            State::Idle => false,
459            State::Armed(ArmedCtx { fab_idx, .. }) => fab_idx == caller_fab_idx,
460        }
461    }
462
463    /// Whether the current fail-safe context already has an in-flight
464    /// `AddNOC` or `UpdateNOC` for `caller_fab_idx`. Used by
465    /// `SetVIDVerificationStatement` to decide whether the VID-verification
466    /// mutation rides along with the pending fabric (and thus rolls back
467    /// on fail-safe expiry) or is committed to storage immediately.
468    pub fn has_pending_noc_for(&self, caller_fab_idx: NonZeroU8) -> bool {
469        let State::Armed(ctx) = &self.state else {
470            return false;
471        };
472        ctx.fab_idx == caller_fab_idx.get()
473            && ctx
474                .flags
475                .intersects(NocFlags::ADD_NOC_RECVD | NocFlags::UPDATE_NOC_RECVD)
476    }
477
478    pub fn check_armed(&self, session_mode: &SessionMode) -> Result<(), Error> {
479        self.check_state(
480            session_mode,
481            NocFlags::empty(),
482            NocFlags::empty(),
483            NocFlags::empty(),
484        )
485    }
486
487    pub fn add_trusted_root_cert<C: Crypto>(
488        &mut self,
489        crypto: C,
490        time: UtcTime,
491        session_mode: &SessionMode,
492        root_ca: &[u8],
493        buf: &mut [u8],
494    ) -> Result<(), Error> {
495        self.check_state(
496            session_mode,
497            NocFlags::empty(),
498            NocFlags::ADD_ROOT_CERT_RECVD,
499            NocFlags::ADD_ROOT_CERT_RECVD,
500        )?;
501
502        // Validate the candidate RCAC by checking its self-signature (a Matter
503        // RCAC is self-issued, so the certificate's own public key must verify
504        // the certificate's signature). Any decode or signature failure must
505        // surface as `INVALID_COMMAND` per Matter Core spec
506        // (`AddTrustedRootCertificate`), not as the generic `Failure` we'd
507        // otherwise get from `ErrorCode::InvalidSignature`.
508        {
509            let root_ref = CertRef::new(TLVElement::new(root_ca));
510            root_ref
511                .verify_chain_start(&crypto, time)
512                .finalise(buf)
513                .map_err(|_| ErrorCode::InvalidCommand)?;
514
515            // Matter spec extra: an RCAC SHALL NOT carry a
516            // `pathLenConstraint` greater than `1` — the deepest valid
517            // Matter chain is RCAC → ICAC → NOC, i.e. at most one
518            // intermediate CA below the root. Mirrors CHIP's
519            // `ValidateChipRCAC`.
520            if let Some(path_len) = root_ref
521                .basic_constraints_path_len()
522                .map_err(|_| ErrorCode::InvalidCommand)?
523            {
524                if path_len > 1 {
525                    Err(ErrorCode::InvalidCommand)?;
526                }
527            }
528        }
529
530        self.root_ca.clear();
531        self.root_ca
532            .extend_from_slice(root_ca)
533            .map_err(|_| ErrorCode::InvalidCommand)?;
534
535        self.add_flags(NocFlags::ADD_ROOT_CERT_RECVD);
536
537        Ok(())
538    }
539
540    pub fn add_csr_req<C: Crypto>(
541        &mut self,
542        crypto: C,
543        session_mode: &SessionMode,
544    ) -> Result<CanonPkcSecretKeyRef<'_>, Error> {
545        self.check_state(
546            session_mode,
547            NocFlags::empty(),
548            NocFlags::ADD_CSR_REQ_RECVD | NocFlags::UPDATE_CSR_REQ_RECVD,
549            NocFlags::ADD_CSR_REQ_RECVD,
550        )?;
551
552        let crypto_secret_key = crypto.generate_secret_key()?;
553        crypto_secret_key.write_canon(&mut self.secret_key)?;
554
555        self.add_flags(NocFlags::ADD_CSR_REQ_RECVD);
556
557        Ok(self.secret_key.reference())
558    }
559
560    pub fn update_csr_req<C: Crypto>(
561        &mut self,
562        crypto: C,
563        session_mode: &SessionMode,
564    ) -> Result<CanonPkcSecretKeyRef<'_>, Error> {
565        // Must be a CASE session
566        Self::get_case_fab_idx(session_mode)?;
567
568        self.check_state(
569            session_mode,
570            NocFlags::empty(),
571            NocFlags::ADD_CSR_REQ_RECVD | NocFlags::UPDATE_CSR_REQ_RECVD,
572            NocFlags::UPDATE_CSR_REQ_RECVD,
573        )?;
574
575        crypto
576            .generate_secret_key()?
577            .write_canon(&mut self.secret_key)?;
578
579        self.add_flags(NocFlags::UPDATE_CSR_REQ_RECVD);
580
581        Ok(self.secret_key.reference())
582    }
583
584    #[allow(clippy::too_many_arguments)]
585    pub fn update_noc<'a, C: Crypto>(
586        &mut self,
587        crypto: C,
588        time: UtcTime,
589        fabrics: &'a mut Fabrics,
590        session_mode: &SessionMode,
591        icac: Option<&[u8]>,
592        noc: &[u8],
593        buf: &mut [u8],
594        mut mdns_notif: impl FnMut(),
595    ) -> Result<&'a mut Fabric, Error> {
596        let fab_idx = Self::get_case_fab_idx(session_mode)?;
597
598        // `UpdateNOC` only requires the corresponding `CSRRequest` (with
599        // `isForUpdateNOC=true`) to have been processed in this fail-safe
600        // context. Per Matter Core spec it must NOT
601        // have been preceded by `AddTrustedRootCertificate`, `AddNOC`,
602        // `UpdateNOC`, or a CSRRequest of the wrong kind — those go in
603        // `absent`. `validate_certs` further down uses the *committed*
604        // root cert (`fabrics.fabric(fab_idx).root_ca()`), not anything
605        // staged via AddTrustedRootCertificate.
606        self.check_state(
607            session_mode,
608            NocFlags::UPDATE_CSR_REQ_RECVD,
609            NocFlags::ADD_ROOT_CERT_RECVD
610                | NocFlags::ADD_NOC_RECVD
611                | NocFlags::ADD_CSR_REQ_RECVD
612                | NocFlags::UPDATE_NOC_RECVD,
613            NocFlags::UPDATE_NOC_RECVD,
614        )?;
615
616        {
617            let noc_ref = CertRef::new(TLVElement::new(noc));
618            let icac_ref = icac.map(|icac| CertRef::new(TLVElement::new(icac)));
619            // `UpdateNOC` re-uses the existing fabric's root cert; it does
620            // not consume one staged via `AddTrustedRootCertificate` (the
621            // `absent` constraint above ensures none was staged).
622            let fabric_root_ca = fabrics.fabric(fab_idx)?.root_ca();
623            let root_ref = CertRef::new(TLVElement::new(fabric_root_ca));
624
625            // Validate the certs first. A chain that doesn't pass
626            // signature verification (or that doesn't chain back to the
627            // staged root) is reported as `kInvalidNOC` cluster status per
628            // Matter Core spec (`UpdateNOC`).
629            Self::validate_certs(&crypto, time, &noc_ref, icac_ref.as_ref(), &root_ref, buf)
630                .map_err(|_| ErrorCode::NocInvalidNoc)?;
631
632            // The NOC's public key must match the public key derived from
633            // the most recent `CSRRequest(isForUpdateNOC=true)` (Matter
634            // Core spec).
635            let mut csr_pubkey = crate::crypto::CanonPkcPublicKey::new();
636            crypto
637                .secret_key(self.secret_key.reference())?
638                .pub_key()?
639                .write_canon(&mut csr_pubkey)?;
640            if csr_pubkey.access().as_slice() != noc_ref.pubkey()? {
641                Err(ErrorCode::NocInvalidPublicKey)?;
642            }
643
644            // Check that the fabric ID in the NOC matches the fabric
645            // being updated. The root cert pubkey check is implicit: the
646            // chain validation above used the fabric's own root cert.
647
648            let fabric_id = noc_ref.get_fabric_id()?;
649            let fabric = fabrics.fabric(fab_idx)?;
650
651            if fabric_id != fabric.fabric_id() {
652                Err(ErrorCode::NocFabricConflict)?;
653            }
654        }
655
656        // `Fabrics::update` keeps the existing root cert in place — no
657        // need (and no reason) to copy it out of the fabric just to pass
658        // it back in.
659        let fabric = fabrics.update(
660            &crypto,
661            fab_idx,
662            self.secret_key.reference(),
663            noc,
664            icac.unwrap_or(&[]),
665        )?;
666
667        let State::Armed(ctx) = &mut self.state else {
668            // Impossible to be in any other state because otherwise
669            // check_state would have failed
670            unreachable!();
671        };
672
673        ctx.fab_idx = fabric.fab_idx().get();
674        self.add_flags(NocFlags::UPDATE_NOC_RECVD);
675
676        mdns_notif();
677
678        Ok(fabric)
679    }
680
681    #[allow(clippy::too_many_arguments)]
682    pub fn add_noc<'a, C: Crypto>(
683        &mut self,
684        crypto: C,
685        time: UtcTime,
686        fabrics: &'a mut Fabrics,
687        session_mode: &SessionMode,
688        vendor_id: u16,
689        icac: Option<&[u8]>,
690        noc: &[u8],
691        ipk: &[u8],
692        case_admin_subject: u64,
693        buf: &mut [u8],
694        mut mdns_notif: impl FnMut(),
695    ) -> Result<&'a mut Fabric, Error> {
696        self.check_state(
697            session_mode,
698            NocFlags::ADD_ROOT_CERT_RECVD | NocFlags::ADD_CSR_REQ_RECVD,
699            NocFlags::ADD_NOC_RECVD | NocFlags::UPDATE_CSR_REQ_RECVD | NocFlags::UPDATE_NOC_RECVD,
700            NocFlags::ADD_NOC_RECVD,
701        )?;
702
703        // CaseAdminSubject must be either a valid Operational Node ID or a
704        // CASE Authenticated Tag (CAT) — Matter Core spec
705        // (`AddNOC`). Anything else (most commonly 0) is reported as
706        // `kInvalidAdminSubject` cluster status.
707        if !crate::acl::is_node(case_admin_subject) && !crate::acl::is_noc_cat(case_admin_subject) {
708            Err(ErrorCode::NocInvalidAdminSubject)?;
709        }
710
711        // `self.secret_key` was stashed by `add_csr_req`
712        Self::check_new_noc(
713            &crypto,
714            time,
715            fabrics,
716            &self.root_ca,
717            icac,
718            noc,
719            self.secret_key.reference(),
720            buf,
721        )?;
722
723        let fabric = fabrics
724            .add(
725                &crypto,
726                self.secret_key.reference(),
727                &self.root_ca,
728                noc,
729                icac.unwrap_or(&[]),
730                Some(CanonAeadKeyRef::try_new(ipk)?),
731                vendor_id,
732                case_admin_subject,
733            )
734            .map_err(|e| {
735                if e.code() == ErrorCode::ResourceExhausted {
736                    ErrorCode::NocFabricTableFull.into()
737                } else {
738                    e
739                }
740            })?;
741
742        info!(
743            "Added operational fabric with local index {}",
744            fabric.fab_idx()
745        );
746
747        let State::Armed(ctx) = &mut self.state else {
748            // Impossible to be in any other state because otherwise
749            // check_state would have failed
750            unreachable!();
751        };
752
753        ctx.fab_idx = fabric.fab_idx().get();
754        self.add_flags(NocFlags::ADD_NOC_RECVD);
755
756        mdns_notif();
757
758        Ok(fabric)
759    }
760
761    pub fn breadcrumb(&self) -> u64 {
762        self.breadcrumb
763    }
764
765    pub fn set_breadcrumb(&mut self, value: u64) {
766        self.breadcrumb = value;
767    }
768
769    /// The fabric added by `AddNOC` in the current fail-safe context and the
770    /// seconds left until expiry; `None` if there is no such fabric.
771    pub fn pending_add_noc(&self) -> Option<(NonZeroU8, u16)> {
772        let State::Armed(ctx) = &self.state else {
773            return None;
774        };
775
776        if !ctx.flags.contains(NocFlags::ADD_NOC_RECVD) {
777            return None;
778        }
779
780        let fab_idx = NonZeroU8::new(ctx.fab_idx)?;
781
782        let secs_left = ctx
783            .expires_at()
784            .checked_duration_since(Instant::now())
785            .map_or(0, |left| left.as_secs().min(u16::MAX as u64) as u16);
786
787        Some((fab_idx, secs_left))
788    }
789
790    /// Arm the fail-safe for a fabric resumed from a commissioning handover,
791    /// as if `AddNOC` had just been processed for it. `Busy` if already armed.
792    pub fn arm_resumed(
793        &mut self,
794        fab_idx: NonZeroU8,
795        timeout_secs: u16,
796        breadcrumb: u64,
797    ) -> Result<(), Error> {
798        if !matches!(self.state, State::Idle) {
799            return Err(ErrorCode::Busy.into());
800        }
801
802        self.state = State::Armed(ArmedCtx::new(
803            timeout_secs,
804            self.max_cumulative_secs,
805            fab_idx.get(),
806            NocFlags::ADD_ROOT_CERT_RECVD | NocFlags::ADD_CSR_REQ_RECVD | NocFlags::ADD_NOC_RECVD,
807        ));
808        self.breadcrumb = breadcrumb;
809
810        Ok(())
811    }
812
813    /// Check that a NOC is acceptable for a new fabric: the chain verifies
814    /// against `root_ca`, the NOC public key matches `secret_key`, and no
815    /// existing fabric has the same fabric ID under the same root.
816    #[allow(clippy::too_many_arguments)]
817    pub fn check_new_noc<C: Crypto>(
818        crypto: &C,
819        time: UtcTime,
820        fabrics: &Fabrics,
821        root_ca: &[u8],
822        icac: Option<&[u8]>,
823        noc: &[u8],
824        secret_key: CanonPkcSecretKeyRef<'_>,
825        buf: &mut [u8],
826    ) -> Result<(), Error> {
827        let noc_ref = CertRef::new(TLVElement::new(noc));
828        let icac_ref = icac.map(|icac| CertRef::new(TLVElement::new(icac)));
829        let root_ref = CertRef::new(TLVElement::new(root_ca));
830
831        // Validate the certs first. A chain that doesn't pass
832        // signature verification (or that doesn't chain back to the
833        // staged root) is reported as `kInvalidNOC` cluster status per
834        // Matter Core spec (`AddNOC`).
835        Self::validate_certs(crypto, time, &noc_ref, icac_ref.as_ref(), &root_ref, buf)
836            .map_err(|_| ErrorCode::NocInvalidNoc)?;
837
838        // The NOC's public key must match the public key derived from
839        // the most recent `CSRRequest` (Matter Core spec).
840        let mut csr_pubkey = crate::crypto::CanonPkcPublicKey::new();
841        crypto
842            .secret_key(secret_key)?
843            .pub_key()?
844            .write_canon(&mut csr_pubkey)?;
845        if csr_pubkey.access().as_slice() != noc_ref.pubkey()? {
846            Err(ErrorCode::NocInvalidPublicKey)?;
847        }
848
849        // Check that there is no fabric with the same fabric ID and root cert pubkey
850        // as the one in the NOC, to avoid adding duplicate fabrics
851
852        let fabric_id = noc_ref.get_fabric_id()?;
853        let root_cert_pubkey = root_ref.pubkey()?;
854
855        for fabric in fabrics.iter() {
856            if fabric_id == fabric.fabric_id() {
857                let f_root_ref = CertRef::new(TLVElement::new(fabric.root_ca()));
858                let f_root_pubkey = f_root_ref.pubkey()?;
859
860                if root_cert_pubkey == f_root_pubkey {
861                    // A fabric with the same ID and root cert pubkey already exists,
862                    // which means that this NOC cannot be accepted
863                    Err(ErrorCode::NocFabricConflict)?;
864                }
865            }
866        }
867
868        Ok(())
869    }
870
871    #[allow(clippy::too_many_arguments)]
872    fn validate_certs<C: Crypto>(
873        crypto: C,
874        time: UtcTime,
875        noc: &CertRef,
876        icac: Option<&CertRef>,
877        root: &CertRef,
878        buf: &mut [u8],
879    ) -> Result<(), Error> {
880        let mut verifier = noc.verify_chain_start(crypto, time);
881
882        if let Some(icac) = icac {
883            // If ICAC is present handle it. Reject the case where the
884            // commissioner re-uses the RCAC as the ICAC:
885            // the spec requires the ICAC to be a separate CA cert
886            // (i.e. not self-signed).
887            if icac.is_self_signed()? {
888                return Err(ErrorCode::InvalidData.into());
889            }
890            verifier = verifier.add_cert(icac, buf)?;
891        }
892
893        verifier.add_cert(root, buf)?.finalise(buf)
894    }
895
896    fn get_case_fab_idx(session_mode: &SessionMode) -> Result<NonZeroU8, Error> {
897        if let SessionMode::Case { fab_idx, .. } = session_mode {
898            Ok(*fab_idx)
899        } else {
900            // Only CASE session supported
901            Err(ErrorCode::GennCommInvalidAuthentication.into())
902        }
903    }
904
905    fn check_state(
906        &self,
907        session_mode: &SessionMode,
908        present: NocFlags,
909        absent: NocFlags,
910        op: NocFlags,
911    ) -> Result<(), Error> {
912        if let State::Armed(ctx) = &self.state {
913            if matches!(session_mode, SessionMode::PlainText) {
914                // Session is plain text
915                Err(ErrorCode::GennCommInvalidAuthentication)?;
916            }
917
918            if op == NocFlags::UPDATE_NOC_RECVD && !matches!(session_mode, SessionMode::Case { .. })
919            {
920                // Update NOC requires a CASE session
921                Err(ErrorCode::GennCommInvalidAuthentication)?;
922            }
923
924            if ctx.fab_idx != session_mode.fab_idx() {
925                // Fabric index does not match
926                Err(ErrorCode::NocInvalidFabricIndex)?;
927            }
928
929            if !ctx.flags.contains(present) {
930                // State is not what is expected for that concrete command.
931                //
932                // Disambiguate "no CSR at all" from "wrong CSR type" per
933                // Matter Core spec, `AddNOC` / `UpdateNOC`:
934                //   * No `CSRRequest` of either kind seen yet for this
935                //     fail-safe context → `kMissingCsr` cluster status.
936                //   * A CSR was issued but with the opposite
937                //     `isForUpdateNOC` flag from the command being
938                //     processed (e.g. `UpdateNOC` after a CSR for
939                //     `AddNOC`) → IM `CONSTRAINT_ERROR`.
940                let any_csr = ctx
941                    .flags
942                    .intersects(NocFlags::ADD_CSR_REQ_RECVD | NocFlags::UPDATE_CSR_REQ_RECVD);
943                if (op == NocFlags::ADD_NOC_RECVD || op == NocFlags::UPDATE_NOC_RECVD) && !any_csr {
944                    Err(ErrorCode::NocMissingCsr)?;
945                }
946
947                Err(ErrorCode::ConstraintError)?;
948            }
949
950            if !ctx.flags.intersection(absent).is_empty() {
951                // State is not what is expected for that concrete command.
952                //
953                // Two flavours both surface as IM `CONSTRAINT_ERROR` per
954                // Matter Core spec, `AddNOC` / `UpdateNOC`:
955                //   * the same `Add`/`UpdateNOC` was already received in
956                //     this fail-safe context
957                //   * the most recent `CSRRequest` had the wrong
958                //     `isForUpdateNOC` flag for the command being
959                //     processed (e.g. UpdateNOC after an AddNOC-style CSR)
960                Err(ErrorCode::ConstraintError)?;
961            }
962        } else {
963            // Fail-safe is not armed
964            Err(ErrorCode::FailSafeRequired)?;
965        }
966
967        Ok(())
968    }
969
970    fn add_flags(&mut self, flags: NocFlags) {
971        match &mut self.state {
972            State::Armed(ctx) => ctx.flags |= flags,
973            _ => panic!("Not armed"),
974        }
975    }
976}
977
978impl Default for FailSafe {
979    fn default() -> Self {
980        Self::new()
981    }
982}
983
984#[cfg(test)]
985#[cfg_attr(coverage_nightly, coverage(off))]
986mod tests {
987    use core::num::NonZeroU8;
988
989    use crate::cert::gen::VALID_FOREVER;
990    use crate::crypto::{test_only_crypto, CanonPkcSecretKey, Crypto, PKC_CANON_SECRET_KEY_LEN};
991    use crate::dm::ROOT_ENDPOINT_ID;
992    use crate::dm::{ClusterId, EndptId};
993    use crate::error::{Error, ErrorCode};
994    use crate::fabric::tests::{
995        add_fabric, mint_icac, mint_noc, mint_noc_for_pubkey, mint_rcac, pubkey_of, TestRcac,
996        TEST_IPK,
997    };
998    use crate::fabric::{FabricPersist, Fabrics, MAX_FABRICS};
999    use crate::persist::{MemKv, MemKvBlobStore};
1000    use crate::session::SessionMode;
1001    use crate::utils::epoch::UtcTime;
1002
1003    use super::{Expiry, FailSafe, DEFAULT_FAILSAFE_EXPIRY_SECS};
1004
1005    fn pase(fab_idx: u8) -> SessionMode {
1006        SessionMode::Pase { fab_idx }
1007    }
1008
1009    fn case(fab_idx: u8) -> SessionMode {
1010        SessionMode::Case {
1011            fab_idx: NonZeroU8::new(fab_idx).unwrap(),
1012            cat_ids: Default::default(),
1013        }
1014    }
1015
1016    fn idx(i: u8) -> NonZeroU8 {
1017        NonZeroU8::new(i).unwrap()
1018    }
1019
1020    /// A UTC time inside the validity window of every minted certificate.
1021    fn now() -> UtcTime {
1022        UtcTime::Reliable(VALID_FOREVER.not_before as u64 * 1_000_000)
1023    }
1024
1025    fn code<T>(r: Result<T, Error>) -> ErrorCode {
1026        r.err().expect("expected an error").code()
1027    }
1028
1029    /// Arm a fresh fail-safe over `session_mode` with the default expiry.
1030    fn armed(session_mode: &SessionMode) -> FailSafe {
1031        let mut fs = FailSafe::new();
1032        fs.arm(DEFAULT_FAILSAFE_EXPIRY_SECS, 0, session_mode, false)
1033            .unwrap();
1034        fs
1035    }
1036
1037    /// Stage `rcac` via `AddTrustedRootCertificate`, then issue an `AddNOC`-style
1038    /// CSR and return the generated secret key.
1039    fn stage_root_and_csr<C: Crypto>(
1040        crypto: &C,
1041        fs: &mut FailSafe,
1042        session_mode: &SessionMode,
1043        rcac: &TestRcac,
1044    ) -> CanonPkcSecretKey {
1045        let mut buf = [0u8; 1024];
1046        fs.add_trusted_root_cert(crypto, now(), session_mode, &rcac.cert, &mut buf)
1047            .unwrap();
1048
1049        CanonPkcSecretKey::new_from_ref(fs.add_csr_req(crypto, session_mode).unwrap())
1050    }
1051
1052    /// Drive the full `AddNOC` flow over PASE for a new fabric with
1053    /// `fabric_id` / `node_id`, returning the staged RCAC and the local index
1054    /// of the pending fabric.
1055    fn add_noc_flow<C: Crypto>(
1056        crypto: &C,
1057        fs: &mut FailSafe,
1058        fabrics: &mut Fabrics,
1059        fabric_id: u64,
1060        node_id: u64,
1061    ) -> (TestRcac, NonZeroU8) {
1062        let rcac = mint_rcac(crypto, fabric_id, 0x77);
1063        let key = stage_root_and_csr(crypto, fs, &pase(0), &rcac);
1064        let noc = mint_noc_for_pubkey(
1065            crypto,
1066            &rcac,
1067            true,
1068            pubkey_of(crypto, key.reference()).reference(),
1069            node_id,
1070        );
1071
1072        let mut buf = [0u8; 1024];
1073        let fab_idx = fs
1074            .add_noc(
1075                crypto,
1076                now(),
1077                fabrics,
1078                &pase(0),
1079                0xfff1,
1080                None,
1081                &noc,
1082                &TEST_IPK,
1083                node_id,
1084                &mut buf,
1085                || {},
1086            )
1087            .unwrap()
1088            .fab_idx();
1089
1090        (rcac, fab_idx)
1091    }
1092
1093    /// The deadlines the timeout checks sleep until: the fail-safe's while armed,
1094    /// the commissioning window's while open.
1095    #[test]
1096    fn expiry_deadlines() {
1097        use crate::utils::timers::{Duration, Instant};
1098
1099        let mut fs = FailSafe::new();
1100        assert_eq!(fs.expires_at(), None);
1101
1102        let before = Instant::now();
1103        fs = armed(&pase(0));
1104        let expires_at = fs.expires_at().unwrap();
1105        assert!(expires_at >= before + Duration::from_secs(DEFAULT_FAILSAFE_EXPIRY_SECS as u64));
1106        assert!(
1107            expires_at <= Instant::now() + Duration::from_secs(DEFAULT_FAILSAFE_EXPIRY_SECS as u64)
1108        );
1109    }
1110
1111    /// A context ends at most `MaxCumulativeFailsafeSeconds` after it was
1112    /// created: re-arming does not move that end, and a new limit only applies
1113    /// to the contexts created after it.
1114    #[test]
1115    fn rearming_does_not_extend_the_cumulative_lifetime() {
1116        use crate::utils::timers::{Duration, Instant};
1117
1118        let mut fs = FailSafe::new();
1119        fs.set_max_cumulative_secs(10);
1120
1121        let before = Instant::now();
1122        fs.arm(60, 0, &pase(0), false).unwrap();
1123        let after = Instant::now();
1124
1125        let cumulative_end = fs.expires_at().unwrap();
1126        assert!(cumulative_end >= before + Duration::from_secs(10));
1127        assert!(cumulative_end <= after + Duration::from_secs(10));
1128
1129        fs.arm(60, 0, &pase(0), false).unwrap();
1130        assert_eq!(fs.expires_at(), Some(cumulative_end));
1131
1132        fs.set_max_cumulative_secs(1000);
1133        fs.arm(60, 0, &pase(0), false).unwrap();
1134        assert_eq!(fs.expires_at(), Some(cumulative_end));
1135
1136        // A shorter armed timeout still ends the context first
1137        fs.arm(1, 0, &pase(0), false).unwrap();
1138        assert!(fs.expires_at().unwrap() < cumulative_end);
1139    }
1140
1141    #[test]
1142    fn new_and_init_are_idle() {
1143        use crate::utils::init::InitMaybeUninit;
1144
1145        let mut init = core::mem::MaybeUninit::<FailSafe>::uninit();
1146        let init = init.init_with(FailSafe::init());
1147
1148        for fs in [&FailSafe::new(), &FailSafe::default(), &*init] {
1149            assert!(!fs.is_armed());
1150            assert!(!fs.is_armed_for(0));
1151            assert!(!fs.has_pending_noc_for(idx(1)));
1152            assert_eq!(fs.breadcrumb(), 0);
1153            assert!(fs.pending_root_ca().is_none());
1154            assert!(fs.pending_add_noc().is_none());
1155            assert_eq!(code(fs.check_armed(&pase(0))), ErrorCode::FailSafeRequired);
1156            assert_eq!(code(fs.check_armed(&case(1))), ErrorCode::FailSafeRequired);
1157        }
1158    }
1159
1160    #[test]
1161    fn arm_over_pase_from_idle() {
1162        let mut fs = FailSafe::new();
1163        fs.arm(60, 7, &pase(0), false).unwrap();
1164
1165        assert!(fs.is_armed());
1166        assert!(fs.is_armed_for(0));
1167        assert!(!fs.is_armed_for(1));
1168        assert!(!fs.has_pending_noc_for(idx(1)));
1169        assert_eq!(fs.breadcrumb(), 7);
1170        assert!(fs.pending_root_ca().is_none());
1171        assert!(fs.pending_add_noc().is_none());
1172
1173        fs.check_armed(&pase(0)).unwrap();
1174        assert_eq!(
1175            code(fs.check_armed(&case(1))),
1176            ErrorCode::NocInvalidFabricIndex
1177        );
1178        assert_eq!(
1179            code(fs.check_armed(&pase(1))),
1180            ErrorCode::NocInvalidFabricIndex
1181        );
1182        assert_eq!(
1183            code(fs.check_armed(&SessionMode::PlainText)),
1184            ErrorCode::GennCommInvalidAuthentication
1185        );
1186    }
1187
1188    #[test]
1189    fn arm_over_case_from_idle() {
1190        let mut fs = FailSafe::new();
1191        fs.arm(60, 1, &case(2), false).unwrap();
1192
1193        assert!(fs.is_armed());
1194        assert!(fs.is_armed_for(2));
1195        assert!(!fs.is_armed_for(0));
1196        assert_eq!(fs.breadcrumb(), 1);
1197
1198        fs.check_armed(&case(2)).unwrap();
1199        assert_eq!(
1200            code(fs.check_armed(&case(1))),
1201            ErrorCode::NocInvalidFabricIndex
1202        );
1203        assert_eq!(
1204            code(fs.check_armed(&pase(0))),
1205            ErrorCode::NocInvalidFabricIndex
1206        );
1207    }
1208
1209    #[test]
1210    fn arm_rejects_plaintext_sessions() {
1211        let mut fs = FailSafe::new();
1212
1213        assert_eq!(
1214            code(fs.arm(60, 1, &SessionMode::PlainText, false)),
1215            ErrorCode::GennCommInvalidAuthentication
1216        );
1217        assert!(!fs.is_armed());
1218        assert_eq!(fs.breadcrumb(), 0);
1219    }
1220
1221    #[test]
1222    fn arm_over_case_with_open_commissioning_window_is_busy() {
1223        let mut fs = FailSafe::new();
1224        assert_eq!(code(fs.arm(60, 1, &case(1), true)), ErrorCode::Busy);
1225        assert!(!fs.is_armed());
1226
1227        // PASE arming is fine while the window is open
1228        fs.arm(60, 1, &pase(0), true).unwrap();
1229        assert!(fs.is_armed_for(0));
1230    }
1231
1232    #[test]
1233    fn rearm_from_same_session_extends_and_updates_breadcrumb() {
1234        let mut fs = FailSafe::new();
1235        fs.arm(60, 1, &pase(0), false).unwrap();
1236        fs.arm(120, 2, &pase(0), false).unwrap();
1237
1238        assert!(fs.is_armed_for(0));
1239        assert_eq!(fs.breadcrumb(), 2);
1240
1241        // A commissioning window opened meanwhile does not affect re-arming
1242        let mut fs = FailSafe::new();
1243        fs.arm(60, 1, &case(1), false).unwrap();
1244        fs.arm(60, 3, &case(1), true).unwrap();
1245        assert!(fs.is_armed_for(1));
1246        assert_eq!(fs.breadcrumb(), 3);
1247    }
1248
1249    #[test]
1250    fn rearm_from_other_session_is_rejected() {
1251        let mut fs = FailSafe::new();
1252        fs.arm(60, 1, &pase(0), false).unwrap();
1253
1254        assert_eq!(
1255            code(fs.arm(60, 2, &case(1), false)),
1256            ErrorCode::NocInvalidFabricIndex
1257        );
1258        assert_eq!(
1259            code(fs.arm(60, 2, &SessionMode::PlainText, false)),
1260            ErrorCode::GennCommInvalidAuthentication
1261        );
1262
1263        assert!(fs.is_armed_for(0));
1264        assert_eq!(fs.breadcrumb(), 1);
1265
1266        let mut fs = FailSafe::new();
1267        fs.arm(60, 1, &case(1), false).unwrap();
1268        assert_eq!(
1269            code(fs.arm(60, 2, &case(2), false)),
1270            ErrorCode::NocInvalidFabricIndex
1271        );
1272        assert!(fs.is_armed_for(1));
1273    }
1274
1275    #[test]
1276    fn rearm_with_zero_timeout_disarms() {
1277        let mut fs = FailSafe::new();
1278        fs.arm(60, 5, &case(1), false).unwrap();
1279
1280        fs.arm(0, 9, &case(1), false).unwrap();
1281
1282        assert!(!fs.is_armed());
1283        assert_eq!(fs.breadcrumb(), 0);
1284    }
1285
1286    #[test]
1287    fn arm_from_idle_with_zero_timeout_is_a_noop() {
1288        let mut fs = FailSafe::new();
1289        fs.set_breadcrumb(3);
1290        fs.arm(0, 5, &pase(0), false).unwrap();
1291        assert!(!fs.is_armed());
1292        assert_eq!(fs.breadcrumb(), 3);
1293
1294        // The session checks still apply
1295        assert_eq!(
1296            fs.arm(0, 5, &SessionMode::PlainText, false)
1297                .unwrap_err()
1298                .code(),
1299            ErrorCode::GennCommInvalidAuthentication
1300        );
1301    }
1302
1303    /// The `(endpoint, cluster)` notifications an expiry emits.
1304    fn expected_expiry_changes() -> std::vec::Vec<(EndptId, ClusterId)> {
1305        std::vec![(ROOT_ENDPOINT_ID, super::OPERATIONAL_CREDENTIALS_CLUSTER_ID,)]
1306    }
1307
1308    #[test]
1309    fn check_failsafe_timeout_before_expiry_is_a_noop() {
1310        let mut fs = armed(&pase(0));
1311        let mut fabrics = Fabrics::new();
1312        let kv = MemKv::new(MemKvBlobStore::default());
1313        let mut mdns = 0;
1314
1315        let removed = fs
1316            .check_failsafe_timeout(
1317                &mut fabrics,
1318                || panic!("no removal expected"),
1319                &kv,
1320                || mdns += 1,
1321                |_, _| panic!("no change expected"),
1322            )
1323            .unwrap();
1324
1325        assert_eq!(removed, None);
1326        assert!(fs.is_armed_for(0));
1327        assert_eq!(mdns, 0);
1328
1329        // Nor does it do anything when idle
1330        let mut fs = FailSafe::new();
1331        let removed = fs
1332            .check_failsafe_timeout(
1333                &mut fabrics,
1334                || panic!("no removal expected"),
1335                &kv,
1336                || mdns += 1,
1337                |_, _| panic!("no change expected"),
1338            )
1339            .unwrap();
1340        assert_eq!(removed, None);
1341        assert_eq!(mdns, 0);
1342    }
1343
1344    #[test]
1345    fn disarm_requires_case_session_matching_the_armed_fabric() {
1346        let crypto = test_only_crypto();
1347        let mut fabrics = Fabrics::new();
1348        add_fabric(&crypto, &mut fabrics, 0xa, 0x1a);
1349
1350        // Not armed
1351        let mut fs = FailSafe::new();
1352        assert_eq!(
1353            code(fs.disarm(&case(1), &mut fabrics)),
1354            ErrorCode::FailSafeRequired
1355        );
1356
1357        // Armed over PASE: PASE cannot disarm, nor can a CASE session of
1358        // another fabric
1359        let mut fs = armed(&pase(0));
1360        assert_eq!(
1361            code(fs.disarm(&pase(0), &mut fabrics)),
1362            ErrorCode::GennCommInvalidAuthentication
1363        );
1364        assert_eq!(
1365            code(fs.disarm(&case(1), &mut fabrics)),
1366            ErrorCode::NocInvalidFabricIndex
1367        );
1368        assert!(fs.is_armed_for(0));
1369
1370        // Armed over CASE for a fabric that is not in the table
1371        let mut fs = armed(&case(2));
1372        assert_eq!(code(fs.disarm(&case(2), &mut fabrics)), ErrorCode::NotFound);
1373        assert!(fs.is_armed_for(2));
1374
1375        // Armed over CASE for an existing fabric
1376        let mut fs = FailSafe::new();
1377        fs.arm(60, 4, &case(1), false).unwrap();
1378        let fabric = fs.disarm(&case(1), &mut fabrics).unwrap();
1379        assert_eq!(fabric.fab_idx(), idx(1));
1380        assert!(!fs.is_armed());
1381        assert_eq!(fs.breadcrumb(), 0);
1382    }
1383
1384    #[test]
1385    fn breadcrumb_is_settable_and_reset_on_arm_and_disarm() {
1386        let crypto = test_only_crypto();
1387        let mut fabrics = Fabrics::new();
1388        add_fabric(&crypto, &mut fabrics, 0xa, 0x1a);
1389
1390        let mut fs = FailSafe::new();
1391        fs.set_breadcrumb(42);
1392        assert_eq!(fs.breadcrumb(), 42);
1393
1394        fs.arm(60, 7, &case(1), false).unwrap();
1395        assert_eq!(fs.breadcrumb(), 7);
1396
1397        fs.set_breadcrumb(99);
1398        assert_eq!(fs.breadcrumb(), 99);
1399
1400        fs.disarm(&case(1), &mut fabrics).unwrap();
1401        assert_eq!(fs.breadcrumb(), 0);
1402    }
1403
1404    #[test]
1405    fn add_trusted_root_cert_stages_a_pending_root_ca() {
1406        let crypto = test_only_crypto();
1407        let rcac = mint_rcac(&crypto, 0xfab, 0x77);
1408        let mut buf = [0u8; 1024];
1409
1410        // Not armed
1411        let mut fs = FailSafe::new();
1412        assert_eq!(
1413            code(fs.add_trusted_root_cert(&crypto, now(), &pase(0), &rcac.cert, &mut buf)),
1414            ErrorCode::FailSafeRequired
1415        );
1416
1417        let mut fs = armed(&pase(0));
1418
1419        // Wrong session
1420        assert_eq!(
1421            code(fs.add_trusted_root_cert(&crypto, now(), &case(1), &rcac.cert, &mut buf)),
1422            ErrorCode::NocInvalidFabricIndex
1423        );
1424
1425        // Garbage and non-self-signed certs are INVALID_COMMAND
1426        assert_eq!(
1427            code(fs.add_trusted_root_cert(&crypto, now(), &pase(0), &[1, 2, 3], &mut buf)),
1428            ErrorCode::InvalidCommand
1429        );
1430        let icac = mint_icac(&crypto, &rcac);
1431        assert_eq!(
1432            code(fs.add_trusted_root_cert(&crypto, now(), &pase(0), &icac.cert, &mut buf)),
1433            ErrorCode::InvalidCommand
1434        );
1435        assert!(fs.pending_root_ca().is_none());
1436
1437        fs.add_trusted_root_cert(&crypto, now(), &pase(0), &rcac.cert, &mut buf)
1438            .unwrap();
1439        assert_eq!(fs.pending_root_ca(), Some(rcac.cert.as_slice()));
1440
1441        // Only once per fail-safe context
1442        assert_eq!(
1443            code(fs.add_trusted_root_cert(&crypto, now(), &pase(0), &rcac.cert, &mut buf)),
1444            ErrorCode::ConstraintError
1445        );
1446        assert_eq!(fs.pending_root_ca(), Some(rcac.cert.as_slice()));
1447    }
1448
1449    #[test]
1450    fn drop_pending_root_ca_keeps_a_root_bound_by_add_noc() {
1451        let crypto = test_only_crypto();
1452        let rcac = mint_rcac(&crypto, 0xfab, 0x77);
1453        let mut buf = [0u8; 1024];
1454
1455        // An unbound root is dropped, the fail-safe stays armed, and a second
1456        // root is still refused
1457        let mut fs = armed(&pase(0));
1458        fs.add_trusted_root_cert(&crypto, now(), &pase(0), &rcac.cert, &mut buf)
1459            .unwrap();
1460        fs.drop_pending_root_ca();
1461        assert!(fs.pending_root_ca().is_none());
1462        assert!(fs.is_armed());
1463        assert_eq!(
1464            code(fs.add_trusted_root_cert(&crypto, now(), &pase(0), &rcac.cert, &mut buf)),
1465            ErrorCode::ConstraintError
1466        );
1467
1468        // A root that `AddNOC` bound to the pending fabric stays
1469        let mut fabrics = Fabrics::new();
1470        let mut fs = armed(&pase(0));
1471        let (rcac, _) = add_noc_flow(&crypto, &mut fs, &mut fabrics, 0xfab, 0x1234);
1472        fs.drop_pending_root_ca();
1473        assert_eq!(fs.root_ca.as_slice(), rcac.cert.as_slice());
1474    }
1475
1476    #[test]
1477    fn add_csr_req_is_once_per_context_and_pase_cannot_update() {
1478        let crypto = test_only_crypto();
1479
1480        let mut fs = FailSafe::new();
1481        assert_eq!(
1482            code(fs.add_csr_req(&crypto, &pase(0))),
1483            ErrorCode::FailSafeRequired
1484        );
1485
1486        let mut fs = armed(&pase(0));
1487        assert_eq!(
1488            code(fs.add_csr_req(&crypto, &case(1))),
1489            ErrorCode::NocInvalidFabricIndex
1490        );
1491
1492        let key = CanonPkcSecretKey::new_from_ref(fs.add_csr_req(&crypto, &pase(0)).unwrap());
1493        assert_ne!(key.access(), &[0u8; PKC_CANON_SECRET_KEY_LEN]);
1494
1495        assert_eq!(
1496            code(fs.add_csr_req(&crypto, &pase(0))),
1497            ErrorCode::ConstraintError
1498        );
1499        assert_eq!(
1500            code(fs.update_csr_req(&crypto, &pase(0))),
1501            ErrorCode::GennCommInvalidAuthentication
1502        );
1503    }
1504
1505    #[test]
1506    fn update_csr_req_over_case_is_once_per_context() {
1507        let crypto = test_only_crypto();
1508
1509        let mut fs = armed(&case(1));
1510        assert_eq!(
1511            code(fs.update_csr_req(&crypto, &case(2))),
1512            ErrorCode::NocInvalidFabricIndex
1513        );
1514
1515        let key = CanonPkcSecretKey::new_from_ref(fs.update_csr_req(&crypto, &case(1)).unwrap());
1516        assert_ne!(key.access(), &[0u8; PKC_CANON_SECRET_KEY_LEN]);
1517
1518        assert_eq!(
1519            code(fs.update_csr_req(&crypto, &case(1))),
1520            ErrorCode::ConstraintError
1521        );
1522        assert_eq!(
1523            code(fs.add_csr_req(&crypto, &case(1))),
1524            ErrorCode::ConstraintError
1525        );
1526    }
1527
1528    #[test]
1529    fn noc_command_ordering_matrix() {
1530        let crypto = test_only_crypto();
1531        let mut fabrics = Fabrics::new();
1532        add_fabric(&crypto, &mut fabrics, 0xa, 0x1a);
1533        let rcac = mint_rcac(&crypto, 0xfab, 0x77);
1534        let mut buf = [0u8; 1024];
1535
1536        // AddNOC on an armed context that has seen no CSR at all
1537        let mut fs = armed(&pase(0));
1538        fs.add_trusted_root_cert(&crypto, now(), &pase(0), &rcac.cert, &mut buf)
1539            .unwrap();
1540        assert_eq!(
1541            code(fs.add_noc(
1542                &crypto,
1543                now(),
1544                &mut fabrics,
1545                &pase(0),
1546                0xfff1,
1547                None,
1548                &[],
1549                &TEST_IPK,
1550                0x1a,
1551                &mut buf,
1552                || {}
1553            )),
1554            ErrorCode::NocMissingCsr
1555        );
1556
1557        // AddNOC after a CSR but without a trusted root
1558        let mut fs = armed(&pase(0));
1559        fs.add_csr_req(&crypto, &pase(0)).unwrap();
1560        assert_eq!(
1561            code(fs.add_noc(
1562                &crypto,
1563                now(),
1564                &mut fabrics,
1565                &pase(0),
1566                0xfff1,
1567                None,
1568                &[],
1569                &TEST_IPK,
1570                0x1a,
1571                &mut buf,
1572                || {}
1573            )),
1574            ErrorCode::ConstraintError
1575        );
1576
1577        // UpdateNOC over PASE is never allowed
1578        assert_eq!(
1579            code(fs.update_noc(
1580                &crypto,
1581                now(),
1582                &mut fabrics,
1583                &pase(0),
1584                None,
1585                &[],
1586                &mut buf,
1587                || {}
1588            )),
1589            ErrorCode::GennCommInvalidAuthentication
1590        );
1591
1592        // UpdateNOC over CASE without any CSR
1593        let mut fs = armed(&case(1));
1594        assert_eq!(
1595            code(fs.update_noc(
1596                &crypto,
1597                now(),
1598                &mut fabrics,
1599                &case(1),
1600                None,
1601                &[],
1602                &mut buf,
1603                || {}
1604            )),
1605            ErrorCode::NocMissingCsr
1606        );
1607
1608        // UpdateNOC over CASE after an AddNOC-style CSR
1609        fs.add_csr_req(&crypto, &case(1)).unwrap();
1610        assert_eq!(
1611            code(fs.update_noc(
1612                &crypto,
1613                now(),
1614                &mut fabrics,
1615                &case(1),
1616                None,
1617                &[],
1618                &mut buf,
1619                || {}
1620            )),
1621            ErrorCode::ConstraintError
1622        );
1623
1624        // AddNOC over CASE after an UpdateNOC-style CSR
1625        let mut fs = armed(&case(1));
1626        fs.update_csr_req(&crypto, &case(1)).unwrap();
1627        assert_eq!(
1628            code(fs.add_noc(
1629                &crypto,
1630                now(),
1631                &mut fabrics,
1632                &case(1),
1633                0xfff1,
1634                None,
1635                &[],
1636                &TEST_IPK,
1637                0x1a,
1638                &mut buf,
1639                || {}
1640            )),
1641            ErrorCode::ConstraintError
1642        );
1643
1644        // A trusted root staged in an UpdateNOC context blocks UpdateNOC
1645        fs.add_trusted_root_cert(&crypto, now(), &case(1), &rcac.cert, &mut buf)
1646            .unwrap();
1647        assert_eq!(
1648            code(fs.update_noc(
1649                &crypto,
1650                now(),
1651                &mut fabrics,
1652                &case(1),
1653                None,
1654                &[],
1655                &mut buf,
1656                || {}
1657            )),
1658            ErrorCode::ConstraintError
1659        );
1660
1661        // Nothing is allowed from another session
1662        assert_eq!(
1663            code(fs.update_noc(
1664                &crypto,
1665                now(),
1666                &mut fabrics,
1667                &case(2),
1668                None,
1669                &[],
1670                &mut buf,
1671                || {}
1672            )),
1673            ErrorCode::NocInvalidFabricIndex
1674        );
1675    }
1676
1677    #[test]
1678    fn add_noc_creates_a_pending_fabric() {
1679        let crypto = test_only_crypto();
1680        let mut fabrics = Fabrics::new();
1681        let mut fs = armed(&pase(0));
1682
1683        let rcac = mint_rcac(&crypto, 0xfab, 0x77);
1684        let key = stage_root_and_csr(&crypto, &mut fs, &pase(0), &rcac);
1685        assert!(fs.pending_root_ca().is_some());
1686
1687        let noc = mint_noc_for_pubkey(
1688            &crypto,
1689            &rcac,
1690            true,
1691            pubkey_of(&crypto, key.reference()).reference(),
1692            0x1234,
1693        );
1694
1695        let mut buf = [0u8; 1024];
1696        let mut mdns = 0;
1697        let fabric = fs
1698            .add_noc(
1699                &crypto,
1700                now(),
1701                &mut fabrics,
1702                &pase(0),
1703                0xfff1,
1704                None,
1705                &noc,
1706                &TEST_IPK,
1707                0x1a,
1708                &mut buf,
1709                || mdns += 1,
1710            )
1711            .unwrap();
1712
1713        assert_eq!(mdns, 1);
1714        assert_eq!(fabric.fab_idx(), idx(1));
1715        assert_eq!(fabric.node_id(), 0x1234);
1716        assert_eq!(fabric.fabric_id(), 0xfab);
1717        assert_eq!(fabric.vendor_id(), 0xfff1);
1718        assert_eq!(fabric.root_ca(), rcac.cert.as_slice());
1719        assert_eq!(fabric.noc(), noc.as_slice());
1720        assert!(fabric.icac().is_empty());
1721        assert_eq!(fabric.secret_key().access(), key.access());
1722        assert_eq!(fabric.ipk().epoch_key().access(), &TEST_IPK);
1723        assert_eq!(fabric.acl().len(), 1);
1724
1725        // The context now follows the new fabric
1726        assert!(fs.is_armed_for(1));
1727        assert!(!fs.is_armed_for(0));
1728        assert!(fs.has_pending_noc_for(idx(1)));
1729        assert!(!fs.has_pending_noc_for(idx(2)));
1730        assert!(fs.pending_root_ca().is_none());
1731        let (fab_idx, secs_left) = fs.pending_add_noc().unwrap();
1732        assert_eq!(fab_idx, idx(1));
1733        assert!(secs_left <= DEFAULT_FAILSAFE_EXPIRY_SECS);
1734        assert!(secs_left > 0);
1735
1736        // The PASE session is expected to be upgraded to the new fabric
1737        assert_eq!(
1738            code(fs.check_armed(&pase(0))),
1739            ErrorCode::NocInvalidFabricIndex
1740        );
1741        fs.check_armed(&pase(1)).unwrap();
1742
1743        // Only one AddNOC per context
1744        assert_eq!(
1745            code(fs.add_noc(
1746                &crypto,
1747                now(),
1748                &mut fabrics,
1749                &pase(1),
1750                0xfff1,
1751                None,
1752                &noc,
1753                &TEST_IPK,
1754                0x1a,
1755                &mut buf,
1756                || {}
1757            )),
1758            ErrorCode::ConstraintError
1759        );
1760        assert_eq!(
1761            code(fs.add_csr_req(&crypto, &pase(1))),
1762            ErrorCode::ConstraintError
1763        );
1764        assert_eq!(fabrics.iter().count(), 1);
1765    }
1766
1767    #[test]
1768    fn add_noc_with_icac() {
1769        let crypto = test_only_crypto();
1770        let mut fabrics = Fabrics::new();
1771        let mut fs = armed(&pase(0));
1772
1773        let rcac = mint_rcac(&crypto, 0xfab, 0x77);
1774        let icac = mint_icac(&crypto, &rcac);
1775        let key = stage_root_and_csr(&crypto, &mut fs, &pase(0), &rcac);
1776        let noc = mint_noc_for_pubkey(
1777            &crypto,
1778            &icac,
1779            false,
1780            pubkey_of(&crypto, key.reference()).reference(),
1781            0x1234,
1782        );
1783
1784        let mut buf = [0u8; 1024];
1785        let fabric = fs
1786            .add_noc(
1787                &crypto,
1788                now(),
1789                &mut fabrics,
1790                &pase(0),
1791                0xfff1,
1792                Some(&icac.cert),
1793                &noc,
1794                &TEST_IPK,
1795                0x1a,
1796                &mut buf,
1797                || {},
1798            )
1799            .unwrap();
1800
1801        assert_eq!(fabric.icac(), icac.cert.as_slice());
1802        assert_eq!(fabric.node_id(), 0x1234);
1803
1804        // Passing the RCAC itself as the ICAC is rejected
1805        let mut fs = armed(&pase(0));
1806        let key = stage_root_and_csr(&crypto, &mut fs, &pase(0), &rcac);
1807        let noc = mint_noc_for_pubkey(
1808            &crypto,
1809            &rcac,
1810            true,
1811            pubkey_of(&crypto, key.reference()).reference(),
1812            0x1235,
1813        );
1814        assert_eq!(
1815            code(fs.add_noc(
1816                &crypto,
1817                now(),
1818                &mut Fabrics::new(),
1819                &pase(0),
1820                0xfff1,
1821                Some(&rcac.cert),
1822                &noc,
1823                &TEST_IPK,
1824                0x1a,
1825                &mut buf,
1826                || {}
1827            )),
1828            ErrorCode::NocInvalidNoc
1829        );
1830    }
1831
1832    #[test]
1833    fn add_noc_rejects_bad_admin_subject_key_mismatch_and_foreign_chains() {
1834        let crypto = test_only_crypto();
1835        let mut fabrics = Fabrics::new();
1836        let mut buf = [0u8; 1024];
1837
1838        let rcac = mint_rcac(&crypto, 0xfab, 0x77);
1839        let mut fs = armed(&pase(0));
1840        let key = stage_root_and_csr(&crypto, &mut fs, &pase(0), &rcac);
1841        let pubkey = pubkey_of(&crypto, key.reference());
1842        let noc = mint_noc_for_pubkey(&crypto, &rcac, true, pubkey.reference(), 0x1234);
1843
1844        // CaseAdminSubject must be a node ID or a CAT
1845        assert_eq!(
1846            code(fs.add_noc(
1847                &crypto,
1848                now(),
1849                &mut fabrics,
1850                &pase(0),
1851                0xfff1,
1852                None,
1853                &noc,
1854                &TEST_IPK,
1855                0,
1856                &mut buf,
1857                || {}
1858            )),
1859            ErrorCode::NocInvalidAdminSubject
1860        );
1861
1862        // A NOC for some other key than the CSR's
1863        let other_noc = mint_noc(&crypto, &rcac, true, 0x1234);
1864        assert_eq!(
1865            code(fs.add_noc(
1866                &crypto,
1867                now(),
1868                &mut fabrics,
1869                &pase(0),
1870                0xfff1,
1871                None,
1872                &other_noc.cert,
1873                &TEST_IPK,
1874                0x1a,
1875                &mut buf,
1876                || {}
1877            )),
1878            ErrorCode::NocInvalidPublicKey
1879        );
1880
1881        // A NOC not chaining to the staged root
1882        let other_rcac = mint_rcac(&crypto, 0xfab, 0x78);
1883        let foreign_noc =
1884            mint_noc_for_pubkey(&crypto, &other_rcac, true, pubkey.reference(), 0x1234);
1885        assert_eq!(
1886            code(fs.add_noc(
1887                &crypto,
1888                now(),
1889                &mut fabrics,
1890                &pase(0),
1891                0xfff1,
1892                None,
1893                &foreign_noc,
1894                &TEST_IPK,
1895                0x1a,
1896                &mut buf,
1897                || {}
1898            )),
1899            ErrorCode::NocInvalidNoc
1900        );
1901
1902        // A malformed IPK
1903        assert_eq!(
1904            code(fs.add_noc(
1905                &crypto,
1906                now(),
1907                &mut fabrics,
1908                &pase(0),
1909                0xfff1,
1910                None,
1911                &noc,
1912                &TEST_IPK[..15],
1913                0x1a,
1914                &mut buf,
1915                || {}
1916            )),
1917            ErrorCode::InvalidData
1918        );
1919
1920        // None of the failures consumed the context or added a fabric
1921        assert!(fs.is_armed_for(0));
1922        assert!(fs.pending_root_ca().is_some());
1923        assert!(fs.pending_add_noc().is_none());
1924        assert_eq!(fabrics.iter().count(), 0);
1925
1926        // A CAT admin subject is accepted
1927        fs.add_noc(
1928            &crypto,
1929            now(),
1930            &mut fabrics,
1931            &pase(0),
1932            0xfff1,
1933            None,
1934            &noc,
1935            &TEST_IPK,
1936            0xffff_fffd_0001_0001,
1937            &mut buf,
1938            || {},
1939        )
1940        .unwrap();
1941        assert_eq!(fabrics.iter().count(), 1);
1942    }
1943
1944    #[test]
1945    fn add_noc_rejects_duplicate_fabric_and_full_table() {
1946        let crypto = test_only_crypto();
1947        let mut fabrics = Fabrics::new();
1948        let mut buf = [0u8; 1024];
1949
1950        // A fabric with the same fabric ID under the same root already exists
1951        let rcac = mint_rcac(&crypto, 0xfab, 0x77);
1952        let existing = mint_noc(&crypto, &rcac, true, 0x1111);
1953        fabrics
1954            .add(
1955                &crypto,
1956                existing.key.reference(),
1957                &rcac.cert,
1958                &existing.cert,
1959                &[],
1960                Some(crate::crypto::CanonAeadKeyRef::new(&TEST_IPK)),
1961                0xfff1,
1962                0x1111,
1963            )
1964            .unwrap();
1965
1966        let mut fs = armed(&pase(0));
1967        let key = stage_root_and_csr(&crypto, &mut fs, &pase(0), &rcac);
1968        let noc = mint_noc_for_pubkey(
1969            &crypto,
1970            &rcac,
1971            true,
1972            pubkey_of(&crypto, key.reference()).reference(),
1973            0x2222,
1974        );
1975        assert_eq!(
1976            code(fs.add_noc(
1977                &crypto,
1978                now(),
1979                &mut fabrics,
1980                &pase(0),
1981                0xfff1,
1982                None,
1983                &noc,
1984                &TEST_IPK,
1985                0x1a,
1986                &mut buf,
1987                || {}
1988            )),
1989            ErrorCode::NocFabricConflict
1990        );
1991        assert_eq!(fabrics.iter().count(), 1);
1992
1993        // Same fabric ID under a different root is a different fabric
1994        let mut fabrics = Fabrics::new();
1995        for i in 0..MAX_FABRICS as u64 {
1996            add_fabric(&crypto, &mut fabrics, 0x100 + i, 0x200 + i);
1997        }
1998        assert_eq!(
1999            code(fs.add_noc(
2000                &crypto,
2001                now(),
2002                &mut fabrics,
2003                &pase(0),
2004                0xfff1,
2005                None,
2006                &noc,
2007                &TEST_IPK,
2008                0x1a,
2009                &mut buf,
2010                || {}
2011            )),
2012            ErrorCode::NocFabricTableFull
2013        );
2014        assert_eq!(fabrics.iter().count(), MAX_FABRICS);
2015        assert!(fs.pending_add_noc().is_none());
2016    }
2017
2018    #[test]
2019    fn update_noc_replaces_the_fabric_noc() {
2020        let crypto = test_only_crypto();
2021        let mut fabrics = Fabrics::new();
2022        let mut buf = [0u8; 1024];
2023
2024        let rcac = mint_rcac(&crypto, 0xfab, 0x77);
2025        let original = mint_noc(&crypto, &rcac, true, 0x1111);
2026        fabrics
2027            .add(
2028                &crypto,
2029                original.key.reference(),
2030                &rcac.cert,
2031                &original.cert,
2032                &[],
2033                Some(crate::crypto::CanonAeadKeyRef::new(&TEST_IPK)),
2034                0xfff1,
2035                0x1111,
2036            )
2037            .unwrap();
2038        fabrics.update_label(idx(1), "home").unwrap();
2039
2040        let mut fs = armed(&case(1));
2041        let key = CanonPkcSecretKey::new_from_ref(fs.update_csr_req(&crypto, &case(1)).unwrap());
2042        let pubkey = pubkey_of(&crypto, key.reference());
2043
2044        // A NOC for some other key than the CSR's
2045        assert_eq!(
2046            code(fs.update_noc(
2047                &crypto,
2048                now(),
2049                &mut fabrics,
2050                &case(1),
2051                None,
2052                &original.cert,
2053                &mut buf,
2054                || {}
2055            )),
2056            ErrorCode::NocInvalidPublicKey
2057        );
2058
2059        // A NOC not chaining to the fabric's root
2060        let other_rcac = mint_rcac(&crypto, 0xfab, 0x78);
2061        let foreign = mint_noc_for_pubkey(&crypto, &other_rcac, true, pubkey.reference(), 0x2222);
2062        assert_eq!(
2063            code(fs.update_noc(
2064                &crypto,
2065                now(),
2066                &mut fabrics,
2067                &case(1),
2068                None,
2069                &foreign,
2070                &mut buf,
2071                || {}
2072            )),
2073            ErrorCode::NocInvalidNoc
2074        );
2075        assert_eq!(fabrics.get(idx(1)).unwrap().node_id(), 0x1111);
2076        assert!(!fs.has_pending_noc_for(idx(1)));
2077
2078        let noc = mint_noc_for_pubkey(&crypto, &rcac, true, pubkey.reference(), 0x2222);
2079        let mut mdns = 0;
2080        let fabric = fs
2081            .update_noc(
2082                &crypto,
2083                now(),
2084                &mut fabrics,
2085                &case(1),
2086                None,
2087                &noc,
2088                &mut buf,
2089                || mdns += 1,
2090            )
2091            .unwrap();
2092
2093        assert_eq!(mdns, 1);
2094        assert_eq!(fabric.fab_idx(), idx(1));
2095        assert_eq!(fabric.node_id(), 0x2222);
2096        assert_eq!(fabric.noc(), noc.as_slice());
2097        assert_eq!(fabric.secret_key().access(), key.access());
2098        assert_eq!(fabric.root_ca(), rcac.cert.as_slice());
2099        assert_eq!(fabric.label(), "home");
2100
2101        assert!(fs.is_armed_for(1));
2102        assert!(fs.has_pending_noc_for(idx(1)));
2103        // Only `AddNOC` reports a pending fabric
2104        assert!(fs.pending_add_noc().is_none());
2105        assert!(fs.pending_root_ca().is_none());
2106
2107        // Only one UpdateNOC per context
2108        assert_eq!(
2109            code(fs.update_noc(
2110                &crypto,
2111                now(),
2112                &mut fabrics,
2113                &case(1),
2114                None,
2115                &noc,
2116                &mut buf,
2117                || {}
2118            )),
2119            ErrorCode::ConstraintError
2120        );
2121    }
2122
2123    #[test]
2124    fn expire_when_idle_is_a_noop() {
2125        let mut fs = FailSafe::new();
2126        fs.set_breadcrumb(5);
2127
2128        let removed = fs
2129            .expire(
2130                &mut Fabrics::new(),
2131                || {},
2132                MemKv::new(MemKvBlobStore::default()),
2133                || panic!("no mdns notification expected"),
2134                |_, _| panic!("no change expected"),
2135            )
2136            .unwrap();
2137
2138        assert_eq!(removed, None);
2139        assert_eq!(fs.breadcrumb(), 5);
2140    }
2141
2142    #[test]
2143    fn expire_drops_a_fabric_pending_from_add_noc() {
2144        let crypto = test_only_crypto();
2145        let mut fabrics = Fabrics::new();
2146        let mut fs = armed(&pase(0));
2147        fs.set_breadcrumb(3);
2148
2149        let (_, fab_idx) = add_noc_flow(&crypto, &mut fs, &mut fabrics, 0xfab, 0x1234);
2150        assert_eq!(fab_idx, idx(1));
2151        assert!(fabrics.get(idx(1)).is_some());
2152
2153        let mut mdns = 0;
2154        let mut changes = std::vec::Vec::new();
2155        let removed = fs
2156            .expire(
2157                &mut fabrics,
2158                || {},
2159                MemKv::new(MemKvBlobStore::default()),
2160                || mdns += 1,
2161                |ep, cl| changes.push((ep, cl)),
2162            )
2163            .unwrap();
2164
2165        assert_eq!(
2166            removed,
2167            Some(Expiry {
2168                removed_fabric: Some(idx(1))
2169            })
2170        );
2171        assert!(fabrics.get(idx(1)).is_none());
2172        assert_eq!(fabrics.iter().count(), 0);
2173        assert!(!fs.is_armed());
2174        assert_eq!(fs.breadcrumb(), 0);
2175        assert!(fs.pending_add_noc().is_none());
2176        assert_eq!(mdns, 1);
2177        assert_eq!(changes, expected_expiry_changes());
2178    }
2179
2180    #[test]
2181    fn expire_restores_a_persisted_fabric_after_update_noc() {
2182        let crypto = test_only_crypto();
2183        let mut fabrics = Fabrics::new();
2184        let mut buf = [0u8; 1024];
2185
2186        let rcac = mint_rcac(&crypto, 0xfab, 0x77);
2187        let original = mint_noc(&crypto, &rcac, true, 0x1111);
2188        fabrics
2189            .add(
2190                &crypto,
2191                original.key.reference(),
2192                &rcac.cert,
2193                &original.cert,
2194                &[],
2195                Some(crate::crypto::CanonAeadKeyRef::new(&TEST_IPK)),
2196                0xfff1,
2197                0x1111,
2198            )
2199            .unwrap();
2200        fabrics.update_label(idx(1), "home").unwrap();
2201
2202        let kv = MemKv::new(MemKvBlobStore::default());
2203        FabricPersist::new(&kv)
2204            .store(fabrics.get(idx(1)).unwrap())
2205            .unwrap();
2206
2207        let mut fs = armed(&case(1));
2208        let key = CanonPkcSecretKey::new_from_ref(fs.update_csr_req(&crypto, &case(1)).unwrap());
2209        let noc = mint_noc_for_pubkey(
2210            &crypto,
2211            &rcac,
2212            true,
2213            pubkey_of(&crypto, key.reference()).reference(),
2214            0x2222,
2215        );
2216        fs.update_noc(
2217            &crypto,
2218            now(),
2219            &mut fabrics,
2220            &case(1),
2221            None,
2222            &noc,
2223            &mut buf,
2224            || {},
2225        )
2226        .unwrap();
2227        assert_eq!(fabrics.get(idx(1)).unwrap().node_id(), 0x2222);
2228
2229        let removed = fs
2230            .expire(&mut fabrics, || {}, &kv, || {}, |_, _| {})
2231            .unwrap();
2232
2233        // The fabric is resurrected from storage rather than removed
2234        assert_eq!(
2235            removed,
2236            Some(Expiry {
2237                removed_fabric: None
2238            })
2239        );
2240        let fabric = fabrics.get(idx(1)).unwrap();
2241        assert_eq!(fabric.node_id(), 0x1111);
2242        assert_eq!(fabric.noc(), original.cert.as_slice());
2243        assert_eq!(fabric.secret_key().access(), original.key.access());
2244        assert_eq!(fabric.label(), "home");
2245        assert!(!fs.is_armed());
2246    }
2247
2248    #[test]
2249    fn expire_of_a_context_without_pending_noc_keeps_fabrics() {
2250        let crypto = test_only_crypto();
2251        let mut fabrics = Fabrics::new();
2252        add_fabric(&crypto, &mut fabrics, 0xa, 0x1a);
2253
2254        let kv = MemKv::new(MemKvBlobStore::default());
2255        FabricPersist::new(&kv)
2256            .store(fabrics.get(idx(1)).unwrap())
2257            .unwrap();
2258
2259        // Armed over CASE for fabric 1 but nothing staged: the fabric is
2260        // reloaded from its persisted copy and reported as kept
2261        let mut fs = armed(&case(1));
2262        let removed = fs
2263            .expire(&mut fabrics, || {}, &kv, || {}, |_, _| {})
2264            .unwrap();
2265        assert_eq!(
2266            removed,
2267            Some(Expiry {
2268                removed_fabric: None
2269            })
2270        );
2271        assert_eq!(fabrics.get(idx(1)).unwrap().node_id(), 0x1a);
2272
2273        // Armed over PASE with no fabric involved: nothing to roll back
2274        let mut fs = armed(&pase(0));
2275        let removed = fs
2276            .expire(&mut fabrics, || {}, &kv, || {}, |_, _| {})
2277            .unwrap();
2278        assert_eq!(
2279            removed,
2280            Some(Expiry {
2281                removed_fabric: None
2282            })
2283        );
2284        assert_eq!(fabrics.iter().count(), 1);
2285    }
2286
2287    #[test]
2288    fn expire_removes_the_pase_sessions_only_when_armed() {
2289        let mut removals = 0;
2290
2291        let mut fs = armed(&pase(0));
2292        fs.expire(
2293            &mut Fabrics::new(),
2294            || removals += 1,
2295            MemKv::new(MemKvBlobStore::default()),
2296            || {},
2297            |_, _| {},
2298        )
2299        .unwrap();
2300        assert_eq!(removals, 1);
2301
2302        // Not armed anymore
2303        fs.expire(
2304            &mut Fabrics::new(),
2305            || removals += 1,
2306            MemKv::new(MemKvBlobStore::default()),
2307            || {},
2308            |_, _| {},
2309        )
2310        .unwrap();
2311        assert_eq!(removals, 1);
2312    }
2313
2314    #[test]
2315    fn arm_resumed_behaves_like_a_context_after_add_noc() {
2316        let crypto = test_only_crypto();
2317        let mut fabrics = Fabrics::new();
2318        let mut buf = [0u8; 1024];
2319
2320        let mut fs = FailSafe::new();
2321        fs.arm_resumed(idx(3), 30, 11).unwrap();
2322
2323        assert!(fs.is_armed_for(3));
2324        assert!(fs.has_pending_noc_for(idx(3)));
2325        assert_eq!(fs.breadcrumb(), 11);
2326        let (fab_idx, secs_left) = fs.pending_add_noc().unwrap();
2327        assert_eq!(fab_idx, idx(3));
2328        assert!(secs_left <= 30);
2329        // No root cert bytes were staged, so none is pending
2330        assert!(fs.pending_root_ca().is_none());
2331
2332        // Already armed
2333        assert_eq!(code(fs.arm_resumed(idx(4), 30, 12)), ErrorCode::Busy);
2334        assert!(fs.is_armed_for(3));
2335
2336        // The NOC commands are consumed, exactly as after a real AddNOC
2337        assert_eq!(
2338            code(fs.add_csr_req(&crypto, &pase(3))),
2339            ErrorCode::ConstraintError
2340        );
2341        assert_eq!(
2342            code(fs.add_noc(
2343                &crypto,
2344                now(),
2345                &mut fabrics,
2346                &pase(3),
2347                0xfff1,
2348                None,
2349                &[],
2350                &TEST_IPK,
2351                0x1a,
2352                &mut buf,
2353                || {}
2354            )),
2355            ErrorCode::ConstraintError
2356        );
2357
2358        // Re-arming from the same session and disarming work as usual
2359        fs.arm(60, 13, &pase(3), false).unwrap();
2360        assert_eq!(fs.breadcrumb(), 13);
2361        fs.arm(0, 0, &pase(3), false).unwrap();
2362        assert!(!fs.is_armed());
2363
2364        // Arming normally after that is fine again
2365        fs.arm_resumed(idx(4), 30, 12).unwrap();
2366        assert!(fs.is_armed_for(4));
2367    }
2368}