Qualify atomic deny-only helper abandonment on actual Linux VM
Rust development slice / linux (push) Failing after 7s

This commit is contained in:
2026-11-14 06:48:32 +01:00
parent 44c45c15b9
commit 67370d21a3
7 changed files with 1174 additions and 14 deletions
+49 -9
View File
@@ -52,6 +52,40 @@ impl Binding {
request: &Request,
now: DateTime<Utc>,
verifier: &impl Ed25519Verifier,
) -> Result<(JobPayload, ExecutionPermitPayload)> {
let (job, p) = self.verify_signed_request(request, verifier)?;
ensure!(
permit_window(&job, &p) && now >= p.not_before && now < p.start_before,
"PERMIT_TIME"
);
Ok((job, p))
}
/// Evidence-only verification. This never supplies a current start window
/// and cannot be substituted for verify_with at an execution boundary.
pub fn verify_historical_for_denial_with(
&self,
request: &Request,
identity: HelperIdentity,
verifier: &impl Ed25519Verifier,
) -> Result<VerifiedHistoricalDenial> {
let (job, permit) = self.verify_signed_request(request, verifier)?;
ensure!(permit_window(&job, &permit), "PERMIT_TIME");
ensure!(
job.execution_identity == identity.as_str()
&& matches!(&job.action, rmm_domain::jobs::Action::SetServiceState { state, .. }
if matches!(state.as_str(), "running" | "stopped")),
"DENIAL_HELPER_SCOPE"
);
Ok(VerifiedHistoricalDenial {
request: request.clone(),
permit,
request_sha256: hash(&serde_json::to_vec(request)?),
})
}
fn verify_signed_request(
&self,
request: &Request,
verifier: &impl Ed25519Verifier,
) -> Result<(JobPayload, ExecutionPermitPayload)> {
let job = self.job(&request.job_bytes)?;
ensure!(
@@ -91,19 +125,25 @@ impl Binding {
&& p.max_runtime_seconds == job.max_runtime_seconds,
"PERMIT_BINDING"
);
ensure!(
p.not_before >= job.not_before
&& p.start_before <= job.start_before
&& p.not_before < p.start_before
&& (p.start_before - p.not_before).num_seconds() <= 60
&& now >= p.not_before
&& now < p.start_before,
"PERMIT_TIME"
);
Ok((job, p))
}
}
fn permit_window(job: &JobPayload, p: &ExecutionPermitPayload) -> bool {
p.not_before >= job.not_before
&& p.start_before <= job.start_before
&& p.not_before < p.start_before
&& (p.start_before - p.not_before).num_seconds() <= 60
}
/// Not serializable or constructible by an IPC caller. Only the deny-only
/// helper path consumes this evidence; it is never an execution authorization.
pub struct VerifiedHistoricalDenial {
pub(crate) request: Request,
pub(crate) permit: ExecutionPermitPayload,
pub(crate) request_sha256: String,
}
#[derive(Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Request {
+250 -1
View File
@@ -2,7 +2,7 @@
//! an operation or grants authority from an agent-provided ready/unlock flag.
//! Both general and APT listeners must use the SAME executor.lock and SQLite DB.
use crate::auth::HelperIdentity;
use crate::auth::{Binding, Request};
use crate::auth::{Binding, Outcome, Request};
use crate::crypto::{DefaultVerifier, Ed25519Verifier};
use anyhow::{Context, Result, ensure};
use chrono::{DateTime, Utc};
@@ -27,6 +27,72 @@ pub trait BootSource {
pub trait ExecutorLedgerGuard {
fn check(&self, db: &Connection) -> Result<()>;
}
/// OS adapter contract, not an IPC assertion. The implementation must pin the
/// live helper PID/creation and ledger/lock file identities, and independently
/// read the fixed protected intent store's immutable known_no_dispatch CAS.
/// The same executor guard stays held throughout this check and the commit.
pub trait NoStartGuard: ExecutorLedgerGuard {
fn live_instance_sha256(&self) -> Result<String>;
fn verify_no_dispatch(
&self,
original: &Request,
anchor: &NoStartAnchor,
) -> Result<NoDispatchObservation>;
}
/// Trusted adapter return value only: deliberately has no IPC deserializer.
#[derive(Debug, PartialEq, Eq)]
pub struct NoDispatchObservation {
pub intent_id: Uuid,
pub intent_sha256: String,
pub intent_recorded_at: DateTime<Utc>,
pub original_boot_id: Uuid,
}
/// Historical ready context, never a new lease or execution authorization.
/// Deserialization alone conveys no authority: every field is checked against
/// the still-held helper instance and the original independently stored history.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NoStartAnchor {
journal_id: Uuid,
checkpoint: u64,
decision_id: Uuid,
connection_generation: u64,
boot_id: Uuid,
binding_sha256: String,
execution_identity: String,
helper_instance_sha256: String,
helper_born_at: DateTime<Utc>,
sync_request_sha256: String,
signed_response_sha256: String,
ledger_fingerprint: String,
captured_at: DateTime<Utc>,
}
impl NoStartAnchor {
pub fn journal_id(&self) -> Uuid {
self.journal_id
}
pub fn checkpoint(&self) -> u64 {
self.checkpoint
}
pub fn decision_id(&self) -> Uuid {
self.decision_id
}
pub fn connection_generation(&self) -> u64 {
self.connection_generation
}
pub fn boot_id(&self) -> Uuid {
self.boot_id
}
pub fn helper_instance_sha256(&self) -> &str {
&self.helper_instance_sha256
}
pub fn sync_request_sha256(&self) -> &str {
&self.sync_request_sha256
}
pub fn signed_response_sha256(&self) -> &str {
&self.signed_response_sha256
}
}
/// Same two fields as public SyncResponse, without adding a new dependency or
/// wire type. RPC glue copies the ORIGINAL bytes/signature, never reserializes.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
@@ -122,6 +188,183 @@ impl<V: Ed25519Verifier> HelperSync<V> {
pub fn active_generation(&self) -> Option<u64> {
self.lease.as_ref().map(|lease| lease.generation)
}
/// Capture only an actually confirmed live ready lease, before an intent
/// or fence closes it. Retaining this anchor cannot keep that lease alive.
pub fn no_start_anchor(
&self,
db: &Connection,
guard: &impl NoStartGuard,
generation: u64,
clock: &impl Clock,
boot: &impl BootSource,
) -> Result<NoStartAnchor> {
ensure!(
self.can_start(db, guard, generation, clock, boot),
"DENIAL_READY_ANCHOR_REQUIRED"
);
let lease = self
.lease
.as_ref()
.context("DENIAL_READY_ANCHOR_REQUIRED")?;
let meta = metadata(db)?;
let (response, request): (Vec<u8>, Vec<u8>) = db.query_row(
"SELECT response,request FROM helper_sync_decisions WHERE decision_id=?1",
[lease.decision_id.to_string()],
|r| Ok((r.get(0)?, r.get(1)?)),
)?;
let instance = guard.live_instance_sha256()?;
ensure!(digest(&instance), "DENIAL_HELPER_INSTANCE_INVALID");
let capture: Vec<u8> = db.query_row(
"SELECT snapshot FROM helper_sync_captures WHERE checkpoint=?1",
[meta.checkpoint],
|r| r.get(0),
)?;
let capture: Snapshot = serde_json::from_slice(&capture)?;
let anchor = NoStartAnchor {
journal_id: meta.journal_id,
checkpoint: meta.checkpoint,
decision_id: lease.decision_id,
connection_generation: generation,
boot_id: lease.boot_id,
binding_sha256: hash(&serde_json::to_vec(&self.binding)?),
execution_identity: self.identity.as_str().into(),
helper_instance_sha256: instance,
helper_born_at: self.born,
sync_request_sha256: hash(&request),
signed_response_sha256: hash(&response),
ledger_fingerprint: lease.fingerprint.clone(),
captured_at: capture.captured_at,
};
self.verify_no_start_anchor(db, guard, &anchor, clock, boot)?;
Ok(anchor)
}
/// Deny-only: the grant may be expired, but no historical timestamp is ever
/// passed to an execute verifier. Existing consumption is immutable. A new
/// c/start/no-effect outcome is committed atomically and remains locked for
/// the ordinary independently signed Sync decision.
pub fn abandon_no_start(
&mut self,
db: &mut Connection,
guard: &impl NoStartGuard,
anchor: &NoStartAnchor,
request: &Request,
clock: &impl Clock,
boot: &impl BootSource,
) -> Result<Outcome> {
self.close();
guard.check(db)?;
let original = self.binding.verify_historical_for_denial_with(
request,
self.identity,
&self.verifier,
)?;
let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
if let Some(outcome) = crate::ledger::existing_no_start(&tx, &original)? {
// No changed row and no classification of a missing original start.
tx.commit()?;
return Ok(outcome);
}
self.verify_no_start_anchor(&tx, guard, anchor, clock, boot)?;
let observation = guard.verify_no_dispatch(request, anchor)?;
let now = self.verify_no_start_anchor(&tx, guard, anchor, clock, boot)?;
ensure!(
!observation.intent_id.is_nil()
&& digest(&observation.intent_sha256)
&& observation.original_boot_id == anchor.boot_id
&& observation.intent_recorded_at >= anchor.captured_at
&& observation.intent_recorded_at <= now,
"DENIAL_INTENT_BINDING"
);
let outcome =
crate::ledger::record_no_start_in(&tx, &original, anchor.boot_id, now, &observation)?;
guard.check(&tx)?;
ensure!(
guard.live_instance_sha256()? == anchor.helper_instance_sha256,
"DENIAL_HELPER_INSTANCE_CHANGED"
);
ensure!(
guard.verify_no_dispatch(request, anchor)? == observation,
"DENIAL_INTENT_CHANGED_DURING_COMMIT"
);
tx.commit()?;
Ok(outcome)
}
fn verify_no_start_anchor(
&self,
db: &Connection,
guard: &impl NoStartGuard,
anchor: &NoStartAnchor,
clock: &impl Clock,
boot: &impl BootSource,
) -> Result<DateTime<Utc>> {
guard.check(db)?;
let now = clock.now()?;
ensure!(
anchor.helper_born_at == self.born
&& now >= self.born
&& boot.current_boot()? == anchor.boot_id
&& !anchor.boot_id.is_nil()
&& anchor.execution_identity == self.identity.as_str()
&& anchor.binding_sha256 == hash(&serde_json::to_vec(&self.binding)?)
&& digest(&anchor.helper_instance_sha256)
&& guard.live_instance_sha256()? == anchor.helper_instance_sha256,
"DENIAL_HELPER_CONTEXT_CHANGED"
);
let meta = metadata(db)?;
ensure!(
meta.fault.is_none()
&& meta.journal_id == anchor.journal_id
&& meta.checkpoint == anchor.checkpoint
&& meta.decision == Some(anchor.decision_id)
&& meta.generation == anchor.connection_generation
&& ledger_fingerprint(db)? == anchor.ledger_fingerprint,
"DENIAL_HELPER_LINEAGE_CHANGED"
);
// Exact equality is deliberate: a first implementation refuses even
// legitimate intervening progress rather than inventing lineage links.
verify_checkpoint_repair_history_with(
db,
&self.binding,
None,
self.identity,
&self.verifier,
)?;
let (response, raw): (Vec<u8>, Vec<u8>) = db.query_row(
"SELECT response,request FROM helper_sync_decisions WHERE decision_id=?1",
[anchor.decision_id.to_string()],
|r| Ok((r.get(0)?, r.get(1)?)),
)?;
ensure!(
hash(&response) == anchor.signed_response_sha256
&& hash(&raw) == anchor.sync_request_sha256,
"DENIAL_READY_BYTES_CHANGED"
);
let signed: SignedResponse = serde_json::from_slice(&response)?;
let parsed: ReconcileDecisionPayload = serde_json::from_slice(&signed.decision_bytes)?;
// Historical Sync evidence only, never a lease. Its original signature
// and immutable stored request remain mandatory after expiry.
let decision = verify(&self.verifier, &self.binding, &signed, parsed.issued_at)?;
let capture: Vec<u8> = db.query_row(
"SELECT snapshot FROM helper_sync_captures WHERE checkpoint=?1",
[anchor.checkpoint],
|r| r.get(0),
)?;
let capture: Snapshot = serde_json::from_slice(&capture)?;
ensure!(
decision.ready
&& decision.helper_ready
&& decision.decision_id == anchor.decision_id
&& decision.boot_id == anchor.boot_id
&& decision.helper_journal_id == Some(anchor.journal_id)
&& decision.helper_checkpoint == anchor.checkpoint
&& decision.connection_generation == anchor.connection_generation
&& capture.captured_at == anchor.captured_at
&& capture.boot_id == anchor.boot_id
&& capture.captured_at <= now,
"DENIAL_CONFIRMED_READY_REQUIRED"
);
Ok(now)
}
/// Every call creates a NEW durable checkpoint challenge and closes the old
/// lease. Use apply's returned snapshot for its ACK, not another snapshot().
pub fn snapshot(
@@ -494,6 +737,12 @@ impl<V: Ed25519Verifier> HelperSync<V> {
}
}
fn digest(value: &str) -> bool {
value.len() == 64
&& value
.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}
fn pinned_key(binding: &Binding, verifier: &impl Ed25519Verifier) -> Result<Vec<u8>> {
let raw = hex::decode(&binding.public_key_hex)?;
ensure!(raw.len() == 32, "PINNED_HELPER_KEY_SIZE");
+106 -1
View File
@@ -1,5 +1,5 @@
//! Connection-level ledger rules, with OS path/lock/ACL handling left to adapters.
use crate::auth::{Outcome, Request};
use crate::auth::{Outcome, Request, VerifiedHistoricalDenial};
use anyhow::{Context, Result, ensure};
use chrono::{DateTime, Utc};
use rmm_domain::jobs::{ExecutionPermitPayload, JobPayload};
@@ -77,6 +77,111 @@ pub fn begin_execution(
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)
}
fn validate_start_request(p: &ExecutionPermitPayload, request: &Request) -> Result<()> {
ensure!(
request.job_bytes.len() <= 65536
+406
View File
@@ -47,6 +47,412 @@ impl BootSource for TestBoot {
Ok(self.0)
}
}
/// Test-only protected-store/peer adapter. These unit checks do not qualify
/// Windows ACLs, a live SCM peer, file identities or the real intent CAS.
struct TestNoStartGuard {
ledger: ExecutorGuard,
instance: String,
request_sha256: String,
anchor_sha256: String,
intent_recorded_at: DateTime<Utc>,
original_boot_id: Uuid,
dispatch_possible: bool,
}
impl ExecutorLedgerGuard for TestNoStartGuard {
fn check(&self, db: &Connection) -> anyhow::Result<()> {
self.ledger.check(db)
}
}
impl NoStartGuard for TestNoStartGuard {
fn live_instance_sha256(&self) -> anyhow::Result<String> {
Ok(self.instance.clone())
}
fn verify_no_dispatch(
&self,
original: &Request,
anchor: &NoStartAnchor,
) -> anyhow::Result<NoDispatchObservation> {
anyhow::ensure!(
!self.dispatch_possible
&& self.request_sha256 == hash(&serde_json::to_vec(original)?)
&& self.anchor_sha256 == hash(&serde_json::to_vec(anchor)?),
"TEST_INTENT_NOT_PROVEN"
);
Ok(NoDispatchObservation {
intent_id: Uuid::from_u128(900),
intent_sha256: hash(b"immutable test-only intent bytes"),
intent_recorded_at: self.intent_recorded_at,
original_boot_id: self.original_boot_id,
})
}
}
fn denial_case() -> (
Fixture,
HelperSync,
NoStartAnchor,
Request,
TestNoStartGuard,
) {
let mut f = Fixture::new();
f.identity = HelperIdentity::System;
let mut sync = f.sync();
let capture = f.snapshot(&mut sync, 7);
let raw = f.request(&capture);
let ready = f.decision(&capture, &raw, 7, true);
assert!(f.apply(&mut sync, &ready, &raw).unwrap().ready);
let job = JobPayload {
schema_version: 1,
tenant_id: f.binding.tenant_id,
asset_id: f.binding.asset_id,
agent_id: f.binding.agent_id,
enrollment_generation: 1,
assignment_version: 3,
job_id: Uuid::new_v4(),
attempt_id: Uuid::new_v4(),
action: Action::SetServiceState {
unit: "RustDiscoveryMvpFixture".into(),
state: "running".into(),
},
execution_identity: "system".into(),
not_before: f.clock.now - Duration::seconds(10),
start_before: f.clock.now + Duration::minutes(5),
max_runtime_seconds: 30,
max_output_bytes: 4096,
};
let permit = ExecutionPermitPayload {
domain: "rmm.execution-permit".into(),
schema_version: 1,
grant_id: Uuid::new_v4(),
authorization_id: Uuid::new_v4(),
tenant_id: job.tenant_id,
asset_id: job.asset_id,
agent_id: job.agent_id,
enrollment_generation: 1,
assignment_version: 3,
job_id: job.job_id,
attempt_id: job.attempt_id,
plan_hash: hash(b"approved exact service plan"),
job_payload_hash: hash(&encode(&job).unwrap()),
action: job.action.name().into(),
execution_identity: job.execution_identity.clone(),
max_runtime_seconds: 30,
not_before: f.clock.now - Duration::seconds(1),
start_before: f.clock.now + Duration::seconds(59),
key_id: hash(&f.key.verifying_key().to_bytes()),
};
let bytes = encode(&permit).unwrap();
let request = Request {
job_bytes: encode(&job).unwrap(),
signature: f.key.sign(&bytes).to_bytes().to_vec(),
permit_bytes: bytes,
plan_hash: permit.plan_hash,
authorization_id: permit.authorization_id,
};
let mut guard = TestNoStartGuard {
ledger: ExecutorGuard {
directory: f.dir.clone(),
},
instance: hash(b"same live helper PID/creation/ledger/lock fixture"),
request_sha256: hash(&serde_json::to_vec(&request).unwrap()),
anchor_sha256: String::new(),
intent_recorded_at: f.clock.now,
original_boot_id: f.boot.0,
dispatch_possible: false,
};
let anchor = sync
.no_start_anchor(&f.db, &guard, 7, &f.clock, &f.boot)
.unwrap();
guard.anchor_sha256 = hash(&serde_json::to_vec(&anchor).unwrap());
(f, sync, anchor, request, guard)
}
fn denial_ledger_bytes(db: &Connection) -> 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) ORDER BY c.grant_id").unwrap();
type Row = (
String,
String,
u64,
String,
String,
Option<Vec<u8>>,
Option<Vec<u8>>,
Option<Vec<u8>>,
);
let rows = statement
.query_map([], |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)?,
))
})
.unwrap()
.collect::<rusqlite::Result<Vec<Row>>>()
.unwrap();
serde_json::to_vec(&rows).unwrap()
}
#[test]
fn abandon_after_expiry_records_deny_only_evidence_and_requires_normal_signed_unlock() {
let (mut f, mut sync, anchor, request, mut guard) = denial_case();
let permit: ExecutionPermitPayload = serde_json::from_slice(&request.permit_bytes).unwrap();
f.clock.now += Duration::seconds(120);
assert!(f.binding.verify(&request, f.clock.now).is_err());
let outcome = sync
.abandon_no_start(&mut f.db, &guard, &anchor, &request, &f.clock, &f.boot)
.unwrap();
assert_eq!(outcome.state, "failed");
assert_eq!(outcome.error_code, "HELPER_ABANDONED_BEFORE_DISPATCH");
assert_eq!(outcome.evidence["not_started"], true);
assert_eq!(outcome.evidence["postconditions_passed"], false);
assert_eq!(
outcome.evidence["observed_at"],
serde_json::to_value(f.clock.now).unwrap()
);
assert!(
outcome.stdout.is_empty()
&& outcome.stderr.is_empty()
&& outcome.exit_code.is_none()
&& !outcome.reboot_required
);
assert_eq!(
f.db.query_row::<u32, _, _>(
"SELECT count(*) FROM consumed WHERE result IS NULL",
[],
|r| r.get(0)
)
.unwrap(),
1
);
let before = denial_ledger_bytes(&f.db);
guard.dispatch_possible = true; // An existing outcome is returned, never reclassified.
let repeated = sync
.abandon_no_start(&mut f.db, &guard, &anchor, &request, &f.clock, &f.boot)
.unwrap();
assert_eq!(
serde_json::to_vec(&outcome).unwrap(),
serde_json::to_vec(&repeated).unwrap()
);
assert_eq!(denial_ledger_bytes(&f.db), before);
assert!(
rmm_agent_core::ledger::begin_execution(
&mut f.db,
&permit,
&request,
f.boot.0,
f.clock.now
)
.is_err()
);
assert!(!sync.can_start(&f.db, &f.guard, 7, &f.clock, &f.boot));
let capture = f.snapshot(&mut sync, 7);
assert_eq!(
capture.attempts[0].original_request_sha256,
hash(&serde_json::to_vec(&request).unwrap())
);
let raw = f.request(&capture);
let decision = f.decision(&capture, &raw, 7, true);
assert!(f.apply(&mut sync, &decision, &raw).unwrap().ready);
assert_eq!(
f.db.query_row::<u32, _, _>(
"SELECT count(*) FROM consumed WHERE result IS NOT NULL",
[],
|r| r.get(0)
)
.unwrap(),
1
);
assert!(
rmm_agent_core::ledger::begin_execution(
&mut f.db,
&permit,
&request,
f.boot.0,
f.clock.now
)
.is_err()
);
}
#[test]
fn abandon_storage_failure_rolls_back_consumption_start_and_outcome_together() {
for trigger in [
"CREATE TRIGGER refuse_start BEFORE INSERT ON execution_evidence BEGIN SELECT RAISE(ABORT,'fixture failure'); END;",
"CREATE TRIGGER refuse_outcome BEFORE UPDATE OF outcome ON execution_evidence BEGIN SELECT RAISE(ABORT,'fixture failure'); END;",
] {
let (mut f, mut sync, anchor, request, guard) = denial_case();
f.db.execute_batch(trigger).unwrap();
assert!(
sync.abandon_no_start(&mut f.db, &guard, &anchor, &request, &f.clock, &f.boot)
.is_err()
);
for table in ["consumed", "execution_evidence"] {
assert_eq!(
f.db.query_row::<u32, _, _>(&format!("SELECT count(*) FROM {table}"), [], |r| r
.get(0))
.unwrap(),
0
);
}
f.db.execute_batch(
"DROP TRIGGER IF EXISTS refuse_start;DROP TRIGGER IF EXISTS refuse_outcome",
)
.unwrap();
assert!(
sync.abandon_no_start(&mut f.db, &guard, &anchor, &request, &f.clock, &f.boot)
.is_ok()
);
}
}
#[test]
fn abandon_preserves_existing_known_unknown_missing_start_and_foreign_request_rows() {
use rmm_agent_core::{auth::Outcome, ledger};
for variant in [
"known",
"unknown",
"missing_start",
"missing_outcome",
"foreign_grant",
"changed_request",
] {
let (mut f, mut sync, anchor, request, guard) = denial_case();
let mut stored = request.clone();
let mut permit: ExecutionPermitPayload =
serde_json::from_slice(&request.permit_bytes).unwrap();
if variant == "foreign_grant" {
permit.grant_id = Uuid::new_v4();
}
if variant == "changed_request" {
permit.plan_hash = hash(b"other signed plan");
stored.plan_hash = permit.plan_hash.clone();
}
stored.permit_bytes = encode(&permit).unwrap();
stored.signature = f.key.sign(&stored.permit_bytes).to_bytes().to_vec();
if variant == "missing_start" {
ledger::consume(&mut f.db, &permit).unwrap();
} else {
ledger::begin_execution(&mut f.db, &permit, &stored, f.boot.0, f.clock.now).unwrap();
}
if variant == "known" || variant == "unknown" {
let mut outcome = Outcome::unknown("ORIGINAL_OUTCOME");
if variant == "known" {
outcome.state = "failed".into();
}
ledger::persist_outcome(&f.db, &permit, &outcome).unwrap();
if variant == "known" {
ledger::finish(&f.db, &permit, &outcome).unwrap();
}
}
let before = denial_ledger_bytes(&f.db);
let response =
sync.abandon_no_start(&mut f.db, &guard, &anchor, &request, &f.clock, &f.boot);
if matches!(variant, "foreign_grant" | "changed_request") {
assert!(response.is_err(), "{variant}");
} else {
let outcome = response.unwrap();
assert_eq!(
outcome.state,
if variant == "known" {
"failed"
} else {
"unknown"
},
"{variant}"
);
assert_ne!(outcome.error_code, "HELPER_ABANDONED_BEFORE_DISPATCH");
}
assert_eq!(denial_ledger_bytes(&f.db), before, "{variant}");
}
}
#[test]
fn abandon_rejects_wrong_signature_scope_clock_boot_lineage_instance_and_dispatch_proof() {
for variant in [
"signature",
"tenant",
"root_identity",
"script",
"restarted",
"clock",
"boot",
"instance",
"history",
"checkpoint",
"dispatch",
"future_intent",
] {
let (mut f, mut sync, anchor, mut request, mut guard) = denial_case();
match variant {
"signature" => request.signature[0] ^= 1,
"tenant" | "root_identity" | "script" | "restarted" => {
let mut job: JobPayload = serde_json::from_slice(&request.job_bytes).unwrap();
let mut p: ExecutionPermitPayload =
serde_json::from_slice(&request.permit_bytes).unwrap();
if variant == "tenant" {
job.tenant_id = Uuid::new_v4();
p.tenant_id = job.tenant_id;
}
if variant == "root_identity" {
job.execution_identity = "root".into();
p.execution_identity = "root".into();
}
if variant == "script" {
job.action = script();
p.action = job.action.name().into();
}
if variant == "restarted" {
job.action = Action::SetServiceState {
unit: "RustDiscoveryMvpFixture".into(),
state: "restarted".into(),
};
}
request.job_bytes = encode(&job).unwrap();
p.job_payload_hash = hash(&request.job_bytes);
request.permit_bytes = encode(&p).unwrap();
request.signature = f.key.sign(&request.permit_bytes).to_bytes().to_vec();
}
"clock" => f.clock.trusted = false,
"boot" => f.boot.0 = Uuid::new_v4(),
"instance" => guard.instance = hash(b"different helper PID or ledger identity"),
"history" => {
f.db.execute("DELETE FROM helper_sync_decisions", [])
.unwrap();
}
"checkpoint" => {
f.db.execute("UPDATE helper_sync_meta SET checkpoint=checkpoint+1", [])
.unwrap();
}
"dispatch" => guard.dispatch_possible = true,
"future_intent" => guard.intent_recorded_at = f.clock.now + Duration::seconds(1),
_ => unreachable!(),
}
assert!(
sync.abandon_no_start(&mut f.db, &guard, &anchor, &request, &f.clock, &f.boot)
.is_err(),
"{variant}"
);
assert_eq!(
f.db.query_row::<u32, _, _>("SELECT count(*) FROM consumed", [], |r| r.get(0))
.unwrap(),
0,
"{variant}"
);
assert_eq!(
f.db.query_row::<u32, _, _>("SELECT count(*) FROM execution_evidence", [], |r| r
.get(0))
.unwrap(),
0,
"{variant}"
);
}
}
struct Fixture {
dir: PathBuf,
db: Connection,