nmrs 3.4.2

A Rust library for NetworkManager over D-Bus
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
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
use std::collections::HashMap;
use std::future::Future;
use std::panic::{AssertUnwindSafe, resume_unwind};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;

use futures::{FutureExt, StreamExt};
use nmrs::agent::{SecretAgent, SecretAgentFlags, SecretAgentHandle, SecretSetting};
use nmrs::builders::WireGuardBuilder;
use nmrs::raw::zvariant::{OwnedObjectPath, OwnedValue, Value};
use nmrs::{
    ActiveConnection, ActiveConnectionState, ConnectionError, DeviceState, MonitorHandle,
    NetworkEvent, NetworkEventStream, NetworkManager, SettingsChange, SettingsEventStream,
    SettingsPatch, SettingsSummary, TimeoutConfig, WifiKeyMgmt, WifiScope, WifiSecurity,
    WireGuardPeer,
};
use serial_test::serial;
use tokio::time::{sleep, timeout};
use uuid::Uuid;

const DBUS_TIMEOUT: Duration = Duration::from_secs(10);
const EVENT_TIMEOUT: Duration = Duration::from_secs(10);
const WIFI_TIMEOUT: Duration = Duration::from_secs(50);

fn required_env(name: &str) -> String {
    match std::env::var(name) {
        Ok(value) if !value.trim().is_empty() => value,
        Ok(_) => panic!("{name} must not be empty"),
        Err(error) => panic!(
            "{name} is required for this ignored integration test ({error}); use the isolated test harness"
        ),
    }
}

fn required_capability(name: &str) {
    let value = required_env(name);
    assert_eq!(value, "1", "{name} must be set to 1, got {value:?}");
}

async fn bounded<T>(
    description: &str,
    duration: Duration,
    operation: impl Future<Output = T>,
) -> T {
    timeout(duration, operation)
        .await
        .unwrap_or_else(|_| panic!("timed out after {duration:?}: {description}"))
}

async fn network_manager() -> NetworkManager {
    required_capability("NMRS_REQUIRE_NETWORKMANAGER");

    let config = TimeoutConfig::new()
        .with_connection_timeout(Duration::from_secs(40))
        .with_disconnect_timeout(Duration::from_secs(15));
    bounded(
        "connect to the system D-Bus and NetworkManager",
        DBUS_TIMEOUT,
        NetworkManager::with_config(config),
    )
    .await
    .expect("the harness declared NetworkManager available, but initialization failed")
}

async fn next_settings_change(
    stream: &mut SettingsEventStream,
    description: &str,
    mut matches: impl FnMut(&SettingsChange) -> bool,
) -> SettingsChange {
    timeout(EVENT_TIMEOUT, async {
        loop {
            match stream.next().await {
                Some(Ok(change)) if matches(&change) => return change,
                Some(Ok(_)) => {}
                Some(Err(error)) => panic!("settings event stream failed: {error}"),
                None => panic!("settings event stream ended before {description}"),
            }
        }
    })
    .await
    .unwrap_or_else(|_| panic!("timed out waiting for {description}"))
}

async fn next_network_event(
    stream: &mut NetworkEventStream,
    description: &str,
    mut matches: impl FnMut(&NetworkEvent) -> bool,
) -> NetworkEvent {
    timeout(EVENT_TIMEOUT, async {
        loop {
            match stream.next().await {
                Some(Ok(event)) if matches(&event) => return event,
                Some(Ok(_)) => {}
                Some(Err(error)) => panic!("network event stream failed: {error}"),
                None => panic!("network event stream ended before {description}"),
            }
        }
    })
    .await
    .unwrap_or_else(|_| panic!("timed out waiting for {description}"))
}

fn change_has_path(change: &SettingsChange, expected_kind: &str, expected_path: &str) -> bool {
    match (expected_kind, change) {
        ("added", SettingsChange::Added { path })
        | ("updated", SettingsChange::Updated { path })
        | ("removed", SettingsChange::Removed { path }) => path.as_str() == expected_path,
        _ => false,
    }
}

async fn cleanup_saved_profile(nm: &NetworkManager, uuid: &str) -> Vec<String> {
    match timeout(DBUS_TIMEOUT, nm.delete_saved_connection(uuid)).await {
        Ok(Ok(())) => Vec::new(),
        Ok(Err(ConnectionError::SavedConnectionNotFound(missing))) if missing == uuid => Vec::new(),
        Ok(Err(error)) => vec![format!("delete saved profile {uuid}: {error}")],
        Err(_) => vec![format!("delete saved profile {uuid}: timed out")],
    }
}

async fn cleanup_wifi_profile(wifi: &WifiScope, ssid: &str) -> Vec<String> {
    let mut failures = Vec::new();

    match timeout(DBUS_TIMEOUT, wifi.disconnect()).await {
        Ok(Ok(())) => {}
        Ok(Err(error)) => failures.push(format!("disconnect {ssid:?}: {error}")),
        Err(_) => failures.push(format!("disconnect {ssid:?}: timed out")),
    }
    match timeout(WIFI_TIMEOUT, wifi.forget(ssid)).await {
        Ok(Ok(())) => {}
        Ok(Err(error)) => failures.push(format!("forget {ssid:?}: {error}")),
        Err(_) => failures.push(format!("forget {ssid:?}: timed out")),
    }

    failures
}

async fn disconnect_device(nm: &NetworkManager, interface: &str) -> nmrs::Result<()> {
    let path = nm.get_device_by_interface(interface).await?;
    let proxy = nmrs::raw::zbus::Proxy::new(
        nm.dbus_connection(),
        "org.freedesktop.NetworkManager",
        path,
        "org.freedesktop.NetworkManager.Device",
    )
    .await?;
    let state = DeviceState::from(proxy.get_property::<u32>("State").await?);
    if matches!(
        state,
        DeviceState::Unmanaged | DeviceState::Unavailable | DeviceState::Disconnected
    ) {
        return Ok(());
    }

    proxy.call_method("Disconnect", &()).await?;
    loop {
        let state = DeviceState::from(proxy.get_property::<u32>("State").await?);
        if matches!(state, DeviceState::Unavailable | DeviceState::Disconnected) {
            return Ok(());
        }
        sleep(Duration::from_millis(25)).await;
    }
}

