matter-commissioning 0.1.0

Matter commissioning state machine: setup payload, attestation, NOC issuance, network commissioning.
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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
//! CASE bridge (M6.6.3b): operational discovery + drive the sans-IO
//! `CaseInitiator` over the unsecured datagram path.
//!
//! CASE Sigma1/2/3 are exchanged UNSECURED (session-id 0, `SecureChannel`
//! protocol) — the operational secured session only exists once the handshake
//! derives keys.

use std::net::SocketAddr;

use matter_cert::{MatterTime, TrustedRoots};
use matter_crypto::{CaseCredentials, CaseInitiator};
use matter_transport::{Discovery, ServiceKind, SessionId, SessionManager, SessionRole};

use crate::driver::datagram::AsyncDatagram;
use crate::driver::error::DriverError;
use crate::driver::unsecured::{parse_status_report, require_handshake_opcode, UnsecuredExchange};

/// Build the operational mDNS instance name `<compressed-fabric-id>-<node-id>`,
/// each as fixed-width uppercase hex (16 + 1 + 16 chars), per the Matter
/// operational-discovery instance-name convention.
///
/// FLAGGED: confirm exact casing/width/separator against matter.js byte parity
/// before the first real-device CASE (M6.6.5); this matches the connectedhomeip
/// convention and the in-tree examples.
#[must_use]
pub fn operational_instance_name(compressed_fabric_id: [u8; 8], node_id: u64) -> String {
    let cfid = u64::from_be_bytes(compressed_fabric_id);
    format!("{cfid:016X}-{node_id:016X}")
}

/// How many times [`resolve_operational`] polls discovery before giving up, and
/// the gap between polls (~30 s total) — bounded so the driver doesn't hang
/// forever. The operational record only appears after `AddNOC`, so mDNS
/// propagation can take several seconds on a real LAN (observed during M6.6.5
/// validation); chip's session-establishment discovery budget is of the same
/// order. `pub(crate)` so `commission()` (the IP path) can pass this exact
/// budget into [`resolve_operational_with_attempts`] via `establish_case_session`.
pub(crate) const RESOLVE_POLL_ATTEMPTS: u32 = 300;
const RESOLVE_POLL_INTERVAL: std::time::Duration = std::time::Duration::from_millis(100);

/// Operational-resolve budget for the BLE (BTP) commissioning path: ~60 s at
/// `RESOLVE_POLL_INTERVAL` (100 ms) per poll. Over BLE the device has only
/// just been handed Wi-Fi credentials when `commission_ble` reaches
/// `EstablishCase`, so it must still associate to the AP, obtain a DHCP lease,
/// and announce its `_matter._tcp` operational record before the resolve can
/// succeed — a materially longer window than the IP path's ~30 s (design D11.2).
pub const BLE_RESOLVE_POLL_ATTEMPTS: u32 = 600;

/// Pick the most routable address from an mDNS record: IPv4 first, then any
/// non-link-local IPv6, then whatever is left. A `fe80::` IPv6 needs an
/// interface scope id that [`MatterService`](matter_transport::MatterService)
/// does not carry, so a dial-out socket cannot route to it — devices often
/// list it FIRST, ahead of perfectly routable addresses (M6.6.5: closes the
/// previously FLAGGED `.first()` pick). Shared with `resolve_commissionable`.
pub(crate) fn preferred_address(addresses: &[std::net::IpAddr]) -> Option<std::net::IpAddr> {
    let is_v6_link_local = |a: &std::net::IpAddr| match a {
        std::net::IpAddr::V6(v6) => (v6.segments()[0] & 0xffc0) == 0xfe80,
        std::net::IpAddr::V4(_) => false,
    };
    addresses
        .iter()
        .find(|a| a.is_ipv4())
        .or_else(|| addresses.iter().find(|a| !is_v6_link_local(a)))
        .or_else(|| addresses.first())
        .copied()
}

/// Browse `_matter._tcp` operational records and return the socket address of
/// the node whose instance name matches `(compressed_fabric_id, node_id)`.
///
/// The advertised address list is filtered for routability
/// (IPv4 → non-link-local IPv6 → fallback) — see `preferred_address`.
///
/// # Errors
///
/// - [`DriverError::Transport`] if the discovery query fails.
/// - [`DriverError::Discovery`] if no matching record with an address appears
///   within the poll budget.
pub async fn resolve_operational<D: Discovery>(
    discovery: &mut D,
    compressed_fabric_id: [u8; 8],
    node_id: u64,
) -> Result<SocketAddr, DriverError> {
    // The IP path's ~30 s budget. Delegates to the parameterized form so the
    // BLE path can raise the budget without duplicating the poll loop.
    resolve_operational_with_attempts(
        discovery,
        compressed_fabric_id,
        node_id,
        RESOLVE_POLL_ATTEMPTS,
    )
    .await
}

