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
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
/*
*
* 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::mem::MaybeUninit;
use core::num::NonZeroU8;
use cfg_if::cfg_if;
use crate::acl::{self, AccessReq, AclEntry, AuthMode};
use crate::cert::{CertRef, MAX_CERT_TLV_LEN};
use crate::crypto::{
CanonAeadKeyRef, CanonPkcPublicKeyRef, CanonPkcSecretKey, CanonPkcSecretKeyRef, Crypto,
CryptoSensitive, Digest, Hash, Kdf, PKC_CANON_PUBLIC_KEY_LEN,
};
use crate::dm::Privilege;
use crate::error::{Error, ErrorCode};
use crate::group_keys::KeySet;
use crate::persist::{
load_logged, KvBlobStore, KvBlobStoreAccess, Persist, FABRIC_KEYS_START, NEXT_FABRIC_INDEX_KEY,
};
#[cfg(feature = "groups")]
use crate::tlv::Skippable;
use crate::tlv::{FromTLV, TLVElement, TlvError, TlvErrorCode, ToTLV};
use crate::utils::init::{init, Init, InitMaybeUninit, IntoFallibleInit};
use crate::utils::storage::{String, Vec};
const COMPRESSED_FABRIC_ID_LEN: usize = 8;
/// The largest fabric index: 0 is reserved, and 255 would leave no room for
/// nullable fabric index fields.
const MAX_FAB_IDX: u8 = u8::MAX - 1;
/// All multicast-group fabric state: the group key sets, the group→keyset
/// mapping, and the group table. Gated as one inline module so the whole block
/// (consts, TLV structs and the `Groups` container) is compiled out with a
/// single `#[cfg]` when the `groups` feature is off, and re-exported so the rest
/// of `fabric` refers to these items unqualified.
#[cfg(feature = "groups")]
mod groups {
use core::str::FromStr;
use cfg_if::cfg_if;
use crate::error::{Error, ErrorCode};
use crate::group_keys::GroupKeySet;
use crate::tlv::{FromTLV, ToTLV};
use crate::utils::init::{init, Init, InitDefault};
use crate::utils::storage::{String, Vec};
cfg_if! {
if #[cfg(feature = "max-group-keys-per-fabric-5")] {
/// Max number of group key sets per fabric (excluding IPK at index 0).
pub const MAX_GROUP_KEYS_PER_FABRIC: usize = 5;
} else if #[cfg(feature = "max-group-keys-per-fabric-4")] {
/// Max number of group key sets per fabric (excluding IPK at index 0).
pub const MAX_GROUP_KEYS_PER_FABRIC: usize = 4;
} else if #[cfg(feature = "max-group-keys-per-fabric-3")] {
/// Max number of group key sets per fabric (excluding IPK at index 0).
pub const MAX_GROUP_KEYS_PER_FABRIC: usize = 3;
} else if #[cfg(feature = "max-group-keys-per-fabric-2")] {
/// Max number of group key sets per fabric (excluding IPK at index 0).
pub const MAX_GROUP_KEYS_PER_FABRIC: usize = 2;
} else { // Matter requires a minimum of 3 group key sets per fabric
/// Max number of group key sets per fabric (excluding IPK at index 0).
pub const MAX_GROUP_KEYS_PER_FABRIC: usize = 3;
}
}
/// Max length of a group name (per Matter spec).
pub const MAX_GROUP_NAME_LEN: usize = 16;
cfg_if! {
if #[cfg(feature = "max-groups-per-fabric-32")] {
/// Max number of group key map entries per fabric.
pub const MAX_GROUPS_PER_FABRIC: usize = 32;
} else if #[cfg(feature = "max-groups-per-fabric-16")] {
/// Max number of group key map entries per fabric.
pub const MAX_GROUPS_PER_FABRIC: usize = 16;
} else if #[cfg(feature = "max-groups-per-fabric-12")] {
/// Max number of group key map entries per fabric.
pub const MAX_GROUPS_PER_FABRIC: usize = 12;
} else if #[cfg(feature = "max-groups-per-fabric-8")] {
/// Max number of group key map entries per fabric.
pub const MAX_GROUPS_PER_FABRIC: usize = 9;
} else if #[cfg(feature = "max-groups-per-fabric-7")] {
/// Max number of group key map entries per fabric.
pub const MAX_GROUPS_PER_FABRIC: usize = 7;
} else if #[cfg(feature = "max-groups-per-fabric-6")] {
/// Max number of group key map entries per fabric.
pub const MAX_GROUPS_PER_FABRIC: usize = 6;
} else if #[cfg(feature = "max-groups-per-fabric-5")] {
/// Max number of group key map entries per fabric.
pub const MAX_GROUPS_PER_FABRIC: usize = 5;
} else if #[cfg(feature = "max-groups-per-fabric-4")] {
/// Max number of group key map entries per fabric.
pub const MAX_GROUPS_PER_FABRIC: usize = 4;
} else { // Matter requires a minimum of 4 group table entries per fabric
/// Max number of group key map entries per fabric.
pub const MAX_GROUPS_PER_FABRIC: usize = 4;
}
}
cfg_if! {
if #[cfg(feature = "max-group-endpoints-per-fabric-5")] {
/// Max number of endpoints per group entry.
pub const GROUP_ENDPOINTS_PER_FABRIC: usize = 5;
} else if #[cfg(feature = "max-group-endpoints-per-fabric-4")] {
/// Max number of endpoints per group entry.
pub const GROUP_ENDPOINTS_PER_FABRIC: usize = 4;
} else if #[cfg(feature = "max-group-endpoints-per-fabric-3")] {
/// Max number of endpoints per group entry.
pub const GROUP_ENDPOINTS_PER_FABRIC: usize = 3;
} else if #[cfg(feature = "max-group-endpoints-per-fabric-2")] {
/// Max number of endpoints per group entry.
pub const GROUP_ENDPOINTS_PER_FABRIC: usize = 2;
} else if #[cfg(feature = "max-group-endpoints-per-fabric-1")] {
/// Max number of endpoints per group entry.
pub const GROUP_ENDPOINTS_PER_FABRIC: usize = 1;
} else { // Default: 3 endpoints per group entry
/// Max number of endpoints per group entry.
pub const GROUP_ENDPOINTS_PER_FABRIC: usize = 3;
}
}
/// A group table entry mapping a group ID to its endpoints and name.
#[derive(Debug, FromTLV, ToTLV)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct GroupEndpointMapping {
pub group_id: u16,
pub endpoints: Vec<u16, GROUP_ENDPOINTS_PER_FABRIC>,
pub group_name: String<MAX_GROUP_NAME_LEN>,
/// Whether the (Groupcast-managed) group has auxiliary ACL entries
/// generated for its endpoints - see the Groupcast cluster's
/// `ConfigureAuxiliaryACL` command and the `AuxiliaryACL` attribute
/// of the Access Control cluster.
///
/// `None` (in blobs persisted before the field existed) means `false`.
pub has_aux_acl: Option<bool>,
/// The multicast-address policy of the group, when it is managed by
/// the Groupcast cluster.
///
/// `None` means the group was created via the legacy Groups cluster,
/// which behaves like the `PerGroup` policy (such nodes join the
/// fabric+group-scoped multicast address) - the `PerGroup` policy
/// exists precisely for interop with them.
pub mcast_policy: Option<MulticastAddrPolicy>,
}
/// The multicast address policy of a group.
///
/// The values are the ones of the Groupcast cluster.
#[derive(Debug, PartialEq, Eq, Copy, Clone, Hash, FromTLV, ToTLV)]
#[tlvargs(datatype = "u8")]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[repr(u8)]
pub enum MulticastAddrPolicy {
/// The group uses the IANA-assigned Groupcast multicast address.
#[enumval(0)]
IanaAddr = 0,
/// The group uses a multicast address computed from its fabric and group IDs.
#[enumval(1)]
PerGroup = 1,
}
impl GroupEndpointMapping {
/// Whether the group has auxiliary ACL entries generated for its
/// endpoints.
pub fn has_aux_acl(&self) -> bool {
self.has_aux_acl.unwrap_or(false)
}
/// The effective multicast-address policy of the group (legacy
/// Groups-cluster entries behave as `PerGroup`).
pub fn effective_mcast_policy(&self) -> MulticastAddrPolicy {
self.mcast_policy.unwrap_or(MulticastAddrPolicy::PerGroup)
}
/// Whether the group is managed by the Groupcast cluster (as opposed
/// to the legacy Groups cluster).
pub fn groupcast_managed(&self) -> bool {
self.mcast_policy.is_some()
}
}
/// A stored group key map entry (maps group ID to key set).
#[derive(Debug, Clone, Default, FromTLV, ToTLV)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct GroupKeyMapping {
pub group_id: u16,
pub group_key_set_id: u16,
}
#[derive(Debug, FromTLV, ToTLV)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct Groups {
/// Group key sets (excluding IPK which is stored in `ipk`)
key_sets: Vec<GroupKeySet, MAX_GROUP_KEYS_PER_FABRIC>,
/// Groups keyset mapping
key_map: Vec<GroupKeyMapping, MAX_GROUPS_PER_FABRIC>,
/// Group table (group ID → endpoints + name)
endpoint_mapping: Vec<GroupEndpointMapping, MAX_GROUPS_PER_FABRIC>,
}
impl Groups {
pub const fn new() -> Self {
Self {
key_sets: Vec::new(),
key_map: Vec::new(),
endpoint_mapping: Vec::new(),
}
}
pub fn init() -> impl Init<Self> {
init!(Self {
key_sets <- Vec::init(),
key_map <- Vec::init(),
endpoint_mapping <- Vec::init(),
})
}
/// Return an iterator over the group key sets of the fabric
pub fn key_set_iter(&self) -> impl Iterator<Item = &GroupKeySet> {
self.key_sets.iter()
}
/// Find a group key set by ID
pub fn key_set_get(&self, id: u16) -> Option<&GroupKeySet> {
self.key_sets.iter().find(|e| e.group_key_set_id == id)
}
/// Add or update a group key set
pub fn key_set_add(&mut self, entry: GroupKeySet) -> Result<(), Error> {
if let Some(existing) = self
.key_sets
.iter_mut()
.find(|e| e.group_key_set_id == entry.group_key_set_id)
{
*existing = entry;
} else {
self.key_sets
.push(entry)
.map_err(|_| ErrorCode::ResourceExhausted)?;
}
Ok(())
}
/// Remove a group key set by ID. Returns true if found and removed.
pub fn key_set_remove(&mut self, id: u16) -> Result<(), Error> {
let before = self.key_sets.len();
self.key_sets.retain(|e| e.group_key_set_id != id);
let removed = self.key_sets.len() < before;
self.key_map_remove_by_key_set(id);
// Check if element was actually removed
if removed {
Ok(())
} else {
Err(Error::new(ErrorCode::NotFound))
}
}
/// Append a group key map entry.
///
/// A full map answers `Failure` rather than `ResourceExhausted`: that is
/// the status the CHIP SDK gives, and what its `TestGroupKeyManagementCluster`
/// expects, for the per-entry appends chip-tool turns a list write into.
pub fn key_map_add(&mut self, entry: GroupKeyMapping) -> Result<(), Error> {
self.key_map.push(entry).map_err(|_| ErrorCode::Failure)?;
Ok(())
}
/// Return an iterator over the group key map entries of the fabric
pub fn key_map_iter(&self) -> impl Iterator<Item = &GroupKeyMapping> {
self.key_map.iter()
}
/// Replace all group key map entries
pub fn key_map_replace(
&mut self,
entries: impl Iterator<Item = GroupKeyMapping>,
) -> Result<(), Error> {
self.key_map.clear();
for entry in entries {
self.key_map
.push(entry)
.map_err(|_| ErrorCode::ResourceExhausted)?;
}
Ok(())
}
/// Remove group key map entries that reference a specific key set ID
pub fn key_map_remove_by_key_set(&mut self, key_set_id: u16) {
self.key_map.retain(|e| e.group_key_set_id != key_set_id);
}
/// Return an iterator over the group table entries
pub fn iter(&self) -> impl Iterator<Item = &GroupEndpointMapping> {
self.endpoint_mapping.iter()
}
/// Look up a group by ID
pub fn get(&self, group_id: u16) -> Option<&GroupEndpointMapping> {
self.endpoint_mapping
.iter()
.find(|e| e.group_id == group_id)
}
/// Look up a group by ID, mutably
pub fn get_mut(&mut self, group_id: u16) -> Option<&mut GroupEndpointMapping> {
self.endpoint_mapping
.iter_mut()
.find(|e| e.group_id == group_id)
}
/// Add an endpoint to a group.
/// Returns true if the endpoint was already a member (name still updated per spec).
pub fn add(
&mut self,
endpoint_id: u16,
group_id: u16,
group_name: &str,
) -> Result<bool, Error> {
// Validate the name up-front, so that a rejected command leaves the table untouched
let group_name =
String::from_str(group_name).map_err(|_| ErrorCode::ConstraintError)?;
let entry = if let Some(entry) = self
.endpoint_mapping
.iter_mut()
.find(|e| e.group_id == group_id)
{
entry
} else {
self.endpoint_mapping
.push(GroupEndpointMapping {
group_id,
endpoints: Vec::new(),
group_name: group_name.clone(),
has_aux_acl: None,
mcast_policy: None,
})
.map_err(|_| ErrorCode::ResourceExhausted)?;
unwrap!(self.endpoint_mapping.last_mut())
};
// Update group name
entry.group_name = group_name;
if entry.endpoints.contains(&endpoint_id) {
return Ok(true);
}
entry
.endpoints
.push(endpoint_id)
.map_err(|_| ErrorCode::ResourceExhausted)?;
Ok(false)
}
/// Remove an endpoint from a group, or from all groups if `group_id` is `None`.
/// Returns true if the endpoint was removed from at least one group.
pub fn remove(&mut self, endpoint_id: u16, group_id: Option<u16>) -> bool {
let mut removed = false;
for entry in self.endpoint_mapping.iter_mut() {
if group_id.is_some_and(|id| id != entry.group_id) {
continue;
}
let before = entry.endpoints.len();
entry.endpoints.retain(|&ep| ep != endpoint_id);
if entry.endpoints.len() < before {
removed = true;
}
}
// Remove entries with no endpoints left - except Groupcast-managed
// ones, which may legitimately exist with no endpoints (a
// sender-only membership); the Groupcast cluster removes those
// explicitly via its `LeaveGroup` command.
self.endpoint_mapping
.retain(|e| !e.endpoints.is_empty() || e.groupcast_managed());
removed
}
/// Join endpoints to a group on behalf of the Groupcast cluster,
/// creating the membership if it does not exist.
///
/// - `endpoints`: the endpoints to add (may be empty for a
/// sender-only membership); duplicates are omitted;
/// - `replace`: when `true`, the given endpoints replace the
/// existing list instead of being appended;
/// - `mcast_policy`: the multicast-address policy; applied on
/// creation, or updated when `Some` on an existing membership.
///
/// Errors with `ResourceExhausted` when the membership or endpoint
/// capacity is exceeded; the membership is left unchanged in that
/// case, except that a possibly-performed `replace` clearing is
/// rolled back by restoring nothing (the caller re-checks capacity
/// upfront via [`Self::group_count`] and the endpoint capacity).
pub fn groupcast_join(
&mut self,
group_id: u16,
endpoints: &[u16],
replace: bool,
mcast_policy: Option<MulticastAddrPolicy>,
) -> Result<(), Error> {
let entry = if let Some(entry) = self
.endpoint_mapping
.iter_mut()
.find(|e| e.group_id == group_id)
{
entry
} else {
self.endpoint_mapping
.push(GroupEndpointMapping {
group_id,
endpoints: Vec::new(),
group_name: String::new(),
has_aux_acl: Some(false),
mcast_policy: Some(mcast_policy.unwrap_or(MulticastAddrPolicy::IanaAddr)),
})
.map_err(|_| ErrorCode::ResourceExhausted)?;
unwrap!(self.endpoint_mapping.last_mut())
};
// Joining via Groupcast upgrades a legacy entry to
// Groupcast-managed (the default policy matches the legacy
// behavior)
if entry.mcast_policy.is_none() {
entry.mcast_policy = Some(MulticastAddrPolicy::PerGroup);
}
if let Some(mcast_policy) = mcast_policy {
entry.mcast_policy = Some(mcast_policy);
}
if replace {
entry.endpoints.clear();
}
for endpoint in endpoints {
if !entry.endpoints.contains(endpoint) {
entry
.endpoints
.push(*endpoint)
.map_err(|_| ErrorCode::ResourceExhausted)?;
}
}
Ok(())
}
/// Remove a whole group membership. Returns `true` if it existed.
pub fn groupcast_remove(&mut self, group_id: u16) -> bool {
let before = self.endpoint_mapping.len();
self.endpoint_mapping.retain(|e| e.group_id != group_id);
before != self.endpoint_mapping.len()
}
/// Set the `has_aux_acl` flag of a group membership.
/// Returns `true` if the flag changed.
pub fn set_has_aux_acl(&mut self, group_id: u16, has_aux_acl: bool) -> bool {
let Some(entry) = self
.endpoint_mapping
.iter_mut()
.find(|e| e.group_id == group_id)
else {
return false;
};
let changed = entry.has_aux_acl() != has_aux_acl;
entry.has_aux_acl = Some(has_aux_acl);
changed
}
/// The number of group memberships of this fabric.
pub fn group_count(&self) -> usize {
self.endpoint_mapping.len()
}
/// Look up the key set ID mapped to a group, if any.
pub fn key_map_get(&self, group_id: u16) -> Option<u16> {
self.key_map
.iter()
.find(|e| e.group_id == group_id)
.map(|e| e.group_key_set_id)
}
/// Map a group to a key set, replacing any previous mapping of that
/// group.
pub fn key_map_set_group(&mut self, group_id: u16, key_set_id: u16) -> Result<(), Error> {
if let Some(entry) = self.key_map.iter_mut().find(|e| e.group_id == group_id) {
entry.group_key_set_id = key_set_id;
return Ok(());
}
self.key_map
.push(GroupKeyMapping {
group_id,
group_key_set_id: key_set_id,
})
.map_err(|_| ErrorCode::ResourceExhausted.into())
}
/// Remove all key-set mappings of the given group.
pub fn key_map_remove_group(&mut self, group_id: u16) {
self.key_map.retain(|e| e.group_id != group_id);
}
}
impl Default for Groups {
fn default() -> Self {
Self::new()
}
}
impl InitDefault for Groups {
fn init_default() -> impl Init<Self> {
Self::init()
}
}
}
#[cfg(feature = "groups")]
pub use groups::*;
/// Fabric type
#[derive(Debug, ToTLV, FromTLV)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct Fabric {
/// Fabric local index
fab_idx: NonZeroU8,
/// Fabric node ID
node_id: u64,
/// Fabric ID
fabric_id: u64,
/// Vendor ID
vendor_id: u16,
/// Compressed ID
compressed_fabric_id: u64,
/// Fabric secret key
secret_key: CanonPkcSecretKey,
/// Root CA certificate to be used when verifying the node's certificate
///
/// Note that we deviate from the Matter spec here, in that we store the
/// root certificate in the Fabric type itself, rather than - as the
/// spec mandates - in a separate Root CA store
///
/// This simplifies the implementation, but results in potentially multiple
/// copies of the same Root CA used accross multiple fabrics.
root_ca: Vec<u8, { MAX_CERT_TLV_LEN }>,
/// Either the Intermediate CA certificate (`vvsc_set == false`) or the
/// Vendor Verification Signing Cert (`vvsc_set == true`). The two are
/// mutually exclusive in the cert chain (Matter Core spec) —
/// a fabric with an ICAC cannot also carry a VVSC and vice
/// versa — so we share one buffer instead of paying for both. Empty
/// means neither is set; in that case `vvsc_set` is meaningless.
icac_or_vvsc: Vec<u8, { MAX_CERT_TLV_LEN }>,
/// Selector for what `icac_or_vvsc` holds: `false` for an ICAC,
/// `true` for a VVSC.
vvsc_set: bool,
/// Node Operational Certificate
noc: Vec<u8, { MAX_CERT_TLV_LEN }>,
/// Identity Protection Key
ipk: KeySet,
/// Fabric label; unique accross all fabrics on the device
label: String<32>,
/// Access Control List
acl: Vec<AclEntry, { acl::MAX_ACL_ENTRIES_PER_FABRIC }>,
/// Fabric group information.
#[cfg(feature = "groups")]
#[tagval(13)]
groups: Skippable<Groups>,
/// VID Verification Statement (Matter Core spec).
/// Either empty (not set) or exactly `VID_VERIFICATION_STATEMENT_LEN`
/// bytes long; the cluster XML enforces both bounds at the schema
/// level (`length="85" minLength="85"`).
#[tagval(14)]
vid_verification_statement: Vec<u8, VID_VERIFICATION_STATEMENT_LEN>,
}
/// Exact length of a non-empty VID Verification Statement.
/// Matches `length="85" minLength="85"` on
/// `OperationalCredentials::SetVIDVerificationStatement.vid_verification_statement`.
pub const VID_VERIFICATION_STATEMENT_LEN: usize = 85;
impl Fabric {
/// Return an in-place-initializer for a Fabric type, with the
/// provided Fabric Index and KeyPair
///
/// All other fields are initialized to default values, which are NOT
/// valid for the operation of the fabric.
///
/// The Fabric must be updated with the correct values before it can be
/// used, via `Fabric::update`.
fn init(fab_idx: NonZeroU8) -> impl Init<Self> {
// NOTE: the `init!` macro does not accept `#[cfg]` on its field entries,
// so the `groups` field (present only under the `groups` feature) forces
// two variants of the initializer that differ solely by that last field.
#[cfg(feature = "groups")]
let r = init!(Self {
fab_idx,
node_id: 0,
fabric_id: 0,
vendor_id: 0,
compressed_fabric_id: 0,
secret_key <- CanonPkcSecretKey::init(),
root_ca <- Vec::init(),
icac_or_vvsc <- Vec::init(),
vvsc_set: false,
noc <- Vec::init(),
ipk <- KeySet::init(),
label: String::new(),
acl <- Vec::init(),
vid_verification_statement <- Vec::init(),
groups <- Skippable::init_default(),
});
#[cfg(not(feature = "groups"))]
let r = init!(Self {
fab_idx,
node_id: 0,
fabric_id: 0,
vendor_id: 0,
compressed_fabric_id: 0,
secret_key <- CanonPkcSecretKey::init(),
root_ca <- Vec::init(),
icac_or_vvsc <- Vec::init(),
vvsc_set: false,
noc <- Vec::init(),
ipk <- KeySet::init(),
label: String::new(),
acl <- Vec::init(),
vid_verification_statement <- Vec::init(),
});
r
}
/// Update the fabric with the provided data so that it can operate.
///
/// This method is supposed to be called right after `Fabric::init` or
/// when the NOC of the fabric needs to be updated.
///
/// `root_ca` is `None` when called from the `UpdateNOC` flow — Matter
/// Core spec keeps the fabric's root cert unchanged
/// across `UpdateNOC`, and re-passing the existing bytes here would
/// require a (large) caller-side copy of `self.root_ca`. `Some(...)`
/// is used by the initial `AddNOC` flow, where the cert was just
/// staged in the fail-safe context.
#[allow(clippy::too_many_arguments)]
fn update<C: Crypto>(
&mut self,
crypto: C,
root_ca: Option<&[u8]>,
noc: &[u8],
icac: &[u8],
secret_key: CanonPkcSecretKeyRef<'_>,
epoch_key: Option<CanonAeadKeyRef<'_>>,
vendor_id: Option<u16>,
case_admin_subject: Option<u64>,
) -> Result<(), Error> {
if let Some(root_ca) = root_ca {
self.root_ca.clear();
self.root_ca
.extend_from_slice(root_ca)
.map_err(|_| ErrorCode::BufferTooSmall)?;
}
// `AddNOC` / `UpdateNOC` always replace the cert chain, so any
// previously-staged VVSC for this fabric is implicitly cleared
// here — the spec doesn't allow an ICAC and a VVSC to coexist.
self.icac_or_vvsc.clear();
self.icac_or_vvsc
.extend_from_slice(icac)
.map_err(|_| ErrorCode::BufferTooSmall)?;
self.vvsc_set = false;
self.noc.clear();
self.noc
.extend_from_slice(noc)
.map_err(|_| ErrorCode::BufferTooSmall)?;
let root_cert = CertRef::new(TLVElement::new(self.root_ca.as_slice()));
let noc_cert = CertRef::new(TLVElement::new(noc));
self.node_id = noc_cert.get_node_id()?;
self.fabric_id = noc_cert.get_fabric_id()?;
self.compressed_fabric_id = Self::compute_compressed_fabric_id(
&crypto,
root_cert.pubkey()?.try_into()?,
self.fabric_id,
);
if let Some(epoch_key) = epoch_key {
self.ipk
.update(&crypto, epoch_key, &self.compressed_fabric_id)?;
}
if let Some(vendor_id) = vendor_id {
self.vendor_id = vendor_id;
}
if let Some(case_admin_subject) = case_admin_subject {
self.acl.clear();
self.acl.push_init(
AclEntry::init(None, Privilege::ADMIN, AuthMode::Case)
.into_fallible()
.chain(|e| {
e.fab_idx = Some(self.fab_idx);
e.add_subject(case_admin_subject)
}),
|| ErrorCode::ResourceExhausted.into(),
)?;
}
self.secret_key.load(secret_key);
Ok(())
}
/// Is the fabric matching the privided destination ID
pub fn is_dest_id<C: Crypto>(
&self,
crypto: C,
random: &[u8],
target: &[u8],
) -> Result<(), Error> {
let mut mac = crypto.hmac(self.ipk.op_key())?;
mac.update(random)?;
mac.update(CertRef::new(TLVElement::new(self.root_ca())).pubkey()?)?;
mac.update(&self.fabric_id.to_le_bytes())?;
mac.update(&self.node_id.to_le_bytes())?;
let mut id = MaybeUninit::<Hash>::uninit(); // TODO MEDIUM BUFFER
let id = id.init_with(Hash::init());
mac.finish(id)?;
if id.access() == target {
Ok(())
} else {
Err(ErrorCode::NotFound.into())
}
}
/// Compute the destination identifier for a target node on this fabric.
///
/// Used by the CASE initiator to build Sigma1 (spec).
/// destinationMessage = initiatorRandom || rootPublicKey || fabricId(LE) || nodeId(LE)
/// destinationIdentifier = Crypto_HMAC(key=IPK, message=destinationMessage)
///
/// # Arguments
/// - `target_node_id`: The node ID of the destination (peer) node, NOT the local node.
pub fn compute_dest_id<C: Crypto>(
&self,
crypto: C,
random: &[u8],
target_node_id: u64,
out: &mut Hash,
) -> Result<(), Error> {
let mut mac = crypto.hmac(self.ipk.op_key())?;
mac.update(random)?;
mac.update(CertRef::new(TLVElement::new(self.root_ca())).pubkey()?)?;
mac.update(&self.fabric_id.to_le_bytes())?;
mac.update(&target_node_id.to_le_bytes())?;
mac.finish(out)?;
Ok(())
}
/// Return the secret key of the fabric
pub fn secret_key(&self) -> CanonPkcSecretKeyRef<'_> {
self.secret_key.reference()
}
/// Return the fabric's node ID
pub fn node_id(&self) -> u64 {
self.node_id
}
/// Return the fabric's fabric ID
pub fn fabric_id(&self) -> u64 {
self.fabric_id
}
/// Return the fabric's local index
pub fn fab_idx(&self) -> NonZeroU8 {
self.fab_idx
}
/// Return the fabric's compressed fabric ID
pub fn compressed_fabric_id(&self) -> u64 {
self.compressed_fabric_id
}
/// Return the fabric's Vendor ID
pub fn vendor_id(&self) -> u16 {
self.vendor_id
}
/// Return the fabric's label
pub fn label(&self) -> &str {
&self.label
}
/// Return the fabric's Root CA in encoded TLV form
///
/// Use `CertRef` to decode on the fly
pub fn root_ca(&self) -> &[u8] {
&self.root_ca
}
/// Return the fabric's ICAC in encoded TLV form
///
/// Use `CertRef` to decode on the fly.
///
/// Note that this method might return an empty slice,
/// which indicates that this fabric does not have an ICAC.
/// (The shared `icac_or_vvsc` slot may instead hold a VVSC; see
/// `vvsc()`.)
pub fn icac(&self) -> &[u8] {
if self.vvsc_set {
&[]
} else {
&self.icac_or_vvsc
}
}
/// Return the fabric's NOC
pub fn noc(&self) -> &[u8] {
&self.noc
}
/// Return the fabric's IPK
pub fn ipk(&self) -> &KeySet {
&self.ipk
}
/// Return the fabric's groups, or an empty group state if this fabric was
/// persisted before the `groups` field existed (see [`Fabric::groups`]).
#[cfg(feature = "groups")]
pub fn groups(&self) -> &Groups {
self.groups.value()
}
/// Return a mutable reference to the fabric's groups, materializing empty
/// group state on first access if it was absent.
#[cfg(feature = "groups")]
pub fn groups_mut(&mut self) -> &mut Groups {
self.groups.value_mut()
}
/// Return the fabric's VVSC bytes (Matter Core spec).
/// Empty when `SetVIDVerificationStatement` has never been called with
/// a non-empty VVSC for this fabric, or when the fabric instead carries
/// an ICAC (see `icac()`) — VVSC and ICAC share storage and are
/// mutually exclusive per spec.
pub fn vvsc(&self) -> &[u8] {
if self.vvsc_set {
&self.icac_or_vvsc
} else {
&[]
}
}
/// Return the fabric's VID Verification Statement bytes (Matter Core
/// spec). Either empty (not set) or
/// exactly `VID_VERIFICATION_STATEMENT_LEN` bytes.
pub fn vid_verification_statement(&self) -> &[u8] {
&self.vid_verification_statement
}
/// Apply a `SetVIDVerificationStatement` mutation to the fabric. Each
/// field is `Some(slice)` for "replace with this value" (where an
/// empty slice clears the value), or `None` for "leave unchanged".
/// The caller is responsible for spec-level validation (size limits,
/// VVSC vs ICAC mutual exclusion, "all fields absent" → INVALID_COMMAND,
/// VendorID range, …); this method only enforces the storage
/// invariants (`Vec` capacity).
pub fn set_vid_verification(
&mut self,
vendor_id: Option<u16>,
vid_verification_statement: Option<&[u8]>,
vvsc: Option<&[u8]>,
) -> Result<(), Error> {
if let Some(vid) = vendor_id {
self.vendor_id = vid;
}
if let Some(vvs) = vid_verification_statement {
self.vid_verification_statement.clear();
self.vid_verification_statement
.extend_from_slice(vvs)
.map_err(|_| ErrorCode::BufferTooSmall)?;
}
if let Some(v) = vvsc {
// VVSC and ICAC share `icac_or_vvsc`. Clearing the VVSC must
// not stomp on an existing ICAC: per spec the
// two never coexist on the same fabric, so an empty-VVSC
// request against a fabric that holds an ICAC is a no-op
// here. The cluster handler still rejects a *non-empty* VVSC
// against such a fabric upstream.
if !v.is_empty() {
self.icac_or_vvsc.clear();
self.icac_or_vvsc
.extend_from_slice(v)
.map_err(|_| ErrorCode::BufferTooSmall)?;
self.vvsc_set = true;
} else if self.vvsc_set {
self.icac_or_vvsc.clear();
self.vvsc_set = false;
}
}
Ok(())
}
/// Return the ACL entries of the fabric
pub fn acl(&self) -> &[AclEntry] {
&self.acl
}
/// Return an iterator over the ACL entries of the fabric
pub fn acl_iter(&self) -> impl Iterator<Item = &AclEntry> {
self.acl.iter()
}
/// Add a new ACL entry to the fabric.
///
/// Return the index of the added entry.
pub fn acl_add(&mut self, mut entry: AclEntry) -> Result<usize, Error> {
if entry.auth_mode() == AuthMode::Pase {
// Reserved for future use
Err(ErrorCode::ConstraintError)?;
}
// Overwrite the fabric index with our accessing fabric index
entry.fab_idx = Some(self.fab_idx);
self.acl
.push(entry)
.map_err(|_| ErrorCode::ResourceExhausted)?;
Ok(self.acl.len() - 1)
}
/// Add a new ACL entry to the fabric using the supplied initializer.
///
/// Return the index of the added entry.
pub fn acl_add_init<I>(&mut self, init: I) -> Result<usize, Error>
where
I: Init<AclEntry, Error>,
{
self.acl
.push_init(init, || ErrorCode::ResourceExhausted.into())?;
let idx = self.acl.len() - 1;
if self.acl[idx].auth_mode() == AuthMode::Pase {
// Reserved for future use
self.acl.pop();
Err(ErrorCode::ConstraintError)?;
}
let entry = &mut self.acl[idx];
// Overwrite the fabric index with our accessing fabric index
entry.fab_idx = Some(self.fab_idx);
Ok(idx)
}
/// Update an existing ACL entry in the fabric
pub fn acl_update(&mut self, idx: usize, mut entry: AclEntry) -> Result<(), Error> {
if self.acl.len() <= idx {
return Err(ErrorCode::NotFound.into());
}
// Overwrite the fabric index with our accessing fabric index
entry.fab_idx = Some(self.fab_idx);
self.acl[idx] = entry;
Ok(())
}
/// Update an existing ACL entry in the fabric using the supplied initializer
pub fn acl_update_init<I>(&mut self, idx: usize, init: I) -> Result<(), Error>
where
I: Init<AclEntry, Error>,
{
if self.acl.len() <= idx {
return Err(ErrorCode::NotFound.into());
}
// TODO: Needs #214
let mut entry = MaybeUninit::uninit();
let entry = entry.try_init_with(init)?.clone();
self.acl[idx] = entry;
// Overwrite the fabric index with our accessing fabric index
self.acl[idx].fab_idx = Some(self.fab_idx);
Ok(())
}
/// Remove an ACL entry from the fabric
pub fn acl_remove(&mut self, idx: usize) -> Result<(), Error> {
if self.acl.len() <= idx {
return Err(ErrorCode::NotFound.into());
}
self.acl.remove(idx);
Ok(())
}
/// Remove all ACL entries from the fabric
pub fn acl_remove_all(&mut self) {
// pub for tests
self.acl.clear();
}
/// Check if the fabric allows the given access request
///
/// Note that the fabric index in the access request needs to be checked before that.
/// `aux_acl_enabled` conveys whether the node advertises the Access Control
/// cluster's `AUXILIARY` feature - see `AclEntry::allow`.
fn allow(&self, req: &AccessReq, aux_acl_enabled: bool) -> bool {
for e in &self.acl {
if e.allow(req, aux_acl_enabled) {
return true;
}
}
debug!(
"ACL Disallow for subjects {} fab idx {}",
req.accessor().subjects(),
req.accessor().fab_idx
);
false
}
/// The compressed fabric ID of the fabric with root public key
/// `root_pubkey` and fabric ID `fabric_id`: what its nodes advertise over
/// mDNS.
pub fn compute_compressed_fabric_id<C: Crypto>(
crypto: C,
root_pubkey: CanonPkcPublicKeyRef<'_>,
fabric_id: u64,
) -> u64 {
const COMPRESSED_FABRIC_ID_INFO: &[u8; 16] = &[
0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73, 0x73, 0x65, 0x64, 0x46, 0x61, 0x62, 0x72,
0x69, 0x63,
];
let mut compressed_fabric_id = CryptoSensitive::<{ COMPRESSED_FABRIC_ID_LEN }>::new();
unwrap!(unwrap!(crypto.kdf()).expand(
&fabric_id.to_be_bytes(),
root_pubkey.split::<1, { PKC_CANON_PUBLIC_KEY_LEN - 1 }>().1,
COMPRESSED_FABRIC_ID_INFO,
&mut compressed_fabric_id,
));
u64::from_be_bytes(*compressed_fabric_id.access())
}
}
cfg_if! {
if #[cfg(feature = "max-fabrics-32")] {
/// Max number of supported fabrics
pub const MAX_FABRICS: usize = 32;
} else if #[cfg(feature = "max-fabrics-16")] {
/// Max number of supported fabrics
pub const MAX_FABRICS: usize = 16;
} else if #[cfg(feature = "max-fabrics-8")] {
/// Max number of supported fabrics
pub const MAX_FABRICS: usize = 8;
} else if #[cfg(feature = "max-fabrics-7")] {
/// Max number of supported fabrics
pub const MAX_FABRICS: usize = 7;
} else if #[cfg(feature = "max-fabrics-6")] {
/// Max number of supported fabrics
pub const MAX_FABRICS: usize = 6;
} else if #[cfg(feature = "max-fabrics-5")] {
/// Max number of supported fabrics
pub const MAX_FABRICS: usize = 5;
} else if #[cfg(feature = "max-fabrics-4")] {
/// Max number of supported fabrics
pub const MAX_FABRICS: usize = 4;
} else if #[cfg(feature = "max-fabrics-3")] {
/// Max number of supported fabrics
pub const MAX_FABRICS: usize = 3;
} else if #[cfg(feature = "max-fabrics-2")] {
/// Max number of supported fabrics
pub const MAX_FABRICS: usize = 2;
} else if #[cfg(feature = "max-fabrics-1")] {
/// Max number of supported fabrics
pub const MAX_FABRICS: usize = 1;
} else { // Matter requires a minimum of 5 fabrics
/// Max number of supported fabrics
pub const MAX_FABRICS: usize = 5;
}
}
/// All fabrics
pub struct Fabrics {
fabrics: Vec<Fabric, MAX_FABRICS>,
/// The indices of the persisted fabrics that could not be loaded, one bit
/// each. Never reallocated: state kept for them outside of the fabric (CASE
/// resumption records, bindings, ...) would pass to the new fabric.
unloaded: [u8; 32],
/// The first index tried for the next added fabric. Indices are handed out
/// in increasing order, wrapping around after [`MAX_FAB_IDX`], so that the
/// index of a removed fabric is not reused soon.
next_fab_idx: NonZeroU8,
}
impl Default for Fabrics {
fn default() -> Self {
Self::new()
}
}
impl Fabrics {
/// Create a new Fabrics instance
#[inline(always)]
pub const fn new() -> Self {
Self {
fabrics: Vec::new(),
unloaded: [0; 32],
next_fab_idx: NonZeroU8::MIN,
}
}
/// Return an in-place-initializer for a Fabrics type
pub fn init() -> impl Init<Self> {
init!(Self {
fabrics <- Vec::init(),
unloaded: [0; 32],
next_fab_idx: NonZeroU8::MIN,
})
}
/// Remove all fabrics
pub fn reset(&mut self) {
self.fabrics.clear();
self.unloaded = [0; 32];
self.next_fab_idx = NonZeroU8::MIN;
}
/// Remove all fabrics from the provided BLOB store as well as from memory.
///
/// # Arguments
/// - `store`: the BLOB store to remove the fabrics from
/// - `buf`: a temporary buffer to use for removing the fabrics
pub fn reset_persist<S: KvBlobStore>(
&mut self,
mut store: S,
buf: &mut [u8],
) -> Result<(), Error> {
self.reset();
let mut result = Ok(());
for idx in 1..=255u8 {
result = result.and(store.remove(FABRIC_KEYS_START + idx as u16, buf));
}
result = result.and(store.remove(NEXT_FABRIC_INDEX_KEY, buf));
if result.is_ok() {
info!("Removed all fabrics from storage");
}
result
}
/// Load all fabrics from the provided BLOB store
///
/// # Arguments
/// - `store`: the BLOB store to load the fabrics from
/// - `buf`: a temporary buffer to use for loading the fabrics
pub fn load_persist<S: KvBlobStore>(
&mut self,
mut store: S,
buf: &mut [u8],
) -> Result<(), Error> {
self.reset();
for fab_idx in 1..=255u8 {
self.add_load(fab_idx, &mut store, buf)?;
}
let next_fab_idx = load_logged(&mut store, NEXT_FABRIC_INDEX_KEY, buf, |data| {
NonZeroU8::new(TLVElement::new(data).u8()?)
.filter(|fab_idx| fab_idx.get() <= MAX_FAB_IDX)
.ok_or(ErrorCode::Invalid.into())
});
self.next_fab_idx = match next_fab_idx {
Ok(Some(fab_idx)) => fab_idx,
// Not stored (e.g. by an older version), or unreadable: the one
// after the largest index taken
_ => Self::fab_idx_after(
(1..=MAX_FAB_IDX)
.rev()
.find(|fab_idx| self.is_taken(*fab_idx))
.unwrap_or(0),
),
};
Ok(())
}
/// Load the fabric with index `fab_idx` from `store`, if persisted.
///
/// A fabric that cannot be loaded is skipped, with its index kept reserved.
pub fn add_load<S: KvBlobStore>(
&mut self,
fab_idx: u8,
mut store: S,
buf: &mut [u8],
) -> Result<(), Error> {
let loaded = load_logged(
&mut store,
FABRIC_KEYS_START + fab_idx as u16,
buf,
|data| {
self.fabrics
.push_init(Fabric::init_from_tlv(TLVElement::new(data)), || {
TlvErrorCode::CapacityExceeded.into()
})
.map_err(Into::into)
},
);
match loaded {
Ok(Some(())) => {
let fabric = unwrap!(self.fabrics.last());
info!(
"Loaded fabric {} with ID {:x} from storage",
fabric.fab_idx(),
fabric.compressed_fabric_id()
);
}
Ok(None) => (),
Err(_) => self.unloaded[fab_idx as usize / 8] |= 1 << (fab_idx % 8),
}
Ok(())
}
/// Whether the index `fab_idx` is taken by a fabric, loaded or not.
fn is_taken(&self, fab_idx: u8) -> bool {
self.unloaded[fab_idx as usize / 8] & (1 << (fab_idx % 8)) != 0
|| self.iter().any(|fabric| fabric.fab_idx().get() == fab_idx)
}
/// The fabric index after `fab_idx` (or the first one, for 0).
fn fab_idx_after(fab_idx: u8) -> NonZeroU8 {
unwrap!(NonZeroU8::new(fab_idx % MAX_FAB_IDX + 1))
}
/// The first index tried for the next added fabric.
///
/// To be persisted with [`FabricPersist::store_next_fab_idx`] whenever a
/// fabric is committed to or removed from storage.
pub fn next_fab_idx(&self) -> NonZeroU8 {
self.next_fab_idx
}
/// Add a new fabric to the fabrics with the provided data and immediately updates it with the provided post-init updater.
///
/// This method is unlikely to be useful outside of tests.
///
/// If this operation succeeds, the fabric immediately becomes operational.
pub fn add_with_post_init<F>(&mut self, post_init: F) -> Result<&mut Fabric, Error>
where
F: FnOnce(&mut Fabric) -> Result<(), Error>,
{
let mut fab_idx = self.next_fab_idx;
while self.is_taken(fab_idx.get()) {
fab_idx = Self::fab_idx_after(fab_idx.get());
if fab_idx == self.next_fab_idx {
return Err(ErrorCode::ResourceExhausted.into());
}
}
self.fabrics.push_init(
Fabric::init(fab_idx)
.into_fallible::<Error>()
.chain(post_init),
|| ErrorCode::ResourceExhausted.into(),
)?;
self.next_fab_idx = Self::fab_idx_after(fab_idx.get());
let fabric = unwrap!(self.fabrics.last_mut());
Ok(fabric)
}
/// Add a new fabric to the fabrics with the provided data.
///
/// If this operation succeeds, the fabric immediately becomes operational.
#[allow(clippy::too_many_arguments)]
pub fn add<C: Crypto>(
&mut self,
crypto: C,
secret_key: CanonPkcSecretKeyRef<'_>,
root_ca: &[u8],
noc: &[u8],
icac: &[u8],
epoch_key: Option<CanonAeadKeyRef<'_>>,
vendor_id: u16,
case_admin_subject: u64,
) -> Result<&mut Fabric, Error> {
self.add_with_post_init(|fabric| {
fabric.update(
crypto,
Some(root_ca),
noc,
icac,
secret_key,
epoch_key,
Some(vendor_id),
Some(case_admin_subject),
)
})
}
/// Add a new fabric with an explicit ACL instead of the single admin entry
/// [`Fabrics::add`] seeds.
///
/// If this operation succeeds, the fabric immediately becomes operational.
#[allow(clippy::too_many_arguments)]
pub fn add_with_acl<C, I>(
&mut self,
crypto: C,
secret_key: CanonPkcSecretKeyRef<'_>,
root_ca: &[u8],
noc: &[u8],
icac: &[u8],
epoch_key: Option<CanonAeadKeyRef<'_>>,
vendor_id: u16,
acl: I,
) -> Result<&mut Fabric, Error>
where
C: Crypto,
I: IntoIterator<Item = Result<AclEntry, TlvError>>,
{
self.add_with_post_init(|fabric| {
fabric.update(
crypto,
Some(root_ca),
noc,
icac,
secret_key,
epoch_key,
Some(vendor_id),
None,
)?;
for entry in acl {
fabric.acl_add(entry?)?;
}
Ok(())
})
}
/// Update an existing fabric with the provided data (usually, as a result of an `UpdateNOC` IM command).
///
/// The fabric's existing root cert is preserved across this call —
/// `UpdateNOC` per Matter Core spec is not allowed
/// to change the root, and re-passing the bytes would force the
/// caller to take a (large) heap-less copy of `Fabric::root_ca`.
///
/// If this operation succeeds, the fabric immediately becomes operational.
/// Note however, that the caller is expected to remove all sessions associated with the fabric, as they would
/// contain invalid keys after the NOC update.
pub fn update<C: Crypto>(
&mut self,
crypto: C,
fab_idx: NonZeroU8,
secret_key: CanonPkcSecretKeyRef<'_>,
noc: &[u8],
icac: &[u8],
) -> Result<&mut Fabric, Error> {
let fabric = self.fabric_mut(fab_idx)?;
fabric.update(crypto, None, noc, icac, secret_key, None, None, None)?;
Ok(fabric)
}
pub fn update_label(&mut self, fab_idx: NonZeroU8, label: &str) -> Result<&mut Fabric, Error> {
if self.iter().any(|fabric| {
fabric.fab_idx != fab_idx && !fabric.label.is_empty() && fabric.label == label
}) {
return Err(ErrorCode::Invalid.into());
}
let fabric = self.fabric_mut(fab_idx)?;
fabric.label.clear();
fabric
.label
.push_str(label)
.map_err(|_| ErrorCode::ConstraintError)?;
Ok(fabric)
}
/// Remove a fabric from the fabrics
pub fn remove(&mut self, fab_idx: NonZeroU8) -> Result<(), Error> {
let _ = self.fabric(fab_idx)?;
self.fabrics.retain(|fabric| fabric.fab_idx != fab_idx);
Ok(())
}
/// Get a fabric that matches the provided destination ID
pub fn get_by_dest_id<C: Crypto>(
&self,
crypto: C,
random: &[u8],
target: &[u8],
) -> Option<&Fabric> {
self.iter()
.find(|fabric| fabric.is_dest_id(&crypto, random, target).is_ok())
}
/// Get a fabric by its local index
pub fn get(&self, fab_idx: NonZeroU8) -> Option<&Fabric> {
self.iter().find(|fabric| fabric.fab_idx == fab_idx)
}
/// Get a mutable fabric reference by its local index
pub fn get_mut(&mut self, fab_idx: NonZeroU8) -> Option<&mut Fabric> {
// pub for testing
self.fabrics
.iter_mut()
.find(|fabric| fabric.fab_idx == fab_idx)
}
/// Iterate over the fabrics
pub fn iter(&self) -> impl Iterator<Item = &Fabric> {
self.fabrics.iter()
}
/// Get a fabric by its local index
///
/// Returns an error if the fabric is not found
pub fn fabric(&self, fab_idx: NonZeroU8) -> Result<&Fabric, Error> {
self.get(fab_idx).ok_or(ErrorCode::NotFound.into())
}
/// Get a mutable fabric reference by its local index
///
/// Returns an error if the fabric is not found
pub fn fabric_mut(&mut self, fab_idx: NonZeroU8) -> Result<&mut Fabric, Error> {
self.get_mut(fab_idx).ok_or(ErrorCode::NotFound.into())
}
/// Check if the given access request should be allowed, based on all operational fabrics
/// and their ACLs
///
/// `aux_acl_enabled` conveys whether the node advertises the Access Control
/// cluster's `AUXILIARY` feature - see `AclEntry::allow`.
pub fn allow(&self, req: &AccessReq, aux_acl_enabled: bool) -> bool {
// PASE Sessions with no fabric index have implicit access grant,
// but only as long as the ACL list is empty
//
// As per the spec:
// The Access Control List is able to have an initial entry added because the Access Control Privilege
// Granting algorithm behaves as if, over a PASE commissioning channel during the commissioning
// phase, the following implicit Access Control Entry were present on the Commissionee (but not on
// the Commissioner):
// Access Control Cluster: {
// ACL: [
// 0: {
// // implicit entry only; does not explicitly exist!
// FabricIndex: 0, // not fabric-specific
// Privilege: Administer,
// AuthMode: PASE,
// Subjects: [],
// Targets: [] // entire node
// }
// ],
// Extension: []
// }
if req.accessor().auth_mode() == Some(AuthMode::Pase) {
return true;
}
let Ok(fab_idx) = req.accessor().fab_idx() else {
return false;
};
let Some(fabric) = self.get(fab_idx) else {
return false;
};
fabric.allow(req, aux_acl_enabled)
}
}
/// A utility for persisting a fabric in a `KvBlobStore` instance.
///
/// Like [`Persist`], it logs and ignores what it cannot persist, unless created
/// with [`FabricPersist::strict`].
pub struct FabricPersist<S>(Persist<S>);
impl<S> FabricPersist<S>
where
S: KvBlobStoreAccess,
{
/// Create a new `FabricPersist` with the given key-value store instance.
pub const fn new(kvb: S) -> Self {
Self(Persist::new(kvb))
}
/// Create a new `FabricPersist` with the given key-value store instance,
/// which returns the errors of what it cannot persist.
pub const fn strict(kvb: S) -> Self {
Self(Persist::strict(kvb))
}
/// Return a reference to the underlying `Persist` instance.
pub fn persist_mut(&mut self) -> &mut Persist<S> {
&mut self.0
}
/// Save the provided fabric in the persistent storage.
pub fn store(&mut self, fabric: &Fabric) -> Result<(), Error> {
self.0
.store_tlv(FABRIC_KEYS_START + fabric.fab_idx().get() as u16, fabric)
}
/// Remove the fabric with the given index from the persistent storage.
pub fn remove(&mut self, fab_idx: NonZeroU8) -> Result<(), Error> {
self.0.remove(FABRIC_KEYS_START + fab_idx.get() as u16)
}
/// Save [`Fabrics::next_fab_idx`] in the persistent storage.
pub fn store_next_fab_idx(&mut self, next_fab_idx: NonZeroU8) -> Result<(), Error> {
self.0.store_tlv(NEXT_FABRIC_INDEX_KEY, next_fab_idx.get())
}
/// Call at the end when finished with everything else
/// No-op for now
pub fn run(self) -> Result<(), Error> {
self.0.run()
}
}
#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
pub(crate) mod tests {
use core::mem::MaybeUninit;
use core::num::NonZeroU8;
use crate::acl::{AccessReq, AccessorSubjects, AclEntry, AuthMode, SubjectDescriptor, Target};
use crate::cert::gen::{CertGenerator, CertType, IssuerDN, SubjectDN, Validity, VALID_FOREVER};
use crate::cert::{CertRef, MAX_CERT_TLV_AND_ASN1_LEN};
use crate::crypto::test_only_crypto;
use crate::crypto::{
CanonAeadKeyRef, CanonPkcPublicKey, CanonPkcPublicKeyRef, CanonPkcSecretKey,
CanonPkcSecretKeyRef, Crypto, Hash, PublicKey, Rng, SecretKey, SigningSecretKey,
AEAD_CANON_KEY_LEN,
};
use crate::dm::{Access, Privilege};
use crate::error::{Error, ErrorCode};
use crate::im::GenericPath;
use crate::persist::{
KvBlobStore, KvBlobStoreAccess, MemKv, MemKvBlobStore, FABRIC_KEYS_START,
NEXT_FABRIC_INDEX_KEY,
};
use crate::tlv::TLVElement;
use crate::utils::init::{Init, InitMaybeUninit, IntoFallibleInit};
use super::{
Fabric, FabricPersist, Fabrics, MAX_FABRICS, MAX_FAB_IDX, VID_VERIFICATION_STATEMENT_LEN,
};
/// A freshly minted, self-signed RCAC.
pub(crate) struct TestRcac {
pub(crate) key: CanonPkcSecretKey,
pub(crate) cert: std::vec::Vec<u8>,
}
/// A freshly minted NOC, chained (directly or via an ICAC) to some RCAC.
pub(crate) struct TestNoc {
pub(crate) key: CanonPkcSecretKey,
pub(crate) cert: std::vec::Vec<u8>,
}
/// Write the canonical public key of a secret key into `out`.
pub(crate) fn pubkey_of<C: Crypto>(
crypto: &C,
key: CanonPkcSecretKeyRef<'_>,
) -> CanonPkcPublicKey {
let mut out = CanonPkcPublicKey::new();
crypto
.secret_key(key)
.unwrap()
.pub_key()
.unwrap()
.write_canon(&mut out)
.unwrap();
out
}
/// Mint a self-signed RCAC for `fabric_id` with subject CA ID `rcac_id`.
pub(crate) fn mint_rcac<C: Crypto>(crypto: &C, fabric_id: u64, rcac_id: u64) -> TestRcac {
let rcac_secret_key = crypto.generate_secret_key().unwrap();
let mut rcac_pubkey = CanonPkcPublicKey::new();
rcac_secret_key
.pub_key()
.unwrap()
.write_canon(&mut rcac_pubkey)
.unwrap();
let mut buf = [0u8; MAX_CERT_TLV_AND_ASN1_LEN];
let len = CertGenerator::new(&mut buf)
.generate(
crypto,
CertType::Rcac,
&[0x01],
VALID_FOREVER,
SubjectDN {
node_id: None,
fabric_id: Some(fabric_id),
cat_ids: &[],
ca_id: Some(rcac_id),
},
IssuerDN {
ca_id: None,
fabric_id: None,
is_rcac: false,
},
rcac_pubkey.reference(),
None,
&rcac_secret_key,
)
.unwrap();
let mut key = CanonPkcSecretKey::new();
rcac_secret_key.write_canon(&mut key).unwrap();
TestRcac {
key,
cert: buf[..len].to_vec(),
}
}
/// Mint an ICAC signed by `rcac`.
pub(crate) fn mint_icac<C: Crypto>(crypto: &C, rcac: &TestRcac) -> TestRcac {
let rcac_cert = CertRef::new(TLVElement::new(&rcac.cert));
let rcac_pubkey = rcac_cert.pubkey().unwrap().try_into().unwrap();
let rcac_id = rcac_cert.get_ca_id().unwrap();
let fabric_id = rcac_cert.get_fabric_id().unwrap();
// A random ICAC ID, as an issuer of ICACs would use
let mut icac_id = [0u8; 8];
crypto.rand().unwrap().fill_bytes(&mut icac_id);
let icac_secret_key = crypto.generate_secret_key().unwrap();
let mut icac_pubkey = CanonPkcPublicKey::new();
icac_secret_key
.pub_key()
.unwrap()
.write_canon(&mut icac_pubkey)
.unwrap();
let rcac_secret_key = crypto.secret_key(rcac.key.reference()).unwrap();
let mut buf = [0u8; MAX_CERT_TLV_AND_ASN1_LEN];
let len = CertGenerator::new(&mut buf)
.generate(
crypto,
CertType::Icac,
&[0x01],
VALID_FOREVER,
SubjectDN {
node_id: None,
fabric_id: Some(fabric_id),
cat_ids: &[],
ca_id: Some(u64::from_be_bytes(icac_id)),
},
IssuerDN {
ca_id: Some(rcac_id),
fabric_id: Some(fabric_id),
is_rcac: true,
},
icac_pubkey.reference(),
Some(rcac_pubkey),
&rcac_secret_key,
)
.unwrap();
let mut key = CanonPkcSecretKey::new();
icac_secret_key.write_canon(&mut key).unwrap();
TestRcac {
key,
cert: buf[..len].to_vec(),
}
}
/// Mint a NOC for `node_id` carrying `noc_pubkey`, signed by `issuer`
/// (an RCAC when `issuer_is_rcac`, an ICAC otherwise). The fabric ID and
/// the issuer CA ID are taken from the issuer certificate.
pub(crate) fn mint_noc_for_pubkey<C: Crypto>(
crypto: &C,
issuer: &TestRcac,
issuer_is_rcac: bool,
noc_pubkey: CanonPkcPublicKeyRef<'_>,
node_id: u64,
) -> std::vec::Vec<u8> {
let issuer_ref = CertRef::new(TLVElement::new(&issuer.cert));
let fabric_id = issuer_ref.get_fabric_id().unwrap();
let ca_id = issuer_ref.get_ca_id().unwrap();
let issuer_pubkey = pubkey_of(crypto, issuer.key.reference());
let signing_key = crypto.secret_key(issuer.key.reference()).unwrap();
let mut buf = [0u8; MAX_CERT_TLV_AND_ASN1_LEN];
let len = CertGenerator::new(&mut buf)
.generate(
crypto,
CertType::Noc,
&[0x02],
VALID_FOREVER,
SubjectDN {
node_id: Some(node_id),
fabric_id: Some(fabric_id),
cat_ids: &[],
ca_id: None,
},
IssuerDN {
ca_id: Some(ca_id),
fabric_id: Some(fabric_id),
is_rcac: issuer_is_rcac,
},
noc_pubkey,
Some(issuer_pubkey.reference()),
&signing_key,
)
.unwrap();
buf[..len].to_vec()
}
/// Mint a NOC with a fresh keypair for `node_id`, signed by `issuer`.
pub(crate) fn mint_noc<C: Crypto>(
crypto: &C,
issuer: &TestRcac,
issuer_is_rcac: bool,
node_id: u64,
) -> TestNoc {
let noc_secret_key = crypto.generate_secret_key().unwrap();
let mut key = CanonPkcSecretKey::new();
noc_secret_key.write_canon(&mut key).unwrap();
let cert = mint_noc_for_pubkey(
crypto,
issuer,
issuer_is_rcac,
pubkey_of(crypto, key.reference()).reference(),
node_id,
);
TestNoc { key, cert }
}
/// The IPK epoch key used by every fabric these tests add.
pub(crate) const TEST_IPK: [u8; AEAD_CANON_KEY_LEN] = [0x5a; AEAD_CANON_KEY_LEN];
/// Add an RCAC-direct fabric for (`fabric_id`, `node_id`) with vendor ID
/// `0x8000` and `node_id` as the CASE admin subject. Returns its index.
pub(crate) fn add_fabric<C: Crypto>(
crypto: &C,
fabrics: &mut Fabrics,
fabric_id: u64,
node_id: u64,
) -> NonZeroU8 {
let rcac = mint_rcac(crypto, fabric_id, 0x10 + fabric_id);
let noc = mint_noc(crypto, &rcac, true, node_id);
fabrics
.add(
crypto,
noc.key.reference(),
&rcac.cert,
&noc.cert,
&[],
Some(CanonAeadKeyRef::new(&TEST_IPK)),
0x8000,
node_id,
)
.unwrap()
.fab_idx()
}
fn idx(i: u8) -> NonZeroU8 {
NonZeroU8::new(i).unwrap()
}
/// The Matter spec's "Compressed Fabric Identifier" example: this root
/// public key and fabric ID compress to `87e1b004e235a130`.
#[test]
fn compressed_fabric_id_matches_spec_example() {
const ROOT_PUBKEY: [u8; 65] = [
0x04, 0x4a, 0x9f, 0x42, 0xb1, 0xca, 0x48, 0x40, 0xd3, 0x72, 0x92, 0xbb, 0xc7, 0xf6,
0xa7, 0xe1, 0x1e, 0x22, 0x20, 0x0c, 0x97, 0x6f, 0xc9, 0x00, 0xdb, 0xc9, 0x8a, 0x7a,
0x38, 0x3a, 0x64, 0x1c, 0xb8, 0x25, 0x4a, 0x2e, 0x56, 0xd4, 0xe2, 0x95, 0xa8, 0x47,
0x94, 0x3b, 0x4e, 0x38, 0x97, 0xc4, 0xa7, 0x73, 0xe9, 0x30, 0x27, 0x7b, 0x4d, 0x9f,
0xbe, 0xde, 0x8a, 0x05, 0x26, 0x86, 0xbf, 0xac, 0xfa,
];
let crypto = test_only_crypto();
let compressed = Fabric::compute_compressed_fabric_id(
&crypto,
CanonPkcPublicKeyRef::new(&ROOT_PUBKEY),
0x2906_c908_d115_d362,
);
assert_eq!(compressed, 0x87e1_b004_e235_a130);
}
/// Lock the on-disk TLV tag layout of the fields whose position is sensitive
/// to the `groups` feature. A released `rs-matter` persists `groups` at
/// context tag 13 and `vid_verification_statement` at 14; gating `groups` in
/// or out must not move either. Serializing an (empty) `Fabric` and checking
/// the raw tags catches any future reorder that would silently corrupt
/// existing persisted fabrics.
#[test]
fn fabric_tlv_tag_layout_is_stable() {
use crate::tlv::{TLVElement, TLVTag, ToTLV};
use crate::utils::init::InitMaybeUninit;
use crate::utils::storage::WriteBuf;
let mut fabric = core::mem::MaybeUninit::<Fabric>::uninit();
let fabric = fabric.init_with(Fabric::init(unwrap!(NonZeroU8::new(1))));
let mut buf = [0u8; 512];
let mut wb = WriteBuf::new(&mut buf);
fabric.to_tlv(&TLVTag::Anonymous, &mut wb).unwrap();
let len = wb.get_tail();
let root = TLVElement::new(&buf[..len]).structure().unwrap();
// `find_ctx` returns an EMPTY element (not an error) when the tag is
// absent, so presence is `!is_empty()` and absence is `is_empty()`.
// `acl` (the last always-present field before the sensitive pair) is at 12.
assert!(
!root.find_ctx(12).unwrap().is_empty(),
"acl must stay at TLV tag 12"
);
// `vid_verification_statement` must always be at context tag 14.
assert!(
!root.find_ctx(14).unwrap().is_empty(),
"vid_verification_statement must stay at TLV tag 14"
);
// With `groups` compiled in it must be at tag 13; compiled out, tag 13 is
// simply absent (and a reader defaults it).
#[cfg(feature = "groups")]
assert!(
!root.find_ctx(13).unwrap().is_empty(),
"groups must be at TLV tag 13 when compiled in"
);
#[cfg(not(feature = "groups"))]
assert!(
root.find_ctx(13).unwrap().is_empty(),
"no field should occupy tag 13 when groups is compiled out"
);
}
/// Verify that `compute_dest_id` and `is_dest_id` agree: the hash output by
/// `compute_dest_id` must be accepted by `is_dest_id` on the same fabric with
/// the same random nonce.
///
/// Uses runtime-generated certs (via `CertGenerator`) with a real keypair
/// so the fabric is in a valid state — the secret key matches the NOC's public key.
#[test]
fn test_compute_dest_id_matches_is_dest_id() {
let crypto = test_only_crypto();
let fabric_id: u64 = 1;
let rcac_id: u64 = 1;
let node_id: u64 = 100;
// Generate RCAC keypair and build self-signed RCAC
let rcac_secret_key = crypto.generate_secret_key().unwrap();
let mut rcac_pubkey_canon = crate::crypto::CanonPkcPublicKey::new();
rcac_secret_key
.pub_key()
.unwrap()
.write_canon(&mut rcac_pubkey_canon)
.unwrap();
let validity = Validity {
not_before: 0,
not_after: 0,
};
let mut rcac_buf = [0u8; MAX_CERT_TLV_AND_ASN1_LEN];
let rcac_len = CertGenerator::new(&mut rcac_buf)
.generate(
&crypto,
CertType::Rcac,
&[0x01],
validity,
SubjectDN {
node_id: None,
fabric_id: Some(fabric_id),
cat_ids: &[],
ca_id: Some(rcac_id),
},
IssuerDN {
ca_id: None,
fabric_id: None,
is_rcac: false,
},
rcac_pubkey_canon.reference(),
None,
&rcac_secret_key,
)
.unwrap();
// Generate NOC keypair and build NOC signed by RCAC
let noc_secret_key = crypto.generate_secret_key().unwrap();
let mut noc_pubkey_canon = crate::crypto::CanonPkcPublicKey::new();
noc_secret_key
.pub_key()
.unwrap()
.write_canon(&mut noc_pubkey_canon)
.unwrap();
let mut noc_secret_key_canon = CanonPkcSecretKey::new();
noc_secret_key
.write_canon(&mut noc_secret_key_canon)
.unwrap();
let mut noc_buf = [0u8; MAX_CERT_TLV_AND_ASN1_LEN];
let noc_len = CertGenerator::new(&mut noc_buf)
.generate(
&crypto,
CertType::Noc,
&[0x02],
validity,
SubjectDN {
node_id: Some(node_id),
fabric_id: Some(fabric_id),
cat_ids: &[],
ca_id: None,
},
IssuerDN {
ca_id: Some(rcac_id),
fabric_id: Some(fabric_id),
is_rcac: true,
},
noc_pubkey_canon.reference(),
Some(rcac_pubkey_canon.reference()),
&rcac_secret_key,
)
.unwrap();
// Build fabric with real certs and matching secret key
let epoch_key = [0x5a_u8; AEAD_CANON_KEY_LEN];
let mut fabrics = Fabrics::new();
fabrics
.add(
&crypto,
noc_secret_key_canon.reference(),
&rcac_buf[..rcac_len],
&noc_buf[..noc_len],
&[], // no ICAC
Some(CanonAeadKeyRef::new(&epoch_key)),
0x8000,
node_id,
)
.expect("Fabrics::add should succeed");
let fab_idx = core::num::NonZeroU8::new(1).unwrap();
let fabric = fabrics
.get(fab_idx)
.expect("fabric at index 1 should exist");
let random = [0xABu8; 32];
// Compute the destination ID (targeting this fabric's own node).
let mut dest_id = MaybeUninit::<Hash>::uninit();
let dest_id = dest_id.init_with(Hash::init());
fabric
.compute_dest_id(&crypto, &random, fabric.node_id(), dest_id)
.expect("compute_dest_id should not fail");
// is_dest_id must accept the computed value.
fabric
.is_dest_id(&crypto, &random, dest_id.access())
.expect("is_dest_id should accept hash produced by compute_dest_id");
}
#[test]
fn add_assigns_sequential_indices_and_iter_is_insertion_ordered() {
let crypto = test_only_crypto();
let mut fabrics = Fabrics::new();
assert_eq!(fabrics.iter().count(), 0);
let a = add_fabric(&crypto, &mut fabrics, 0xa, 0x1a);
let b = add_fabric(&crypto, &mut fabrics, 0xb, 0x1b);
let c = add_fabric(&crypto, &mut fabrics, 0xc, 0x1c);
assert_eq!((a, b, c), (idx(1), idx(2), idx(3)));
let order: std::vec::Vec<_> = fabrics.iter().map(|f| f.fab_idx().get()).collect();
assert_eq!(order, [1, 2, 3]);
}
#[test]
fn add_populates_fabric_fields() {
let crypto = test_only_crypto();
let mut fabrics = Fabrics::new();
let rcac = mint_rcac(&crypto, 0xfab, 0x77);
let noc = mint_noc(&crypto, &rcac, true, 0x1234);
let fabric = fabrics
.add(
&crypto,
noc.key.reference(),
&rcac.cert,
&noc.cert,
&[],
Some(CanonAeadKeyRef::new(&TEST_IPK)),
0xfff1,
0x1234,
)
.unwrap();
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.cert.as_slice());
assert!(fabric.icac().is_empty());
assert!(fabric.vvsc().is_empty());
assert!(fabric.vid_verification_statement().is_empty());
assert_eq!(fabric.label(), "");
assert_eq!(fabric.secret_key().access(), noc.key.access());
// The compressed fabric ID is derived from the root pubkey + fabric ID
let root_cert = CertRef::new(TLVElement::new(&rcac.cert));
let root_pubkey = root_cert.pubkey().unwrap();
assert_eq!(
fabric.compressed_fabric_id(),
Fabric::compute_compressed_fabric_id(&crypto, root_pubkey.try_into().unwrap(), 0xfab)
);
// The IPK epoch key is stored and an operational key derived from it
assert_eq!(fabric.ipk().epoch_key().access(), &TEST_IPK);
assert_ne!(fabric.ipk().op_key().access(), &[0u8; AEAD_CANON_KEY_LEN]);
// A single CASE admin entry for the admin subject is seeded
let mut expected = AclEntry::new(Some(idx(1)), Privilege::ADMIN, AuthMode::Case);
expected.add_subject(0x1234).unwrap();
assert_eq!(fabric.acl(), &[expected]);
}
#[test]
fn add_with_icac_stores_icac() {
let crypto = test_only_crypto();
let mut fabrics = Fabrics::new();
let rcac = mint_rcac(&crypto, 0xfab, 0x77);
let icac = mint_icac(&crypto, &rcac);
let noc = mint_noc(&crypto, &icac, false, 0x1234);
let fabric = fabrics
.add(
&crypto,
noc.key.reference(),
&rcac.cert,
&noc.cert,
&icac.cert,
Some(CanonAeadKeyRef::new(&TEST_IPK)),
0xfff1,
0x1234,
)
.unwrap();
assert_eq!(fabric.icac(), icac.cert.as_slice());
assert!(fabric.vvsc().is_empty());
assert_eq!(fabric.fabric_id(), 0xfab);
}
#[test]
fn add_with_post_init_error_leaves_no_fabric() {
let mut fabrics = Fabrics::new();
let err = fabrics
.add_with_post_init(|_| Err(ErrorCode::Invalid.into()))
.unwrap_err();
assert_eq!(err.code(), ErrorCode::Invalid);
assert_eq!(fabrics.iter().count(), 0);
}
#[test]
fn add_fails_with_resource_exhausted_when_full() {
let crypto = test_only_crypto();
let mut fabrics = Fabrics::new();
for i in 0..MAX_FABRICS as u64 {
add_fabric(&crypto, &mut fabrics, 0x100 + i, 0x200 + i);
}
assert_eq!(fabrics.iter().count(), MAX_FABRICS);
let rcac = mint_rcac(&crypto, 0xfab, 0x77);
let noc = mint_noc(&crypto, &rcac, true, 0x1234);
let err = fabrics
.add(
&crypto,
noc.key.reference(),
&rcac.cert,
&noc.cert,
&[],
Some(CanonAeadKeyRef::new(&TEST_IPK)),
0xfff1,
0x1234,
)
.unwrap_err();
assert_eq!(err.code(), ErrorCode::ResourceExhausted);
assert_eq!(fabrics.iter().count(), MAX_FABRICS);
}
#[test]
fn remove_drops_fabric_and_next_add_uses_the_next_index() {
let crypto = test_only_crypto();
let mut fabrics = Fabrics::new();
add_fabric(&crypto, &mut fabrics, 0xa, 0x1a);
add_fabric(&crypto, &mut fabrics, 0xb, 0x1b);
add_fabric(&crypto, &mut fabrics, 0xc, 0x1c);
fabrics.remove(idx(2)).unwrap();
assert!(fabrics.get(idx(2)).is_none());
assert_eq!(
fabrics.fabric(idx(2)).unwrap_err().code(),
ErrorCode::NotFound
);
assert_eq!(
fabrics.remove(idx(2)).unwrap_err().code(),
ErrorCode::NotFound
);
let order: std::vec::Vec<_> = fabrics.iter().map(|f| f.fab_idx().get()).collect();
assert_eq!(order, [1, 3]);
// Freed indices are not reused, the largest one included
assert_eq!(add_fabric(&crypto, &mut fabrics, 0xd, 0x1d), idx(4));
fabrics.remove(idx(4)).unwrap();
assert_eq!(add_fabric(&crypto, &mut fabrics, 0xe, 0x1e), idx(5));
}
#[test]
fn indices_wrap_around_past_the_taken_ones() {
let mut store = MemKvBlobStore::default();
store
.store(FABRIC_KEYS_START + 1, &[0xff], &mut [])
.unwrap();
let kv = MemKv::new(store);
FabricPersist::new(&kv)
.store_next_fab_idx(idx(MAX_FAB_IDX))
.unwrap();
let mut fabrics = load_all(&kv);
assert_eq!(fabrics.next_fab_idx(), idx(MAX_FAB_IDX));
let mut add = || fabrics.add_with_post_init(|_| Ok(())).unwrap().fab_idx();
assert_eq!(add(), idx(MAX_FAB_IDX));
// Index 1 is kept by the fabric that could not be loaded
assert_eq!(add(), idx(2));
}
#[test]
fn get_and_fabric_accessors_agree() {
let crypto = test_only_crypto();
let mut fabrics = Fabrics::new();
add_fabric(&crypto, &mut fabrics, 0xa, 0x1a);
add_fabric(&crypto, &mut fabrics, 0xb, 0x1b);
assert_eq!(fabrics.get(idx(2)).unwrap().fabric_id(), 0xb);
assert_eq!(fabrics.get_mut(idx(2)).unwrap().fabric_id(), 0xb);
assert_eq!(fabrics.fabric(idx(1)).unwrap().fabric_id(), 0xa);
assert_eq!(fabrics.fabric_mut(idx(1)).unwrap().fabric_id(), 0xa);
assert!(fabrics.get(idx(3)).is_none());
assert!(fabrics.get_mut(idx(3)).is_none());
assert_eq!(
fabrics.fabric(idx(3)).unwrap_err().code(),
ErrorCode::NotFound
);
assert_eq!(
fabrics.fabric_mut(idx(3)).unwrap_err().code(),
ErrorCode::NotFound
);
}
#[test]
fn update_replaces_noc_and_key_but_keeps_root_acl_and_label() {
let crypto = test_only_crypto();
let mut fabrics = Fabrics::new();
let rcac = mint_rcac(&crypto, 0xfab, 0x77);
let icac = mint_icac(&crypto, &rcac);
let noc = mint_noc(&crypto, &icac, false, 0x1234);
let fab_idx = fabrics
.add(
&crypto,
noc.key.reference(),
&rcac.cert,
&noc.cert,
&icac.cert,
Some(CanonAeadKeyRef::new(&TEST_IPK)),
0xfff1,
0x1234,
)
.unwrap()
.fab_idx();
fabrics.update_label(fab_idx, "home").unwrap();
let fabric = fabrics.get_mut(fab_idx).unwrap();
fabric
.set_vid_verification(None, None, Some(&[0xaa; 40]))
.unwrap();
assert!(!fabric.vvsc().is_empty());
let old_compressed = fabric.compressed_fabric_id();
let old_acl = fabric.acl().to_vec();
// A new NOC for a different node ID, signed directly by the RCAC
let new_noc = mint_noc(&crypto, &rcac, true, 0x5678);
let fabric = fabrics
.update(
&crypto,
fab_idx,
new_noc.key.reference(),
&new_noc.cert,
&[],
)
.unwrap();
assert_eq!(fabric.node_id(), 0x5678);
assert_eq!(fabric.fabric_id(), 0xfab);
assert_eq!(fabric.noc(), new_noc.cert.as_slice());
assert_eq!(fabric.secret_key().access(), new_noc.key.access());
assert_eq!(fabric.root_ca(), rcac.cert.as_slice());
assert_eq!(fabric.compressed_fabric_id(), old_compressed);
assert_eq!(fabric.vendor_id(), 0xfff1);
assert_eq!(fabric.label(), "home");
assert_eq!(fabric.acl(), old_acl.as_slice());
assert_eq!(fabric.ipk().epoch_key().access(), &TEST_IPK);
// The cert chain is replaced wholesale: ICAC gone, staged VVSC gone
assert!(fabric.icac().is_empty());
assert!(fabric.vvsc().is_empty());
assert_eq!(
fabrics
.update(&crypto, idx(9), new_noc.key.reference(), &new_noc.cert, &[])
.unwrap_err()
.code(),
ErrorCode::NotFound
);
}
#[test]
fn update_label_rejects_duplicates_and_overlong_labels() {
let crypto = test_only_crypto();
let mut fabrics = Fabrics::new();
add_fabric(&crypto, &mut fabrics, 0xa, 0x1a);
add_fabric(&crypto, &mut fabrics, 0xb, 0x1b);
assert_eq!(
fabrics.update_label(idx(1), "home").unwrap().label(),
"home"
);
// Re-labelling the same fabric with its own label is fine
assert_eq!(
fabrics.update_label(idx(1), "home").unwrap().label(),
"home"
);
// Another fabric may not take a label already in use
assert_eq!(
fabrics.update_label(idx(2), "home").unwrap_err().code(),
ErrorCode::Invalid
);
assert_eq!(fabrics.get(idx(2)).unwrap().label(), "");
// Empty labels never conflict
assert_eq!(fabrics.update_label(idx(2), "").unwrap().label(), "");
assert_eq!(fabrics.update_label(idx(1), "").unwrap().label(), "");
// At most 32 bytes
assert_eq!(
fabrics
.update_label(idx(2), &"x".repeat(32))
.unwrap()
.label()
.len(),
32
);
assert_eq!(
fabrics
.update_label(idx(2), &"y".repeat(33))
.unwrap_err()
.code(),
ErrorCode::ConstraintError
);
assert_eq!(
fabrics.update_label(idx(7), "x").unwrap_err().code(),
ErrorCode::NotFound
);
}
#[test]
fn get_by_dest_id_finds_only_the_matching_fabric() {
let crypto = test_only_crypto();
let mut fabrics = Fabrics::new();
add_fabric(&crypto, &mut fabrics, 0xa, 0x1a);
add_fabric(&crypto, &mut fabrics, 0xb, 0x1b);
let random = [0x42u8; 32];
let mut dest_id = Hash::new();
fabrics
.get(idx(2))
.unwrap()
.compute_dest_id(&crypto, &random, 0x1b, &mut dest_id)
.unwrap();
let found = fabrics
.get_by_dest_id(&crypto, &random, dest_id.access())
.unwrap();
assert_eq!(found.fab_idx(), idx(2));
// A different initiator random yields a different destination ID
let other_random = [0x43u8; 32];
assert!(fabrics
.get_by_dest_id(&crypto, &other_random, dest_id.access())
.is_none());
// ...and so does a destination ID computed for some other node
let mut other_dest_id = Hash::new();
fabrics
.get(idx(2))
.unwrap()
.compute_dest_id(&crypto, &random, 0x1c, &mut other_dest_id)
.unwrap();
assert!(fabrics
.get_by_dest_id(&crypto, &random, other_dest_id.access())
.is_none());
}
#[test]
fn acl_add_update_remove() {
let crypto = test_only_crypto();
let mut fabrics = Fabrics::new();
let fab_idx = add_fabric(&crypto, &mut fabrics, 0xa, 0x1a);
let fabric = fabrics.get_mut(fab_idx).unwrap();
assert_eq!(fabric.acl().len(), 1);
// The entry's fabric index is overwritten with the fabric's own
let mut entry = AclEntry::new(Some(idx(9)), Privilege::VIEW, AuthMode::Case);
entry.add_subject(0x99).unwrap();
assert_eq!(fabric.acl_add(entry.clone()).unwrap(), 1);
entry.fab_idx = Some(fab_idx);
assert_eq!(fabric.acl()[1], entry);
assert_eq!(fabric.acl_iter().count(), 2);
// PASE entries are reserved
assert_eq!(
fabric
.acl_add(AclEntry::new(None, Privilege::VIEW, AuthMode::Pase))
.unwrap_err()
.code(),
ErrorCode::ConstraintError
);
assert_eq!(fabric.acl().len(), 2);
// Update in place, again forcing the fabric index
let mut updated = AclEntry::new(None, Privilege::OPERATE, AuthMode::Case);
updated
.add_target(Target::new(Some(1), None, None))
.unwrap();
fabric.acl_update(1, updated.clone()).unwrap();
updated.fab_idx = Some(fab_idx);
assert_eq!(fabric.acl()[1], updated);
assert_eq!(
fabric.acl_update(2, entry.clone()).unwrap_err().code(),
ErrorCode::NotFound
);
// Remove shifts the remaining entries down
fabric.acl_remove(0).unwrap();
assert_eq!(fabric.acl(), &[updated]);
assert_eq!(
fabric.acl_remove(1).unwrap_err().code(),
ErrorCode::NotFound
);
fabric.acl_remove_all();
assert!(fabric.acl().is_empty());
}
#[test]
fn acl_add_init_rejects_pase_entries() {
let crypto = test_only_crypto();
let mut fabrics = Fabrics::new();
let fab_idx = add_fabric(&crypto, &mut fabrics, 0xa, 0x1a);
let fabric = fabrics.get_mut(fab_idx).unwrap();
let count = fabric.acl().len();
assert_eq!(
fabric
.acl_add_init(
AclEntry::init(None, Privilege::VIEW, AuthMode::Pase).into_fallible::<Error>()
)
.unwrap_err()
.code(),
ErrorCode::ConstraintError
);
assert_eq!(fabric.acl().len(), count);
}
#[test]
fn acl_add_init_and_update_init() {
let crypto = test_only_crypto();
let mut fabrics = Fabrics::new();
let fab_idx = add_fabric(&crypto, &mut fabrics, 0xa, 0x1a);
let fabric = fabrics.get_mut(fab_idx).unwrap();
let i = fabric
.acl_add_init(
AclEntry::init(None, Privilege::MANAGE, AuthMode::Case)
.into_fallible::<Error>()
.chain(|e| e.add_subject(0x55)),
)
.unwrap();
assert_eq!(i, 1);
let mut expected = AclEntry::new(Some(fab_idx), Privilege::MANAGE, AuthMode::Case);
expected.add_subject(0x55).unwrap();
assert_eq!(fabric.acl()[1], expected);
// The entry's fabric index is overwritten with the fabric's own
fabric
.acl_update_init(
1,
AclEntry::init(Some(idx(9)), Privilege::VIEW, AuthMode::Case)
.into_fallible::<Error>()
.chain(|e| e.add_subject(0x66)),
)
.unwrap();
let mut expected = AclEntry::new(Some(fab_idx), Privilege::VIEW, AuthMode::Case);
expected.add_subject(0x66).unwrap();
assert_eq!(fabric.acl()[1], expected);
assert_eq!(
fabric
.acl_update_init(
5,
AclEntry::init(None, Privilege::VIEW, AuthMode::Case).into_fallible::<Error>()
)
.unwrap_err()
.code(),
ErrorCode::NotFound
);
}
#[test]
fn acl_add_fails_with_resource_exhausted_when_full() {
let crypto = test_only_crypto();
let mut fabrics = Fabrics::new();
let fab_idx = add_fabric(&crypto, &mut fabrics, 0xa, 0x1a);
let fabric = fabrics.get_mut(fab_idx).unwrap();
// One admin entry is seeded on add
for _ in 1..crate::acl::MAX_ACL_ENTRIES_PER_FABRIC {
fabric
.acl_add(AclEntry::new(None, Privilege::VIEW, AuthMode::Case))
.unwrap();
}
assert_eq!(fabric.acl().len(), crate::acl::MAX_ACL_ENTRIES_PER_FABRIC);
assert_eq!(
fabric
.acl_add(AclEntry::new(None, Privilege::VIEW, AuthMode::Case))
.unwrap_err()
.code(),
ErrorCode::ResourceExhausted
);
assert_eq!(
fabric
.acl_add_init(
AclEntry::init(None, Privilege::VIEW, AuthMode::Case).into_fallible::<Error>()
)
.unwrap_err()
.code(),
ErrorCode::ResourceExhausted
);
}
/// Whether `fabrics` grants a `READ` of endpoint `endpoint` (with `RV`
/// target permissions) to the given accessor.
fn allowed(
fabrics: &Fabrics,
fab_idx: u8,
subject: u64,
auth_mode: Option<AuthMode>,
endpoint: u16,
aux_acl_enabled: bool,
) -> bool {
let accessor = SubjectDescriptor::new(
fab_idx,
aux_acl_enabled,
AccessorSubjects::new(subject),
auth_mode,
);
let mut req = AccessReq::new(
&accessor,
GenericPath::new(Some(endpoint), Some(0x1d), None),
Access::READ,
&[],
);
req.set_target_perms(Access::RV);
fabrics.allow(&req, aux_acl_enabled)
}
#[test]
fn allow_matches_subject_fabric_and_auth_mode() {
let crypto = test_only_crypto();
let mut fabrics = Fabrics::new();
add_fabric(&crypto, &mut fabrics, 0xa, 0x1a);
add_fabric(&crypto, &mut fabrics, 0xb, 0x1b);
// The seeded admin entry grants the admin subject over CASE
assert!(allowed(&fabrics, 1, 0x1a, Some(AuthMode::Case), 1, false));
// ...but not other subjects, other fabrics, or other auth modes
assert!(!allowed(&fabrics, 1, 0x1b, Some(AuthMode::Case), 1, false));
assert!(!allowed(&fabrics, 2, 0x1a, Some(AuthMode::Case), 1, false));
assert!(!allowed(&fabrics, 1, 0x1a, Some(AuthMode::Group), 1, false));
// PASE accessors get the implicit administer grant
assert!(allowed(&fabrics, 0, 1, Some(AuthMode::Pase), 1, false));
// Plain-text accessors (no fabric) and unknown fabrics are denied
assert!(!allowed(&fabrics, 0, 0x1a, None, 1, false));
assert!(!allowed(&fabrics, 7, 0x1a, Some(AuthMode::Case), 1, false));
// A wildcard-subject entry admits anyone on that fabric
fabrics
.get_mut(idx(2))
.unwrap()
.acl_add(AclEntry::new(None, Privilege::VIEW, AuthMode::Case))
.unwrap();
assert!(allowed(&fabrics, 2, 0x1a, Some(AuthMode::Case), 1, false));
assert!(!allowed(&fabrics, 1, 0x999, Some(AuthMode::Case), 1, false));
}
#[test]
fn allow_aux_acl_excludes_root_endpoint_for_wildcard_group_entries() {
let crypto = test_only_crypto();
let mut fabrics = Fabrics::new();
add_fabric(&crypto, &mut fabrics, 0xa, 0x1a);
let mut entry = AclEntry::new(None, Privilege::OPERATE, AuthMode::Group);
entry.add_subject(0x1234).unwrap();
fabrics.get_mut(idx(1)).unwrap().acl_add(entry).unwrap();
// Without the AUXILIARY feature a wildcard-target group entry covers the whole node
assert!(allowed(
&fabrics,
1,
0x1234,
Some(AuthMode::Group),
0,
false
));
assert!(allowed(
&fabrics,
1,
0x1234,
Some(AuthMode::Group),
1,
false
));
// With it, the root endpoint is excluded
assert!(!allowed(
&fabrics,
1,
0x1234,
Some(AuthMode::Group),
0,
true
));
assert!(allowed(&fabrics, 1, 0x1234, Some(AuthMode::Group), 1, true));
// CASE entries are unaffected either way
assert!(allowed(&fabrics, 1, 0x1a, Some(AuthMode::Case), 0, true));
}
#[test]
fn set_vid_verification_updates_only_the_given_fields() {
let crypto = test_only_crypto();
let mut fabrics = Fabrics::new();
let fab_idx = add_fabric(&crypto, &mut fabrics, 0xa, 0x1a);
let fabric = fabrics.get_mut(fab_idx).unwrap();
// Vendor ID alone
fabric
.set_vid_verification(Some(0x1234), None, None)
.unwrap();
assert_eq!(fabric.vendor_id(), 0x1234);
assert!(fabric.vid_verification_statement().is_empty());
assert!(fabric.vvsc().is_empty());
// Statement of the exact allowed length; longer is rejected
let stmt = [0xab; VID_VERIFICATION_STATEMENT_LEN];
fabric
.set_vid_verification(None, Some(&stmt), None)
.unwrap();
assert_eq!(fabric.vid_verification_statement(), &stmt);
assert_eq!(fabric.vendor_id(), 0x1234);
let too_long = [0xab; VID_VERIFICATION_STATEMENT_LEN + 1];
assert_eq!(
fabric
.set_vid_verification(None, Some(&too_long), None)
.unwrap_err()
.code(),
ErrorCode::BufferTooSmall
);
// Empty statement clears it
fabric.set_vid_verification(None, Some(&[]), None).unwrap();
assert!(fabric.vid_verification_statement().is_empty());
// A VVSC occupies the (otherwise empty) ICAC slot
fabric
.set_vid_verification(None, None, Some(&[0xcd; 30]))
.unwrap();
assert_eq!(fabric.vvsc(), &[0xcd; 30]);
assert!(fabric.icac().is_empty());
// An empty VVSC clears it
fabric.set_vid_verification(None, None, Some(&[])).unwrap();
assert!(fabric.vvsc().is_empty());
assert!(fabric.icac().is_empty());
}
#[test]
fn set_vid_verification_empty_vvsc_does_not_clear_icac() {
let crypto = test_only_crypto();
let mut fabrics = Fabrics::new();
let rcac = mint_rcac(&crypto, 0xfab, 0x77);
let icac = mint_icac(&crypto, &rcac);
let noc = mint_noc(&crypto, &icac, false, 0x1234);
let fabric = fabrics
.add(
&crypto,
noc.key.reference(),
&rcac.cert,
&noc.cert,
&icac.cert,
Some(CanonAeadKeyRef::new(&TEST_IPK)),
0xfff1,
0x1234,
)
.unwrap();
fabric.set_vid_verification(None, None, Some(&[])).unwrap();
assert_eq!(fabric.icac(), icac.cert.as_slice());
assert!(fabric.vvsc().is_empty());
}
/// Persist every fabric of `fabrics` into `kv`.
fn store_all(fabrics: &Fabrics, kv: &MemKv) {
let mut persist = FabricPersist::new(kv);
for fabric in fabrics.iter() {
persist.store(fabric).unwrap();
}
persist.run().unwrap();
}
/// Load a fresh `Fabrics` from `kv`.
fn load_all(kv: &MemKv) -> Fabrics {
let mut fabrics = Fabrics::new();
kv.access(|kv, buf| fabrics.load_persist(kv, buf)).unwrap();
fabrics
}
/// Assert that `a` and `b` carry the same persisted state.
fn assert_same_fabric(a: &Fabric, b: &Fabric) {
assert_eq!(a.fab_idx(), b.fab_idx());
assert_eq!(a.node_id(), b.node_id());
assert_eq!(a.fabric_id(), b.fabric_id());
assert_eq!(a.vendor_id(), b.vendor_id());
assert_eq!(a.compressed_fabric_id(), b.compressed_fabric_id());
assert_eq!(a.secret_key().access(), b.secret_key().access());
assert_eq!(a.root_ca(), b.root_ca());
assert_eq!(a.icac(), b.icac());
assert_eq!(a.vvsc(), b.vvsc());
assert_eq!(a.noc(), b.noc());
assert_eq!(a.ipk().epoch_key().access(), b.ipk().epoch_key().access());
assert_eq!(a.ipk().op_key().access(), b.ipk().op_key().access());
assert_eq!(a.label(), b.label());
assert_eq!(a.acl(), b.acl());
assert_eq!(
a.vid_verification_statement(),
b.vid_verification_statement()
);
#[cfg(feature = "groups")]
{
let ga = a.groups();
let gb = b.groups();
let ks_a: std::vec::Vec<_> = ga
.key_set_iter()
.map(|k| {
(
k.group_key_set_id,
k.group_key_security_policy,
k.epoch_keys.len(),
)
})
.collect();
let ks_b: std::vec::Vec<_> = gb
.key_set_iter()
.map(|k| {
(
k.group_key_set_id,
k.group_key_security_policy,
k.epoch_keys.len(),
)
})
.collect();
assert_eq!(ks_a, ks_b);
for (ka, kb) in ga.key_set_iter().zip(gb.key_set_iter()) {
for (ea, eb) in ka.epoch_keys.iter().zip(kb.epoch_keys.iter()) {
assert_eq!(ea.epoch_start_time, eb.epoch_start_time);
assert_eq!(ea.epoch_key.access(), eb.epoch_key.access());
}
}
let km_a: std::vec::Vec<_> = ga
.key_map_iter()
.map(|m| (m.group_id, m.group_key_set_id))
.collect();
let km_b: std::vec::Vec<_> = gb
.key_map_iter()
.map(|m| (m.group_id, m.group_key_set_id))
.collect();
assert_eq!(km_a, km_b);
let ep_a: std::vec::Vec<_> = ga
.iter()
.map(|e| {
(
e.group_id,
e.endpoints.to_vec(),
e.group_name.clone(),
e.has_aux_acl(),
e.groupcast_managed(),
)
})
.collect();
let ep_b: std::vec::Vec<_> = gb
.iter()
.map(|e| {
(
e.group_id,
e.endpoints.to_vec(),
e.group_name.clone(),
e.has_aux_acl(),
e.groupcast_managed(),
)
})
.collect();
assert_eq!(ep_a, ep_b);
}
}
#[test]
fn store_then_load_yields_equal_fabrics() {
let crypto = test_only_crypto();
let mut fabrics = Fabrics::new();
let rcac = mint_rcac(&crypto, 0xfab, 0x77);
let icac = mint_icac(&crypto, &rcac);
let noc = mint_noc(&crypto, &icac, false, 0x1234);
fabrics
.add(
&crypto,
noc.key.reference(),
&rcac.cert,
&noc.cert,
&icac.cert,
Some(CanonAeadKeyRef::new(&TEST_IPK)),
0xfff1,
0x1234,
)
.unwrap();
add_fabric(&crypto, &mut fabrics, 0xb, 0x1b);
fabrics.update_label(idx(1), "first").unwrap();
{
let fabric = fabrics.get_mut(idx(1)).unwrap();
let mut entry = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
entry.add_subject(0x99).unwrap();
entry
.add_target(Target::new(Some(1), Some(6), None))
.unwrap();
fabric.acl_add(entry).unwrap();
fabric
.set_vid_verification(
Some(0x4321),
Some(&[0x11; VID_VERIFICATION_STATEMENT_LEN]),
None,
)
.unwrap();
}
{
let fabric = fabrics.get_mut(idx(2)).unwrap();
fabric
.set_vid_verification(None, None, Some(&[0xcd; 30]))
.unwrap();
#[cfg(feature = "groups")]
{
use crate::group_keys::{GroupEpochKeyEntry, GroupKeySet};
let groups = fabric.groups_mut();
let mut key_set = GroupKeySet {
group_key_set_id: 0x11,
group_key_security_policy: 1,
epoch_keys: crate::utils::storage::Vec::new(),
};
key_set
.epoch_keys
.push(GroupEpochKeyEntry {
epoch_key: crate::crypto::CanonAeadKey::new_from_ref(CanonAeadKeyRef::new(
&[0x77; AEAD_CANON_KEY_LEN],
)),
epoch_start_time: 1234,
})
.unwrap();
groups.key_set_add(key_set).unwrap();
groups.key_map_set_group(0x100, 0x11).unwrap();
groups.add(1, 0x100, "kitchen").unwrap();
groups.groupcast_join(0x101, &[2, 3], false, None).unwrap();
groups.set_has_aux_acl(0x101, true);
}
}
let store = MemKvBlobStore::default();
let kv = MemKv::new(store.clone());
store_all(&fabrics, &kv);
assert!(store.contains_key(FABRIC_KEYS_START + 1));
assert!(store.contains_key(FABRIC_KEYS_START + 2));
assert_eq!(store.len(), 2);
let loaded = load_all(&kv);
assert_eq!(loaded.iter().count(), 2);
for fabric in fabrics.iter() {
assert_same_fabric(fabric, loaded.get(fabric.fab_idx()).unwrap());
}
// Loaded fabrics remain fully functional (e.g. for destination ID lookups)
let random = [0x42u8; 32];
let mut dest_id = Hash::new();
fabrics
.get(idx(1))
.unwrap()
.compute_dest_id(&crypto, &random, 0x1234, &mut dest_id)
.unwrap();
assert_eq!(
loaded
.get_by_dest_id(&crypto, &random, dest_id.access())
.unwrap()
.fab_idx(),
idx(1)
);
}
#[test]
fn persist_remove_deletes_the_blob() {
let crypto = test_only_crypto();
let mut fabrics = Fabrics::new();
add_fabric(&crypto, &mut fabrics, 0xa, 0x1a);
add_fabric(&crypto, &mut fabrics, 0xb, 0x1b);
let store = MemKvBlobStore::default();
let kv = MemKv::new(store.clone());
store_all(&fabrics, &kv);
assert_eq!(store.len(), 2);
let mut persist = FabricPersist::new(&kv);
persist.remove(idx(1)).unwrap();
persist.run().unwrap();
assert!(!store.contains_key(FABRIC_KEYS_START + 1));
assert!(store.contains_key(FABRIC_KEYS_START + 2));
let loaded = load_all(&kv);
let order: std::vec::Vec<_> = loaded.iter().map(|f| f.fab_idx().get()).collect();
assert_eq!(order, [2]);
// Removing a blob that is not there is not an error
FabricPersist::new(&kv).remove(idx(1)).unwrap();
}
#[test]
fn reset_persist_clears_memory_and_storage() {
let crypto = test_only_crypto();
let mut fabrics = Fabrics::new();
add_fabric(&crypto, &mut fabrics, 0xa, 0x1a);
add_fabric(&crypto, &mut fabrics, 0xb, 0x1b);
let store = MemKvBlobStore::default();
let kv = MemKv::new(store.clone());
store_all(&fabrics, &kv);
FabricPersist::new(&kv)
.store_next_fab_idx(fabrics.next_fab_idx())
.unwrap();
assert_eq!(store.len(), 3);
kv.access(|kv, buf| fabrics.reset_persist(kv, buf)).unwrap();
assert_eq!(fabrics.iter().count(), 0);
assert_eq!(fabrics.next_fab_idx(), idx(1));
assert_eq!(store.len(), 0);
assert_eq!(load_all(&kv).iter().count(), 0);
}
#[test]
fn next_fab_idx_is_loaded_back() {
let crypto = test_only_crypto();
let mut fabrics = Fabrics::new();
add_fabric(&crypto, &mut fabrics, 0xa, 0x1a);
add_fabric(&crypto, &mut fabrics, 0xb, 0x1b);
fabrics.remove(idx(2)).unwrap();
let kv = MemKv::new(MemKvBlobStore::default());
store_all(&fabrics, &kv);
FabricPersist::new(&kv)
.store_next_fab_idx(fabrics.next_fab_idx())
.unwrap();
let mut loaded = load_all(&kv);
assert_eq!(loaded.next_fab_idx(), idx(3));
assert_eq!(add_fabric(&crypto, &mut loaded, 0xc, 0x1c), idx(3));
}
#[test]
fn missing_or_unreadable_next_fab_idx_follows_the_largest_index() {
let crypto = test_only_crypto();
let mut fabrics = Fabrics::new();
add_fabric(&crypto, &mut fabrics, 0xa, 0x1a);
add_fabric(&crypto, &mut fabrics, 0xb, 0x1b);
add_fabric(&crypto, &mut fabrics, 0xc, 0x1c);
fabrics.remove(idx(1)).unwrap();
let store = MemKvBlobStore::default();
let kv = MemKv::new(store.clone());
store_all(&fabrics, &kv);
assert_eq!(load_all(&kv).next_fab_idx(), idx(4));
for unreadable in [&[0xff][..], &[0x04, 0x00], &[0x04, 0xff]] {
let mut raw = store.clone();
raw.store(NEXT_FABRIC_INDEX_KEY, unreadable, &mut [])
.unwrap();
assert_eq!(load_all(&kv).next_fab_idx(), idx(4));
}
}
#[test]
fn unloadable_fabric_keeps_its_index() {
let mut store = MemKvBlobStore::default();
store
.store(FABRIC_KEYS_START + 1, &[0xff], &mut [])
.unwrap();
let mut fabrics = load_all(&MemKv::new(store));
assert_eq!(fabrics.iter().count(), 0);
let fabric = fabrics.add_with_post_init(|_| Ok(())).unwrap();
assert_eq!(fabric.fab_idx(), idx(2));
}
#[test]
fn fabric_removal_drops_its_acl_and_groups() {
let crypto = test_only_crypto();
let mut fabrics = Fabrics::new();
let rcac = mint_rcac(&crypto, 0xfab, 0x77);
let noc = mint_noc(&crypto, &rcac, true, 0x1234);
let add = |fabrics: &mut Fabrics| -> NonZeroU8 {
fabrics
.add(
&crypto,
noc.key.reference(),
&rcac.cert,
&noc.cert,
&[],
Some(CanonAeadKeyRef::new(&TEST_IPK)),
0xfff1,
0x1234,
)
.unwrap()
.fab_idx()
};
let fab_idx = add(&mut fabrics);
{
let fabric = fabrics.get_mut(fab_idx).unwrap();
fabric
.acl_add(AclEntry::new(None, Privilege::VIEW, AuthMode::Case))
.unwrap();
assert_eq!(fabric.acl().len(), 2);
#[cfg(feature = "groups")]
{
fabric.groups_mut().add(1, 0x100, "g").unwrap();
assert_eq!(fabric.groups().group_count(), 1);
}
}
fabrics.remove(fab_idx).unwrap();
assert_eq!(fabrics.iter().count(), 0);
// A fabric re-added with the same identity starts from a clean slate
let fab_idx = add(&mut fabrics);
let fabric = fabrics.get(fab_idx).unwrap();
assert_eq!(fabric.acl().len(), 1);
assert_eq!(fabric.label(), "");
#[cfg(feature = "groups")]
{
assert_eq!(fabric.groups().group_count(), 0);
assert_eq!(fabric.groups().key_set_iter().count(), 0);
assert_eq!(fabric.groups().key_map_iter().count(), 0);
}
}
#[cfg(feature = "groups")]
mod groups {
use crate::crypto::{CanonAeadKey, CanonAeadKeyRef, AEAD_CANON_KEY_LEN};
use crate::error::ErrorCode;
use crate::fabric::MulticastAddrPolicy;
use crate::fabric::{
GroupKeyMapping, Groups, GROUP_ENDPOINTS_PER_FABRIC, MAX_GROUPS_PER_FABRIC,
MAX_GROUP_KEYS_PER_FABRIC, MAX_GROUP_NAME_LEN,
};
use crate::group_keys::{GroupEpochKeyEntry, GroupKeySet};
fn key_set(id: u16, policy: u8) -> GroupKeySet {
let mut key_set = GroupKeySet {
group_key_set_id: id,
group_key_security_policy: policy,
epoch_keys: crate::utils::storage::Vec::new(),
};
key_set
.epoch_keys
.push(GroupEpochKeyEntry {
epoch_key: CanonAeadKey::new_from_ref(CanonAeadKeyRef::new(
&[id as u8; AEAD_CANON_KEY_LEN],
)),
epoch_start_time: id as u64,
})
.unwrap();
key_set
}
#[test]
fn key_set_add_get_remove_iter_and_capacity() {
let mut groups = Groups::new();
assert!(groups.key_set_get(1).is_none());
assert_eq!(groups.key_set_iter().count(), 0);
groups.key_set_add(key_set(1, 0)).unwrap();
groups.key_set_add(key_set(2, 0)).unwrap();
assert_eq!(groups.key_set_get(1).unwrap().group_key_security_policy, 0);
assert_eq!(
groups.key_set_get(2).unwrap().epoch_keys[0].epoch_start_time,
2
);
// Re-adding an existing ID replaces it in place
groups.key_set_add(key_set(1, 1)).unwrap();
assert_eq!(groups.key_set_get(1).unwrap().group_key_security_policy, 1);
let ids: std::vec::Vec<_> = groups.key_set_iter().map(|k| k.group_key_set_id).collect();
assert_eq!(ids, [1, 2]);
for id in 3..=MAX_GROUP_KEYS_PER_FABRIC as u16 {
groups.key_set_add(key_set(id, 0)).unwrap();
}
assert_eq!(groups.key_set_iter().count(), MAX_GROUP_KEYS_PER_FABRIC);
assert_eq!(
groups
.key_set_add(key_set(MAX_GROUP_KEYS_PER_FABRIC as u16 + 1, 0))
.unwrap_err()
.code(),
ErrorCode::ResourceExhausted
);
groups.key_set_remove(1).unwrap();
assert!(groups.key_set_get(1).is_none());
assert_eq!(groups.key_set_iter().count(), MAX_GROUP_KEYS_PER_FABRIC - 1);
assert_eq!(
groups.key_set_remove(1).unwrap_err().code(),
ErrorCode::NotFound
);
}
#[test]
fn key_set_remove_drops_key_map_entries_referencing_it() {
let mut groups = Groups::new();
groups.key_set_add(key_set(1, 0)).unwrap();
groups.key_set_add(key_set(2, 0)).unwrap();
groups.key_map_set_group(0x100, 1).unwrap();
groups.key_map_set_group(0x101, 2).unwrap();
groups.key_map_set_group(0x102, 1).unwrap();
groups.key_set_remove(1).unwrap();
let map: std::vec::Vec<_> = groups
.key_map_iter()
.map(|m| (m.group_id, m.group_key_set_id))
.collect();
assert_eq!(map, [(0x101, 2)]);
assert_eq!(groups.key_map_get(0x100), None);
assert_eq!(groups.key_map_get(0x101), Some(2));
}
#[test]
fn key_map_add_replace_get_set_and_remove() {
let mut groups = Groups::new();
groups
.key_map_add(GroupKeyMapping {
group_id: 0x100,
group_key_set_id: 1,
})
.unwrap();
assert_eq!(groups.key_map_get(0x100), Some(1));
assert_eq!(groups.key_map_get(0x101), None);
// `key_map_add` does not dedupe; `key_map_get` returns the first match
groups
.key_map_add(GroupKeyMapping {
group_id: 0x100,
group_key_set_id: 2,
})
.unwrap();
assert_eq!(groups.key_map_iter().count(), 2);
assert_eq!(groups.key_map_get(0x100), Some(1));
// `key_map_set_group` replaces the (first) mapping of the group
groups.key_map_set_group(0x100, 3).unwrap();
assert_eq!(groups.key_map_get(0x100), Some(3));
groups.key_map_set_group(0x101, 1).unwrap();
assert_eq!(groups.key_map_get(0x101), Some(1));
assert_eq!(groups.key_map_iter().count(), 3);
// `key_map_remove_group` drops every mapping of the group
groups.key_map_remove_group(0x100);
let map: std::vec::Vec<_> = groups
.key_map_iter()
.map(|m| (m.group_id, m.group_key_set_id))
.collect();
assert_eq!(map, [(0x101, 1)]);
// `key_map_replace` swaps the whole table
groups
.key_map_replace([(0x200, 5), (0x201, 6)].into_iter().map(
|(group_id, group_key_set_id)| GroupKeyMapping {
group_id,
group_key_set_id,
},
))
.unwrap();
let map: std::vec::Vec<_> = groups
.key_map_iter()
.map(|m| (m.group_id, m.group_key_set_id))
.collect();
assert_eq!(map, [(0x200, 5), (0x201, 6)]);
groups.key_map_remove_by_key_set(5);
assert_eq!(groups.key_map_get(0x200), None);
assert_eq!(groups.key_map_get(0x201), Some(6));
}
#[test]
fn key_map_capacity() {
let mut groups = Groups::new();
for i in 0..MAX_GROUPS_PER_FABRIC as u16 {
groups.key_map_set_group(0x100 + i, 1).unwrap();
}
assert_eq!(groups.key_map_iter().count(), MAX_GROUPS_PER_FABRIC);
assert_eq!(
groups.key_map_set_group(0x1ff, 1).unwrap_err().code(),
ErrorCode::ResourceExhausted
);
assert_eq!(
groups
.key_map_add(GroupKeyMapping {
group_id: 0x1ff,
group_key_set_id: 1,
})
.unwrap_err()
.code(),
ErrorCode::Failure
);
// Replacing an existing group's mapping still works when full
groups.key_map_set_group(0x100, 2).unwrap();
assert_eq!(groups.key_map_get(0x100), Some(2));
assert_eq!(
groups
.key_map_replace((0..=MAX_GROUPS_PER_FABRIC as u16).map(|i| GroupKeyMapping {
group_id: i,
group_key_set_id: 1,
}))
.unwrap_err()
.code(),
ErrorCode::ResourceExhausted
);
}
#[test]
fn endpoint_mapping_add_get_and_remove() {
let mut groups = Groups::new();
assert!(groups.get(0x100).is_none());
assert_eq!(groups.group_count(), 0);
// First membership creates the group; a repeat reports it as existing
assert!(!groups.add(1, 0x100, "kitchen").unwrap());
assert!(groups.add(1, 0x100, "kitchen").unwrap());
assert!(!groups.add(2, 0x100, "cuisine").unwrap());
assert!(!groups.add(2, 0x101, "hall").unwrap());
assert_eq!(groups.group_count(), 2);
let entry = groups.get(0x100).unwrap();
assert_eq!(entry.endpoints.as_slice(), &[1, 2]);
// The most recent add renames the group
assert_eq!(entry.group_name.as_str(), "cuisine");
assert!(!entry.has_aux_acl());
assert!(!entry.groupcast_managed());
assert!(matches!(
entry.effective_mcast_policy(),
MulticastAddrPolicy::PerGroup
));
let ids: std::vec::Vec<_> = groups.iter().map(|e| e.group_id).collect();
assert_eq!(ids, [0x100, 0x101]);
groups.get_mut(0x101).unwrap().group_name.clear();
assert_eq!(groups.get(0x101).unwrap().group_name.as_str(), "");
assert!(groups.get_mut(0x1ff).is_none());
// Removing a non-member is a no-op
assert!(!groups.remove(7, Some(0x100)));
assert!(!groups.remove(1, Some(0x101)));
// Removing from one group leaves the others alone
assert!(groups.remove(1, Some(0x100)));
assert_eq!(groups.get(0x100).unwrap().endpoints.as_slice(), &[2]);
// Removing from all groups; legacy groups left empty disappear
assert!(groups.remove(2, None));
assert!(groups.get(0x100).is_none());
assert!(groups.get(0x101).is_none());
assert_eq!(groups.group_count(), 0);
}
#[test]
fn endpoint_mapping_capacity_and_name_length() {
let mut groups = Groups::new();
for i in 0..MAX_GROUPS_PER_FABRIC as u16 {
groups.add(1, 0x100 + i, "g").unwrap();
}
assert_eq!(groups.group_count(), MAX_GROUPS_PER_FABRIC);
assert_eq!(
groups.add(1, 0x1ff, "g").unwrap_err().code(),
ErrorCode::ResourceExhausted
);
// An existing group still accepts endpoints up to its own capacity
for ep in 2..=GROUP_ENDPOINTS_PER_FABRIC as u16 {
groups.add(ep, 0x100, "g").unwrap();
}
assert_eq!(
groups.get(0x100).unwrap().endpoints.len(),
GROUP_ENDPOINTS_PER_FABRIC
);
assert_eq!(
groups
.add(GROUP_ENDPOINTS_PER_FABRIC as u16 + 1, 0x100, "g")
.unwrap_err()
.code(),
ErrorCode::ResourceExhausted
);
let mut fresh = Groups::new();
fresh
.add(1, 0x100, &"n".repeat(MAX_GROUP_NAME_LEN))
.unwrap();
assert_eq!(
fresh
.add(1, 0x101, &"n".repeat(MAX_GROUP_NAME_LEN + 1))
.unwrap_err()
.code(),
ErrorCode::ConstraintError
);
assert_eq!(fresh.group_count(), 1);
// A rejected name leaves an existing group's name and members untouched
assert_eq!(
fresh
.add(2, 0x100, &"n".repeat(MAX_GROUP_NAME_LEN + 1))
.unwrap_err()
.code(),
ErrorCode::ConstraintError
);
let entry = fresh.get(0x100).unwrap();
assert_eq!(entry.group_name.as_str(), "n".repeat(MAX_GROUP_NAME_LEN));
assert_eq!(entry.endpoints.as_slice(), &[1]);
}
#[test]
fn groupcast_join_and_remove() {
let mut groups = Groups::new();
// A new Groupcast membership defaults to the IANA address policy
groups
.groupcast_join(0x100, &[1, 2, 2], false, None)
.unwrap();
let entry = groups.get(0x100).unwrap();
assert_eq!(entry.endpoints.as_slice(), &[1, 2]);
assert_eq!(entry.group_name.as_str(), "");
assert!(entry.groupcast_managed());
assert!(!entry.has_aux_acl());
assert!(matches!(
entry.effective_mcast_policy(),
MulticastAddrPolicy::IanaAddr
));
// Appending dedupes; replacing swaps the list; policy updates when given
groups
.groupcast_join(0x100, &[2, 3], false, Some(MulticastAddrPolicy::PerGroup))
.unwrap();
let entry = groups.get(0x100).unwrap();
assert_eq!(entry.endpoints.as_slice(), &[1, 2, 3]);
assert!(matches!(
entry.effective_mcast_policy(),
MulticastAddrPolicy::PerGroup
));
groups.groupcast_join(0x100, &[9], true, None).unwrap();
let entry = groups.get(0x100).unwrap();
assert_eq!(entry.endpoints.as_slice(), &[9]);
assert!(matches!(
entry.effective_mcast_policy(),
MulticastAddrPolicy::PerGroup
));
// A sender-only membership has no endpoints but still exists
groups.groupcast_join(0x101, &[], false, None).unwrap();
assert_eq!(groups.get(0x101).unwrap().endpoints.len(), 0);
assert_eq!(groups.group_count(), 2);
// Joining a legacy (Groups cluster) entry upgrades it, keeping the
// legacy-compatible PerGroup policy unless told otherwise
groups.add(4, 0x102, "legacy").unwrap();
groups.groupcast_join(0x102, &[5], false, None).unwrap();
let entry = groups.get(0x102).unwrap();
assert!(entry.groupcast_managed());
assert_eq!(entry.endpoints.as_slice(), &[4, 5]);
assert_eq!(entry.group_name.as_str(), "legacy");
assert!(matches!(
entry.effective_mcast_policy(),
MulticastAddrPolicy::PerGroup
));
// Endpoint removal keeps an emptied Groupcast-managed entry around
assert!(groups.remove(9, None));
assert!(groups.get(0x100).is_some());
assert_eq!(groups.get(0x100).unwrap().endpoints.len(), 0);
assert!(groups.groupcast_remove(0x100));
assert!(groups.get(0x100).is_none());
assert!(!groups.groupcast_remove(0x100));
assert_eq!(groups.group_count(), 2);
}
#[test]
fn groupcast_join_capacity() {
let mut groups = Groups::new();
for i in 0..MAX_GROUPS_PER_FABRIC as u16 {
groups.groupcast_join(0x100 + i, &[], false, None).unwrap();
}
assert_eq!(
groups
.groupcast_join(0x1ff, &[], false, None)
.unwrap_err()
.code(),
ErrorCode::ResourceExhausted
);
let endpoints: std::vec::Vec<u16> = (1..=GROUP_ENDPOINTS_PER_FABRIC as u16).collect();
groups
.groupcast_join(0x100, &endpoints, false, None)
.unwrap();
assert_eq!(
groups
.groupcast_join(0x100, &[0xee], false, None)
.unwrap_err()
.code(),
ErrorCode::ResourceExhausted
);
assert_eq!(
groups.get(0x100).unwrap().endpoints.len(),
GROUP_ENDPOINTS_PER_FABRIC
);
}
#[test]
fn set_has_aux_acl_reports_changes() {
let mut groups = Groups::new();
assert!(!groups.set_has_aux_acl(0x100, true));
groups.groupcast_join(0x100, &[1], false, None).unwrap();
assert!(!groups.get(0x100).unwrap().has_aux_acl());
assert!(groups.set_has_aux_acl(0x100, true));
assert!(groups.get(0x100).unwrap().has_aux_acl());
assert!(!groups.set_has_aux_acl(0x100, true));
assert!(groups.set_has_aux_acl(0x100, false));
assert!(!groups.get(0x100).unwrap().has_aux_acl());
// Legacy entries have no flag set; setting one works the same way
groups.add(1, 0x101, "g").unwrap();
assert!(!groups.set_has_aux_acl(0x101, false));
assert!(groups.set_has_aux_acl(0x101, true));
assert!(groups.get(0x101).unwrap().has_aux_acl());
}
}
}