trusty-common 0.53.5

Shared utilities and provider-agnostic streaming chat (ChatProvider, OllamaProvider, OpenRouter, tool-use) for trusty-* projects
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
//! Coverage for the #5099 socket-permission contract.
//!
//! The mode assertions are the regression proof: against the pre-fix commit —
//! where every bind site called `UnixListener::bind` bare — the socket comes
//! back at the umask-derived mode (`0755` under the common `022` umask) and the
//! directory at whatever `create_dir_all` produced.
//!
//! Every refusal path is covered by a pure decision function
//! (`classify_existing_dir`, `peer_uid_verdict`), so foreign-uid and
//! foreign-owner policy is asserted without root and without a second account.
//! What remains genuinely unreachable unprivileged is only the platform syscall
//! plumbing that feeds those functions.

use super::dir::{DirVerdict, classify_existing_dir};
use super::peer::peer_uid_verdict;
use super::singleton::{TakeoverVerdict, classify_takeover};
use super::*;

use std::os::unix::fs::PermissionsExt;
use std::time::Duration;

/// Mode bits of `path`, masked to the permission nibbles. Uses `lstat` so a
/// symlink's own mode is reported, never its target's.
fn mode_of(path: &Path) -> u32 {
    std::fs::symlink_metadata(path)
        .expect("stat path under test")
        .permissions()
        .mode()
        & 0o777
}

// ── path resolution ─────────────────────────────────────────────────────────

#[test]
fn scratch_socket_dir_from_uses_tmpdir_when_set() {
    // Why: on macOS the per-user `/var/folders/…/T/` must be honored, not
    // replaced by `/tmp`.
    let dir = scratch_socket_dir_from(Some("/var/folders/xy/T"), 501);
    assert_eq!(dir, Path::new("/var/folders/xy/T/trusty-501"));
}

#[test]
fn scratch_socket_dir_from_falls_back_to_tmp() {
    // Why: #5099's core exposure — an unset `TMPDIR` on Linux used to land the
    // socket directly in world-writable `/tmp`. The fallback must still
    // interpose a uid-keyed directory that this process can hold at 0700.
    for absent in [None, Some(""), Some("   ")] {
        let dir = scratch_socket_dir_from(absent, 1000);
        assert_eq!(
            dir,
            Path::new("/tmp/trusty-1000"),
            "TMPDIR={absent:?} must still get a uid-keyed subdirectory"
        );
    }
}

#[test]
fn scratch_socket_dir_is_uid_keyed() {
    // Why: two users on one host must never share a socket directory.
    let dir = scratch_socket_dir();
    let leaf = dir
        .file_name()
        .and_then(|n| n.to_str())
        .expect("scratch dir has a leaf name");
    assert_eq!(leaf, format!("trusty-{}", self_uid()));
}

// ── sun_path budget (review finding 4) ──────────────────────────────────────

#[test]
fn sun_path_capacity_is_platform_plausible() {
    // Why: derived from struct layout, so a wrong answer would silently skew
    // every budget check. macOS is 104, Linux 108.
    let cap = sun_path_capacity();
    assert!(
        (104..=108).contains(&cap),
        "sun_path capacity {cap} is outside the known 104..=108 range"
    );
}

#[test]
fn check_sun_path_budget_accepts_a_path_that_fits() {
    let path = PathBuf::from("/tmp/trusty-501/short.sock");
    check_sun_path_budget(&path).expect("a short path must fit");
}

#[test]
fn check_sun_path_budget_rejects_an_over_long_path() {
    // Why: the pre-check exists to replace a bare `invalid argument` with a
    // message naming the budget and the overflow.
    let long = format!("/tmp/{}.sock", "x".repeat(sun_path_capacity()));
    let err = check_sun_path_budget(Path::new(&long)).expect_err("must reject");
    match err {
        UdsSecurityError::PathTooLong { len, capacity, .. } => {
            assert!(len >= capacity, "len {len} must exceed capacity {capacity}");
            let rendered = err.to_string();
            assert!(
                rendered.contains(&capacity.to_string()) && rendered.contains(&len.to_string()),
                "diagnostic must name both the budget and the actual length: {rendered}"
            );
        }
        other => panic!("expected PathTooLong, got {other:?}"),
    }
}

#[tokio::test]
async fn bind_hardened_rejects_an_over_long_path() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let long = tmp.path().join(format!("{}.sock", "x".repeat(120)));
    let err = bind_hardened(&long).expect_err("must reject before binding");
    assert!(
        matches!(err, UdsSecurityError::PathTooLong { .. }),
        "expected PathTooLong, got {err:?}"
    );
}

// ── directory decisions, as pure functions (review finding 5) ───────────────

#[test]
fn classify_existing_dir_rejects_a_symlink() {
    // Why: THE review-finding-1 policy. `metadata()` on a symlinked directory
    // reports the TARGET's owner and mode, so a link pointing at any directory
    // this uid happens to own would otherwise pass the owner check — and
    // `set_permissions` would then chmod the target.
    let err = classify_existing_dir(Path::new("/tmp/x"), true, false, "symlink", 501, 0o700, 501)
        .expect_err("a symlink must be refused even when owner and mode look right");
    assert!(
        matches!(err, UdsSecurityError::SymlinkDir { .. }),
        "expected SymlinkDir, got {err:?}"
    );
}

#[test]
fn classify_existing_dir_rejects_a_regular_file() {
    // Why: review round 2, finding 1. A regular file owned by this uid at the
    // socket-dir path passed the symlink AND owner checks, was classified
    // `Narrow`, and got chmod'd to 0700 before `bind` failed ENOTDIR.
    let err = classify_existing_dir(
        Path::new("/tmp/x"),
        false,
        false,
        "regular file",
        501,
        0o644,
        501,
    )
    .expect_err("a non-directory must be refused");
    match err {
        UdsSecurityError::NotADirectory { ref found, .. } => {
            assert_eq!(found, "regular file", "diagnostic must name what was found");
        }
        other => panic!("expected NotADirectory, got {other:?}"),
    }
}

#[test]
fn classify_existing_dir_checks_file_type_before_owner() {
    // Why: a foreign-owned non-directory must report NotADirectory. Reporting
    // ForeignDirOwner would imply the path was a directory worth chmodding.
    let err = classify_existing_dir(Path::new("/tmp/x"), false, false, "fifo", 999, 0o777, 501)
        .expect_err("no");
    assert!(
        matches!(err, UdsSecurityError::NotADirectory { .. }),
        "file type must be checked before ownership, got {err:?}"
    );
}

#[test]
fn classify_existing_dir_rejects_a_foreign_owner() {
    let err = classify_existing_dir(Path::new("/tmp/x"), false, true, "directory", 0, 0o700, 501)
        .expect_err("a root-owned directory must be refused");
    match err {
        UdsSecurityError::ForeignDirOwner {
            owner, expected, ..
        } => {
            assert_eq!((owner, expected), (0, 501));
        }
        other => panic!("expected ForeignDirOwner, got {other:?}"),
    }
}

