cosca 0.9.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
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
//! Pure validation and error mapping for a persisted identity record. Compiled and run on
//! EVERY host, so the Linux-only boot-session branches are exercised on Windows and macOS
//! CI too.

use super::{
    reject, scope_error, validate, Platform, ProcessIdRecord, Scope, ScopeReadError, TokenKind, RECORD_VERSION,
};
use crate::error::{Error, RecordErrorKind};

/// A well-formed Linux record: boot session `36c3…`, pid namespace 4026531836, a pidfs inode.
fn linux_record() -> ProcessIdRecord {
    ProcessIdRecord {
        version: RECORD_VERSION,
        platform: Platform::Linux,
        pid: 4242,
        token: 162_431_157,
        boot_id: Some("36c39237-f06e-4e88-a74d-ea99d42b817c".into()),
        pid_ns: Some(4_026_531_836),
        token_kind: Some(TokenKind::Pidfs),
    }
}

fn linux_scope() -> Scope {
    Scope {
        boot_id: Some("36c39237-f06e-4e88-a74d-ea99d42b817c".into()),
        pid_ns: Some(4_026_531_836),
        token_kind: Some(TokenKind::Pidfs),
    }
}

/// A well-formed Windows record. The token is a real measured creation FILETIME,
/// deliberately larger than 2^53.
fn windows_record() -> ProcessIdRecord {
    ProcessIdRecord {
        version: RECORD_VERSION,
        platform: Platform::Windows,
        pid: 4242,
        token: 134_301_578_477_907_396,
        boot_id: None,
        pid_ns: None,
        token_kind: None,
    }
}

#[skuld::test]
fn a_matching_linux_record_validates() {
    assert_eq!(
        validate(&linux_record(), &Platform::Linux, &linux_scope()),
        Ok((4242, 162_431_157))
    );
}

#[skuld::test]
fn a_windows_record_validates_with_an_empty_scope() {
    assert_eq!(
        validate(&windows_record(), &Platform::Windows, &Scope::none()),
        Ok((4242, 134_301_578_477_907_396))
    );
}

#[skuld::test]
fn a_linux_record_is_rejected_on_windows() {
    // The measured hazard: Linux jiffies are boot-relative and would be compared against
    // an absolute FILETIME. Must never be accepted.
    assert_eq!(
        validate(&linux_record(), &Platform::Windows, &Scope::none()),
        Err(RecordErrorKind::ForeignPlatform)
    );
}

#[skuld::test]
fn a_windows_record_is_rejected_on_linux() {
    assert_eq!(
        validate(&windows_record(), &Platform::Linux, &linux_scope()),
        Err(RecordErrorKind::ForeignPlatform)
    );
}

#[skuld::test]
fn an_unknown_platform_tag_is_rejected_not_a_parse_failure() {
    let mut r = linux_record();
    r.platform = Platform::Other("freebsd".into());
    assert_eq!(
        validate(&r, &Platform::Linux, &linux_scope()),
        Err(RecordErrorKind::ForeignPlatform)
    );
}

#[skuld::test]
fn an_unknown_version_is_rejected_before_anything_else() {
    let mut r = linux_record();
    r.version = RECORD_VERSION + 1;
    // Also make it foreign-platform, to pin that VERSION is checked FIRST: a future
    // format may reuse these fields with different meanings.
    r.platform = Platform::Other("freebsd".into());
    assert_eq!(
        validate(&r, &Platform::Linux, &linux_scope()),
        Err(RecordErrorKind::UnknownVersion)
    );
}

#[skuld::test]
fn a_version_zero_record_is_rejected() {
    let mut r = linux_record();
    r.version = 0;
    assert_eq!(
        validate(&r, &Platform::Linux, &linux_scope()),
        Err(RecordErrorKind::UnknownVersion)
    );
}

