rs-matter-node-core 0.5.0

Native Rust implementation of the Matter (Smart-Home) ecosystem - what the node is built on: fabrics, ACL, fail-safe
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
/*
 *
 *    Copyright (c) 2022-2026 Project CHIP Authors
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

use core::num::NonZeroU8;

use crate::cert::{CertRef, MAX_CERT_TLV_LEN};
use crate::crypto::{
    CanonAeadKeyRef, CanonPkcSecretKey, CanonPkcSecretKeyRef, Crypto, PublicKey, SecretKey,
    SigningSecretKey, PKC_SECRET_KEY_ZEROED,
};
use crate::dm::ROOT_ENDPOINT_ID;
use crate::dm::{ClusterId, EndptId, HandlerContext, LifecycleOp};
use crate::error::{Error, ErrorCode};
use crate::fabric::{Fabric, Fabrics};
use crate::im::IMStatusCode;
use crate::persist::KvBlobStoreAccess;
use crate::session::SessionMode;
use crate::tlv::TLVElement;
use crate::utils::bitflags::bitflags;
use crate::utils::epoch::UtcTime;
use crate::utils::init::{init, Init};
use crate::utils::storage::Vec;
use crate::utils::timers::{Duration, Instant};

bitflags! {
    #[repr(transparent)]
    #[derive(Default)]
    #[cfg_attr(not(feature = "defmt"), derive(Debug, Copy, Clone, Eq, PartialEq, Hash))]
    pub struct NocFlags: u8 {
        const ADD_CSR_REQ_RECVD = 0x01;
        const UPDATE_CSR_REQ_RECVD = 0x02;
        const ADD_ROOT_CERT_RECVD = 0x04;
        const ADD_NOC_RECVD = 0x08;
        const UPDATE_NOC_RECVD = 0x10;
    }
}

#[derive(PartialEq)]
pub struct ArmedCtx {
    armed_at: Instant,
    timeout_secs: u16,
    /// When the context ends regardless of re-arms: set when it is created,
    /// `MaxCumulativeFailsafeSeconds` later, and never moved
    cumulative_expires_at: Instant,
    fab_idx: u8,
    flags: NocFlags,
}

impl ArmedCtx {
    fn new(timeout_secs: u16, max_cumulative_secs: u16, fab_idx: u8, flags: NocFlags) -> Self {
        let now = Instant::now();

        Self {
            armed_at: now,
            timeout_secs,
            cumulative_expires_at: now
                .saturating_add(Duration::from_secs(max_cumulative_secs as u64)),
            fab_idx,
            flags,
        }
    }

    /// When the context expires: at the end of the armed timeout, or of its
    /// cumulative lifetime, whichever comes first.
    fn expires_at(&self) -> Instant {
        self.armed_at
            .saturating_add(Duration::from_secs(self.timeout_secs as u64))
            .min(self.cumulative_expires_at)
    }
}

#[derive(PartialEq)]
pub enum State {
    Idle,
    Armed(ArmedCtx),
}

pub enum IMError {
    Error(Error),
    Status(IMStatusCode),
}

impl From<Error> for IMError {
    fn from(e: Error) -> Self {
        IMError::Error(e)
    }
}

impl From<IMStatusCode> for IMError {
    fn from(e: IMStatusCode) -> Self {
        IMError::Status(e)
    }
}

/// Default fail-safe expiry length used when the device implicitly arms the
/// fail-safe (e.g. on PASE session establishment). Mirrors
/// `CHIP_DEVICE_CONFIG_FAILSAFE_EXPIRY_LENGTH_SEC` from the reference SDK.
pub const DEFAULT_FAILSAFE_EXPIRY_SECS: u16 = 60;

/// Default `MaxCumulativeFailsafeSeconds`, the longest a fail-safe context
/// lasts however often it is re-armed, until [`FailSafe::set_max_cumulative_secs`]
/// sets the node's own.
pub const DEFAULT_FAILSAFE_MAX_CUMULATIVE_SECS: u16 = 900;

/// The ID of the Operational Credentials cluster.
const OPERATIONAL_CREDENTIALS_CLUSTER_ID: ClusterId = 0x003E;

/// The outcome of a fail-safe expiry.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct Expiry {
    /// The fabric the rollback removed, if any.
    pub removed_fabric: Option<NonZeroU8>,
}

impl Expiry {
    /// Broadcast the expiry to the handlers of `ctx`: `LifecycleOp::FailSafeExpiry`,
    /// then the removal of the fabric the rollback dropped, if any.
    ///
    /// The broadcasts run the handlers inline, so this must NOT be called
    /// while holding the Matter state lock.
    ///
    /// The expiry removes the PASE sessions, so the caller also has to tell the
    /// waiters on them, with `Transport::notify_session_removed`.
    pub fn notify(&self, ctx: impl HandlerContext) {
        if let Err(e) = ctx.broadcast_lifecycle(LifecycleOp::FailSafeExpiry) {
            warn!("Failed to broadcast the fail-safe expiry: {:?}", e);
        }

        if let Some(fab_idx) = self.removed_fabric {
            ctx.notify_fabric_removed(fab_idx);
        }
    }
}

pub struct FailSafe {
    state: State,
    secret_key: CanonPkcSecretKey,
    root_ca: Vec<u8, { MAX_CERT_TLV_LEN }>,
    breadcrumb: u64,
    max_cumulative_secs: u16,
}

impl FailSafe {
    #[inline(always)]
    pub const fn new() -> Self {
        Self {
            state: State::Idle,
            secret_key: PKC_SECRET_KEY_ZEROED,
            root_ca: Vec::new(),
            breadcrumb: 0,
            max_cumulative_secs: DEFAULT_FAILSAFE_MAX_CUMULATIVE_SECS,
        }
    }

    pub fn init() -> impl Init<Self> {
        init!(Self {
            state: State::Idle,
            secret_key <- CanonPkcSecretKey::init(),
            root_ca <- Vec::init(),
            breadcrumb: 0,
            max_cumulative_secs: DEFAULT_FAILSAFE_MAX_CUMULATIVE_SECS
        })
    }

    /// Set `MaxCumulativeFailsafeSeconds`, the longest a fail-safe context
    /// lasts however often it is re-armed. Applies to the contexts created
    /// from now on: an armed one keeps its lifetime.
    pub fn set_max_cumulative_secs(&mut self, secs: u16) {
        self.max_cumulative_secs = secs;
    }

    /// Check if the fail-safe timer has expired and if so disarms and restores the state of the fabric as well as
    /// the basic info settings.
    ///
    /// This should be called periodically to ensure that the fail-safe state is updated in a timely manner.
    /// 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.
    ///
    /// Returns the outcome of the expiry, if the fail-safe did expire (see
    /// [`FailSafe::expire`]).
    pub fn check_failsafe_timeout<S>(
        &mut self,
        fabrics: &mut Fabrics,
        remove_pase_sessions: impl FnOnce(),
        kv: S,
        mdns_notif: impl FnMut(),
        notify_change: impl FnMut(EndptId, ClusterId),
    ) -> Result<Option<Expiry>, Error>
    where
        S: KvBlobStoreAccess,
    {
        if let State::Armed(ctx) = &self.state {
            if Instant::now() >= ctx.expires_at() {
                // Timeout path: no caller exchange to preserve, so wipe
                // every PASE session along with the fabric rollback.
                return self.expire(fabrics, remove_pase_sessions, kv, mdns_notif, notify_change);
            }
        }

        Ok(None)
    }

    /// Force the fail-safe context to expire immediately, rolling back any
    /// fabric changes that the in-flight commissioning had staged and
    /// resetting the breadcrumb to 0.
    ///
    /// `remove_pase_sessions` removes the PASE sessions, which are orphaned by
    /// the rollback. When the trigger arrived over PASE, it should keep the
    /// session of the triggering exchange alive (marked expired), so that the
    /// response can still be sent before the slot is reclaimed.
    ///
    /// Returns `None` if the fail-safe was not armed. Otherwise, the caller
    /// must broadcast `LifecycleOp::FailSafeExpiry` once the Matter state lock
    /// is released, so that the handlers drop what they staged (networks and
    /// the like), and `HandlerContext::notify_fabric_removed` for the
    /// returned removed fabric. That is a fabric added by the in-flight
    /// `AddNOC`, which has no persisted copy yet; a pre-existing fabric
    /// mutated by `UpdateNOC` is resurrected from its persisted copy instead.
    pub fn expire<S>(
        &mut self,
        fabrics: &mut Fabrics,
        remove_pase_sessions: impl FnOnce(),
        kv: S,
        mut mdns_notif: impl FnMut(),
        mut notify_change: impl FnMut(EndptId, ClusterId),
    ) -> Result<Option<Expiry>, Error>
    where
        S: KvBlobStoreAccess,
    {
        let State::Armed(ctx) = &self.state else {
            return Ok(None);
        };

        warn!(
            "Fail-Safe timeout expired for fabric {}, disarming",
            ctx.fab_idx
        );

        let fab_idx_raw = ctx.fab_idx;
        let mut removed_fabric = None;

        kv.access(|mut kv, buf| {
            if let Some(fab_idx) = NonZeroU8::new(fab_idx_raw) {
                fabrics.remove(fab_idx)?;
                fabrics.add_load(fab_idx.get(), &mut kv, buf)?;

                removed_fabric = fabrics.get(fab_idx).is_none().then_some(fab_idx);
            }

            Ok::<_, Error>(())
        })?;

        // Any PASE session that was in flight under this fail-safe is
        // now orphaned: its commissioning attempt was rolled back, so the
        // session has nothing to do and should not stick around to fill
        // the session table (same leak class fixed for
        // `CommissioningComplete`).
        remove_pase_sessions();

        self.state = State::Idle;
        self.breadcrumb = 0;

        mdns_notif();

        // The rollback above restores attributes visible to subscribers —
        // `OperationalCredentials::NOCs` / `Fabrics` (including `vvsc`,
        // `VIDVerificationStatement`, `vendorID` mutated in-failsafe by
        // `SetVIDVerificationStatement`) — to their persisted values. Notify
        // so any active subscriptions re-report.
        //
        // TODO: this only flags subscriptions for re-reporting; it does
        // *not* bump the affected clusters' data versions. `Failsafe`
        // has no handle to the cluster meta needed to do that. Pre-existing
        // limitation, not introduced by the timeout-vs-force-expiry path.
        notify_change(ROOT_ENDPOINT_ID, OPERATIONAL_CREDENTIALS_CLUSTER_ID);

        Ok(Some(Expiry { removed_fabric }))
    }

    pub fn arm(
        &mut self,
        timeout_secs: u16,
        breadcrumb: u64,
        session_mode: &SessionMode,
        comm_window_open: bool,
    ) -> Result<(), Error> {
        if matches!(self.state, State::Idle) {
            if matches!(session_mode, SessionMode::PlainText) {
                // Only PASE and CASE sessions supported
                return Err(ErrorCode::GennCommInvalidAuthentication.into());
            }

            if comm_window_open && matches!(session_mode, SessionMode::Case { .. }) {
                // Cannot arm via CASE while there's an active window
                return Err(ErrorCode::Busy.into());
            }

            // if !comm_window_open && !matches!(session_mode, SessionMode::Case { .. }) {
            //     // Cannot arm via PASE if there is no active commissioning window
            //     return Err(ErrorCode::GennCommInvalidAuthentication.into());
            // }

            if timeout_secs == 0 {
                // Expiring a fail-safe which is not armed succeeds without side effects
                return Ok(());
            }

            self.state = State::Armed(ArmedCtx::new(
                timeout_secs,
                self.max_cumulative_secs,
                session_mode.fab_idx(),
                NocFlags::empty(),
            ));
            self.breadcrumb = breadcrumb;

            return Ok(());
        }

        // Re-arm

        self.check_state(
            session_mode,
            NocFlags::empty(),
            NocFlags::empty(),
            NocFlags::empty(),
        )?;

        let State::Armed(ctx) = &mut self.state else {
            // Impossible, as we checked for Idle above
            unreachable!();
        };

        if timeout_secs > 0 {
            ctx.armed_at = Instant::now();
            ctx.timeout_secs = timeout_secs;
            self.breadcrumb = breadcrumb;
        } else {
            // As per the spec, when timeout seconds is 0, we have to actually disarm
            self.state = State::Idle;
            self.breadcrumb = 0;
        }

        Ok(())
    }

    pub fn disarm<'a>(
        &mut self,
        session_mode: &SessionMode,
        fabrics: &'a mut Fabrics,
    ) -> Result<&'a mut Fabric, Error> {
        self.disarm_with(session_mode, fabrics, |_| Ok(()))
    }

    /// Like [`Self::disarm`], running `commit` on the fabric first. If `commit`
    /// fails, the fail-safe stays armed, for its expiry to revert the fabric.
    pub fn disarm_with<'a, F>(
        &mut self,
        session_mode: &SessionMode,
        fabrics: &'a mut Fabrics,
        commit: F,
    ) -> Result<&'a mut Fabric, Error>
    where
        F: FnOnce(&Fabric) -> Result<(), Error>,
    {
        if matches!(self.state, State::Idle) {
            error!("Received Fail-Safe Disarm without it being armed");
            return Err(ErrorCode::FailSafeRequired.into());
        }

        // Has to be a CASE session
        let fab_idx = Self::get_case_fab_idx(session_mode)?;

        self.check_state(
            session_mode,
            NocFlags::empty(),
            NocFlags::empty(),
            NocFlags::empty(),
        )?;

        let fabric = fabrics.fabric_mut(fab_idx)?;

        commit(fabric)?;

        self.state = State::Idle;
        self.breadcrumb = 0;

        Ok(fabric)
    }

    /// When the armed fail-safe expires, or `None` if it is not armed.
    pub fn expires_at(&self) -> Option<Instant> {
        match &self.state {
            State::Armed(ctx) => Some(ctx.expires_at()),
            _ => None,
        }
    }

    pub fn is_armed(&self) -> bool {
        matches!(self.state, State::Armed(_))
    }

    /// Return the trusted root certificate that has been staged via
    /// `AddTrustedRootCertificate` while the fail-safe is armed but has not
    /// yet been bound to a fabric via `AddNOC` / `UpdateNOC`.
    ///
    /// Once `AddNOC` or `UpdateNOC` is processed the root certificate is
    /// owned by the (new or updated) fabric and is reported through the
    /// fabric table; until then it has no fabric association but the spec
    /// still requires it to appear in the `TrustedRootCertificates` list
    /// (Matter Core spec, NodeOperationalCredentials cluster).
    pub fn pending_root_ca(&self) -> Option<&[u8]> {
        let State::Armed(ctx) = &self.state else {
            return None;
        };

        if !ctx.flags.contains(NocFlags::ADD_ROOT_CERT_RECVD) {
            return None;
        }

        if ctx
            .flags
            .intersects(NocFlags::ADD_NOC_RECVD | NocFlags::UPDATE_NOC_RECVD)
        {
            return None;
        }

        (!self.root_ca.is_empty()).then_some(self.root_ca.as_slice())
    }

    /// Drop the trusted root certificate staged via `AddTrustedRootCertificate`,
    /// if no `AddNOC` / `UpdateNOC` has bound it to a fabric yet.
    ///
    /// For fabric removal: the root is then not referenced by any operational
    /// certificate, so it must go. The fail-safe stays armed, and another
    /// `AddTrustedRootCertificate` in it is still refused.
    pub fn drop_pending_root_ca(&mut self) {
        if self.pending_root_ca().is_some() {
            self.root_ca.clear();
        }
    }

    pub fn is_armed_for(&self, caller_fab_idx: u8) -> bool {
        match self.state {
            State::Idle => false,
            State::Armed(ArmedCtx { fab_idx, .. }) => fab_idx == caller_fab_idx,
        }
    }

    /// Whether the current fail-safe context already has an in-flight
    /// `AddNOC` or `UpdateNOC` for `caller_fab_idx`. Used by
    /// `SetVIDVerificationStatement` to decide whether the VID-verification
    /// mutation rides along with the pending fabric (and thus rolls back
    /// on fail-safe expiry) or is committed to storage immediately.
    pub fn has_pending_noc_for(&self, caller_fab_idx: NonZeroU8) -> bool {
        let State::Armed(ctx) = &self.state else {
            return false;
        };
        ctx.fab_idx == caller_fab_idx.get()
            && ctx
                .flags
                .intersects(NocFlags::ADD_NOC_RECVD | NocFlags::UPDATE_NOC_RECVD)
    }

    pub fn check_armed(&self, session_mode: &SessionMode) -> Result<(), Error> {
        self.check_state(
            session_mode,
            NocFlags::empty(),
            NocFlags::empty(),
            NocFlags::empty(),
        )
    }

    pub fn add_trusted_root_cert<C: Crypto>(
        &mut self,
        crypto: C,
        time: UtcTime,
        session_mode: &SessionMode,
        root_ca: &[u8],
        buf: &mut [u8],
    ) -> Result<(), Error> {
        self.check_state(
            session_mode,
            NocFlags::empty(),
            NocFlags::ADD_ROOT_CERT_RECVD,
            NocFlags::ADD_ROOT_CERT_RECVD,
        )?;

        // Validate the candidate RCAC by checking its self-signature (a Matter
        // RCAC is self-issued, so the certificate's own public key must verify
        // the certificate's signature). Any decode or signature failure must
        // surface as `INVALID_COMMAND` per Matter Core spec
        // (`AddTrustedRootCertificate`), not as the generic `Failure` we'd
        // otherwise get from `ErrorCode::InvalidSignature`.
        {
            let root_ref = CertRef::new(TLVElement::new(root_ca));
            root_ref
                .verify_chain_start(&crypto, time)
                .finalise(buf)
                .map_err(|_| ErrorCode::InvalidCommand)?;

            // Matter spec extra: an RCAC SHALL NOT carry a
            // `pathLenConstraint` greater than `1` — the deepest valid
            // Matter chain is RCAC → ICAC → NOC, i.e. at most one
            // intermediate CA below the root. Mirrors CHIP's
            // `ValidateChipRCAC`.
            if let Some(path_len) = root_ref
                .basic_constraints_path_len()
                .map_err(|_| ErrorCode::InvalidCommand)?
            {
                if path_len > 1 {
                    Err(ErrorCode::InvalidCommand)?;
                }
            }
        }

        self.root_ca.clear();
        self.root_ca
            .extend_from_slice(root_ca)
            .map_err(|_| ErrorCode::InvalidCommand)?;

        self.add_flags(NocFlags::ADD_ROOT_CERT_RECVD);

        Ok(())
    }

    pub fn add_csr_req<C: Crypto>(
        &mut self,
        crypto: C,
        session_mode: &SessionMode,
    ) -> Result<CanonPkcSecretKeyRef<'_>, Error> {
        self.check_state(
            session_mode,
            NocFlags::empty(),
            NocFlags::ADD_CSR_REQ_RECVD | NocFlags::UPDATE_CSR_REQ_RECVD,
            NocFlags::ADD_CSR_REQ_RECVD,
        )?;

        let crypto_secret_key = crypto.generate_secret_key()?;
        crypto_secret_key.write_canon(&mut self.secret_key)?;

        self.add_flags(NocFlags::ADD_CSR_REQ_RECVD);

        Ok(self.secret_key.reference())
    }

    pub fn update_csr_req<C: Crypto>(
        &mut self,
        crypto: C,
        session_mode: &SessionMode,
    ) -> Result<CanonPkcSecretKeyRef<'_>, Error> {
        // Must be a CASE session
        Self::get_case_fab_idx(session_mode)?;

        self.check_state(
            session_mode,
            NocFlags::empty(),
            NocFlags::ADD_CSR_REQ_RECVD | NocFlags::UPDATE_CSR_REQ_RECVD,
            NocFlags::UPDATE_CSR_REQ_RECVD,
        )?;

        crypto
            .generate_secret_key()?
            .write_canon(&mut self.secret_key)?;

        self.add_flags(NocFlags::UPDATE_CSR_REQ_RECVD);

        Ok(self.secret_key.reference())
    }

    #[allow(clippy::too_many_arguments)]
    pub fn update_noc<'a, C: Crypto>(
        &mut self,
        crypto: C,
        time: UtcTime,
        fabrics: &'a mut Fabrics,
        session_mode: &SessionMode,
        icac: Option<&[u8]>,
        noc: &[u8],
        buf: &mut [u8],
        mut mdns_notif: impl FnMut(),
    ) -> Result<&'a mut Fabric, Error> {
        let fab_idx = Self::get_case_fab_idx(session_mode)?;

        // `UpdateNOC` only requires the corresponding `CSRRequest` (with
        // `isForUpdateNOC=true`) to have been processed in this fail-safe
        // context. Per Matter Core spec it must NOT
        // have been preceded by `AddTrustedRootCertificate`, `AddNOC`,
        // `UpdateNOC`, or a CSRRequest of the wrong kind — those go in
        // `absent`. `validate_certs` further down uses the *committed*
        // root cert (`fabrics.fabric(fab_idx).root_ca()`), not anything
        // staged via AddTrustedRootCertificate.
        self.check_state(
            session_mode,
            NocFlags::UPDATE_CSR_REQ_RECVD,
            NocFlags::ADD_ROOT_CERT_RECVD
                | NocFlags::ADD_NOC_RECVD
                | NocFlags::ADD_CSR_REQ_RECVD
                | NocFlags::UPDATE_NOC_RECVD,
            NocFlags::UPDATE_NOC_RECVD,
        )?;

        {
            let noc_ref = CertRef::new(TLVElement::new(noc));
            let icac_ref = icac.map(|icac| CertRef::new(TLVElement::new(icac)));
            // `UpdateNOC` re-uses the existing fabric's root cert; it does
            // not consume one staged via `AddTrustedRootCertificate` (the
            // `absent` constraint above ensures none was staged).
            let fabric_root_ca = fabrics.fabric(fab_idx)?.root_ca();
            let root_ref = CertRef::new(TLVElement::new(fabric_root_ca));

            // Validate the certs first. A chain that doesn't pass
            // signature verification (or that doesn't chain back to the
            // staged root) is reported as `kInvalidNOC` cluster status per
            // Matter Core spec (`UpdateNOC`).
            Self::validate_certs(&crypto, time, &noc_ref, icac_ref.as_ref(), &root_ref, buf)
                .map_err(|_| ErrorCode::NocInvalidNoc)?;

            // The NOC's public key must match the public key derived from
            // the most recent `CSRRequest(isForUpdateNOC=true)` (Matter
            // Core spec).
            let mut csr_pubkey = crate::crypto::CanonPkcPublicKey::new();
            crypto
                .secret_key(self.secret_key.reference())?
                .pub_key()?
                .write_canon(&mut csr_pubkey)?;
            if csr_pubkey.access().as_slice() != noc_ref.pubkey()? {
                Err(ErrorCode::NocInvalidPublicKey)?;
            }

            // Check that the fabric ID in the NOC matches the fabric
            // being updated. The root cert pubkey check is implicit: the
            // chain validation above used the fabric's own root cert.

            let fabric_id = noc_ref.get_fabric_id()?;
            let fabric = fabrics.fabric(fab_idx)?;

            if fabric_id != fabric.fabric_id() {
                Err(ErrorCode::NocFabricConflict)?;
            }
        }

        // `Fabrics::update` keeps the existing root cert in place — no
        // need (and no reason) to copy it out of the fabric just to pass
        // it back in.
        let fabric = fabrics.update(
            &crypto,
            fab_idx,
            self.secret_key.reference(),
            noc,
            icac.unwrap_or(&[]),
        )?;

        let State::Armed(ctx) = &mut self.state else {
            // Impossible to be in any other state because otherwise
            // check_state would have failed
            unreachable!();
        };

        ctx.fab_idx = fabric.fab_idx().get();
        self.add_flags(NocFlags::UPDATE_NOC_RECVD);

        mdns_notif();

        Ok(fabric)
    }

    #[allow(clippy::too_many_arguments)]
    pub fn add_noc<'a, C: Crypto>(
        &mut self,
        crypto: C,
        time: UtcTime,
        fabrics: &'a mut Fabrics,
        session_mode: &SessionMode,
        vendor_id: u16,
        icac: Option<&[u8]>,
        noc: &[u8],
        ipk: &[u8],
        case_admin_subject: u64,
        buf: &mut [u8],
        mut mdns_notif: impl FnMut(),
    ) -> Result<&'a mut Fabric, Error> {
        self.check_state(
            session_mode,
            NocFlags::ADD_ROOT_CERT_RECVD | NocFlags::ADD_CSR_REQ_RECVD,
            NocFlags::ADD_NOC_RECVD | NocFlags::UPDATE_CSR_REQ_RECVD | NocFlags::UPDATE_NOC_RECVD,
            NocFlags::ADD_NOC_RECVD,
        )?;

        // CaseAdminSubject must be either a valid Operational Node ID or a
        // CASE Authenticated Tag (CAT) — Matter Core spec
        // (`AddNOC`). Anything else (most commonly 0) is reported as
        // `kInvalidAdminSubject` cluster status.
        if !crate::acl::is_node(case_admin_subject) && !crate::acl::is_noc_cat(case_admin_subject) {
            Err(ErrorCode::NocInvalidAdminSubject)?;
        }

        // `self.secret_key` was stashed by `add_csr_req`
        Self::check_new_noc(
            &crypto,
            time,
            fabrics,
            &self.root_ca,
            icac,
            noc,
            self.secret_key.reference(),
            buf,
        )?;

        let fabric = fabrics
            .add(
                &crypto,
                self.secret_key.reference(),
                &self.root_ca,
                noc,
                icac.unwrap_or(&[]),
                Some(CanonAeadKeyRef::try_new(ipk)?),
                vendor_id,
                case_admin_subject,
            )
            .map_err(|e| {
                if e.code() == ErrorCode::ResourceExhausted {
                    ErrorCode::NocFabricTableFull.into()
                } else {
                    e
                }
            })?;

        info!(
            "Added operational fabric with local index {}",
            fabric.fab_idx()
        );

        let State::Armed(ctx) = &mut self.state else {
            // Impossible to be in any other state because otherwise
            // check_state would have failed
            unreachable!();
        };

        ctx.fab_idx = fabric.fab_idx().get();
        self.add_flags(NocFlags::ADD_NOC_RECVD);

        mdns_notif();

        Ok(fabric)
    }

    pub fn breadcrumb(&self) -> u64 {
        self.breadcrumb
    }

    pub fn set_breadcrumb(&mut self, value: u64) {
        self.breadcrumb = value;
    }

    /// The fabric added by `AddNOC` in the current fail-safe context and the
    /// seconds left until expiry; `None` if there is no such fabric.
    pub fn pending_add_noc(&self) -> Option<(NonZeroU8, u16)> {
        let State::Armed(ctx) = &self.state else {
            return None;
        };

        if !ctx.flags.contains(NocFlags::ADD_NOC_RECVD) {
            return None;
        }

        let fab_idx = NonZeroU8::new(ctx.fab_idx)?;

        let secs_left = ctx
            .expires_at()
            .checked_duration_since(Instant::now())
            .map_or(0, |left| left.as_secs().min(u16::MAX as u64) as u16);

        Some((fab_idx, secs_left))
    }

    /// Arm the fail-safe for a fabric resumed from a commissioning handover,
    /// as if `AddNOC` had just been processed for it. `Busy` if already armed.
    pub fn arm_resumed(
        &mut self,
        fab_idx: NonZeroU8,
        timeout_secs: u16,
        breadcrumb: u64,
    ) -> Result<(), Error> {
        if !matches!(self.state, State::Idle) {
            return Err(ErrorCode::Busy.into());
        }

        self.state = State::Armed(ArmedCtx::new(
            timeout_secs,
            self.max_cumulative_secs,
            fab_idx.get(),
            NocFlags::ADD_ROOT_CERT_RECVD | NocFlags::ADD_CSR_REQ_RECVD | NocFlags::ADD_NOC_RECVD,
        ));
        self.breadcrumb = breadcrumb;

        Ok(())
    }

    /// Check that a NOC is acceptable for a new fabric: the chain verifies
    /// against `root_ca`, the NOC public key matches `secret_key`, and no
    /// existing fabric has the same fabric ID under the same root.
    #[allow(clippy::too_many_arguments)]
    pub fn check_new_noc<C: Crypto>(
        crypto: &C,
        time: UtcTime,
        fabrics: &Fabrics,
        root_ca: &[u8],
        icac: Option<&[u8]>,
        noc: &[u8],
        secret_key: CanonPkcSecretKeyRef<'_>,
        buf: &mut [u8],
    ) -> Result<(), Error> {
        let noc_ref = CertRef::new(TLVElement::new(noc));
        let icac_ref = icac.map(|icac| CertRef::new(TLVElement::new(icac)));
        let root_ref = CertRef::new(TLVElement::new(root_ca));

        // Validate the certs first. A chain that doesn't pass
        // signature verification (or that doesn't chain back to the
        // staged root) is reported as `kInvalidNOC` cluster status per
        // Matter Core spec (`AddNOC`).
        Self::validate_certs(crypto, time, &noc_ref, icac_ref.as_ref(), &root_ref, buf)
            .map_err(|_| ErrorCode::NocInvalidNoc)?;

        // The NOC's public key must match the public key derived from
        // the most recent `CSRRequest` (Matter Core spec).
        let mut csr_pubkey = crate::crypto::CanonPkcPublicKey::new();
        crypto
            .secret_key(secret_key)?
            .pub_key()?
            .write_canon(&mut csr_pubkey)?;
        if csr_pubkey.access().as_slice() != noc_ref.pubkey()? {
            Err(ErrorCode::NocInvalidPublicKey)?;
        }

        // Check that there is no fabric with the same fabric ID and root cert pubkey
        // as the one in the NOC, to avoid adding duplicate fabrics

        let fabric_id = noc_ref.get_fabric_id()?;
        let root_cert_pubkey = root_ref.pubkey()?;

        for fabric in fabrics.iter() {
            if fabric_id == fabric.fabric_id() {
                let f_root_ref = CertRef::new(TLVElement::new(fabric.root_ca()));
                let f_root_pubkey = f_root_ref.pubkey()?;

                if root_cert_pubkey == f_root_pubkey {
                    // A fabric with the same ID and root cert pubkey already exists,
                    // which means that this NOC cannot be accepted
                    Err(ErrorCode::NocFabricConflict)?;
                }
            }
        }

        Ok(())
    }

    #[allow(clippy::too_many_arguments)]
    fn validate_certs<C: Crypto>(
        crypto: C,
        time: UtcTime,
        noc: &CertRef,
        icac: Option<&CertRef>,
        root: &CertRef,
        buf: &mut [u8],
    ) -> Result<(), Error> {
        let mut verifier = noc.verify_chain_start(crypto, time);

        if let Some(icac) = icac {
            // If ICAC is present handle it. Reject the case where the
            // commissioner re-uses the RCAC as the ICAC:
            // the spec requires the ICAC to be a separate CA cert
            // (i.e. not self-signed).
            if icac.is_self_signed()? {
                return Err(ErrorCode::InvalidData.into());
            }
            verifier = verifier.add_cert(icac, buf)?;
        }

        verifier.add_cert(root, buf)?.finalise(buf)
    }

    fn get_case_fab_idx(session_mode: &SessionMode) -> Result<NonZeroU8, Error> {
        if let SessionMode::Case { fab_idx, .. } = session_mode {
            Ok(*fab_idx)
        } else {
            // Only CASE session supported
            Err(ErrorCode::GennCommInvalidAuthentication.into())
        }
    }

    fn check_state(
        &self,
        session_mode: &SessionMode,
        present: NocFlags,
        absent: NocFlags,
        op: NocFlags,
    ) -> Result<(), Error> {
        if let State::Armed(ctx) = &self.state {
            if matches!(session_mode, SessionMode::PlainText) {
                // Session is plain text
                Err(ErrorCode::GennCommInvalidAuthentication)?;
            }

            if op == NocFlags::UPDATE_NOC_RECVD && !matches!(session_mode, SessionMode::Case { .. })
            {
                // Update NOC requires a CASE session
                Err(ErrorCode::GennCommInvalidAuthentication)?;
            }

            if ctx.fab_idx != session_mode.fab_idx() {
                // Fabric index does not match
                Err(ErrorCode::NocInvalidFabricIndex)?;
            }

            if !ctx.flags.contains(present) {
                // State is not what is expected for that concrete command.
                //
                // Disambiguate "no CSR at all" from "wrong CSR type" per
                // Matter Core spec, `AddNOC` / `UpdateNOC`:
                //   * No `CSRRequest` of either kind seen yet for this
                //     fail-safe context → `kMissingCsr` cluster status.
                //   * A CSR was issued but with the opposite
                //     `isForUpdateNOC` flag from the command being
                //     processed (e.g. `UpdateNOC` after a CSR for
                //     `AddNOC`) → IM `CONSTRAINT_ERROR`.
                let any_csr = ctx
                    .flags
                    .intersects(NocFlags::ADD_CSR_REQ_RECVD | NocFlags::UPDATE_CSR_REQ_RECVD);
                if (op == NocFlags::ADD_NOC_RECVD || op == NocFlags::UPDATE_NOC_RECVD) && !any_csr {
                    Err(ErrorCode::NocMissingCsr)?;
                }

                Err(ErrorCode::ConstraintError)?;
            }

            if !ctx.flags.intersection(absent).is_empty() {
                // State is not what is expected for that concrete command.
                //
                // Two flavours both surface as IM `CONSTRAINT_ERROR` per
                // Matter Core spec, `AddNOC` / `UpdateNOC`:
                //   * the same `Add`/`UpdateNOC` was already received in
                //     this fail-safe context
                //   * the most recent `CSRRequest` had the wrong
                //     `isForUpdateNOC` flag for the command being
                //     processed (e.g. UpdateNOC after an AddNOC-style CSR)
                Err(ErrorCode::ConstraintError)?;
            }
        } else {
            // Fail-safe is not armed
            Err(ErrorCode::FailSafeRequired)?;
        }

        Ok(())
    }

    fn add_flags(&mut self, flags: NocFlags) {
        match &mut self.state {
            State::Armed(ctx) => ctx.flags |= flags,
            _ => panic!("Not armed"),
        }
    }
}

impl Default for FailSafe {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
    use core::num::NonZeroU8;

    use crate::cert::gen::VALID_FOREVER;
    use crate::crypto::{test_only_crypto, CanonPkcSecretKey, Crypto, PKC_CANON_SECRET_KEY_LEN};
    use crate::dm::ROOT_ENDPOINT_ID;
    use crate::dm::{ClusterId, EndptId};
    use crate::error::{Error, ErrorCode};
    use crate::fabric::tests::{
        add_fabric, mint_icac, mint_noc, mint_noc_for_pubkey, mint_rcac, pubkey_of, TestRcac,
        TEST_IPK,
    };
    use crate::fabric::{FabricPersist, Fabrics, MAX_FABRICS};
    use crate::persist::{MemKv, MemKvBlobStore};
    use crate::session::SessionMode;
    use crate::utils::epoch::UtcTime;

    use super::{Expiry, FailSafe, DEFAULT_FAILSAFE_EXPIRY_SECS};

    fn pase(fab_idx: u8) -> SessionMode {
        SessionMode::Pase { fab_idx }
    }

    fn case(fab_idx: u8) -> SessionMode {
        SessionMode::Case {
            fab_idx: NonZeroU8::new(fab_idx).unwrap(),
            cat_ids: Default::default(),
        }
    }

    fn idx(i: u8) -> NonZeroU8 {
        NonZeroU8::new(i).unwrap()
    }

    /// A UTC time inside the validity window of every minted certificate.
    fn now() -> UtcTime {
        UtcTime::Reliable(VALID_FOREVER.not_before as u64 * 1_000_000)
    }

    fn code<T>(r: Result<T, Error>) -> ErrorCode {
        r.err().expect("expected an error").code()
    }

    /// Arm a fresh fail-safe over `session_mode` with the default expiry.
    fn armed(session_mode: &SessionMode) -> FailSafe {
        let mut fs = FailSafe::new();
        fs.arm(DEFAULT_FAILSAFE_EXPIRY_SECS, 0, session_mode, false)
            .unwrap();
        fs
    }

    /// Stage `rcac` via `AddTrustedRootCertificate`, then issue an `AddNOC`-style
    /// CSR and return the generated secret key.
    fn stage_root_and_csr<C: Crypto>(
        crypto: &C,
        fs: &mut FailSafe,
        session_mode: &SessionMode,
        rcac: &TestRcac,
    ) -> CanonPkcSecretKey {
        let mut buf = [0u8; 1024];
        fs.add_trusted_root_cert(crypto, now(), session_mode, &rcac.cert, &mut buf)
            .unwrap();

        CanonPkcSecretKey::new_from_ref(fs.add_csr_req(crypto, session_mode).unwrap())
    }

    /// Drive the full `AddNOC` flow over PASE for a new fabric with
    /// `fabric_id` / `node_id`, returning the staged RCAC and the local index
    /// of the pending fabric.
    fn add_noc_flow<C: Crypto>(
        crypto: &C,
        fs: &mut FailSafe,
        fabrics: &mut Fabrics,
        fabric_id: u64,
        node_id: u64,
    ) -> (TestRcac, NonZeroU8) {
        let rcac = mint_rcac(crypto, fabric_id, 0x77);
        let key = stage_root_and_csr(crypto, fs, &pase(0), &rcac);
        let noc = mint_noc_for_pubkey(
            crypto,
            &rcac,
            true,
            pubkey_of(crypto, key.reference()).reference(),
            node_id,
        );

        let mut buf = [0u8; 1024];
        let fab_idx = fs
            .add_noc(
                crypto,
                now(),
                fabrics,
                &pase(0),
                0xfff1,
                None,
                &noc,
                &TEST_IPK,
                node_id,
                &mut buf,
                || {},
            )
            .unwrap()
            .fab_idx();

        (rcac, fab_idx)
    }

    /// The deadlines the timeout checks sleep until: the fail-safe's while armed,
    /// the commissioning window's while open.
    #[test]
    fn expiry_deadlines() {
        use crate::utils::timers::{Duration, Instant};

        let mut fs = FailSafe::new();
        assert_eq!(fs.expires_at(), None);

        let before = Instant::now();
        fs = armed(&pase(0));
        let expires_at = fs.expires_at().unwrap();
        assert!(expires_at >= before + Duration::from_secs(DEFAULT_FAILSAFE_EXPIRY_SECS as u64));
        assert!(
            expires_at <= Instant::now() + Duration::from_secs(DEFAULT_FAILSAFE_EXPIRY_SECS as u64)
        );
    }

    /// A context ends at most `MaxCumulativeFailsafeSeconds` after it was
    /// created: re-arming does not move that end, and a new limit only applies
    /// to the contexts created after it.
    #[test]
    fn rearming_does_not_extend_the_cumulative_lifetime() {
        use crate::utils::timers::{Duration, Instant};

        let mut fs = FailSafe::new();
        fs.set_max_cumulative_secs(10);

        let before = Instant::now();
        fs.arm(60, 0, &pase(0), false).unwrap();
        let after = Instant::now();

        let cumulative_end = fs.expires_at().unwrap();
        assert!(cumulative_end >= before + Duration::from_secs(10));
        assert!(cumulative_end <= after + Duration::from_secs(10));

        fs.arm(60, 0, &pase(0), false).unwrap();
        assert_eq!(fs.expires_at(), Some(cumulative_end));

        fs.set_max_cumulative_secs(1000);
        fs.arm(60, 0, &pase(0), false).unwrap();
        assert_eq!(fs.expires_at(), Some(cumulative_end));

        // A shorter armed timeout still ends the context first
        fs.arm(1, 0, &pase(0), false).unwrap();
        assert!(fs.expires_at().unwrap() < cumulative_end);
    }

    #[test]
    fn new_and_init_are_idle() {
        use crate::utils::init::InitMaybeUninit;

        let mut init = core::mem::MaybeUninit::<FailSafe>::uninit();
        let init = init.init_with(FailSafe::init());

        for fs in [&FailSafe::new(), &FailSafe::default(), &*init] {
            assert!(!fs.is_armed());
            assert!(!fs.is_armed_for(0));
            assert!(!fs.has_pending_noc_for(idx(1)));
            assert_eq!(fs.breadcrumb(), 0);
            assert!(fs.pending_root_ca().is_none());
            assert!(fs.pending_add_noc().is_none());
            assert_eq!(code(fs.check_armed(&pase(0))), ErrorCode::FailSafeRequired);
            assert_eq!(code(fs.check_armed(&case(1))), ErrorCode::FailSafeRequired);
        }
    }

    #[test]
    fn arm_over_pase_from_idle() {
        let mut fs = FailSafe::new();
        fs.arm(60, 7, &pase(0), false).unwrap();

        assert!(fs.is_armed());
        assert!(fs.is_armed_for(0));
        assert!(!fs.is_armed_for(1));
        assert!(!fs.has_pending_noc_for(idx(1)));
        assert_eq!(fs.breadcrumb(), 7);
        assert!(fs.pending_root_ca().is_none());
        assert!(fs.pending_add_noc().is_none());

        fs.check_armed(&pase(0)).unwrap();
        assert_eq!(
            code(fs.check_armed(&case(1))),
            ErrorCode::NocInvalidFabricIndex
        );
        assert_eq!(
            code(fs.check_armed(&pase(1))),
            ErrorCode::NocInvalidFabricIndex
        );
        assert_eq!(
            code(fs.check_armed(&SessionMode::PlainText)),
            ErrorCode::GennCommInvalidAuthentication
        );
    }

    #[test]
    fn arm_over_case_from_idle() {
        let mut fs = FailSafe::new();
        fs.arm(60, 1, &case(2), false).unwrap();

        assert!(fs.is_armed());
        assert!(fs.is_armed_for(2));
        assert!(!fs.is_armed_for(0));
        assert_eq!(fs.breadcrumb(), 1);

        fs.check_armed(&case(2)).unwrap();
        assert_eq!(
            code(fs.check_armed(&case(1))),
            ErrorCode::NocInvalidFabricIndex
        );
        assert_eq!(
            code(fs.check_armed(&pase(0))),
            ErrorCode::NocInvalidFabricIndex
        );
    }

    #[test]
    fn arm_rejects_plaintext_sessions() {
        let mut fs = FailSafe::new();

        assert_eq!(
            code(fs.arm(60, 1, &SessionMode::PlainText, false)),
            ErrorCode::GennCommInvalidAuthentication
        );
        assert!(!fs.is_armed());
        assert_eq!(fs.breadcrumb(), 0);
    }

    #[test]
    fn arm_over_case_with_open_commissioning_window_is_busy() {
        let mut fs = FailSafe::new();
        assert_eq!(code(fs.arm(60, 1, &case(1), true)), ErrorCode::Busy);
        assert!(!fs.is_armed());

        // PASE arming is fine while the window is open
        fs.arm(60, 1, &pase(0), true).unwrap();
        assert!(fs.is_armed_for(0));
    }

    #[test]
    fn rearm_from_same_session_extends_and_updates_breadcrumb() {
        let mut fs = FailSafe::new();
        fs.arm(60, 1, &pase(0), false).unwrap();
        fs.arm(120, 2, &pase(0), false).unwrap();

        assert!(fs.is_armed_for(0));
        assert_eq!(fs.breadcrumb(), 2);

        // A commissioning window opened meanwhile does not affect re-arming
        let mut fs = FailSafe::new();
        fs.arm(60, 1, &case(1), false).unwrap();
        fs.arm(60, 3, &case(1), true).unwrap();
        assert!(fs.is_armed_for(1));
        assert_eq!(fs.breadcrumb(), 3);
    }

    #[test]
    fn rearm_from_other_session_is_rejected() {
        let mut fs = FailSafe::new();
        fs.arm(60, 1, &pase(0), false).unwrap();

        assert_eq!(
            code(fs.arm(60, 2, &case(1), false)),
            ErrorCode::NocInvalidFabricIndex
        );
        assert_eq!(
            code(fs.arm(60, 2, &SessionMode::PlainText, false)),
            ErrorCode::GennCommInvalidAuthentication
        );

        assert!(fs.is_armed_for(0));
        assert_eq!(fs.breadcrumb(), 1);

        let mut fs = FailSafe::new();
        fs.arm(60, 1, &case(1), false).unwrap();
        assert_eq!(
            code(fs.arm(60, 2, &case(2), false)),
            ErrorCode::NocInvalidFabricIndex
        );
        assert!(fs.is_armed_for(1));
    }

    #[test]
    fn rearm_with_zero_timeout_disarms() {
        let mut fs = FailSafe::new();
        fs.arm(60, 5, &case(1), false).unwrap();

        fs.arm(0, 9, &case(1), false).unwrap();

        assert!(!fs.is_armed());
        assert_eq!(fs.breadcrumb(), 0);
    }

    #[test]
    fn arm_from_idle_with_zero_timeout_is_a_noop() {
        let mut fs = FailSafe::new();
        fs.set_breadcrumb(3);
        fs.arm(0, 5, &pase(0), false).unwrap();
        assert!(!fs.is_armed());
        assert_eq!(fs.breadcrumb(), 3);

        // The session checks still apply
        assert_eq!(
            fs.arm(0, 5, &SessionMode::PlainText, false)
                .unwrap_err()
                .code(),
            ErrorCode::GennCommInvalidAuthentication
        );
    }

    /// The `(endpoint, cluster)` notifications an expiry emits.
    fn expected_expiry_changes() -> std::vec::Vec<(EndptId, ClusterId)> {
        std::vec![(ROOT_ENDPOINT_ID, super::OPERATIONAL_CREDENTIALS_CLUSTER_ID,)]
    }

    #[test]
    fn check_failsafe_timeout_before_expiry_is_a_noop() {
        let mut fs = armed(&pase(0));
        let mut fabrics = Fabrics::new();
        let kv = MemKv::new(MemKvBlobStore::default());
        let mut mdns = 0;

        let removed = fs
            .check_failsafe_timeout(
                &mut fabrics,
                || panic!("no removal expected"),
                &kv,
                || mdns += 1,
                |_, _| panic!("no change expected"),
            )
            .unwrap();

        assert_eq!(removed, None);
        assert!(fs.is_armed_for(0));
        assert_eq!(mdns, 0);

        // Nor does it do anything when idle
        let mut fs = FailSafe::new();
        let removed = fs
            .check_failsafe_timeout(
                &mut fabrics,
                || panic!("no removal expected"),
                &kv,
                || mdns += 1,
                |_, _| panic!("no change expected"),
            )
            .unwrap();
        assert_eq!(removed, None);
        assert_eq!(mdns, 0);
    }

    #[test]
    fn disarm_requires_case_session_matching_the_armed_fabric() {
        let crypto = test_only_crypto();
        let mut fabrics = Fabrics::new();
        add_fabric(&crypto, &mut fabrics, 0xa, 0x1a);

        // Not armed
        let mut fs = FailSafe::new();
        assert_eq!(
            code(fs.disarm(&case(1), &mut fabrics)),
            ErrorCode::FailSafeRequired
        );

        // Armed over PASE: PASE cannot disarm, nor can a CASE session of
        // another fabric
        let mut fs = armed(&pase(0));
        assert_eq!(
            code(fs.disarm(&pase(0), &mut fabrics)),
            ErrorCode::GennCommInvalidAuthentication
        );
        assert_eq!(
            code(fs.disarm(&case(1), &mut fabrics)),
            ErrorCode::NocInvalidFabricIndex
        );
        assert!(fs.is_armed_for(0));

        // Armed over CASE for a fabric that is not in the table
        let mut fs = armed(&case(2));
        assert_eq!(code(fs.disarm(&case(2), &mut fabrics)), ErrorCode::NotFound);
        assert!(fs.is_armed_for(2));

        // Armed over CASE for an existing fabric
        let mut fs = FailSafe::new();
        fs.arm(60, 4, &case(1), false).unwrap();
        let fabric = fs.disarm(&case(1), &mut fabrics).unwrap();
        assert_eq!(fabric.fab_idx(), idx(1));
        assert!(!fs.is_armed());
        assert_eq!(fs.breadcrumb(), 0);
    }

    #[test]
    fn breadcrumb_is_settable_and_reset_on_arm_and_disarm() {
        let crypto = test_only_crypto();
        let mut fabrics = Fabrics::new();
        add_fabric(&crypto, &mut fabrics, 0xa, 0x1a);

        let mut fs = FailSafe::new();
        fs.set_breadcrumb(42);
        assert_eq!(fs.breadcrumb(), 42);

        fs.arm(60, 7, &case(1), false).unwrap();
        assert_eq!(fs.breadcrumb(), 7);

        fs.set_breadcrumb(99);
        assert_eq!(fs.breadcrumb(), 99);

        fs.disarm(&case(1), &mut fabrics).unwrap();
        assert_eq!(fs.breadcrumb(), 0);
    }

    #[test]
    fn add_trusted_root_cert_stages_a_pending_root_ca() {
        let crypto = test_only_crypto();
        let rcac = mint_rcac(&crypto, 0xfab, 0x77);
        let mut buf = [0u8; 1024];

        // Not armed
        let mut fs = FailSafe::new();
        assert_eq!(
            code(fs.add_trusted_root_cert(&crypto, now(), &pase(0), &rcac.cert, &mut buf)),
            ErrorCode::FailSafeRequired
        );

        let mut fs = armed(&pase(0));

        // Wrong session
        assert_eq!(
            code(fs.add_trusted_root_cert(&crypto, now(), &case(1), &rcac.cert, &mut buf)),
            ErrorCode::NocInvalidFabricIndex
        );

        // Garbage and non-self-signed certs are INVALID_COMMAND
        assert_eq!(
            code(fs.add_trusted_root_cert(&crypto, now(), &pase(0), &[1, 2, 3], &mut buf)),
            ErrorCode::InvalidCommand
        );
        let icac = mint_icac(&crypto, &rcac);
        assert_eq!(
            code(fs.add_trusted_root_cert(&crypto, now(), &pase(0), &icac.cert, &mut buf)),
            ErrorCode::InvalidCommand
        );
        assert!(fs.pending_root_ca().is_none());

        fs.add_trusted_root_cert(&crypto, now(), &pase(0), &rcac.cert, &mut buf)
            .unwrap();
        assert_eq!(fs.pending_root_ca(), Some(rcac.cert.as_slice()));

        // Only once per fail-safe context
        assert_eq!(
            code(fs.add_trusted_root_cert(&crypto, now(), &pase(0), &rcac.cert, &mut buf)),
            ErrorCode::ConstraintError
        );
        assert_eq!(fs.pending_root_ca(), Some(rcac.cert.as_slice()));
    }

    #[test]
    fn drop_pending_root_ca_keeps_a_root_bound_by_add_noc() {
        let crypto = test_only_crypto();
        let rcac = mint_rcac(&crypto, 0xfab, 0x77);
        let mut buf = [0u8; 1024];

        // An unbound root is dropped, the fail-safe stays armed, and a second
        // root is still refused
        let mut fs = armed(&pase(0));
        fs.add_trusted_root_cert(&crypto, now(), &pase(0), &rcac.cert, &mut buf)
            .unwrap();
        fs.drop_pending_root_ca();
        assert!(fs.pending_root_ca().is_none());
        assert!(fs.is_armed());
        assert_eq!(
            code(fs.add_trusted_root_cert(&crypto, now(), &pase(0), &rcac.cert, &mut buf)),
            ErrorCode::ConstraintError
        );

        // A root that `AddNOC` bound to the pending fabric stays
        let mut fabrics = Fabrics::new();
        let mut fs = armed(&pase(0));
        let (rcac, _) = add_noc_flow(&crypto, &mut fs, &mut fabrics, 0xfab, 0x1234);
        fs.drop_pending_root_ca();
        assert_eq!(fs.root_ca.as_slice(), rcac.cert.as_slice());
    }

    #[test]
    fn add_csr_req_is_once_per_context_and_pase_cannot_update() {
        let crypto = test_only_crypto();

        let mut fs = FailSafe::new();
        assert_eq!(
            code(fs.add_csr_req(&crypto, &pase(0))),
            ErrorCode::FailSafeRequired
        );

        let mut fs = armed(&pase(0));
        assert_eq!(
            code(fs.add_csr_req(&crypto, &case(1))),
            ErrorCode::NocInvalidFabricIndex
        );

        let key = CanonPkcSecretKey::new_from_ref(fs.add_csr_req(&crypto, &pase(0)).unwrap());
        assert_ne!(key.access(), &[0u8; PKC_CANON_SECRET_KEY_LEN]);

        assert_eq!(
            code(fs.add_csr_req(&crypto, &pase(0))),
            ErrorCode::ConstraintError
        );
        assert_eq!(
            code(fs.update_csr_req(&crypto, &pase(0))),
            ErrorCode::GennCommInvalidAuthentication
        );
    }

    #[test]
    fn update_csr_req_over_case_is_once_per_context() {
        let crypto = test_only_crypto();

        let mut fs = armed(&case(1));
        assert_eq!(
            code(fs.update_csr_req(&crypto, &case(2))),
            ErrorCode::NocInvalidFabricIndex
        );

        let key = CanonPkcSecretKey::new_from_ref(fs.update_csr_req(&crypto, &case(1)).unwrap());
        assert_ne!(key.access(), &[0u8; PKC_CANON_SECRET_KEY_LEN]);

        assert_eq!(
            code(fs.update_csr_req(&crypto, &case(1))),
            ErrorCode::ConstraintError
        );
        assert_eq!(
            code(fs.add_csr_req(&crypto, &case(1))),
            ErrorCode::ConstraintError
        );
    }

    #[test]
    fn noc_command_ordering_matrix() {
        let crypto = test_only_crypto();
        let mut fabrics = Fabrics::new();
        add_fabric(&crypto, &mut fabrics, 0xa, 0x1a);
        let rcac = mint_rcac(&crypto, 0xfab, 0x77);
        let mut buf = [0u8; 1024];

        // AddNOC on an armed context that has seen no CSR at all
        let mut fs = armed(&pase(0));
        fs.add_trusted_root_cert(&crypto, now(), &pase(0), &rcac.cert, &mut buf)
            .unwrap();
        assert_eq!(
            code(fs.add_noc(
                &crypto,
                now(),
                &mut fabrics,
                &pase(0),
                0xfff1,
                None,
                &[],
                &TEST_IPK,
                0x1a,
                &mut buf,
                || {}
            )),
            ErrorCode::NocMissingCsr
        );

        // AddNOC after a CSR but without a trusted root
        let mut fs = armed(&pase(0));
        fs.add_csr_req(&crypto, &pase(0)).unwrap();
        assert_eq!(
            code(fs.add_noc(
                &crypto,
                now(),
                &mut fabrics,
                &pase(0),
                0xfff1,
                None,
                &[],
                &TEST_IPK,
                0x1a,
                &mut buf,
                || {}
            )),
            ErrorCode::ConstraintError
        );

        // UpdateNOC over PASE is never allowed
        assert_eq!(
            code(fs.update_noc(
                &crypto,
                now(),
                &mut fabrics,
                &pase(0),
                None,
                &[],
                &mut buf,
                || {}
            )),
            ErrorCode::GennCommInvalidAuthentication
        );

        // UpdateNOC over CASE without any CSR
        let mut fs = armed(&case(1));
        assert_eq!(
            code(fs.update_noc(
                &crypto,
                now(),
                &mut fabrics,
                &case(1),
                None,
                &[],
                &mut buf,
                || {}
            )),
            ErrorCode::NocMissingCsr
        );

        // UpdateNOC over CASE after an AddNOC-style CSR
        fs.add_csr_req(&crypto, &case(1)).unwrap();
        assert_eq!(
            code(fs.update_noc(
                &crypto,
                now(),
                &mut fabrics,
                &case(1),
                None,
                &[],
                &mut buf,
                || {}
            )),
            ErrorCode::ConstraintError
        );

        // AddNOC over CASE after an UpdateNOC-style CSR
        let mut fs = armed(&case(1));
        fs.update_csr_req(&crypto, &case(1)).unwrap();
        assert_eq!(
            code(fs.add_noc(
                &crypto,
                now(),
                &mut fabrics,
                &case(1),
                0xfff1,
                None,
                &[],
                &TEST_IPK,
                0x1a,
                &mut buf,
                || {}
            )),
            ErrorCode::ConstraintError
        );

        // A trusted root staged in an UpdateNOC context blocks UpdateNOC
        fs.add_trusted_root_cert(&crypto, now(), &case(1), &rcac.cert, &mut buf)
            .unwrap();
        assert_eq!(
            code(fs.update_noc(
                &crypto,
                now(),
                &mut fabrics,
                &case(1),
                None,
                &[],
                &mut buf,
                || {}
            )),
            ErrorCode::ConstraintError
        );

        // Nothing is allowed from another session
        assert_eq!(
            code(fs.update_noc(
                &crypto,
                now(),
                &mut fabrics,
                &case(2),
                None,
                &[],
                &mut buf,
                || {}
            )),
            ErrorCode::NocInvalidFabricIndex
        );
    }

    #[test]
    fn add_noc_creates_a_pending_fabric() {
        let crypto = test_only_crypto();
        let mut fabrics = Fabrics::new();
        let mut fs = armed(&pase(0));

        let rcac = mint_rcac(&crypto, 0xfab, 0x77);
        let key = stage_root_and_csr(&crypto, &mut fs, &pase(0), &rcac);
        assert!(fs.pending_root_ca().is_some());

        let noc = mint_noc_for_pubkey(
            &crypto,
            &rcac,
            true,
            pubkey_of(&crypto, key.reference()).reference(),
            0x1234,
        );

        let mut buf = [0u8; 1024];
        let mut mdns = 0;
        let fabric = fs
            .add_noc(
                &crypto,
                now(),
                &mut fabrics,
                &pase(0),
                0xfff1,
                None,
                &noc,
                &TEST_IPK,
                0x1a,
                &mut buf,
                || mdns += 1,
            )
            .unwrap();

        assert_eq!(mdns, 1);
        assert_eq!(fabric.fab_idx(), idx(1));
        assert_eq!(fabric.node_id(), 0x1234);
        assert_eq!(fabric.fabric_id(), 0xfab);
        assert_eq!(fabric.vendor_id(), 0xfff1);
        assert_eq!(fabric.root_ca(), rcac.cert.as_slice());
        assert_eq!(fabric.noc(), noc.as_slice());
        assert!(fabric.icac().is_empty());
        assert_eq!(fabric.secret_key().access(), key.access());
        assert_eq!(fabric.ipk().epoch_key().access(), &TEST_IPK);
        assert_eq!(fabric.acl().len(), 1);

        // The context now follows the new fabric
        assert!(fs.is_armed_for(1));
        assert!(!fs.is_armed_for(0));
        assert!(fs.has_pending_noc_for(idx(1)));
        assert!(!fs.has_pending_noc_for(idx(2)));
        assert!(fs.pending_root_ca().is_none());
        let (fab_idx, secs_left) = fs.pending_add_noc().unwrap();
        assert_eq!(fab_idx, idx(1));
        assert!(secs_left <= DEFAULT_FAILSAFE_EXPIRY_SECS);
        assert!(secs_left > 0);

        // The PASE session is expected to be upgraded to the new fabric
        assert_eq!(
            code(fs.check_armed(&pase(0))),
            ErrorCode::NocInvalidFabricIndex
        );
        fs.check_armed(&pase(1)).unwrap();

        // Only one AddNOC per context
        assert_eq!(
            code(fs.add_noc(
                &crypto,
                now(),
                &mut fabrics,
                &pase(1),
                0xfff1,
                None,
                &noc,
                &TEST_IPK,
                0x1a,
                &mut buf,
                || {}
            )),
            ErrorCode::ConstraintError
        );
        assert_eq!(
            code(fs.add_csr_req(&crypto, &pase(1))),
            ErrorCode::ConstraintError
        );
        assert_eq!(fabrics.iter().count(), 1);
    }

    #[test]
    fn add_noc_with_icac() {
        let crypto = test_only_crypto();
        let mut fabrics = Fabrics::new();
        let mut fs = armed(&pase(0));

        let rcac = mint_rcac(&crypto, 0xfab, 0x77);
        let icac = mint_icac(&crypto, &rcac);
        let key = stage_root_and_csr(&crypto, &mut fs, &pase(0), &rcac);
        let noc = mint_noc_for_pubkey(
            &crypto,
            &icac,
            false,
            pubkey_of(&crypto, key.reference()).reference(),
            0x1234,
        );

        let mut buf = [0u8; 1024];
        let fabric = fs
            .add_noc(
                &crypto,
                now(),
                &mut fabrics,
                &pase(0),
                0xfff1,
                Some(&icac.cert),
                &noc,
                &TEST_IPK,
                0x1a,
                &mut buf,
                || {},
            )
            .unwrap();

        assert_eq!(fabric.icac(), icac.cert.as_slice());
        assert_eq!(fabric.node_id(), 0x1234);

        // Passing the RCAC itself as the ICAC is rejected
        let mut fs = armed(&pase(0));
        let key = stage_root_and_csr(&crypto, &mut fs, &pase(0), &rcac);
        let noc = mint_noc_for_pubkey(
            &crypto,
            &rcac,
            true,
            pubkey_of(&crypto, key.reference()).reference(),
            0x1235,
        );
        assert_eq!(
            code(fs.add_noc(
                &crypto,
                now(),
                &mut Fabrics::new(),
                &pase(0),
                0xfff1,
                Some(&rcac.cert),
                &noc,
                &TEST_IPK,
                0x1a,
                &mut buf,
                || {}
            )),
            ErrorCode::NocInvalidNoc
        );
    }

    #[test]
    fn add_noc_rejects_bad_admin_subject_key_mismatch_and_foreign_chains() {
        let crypto = test_only_crypto();
        let mut fabrics = Fabrics::new();
        let mut buf = [0u8; 1024];

        let rcac = mint_rcac(&crypto, 0xfab, 0x77);
        let mut fs = armed(&pase(0));
        let key = stage_root_and_csr(&crypto, &mut fs, &pase(0), &rcac);
        let pubkey = pubkey_of(&crypto, key.reference());
        let noc = mint_noc_for_pubkey(&crypto, &rcac, true, pubkey.reference(), 0x1234);

        // CaseAdminSubject must be a node ID or a CAT
        assert_eq!(
            code(fs.add_noc(
                &crypto,
                now(),
                &mut fabrics,
                &pase(0),
                0xfff1,
                None,
                &noc,
                &TEST_IPK,
                0,
                &mut buf,
                || {}
            )),
            ErrorCode::NocInvalidAdminSubject
        );

        // A NOC for some other key than the CSR's
        let other_noc = mint_noc(&crypto, &rcac, true, 0x1234);
        assert_eq!(
            code(fs.add_noc(
                &crypto,
                now(),
                &mut fabrics,
                &pase(0),
                0xfff1,
                None,
                &other_noc.cert,
                &TEST_IPK,
                0x1a,
                &mut buf,
                || {}
            )),
            ErrorCode::NocInvalidPublicKey
        );

        // A NOC not chaining to the staged root
        let other_rcac = mint_rcac(&crypto, 0xfab, 0x78);
        let foreign_noc =
            mint_noc_for_pubkey(&crypto, &other_rcac, true, pubkey.reference(), 0x1234);
        assert_eq!(
            code(fs.add_noc(
                &crypto,
                now(),
                &mut fabrics,
                &pase(0),
                0xfff1,
                None,
                &foreign_noc,
                &TEST_IPK,
                0x1a,
                &mut buf,
                || {}
            )),
            ErrorCode::NocInvalidNoc
        );

        // A malformed IPK
        assert_eq!(
            code(fs.add_noc(
                &crypto,
                now(),
                &mut fabrics,
                &pase(0),
                0xfff1,
                None,
                &noc,
                &TEST_IPK[..15],
                0x1a,
                &mut buf,
                || {}
            )),
            ErrorCode::InvalidData
        );

        // None of the failures consumed the context or added a fabric
        assert!(fs.is_armed_for(0));
        assert!(fs.pending_root_ca().is_some());
        assert!(fs.pending_add_noc().is_none());
        assert_eq!(fabrics.iter().count(), 0);

        // A CAT admin subject is accepted
        fs.add_noc(
            &crypto,
            now(),
            &mut fabrics,
            &pase(0),
            0xfff1,
            None,
            &noc,
            &TEST_IPK,
            0xffff_fffd_0001_0001,
            &mut buf,
            || {},
        )
        .unwrap();
        assert_eq!(fabrics.iter().count(), 1);
    }

    #[test]
    fn add_noc_rejects_duplicate_fabric_and_full_table() {
        let crypto = test_only_crypto();
        let mut fabrics = Fabrics::new();
        let mut buf = [0u8; 1024];

        // A fabric with the same fabric ID under the same root already exists
        let rcac = mint_rcac(&crypto, 0xfab, 0x77);
        let existing = mint_noc(&crypto, &rcac, true, 0x1111);
        fabrics
            .add(
                &crypto,
                existing.key.reference(),
                &rcac.cert,
                &existing.cert,
                &[],
                Some(crate::crypto::CanonAeadKeyRef::new(&TEST_IPK)),
                0xfff1,
                0x1111,
            )
            .unwrap();

        let mut fs = armed(&pase(0));
        let key = stage_root_and_csr(&crypto, &mut fs, &pase(0), &rcac);
        let noc = mint_noc_for_pubkey(
            &crypto,
            &rcac,
            true,
            pubkey_of(&crypto, key.reference()).reference(),
            0x2222,
        );
        assert_eq!(
            code(fs.add_noc(
                &crypto,
                now(),
                &mut fabrics,
                &pase(0),
                0xfff1,
                None,
                &noc,
                &TEST_IPK,
                0x1a,
                &mut buf,
                || {}
            )),
            ErrorCode::NocFabricConflict
        );
        assert_eq!(fabrics.iter().count(), 1);

        // Same fabric ID under a different root is a different fabric
        let mut fabrics = Fabrics::new();
        for i in 0..MAX_FABRICS as u64 {
            add_fabric(&crypto, &mut fabrics, 0x100 + i, 0x200 + i);
        }
        assert_eq!(
            code(fs.add_noc(
                &crypto,
                now(),
                &mut fabrics,
                &pase(0),
                0xfff1,
                None,
                &noc,
                &TEST_IPK,
                0x1a,
                &mut buf,
                || {}
            )),
            ErrorCode::NocFabricTableFull
        );
        assert_eq!(fabrics.iter().count(), MAX_FABRICS);
        assert!(fs.pending_add_noc().is_none());
    }

    #[test]
    fn update_noc_replaces_the_fabric_noc() {
        let crypto = test_only_crypto();
        let mut fabrics = Fabrics::new();
        let mut buf = [0u8; 1024];

        let rcac = mint_rcac(&crypto, 0xfab, 0x77);
        let original = mint_noc(&crypto, &rcac, true, 0x1111);
        fabrics
            .add(
                &crypto,
                original.key.reference(),
                &rcac.cert,
                &original.cert,
                &[],
                Some(crate::crypto::CanonAeadKeyRef::new(&TEST_IPK)),
                0xfff1,
                0x1111,
            )
            .unwrap();
        fabrics.update_label(idx(1), "home").unwrap();

        let mut fs = armed(&case(1));
        let key = CanonPkcSecretKey::new_from_ref(fs.update_csr_req(&crypto, &case(1)).unwrap());
        let pubkey = pubkey_of(&crypto, key.reference());

        // A NOC for some other key than the CSR's
        assert_eq!(
            code(fs.update_noc(
                &crypto,
                now(),
                &mut fabrics,
                &case(1),
                None,
                &original.cert,
                &mut buf,
                || {}
            )),
            ErrorCode::NocInvalidPublicKey
        );

        // A NOC not chaining to the fabric's root
        let other_rcac = mint_rcac(&crypto, 0xfab, 0x78);
        let foreign = mint_noc_for_pubkey(&crypto, &other_rcac, true, pubkey.reference(), 0x2222);
        assert_eq!(
            code(fs.update_noc(
                &crypto,
                now(),
                &mut fabrics,
                &case(1),
                None,
                &foreign,
                &mut buf,
                || {}
            )),
            ErrorCode::NocInvalidNoc
        );
        assert_eq!(fabrics.get(idx(1)).unwrap().node_id(), 0x1111);
        assert!(!fs.has_pending_noc_for(idx(1)));

        let noc = mint_noc_for_pubkey(&crypto, &rcac, true, pubkey.reference(), 0x2222);
        let mut mdns = 0;
        let fabric = fs
            .update_noc(
                &crypto,
                now(),
                &mut fabrics,
                &case(1),
                None,
                &noc,
                &mut buf,
                || mdns += 1,
            )
            .unwrap();

        assert_eq!(mdns, 1);
        assert_eq!(fabric.fab_idx(), idx(1));
        assert_eq!(fabric.node_id(), 0x2222);
        assert_eq!(fabric.noc(), noc.as_slice());
        assert_eq!(fabric.secret_key().access(), key.access());
        assert_eq!(fabric.root_ca(), rcac.cert.as_slice());
        assert_eq!(fabric.label(), "home");

        assert!(fs.is_armed_for(1));
        assert!(fs.has_pending_noc_for(idx(1)));
        // Only `AddNOC` reports a pending fabric
        assert!(fs.pending_add_noc().is_none());
        assert!(fs.pending_root_ca().is_none());

        // Only one UpdateNOC per context
        assert_eq!(
            code(fs.update_noc(
                &crypto,
                now(),
                &mut fabrics,
                &case(1),
                None,
                &noc,
                &mut buf,
                || {}
            )),
            ErrorCode::ConstraintError
        );
    }

    #[test]
    fn expire_when_idle_is_a_noop() {
        let mut fs = FailSafe::new();
        fs.set_breadcrumb(5);

        let removed = fs
            .expire(
                &mut Fabrics::new(),
                || {},
                MemKv::new(MemKvBlobStore::default()),
                || panic!("no mdns notification expected"),
                |_, _| panic!("no change expected"),
            )
            .unwrap();

        assert_eq!(removed, None);
        assert_eq!(fs.breadcrumb(), 5);
    }

    #[test]
    fn expire_drops_a_fabric_pending_from_add_noc() {
        let crypto = test_only_crypto();
        let mut fabrics = Fabrics::new();
        let mut fs = armed(&pase(0));
        fs.set_breadcrumb(3);

        let (_, fab_idx) = add_noc_flow(&crypto, &mut fs, &mut fabrics, 0xfab, 0x1234);
        assert_eq!(fab_idx, idx(1));
        assert!(fabrics.get(idx(1)).is_some());

        let mut mdns = 0;
        let mut changes = std::vec::Vec::new();
        let removed = fs
            .expire(
                &mut fabrics,
                || {},
                MemKv::new(MemKvBlobStore::default()),
                || mdns += 1,
                |ep, cl| changes.push((ep, cl)),
            )
            .unwrap();

        assert_eq!(
            removed,
            Some(Expiry {
                removed_fabric: Some(idx(1))
            })
        );
        assert!(fabrics.get(idx(1)).is_none());
        assert_eq!(fabrics.iter().count(), 0);
        assert!(!fs.is_armed());
        assert_eq!(fs.breadcrumb(), 0);
        assert!(fs.pending_add_noc().is_none());
        assert_eq!(mdns, 1);
        assert_eq!(changes, expected_expiry_changes());
    }

    #[test]
    fn expire_restores_a_persisted_fabric_after_update_noc() {
        let crypto = test_only_crypto();
        let mut fabrics = Fabrics::new();
        let mut buf = [0u8; 1024];

        let rcac = mint_rcac(&crypto, 0xfab, 0x77);
        let original = mint_noc(&crypto, &rcac, true, 0x1111);
        fabrics
            .add(
                &crypto,
                original.key.reference(),
                &rcac.cert,
                &original.cert,
                &[],
                Some(crate::crypto::CanonAeadKeyRef::new(&TEST_IPK)),
                0xfff1,
                0x1111,
            )
            .unwrap();
        fabrics.update_label(idx(1), "home").unwrap();

        let kv = MemKv::new(MemKvBlobStore::default());
        FabricPersist::new(&kv)
            .store(fabrics.get(idx(1)).unwrap())
            .unwrap();

        let mut fs = armed(&case(1));
        let key = CanonPkcSecretKey::new_from_ref(fs.update_csr_req(&crypto, &case(1)).unwrap());
        let noc = mint_noc_for_pubkey(
            &crypto,
            &rcac,
            true,
            pubkey_of(&crypto, key.reference()).reference(),
            0x2222,
        );
        fs.update_noc(
            &crypto,
            now(),
            &mut fabrics,
            &case(1),
            None,
            &noc,
            &mut buf,
            || {},
        )
        .unwrap();
        assert_eq!(fabrics.get(idx(1)).unwrap().node_id(), 0x2222);

        let removed = fs
            .expire(&mut fabrics, || {}, &kv, || {}, |_, _| {})
            .unwrap();

        // The fabric is resurrected from storage rather than removed
        assert_eq!(
            removed,
            Some(Expiry {
                removed_fabric: None
            })
        );
        let fabric = fabrics.get(idx(1)).unwrap();
        assert_eq!(fabric.node_id(), 0x1111);
        assert_eq!(fabric.noc(), original.cert.as_slice());
        assert_eq!(fabric.secret_key().access(), original.key.access());
        assert_eq!(fabric.label(), "home");
        assert!(!fs.is_armed());
    }

    #[test]
    fn expire_of_a_context_without_pending_noc_keeps_fabrics() {
        let crypto = test_only_crypto();
        let mut fabrics = Fabrics::new();
        add_fabric(&crypto, &mut fabrics, 0xa, 0x1a);

        let kv = MemKv::new(MemKvBlobStore::default());
        FabricPersist::new(&kv)
            .store(fabrics.get(idx(1)).unwrap())
            .unwrap();

        // Armed over CASE for fabric 1 but nothing staged: the fabric is
        // reloaded from its persisted copy and reported as kept
        let mut fs = armed(&case(1));
        let removed = fs
            .expire(&mut fabrics, || {}, &kv, || {}, |_, _| {})
            .unwrap();
        assert_eq!(
            removed,
            Some(Expiry {
                removed_fabric: None
            })
        );
        assert_eq!(fabrics.get(idx(1)).unwrap().node_id(), 0x1a);

        // Armed over PASE with no fabric involved: nothing to roll back
        let mut fs = armed(&pase(0));
        let removed = fs
            .expire(&mut fabrics, || {}, &kv, || {}, |_, _| {})
            .unwrap();
        assert_eq!(
            removed,
            Some(Expiry {
                removed_fabric: None
            })
        );
        assert_eq!(fabrics.iter().count(), 1);
    }

    #[test]
    fn expire_removes_the_pase_sessions_only_when_armed() {
        let mut removals = 0;

        let mut fs = armed(&pase(0));
        fs.expire(
            &mut Fabrics::new(),
            || removals += 1,
            MemKv::new(MemKvBlobStore::default()),
            || {},
            |_, _| {},
        )
        .unwrap();
        assert_eq!(removals, 1);

        // Not armed anymore
        fs.expire(
            &mut Fabrics::new(),
            || removals += 1,
            MemKv::new(MemKvBlobStore::default()),
            || {},
            |_, _| {},
        )
        .unwrap();
        assert_eq!(removals, 1);
    }

    #[test]
    fn arm_resumed_behaves_like_a_context_after_add_noc() {
        let crypto = test_only_crypto();
        let mut fabrics = Fabrics::new();
        let mut buf = [0u8; 1024];

        let mut fs = FailSafe::new();
        fs.arm_resumed(idx(3), 30, 11).unwrap();

        assert!(fs.is_armed_for(3));
        assert!(fs.has_pending_noc_for(idx(3)));
        assert_eq!(fs.breadcrumb(), 11);
        let (fab_idx, secs_left) = fs.pending_add_noc().unwrap();
        assert_eq!(fab_idx, idx(3));
        assert!(secs_left <= 30);
        // No root cert bytes were staged, so none is pending
        assert!(fs.pending_root_ca().is_none());

        // Already armed
        assert_eq!(code(fs.arm_resumed(idx(4), 30, 12)), ErrorCode::Busy);
        assert!(fs.is_armed_for(3));

        // The NOC commands are consumed, exactly as after a real AddNOC
        assert_eq!(
            code(fs.add_csr_req(&crypto, &pase(3))),
            ErrorCode::ConstraintError
        );
        assert_eq!(
            code(fs.add_noc(
                &crypto,
                now(),
                &mut fabrics,
                &pase(3),
                0xfff1,
                None,
                &[],
                &TEST_IPK,
                0x1a,
                &mut buf,
                || {}
            )),
            ErrorCode::ConstraintError
        );

        // Re-arming from the same session and disarming work as usual
        fs.arm(60, 13, &pase(3), false).unwrap();
        assert_eq!(fs.breadcrumb(), 13);
        fs.arm(0, 0, &pase(3), false).unwrap();
        assert!(!fs.is_armed());

        // Arming normally after that is fine again
        fs.arm_resumed(idx(4), 30, 12).unwrap();
        assert!(fs.is_armed_for(4));
    }
}