#[test]
fn classify_existing_dir_narrows_a_wide_dir() {
    let v = classify_existing_dir(
        Path::new("/tmp/x"),
        false,
        true,
        "directory",
        501,
        0o755,
        501,
    )
    .expect("ours");
    assert_eq!(v, DirVerdict::Narrow);
}

#[test]
fn classify_existing_dir_accepts_an_already_correct_dir() {
    let v = classify_existing_dir(
        Path::new("/tmp/x"),
        false,
        true,
        "directory",
        501,
        0o700,
        501,
    )
    .expect("ours");
    assert_eq!(v, DirVerdict::Accept);
}

#[test]
fn classify_existing_dir_checks_symlink_before_owner() {
    // Why: ordering matters. An attacker-owned symlink must report SymlinkDir,
    // not ForeignDirOwner — the latter would imply the path itself was checked.
    let err = classify_existing_dir(Path::new("/tmp/x"), true, false, "symlink", 999, 0o777, 501)
        .expect_err("no");
    assert!(
        matches!(err, UdsSecurityError::SymlinkDir { .. }),
        "symlink must be rejected before ownership is considered, got {err:?}"
    );
}

// ── directory behaviour on a real filesystem ────────────────────────────────

#[test]
fn prepare_socket_dir_creates_at_0700() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let dir = tmp.path().join("sockets");

    prepare_socket_dir(&dir).expect("prepare fresh socket dir");

    assert_eq!(
        mode_of(&dir),
        SOCKET_DIR_MODE,
        "fresh socket dir must be 0700"
    );
}

#[test]
fn prepare_socket_dir_creates_missing_ancestors() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let dir = tmp.path().join("a").join("b").join("sockets");

    prepare_socket_dir(&dir).expect("prepare nested socket dir");

    assert_eq!(mode_of(&dir), SOCKET_DIR_MODE);
}

#[test]
fn prepare_socket_dir_narrows_a_wide_existing_dir() {
    // Why: the directory this replaces was created by `create_dir_all`, so on
    // every existing install it is already 0755. Upgrading must repair it.
    let tmp = tempfile::tempdir().expect("tempdir");
    let dir = tmp.path().join("sockets");
    std::fs::create_dir(&dir).expect("create wide dir");
    std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).expect("widen");
    assert_eq!(mode_of(&dir), 0o755, "precondition: dir starts wide");

    prepare_socket_dir(&dir).expect("prepare pre-existing socket dir");

    assert_eq!(
        mode_of(&dir),
        SOCKET_DIR_MODE,
        "existing dir must be narrowed"
    );
}

#[test]
fn prepare_socket_dir_rejects_a_symlink() {
    // Why: the end-to-end version of review finding 1, on a real filesystem.
    // The link points at a directory THIS uid owns, which is exactly the case
    // the old `metadata()`-based check waved through. Asserts the target is
    // left untouched — the old code chmod'd it to 0700.
    let tmp = tempfile::tempdir().expect("tempdir");
    let target = tmp.path().join("attacker_controlled");
    std::fs::create_dir(&target).expect("create target");
    std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o777)).expect("widen");
    let link = tmp.path().join("sockets");
    std::os::unix::fs::symlink(&target, &link).expect("create symlink");

    let err = prepare_socket_dir(&link).expect_err("a symlinked socket dir must be refused");

    assert!(
        matches!(err, UdsSecurityError::SymlinkDir { .. }),
        "expected SymlinkDir, got {err:?}"
    );
    assert_eq!(
        mode_of(&target),
        0o777,
        "the symlink target must NOT have been chmod'd"
    );
}

#[test]
fn prepare_socket_dir_rejects_a_regular_file_without_chmodding_it() {
    // Why: the end-to-end half of review-round-2 finding 1. The pre-fix code
    // chmod'd this file to 0700 on its way to an ENOTDIR from `bind`; the mode
    // assertion is what proves the file was left alone.
    let tmp = tempfile::tempdir().expect("tempdir");
    let planted = tmp.path().join("sockets");
    std::fs::write(&planted, b"not a directory").expect("plant file");
    std::fs::set_permissions(&planted, std::fs::Permissions::from_mode(0o644)).expect("chmod");

    let err = prepare_socket_dir(&planted).expect_err("a non-directory must be refused");

    match err {
        UdsSecurityError::NotADirectory { ref found, .. } => {
            assert_eq!(found, "regular file");
        }
        other => panic!("expected NotADirectory, got {other:?}"),
    }
    assert_eq!(
        mode_of(&planted),
        0o644,
        "the planted file must NOT have been chmod'd"
    );
}

#[test]
fn prepare_socket_dir_is_idempotent() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let dir = tmp.path().join("sockets");

    prepare_socket_dir(&dir).expect("first prepare");
    prepare_socket_dir(&dir).expect("second prepare must succeed");

    assert_eq!(mode_of(&dir), SOCKET_DIR_MODE);
}

// ── bind ────────────────────────────────────────────────────────────────────

#[tokio::test]
async fn bind_hardened_sets_socket_0600_and_dir_0700() {
    // Why: THE regression test for #5099. Against the pre-fix commit the socket
    // comes back at the umask default (0755 under umask 022) and this assertion
    // fails.
    let tmp = tempfile::tempdir().expect("tempdir");
    let dir = tmp.path().join("sockets");
    let sock = dir.join("t.sock");

    let _listener = bind_hardened(&sock).expect("bind hardened listener");

    assert_eq!(mode_of(&sock), SOCKET_MODE, "socket must be 0600");
    assert_eq!(mode_of(&dir), SOCKET_DIR_MODE, "socket dir must be 0700");
}

#[tokio::test]
async fn bind_hardened_socket_is_connectable_after_hardening() {
    // Why: narrowing to 0600 must not break the same-uid client the socket
    // exists for — a fix that made the socket unusable would also pass a
    // mode-only assertion. Also proves the accept-side peer check admits a
    // legitimate peer.
    let tmp = tempfile::tempdir().expect("tempdir");
    let sock = tmp.path().join("sockets").join("t.sock");
    let listener = bind_hardened(&sock).expect("bind hardened listener");

    let client = UnixStream::connect(&sock).await.expect("same-uid connect");
    let (accepted, _) = listener.accept().await.expect("accept");

    ensure_peer_is_self(&accepted).expect("same-uid peer must be accepted");
    drop(client);
}

#[tokio::test]
async fn bind_hardened_rejects_a_path_with_no_parent() {
    // Failure path: a bare relative filename has no directory to harden, so the
    // bind must be refused rather than silently binding unprotected.
    let err = bind_hardened(Path::new("bare.sock")).expect_err("must refuse");
    assert!(
        matches!(err, UdsSecurityError::NoParent { .. }),
        "expected NoParent, got {err:?}"
    );
}