#[skuld::test]
fn a_linux_record_from_a_different_boot_is_rejected() {
    // After a reboot the jiffy counter restarts, so a saved token would alias onto whatever
    // now occupies the pid.
    let scope = Scope {
        boot_id: Some("00000000-0000-0000-0000-000000000000".into()),
        ..linux_scope()
    };
    assert_eq!(
        validate(&linux_record(), &Platform::Linux, &scope),
        Err(RecordErrorKind::ForeignBootSession)
    );
}

#[skuld::test]
fn a_linux_record_from_a_different_pid_namespace_is_rejected() {
    // Measured: a container shares the host's boot_id but has its own pid namespace,
    // so boot_id alone does not scope the pid.
    let scope = Scope {
        pid_ns: Some(4_026_532_417),
        ..linux_scope()
    };
    assert_eq!(
        validate(&linux_record(), &Platform::Linux, &scope),
        Err(RecordErrorKind::ForeignPidNamespace)
    );
}

#[skuld::test]
fn a_linux_record_without_a_boot_id_is_rejected() {
    let mut r = linux_record();
    r.boot_id = None;
    assert_eq!(
        validate(&r, &Platform::Linux, &linux_scope()),
        Err(RecordErrorKind::MissingBootSession)
    );
}

#[skuld::test]
fn a_linux_record_without_a_pid_namespace_is_rejected() {
    let mut r = linux_record();
    r.pid_ns = None;
    assert_eq!(
        validate(&r, &Platform::Linux, &linux_scope()),
        Err(RecordErrorKind::MissingPidNamespace)
    );
}

#[skuld::test]
fn scope_fields_the_host_does_not_use_are_ignored() {
    // A Windows record that somehow carries Linux scope fields is still valid on Windows:
    // the platform matched, and this host has no boot session to compare against.
    let mut r = windows_record();
    r.boot_id = Some("36c39237-f06e-4e88-a74d-ea99d42b817c".into());
    r.pid_ns = Some(4_026_531_836);
    assert_eq!(
        validate(&r, &Platform::Windows, &Scope::none()),
        Ok((4242, 134_301_578_477_907_396))
    );
}

#[skuld::test]
fn platform_tags_round_trip_through_their_wire_strings() {
    for p in [Platform::Linux, Platform::MacOs, Platform::Windows] {
        assert_eq!(Platform::from_wire(p.as_str()), p);
    }
    assert_eq!(Platform::from_wire("freebsd"), Platform::Other("freebsd".into()));
    assert_eq!(Platform::Other("freebsd".into()).as_str(), "freebsd");
}

#[skuld::test]
fn the_wire_strings_are_the_documented_ones() {
    // Pinned literals: these strings are the persisted format and may never drift.
    assert_eq!(Platform::Linux.as_str(), "linux");
    assert_eq!(Platform::MacOs.as_str(), "macos");
    assert_eq!(Platform::Windows.as_str(), "windows");
}

#[skuld::test]
fn token_kinds_round_trip_through_their_wire_strings_and_an_unknown_one_is_other() {
    for kind in [TokenKind::Pidfs, TokenKind::Ticks] {
        assert_eq!(TokenKind::from_wire(kind.as_str()), kind);
    }
    // Pinned literals: these strings are the persisted format and may never drift.
    assert_eq!(TokenKind::Pidfs.as_str(), "pidfs");
    assert_eq!(TokenKind::Ticks.as_str(), "ticks");
    assert_eq!(TokenKind::from_wire("tsc"), TokenKind::Other("tsc".into()));
    assert_eq!(TokenKind::Other("tsc".into()).as_str(), "tsc");
}

#[skuld::test]
fn platform_current_names_this_host() {
    // Expected value from `std::env::consts::OS`, an independent fact about the build
    // target — NOT a second copy of `Platform::current`'s own cfg branching, which would
    // only prove the two agree with each other. The three wire strings were chosen to
    // match `consts::OS` exactly, so this is a straight comparison.
    assert_eq!(Platform::current().as_str(), std::env::consts::OS);
}

