//! Read-only current-version history verification under the actual retained //! executor guard. Every input file must already have been independently opened //! and authenticated by the local adapter. No request supplies trusted keys. //! //! This is admission-oriented verification: current release-key revocations //! apply. It must NOT gate an Unknown-only historical adjudication. A changed //! job-signing key needs an independently retained historical Binding; keys are //! never learned from a job. There is no clock, dispatch, repair or resume here. use anyhow::{Context, Result, ensure}; use chrono::{DateTime, Utc}; use ed25519_dalek::{Signature, VerifyingKey}; use rmm_agent_core::{ auth::{Binding, Outcome, Request}, helper_reconcile::ExecutorLedgerGuard, ledger, update_handoff::{self, NativeEffect, NativeEffectClaim}, }; use rmm_domain::{ agent_update::{self, Platform, ReleaseEnvelope, UpdateKeyringFile}, agent_update_provisioning::{ ActivationEvidence, BASELINE_SIGNATURE_DOMAIN, InstalledReleaseRecord, MAX_RECORD_BYTES, SignedBaselineRecord, }, jobs::{Action, hash}, }; use rmm_updater::{ ActiveRelease, Platform as ReleasePlatform, SignedRelease, TrustedContext, TrustedUpdateKey, UpdateKeyring, verify_release, }; use rmm_updater_handoff::{Event, Evidence, Handoff, HealthReceipt, Phase, SignedHealth}; use rusqlite::{Connection, OptionalExtension, params}; use std::collections::{BTreeMap, BTreeSet}; use uuid::Uuid; const MAX_RECORDS: usize = 64; const MAX_TOTAL_BYTES: usize = 2 * 1024 * 1024; /// `predecessor_records` is an unordered exact set of intermediate records. /// The signed initial record may optionally appear once. Missing, duplicate, /// unused/forked or completed-but-omitted records are denied. V1 rollback and /// historical job-key rotation without its trusted binding are unsupported. pub fn verify_history( db: &Connection, guard: &impl ExecutorLedgerGuard, binding: &Binding, protected_keyring: &UpdateKeyringFile, baseline: &SignedBaselineRecord, predecessor_records: &[Vec], active_raw: &[u8], ) -> Result { guard.check(db)?; ensure!(protected_keyring.validate(), "UPDATE_HISTORY_KEYRING"); let initial = baseline.decode().map_err(anyhow::Error::msg)?; ensure!( initial.record.platform == Platform::LinuxX64, "UPDATE_HISTORY_PLATFORM" ); let keyring = current_keyring(protected_keyring)?; let initial_release = initial .record .release_envelope .decode() .map_err(anyhow::Error::msg)?; let entry = protected_keyring .keys .iter() .find(|key| hex::decode(&key.public_key_hex).is_ok_and(|raw| hash(&raw) == baseline.key_id)) .context("UPDATE_HISTORY_BASELINE_KEY_MISSING")?; ensure!( !entry.revoked && entry.platform == initial.record.platform && (entry.first_sequence..=entry.last_sequence) .contains(&initial_release.manifest.release_sequence), "UPDATE_HISTORY_BASELINE_KEY_REVOKED_OR_RANGE" ); let public: [u8; 32] = hex::decode(&entry.public_key_hex)? .try_into() .map_err(|_| anyhow::anyhow!("UPDATE_HISTORY_KEY_SIZE"))?; let verifier = VerifyingKey::from_bytes(&public)?; ensure!(!verifier.is_weak(), "UPDATE_HISTORY_WEAK_BASELINE_KEY"); let mut signed = BASELINE_SIGNATURE_DOMAIN.to_vec(); signed.extend_from_slice(&initial.payload_bytes); verifier.verify_strict(&signed, &Signature::from_bytes(&initial.signature))?; verify_record_release(&keyring, protected_keyring.generation, &initial.record)?; ensure!( predecessor_records.len() < MAX_RECORDS && !active_raw.is_empty() && active_raw.len() <= MAX_RECORD_BYTES, "UPDATE_HISTORY_RECORD_LIMIT" ); let mut total = active_raw .len() .checked_add(initial.payload_bytes.len()) .context("UPDATE_HISTORY_SIZE")?; let active = InstalledReleaseRecord::from_bytes(active_raw).map_err(anyhow::Error::msg)?; let active_hash = hash(active_raw); let baseline_hash = hash(&initial.payload_bytes); let mut previous = BTreeMap::new(); for raw in predecessor_records { total = total .checked_add(raw.len()) .context("UPDATE_HISTORY_SIZE")?; ensure!( !raw.is_empty() && raw.len() <= MAX_RECORD_BYTES && total <= MAX_TOTAL_BYTES, "UPDATE_HISTORY_SIZE" ); let digest = hash(raw); ensure!( digest != active_hash && previous.insert(digest, raw.as_slice()).is_none(), "UPDATE_HISTORY_DUPLICATE" ); } ensure!(total <= MAX_TOTAL_BYTES, "UPDATE_HISTORY_SIZE"); let mut chain = vec![(active_hash, active_raw, active.clone())]; while chain.last().context("UPDATE_HISTORY_EMPTY")?.0 != baseline_hash { ensure!(chain.len() < MAX_RECORDS, "UPDATE_HISTORY_DEPTH"); let current = &chain.last().context("UPDATE_HISTORY_EMPTY")?.2; let digest = current .previous_record_sha256 .as_ref() .context("UPDATE_HISTORY_PARENT_MISSING")?; let raw = if *digest == baseline_hash { if let Some(copy) = previous.remove(digest) { ensure!( copy == initial.payload_bytes, "UPDATE_HISTORY_BASELINE_CHANGED" ); } initial.payload_bytes.as_slice() } else { previous .remove(digest) .context("UPDATE_HISTORY_PARENT_MISSING")? }; ensure!( !chain.iter().any(|(seen, _, _)| seen == digest), "UPDATE_HISTORY_CYCLE" ); let record = InstalledReleaseRecord::from_bytes(raw).map_err(anyhow::Error::msg)?; chain.push((digest.clone(), raw, record)); } ensure!( previous.is_empty() && chain.last().context("UPDATE_HISTORY_EMPTY")?.1 == initial.payload_bytes, "UPDATE_HISTORY_UNUSED_OR_WRONG_ANCHOR" ); let mut grants = BTreeSet::new(); for pair in chain.windows(2) { let (digest, raw, record) = &pair[0]; let (parent_digest, _, parent) = &pair[1]; ensure!( !record.rolled_back && record.platform == parent.platform && record.activation_floor > parent.activation_floor && record.activated_at >= parent.activated_at, "UPDATE_HISTORY_FLOOR_OR_ROLLBACK" ); verify_record_release(&keyring, protected_keyring.generation, record)?; let grant = verify_update(db, guard, binding, raw, record, parent_digest, parent)?; ensure!(grants.insert(grant), "UPDATE_HISTORY_REUSED_GRANT"); ensure!(*digest == hash(raw), "UPDATE_HISTORY_RECORD_CHANGED"); } // Detect a record-file-only rollback/fork: every completed publication in // this same device ledger must be present in the verified chain. ensure!( completed_update_grants(db, binding)? == grants, "UPDATE_HISTORY_OMITTED_CONSUMPTION" ); let exists: bool = db.query_row("SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name='agent_update_handoffs')", [], |r| r.get(0))?; if exists { let mut query = db.prepare("SELECT h.grant_id,c.claim FROM agent_update_handoffs h LEFT JOIN agent_update_native_claims c ON c.grant_id=h.grant_id AND c.effect_key='publish_installed_record' WHERE h.phase='outcome_persisted' ORDER BY h.grant_id LIMIT 65")?; let mut rows = query.query([])?; let mut seen = BTreeSet::new(); while let Some(row) = rows.next()? { let grant: String = row.get(0)?; let raw: Option> = row.get(1)?; let raw = raw.context("UPDATE_HISTORY_PUBLICATION_MISSING")?; ensure!( raw.len() <= 2048 && seen.len() < MAX_RECORDS, "UPDATE_HISTORY_PUBLICATION_LIMIT" ); let claim: NativeEffectClaim = serde_json::from_slice(&raw)?; let grant = Uuid::parse_str(&grant)?; ensure!( claim.grant_id() == grant && grants.contains(&grant) && seen.insert(grant), "UPDATE_HISTORY_OMITTED_PUBLICATION" ); } ensure!(seen == grants, "UPDATE_HISTORY_MISSING_PUBLICATION"); } else { ensure!(grants.is_empty(), "UPDATE_HISTORY_MISSING_LEDGER"); } guard.check(db)?; Ok(active) } fn current_keyring(file: &UpdateKeyringFile) -> Result { let mut keys = Vec::new(); for key in &file.keys { let public: [u8; 32] = hex::decode(&key.public_key_hex)? .try_into() .map_err(|_| anyhow::anyhow!("UPDATE_HISTORY_KEY_SIZE"))?; keys.push(TrustedUpdateKey::new( public, match key.platform { Platform::LinuxX64 => ReleasePlatform::LinuxX64, Platform::WindowsX64 => ReleasePlatform::WindowsX64, }, key.first_sequence, key.last_sequence, key.revoked, )?); } UpdateKeyring::new(file.generation, keys) } /// The authoritative completed set starts at ORIGINAL consumptions, not at an /// optional successor proof row. Stream a bounded local history, including old /// non-update jobs, without exposing any request/script bytes outside here. fn completed_update_grants(db: &Connection, binding: &Binding) -> Result> { let mut query=db.prepare("SELECT c.grant_id,e.start,e.outcome,c.result FROM consumed c LEFT JOIN execution_evidence e USING(grant_id) WHERE c.result IS NOT NULL OR e.outcome IS NOT NULL ORDER BY c.grant_id LIMIT 4097")?; let mut rows = query.query([])?; let mut count = 0; let mut bytes = 0usize; let mut grants = BTreeSet::new(); while let Some(row) = rows.next()? { count += 1; ensure!(count <= 4096, "UPDATE_HISTORY_CONSUMPTION_LIMIT"); let grant: String = row.get(0)?; let start: Option> = row.get(1)?; let outcome: Option> = row.get(2)?; let finished: Option> = row.get(3)?; for raw in [&start, &outcome, &finished].into_iter().flatten() { bytes = bytes .checked_add(raw.len()) .context("UPDATE_HISTORY_CONSUMPTION_SIZE")?; ensure!( raw.len() <= 512 * 1024 && bytes <= 16 * 1024 * 1024, "UPDATE_HISTORY_CONSUMPTION_SIZE" ); } let raw = outcome .as_ref() .or(finished.as_ref()) .context("UPDATE_HISTORY_COMPLETION_MISSING")?; if let (Some(a), Some(b)) = (&outcome, &finished) { let a: rmm_domain::reconciliation::ReconciledOutcome = serde_json::from_slice(a)?; let b: rmm_domain::reconciliation::ReconciledOutcome = serde_json::from_slice(b)?; ensure!( rmm_domain::reconciliation::canonical_outcome_bytes(&a)? == rmm_domain::reconciliation::canonical_outcome_bytes(&b)?, "UPDATE_HISTORY_COMPLETION_CHANGED" ); } let value: Outcome = serde_json::from_slice(raw)?; if value.state != "succeeded" { continue; } let start = start.context("UPDATE_HISTORY_START_MISSING")?; let start: serde_json::Value = serde_json::from_slice(&start)?; let request: Request = serde_json::from_value(start["request"].clone())?; let reserved_at: DateTime = serde_json::from_value(start["reserved_at"].clone())?; let (job, permit) = binding.verify(&request, reserved_at)?; ensure!( permit.grant_id.to_string() == grant, "UPDATE_HISTORY_CONSUMPTION_CHANGED" ); if matches!(job.action, Action::UpdateAgent { .. }) { ensure!( grants.len() < MAX_RECORDS && grants.insert(permit.grant_id), "UPDATE_HISTORY_COMPLETION_LIMIT" ); } } Ok(grants) } fn verify_record_release( keys: &UpdateKeyring, generation: u64, record: &InstalledReleaseRecord, ) -> Result<()> { ensure!( !record.rolled_back, "UPDATE_HISTORY_V1_ROLLBACK_UNSUPPORTED" ); let decoded = record .release_envelope .decode() .map_err(anyhow::Error::msg)?; let platform = match record.platform { Platform::LinuxX64 => ReleasePlatform::LinuxX64, Platform::WindowsX64 => ReleasePlatform::WindowsX64, }; let envelope: &ReleaseEnvelope = &record.release_envelope; verify_release( SignedRelease { schema_version: envelope.schema_version, key_id: &envelope.key_id, payload_bytes: &decoded.payload_bytes, signature: &decoded.signature, }, keys, &TrustedContext { platform, now_utc_seconds: record.activated_at, keyring_generation: generation, protocol_major: decoded.manifest.protocol_major, state_schema: decoded.manifest.state_schema, updater_version: 1, minimum_release_sequence: record.activation_floor, active_release: Some(ActiveRelease { sequence: decoded.manifest.release_sequence, manifest_sha256: record.manifest_sha256.clone(), }), }, )?; Ok(()) } fn verify_update( db: &Connection, guard: &impl ExecutorLedgerGuard, binding: &Binding, raw_record: &[u8], record: &InstalledReleaseRecord, parent_hash: &str, parent: &InstalledReleaseRecord, ) -> Result { let ActivationEvidence::Updated { handoff_sha256, signed_health_sha256, } = &record.activation_evidence else { anyhow::bail!("UPDATE_HISTORY_BOOTSTRAP_FORK"); }; let mut query = db.prepare("SELECT h.grant_id,h.record,e.start,e.outcome,c.result FROM agent_update_handoffs h JOIN execution_evidence e USING(grant_id) JOIN consumed c USING(grant_id) WHERE h.record_sha256=?1 LIMIT 2")?; let values = query .query_map([handoff_sha256], |r| { Ok(( r.get::<_, String>(0)?, r.get::<_, Vec>(1)?, r.get::<_, Vec>(2)?, r.get::<_, Option>>(3)?, r.get::<_, Option>>(4)?, )) })? .collect::>>()?; ensure!( values.len() == 1, "UPDATE_HISTORY_ORIGINAL_MISSING_OR_DUPLICATE" ); let (grant, raw_handoff, start, outcome, finished) = &values[0]; ensure!( raw_handoff.len() <= rmm_updater_handoff::MAX_RECORD_BYTES && start.len() <= 512 * 1024, "UPDATE_HISTORY_ORIGINAL_LIMIT" ); let grant = Uuid::parse_str(grant)?; let header: Handoff = serde_json::from_slice(raw_handoff)?; ensure!( header.bytes()? == *raw_handoff && hash(raw_handoff) == *handoff_sha256 && header.attempt.grant_id == grant && header.predecessor_record_sha256 == parent_hash, "UPDATE_HISTORY_ORIGINAL_BINDING" ); let start_value: serde_json::Value = serde_json::from_slice(start)?; let reserved_at: DateTime = serde_json::from_value(start_value["reserved_at"].clone())?; let request: Request = serde_json::from_value(start_value["request"].clone())?; // Historical identity/signature/window verification only. Never a live // execution verifier or a replacement start grant. let (job, permit) = binding.verify(&request, reserved_at)?; let Action::UpdateAgent { update } = &job.action else { anyhow::bail!("UPDATE_HISTORY_JOB_ACTION"); }; let previous = parent .release_envelope .decode() .map_err(anyhow::Error::msg)?; ensure!( job.execution_identity == "root" && update.release_envelope == record.release_envelope && agent_update::handoff_matches_job(&header, &job) && header.attempt.grant_id == permit.grant_id && header.attempt.job_payload_sha256 == permit.job_payload_hash && header.attempt.plan_id == permit.agent_update_plan_id.context("UPDATE_HISTORY_PLAN")? && header.attempt.authorization_id == permit.authorization_id && header.attempt.plan_sha256 == permit.plan_hash && header.attempt.original_start_witness_sha256 == hash(start) && header.attempt.original_request_sha256 == hash(&serde_json::to_vec(&request)?) && header.consumed_at == u64::try_from(reserved_at.timestamp())? && header.finish_before == header .consumed_at .checked_add(600) .context("UPDATE_HISTORY_DEADLINE")? && ledger::start_witness_bytes(&permit, &request, header.boot_id, reserved_at)? == *start && update.predecessor.installed_record_sha256 == parent_hash && update.predecessor.manifest_sha256 == parent.manifest_sha256 && update.predecessor.release_id == previous.manifest.release_id && update.predecessor.release_sequence == previous.manifest.release_sequence && header.predecessor.manifest_sha256 == parent.manifest_sha256 && header.predecessor.agent_sha256 == previous.manifest.artifacts[0].sha256 && header.predecessor.helper_sha256 == previous.manifest.artifacts[1].sha256 && header.target.manifest_sha256 == record.manifest_sha256, "UPDATE_HISTORY_SIGNED_ORIGINAL_CHANGED" ); let (count,size):(u64,u64)=db.query_row("SELECT count(*),COALESCE(sum(length(event)),0) FROM (SELECT event FROM agent_update_handoff_events WHERE grant_id=?1 ORDER BY sequence LIMIT 17)", [grant.to_string()], |r|Ok((r.get(0)?,r.get(1)?)))?; ensure!( count <= 16 && size <= 16 * 16384, "UPDATE_HISTORY_EVENT_LIMIT" ); let journal = update_handoff::read(db, guard, grant)?; ensure!( journal.phase() == Phase::OutcomePersisted, "UPDATE_HISTORY_INCOMPLETE_OR_UNKNOWN" ); let (helper, agent): (String, Option) = db.query_row( "SELECT journal_id,agent_journal_id FROM helper_sync_meta WHERE id=1", [], |r| Ok((r.get(0)?, r.get(1)?)), )?; ensure!( helper == header.helper_journal_id.to_string() && agent.as_deref() == Some(header.agent_journal_id.to_string().as_str()), "UPDATE_HISTORY_LEDGER_LINEAGE" ); let mut events = db.prepare( "SELECT event FROM agent_update_handoff_events WHERE grant_id=?1 ORDER BY sequence", )?; let events = events .query_map([grant.to_string()], |r| r.get::<_, Vec>(0))? .collect::>>()?; complete_native_history(db, &header, &events, parent_hash, &hash(raw_record))?; let mut health: Option<(SignedHealth, u64)> = None; let mut final_at = None; for raw in &events { let event: Event = serde_json::from_slice(raw)?; match event.evidence { Evidence::HealthVerified { receipt } => { ensure!(health.is_none(), "UPDATE_HISTORY_DOUBLE_HEALTH"); health = Some((receipt, event.observed_at)); } Evidence::OutcomePersisted { outcome_sha256 } => { let original = outcome.as_ref().context("UPDATE_HISTORY_OUTCOME_MISSING")?; ensure!( original.len() <= 512 * 1024 && hash(original) == outcome_sha256, "UPDATE_HISTORY_OUTCOME_CHANGED" ); let value: Outcome = serde_json::from_slice(original)?; ensure!( value.state == "succeeded" && !value.reboot_required && finished.as_ref().is_none_or(|v| v == original), "UPDATE_HISTORY_OUTCOME_NOT_SUCCESS" ); final_at = Some(event.observed_at); } _ => {} } } let (health, verified_at) = health.context("UPDATE_HISTORY_HEALTH_MISSING")?; let receipt: HealthReceipt = serde_json::from_slice(&health.payload)?; ensure!( hash(&serde_json::to_vec(&health)?) == *signed_health_sha256 && record.activated_at == receipt.issued_at && final_at.context("UPDATE_HISTORY_FINAL_MISSING")? >= verified_at, "UPDATE_HISTORY_HEALTH_OR_ACTIVATION_CHANGED" ); // Journal replay already independently verified the health signature with // the public key bound by this ORIGINAL signed job and checked its deadline. let record_hash = hash(raw_record); let saved = publication( db, grant, "save_installed_record", parent_hash, &record_hash, )?; let published = publication( db, grant, "publish_installed_record", parent_hash, &record_hash, )?; ensure!( saved.0.timestamp() >= i64::try_from(verified_at)? && published.0 >= saved.1 && published.1.timestamp() <= i64::try_from(final_at.context("UPDATE_HISTORY_FINAL_MISSING")?)?, "UPDATE_HISTORY_PUBLICATION_ORDER" ); guard.check(db)?; Ok(grant) } fn complete_native_history( db: &Connection, header: &Handoff, events: &[Vec], old: &str, new: &str, ) -> Result<()> { use rmm_agent_core::update_handoff::{NativeFileRole as F, NativeService as S}; let mut expected = BTreeSet::new(); for service in [S::Agent, S::General, S::Full] { expected.insert(serde_json::to_string(&NativeEffect::StopService { service, })?); expected.insert(serde_json::to_string(&NativeEffect::StartService { service, })?); } for role in [F::AgentBinary, F::HelperBinary, F::FullConfig, F::FullPin] { expected.insert(serde_json::to_string(&NativeEffect::SavePredecessor { role, })?); expected.insert(serde_json::to_string(&NativeEffect::PublishReplacement { role, })?); } expected.insert(serde_json::to_string(&NativeEffect::ReturnLedger)?); expected.insert("save_installed_record".into()); expected.insert("publish_installed_record".into()); let parsed = events .iter() .map(|raw| Ok((hash(raw), serde_json::from_slice::(raw)?))) .collect::>>()?; let time = |predicate: &dyn Fn(&Evidence) -> bool| -> Result { let entries = parsed .values() .filter(|event| predicate(&event.evidence)) .collect::>(); ensure!(entries.len() == 1, "UPDATE_HISTORY_NATIVE_PHASE_MISSING"); Ok(entries[0].observed_at) }; let grant = header.attempt.grant_id.to_string(); let mut query=db.prepare("SELECT c.effect_key,c.claim,c.claim_sha256,o.claim_sha256,o.observation_sha256,o.observed_at FROM agent_update_native_claims c LEFT JOIN agent_update_native_observations o USING(grant_id,effect_key) WHERE c.grant_id=?1 ORDER BY c.effect_key LIMIT 18")?; let mut rows = query.query([grant])?; let mut seen = BTreeSet::new(); let mut return_group: Option<(String, DateTime)> = None; while let Some(row) = rows.next()? { let key: String = row.get(0)?; let raw: Vec = row.get(1)?; let digest: String = row.get(2)?; ensure!( seen.len() < 17 && raw.len() <= 2048 && hash(&raw) == digest && expected.contains(&key) && seen.insert(key.clone()), "UPDATE_HISTORY_NATIVE_SET" ); let claim: NativeEffectClaim = serde_json::from_slice(&raw)?; let expected_key = match claim.effect() { NativeEffect::SaveInstalledRecord { old_sha256, new_sha256, } => { ensure!( old_sha256 == old && new_sha256 == new, "UPDATE_HISTORY_RECORD_PAIR" ); "save_installed_record".into() } NativeEffect::PublishInstalledRecord { old_sha256, new_sha256, } => { ensure!( old_sha256 == old && new_sha256 == new, "UPDATE_HISTORY_RECORD_PAIR" ); "publish_installed_record".into() } effect => serde_json::to_string(effect)?, }; let head = parsed .get(claim.head_sha256()) .context("UPDATE_HISTORY_NATIVE_HEAD_MISSING")?; let expected_head = match claim.effect() { NativeEffect::StopService { .. } => matches!(head.evidence, Evidence::StopIntent), NativeEffect::StartService { .. } | NativeEffect::ReturnLedger => { matches!(head.evidence, Evidence::LedgerReturnIntent) } NativeEffect::SaveInstalledRecord { .. } | NativeEffect::PublishInstalledRecord { .. } => { matches!(head.evidence, Evidence::HealthVerified { .. }) } NativeEffect::SavePredecessor { role } | NativeEffect::PublishReplacement { role } => { let expected = match role { F::AgentBinary => rmm_updater_handoff::FileRole::AgentBinary, F::HelperBinary => rmm_updater_handoff::FileRole::HelperBinary, F::FullConfig => rmm_updater_handoff::FileRole::LinuxFullConfig, F::FullPin => rmm_updater_handoff::FileRole::LinuxFullPin, }; matches!(head.evidence,Evidence::ReplaceIntent{role} if role==expected) } _ => false, }; ensure!( key == expected_key && expected_head && serde_json::to_vec(&claim)? == raw && claim.grant_id() == header.attempt.grant_id && claim.owner_nonce() == header.owner_nonce && u64::try_from(claim.claimed_at().timestamp())? >= head.observed_at && u64::try_from(claim.claimed_at().timestamp())? >= header.consumed_at && u64::try_from(claim.claimed_at().timestamp())? < header.finish_before, "UPDATE_HISTORY_NATIVE_CLAIM_CHANGED" ); if matches!( claim.effect(), NativeEffect::ReturnLedger | NativeEffect::StartService { .. } ) { let group = (claim.head_sha256().to_owned(), claim.claimed_at()); ensure!( u64::try_from(group.1.timestamp())? == head.observed_at && return_group.as_ref().is_none_or(|prior| prior == &group), "UPDATE_HISTORY_RETURN_STARTS_NOT_ATOMIC" ); return_group = Some(group); } let observed: Option = row.get(3)?; let observation: Option = row.get(4)?; let when: Option = row.get(5)?; if matches!(claim.effect(), NativeEffect::ReturnLedger) { ensure!( observed.is_none() && observation.is_none() && when.is_none(), "UPDATE_HISTORY_FALSE_RETURN_OBSERVATION" ); } else { ensure!( observed.as_ref() == Some(&digest) && observation .as_ref() .is_some_and(|v| agent_update::digest(v)), "UPDATE_HISTORY_NATIVE_OBSERVATION" ); let when: DateTime = when.context("UPDATE_HISTORY_NATIVE_OBSERVATION")?.parse()?; ensure!( when >= claim.claimed_at() && u64::try_from(when.timestamp())? < header.finish_before, "UPDATE_HISTORY_NATIVE_OBSERVATION_TIME" ); let end = match claim.effect() { NativeEffect::StopService { .. } => { time(&|e| matches!(e, Evidence::AllStopped { .. }))? } NativeEffect::StartService { .. } => { time(&|e| matches!(e, Evidence::ServicesStarted { .. }))? } NativeEffect::SaveInstalledRecord { .. } | NativeEffect::PublishInstalledRecord { .. } => { time(&|e| matches!(e, Evidence::OutcomePersisted { .. }))? } NativeEffect::SavePredecessor { role } | NativeEffect::PublishReplacement { role } => { let expected = match role { F::AgentBinary => rmm_updater_handoff::FileRole::AgentBinary, F::HelperBinary => rmm_updater_handoff::FileRole::HelperBinary, F::FullConfig => rmm_updater_handoff::FileRole::LinuxFullConfig, F::FullPin => rmm_updater_handoff::FileRole::LinuxFullPin, }; time(&|e| matches!(e,Evidence::Replaced{role,..} if *role==expected))? } _ => anyhow::bail!("UPDATE_HISTORY_NATIVE_PHASE"), }; ensure!( u64::try_from(when.timestamp())? <= end, "UPDATE_HISTORY_NATIVE_LATE_OBSERVATION" ); if let NativeEffect::PublishReplacement { role } = claim.effect() { let save = serde_json::to_string(&NativeEffect::SavePredecessor { role: *role })?; let saved:String=db.query_row("SELECT observed_at FROM agent_update_native_observations WHERE grant_id=?1 AND effect_key=?2",params![header.attempt.grant_id.to_string(),save],|r|r.get(0))?; let saved: DateTime = saved.parse()?; ensure!( saved <= claim.claimed_at(), "UPDATE_HISTORY_NATIVE_PUBLISH_BEFORE_SAVE" ); } } } ensure!(seen == expected, "UPDATE_HISTORY_NATIVE_HISTORY_MISSING"); Ok(()) } fn publication( db: &Connection, grant: Uuid, effect: &str, old: &str, new: &str, ) -> Result<(DateTime, DateTime)> { let value: Option<(Vec,String,String,String)> = db.query_row( "SELECT c.claim,c.claim_sha256,o.claim_sha256,o.observed_at FROM agent_update_native_claims c JOIN agent_update_native_observations o USING(grant_id,effect_key) WHERE c.grant_id=?1 AND c.effect_key=?2", params![grant.to_string(),effect], |r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?))).optional()?; let (raw, digest, observed, at) = value.context("UPDATE_HISTORY_PUBLICATION_MISSING")?; ensure!( raw.len() <= 2048 && hash(&raw) == digest && digest == observed, "UPDATE_HISTORY_PUBLICATION_CHANGED" ); let claim: NativeEffectClaim = serde_json::from_slice(&raw)?; let expected = if effect == "save_installed_record" { NativeEffect::SaveInstalledRecord { old_sha256: old.into(), new_sha256: new.into(), } } else { NativeEffect::PublishInstalledRecord { old_sha256: old.into(), new_sha256: new.into(), } }; let observed: DateTime = at.parse()?; ensure!( serde_json::to_vec(&claim)? == raw && claim.grant_id() == grant && claim.effect() == &expected && observed >= claim.claimed_at(), "UPDATE_HISTORY_PUBLICATION_PAIR" ); Ok((claim.claimed_at(), observed)) } #[cfg(test)] mod tests { // Historical in-memory bytes only: no service, filesystem, real operation, // current authority or simulated WebUI approval is created by this fixture. use super::*; use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; use ed25519_dalek::{Signer, SigningKey}; use rmm_domain::{ agent_update::*, jobs::{ExecutionPermitPayload, JobPayload}, }; use rmm_updater_handoff::*; use serde_json::json; struct MemoryGuard(usize); impl ExecutorLedgerGuard for MemoryGuard { fn check(&self, db: &Connection) -> Result<()> { ensure!( unsafe { db.handle() } as usize == self.0, "fixture connection" ); Ok(()) } } fn at(seconds: i64) -> DateTime { DateTime::from_timestamp(seconds, 0).unwrap() } fn digest(n: u8) -> String { format!("{n:02x}").repeat(32) } fn envelope(mut manifest: ReleaseManifest, sequence: u64, key: &SigningKey) -> ReleaseEnvelope { manifest.release_sequence = sequence; manifest.published_at = 90; manifest.expires_at = 2000; let payload = serde_json::to_vec(&manifest).unwrap(); let mut signed = rmm_updater::RELEASE_SIGNATURE_DOMAIN.to_vec(); signed.extend_from_slice(&payload); ReleaseEnvelope { schema_version: 1, key_id: hash(key.verifying_key().as_bytes()), payload_bytes: URL_SAFE_NO_PAD.encode(&payload), signature: URL_SAFE_NO_PAD.encode(key.sign(&signed).to_bytes()), } } fn append(journal: &mut Journal, events: &mut Vec>, at: u64, evidence: Evidence) { let raw = journal.prepare(at, evidence).unwrap(); journal.replay(&raw).unwrap(); events.push(raw); } struct Fixture { db: Connection, guard: MemoryGuard, binding: Binding, keys: UpdateKeyringFile, baseline: SignedBaselineRecord, initial: Vec, active: Vec, } fn fixture() -> Fixture { let release = SigningKey::from_bytes(&[71; 32]); // public synthetic TEST seed let jobs = SigningKey::from_bytes(&[72; 32]); let health = SigningKey::from_bytes(&[73; 32]); let golden: serde_json::Value = serde_json::from_str(include_str!( "../../../tests/agent_update/codec-golden.json" )) .unwrap(); let mut job: JobPayload = serde_json::from_value(golden["linux_full"]["payload"]["jobs"][0]["payload"].clone()) .unwrap(); job.not_before = at(100); job.start_before = at(700); let Action::UpdateAgent { update } = &mut job.action else { panic!("fixture action") }; let target = envelope(update.manifest().unwrap(), 2, &release); let mut old = target.decode().unwrap().manifest; old.release_id = update.predecessor.release_id; old.artifacts[0].artifact_id = Uuid::from_u128(901); old.artifacts[1].artifact_id = Uuid::from_u128(902); old.artifacts[0].sha256 = update.predecessor.agent_sha256.clone(); old.artifacts[1].sha256 = update.predecessor.helper_sha256.clone(); let old = envelope(old, 1, &release); let initial = InstalledReleaseRecord { schema_version: 1, profile: "decoder_compatible_handoff_v1".into(), platform: Platform::LinuxX64, manifest_sha256: hash(&old.decode().unwrap().payload_bytes), release_envelope: old, activation_floor: 1, activated_at: 95, previous_record_sha256: None, activation_evidence: ActivationEvidence::Bootstrap { qualification_receipt_sha256: digest(80), }, rolled_back: false, }; let initial = initial.bytes().unwrap(); let mut signed = BASELINE_SIGNATURE_DOMAIN.to_vec(); signed.extend_from_slice(&initial); let baseline = SignedBaselineRecord { schema_version: 1, key_id: hash(release.verifying_key().as_bytes()), payload_bytes: URL_SAFE_NO_PAD.encode(&initial), signature: URL_SAFE_NO_PAD.encode(release.sign(&signed).to_bytes()), }; let keys = UpdateKeyringFile { schema_version: 1, generation: 1, keys: vec![UpdateKeyringEntry { public_key_hex: hex::encode(release.verifying_key().as_bytes()), platform: Platform::LinuxX64, first_sequence: 1, last_sequence: 50, revoked: false, }], }; update.release_envelope = target; update.release_envelope_sha256 = update.release_envelope.sha256().unwrap(); update.manifest_sha256 = hash(&update.release_envelope.decode().unwrap().payload_bytes); update.predecessor.manifest_sha256 = InstalledReleaseRecord::from_bytes(&initial) .unwrap() .manifest_sha256; update.predecessor.installed_record_sha256 = hash(&initial); update.updater.health_public_key_hex = hex::encode(health.verifying_key().as_bytes()); update.updater.keyring_sha256 = hash(&serde_json::to_vec(&keys).unwrap()); if let PeerPinTransition::LinuxGeneralFullV1 { full, .. } = &mut update.peer_pin_transition { full.effective_signing_key_id = hash(jobs.verifying_key().as_bytes()); } assert!(update.validate()); let binding = Binding { tenant_id: job.tenant_id, asset_id: job.asset_id, agent_id: job.agent_id, enrollment_generation: job.enrollment_generation, assignment_version: job.assignment_version, public_key_hex: hex::encode(jobs.verifying_key().as_bytes()), }; let permit = ExecutionPermitPayload { domain: "rmm.execution-permit".into(), schema_version: 1, grant_id: Uuid::from_u128(101), tenant_id: job.tenant_id, asset_id: job.asset_id, agent_id: job.agent_id, enrollment_generation: job.enrollment_generation, assignment_version: job.assignment_version, job_id: job.job_id, attempt_id: job.attempt_id, authorization_id: Uuid::from_u128(102), plan_hash: digest(90), job_payload_hash: hash(&serde_json::to_vec(&job).unwrap()), action: "update_agent".into(), execution_identity: "root".into(), not_before: at(100), start_before: at(160), max_runtime_seconds: 600, key_id: hash(jobs.verifying_key().as_bytes()), agent_update_plan_id: Some(Uuid::from_u128(103)), }; let permit_raw = serde_json::to_vec(&permit).unwrap(); let request = Request { job_bytes: serde_json::to_vec(&job).unwrap(), signature: jobs.sign(&permit_raw).to_bytes().to_vec(), permit_bytes: permit_raw, plan_hash: permit.plan_hash.clone(), authorization_id: permit.authorization_id, }; binding.verify(&request, at(100)).unwrap(); let Action::UpdateAgent { update } = &job.action else { panic!("fixture") }; let PeerPinTransition::LinuxGeneralFullV1 { full, .. } = &update.peer_pin_transition else { panic!("fixture") }; let boot = Uuid::from_u128(104); let start = ledger::start_witness_bytes(&permit, &request, boot, at(100)).unwrap(); let header = Handoff { schema_version: 1, attempt: AttemptBinding { tenant_id: job.tenant_id, asset_id: job.asset_id, agent_id: job.agent_id, enrollment_generation: 1, assignment_version: 1, plan_id: permit.agent_update_plan_id.unwrap(), plan_sha256: permit.plan_hash.clone(), job_id: job.job_id, attempt_id: job.attempt_id, job_payload_sha256: permit.job_payload_hash.clone(), grant_id: permit.grant_id, authorization_id: permit.authorization_id, original_request_sha256: hash(&serde_json::to_vec(&request).unwrap()), original_start_witness_sha256: hash(&start), }, agent_journal_id: Uuid::from_u128(105), helper_journal_id: Uuid::from_u128(106), helper_checkpoint: 7, previous_decision_id: Uuid::from_u128(107), boot_id: boot, connection_generation: 1, owner_nonce: Uuid::from_u128(108), updater_sha256: update.updater.binary_sha256.clone(), updater_policy_sha256: update.updater.policy_sha256.clone(), predecessor_record_sha256: hash(&initial), retained_state_sha256: digest(91), ledger_identity_sha256: digest(92), staged_files_sha256: digest(93), predecessor: CodePair { manifest_sha256: update.predecessor.manifest_sha256.clone(), agent_sha256: update.predecessor.agent_sha256.clone(), helper_sha256: update.predecessor.helper_sha256.clone(), pin_sha256: full.old_pin_sha256.clone(), }, target: CodePair { manifest_sha256: update.manifest_sha256.clone(), agent_sha256: update.manifest().unwrap().artifacts[0].sha256.clone(), helper_sha256: full.new_helper_sha256.clone(), pin_sha256: full.new_pin_sha256.clone(), }, pin_transition: PinTransition::LinuxGeneralFullV1, pin_transition_sha256: hash(&serde_json::to_vec(&update.peer_pin_transition).unwrap()), files: vec![ FileTransition { role: FileRole::AgentBinary, old_sha256: update.predecessor.agent_sha256.clone(), new_sha256: update.manifest().unwrap().artifacts[0].sha256.clone(), }, FileTransition { role: FileRole::HelperBinary, old_sha256: full.old_helper_sha256.clone(), new_sha256: full.new_helper_sha256.clone(), }, FileTransition { role: FileRole::LinuxFullConfig, old_sha256: full.old_config_sha256.clone(), new_sha256: full.new_config_sha256.clone(), }, FileTransition { role: FileRole::LinuxFullPin, old_sha256: full.old_pin_sha256.clone(), new_sha256: full.new_pin_sha256.clone(), }, ], stop_set: vec![ Service::LinuxAgent, Service::LinuxGeneralHelper, Service::LinuxFullHelper, ], consumed_at: 100, finish_before: 700, }; assert!(agent_update::handoff_matches_job(&header, &job)); let raw_header = header.bytes().unwrap(); let mut journal = Journal::open(&raw_header, health.verifying_key().to_bytes()).unwrap(); let mut events = vec![]; append(&mut journal, &mut events, 100, Evidence::StopIntent); append( &mut journal, &mut events, 102, Evidence::AllStopped { observation_sha256: digest(94), }, ); append( &mut journal, &mut events, 103, Evidence::UpdaterOwnsLedger { process: Process { pid: 300, birth: 3000, image_sha256: header.updater_sha256.clone(), }, ledger_identity_sha256: header.ledger_identity_sha256.clone(), }, ); for file in &header.files { append( &mut journal, &mut events, 104, Evidence::ReplaceIntent { role: file.role }, ); append( &mut journal, &mut events, 104, Evidence::Replaced { role: file.role, observed_sha256: file.new_sha256.clone(), }, ); } append( &mut journal, &mut events, 105, Evidence::PairVerified { pair: header.target.clone(), retained_state_sha256: header.retained_state_sha256.clone(), }, ); append(&mut journal, &mut events, 106, Evidence::LedgerReturnIntent); let services = header .stop_set .iter() .enumerate() .map(|(i, s)| StartedService { service: *s, process: Process { pid: 400 + i as u32, birth: 4000 + i as u64, image_sha256: if *s == Service::LinuxAgent { header.target.agent_sha256.clone() } else { header.target.helper_sha256.clone() }, }, }) .collect::>(); append( &mut journal, &mut events, 107, Evidence::ServicesStarted { services: services.clone(), ledger_identity_sha256: header.ledger_identity_sha256.clone(), observation_sha256: digest(95), }, ); let receipt = HealthReceipt { schema_version: 1, handoff_sha256: hash(&raw_header), owner_nonce: header.owner_nonce, boot_id: boot, helper_journal_id: header.helper_journal_id, agent_journal_id: header.agent_journal_id, connection_generation: 2, service_processes: services, ledger_identity_sha256: header.ledger_identity_sha256.clone(), signed_sync_decision_id: Uuid::from_u128(109), signed_sync_request_sha256: digest(96), signed_sync_response_sha256: digest(97), signed_sync_applied_at: 108, ready: false, inventory_message_id: Uuid::from_u128(110), inventory_received_at: 108, inventory_ack_sha256: digest(98), issued_at: 109, valid_until: 200, }; let payload = serde_json::to_vec(&receipt).unwrap(); let mut signed = HEALTH_DOMAIN.to_vec(); signed.extend_from_slice(&payload); let receipt = SignedHealth { payload, signature: health.sign(&signed).to_bytes().to_vec(), }; append( &mut journal, &mut events, 110, Evidence::HealthVerified { receipt: receipt.clone(), }, ); let outcome = serde_json::to_vec(&Outcome { state: "succeeded".into(), stdout: vec![], stderr: vec![], exit_code: Some(0), output_truncated: false, reboot_required: false, evidence: json!({"test_only":true}), error_code: String::new(), }) .unwrap(); append( &mut journal, &mut events, 113, Evidence::OutcomePersisted { outcome_sha256: hash(&outcome), }, ); let active = InstalledReleaseRecord { schema_version: 1, profile: "decoder_compatible_handoff_v1".into(), platform: Platform::LinuxX64, release_envelope: update.release_envelope.clone(), manifest_sha256: update.manifest_sha256.clone(), activation_floor: 2, activated_at: 109, previous_record_sha256: Some(hash(&initial)), activation_evidence: ActivationEvidence::Updated { handoff_sha256: hash(&raw_header), signed_health_sha256: hash(&serde_json::to_vec(&receipt).unwrap()), }, rolled_back: false, } .bytes() .unwrap(); let db = Connection::open_in_memory().unwrap(); let guard = MemoryGuard(unsafe { db.handle() } as usize); ledger::initialize_ledger(&db).unwrap(); update_handoff::initialize(&db, &guard).unwrap(); db.execute( "INSERT INTO consumed VALUES(?1,?2,1,?3,?4,?5)", params![ permit.grant_id.to_string(), job.agent_id.to_string(), job.job_id.to_string(), job.attempt_id.to_string(), outcome ], ) .unwrap(); db.execute( "INSERT INTO execution_evidence VALUES(?1,?2,?3)", params![permit.grant_id.to_string(), start, outcome], ) .unwrap(); db.execute( "INSERT INTO agent_update_handoffs VALUES(?1,?2,?3,?4,?5,16,'outcome_persisted')", params![ permit.grant_id.to_string(), raw_header, hash(&raw_header), health.verifying_key().to_bytes().to_vec(), journal.head_sha256() ], ) .unwrap(); let participant = |role, pid, image: String| ParticipantIdentity { role, pid, birth: u64::from(pid) * 10, image_sha256: image, security_principal: "uid:0".into(), service_instance_sha256: digest(99), }; let delegation = UpdateDelegation { schema_version: 1, handoff_sha256: hash(&raw_header), owner_nonce: header.owner_nonce, boot_id: boot, prepared_at: at(100), updater: participant( ParticipantRole::LinuxUpdater, 300, header.updater_sha256.clone(), ), original_helper: participant( ParticipantRole::LinuxFullHelper, 301, header.predecessor.helper_sha256.clone(), ), }; let delegation = serde_json::to_vec(&delegation).unwrap(); db.execute( "INSERT INTO agent_update_delegations VALUES(?1,?2,?3)", params![permit.grant_id.to_string(), delegation, hash(&delegation)], ) .unwrap(); for (i, event) in events.iter().enumerate() { db.execute( "INSERT INTO agent_update_handoff_events VALUES(?1,?2,?3,?4)", params![permit.grant_id.to_string(), i + 1, event, hash(event)], ) .unwrap(); } for (name, effect, claimed, observed) in [ ( "save_installed_record", NativeEffect::SaveInstalledRecord { old_sha256: hash(&initial), new_sha256: hash(&active), }, 110, 111, ), ( "publish_installed_record", NativeEffect::PublishInstalledRecord { old_sha256: hash(&initial), new_sha256: hash(&active), }, 111, 112, ), ] { let claim: NativeEffectClaim = serde_json::from_value( json!({"grant_id":permit.grant_id,"owner_nonce":header.owner_nonce, "head_sha256":hash(&events[14]),"effect":effect,"claimed_at":at(claimed)}), ) .unwrap(); let raw = serde_json::to_vec(&claim).unwrap(); db.execute( "INSERT INTO agent_update_native_claims VALUES(?1,?2,?3,?4)", params![permit.grant_id.to_string(), name, raw, hash(&raw)], ) .unwrap(); db.execute( "INSERT INTO agent_update_native_observations VALUES(?1,?2,?3,?4,?5)", params![ permit.grant_id.to_string(), name, hash(&raw), digest(100), at(observed).to_rfc3339() ], ) .unwrap(); } use rmm_agent_core::update_handoff::{NativeFileRole as F, NativeService as S}; let mut native = vec![]; for service in [S::Agent, S::General, S::Full] { native.push((NativeEffect::StopService { service }, 0, 100, Some(102))); native.push((NativeEffect::StartService { service }, 12, 106, Some(107))); } for (i, role) in [F::AgentBinary, F::HelperBinary, F::FullConfig, F::FullPin] .into_iter() .enumerate() { native.push(( NativeEffect::SavePredecessor { role }, 3 + 2 * i, 104, Some(104), )); native.push(( NativeEffect::PublishReplacement { role }, 3 + 2 * i, 104, Some(104), )); } native.push((NativeEffect::ReturnLedger, 12, 106, None)); for (effect, head, claimed, observed) in native { let name = serde_json::to_string(&effect).unwrap(); let claim: NativeEffectClaim = serde_json::from_value( json!({"grant_id":permit.grant_id,"owner_nonce":header.owner_nonce, "head_sha256":hash(&events[head]),"effect":effect,"claimed_at":at(claimed)}), ) .unwrap(); let raw = serde_json::to_vec(&claim).unwrap(); db.execute( "INSERT INTO agent_update_native_claims VALUES(?1,?2,?3,?4)", params![permit.grant_id.to_string(), name, raw, hash(&raw)], ) .unwrap(); if let Some(observed) = observed { db.execute( "INSERT INTO agent_update_native_observations VALUES(?1,?2,?3,?4,?5)", params![ permit.grant_id.to_string(), name, hash(&raw), digest(100), at(observed).to_rfc3339() ], ) .unwrap(); } } db.execute_batch( "CREATE TABLE helper_sync_meta(id INTEGER,journal_id TEXT,agent_journal_id TEXT)", ) .unwrap(); db.execute( "INSERT INTO helper_sync_meta VALUES(1,?1,?2)", params![ header.helper_journal_id.to_string(), header.agent_journal_id.to_string() ], ) .unwrap(); Fixture { db, guard, binding, keys, baseline, initial, active, } } #[test] fn public_record_builder_binds_actual_original_key_and_exact_health_head() { let f = fixture(); let (grant, record, start):(String,Vec,Vec)=f.db.query_row( "SELECT h.grant_id,h.record,e.start FROM agent_update_handoffs h JOIN execution_evidence e USING(grant_id)", [],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?))).unwrap(); let grant: Uuid = grant.parse().unwrap(); let delegation = update_handoff::read_delegation(&f.db, grant).unwrap(); let original = crate::original::Original::verify_retained(&f.binding, &start, &record, delegation) .unwrap(); let key: [u8; 32] = hex::decode(&original.update().updater.health_public_key_hex) .unwrap() .try_into() .unwrap(); let mut journal = Journal::open(&record, key).unwrap(); let mut wrong_journal = Journal::open( &record, SigningKey::from_bytes(&[88; 32]).verifying_key().to_bytes(), ) .unwrap(); let mut statement = f.db.prepare("SELECT event FROM agent_update_handoff_events ORDER BY sequence") .unwrap(); let events = statement .query_map([], |r| r.get::<_, Vec>(0)) .unwrap() .collect::>>() .unwrap(); let mut health_raw = None; let mut wrong_health_raw = None; for raw in events { let event: Event = serde_json::from_slice(&raw).unwrap(); if let Evidence::HealthVerified { receipt } = &event.evidence { journal.replay(&raw).unwrap(); let mut wrong = receipt.clone(); let mut message = HEALTH_DOMAIN.to_vec(); message.extend_from_slice(&wrong.payload); wrong.signature = SigningKey::from_bytes(&[88; 32]) .sign(&message) .to_bytes() .to_vec(); let forged = wrong_journal .prepare( event.observed_at, Evidence::HealthVerified { receipt: wrong }, ) .unwrap(); wrong_journal.replay(&forged).unwrap(); wrong_health_raw = Some(forged); health_raw = Some(raw); break; } journal.replay(&raw).unwrap(); wrong_journal.replay(&raw).unwrap(); } let health_raw = health_raw.unwrap(); let built = crate::record::BuiltRecord::build(&original, &f.initial, &journal, &health_raw) .unwrap(); assert_eq!(built.raw(), f.active); assert_eq!(built.sha256(), hash(&f.active)); // A complete kernel Journal can be constructed with the wrong external // key. The public builder must independently enforce the ORIGINAL job. assert!( crate::record::BuiltRecord::build( &original, &f.initial, &wrong_journal, &wrong_health_raw.unwrap() ) .is_err() ); let mut changed: Event = serde_json::from_slice(&health_raw).unwrap(); changed.observed_at += 1; assert!( crate::record::BuiltRecord::build( &original, &f.initial, &journal, &serde_json::to_vec(&changed).unwrap() ) .is_err() ); assert!( crate::record::BuiltRecord::build(&original, &f.active, &journal, &health_raw).is_err() ); } #[test] fn completed_history_rejects_file_only_rollback_forks_and_tampered_activation_without_writes() { let f = fixture(); let before: u64 = f.db.query_row("SELECT total_changes()", [], |r| r.get(0)) .unwrap(); let result = verify_history( &f.db, &f.guard, &f.binding, &f.keys, &f.baseline, &[], &f.active, ) .unwrap(); assert_eq!(result.activation_floor, 2); assert!( verify_history( &f.db, &f.guard, &f.binding, &f.keys, &f.baseline, &[], &f.initial ) .is_err() ); let mut altered = InstalledReleaseRecord::from_bytes(&f.active).unwrap(); altered.activated_at += 1; let altered = altered.bytes().unwrap(); assert!( verify_history( &f.db, &f.guard, &f.binding, &f.keys, &f.baseline, &[], &altered ) .is_err() ); assert!( verify_history( &f.db, &f.guard, &f.binding, &f.keys, &f.baseline, &[altered], &f.active ) .is_err() ); let mut keys = f.keys.clone(); keys.keys[0].revoked = true; assert!( verify_history( &f.db, &f.guard, &f.binding, &keys, &f.baseline, &[], &f.active ) .is_err() ); let after: u64 = f.db.query_row("SELECT total_changes()", [], |r| r.get(0)) .unwrap(); assert_eq!(before, after); assert_eq!(f.active, result.bytes().unwrap()); // All byte/hash links still match, but this phase could never claim // the original Agent save. Membership in *some* event head is weaker. let corrupt = fixture(); let key = serde_json::to_string(&NativeEffect::SavePredecessor { role: rmm_agent_core::update_handoff::NativeFileRole::AgentBinary, }) .unwrap(); let raw: Vec = corrupt .db .query_row( "SELECT claim FROM agent_update_native_claims WHERE effect_key=?1", [&key], |r| r.get(0), ) .unwrap(); let outcome_head: String = corrupt .db .query_row( "SELECT event_sha256 FROM agent_update_handoff_events WHERE sequence=16", [], |r| r.get(0), ) .unwrap(); let mut value: serde_json::Value = serde_json::from_slice(&raw).unwrap(); value["head_sha256"] = json!(outcome_head); let changed: NativeEffectClaim = serde_json::from_value(value).unwrap(); let raw = serde_json::to_vec(&changed).unwrap(); corrupt.db.execute("UPDATE agent_update_native_claims SET claim=?1,claim_sha256=?2 WHERE effect_key=?3",params![raw,hash(&raw),key]).unwrap(); corrupt .db .execute( "UPDATE agent_update_native_observations SET claim_sha256=?1 WHERE effect_key=?2", params![hash(&raw), key], ) .unwrap(); assert!( verify_history( &corrupt.db, &corrupt.guard, &corrupt.binding, &corrupt.keys, &corrupt.baseline, &[], &corrupt.active ) .is_err() ); let late = fixture(); let key = serde_json::to_string(&NativeEffect::ReturnLedger).unwrap(); let raw: Vec = late .db .query_row( "SELECT claim FROM agent_update_native_claims WHERE effect_key=?1", [&key], |r| r.get(0), ) .unwrap(); let mut value: serde_json::Value = serde_json::from_slice(&raw).unwrap(); value["claimed_at"] = json!(at(699)); let changed: NativeEffectClaim = serde_json::from_value(value).unwrap(); let raw = serde_json::to_vec(&changed).unwrap(); late.db.execute("UPDATE agent_update_native_claims SET claim=?1,claim_sha256=?2 WHERE effect_key=?3",params![raw,hash(&raw),key]).unwrap(); assert!( verify_history( &late.db, &late.guard, &late.binding, &late.keys, &late.baseline, &[], &late.active ) .is_err() ); // A missing successor proof cannot define away its original completed // consumption. Neither losing Publish nor the whole handoff lowers floor. let missing = fixture(); missing.db.execute("DELETE FROM agent_update_native_observations WHERE effect_key='publish_installed_record'",[]).unwrap(); missing.db.execute("DELETE FROM agent_update_native_claims WHERE effect_key='publish_installed_record'",[]).unwrap(); assert!( verify_history( &missing.db, &missing.guard, &missing.binding, &missing.keys, &missing.baseline, &[], &missing.initial ) .is_err() ); missing.db.execute_batch("DELETE FROM agent_update_native_observations;DELETE FROM agent_update_native_claims;DELETE FROM agent_update_handoff_events;DELETE FROM agent_update_delegations;DELETE FROM agent_update_handoffs;").unwrap(); assert!( verify_history( &missing.db, &missing.guard, &missing.binding, &missing.keys, &missing.baseline, &[], &missing.initial ) .is_err() ); let unknown = serde_json::to_vec(&Outcome::unknown("test contradictory completion")).unwrap(); missing .db .execute("UPDATE execution_evidence SET outcome=?1", [unknown]) .unwrap(); assert!( verify_history( &missing.db, &missing.guard, &missing.binding, &missing.keys, &missing.baseline, &[], &missing.initial ) .is_err() ); } }