Skip to main content

matter_kit/clusters/
administrator_commissioning.rs

1//! Administrator Commissioning cluster `0x003C` (Core §11.19) — letting a second
2//! administrator in.
3//!
4//! > This cluster is used to trigger a Node to allow a new Administrator to commission it.
5//!
6//! A commissioned device does not accept PASE sessions. This cluster is how an administrator
7//! that already has one opens a window during which it does — so a second ecosystem can
8//! commission the same device without a factory reset.
9//!
10//! # Two methods, and why the passcode differs
11//!
12//! **Enhanced** (`OpenCommissioningWindow`, mandatory) carries "an ephemeral PAKE passcode
13//! verifier … derived from an ephemeral passcode". The administrator generates a passcode,
14//! shows it to the user, computes `(w0, L)` and sends *only that* — so the device never holds
15//! a passcode, and the verifier "SHALL be deleted by the existing Administrator after sending
16//! it to the Node".
17//!
18//! **Basic** (`OpenBasicCommissioningWindow`, optional, feature `BC`) opens the window against
19//! the device's *own* factory passcode — the one printed on its label. That is why it is
20//! optional and why §5.6.2 exists separately: anyone who has ever seen the label can use the
21//! window, for as long as the device lives.
22//!
23//! # Cluster-specific status codes
24//!
25//! §11.19.6 defines three, and the commands have no response command to put them in — so they
26//! travel in a `StatusIB`'s `ClusterStatus` field beside `FAILURE` (§10.6.17). `Busy` in
27//! particular carries information no interaction-model status does: "it is likely that
28//! concurrent commissioning operations from multiple separate Commissioners are about to take
29//! place."
30//!
31//! # Every command is Timed
32//!
33//! §11.19.8's access column is `AT` — Administer **and Timed**. §8.7.4's Timed transaction is
34//! what stops a recorded invocation being replayed later, and opening a commissioning window
35//! is precisely the command where that matters: a replay would put a device back into
36//! commissioning mode at a moment of the attacker's choosing. §8.8.2.3 step b.vi enforces it
37//! before the command reaches this cluster.
38
39use core::cell::RefCell;
40
41use crate::commissioning::window::{
42    CommissioningWindow, EphemeralVerifier, OpenWindow, PAKE_VERIFIER_LEN, WindowStatus,
43};
44use crate::crypto::Spake2pVerifierData;
45use crate::dm::access::{Access, AccessQualities, Privilege};
46use crate::dm::meta::{AttributeDescriptor, ClusterDescriptor, CommandDescriptor};
47use crate::dm::{Resolved, ResolvedCommand};
48use crate::im::{
49    AttributeId, ClusterHandler, ClusterId, CommandId, InteractionContext, Status, StatusIb,
50};
51use crate::msg::{FabricIndex, VendorId};
52use crate::platform::{Duration, Instant};
53use crate::sc::PbkdfParameters;
54use crate::tlv::{ContainerKind, Tag, TlvReader, TlvWriter, set_once};
55
56use super::Cluster;
57
58/// `0x003C` (§11.19.3).
59pub const ID: ClusterId = 0x003C;
60
61/// The only revision §11.19.1 defines.
62pub const REVISION: u16 = 1;
63
64/// `BC` (§11.19.4, bit 0) — "Node supports Basic Commissioning Method".
65pub const FEATURE_BASIC: u32 = 1 << 0;
66
67/// `WindowStatus` (§11.19.7.1) — `RV`, mandatory.
68pub const WINDOW_STATUS: AttributeId = 0x0000;
69/// `AdminFabricIndex` (§11.19.7.2) — nullable, `RV`, mandatory.
70pub const ADMIN_FABRIC_INDEX: AttributeId = 0x0001;
71/// `AdminVendorId` (§11.19.7.3) — nullable, `RV`, mandatory.
72pub const ADMIN_VENDOR_ID: AttributeId = 0x0002;
73
74/// `OpenCommissioningWindow` (§11.19.8.1) — access `AT`, mandatory.
75pub const OPEN_COMMISSIONING_WINDOW: CommandId = 0x00;
76/// `OpenBasicCommissioningWindow` (§11.19.8.2) — access `AT`, feature `BC`.
77pub const OPEN_BASIC_COMMISSIONING_WINDOW: CommandId = 0x01;
78/// `RevokeCommissioning` (§11.19.8.3) — access `AT`, mandatory.
79pub const REVOKE_COMMISSIONING: CommandId = 0x02;
80
81/// `StatusCodeEnum` (§11.19.6.1) — this cluster's own failure codes.
82///
83/// They travel in a `StatusIB`'s `ClusterStatus` beside `FAILURE`, because none of these
84/// commands has a response command to put them in.
85#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
86#[repr(u8)]
87pub enum AdminStatus {
88    /// `0x02` — "Could not be completed because another commissioning is in progress".
89    Busy = 0x02,
90    /// `0x03` — "Provided PAKE parameters were incorrectly formatted or otherwise invalid".
91    PakeParameterError = 0x03,
92    /// `0x04` — "No commissioning window was currently open".
93    WindowNotOpen = 0x04,
94}
95
96impl AdminStatus {
97    /// The value the `ClusterStatus` field carries.
98    #[must_use]
99    pub const fn value(self) -> u8 {
100        self as u8
101    }
102
103    /// As a `StatusIB`: `FAILURE` with this code beside it.
104    #[must_use]
105    pub const fn as_status(self) -> StatusIb {
106        StatusIb::cluster_failure(self.value())
107    }
108}
109
110/// §5.4.2.3.1's floor: "a device SHALL NOT announce for a duration of less than 3 minutes
111/// after announcement commences."
112pub const COMMISSIONING_TIMEOUT_MIN_SECONDS: u16 = 180;
113
114/// §5.4.2.3.1's ceiling for the rapid-interval phase: "a commissionable device SHALL NOT
115/// announce with a rapid interval for a duration longer than 15 minutes".
116pub const COMMISSIONING_TIMEOUT_MAX_SECONDS: u16 = 900;
117
118// --- Descriptors -------------------------------------------------------------------------------
119
120/// Every attribute is `RV`, and the last two are nullable.
121const ATTRIBUTES: &[AttributeDescriptor] = &[
122    AttributeDescriptor::read_only(WINDOW_STATUS),
123    AttributeDescriptor::read_only(ADMIN_FABRIC_INDEX)
124        .with_qualities(crate::dm::meta::AttributeQualities::NULLABLE),
125    AttributeDescriptor::read_only(ADMIN_VENDOR_ID)
126        .with_qualities(crate::dm::meta::AttributeQualities::NULLABLE),
127];
128
129/// `AT` — Administer, and Timed. See the module documentation for why the `T` matters here
130/// more than almost anywhere else.
131const fn timed_admin(id: CommandId) -> CommandDescriptor {
132    CommandDescriptor::new(id)
133        .with_access(Access::invoke(Privilege::Administer).with_qualities(AccessQualities::TIMED))
134}
135
136/// Without the `BC` feature: the two mandatory commands.
137const ENHANCED_COMMANDS: &[CommandDescriptor] = &[
138    timed_admin(OPEN_COMMISSIONING_WINDOW),
139    timed_admin(REVOKE_COMMISSIONING),
140];
141
142/// With `BC`: all three.
143const ALL_COMMANDS: &[CommandDescriptor] = &[
144    timed_admin(OPEN_COMMISSIONING_WINDOW),
145    timed_admin(OPEN_BASIC_COMMISSIONING_WINDOW),
146    timed_admin(REVOKE_COMMISSIONING),
147];
148
149/// The descriptor for a node that supports only the Enhanced Commissioning Method.
150///
151/// The common case, and the safer one: a Basic window runs against the passcode printed on the
152/// device, so anyone who has ever seen the label can use it.
153#[must_use]
154pub const fn cluster() -> ClusterDescriptor<'static> {
155    ClusterDescriptor {
156        id: ID,
157        revision: REVISION,
158        feature_map: 0,
159        attributes: ATTRIBUTES,
160        accepted_commands: ENHANCED_COMMANDS,
161        generated_commands: &[],
162        events: &[],
163    }
164}
165
166/// The descriptor for a node that also supports the Basic Commissioning Method.
167#[must_use]
168pub const fn cluster_with_basic() -> ClusterDescriptor<'static> {
169    ClusterDescriptor {
170        id: ID,
171        revision: REVISION,
172        feature_map: FEATURE_BASIC,
173        attributes: ATTRIBUTES,
174        accepted_commands: ALL_COMMANDS,
175        generated_commands: &[],
176        events: &[],
177    }
178}
179
180/// What revoking a window left for the device to do (§11.19.8.3).
181///
182/// Every step here is outside a cluster's reach, and step 1 runs "regardless of current
183/// commissioning window state" — so a device that only acted when the window had been open
184/// would leave a PASE session alive after a revoke that answered `WindowNotOpen`.
185#[derive(Debug, Clone, Copy, PartialEq, Eq)]
186pub struct Revoked {
187    /// Step 1.b: "terminate any open PASE sessions or PASE sessions in the process of being
188    /// established". Always true.
189    pub close_pase_sessions: bool,
190    /// Step 1.c: "immediately expire any fail-safe held by an open PASE session and perform
191    /// the cleanup steps outlined in §11.10.7.2.2".
192    ///
193    /// `Some` when a fail-safe was armed and had no accessing fabric — which is what "held by
194    /// an open PASE session" means.
195    pub fail_safe_cleanup: Option<crate::commissioning::failsafe::Cleanup>,
196    /// Step 3.b: "stop publishing the DNS-SD records associated with the advertising it was
197    /// doing due to the open commissioning window".
198    ///
199    /// Only when a window was actually open — there is nothing to withdraw otherwise.
200    pub stop_advertising: bool,
201}
202
203/// The Administrator Commissioning cluster.
204pub struct AdministratorCommissioning<'a> {
205    /// The node's commissioning window, shared with General Commissioning.
206    pub window: &'a RefCell<CommissioningWindow>,
207    /// The node's fail-safe. §11.19.8.1: "If the fail-safe timer is currently armed, this
208    /// command SHALL fail with a cluster specific status code of Busy."
209    pub fail_safe: &'a RefCell<crate::commissioning::failsafe::FailSafe>,
210    /// Whether the `BC` feature is supported.
211    pub basic_supported: bool,
212    /// The fabric table, for looking up the opening administrator's `VendorID`.
213    ///
214    /// §11.19.7.3: the attribute "SHALL match the VendorID field of the Fabrics attribute list
215    /// entry associated with the Administrator having opened the window, **at the time of
216    /// window opening**" — so it is read once, here, and not again.
217    vendor_of_fabric: &'a dyn Fn(FabricIndex) -> Option<VendorId>,
218}
219
220impl<'a> AdministratorCommissioning<'a> {
221    /// The cluster for a node that supports only the Enhanced Commissioning Method.
222    ///
223    /// `vendor_of_fabric` answers §11.19.7.3's lookup — it is a closure rather than a fabric
224    /// table reference so that this cluster does not need `Config` and `N` threaded through
225    /// it for one field.
226    #[must_use]
227    pub fn new(
228        window: &'a RefCell<CommissioningWindow>,
229        fail_safe: &'a RefCell<crate::commissioning::failsafe::FailSafe>,
230        vendor_of_fabric: &'a dyn Fn(FabricIndex) -> Option<VendorId>,
231    ) -> Self {
232        Self {
233            window,
234            fail_safe,
235            basic_supported: false,
236            vendor_of_fabric,
237        }
238    }
239
240    /// The same cluster with the `BC` feature.
241    #[must_use]
242    pub fn with_basic(mut self) -> Self {
243        self.basic_supported = true;
244        self
245    }
246
247    /// The descriptor matching this instance's features.
248    #[must_use]
249    pub fn descriptor(&self) -> ClusterDescriptor<'static> {
250        if self.basic_supported {
251            cluster_with_basic()
252        } else {
253            cluster()
254        }
255    }
256
257    /// The two refusals §11.19.8.1 and §11.19.8.2 share.
258    fn may_open(&self, ctx: &InteractionContext<'_>) -> Result<(), StatusIb> {
259        // "Only one commissioning window can be active at a time. If a Node receives another
260        // open commissioning command when an Open Commissioning Window is already active, it
261        // SHALL return a failure response."
262        if self.window.borrow().open(ctx.now).is_some() {
263            return Err(AdminStatus::Busy.as_status());
264        }
265        // "If the fail-safe timer is currently armed, this command SHALL fail with a cluster
266        // specific status code of Busy, since it is likely that concurrent commissioning
267        // operations from multiple separate Commissioners are about to take place."
268        if self.fail_safe.borrow().is_armed(ctx.now) {
269            return Err(AdminStatus::Busy.as_status());
270        }
271        Ok(())
272    }
273
274    /// `OpenCommissioningWindow` (§11.19.8.1) — the Enhanced Commissioning Method.
275    pub fn open_commissioning_window(
276        &self,
277        request: &OpenWindowRequest<'_>,
278        ctx: &InteractionContext<'_>,
279    ) -> Result<(), StatusIb> {
280        self.may_open(ctx)?;
281
282        // "If any format or validity errors related to the PAKEPasscodeVerifier, Iterations or
283        // Salt arguments arise, this command SHALL fail with a cluster specific status code of
284        // PAKEParameterError."
285        //
286        // `Spake2pVerifierData::from_bytes` checks that `L` is a point on the curve and that
287        // `w0` is a valid scalar — which is the whole of "otherwise invalid". A verifier that
288        // merely looked the right length would fail much later, inside PASE, as an
289        // inexplicable handshake failure.
290        Spake2pVerifierData::from_bytes(request.verifier)
291            .map_err(|_| AdminStatus::PakeParameterError.as_status())?;
292        // §3.9's `Crypto_PBKDFParameterSet` bounds, which §11.19.8.1's table repeats:
293        // iterations 1000 to 100000, salt 16 to 32 octets. Building the real
294        // `PbkdfParameters` is the check — and what a PASE responder will answer a
295        // `PBKDFParamRequest` with.
296        let parameters = PbkdfParameters::new(request.iterations, request.salt)
297            .map_err(|_| AdminStatus::PakeParameterError.as_status())?;
298        let mut verifier = [0u8; PAKE_VERIFIER_LEN];
299        verifier.copy_from_slice(request.verifier);
300
301        self.install(
302            WindowStatus::EnhancedOpen,
303            request.timeout_seconds,
304            request.discriminator,
305            Some(EphemeralVerifier {
306                verifier,
307                iterations: parameters.iterations,
308                salt: parameters.salt,
309            }),
310            ctx,
311        )
312    }
313
314    /// `OpenBasicCommissioningWindow` (§11.19.8.2) — the Basic Commissioning Method.
315    ///
316    /// `discriminator` is the device's own, since the command carries none: a Basic window
317    /// advertises under the discriminator printed on the device, alongside the passcode.
318    pub fn open_basic_commissioning_window(
319        &self,
320        timeout_seconds: u16,
321        discriminator: u16,
322        ctx: &InteractionContext<'_>,
323    ) -> Result<(), StatusIb> {
324        if !self.basic_supported {
325            return Err(Status::UnsupportedCommand.into());
326        }
327        self.may_open(ctx)?;
328        self.install(
329            WindowStatus::BasicOpen,
330            timeout_seconds,
331            discriminator,
332            None,
333            ctx,
334        )
335    }
336
337    fn install(
338        &self,
339        status: WindowStatus,
340        timeout_seconds: u16,
341        discriminator: u16,
342        ephemeral: Option<EphemeralVerifier>,
343        ctx: &InteractionContext<'_>,
344    ) -> Result<(), StatusIb> {
345        // §5.4.2.3.1 bounds the announcement duration at both ends, and §11.19.8.1.1 defers to
346        // it: "This timeout value SHALL follow guidance as specified in the initial
347        // Announcement Duration." Out of range is "any other parameter error", which the
348        // section makes `COMMAND_INVALID` rather than a cluster-specific code.
349        if !(COMMISSIONING_TIMEOUT_MIN_SECONDS..=COMMISSIONING_TIMEOUT_MAX_SECONDS)
350            .contains(&timeout_seconds)
351        {
352            return Err(Status::InvalidCommand.into());
353        }
354        // §11.19.8.1: the discriminator is `0 to 4095` — twelve bits.
355        if discriminator > 0x0FFF {
356            return Err(Status::ConstraintError.into());
357        }
358
359        let admin_fabric = ctx.fabric_index;
360        let admin_vendor = admin_fabric.and_then(|fabric| (self.vendor_of_fabric)(fabric));
361        let expires_at = ctx
362            .now
363            .saturating_add(Duration::from_secs(u64::from(timeout_seconds)));
364
365        self.window.borrow_mut().install(OpenWindow {
366            status,
367            expires_at,
368            admin_fabric,
369            admin_vendor,
370            discriminator,
371            ephemeral,
372        });
373        Ok(())
374    }
375
376    /// `RevokeCommissioning` (§11.19.8.3).
377    ///
378    /// > This is an idempotent command.
379    ///
380    /// Step 1 runs "**regardless of current commissioning window state**", and only then does
381    /// step 2 answer `WindowNotOpen` if there was nothing to close. So this returns the work
382    /// to do *and* the status, rather than returning early on the error — a revoke against a
383    /// closed window still terminates PASE sessions and still expires a PASE-held fail-safe.
384    pub fn revoke_commissioning(
385        &self,
386        ctx: &InteractionContext<'_>,
387    ) -> (Revoked, Result<(), StatusIb>) {
388        let was_open = self.window.borrow().open(ctx.now).is_some();
389
390        // Step 1.a: "(for ECM) delete the temporary PAKEPasscodeVerifier and associated data".
391        // Dropping the window drops the verifier, which is `ZeroizeOnDrop`.
392        self.window.borrow_mut().close();
393
394        // Step 1.c: "immediately expire any fail-safe held by an open PASE session". A
395        // fail-safe with no accessing fabric is one a PASE session armed — §11.10.7.2 starts
396        // the context "at the accessing fabric index for the ArmFailSafe command", which a
397        // PASE session does not have.
398        let mut fail_safe = self.fail_safe.borrow_mut();
399        let pase_held = fail_safe
400            .armed(ctx.now)
401            .is_some_and(|armed| armed.fabric_index.is_none());
402        let cleanup = pase_held.then(|| fail_safe.expire(Instant::MAX)).flatten();
403        drop(fail_safe);
404
405        let revoked = Revoked {
406            close_pase_sessions: true,
407            fail_safe_cleanup: cleanup,
408            stop_advertising: was_open,
409        };
410        let status = if was_open {
411            Ok(())
412        } else {
413            // Step 2: "If the commissioning window was NOT open at the time of receipt, the
414            // Node SHALL return a cluster specific status code of WindowNotOpen."
415            Err(AdminStatus::WindowNotOpen.as_status())
416        };
417        (revoked, status)
418    }
419}
420
421/// `OpenCommissioningWindow`'s fields (§11.19.8.1).
422#[derive(Debug, Clone, Copy)]
423pub struct OpenWindowRequest<'a> {
424    /// `CommissioningTimeout [0]` — seconds, bounded by §5.4.2.3.1.
425    pub timeout_seconds: u16,
426    /// `PAKEPasscodeVerifier [1]` — `w0 || L`, exactly 97 octets.
427    pub verifier: &'a [u8],
428    /// `Discriminator [2]` — `0 to 4095`.
429    pub discriminator: u16,
430    /// `Iterations [3]` — `1000 to 100000`.
431    pub iterations: u32,
432    /// `Salt [4]` — 16 to 32 octets.
433    pub salt: &'a [u8],
434}
435
436// --- The wire ----------------------------------------------------------------------------------
437
438impl ClusterHandler for AdministratorCommissioning<'_> {
439    fn read(
440        &self,
441        resolved: &Resolved<'_>,
442        ctx: &InteractionContext<'_>,
443        w: &mut TlvWriter<'_>,
444        tag: Tag,
445    ) -> Result<(), Status> {
446        let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
447        let window = self.window.borrow();
448        let open = window.open(ctx.now);
449        match resolved.attribute {
450            WINDOW_STATUS => full(w.unsigned(tag, u64::from(window.status(ctx.now).value()))),
451            // §11.19.7.2, §11.19.7.3: "When the WindowStatus attribute is set to
452            // WindowNotOpen, this attribute SHALL be set to null." Null, not zero — zero is a
453            // reserved fabric index and 0 is a real vendor id.
454            ADMIN_FABRIC_INDEX => match open.and_then(|window| window.admin_fabric) {
455                Some(fabric) => full(w.unsigned(tag, u64::from(fabric.0))),
456                None => full(w.null(tag)),
457            },
458            ADMIN_VENDOR_ID => match open.and_then(|window| window.admin_vendor) {
459                Some(vendor) => full(w.unsigned(tag, u64::from(vendor.0))),
460                None => full(w.null(tag)),
461            },
462            _ => Err(Status::UnsupportedAttribute),
463        }
464    }
465
466    fn invoke(
467        &self,
468        resolved: &ResolvedCommand<'_>,
469        fields: Option<&[u8]>,
470        ctx: &InteractionContext<'_>,
471        _w: &mut TlvWriter<'_>,
472        _tag: Tag,
473    ) -> Result<Option<CommandId>, StatusIb> {
474        // None of the three has a response command — §11.19.8's Response column is `Y`, so
475        // success is a plain `SUCCESS` status and failure is a `StatusIB` with this cluster's
476        // own code beside `FAILURE`.
477        match resolved.command.id {
478            OPEN_COMMISSIONING_WINDOW => {
479                let request = decode_open_window(fields)?;
480                self.open_commissioning_window(&request, ctx)?;
481                Ok(None)
482            }
483            OPEN_BASIC_COMMISSIONING_WINDOW => {
484                let timeout = decode_basic_window(fields)?;
485                // The command carries no discriminator: a Basic window advertises under the
486                // device's own, which is printed on it beside the passcode. A device that
487                // wants a different one opens an Enhanced window instead.
488                let discriminator = self
489                    .window
490                    .borrow()
491                    .open(ctx.now)
492                    .map_or(0, |window| window.discriminator);
493                self.open_basic_commissioning_window(timeout, discriminator, ctx)?;
494                Ok(None)
495            }
496            REVOKE_COMMISSIONING => {
497                let (_, status) = self.revoke_commissioning(ctx);
498                status?;
499                Ok(None)
500            }
501            _ => Err(Status::UnsupportedCommand.into()),
502        }
503    }
504}
505
506impl Cluster for AdministratorCommissioning<'_> {
507    const ID: ClusterId = ID;
508}
509
510/// Walks a `CommandFields` structure, refusing a truncated or malformed one.
511fn walk_fields<'a>(
512    fields: Option<&'a [u8]>,
513    mut on_field: impl FnMut(u8, &crate::tlv::Element<'a>) -> Result<bool, StatusIb>,
514) -> Result<(), StatusIb> {
515    let fields = fields.ok_or_else(|| StatusIb::new(Status::InvalidCommand))?;
516    let mut reader = TlvReader::new_in(fields, ContainerKind::Structure);
517    let element = reader
518        .next_element()
519        .map_err(|_| StatusIb::new(Status::InvalidCommand))?
520        .ok_or_else(|| StatusIb::new(Status::InvalidCommand))?;
521    if element.value.container() != Some(ContainerKind::Structure) {
522        return Err(Status::InvalidCommand.into());
523    }
524    let start_depth = reader.depth();
525    loop {
526        let Some(field) = reader
527            .next_element()
528            .map_err(|_| StatusIb::new(Status::InvalidCommand))?
529        else {
530            return Err(Status::InvalidCommand.into());
531        };
532        if reader.depth() < start_depth {
533            break;
534        }
535        let Tag::Context(number) = field.tag else {
536            reader
537                .skip_value(&field)
538                .map_err(|_| StatusIb::new(Status::InvalidCommand))?;
539            continue;
540        };
541        if !on_field(number, &field)? {
542            reader
543                .skip_value(&field)
544                .map_err(|_| StatusIb::new(Status::InvalidCommand))?;
545        }
546    }
547    Ok(())
548}
549
550fn decode_open_window(fields: Option<&[u8]>) -> Result<OpenWindowRequest<'_>, StatusIb> {
551    let invalid = || StatusIb::new(Status::InvalidCommand);
552    let mut timeout = None;
553    let mut verifier = None;
554    let mut discriminator = None;
555    let mut iterations = None;
556    let mut salt = None;
557    walk_fields(fields, |number, element| {
558        match number {
559            0 => {
560                let value = element.unsigned().map_err(|_| invalid())?;
561                set_once(
562                    &mut timeout,
563                    u16::try_from(value).map_err(|_| StatusIb::new(Status::ConstraintError))?,
564                )
565            }
566            1 => set_once(&mut verifier, element.octets().map_err(|_| invalid())?),
567            2 => {
568                let value = element.unsigned().map_err(|_| invalid())?;
569                set_once(
570                    &mut discriminator,
571                    u16::try_from(value).map_err(|_| StatusIb::new(Status::ConstraintError))?,
572                )
573            }
574            3 => {
575                let value = element.unsigned().map_err(|_| invalid())?;
576                set_once(
577                    &mut iterations,
578                    u32::try_from(value).map_err(|_| StatusIb::new(Status::ConstraintError))?,
579                )
580            }
581            4 => set_once(&mut salt, element.octets().map_err(|_| invalid())?),
582            _ => return Ok(false),
583        }
584        .map_err(|_| invalid())?;
585        Ok(true)
586    })?;
587    let verifier = verifier.ok_or_else(invalid)?;
588    // §11.19.8.1's table constrains the field to exactly 97 octets. A verifier of the wrong
589    // length is a "format … error related to the PAKEPasscodeVerifier", which the section
590    // gives a cluster-specific code of its own rather than `CONSTRAINT_ERROR`.
591    if verifier.len() != PAKE_VERIFIER_LEN {
592        return Err(AdminStatus::PakeParameterError.as_status());
593    }
594    Ok(OpenWindowRequest {
595        timeout_seconds: timeout.ok_or_else(invalid)?,
596        verifier,
597        discriminator: discriminator.ok_or_else(invalid)?,
598        iterations: iterations.ok_or_else(invalid)?,
599        salt: salt.ok_or_else(invalid)?,
600    })
601}
602
603fn decode_basic_window(fields: Option<&[u8]>) -> Result<u16, StatusIb> {
604    let invalid = || StatusIb::new(Status::InvalidCommand);
605    let mut timeout = None;
606    walk_fields(fields, |number, element| {
607        match number {
608            0 => {
609                let value = element.unsigned().map_err(|_| invalid())?;
610                set_once(
611                    &mut timeout,
612                    u16::try_from(value).map_err(|_| StatusIb::new(Status::ConstraintError))?,
613                )
614                .map_err(|_| invalid())?;
615            }
616            _ => return Ok(false),
617        }
618        Ok(true)
619    })?;
620    timeout.ok_or_else(invalid)
621}