// A pid is data from a file like everything else in the record, and the crate's Unix code
// treats "not a single-process target" as impossible: `open_verified_with` does
// `Pid::from_raw(...).expect("a resolvable ProcessId is never pid 0")`, which
// PANICS on 0, and `src/identity/probe.rs` documents that a value above `i32::MAX` wraps
// negative, where `kill(-N, sig)` hits a whole process group. Restoring such a pid must be
// a typed rejection, never a panic — and never a signal to the wrong target.

#[skuld::test]
fn a_unix_record_with_pid_zero_is_rejected() {
    let mut r = linux_record();
    r.pid = 0;
    assert_eq!(
        validate(&r, &Platform::Linux, &linux_scope()),
        Err(RecordErrorKind::InvalidPid)
    );
}

#[skuld::test]
fn a_macos_record_with_pid_zero_is_rejected() {
    // macOS is the platform where pid 0 actually RESOLVES (`kernel_task`), so the check
    // cannot be left to the later existence probe.
    let r = ProcessIdRecord {
        version: RECORD_VERSION,
        platform: Platform::MacOs,
        pid: 0,
        token: 1,
        boot_id: None,
        pid_ns: None,
        token_kind: None,
    };
    assert_eq!(
        validate(&r, &Platform::MacOs, &Scope::none()),
        Err(RecordErrorKind::InvalidPid)
    );
}

#[skuld::test]
fn a_unix_record_with_a_pid_above_i32_max_is_rejected() {
    let mut r = linux_record();
    r.pid = u32::MAX;
    assert_eq!(
        validate(&r, &Platform::Linux, &linux_scope()),
        Err(RecordErrorKind::InvalidPid)
    );
}

#[skuld::test]
fn a_windows_record_with_pid_zero_is_rejected() {
    let mut r = windows_record();
    r.pid = 0;
    assert_eq!(
        validate(&r, &Platform::Windows, &Scope::none()),
        Err(RecordErrorKind::InvalidPid)
    );
}

#[skuld::test]
fn a_windows_record_with_a_pid_above_i32_max_is_accepted() {
    // Deliberate asymmetry: a Windows pid is a full `DWORD` and is never a `kill(2)`
    // target, so the `i32` ceiling that protects the Unix backends does not apply here.
    let mut r = windows_record();
    r.pid = u32::MAX;
    assert_eq!(
        validate(&r, &Platform::Windows, &Scope::none()),
        Ok((u32::MAX, 134_301_578_477_907_396))
    );
}

#[skuld::test]
fn the_pid_check_runs_after_the_platform_check() {
    // A pid-0 record from the wrong platform is ForeignPlatform: the pid rule is chosen by
    // platform, so it may not be applied before the platform is known to match.
    let mut r = linux_record();
    r.pid = 0;
    assert_eq!(
        validate(&r, &Platform::Windows, &Scope::none()),
        Err(RecordErrorKind::ForeignPlatform)
    );
}

#[skuld::test]
fn a_scope_mismatch_names_the_values_that_diverged() {
    // `kind` alone tells an operator the category; the detail has to say WHICH value
    // failed to match, the way the ScopeUnreadable path names its path and OS error.
    //
    // The live scope deliberately differs from the record in ALL fields. With matching
    // fixtures a single rendered occurrence would satisfy every assertion below, so a
    // regression that dropped the `scope` side from the format string — or rendered the
    // record's value twice — would still pass.
    let live = Scope {
        boot_id: Some("11111111-2222-3333-4444-555555555555".into()),
        pid_ns: Some(4_026_539_999),
        token_kind: Some(TokenKind::Ticks),
    };
    let e = reject(&linux_record(), &live, RecordErrorKind::ForeignBootSession);
    let rendered = e.to_string();
    assert!(
        rendered.contains("36c39237-f06e-4e88-a74d-ea99d42b817c"),
        "the record's boot id must appear: {rendered}"
    );
    assert!(
        rendered.contains("11111111-2222-3333-4444-555555555555"),
        "and the LIVE boot id it failed to match: {rendered}"
    );
    assert!(
        rendered.contains("4026531836"),
        "the record's pid namespace: {rendered}"
    );
    assert!(rendered.contains("4026539999"), "and the live one: {rendered}");
    assert!(rendered.contains("4242"), "and the pid: {rendered}");
    assert!(rendered.contains("pidfs"), "the record's kind of token: {rendered}");
    assert!(rendered.contains("ticks"), "and the live host's: {rendered}");
}