#[tokio::test]
async fn bind_hardened_propagates_an_address_in_use_failure() {
    // Failure path: `bind_hardened` deliberately does NOT unlink a stale socket
    // (that would break `CtrlSocket::bind_singleton`'s probe-first guarantee),
    // so a second bind must surface EADDRINUSE, not swallow it.
    let tmp = tempfile::tempdir().expect("tempdir");
    let sock = tmp.path().join("sockets").join("t.sock");
    let _first = bind_hardened(&sock).expect("first bind");

    let err = bind_hardened(&sock).expect_err("second bind must fail");
    assert!(
        matches!(err, UdsSecurityError::Bind { .. }),
        "expected Bind, got {err:?}"
    );
}

// ── connect (review finding 3) ──────────────────────────────────────────────

#[tokio::test]
async fn connect_hardened_accepts_a_properly_hardened_socket() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let sock = tmp.path().join("sockets").join("t.sock");
    let listener = bind_hardened(&sock).expect("bind");

    let client = connect_hardened(&sock).await.expect("dial our own socket");
    let (accepted, _) = listener.accept().await.expect("accept");
    ensure_peer_is_self(&accepted).expect("peer is us");
    drop(client);
}

#[tokio::test]
async fn connect_hardened_refuses_a_world_readable_socket() {
    // Why: a daemon that predates #5099 still answers at the canonical path.
    // The client must refuse it rather than trusting the transport.
    let tmp = tempfile::tempdir().expect("tempdir");
    let sock = tmp.path().join("sockets").join("t.sock");
    let _listener = bind_hardened(&sock).expect("bind");
    std::fs::set_permissions(&sock, std::fs::Permissions::from_mode(0o777)).expect("widen socket");

    let err = connect_hardened(&sock).await.expect_err("must refuse");
    match err {
        UdsSecurityError::UntrustedSocket { ref reason, .. } => {
            assert!(
                reason.contains("0777"),
                "reason must name the mode: {reason}"
            );
        }
        other => panic!("expected UntrustedSocket, got {other:?}"),
    }
}

#[tokio::test]
async fn connect_hardened_refuses_a_socket_in_a_wide_directory() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let dir = tmp.path().join("sockets");
    let sock = dir.join("t.sock");
    let _listener = bind_hardened(&sock).expect("bind");
    std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).expect("widen dir");

    let err = connect_hardened(&sock).await.expect_err("must refuse");
    match err {
        UdsSecurityError::UntrustedSocket { ref reason, .. } => {
            assert!(
                reason.contains("directory") && reason.contains("0755"),
                "reason must name the directory and its mode: {reason}"
            );
        }
        other => panic!("expected UntrustedSocket, got {other:?}"),
    }
}

#[tokio::test]
async fn connect_hardened_refuses_a_regular_file() {
    // Why: an attacker who cannot bind can still plant a regular file. Dialling
    // it would fail with a confusing ENOTSOCK deep in the client.
    let tmp = tempfile::tempdir().expect("tempdir");
    let dir = tmp.path().join("sockets");
    prepare_socket_dir(&dir).expect("prepare");
    let planted = dir.join("t.sock");
    std::fs::write(&planted, b"not a socket").expect("plant file");
    std::fs::set_permissions(&planted, std::fs::Permissions::from_mode(0o600)).expect("chmod");

    let err = connect_hardened(&planted).await.expect_err("must refuse");
    match err {
        UdsSecurityError::UntrustedSocket { ref reason, .. } => {
            assert!(reason.contains("not a socket"), "got: {reason}");
        }
        other => panic!("expected UntrustedSocket, got {other:?}"),
    }
}

#[test]
fn verify_socket_for_connect_reports_a_stat_failure_as_stat_not_create() {
    // Why: review round 2, finding 2. A dialer creates nothing, so a failed
    // stat used to surface as "create socket directory …" — naming an action
    // never attempted.
    let tmp = tempfile::tempdir().expect("tempdir");
    let missing = tmp.path().join("absent").join("t.sock");

    let err = verify_socket_for_connect(&missing).expect_err("must fail");

    assert!(
        matches!(err, UdsSecurityError::StatForConnect { .. }),
        "expected StatForConnect, got {err:?}"
    );
    assert!(
        !err.to_string().contains("create socket directory"),
        "a dialer must not claim it was creating anything: {err}"
    );
}

#[test]
fn verify_socket_for_connect_refuses_a_regular_file_as_the_directory() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let planted = tmp.path().join("sockets");
    std::fs::write(&planted, b"not a directory").expect("plant file");

    let err = verify_socket_for_connect(&planted.join("t.sock")).expect_err("must refuse");
    assert!(
        matches!(err, UdsSecurityError::NotADirectory { .. }),
        "expected NotADirectory, got {err:?}"
    );
}

#[test]
fn verify_socket_for_connect_refuses_a_symlinked_directory() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let target = tmp.path().join("elsewhere");
    std::fs::create_dir(&target).expect("create target");
    let link = tmp.path().join("sockets");
    std::os::unix::fs::symlink(&target, &link).expect("symlink");

    let err = verify_socket_for_connect(&link.join("t.sock")).expect_err("must refuse");
    assert!(
        matches!(err, UdsSecurityError::SymlinkDir { .. }),
        "expected SymlinkDir, got {err:?}"
    );
}

// ── peer decisions, as pure functions (review finding 5) ────────────────────

#[test]
fn peer_uid_verdict_accepts_the_same_uid() {
    peer_uid_verdict(501, 501).expect("a same-uid peer must be admitted");
}

#[test]
fn peer_uid_verdict_refuses_a_foreign_uid() {
    // Why: this is the refusal that previously had NO unprivileged coverage —
    // the `#[ignore]`d cross-uid test could not run in CI, so the policy was
    // asserted nowhere.
    let err = peer_uid_verdict(999, 501).expect_err("a foreign uid must be refused");
    match err {
        UdsSecurityError::ForeignPeer { peer, expected } => {
            assert_eq!((peer, expected), (999, 501));
        }
        other => panic!("expected ForeignPeer, got {other:?}"),
    }
}

#[test]
fn peer_uid_verdict_refuses_root_when_we_are_not_root() {
    // Why: root is deliberately not special-cased. Admitting it would widen the
    // accepted set for no gain, since root bypasses the filesystem check anyway.
    let err = peer_uid_verdict(0, 501).expect_err("root must be refused like any foreign uid");
    assert!(matches!(err, UdsSecurityError::ForeignPeer { peer: 0, .. }));
}

