Freeze minimal SYSTEM nonstart 221 closure and reproducible Windows source
Rust development slice / linux (push) Failing after 6s

This commit is contained in:
2026-11-16 21:07:24 +01:00
parent 510c069838
commit 559c4cb292
16 changed files with 2222 additions and 37 deletions
@@ -0,0 +1 @@
fn main()->anyhow::Result<()> { let args=std::env::args().skip(1).collect::<Vec<_>>(); anyhow::ensure!(args.len()==2,"PUBLIC_RECEIPT_AND_PLACEHOLDER_PATH_REQUIRED"); let raw=std::fs::read(&args[0])?;let event=std::fs::read(&args[1])?; println!("{}",rmm_agent_core::windows_system_nonstart::receipt_contract(&raw,&event)?); Ok(()) }
+122 -7
View File
@@ -752,6 +752,12 @@ impl<V: Ed25519Verifier> HelperSync<V> {
validate_decision(row, local, d)?;
if d.unlock {
let bytes = unlock_outcome(row, d, current_boot)?;
let preserve = crate::windows_system_nonstart::preserve_original_unlock(
&tx,
&self.binding,
row.grant_id,
&bytes,
)?;
ensure!(
tx.execute(
"UPDATE consumed SET result=?2 WHERE grant_id=?1",
@@ -759,10 +765,12 @@ impl<V: Ed25519Verifier> HelperSync<V> {
)? == 1,
"ROOT_CONSUMPTION_MISSING"
);
tx.execute(
"UPDATE execution_evidence SET outcome=?2 WHERE grant_id=?1",
params![row.grant_id.to_string(), bytes],
)?;
if !preserve {
tx.execute(
"UPDATE execution_evidence SET outcome=?2 WHERE grant_id=?1",
params![row.grant_id.to_string(), bytes],
)?;
}
unlocked.push(row.grant_id);
} else {
safe &= definitive(row)
@@ -1401,12 +1409,16 @@ fn load_rows(
&& attempt_id == job.attempt_id.to_string(),
"LOCAL_REQUEST_BINDING"
);
if let (Some(a), Some(b)) = (&finished, &last) {
let resolved =
crate::windows_system_nonstart::effective_outcome(db, Some(binding), permit.grant_id)?;
if resolved.is_none()
&& let (Some(a), Some(b)) = (&finished, &last)
{
ensure!(canonical(a)? == canonical(b)?, "LOCAL_OUTCOME_CONFLICT");
}
let mut outcome_bytes = last
let mut outcome_bytes = resolved
.as_deref()
.or(finished.as_deref())
.or(last.as_deref().or(finished.as_deref()))
.map(canonical)
.transpose()?
.unwrap_or_default();
@@ -1890,3 +1902,106 @@ fn unique_summaries(rows: &[AttemptView]) -> Result<BTreeMap<(Uuid, Uuid), &Atte
}
Ok(map)
}
/// Exact closed administrative nonstart221 cache materialization. This does not
/// capture, apply a Sync, advance a checkpoint, or create an execution lease.
pub(crate) fn refresh_closed_nonstart_221(db: &Connection, binding: &Binding) -> Result<()> {
use rmm_domain::windows_system_nonstart as closed;
let expected =
crate::windows_system_nonstart::effective_outcome(db, Some(binding), closed::GRANT)?
.context("NONSTART_REFRESH_AUTHENTICATED_COMPLETION_REQUIRED")?;
let raw: Vec<u8> = db.query_row(
"SELECT snapshot FROM helper_sync_captures WHERE checkpoint=413",
[],
|r| r.get(0),
)?;
let snapshot: Snapshot = serde_json::from_slice(&raw)?;
ensure!(
snapshot.checkpoint == 413
&& snapshot.boot_id == closed::BOOT
&& snapshot.attempts.len() == 1,
"NONSTART_REFRESH_ORIGINAL_CAPTURE"
);
let mut original = snapshot.attempts[0].clone();
ensure!(
original.grant_id == closed::GRANT
&& original.job_id == closed::JOB
&& original.attempt_id == closed::ATTEMPT
&& original.state == "unknown"
&& original.outcome_sha256 == closed::UNKNOWN_SHA256,
"NONSTART_REFRESH_ORIGINAL_ATTEMPT"
);
let prior_revision = original.revision;
original.revision = 0;
let prior_fingerprint = hash(&serde_json::to_vec(&original)?);
let (count,revision,fingerprint):(u64,u64,String)=db.query_row("SELECT (SELECT count(*) FROM helper_sync_rows),revision,fingerprint FROM helper_sync_rows WHERE grant_id=?1",[closed::GRANT.to_string()],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?)))?;
ensure!(
count == 1 && revision == prior_revision && fingerprint == prior_fingerprint,
"NONSTART_REFRESH_EXACT_OLD_CACHE"
);
let rows = load_rows(
db,
binding,
true,
HelperIdentity::System,
&crate::crypto::DalekVerifier,
None,
)?;
ensure!(
rows.len() == 1
&& rows[0].grant_id == closed::GRANT
&& rows[0].state == "failed"
&& rows[0].outcome_bytes == expected
&& rows[0].outcome_sha256 == hash(&expected)
&& rows[0].revision == revision.checked_add(1).context("REVISION_OVERFLOW")?,
"NONSTART_REFRESH_EXACT_DERIVED_CACHE"
);
let checked = load_rows(
db,
binding,
false,
HelperIdentity::System,
&crate::crypto::DalekVerifier,
None,
)?;
ensure!(
checked.len() == 1
&& checked[0].grant_id == closed::GRANT
&& checked[0].outcome_bytes == expected
&& checked[0].revision == rows[0].revision,
"NONSTART_REFRESH_READ_ONLY_VALIDATOR"
);
Ok(())
}
/// SDK-only no-effect fixture surface: actual materialization/read validation,
/// strictly an in-memory database with the single original incident grant.
pub(crate) fn nonstart221_memory_rows(
db: &Connection,
binding: &Binding,
refresh: bool,
) -> Result<Vec<LocalAttempt>> {
let path: String = db.query_row(
"SELECT file FROM pragma_database_list WHERE name='main'",
[],
|r| r.get(0),
)?;
ensure!(
path.is_empty()
&& db.query_row("SELECT count(*) FROM consumed", [], |r| r.get::<_, u64>(0))? == 1
&& db.query_row(
"SELECT EXISTS(SELECT 1 FROM consumed WHERE grant_id=?1)",
[rmm_domain::windows_system_nonstart::GRANT.to_string()],
|r| r.get::<_, bool>(0)
)?,
"NONSTART_CONTRACT_MEMORY_ONLY"
);
load_rows(
db,
binding,
refresh,
HelperIdentity::System,
&crate::crypto::DalekVerifier,
None,
)
}
+8 -4
View File
@@ -284,10 +284,14 @@ pub fn events(db: &Connection) -> Result<Vec<Envelope>> {
let bytes = statement
.query_map([], |r| r.get::<_, Vec<u8>>(0))?
.collect::<rusqlite::Result<Vec<_>>>()?;
bytes
.into_iter()
.map(|b| Ok(Envelope::decode(b.as_slice())?))
.collect()
let mut active = vec![];
for bytes in bytes {
let envelope = Envelope::decode(bytes.as_slice())?;
if !crate::windows_system_nonstart::retired_event(db, &envelope)? {
active.push(envelope);
}
}
Ok(active)
}
pub fn ack(db: &mut Connection, id: &str) -> Result<()> {
let tx = db.transaction()?;
+8
View File
@@ -265,6 +265,14 @@ pub(crate) fn persist_outcome_in(
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,
+2
View File
@@ -14,3 +14,5 @@ pub mod update_health_sync;
pub mod windows_sync_history;
pub mod windows_sync_alignment;
pub mod windows_system_nonstart;
+67 -21
View File
@@ -40,10 +40,10 @@ pub trait SyncClock {
}
/// Full trusted UTC interval for crypto validity. Existing point-clock
/// providers retain their contract; interval providers override atomically.
fn bounds(&self) -> Result<(DateTime<Utc>,DateTime<Utc>)> {
let reading=self.reading()?;
ensure!(reading.own_wall<=reading.upper,"CLOCK_INTERVAL_ORDER");
Ok((reading.own_wall,reading.upper))
fn bounds(&self) -> Result<(DateTime<Utc>, DateTime<Utc>)> {
let reading = self.reading()?;
ensure!(reading.own_wall <= reading.upper, "CLOCK_INTERVAL_ORDER");
Ok((reading.own_wall, reading.upper))
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -80,8 +80,12 @@ pub struct Applied {
pub reason: String,
}
/// Diagnostics only; never accepted as an authorization or reusable lease.
#[derive(Clone,Copy)]
pub struct GateObservation {pub signed_ready:bool,pub local_applied:bool,pub helper_ack_pending:bool}
#[derive(Clone, Copy)]
pub struct GateObservation {
pub signed_ready: bool,
pub local_applied: bool,
pub helper_ack_pending: bool,
}
struct Gate {
channel: Channel,
until: DateTime<Utc>,
@@ -129,8 +133,12 @@ impl<V: Ed25519Verifier> ClientSync<V> {
self.channel = None;
self.pending = None;
}
pub fn gate_observation(&self)->Option<GateObservation> {
self.gate.as_ref().map(|g|GateObservation{signed_ready:g.ready,local_applied:g.local_applied,helper_ack_pending:g.helper.is_some()})
pub fn gate_observation(&self) -> Option<GateObservation> {
self.gate.as_ref().map(|g| GateObservation {
signed_ready: g.ready,
local_applied: g.local_applied,
helper_ack_pending: g.helper.is_some(),
})
}
pub fn validity_deadline(&self) -> Option<DateTime<Utc>> {
self.gate.as_ref().map(|gate| gate.until)
@@ -696,7 +704,14 @@ impl<V: Ed25519Verifier> ClientSync<V> {
&& attempt == d.attempt_id.to_string(),
"LOCAL_UNLOCK_CONSUMPTION_BINDING"
);
let previous = previous.context("LOCAL_UNLOCK_PREVIOUS_OUTCOME_MISSING")?;
let resolved = crate::windows_system_nonstart::effective_outcome(
&tx,
Some(&self.binding),
grant,
)?;
let previous = resolved
.or(previous)
.context("LOCAL_UNLOCK_PREVIOUS_OUTCOME_MISSING")?;
let prior = canonical_outcome_bytes(&serde_json::from_slice::<ReconciledOutcome>(
&previous,
)?)?;
@@ -717,14 +732,22 @@ impl<V: Ed25519Verifier> ClientSync<V> {
&& d.outcome_sha256.as_deref() == Some(hash(&bytes).as_str()),
"LOCAL_UNLOCK_CANONICAL_OUTCOME"
);
let preserve = crate::windows_system_nonstart::preserve_original_unlock(
&tx,
&self.binding,
grant,
&bytes,
)?;
tx.execute(
"UPDATE consumed SET result=?2 WHERE grant_id=?1",
params![grant.to_string(), bytes],
)?;
tx.execute(
"UPDATE execution_evidence SET outcome=?2 WHERE grant_id=?1",
params![grant.to_string(), bytes],
)?;
if !preserve {
tx.execute(
"UPDATE execution_evidence SET outcome=?2 WHERE grant_id=?1",
params![grant.to_string(), bytes],
)?;
}
}
tx.execute(
"INSERT INTO reconcile_consumption(decision_id,response) VALUES(?1,?2)",
@@ -820,16 +843,27 @@ pub fn archive_events(db: &Connection) -> Result<()> {
Ok(())
}
fn pending_ids(db: &Connection) -> Result<Vec<String>> {
let mut statement = db.prepare("SELECT id FROM job_events ORDER BY id")?;
let ids = statement
.query_map([], |r| r.get::<_, String>(0))?
let mut statement = db.prepare("SELECT id,payload FROM job_events ORDER BY id")?;
let rows = statement
.query_map([], |r| {
Ok((r.get::<_, String>(0)?, r.get::<_, Vec<u8>>(1)?))
})?
.collect::<rusqlite::Result<Vec<_>>>()?;
for id in &ids {
ensure!(!Uuid::parse_str(id)?.is_nil(), "INVALID_DURABLE_MESSAGE_ID");
let mut ids = vec![];
for (id, bytes) in rows {
ensure!(
!Uuid::parse_str(&id)?.is_nil(),
"INVALID_DURABLE_MESSAGE_ID"
);
let envelope = Envelope::decode(bytes.as_slice())?;
ensure!(envelope.message_id == id, "EVENT_IDENTITY_CONFLICT");
if !crate::windows_system_nonstart::retired_event(db, &envelope)? {
ids.push(id);
}
}
Ok(ids)
}
fn outcome(r: &JobResult) -> Result<ReconciledOutcome> {
pub(crate) fn outcome(r: &JobResult) -> Result<ReconciledOutcome> {
Ok(ReconciledOutcome {
state: r.state.clone(),
stdout: r.stdout.clone(),
@@ -950,7 +984,13 @@ fn attempts(db: &Connection, ledger: &Connection, binding: &Binding) -> Result<V
&& request.authorization_id.to_string() == offer.authorization_id,
"START_EVIDENCE_BINDING"
);
if last.is_some() {
if let Some(resolved) = crate::windows_system_nonstart::effective_outcome(
ledger,
Some(binding),
Uuid::parse_str(&grant_id)?,
)? {
stored = Some(resolved);
} else if last.is_some() {
stored = last;
}
}
@@ -1163,8 +1203,14 @@ fn ingest_helper(
)
.optional()?
.flatten();
let same = existing
let resolved = crate::windows_system_nonstart::effective_outcome(
ledger,
Some(binding),
Uuid::parse_str(&h.grant_id)?,
)?;
let same = resolved
.as_ref()
.or(existing.as_ref())
.map(|b| {
serde_json::from_slice::<ReconciledOutcome>(b)
.and_then(|o| canonical_outcome_bytes(&o))
@@ -0,0 +1,791 @@
//! Exact operator-approved nonstart221. Historical receipt never grants execution.
pub use crate::windows_sync_alignment::{ClosedPairGuard, Local, inventory};
use crate::{
auth::{Binding, Request},
crypto::{DalekVerifier, Ed25519Verifier},
helper_reconcile::Snapshot,
reconcile::{Channel, verify_response_with},
};
use anyhow::{Result, ensure};
use chrono::{DateTime, Utc};
use prost::Message;
use rmm_domain::{
checkpoint_repair::{SignedDecision, SignedReceipt},
jobs::{ExecutionPermitPayload, hash},
windows_system_nonstart as dto,
};
use rmm_protocol::{Envelope, Payload, SyncRequest, SyncResponse};
use rusqlite::{Connection, OptionalExtension, params};
use serde_json::Value;
use uuid::Uuid;
pub const TABLE: &str = "windows_system_nonstart_221_resolution";
const AGENT_START: &str = "f6134c00143b0939a92d2690b8c3a034d332d47241c65a812dcf8f78ead9cfcc";
const HELPER_START: &str = "cf83fc9acbfc1429cca452498c44282f7748d852d73b8221bc0721af60e276d9";
fn canonical(raw: &[u8]) -> Result<Vec<u8>> {
Ok(rmm_domain::reconciliation::canonical_outcome_bytes(
&serde_json::from_slice(raw)?,
)?)
}
fn binding(w: &dto::Witness) -> Binding {
Binding {
tenant_id: w.tenant_id,
asset_id: w.asset_id,
agent_id: w.agent_id,
enrollment_generation: w.enrollment_generation,
assignment_version: w.assignment_version,
public_key_hex: w.verification_public_key_hex.clone(),
}
}
fn receipt(raw: &[u8], local: Option<&Binding>) -> Result<(SignedReceipt, dto::Receipt, String)> {
ensure!(raw.len() <= 4 * 1024 * 1024, "NONSTART_RECEIPT_BOUND");
let signed: SignedReceipt = serde_json::from_slice(raw)?;
let value: dto::Receipt = serde_json::from_slice(&signed.payload)?;
ensure!(
value.valid(value.issued_at),
"NONSTART_RECEIPT_CLOSED_PROFILE"
);
let expected = binding(&value.witness);
if let Some(local) = local {
ensure!(
hash(&serde_json::to_vec(local)?) == hash(&serde_json::to_vec(&expected)?),
"NONSTART_CURRENT_BINDING"
);
}
let key = hex::decode(&expected.public_key_hex)?;
ensure!(
key.len() == 32
&& signed.signature.len() == 64
&& DalekVerifier.verify(&key, &signed.payload, &signed.signature)?,
"NONSTART_RECEIPT_SIGNATURE"
);
// The actual original immutable starts authenticate this historical server key.
for (start, digest) in [
(&value.witness.agent_start, AGENT_START),
(&value.witness.helper_start, HELPER_START),
] {
ensure!(hash(start) == digest, "NONSTART_ORIGINAL_START_HASH");
let saved: Value = serde_json::from_slice(start)?;
let request: Request = serde_json::from_value(saved["request"].clone())?;
let p: ExecutionPermitPayload = serde_json::from_slice(&request.permit_bytes)?;
let (job, p) = expected.verify_with(&request, p.not_before, &DalekVerifier)?;
ensure!(
job.job_id == dto::JOB
&& job.attempt_id == dto::ATTEMPT
&& p.grant_id == dto::GRANT
&& job.execution_identity == "system"
&& hash(&serde_json::to_vec(&request)?)
== "09aa6be3617017e4169f9d83fbfc4cbef43712513a02229a8360dd6a708ee69c",
"NONSTART_ORIGINAL_SIGNED_REQUEST"
);
}
let digest = hash(&serde_json::to_vec(&signed)?);
Ok((signed, value, digest))
}
/// Per-grant historical read only: deliberately no current global count/inventory,
/// clock, code-image or lease assumption. Old unknown bytes remain immutable.
pub fn effective_outcome(
db: &Connection,
local: Option<&Binding>,
grant: Uuid,
) -> Result<Option<Vec<u8>>> {
if grant != dto::GRANT {
return Ok(None);
}
let exists: bool = db.query_row(
"SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name=?1)",
[TABLE],
|r| r.get(0),
)?;
if !exists {
return Ok(None);
}
type Row = (String, Vec<u8>, String, Vec<u8>);
let row:Option<Row>=db.query_row("SELECT role,receipt,receipt_sha256,derived_outcome FROM windows_system_nonstart_221_resolution WHERE grant_id=?1",[grant.to_string()],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?))).optional()?;
let Some((role, raw, digest, derived)) = row else {
return Ok(None);
};
let (_, value, verified_digest) = receipt(&raw, local)?;
ensure!(
digest == verified_digest && matches!(role.as_str(), "agent" | "helper"),
"NONSTART_RESOLUTION_BINDING"
);
let(start,last,finished):(Vec<u8>,Vec<u8>,Vec<u8>)=db.query_row("SELECT e.start,e.outcome,c.result FROM consumed c JOIN execution_evidence e USING(grant_id) WHERE c.grant_id=?1 AND c.agent=?2 AND c.generation=1 AND c.job=?3 AND c.attempt=?4",params![grant.to_string(),value.witness.agent_id.to_string(),dto::JOB.to_string(),dto::ATTEMPT.to_string()],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?)))?;
let expected_start = if role == "agent" {
&value.witness.agent_start
} else {
&value.witness.helper_start
};
let expected = rmm_domain::reconciliation::canonical_outcome_bytes(&dto::failed_outcome(
value.receipt_id,
&digest,
))?;
ensure!(
start == *expected_start
&& hash(&last) == dto::UNKNOWN_SHA256
&& last == value.witness.agent_outcome
&& derived == expected
&& canonical(&finished)? == expected,
"NONSTART_IMMUTABLE_ORIGINAL_AND_DERIVED_RESULT"
);
Ok(Some(expected))
}
/// Storage guard only, called AFTER normal fresh signed-unlock verification.
/// A historical receipt never provides that authority. Its derived completion
/// must be byte-identical; the original Unknown evidence is never overwritten.
pub(crate) fn preserve_original_unlock(
db: &Connection,
binding: &Binding,
grant: Uuid,
bytes: &[u8],
) -> Result<bool> {
let Some(resolved) = effective_outcome(db, Some(binding), grant)? else {
return Ok(false);
};
ensure!(
resolved == bytes,
"NONSTART_SIGNED_UNLOCK_CHANGED_DERIVED_COMPLETION"
);
Ok(true)
}
/// Suppresses only the exact original closed delegation placeholder from delivery.
/// The physical event and original reconciliation archive are never deleted/ACKed.
pub fn retired_event(db: &Connection, envelope: &Envelope) -> Result<bool> {
let Some(Payload::JobResult(result)) = &envelope.payload else {
return Ok(false);
};
if result.job_id != dto::JOB.to_string()
|| result.attempt_id != dto::ATTEMPT.to_string()
|| result.grant_id != dto::GRANT.to_string()
|| result.state != "unknown"
|| result.revision != 1
|| result.error_code != "SYSTEM_DELEGATION_REQUIRES_HELPER_SNAPSHOT"
|| envelope.message_id != "6844ae6d-1f0f-4177-9fdd-9d9ed14b9ff5"
|| hash(&envelope.encode_to_vec())
!= "6907fdbbcd1c287c2545fde2f9ebae54fd3b6629b10b61dc5d3884584d8c74c9"
{
return Ok(false);
}
let exists: bool = db.query_row(
"SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name=?1)",
[TABLE],
|r| r.get(0),
)?;
if !exists {
return Ok(false);
}
let row: Option<(String,Vec<u8>,String,Vec<u8>)> = db.query_row("SELECT role,receipt,receipt_sha256,derived_outcome FROM windows_system_nonstart_221_resolution WHERE grant_id=?1",[dto::GRANT.to_string()],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?))).optional()?;
let Some((role, raw, digest, derived)) = row else {
return Ok(false);
};
let (_, r, actual) = receipt(&raw, None)?;
ensure!(
role == "journal"
&& digest == actual
&& envelope.agent_id == r.witness.agent_id.to_string()
&& envelope.enrollment_generation == r.witness.enrollment_generation
&& envelope.boot_id == dto::BOOT.to_string()
&& envelope.connection_generation == 221
&& r.witness.agent_inventory_sha256
== "124c9318bb5d71572bdde5af34e9c35d83b00b8cfc506cdd6e3157aa6f6bd8da"
&& hash(&rmm_domain::reconciliation::canonical_outcome_bytes(
&crate::reconcile::outcome(result)?
)?) == "a626d3118132b8db525cb3f792f7f278e95833cc3ffe38d34ed7696e7219ab08"
&& derived
== rmm_domain::reconciliation::canonical_outcome_bytes(&dto::failed_outcome(
r.receipt_id,
&digest
))?,
"NONSTART_RETIRED_ORIGINAL_EVENT"
);
Ok(true)
}
fn original(
local: &Local<'_>,
id: Uuid,
decision: Uuid,
cp: u64,
hcp: u64,
) -> Result<(Vec<u8>, SignedDecision)> {
let (raw, env, resp): (Vec<u8>, Vec<u8>, Vec<u8>) = local.agent.query_row(
"SELECT request,envelope,response FROM reconcile_requests WHERE id=?1 AND generation=221",
[id.to_string()],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
)?;
ensure!(
raw.len() <= 65536 && resp.len() <= 131072 && env.len() <= 131072,
"NONSTART_ORIGINAL_BOUND"
);
let request = SyncRequest::decode(raw.as_slice())?;
let envelope = Envelope::decode(env.as_slice())?;
let response = SyncResponse::decode(resp.as_slice())?;
let historical: rmm_domain::reconciliation::ReconcileDecisionPayload =
serde_json::from_slice(&response.decision_bytes)?;
ensure!(
request.encode_to_vec() == raw
&& envelope.payload == Some(Payload::SyncRequest(request.clone()))
&& envelope.sequence == cp
&& envelope.boot_id == dto::BOOT.to_string(),
"NONSTART_ORIGINAL_ENVELOPE"
);
for binding in [local.binding, local.helper_binding] {
let d = verify_response_with(
&DalekVerifier,
binding,
&request,
&Channel {
connection_generation: 221,
boot_id: dto::BOOT,
},
&response,
historical.issued_at,
)?;
ensure!(
d.decision_id == decision
&& d.request_id == id
&& d.checkpoint == cp
&& d.helper_checkpoint == hcp,
"NONSTART_ORIGINAL_RESPONSE"
);
}
let consumed: Vec<u8> = local.consumption.query_row(
"SELECT response FROM reconcile_consumption WHERE decision_id=?1",
[decision.to_string()],
|r| r.get(0),
)?;
ensure!(consumed == resp, "NONSTART_ORIGINAL_CONSUMPTION_RESPONSE");
let capture: Vec<u8> = local.helper.query_row(
"SELECT snapshot FROM helper_sync_captures WHERE checkpoint=?1",
[hcp],
|r| r.get(0),
)?;
let capture: Snapshot = serde_json::from_slice(&capture)?;
ensure!(
capture.boot_id == dto::BOOT
&& capture.checkpoint == hcp
&& capture.attempts.len() == 1
&& capture.attempts[0].job_id == dto::JOB
&& capture.attempts[0].grant_id == dto::GRANT
&& capture.attempts[0].state == "unknown"
&& capture.attempts[0].outcome_sha256 == dto::UNKNOWN_SHA256,
"NONSTART_ORIGINAL_HELPER_CAPTURE"
);
Ok((
raw,
SignedDecision {
decision_bytes: response.decision_bytes,
signature: response.signature,
},
))
}
pub fn witness(
local: &Local<'_>,
guard: &impl ClosedPairGuard,
nonstart: dto::NonstartProof,
) -> Result<dto::Witness> {
guard.check()?;
ensure!(
guard.boot()? == dto::BOOT && nonstart.valid(),
"NONSTART_NATIVE_CONTEXT"
);
let(aj,ac,ag,al,ap):(String,u64,u64,String,Option<String>)=local.agent.query_row("SELECT journal_id,checkpoint,generation,last_decision,pending_request FROM reconcile_meta WHERE id=1 AND fault IS NULL",[],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?,r.get(4)?)))?;
let(hj,hc,hg,hl,hac):(String,u64,u64,String,u64)=local.helper.query_row("SELECT journal_id,checkpoint,generation,last_decision,agent_checkpoint FROM helper_sync_meta WHERE id=1 AND fault IS NULL",[],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?,r.get(4)?)))?;
ensure!(
ac == 10784
&& ag == 221
&& hg == 221
&& hc >= 413
&& hac == 10783
&& al == dto::SECOND.to_string()
&& hl == dto::FIRST.to_string()
&& ap.is_none(),
"NONSTART_ORIGINAL_CONTROL_HEADS"
);
let count = |db: &Connection, table: &str| -> Result<u64> {
Ok(db.query_row(&format!("SELECT count(*) FROM {table}"), [], |r| r.get(0))?)
};
let counts = dto::Counts {
agent_jobs: count(local.agent, "job_attempts")?,
agent_consumed: count(local.consumption, "consumed")?,
agent_starts: count(local.consumption, "execution_evidence")?,
agent_outcomes: local.consumption.query_row(
"SELECT count(*) FROM execution_evidence WHERE outcome IS NOT NULL",
[],
|r| r.get(0),
)?,
helper_consumed: count(local.helper, "consumed")?,
helper_starts: count(local.helper, "execution_evidence")?,
helper_outcomes: local.helper.query_row(
"SELECT count(*) FROM execution_evidence WHERE outcome IS NOT NULL",
[],
|r| r.get(0),
)?,
system_intents: count(local.intents, "system_intents")?,
};
let offer:Vec<u8>=local.agent.query_row("SELECT offer FROM job_attempts WHERE job=?1 AND attempt=?2 AND state='unknown' AND revision=2 AND grant_id=?3",params![dto::JOB.to_string(),dto::ATTEMPT.to_string(),dto::GRANT.to_string()],|r|r.get(0))?;
let row = |db: &Connection| -> Result<(Vec<u8>, Vec<u8>)> {
Ok(db.query_row("SELECT e.start,e.outcome FROM consumed c JOIN execution_evidence e USING(grant_id) WHERE c.grant_id=?1 AND c.result IS NULL",[dto::GRANT.to_string()],|r|Ok((r.get(0)?,r.get(1)?)))?)
};
let (agent_start, agent_outcome) = row(local.consumption)?;
let (helper_start, helper_outcome) = row(local.helper)?;
ensure!(
hash(&agent_start) == AGENT_START
&& hash(&helper_start) == HELPER_START
&& hash(&agent_outcome) == dto::UNKNOWN_SHA256
&& agent_outcome == helper_outcome,
"NONSTART_IMMUTABLE_ORIGINALS"
);
let(intent,digest,phase,mirror):(Vec<u8>,String,String,String)=local.intents.query_row("SELECT i.body,i.digest,i.phase,m.outcome_sha256 FROM system_intents i JOIN system_intent_mirrors m USING(id) WHERE i.grant_id=?1 AND i.cancel_requested=0",[dto::GRANT.to_string()],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?)))?;
ensure!(
hash(&intent) == digest
&& digest == "31c9ddc35a7c09de9e8ec75c835e3dca9e8a816bc031b4b1c1396bd3a2ea46df"
&& phase == "may_have_dispatched"
&& mirror == dto::UNKNOWN_SHA256,
"NONSTART_ORIGINAL_INTENT"
);
let (first_req, first) = original(local, dto::FIRST_REQUEST, dto::FIRST, 10783, 412)?;
let (second_req, second) = original(local, dto::SECOND_REQUEST, dto::SECOND, 10784, 413)?;
let bs = hash(&serde_json::to_vec(local.binding)?);
let hs = hash(&serde_json::to_vec(local.helper_binding)?);
ensure!(bs == hs, "NONSTART_BINDINGS_EQUAL");
let w = dto::Witness {
schema_version: 1,
tenant_id: local.binding.tenant_id,
asset_id: local.binding.asset_id,
agent_id: local.binding.agent_id,
enrollment_generation: 1,
assignment_version: 1,
boot_id: guard.boot()?,
connection_generation: 221,
agent_journal_id: Uuid::parse_str(&aj)?,
helper_journal_id: Uuid::parse_str(&hj)?,
agent_checkpoint: ac,
helper_checkpoint: hc,
agent_last_decision: dto::SECOND,
helper_last_decision: dto::FIRST,
verification_key_id: hash(&hex::decode(&local.binding.public_key_hex)?),
verification_public_key_hex: local.binding.public_key_hex.clone(),
binding_sha256: bs,
helper_binding_sha256: hs,
files: guard.files()?,
agent_inventory_sha256: inventory(local.agent, &[])?,
consumption_inventory_sha256: inventory(local.consumption, &[])?,
helper_inventory_sha256: inventory(local.helper, &[])?,
intent_inventory_sha256: inventory(local.intents, &[])?,
counts,
original_requests: [first_req, second_req],
original_responses: [first, second],
target_job_offer: offer,
agent_start,
helper_start,
agent_outcome,
helper_outcome,
intent,
nonstart,
};
ensure!(w.valid(), "NONSTART_WITNESS_PROFILE");
guard.check()?;
Ok(w)
}
const DDL: &str = "CREATE TABLE windows_system_nonstart_221_resolution(id INTEGER PRIMARY KEY CHECK(id=1),grant_id TEXT NOT NULL UNIQUE,role TEXT NOT NULL CHECK(role IN ('agent','helper','journal')),receipt BLOB NOT NULL,receipt_sha256 TEXT NOT NULL,derived_outcome BLOB NOT NULL,actual_applied_at TEXT NOT NULL,ready INTEGER NOT NULL CHECK(ready=0),helper_ready INTEGER NOT NULL CHECK(helper_ready=0),unlock INTEGER NOT NULL CHECK(unlock=0))";
fn append(
db: &Connection,
role: &str,
raw: &[u8],
r: &dto::Receipt,
digest: &str,
derived: &[u8],
now: DateTime<Utc>,
) -> Result<()> {
db.execute_batch(DDL)?;
for (name, kind) in [
("no_replace", "INSERT"),
("no_update", "UPDATE"),
("no_delete", "DELETE"),
] {
let condition = if kind == "INSERT" {
" WHEN EXISTS(SELECT 1 FROM windows_system_nonstart_221_resolution)"
} else {
""
};
db.execute_batch(&format!("CREATE TRIGGER windows_nonstart_221_{name} BEFORE {kind} ON {TABLE}{condition} BEGIN SELECT RAISE(ABORT,'WINDOWS_NONSTART_221_IMMUTABLE'); END"))?;
}
db.execute(
"INSERT INTO windows_system_nonstart_221_resolution VALUES(1,?1,?2,?3,?4,?5,?6,0,0,0)",
params![
dto::GRANT.to_string(),
role,
raw,
digest,
derived,
now.to_rfc3339()
],
)?;
ensure!(r.valid(now), "NONSTART_FRESH_ADMIN_RECEIPT");
Ok(())
}
/// Exact stopped-pair administrative closure, never an execution grant. Three
/// independently durable journals remain closed on any partial storage failure;
/// callers must not restart either role until verify_applied succeeds.
pub fn apply(
local: &Local<'_>,
guard: &impl ClosedPairGuard,
raw: &[u8],
now: DateTime<Utc>,
) -> Result<()> {
let (_, r, digest) = receipt(raw, Some(local.binding))?;
receipt(raw, Some(local.helper_binding))?;
ensure!(r.valid(now), "NONSTART_FRESH_ADMIN_RECEIPT");
guard.check()?;
for db in [local.agent, local.consumption, local.helper] {
db.execute_batch("BEGIN IMMEDIATE")?;
}
let result = (|| -> Result<()> {
ensure!(
witness(local, guard, r.witness.nonstart.clone())? == r.witness,
"NONSTART_UI_WITNESS_CHANGED"
);
crate::helper_reconcile::verify_checkpoint_repair_history_with(
local.helper,
local.helper_binding,
None,
crate::auth::HelperIdentity::System,
&DalekVerifier,
)?;
let before_agent = inventory(local.agent, &[TABLE, "job_attempts"])?;
let before_consumption = inventory(local.consumption, &[TABLE, "consumed"])?;
let before_helper = inventory(
local.helper,
&[
TABLE,
"consumed",
"helper_sync_decisions",
"helper_sync_meta",
"helper_sync_rows",
],
)?;
let fingerprint: String = local.helper.query_row(
"SELECT fingerprint FROM helper_sync_captures WHERE checkpoint=413",
[],
|r| r.get(0),
)?;
ensure!(
fingerprint == crate::helper_reconcile::ledger_fingerprint(local.helper)?,
"NONSTART_ORIGINAL_LEDGER_FINGERPRINT"
);
let response = &r.witness.original_responses[1];
local.helper.execute("INSERT INTO helper_sync_decisions(decision_id,checkpoint,response,request,fingerprint) VALUES(?1,413,?2,?3,?4)",params![dto::SECOND.to_string(),serde_json::to_vec(&crate::helper_reconcile::SignedResponse{decision_bytes:response.decision_bytes.clone(),signature:response.signature.clone()})?,r.witness.original_requests[1],fingerprint])?;
ensure!(local.helper.execute("UPDATE helper_sync_meta SET last_decision=?1,agent_checkpoint=10784 WHERE id=1 AND checkpoint=?2 AND generation=221 AND last_decision=?3 AND agent_checkpoint=10783 AND fault IS NULL",params![dto::SECOND.to_string(),r.witness.helper_checkpoint,dto::FIRST.to_string()])?==1,"NONSTART_FORWARD_CONTROL_CAS");
let derived = rmm_domain::reconciliation::canonical_outcome_bytes(&dto::failed_outcome(
r.receipt_id,
&digest,
))?;
for (db, role) in [(local.helper, "helper"), (local.consumption, "agent")] {
append(db, role, raw, &r, &digest, &derived, now)?;
ensure!(
db.execute(
"UPDATE consumed SET result=?1 WHERE grant_id=?2 AND result IS NULL",
params![derived, dto::GRANT.to_string()]
)? == 1,
"NONSTART_NULL_COMPLETION_CAS"
);
ensure!(
effective_outcome(db, Some(local.binding), dto::GRANT)?.as_deref()
== Some(derived.as_slice()),
"NONSTART_EFFECTIVE_COMPLETION"
);
}
crate::helper_reconcile::refresh_closed_nonstart_221(local.helper, local.helper_binding)?;
append(local.agent, "journal", raw, &r, &digest, &derived, now)?;
ensure!(local.agent.execute("UPDATE job_attempts SET state='failed',revision=3 WHERE job=?1 AND attempt=?2 AND grant_id=?3 AND state='unknown' AND revision=2",params![dto::JOB.to_string(),dto::ATTEMPT.to_string(),dto::GRANT.to_string()])?==1,"NONSTART_JOB_STATE_CAS");
ensure!(
before_agent == inventory(local.agent, &[TABLE, "job_attempts"])?
&& before_consumption == inventory(local.consumption, &[TABLE, "consumed"])?
&& before_helper
== inventory(
local.helper,
&[
TABLE,
"consumed",
"helper_sync_decisions",
"helper_sync_meta",
"helper_sync_rows"
]
)?
&& inventory(local.intents, &[])? == r.witness.intent_inventory_sha256,
"NONSTART_UNRELATED_HISTORY_UNCHANGED"
);
crate::helper_reconcile::verify_checkpoint_repair_history_with(
local.helper,
local.helper_binding,
None,
crate::auth::HelperIdentity::System,
&DalekVerifier,
)?;
verify_applied(local, guard, raw)?;
guard.check()?;
ensure!(
r.valid(Utc::now()),
"NONSTART_RECEIPT_EXPIRED_BEFORE_COMMIT"
);
Ok(())
})();
if result.is_err() {
for db in [local.agent, local.consumption, local.helper] {
let _ = db.execute_batch("ROLLBACK");
}
return result;
}
// No role can run under the lifetime locks. A commit error is not retried.
// Original rows and receipts remain available for explicit readback.
for db in [local.helper, local.consumption, local.agent] {
db.execute_batch("COMMIT")?;
}
verify_applied(local, guard, raw)?;
Ok(())
}
/// Independent readback: historical evidence only, no receipt freshness/lease.
pub fn verify_applied(
local: &Local<'_>,
guard: &impl ClosedPairGuard,
raw: &[u8],
) -> Result<Value> {
guard.check()?;
let (_, r, digest) = receipt(raw, Some(local.binding))?;
ensure!(guard.boot()? == dto::BOOT, "NONSTART_APPLIED_BOOT");
let expected = rmm_domain::reconciliation::canonical_outcome_bytes(&dto::failed_outcome(
r.receipt_id,
&digest,
))?;
for (db, role) in [
(local.agent, "journal"),
(local.consumption, "agent"),
(local.helper, "helper"),
] {
let (actual_role,actual_raw,actual_digest,derived,applied):(String,Vec<u8>,String,Vec<u8>,String)=db.query_row("SELECT role,receipt,receipt_sha256,derived_outcome,actual_applied_at FROM windows_system_nonstart_221_resolution WHERE id=1 AND grant_id=?1 AND ready=0 AND helper_ready=0 AND unlock=0",[dto::GRANT.to_string()],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?,r.get(4)?)))?;
let at = DateTime::parse_from_rfc3339(&applied)?.with_timezone(&Utc);
ensure!(
actual_role == role
&& actual_raw == raw
&& actual_digest == digest
&& derived == expected
&& r.valid(at),
"NONSTART_APPLIED_ORIGINAL_ADMIN_RECORD"
);
if role != "journal" {
ensure!(
effective_outcome(db, Some(local.binding), dto::GRANT)?.as_deref()
== Some(expected.as_slice()),
"NONSTART_APPLIED_ORIGINAL_OUTCOME"
);
}
}
ensure!(local.agent.query_row("SELECT EXISTS(SELECT 1 FROM job_attempts WHERE job=?1 AND attempt=?2 AND grant_id=?3 AND state='failed' AND revision=3)",params![dto::JOB.to_string(),dto::ATTEMPT.to_string(),dto::GRANT.to_string()],|r|r.get::<_,bool>(0))?,"NONSTART_APPLIED_FAILED_REVISION");
ensure!(local.helper.query_row("SELECT EXISTS(SELECT 1 FROM helper_sync_meta WHERE id=1 AND checkpoint=?1 AND generation=221 AND last_decision=?2 AND agent_checkpoint=10784 AND fault IS NULL)",params![r.witness.helper_checkpoint,dto::SECOND.to_string()],|r|r.get::<_,bool>(0))?,"NONSTART_APPLIED_FORWARD_ONLY_HEAD");
ensure!(
inventory(local.intents, &[])? == r.witness.intent_inventory_sha256,
"NONSTART_APPLIED_IMMUTABLE_INTENTS"
);
for (index, (a, b)) in guard.files()?.iter().zip(&r.witness.files).enumerate() {
ensure!(
a.role == b.role
&& a.file_id == b.file_id
&& (matches!(index, 0 | 1 | 3) || a.sha256 == b.sha256),
"NONSTART_APPLIED_FILE_IDENTITIES"
);
}
crate::helper_reconcile::verify_checkpoint_repair_history_with(
local.helper,
local.helper_binding,
None,
crate::auth::HelperIdentity::System,
&DalekVerifier,
)?;
guard.check()?;
let retained_events: u64 =
local
.agent
.query_row("SELECT count(*) FROM job_events", [], |r| r.get(0))?;
let active_pending = crate::jobs::events(local.agent)?.len();
ensure!(
retained_events == 1 && active_pending == 0,
"NONSTART_APPLIED_RETAINED_EVENT_PROJECTION"
);
Ok(
serde_json::json!({"incident":221,"grant_id":dto::GRANT,"receipt_id":r.receipt_id,"receipt_sha256":digest,"original_unknown_sha256":dto::UNKNOWN_SHA256,"state":"failed","revision":3,"not_started":true,"original_unknown_preserved":true,"old_grant_executed_again":false,"raw_retained_job_events":retained_events,"active_pending_job_events":active_pending,"ready":false,"helper_ready":false,"unlock":false}),
)
}
/// No-effect contract against the actual UI-signed public receipt. Uses the same
/// historical authenticator as the running readers; never opens a product DB.
pub fn receipt_contract(raw: &[u8], original_event: &[u8]) -> Result<Value> {
let (signed, r, _) = receipt(raw, None)?;
let local = binding(&r.witness);
receipt(raw, Some(&local))?;
let mut wrong_signature = signed.clone();
wrong_signature.signature[0] ^= 1;
ensure!(
receipt(&serde_json::to_vec(&wrong_signature)?, Some(&local)).is_err(),
"NONSTART_SIGNATURE_NEGATIVE_FAILED"
);
let db = Connection::open_in_memory()?;
db.execute_batch("CREATE TABLE consumed(grant_id TEXT,agent TEXT,generation INTEGER,job TEXT,attempt TEXT,result BLOB); CREATE TABLE execution_evidence(grant_id TEXT,start BLOB,outcome BLOB)")?;
let digest = hash(&serde_json::to_vec(&signed)?);
let derived = rmm_domain::reconciliation::canonical_outcome_bytes(&dto::failed_outcome(
r.receipt_id,
&digest,
))?;
append(&db, "helper", raw, &r, &digest, &derived, r.issued_at)?;
db.execute(
"INSERT INTO consumed VALUES(?1,?2,1,?3,?4,?5)",
params![
dto::GRANT.to_string(),
r.witness.agent_id.to_string(),
dto::JOB.to_string(),
dto::ATTEMPT.to_string(),
derived
],
)?;
db.execute(
"INSERT INTO execution_evidence VALUES(?1,?2,?3)",
params![
dto::GRANT.to_string(),
r.witness.helper_start,
r.witness.helper_outcome
],
)?;
ensure!(
effective_outcome(&db, Some(&local), dto::GRANT)?.as_deref() == Some(derived.as_slice()),
"NONSTART_REAL_RECEIPT_LOCAL_SCOPE_POSITIVE"
);
// Reproduce the concrete SQL cache bug using only actual signed originals
// in a separate in-memory HELPER ledger. No fabricated server signature.
let cache = Connection::open_in_memory()?;
cache.execute_batch("CREATE TABLE consumed(grant_id TEXT,agent TEXT,generation INTEGER,job TEXT,attempt TEXT,result BLOB); CREATE TABLE execution_evidence(grant_id TEXT,start BLOB,outcome BLOB); CREATE TABLE helper_sync_captures(checkpoint INTEGER,snapshot BLOB); CREATE TABLE helper_sync_rows(grant_id TEXT PRIMARY KEY,revision INTEGER,fingerprint TEXT)")?;
cache.execute(
"INSERT INTO consumed VALUES(?1,?2,1,?3,?4,NULL)",
params![
dto::GRANT.to_string(),
r.witness.agent_id.to_string(),
dto::JOB.to_string(),
dto::ATTEMPT.to_string()
],
)?;
cache.execute(
"INSERT INTO execution_evidence VALUES(?1,?2,?3)",
params![
dto::GRANT.to_string(),
r.witness.helper_start,
r.witness.helper_outcome
],
)?;
let old = crate::helper_reconcile::nonstart221_memory_rows(&cache, &local, true)?;
ensure!(
old.len() == 1 && old[0].state == "unknown",
"NONSTART_CONTRACT_ORIGINAL_CACHE"
);
let prior_revision = old[0].revision;
let snapshot = Snapshot {
journal_id: r.witness.helper_journal_id,
checkpoint: 413,
previous_decision_id: Some(dto::FIRST),
boot_id: dto::BOOT,
captured_at: r.issued_at,
attempts: old,
};
cache.execute(
"INSERT INTO helper_sync_captures VALUES(413,?1)",
[serde_json::to_vec(&snapshot)?],
)?;
append(&cache, "helper", raw, &r, &digest, &derived, r.issued_at)?;
cache.execute(
"UPDATE consumed SET result=?1 WHERE grant_id=?2",
params![derived, dto::GRANT.to_string()],
)?;
let stale = crate::helper_reconcile::nonstart221_memory_rows(&cache, &local, false)
.err()
.ok_or_else(|| anyhow::anyhow!("NONSTART_CONTRACT_STALE_CACHE_NOT_REJECTED"))?;
ensure!(
stale.to_string() == "ROOT_ROW_CHANGED_WITHOUT_SNAPSHOT",
"NONSTART_CONTRACT_EXACT_STALE_FAILURE"
);
crate::helper_reconcile::refresh_closed_nonstart_221(&cache, &local)?;
let fresh = crate::helper_reconcile::nonstart221_memory_rows(&cache, &local, false)?;
ensure!(
fresh.len() == 1
&& fresh[0].revision == prior_revision + 1
&& fresh[0].state == "failed"
&& fresh[0].outcome_bytes == derived,
"NONSTART_CONTRACT_DERIVED_CACHE"
);
let preserve = preserve_original_unlock(&cache, &local, dto::GRANT, &derived)?;
ensure!(preserve, "NONSTART_CONTRACT_UNLOCK_STORAGE_GUARD");
ensure!(
preserve_original_unlock(&cache, &local, dto::GRANT, &r.witness.helper_outcome).is_err(),
"NONSTART_CONTRACT_UNLOCK_CANNOT_RESTORE_UNKNOWN"
);
let original: Vec<u8> = cache.query_row(
"SELECT outcome FROM execution_evidence WHERE grant_id=?1",
[dto::GRANT.to_string()],
|r| r.get(0),
)?;
ensure!(
original == r.witness.helper_outcome,
"NONSTART_CONTRACT_ORIGINAL_PRESERVED"
);
ensure!(
original_event.len() <= 16384
&& hash(original_event)
== "6907fdbbcd1c287c2545fde2f9ebae54fd3b6629b10b61dc5d3884584d8c74c9",
"NONSTART_CONTRACT_EXACT_ORIGINAL_PLACEHOLDER"
);
let event = Envelope::decode(original_event)?;
let journal = Connection::open_in_memory()?;
journal.execute_batch("CREATE TABLE job_events(id TEXT PRIMARY KEY,payload BLOB)")?;
append(&journal, "journal", raw, &r, &digest, &derived, r.issued_at)?;
journal.execute(
"INSERT INTO job_events VALUES(?1,?2)",
params![event.message_id, original_event],
)?;
ensure!(
retired_event(&journal, &event)?
&& crate::jobs::events(&journal)?.is_empty()
&& journal.query_row("SELECT count(*) FROM job_events", [], |r| r
.get::<_, u64>(0))?
== 1,
"NONSTART_CONTRACT_EXACT_RETAINED_PLACEHOLDER"
);
let mut other = event.clone();
other.message_id = Uuid::from_u128(1).to_string();
ensure!(
!retired_event(&journal, &other)?,
"NONSTART_CONTRACT_OTHER_MESSAGE_MUST_REMAIN_ACTIVE"
);
other = event;
other.observed_at += 1;
ensure!(
!retired_event(&journal, &other)?,
"NONSTART_CONTRACT_OTHER_RAW_MUST_REMAIN_ACTIVE"
);
// Keep the valid signed receipt byte-identical. Change only local originals,
// so these failures exercise semantic binding after signature validation.
db.execute(
"UPDATE consumed SET grant_id=?1",
[Uuid::from_u128(1).to_string()],
)?;
ensure!(
effective_outcome(&db, Some(&local), dto::GRANT).is_err(),
"NONSTART_GRANT_NEGATIVE_FAILED"
);
db.execute("UPDATE consumed SET grant_id=?1", [dto::GRANT.to_string()])?;
let mut wrong_unknown = r.witness.agent_outcome.clone();
wrong_unknown[0] ^= 1;
db.execute("UPDATE execution_evidence SET outcome=?1", [wrong_unknown])?;
ensure!(
effective_outcome(&db, Some(&local), dto::GRANT).is_err(),
"NONSTART_ORIGINAL_NEGATIVE_FAILED"
);
Ok(
serde_json::json!({"valid_actual_signed_receipt":true,"original_placeholder_retired":true,"other_message_not_retired":true,"other_raw_not_retired":true,"physical_placeholder_preserved":true,"original_helper_cache_refreshed_once":true,"stale_cache_failure_reproduced":true,"resolved_unlock_storage_guard_preserves_original":true,"wrong_signature_rejected":true,"wrong_grant_rejected":true,"wrong_original_hash_rejected":true,"product_databases_opened":false,"effects":false}),
)
}
+4 -5
View File
@@ -13,11 +13,6 @@ name = "rmm-helper-windows"
path = "src/bin/rmm-helper-windows.rs"
required-features = ["system-helper"]
[[bin]]
name = "rmm-updater-windows"
path = "src/bin/rmm-updater-windows.rs"
required-features = ["system-helper"]
[dependencies]
anyhow.workspace = true
base64 = "=0.22.1"
@@ -63,3 +58,7 @@ name = "windows_system_result_witness"
required-features = ["system-helper"]
[dev-dependencies]
[[example]]
name = "windows_system_nonstart_closed"
required-features = ["system-helper"]
@@ -386,6 +386,7 @@ mod probe {
role: Role::Agent,
helper_image_sha256: None,
binding_schema: 1,
updater_image_sha256: None,
},
};
if kind == "tenant-mismatch" {
@@ -0,0 +1,79 @@
//! Offline, deny-only typed transition from the existing 30s script policy to
//! passive new pair pins. No files, IPC, services, sync, jobs or approvals.
#[cfg(all(windows, feature = "system-helper"))]
fn main() -> anyhow::Result<()> {
use anyhow::{Result, ensure};
use rmm_agent_windows::helper_system::Settings;
use rmm_domain::jobs::{PrivilegedScriptProfile, hash};
use serde::Deserialize;
use std::io::{Read, Write};
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Input {
schema_version: u32,
current_settings: Vec<u8>,
current_settings_sha256: String,
new_agent_sha256: String,
new_helper_sha256: String,
}
fn render(input: Input) -> Result<serde_json::Value> {
ensure!(
input.schema_version == 1
&& !input.current_settings.is_empty()
&& input.current_settings.len() <= 32768
&& hash(&input.current_settings) == input.current_settings_sha256
&& rmm_domain::agent_update::digest(&input.new_agent_sha256)
&& rmm_domain::agent_update::digest(&input.new_helper_sha256),
"SCRIPT_PAIR_PREPARE_INPUT"
);
let mut settings: Settings = serde_json::from_slice(&input.current_settings)?;
settings.validate()?;
ensure!(
settings.schema_version == 3
&& settings.enable_effects
&& settings.max_runtime_seconds == 30
&& !settings.allow_reboot
&& settings.allowed_services.is_empty()
&& settings.allowed_msi_recipe_sha256.is_none()
&& settings.allowed_script_profiles.as_deref()
== Some(&[PrivilegedScriptProfile::FullMaintenanceV1])
&& settings.agent.binary_sha256 != input.new_agent_sha256
&& settings.helper.binary_sha256 != input.new_helper_sha256,
"SCRIPT_PAIR_EXACT_ORIGINAL_30S_SCOPE_REQUIRED"
);
settings.agent.binary_sha256 = input.new_agent_sha256;
settings.helper.binary_sha256 = input.new_helper_sha256;
settings.enable_effects = false;
settings.allowed_script_profiles = None;
settings.validate()?;
let settings_bytes = serde_json::to_vec(&settings)?;
let pin = settings.pin()?;
let pin_bytes = serde_json::to_vec(&pin)?;
ensure!(
pin.policy_sha256 == hash(&settings_bytes),
"SCRIPT_PAIR_CANONICAL_POLICY"
);
Ok(
serde_json::json!({"schema_version":1,"source":"actual_rust_settings_codec",
"prepared_only":true,"target_mutations":false,"target_job_executed":false,
"effects_enabled":false,"settings_bytes":settings_bytes,"settings_sha256":hash(&settings_bytes),
"pin_bytes":pin_bytes,"pin_sha256":hash(&pin_bytes),"policy_sha256":pin.policy_sha256,
"helper_settings_source_sha256":hash(include_bytes!("../src/helper_system.rs")),
"peer_codec_source_sha256":hash(include_bytes!("../src/helper_ipc.rs"))}),
)
}
let mut input = Vec::new();
std::io::stdin()
.take(128 * 1024 + 1)
.read_to_end(&mut input)?;
ensure!(input.len() <= 128 * 1024, "SCRIPT_PAIR_PREPARE_FRAME_LIMIT");
let output = render(serde_json::from_slice(&input)?)?;
std::io::stdout().write_all(&serde_json::to_vec(&output)?)?;
std::io::stdout().write_all(b"\n")?;
Ok(())
}
#[cfg(not(all(windows, feature = "system-helper")))]
fn main() {
eprintln!("Windows/system-helper typed renderer only; no operation executed");
std::process::exit(2);
}
@@ -0,0 +1,587 @@
//! Explicit G205 bootstrap operator. No service stop/start, job, enrollment,
//! configuration rewrite, clock bootstrap or normal HelperSync::apply.
#[cfg(all(windows, feature = "system-helper"))]
mod platform {
use anyhow::{Context, Result, ensure};
use fs2::FileExt;
use rmm_agent_core::{
auth::Binding,
windows_system_nonstart::{self as recovery, ClosedPairGuard, Local},
};
use rmm_agent_windows::{
SERVICE_NAME,
helper_ipc::{self as ipc, PinnedFile},
helper_runtime::intent,
helper_system, native,
};
use rmm_domain::{
jobs::hash,
windows_system_nonstart::{BOOT, FILE_ROLES, NativeFile, NonstartProof},
};
use rusqlite::{Connection, OpenFlags};
use std::{
cell::RefCell,
fs::{File, OpenOptions},
io::{Read, Seek, SeekFrom},
os::windows::{fs::OpenOptionsExt, io::AsRawHandle},
path::{Path, PathBuf},
};
use uuid::Uuid;
use windows_sys::Win32::{Security::*, Storage::FileSystem::*, System::Services::*};
static PHASE: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
fn phase(value: usize) {
PHASE.store(value, std::sync::atomic::Ordering::Relaxed);
}
pub fn diagnostic(error: &anyhow::Error) -> serde_json::Value {
let phases = [
"arguments",
"admin_and_stopped",
"public_binding",
"helper_settings",
"lifetime_locks",
"intent_acl",
"held_file_ids",
"boot_measurement",
"intent_empty_snapshot",
"journal_open",
"original_identity_rows",
"witness_or_apply",
];
let codes = error
.chain()
.filter_map(|cause| {
let text = cause.to_string();
(text.len() <= 96
&& !text.is_empty()
&& text
.bytes()
.all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || b == b'_'))
.then_some(text)
})
.take(8)
.collect::<Vec<_>>();
let mut data = serde_json::json!({"schema_version":1,"diagnostic_only":true,"phase":phases.get(PHASE.load(std::sync::atomic::Ordering::Relaxed)).unwrap_or(&"unknown"),"codes":codes});
for cause in error.chain() {
if let Some(sql) = cause.downcast_ref::<rusqlite::Error>() {
data["sqlite"] = match sql {
rusqlite::Error::SqliteFailure(code, _) => {
serde_json::json!({"code":"SQLITE_FAILURE","sqlite_code":format!("{:?}",code.code),"extended_code":code.extended_code})
}
rusqlite::Error::QueryReturnedNoRows => {
serde_json::json!({"code":"SQLITE_NO_ROWS"})
}
rusqlite::Error::InvalidColumnType(index, name, _) => {
serde_json::json!({"code":"SQLITE_COLUMN_TYPE","index":index,"column":if name.len()<=48&&name.bytes().all(|b|b.is_ascii_alphanumeric()||b==b'_'){name.as_str()}else{"redacted"}})
}
_ => serde_json::json!({"code":"SQLITE_READ_FAILED"}),
};
break;
}
if let Some(codec) = cause.downcast_ref::<serde_json::Error>() {
data["codec"] = serde_json::json!({"code":"JSON_CODEC","line":codec.line(),"column":codec.column()});
}
if let Some(io) = cause.downcast_ref::<std::io::Error>() {
data["io"] = serde_json::json!({"kind":format!("{:?}",io.kind()),"os_code":io.raw_os_error()});
}
}
data
}
const ROOT: &str = r"C:\ProgramData\RustDiscovery";
const STATE: &str = r"C:\ProgramData\RustDiscovery\state";
const PATHS: [&str; 6] = [
r"C:\ProgramData\RustDiscovery\state\telemetry.sqlite",
r"C:\ProgramData\RustDiscovery\state\consumption.sqlite",
r"C:\ProgramData\RustDiscovery\state\agent.lock",
r"C:\ProgramData\RustDiscoverySystem\state\ledger.sqlite",
r"C:\ProgramData\RustDiscoverySystem\state\executor.lock",
intent::DB,
];
struct Sc(SC_HANDLE);
impl Drop for Sc {
fn drop(&mut self) {
unsafe { CloseServiceHandle(self.0) };
}
}
fn stopped(name: &str) -> Result<()> {
let manager =
Sc(unsafe { OpenSCManagerW(std::ptr::null(), std::ptr::null(), SC_MANAGER_CONNECT) });
ensure!(!manager.0.is_null(), "ALIGN_SCM_MANAGER");
let wide = name.encode_utf16().chain(Some(0)).collect::<Vec<_>>();
let service = Sc(unsafe { OpenServiceW(manager.0, wide.as_ptr(), SERVICE_QUERY_STATUS) });
ensure!(!service.0.is_null(), "ALIGN_SCM_SERVICE");
let mut status: SERVICE_STATUS_PROCESS = unsafe { std::mem::zeroed() };
let mut size = 0;
ensure!(
unsafe {
QueryServiceStatusEx(
service.0,
SC_STATUS_PROCESS_INFO,
(&mut status as *mut SERVICE_STATUS_PROCESS).cast(),
std::mem::size_of::<SERVICE_STATUS_PROCESS>() as u32,
&mut size,
)
} != 0
&& status.dwCurrentState == SERVICE_STOPPED,
"ALIGN_BOTH_SERVICES_MUST_BE_STOPPED"
);
Ok(())
}
fn both() -> Result<()> {
stopped(SERVICE_NAME)?;
stopped(ipc::HELPER_SERVICE)
}
fn admin() -> Result<()> {
let mut sid = [0usize; 16];
let mut len = std::mem::size_of_val(&sid) as u32;
let mut member = 0;
ensure!(
unsafe {
CreateWellKnownSid(
WinBuiltinAdministratorsSid,
std::ptr::null_mut(),
sid.as_mut_ptr().cast(),
&mut len,
)
} != 0
&& unsafe {
CheckTokenMembership(std::ptr::null_mut(), sid.as_mut_ptr().cast(), &mut member)
} != 0
&& member != 0,
"ALIGN_ADMINISTRATOR_REQUIRED"
);
Ok(())
}
fn leaf(path: &Path) -> Result<File> {
for parent in path.ancestors() {
ensure!(
std::os::windows::fs::MetadataExt::file_attributes(&parent.symlink_metadata()?)
& FILE_ATTRIBUTE_REPARSE_POINT
== 0,
"ALIGN_NO_REPARSE"
);
}
let file = OpenOptions::new()
.read(true)
.share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE)
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
.open(path)?;
native_id(&file)?;
Ok(file)
}
fn native_id(file: &File) -> Result<[u32; 3]> {
let mut i: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
ensure!(
unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut i) } != 0
&& i.nNumberOfLinks == 1
&& i.dwFileAttributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT)
== 0,
"ALIGN_FILE_ID"
);
Ok([i.dwVolumeSerialNumber, i.nFileIndexHigh, i.nFileIndexLow])
}
fn bytes(mut file: &File, max: u64) -> Result<Vec<u8>> {
ensure!(file.metadata()?.len() <= max, "ALIGN_FILE_LIMIT");
file.seek(SeekFrom::Start(0))?;
let mut data = vec![];
file.take(max + 1).read_to_end(&mut data)?;
ensure!(data.len() as u64 <= max, "ALIGN_FILE_CHANGED");
Ok(data)
}
struct Held {
path: PathBuf,
file: File,
id: ipc::FileIdentity,
legacy: [u32; 3],
}
struct Guard {
held: Vec<Held>,
_locks: Vec<File>,
_settings: RefCell<Vec<PinnedFile>>,
_public: RefCell<Vec<PinnedFile>>,
boot: Uuid,
intents: RefCell<intent::Store>,
}
impl ClosedPairGuard for Guard {
fn check(&self) -> Result<()> {
both()?;
self.intents.borrow_mut().check()?;
for file in self
._settings
.borrow_mut()
.iter_mut()
.chain(self._public.borrow_mut().iter_mut())
{
file.check()?;
}
ensure!(
ipc::file_identity(&self._locks[0])? == self.held[2].id
&& ipc::file_identity(&self._locks[1])? == self.held[4].id,
"ALIGN_ORIGINAL_LOCK_OWNER_HANDLES"
);
for h in &self.held {
ensure!(
ipc::file_identity(&h.file)? == h.id
&& native_id(&h.file)? == h.legacy
&& ipc::file_identity(&leaf(&h.path)?)? == h.id,
"ALIGN_ORIGINAL_FILE_REPLACED"
);
}
Ok(())
}
fn files(&self) -> Result<[NativeFile; 6]> {
self.check()?;
let mut out = vec![];
for (index, (h, role)) in self.held.iter().zip(FILE_ROLES).enumerate() {
// Read a lifetime lock ONLY through the original HANDLE that
// owns its LockFileEx range; a second handle is correctly denied.
let f = match index {
2 => &self._locks[0],
4 => &self._locks[1],
_ => &h.file,
};
out.push(NativeFile {
role: role.into(),
file_id: Some(h.legacy),
sha256: Some(hash(&bytes(f, 256 * 1024 * 1024).context(match index {
0 => "ALIGN_HASH_TELEMETRY",
1 => "ALIGN_HASH_CONSUMPTION",
2 => "ALIGN_HASH_AGENT_LOCK",
3 => "ALIGN_HASH_HELPER_LEDGER",
4 => "ALIGN_HASH_HELPER_LOCK",
_ => "ALIGN_HASH_SYSTEM_INTENTS",
})?)),
});
}
out.try_into()
.map_err(|_| anyhow::anyhow!("ALIGN_FILE_COUNT"))
}
fn boot(&self) -> Result<Uuid> {
Ok(self.boot)
}
}
struct Db {
db: Connection,
_held: Vec<File>,
}
impl Db {
fn open(path: &str, write: bool) -> Result<Self> {
let mut file = leaf(Path::new(path))?;
let mut header = [0; 20];
file.read_exact(&mut header)?;
ensure!(
header.starts_with(b"SQLite format 3\0")
&& header[18] == header[19]
&& matches!(header[18], 1 | 2),
"ALIGN_SQLITE_HEADER"
);
let mut held = vec![file];
let mut wal = false;
let mut shm = false;
let mut journal = false;
for (suffix, present) in [
("-wal", &mut wal),
("-shm", &mut shm),
("-journal", &mut journal),
] {
let p = format!("{path}{suffix}");
if Path::new(&p).try_exists()? {
held.push(leaf(Path::new(&p))?);
*present = true;
}
}
let flags = if write {
OpenFlags::SQLITE_OPEN_READ_WRITE
} else {
OpenFlags::SQLITE_OPEN_READ_ONLY
};
let db = if !write && header[18] == 2 && !(wal && shm) {
ensure!(!wal && !shm && !journal, "ALIGN_ORIGINAL_WAL_INCOMPLETE");
Connection::open_with_flags(
format!("file:///{}?mode=ro&immutable=1", path.replace('\\', "/")),
flags | OpenFlags::SQLITE_OPEN_URI,
)?
} else {
Connection::open_with_flags(path, flags)?
};
db.busy_timeout(std::time::Duration::from_millis(500))?;
Ok(Self { db, _held: held })
}
}
pub fn run() -> Result<()> {
let args = std::env::args().skip(1).collect::<Vec<_>>();
if args == ["--receipt-contract"] {
let file = PinnedFile::open(
Path::new(
r"C:\ProgramData\RustDiscoveryBootstrap\system-nonstart-221-receipt.json",
),
false,
&[],
&[],
false,
)?;
let event=PinnedFile::open(Path::new(r"C:\ProgramData\RustDiscoveryBootstrap\6907fdbbcd1c287c2545fde2f9ebae54fd3b6629b10b61dc5d3884584d8c74c9\placeholder-envelope.pb"),false,&[],&[],false)?;
println!("{}",serde_json::to_string(&recovery::receipt_contract(&bytes(&file.file,4*1024*1024)?,&bytes(&event.file,16384)?)?)?);
return Ok(());
}
let apply = args == ["--apply"];
let verify = args == ["--verify-applied"];
ensure!(
apply || verify || args == ["--witness"],
"ALIGN_FIXED_ARGUMENTS"
);
phase(1);
admin()?;
both()?;
phase(2);
let readers = [ipc::service_sid(SERVICE_NAME)?];
let mut public = vec![PinnedFile::open(
Path::new(ROOT),
true,
&readers,
&[],
false,
)?];
let binding_file = PinnedFile::open(
&Path::new(ROOT).join("binding.json"),
false,
&readers,
&[],
false,
)?;
let binding: Binding = serde_json::from_slice(&bytes(&binding_file.file, 8192)?)?;
public.push(binding_file);
phase(3);
let (settings, pins) = helper_system::read_settings()?;
ensure!(
settings.enable_effects
&& !settings.allow_reboot
&& settings.schema_version == 3
&& settings.pin()?.policy_sha256
== "cfd126d383ec0a948a73270a8362bd835d79341a079be05ce50088f0dbc5791c",
"ALIGN_ORIGINAL_PASSIVE_HELPER_ONLY"
);
phase(4);
let mut locks = vec![];
for index in [2, 4] {
let file = leaf(Path::new(PATHS[index]))?;
file.try_lock_exclusive()
.context("ALIGN_ORIGINAL_LIFETIME_LOCK_BUSY")?;
locks.push(file);
}
both()?;
native::private_path(Path::new(STATE), true)?;
phase(5);
let helper_writer = [ipc::service_sid(ipc::HELPER_SERVICE)?];
let agent_writer = [ipc::service_sid(SERVICE_NAME)?];
public.push(PinnedFile::open_read_shared(
Path::new(intent::ROOT),
true,
&agent_writer,
&[],
)?);
for path in [intent::DB, &format!("{}-journal", intent::DB)] {
let proof = PinnedFile::open_read_shared(Path::new(path), false, &[], &agent_writer)?;
public.push(proof);
}
phase(6);
let mut held = vec![];
for (index, path) in PATHS.into_iter().enumerate() {
if matches!(index, 3 | 4) {
let _check =
PinnedFile::open_read_shared(Path::new(path), false, &[], &helper_writer)?;
} else if index != 5 {
native::private_path(Path::new(path), false)?;
}
let file = leaf(Path::new(path))?;
held.push(Held {
path: PathBuf::from(path),
id: ipc::file_identity(&file)?,
legacy: native_id(&file)?,
file,
});
}
phase(7);
let boot = Uuid::parse_str(
&tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()?
.block_on(native::boot_id())?,
)?;
ensure!(boot == BOOT, "ALIGN_ORIGINAL_BOOT_REQUIRED");
phase(8);
let guard = Guard {
held,
_locks: locks,
_settings: RefCell::new(pins),
_public: RefCell::new(public),
boot,
intents: RefCell::new(intent::Store::open(false)?),
};
guard.check()?;
phase(9);
let a = Db::open(PATHS[0], apply).context("ALIGN_OPEN_TELEMETRY_RO")?;
let c = Db::open(PATHS[1], apply).context("ALIGN_OPEN_CONSUMPTION_RO")?;
let h = Db::open(PATHS[3], apply).context("ALIGN_OPEN_HELPER_JOURNAL")?;
let intents = Db::open(PATHS[5], false).context("ALIGN_OPEN_INTENTS_RO")?;
phase(10);
let intents_identity: Vec<u8> = intents.db.query_row(
"SELECT file_identity FROM system_intent_meta WHERE id=1",
[],
|r| r.get(0),
)?;
ensure!(
serde_json::from_slice::<ipc::FileIdentity>(&intents_identity)? == guard.held[5].id,
"ALIGN_ORIGINAL_INTENT_JOURNAL_IDENTITY"
);
let (ledger, lock, identity): (Vec<u8>, Vec<u8>, String) = h.db.query_row(
"SELECT ledger,executor_lock,binding_sha256 FROM windows_helper_files WHERE id=1",
[],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
)?;
ensure!(
serde_json::from_slice::<ipc::FileIdentity>(&ledger)? == guard.held[3].id
&& serde_json::from_slice::<ipc::FileIdentity>(&lock)? == guard.held[4].id
&& identity == ipc::binding_hash(&settings.binding)?,
"ALIGN_HELPER_ORIGINAL_LEDGER_LOCK_IDENTITY"
);
phase(11);
let live_file = PinnedFile::open(
Path::new(
r"C:\ProgramData\RustDiscoveryBootstrap\1f18d4273d5d19bdc9d8b3bfe4ed49c7aaa0b7cc282c9a04024896f8db274b85\native-live-archive.json",
),
false,
&[],
&[],
false,
)?;
let live_raw = bytes(&live_file.file, 1024 * 1024)?;
ensure!(
hash(&live_raw) == "1f18d4273d5d19bdc9d8b3bfe4ed49c7aaa0b7cc282c9a04024896f8db274b85",
"NONSTART_EXACT_LIVE_ARCHIVE"
);
let archived: serde_json::Value = serde_json::from_slice(&live_raw)?;
let live = &archived["live_archive"];
let stop_file = PinnedFile::open(
Path::new(
r"C:\ProgramData\RustDiscoveryBootstrap\system-nonstart-221-stop\stopped.json",
),
false,
&[],
&[],
false,
)?;
let stop_raw = bytes(&stop_file.file, 32768)?;
let stop: serde_json::Value = serde_json::from_slice(&stop_raw)?;
ensure!(
stop["both_stopped"] == true
&& stop["force_used"] == false
&& stop["original_held_process_exits_verified"] == true
&& stop["journal_rows_changed_by_bootstrap"] == false
&& stop["target_job_executed"] == false
&& stop["live_archive_sha256"] == hash(&live_raw),
"NONSTART_ORIGINAL_HELD_EXIT_PROOF"
);
ensure!(
stop["original_services"]["RmmDiscoverySystemHelper"]["pid"] == 1304
&& stop["original_services"]["RmmDiscoverySystemHelper"]["birth"]
== "134393135436289391"
&& stop["original_services"]["RmmDiscoveryWindows"]["pid"] == 8688
&& stop["original_services"]["RmmDiscoveryWindows"]["birth"]
== "134393135446375865",
"NONSTART_ORIGINAL_LIFETIMES"
);
let nonstart = NonstartProof {
helper_pid: 1304,
helper_birth_filetime: live["helper_birth_filetime"]
.as_str()
.context("NONSTART_BIRTH")?
.into(),
helper_image_sha256: live["helper_image_sha256"]
.as_str()
.context("NONSTART_IMAGE")?
.into(),
system_script_source_sha256: live["system_script_source_sha256"]
.as_str()
.context("NONSTART_SOURCE")?
.into(),
read_share_error: serde_json::from_value(live["read_share_error"].clone())?,
read_write_share_passed: live["read_write_share_passed"] == true,
state_directory_file_id: serde_json::from_value(
live["state_directory_file_id"].clone(),
)?,
evidence_sha256: vec![hash(&live_raw), hash(&stop_raw)],
};
ensure!(
nonstart.valid() && live["original_peer_verified_before_after"] == true,
"NONSTART_ORIGINAL_LIVE_PROOF"
);
let local = Local {
agent: &a.db,
consumption: &c.db,
helper: &h.db,
intents: &intents.db,
binding: &binding,
helper_binding: &settings.binding,
};
if apply || verify {
let file = PinnedFile::open(
Path::new(
r"C:\ProgramData\RustDiscoveryBootstrap\system-nonstart-221-receipt.json",
),
false,
&[],
&[],
false,
)?;
let raw = bytes(&file.file, 4 * 1024 * 1024)?;
if apply {
recovery::apply(&local, &guard, &raw, chrono::Utc::now())?;
}
println!(
"{}",
serde_json::to_string(&recovery::verify_applied(&local, &guard, &raw)?)?
);
return Ok(());
}
let witness = recovery::witness(&local, &guard, nonstart)?;
for (name, raw) in [
("target_job_offer", &witness.target_job_offer),
("agent_start", &witness.agent_start),
("helper_start", &witness.helper_start),
("agent_outcome", &witness.agent_outcome),
("helper_outcome", &witness.helper_outcome),
("intent", &witness.intent),
] {
ensure!(
serde_json::from_value::<Vec<u8>>(live[name].clone())? == *raw,
"NONSTART_LIVE_ARCHIVE_ORIGINAL_CHANGED"
);
}
for index in 0..2 {
ensure!(
serde_json::from_value::<Vec<u8>>(live["original_requests"][index].clone())?
== witness.original_requests[index]
&& serde_json::from_value::<rmm_domain::checkpoint_repair::SignedDecision>(
live["original_responses"][index].clone()
)? == witness.original_responses[index],
"NONSTART_LIVE_ORIGINAL_SYNCS_CHANGED"
);
}
guard.check()?;
println!("{}", serde_json::to_string(&witness)?);
Ok(())
}
}
#[cfg(all(windows, feature = "system-helper"))]
fn main() {
if let Err(error) = platform::run() {
eprintln!("{}", platform::diagnostic(&error));
std::process::exit(1);
}
}
#[cfg(not(all(windows, feature = "system-helper")))]
fn main() {
eprintln!("Windows system-helper only");
std::process::exit(1);
}
+2
View File
@@ -739,6 +739,7 @@ mod installed {
let own_pin = match role {
Role::Agent => &settings.agent,
Role::SystemHelper => &settings.helper,
Role::Updater => anyhow::bail!("TIME_UPDATER_OWN_PROFILE_REQUIRED"),
};
own_pin.validate(role == Role::SystemHelper)?;
ipc::require_self(own_pin)?;
@@ -816,6 +817,7 @@ mod installed {
helper_image_sha256: (role == Role::SystemHelper)
.then(|| own_pin.binary_sha256.clone()),
binding_schema: 1,
updater_image_sha256: None,
};
files.push(config_file);
let mut value = Self {