Skip to main content

matter_kit/clusters/
groupcast.rs

1//! Groupcast, cluster `0x0065` (Core §11.27). **Provisional.**
2//!
3//! > The Groupcast Cluster defines a unified, simpler, and more scalable mechanism for
4//! > configuring, managing, and using groups in Matter. It is designed to replace the legacy
5//! > Groups cluster.
6//!
7//! One cluster where there used to be three. §1.3's Groups held the membership, §11.2's Group
8//! Key Management held the keys and the map between them, and an administrator had to drive
9//! both in the right order on every endpoint. `JoinGroup` does all of it in one command: the
10//! group, the endpoints, the key set and — optionally — the key itself.
11//!
12//! # One multicast address instead of one per group
13//!
14//! §11.27.5.1's `IanaAddr` is the change that makes this scale. Every group uses `FF05::FA`, and
15//! a node "will then filter this traffic at the message layer by attempting decryption with its
16//! available group keys" — which is [`group`](crate::group)'s job anyway, because §4.17.3.6's
17//! Group Session ID never decided the key on its own.
18//!
19//! The alternative is there for the nodes that need it: `PerGroup` gives a group its own
20//! §2.5.6.2 address so a sleepy listener's radio filters the traffic instead of its CPU. §11.27.5.1
21//! says when: "groups with listener members that require extra filtering at the network layer,
22//! such as low power devices", and groups with pre-Groupcast members.
23//!
24//! # Sender and listener are different devices
25//!
26//! §11.27.4: `LN` and `SD` are separate features, and "being a sender does not imply the ability
27//! to listen to messages sent to those multicast addresses". A wall switch joins groups with an
28//! *empty* endpoint list — it has nothing to receive on — and a bulb joins with the endpoint the
29//! light is on. Getting that backwards is `CONSTRAINT_ERROR` on the command rather than a group
30//! that silently never works.
31//!
32//! # What is not here
33//!
34//! `GroupcastTesting` (§11.27.7.6) and its event, which exist so the Test Harness can make a
35//! node emit a groupcast on demand. It is a certification instrument rather than a product
36//! feature, and a device that shipped it would give any administrator a way to make it transmit.
37
38use core::cell::RefCell;
39
40use crate::clusters::generated::groupcast as spec_gc;
41use crate::config::Config;
42use crate::crypto::{SYMMETRIC_KEY_LENGTH_BYTES, SymmetricKey};
43use crate::dm::spec::{Conforming, Optional};
44use crate::dm::{Resolved, ResolvedCommand};
45use crate::group::keys::{EpochKey, GroupKeySecurityPolicy, GroupKeySet, GroupKeys, KeySetId};
46use crate::im::{
47    ClusterHandler, ClusterId, CommandId, EndpointId, InteractionContext, Status, StatusIb,
48};
49use crate::msg::{FabricIndex, GroupId};
50use crate::tlv::{Tag, TlvWriter};
51
52use super::Cluster;
53
54pub use spec_gc::attribute::{
55    FABRIC_UNDER_TEST, MAX_MCAST_ADDR_COUNT, MAX_MEMBERSHIP_COUNT, MEMBERSHIP,
56    USED_MCAST_ADDR_COUNT,
57};
58pub use spec_gc::command::{
59    CONFIGURE_AUXILIARY_ACL, JOIN_GROUP, LEAVE_GROUP, LEAVE_GROUP_RESPONSE, UPDATE_GROUP_KEY,
60};
61pub use spec_gc::{ID, MulticastAddrPolicyEnum, PICS, REVISION};
62
63/// `LN` (§11.27.4.1) — the node can join groups and receive what is sent to them.
64pub const FEATURE_LISTENER: u32 = 1 << 0;
65
66/// `SD` (§11.27.4.2) — the node can send to groups it belongs to.
67pub const FEATURE_SENDER: u32 = 1 << 1;
68
69/// `PGA` (§11.27.4, bit 2) — the node can use §2.5.6.2's per-group multicast addresses.
70pub const FEATURE_PER_GROUP_ADDRESS: u32 = 1 << 2;
71
72/// §11.27.7.1: "For Listeners, this field SHALL list at least 1 endpoint and up to 20
73/// endpoints."
74pub const MAX_JOIN_ENDPOINTS: usize = 20;
75
76/// §11.27.6.2: `MaxMembershipCount` has a constraint of "min 10".
77pub const MIN_MEMBERSHIP_COUNT: u16 = 10;
78
79/// Every element of §11.27 this crate serves, for the [`Optional`] a device declares.
80///
81/// The whole cluster is provisional (§2.13), so §7.3 marks *every* element `P` — which
82/// [`dm::spec`](crate::dm::spec) treats as optional, "a decision the product makes rather than
83/// one the conformance makes for it". A node that implements the cluster implements all of it,
84/// so this is that decision written once.
85///
86/// `ConfigureAuxiliaryACL` is in the list unconditionally: its conformance is `P, LN`, so on a
87/// sender-only node it is disallowed and naming it changes nothing. `GroupcastTesting` is not
88/// in it, for the reason the module documentation gives.
89pub const OPTIONAL: Optional<'static> = Optional {
90    attributes: &[
91        MEMBERSHIP,
92        MAX_MEMBERSHIP_COUNT,
93        MAX_MCAST_ADDR_COUNT,
94        USED_MCAST_ADDR_COUNT,
95        FABRIC_UNDER_TEST,
96    ],
97    commands: &[
98        JOIN_GROUP,
99        LEAVE_GROUP,
100        LEAVE_GROUP_RESPONSE,
101        UPDATE_GROUP_KEY,
102        CONFIGURE_AUXILIARY_ACL,
103    ],
104    events: &[],
105};
106
107/// One group this node belongs to (§11.27.5.4's `MembershipStruct`).
108#[derive(Debug, Clone, PartialEq, Eq)]
109pub struct Membership<const E: usize> {
110    /// The fabric it is scoped to.
111    pub fabric_index: FabricIndex,
112    /// "an identifier for the multicast group within the fabric", never zero.
113    pub group: GroupId,
114    /// The endpoints that receive the group's messages. Empty means sender-only.
115    pub endpoints: heapless::Vec<EndpointId, E>,
116    /// Which key set secures it — "maps directly to the GroupKeySetID as defined in the Group
117    /// Key Management cluster".
118    pub key_set: KeySetId,
119    /// Whether §11.27.10's auxiliary ACL entries were generated for it.
120    pub has_auxiliary_acl: bool,
121    /// How §2.5.6.2's address is built for it.
122    pub policy: MulticastAddrPolicyEnum,
123}
124
125/// The Groupcast cluster (§11.27).
126///
127/// `M` bounds the memberships and `E` the endpoints in one of them. The key material itself is
128/// [`GroupKeys`]'s, shared with
129/// [`group_key_management`](super::group_key_management) — §11.27.7.1's `Key` field creates a
130/// key set there, and §11.27.6.1 has the two attributes mirror each other.
131#[derive(Debug)]
132pub struct Groupcast<
133    'a,
134    C: Config,
135    const M: usize,
136    const E: usize,
137    const K: usize = 15,
138    const G: usize = 20,
139> {
140    keys: &'a RefCell<GroupKeys<C, K, G>>,
141    memberships: RefCell<heapless::Vec<Membership<E>, M>>,
142    feature_map: u32,
143    max_membership: u16,
144    max_addresses: u16,
145    fabric_under_test: core::cell::Cell<FabricIndex>,
146}
147
148impl<'a, C: Config, const M: usize, const E: usize, const K: usize, const G: usize>
149    Groupcast<'a, C, M, E, K, G>
150{
151    /// A cluster with no memberships, over the node's group keys.
152    ///
153    /// `feature_map` says which of `LN`, `SD` and `PGA` this node implements, and §11.27.4's
154    /// `O.a+` requires at least one of the first two — a node that is neither a listener nor a
155    /// sender has no business having the cluster.
156    #[must_use]
157    #[expect(
158        clippy::cast_possible_truncation,
159        reason = "§11.27.6.2's MaxMembershipCount is a uint16, and the branch above holds M to it"
160    )]
161    pub const fn new(keys: &'a RefCell<GroupKeys<C, K, G>>, feature_map: u32) -> Self {
162        Self {
163            keys,
164            memberships: RefCell::new(heapless::Vec::new()),
165            feature_map,
166            max_membership: if M > u16::MAX as usize {
167                u16::MAX
168            } else {
169                M as u16
170            },
171            max_addresses: 1,
172            fabric_under_test: core::cell::Cell::new(FabricIndex(0)),
173        }
174    }
175
176    /// How many §2.5.6.2 per-group addresses the node's radio can subscribe to
177    /// (§11.27.6.3's `MaxMcastAddrCount`, "min 1").
178    ///
179    /// One is the floor because `FF05::FA` alone is enough for every `IanaAddr` group; more is
180    /// what `PGA` needs.
181    #[must_use]
182    pub const fn with_max_addresses(mut self, max: u16) -> Self {
183        self.max_addresses = max;
184        self
185    }
186
187    /// The descriptor for an instance, derived from the specification's tables.
188    pub fn conforming(
189        feature_map: u32,
190        optional: &Optional<'_>,
191    ) -> crate::error::Result<Conforming<5, 6, 1, 1>> {
192        Conforming::new(&spec_gc::CLUSTER, feature_map, optional)
193    }
194
195    /// Every membership, for a device about to persist them or to subscribe to their addresses.
196    #[must_use]
197    pub fn memberships(&self) -> core::cell::Ref<'_, heapless::Vec<Membership<E>, M>> {
198        self.memberships.borrow()
199    }
200
201    /// Whether this node listens for group messages (§11.27.4.1).
202    #[must_use]
203    pub const fn is_listener(&self) -> bool {
204        self.feature_map & FEATURE_LISTENER != 0
205    }
206
207    /// Whether this node sends them (§11.27.4.2).
208    #[must_use]
209    pub const fn is_sender(&self) -> bool {
210        self.feature_map & FEATURE_SENDER != 0
211    }
212
213    /// §11.27.6.1's per-fabric ceiling: "the server SHALL limit the total number of GroupIDs
214    /// used across all entries in the Membership attribute to no more than half (rounded down)
215    /// of the MaxMembershipCount value."
216    ///
217    /// Half, so that one fabric cannot fill the table and leave a second ecosystem unable to
218    /// form a single group.
219    #[must_use]
220    pub const fn per_fabric_limit(&self) -> usize {
221        (self.max_membership / 2) as usize
222    }
223
224    /// Forgets every group one fabric joined — what `RemoveFabric` must do.
225    pub fn remove_fabric(&self, fabric: FabricIndex) {
226        self.memberships
227            .borrow_mut()
228            .retain(|m| m.fabric_index != fabric);
229    }
230
231    fn count_groups(&self, fabric: FabricIndex) -> usize {
232        self.memberships
233            .borrow()
234            .iter()
235            .filter(|m| m.fabric_index == fabric)
236            .count()
237    }
238}
239
240impl<C: Config, const M: usize, const E: usize, const K: usize, const G: usize> ClusterHandler
241    for Groupcast<'_, C, M, E, K, G>
242{
243    /// §11.27.6.1: memberships are fabric-scoped, and a stale one keeps this node listening
244    /// on a multicast address for a fabric it has left.
245    fn on_lifecycle(&self, event: crate::im::Lifecycle) {
246        if let crate::im::Lifecycle::FabricRemoved(fabric) = event {
247            self.remove_fabric(fabric);
248        }
249    }
250    fn read(
251        &self,
252        resolved: &Resolved<'_>,
253        ctx: &InteractionContext<'_>,
254        w: &mut TlvWriter<'_>,
255        tag: Tag,
256    ) -> core::result::Result<(), Status> {
257        let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
258        match resolved.attribute {
259            MAX_MEMBERSHIP_COUNT => full(w.unsigned(tag, u64::from(self.max_membership))),
260            MAX_MCAST_ADDR_COUNT => full(w.unsigned(tag, u64::from(self.max_addresses))),
261            USED_MCAST_ADDR_COUNT => {
262                // §11.27.6.4: how many addresses are actually subscribed. Every `IanaAddr` group
263                // shares `FF05::FA`, so the count is one for all of them together plus one per
264                // `PerGroup` group — which is the whole argument for `IanaAddr`.
265                let memberships = self.memberships.borrow();
266                let per_group = memberships
267                    .iter()
268                    .filter(|m| m.policy == MulticastAddrPolicyEnum::PerGroup)
269                    .count();
270                let iana = usize::from(
271                    memberships
272                        .iter()
273                        .any(|m| m.policy == MulticastAddrPolicyEnum::IanaAddr),
274                );
275                full(w.unsigned(tag, (per_group.saturating_add(iana)) as u64))
276            }
277            FABRIC_UNDER_TEST => full(w.unsigned(tag, u64::from(self.fabric_under_test.get().0))),
278            MEMBERSHIP => {
279                let memberships = self.memberships.borrow();
280                full(w.start_array(tag))?;
281                for entry in memberships
282                    .iter()
283                    .filter(|m| !ctx.fabric_filtered || ctx.fabric_index == Some(m.fabric_index))
284                {
285                    full(w.start_structure(Tag::Anonymous))?;
286                    full(w.unsigned(Tag::Context(0), u64::from(entry.group.0)))?;
287                    if self.is_listener() {
288                        full(w.start_array(Tag::Context(1)))?;
289                        for endpoint in &entry.endpoints {
290                            full(w.unsigned(Tag::Anonymous, u64::from(*endpoint)))?;
291                        }
292                        full(w.end_container())?;
293                    }
294                    full(w.unsigned(Tag::Context(2), u64::from(entry.key_set)))?;
295                    if self.is_listener() {
296                        full(w.bool(Tag::Context(3), entry.has_auxiliary_acl))?;
297                    }
298                    full(w.unsigned(Tag::Context(4), u64::from(entry.policy.value())))?;
299                    full(w.unsigned(Tag::Context(254), u64::from(entry.fabric_index.0)))?;
300                    full(w.end_container())?;
301                }
302                full(w.end_container())
303            }
304            _ => Err(Status::UnsupportedAttribute),
305        }
306    }
307
308    fn invoke(
309        &self,
310        resolved: &ResolvedCommand<'_>,
311        fields: Option<&[u8]>,
312        ctx: &InteractionContext<'_>,
313        w: &mut TlvWriter<'_>,
314        tag: Tag,
315    ) -> core::result::Result<Option<CommandId>, StatusIb> {
316        // §11.27.7: every command is `F`.
317        let fabric = ctx
318            .fabric_index
319            .filter(|f| f.0 != 0)
320            .ok_or(StatusIb::from(Status::UnsupportedAccess))?;
321        let payload = fields.ok_or(StatusIb::from(Status::InvalidCommand))?;
322        match resolved.command.id {
323            JOIN_GROUP => self.join(fabric, payload, ctx),
324            LEAVE_GROUP => self.leave(fabric, payload, w, tag),
325            UPDATE_GROUP_KEY => self.update_key(fabric, payload),
326            CONFIGURE_AUXILIARY_ACL => self.configure_auxiliary_acl(fabric, payload),
327            _ => Err(Status::UnsupportedCommand.into()),
328        }
329    }
330}
331
332impl<C: Config, const M: usize, const E: usize, const K: usize, const G: usize>
333    Groupcast<'_, C, M, E, K, G>
334{
335    /// §11.27.7.1, in the order the specification lists the steps.
336    fn join(
337        &self,
338        fabric: FabricIndex,
339        payload: &[u8],
340        ctx: &InteractionContext<'_>,
341    ) -> core::result::Result<Option<CommandId>, StatusIb> {
342        let decoded: spec_gc::JoinGroupFields<'_> = super::decode_fields(payload)?;
343        // §11.27.5.4: `GroupID` has a constraint of "min 1", and §11.27.7.2 gives 0 a different
344        // meaning entirely — "all groups on the node for this fabric".
345        if decoded.group_id.0 == 0 || decoded.key_set_id == 0 {
346            return Err(Status::ConstraintError.into());
347        }
348
349        let mut endpoints: heapless::Vec<EndpointId, E> = heapless::Vec::new();
350        for endpoint in decoded.endpoints.iter() {
351            let endpoint = endpoint.map_err(|_| StatusIb::from(Status::InvalidCommand))?;
352            // Step 3c: "If any endpoint is invalid or is the RootEndpoint (Endpoint 0), the
353            // server SHALL stop command processing and SHALL return with status
354            // UNSUPPORTED_ENDPOINT" — groupcast never reaches the root endpoint's clusters.
355            if endpoint == 0 {
356                return Err(Status::UnsupportedEndpoint.into());
357            }
358            if endpoints.contains(&endpoint) {
359                // Step 6a/6b: "omitting duplicates".
360                continue;
361            }
362            if endpoints.len() >= MAX_JOIN_ENDPOINTS {
363                return Err(Status::ConstraintError.into());
364            }
365            endpoints
366                .push(endpoint)
367                .map_err(|_| StatusIb::from(Status::ResourceExhausted))?;
368        }
369
370        // Steps 2a and 3a: the feature map decides which shape of join is legal.
371        if endpoints.is_empty() && !self.is_sender() {
372            return Err(Status::ConstraintError.into());
373        }
374        if !endpoints.is_empty() && !self.is_listener() {
375            return Err(Status::ConstraintError.into());
376        }
377        // Step 3d: "If the UseAuxiliaryACL field is provided and the command was invoked by a
378        // client that does not have at least Administer privilege granted" — the command itself
379        // is `M`, so this field is the one part of it an administrator alone may use.
380        // `None` means the caller did not compute a privilege, and this is the cautious branch:
381        // the field generates ACL entries, so "not known to be Administer" is refused.
382        if decoded.use_auxiliary_acl.is_some()
383            && !ctx
384                .privilege
385                .is_some_and(|granted| granted.grants(crate::dm::access::Privilege::Administer))
386        {
387            return Err(Status::UnsupportedAccess.into());
388        }
389        let policy = decoded
390            .mcast_addr_policy
391            .unwrap_or(MulticastAddrPolicyEnum::IanaAddr);
392        if policy == MulticastAddrPolicyEnum::PerGroup
393            && self.feature_map & FEATURE_PER_GROUP_ADDRESS == 0
394        {
395            return Err(Status::ConstraintError.into());
396        }
397
398        self.install_key(fabric, decoded.key_set_id, decoded.key)?;
399
400        let existing = self.find(fabric, decoded.group_id);
401        if existing.is_none() {
402            // Step 1, and §11.27.6.1's per-fabric half.
403            if self.count_groups(fabric) >= self.per_fabric_limit() {
404                return Err(Status::ResourceExhausted.into());
405            }
406        }
407
408        let mut memberships = self.memberships.borrow_mut();
409        match memberships
410            .iter_mut()
411            .find(|m| m.fabric_index == fabric && m.group == decoded.group_id)
412        {
413            Some(entry) => {
414                // Step 6a: `ReplaceEndpoints` true overwrites; otherwise the list is appended to,
415                // "omitting duplicates".
416                if decoded.replace_endpoints == Some(true) {
417                    entry.endpoints.clear();
418                }
419                for endpoint in &endpoints {
420                    if !entry.endpoints.contains(endpoint)
421                        && entry.endpoints.push(*endpoint).is_err()
422                    {
423                        return Err(Status::ResourceExhausted.into());
424                    }
425                }
426                entry.key_set = decoded.key_set_id;
427                entry.policy = policy;
428                if let Some(use_acl) = decoded.use_auxiliary_acl {
429                    entry.has_auxiliary_acl = use_acl;
430                }
431            }
432            None => {
433                memberships
434                    .push(Membership {
435                        fabric_index: fabric,
436                        group: decoded.group_id,
437                        endpoints,
438                        key_set: decoded.key_set_id,
439                        has_auxiliary_acl: decoded.use_auxiliary_acl.unwrap_or(false),
440                        policy,
441                    })
442                    .map_err(|_| StatusIb::from(Status::ResourceExhausted))?;
443            }
444        }
445        drop(memberships);
446
447        // §11.27.9: the group's key set and the §11.2 map move together, so a group joined here
448        // is one [`group::wire`](crate::group::wire) can already send to and receive on.
449        self.keys
450            .borrow_mut()
451            .map_group(fabric, decoded.group_id, decoded.key_set_id)?;
452        Ok(None)
453    }
454
455    /// §11.27.7.2, whose response says which endpoints actually left.
456    fn leave(
457        &self,
458        fabric: FabricIndex,
459        payload: &[u8],
460        w: &mut TlvWriter<'_>,
461        tag: Tag,
462    ) -> core::result::Result<Option<CommandId>, StatusIb> {
463        let decoded: spec_gc::LeaveGroupFields<'_> = super::decode_fields(payload)?;
464        let full = |r: crate::error::Result<()>| r.map_err(|_| StatusIb::from(Status::Failure));
465
466        // Step 1: "If the GroupID is 0x00 … all groups on the node for this fabric are affected."
467        if decoded.group_id.0 == 0 {
468            if self.count_groups(fabric) == 0 {
469                return Err(Status::NotFound.into());
470            }
471            let groups: heapless::Vec<GroupId, M> = self
472                .memberships
473                .borrow()
474                .iter()
475                .filter(|m| m.fabric_index == fabric)
476                .map(|m| m.group)
477                .collect();
478            for group in groups {
479                self.forget(fabric, group);
480            }
481            // §11.27.7.3: the response's Endpoints "SHALL be an empty list if … The GroupID
482            // field is 0, indicating multiple groups were affected, resulting in ambiguous
483            // Endpoints list content."
484            full(w.start_structure(tag))?;
485            full(w.unsigned(Tag::Context(0), 0))?;
486            full(w.start_array(Tag::Context(1)))?;
487            full(w.end_container())?;
488            full(w.end_container())?;
489            return Ok(Some(LEAVE_GROUP_RESPONSE));
490        }
491
492        // Steps 2 and 3.
493        if self.find(fabric, decoded.group_id).is_none() {
494            return Err(Status::NotFound.into());
495        }
496
497        let mut removed: heapless::Vec<EndpointId, E> = heapless::Vec::new();
498        match decoded.endpoints {
499            // Step 4: a partial withdrawal.
500            Some(list) => {
501                let mut memberships = self.memberships.borrow_mut();
502                if let Some(entry) = memberships
503                    .iter_mut()
504                    .find(|m| m.fabric_index == fabric && m.group == decoded.group_id)
505                {
506                    for endpoint in list.iter() {
507                        let Ok(endpoint) = endpoint else { continue };
508                        // Step 4b: "If a listed endpoint is not a member of the group, the
509                        // server SHALL ignore it … the ignored endpoints SHALL be excluded from
510                        // the LeaveGroupResponse."
511                        if entry.endpoints.contains(&endpoint) {
512                            entry.endpoints.retain(|e| *e != endpoint);
513                            let _ = removed.push(endpoint);
514                        }
515                    }
516                }
517                let emptied = memberships.iter().any(|m| {
518                    m.fabric_index == fabric
519                        && m.group == decoded.group_id
520                        && m.endpoints.is_empty()
521                });
522                drop(memberships);
523                // Step 4c: "If a Membership entry is left with no endpoints, and the device is a
524                // Listener only" — a sender still belongs to the group with no endpoints at all,
525                // which is exactly what §11.27.5.4 describes.
526                if emptied && !self.is_sender() {
527                    self.forget(fabric, decoded.group_id);
528                }
529            }
530            // Step 5: the whole group.
531            None => {
532                if let Some(entry) = self.find(fabric, decoded.group_id) {
533                    removed = entry.endpoints;
534                }
535                self.forget(fabric, decoded.group_id);
536            }
537        }
538
539        full(w.start_structure(tag))?;
540        full(w.unsigned(Tag::Context(0), u64::from(decoded.group_id.0)))?;
541        full(w.start_array(Tag::Context(1)))?;
542        for endpoint in &removed {
543            full(w.unsigned(Tag::Anonymous, u64::from(*endpoint)))?;
544        }
545        full(w.end_container())?;
546        full(w.end_container())?;
547        Ok(Some(LEAVE_GROUP_RESPONSE))
548    }
549
550    /// §11.27.7.4.
551    fn update_key(
552        &self,
553        fabric: FabricIndex,
554        payload: &[u8],
555    ) -> core::result::Result<Option<CommandId>, StatusIb> {
556        let decoded: spec_gc::UpdateGroupKeyFields<'_> = super::decode_fields(payload)?;
557        if decoded.group_id.0 == 0 || decoded.key_set_id == 0 {
558            return Err(Status::ConstraintError.into());
559        }
560        // Step 1: the group has to exist first. Updating the key of a group this node has not
561        // joined would install a key nothing uses.
562        if self.find(fabric, decoded.group_id).is_none() {
563            return Err(Status::NotFound.into());
564        }
565        self.install_key(fabric, decoded.key_set_id, decoded.key)?;
566        if let Some(entry) = self
567            .memberships
568            .borrow_mut()
569            .iter_mut()
570            .find(|m| m.fabric_index == fabric && m.group == decoded.group_id)
571        {
572            entry.key_set = decoded.key_set_id;
573        }
574        self.keys
575            .borrow_mut()
576            .map_group(fabric, decoded.group_id, decoded.key_set_id)?;
577        Ok(None)
578    }
579
580    /// §11.27.7.5.
581    fn configure_auxiliary_acl(
582        &self,
583        fabric: FabricIndex,
584        payload: &[u8],
585    ) -> core::result::Result<Option<CommandId>, StatusIb> {
586        let decoded: spec_gc::ConfigureAuxiliaryACLFields = super::decode_fields(payload)?;
587        let mut memberships = self.memberships.borrow_mut();
588        let Some(entry) = memberships
589            .iter_mut()
590            .find(|m| m.fabric_index == fabric && m.group == decoded.group_id)
591        else {
592            return Err(Status::NotFound.into());
593        };
594        entry.has_auxiliary_acl = decoded.use_auxiliary_acl;
595        Ok(None)
596    }
597
598    /// §11.27.7.1 steps 4 and 5, and §11.27.7.4 steps 2 and 3 — the same rule twice.
599    ///
600    /// A `Key` creates the key set; no `Key` requires one to exist already. Either way the
601    /// **input** key is not kept: §11.27.7.1, "the InputKey itself SHALL NOT be stored", so what
602    /// goes into [`GroupKeys`] is the epoch key and what comes out is the operational one.
603    fn install_key(
604        &self,
605        fabric: FabricIndex,
606        key_set: KeySetId,
607        key: Option<&[u8]>,
608    ) -> core::result::Result<(), Status> {
609        let mut keys = self.keys.borrow_mut();
610        match key {
611            Some(key) => {
612                if key.len() != SYMMETRIC_KEY_LENGTH_BYTES {
613                    return Err(Status::ConstraintError);
614                }
615                // "This key SHALL be new for the group, with a unique KeySetID that does not
616                // exist on the node yet."
617                if keys.key_set(fabric, key_set).is_some() {
618                    return Err(Status::AlreadyExists);
619                }
620                let bytes = <[u8; SYMMETRIC_KEY_LENGTH_BYTES]>::try_from(key)
621                    .map_err(|_| Status::ConstraintError)?;
622                let mut epoch_keys = heapless::Vec::new();
623                epoch_keys
624                    .push(EpochKey {
625                        key: SymmetricKey::new(bytes),
626                        // §11.27.7.1 spells the synthesised key set out: TrustFirst,
627                        // EpochStartTime0 = 1, and the other two slots null.
628                        start_time_us: 1,
629                    })
630                    .map_err(|_| Status::ResourceExhausted)?;
631                keys.write_key_set(GroupKeySet {
632                    fabric_index: fabric,
633                    id: key_set,
634                    policy: GroupKeySecurityPolicy::TrustFirst,
635                    epoch_keys,
636                })
637            }
638            // "The server SHALL verify that the KeySetID field maps to an existing
639            // OperationalGroupKey of the fabric. Otherwise … NOT_FOUND."
640            None if keys.key_set(fabric, key_set).is_none() => Err(Status::NotFound),
641            None => Ok(()),
642        }
643    }
644
645    fn find(&self, fabric: FabricIndex, group: GroupId) -> Option<Membership<E>> {
646        self.memberships
647            .borrow()
648            .iter()
649            .find(|m| m.fabric_index == fabric && m.group == group)
650            .cloned()
651    }
652
653    /// Removes a group and everything that hangs off it (§11.27.7.2 steps 4c and 5).
654    fn forget(&self, fabric: FabricIndex, group: GroupId) {
655        let key_set = self.find(fabric, group).map(|m| m.key_set);
656        self.memberships
657            .borrow_mut()
658            .retain(|m| !(m.fabric_index == fabric && m.group == group));
659        let mut keys = self.keys.borrow_mut();
660        let remaining: heapless::Vec<_, 32> = keys
661            .map()
662            .iter()
663            .filter(|(f, g, _)| *f == fabric && *g != group)
664            .map(|(_, g, set)| (*g, *set))
665            .collect();
666        let _ = keys.replace_map(fabric, &remaining);
667        // "The server SHALL also delete all operational group keys of the removed group" — but
668        // only when nothing else is still using the key set, since §11.27.7.1 lets several
669        // groups share one.
670        if let Some(key_set) = key_set
671            && !self
672                .memberships
673                .borrow()
674                .iter()
675                .any(|m| m.fabric_index == fabric && m.key_set == key_set)
676        {
677            let _ = keys.remove_key_set(fabric, key_set);
678        }
679    }
680}
681
682/// So a tuple of clusters can dispatch to it by id.
683impl<C: Config, const M: usize, const E: usize, const K: usize, const G: usize> Cluster
684    for Groupcast<'_, C, M, E, K, G>
685{
686    const ID: ClusterId = ID;
687}