/// Like [`resolve_operational`], but with an explicit poll-attempt budget
/// (each poll is spaced by `RESOLVE_POLL_INTERVAL` = 100 ms). The IP path uses
/// [`resolve_operational`] (`RESOLVE_POLL_ATTEMPTS` = 300, ~30 s); the BLE path
/// passes [`BLE_RESOLVE_POLL_ATTEMPTS`] (600, ~60 s) because a just-provisioned
/// device needs longer to associate to Wi-Fi and announce its operational
/// record (design D11.2).
///
/// # Errors
///
/// - [`DriverError::Transport`] if the discovery query fails.
/// - [`DriverError::Discovery`] if no matching record with an address appears
///   within the `attempts` budget.
pub async fn resolve_operational_with_attempts<D: Discovery>(
    discovery: &mut D,
    compressed_fabric_id: [u8; 8],
    node_id: u64,
    attempts: u32,
) -> Result<SocketAddr, DriverError> {
    let target = operational_instance_name(compressed_fabric_id, node_id);
    let handle = discovery
        .query(ServiceKind::Operational)
        .map_err(DriverError::Transport)?;

    for _ in 0..attempts {
        for svc in discovery.poll_results(handle) {
            if svc.instance_name.eq_ignore_ascii_case(&target) {
                if let Some(addr) = preferred_address(&svc.addresses) {
                    discovery.stop_query(handle);
                    return Ok(SocketAddr::new(addr, svc.port));
                }
            }
        }
        tokio::time::sleep(RESOLVE_POLL_INTERVAL).await;
    }
    discovery.stop_query(handle);
    Err(DriverError::Discovery(format!(
        "operational node {target} not found via mDNS"
    )))
}

// SecureChannel opcodes for the CASE handshake (Matter Core Spec §4.14.1).
const OP_SIGMA1: u8 = 0x30;
const OP_SIGMA2: u8 = 0x31;
const OP_SIGMA3: u8 = 0x32;
/// `SecureChannel` `StatusReport` opcode (spec §4.10.1.1) — the frame the
/// device sends to close the handshake after the terminal `Sigma3`.
const OP_STATUS_REPORT: u8 = 0x40;

const CASE_EXCHANGE_ID: u16 = 1;

/// Drive a fresh CASE (SIGMA-I) handshake against an already-resolved
/// operational `peer` and register the resulting operational session, returning
/// its local [`SessionId`]. `credentials` is this controller's operational
/// identity; `peer_node_id`/`peer_fabric_id` identify the device. Resumption is
/// not used (a fresh handshake every time); that is M8.
///
/// `now` is the wall-clock instant against which the device's operational
/// certificate chain is checked for temporal validity during Sigma2. The caller
/// (controller layer) supplies the real time; this crate never reads the system
/// clock.
///
/// # Errors
///
/// - [`DriverError::Crypto`] if a SIGMA step fails (peer chain/signature
///   invalid, key mismatch, etc.).
/// - [`DriverError::Io`] / [`DriverError::Transport`] / [`DriverError::Timeout`]
///   on datagram, framing, or reply-timeout failure.
// 8 params: the CASE setup (transport, sessions, peer, credentials, roots,
// node/fabric ids) plus the injected validation clock; bundling them would
// obscure the call site.
#[allow(clippy::too_many_arguments)]
pub async fn run_case<T: AsyncDatagram>(
    transport: &T,
    sessions: &mut SessionManager,
    peer: SocketAddr,
    credentials: CaseCredentials,
    trusted_roots: TrustedRoots,
    peer_node_id: u64,
    peer_fabric_id: u64,
    now: MatterTime,
) -> Result<SessionId, DriverError> {
    // Allocate the local session id up front (advertised in Sigma1), run the
    // handshake, then register the established output. `run_case_establish` is
    // the handshake body without the `SessionManager` coupling; keeping the
    // allocate+register here preserves this function's exact behavior for its
    // existing callers.
    let local = sessions.allocate_session_id();
    // `Box::pin` the extracted handshake future so it lives on the heap rather
    // than being embedded inline in this (and every transitive caller's, e.g.
    // `commission`) future. Without this, nesting `run_case_establish`'s frame
    // inside `run_case` grows the commissioning future past clippy's
    // `large_futures` threshold. CASE connect is not a hot path, so the single
    // allocation is negligible.
    let output = Box::pin(run_case_establish(
        transport,
        peer,
        local.0,
        credentials,
        trusted_roots,
        peer_node_id,
        peer_fabric_id,
        now,
    ))
    .await?;
    let sid = sessions.register_case(&output, SessionRole::Initiator);
    Ok(sid)
}

