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 {
+222
View File
@@ -0,0 +1,222 @@
#!/usr/bin/env python3
"""Fixed existing expired Windows script ceiling renewal; Root invokes separately.
No CLI dispatch, job/approval, container recreation, membership, environment or
mount mutation. A committed intent makes this case readback-only, never retry.
"""
def renew_existing_expired_policy(payload):
import datetime as dt
import fcntl
import hashlib
import json
import os
from pathlib import Path
import re
import stat
import subprocess
import uuid
def require(value, code):
if not value:
raise RuntimeError(code)
require(os.geteuid() == 0, 'SYSTEM_RENEW_ROOT_BOOTSTRAP')
require(set(payload) == {'operation', 'case_id', 'expected_roles', 'helper_binary_sha256', 'helper_policy_sha256', 'acceptance_evidence_id'}, 'SYSTEM_RENEW_FIXED_INPUT')
require(payload['operation'] == 'windows_system_existing_expired_script_scope_renew_v1', 'SYSTEM_RENEW_OPERATION')
ident = str(uuid.UUID(payload['case_id']))
evidence_id = str(uuid.UUID(payload['acceptance_evidence_id']))
require(ident == payload['case_id'] and evidence_id == payload['acceptance_evidence_id'] and uuid.UUID(ident).int and uuid.UUID(evidence_id).int, 'SYSTEM_RENEW_CANONICAL_IDS')
require(all(re.fullmatch('[a-f0-9]{64}', payload[n]) for n in ('helper_binary_sha256', 'helper_policy_sha256')), 'SYSTEM_RENEW_FINAL_PINS')
root = Path('/opt/rust-discovery')
tenant = '11111111-1111-4111-8111-111111111111'
asset = 'a176520e-8a91-4e93-a78b-8e7620f430e0'
agent = '63ea15b2-0643-403d-b5b4-cba1288dbea3'
actors = ['automation:' + tenant, 'simulated-testprincipal-a']
mounted = root / 'devstate/windows-system-policy/5fb6d7c9-d2b4-472c-b4fc-2ffea27e3c33/mounted'
original_sha = 'c4993009e62ef9c384ea11a2f201566c2e657c1ba3b452410bb2a9d4774b0169'
case = root / 'devstate/windows-system-policy' / ('renew-' + ident)
epoch_intent = mounted.parent / 'renew-c4993009-intent.json'
def run(args, data=None):
return subprocess.run(args, input=data, capture_output=True, check=True, timeout=25).stdout
def encode(value):
return json.dumps(value, sort_keys=True, separators=(',', ':')).encode()
def digest(data):
return hashlib.sha256(data).hexdigest()
def sync_directory(path):
fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
try:
os.fsync(fd)
finally:
os.close(fd)
def create(path, data, uid=0, gid=0):
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
with os.fdopen(fd, 'wb') as stream:
os.fchown(stream.fileno(), uid, gid)
os.fchmod(stream.fileno(), 0o600)
stream.write(data)
stream.flush()
os.fsync(stream.fileno())
def identity(m):
return [m.st_dev, m.st_ino, m.st_uid, m.st_gid, stat.S_IMODE(m.st_mode), m.st_nlink]
def directory(path, uid=None):
m = path.lstat()
require(stat.S_ISDIR(m.st_mode) and not stat.S_ISLNK(m.st_mode) and not m.st_mode & 0o022, 'SYSTEM_RENEW_PROTECTED_DIRECTORY')
if uid is not None:
require(m.st_uid == uid and m.st_gid == uid and stat.S_IMODE(m.st_mode) == 0o700, 'SYSTEM_RENEW_EXACT_DIRECTORY_OWNER')
return identity(m)
for parent in [root, root / 'devstate', root / 'devstate/windows-system-policy', mounted.parent, mounted]:
directory(parent)
directory(mounted.parent, 0)
mounted_identity = directory(mounted, 10001)
key = (root / 'devstate/jobs/ed25519.pem').lstat() # STAT ONLY, no key content.
require(stat.S_ISREG(key.st_mode) and key.st_nlink == 1 and key.st_uid == key.st_gid == 10001 and stat.S_IMODE(key.st_mode) == 0o600, 'SYSTEM_RENEW_JOB_KEY_OWNER_STAT_ONLY')
roles = payload['expected_roles']
require(set(roles) == {'api', 'gateway'}, 'SYSTEM_RENEW_BOTH_CURRENT_ROLES')
def runtime(role):
expected = roles[role]
require(set(expected) == {'container_id', 'image'} and re.fullmatch('[a-f0-9]{64}', expected['container_id']) and re.fullmatch('sha256:[a-f0-9]{64}', expected['image']), 'SYSTEM_RENEW_CURRENT_CONTAINER_WITNESS')
c = json.loads(run(['docker', 'inspect', expected['container_id']]))[0]
h, conf = c['HostConfig'], c['Config']
require(c['Name'] == '/rust-discovery-server-' + role + '-1' and c['State']['Running'] and c['Image'] == expected['image'], 'SYSTEM_RENEW_CONTAINER_CAS')
require(conf['User'] == '10001:10001' and h['ReadonlyRootfs'] and h['CapDrop'] == ['ALL'] and not h.get('CapAdd') and h['SecurityOpt'] == ['no-new-privileges:true'] and not h['Privileged'], 'SYSTEM_RENEW_SANDBOX')
port = {'api': '18443', 'gateway': '18444'}[role]
require(h['PortBindings'] == {'18443/tcp': [{'HostIp': '127.0.0.1', 'HostPort': port}]} and h.get('PidMode', '') == '' and h.get('IpcMode') == 'private' and h.get('UsernsMode', '') == '' and h['NetworkMode'] in c['NetworkSettings']['Networks'] and not h.get('Devices'), 'SYSTEM_RENEW_PRIVATE_NAMESPACES_AND_PORT')
env = {}
for entry in conf['Env']:
name, separator, value = entry.partition('=')
require(separator and name not in env, 'SYSTEM_RENEW_ENVIRONMENT')
env[name] = value # private RAM only, never output credentials.
require(env.get('RMM_PROFILE') == 'development' and env.get('RMM_DEV_SYSTEM_ENABLED') == 'true' and env.get('RMM_DEV_SYSTEM_POLICY_FILE') == '/system-policy/policy.json', 'SYSTEM_RENEW_EXISTING_ENABLED_FILE')
mounts = [m for m in c['Mounts'] if m['Destination'] == '/system-policy']
require(len(mounts) == 1 and mounts[0]['Type'] == 'bind' and mounts[0]['Source'] == str(mounted) and mounts[0]['RW'] is False and mounts[0]['Propagation'] == 'rprivate', 'SYSTEM_RENEW_EXISTING_READONLY_DIRECTORY_MOUNT')
# Compare the complete actual configuration again after the one file
# operation; no env/container/membership delta is permitted.
return {'id': c['Id'], 'image': c['Image'], 'config': conf, 'host': h, 'mounts': c['Mounts'], 'networks': sorted(c['NetworkSettings']['Networks'])}
before_roles = {role: runtime(role) for role in ('api', 'gateway')}
lock_path = root / 'devstate/.windows-system-scope.lock'
lock = os.open(lock_path, os.O_WRONLY | os.O_CREAT | os.O_NOFOLLOW, 0o600)
try:
lm = os.fstat(lock)
require(stat.S_ISREG(lm.st_mode) and lm.st_uid == 0 and stat.S_IMODE(lm.st_mode) == 0o600 and lm.st_nlink == 1, 'SYSTEM_RENEW_ORIGINAL_SCOPE_LOCK')
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
require(not case.exists() and not epoch_intent.exists(), 'SYSTEM_RENEW_EXISTING_CASE_OR_EPOCH_READBACK_ONLY')
policy_path = mounted / 'policy.json'
fd = os.open(policy_path, os.O_RDONLY | os.O_NOFOLLOW)
with os.fdopen(fd, 'rb') as original:
old_meta = os.fstat(original.fileno())
require(stat.S_ISREG(old_meta.st_mode) and old_meta.st_nlink == 1 and old_meta.st_uid == old_meta.st_gid == 10001 and stat.S_IMODE(old_meta.st_mode) == 0o600 and old_meta.st_size <= 65536, 'SYSTEM_RENEW_EXACT_OLD_POLICY_METADATA')
old_raw = original.read(65537)
require(len(old_raw) <= 65536 and digest(old_raw) == original_sha, 'SYSTEM_RENEW_OLD_EXPIRED_POLICY_CAS')
old = json.loads(old_raw)
require(set(old) == {'schema_version', 'profile', 'expires_at', 'scopes'} and old['schema_version'] == 3 and old['profile'] == 'development' and len(old['scopes']) == 1, 'SYSTEM_RENEW_OLD_POLICY_FORM')
scope = old['scopes'][0]
fields = {'tenant_id', 'asset_id', 'agent_id', 'enrollment_generation', 'assignment_version', 'principals', 'helper_policy_sha256', 'helper_binary_sha256', 'acceptance_evidence_id', 'allowed_services', 'max_runtime_seconds', 'allowed_script_profiles'}
require(set(scope) == fields and scope['tenant_id'] == tenant and scope['asset_id'] == asset and scope['agent_id'] == agent and scope['enrollment_generation'] == scope['assignment_version'] == 1 and scope['principals'] == actors and scope['allowed_services'] == [] and scope['max_runtime_seconds'] == 30 and scope['allowed_script_profiles'] == ['full_maintenance_v1'], 'SYSTEM_RENEW_SAME_SCRIPT_ONLY_SCOPE')
now = dt.datetime.now(dt.timezone.utc)
expiry = dt.datetime.fromisoformat(old['expires_at'].replace('Z', '+00:00'))
require(expiry.tzinfo is not None and expiry <= now, 'SYSTEM_RENEW_OLD_WINDOW_MUST_BE_EXPIRED')
require(scope['helper_binary_sha256'] != payload['helper_binary_sha256'] and scope['helper_policy_sha256'] != payload['helper_policy_sha256'] and scope['acceptance_evidence_id'] != evidence_id, 'SYSTEM_RENEW_NEW_INDEPENDENT_FINAL_PAIR_PROOF')
sql = ("BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY; SELECT json_build_object("
"'installation',(SELECT json_build_object('ready',sync_ready,'helper_ready',helper_sync_ready,'blocked',restore_blocked,'fresh',last_contact_at>clock_timestamp()-interval '45 seconds','same_certificate',certificate_sha256=last_authenticated_certificate_sha256,'auth_fresh',last_authenticated_at>clock_timestamp()-interval '45 seconds','capabilities',capabilities) FROM agent_installations WHERE tenant_id='" + tenant + "' AND asset_id='" + asset + "' AND agent_id='" + agent + "' AND enrollment_generation=1 AND assignment_version=1 AND revoked_at IS NULL),"
"'open_jobs',(SELECT count(*) FROM jobs WHERE tenant_id='" + tenant + "' AND agent_id='" + agent + "' AND state NOT IN ('succeeded','failed','cancelled','expired')),"
"'original221',(SELECT state FROM jobs WHERE tenant_id='" + tenant + "' AND agent_id='" + agent + "' AND job_id='94047873-5088-433b-bc1b-490d3eafe0da' AND attempt_id='f071e6d6-8635-42f7-92fa-533c681edd8b'),"
"'memberships',(SELECT json_agg(q ORDER BY principal) FROM (SELECT principal,kind,permissions,revoked_at FROM memberships WHERE tenant_id='" + tenant + "' AND principal IN ('automation:" + tenant + "','simulated-testprincipal-a')) q)); COMMIT;")
observed = json.loads(run(['docker', 'exec', '-i', 'rust-discovery-server-postgres-1', 'psql', '-X', '-qAt', '-v', 'ON_ERROR_STOP=1', '-U', 'postgres', '-d', 'rmm'], sql.encode()))
live = observed['installation']
require(live and all(live[n] is True for n in ('ready', 'helper_ready', 'fresh', 'same_certificate', 'auth_fresh')) and live['blocked'] is False and observed['open_jobs'] == 0 and observed['original221'] == 'failed', 'SYSTEM_RENEW_ACTUAL_NORMAL_SYNC_AND_TERMINAL221')
needed = {'windows.base/1', 'rmm.sync.v1', 'helper.system.v1', 'system:run_script', 'script.full_maintenance/1', 'helper.binary.sha256:' + payload['helper_binary_sha256'], 'helper.policy.sha256:' + payload['helper_policy_sha256']}
require(needed <= set(live['capabilities']) and not {'linux.base/1', 'system:ensure_package', 'system:set_service_state', 'system:reboot'} & set(live['capabilities']), 'SYSTEM_RENEW_ACTUAL_NARROW_FINAL_CAPABILITIES')
memberships = observed['memberships']
require([m['principal'] for m in memberships] == actors and all(m['revoked_at'] is None and {'scripts:execute', 'system:execute'} <= set(m['permissions']) and m['kind'] == ('automation' if n == 0 else 'test_human') for n, m in enumerate(memberships)), 'SYSTEM_RENEW_SAME_EXISTING_AUTHORIZED_ACTORS')
new = json.loads(old_raw)
new['expires_at'] = (now + dt.timedelta(minutes=15)).isoformat()
new['scopes'][0].update(helper_binary_sha256=payload['helper_binary_sha256'], helper_policy_sha256=payload['helper_policy_sha256'], acceptance_evidence_id=evidence_id)
raw = encode(new)
create(epoch_intent, encode({'schema_version': 1, 'case_id': ident, 'old_policy_sha256': original_sha, 'new_policy_sha256': digest(raw), 'new_expires_at': new['expires_at'], 'automatic_retry': False}))
sync_directory(mounted.parent)
case.mkdir(mode=0o700)
create(case / 'intent.json', encode({'schema_version': 1, 'request': payload, 'old_policy_sha256': original_sha, 'old_policy_identity': identity(old_meta), 'new_policy_sha256': digest(raw), 'new_expires_at': new['expires_at'], 'database_readback': observed}))
create(case / 'original-policy.json', old_raw)
sync_directory(case)
sync_directory(case.parent)
stage_name = '.renew-' + ident + '.json'
stage = mounted / stage_name
create(stage, raw, 10001, 10001)
sync_directory(mounted)
require(directory(mounted, 10001) == mounted_identity and identity(policy_path.lstat()) == identity(old_meta) and policy_path.read_bytes() == old_raw and os.fstat(original.fileno()).st_ino == old_meta.st_ino, 'SYSTEM_RENEW_FINAL_NAMESPACE_CAS')
require({role: runtime(role) for role in ('api', 'gateway')} == before_roles, 'SYSTEM_RENEW_RUNTIME_CHANGED_BEFORE_SWAP')
os.replace(stage, policy_path)
sync_directory(mounted)
require(policy_path.read_bytes() == raw and policy_path.stat().st_uid == policy_path.stat().st_gid == 10001 and stat.S_IMODE(policy_path.stat().st_mode) == 0o600 and (case / 'original-policy.json').read_bytes() == old_raw, 'SYSTEM_RENEW_EXACT_FILE_READBACK')
require({role: runtime(role) for role in ('api', 'gateway')} == before_roles, 'SYSTEM_RENEW_RUNTIME_CHANGED_AFTER_SWAP')
result = {'schema_version': 1, 'case_id': ident, 'renewed': True, 'old_policy_sha256': original_sha, 'policy_sha256': digest(raw), 'expires_at': new['expires_at'], 'original_bytes_backup_verified': True, 'containers_unchanged': True, 'environment_unchanged': True, 'mounts_unchanged': True, 'memberships_changed': False, 'jobs_created': False, 'approvals_created': False, 'automatic_retry': False}
create(case / 'completed.json', encode(result))
sync_directory(case)
return result
finally:
os.close(lock)
def read_existing_policy_renewal(payload):
import hashlib
import json
import os
from pathlib import Path
import stat
import uuid
if os.geteuid() != 0 or set(payload) != {'operation', 'case_id'} or payload['operation'] != 'windows_system_existing_script_scope_renew_readback_v1':
raise RuntimeError('SYSTEM_RENEW_READBACK_INPUT')
ident = str(uuid.UUID(payload['case_id']))
if ident != payload['case_id']:
raise RuntimeError('SYSTEM_RENEW_READBACK_CASE')
parent = Path('/opt/rust-discovery/devstate/windows-system-policy')
case = parent / ('renew-' + ident)
active = parent / '5fb6d7c9-d2b4-472c-b4fc-2ffea27e3c33/mounted/policy.json'
epoch_path = active.parent.parent / 'renew-c4993009-intent.json'
def read(path, owner):
m = path.lstat()
if not stat.S_ISREG(m.st_mode) or m.st_nlink != 1 or m.st_uid != owner or stat.S_IMODE(m.st_mode) != 0o600 or m.st_size > 65536:
raise RuntimeError('SYSTEM_RENEW_READBACK_FILE')
raw = path.read_bytes()
after = path.lstat()
if (m.st_dev, m.st_ino, m.st_mtime_ns, m.st_size) != (after.st_dev, after.st_ino, after.st_mtime_ns, after.st_size):
raise RuntimeError('SYSTEM_RENEW_READBACK_CHANGED')
return raw
raw = read(active, 10001)
current_sha = hashlib.sha256(raw).hexdigest()
epoch = json.loads(read(epoch_path, 0)) if epoch_path.exists() else None
if epoch is not None and epoch['case_id'] != ident:
raise RuntimeError('SYSTEM_RENEW_READBACK_EPOCH_BOUND_TO_ANOTHER_CASE')
if not case.exists():
return {'read_only': True, 'case_present': False, 'epoch_intent_present': epoch is not None, 'policy_sha256': current_sha, 'retry_authorized': False}
m = case.lstat()
if not stat.S_ISDIR(m.st_mode) or m.st_uid != 0 or stat.S_IMODE(m.st_mode) != 0o700:
raise RuntimeError('SYSTEM_RENEW_READBACK_PRIVATE_CASE')
intent = json.loads(read(case / 'intent.json', 0))
backup_ok = False
if (case / 'original-policy.json').exists():
backup_ok = hashlib.sha256(read(case / 'original-policy.json', 0)).hexdigest() == intent['old_policy_sha256']
observed = 'unexpected_current_policy'
if current_sha == intent['old_policy_sha256']:
observed = 'expired_original_observed'
elif current_sha == intent['new_policy_sha256']:
observed = 'exact_replacement_observed'
completed = None
if (case / 'completed.json').exists():
completed = json.loads(read(case / 'completed.json', 0))
if completed['case_id'] != ident or completed['policy_sha256'] != intent['new_policy_sha256']:
raise RuntimeError('SYSTEM_RENEW_READBACK_COMPLETION_BINDING')
return {'schema_version': 1, 'read_only': True, 'case_present': True, 'observed': observed, 'policy_sha256': current_sha, 'original_bytes_backup_verified': backup_ok, 'completed': completed, 'retry_authorized': False, 'jobs_created': False, 'approvals_created': False}
@@ -0,0 +1,176 @@
#!/usr/bin/env python3
"""Prepare the existing stopped-pair8 controller; never invoke its effects.
Only fixed SDK/source/public evidence files may be staged separately. Final pair
and native nonstart221 proof are required before sealing any deployment input.
"""
import argparse
import hashlib
import json
from pathlib import Path
import uuid
ROOT=Path(__file__).resolve().parents[1]
BASE=ROOT/'deploy/windows/Install-DevelopmentPairSuccessor.ps1'
BASE_SHA='78e0e0111c08ab0c91774d7ef87e2f1e6ddf272629859af92c48292a289a42a4'
def sha(raw):return hashlib.sha256(raw).hexdigest()
def replace_once(text,old,new):
assert text.count(old)==1,'exact reviewed predecessor delta'
return text.replace(old,new,1)
def controller():
raw=BASE.read_bytes();assert sha(raw)==BASE_SHA,'reviewed original pair7 controller'
text=raw.decode()
text=replace_once(text,"$m.previous_revision -ne 6", "$m.previous_revision -ne 7")
text=replace_once(text,"'PrepareStopped','InstallStoppedPassive','PrepareProfile','PublishProfile','Read'","'PrepareStopped','InstallStoppedPassive','PrepareProfile','PublishProfile','RestoreActiveStopped','Read'")
text=text.replace('revision6 to7','revision7 to8').replace('revision6','revision7')
text=replace_once(text,"$m.old_helper_sha256 -cne '59675a3cbb3a5d213fc764f38379d6b81baaf9d47a7124470cc2767d4985763e'", "$m.old_helper_sha256 -cne '0502d6c87bd74c99f1665f3cc4b9d74b8e31d0f829d2ce1a1597d72e9be1e726'")
text=replace_once(text,"$previousRevision=6", "$previousRevision=7")
text=replace_once(text,"$previousCase=Join-Path $bootstrap ('job-passive-pair-'+$m.previous_case_id)","$previousCase=Join-Path $bootstrap ('job-stopped-pair-'+$m.previous_case_id)")
text=replace_once(text,"$previous.successor_revision -ne 6", "$previous.successor_revision -ne 7")
marker=". ([scriptblock]::Create($text.Substring($i,$j-$i)))"
auto_observer=r"""
# The previously authorized SYSTEM-script bootstrap already set Helper Auto.
# Bind this existing observed definition; do not change SCM configuration.
$serviceSource=(Get-Item Function:\Service).ScriptBlock.ToString()
$manualToken="`$mode='Manual'"
$at=$serviceSource.IndexOf($manualToken,[StringComparison]::Ordinal)
if($at-lt0-or$at-ne$serviceSource.LastIndexOf($manualToken,[StringComparison]::Ordinal)){throw 'Exact historical helper-mode observer changed.'}
Set-Item Function:\Service ([scriptblock]::Create($serviceSource.Replace($manualToken,"`$mode='Auto'")))
"""
text=replace_once(text,marker,marker+'\n'+auto_observer)
text=text.replace('successor_revision=7','successor_revision=8').replace('profile7','profile8')
old="alignment_verification_sha256,case_id,linux_proof_sha256,new_agent_sha256,new_helper_sha256,old_agent_sha256,old_config_sha256,old_helper_sha256,old_pin_sha256,old_profile_sha256,old_settings_sha256,pair_build_sha256,previous_case_id,previous_publication_sha256,previous_revision,schema_version,windows_proof_sha256"
new="alignment_verification_sha256,case_id,linux_proof_sha256,new_agent_sha256,new_helper_sha256,old_agent_sha256,old_config_sha256,old_helper_sha256,old_native_result_sha256,old_pin_sha256,old_profile_sha256,old_qualification_sha256,old_settings_sha256,pair_build_sha256,passive_codec_sha256,passive_render_input_sha256,passive_render_sha256,previous_case_id,previous_publication_sha256,previous_revision,schema_version,windows_proof_sha256"
text=replace_once(text,old,new)
old="if ($alignment.read_only -ne $true -or $alignment.admin_archive_verified -ne $true -or $alignment.helper_checkpoint -ne 201 -or $alignment.agent_checkpoint -ne 10137 -or $alignment.helper_last_decision -cne '2af359c5-5b5c-4992-b445-1c00e271a288' -or $alignment.ready -ne $false -or $alignment.helper_ready -ne $false -or $alignment.unlock -ne $false) { throw 'Actual closed G205 verification required.' }"
# Private, fixed bootstrap witness from actual native221 verification; not a
# product wire protocol, permission, retry, sync lease or approval.
new="""$expectedVerification='active_pending_job_events,grant_id,incident,not_started,old_grant_executed_again,original_unknown_preserved,original_unknown_sha256,raw_retained_job_events,ready,receipt_id,receipt_sha256,revision,state,helper_ready,unlock'
if((($alignment.PSObject.Properties.Name|Sort-Object)-join',')-cne(($expectedVerification.Split(',')|Sort-Object)-join',')-or$alignment.incident-ne221-or$alignment.grant_id-cne'97e705b8-fb2b-4158-84d9-d90595d1ce6e'-or$alignment.state-cne'failed'-or$alignment.revision-ne3-or$alignment.not_started-ne$true-or$alignment.original_unknown_preserved-ne$true-or$alignment.old_grant_executed_again-ne$false-or$alignment.original_unknown_sha256-cne'1f284b66578d61c4364cc0060a67ce9b467e1d661ed8885804391b51a6f18b1a'-or$alignment.raw_retained_job_events-ne1-or$alignment.active_pending_job_events-ne0-or$alignment.receipt_sha256-cnotmatch'^[0-9a-f]{64}$'-or[guid]::ParseExact($alignment.receipt_id,'D').ToString()-cne$alignment.receipt_id-or$alignment.ready-ne$false-or$alignment.helper_ready-ne$false-or$alignment.unlock-ne$false){throw 'Exact actual SDK verify_applied221 output required; no projected wrapper or fabricated witness.'}"""
text=replace_once(text,old,new)
old="foreach ($name in @('linux-proof.json','windows-proof.json')) { $proof=Get-Content -LiteralPath (Join-Path $inputFolder $name) -Raw|ConvertFrom-Json;if ($proof.verified -ne $true -or $proof.passed -ne 3 -or $proof.failed -ne 0) { throw 'Native targeted units have not passed.' } }"
new=r"""foreach($name in @('linux-proof.json','windows-proof.json')){
$proof=Get-Content -LiteralPath (Join-Path $inputFolder $name) -Raw|ConvertFrom-Json
if($name-ceq'linux-proof.json'){
if($proof.native_platform-cne'cloud-linux-x86_64'-or$proof.exit_code-ne0-or$proof.verified-ne$true-or$proof.uid-ne65534-or$proof.isolated_network-ne$true-or$proof.no_new_privs-ne$true-or$proof.stderr-cne''-or$proof.binary_sha256-cnotmatch'^[0-9a-f]{64}$'){throw 'Actual original Cloud Linux receipt-contract result required.'}
$contract=$proof.stdout|ConvertFrom-Json
}else{
if($proof.native_platform-cne'windows11-amd64'-or$proof.sdk_sha256-cnotmatch'^[0-9a-f]{64}$'-or$null-eq$proof.actual_result){throw 'Actual original native Windows receipt-contract result required.'}
$contract=$proof.actual_result
}
foreach($field in @('valid_actual_signed_receipt','wrong_grant_rejected','wrong_original_hash_rejected','wrong_signature_rejected','original_helper_cache_refreshed_once','stale_cache_failure_reproduced','resolved_unlock_storage_guard_preserves_original','original_placeholder_retired','other_message_not_retired','other_raw_not_retired','physical_placeholder_preserved')){if($contract.$field-ne$true){throw 'Actual current nonstart221 contract incomplete.'}}
if($contract.effects-ne$false-or$contract.product_databases_opened-ne$false){throw 'Receipt-contract must have no product effects.'}
}"""
text=replace_once(text,old,new)
start=text.index(' $s=$utf8.GetString([IO.File]::ReadAllBytes((Baseline \'settings\')))')
end=text.index(" $c=Get-Content -LiteralPath (Baseline 'config')",start)
replacement=r''' $renderInputPath=Join-Path $inputFolder 'passive-input.json'
$renderPath=Join-Path $inputFolder 'passive-render.json'
foreach($entry in @(@($renderInputPath,$m.passive_render_input_sha256),@($renderPath,$m.passive_render_sha256))){CheckControl $entry[0] $false;if((Hash $entry[0])-cne$entry[1]){throw 'Typed passive renderer evidence changed.'}}
$ri=Get-Content -LiteralPath $renderInputPath -Raw|ConvertFrom-Json
$ro=Get-Content -LiteralPath $renderPath -Raw|ConvertFrom-Json
if($ri.schema_version-ne1-or$ri.current_settings_sha256-cne$m.old_settings_sha256-or(BytesHash ([byte[]]$ri.current_settings))-cne$m.old_settings_sha256-or$ri.new_agent_sha256-cne$m.new_agent_sha256-or$ri.new_helper_sha256-cne$m.new_helper_sha256-or$ro.source-cne'actual_rust_settings_codec'-or$ro.prepared_only-ne$true-or$ro.target_mutations-ne$false-or$ro.target_job_executed-ne$false-or$ro.effects_enabled-ne$false){throw 'Exact deny-only typed passive pair render required.'}
$codec=Join-Path (Join-Path $bootstrap $m.passive_codec_sha256) 'windows_script_pair_prepare.exe';CheckControl $codec $false
if((Hash $codec)-cne$m.passive_codec_sha256){throw 'Actual readonly typed codec artifact changed.'}
$settingsBytes=[byte[]]$ro.settings_bytes;$pinBytes=[byte[]]$ro.pin_bytes
$newHashes.settings=BytesHash $settingsBytes;$newHashes.pin=BytesHash $pinBytes
if($newHashes.settings-cne$ro.settings_sha256-or$newHashes.pin-cne$ro.pin_sha256){throw 'Actual typed passive bytes changed.'}
$old=Get-Content -LiteralPath (Baseline 'settings') -Raw|ConvertFrom-Json
$ns=$utf8.GetString($settingsBytes)|ConvertFrom-Json;$np=$utf8.GetString($pinBytes)|ConvertFrom-Json
if($old.schema_version-ne3-or$old.enable_effects-ne$true-or$old.max_runtime_seconds-ne30-or($old.allowed_script_profiles-join',')-cne'full_maintenance_v1'-or$ns.enable_effects-ne$false-or$ns.allow_reboot-ne$false-or$ns.max_runtime_seconds-ne30-or@($ns.allowed_services).Count-ne0-or$null-ne$ns.PSObject.Properties['allowed_script_profiles']-or$null-ne$ns.PSObject.Properties['allowed_msi_recipe_sha256']-or$ns.agent.binary_sha256-cne$m.new_agent_sha256-or$ns.helper.binary_sha256-cne$m.new_helper_sha256-or$np.policy_sha256-cne$newHashes.settings-or!(JsonEqual $ns.binding $old.binding)-or!(JsonEqual $np.binding $old.binding)){throw 'Only same-identity passive script pair transition.'}
'''
text=text[:start]+replacement+text[end:]
text=replace_once(text,"return [ordered]@{settings=$utf8.GetBytes($s);pin=$utf8.GetBytes($p);config=$configBytes}","return [ordered]@{settings=$settingsBytes;pin=$pinBytes;config=$configBytes}")
# The old script qualification belongs to the old image/policy. Keep its
# bytes, native file IDs AND ACL while retiring the active names, under
# both original locks before any new passive component can start.
declaration=r"""
function OriginalScriptQualification {
$q=[ordered]@{}
foreach($entry in @(@('qualification','system-qualification.json',$m.old_qualification_sha256),@('native_result','system-native-result.json',$m.old_native_result_sha256))){
$path=Join-Path $helperRoot $entry[1];$v=FileIdentity $path
if($v.sha256-cne$entry[2]){throw 'Exact old script qualification CAS required.'}
$q[$entry[0]]=$v
}
return $q
}
function ArchiveOriginalScriptQualification($original) {
StopCheck
if(Test-Path -LiteralPath (Marker 'qualification-archive-intent')){throw 'Existing qualification archive intent: readback only.'}
if(!(JsonEqual $original (OriginalScriptQualification))){throw 'Old script qualification changed after preparation.'}
Record 'qualification-archive-intent' @{id=$id;files=$original;manifest_sha256=$ManifestSha256}
$after=[ordered]@{}
foreach($entry in @(@('qualification','system-qualification.json'),@('native_result','system-native-result.json'))){
$name=$entry[0];$source=Join-Path $helperRoot $entry[1];$dest=Join-Path $work ('archived-'+$entry[1])
if(Test-Path -LiteralPath $dest){throw 'Original qualification archive already exists.'}
if(!(JsonEqual $original.$name (FileIdentity $source))){throw 'Original qualification CAS changed.'}
[IO.File]::Move($source,$dest)
$v=FileIdentity $dest
# Same-volume rename must retain bytes, file identity AND security;
# do not restrict/change the original descriptor or reconstruct a file.
foreach($field in @('sha256','file_id','volume_serial','acl_sha256')){if($v.$field-cne$original.$name.$field){throw 'Original qualification archive identity or ACL changed.'}}
if(Test-Path -LiteralPath $source){throw 'Old active qualification name still present.'}
$after[$name]=$v
}
Record 'qualification-archived' @{id=$id;files=$after;originals=$original;active_names_absent=$true;new_qualification_created=$false}
}
"""
text=replace_once(text,'$rendered=RenderPairFiles',declaration+'\n$rendered=RenderPairFiles')
text=replace_once(text,'$before=CurrentFiles;$device=PreservedNativeState','$before=CurrentFiles;$device=PreservedNativeState;$scriptQualification=OriginalScriptQualification')
text=replace_once(text,'new_hashes=$newHashes;original_services_stopped=$true;successor_revision=8;','new_hashes=$newHashes;script_qualification=$scriptQualification;original_services_stopped=$true;successor_revision=8;')
text=replace_once(text," foreach ($name in $locations.Keys) {\n $inputPath=Join-Path $work ('new-'+$name)"," ArchiveOriginalScriptQualification $preparedPair.script_qualification\n foreach ($name in $locations.Keys) {\n $inputPath=Join-Path $work ('new-'+$name)")
restore=r"""
if($Action-ceq'RestoreActiveStopped') {
StopCheck
$publication=LoadRecord 'profile-published';$installedPair=LoadRecord 'installed'
if($publication.id-cne$id-or$publication.successor_revision-ne8-or(Hash $target)-cne$publication.configuration.sha256){throw 'Actual published profile8 required before original config restoration.'}
foreach($name in @('agent','helper','settings','pin')){if((Hash $locations[$name])-cne$newHashes[$name]){throw 'Exact passive final pair required.'}}
if((Hash $config)-cne$newHashes.config-or(Hash (Join-Path $work 'old-config'))-cne$m.old_config_sha256){throw 'Exact current passive and preserved original active config required.'}
if(!(Test-Path -LiteralPath (Marker 'qualification-archived'))-or(Test-Path -LiteralPath (Join-Path $helperRoot 'system-qualification.json'))-or(Test-Path -LiteralPath (Join-Path $helperRoot 'system-native-result.json'))){throw 'Old qualification must remain archived; no new scope before actual native prerequisites.'}
if(Test-Path -LiteralPath (Marker 'active-config-restore-intent')){throw 'Existing restore intent means readback-only.'}
$locks=[RmmStoppedPairLocks]::new()
try {
StopCheck
$before=FileIdentity $config;$retained=PreservedNativeState
if(!(JsonEqual $before $installedPair.files.config)){throw 'Actual original passive config identity changed.'}
$active=Get-Content -LiteralPath (Join-Path $work 'old-config') -Raw|ConvertFrom-Json
if($active.enable_jobs-ne$true-or$active.windows_execution_profile-cne'powershell_51_remote_signed'-or$active.server_name-cne'discovery.ease-technologies.de'-or$active.state_directory-cne$agentState){throw 'Only original already authorized active client configuration.'}
Record 'active-config-restore-intent' @{id=$id;original_active_sha256=$m.old_config_sha256;current=$before;preserved=$retained;services_stopped=$true}
SwapFile 'config' (Join-Path $work 'old-config') $before $m.old_config_sha256 'active-config'
if(!(JsonEqual $retained (PreservedNativeState))){throw 'Original state changed during config restoration.'}
Record 'active-config-restored' @{id=$id;config=(FileIdentity $config);preserved=$retained;services_started=$false;scope_activated=$false;job_created=$false}
} finally {$locks.Dispose()}
Write-Output 'Original active config restored under original locks; pair remains stopped and SYSTEM scope unconfigured.';return
}
"""
text=replace_once(text,'# The qualified publisher\'s action bodies are excluded.',restore+'\n# The qualified publisher\'s action bodies are excluded.')
return text.encode()
def policy_controller():
# Same four typed public files and preservation/locking implementation as
# the first native script-scope bootstrap, without its already-completed
# Manual->Auto transition or its one historical no-effect resume exception.
import windows_system_job_bootstrap as base
text=base.APPLY_STOPPED
text=replace_once(text,'param([switch]$ResumeNoEffectEb285544)','$ResumeNoEffectEb285544=$false')
text=text.replace('windows_system_script_scope_stopped_v1','windows_system_script_successor_scope_stopped_v1')
text=replace_once(text,"$p.helper_start_transition.before-cne'Manual'-or$p.helper_start_transition.after-cne'Auto'-or$definitions.RmmDiscoverySystemHelper.start_mode-cne'Manual'","$p.helper_start_transition.before-cne'Auto'-or$p.helper_start_transition.after-cne'Auto'-or$definitions.RmmDiscoverySystemHelper.start_mode-cne'Auto'")
text=text.replace("Exact Manual to Auto helper transition only","Existing Helper Auto must remain Auto")
start=text.index("$stage='helper-autostart'\n")
end=text.index("$stage='final-preservation'",start)
text=text[:start]+r"""$stage='helper-autostart-unchanged'
$automatic=ServiceDefinitions
if(($automatic|ConvertTo-Json -Depth 6 -Compress)-cne($definitions|ConvertTo-Json -Depth 6 -Compress)-or$automatic.RmmDiscoverySystemHelper.start_mode-cne'Auto'-or$automatic.RmmDiscoveryWindows.start_mode-cne'Auto'){throw 'Original automatic SCM definitions must remain unchanged'}
"""+text[end:]
text=replace_once(text,"helper_autostart='Auto';services=$automatic;","helper_autostart='Auto';helper_start_mode_changed=$false;services=$automatic;")
return text.encode()
def main():
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('action',choices=['controller','policy-controller']);parser.add_argument('folder');args=parser.parse_args()
folder=Path(args.folder);folder.mkdir(mode=0o700,parents=True,exist_ok=True)
data=controller() if args.action=='controller' else policy_controller();path=folder/('Install-SystemScriptPairSuccessor.ps1' if args.action=='controller' else 'Install-SystemScriptSuccessorScope.ps1')
with path.open('xb')as f:f.write(data)
path.chmod(0o600)
print(json.dumps({'controller':str(path),'sha256':sha(data),'prepared_only':True,'target_mutated':False,'native_221_witness_pending':True,'final_pair_pending':True}))
if __name__=='__main__':main()
@@ -0,0 +1,87 @@
{
"schema_version": 1,
"scope": "S0-S2 only: preserved nonstart221 and new SYSTEM PowerShell job",
"baseline_commit": "510c069",
"source_files": {
"crates/agent-core/src/lib.rs": {
"sha256": "335d666030fc15f8168150e8c8d156e3a33f1e5ef291312771970501823ce733",
"bytes": 616
},
"crates/agent-core/src/jobs.rs": {
"sha256": "c1cc5312865629e81d475aedd46095376201a5172c988653fdca36ba2347b644",
"bytes": 16731
},
"crates/agent-core/src/ledger.rs": {
"sha256": "cc49361bd8a398543289e3361a35ef1a84cdcd086c94abf6c28323a3d8f86896",
"bytes": 14003
},
"crates/agent-core/src/reconcile.rs": {
"sha256": "e2e1d79a30387c7820aa89d18b1e4aeb68033361c00354985ae02b325a0d63aa",
"bytes": 64006
},
"crates/agent-core/src/helper_reconcile.rs": {
"sha256": "ef44c21685677ba4f87c7b33b8cc5926d482d1bd96de8c39914533b078cb7a2d",
"bytes": 80342
},
"crates/agent-core/src/windows_system_nonstart.rs": {
"sha256": "baef90ff254700cbfd1ed798064ae5b07445f361fb705251916157706b923cc9",
"bytes": 35149
},
"crates/agent-core/examples/windows_nonstart_receipt_contract.rs": {
"sha256": "80a871d8cc1c95bb4e0a347cf1aa8006c069467909858a4300d9f13da1e8737f",
"bytes": 331
},
"crates/agent-windows/examples/windows_system_nonstart_closed.rs": {
"sha256": "66c96d423a8ce5e1f207d143e223842095ab719f88070d4987f2e2615acc29f2",
"bytes": 23203
},
"crates/agent-windows/examples/windows_script_pair_prepare.rs": {
"sha256": "edf861d5b900511c5623789e0ee494fac4fe8cacb4085594454bd9dc0fe815d0",
"bytes": 3673
},
"crates/agent-windows/examples/time_route_probe.rs": {
"sha256": "49cd769275b651e97e678ac3369b6b67b3375637875fd8a7c6d98a174905b8ff",
"bytes": 20472
},
"deploy/windows_system_scope_renew.py": {
"sha256": "ef626efe11f7f43012285e958a76f21acd57b07dc2352089909f2f9925329c0c",
"bytes": 17176
},
"deploy/windows_system_script_successor_prepare.py": {
"sha256": "30534a742212efc18235deb3a638b0dd361956078f6cc17eea5acf0dbf4e5f31",
"bytes": 18013
},
"crates/agent-windows/Cargo.toml": {
"sha256": "7aadc16e9124f5759b8194b2d5abc65198484c70a4b5f8ac69c0f52dbf099672",
"bytes": 2108
},
"crates/agent-windows/src/signed_clock.rs": {
"sha256": "eb952ebc61d3e71fbd9f4b69a340c303c37dcfc5edcc4da39539e2f506a2e668",
"bytes": 62526
}
},
"already_tracked_dependencies": [
"crates/domain/src/windows_system_nonstart.rs",
"crates/domain/src/windows_sync_alignment.rs",
"crates/agent-core/src/windows_sync_alignment.rs",
"crates/agent-windows/src/system_script.rs"
],
"windows_product_src": "HEAD 510c069, without local updater/lifecycle WIP",
"new_pair_built": false,
"existing_operator_sdk": {
"sha256": "66c156ce0e20c2bc089fffb06e87aa8d5eaba042f175a3e9ddfa4b6fdd752c3a",
"built_before_this_source_checkpoint": true,
"do_not_relabel_as_build_from_this_commit": true
},
"private_operator_inputs": [
"Pinned existing SSH configuration in credentials/ (never commit).",
"Actual original live/stop archive and four SQLite journals on existing Windows VM.",
"Original stopped witness b92a51bb... and actual WebUI receipt; raw evidence remains in protected devstate."
],
"deferred_without_deletion": "Remaining local Windows updater/lifecycle WIP; no global staging or reset.",
"minimal_committed_updater_api_compatibility": [
"Agent Context explicitly omits updater_image_sha256 (None), including time_route_probe.",
"Agent/SystemHelper constructor explicitly refuses Role::Updater.",
"Premature untracked updater binary registration deferred; updater sources remain outside this closure."
]
}
+65
View File
@@ -0,0 +1,65 @@
# S0–S2: tatsächliche Abschlussstrecke für Windows SYSTEM
16. November 2026. Der Betreiber hat S0–S2 des
[Abschlussplans](mvp-completion-plan.md) ausdrücklich beauftragt. Keine
Linuxkapazitäts-, Updater-, MSI-, Zertifikats- oder Rebootarbeiten gehören zu
diesem Schritt. Der bestehende Fall 221 bleibt vollständig historienerhaltend.
## S0: enger reproduzierbarer Quellenstand
Der neue Quellencheckpoint ergänzt die bereits versionierte Domain-/Server-
und Windows-Sharingbasis ausschließlich um sechs notwendige Coredateien,
Operator-/Metadatenbeispiele und die zwei vorbereiteten S2-Controller.
[Exakte Quellen und SHA-256](evidence/windows-system-s0-source.json).
Zwei Agents prüften die Abhängigkeiten: Der Operator benötigt keine der
lokalen Windows-Updater-/Lifecycleänderungen. Produktquellen für das neue
Agent-/Helperpaar stammen aus diesem Gitstand, nicht aus einem veralteten
vollständigen privaten Snapshot. Der übrige lokale Arbeitsstand bleibt erhalten.
Die Prüfung eines frischen Checkoutstands fand außerdem bereits versionierte
unvollständige Updater-API-Anschlüsse. Nur die benötigte Kompatibilität wird
ergänzt: bestehende Agentkontexte setzen das neue optionale Updaterimage auf
None; der Agent-/Helperuhrkonstruktor verweigert ausdrücklich die Updaterrolle.
Die vorzeitig registrierte, noch unversionierte Updaterbinary wird aus dieser
engen Cargoauswahl zurückgestellt. Keine Updaterimplementierung oder Fähigkeit
wird übernommen. Die übrigen Änderungen derselben Arbeitsdateien bleiben
unverändert lokal erhalten; Git enthält nur die geprüften Teiländerungen.
Der bereits vorhandene Operator-SDK `66c156ce…` wurde aus seinem früheren
eigenständigen Snapshot gebaut. Dessen SHA-/Buildbeleg wird nicht nachträglich
diesem Gitcheckpoint zugeschrieben. Seine sechs Coredateien stimmen bytegenau
mit den hier versionierten überein. Der neue Produktpaarbuild und dessen
Manifest werden separat ausgewiesen. Noch keine neue SYSTEM-Abnahme.
## Bestehenden Entwicklungstransport wieder verbunden
Der neue SSH-Leseversuch scheiterte am fehlenden Reverse-Forward mit
`Connection refused`, nicht an einer neuen Hostkey- oder Benutzerfreigabe.
Die vorhandene Windows-KVM-VM lief. Ihre bereits bereitgestellte lokale
Administrator-Konsole zeigte den bestehenden Task `RmmDevReverseTunnel` als
Ready mit letztem Exit 255. Der Integrator forderte genau einmal den normalen
Start dieses vorhandenen Tasks an; keine Task-/SSH-Konfiguration geändert.
Die neue strikt gepinnte SSH-Verbindung um **20:00:28 UTC / 21:00:28 MEZ**
bestätigte Task Running und beide RMM-Dienste weiterhin Stopped. Kein
Userhandgriff, kein Reboot, kein RMM-Job und keine Journalkorrektur.
Danach wurde ausschließlich der SDK mit vollständigem Hashreadback in den
geschützten Bootstrap-Hashpfad übertragen; 23202304 Byte, SHA-256
`66c156ce0e20c2bc089fffb06e87aa8d5eaba042f175a3e9ddfa4b6fdd752c3a`.
Dies ist ein Stagingnachweis, keine native Anwendung oder Bereitstellung eines
neuen RMM-Agenten. Ausfallsicherheit des Entwicklungstasks ist damit nicht
allgemein abgenommen; kein neues Transportframework wurde begonnen.
Der neue native SDK-Lesezeuge um **20:04:08 UTC** endete mit Exit 0 und exakt
dem ursprünglichen kanonischen Witnesshash `b92a51bb…`. Weiterhin vier Agentjobs,
drei Agentverbräuche/-starts/-outcomes und ein Helperverbrauch/-start/-outcome
sowie ein Intent. Kein Abschluss wurde dabei angewandt und keine Rolle gestartet.
## Noch offene Ausführung
Neuen ursprünglichen Zeugen lesen und vergleichen; tatsächliche frische
WebUI-Quittung, Windows-Vertrag, einmalige Anwendung und separate Nachprüfung.
Erst danach das neue Paar installieren und qualifizieren, regulären frischen
SignedSync nachweisen, bestehenden SYSTEM-Scope eng erneuern und einen neuen
MCP-/WebUI-SYSTEM-PowerShell-Auftrag ausführen. Diese Handlungen sind hier
zunächst geplant und werden erst nach tatsächlicher Ausführung ergänzt.