#[skuld::test]
fn a_record_of_the_other_kind_of_token_is_rejected() {
    // A pidfs inode is no starttime: compared with each other they would alias.
    for (record_kind, host_kind) in [
        (TokenKind::Pidfs, TokenKind::Ticks),
        (TokenKind::Ticks, TokenKind::Pidfs),
    ] {
        let mut r = linux_record();
        r.token_kind = Some(record_kind.clone());
        let scope = Scope {
            token_kind: Some(host_kind.clone()),
            ..linux_scope()
        };
        assert_eq!(
            validate(&r, &Platform::Linux, &scope),
            Err(RecordErrorKind::ForeignTokenKind),
            "{record_kind:?} record on a {host_kind:?} host"
        );
    }
}

#[skuld::test]
fn a_record_of_the_same_kind_of_token_validates() {
    let mut r = linux_record();
    r.token_kind = Some(TokenKind::Ticks);
    let scope = Scope {
        token_kind: Some(TokenKind::Ticks),
        ..linux_scope()
    };
    assert_eq!(validate(&r, &Platform::Linux, &scope), Ok((4242, 162_431_157)));
}

#[skuld::test]
fn an_unknown_kind_of_token_is_rejected_as_foreign() {
    let mut r = linux_record();
    r.token_kind = Some(TokenKind::Other("tsc".into()));
    assert_eq!(
        validate(&r, &Platform::Linux, &linux_scope()),
        Err(RecordErrorKind::ForeignTokenKind)
    );
}

#[skuld::test]
fn a_linux_record_without_a_kind_of_token_is_rejected() {
    let mut r = linux_record();
    r.token_kind = None;
    assert_eq!(
        validate(&r, &Platform::Linux, &linux_scope()),
        Err(RecordErrorKind::MissingTokenKind)
    );
}

/// The kind is checked last: a record of another pid namespace and another kind reports the
/// namespace, which says more about where the record came from.
#[skuld::test]
fn the_kind_of_token_is_checked_after_the_pid_namespace() {
    let mut r = linux_record();
    r.token_kind = Some(TokenKind::Ticks);
    let scope = Scope {
        pid_ns: Some(1),
        ..linux_scope()
    };
    assert_eq!(
        validate(&r, &Platform::Linux, &scope),
        Err(RecordErrorKind::ForeignPidNamespace)
    );
}

#[skuld::test]
fn a_record_of_a_host_without_kinds_ignores_a_stray_kind() {
    let mut r = windows_record();
    r.token_kind = Some(TokenKind::Pidfs);
    assert_eq!(
        validate(&r, &Platform::Windows, &Scope::none()),
        Ok((4242, 134_301_578_477_907_396))
    );
}

#[skuld::test]
fn a_scope_read_failure_keeps_the_path_and_the_cause() {
    // The one failure to_record/try_from can have. The mapping is pure, so it is checked
    // on every host even though only Linux can trigger it for real.
    let e = scope_error(ScopeReadError {
        path: "/proc/sys/kernel/random/boot_id".to_owned(),
        source: std::io::Error::new(std::io::ErrorKind::NotFound, "No such file or directory"),
    });
    let Error::IdentityRecord { kind, detail, source } = &e else {
        panic!("expected Error::IdentityRecord, got {e:?}");
    };
    assert_eq!(*kind, RecordErrorKind::ScopeUnreadable);
    assert!(
        detail.contains("/proc/sys/kernel/random/boot_id"),
        "the failing path must be in the detail, got {detail:?}"
    );
    let Some(Error::Io(source)) = source.as_deref() else {
        panic!("the io error must be preserved as the source, got {source:?}");
    };
    assert_eq!(source.kind(), std::io::ErrorKind::NotFound);
    assert_eq!(source.to_string(), "No such file or directory");
    assert!(!detail.contains("No such file or directory"), "{detail}");
}

