Files
rust-discovery/crates/agent-core/src/ledger.rs
T

382 lines
15 KiB
Rust

//! Connection-level ledger rules, with OS path/lock/ACL handling left to adapters.
use crate::auth::{Outcome, Request, VerifiedHistoricalDenial};
use anyhow::{Context, Result, ensure};
use chrono::{DateTime, Utc};
use rmm_domain::jobs::{ExecutionPermitPayload, JobPayload};
use rmm_domain::{
jobs::hash,
reconciliation::{ReconciledOutcome, canonical_outcome_bytes},
};
use rusqlite::{OptionalExtension, TransactionBehavior, params};
use uuid::Uuid;
/// Finite 1 GiB bound for durable agent/helper history. Unexpected page sizes
/// are refused rather than silently multiplying the byte limit. No compaction
/// or tombstone deletion occurs here; SQLITE_FULL must still fail closed.
pub fn bounded_journal_capacity(db: &rusqlite::Connection) -> Result<()> {
let page_size: u32 = db.query_row("PRAGMA page_size", [], |r| r.get(0))?;
ensure!(page_size == 4096, "JOURNAL_PAGE_SIZE_UNSUPPORTED");
let maximum: u32 = db.query_row("PRAGMA max_page_count=262144", [], |r| r.get(0))?;
ensure!(maximum == 262144, "JOURNAL_STORAGE_CAPACITY_BLOCKED");
Ok(())
}
/// The platform adapter must securely open/lock the file before calling this.
/// No file creation, ACL repair or journal reset is performed here.
pub fn initialize_ledger(db: &rusqlite::Connection) -> Result<()> {
bounded_journal_capacity(db)?;
db.execute_batch("PRAGMA synchronous=FULL; PRAGMA journal_mode=DELETE;
CREATE TABLE IF NOT EXISTS consumed(grant_id TEXT PRIMARY KEY, agent TEXT NOT NULL, generation INTEGER NOT NULL,
job TEXT NOT NULL, attempt TEXT NOT NULL, result BLOB, UNIQUE(agent,generation,job,attempt));
CREATE TABLE IF NOT EXISTS execution_evidence(grant_id TEXT PRIMARY KEY, start BLOB NOT NULL, outcome BLOB);")?;
let check: String = db.query_row("PRAGMA integrity_check", [], |r| r.get(0))?;
ensure!(check == "ok", "JOURNAL_INTEGRITY");
Ok(())
}
/// Before a human WebUI closure replaces the unresolved local outcome, keep the
/// exact original outcome bytes once. A differing second copy fails closed.
pub(crate) fn retain_closure_original(
db: &rusqlite::Connection,
grant: Uuid,
original: &[u8],
closure: &[u8],
) -> Result<()> {
db.execute_batch("CREATE TABLE IF NOT EXISTS unknown_closure_originals(grant_id TEXT PRIMARY KEY, original_outcome BLOB NOT NULL, closure_outcome BLOB NOT NULL);")?;
let existing: Option<(Vec<u8>, Vec<u8>)> = db
.query_row(
"SELECT original_outcome,closure_outcome FROM unknown_closure_originals WHERE grant_id=?1",
[grant.to_string()],
|r| Ok((r.get(0)?, r.get(1)?)),
)
.optional()?;
match existing {
Some((old, done)) => ensure!(
done == closure && (old == original || original == closure),
"CLOSURE_ORIGINAL_CHANGED"
),
None => {
db.execute(
"INSERT INTO unknown_closure_originals VALUES(?1,?2,?3)",
params![grant.to_string(), original, closure],
)?;
}
}
Ok(())
}
/// Legacy split reservation API retained for old fixtures/readers. Production
/// callers use begin_execution so a crash cannot lose the original start witness.
pub fn consume(db: &mut rusqlite::Connection, p: &ExecutionPermitPayload) -> Result<()> {
let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
consume_in(&tx, p)?;
tx.commit()?;
Ok(())
}
pub(crate) fn consume_in(db: &rusqlite::Connection, p: &ExecutionPermitPayload) -> Result<()> {
let unresolved: i64 = db.query_row(
"SELECT count(*) FROM consumed WHERE result IS NULL",
[],
|r| r.get(0),
)?;
ensure!(unresolved == 0, "UNRESOLVED_EFFECT_RESOURCE_LOCKED");
db.execute(
"INSERT INTO consumed(grant_id,agent,generation,job,attempt) VALUES(?1,?2,?3,?4,?5)",
params![
p.grant_id.to_string(),
p.agent_id.to_string(),
p.enrollment_generation,
p.job_id.to_string(),
p.attempt_id.to_string()
],
)?;
Ok(())
}
/// Caller has already checked the signature, qualified clock, fresh Sync and
/// policy. Persist consumption and the exact legacy start witness atomically.
pub fn begin_execution(
db: &mut rusqlite::Connection,
permit: &ExecutionPermitPayload,
request: &Request,
previous_boot_id: Uuid,
recorded_at: DateTime<Utc>,
) -> Result<()> {
validate_start_request(permit, request)?;
let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
consume_in(&tx, permit)?;
save_start(&tx, permit, request, previous_boot_id, recorded_at)?;
tx.commit()?;
Ok(())
}
/// Retained evidence only. In particular, a legacy consumption without its
/// original start can never be repaired into a proven nonstart by this path.
pub(crate) fn existing_no_start(
db: &rusqlite::Connection,
original: &VerifiedHistoricalDenial,
) -> Result<Option<Outcome>> {
let p = &original.permit;
type Row = (
String,
String,
u64,
String,
String,
Option<Vec<u8>>,
Option<Vec<u8>>,
Option<Vec<u8>>,
);
let mut statement = db.prepare("SELECT c.grant_id,c.agent,c.generation,c.job,c.attempt,c.result,e.start,e.outcome FROM consumed c LEFT JOIN execution_evidence e USING(grant_id) WHERE c.grant_id=?1 OR (c.agent=?2 AND c.generation=?3 AND c.job=?4 AND c.attempt=?5)")?;
let rows = statement
.query_map(
params![
p.grant_id.to_string(),
p.agent_id.to_string(),
p.enrollment_generation,
p.job_id.to_string(),
p.attempt_id.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)?,
))
},
)?
.collect::<rusqlite::Result<Vec<Row>>>()?;
ensure!(rows.len() <= 1, "DENIAL_EXISTING_ATTEMPT_CONFLICT");
let Some((grant, agent, generation, job, attempt, finished, start, outcome)) =
rows.into_iter().next()
else {
return Ok(None);
};
ensure!(
grant == p.grant_id.to_string()
&& agent == p.agent_id.to_string()
&& generation == p.enrollment_generation
&& job == p.job_id.to_string()
&& attempt == p.attempt_id.to_string(),
"DENIAL_EXISTING_ATTEMPT_CONFLICT"
);
let Some(start) = start else {
return Ok(Some(Outcome::unknown("HELPER_PREVIOUS_START_UNRESOLVED")));
};
let start: serde_json::Value = serde_json::from_slice(&start)?;
let saved: Request = serde_json::from_value(start["request"].clone())?;
ensure!(
serde_json::to_vec(&saved)? == serde_json::to_vec(&original.request)?,
"DENIAL_EXISTING_REQUEST_CONFLICT"
);
let boot: Uuid = serde_json::from_value(start["previous_boot_id"].clone())?;
ensure!(!boot.is_nil(), "DENIAL_EXISTING_ORIGINAL_BOOT_MISSING");
let _: DateTime<Utc> = serde_json::from_value(start["reserved_at"].clone())?;
if let (Some(a), Some(b)) = (&finished, &outcome) {
ensure!(
canonical(a)? == canonical(b)?,
"DENIAL_EXISTING_OUTCOME_CONFLICT"
);
}
let Some(bytes) = outcome.or(finished) else {
return Ok(Some(Outcome::unknown("HELPER_PREVIOUS_EFFECT_UNRESOLVED")));
};
Ok(Some(serde_json::from_slice(&canonical(&bytes)?)?))
}
/// Called only inside HelperSync's guarded Immediate transaction after its
/// independent intent/lineage checks. Never finish/unlock here. All three
/// witnesses commit together, so no crash can expose a bare new consumption.
pub(crate) fn record_no_start_in(
db: &rusqlite::Connection,
original: &VerifiedHistoricalDenial,
boot: Uuid,
observed_at: DateTime<Utc>,
witness: &crate::helper_reconcile::NoDispatchObservation,
) -> Result<Outcome> {
let p = &original.permit;
validate_start_request(p, &original.request)?;
consume_in(db, p)?;
save_start(db, p, &original.request, boot, observed_at)?;
let outcome = Outcome {
state: "failed".into(),
evidence: serde_json::json!({"not_started":true,"postconditions_passed":false,
"deny_only":true,"reservation_only":true,"original_request_sha256":original.request_sha256,
"intent_id":witness.intent_id,"intent_sha256":witness.intent_sha256,
"intent_recorded_at":witness.intent_recorded_at,"observed_at":observed_at}),
..Outcome::unknown("HELPER_ABANDONED_BEFORE_DISPATCH")
};
persist_outcome_in(db, p, &outcome)?;
Ok(outcome)
}
pub(crate) fn validate_start_request(p: &ExecutionPermitPayload, request: &Request) -> Result<()> {
ensure!(
request.job_bytes.len() <= 65536
&& request.permit_bytes.len() <= 8192
&& request.signature.len() == 64,
"START_REQUEST_SIZE"
);
let saved: ExecutionPermitPayload = serde_json::from_slice(&request.permit_bytes)?;
let j: JobPayload = serde_json::from_slice(&request.job_bytes)?;
ensure!(
saved == *p
&& request.authorization_id == p.authorization_id
&& request.plan_hash == p.plan_hash
&& p.job_payload_hash == hash(&request.job_bytes)
&& p.tenant_id == j.tenant_id
&& p.asset_id == j.asset_id
&& p.agent_id == j.agent_id
&& p.enrollment_generation == j.enrollment_generation
&& p.assignment_version == j.assignment_version
&& p.job_id == j.job_id
&& p.attempt_id == j.attempt_id
&& p.action == j.action.name()
&& p.execution_identity == j.execution_identity
&& p.max_runtime_seconds == j.max_runtime_seconds,
"STORED_START_REQUEST_BINDING"
);
Ok(())
}
fn canonical(bytes: &[u8]) -> Result<Vec<u8>> {
Ok(canonical_outcome_bytes(&serde_json::from_slice::<
ReconciledOutcome,
>(bytes)?)?)
}
/// Compare-and-set the original completion evidence WITHOUT releasing a lock.
/// Existing identical bytes are preserved; contradictory completions fail closed.
pub fn persist_outcome(
db: &rusqlite::Connection,
p: &ExecutionPermitPayload,
outcome: &Outcome,
) -> Result<()> {
let tx = db.unchecked_transaction()?;
persist_outcome_in(&tx, p, outcome)?;
tx.commit()?;
Ok(())
}
pub(crate) fn persist_outcome_in(
db: &rusqlite::Connection,
p: &ExecutionPermitPayload,
outcome: &Outcome,
) -> Result<Vec<u8>> {
ensure!(
matches!(
outcome.state.as_str(),
"unknown" | "awaiting_reboot" | "succeeded" | "failed" | "cancelled" | "expired"
),
"INVALID_STORED_OUTCOME_STATE"
);
type CompletionRow = (
String,
u64,
String,
String,
Vec<u8>,
Option<Vec<u8>>,
Option<Vec<u8>>,
);
let row:Option<CompletionRow>=db.query_row(
"SELECT c.agent,c.generation,c.job,c.attempt,e.start,e.outcome,c.result FROM consumed c JOIN execution_evidence e USING(grant_id) WHERE c.grant_id=?1",[p.grant_id.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)?))).optional()?;
let (agent, generation, job, attempt, start, prior, finished) =
row.context("STORED_COMPLETION_START_MISSING")?;
ensure!(
agent == p.agent_id.to_string()
&& generation == p.enrollment_generation
&& job == p.job_id.to_string()
&& attempt == p.attempt_id.to_string(),
"STORED_COMPLETION_CONSUMPTION_BINDING"
);
let start: serde_json::Value = serde_json::from_slice(&start)?;
let request: Request = serde_json::from_value(start["request"].clone())?;
validate_start_request(p, &request)?;
let bytes = serde_json::to_vec(outcome)?;
let expected = canonical(&bytes)?;
if let Some(resolved) = crate::windows_system_nonstart::effective_outcome(db, None, p.grant_id)?
{
ensure!(
canonical(&resolved)? == expected,
"STORED_COMPLETION_CONFLICT"
);
return Ok(resolved);
}
for previous in [&prior, &finished].into_iter().flatten() {
ensure!(
canonical(previous)? == expected,
"STORED_COMPLETION_CONFLICT"
);
}
if prior.is_none() {
ensure!(
db.execute(
"UPDATE execution_evidence SET outcome=?2 WHERE grant_id=?1 AND outcome IS NULL",
params![p.grant_id.to_string(), bytes]
)? == 1,
"STORED_COMPLETION_CAS_CONFLICT"
);
}
Ok(prior.unwrap_or(bytes))
}
/// Called only AFTER the corresponding journal result committed. A crash before
/// this call retains the original outcome for the normal signed reconciliation.
pub fn finish(
db: &rusqlite::Connection,
p: &ExecutionPermitPayload,
outcome: &Outcome,
) -> Result<()> {
let tx = db.unchecked_transaction()?;
let bytes = persist_outcome_in(&tx, p, outcome)?;
if outcome.state != "unknown" && outcome.state != "awaiting_reboot" {
tx.execute(
"UPDATE consumed SET result=?2 WHERE grant_id=?1 AND result IS NULL",
params![p.grant_id.to_string(), bytes],
)?;
}
tx.commit()?;
Ok(())
}
/// Persist the original boot and exact signed request BEFORE any reboot/effect.
/// Awaiting/unknown outcomes never release consumed.result's resource lock.
pub fn save_start(
db: &rusqlite::Connection,
permit: &ExecutionPermitPayload,
request: &Request,
previous_boot_id: Uuid,
recorded_at: DateTime<Utc>,
) -> Result<()> {
let bytes = start_witness_bytes(permit, request, previous_boot_id, recorded_at)?;
db.execute(
"INSERT INTO execution_evidence(grant_id,start) VALUES(?1,?2)",
rusqlite::params![permit.grant_id.to_string(), bytes],
)?;
Ok(())
}
/// Exact existing start codec, also used to bind the immutable update handoff
/// before atomic consumption. This does not persist or authorize anything.
pub fn start_witness_bytes(
_permit: &ExecutionPermitPayload,
request: &Request,
previous_boot_id: Uuid,
recorded_at: DateTime<Utc>,
) -> Result<Vec<u8>> {
let job: JobPayload = serde_json::from_slice(&request.job_bytes)?;
ensure!(!previous_boot_id.is_nil(), "ORIGINAL_BOOT_MISSING");
let deadline = match job.action {
rmm_domain::jobs::Action::Reboot {
reconnect_timeout_seconds,
..
} => Some(recorded_at + chrono::Duration::seconds(reconnect_timeout_seconds.into())),
_ => None,
};
let evidence = serde_json::json!({"previous_boot_id":previous_boot_id.to_string(),
"reserved_at":recorded_at,"reconnect_deadline":deadline,"request":request,
"reauthentication_required":true,"postconditions_passed":false});
Ok(serde_json::to_vec(&evidence)?)
}