rs-matter 0.2.0

Native Rust implementation of the Matter (Smart-Home) ecosystem
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
/*
 *
 *    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 core::str::FromStr;

use cfg_if::cfg_if;
use heapless::String;

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::{GroupKeySet, KeySet};
use crate::persist::{KvBlobStore, KvBlobStoreAccess, Persist, FABRIC_KEYS_START};
use crate::tlv::{FromTLV, TLVElement, ToTLV};
use crate::transport::network::MatterLocalService;
use crate::utils::init::{init, Init, InitMaybeUninit, IntoFallibleInit};
use crate::utils::storage::Vec;

const COMPRESSED_FABRIC_ID_LEN: usize = 8;

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 {
        /// Max number of group key sets per fabric (excluding IPK at index 0).
        pub const MAX_GROUP_KEYS_PER_FABRIC: usize = 0;
    }
}

/// 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 {
        /// Max number of group key map entries per fabric.
        pub const MAX_GROUPS_PER_FABRIC: usize = 0;
    }
}

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 {
        /// Max number of endpoints per group entry.
        pub const GROUP_ENDPOINTS_PER_FABRIC: usize = 0;
    }
}

/// 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>,
}

/// 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 {
    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))
        }
    }

    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)
    }

    /// 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> {
        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: unwrap!(String::from_str(group_name)),
                })
                .map_err(|_| ErrorCode::ResourceExhausted)?;
            unwrap!(self.endpoint_mapping.last_mut())
        };

        // Update group name
        entry.group_name.clear();
        unwrap!(entry.group_name.push_str(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
        self.endpoint_mapping.retain(|e| !e.endpoints.is_empty());

        removed
    }
}

/// 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
    groups: 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"`).
    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> {
        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(),
            groups <- Groups::init(),
            vid_verification_statement <- Vec::init(),
        })
    }

    /// 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(())
    }

    pub fn mdns_service(&self) -> Option<MatterLocalService> {
        self.mdns_service_for(self.node_id)
    }

    pub fn mdns_service_for(&self, node_id: u64) -> Option<MatterLocalService> {
        (!self.noc.is_empty()).then_some(MatterLocalService::Commissioned {
            compressed_fabric_id: self.compressed_fabric_id,
            node_id,
        })
    }

    /// 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
    pub fn groups(&self) -> &Groups {
        &self.groups
    }

    /// Return a mutable reference to the fabric's groups
    pub fn groups_mut(&mut self) -> &mut Groups {
        &mut self.groups
    }

    /// 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 (heapless `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 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>,
    {
        // if entry.auth_mode() == AuthMode::Pase {
        //     // Reserved for future use
        //     Err(ErrorCode::ConstraintError)?;
        // }

        self.acl
            .push_init(init, || ErrorCode::ResourceExhausted.into())?;

        let idx = self.acl.len() - 1;
        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.
    fn allow(&self, req: &AccessReq) -> bool {
        for e in &self.acl {
            if e.allow(req) {
                return true;
            }
        }

        debug!(
            "ACL Disallow for subjects {} fab idx {}",
            req.accessor().subjects(),
            req.accessor().fab_idx
        );

        false
    }

    /// Compute the compressed fabric ID
    pub(crate) 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 { // 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>,
}

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(),
        }
    }

    /// Return an in-place-initializer for a Fabrics type
    pub fn init() -> impl Init<Self> {
        init!(Self {
            fabrics <- Vec::init(),
        })
    }

    /// Remove all fabrics
    pub fn reset(&mut self) {
        self.fabrics.clear();
    }

    /// 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();

        for idx in 1..=255u8 {
            store.remove(FABRIC_KEYS_START + idx as u16, buf)?;
        }

        info!("Removed all fabrics from storage");

        Ok(())
    }

    /// 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)?;
        }

        Ok(())
    }

    pub(crate) fn add_load<S: KvBlobStore>(
        &mut self,
        fab_idx: u8,
        mut store: S,
        buf: &mut [u8],
    ) -> Result<(), Error> {
        if let Some(data) = store.load(FABRIC_KEYS_START + fab_idx as u16, buf)? {
            self.fabrics
                .push_init(Fabric::init_from_tlv(TLVElement::new(data)), || {
                    ErrorCode::ResourceExhausted.into()
                })?;

            let fabric = unwrap!(self.fabrics.last());

            info!(
                "Loaded fabric {} with ID {:x} from storage",
                fabric.fab_idx(),
                fabric.compressed_fabric_id()
            );
        }

        Ok(())
    }

    /// 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 max_fab_idx = self
            .iter()
            .map(|fabric| fabric.fab_idx().get())
            .max()
            .unwrap_or(0);
        let fab_idx = unwrap!(NonZeroU8::new(if max_fab_idx < u8::MAX - 1 {
            // First try with the next available fabric index larger than all currently used
            max_fab_idx + 1
        } else {
            // If there is already a fabric with index 254, try to find the first unused one
            let Some(fab_idx) = (1..u8::MAX)
                .find(|fab_idx| self.iter().all(|fabric| fabric.fab_idx().get() != *fab_idx))
            else {
                return Err(ErrorCode::ResourceExhausted.into());
            };

            fab_idx
        })); // We never use 0 as a fabric index, nor u8::MAX

        self.fabrics.push_init(
            Fabric::init(fab_idx)
                .into_fallible::<Error>()
                .chain(post_init),
            || ErrorCode::ResourceExhausted.into(),
        )?;

        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),
            )
        })
    }

    /// 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
    pub fn allow(&self, req: &AccessReq) -> 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)
    }
}

/// A utility for persisting a fabric in a `KvBlobStore` instance.
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))
    }

    /// 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)
    }

    /// Call at the end when finished with everything else
    /// No-op for now
    pub fn run(self) -> Result<(), Error> {
        self.0.run()
    }
}

#[cfg(test)]
mod tests {
    use core::mem::MaybeUninit;

    use crate::cert::gen::{CertGenerator, CertType, IssuerDN, SubjectDN, Validity};
    use crate::cert::MAX_CERT_TLV_AND_ASN1_LEN;
    use crate::crypto::test_only_crypto;
    use crate::crypto::{
        CanonAeadKeyRef, CanonPkcSecretKey, Crypto, Hash, PublicKey, SecretKey, SigningSecretKey,
        AEAD_CANON_KEY_LEN,
    };
    use crate::utils::init::InitMaybeUninit;

    use super::Fabrics;

    /// 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");
    }
}