Skip to main content

matter_kit/
acl.rs

1//! Who may do what to which element: the Access Control List (Core §6.6).
2//!
3//! Every interaction a commissioned node serves is checked here first. §6.6.6 gives the
4//! decision as a "Conceptual Access Control Privilege Granting algorithm" and is unusually
5//! strict about it — "Implementations of this algorithm SHALL have an identical outcome to
6//! the output of this conceptual algorithm" — so [`Acl::granted`] follows its pseudocode
7//! clause by clause rather than paraphrasing it.
8//!
9//! # What an entry is
10//!
11//! An [`Entry`] grants one [`Privilege`] to a set of *subjects*, over a set of *targets*,
12//! for one authentication mode, on one fabric. Every one of those is a filter, and an empty
13//! subject or target list is a **wildcard** rather than an empty set — the single most
14//! dangerous place to get a sign backwards, because reading it as "matches nothing" turns
15//! the broadest possible grant into a no-op and reading it the other way is worse.
16//!
17//! # Why there is no entry for the commissioner
18//!
19//! A factory-fresh node has an empty ACL, and a commissioner arriving over PASE has no entry
20//! to match. §6.6.6.2 resolves that in the algorithm rather than in the table:
21//!
22//! > PASE commissioning channel implicitly grants administer privilege to commissioner
23//!
24//! so the grant exists only while the PASE session does, and cannot be written, read back,
25//! or left behind. §6.6.2.1 is explicit that the table must not be able to express it:
26//! "ACL entries with a PASE authentication mode SHALL NOT be explicitly added to the Access
27//! Control List", which [`Acl::add`] enforces.
28//!
29//! # Fabric isolation
30//!
31//! An entry belongs to a fabric and is invisible to every other one. That is what stops a
32//! second administrator on the same node from granting itself access to the first's
33//! endpoints, and it is why [`Acl::granted`] rejects a fabric mismatch before it looks at
34//! anything else.
35
36use core::marker::PhantomData;
37
38use heapless::Vec;
39
40use crate::config::{AssertValid, Config};
41use crate::dm::{Node, Privilege};
42use crate::error::{Error, ErrorCode, Result, bail};
43use crate::im::{ClusterId, EndpointId};
44use crate::msg::{CaseAuthenticatedTag, FabricIndex, NodeId};
45
46/// How the subject of an action authenticated itself (§9.10.5.4).
47///
48/// An entry matches only an action authenticated the same way. The modes are not
49/// interchangeable and one never subsumes another: a group key proves possession of a shared
50/// secret, a CASE session proves a certificate chain back to the fabric root, and confusing
51/// the two would let a group message act with a node's identity.
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
53pub enum AuthMode {
54    /// `1` — a passcode-authenticated session, during commissioning only.
55    Pase = 1,
56    /// `2` — a CASE session, authenticated by an operational certificate.
57    Case = 2,
58    /// `3` — a group message, authenticated by an operational group key.
59    Group = 3,
60}
61
62impl AuthMode {
63    /// Reads the enum value off the wire.
64    #[must_use]
65    pub const fn from_value(value: u8) -> Option<Self> {
66        match value {
67            1 => Some(Self::Pase),
68            2 => Some(Self::Case),
69            3 => Some(Self::Group),
70            _ => None,
71        }
72    }
73}
74
75/// What an entry applies to (§9.10.5.6's `AccessControlTargetStruct`).
76///
77/// Every field is nullable and a null one is a wildcard. §6.6.6.2 states two preconditions
78/// the algorithm relies on, both checked by [`Target::is_valid`]: a target may not be empty,
79/// and it may not name both an endpoint and a device type — they are two ways of saying
80/// *where*, and an entry that used both would be asking a question with no defined answer.
81#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
82pub struct Target {
83    /// `Cluster [0]` — which cluster, or every cluster.
84    pub cluster: Option<ClusterId>,
85    /// `Endpoint [1]` — which endpoint, or every endpoint.
86    pub endpoint: Option<EndpointId>,
87    /// `DeviceType [2]` — every endpoint conforming to this device type (§9.5.6.1).
88    pub device_type: Option<u32>,
89}
90
91impl Target {
92    /// A target naming one cluster, anywhere on the node.
93    #[must_use]
94    pub const fn cluster(cluster: ClusterId) -> Self {
95        Self {
96            cluster: Some(cluster),
97            endpoint: None,
98            device_type: None,
99        }
100    }
101
102    /// A target naming one endpoint, every cluster on it.
103    #[must_use]
104    pub const fn endpoint(endpoint: EndpointId) -> Self {
105        Self {
106            cluster: None,
107            endpoint: Some(endpoint),
108            device_type: None,
109        }
110    }
111
112    /// A target naming every endpoint that conforms to a device type.
113    #[must_use]
114    pub const fn device_type(device_type: u32) -> Self {
115        Self {
116            cluster: None,
117            endpoint: None,
118            device_type: Some(device_type),
119        }
120    }
121
122    /// The same target, narrowed to one cluster.
123    #[must_use]
124    pub const fn and_cluster(mut self, cluster: ClusterId) -> Self {
125        self.cluster = Some(cluster);
126        self
127    }
128
129    /// §6.6.6.2's two preconditions on a target.
130    ///
131    /// "Precondition: target cannot be empty" and "Precondition: target cannot specify both
132    /// endpoint and device type". The algorithm asserts these rather than handling them, so
133    /// they are refused at the door instead.
134    #[must_use]
135    pub const fn is_valid(&self) -> bool {
136        let named = self.cluster.is_some() || self.endpoint.is_some() || self.device_type.is_some();
137        let both_places = self.endpoint.is_some() && self.device_type.is_some();
138        if !named || both_places {
139            return false;
140        }
141        // Each field that *is* present has to name something that could exist. §7.21.2's MEI
142        // tables bound a cluster id and a device type id, and §7.19.2.27 bounds an endpoint
143        // number: "Endpoint numbers SHALL NOT be 0xFFFF". An out-of-range identifier here is
144        // not a target the node happens not to have — it is a target no node could have, which
145        // is §8.10.1's `CONSTRAINT_ERROR` and not `UNSUPPORTED_CLUSTER`.
146        //
147        // Unchecked, `0xFFFF_FFFF` is stored, read back and matched against nothing forever:
148        // an administrator's mistake that takes effect as an entry which grants access to no
149        // cluster on no endpoint, and says so nowhere.
150        if let Some(cluster) = self.cluster
151            && !crate::dm::mei::cluster_is_valid(cluster)
152        {
153            return false;
154        }
155        if let Some(device_type) = self.device_type
156            && !crate::dm::mei::device_type_is_valid(device_type)
157        {
158            return false;
159        }
160        if let Some(endpoint) = self.endpoint
161            && endpoint == 0xFFFF
162        {
163            return false;
164        }
165        true
166    }
167
168    /// Whether this target covers an element on `endpoint` in `cluster`.
169    fn matches(&self, node: &Node<'_>, endpoint: EndpointId, cluster: ClusterId) -> bool {
170        if self.cluster.is_some_and(|wanted| wanted != cluster) {
171            return false;
172        }
173        if self.endpoint.is_some_and(|wanted| wanted != endpoint) {
174            return false;
175        }
176        if let Some(wanted) = self.device_type {
177            // "Endpoint may be specified indirectly via device type" — so this asks the node
178            // what the endpoint *is*, which is why device types live on the endpoint rather
179            // than only on its Descriptor cluster.
180            let Some(endpoint) = node.endpoint(endpoint) else {
181                return false;
182            };
183            if !endpoint.has_device_type(wanted) {
184                return false;
185            }
186        }
187        true
188    }
189}
190
191/// One access control entry (§9.10.5.7's `AccessControlEntryStruct`).
192///
193/// `S` and `T` bound the subject and target lists, and are exactly what §9.10.6.5's
194/// `SubjectsPerAccessControlEntry` and §9.10.6.6's `TargetsPerAccessControlEntry` report —
195/// constrained to `4..=65534` and `3..=65534`, which [`Acl::CHECK`] holds them to. They default
196/// to those minima.
197#[derive(Debug, Clone, PartialEq, Eq)]
198pub struct Entry<const S: usize, const T: usize> {
199    /// The fabric this entry belongs to, and the only one that can see it.
200    pub fabric_index: FabricIndex,
201    /// `Privilege [1]` — what this entry grants.
202    pub privilege: Privilege,
203    /// `AuthMode [2]` — the authentication mode it applies to.
204    pub auth_mode: AuthMode,
205    /// `Subjects [3]` — who. **Empty is a wildcard**, not an empty set.
206    pub subjects: Vec<NodeId, S>,
207    /// `Targets [4]` — what. **Empty is a wildcard**, not an empty set.
208    pub targets: Vec<Target, T>,
209}
210
211impl<const S: usize, const T: usize> Entry<S, T> {
212    /// An entry granting `privilege` to CASE subjects on `fabric`, wildcard in both lists.
213    #[must_use]
214    pub fn case(fabric_index: FabricIndex, privilege: Privilege) -> Self {
215        Self {
216            fabric_index,
217            privilege,
218            auth_mode: AuthMode::Case,
219            subjects: Vec::new(),
220            targets: Vec::new(),
221        }
222    }
223
224    /// Adds a subject, which narrows the entry from its wildcard.
225    ///
226    /// A CAT is carried as its §6.6.2.1.2 node-id sub-encoding; [`CaseAuthenticatedTag`]
227    /// produces it.
228    pub fn with_subject(mut self, subject: NodeId) -> Result<Self> {
229        self.subjects
230            .push(subject)
231            .map_err(|_| Error::new(ErrorCode::NoSpace))?;
232        Ok(self)
233    }
234
235    /// Adds a target, which narrows the entry from its wildcard.
236    pub fn with_target(mut self, target: Target) -> Result<Self> {
237        if !target.is_valid() {
238            bail!(InvalidArgument)
239        }
240        self.targets
241            .push(target)
242            .map_err(|_| Error::new(ErrorCode::NoSpace))?;
243        Ok(self)
244    }
245
246    /// Whether this entry is one §6.6 permits to exist.
247    fn is_well_formed(&self) -> bool {
248        // §6.6.2.1: "ACL entries with a PASE authentication mode SHALL NOT be explicitly
249        // added to the Access Control List" — the commissioner's grant is implicit and
250        // temporary, and an explicit one would outlive the session that justified it.
251        if matches!(self.auth_mode, AuthMode::Pase) {
252            return false;
253        }
254        // §6.6.2.11: "it SHALL NOT be valid to have an Administer privilege set on an Access
255        // Control Entry, unless AuthMode is 'CASE'." Stated as the specification states it —
256        // a positive requirement on CASE rather than a prohibition on Group — because that is
257        // the rule that survives if the set of authentication modes ever grows. A group key is
258        // a shared secret with "no source Node authentication and reduced attribution
259        // ability", so administering with one would make every holder an administrator and
260        // leave no record of which one acted.
261        if matches!(self.privilege, Privilege::Administer)
262            && !matches!(self.auth_mode, AuthMode::Case)
263        {
264            return false;
265        }
266        // §6.6.6.2: "only CASE and Group auth can have empty subjects".
267        if self.subjects.is_empty() && !matches!(self.auth_mode, AuthMode::Case | AuthMode::Group) {
268            return false;
269        }
270        // A fabric index of 0 names no fabric; §6.6.6.2 skips such entries outright, so one
271        // could never grant anything.
272        if self.fabric_index.0 == 0 {
273            return false;
274        }
275        // §9.10.5.7's Subject Semantics table gives each authentication mode its own shape for
276        // a Subject ID, and a value outside it is not a subject that can ever match. Left
277        // unchecked, an entry naming `0` — the Unspecified Node ID, "a reserved value that
278        // never appears in messages or protocol usage" (§2.5.5.6) — is stored, read back, and
279        // grants nothing to anybody, which is indistinguishable from an administrator's
280        // typo taking effect.
281        if !self.subjects.iter().all(|s| self.subject_is_valid(*s)) {
282            return false;
283        }
284        self.targets.iter().all(Target::is_valid)
285    }
286
287    /// Whether `subject` is a Subject ID this entry's authentication mode can carry
288    /// (§9.10.5.7).
289    fn subject_is_valid(&self, subject: NodeId) -> bool {
290        match self.auth_mode {
291            // "CASE — 64-bits → Node ID or CASE Authenticated Tag". A CAT's version is part of
292            // the check: §6.6.2.1.2 says "A version number of 0 is invalid and SHALL NOT be
293            // used", so `0xFFFF_FFFD_xxxx_0000` is in the range and is still not a CAT.
294            AuthMode::Case => match subject.kind() {
295                crate::msg::NodeIdKind::Operational => true,
296                crate::msg::NodeIdKind::CaseAuthenticatedTag => {
297                    CaseAuthenticatedTag::from_node_id(subject).is_some_and(|cat| cat.is_valid())
298                }
299                _ => false,
300            },
301            // "Group — Lower 16-bits → Group ID, Upper 48-bits → all bits clear." Group 0 is
302            // excluded because §11.2.4 reserves it: "The Group ID 0 is reserved for the
303            // All-Nodes group", which no access control entry names.
304            AuthMode::Group => subject.0 != 0 && subject.0 <= u64::from(u16::MAX),
305            // Unreachable: a PASE entry is refused above, before this is asked.
306            AuthMode::Pase => false,
307        }
308    }
309}
310
311/// The set of privileges an action was granted (§6.6.6.2).
312///
313/// A set rather than a single highest privilege, because §9.10.5.2's `ProxyView` is *not*
314/// part of the subsumption chain: `add_granted_privilege` expands Operate, Manage and
315/// Administer downward to View, but nothing grants `ProxyView` except `ProxyView` itself.
316/// Collapsing the set to its maximum would quietly hand every `View` holder a privilege the
317/// specification never gives them.
318#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
319pub struct Granted(u8);
320
321impl Granted {
322    /// Nothing granted.
323    pub const NONE: Self = Self(0);
324
325    const fn bit(privilege: Privilege) -> u8 {
326        1u8 << (privilege as u8)
327    }
328
329    /// §6.6.6.2's `add_granted_privilege`, including everything the privilege subsumes.
330    fn add(&mut self, privilege: Privilege) {
331        self.0 |= Self::bit(privilege);
332        match privilege {
333            Privilege::Operate => self.0 |= Self::bit(Privilege::View),
334            Privilege::Manage => {
335                self.0 |= Self::bit(Privilege::Operate) | Self::bit(Privilege::View);
336            }
337            Privilege::Administer => {
338                self.0 |= Self::bit(Privilege::Manage)
339                    | Self::bit(Privilege::Operate)
340                    | Self::bit(Privilege::View);
341            }
342            Privilege::ProxyView | Privilege::View => {}
343        }
344    }
345
346    /// Whether the set contains `privilege`.
347    #[must_use]
348    pub const fn has(self, privilege: Privilege) -> bool {
349        self.0 & Self::bit(privilege) != 0
350    }
351
352    /// Whether nothing at all was granted.
353    #[must_use]
354    pub const fn is_empty(self) -> bool {
355        self.0 == 0
356    }
357
358    /// The strongest privilege in the set, in §6.6.1's order.
359    ///
360    /// A set is what §6.6.6.2 actually produces, and it is the honest shape — ProxyView sits
361    /// outside the chain, so "the maximum" is not always a single answer. This reduces it to
362    /// one for the callers that need a single value to hand a cluster, and ProxyView is not
363    /// among the answers: it grants nothing the other four do and is never what a cluster
364    /// means by "the privilege this subject holds".
365    #[must_use]
366    pub const fn highest(self) -> Option<Privilege> {
367        if self.has(Privilege::Administer) {
368            Some(Privilege::Administer)
369        } else if self.has(Privilege::Manage) {
370            Some(Privilege::Manage)
371        } else if self.has(Privilege::Operate) {
372            Some(Privilege::Operate)
373        } else if self.has(Privilege::View) {
374            Some(Privilege::View)
375        } else {
376            None
377        }
378    }
379}
380
381/// What an incoming message authenticated as — §6.6.6.1.3's Incoming Subject Descriptor.
382///
383/// Derived once per message from the session it arrived on (§6.6.6.3), never from the
384/// message's own claims: a source node id in a header is whatever the sender wrote, while the
385/// id in a session context is what CASE proved.
386#[derive(Debug, Clone, PartialEq, Eq)]
387pub struct SubjectDescriptor {
388    /// Whether commissioning is under way on this session.
389    ///
390    /// The one thing that turns a PASE session into an administrator, and only for as long as
391    /// it is true.
392    pub is_commissioning: bool,
393    /// How the action authenticated, or `None` for §6.6.6.3's `AuthModeEnum::None`.
394    ///
395    /// `None` is the "do nothing on error" outcome: a message whose session could not be
396    /// identified gets a descriptor that matches no entry, so it is granted nothing rather
397    /// than being treated as some default. Modelling it as `Option` rather than as a fourth
398    /// [`AuthMode`] keeps it out of [`Entry`] entirely — an entry that authenticated nobody
399    /// is not a thing the table can hold.
400    pub auth_mode: Option<AuthMode>,
401    /// The subjects it presents: a CASE node's operational id plus any CATs its certificate
402    /// carried, a group id for a group message, or the passcode id for PASE.
403    ///
404    /// Four, because §6.5.6 allows a NOC to carry at most three CATs alongside its node id.
405    pub subjects: Vec<NodeId, 4>,
406    /// Which fabric, or 0 for a PASE session that has none yet.
407    pub fabric_index: FabricIndex,
408}
409
410/// "`DEFAULT_COMMISSIONING_PASSCODE = 0`" (§6.6.6.3).
411///
412/// The subject a PASE session presents. §6.6.2.1: "any Passcode ID other than 0 … is reserved
413/// for future use".
414pub const DEFAULT_COMMISSIONING_PASSCODE: u64 = 0;
415
416impl SubjectDescriptor {
417    /// §6.6.6.3's starting value: authenticated as nobody, granted nothing.
418    ///
419    /// The result for a message whose session cannot be identified — "Do nothing on error,
420    /// ISD remains unchanged".
421    #[must_use]
422    pub fn unauthenticated() -> Self {
423        Self {
424            is_commissioning: false,
425            auth_mode: None,
426            subjects: Vec::new(),
427            fabric_index: FabricIndex(0),
428        }
429    }
430
431    /// The descriptor for a PASE session (§6.6.6.3).
432    ///
433    /// `IsCommissioning` is true for *any* PASE session: the specification sets it in the PASE
434    /// branch unconditionally, because a passcode-authenticated session exists only to
435    /// commission. The fabric "may be zero" — it is, until `AddNOC`.
436    #[must_use]
437    pub fn pase(fabric_index: FabricIndex) -> Self {
438        let mut subjects = Vec::new();
439        let _ = subjects.push(NodeId(DEFAULT_COMMISSIONING_PASSCODE));
440        Self {
441            is_commissioning: true,
442            auth_mode: Some(AuthMode::Pase),
443            subjects,
444            fabric_index,
445        }
446    }
447
448    /// The descriptor for a commissioner on the PASE channel before it has a fabric.
449    #[must_use]
450    pub fn commissioning() -> Self {
451        Self::pase(FabricIndex(0))
452    }
453
454    /// The descriptor for a CASE session with a node id and no CATs.
455    #[must_use]
456    pub fn case(fabric_index: FabricIndex, node_id: NodeId) -> Self {
457        let mut subjects = Vec::new();
458        let _ = subjects.push(node_id);
459        Self {
460            is_commissioning: false,
461            auth_mode: Some(AuthMode::Case),
462            subjects,
463            fabric_index,
464        }
465    }
466
467    /// The descriptor for a group message (§6.6.6.3).
468    ///
469    /// The caller must already have checked that the group and key are mapped — the spec sets
470    /// the auth mode only "if group_key_management_cluster.group_key_map_has_mapping(group_id,
471    /// group_key_id)", and a message that failed that check is
472    /// [`SubjectDescriptor::unauthenticated`].
473    #[must_use]
474    pub fn group(fabric_index: FabricIndex, group_id: crate::msg::GroupId) -> Self {
475        let mut subjects = Vec::new();
476        let _ = subjects.push(NodeId(u64::from(group_id.0)));
477        Self {
478            is_commissioning: false,
479            auth_mode: Some(AuthMode::Group),
480            subjects,
481            fabric_index,
482        }
483    }
484
485    /// Adds a CAT the peer's operational certificate carried (§6.6.2.1.2).
486    pub fn with_cat(mut self, cat: CaseAuthenticatedTag) -> Result<Self> {
487        self.subjects
488            .push(cat.to_node_id())
489            .map_err(|_| Error::new(ErrorCode::NoSpace))?;
490        Ok(self)
491    }
492
493    /// §6.6.6.3's derivation, for a unicast session.
494    ///
495    /// > Each incoming message has a unique `<AuthMode, SubjectDescriptor>` applicable to it,
496    /// > whose derivation is deterministic based on both incoming message fields and session
497    /// > metadata fields.
498    ///
499    /// Session metadata, never the message's own claims — a source node id in a header is
500    /// whatever the sender wrote, while the id in a session context is what CASE proved. That
501    /// is the whole reason this takes a [`SecureSession`](crate::session::SecureSession)
502    /// rather than a header.
503    ///
504    /// `pending_fabric` is the fabric index `AddNOC` has created but the fail-safe has not yet
505    /// committed, if any: §6.6.6.3 marks a CASE session on it as commissioning, which is how a
506    /// commissioner that has switched from PASE to CASE mid-flow keeps its standing.
507    ///
508    /// Group messages do not arrive on a unicast session and are built with
509    /// [`SubjectDescriptor::group`] instead, after the Group Key Management check the
510    /// specification requires.
511    #[cfg(feature = "rustcrypto")]
512    #[cfg_attr(docsrs, doc(cfg(feature = "rustcrypto")))]
513    #[must_use]
514    pub fn from_session(
515        session: &crate::session::SecureSession,
516        pending_fabric: Option<FabricIndex>,
517    ) -> Self {
518        match session.kind {
519            crate::session::SessionKind::Pase => Self::pase(session.fabric_index),
520            crate::session::SessionKind::Case => {
521                // "assert(isd.FabricIndex != 0) # cannot be zero" — a CASE session without a
522                // fabric is not a thing that can exist, and treating one as fabric 0 would
523                // silently match no entry rather than saying so.
524                if session.fabric_index.0 == 0 {
525                    return Self::unauthenticated();
526                }
527                let mut descriptor = Self::case(session.fabric_index, session.peer_node_id);
528                descriptor.is_commissioning =
529                    pending_fabric.is_some_and(|pending| pending == session.fabric_index);
530                for cat in &session.peer_cats {
531                    // The list is sized for a node id plus §6.5.6's three CATs, so this
532                    // cannot overflow for a well-formed certificate.
533                    let _ = descriptor.subjects.push(cat.to_node_id());
534                }
535                descriptor
536            }
537        }
538    }
539}
540
541/// §6.6.6.2's `subject_matches`.
542///
543/// "Subjects must match exactly, or both are CAT with matching CAT ID and acceptable CAT
544/// version." The version comparison is the interesting half and its direction is the whole
545/// point: the *entry* names the minimum version and the *subject* must be at least that, so
546/// an administrator revokes a tag by issuing a higher version and rewriting the entry. Read
547/// backwards, a revoked node keeps its access forever.
548fn subject_matches(acl_subject: NodeId, isd_subject: NodeId) -> bool {
549    if acl_subject == isd_subject {
550        return true;
551    }
552    match (
553        CaseAuthenticatedTag::from_node_id(acl_subject),
554        CaseAuthenticatedTag::from_node_id(isd_subject),
555    ) {
556        (Some(acl), Some(isd)) => {
557            acl.identifier() == isd.identifier() && isd.version() >= acl.version()
558        }
559        _ => false,
560    }
561}
562
563/// A node's Access Control List, and the decision it exists to make (§6.6).
564///
565/// `N` is how many entries the list holds across every fabric, and `S` and `T` how many
566/// subjects and targets one entry may name. All three default to the specification's minima for
567/// a five-fabric node; [`Acl::CHECK`] refuses anything smaller, against the `Config` the list is
568/// parameterised by, so a node cannot promise a share of a list it does not have.
569#[derive(Debug)]
570pub struct Acl<C: Config, const N: usize = 20, const S: usize = 4, const T: usize = 3> {
571    entries: Vec<Entry<S, T>, N>,
572    _config: PhantomData<C>,
573}
574
575impl<C: Config, const N: usize, const S: usize, const T: usize> crate::config::Capacity
576    for Acl<C, N, S, T>
577{
578    const TOTAL: usize = N;
579    /// §9.10.6.7's `AccessControlEntriesPerFabric`: the fixed share each fabric is promised.
580    const PER_FABRIC: usize = C::ACL_ENTRIES_PER_FABRIC;
581}
582
583impl<C: Config, const N: usize, const S: usize, const T: usize> Acl<C, N, S, T> {
584    /// Compile-time proof that this list can keep §2.11.1.1's promise, and that its entries are
585    /// wide enough for §9.10.6.5 and §9.10.6.6.
586    ///
587    /// > at least four Access Control Entries available for every fabric supported by the node
588    ///
589    /// `S` and `T` are the values `SubjectsPerAccessControlEntry` and
590    /// `TargetsPerAccessControlEntry` report, and their constraints are `4 to 65534` and
591    /// `3 to 65534` — so a narrower entry is a node whose own attribute is out of constraint.
592    pub const CHECK: () = {
593        let () = AssertValid::<C>::CHECK;
594        assert!(
595            N >= C::ACL_ENTRIES_PER_FABRIC * C::FABRICS,
596            "Acl: Core §2.11.1.1 promises ACL_ENTRIES_PER_FABRIC to every fabric, so the list \
597             must hold FABRICS × that many"
598        );
599        assert!(
600            S >= 4,
601            "Acl: §9.10.6.5 constrains SubjectsPerAccessControlEntry to 4..=65534"
602        );
603        assert!(
604            T >= 3,
605            "Acl: §9.10.6.6 constrains TargetsPerAccessControlEntry to 3..=65534"
606        );
607    };
608}
609
610impl<C: Config, const N: usize, const S: usize, const T: usize> Default for Acl<C, N, S, T> {
611    fn default() -> Self {
612        Self::new()
613    }
614}
615
616impl<C: Config, const N: usize, const S: usize, const T: usize> Acl<C, N, S, T> {
617    /// An empty list — what a factory-fresh node has (§9.10.6.1).
618    #[must_use]
619    pub fn new() -> Self {
620        let () = Self::CHECK;
621        Self {
622            entries: Vec::new(),
623            _config: PhantomData,
624        }
625    }
626
627    /// How many entries the list holds, across every fabric.
628    #[must_use]
629    pub fn len(&self) -> usize {
630        self.entries.len()
631    }
632
633    /// Whether the list is empty.
634    #[must_use]
635    pub fn is_empty(&self) -> bool {
636        self.entries.is_empty()
637    }
638
639    /// Every entry, in order.
640    pub fn entries(&self) -> impl Iterator<Item = &Entry<S, T>> {
641        self.entries.iter()
642    }
643
644    /// The entries belonging to one fabric — what a read of the `ACL` attribute reports.
645    ///
646    /// §9.10.6's `ACL` attribute is `F`, fabric-scoped, so a client sees its own fabric's
647    /// entries and no others.
648    pub fn of_fabric(&self, fabric: FabricIndex) -> impl Iterator<Item = &Entry<S, T>> {
649        self.entries
650            .iter()
651            .filter(move |entry| entry.fabric_index == fabric)
652    }
653
654    /// How many entries one fabric has, against [`Config::ACL_ENTRIES_PER_FABRIC`].
655    #[must_use]
656    pub fn len_of_fabric(&self, fabric: FabricIndex) -> usize {
657        self.of_fabric(fabric).count()
658    }
659
660    /// Adds an entry.
661    ///
662    /// Refuses one §6.6 does not permit to exist — a PASE entry, a Group entry at Administer,
663    /// an entry on no fabric, or a malformed target — with [`ErrorCode::InvalidArgument`],
664    /// and a fabric already at its quota with [`ErrorCode::NoSpace`].
665    pub fn add(&mut self, entry: Entry<S, T>) -> Result<()> {
666        if !entry.is_well_formed() {
667            bail!(InvalidArgument)
668        }
669        if self.len_of_fabric(entry.fabric_index) >= <Self as crate::config::Capacity>::PER_FABRIC {
670            bail!(NoSpace)
671        }
672        self.entries
673            .push(entry)
674            .map_err(|_| Error::new(ErrorCode::NoSpace))
675    }
676
677    /// Adds §11.18.6.8 step 7's administrator entry for a fabric just joined.
678    ///
679    /// `AddNOC` carries a `CaseAdminSubject`, and the specification fixes exactly what the
680    /// resulting entry must be:
681    ///
682    /// ```text
683    /// { FabricIndex: <new>, Privilege: Administer, AuthMode: CASE,
684    ///   Subjects: [CaseAdminSubject], Targets: [] }   // entire node
685    /// ```
686    ///
687    /// It exists as a named constructor because the consequence of getting it wrong is not a
688    /// visible failure. §11.18.6.8: "Unless such an Access Control Entry is added atomically
689    /// as described here, there would be no way for the caller on its given Fabric to
690    /// eventually add another Access Control Entry for CASE authentication mode" — the fabric
691    /// is joined, the node advertises itself, and the moment the PASE session closes nobody
692    /// can administer it again.
693    ///
694    /// `subject` must be an operational node id or a CAT; anything else is
695    /// [`ErrorCode::InvalidArgument`], which is the condition §11.18.6.8 answers with
696    /// `InvalidAdminSubject`.
697    pub fn add_admin_for_fabric(&mut self, fabric: FabricIndex, subject: NodeId) -> Result<()> {
698        // "not being in either the Operational or CASE Authenticated Tag range".
699        if !matches!(
700            subject.kind(),
701            crate::msg::NodeIdKind::Operational | crate::msg::NodeIdKind::CaseAuthenticatedTag
702        ) {
703            bail!(InvalidArgument)
704        }
705        let entry = Entry::<S, T>::case(fabric, Privilege::Administer).with_subject(subject)?;
706        self.add(entry)
707    }
708
709    /// Removes every entry of one fabric — §6.6.4's side-effect of `RemoveFabric`.
710    ///
711    /// A fabric's entries must not outlive it. Left behind, they would be matched by the next
712    /// fabric to be issued the same index, handing a new administrator the privileges of a
713    /// removed one.
714    pub fn remove_fabric(&mut self, fabric: FabricIndex) {
715        self.entries.retain(|entry| entry.fabric_index != fabric);
716    }
717
718    /// Replaces one fabric's entries, which is how §10.6.4.3.1's list write lands.
719    ///
720    /// A write of the whole `ACL` attribute replaces only the accessing fabric's entries;
721    /// every other fabric's are untouched, because they were never visible to the writer.
722    pub fn replace_fabric(
723        &mut self,
724        fabric: FabricIndex,
725        entries: impl IntoIterator<Item = Entry<S, T>>,
726    ) -> Result<()> {
727        self.entries.retain(|entry| entry.fabric_index != fabric);
728        for entry in entries {
729            self.add(entry)?;
730        }
731        Ok(())
732    }
733
734    /// §6.6.6.2's `get_granted_privileges`: every privilege this action holds here.
735    ///
736    /// Follows the pseudocode clause by clause. The order of the checks is not cosmetic — a
737    /// fabric mismatch is rejected before an auth mode, and both before any subject is
738    /// compared — because each one is what makes the next one's comparison meaningful.
739    #[must_use]
740    pub fn granted(
741        &self,
742        node: &Node<'_>,
743        subject: &SubjectDescriptor,
744        endpoint: EndpointId,
745        cluster: ClusterId,
746    ) -> Granted {
747        let mut granted = Granted::NONE;
748
749        // "PASE commissioning channel implicitly grants administer privilege to commissioner".
750        // It is deliberately not an entry: it exists only while this session does.
751        if subject.auth_mode == Some(AuthMode::Pase) && subject.is_commissioning {
752            granted.add(Privilege::Administer);
753        }
754
755        for entry in &self.entries {
756            // "End checking if highest privilege is granted".
757            if granted.has(Privilege::Administer) {
758                break;
759            }
760            // "FabricIndex must match, there are no valid entries with FabricIndex == 0".
761            if entry.fabric_index.0 == 0 || entry.fabric_index != subject.fabric_index {
762                continue;
763            }
764            if Some(entry.auth_mode) != subject.auth_mode {
765                continue;
766            }
767
768            // "Subject must match, or be wildcard" — and empty *is* the wildcard.
769            if !entry.subjects.is_empty() {
770                let matched = entry.subjects.iter().any(|acl_subject| {
771                    subject
772                        .subjects
773                        .iter()
774                        .any(|isd| subject_matches(*acl_subject, *isd))
775                });
776                if !matched {
777                    continue;
778                }
779            }
780
781            // "Target must match, or be wildcard".
782            if entry.targets.is_empty() {
783                // The Auxiliary feature's carve-out: a group may not reach endpoint 0, whose
784                // clusters administer the node itself.
785                if matches!(entry.auth_mode, AuthMode::Group) && C::ACL_AUXILIARY && endpoint == 0 {
786                    continue;
787                }
788            } else {
789                let matched = entry
790                    .targets
791                    .iter()
792                    .any(|target| target.matches(node, endpoint, cluster));
793                if !matched {
794                    continue;
795                }
796            }
797
798            // §6.6.6.2's remaining clause is `extensions_are_valid`, which validates the
799            // `Extension` attribute against the entry. That attribute belongs to the `EXTS`
800            // feature and is not served here, so there are no extensions to invalidate an
801            // entry and the clause is vacuously true — not skipped.
802            granted.add(entry.privilege);
803        }
804
805        // "Should never grant Administer privilege to a Group." An entry that could do so is
806        // refused by `add`, so this can only fire on a list built some other way — and it
807        // fires by withholding the privilege rather than by trusting the earlier check.
808        if subject.auth_mode == Some(AuthMode::Group) && granted.has(Privilege::Administer) {
809            return Granted::NONE;
810        }
811
812        granted
813    }
814
815    /// Whether an action holding `required` may proceed.
816    ///
817    /// The shape [`AccessControl`](crate::im::AccessControl) wants. `Restricted` is never
818    /// returned: §6.6.2.8's Access Restriction List belongs to the ManagedDevice feature,
819    /// which this build does not implement, and inventing a restriction would deny access the
820    /// specification grants.
821    #[must_use]
822    pub fn allows(
823        &self,
824        node: &Node<'_>,
825        subject: &SubjectDescriptor,
826        endpoint: EndpointId,
827        cluster: ClusterId,
828        required: Privilege,
829    ) -> crate::im::Outcome {
830        if self.granted(node, subject, endpoint, cluster).has(required) {
831            crate::im::Outcome::Granted
832        } else {
833            crate::im::Outcome::Denied
834        }
835    }
836}
837
838/// An [`Acl`] as the [`AccessControl`](crate::im::AccessControl) one interaction sees.
839///
840/// The trait asks "may this action have `required` on this path?" and takes no subject,
841/// because the subject is not a property of the path — it is a property of the *session the
842/// action arrived on*. So the subject is bound here, once, when the interaction is set up,
843/// and the trait's question becomes answerable:
844///
845/// ```no_run
846/// # use core::cell::RefCell;
847/// # use matter_kit::acl::{Acl, AclAccess, SubjectDescriptor};
848/// # use matter_kit::config::DefaultConfig;
849/// # use matter_kit::dm::Node;
850/// # use matter_kit::msg::{FabricIndex, NodeId};
851/// # fn go(node: Node<'_>, acl: &RefCell<Acl<DefaultConfig, 20, 4, 3>>) {
852/// // Derived from the session (§6.6.6.3), never from anything the message claimed.
853/// let subject = SubjectDescriptor::case(FabricIndex(1), NodeId(0x1234));
854/// let access = AclAccess::new(acl, node, &subject);
855/// // `access` is now what `Server::new` takes.
856/// # let _ = access;
857/// # }
858/// ```
859///
860/// A path that is not concrete is denied. Every call the server makes passes a concrete one —
861/// a wildcard is expanded before it is checked — so this is unreachable in practice, and it
862/// fails closed rather than guessing which endpoint a caller meant.
863#[derive(Debug)]
864pub struct AclAccess<'a, C: Config, const N: usize, const S: usize, const T: usize> {
865    acl: &'a core::cell::RefCell<Acl<C, N, S, T>>,
866    node: Node<'a>,
867    subject: &'a SubjectDescriptor,
868}
869
870impl<'a, C: Config, const N: usize, const S: usize, const T: usize> AclAccess<'a, C, N, S, T> {
871    /// Binds a list, a node and the subject of one interaction.
872    #[must_use]
873    pub const fn new(
874        acl: &'a core::cell::RefCell<Acl<C, N, S, T>>,
875        node: Node<'a>,
876        subject: &'a SubjectDescriptor,
877    ) -> Self {
878        Self { acl, node, subject }
879    }
880}
881
882impl<C: Config, const N: usize, const S: usize, const T: usize> crate::im::AccessControl
883    for AclAccess<'_, C, N, S, T>
884{
885    fn allows(&self, path: &crate::im::AttributePath, required: Privilege) -> crate::im::Outcome {
886        let (Some(endpoint), Some(cluster)) = (path.endpoint, path.cluster) else {
887            return crate::im::Outcome::Denied;
888        };
889        self.acl
890            .borrow()
891            .allows(&self.node, self.subject, endpoint, cluster, required)
892    }
893}
894
895#[cfg(test)]
896mod tests {
897    use super::*;
898    use crate::config::DefaultConfig;
899    use crate::dm::{
900        AttributeDescriptor, ClusterDescriptor, CommandDescriptor, DeviceType, Endpoint,
901    };
902
903    // The defaults are the specification's own minima for `DefaultConfig`, so naming none of
904    // them is what a conformant node looks like.
905    type TestAcl = Acl<DefaultConfig>;
906    type TestEntry = Entry<4, 3>;
907
908    const ATTRS: &[AttributeDescriptor] = &[AttributeDescriptor::read_only(0)];
909    const NO_CMDS: &[CommandDescriptor] = &[];
910
911    const fn cluster(id: ClusterId) -> ClusterDescriptor<'static> {
912        ClusterDescriptor {
913            id,
914            revision: 1,
915            feature_map: 0,
916            attributes: ATTRS,
917            accepted_commands: NO_CMDS,
918            generated_commands: &[],
919            events: &[],
920        }
921    }
922
923    const ON_OFF: ClusterId = 0x0006;
924    const LEVEL: ClusterId = 0x0008;
925    const ROOT: &[ClusterDescriptor<'static>] = &[cluster(0x001D)];
926    const APP: &[ClusterDescriptor<'static>] = &[cluster(ON_OFF), cluster(LEVEL)];
927    /// `0x0100` is the Device Library's On/Off Light.
928    const LIGHT: &[DeviceType] = &[DeviceType::new(0x0100, 1)];
929    const ENDPOINTS: &[Endpoint<'static>] = &[
930        Endpoint::new(0, ROOT),
931        Endpoint::new(1, APP).with_device_types(LIGHT),
932    ];
933
934    fn node() -> Node<'static> {
935        Node::new(ENDPOINTS)
936    }
937
938    const F1: FabricIndex = FabricIndex(1);
939    const F2: FabricIndex = FabricIndex(2);
940    const ALICE: NodeId = NodeId(0x0000_0000_0000_1111);
941    const BOB: NodeId = NodeId(0x0000_0000_0000_2222);
942
943    #[test]
944    fn an_empty_list_grants_nothing() {
945        let acl = TestAcl::new();
946        let subject = SubjectDescriptor::case(F1, ALICE);
947        assert!(acl.granted(&node(), &subject, 1, ON_OFF).is_empty());
948    }
949
950    #[test]
951    fn a_pase_commissioner_is_an_administrator_without_an_entry() {
952        // §6.6.6.2's first clause, and §9.10.6.1's reason the ACL can start empty at all.
953        let acl = TestAcl::new();
954        let granted = acl.granted(&node(), &SubjectDescriptor::commissioning(), 0, 0x001D);
955        assert!(granted.has(Privilege::Administer));
956        assert!(granted.has(Privilege::View), "and everything it subsumes");
957    }
958
959    #[test]
960    fn a_pase_session_that_is_not_commissioning_grants_nothing() {
961        let acl = TestAcl::new();
962        let mut subject = SubjectDescriptor::commissioning();
963        subject.is_commissioning = false;
964        assert!(acl.granted(&node(), &subject, 0, 0x001D).is_empty());
965    }
966
967    #[test]
968    fn an_empty_subject_list_is_a_wildcard_not_an_empty_set() {
969        // The sign that must not be backwards: empty means "anyone on this fabric".
970        let mut acl = TestAcl::new();
971        acl.add(TestEntry::case(F1, Privilege::Operate))
972            .expect("add");
973        let granted = acl.granted(&node(), &SubjectDescriptor::case(F1, ALICE), 1, ON_OFF);
974        assert!(granted.has(Privilege::Operate));
975        assert!(granted.has(Privilege::View), "Operate subsumes View");
976        assert!(!granted.has(Privilege::Manage));
977    }
978
979    #[test]
980    fn a_named_subject_excludes_every_other() {
981        let mut acl = TestAcl::new();
982        acl.add(
983            TestEntry::case(F1, Privilege::Manage)
984                .with_subject(ALICE)
985                .expect("subject"),
986        )
987        .expect("add");
988        assert!(
989            acl.granted(&node(), &SubjectDescriptor::case(F1, ALICE), 1, ON_OFF)
990                .has(Privilege::Manage)
991        );
992        assert!(
993            acl.granted(&node(), &SubjectDescriptor::case(F1, BOB), 1, ON_OFF)
994                .is_empty()
995        );
996    }
997
998    #[test]
999    fn another_fabrics_entry_is_invisible() {
1000        // The isolation that stops a second administrator inheriting the first's node.
1001        let mut acl = TestAcl::new();
1002        acl.add(TestEntry::case(F2, Privilege::Administer))
1003            .expect("add");
1004        assert!(
1005            acl.granted(&node(), &SubjectDescriptor::case(F1, ALICE), 1, ON_OFF)
1006                .is_empty()
1007        );
1008        assert!(
1009            acl.granted(&node(), &SubjectDescriptor::case(F2, ALICE), 1, ON_OFF)
1010                .has(Privilege::Administer)
1011        );
1012    }
1013
1014    #[test]
1015    fn an_auth_mode_never_subsumes_another() {
1016        let mut acl = TestAcl::new();
1017        acl.add(TestEntry::case(F1, Privilege::Operate))
1018            .expect("add");
1019        let mut group = SubjectDescriptor::case(F1, ALICE);
1020        group.auth_mode = Some(AuthMode::Group);
1021        assert!(acl.granted(&node(), &group, 1, ON_OFF).is_empty());
1022    }
1023
1024    #[test]
1025    fn a_target_narrows_to_one_cluster() {
1026        let mut acl = TestAcl::new();
1027        acl.add(
1028            TestEntry::case(F1, Privilege::Operate)
1029                .with_target(Target::cluster(ON_OFF))
1030                .expect("target"),
1031        )
1032        .expect("add");
1033        let subject = SubjectDescriptor::case(F1, ALICE);
1034        assert!(
1035            acl.granted(&node(), &subject, 1, ON_OFF)
1036                .has(Privilege::Operate)
1037        );
1038        assert!(acl.granted(&node(), &subject, 1, LEVEL).is_empty());
1039    }
1040
1041    #[test]
1042    fn a_target_may_name_an_endpoint_by_its_device_type() {
1043        // "Endpoint may be specified indirectly via device type" — which only works because
1044        // the endpoint itself carries its device types.
1045        let mut acl = TestAcl::new();
1046        acl.add(
1047            TestEntry::case(F1, Privilege::Operate)
1048                .with_target(Target::device_type(0x0100))
1049                .expect("target"),
1050        )
1051        .expect("add");
1052        let subject = SubjectDescriptor::case(F1, ALICE);
1053        assert!(
1054            acl.granted(&node(), &subject, 1, ON_OFF)
1055                .has(Privilege::Operate),
1056            "endpoint 1 is an On/Off Light"
1057        );
1058        assert!(
1059            acl.granted(&node(), &subject, 0, 0x001D).is_empty(),
1060            "endpoint 0 is not"
1061        );
1062    }
1063
1064    #[test]
1065    fn a_cat_matches_at_or_above_the_entrys_version() {
1066        // The direction that decides whether revocation works at all.
1067        let tag = CaseAuthenticatedTag::new(0xABCD, 3);
1068        let mut acl = TestAcl::new();
1069        acl.add(
1070            TestEntry::case(F1, Privilege::Manage)
1071                .with_subject(tag.to_node_id())
1072                .expect("subject"),
1073        )
1074        .expect("add");
1075
1076        for (version, expected) in [(2u16, false), (3, true), (4, true)] {
1077            let subject = SubjectDescriptor::case(F1, ALICE)
1078                .with_cat(CaseAuthenticatedTag::new(0xABCD, version))
1079                .expect("cat");
1080            assert_eq!(
1081                acl.granted(&node(), &subject, 1, ON_OFF)
1082                    .has(Privilege::Manage),
1083                expected,
1084                "version {version} against an entry naming 3"
1085            );
1086        }
1087    }
1088
1089    #[test]
1090    fn a_cat_with_another_identifier_never_matches() {
1091        let mut acl = TestAcl::new();
1092        acl.add(
1093            TestEntry::case(F1, Privilege::Manage)
1094                .with_subject(CaseAuthenticatedTag::new(0xABCD, 1).to_node_id())
1095                .expect("subject"),
1096        )
1097        .expect("add");
1098        let subject = SubjectDescriptor::case(F1, ALICE)
1099            .with_cat(CaseAuthenticatedTag::new(0x1234, 9))
1100            .expect("cat");
1101        assert!(acl.granted(&node(), &subject, 1, ON_OFF).is_empty());
1102    }
1103
1104    #[test]
1105    fn a_pase_entry_cannot_be_written() {
1106        // §6.6.2.1: the commissioner's grant is implicit, and an explicit one would outlive
1107        // the session that justified it.
1108        let mut acl = TestAcl::new();
1109        let mut entry = TestEntry::case(F1, Privilege::Administer);
1110        entry.auth_mode = AuthMode::Pase;
1111        assert_eq!(
1112            acl.add(entry).map_err(|e| e.code()),
1113            Err(ErrorCode::InvalidArgument)
1114        );
1115    }
1116
1117    #[test]
1118    fn a_group_entry_may_not_administer() {
1119        // §9.10.5.7: a group key has no per-node attribution, so administering with one
1120        // would make every holder an administrator and leave no record of which acted.
1121        let mut acl = TestAcl::new();
1122        let mut entry = TestEntry::case(F1, Privilege::Administer);
1123        entry.auth_mode = AuthMode::Group;
1124        assert_eq!(
1125            acl.add(entry).map_err(|e| e.code()),
1126            Err(ErrorCode::InvalidArgument)
1127        );
1128    }
1129
1130    #[test]
1131    fn a_target_naming_both_an_endpoint_and_a_device_type_is_refused() {
1132        let target = Target {
1133            cluster: None,
1134            endpoint: Some(1),
1135            device_type: Some(0x0100),
1136        };
1137        assert!(!target.is_valid());
1138        assert!(
1139            TestEntry::case(F1, Privilege::View)
1140                .with_target(target)
1141                .is_err()
1142        );
1143    }
1144
1145    #[test]
1146    fn an_empty_target_is_refused() {
1147        assert!(!Target::default().is_valid());
1148    }
1149
1150    #[test]
1151    fn proxy_view_is_not_subsumed_by_anything() {
1152        // §9.10.5.2's subsumption chain runs View ← Operate ← Manage ← Administer. ProxyView
1153        // is outside it, so an Administer grant does not carry it.
1154        let mut acl = TestAcl::new();
1155        acl.add(TestEntry::case(F1, Privilege::Administer))
1156            .expect("add");
1157        let granted = acl.granted(&node(), &SubjectDescriptor::case(F1, ALICE), 1, ON_OFF);
1158        assert!(granted.has(Privilege::Administer));
1159        assert!(granted.has(Privilege::View));
1160        assert!(
1161            !granted.has(Privilege::ProxyView),
1162            "ProxyView is not in the chain"
1163        );
1164    }
1165
1166    #[test]
1167    fn removing_a_fabric_takes_its_entries() {
1168        let mut acl = TestAcl::new();
1169        acl.add(TestEntry::case(F1, Privilege::Operate))
1170            .expect("add");
1171        acl.add(TestEntry::case(F2, Privilege::Operate))
1172            .expect("add");
1173        acl.remove_fabric(F1);
1174        assert_eq!(acl.len(), 1);
1175        assert!(
1176            acl.granted(&node(), &SubjectDescriptor::case(F1, ALICE), 1, ON_OFF)
1177                .is_empty()
1178        );
1179        assert!(
1180            acl.granted(&node(), &SubjectDescriptor::case(F2, ALICE), 1, ON_OFF)
1181                .has(Privilege::Operate)
1182        );
1183    }
1184
1185    #[test]
1186    fn the_add_noc_administrator_entry_has_the_shape_11_18_6_8_fixes() {
1187        // The entry that keeps a freshly commissioned node administrable. Its shape is
1188        // specified exactly, and every field of it matters.
1189        let mut acl = TestAcl::new();
1190        acl.add_admin_for_fabric(F1, ALICE).expect("bootstrap");
1191
1192        let entry = acl.of_fabric(F1).next().expect("one entry");
1193        assert_eq!(entry.privilege, Privilege::Administer);
1194        assert_eq!(entry.auth_mode, AuthMode::Case);
1195        assert_eq!(entry.subjects.as_slice(), &[ALICE]);
1196        assert!(
1197            entry.targets.is_empty(),
1198            "Targets: [] means the entire node"
1199        );
1200
1201        // ...and it does what it is for: that subject can now administer over CASE.
1202        let subject = SubjectDescriptor::case(F1, ALICE);
1203        assert!(
1204            acl.granted(&node(), &subject, 0, 0x001D)
1205                .has(Privilege::Administer)
1206        );
1207    }
1208
1209    #[test]
1210    fn a_target_naming_an_identifier_that_cannot_exist_is_refused() {
1211        // §7.21.2's MEI tables and §7.19.2.27's "Endpoint numbers SHALL NOT be 0xFFFF". A
1212        // target whose cluster, endpoint or device type is outside its range names nothing any
1213        // node could ever have, so it is a constraint error rather than an absent cluster.
1214        for bad in [
1215            // Prefix 0xFFFF is Invalid in Table 103's own words.
1216            Target {
1217                cluster: Some(0xFFFF_FFFF),
1218                ..Target::default()
1219            },
1220            // The gap between a standard cluster and a manufacturer-specific one.
1221            Target {
1222                cluster: Some(0x0000_8000),
1223                ..Target::default()
1224            },
1225            Target {
1226                device_type: Some(0xFFFF_FFFF),
1227                ..Target::default()
1228            },
1229            // Past Table 102's 0xBFFF for a device type.
1230            Target {
1231                device_type: Some(0x0000_C000),
1232                ..Target::default()
1233            },
1234            Target {
1235                endpoint: Some(0xFFFF),
1236                ..Target::default()
1237            },
1238        ] {
1239            assert!(!bad.is_valid(), "{bad:?} was accepted");
1240            // And `with_target` refuses it, so it cannot reach an entry in the first place.
1241            let entry = TestEntry::case(F1, Privilege::Operate)
1242                .with_target(bad)
1243                .map_err(|e| e.code());
1244            assert_eq!(entry.err(), Some(ErrorCode::InvalidArgument));
1245        }
1246
1247        // And the shapes that are legal stay legal.
1248        for good in [
1249            Target {
1250                cluster: Some(0x0000_0006),
1251                ..Target::default()
1252            },
1253            Target {
1254                cluster: Some(0xFFF1_FC00),
1255                ..Target::default()
1256            },
1257            Target {
1258                endpoint: Some(1),
1259                ..Target::default()
1260            },
1261            Target {
1262                device_type: Some(0x0000_0100),
1263                ..Target::default()
1264            },
1265        ] {
1266            assert!(good.is_valid(), "{good:?} was refused");
1267        }
1268    }
1269
1270    #[test]
1271    fn a_subject_outside_its_auth_modes_shape_is_refused() {
1272        // §9.10.5.7's Subject Semantics table. Every one of these is a 64-bit integer the
1273        // decoder is happy with and the access-control algorithm can never match, so an entry
1274        // holding one is an administrator's mistake that takes effect as silence.
1275        for bad in [
1276            // §2.5.5.6's Unspecified Node ID: "a reserved value that never appears in messages
1277            // or protocol usage".
1278            NodeId(0),
1279            // The top of the group range, which is not a CASE subject at all.
1280            NodeId(0xFFFF_FFFF_FFFF_FFFF),
1281            // A group node id, likewise.
1282            NodeId(0xFFFF_FFFF_FFFF_0000),
1283            // In the CAT range, and not a CAT: §6.6.2.1.2 says "A version number of 0 is
1284            // invalid and SHALL NOT be used", and this one's version is 0.
1285            NodeId(0xFFFF_FFFD_0000_0000),
1286            NodeId(0xFFFF_FFFD_ABCD_0000),
1287            // The PAKE key identifier and temporary-local ranges are not subjects either.
1288            NodeId(0xFFFF_FFFB_0000_0001),
1289            NodeId(0xFFFF_FFFE_0000_0001),
1290        ] {
1291            let mut acl = TestAcl::new();
1292            let entry = TestEntry::case(F1, Privilege::Operate)
1293                .with_subject(bad)
1294                .expect("the list has room");
1295            assert_eq!(
1296                acl.add(entry).map_err(|e| e.code()),
1297                Err(ErrorCode::InvalidArgument),
1298                "{bad:?} was accepted as a CASE subject"
1299            );
1300        }
1301
1302        // And the two shapes that are legal stay legal.
1303        for good in [ALICE, CaseAuthenticatedTag::new(0xABCD, 2).to_node_id()] {
1304            let mut acl = TestAcl::new();
1305            let entry = TestEntry::case(F1, Privilege::Operate)
1306                .with_subject(good)
1307                .expect("the list has room");
1308            acl.add(entry).expect("a legal CASE subject");
1309        }
1310    }
1311
1312    #[test]
1313    fn a_group_subject_is_a_group_id_and_nothing_else() {
1314        // "Group — Lower 16-bits → Group ID, Upper 48-bits → all bits clear", and §11.2.4
1315        // reserves group 0 for the All-Nodes group.
1316        let mut acl = TestAcl::new();
1317        let mut entry = TestEntry::case(F1, Privilege::Operate);
1318        entry.auth_mode = AuthMode::Group;
1319        // `ALICE` is deliberately not in this list: it is `0x1111`, which fits in sixteen bits
1320        // and *is* a well-formed group subject. A node id is only out of shape here when it
1321        // sets one of the upper forty-eight.
1322        for bad in [NodeId(0), NodeId(0x0001_0000), NodeId(0x1234_5678)] {
1323            let candidate = entry.clone().with_subject(bad).expect("the list has room");
1324            assert_eq!(
1325                acl.add(candidate).map_err(|e| e.code()),
1326                Err(ErrorCode::InvalidArgument),
1327                "{bad:?} was accepted as a Group subject"
1328            );
1329        }
1330        let good = entry.with_subject(NodeId(0x1234)).expect("room");
1331        acl.add(good).expect("a group id is a group subject");
1332    }
1333
1334    #[test]
1335    fn a_case_admin_subject_outside_the_two_legal_ranges_is_refused() {
1336        // §11.18.6.8: "not being in either the Operational or CASE Authenticated Tag range"
1337        // is `InvalidAdminSubject`. A group id or zero names something that can never
1338        // authenticate over CASE, so an entry for it would be permanently dead — and the
1339        // node permanently unadministrable.
1340        let mut acl = TestAcl::new();
1341        for bad in [NodeId(0), NodeId(0xFFFF_FFFF_FFFF_0001)] {
1342            assert_eq!(
1343                acl.add_admin_for_fabric(F1, bad).map_err(|e| e.code()),
1344                Err(ErrorCode::InvalidArgument),
1345                "{bad:?}"
1346            );
1347        }
1348        // A CAT is legal, and is how §6.6.3's fleet administrators are granted.
1349        acl.add_admin_for_fabric(F1, CaseAuthenticatedTag::new(0xFFF1, 1).to_node_id())
1350            .expect("a CAT is a valid admin subject");
1351    }
1352
1353    #[test]
1354    fn administer_requires_case_whichever_way_it_is_asked_for() {
1355        // §6.6.2.11: "it SHALL NOT be valid to have an Administer privilege set on an Access
1356        // Control Entry, unless AuthMode is 'CASE'."
1357        let mut acl = TestAcl::new();
1358        for mode in [AuthMode::Group, AuthMode::Pase] {
1359            let mut entry = TestEntry::case(F1, Privilege::Administer);
1360            entry.auth_mode = mode;
1361            assert_eq!(
1362                acl.add(entry).map_err(|e| e.code()),
1363                Err(ErrorCode::InvalidArgument),
1364                "{mode:?} at Administer"
1365            );
1366        }
1367        // Every lower privilege is fine on a Group entry.
1368        for privilege in [Privilege::View, Privilege::Operate, Privilege::Manage] {
1369            let mut entry = TestEntry::case(F1, privilege);
1370            entry.auth_mode = AuthMode::Group;
1371            acl.add(entry)
1372                .expect("a group entry below Administer is legal");
1373        }
1374    }
1375
1376    #[test]
1377    fn a_fabrics_quota_is_its_own() {
1378        let mut acl = TestAcl::new();
1379        for _ in 0..DefaultConfig::ACL_ENTRIES_PER_FABRIC {
1380            acl.add(TestEntry::case(F1, Privilege::View)).expect("fits");
1381        }
1382        assert_eq!(
1383            acl.add(TestEntry::case(F1, Privilege::View))
1384                .map_err(|e| e.code()),
1385            Err(ErrorCode::NoSpace)
1386        );
1387        acl.add(TestEntry::case(F2, Privilege::View))
1388            .expect("another fabric has its own quota");
1389    }
1390
1391    // --- §6.6.6.3, deriving the subject from the session ------------------------------------
1392
1393    #[cfg(feature = "rustcrypto")]
1394    fn session(kind: crate::session::SessionKind) -> crate::session::SecureSession {
1395        use crate::msg::SessionId;
1396        use crate::platform::Instant;
1397        use crate::session::{EstablishedKeys, Role, SecureSession};
1398        SecureSession::new(
1399            SessionId(1),
1400            SessionId(2),
1401            kind,
1402            Role::Responder,
1403            EstablishedKeys::derive(b"shared secret", &[]).expect("derive"),
1404            1,
1405            Instant::ZERO,
1406        )
1407    }
1408
1409    #[cfg(feature = "rustcrypto")]
1410    #[test]
1411    fn a_pase_session_derives_the_commissioning_subject() {
1412        // §6.6.6.3's PASE branch sets IsCommissioning unconditionally and presents the
1413        // passcode id as the subject.
1414        let s = session(crate::session::SessionKind::Pase);
1415        let isd = SubjectDescriptor::from_session(&s, None);
1416        assert_eq!(isd.auth_mode, Some(AuthMode::Pase));
1417        assert!(isd.is_commissioning);
1418        assert_eq!(
1419            isd.subjects.as_slice(),
1420            &[NodeId(DEFAULT_COMMISSIONING_PASSCODE)]
1421        );
1422        assert_eq!(isd.fabric_index, FabricIndex(0), "PASE has no fabric yet");
1423    }
1424
1425    #[cfg(feature = "rustcrypto")]
1426    #[test]
1427    fn a_case_session_presents_its_node_id_and_every_cat() {
1428        let mut s = session(crate::session::SessionKind::Case);
1429        s.fabric_index = F1;
1430        s.peer_node_id = ALICE;
1431        let tags = [
1432            CaseAuthenticatedTag::new(0xAAAA, 1),
1433            CaseAuthenticatedTag::new(0xBBBB, 2),
1434            CaseAuthenticatedTag::new(0xCCCC, 3),
1435        ];
1436        for tag in tags {
1437            s.peer_cats.push(tag).expect("three fit");
1438        }
1439
1440        let isd = SubjectDescriptor::from_session(&s, None);
1441        assert_eq!(isd.auth_mode, Some(AuthMode::Case));
1442        assert!(!isd.is_commissioning);
1443        assert_eq!(isd.fabric_index, F1);
1444        assert_eq!(
1445            isd.subjects.len(),
1446            4,
1447            "the node id plus §6.5.6's three CATs"
1448        );
1449        assert_eq!(isd.subjects[0], ALICE);
1450        for (index, tag) in tags.iter().enumerate() {
1451            assert_eq!(isd.subjects[index + 1], tag.to_node_id());
1452        }
1453    }
1454
1455    #[cfg(feature = "rustcrypto")]
1456    #[test]
1457    fn a_case_session_on_the_pending_fabric_is_still_commissioning() {
1458        // §6.6.6.3: "isd.IsCommissioning = get_fabric_index(session_id) ==
1459        // get_pending_fabric_index()". A commissioner that has switched from PASE to CASE
1460        // before the fail-safe commits keeps its standing.
1461        let mut s = session(crate::session::SessionKind::Case);
1462        s.fabric_index = F1;
1463        s.peer_node_id = ALICE;
1464
1465        assert!(SubjectDescriptor::from_session(&s, Some(F1)).is_commissioning);
1466        assert!(!SubjectDescriptor::from_session(&s, Some(F2)).is_commissioning);
1467        assert!(!SubjectDescriptor::from_session(&s, None).is_commissioning);
1468    }
1469
1470    #[cfg(feature = "rustcrypto")]
1471    #[test]
1472    fn a_case_session_without_a_fabric_authenticates_nobody() {
1473        // "assert(isd.FabricIndex != 0) # cannot be zero". Rather than carry on with a fabric
1474        // that names nothing, the derivation returns the "no auth" descriptor — which grants
1475        // nothing, where fabric 0 would merely have failed to match and looked the same.
1476        let s = session(crate::session::SessionKind::Case);
1477        assert_eq!(s.fabric_index.0, 0);
1478        let isd = SubjectDescriptor::from_session(&s, None);
1479        assert_eq!(isd.auth_mode, None);
1480        assert!(isd.subjects.is_empty());
1481    }
1482
1483    #[test]
1484    fn an_unauthenticated_subject_matches_no_entry_at_all() {
1485        // §6.6.6.3's error path: "Do nothing on error, ISD remains unchanged." A wildcard
1486        // entry grants everyone on its fabric — and still not this.
1487        let mut acl = TestAcl::new();
1488        acl.add(TestEntry::case(F1, Privilege::Administer))
1489            .expect("add");
1490        let mut isd = SubjectDescriptor::unauthenticated();
1491        isd.fabric_index = F1;
1492        assert!(acl.granted(&node(), &isd, 1, ON_OFF).is_empty());
1493    }
1494
1495    #[test]
1496    fn a_group_subject_presents_its_group_id() {
1497        let isd = SubjectDescriptor::group(F1, crate::msg::GroupId(7));
1498        assert_eq!(isd.auth_mode, Some(AuthMode::Group));
1499        assert_eq!(isd.subjects.as_slice(), &[NodeId(7)]);
1500        assert!(!isd.is_commissioning);
1501    }
1502
1503    #[test]
1504    fn a_read_of_the_attribute_sees_only_its_own_fabric() {
1505        let mut acl = TestAcl::new();
1506        acl.add(TestEntry::case(F1, Privilege::Operate))
1507            .expect("add");
1508        acl.add(TestEntry::case(F2, Privilege::Manage))
1509            .expect("add");
1510        assert_eq!(acl.len_of_fabric(F1), 1);
1511        assert!(
1512            acl.of_fabric(F1)
1513                .all(|entry| entry.privilege == Privilege::Operate)
1514        );
1515    }
1516}