Skip to main content

matter_kit/clusters/
icd_management.rs

1//! ICD Management, cluster `0x0046` (Core §9.16).
2//!
3//! A device on a coin cell is asleep for almost all of its life. A client that wants to hear
4//! from one registers here, and the device sends it a [Check-In
5//! message](crate::icd::checkin) when it wakes and finds nobody subscribed.
6//!
7//! > ICD Management Cluster enables configuration of the ICD's behavior and ensuring that
8//! > listed clients can be notified when an intermittently connected device, ICD, is available
9//! > for communication.
10//!
11//! # Two node ids, and they are not the same thing
12//!
13//! §9.16.5.3's registration has both a `CheckInNodeID` and a `MonitoredSubject`, and the
14//! difference is the point of the design. The **monitored subject** is what the device watches
15//! for: if any subscription on this fabric matches it, the client is present and no check-in is
16//! due. The **check-in node id** is where the message goes when it is. A phone app might be
17//! monitored as a CAT shared by every phone in the household while check-ins go to one hub.
18//!
19//! Matching the monitored subject is not an equality test — "Matching SHALL be determined using
20//! the subject_matches function defined in the Access Control Privilege Granting Algorithm", so
21//! a CAT subject matches a subscriber holding that tag at an equal or higher version, exactly as
22//! [`acl`](crate::acl) decides it. [`Registration::matches_subscriber`](crate::clusters::icd_management::Registration::matches_subscriber) is that function.
23//!
24//! # The verification key is what stops one manager evicting another's client
25//!
26//! `RegisterClient` and `UnregisterClient` both carry an optional `VerificationKey`, and
27//! §9.16.7.1 makes it conditional on privilege rather than optional in practice:
28//!
29//! > The verification key SHALL be provided for clients with manage permissions. The
30//! > verification key SHOULD NOT be provided by clients with administrator permissions for the
31//! > server cluster. The verification key SHALL be ignored by the server if it is provided by
32//! > a client with administrator permissions.
33//!
34//! So a manager may only touch a registration whose stored key it already knows — it must
35//! prove it is the client it claims to be replacing. Without that check, any node with Manage
36//! on this cluster could point another client's check-ins at itself, or simply delete them, and
37//! the client would go silently unnotified: the symptom is a battery device that appears to
38//! work and a client that never hears from it.
39//!
40//! # What this holds and what it does not
41//!
42//! The table, the timings, and the counter. **Not** the sleep schedule: when a device idles,
43//! when it wakes, and what it does with `StayActiveRequest` are the application's and the
44//! radio's, because nothing here can know a power budget.
45
46use core::cell::RefCell;
47use core::marker::PhantomData;
48
49use crate::config::Config;
50use crate::crypto::{SYMMETRIC_KEY_LENGTH_BYTES, SymmetricKey, ct_eq};
51use crate::dm::spec::{Conforming, Optional};
52use crate::dm::{Privilege, Resolved, ResolvedCommand};
53use crate::im::{
54    AttributeId, ClusterHandler, ClusterId, CommandId, InteractionContext, Status, StatusIb,
55};
56use crate::msg::{FabricIndex, NodeId};
57use crate::tlv::{ContainerKind, Tag, TlvReader, TlvWriter, Value};
58
59use super::Cluster;
60
61/// `0x0046` (§9.16.3).
62pub const ID: ClusterId = 0x0046;
63
64/// The revision §9.16.1's table ends on.
65pub const REVISION: u16 = 3;
66
67/// `IdleModeDuration` (§9.16.6.1) — `uint32`, seconds, `RV F`, mandatory.
68pub const IDLE_MODE_DURATION: AttributeId = 0x0000;
69/// `ActiveModeDuration` (§9.16.6.2) — `uint32`, milliseconds, `RV F`, mandatory.
70pub const ACTIVE_MODE_DURATION: AttributeId = 0x0001;
71/// `ActiveModeThreshold` (§9.16.6.3) — `uint16`, milliseconds, `RV F`, mandatory.
72pub const ACTIVE_MODE_THRESHOLD: AttributeId = 0x0002;
73/// `RegisteredClients` (§9.16.6.4) — `list[MonitoringRegistrationStruct]`, `RAF N`.
74pub const REGISTERED_CLIENTS: AttributeId = 0x0003;
75/// `ICDCounter` (§9.16.6.5) — `uint32`, `RA CN`.
76pub const ICD_COUNTER: AttributeId = 0x0004;
77/// `ClientsSupportedPerFabric` (§9.16.6.6) — `uint16`, `RV F`, min 1.
78pub const CLIENTS_SUPPORTED_PER_FABRIC: AttributeId = 0x0005;
79/// `UserActiveModeTriggerHint` (§9.16.6.7) — `UserActiveModeTriggerBitmap`, `RV F`.
80pub const USER_ACTIVE_MODE_TRIGGER_HINT: AttributeId = 0x0006;
81/// `UserActiveModeTriggerInstruction` (§9.16.6) — `string`, max 128, `RV F`.
82pub const USER_ACTIVE_MODE_TRIGGER_INSTRUCTION: AttributeId = 0x0007;
83/// `OperatingMode` (§9.16.6) — `OperatingModeEnum`, `RV`.
84pub const OPERATING_MODE: AttributeId = 0x0008;
85/// `MaximumCheckInBackoff` (§9.16.6) — `uint32`, seconds, `RV F`.
86pub const MAXIMUM_CHECK_IN_BACKOFF: AttributeId = 0x0009;
87
88/// `RegisterClient` (§9.16.7.1) — `MF`.
89pub const REGISTER_CLIENT: CommandId = 0x00;
90/// `RegisterClientResponse` (§9.16.7.2).
91pub const REGISTER_CLIENT_RESPONSE: CommandId = 0x01;
92/// `UnregisterClient` (§9.16.7.3) — `MF`.
93pub const UNREGISTER_CLIENT: CommandId = 0x02;
94/// `StayActiveRequest` (§9.16.7.4).
95pub const STAY_ACTIVE_REQUEST: CommandId = 0x03;
96/// `StayActiveResponse` (§9.16.7.5).
97pub const STAY_ACTIVE_RESPONSE: CommandId = 0x04;
98
99/// The global `FabricIndex` field of a fabric-scoped struct (§7.19.1.9).
100pub const FABRIC_INDEX_FIELD: u8 = 254;
101
102/// `IdleModeDuration`'s upper bound, 64800 seconds — eighteen hours (§9.16.6).
103pub const IDLE_MODE_DURATION_MAX: u32 = 64_800;
104
105bitflags::bitflags! {
106    /// §9.16.5.1's `UserActiveModeTriggerBitmap`: how a person wakes the device.
107    ///
108    /// A client shows this to a user who is waiting for a sleepy device to answer, so the
109    /// value is a *user interface* rather than a capability — which is why several bits carry
110    /// a dependency on `UserActiveModeTriggerInstruction`: "Press the reset button for N
111    /// seconds" is useless without N.
112    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
113    pub struct UserActiveModeTrigger: u32 {
114        /// Power-cycling the device wakes it.
115        const POWER_CYCLE = 1 << 0;
116        /// The device's own settings menu explains how.
117        const SETTINGS_MENU = 1 << 1;
118        /// `UserActiveModeTriggerInstruction` describes a custom way. Requires it.
119        const CUSTOM_INSTRUCTION = 1 << 2;
120        /// The device manual explains how.
121        const DEVICE_MANUAL = 1 << 3;
122        /// Actuating the sensor wakes it — opening the door, for a door sensor.
123        const ACTUATE_SENSOR = 1 << 4;
124        /// Actuating the sensor for N seconds. Requires the instruction.
125        const ACTUATE_SENSOR_SECONDS = 1 << 5;
126        /// Actuating the sensor N times. Requires the instruction.
127        const ACTUATE_SENSOR_TIMES = 1 << 6;
128        /// Actuating the sensor until a light blinks.
129        const ACTUATE_SENSOR_LIGHTS_BLINK = 1 << 7;
130        /// Pressing the reset button.
131        const RESET_BUTTON = 1 << 8;
132        /// Pressing the reset button until a light blinks.
133        const RESET_BUTTON_LIGHTS_BLINK = 1 << 9;
134        /// Pressing the reset button for N seconds. Requires the instruction.
135        const RESET_BUTTON_SECONDS = 1 << 10;
136        /// Pressing the reset button N times. Requires the instruction.
137        const RESET_BUTTON_TIMES = 1 << 11;
138        /// Pressing the setup button.
139        const SETUP_BUTTON = 1 << 12;
140        /// Pressing the setup button for N seconds. Requires the instruction.
141        const SETUP_BUTTON_SECONDS = 1 << 13;
142        /// Pressing the setup button until a light blinks.
143        const SETUP_BUTTON_LIGHTS_BLINK = 1 << 14;
144        /// Pressing the setup button N times. Requires the instruction.
145        const SETUP_BUTTON_TIMES = 1 << 15;
146        /// Pressing an application-defined button. Requires the instruction.
147        const APP_DEFINED_BUTTON = 1 << 16;
148    }
149}
150
151impl UserActiveModeTrigger {
152    /// The bits §9.16.6.7 says require `UserActiveModeTriggerInstruction` to be present.
153    ///
154    /// Three bits that *depend* on the instruction do not *require* it —
155    /// "ActuateSensorLightsBlink, ResetButtonLightsBlink and SetupButtonLightsBlink (i.e. bits
156    /// 7, 9 and 14) have a dependency on the UserActiveModeTriggerInstruction attribute but do
157    /// not require the attribute to be present" — because the instruction only adds the colour
158    /// of the light. They are excluded here.
159    pub const REQUIRE_INSTRUCTION: Self = Self::from_bits_truncate(
160        Self::CUSTOM_INSTRUCTION.bits()
161            | Self::ACTUATE_SENSOR_SECONDS.bits()
162            | Self::ACTUATE_SENSOR_TIMES.bits()
163            | Self::RESET_BUTTON_SECONDS.bits()
164            | Self::RESET_BUTTON_TIMES.bits()
165            | Self::SETUP_BUTTON_SECONDS.bits()
166            | Self::SETUP_BUTTON_TIMES.bits()
167            | Self::APP_DEFINED_BUTTON.bits(),
168    );
169
170    /// Whether this hint obliges the device to publish an instruction string.
171    #[must_use]
172    pub const fn needs_instruction(self) -> bool {
173        self.intersects(Self::REQUIRE_INSTRUCTION)
174    }
175}
176
177bitflags::bitflags! {
178    /// §9.16.4's features.
179    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
180    pub struct Feature: u32 {
181        /// `CIP` — the Check-In Protocol's attributes and commands.
182        const CHECK_IN_PROTOCOL_SUPPORT = 1 << 0;
183        /// `UAT` — "supported if and only if the device has a user active mode trigger".
184        const USER_ACTIVE_MODE_TRIGGER = 1 << 1;
185        /// `LITS` — the device can operate as a Long Idle Time ICD.
186        const LONG_IDLE_TIME_SUPPORT = 1 << 2;
187        /// `DSLS` — it can switch between SIT and LIT while a client is registered.
188        const DYNAMIC_SIT_LIT_SUPPORT = 1 << 3;
189    }
190}
191
192/// §9.16.5's `ClientTypeEnum` — how available the registered client is.
193#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
194#[repr(u8)]
195pub enum ClientType {
196    /// "typically resident, always-on, fixed infrastructure in the home" — a hub.
197    #[default]
198    Permanent = 0,
199    /// "mobile or non-resident or not always-on" — a phone that leaves the house.
200    Ephemeral = 1,
201}
202
203impl ClientType {
204    /// Reads a wire value; anything else is `CONSTRAINT_ERROR`.
205    pub const fn from_value(value: u64) -> Result<Self, Status> {
206        match value {
207            0 => Ok(Self::Permanent),
208            1 => Ok(Self::Ephemeral),
209            _ => Err(Status::ConstraintError),
210        }
211    }
212}
213
214/// §9.16.5.2's `OperatingModeEnum`.
215#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
216#[repr(u8)]
217pub enum OperatingMode {
218    /// Short Idle Time: the device is reachable often enough for ordinary interaction.
219    #[default]
220    Sit = 0,
221    /// Long Idle Time: it is not, and a client must expect to wait for a check-in.
222    Lit = 1,
223}
224
225/// One registered client (§9.16.5.3's `MonitoringRegistrationStruct`), fabric-scoped.
226///
227/// The `Key` field of that struct is deprecated and never leaves the device — §9.16.5.3 marks
228/// it `D`, and it is the shared secret [`checkin`](crate::icd::checkin) encrypts with. Reading
229/// the list gives back everything *except* it, which is what makes the verification-key rule
230/// mean anything: a client that could read the key would not have to prove it knew it.
231#[derive(Debug, Clone)]
232pub struct Registration {
233    /// Where a Check-In message goes.
234    pub check_in_node_id: NodeId,
235    /// The subject whose subscription counts as "this client is present" (§6.6.6.2's
236    /// `subject_matches`), so a Node ID or a CAT.
237    pub monitored_subject: u64,
238    /// How available the client says it is.
239    pub client_type: ClientType,
240    /// Which fabric registered it.
241    pub fabric_index: FabricIndex,
242    /// The ICDToken — "a 128-bit symmetric key shared by the ICD and the ICD Client, used to
243    /// encrypt Check-In messages from this ICD to the MonitoredSubject".
244    key: SymmetricKey,
245}
246
247/// A CAT subject: the operational node id range §6.6.2.1.2 reserves for them.
248const CAT_PREFIX: u64 = 0xFFFF_FFFD_0000_0000;
249const CAT_MASK: u64 = 0xFFFF_FFFF_0000_0000;
250
251impl Registration {
252    /// Records a client.
253    #[must_use]
254    pub const fn new(
255        check_in_node_id: NodeId,
256        monitored_subject: u64,
257        client_type: ClientType,
258        fabric_index: FabricIndex,
259        key: SymmetricKey,
260    ) -> Self {
261        Self {
262            check_in_node_id,
263            monitored_subject,
264            client_type,
265            fabric_index,
266            key,
267        }
268    }
269
270    /// The key Check-In messages to this client are encrypted with.
271    #[must_use]
272    pub const fn key(&self) -> &SymmetricKey {
273        &self.key
274    }
275
276    /// Whether a subscriber on this fabric satisfies the monitored subject.
277    ///
278    /// §9.16.5.3 defers to §6.6.6.2's `subject_matches`, and the CAT half is the part a
279    /// direct comparison gets wrong:
280    ///
281    /// > if the MonitoredSubject has the value 0xFFFF_FFFD_AA12_0002, and one of the
282    /// > subscribers … bears the CASE Authenticated TAG value 0xAA12 and the version 0x0002
283    /// > **or higher** within its NOC, then the entry matches.
284    ///
285    /// Comparing CATs for equality instead makes every client appear absent the moment its
286    /// tag version is bumped — and the device starts sending check-ins to a client that is
287    /// sitting there subscribed.
288    #[must_use]
289    #[expect(
290        clippy::cast_possible_truncation,
291        reason = "§9.16.5.2's monitored subject is matched against a CAT, which is 32 bits (§6.5.6.3)"
292    )]
293    pub fn matches_subscriber(&self, node: NodeId, cats: &[u32]) -> bool {
294        if self.monitored_subject & CAT_MASK != CAT_PREFIX {
295            return self.monitored_subject == node.0;
296        }
297        let wanted = self.monitored_subject as u32;
298        let (wanted_tag, wanted_version) = (wanted >> 16, wanted & 0xFFFF);
299        cats.iter().any(|&cat| {
300            let (tag, version) = (cat >> 16, cat & 0xFFFF);
301            tag == wanted_tag && version >= wanted_version
302        })
303    }
304
305    /// Writes the struct as §9.16.5.3 defines it, without the deprecated `Key`.
306    fn encode(&self, w: &mut TlvWriter<'_>) -> crate::error::Result<()> {
307        w.start_structure(Tag::Anonymous)?;
308        w.unsigned(Tag::Context(1), self.check_in_node_id.0)?;
309        w.unsigned(Tag::Context(2), self.monitored_subject)?;
310        w.unsigned(Tag::Context(4), self.client_type as u64)?;
311        w.unsigned(
312            Tag::Context(FABRIC_INDEX_FIELD),
313            u64::from(self.fabric_index.0),
314        )?;
315        w.end_container()
316    }
317}
318
319/// The fields of `RegisterClient` (§9.16.7.1).
320#[derive(Debug, Clone)]
321struct RegisterFields {
322    check_in_node_id: NodeId,
323    monitored_subject: u64,
324    key: SymmetricKey,
325    verification_key: Option<SymmetricKey>,
326    client_type: ClientType,
327}
328
329/// Reads a 16-octet key field, refusing any other length.
330///
331/// §9.16.7.1 constrains both `Key` and `VerificationKey` to exactly 16. A shorter one padded
332/// to length would be a weaker key that still worked.
333fn key_field(bytes: &[u8]) -> Result<SymmetricKey, Status> {
334    if bytes.len() != SYMMETRIC_KEY_LENGTH_BYTES {
335        return Err(Status::ConstraintError);
336    }
337    SymmetricKey::from_slice(bytes).map_err(|_| Status::ConstraintError)
338}
339
340fn decode_register(fields: &[u8]) -> Result<RegisterFields, Status> {
341    let mut reader = TlvReader::new_in(fields, ContainerKind::Structure);
342    let element = reader
343        .next_element()
344        .map_err(|_| Status::InvalidAction)?
345        .ok_or(Status::InvalidAction)?;
346    if element.value.container() != Some(ContainerKind::Structure) {
347        return Err(Status::InvalidAction);
348    }
349
350    let mut check_in_node_id = None;
351    let mut monitored_subject = None;
352    let mut key = None;
353    let mut verification_key = None;
354    let mut client_type = None;
355    loop {
356        let Some(field) = reader.next_element().map_err(|_| Status::InvalidAction)? else {
357            return Err(Status::InvalidAction);
358        };
359        if field.value == Value::EndOfContainer {
360            break;
361        }
362        match field.tag.context() {
363            Some(0) => {
364                check_in_node_id = Some(NodeId(
365                    field.unsigned().map_err(|_| Status::ConstraintError)?,
366                ));
367            }
368            Some(1) => {
369                monitored_subject = Some(field.unsigned().map_err(|_| Status::ConstraintError)?);
370            }
371            Some(2) => {
372                key = Some(key_field(
373                    field.octets().map_err(|_| Status::ConstraintError)?,
374                )?);
375            }
376            Some(3) => {
377                verification_key = Some(key_field(
378                    field.octets().map_err(|_| Status::ConstraintError)?,
379                )?);
380            }
381            Some(4) => {
382                client_type = Some(ClientType::from_value(
383                    field.unsigned().map_err(|_| Status::ConstraintError)?,
384                )?);
385            }
386            _ => {
387                reader
388                    .skip_value(&field)
389                    .map_err(|_| Status::InvalidAction)?;
390            }
391        }
392    }
393
394    let (Some(check_in_node_id), Some(monitored_subject), Some(key), Some(client_type)) =
395        (check_in_node_id, monitored_subject, key, client_type)
396    else {
397        // §8.8.2.3: a command missing a mandatory field is not a command.
398        return Err(Status::InvalidCommand);
399    };
400    Ok(RegisterFields {
401        check_in_node_id,
402        monitored_subject,
403        key,
404        verification_key,
405        client_type,
406    })
407}
408
409/// The fields of `UnregisterClient` (§9.16.7.3).
410fn decode_unregister(fields: &[u8]) -> Result<(NodeId, Option<SymmetricKey>), Status> {
411    let mut reader = TlvReader::new_in(fields, ContainerKind::Structure);
412    let element = reader
413        .next_element()
414        .map_err(|_| Status::InvalidAction)?
415        .ok_or(Status::InvalidAction)?;
416    if element.value.container() != Some(ContainerKind::Structure) {
417        return Err(Status::InvalidAction);
418    }
419    let mut node = None;
420    let mut verification_key = None;
421    loop {
422        let Some(field) = reader.next_element().map_err(|_| Status::InvalidAction)? else {
423            return Err(Status::InvalidAction);
424        };
425        if field.value == Value::EndOfContainer {
426            break;
427        }
428        match field.tag.context() {
429            Some(0) => {
430                node = Some(NodeId(
431                    field.unsigned().map_err(|_| Status::ConstraintError)?,
432                ))
433            }
434            Some(1) => {
435                verification_key = Some(key_field(
436                    field.octets().map_err(|_| Status::ConstraintError)?,
437                )?);
438            }
439            _ => {
440                reader
441                    .skip_value(&field)
442                    .map_err(|_| Status::InvalidAction)?;
443            }
444        }
445    }
446    node.map(|n| (n, verification_key))
447        .ok_or(Status::InvalidCommand)
448}
449
450/// Reads `StayActiveRequest`'s single field (§9.16.7.4).
451fn decode_stay_active(fields: &[u8]) -> Result<u32, Status> {
452    let mut reader = TlvReader::new_in(fields, ContainerKind::Structure);
453    let element = reader
454        .next_element()
455        .map_err(|_| Status::InvalidAction)?
456        .ok_or(Status::InvalidAction)?;
457    if element.value.container() != Some(ContainerKind::Structure) {
458        return Err(Status::InvalidAction);
459    }
460    let mut duration = None;
461    loop {
462        let Some(field) = reader.next_element().map_err(|_| Status::InvalidAction)? else {
463            return Err(Status::InvalidAction);
464        };
465        if field.value == Value::EndOfContainer {
466            break;
467        }
468        if field.tag.context() == Some(0) {
469            duration = Some(
470                u32::try_from(field.unsigned().map_err(|_| Status::ConstraintError)?)
471                    .map_err(|_| Status::ConstraintError)?,
472            );
473        } else {
474            reader
475                .skip_value(&field)
476                .map_err(|_| Status::InvalidAction)?;
477        }
478    }
479    duration.ok_or(Status::InvalidCommand)
480}
481
482/// The timings a device publishes about its own sleep (§9.16.6.1–9.16.6.3).
483#[derive(Debug, Clone, Copy, PartialEq, Eq)]
484pub struct Timings {
485    /// `IdleModeDuration`, in **seconds**: "the maximum interval in seconds the server can
486    /// stay in idle mode".
487    pub idle_mode_duration: u32,
488    /// `ActiveModeDuration`, in **milliseconds**: "the minimum interval in milliseconds the
489    /// server typically will stay in active mode after initial transition out of idle mode".
490    pub active_mode_duration: u32,
491    /// `ActiveModeThreshold`, in **milliseconds**: how long it stays active after traffic.
492    pub active_mode_threshold: u16,
493    /// `MaximumCheckInBackoff`, in seconds, at least `IdleModeDuration`.
494    pub maximum_check_in_backoff: u32,
495}
496
497impl Default for Timings {
498    /// §9.16.6's fallbacks: one second idle, 300 ms active, 300 ms threshold.
499    fn default() -> Self {
500        Self {
501            idle_mode_duration: 1,
502            active_mode_duration: 300,
503            active_mode_threshold: 300,
504            maximum_check_in_backoff: 1,
505        }
506    }
507}
508
509impl Timings {
510    /// Whether the four values satisfy §9.16.6's constraints.
511    ///
512    /// The units are the trap. `IdleModeDuration` is seconds and `ActiveModeDuration` is
513    /// milliseconds, and "The IdleModeDuration SHALL NOT be smaller than the
514    /// ActiveModeDuration" compares them as *durations* — so a device advertising one second
515    /// idle and five seconds active is describing something impossible, and a check that
516    /// compared the two numbers directly would pass it.
517    #[must_use]
518    pub const fn is_valid(&self) -> bool {
519        if self.idle_mode_duration == 0 || self.idle_mode_duration > IDLE_MODE_DURATION_MAX {
520            return false;
521        }
522        if self.maximum_check_in_backoff < self.idle_mode_duration
523            || self.maximum_check_in_backoff > IDLE_MODE_DURATION_MAX
524        {
525            return false;
526        }
527        // Compare in milliseconds; `idle_mode_duration` is at most 64800, so this cannot
528        // overflow a u32.
529        self.idle_mode_duration.saturating_mul(1000) >= self.active_mode_duration
530    }
531}
532
533/// The descriptor for an instance with these features.
534///
535/// Derived from the specification's own tables rather than written out, because the element
536/// set *moves with the feature map*: without `UAT` there is no `UserActiveModeTriggerHint`,
537/// without `LITS` no `OperatingMode` and no `StayActiveRequest`. A fixed list would advertise
538/// all of them whatever the device claimed, and a client reading `AttributeList` would believe
539/// it — then read an attribute the device answers `UNSUPPORTED_ATTRIBUTE` for.
540///
541/// `Optional` names the elements §9.16.6 leaves to the product. The storage lives in the
542/// returned value, so a device holds one per cluster instance for as long as its node exists.
543///
544/// Returns [`ErrorCode::InvalidArgument`](crate::ErrorCode) for a feature this revision does
545/// not define.
546pub fn conforming(
547    features: Feature,
548    optional: &Optional<'_>,
549) -> crate::error::Result<Conforming<12, 4, 2, 0>> {
550    Conforming::new(
551        &crate::clusters::generated::icd_management::CLUSTER,
552        features.bits(),
553        optional,
554    )
555}
556
557/// What a device must do when `StayActiveRequest` arrives.
558///
559/// §9.16.7.4 makes the answer the device's, not the cluster's: the `PromisedActiveDuration`
560/// is "the greater of" what the client asked for and "the server's planned remaining active
561/// time based on the ActiveModeThreshold and **its internal resources and power budget**".
562/// Nothing here knows a power budget, so the device supplies this and the cluster reports it.
563pub trait StayActive {
564    /// The duration in milliseconds this device promises to remain reachable, having been
565    /// asked for `requested`.
566    fn promise(&self, requested: u32) -> u32;
567}
568
569/// A device that simply grants what it is asked for.
570///
571/// Correct for a mains-powered node and a reasonable starting point for a battery one, since
572/// §9.16.7.4 permits a server to "replace StayActiveDuration with Minimum Active Duration" —
573/// but a device with a real power budget should say so rather than promise what it cannot keep.
574#[derive(Debug, Clone, Copy, Default)]
575pub struct GrantRequested;
576
577impl StayActive for GrantRequested {
578    fn promise(&self, requested: u32) -> u32 {
579        requested
580    }
581}
582
583/// The ICD Management cluster's state (§9.16.6).
584///
585/// `N` is the total number of registrations across every fabric, and
586/// [`Config::ICD_CLIENTS_PER_FABRIC`] is what §9.16.6.6 publishes and what any one fabric may
587/// use, so that the first fabric to register cannot leave a later one unable to.
588/// [`IcdManagement::CHECK`] refuses at compile time an `N` too small for every fabric to have
589/// its share — the attribute is a promise, and a promise the table cannot keep is the defect
590/// this whole shape exists to stop.
591#[derive(Debug)]
592pub struct IcdManagement<'a, C: Config, const N: usize = 5, A: StayActive = GrantRequested> {
593    clients: RefCell<heapless::Vec<Registration, N>>,
594    counter: RefCell<u32>,
595    timings: Timings,
596    features: Feature,
597    operating_mode: RefCell<OperatingMode>,
598    trigger_hint: UserActiveModeTrigger,
599    trigger_instruction: &'a str,
600    stay_active: A,
601    _config: PhantomData<C>,
602}
603
604impl<'a, C: Config, const N: usize> IcdManagement<'a, C, N, GrantRequested> {
605    /// A cluster for a device that grants every `StayActiveRequest` in full.
606    #[must_use]
607    pub const fn new(features: Feature, timings: Timings) -> Self {
608        Self::with_stay_active(features, timings, GrantRequested)
609    }
610}
611
612impl<'a, C: Config, const N: usize, A: StayActive> IcdManagement<'a, C, N, A> {
613    /// Compile-time proof that the registration table can keep §9.16.6.6's promise.
614    ///
615    /// > This attribute SHALL indicate the maximum number of entries that the server is able to
616    /// > store for each fabric in the RegisteredClients attribute.
617    ///
618    /// "For each fabric", so the table needs `FABRICS × ICD_CLIENTS_PER_FABRIC` slots. Without
619    /// this, `ClientsSupportedPerFabric` is a number a device states and a table that cannot
620    /// honour it — and the fabric that finds out is the last one to register.
621    pub const CHECK: () = {
622        let () = crate::config::AssertValid::<C>::CHECK;
623        assert!(
624            N >= C::ICD_CLIENTS_PER_FABRIC * C::FABRICS,
625            "IcdManagement: §9.16.6.6 promises ICD_CLIENTS_PER_FABRIC registrations to every \
626             fabric, so the table must hold FABRICS × that many"
627        );
628    };
629
630    /// A cluster whose device decides how long it can stay awake.
631    #[must_use]
632    pub const fn with_stay_active(features: Feature, timings: Timings, stay_active: A) -> Self {
633        let () = Self::CHECK;
634        Self {
635            clients: RefCell::new(heapless::Vec::new()),
636            counter: RefCell::new(0),
637            timings,
638            features,
639            // §9.16.6: a device that does not support LIT is always SIT.
640            operating_mode: RefCell::new(OperatingMode::Sit),
641            trigger_hint: UserActiveModeTrigger::empty(),
642            trigger_instruction: "",
643            stay_active,
644            _config: PhantomData,
645        }
646    }
647
648    /// Declares how a person wakes this device (§9.16.6.7).
649    ///
650    /// Returns [`ErrorCode::InvalidArgument`](crate::ErrorCode) when the hint names a trigger
651    /// that needs an instruction and none is given: "If the attribute indicates support for a
652    /// trigger that is dependent on the UserActiveModeTriggerInstruction … the
653    /// UserActiveModeTriggerInstruction attribute SHALL be implemented and SHALL provide the
654    /// required information." A hint reading "press the button for N seconds" with no N is
655    /// worse than no hint, because a client will display it.
656    pub fn with_trigger(
657        mut self,
658        hint: UserActiveModeTrigger,
659        instruction: &'a str,
660    ) -> crate::error::Result<Self> {
661        if instruction.len() > 128 {
662            crate::error::bail!(InvalidArgument)
663        }
664        if hint.needs_instruction() && instruction.is_empty() {
665            crate::error::bail!(InvalidArgument)
666        }
667        self.trigger_hint = hint;
668        self.trigger_instruction = instruction;
669        Ok(self)
670    }
671
672    /// The timings this device publishes.
673    #[must_use]
674    pub const fn timings(&self) -> Timings {
675        self.timings
676    }
677
678    /// The current operating mode (§9.16.5.2).
679    #[must_use]
680    pub fn operating_mode(&self) -> OperatingMode {
681        *self.operating_mode.borrow()
682    }
683
684    /// Switches between Short and Long Idle Time.
685    ///
686    /// §9.16.4.4: a device may do this while a client is registered only with `DSLS`. Without
687    /// that feature a registered client has been promised the mode it saw, and changing it
688    /// underneath means the client's polling assumptions are silently wrong.
689    pub fn set_operating_mode(&self, mode: OperatingMode) -> Result<(), Status> {
690        if !self.features.contains(Feature::LONG_IDLE_TIME_SUPPORT) {
691            return Err(Status::UnsupportedAttribute);
692        }
693        if mode == OperatingMode::Lit
694            && !self.features.contains(Feature::DYNAMIC_SIT_LIT_SUPPORT)
695            && !self.clients.borrow().is_empty()
696        {
697            return Err(Status::InvalidInState);
698        }
699        *self.operating_mode.borrow_mut() = mode;
700        Ok(())
701    }
702
703    /// The `ICDCounter` (§9.16.6.5) — the Check-In Counter for the next message.
704    #[must_use]
705    pub fn counter(&self) -> u32 {
706        *self.counter.borrow()
707    }
708
709    /// Advances the counter and returns the value the next Check-In message must be
710    /// encrypted with.
711    ///
712    /// It advances **first**, and that order is forced by §4.22.3.3 rather than chosen. A
713    /// client stores the `ICDCounter` it was handed at registration as its *starting* value,
714    /// and validation is `stored offset < received − start`: a check-in bearing the very
715    /// value that was reported has an offset of zero and is rejected as a replay. Appendix
716    /// F.4's Test 3 is exactly that message, and it decrypts perfectly — so a device that
717    /// reported N and then checked in with N would look, from the client's side, like an
718    /// attacker replaying an old message, with nothing anywhere explaining why.
719    ///
720    /// Each value is used once besides: reusing one reuses the nonce it derives
721    /// ([`checkin`](crate::icd::checkin)), so this both advances and reads rather than
722    /// offering the two separately.
723    pub fn next_check_in_counter(&self) -> u32 {
724        let mut counter = self.counter.borrow_mut();
725        *counter = counter.wrapping_add(1);
726        *counter
727    }
728
729    /// Restores the counter after a reboot, at exactly the value given.
730    ///
731    /// §4.6.3: "Nodes are required to persist the Check-In Counter in durable storage", and a
732    /// counter that rewinds reuses a nonce. A device persisting this should store *ahead* of
733    /// where it is — §4.6.3 describes the strategy — exactly as the message counters do.
734    pub fn restore_counter(&self, value: u32) {
735        *self.counter.borrow_mut() = value;
736    }
737
738    /// §4.6.3's factory-reset initialisation, from a full-width random word.
739    ///
740    /// "The device SHALL randomize the initial value of the counter on factory reset per
741    /// Section 4.6.1.1" — the same `Crypto_DRBG(len = 28) + 1` as every other counter in the
742    /// specification, so this goes through the same
743    /// [`initial_counter`](crate::msg::initial_counter).
744    ///
745    /// A factory-fresh cluster starts at zero, because a `const fn` constructor has no
746    /// randomness to draw on and inventing one would be worse than asking. Call this once, when
747    /// the device has no persisted counter to restore; on every boot after that, call
748    /// [`restore_counter`](Self::restore_counter) with what was stored. Starting from zero
749    /// every time is what §4.6.3 forbids: the client validates a check-in as
750    /// `stored offset < received − start`, so a counter that rewinds past a registered client's
751    /// starting value makes every later check-in look like a replay, and the client stops
752    /// waking for a device that is calling it.
753    pub fn randomize_counter(&self, randomness: u32) {
754        *self.counter.borrow_mut() = crate::msg::initial_counter(randomness);
755    }
756
757    /// Every registration, for a device about to persist them or send a check-in.
758    #[must_use]
759    pub fn clients(&self) -> core::cell::Ref<'_, heapless::Vec<Registration, N>> {
760        self.clients.borrow()
761    }
762
763    /// How many registrations one fabric holds.
764    #[must_use]
765    pub fn len_of_fabric(&self, fabric: FabricIndex) -> usize {
766        self.clients
767            .borrow()
768            .iter()
769            .filter(|c| c.fabric_index == fabric)
770            .count()
771    }
772
773    /// Removes every registration of one fabric — what `RemoveFabric` must do.
774    pub fn remove_fabric(&self, fabric: FabricIndex) {
775        self.clients
776            .borrow_mut()
777            .retain(|c| c.fabric_index != fabric);
778    }
779
780    /// §9.16.7.1's steps 1–5.
781    fn register(
782        &self,
783        fields: RegisterFields,
784        fabric: FabricIndex,
785        administrator: bool,
786    ) -> Result<(), StatusIb> {
787        let mut clients = self.clients.borrow_mut();
788        let existing = clients.iter().position(|c| {
789            c.fabric_index == fabric && c.check_in_node_id == fields.check_in_node_id
790        });
791
792        match existing {
793            // Step 1a → 2: an entry for this CheckInNodeID already exists, so this is a
794            // *modification* and the verification key decides whether it is allowed.
795            Some(position) => {
796                let Some(entry) = clients.get_mut(position) else {
797                    return Err(Status::Failure.into());
798                };
799                if !administrator {
800                    // Steps 3a and 3b. `ct_eq` because a comparison that stops at the first
801                    // differing octet tells an attacker how much of the key it has guessed.
802                    let Some(verification) = fields.verification_key else {
803                        return Err(Status::Failure.into());
804                    };
805                    if !ct_eq(verification.as_bytes(), entry.key.as_bytes()) {
806                        return Err(Status::Failure.into());
807                    }
808                }
809                // Step 4.
810                entry.monitored_subject = fields.monitored_subject;
811                entry.client_type = fields.client_type;
812                entry.key = fields.key;
813                Ok(())
814            }
815            // Step 1b, or 1c. Counted from the borrow already held: reaching for a second one
816            // here is a panic, not a compile error, and `RefCell` is the only thing in this
817            // crate that can still do that.
818            None => {
819                let used = clients.iter().filter(|c| c.fabric_index == fabric).count();
820                if used >= C::ICD_CLIENTS_PER_FABRIC {
821                    return Err(Status::ResourceExhausted.into());
822                }
823                clients
824                    .push(Registration::new(
825                        fields.check_in_node_id,
826                        fields.monitored_subject,
827                        fields.client_type,
828                        fabric,
829                        fields.key,
830                    ))
831                    .map_err(|_| StatusIb::from(Status::ResourceExhausted))
832            }
833        }
834    }
835
836    /// §9.16.7.3's steps 1–5.
837    fn unregister(
838        &self,
839        node: NodeId,
840        verification_key: Option<SymmetricKey>,
841        fabric: FabricIndex,
842        administrator: bool,
843    ) -> Result<(), StatusIb> {
844        let mut clients = self.clients.borrow_mut();
845        let Some(position) = clients
846            .iter()
847            .position(|c| c.fabric_index == fabric && c.check_in_node_id == node)
848        else {
849            // Steps 1a and 2a are the same outcome from a client's point of view, and giving
850            // them different ones would tell an unprivileged caller which node ids are
851            // registered on a fabric it cannot read.
852            return Err(Status::NotFound.into());
853        };
854        if !administrator {
855            let Some(entry) = clients.get(position) else {
856                return Err(Status::Failure.into());
857            };
858            let Some(verification) = verification_key else {
859                return Err(Status::Failure.into());
860            };
861            if !ct_eq(verification.as_bytes(), entry.key.as_bytes()) {
862                return Err(Status::Failure.into());
863            }
864        }
865        clients.remove(position);
866        Ok(())
867    }
868
869    /// Whether a fabric's entries belong in this read (§7.19.1.8.2).
870    fn visible(ctx: &InteractionContext<'_>, index: FabricIndex) -> bool {
871        !ctx.fabric_filtered || ctx.fabric_index == Some(index)
872    }
873
874    /// Whether the caller holds Administer over this cluster (§9.16.7.1 step 2).
875    ///
876    /// An unknown privilege is treated as *not* administrator, which is the cautious reading:
877    /// the consequence is a manager-shaped rule applied to an administrator, which refuses a
878    /// modification that had no verification key. The other default would let anyone who
879    /// reached the command bypass the key check entirely.
880    fn is_administrator(ctx: &InteractionContext<'_>) -> bool {
881        ctx.privilege
882            .is_some_and(|p| p.grants(Privilege::Administer))
883    }
884}
885
886impl<C: Config, const N: usize, A: StayActive> ClusterHandler for IcdManagement<'_, C, N, A> {
887    /// §9.16.6.4: registrations are per fabric, and each one holds a shared key. A
888    /// registration that outlives its fabric is key material for somebody who has left.
889    fn on_lifecycle(&self, event: crate::im::Lifecycle) {
890        if let crate::im::Lifecycle::FabricRemoved(fabric) = event {
891            self.remove_fabric(fabric);
892        }
893    }
894    fn read(
895        &self,
896        resolved: &Resolved<'_>,
897        ctx: &InteractionContext<'_>,
898        w: &mut TlvWriter<'_>,
899        tag: Tag,
900    ) -> Result<(), Status> {
901        let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
902        match resolved.attribute {
903            IDLE_MODE_DURATION => full(w.unsigned(tag, u64::from(self.timings.idle_mode_duration))),
904            ACTIVE_MODE_DURATION => {
905                full(w.unsigned(tag, u64::from(self.timings.active_mode_duration)))
906            }
907            ACTIVE_MODE_THRESHOLD => {
908                full(w.unsigned(tag, u64::from(self.timings.active_mode_threshold)))
909            }
910            REGISTERED_CLIENTS => {
911                if !self.features.contains(Feature::CHECK_IN_PROTOCOL_SUPPORT) {
912                    return Err(Status::UnsupportedAttribute);
913                }
914                let clients = self.clients.borrow();
915                full(w.start_array(tag))?;
916                for client in clients
917                    .iter()
918                    .filter(|c| Self::visible(ctx, c.fabric_index))
919                {
920                    full(client.encode(w))?;
921                }
922                full(w.end_container())
923            }
924            ICD_COUNTER => {
925                if !self.features.contains(Feature::CHECK_IN_PROTOCOL_SUPPORT) {
926                    return Err(Status::UnsupportedAttribute);
927                }
928                full(w.unsigned(tag, u64::from(self.counter())))
929            }
930            CLIENTS_SUPPORTED_PER_FABRIC => {
931                if !self.features.contains(Feature::CHECK_IN_PROTOCOL_SUPPORT) {
932                    return Err(Status::UnsupportedAttribute);
933                }
934                full(w.unsigned(tag, C::ICD_CLIENTS_PER_FABRIC as u64))
935            }
936            USER_ACTIVE_MODE_TRIGGER_HINT => {
937                if !self.features.contains(Feature::USER_ACTIVE_MODE_TRIGGER) {
938                    return Err(Status::UnsupportedAttribute);
939                }
940                full(w.unsigned(tag, u64::from(self.trigger_hint.bits())))
941            }
942            USER_ACTIVE_MODE_TRIGGER_INSTRUCTION => {
943                if !self.features.contains(Feature::USER_ACTIVE_MODE_TRIGGER) {
944                    return Err(Status::UnsupportedAttribute);
945                }
946                full(w.utf8(tag, self.trigger_instruction))
947            }
948            OPERATING_MODE => {
949                if !self.features.contains(Feature::LONG_IDLE_TIME_SUPPORT) {
950                    return Err(Status::UnsupportedAttribute);
951                }
952                full(w.unsigned(tag, self.operating_mode() as u64))
953            }
954            MAXIMUM_CHECK_IN_BACKOFF => {
955                if !self.features.contains(Feature::CHECK_IN_PROTOCOL_SUPPORT) {
956                    return Err(Status::UnsupportedAttribute);
957                }
958                full(w.unsigned(tag, u64::from(self.timings.maximum_check_in_backoff)))
959            }
960            _ => Err(Status::UnsupportedAttribute),
961        }
962    }
963
964    fn invoke(
965        &self,
966        resolved: &ResolvedCommand<'_>,
967        fields: Option<&[u8]>,
968        ctx: &InteractionContext<'_>,
969        w: &mut TlvWriter<'_>,
970        tag: Tag,
971    ) -> Result<Option<CommandId>, StatusIb> {
972        let full = |r: crate::error::Result<()>| r.map_err(|_| StatusIb::from(Status::Failure));
973        match resolved.command.id {
974            REGISTER_CLIENT => {
975                if !self.features.contains(Feature::CHECK_IN_PROTOCOL_SUPPORT) {
976                    return Err(Status::UnsupportedCommand.into());
977                }
978                // §8.8.2.3 step b.v: a fabric-scoped command with no accessing fabric has
979                // nowhere to put its entry. A PASE session during commissioning is exactly
980                // that case.
981                let Some(fabric) = ctx.fabric_index else {
982                    return Err(Status::UnsupportedAccess.into());
983                };
984                let fields =
985                    decode_register(fields.ok_or(StatusIb::from(Status::InvalidCommand))?)?;
986                self.register(fields, fabric, Self::is_administrator(ctx))?;
987
988                // §9.16.7.2: "The ICDCounter field SHALL be set to the ICDCounter attribute of
989                // the server." The client stores it as the starting value its replay window is
990                // measured from (§4.22.1.2), so it must be the counter the *next* check-in
991                // will exceed rather than one already spent.
992                full(w.start_structure(tag))?;
993                full(w.unsigned(Tag::Context(0), u64::from(self.counter())))?;
994                full(w.end_container())?;
995                Ok(Some(REGISTER_CLIENT_RESPONSE))
996            }
997            UNREGISTER_CLIENT => {
998                if !self.features.contains(Feature::CHECK_IN_PROTOCOL_SUPPORT) {
999                    return Err(Status::UnsupportedCommand.into());
1000                }
1001                let Some(fabric) = ctx.fabric_index else {
1002                    return Err(Status::UnsupportedAccess.into());
1003                };
1004                let (node, verification_key) =
1005                    decode_unregister(fields.ok_or(StatusIb::from(Status::InvalidCommand))?)?;
1006                self.unregister(node, verification_key, fabric, Self::is_administrator(ctx))?;
1007                Ok(None)
1008            }
1009            STAY_ACTIVE_REQUEST => {
1010                if !self.features.contains(Feature::LONG_IDLE_TIME_SUPPORT) {
1011                    return Err(Status::UnsupportedCommand.into());
1012                }
1013                let requested =
1014                    decode_stay_active(fields.ok_or(StatusIb::from(Status::InvalidCommand))?)?;
1015                let promised = self.stay_active.promise(requested);
1016                full(w.start_structure(tag))?;
1017                full(w.unsigned(Tag::Context(0), u64::from(promised)))?;
1018                full(w.end_container())?;
1019                Ok(Some(STAY_ACTIVE_RESPONSE))
1020            }
1021            _ => Err(Status::UnsupportedCommand.into()),
1022        }
1023    }
1024}
1025
1026/// So a tuple of clusters can dispatch to it by id.
1027impl<C: Config, const N: usize, A: StayActive> Cluster for IcdManagement<'_, C, N, A> {
1028    const ID: ClusterId = ID;
1029}