Skip to main content

rs_matter_node_core/
fabric.rs

1/*
2 *
3 *    Copyright (c) 2022-2026 Project CHIP Authors
4 *
5 *    Licensed under the Apache License, Version 2.0 (the "License");
6 *    you may not use this file except in compliance with the License.
7 *    You may obtain a copy of the License at
8 *
9 *        http://www.apache.org/licenses/LICENSE-2.0
10 *
11 *    Unless required by applicable law or agreed to in writing, software
12 *    distributed under the License is distributed on an "AS IS" BASIS,
13 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *    See the License for the specific language governing permissions and
15 *    limitations under the License.
16 */
17
18use core::mem::MaybeUninit;
19use core::num::NonZeroU8;
20
21use cfg_if::cfg_if;
22
23use crate::acl::{self, AccessReq, AclEntry, AuthMode};
24use crate::cert::{CertRef, MAX_CERT_TLV_LEN};
25use crate::crypto::{
26    CanonAeadKeyRef, CanonPkcPublicKeyRef, CanonPkcSecretKey, CanonPkcSecretKeyRef, Crypto,
27    CryptoSensitive, Digest, Hash, Kdf, PKC_CANON_PUBLIC_KEY_LEN,
28};
29use crate::dm::Privilege;
30use crate::error::{Error, ErrorCode};
31use crate::group_keys::KeySet;
32use crate::persist::{
33    load_logged, KvBlobStore, KvBlobStoreAccess, Persist, FABRIC_KEYS_START, NEXT_FABRIC_INDEX_KEY,
34};
35#[cfg(feature = "groups")]
36use crate::tlv::Skippable;
37use crate::tlv::{FromTLV, TLVElement, TlvError, TlvErrorCode, ToTLV};
38use crate::utils::init::{init, Init, InitMaybeUninit, IntoFallibleInit};
39use crate::utils::storage::{String, Vec};
40
41const COMPRESSED_FABRIC_ID_LEN: usize = 8;
42
43/// The largest fabric index: 0 is reserved, and 255 would leave no room for
44/// nullable fabric index fields.
45const MAX_FAB_IDX: u8 = u8::MAX - 1;
46
47/// All multicast-group fabric state: the group key sets, the group→keyset
48/// mapping, and the group table. Gated as one inline module so the whole block
49/// (consts, TLV structs and the `Groups` container) is compiled out with a
50/// single `#[cfg]` when the `groups` feature is off, and re-exported so the rest
51/// of `fabric` refers to these items unqualified.
52#[cfg(feature = "groups")]
53mod groups {
54    use core::str::FromStr;
55
56    use cfg_if::cfg_if;
57
58    use crate::error::{Error, ErrorCode};
59    use crate::group_keys::GroupKeySet;
60    use crate::tlv::{FromTLV, ToTLV};
61    use crate::utils::init::{init, Init, InitDefault};
62    use crate::utils::storage::{String, Vec};
63
64    cfg_if! {
65        if #[cfg(feature = "max-group-keys-per-fabric-5")] {
66            /// Max number of group key sets per fabric (excluding IPK at index 0).
67            pub const MAX_GROUP_KEYS_PER_FABRIC: usize = 5;
68        } else if #[cfg(feature = "max-group-keys-per-fabric-4")] {
69            /// Max number of group key sets per fabric (excluding IPK at index 0).
70            pub const MAX_GROUP_KEYS_PER_FABRIC: usize = 4;
71        } else if #[cfg(feature = "max-group-keys-per-fabric-3")] {
72            /// Max number of group key sets per fabric (excluding IPK at index 0).
73            pub const MAX_GROUP_KEYS_PER_FABRIC: usize = 3;
74        } else if #[cfg(feature = "max-group-keys-per-fabric-2")] {
75            /// Max number of group key sets per fabric (excluding IPK at index 0).
76            pub const MAX_GROUP_KEYS_PER_FABRIC: usize = 2;
77        } else { // Matter requires a minimum of 3 group key sets per fabric
78            /// Max number of group key sets per fabric (excluding IPK at index 0).
79            pub const MAX_GROUP_KEYS_PER_FABRIC: usize = 3;
80        }
81    }
82
83    /// Max length of a group name (per Matter spec).
84    pub const MAX_GROUP_NAME_LEN: usize = 16;
85
86    cfg_if! {
87        if #[cfg(feature = "max-groups-per-fabric-32")] {
88            /// Max number of group key map entries per fabric.
89            pub const MAX_GROUPS_PER_FABRIC: usize = 32;
90        } else if #[cfg(feature = "max-groups-per-fabric-16")] {
91            /// Max number of group key map entries per fabric.
92            pub const MAX_GROUPS_PER_FABRIC: usize = 16;
93        } else if #[cfg(feature = "max-groups-per-fabric-12")] {
94            /// Max number of group key map entries per fabric.
95            pub const MAX_GROUPS_PER_FABRIC: usize = 12;
96        } else if #[cfg(feature = "max-groups-per-fabric-8")] {
97            /// Max number of group key map entries per fabric.
98            pub const MAX_GROUPS_PER_FABRIC: usize = 9;
99        } else if #[cfg(feature = "max-groups-per-fabric-7")] {
100            /// Max number of group key map entries per fabric.
101            pub const MAX_GROUPS_PER_FABRIC: usize = 7;
102        } else if #[cfg(feature = "max-groups-per-fabric-6")] {
103            /// Max number of group key map entries per fabric.
104            pub const MAX_GROUPS_PER_FABRIC: usize = 6;
105        } else if #[cfg(feature = "max-groups-per-fabric-5")] {
106            /// Max number of group key map entries per fabric.
107            pub const MAX_GROUPS_PER_FABRIC: usize = 5;
108        } else if #[cfg(feature = "max-groups-per-fabric-4")] {
109            /// Max number of group key map entries per fabric.
110            pub const MAX_GROUPS_PER_FABRIC: usize = 4;
111        } else { // Matter requires a minimum of 4 group table entries per fabric
112            /// Max number of group key map entries per fabric.
113            pub const MAX_GROUPS_PER_FABRIC: usize = 4;
114        }
115    }
116
117    cfg_if! {
118        if #[cfg(feature = "max-group-endpoints-per-fabric-5")] {
119            /// Max number of endpoints per group entry.
120            pub const GROUP_ENDPOINTS_PER_FABRIC: usize = 5;
121        } else if #[cfg(feature = "max-group-endpoints-per-fabric-4")] {
122            /// Max number of endpoints per group entry.
123            pub const GROUP_ENDPOINTS_PER_FABRIC: usize = 4;
124        } else if #[cfg(feature = "max-group-endpoints-per-fabric-3")] {
125            /// Max number of endpoints per group entry.
126            pub const GROUP_ENDPOINTS_PER_FABRIC: usize = 3;
127        } else if #[cfg(feature = "max-group-endpoints-per-fabric-2")] {
128            /// Max number of endpoints per group entry.
129            pub const GROUP_ENDPOINTS_PER_FABRIC: usize = 2;
130        } else if #[cfg(feature = "max-group-endpoints-per-fabric-1")] {
131            /// Max number of endpoints per group entry.
132            pub const GROUP_ENDPOINTS_PER_FABRIC: usize = 1;
133        } else { // Default: 3 endpoints per group entry
134            /// Max number of endpoints per group entry.
135            pub const GROUP_ENDPOINTS_PER_FABRIC: usize = 3;
136        }
137    }
138
139    /// A group table entry mapping a group ID to its endpoints and name.
140    #[derive(Debug, FromTLV, ToTLV)]
141    #[cfg_attr(feature = "defmt", derive(defmt::Format))]
142    pub struct GroupEndpointMapping {
143        pub group_id: u16,
144        pub endpoints: Vec<u16, GROUP_ENDPOINTS_PER_FABRIC>,
145        pub group_name: String<MAX_GROUP_NAME_LEN>,
146        /// Whether the (Groupcast-managed) group has auxiliary ACL entries
147        /// generated for its endpoints - see the Groupcast cluster's
148        /// `ConfigureAuxiliaryACL` command and the `AuxiliaryACL` attribute
149        /// of the Access Control cluster.
150        ///
151        /// `None` (in blobs persisted before the field existed) means `false`.
152        pub has_aux_acl: Option<bool>,
153        /// The multicast-address policy of the group, when it is managed by
154        /// the Groupcast cluster.
155        ///
156        /// `None` means the group was created via the legacy Groups cluster,
157        /// which behaves like the `PerGroup` policy (such nodes join the
158        /// fabric+group-scoped multicast address) - the `PerGroup` policy
159        /// exists precisely for interop with them.
160        pub mcast_policy: Option<MulticastAddrPolicy>,
161    }
162
163    /// The multicast address policy of a group.
164    ///
165    /// The values are the ones of the Groupcast cluster.
166    #[derive(Debug, PartialEq, Eq, Copy, Clone, Hash, FromTLV, ToTLV)]
167    #[tlvargs(datatype = "u8")]
168    #[cfg_attr(feature = "defmt", derive(defmt::Format))]
169    #[repr(u8)]
170    pub enum MulticastAddrPolicy {
171        /// The group uses the IANA-assigned Groupcast multicast address.
172        #[enumval(0)]
173        IanaAddr = 0,
174        /// The group uses a multicast address computed from its fabric and group IDs.
175        #[enumval(1)]
176        PerGroup = 1,
177    }
178
179    impl GroupEndpointMapping {
180        /// Whether the group has auxiliary ACL entries generated for its
181        /// endpoints.
182        pub fn has_aux_acl(&self) -> bool {
183            self.has_aux_acl.unwrap_or(false)
184        }
185
186        /// The effective multicast-address policy of the group (legacy
187        /// Groups-cluster entries behave as `PerGroup`).
188        pub fn effective_mcast_policy(&self) -> MulticastAddrPolicy {
189            self.mcast_policy.unwrap_or(MulticastAddrPolicy::PerGroup)
190        }
191
192        /// Whether the group is managed by the Groupcast cluster (as opposed
193        /// to the legacy Groups cluster).
194        pub fn groupcast_managed(&self) -> bool {
195            self.mcast_policy.is_some()
196        }
197    }
198
199    /// A stored group key map entry (maps group ID to key set).
200    #[derive(Debug, Clone, Default, FromTLV, ToTLV)]
201    #[cfg_attr(feature = "defmt", derive(defmt::Format))]
202    pub struct GroupKeyMapping {
203        pub group_id: u16,
204        pub group_key_set_id: u16,
205    }
206
207    #[derive(Debug, FromTLV, ToTLV)]
208    #[cfg_attr(feature = "defmt", derive(defmt::Format))]
209    pub struct Groups {
210        /// Group key sets (excluding IPK which is stored in `ipk`)
211        key_sets: Vec<GroupKeySet, MAX_GROUP_KEYS_PER_FABRIC>,
212        /// Groups keyset mapping
213        key_map: Vec<GroupKeyMapping, MAX_GROUPS_PER_FABRIC>,
214        /// Group table (group ID → endpoints + name)
215        endpoint_mapping: Vec<GroupEndpointMapping, MAX_GROUPS_PER_FABRIC>,
216    }
217
218    impl Groups {
219        pub const fn new() -> Self {
220            Self {
221                key_sets: Vec::new(),
222                key_map: Vec::new(),
223                endpoint_mapping: Vec::new(),
224            }
225        }
226
227        pub fn init() -> impl Init<Self> {
228            init!(Self {
229                key_sets <- Vec::init(),
230                key_map <- Vec::init(),
231                endpoint_mapping <- Vec::init(),
232            })
233        }
234
235        /// Return an iterator over the group key sets of the fabric
236        pub fn key_set_iter(&self) -> impl Iterator<Item = &GroupKeySet> {
237            self.key_sets.iter()
238        }
239
240        /// Find a group key set by ID
241        pub fn key_set_get(&self, id: u16) -> Option<&GroupKeySet> {
242            self.key_sets.iter().find(|e| e.group_key_set_id == id)
243        }
244
245        /// Add or update a group key set
246        pub fn key_set_add(&mut self, entry: GroupKeySet) -> Result<(), Error> {
247            if let Some(existing) = self
248                .key_sets
249                .iter_mut()
250                .find(|e| e.group_key_set_id == entry.group_key_set_id)
251            {
252                *existing = entry;
253            } else {
254                self.key_sets
255                    .push(entry)
256                    .map_err(|_| ErrorCode::ResourceExhausted)?;
257            }
258            Ok(())
259        }
260
261        /// Remove a group key set by ID. Returns true if found and removed.
262        pub fn key_set_remove(&mut self, id: u16) -> Result<(), Error> {
263            let before = self.key_sets.len();
264            self.key_sets.retain(|e| e.group_key_set_id != id);
265            let removed = self.key_sets.len() < before;
266
267            self.key_map_remove_by_key_set(id);
268
269            // Check if element was actually removed
270            if removed {
271                Ok(())
272            } else {
273                Err(Error::new(ErrorCode::NotFound))
274            }
275        }
276
277        /// Append a group key map entry.
278        ///
279        /// A full map answers `Failure` rather than `ResourceExhausted`: that is
280        /// the status the CHIP SDK gives, and what its `TestGroupKeyManagementCluster`
281        /// expects, for the per-entry appends chip-tool turns a list write into.
282        pub fn key_map_add(&mut self, entry: GroupKeyMapping) -> Result<(), Error> {
283            self.key_map.push(entry).map_err(|_| ErrorCode::Failure)?;
284
285            Ok(())
286        }
287
288        /// Return an iterator over the group key map entries of the fabric
289        pub fn key_map_iter(&self) -> impl Iterator<Item = &GroupKeyMapping> {
290            self.key_map.iter()
291        }
292
293        /// Replace all group key map entries
294        pub fn key_map_replace(
295            &mut self,
296            entries: impl Iterator<Item = GroupKeyMapping>,
297        ) -> Result<(), Error> {
298            self.key_map.clear();
299            for entry in entries {
300                self.key_map
301                    .push(entry)
302                    .map_err(|_| ErrorCode::ResourceExhausted)?;
303            }
304            Ok(())
305        }
306
307        /// Remove group key map entries that reference a specific key set ID
308        pub fn key_map_remove_by_key_set(&mut self, key_set_id: u16) {
309            self.key_map.retain(|e| e.group_key_set_id != key_set_id);
310        }
311
312        /// Return an iterator over the group table entries
313        pub fn iter(&self) -> impl Iterator<Item = &GroupEndpointMapping> {
314            self.endpoint_mapping.iter()
315        }
316
317        /// Look up a group by ID
318        pub fn get(&self, group_id: u16) -> Option<&GroupEndpointMapping> {
319            self.endpoint_mapping
320                .iter()
321                .find(|e| e.group_id == group_id)
322        }
323
324        /// Look up a group by ID, mutably
325        pub fn get_mut(&mut self, group_id: u16) -> Option<&mut GroupEndpointMapping> {
326            self.endpoint_mapping
327                .iter_mut()
328                .find(|e| e.group_id == group_id)
329        }
330
331        /// Add an endpoint to a group.
332        /// Returns true if the endpoint was already a member (name still updated per spec).
333        pub fn add(
334            &mut self,
335            endpoint_id: u16,
336            group_id: u16,
337            group_name: &str,
338        ) -> Result<bool, Error> {
339            // Validate the name up-front, so that a rejected command leaves the table untouched
340            let group_name =
341                String::from_str(group_name).map_err(|_| ErrorCode::ConstraintError)?;
342
343            let entry = if let Some(entry) = self
344                .endpoint_mapping
345                .iter_mut()
346                .find(|e| e.group_id == group_id)
347            {
348                entry
349            } else {
350                self.endpoint_mapping
351                    .push(GroupEndpointMapping {
352                        group_id,
353                        endpoints: Vec::new(),
354                        group_name: group_name.clone(),
355                        has_aux_acl: None,
356                        mcast_policy: None,
357                    })
358                    .map_err(|_| ErrorCode::ResourceExhausted)?;
359                unwrap!(self.endpoint_mapping.last_mut())
360            };
361
362            // Update group name
363            entry.group_name = group_name;
364
365            if entry.endpoints.contains(&endpoint_id) {
366                return Ok(true);
367            }
368
369            entry
370                .endpoints
371                .push(endpoint_id)
372                .map_err(|_| ErrorCode::ResourceExhausted)?;
373
374            Ok(false)
375        }
376
377        /// Remove an endpoint from a group, or from all groups if `group_id` is `None`.
378        /// Returns true if the endpoint was removed from at least one group.
379        pub fn remove(&mut self, endpoint_id: u16, group_id: Option<u16>) -> bool {
380            let mut removed = false;
381
382            for entry in self.endpoint_mapping.iter_mut() {
383                if group_id.is_some_and(|id| id != entry.group_id) {
384                    continue;
385                }
386                let before = entry.endpoints.len();
387                entry.endpoints.retain(|&ep| ep != endpoint_id);
388                if entry.endpoints.len() < before {
389                    removed = true;
390                }
391            }
392
393            // Remove entries with no endpoints left - except Groupcast-managed
394            // ones, which may legitimately exist with no endpoints (a
395            // sender-only membership); the Groupcast cluster removes those
396            // explicitly via its `LeaveGroup` command.
397            self.endpoint_mapping
398                .retain(|e| !e.endpoints.is_empty() || e.groupcast_managed());
399
400            removed
401        }
402
403        /// Join endpoints to a group on behalf of the Groupcast cluster,
404        /// creating the membership if it does not exist.
405        ///
406        /// - `endpoints`: the endpoints to add (may be empty for a
407        ///   sender-only membership); duplicates are omitted;
408        /// - `replace`: when `true`, the given endpoints replace the
409        ///   existing list instead of being appended;
410        /// - `mcast_policy`: the multicast-address policy; applied on
411        ///   creation, or updated when `Some` on an existing membership.
412        ///
413        /// Errors with `ResourceExhausted` when the membership or endpoint
414        /// capacity is exceeded; the membership is left unchanged in that
415        /// case, except that a possibly-performed `replace` clearing is
416        /// rolled back by restoring nothing (the caller re-checks capacity
417        /// upfront via [`Self::group_count`] and the endpoint capacity).
418        pub fn groupcast_join(
419            &mut self,
420            group_id: u16,
421            endpoints: &[u16],
422            replace: bool,
423            mcast_policy: Option<MulticastAddrPolicy>,
424        ) -> Result<(), Error> {
425            let entry = if let Some(entry) = self
426                .endpoint_mapping
427                .iter_mut()
428                .find(|e| e.group_id == group_id)
429            {
430                entry
431            } else {
432                self.endpoint_mapping
433                    .push(GroupEndpointMapping {
434                        group_id,
435                        endpoints: Vec::new(),
436                        group_name: String::new(),
437                        has_aux_acl: Some(false),
438                        mcast_policy: Some(mcast_policy.unwrap_or(MulticastAddrPolicy::IanaAddr)),
439                    })
440                    .map_err(|_| ErrorCode::ResourceExhausted)?;
441                unwrap!(self.endpoint_mapping.last_mut())
442            };
443
444            // Joining via Groupcast upgrades a legacy entry to
445            // Groupcast-managed (the default policy matches the legacy
446            // behavior)
447            if entry.mcast_policy.is_none() {
448                entry.mcast_policy = Some(MulticastAddrPolicy::PerGroup);
449            }
450
451            if let Some(mcast_policy) = mcast_policy {
452                entry.mcast_policy = Some(mcast_policy);
453            }
454
455            if replace {
456                entry.endpoints.clear();
457            }
458
459            for endpoint in endpoints {
460                if !entry.endpoints.contains(endpoint) {
461                    entry
462                        .endpoints
463                        .push(*endpoint)
464                        .map_err(|_| ErrorCode::ResourceExhausted)?;
465                }
466            }
467
468            Ok(())
469        }
470
471        /// Remove a whole group membership. Returns `true` if it existed.
472        pub fn groupcast_remove(&mut self, group_id: u16) -> bool {
473            let before = self.endpoint_mapping.len();
474            self.endpoint_mapping.retain(|e| e.group_id != group_id);
475
476            before != self.endpoint_mapping.len()
477        }
478
479        /// Set the `has_aux_acl` flag of a group membership.
480        /// Returns `true` if the flag changed.
481        pub fn set_has_aux_acl(&mut self, group_id: u16, has_aux_acl: bool) -> bool {
482            let Some(entry) = self
483                .endpoint_mapping
484                .iter_mut()
485                .find(|e| e.group_id == group_id)
486            else {
487                return false;
488            };
489
490            let changed = entry.has_aux_acl() != has_aux_acl;
491            entry.has_aux_acl = Some(has_aux_acl);
492
493            changed
494        }
495
496        /// The number of group memberships of this fabric.
497        pub fn group_count(&self) -> usize {
498            self.endpoint_mapping.len()
499        }
500
501        /// Look up the key set ID mapped to a group, if any.
502        pub fn key_map_get(&self, group_id: u16) -> Option<u16> {
503            self.key_map
504                .iter()
505                .find(|e| e.group_id == group_id)
506                .map(|e| e.group_key_set_id)
507        }
508
509        /// Map a group to a key set, replacing any previous mapping of that
510        /// group.
511        pub fn key_map_set_group(&mut self, group_id: u16, key_set_id: u16) -> Result<(), Error> {
512            if let Some(entry) = self.key_map.iter_mut().find(|e| e.group_id == group_id) {
513                entry.group_key_set_id = key_set_id;
514                return Ok(());
515            }
516
517            self.key_map
518                .push(GroupKeyMapping {
519                    group_id,
520                    group_key_set_id: key_set_id,
521                })
522                .map_err(|_| ErrorCode::ResourceExhausted.into())
523        }
524
525        /// Remove all key-set mappings of the given group.
526        pub fn key_map_remove_group(&mut self, group_id: u16) {
527            self.key_map.retain(|e| e.group_id != group_id);
528        }
529    }
530
531    impl Default for Groups {
532        fn default() -> Self {
533            Self::new()
534        }
535    }
536
537    impl InitDefault for Groups {
538        fn init_default() -> impl Init<Self> {
539            Self::init()
540        }
541    }
542}
543
544#[cfg(feature = "groups")]
545pub use groups::*;
546
547/// Fabric type
548#[derive(Debug, ToTLV, FromTLV)]
549#[cfg_attr(feature = "defmt", derive(defmt::Format))]
550pub struct Fabric {
551    /// Fabric local index
552    fab_idx: NonZeroU8,
553    /// Fabric node ID
554    node_id: u64,
555    /// Fabric ID
556    fabric_id: u64,
557    /// Vendor ID
558    vendor_id: u16,
559    /// Compressed ID
560    compressed_fabric_id: u64,
561    /// Fabric secret key
562    secret_key: CanonPkcSecretKey,
563    /// Root CA certificate to be used when verifying the node's certificate
564    ///
565    /// Note that we deviate from the Matter spec here, in that we store the
566    /// root certificate in the Fabric type itself, rather than - as the
567    /// spec mandates - in a separate Root CA store
568    ///
569    /// This simplifies the implementation, but results in potentially multiple
570    /// copies of the same Root CA used accross multiple fabrics.
571    root_ca: Vec<u8, { MAX_CERT_TLV_LEN }>,
572    /// Either the Intermediate CA certificate (`vvsc_set == false`) or the
573    /// Vendor Verification Signing Cert (`vvsc_set == true`). The two are
574    /// mutually exclusive in the cert chain (Matter Core spec) —
575    /// a fabric with an ICAC cannot also carry a VVSC and vice
576    /// versa — so we share one buffer instead of paying for both. Empty
577    /// means neither is set; in that case `vvsc_set` is meaningless.
578    icac_or_vvsc: Vec<u8, { MAX_CERT_TLV_LEN }>,
579    /// Selector for what `icac_or_vvsc` holds: `false` for an ICAC,
580    /// `true` for a VVSC.
581    vvsc_set: bool,
582    /// Node Operational Certificate
583    noc: Vec<u8, { MAX_CERT_TLV_LEN }>,
584    /// Identity Protection Key
585    ipk: KeySet,
586    /// Fabric label; unique accross all fabrics on the device
587    label: String<32>,
588    /// Access Control List
589    acl: Vec<AclEntry, { acl::MAX_ACL_ENTRIES_PER_FABRIC }>,
590    /// Fabric group information.
591    #[cfg(feature = "groups")]
592    #[tagval(13)]
593    groups: Skippable<Groups>,
594    /// VID Verification Statement (Matter Core spec).
595    /// Either empty (not set) or exactly `VID_VERIFICATION_STATEMENT_LEN`
596    /// bytes long; the cluster XML enforces both bounds at the schema
597    /// level (`length="85" minLength="85"`).
598    #[tagval(14)]
599    vid_verification_statement: Vec<u8, VID_VERIFICATION_STATEMENT_LEN>,
600}
601
602/// Exact length of a non-empty VID Verification Statement.
603/// Matches `length="85" minLength="85"` on
604/// `OperationalCredentials::SetVIDVerificationStatement.vid_verification_statement`.
605pub const VID_VERIFICATION_STATEMENT_LEN: usize = 85;
606
607impl Fabric {
608    /// Return an in-place-initializer for a Fabric type, with the
609    /// provided Fabric Index and KeyPair
610    ///
611    /// All other fields are initialized to default values, which are NOT
612    /// valid for the operation of the fabric.
613    ///
614    /// The Fabric must be updated with the correct values before it can be
615    /// used, via `Fabric::update`.
616    fn init(fab_idx: NonZeroU8) -> impl Init<Self> {
617        // NOTE: the `init!` macro does not accept `#[cfg]` on its field entries,
618        // so the `groups` field (present only under the `groups` feature) forces
619        // two variants of the initializer that differ solely by that last field.
620        #[cfg(feature = "groups")]
621        let r = init!(Self {
622            fab_idx,
623            node_id: 0,
624            fabric_id: 0,
625            vendor_id: 0,
626            compressed_fabric_id: 0,
627            secret_key <- CanonPkcSecretKey::init(),
628            root_ca <- Vec::init(),
629            icac_or_vvsc <- Vec::init(),
630            vvsc_set: false,
631            noc <- Vec::init(),
632            ipk <- KeySet::init(),
633            label: String::new(),
634            acl <- Vec::init(),
635            vid_verification_statement <- Vec::init(),
636            groups <- Skippable::init_default(),
637        });
638
639        #[cfg(not(feature = "groups"))]
640        let r = init!(Self {
641            fab_idx,
642            node_id: 0,
643            fabric_id: 0,
644            vendor_id: 0,
645            compressed_fabric_id: 0,
646            secret_key <- CanonPkcSecretKey::init(),
647            root_ca <- Vec::init(),
648            icac_or_vvsc <- Vec::init(),
649            vvsc_set: false,
650            noc <- Vec::init(),
651            ipk <- KeySet::init(),
652            label: String::new(),
653            acl <- Vec::init(),
654            vid_verification_statement <- Vec::init(),
655        });
656        r
657    }
658
659    /// Update the fabric with the provided data so that it can operate.
660    ///
661    /// This method is supposed to be called right after `Fabric::init` or
662    /// when the NOC of the fabric needs to be updated.
663    ///
664    /// `root_ca` is `None` when called from the `UpdateNOC` flow — Matter
665    /// Core spec keeps the fabric's root cert unchanged
666    /// across `UpdateNOC`, and re-passing the existing bytes here would
667    /// require a (large) caller-side copy of `self.root_ca`. `Some(...)`
668    /// is used by the initial `AddNOC` flow, where the cert was just
669    /// staged in the fail-safe context.
670    #[allow(clippy::too_many_arguments)]
671    fn update<C: Crypto>(
672        &mut self,
673        crypto: C,
674        root_ca: Option<&[u8]>,
675        noc: &[u8],
676        icac: &[u8],
677        secret_key: CanonPkcSecretKeyRef<'_>,
678        epoch_key: Option<CanonAeadKeyRef<'_>>,
679        vendor_id: Option<u16>,
680        case_admin_subject: Option<u64>,
681    ) -> Result<(), Error> {
682        if let Some(root_ca) = root_ca {
683            self.root_ca.clear();
684            self.root_ca
685                .extend_from_slice(root_ca)
686                .map_err(|_| ErrorCode::BufferTooSmall)?;
687        }
688        // `AddNOC` / `UpdateNOC` always replace the cert chain, so any
689        // previously-staged VVSC for this fabric is implicitly cleared
690        // here — the spec doesn't allow an ICAC and a VVSC to coexist.
691        self.icac_or_vvsc.clear();
692        self.icac_or_vvsc
693            .extend_from_slice(icac)
694            .map_err(|_| ErrorCode::BufferTooSmall)?;
695        self.vvsc_set = false;
696        self.noc.clear();
697        self.noc
698            .extend_from_slice(noc)
699            .map_err(|_| ErrorCode::BufferTooSmall)?;
700
701        let root_cert = CertRef::new(TLVElement::new(self.root_ca.as_slice()));
702        let noc_cert = CertRef::new(TLVElement::new(noc));
703
704        self.node_id = noc_cert.get_node_id()?;
705        self.fabric_id = noc_cert.get_fabric_id()?;
706        self.compressed_fabric_id = Self::compute_compressed_fabric_id(
707            &crypto,
708            root_cert.pubkey()?.try_into()?,
709            self.fabric_id,
710        );
711
712        if let Some(epoch_key) = epoch_key {
713            self.ipk
714                .update(&crypto, epoch_key, &self.compressed_fabric_id)?;
715        }
716
717        if let Some(vendor_id) = vendor_id {
718            self.vendor_id = vendor_id;
719        }
720
721        if let Some(case_admin_subject) = case_admin_subject {
722            self.acl.clear();
723            self.acl.push_init(
724                AclEntry::init(None, Privilege::ADMIN, AuthMode::Case)
725                    .into_fallible()
726                    .chain(|e| {
727                        e.fab_idx = Some(self.fab_idx);
728                        e.add_subject(case_admin_subject)
729                    }),
730                || ErrorCode::ResourceExhausted.into(),
731            )?;
732        }
733
734        self.secret_key.load(secret_key);
735
736        Ok(())
737    }
738
739    /// Is the fabric matching the privided destination ID
740    pub fn is_dest_id<C: Crypto>(
741        &self,
742        crypto: C,
743        random: &[u8],
744        target: &[u8],
745    ) -> Result<(), Error> {
746        let mut mac = crypto.hmac(self.ipk.op_key())?;
747
748        mac.update(random)?;
749        mac.update(CertRef::new(TLVElement::new(self.root_ca())).pubkey()?)?;
750
751        mac.update(&self.fabric_id.to_le_bytes())?;
752        mac.update(&self.node_id.to_le_bytes())?;
753
754        let mut id = MaybeUninit::<Hash>::uninit(); // TODO MEDIUM BUFFER
755        let id = id.init_with(Hash::init());
756        mac.finish(id)?;
757        if id.access() == target {
758            Ok(())
759        } else {
760            Err(ErrorCode::NotFound.into())
761        }
762    }
763
764    /// Compute the destination identifier for a target node on this fabric.
765    ///
766    /// Used by the CASE initiator to build Sigma1 (spec).
767    /// destinationMessage = initiatorRandom || rootPublicKey || fabricId(LE) || nodeId(LE)
768    /// destinationIdentifier = Crypto_HMAC(key=IPK, message=destinationMessage)
769    ///
770    /// # Arguments
771    /// - `target_node_id`: The node ID of the destination (peer) node, NOT the local node.
772    pub fn compute_dest_id<C: Crypto>(
773        &self,
774        crypto: C,
775        random: &[u8],
776        target_node_id: u64,
777        out: &mut Hash,
778    ) -> Result<(), Error> {
779        let mut mac = crypto.hmac(self.ipk.op_key())?;
780
781        mac.update(random)?;
782        mac.update(CertRef::new(TLVElement::new(self.root_ca())).pubkey()?)?;
783        mac.update(&self.fabric_id.to_le_bytes())?;
784        mac.update(&target_node_id.to_le_bytes())?;
785
786        mac.finish(out)?;
787        Ok(())
788    }
789
790    /// Return the secret key of the fabric
791    pub fn secret_key(&self) -> CanonPkcSecretKeyRef<'_> {
792        self.secret_key.reference()
793    }
794
795    /// Return the fabric's node ID
796    pub fn node_id(&self) -> u64 {
797        self.node_id
798    }
799
800    /// Return the fabric's fabric ID
801    pub fn fabric_id(&self) -> u64 {
802        self.fabric_id
803    }
804
805    /// Return the fabric's local index
806    pub fn fab_idx(&self) -> NonZeroU8 {
807        self.fab_idx
808    }
809
810    /// Return the fabric's compressed fabric ID
811    pub fn compressed_fabric_id(&self) -> u64 {
812        self.compressed_fabric_id
813    }
814
815    /// Return the fabric's Vendor ID
816    pub fn vendor_id(&self) -> u16 {
817        self.vendor_id
818    }
819
820    /// Return the fabric's label
821    pub fn label(&self) -> &str {
822        &self.label
823    }
824
825    /// Return the fabric's Root CA in encoded TLV form
826    ///
827    /// Use `CertRef` to decode on the fly
828    pub fn root_ca(&self) -> &[u8] {
829        &self.root_ca
830    }
831
832    /// Return the fabric's ICAC in encoded TLV form
833    ///
834    /// Use `CertRef` to decode on the fly.
835    ///
836    /// Note that this method might return an empty slice,
837    /// which indicates that this fabric does not have an ICAC.
838    /// (The shared `icac_or_vvsc` slot may instead hold a VVSC; see
839    /// `vvsc()`.)
840    pub fn icac(&self) -> &[u8] {
841        if self.vvsc_set {
842            &[]
843        } else {
844            &self.icac_or_vvsc
845        }
846    }
847
848    /// Return the fabric's NOC
849    pub fn noc(&self) -> &[u8] {
850        &self.noc
851    }
852
853    /// Return the fabric's IPK
854    pub fn ipk(&self) -> &KeySet {
855        &self.ipk
856    }
857
858    /// Return the fabric's groups, or an empty group state if this fabric was
859    /// persisted before the `groups` field existed (see [`Fabric::groups`]).
860    #[cfg(feature = "groups")]
861    pub fn groups(&self) -> &Groups {
862        self.groups.value()
863    }
864
865    /// Return a mutable reference to the fabric's groups, materializing empty
866    /// group state on first access if it was absent.
867    #[cfg(feature = "groups")]
868    pub fn groups_mut(&mut self) -> &mut Groups {
869        self.groups.value_mut()
870    }
871
872    /// Return the fabric's VVSC bytes (Matter Core spec).
873    /// Empty when `SetVIDVerificationStatement` has never been called with
874    /// a non-empty VVSC for this fabric, or when the fabric instead carries
875    /// an ICAC (see `icac()`) — VVSC and ICAC share storage and are
876    /// mutually exclusive per spec.
877    pub fn vvsc(&self) -> &[u8] {
878        if self.vvsc_set {
879            &self.icac_or_vvsc
880        } else {
881            &[]
882        }
883    }
884
885    /// Return the fabric's VID Verification Statement bytes (Matter Core
886    /// spec). Either empty (not set) or
887    /// exactly `VID_VERIFICATION_STATEMENT_LEN` bytes.
888    pub fn vid_verification_statement(&self) -> &[u8] {
889        &self.vid_verification_statement
890    }
891
892    /// Apply a `SetVIDVerificationStatement` mutation to the fabric. Each
893    /// field is `Some(slice)` for "replace with this value" (where an
894    /// empty slice clears the value), or `None` for "leave unchanged".
895    /// The caller is responsible for spec-level validation (size limits,
896    /// VVSC vs ICAC mutual exclusion, "all fields absent" → INVALID_COMMAND,
897    /// VendorID range, …); this method only enforces the storage
898    /// invariants (`Vec` capacity).
899    pub fn set_vid_verification(
900        &mut self,
901        vendor_id: Option<u16>,
902        vid_verification_statement: Option<&[u8]>,
903        vvsc: Option<&[u8]>,
904    ) -> Result<(), Error> {
905        if let Some(vid) = vendor_id {
906            self.vendor_id = vid;
907        }
908
909        if let Some(vvs) = vid_verification_statement {
910            self.vid_verification_statement.clear();
911            self.vid_verification_statement
912                .extend_from_slice(vvs)
913                .map_err(|_| ErrorCode::BufferTooSmall)?;
914        }
915
916        if let Some(v) = vvsc {
917            // VVSC and ICAC share `icac_or_vvsc`. Clearing the VVSC must
918            // not stomp on an existing ICAC: per spec the
919            // two never coexist on the same fabric, so an empty-VVSC
920            // request against a fabric that holds an ICAC is a no-op
921            // here. The cluster handler still rejects a *non-empty* VVSC
922            // against such a fabric upstream.
923            if !v.is_empty() {
924                self.icac_or_vvsc.clear();
925                self.icac_or_vvsc
926                    .extend_from_slice(v)
927                    .map_err(|_| ErrorCode::BufferTooSmall)?;
928                self.vvsc_set = true;
929            } else if self.vvsc_set {
930                self.icac_or_vvsc.clear();
931                self.vvsc_set = false;
932            }
933        }
934
935        Ok(())
936    }
937
938    /// Return the ACL entries of the fabric
939    pub fn acl(&self) -> &[AclEntry] {
940        &self.acl
941    }
942
943    /// Return an iterator over the ACL entries of the fabric
944    pub fn acl_iter(&self) -> impl Iterator<Item = &AclEntry> {
945        self.acl.iter()
946    }
947
948    /// Add a new ACL entry to the fabric.
949    ///
950    /// Return the index of the added entry.
951    pub fn acl_add(&mut self, mut entry: AclEntry) -> Result<usize, Error> {
952        if entry.auth_mode() == AuthMode::Pase {
953            // Reserved for future use
954            Err(ErrorCode::ConstraintError)?;
955        }
956
957        // Overwrite the fabric index with our accessing fabric index
958        entry.fab_idx = Some(self.fab_idx);
959
960        self.acl
961            .push(entry)
962            .map_err(|_| ErrorCode::ResourceExhausted)?;
963
964        Ok(self.acl.len() - 1)
965    }
966
967    /// Add a new ACL entry to the fabric using the supplied initializer.
968    ///
969    /// Return the index of the added entry.
970    pub fn acl_add_init<I>(&mut self, init: I) -> Result<usize, Error>
971    where
972        I: Init<AclEntry, Error>,
973    {
974        self.acl
975            .push_init(init, || ErrorCode::ResourceExhausted.into())?;
976
977        let idx = self.acl.len() - 1;
978
979        if self.acl[idx].auth_mode() == AuthMode::Pase {
980            // Reserved for future use
981            self.acl.pop();
982            Err(ErrorCode::ConstraintError)?;
983        }
984
985        let entry = &mut self.acl[idx];
986
987        // Overwrite the fabric index with our accessing fabric index
988        entry.fab_idx = Some(self.fab_idx);
989
990        Ok(idx)
991    }
992
993    /// Update an existing ACL entry in the fabric
994    pub fn acl_update(&mut self, idx: usize, mut entry: AclEntry) -> Result<(), Error> {
995        if self.acl.len() <= idx {
996            return Err(ErrorCode::NotFound.into());
997        }
998
999        // Overwrite the fabric index with our accessing fabric index
1000        entry.fab_idx = Some(self.fab_idx);
1001
1002        self.acl[idx] = entry;
1003
1004        Ok(())
1005    }
1006
1007    /// Update an existing ACL entry in the fabric using the supplied initializer
1008    pub fn acl_update_init<I>(&mut self, idx: usize, init: I) -> Result<(), Error>
1009    where
1010        I: Init<AclEntry, Error>,
1011    {
1012        if self.acl.len() <= idx {
1013            return Err(ErrorCode::NotFound.into());
1014        }
1015
1016        // TODO: Needs #214
1017        let mut entry = MaybeUninit::uninit();
1018        let entry = entry.try_init_with(init)?.clone();
1019
1020        self.acl[idx] = entry;
1021
1022        // Overwrite the fabric index with our accessing fabric index
1023        self.acl[idx].fab_idx = Some(self.fab_idx);
1024
1025        Ok(())
1026    }
1027
1028    /// Remove an ACL entry from the fabric
1029    pub fn acl_remove(&mut self, idx: usize) -> Result<(), Error> {
1030        if self.acl.len() <= idx {
1031            return Err(ErrorCode::NotFound.into());
1032        }
1033
1034        self.acl.remove(idx);
1035
1036        Ok(())
1037    }
1038
1039    /// Remove all ACL entries from the fabric
1040    pub fn acl_remove_all(&mut self) {
1041        // pub for tests
1042        self.acl.clear();
1043    }
1044
1045    /// Check if the fabric allows the given access request
1046    ///
1047    /// Note that the fabric index in the access request needs to be checked before that.
1048    /// `aux_acl_enabled` conveys whether the node advertises the Access Control
1049    /// cluster's `AUXILIARY` feature - see `AclEntry::allow`.
1050    fn allow(&self, req: &AccessReq, aux_acl_enabled: bool) -> bool {
1051        for e in &self.acl {
1052            if e.allow(req, aux_acl_enabled) {
1053                return true;
1054            }
1055        }
1056
1057        debug!(
1058            "ACL Disallow for subjects {} fab idx {}",
1059            req.accessor().subjects(),
1060            req.accessor().fab_idx
1061        );
1062
1063        false
1064    }
1065
1066    /// The compressed fabric ID of the fabric with root public key
1067    /// `root_pubkey` and fabric ID `fabric_id`: what its nodes advertise over
1068    /// mDNS.
1069    pub fn compute_compressed_fabric_id<C: Crypto>(
1070        crypto: C,
1071        root_pubkey: CanonPkcPublicKeyRef<'_>,
1072        fabric_id: u64,
1073    ) -> u64 {
1074        const COMPRESSED_FABRIC_ID_INFO: &[u8; 16] = &[
1075            0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73, 0x73, 0x65, 0x64, 0x46, 0x61, 0x62, 0x72,
1076            0x69, 0x63,
1077        ];
1078
1079        let mut compressed_fabric_id = CryptoSensitive::<{ COMPRESSED_FABRIC_ID_LEN }>::new();
1080        unwrap!(unwrap!(crypto.kdf()).expand(
1081            &fabric_id.to_be_bytes(),
1082            root_pubkey.split::<1, { PKC_CANON_PUBLIC_KEY_LEN - 1 }>().1,
1083            COMPRESSED_FABRIC_ID_INFO,
1084            &mut compressed_fabric_id,
1085        ));
1086
1087        u64::from_be_bytes(*compressed_fabric_id.access())
1088    }
1089}
1090
1091cfg_if! {
1092    if #[cfg(feature = "max-fabrics-32")] {
1093        /// Max number of supported fabrics
1094        pub const MAX_FABRICS: usize = 32;
1095    } else if #[cfg(feature = "max-fabrics-16")] {
1096        /// Max number of supported fabrics
1097        pub const MAX_FABRICS: usize = 16;
1098    } else if #[cfg(feature = "max-fabrics-8")] {
1099        /// Max number of supported fabrics
1100        pub const MAX_FABRICS: usize = 8;
1101    } else if #[cfg(feature = "max-fabrics-7")] {
1102        /// Max number of supported fabrics
1103        pub const MAX_FABRICS: usize = 7;
1104    } else if #[cfg(feature = "max-fabrics-6")] {
1105        /// Max number of supported fabrics
1106        pub const MAX_FABRICS: usize = 6;
1107    } else if #[cfg(feature = "max-fabrics-5")] {
1108        /// Max number of supported fabrics
1109        pub const MAX_FABRICS: usize = 5;
1110    } else if #[cfg(feature = "max-fabrics-4")] {
1111        /// Max number of supported fabrics
1112        pub const MAX_FABRICS: usize = 4;
1113    } else if #[cfg(feature = "max-fabrics-3")] {
1114        /// Max number of supported fabrics
1115        pub const MAX_FABRICS: usize = 3;
1116    } else if #[cfg(feature = "max-fabrics-2")] {
1117        /// Max number of supported fabrics
1118        pub const MAX_FABRICS: usize = 2;
1119    } else if #[cfg(feature = "max-fabrics-1")] {
1120        /// Max number of supported fabrics
1121        pub const MAX_FABRICS: usize = 1;
1122    } else { // Matter requires a minimum of 5 fabrics
1123        /// Max number of supported fabrics
1124        pub const MAX_FABRICS: usize = 5;
1125    }
1126}
1127
1128/// All fabrics
1129pub struct Fabrics {
1130    fabrics: Vec<Fabric, MAX_FABRICS>,
1131    /// The indices of the persisted fabrics that could not be loaded, one bit
1132    /// each. Never reallocated: state kept for them outside of the fabric (CASE
1133    /// resumption records, bindings, ...) would pass to the new fabric.
1134    unloaded: [u8; 32],
1135    /// The first index tried for the next added fabric. Indices are handed out
1136    /// in increasing order, wrapping around after [`MAX_FAB_IDX`], so that the
1137    /// index of a removed fabric is not reused soon.
1138    next_fab_idx: NonZeroU8,
1139}
1140
1141impl Default for Fabrics {
1142    fn default() -> Self {
1143        Self::new()
1144    }
1145}
1146
1147impl Fabrics {
1148    /// Create a new Fabrics instance
1149    #[inline(always)]
1150    pub const fn new() -> Self {
1151        Self {
1152            fabrics: Vec::new(),
1153            unloaded: [0; 32],
1154            next_fab_idx: NonZeroU8::MIN,
1155        }
1156    }
1157
1158    /// Return an in-place-initializer for a Fabrics type
1159    pub fn init() -> impl Init<Self> {
1160        init!(Self {
1161            fabrics <- Vec::init(),
1162            unloaded: [0; 32],
1163            next_fab_idx: NonZeroU8::MIN,
1164        })
1165    }
1166
1167    /// Remove all fabrics
1168    pub fn reset(&mut self) {
1169        self.fabrics.clear();
1170        self.unloaded = [0; 32];
1171        self.next_fab_idx = NonZeroU8::MIN;
1172    }
1173
1174    /// Remove all fabrics from the provided BLOB store as well as from memory.
1175    ///
1176    /// # Arguments
1177    /// - `store`: the BLOB store to remove the fabrics from
1178    /// - `buf`: a temporary buffer to use for removing the fabrics
1179    pub fn reset_persist<S: KvBlobStore>(
1180        &mut self,
1181        mut store: S,
1182        buf: &mut [u8],
1183    ) -> Result<(), Error> {
1184        self.reset();
1185
1186        let mut result = Ok(());
1187
1188        for idx in 1..=255u8 {
1189            result = result.and(store.remove(FABRIC_KEYS_START + idx as u16, buf));
1190        }
1191
1192        result = result.and(store.remove(NEXT_FABRIC_INDEX_KEY, buf));
1193
1194        if result.is_ok() {
1195            info!("Removed all fabrics from storage");
1196        }
1197
1198        result
1199    }
1200
1201    /// Load all fabrics from the provided BLOB store
1202    ///
1203    /// # Arguments
1204    /// - `store`: the BLOB store to load the fabrics from
1205    /// - `buf`: a temporary buffer to use for loading the fabrics
1206    pub fn load_persist<S: KvBlobStore>(
1207        &mut self,
1208        mut store: S,
1209        buf: &mut [u8],
1210    ) -> Result<(), Error> {
1211        self.reset();
1212
1213        for fab_idx in 1..=255u8 {
1214            self.add_load(fab_idx, &mut store, buf)?;
1215        }
1216
1217        let next_fab_idx = load_logged(&mut store, NEXT_FABRIC_INDEX_KEY, buf, |data| {
1218            NonZeroU8::new(TLVElement::new(data).u8()?)
1219                .filter(|fab_idx| fab_idx.get() <= MAX_FAB_IDX)
1220                .ok_or(ErrorCode::Invalid.into())
1221        });
1222
1223        self.next_fab_idx = match next_fab_idx {
1224            Ok(Some(fab_idx)) => fab_idx,
1225            // Not stored (e.g. by an older version), or unreadable: the one
1226            // after the largest index taken
1227            _ => Self::fab_idx_after(
1228                (1..=MAX_FAB_IDX)
1229                    .rev()
1230                    .find(|fab_idx| self.is_taken(*fab_idx))
1231                    .unwrap_or(0),
1232            ),
1233        };
1234
1235        Ok(())
1236    }
1237
1238    /// Load the fabric with index `fab_idx` from `store`, if persisted.
1239    ///
1240    /// A fabric that cannot be loaded is skipped, with its index kept reserved.
1241    pub fn add_load<S: KvBlobStore>(
1242        &mut self,
1243        fab_idx: u8,
1244        mut store: S,
1245        buf: &mut [u8],
1246    ) -> Result<(), Error> {
1247        let loaded = load_logged(
1248            &mut store,
1249            FABRIC_KEYS_START + fab_idx as u16,
1250            buf,
1251            |data| {
1252                self.fabrics
1253                    .push_init(Fabric::init_from_tlv(TLVElement::new(data)), || {
1254                        TlvErrorCode::CapacityExceeded.into()
1255                    })
1256                    .map_err(Into::into)
1257            },
1258        );
1259
1260        match loaded {
1261            Ok(Some(())) => {
1262                let fabric = unwrap!(self.fabrics.last());
1263
1264                info!(
1265                    "Loaded fabric {} with ID {:x} from storage",
1266                    fabric.fab_idx(),
1267                    fabric.compressed_fabric_id()
1268                );
1269            }
1270            Ok(None) => (),
1271            Err(_) => self.unloaded[fab_idx as usize / 8] |= 1 << (fab_idx % 8),
1272        }
1273
1274        Ok(())
1275    }
1276
1277    /// Whether the index `fab_idx` is taken by a fabric, loaded or not.
1278    fn is_taken(&self, fab_idx: u8) -> bool {
1279        self.unloaded[fab_idx as usize / 8] & (1 << (fab_idx % 8)) != 0
1280            || self.iter().any(|fabric| fabric.fab_idx().get() == fab_idx)
1281    }
1282
1283    /// The fabric index after `fab_idx` (or the first one, for 0).
1284    fn fab_idx_after(fab_idx: u8) -> NonZeroU8 {
1285        unwrap!(NonZeroU8::new(fab_idx % MAX_FAB_IDX + 1))
1286    }
1287
1288    /// The first index tried for the next added fabric.
1289    ///
1290    /// To be persisted with [`FabricPersist::store_next_fab_idx`] whenever a
1291    /// fabric is committed to or removed from storage.
1292    pub fn next_fab_idx(&self) -> NonZeroU8 {
1293        self.next_fab_idx
1294    }
1295
1296    /// Add a new fabric to the fabrics with the provided data and immediately updates it with the provided post-init updater.
1297    ///
1298    /// This method is unlikely to be useful outside of tests.
1299    ///
1300    /// If this operation succeeds, the fabric immediately becomes operational.
1301    pub fn add_with_post_init<F>(&mut self, post_init: F) -> Result<&mut Fabric, Error>
1302    where
1303        F: FnOnce(&mut Fabric) -> Result<(), Error>,
1304    {
1305        let mut fab_idx = self.next_fab_idx;
1306
1307        while self.is_taken(fab_idx.get()) {
1308            fab_idx = Self::fab_idx_after(fab_idx.get());
1309
1310            if fab_idx == self.next_fab_idx {
1311                return Err(ErrorCode::ResourceExhausted.into());
1312            }
1313        }
1314
1315        self.fabrics.push_init(
1316            Fabric::init(fab_idx)
1317                .into_fallible::<Error>()
1318                .chain(post_init),
1319            || ErrorCode::ResourceExhausted.into(),
1320        )?;
1321
1322        self.next_fab_idx = Self::fab_idx_after(fab_idx.get());
1323
1324        let fabric = unwrap!(self.fabrics.last_mut());
1325
1326        Ok(fabric)
1327    }
1328
1329    /// Add a new fabric to the fabrics with the provided data.
1330    ///
1331    /// If this operation succeeds, the fabric immediately becomes operational.
1332    #[allow(clippy::too_many_arguments)]
1333    pub fn add<C: Crypto>(
1334        &mut self,
1335        crypto: C,
1336        secret_key: CanonPkcSecretKeyRef<'_>,
1337        root_ca: &[u8],
1338        noc: &[u8],
1339        icac: &[u8],
1340        epoch_key: Option<CanonAeadKeyRef<'_>>,
1341        vendor_id: u16,
1342        case_admin_subject: u64,
1343    ) -> Result<&mut Fabric, Error> {
1344        self.add_with_post_init(|fabric| {
1345            fabric.update(
1346                crypto,
1347                Some(root_ca),
1348                noc,
1349                icac,
1350                secret_key,
1351                epoch_key,
1352                Some(vendor_id),
1353                Some(case_admin_subject),
1354            )
1355        })
1356    }
1357
1358    /// Add a new fabric with an explicit ACL instead of the single admin entry
1359    /// [`Fabrics::add`] seeds.
1360    ///
1361    /// If this operation succeeds, the fabric immediately becomes operational.
1362    #[allow(clippy::too_many_arguments)]
1363    pub fn add_with_acl<C, I>(
1364        &mut self,
1365        crypto: C,
1366        secret_key: CanonPkcSecretKeyRef<'_>,
1367        root_ca: &[u8],
1368        noc: &[u8],
1369        icac: &[u8],
1370        epoch_key: Option<CanonAeadKeyRef<'_>>,
1371        vendor_id: u16,
1372        acl: I,
1373    ) -> Result<&mut Fabric, Error>
1374    where
1375        C: Crypto,
1376        I: IntoIterator<Item = Result<AclEntry, TlvError>>,
1377    {
1378        self.add_with_post_init(|fabric| {
1379            fabric.update(
1380                crypto,
1381                Some(root_ca),
1382                noc,
1383                icac,
1384                secret_key,
1385                epoch_key,
1386                Some(vendor_id),
1387                None,
1388            )?;
1389
1390            for entry in acl {
1391                fabric.acl_add(entry?)?;
1392            }
1393
1394            Ok(())
1395        })
1396    }
1397
1398    /// Update an existing fabric with the provided data (usually, as a result of an `UpdateNOC` IM command).
1399    ///
1400    /// The fabric's existing root cert is preserved across this call —
1401    /// `UpdateNOC` per Matter Core spec is not allowed
1402    /// to change the root, and re-passing the bytes would force the
1403    /// caller to take a (large) heap-less copy of `Fabric::root_ca`.
1404    ///
1405    /// If this operation succeeds, the fabric immediately becomes operational.
1406    /// Note however, that the caller is expected to remove all sessions associated with the fabric, as they would
1407    /// contain invalid keys after the NOC update.
1408    pub fn update<C: Crypto>(
1409        &mut self,
1410        crypto: C,
1411        fab_idx: NonZeroU8,
1412        secret_key: CanonPkcSecretKeyRef<'_>,
1413        noc: &[u8],
1414        icac: &[u8],
1415    ) -> Result<&mut Fabric, Error> {
1416        let fabric = self.fabric_mut(fab_idx)?;
1417
1418        fabric.update(crypto, None, noc, icac, secret_key, None, None, None)?;
1419
1420        Ok(fabric)
1421    }
1422
1423    pub fn update_label(&mut self, fab_idx: NonZeroU8, label: &str) -> Result<&mut Fabric, Error> {
1424        if self.iter().any(|fabric| {
1425            fabric.fab_idx != fab_idx && !fabric.label.is_empty() && fabric.label == label
1426        }) {
1427            return Err(ErrorCode::Invalid.into());
1428        }
1429
1430        let fabric = self.fabric_mut(fab_idx)?;
1431        fabric.label.clear();
1432        fabric
1433            .label
1434            .push_str(label)
1435            .map_err(|_| ErrorCode::ConstraintError)?;
1436
1437        Ok(fabric)
1438    }
1439
1440    /// Remove a fabric from the fabrics
1441    pub fn remove(&mut self, fab_idx: NonZeroU8) -> Result<(), Error> {
1442        let _ = self.fabric(fab_idx)?;
1443
1444        self.fabrics.retain(|fabric| fabric.fab_idx != fab_idx);
1445
1446        Ok(())
1447    }
1448
1449    /// Get a fabric that matches the provided destination ID
1450    pub fn get_by_dest_id<C: Crypto>(
1451        &self,
1452        crypto: C,
1453        random: &[u8],
1454        target: &[u8],
1455    ) -> Option<&Fabric> {
1456        self.iter()
1457            .find(|fabric| fabric.is_dest_id(&crypto, random, target).is_ok())
1458    }
1459
1460    /// Get a fabric by its local index
1461    pub fn get(&self, fab_idx: NonZeroU8) -> Option<&Fabric> {
1462        self.iter().find(|fabric| fabric.fab_idx == fab_idx)
1463    }
1464
1465    /// Get a mutable fabric reference by its local index
1466    pub fn get_mut(&mut self, fab_idx: NonZeroU8) -> Option<&mut Fabric> {
1467        // pub for testing
1468        self.fabrics
1469            .iter_mut()
1470            .find(|fabric| fabric.fab_idx == fab_idx)
1471    }
1472
1473    /// Iterate over the fabrics
1474    pub fn iter(&self) -> impl Iterator<Item = &Fabric> {
1475        self.fabrics.iter()
1476    }
1477
1478    /// Get a fabric by its local index
1479    ///
1480    /// Returns an error if the fabric is not found
1481    pub fn fabric(&self, fab_idx: NonZeroU8) -> Result<&Fabric, Error> {
1482        self.get(fab_idx).ok_or(ErrorCode::NotFound.into())
1483    }
1484
1485    /// Get a mutable fabric reference by its local index
1486    ///
1487    /// Returns an error if the fabric is not found
1488    pub fn fabric_mut(&mut self, fab_idx: NonZeroU8) -> Result<&mut Fabric, Error> {
1489        self.get_mut(fab_idx).ok_or(ErrorCode::NotFound.into())
1490    }
1491
1492    /// Check if the given access request should be allowed, based on all operational fabrics
1493    /// and their ACLs
1494    ///
1495    /// `aux_acl_enabled` conveys whether the node advertises the Access Control
1496    /// cluster's `AUXILIARY` feature - see `AclEntry::allow`.
1497    pub fn allow(&self, req: &AccessReq, aux_acl_enabled: bool) -> bool {
1498        // PASE Sessions with no fabric index have implicit access grant,
1499        // but only as long as the ACL list is empty
1500        //
1501        // As per the spec:
1502        // The Access Control List is able to have an initial entry added because the Access Control Privilege
1503        // Granting algorithm behaves as if, over a PASE commissioning channel during the commissioning
1504        // phase, the following implicit Access Control Entry were present on the Commissionee (but not on
1505        // the Commissioner):
1506        // Access Control Cluster: {
1507        //     ACL: [
1508        //         0: {
1509        //             // implicit entry only; does not explicitly exist!
1510        //             FabricIndex: 0, // not fabric-specific
1511        //             Privilege: Administer,
1512        //             AuthMode: PASE,
1513        //             Subjects: [],
1514        //             Targets: [] // entire node
1515        //         }
1516        //     ],
1517        //     Extension: []
1518        // }
1519        if req.accessor().auth_mode() == Some(AuthMode::Pase) {
1520            return true;
1521        }
1522
1523        let Ok(fab_idx) = req.accessor().fab_idx() else {
1524            return false;
1525        };
1526
1527        let Some(fabric) = self.get(fab_idx) else {
1528            return false;
1529        };
1530
1531        fabric.allow(req, aux_acl_enabled)
1532    }
1533}
1534
1535/// A utility for persisting a fabric in a `KvBlobStore` instance.
1536///
1537/// Like [`Persist`], it logs and ignores what it cannot persist, unless created
1538/// with [`FabricPersist::strict`].
1539pub struct FabricPersist<S>(Persist<S>);
1540
1541impl<S> FabricPersist<S>
1542where
1543    S: KvBlobStoreAccess,
1544{
1545    /// Create a new `FabricPersist` with the given key-value store instance.
1546    pub const fn new(kvb: S) -> Self {
1547        Self(Persist::new(kvb))
1548    }
1549
1550    /// Create a new `FabricPersist` with the given key-value store instance,
1551    /// which returns the errors of what it cannot persist.
1552    pub const fn strict(kvb: S) -> Self {
1553        Self(Persist::strict(kvb))
1554    }
1555
1556    /// Return a reference to the underlying `Persist` instance.
1557    pub fn persist_mut(&mut self) -> &mut Persist<S> {
1558        &mut self.0
1559    }
1560
1561    /// Save the provided fabric in the persistent storage.
1562    pub fn store(&mut self, fabric: &Fabric) -> Result<(), Error> {
1563        self.0
1564            .store_tlv(FABRIC_KEYS_START + fabric.fab_idx().get() as u16, fabric)
1565    }
1566
1567    /// Remove the fabric with the given index from the persistent storage.
1568    pub fn remove(&mut self, fab_idx: NonZeroU8) -> Result<(), Error> {
1569        self.0.remove(FABRIC_KEYS_START + fab_idx.get() as u16)
1570    }
1571
1572    /// Save [`Fabrics::next_fab_idx`] in the persistent storage.
1573    pub fn store_next_fab_idx(&mut self, next_fab_idx: NonZeroU8) -> Result<(), Error> {
1574        self.0.store_tlv(NEXT_FABRIC_INDEX_KEY, next_fab_idx.get())
1575    }
1576
1577    /// Call at the end when finished with everything else
1578    /// No-op for now
1579    pub fn run(self) -> Result<(), Error> {
1580        self.0.run()
1581    }
1582}
1583
1584#[cfg(test)]
1585#[cfg_attr(coverage_nightly, coverage(off))]
1586pub(crate) mod tests {
1587    use core::mem::MaybeUninit;
1588    use core::num::NonZeroU8;
1589
1590    use crate::acl::{AccessReq, AccessorSubjects, AclEntry, AuthMode, SubjectDescriptor, Target};
1591    use crate::cert::gen::{CertGenerator, CertType, IssuerDN, SubjectDN, Validity, VALID_FOREVER};
1592    use crate::cert::{CertRef, MAX_CERT_TLV_AND_ASN1_LEN};
1593    use crate::crypto::test_only_crypto;
1594    use crate::crypto::{
1595        CanonAeadKeyRef, CanonPkcPublicKey, CanonPkcPublicKeyRef, CanonPkcSecretKey,
1596        CanonPkcSecretKeyRef, Crypto, Hash, PublicKey, Rng, SecretKey, SigningSecretKey,
1597        AEAD_CANON_KEY_LEN,
1598    };
1599    use crate::dm::{Access, Privilege};
1600    use crate::error::{Error, ErrorCode};
1601    use crate::im::GenericPath;
1602    use crate::persist::{
1603        KvBlobStore, KvBlobStoreAccess, MemKv, MemKvBlobStore, FABRIC_KEYS_START,
1604        NEXT_FABRIC_INDEX_KEY,
1605    };
1606    use crate::tlv::TLVElement;
1607    use crate::utils::init::{Init, InitMaybeUninit, IntoFallibleInit};
1608
1609    use super::{
1610        Fabric, FabricPersist, Fabrics, MAX_FABRICS, MAX_FAB_IDX, VID_VERIFICATION_STATEMENT_LEN,
1611    };
1612
1613    /// A freshly minted, self-signed RCAC.
1614    pub(crate) struct TestRcac {
1615        pub(crate) key: CanonPkcSecretKey,
1616        pub(crate) cert: std::vec::Vec<u8>,
1617    }
1618
1619    /// A freshly minted NOC, chained (directly or via an ICAC) to some RCAC.
1620    pub(crate) struct TestNoc {
1621        pub(crate) key: CanonPkcSecretKey,
1622        pub(crate) cert: std::vec::Vec<u8>,
1623    }
1624
1625    /// Write the canonical public key of a secret key into `out`.
1626    pub(crate) fn pubkey_of<C: Crypto>(
1627        crypto: &C,
1628        key: CanonPkcSecretKeyRef<'_>,
1629    ) -> CanonPkcPublicKey {
1630        let mut out = CanonPkcPublicKey::new();
1631        crypto
1632            .secret_key(key)
1633            .unwrap()
1634            .pub_key()
1635            .unwrap()
1636            .write_canon(&mut out)
1637            .unwrap();
1638        out
1639    }
1640
1641    /// Mint a self-signed RCAC for `fabric_id` with subject CA ID `rcac_id`.
1642    pub(crate) fn mint_rcac<C: Crypto>(crypto: &C, fabric_id: u64, rcac_id: u64) -> TestRcac {
1643        let rcac_secret_key = crypto.generate_secret_key().unwrap();
1644        let mut rcac_pubkey = CanonPkcPublicKey::new();
1645        rcac_secret_key
1646            .pub_key()
1647            .unwrap()
1648            .write_canon(&mut rcac_pubkey)
1649            .unwrap();
1650
1651        let mut buf = [0u8; MAX_CERT_TLV_AND_ASN1_LEN];
1652        let len = CertGenerator::new(&mut buf)
1653            .generate(
1654                crypto,
1655                CertType::Rcac,
1656                &[0x01],
1657                VALID_FOREVER,
1658                SubjectDN {
1659                    node_id: None,
1660                    fabric_id: Some(fabric_id),
1661                    cat_ids: &[],
1662                    ca_id: Some(rcac_id),
1663                },
1664                IssuerDN {
1665                    ca_id: None,
1666                    fabric_id: None,
1667                    is_rcac: false,
1668                },
1669                rcac_pubkey.reference(),
1670                None,
1671                &rcac_secret_key,
1672            )
1673            .unwrap();
1674
1675        let mut key = CanonPkcSecretKey::new();
1676        rcac_secret_key.write_canon(&mut key).unwrap();
1677
1678        TestRcac {
1679            key,
1680            cert: buf[..len].to_vec(),
1681        }
1682    }
1683
1684    /// Mint an ICAC signed by `rcac`.
1685    pub(crate) fn mint_icac<C: Crypto>(crypto: &C, rcac: &TestRcac) -> TestRcac {
1686        let rcac_cert = CertRef::new(TLVElement::new(&rcac.cert));
1687        let rcac_pubkey = rcac_cert.pubkey().unwrap().try_into().unwrap();
1688        let rcac_id = rcac_cert.get_ca_id().unwrap();
1689        let fabric_id = rcac_cert.get_fabric_id().unwrap();
1690
1691        // A random ICAC ID, as an issuer of ICACs would use
1692        let mut icac_id = [0u8; 8];
1693        crypto.rand().unwrap().fill_bytes(&mut icac_id);
1694
1695        let icac_secret_key = crypto.generate_secret_key().unwrap();
1696        let mut icac_pubkey = CanonPkcPublicKey::new();
1697        icac_secret_key
1698            .pub_key()
1699            .unwrap()
1700            .write_canon(&mut icac_pubkey)
1701            .unwrap();
1702
1703        let rcac_secret_key = crypto.secret_key(rcac.key.reference()).unwrap();
1704
1705        let mut buf = [0u8; MAX_CERT_TLV_AND_ASN1_LEN];
1706        let len = CertGenerator::new(&mut buf)
1707            .generate(
1708                crypto,
1709                CertType::Icac,
1710                &[0x01],
1711                VALID_FOREVER,
1712                SubjectDN {
1713                    node_id: None,
1714                    fabric_id: Some(fabric_id),
1715                    cat_ids: &[],
1716                    ca_id: Some(u64::from_be_bytes(icac_id)),
1717                },
1718                IssuerDN {
1719                    ca_id: Some(rcac_id),
1720                    fabric_id: Some(fabric_id),
1721                    is_rcac: true,
1722                },
1723                icac_pubkey.reference(),
1724                Some(rcac_pubkey),
1725                &rcac_secret_key,
1726            )
1727            .unwrap();
1728
1729        let mut key = CanonPkcSecretKey::new();
1730        icac_secret_key.write_canon(&mut key).unwrap();
1731
1732        TestRcac {
1733            key,
1734            cert: buf[..len].to_vec(),
1735        }
1736    }
1737
1738    /// Mint a NOC for `node_id` carrying `noc_pubkey`, signed by `issuer`
1739    /// (an RCAC when `issuer_is_rcac`, an ICAC otherwise). The fabric ID and
1740    /// the issuer CA ID are taken from the issuer certificate.
1741    pub(crate) fn mint_noc_for_pubkey<C: Crypto>(
1742        crypto: &C,
1743        issuer: &TestRcac,
1744        issuer_is_rcac: bool,
1745        noc_pubkey: CanonPkcPublicKeyRef<'_>,
1746        node_id: u64,
1747    ) -> std::vec::Vec<u8> {
1748        let issuer_ref = CertRef::new(TLVElement::new(&issuer.cert));
1749        let fabric_id = issuer_ref.get_fabric_id().unwrap();
1750        let ca_id = issuer_ref.get_ca_id().unwrap();
1751        let issuer_pubkey = pubkey_of(crypto, issuer.key.reference());
1752        let signing_key = crypto.secret_key(issuer.key.reference()).unwrap();
1753
1754        let mut buf = [0u8; MAX_CERT_TLV_AND_ASN1_LEN];
1755        let len = CertGenerator::new(&mut buf)
1756            .generate(
1757                crypto,
1758                CertType::Noc,
1759                &[0x02],
1760                VALID_FOREVER,
1761                SubjectDN {
1762                    node_id: Some(node_id),
1763                    fabric_id: Some(fabric_id),
1764                    cat_ids: &[],
1765                    ca_id: None,
1766                },
1767                IssuerDN {
1768                    ca_id: Some(ca_id),
1769                    fabric_id: Some(fabric_id),
1770                    is_rcac: issuer_is_rcac,
1771                },
1772                noc_pubkey,
1773                Some(issuer_pubkey.reference()),
1774                &signing_key,
1775            )
1776            .unwrap();
1777
1778        buf[..len].to_vec()
1779    }
1780
1781    /// Mint a NOC with a fresh keypair for `node_id`, signed by `issuer`.
1782    pub(crate) fn mint_noc<C: Crypto>(
1783        crypto: &C,
1784        issuer: &TestRcac,
1785        issuer_is_rcac: bool,
1786        node_id: u64,
1787    ) -> TestNoc {
1788        let noc_secret_key = crypto.generate_secret_key().unwrap();
1789        let mut key = CanonPkcSecretKey::new();
1790        noc_secret_key.write_canon(&mut key).unwrap();
1791
1792        let cert = mint_noc_for_pubkey(
1793            crypto,
1794            issuer,
1795            issuer_is_rcac,
1796            pubkey_of(crypto, key.reference()).reference(),
1797            node_id,
1798        );
1799
1800        TestNoc { key, cert }
1801    }
1802
1803    /// The IPK epoch key used by every fabric these tests add.
1804    pub(crate) const TEST_IPK: [u8; AEAD_CANON_KEY_LEN] = [0x5a; AEAD_CANON_KEY_LEN];
1805
1806    /// Add an RCAC-direct fabric for (`fabric_id`, `node_id`) with vendor ID
1807    /// `0x8000` and `node_id` as the CASE admin subject. Returns its index.
1808    pub(crate) fn add_fabric<C: Crypto>(
1809        crypto: &C,
1810        fabrics: &mut Fabrics,
1811        fabric_id: u64,
1812        node_id: u64,
1813    ) -> NonZeroU8 {
1814        let rcac = mint_rcac(crypto, fabric_id, 0x10 + fabric_id);
1815        let noc = mint_noc(crypto, &rcac, true, node_id);
1816
1817        fabrics
1818            .add(
1819                crypto,
1820                noc.key.reference(),
1821                &rcac.cert,
1822                &noc.cert,
1823                &[],
1824                Some(CanonAeadKeyRef::new(&TEST_IPK)),
1825                0x8000,
1826                node_id,
1827            )
1828            .unwrap()
1829            .fab_idx()
1830    }
1831
1832    fn idx(i: u8) -> NonZeroU8 {
1833        NonZeroU8::new(i).unwrap()
1834    }
1835
1836    /// The Matter spec's "Compressed Fabric Identifier" example: this root
1837    /// public key and fabric ID compress to `87e1b004e235a130`.
1838    #[test]
1839    fn compressed_fabric_id_matches_spec_example() {
1840        const ROOT_PUBKEY: [u8; 65] = [
1841            0x04, 0x4a, 0x9f, 0x42, 0xb1, 0xca, 0x48, 0x40, 0xd3, 0x72, 0x92, 0xbb, 0xc7, 0xf6,
1842            0xa7, 0xe1, 0x1e, 0x22, 0x20, 0x0c, 0x97, 0x6f, 0xc9, 0x00, 0xdb, 0xc9, 0x8a, 0x7a,
1843            0x38, 0x3a, 0x64, 0x1c, 0xb8, 0x25, 0x4a, 0x2e, 0x56, 0xd4, 0xe2, 0x95, 0xa8, 0x47,
1844            0x94, 0x3b, 0x4e, 0x38, 0x97, 0xc4, 0xa7, 0x73, 0xe9, 0x30, 0x27, 0x7b, 0x4d, 0x9f,
1845            0xbe, 0xde, 0x8a, 0x05, 0x26, 0x86, 0xbf, 0xac, 0xfa,
1846        ];
1847
1848        let crypto = test_only_crypto();
1849
1850        let compressed = Fabric::compute_compressed_fabric_id(
1851            &crypto,
1852            CanonPkcPublicKeyRef::new(&ROOT_PUBKEY),
1853            0x2906_c908_d115_d362,
1854        );
1855
1856        assert_eq!(compressed, 0x87e1_b004_e235_a130);
1857    }
1858
1859    /// Lock the on-disk TLV tag layout of the fields whose position is sensitive
1860    /// to the `groups` feature. A released `rs-matter` persists `groups` at
1861    /// context tag 13 and `vid_verification_statement` at 14; gating `groups` in
1862    /// or out must not move either. Serializing an (empty) `Fabric` and checking
1863    /// the raw tags catches any future reorder that would silently corrupt
1864    /// existing persisted fabrics.
1865    #[test]
1866    fn fabric_tlv_tag_layout_is_stable() {
1867        use crate::tlv::{TLVElement, TLVTag, ToTLV};
1868        use crate::utils::init::InitMaybeUninit;
1869        use crate::utils::storage::WriteBuf;
1870
1871        let mut fabric = core::mem::MaybeUninit::<Fabric>::uninit();
1872        let fabric = fabric.init_with(Fabric::init(unwrap!(NonZeroU8::new(1))));
1873
1874        let mut buf = [0u8; 512];
1875        let mut wb = WriteBuf::new(&mut buf);
1876        fabric.to_tlv(&TLVTag::Anonymous, &mut wb).unwrap();
1877        let len = wb.get_tail();
1878
1879        let root = TLVElement::new(&buf[..len]).structure().unwrap();
1880
1881        // `find_ctx` returns an EMPTY element (not an error) when the tag is
1882        // absent, so presence is `!is_empty()` and absence is `is_empty()`.
1883
1884        // `acl` (the last always-present field before the sensitive pair) is at 12.
1885        assert!(
1886            !root.find_ctx(12).unwrap().is_empty(),
1887            "acl must stay at TLV tag 12"
1888        );
1889
1890        // `vid_verification_statement` must always be at context tag 14.
1891        assert!(
1892            !root.find_ctx(14).unwrap().is_empty(),
1893            "vid_verification_statement must stay at TLV tag 14"
1894        );
1895
1896        // With `groups` compiled in it must be at tag 13; compiled out, tag 13 is
1897        // simply absent (and a reader defaults it).
1898        #[cfg(feature = "groups")]
1899        assert!(
1900            !root.find_ctx(13).unwrap().is_empty(),
1901            "groups must be at TLV tag 13 when compiled in"
1902        );
1903        #[cfg(not(feature = "groups"))]
1904        assert!(
1905            root.find_ctx(13).unwrap().is_empty(),
1906            "no field should occupy tag 13 when groups is compiled out"
1907        );
1908    }
1909
1910    /// Verify that `compute_dest_id` and `is_dest_id` agree: the hash output by
1911    /// `compute_dest_id` must be accepted by `is_dest_id` on the same fabric with
1912    /// the same random nonce.
1913    ///
1914    /// Uses runtime-generated certs (via `CertGenerator`) with a real keypair
1915    /// so the fabric is in a valid state — the secret key matches the NOC's public key.
1916    #[test]
1917    fn test_compute_dest_id_matches_is_dest_id() {
1918        let crypto = test_only_crypto();
1919
1920        let fabric_id: u64 = 1;
1921        let rcac_id: u64 = 1;
1922        let node_id: u64 = 100;
1923
1924        // Generate RCAC keypair and build self-signed RCAC
1925        let rcac_secret_key = crypto.generate_secret_key().unwrap();
1926        let mut rcac_pubkey_canon = crate::crypto::CanonPkcPublicKey::new();
1927        rcac_secret_key
1928            .pub_key()
1929            .unwrap()
1930            .write_canon(&mut rcac_pubkey_canon)
1931            .unwrap();
1932
1933        let validity = Validity {
1934            not_before: 0,
1935            not_after: 0,
1936        };
1937
1938        let mut rcac_buf = [0u8; MAX_CERT_TLV_AND_ASN1_LEN];
1939        let rcac_len = CertGenerator::new(&mut rcac_buf)
1940            .generate(
1941                &crypto,
1942                CertType::Rcac,
1943                &[0x01],
1944                validity,
1945                SubjectDN {
1946                    node_id: None,
1947                    fabric_id: Some(fabric_id),
1948                    cat_ids: &[],
1949                    ca_id: Some(rcac_id),
1950                },
1951                IssuerDN {
1952                    ca_id: None,
1953                    fabric_id: None,
1954                    is_rcac: false,
1955                },
1956                rcac_pubkey_canon.reference(),
1957                None,
1958                &rcac_secret_key,
1959            )
1960            .unwrap();
1961
1962        // Generate NOC keypair and build NOC signed by RCAC
1963        let noc_secret_key = crypto.generate_secret_key().unwrap();
1964        let mut noc_pubkey_canon = crate::crypto::CanonPkcPublicKey::new();
1965        noc_secret_key
1966            .pub_key()
1967            .unwrap()
1968            .write_canon(&mut noc_pubkey_canon)
1969            .unwrap();
1970
1971        let mut noc_secret_key_canon = CanonPkcSecretKey::new();
1972        noc_secret_key
1973            .write_canon(&mut noc_secret_key_canon)
1974            .unwrap();
1975
1976        let mut noc_buf = [0u8; MAX_CERT_TLV_AND_ASN1_LEN];
1977        let noc_len = CertGenerator::new(&mut noc_buf)
1978            .generate(
1979                &crypto,
1980                CertType::Noc,
1981                &[0x02],
1982                validity,
1983                SubjectDN {
1984                    node_id: Some(node_id),
1985                    fabric_id: Some(fabric_id),
1986                    cat_ids: &[],
1987                    ca_id: None,
1988                },
1989                IssuerDN {
1990                    ca_id: Some(rcac_id),
1991                    fabric_id: Some(fabric_id),
1992                    is_rcac: true,
1993                },
1994                noc_pubkey_canon.reference(),
1995                Some(rcac_pubkey_canon.reference()),
1996                &rcac_secret_key,
1997            )
1998            .unwrap();
1999
2000        // Build fabric with real certs and matching secret key
2001        let epoch_key = [0x5a_u8; AEAD_CANON_KEY_LEN];
2002        let mut fabrics = Fabrics::new();
2003        fabrics
2004            .add(
2005                &crypto,
2006                noc_secret_key_canon.reference(),
2007                &rcac_buf[..rcac_len],
2008                &noc_buf[..noc_len],
2009                &[], // no ICAC
2010                Some(CanonAeadKeyRef::new(&epoch_key)),
2011                0x8000,
2012                node_id,
2013            )
2014            .expect("Fabrics::add should succeed");
2015
2016        let fab_idx = core::num::NonZeroU8::new(1).unwrap();
2017        let fabric = fabrics
2018            .get(fab_idx)
2019            .expect("fabric at index 1 should exist");
2020
2021        let random = [0xABu8; 32];
2022
2023        // Compute the destination ID (targeting this fabric's own node).
2024        let mut dest_id = MaybeUninit::<Hash>::uninit();
2025        let dest_id = dest_id.init_with(Hash::init());
2026        fabric
2027            .compute_dest_id(&crypto, &random, fabric.node_id(), dest_id)
2028            .expect("compute_dest_id should not fail");
2029
2030        // is_dest_id must accept the computed value.
2031        fabric
2032            .is_dest_id(&crypto, &random, dest_id.access())
2033            .expect("is_dest_id should accept hash produced by compute_dest_id");
2034    }
2035
2036    #[test]
2037    fn add_assigns_sequential_indices_and_iter_is_insertion_ordered() {
2038        let crypto = test_only_crypto();
2039        let mut fabrics = Fabrics::new();
2040
2041        assert_eq!(fabrics.iter().count(), 0);
2042
2043        let a = add_fabric(&crypto, &mut fabrics, 0xa, 0x1a);
2044        let b = add_fabric(&crypto, &mut fabrics, 0xb, 0x1b);
2045        let c = add_fabric(&crypto, &mut fabrics, 0xc, 0x1c);
2046
2047        assert_eq!((a, b, c), (idx(1), idx(2), idx(3)));
2048
2049        let order: std::vec::Vec<_> = fabrics.iter().map(|f| f.fab_idx().get()).collect();
2050        assert_eq!(order, [1, 2, 3]);
2051    }
2052
2053    #[test]
2054    fn add_populates_fabric_fields() {
2055        let crypto = test_only_crypto();
2056        let mut fabrics = Fabrics::new();
2057
2058        let rcac = mint_rcac(&crypto, 0xfab, 0x77);
2059        let noc = mint_noc(&crypto, &rcac, true, 0x1234);
2060
2061        let fabric = fabrics
2062            .add(
2063                &crypto,
2064                noc.key.reference(),
2065                &rcac.cert,
2066                &noc.cert,
2067                &[],
2068                Some(CanonAeadKeyRef::new(&TEST_IPK)),
2069                0xfff1,
2070                0x1234,
2071            )
2072            .unwrap();
2073
2074        assert_eq!(fabric.fab_idx(), idx(1));
2075        assert_eq!(fabric.node_id(), 0x1234);
2076        assert_eq!(fabric.fabric_id(), 0xfab);
2077        assert_eq!(fabric.vendor_id(), 0xfff1);
2078        assert_eq!(fabric.root_ca(), rcac.cert.as_slice());
2079        assert_eq!(fabric.noc(), noc.cert.as_slice());
2080        assert!(fabric.icac().is_empty());
2081        assert!(fabric.vvsc().is_empty());
2082        assert!(fabric.vid_verification_statement().is_empty());
2083        assert_eq!(fabric.label(), "");
2084        assert_eq!(fabric.secret_key().access(), noc.key.access());
2085
2086        // The compressed fabric ID is derived from the root pubkey + fabric ID
2087        let root_cert = CertRef::new(TLVElement::new(&rcac.cert));
2088        let root_pubkey = root_cert.pubkey().unwrap();
2089        assert_eq!(
2090            fabric.compressed_fabric_id(),
2091            Fabric::compute_compressed_fabric_id(&crypto, root_pubkey.try_into().unwrap(), 0xfab)
2092        );
2093
2094        // The IPK epoch key is stored and an operational key derived from it
2095        assert_eq!(fabric.ipk().epoch_key().access(), &TEST_IPK);
2096        assert_ne!(fabric.ipk().op_key().access(), &[0u8; AEAD_CANON_KEY_LEN]);
2097
2098        // A single CASE admin entry for the admin subject is seeded
2099        let mut expected = AclEntry::new(Some(idx(1)), Privilege::ADMIN, AuthMode::Case);
2100        expected.add_subject(0x1234).unwrap();
2101        assert_eq!(fabric.acl(), &[expected]);
2102    }
2103
2104    #[test]
2105    fn add_with_icac_stores_icac() {
2106        let crypto = test_only_crypto();
2107        let mut fabrics = Fabrics::new();
2108
2109        let rcac = mint_rcac(&crypto, 0xfab, 0x77);
2110        let icac = mint_icac(&crypto, &rcac);
2111        let noc = mint_noc(&crypto, &icac, false, 0x1234);
2112
2113        let fabric = fabrics
2114            .add(
2115                &crypto,
2116                noc.key.reference(),
2117                &rcac.cert,
2118                &noc.cert,
2119                &icac.cert,
2120                Some(CanonAeadKeyRef::new(&TEST_IPK)),
2121                0xfff1,
2122                0x1234,
2123            )
2124            .unwrap();
2125
2126        assert_eq!(fabric.icac(), icac.cert.as_slice());
2127        assert!(fabric.vvsc().is_empty());
2128        assert_eq!(fabric.fabric_id(), 0xfab);
2129    }
2130
2131    #[test]
2132    fn add_with_post_init_error_leaves_no_fabric() {
2133        let mut fabrics = Fabrics::new();
2134
2135        let err = fabrics
2136            .add_with_post_init(|_| Err(ErrorCode::Invalid.into()))
2137            .unwrap_err();
2138
2139        assert_eq!(err.code(), ErrorCode::Invalid);
2140        assert_eq!(fabrics.iter().count(), 0);
2141    }
2142
2143    #[test]
2144    fn add_fails_with_resource_exhausted_when_full() {
2145        let crypto = test_only_crypto();
2146        let mut fabrics = Fabrics::new();
2147
2148        for i in 0..MAX_FABRICS as u64 {
2149            add_fabric(&crypto, &mut fabrics, 0x100 + i, 0x200 + i);
2150        }
2151        assert_eq!(fabrics.iter().count(), MAX_FABRICS);
2152
2153        let rcac = mint_rcac(&crypto, 0xfab, 0x77);
2154        let noc = mint_noc(&crypto, &rcac, true, 0x1234);
2155        let err = fabrics
2156            .add(
2157                &crypto,
2158                noc.key.reference(),
2159                &rcac.cert,
2160                &noc.cert,
2161                &[],
2162                Some(CanonAeadKeyRef::new(&TEST_IPK)),
2163                0xfff1,
2164                0x1234,
2165            )
2166            .unwrap_err();
2167
2168        assert_eq!(err.code(), ErrorCode::ResourceExhausted);
2169        assert_eq!(fabrics.iter().count(), MAX_FABRICS);
2170    }
2171
2172    #[test]
2173    fn remove_drops_fabric_and_next_add_uses_the_next_index() {
2174        let crypto = test_only_crypto();
2175        let mut fabrics = Fabrics::new();
2176
2177        add_fabric(&crypto, &mut fabrics, 0xa, 0x1a);
2178        add_fabric(&crypto, &mut fabrics, 0xb, 0x1b);
2179        add_fabric(&crypto, &mut fabrics, 0xc, 0x1c);
2180
2181        fabrics.remove(idx(2)).unwrap();
2182
2183        assert!(fabrics.get(idx(2)).is_none());
2184        assert_eq!(
2185            fabrics.fabric(idx(2)).unwrap_err().code(),
2186            ErrorCode::NotFound
2187        );
2188        assert_eq!(
2189            fabrics.remove(idx(2)).unwrap_err().code(),
2190            ErrorCode::NotFound
2191        );
2192
2193        let order: std::vec::Vec<_> = fabrics.iter().map(|f| f.fab_idx().get()).collect();
2194        assert_eq!(order, [1, 3]);
2195
2196        // Freed indices are not reused, the largest one included
2197        assert_eq!(add_fabric(&crypto, &mut fabrics, 0xd, 0x1d), idx(4));
2198
2199        fabrics.remove(idx(4)).unwrap();
2200        assert_eq!(add_fabric(&crypto, &mut fabrics, 0xe, 0x1e), idx(5));
2201    }
2202
2203    #[test]
2204    fn indices_wrap_around_past_the_taken_ones() {
2205        let mut store = MemKvBlobStore::default();
2206        store
2207            .store(FABRIC_KEYS_START + 1, &[0xff], &mut [])
2208            .unwrap();
2209
2210        let kv = MemKv::new(store);
2211        FabricPersist::new(&kv)
2212            .store_next_fab_idx(idx(MAX_FAB_IDX))
2213            .unwrap();
2214
2215        let mut fabrics = load_all(&kv);
2216        assert_eq!(fabrics.next_fab_idx(), idx(MAX_FAB_IDX));
2217
2218        let mut add = || fabrics.add_with_post_init(|_| Ok(())).unwrap().fab_idx();
2219
2220        assert_eq!(add(), idx(MAX_FAB_IDX));
2221        // Index 1 is kept by the fabric that could not be loaded
2222        assert_eq!(add(), idx(2));
2223    }
2224
2225    #[test]
2226    fn get_and_fabric_accessors_agree() {
2227        let crypto = test_only_crypto();
2228        let mut fabrics = Fabrics::new();
2229
2230        add_fabric(&crypto, &mut fabrics, 0xa, 0x1a);
2231        add_fabric(&crypto, &mut fabrics, 0xb, 0x1b);
2232
2233        assert_eq!(fabrics.get(idx(2)).unwrap().fabric_id(), 0xb);
2234        assert_eq!(fabrics.get_mut(idx(2)).unwrap().fabric_id(), 0xb);
2235        assert_eq!(fabrics.fabric(idx(1)).unwrap().fabric_id(), 0xa);
2236        assert_eq!(fabrics.fabric_mut(idx(1)).unwrap().fabric_id(), 0xa);
2237
2238        assert!(fabrics.get(idx(3)).is_none());
2239        assert!(fabrics.get_mut(idx(3)).is_none());
2240        assert_eq!(
2241            fabrics.fabric(idx(3)).unwrap_err().code(),
2242            ErrorCode::NotFound
2243        );
2244        assert_eq!(
2245            fabrics.fabric_mut(idx(3)).unwrap_err().code(),
2246            ErrorCode::NotFound
2247        );
2248    }
2249
2250    #[test]
2251    fn update_replaces_noc_and_key_but_keeps_root_acl_and_label() {
2252        let crypto = test_only_crypto();
2253        let mut fabrics = Fabrics::new();
2254
2255        let rcac = mint_rcac(&crypto, 0xfab, 0x77);
2256        let icac = mint_icac(&crypto, &rcac);
2257        let noc = mint_noc(&crypto, &icac, false, 0x1234);
2258
2259        let fab_idx = fabrics
2260            .add(
2261                &crypto,
2262                noc.key.reference(),
2263                &rcac.cert,
2264                &noc.cert,
2265                &icac.cert,
2266                Some(CanonAeadKeyRef::new(&TEST_IPK)),
2267                0xfff1,
2268                0x1234,
2269            )
2270            .unwrap()
2271            .fab_idx();
2272        fabrics.update_label(fab_idx, "home").unwrap();
2273
2274        let fabric = fabrics.get_mut(fab_idx).unwrap();
2275        fabric
2276            .set_vid_verification(None, None, Some(&[0xaa; 40]))
2277            .unwrap();
2278        assert!(!fabric.vvsc().is_empty());
2279        let old_compressed = fabric.compressed_fabric_id();
2280        let old_acl = fabric.acl().to_vec();
2281
2282        // A new NOC for a different node ID, signed directly by the RCAC
2283        let new_noc = mint_noc(&crypto, &rcac, true, 0x5678);
2284        let fabric = fabrics
2285            .update(
2286                &crypto,
2287                fab_idx,
2288                new_noc.key.reference(),
2289                &new_noc.cert,
2290                &[],
2291            )
2292            .unwrap();
2293
2294        assert_eq!(fabric.node_id(), 0x5678);
2295        assert_eq!(fabric.fabric_id(), 0xfab);
2296        assert_eq!(fabric.noc(), new_noc.cert.as_slice());
2297        assert_eq!(fabric.secret_key().access(), new_noc.key.access());
2298        assert_eq!(fabric.root_ca(), rcac.cert.as_slice());
2299        assert_eq!(fabric.compressed_fabric_id(), old_compressed);
2300        assert_eq!(fabric.vendor_id(), 0xfff1);
2301        assert_eq!(fabric.label(), "home");
2302        assert_eq!(fabric.acl(), old_acl.as_slice());
2303        assert_eq!(fabric.ipk().epoch_key().access(), &TEST_IPK);
2304
2305        // The cert chain is replaced wholesale: ICAC gone, staged VVSC gone
2306        assert!(fabric.icac().is_empty());
2307        assert!(fabric.vvsc().is_empty());
2308
2309        assert_eq!(
2310            fabrics
2311                .update(&crypto, idx(9), new_noc.key.reference(), &new_noc.cert, &[])
2312                .unwrap_err()
2313                .code(),
2314            ErrorCode::NotFound
2315        );
2316    }
2317
2318    #[test]
2319    fn update_label_rejects_duplicates_and_overlong_labels() {
2320        let crypto = test_only_crypto();
2321        let mut fabrics = Fabrics::new();
2322
2323        add_fabric(&crypto, &mut fabrics, 0xa, 0x1a);
2324        add_fabric(&crypto, &mut fabrics, 0xb, 0x1b);
2325
2326        assert_eq!(
2327            fabrics.update_label(idx(1), "home").unwrap().label(),
2328            "home"
2329        );
2330
2331        // Re-labelling the same fabric with its own label is fine
2332        assert_eq!(
2333            fabrics.update_label(idx(1), "home").unwrap().label(),
2334            "home"
2335        );
2336
2337        // Another fabric may not take a label already in use
2338        assert_eq!(
2339            fabrics.update_label(idx(2), "home").unwrap_err().code(),
2340            ErrorCode::Invalid
2341        );
2342        assert_eq!(fabrics.get(idx(2)).unwrap().label(), "");
2343
2344        // Empty labels never conflict
2345        assert_eq!(fabrics.update_label(idx(2), "").unwrap().label(), "");
2346        assert_eq!(fabrics.update_label(idx(1), "").unwrap().label(), "");
2347
2348        // At most 32 bytes
2349        assert_eq!(
2350            fabrics
2351                .update_label(idx(2), &"x".repeat(32))
2352                .unwrap()
2353                .label()
2354                .len(),
2355            32
2356        );
2357        assert_eq!(
2358            fabrics
2359                .update_label(idx(2), &"y".repeat(33))
2360                .unwrap_err()
2361                .code(),
2362            ErrorCode::ConstraintError
2363        );
2364
2365        assert_eq!(
2366            fabrics.update_label(idx(7), "x").unwrap_err().code(),
2367            ErrorCode::NotFound
2368        );
2369    }
2370
2371    #[test]
2372    fn get_by_dest_id_finds_only_the_matching_fabric() {
2373        let crypto = test_only_crypto();
2374        let mut fabrics = Fabrics::new();
2375
2376        add_fabric(&crypto, &mut fabrics, 0xa, 0x1a);
2377        add_fabric(&crypto, &mut fabrics, 0xb, 0x1b);
2378
2379        let random = [0x42u8; 32];
2380        let mut dest_id = Hash::new();
2381        fabrics
2382            .get(idx(2))
2383            .unwrap()
2384            .compute_dest_id(&crypto, &random, 0x1b, &mut dest_id)
2385            .unwrap();
2386
2387        let found = fabrics
2388            .get_by_dest_id(&crypto, &random, dest_id.access())
2389            .unwrap();
2390        assert_eq!(found.fab_idx(), idx(2));
2391
2392        // A different initiator random yields a different destination ID
2393        let other_random = [0x43u8; 32];
2394        assert!(fabrics
2395            .get_by_dest_id(&crypto, &other_random, dest_id.access())
2396            .is_none());
2397
2398        // ...and so does a destination ID computed for some other node
2399        let mut other_dest_id = Hash::new();
2400        fabrics
2401            .get(idx(2))
2402            .unwrap()
2403            .compute_dest_id(&crypto, &random, 0x1c, &mut other_dest_id)
2404            .unwrap();
2405        assert!(fabrics
2406            .get_by_dest_id(&crypto, &random, other_dest_id.access())
2407            .is_none());
2408    }
2409
2410    #[test]
2411    fn acl_add_update_remove() {
2412        let crypto = test_only_crypto();
2413        let mut fabrics = Fabrics::new();
2414
2415        let fab_idx = add_fabric(&crypto, &mut fabrics, 0xa, 0x1a);
2416        let fabric = fabrics.get_mut(fab_idx).unwrap();
2417        assert_eq!(fabric.acl().len(), 1);
2418
2419        // The entry's fabric index is overwritten with the fabric's own
2420        let mut entry = AclEntry::new(Some(idx(9)), Privilege::VIEW, AuthMode::Case);
2421        entry.add_subject(0x99).unwrap();
2422        assert_eq!(fabric.acl_add(entry.clone()).unwrap(), 1);
2423        entry.fab_idx = Some(fab_idx);
2424        assert_eq!(fabric.acl()[1], entry);
2425        assert_eq!(fabric.acl_iter().count(), 2);
2426
2427        // PASE entries are reserved
2428        assert_eq!(
2429            fabric
2430                .acl_add(AclEntry::new(None, Privilege::VIEW, AuthMode::Pase))
2431                .unwrap_err()
2432                .code(),
2433            ErrorCode::ConstraintError
2434        );
2435        assert_eq!(fabric.acl().len(), 2);
2436
2437        // Update in place, again forcing the fabric index
2438        let mut updated = AclEntry::new(None, Privilege::OPERATE, AuthMode::Case);
2439        updated
2440            .add_target(Target::new(Some(1), None, None))
2441            .unwrap();
2442        fabric.acl_update(1, updated.clone()).unwrap();
2443        updated.fab_idx = Some(fab_idx);
2444        assert_eq!(fabric.acl()[1], updated);
2445
2446        assert_eq!(
2447            fabric.acl_update(2, entry.clone()).unwrap_err().code(),
2448            ErrorCode::NotFound
2449        );
2450
2451        // Remove shifts the remaining entries down
2452        fabric.acl_remove(0).unwrap();
2453        assert_eq!(fabric.acl(), &[updated]);
2454        assert_eq!(
2455            fabric.acl_remove(1).unwrap_err().code(),
2456            ErrorCode::NotFound
2457        );
2458
2459        fabric.acl_remove_all();
2460        assert!(fabric.acl().is_empty());
2461    }
2462
2463    #[test]
2464    fn acl_add_init_rejects_pase_entries() {
2465        let crypto = test_only_crypto();
2466        let mut fabrics = Fabrics::new();
2467
2468        let fab_idx = add_fabric(&crypto, &mut fabrics, 0xa, 0x1a);
2469        let fabric = fabrics.get_mut(fab_idx).unwrap();
2470        let count = fabric.acl().len();
2471
2472        assert_eq!(
2473            fabric
2474                .acl_add_init(
2475                    AclEntry::init(None, Privilege::VIEW, AuthMode::Pase).into_fallible::<Error>()
2476                )
2477                .unwrap_err()
2478                .code(),
2479            ErrorCode::ConstraintError
2480        );
2481        assert_eq!(fabric.acl().len(), count);
2482    }
2483
2484    #[test]
2485    fn acl_add_init_and_update_init() {
2486        let crypto = test_only_crypto();
2487        let mut fabrics = Fabrics::new();
2488
2489        let fab_idx = add_fabric(&crypto, &mut fabrics, 0xa, 0x1a);
2490        let fabric = fabrics.get_mut(fab_idx).unwrap();
2491
2492        let i = fabric
2493            .acl_add_init(
2494                AclEntry::init(None, Privilege::MANAGE, AuthMode::Case)
2495                    .into_fallible::<Error>()
2496                    .chain(|e| e.add_subject(0x55)),
2497            )
2498            .unwrap();
2499        assert_eq!(i, 1);
2500        let mut expected = AclEntry::new(Some(fab_idx), Privilege::MANAGE, AuthMode::Case);
2501        expected.add_subject(0x55).unwrap();
2502        assert_eq!(fabric.acl()[1], expected);
2503
2504        // The entry's fabric index is overwritten with the fabric's own
2505        fabric
2506            .acl_update_init(
2507                1,
2508                AclEntry::init(Some(idx(9)), Privilege::VIEW, AuthMode::Case)
2509                    .into_fallible::<Error>()
2510                    .chain(|e| e.add_subject(0x66)),
2511            )
2512            .unwrap();
2513        let mut expected = AclEntry::new(Some(fab_idx), Privilege::VIEW, AuthMode::Case);
2514        expected.add_subject(0x66).unwrap();
2515        assert_eq!(fabric.acl()[1], expected);
2516
2517        assert_eq!(
2518            fabric
2519                .acl_update_init(
2520                    5,
2521                    AclEntry::init(None, Privilege::VIEW, AuthMode::Case).into_fallible::<Error>()
2522                )
2523                .unwrap_err()
2524                .code(),
2525            ErrorCode::NotFound
2526        );
2527    }
2528
2529    #[test]
2530    fn acl_add_fails_with_resource_exhausted_when_full() {
2531        let crypto = test_only_crypto();
2532        let mut fabrics = Fabrics::new();
2533
2534        let fab_idx = add_fabric(&crypto, &mut fabrics, 0xa, 0x1a);
2535        let fabric = fabrics.get_mut(fab_idx).unwrap();
2536
2537        // One admin entry is seeded on add
2538        for _ in 1..crate::acl::MAX_ACL_ENTRIES_PER_FABRIC {
2539            fabric
2540                .acl_add(AclEntry::new(None, Privilege::VIEW, AuthMode::Case))
2541                .unwrap();
2542        }
2543        assert_eq!(fabric.acl().len(), crate::acl::MAX_ACL_ENTRIES_PER_FABRIC);
2544
2545        assert_eq!(
2546            fabric
2547                .acl_add(AclEntry::new(None, Privilege::VIEW, AuthMode::Case))
2548                .unwrap_err()
2549                .code(),
2550            ErrorCode::ResourceExhausted
2551        );
2552        assert_eq!(
2553            fabric
2554                .acl_add_init(
2555                    AclEntry::init(None, Privilege::VIEW, AuthMode::Case).into_fallible::<Error>()
2556                )
2557                .unwrap_err()
2558                .code(),
2559            ErrorCode::ResourceExhausted
2560        );
2561    }
2562
2563    /// Whether `fabrics` grants a `READ` of endpoint `endpoint` (with `RV`
2564    /// target permissions) to the given accessor.
2565    fn allowed(
2566        fabrics: &Fabrics,
2567        fab_idx: u8,
2568        subject: u64,
2569        auth_mode: Option<AuthMode>,
2570        endpoint: u16,
2571        aux_acl_enabled: bool,
2572    ) -> bool {
2573        let accessor = SubjectDescriptor::new(
2574            fab_idx,
2575            aux_acl_enabled,
2576            AccessorSubjects::new(subject),
2577            auth_mode,
2578        );
2579        let mut req = AccessReq::new(
2580            &accessor,
2581            GenericPath::new(Some(endpoint), Some(0x1d), None),
2582            Access::READ,
2583            &[],
2584        );
2585        req.set_target_perms(Access::RV);
2586
2587        fabrics.allow(&req, aux_acl_enabled)
2588    }
2589
2590    #[test]
2591    fn allow_matches_subject_fabric_and_auth_mode() {
2592        let crypto = test_only_crypto();
2593        let mut fabrics = Fabrics::new();
2594
2595        add_fabric(&crypto, &mut fabrics, 0xa, 0x1a);
2596        add_fabric(&crypto, &mut fabrics, 0xb, 0x1b);
2597
2598        // The seeded admin entry grants the admin subject over CASE
2599        assert!(allowed(&fabrics, 1, 0x1a, Some(AuthMode::Case), 1, false));
2600
2601        // ...but not other subjects, other fabrics, or other auth modes
2602        assert!(!allowed(&fabrics, 1, 0x1b, Some(AuthMode::Case), 1, false));
2603        assert!(!allowed(&fabrics, 2, 0x1a, Some(AuthMode::Case), 1, false));
2604        assert!(!allowed(&fabrics, 1, 0x1a, Some(AuthMode::Group), 1, false));
2605
2606        // PASE accessors get the implicit administer grant
2607        assert!(allowed(&fabrics, 0, 1, Some(AuthMode::Pase), 1, false));
2608
2609        // Plain-text accessors (no fabric) and unknown fabrics are denied
2610        assert!(!allowed(&fabrics, 0, 0x1a, None, 1, false));
2611        assert!(!allowed(&fabrics, 7, 0x1a, Some(AuthMode::Case), 1, false));
2612
2613        // A wildcard-subject entry admits anyone on that fabric
2614        fabrics
2615            .get_mut(idx(2))
2616            .unwrap()
2617            .acl_add(AclEntry::new(None, Privilege::VIEW, AuthMode::Case))
2618            .unwrap();
2619        assert!(allowed(&fabrics, 2, 0x1a, Some(AuthMode::Case), 1, false));
2620        assert!(!allowed(&fabrics, 1, 0x999, Some(AuthMode::Case), 1, false));
2621    }
2622
2623    #[test]
2624    fn allow_aux_acl_excludes_root_endpoint_for_wildcard_group_entries() {
2625        let crypto = test_only_crypto();
2626        let mut fabrics = Fabrics::new();
2627
2628        add_fabric(&crypto, &mut fabrics, 0xa, 0x1a);
2629
2630        let mut entry = AclEntry::new(None, Privilege::OPERATE, AuthMode::Group);
2631        entry.add_subject(0x1234).unwrap();
2632        fabrics.get_mut(idx(1)).unwrap().acl_add(entry).unwrap();
2633
2634        // Without the AUXILIARY feature a wildcard-target group entry covers the whole node
2635        assert!(allowed(
2636            &fabrics,
2637            1,
2638            0x1234,
2639            Some(AuthMode::Group),
2640            0,
2641            false
2642        ));
2643        assert!(allowed(
2644            &fabrics,
2645            1,
2646            0x1234,
2647            Some(AuthMode::Group),
2648            1,
2649            false
2650        ));
2651
2652        // With it, the root endpoint is excluded
2653        assert!(!allowed(
2654            &fabrics,
2655            1,
2656            0x1234,
2657            Some(AuthMode::Group),
2658            0,
2659            true
2660        ));
2661        assert!(allowed(&fabrics, 1, 0x1234, Some(AuthMode::Group), 1, true));
2662
2663        // CASE entries are unaffected either way
2664        assert!(allowed(&fabrics, 1, 0x1a, Some(AuthMode::Case), 0, true));
2665    }
2666
2667    #[test]
2668    fn set_vid_verification_updates_only_the_given_fields() {
2669        let crypto = test_only_crypto();
2670        let mut fabrics = Fabrics::new();
2671
2672        let fab_idx = add_fabric(&crypto, &mut fabrics, 0xa, 0x1a);
2673        let fabric = fabrics.get_mut(fab_idx).unwrap();
2674
2675        // Vendor ID alone
2676        fabric
2677            .set_vid_verification(Some(0x1234), None, None)
2678            .unwrap();
2679        assert_eq!(fabric.vendor_id(), 0x1234);
2680        assert!(fabric.vid_verification_statement().is_empty());
2681        assert!(fabric.vvsc().is_empty());
2682
2683        // Statement of the exact allowed length; longer is rejected
2684        let stmt = [0xab; VID_VERIFICATION_STATEMENT_LEN];
2685        fabric
2686            .set_vid_verification(None, Some(&stmt), None)
2687            .unwrap();
2688        assert_eq!(fabric.vid_verification_statement(), &stmt);
2689        assert_eq!(fabric.vendor_id(), 0x1234);
2690
2691        let too_long = [0xab; VID_VERIFICATION_STATEMENT_LEN + 1];
2692        assert_eq!(
2693            fabric
2694                .set_vid_verification(None, Some(&too_long), None)
2695                .unwrap_err()
2696                .code(),
2697            ErrorCode::BufferTooSmall
2698        );
2699
2700        // Empty statement clears it
2701        fabric.set_vid_verification(None, Some(&[]), None).unwrap();
2702        assert!(fabric.vid_verification_statement().is_empty());
2703
2704        // A VVSC occupies the (otherwise empty) ICAC slot
2705        fabric
2706            .set_vid_verification(None, None, Some(&[0xcd; 30]))
2707            .unwrap();
2708        assert_eq!(fabric.vvsc(), &[0xcd; 30]);
2709        assert!(fabric.icac().is_empty());
2710
2711        // An empty VVSC clears it
2712        fabric.set_vid_verification(None, None, Some(&[])).unwrap();
2713        assert!(fabric.vvsc().is_empty());
2714        assert!(fabric.icac().is_empty());
2715    }
2716
2717    #[test]
2718    fn set_vid_verification_empty_vvsc_does_not_clear_icac() {
2719        let crypto = test_only_crypto();
2720        let mut fabrics = Fabrics::new();
2721
2722        let rcac = mint_rcac(&crypto, 0xfab, 0x77);
2723        let icac = mint_icac(&crypto, &rcac);
2724        let noc = mint_noc(&crypto, &icac, false, 0x1234);
2725
2726        let fabric = fabrics
2727            .add(
2728                &crypto,
2729                noc.key.reference(),
2730                &rcac.cert,
2731                &noc.cert,
2732                &icac.cert,
2733                Some(CanonAeadKeyRef::new(&TEST_IPK)),
2734                0xfff1,
2735                0x1234,
2736            )
2737            .unwrap();
2738
2739        fabric.set_vid_verification(None, None, Some(&[])).unwrap();
2740        assert_eq!(fabric.icac(), icac.cert.as_slice());
2741        assert!(fabric.vvsc().is_empty());
2742    }
2743
2744    /// Persist every fabric of `fabrics` into `kv`.
2745    fn store_all(fabrics: &Fabrics, kv: &MemKv) {
2746        let mut persist = FabricPersist::new(kv);
2747        for fabric in fabrics.iter() {
2748            persist.store(fabric).unwrap();
2749        }
2750        persist.run().unwrap();
2751    }
2752
2753    /// Load a fresh `Fabrics` from `kv`.
2754    fn load_all(kv: &MemKv) -> Fabrics {
2755        let mut fabrics = Fabrics::new();
2756        kv.access(|kv, buf| fabrics.load_persist(kv, buf)).unwrap();
2757        fabrics
2758    }
2759
2760    /// Assert that `a` and `b` carry the same persisted state.
2761    fn assert_same_fabric(a: &Fabric, b: &Fabric) {
2762        assert_eq!(a.fab_idx(), b.fab_idx());
2763        assert_eq!(a.node_id(), b.node_id());
2764        assert_eq!(a.fabric_id(), b.fabric_id());
2765        assert_eq!(a.vendor_id(), b.vendor_id());
2766        assert_eq!(a.compressed_fabric_id(), b.compressed_fabric_id());
2767        assert_eq!(a.secret_key().access(), b.secret_key().access());
2768        assert_eq!(a.root_ca(), b.root_ca());
2769        assert_eq!(a.icac(), b.icac());
2770        assert_eq!(a.vvsc(), b.vvsc());
2771        assert_eq!(a.noc(), b.noc());
2772        assert_eq!(a.ipk().epoch_key().access(), b.ipk().epoch_key().access());
2773        assert_eq!(a.ipk().op_key().access(), b.ipk().op_key().access());
2774        assert_eq!(a.label(), b.label());
2775        assert_eq!(a.acl(), b.acl());
2776        assert_eq!(
2777            a.vid_verification_statement(),
2778            b.vid_verification_statement()
2779        );
2780
2781        #[cfg(feature = "groups")]
2782        {
2783            let ga = a.groups();
2784            let gb = b.groups();
2785
2786            let ks_a: std::vec::Vec<_> = ga
2787                .key_set_iter()
2788                .map(|k| {
2789                    (
2790                        k.group_key_set_id,
2791                        k.group_key_security_policy,
2792                        k.epoch_keys.len(),
2793                    )
2794                })
2795                .collect();
2796            let ks_b: std::vec::Vec<_> = gb
2797                .key_set_iter()
2798                .map(|k| {
2799                    (
2800                        k.group_key_set_id,
2801                        k.group_key_security_policy,
2802                        k.epoch_keys.len(),
2803                    )
2804                })
2805                .collect();
2806            assert_eq!(ks_a, ks_b);
2807            for (ka, kb) in ga.key_set_iter().zip(gb.key_set_iter()) {
2808                for (ea, eb) in ka.epoch_keys.iter().zip(kb.epoch_keys.iter()) {
2809                    assert_eq!(ea.epoch_start_time, eb.epoch_start_time);
2810                    assert_eq!(ea.epoch_key.access(), eb.epoch_key.access());
2811                }
2812            }
2813
2814            let km_a: std::vec::Vec<_> = ga
2815                .key_map_iter()
2816                .map(|m| (m.group_id, m.group_key_set_id))
2817                .collect();
2818            let km_b: std::vec::Vec<_> = gb
2819                .key_map_iter()
2820                .map(|m| (m.group_id, m.group_key_set_id))
2821                .collect();
2822            assert_eq!(km_a, km_b);
2823
2824            let ep_a: std::vec::Vec<_> = ga
2825                .iter()
2826                .map(|e| {
2827                    (
2828                        e.group_id,
2829                        e.endpoints.to_vec(),
2830                        e.group_name.clone(),
2831                        e.has_aux_acl(),
2832                        e.groupcast_managed(),
2833                    )
2834                })
2835                .collect();
2836            let ep_b: std::vec::Vec<_> = gb
2837                .iter()
2838                .map(|e| {
2839                    (
2840                        e.group_id,
2841                        e.endpoints.to_vec(),
2842                        e.group_name.clone(),
2843                        e.has_aux_acl(),
2844                        e.groupcast_managed(),
2845                    )
2846                })
2847                .collect();
2848            assert_eq!(ep_a, ep_b);
2849        }
2850    }
2851
2852    #[test]
2853    fn store_then_load_yields_equal_fabrics() {
2854        let crypto = test_only_crypto();
2855        let mut fabrics = Fabrics::new();
2856
2857        let rcac = mint_rcac(&crypto, 0xfab, 0x77);
2858        let icac = mint_icac(&crypto, &rcac);
2859        let noc = mint_noc(&crypto, &icac, false, 0x1234);
2860        fabrics
2861            .add(
2862                &crypto,
2863                noc.key.reference(),
2864                &rcac.cert,
2865                &noc.cert,
2866                &icac.cert,
2867                Some(CanonAeadKeyRef::new(&TEST_IPK)),
2868                0xfff1,
2869                0x1234,
2870            )
2871            .unwrap();
2872        add_fabric(&crypto, &mut fabrics, 0xb, 0x1b);
2873
2874        fabrics.update_label(idx(1), "first").unwrap();
2875        {
2876            let fabric = fabrics.get_mut(idx(1)).unwrap();
2877            let mut entry = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
2878            entry.add_subject(0x99).unwrap();
2879            entry
2880                .add_target(Target::new(Some(1), Some(6), None))
2881                .unwrap();
2882            fabric.acl_add(entry).unwrap();
2883            fabric
2884                .set_vid_verification(
2885                    Some(0x4321),
2886                    Some(&[0x11; VID_VERIFICATION_STATEMENT_LEN]),
2887                    None,
2888                )
2889                .unwrap();
2890        }
2891        {
2892            let fabric = fabrics.get_mut(idx(2)).unwrap();
2893            fabric
2894                .set_vid_verification(None, None, Some(&[0xcd; 30]))
2895                .unwrap();
2896
2897            #[cfg(feature = "groups")]
2898            {
2899                use crate::group_keys::{GroupEpochKeyEntry, GroupKeySet};
2900
2901                let groups = fabric.groups_mut();
2902                let mut key_set = GroupKeySet {
2903                    group_key_set_id: 0x11,
2904                    group_key_security_policy: 1,
2905                    epoch_keys: crate::utils::storage::Vec::new(),
2906                };
2907                key_set
2908                    .epoch_keys
2909                    .push(GroupEpochKeyEntry {
2910                        epoch_key: crate::crypto::CanonAeadKey::new_from_ref(CanonAeadKeyRef::new(
2911                            &[0x77; AEAD_CANON_KEY_LEN],
2912                        )),
2913                        epoch_start_time: 1234,
2914                    })
2915                    .unwrap();
2916                groups.key_set_add(key_set).unwrap();
2917                groups.key_map_set_group(0x100, 0x11).unwrap();
2918                groups.add(1, 0x100, "kitchen").unwrap();
2919                groups.groupcast_join(0x101, &[2, 3], false, None).unwrap();
2920                groups.set_has_aux_acl(0x101, true);
2921            }
2922        }
2923
2924        let store = MemKvBlobStore::default();
2925        let kv = MemKv::new(store.clone());
2926        store_all(&fabrics, &kv);
2927
2928        assert!(store.contains_key(FABRIC_KEYS_START + 1));
2929        assert!(store.contains_key(FABRIC_KEYS_START + 2));
2930        assert_eq!(store.len(), 2);
2931
2932        let loaded = load_all(&kv);
2933        assert_eq!(loaded.iter().count(), 2);
2934
2935        for fabric in fabrics.iter() {
2936            assert_same_fabric(fabric, loaded.get(fabric.fab_idx()).unwrap());
2937        }
2938
2939        // Loaded fabrics remain fully functional (e.g. for destination ID lookups)
2940        let random = [0x42u8; 32];
2941        let mut dest_id = Hash::new();
2942        fabrics
2943            .get(idx(1))
2944            .unwrap()
2945            .compute_dest_id(&crypto, &random, 0x1234, &mut dest_id)
2946            .unwrap();
2947        assert_eq!(
2948            loaded
2949                .get_by_dest_id(&crypto, &random, dest_id.access())
2950                .unwrap()
2951                .fab_idx(),
2952            idx(1)
2953        );
2954    }
2955
2956    #[test]
2957    fn persist_remove_deletes_the_blob() {
2958        let crypto = test_only_crypto();
2959        let mut fabrics = Fabrics::new();
2960
2961        add_fabric(&crypto, &mut fabrics, 0xa, 0x1a);
2962        add_fabric(&crypto, &mut fabrics, 0xb, 0x1b);
2963
2964        let store = MemKvBlobStore::default();
2965        let kv = MemKv::new(store.clone());
2966        store_all(&fabrics, &kv);
2967        assert_eq!(store.len(), 2);
2968
2969        let mut persist = FabricPersist::new(&kv);
2970        persist.remove(idx(1)).unwrap();
2971        persist.run().unwrap();
2972
2973        assert!(!store.contains_key(FABRIC_KEYS_START + 1));
2974        assert!(store.contains_key(FABRIC_KEYS_START + 2));
2975
2976        let loaded = load_all(&kv);
2977        let order: std::vec::Vec<_> = loaded.iter().map(|f| f.fab_idx().get()).collect();
2978        assert_eq!(order, [2]);
2979
2980        // Removing a blob that is not there is not an error
2981        FabricPersist::new(&kv).remove(idx(1)).unwrap();
2982    }
2983
2984    #[test]
2985    fn reset_persist_clears_memory_and_storage() {
2986        let crypto = test_only_crypto();
2987        let mut fabrics = Fabrics::new();
2988
2989        add_fabric(&crypto, &mut fabrics, 0xa, 0x1a);
2990        add_fabric(&crypto, &mut fabrics, 0xb, 0x1b);
2991
2992        let store = MemKvBlobStore::default();
2993        let kv = MemKv::new(store.clone());
2994        store_all(&fabrics, &kv);
2995        FabricPersist::new(&kv)
2996            .store_next_fab_idx(fabrics.next_fab_idx())
2997            .unwrap();
2998        assert_eq!(store.len(), 3);
2999
3000        kv.access(|kv, buf| fabrics.reset_persist(kv, buf)).unwrap();
3001
3002        assert_eq!(fabrics.iter().count(), 0);
3003        assert_eq!(fabrics.next_fab_idx(), idx(1));
3004        assert_eq!(store.len(), 0);
3005        assert_eq!(load_all(&kv).iter().count(), 0);
3006    }
3007
3008    #[test]
3009    fn next_fab_idx_is_loaded_back() {
3010        let crypto = test_only_crypto();
3011        let mut fabrics = Fabrics::new();
3012
3013        add_fabric(&crypto, &mut fabrics, 0xa, 0x1a);
3014        add_fabric(&crypto, &mut fabrics, 0xb, 0x1b);
3015        fabrics.remove(idx(2)).unwrap();
3016
3017        let kv = MemKv::new(MemKvBlobStore::default());
3018        store_all(&fabrics, &kv);
3019        FabricPersist::new(&kv)
3020            .store_next_fab_idx(fabrics.next_fab_idx())
3021            .unwrap();
3022
3023        let mut loaded = load_all(&kv);
3024        assert_eq!(loaded.next_fab_idx(), idx(3));
3025        assert_eq!(add_fabric(&crypto, &mut loaded, 0xc, 0x1c), idx(3));
3026    }
3027
3028    #[test]
3029    fn missing_or_unreadable_next_fab_idx_follows_the_largest_index() {
3030        let crypto = test_only_crypto();
3031        let mut fabrics = Fabrics::new();
3032
3033        add_fabric(&crypto, &mut fabrics, 0xa, 0x1a);
3034        add_fabric(&crypto, &mut fabrics, 0xb, 0x1b);
3035        add_fabric(&crypto, &mut fabrics, 0xc, 0x1c);
3036        fabrics.remove(idx(1)).unwrap();
3037
3038        let store = MemKvBlobStore::default();
3039        let kv = MemKv::new(store.clone());
3040        store_all(&fabrics, &kv);
3041
3042        assert_eq!(load_all(&kv).next_fab_idx(), idx(4));
3043
3044        for unreadable in [&[0xff][..], &[0x04, 0x00], &[0x04, 0xff]] {
3045            let mut raw = store.clone();
3046            raw.store(NEXT_FABRIC_INDEX_KEY, unreadable, &mut [])
3047                .unwrap();
3048
3049            assert_eq!(load_all(&kv).next_fab_idx(), idx(4));
3050        }
3051    }
3052
3053    #[test]
3054    fn unloadable_fabric_keeps_its_index() {
3055        let mut store = MemKvBlobStore::default();
3056        store
3057            .store(FABRIC_KEYS_START + 1, &[0xff], &mut [])
3058            .unwrap();
3059
3060        let mut fabrics = load_all(&MemKv::new(store));
3061        assert_eq!(fabrics.iter().count(), 0);
3062
3063        let fabric = fabrics.add_with_post_init(|_| Ok(())).unwrap();
3064        assert_eq!(fabric.fab_idx(), idx(2));
3065    }
3066
3067    #[test]
3068    fn fabric_removal_drops_its_acl_and_groups() {
3069        let crypto = test_only_crypto();
3070        let mut fabrics = Fabrics::new();
3071
3072        let rcac = mint_rcac(&crypto, 0xfab, 0x77);
3073        let noc = mint_noc(&crypto, &rcac, true, 0x1234);
3074
3075        let add = |fabrics: &mut Fabrics| -> NonZeroU8 {
3076            fabrics
3077                .add(
3078                    &crypto,
3079                    noc.key.reference(),
3080                    &rcac.cert,
3081                    &noc.cert,
3082                    &[],
3083                    Some(CanonAeadKeyRef::new(&TEST_IPK)),
3084                    0xfff1,
3085                    0x1234,
3086                )
3087                .unwrap()
3088                .fab_idx()
3089        };
3090
3091        let fab_idx = add(&mut fabrics);
3092        {
3093            let fabric = fabrics.get_mut(fab_idx).unwrap();
3094            fabric
3095                .acl_add(AclEntry::new(None, Privilege::VIEW, AuthMode::Case))
3096                .unwrap();
3097            assert_eq!(fabric.acl().len(), 2);
3098
3099            #[cfg(feature = "groups")]
3100            {
3101                fabric.groups_mut().add(1, 0x100, "g").unwrap();
3102                assert_eq!(fabric.groups().group_count(), 1);
3103            }
3104        }
3105
3106        fabrics.remove(fab_idx).unwrap();
3107        assert_eq!(fabrics.iter().count(), 0);
3108
3109        // A fabric re-added with the same identity starts from a clean slate
3110        let fab_idx = add(&mut fabrics);
3111        let fabric = fabrics.get(fab_idx).unwrap();
3112        assert_eq!(fabric.acl().len(), 1);
3113        assert_eq!(fabric.label(), "");
3114
3115        #[cfg(feature = "groups")]
3116        {
3117            assert_eq!(fabric.groups().group_count(), 0);
3118            assert_eq!(fabric.groups().key_set_iter().count(), 0);
3119            assert_eq!(fabric.groups().key_map_iter().count(), 0);
3120        }
3121    }
3122
3123    #[cfg(feature = "groups")]
3124    mod groups {
3125        use crate::crypto::{CanonAeadKey, CanonAeadKeyRef, AEAD_CANON_KEY_LEN};
3126        use crate::error::ErrorCode;
3127        use crate::fabric::MulticastAddrPolicy;
3128        use crate::fabric::{
3129            GroupKeyMapping, Groups, GROUP_ENDPOINTS_PER_FABRIC, MAX_GROUPS_PER_FABRIC,
3130            MAX_GROUP_KEYS_PER_FABRIC, MAX_GROUP_NAME_LEN,
3131        };
3132        use crate::group_keys::{GroupEpochKeyEntry, GroupKeySet};
3133
3134        fn key_set(id: u16, policy: u8) -> GroupKeySet {
3135            let mut key_set = GroupKeySet {
3136                group_key_set_id: id,
3137                group_key_security_policy: policy,
3138                epoch_keys: crate::utils::storage::Vec::new(),
3139            };
3140            key_set
3141                .epoch_keys
3142                .push(GroupEpochKeyEntry {
3143                    epoch_key: CanonAeadKey::new_from_ref(CanonAeadKeyRef::new(
3144                        &[id as u8; AEAD_CANON_KEY_LEN],
3145                    )),
3146                    epoch_start_time: id as u64,
3147                })
3148                .unwrap();
3149            key_set
3150        }
3151
3152        #[test]
3153        fn key_set_add_get_remove_iter_and_capacity() {
3154            let mut groups = Groups::new();
3155
3156            assert!(groups.key_set_get(1).is_none());
3157            assert_eq!(groups.key_set_iter().count(), 0);
3158
3159            groups.key_set_add(key_set(1, 0)).unwrap();
3160            groups.key_set_add(key_set(2, 0)).unwrap();
3161            assert_eq!(groups.key_set_get(1).unwrap().group_key_security_policy, 0);
3162            assert_eq!(
3163                groups.key_set_get(2).unwrap().epoch_keys[0].epoch_start_time,
3164                2
3165            );
3166
3167            // Re-adding an existing ID replaces it in place
3168            groups.key_set_add(key_set(1, 1)).unwrap();
3169            assert_eq!(groups.key_set_get(1).unwrap().group_key_security_policy, 1);
3170            let ids: std::vec::Vec<_> = groups.key_set_iter().map(|k| k.group_key_set_id).collect();
3171            assert_eq!(ids, [1, 2]);
3172
3173            for id in 3..=MAX_GROUP_KEYS_PER_FABRIC as u16 {
3174                groups.key_set_add(key_set(id, 0)).unwrap();
3175            }
3176            assert_eq!(groups.key_set_iter().count(), MAX_GROUP_KEYS_PER_FABRIC);
3177            assert_eq!(
3178                groups
3179                    .key_set_add(key_set(MAX_GROUP_KEYS_PER_FABRIC as u16 + 1, 0))
3180                    .unwrap_err()
3181                    .code(),
3182                ErrorCode::ResourceExhausted
3183            );
3184
3185            groups.key_set_remove(1).unwrap();
3186            assert!(groups.key_set_get(1).is_none());
3187            assert_eq!(groups.key_set_iter().count(), MAX_GROUP_KEYS_PER_FABRIC - 1);
3188            assert_eq!(
3189                groups.key_set_remove(1).unwrap_err().code(),
3190                ErrorCode::NotFound
3191            );
3192        }
3193
3194        #[test]
3195        fn key_set_remove_drops_key_map_entries_referencing_it() {
3196            let mut groups = Groups::new();
3197
3198            groups.key_set_add(key_set(1, 0)).unwrap();
3199            groups.key_set_add(key_set(2, 0)).unwrap();
3200            groups.key_map_set_group(0x100, 1).unwrap();
3201            groups.key_map_set_group(0x101, 2).unwrap();
3202            groups.key_map_set_group(0x102, 1).unwrap();
3203
3204            groups.key_set_remove(1).unwrap();
3205
3206            let map: std::vec::Vec<_> = groups
3207                .key_map_iter()
3208                .map(|m| (m.group_id, m.group_key_set_id))
3209                .collect();
3210            assert_eq!(map, [(0x101, 2)]);
3211            assert_eq!(groups.key_map_get(0x100), None);
3212            assert_eq!(groups.key_map_get(0x101), Some(2));
3213        }
3214
3215        #[test]
3216        fn key_map_add_replace_get_set_and_remove() {
3217            let mut groups = Groups::new();
3218
3219            groups
3220                .key_map_add(GroupKeyMapping {
3221                    group_id: 0x100,
3222                    group_key_set_id: 1,
3223                })
3224                .unwrap();
3225            assert_eq!(groups.key_map_get(0x100), Some(1));
3226            assert_eq!(groups.key_map_get(0x101), None);
3227
3228            // `key_map_add` does not dedupe; `key_map_get` returns the first match
3229            groups
3230                .key_map_add(GroupKeyMapping {
3231                    group_id: 0x100,
3232                    group_key_set_id: 2,
3233                })
3234                .unwrap();
3235            assert_eq!(groups.key_map_iter().count(), 2);
3236            assert_eq!(groups.key_map_get(0x100), Some(1));
3237
3238            // `key_map_set_group` replaces the (first) mapping of the group
3239            groups.key_map_set_group(0x100, 3).unwrap();
3240            assert_eq!(groups.key_map_get(0x100), Some(3));
3241            groups.key_map_set_group(0x101, 1).unwrap();
3242            assert_eq!(groups.key_map_get(0x101), Some(1));
3243            assert_eq!(groups.key_map_iter().count(), 3);
3244
3245            // `key_map_remove_group` drops every mapping of the group
3246            groups.key_map_remove_group(0x100);
3247            let map: std::vec::Vec<_> = groups
3248                .key_map_iter()
3249                .map(|m| (m.group_id, m.group_key_set_id))
3250                .collect();
3251            assert_eq!(map, [(0x101, 1)]);
3252
3253            // `key_map_replace` swaps the whole table
3254            groups
3255                .key_map_replace([(0x200, 5), (0x201, 6)].into_iter().map(
3256                    |(group_id, group_key_set_id)| GroupKeyMapping {
3257                        group_id,
3258                        group_key_set_id,
3259                    },
3260                ))
3261                .unwrap();
3262            let map: std::vec::Vec<_> = groups
3263                .key_map_iter()
3264                .map(|m| (m.group_id, m.group_key_set_id))
3265                .collect();
3266            assert_eq!(map, [(0x200, 5), (0x201, 6)]);
3267
3268            groups.key_map_remove_by_key_set(5);
3269            assert_eq!(groups.key_map_get(0x200), None);
3270            assert_eq!(groups.key_map_get(0x201), Some(6));
3271        }
3272
3273        #[test]
3274        fn key_map_capacity() {
3275            let mut groups = Groups::new();
3276
3277            for i in 0..MAX_GROUPS_PER_FABRIC as u16 {
3278                groups.key_map_set_group(0x100 + i, 1).unwrap();
3279            }
3280            assert_eq!(groups.key_map_iter().count(), MAX_GROUPS_PER_FABRIC);
3281
3282            assert_eq!(
3283                groups.key_map_set_group(0x1ff, 1).unwrap_err().code(),
3284                ErrorCode::ResourceExhausted
3285            );
3286            assert_eq!(
3287                groups
3288                    .key_map_add(GroupKeyMapping {
3289                        group_id: 0x1ff,
3290                        group_key_set_id: 1,
3291                    })
3292                    .unwrap_err()
3293                    .code(),
3294                ErrorCode::Failure
3295            );
3296
3297            // Replacing an existing group's mapping still works when full
3298            groups.key_map_set_group(0x100, 2).unwrap();
3299            assert_eq!(groups.key_map_get(0x100), Some(2));
3300
3301            assert_eq!(
3302                groups
3303                    .key_map_replace((0..=MAX_GROUPS_PER_FABRIC as u16).map(|i| GroupKeyMapping {
3304                        group_id: i,
3305                        group_key_set_id: 1,
3306                    }))
3307                    .unwrap_err()
3308                    .code(),
3309                ErrorCode::ResourceExhausted
3310            );
3311        }
3312
3313        #[test]
3314        fn endpoint_mapping_add_get_and_remove() {
3315            let mut groups = Groups::new();
3316
3317            assert!(groups.get(0x100).is_none());
3318            assert_eq!(groups.group_count(), 0);
3319
3320            // First membership creates the group; a repeat reports it as existing
3321            assert!(!groups.add(1, 0x100, "kitchen").unwrap());
3322            assert!(groups.add(1, 0x100, "kitchen").unwrap());
3323            assert!(!groups.add(2, 0x100, "cuisine").unwrap());
3324            assert!(!groups.add(2, 0x101, "hall").unwrap());
3325            assert_eq!(groups.group_count(), 2);
3326
3327            let entry = groups.get(0x100).unwrap();
3328            assert_eq!(entry.endpoints.as_slice(), &[1, 2]);
3329            // The most recent add renames the group
3330            assert_eq!(entry.group_name.as_str(), "cuisine");
3331            assert!(!entry.has_aux_acl());
3332            assert!(!entry.groupcast_managed());
3333            assert!(matches!(
3334                entry.effective_mcast_policy(),
3335                MulticastAddrPolicy::PerGroup
3336            ));
3337
3338            let ids: std::vec::Vec<_> = groups.iter().map(|e| e.group_id).collect();
3339            assert_eq!(ids, [0x100, 0x101]);
3340
3341            groups.get_mut(0x101).unwrap().group_name.clear();
3342            assert_eq!(groups.get(0x101).unwrap().group_name.as_str(), "");
3343            assert!(groups.get_mut(0x1ff).is_none());
3344
3345            // Removing a non-member is a no-op
3346            assert!(!groups.remove(7, Some(0x100)));
3347            assert!(!groups.remove(1, Some(0x101)));
3348
3349            // Removing from one group leaves the others alone
3350            assert!(groups.remove(1, Some(0x100)));
3351            assert_eq!(groups.get(0x100).unwrap().endpoints.as_slice(), &[2]);
3352
3353            // Removing from all groups; legacy groups left empty disappear
3354            assert!(groups.remove(2, None));
3355            assert!(groups.get(0x100).is_none());
3356            assert!(groups.get(0x101).is_none());
3357            assert_eq!(groups.group_count(), 0);
3358        }
3359
3360        #[test]
3361        fn endpoint_mapping_capacity_and_name_length() {
3362            let mut groups = Groups::new();
3363
3364            for i in 0..MAX_GROUPS_PER_FABRIC as u16 {
3365                groups.add(1, 0x100 + i, "g").unwrap();
3366            }
3367            assert_eq!(groups.group_count(), MAX_GROUPS_PER_FABRIC);
3368            assert_eq!(
3369                groups.add(1, 0x1ff, "g").unwrap_err().code(),
3370                ErrorCode::ResourceExhausted
3371            );
3372
3373            // An existing group still accepts endpoints up to its own capacity
3374            for ep in 2..=GROUP_ENDPOINTS_PER_FABRIC as u16 {
3375                groups.add(ep, 0x100, "g").unwrap();
3376            }
3377            assert_eq!(
3378                groups.get(0x100).unwrap().endpoints.len(),
3379                GROUP_ENDPOINTS_PER_FABRIC
3380            );
3381            assert_eq!(
3382                groups
3383                    .add(GROUP_ENDPOINTS_PER_FABRIC as u16 + 1, 0x100, "g")
3384                    .unwrap_err()
3385                    .code(),
3386                ErrorCode::ResourceExhausted
3387            );
3388
3389            let mut fresh = Groups::new();
3390            fresh
3391                .add(1, 0x100, &"n".repeat(MAX_GROUP_NAME_LEN))
3392                .unwrap();
3393            assert_eq!(
3394                fresh
3395                    .add(1, 0x101, &"n".repeat(MAX_GROUP_NAME_LEN + 1))
3396                    .unwrap_err()
3397                    .code(),
3398                ErrorCode::ConstraintError
3399            );
3400            assert_eq!(fresh.group_count(), 1);
3401
3402            // A rejected name leaves an existing group's name and members untouched
3403            assert_eq!(
3404                fresh
3405                    .add(2, 0x100, &"n".repeat(MAX_GROUP_NAME_LEN + 1))
3406                    .unwrap_err()
3407                    .code(),
3408                ErrorCode::ConstraintError
3409            );
3410            let entry = fresh.get(0x100).unwrap();
3411            assert_eq!(entry.group_name.as_str(), "n".repeat(MAX_GROUP_NAME_LEN));
3412            assert_eq!(entry.endpoints.as_slice(), &[1]);
3413        }
3414
3415        #[test]
3416        fn groupcast_join_and_remove() {
3417            let mut groups = Groups::new();
3418
3419            // A new Groupcast membership defaults to the IANA address policy
3420            groups
3421                .groupcast_join(0x100, &[1, 2, 2], false, None)
3422                .unwrap();
3423            let entry = groups.get(0x100).unwrap();
3424            assert_eq!(entry.endpoints.as_slice(), &[1, 2]);
3425            assert_eq!(entry.group_name.as_str(), "");
3426            assert!(entry.groupcast_managed());
3427            assert!(!entry.has_aux_acl());
3428            assert!(matches!(
3429                entry.effective_mcast_policy(),
3430                MulticastAddrPolicy::IanaAddr
3431            ));
3432
3433            // Appending dedupes; replacing swaps the list; policy updates when given
3434            groups
3435                .groupcast_join(0x100, &[2, 3], false, Some(MulticastAddrPolicy::PerGroup))
3436                .unwrap();
3437            let entry = groups.get(0x100).unwrap();
3438            assert_eq!(entry.endpoints.as_slice(), &[1, 2, 3]);
3439            assert!(matches!(
3440                entry.effective_mcast_policy(),
3441                MulticastAddrPolicy::PerGroup
3442            ));
3443
3444            groups.groupcast_join(0x100, &[9], true, None).unwrap();
3445            let entry = groups.get(0x100).unwrap();
3446            assert_eq!(entry.endpoints.as_slice(), &[9]);
3447            assert!(matches!(
3448                entry.effective_mcast_policy(),
3449                MulticastAddrPolicy::PerGroup
3450            ));
3451
3452            // A sender-only membership has no endpoints but still exists
3453            groups.groupcast_join(0x101, &[], false, None).unwrap();
3454            assert_eq!(groups.get(0x101).unwrap().endpoints.len(), 0);
3455            assert_eq!(groups.group_count(), 2);
3456
3457            // Joining a legacy (Groups cluster) entry upgrades it, keeping the
3458            // legacy-compatible PerGroup policy unless told otherwise
3459            groups.add(4, 0x102, "legacy").unwrap();
3460            groups.groupcast_join(0x102, &[5], false, None).unwrap();
3461            let entry = groups.get(0x102).unwrap();
3462            assert!(entry.groupcast_managed());
3463            assert_eq!(entry.endpoints.as_slice(), &[4, 5]);
3464            assert_eq!(entry.group_name.as_str(), "legacy");
3465            assert!(matches!(
3466                entry.effective_mcast_policy(),
3467                MulticastAddrPolicy::PerGroup
3468            ));
3469
3470            // Endpoint removal keeps an emptied Groupcast-managed entry around
3471            assert!(groups.remove(9, None));
3472            assert!(groups.get(0x100).is_some());
3473            assert_eq!(groups.get(0x100).unwrap().endpoints.len(), 0);
3474
3475            assert!(groups.groupcast_remove(0x100));
3476            assert!(groups.get(0x100).is_none());
3477            assert!(!groups.groupcast_remove(0x100));
3478            assert_eq!(groups.group_count(), 2);
3479        }
3480
3481        #[test]
3482        fn groupcast_join_capacity() {
3483            let mut groups = Groups::new();
3484
3485            for i in 0..MAX_GROUPS_PER_FABRIC as u16 {
3486                groups.groupcast_join(0x100 + i, &[], false, None).unwrap();
3487            }
3488            assert_eq!(
3489                groups
3490                    .groupcast_join(0x1ff, &[], false, None)
3491                    .unwrap_err()
3492                    .code(),
3493                ErrorCode::ResourceExhausted
3494            );
3495
3496            let endpoints: std::vec::Vec<u16> = (1..=GROUP_ENDPOINTS_PER_FABRIC as u16).collect();
3497            groups
3498                .groupcast_join(0x100, &endpoints, false, None)
3499                .unwrap();
3500            assert_eq!(
3501                groups
3502                    .groupcast_join(0x100, &[0xee], false, None)
3503                    .unwrap_err()
3504                    .code(),
3505                ErrorCode::ResourceExhausted
3506            );
3507            assert_eq!(
3508                groups.get(0x100).unwrap().endpoints.len(),
3509                GROUP_ENDPOINTS_PER_FABRIC
3510            );
3511        }
3512
3513        #[test]
3514        fn set_has_aux_acl_reports_changes() {
3515            let mut groups = Groups::new();
3516
3517            assert!(!groups.set_has_aux_acl(0x100, true));
3518
3519            groups.groupcast_join(0x100, &[1], false, None).unwrap();
3520            assert!(!groups.get(0x100).unwrap().has_aux_acl());
3521
3522            assert!(groups.set_has_aux_acl(0x100, true));
3523            assert!(groups.get(0x100).unwrap().has_aux_acl());
3524            assert!(!groups.set_has_aux_acl(0x100, true));
3525            assert!(groups.set_has_aux_acl(0x100, false));
3526            assert!(!groups.get(0x100).unwrap().has_aux_acl());
3527
3528            // Legacy entries have no flag set; setting one works the same way
3529            groups.add(1, 0x101, "g").unwrap();
3530            assert!(!groups.set_has_aux_acl(0x101, false));
3531            assert!(groups.set_has_aux_acl(0x101, true));
3532            assert!(groups.get(0x101).unwrap().has_aux_acl());
3533        }
3534    }
3535}