#[tokio::test]
async fn peer_uid_of_self_connection_is_self() {
    // Why: proves the platform syscall is wired up correctly on this target — a
    // stub returning 0 would pass `peer_uid_verdict` only for root.
    let tmp = tempfile::tempdir().expect("tempdir");
    let sock = tmp.path().join("sockets").join("t.sock");
    let listener = bind_hardened(&sock).expect("bind");

    let _client = UnixStream::connect(&sock).await.expect("connect");
    let (accepted, _) = listener.accept().await.expect("accept");

    assert_eq!(
        peer_uid(&accepted).expect("read peer uid"),
        self_uid(),
        "a connection from this process must report this process's uid"
    );
}

/// Why (#6642): the console identifies a UDS daemon's process by asking the
/// kernel who is on the other end of the connection it already makes. A stub
/// returning `None` would leave every UDS service's CPU graph permanently
/// empty, with nothing failing to say so.
/// What: connects to a socket this process is also listening on, so the peer pid
/// has one correct answer — this process's own.
#[tokio::test]
async fn peer_pid_of_self_connection_is_this_process() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let sock = tmp.path().join("sockets").join("pid.sock");
    let listener = bind_hardened(&sock).expect("bind");

    let _client = UnixStream::connect(&sock).await.expect("connect");
    let (accepted, _) = listener.accept().await.expect("accept");

    // Darwin and Linux both implement this; every other target answers None by
    // design, so the assertion is scoped to the two that must work.
    #[cfg(any(target_os = "linux", target_os = "macos", target_os = "ios"))]
    assert_eq!(
        super::peer::peer_pid(&accepted),
        Some(std::process::id()),
        "a connection from this process must report this process's pid"
    );
    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "ios")))]
    assert_eq!(super::peer::peer_pid(&accepted), None);
}

// ── singleton bind (#5182) ──────────────────────────────────────────────────

#[tokio::test]
async fn bind_singleton_binds_a_fresh_path() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let sock = tmp.path().join("sockets").join("fresh.sock");

    let listener = bind_singleton_hardened(&sock).await.expect("bind fresh");

    assert_eq!(mode_of(&sock), SOCKET_MODE, "a takeover must still harden");
    drop(listener);
}

#[tokio::test]
async fn bind_singleton_takes_over_a_stale_socket_file() {
    // Why: a console-supervised child that is SIGKILLed leaves its socket file
    // behind. Without the takeover the next spawn fails EADDRINUSE forever and
    // every delivery stays pending — the state #5182 exists to leave.
    let tmp = tempfile::tempdir().expect("tempdir");
    let sock = tmp.path().join("sockets").join("stale.sock");
    let dead = bind_hardened(&sock).expect("bind first");
    drop(dead); // tokio does not unlink on drop, so the file survives.
    assert!(sock.exists(), "the corpse must still be on disk");

    // The subject is the takeover, not how fast the kernel reclaims a socket.
    wait_until_corpse(&sock).await;

    let listener = bind_singleton_hardened(&sock)
        .await
        .expect("a socket nobody serves must be taken over");

    assert_eq!(mode_of(&sock), SOCKET_MODE);
    drop(listener);
}

#[tokio::test]
async fn bind_singleton_refuses_a_socket_someone_is_serving() {
    // Two listeners on one path means the kernel picks which one a delivery
    // reaches, so the second must fail rather than unlink a live owner.
    let tmp = tempfile::tempdir().expect("tempdir");
    let sock = tmp.path().join("sockets").join("live.sock");
    let _live = bind_hardened(&sock).expect("bind the live owner");

    let err = bind_singleton_hardened(&sock)
        .await
        .expect_err("a served socket must not be taken over");

    assert!(
        matches!(err, UdsSecurityError::AlreadyServing { .. }),
        "expected AlreadyServing, got {err:?}"
    );
    assert!(sock.exists(), "the live owner's socket must survive");
}

// ── the takeover decision (#7312) ───────────────────────────────────────────
//
// Every arm below is asserted against `classify_takeover` directly, because two
// of the four cannot be reached through real syscalls on this machine: Linux
// reports a non-socket as ECONNREFUSED and macOS as ENOTSOCK, and neither
// platform lets an unprivileged test manufacture an `Inconclusive` probe of a
// real socket.

#[test]
fn takeover_verdict_refuses_a_non_socket_even_when_the_probe_says_dead() {
    // This pair — not a socket, probe says NotServing — is exactly what Linux
    // hands the decision for a regular file on the socket path. Before #7312 it
    // unlinked the file and bound over it.
    assert_eq!(
        classify_takeover(false, Some(SocketVerdict::NotServing)),
        TakeoverVerdict::NotASocket
    );
}

#[test]
fn takeover_verdict_refuses_a_non_socket_on_every_probe_answer() {
    for verdict in [
        SocketVerdict::Serving,
        SocketVerdict::NotServing,
        SocketVerdict::Inconclusive,
    ] {
        assert_eq!(
            classify_takeover(false, Some(verdict)),
            TakeoverVerdict::NotASocket,
            "the file type outranks the probe, got {verdict:?}"
        );
    }
}

#[test]
fn takeover_verdict_refuses_a_non_socket_that_was_never_probed() {
    // What `bind_singleton_hardened` actually passes for a non-socket: no
    // verdict, because it does not spend a connect on one.
    assert_eq!(
        classify_takeover(false, None),
        TakeoverVerdict::NotASocket,
        "an unprobed non-socket is still refused"
    );
}

#[test]
fn takeover_verdict_refuses_an_unprobed_socket() {
    // A missing verdict is never grounds to unlink. Only the one the kernel
    // proved is.
    assert_eq!(classify_takeover(true, None), TakeoverVerdict::Occupied);
}

#[test]
fn takeover_verdict_takes_over_a_dead_socket() {
    // The one arm that unlinks anything, unchanged by #7312.
    assert_eq!(
        classify_takeover(true, Some(SocketVerdict::NotServing)),
        TakeoverVerdict::TakeOver
    );
}

#[test]
fn takeover_verdict_refuses_a_served_socket() {
    assert_eq!(
        classify_takeover(true, Some(SocketVerdict::Serving)),
        TakeoverVerdict::Occupied
    );
}

#[test]
fn takeover_verdict_refuses_an_inconclusive_probe() {
    // The fail-open check: `Inconclusive` must never reach the unlink. A probe
    // that could not settle the question is treated as a live owner.
    assert_eq!(
        classify_takeover(true, Some(SocketVerdict::Inconclusive)),
        TakeoverVerdict::Occupied
    );
}

