Skip to main content

matter_kit/dm/
access.rs

1//! Access qualities: who may read, write and invoke what (Core §7.6, §6.6.1).
2//!
3//! Every attribute, command and event declares what kind of access it supports and the
4//! **lowest** privilege that suffices. §7.6: "Elements SHALL only include the lowest required
5//! privilege for a type of access", because a higher privilege implicitly grants every lower
6//! one — §6.6.1: "When a Node is granted a particular privilege, it is also implicitly
7//! granted all logically lower privilege levels as well."
8//!
9//! That ordering is why [`Privilege`] is `Ord` and why [`Privilege::grants`] exists: a check
10//! is a comparison, not a set membership test.
11//!
12//! # The defaults are not "none"
13//!
14//! §7.6 gives every element an access quality whether or not the cluster wrote one down:
15//!
16//! > Attributes, commands, and events that do not define any privileges as access qualities
17//! > SHALL be deemed to have the following: View privilege required for Read access, Operate
18//! > privilege required for Write access, Operate privilege required for Invoke access for
19//! > request commands.
20//!
21//! So [`Access::default`] is `R V` — readable at View — and [`Access::read_write`] is `RW VO`,
22//! which is what "an attribute with access 'RW'" means. Getting this wrong in the permissive
23//! direction would expose an attribute the cluster never meant to be writable.
24
25/// An access-control privilege (§6.6.1, §7.6.6–7.6.9).
26///
27/// Ordered from least to most: a subject granted one is granted every lower one.
28/// `ProxyView` sits below `View` and exists for proxies, which need to see a node's shape
29/// without being able to read its data.
30#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
31pub enum Privilege {
32    /// Enough to observe a node through a proxy, and nothing more.
33    ProxyView,
34    /// "SHALL support Read (if readable) and Invoke (if invocable) access" (§7.6.6).
35    View,
36    /// Adds Write (§7.6.7).
37    Operate,
38    /// Adds configuration (§7.6.8).
39    Manage,
40    /// Everything, including the Access Control cluster itself (§7.6.9).
41    Administer,
42}
43
44impl Privilege {
45    /// Whether holding `self` grants `required`.
46    ///
47    /// §6.6.1's subsumption rule — with the one exception that makes it not quite a
48    /// comparison. §9.10.5.2's chain runs View ← Operate ← Manage ← Administer, and
49    /// `ProxyView` is **outside it**: §6.6.6.2's `add_granted_privilege` expands Operate,
50    /// Manage and Administer downward to View and never mentions ProxyView, so nothing grants
51    /// it but itself and it grants nothing else.
52    ///
53    /// Treating the five as totally ordered would hand every `View` holder a privilege the
54    /// specification never gives them — quietly, and in the permissive direction. The `Ord`
55    /// derive still orders them for convenience; this is the access decision, and
56    /// [`Acl::granted`](crate::acl::Acl::granted) agrees with it.
57    #[must_use]
58    pub const fn grants(self, required: Self) -> bool {
59        match (self, required) {
60            (Self::ProxyView, Self::ProxyView) => true,
61            (Self::ProxyView, _) | (_, Self::ProxyView) => false,
62            _ => (self as u8) >= (required as u8),
63        }
64    }
65}
66
67bitflags::bitflags! {
68    /// The fabric and timing qualities of §7.6's Access column.
69    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
70    pub struct AccessQualities: u8 {
71        /// `F` — fabric-scoped: the data belongs to one fabric (§7.5.3).
72        const FABRIC_SCOPED = 1 << 0;
73        /// `S` — fabric-sensitive: other fabrics' entries are hidden, not merely filtered
74        /// (§7.6.5).
75        const FABRIC_SENSITIVE = 1 << 1;
76        /// `T` — "Write Access or Invoke Access with timed interaction only" (§8.7).
77        const TIMED = 1 << 2;
78        /// `L` — Large Message: §7.7.5 says such an element "SHALL require TCP for
79        /// communication", and §8.8.2.3 step b.iv makes invoking one over UDP
80        /// [`INVALID_TRANSPORT_TYPE`](crate::im::Status::InvalidTransportType).
81        const LARGE = 1 << 3;
82    }
83}
84
85/// What an element supports and what it costs (§7.6).
86#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
87pub struct Access {
88    /// The privilege a read needs, or `None` if the element is not readable.
89    pub read: Option<Privilege>,
90    /// The privilege a write needs, or `None` if the element is not writable.
91    pub write: Option<Privilege>,
92    /// The privilege an invoke needs, for a command.
93    pub invoke: Option<Privilege>,
94    /// The fabric and timing qualities.
95    pub qualities: AccessQualities,
96}
97
98impl Default for Access {
99    /// `R V` — §7.6's default for an element that declares nothing.
100    fn default() -> Self {
101        Self::read_only(Privilege::View)
102    }
103}
104
105impl Access {
106    /// `R <privilege>` — readable and not writable.
107    #[must_use]
108    pub const fn read_only(privilege: Privilege) -> Self {
109        Self {
110            read: Some(privilege),
111            write: None,
112            invoke: None,
113            qualities: AccessQualities::empty(),
114        }
115    }
116
117    /// `RW VO` — §7.6's reading of "an attribute with access 'RW'".
118    #[must_use]
119    pub const fn read_write() -> Self {
120        Self {
121            read: Some(Privilege::View),
122            write: Some(Privilege::Operate),
123            invoke: None,
124            qualities: AccessQualities::empty(),
125        }
126    }
127
128    /// `RW` with explicit privileges.
129    #[must_use]
130    pub const fn read_write_with(read: Privilege, write: Privilege) -> Self {
131        Self {
132            read: Some(read),
133            write: Some(write),
134            invoke: None,
135            qualities: AccessQualities::empty(),
136        }
137    }
138
139    /// `W <privilege>` — writable and not readable.
140    #[must_use]
141    pub const fn write_only(privilege: Privilege) -> Self {
142        Self {
143            read: None,
144            write: Some(privilege),
145            invoke: None,
146            qualities: AccessQualities::empty(),
147        }
148    }
149
150    /// An invocable command. §7.6's default for a request command is Operate.
151    #[must_use]
152    pub const fn invoke(privilege: Privilege) -> Self {
153        Self {
154            read: None,
155            write: None,
156            invoke: Some(privilege),
157            qualities: AccessQualities::empty(),
158        }
159    }
160
161    /// The same access with extra qualities.
162    #[must_use]
163    pub const fn with_qualities(mut self, qualities: AccessQualities) -> Self {
164        self.qualities = qualities;
165        self
166    }
167
168    /// Whether the element can be read at all.
169    #[must_use]
170    pub const fn is_readable(&self) -> bool {
171        self.read.is_some()
172    }
173
174    /// Whether the element can be written at all.
175    #[must_use]
176    pub const fn is_writable(&self) -> bool {
177        self.write.is_some()
178    }
179
180    /// Whether a write or invoke requires a Timed interaction (§8.7).
181    #[must_use]
182    pub const fn needs_timed(&self) -> bool {
183        self.qualities.contains(AccessQualities::TIMED)
184    }
185
186    /// Whether the element is fabric-scoped.
187    #[must_use]
188    pub const fn is_fabric_scoped(&self) -> bool {
189        self.qualities.contains(AccessQualities::FABRIC_SCOPED)
190    }
191
192    /// Whether the element is fabric-sensitive.
193    #[must_use]
194    pub const fn is_fabric_sensitive(&self) -> bool {
195        self.qualities.contains(AccessQualities::FABRIC_SENSITIVE)
196    }
197
198    /// Whether the element requires a transport that can carry Large Messages (§7.7.5).
199    #[must_use]
200    pub const fn needs_large_messages(&self) -> bool {
201        self.qualities.contains(AccessQualities::LARGE)
202    }
203}
204
205#[cfg(test)]
206mod tests {
207    use super::*;
208
209    #[test]
210    fn a_higher_privilege_grants_every_lower_one() {
211        // §6.6.1: "When a Node is granted a particular privilege, it is also implicitly
212        // granted all logically lower privilege levels as well." §9.10.5.2 gives the chain,
213        // which is the four privileges other than ProxyView.
214        let chain = [
215            Privilege::View,
216            Privilege::Operate,
217            Privilege::Manage,
218            Privilege::Administer,
219        ];
220        for (i, held) in chain.iter().enumerate() {
221            for (j, required) in chain.iter().enumerate() {
222                assert_eq!(
223                    held.grants(*required),
224                    i >= j,
225                    "{held:?} granting {required:?}"
226                );
227            }
228        }
229    }
230
231    #[test]
232    fn proxy_view_is_outside_the_chain_in_both_directions() {
233        // §6.6.6.2's `add_granted_privilege` expands Operate, Manage and Administer down to
234        // View and never mentions ProxyView. So Administer does not carry it — and it does
235        // not carry View either, which is the half a "lowest privilege" reading gets wrong.
236        for other in [
237            Privilege::View,
238            Privilege::Operate,
239            Privilege::Manage,
240            Privilege::Administer,
241        ] {
242            assert!(!other.grants(Privilege::ProxyView), "{other:?} → ProxyView");
243            assert!(!Privilege::ProxyView.grants(other), "ProxyView → {other:?}");
244        }
245        assert!(Privilege::ProxyView.grants(Privilege::ProxyView));
246    }
247
248    #[test]
249    fn administer_grants_a_view_level_read() {
250        // The case a set-of-privileges design gets wrong by forgetting to expand.
251        assert!(Privilege::Administer.grants(Privilege::View));
252        assert!(!Privilege::View.grants(Privilege::Administer));
253    }
254
255    #[test]
256    fn the_defaults_are_the_ones_7_6_states() {
257        // "An event with implicit read access or explicit 'R' access defaults to access
258        // 'R V'. An attribute with access 'RW' defaults to access 'RW VO'."
259        assert_eq!(Access::default().read, Some(Privilege::View));
260        assert_eq!(Access::default().write, None, "a default is not writable");
261
262        let rw = Access::read_write();
263        assert_eq!(rw.read, Some(Privilege::View));
264        assert_eq!(rw.write, Some(Privilege::Operate));
265    }
266
267    #[test]
268    fn a_write_only_attribute_is_not_readable() {
269        // §8.4.3.2: a read of one is UNSUPPORTED_READ, which needs this to be expressible.
270        let access = Access::write_only(Privilege::Manage);
271        assert!(!access.is_readable());
272        assert!(access.is_writable());
273    }
274
275    #[test]
276    fn the_large_message_quality_is_its_own_thing() {
277        // §7.7.5: an `L` element "SHALL require TCP for communication". It is independent of
278        // privilege — an administrator still cannot invoke one over UDP.
279        let access = Access::invoke(Privilege::Administer).with_qualities(AccessQualities::LARGE);
280        assert!(access.needs_large_messages());
281        assert!(!access.needs_timed());
282        assert_eq!(access.invoke, Some(Privilege::Administer));
283    }
284
285    #[test]
286    fn qualities_are_independent_of_privileges() {
287        let access = Access::read_write()
288            .with_qualities(AccessQualities::FABRIC_SCOPED | AccessQualities::TIMED);
289        assert!(access.is_fabric_scoped());
290        assert!(access.needs_timed());
291        assert!(!access.is_fabric_sensitive());
292        assert_eq!(access.read, Some(Privilege::View), "unchanged");
293    }
294}