async fn cleanup_wired_profile(nm: &NetworkManager, interface: &str) -> Vec<String> {
    let mut failures = Vec::new();
    match timeout(DBUS_TIMEOUT, disconnect_device(nm, interface)).await {
        Ok(Ok(())) => {}
        Ok(Err(error)) => failures.push(format!("disconnect {interface}: {error}")),
        Err(_) => failures.push(format!("disconnect {interface}: timed out")),
    }

    match timeout(DBUS_TIMEOUT, nm.get_saved_connection_uuid(interface)).await {
        Ok(Ok(Some(uuid))) => failures.extend(cleanup_saved_profile(nm, &uuid).await),
        Ok(Ok(None)) => {}
        Ok(Err(error)) => failures.push(format!("resolve {interface} profile: {error}")),
        Err(_) => failures.push(format!("resolve {interface} profile: timed out")),
    }

    failures
}

async fn cleanup_vpn_profile(nm: &NetworkManager, uuid: &str) -> Vec<String> {
    let mut failures = Vec::new();
    match timeout(DBUS_TIMEOUT, nm.disconnect_vpn_by_uuid(uuid)).await {
        Ok(Ok(())) => {}
        Ok(Err(ConnectionError::VpnNotFound(missing))) if missing == uuid => {}
        Ok(Err(error)) => failures.push(format!("disconnect VPN {uuid}: {error}")),
        Err(_) => failures.push(format!("disconnect VPN {uuid}: timed out")),
    }
    failures.extend(cleanup_saved_profile(nm, uuid).await);
    failures
}

async fn cleanup_secret_agent(handle: SecretAgentHandle) -> Option<String> {
    match timeout(DBUS_TIMEOUT, handle.unregister()).await {
        Ok(Ok(())) => None,
        Ok(Err(error)) => Some(format!("unregister secret agent: {error}")),
        Err(_) => Some("unregister secret agent: timed out".into()),
    }
}

#[derive(Debug)]
struct RawActiveConnection {
    path: OwnedObjectPath,
    connection_path: OwnedObjectPath,
    id: String,
    connection_type: String,
    state: u32,
}

async fn raw_active_connection(
    nm: &NetworkManager,
    uuid: &str,
) -> nmrs::Result<Option<RawActiveConnection>> {
    let active_paths = raw_active_paths(nm).await?;

    for path in active_paths {
        let active = nmrs::raw::zbus::Proxy::new(
            nm.dbus_connection(),
            "org.freedesktop.NetworkManager",
            path.clone(),
            "org.freedesktop.NetworkManager.Connection.Active",
        )
        .await?;
        if active.get_property::<String>("Uuid").await? != uuid {
            continue;
        }

        return Ok(Some(RawActiveConnection {
            path,
            connection_path: active.get_property("Connection").await?,
            id: active.get_property("Id").await?,
            connection_type: active.get_property("Type").await?,
            state: active.get_property("State").await?,
        }));
    }

    Ok(None)
}

async fn raw_active_paths(nm: &NetworkManager) -> nmrs::Result<Vec<OwnedObjectPath>> {
    let manager = nmrs::raw::zbus::Proxy::new(
        nm.dbus_connection(),
        "org.freedesktop.NetworkManager",
        "/org/freedesktop/NetworkManager",
        "org.freedesktop.NetworkManager",
    )
    .await?;
    manager
        .get_property::<Vec<OwnedObjectPath>>("ActiveConnections")
        .await
        .map_err(Into::into)
}

async fn stop_monitor(description: &str, handle: MonitorHandle) -> Option<String> {
    match timeout(DBUS_TIMEOUT, handle.stop()).await {
        Ok(Ok(())) => None,
        Ok(Err(error)) => Some(format!("stop {description}: {error}")),
        Err(_) => Some(format!("stop {description}: timed out")),
    }
}

fn finish_after_cleanup(
    outcome: Result<(), Box<dyn std::any::Any + Send>>,
    cleanup_failures: Vec<String>,
) {
    if let Err(payload) = outcome {
        for failure in cleanup_failures {
            eprintln!("cleanup after integration-test panic failed: {failure}");
        }
        resume_unwind(payload);
    }

    assert!(
        cleanup_failures.is_empty(),
        "integration cleanup failed: {}",
        cleanup_failures.join("; ")
    );
}

async fn active_connections(nm: &NetworkManager) -> Vec<ActiveConnection> {
    bounded(
        "list typed active connections",
        DBUS_TIMEOUT,
        nm.list_active_connections(),
    )
    .await
    .expect("failed to list typed active connections")
}