/// Drive a fresh CASE (SIGMA-I) handshake to completion over `transport` and
/// return the established [`CaseSessionOutput`](matter_crypto::CaseSessionOutput)
/// **without registering it** — so the caller can register it into its own
/// [`SessionManager`] (e.g. after a spawned, own-socket handshake that hands the
/// session back to a controller actor; see M9-G-d). `local_session_id` is the
/// local session id to advertise in Sigma1 (the caller allocates it).
///
/// [`run_case`] is `allocate_session_id` + this function + `register_case`; the
/// two share this body so their handshake behavior is identical.
///
/// # Errors
///
/// - [`DriverError::Crypto`] if a SIGMA step fails (peer chain/signature
///   invalid, key mismatch, etc.).
/// - [`DriverError::Io`] / [`DriverError::Transport`] / [`DriverError::Timeout`]
///   on datagram, framing, or reply-timeout failure.
/// - [`DriverError::SessionEstablishmentFailed`] if the device closes the
///   handshake with a non-success `StatusReport`.
// Same 8-input CASE setup as `run_case`, with an explicit `local_session_id`
// in place of the `SessionManager` this variant does not touch.
#[allow(clippy::too_many_arguments)]
pub async fn run_case_establish<T: AsyncDatagram>(
    transport: &T,
    peer: SocketAddr,
    local_session_id: u16,
    credentials: CaseCredentials,
    trusted_roots: TrustedRoots,
    peer_node_id: u64,
    peer_fabric_id: u64,
    now: MatterTime,
) -> Result<matter_crypto::CaseSessionOutput, DriverError> {
    let mut initiator = CaseInitiator::new(
        credentials,
        trusted_roots,
        peer_node_id,
        peer_fabric_id,
        local_session_id,
        now,
    )?;
    // CSPRNG-seeded counter + ephemeral source node id (spec §4.5.1.1,
    // §4.13.2.1) — same unsecured-header requirements as PASE apply to SIGMA.
    let mut exch = UnsecuredExchange::new_ephemeral(CASE_EXCHANGE_ID)?;

    let sigma1 = initiator.start()?;
    let sigma2 = exch
        .send_and_recv(transport, peer, OP_SIGMA1, OP_SIGMA2, &sigma1, None)
        .await?;
    if let Err(e) = require_handshake_opcode(&sigma2, OP_SIGMA2) {
        // Best-effort ack so a rejecting device stops retransmitting its
        // (reliable) StatusReport before we abort.
        let _ = exch
            .send_standalone_ack(transport, peer, sigma2.message_counter)
            .await;
        return Err(e);
    }
    #[cfg(feature = "tracing")]
    tracing::debug!(
        sigma2 = %crate::hexdump::hex(&sigma2.payload),
        "received Sigma2"
    );
    initiator.handle_sigma2(&sigma2.payload)?;

    // Sigma3 is sent reliably and the device closes the handshake with a
    // SecureChannel StatusReport (success or failure) — consumed and acked
    // here, exactly as in `run_pase` (see that bridge for rationale).
    let sigma3 = initiator.next_message()?;
    let report = exch
        .send_and_recv(
            transport,
            peer,
            OP_SIGMA3,
            OP_STATUS_REPORT,
            &sigma3,
            Some(sigma2.message_counter),
        )
        .await?;
    let status = parse_status_report(&report)?;
    exch.send_standalone_ack(transport, peer, report.message_counter)
        .await?;
    if !status.is_session_establishment_success() {
        return Err(DriverError::SessionEstablishmentFailed {
            general_code: status.general_code,
            protocol_code: status.protocol_code,
        });
    }

    let output = initiator.finish()?;
    Ok(output)
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)] // Test-code carve-out: see CLAUDE.md.
mod tests {
    use super::*;

    #[test]
    fn operational_instance_name_formats_16_16_uppercase_hex() {
        let cfid = [0x87, 0xe1, 0xb0, 0x04, 0xe2, 0x35, 0xa1, 0x30];
        let node_id: u64 = 0x0000_0000_0000_0001;
        assert_eq!(
            operational_instance_name(cfid, node_id),
            "87E1B004E235A130-0000000000000001"
        );
    }

