Skip to main content

matter_kit/commissioning/
failsafe.rs

1//! The fail-safe: what makes commissioning recoverable (Core §11.10.7.2).
2//!
3//! Commissioning writes a lot of state into a device — a trusted root, an operational
4//! certificate, a fabric entry, a network configuration — and any of it can fail halfway. A
5//! device that kept the half of it that landed would be neither commissioned nor factory
6//! fresh, which is the one state nobody can recover from without a reset button.
7//!
8//! So every commissioning write happens inside a **fail-safe context**: a transaction with a
9//! timer. If the commissioner finishes, `CommissioningComplete` disarms it and the state
10//! stands. If anything goes wrong — a crash, a lost network, a commissioner that walks away
11//! — the timer expires and §11.10.7.2.2's eleven cleanup steps put the device back.
12//!
13//! # Two timers, and why the second one cannot be extended
14//!
15//! `ArmFailSafe` may be called again to extend the deadline, which a commissioner doing slow
16//! work needs. That alone would let a commissioner hold a device hostage forever, so
17//! §11.10.7.2 adds a second timer:
18//!
19//! > On creation of the Fail Safe Context a second timer SHALL be created to expire at
20//! > MaxCumulativeFailsafeSeconds … it SHALL NOT be extended or modified on subsequent
21//! > invocations of ArmFailSafe associated with this Fail Safe Context.
22//!
23//! The first timer bounds one step; the second bounds the whole attempt. [`FailSafe::arm`]
24//! enforces both.
25//!
26//! # A restart is an expiry
27//!
28//! > If the receiver restarts unexpectedly (e.g., power interruption, software crash, or
29//! > other reset) the receiver SHALL behave as if the fail-safe timer expired and perform the
30//! > sequence of clean-up steps listed below.
31//!
32//! Which is why nothing a fail-safe protects may be committed to persistent storage before
33//! `CommissioningComplete`: a device that persisted a fabric and then lost power would come
34//! back holding a fabric no commissioner knows about. [`FailSafe`] is deliberately not
35//! persistable for that reason.
36
37use crate::error::{Result, bail};
38use crate::msg::FabricIndex;
39use crate::platform::{Duration, Instant};
40
41/// `CommissioningErrorEnum` (§11.10.5.1).
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
43#[repr(u8)]
44#[non_exhaustive]
45pub enum CommissioningError {
46    /// `0` — no error.
47    Ok = 0,
48    /// `1` — "Attempting to set regulatory configuration to a region or indoor/outdoor mode
49    /// for which the server does not have proper configuration."
50    ValueOutsideRange = 1,
51    /// `2` — "Executed CommissioningComplete outside CASE session."
52    InvalidAuthentication = 2,
53    /// `3` — "Executed CommissioningComplete when there was no active Fail-Safe context."
54    NoFailSafe = 3,
55    /// `4` — "Attempting to arm fail-safe or execute CommissioningComplete from a fabric
56    /// different than the one associated with the current fail-safe context."
57    BusyWithOtherAdmin = 4,
58    /// `5` — a required Terms and Conditions feature was not accepted.
59    RequiredTcNotAccepted = 5,
60    /// `6` — no or insufficient Terms and Conditions acknowledgements.
61    TcAcknowledgementsNotReceived = 6,
62    /// `7` — the acknowledged Terms and Conditions version is below the minimum.
63    TcMinVersionNotMet = 7,
64}
65
66impl CommissioningError {
67    /// The value the enum encodes as.
68    #[must_use]
69    pub const fn value(self) -> u8 {
70        self as u8
71    }
72
73    /// Whether this is [`CommissioningError::Ok`].
74    #[must_use]
75    pub const fn is_ok(self) -> bool {
76        matches!(self, Self::Ok)
77    }
78}
79
80/// "a conservative initial duration (in seconds) to set in the FailSafe for the commissioning
81/// flow to complete successfully" — §11.10.7.2's `ExpiryLengthSeconds` fallback.
82pub const DEFAULT_EXPIRY_SECONDS: u16 = 900;
83
84/// §11.10.5.4: "it is RECOMMENDED that the value of this field be aligned with the initial
85/// Announcement Duration and default to 900 seconds."
86pub const DEFAULT_MAX_CUMULATIVE_SECONDS: u16 = 900;
87
88/// `BasicCommissioningInfo` (§11.10.5.4).
89#[derive(Debug, Clone, Copy, PartialEq, Eq)]
90pub struct BasicCommissioningInfo {
91    /// `FailSafeExpiryLengthSeconds [0]`.
92    pub expiry_length_seconds: u16,
93    /// `MaxCumulativeFailsafeSeconds [1]`, which "SHALL be greater than or equal to the
94    /// FailSafeExpiryLengthSeconds".
95    pub max_cumulative_seconds: u16,
96}
97
98impl Default for BasicCommissioningInfo {
99    fn default() -> Self {
100        Self {
101            expiry_length_seconds: DEFAULT_EXPIRY_SECONDS,
102            max_cumulative_seconds: DEFAULT_MAX_CUMULATIVE_SECONDS,
103        }
104    }
105}
106
107impl BasicCommissioningInfo {
108    /// Checks §11.10.5.4's ordering constraint.
109    #[must_use]
110    pub const fn is_valid(&self) -> bool {
111        self.max_cumulative_seconds >= self.expiry_length_seconds
112    }
113}
114
115/// What has happened inside the current fail-safe period, and therefore what must be undone.
116///
117/// §11.10.7.2's "Fail Safe Context" lists exactly this state. Each flag decides one of
118/// §11.10.7.2.2's cleanup steps: without them, expiry could not tell a device that merely
119/// armed a fail-safe from one that joined a fabric.
120#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
121pub struct Progress {
122    /// "Whether an AddNOC command … has taken place" — step 7 removes the fabric it added.
123    pub added_noc: bool,
124    /// Whether `UpdateNOC` has — step 6 reverts that fabric's credentials.
125    pub updated_noc: bool,
126    /// Whether `CSRRequest` has — step 8 discards the operational key it generated, but only
127    /// if no NOC command used it.
128    pub csr_requested: bool,
129    /// Whether `AddTrustedRootCertificate` has — step 9 removes roots no fabric references.
130    pub added_trusted_root: bool,
131    /// Whether the Network Commissioning `Networks` attribute was touched — step 5 restores
132    /// it.
133    pub changed_networks: bool,
134}
135
136impl Progress {
137    /// Whether the operational key from a `CSRRequest` is now orphaned.
138    ///
139    /// §11.10.7.2.2 step 8: "If the CSRRequest command had been successfully invoked, but no
140    /// AddNOC or UpdateNOC command had been successfully invoked, then the new operational
141    /// key pair … SHALL be removed as it is no longer needed."
142    #[must_use]
143    pub const fn orphaned_operational_key(&self) -> bool {
144        self.csr_requested && !self.added_noc && !self.updated_noc
145    }
146}
147
148/// The armed fail-safe context.
149#[derive(Debug, Clone, Copy, PartialEq, Eq)]
150pub struct Armed {
151    /// When the current `ExpiryLengthSeconds` runs out.
152    pub expires_at: Instant,
153    /// When the cumulative timer runs out. Never extended.
154    pub cumulative_expires_at: Instant,
155    /// The fabric the context is scoped to.
156    ///
157    /// "starting at the accessing fabric index for the ArmFailSafe command, and updated with
158    /// the Fabric Index associated with an AddNOC or an UpdateNOC command being invoked
159    /// successfully". `None` on a PASE session, which has no accessing fabric.
160    pub fabric_index: Option<FabricIndex>,
161    /// What has happened so far.
162    pub progress: Progress,
163}
164
165/// The fail-safe state machine (§11.10.7.2).
166///
167/// Holds no timer of its own: every method takes the current [`Instant`], so the same code
168/// runs against `platform::sim`'s virtual clock in a test and a real one on a device — which
169/// is how the expiry paths get tested at all.
170#[derive(Debug, Clone, Copy, PartialEq, Eq)]
171pub struct FailSafe {
172    info: BasicCommissioningInfo,
173    armed: Option<Armed>,
174    /// §11.10.6.1's `Breadcrumb`. Reset to zero on expiry (step 10), on
175    /// `CommissioningComplete` (step 5), and "on start/restart of the server".
176    breadcrumb: u64,
177}
178
179/// What a caller must do after the fail-safe expired (§11.10.7.2.2).
180///
181/// The cleanup steps touch the fabric table, the session table, the key store and the network
182/// configuration — none of which this module owns. So expiry *reports* what must be undone
183/// and the caller does it, which is also what keeps the eleven steps auditable against the
184/// specification rather than buried in a method.
185#[derive(Debug, Clone, Copy, PartialEq, Eq)]
186pub struct Cleanup {
187    /// Step 2 and 3: terminate any open PASE session and revoke its administrative privilege.
188    pub close_pase_sessions: bool,
189    /// Step 4: terminate CASE sessions for this fabric, if a NOC command recorded one.
190    pub close_case_sessions_for: Option<FabricIndex>,
191    /// Step 5: restore the `Networks` attribute.
192    pub restore_networks: bool,
193    /// Step 6: revert this fabric's operational key, NOC and ICAC.
194    pub revert_noc_for: Option<FabricIndex>,
195    /// Step 7: remove the fabric `AddNOC` added, as though by `RemoveFabric`.
196    pub remove_fabric: Option<FabricIndex>,
197    /// Step 8: discard the operational key a `CSRRequest` generated and nothing used.
198    pub discard_operational_key: bool,
199    /// Step 9: remove trusted roots no fabric references.
200    pub prune_trusted_roots: bool,
201}
202
203impl FailSafe {
204    /// A disarmed fail-safe.
205    #[must_use]
206    pub const fn new(info: BasicCommissioningInfo) -> Self {
207        Self {
208            info,
209            armed: None,
210            breadcrumb: 0,
211        }
212    }
213
214    /// The `BasicCommissioningInfo` attribute.
215    #[must_use]
216    pub const fn info(&self) -> BasicCommissioningInfo {
217        self.info
218    }
219
220    /// The `Breadcrumb` attribute (§11.10.6.1).
221    #[must_use]
222    pub const fn breadcrumb(&self) -> u64 {
223        self.breadcrumb
224    }
225
226    /// Writes the `Breadcrumb`. Its content "is unspecified and its value is not otherwise
227    /// used by the functioning of any cluster".
228    pub const fn set_breadcrumb(&mut self, value: u64) {
229        self.breadcrumb = value;
230    }
231
232    /// Whether a context is currently armed, as of `now`.
233    ///
234    /// Expiry is *lazy*: nothing here runs on a timer, so a caller that never asks never
235    /// learns. A device drives this from its own timer and from
236    /// [`FailSafe::next_deadline`].
237    #[must_use]
238    pub fn is_armed(&self, now: Instant) -> bool {
239        self.armed
240            .is_some_and(|armed| !Self::has_expired(&armed, now))
241    }
242
243    /// The armed context, if one is live as of `now`.
244    #[must_use]
245    pub fn armed(&self, now: Instant) -> Option<Armed> {
246        self.armed.filter(|armed| !Self::has_expired(armed, now))
247    }
248
249    /// When the next expiry is due, whichever timer is sooner.
250    #[must_use]
251    pub fn next_deadline(&self) -> Option<Instant> {
252        self.armed.map(|armed| {
253            if armed.cumulative_expires_at < armed.expires_at {
254                armed.cumulative_expires_at
255            } else {
256                armed.expires_at
257            }
258        })
259    }
260
261    fn has_expired(armed: &Armed, now: Instant) -> bool {
262        now >= armed.expires_at || now >= armed.cumulative_expires_at
263    }
264
265    /// `ArmFailSafe` (§11.10.7.2).
266    ///
267    /// `accessing_fabric` is the fabric of the session the command arrived on — `None` for a
268    /// PASE session, which is the ordinary case during initial commissioning.
269    /// `window_open_over_case` is the one condition that is not about the timer:
270    ///
271    /// > If the fail-safe timer is not currently armed, the commissioning window is open, and
272    /// > the command was received over a CASE session … respond with … BusyWithOtherAdmin.
273    /// > This is done to allow commissioners, which use PASE connections, the opportunity to
274    /// > use the failsafe during the relatively short commissioning window.
275    ///
276    /// That is not a conflict between two administrators — it is a *priority* rule, holding
277    /// the fail-safe for the commissioner that is mid-flow over PASE.
278    pub fn arm(
279        &mut self,
280        expiry_length_seconds: u16,
281        breadcrumb: u64,
282        accessing_fabric: Option<FabricIndex>,
283        now: Instant,
284        window_open_over_case: bool,
285    ) -> ArmResult {
286        // A context that lapsed while nobody was looking is still owed its cleanup. A device
287        // drives that from its own timer ([`FailSafe::next_deadline`]), but a device without
288        // one would otherwise discard the lapsed context here — keeping the half-added fabric
289        // that step 7 exists to remove.
290        let lapsed = self.expire(now);
291
292        let live = self.armed(now);
293
294        let outcome = if live.is_none() && window_open_over_case {
295            ArmOutcome::Refused(CommissioningError::BusyWithOtherAdmin)
296        } else {
297            match (expiry_length_seconds, live) {
298                // "If ExpiryLengthSeconds is 0 and the fail-safe timer was already armed and
299                // the accessing fabric matches … the fail-safe timer SHALL be immediately
300                // expired (see further below for side-effects of expiration)."
301                (0, Some(armed)) if armed.fabric_index == accessing_fabric => {
302                    let cleanup = self.expire_now(armed);
303                    return ArmResult {
304                        outcome: ArmOutcome::Disarmed,
305                        // Only one context can be live, so `lapsed` is necessarily `None`
306                        // here; `or` keeps that an invariant rather than an assumption.
307                        cleanup: lapsed.or(Some(cleanup)),
308                    };
309                }
310                // "If ExpiryLengthSeconds is 0 and the fail-safe timer was not armed, then
311                // this command invocation SHALL lead to a success response with no
312                // side-effects against the fail-safe context." The Breadcrumb is not part of
313                // that context — "The value of the Breadcrumb field SHALL be written to the
314                // Breadcrumb on successful execution of the command" applies to every
315                // success — so it lands.
316                (0, None) => {
317                    self.breadcrumb = breadcrumb;
318                    ArmOutcome::NoChange
319                }
320                // A zero expiry from a different fabric is the conflict case: otherwise any
321                // administrator could cancel a commissioner mid-flow and trigger its
322                // rollback.
323                (0, Some(_)) => ArmOutcome::Refused(CommissioningError::BusyWithOtherAdmin),
324                // "If ExpiryLengthSeconds is non-zero and the fail-safe timer was not
325                // currently armed, then the fail-safe timer SHALL be armed for that
326                // duration."
327                (seconds, None) => {
328                    let cumulative = now.saturating_add(Duration::from_secs(u64::from(
329                        self.info.max_cumulative_seconds,
330                    )));
331                    self.armed = Some(Armed {
332                        expires_at: Self::deadline(now, seconds, cumulative),
333                        cumulative_expires_at: cumulative,
334                        fabric_index: accessing_fabric,
335                        progress: Progress::default(),
336                    });
337                    self.breadcrumb = breadcrumb;
338                    ArmOutcome::Armed
339                }
340                // "…and the accessing Fabric matches the fail-safe context's associated
341                // Fabric, then the fail-safe timer SHALL be re-armed to expire in
342                // ExpiryLengthSeconds."
343                (seconds, Some(armed)) if armed.fabric_index == accessing_fabric => {
344                    // The cumulative timer is *not* touched: that is what stops an
345                    // administrator extending a hold on the device indefinitely.
346                    self.armed = Some(Armed {
347                        expires_at: Self::deadline(now, seconds, armed.cumulative_expires_at),
348                        ..armed
349                    });
350                    self.breadcrumb = breadcrumb;
351                    ArmOutcome::Armed
352                }
353                // "Otherwise … BusyWithOtherAdmin, indicating a likely conflict between
354                // commissioners."
355                (_, Some(_)) => ArmOutcome::Refused(CommissioningError::BusyWithOtherAdmin),
356            }
357        };
358
359        ArmResult {
360            outcome,
361            cleanup: lapsed,
362        }
363    }
364
365    /// The expiry instant, clamped so it can never outlast the cumulative timer.
366    fn deadline(now: Instant, seconds: u16, cumulative: Instant) -> Instant {
367        let requested = now.saturating_add(Duration::from_secs(u64::from(seconds)));
368        if requested > cumulative {
369            cumulative
370        } else {
371            requested
372        }
373    }
374
375    /// Records that something happened inside the fail-safe period.
376    ///
377    /// Returns [`ErrorCode::InvalidState`](crate::error::ErrorCode::InvalidState) when nothing is armed, which is what makes
378    /// §11.18's `FAILSAFE_REQUIRED` reachable: a command that mutates commissioning state
379    /// outside a fail-safe has nothing to be rolled back by.
380    pub fn record(&mut self, now: Instant, f: impl FnOnce(&mut Progress)) -> Result<()> {
381        let Some(armed) = self.armed.as_mut().filter(|a| !Self::has_expired(a, now)) else {
382            bail!(InvalidState)
383        };
384        f(&mut armed.progress);
385        Ok(())
386    }
387
388    /// Moves the context to the fabric an `AddNOC` or `UpdateNOC` just created or changed.
389    ///
390    /// §11.10.7.2: the context's fabric index is "updated with the Fabric Index associated
391    /// with an AddNOC or an UpdateNOC command being invoked successfully". That is what lets
392    /// `CommissioningComplete` arrive over CASE on the *new* fabric and still match.
393    pub fn adopt_fabric(&mut self, fabric: FabricIndex, now: Instant) -> Result<()> {
394        let Some(armed) = self.armed.as_mut().filter(|a| !Self::has_expired(a, now)) else {
395            bail!(InvalidState)
396        };
397        armed.fabric_index = Some(fabric);
398        Ok(())
399    }
400
401    /// `CommissioningComplete` (§11.10.7.6).
402    ///
403    /// `over_case` and `accessing_fabric` describe the session it arrived on. The three
404    /// refusals are exactly the ones §11.10.7.6 names, and the order matters: a command with
405    /// no fail-safe at all is `NoFailSafe` whether or not it came over CASE.
406    pub fn complete(
407        &mut self,
408        over_case: bool,
409        accessing_fabric: Option<FabricIndex>,
410        now: Instant,
411    ) -> CompleteResult {
412        // As in [`FailSafe::arm`]: a context that lapsed unobserved is still owed its
413        // cleanup, and this is the last moment to notice before answering `NoFailSafe`.
414        let lapsed = self.expire(now);
415
416        let Some(armed) = self.armed(now) else {
417            // "An ErrorCode of NoFailSafe SHALL be responded to the invoker if the
418            // CommissioningComplete command was received when no Fail-Safe context exists."
419            return CompleteResult {
420                error: CommissioningError::NoFailSafe,
421                cleanup: lapsed,
422            };
423        };
424        if !over_case {
425            // "this command is only permitted over CASE … An ErrorCode of
426            // InvalidAuthentication SHALL be responded" otherwise.
427            return CompleteResult {
428                error: CommissioningError::InvalidAuthentication,
429                cleanup: lapsed,
430            };
431        }
432        if accessing_fabric.is_none() || accessing_fabric != armed.fabric_index {
433            // "or if the accessing fabric is not the one associated with the ongoing
434            // Fail-Safe context." After AddNOC that is the *new* fabric, which
435            // `adopt_fabric` recorded.
436            return CompleteResult {
437                error: CommissioningError::InvalidAuthentication,
438                cleanup: lapsed,
439            };
440        }
441
442        // Steps 1 and 5. Steps 2, 3 and 4 touch the commissioning window and the session
443        // table, which this does not own — [`Completion`](crate::clusters::
444        // general_commissioning::Completion) reports them.
445        self.armed = None;
446        self.breadcrumb = 0;
447        CompleteResult {
448            error: CommissioningError::Ok,
449            cleanup: lapsed,
450        }
451    }
452
453    /// Expires the context and reports §11.10.7.2.2's cleanup steps.
454    ///
455    /// Call this when [`FailSafe::next_deadline`] passes, and on start-up: "If the receiver
456    /// restarts unexpectedly … the receiver SHALL behave as if the fail-safe timer expired."
457    ///
458    /// Returns `None` if nothing was armed.
459    pub fn expire(&mut self, now: Instant) -> Option<Cleanup> {
460        let armed = self.armed?;
461        if !Self::has_expired(&armed, now) {
462            return None;
463        }
464        Some(self.expire_now(armed))
465    }
466
467    /// Expires `armed`, whatever the time — what `ArmFailSafe(0)` does.
468    fn expire_now(&mut self, armed: Armed) -> Cleanup {
469        self.armed = None;
470        // Step 10: "Reset the Breadcrumb attribute to zero."
471        self.breadcrumb = 0;
472        let progress = armed.progress;
473        Cleanup {
474            // Steps 2 and 3: terminate any open PASE session and revoke the temporary
475            // administrative privileges it was granted. Unconditional — §11.10.7.2.2 does not
476            // make them depend on what happened during the period.
477            close_pase_sessions: true,
478            // Step 4: only if a NOC command recorded a fabric.
479            close_case_sessions_for: (progress.added_noc || progress.updated_noc)
480                .then_some(armed.fabric_index)
481                .flatten(),
482            // Step 5.
483            restore_networks: progress.changed_networks,
484            // Step 6.
485            revert_noc_for: progress.updated_noc.then_some(armed.fabric_index).flatten(),
486            // Step 7.
487            remove_fabric: progress.added_noc.then_some(armed.fabric_index).flatten(),
488            // Step 8.
489            discard_operational_key: progress.orphaned_operational_key(),
490            // Step 9.
491            prune_trusted_roots: progress.added_trusted_root,
492        }
493    }
494}
495
496/// What `ArmFailSafe` did (§11.10.7.2).
497#[derive(Debug, Clone, Copy, PartialEq, Eq)]
498pub enum ArmOutcome {
499    /// The timer was armed or re-armed; answer `OK`.
500    Armed,
501    /// `ExpiryLengthSeconds` was zero and nothing was armed: a success with no side-effect
502    /// on the fail-safe context. Answer `OK`.
503    NoChange,
504    /// `ExpiryLengthSeconds` was zero and a matching context was armed, so it expired
505    /// immediately. [`ArmResult::cleanup`] carries the steps that still apply.
506    Disarmed,
507    /// The command was refused; answer with this error and change nothing.
508    Refused(CommissioningError),
509}
510
511/// What `ArmFailSafe` produced.
512///
513/// `cleanup` is separate from `outcome` because the two answer different questions: the
514/// outcome decides the `ErrorCode` in the response, and the cleanup is work the device owes
515/// whether the command succeeded or not — a context that lapsed while nobody was watching is
516/// reaped here, and dropping it on the floor would leave behind exactly the half-commissioned
517/// state §11.10.7.2.2 exists to prevent.
518#[derive(Debug, Clone, Copy, PartialEq, Eq)]
519pub struct ArmResult {
520    /// What the command did; [`ArmOutcome::error_code`] turns it into a response.
521    pub outcome: ArmOutcome,
522    /// §11.10.7.2.2's cleanup steps, if any context ended.
523    pub cleanup: Option<Cleanup>,
524}
525
526/// What `CommissioningComplete` produced (§11.10.7.6).
527#[derive(Debug, Clone, Copy, PartialEq, Eq)]
528pub struct CompleteResult {
529    /// The `ErrorCode` for the response.
530    pub error: CommissioningError,
531    /// §11.10.7.2.2's cleanup steps, owed to a context that had already lapsed. A *successful*
532    /// completion produces none: it is not a rollback.
533    pub cleanup: Option<Cleanup>,
534}
535
536impl ArmOutcome {
537    /// The `ErrorCode` to put in an `ArmFailSafeResponse`.
538    #[must_use]
539    pub const fn error_code(&self) -> CommissioningError {
540        match self {
541            Self::Armed | Self::NoChange | Self::Disarmed => CommissioningError::Ok,
542            Self::Refused(error) => *error,
543        }
544    }
545}