Qualify approved Windows clock profile on Linux and record preserved Chrony restart
Rust development slice / linux (push) Failing after 7s

This commit is contained in:
2026-11-15 11:51:11 +01:00
parent be57d98955
commit b8ca8266bb
5 changed files with 976 additions and 101 deletions
+529 -101
View File
@@ -28,6 +28,188 @@ fn independent_time_key(time_key_hex: &str, job_key_hex: &str) -> Result<[u8; 32
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>,
@@ -75,6 +257,24 @@ impl Continuity {
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,
@@ -144,31 +344,54 @@ impl Continuity {
}
}
/// All three native clocks are read in one bracket. The qualified base error
/// is a protected installation input, never inferred from 100ns resolution.
// 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,
base_error_ns: u64,
mode: CaptureMode,
) -> Result<Sample> {
const FILETIME_UNIX: u64 = 116_444_736_000_000_000;
ensure!(
base_error_ns > 0 && base_error_ns <= MAX_BASE_ERROR_NS,
"TIME_NATIVE_CALIBRATION_REQUIRED"
);
let width = raw_widths(
let (width, unbiased_width) = raw_widths(
interrupt_before,
interrupt_after,
unbiased_before,
unbiased_after,
)?
.0;
let capture_error_ns = width
.checked_add(base_error_ns)
.ok_or_else(|| anyhow::anyhow!("TIME_NATIVE_CAPTURE_OVERFLOW"))?;
)?;
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"
@@ -404,13 +627,11 @@ mod installed {
use super::*;
use crate::helper_ipc::{self as ipc, PeerProof, PinnedFile};
use anyhow::Context as _;
use rmm_agent_core::auth::Binding;
use rmm_domain::jobs::hash;
use rmm_time_attestation::{
Challenge, Context, Interval, Pins, Request, Role, SignedAttestation, VerifiedEvidence,
Verifier,
};
use serde::{Deserialize, Serialize};
use std::{
collections::BTreeMap,
io::Read,
@@ -423,47 +644,36 @@ mod installed {
const MAX_CONFIG_BYTES: usize = 16_384;
const MAX_REPLY_BYTES: usize = 16_384;
/// Provision only after an independent qualification of these actual
/// native APIs/platform/image. A file field is not a measured accuracy.
#[derive(Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Calibration {
pub role: Role,
pub binary_sha256: String,
pub qualification_sha256: String,
pub base_error_ns: u64,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Configuration {
pub schema_version: u32,
pub key_generation: u64,
pub server_instance: Uuid,
pub binding: Binding,
pub public_keys_hex: BTreeMap<String, String>,
pub calibrations: Vec<Calibration>,
}
fn digest(value: &str) -> bool {
value.len() == 64
&& value
.bytes()
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
}
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()))
}
fn capture(base_error_ns: u64) -> Result<Sample> {
// 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, base_error_ns)
bracket_sample(raw.wall, raw.ib, raw.ia, raw.ub, raw.ua, mode)
}
fn observed(boot: Uuid, base_error_ns: u64) -> Result<(Sample, u64)> {
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(base_error_ns) {
let value = match capture(mode) {
Ok(value) => value,
Err(error) => {
state.invalidate();
@@ -492,7 +702,7 @@ mod installed {
config_sha256: String,
boot_id: Uuid,
connection_generation: u64,
base_error_ns: u64,
capture_mode: CaptureMode,
pending: Option<Pending>,
latest: Option<HeldEvidence>,
}
@@ -501,6 +711,7 @@ mod installed {
/// 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,
@@ -535,50 +746,25 @@ mod installed {
.take(MAX_CONFIG_BYTES as u64 + 1)
.read_to_end(&mut raw)?;
ensure!(raw.len() <= MAX_CONFIG_BYTES, "TIME_NATIVE_CONFIG_SIZE");
let config: Configuration = serde_json::from_slice(&raw)?;
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!(
config.schema_version == 1
&& config.key_generation > 0
&& config.calibrations.len() == 2,
"TIME_NATIVE_CONFIG_PROFILE"
);
ensure!(
hash(&serde_json::to_vec(&config.binding)?)
hash(&serde_json::to_vec(config.binding())?)
== hash(&serde_json::to_vec(&settings.binding)?),
"TIME_NATIVE_DEVICE_BINDING"
);
for expected in [Role::Agent, Role::SystemHelper] {
let mut values = config
.calibrations
.iter()
.filter(|value| value.role == expected);
let value = values.next().context("TIME_NATIVE_CALIBRATION_MISSING")?;
ensure!(
values.next().is_none()
&& digest(&value.binary_sha256)
&& digest(&value.qualification_sha256)
&& value.base_error_ns > 0
&& value.base_error_ns <= MAX_BASE_ERROR_NS,
"TIME_NATIVE_CALIBRATION_PROFILE"
);
let pin = if expected == Role::Agent {
&settings.agent
} else {
&settings.helper
};
ensure!(
value.binary_sha256 == pin.binary_sha256,
"TIME_NATIVE_CALIBRATION_IMAGE"
);
}
let base_error_ns = config
.calibrations
.iter()
.find(|value| value.role == role)
.context("TIME_NATIVE_CALIBRATION_MISSING")?
.base_error_ns;
let keys = config
.public_keys_hex
.public_keys()
.iter()
.map(|(id, key)| {
ensure!(digest(key), "TIME_NATIVE_PUBLIC_KEY");
@@ -586,11 +772,11 @@ mod installed {
Ok((id.clone(), raw))
})
.collect::<Result<BTreeMap<_, _>>>()?;
let pins = Pins::new(config.key_generation, config.server_instance, keys)?;
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))?;
.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.
@@ -617,7 +803,7 @@ mod installed {
config_sha256: hash(&raw),
boot_id,
connection_generation,
base_error_ns,
capture_mode,
pending: None,
latest: None,
};
@@ -626,7 +812,8 @@ mod installed {
.lock()
.map_err(|_| anyhow::anyhow!("TIME_NATIVE_STATE_POISONED"))?
.accept_connection(connection_generation)?;
observed(boot_id, base_error_ns)?;
observed(boot_id, capture_mode)?;
failure_fence.armed = false;
Ok(value)
}
fn recheck(&mut self) -> Result<()> {
@@ -670,7 +857,7 @@ mod installed {
.lock()
.map_err(|_| anyhow::anyhow!("TIME_NATIVE_STATE_POISONED"))?;
state.require_connection(connection_generation)?;
let sample = match capture(self.base_error_ns) {
let sample = match capture(self.capture_mode) {
Ok(value) => value,
Err(error) => {
state.invalidate();
@@ -705,7 +892,7 @@ mod installed {
) -> Result<T> {
let pending = self.pending.take().context("TIME_NATIVE_NO_CHALLENGE")?;
let result = (|| {
let (received, epoch) = observed(self.boot_id, self.base_error_ns)?;
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)?;
@@ -714,7 +901,7 @@ mod installed {
let (evidence, interval) =
self.verifier
.finish_evidence(pending.challenge, &signed, received, || {
let (sample, epoch) = observed(self.boot_id, self.base_error_ns)?;
let (sample, epoch) = observed(self.boot_id, self.capture_mode)?;
ensure!(epoch == pending.epoch, "TIME_NATIVE_CHALLENGE_INVALIDATED");
checked = Some(sample);
Ok(sample)
@@ -762,7 +949,7 @@ mod installed {
.epoch;
let checked = (|| {
self.recheck()?;
let (sample, current_epoch) = observed(self.boot_id, self.base_error_ns)?;
let (sample, current_epoch) = observed(self.boot_id, self.capture_mode)?;
ensure!(epoch == current_epoch, "TIME_NATIVE_EVIDENCE_INVALIDATED");
let state = process()
.lock()
@@ -945,9 +1132,7 @@ mod installed {
}
}
#[cfg(all(windows, feature = "system-helper"))]
pub use installed::{
BoundClock, CONFIG_PATH, Calibration, Comparison, Configuration, RuntimeClock, SignedClock,
};
pub use installed::{BoundClock, CONFIG_PATH, Comparison, RuntimeClock, SignedClock};
#[cfg(test)]
mod tests {
@@ -1031,13 +1216,256 @@ mod tests {
#[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, 1_000_000).unwrap();
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, 1_000_000).is_err());
assert!(bracket_sample(wall, 100, 120, 90, 89, 1_000_000).is_err());
assert!(bracket_sample(wall, 100, 120, 90, 110, 0).is_err());
assert!(bracket_sample(wall, 0, 500_000, 0, 500_000, 1_000_000).is_err());
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() {