/// Exercises NetworkManager's settings API against the isolated D-Bus harness.
///
/// This is ignored intentionally: a normal `cargo test` must never discover or
/// mutate the developer's host NetworkManager. The CI/Docker harness opts in.
#[tokio::test]
#[serial]
#[ignore = "requires NMRS_REQUIRE_NETWORKMANAGER=1 and an isolated NetworkManager"]
async fn networkmanager_profile_crud_and_settings_events() {
    let nm = network_manager().await;
    let mut events = bounded(
        "subscribe to saved-connection settings events",
        DBUS_TIMEOUT,
        nm.settings_events(),
    )
    .await
    .expect("failed to subscribe to saved-connection settings events");
    let mut network_events = bounded(
        "subscribe to unified NetworkManager events",
        DBUS_TIMEOUT,
        nm.network_events(),
    )
    .await
    .expect("failed to subscribe to unified NetworkManager events");

    let id = format!("nmrs-integration-{}", Uuid::new_v4());
    let renamed_id = format!("{id}-updated");
    let uuid = Uuid::new_v4();
    let uuid_string = uuid.to_string();
    let outcome = AssertUnwindSafe(async {
        let settings = WireGuardBuilder::new(&id)
            .private_key("YBk6X3pP8KjKz7+HFWzVHNqL3qTZq8hX9VxFQJ4zVmM=")
            .address("10.203.0.2/24")
            .add_peer(WireGuardPeer::new(
                "HIgo9xNzJMWLKAShlKl6/bUT1VI9Q0SDBXGtLXkPFXc=",
                "192.0.2.1:51820",
                vec!["10.204.0.0/16".into()],
            ))
            .mtu(1380)
            .uuid(uuid)
            .autoconnect(false)
            .build()
            .expect("the integration WireGuard profile must be valid");

        let path = bounded(
            "add a WireGuard settings profile",
            DBUS_TIMEOUT,
            nm.add_connection(settings),
        )
        .await
        .expect("NetworkManager rejected a valid WireGuard settings profile");
        let path_string = path.as_str().to_owned();

        let added = next_settings_change(&mut events, "the profile Added event", |change| {
            change_has_path(change, "added", &path_string)
        })
        .await;
        assert!(
            matches!(added, SettingsChange::Added { .. }),
            "expected an Added event, got {added:?}"
        );
        let unified_added = next_network_event(
            &mut network_events,
            "the unified SettingsChanged(Added) event",
            |event| {
                matches!(
                    event,
                    NetworkEvent::SettingsChanged(SettingsChange::Added { path })
                        if path.as_str() == path_string
                )
            },
        )
        .await;
        assert!(
            matches!(
                unified_added,
                NetworkEvent::SettingsChanged(SettingsChange::Added { ref path })
                    if path.as_str() == path_string
            ),
            "expected the exact unified Added event, got {unified_added:?}"
        );

        let brief = bounded(
            "list saved connection identities",
            DBUS_TIMEOUT,
            nm.list_saved_connections_brief(),
        )
        .await
        .expect("failed to list saved connection identities")
        .into_iter()
        .find(|profile| profile.uuid == uuid_string)
        .expect("the newly added profile was absent from the brief listing");
        assert_eq!(brief.path, path);
        assert_eq!(brief.id, id);
        assert_eq!(brief.connection_type, "wireguard");

        let profile = bounded(
            "decode the saved WireGuard profile",
            DBUS_TIMEOUT,
            nm.get_saved_connection(&uuid_string),
        )
        .await
        .expect("failed to load the newly added WireGuard profile");
        assert_eq!(profile.path, path);
        assert_eq!(profile.id, id);
        assert_eq!(profile.connection_type, "wireguard");
        assert!(!profile.autoconnect);
        match profile.summary {
            SettingsSummary::WireGuard {
                mtu,
                peer_count,
                first_peer_endpoint,
                ..
            } => {
                assert_eq!(mtu, Some(1380));
                assert_eq!(peer_count, 1);
                assert_eq!(first_peer_endpoint.as_deref(), Some("192.0.2.1:51820"));
            }
            other => panic!("expected a WireGuard settings summary, got {other:?}"),
        }

        let mut patch = SettingsPatch::default();
        patch.id = Some(renamed_id.clone());
        patch.autoconnect = Some(true);
        patch.autoconnect_priority = Some(42);
        bounded(
            "update the saved profile",
            DBUS_TIMEOUT,
            nm.update_saved_connection(&uuid_string, patch),
        )
        .await
        .expect("failed to update the saved profile");

        let updated_event = next_settings_change(&mut events, "the profile Updated event", |change| {
            change_has_path(change, "updated", &path_string)
        })
        .await;
        assert!(
            matches!(updated_event, SettingsChange::Updated { .. }),
            "expected an Updated event, got {updated_event:?}"
        );
        let unified_updated = next_network_event(
            &mut network_events,
            "the unified SettingsChanged(Updated) event",
            |event| {
                matches!(
                    event,
                    NetworkEvent::SettingsChanged(SettingsChange::Updated { path })
                        if path.as_str() == path_string
                )
            },
        )
        .await;
        assert!(
            matches!(
                unified_updated,
                NetworkEvent::SettingsChanged(SettingsChange::Updated { ref path })
                    if path.as_str() == path_string
            ),
            "expected the exact unified Updated event, got {unified_updated:?}"
        );
        let updated = bounded(
            "reload the updated profile",
            DBUS_TIMEOUT,
            nm.get_saved_connection(&uuid_string),
        )
        .await
        .expect("failed to reload the updated profile");
        assert_eq!(updated.id, renamed_id);
        assert!(updated.autoconnect);
        assert_eq!(updated.autoconnect_priority, 42);

        bounded(
            "delete the saved profile",
            DBUS_TIMEOUT,
            nm.delete_saved_connection(&uuid_string),
        )
        .await
        .expect("failed to delete the saved profile");
        let removed_event = next_settings_change(&mut events, "the profile Removed event", |change| {
            change_has_path(change, "removed", &path_string)
        })
        .await;
        assert!(
            matches!(removed_event, SettingsChange::Removed { .. }),
            "expected a Removed event, got {removed_event:?}"
        );
        let unified_removed = next_network_event(
            &mut network_events,
            "the unified SettingsChanged(Removed) event",
            |event| {
                matches!(
                    event,
                    NetworkEvent::SettingsChanged(SettingsChange::Removed { path })
                        if path.as_str() == path_string
                )
            },
        )
        .await;
        assert!(
            matches!(
                unified_removed,
                NetworkEvent::SettingsChanged(SettingsChange::Removed { ref path })
                    if path.as_str() == path_string
            ),
            "expected the exact unified Removed event, got {unified_removed:?}"
        );

        let ids = bounded(
            "list profiles after deletion",
            DBUS_TIMEOUT,
            nm.list_saved_connection_ids(),
        )
        .await
        .expect("failed to list profiles after deletion");
        assert!(!ids.iter().any(|candidate| candidate == &renamed_id));

        let error = bounded(
            "load a deleted profile",
            DBUS_TIMEOUT,
            nm.get_saved_connection(&uuid_string),
        )
        .await
        .expect_err("loading a deleted profile must fail");
        assert!(
            matches!(error, ConnectionError::SavedConnectionNotFound(ref missing) if missing == &uuid_string),
            "expected SavedConnectionNotFound for {uuid_string}, got {error:?}"
        );
    })
    .catch_unwind()
    .await;

    let cleanup_failures = cleanup_saved_profile(&nm, &uuid_string).await;
    finish_after_cleanup(outcome, cleanup_failures);
}

