1271 lines
50 KiB
Rust
1271 lines
50 KiB
Rust
//! Append-only storage in the EXISTING protected helper consumption ledger.
|
|
//! No effects, generic Unknown healing, second journal ID or start lease.
|
|
//! Admission is only callable through HelperSync's independently checked gate.
|
|
use crate::{
|
|
auth::{Outcome, Request},
|
|
helper_reconcile::ExecutorLedgerGuard,
|
|
ledger,
|
|
};
|
|
use anyhow::{Context, Result, ensure};
|
|
use chrono::{DateTime, Utc};
|
|
use rmm_domain::agent_update::UpdateDelegation;
|
|
use rmm_domain::jobs::{Action, ExecutionPermitPayload, JobPayload, hash};
|
|
use rmm_updater_handoff::{Event, Evidence, Handoff, Journal, Phase, UnknownReason};
|
|
use rusqlite::{Connection, OptionalExtension, TransactionBehavior, params};
|
|
use uuid::Uuid;
|
|
|
|
/// Trusted LOCAL adapter, never an IPC-supplied approved/ready boolean. It
|
|
/// authenticates the stable updater peer, immutable staging/pins/keyring,
|
|
/// release signatures/floor, exact existing file IDs and local update policy.
|
|
/// It must not stop services or replace files while validating admission.
|
|
pub trait UpdateAdmissionGuard: ExecutorLedgerGuard {
|
|
/// Independently loaded from the fixed protected local provisioning pin.
|
|
fn health_public_key(&self) -> Result<[u8; 32]>;
|
|
fn verify_prepared_update(
|
|
&self,
|
|
original: &Request,
|
|
handoff: &Handoff,
|
|
delegation: &UpdateDelegation,
|
|
now: DateTime<Utc>,
|
|
) -> Result<()>;
|
|
}
|
|
|
|
/// Role comes from an authenticated concrete local participant, not IPC data.
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub enum Participant {
|
|
/// Authenticated Full reader; never a native effect participant.
|
|
Observer,
|
|
OriginalHelper,
|
|
StableUpdater,
|
|
NewHelper,
|
|
}
|
|
pub trait UpdateParticipantGuard: ExecutorLedgerGuard {
|
|
fn participant(&self) -> Participant;
|
|
fn verify_native_effect(
|
|
&self,
|
|
_handoff: &Handoff,
|
|
_delegation: &UpdateDelegation,
|
|
_effect: &NativeEffect,
|
|
_stage: NativeEffectStage,
|
|
) -> Result<()> {
|
|
anyhow::bail!("UPDATE_NATIVE_EFFECT_NOT_QUALIFIED")
|
|
}
|
|
/// Recheck fixed service/PID/birth/image, original boot, SAME file IDs,
|
|
/// current clock/deadline and evidence-specific protected observations.
|
|
/// Health additionally compares receipt contents with the actually applied
|
|
/// current signed sync and received inventory ACK. No service/file effect.
|
|
fn verify_update_event(
|
|
&self,
|
|
handoff: &Handoff,
|
|
delegation: &UpdateDelegation,
|
|
event: &Event,
|
|
) -> Result<()>;
|
|
}
|
|
|
|
/// Bootstrap/create-only schema extension. Caller holds the actual existing
|
|
/// executor guard. This does not alter old schema objects, rows or file IDs.
|
|
pub fn initialize(db: &Connection, guard: &impl ExecutorLedgerGuard) -> Result<()> {
|
|
guard.check(db)?;
|
|
db.execute_batch("PRAGMA foreign_keys=ON;")?;
|
|
ensure!(
|
|
db.query_row("PRAGMA foreign_keys", [], |r| r.get::<_, bool>(0))?,
|
|
"UPDATE_LEDGER_FOREIGN_KEYS_REQUIRED"
|
|
);
|
|
db.execute_batch(
|
|
"CREATE TABLE IF NOT EXISTS agent_update_handoffs(
|
|
grant_id TEXT PRIMARY KEY REFERENCES consumed(grant_id), record BLOB NOT NULL,
|
|
record_sha256 TEXT NOT NULL, health_public_key BLOB NOT NULL, head_sha256 TEXT NOT NULL,
|
|
event_count INTEGER NOT NULL, phase TEXT NOT NULL);
|
|
CREATE TABLE IF NOT EXISTS agent_update_delegations(
|
|
grant_id TEXT PRIMARY KEY REFERENCES agent_update_handoffs(grant_id),
|
|
witness BLOB NOT NULL, witness_sha256 TEXT NOT NULL);
|
|
CREATE TABLE IF NOT EXISTS agent_update_handoff_events(
|
|
grant_id TEXT NOT NULL REFERENCES agent_update_handoffs(grant_id), sequence INTEGER NOT NULL,
|
|
event BLOB NOT NULL, event_sha256 TEXT NOT NULL, PRIMARY KEY(grant_id,sequence));
|
|
CREATE TABLE IF NOT EXISTS agent_update_native_claims(
|
|
grant_id TEXT NOT NULL REFERENCES agent_update_handoffs(grant_id),effect_key TEXT NOT NULL,
|
|
claim BLOB NOT NULL,claim_sha256 TEXT NOT NULL,PRIMARY KEY(grant_id,effect_key));
|
|
CREATE TABLE IF NOT EXISTS agent_update_native_observations(
|
|
grant_id TEXT NOT NULL,effect_key TEXT NOT NULL,claim_sha256 TEXT NOT NULL,
|
|
observation_sha256 TEXT NOT NULL,observed_at TEXT NOT NULL,PRIMARY KEY(grant_id,effect_key),
|
|
FOREIGN KEY(grant_id,effect_key) REFERENCES agent_update_native_claims(grant_id,effect_key));
|
|
CREATE TABLE IF NOT EXISTS agent_update_sync_applied(
|
|
grant_id TEXT NOT NULL REFERENCES agent_update_handoffs(grant_id),decision_id TEXT NOT NULL,
|
|
witness BLOB NOT NULL,witness_sha256 TEXT NOT NULL,PRIMARY KEY(grant_id,decision_id));",
|
|
)?;
|
|
Ok(())
|
|
}
|
|
|
|
/// Prepared exact local bytes, not an authorization. HelperSync independently
|
|
/// checks fresh live admission before these bytes can be consumed.
|
|
pub struct PreparedHandoff<'a> {
|
|
pub request: &'a Request,
|
|
pub handoff: &'a Handoff,
|
|
pub delegation: &'a UpdateDelegation,
|
|
pub recorded_at: DateTime<Utc>,
|
|
}
|
|
|
|
pub(crate) fn consume(
|
|
db: &mut Connection,
|
|
guard: &impl UpdateAdmissionGuard,
|
|
permit: &ExecutionPermitPayload,
|
|
prepared: &PreparedHandoff<'_>,
|
|
health_public_key: [u8; 32],
|
|
check_fresh: &impl Fn(&Connection) -> Result<()>,
|
|
) -> Result<()> {
|
|
let PreparedHandoff {
|
|
request,
|
|
handoff,
|
|
delegation,
|
|
recorded_at: now,
|
|
} = *prepared;
|
|
guard.check(db)?;
|
|
ledger::validate_start_request(permit, request)?;
|
|
let job: JobPayload = serde_json::from_slice(&request.job_bytes)?;
|
|
let Action::UpdateAgent { update } = &job.action else {
|
|
anyhow::bail!("UPDATE_ACTION_REQUIRED");
|
|
};
|
|
ensure!(
|
|
update.validate() && update.execution_identity() == Some(job.execution_identity.as_str()),
|
|
"UPDATE_ACTION_INVALID"
|
|
);
|
|
ensure!(
|
|
rmm_domain::agent_update::job_health_public_key(&job).map_err(anyhow::Error::msg)?
|
|
== health_public_key
|
|
&& guard.health_public_key()? == health_public_key,
|
|
"UPDATE_HEALTH_PIN_BINDING"
|
|
);
|
|
let record = handoff.bytes()?;
|
|
let mut journal = Journal::open(&record, health_public_key)?;
|
|
ensure!(
|
|
delegation.validate()
|
|
&& delegation.handoff_sha256 == hash(&record)
|
|
&& delegation.owner_nonce == handoff.owner_nonce
|
|
&& delegation.boot_id == handoff.boot_id
|
|
&& delegation.prepared_at == now
|
|
&& delegation.updater.image_sha256 == handoff.updater_sha256
|
|
&& delegation.original_helper.image_sha256 == handoff.predecessor.helper_sha256,
|
|
"UPDATE_DELEGATION_BINDING"
|
|
);
|
|
let delegation_bytes = serde_json::to_vec(delegation)?;
|
|
let at = u64::try_from(now.timestamp())?;
|
|
let start = ledger::start_witness_bytes(permit, request, handoff.boot_id, now)?;
|
|
ensure!(
|
|
handoff.attempt.tenant_id == permit.tenant_id
|
|
&& handoff.attempt.asset_id == permit.asset_id
|
|
&& handoff.attempt.agent_id == permit.agent_id
|
|
&& handoff.attempt.enrollment_generation == permit.enrollment_generation
|
|
&& handoff.attempt.assignment_version == permit.assignment_version
|
|
&& handoff.attempt.job_id == permit.job_id
|
|
&& handoff.attempt.attempt_id == permit.attempt_id
|
|
&& handoff.attempt.grant_id == permit.grant_id
|
|
&& handoff.attempt.authorization_id == permit.authorization_id
|
|
&& Some(handoff.attempt.plan_id) == permit.agent_update_plan_id
|
|
&& handoff.attempt.plan_sha256 == permit.plan_hash
|
|
&& handoff.attempt.job_payload_sha256 == permit.job_payload_hash
|
|
&& handoff.attempt.original_request_sha256 == hash(&serde_json::to_vec(request)?)
|
|
&& handoff.attempt.original_start_witness_sha256 == hash(&start)
|
|
&& handoff.consumed_at == at
|
|
&& handoff.finish_before == at.checked_add(600).context("UPDATE_DEADLINE_OVERFLOW")?
|
|
&& permit.max_runtime_seconds == 600,
|
|
"UPDATE_ORIGINAL_BINDING"
|
|
);
|
|
let manifest = update.manifest().map_err(anyhow::Error::msg)?;
|
|
ensure!(
|
|
rmm_domain::agent_update::handoff_matches_job(handoff, &job),
|
|
"UPDATE_EXACT_JOB_TRANSITION_BINDING"
|
|
);
|
|
ensure!(
|
|
handoff.target.manifest_sha256 == update.manifest_sha256
|
|
&& handoff.target.agent_sha256 == manifest.artifacts[0].sha256
|
|
&& handoff.target.helper_sha256 == manifest.artifacts[1].sha256
|
|
&& handoff.predecessor.manifest_sha256 == update.predecessor.manifest_sha256
|
|
&& handoff.predecessor.agent_sha256 == update.predecessor.agent_sha256
|
|
&& handoff.predecessor.helper_sha256 == update.predecessor.helper_sha256
|
|
&& handoff.predecessor_record_sha256 == update.predecessor.installed_record_sha256
|
|
&& handoff.updater_sha256 == update.updater.binary_sha256
|
|
&& handoff.updater_policy_sha256 == update.updater.policy_sha256
|
|
&& handoff.pin_transition_sha256
|
|
== hash(&serde_json::to_vec(&update.peer_pin_transition)?),
|
|
"UPDATE_CODEPAIR_BINDING"
|
|
);
|
|
guard.verify_prepared_update(request, handoff, delegation, now)?;
|
|
let stop_intent = journal.prepare(at, Evidence::StopIntent)?;
|
|
journal.replay(&stop_intent)?;
|
|
// Consumption, exact legacy start, immutable handoff and first stop intent
|
|
// commit together. Any failed INSERT rolls ALL of them back.
|
|
let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
|
guard.check(&tx)?;
|
|
guard.verify_prepared_update(request, handoff, delegation, now)?;
|
|
check_fresh(&tx)?;
|
|
ledger::consume_in(&tx, permit)?;
|
|
ledger::save_start(&tx, permit, request, handoff.boot_id, now)?;
|
|
tx.execute("INSERT INTO agent_update_handoffs(grant_id,record,record_sha256,health_public_key,head_sha256,event_count,phase)
|
|
VALUES(?1,?2,?3,?4,?5,1,'stop_intent')",params![permit.grant_id.to_string(),record,
|
|
journal.handoff_sha256(),health_public_key.to_vec(),journal.head_sha256()])?;
|
|
tx.execute(
|
|
"INSERT INTO agent_update_delegations(grant_id,witness,witness_sha256) VALUES(?1,?2,?3)",
|
|
params![
|
|
permit.grant_id.to_string(),
|
|
delegation_bytes,
|
|
hash(&delegation_bytes)
|
|
],
|
|
)?;
|
|
tx.execute("INSERT INTO agent_update_handoff_events(grant_id,sequence,event,event_sha256) VALUES(?1,1,?2,?3)",
|
|
params![permit.grant_id.to_string(),stop_intent,hash(&stop_intent)])?;
|
|
tx.commit()?;
|
|
Ok(())
|
|
}
|
|
|
|
/// Read-only replay under the current authenticated guard. Original immutable
|
|
/// start, consumption, rows, event hashes, count and stored head all agree.
|
|
/// This returns neither a Ready lease nor permission to resume an OS effect.
|
|
pub fn read(db: &Connection, guard: &impl ExecutorLedgerGuard, grant: Uuid) -> Result<Journal> {
|
|
guard.check(db)?;
|
|
read_locked(db, grant)
|
|
}
|
|
pub(crate) fn read_locked(db: &Connection, grant: Uuid) -> Result<Journal> {
|
|
type Row = (
|
|
Vec<u8>,
|
|
String,
|
|
Vec<u8>,
|
|
String,
|
|
u32,
|
|
String,
|
|
Vec<u8>,
|
|
Option<Vec<u8>>,
|
|
Option<Vec<u8>>,
|
|
);
|
|
let row: Option<Row> = db.query_row("SELECT h.record,h.record_sha256,h.health_public_key,h.head_sha256,h.event_count,h.phase,
|
|
e.start,e.outcome,c.result FROM agent_update_handoffs h JOIN consumed c USING(grant_id)
|
|
JOIN execution_evidence e USING(grant_id) WHERE h.grant_id=?1",[grant.to_string()],|r|
|
|
Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?,r.get(4)?,r.get(5)?,r.get(6)?,r.get(7)?,r.get(8)?)))
|
|
.optional()?;
|
|
let (record, record_hash, key, head, count, phase, start, outcome, result) =
|
|
row.context("UPDATE_HANDOFF_MISSING")?;
|
|
ensure!(
|
|
hash(&record) == record_hash && key.len() == 32,
|
|
"UPDATE_HANDOFF_RECORD_CHANGED"
|
|
);
|
|
let handoff: Handoff = serde_json::from_slice(&record)?;
|
|
ensure!(
|
|
handoff.attempt.grant_id == grant
|
|
&& hash(&start) == handoff.attempt.original_start_witness_sha256,
|
|
"UPDATE_HANDOFF_ORIGINAL_CHANGED"
|
|
);
|
|
let consumed: (String, u64, String, String) = db.query_row(
|
|
"SELECT agent,generation,job,attempt FROM consumed WHERE grant_id=?1",
|
|
[grant.to_string()],
|
|
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
|
|
)?;
|
|
ensure!(
|
|
consumed.0 == handoff.attempt.agent_id.to_string()
|
|
&& consumed.1 == handoff.attempt.enrollment_generation
|
|
&& consumed.2 == handoff.attempt.job_id.to_string()
|
|
&& consumed.3 == handoff.attempt.attempt_id.to_string(),
|
|
"UPDATE_HANDOFF_CONSUMED_CHANGED"
|
|
);
|
|
let start_value: serde_json::Value = serde_json::from_slice(&start)?;
|
|
let original: Request = serde_json::from_value(start_value["request"].clone())?;
|
|
let original_job: JobPayload = serde_json::from_slice(&original.job_bytes)?;
|
|
ensure!(
|
|
rmm_domain::agent_update::job_health_public_key(&original_job)
|
|
.map_err(anyhow::Error::msg)?
|
|
.as_slice()
|
|
== key.as_slice(),
|
|
"UPDATE_STORED_HEALTH_KEY_CHANGED"
|
|
);
|
|
let delegation = read_delegation(db, grant)?;
|
|
ensure!(
|
|
delegation.handoff_sha256 == record_hash
|
|
&& delegation.owner_nonce == handoff.owner_nonce
|
|
&& delegation.boot_id == handoff.boot_id
|
|
&& delegation.updater.image_sha256 == handoff.updater_sha256
|
|
&& delegation.original_helper.image_sha256 == handoff.predecessor.helper_sha256,
|
|
"UPDATE_DELEGATION_BINDING"
|
|
);
|
|
// Native intents are subordinate immutable rows, not another consumption
|
|
// or execution journal. Replaying them never authorizes dispatch.
|
|
let mut native=db.prepare("SELECT effect_key,claim,claim_sha256 FROM agent_update_native_claims WHERE grant_id=?1 ORDER BY effect_key")?;
|
|
let native_rows = native.query_map([grant.to_string()], |r| {
|
|
Ok((
|
|
r.get::<_, String>(0)?,
|
|
r.get::<_, Vec<u8>>(1)?,
|
|
r.get::<_, String>(2)?,
|
|
))
|
|
})?;
|
|
let mut native_count = 0;
|
|
for row in native_rows {
|
|
native_count += 1;
|
|
let (effect_key, raw, digest) = row?;
|
|
let claim: NativeEffectClaim = serde_json::from_slice(&raw)?;
|
|
ensure!(
|
|
native_count <= 17
|
|
&& raw.len() <= 2048
|
|
&& hash(&raw) == digest
|
|
&& serde_json::to_vec(&claim)? == raw
|
|
&& claim.grant_id == grant
|
|
&& claim.owner_nonce == handoff.owner_nonce
|
|
&& native_key(&claim.effect)? == effect_key
|
|
&& rmm_domain::agent_update::digest(&claim.head_sha256),
|
|
"UPDATE_NATIVE_HISTORY_CHANGED"
|
|
);
|
|
}
|
|
let invalid:u64=db.query_row("SELECT count(*) FROM agent_update_native_observations o LEFT JOIN agent_update_native_claims c ON c.grant_id=o.grant_id AND c.effect_key=o.effect_key WHERE o.grant_id=?1 AND (c.claim_sha256 IS NULL OR c.claim_sha256<>o.claim_sha256)",[grant.to_string()],|r|r.get(0))?;
|
|
ensure!(invalid == 0, "UPDATE_NATIVE_OBSERVATION_BINDING");
|
|
let mut journal = Journal::open(
|
|
&record,
|
|
key.try_into()
|
|
.map_err(|_| anyhow::anyhow!("UPDATE_HEALTH_KEY"))?,
|
|
)?;
|
|
let mut statement = db.prepare("SELECT sequence,event,event_sha256 FROM agent_update_handoff_events WHERE grant_id=?1 ORDER BY sequence")?;
|
|
let rows = statement.query_map([grant.to_string()], |r| {
|
|
Ok((
|
|
r.get::<_, u32>(0)?,
|
|
r.get::<_, Vec<u8>>(1)?,
|
|
r.get::<_, String>(2)?,
|
|
))
|
|
})?;
|
|
let mut observed = 0;
|
|
let mut stored_outcome_hash = None;
|
|
for row in rows {
|
|
let (sequence, event, event_hash) = row?;
|
|
observed += 1;
|
|
ensure!(
|
|
sequence == observed && hash(&event) == event_hash,
|
|
"UPDATE_HANDOFF_EVENT_CHANGED"
|
|
);
|
|
journal.replay(&event)?;
|
|
let parsed: Event = serde_json::from_slice(&event)?;
|
|
if let Evidence::OutcomePersisted { outcome_sha256 } = parsed.evidence {
|
|
stored_outcome_hash = Some(outcome_sha256);
|
|
}
|
|
}
|
|
ensure!(
|
|
observed == count && journal.head_sha256() == head && phase == phase_name(journal.phase()),
|
|
"UPDATE_HANDOFF_HEAD_CHANGED"
|
|
);
|
|
if journal.phase() == Phase::OutcomePersisted {
|
|
ensure!(
|
|
outcome
|
|
.as_ref()
|
|
.is_some_and(|bytes| stored_outcome_hash.as_ref() == Some(&hash(bytes))),
|
|
"UPDATE_HANDOFF_FINAL_OUTCOME_MISSING_OR_CHANGED"
|
|
);
|
|
}
|
|
if outcome.is_some() || result.is_some() {
|
|
ensure!(
|
|
matches!(journal.phase(), Phase::OutcomePersisted | Phase::Unknown),
|
|
"UPDATE_HANDOFF_OUTCOME_CONFLICT"
|
|
);
|
|
if let (Some(a), Some(b)) = (outcome, result) {
|
|
ensure!(a == b, "UPDATE_HANDOFF_OUTCOME_CONFLICT");
|
|
}
|
|
}
|
|
Ok(journal)
|
|
}
|
|
|
|
/// Only metadata under an already checked helper executor guard. Live owner,
|
|
/// clock and boot checks remain required at capture/apply, never inferred here.
|
|
pub(crate) fn proof_locked(
|
|
db: &Connection,
|
|
grant: Uuid,
|
|
) -> Result<Option<rmm_domain::agent_update::UpdateInflightProof>> {
|
|
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 {
|
|
return Ok(None);
|
|
}
|
|
let record: Option<Vec<u8>> = db
|
|
.query_row(
|
|
"SELECT record FROM agent_update_handoffs WHERE grant_id=?1",
|
|
[grant.to_string()],
|
|
|r| r.get(0),
|
|
)
|
|
.optional()?;
|
|
let Some(record) = record else {
|
|
return Ok(None);
|
|
};
|
|
let journal = read_locked(db, grant)?;
|
|
if matches!(journal.phase(), Phase::Unknown | Phase::OutcomePersisted) {
|
|
return Ok(None);
|
|
}
|
|
let mut statement = db.prepare(
|
|
"SELECT event FROM agent_update_handoff_events WHERE grant_id=?1 ORDER BY sequence",
|
|
)?;
|
|
let events = statement
|
|
.query_map([grant.to_string()], |r| r.get::<_, Vec<u8>>(0))?
|
|
.collect::<rusqlite::Result<Vec<_>>>()?;
|
|
Ok(Some(
|
|
rmm_domain::agent_update::UpdateInflightProof::from_raw(
|
|
&record,
|
|
read_delegation(db, grant)?,
|
|
&events,
|
|
journal.head_sha256().into(),
|
|
)
|
|
.map_err(anyhow::Error::msg)?,
|
|
))
|
|
}
|
|
|
|
/// Shared pure validator, still no OS owner attestation or readiness claim.
|
|
pub fn verify_inflight_proof(
|
|
proof: &rmm_domain::agent_update::UpdateInflightProof,
|
|
health_key: [u8; 32],
|
|
) -> Result<(Handoff, Journal)> {
|
|
rmm_domain::agent_update::verify_inflight_proof(proof, health_key).map_err(anyhow::Error::msg)
|
|
}
|
|
pub fn inflight_decision(
|
|
proof: &rmm_domain::agent_update::UpdateInflightProof,
|
|
health_key: [u8; 32],
|
|
) -> Result<rmm_domain::agent_update::UpdateInflightDecision> {
|
|
rmm_domain::agent_update::inflight_decision(proof, health_key).map_err(anyhow::Error::msg)
|
|
}
|
|
|
|
/// CAS append only. The actual participant/OS adapter authenticates which
|
|
/// writer owns the SAME guard and which raw observations support this event.
|
|
/// Callers cannot mutate original rows or replace an existing terminal outcome.
|
|
pub fn append(
|
|
db: &mut Connection,
|
|
guard: &impl UpdateParticipantGuard,
|
|
grant: Uuid,
|
|
expected_head: &str,
|
|
event: &[u8],
|
|
) -> Result<()> {
|
|
let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
|
let mut journal = read(&tx, guard, grant)?;
|
|
ensure!(
|
|
journal.head_sha256() == expected_head,
|
|
"UPDATE_HANDOFF_CAS_CONFLICT"
|
|
);
|
|
let parsed: Event = serde_json::from_slice(event)?;
|
|
ensure!(
|
|
!matches!(
|
|
parsed.evidence,
|
|
Evidence::OutcomePersisted { .. } | Evidence::Unknown { .. }
|
|
),
|
|
"UPDATE_TERMINAL_REQUIRES_OUTCOME_CAS"
|
|
);
|
|
verify_writer(&tx, guard, grant, &parsed)?;
|
|
journal.replay(event)?;
|
|
append_in(&tx, grant, expected_head, event, &parsed, &journal)?;
|
|
tx.commit()?;
|
|
Ok(())
|
|
}
|
|
|
|
pub fn read_delegation(db: &Connection, grant: Uuid) -> Result<UpdateDelegation> {
|
|
let (raw, expected): (Vec<u8>, String) = db.query_row(
|
|
"SELECT witness,witness_sha256 FROM agent_update_delegations WHERE grant_id=?1",
|
|
[grant.to_string()],
|
|
|r| Ok((r.get(0)?, r.get(1)?)),
|
|
)?;
|
|
ensure!(
|
|
raw.len() <= 8192 && hash(&raw) == expected,
|
|
"UPDATE_DELEGATION_CHANGED"
|
|
);
|
|
let delegation: UpdateDelegation = serde_json::from_slice(&raw)?;
|
|
ensure!(
|
|
delegation.validate() && serde_json::to_vec(&delegation)? == raw,
|
|
"UPDATE_DELEGATION_INVALID"
|
|
);
|
|
Ok(delegation)
|
|
}
|
|
|
|
fn verify_writer(
|
|
db: &Connection,
|
|
guard: &impl UpdateParticipantGuard,
|
|
grant: Uuid,
|
|
event: &Event,
|
|
) -> Result<()> {
|
|
let raw: Vec<u8> = db.query_row(
|
|
"SELECT record FROM agent_update_handoffs WHERE grant_id=?1",
|
|
[grant.to_string()],
|
|
|r| r.get(0),
|
|
)?;
|
|
let handoff: Handoff = serde_json::from_slice(&raw)?;
|
|
let expected = match event.evidence {
|
|
Evidence::AllStopped { .. }
|
|
| Evidence::UpdaterOwnsLedger { .. }
|
|
| Evidence::ReplaceIntent { .. }
|
|
| Evidence::Replaced { .. }
|
|
| Evidence::PairVerified { .. }
|
|
| Evidence::LedgerReturnIntent => Participant::StableUpdater,
|
|
Evidence::ServicesStarted { .. }
|
|
| Evidence::HealthVerified { .. }
|
|
| Evidence::OutcomePersisted { .. } => Participant::NewHelper,
|
|
Evidence::Unknown { .. } => guard.participant(),
|
|
Evidence::StopIntent => anyhow::bail!("UPDATE_STOP_ALREADY_ATOMICALLY_STORED"),
|
|
};
|
|
ensure!(guard.participant() == expected, "UPDATE_WRITER_ROLE");
|
|
let require_observed = |effect: NativeEffect| -> Result<()> {
|
|
let count:u64=db.query_row("SELECT count(*) FROM agent_update_native_observations WHERE grant_id=?1 AND effect_key=?2",params![grant.to_string(),native_key(&effect)?],|r|r.get(0))?;
|
|
ensure!(count == 1, "UPDATE_NATIVE_OBSERVATION_REQUIRED");
|
|
Ok(())
|
|
};
|
|
match &event.evidence {
|
|
Evidence::AllStopped { .. } => {
|
|
for service in [
|
|
NativeService::Agent,
|
|
NativeService::General,
|
|
NativeService::Full,
|
|
] {
|
|
if handoff.stop_set.contains(&native_service(service)) {
|
|
require_observed(NativeEffect::StopService { service })?;
|
|
}
|
|
}
|
|
}
|
|
Evidence::Replaced { role, .. } => {
|
|
let role = match role {
|
|
rmm_updater_handoff::FileRole::AgentBinary => NativeFileRole::AgentBinary,
|
|
rmm_updater_handoff::FileRole::HelperBinary => NativeFileRole::HelperBinary,
|
|
rmm_updater_handoff::FileRole::LinuxFullConfig => NativeFileRole::FullConfig,
|
|
rmm_updater_handoff::FileRole::LinuxFullPin => NativeFileRole::FullPin,
|
|
_ => anyhow::bail!("UPDATE_NATIVE_PLATFORM_UNQUALIFIED"),
|
|
};
|
|
require_observed(NativeEffect::PublishReplacement { role })?;
|
|
}
|
|
Evidence::ServicesStarted { .. } => {
|
|
for service in [
|
|
NativeService::General,
|
|
NativeService::Full,
|
|
NativeService::Agent,
|
|
] {
|
|
require_observed(NativeEffect::StartService { service })?;
|
|
}
|
|
}
|
|
_ => {}
|
|
}
|
|
guard.verify_update_event(&handoff, &read_delegation(db, grant)?, event)
|
|
}
|
|
|
|
fn append_in(
|
|
tx: &Connection,
|
|
grant: Uuid,
|
|
expected_head: &str,
|
|
event: &[u8],
|
|
parsed: &Event,
|
|
journal: &Journal,
|
|
) -> Result<()> {
|
|
tx.execute("INSERT INTO agent_update_handoff_events(grant_id,sequence,event,event_sha256) VALUES(?1,?2,?3,?4)",
|
|
params![grant.to_string(),parsed.sequence,event,hash(event)])?;
|
|
ensure!(tx.execute("UPDATE agent_update_handoffs SET head_sha256=?2,event_count=?3,phase=?4 WHERE grant_id=?1 AND head_sha256=?5",
|
|
params![grant.to_string(),journal.head_sha256(),parsed.sequence,phase_name(journal.phase()),expected_head])? == 1,"UPDATE_HANDOFF_CAS_CONFLICT");
|
|
Ok(())
|
|
}
|
|
|
|
/// Final outcome and its handoff event commit atomically. Does NOT set
|
|
/// consumed.result or create a Ready lease: normal signed mirroring/sync must
|
|
/// still agree with the exact bytes. Existing Unknown cannot be overwritten.
|
|
pub fn finalize(
|
|
db: &mut Connection,
|
|
guard: &impl UpdateParticipantGuard,
|
|
permit: &ExecutionPermitPayload,
|
|
expected_head: &str,
|
|
observed_at: u64,
|
|
outcome: &Outcome,
|
|
) -> Result<()> {
|
|
ensure!(
|
|
guard.participant() == Participant::NewHelper
|
|
&& outcome.state == "succeeded"
|
|
&& !outcome.reboot_required,
|
|
"UPDATE_FINAL_OUTCOME_PROFILE"
|
|
);
|
|
let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
|
let mut journal = read(&tx, guard, permit.grant_id)?;
|
|
let records:u64=tx.query_row("SELECT count(*) FROM agent_update_native_observations WHERE grant_id=?1 AND effect_key IN ('save_installed_record','publish_installed_record')",[permit.grant_id.to_string()],|r|r.get(0))?;
|
|
ensure!(records == 2, "UPDATE_INSTALLED_RECORD_NOT_CONFIRMED");
|
|
ensure!(
|
|
journal.head_sha256() == expected_head && journal.phase() == Phase::HealthVerified,
|
|
"UPDATE_FINAL_HEAD_OR_PHASE"
|
|
);
|
|
let outcome_bytes = ledger::persist_outcome_in(&tx, permit, outcome)?;
|
|
let event = journal.prepare(
|
|
observed_at,
|
|
Evidence::OutcomePersisted {
|
|
outcome_sha256: hash(&outcome_bytes),
|
|
},
|
|
)?;
|
|
let parsed: Event = serde_json::from_slice(&event)?;
|
|
verify_writer(&tx, guard, permit.grant_id, &parsed)?;
|
|
journal.replay(&event)?;
|
|
append_in(
|
|
&tx,
|
|
permit.grant_id,
|
|
expected_head,
|
|
&event,
|
|
&parsed,
|
|
&journal,
|
|
)?;
|
|
tx.commit()?;
|
|
Ok(())
|
|
}
|
|
|
|
/// Persist uncertainty once under the same original consumption. No release,
|
|
/// new start, result rewrite or transition back out of Unknown is provided.
|
|
pub fn mark_unknown(
|
|
db: &mut Connection,
|
|
guard: &impl UpdateParticipantGuard,
|
|
permit: &ExecutionPermitPayload,
|
|
expected_head: &str,
|
|
observed_at: u64,
|
|
reason: UnknownReason,
|
|
) -> Result<()> {
|
|
let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
|
let mut journal = read(&tx, guard, permit.grant_id)?;
|
|
ensure!(
|
|
journal.head_sha256() == expected_head,
|
|
"UPDATE_UNKNOWN_HEAD_CHANGED"
|
|
);
|
|
let event = journal.prepare(observed_at, Evidence::Unknown { reason })?;
|
|
let parsed: Event = serde_json::from_slice(&event)?;
|
|
verify_writer(&tx, guard, permit.grant_id, &parsed)?;
|
|
ledger::persist_outcome_in(&tx, permit, &Outcome::unknown("AGENT_UPDATE_UNCERTAIN"))?;
|
|
journal.replay(&event)?;
|
|
append_in(
|
|
&tx,
|
|
permit.grant_id,
|
|
expected_head,
|
|
&event,
|
|
&parsed,
|
|
&journal,
|
|
)?;
|
|
tx.commit()?;
|
|
Ok(())
|
|
}
|
|
|
|
/// Called only by independently verifying helper capture under its existing
|
|
/// IMMEDIATE transaction/guard after a live owner/boot/deadline check failed.
|
|
/// It creates uncertainty, never effects or a successful result.
|
|
pub(crate) fn mark_unknown_locked(
|
|
db: &Connection,
|
|
permit: &ExecutionPermitPayload,
|
|
observed_at: u64,
|
|
reason: UnknownReason,
|
|
) -> Result<Vec<u8>> {
|
|
let mut journal = read_locked(db, permit.grant_id)?;
|
|
let head = journal.head_sha256().to_owned();
|
|
let event = journal.prepare(observed_at, Evidence::Unknown { reason })?;
|
|
let parsed: Event = serde_json::from_slice(&event)?;
|
|
let outcome = ledger::persist_outcome_in(
|
|
db,
|
|
permit,
|
|
&Outcome::unknown("AGENT_UPDATE_OWNER_OR_DEADLINE_UNPROVEN"),
|
|
)?;
|
|
journal.replay(&event)?;
|
|
append_in(db, permit.grant_id, &head, &event, &parsed, &journal)?;
|
|
Ok(outcome)
|
|
}
|
|
|
|
fn phase_name(phase: Phase) -> &'static str {
|
|
match phase {
|
|
Phase::HandoffConsumed => "handoff_consumed",
|
|
Phase::StopIntent => "stop_intent",
|
|
Phase::AllStopped => "all_stopped",
|
|
Phase::UpdaterOwnsLedger => "updater_owns_ledger",
|
|
Phase::ReplaceIntent => "replace_intent",
|
|
Phase::Replaced => "replaced",
|
|
Phase::PairVerified => "pair_verified",
|
|
Phase::LedgerReturnIntent => "ledger_return_intent",
|
|
Phase::ServicesStarted => "services_started",
|
|
Phase::HealthVerified => "health_verified",
|
|
Phase::OutcomePersisted => "outcome_persisted",
|
|
Phase::Unknown => "unknown",
|
|
}
|
|
}
|
|
|
|
/// Closed native sub-effects, subordinate to the original consumed attempt.
|
|
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
|
#[serde(tag = "effect", rename_all = "snake_case", deny_unknown_fields)]
|
|
pub enum NativeEffect {
|
|
StopService {
|
|
service: NativeService,
|
|
},
|
|
SavePredecessor {
|
|
role: NativeFileRole,
|
|
},
|
|
PublishReplacement {
|
|
role: NativeFileRole,
|
|
},
|
|
RestorePredecessor {
|
|
role: NativeFileRole,
|
|
},
|
|
StartService {
|
|
service: NativeService,
|
|
},
|
|
ReturnLedger,
|
|
SaveInstalledRecord {
|
|
old_sha256: String,
|
|
new_sha256: String,
|
|
},
|
|
PublishInstalledRecord {
|
|
old_sha256: String,
|
|
new_sha256: String,
|
|
},
|
|
}
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
|
#[serde(rename_all = "snake_case")]
|
|
pub enum NativeService {
|
|
Agent,
|
|
General,
|
|
Full,
|
|
}
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
|
#[serde(rename_all = "snake_case")]
|
|
pub enum NativeFileRole {
|
|
AgentBinary,
|
|
HelperBinary,
|
|
FullConfig,
|
|
FullPin,
|
|
}
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub enum NativeEffectStage {
|
|
Claim,
|
|
Observe,
|
|
ReserveFutureStart,
|
|
}
|
|
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct NativeEffectClaim {
|
|
grant_id: Uuid,
|
|
owner_nonce: Uuid,
|
|
head_sha256: String,
|
|
effect: NativeEffect,
|
|
claimed_at: DateTime<Utc>,
|
|
}
|
|
impl NativeEffectClaim {
|
|
pub fn grant_id(&self) -> Uuid {
|
|
self.grant_id
|
|
}
|
|
pub fn owner_nonce(&self) -> Uuid {
|
|
self.owner_nonce
|
|
}
|
|
pub fn head_sha256(&self) -> &str {
|
|
&self.head_sha256
|
|
}
|
|
pub fn effect(&self) -> &NativeEffect {
|
|
&self.effect
|
|
}
|
|
pub fn claimed_at(&self) -> DateTime<Utc> {
|
|
self.claimed_at
|
|
}
|
|
}
|
|
pub struct PreparedReturnClaims {
|
|
pub return_ledger: NativeEffectClaim,
|
|
pub starts: [NativeEffectClaim; 3],
|
|
}
|
|
fn native_context(
|
|
db: &Connection,
|
|
guard: &impl UpdateParticipantGuard,
|
|
grant: Uuid,
|
|
now: DateTime<Utc>,
|
|
) -> Result<(Handoff, UpdateDelegation, Journal)> {
|
|
let journal = read(db, guard, grant)?;
|
|
let raw: Vec<u8> = db.query_row(
|
|
"SELECT record FROM agent_update_handoffs WHERE grant_id=?1",
|
|
[grant.to_string()],
|
|
|r| r.get(0),
|
|
)?;
|
|
let h: Handoff = serde_json::from_slice(&raw)?;
|
|
let d = read_delegation(db, grant)?;
|
|
let seconds = u64::try_from(now.timestamp())?;
|
|
ensure!(
|
|
seconds >= h.consumed_at
|
|
&& seconds < h.finish_before
|
|
&& !matches!(journal.phase(), Phase::Unknown | Phase::OutcomePersisted),
|
|
"UPDATE_NATIVE_DEADLINE_OR_TERMINAL"
|
|
);
|
|
Ok((h, d, journal))
|
|
}
|
|
fn native_role(role: NativeFileRole) -> rmm_updater_handoff::FileRole {
|
|
use rmm_updater_handoff::FileRole as F;
|
|
match role {
|
|
NativeFileRole::AgentBinary => F::AgentBinary,
|
|
NativeFileRole::HelperBinary => F::HelperBinary,
|
|
NativeFileRole::FullConfig => F::LinuxFullConfig,
|
|
NativeFileRole::FullPin => F::LinuxFullPin,
|
|
}
|
|
}
|
|
fn native_service(service: NativeService) -> rmm_updater_handoff::Service {
|
|
use rmm_updater_handoff::Service as S;
|
|
match service {
|
|
NativeService::Agent => S::LinuxAgent,
|
|
NativeService::General => S::LinuxGeneralHelper,
|
|
NativeService::Full => S::LinuxFullHelper,
|
|
}
|
|
}
|
|
fn native_key(effect: &NativeEffect) -> Result<String> {
|
|
match effect {
|
|
NativeEffect::SaveInstalledRecord { .. } => Ok("save_installed_record".into()),
|
|
NativeEffect::PublishInstalledRecord { .. } => Ok("publish_installed_record".into()),
|
|
_ => Ok(serde_json::to_string(effect)?),
|
|
}
|
|
}
|
|
fn insert_native_claim(
|
|
db: &Connection,
|
|
h: &Handoff,
|
|
head: &str,
|
|
effect: NativeEffect,
|
|
now: DateTime<Utc>,
|
|
) -> Result<NativeEffectClaim> {
|
|
let count: u64 = db.query_row(
|
|
"SELECT count(*) FROM agent_update_native_claims WHERE grant_id=?1",
|
|
[h.attempt.grant_id.to_string()],
|
|
|r| r.get(0),
|
|
)?;
|
|
ensure!(count < 17, "UPDATE_NATIVE_EFFECT_LIMIT");
|
|
let claim = NativeEffectClaim {
|
|
grant_id: h.attempt.grant_id,
|
|
owner_nonce: h.owner_nonce,
|
|
head_sha256: head.into(),
|
|
effect,
|
|
claimed_at: now,
|
|
};
|
|
let raw = serde_json::to_vec(&claim)?;
|
|
db.execute("INSERT INTO agent_update_native_claims(grant_id,effect_key,claim,claim_sha256) VALUES(?1,?2,?3,?4)",params![claim.grant_id.to_string(),native_key(&claim.effect)?,raw,hash(&raw)])?;
|
|
Ok(claim)
|
|
}
|
|
/// A duplicate intent is a hard denial, never a dispatch/resume instruction.
|
|
pub fn claim_native_effect(
|
|
db: &mut Connection,
|
|
guard: &impl UpdateParticipantGuard,
|
|
grant: Uuid,
|
|
expected_head: &str,
|
|
effect: &NativeEffect,
|
|
now: DateTime<Utc>,
|
|
) -> Result<NativeEffectClaim> {
|
|
let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
|
let (h, d, j) = native_context(&tx, guard, grant, now)?;
|
|
ensure!(
|
|
j.head_sha256() == expected_head,
|
|
"UPDATE_HANDOFF_CAS_CONFLICT"
|
|
);
|
|
match effect {
|
|
NativeEffect::StopService { service } => ensure!(
|
|
guard.participant() == Participant::OriginalHelper
|
|
&& j.phase() == Phase::StopIntent
|
|
&& h.stop_set.contains(&native_service(*service)),
|
|
"UPDATE_NATIVE_STOP_ROLE"
|
|
),
|
|
NativeEffect::SavePredecessor { role } | NativeEffect::PublishReplacement { role } => {
|
|
ensure!(
|
|
guard.participant() == Participant::StableUpdater
|
|
&& j.phase() == Phase::ReplaceIntent,
|
|
"UPDATE_NATIVE_REPLACE_ROLE"
|
|
);
|
|
let last:Vec<u8>=tx.query_row("SELECT event FROM agent_update_handoff_events WHERE grant_id=?1 ORDER BY sequence DESC LIMIT 1",[grant.to_string()],|r|r.get(0))?;
|
|
ensure!(
|
|
serde_json::from_slice::<Event>(&last)?.evidence
|
|
== Evidence::ReplaceIntent {
|
|
role: native_role(*role)
|
|
},
|
|
"UPDATE_NATIVE_REPLACE_FILE"
|
|
);
|
|
if matches!(effect, NativeEffect::PublishReplacement { .. }) {
|
|
let save = native_key(&NativeEffect::SavePredecessor { role: *role })?;
|
|
let count:u64=tx.query_row("SELECT count(*) FROM agent_update_native_observations WHERE grant_id=?1 AND effect_key=?2",params![grant.to_string(),save],|r|r.get(0))?;
|
|
ensure!(count == 1, "UPDATE_NATIVE_SAVE_NOT_OBSERVED");
|
|
}
|
|
}
|
|
NativeEffect::SaveInstalledRecord {
|
|
old_sha256,
|
|
new_sha256,
|
|
}
|
|
| NativeEffect::PublishInstalledRecord {
|
|
old_sha256,
|
|
new_sha256,
|
|
} => {
|
|
ensure!(
|
|
guard.participant() == Participant::NewHelper
|
|
&& j.phase() == Phase::HealthVerified
|
|
&& *old_sha256 == h.predecessor_record_sha256
|
|
&& rmm_domain::agent_update::digest(new_sha256)
|
|
&& old_sha256 != new_sha256,
|
|
"UPDATE_NATIVE_INSTALLED_RECORD_BINDING"
|
|
);
|
|
if matches!(effect, NativeEffect::PublishInstalledRecord { .. }) {
|
|
let save = native_key(&NativeEffect::SaveInstalledRecord {
|
|
old_sha256: old_sha256.clone(),
|
|
new_sha256: new_sha256.clone(),
|
|
})?;
|
|
let count:u64=tx.query_row("SELECT count(*) FROM agent_update_native_observations WHERE grant_id=?1 AND effect_key=?2",params![grant.to_string(),save],|r|r.get(0))?;
|
|
ensure!(count == 1, "UPDATE_NATIVE_RECORD_SAVE_NOT_OBSERVED");
|
|
require_matching_record_save(&tx, grant, old_sha256, new_sha256)?;
|
|
}
|
|
}
|
|
// Rollback needs its own qualified event transition; never infer it
|
|
// from an uncertain replacement or silently restart the predecessor.
|
|
NativeEffect::RestorePredecessor { .. }
|
|
| NativeEffect::StartService { .. }
|
|
| NativeEffect::ReturnLedger => anyhow::bail!("UPDATE_NATIVE_SPECIAL_TRANSITION_REQUIRED"),
|
|
}
|
|
guard.verify_native_effect(&h, &d, effect, NativeEffectStage::Claim)?;
|
|
let result = insert_native_claim(&tx, &h, expected_head, effect.clone(), now)?;
|
|
guard.check(&tx)?;
|
|
tx.commit()?;
|
|
Ok(result)
|
|
}
|
|
pub fn observe_native_effect(
|
|
db: &mut Connection,
|
|
guard: &impl UpdateParticipantGuard,
|
|
claim: &NativeEffectClaim,
|
|
observation_sha256: &str,
|
|
now: DateTime<Utc>,
|
|
) -> Result<()> {
|
|
ensure!(
|
|
rmm_domain::agent_update::digest(observation_sha256),
|
|
"UPDATE_NATIVE_OBSERVATION_HASH"
|
|
);
|
|
let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
|
let (h, d, j) = native_context(&tx, guard, claim.grant_id, now)?;
|
|
ensure!(
|
|
h.owner_nonce == claim.owner_nonce && now >= claim.claimed_at,
|
|
"UPDATE_NATIVE_CLAIM_BINDING"
|
|
);
|
|
let raw: Vec<u8> = tx.query_row(
|
|
"SELECT claim FROM agent_update_native_claims WHERE grant_id=?1 AND effect_key=?2",
|
|
params![claim.grant_id.to_string(), native_key(&claim.effect)?],
|
|
|r| r.get(0),
|
|
)?;
|
|
ensure!(
|
|
raw == serde_json::to_vec(claim)?,
|
|
"UPDATE_NATIVE_CLAIM_CHANGED"
|
|
);
|
|
match claim.effect {
|
|
NativeEffect::StopService { .. } => ensure!(
|
|
guard.participant() == Participant::StableUpdater
|
|
&& matches!(
|
|
j.phase(),
|
|
Phase::StopIntent | Phase::AllStopped | Phase::UpdaterOwnsLedger
|
|
),
|
|
"UPDATE_NATIVE_STOP_OBSERVER"
|
|
),
|
|
NativeEffect::StartService { .. } => ensure!(
|
|
guard.participant() == Participant::NewHelper && j.phase() == Phase::LedgerReturnIntent,
|
|
"UPDATE_NATIVE_START_OBSERVER"
|
|
),
|
|
NativeEffect::SavePredecessor { .. } | NativeEffect::PublishReplacement { .. } => ensure!(
|
|
guard.participant() == Participant::StableUpdater
|
|
&& j.phase() == Phase::ReplaceIntent
|
|
&& j.head_sha256() == claim.head_sha256,
|
|
"UPDATE_NATIVE_FILE_OBSERVER"
|
|
),
|
|
NativeEffect::SaveInstalledRecord { .. } | NativeEffect::PublishInstalledRecord { .. } => {
|
|
ensure!(
|
|
guard.participant() == Participant::NewHelper
|
|
&& j.phase() == Phase::HealthVerified
|
|
&& j.head_sha256() == claim.head_sha256,
|
|
"UPDATE_NATIVE_RECORD_OBSERVER"
|
|
)
|
|
}
|
|
NativeEffect::ReturnLedger | NativeEffect::RestorePredecessor { .. } => {
|
|
anyhow::bail!("UPDATE_NATIVE_OBSERVATION_NOT_SUPPORTED")
|
|
}
|
|
}
|
|
guard.verify_native_effect(&h, &d, &claim.effect, NativeEffectStage::Observe)?;
|
|
tx.execute("INSERT INTO agent_update_native_observations(grant_id,effect_key,claim_sha256,observation_sha256,observed_at) VALUES(?1,?2,?3,?4,?5)",params![claim.grant_id.to_string(),native_key(&claim.effect)?,hash(&raw),observation_sha256,now.to_rfc3339()])?;
|
|
guard.check(&tx)?;
|
|
tx.commit()?;
|
|
Ok(())
|
|
}
|
|
/// ReturnIntent and exactly one future start sequence commit together while
|
|
/// the updater still holds the SAME lock. Returned values are evidence only;
|
|
/// only the live original worker's non-clone execution token may dispatch them.
|
|
pub fn prepare_return_and_starts(
|
|
db: &mut Connection,
|
|
guard: &impl UpdateParticipantGuard,
|
|
grant: Uuid,
|
|
expected_head: &str,
|
|
return_event: &[u8],
|
|
now: DateTime<Utc>,
|
|
) -> Result<PreparedReturnClaims> {
|
|
let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
|
let (h, d, mut j) = native_context(&tx, guard, grant, now)?;
|
|
ensure!(
|
|
guard.participant() == Participant::StableUpdater
|
|
&& j.phase() == Phase::PairVerified
|
|
&& j.head_sha256() == expected_head,
|
|
"UPDATE_NATIVE_RETURN_ROLE"
|
|
);
|
|
ensure!(
|
|
h.stop_set
|
|
.contains(&rmm_updater_handoff::Service::LinuxFullHelper),
|
|
"UPDATE_NATIVE_FULL_PROFILE_REQUIRED"
|
|
);
|
|
let missing:u64=tx.query_row("SELECT count(*) FROM agent_update_native_claims c LEFT JOIN agent_update_native_observations o ON c.grant_id=o.grant_id AND c.effect_key=o.effect_key WHERE c.grant_id=?1 AND o.effect_key IS NULL",[grant.to_string()],|r|r.get(0))?;
|
|
ensure!(missing == 0, "UPDATE_NATIVE_UNOBSERVED_EFFECT");
|
|
let parsed: Event = serde_json::from_slice(return_event)?;
|
|
ensure!(
|
|
parsed.evidence == Evidence::LedgerReturnIntent
|
|
&& parsed.observed_at == u64::try_from(now.timestamp())?,
|
|
"UPDATE_NATIVE_RETURN_EVENT"
|
|
);
|
|
verify_writer(&tx, guard, grant, &parsed)?;
|
|
guard.verify_native_effect(
|
|
&h,
|
|
&d,
|
|
&NativeEffect::ReturnLedger,
|
|
NativeEffectStage::Claim,
|
|
)?;
|
|
for service in [
|
|
NativeService::General,
|
|
NativeService::Full,
|
|
NativeService::Agent,
|
|
] {
|
|
guard.verify_native_effect(
|
|
&h,
|
|
&d,
|
|
&NativeEffect::StartService { service },
|
|
NativeEffectStage::ReserveFutureStart,
|
|
)?;
|
|
}
|
|
j.replay(return_event)?;
|
|
append_in(&tx, grant, expected_head, return_event, &parsed, &j)?;
|
|
let return_ledger =
|
|
insert_native_claim(&tx, &h, j.head_sha256(), NativeEffect::ReturnLedger, now)?;
|
|
let mut starts = Vec::new();
|
|
for service in [
|
|
NativeService::General,
|
|
NativeService::Full,
|
|
NativeService::Agent,
|
|
] {
|
|
starts.push(insert_native_claim(
|
|
&tx,
|
|
&h,
|
|
j.head_sha256(),
|
|
NativeEffect::StartService { service },
|
|
now,
|
|
)?);
|
|
}
|
|
guard.check(&tx)?;
|
|
tx.commit()?;
|
|
Ok(PreparedReturnClaims {
|
|
return_ledger,
|
|
starts: starts
|
|
.try_into()
|
|
.map_err(|_| anyhow::anyhow!("UPDATE_NATIVE_START_COUNT"))?,
|
|
})
|
|
}
|
|
|
|
/// Additive Fullhelper-only bridge. No freely chosen paths, command, event or
|
|
/// current-ready assertion can cross this protocol.
|
|
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct NativeControlRequest {
|
|
pub operation: String,
|
|
pub schema_version: u32,
|
|
pub challenge: Uuid,
|
|
pub tenant_id: Uuid,
|
|
pub asset_id: Uuid,
|
|
pub agent_id: Uuid,
|
|
pub enrollment_generation: u64,
|
|
pub assignment_version: u64,
|
|
pub grant_id: Uuid,
|
|
pub owner_nonce: Uuid,
|
|
pub handoff_sha256: String,
|
|
pub method: NativeControlOperation,
|
|
}
|
|
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
|
|
#[serde(tag = "method", rename_all = "snake_case", deny_unknown_fields)]
|
|
pub enum NativeControlOperation {
|
|
ReadOriginal,
|
|
ClaimStop {
|
|
expected_head_sha256: String,
|
|
service: NativeService,
|
|
},
|
|
ObserveStarts {
|
|
services: Vec<rmm_updater_handoff::StartedService>,
|
|
observation_sha256: String,
|
|
},
|
|
Health {
|
|
receipt: rmm_updater_handoff::SignedHealth,
|
|
},
|
|
Finalize,
|
|
}
|
|
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct NativeControlReply {
|
|
pub schema_version: u32,
|
|
pub challenge: Uuid,
|
|
pub tenant_id: Uuid,
|
|
pub asset_id: Uuid,
|
|
pub agent_id: Uuid,
|
|
pub enrollment_generation: u64,
|
|
pub assignment_version: u64,
|
|
pub grant_id: Uuid,
|
|
pub owner_nonce: Uuid,
|
|
pub handoff_sha256: String,
|
|
pub ready: bool,
|
|
pub proof: Option<rmm_domain::agent_update::UpdateInflightProof>,
|
|
pub original_outcome_base64url: Option<String>,
|
|
pub claim: Option<NativeEffectClaim>,
|
|
/// Only ReadOriginal; exact retained execution_evidence.start bytes,
|
|
/// bounded to 512KiB before canonical Base64url encoding, never rewritten.
|
|
pub original_start_base64url: Option<String>,
|
|
}
|
|
|
|
fn require_matching_record_save(
|
|
db: &Connection,
|
|
grant: Uuid,
|
|
old_sha256: &str,
|
|
new_sha256: &str,
|
|
) -> Result<()> {
|
|
let (raw,digest,observed_claim):(Vec<u8>,String,String)=db.query_row(
|
|
"SELECT c.claim,c.claim_sha256,o.claim_sha256 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='save_installed_record'",
|
|
[grant.to_string()],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?)))?;
|
|
let claim: NativeEffectClaim = serde_json::from_slice(&raw)?;
|
|
ensure!(
|
|
hash(&raw) == digest
|
|
&& digest == observed_claim
|
|
&& serde_json::to_vec(&claim)? == raw
|
|
&& claim.grant_id == grant
|
|
&& claim.effect
|
|
== NativeEffect::SaveInstalledRecord {
|
|
old_sha256: old_sha256.into(),
|
|
new_sha256: new_sha256.into()
|
|
},
|
|
"UPDATE_NATIVE_RECORD_PUBLISH_PAIR_CHANGED"
|
|
);
|
|
Ok(())
|
|
}
|
|
#[cfg(test)]
|
|
mod native_record_tests {
|
|
use super::*;
|
|
#[test]
|
|
fn record_publish_requires_exact_saved_record_even_when_original_head_did_not_change() {
|
|
let db = Connection::open_in_memory().unwrap();
|
|
db.execute_batch("CREATE TABLE agent_update_native_claims(grant_id TEXT,effect_key TEXT,claim BLOB,claim_sha256 TEXT); CREATE TABLE agent_update_native_observations(grant_id TEXT,effect_key TEXT,claim_sha256 TEXT);").unwrap();
|
|
let grant = Uuid::new_v4();
|
|
let head = "12".repeat(32);
|
|
let old = "34".repeat(32);
|
|
let new = "56".repeat(32);
|
|
let claim = NativeEffectClaim {
|
|
grant_id: grant,
|
|
owner_nonce: Uuid::new_v4(),
|
|
head_sha256: head.clone(),
|
|
effect: NativeEffect::SaveInstalledRecord {
|
|
old_sha256: old.clone(),
|
|
new_sha256: new.clone(),
|
|
},
|
|
claimed_at: Utc::now(),
|
|
};
|
|
let raw = serde_json::to_vec(&claim).unwrap();
|
|
let digest = hash(&raw);
|
|
db.execute(
|
|
"INSERT INTO agent_update_native_claims VALUES(?1,'save_installed_record',?2,?3)",
|
|
params![grant.to_string(), raw, digest],
|
|
)
|
|
.unwrap();
|
|
db.execute(
|
|
"INSERT INTO agent_update_native_observations VALUES(?1,'save_installed_record',?2)",
|
|
params![grant.to_string(), digest],
|
|
)
|
|
.unwrap();
|
|
require_matching_record_save(&db, grant, &old, &new).unwrap();
|
|
assert!(require_matching_record_save(&db, grant, &old, &"78".repeat(32)).is_err());
|
|
let stored: Vec<u8> = db
|
|
.query_row("SELECT claim FROM agent_update_native_claims", [], |r| {
|
|
r.get(0)
|
|
})
|
|
.unwrap();
|
|
assert_eq!(stored, raw);
|
|
assert_eq!(
|
|
serde_json::from_slice::<NativeEffectClaim>(&stored)
|
|
.unwrap()
|
|
.head_sha256,
|
|
head
|
|
);
|
|
}
|
|
}
|
|
|
|
/// Read the exact immutable native reservation, never a dispatch token.
|
|
pub fn read_native_claim(
|
|
db: &Connection,
|
|
guard: &impl ExecutorLedgerGuard,
|
|
grant: Uuid,
|
|
effect: &NativeEffect,
|
|
) -> Result<NativeEffectClaim> {
|
|
read(db, guard, grant)?;
|
|
let raw: Vec<u8> = db.query_row(
|
|
"SELECT claim FROM agent_update_native_claims WHERE grant_id=?1 AND effect_key=?2",
|
|
params![grant.to_string(), native_key(effect)?],
|
|
|r| r.get(0),
|
|
)?;
|
|
let claim: NativeEffectClaim = serde_json::from_slice(&raw)?;
|
|
ensure!(
|
|
claim.grant_id == grant && claim.effect == *effect,
|
|
"UPDATE_NATIVE_ORIGINAL_CLAIM_REQUIRED"
|
|
);
|
|
Ok(claim)
|
|
}
|
|
/// No new capture/checkpoint or readiness is generated by this read.
|
|
pub fn current_proof(
|
|
db: &Connection,
|
|
guard: &impl ExecutorLedgerGuard,
|
|
grant: Uuid,
|
|
) -> Result<Option<rmm_domain::agent_update::UpdateInflightProof>> {
|
|
read(db, guard, grant)?;
|
|
proof_locked(db, grant)
|
|
}
|
|
/// Actual local control application, recorded by HelperSync in the SAME
|
|
/// transaction as its verified original decision. Never supplied by IPC.
|
|
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct AppliedUpdateSync {
|
|
pub schema_version: u32,
|
|
pub grant_id: Uuid,
|
|
pub decision_id: Uuid,
|
|
pub request_sha256: String,
|
|
pub response_protobuf_sha256: String,
|
|
pub applied_at: DateTime<Utc>,
|
|
}
|
|
pub(crate) fn record_applied_sync(db: &Connection, witness: &AppliedUpdateSync) -> Result<()> {
|
|
ensure!(
|
|
witness.schema_version == 1
|
|
&& !witness.grant_id.is_nil()
|
|
&& !witness.decision_id.is_nil()
|
|
&& rmm_domain::agent_update::digest(&witness.request_sha256)
|
|
&& rmm_domain::agent_update::digest(&witness.response_protobuf_sha256),
|
|
"UPDATE_APPLIED_SYNC_SHAPE"
|
|
);
|
|
let raw = serde_json::to_vec(witness)?;
|
|
db.execute("INSERT INTO agent_update_sync_applied(grant_id,decision_id,witness,witness_sha256) VALUES(?1,?2,?3,?4)",params![witness.grant_id.to_string(),witness.decision_id.to_string(),raw,hash(&raw)])?;
|
|
Ok(())
|
|
}
|
|
pub fn read_applied_sync(
|
|
db: &Connection,
|
|
guard: &impl ExecutorLedgerGuard,
|
|
grant: Uuid,
|
|
decision: Uuid,
|
|
) -> Result<AppliedUpdateSync> {
|
|
use prost::Message;
|
|
guard.check(db)?;
|
|
let (raw,digest):(Vec<u8>,String)=db.query_row("SELECT witness,witness_sha256 FROM agent_update_sync_applied WHERE grant_id=?1 AND decision_id=?2",params![grant.to_string(),decision.to_string()],|r|Ok((r.get(0)?,r.get(1)?)))?;
|
|
let witness: AppliedUpdateSync = serde_json::from_slice(&raw)?;
|
|
ensure!(
|
|
raw.len() <= 2048
|
|
&& hash(&raw) == digest
|
|
&& serde_json::to_vec(&witness)? == raw
|
|
&& witness.schema_version == 1
|
|
&& witness.grant_id == grant
|
|
&& witness.decision_id == decision,
|
|
"UPDATE_APPLIED_SYNC_CHANGED"
|
|
);
|
|
let (saved_response, request): (Vec<u8>, Vec<u8>) = db.query_row(
|
|
"SELECT response,request FROM helper_sync_decisions WHERE decision_id=?1",
|
|
[decision.to_string()],
|
|
|r| Ok((r.get(0)?, r.get(1)?)),
|
|
)?;
|
|
let response: crate::helper_reconcile::SignedResponse =
|
|
serde_json::from_slice(&saved_response)?;
|
|
let protobuf = rmm_protocol::SyncResponse {
|
|
decision_bytes: response.decision_bytes,
|
|
signature: response.signature,
|
|
}
|
|
.encode_to_vec();
|
|
ensure!(
|
|
hash(&protobuf) == witness.response_protobuf_sha256
|
|
&& hash(&request) == witness.request_sha256,
|
|
"UPDATE_APPLIED_SYNC_ORIGINAL_BYTES_CHANGED"
|
|
);
|
|
guard.check(db)?;
|
|
Ok(witness)
|
|
}
|