// Live round trip ======================================================================

use super::{record_from, restore};
use crate::identity::{Existence, Liveness, ProcessId};

/// A scope read that failed, for driving the failure wiring of `record_from` / `restore`.
fn a_failed_scope_read() -> Result<Scope, ScopeReadError> {
    Err(ScopeReadError {
        path: "/proc/sys/kernel/random/boot_id".to_owned(),
        source: std::io::Error::new(std::io::ErrorKind::PermissionDenied, "Permission denied"),
    })
}

#[skuld::test]
fn a_failed_scope_read_aborts_writing_a_record() {
    // Drives the `?` inside `record_from` — the wiring `to_record` is one line of. Runs on
    // every host, including the two whose real `session_scope` cannot fail.
    let e = record_from(&ProcessId::current(), a_failed_scope_read()).expect_err("must not produce a record");
    let Error::IdentityRecord { kind, source, .. } = &e else {
        panic!("expected Error::IdentityRecord, got {e:?}");
    };
    assert_eq!(*kind, RecordErrorKind::ScopeUnreadable);
    let Some(Error::Io(cause)) = source.as_deref() else {
        panic!("cause preserved, got {source:?}");
    };
    assert_eq!(cause.kind(), std::io::ErrorKind::PermissionDenied);
}

#[skuld::test]
fn a_failed_scope_read_aborts_restoring_a_record() {
    // The same for `restore`. The record itself is perfectly valid — only the host's own
    // scope read failed — so anything other than ScopeUnreadable means the `?` is misplaced
    // and a record was validated against a scope nobody managed to read.
    let record = ProcessIdRecord {
        version: RECORD_VERSION,
        platform: Platform::current(),
        pid: 4242,
        token: 1,
        boot_id: None,
        pid_ns: None,
        token_kind: None,
    };
    let e = restore(&record, &Platform::current(), a_failed_scope_read()).expect_err("must not restore");
    let Error::IdentityRecord { kind, .. } = &e else {
        panic!("expected Error::IdentityRecord, got {e:?}");
    };
    assert_eq!(*kind, RecordErrorKind::ScopeUnreadable);
}

#[skuld::test]
fn the_current_identity_round_trips_through_a_record() {
    let me = ProcessId::current();
    let record = me.to_record().expect("this host can describe its own boot session");
    assert_eq!(record.version, RECORD_VERSION);
    assert_eq!(record.platform, Platform::current());
    assert_eq!(record.pid, me.pid());
    let back = ProcessId::try_from(&record).expect("a record just written here must restore");
    assert_eq!(back, me, "the restored identity must equal the original");
    // And the restored identity is still a working identity, not just equal bits.
    assert_eq!(back.exists(), Existence::Present);
    assert_eq!(back.is_alive(), Liveness::Alive);
}

#[skuld::test]
fn restoring_is_not_a_liveness_check() {
    // A record for a process that has exited still RESTORES — validation is about whether
    // the token can be compared here at all, not about whether the process is there.
    let mut child = crate::test_child::spawn_a_process_that_exits();
    let id = ProcessId::of(child.id())
        .found()
        .expect("a just-spawned child resolves");
    let record = id.to_record().expect("to_record");
    child.wait().expect("wait");
    let back = ProcessId::try_from(&record).expect("a record for a dead process still restores");
    assert_eq!(back, id);
    // `is_alive`, not `exists`: `child` still holds the process handle, and on Windows
    // that pins the kernel object so `exists()` stays Present. `is_alive` reads the
    // signaled state and is correct the instant the process exits.
    assert_eq!(
        back.is_alive(),
        Liveness::Dead,
        "…and only then does it report the process is not running"
    );
}

