Skip to main content

rs_matter_node_core/
acl.rs

1/*
2 *
3 *    Copyright (c) 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
18//! This module contains the implementation of the `rs-matter` Access Control List (ACL)
19
20use core::fmt::Display;
21use core::num::NonZeroU8;
22use core::ops::RangeInclusive;
23
24use cfg_if::cfg_if;
25
26use num::FromPrimitive;
27use num_derive::FromPrimitive;
28
29use crate::dm::{Access, ClusterId, DeviceType, EndptId, NodeId, Privilege};
30use crate::error::{Error, ErrorCode};
31use crate::fabric::Fabrics;
32use crate::im::GenericPath;
33use crate::session::{SessionMode, MAX_CAT_IDS_PER_NOC};
34use crate::tlv::{
35    FromTLV, Nullable, TLVElement, TLVTag, TLVWrite, TlvError, TlvErrorCode, ToTLV, TLV,
36};
37use crate::utils::init::{init, Init};
38use crate::utils::storage::Vec;
39
40cfg_if! {
41    if #[cfg(feature = "max-subjects-per-acl-32")] {
42        /// Max subjects per ACL entry
43        pub const MAX_SUBJECTS_PER_ACL_ENTRY: usize = 32;
44    } else if #[cfg(feature = "max-subjects-per-acl-16")] {
45        /// Max subjects per ACL entry
46        pub const MAX_SUBJECTS_PER_ACL_ENTRY: usize = 16;
47    } else if #[cfg(feature = "max-subjects-per-acl-8")] {
48        /// Max subjects per ACL entry
49        pub const MAX_SUBJECTS_PER_ACL_ENTRY: usize = 8;
50    } else if #[cfg(feature = "max-subjects-per-acl-7")] {
51        /// Max subjects per ACL entry
52        pub const MAX_SUBJECTS_PER_ACL_ENTRY: usize = 7;
53    } else if #[cfg(feature = "max-subjects-per-acl-6")] {
54        /// Max subjects per ACL entry
55        pub const MAX_SUBJECTS_PER_ACL_ENTRY: usize = 6;
56    } else if #[cfg(feature = "max-subjects-per-acl-5")] {
57        /// Max subjects per ACL entry
58        pub const MAX_SUBJECTS_PER_ACL_ENTRY: usize = 5;
59    } else if #[cfg(feature = "max-subjects-per-acl-4")] {
60        /// Max subjects per ACL entry
61        pub const MAX_SUBJECTS_PER_ACL_ENTRY: usize = 4;
62    } else if #[cfg(feature = "max-subjects-per-acl-3")] {
63        /// Max subjects per ACL entry
64        pub const MAX_SUBJECTS_PER_ACL_ENTRY: usize = 3;
65    } else if #[cfg(feature = "max-subjects-per-acl-2")] {
66        /// Max subjects per ACL entry
67        pub const MAX_SUBJECTS_PER_ACL_ENTRY: usize = 2;
68    } else if #[cfg(feature = "max-subjects-per-acl-1")] {
69        /// Max subjects per ACL entry
70        pub const MAX_SUBJECTS_PER_ACL_ENTRY: usize = 1;
71    } else {
72        /// Max subjects per ACL entry
73        pub const MAX_SUBJECTS_PER_ACL_ENTRY: usize = 4;
74    }
75}
76
77cfg_if! {
78    if #[cfg(feature = "max-targets-per-acl-32")] {
79        /// Max targets per ACL entry
80        pub const MAX_TARGETS_PER_ACL_ENTRY: usize = 32;
81    } else if #[cfg(feature = "max-targets-per-acl-16")] {
82        /// Max targets per ACL entry
83        pub const MAX_TARGETS_PER_ACL_ENTRY: usize = 16;
84    } else if #[cfg(feature = "max-targets-per-acl-8")] {
85        /// Max targets per ACL entry
86        pub const MAX_TARGETS_PER_ACL_ENTRY: usize = 8;
87    } else if #[cfg(feature = "max-targets-per-acl-7")] {
88        /// Max targets per ACL entry
89        pub const MAX_TARGETS_PER_ACL_ENTRY: usize = 7;
90    } else if #[cfg(feature = "max-targets-per-acl-6")] {
91        /// Max targets per ACL entry
92        pub const MAX_TARGETS_PER_ACL_ENTRY: usize = 6;
93    } else if #[cfg(feature = "max-targets-per-acl-5")] {
94        /// Max targets per ACL entry
95        pub const MAX_TARGETS_PER_ACL_ENTRY: usize = 5;
96    } else if #[cfg(feature = "max-targets-per-acl-4")] {
97        /// Max targets per ACL entry
98        pub const MAX_TARGETS_PER_ACL_ENTRY: usize = 4;
99    } else if #[cfg(feature = "max-targets-per-acl-3")] {
100        /// Max targets per ACL entry
101        pub const MAX_TARGETS_PER_ACL_ENTRY: usize = 3;
102    } else if #[cfg(feature = "max-targets-per-acl-2")] {
103        /// Max targets per ACL entry
104        pub const MAX_TARGETS_PER_ACL_ENTRY: usize = 2;
105    } else if #[cfg(feature = "max-targets-per-acl-1")] {
106        /// Max targets per ACL entry
107        pub const MAX_TARGETS_PER_ACL_ENTRY: usize = 1;
108    } else {
109        /// Max targets per ACL entry
110        pub const MAX_TARGETS_PER_ACL_ENTRY: usize = 3;
111    }
112}
113
114cfg_if! {
115    if #[cfg(feature = "max-acls-per-fabric-32")] {
116        /// Max ACL entries per fabric
117        pub const MAX_ACL_ENTRIES_PER_FABRIC: usize = 32;
118    } else if #[cfg(feature = "max-acls-per-fabric-16")] {
119        /// Max ACL entries per fabric
120        pub const MAX_ACL_ENTRIES_PER_FABRIC: usize = 16;
121    } else if #[cfg(feature = "max-acls-per-fabric-8")] {
122        /// Max ACL entries per fabric
123        pub const MAX_ACL_ENTRIES_PER_FABRIC: usize = 8;
124    } else if #[cfg(feature = "max-acls-per-fabric-7")] {
125        /// Max ACL entries per fabric
126        pub const MAX_ACL_ENTRIES_PER_FABRIC: usize = 7;
127    } else if #[cfg(feature = "max-acls-per-fabric-6")] {
128        /// Max ACL entries per fabric
129        pub const MAX_ACL_ENTRIES_PER_FABRIC: usize = 6;
130    } else if #[cfg(feature = "max-acls-per-fabric-5")] {
131        /// Max ACL entries per fabric
132        pub const MAX_ACL_ENTRIES_PER_FABRIC: usize = 5;
133    } else if #[cfg(feature = "max-acls-per-fabric-4")] {
134        /// Max ACL entries per fabric
135        pub const MAX_ACL_ENTRIES_PER_FABRIC: usize = 4;
136    } else if #[cfg(feature = "max-acls-per-fabric-3")] {
137        /// Max ACL entries per fabric
138        pub const MAX_ACL_ENTRIES_PER_FABRIC: usize = 3;
139    } else if #[cfg(feature = "max-acls-per-fabric-2")] {
140        /// Max ACL entries per fabric
141        pub const MAX_ACL_ENTRIES_PER_FABRIC: usize = 2;
142    } else if #[cfg(feature = "max-acls-per-fabric-1")] {
143        /// Max ACL entries per fabric
144        pub const MAX_ACL_ENTRIES_PER_FABRIC: usize = 1;
145    } else {
146        /// Max ACL entries per fabric
147        pub const MAX_ACL_ENTRIES_PER_FABRIC: usize = 4;
148    }
149}
150
151/// An enum modeling the different authentication modes
152// TODO: Check if this and the SessionMode can be combined into some generic data structure
153#[derive(FromPrimitive, Copy, Clone, PartialEq, Debug)]
154#[cfg_attr(feature = "defmt", derive(defmt::Format))]
155#[repr(u8)]
156///
157/// The values are the ones of the Access Control cluster.
158pub enum AuthMode {
159    /// PASE authentication
160    Pase = 1,
161    /// CASE authentication
162    Case = 2,
163    /// Group authentication
164    Group = 3,
165}
166
167impl FromTLV<'_> for AuthMode {
168    fn from_tlv(t: &TLVElement) -> Result<Self, TlvError>
169    where
170        Self: Sized,
171    {
172        Self::from_u8(t.u8()?).ok_or(TlvErrorCode::InvalidValue.into())
173    }
174}
175
176impl ToTLV for AuthMode {
177    fn to_tlv<W: TLVWrite>(&self, tag: &TLVTag, mut tw: W) -> Result<(), TlvError> {
178        tw.u8(tag, *self as _)
179    }
180
181    fn tlv_iter(&self, tag: TLVTag) -> impl Iterator<Item = Result<TLV<'_>, TlvError>> {
182        TLV::u8(tag, *self as _).into_tlv_iter()
183    }
184}
185
186/// The type of an auxiliary ACL entry: one that the node synthesizes rather
187/// than an administrator writes.
188///
189/// The values are the ones of the Access Control cluster.
190#[derive(FromPrimitive, Copy, Clone, PartialEq, Eq, Debug)]
191#[cfg_attr(feature = "defmt", derive(defmt::Format))]
192#[repr(u8)]
193pub enum AuxiliaryType {
194    /// Synthesized by the system
195    System = 0,
196    /// Synthesized for the Groupcast cluster
197    Groupcast = 1,
198}
199
200impl FromTLV<'_> for AuxiliaryType {
201    fn from_tlv(t: &TLVElement) -> Result<Self, TlvError>
202    where
203        Self: Sized,
204    {
205        Self::from_u8(t.u8()?).ok_or(TlvErrorCode::InvalidValue.into())
206    }
207}
208
209impl ToTLV for AuxiliaryType {
210    fn to_tlv<W: TLVWrite>(&self, tag: &TLVTag, mut tw: W) -> Result<(), TlvError> {
211        tw.u8(tag, *self as _)
212    }
213
214    fn tlv_iter(&self, tag: TLVTag) -> impl Iterator<Item = Result<TLV<'_>, TlvError>> {
215        TLV::u8(tag, *self as _).into_tlv_iter()
216    }
217}
218
219/// An accessor can have as many identities: one node id and up to MAX_CAT_IDS_PER_NOC
220const MAX_ACCESSOR_SUBJECTS: usize = 1 + MAX_CAT_IDS_PER_NOC;
221
222/// The CAT Prefix used in Subjects
223pub const NOC_CAT_SUBJECT_PREFIX: u64 = 0xFFFF_FFFD_0000_0000;
224pub const NOC_CAT_SUBJECT_MASK: u64 = 0xFFFF_FFFF_0000_0000;
225
226const NOC_CAT_ID_MASK: u64 = 0xFFFF_0000;
227const NOC_CAT_VERSION_MASK: u64 = 0xFFFF;
228
229/// The Node ID min range
230const NODE_ID_RANGE: RangeInclusive<u64> = 1..=0xFFFF_FFEF_FFFF_FFFF;
231
232/// Is this identifier a NOC CAT
233pub fn is_noc_cat(id: u64) -> bool {
234    ((id & NOC_CAT_SUBJECT_MASK) == NOC_CAT_SUBJECT_PREFIX)
235        && ((id & (NOC_CAT_ID_MASK | NOC_CAT_VERSION_MASK)) > 0)
236}
237
238/// Get the 16-bit NOC CAT id from the identifier
239fn get_noc_cat_id(id: u64) -> u64 {
240    (id & NOC_CAT_ID_MASK) >> 16
241}
242
243/// Get the 16-bit NOC CAT version from the identifier
244fn get_noc_cat_version(id: u64) -> u64 {
245    id & NOC_CAT_VERSION_MASK
246}
247
248/// Generate CAT that is embeddedable in the NoC
249/// This only generates the 32-bit CAT ID
250pub fn gen_noc_cat(id: u16, version: u16) -> u32 {
251    ((id as u32) << 16) | version as u32
252}
253
254/// Is this identifier a node id
255pub fn is_node(id: u64) -> bool {
256    NODE_ID_RANGE.contains(&id)
257}
258
259/// The Subjects that identify the Accessor
260pub struct AccessorSubjects([u64; MAX_ACCESSOR_SUBJECTS]);
261
262impl AccessorSubjects {
263    /// Create a new AccessorSubjects object
264    /// The first subject is the node id
265    pub fn new(id: u64) -> Self {
266        let mut a = Self(Default::default());
267        a.0[0] = id;
268        a
269    }
270
271    /// Add a CAT id to the AccessorSubjects
272    pub fn add_catid(&mut self, subject: u32) -> Result<(), Error> {
273        for (i, val) in self.0.iter().enumerate() {
274            if *val == 0 {
275                self.0[i] = NOC_CAT_SUBJECT_PREFIX | (subject as u64);
276                return Ok(());
277            }
278        }
279        Err(ErrorCode::ResourceExhausted.into())
280    }
281
282    /// Match the acl_subject with any of the current subjects
283    /// If a NOC CAT is specified, CAT aware matching is also performed
284    pub fn matches(&self, acl_subject: u64) -> bool {
285        for v in self.0.iter() {
286            if *v == 0 {
287                continue;
288            }
289
290            if *v == acl_subject {
291                return true;
292            } else {
293                // NOC CAT match
294                if is_noc_cat(*v)
295                    && is_noc_cat(acl_subject)
296                    && (get_noc_cat_id(*v) == get_noc_cat_id(acl_subject))
297                    && (get_noc_cat_version(*v) >= get_noc_cat_version(acl_subject))
298                {
299                    return true;
300                }
301            }
302        }
303
304        false
305    }
306}
307
308impl Display for AccessorSubjects {
309    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::result::Result<(), core::fmt::Error> {
310        write!(f, "[")?;
311        for i in self.0 {
312            if is_noc_cat(i) {
313                write!(f, "CAT({} - {})", get_noc_cat_id(i), get_noc_cat_version(i))?;
314            } else if i != 0 {
315                write!(f, "{}, ", i)?;
316            }
317        }
318        write!(f, "]")
319    }
320}
321
322#[cfg(feature = "defmt")]
323impl defmt::Format for AccessorSubjects {
324    fn format(&self, f: defmt::Formatter) {
325        defmt::write!(f, "[");
326        for i in self.0 {
327            if is_noc_cat(i) {
328                defmt::write!(f, "CAT({} - {})", get_noc_cat_id(i), get_noc_cat_version(i));
329            } else if i != 0 {
330                defmt::write!(f, "{}, ", i);
331            }
332        }
333        defmt::write!(f, "]")
334    }
335}
336
337/// Who is making an access request.
338///
339/// `Accessor`, in `rs-matter-node`, puts this together with the fabric
340/// table that the requests are checked against.
341pub struct SubjectDescriptor {
342    /// The fabric index of the accessor
343    pub fab_idx: u8,
344    /// Whether AUX ACL was enabled at the time this accessor was instantiated
345    aux_acl_enabled: bool,
346    /// Accessor's subject: could be node-id, NoC CAT, group id
347    subjects: AccessorSubjects,
348    /// The auth mode of this session. Might be `None` for plain-text sessions
349    auth_mode: Option<AuthMode>,
350}
351
352impl SubjectDescriptor {
353    /// Create the subject descriptor of a session
354    ///
355    /// # Arguments
356    /// - `session_mode`: The mode of the session
357    /// - `peer_node_id`: The node ID of the peer of the session, if the session has one
358    /// - `aux_acl_enabled`: Whether AUX ACL is enabled
359    pub fn for_session(
360        session_mode: &SessionMode,
361        peer_node_id: Option<NodeId>,
362        aux_acl_enabled: bool,
363    ) -> Self {
364        match session_mode {
365            SessionMode::Case {
366                fab_idx, cat_ids, ..
367            } => {
368                let mut subject = AccessorSubjects::new(peer_node_id.unwrap_or_default());
369                for i in *cat_ids {
370                    if i != 0 {
371                        let _ = subject.add_catid(i);
372                    }
373                }
374                Self::new(
375                    fab_idx.get(),
376                    aux_acl_enabled,
377                    subject,
378                    Some(AuthMode::Case),
379                )
380            }
381            SessionMode::Pase { fab_idx } => Self::new(
382                *fab_idx,
383                aux_acl_enabled,
384                AccessorSubjects::new(1),
385                Some(AuthMode::Pase),
386            ),
387            SessionMode::Group { fab_idx, group_id } => Self::new(
388                fab_idx.get(),
389                aux_acl_enabled,
390                AccessorSubjects::new(*group_id as u64),
391                Some(AuthMode::Group),
392            ),
393            SessionMode::PlainText => Self::new(0, aux_acl_enabled, AccessorSubjects::new(1), None),
394        }
395    }
396
397    /// Create a new subject descriptor
398    ///
399    /// # Arguments
400    /// - `fab_idx`: The fabric index of the accessor (0 means no fabric index)
401    /// - `aux_acl_enabled`: Whether AUX ACL was enabled at the time this accessor was instantiated
402    /// - `subjects`: The subjects of the accessor
403    /// - `auth_mode`: The auth mode of the accessor
404    pub const fn new(
405        fab_idx: u8,
406        aux_acl_enabled: bool,
407        subjects: AccessorSubjects,
408        auth_mode: Option<AuthMode>,
409    ) -> Self {
410        Self {
411            fab_idx,
412            aux_acl_enabled,
413            subjects,
414            auth_mode,
415        }
416    }
417
418    pub fn fab_idx(&self) -> Result<NonZeroU8, Error> {
419        NonZeroU8::new(self.fab_idx).ok_or(ErrorCode::UnsupportedAccess.into())
420    }
421
422    /// Return whether AUX ACL was enabled at the time this accessor was instantiated
423    pub const fn aux_acl_enabled(&self) -> bool {
424        self.aux_acl_enabled
425    }
426
427    /// Return the subjects of the accessor
428    pub const fn subjects(&self) -> &AccessorSubjects {
429        &self.subjects
430    }
431
432    /// Return the auth mode of the accessor
433    pub const fn auth_mode(&self) -> Option<AuthMode> {
434        self.auth_mode
435    }
436
437    /// Return whether the given endpoint is accessible for this accessor.
438    ///
439    /// For group sessions, only endpoints that are members of the group are accessible.
440    /// For all other session types, all endpoints are accessible.
441    pub fn is_endpoint_accessible(&self, endpoint_id: EndptId, fabrics: &Fabrics) -> bool {
442        if self.auth_mode != Some(AuthMode::Group) {
443            return true;
444        }
445
446        // A group session reaches an endpoint only if that endpoint is a member
447        // of the session's group.
448        #[cfg(feature = "groups")]
449        {
450            let group_id = self.subjects.0[0] as u16;
451
452            let Some(fab_idx) = core::num::NonZeroU8::new(self.fab_idx) else {
453                return false;
454            };
455
456            let Some(fabric) = fabrics.get(fab_idx) else {
457                return false;
458            };
459
460            fabric
461                .groups()
462                .get(group_id)
463                .is_some_and(|e| e.endpoints.contains(&endpoint_id))
464        }
465
466        // Without multicast group support there are no group sessions, so
467        // `auth_mode` above is never `Group` and this point is unreachable. Deny
468        // anyway (fail closed): if a `Group` auth mode ever did reach here, it must
469        // not silently grant access to an endpoint.
470        #[cfg(not(feature = "groups"))]
471        {
472            let _ = (endpoint_id, fabrics);
473            false
474        }
475    }
476
477    /// Return the peer node ID (admin node ID) for CASE sessions, or None for PASE/other sessions.
478    pub fn peer_node_id(&self) -> Option<u64> {
479        if matches!(self.auth_mode, Some(AuthMode::Case)) {
480            let id = self.subjects.0[0];
481            if is_node(id) {
482                Some(id)
483            } else {
484                None
485            }
486        } else {
487            None
488        }
489    }
490}
491
492/// Access Descriptor Object
493#[derive(Debug)]
494#[cfg_attr(feature = "defmt", derive(defmt::Format))]
495pub struct AccessDesc<'a> {
496    /// The object to be acted upon
497    path: GenericPath,
498    /// The target permissions
499    target_perms: Option<Access>,
500    // The operation being done
501    operation: Access,
502    /// The device types of the endpoint hosting `path`. Used by ACL `Target`
503    /// entries that filter by `DeviceType` (Matter Core spec).
504    /// Empty when the access target's endpoint is unknown / not yet expanded.
505    device_types: &'a [DeviceType],
506}
507
508/// Access Request Object
509pub struct AccessReq<'a> {
510    /// The accessor requesting access
511    accessor: &'a SubjectDescriptor,
512    /// The object being accessed
513    object: AccessDesc<'a>,
514}
515
516impl<'a> AccessReq<'a> {
517    /// Create an access request object.
518    ///
519    /// An access request specifies the _accessor_ attempting to access _path_
520    /// with _operation_. `device_types` lists the device types declared by
521    /// the endpoint that hosts `path`; pass an empty slice when this is not
522    /// applicable (e.g. for unit tests that don't exercise `DeviceType` ACL
523    /// targets).
524    pub const fn new(
525        accessor: &'a SubjectDescriptor,
526        path: GenericPath,
527        operation: Access,
528        device_types: &'a [DeviceType],
529    ) -> Self {
530        AccessReq {
531            accessor,
532            object: AccessDesc {
533                path,
534                target_perms: None,
535                operation,
536                device_types,
537            },
538        }
539    }
540
541    /// Return the accessor of the request
542    pub fn accessor(&self) -> &SubjectDescriptor {
543        self.accessor
544    }
545
546    /// Return the operation of the request
547    pub fn operation(&self) -> Access {
548        self.object.operation
549    }
550
551    /// Add target's permissions to the request
552    ///
553    /// The permissions that are associated with the target (identified by the
554    /// path in the AccessReq) are added to the request
555    pub fn set_target_perms(&mut self, perms: Access) {
556        self.object.target_perms = Some(perms);
557    }
558
559    /// Check if access is allowed
560    ///
561    /// This checks all the ACL list to identify if any of the ACLs provides the
562    /// _accessor_ the necessary privileges to access the target as per its
563    /// permissions
564    pub fn allow(&self, fabrics: &Fabrics) -> bool {
565        let allow = fabrics.allow(self, self.accessor.aux_acl_enabled());
566
567        #[cfg(feature = "groups")]
568        let allow = allow || self.allow_groupcast_auxiliary(fabrics);
569
570        allow
571    }
572
573    /// Check whether access is granted by an auxiliary ACL entry synthesized
574    /// from the Groupcast group table: a Group-auth accessor whose group has
575    /// `HasAuxiliaryACL` set is granted the `Operate` privilege on the
576    /// group's endpoints (see the Groupcast Auxiliary ACL Handling section of
577    /// the Matter Core spec).
578    #[cfg(feature = "groups")]
579    fn allow_groupcast_auxiliary(&self, fabrics: &Fabrics) -> bool {
580        if !self.accessor.aux_acl_enabled() {
581            return false;
582        }
583
584        if self.accessor.auth_mode != Some(AuthMode::Group) {
585            return false;
586        }
587
588        let Ok(fab_idx) = self.accessor.fab_idx() else {
589            return false;
590        };
591
592        let Some(fabric) = fabrics.get(fab_idx) else {
593            return false;
594        };
595
596        // Synthesized entries always carry concrete endpoint targets
597        let Some(endpoint) = self.object.path.endpoint else {
598            return false;
599        };
600
601        let granted = fabric.groups().iter().any(|entry| {
602            entry.has_aux_acl()
603                && entry.endpoints.contains(&endpoint)
604                && self.accessor.subjects.matches(entry.group_id as u64)
605        });
606
607        granted
608            && self
609                .object
610                .target_perms
611                .is_some_and(|access| access.is_ok(self.object.operation, Privilege::OPERATE))
612    }
613}
614
615/// The target object
616#[derive(FromTLV, ToTLV, Clone, Debug, PartialEq)]
617#[cfg_attr(feature = "defmt", derive(defmt::Format))]
618pub struct Target {
619    pub cluster: Option<ClusterId>,
620    pub endpoint: Option<EndptId>,
621    pub device_type: Option<u32>,
622}
623
624impl Target {
625    /// Create a new target object
626    pub const fn new(
627        endpoint: Option<EndptId>,
628        cluster: Option<ClusterId>,
629        device_type: Option<u32>,
630    ) -> Self {
631        Self {
632            cluster,
633            endpoint,
634            device_type,
635        }
636    }
637}
638
639/// The ACL entry object
640#[derive(ToTLV, FromTLV, Clone, Debug, PartialEq)]
641#[cfg_attr(feature = "defmt", derive(defmt::Format))]
642#[tlvargs(start = 1)]
643pub struct AclEntry {
644    /// The privilege of the entry
645    privilege: Privilege,
646    /// The auth mode of the entry
647    auth_mode: AuthMode,
648    /// The subjects of the entry
649    subjects: Nullable<Vec<u64, MAX_SUBJECTS_PER_ACL_ENTRY>>,
650    /// The targets of the entry
651    targets: Nullable<Vec<Target, MAX_TARGETS_PER_ACL_ENTRY>>,
652    // TODO: Figure out what this is, document and use
653    auxiliary_type: Option<AuxiliaryType>,
654    // Note that this field will always be `Some(NN)` when the entry is persisted in storage,
655    // however, it will be `None` when the entry is coming from the other peer.
656    #[tagval(crate::im::FABRIC_INDEX_TAG)]
657    pub fab_idx: Option<NonZeroU8>,
658}
659
660impl AclEntry {
661    /// Create a new ACL entry object
662    pub const fn new(
663        fab_idx: Option<NonZeroU8>,
664        privilege: Privilege,
665        auth_mode: AuthMode,
666    ) -> Self {
667        Self {
668            fab_idx,
669            privilege,
670            auth_mode,
671            subjects: Nullable::none(),
672            targets: Nullable::none(),
673            auxiliary_type: None,
674        }
675    }
676
677    /// Return an initializer for an ACL entry object
678    /// using the given fabric index, privilege and auth mode as input
679    pub fn init(
680        fab_idx: Option<NonZeroU8>,
681        privilege: Privilege,
682        auth_mode: AuthMode,
683    ) -> impl Init<Self> {
684        init!(Self {
685            fab_idx,
686            privilege,
687            auth_mode,
688            subjects <- Nullable::init_none(),
689            targets <- Nullable::init_none(),
690            auxiliary_type: None,
691        })
692    }
693
694    /// Normalize the ACL entry by converting non-null but empty
695    /// subjects/targets to null, as the spec and YAML tests expect
696    pub fn normalize(&mut self) {
697        if self
698            .subjects
699            .as_opt_ref()
700            .map(|subjects| subjects.is_empty())
701            .unwrap_or(false)
702        {
703            self.subjects.clear();
704        }
705
706        if self
707            .targets
708            .as_opt_ref()
709            .map(|targets| targets.is_empty())
710            .unwrap_or(false)
711        {
712            self.targets.clear();
713        }
714    }
715
716    /// Return the privilege of the ACL entry
717    pub fn privilege(&self) -> Privilege {
718        self.privilege
719    }
720
721    /// Set the privilege of the ACL entry
722    pub fn set_privilege(&mut self, privilege: Privilege) {
723        self.privilege = privilege;
724    }
725
726    /// Return the auth mode of the ACL entry
727    pub fn auth_mode(&self) -> AuthMode {
728        self.auth_mode
729    }
730
731    /// Set the auth mode of the ACL entry
732    pub fn set_auth_mode(&mut self, auth_mode: AuthMode) {
733        self.auth_mode = auth_mode;
734    }
735
736    /// Return the subjects of the ACL entry
737    pub fn subjects(&self) -> Nullable<&[u64]> {
738        Nullable::new(self.subjects.as_opt_ref().map(|v| v.as_slice()))
739    }
740
741    /// Return the targets of the ACL entry
742    pub fn targets(&self) -> Nullable<&[Target]> {
743        Nullable::new(self.targets.as_opt_ref().map(|v| v.as_slice()))
744    }
745
746    /// Return the auxiliary type of the ACL entry, if it is an auxiliary one
747    pub fn auxiliary_type(&self) -> Option<AuxiliaryType> {
748        self.auxiliary_type
749    }
750
751    /// Check if the ACL entry allows access to the given accessor and object
752    ///
753    /// `aux_acl_enabled` conveys whether the node advertises the Access Control
754    /// cluster's `AUXILIARY` feature, which changes how wildcard-target
755    /// Group-auth entries are evaluated - see [`Self::match_access_desc`].
756    pub fn allow(&self, req: &AccessReq, aux_acl_enabled: bool) -> bool {
757        self.match_accessor(req.accessor) && self.match_access_desc(&req.object, aux_acl_enabled)
758    }
759
760    /// Add a subject to the ACL entry
761    pub fn add_subject(&mut self, subject: u64) -> Result<(), Error> {
762        if self.subjects.is_none() {
763            self.subjects.reinit(Nullable::init_some(Vec::init()));
764        }
765
766        unwrap!(self.subjects.as_opt_mut())
767            .push(subject)
768            .map_err(|_| ErrorCode::ResourceExhausted.into())
769    }
770
771    /// Add a CAT id to the ACL entry
772    pub fn add_subject_catid(&mut self, cat_id: u32) -> Result<(), Error> {
773        self.add_subject(NOC_CAT_SUBJECT_PREFIX | cat_id as u64)
774    }
775
776    /// Add a target to the ACL entry
777    pub fn add_target(&mut self, target: Target) -> Result<(), Error> {
778        if self.targets.is_none() {
779            self.targets.reinit(Nullable::init_some(Vec::init()));
780        }
781
782        unwrap!(self.targets.as_opt_mut())
783            .push(target)
784            .map_err(|_| ErrorCode::ResourceExhausted.into())
785    }
786
787    fn match_accessor(&self, accessor: &SubjectDescriptor) -> bool {
788        if Some(self.auth_mode) != accessor.auth_mode {
789            return false;
790        }
791
792        let allow = self.subjects().as_opt_ref().is_none_or(|subjects| {
793            // Subjects array null or empty implies allow for all subjects
794            // Otherwise, check if the accessor's subject matches any of the ACL entry's subjects
795            subjects.is_empty() || subjects.iter().any(|s| accessor.subjects.matches(*s))
796        });
797
798        // true if both are true
799        allow
800            && self
801                .fab_idx
802                .map(|fab_idx| fab_idx.get() == accessor.fab_idx)
803                .unwrap_or(false)
804    }
805
806    fn match_access_desc(&self, object: &AccessDesc, aux_acl_enabled: bool) -> bool {
807        // Per the Matter Core spec, when the Access Control cluster's
808        // `AUXILIARY` feature is advertised, an empty (wildcard) targets
809        // list on a Group-auth entry grants access to all endpoints
810        // *except* the root endpoint; without the feature it covers the
811        // whole node. (Explicitly-listed targets are unaffected.)
812        if aux_acl_enabled
813            && matches!(self.auth_mode, AuthMode::Group)
814            && object.path.endpoint == Some(crate::dm::ROOT_ENDPOINT_ID)
815            && self
816                .targets
817                .as_opt_ref()
818                .is_none_or(|targets| targets.is_empty())
819        {
820            return false;
821        }
822
823        let allow = self.targets.as_opt_ref().is_none_or(|targets| {
824            // Targets array null or empty implies allow for all targets
825            // Otherwise, check if the target matches any of the ACL entry's targets
826            targets.is_empty()
827                || targets.iter().any(|t| {
828                    let endpoint_match = t.endpoint.is_none() || t.endpoint == object.path.endpoint;
829                    let cluster_match = t.cluster.is_none() || t.cluster == object.path.cluster;
830                    // When `Target.device_type` is set, the access target's endpoint
831                    // must declare a matching device type in its `DeviceTypeList`
832                    // (Matter Core spec).
833                    let device_type_match = match t.device_type {
834                        Some(dt) => object
835                            .device_types
836                            .iter()
837                            .any(|endpoint_dt| endpoint_dt.dtype as u32 == dt),
838                        None => true,
839                    };
840                    endpoint_match && cluster_match && device_type_match
841                })
842        });
843
844        if allow {
845            // Check that the object's access allows this operation with this privilege
846            if let Some(access) = object.target_perms {
847                access.is_ok(object.operation, self.privilege)
848            } else {
849                false
850            }
851        } else {
852            false
853        }
854    }
855}
856
857#[cfg(test)]
858#[allow(clippy::bool_assert_comparison)]
859pub(crate) mod tests {
860    use core::num::NonZeroU8;
861
862    use crate::acl::{gen_noc_cat, AccessorSubjects};
863    use crate::dm::{Access, Privilege};
864    use crate::error::Error;
865    use crate::fabric::Fabrics;
866    use crate::im::GenericPath;
867
868    use super::{AccessReq, AclEntry, AuthMode, SubjectDescriptor, Target};
869
870    pub(crate) const FAB_1: NonZeroU8 = match NonZeroU8::new(1) {
871        Some(f) => f,
872        None => ::core::unreachable!(),
873    };
874
875    pub(crate) const FAB_2: NonZeroU8 = match NonZeroU8::new(2) {
876        Some(f) => f,
877        None => ::core::unreachable!(),
878    };
879
880    fn add_fabric(fabrics: &mut Fabrics) {
881        // Add fabric with ID 1
882        fabrics.add_with_post_init(|_| Ok(())).unwrap();
883    }
884
885    fn add_acl(fabrics: &mut Fabrics, fab_idx: NonZeroU8, entry: AclEntry) -> Result<usize, Error> {
886        fabrics.fabric_mut(fab_idx)?.acl_add(entry)
887    }
888
889    fn remove_all_acl(fabrics: &mut Fabrics, fab_idx: NonZeroU8) {
890        fabrics.fabric_mut(fab_idx).unwrap().acl_remove_all()
891    }
892
893    #[test]
894    fn test_basic_empty_subject_target() {
895        let mut fabrics = Fabrics::new();
896        let accessor = SubjectDescriptor::new(
897            0,
898            false,
899            AccessorSubjects::new(112233),
900            Some(AuthMode::Pase),
901        );
902        let path = GenericPath::new(Some(1), Some(1234), None);
903        let mut req_pase = AccessReq::new(&accessor, path, Access::READ, &[]);
904        req_pase.set_target_perms(Access::RWVA);
905
906        // Always allow for PASE sessions
907        assert!(req_pase.allow(&fabrics));
908
909        let accessor = SubjectDescriptor::new(
910            2,
911            false,
912            AccessorSubjects::new(112233),
913            Some(AuthMode::Case),
914        );
915        let path = GenericPath::new(Some(1), Some(1234), None);
916        let mut req = AccessReq::new(&accessor, path, Access::READ, &[]);
917        req.set_target_perms(Access::RWVA);
918
919        // Default deny for CASE
920        assert_eq!(req.allow(&fabrics), false);
921
922        // Add fabric with ID 1
923        add_fabric(&mut fabrics);
924
925        // Deny adding invalid auth mode (PASE is reserved for future)
926        let new = AclEntry::new(None, Privilege::VIEW, AuthMode::Pase);
927        assert!(add_acl(&mut fabrics, FAB_1, new).is_err());
928
929        // Deny for fab idx mismatch
930        let new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
931        assert_eq!(add_acl(&mut fabrics, FAB_1, new).unwrap(), 0);
932        assert_eq!(req.allow(&fabrics), false);
933
934        // Always allow for PASE sessions
935        assert!(req_pase.allow(&fabrics));
936
937        // Add fabric with ID 2
938        add_fabric(&mut fabrics);
939
940        // Allow
941        let new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
942        assert_eq!(add_acl(&mut fabrics, FAB_2, new).unwrap(), 0);
943        assert_eq!(req.allow(&fabrics), true);
944    }
945
946    #[test]
947    fn test_subject() {
948        let mut fabrics = Fabrics::new();
949
950        // Add fabric with ID 1
951        add_fabric(&mut fabrics);
952
953        let accessor = SubjectDescriptor::new(
954            1,
955            false,
956            AccessorSubjects::new(112233),
957            Some(AuthMode::Case),
958        );
959        let path = GenericPath::new(Some(1), Some(1234), None);
960        let mut req = AccessReq::new(&accessor, path, Access::READ, &[]);
961        req.set_target_perms(Access::RWVA);
962
963        // Deny for subject mismatch
964        let mut new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
965        new.add_subject(112232).unwrap();
966        assert_eq!(add_acl(&mut fabrics, FAB_1, new).unwrap(), 0);
967        assert_eq!(req.allow(&fabrics), false);
968
969        // Allow for subject match - target is wildcard
970        let mut new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
971        new.add_subject(112233).unwrap();
972        assert_eq!(add_acl(&mut fabrics, FAB_1, new).unwrap(), 1);
973        assert_eq!(req.allow(&fabrics), true);
974    }
975
976    #[test]
977    fn test_cat() {
978        let mut fabrics = Fabrics::new();
979
980        // Add fabric with ID 1
981        add_fabric(&mut fabrics);
982
983        let allow_cat = 0xABCD;
984        let disallow_cat = 0xCAFE;
985        let v2 = 2;
986        let v3 = 3;
987        // Accessor has nodeif and CAT 0xABCD_0002
988        let mut subjects = AccessorSubjects::new(112233);
989        subjects.add_catid(gen_noc_cat(allow_cat, v2)).unwrap();
990
991        let accessor = SubjectDescriptor::new(1, false, subjects, Some(AuthMode::Case));
992        let path = GenericPath::new(Some(1), Some(1234), None);
993        let mut req = AccessReq::new(&accessor, path, Access::READ, &[]);
994        req.set_target_perms(Access::RWVA);
995
996        // Deny for CAT id mismatch
997        let mut new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
998        new.add_subject_catid(gen_noc_cat(disallow_cat, v2))
999            .unwrap();
1000        add_acl(&mut fabrics, FAB_1, new).unwrap();
1001        assert_eq!(req.allow(&fabrics), false);
1002
1003        // Deny of CAT version mismatch
1004        let mut new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
1005        new.add_subject_catid(gen_noc_cat(allow_cat, v3)).unwrap();
1006        add_acl(&mut fabrics, FAB_1, new).unwrap();
1007        assert_eq!(req.allow(&fabrics), false);
1008
1009        // Allow for CAT match
1010        let mut new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
1011        new.add_subject_catid(gen_noc_cat(allow_cat, v2)).unwrap();
1012        add_acl(&mut fabrics, FAB_1, new).unwrap();
1013        assert_eq!(req.allow(&fabrics), true);
1014    }
1015
1016    #[test]
1017    fn test_cat_version() {
1018        let mut fabrics = Fabrics::new();
1019
1020        // Add fabric with ID 1
1021        add_fabric(&mut fabrics);
1022
1023        let allow_cat = 0xABCD;
1024        let disallow_cat = 0xCAFE;
1025        let v2 = 2;
1026        let v3 = 3;
1027        // Accessor has nodeif and CAT 0xABCD_0003
1028        let mut subjects = AccessorSubjects::new(112233);
1029        subjects.add_catid(gen_noc_cat(allow_cat, v3)).unwrap();
1030
1031        let accessor = SubjectDescriptor::new(1, false, subjects, Some(AuthMode::Case));
1032        let path = GenericPath::new(Some(1), Some(1234), None);
1033        let mut req = AccessReq::new(&accessor, path, Access::READ, &[]);
1034        req.set_target_perms(Access::RWVA);
1035
1036        // Deny for CAT id mismatch
1037        let mut new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
1038        new.add_subject_catid(gen_noc_cat(disallow_cat, v2))
1039            .unwrap();
1040        add_acl(&mut fabrics, FAB_1, new).unwrap();
1041        assert_eq!(req.allow(&fabrics), false);
1042
1043        // Allow for CAT match and version more than ACL version
1044        let mut new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
1045        new.add_subject_catid(gen_noc_cat(allow_cat, v2)).unwrap();
1046        add_acl(&mut fabrics, FAB_1, new).unwrap();
1047        assert_eq!(req.allow(&fabrics), true);
1048    }
1049
1050    #[test]
1051    fn test_target() {
1052        let mut fabrics = Fabrics::new();
1053
1054        // Add fabric with ID 1
1055        add_fabric(&mut fabrics);
1056
1057        let accessor = SubjectDescriptor::new(
1058            1,
1059            false,
1060            AccessorSubjects::new(112233),
1061            Some(AuthMode::Case),
1062        );
1063        let path = GenericPath::new(Some(1), Some(1234), None);
1064        let mut req = AccessReq::new(&accessor, path, Access::READ, &[]);
1065        req.set_target_perms(Access::RWVA);
1066
1067        // Deny for target mismatch
1068        let mut new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
1069        new.add_target(Target {
1070            cluster: Some(2),
1071            endpoint: Some(4567),
1072            device_type: None,
1073        })
1074        .unwrap();
1075        add_acl(&mut fabrics, FAB_1, new).unwrap();
1076        assert_eq!(req.allow(&fabrics), false);
1077
1078        // Allow for cluster match - subject wildcard
1079        let mut new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
1080        new.add_target(Target {
1081            cluster: Some(1234),
1082            endpoint: None,
1083            device_type: None,
1084        })
1085        .unwrap();
1086        add_acl(&mut fabrics, FAB_1, new).unwrap();
1087        assert_eq!(req.allow(&fabrics), true);
1088
1089        // Clean state
1090        remove_all_acl(&mut fabrics, FAB_1);
1091
1092        // Allow for endpoint match - subject wildcard
1093        let mut new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
1094        new.add_target(Target {
1095            cluster: None,
1096            endpoint: Some(1),
1097            device_type: None,
1098        })
1099        .unwrap();
1100        add_acl(&mut fabrics, FAB_1, new).unwrap();
1101        assert_eq!(req.allow(&fabrics), true);
1102
1103        // Clean state
1104        remove_all_acl(&mut fabrics, FAB_1);
1105
1106        // Allow for exact match
1107        let mut new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
1108        new.add_target(Target {
1109            cluster: Some(1234),
1110            endpoint: Some(1),
1111            device_type: None,
1112        })
1113        .unwrap();
1114        new.add_subject(112233).unwrap();
1115        add_acl(&mut fabrics, FAB_1, new).unwrap();
1116        assert_eq!(req.allow(&fabrics), true);
1117    }
1118
1119    #[test]
1120    fn test_privilege() {
1121        let mut fabrics = Fabrics::new();
1122
1123        // Add fabric with ID 1
1124        add_fabric(&mut fabrics);
1125
1126        let accessor = SubjectDescriptor::new(
1127            1,
1128            false,
1129            AccessorSubjects::new(112233),
1130            Some(AuthMode::Case),
1131        );
1132        let path = GenericPath::new(Some(1), Some(1234), None);
1133
1134        // Create an Exact Match ACL with View privilege
1135        let mut new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
1136        new.add_target(Target {
1137            cluster: Some(1234),
1138            endpoint: Some(1),
1139            device_type: None,
1140        })
1141        .unwrap();
1142        new.add_subject(112233).unwrap();
1143        add_acl(&mut fabrics, FAB_1, new).unwrap();
1144
1145        // Write on an RWVA without admin access - deny
1146        let mut req = AccessReq::new(&accessor, path.clone(), Access::WRITE, &[]);
1147        req.set_target_perms(Access::RWVA);
1148        assert_eq!(req.allow(&fabrics), false);
1149
1150        // Create an Exact Match ACL with Admin privilege
1151        let mut new = AclEntry::new(None, Privilege::ADMIN, AuthMode::Case);
1152        new.add_target(Target {
1153            cluster: Some(1234),
1154            endpoint: Some(1),
1155            device_type: None,
1156        })
1157        .unwrap();
1158        new.add_subject(112233).unwrap();
1159        add_acl(&mut fabrics, FAB_1, new).unwrap();
1160
1161        // Write on an RWVA with admin access - allow
1162        let mut req = AccessReq::new(&accessor, path, Access::WRITE, &[]);
1163        req.set_target_perms(Access::RWVA);
1164        assert_eq!(req.allow(&fabrics), true);
1165    }
1166
1167    #[test]
1168    fn test_delete_for_fabric() {
1169        let mut fabrics = Fabrics::new();
1170
1171        // Add fabric with ID 1
1172        add_fabric(&mut fabrics);
1173
1174        // Add fabric with ID 2
1175        add_fabric(&mut fabrics);
1176
1177        let path = GenericPath::new(Some(1), Some(1234), None);
1178        let accessor2 = SubjectDescriptor::new(
1179            1,
1180            false,
1181            AccessorSubjects::new(112233),
1182            Some(AuthMode::Case),
1183        );
1184        let mut req1 = AccessReq::new(&accessor2, path.clone(), Access::READ, &[]);
1185        req1.set_target_perms(Access::RWVA);
1186        let accessor3 = SubjectDescriptor::new(
1187            2,
1188            false,
1189            AccessorSubjects::new(112233),
1190            Some(AuthMode::Case),
1191        );
1192        let mut req2 = AccessReq::new(&accessor3, path, Access::READ, &[]);
1193        req2.set_target_perms(Access::RWVA);
1194
1195        // Allow for subject match - target is wildcard - Fabric idx 2
1196        let mut new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
1197        new.add_subject(112233).unwrap();
1198        assert_eq!(add_acl(&mut fabrics, FAB_1, new).unwrap(), 0);
1199
1200        // Allow for subject match - target is wildcard - Fabric idx 3
1201        let mut new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
1202        new.add_subject(112233).unwrap();
1203        assert_eq!(add_acl(&mut fabrics, FAB_2, new).unwrap(), 0);
1204
1205        // Req for Fabric idx 1 gets denied, and that for Fabric idx 2 is allowed
1206        assert_eq!(req1.allow(&fabrics), true);
1207        assert_eq!(req2.allow(&fabrics), true);
1208        remove_all_acl(&mut fabrics, FAB_1);
1209        assert_eq!(req1.allow(&fabrics), false);
1210        assert_eq!(req2.allow(&fabrics), true);
1211    }
1212
1213    /// With the `AUXILIARY` feature advertised, a wildcard-target Group-auth
1214    /// entry no longer covers the root endpoint (but explicit targets and
1215    /// other endpoints are unaffected).
1216    #[test]
1217    fn test_aux_wildcard_group_excludes_root_endpoint() {
1218        let mut fabrics = Fabrics::new();
1219        add_fabric(&mut fabrics);
1220
1221        const GROUP_ID: u64 = 0x12AB;
1222
1223        // A regular (writable) ACL entry: Group auth, wildcard targets
1224        let mut entry = AclEntry::new(None, Privilege::OPERATE, AuthMode::Group);
1225        entry.add_subject(GROUP_ID).unwrap();
1226        add_acl(&mut fabrics, FAB_1, entry).unwrap();
1227
1228        let accessor = SubjectDescriptor::new(
1229            FAB_1.get(),
1230            false,
1231            AccessorSubjects::new(GROUP_ID),
1232            Some(AuthMode::Group),
1233        );
1234
1235        let ep0 = GenericPath::new(Some(0), Some(1234), None);
1236        let ep1 = GenericPath::new(Some(1), Some(1234), None);
1237
1238        // Without the feature: the wildcard covers the whole node
1239        for path in [ep0.clone(), ep1.clone()] {
1240            let mut req = AccessReq::new(&accessor, path, Access::WRITE, &[]);
1241            req.set_target_perms(Access::WO);
1242            assert!(req.allow(&fabrics));
1243        }
1244
1245        let accessor = SubjectDescriptor::new(
1246            FAB_1.get(),
1247            true,
1248            AccessorSubjects::new(GROUP_ID),
1249            Some(AuthMode::Group),
1250        );
1251
1252        // With the feature: the root endpoint is excluded...
1253        let mut req = AccessReq::new(&accessor, ep0.clone(), Access::WRITE, &[]);
1254        req.set_target_perms(Access::WO);
1255        assert!(!req.allow(&fabrics));
1256
1257        // ...other endpoints are unaffected...
1258        let mut req = AccessReq::new(&accessor, ep1, Access::WRITE, &[]);
1259        req.set_target_perms(Access::WO);
1260        assert!(req.allow(&fabrics));
1261
1262        // ...and an entry explicitly targeting the root endpoint still works.
1263        remove_all_acl(&mut fabrics, FAB_1);
1264        let mut entry = AclEntry::new(None, Privilege::OPERATE, AuthMode::Group);
1265        entry.add_subject(GROUP_ID).unwrap();
1266        entry.add_target(Target::new(Some(0), None, None)).unwrap();
1267        add_acl(&mut fabrics, FAB_1, entry).unwrap();
1268
1269        let mut req = AccessReq::new(&accessor, ep0, Access::WRITE, &[]);
1270        req.set_target_perms(Access::WO);
1271        assert!(req.allow(&fabrics));
1272    }
1273}