use super::{
reject, scope_error, validate, Platform, ProcessIdRecord, Scope, ScopeReadError, TokenKind, RECORD_VERSION,
};
use crate::error::{Error, RecordErrorKind};
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),
}
}
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() {
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;
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() {
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() {
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() {
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() {
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);
}
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() {
assert_eq!(Platform::current().as_str(), std::env::consts::OS);
}
#[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() {
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() {
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() {
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() {
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() {
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)
);
}
#[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() {
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 source = source.as_ref().expect("the io error must be preserved as the source");
assert_eq!(source.kind(), std::io::ErrorKind::NotFound);
let rendered = e.to_string();
assert!(rendered.contains("/proc/sys/kernel/random/boot_id"), "{rendered}");
}
use super::{record_from, restore};
use crate::identity::{Existence, Liveness, ProcessId};
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() {
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);
assert_eq!(
source.as_ref().expect("cause preserved").kind(),
std::io::ErrorKind::PermissionDenied
);
}
#[skuld::test]
fn a_failed_scope_read_aborts_restoring_a_record() {
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");
assert_eq!(back.exists(), Existence::Present);
assert_eq!(back.is_alive(), Liveness::Alive);
}
#[skuld::test]
fn restoring_is_not_a_liveness_check() {
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);
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;
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");
}
}
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() {
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);
}
#[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() {
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}");
assert_eq!(
source.as_ref().expect("cause preserved").kind(),
std::io::ErrorKind::NotFound
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_blank_boot_id_is_refused_rather_than_stored() {
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);
}
#[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!(
source.as_ref().expect("cause preserved").raw_os_error(),
Some(libc::EPERM)
);
}
#[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!(
source.as_ref().expect("cause preserved").raw_os_error(),
Some(libc::EBADF)
);
}
#[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));
}
}
#[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:?}"
);
}