Skip to main content

matter_kit/clusters/
access_control.rs

1//! Access Control, cluster `0x001F` (Core §9.10).
2//!
3//! The cluster an administrator uses to say who may do what. Its own access quality is the
4//! point of the design: §9.10.5.7 requires "the Administer privilege to observe and modify
5//! the Access Control Cluster itself", so the only subject that can widen a node's
6//! permissions is one that already holds the widest.
7//!
8//! The decision logic is not here — it is [`acl`](crate::acl), because §6.6.6's algorithm is
9//! consulted on every interaction while this cluster is consulted only when someone edits the
10//! list. This is the *editing* half: the `ACL` attribute's read, its write, and the event that
11//! records the change.
12//!
13//! # Why the write is the interesting part
14//!
15//! `ACL` is a **list**, and §10.6.4.3.1 gives a client two ways to write one: replace the
16//! whole list, or append one entry at a time. An administrator writing four entries sends an
17//! empty array followed by four appends, so a cluster that treated every block as a
18//! replacement would end up holding one entry and report `SUCCESS` for all five blocks. That
19//! is why [`ClusterHandler::write`] takes a [`WriteOp`] — and why this cluster is the one
20//! that would have been hurt most by its absence.
21//!
22//! # Fabric scoping is enforced twice
23//!
24//! `ACL` is `F`, so a read reports only the accessing fabric's entries (§7.19.1.8.2) and a
25//! write replaces only the accessing fabric's. Neither is a filter applied for tidiness: an
26//! administrator on fabric 2 that could see or overwrite fabric 1's entries would be able to
27//! take the node away from the administrator that commissioned it.
28
29use core::cell::RefCell;
30
31use crate::acl::{Acl, AuthMode, Entry, Target};
32use crate::config::Config;
33use crate::dm::{
34    Access, AccessQualities, AttributeDescriptor, ClusterDescriptor, CommandDescriptor,
35    EventDescriptor, EventPriority, Privilege, Resolved,
36};
37use crate::im::{
38    AttributeId, ClusterHandler, ClusterId, EventId, InteractionContext, Status, WriteOp,
39};
40use crate::msg::{FabricIndex, NodeId};
41use crate::tlv::{ContainerKind, Tag, TlvReader, TlvWriter, Value};
42
43use super::Cluster;
44
45/// `0x001F` (§9.10.3).
46pub const ID: ClusterId = 0x001F;
47
48/// The revision §9.10.1's table ends on.
49pub const REVISION: u16 = 3;
50
51/// `ACL` (§9.10.6) — `list[AccessControlEntryStruct]`, `RW A F`, mandatory.
52pub const ACL: AttributeId = 0x0000;
53/// `Extension` (§9.10.6) — `list[AccessControlExtensionStruct]`, `RW A F`, `EXTS`.
54pub const EXTENSION: AttributeId = 0x0001;
55/// `SubjectsPerAccessControlEntry` (§9.10.6.5) — `uint16` `4 to 65534`, `F`, `RV`.
56pub const SUBJECTS_PER_ENTRY: AttributeId = 0x0002;
57/// `TargetsPerAccessControlEntry` (§9.10.6.6) — `uint16` `3 to 65534`, `F`, `RV`.
58pub const TARGETS_PER_ENTRY: AttributeId = 0x0003;
59/// `AccessControlEntriesPerFabric` (§9.10.6.7) — `uint16` `4 to 65534`, `F`, `RV`.
60pub const ENTRIES_PER_FABRIC: AttributeId = 0x0004;
61
62/// `AccessControlEntryChanged` (§9.10.9.1).
63pub const ACCESS_CONTROL_ENTRY_CHANGED: EventId = 0x0000;
64
65/// The global `FabricIndex` field of a fabric-scoped struct (§7.19.1.9).
66pub const FABRIC_INDEX_FIELD: u8 = 254;
67
68/// `ChangeTypeEnum` (§9.10.5.1).
69///
70/// A list attribute's entry is identified by its index — §10.6.4.3.1 edits by index — so a
71/// whole-list write is compared position by position: a position present before and after was
72/// *changed*, one only in the new list *added*, one only in the old list *removed*. A replace
73/// is not a wipe and a refill, and reporting it as one tells a controller it has lost entries
74/// it still has.
75#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
76pub enum ChangeType {
77    /// `0` — "Entry or extension was changed".
78    Changed = 0,
79    /// `1` — "Entry or extension was added".
80    Added = 1,
81    /// `2` — "Entry or extension was removed".
82    Removed = 2,
83}
84
85/// §9.10.6's attributes, in id order.
86///
87/// `ACL` is the only writable one, and it needs Administer for *both* directions — §9.10.5.7:
88/// "The Access Control Cluster SHALL require the Administer privilege to observe and modify
89/// the Access Control Cluster itself." A `View` subject cannot even read the list, which is
90/// what stops it enumerating who else has access.
91const ATTRIBUTES: &[AttributeDescriptor] = &[
92    AttributeDescriptor::read_write(ACL).with_access(
93        Access::read_write_with(Privilege::Administer, Privilege::Administer)
94            .with_qualities(AccessQualities::FABRIC_SCOPED),
95    ),
96    AttributeDescriptor::read_only(SUBJECTS_PER_ENTRY),
97    AttributeDescriptor::read_only(TARGETS_PER_ENTRY),
98    AttributeDescriptor::read_only(ENTRIES_PER_FABRIC),
99];
100
101const NO_COMMANDS: &[CommandDescriptor] = &[];
102
103/// §9.10.9's events. `AccessControlEntryChanged` is `INFO` priority and fabric-sensitive.
104const EVENTS: &[EventDescriptor] =
105    &[EventDescriptor::new(ACCESS_CONTROL_ENTRY_CHANGED).with_priority(EventPriority::Info)];
106
107/// The descriptor for this cluster.
108#[must_use]
109pub const fn cluster() -> ClusterDescriptor<'static> {
110    ClusterDescriptor {
111        id: ID,
112        revision: REVISION,
113        feature_map: 0,
114        attributes: ATTRIBUTES,
115        accepted_commands: NO_COMMANDS,
116        generated_commands: &[],
117        events: EVENTS,
118    }
119}
120
121/// How many [`EntryChanged`] records the cluster holds before the device drains them.
122///
123/// One write can produce several: §9.10.9.1 asks for an event per entry, and a replace is a
124/// removal of everything that was there followed by an addition of everything that now is. The
125/// bound is what a device is expected to drain between interactions, not a list capacity — a
126/// device that drains after every write never reaches it, and §9.10.6 requires only four ACL
127/// entries per fabric, so eight covers a full replace of a conforming fabric's list.
128const PENDING: usize = 8;
129
130/// What one change to the `ACL` attribute should be recorded as (§9.10.9.1).
131///
132/// The server "SHALL generate AccessControlEntryChanged events whenever its ACL attribute
133/// data is changed by an Administrator", and the event names *who*: "Exactly one of
134/// AdminNodeID and AdminPasscodeID SHALL be set, depending on whether the change occurred via
135/// a CASE or PASE session". Reported rather than logged here, because §7.14's event store is
136/// the device's and this cluster does not own one.
137#[derive(Debug, Clone, PartialEq, Eq)]
138pub struct EntryChanged<const S: usize, const T: usize> {
139    /// The administrator's node id, when the change came over CASE.
140    pub admin_node_id: Option<NodeId>,
141    /// The passcode id, when it came over PASE. Always `Some(0)` in practice: "Non-zero
142    /// values are reserved for future use".
143    pub admin_passcode_id: Option<u16>,
144    /// What happened.
145    pub change_type: ChangeType,
146    /// `LatestValue [4]` — "The latest value of the changed entry", which for a removal is the
147    /// entry as it stood when it was removed.
148    ///
149    /// `None` is the field's null, which §9.10.9.1 permits only as a concession: "This field
150    /// SHOULD be set if resources are adequate for it; otherwise it SHALL be set to NULL if
151    /// resources are scarce." An audit trail of *when* the list changed and never *to what* is
152    /// most of the way to no audit trail, so this carries the entry wherever one is available.
153    pub latest_value: Option<Entry<S, T>>,
154    /// The fabric whose list changed.
155    pub fabric_index: FabricIndex,
156}
157
158impl<const S: usize, const T: usize> EntryChanged<S, T> {
159    /// The record for a change made on `ctx`'s session.
160    #[must_use]
161    pub fn for_session(
162        ctx: &InteractionContext<'_>,
163        change_type: ChangeType,
164        latest_value: Option<Entry<S, T>>,
165    ) -> Self {
166        // §6.6.6.3 derives the administrator's identity from the *session*, never from
167        // anything the message claimed.
168        let (admin_node_id, admin_passcode_id) = match ctx.peer_node_id {
169            Some(node_id) => (Some(node_id), None),
170            None => (None, Some(0)),
171        };
172        let fabric_index = ctx.fabric_index.unwrap_or(FabricIndex(0));
173        Self {
174            admin_node_id,
175            admin_passcode_id,
176            change_type,
177            latest_value,
178            fabric_index,
179        }
180    }
181
182    /// The same record, attributed to a fabric the session does not yet carry.
183    ///
184    /// §11.18.6.8 step 7 adds the administrator entry for a fabric *during* `AddNOC`, over a
185    /// PASE session whose accessing fabric is bound only at step 10a — so at the moment of the
186    /// change `ctx.fabric_index` is still none, and the event would be attributed to fabric 0
187    /// and visible to nobody. §7.14.4 makes a fabric-sensitive event readable only by its own
188    /// fabric, which for this one means the fabric it just created.
189    #[must_use]
190    pub fn for_fabric(mut self, fabric_index: FabricIndex) -> Self {
191        self.fabric_index = fabric_index;
192        self
193    }
194
195    /// Writes the event's fields (§9.10.9.1).
196    pub fn encode(&self, w: &mut TlvWriter<'_>, tag: Tag) -> crate::error::Result<()> {
197        w.start_structure(tag)?;
198        match self.admin_node_id {
199            Some(id) => w.unsigned(Tag::Context(1), id.0)?,
200            None => w.null(Tag::Context(1))?,
201        }
202        match self.admin_passcode_id {
203            Some(id) => w.unsigned(Tag::Context(2), u64::from(id))?,
204            None => w.null(Tag::Context(2))?,
205        }
206        w.unsigned(Tag::Context(3), self.change_type as u64)?;
207        match &self.latest_value {
208            Some(entry) => write_entry(w, Tag::Context(4), entry)?,
209            None => w.null(Tag::Context(4))?,
210        }
211        w.unsigned(
212            Tag::Context(FABRIC_INDEX_FIELD),
213            u64::from(self.fabric_index.0),
214        )?;
215        w.end_container()
216    }
217}
218
219/// One `AccessControlEntryStruct` (§9.10.5.7), as the `ACL` attribute and the
220/// `AccessControlEntryChanged` event both need it.
221///
222/// One encoder rather than two: an event whose `LatestValue` disagreed with the attribute it
223/// reports a change to would be worse than no event, and two copies of this drift in exactly
224/// the fields — the null-as-wildcard ones — that are easiest to get wrong.
225fn write_entry<const S: usize, const T: usize>(
226    w: &mut TlvWriter<'_>,
227    tag: Tag,
228    entry: &Entry<S, T>,
229) -> crate::error::Result<()> {
230    w.start_structure(tag)?;
231    w.unsigned(Tag::Context(1), privilege_value(entry.privilege))?;
232    w.unsigned(Tag::Context(2), entry.auth_mode as u64)?;
233    // §9.10.5.7's Subjects and Targets are both `X` — nullable — and an empty list is written
234    // as null rather than as an empty array, because null is the wildcard the algorithm reads
235    // and an empty array would say "matches nothing".
236    if entry.subjects.is_empty() {
237        w.null(Tag::Context(3))?;
238    } else {
239        w.start_array(Tag::Context(3))?;
240        for subject in &entry.subjects {
241            w.unsigned(Tag::Anonymous, subject.0)?;
242        }
243        w.end_container()?;
244    }
245    if entry.targets.is_empty() {
246        w.null(Tag::Context(4))?;
247    } else {
248        w.start_array(Tag::Context(4))?;
249        for target in &entry.targets {
250            w.start_structure(Tag::Anonymous)?;
251            match target.cluster {
252                Some(id) => w.unsigned(Tag::Context(0), u64::from(id))?,
253                None => w.null(Tag::Context(0))?,
254            }
255            match target.endpoint {
256                Some(id) => w.unsigned(Tag::Context(1), u64::from(id))?,
257                None => w.null(Tag::Context(1))?,
258            }
259            match target.device_type {
260                Some(id) => w.unsigned(Tag::Context(2), u64::from(id))?,
261                None => w.null(Tag::Context(2))?,
262            }
263            w.end_container()?;
264        }
265        w.end_container()?;
266    }
267    w.unsigned(
268        Tag::Context(FABRIC_INDEX_FIELD),
269        u64::from(entry.fabric_index.0),
270    )?;
271    w.end_container()
272}
273
274/// The Access Control cluster over a node's [`Acl`].
275///
276/// The list is borrowed rather than owned, because §6.6.6 consults it on every interaction
277/// while this cluster only edits it — the same table has to be visible to both, and a copy
278/// would be a second answer to "who may do what".
279#[derive(Debug)]
280pub struct AccessControl<'a, C: Config, const N: usize, const S: usize, const T: usize> {
281    acl: &'a RefCell<Acl<C, N, S, T>>,
282    /// What the last write recorded, for the device to turn into §7.14 events.
283    pending: RefCell<heapless::Vec<EntryChanged<S, T>, PENDING>>,
284}
285
286impl<'a, C: Config, const N: usize, const S: usize, const T: usize> AccessControl<'a, C, N, S, T> {
287    /// A cluster over a node's access control list.
288    #[must_use]
289    pub fn new(acl: &'a RefCell<Acl<C, N, S, T>>) -> Self {
290        Self {
291            acl,
292            pending: RefCell::new(heapless::Vec::new()),
293        }
294    }
295
296    /// The list this cluster edits.
297    #[must_use]
298    pub const fn acl(&self) -> &'a RefCell<Acl<C, N, S, T>> {
299        self.acl
300    }
301
302    /// §11.18.6.8 step 7's administrator entry, added through the cluster so that it is
303    /// recorded like any other change.
304    ///
305    /// `AddNOC` creates exactly one ACL entry — "there would be no way for the caller on its
306    /// given Fabric to eventually add another Access Control Entry for CASE authentication
307    /// mode" without it — and it is the *only* entry on a freshly commissioned fabric. Added
308    /// straight to the [`Acl`] it is invisible to §9.10.9.1: the cluster never sees it, so the
309    /// audit trail of an Access Control cluster begins by omitting the one entry that granted
310    /// everything else. That is what the Test Harness reads first, and it is what an auditor
311    /// would want first.
312    ///
313    /// `ctx` is the `AddNOC` interaction, which is a PASE session — so the event names an
314    /// `AdminPasscodeID` and a null `AdminNodeID`, as §9.10.9.1 requires of a change made over
315    /// PASE. `fabric` is passed separately because §11.18.6.8 binds the accessing fabric to the
316    /// session only at step 10a, *after* this: taking it from `ctx` would attribute the event
317    /// to fabric 0, where §7.14.4's fabric sensitivity would hide it from everybody.
318    pub fn add_admin_for_fabric(
319        &self,
320        fabric: FabricIndex,
321        subject: NodeId,
322        ctx: &InteractionContext<'_>,
323    ) -> crate::error::Result<()> {
324        self.acl
325            .borrow_mut()
326            .add_admin_for_fabric(fabric, subject)?;
327        // The entry just added, which `Acl::add` appends: the last one on this fabric.
328        let entry = self.acl.borrow().of_fabric(fabric).last().cloned();
329        self.record(EntryChanged::for_session(ctx, ChangeType::Added, entry).for_fabric(fabric));
330        Ok(())
331    }
332
333    /// Takes the [`EntryChanged`] records the last writes produced (§9.10.9.1).
334    ///
335    /// The device turns these into events in its own store. Draining rather than reading
336    /// means a record is reported once, and a device that never drains cannot silently
337    /// accumulate them forever — the buffer is fixed and the oldest records are dropped,
338    /// the same way §7.14.2's event ring drops its oldest.
339    pub fn take_changes(&self) -> heapless::Vec<EntryChanged<S, T>, PENDING> {
340        core::mem::take(&mut self.pending.borrow_mut())
341    }
342
343    fn record(&self, change: EntryChanged<S, T>) {
344        let mut pending = self.pending.borrow_mut();
345        if pending.is_full() {
346            // Dropping the oldest matches §7.14.2's event ring: the most recent change is the
347            // one an auditor needs first.
348            let _ = pending.remove(0);
349        }
350        let _ = pending.push(change);
351    }
352
353    /// Whether a fabric's entries belong in this read (§7.19.1.8.2).
354    fn visible(ctx: &InteractionContext<'_>, index: FabricIndex) -> bool {
355        !ctx.fabric_filtered || ctx.fabric_index == Some(index)
356    }
357
358    fn read_acl(
359        &self,
360        ctx: &InteractionContext<'_>,
361        w: &mut TlvWriter<'_>,
362        tag: Tag,
363    ) -> Result<(), Status> {
364        let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
365        let acl = self.acl.borrow();
366        full(w.start_array(tag))?;
367        for entry in acl.entries().filter(|e| Self::visible(ctx, e.fabric_index)) {
368            full(write_entry(w, Tag::Anonymous, entry))?;
369        }
370        full(w.end_container())
371    }
372}
373
374/// §9.10.5.2's wire values, which are not this crate's enum discriminants.
375///
376/// The specification numbers `View` 1 and `ProxyView` 2; [`Privilege`] orders them by what
377/// they grant, so `ProxyView` sorts *below* `View`. The two orders disagree on purpose and
378/// this is where they are reconciled — encoding the discriminant directly would silently
379/// swap View and ProxyView on the wire.
380const fn privilege_value(privilege: Privilege) -> u64 {
381    match privilege {
382        Privilege::View => 1,
383        Privilege::ProxyView => 2,
384        Privilege::Operate => 3,
385        Privilege::Manage => 4,
386        Privilege::Administer => 5,
387    }
388}
389
390const fn privilege_from_value(value: u64) -> Option<Privilege> {
391    match value {
392        1 => Some(Privilege::View),
393        2 => Some(Privilege::ProxyView),
394        3 => Some(Privilege::Operate),
395        4 => Some(Privilege::Manage),
396        5 => Some(Privilege::Administer),
397        _ => None,
398    }
399}
400
401/// Reads one `AccessControlEntryStruct` (§9.10.5.7) whose opening structure has been taken.
402fn decode_entry<const S: usize, const T: usize>(
403    reader: &mut TlvReader<'_>,
404    fabric_index: FabricIndex,
405) -> Result<Entry<S, T>, Status> {
406    let mut privilege = None;
407    let mut auth_mode = None;
408    let mut subjects = heapless::Vec::new();
409    let mut targets = heapless::Vec::new();
410
411    loop {
412        let Some(element) = reader.next_element().map_err(|_| Status::InvalidAction)? else {
413            return Err(Status::InvalidAction);
414        };
415        if element.value == Value::EndOfContainer {
416            break;
417        }
418        match element.tag.context() {
419            Some(1) => {
420                let value = element.unsigned().map_err(|_| Status::ConstraintError)?;
421                privilege = Some(privilege_from_value(value).ok_or(Status::ConstraintError)?);
422            }
423            Some(2) => {
424                let value = element.unsigned().map_err(|_| Status::ConstraintError)?;
425                let narrowed = u8::try_from(value).map_err(|_| Status::ConstraintError)?;
426                auth_mode = Some(AuthMode::from_value(narrowed).ok_or(Status::ConstraintError)?);
427            }
428            Some(3) => {
429                if element.value.is_null() {
430                    continue;
431                }
432                if element.value.container() != Some(ContainerKind::Array) {
433                    return Err(Status::InvalidAction);
434                }
435                loop {
436                    let Some(item) = reader.next_element().map_err(|_| Status::InvalidAction)?
437                    else {
438                        return Err(Status::InvalidAction);
439                    };
440                    if item.value == Value::EndOfContainer {
441                        break;
442                    }
443                    let id = item.unsigned().map_err(|_| Status::ConstraintError)?;
444                    subjects
445                        .push(NodeId(id))
446                        .map_err(|_| Status::ResourceExhausted)?;
447                }
448            }
449            Some(4) => {
450                if element.value.is_null() {
451                    continue;
452                }
453                if element.value.container() != Some(ContainerKind::Array) {
454                    return Err(Status::InvalidAction);
455                }
456                loop {
457                    let Some(item) = reader.next_element().map_err(|_| Status::InvalidAction)?
458                    else {
459                        return Err(Status::InvalidAction);
460                    };
461                    if item.value == Value::EndOfContainer {
462                        break;
463                    }
464                    if item.value.container() != Some(ContainerKind::Structure) {
465                        return Err(Status::InvalidAction);
466                    }
467                    targets
468                        .push(decode_target(reader)?)
469                        .map_err(|_| Status::ResourceExhausted)?;
470                }
471            }
472            // The FabricIndex a client sends is ignored: §7.19.1.9's field is set by the
473            // server from the accessing fabric, so a client cannot write into another's list
474            // by naming it.
475            _ => reader
476                .skip_value(&element)
477                .map_err(|_| Status::InvalidAction)?,
478        }
479    }
480
481    Ok(Entry {
482        fabric_index,
483        privilege: privilege.ok_or(Status::InvalidAction)?,
484        auth_mode: auth_mode.ok_or(Status::InvalidAction)?,
485        subjects,
486        targets,
487    })
488}
489
490/// Reads one `AccessControlTargetStruct` (§9.10.5.6) whose opening structure has been taken.
491fn decode_target(reader: &mut TlvReader<'_>) -> Result<Target, Status> {
492    let mut target = Target::default();
493    loop {
494        let Some(element) = reader.next_element().map_err(|_| Status::InvalidAction)? else {
495            return Err(Status::InvalidAction);
496        };
497        if element.value == Value::EndOfContainer {
498            break;
499        }
500        if element.value.is_null() {
501            continue;
502        }
503        let value = element.unsigned().map_err(|_| Status::ConstraintError)?;
504        match element.tag.context() {
505            Some(0) => {
506                target.cluster = Some(u32::try_from(value).map_err(|_| Status::ConstraintError)?);
507            }
508            Some(1) => {
509                target.endpoint = Some(u16::try_from(value).map_err(|_| Status::ConstraintError)?);
510            }
511            Some(2) => {
512                target.device_type =
513                    Some(u32::try_from(value).map_err(|_| Status::ConstraintError)?);
514            }
515            _ => {}
516        }
517    }
518    if !target.is_valid() {
519        return Err(Status::ConstraintError);
520    }
521    Ok(target)
522}
523
524impl<C: Config, const N: usize, const S: usize, const T: usize> ClusterHandler
525    for AccessControl<'_, C, N, S, T>
526{
527    /// §9.10.5.3: every ACL entry carries a `FabricIndex`, and §11.18.6.12 removes them with
528    /// the fabric. An entry that survives grants the *next* holder of that index whatever it
529    /// granted — the one case in this file that is an escalation rather than a leak.
530    fn on_lifecycle(&self, event: crate::im::Lifecycle) {
531        if let crate::im::Lifecycle::FabricRemoved(fabric) = event {
532            self.acl.borrow_mut().remove_fabric(fabric);
533        }
534    }
535    fn read(
536        &self,
537        resolved: &Resolved<'_>,
538        ctx: &InteractionContext<'_>,
539        w: &mut TlvWriter<'_>,
540        tag: Tag,
541    ) -> Result<(), Status> {
542        let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
543        match resolved.attribute {
544            ACL => self.read_acl(ctx, w, tag),
545            // §9.10.6.5–7 report the *minimum* the server supports, and every one of the three
546            // comes from the list that will have to honour it: `S` and `T` are the entry's own
547            // widths, and `PER_FABRIC` is the quota `Acl::insert` enforces. `Acl::CHECK` is what
548            // makes the third of those a promise the list can keep — without it this attribute
549            // is a number typed next to a table of a different size.
550            SUBJECTS_PER_ENTRY => full(w.unsigned(tag, S as u64)),
551            TARGETS_PER_ENTRY => full(w.unsigned(tag, T as u64)),
552            ENTRIES_PER_FABRIC => full(w.unsigned(
553                tag,
554                <Acl<C, N, S, T> as crate::config::Capacity>::PER_FABRIC as u64,
555            )),
556            _ => Err(Status::UnsupportedAttribute),
557        }
558    }
559
560    fn write(
561        &self,
562        resolved: &Resolved<'_>,
563        data: &[u8],
564        op: WriteOp,
565        ctx: &InteractionContext<'_>,
566    ) -> Result<(), Status> {
567        if resolved.attribute != ACL {
568            return Err(Status::UnsupportedWrite);
569        }
570        // §7.19.1.8.1: a write to a fabric-scoped list needs an accessing fabric to scope it
571        // to. A PASE session has none, so it cannot edit the list even though it holds
572        // Administer — there is no fabric for its entries to belong to.
573        let Some(fabric_index) = ctx.fabric_index else {
574            return Err(Status::UnsupportedAccess);
575        };
576
577        let mut reader = TlvReader::new_in(data, ContainerKind::Structure);
578        let element = reader
579            .next_element()
580            .map_err(|_| Status::InvalidAction)?
581            .ok_or(Status::InvalidAction)?;
582
583        let mut acl = self.acl.borrow_mut();
584        match op {
585            WriteOp::Replace => {
586                // §10.6.4.3.1's REPLACE: "Data SHALL contain new values that will replace the
587                // existing contents of the list", so an empty array clears it — which is how
588                // the item-by-item encoding begins.
589                if element.value.container() != Some(ContainerKind::Array) {
590                    return Err(Status::InvalidAction);
591                }
592                let mut replacement: heapless::Vec<Entry<S, T>, N> = heapless::Vec::new();
593                loop {
594                    let Some(item) = reader.next_element().map_err(|_| Status::InvalidAction)?
595                    else {
596                        return Err(Status::InvalidAction);
597                    };
598                    if item.value == Value::EndOfContainer {
599                        break;
600                    }
601                    if item.value.container() != Some(ContainerKind::Structure) {
602                        return Err(Status::InvalidAction);
603                    }
604                    replacement
605                        .push(decode_entry(&mut reader, fabric_index)?)
606                        .map_err(|_| Status::ResourceExhausted)?;
607                }
608                // §9.10.9.1 wants "the latest value of the changed entry" in every event, and
609                // a replace removes entries as well as adding them — so the outgoing list is
610                // copied out before it stops existing. `PENDING` because a record beyond that
611                // many would be dropped by `record` anyway; copying further would buy nothing.
612                let removed: heapless::Vec<Entry<S, T>, PENDING> =
613                    acl.of_fabric(fabric_index).take(PENDING).cloned().collect();
614                // A replace that fails partway leaves the fabric's list partly rebuilt. That
615                // is not a defect to hide: §10.6.4.3.1 says so directly — "clients that
616                // receive an error status for a write action to a list attribute SHOULD NOT
617                // assume that the list contents are unchanged" — and pretending otherwise
618                // would mean buffering a second copy of the whole list to roll back to.
619                acl.replace_fabric(fabric_index, replacement)
620                    .map_err(|_| Status::ConstraintError)?;
621                let added: heapless::Vec<Entry<S, T>, PENDING> =
622                    acl.of_fabric(fabric_index).take(PENDING).cloned().collect();
623                drop(acl);
624                // §9.10.9.1 gives three change types and a replace can produce all three, so
625                // the two lists are compared **position by position**:
626                //
627                //   - a position that existed before and exists now was *changed*;
628                //   - a position only in the new list was *added*;
629                //   - a position only in the old list was *removed*.
630                //
631                // A list attribute's entry is identified by its index — §10.6.4.3.1 edits by
632                // index — so rewriting the same value at the same position is still a write of
633                // that entry and is still a Changed. A controller replacing `[admin]` with
634                // `[admin, operator]` therefore gets one Changed and one Added, not a Removed
635                // and two Addeds.
636                //
637                // The legacy list encoding falls out of the same rule rather than needing one
638                // of its own: a client that clears the list and appends to it sends a replace
639                // with an empty list — every position removed — and then one append per entry.
640                let mut old_entries = removed.into_iter();
641                let mut new_entries = added.into_iter();
642                loop {
643                    let (change_type, entry) = match (new_entries.next(), old_entries.next()) {
644                        (Some(entry), Some(_)) => (ChangeType::Changed, entry),
645                        (Some(entry), None) => (ChangeType::Added, entry),
646                        (None, Some(entry)) => (ChangeType::Removed, entry),
647                        (None, None) => break,
648                    };
649                    self.record(EntryChanged::for_session(ctx, change_type, Some(entry)));
650                }
651            }
652            WriteOp::Append => {
653                // §10.6.4.3.1's ADD: "Data containing the new value of the list item that
654                // will be added to the list."
655                if element.value.container() != Some(ContainerKind::Structure) {
656                    return Err(Status::InvalidAction);
657                }
658                let entry = decode_entry::<S, T>(&mut reader, fabric_index)?;
659                let recorded = entry.clone();
660                acl.add(entry).map_err(|e| match e.code() {
661                    crate::ErrorCode::NoSpace => Status::ResourceExhausted,
662                    _ => Status::ConstraintError,
663                })?;
664                drop(acl);
665                self.record(EntryChanged::for_session(
666                    ctx,
667                    ChangeType::Added,
668                    Some(recorded),
669                ));
670            }
671        }
672        Ok(())
673    }
674}
675
676impl<C: Config, const N: usize, const S: usize, const T: usize> Cluster
677    for AccessControl<'_, C, N, S, T>
678{
679    const ID: ClusterId = ID;
680}
681
682#[cfg(test)]
683mod tests {
684    use super::*;
685    use crate::config::DefaultConfig;
686
687    type TestAcl = Acl<DefaultConfig>;
688
689    #[test]
690    fn the_wire_values_are_section_9_10_5_2s_and_not_the_enums_order() {
691        // `Privilege` orders by what it grants, so ProxyView sorts below View; §9.10.5.2
692        // numbers View 1 and ProxyView 2. Encoding the discriminant would swap them.
693        assert_eq!(privilege_value(Privilege::View), 1);
694        assert_eq!(privilege_value(Privilege::ProxyView), 2);
695        assert_eq!(privilege_value(Privilege::Operate), 3);
696        assert_eq!(privilege_value(Privilege::Administer), 5);
697        for value in 1..=5u64 {
698            let privilege = privilege_from_value(value).expect("defined");
699            assert_eq!(privilege_value(privilege), value, "round trips");
700        }
701        assert!(privilege_from_value(0).is_none());
702        assert!(privilege_from_value(6).is_none());
703    }
704
705    #[test]
706    fn the_descriptor_needs_administer_in_both_directions() {
707        // §9.10.5.7: "The Access Control Cluster SHALL require the Administer privilege to
708        // observe and modify the Access Control Cluster itself." A View subject that could
709        // read the list would learn who else has access to the node.
710        let descriptor = cluster();
711        let acl = descriptor.attribute(ACL).expect("ACL attribute");
712        assert_eq!(acl.access.read, Some(Privilege::Administer));
713        assert_eq!(acl.access.write, Some(Privilege::Administer));
714        assert!(acl.access.is_fabric_scoped());
715    }
716
717    #[test]
718    fn the_minima_are_reported_from_the_list_that_holds_them() {
719        // §9.10.6.5, §9.10.6.6 and §9.10.6.7 are constrained to `4..`, `3..` and `4..`, and all
720        // three are answered from the list rather than from a constant beside it —
721        // `Acl::CHECK` is what refuses a list too narrow or too short to mean them.
722        let acl = RefCell::new(TestAcl::new());
723        let cluster_impl = AccessControl::<_, 20, 4, 3>::new(&acl);
724        assert_eq!(cluster_impl.acl().borrow().len(), 0);
725        assert_eq!(<TestAcl as crate::config::Capacity>::PER_FABRIC, 4);
726        const {
727            assert!(
728                <TestAcl as crate::config::Capacity>::TOTAL
729                    >= <TestAcl as crate::config::Capacity>::PER_FABRIC * DefaultConfig::FABRICS
730            );
731        }
732    }
733}