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