rs-matter 0.2.0

Native Rust implementation of the Matter (Smart-Home) ecosystem
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
/*
 *
 *    Copyright (c) 2025-2026 Project CHIP Authors
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

//! This module contains the implementation of the Group Key Management cluster and its handler.

use core::num::NonZeroU8;

use crate::crypto::AEAD_CANON_KEY_LEN;
use crate::dm::{
    ArrayAttributeRead, ArrayAttributeWrite, Cluster, Dataver, InvokeContext, ReadContext,
    WriteContext,
};
use crate::error::{Error, ErrorCode};
use crate::fabric::{
    FabricPersist, GroupKeyMapping, MAX_GROUPS_PER_FABRIC, MAX_GROUP_KEYS_PER_FABRIC,
};
use crate::group_keys::{GroupEpochKeyEntry, GroupKeySet};
use crate::tlv::{Nullable, Octets, TLVArray, TLVBuilderParent};
use crate::with;

pub use crate::dm::clusters::decl::group_key_management::*;

/// The system implementation of a handler for the Group Key Management Matter cluster.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct GrpKeyMgmtHandler {
    dataver: Dataver,
}

impl GrpKeyMgmtHandler {
    /// Creates a new instance of the `GrpKeyMgmtHandler` with the given `Dataver`.
    pub const fn new(dataver: Dataver) -> Self {
        Self { dataver }
    }

    /// Adapt the handler instance to the generic `rs-matter` `Handler` trait
    pub const fn adapt(self) -> HandlerAdaptor<Self> {
        HandlerAdaptor(self)
    }
}

impl ClusterHandler for GrpKeyMgmtHandler {
    const CLUSTER: Cluster<'static> = FULL_CLUSTER.with_attrs(with!(required));

    fn dataver(&self) -> u32 {
        self.dataver.get()
    }

    fn dataver_changed(&self) {
        self.dataver.changed();
    }

    fn group_key_map<P: TLVBuilderParent>(
        &self,
        ctx: impl ReadContext,
        builder: ArrayAttributeRead<GroupKeyMapStructArrayBuilder<P>, GroupKeyMapStructBuilder<P>>,
    ) -> Result<P, Error> {
        let attr = ctx.attr();

        ctx.exchange().with_state(|state| {
            let mut entries = state
                .fabrics
                .iter()
                .filter(|fabric| !attr.fab_filter || fabric.fab_idx().get() == attr.fab_idx)
                .flat_map(|fabric| {
                    fabric
                        .groups()
                        .key_map_iter()
                        .map(move |entry| (fabric.fab_idx(), entry))
                });

            match builder {
                ArrayAttributeRead::ReadAll(mut builder) => {
                    for (fab_idx, entry) in entries {
                        builder = builder
                            .push()?
                            .group_id(entry.group_id)?
                            .group_key_set_id(entry.group_key_set_id)?
                            .fabric_index(Some(fab_idx.get()))?
                            .end()?;
                    }
                    builder.end()
                }
                ArrayAttributeRead::ReadOne(index, builder) => {
                    let Some((fab_idx, entry)) = entries.nth(index as usize) else {
                        return Err(ErrorCode::ConstraintError.into());
                    };
                    builder
                        .group_id(entry.group_id)?
                        .group_key_set_id(entry.group_key_set_id)?
                        .fabric_index(Some(fab_idx.get()))?
                        .end()
                }
                ArrayAttributeRead::ReadNone(builder) => builder.end(),
            }
        })
    }

    fn group_table<P: TLVBuilderParent>(
        &self,
        ctx: impl ReadContext,
        builder: ArrayAttributeRead<
            GroupInfoMapStructArrayBuilder<P>,
            GroupInfoMapStructBuilder<P>,
        >,
    ) -> Result<P, Error> {
        let attr = ctx.attr();

        ctx.exchange().with_state(|state| {
            let mut entries = state
                .fabrics
                .iter()
                .filter(|fabric| !attr.fab_filter || fabric.fab_idx().get() == attr.fab_idx)
                .flat_map(|fabric| {
                    fabric
                        .groups()
                        .iter()
                        .map(move |entry| (fabric.fab_idx(), entry))
                });

            match builder {
                ArrayAttributeRead::ReadAll(mut builder) => {
                    for (fab_idx, entry) in entries {
                        let mut endpoints_builder =
                            builder.push()?.group_id(entry.group_id)?.endpoints()?;
                        for &ep in entry.endpoints.iter() {
                            endpoints_builder = endpoints_builder.push(&ep)?;
                        }
                        builder = endpoints_builder
                            .end()?
                            .group_name(Some(entry.group_name.as_str()))?
                            .fabric_index(Some(fab_idx.get()))?
                            .end()?;
                    }
                    builder.end()
                }
                ArrayAttributeRead::ReadOne(index, builder) => {
                    let Some((fab_idx, entry)) = entries.nth(index as usize) else {
                        return Err(ErrorCode::ConstraintError.into());
                    };
                    let mut endpoints_builder = builder.group_id(entry.group_id)?.endpoints()?;
                    for &ep in entry.endpoints.iter() {
                        endpoints_builder = endpoints_builder.push(&ep)?;
                    }
                    endpoints_builder
                        .end()?
                        .group_name(Some(entry.group_name.as_str()))?
                        .fabric_index(Some(fab_idx.get()))?
                        .end()
                }
                ArrayAttributeRead::ReadNone(builder) => builder.end(),
            }
        })
    }

    fn max_groups_per_fabric(&self, _ctx: impl ReadContext) -> Result<u16, Error> {
        Ok(MAX_GROUPS_PER_FABRIC as _)
    }

    fn max_group_keys_per_fabric(&self, _ctx: impl ReadContext) -> Result<u16, Error> {
        // +1 for IPK (key set 0)
        Ok(MAX_GROUP_KEYS_PER_FABRIC as u16 + 1)
    }

    fn set_group_key_map(
        &self,
        ctx: impl WriteContext,
        value: ArrayAttributeWrite<TLVArray<'_, GroupKeyMapStruct<'_>>, GroupKeyMapStruct<'_>>,
    ) -> Result<(), Error> {
        let fab_idx = NonZeroU8::new(ctx.attr().fab_idx).ok_or(ErrorCode::UnsupportedAccess)?;

        let mut persist = FabricPersist::new(ctx.kv());

        ctx.exchange().with_state(|state| {
            let fabric = state.fabrics.fabric_mut(fab_idx)?;

            match value {
                ArrayAttributeWrite::Replace(list) => {
                    // First validate all entries
                    let mut count: usize = 0;
                    for entry in &list {
                        count += 1;
                        if count > MAX_GROUP_KEYS_PER_FABRIC {
                            return Err(ErrorCode::Failure.into());
                        }
                        let entry = entry?;
                        // GroupKeySetID must not be 0
                        if entry.group_key_set_id()? == 0 {
                            return Err(ErrorCode::ConstraintError.into());
                        }
                    }

                    // Now replace all entries
                    let entries = list.into_iter().filter_map(|entry| {
                        let entry = entry.ok()?;
                        Some(GroupKeyMapping {
                            group_id: entry.group_id().ok()?,
                            group_key_set_id: entry.group_key_set_id().ok()?,
                        })
                    });

                    fabric.groups_mut().key_map_replace(entries)?;
                }
                ArrayAttributeWrite::Add(entry) => {
                    // GroupKeySetID must not be 0
                    if entry.group_key_set_id()? == 0 {
                        return Err(ErrorCode::ConstraintError.into());
                    }

                    fabric.groups_mut().key_map_add(GroupKeyMapping {
                        group_id: entry.group_id().map_err(|_| ErrorCode::InvalidCommand)?,
                        group_key_set_id: entry
                            .group_key_set_id()
                            .map_err(|_| ErrorCode::InvalidCommand)?,
                    })?;
                }
                _ => {
                    return Err(ErrorCode::InvalidAction.into());
                }
            }

            // NOTE: Not sure this is a spec-compliant behavor:
            // If the failsafe is armed for our fabric, we'll NOT persist the group key changes until commissioning is complete.
            // And we'll LOSE those changes if the failsafe times out before commissioning completes.
            if !state.failsafe.is_armed_for(fab_idx.get()) {
                persist.store(fabric)?;
            }

            ctx.exchange().matter().transport().notify_groups_changed();

            Ok(())
        })?;

        persist.run()
    }

    fn handle_key_set_write(
        &self,
        ctx: impl InvokeContext,
        request: KeySetWriteRequest<'_>,
    ) -> Result<(), Error> {
        let fab_idx = ctx.exchange().accessor()?.fab_idx()?;
        let key_set = request.group_key_set()?;

        let group_key_set_id = key_set.group_key_set_id()?;
        let group_key_security_policy = key_set.group_key_security_policy()?;

        // GroupKeySetID 0 is reserved for IPK
        if group_key_set_id == 0 {
            return Err(ErrorCode::InvalidCommand.into());
        }

        // Parse nullable epoch keys and start times
        let epoch_key_0 = key_set.epoch_key_0()?;
        let epoch_start_time_0 = key_set.epoch_start_time_0()?;
        let epoch_key_1 = key_set.epoch_key_1()?;
        let epoch_start_time_1 = key_set.epoch_start_time_1()?;
        let epoch_key_2 = key_set.epoch_key_2()?;
        let epoch_start_time_2 = key_set.epoch_start_time_2()?;

        // Validate EpochKey0 must not be null
        let Some(epoch_key_0_val) = epoch_key_0.as_opt_ref() else {
            return Err(ErrorCode::InvalidCommand.into());
        };

        // Validate EpochStartTime0 must not be null
        let Some(&epoch_start_time_0_val) = epoch_start_time_0.as_opt_ref() else {
            return Err(ErrorCode::InvalidCommand.into());
        };

        // Validate EpochStartTime0 must not be 0
        if epoch_start_time_0_val == 0 {
            return Err(ErrorCode::InvalidCommand.into());
        }

        // Validate EpochKey0 length must be 16
        if epoch_key_0_val.0.len() != AEAD_CANON_KEY_LEN {
            return Err(ErrorCode::ConstraintError.into());
        }

        let has_epoch_key_1 = epoch_key_1.as_opt_ref().is_some();
        let has_epoch_start_time_1 = epoch_start_time_1.as_opt_ref().is_some();

        // If one of key1/time1 is present, both must be present
        if has_epoch_key_1 != has_epoch_start_time_1 {
            return Err(ErrorCode::InvalidCommand.into());
        }

        let mut entry = GroupKeySet {
            group_key_set_id,
            group_key_security_policy: group_key_security_policy as u8,
            ..Default::default()
        };

        // Push epoch key 0
        let mut key0 = GroupEpochKeyEntry {
            epoch_key: Default::default(),
            epoch_start_time: epoch_start_time_0_val,
        };
        key0.epoch_key
            .try_load_from_slice(epoch_key_0_val.0)
            .map_err(|_| ErrorCode::ConstraintError)?;
        entry
            .epoch_keys
            .push(key0)
            .map_err(|_| Error::from(ErrorCode::ConstraintError))?;

        if has_epoch_key_1 {
            let epoch_key_1_val = epoch_key_1.as_opt_ref().unwrap();
            let &epoch_start_time_1_val = epoch_start_time_1.as_opt_ref().unwrap();

            // Validate key length
            if epoch_key_1_val.0.len() != AEAD_CANON_KEY_LEN {
                return Err(ErrorCode::ConstraintError.into());
            }

            // Validate time1 > time0
            if epoch_start_time_1_val <= epoch_start_time_0_val {
                return Err(ErrorCode::InvalidCommand.into());
            }

            let mut key1 = GroupEpochKeyEntry {
                epoch_key: Default::default(),
                epoch_start_time: epoch_start_time_1_val,
            };
            key1.epoch_key
                .try_load_from_slice(epoch_key_1_val.0)
                .map_err(|_| ErrorCode::ConstraintError)?;
            entry
                .epoch_keys
                .push(key1)
                .map_err(|_| Error::from(ErrorCode::ConstraintError))?;

            // Check epoch key 2
            let has_epoch_key_2 = epoch_key_2.as_opt_ref().is_some();
            let has_epoch_start_time_2 = epoch_start_time_2.as_opt_ref().is_some();

            if has_epoch_key_2 != has_epoch_start_time_2 {
                return Err(ErrorCode::InvalidCommand.into());
            }

            if has_epoch_key_2 {
                let epoch_key_2_val = epoch_key_2.as_opt_ref().unwrap();
                let &epoch_start_time_2_val = epoch_start_time_2.as_opt_ref().unwrap();

                // Validate key length
                if epoch_key_2_val.0.len() != AEAD_CANON_KEY_LEN {
                    return Err(ErrorCode::ConstraintError.into());
                }

                // Validate time2 > time1
                if epoch_start_time_2_val <= epoch_start_time_1_val {
                    return Err(ErrorCode::InvalidCommand.into());
                }

                let mut key2 = GroupEpochKeyEntry {
                    epoch_key: Default::default(),
                    epoch_start_time: epoch_start_time_2_val,
                };
                key2.epoch_key
                    .try_load_from_slice(epoch_key_2_val.0)
                    .map_err(|_| ErrorCode::ConstraintError)?;
                entry
                    .epoch_keys
                    .push(key2)
                    .map_err(|_| Error::from(ErrorCode::ConstraintError))?;
            }
        } else {
            // If key1 not present, key2 must not be present either
            let has_epoch_key_2 = epoch_key_2.as_opt_ref().is_some();
            let has_epoch_start_time_2 = epoch_start_time_2.as_opt_ref().is_some();

            if has_epoch_key_2 || has_epoch_start_time_2 {
                return Err(ErrorCode::InvalidCommand.into());
            }
        }

        let mut persist = FabricPersist::new(ctx.kv());

        ctx.exchange().with_state(|state| {
            let fabric = state.fabrics.fabric_mut(fab_idx)?;

            fabric.groups_mut().key_set_add(entry)?;

            // NOTE: Not sure this is a spec-compliant behavor:
            // If the failsafe is armed for our fabric, we'll NOT persist the group key changes until commissioning is complete.
            // And we'll LOSE those changes if the failsafe times out before commissioning completes.
            if !state.failsafe.is_armed_for(fab_idx.get()) {
                persist.store(fabric)?;
            }

            ctx.exchange().matter().transport().notify_groups_changed();

            Ok(())
        })?;

        ctx.notify_own_cluster_changed();

        persist.run()
    }

    fn handle_key_set_read<P: TLVBuilderParent>(
        &self,
        ctx: impl InvokeContext,
        request: KeySetReadRequest<'_>,
        response: KeySetReadResponseBuilder<P>,
    ) -> Result<P, Error> {
        let fab_idx = ctx.exchange().accessor()?.fab_idx()?;
        let group_key_set_id = request.group_key_set_id()?;

        ctx.exchange().with_state(|state| {
            let fabric = state.fabrics.fabric(fab_idx)?;

            // KeySet ID 0 is the IPK (Identity Protection Key); per Matter
            // Core spec it is always present once the
            // fabric has been added (`AddNOC`) and is reported here with
            // its epoch keys redacted to null. The IPK isn't kept in the
            // generic `key_sets` list — it lives on the fabric directly.
            // Any other ID is looked up in the per-fabric `key_sets` map.
            if group_key_set_id == 0 {
                return response
                    .group_key_set()?
                    .group_key_set_id(0)?
                    .group_key_security_policy(GroupKeySecurityPolicyEnum::TrustFirst)?
                    .epoch_key_0(Nullable::<Octets<'_>>::none())?
                    .epoch_start_time_0(Nullable::some(0))?
                    .epoch_key_1(Nullable::<Octets<'_>>::none())?
                    .epoch_start_time_1(Nullable::none())?
                    .epoch_key_2(Nullable::<Octets<'_>>::none())?
                    .epoch_start_time_2(Nullable::none())?
                    .end()?
                    .end();
            }

            let entry = fabric
                .groups()
                .key_set_get(group_key_set_id)
                .ok_or(ErrorCode::NotFound)?;

            // Build response: epoch keys are always null, start times are preserved
            response
                .group_key_set()?
                .group_key_set_id(group_key_set_id)?
                .group_key_security_policy(
                    // SAFETY: group_key_security_policy is validated at write time
                    // and the enum is #[repr(u8)]
                    unsafe {
                        core::mem::transmute::<u8, GroupKeySecurityPolicyEnum>(
                            entry.group_key_security_policy,
                        )
                    },
                )?
                .epoch_key_0(Nullable::<Octets<'_>>::none())?
                .epoch_start_time_0(Nullable::some(entry.epoch_keys[0].epoch_start_time))?
                .epoch_key_1(Nullable::<Octets<'_>>::none())?
                .epoch_start_time_1(if let Some(k) = entry.epoch_keys.get(1) {
                    Nullable::some(k.epoch_start_time)
                } else {
                    Nullable::none()
                })?
                .epoch_key_2(Nullable::<Octets<'_>>::none())?
                .epoch_start_time_2(if let Some(k) = entry.epoch_keys.get(2) {
                    Nullable::some(k.epoch_start_time)
                } else {
                    Nullable::none()
                })?
                .end()?
                .end()
        })
    }

    fn handle_key_set_remove(
        &self,
        ctx: impl InvokeContext,
        request: KeySetRemoveRequest<'_>,
    ) -> Result<(), Error> {
        let fab_idx = ctx.exchange().accessor()?.fab_idx()?;
        let group_key_set_id = request.group_key_set_id()?;

        // KeySetRemove of ID 0 (IPK) is not allowed
        if group_key_set_id == 0 {
            return Err(ErrorCode::InvalidCommand.into());
        }

        let mut persist = FabricPersist::new(ctx.kv());

        ctx.exchange().with_state(|state| {
            let fabric = state.fabrics.fabric_mut(fab_idx)?;

            fabric.groups_mut().key_set_remove(group_key_set_id)?;

            // NOTE: Not sure this is a spec-compliant behavor:
            // If the failsafe is armed for our fabric, we'll NOT persist the group key changes until commissioning is complete.
            // And we'll LOSE those changes if the failsafe times out before commissioning completes.
            if !state.failsafe.is_armed_for(fab_idx.get()) {
                persist.store(fabric)?;
            }

            ctx.exchange().matter().transport().notify_groups_changed();

            Ok(())
        })?;

        ctx.notify_own_cluster_changed();

        persist.run()
    }

    fn handle_key_set_read_all_indices<P: TLVBuilderParent>(
        &self,
        ctx: impl InvokeContext,
        response: KeySetReadAllIndicesResponseBuilder<P>,
    ) -> Result<P, Error> {
        let fab_idx = ctx.exchange().accessor()?.fab_idx()?;

        ctx.exchange().with_state(|state| {
            let fabric = state.fabrics.fabric(fab_idx)?;

            // Always include IPK (0) plus all stored key set IDs
            let mut ids = response.group_key_set_i_ds()?;
            ids = ids.push(&0u16)?;

            for entry in fabric.groups().key_set_iter() {
                ids = ids.push(&entry.group_key_set_id)?;
            }

            ids.end()?.end()
        })
    }
}