#[tokio::test]
async fn bind_singleton_refuses_a_regular_file_and_leaves_it_on_disk() {
    // #7312: the takeover exists for a socket corpse. A regular file on the
    // socket path is not one, and deleting it is data loss in whatever owns it.
    //
    // This is the platform split, in one test. macOS answers a connect to a
    // regular file with ENOTSOCK, which reads `Inconclusive` and refused — by
    // accident, and under the wrong error. Linux answers ECONNREFUSED, which
    // read `NotServing`: the file was unlinked, the bind succeeded, and
    // `trusty-code`'s `run_uds_socket_bind_failure_is_fatal` then served
    // forever instead of failing, hanging a CI shard until its 45-minute
    // cancel. Both platforms must now refuse for the stated reason.
    let tmp = tempfile::tempdir().expect("tempdir");
    let dir = tmp.path().join("sockets");
    std::fs::create_dir_all(&dir).expect("socket dir");
    let sock = dir.join("occupied.sock");
    std::fs::write(&sock, b"not a socket").expect("occupy the socket path");

    let err = bind_singleton_hardened(&sock)
        .await
        .expect_err("a regular file on the socket path must stop the bind");

    let rendered = err.to_string();
    assert!(
        rendered.contains("is a regular file, not a socket"),
        "the refusal must name what is actually there, got: {rendered}"
    );
    assert!(sock.exists(), "the file must not have been unlinked");
    assert_eq!(
        std::fs::read(&sock).expect("read the file back"),
        b"not a socket",
        "the file's contents must be untouched"
    );
}

/// Wait for a dropped listener's socket to actually read dead.
///
/// Why: dropping the listener closes the fd, and the kernel finishes tearing
/// the socket down afterwards; on macOS under a loaded test binary a connect
/// lands in that window and succeeds. Two tests establish the same
/// precondition, so the loop is written once.
async fn wait_until_corpse(sock: &Path) {
    let deadline = std::time::Instant::now() + Duration::from_secs(5);
    while probe_socket_verdict(sock, Duration::from_millis(50)).await != SocketVerdict::NotServing {
        assert!(
            std::time::Instant::now() < deadline,
            "the dropped listener never stopped answering connects"
        );
        tokio::time::sleep(Duration::from_millis(10)).await;
    }
}

/// Why: #8759 — two daemons starting on one data root both proved the same
/// socket dead, both unlinked and bound, and both went on serving: the loser's
/// listener sat on an unlinked inode while believing it owned the path.
/// What: the first binder has decided to take over the corpse; the second runs
/// its whole bind inside that gap via the `before_takeover` hook, so the
/// interleaving is forced rather than slept into. Exactly one may come back
/// `Ok`, and the path on disk must reach that one.
/// Test: itself.
#[tokio::test]
async fn bind_singleton_racing_takeover_leaves_exactly_one_owner() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let sock = tmp.path().join("sockets").join("race.sock");
    drop(bind_hardened(&sock).expect("bind the soon-to-be corpse"));
    wait_until_corpse(&sock).await;

    let mut second = None;
    let slot = &mut second;
    let path = &sock;
    let first = super::singleton::bind_singleton_with(&sock, move || async move {
        *slot = Some(bind_singleton_hardened(path).await);
    })
    .await;
    let second = second.expect("the hook runs on the takeover arm");

    let owners = usize::from(first.is_ok()) + usize::from(second.is_ok());
    assert_eq!(
        owners, 1,
        "exactly one binder may own the socket; first: {first:?}, second: {second:?}"
    );
    // A completed UDS connect is already queued on the listener it reached, so
    // a non-blocking accept answers "was it this one?" with no wait.
    let owner = first
        .or(second)
        .expect("one owner, asserted above")
        .into_std()
        .expect("into_std");
    let _client = std::os::unix::net::UnixStream::connect(&sock)
        .expect("the socket path must reach a listener");
    owner
        .accept()
        .expect("the connection must be queued on the owner, not an orphan");
}

/// Inode of the file at `path`, read without following a symlink.
fn inode_of(path: &Path) -> u64 {
    std::os::unix::fs::MetadataExt::ino(&std::fs::symlink_metadata(path).expect("lstat"))
}

/// Why: #8759 — a binder that finds the bind lock held must refuse rather than
/// step around another binder's takeover.
/// What: a second descriptor holds `<sock>.lock` over a corpse; the bind
/// refuses with `BindInProgress` and leaves the corpse's inode in place. Once
/// the holder lets go, the same bind takes the corpse over.
/// Test: itself.
#[tokio::test]
async fn bind_singleton_refuses_while_another_binder_holds_the_lock() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let sock = tmp.path().join("sockets").join("held.sock");
    drop(bind_hardened(&sock).expect("bind the soon-to-be corpse"));
    wait_until_corpse(&sock).await;
    let corpse = inode_of(&sock);
    let holder = std::fs::OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(super::singleton::bind_lock_path(&sock))
        .expect("open the bind lock file");
    holder.try_lock().expect("take the bind lock");

    let err = bind_singleton_hardened(&sock)
        .await
        .expect_err("a held bind lock must refuse");
    assert!(
        matches!(err, UdsSecurityError::BindInProgress { ref path } if *path == sock),
        "expected BindInProgress for {}, got {err:?}",
        sock.display()
    );
    assert_eq!(
        inode_of(&sock),
        corpse,
        "a refused bind must not touch the path"
    );

    drop(holder);
    bind_singleton_hardened(&sock)
        .await
        .expect("a released lock lets the corpse be taken over");
}

/// Why: #8759 Fail-Open Check — a bind lock that cannot be taken must stop the
/// bind, never downgrade to an unlocked takeover.
/// What: a directory sits where `<sock>.lock` belongs, so opening it fails; the
/// bind returns `BindLock` and the corpse it would otherwise have reclaimed
/// keeps its inode.
/// Test: itself.
#[tokio::test]
async fn bind_singleton_fails_closed_when_the_bind_lock_cannot_be_opened() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let sock = tmp.path().join("sockets").join("blocked.sock");
    std::fs::create_dir_all(sock.parent().expect("parent")).expect("socket dir");
    std::fs::create_dir(super::singleton::bind_lock_path(&sock)).expect("dir at the lock path");
    let dead = std::os::unix::net::UnixListener::bind(&sock).expect("bind the corpse");
    drop(dead);
    wait_until_corpse(&sock).await;
    let corpse = inode_of(&sock);

    let err = bind_singleton_hardened(&sock)
        .await
        .expect_err("an unusable bind lock must refuse");
    assert_bind_lock_refusal(&err, &sock, "is a directory, not a regular file");
    assert_eq!(
        inode_of(&sock),
        corpse,
        "no takeover may run without the lock"
    );
}

/// Asserts `err` is a `BindLock` refusal on `<sock>.lock` whose message names
/// that path and carries `reason`.
fn assert_bind_lock_refusal(err: &UdsSecurityError, sock: &Path, reason: &str) {
    let lock = super::singleton::bind_lock_path(sock);
    assert!(
        matches!(err, UdsSecurityError::BindLock { path, .. } if *path == lock),
        "expected BindLock on {}, got {err:?}",
        lock.display()
    );
    let message = err.to_string();
    assert!(
        message.contains(&lock.display().to_string()) && message.contains(reason),
        "message must name {} and say {reason:?}; got {message:?}",
        lock.display()
    );
}