#[skuld::test]
fn a_record_from_this_host_carries_exactly_this_hosts_scope() {
    let record = ProcessId::current().to_record().expect("to_record");
    #[cfg(target_os = "linux")]
    {
        use std::os::unix::fs::MetadataExt;
        // Expected values read INDEPENDENTLY from /proc, not from the new code.
        let boot_id =
            std::fs::read_to_string("/proc/sys/kernel/random/boot_id").expect("/proc/sys/kernel/random/boot_id");
        assert_eq!(record.boot_id.as_deref(), Some(boot_id.trim()));
        let ino = std::fs::metadata("/proc/self/ns/pid").expect("ns/pid").ino();
        assert_eq!(record.pid_ns, Some(ino));
    }
    #[cfg(not(target_os = "linux"))]
    {
        assert_eq!(record.boot_id, None, "an absolute token needs no boot session");
        assert_eq!(record.pid_ns, None, "no pid namespaces on this platform");
    }
}

/// Assert `TryFrom` on `record` fails with `kind`.
fn assert_refused(record: &ProcessIdRecord, kind: RecordErrorKind) {
    match ProcessId::try_from(record) {
        Err(Error::IdentityRecord { kind: got, .. }) => assert_eq!(got, kind),
        Err(other) => panic!("expected Error::IdentityRecord({kind:?}), got {other:?}"),
        Ok(id) => panic!("expected {kind:?}, but the record restored to {id:?}"),
    }
}

#[skuld::test]
fn a_foreign_platform_record_is_refused_with_a_typed_error() {
    let mut record = ProcessId::current().to_record().expect("to_record");
    record.platform = Platform::Other("freebsd".into());
    assert_refused(&record, RecordErrorKind::ForeignPlatform);
}

#[skuld::test]
fn a_pid_zero_record_is_refused_through_the_live_path() {
    // The path that matters: a corrupt or hand-edited file reaching `Process::kill` with
    // pid 0 would panic in `open_verified_with` rather than return an error.
    let mut record = ProcessId::current().to_record().expect("to_record");
    record.pid = 0;
    assert_refused(&record, RecordErrorKind::InvalidPid);
}

#[cfg(unix)]
#[skuld::test]
fn a_pid_above_i32_max_is_refused_through_the_live_path() {
    let mut record = ProcessId::current().to_record().expect("to_record");
    record.pid = u32::MAX;
    assert_refused(&record, RecordErrorKind::InvalidPid);
}

// These four run only on Linux because only Linux has a non-empty scope. They are what
// pins `session_scope()` to the shape `validate` compares against: without them a scope
// left empty, or a boot_id read with a trailing newline, would pass every other test while
// silently disabling the boot check (or rejecting every real restore).

#[cfg(target_os = "linux")]
#[skuld::test]
fn a_record_from_a_different_boot_is_refused_through_the_live_path() {
    let mut record = ProcessId::current().to_record().expect("to_record");
    record.boot_id = Some("00000000-0000-0000-0000-000000000000".into());
    assert_refused(&record, RecordErrorKind::ForeignBootSession);
}

#[cfg(target_os = "linux")]
#[skuld::test]
fn a_record_without_a_boot_id_is_refused_through_the_live_path() {
    let mut record = ProcessId::current().to_record().expect("to_record");
    record.boot_id = None;
    assert_refused(&record, RecordErrorKind::MissingBootSession);
}

#[cfg(target_os = "linux")]
#[skuld::test]
fn a_record_from_a_different_pid_namespace_is_refused_through_the_live_path() {
    let mut record = ProcessId::current().to_record().expect("to_record");
    record.pid_ns = Some(record.pid_ns.expect("linux records carry a pid namespace") + 1);
    assert_refused(&record, RecordErrorKind::ForeignPidNamespace);
}

