trusty-common 0.49.0

Shared utilities and provider-agnostic streaming chat (ChatProvider, OllamaProvider, OpenRouter, tool-use) for trusty-* projects
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
//! 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::*;

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");

    // Dropping the listener closes the fd; the kernel finishes tearing the
    // socket down afterwards, and on macOS under a loaded test binary a connect
    // lands in that window and succeeds. Waiting for the corpse to actually
    // read dead establishes the precondition this test assumes — the subject is
    // the takeover, not how fast the kernel reclaims a socket.
    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;
    }

    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");
}