/// Plants `plant` at `<sock>.lock` in a fresh socket dir, binds, and asserts the
/// bind refused with `reason` and created no socket.
async fn refuse_with_lock_path_occupant(
    tmp: &tempfile::TempDir,
    plant: impl FnOnce(&Path),
    reason: &str,
) {
    let sock = tmp.path().join("sockets").join("planted.sock");
    std::fs::create_dir_all(sock.parent().expect("parent")).expect("socket dir");
    plant(&super::singleton::bind_lock_path(&sock));

    let err = bind_singleton_hardened(&sock)
        .await
        .expect_err("a lock path that is not a plain file must refuse");

    assert_bind_lock_refusal(&err, &sock, reason);
    assert!(
        std::fs::symlink_metadata(&sock).is_err(),
        "a refused bind must not create the socket"
    );
}

/// Why: #8759 review — a symlink planted at `<sock>.lock` must never be
/// followed, or the lock (and its `0600` create) lands on the link's target.
/// What: the link points at a file outside the socket dir; the bind refuses
/// with `BindLock`, the target keeps its bytes and is not left locked.
/// Test: itself.
#[tokio::test]
async fn bind_singleton_refuses_a_symlink_to_a_file_at_the_lock_path() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let victim = tmp.path().join("victim.txt");
    std::fs::write(&victim, b"victim").expect("write victim");

    refuse_with_lock_path_occupant(
        &tmp,
        |lock| std::os::unix::fs::symlink(&victim, lock).expect("plant symlink"),
        "is a symlink; refusing to follow it",
    )
    .await;

    assert_eq!(std::fs::read(&victim).expect("read victim"), b"victim");
    let probe = std::fs::File::open(&victim).expect("open victim");
    probe
        .try_lock()
        .expect("the link's target must not be left locked");
}

/// Why: #8759 review — `O_CREAT` through a dangling link creates the link's
/// target, so a followed link lets anyone who can plant one create a file.
/// What: the bind refuses with `BindLock` and the target never appears.
/// Test: itself.
#[tokio::test]
async fn bind_singleton_refuses_a_dangling_symlink_at_the_lock_path() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let target = tmp.path().join("created-through-the-link");

    refuse_with_lock_path_occupant(
        &tmp,
        |lock| std::os::unix::fs::symlink(&target, lock).expect("plant symlink"),
        "is a symlink; refusing to follow it",
    )
    .await;

    assert!(
        std::fs::symlink_metadata(&target).is_err(),
        "the bind lock must not create a dangling link's target"
    );
}

/// Why: #8759 review — a link to a directory is refused as a link, on its own
/// type, not by whatever the directory makes `open` return.
/// What: the bind refuses with `BindLock` naming the symlink.
/// Test: itself.
#[tokio::test]
async fn bind_singleton_refuses_a_symlink_to_a_directory_at_the_lock_path() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let dir = tmp.path().join("elsewhere");
    std::fs::create_dir(&dir).expect("target dir");

    refuse_with_lock_path_occupant(
        &tmp,
        |lock| std::os::unix::fs::symlink(&dir, lock).expect("plant symlink"),
        "is a symlink; refusing to follow it",
    )
    .await;
}

/// Why: #8759 review — `open` succeeds on a FIFO, so only a file-type check on
/// the opened descriptor refuses a lock path that is not a regular file.
/// What: a FIFO at `<sock>.lock`; the bind refuses with `BindLock`.
/// Test: itself.
#[tokio::test]
async fn bind_singleton_refuses_a_fifo_at_the_lock_path() {
    let tmp = tempfile::tempdir().expect("tempdir");
    refuse_with_lock_path_occupant(
        &tmp,
        |lock| {
            use std::os::unix::ffi::OsStrExt as _;
            let c_path = std::ffi::CString::new(lock.as_os_str().as_bytes()).expect("c path");
            // SAFETY: `c_path` is a valid NUL-terminated path for the call.
            let rc = unsafe { libc::mkfifo(c_path.as_ptr(), 0o600) };
            assert_eq!(rc, 0, "mkfifo: {}", std::io::Error::last_os_error());
        },
        "is a fifo, not a regular file",
    )
    .await;
}

/// Why: #8759 review — a guard held past a successful return would turn every
/// later start on the same path into `BindInProgress` for this process's life.
/// What: bind, drop the listener, bind the same path again; the second bind
/// takes the corpse over instead of reporting the lock held.
/// Test: itself.
#[tokio::test]
async fn bind_singleton_releases_the_bind_lock_when_it_returns() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let sock = tmp.path().join("sockets").join("released.sock");

    let first = bind_singleton_hardened(&sock).await.expect("first bind");
    drop(first);
    wait_until_corpse(&sock).await;

    let second = bind_singleton_hardened(&sock)
        .await
        .expect("a returned bind must not still hold the bind lock");
    drop(second);
}

#[tokio::test]
async fn bind_singleton_hardened_refuses_a_symlink_to_a_dead_socket() {
    // #7312: a symlink is refused on its own type, and the dead socket it
    // points at is NOT the corpse this function may reclaim — reclaiming
    // through a link would unlink the link and bind a fresh socket at a path
    // whose name still promises indirection. `verify_socket_for_connect`
    // refuses a symlinked socket on the dialing side for the same reason.
    //
    // Note the target here is genuinely dead, so the probe would answer
    // `NotServing` on BOTH platforms. Only the file-type check stops the
    // takeover, which makes this the arm with no platform escape hatch.
    let tmp = tempfile::tempdir().expect("tempdir");
    let dir = tmp.path().join("sockets");
    let target = dir.join("dead.sock");
    let dead = bind_hardened(&target).expect("bind the soon-to-be corpse");
    drop(dead); // tokio does not unlink on drop, so the file survives.
    wait_until_corpse(&target).await;

    let link = dir.join("link.sock");
    std::os::unix::fs::symlink(&target, &link).expect("symlink onto the corpse");

    let err = bind_singleton_hardened(&link)
        .await
        .expect_err("a symlinked socket path must stop the bind");

    assert!(
        matches!(err, UdsSecurityError::NotASocketFile { ref found, .. } if found == "symlink"),
        "expected NotASocketFile naming a symlink, got {err:?}"
    );
    assert!(
        std::fs::symlink_metadata(&link).is_ok(),
        "the symlink itself must survive"
    );
    assert!(
        std::fs::symlink_metadata(&target).is_ok(),
        "the symlink's target must survive"
    );
}

