Files
rust-discovery/crates/updater-handoff/tests/handoff_contract.rs
T
2026-11-16 10:25:25 +01:00

665 lines
22 KiB
Rust

use ed25519_dalek::{Signer, SigningKey};
use rmm_updater_handoff::*;
use serde_json::{Value, json};
use uuid::Uuid;
fn id(n: u128) -> Uuid {
Uuid::from_u128(n)
}
fn h(n: u8) -> String {
format!("{n:02x}").repeat(32)
}
fn process(pid: u32, image: &str) -> Process {
Process {
pid,
birth: u64::from(pid) + 1000,
image_sha256: image.into(),
}
}
fn handoff() -> Handoff {
Handoff {
schema_version: 1,
attempt: AttemptBinding {
tenant_id: id(1),
asset_id: id(2),
agent_id: id(3),
enrollment_generation: 1,
assignment_version: 2,
plan_id: id(4),
plan_sha256: h(1),
job_id: id(5),
attempt_id: id(6),
job_payload_sha256: h(2),
grant_id: id(7),
authorization_id: id(8),
original_request_sha256: h(3),
original_start_witness_sha256: h(4),
},
agent_journal_id: id(9),
helper_journal_id: id(10),
helper_checkpoint: 7,
previous_decision_id: id(11),
boot_id: id(12),
connection_generation: 20,
owner_nonce: id(13),
updater_sha256: h(5),
updater_policy_sha256: h(6),
predecessor_record_sha256: h(7),
retained_state_sha256: h(8),
ledger_identity_sha256: h(22),
staged_files_sha256: h(9),
predecessor: CodePair {
manifest_sha256: h(10),
agent_sha256: h(11),
helper_sha256: h(12),
pin_sha256: h(13),
},
target: CodePair {
manifest_sha256: h(14),
agent_sha256: h(15),
helper_sha256: h(16),
pin_sha256: h(17),
},
pin_transition: PinTransition::LinuxGeneralFullV1,
pin_transition_sha256: h(18),
files: vec![
FileTransition {
role: FileRole::AgentBinary,
old_sha256: h(11),
new_sha256: h(15),
},
FileTransition {
role: FileRole::HelperBinary,
old_sha256: h(12),
new_sha256: h(16),
},
FileTransition {
role: FileRole::LinuxFullConfig,
old_sha256: h(19),
new_sha256: h(20),
},
FileTransition {
role: FileRole::LinuxFullPin,
old_sha256: h(13),
new_sha256: h(17),
},
],
stop_set: vec![
Service::LinuxAgent,
Service::LinuxGeneralHelper,
Service::LinuxFullHelper,
],
consumed_at: 100,
finish_before: 700,
}
}
fn key() -> SigningKey {
SigningKey::from_bytes(&[73; 32])
}
#[test]
fn windows_clock_transition_keeps_historical_four_file_shape_and_requires_exact_new_fifth_role() {
let mut value = handoff();
value.pin_transition = PinTransition::WindowsCodePairV1;
value.stop_set = vec![Service::WindowsAgent, Service::WindowsHelper];
value.files[2].role = FileRole::WindowsSettings;
value.files[3].role = FileRole::WindowsPin;
value.validate().unwrap();
let old = value.bytes().unwrap();
value.pin_transition = PinTransition::WindowsCodePairClockV1;
assert!(value.validate().is_err());
value.files.push(FileTransition {
role: FileRole::WindowsTimeProfile,
old_sha256: h(23),
new_sha256: h(24),
});
value.validate().unwrap();
value.files[3].new_sha256 = h(25);
assert!(value.validate().is_err());
value.files[3].new_sha256 = value.target.pin_sha256.clone();
value.files.swap(3, 4);
assert!(value.validate().is_err());
let historical: Handoff = serde_json::from_slice(&old).unwrap();
assert_eq!(historical.bytes().unwrap(), old);
}
fn open(handoff: &Handoff) -> Journal {
Journal::open(&handoff.bytes().unwrap(), key().verifying_key().to_bytes()).unwrap()
}
fn append(journal: &mut Journal, at: u64, evidence: Evidence) -> Vec<u8> {
let bytes = journal.prepare(at, evidence).unwrap();
journal.replay(&bytes).unwrap();
bytes
}
fn services(handoff: &Handoff) -> Vec<StartedService> {
handoff
.stop_set
.iter()
.filter(|s| **s != Service::LinuxAptHelper)
.enumerate()
.map(|(i, service)| StartedService {
service: *service,
process: process(
50 + i as u32,
if *service == Service::LinuxAgent {
&handoff.target.agent_sha256
} else {
&handoff.target.helper_sha256
},
),
})
.collect()
}
fn until_started(journal: &mut Journal, handoff: &Handoff) -> Vec<Vec<u8>> {
let mut events = vec![
append(journal, 101, Evidence::StopIntent),
append(
journal,
102,
Evidence::AllStopped {
observation_sha256: h(21),
},
),
append(
journal,
103,
Evidence::UpdaterOwnsLedger {
process: process(40, &handoff.updater_sha256),
ledger_identity_sha256: h(22),
},
),
];
for file in &handoff.files {
events.push(append(
journal,
104,
Evidence::ReplaceIntent { role: file.role },
));
events.push(append(
journal,
104,
Evidence::Replaced {
role: file.role,
observed_sha256: file.new_sha256.clone(),
},
));
}
events.push(append(
journal,
105,
Evidence::PairVerified {
pair: handoff.target.clone(),
retained_state_sha256: handoff.retained_state_sha256.clone(),
},
));
events.push(append(journal, 106, Evidence::LedgerReturnIntent));
events.push(append(
journal,
107,
Evidence::ServicesStarted {
services: services(handoff),
ledger_identity_sha256: h(22),
observation_sha256: h(23),
},
));
events
}
fn receipt(journal: &Journal, handoff: &Handoff) -> HealthReceipt {
HealthReceipt {
schema_version: 1,
handoff_sha256: journal.handoff_sha256().into(),
owner_nonce: handoff.owner_nonce,
boot_id: handoff.boot_id,
helper_journal_id: handoff.helper_journal_id,
agent_journal_id: handoff.agent_journal_id,
connection_generation: 21,
service_processes: services(handoff),
ledger_identity_sha256: h(22),
signed_sync_decision_id: id(14),
signed_sync_request_sha256: h(24),
signed_sync_response_sha256: h(25),
signed_sync_applied_at: 108,
ready: false,
inventory_message_id: id(15),
inventory_received_at: 108,
inventory_ack_sha256: h(26),
issued_at: 109,
valid_until: 200,
}
}
fn signed(receipt: &HealthReceipt, domain: &[u8], key: &SigningKey) -> SignedHealth {
let payload = serde_json::to_vec(receipt).unwrap();
let mut bytes = domain.to_vec();
bytes.extend_from_slice(&payload);
SignedHealth {
payload,
signature: key.sign(&bytes).to_bytes().to_vec(),
}
}
#[test]
fn full_linux_three_service_handoff_replays_exactly_sixteen_events() {
let handoff = handoff();
let mut journal = open(&handoff);
let mut events = until_started(&mut journal, &handoff);
let receipt = signed(&receipt(&journal, &handoff), HEALTH_DOMAIN, &key());
events.push(append(
&mut journal,
110,
Evidence::HealthVerified { receipt },
));
events.push(append(
&mut journal,
111,
Evidence::OutcomePersisted {
outcome_sha256: h(27),
},
));
assert_eq!(events.len(), MAX_EVENTS);
assert_eq!(journal.phase(), Phase::OutcomePersisted);
let mut reopened = open(&handoff);
for event in events {
reopened.replay(&event).unwrap();
}
assert_eq!(journal.head_sha256(), reopened.head_sha256());
assert_eq!(reopened.phase(), Phase::OutcomePersisted);
assert!(reopened.prepare(112, Evidence::StopIntent).is_err());
}
#[test]
fn no_ownership_before_stop_no_partial_pair_no_start_before_return() {
let handoff = handoff();
let mut journal = open(&handoff);
assert!(
journal
.prepare(
101,
Evidence::UpdaterOwnsLedger {
process: process(40, &handoff.updater_sha256),
ledger_identity_sha256: h(22)
}
)
.is_err()
);
append(&mut journal, 101, Evidence::StopIntent);
append(
&mut journal,
102,
Evidence::AllStopped {
observation_sha256: h(21),
},
);
append(
&mut journal,
103,
Evidence::UpdaterOwnsLedger {
process: process(40, &handoff.updater_sha256),
ledger_identity_sha256: h(22),
},
);
assert!(
journal
.prepare(
104,
Evidence::PairVerified {
pair: handoff.target.clone(),
retained_state_sha256: handoff.retained_state_sha256.clone()
}
)
.is_err()
);
assert!(
journal
.prepare(
104,
Evidence::ReplaceIntent {
role: FileRole::HelperBinary
}
)
.is_err()
);
for file in &handoff.files {
append(
&mut journal,
104,
Evidence::ReplaceIntent { role: file.role },
);
assert!(
journal
.prepare(
104,
Evidence::Replaced {
role: file.role,
observed_sha256: h(99)
}
)
.is_err()
);
append(
&mut journal,
104,
Evidence::Replaced {
role: file.role,
observed_sha256: file.new_sha256.clone(),
},
);
}
append(
&mut journal,
105,
Evidence::PairVerified {
pair: handoff.target.clone(),
retained_state_sha256: handoff.retained_state_sha256.clone(),
},
);
assert!(
journal
.prepare(
106,
Evidence::ServicesStarted {
services: services(&handoff),
ledger_identity_sha256: h(22),
observation_sha256: h(23)
}
)
.is_err()
);
append(&mut journal, 106, Evidence::LedgerReturnIntent);
let mut incomplete = services(&handoff);
incomplete.pop();
assert!(
journal
.prepare(
107,
Evidence::ServicesStarted {
services: incomplete,
ledger_identity_sha256: h(22),
observation_sha256: h(23)
}
)
.is_err()
);
}
#[test]
fn event_chain_clock_limits_and_canonical_bytes_fail_closed() {
let handoff = handoff();
let mut journal = open(&handoff);
let event = journal.prepare(101, Evidence::StopIntent).unwrap();
for field in [
"handoff_sha256",
"previous_sha256",
"boot_id",
"sequence",
"observed_at",
] {
let mut value: Value = serde_json::from_slice(&event).unwrap();
value[field] = match field {
"sequence" => json!(2),
"observed_at" => json!(99),
"boot_id" => json!(id(99)),
_ => json!(h(99)),
};
let parsed: Event = serde_json::from_value(value).unwrap();
assert!(
journal
.replay(&serde_json::to_vec(&parsed).unwrap())
.is_err(),
"{field}"
);
}
let mut whitespace = event.clone();
whitespace.push(b' ');
assert!(journal.replay(&whitespace).is_err());
assert!(journal.replay(&vec![b' '; MAX_EVENT_BYTES + 1]).is_err());
assert!(journal.prepare(700, Evidence::StopIntent).is_err());
journal.replay(&event).unwrap();
assert!(journal.replay(&event).is_err());
assert_eq!(journal.phase(), Phase::StopIntent);
}
#[test]
fn health_is_domain_bound_fresh_evidence_and_never_opens_ready() {
let handoff = handoff();
let mut journal = open(&handoff);
until_started(&mut journal, &handoff);
let baseline = receipt(&journal, &handoff);
for change in 0..11 {
let mut receipt = baseline.clone();
match change {
0 => receipt.ready = true,
1 => receipt.owner_nonce = id(99),
2 => receipt.boot_id = id(99),
3 => receipt.helper_journal_id = id(99),
4 => receipt.connection_generation = 20,
5 => receipt.signed_sync_applied_at = 106,
6 => receipt.inventory_received_at = 106,
7 => receipt.service_processes[1].process.birth += 1,
8 => receipt.valid_until = 110,
9 => receipt.handoff_sha256 = h(99),
_ => receipt.issued_at = 111,
}
assert!(
journal
.prepare(
110,
Evidence::HealthVerified {
receipt: signed(&receipt, HEALTH_DOMAIN, &key())
}
)
.is_err(),
"change {change}"
);
}
assert!(
journal
.prepare(
110,
Evidence::HealthVerified {
receipt: signed(&baseline, b"rmm.execution-permit.v1\0", &key())
}
)
.is_err()
);
assert!(
journal
.prepare(
110,
Evidence::HealthVerified {
receipt: signed(&baseline, HEALTH_DOMAIN, &SigningKey::from_bytes(&[74; 32]))
}
)
.is_err()
);
let mut late = baseline;
late.issued_at = 287;
late.valid_until = 400;
assert!(
journal
.prepare(
287,
Evidence::HealthVerified {
receipt: signed(&late, HEALTH_DOMAIN, &key())
}
)
.is_err()
);
append(
&mut journal,
701,
Evidence::Unknown {
reason: UnknownReason::DeadlineExpired,
},
);
assert_eq!(journal.phase(), Phase::Unknown);
assert!(
journal
.prepare(
702,
Evidence::HealthVerified {
receipt: signed(&late, HEALTH_DOMAIN, &key())
}
)
.is_err()
);
assert!(journal.prepare(702, Evidence::StopIntent).is_err());
}
#[test]
fn closed_service_sets_reject_omitted_full_and_apt_restart() {
let mut handoff = handoff();
handoff.stop_set.pop();
assert!(handoff.bytes().is_err());
handoff.stop_set.push(Service::LinuxFullHelper);
handoff.stop_set.push(Service::LinuxAptHelper);
let mut journal = open(&handoff);
until_started(&mut journal, &handoff);
assert_eq!(journal.phase(), Phase::ServicesStarted);
handoff.files[3].new_sha256 = h(99);
assert!(handoff.bytes().is_err());
}
fn full_files() -> (Vec<u8>, Vec<u8>) {
let public_key = hex::encode(key().verifying_key().as_bytes());
let identity = json!({"tenant_id":id(1),"asset_id":id(2),"agent_id":id(3),
"enrollment_generation":1,"assignment_version":2,"signing_key_id":sha256(&hex::decode(&public_key).unwrap())});
// Exact Policy codec order copied from runtime control::Policy schema2.
let policy = format!(
"{{\"schema_version\":2,\"profile\":\"full_maintenance_v1\",\"identity\":{{\"tenant_id\":\"{}\",\"asset_id\":\"{}\",\"agent_id\":\"{}\",\"enrollment_generation\":1,\"assignment_version\":2,\"signing_key_id\":\"{}\"}},\"allowed_services\":[],\"allow_root_scripts\":true,\"allow_reboot\":false,\"allowed_script_profiles\":[\"full_maintenance_v1\"],\"helper_binary_sha256\":\"{}\"}}",
id(1),
id(2),
id(3),
identity["signing_key_id"].as_str().unwrap(),
h(12)
);
let config = json!({"profile":"full_maintenance_v1", "binding":{"tenant_id":id(1),"asset_id":id(2),
"agent_id":id(3),"enrollment_generation":1,"assignment_version":2,"public_key_hex":public_key},
"signing_key_file":format!("/etc/rmm/{}/public-key.json",h(12)),"agent_uid":993,"socket_gid":984,
"socket":"/run/rmm-full-helper/helper.sock","state":"/var/lib/rmm-helper","allowed_services":[],
"allow_reboot":false,"allow_root_scripts":true,"allowed_script_profiles":["full_maintenance_v1"],
"helper_binary_sha256":h(12)});
let pin = json!({"schema_version":2,"profile":"full_maintenance_v1","identity":identity,
"policy_sha256":sha256(policy.as_bytes()),"helper_binary_sha256":h(12)});
(
serde_json::to_vec_pretty(&config).unwrap(),
serde_json::to_vec_pretty(&pin).unwrap(),
)
}
fn render_linux_full(
config: &[u8],
pin: &[u8],
target: &str,
) -> anyhow::Result<LinuxFullTransition> {
rmm_updater_handoff::render_linux_full(config, pin, target, &key().verifying_key())
}
#[test]
fn full_renderer_binds_provisioned_file_key_without_inserting_it_into_raw_config() {
let (inline_config, pin) = full_files();
let mut file_config: Value = serde_json::from_slice(&inline_config).unwrap();
file_config["binding"]["public_key_hex"] = json!("");
let bytes = serde_json::to_vec_pretty(&file_config).unwrap();
let transition = render_linux_full(&bytes, &pin, &h(16)).unwrap();
let actual: Value = serde_json::from_slice(transition.new_config_bytes()).unwrap();
assert_eq!(actual["binding"]["public_key_hex"], "");
assert_eq!(actual["signing_key_file"], file_config["signing_key_file"]);
assert_eq!(
transition.proof().effective_signing_key_id,
sha256(key().verifying_key().as_bytes())
);
let expected = String::from_utf8(bytes.clone()).unwrap().replace(
&format!("\"helper_binary_sha256\": \"{}\"", h(12)),
&format!("\"helper_binary_sha256\": \"{}\"", h(16)),
);
assert_eq!(transition.new_config_bytes(), expected.as_bytes());
let inline = render_linux_full(&inline_config, &pin, &h(16)).unwrap();
assert_eq!(
transition.proof().new_policy_sha256,
inline.proof().new_policy_sha256
);
assert_eq!(transition.new_pin_bytes(), inline.new_pin_bytes());
let foreign_key = SigningKey::from_bytes(&[74; 32]).verifying_key();
assert!(rmm_updater_handoff::render_linux_full(&bytes, &pin, &h(16), &foreign_key).is_err());
assert!(
rmm_updater_handoff::render_linux_full(&inline_config, &pin, &h(16), &foreign_key).is_err()
);
file_config
.as_object_mut()
.unwrap()
.remove("signing_key_file");
assert!(render_linux_full(&serde_json::to_vec(&file_config).unwrap(), &pin, &h(16)).is_err());
file_config["signing_key_file"] = json!("relative-key.json");
assert!(render_linux_full(&serde_json::to_vec(&file_config).unwrap(), &pin, &h(16)).is_err());
}
#[test]
fn full_renderer_changes_only_named_hash_spans_preserving_all_other_raw_bytes() {
let (config, pin) = full_files();
let transition = render_linux_full(&config, &pin, &h(16)).unwrap();
assert_eq!(transition.proof().old_config_sha256, sha256(&config));
let before: Value = serde_json::from_slice(&config).unwrap();
let after: Value = serde_json::from_slice(transition.new_config_bytes()).unwrap();
assert_eq!(before["signing_key_file"], after["signing_key_file"]);
assert!(after["signing_key_file"].as_str().unwrap().contains(&h(12)));
let needle = format!("\"helper_binary_sha256\": \"{}\"", h(12));
let expected = String::from_utf8(config)
.unwrap()
.replace(&needle, &format!("\"helper_binary_sha256\": \"{}\"", h(16)));
assert_eq!(transition.new_config_bytes(), expected.as_bytes());
let old_pin = String::from_utf8(pin).unwrap();
let expected = old_pin
.replace(&needle, &format!("\"helper_binary_sha256\": \"{}\"", h(16)))
.replace(
&transition.proof().old_policy_sha256,
&transition.proof().new_policy_sha256,
);
assert_eq!(transition.new_pin_bytes(), expected.as_bytes());
assert_eq!(transition.sha256().unwrap().len(), 64);
assert!(
render_linux_full(
transition.new_config_bytes(),
transition.new_pin_bytes(),
&h(17)
)
.is_ok()
);
}
#[test]
fn full_renderer_rejects_foreign_pins_unknown_duplicate_escaped_and_privilege_changes() {
let (config, pin) = full_files();
for field in [
"allow_reboot",
"allowed_services",
"allowed_script_profiles",
"profile",
"apt_provider",
] {
let mut value: Value = serde_json::from_slice(&config).unwrap();
value[field] = match field {
"allow_reboot" => json!(true),
"allowed_services" => json!(["other.service"]),
"allowed_script_profiles" => Value::Null,
"profile" => json!("general"),
_ => json!({}),
};
assert!(
render_linux_full(&serde_json::to_vec(&value).unwrap(), &pin, &h(16)).is_err(),
"{field}"
);
}
let mut foreign: Value = serde_json::from_slice(&pin).unwrap();
foreign["identity"]["agent_id"] = json!(id(99));
assert!(render_linux_full(&config, &serde_json::to_vec(&foreign).unwrap(), &h(16)).is_err());
let mut unknown: Value = serde_json::from_slice(&config).unwrap();
unknown["binding"]["new_field"] = json!(true);
assert!(render_linux_full(&serde_json::to_vec(&unknown).unwrap(), &pin, &h(16)).is_err());
let text = String::from_utf8(config).unwrap();
let duplicate = text.replacen("{", "{\"helper_binary_sha256\":\"0000000000000000000000000000000000000000000000000000000000000000\",",1);
assert!(render_linux_full(duplicate.as_bytes(), &pin, &h(16)).is_err());
let escaped = text.replace(
&format!("\"helper_binary_sha256\": \"{}\"", h(12)),
&format!("\"helper_binary_sha256\": \"\\u0030{}\"", &h(12)[1..]),
);
assert!(render_linux_full(escaped.as_bytes(), &pin, &h(16)).is_err());
}