Skip to main content

rs_matter_node_core/
handover.rs

1/*
2 *
3 *    Copyright (c) 2026 Project CHIP Authors
4 *
5 *    Licensed under the Apache License, Version 2.0 (the "License");
6 *    you may not use this file except in compliance with the License.
7 *    You may obtain a copy of the License at
8 *
9 *        http://www.apache.org/licenses/LICENSE-2.0
10 *
11 *    Unless required by applicable law or agreed to in writing, software
12 *    distributed under the License is distributed on an "AS IS" BASIS,
13 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *    See the License for the specific language governing permissions and
15 *    limitations under the License.
16 */
17
18//! Commissioning handover: suspend a half-done commissioning on one node and
19//! resume it on another.
20
21use core::fmt::{self, Debug};
22use core::marker::PhantomData;
23
24use crate::acl::AclEntry;
25use crate::basic_info::RegulatoryLocationType;
26use crate::crypto::{CanonAeadKey, CanonPkcSecretKey};
27use crate::error::{Error, ErrorCode};
28use crate::fabric::Fabric;
29use crate::networks::{Networks, NetworksError, WirelessCreds};
30use crate::tlv::{
31    EitherIter, FromTLV, OctetStr, Octets, TLVArray, TLVArrayOrSlice, TLVElement, TLVTag, TLVWrite,
32    TlvError, TlvErrorCode, ToTLV, Utf8Str, TLV,
33};
34
35/// The envelope version.
36pub const HANDOVER_VERSION: u8 = 1;
37
38/// A borrowed view of one staged network, convertible from and to
39/// [`WirelessCreds`].
40pub trait HandoverNetwork: Copy {
41    /// This view type at lifetime `'c`.
42    type Borrowed<'c>: HandoverNetwork + FromTLV<'c> + ToTLV;
43
44    /// The view of `creds`, if of this kind.
45    fn from_creds<'c>(creds: &WirelessCreds<'c>) -> Option<Self::Borrowed<'c>>;
46
47    /// The credentials of this view.
48    fn creds(&self) -> WirelessCreds<'_>;
49}
50
51/// A staged Wi-Fi network; same tags as the `AddOrUpdateWiFiNetwork` arguments.
52#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, FromTLV, ToTLV)]
53#[cfg_attr(feature = "defmt", derive(defmt::Format))]
54#[tlvargs(lifetime = "'a")]
55pub struct HandoverWifi<'a> {
56    pub ssid: OctetStr<'a>,
57    pub credentials: OctetStr<'a>,
58}
59
60impl HandoverNetwork for HandoverWifi<'_> {
61    type Borrowed<'c> = HandoverWifi<'c>;
62
63    fn from_creds<'c>(creds: &WirelessCreds<'c>) -> Option<Self::Borrowed<'c>> {
64        match creds {
65            WirelessCreds::Wifi { ssid, pass } => Some(HandoverWifi {
66                ssid: Octets(ssid),
67                credentials: Octets(pass),
68            }),
69            WirelessCreds::Thread { .. } => None,
70        }
71    }
72
73    fn creds(&self) -> WirelessCreds<'_> {
74        WirelessCreds::Wifi {
75            ssid: self.ssid.0,
76            pass: self.credentials.0,
77        }
78    }
79}
80
81/// A staged Thread network; same tag as the `AddOrUpdateThreadNetwork` argument.
82#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, FromTLV, ToTLV)]
83#[cfg_attr(feature = "defmt", derive(defmt::Format))]
84#[tlvargs(lifetime = "'a")]
85pub struct HandoverThread<'a> {
86    pub operational_dataset: OctetStr<'a>,
87}
88
89impl HandoverNetwork for HandoverThread<'_> {
90    type Borrowed<'c> = HandoverThread<'c>;
91
92    fn from_creds<'c>(creds: &WirelessCreds<'c>) -> Option<Self::Borrowed<'c>> {
93        match creds {
94            WirelessCreds::Thread { dataset_tlv } => Some(HandoverThread {
95                operational_dataset: Octets(dataset_tlv),
96            }),
97            WirelessCreds::Wifi { .. } => None,
98        }
99    }
100
101    fn creds(&self) -> WirelessCreds<'_> {
102        WirelessCreds::Thread {
103            dataset_tlv: self.operational_dataset.0,
104        }
105    }
106}
107
108/// The staged networks of kind `T` ([`HandoverWifi`] or [`HandoverThread`]),
109/// serialized as a TLV array of `T`.
110///
111/// Never materialized: read lazily from the TLV, a slice, or the live
112/// [`Networks`] store, whose credentials are only reachable via callbacks.
113/// Hence [`for_each`](Self::for_each) instead of an iterator, and hence
114/// `tlv_iter` errors with `InvalidState` for a store-backed instance
115/// (`to_tlv` always works).
116pub struct HandoverNetworks<'a, T> {
117    source: NetworksSource<'a, T>,
118    _kind: PhantomData<fn() -> T>,
119}
120
121enum NetworksSource<'a, T> {
122    Tlv(TLVElement<'a>),
123    Slice(&'a [T]),
124    Store(&'a dyn Networks),
125}
126
127impl<'a, T> HandoverNetworks<'a, T>
128where
129    T: HandoverNetwork,
130{
131    /// The networks in `slice`.
132    pub const fn from_slice(slice: &'a [T]) -> Self {
133        Self {
134            source: NetworksSource::Slice(slice),
135            _kind: PhantomData,
136        }
137    }
138
139    /// The networks of kind `T` in the store.
140    pub const fn from_store(networks: &'a dyn Networks) -> Self {
141        Self {
142            source: NetworksSource::Store(networks),
143            _kind: PhantomData,
144        }
145    }
146
147    /// Call `f` with each network's credentials, in order.
148    pub fn for_each(
149        &self,
150        f: &mut dyn FnMut(&WirelessCreds<'_>) -> Result<(), Error>,
151    ) -> Result<(), Error> {
152        match &self.source {
153            NetworksSource::Tlv(element) => {
154                for network in TLVArray::<T::Borrowed<'a>>::new(element.clone())?.iter() {
155                    f(&network?.creds())?;
156                }
157
158                Ok(())
159            }
160            NetworksSource::Slice(slice) => {
161                for network in *slice {
162                    f(&network.creds())?;
163                }
164
165                Ok(())
166            }
167            NetworksSource::Store(networks) => networks.networks(&mut |network_id| {
168                networks
169                    .creds(network_id, &mut |creds| {
170                        if T::from_creds(creds).is_some() {
171                            f(creds)?;
172                        }
173
174                        Ok(())
175                    })
176                    .map(|_| ())
177                    .map_err(networks_error)
178            }),
179        }
180    }
181
182    /// Whether there are no networks.
183    pub fn is_empty(&self) -> Result<bool, Error> {
184        let mut empty = true;
185
186        self.for_each(&mut |_| {
187            empty = false;
188            Ok(())
189        })?;
190
191        Ok(empty)
192    }
193}
194
195impl<'a, T> FromTLV<'a> for HandoverNetworks<'a, T>
196where
197    T: HandoverNetwork + 'a,
198{
199    fn from_tlv(element: &TLVElement<'a>) -> Result<Self, TlvError> {
200        Ok(Self {
201            source: NetworksSource::Tlv(
202                TLVArray::<T::Borrowed<'a>>::new(element.clone())?
203                    .element()
204                    .clone(),
205            ),
206            _kind: PhantomData,
207        })
208    }
209}
210
211impl<'a, T> ToTLV for HandoverNetworks<'a, T>
212where
213    T: HandoverNetwork + ToTLV,
214{
215    fn to_tlv<W: TLVWrite>(&self, tag: &TLVTag, mut tw: W) -> Result<(), TlvError> {
216        tw.start_array(tag)?;
217
218        // `for_each` reports the shared `Error`, so the `TlvError` of the inner
219        // `to_tlv` is carried out of the closure rather than flattened - it can be
220        // `NoSpace`, which the caller needs in order to chunk.
221        let mut tlv_err = None;
222
223        self.for_each(&mut |creds| {
224            // `for_each` only yields networks of kind `T`
225            let network = unwrap!(T::from_creds(creds));
226
227            if let Err(err) = network.to_tlv(&TLVTag::Anonymous, &mut tw) {
228                tlv_err = Some(err.code());
229                Err(err)?;
230            }
231
232            Ok(())
233        })
234        .map_err(|err| {
235            TlvError::new(tlv_err.unwrap_or_else(|| {
236                // Reading the networks out of the store failed. There is no TLV
237                // code for that, so log the cause before flattening it away.
238                error!("Cannot read the networks to serialize: {}", err);
239                TlvErrorCode::NotFound
240            }))
241        })?;
242
243        tw.end_container()
244    }
245
246    fn tlv_iter(&self, tag: TLVTag) -> impl Iterator<Item = Result<TLV<'_>, TlvError>> {
247        match &self.source {
248            NetworksSource::Tlv(element) => {
249                EitherIter::First(EitherIter::First(element.tlv_iter(tag)))
250            }
251            NetworksSource::Slice(slice) => {
252                EitherIter::First(EitherIter::Second(slice.tlv_iter(tag)))
253            }
254            // Callbacks cannot drive an iterator; use `to_tlv`
255            NetworksSource::Store(_) => {
256                error!("A store-backed `HandoverNetworks` cannot be iterated; use `to_tlv`");
257
258                EitherIter::Second(core::iter::once(Err(TlvErrorCode::NotFound.into())))
259            }
260        }
261    }
262}
263
264impl<T> Debug for HandoverNetworks<'_, T> {
265    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
266        match &self.source {
267            NetworksSource::Tlv(element) => f.debug_tuple("Tlv").field(element).finish(),
268            NetworksSource::Slice(slice) => f.debug_tuple("Slice").field(&slice.len()).finish(),
269            NetworksSource::Store(_) => f.debug_tuple("Store").finish(),
270        }
271    }
272}
273
274#[cfg(feature = "defmt")]
275impl<T> defmt::Format for HandoverNetworks<'_, T> {
276    fn format(&self, f: defmt::Formatter<'_>) {
277        match &self.source {
278            NetworksSource::Tlv(element) => defmt::write!(f, "Tlv({})", element),
279            NetworksSource::Slice(slice) => defmt::write!(f, "Slice({})", slice.len()),
280            NetworksSource::Store(_) => defmt::write!(f, "Store"),
281        }
282    }
283}
284
285/// The regulatory configuration, as set by `SetRegulatoryConfig`.
286#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, FromTLV, ToTLV)]
287#[cfg_attr(feature = "defmt", derive(defmt::Format))]
288#[tlvargs(lifetime = "'a")]
289pub struct HandoverRegulatory<'a> {
290    /// Two-letter ISO 3166-1 country code.
291    pub country_code: Utf8Str<'a>,
292    pub location_type: RegulatoryLocationType,
293}
294
295/// The commissioning handover envelope.
296///
297/// Needed for NFC (NTL) commissioning, where phase 1 - PASE, `ArmFailSafe`,
298/// `AddNOC`, the ACL writes, `AddOrUpdate*Network` - runs on the NFC subsystem
299/// with the main CPU off, and phase 2 - operational discovery, CASE,
300/// `CommissioningComplete` - runs on the host once it boots. The outcome of
301/// phase 1 travels between the two as a [`CommissioningHandover`]: a
302/// versioned TLV envelope, mostly made of spec-defined TLV, so a vendor NFC
303/// stack can produce it without `rs-matter`.
304///
305/// # Security
306///
307/// The envelope carries the node's operational private key, the IPK and the
308/// network credentials. The channel it travels over is the security boundary.
309#[derive(Debug, FromTLV, ToTLV)]
310#[cfg_attr(feature = "defmt", derive(defmt::Format))]
311#[tlvargs(lifetime = "'a")]
312pub struct CommissioningHandover<'a> {
313    pub version: u8,
314    pub root_ca: OctetStr<'a>,
315    pub icac: Option<OctetStr<'a>>,
316    pub noc: OctetStr<'a>,
317    pub secret_key: CanonPkcSecretKey,
318    pub ipk: CanonAeadKey,
319    pub admin_vendor_id: u16,
320    pub label: Utf8Str<'a>,
321    /// `FabricIndex` is ignored on import.
322    pub acl: TLVArrayOrSlice<'a, AclEntry>,
323    pub wifi_networks: HandoverNetworks<'a, HandoverWifi<'a>>,
324    pub thread_networks: HandoverNetworks<'a, HandoverThread<'a>>,
325    pub regulatory: Option<HandoverRegulatory<'a>>,
326    pub fail_safe_remaining_secs: u16,
327    pub breadcrumb: u64,
328}
329
330impl CommissioningHandover<'_> {
331    /// Structural validation: version, non-empty ACL, well-formed regulatory
332    /// config. Certificates and keys are checked on import.
333    pub fn validate(&self) -> Result<(), Error> {
334        if self.version != HANDOVER_VERSION {
335            error!(
336                "Unsupported commissioning handover version {} (expected {})",
337                self.version, HANDOVER_VERSION
338            );
339            Err(ErrorCode::InvalidData)?;
340        }
341
342        if self.acl.iter()?.next().is_none() {
343            error!("Commissioning handover carries no ACL entries");
344            Err(ErrorCode::InvalidData)?;
345        }
346
347        if let Some(regulatory) = &self.regulatory {
348            if regulatory.country_code.len() != 2 {
349                error!("Commissioning handover carries an invalid country code");
350                Err(ErrorCode::InvalidData)?;
351            }
352        }
353
354        Ok(())
355    }
356
357    /// Build the envelope for the pending `fabric` and hand it to `f`.
358    pub fn with_pending<N, F, R>(
359        fabric: &Fabric,
360        networks: N,
361        regulatory: Option<HandoverRegulatory<'_>>,
362        fail_safe_remaining_secs: u16,
363        breadcrumb: u64,
364        f: F,
365    ) -> Result<R, Error>
366    where
367        N: Networks,
368        F: FnOnce(&CommissioningHandover<'_>) -> Result<R, Error>,
369    {
370        let handover = CommissioningHandover {
371            version: HANDOVER_VERSION,
372            root_ca: Octets(fabric.root_ca()),
373            icac: (!fabric.icac().is_empty()).then(|| Octets(fabric.icac())),
374            noc: Octets(fabric.noc()),
375            secret_key: CanonPkcSecretKey::new_from_ref(fabric.secret_key()),
376            ipk: CanonAeadKey::new_from_ref(fabric.ipk().epoch_key()),
377            admin_vendor_id: fabric.vendor_id(),
378            label: fabric.label(),
379            acl: TLVArrayOrSlice::new_slice(fabric.acl()),
380            wifi_networks: HandoverNetworks::from_store(&networks),
381            thread_networks: HandoverNetworks::from_store(&networks),
382            regulatory,
383            fail_safe_remaining_secs,
384            breadcrumb,
385        };
386
387        f(&handover)
388    }
389}
390
391/// Stage the networks of `handover` into `networks`, as `AddOrUpdate*Network`
392/// would.
393pub fn stage_networks<N>(handover: &CommissioningHandover<'_>, mut networks: N) -> Result<(), Error>
394where
395    N: Networks,
396{
397    let mut staged = false;
398
399    let mut stage = |creds: &WirelessCreds<'_>| {
400        networks.add_or_update(creds).map_err(networks_error)?;
401        staged = true;
402
403        Ok(())
404    };
405
406    handover.wifi_networks.for_each(&mut stage)?;
407    handover.thread_networks.for_each(&mut stage)?;
408
409    // No `ConnectNetwork` will follow: the node must connect by itself,
410    // so hand the store to the connectivity manager right away
411    if staged {
412        networks.set_managed(true)?;
413    }
414
415    Ok(())
416}
417
418fn networks_error(err: NetworksError) -> Error {
419    match err {
420        NetworksError::Other(err) => err,
421        NetworksError::NetworkIdNotFound => ErrorCode::NotFound.into(),
422        NetworksError::DuplicateNetworkId
423        | NetworksError::OutOfRange
424        | NetworksError::BoundsExceeded => ErrorCode::InvalidData.into(),
425    }
426}
427
428#[cfg(test)]
429#[cfg_attr(coverage_nightly, coverage(off))]
430mod tests {
431    use super::*;
432
433    use crate::acl::{AuthMode, Target};
434    use crate::dm::Privilege;
435    use crate::utils::storage::Vec;
436    use crate::utils::storage::WriteBuf;
437
438    fn collect_acl<const N: usize>(acl: &TLVArrayOrSlice<'_, AclEntry>) -> Vec<AclEntry, N> {
439        acl.iter().unwrap().map(|item| item.unwrap()).collect()
440    }
441
442    /// The network IDs of all networks, in order.
443    fn collect_network_ids<T: HandoverNetwork, const N: usize>(
444        networks: &HandoverNetworks<'_, T>,
445    ) -> Vec<Vec<u8, 64>, N> {
446        let mut collected = Vec::new();
447
448        networks
449            .for_each(&mut |creds| {
450                collected
451                    .push(Vec::from_slice(creds.id()?).unwrap())
452                    .map_err(|_| ErrorCode::ResourceExhausted)?;
453                Ok(())
454            })
455            .unwrap();
456
457        collected
458    }
459
460    #[test]
461    fn round_trip() {
462        let mut admin = AclEntry::new(None, Privilege::ADMIN, AuthMode::Case);
463        admin.add_subject(112233).unwrap();
464
465        let mut operate = AclEntry::new(None, Privilege::OPERATE, AuthMode::Case);
466        operate.add_subject(0xFFFF_FFFD_0001_0001).unwrap();
467        operate
468            .add_target(Target::new(Some(1), None, None))
469            .unwrap();
470
471        let acl = [admin, operate];
472        let wifi = [HandoverWifi {
473            ssid: Octets(b"home"),
474            credentials: Octets(b"secret"),
475        }];
476        // Just an Extended PAN ID TLV
477        let thread = [HandoverThread {
478            operational_dataset: Octets(&[0x02, 0x08, 1, 2, 3, 4, 5, 6, 7, 8]),
479        }];
480
481        let handover = CommissioningHandover {
482            version: HANDOVER_VERSION,
483            root_ca: Octets(&[1, 2, 3]),
484            icac: None,
485            noc: Octets(&[4, 5, 6]),
486            secret_key: CanonPkcSecretKey::from([7u8; 32]),
487            ipk: CanonAeadKey::from([8u8; 16]),
488            admin_vendor_id: 0xfff1,
489            label: "lab",
490            acl: TLVArrayOrSlice::new_slice(&acl),
491            wifi_networks: HandoverNetworks::from_slice(&wifi),
492            thread_networks: HandoverNetworks::from_slice(&thread),
493            regulatory: Some(HandoverRegulatory {
494                country_code: "BG",
495                location_type: RegulatoryLocationType::IndoorOutdoor,
496            }),
497            fail_safe_remaining_secs: 42,
498            breadcrumb: 7,
499        };
500
501        let mut buf = [0u8; 512];
502        let mut wb = WriteBuf::new(&mut buf);
503        handover.to_tlv(&TLVTag::Anonymous, &mut wb).unwrap();
504        let len = wb.get_tail();
505
506        let parsed = CommissioningHandover::from_tlv(&TLVElement::new(&buf[..len])).unwrap();
507        parsed.validate().unwrap();
508
509        assert_eq!(parsed.version, HANDOVER_VERSION);
510        assert_eq!(parsed.root_ca.0, &[1, 2, 3]);
511        assert!(parsed.icac.is_none());
512        assert_eq!(parsed.noc.0, &[4, 5, 6]);
513        assert_eq!(parsed.secret_key.access(), &[7u8; 32]);
514        assert_eq!(parsed.ipk.access(), &[8u8; 16]);
515        assert_eq!(parsed.admin_vendor_id, 0xfff1);
516        assert_eq!(parsed.label, "lab");
517        assert_eq!(parsed.fail_safe_remaining_secs, 42);
518        assert_eq!(parsed.breadcrumb, 7);
519        assert_eq!(parsed.regulatory.unwrap().country_code, "BG");
520        assert_eq!(collect_acl::<4>(&parsed.acl).as_slice(), &acl);
521
522        let wifi_ids = collect_network_ids::<_, 2>(&parsed.wifi_networks);
523        assert_eq!(wifi_ids.len(), 1);
524        assert_eq!(wifi_ids[0], b"home");
525
526        let thread_ids = collect_network_ids::<_, 2>(&parsed.thread_networks);
527        assert_eq!(thread_ids.len(), 1);
528        assert_eq!(thread_ids[0], &[1, 2, 3, 4, 5, 6, 7, 8]);
529
530        // `tlv_iter` must agree with `to_tlv`
531        let mut buf2 = [0u8; 512];
532        let mut wb2 = WriteBuf::new(&mut buf2);
533        for tlv in handover.tlv_iter(TLVTag::Anonymous) {
534            let tlv = tlv.unwrap();
535            wb2.tlv(&tlv.tag, &tlv.value).unwrap();
536        }
537        let len2 = wb2.get_tail();
538        assert_eq!(&buf[..len], &buf2[..len2]);
539    }
540
541    #[test]
542    fn rejects_empty_acl_and_bad_version() {
543        let handover = CommissioningHandover {
544            version: HANDOVER_VERSION + 1,
545            root_ca: Octets(&[]),
546            icac: None,
547            noc: Octets(&[]),
548            secret_key: CanonPkcSecretKey::new(),
549            ipk: CanonAeadKey::new(),
550            admin_vendor_id: 0,
551            label: "",
552            acl: TLVArrayOrSlice::new_slice(&[]),
553            wifi_networks: HandoverNetworks::from_slice(&[]),
554            thread_networks: HandoverNetworks::from_slice(&[]),
555            regulatory: None,
556            fail_safe_remaining_secs: 0,
557            breadcrumb: 0,
558        };
559
560        assert!(handover.validate().is_err());
561
562        let handover = CommissioningHandover {
563            version: HANDOVER_VERSION,
564            ..handover
565        };
566        assert!(handover.validate().is_err());
567
568        let admin = [AclEntry::new(None, Privilege::ADMIN, AuthMode::Case)];
569        let handover = CommissioningHandover {
570            acl: TLVArrayOrSlice::new_slice(&admin),
571            ..handover
572        };
573        assert!(handover.validate().is_ok());
574        assert!(handover.wifi_networks.is_empty().unwrap());
575    }
576}