#[tokio::test]
async fn bind_singleton_hardened_refuses_a_symlink_to_a_live_socket() {
    // The same refusal with an owner behind it: unlinking here would strand a
    // live listener, which is what `AlreadyServing` exists to prevent — but the
    // symlink is refused before the probe ever runs, so the refusal does not
    // depend on catching the owner in the act.
    let tmp = tempfile::tempdir().expect("tempdir");
    let dir = tmp.path().join("sockets");
    let target = dir.join("live.sock");
    let _live = bind_hardened(&target).expect("bind the live owner");

    let link = dir.join("link.sock");
    std::os::unix::fs::symlink(&target, &link).expect("symlink onto the live socket");

    let err = bind_singleton_hardened(&link)
        .await
        .expect_err("a symlinked socket path must stop the bind");

    assert!(
        matches!(err, UdsSecurityError::NotASocketFile { ref found, .. } if found == "symlink"),
        "expected NotASocketFile naming a symlink, got {err:?}"
    );
    assert!(
        std::fs::symlink_metadata(&link).is_ok(),
        "the symlink itself must survive"
    );
    assert!(
        socket_is_serving(&target, Duration::from_millis(500)).await,
        "the live owner must still be answering on its own path"
    );
}

#[tokio::test]
async fn bind_singleton_refuses_a_directory_on_the_socket_path() {
    // The other shape the same rule covers: a directory is not a corpse either,
    // and `remove_file` on one would have failed silently, leaving the bind to
    // report an unrelated EADDRINUSE.
    let tmp = tempfile::tempdir().expect("tempdir");
    let dir = tmp.path().join("sockets");
    let sock = dir.join("occupied.sock");
    std::fs::create_dir_all(&sock).expect("occupy the socket path with a directory");

    let err = bind_singleton_hardened(&sock)
        .await
        .expect_err("a directory on the socket path must stop the bind");

    assert!(
        matches!(err, UdsSecurityError::NotASocketFile { ref found, .. } if found == "directory"),
        "expected NotASocketFile naming a directory, got {err:?}"
    );
    assert!(sock.is_dir(), "the directory must survive");
}

// ---------------------------------------------------------------------------
// #6896 — socket buffer sizing.
// ---------------------------------------------------------------------------

/// One write into a socket under measurement, in bytes. 8 KiB is the macOS
/// default buffer, so an unsized socket absorbs one or two of these.
const FILL_CHUNK: usize = 8 * 1024;

/// Bytes a writer can hand the kernel before the socket stops accepting them,
/// with nothing draining the other end.
///
/// This is the figure the round-trip count derives from: a frame of `F` bytes
/// costs `ceil(F / in_flight)` write-then-drain round trips, and each one parks
/// and unparks the writing task.
fn bytes_in_flight(stream: &tokio::net::UnixStream) -> usize {
    let chunk = vec![0u8; FILL_CHUNK];
    let mut written = 0usize;
    loop {
        match stream.try_write(&chunk) {
            Ok(0) => return written,
            Ok(n) => written += n,
            // Every other error is also "no more fits" for this measurement;
            // returning what was accepted keeps the test from spinning.
            Err(_) => return written,
        }
    }
}

/// Round trips an 8 MiB frame costs at a given in-flight window.
fn round_trips(in_flight: usize) -> usize {
    let frame = MAX_FRAME_BYTES as usize;
    if in_flight == 0 {
        return frame;
    }
    frame.div_ceil(in_flight)
}

/// The granted sizes, or a panic naming what came back instead.
fn expect_sized(outcome: SocketBufferOutcome) -> SocketBufferSizes {
    match outcome {
        SocketBufferOutcome::Sized(sizes) => sizes,
        other => panic!("expected a sized socket, got {other:?}"),
    }
}

#[tokio::test]
async fn tune_connected_buffers_raises_both_buffers_on_a_socketpair() {
    let (a, _b) = tokio::net::UnixStream::pair().expect("socketpair");

    let sized = expect_sized(tune_connected_buffers(&a).expect("size the buffers"));

    // The kernel clamps, so the granted size is asserted as a floor against the
    // platform default rather than an equality against the request.
    assert!(
        sized.send >= FILL_CHUNK * 2 && sized.recv >= FILL_CHUNK * 2,
        "expected both buffers well above the 8 KiB macOS default, got {sized:?}"
    );
}

/// A socket whose peer has gone is reported, not failed.
///
/// Why: macOS answers EINVAL to `setsockopt(SO_SNDBUF)` once the peer has hung
/// up, and an accepted socket is routinely in that state — a liveness probe
/// connects and closes. Treating it as a failure turned every probe into a
/// connection error, which is the regression this test pins.
#[tokio::test]
async fn tune_connected_buffers_reports_a_peer_that_already_hung_up() {
    let (a, b) = tokio::net::UnixStream::pair().expect("socketpair");
    drop(b);

    let outcome = tune_connected_buffers(&a).expect("a dead peer is not a sizing failure");

    // Linux sets the buffer regardless of connection state, so both outcomes
    // are correct there; what must never happen is an error.
    assert!(
        matches!(
            outcome,
            SocketBufferOutcome::PeerHungUp | SocketBufferOutcome::Sized(_)
        ),
        "unexpected outcome {outcome:?}"
    );
    #[cfg(target_os = "macos")]
    assert_eq!(outcome, SocketBufferOutcome::PeerHungUp);
}

/// The fail-open the #6896 review found: `getpeername` cannot answer for a
/// LISTENING socket, so the errno was the only surviving signal there.
///
/// Why this is the regression rather than an end-to-end test: the hazard is a
/// classification, and forcing a real `EINVAL` out of `setsockopt` on a healthy
/// listener is not something a test can arrange. Feeding the classifier a real
/// listener fd and a synthesized `EINVAL` reaches the same decision the bind
/// path would, on every platform — `getpeername` fails on a listener
/// unconditionally, so the `connected = true` arm below is the fail-open, and
/// the `connected = false` arm is the fix.
#[tokio::test]
async fn a_listener_can_never_classify_a_failure_as_a_hung_up_peer() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let sock = tmp.path().join("sockets").join("classify.sock");
    let listener = bind_hardened(&sock).expect("bind hardened");
    let fd = std::os::fd::AsRawFd::as_raw_fd(&listener);

    let einval = UdsSecurityError::SocketBuffer {
        option: "SO_SNDBUF",
        requested: SOCKET_BUFFER_BYTES,
        source: std::io::Error::from_raw_os_error(libc::EINVAL),
    };

    assert!(
        sockbuf::hangup_is_benign(true, &einval, fd),
        "a listener has no peer, so the connected form would wave this through — \
         which is exactly why the bind path must not use it"
    );
    assert!(
        !sockbuf::hangup_is_benign(false, &einval, fd),
        "the listener form must report the failure, whatever the errno says"
    );
}

