Skip to main content

matter_kit/clusters/tls/
client_management.rs

1//! TLS Client Management, cluster `0x0802` (Core §14.5).
2//!
3//! > This Cluster is used to provision TLS Endpoints with enough information to facilitate
4//! > subsequent connection.
5//!
6//! A TLS endpoint is a hostname, a port, the root CA to authenticate the server with, and
7//! optionally the client certificate to present. Nothing here opens a connection: §14.5 is
8//! configuration, and the clusters that actually connect — Camera AV Stream Management, WebRTC
9//! — name an endpoint id and let the platform's TLS stack do the rest.
10//!
11//! # Five cluster-specific status codes, because `FAILURE` would say nothing
12//!
13//! §14.5.5.1 defines its own codes, and they are the difference between an administrator who
14//! can fix the problem and one who cannot: `RootCertificateNotFound` means provision the CA
15//! first, `EndpointAlreadyInstalled` means this host and port are already configured,
16//! `InvalidTime` means the clock has not been set yet. All five ride in a `StatusIb`'s
17//! `ClusterStatus` beside §8.10's `FAILURE`, because none of these commands has a response to
18//! put them in.
19//!
20//! # An endpoint in use cannot be removed
21//!
22//! §14.5.4.2's `ReferenceCount` is "the number of entities currently using this TLS Endpoint",
23//! and §14.5.7.5 refuses to remove one that is non-zero. The count is the application's to keep
24//! — "The node SHALL recompute this field to reflect the correct value at runtime" — through
25//! [`TlsTables::set_reference_count`]; the refusal is this cluster's.
26
27use crate::clusters::generated::tls_client_management as spec_tls;
28use crate::dm::spec::{Conforming, Optional};
29use crate::dm::{Resolved, ResolvedCommand};
30use crate::im::{ClusterHandler, ClusterId, CommandId, InteractionContext, Status, StatusIb};
31use crate::msg::FabricIndex;
32use crate::tlv::{Tag, TlvWriter, ToTlv};
33
34use super::{EndpointEntry, HOSTNAME_MAX, HOSTNAME_MIN, TlsEndpointId, TlsTables, visible};
35use crate::clusters::Cluster;
36
37pub use spec_tls::attribute::{MAX_PROVISIONED, PROVISIONED_ENDPOINTS};
38pub use spec_tls::command::{
39    FIND_ENDPOINT, FIND_ENDPOINT_RESPONSE, PROVISION_ENDPOINT, PROVISION_ENDPOINT_RESPONSE,
40    REMOVE_ENDPOINT,
41};
42pub use spec_tls::{ID, PICS, REVISION, StatusCodeEnum};
43
44/// The TLS Client Management cluster (§14.5).
45///
46/// It needs no hooks: an endpoint is four small fields, and the certificates it names belong to
47/// [`certificate_management`](super::certificate_management).
48#[derive(Debug)]
49pub struct ClientManagement<'a, const R: usize, const C: usize, const E: usize> {
50    tables: &'a TlsTables<R, C, E>,
51}
52
53impl<'a, const R: usize, const C: usize, const E: usize> ClientManagement<'a, R, C, E> {
54    /// A cluster over shared tables.
55    #[must_use]
56    pub const fn new(tables: &'a TlsTables<R, C, E>) -> Self {
57        Self { tables }
58    }
59
60    /// The descriptor for an instance, derived from the specification's tables.
61    pub fn conforming(
62        feature_map: u32,
63        optional: &Optional<'_>,
64    ) -> crate::error::Result<Conforming<2, 3, 2, 0>> {
65        Conforming::new(&spec_tls::CLUSTER, feature_map, optional)
66    }
67
68    /// The tables this cluster shares with
69    /// [`certificate_management`](super::certificate_management).
70    #[must_use]
71    pub const fn tables(&self) -> &'a TlsTables<R, C, E> {
72        self.tables
73    }
74}
75
76/// One of §14.5.5.1's cluster-specific codes, as a `FAILURE` with a `ClusterStatus`.
77fn cluster_status(code: StatusCodeEnum) -> StatusIb {
78    StatusIb::cluster_failure(code.value())
79}
80
81impl<const R: usize, const C: usize, const E: usize> ClusterHandler
82    for ClientManagement<'_, R, C, E>
83{
84    fn read(
85        &self,
86        resolved: &Resolved<'_>,
87        ctx: &InteractionContext<'_>,
88        w: &mut TlvWriter<'_>,
89        tag: Tag,
90    ) -> Result<(), Status> {
91        let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
92        match resolved.attribute {
93            MAX_PROVISIONED => full(w.unsigned(tag, u64::from(self.tables.max_endpoints()))),
94            PROVISIONED_ENDPOINTS => {
95                let endpoints = self.tables.endpoints();
96                full(w.start_array(tag))?;
97                for endpoint in endpoints.iter().filter(|e| visible(ctx, e.fabric_index)) {
98                    full(encode_endpoint(endpoint, w, Tag::Anonymous))?;
99                }
100                full(w.end_container())
101            }
102            _ => Err(Status::UnsupportedAttribute),
103        }
104    }
105
106    fn invoke(
107        &self,
108        resolved: &ResolvedCommand<'_>,
109        fields: Option<&[u8]>,
110        ctx: &InteractionContext<'_>,
111        w: &mut TlvWriter<'_>,
112        tag: Tag,
113    ) -> Result<Option<CommandId>, StatusIb> {
114        // Every command in §14.5.7 is `F`.
115        let fabric = ctx
116            .fabric_index
117            .filter(|f| f.0 != 0)
118            .ok_or(StatusIb::from(Status::UnsupportedAccess))?;
119        let payload = fields.ok_or(StatusIb::from(Status::InvalidCommand))?;
120        match resolved.command.id {
121            PROVISION_ENDPOINT => self.provision(fabric, payload, w, tag),
122            FIND_ENDPOINT => self.find(fabric, payload, w, tag),
123            REMOVE_ENDPOINT => self.remove(fabric, payload),
124            _ => Err(Status::UnsupportedCommand.into()),
125        }
126    }
127}
128
129impl<const R: usize, const C: usize, const E: usize> ClientManagement<'_, R, C, E> {
130    /// §14.5.7.1, in the order the specification lists the checks.
131    fn provision(
132        &self,
133        fabric: FabricIndex,
134        payload: &[u8],
135        w: &mut TlvWriter<'_>,
136        tag: Tag,
137    ) -> Result<Option<CommandId>, StatusIb> {
138        let decoded: spec_tls::ProvisionEndpointFields<'_> =
139            crate::clusters::decode_fields(payload)?;
140        // §14.5.4.2's constraints: a hostname of "4 to 253" and a port of "1 to 65535" — port 0
141        // is not a port, and a node that stored one would try to connect to it.
142        if !(HOSTNAME_MIN..=HOSTNAME_MAX).contains(&decoded.hostname.len()) || decoded.port == 0 {
143            return Err(Status::ConstraintError.into());
144        }
145        // "If the UTCTime attribute of the Time Synchronization cluster is null: Fail the
146        // command with the cluster-specific status code of InvalidTime."
147        if !self.tables.time_known() {
148            return Err(cluster_status(StatusCodeEnum::InvalidTime));
149        }
150        // The root certificate has to exist, on this fabric. Both failures are one code, the
151        // same way §14.4.6 folds "not found" and "not yours" into `NOT_FOUND`.
152        if !self
153            .tables
154            .roots()
155            .iter()
156            .any(|r| r.caid == decoded.caid && r.fabric_index == fabric)
157        {
158            return Err(cluster_status(StatusCodeEnum::RootCertificateNotFound));
159        }
160        let ccdid = decoded.ccdid.0;
161        if let Some(ccdid) = ccdid
162            && !self
163                .tables
164                .clients()
165                .iter()
166                .any(|c| c.ccdid == ccdid && c.fabric_index == fabric)
167        {
168            return Err(cluster_status(StatusCodeEnum::ClientCertificateNotFound));
169        }
170
171        let endpoint_id = match decoded.endpoint_id.0 {
172            None => {
173                if self.tables.count_endpoints(fabric) >= usize::from(self.tables.max_endpoints()) {
174                    return Err(Status::ResourceExhausted.into());
175                }
176                if self.host_taken(fabric, decoded.hostname, decoded.port, None) {
177                    return Err(cluster_status(StatusCodeEnum::EndpointAlreadyInstalled));
178                }
179                let taken = |candidate: TlsEndpointId| {
180                    self.tables
181                        .endpoints()
182                        .iter()
183                        .any(|e| e.endpoint_id == candidate)
184                };
185                let endpoint_id =
186                    TlsTables::<R, C, E>::allocate(&self.tables.next_endpoint_id, taken)
187                        .ok_or(StatusIb::from(Status::ResourceExhausted))?;
188                let mut hostname = heapless::Vec::new();
189                hostname
190                    .extend_from_slice(decoded.hostname)
191                    .map_err(|_| StatusIb::from(Status::ConstraintError))?;
192                self.tables
193                    .endpoints
194                    .borrow_mut()
195                    .push(EndpointEntry {
196                        fabric_index: fabric,
197                        endpoint_id,
198                        hostname,
199                        port: decoded.port,
200                        caid: decoded.caid,
201                        ccdid,
202                        // "Set the ReferenceCount field to 0."
203                        reference_count: 0,
204                    })
205                    .map_err(|_| StatusIb::from(Status::ResourceExhausted))?;
206                endpoint_id
207            }
208            Some(endpoint_id) => {
209                if !self
210                    .tables
211                    .endpoints()
212                    .iter()
213                    .any(|e| e.endpoint_id == endpoint_id && e.fabric_index == fabric)
214                {
215                    return Err(Status::NotFound.into());
216                }
217                // "If *another* entry exists for the passed in Hostname / Port combination" —
218                // rewriting an endpoint to the host it already has is not a collision with
219                // itself.
220                if self.host_taken(fabric, decoded.hostname, decoded.port, Some(endpoint_id)) {
221                    return Err(cluster_status(StatusCodeEnum::EndpointAlreadyInstalled));
222                }
223                let mut endpoints = self.tables.endpoints.borrow_mut();
224                let Some(entry) = endpoints
225                    .iter_mut()
226                    .find(|e| e.endpoint_id == endpoint_id && e.fabric_index == fabric)
227                else {
228                    return Err(Status::NotFound.into());
229                };
230                entry.hostname.clear();
231                entry
232                    .hostname
233                    .extend_from_slice(decoded.hostname)
234                    .map_err(|_| StatusIb::from(Status::ConstraintError))?;
235                entry.port = decoded.port;
236                entry.caid = decoded.caid;
237                entry.ccdid = ccdid;
238                endpoint_id
239            }
240        };
241        spec_tls::ProvisionEndpointResponseFields { endpoint_id }
242            .to_tlv(w, tag)
243            .map_err(|_| StatusIb::from(Status::Failure))?;
244        Ok(Some(PROVISION_ENDPOINT_RESPONSE))
245    }
246
247    /// §14.5.7.3.
248    fn find(
249        &self,
250        fabric: FabricIndex,
251        payload: &[u8],
252        w: &mut TlvWriter<'_>,
253        tag: Tag,
254    ) -> Result<Option<CommandId>, StatusIb> {
255        let decoded: spec_tls::FindEndpointFields = crate::clusters::decode_fields(payload)?;
256        if self.tables.endpoints().is_empty() {
257            return Err(Status::NotFound.into());
258        }
259        let endpoints = self.tables.endpoints();
260        let entry = endpoints
261            .iter()
262            .find(|e| e.endpoint_id == decoded.endpoint_id && e.fabric_index == fabric)
263            .ok_or(StatusIb::from(Status::NotFound))?;
264        let full = |r: crate::error::Result<()>| r.map_err(|_| StatusIb::from(Status::Failure));
265        full(w.start_structure(tag))?;
266        full(encode_endpoint(entry, w, Tag::Context(0)))?;
267        full(w.end_container())?;
268        Ok(Some(FIND_ENDPOINT_RESPONSE))
269    }
270
271    /// §14.5.7.5.
272    fn remove(&self, fabric: FabricIndex, payload: &[u8]) -> Result<Option<CommandId>, StatusIb> {
273        let decoded: spec_tls::RemoveEndpointFields = crate::clusters::decode_fields(payload)?;
274        if self.tables.endpoints().is_empty() {
275            return Err(Status::NotFound.into());
276        }
277        let found = self
278            .tables
279            .endpoints()
280            .iter()
281            .find(|e| e.endpoint_id == decoded.endpoint_id && e.fabric_index == fabric)
282            .map(|e| e.reference_count)
283            .ok_or(StatusIb::from(Status::NotFound))?;
284        // "If the ReferenceCount of that matching entry is greater than 0: Fail the command
285        // with the status code INVALID_IN_STATE." Something is connected through it.
286        if found > 0 {
287            return Err(Status::InvalidInState.into());
288        }
289        self.tables
290            .endpoints
291            .borrow_mut()
292            .retain(|e| !(e.endpoint_id == decoded.endpoint_id && e.fabric_index == fabric));
293        Ok(None)
294    }
295
296    /// Whether this fabric already has an endpoint for `hostname` and `port`, ignoring `except`.
297    fn host_taken(
298        &self,
299        fabric: FabricIndex,
300        hostname: &[u8],
301        port: u16,
302        except: Option<TlsEndpointId>,
303    ) -> bool {
304        self.tables.endpoints().iter().any(|e| {
305            e.fabric_index == fabric
306                && e.port == port
307                && e.hostname == hostname
308                && except != Some(e.endpoint_id)
309        })
310    }
311}
312
313/// §14.5.4.2's `TLSEndpointStruct`.
314fn encode_endpoint(
315    entry: &EndpointEntry,
316    w: &mut TlvWriter<'_>,
317    tag: Tag,
318) -> crate::error::Result<()> {
319    w.start_structure(tag)?;
320    w.unsigned(Tag::Context(0), u64::from(entry.endpoint_id))?;
321    w.octets(Tag::Context(1), &entry.hostname)?;
322    w.unsigned(Tag::Context(2), u64::from(entry.port))?;
323    w.unsigned(Tag::Context(3), u64::from(entry.caid))?;
324    match entry.ccdid {
325        // §14.5.4.2: "A NULL value means no client certificate is used with this endpoint."
326        Some(ccdid) => w.unsigned(Tag::Context(4), u64::from(ccdid))?,
327        None => w.null(Tag::Context(4))?,
328    }
329    w.unsigned(Tag::Context(5), u64::from(entry.reference_count))?;
330    w.unsigned(Tag::Context(254), u64::from(entry.fabric_index.0))?;
331    w.end_container()
332}
333
334/// So a tuple of clusters can dispatch to it by id.
335impl<const R: usize, const C: usize, const E: usize> Cluster for ClientManagement<'_, R, C, E> {
336    const ID: ClusterId = ID;
337}