/// Exercises a real NetworkManager-to-agent secret request while activating a
/// native WireGuard VPN, plus registration ownership and cleanup rules.
#[tokio::test]
#[serial]
#[ignore = "requires NMRS_REQUIRE_NETWORKMANAGER=1 and an isolated NetworkManager"]
async fn networkmanager_secret_agent_registration_lifecycle() {
    let nm = network_manager().await;
    let suffix = Uuid::new_v4().simple().to_string();
    let invalid_identifier = format!("com.nmrs:integration.Agent{suffix}");
    let invalid_error = match bounded(
        "reject an invalid secret-agent identifier",
        DBUS_TIMEOUT,
        SecretAgent::builder()
            .with_identifier(&invalid_identifier)
            .register(),
    )
    .await
    {
        Err(error) => error,
        Ok((handle, _requests)) => {
            bounded(
                "unregister unexpectedly accepted invalid agent",
                DBUS_TIMEOUT,
                handle.unregister(),
            )
            .await
            .expect("failed to clean up unexpectedly accepted invalid agent");
            panic!("NetworkManager accepted invalid agent identifier {invalid_identifier:?}");
        }
    };
    assert!(
        matches!(
            invalid_error,
            ConnectionError::AgentRegistration { ref context }
                if context.contains("registering secret agent")
                    && context.contains("InvalidIdentifier")
        ),
        "expected NetworkManager's InvalidIdentifier registration rejection, got {invalid_error:?}"
    );

    let identifier = format!("com.nmrs.integration.Agent{suffix}");
    let (handle, mut requests) = bounded(
        "register the first secret agent",
        DBUS_TIMEOUT,
        SecretAgent::builder()
            .with_identifier(&identifier)
            .register(),
    )
    .await
    .expect("failed to register the first secret agent");
    let mut active_handle = Some(handle);
    let profile_id = format!("nmrs-agent-wireguard-{suffix}");
    let profile_uuid = Uuid::new_v4().to_string();
    let private_key = "YBk6X3pP8KjKz7+HFWzVHNqL3qTZq8hX9VxFQJ4zVmM=";

    let outcome = AssertUnwindSafe(async {
        let duplicate_error = match bounded(
            "reject a duplicate secret-agent identifier",
            DBUS_TIMEOUT,
            SecretAgent::builder()
                .with_identifier(&identifier)
                .register(),
        )
        .await
        {
            Err(error) => error,
            Ok((duplicate, _duplicate_requests)) => {
                bounded(
                    "unregister unexpectedly accepted duplicate agent",
                    DBUS_TIMEOUT,
                    duplicate.unregister(),
                )
                .await
                .expect("failed to clean up unexpectedly accepted duplicate agent");
                panic!("NetworkManager accepted duplicate agent identifier {identifier:?}");
            }
        };
        assert!(
            matches!(duplicate_error, ConnectionError::AgentAlreadyRegistered),
            "expected AgentAlreadyRegistered for duplicate registration, got {duplicate_error:?}"
        );

        let reregister_error = bounded(
            "reject re-registration while the agent is active",
            DBUS_TIMEOUT,
            active_handle
                .as_ref()
                .expect("the primary agent handle disappeared")
                .reregister(),
        )
        .await
        .expect_err("an active secret agent must not re-register");
        assert!(
            matches!(reregister_error, ConnectionError::AgentAlreadyRegistered),
            "expected AgentAlreadyRegistered for active re-registration, got {reregister_error:?}"
        );

        let profile_uuid_value = Uuid::parse_str(&profile_uuid)
            .expect("the generated integration profile UUID must parse");
        let mut settings = WireGuardBuilder::new(&profile_id)
            .private_key(private_key)
            .address("10.207.0.2/24")
            .add_peer(WireGuardPeer::new(
                "HIgo9xNzJMWLKAShlKl6/bUT1VI9Q0SDBXGtLXkPFXc=",
                "192.0.2.1:51820",
                vec!["10.208.0.0/16".into()],
            ))
            .uuid(profile_uuid_value)
            .autoconnect(false)
            .build()
            .expect("the agent-owned WireGuard profile must be valid");
        let wireguard = settings
            .get_mut("wireguard")
            .expect("the WireGuard builder omitted its settings section");
        assert!(
            wireguard.remove("private-key").is_some(),
            "the WireGuard builder omitted its private key"
        );
        wireguard.insert("private-key-flags", Value::from(1u32));

        let profile_path = bounded(
            "add the agent-owned WireGuard profile",
            DBUS_TIMEOUT,
            nm.add_connection(settings),
        )
        .await
        .expect("NetworkManager rejected the agent-owned WireGuard profile");

        let missing_uuid = Uuid::new_v4().to_string();
        let missing_error = bounded(
            "reject activation of a missing VPN UUID",
            DBUS_TIMEOUT,
            nm.connect_vpn_by_uuid(&missing_uuid),
        )
        .await
        .expect_err("activation of a missing VPN UUID must fail");
        assert!(
            matches!(missing_error, ConnectionError::VpnNotFound(ref missing) if missing == &missing_uuid),
            "expected VpnNotFound for {missing_uuid}, got {missing_error:?}"
        );

        let get_secrets = async {
            let profile = nmrs::raw::zbus::Proxy::new(
                nm.dbus_connection(),
                "org.freedesktop.NetworkManager",
                profile_path.clone(),
                "org.freedesktop.NetworkManager.Settings.Connection",
            )
            .await
            .expect("failed to create the saved-profile D-Bus proxy");
            let reply = profile
                .call_method("GetSecrets", &("wireguard",))
                .await
                .expect("NetworkManager failed to route GetSecrets to the registered agent");
            reply
                .body()
                .deserialize::<HashMap<String, HashMap<String, OwnedValue>>>()
                .expect("NetworkManager returned a malformed GetSecrets reply")
        };
        let secret_exchange = async {
            let request = bounded(
                "receive NetworkManager's saved-profile GetSecrets request",
                DBUS_TIMEOUT,
                requests.next(),
            )
            .await
            .expect("the secret-agent request stream closed during activation");
            assert_eq!(request.connection_uuid, profile_uuid);
            assert_eq!(request.connection_id, profile_id);
            assert_eq!(request.connection_type, "wireguard");
            assert_eq!(request.connection_path, profile_path);
            assert!(
                matches!(request.setting, SecretSetting::Other(ref name) if name == "wireguard"),
                "expected a wireguard secret request, got {:?}",
                request.setting
            );
            assert_eq!(
                request.flags,
                SecretAgentFlags::USER_REQUESTED,
                "saved-profile GetSecrets used unexpected request flags: {:?}",
                request.flags,
            );
            assert!(request.hints.is_empty());
            assert!(request.existing_secrets.is_empty());

            let mut reply = HashMap::new();
            reply.insert(
                "private-key".into(),
                OwnedValue::from(nmrs::raw::zvariant::Str::from(private_key)),
            );
            request
                .responder
                .raw("wireguard", reply)
                .await
                .expect("failed to route the WireGuard secret reply to NetworkManager");
        };
        let (returned_secrets, ()) = tokio::join!(get_secrets, secret_exchange);
        let returned_private_key = <&str>::try_from(
            returned_secrets
                .get("wireguard")
                .and_then(|setting| setting.get("private-key"))
                .expect("the GetSecrets reply omitted wireguard.private-key"),
        )
        .expect("wireguard.private-key was not returned as a string");
        assert_eq!(returned_private_key, private_key);

        let mut wireguard_overlay = HashMap::new();
        wireguard_overlay.insert(
            "private-key".into(),
            OwnedValue::from(nmrs::raw::zvariant::Str::from(returned_private_key)),
        );
        wireguard_overlay.insert("private-key-flags".into(), OwnedValue::from(0u32));
        let mut overlay = HashMap::new();
        overlay.insert("wireguard".into(), wireguard_overlay);
        let mut patch = SettingsPatch::default();
        patch.raw_overlay = Some(overlay);
        bounded(
            "persist the agent-provided WireGuard private key",
            DBUS_TIMEOUT,
            nm.update_saved_connection(&profile_uuid, patch),
        )
        .await
        .expect("failed to persist the agent-provided WireGuard private key");

        bounded(
            "activate the configured WireGuard profile",
            WIFI_TIMEOUT,
            nm.connect_vpn_by_uuid(&profile_uuid),
        )
        .await
        .expect("WireGuard activation failed after persisting the agent-provided key");

        let raw_active = bounded(
            "inspect the active WireGuard connection over D-Bus",
            DBUS_TIMEOUT,
            raw_active_connection(&nm, &profile_uuid),
        )
        .await
        .expect("failed to inspect active connections over D-Bus")
        .expect("NetworkManager omitted the activated WireGuard connection");
        assert_ne!(raw_active.path.as_str(), "/");
        assert_eq!(raw_active.connection_path, profile_path);
        assert_eq!(raw_active.id, profile_id);
        assert_eq!(raw_active.connection_type, "wireguard");
        assert_eq!(raw_active.state, 2, "raw active state was not Activated");

        let mut last_active = Vec::new();
        let active_vpn = timeout(EVENT_TIMEOUT, async {
            loop {
                last_active = active_connections(&nm).await;
                if let Some(vpn) = last_active.iter().find_map(|connection| match connection {
                    ActiveConnection::Vpn(vpn)
                        if vpn.uuid == profile_uuid
                            && vpn.state == ActiveConnectionState::Activated
                            && vpn.interface.as_deref() == Some("wg-nmrs-agent")
                            && vpn
                                .ip4_address
                                .as_deref()
                                .is_some_and(|address| address.starts_with("10.207.0.2/")) =>
                    {
                        Some(vpn.clone())
                    }
                    _ => None,
                }) {
                    break vpn;
                }
                sleep(Duration::from_millis(25)).await;
            }
        })
        .await
        .unwrap_or_else(|_| {
            panic!(
                "typed active connections never exposed the configured WireGuard state: {last_active:?}"
            )
        });
        assert_eq!(active_vpn.id, profile_id);
        assert_eq!(active_vpn.state, ActiveConnectionState::Activated);
        assert_eq!(active_vpn.interface.as_deref(), Some("wg-nmrs-agent"));
        assert!(
            active_vpn
                .ip4_address
                .as_deref()
                .is_some_and(|address| address.starts_with("10.207.0.2/")),
            "typed VPN connection omitted its configured address: {active_vpn:?}"
        );

        bounded(
            "deactivate the WireGuard VPN",
            DBUS_TIMEOUT,
            nm.disconnect_vpn_by_uuid(&profile_uuid),
        )
        .await
        .expect("failed to deactivate the WireGuard VPN");
        timeout(EVENT_TIMEOUT, async {
            loop {
                let raw_absent = raw_active_paths(&nm)
                    .await
                    .expect("failed to inspect D-Bus state after VPN deactivation")
                    .iter()
                    .all(|path| path != &raw_active.path);
                if raw_absent {
                    let typed_absent =
                        !active_connections(&nm).await.iter().any(|connection| {
                            matches!(connection, ActiveConnection::Vpn(vpn) if vpn.uuid == profile_uuid)
                        });
                    if typed_absent {
                        break;
                    }
                }
                sleep(Duration::from_millis(25)).await;
            }
        })
        .await
        .expect("WireGuard remained active after D-Bus deactivation");

        bounded(
            "delete the agent-owned WireGuard profile",
            DBUS_TIMEOUT,
            nm.delete_saved_connection(&profile_uuid),
        )
        .await
        .expect("failed to delete the agent-owned WireGuard profile");

        let primary = active_handle
            .take()
            .expect("the primary agent handle disappeared before unregister");
        bounded(
            "unregister the first secret agent",
            DBUS_TIMEOUT,
            primary.unregister(),
        )
        .await
        .expect("failed to unregister the first secret agent");
        assert!(
            bounded(
                "wait for the first request stream to close",
                DBUS_TIMEOUT,
                requests.next(),
            )
            .await
            .is_none(),
            "secret request stream remained open after unregister"
        );

        let (replacement, mut replacement_requests) = bounded(
            "re-register the released secret-agent identifier",
            DBUS_TIMEOUT,
            SecretAgent::builder()
                .with_identifier(&identifier)
                .register(),
        )
        .await
        .expect("the identifier was not released after unregister");
        active_handle = Some(replacement);
        let replacement = active_handle
            .take()
            .expect("the replacement agent handle disappeared before unregister");
        bounded(
            "unregister the replacement secret agent",
            DBUS_TIMEOUT,
            replacement.unregister(),
        )
        .await
        .expect("failed to unregister the replacement secret agent");
        assert!(
            bounded(
                "wait for the replacement request stream to close",
                DBUS_TIMEOUT,
                replacement_requests.next(),
            )
            .await
            .is_none(),
            "replacement request stream remained open after unregister"
        );
    })
    .catch_unwind()
    .await;

    let mut cleanup_failures = cleanup_vpn_profile(&nm, &profile_uuid).await;
    if let Some(handle) = active_handle.take()
        && let Some(failure) = cleanup_secret_agent(handle).await
    {
        cleanup_failures.push(failure);
    }
    finish_after_cleanup(outcome, cleanup_failures);
}