/// The strict form refuses precisely where the forgiving one tolerates.
///
/// A hung-up peer is the one condition the two treat differently, so a socket
/// in that state is what separates them. On Linux `setsockopt` ignores the
/// connection state and both simply succeed, which is why the divergence is
/// asserted only on macOS; the type-level guarantee — `tune_listener_buffers`
/// has no benign variant to return — holds on both.
#[tokio::test]
async fn tune_listener_buffers_refuses_where_the_connected_form_tolerates() {
    let (strict_side, peer) = tokio::net::UnixStream::pair().expect("socketpair");
    drop(peer);
    let (lenient_side, peer) = tokio::net::UnixStream::pair().expect("socketpair");
    drop(peer);

    let strict = tune_listener_buffers(&strict_side);
    let lenient = tune_connected_buffers(&lenient_side).expect("the forgiving form tolerates it");

    #[cfg(target_os = "macos")]
    {
        assert_eq!(lenient, SocketBufferOutcome::PeerHungUp);
        let err = strict.expect_err("the listener form must not absorb a sizing failure");
        assert!(
            matches!(err, UdsSecurityError::SocketBuffer { .. }),
            "expected SocketBuffer, got {err:?}"
        );
    }
    #[cfg(not(target_os = "macos"))]
    {
        assert!(strict.is_ok(), "linux sizes a hung-up socket: {strict:?}");
        assert!(matches!(lenient, SocketBufferOutcome::Sized(_)));
    }
}

/// A read-back failure names the read, not a set that never happened.
#[test]
fn a_read_back_failure_names_its_own_operation() {
    // A closed fd is the one way to make `getsockopt` fail on demand.
    let bad = std::os::unix::net::UnixStream::pair()
        .expect("socketpair")
        .0;
    let fd = std::os::fd::AsRawFd::as_raw_fd(&bad);
    drop(bad);

    let err = socket_buffer_sizes(&BorrowedFdForTest(fd))
        .expect_err("a closed fd cannot answer getsockopt");

    assert!(
        matches!(err, UdsSecurityError::SocketBufferRead { .. }),
        "expected SocketBufferRead, got {err:?}"
    );
    let text = err.to_string();
    assert!(
        text.starts_with("read SO_SNDBUF back"),
        "a read failure must not be reported as a set: {text}"
    );
}

/// A bare fd, so a read-back can be aimed at one that is already closed.
struct BorrowedFdForTest(i32);

impl std::os::fd::AsRawFd for BorrowedFdForTest {
    fn as_raw_fd(&self) -> i32 {
        self.0
    }
}

/// On Linux, the server side is sized on the accepted socket, not inherited
/// from the listener: `accept` hands back a default-sized socket however the
/// listener was sized (#6896).
#[tokio::test]
async fn accept_sized_raises_the_accepted_socket_to_the_listeners_sizing() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let sock = tmp.path().join("sockets").join("inherit.sock");
    let listener = bind_hardened(&sock).expect("bind hardened");
    let _client = connect_hardened(&sock).await.expect("connect hardened");
    let (server, _) = accept_sized(&listener).await.expect("accept sized");

    let on_listener = socket_buffer_sizes(&listener).expect("read the listener");
    let accepted = socket_buffer_sizes(&server).expect("read the accepted socket");

    // Two granted figures compared against each other, never against
    // `SOCKET_BUFFER_BYTES`: both sockets asked the same host for the same
    // bytes, so the same `wmem_max` clamp and the same Linux doubling landed on
    // both, whatever those two produce here. Comparing either against the
    // request is what fails on Linux — it answers 2 MiB to a 1 MiB request, and
    // 425984 where `wmem_max` is 212992.
    assert_eq!(
        accepted, on_listener,
        "an accepted socket must carry the same granted sizing as its listener"
    );
    // The regression this guards: drop the sizing from `accept_sized` and the
    // accepted socket falls back to `net.core.wmem_default` on Linux, which is
    // half the listener's granted figure or less.
    assert!(
        accepted.send >= FILL_CHUNK * 2 && accepted.recv >= FILL_CHUNK * 2,
        "the accepted socket must carry the raised sizing, not the platform default: {accepted:?}"
    );
}

#[test]
fn socket_buffer_request_stays_within_the_frame_budget() {
    // macOS refuses a reservation past `kern.ipc.maxsockbuf` scaled by the mbuf
    // overhead, and `sockbuf` propagates that refusal rather than defaulting.
    // Staying an eighth of the frame budget is what keeps the request reachable.
    assert_eq!(SOCKET_BUFFER_BYTES, 1024 * 1024);
    assert!((SOCKET_BUFFER_BYTES as u64) < MAX_FRAME_BYTES);
}

/// The #6896 measurement: a hardened pair holds far more in flight than a pair
/// left at the platform default, so a frame-budget exchange costs far fewer
/// round trips.
///
/// Why a ratio rather than a wall-clock figure: the cost the issue names is the
/// COUNT of write-then-drain round trips, each a task park and unpark, and that
/// count is a deterministic function of the socket buffer sizes. Timing it
/// instead would measure the scheduler under whatever else the host is doing.
///
/// The 8x floor is asserted only on macOS. Linux ships `net.core.wmem_default`
/// at 212992 — 26x the macOS figure — so there the contract the issue states is
/// "unchanged or improved", which is the unconditional assertion below.
#[tokio::test]
async fn hardened_sockets_hold_far_more_in_flight_than_the_platform_default() {
    let tmp = tempfile::tempdir().expect("tempdir");

    // Baseline: a bare bind and connect — what this module did before #6896.
    let plain_path = tmp.path().join("plain.sock");
    let plain_listener = tokio::net::UnixListener::bind(&plain_path).expect("bind plain");
    let plain_client = tokio::net::UnixStream::connect(&plain_path)
        .await
        .expect("connect plain");
    let (_plain_server, _) = plain_listener.accept().await.expect("accept plain");
    let plain = bytes_in_flight(&plain_client);

    // The production paths: `bind_hardened` sizes the listener (and so every
    // socket `accept` returns), `connect_hardened` sizes the dialling end.
    let sized_path = tmp.path().join("sockets").join("sized.sock");
    let sized_listener = bind_hardened(&sized_path).expect("bind hardened");
    let sized_client = connect_hardened(&sized_path)
        .await
        .expect("connect hardened");
    let (_sized_server, _) = sized_listener.accept().await.expect("accept hardened");
    let sized = bytes_in_flight(&sized_client);

    eprintln!(
        "#6896 in-flight bytes: default={plain} ({} round trips for an 8 MiB frame), \
         sized={sized} ({} round trips)",
        round_trips(plain),
        round_trips(sized)
    );

    assert!(
        sized >= plain,
        "sizing must never reduce what a socket holds in flight: \
         default={plain}, sized={sized}"
    );

    #[cfg(target_os = "macos")]
    assert!(
        sized >= plain * 8 && round_trips(sized) * 8 <= round_trips(plain),
        "expected at least an 8x drop in round trips on macOS: \
         default={plain} ({} round trips), sized={sized} ({} round trips)",
        round_trips(plain),
        round_trips(sized)
    );
}