Files
rust-discovery/crates/privileged-helper/src/apt_configured_reconcile.rs
T

760 lines
33 KiB
Rust

//! One historical configure-only fixture whose effect completed but whose old
//! acceptance rejected an ambient host reboot flag. Read-only proof, FAILED
//! acceptance, and ordinary signed Sync only; never retry or retroactive success.
use super::*;
use rmm_domain::apt_transaction::{AptNativeRecovery, AptTransactionOperation};
const TARGET_GRANT: &str = "33775478-15b0-46ec-b059-44f500dbb0b6";
const PRIOR_GRANT: &str = "31ef5e5e-5dbd-4428-a9a1-cbd15de2f5a0";
const OLD_PROVIDER: &str = "5ff260f75cb2959678f6be729d3a806a4ea29febd5ae4003317fed41afc25327";
const OLD_RUNTIME: &str = "706c74d72592db990b47869b06ebc8668dffe029d01b13df52d7ef4f22b758fe";
const CLASSIFIED: &str = "APT_RECOVERY_CONFIGURED_ACCEPTANCE_REBOOT_FLAG_VERIFIED";
const ACTIVE_NAMES: [&str; 10] = [
"context.json",
"signed-action.json",
"expectation.json",
"baseline.json",
"launch.json",
"native-prechecks.json",
"sandbox-ready.json",
"sandbox-result.json",
"hook-armed.json",
"partial-proof.json",
];
#[derive(Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Proof {
schema_version: u32,
#[serde(rename = "type")]
kind: String,
transaction_sha256: String,
job_payload_sha256: String,
effect_armed_ledger_id: String,
grant_id: Uuid,
job_id: Uuid,
attempt_id: Uuid,
authorization_id: Uuid,
plan_sha256: String,
original_evidence_sha256: String,
partial_proof_sha256: String,
original_baseline_sha256: String,
observed_snapshot_sha256: String,
status_fingerprint: String,
fixture_payload_sha256: String,
snapshot: BTreeMap<String, PackageState>,
checked_at_ms: i64,
effect_complete: bool,
partial_effect: bool,
postconditions_passed: bool,
reboot_required: bool,
host_reboot_required: bool,
host_reboot_marker_sha256: String,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Output {
effect_state: String,
code: String,
proof: Proof,
}
fn eligible(binding: &Binding, row: &LedgerRow) -> Result<Option<Candidate>> {
if row.grant != TARGET_GRANT {
return Ok(None);
}
ensure!(
row.start.len() <= 512 * 1024 && row.outcome.len() <= 512 * 1024,
"APT_CONFIGURED_RECORD_LIMIT"
);
let old: Outcome = serde_json::from_slice(&row.outcome)?;
if old.state != "unknown" || old.error_code != "FIXTURE_UNEXPECTED_REBOOT_REQUIRED" {
return Ok(None);
}
let start: SavedStart = serde_json::from_slice(&row.start)?;
let permit: ExecutionPermitPayload = serde_json::from_slice(&start.request.permit_bytes)?;
let (job, permit) = binding.verify(&start.request, permit.not_before)?;
ensure!(
!start.previous_boot_id.is_nil()
&& start.reauthentication_required
&& !start.postconditions_passed
&& start.reconnect_deadline.is_none()
&& start.reserved_at <= permit.start_before
&& row.agent == binding.agent_id.to_string()
&& row.generation == binding.enrollment_generation
&& row.grant == permit.grant_id.to_string()
&& row.job == job.job_id.to_string()
&& row.attempt == job.attempt_id.to_string()
&& job.execution_identity == "root",
"APT_CONFIGURED_ORIGINAL_BINDING"
);
let Action::AptNativeAcceptance {
recipe_id,
recipe_version,
apt_manifest: m,
} = &job.action
else {
return Ok(None);
};
let Some(reference) = &m.native_recovery else {
return Ok(None);
};
ensure!(
recipe_id == apt::INSTALL_RECIPE
&& recipe_version == "1"
&& m.validate()
&& m.schema_version == 4
&& m.native_retry.is_none()
&& reference.previous_grant_id.to_string() == PRIOR_GRANT
&& m.provider_sha256 == OLD_PROVIDER
&& m.runtime_sha256 == OLD_RUNTIME
&& m.resolved_apt_transaction.operation == Some(AptTransactionOperation::ConfigureOnly)
&& m.action == "apt-native-acceptance"
&& m.execution_profile == "dev-test",
"APT_CONFIGURED_FIXED_HISTORICAL_ACTION"
);
let ledger = format!("apt-{}-{}", permit.grant_id, row.rowid);
ensure!(
old.exit_code == Some(0)
&& old.stdout.is_empty()
&& old.stderr.is_empty()
&& !old.output_truncated
&& !old.reboot_required
&& old.evidence["postconditions_passed"] == false
&& old.evidence["test_acceptance"] == true
&& old.evidence["noProductionEvidence"] == true
&& old.evidence["effect_armed_ledger_id"] == ledger,
"APT_CONFIGURED_EXPECTED_UNKNOWN"
);
Ok(Some(Candidate {
request: start.request.clone(),
permit: permit.clone(),
manifest: m.clone(),
probe: ProbeRequest {
transaction_sha256: m.transaction_sha256.clone(),
job_payload_sha256: hash(&start.request.job_bytes),
effect_armed_ledger_id: ledger,
grant_id: permit.grant_id,
job_id: job.job_id,
attempt_id: job.attempt_id,
authorization_id: permit.authorization_id,
plan_sha256: permit.plan_hash.clone(),
},
original_boot_id: start.previous_boot_id,
original_outcome: row.outcome.clone(),
}))
}
fn names(reference: &AptNativeRecovery) -> Vec<String> {
ACTIVE_NAMES
.into_iter()
.map(str::to_owned)
.chain([
"bootstrap-attempt-rmm-apt-fixture-install-1.0.json".into(),
"bootstrap-retry-rmm-apt-fixture-install-1.0.json".into(),
format!("recovery-attempt-{}.json", reference.previous_grant_id),
])
.collect()
}
fn configure_protocol_sha256() -> String {
hash(&serde_json::to_vec(&json!([{"name":"rmm-mvp-test","old_version":"1.0","old_arch":"all","old_multiarch":"none",
"direction":"=","new_version":"1.0","new_arch":"all","new_multiarch":"none","action":"**CONFIGURE**"}])).expect("fixed protocol object"))
}
fn read_current(reference: &AptNativeRecovery) -> Result<BTreeMap<String, Vec<u8>>> {
let base = Path::new(BASE);
crate::private_path(base, 0, true)?;
crate::private_path(&base.join("active"), 0, true)?;
ensure!(
matches!(fs::symlink_metadata(base.join("active/host-reboot-before.json")),Err(e) if e.kind()==std::io::ErrorKind::NotFound),
"APT_CONFIGURED_HISTORICAL_BEFORE_MUST_BE_ABSENT"
);
for name in [
"acceptance-rmm-apt-fixture-install-1.0.json".into(),
"pending-acceptance-rmm-apt-fixture-install-1.0.json".into(),
format!("recovery-{}.json", reference.previous_grant_id),
format!("pending-recovery-{}.json", reference.previous_grant_id),
] {
ensure!(
matches!(fs::symlink_metadata(base.join(name)),Err(e) if e.kind()==std::io::ErrorKind::NotFound),
"APT_CONFIGURED_ACCEPTANCE_MUST_NOT_EXIST"
);
}
let mut files = BTreeMap::new();
for name in names(reference).into_iter().chain(["apt.conf".into()]) {
let root = if ACTIVE_NAMES.contains(&name.as_str()) || name == "apt.conf" {
base.join("active")
} else {
base.into()
};
files.insert(name.clone(), sealed(&root.join(name), 1024 * 1024)?);
}
Ok(files)
}
fn previous_files(reference: &AptNativeRecovery) -> Result<BTreeMap<String, Vec<u8>>> {
let root = Path::new(BASE)
.join("history")
.join(reference.previous_grant_id.to_string());
crate::private_path(&root, 0, true)?;
let mut files = BTreeMap::new();
for name in EVIDENCE_NAMES.into_iter().chain(["apt.conf"]) {
let path = if name.starts_with("bootstrap-") {
Path::new(BASE).join(name)
} else {
root.join(name)
};
files.insert(name.into(), sealed(&path, 1024 * 1024)?);
}
Ok(files)
}
fn current_evidence(
c: &Candidate,
prior: &ClosedPartial,
files: &BTreeMap<String, Vec<u8>>,
) -> Result<BTreeMap<String, PackageState>> {
let read = |name: &str| files.get(name).context("APT_CONFIGURED_EVIDENCE_MISSING");
let reference = c
.manifest
.native_recovery
.as_ref()
.context("APT_CONFIGURED_REFERENCE")?;
ensure!(
prior.reference == *reference
&& read("partial-proof.json")? == &prior.proof
&& hash(&prior.proof) == reference.partial_proof_sha256
&& prior.baseline_sha256 == c.manifest.resolved_apt_transaction.baseline_sha256
&& prior.status_fingerprint == c.manifest.resolved_apt_transaction.status_fingerprint
&& prior.previous_start_before <= c.permit.not_before
&& prior.job_id != c.probe.job_id
&& prior.authorization_id != c.probe.authorization_id
&& prior.plan_sha256 != c.probe.plan_sha256,
"APT_CONFIGURED_PRIOR_CLOSED_PROOF_BINDING"
);
ensure!(
read("signed-action.json")? == &c.request.job_bytes
&& read("expectation.json")? == &c.manifest.transaction_bytes
&& hash(read("baseline.json")?) == c.manifest.resolved_apt_transaction.baseline_sha256
&& hash(read("apt.conf")?) == c.manifest.apt_config_sha256,
"APT_CONFIGURED_HISTORICAL_FILE_HASH"
);
let context: ContextRecord = serde_json::from_slice(read("context.json")?)?;
ensure!(
context.schema_version == 2
&& context.action == "apt-native-acceptance"
&& context.execution_profile == "dev-test"
&& context.transaction_sha256 == c.probe.transaction_sha256
&& context.job_payload_sha256 == c.probe.job_payload_sha256
&& context.effect_armed_ledger_id == c.probe.effect_armed_ledger_id
&& context.grant_id == c.probe.grant_id
&& context.job_id == c.probe.job_id
&& context.attempt_id == c.probe.attempt_id
&& context.authorization_id == c.probe.authorization_id
&& context.plan_sha256 == c.probe.plan_sha256
&& context.boot_id == c.original_boot_id
&& context.not_before_ms == c.permit.not_before.timestamp_millis()
&& context.start_before_ms == c.permit.start_before.timestamp_millis()
&& context.monotonic_start_before_ns > 0,
"APT_CONFIGURED_ORIGINAL_CONTEXT"
);
let value = |name: &str| -> Result<Value> { Ok(serde_json::from_slice(read(name)?)?) };
ensure!(
value("launch.json")?
== json!({"transaction_sha256":c.probe.transaction_sha256,"effect_armed_ledger_id":c.probe.effect_armed_ledger_id})
&& value("sandbox-ready.json")?
== json!({"transaction_sha256":c.probe.transaction_sha256,"sandbox_version":1})
&& value("sandbox-result.json")?
== json!({"transaction_sha256":c.probe.transaction_sha256,"apt_exit_code":0,"reboot_required":false})
&& value("native-prechecks.json")? == native_prechecks(c),
"APT_CONFIGURED_NATIVE_CHILD_RESULT"
);
let hook = value("hook-armed.json")?;
ensure!(
hook["transaction_sha256"] == c.probe.transaction_sha256
&& hook["grant_id"] == c.probe.grant_id.to_string()
&& hook["effect_armed_ledger_id"] == c.probe.effect_armed_ledger_id
&& hook["protocol_sha256"] == configure_protocol_sha256()
&& hook["armed_at_ms"]
.as_i64()
.is_some_and(|t| t >= context.not_before_ms && t < context.start_before_ms),
"APT_CONFIGURED_ARMED_HOOK"
);
ensure!(
value(&format!(
"recovery-attempt-{}.json",
reference.previous_grant_id
))? == json!({
"transaction_sha256":c.probe.transaction_sha256,"job_payload_sha256":c.probe.job_payload_sha256,
"grant_id":c.probe.grant_id,"attempt_id":c.probe.attempt_id,"native_recovery":reference}),
"APT_CONFIGURED_ONCE_MARKER"
);
let baseline: BTreeMap<String, PackageState> = serde_json::from_slice(read("baseline.json")?)?;
ensure!(
baseline.get("rmm-mvp-test:all")
== Some(&PackageState {
version: "1.0".into(),
status: "install ok unpacked".into()
}),
"APT_CONFIGURED_ORIGINAL_UNPACKED_BASELINE"
);
Ok(baseline)
}
fn evidence_digest(c: &Candidate, files: &BTreeMap<String, Vec<u8>>) -> Result<String> {
let reference = c
.manifest
.native_recovery
.as_ref()
.context("APT_CONFIGURED_REFERENCE")?;
let hashes = names(reference)
.into_iter()
.map(|name| {
let digest = hash(
files
.get(&name)
.context("APT_CONFIGURED_EVIDENCE_MISSING")?,
);
Ok((name, digest))
})
.collect::<Result<BTreeMap<_, _>>>()?;
Ok(hash(&serde_json::to_vec(&hashes)?))
}
fn verify(
c: &Candidate,
prior: &ClosedPartial,
files: &BTreeMap<String, Vec<u8>>,
output: &Output,
now: DateTime<Utc>,
) -> Result<()> {
let mut expected = current_evidence(c, prior, files)?;
expected.insert(
"rmm-mvp-test:all".into(),
PackageState {
version: "1.0".into(),
status: "install ok installed".into(),
},
);
let p = &output.proof;
let actual = ProbeRequest {
transaction_sha256: p.transaction_sha256.clone(),
job_payload_sha256: p.job_payload_sha256.clone(),
effect_armed_ledger_id: p.effect_armed_ledger_id.clone(),
grant_id: p.grant_id,
job_id: p.job_id,
attempt_id: p.attempt_id,
authorization_id: p.authorization_id,
plan_sha256: p.plan_sha256.clone(),
};
ensure!(
output.effect_state == "known_failed"
&& output.code == CLASSIFIED
&& p.schema_version == 1
&& p.kind == "rmm.apt.configured-recovery-reconciliation"
&& actual == c.probe
&& p.effect_complete
&& !p.partial_effect
&& !p.postconditions_passed
&& p.reboot_required
&& p.host_reboot_required
&& digest(&p.host_reboot_marker_sha256)
&& p.original_evidence_sha256 == evidence_digest(c, files)?
&& p.partial_proof_sha256 == prior.reference.partial_proof_sha256
&& p.original_baseline_sha256 == c.manifest.resolved_apt_transaction.baseline_sha256
&& p.snapshot == expected
&& p.observed_snapshot_sha256
== hash(&serde_json::to_vec(&serde_json::to_value(&p.snapshot)?)?)
&& p.fixture_payload_sha256 == hash(b"1.0\n")
&& digest(&p.status_fingerprint)
&& p.checked_at_ms >= now.timestamp_millis() - 1000
&& p.checked_at_ms <= Utc::now().timestamp_millis() + 1000,
"APT_CONFIGURED_READONLY_PROOF_BINDING"
);
Ok(())
}
fn persist(db: &mut Connection, c: &Candidate, p: &Proof) -> Result<()> {
let proof = serde_json::to_vec(&serde_json::to_value(p)?)?;
let proof_sha = hash(&proof);
let outcome = Outcome {
state: "failed".into(),
stdout: vec![],
stderr: vec![],
exit_code: Some(0),
output_truncated: false,
reboot_required: true,
evidence: json!({"postconditions_passed":false,"effect_complete":true,"partial_effect":false,"reconciled_postconditions":true,
"effect_armed_ledger_id":c.probe.effect_armed_ledger_id,"test_acceptance":true,"noProductionEvidence":true,
"apt":{"test_acceptance":true,"noProductionEvidence":true,"effect_complete":true,"partial_effect":false,
"fixture_status":"install ok installed","fixture_version":"1.0","fixture_payload_sha256":p.fixture_payload_sha256,
"snapshot_sha256":p.observed_snapshot_sha256,"status_fingerprint":p.status_fingerprint,
"host_reboot_required":true,"host_reboot_marker_sha256":p.host_reboot_marker_sha256,
"host_reboot_required_before":null,"acceptance_reboot_baseline_missing":true,"reconciliation_proof_sha256":proof_sha}}),
error_code: CLASSIFIED.into(),
};
let classified = serde_json::to_vec(&outcome)?;
let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
// Lazy, append-only local evidence. Existing partial-proof rows are intact;
// ordinary open_ledger/probe never creates this table or changes history.
tx.execute_batch("CREATE TABLE IF NOT EXISTS apt_effect_reconciliations(grant_id TEXT PRIMARY KEY,
original_request_sha256 TEXT NOT NULL,previous_outcome_sha256 TEXT NOT NULL,previous_outcome BLOB NOT NULL,
proof_sha256 TEXT NOT NULL,proof BLOB NOT NULL,classified_outcome BLOB NOT NULL,checked_at_ms INTEGER NOT NULL);")?;
let current:(Option<Vec<u8>>,Option<Vec<u8>>)=tx.query_row("SELECT c.result,e.outcome FROM consumed c JOIN execution_evidence e USING(grant_id) WHERE grant_id=?1",
[c.probe.grant_id.to_string()],|r|Ok((r.get(0)?,r.get(1)?)))?;
ensure!(
current.0.is_none() && current.1.as_deref() == Some(c.original_outcome.as_slice()),
"APT_CONFIGURED_OUTCOME_CHANGED"
);
tx.execute(
"INSERT INTO apt_effect_reconciliations VALUES(?1,?2,?3,?4,?5,?6,?7,?8)",
params![
c.probe.grant_id.to_string(),
hash(&serde_json::to_vec(&c.request)?),
hash(&c.original_outcome),
c.original_outcome,
proof_sha,
proof,
classified,
p.checked_at_ms
],
)?;
ensure!(
tx.execute(
"UPDATE execution_evidence SET outcome=?2 WHERE grant_id=?1 AND outcome=?3",
params![c.probe.grant_id.to_string(), classified, c.original_outcome]
)? == 1,
"APT_CONFIGURED_OUTCOME_CHANGED"
);
// No consumed.result update. Only normal signed RootSync closes the lock.
tx.commit()?;
Ok(())
}
pub(super) fn refresh(
db: &mut Connection,
binding: &Binding,
row: &LedgerRow,
now: DateTime<Utc>,
) -> Result<bool> {
let Some(c) = eligible(binding, row)? else {
return Ok(false);
};
let reference = c
.manifest
.native_recovery
.as_ref()
.context("APT_CONFIGURED_REFERENCE")?;
let Ok(historical) = previous_files(reference) else {
return Ok(false);
};
let Ok(prior) = closed_partial_from(db, binding, Some(reference), || Ok(historical.clone()))
else {
return Ok(false);
};
let Ok(files) = read_current(reference) else {
return Ok(false);
};
if current_evidence(&c, &prior, &files).is_err() {
return Ok(false);
}
let Ok(raw) = probe_mode(&c, "verify-configured-recovery") else {
return Ok(false);
};
let Ok(output) = serde_json::from_slice::<Output>(&raw) else {
return Ok(false);
};
if verify(&c, &prior, &files, &output, now).is_err() {
return Ok(false);
}
// Re-read every sealed historical witness after the independent live probe.
if read_current(reference)? != files
|| previous_files(reference)? != historical
|| hash(&sealed(Path::new("/run/reboot-required"), 4096)?)
!= output.proof.host_reboot_marker_sha256
{
return Ok(false);
}
persist(db, &c, &output.proof)?;
Ok(true)
}
#[cfg(test)]
mod tests {
use super::*;
use openssl::{pkey::PKey, sign::Signer};
struct Fixture {
binding: Binding,
row: LedgerRow,
prior: ClosedPartial,
files: BTreeMap<String, Vec<u8>>,
now: DateTime<Utc>,
}
fn fixture() -> Fixture {
let now = Utc::now();
let key = PKey::generate_ed25519().unwrap();
let binding = 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: hex::encode(key.raw_public_key().unwrap()),
};
let baseline = json!({"base-files:amd64":{"version":"1","status":"install ok installed"},"rmm-mvp-test:all":{"version":"1.0","status":"install ok unpacked"}});
// A trusted prior object is supplied to this unit boundary. The
// independent closed_partial_from signature/history checks have their
// existing integration guards; this fixture does not assert native proof.
let proof = serde_json::to_vec(
&json!({"isolated_verified_prior_fixture":true,"snapshot":baseline}),
)
.unwrap();
let reference = AptNativeRecovery {
schema_version: 1,
previous_grant_id: PRIOR_GRANT.parse().unwrap(),
previous_attempt_id: Uuid::new_v4(),
partial_proof_sha256: hash(&proof),
};
let baseline_sha = hash(&serde_json::to_vec(&baseline).unwrap());
let tx = json!({"schema_version":2,"operation":"configure_only","recipe_id":apt::INSTALL_RECIPE,"recipe_version":"1","platform":"ubuntu-24.04-amd64",
"resolver_config_version":"rmm-apt-local-v1","no_reboot":true,"status_fingerprint":"a".repeat(64),"baseline_sha256":baseline_sha,
"packages":[{"name":"rmm-mvp-test","architecture":"all","old_version":"1.0","new_version":"1.0","origin":"rmm-test",
"sha256":"74036ae81223deab3aae994fd2a2a695af408741777e1ce17dcb4e32f1235867","size":20672,
"archive_path":"/var/lib/rmm-apt-transaction/archives/74036ae81223deab3aae994fd2a2a695af408741777e1ce17dcb4e32f1235867.deb"}]});
let txbytes = serde_json::to_vec(&tx).unwrap();
let manifest = json!({"type":"rmm.apt.helper-action","schema_version":4,"action":"apt-native-acceptance","execution_profile":"dev-test",
"transaction_sha256":hash(&txbytes),"transaction_bytes":txbytes,"resolved_apt_transaction":tx,"native_recovery":reference,
"provider_sha256":OLD_PROVIDER,"hook_sha256":"b".repeat(64),"runtime_sha256":OLD_RUNTIME,"apt_config_sha256":hash(b"historical config"),"test_result_id":"configured-fixture"});
let job:JobPayload=serde_json::from_value(json!({"schema_version":1,"tenant_id":binding.tenant_id,"agent_id":binding.agent_id,"asset_id":binding.asset_id,
"enrollment_generation":1,"assignment_version":1,"job_id":Uuid::new_v4(),"attempt_id":Uuid::new_v4(),"execution_identity":"root",
"not_before":now,"start_before":now+chrono::Duration::minutes(15),"max_runtime_seconds":300,"max_output_bytes":65536,
"action":{"action":"apt_native_acceptance","recipe_id":apt::INSTALL_RECIPE,"recipe_version":"1","apt_manifest":manifest}})).unwrap();
let permit = ExecutionPermitPayload {
domain: "rmm.execution-permit".into(),
schema_version: 1,
grant_id: TARGET_GRANT.parse().unwrap(),
authorization_id: Uuid::new_v4(),
tenant_id: job.tenant_id,
asset_id: job.asset_id,
agent_id: job.agent_id,
enrollment_generation: 1,
assignment_version: 1,
job_id: job.job_id,
attempt_id: job.attempt_id,
plan_hash: "c".repeat(64),
job_payload_hash: hash(&encode(&job).unwrap()),
action: "apt_native_acceptance".into(),
execution_identity: "root".into(),
not_before: now,
start_before: now + chrono::Duration::seconds(60),
max_runtime_seconds: 300,
key_id: hash(&key.raw_public_key().unwrap()),
};
let bytes = encode(&permit).unwrap();
let request = Request {
job_bytes: encode(&job).unwrap(),
permit_bytes: bytes.clone(),
signature: Signer::new_without_digest(&key)
.unwrap()
.sign_oneshot_to_vec(&bytes)
.unwrap(),
plan_hash: permit.plan_hash.clone(),
authorization_id: permit.authorization_id,
};
let boot = Uuid::new_v4();
let ledger = format!("apt-{}-11", permit.grant_id);
let old = Outcome {
exit_code: Some(0),
evidence: json!({"postconditions_passed":false,"test_acceptance":true,"noProductionEvidence":true,"effect_armed_ledger_id":ledger}),
..Outcome::unknown("FIXTURE_UNEXPECTED_REBOOT_REQUIRED")
};
let row=LedgerRow{rowid:11,grant:permit.grant_id.to_string(),agent:binding.agent_id.to_string(),generation:1,job:job.job_id.to_string(),attempt:job.attempt_id.to_string(),outcome:serde_json::to_vec(&old).unwrap(),
start:serde_json::to_vec(&json!({"previous_boot_id":boot,"reserved_at":now,"reconnect_deadline":null,"request":request,"reauthentication_required":true,"postconditions_passed":false})).unwrap()};
let prior = ClosedPartial {
reference,
proof,
job_id: Uuid::new_v4(),
authorization_id: Uuid::new_v4(),
plan_sha256: "d".repeat(64),
previous_start_before: now - chrono::Duration::seconds(1),
baseline_sha256: baseline_sha,
status_fingerprint: "a".repeat(64),
};
let c = eligible(&binding, &row).unwrap().unwrap();
let mut files = BTreeMap::from([
("signed-action.json".into(), c.request.job_bytes.clone()),
(
"expectation.json".into(),
c.manifest.transaction_bytes.clone(),
),
(
"baseline.json".into(),
serde_json::to_vec(&baseline).unwrap(),
),
("apt.conf".into(), b"historical config".to_vec()),
("partial-proof.json".into(), prior.proof.clone()),
(
"bootstrap-attempt-rmm-apt-fixture-install-1.0.json".into(),
b"retained install marker".to_vec(),
),
(
"bootstrap-retry-rmm-apt-fixture-install-1.0.json".into(),
b"retained retry marker".to_vec(),
),
]);
for (name, value) in [
(
"context.json".into(),
json!({"schema_version":2,"transaction_sha256":c.probe.transaction_sha256,"job_payload_sha256":c.probe.job_payload_sha256,"effect_armed_ledger_id":ledger,
"grant_id":permit.grant_id,"job_id":job.job_id,"attempt_id":job.attempt_id,"authorization_id":permit.authorization_id,"plan_sha256":permit.plan_hash,
"action":"apt-native-acceptance","execution_profile":"dev-test","not_before_ms":now.timestamp_millis(),"start_before_ms":permit.start_before.timestamp_millis(),"boot_id":boot,"monotonic_start_before_ns":1}),
),
(
"launch.json".into(),
json!({"transaction_sha256":c.probe.transaction_sha256,"effect_armed_ledger_id":ledger}),
),
(
"sandbox-ready.json".into(),
json!({"transaction_sha256":c.probe.transaction_sha256,"sandbox_version":1}),
),
(
"sandbox-result.json".into(),
json!({"transaction_sha256":c.probe.transaction_sha256,"apt_exit_code":0,"reboot_required":false}),
),
("native-prechecks.json".into(), native_prechecks(&c)),
(
"hook-armed.json".into(),
json!({"transaction_sha256":c.probe.transaction_sha256,"effect_armed_ledger_id":ledger,"grant_id":permit.grant_id,"protocol_sha256":configure_protocol_sha256(),"armed_at_ms":now.timestamp_millis()}),
),
(
format!("recovery-attempt-{PRIOR_GRANT}.json"),
json!({"transaction_sha256":c.probe.transaction_sha256,"job_payload_sha256":c.probe.job_payload_sha256,"grant_id":permit.grant_id,"attempt_id":permit.attempt_id,"native_recovery":prior.reference}),
),
] {
files.insert(name, serde_json::to_vec(&value).unwrap());
}
Fixture {
binding,
row,
prior,
files,
now,
}
}
fn output(f: &Fixture, c: &Candidate) -> Output {
let mut snapshot = current_evidence(c, &f.prior, &f.files).unwrap();
snapshot.get_mut("rmm-mvp-test:all").unwrap().status = "install ok installed".into();
Output {
effect_state: "known_failed".into(),
code: CLASSIFIED.into(),
proof: Proof {
schema_version: 1,
kind: "rmm.apt.configured-recovery-reconciliation".into(),
transaction_sha256: c.probe.transaction_sha256.clone(),
job_payload_sha256: c.probe.job_payload_sha256.clone(),
effect_armed_ledger_id: c.probe.effect_armed_ledger_id.clone(),
grant_id: c.probe.grant_id,
job_id: c.probe.job_id,
attempt_id: c.probe.attempt_id,
authorization_id: c.probe.authorization_id,
plan_sha256: c.probe.plan_sha256.clone(),
original_evidence_sha256: evidence_digest(c, &f.files).unwrap(),
partial_proof_sha256: f.prior.reference.partial_proof_sha256.clone(),
original_baseline_sha256: f.prior.baseline_sha256.clone(),
observed_snapshot_sha256: hash(
&serde_json::to_vec(&serde_json::to_value(&snapshot).unwrap()).unwrap(),
),
status_fingerprint: "e".repeat(64),
fixture_payload_sha256: hash(b"1.0\n"),
snapshot,
checked_at_ms: f.now.timestamp_millis(),
effect_complete: true,
partial_effect: false,
postconditions_passed: false,
reboot_required: true,
host_reboot_required: true,
host_reboot_marker_sha256: "f".repeat(64),
},
}
}
#[test]
fn configured_exact_signed_candidate_and_full_proof_do_not_invent_before_or_success() {
let f = fixture();
let c = eligible(&f.binding, &f.row).unwrap().unwrap();
let out = output(&f, &c);
verify(&c, &f.prior, &f.files, &out, f.now).unwrap();
for variant in 0..6 {
let mut changed = output(&f, &c);
match variant {
0 => changed.proof.postconditions_passed = true,
1 => changed.proof.reboot_required = false,
2 => changed.proof.partial_effect = true,
3 => {
changed
.proof
.snapshot
.get_mut("base-files:amd64")
.unwrap()
.version = "unrelated change".into()
}
4 => changed.proof.grant_id = Uuid::new_v4(),
_ => changed.proof.checked_at_ms -= 60000,
}
assert!(verify(&c, &f.prior, &f.files, &changed, f.now).is_err());
}
let mut row = f.row.clone();
row.grant = Uuid::new_v4().to_string();
assert!(eligible(&f.binding, &row).unwrap().is_none());
let mut tampered = f.files.clone();
let mut hook: Value = serde_json::from_slice(&tampered["hook-armed.json"]).unwrap();
hook["protocol_sha256"] = json!("0".repeat(64));
tampered.insert("hook-armed.json".into(), serde_json::to_vec(&hook).unwrap());
assert!(current_evidence(&c, &f.prior, &tampered).is_err());
}
#[test]
fn configured_append_preserves_original_unknown_and_consumed_lock_until_signed_sync() {
let f = fixture();
let c = eligible(&f.binding, &f.row).unwrap().unwrap();
let out = output(&f, &c);
let mut db = Connection::open_in_memory().unwrap();
db.execute_batch("CREATE TABLE consumed(grant_id TEXT PRIMARY KEY,result BLOB);CREATE TABLE execution_evidence(grant_id TEXT PRIMARY KEY,outcome BLOB);").unwrap();
db.execute(
"INSERT INTO consumed VALUES(?1,NULL)",
[&c.probe.grant_id.to_string()],
)
.unwrap();
db.execute(
"INSERT INTO execution_evidence VALUES(?1,?2)",
params![c.probe.grant_id.to_string(), c.original_outcome],
)
.unwrap();
persist(&mut db, &c, &out.proof).unwrap();
assert!(
db.query_row("SELECT result IS NULL FROM consumed", [], |r| r
.get::<_, bool>(0))
.unwrap()
);
assert_eq!(
db.query_row(
"SELECT previous_outcome FROM apt_effect_reconciliations",
[],
|r| r.get::<_, Vec<u8>>(0)
)
.unwrap(),
c.original_outcome
);
let classified: Vec<u8> = db
.query_row("SELECT outcome FROM execution_evidence", [], |r| r.get(0))
.unwrap();
let value: Outcome = serde_json::from_slice(&classified).unwrap();
assert_eq!(value.state, "failed");
assert_eq!(value.error_code, CLASSIFIED);
assert!(value.reboot_required);
assert_eq!(value.evidence["effect_complete"], true);
assert_eq!(value.evidence["postconditions_passed"], false);
assert_eq!(
value.evidence["apt"]["host_reboot_required_before"],
Value::Null
);
assert!(persist(&mut db, &c, &out.proof).is_err());
assert_eq!(
db.query_row("SELECT count(*) FROM apt_effect_reconciliations", [], |r| r
.get::<_, u64>(0))
.unwrap(),
1
);
}
}