/// Exercises a deterministic veth/DHCP wired connection without touching the
/// container's Docker-provided `eth0` interface.
#[tokio::test]
#[serial]
#[ignore = "requires NMRS_REQUIRE_WIRED=1 and the isolated veth harness"]
async fn wired_connection_lifecycle() {
    required_capability("NMRS_REQUIRE_WIRED");
    let interface = required_env("NMRS_WIRED_INTERFACE");
    let nm = network_manager().await;

    let outcome = AssertUnwindSafe(async {
        let devices = bounded("list wired devices", DBUS_TIMEOUT, nm.list_wired_devices())
            .await
            .expect("failed to list wired devices");
        let device = devices
            .iter()
            .find(|device| device.interface == interface)
            .unwrap_or_else(|| {
                panic!("managed veth interface {interface:?} was missing: {devices:?}")
            });
        assert_eq!(device.managed, Some(true));
        assert!(!device.path.is_empty());

        let details = bounded(
            "list detailed wired devices",
            DBUS_TIMEOUT,
            nm.list_wired_device_details(),
        )
        .await
        .expect("failed to list detailed wired devices");
        let detail = details
            .iter()
            .find(|device| device.interface == interface)
            .expect("managed veth was absent from detailed wired devices");
        assert!(!detail.path.is_empty());
        assert!(!detail.hw_address.is_empty());
        assert!(detail.active_connection_id.is_none());

        bounded(
            "connect the managed veth client",
            WIFI_TIMEOUT,
            nm.connect_wired(),
        )
        .await
        .expect("wired activation or DHCP failed");
        let saved_uuid = bounded(
            "resolve the wired profile UUID",
            DBUS_TIMEOUT,
            nm.get_saved_connection_uuid(&interface),
        )
        .await
        .expect("failed to resolve the wired profile UUID")
        .expect("wired activation did not create a saved profile");

        let active = active_connections(&nm).await;
        let active_wired = active
            .iter()
            .find_map(|connection| match connection {
                ActiveConnection::Wired(wired)
                    if wired.interface.as_deref() == Some(interface.as_str()) =>
                {
                    Some(wired.clone())
                }
                _ => None,
            })
            .unwrap_or_else(|| {
                panic!("typed active connections omitted the veth connection: {active:?}")
            });
        assert_eq!(active_wired.id, interface);
        assert_eq!(active_wired.uuid, saved_uuid);
        assert_eq!(active_wired.state, ActiveConnectionState::Activated);
        assert!(
            active_wired
                .ip4_address
                .as_deref()
                .is_some_and(|address| address.starts_with("192.168.251.")),
            "typed wired connection omitted its DHCP address"
        );

        let connected_details = bounded(
            "read connected wired details",
            DBUS_TIMEOUT,
            nm.list_wired_device_details(),
        )
        .await
        .expect("failed to read connected wired details");
        let connected = connected_details
            .iter()
            .find(|device| device.interface == interface)
            .expect("connected veth was absent from detailed wired devices");
        assert_eq!(connected.state, DeviceState::Activated);
        assert_eq!(
            connected.active_connection_id.as_deref(),
            Some(interface.as_str())
        );
        assert!(
            connected
                .ip4_address
                .as_deref()
                .is_some_and(|address| address.starts_with("192.168.251."))
        );

        bounded(
            "disconnect the managed veth client",
            DBUS_TIMEOUT,
            disconnect_device(&nm, &interface),
        )
        .await
        .expect("failed to disconnect the managed veth client");
        timeout(EVENT_TIMEOUT, async {
            loop {
                if !active_connections(&nm).await.iter().any(|connection| {
                    matches!(connection, ActiveConnection::Wired(wired) if wired.uuid == saved_uuid)
                }) {
                    break;
                }
                sleep(Duration::from_millis(25)).await;
            }
        })
        .await
        .expect("typed wired connection remained active after disconnect");

        let disconnected_details = bounded(
            "read disconnected wired details",
            DBUS_TIMEOUT,
            nm.list_wired_device_details(),
        )
        .await
        .expect("failed to read disconnected wired details");
        let disconnected = disconnected_details
            .iter()
            .find(|device| device.interface == interface)
            .expect("disconnected veth was absent from detailed wired devices");
        assert_eq!(disconnected.state, DeviceState::Disconnected);
        assert!(disconnected.active_connection_id.is_none());

        bounded(
            "delete the wired profile",
            DBUS_TIMEOUT,
            nm.delete_saved_connection(&saved_uuid),
        )
        .await
        .expect("failed to delete the wired profile");
        assert!(
            bounded(
                "resolve wired profile after deletion",
                DBUS_TIMEOUT,
                nm.get_saved_connection_uuid(&interface),
            )
            .await
            .expect("failed to resolve wired profile after deletion")
            .is_none()
        );
    })
    .catch_unwind()
    .await;

    let cleanup_failures = cleanup_wired_profile(&nm, &interface).await;
    finish_after_cleanup(outcome, cleanup_failures);
}