#[cfg(target_os = "linux")]
#[skuld::test]
fn a_record_without_a_pid_namespace_is_refused_through_the_live_path() {
    let mut record = ProcessId::current().to_record().expect("to_record");
    record.pid_ns = None;
    assert_refused(&record, RecordErrorKind::MissingPidNamespace);
}

#[cfg(target_os = "linux")]
#[skuld::test]
fn an_unreadable_boot_session_is_reported_with_its_path_and_cause() {
    // A real failed read of real paths that do not exist — no mocking. This is the only
    // way ScopeUnreadable is reachable in a test; on Windows and macOS the scope read
    // cannot fail at all, and the pure mapping is covered by
    // `a_scope_read_failure_keeps_the_path_and_the_cause`.
    let missing = std::path::Path::new("/proc/cosca-no-such-boot-id");
    let err = crate::identity::backend::session_scope_at(
        &crate::identity::HostKernel,
        missing,
        std::path::Path::new("/proc/self/ns/pid"),
    )
    .map_err(scope_error)
    .expect_err("a nonexistent path must fail");
    let Error::IdentityRecord { kind, detail, source } = &err else {
        panic!("expected Error::IdentityRecord, got {err:?}");
    };
    assert_eq!(*kind, RecordErrorKind::ScopeUnreadable);
    assert!(detail.contains("/proc/cosca-no-such-boot-id"), "{detail}");
    let Some(Error::Io(cause)) = source.as_deref() else {
        panic!("cause preserved, got {source:?}");
    };
    assert_eq!(cause.kind(), std::io::ErrorKind::NotFound);
}

#[cfg(target_os = "linux")]
#[skuld::test]
fn a_blank_boot_id_is_refused_rather_than_stored() {
    // A container runtime that masks the boot_id file (bind-mounting /dev/null over it)
    // makes the read SUCCEED and return "". Storing that as Some("") would compare equal to
    // the next boot's Some(""), silently disabling the boot-session check. A real file, a
    // real read — the emptiness is genuine, not mocked.
    let dir = tempfile::tempdir().expect("tempdir");
    let blank = dir.path().join("boot_id");
    std::fs::write(&blank, "\n").expect("write");
    let err = crate::identity::backend::session_scope_at(
        &crate::identity::HostKernel,
        &blank,
        std::path::Path::new("/proc/self/ns/pid"),
    )
    .map_err(scope_error)
    .expect_err("a blank boot_id must be refused");
    let Error::IdentityRecord { kind, .. } = &err else {
        panic!("expected Error::IdentityRecord, got {err:?}");
    };
    assert_eq!(*kind, RecordErrorKind::ScopeUnreadable);
}

/// The host's kind of token is read from its own pidfd. A host that refuses `pidfd_open` to this
/// process cannot say, and neither a record can be written nor one checked: `ScopeUnreadable`
/// naming `pidfd_open`.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_host_whose_own_pidfd_cannot_be_opened_has_no_scope() {
    let kernel = crate::identity::FakeKernel::new().on_pidfd_open(std::process::id(), Err(rustix::io::Errno::PERM));
    let err = crate::identity::backend::session_scope_at(
        &kernel,
        std::path::Path::new("/proc/sys/kernel/random/boot_id"),
        std::path::Path::new("/proc/self/ns/pid"),
    )
    .map_err(scope_error)
    .expect_err("a refused pidfd_open must fail the scope");
    let Error::IdentityRecord { kind, detail, source } = &err else {
        panic!("expected Error::IdentityRecord, got {err:?}");
    };
    assert_eq!(*kind, RecordErrorKind::ScopeUnreadable);
    assert!(detail.contains("pidfd_open"), "{detail}");
    assert_eq!(
        crate::error::first_os_code(&**source.as_ref().expect("cause preserved")),
        Some(libc::EPERM)
    );
}