    use std::collections::HashMap;
    use std::net::{IpAddr, Ipv4Addr};

    use matter_transport::{MatterService, QueryHandle};

    struct FakeDiscovery {
        service: MatterService,
    }

    impl Discovery for FakeDiscovery {
        fn publish(&mut self, _s: &MatterService) -> matter_transport::Result<()> {
            Ok(())
        }
        fn unpublish(&mut self, _n: &str, _k: ServiceKind) -> matter_transport::Result<()> {
            Ok(())
        }
        fn query(&mut self, _k: ServiceKind) -> matter_transport::Result<QueryHandle> {
            Ok(QueryHandle(1))
        }
        fn stop_query(&mut self, _h: QueryHandle) {}
        fn poll_results(&mut self, _h: QueryHandle) -> Vec<MatterService> {
            vec![self.service.clone()]
        }
    }

    #[tokio::test]
    async fn resolve_operational_returns_matching_addr() {
        let cfid = [0x87, 0xe1, 0xb0, 0x04, 0xe2, 0x35, 0xa1, 0x30];
        let node_id: u64 = 1;
        let name = operational_instance_name(cfid, node_id);
        let mut disc = FakeDiscovery {
            service: MatterService::new(
                name,
                ServiceKind::Operational,
                vec![IpAddr::V4(Ipv4Addr::new(192, 0, 2, 7))],
                5540,
                HashMap::new(),
            ),
        };
        let addr = resolve_operational(&mut disc, cfid, node_id).await.unwrap();
        assert_eq!(
            addr,
            std::net::SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 0, 2, 7)), 5540)
        );
    }

    #[tokio::test]
    async fn resolve_operational_prefers_routable_addresses() {
        // mDNS records list link-local IPv6 first on many devices, but a
        // `fe80::` address without a scope id is unroutable from a dial-out
        // socket. Prefer IPv4, then non-link-local IPv6, and fall back to
        // whatever is left (M6.6.5: closes the FLAGGED `.first()` pick).
        use std::net::Ipv6Addr;
        let cfid = [0x87, 0xe1, 0xb0, 0x04, 0xe2, 0x35, 0xa1, 0x30];
        let node_id: u64 = 1;
        let name = operational_instance_name(cfid, node_id);
        let link_local = IpAddr::V6(Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 0x1d42));
        let ula = IpAddr::V6(Ipv6Addr::new(0xfdfc, 0x20da, 0x4273, 0x126f, 0, 0, 0, 1));
        let v4 = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 248));

        // Link-local listed first, IPv4 buried last — IPv4 must win.
        let mut disc = FakeDiscovery {
            service: MatterService::new(
                name.clone(),
                ServiceKind::Operational,
                vec![link_local, ula, v4],
                5540,
                HashMap::new(),
            ),
        };
        let addr = resolve_operational(&mut disc, cfid, node_id).await.unwrap();
        assert_eq!(addr, std::net::SocketAddr::new(v4, 5540));

        // No IPv4: the non-link-local IPv6 must win over fe80.
        let mut disc = FakeDiscovery {
            service: MatterService::new(
                name,
                ServiceKind::Operational,
                vec![link_local, ula],
                5540,
                HashMap::new(),
            ),
        };
        let addr = resolve_operational(&mut disc, cfid, node_id).await.unwrap();
        assert_eq!(addr, std::net::SocketAddr::new(ula, 5540));
    }

    /// A [`Discovery`] stub that returns no results for the first
    /// `succeed_on - 1` polls and the matching operational record on poll
    /// `succeed_on`, counting every `poll_results` call. Lets a test assert the
    /// attempt budget is respected exactly.
    struct CountingDiscovery {
        service: MatterService,
        succeed_on: u32,
        polls: u32,
    }

    impl Discovery for CountingDiscovery {
        fn publish(&mut self, _s: &MatterService) -> matter_transport::Result<()> {
            Ok(())
        }
        fn unpublish(&mut self, _n: &str, _k: ServiceKind) -> matter_transport::Result<()> {
            Ok(())
        }
        fn query(&mut self, _k: ServiceKind) -> matter_transport::Result<QueryHandle> {
            Ok(QueryHandle(1))
        }
        fn stop_query(&mut self, _h: QueryHandle) {}
        fn poll_results(&mut self, _h: QueryHandle) -> Vec<MatterService> {
            self.polls += 1;
            if self.polls >= self.succeed_on {
                vec![self.service.clone()]
            } else {
                vec![]
            }
        }
    }

    fn counting_discovery(cfid: [u8; 8], node_id: u64, succeed_on: u32) -> CountingDiscovery {
        CountingDiscovery {
            service: MatterService::new(
                operational_instance_name(cfid, node_id),
                ServiceKind::Operational,
                vec![IpAddr::V4(Ipv4Addr::new(192, 0, 2, 9))],
                5540,
                HashMap::new(),
            ),
            succeed_on,
            polls: 0,
        }
    }

    /// The record appears on the 3rd poll; a budget of 3 succeeds and stops
    /// polling exactly when it finds it. Paused time auto-advances the two
    /// 100 ms inter-poll sleeps so the test runs instantly.
    #[tokio::test(start_paused = true)]
    async fn resolve_operational_with_attempts_succeeds_within_budget() {
        let cfid = [0x87, 0xe1, 0xb0, 0x04, 0xe2, 0x35, 0xa1, 0x30];
        let node_id: u64 = 1;
        let mut disc = counting_discovery(cfid, node_id, 3);
        let addr = resolve_operational_with_attempts(&mut disc, cfid, node_id, 3)
            .await
            .unwrap();
        assert_eq!(
            addr,
            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 0, 2, 9)), 5540)
        );
        assert_eq!(disc.polls, 3, "must poll exactly until the record appears");
    }

    /// The record would appear on the 5th poll, but a budget of 4 gives up
    /// first — proving the attempt count is the hard bound.
    #[tokio::test(start_paused = true)]
    async fn resolve_operational_with_attempts_respects_budget() {
        let cfid = [0x87, 0xe1, 0xb0, 0x04, 0xe2, 0x35, 0xa1, 0x30];
        let node_id: u64 = 1;
        let mut disc = counting_discovery(cfid, node_id, 5);
        let err = resolve_operational_with_attempts(&mut disc, cfid, node_id, 4)
            .await
            .expect_err("a 4-poll budget must give up before the 5th-poll record");
        assert!(matches!(err, DriverError::Discovery(_)), "got {err:?}");
        assert_eq!(disc.polls, 4, "must poll exactly the budget then stop");
    }

    /// The existing `resolve_operational` entry point still resolves via its
    /// delegated 300-attempt budget.
    #[tokio::test]
    async fn resolve_operational_still_resolves_via_delegation() {
        let cfid = [0x87, 0xe1, 0xb0, 0x04, 0xe2, 0x35, 0xa1, 0x30];
        let node_id: u64 = 1;
        let mut disc = counting_discovery(cfid, node_id, 1);
        let addr = resolve_operational(&mut disc, cfid, node_id).await.unwrap();
        assert_eq!(
            addr,
            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 0, 2, 9)), 5540)
        );
    }

    // -----------------------------------------------------------------------
    // run_case loopback test (M6.6.3b Task 5)
    // -----------------------------------------------------------------------

    use matter_cert::test_support::{build_unsigned, with_signature, TestCertFields};
    use matter_cert::{
        BasicConstraints, DistinguishedName, DnAttribute, Extensions, KeyIdentifier, KeyUsage,
        MatterCertificate, MatterTime, PublicKey, Signature, TrustAnchor, TrustedRoots,
    };
    use matter_crypto::{CaseCredentials, CaseResponder, CaseSigner, RingSigner, Sigma1Outcome};
    use matter_transport::{SessionKeys, SessionManager};

    use crate::driver::datagram::InMemoryDatagram;
    use crate::driver::unsecured::{decode_unsecured, encode_unsecured};

    const T_FABRIC_ID: u64 = 0x4242_4242_4242_4242;
    const T_INITIATOR_NODE: u64 = 0xDEAD_BEEF_CAFE_F00D;
    const T_RESPONDER_NODE: u64 = 0xBABE_FEED_1234_5678;
    const T_IPK: [u8; 16] = [0x77; 16];
    const T_RCAC_SKI: [u8; 20] = [0x01; 20];
    const T_NOC_SKI: [u8; 20] = [0x02; 20];

    /// Build a self-signed RCAC and return it with its signer and raw public
    /// key. The caller builds `TrustedRoots` from the returned `&rcac` so
    /// that two independent roots sets (controller + device) can be derived
    /// without requiring `TrustedRoots: Clone` — though it happens to be
    /// `Clone`, both patterns work.
    fn build_test_rcac() -> (MatterCertificate, RingSigner, [u8; 65]) {
        let (rcac_signer, _pkcs8) = RingSigner::generate().unwrap();
        let rcac_pub = *rcac_signer.public_key().as_bytes();
        let rcac_dn = DistinguishedName::new(vec![DnAttribute::RcacId(1)]);
        let extensions = Extensions::builder()
            .basic_constraints(Some(BasicConstraints::new(true, Some(1))))
            .key_usage(Some(KeyUsage::KEY_CERT_SIGN))
            .subject_key_identifier(Some(KeyIdentifier(T_RCAC_SKI)))
            .authority_key_identifier(Some(KeyIdentifier(T_RCAC_SKI)))
            .build();
        let fields = TestCertFields {
            serial: vec![0x01],
            issuer: rcac_dn.clone(),
            not_before: MatterTime::from_unix_secs(1_700_000_000),
            not_after: MatterTime::from_unix_secs(2_500_000_000),
            subject: rcac_dn,
            public_key: PublicKey::new(rcac_pub).unwrap(),
            extensions,
            signature: Signature::new([0u8; 64]),
        };
        let unsigned = build_unsigned(fields);
        let tbs = unsigned.to_x509_tbs_der().unwrap();
        let sig = rcac_signer.sign_p256_sha256(&tbs).unwrap();
        let rcac = with_signature(&unsigned, Signature::new(sig));
        (rcac, rcac_signer, rcac_pub)
    }

    fn roots_for(rcac: &MatterCertificate) -> TrustedRoots {
        let mut roots = TrustedRoots::new();
        roots.add(TrustAnchor::from_root_cert(rcac));
        roots
    }

    fn build_test_noc(rcac_signer: &RingSigner, node_id: u64) -> (MatterCertificate, RingSigner) {
        let (noc_signer, _) = RingSigner::generate().unwrap();
        let noc_pub = *noc_signer.public_key().as_bytes();
        let subject_dn = DistinguishedName::new(vec![
            DnAttribute::FabricId(T_FABRIC_ID),
            DnAttribute::NodeId(node_id),
        ]);
        let issuer_dn = DistinguishedName::new(vec![DnAttribute::RcacId(1)]);
        let extensions = Extensions::builder()
            .basic_constraints(Some(BasicConstraints::new(false, None)))
            .key_usage(Some(KeyUsage::DIGITAL_SIGNATURE))
            .subject_key_identifier(Some(KeyIdentifier(T_NOC_SKI)))
            .authority_key_identifier(Some(KeyIdentifier(T_RCAC_SKI)))
            .build();
        let fields = TestCertFields {
            serial: vec![0x02],
            issuer: issuer_dn,
            not_before: MatterTime::from_unix_secs(1_700_000_000),
            not_after: MatterTime::from_unix_secs(2_500_000_000),
            subject: subject_dn,
            public_key: PublicKey::new(noc_pub).unwrap(),
            extensions,
            signature: Signature::new([0u8; 64]),
        };
        let unsigned = build_unsigned(fields);
        let tbs = unsigned.to_x509_tbs_der().unwrap();
        let sig = rcac_signer.sign_p256_sha256(&tbs).unwrap();
        let noc = with_signature(&unsigned, Signature::new(sig));
        (noc, noc_signer)
    }

    fn creds(
        noc: MatterCertificate,
        signer: RingSigner,
        node_id: u64,
        rcac_pub: [u8; 65],
    ) -> CaseCredentials {
        CaseCredentials {
            noc,
            icac: None,
            signer: Box::new(signer),
            fabric_id: T_FABRIC_ID,
            node_id,
            ipk: T_IPK,
            rcac_public_key: rcac_pub,
        }
    }

    #[tokio::test]
    async fn run_case_surfaces_sigma1_status_report_rejection() {
        // A device that cannot match Sigma1's destination id (e.g. IPK or
        // fabric mismatch) answers with a StatusReport (NoSharedTrustRoots,
        // protocol code 0x0001) instead of Sigma2. run_case must surface the
        // device's codes, not feed the report into the Sigma2 parser
        // (observed: Tapo P110M, M6.6.5 — misparsed as "invalid parameter").
        let (rcac, rcac_signer, rcac_pub) = build_test_rcac();
        let (init_noc, init_signer) = build_test_noc(&rcac_signer, T_INITIATOR_NODE);
        let init_creds = creds(init_noc, init_signer, T_INITIATOR_NODE, rcac_pub);
        let ctrl_roots = roots_for(&rcac);

        let (ctrl_io, dev_io) = InMemoryDatagram::pair();
        let dev_addr = dev_io.local_addr();
        let ctrl_addr = ctrl_io.local_addr();
        let mut sessions = SessionManager::new();

        let device = async {
            let (p, _) = dev_io.recv_from().await.unwrap();
            let m = decode_unsecured(&p).unwrap();
            // StatusReport: FAILURE / SecureChannel NoSharedTrustRoots.
            let mut body = Vec::new();
            body.extend_from_slice(&1u16.to_le_bytes());
            body.extend_from_slice(&0u32.to_le_bytes());
            body.extend_from_slice(&0x0001u16.to_le_bytes());
            let report = encode_unsecured(
                200,
                m.exchange_id,
                0x40,
                matter_transport::ProtocolId::SECURE_CHANNEL,
                false,
                true,
                Some(m.message_counter),
                None,
                &body,
            );
            dev_io.send_to(&report, ctrl_addr).await.unwrap();
        };

        let controller = run_case(
            &ctrl_io,
            &mut sessions,
            dev_addr,
            init_creds,
            ctrl_roots,
            T_RESPONDER_NODE,
            T_FABRIC_ID,
            MatterTime::from_unix_secs(2_000_000_000),
        );

        let (ctrl_result, ()) = tokio::join!(controller, device);
        let err = ctrl_result.unwrap_err();
        assert!(
            matches!(
                err,
                DriverError::SessionEstablishmentFailed {
                    general_code: 1,
                    protocol_code: 0x0001,
                }
            ),
            "expected SessionEstablishmentFailed, got: {err:?}"
        );
    }

    #[tokio::test]
    async fn run_case_establishes_matching_session() {
        let (rcac, rcac_signer, rcac_pub) = build_test_rcac();
        let (init_noc, init_signer) = build_test_noc(&rcac_signer, T_INITIATOR_NODE);
        let (resp_noc, resp_signer) = build_test_noc(&rcac_signer, T_RESPONDER_NODE);
        let init_creds = creds(init_noc, init_signer, T_INITIATOR_NODE, rcac_pub);
        let resp_creds = creds(resp_noc, resp_signer, T_RESPONDER_NODE, rcac_pub);
        let resp_roots = roots_for(&rcac);
        let ctrl_roots = roots_for(&rcac);

        let (ctrl_io, dev_io) = InMemoryDatagram::pair();
        let dev_addr = dev_io.local_addr();
        let ctrl_addr = ctrl_io.local_addr();
        let mut sessions = SessionManager::new();

        let device = async {
            let mut responder = CaseResponder::new(
                resp_creds,
                resp_roots,
                0x00D2,
                MatterTime::from_unix_secs(2_000_000_000),
            )
            .unwrap();
            let (p, _) = dev_io.recv_from().await.unwrap();
            let m = decode_unsecured(&p).unwrap();
            assert!(matches!(
                responder.handle_sigma1(&m.payload).unwrap(),
                Sigma1Outcome::NewSession
            ));
            let sigma2 = responder.next_message().unwrap();
            let wire = encode_unsecured(
                200,
                m.exchange_id,
                0x31,
                matter_transport::ProtocolId::SECURE_CHANNEL,
                false,
                true,
                Some(m.message_counter),
                None,
                &sigma2,
            );
            dev_io.send_to(&wire, ctrl_addr).await.unwrap();
            let (p, _) = dev_io.recv_from().await.unwrap();
            let m = decode_unsecured(&p).unwrap();
            responder.handle_sigma3(&m.payload).unwrap();

            // Close the handshake with a success StatusReport (real-device
            // behaviour) and expect the controller's standalone ack.
            let mut body = Vec::new();
            body.extend_from_slice(&0u16.to_le_bytes());
            body.extend_from_slice(&0u32.to_le_bytes());
            body.extend_from_slice(&0u16.to_le_bytes());
            let report = encode_unsecured(
                201,
                m.exchange_id,
                0x40,
                matter_transport::ProtocolId::SECURE_CHANNEL,
                false,
                true,
                Some(m.message_counter),
                None,
                &body,
            );
            dev_io.send_to(&report, ctrl_addr).await.unwrap();
            let ack = tokio::time::timeout(std::time::Duration::from_secs(2), dev_io.recv_from())
                .await
                .expect("controller must ack the StatusReport")
                .unwrap();
            let ack = decode_unsecured(&ack.0).unwrap();
            assert_eq!(ack.opcode, 0x10);
            assert_eq!(ack.ack_counter, Some(201));

            responder.finish().unwrap()
        };

        let controller = run_case(
            &ctrl_io,
            &mut sessions,
            dev_addr,
            init_creds,
            ctrl_roots,
            T_RESPONDER_NODE,
            T_FABRIC_ID,
            MatterTime::from_unix_secs(2_000_000_000),
        );

        let (ctrl_result, dev_out) = tokio::join!(controller, device);
        let sid = ctrl_result.unwrap();
        let registered = sessions.get(sid).unwrap();
        assert_eq!(registered.keys, SessionKeys::from_case_output(&dev_out));
        assert_eq!(registered.peer_id, matter_transport::SessionId(0x00D2));
    }

    /// M9-G-d Task 2: `run_case_establish` drives the same handshake but returns
    /// the [`CaseSessionOutput`] WITHOUT registering it, advertising the caller's
    /// `local_session_id` in Sigma1. The returned output must (a) carry that
    /// local id and (b) register into a fresh `SessionManager` yielding a usable
    /// session whose keys match the device's — i.e. the hand-back path a spawned,
    /// own-socket connect uses to give the actor a ready-to-register session.
    #[tokio::test]
    async fn run_case_establish_returns_registerable_output() {
        let (rcac, rcac_signer, rcac_pub) = build_test_rcac();
        let (init_noc, init_signer) = build_test_noc(&rcac_signer, T_INITIATOR_NODE);
        let (resp_noc, resp_signer) = build_test_noc(&rcac_signer, T_RESPONDER_NODE);
        let init_creds = creds(init_noc, init_signer, T_INITIATOR_NODE, rcac_pub);
        let resp_creds = creds(resp_noc, resp_signer, T_RESPONDER_NODE, rcac_pub);
        let resp_roots = roots_for(&rcac);
        let ctrl_roots = roots_for(&rcac);

        let (ctrl_io, dev_io) = InMemoryDatagram::pair();
        let dev_addr = dev_io.local_addr();
        let ctrl_addr = ctrl_io.local_addr();

        // The local session id the caller allocates and advertises in Sigma1.
        let local_session_id: u16 = 0x0777;

        let device = async {
            let mut responder = CaseResponder::new(
                resp_creds,
                resp_roots,
                0x00D2,
                MatterTime::from_unix_secs(2_000_000_000),
            )
            .unwrap();
            let (p, _) = dev_io.recv_from().await.unwrap();
            let m = decode_unsecured(&p).unwrap();
            assert!(matches!(
                responder.handle_sigma1(&m.payload).unwrap(),
                Sigma1Outcome::NewSession
            ));
            let sigma2 = responder.next_message().unwrap();
            let wire = encode_unsecured(
                200,
                m.exchange_id,
                0x31,
                matter_transport::ProtocolId::SECURE_CHANNEL,
                false,
                true,
                Some(m.message_counter),
                None,
                &sigma2,
            );
            dev_io.send_to(&wire, ctrl_addr).await.unwrap();
            let (p, _) = dev_io.recv_from().await.unwrap();
            let m = decode_unsecured(&p).unwrap();
            responder.handle_sigma3(&m.payload).unwrap();
            let mut body = Vec::new();
            body.extend_from_slice(&0u16.to_le_bytes());
            body.extend_from_slice(&0u32.to_le_bytes());
            body.extend_from_slice(&0u16.to_le_bytes());
            let report = encode_unsecured(
                201,
                m.exchange_id,
                0x40,
                matter_transport::ProtocolId::SECURE_CHANNEL,
                false,
                true,
                Some(m.message_counter),
                None,
                &body,
            );
            dev_io.send_to(&report, ctrl_addr).await.unwrap();
            let ack = tokio::time::timeout(std::time::Duration::from_secs(2), dev_io.recv_from())
                .await
                .expect("controller must ack the StatusReport")
                .unwrap();
            let ack = decode_unsecured(&ack.0).unwrap();
            assert_eq!(ack.opcode, 0x10);
            assert_eq!(ack.ack_counter, Some(201));
            responder.finish().unwrap()
        };

        let controller = run_case_establish(
            &ctrl_io,
            dev_addr,
            local_session_id,
            init_creds,
            ctrl_roots,
            T_RESPONDER_NODE,
            T_FABRIC_ID,
            MatterTime::from_unix_secs(2_000_000_000),
        );

        let (ctrl_result, dev_out) = tokio::join!(controller, device);
        let output = ctrl_result.unwrap();

        // (a) The output advertises the caller-chosen local session id.
        assert_eq!(output.local.session_id, local_session_id);

        // (b) The un-registered output registers cleanly and yields a usable
        // session whose keys match the device's derived keys.
        let mut sessions = SessionManager::new();
        let sid = sessions.register_case(&output, SessionRole::Initiator);
        let registered = sessions.get(sid).unwrap();
        assert_eq!(registered.keys, SessionKeys::from_case_output(&dev_out));
        assert_eq!(registered.peer_id, matter_transport::SessionId(0x00D2));
    }
}