/// Proves discovery, WPA authentication, DHCP, saved-secret reuse, and cleanup
/// against the deterministic mac80211_hwsim access point.
#[tokio::test]
#[serial]
#[ignore = "requires the isolated mac80211_hwsim WiFi harness"]
async fn wifi_wpa_saved_connection_lifecycle() {
    required_capability("NMRS_REQUIRE_WIFI");
    let interface = required_env("NMRS_WIFI_INTERFACE");
    let ssid = required_env("NMRS_EXPECT_WIFI_SSID");
    let absent_ssid = format!("{ssid}-absent");
    let password = required_env("NMRS_WIFI_PASSWORD");
    assert!(
        (8..=63).contains(&password.len()),
        "NMRS_WIFI_PASSWORD must be a valid WPA passphrase"
    );

    let nm = network_manager().await;
    let initial_wifi_enabled = bounded(
        "read the initial WiFi radio state",
        DBUS_TIMEOUT,
        nm.wifi_state(),
    )
    .await
    .expect("failed to capture the WiFi radio state before the test")
    .enabled;
    let wifi = nm.wifi(&interface);
    let device_callback_count = Arc::new(AtomicUsize::new(0));
    let callback_count = Arc::clone(&device_callback_count);
    let network_callback_count = Arc::new(AtomicUsize::new(0));
    let network_callback = Arc::clone(&network_callback_count);
    let mut device_monitor = None;
    let mut network_monitor = None;

    let outcome = AssertUnwindSafe(async {
        device_monitor = Some(
            bounded(
                "start the WiFi device callback monitor",
                DBUS_TIMEOUT,
                nm.monitor_device_changes(move || {
                    callback_count.fetch_add(1, Ordering::SeqCst);
                }),
            )
            .await
            .expect("the WiFi device callback monitor did not become ready"),
        );
        network_monitor = Some(
            bounded(
                "start the WiFi network callback monitor",
                DBUS_TIMEOUT,
                nm.monitor_network_changes(move || {
                    network_callback.fetch_add(1, Ordering::SeqCst);
                }),
            )
            .await
            .expect("the WiFi network callback monitor did not become ready"),
        );

        bounded(
            "enable the WiFi radio",
            DBUS_TIMEOUT,
            nm.set_wireless_enabled(true),
        )
        .await
        .expect("the harness declared WiFi available, but enabling it failed");
        bounded(
            "wait for the WiFi device to become ready",
            DBUS_TIMEOUT,
            nm.wait_for_wifi_ready(),
        )
        .await
        .expect("the harness WiFi device did not become ready");

        let devices = bounded(
            "list wireless devices",
            DBUS_TIMEOUT,
            nm.list_wireless_devices(),
        )
        .await
        .expect("failed to list wireless devices");
        let device = devices
            .iter()
            .find(|device| device.interface == interface)
            .unwrap_or_else(|| {
                panic!("harness WiFi interface {interface:?} was not managed: {devices:?}")
            });
        assert!(!device.path.is_empty());
        assert_eq!(device.managed, Some(true));

        bounded(
            "remove any stale test profile",
            DBUS_TIMEOUT,
            wifi.forget(&ssid),
        )
        .await
        .expect("failed to remove a stale test profile");
        bounded(
            "remove any stale absent-network profile",
            DBUS_TIMEOUT,
            wifi.forget(&absent_ssid),
        )
        .await
        .expect("failed to remove a stale absent-network profile");

        let absent_error = bounded(
            "reject an absent SSID",
            WIFI_TIMEOUT,
            wifi.connect(
                &absent_ssid,
                WifiSecurity::WpaPsk {
                    psk: password.clone(),
                },
            ),
        )
        .await
        .expect_err("connecting to an absent SSID must fail");
        assert!(
            matches!(absent_error, ConnectionError::NotFound),
            "expected NotFound for absent SSID, got {absent_error:?}"
        );
        assert!(
            !bounded(
                "check absent SSID profile",
                DBUS_TIMEOUT,
                nm.has_saved_connection(&absent_ssid),
            )
            .await
            .expect("failed to check the absent SSID profile"),
            "an absent SSID created a saved profile"
        );

        bounded("scan for the harness AP", DBUS_TIMEOUT, wifi.scan())
            .await
            .expect("the harness WiFi scan failed");
        let network = timeout(Duration::from_secs(15), async {
            loop {
                let networks = wifi
                    .list_networks()
                    .await
                    .expect("listing WiFi scan results failed");
                if let Some(network) = networks.into_iter().find(|network| network.ssid == ssid) {
                    return network;
                }
                sleep(Duration::from_millis(500)).await;
            }
        })
        .await
        .unwrap_or_else(|_| panic!("the expected access point {ssid:?} was not discovered"));
        assert_eq!(network.device, interface);
        assert!(network.secured);
        assert!(network.is_psk);
        assert!(!network.is_eap);
        assert!(!network.best_bssid.is_empty());
        assert!(
            network
                .bssids
                .iter()
                .any(|bssid| bssid == &network.best_bssid)
        );

        network_callback_count.store(0, Ordering::SeqCst);
        bounded(
            "disable WiFi to remove the monitored access point",
            DBUS_TIMEOUT,
            nm.set_wireless_enabled(false),
        )
        .await
        .expect("failed to disable WiFi for the network-monitor contract");
        timeout(EVENT_TIMEOUT, async {
            while network_callback_count.load(Ordering::SeqCst) == 0 {
                sleep(Duration::from_millis(25)).await;
            }
        })
        .await
        .expect("network callback was not delivered when the access point disappeared");
        bounded(
            "re-enable WiFi after the network-monitor contract",
            DBUS_TIMEOUT,
            nm.set_wireless_enabled(true),
        )
        .await
        .expect("failed to re-enable WiFi after the network-monitor contract");
        bounded(
            "wait for WiFi after the network-monitor contract",
            DBUS_TIMEOUT,
            nm.wait_for_wifi_ready(),
        )
        .await
        .expect("the WiFi device did not recover after re-enabling it");
        bounded(
            "rescan after the network-monitor contract",
            DBUS_TIMEOUT,
            wifi.scan(),
        )
        .await
        .expect("the post-monitor WiFi scan failed");
        let access_point = timeout(Duration::from_secs(15), async {
            loop {
                let access_points = wifi
                    .list_access_points()
                    .await
                    .expect("listing per-BSSID access points failed");
                if let Some(access_point) = access_points
                    .into_iter()
                    .find(|access_point| access_point.ssid == ssid)
                {
                    return access_point;
                }
                sleep(Duration::from_millis(500)).await;
            }
        })
        .await
        .unwrap_or_else(|_| panic!("the access point {ssid:?} did not return after re-enabling"));
        assert_eq!(access_point.interface, interface);
        assert_eq!(access_point.ssid_bytes, ssid.as_bytes());
        assert!(!access_point.bssid.is_empty());
        assert!(access_point.frequency_mhz > 0);
        assert!(access_point.security.psk);
        let expected_bssid = access_point.bssid.clone();

        let wrong_psk_error = bounded(
            "reject an incorrect WPA passphrase",
            WIFI_TIMEOUT,
            wifi.connect(
                &ssid,
                WifiSecurity::WpaPsk {
                    psk: "nmrs-definitely-wrong-password".into(),
                },
            ),
        )
        .await
        .expect_err("an incorrect WPA passphrase must fail");
        assert!(
            matches!(wrong_psk_error, ConnectionError::AuthFailed),
            "expected AuthFailed for an incorrect WPA passphrase, got {wrong_psk_error:?}"
        );
        assert!(
            !bounded(
                "check state after rejected WPA authentication",
                DBUS_TIMEOUT,
                nm.is_connected(&ssid),
            )
            .await
            .expect("failed to query state after rejected WPA authentication")
        );
        assert!(
            !active_connections(&nm)
                .await
                .iter()
                .any(|active| matches!(active, ActiveConnection::Wifi(wifi) if wifi.ssid == ssid)),
            "rejected WPA authentication left an active WiFi connection"
        );
        assert!(
            !bounded(
                "check profile after rejected WPA authentication",
                DBUS_TIMEOUT,
                nm.has_saved_connection(&ssid),
            )
            .await
            .expect("failed to query profile after rejected WPA authentication"),
            "rejected WPA authentication left a saved bad profile"
        );

        device_callback_count.store(0, Ordering::SeqCst);
        bounded(
            "connect to the WPA access point",
            WIFI_TIMEOUT,
            wifi.connect(
                &ssid,
                WifiSecurity::WpaPsk {
                    psk: password.clone(),
                },
            ),
        )
        .await
        .expect("WPA authentication or DHCP activation failed");
        timeout(EVENT_TIMEOUT, async {
            while device_callback_count.load(Ordering::SeqCst) == 0 {
                sleep(Duration::from_millis(25)).await;
            }
        })
        .await
        .expect("device callback was not delivered during WiFi activation");
        assert!(
            bounded(
                "check connected state",
                DBUS_TIMEOUT,
                nm.is_connected(&ssid)
            )
            .await
            .expect("failed to query connected state")
        );
        let current_ssid = bounded("read the current SSID", DBUS_TIMEOUT, nm.current_ssid()).await;
        assert_eq!(current_ssid.as_deref(), Some(ssid.as_str()));

        let active = bounded(
            "read the active WiFi network",
            DBUS_TIMEOUT,
            nm.current_network(),
        )
        .await
        .expect("failed to read the active WiFi network")
        .expect("connect returned success without an active WiFi network");
        assert_eq!(active.ssid, ssid);
        assert_eq!(active.device, interface);
        assert!(active.is_active);
        let ip4_address = active
            .ip4_address
            .as_deref()
            .expect("successful activation did not acquire an IPv4 DHCP lease");
        assert!(
            ip4_address.starts_with("192.168.250."),
            "unexpected DHCP address {ip4_address:?}"
        );

        assert!(
            bounded(
                "check for the saved WiFi profile",
                DBUS_TIMEOUT,
                nm.has_saved_connection(&ssid),
            )
            .await
            .expect("failed to query the saved WiFi profile")
        );
        let saved_path = bounded(
            "resolve the saved WiFi path",
            DBUS_TIMEOUT,
            nm.get_saved_connection_path(&ssid),
        )
        .await
        .expect("failed to resolve the saved WiFi path")
        .expect("successful WPA connection did not create a saved profile");
        assert_ne!(saved_path.as_str(), "/");
        let saved_uuid = bounded(
            "resolve the saved WiFi UUID",
            DBUS_TIMEOUT,
            nm.get_saved_connection_uuid(&ssid),
        )
        .await
        .expect("failed to resolve the saved WiFi UUID")
        .expect("successful WPA connection had no saved UUID");
        let saved = bounded(
            "decode the saved WiFi profile",
            DBUS_TIMEOUT,
            nm.get_saved_connection(&saved_uuid),
        )
        .await
        .expect("failed to decode the saved WiFi profile");
        assert_eq!(saved.id, ssid);
        assert_eq!(saved.connection_type, "802-11-wireless");
        match saved.summary {
            SettingsSummary::Wifi {
                ssid: saved_ssid,
                security: Some(security),
                ..
            } => {
                assert_eq!(saved_ssid, ssid);
                assert_eq!(security.key_mgmt, WifiKeyMgmt::WpaPsk);
            }
            other => panic!("expected a WPA WiFi settings summary, got {other:?}"),
        }

        let active = active_connections(&nm).await;
        let typed_wifi = active
            .iter()
            .find_map(|connection| match connection {
                ActiveConnection::Wifi(wifi) if wifi.ssid == ssid => Some(wifi.clone()),
                _ => None,
            })
            .unwrap_or_else(|| {
                panic!("typed active connections omitted the connected WiFi network: {active:?}")
            });
        assert_eq!(typed_wifi.id, ssid);
        assert_eq!(typed_wifi.uuid, saved_uuid);
        assert_eq!(typed_wifi.ssid, ssid);
        assert_eq!(typed_wifi.interface.as_deref(), Some(interface.as_str()));
        assert_eq!(typed_wifi.bssid.as_deref(), Some(expected_bssid.as_str()));
        assert!(typed_wifi.strength.is_some());
        assert_eq!(typed_wifi.state, ActiveConnectionState::Activated);
        assert!(
            typed_wifi
                .ip4_address
                .as_deref()
                .is_some_and(|address| address.starts_with("192.168.250.")),
            "typed active WiFi connection omitted its DHCP address"
        );

        bounded(
            "disconnect the WiFi device",
            DBUS_TIMEOUT,
            wifi.disconnect(),
        )
        .await
        .expect("failed to disconnect after the initial WPA connection");
        assert!(
            !bounded(
                "check disconnected state",
                DBUS_TIMEOUT,
                nm.is_connected(&ssid),
            )
            .await
            .expect("failed to query disconnected state")
        );
        assert!(
            !active_connections(&nm).await.iter().any(
                |active| matches!(active, ActiveConnection::Wifi(wifi) if wifi.uuid == saved_uuid)
            ),
            "typed active WiFi connection remained after disconnect"
        );

        bounded(
            "reconnect with NetworkManager's saved PSK",
            WIFI_TIMEOUT,
            wifi.connect(&ssid, WifiSecurity::WpaPsk { psk: String::new() }),
        )
        .await
        .expect("saved-credential WPA reconnect failed");
        assert!(
            bounded(
                "check saved-credential reconnect",
                DBUS_TIMEOUT,
                nm.is_connected(&ssid),
            )
            .await
            .expect("failed to query the saved-credential reconnect")
        );

        bounded(
            "forget the active WiFi profile",
            WIFI_TIMEOUT,
            wifi.forget(&ssid),
        )
        .await
        .expect("failed to disconnect and forget the WiFi profile");
        assert!(
            !bounded(
                "check profile removal",
                DBUS_TIMEOUT,
                nm.has_saved_connection(&ssid),
            )
            .await
            .expect("failed to query profile removal")
        );
        assert!(
            bounded(
                "resolve path after forgetting",
                DBUS_TIMEOUT,
                nm.get_saved_connection_path(&ssid),
            )
            .await
            .expect("failed to resolve the profile path after forgetting")
            .is_none()
        );
        assert!(
            bounded(
                "resolve UUID after forgetting",
                DBUS_TIMEOUT,
                nm.get_saved_connection_uuid(&ssid),
            )
            .await
            .expect("failed to resolve the profile UUID after forgetting")
            .is_none()
        );

        let error = bounded(
            "reject an empty PSK without saved credentials",
            DBUS_TIMEOUT,
            wifi.connect(&ssid, WifiSecurity::WpaPsk { psk: String::new() }),
        )
        .await
        .expect_err("an empty PSK without a saved profile must fail");
        assert!(
            matches!(error, ConnectionError::MissingPassword),
            "expected MissingPassword after forgetting saved credentials, got {error:?}"
        );
    })
    .catch_unwind()
    .await;

    let mut cleanup_failures = cleanup_wifi_profile(&wifi, &ssid).await;
    match timeout(WIFI_TIMEOUT, wifi.forget(&absent_ssid)).await {
        Ok(Ok(())) => {}
        Ok(Err(error)) => cleanup_failures.push(format!("forget {absent_ssid:?}: {error}")),
        Err(_) => cleanup_failures.push(format!("forget {absent_ssid:?}: timed out")),
    }
    if let Some(handle) = device_monitor.take()
        && let Some(failure) = stop_monitor("WiFi device callback monitor", handle).await
    {
        cleanup_failures.push(failure);
    }
    if let Some(handle) = network_monitor.take()
        && let Some(failure) = stop_monitor("WiFi network callback monitor", handle).await
    {
        cleanup_failures.push(failure);
    }
    match timeout(DBUS_TIMEOUT, nm.set_wireless_enabled(initial_wifi_enabled)).await {
        Ok(Ok(())) => {}
        Ok(Err(error)) => cleanup_failures.push(format!(
            "restore WiFi radio enabled={initial_wifi_enabled}: {error}"
        )),
        Err(_) => cleanup_failures.push(format!(
            "restore WiFi radio enabled={initial_wifi_enabled}: timed out"
        )),
    }
    finish_after_cleanup(outcome, cleanup_failures);
}