matter_kit/clusters/joint_fabric_administrator.rs
1//! Joint Fabric Administrator, cluster `0x0753` (Core §11.25).
2//!
3//! The device side of §12.2.5's Joint Commissioning Method — the handshake by which one
4//! ecosystem's administrator gets a cross-signed ICAC from another's, so that both end up
5//! anchored to the same root.
6//!
7//! # Three commands, in one order, inside one fail-safe
8//!
9//! §11.25.6 is a sequence, and the sequence is the security:
10//!
11//! 1. `ICACCSRRequest` — "give me a certificate signing request for your intermediate CA". The
12//! server answers with a PKCS #10 CSR over a key it holds.
13//! 2. The anchor signs it, having first run §6.4.10's Vendor ID Verification and checked that
14//! the peer really is an administrator on its own fabric (§12.2.5 step 4).
15//! 3. `AddICAC` — "here is that ICAC, cross-signed". The server verifies the chain, the public
16//! key against the CSR it issued, and the DN.
17//!
18//! Every step of it is inside an armed fail-safe, and §11.25.6.1 and §11.25.6.3 both refuse
19//! outright without one: everything a Joint Fabric adds is undone if the commissioner walks
20//! away, and a half-joined fabric is one where two ecosystems disagree about who may administer
21//! what.
22//!
23//! # The public key check is the whole point of the CSR
24//!
25//! §11.25.6.3 step 2: "The public key of the ICAC SHALL match the public key present in the last
26//! ICACCSRResponse provided to the Administrator that sent the AddICAC command." Without it an
27//! anchor could hand back an ICAC over a key of *its* choosing, and the joining ecosystem would
28//! install an intermediate CA it does not hold the private key for — or worse, one the anchor
29//! does.
30//!
31//! # What is not here
32//!
33//! The anchor *transfer* commands (§11.25.6.6–§11.25.6.8) are accepted and reported: moving the
34//! anchor role between ecosystems needs user consent and a datastore quiesce, neither of which
35//! is this cluster's to decide. [`AnchorTransfer`] is what the application answers with.
36
37use core::cell::{Cell, RefCell};
38
39use crate::clusters::generated::joint_fabric_administrator as spec_jf;
40use crate::commissioning::failsafe::FailSafe;
41use crate::commissioning::window::CommissioningWindow;
42use crate::dm::spec::{Conforming, Optional};
43use crate::dm::{Resolved, ResolvedCommand};
44use crate::im::{
45 ClusterHandler, ClusterId, CommandId, EndpointId, InteractionContext, Status, StatusIb,
46};
47use crate::msg::FabricIndex;
48use crate::tlv::{Tag, TlvWriter, ToTlv};
49
50use super::Cluster;
51
52pub use spec_jf::attribute::ADMINISTRATOR_FABRIC_INDEX;
53pub use spec_jf::command::{
54 ADD_ICAC, ANNOUNCE_JOINT_FABRIC_ADMINISTRATOR, ICAC_RESPONSE, ICACCSR_REQUEST,
55 ICACCSR_RESPONSE, OPEN_JOINT_COMMISSIONING_WINDOW, TRANSFER_ANCHOR_COMPLETE,
56 TRANSFER_ANCHOR_REQUEST, TRANSFER_ANCHOR_RESPONSE,
57};
58pub use spec_jf::{
59 ICACCSRResponseStatusCodeEnum, ICACResponseStatusEnum, ID, PICS, REVISION,
60 TransferAnchorResponseStatusEnum,
61};
62
63/// §11.25.6.2's constraint on `ICACCSR`: "max 600".
64pub const ICACCSR_MAX: usize = 600;
65
66/// §11.25.6.3's constraint on `ICACValue`: "max 400".
67pub const ICAC_MAX: usize = 400;
68
69/// What the product does with the two halves of ICAC cross-signing.
70///
71/// Both are cryptography this cluster deliberately does not do itself: the key pair behind the
72/// CSR is the node's own intermediate CA key, which may live in a secure element, and validating
73/// a cross-signed ICAC is [`cert`](crate::cert)'s chain walk against a root only the application
74/// knows it has.
75pub trait JointFabricHooks {
76 /// §11.25.6.1: writes a PKCS #10 CSR for this node's intermediate CA key.
77 ///
78 /// Returns how many octets it wrote. §11.25.6.2 caps it at [`ICACCSR_MAX`].
79 fn write_icac_csr(&self, out: &mut [u8]) -> core::result::Result<usize, Status>;
80
81 /// §11.25.6.3's three checks, in the specification's own order.
82 ///
83 /// The order is what makes the two statuses meaningful: `InvalidPublicKey` says "this is not
84 /// the key I asked you to sign", and `InvalidICAC` says "this does not chain, or the DN is
85 /// wrong". Collapsing them would leave an administrator unable to tell a mis-signed
86 /// certificate from a mis-addressed one.
87 fn validate_icac(&self, icac: &[u8], fabric: FabricIndex) -> ICACResponseStatusEnum;
88
89 /// Installs a validated ICAC. §12.2.5: it becomes the intermediate every NOC this ecosystem
90 /// issues chains through.
91 fn install_icac(&self, icac: &[u8], fabric: FabricIndex) -> core::result::Result<(), Status>;
92
93 /// §11.25.6.6: whether this node will give up the anchor role right now.
94 ///
95 /// §11.25.4.2 gives two reasons it might not, and both are the application's: the datastore
96 /// is busy, or "User has not consented for Anchor Transfer".
97 fn anchor_transfer(&self) -> AnchorTransfer {
98 AnchorTransfer::Refused(TransferAnchorResponseStatusEnum::TransferAnchorStatusNoUserConsent)
99 }
100
101 /// §11.25.6.8: the transfer finished, and this node is no longer the anchor.
102 fn anchor_transferred(&self) {}
103
104 /// §11.25.6.9: a peer said where to find *its* Joint Fabric Administrator cluster.
105 fn administrator_announced(&self, endpoint: EndpointId) {
106 let _ = endpoint;
107 }
108}
109
110/// What §11.25.6.6 is answered with.
111#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112pub enum AnchorTransfer {
113 /// The node will transfer the anchor role.
114 Accepted,
115 /// It will not, and this is why.
116 Refused(TransferAnchorResponseStatusEnum),
117}
118
119/// The Joint Fabric Administrator cluster (§11.25).
120#[derive(Debug)]
121pub struct JointFabricAdministrator<'a, H: JointFabricHooks> {
122 hooks: &'a H,
123 /// The node's fail-safe: §11.25.6.1 and §11.25.6.3 both require one armed.
124 fail_safe: &'a RefCell<FailSafe>,
125 /// The node's commissioning window, which `OpenJointCommissioningWindow` opens.
126 window: &'a RefCell<CommissioningWindow>,
127 /// §11.25.5.1's `AdministratorFabricIndex`, null until a fabric is the Joint Fabric's.
128 administrator_fabric: Cell<Option<FabricIndex>>,
129 /// Whether a CSR has been issued in this fail-safe period, and to which fabric.
130 ///
131 /// §11.25.6.3 step 2 compares the ICAC's public key against "the last ICACCSRResponse
132 /// provided to the Administrator that sent the AddICAC command" — so the pairing is per
133 /// administrator, not per node.
134 csr_issued_to: Cell<Option<FabricIndex>>,
135 /// §11.25.6.1 and §11.25.6.3: "If a prior AddICAC command was successfully executed within
136 /// the fail-safe timer period, then this command SHALL fail with a CONSTRAINT_ERROR."
137 icac_added: Cell<bool>,
138}
139
140impl<'a, H: JointFabricHooks> JointFabricAdministrator<'a, H> {
141 /// The cluster on a node that is not yet part of a Joint Fabric.
142 #[must_use]
143 pub const fn new(
144 hooks: &'a H,
145 fail_safe: &'a RefCell<FailSafe>,
146 window: &'a RefCell<CommissioningWindow>,
147 ) -> Self {
148 Self {
149 hooks,
150 fail_safe,
151 window,
152 administrator_fabric: Cell::new(None),
153 csr_issued_to: Cell::new(None),
154 icac_added: Cell::new(false),
155 }
156 }
157
158 /// The descriptor for an instance, derived from the specification's tables.
159 pub fn conforming(
160 feature_map: u32,
161 optional: &Optional<'_>,
162 ) -> crate::error::Result<Conforming<1, 6, 3, 0>> {
163 Conforming::new(&spec_jf::CLUSTER, feature_map, optional)
164 }
165
166 /// `AdministratorFabricIndex` (§11.25.5.1), null when no fabric is the Joint Fabric's.
167 #[must_use]
168 pub fn administrator_fabric(&self) -> Option<FabricIndex> {
169 self.administrator_fabric.get()
170 }
171
172 /// Names the fabric this node administers the Joint Fabric through.
173 ///
174 /// §11.25.5.1: "the FabricIndex from the Endpoint 0's Operational Cluster Fabrics attribute
175 /// … which is associated with the JointFabric". Until it is set, §11.25.6.1 and §11.25.6.5
176 /// both refuse: there is no fabric to cross-sign into.
177 pub fn set_administrator_fabric(&self, fabric: Option<FabricIndex>) {
178 self.administrator_fabric.set(fabric);
179 }
180
181 /// Clears the per-fail-safe state, which a device does when the fail-safe expires or
182 /// `CommissioningComplete` runs.
183 ///
184 /// §11.25.6.1's `CONSTRAINT_ERROR` and §11.25.6.3's are both scoped to "within the fail-safe
185 /// timer period", so an abandoned attempt must not block the next one for ever.
186 pub fn reset_fail_safe_state(&self) {
187 self.csr_issued_to.set(None);
188 self.icac_added.set(false);
189 }
190
191 /// Whether a fail-safe is armed, which §11.25.6.1 and §11.25.6.3 both require.
192 fn fail_safe_armed(&self, ctx: &InteractionContext<'_>) -> bool {
193 self.fail_safe.borrow().is_armed(ctx.now)
194 }
195}
196
197impl<H: JointFabricHooks> ClusterHandler for JointFabricAdministrator<'_, H> {
198 fn read(
199 &self,
200 resolved: &Resolved<'_>,
201 _ctx: &InteractionContext<'_>,
202 w: &mut TlvWriter<'_>,
203 tag: Tag,
204 ) -> core::result::Result<(), Status> {
205 let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
206 match resolved.attribute {
207 ADMINISTRATOR_FABRIC_INDEX => match self.administrator_fabric.get() {
208 Some(fabric) => full(w.unsigned(tag, u64::from(fabric.0))),
209 // §11.25.5.1: "This field SHALL have the value of null if there is no fabric
210 // associated with the JointFabric."
211 None => full(w.null(tag)),
212 },
213 _ => Err(Status::UnsupportedAttribute),
214 }
215 }
216
217 fn invoke(
218 &self,
219 resolved: &ResolvedCommand<'_>,
220 fields: Option<&[u8]>,
221 ctx: &InteractionContext<'_>,
222 w: &mut TlvWriter<'_>,
223 tag: Tag,
224 ) -> core::result::Result<Option<CommandId>, StatusIb> {
225 let full = |r: crate::error::Result<()>| r.map_err(|_| StatusIb::from(Status::Failure));
226 match resolved.command.id {
227 ICACCSR_REQUEST => {
228 let status = self.icac_csr_request(ctx);
229 let mut buf = [0u8; ICACCSR_MAX];
230 let csr = match status {
231 ICACCSRResponseStatusCodeEnum::OK => {
232 let written = self.hooks.write_icac_csr(&mut buf)?;
233 let csr = buf
234 .get(..written)
235 .filter(|csr| csr.len() <= ICACCSR_MAX)
236 .ok_or(StatusIb::from(Status::Failure))?;
237 // Only now is the CSR "provided", so only now may §11.25.6.3's pairing
238 // be recorded: a refused request must not license an `AddICAC`.
239 self.csr_issued_to.set(ctx.fabric_index);
240 Some(csr)
241 }
242 _ => None,
243 };
244 full(
245 spec_jf::ICACCSRResponseFields {
246 status_code: status,
247 // §11.25.6.2: the field's conformance is "StatusCode == OK, O", so a
248 // failure carries no CSR at all rather than an empty one.
249 icaccsr: csr,
250 }
251 .to_tlv(w, tag),
252 )?;
253 Ok(Some(ICACCSR_RESPONSE))
254 }
255 ADD_ICAC => {
256 let payload = fields.ok_or(StatusIb::from(Status::InvalidCommand))?;
257 let decoded: spec_jf::AddICACFields<'_> = super::decode_fields(payload)?;
258 let status = self.add_icac(&decoded, ctx)?;
259 full(
260 spec_jf::ICACResponseFields {
261 status_code: status,
262 }
263 .to_tlv(w, tag),
264 )?;
265 Ok(Some(ICAC_RESPONSE))
266 }
267 OPEN_JOINT_COMMISSIONING_WINDOW => {
268 let payload = fields.ok_or(StatusIb::from(Status::InvalidCommand))?;
269 let decoded: spec_jf::OpenJointCommissioningWindowFields<'_> =
270 super::decode_fields(payload)?;
271 self.open_joint_window(&decoded, ctx)?;
272 Ok(None)
273 }
274 TRANSFER_ANCHOR_REQUEST => {
275 let status = match self.hooks.anchor_transfer() {
276 AnchorTransfer::Accepted => TransferAnchorResponseStatusEnum::OK,
277 AnchorTransfer::Refused(why) => why,
278 };
279 full(
280 spec_jf::TransferAnchorResponseFields {
281 status_code: status,
282 }
283 .to_tlv(w, tag),
284 )?;
285 Ok(Some(TRANSFER_ANCHOR_RESPONSE))
286 }
287 TRANSFER_ANCHOR_COMPLETE => {
288 self.hooks.anchor_transferred();
289 // §12.2.5: the anchor role has moved, so this node no longer administers the
290 // Joint Fabric through the fabric it named.
291 self.administrator_fabric.set(None);
292 Ok(None)
293 }
294 ANNOUNCE_JOINT_FABRIC_ADMINISTRATOR => {
295 let payload = fields.ok_or(StatusIb::from(Status::InvalidCommand))?;
296 let decoded: spec_jf::AnnounceJointFabricAdministratorFields =
297 super::decode_fields(payload)?;
298 self.hooks.administrator_announced(decoded.endpoint_id);
299 Ok(None)
300 }
301 _ => Err(Status::UnsupportedCommand.into()),
302 }
303 }
304}
305
306impl<H: JointFabricHooks> JointFabricAdministrator<'_, H> {
307 /// §11.25.6.1's preconditions, in the order the specification lists them.
308 ///
309 /// Each has its own cluster-specific status because each tells the administrator a different
310 /// thing to do: arm a fail-safe, run Vendor ID Verification, or set the fabric index first.
311 fn icac_csr_request(&self, ctx: &InteractionContext<'_>) -> ICACCSRResponseStatusCodeEnum {
312 if !self.fail_safe_armed(ctx) {
313 // A `FAILSAFE_REQUIRED` interaction-model status, not a cluster one — but the
314 // command has a response, so it is carried there. `Busy` is the closest the enum
315 // comes and §11.25.4.3 does not define a fail-safe code, so the refusal is the
316 // interaction model's; see `add_icac` for the same rule with a status code of its
317 // own.
318 return ICACCSRResponseStatusCodeEnum::Busy;
319 }
320 // "If the FabricFabric Table Vendor ID Verification Procedure has not been executed
321 // against the initiator of this command, the command SHALL fail with a JfVidNotVerified
322 // status code." The verification is §6.4.10's, run by the *peer* against this node's
323 // fabric, and the application records it.
324 if !ctx.vendor_id_verified {
325 return ICACCSRResponseStatusCodeEnum::VIDNotVerified;
326 }
327 if self.administrator_fabric.get().is_none() {
328 return ICACCSRResponseStatusCodeEnum::InvalidAdministratorFabricIndex;
329 }
330 // "If a prior AddICAC command was successfully executed within the fail-safe timer
331 // period, then this command SHALL fail with a CONSTRAINT_ERROR status code." One ICAC
332 // per fail-safe: a second CSR after a successful add would be a second intermediate CA
333 // for the same join.
334 if self.icac_added.get() {
335 return ICACCSRResponseStatusCodeEnum::Busy;
336 }
337 ICACCSRResponseStatusCodeEnum::OK
338 }
339
340 /// §11.25.6.3.
341 fn add_icac(
342 &self,
343 request: &spec_jf::AddICACFields<'_>,
344 ctx: &InteractionContext<'_>,
345 ) -> core::result::Result<ICACResponseStatusEnum, StatusIb> {
346 // "This command SHALL be received over a CASE session otherwise it SHALL fail with an
347 // INVALID_COMMAND status code." A PASE session has no accessing fabric, which is also
348 // what makes the ICAC un-addressable.
349 let Some(fabric) = ctx.fabric_index.filter(|f| f.0 != 0) else {
350 return Err(Status::InvalidCommand.into());
351 };
352 if !self.fail_safe_armed(ctx) {
353 return Err(Status::FailsafeRequired.into());
354 }
355 if self.icac_added.get() {
356 return Err(Status::ConstraintError.into());
357 }
358 if request.icac_value.len() > ICAC_MAX {
359 return Err(Status::ConstraintError.into());
360 }
361 // Step 2's pairing: the ICAC has to answer *this* administrator's CSR. Without a CSR
362 // there is nothing for its public key to match, so there is nothing to install.
363 if self.csr_issued_to.get() != Some(fabric) {
364 return Ok(ICACResponseStatusEnum::InvalidPublicKey);
365 }
366
367 let status = self.hooks.validate_icac(request.icac_value, fabric);
368 if status != ICACResponseStatusEnum::OK {
369 // "If any of the above validation checks fail, the server SHALL immediately respond
370 // to the client with an ICACResponse" — and nothing is installed.
371 return Ok(status);
372 }
373 self.hooks.install_icac(request.icac_value, fabric)?;
374 self.icac_added.set(true);
375 // §12.2.5: the fabric this ICAC was cross-signed into is the one the node now
376 // administers the Joint Fabric through.
377 self.administrator_fabric.set(Some(fabric));
378 Ok(ICACResponseStatusEnum::OK)
379 }
380
381 /// §11.25.6.5 — "an alias onto the OpenCommissioningWindow command".
382 fn open_joint_window(
383 &self,
384 request: &spec_jf::OpenJointCommissioningWindowFields<'_>,
385 ctx: &InteractionContext<'_>,
386 ) -> core::result::Result<(), StatusIb> {
387 // "This command SHALL fail with a InvalidAdministratorFabricIndex status code sent back
388 // to the initiator if the AdministratorFabricIndex attribute has the value of null."
389 // There would be no fabric for the joining ecosystem to be cross-signed into.
390 if self.administrator_fabric.get().is_none() {
391 return Err(StatusIb::cluster_failure(
392 ICACCSRResponseStatusCodeEnum::InvalidAdministratorFabricIndex.value(),
393 ));
394 }
395 // Everything else is §11.19.8.1's, unchanged — the alias is not a different window.
396 let admin = crate::clusters::administrator_commissioning::AdministratorCommissioning::new(
397 self.window,
398 self.fail_safe,
399 &|_| None,
400 );
401 admin.open_commissioning_window(
402 &crate::clusters::administrator_commissioning::OpenWindowRequest {
403 timeout_seconds: request.commissioning_timeout,
404 verifier: request.pake_passcode_verifier,
405 discriminator: request.discriminator,
406 iterations: request.iterations,
407 salt: request.salt,
408 },
409 ctx,
410 )
411 }
412}
413
414/// So a tuple of clusters can dispatch to it by id.
415impl<H: JointFabricHooks> Cluster for JointFabricAdministrator<'_, H> {
416 const ID: ClusterId = ID;
417}