matter_kit/clusters/commissioner_control.rs
1//! Commissioner Control, cluster `0x0751` (Core §11.26) — Fabric Synchronization's front door.
2//!
3//! > The Commissioner Control Cluster supports the ability for clients to request the
4//! > commissioning of themselves or other nodes onto a fabric which the cluster server can
5//! > commission onto. An example use case is ecosystem to ecosystem Fabric Synchronization
6//! > setup.
7//!
8//! Two ecosystems, and a householder who has a light in one and wants it in the other. The
9//! usual answer is to commission the light twice, which means the light holds two fabrics and
10//! the user does the work. Fabric Synchronization is the other answer: the ecosystems talk to
11//! each other, and one asks the other to open a commissioning window on a node it already has.
12//!
13//! # Three commands and a deliberate pause between them
14//!
15//! §11.26.6 splits what could have been one command into two, and says why:
16//!
17//! > This is required to be a separate step in order to provide the server time for interacting
18//! > with a user before informing the client that the CommissionNode operation may be
19//! > successful.
20//!
21//! So `RequestCommissioningApproval` always answers `SUCCESS` — it is a *question*, not an
22//! action — and the real answer arrives later as a `CommissioningRequestResult` event. Only
23//! then does the client send `CommissionNode`, and the server answers by invoking
24//! `ReverseOpenCommissioningWindow` back at it.
25//!
26//! The direction reversal is the point: the *server* of this cluster ends up as the
27//! commissioner, and the client as the thing that opens a window. §11.26.6.8 is explicit that
28//! the reverse command "is an alias onto the OpenCommissioningWindow command within the
29//! Administrator Commissioning Cluster".
30//!
31//! # Both commands are CASE-only
32//!
33//! §11.26.6.1 and §11.26.6.5: "If the command is not executed via a CASE session, the command
34//! SHALL fail with a status code of UNSUPPORTED_ACCESS." A request over PASE would come from
35//! something that has not yet proved which fabric it is on — and the whole flow turns on the
36//! server being able to match a later `CommissionNode` to the *same* node on the *same* fabric.
37
38use core::cell::{Cell, RefCell};
39
40use crate::clusters::generated::commissioner_control as spec_cctrl;
41use crate::dm::spec::{Conforming, Optional};
42use crate::dm::{Resolved, ResolvedCommand};
43use crate::im::{ClusterHandler, ClusterId, CommandId, InteractionContext, Status, StatusIb};
44use crate::msg::{FabricIndex, NodeId, VendorId};
45use crate::tlv::{Tag, TlvWriter, ToTlv};
46
47use super::Cluster;
48
49pub use spec_cctrl::attribute::SUPPORTED_DEVICE_CATEGORIES;
50pub use spec_cctrl::command::{
51 COMMISSION_NODE, REQUEST_COMMISSIONING_APPROVAL, REVERSE_OPEN_COMMISSIONING_WINDOW,
52};
53pub use spec_cctrl::event::COMMISSIONING_REQUEST_RESULT;
54pub use spec_cctrl::{ID, PICS, REVISION, SupportedDeviceCategoryBitmap};
55
56/// §11.26.6.1's constraint on `Label`: "max 64".
57pub const LABEL_MAX: usize = 64;
58
59/// One outstanding approval request.
60///
61/// §11.26.6.5 makes the triple load-bearing: "The server SHALL return FAILURE if the
62/// CommissionNode command is not sent from the same NodeID and on the same fabric as the
63/// RequestCommissioningApproval or if the provided RequestID ... does not match."
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub struct Request {
66 /// The client's own identifier for this request.
67 pub request_id: u64,
68 /// Which node asked.
69 pub client_node_id: NodeId,
70 /// On which fabric.
71 pub fabric: FabricIndex,
72 /// The vendor of the device the client wants commissioned — matched against the Basic
73 /// Information of whatever turns up (§11.26.6.8).
74 pub vendor_id: VendorId,
75 /// Its product id.
76 pub product_id: u16,
77 /// Whether the server has decided yet.
78 pub approved: Option<bool>,
79}
80
81/// What the server tells the client when its decision is ready (§11.26.7.1).
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub enum Decision {
84 /// "the server is ready to begin commissioning the requested device".
85 Approved,
86 /// "the server timed out due to user inaction".
87 TimedOut,
88 /// Anything else.
89 Refused,
90}
91
92impl Decision {
93 /// The `StatusCode` §11.26.7.3 puts in the event.
94 #[must_use]
95 pub const fn status(self) -> Status {
96 match self {
97 Self::Approved => Status::Success,
98 Self::TimedOut => Status::Timeout,
99 Self::Refused => Status::Failure,
100 }
101 }
102}
103
104/// An event this cluster produced, for the device to record in its own store (§7.14).
105#[derive(Debug, Clone, Copy, PartialEq, Eq)]
106pub struct CommissioningRequestResult {
107 /// Matches the `RequestID` the client sent.
108 pub request_id: u64,
109 /// The node that sent it.
110 pub client_node_id: NodeId,
111 /// What the server decided.
112 pub decision: Decision,
113}
114
115/// What the window a `ReverseOpenCommissioningWindow` asks the client to open (§11.26.6.8).
116///
117/// Every field is `OpenCommissioningWindow`'s — §11.26.6.8 says so: "This is an alias onto the
118/// OpenCommissioningWindow command within the Administrator Commissioning Cluster."
119#[derive(Debug, Clone, Copy)]
120pub struct Window<'a> {
121 /// How long the window stays open, in seconds.
122 pub commissioning_timeout: u16,
123 /// §11.19.8.1's 97-octet PAKE verifier.
124 pub pake_passcode_verifier: &'a [u8],
125 /// The 12-bit discriminator (§5.1.1.3).
126 pub discriminator: u16,
127 /// PBKDF iterations, 1000 to 100000.
128 pub iterations: u32,
129 /// The salt, 16 to 32 octets.
130 pub salt: &'a [u8],
131}
132
133/// §11.19.8.1's constraint on `PAKEPasscodeVerifier`: exactly 97 octets.
134pub const VERIFIER_LEN: usize = 97;
135
136/// What the product decides about a request.
137pub trait CommissionerControlHooks {
138 /// §11.26.6.1: a client would like a device commissioned.
139 ///
140 /// > The server MAY request approval from the user, but it is not required.
141 ///
142 /// Whatever this returns, the *command* answers `SUCCESS` — §11.26.6.1 requires it. The
143 /// decision reaches the client as a `CommissioningRequestResult` event, which is exactly
144 /// the separation the two-step flow exists for: asking a person takes longer than a
145 /// command may.
146 fn requested(&self, request: &Request);
147
148 /// §11.26.6.5: the client is ready, so open a window on the node it named.
149 ///
150 /// The server is about to become the *commissioner*; this returns the window parameters it
151 /// wants the client to open. `None` refuses.
152 fn window(&self, request: &Request) -> Option<Window<'_>>;
153}
154
155/// Commissioner Control over a node that can commission others.
156#[derive(Debug)]
157pub struct CommissionerControl<'a, H: CommissionerControlHooks, const N: usize = 4> {
158 hooks: &'a H,
159 categories: SupportedDeviceCategoryBitmap,
160 pending: RefCell<heapless::Vec<Request, N>>,
161 events: RefCell<heapless::Vec<CommissioningRequestResult, N>>,
162 /// The window the last `CommissionNode` produced, for the caller to send.
163 reverse: Cell<bool>,
164}
165
166impl<'a, H: CommissionerControlHooks, const N: usize> CommissionerControl<'a, H, N> {
167 /// A cluster over `hooks`, advertising `categories`.
168 #[must_use]
169 pub fn new(hooks: &'a H, categories: SupportedDeviceCategoryBitmap) -> Self {
170 Self {
171 hooks,
172 categories,
173 pending: RefCell::new(heapless::Vec::new()),
174 events: RefCell::new(heapless::Vec::new()),
175 reverse: Cell::new(false),
176 }
177 }
178
179 /// The descriptor for an instance, derived from the specification's tables.
180 pub fn conforming(
181 feature_map: u32,
182 optional: &Optional<'_>,
183 ) -> crate::error::Result<Conforming<1, 2, 1, 1>> {
184 Conforming::new(&spec_cctrl::CLUSTER, feature_map, optional)
185 }
186
187 /// `SupportedDeviceCategories` (§11.26.5.1).
188 #[must_use]
189 pub const fn categories(&self) -> SupportedDeviceCategoryBitmap {
190 self.categories
191 }
192
193 /// The requests this server has not yet answered.
194 #[must_use]
195 pub fn pending(&self) -> core::cell::Ref<'_, heapless::Vec<Request, N>> {
196 self.pending.borrow()
197 }
198
199 /// Records the server's decision about a request, producing §11.26.7.1's event.
200 ///
201 /// Separate from the command because the decision may take a person: §11.26.6.1 is explicit
202 /// that the two-step flow exists "to provide the server time for interacting with a user".
203 pub fn decide(&self, request_id: u64, client: NodeId, decision: Decision) -> bool {
204 let mut pending = self.pending.borrow_mut();
205 let Some(request) = pending
206 .iter_mut()
207 .find(|r| r.request_id == request_id && r.client_node_id == client)
208 else {
209 return false;
210 };
211 request.approved = Some(decision == Decision::Approved);
212 drop(pending);
213 let mut events = self.events.borrow_mut();
214 if events.is_full() {
215 events.remove(0);
216 }
217 let _ = events.push(CommissioningRequestResult {
218 request_id,
219 client_node_id: client,
220 decision,
221 });
222 true
223 }
224
225 /// Takes the event records the cluster has produced.
226 pub fn take_events(&self) -> heapless::Vec<CommissioningRequestResult, N> {
227 core::mem::take(&mut self.events.borrow_mut())
228 }
229
230 /// Whether the last `CommissionNode` asked the caller to send a
231 /// `ReverseOpenCommissioningWindow` back to the client.
232 ///
233 /// §11.26.6's command table marks that one `server ⇒ client`: it is not a *response*, it is
234 /// a command the server invokes on the client over the same CASE session. So the interaction
235 /// model's response machinery cannot carry it, and the caller sends it — which is also why
236 /// it is the one command here this cluster does not answer with itself.
237 #[must_use]
238 pub fn reverse_pending(&self) -> bool {
239 self.reverse.replace(false)
240 }
241
242 /// Forgets a request — after the reverse window has been sent, or the approval has lapsed.
243 pub fn forget(&self, request_id: u64, client: NodeId) {
244 self.pending
245 .borrow_mut()
246 .retain(|r| !(r.request_id == request_id && r.client_node_id == client));
247 }
248}
249
250impl<H: CommissionerControlHooks, const N: usize> ClusterHandler for CommissionerControl<'_, H, N> {
251 fn read(
252 &self,
253 resolved: &Resolved<'_>,
254 _ctx: &InteractionContext<'_>,
255 w: &mut TlvWriter<'_>,
256 tag: Tag,
257 ) -> Result<(), Status> {
258 if resolved.attribute != SUPPORTED_DEVICE_CATEGORIES {
259 return Err(Status::UnsupportedAttribute);
260 }
261 w.unsigned(tag, u64::from(self.categories.bits()))
262 .map_err(|_| Status::ResourceExhausted)
263 }
264
265 fn invoke(
266 &self,
267 resolved: &ResolvedCommand<'_>,
268 fields: Option<&[u8]>,
269 ctx: &InteractionContext<'_>,
270 w: &mut TlvWriter<'_>,
271 tag: Tag,
272 ) -> Result<Option<CommandId>, StatusIb> {
273 let payload = || fields.ok_or(StatusIb::from(Status::InvalidCommand));
274 // §11.26.6.1 and §11.26.6.5: "If the command is not executed via a CASE session, the
275 // command SHALL fail with a status code of UNSUPPORTED_ACCESS." A request over PASE
276 // comes from something that has not proved which fabric it is on, and the whole flow
277 // turns on matching a later `CommissionNode` to the same node on the same fabric.
278 let (Some(fabric), Some(client)) = (ctx.fabric_index, ctx.peer_node_id) else {
279 return Err(Status::UnsupportedAccess.into());
280 };
281 match resolved.command.id {
282 REQUEST_COMMISSIONING_APPROVAL => {
283 let decoded: spec_cctrl::RequestCommissioningApprovalFields<'_> =
284 super::decode_fields(payload()?)?;
285 if decoded.label.is_some_and(|label| label.len() > LABEL_MAX) {
286 return Err(Status::ConstraintError.into());
287 }
288 let mut pending = self.pending.borrow_mut();
289 // §11.26.6.1: "If the RequestID and client NodeID ... match a previously
290 // received RequestCommissioningApproval and the server has not returned an
291 // error or completed commissioning ... then the server SHOULD return FAILURE."
292 // Two live requests with one id would make the later `CommissionNode` ambiguous.
293 if pending
294 .iter()
295 .any(|r| r.request_id == decoded.request_id && r.client_node_id == client)
296 {
297 return Err(Status::Failure.into());
298 }
299 let request = Request {
300 request_id: decoded.request_id,
301 client_node_id: client,
302 fabric,
303 vendor_id: decoded.vendor_id,
304 product_id: decoded.product_id,
305 approved: None,
306 };
307 pending
308 .push(request)
309 .map_err(|_| StatusIb::from(Status::ResourceExhausted))?;
310 drop(pending);
311 self.hooks.requested(&request);
312 // §11.26.6.1: "The server SHALL always return SUCCESS to a correctly formatted
313 // RequestCommissioningApproval command, and then generate a
314 // CommissioningRequestResult event ... once the result is ready." The command
315 // is a question; the answer is an event.
316 Ok(None)
317 }
318 COMMISSION_NODE => {
319 let decoded: spec_cctrl::CommissionNodeFields = super::decode_fields(payload()?)?;
320 let pending = self.pending.borrow();
321 // §11.26.6.5's three-way match: same RequestID, same NodeID, same fabric.
322 let Some(request) = pending.iter().copied().find(|r| {
323 r.request_id == decoded.request_id
324 && r.client_node_id == client
325 && r.fabric == fabric
326 }) else {
327 return Err(Status::Failure.into());
328 };
329 drop(pending);
330 // A request nobody has approved is not one to act on — §11.26.7.1's event is
331 // what says it is ready, and a client that jumped the gun is asking the server
332 // to commission something it has not agreed to.
333 if request.approved != Some(true) {
334 return Err(Status::Failure.into());
335 }
336 let Some(window) = self.hooks.window(&request) else {
337 return Err(Status::Failure.into());
338 };
339 // §11.19.8.1's constraints, which §11.26.6.8 inherits wholesale.
340 if window.pake_passcode_verifier.len() != VERIFIER_LEN
341 || window.discriminator > 0x0FFF
342 || !(1_000..=100_000).contains(&window.iterations)
343 || !(16..=32).contains(&window.salt.len())
344 {
345 return Err(Status::Failure.into());
346 }
347 let _ = decoded.response_timeout_seconds;
348 self.reverse.set(true);
349 spec_cctrl::ReverseOpenCommissioningWindowFields {
350 commissioning_timeout: window.commissioning_timeout,
351 pake_passcode_verifier: window.pake_passcode_verifier,
352 discriminator: window.discriminator,
353 iterations: window.iterations,
354 salt: window.salt,
355 }
356 .to_tlv(w, tag)
357 .map_err(|_| StatusIb::from(Status::Failure))?;
358 Ok(Some(REVERSE_OPEN_COMMISSIONING_WINDOW))
359 }
360 _ => Err(Status::UnsupportedCommand.into()),
361 }
362 }
363}
364
365/// So a tuple of clusters can dispatch to it by id.
366impl<H: CommissionerControlHooks, const N: usize> Cluster for CommissionerControl<'_, H, N> {
367 const ID: ClusterId = ID;
368}