Files
rust-discovery/crates/agent-windows/src/signed_clock.rs
T
2026-11-15 14:35:22 +01:00

1581 lines
61 KiB
Rust

//! Independent signed time comparison for the Windows agent and SYSTEM helper.
//! Runtime readers use only their own fresh evidence and protected connection.
//! No provisioning, W32Time change or job authorization occurs here; the legacy
//! RPC adapter remains closed and is never a runtime fallback.
#![cfg(any(test, all(windows, feature = "system-helper")))]
use anyhow::{Result, ensure};
use rmm_time_attestation::Sample;
use uuid::Uuid;
const SECOND_NS: u64 = 1_000_000_000;
const MAX_BASE_ERROR_NS: u64 = 10_000_000;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SamplingMode {
Passive,
Jobs,
}
impl SamplingMode {
pub fn configured(jobs: bool, profile: &std::path::Path) -> std::io::Result<Option<Self>> {
if jobs {
return Ok(Some(Self::Jobs));
}
Ok(profile.try_exists()?.then_some(Self::Passive))
}
pub fn interval(self, verified: bool) -> std::time::Duration {
use std::time::Duration;
match (self, verified) {
(Self::Passive, _) => Duration::from_secs(30),
(Self::Jobs, true) => Duration::from_millis(20),
(Self::Jobs, false) => Duration::from_millis(500),
}
}
}
fn independent_time_key(time_key_hex: &str, job_key_hex: &str) -> Result<[u8; 32]> {
fn decode(value: &str) -> Result<[u8; 32]> {
ensure!(
value.len() == 64 && value.bytes().all(|byte| byte.is_ascii_hexdigit()),
"TIME_NATIVE_PUBLIC_KEY"
);
let mut raw = [0u8; 32];
for (index, byte) in raw.iter_mut().enumerate() {
*byte = u8::from_str_radix(&value[index * 2..index * 2 + 2], 16)?;
}
Ok(raw)
}
let time = decode(time_key_hex)?;
let job = decode(job_key_hex)?;
ensure!(time != job, "TIME_NATIVE_KEY_ROLE_REUSE");
Ok(time)
}
/// Schema1 retains independent numeric platform calibration. Schema2 is an
/// explicit opt-in to the user-approved nominal OS/active-guest trust model.
/// Disjoint deny-unknown-fields records prevent even null mixed-mode fields.
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(untagged)]
pub enum Configuration {
Physical(PhysicalConfiguration),
TrustedOs(TrustedOsConfiguration),
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(deny_unknown_fields)]
pub struct PhysicalConfiguration {
pub schema_version: u32,
pub key_generation: u64,
pub server_instance: Uuid,
pub binding: rmm_agent_core::auth::Binding,
pub public_keys_hex: std::collections::BTreeMap<String, String>,
pub calibrations: Vec<Calibration>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(deny_unknown_fields)]
pub struct Calibration {
pub role: rmm_time_attestation::Role,
pub binary_sha256: String,
pub qualification_sha256: String,
pub base_error_ns: u64,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(deny_unknown_fields)]
pub struct TrustedOsConfiguration {
pub schema_version: u32,
pub key_generation: u64,
pub server_instance: Uuid,
pub binding: rmm_agent_core::auth::Binding,
pub public_keys_hex: std::collections::BTreeMap<String, String>,
pub trusted_os_active_guest: TrustedOsActiveGuest,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(deny_unknown_fields)]
pub struct TrustedOsActiveGuest {
pub operating_assumption: ActiveGuestOperation,
pub platform: TrustedPlatform,
pub platform_provenance_sha256: String,
pub qualifications: Vec<RoleQualification>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub enum ActiveGuestOperation {
#[serde(rename = "active_guest_no_pause_save_restore_snapshot_migration_host_suspend")]
NoPauseSaveRestoreSnapshotMigrationHostSuspend,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub enum TrustedPlatform {
#[serde(rename = "kvm_qemu_hypervclock")]
KvmQemuHypervClock,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(deny_unknown_fields)]
pub struct RoleQualification {
pub role: rmm_time_attestation::Role,
pub binary_sha256: String,
pub qualification_sha256: String,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum CaptureMode {
Physical { base_error_ns: u64 },
TrustedOsActiveGuest,
}
fn digest(value: &str) -> bool {
value.len() == 64
&& value
.bytes()
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
}
impl Configuration {
#[cfg(all(windows, feature = "system-helper"))]
fn binding(&self) -> &rmm_agent_core::auth::Binding {
match self {
Self::Physical(value) => &value.binding,
Self::TrustedOs(value) => &value.binding,
}
}
fn key_generation(&self) -> u64 {
match self {
Self::Physical(value) => value.key_generation,
Self::TrustedOs(value) => value.key_generation,
}
}
#[cfg(all(windows, feature = "system-helper"))]
fn server_instance(&self) -> Uuid {
match self {
Self::Physical(value) => value.server_instance,
Self::TrustedOs(value) => value.server_instance,
}
}
#[cfg(all(windows, feature = "system-helper"))]
fn public_keys(&self) -> &std::collections::BTreeMap<String, String> {
match self {
Self::Physical(value) => &value.public_keys_hex,
Self::TrustedOs(value) => &value.public_keys_hex,
}
}
fn capture_mode(
&self,
own_role: rmm_time_attestation::Role,
agent_image: &str,
helper_image: &str,
) -> Result<CaptureMode> {
use rmm_time_attestation::Role;
ensure!(self.key_generation() > 0, "TIME_NATIVE_CONFIG_PROFILE");
let images = [
(Role::Agent, agent_image),
(Role::SystemHelper, helper_image),
];
match self {
Self::Physical(value) => {
ensure!(
value.schema_version == 1 && value.calibrations.len() == 2,
"TIME_NATIVE_CONFIG_PROFILE"
);
let mut own = None;
for (role, image) in images {
let mut values = value.calibrations.iter().filter(|v| v.role == role);
let item = values
.next()
.ok_or_else(|| anyhow::anyhow!("TIME_NATIVE_CALIBRATION_MISSING"))?;
ensure!(
values.next().is_none()
&& digest(&item.binary_sha256)
&& digest(&item.qualification_sha256)
&& item.base_error_ns > 0
&& item.base_error_ns <= MAX_BASE_ERROR_NS,
"TIME_NATIVE_CALIBRATION_PROFILE"
);
ensure!(item.binary_sha256 == image, "TIME_NATIVE_CALIBRATION_IMAGE");
if role == own_role {
own = Some(item.base_error_ns);
}
}
Ok(CaptureMode::Physical {
base_error_ns: own
.ok_or_else(|| anyhow::anyhow!("TIME_NATIVE_CALIBRATION_MISSING"))?,
})
}
Self::TrustedOs(value) => {
let profile = &value.trusted_os_active_guest;
ensure!(
value.schema_version == 2
&& profile.qualifications.len() == 2
&& digest(&profile.platform_provenance_sha256),
"TIME_NATIVE_TRUSTED_PROFILE"
);
// Both fields have exactly one accepted, explicit enum value.
// A JSON boolean, missing value or unknown variant cannot opt in.
ensure!(
matches!(
profile.operating_assumption,
ActiveGuestOperation::NoPauseSaveRestoreSnapshotMigrationHostSuspend
) && matches!(profile.platform, TrustedPlatform::KvmQemuHypervClock),
"TIME_NATIVE_ACTIVE_GUEST_ASSUMPTION"
);
for (role, image) in images {
let mut values = profile.qualifications.iter().filter(|v| v.role == role);
let item = values
.next()
.ok_or_else(|| anyhow::anyhow!("TIME_NATIVE_QUALIFICATION_MISSING"))?;
ensure!(
values.next().is_none()
&& digest(&item.binary_sha256)
&& digest(&item.qualification_sha256),
"TIME_NATIVE_QUALIFICATION_PROFILE"
);
ensure!(
item.binary_sha256 == image,
"TIME_NATIVE_QUALIFICATION_IMAGE"
);
}
Ok(CaptureMode::TrustedOsActiveGuest)
}
}
}
}
#[derive(Default)]
struct Continuity {
boot_id: Option<Uuid>,
previous: Option<Sample>,
epoch: u64,
exhausted: bool,
active: Option<Uuid>,
configuration: Option<(u64, String)>,
connection_generation: Option<u64>,
}
impl Continuity {
fn invalidate(&mut self) {
self.active = None;
match self.epoch.checked_add(1) {
Some(epoch) if !self.exhausted => self.epoch = epoch,
_ => self.exhausted = true,
}
}
fn observe(&mut self, boot_id: Uuid, sample: Sample) -> Result<()> {
let valid = !boot_id.is_nil()
&& !self.exhausted
&& self.boot_id.is_none_or(|old| old == boot_id)
&& sample.wall_utc_ns > 0
&& sample.capture_error_ns <= rmm_time_attestation::MAX_CAPTURE_ERROR_NS
&& self.previous.is_none_or(|old| {
match (
sample.wall_utc_ns.checked_sub(old.wall_utc_ns),
sample.interrupt_ns.checked_sub(old.interrupt_ns),
sample.unbiased_ns.checked_sub(old.unbiased_ns),
) {
(Some(wall), Some(interrupt), Some(unbiased)) if wall >= 0 => {
(wall as u64).abs_diff(interrupt) <= SECOND_NS
&& interrupt.abs_diff(unbiased) <= SECOND_NS
}
_ => false,
}
});
// Never adopt a different boot in a surviving process. A new adapter
// object cannot erase this process-wide identity/continuity history.
self.boot_id.get_or_insert(boot_id);
self.previous = Some(sample);
if !valid {
self.invalidate();
}
ensure!(valid, "TIME_NATIVE_DISCONTINUITY_OR_BOOT");
Ok(())
}
fn observe_configuration_raw(&mut self, sha256: &str) -> Result<()> {
ensure!(!self.exhausted, "TIME_NATIVE_CONFIGURATION_EXHAUSTED");
if self
.configuration
.as_ref()
.is_some_and(|(_, old)| old != sha256)
{
// Observe before decoding: malformed or mixed-profile bytes must
// invalidate old evidence too. Do not adopt a new hash or floor.
self.invalidate();
}
Ok(())
}
fn configuration_failure(&mut self) {
if self.configuration.is_some() {
self.invalidate();
}
}
fn accept_configuration(&mut self, generation: u64, sha256: &str) -> Result<()> {
ensure!(
generation > 0 && !self.exhausted,
"TIME_NATIVE_CONFIGURATION_GENERATION"
);
if let Some((current, hash)) = &self.configuration {
if generation < *current || (generation == *current && hash != sha256) {
// A constructor has positively observed a protected rollback
// or fork. Reject it without adopting its head, and retain the
// process-wide failure even if the original bytes are restored.
self.invalidate();
anyhow::bail!("TIME_NATIVE_CONFIGURATION_ROLLBACK_OR_FORK");
}
if generation > *current {
self.invalidate();
}
}
self.configuration = Some((generation, sha256.into()));
Ok(())
}
fn accept_connection(&mut self, generation: u64) -> Result<()> {
ensure!(
generation > 0
&& !self.exhausted
&& self
.connection_generation
.is_none_or(|old| generation >= old),
"TIME_NATIVE_CONNECTION_ROLLBACK"
);
if self
.connection_generation
.is_some_and(|old| generation > old)
{
self.invalidate();
}
self.connection_generation = Some(generation);
Ok(())
}
fn require_connection(&self, generation: u64) -> Result<()> {
ensure!(
!self.exhausted && self.connection_generation == Some(generation),
"TIME_NATIVE_CONNECTION_CHANGED"
);
Ok(())
}
fn reserve(&mut self, owner: Uuid) -> Result<u64> {
ensure!(
!self.exhausted && !owner.is_nil() && self.active.is_none(),
"TIME_NATIVE_CHALLENGE_BUSY"
);
self.active = Some(owner);
Ok(self.epoch)
}
fn require_owner(&self, owner: Uuid, epoch: u64) -> Result<()> {
ensure!(
!self.exhausted && self.active == Some(owner) && self.epoch == epoch,
"TIME_NATIVE_CHALLENGE_INVALIDATED"
);
Ok(())
}
fn require_epoch(&self, epoch: u64) -> Result<()> {
ensure!(
!self.exhausted && self.epoch == epoch,
"TIME_NATIVE_EVIDENCE_INVALIDATED"
);
Ok(())
}
}
// Called only after the installed loader's protected, bounded read. Keeping
// raw observation ahead of serde/profile validation also covers invalid V2.
fn load_configuration(
state: &mut Continuity,
raw: &[u8],
role: rmm_time_attestation::Role,
agent_image: &str,
helper_image: &str,
) -> Result<(Configuration, CaptureMode)> {
state.observe_configuration_raw(&rmm_domain::jobs::hash(raw))?;
let config: Configuration = serde_json::from_slice(raw)?;
let mode = config.capture_mode(role, agent_image, helper_image)?;
Ok((config, mode))
}
/// All three native clocks are read in one bracket. The protected mode chooses
/// either actual numeric calibration or the explicit nominal OS trust profile.
/// Neither a 100ns representation nor a bracket claims physical accuracy.
fn bracket_sample(
wall_filetime: u64,
interrupt_before: u64,
interrupt_after: u64,
unbiased_before: u64,
unbiased_after: u64,
mode: CaptureMode,
) -> Result<Sample> {
const FILETIME_UNIX: u64 = 116_444_736_000_000_000;
let (width, unbiased_width) = raw_widths(
interrupt_before,
interrupt_after,
unbiased_before,
unbiased_after,
)?;
let capture_error_ns = match mode {
CaptureMode::Physical { base_error_ns } => {
ensure!(
base_error_ns > 0 && base_error_ns <= MAX_BASE_ERROR_NS,
"TIME_NATIVE_CALIBRATION_REQUIRED"
);
width
.checked_add(base_error_ns)
.ok_or_else(|| anyhow::anyhow!("TIME_NATIVE_CAPTURE_OVERFLOW"))?
}
// This is a software bracket in trusted nominal OS units, not a
// physical accuracy bound. Checked multiplication by100 is exact, so
// there is no conversion rounding remainder or invented base constant.
CaptureMode::TrustedOsActiveGuest => width.max(unbiased_width),
};
ensure!(
capture_error_ns <= rmm_time_attestation::MAX_CAPTURE_ERROR_NS,
"TIME_NATIVE_CAPTURE_BUDGET"
);
let wall_utc_ns = wall_filetime
.checked_sub(FILETIME_UNIX)
.and_then(|value| value.checked_mul(100))
.ok_or_else(|| anyhow::anyhow!("TIME_NATIVE_WALL_RANGE"))?
.try_into()?;
Ok(Sample {
wall_utc_ns,
interrupt_ns: interrupt_after
.checked_mul(100)
.ok_or_else(|| anyhow::anyhow!("TIME_NATIVE_COUNTER_RANGE"))?,
unbiased_ns: unbiased_after
.checked_mul(100)
.ok_or_else(|| anyhow::anyhow!("TIME_NATIVE_COUNTER_RANGE"))?,
capture_error_ns,
})
}
fn raw_widths(ib: u64, ia: u64, ub: u64, ua: u64) -> Result<(u64, u64)> {
let width = ia
.checked_sub(ib)
.and_then(|value| value.checked_mul(100))
.ok_or_else(|| anyhow::anyhow!("TIME_NATIVE_CAPTURE_COUNTER"))?;
let unbiased_width = ua
.checked_sub(ub)
.and_then(|value| value.checked_mul(100))
.ok_or_else(|| anyhow::anyhow!("TIME_NATIVE_CAPTURE_COUNTER"))?;
ensure!(
width.abs_diff(unbiased_width) <= SECOND_NS,
"TIME_NATIVE_CAPTURE_SUSPEND"
);
Ok((width, unbiased_width))
}
/// Private raw capture, not a Sample and never clock authority.
#[derive(Clone, Copy)]
struct RawCapture {
wall: u64,
ib: u64,
ub: u64,
ua: u64,
ia: u64,
}
impl RawCapture {
fn widths(self) -> Result<(u64, u64)> {
ensure!(
self.wall > 116_444_736_000_000_000 && self.ib > 0 && self.ub > 0,
"TIME_NATIVE_RAW_RANGE"
);
raw_widths(self.ib, self.ia, self.ub, self.ua)
}
fn row(self) -> [u64; 5] {
[self.wall, self.ib, self.ub, self.ua, self.ia]
}
}
/// Fixed read-only getter sequence shared by installed and diagnostic paths.
#[cfg(windows)]
fn raw_capture() -> Result<RawCapture> {
#[link(name = "kernel32")]
unsafe extern "system" {
fn GetSystemTimePreciseAsFileTime(value: *mut u64);
fn QueryInterruptTimePrecise(value: *mut u64);
fn QueryUnbiasedInterruptTimePrecise(value: *mut u64);
}
let mut value = RawCapture {
wall: 0,
ib: 0,
ub: 0,
ua: 0,
ia: 0,
};
// SAFETY: documented VOID getters write valid aligned u64 outputs. These
// Windows10+ imports have no optional fallback or caller-selected target.
unsafe {
QueryInterruptTimePrecise(&mut value.ib);
QueryUnbiasedInterruptTimePrecise(&mut value.ub);
GetSystemTimePreciseAsFileTime(&mut value.wall);
QueryUnbiasedInterruptTimePrecise(&mut value.ua);
QueryInterruptTimePrecise(&mut value.ia);
}
value.widths()?;
Ok(value)
}
const RAW_SAMPLES: usize = 128;
const RAW_BUDGET_NS: u64 = 250_000_000;
/// Numeric observations only. No Deserialize, calibrated Sample conversion or
/// readiness flag; a report cannot open SignedClock or bypass its pin loader.
#[derive(serde::Serialize)]
pub struct CaptureDiagnostics {
schema_version: u32,
calibrated: bool,
clock_authority: bool,
columns_100ns: [&'static str; 5],
samples_100ns: Vec<[u64; 5]>,
sample_count: u32,
elapsed_monotonic_ns: u64,
elapsed_interrupt_ns: u64,
max_bracket_ns: u64,
max_internal_interrupt_unbiased_difference_ns: u64,
max_wall_interrupt_difference_ns: u64,
max_interrupt_unbiased_difference_ns: u64,
}
struct RawSeries {
first: Option<RawCapture>,
previous: Option<RawCapture>,
rows: Vec<[u64; 5]>,
max_bracket_ns: u64,
max_internal_delta_ns: u64,
max_wall_delta_ns: u64,
max_unbiased_delta_ns: u64,
}
impl RawSeries {
fn new() -> Self {
Self {
first: None,
previous: None,
rows: Vec::with_capacity(RAW_SAMPLES),
max_bracket_ns: 0,
max_internal_delta_ns: 0,
max_wall_delta_ns: 0,
max_unbiased_delta_ns: 0,
}
}
fn push(&mut self, value: RawCapture) -> Result<()> {
ensure!(self.rows.len() < RAW_SAMPLES, "TIME_RAW_SAMPLE_LIMIT");
let (width, unbiased_width) = value.widths()?;
ensure!(width <= RAW_BUDGET_NS, "TIME_RAW_CAPTURE_BUDGET");
if let Some(previous) = self.previous {
let wall = value
.wall
.checked_sub(previous.wall)
.and_then(|v| v.checked_mul(100))
.ok_or_else(|| anyhow::anyhow!("TIME_RAW_WALL_BACKWARD"))?;
let interrupt = value
.ia
.checked_sub(previous.ia)
.and_then(|v| v.checked_mul(100))
.ok_or_else(|| anyhow::anyhow!("TIME_RAW_INTERRUPT_BACKWARD"))?;
let unbiased = value
.ua
.checked_sub(previous.ua)
.and_then(|v| v.checked_mul(100))
.ok_or_else(|| anyhow::anyhow!("TIME_RAW_UNBIASED_BACKWARD"))?;
ensure!(
value.ib >= previous.ia && value.ub >= previous.ua,
"TIME_RAW_COUNTER_ORDER"
);
self.max_wall_delta_ns = self.max_wall_delta_ns.max(wall.abs_diff(interrupt));
self.max_unbiased_delta_ns =
self.max_unbiased_delta_ns.max(interrupt.abs_diff(unbiased));
ensure!(
wall.abs_diff(interrupt) <= SECOND_NS && interrupt.abs_diff(unbiased) <= SECOND_NS,
"TIME_RAW_DISCONTINUITY"
);
}
self.first.get_or_insert(value);
self.previous = Some(value);
self.max_bracket_ns = self.max_bracket_ns.max(width);
self.max_internal_delta_ns = self
.max_internal_delta_ns
.max(width.abs_diff(unbiased_width));
self.rows.push(value.row());
Ok(())
}
fn finish(self, elapsed_monotonic_ns: u64) -> Result<CaptureDiagnostics> {
ensure!(
self.rows.len() == RAW_SAMPLES && elapsed_monotonic_ns <= RAW_BUDGET_NS,
"TIME_RAW_INCOMPLETE_OR_EXPIRED"
);
let first = self
.first
.ok_or_else(|| anyhow::anyhow!("TIME_RAW_EMPTY"))?;
let last = self
.previous
.ok_or_else(|| anyhow::anyhow!("TIME_RAW_EMPTY"))?;
let elapsed_interrupt_ns = last
.ia
.checked_sub(first.ib)
.and_then(|v| v.checked_mul(100))
.ok_or_else(|| anyhow::anyhow!("TIME_RAW_COUNTER_RANGE"))?;
ensure!(
elapsed_interrupt_ns <= RAW_BUDGET_NS,
"TIME_RAW_INTERRUPT_BUDGET"
);
Ok(CaptureDiagnostics {
schema_version: 1,
calibrated: false,
clock_authority: false,
columns_100ns: [
"wall_filetime",
"interrupt_before",
"unbiased_before",
"unbiased_after",
"interrupt_after",
],
samples_100ns: self.rows,
sample_count: RAW_SAMPLES as u32,
elapsed_monotonic_ns,
elapsed_interrupt_ns,
max_bracket_ns: self.max_bracket_ns,
max_internal_interrupt_unbiased_difference_ns: self.max_internal_delta_ns,
max_wall_interrupt_difference_ns: self.max_wall_delta_ns,
max_interrupt_unbiased_difference_ns: self.max_unbiased_delta_ns,
})
}
}
/// Exactly128 bounded captures, spaced at fixed1ms target offsets. A missed
/// 250ms own-monotonic budget aborts; no sleep/time-setting API is used.
#[cfg(windows)]
pub fn diagnostic_capture_series() -> Result<CaptureDiagnostics> {
let started = std::time::Instant::now();
let budget = std::time::Duration::from_nanos(RAW_BUDGET_NS);
let mut series = RawSeries::new();
for index in 0..RAW_SAMPLES {
let due = std::time::Duration::from_millis(index as u64);
loop {
let elapsed = started.elapsed();
ensure!(elapsed <= budget, "TIME_RAW_MONOTONIC_BUDGET");
if elapsed >= due {
break;
}
std::hint::spin_loop();
}
series.push(raw_capture()?)?;
}
series.finish(started.elapsed().as_nanos().try_into()?)
}
#[cfg(all(windows, feature = "system-helper"))]
mod installed {
use super::*;
use crate::helper_ipc::{self as ipc, PeerProof, PinnedFile};
use anyhow::Context as _;
use rmm_domain::jobs::hash;
use rmm_time_attestation::{
Challenge, Context, Interval, Pins, Request, Role, SignedAttestation, VerifiedEvidence,
Verifier,
};
use std::{
collections::BTreeMap,
io::Read,
path::Path,
sync::{Arc, Mutex, OnceLock},
};
pub const CONFIG_PATH: &str = r"C:\ProgramData\RustDiscoverySystem\time-attestation.json";
const PUBLIC_ROOT: &str = r"C:\ProgramData\RustDiscoverySystem";
const MAX_CONFIG_BYTES: usize = 16_384;
const MAX_REPLY_BYTES: usize = 16_384;
static PROCESS: OnceLock<Mutex<Continuity>> = OnceLock::new();
static INCARNATION: OnceLock<Uuid> = OnceLock::new();
fn process() -> &'static Mutex<Continuity> {
PROCESS.get_or_init(|| Mutex::new(Continuity::default()))
}
// Any constructor failure/cancellation with a known configuration head
// closes process-global authority, including failures before raw bytes can
// be read. Successful same-config constructors do not rotate the epoch.
struct ConstructorFailureFence {
armed: bool,
}
impl Drop for ConstructorFailureFence {
fn drop(&mut self) {
if self.armed
&& let Ok(mut state) = process().lock()
{
state.configuration_failure();
}
}
}
fn capture(mode: CaptureMode) -> Result<Sample> {
let raw = raw_capture()?;
bracket_sample(raw.wall, raw.ib, raw.ia, raw.ub, raw.ua, mode)
}
fn observed(boot: Uuid, mode: CaptureMode) -> Result<(Sample, u64)> {
let mut state = process()
.lock()
.map_err(|_| anyhow::anyhow!("TIME_NATIVE_STATE_POISONED"))?;
let value = match capture(mode) {
Ok(value) => value,
Err(error) => {
state.invalidate();
return Err(error);
}
};
state.observe(boot, value)?;
Ok((value, state.epoch))
}
struct Pending {
owner: Uuid,
epoch: u64,
challenge: Challenge,
}
struct HeldEvidence {
evidence: VerifiedEvidence,
epoch: u64,
}
/// Own-process role proof, protected held configuration, private challenge
/// and native timers. No constructor accepts agent-reported helper times.
pub struct SignedClock {
verifier: Verifier,
own_process: PeerProof,
files: Vec<PinnedFile>,
config_sha256: String,
boot_id: Uuid,
connection_generation: u64,
capture_mode: CaptureMode,
pending: Option<Pending>,
latest: Option<HeldEvidence>,
}
impl SignedClock {
/// Connection generation is later confirmed by the independently
/// signed server response. It is never itself a ready/sync flag.
pub async fn open(role: Role, connection_generation: u64) -> Result<Self> {
ensure!(connection_generation > 0, "TIME_NATIVE_CONNECTION");
let mut failure_fence = ConstructorFailureFence { armed: true };
let (settings, mut files) = crate::helper_system::read_settings()?;
let own_pin = match role {
Role::Agent => &settings.agent,
Role::SystemHelper => &settings.helper,
};
own_pin.validate(role == Role::SystemHelper)?;
ipc::require_self(own_pin)?;
let own_process = PeerProof::for_service(
own_pin,
// SAFETY: this getter takes no arguments and returns own PID.
unsafe { windows_sys::Win32::System::Threading::GetCurrentProcessId() },
)?;
let readers = vec![
settings.agent.service_sid.clone(),
settings.helper.service_sid.clone(),
];
files.push(PinnedFile::open(
Path::new(PUBLIC_ROOT),
true,
&readers,
&[],
false,
)?);
let mut config_file =
PinnedFile::open(Path::new(CONFIG_PATH), false, &readers, &[], false)?;
ensure!(
config_file.file.metadata()?.len() <= MAX_CONFIG_BYTES as u64,
"TIME_NATIVE_CONFIG_SIZE"
);
let mut raw = Vec::new();
(&mut config_file.file)
.take(MAX_CONFIG_BYTES as u64 + 1)
.read_to_end(&mut raw)?;
ensure!(raw.len() <= MAX_CONFIG_BYTES, "TIME_NATIVE_CONFIG_SIZE");
let (config, capture_mode) = {
let mut state = process()
.lock()
.map_err(|_| anyhow::anyhow!("TIME_NATIVE_STATE_POISONED"))?;
load_configuration(
&mut state,
&raw,
role,
&settings.agent.binary_sha256,
&settings.helper.binary_sha256,
)?
};
ensure!(
hash(&serde_json::to_vec(config.binding())?)
== hash(&serde_json::to_vec(&settings.binding)?),
"TIME_NATIVE_DEVICE_BINDING"
);
let keys = config
.public_keys()
.iter()
.map(|(id, key)| {
ensure!(digest(key), "TIME_NATIVE_PUBLIC_KEY");
let raw = independent_time_key(key, &settings.binding.public_key_hex)?;
Ok((id.clone(), raw))
})
.collect::<Result<BTreeMap<_, _>>>()?;
let pins = Pins::new(config.key_generation(), config.server_instance(), keys)?;
process()
.lock()
.map_err(|_| anyhow::anyhow!("TIME_NATIVE_STATE_POISONED"))?
.accept_configuration(config.key_generation(), &hash(&raw))?;
// The existing fixed read-only native getter is independent in
// each process. It finishes BEFORE challenge/RTT timing begins.
let boot_id = Uuid::parse_str(&crate::native::boot_id().await?)?;
let context = Context {
tenant_id: settings.binding.tenant_id,
asset_id: settings.binding.asset_id,
agent_id: settings.binding.agent_id,
enrollment_generation: settings.binding.enrollment_generation,
assignment_generation: settings.binding.assignment_version,
connection_generation,
windows_boot_id: boot_id,
verifier_incarnation: *INCARNATION.get_or_init(Uuid::new_v4),
role,
helper_image_sha256: (role == Role::SystemHelper)
.then(|| own_pin.binary_sha256.clone()),
binding_schema: 1,
};
files.push(config_file);
let mut value = Self {
verifier: Verifier::new(context, pins)?,
own_process,
files,
config_sha256: hash(&raw),
boot_id,
connection_generation,
capture_mode,
pending: None,
latest: None,
};
value.recheck()?;
process()
.lock()
.map_err(|_| anyhow::anyhow!("TIME_NATIVE_STATE_POISONED"))?
.accept_connection(connection_generation)?;
observed(boot_id, capture_mode)?;
failure_fence.armed = false;
Ok(value)
}
fn recheck(&mut self) -> Result<()> {
let result = (|| {
self.own_process.check()?;
for file in &mut self.files {
file.check()?;
}
let config = self.files.last_mut().context("TIME_NATIVE_CONFIG_HELD")?;
ensure!(
config.sha256()? == self.config_sha256,
"TIME_NATIVE_CONFIG_CHANGED"
);
Ok(())
})();
if result.is_err() {
self.invalidate_observed_context();
}
result
}
fn invalidate_observed_context(&mut self) {
self.latest = None;
self.pending = None;
self.verifier.invalidate();
// A positively observed protected-context failure is shared by
// every object in this process, even if this object owns no nonce.
// Restoring old bytes must not revive any older same-generation
// evidence. Poisoned state already refuses all future access.
if let Ok(mut state) = process().lock() {
state.invalidate();
}
}
pub fn begin(&mut self, connection_generation: u64) -> Result<Request> {
if connection_generation != self.connection_generation {
self.close();
anyhow::bail!("TIME_NATIVE_CONNECTION_CHANGED");
}
ensure!(self.pending.is_none(), "TIME_NATIVE_PENDING");
self.recheck()?;
let mut state = process()
.lock()
.map_err(|_| anyhow::anyhow!("TIME_NATIVE_STATE_POISONED"))?;
state.require_connection(connection_generation)?;
let sample = match capture(self.capture_mode) {
Ok(value) => value,
Err(error) => {
state.invalidate();
return Err(error);
}
};
state.observe(self.boot_id, sample)?;
let owner = Uuid::new_v4();
let epoch = state.reserve(owner)?;
let challenge = match self.verifier.begin(sample) {
Ok(value) => value,
Err(error) => {
state.invalidate();
return Err(error);
}
};
let request = challenge.request().clone();
self.pending = Some(Pending {
owner,
epoch,
challenge,
});
Ok(request)
}
/// Call immediately after this verifier receives the complete bounded
/// response. The helper's caller supplies bytes only, never timestamps.
/// All failures consume the original request; no transparent retry.
pub fn complete<T>(
&mut self,
bytes: &[u8],
consume: impl FnOnce(&Comparison) -> Result<T>,
) -> Result<T> {
let pending = self.pending.take().context("TIME_NATIVE_NO_CHALLENGE")?;
let result = (|| {
let (received, epoch) = observed(self.boot_id, self.capture_mode)?;
ensure!(epoch == pending.epoch, "TIME_NATIVE_CHALLENGE_INVALIDATED");
ensure!(bytes.len() <= MAX_REPLY_BYTES, "TIME_NATIVE_REPLY_SIZE");
let signed: SignedAttestation = serde_json::from_slice(bytes)?;
self.recheck()?;
let mut checked = None;
let (evidence, interval) =
self.verifier
.finish_evidence(pending.challenge, &signed, received, || {
let (sample, epoch) = observed(self.boot_id, self.capture_mode)?;
ensure!(epoch == pending.epoch, "TIME_NATIVE_CHALLENGE_INVALIDATED");
checked = Some(sample);
Ok(sample)
})?;
let mut state = process()
.lock()
.map_err(|_| anyhow::anyhow!("TIME_NATIVE_STATE_POISONED"))?;
state.require_owner(pending.owner, pending.epoch)?;
state.active = None;
self.latest = Some(HeldEvidence {
evidence,
epoch: pending.epoch,
});
let comparison = Comparison {
interval,
wall_utc_ns: checked.context("TIME_NATIVE_FINAL_SAMPLE")?.wall_utc_ns,
};
drop(state);
consume(&comparison)
})();
if result.is_err() {
self.latest = None;
self.verifier.invalidate();
if let Ok(mut state) = process().lock()
&& state.active == Some(pending.owner)
{
state.invalidate();
}
}
result
}
/// No IO/IPC callback, reply, caller timestamp or ready flag is needed
/// for reads. Only a freshly recaptured own wall observation, bounded
/// by the original finite evidence, is exposed inside this callback.
pub fn with_current_comparison<T>(
&mut self,
consume: impl FnOnce(&Comparison) -> Result<T>,
) -> Result<T> {
// A first/next refresh may be pending. Absence/ordinary expiry of
// the old evidence must not consume that independent new nonce.
let epoch = self
.latest
.as_ref()
.context("TIME_NATIVE_NO_EVIDENCE")?
.epoch;
let checked = (|| {
self.recheck()?;
let (sample, current_epoch) = observed(self.boot_id, self.capture_mode)?;
ensure!(epoch == current_epoch, "TIME_NATIVE_EVIDENCE_INVALIDATED");
let state = process()
.lock()
.map_err(|_| anyhow::anyhow!("TIME_NATIVE_STATE_POISONED"))?;
state.require_epoch(epoch)?;
state.require_connection(self.connection_generation)?;
Ok(sample)
})();
let checked = match checked {
Ok(value) => value,
Err(error) => {
self.close();
return Err(error);
}
};
let evidence = &self
.latest
.as_ref()
.context("TIME_NATIVE_NO_EVIDENCE")?
.evidence;
let interval = match self.verifier.check_evidence(evidence, checked) {
Ok(value) => value,
Err(error) => {
self.latest = None;
return Err(error);
}
};
consume(&Comparison {
interval,
wall_utc_ns: checked.wall_utc_ns,
})
}
pub fn close(&mut self) {
self.verifier.invalidate();
let evidence_epoch = self.latest.take().map(|value| value.epoch);
let pending = self.pending.take();
if let Ok(mut state) = process().lock() {
let owns_pending = pending.is_some_and(|value| state.active == Some(value.owner));
if owns_pending || evidence_epoch == Some(state.epoch) {
state.invalidate();
}
}
}
}
impl Drop for SignedClock {
fn drop(&mut self) {
self.close();
}
}
/// Shared only inside one installed process. HTTP/IPC receives no access to
/// this slot or to its clock readings; its control surface is nonce/bytes.
#[derive(Clone)]
pub struct RuntimeClock {
role: Role,
state: Arc<Mutex<Option<(u64, SignedClock)>>>,
}
#[derive(Clone)]
pub struct BoundClock {
source: RuntimeClock,
generation: u64,
}
impl RuntimeClock {
pub fn new(role: Role) -> Self {
Self {
role,
state: Arc::new(Mutex::new(None)),
}
}
pub fn for_generation(&self, generation: u64) -> BoundClock {
BoundClock {
source: self.clone(),
generation,
}
}
pub fn configured_for(&self, generation: u64) -> bool {
self.state
.lock()
.is_ok_and(|state| state.as_ref().is_some_and(|(held, _)| *held == generation))
}
pub async fn open_connection(&self, generation: u64) -> Result<()> {
ensure!(generation > 0, "TIME_RUNTIME_GENERATION");
self.close()?;
let clock = SignedClock::open(self.role, generation).await?;
let mut state = self
.state
.lock()
.map_err(|_| anyhow::anyhow!("TIME_RUNTIME_POISONED"))?;
*state = Some((generation, clock));
Ok(())
}
pub fn begin(&self, generation: u64) -> Result<Request> {
let mut state = self
.state
.lock()
.map_err(|_| anyhow::anyhow!("TIME_RUNTIME_POISONED"))?;
let (held, clock) = state.as_mut().context("TIME_RUNTIME_NOT_CONFIGURED")?;
ensure!(*held == generation, "TIME_RUNTIME_CONNECTION_CHANGED");
clock.begin(generation)
}
pub fn complete(&self, generation: u64, bytes: &[u8]) -> Result<()> {
let mut state = self
.state
.lock()
.map_err(|_| anyhow::anyhow!("TIME_RUNTIME_POISONED"))?;
let (held, clock) = state.as_mut().context("TIME_RUNTIME_NOT_CONFIGURED")?;
ensure!(*held == generation, "TIME_RUNTIME_CONNECTION_CHANGED");
clock.complete(bytes, |_| Ok(()))
}
pub fn close_generation(&self, generation: u64) -> Result<()> {
let mut state = self
.state
.lock()
.map_err(|_| anyhow::anyhow!("TIME_RUNTIME_POISONED"))?;
if state.as_ref().is_some_and(|(held, _)| *held == generation) {
state.take(); // Drop fences this instance's pending/evidence.
}
Ok(())
}
pub fn close(&self) -> Result<()> {
self.state
.lock()
.map_err(|_| anyhow::anyhow!("TIME_RUNTIME_POISONED"))?
.take();
Ok(())
}
}
impl BoundClock {
pub fn source(&self) -> RuntimeClock {
self.source.clone()
}
pub fn for_generation(&self, generation: u64) -> Self {
self.source.for_generation(generation)
}
pub fn require_generation(&self, generation: u64) -> Result<()> {
ensure!(
self.generation == generation && generation > 0,
"TIME_RUNTIME_GENERATION"
);
Ok(())
}
}
impl rmm_agent_core::reconcile::SyncClock for BoundClock {
fn now(&self) -> Result<chrono::DateTime<chrono::Utc>> {
Ok(self.reading()?.own_wall)
}
fn reading(&self) -> Result<rmm_agent_core::reconcile::ClockReading> {
ensure!(self.generation > 0, "TIME_RUNTIME_NO_CONNECTION");
let mut state = self
.source
.state
.lock()
.map_err(|_| anyhow::anyhow!("TIME_RUNTIME_POISONED"))?;
let (held, clock) = state.as_mut().context("TIME_RUNTIME_NO_EVIDENCE")?;
ensure!(*held == self.generation, "TIME_RUNTIME_CONNECTION_CHANGED");
clock.with_current_comparison(|value| {
let own_wall = chrono::DateTime::from_timestamp_nanos(value.wall_utc_ns());
let upper = chrono::DateTime::from_timestamp_nanos(value.interval().upper_utc_ns());
Ok(rmm_agent_core::reconcile::ClockReading {
own_wall,
upper: upper.max(own_wall),
})
})
}
}
/// Borrowed only inside a completion/current-comparison callback, never returned as a
/// storable clock/lease/permit. Runtime callers must retain all job gates.
pub struct Comparison {
interval: Interval,
wall_utc_ns: i64,
}
impl Comparison {
pub fn interval(&self) -> &Interval {
&self.interval
}
pub fn wall_utc_ns(&self) -> i64 {
self.wall_utc_ns
}
}
}
#[cfg(all(windows, feature = "system-helper"))]
pub use installed::{BoundClock, CONFIG_PATH, Comparison, RuntimeClock, SignedClock};
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn passive_sampling_requires_a_profile_and_uses_heartbeat_cadence() {
let dir = std::env::temp_dir().join(Uuid::new_v4().to_string());
std::fs::create_dir(&dir).unwrap();
let profile = dir.join("time-attestation.json");
assert_eq!(SamplingMode::configured(false, &profile).unwrap(), None);
assert_eq!(
SamplingMode::configured(true, &profile).unwrap(),
Some(SamplingMode::Jobs)
);
std::fs::write(&profile, b"{}").unwrap();
assert_eq!(
SamplingMode::configured(false, &profile).unwrap(),
Some(SamplingMode::Passive)
);
for verified in [false, true] {
assert_eq!(
SamplingMode::Passive.interval(verified),
std::time::Duration::from_secs(30)
);
}
std::fs::remove_dir_all(dir).unwrap();
}
fn sample(ns: u64) -> Sample {
Sample {
wall_utc_ns: 1_800_000_000_000_000_000 + ns as i64,
interrupt_ns: 10_000_000_000 + ns,
unbiased_ns: 9_000_000_000 + ns,
capture_error_ns: 1_000_000,
}
}
fn raw(index: u64) -> RawCapture {
RawCapture {
wall: 134_444_736_000_000_000 + index * 10_000,
ib: 10_000_000 + index * 10_000,
ia: 10_000_010 + index * 10_000,
ub: 9_000_000 + index * 10_000,
ua: 9_000_008 + index * 10_000,
}
}
#[test]
fn raw_capture_denies_backward_wall_counters_and_incomplete_or_expired_series() {
let mut series = RawSeries::new();
series.push(raw(0)).unwrap();
assert!(
series
.push(RawCapture {
wall: raw(0).wall - 1,
..raw(1)
})
.is_err()
);
let mut series = RawSeries::new();
series.push(raw(0)).unwrap();
assert!(
series
.push(RawCapture {
ia: raw(0).ia - 1,
ib: raw(0).ib - 1,
..raw(1)
})
.is_err()
);
assert!(RawSeries::new().finish(0).is_err());
let mut series = RawSeries::new();
for index in 0..RAW_SAMPLES as u64 {
series.push(raw(index)).unwrap();
}
assert!(series.finish(RAW_BUDGET_NS + 1).is_err());
}
#[test]
fn complete_raw_report_is_bounded_non_authoritative_and_keeps_actual_brackets() {
let mut series = RawSeries::new();
for index in 0..RAW_SAMPLES as u64 {
series.push(raw(index)).unwrap();
}
assert!(series.push(raw(RAW_SAMPLES as u64)).is_err());
let report = series.finish(128_000_000).unwrap();
assert_eq!(report.sample_count, 128);
assert_eq!(report.max_bracket_ns, 1000);
assert_eq!(report.elapsed_interrupt_ns, 127_001_000);
assert_eq!(report.max_internal_interrupt_unbiased_difference_ns, 200);
let value = serde_json::to_value(&report).unwrap();
assert_eq!(value["calibrated"], false);
assert_eq!(value["clock_authority"], false);
assert!(value.get("capture_error_ns").is_none());
assert!(serde_json::to_vec(&report).unwrap().len() < 16384);
}
#[test]
fn job_key_cannot_be_reintroduced_as_a_time_key_with_different_hex_case() {
assert_eq!(
independent_time_key(&"ab".repeat(32), &"AB".repeat(32))
.unwrap_err()
.to_string(),
"TIME_NATIVE_KEY_ROLE_REUSE"
);
assert!(independent_time_key(&"ab".repeat(32), &"cd".repeat(32)).is_ok());
assert!(independent_time_key(&"ab".repeat(32), "not-a-provisioned-job-key").is_err());
}
#[test]
fn bracket_uses_actual_capture_width_and_refuses_unqualified_or_backward_counters() {
let wall = 116_444_736_000_000_000 + 18_000_000_000_000_000;
let result = bracket_sample(
wall,
100,
120,
90,
110,
CaptureMode::Physical {
base_error_ns: 1_000_000,
},
)
.unwrap();
assert_eq!(result.wall_utc_ns, 1_800_000_000_000_000_000);
assert_eq!(result.capture_error_ns, 1_002_000);
assert!(
bracket_sample(
wall,
100,
99,
90,
110,
CaptureMode::Physical {
base_error_ns: 1_000_000
}
)
.is_err()
);
assert!(
bracket_sample(
wall,
100,
120,
90,
89,
CaptureMode::Physical {
base_error_ns: 1_000_000
}
)
.is_err()
);
assert!(
bracket_sample(
wall,
100,
120,
90,
110,
CaptureMode::Physical { base_error_ns: 0 }
)
.is_err()
);
assert!(
bracket_sample(
wall,
0,
500_000,
0,
500_000,
CaptureMode::Physical {
base_error_ns: 1_000_000
}
)
.is_err()
);
}
#[test]
fn trusted_profile_requires_explicit_disjoint_schema_and_both_role_images() {
use rmm_time_attestation::Role;
let agent = "ab".repeat(32);
let helper = "cd".repeat(32);
let profile = serde_json::json!({
"operating_assumption": "active_guest_no_pause_save_restore_snapshot_migration_host_suspend",
"platform": "kvm_qemu_hypervclock",
"platform_provenance_sha256": "ef".repeat(32),
"qualifications": [
{"role":"agent", "binary_sha256": agent, "qualification_sha256": "12".repeat(32)},
{"role":"system_helper", "binary_sha256": helper, "qualification_sha256": "34".repeat(32)}
]
});
let config = serde_json::json!({
"schema_version": 2, "key_generation": 3, "server_instance": Uuid::new_v4(),
"binding": {"tenant_id":Uuid::new_v4(), "asset_id":Uuid::new_v4(), "agent_id":Uuid::new_v4(),
"enrollment_generation":1, "assignment_version":1, "public_key_hex":"56".repeat(32)},
"public_keys_hex": {"time1":"78".repeat(32)},
"trusted_os_active_guest": profile
});
let mode = |value: serde_json::Value| -> Result<CaptureMode> {
serde_json::from_value::<Configuration>(value)?.capture_mode(
Role::Agent,
&agent,
&helper,
)
};
assert_eq!(
mode(config.clone()).unwrap(),
CaptureMode::TrustedOsActiveGuest
);
for mutation in 0..12 {
let mut bad = config.clone();
match mutation {
0 => bad["schema_version"] = 1.into(),
1 => bad["schema_version"] = 3.into(),
2 => {
bad.as_object_mut()
.unwrap()
.remove("trusted_os_active_guest");
}
3 => bad["calibrations"] = serde_json::json!([]),
4 => bad["calibrations"] = serde_json::Value::Null,
5 => bad["trusted_os_active_guest"]["operating_assumption"] = "automatic".into(),
6 => {
bad["trusted_os_active_guest"]
.as_object_mut()
.unwrap()
.remove("platform_provenance_sha256");
}
7 => bad["trusted_os_active_guest"]["platform"] = "any_vm".into(),
8 => {
bad["trusted_os_active_guest"]["qualifications"][1]["binary_sha256"] =
agent.clone().into()
}
9 => bad["trusted_os_active_guest"]["qualifications"][1]["role"] = "agent".into(),
10 => {
bad["trusted_os_active_guest"]["qualifications"][1]["qualification_sha256"] =
"".into()
}
_ => {
bad["trusted_os_active_guest"]["qualifications"][0]["base_error_ns"] = 1.into()
}
}
assert!(mode(bad).is_err(), "mutation {mutation}");
}
// Old configurations keep their positive numeric contract; neither a
// version flip nor a null/mixed profile silently changes that mode.
let mut physical = config.clone();
physical
.as_object_mut()
.unwrap()
.remove("trusted_os_active_guest");
physical["schema_version"] = 1.into();
physical["calibrations"] = serde_json::json!([
{"role":"agent", "binary_sha256":agent, "qualification_sha256":"12".repeat(32), "base_error_ns":1_000_000},
{"role":"system_helper", "binary_sha256":helper, "qualification_sha256":"34".repeat(32), "base_error_ns":2_000_000}
]);
assert_eq!(
mode(physical.clone()).unwrap(),
CaptureMode::Physical {
base_error_ns: 1_000_000
}
);
let mut bad = physical.clone();
bad["trusted_os_active_guest"] = serde_json::Value::Null;
assert!(mode(bad).is_err());
let mut bad = physical.clone();
bad["schema_version"] = 2.into();
assert!(mode(bad).is_err());
physical["calibrations"][0]["base_error_ns"] = 0.into();
assert!(mode(physical).is_err());
}
#[test]
fn trusted_os_capture_uses_both_full_brackets_and_exact_integer_units() {
let wall = 116_444_736_000_000_000 + 18_000_000_000_000_000;
let trusted = CaptureMode::TrustedOsActiveGuest;
let sample = bracket_sample(wall, 100, 120, 90, 130, trusted).unwrap();
assert_eq!(sample.capture_error_ns, 4_000);
assert_eq!(sample.wall_utc_ns, 1_800_000_000_000_000_000);
assert_eq!(sample.interrupt_ns, 12_000);
assert_eq!(sample.unbiased_ns, 13_000);
let physical = bracket_sample(
wall,
100,
120,
90,
130,
CaptureMode::Physical {
base_error_ns: 1_000_000,
},
)
.unwrap();
assert_eq!(physical.capture_error_ns, 1_002_000);
// Exact OS-domain conversions add no guessed positive base constant.
assert_eq!(
bracket_sample(wall, 100, 100, 90, 90, trusted)
.unwrap()
.capture_error_ns,
0
);
assert_eq!(
bracket_sample(wall, 1, 500_001, 1, 500_001, trusted)
.unwrap()
.capture_error_ns,
rmm_time_attestation::MAX_CAPTURE_ERROR_NS
);
assert!(bracket_sample(wall, 1, 100_001, 1, 500_002, trusted).is_err());
assert!(bracket_sample(wall, 100, 99, 90, 130, trusted).is_err());
assert!(bracket_sample(wall, u64::MAX - 1, u64::MAX, 1, 2, trusted).is_err());
assert!(bracket_sample(u64::MAX, 100, 120, 90, 130, trusted).is_err());
}
#[test]
fn malformed_observed_config_and_failed_reads_cannot_restore_old_authority() {
use rmm_time_attestation::Role;
let agent = "ab".repeat(32);
let helper = "cd".repeat(32);
let old_raw = serde_json::to_vec(&serde_json::json!({
"schema_version":1, "key_generation":4, "server_instance":Uuid::new_v4(),
"binding":{"tenant_id":Uuid::new_v4(),"asset_id":Uuid::new_v4(),"agent_id":Uuid::new_v4(),
"enrollment_generation":1,"assignment_version":1,"public_key_hex":"56".repeat(32)},
"public_keys_hex":{"time1":"78".repeat(32)},
"calibrations":[
{"role":"agent","binary_sha256":agent,"qualification_sha256":"12".repeat(32),"base_error_ns":1_000_000},
{"role":"system_helper","binary_sha256":helper,"qualification_sha256":"34".repeat(32),"base_error_ns":1_000_000}
]
})).unwrap();
let old_sha = rmm_domain::jobs::hash(&old_raw);
let mut state = Continuity::default();
assert!(load_configuration(&mut state, &old_raw, Role::Agent, &agent, &helper).is_ok());
state.accept_configuration(4, &old_sha).unwrap();
let held_epoch = state.epoch;
let owner = Uuid::new_v4();
state.reserve(owner).unwrap();
// This is the actual constructor's pre-parse path, not a valid DTO
// mutation that would accidentally fail only after accepting a head.
assert!(
load_configuration(
&mut state,
b"{malformed",
Role::Agent,
&"ab".repeat(32),
&"cd".repeat(32)
)
.is_err()
);
assert_eq!(state.configuration, Some((4, old_sha.clone())));
assert!(state.require_owner(owner, held_epoch).is_err());
assert!(state.require_epoch(held_epoch).is_err());
let fenced_epoch = state.epoch;
assert!(load_configuration(&mut state, &old_raw, Role::Agent, &agent, &helper).is_ok());
state.accept_configuration(4, &old_sha).unwrap();
assert_eq!(state.epoch, fenced_epoch); // Same valid head is not a reset.
assert!(state.require_epoch(held_epoch).is_err());
let fresh = Uuid::new_v4();
let fresh_epoch = state.reserve(fresh).unwrap();
state.require_owner(fresh, fresh_epoch).unwrap();
// The constructor's failure/cancellation guard also covers protected
// pin/read errors before a new raw hash could be obtained.
state.configuration_failure();
assert!(state.require_owner(fresh, fresh_epoch).is_err());
assert_eq!(state.configuration, Some((4, old_sha)));
let mut unconfigured = Continuity::default();
unconfigured.configuration_failure();
assert_eq!(unconfigured.epoch, 0);
}
#[test]
fn retained_process_fence_rejects_old_challenge_and_boot_substitution() {
let boot = Uuid::new_v4();
let owner = Uuid::new_v4();
let mut state = Continuity::default();
state.accept_configuration(4, "one-config").unwrap();
state.accept_connection(3).unwrap();
let before_rollback = state.epoch;
assert!(state.accept_configuration(3, "old-config").is_err());
assert!(state.require_epoch(before_rollback).is_err());
assert_eq!(state.configuration, Some((4, "one-config".into())));
state.accept_configuration(4, "one-config").unwrap();
let before_fork = state.epoch;
assert!(state.accept_configuration(4, "different-config").is_err());
assert!(state.require_epoch(before_fork).is_err());
assert_eq!(state.configuration, Some((4, "one-config".into())));
state.accept_configuration(4, "one-config").unwrap();
assert!(state.require_epoch(before_rollback).is_err());
assert!(state.require_epoch(before_fork).is_err());
state.observe(boot, sample(0)).unwrap();
let first_clock_evidence = state.epoch;
let other_clock_evidence = state.epoch;
// recheck's observed-context failure fences the entire process even
// when no object currently owns a pending nonce. Same-generation
// restoration does not erase the observed failure or heal old proof.
state.invalidate();
state.accept_configuration(4, "one-config").unwrap();
assert!(state.require_epoch(first_clock_evidence).is_err());
assert!(state.require_epoch(other_clock_evidence).is_err());
let original_epoch = state.reserve(owner).unwrap();
assert!(original_epoch > first_clock_evidence);
// An outstanding refresh owns a nonce, not the older finite evidence.
state.require_epoch(original_epoch).unwrap();
assert!(state.reserve(Uuid::new_v4()).is_err());
let mut resumed = sample(2_000_000_000);
resumed.unbiased_ns = 9_000_000_000;
assert!(state.observe(boot, resumed).is_err());
assert!(state.require_owner(owner, original_epoch).is_err());
assert!(state.require_epoch(original_epoch).is_err());
// A caller reconstructing its verifier still sees this retained state.
state.observe(boot, resumed).unwrap();
let next = Uuid::new_v4();
let epoch = state.reserve(next).unwrap();
assert!(epoch > original_epoch);
state.require_owner(next, epoch).unwrap();
state.require_epoch(epoch).unwrap();
state.accept_connection(4).unwrap();
assert!(state.require_owner(next, epoch).is_err());
assert!(state.require_epoch(epoch).is_err());
assert!(state.require_connection(3).is_err());
assert!(state.accept_connection(3).is_err());
state.require_connection(4).unwrap();
assert!(state.observe(Uuid::new_v4(), resumed).is_err());
assert!(state.require_owner(next, epoch).is_err());
state.epoch = u64::MAX;
state.invalidate();
assert!(state.exhausted);
assert!(state.require_epoch(state.epoch).is_err());
state.invalidate();
assert!(state.exhausted);
assert!(state.reserve(Uuid::new_v4()).is_err());
}
}