Files
rust-discovery/crates/update-history/src/lib.rs
T
kevin_janssen cafd13bca9
Rust development slice / linux (push) Failing after 7s
Deploy reviewed Windows sync alignment with schema 20 server
Bind the administrative connection-205 review to original signed history and preserve closed readiness. Include the qualified server dependency closure, UI review, native ARM64 build provenance, and guarded deployment evidence. Migration, API/gateway replacement and TLS checks passed with unchanged job authority, protected mounts and time/database services; native Windows receipt application remains separate.
2026-11-16 13:30:31 +01:00

776 lines
33 KiB
Rust

//! 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<u8>],
active_raw: &[u8],
) -> Result<InstalledReleaseRecord> {
guard.check(db)?;
ensure!(protected_keyring.validate(), "UPDATE_HISTORY_KEYRING");
let initial = baseline.decode().map_err(anyhow::Error::msg)?;
ensure!(
matches!(
initial.record.platform,
Platform::LinuxX64 | Platform::WindowsX64
),
"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,
initial_release.manifest.protocol_major,
initial_release.manifest.state_schema,
)?;
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,
initial_release.manifest.protocol_major,
initial_release.manifest.state_schema,
)?;
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<Vec<u8>> = 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<UpdateKeyring> {
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<BTreeSet<Uuid>> {
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<Vec<u8>> = row.get(1)?;
let outcome: Option<Vec<u8>> = row.get(2)?;
let finished: Option<Vec<u8>> = 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<Utc> = 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,
baseline_protocol_major: u32,
baseline_state_schema: u32,
) -> 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,
// Anchor compatibility to the separately signed, qualified
// bootstrap. A signed successor cannot attest its own decoder
// compatibility by supplying both sides of this comparison.
protocol_major: baseline_protocol_major,
state_schema: baseline_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<Uuid> {
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<u8>>(1)?,
r.get::<_, Vec<u8>>(2)?,
r.get::<_, Option<Vec<u8>>>(3)?,
r.get::<_, Option<Vec<u8>>>(4)?,
))
})?
.collect::<rusqlite::Result<Vec<_>>>()?;
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<Utc> = 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
== match record.platform {
Platform::LinuxX64 => "root",
Platform::WindowsX64 => "system",
}
&& 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<String>) = 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<u8>>(0))?
.collect::<rusqlite::Result<Vec<_>>>()?;
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<u8>],
old: &str,
new: &str,
) -> Result<()> {
use rmm_agent_core::update_handoff::{NativeFileRole as F, NativeService as S};
let mut expected = BTreeSet::new();
let (services, roles): (&[S], &[F]) = match header.pin_transition {
rmm_updater_handoff::PinTransition::LinuxGeneralFullV1 => (
&[S::Agent, S::General, S::Full],
&[F::AgentBinary, F::HelperBinary, F::FullConfig, F::FullPin],
),
rmm_updater_handoff::PinTransition::WindowsCodePairClockV1 => (
&[S::WindowsAgent, S::WindowsHelper],
&[
F::AgentBinary,
F::HelperBinary,
F::WindowsSettings,
F::WindowsPin,
F::WindowsTimeProfile,
],
),
_ => anyhow::bail!("UPDATE_HISTORY_UNSUPPORTED_NATIVE_PROFILE"),
};
for service in services.iter().copied() {
expected.insert(serde_json::to_string(&NativeEffect::StopService {
service,
})?);
expected.insert(serde_json::to_string(&NativeEffect::StartService {
service,
})?);
}
for role in roles.iter().copied() {
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::<Event>(raw)?)))
.collect::<Result<BTreeMap<_, _>>>()?;
let time = |predicate: &dyn Fn(&Evidence) -> bool| -> Result<u64> {
let entries = parsed
.values()
.filter(|event| predicate(&event.evidence))
.collect::<Vec<_>>();
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<Utc>)> = None;
while let Some(row) = rows.next()? {
let key: String = row.get(0)?;
let raw: Vec<u8> = 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,
F::WindowsSettings => rmm_updater_handoff::FileRole::WindowsSettings,
F::WindowsPin => rmm_updater_handoff::FileRole::WindowsPin,
F::WindowsTimeProfile => rmm_updater_handoff::FileRole::WindowsTimeProfile,
};
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<String> = row.get(3)?;
let observation: Option<String> = row.get(4)?;
let when: Option<String> = 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<Utc> = 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,
F::WindowsSettings => rmm_updater_handoff::FileRole::WindowsSettings,
F::WindowsPin => rmm_updater_handoff::FileRole::WindowsPin,
F::WindowsTimeProfile => rmm_updater_handoff::FileRole::WindowsTimeProfile,
};
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<Utc> = 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<Utc>, DateTime<Utc>)> {
let value: Option<(Vec<u8>,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<Utc> = 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))
}