matter_kit/jf.rs
1//! Joint Fabric: two ecosystems, one root of trust (Core ch. 12).
2//!
3//! Needs the `rustcrypto` feature: the certificates are [`cert`](crate::cert)'s.
4//!
5//! Ordinarily two ecosystems on the same device are two *fabrics*: two roots, two sets of
6//! operational certificates, two access-control lists, and a device that has to hold both.
7//! §12.2 is the alternative. Both ecosystems' intermediate CAs are cross-signed by one **Anchor
8//! CA**, so every node they commission chains to the same root — and an administrator of either
9//! ecosystem can administer any of it.
10//!
11//! > The joint operation ensures that ICA's from both Fabric A and Fabric B are signed by the
12//! > Anchor CA … establishing a common trust between all devices of the original Fabric A and
13//! > Fabric B and all newly added devices to the "Joint Fabric".
14//!
15//! # The two tags are the whole access model
16//!
17//! A Joint Fabric does not name administrators by Node ID — there may be many of them, from
18//! several companies, and the set changes. It names them by
19//! [`CaseAuthenticatedTag`], and §12.2.4 reserves two
20//! identifiers for it:
21//!
22//! * the **Administrator CAT** (`0xFFFF`): every device on a Joint Fabric "SHALL contain an ACL
23//! entry granting Administer privilege to CaseSubjectAdmin set to the Administrator CAT";
24//! * the **Anchor CAT** (`0xFFFE`), which does the same one level up — it is what restricts
25//! Administer *on an administrator* to the anchor.
26//!
27//! # Revocation is a version bump, and it is meant to hurt
28//!
29//! §12.2.4.1 is unusually candid about the cost:
30//!
31//! > The Joint Fabric Anchor Administrator SHALL increment the version number of the
32//! > Administrator CAT … update the existing credentials (NOC) for all Administrator Nodes that
33//! > are NOT being revoked … and update the ACL entry of all Nodes whose subject list contains
34//! > the prior version … Completing this operation requires visiting all the nodes in the Joint
35//! > Fabric, a task which might take a long time to complete or might never complete if some
36//! > Nodes are permanently offline.
37//!
38//! [`Revocation`] is that walk, as a value: which nodes still hold the old version, and whether
39//! the anchor is done. A device is *not* safe until its ACL has moved, so an implementation that
40//! reported success on the first successful write would be reporting the opposite of the truth.
41
42use crate::cert::dn::DnAttributeKind;
43use crate::error::{Error, ErrorCode, Result, bail};
44use crate::msg::{CaseAuthenticatedTag, NodeId};
45
46/// §12.2.3: the Anchor ICAC "SHALL contain the reserved org-unit-name attribute … with value
47/// `jf-anchor-icac` in its Subject DN".
48///
49/// It is the marker that says an intermediate CA is *the* anchor's rather than merely one the
50/// anchor signed, and §12.2.5 has a commissioner check for it before trusting a peer to act as
51/// the Joint Fabric's anchor.
52pub const ANCHOR_ICAC_OU: &str = "jf-anchor-icac";
53
54/// §12.2.2's ceiling on a newly allocated Node ID: "less than 0xFFFF_FFEF_FFFF_FFFF".
55pub const NODE_ID_MAX: u64 = 0xFFFF_FFEE_FFFF_FFFF;
56
57/// The pair of tags a Joint Fabric is administered through (§12.2.4).
58///
59/// Both carry a version, and the version is what makes them revocable: §12.2.4.1's walk. They
60/// are constructed rather than defaulted because the version is fabric state — a fabric that has
61/// revoked twice is on version 3, and a node still holding version 1 is one that was missed.
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub struct JointFabricTags {
64 /// §12.2.4.1's Administrator CAT: every node on the fabric grants Administer to it.
65 pub administrator: CaseAuthenticatedTag,
66 /// §12.2.4.2's Anchor CAT: every *administrator* grants Administer to it.
67 pub anchor: CaseAuthenticatedTag,
68}
69
70impl JointFabricTags {
71 /// The two tags at `version`.
72 ///
73 /// §6.6.2.1.2: "A version number of 0 is invalid", so version 0 is refused rather than
74 /// silently producing a tag no access-control entry would ever match.
75 pub const fn new(version: u16) -> Result<Self> {
76 if version == 0 {
77 bail!(InvalidArgument)
78 }
79 Ok(Self {
80 administrator: CaseAuthenticatedTag::new(
81 CaseAuthenticatedTag::ADMINISTRATOR_IDENTIFIER,
82 version,
83 ),
84 anchor: CaseAuthenticatedTag::new(CaseAuthenticatedTag::ANCHOR_IDENTIFIER, version),
85 })
86 }
87
88 /// Whether `tag` is this fabric's Administrator CAT, at this exact version.
89 ///
90 /// The version matters: §12.2.4.1's revocation works by leaving a stale version behind, so a
91 /// check that compared only the identifier would keep honouring the administrator the anchor
92 /// had just revoked.
93 #[must_use]
94 pub fn grants_administrator(&self, tag: CaseAuthenticatedTag) -> bool {
95 tag == self.administrator
96 }
97
98 /// Whether `tag` is this fabric's Anchor CAT, at this exact version.
99 #[must_use]
100 pub fn grants_anchor(&self, tag: CaseAuthenticatedTag) -> bool {
101 tag == self.anchor
102 }
103
104 /// The tags after §12.2.4.1's revocation step.
105 ///
106 /// "increment the version number of the Administrator CAT to a value higher than its current
107 /// value (e.g., from 0x0000 to 0x0001)". A fabric that has exhausted the 16-bit version has
108 /// no way left to revoke, which is a state to report rather than to wrap through: wrapping
109 /// would re-authorise whoever held version 1.
110 pub const fn revoked(&self) -> Result<Self> {
111 let Some(next) = self.administrator.version().checked_add(1) else {
112 bail!(NoSpace)
113 };
114 Self::new(next)
115 }
116}
117
118/// Whether a Node ID may be allocated on a Joint Fabric (§12.2.2).
119///
120/// > be greater than 0x0000_0000_0000_0000, but less than 0xFFFF_FFEF_FFFF_FFFF, representing a
121/// > value within the Operational NodeID range … be checked to ensure its uniqueness in the
122/// > NodeList attribute.
123///
124/// Uniqueness is the caller's — it needs the datastore — but the range is not, and a
125/// commissioner that allocated outside it would issue a NOC no node could use as an
126/// operational identity.
127#[must_use]
128pub fn is_allocatable(node: NodeId) -> bool {
129 node.0 > 0 && node.0 < NODE_ID_MAX.saturating_add(1)
130}
131
132/// §12.2.4.1's revocation walk: the part that cannot be done in one command.
133///
134/// Constructed with every node whose ACL or NOC still names the old version, and ticked off as
135/// each is updated. [`is_complete`](Self::is_complete) is the only thing that may be reported as
136/// success — and §12.2.4.1 says outright that it may never arrive, because "some Nodes are
137/// permanently offline or otherwise unreachable".
138#[derive(Debug)]
139pub struct Revocation<const N: usize> {
140 tags: JointFabricTags,
141 outstanding: heapless::Vec<NodeId, N>,
142}
143
144impl<const N: usize> Revocation<N> {
145 /// Begins a revocation: the new tags, and every node that has to be visited.
146 ///
147 /// `nodes` is the whole fabric, administrators included — §12.2.4.1 updates NOCs *and* ACL
148 /// entries, and a node whose ACL still lists the old Administrator CAT is a node the revoked
149 /// administrator can still administer.
150 pub fn begin(
151 previous: &JointFabricTags,
152 nodes: impl IntoIterator<Item = NodeId>,
153 ) -> Result<Self> {
154 let tags = previous.revoked()?;
155 let mut outstanding = heapless::Vec::new();
156 for node in nodes {
157 outstanding
158 .push(node)
159 .map_err(|_| Error::new(ErrorCode::NoSpace))?;
160 }
161 Ok(Self { tags, outstanding })
162 }
163
164 /// The tags every node is being moved to.
165 #[must_use]
166 pub const fn tags(&self) -> &JointFabricTags {
167 &self.tags
168 }
169
170 /// Records that one node now holds the new version.
171 ///
172 /// Returns whether it was one that still owed the update — a second report for the same node
173 /// is not progress, and counting it would let a retry loop declare the fabric safe.
174 pub fn updated(&mut self, node: NodeId) -> bool {
175 let before = self.outstanding.len();
176 self.outstanding.retain(|n| *n != node);
177 self.outstanding.len() != before
178 }
179
180 /// The nodes that have not been reached yet.
181 #[must_use]
182 pub fn outstanding(&self) -> &[NodeId] {
183 &self.outstanding
184 }
185
186 /// Whether every node has moved, and the revocation has actually taken effect.
187 #[must_use]
188 pub fn is_complete(&self) -> bool {
189 self.outstanding.is_empty()
190 }
191}
192
193/// Whether a certificate's Subject DN marks it as the Anchor ICAC (§12.2.3).
194///
195/// `subject` is the decoded DN, as [`cert`](crate::cert) produces it. The check is on the
196/// *Subject*, not the issuer: an ICAC the anchor signed is not the anchor's own.
197pub fn is_anchor_icac<'a>(subject: impl IntoIterator<Item = (DnAttributeKind, &'a [u8])>) -> bool {
198 subject.into_iter().any(|(kind, value)| {
199 kind == DnAttributeKind::OrgUnitName && value == ANCHOR_ICAC_OU.as_bytes()
200 })
201}
202
203#[cfg(test)]
204mod tests {
205 use super::*;
206
207 #[test]
208 fn the_two_tags_use_the_reserved_identifiers() {
209 // §12.2.4: 0xFFFF and 0xFFFE are reserved to the Joint Fabric precisely so that an
210 // ecosystem cannot have allocated them for something else.
211 let tags = JointFabricTags::new(1).expect("version 1");
212 assert_eq!(tags.administrator.identifier(), 0xFFFF);
213 assert_eq!(tags.anchor.identifier(), 0xFFFE);
214 assert_eq!(tags.administrator.version(), 1);
215 assert!(tags.administrator.is_valid());
216 }
217
218 #[test]
219 fn version_zero_is_not_a_tag() {
220 // §6.6.2.1.2: "A version number of 0 is invalid." A tag at version 0 would match no
221 // access-control entry, so a fabric built on one would be an administrator nobody obeys.
222 assert!(JointFabricTags::new(0).is_err());
223 }
224
225 #[test]
226 fn revocation_leaves_the_old_version_behind() {
227 // §12.2.4.1: revoking is incrementing, and the *old* version is what stops working —
228 // which is why a check on the identifier alone would revoke nobody.
229 let before = JointFabricTags::new(1).expect("v1");
230 let after = before.revoked().expect("v2");
231 assert_eq!(after.administrator.version(), 2);
232 assert!(!after.grants_administrator(before.administrator));
233 assert!(after.grants_administrator(after.administrator));
234 assert!(!after.grants_anchor(before.anchor));
235 }
236
237 #[test]
238 fn a_fabric_that_has_run_out_of_versions_says_so() {
239 // Wrapping would re-authorise whoever still held version 1, which is the opposite of
240 // what the operation is for.
241 let last = JointFabricTags::new(u16::MAX).expect("v65535");
242 assert!(last.revoked().is_err());
243 }
244
245 #[test]
246 fn the_node_id_range_excludes_both_ends() {
247 // §12.2.2, and Table 4's operational range: 0 is unspecified and the top of the space is
248 // reserved for group, CAT and PAKE identifiers.
249 assert!(!is_allocatable(NodeId(0)));
250 assert!(is_allocatable(NodeId(1)));
251 assert!(is_allocatable(NodeId(NODE_ID_MAX)));
252 assert!(!is_allocatable(NodeId(0xFFFF_FFEF_FFFF_FFFF)));
253 assert!(!is_allocatable(NodeId(u64::MAX)));
254 }
255
256 #[test]
257 fn the_anchor_marker_is_on_the_subject() {
258 assert!(is_anchor_icac([(
259 DnAttributeKind::OrgUnitName,
260 ANCHOR_ICAC_OU.as_bytes()
261 )]));
262 // An ICAC with some other organisational unit is one the anchor signed, not the
263 // anchor's own — and §12.2.5 has a commissioner refuse to treat it as the anchor.
264 assert!(!is_anchor_icac([(
265 DnAttributeKind::OrgUnitName,
266 b"Acme Lighting".as_slice()
267 )]));
268 // And the value on the wrong attribute proves nothing.
269 assert!(!is_anchor_icac([(
270 DnAttributeKind::CommonName,
271 ANCHOR_ICAC_OU.as_bytes()
272 )]));
273 }
274
275 #[test]
276 fn a_revocation_is_only_complete_when_every_node_has_moved() {
277 // §12.2.4.1: the walk "might take a long time to complete or might never complete".
278 // Reporting success on the first write would report the opposite of the truth.
279 let before = JointFabricTags::new(1).expect("v1");
280 let nodes = [NodeId(1), NodeId(2), NodeId(3)];
281 let mut walk = Revocation::<8>::begin(&before, nodes).expect("begin");
282 assert_eq!(walk.tags().administrator.version(), 2);
283 assert!(!walk.is_complete());
284
285 assert!(walk.updated(NodeId(2)));
286 // A second report for the same node is not progress.
287 assert!(!walk.updated(NodeId(2)));
288 assert_eq!(walk.outstanding(), &[NodeId(1), NodeId(3)]);
289 assert!(!walk.is_complete());
290
291 assert!(walk.updated(NodeId(1)));
292 assert!(walk.updated(NodeId(3)));
293 assert!(walk.is_complete());
294 }
295}