/// A host whose own pidfd's inode cannot be read has no scope either, and the error names that read,
/// not `pidfd_open`, with its errno.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_host_whose_own_pidfs_ino_cannot_be_read_has_no_scope() {
    let (pidfd, _writer) = std::io::pipe().expect("a pipe");
    let kernel = crate::identity::FakeKernel::new()
        .on_pidfd_open(std::process::id(), Ok(pidfd.into()))
        .on_pidfs_ino(std::process::id(), Err(rustix::io::Errno::BADF));
    let err = crate::identity::backend::session_scope_at(
        &kernel,
        std::path::Path::new("/proc/sys/kernel/random/boot_id"),
        std::path::Path::new("/proc/self/ns/pid"),
    )
    .map_err(scope_error)
    .expect_err("a failed inode read must fail the scope");
    let Error::IdentityRecord { kind, detail, source } = &err else {
        panic!("expected Error::IdentityRecord, got {err:?}");
    };
    assert_eq!(*kind, RecordErrorKind::ScopeUnreadable);
    assert!(
        detail.contains("pidfs_ino") && !detail.contains("pidfd_open"),
        "{detail}"
    );
    assert_eq!(
        crate::error::first_os_code(&**source.as_ref().expect("cause preserved")),
        Some(libc::EBADF)
    );
}

/// The kind a pidfd shows is the kind of the scope: pidfs says `pidfs`, a pidfd with no inode
/// says `ticks`.
#[cfg(target_os = "linux")]
#[skuld::test]
fn the_scope_names_the_kind_of_token_the_hosts_pidfds_give() {
    let (pidfd, _writer) = std::io::pipe().expect("a pipe");
    for (answer, kind) in [(Some(5), TokenKind::Pidfs), (None, TokenKind::Ticks)] {
        let kernel = crate::identity::FakeKernel::new()
            .on_pidfd_open(std::process::id(), Ok(pidfd.try_clone().expect("dup").into()))
            .on_pidfs_ino(std::process::id(), Ok(answer));
        let scope = crate::identity::backend::session_scope_at(
            &kernel,
            std::path::Path::new("/proc/sys/kernel/random/boot_id"),
            std::path::Path::new("/proc/self/ns/pid"),
        )
        .expect("the scope reads");
        assert_eq!(scope.token_kind, Some(kind));
    }
}

/// A record names the kind of the id it holds, whatever the host's kind is; the host's kind is
/// what the way back checks. Mutant: "the record is written with the host's kind".
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_record_names_its_ids_own_kind_and_restores_into_it() {
    use crate::identity::Key;

    for (key, kind) in [(Key::Pidfs(77), TokenKind::Pidfs), (Key::Ticks(77), TokenKind::Ticks)] {
        let id = ProcessId::from_parts_for_test(4242, key);
        let scope = Scope {
            token_kind: Some(kind.clone()),
            ..linux_scope()
        };
        let record = record_from(&id, Ok(scope.clone())).expect("a record");
        assert_eq!(record.token, 77);
        assert_eq!(record.token_kind, Some(kind));
        assert_eq!(restore(&record, &Platform::Linux, Ok(scope)).expect("restores"), id);
    }
    let id = ProcessId::from_parts_for_test(4242, Key::Pidfs(77));
    let ticks_host = Scope {
        token_kind: Some(TokenKind::Ticks),
        ..linux_scope()
    };
    let record = record_from(&id, Ok(ticks_host.clone())).expect("a record");
    assert_eq!(record.token_kind, Some(TokenKind::Pidfs));
    let err = restore(&record, &Platform::Linux, Ok(ticks_host)).expect_err("another kind of host");
    assert!(
        matches!(
            err,
            Error::IdentityRecord {
                kind: RecordErrorKind::ForeignTokenKind,
                ..
            }
        ),
        "{err:?}"
    );
}