From fd17b6c662ee44f93aec4d1fd7bca39acb25ae07 Mon Sep 17 00:00:00 2001 From: Kevin Janssen Date: Sun, 15 Nov 2026 23:27:14 +0100 Subject: [PATCH] Implement and natively verify the human-reviewed Windows recovery tool --- Cargo.lock | 1 + .../examples/windows_sync_history.rs | 259 +---------- crates/agent-core/src/lib.rs | 1 + crates/agent-core/src/windows_sync_history.rs | 155 +++++++ .../tests/support/windows_review_fixture.rs | 125 ++++++ crates/agent-windows/Cargo.toml | 7 + .../examples/windows_reviewed_recovery.rs | 337 ++++++++++++++ .../windows_reviewed_recovery/local.rs | 412 ++++++++++++++++++ crates/agent-windows/src/helper_intent.rs | 17 + crates/agent-windows/src/helper_ipc.rs | 3 +- crates/domain/src/windows_sync_history.rs | 23 +- docs/windows-profile-acceptance.md | 12 + 12 files changed, 1109 insertions(+), 243 deletions(-) create mode 100644 crates/agent-core/src/windows_sync_history.rs create mode 100644 crates/agent-core/tests/support/windows_review_fixture.rs create mode 100644 crates/agent-windows/examples/windows_reviewed_recovery.rs create mode 100644 crates/agent-windows/examples/windows_reviewed_recovery/local.rs diff --git a/Cargo.lock b/Cargo.lock index 9786d40..deebbf2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2244,6 +2244,7 @@ dependencies = [ "anyhow", "cc", "chrono", + "ed25519-dalek", "fs2", "futures-util", "prost", diff --git a/crates/agent-core/examples/windows_sync_history.rs b/crates/agent-core/examples/windows_sync_history.rs index 24d59f2..ade58ba 100644 --- a/crates/agent-core/examples/windows_sync_history.rs +++ b/crates/agent-core/examples/windows_sync_history.rs @@ -1,34 +1,17 @@ //! Operator-side readback of the two historical Windows test decisions. //! Output contains public digests only. This example has no repair or job entry point. use anyhow::{Context, Result, ensure}; -use prost::Message; use rmm_agent_core::{ auth::Binding, - crypto::DalekVerifier, - helper_reconcile::SignedResponse, - reconcile::{Channel, verify_response_with}, + windows_sync_history::{BINDING_SHA256, FAULT, LAST, verify_local_history}, }; -use rmm_domain::{jobs::hash, reconciliation::ReconcileDecisionPayload}; -use rmm_protocol::{Envelope, Payload, SyncRequest, SyncResponse}; -use rusqlite::{Connection, OpenFlags, params}; +use rmm_domain::jobs::hash; +use rusqlite::{Connection, OpenFlags}; use std::{ fs::{File, OpenOptions}, io::Read, path::Path, }; -use uuid::Uuid; - -const AGENT: &str = "63ea15b2-0643-403d-b5b4-cba1288dbea3"; -const BOOT: &str = "a9ad0895-5a96-8f2c-8fb6-cfdc2d5225ea"; -const FIRST: &str = "b6a3101f-68ad-41c8-be4e-4c7c2bc963d6"; -const LAST: &str = "0633a4de-7e52-4e5d-a2a1-59fb134817fe"; -const FAULT: &str = "HELPER_CHECKPOINT_REQUIRED"; -const BINDING_SHA256: &str = "9239ee9f4142735867e77451478bf309fbf449d730a0ede6c958bc8018830dde"; -const CASES: [(&str, &str, u64); 2] = [ - ("1418b4a3-8370-404d-b29a-920ba9f0f4d7", FIRST, 6755), - ("9eba037c-825f-4a96-be14-cca130c1e83d", LAST, 6756), -]; - fn held(path: &Path) -> Result { for node in path.ancestors() { let meta = node.symlink_metadata()?; @@ -92,117 +75,19 @@ fn inspect( helper: &Connection, binding: &Binding, ) -> Result<()> { - let count = |db: &Connection, sql| -> Result { Ok(db.query_row(sql, [], |r| r.get(0))?) }; - ensure!( - count(agent, "SELECT count(*) FROM reconcile_requests")? == 2 - && count(local, "SELECT count(*) FROM reconcile_consumption")? == 2 - && count(helper, "SELECT count(*) FROM helper_sync_decisions")? == 1, - "history length" - ); - ensure!( - count( - agent, - "SELECT (SELECT count(*) FROM job_attempts)+(SELECT count(*) FROM reconcile_outcomes)+(SELECT count(*) FROM reconcile_results)" - )? == 0 - && count( - local, - "SELECT (SELECT count(*) FROM consumed)+(SELECT count(*) FROM execution_evidence)" - )? == 0 - && count( - helper, - "SELECT (SELECT count(*) FROM consumed)+(SELECT count(*) FROM execution_evidence)" - )? == 0, - "nonempty execution history" - ); - - let chan = Channel { - connection_generation: 150, - boot_id: Uuid::parse_str(BOOT)?, - }; - let mut digest_lines = Vec::new(); - for (request_id, decision_id, checkpoint) in CASES { - let (raw_request, envelope_bytes, raw_response): (Vec, Vec, Vec) = agent.query_row( - "SELECT request,envelope,response FROM reconcile_requests WHERE id=? AND generation=150 AND length(request) BETWEEN 1 AND 524288 AND length(envelope) BETWEEN 1 AND 524288 AND length(response) BETWEEN 1 AND 524288", - [request_id], |r| Ok((r.get(0)?,r.get(1)?,r.get(2)?)))?; - let request = SyncRequest::decode(raw_request.as_slice())?; - let envelope = Envelope::decode(envelope_bytes.as_slice())?; - let response = SyncResponse::decode(raw_response.as_slice())?; - ensure!( - request.encode_to_vec() == raw_request && response.encode_to_vec() == raw_response, - "noncanonical original record" - ); - ensure!( - envelope.protocol_major == 1 - && envelope.protocol_minor == 0 - && envelope.agent_id == AGENT - && envelope.enrollment_generation == 1 - && envelope.connection_generation == 150 - && envelope.boot_id == BOOT - && envelope.sequence == checkpoint - && envelope.payload == Some(Payload::SyncRequest(request.clone())), - "envelope binding" - ); - let first = decision_id == FIRST; - ensure!( - request.request_id == request_id - && request.checkpoint == checkpoint - && request.assignment_version == 1 - && request.helper_checkpoint == 1 - && request.journal_complete - && request.previous_decision_id == if first { "" } else { FIRST } - && request.previous_request_id.is_empty() - && request.helper_previous_decision_id.is_empty() - && request.attempts.is_empty(), - "request history" - ); - // Historical validation uses the signed issue time, never a present-day lease. - let historical: ReconcileDecisionPayload = - serde_json::from_slice(&response.decision_bytes)?; - let d = verify_response_with( - &DalekVerifier, - binding, - &request, - &chan, - &response, - historical.issued_at, - )?; - ensure!( - d.decision_id.to_string() == decision_id - && d.attempts.is_empty() - && d.ready == first - && d.helper_ready == first - && d.reason == if first { "CONSISTENT" } else { FAULT }, - "signed decision" - ); - let ledger_response: Vec = local.query_row("SELECT response FROM reconcile_consumption WHERE decision_id=? AND length(response) BETWEEN 1 AND 524288", [decision_id], |r|r.get(0))?; - ensure!( - ledger_response == raw_response, - "consumption decision differs" - ); - if !first { - let (helper_raw, helper_request): (Vec, Vec) = helper.query_row( - "SELECT response,request FROM helper_sync_decisions WHERE decision_id=? AND checkpoint=1 AND length(response) BETWEEN 1 AND 2097152 AND length(request) BETWEEN 1 AND 524288", - [decision_id], |r|Ok((r.get(0)?,r.get(1)?)))?; - let h: SignedResponse = serde_json::from_slice(&helper_raw)?; - ensure!( - helper_request == raw_request - && h.decision_bytes == response.decision_bytes - && h.signature == response.signature, - "helper signed history" + let rows = verify_local_history(agent, local, helper, binding, binding, Some(FAULT))?; + for d in rows { + let cp = &d["checkpoint"]; + for (label, key) in [ + ("request", "request_sha256"), + ("decision", "payload_sha256"), + ("signature", "signature_sha256"), + ] { + println!( + "{cp} {label} {}", + d[key].as_str().context("verified digest missing")? ); - let head: bool = agent.query_row("SELECT EXISTS(SELECT 1 FROM reconcile_meta WHERE id=1 AND journal_id=?1 AND checkpoint=6756 AND generation=150 AND last_decision=?2 AND pending_request IS NULL AND helper_id=?3 AND helper_checkpoint=1 AND fault=?4)",params![request.journal_id, LAST, request.helper_journal_id, FAULT], |r|r.get(0))?; - let helper_head: bool = helper.query_row("SELECT EXISTS(SELECT 1 FROM helper_sync_meta WHERE id=1 AND journal_id=?1 AND checkpoint>=1 AND generation=150 AND last_decision=?2 AND agent_journal_id=?3 AND agent_checkpoint=6756 AND fault IS NULL)",params![request.helper_journal_id,LAST,request.journal_id],|r|r.get(0))?; - ensure!(head && helper_head, "live reconciliation heads differ"); } - digest_lines.push(format!( - "{checkpoint} request {}\n{checkpoint} decision {}\n{checkpoint} signature {}", - hash(&raw_request), - hash(&response.decision_bytes), - hash(&response.signature) - )); - } - for line in digest_lines { - println!("{line}"); } println!( "public key {}", @@ -212,7 +97,6 @@ fn inspect( println!("agent fault {FAULT}; jobs and consumptions 0"); Ok(()) } - fn main() -> Result<()> { ensure!( cfg!(windows) && std::env::args_os().count() == 1, @@ -239,114 +123,17 @@ fn main() -> Result<()> { #[cfg(test)] mod tests { use super::*; - use chrono::{Duration, Utc}; - use ed25519_dalek::{Signer, SigningKey}; - + use ed25519_dalek::SigningKey; + use rmm_agent_core::windows_sync_history::FIRST; + mod data { + include!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/support/windows_review_fixture.rs" + )); + } #[test] fn verifies_two_originals_and_rejects_changed_history() -> Result<()> { - let a = Connection::open_in_memory()?; - let l = Connection::open_in_memory()?; - let h = Connection::open_in_memory()?; - rmm_agent_core::reconcile::initialize(&a)?; - a.execute_batch("CREATE TABLE job_attempts(job);")?; - for db in [&l, &h] { - db.execute_batch( - "CREATE TABLE consumed(grant_id); CREATE TABLE execution_evidence(grant_id);", - )?; - } - l.execute_batch("CREATE TABLE reconcile_consumption(decision_id,response);")?; - h.execute_batch("CREATE TABLE helper_sync_decisions(decision_id,checkpoint,response,request); CREATE TABLE helper_sync_meta(id,journal_id,checkpoint,generation,last_decision,agent_journal_id,agent_checkpoint,fault);")?; - let id = Uuid::new_v4(); - let peer = Uuid::new_v4(); - let key = SigningKey::from_bytes(&[13; 32]); // Public deterministic fixture only. - let binding = Binding { - tenant_id: Uuid::new_v4(), - agent_id: Uuid::parse_str(AGENT)?, - asset_id: Uuid::new_v4(), - assignment_version: 1, - enrollment_generation: 1, - public_key_hex: hex::encode(key.verifying_key().to_bytes()), - }; - for (req, dec, cp) in CASES { - let first = dec == FIRST; - let r = SyncRequest { - request_id: req.into(), - journal_id: id.to_string(), - checkpoint: cp, - assignment_version: 1, - journal_complete: true, - helper_journal_id: peer.to_string(), - helper_checkpoint: 1, - previous_decision_id: if first { "" } else { FIRST }.into(), - ..Default::default() - }; - let raw = r.encode_to_vec(); - let e = Envelope { - protocol_major: 1, - agent_id: AGENT.into(), - enrollment_generation: 1, - connection_generation: 150, - boot_id: BOOT.into(), - sequence: cp, - payload: Some(Payload::SyncRequest(r)), - ..Default::default() - }; - let now = Utc::now() - Duration::hours(1); - let d = ReconcileDecisionPayload { - domain: "rmm.reconciliation-decision".into(), - schema_version: 1, - decision_id: Uuid::parse_str(dec)?, - request_id: Uuid::parse_str(req)?, - request_hash: hash(&raw), - tenant_id: binding.tenant_id, - asset_id: binding.asset_id, - agent_id: binding.agent_id, - enrollment_generation: 1, - assignment_version: 1, - connection_generation: 150, - boot_id: Uuid::parse_str(BOOT)?, - journal_id: id, - checkpoint: cp, - helper_journal_id: Some(peer), - helper_checkpoint: 1, - issued_at: now, - valid_until: now + Duration::seconds(60), - ready: first, - helper_ready: first, - reason: if first { "CONSISTENT" } else { FAULT }.into(), - attempts: vec![], - acknowledged_message_ids: vec![], - key_id: hash(&key.verifying_key().to_bytes()), - }; - let bytes = serde_json::to_vec(&d)?; - let signed = SyncResponse { - signature: key.sign(&bytes).to_bytes().into(), - decision_bytes: bytes, - }; - a.execute("INSERT INTO reconcile_requests(id,request,envelope,generation,response) VALUES(?,?,?,150,?)",params![req,raw,e.encode_to_vec(),signed.encode_to_vec()])?; - l.execute( - "INSERT INTO reconcile_consumption VALUES(?,?)", - params![dec, signed.encode_to_vec()], - )?; - if !first { - h.execute( - "INSERT INTO helper_sync_decisions VALUES(?,1,?,?)", - params![ - dec, - serde_json::to_vec(&SignedResponse { - signature: signed.signature, - decision_bytes: signed.decision_bytes - })?, - raw - ], - )?; - } - } - a.execute("UPDATE reconcile_meta SET journal_id=?,checkpoint=6756,generation=150,last_decision=?,helper_id=?,helper_checkpoint=1,fault=?",params![id.to_string(),LAST,peer.to_string(),FAULT])?; - h.execute( - "INSERT INTO helper_sync_meta VALUES(1,?,9,150,?,?,6756,NULL)", - params![peer.to_string(), LAST, id.to_string()], - )?; + let (a, l, h, binding, _) = data::verified_pair()?; inspect(&a, &l, &h, &binding)?; let mut foreign = binding.clone(); foreign.public_key_hex = diff --git a/crates/agent-core/src/lib.rs b/crates/agent-core/src/lib.rs index c7f6fb4..10a0d5c 100644 --- a/crates/agent-core/src/lib.rs +++ b/crates/agent-core/src/lib.rs @@ -11,3 +11,4 @@ pub mod reconcile; pub mod update_handoff; pub mod update_health_inventory; pub mod update_health_sync; +pub mod windows_sync_history; diff --git a/crates/agent-core/src/windows_sync_history.rs b/crates/agent-core/src/windows_sync_history.rs new file mode 100644 index 0000000..58079b3 --- /dev/null +++ b/crates/agent-core/src/windows_sync_history.rs @@ -0,0 +1,155 @@ +//! Public, read-only comparison of the three Windows journals for the November 2026 incident. +use crate::{ + auth::Binding, + crypto::DalekVerifier, + helper_reconcile::SignedResponse, + reconcile::{Channel, verify_response_with}, +}; +use anyhow::{Result, ensure}; +use prost::Message; +use rmm_domain::{jobs::hash, reconciliation::ReconcileDecisionPayload}; +use rmm_protocol::{Envelope, Payload, SyncRequest, SyncResponse}; +use rusqlite::{Connection, params}; +use uuid::Uuid; +pub const AGENT: &str = "63ea15b2-0643-403d-b5b4-cba1288dbea3"; +pub const BOOT: &str = "a9ad0895-5a96-8f2c-8fb6-cfdc2d5225ea"; +pub const FIRST: &str = "b6a3101f-68ad-41c8-be4e-4c7c2bc963d6"; +pub const LAST: &str = "0633a4de-7e52-4e5d-a2a1-59fb134817fe"; +pub const FAULT: &str = "HELPER_CHECKPOINT_REQUIRED"; +pub const BINDING_SHA256: &str = "9239ee9f4142735867e77451478bf309fbf449d730a0ede6c958bc8018830dde"; +pub const CASES: [(&str, &str, u64); 2] = [ + ("1418b4a3-8370-404d-b29a-920ba9f0f4d7", FIRST, 6755), + ("9eba037c-825f-4a96-be14-cca130c1e83d", LAST, 6756), +]; + +pub fn verify_local_history( + agent: &Connection, + local: &Connection, + helper: &Connection, + binding: &Binding, + helper_binding: &Binding, + expected_fault: Option<&str>, +) -> Result> { + let count = |db: &Connection, sql| -> Result { Ok(db.query_row(sql, [], |r| r.get(0))?) }; + ensure!( + count(agent, "SELECT count(*) FROM reconcile_requests")? == 2 + && count(local, "SELECT count(*) FROM reconcile_consumption")? == 2 + && count(helper, "SELECT count(*) FROM helper_sync_decisions")? == 1, + "history length" + ); + ensure!( + count( + agent, + "SELECT (SELECT count(*) FROM job_attempts)+(SELECT count(*) FROM reconcile_outcomes)+(SELECT count(*) FROM reconcile_results)" + )? == 0 + && count( + local, + "SELECT (SELECT count(*) FROM consumed)+(SELECT count(*) FROM execution_evidence)" + )? == 0 + && count( + helper, + "SELECT (SELECT count(*) FROM consumed)+(SELECT count(*) FROM execution_evidence)" + )? == 0, + "nonempty execution history" + ); + + let chan = Channel { + connection_generation: 150, + boot_id: Uuid::parse_str(BOOT)?, + }; + let mut decisions = Vec::with_capacity(CASES.len()); + for (request_id, decision_id, checkpoint) in CASES { + let (raw_request, envelope_bytes, raw_response): (Vec, Vec, Vec) = agent.query_row( + "SELECT request,envelope,response FROM reconcile_requests WHERE id=? AND generation=150 AND length(request) BETWEEN 1 AND 524288 AND length(envelope) BETWEEN 1 AND 524288 AND length(response) BETWEEN 1 AND 524288", + [request_id], |r| Ok((r.get(0)?,r.get(1)?,r.get(2)?)))?; + let request = SyncRequest::decode(raw_request.as_slice())?; + let envelope = Envelope::decode(envelope_bytes.as_slice())?; + let response = SyncResponse::decode(raw_response.as_slice())?; + ensure!( + request.encode_to_vec() == raw_request && response.encode_to_vec() == raw_response, + "noncanonical original record" + ); + ensure!( + envelope.protocol_major == 1 + && envelope.protocol_minor == 0 + && envelope.agent_id == AGENT + && envelope.enrollment_generation == 1 + && envelope.connection_generation == 150 + && envelope.boot_id == BOOT + && envelope.sequence == checkpoint + && envelope.payload == Some(Payload::SyncRequest(request.clone())), + "envelope binding" + ); + let first = decision_id == FIRST; + ensure!( + request.request_id == request_id + && request.checkpoint == checkpoint + && request.assignment_version == 1 + && request.helper_checkpoint == 1 + && request.journal_complete + && request.previous_decision_id == if first { "" } else { FIRST } + && request.previous_request_id.is_empty() + && request.helper_previous_decision_id.is_empty() + && request.attempts.is_empty(), + "request history" + ); + // Historical validation uses the signed issue time, never a present-day lease. + let historical: ReconcileDecisionPayload = + serde_json::from_slice(&response.decision_bytes)?; + let d = verify_response_with( + &DalekVerifier, + binding, + &request, + &chan, + &response, + historical.issued_at, + )?; + ensure!( + d.decision_id.to_string() == decision_id + && d.attempts.is_empty() + && d.ready == first + && d.helper_ready == first + && d.reason == if first { "CONSISTENT" } else { FAULT }, + "signed decision" + ); + let ledger_response: Vec = local.query_row("SELECT response FROM reconcile_consumption WHERE decision_id=? AND length(response) BETWEEN 1 AND 524288", [decision_id], |r|r.get(0))?; + ensure!( + ledger_response == raw_response, + "consumption decision differs" + ); + if !first { + let (helper_raw, helper_request): (Vec, Vec) = helper.query_row( + "SELECT response,request FROM helper_sync_decisions WHERE decision_id=? AND checkpoint=1 AND length(response) BETWEEN 1 AND 2097152 AND length(request) BETWEEN 1 AND 524288", + [decision_id], |r|Ok((r.get(0)?,r.get(1)?)))?; + let h: SignedResponse = serde_json::from_slice(&helper_raw)?; + ensure!( + helper_request == raw_request + && h.decision_bytes == response.decision_bytes + && h.signature == response.signature, + "helper signed history" + ); + // The helper configuration provides its own protected trust binding. + let helper_signed = SyncResponse { + decision_bytes: h.decision_bytes, + signature: h.signature, + }; + verify_response_with( + &DalekVerifier, + helper_binding, + &request, + &chan, + &helper_signed, + historical.issued_at, + )?; + let head: bool = agent.query_row("SELECT EXISTS(SELECT 1 FROM reconcile_meta WHERE id=1 AND journal_id=?1 AND checkpoint=6756 AND generation=150 AND last_decision=?2 AND pending_request IS NULL AND helper_id=?3 AND helper_checkpoint=1 AND fault IS ?4)",params![request.journal_id, LAST, request.helper_journal_id, expected_fault], |r|r.get(0))?; + let helper_head: bool = helper.query_row("SELECT EXISTS(SELECT 1 FROM helper_sync_meta WHERE id=1 AND journal_id=?1 AND checkpoint>=1 AND generation=150 AND last_decision=?2 AND agent_journal_id=?3 AND agent_checkpoint=6756 AND fault IS NULL)",params![request.helper_journal_id,LAST,request.journal_id],|r|r.get(0))?; + ensure!(head && helper_head, "live reconciliation heads differ"); + } + decisions.push(serde_json::json!({ + "checkpoint": checkpoint, "request_id": request_id, "request_sha256": hash(&raw_request), + "decision_id": decision_id, "payload_sha256": hash(&response.decision_bytes), + "signature_sha256": hash(&response.signature), "reason": d.reason + })); + } + Ok(decisions) +} diff --git a/crates/agent-core/tests/support/windows_review_fixture.rs b/crates/agent-core/tests/support/windows_review_fixture.rs new file mode 100644 index 0000000..7772a35 --- /dev/null +++ b/crates/agent-core/tests/support/windows_review_fixture.rs @@ -0,0 +1,125 @@ +// Isolated synthetic test data shared by the two Windows operator CLI test harnesses. +use anyhow::Result; +use chrono::{Duration, Utc}; +use ed25519_dalek::{Signer, SigningKey}; +use prost::Message; +use rmm_agent_core::{ + auth::Binding, + helper_reconcile::SignedResponse, + windows_sync_history::{AGENT, BOOT, CASES, FAULT, FIRST, LAST}, +}; +use rmm_domain::{jobs::hash, reconciliation::ReconcileDecisionPayload}; +use rmm_protocol::{Envelope, Payload, SyncRequest, SyncResponse}; +use rusqlite::{Connection, params}; +use uuid::Uuid; +pub fn verified_pair() -> Result<(Connection, Connection, Connection, Binding, SigningKey)> { + let a = Connection::open_in_memory()?; + let l = Connection::open_in_memory()?; + let h = Connection::open_in_memory()?; + rmm_agent_core::reconcile::initialize(&a)?; + a.execute_batch("CREATE TABLE job_attempts(job); CREATE TABLE job_events(id,payload); CREATE TABLE events(id,payload);")?; + for db in [&l, &h] { + db.execute_batch( + "CREATE TABLE consumed(grant_id); CREATE TABLE execution_evidence(grant_id);", + )?; + } + l.execute_batch("CREATE TABLE reconcile_consumption(decision_id,response);")?; + h.execute_batch("CREATE TABLE helper_sync_rows(grant_id); CREATE TABLE helper_sync_decisions(decision_id,checkpoint,response,request); CREATE TABLE helper_sync_meta(id,journal_id,checkpoint,generation,last_decision,agent_journal_id,agent_checkpoint,fault);")?; + let id = Uuid::new_v4(); + let peer = Uuid::new_v4(); + let key = SigningKey::from_bytes(&[13; 32]); // Public deterministic fixture only. + let binding = Binding { + tenant_id: Uuid::new_v4(), + agent_id: Uuid::parse_str(AGENT)?, + asset_id: Uuid::new_v4(), + assignment_version: 1, + enrollment_generation: 1, + public_key_hex: key + .verifying_key() + .to_bytes() + .iter() + .map(|b| format!("{b:02x}")) + .collect(), + }; + for (req, dec, cp) in CASES { + let first = dec == FIRST; + let r = SyncRequest { + request_id: req.into(), + journal_id: id.to_string(), + checkpoint: cp, + assignment_version: 1, + journal_complete: true, + helper_journal_id: peer.to_string(), + helper_checkpoint: 1, + previous_decision_id: if first { "" } else { FIRST }.into(), + ..Default::default() + }; + let raw = r.encode_to_vec(); + let e = Envelope { + protocol_major: 1, + agent_id: AGENT.into(), + enrollment_generation: 1, + connection_generation: 150, + boot_id: BOOT.into(), + sequence: cp, + payload: Some(Payload::SyncRequest(r)), + ..Default::default() + }; + let now = Utc::now() - Duration::hours(1); + let d = ReconcileDecisionPayload { + domain: "rmm.reconciliation-decision".into(), + schema_version: 1, + decision_id: Uuid::parse_str(dec)?, + request_id: Uuid::parse_str(req)?, + request_hash: hash(&raw), + tenant_id: binding.tenant_id, + asset_id: binding.asset_id, + agent_id: binding.agent_id, + enrollment_generation: 1, + assignment_version: 1, + connection_generation: 150, + boot_id: Uuid::parse_str(BOOT)?, + journal_id: id, + checkpoint: cp, + helper_journal_id: Some(peer), + helper_checkpoint: 1, + issued_at: now, + valid_until: now + Duration::seconds(60), + ready: first, + helper_ready: first, + reason: if first { "CONSISTENT" } else { FAULT }.into(), + attempts: vec![], + acknowledged_message_ids: vec![], + key_id: hash(&key.verifying_key().to_bytes()), + }; + let bytes = serde_json::to_vec(&d)?; + let signed = SyncResponse { + signature: key.sign(&bytes).to_bytes().into(), + decision_bytes: bytes, + }; + a.execute("INSERT INTO reconcile_requests(id,request,envelope,generation,response) VALUES(?,?,?,150,?)",params![req,raw,e.encode_to_vec(),signed.encode_to_vec()])?; + l.execute( + "INSERT INTO reconcile_consumption VALUES(?,?)", + params![dec, signed.encode_to_vec()], + )?; + if !first { + h.execute( + "INSERT INTO helper_sync_decisions VALUES(?,1,?,?)", + params![ + dec, + serde_json::to_vec(&SignedResponse { + signature: signed.signature, + decision_bytes: signed.decision_bytes + })?, + raw + ], + )?; + } + } + a.execute("UPDATE reconcile_meta SET journal_id=?,checkpoint=6756,generation=150,last_decision=?,helper_id=?,helper_checkpoint=1,fault=?",params![id.to_string(),LAST,peer.to_string(),FAULT])?; + h.execute( + "INSERT INTO helper_sync_meta VALUES(1,?,9,150,?,?,6756,NULL)", + params![peer.to_string(), LAST, id.to_string()], + )?; + Ok((a, l, h, binding, key)) +} diff --git a/crates/agent-windows/Cargo.toml b/crates/agent-windows/Cargo.toml index e81105f..1bfd5c7 100644 --- a/crates/agent-windows/Cargo.toml +++ b/crates/agent-windows/Cargo.toml @@ -42,3 +42,10 @@ cc = "=1.11.1" [target.'cfg(windows)'.dependencies] windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_ApplicationInstallationAndServicing", "Win32_System_EventLog", "Win32_System_Diagnostics_ToolHelp", "Win32_System_JobObjects", "Win32_System_Pipes", "Win32_System_SystemInformation", "Win32_System_Registry", "Win32_System_Memory", "Win32_System_Services", "Win32_System_Threading"] } + +[[example]] +name = "windows_reviewed_recovery" +required-features = ["system-helper"] + +[dev-dependencies] +ed25519-dalek = "=2.2.0" diff --git a/crates/agent-windows/examples/windows_reviewed_recovery.rs b/crates/agent-windows/examples/windows_reviewed_recovery.rs new file mode 100644 index 0000000..1241e39 --- /dev/null +++ b/crates/agent-windows/examples/windows_reviewed_recovery.rs @@ -0,0 +1,337 @@ +//! Local operator CLI. Verifies the scoped OIDC review; a fresh ordinary Sync is still required. +#[cfg(any(windows, test))] +#[path = "windows_reviewed_recovery/local.rs"] +mod local; + +#[cfg(windows)] +mod windows { + use super::local::{LocalJournals, Reviewed}; + use anyhow::{Context, Result, ensure}; + use fs2::FileExt; + use rmm_agent_core::{ + auth::Binding, + windows_sync_history::{BINDING_SHA256, BOOT, FAULT, verify_local_history}, + }; + use rmm_agent_windows::{ + SERVICE_NAME, + helper_ipc::{self as ipc, PinnedFile}, + helper_runtime::intent, + helper_system, native, + }; + use rmm_domain::{jobs::hash, windows_sync_history::case_witness}; + use rusqlite::{Connection, OpenFlags}; + use std::{ + fs::{File, OpenOptions}, + io::{Read, Seek, SeekFrom}, + os::windows::{ + fs::{MetadataExt, OpenOptionsExt}, + io::AsRawHandle, + }, + path::Path, + }; + use windows_sys::Win32::{ + Storage::FileSystem::{BY_HANDLE_FILE_INFORMATION, GetFileInformationByHandle}, + System::Services::*, + }; + const ROOT: &str = r"C:\ProgramData\RustDiscovery"; + const STATE: &str = r"C:\ProgramData\RustDiscovery\state"; + const RECEIPT: &str = r"C:\ProgramData\RustDiscoveryBootstrap\windows-checkpoint-review.json"; + const PASSIVE: &str = "7c9f6f3642ef84337c3cd761d8a4788c4babe81522fdd987a3eb9b819bc8d851"; + const AGENT_DB: &str = r"C:\ProgramData\RustDiscovery\state\telemetry.sqlite"; + const LOCAL_DB: &str = r"C:\ProgramData\RustDiscovery\state\consumption.sqlite"; + const HELPER_DB: &str = r"C:\ProgramData\RustDiscoverySystem\state\ledger.sqlite"; + + struct ScHandle(SC_HANDLE); + impl Drop for ScHandle { + fn drop(&mut self) { + unsafe { + CloseServiceHandle(self.0); + } + } + } + fn is_stopped(name: &str) -> Result { + let mgr = ScHandle(unsafe { + OpenSCManagerW(std::ptr::null(), std::ptr::null(), SC_MANAGER_CONNECT) + }); + ensure!(!mgr.0.is_null(), "SCM unreadable"); + let name: Vec = name.encode_utf16().chain(Some(0)).collect(); + let svc = ScHandle(unsafe { OpenServiceW(mgr.0, name.as_ptr(), SERVICE_QUERY_STATUS) }); + ensure!(!svc.0.is_null(), "service missing"); + let mut status: SERVICE_STATUS_PROCESS = unsafe { std::mem::zeroed() }; + let mut size = 0; + ensure!( + unsafe { + QueryServiceStatusEx( + svc.0, + SC_STATUS_PROCESS_INFO, + (&mut status as *mut SERVICE_STATUS_PROCESS).cast(), + size_of::() as u32, + &mut size, + ) + } != 0, + "service status unreadable" + ); + Ok(status.dwCurrentState == SERVICE_STOPPED && status.dwProcessId == 0) + } + fn both_stopped() -> Result { + Ok(is_stopped(SERVICE_NAME)? && is_stopped(ipc::HELPER_SERVICE)?) + } + fn leaf(path: &Path) -> Result { + for a in path.ancestors() { + ensure!( + a.symlink_metadata()?.file_attributes() & 0x400 == 0, + "reparse path" + ); + } + let f = OpenOptions::new().read(true).share_mode(3).open(path)?; + let mut i: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() }; + ensure!( + unsafe { GetFileInformationByHandle(f.as_raw_handle(), &mut i) } != 0 + && i.nNumberOfLinks == 1 + && i.dwFileAttributes & 0x410 == 0, + "unexpected file/hardlink" + ); + Ok(f) + } + struct Db { + db: Connection, + _handles: Vec, + } + impl Db { + fn open(path: &str, write: bool, stopped: bool) -> Result { + let mut main = leaf(Path::new(path))?; + let mut header = [0u8; 20]; + main.read_exact(&mut header)?; + ensure!( + header.starts_with(b"SQLite format 3\0") + && header[18] == header[19] + && matches!(header[18], 1 | 2), + "unexpected SQLite header" + ); + let mut files = vec![main]; + let mut has_wal = false; + let mut has_shm = false; + let mut has_journal = false; + for (suffix, present) in [ + ("-wal", &mut has_wal), + ("-shm", &mut has_shm), + ("-journal", &mut has_journal), + ] { + let name = format!("{path}{suffix}"); + if Path::new(&name).try_exists()? { + files.push(leaf(Path::new(&name))?); + *present = true; + } + } + let flags = if write { + OpenFlags::SQLITE_OPEN_READ_WRITE + } else { + OpenFlags::SQLITE_OPEN_READ_ONLY + }; + let db = if !write && header[18] == 2 && !(has_wal && has_shm) { + // Only under both exclusive lifetime service locks, after a clean WAL close. + ensure!( + stopped && !has_wal && !has_shm && !has_journal, + "read-only WAL snapshot unavailable" + ); + let url = format!("file:///{}?mode=ro&immutable=1", path.replace('\\', "/")); + Connection::open_with_flags(url, flags | OpenFlags::SQLITE_OPEN_URI)? + } else { + Connection::open_with_flags(path, flags)? + }; + db.busy_timeout(std::time::Duration::from_secs(2))?; + db.execute_batch("PRAGMA trusted_schema=OFF")?; + if write { + db.execute_batch("PRAGMA synchronous=FULL")?; + } else { + db.execute_batch("PRAGMA query_only=ON; BEGIN;")?; + } + Ok(Self { + db, + _handles: files, + }) + } + } + fn data(file: &mut File, max: u64) -> Result> { + ensure!(file.metadata()?.len() <= max, "public file too large"); + file.seek(SeekFrom::Start(0))?; + let mut bytes = vec![]; + file.take(max + 1).read_to_end(&mut bytes)?; + ensure!(bytes.len() as u64 <= max, "public file changed"); + Ok(bytes) + } + pub fn run() -> Result<()> { + let args: Vec<_> = std::env::args().skip(1).collect(); + ensure!( + args.len() == 1 + && matches!( + args[0].as_str(), + "prepare" | "read" | "verify-receipt" | "apply" + ), + "use prepare, read, verify-receipt or apply" + ); + let apply = args[0] == "apply"; + let key_readers = [ipc::service_sid(SERVICE_NAME)?]; + let _root = PinnedFile::open(Path::new(ROOT), true, &key_readers, &[], false)?; + let mut binding_file = PinnedFile::open( + &Path::new(ROOT).join("binding.json"), + false, + &key_readers, + &[], + false, + )?; + let bytes = data(&mut binding_file.file, 8192)?; + ensure!(hash(&bytes) == BINDING_SHA256, "changed job binding"); + let agent: Binding = serde_json::from_slice(&bytes)?; + let (settings, _helper_pins) = helper_system::read_settings()?; + let witness = case_witness(); + ensure!( + !settings.enable_effects && !settings.allow_reboot, + "expected passive helper policy" + ); + let mut config = PinnedFile::open( + &Path::new(ROOT).join("config.json"), + false, + &key_readers, + &[], + false, + )?; + ensure!( + config.sha256()? == PASSIVE, + "operator must restore passive config first" + ); + let boot = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build()? + .block_on(native::boot_id())?; + ensure!(boot == BOOT, "unexpected Windows boot"); + let review = if matches!(args[0].as_str(), "verify-receipt" | "apply") { + let _folder = PinnedFile::open( + Path::new(RECEIPT).parent().context("bootstrap path")?, + true, + &[], + &[], + false, + )?; + let mut file = PinnedFile::open(Path::new(RECEIPT), false, &[], &[], false)?; + Some(Reviewed::verify( + data(&mut file.file, 65536)?, + &agent, + &settings.binding, + &witness, + )?) + } else { + None + }; + let mut locks = vec![]; + let quiescent = both_stopped()?; + ensure!( + !apply || quiescent, + "both services must be stopped by the operator" + ); + if quiescent { + for path in [ + Path::new(STATE).join("agent.lock"), + Path::new(helper_system::STATE_ROOT).join("executor.lock"), + ] { + let f = leaf(&path)?; + f.try_lock_exclusive().context("service lock busy")?; + locks.push(f); + } + ensure!(both_stopped()?, "service started during recovery"); + } + native::private_path(Path::new(STATE), true)?; + for p in [AGENT_DB, LOCAL_DB] { + native::private_path(Path::new(p), false)?; + } + let helper_sid = [ipc::service_sid(ipc::HELPER_SERVICE)?]; + let _helper_state = PinnedFile::open_read_shared( + Path::new(helper_system::STATE_ROOT), + true, + &[], + &helper_sid, + )?; + let helper_file = + PinnedFile::open_read_shared(Path::new(HELPER_DB), false, &[], &helper_sid)?; + let mut a = Db::open(AGENT_DB, apply, quiescent)?; + let c = Db::open(LOCAL_DB, false, quiescent)?; + let h = Db::open(HELPER_DB, false, quiescent)?; + let (ledger, lock, pin): (Vec, Vec, 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::(&ledger)? == helper_file.identity + && pin == ipc::binding_hash(&settings.binding)?, + "helper journal or binding changed" + ); + let _intents = if Path::new(intent::DB).try_exists()? { + Some(intent::Store::open_empty_history_snapshot()?) + } else { + None + }; + if apply { + ensure!( + serde_json::from_slice::(&lock)? + == ipc::file_identity(&locks[1])?, + "helper lock identity changed" + ); + ensure!(both_stopped()?, "service started during recovery"); + let mut db = LocalJournals { + agent: &mut a.db, + consumption: &c.db, + helper: &h.db, + agent_binding: &agent, + helper_binding: &settings.binding, + }; + println!( + "{}", + db.apply( + review.as_ref().context("missing real human receipt")?, + chrono::Utc::now + )? + ); + } else { + let fault: Option = + a.db.query_row("SELECT fault FROM reconcile_meta WHERE id=1", [], |r| { + r.get(0) + })?; + ensure!( + fault.is_none() || fault.as_deref() == Some(FAULT), + "different fault" + ); + let decisions = verify_local_history( + &a.db, + &c.db, + &h.db, + &agent, + &settings.binding, + fault.as_deref(), + )?; + ensure!( + serde_json::Value::Array(decisions) == witness["decisions"], + "unreviewed current history" + ); + if let Some(review) = &review { + review.timely(chrono::Utc::now())?; + println!("valid human review for the verified local history"); + } + println!( + "verified contracted history; fault={}", + fault.as_deref().unwrap_or("none") + ); + } + Ok(()) + } +} +fn main() -> anyhow::Result<()> { + #[cfg(windows)] + { + windows::run() + } + #[cfg(not(windows))] + { + anyhow::bail!("native Windows operator executable") + } +} diff --git a/crates/agent-windows/examples/windows_reviewed_recovery/local.rs b/crates/agent-windows/examples/windows_reviewed_recovery/local.rs new file mode 100644 index 0000000..05df041 --- /dev/null +++ b/crates/agent-windows/examples/windows_reviewed_recovery/local.rs @@ -0,0 +1,412 @@ +//! Transactional local half of the human-reviewed, zero-job test incident. +use anyhow::{Context, Result, ensure}; +use chrono::{DateTime, Utc}; +use prost::Message; +use rmm_agent_core::{ + auth::Binding, + crypto::{DalekVerifier, Ed25519Verifier}, + windows_sync_history::{FAULT, LAST, verify_local_history}, +}; +use rmm_domain::{checkpoint_repair::SignedReceipt, jobs::hash, windows_sync_history::Receipt}; +use rmm_protocol::{Envelope, Payload}; +use rusqlite::{Connection, OptionalExtension, TransactionBehavior, params, types::ValueRef}; +use serde_json::Value; +use sha2::{Digest, Sha256}; + +const AUDIT: &str = "windows_human_checkpoint_recovery"; +const AUDIT_SQL: &str = "CREATE TABLE windows_human_checkpoint_recovery(id INTEGER PRIMARY KEY CHECK(id=1),review_id TEXT NOT NULL,receipt_id TEXT NOT NULL,old_fault TEXT NOT NULL,original_receipt BLOB NOT NULL,inventory_sha256 TEXT NOT NULL,applied_at TEXT NOT NULL)"; +pub struct Reviewed { + receipt: Receipt, + original: Vec, +} + +impl Reviewed { + pub fn verify( + raw: Vec, + agent: &Binding, + helper: &Binding, + expected: &Value, + ) -> Result { + ensure!(raw.len() <= 65536, "recovery envelope size"); + let envelope: SignedReceipt = serde_json::from_slice(&raw)?; + ensure!( + envelope.payload.len() <= 16384 && envelope.signature.len() == 64, + "recovery signature size" + ); + for b in [agent, helper] { + let key = hex_key(&b.public_key_hex)?; + ensure!( + expected["verification_key_id"] == hash(&key) + && expected["tenant_id"] == b.tenant_id.to_string() + && expected["agent_id"] == b.agent_id.to_string() + && expected["asset_id"] == b.asset_id.to_string() + && expected["enrollment_generation"] == b.enrollment_generation + && expected["assignment_version"] == b.assignment_version, + "pinned independent role identity" + ); + ensure!( + DalekVerifier.verify(&key, &envelope.payload, &envelope.signature)?, + "recovery signature" + ); + } + let receipt: Receipt = serde_json::from_slice(&envelope.payload)?; + // Historical validity is sufficient for looking up a previously committed receipt. + ensure!( + receipt.matches_reviewed_witness(expected, receipt.issued_at), + "historical human review" + ); + Ok(Self { + receipt, + original: raw, + }) + } + pub fn timely(&self, now: DateTime) -> Result<()> { + ensure!( + self.receipt.issued_at <= now && now < self.receipt.valid_until, + "human receipt expired or premature" + ); + Ok(()) + } +} + +fn hex_key(s: &str) -> Result> { + ensure!(s.len() == 64 && s.is_ascii(), "job pin shape"); + (0..64) + .step_by(2) + .map(|i| u8::from_str_radix(&s[i..i + 2], 16).map_err(Into::into)) + .collect() +} + +fn include(hash: &mut Sha256, tag: u8, bytes: &[u8]) { + hash.update([tag]); + hash.update((bytes.len() as u64).to_le_bytes()); + hash.update(bytes); +} + +/// Compare the full logical contents and schema, excluding only the receipt and normalized fault. +fn inventory(db: &Connection) -> Result { + let check: String = db.query_row("PRAGMA integrity_check", [], |r| r.get(0))?; + ensure!(check == "ok", "journal integrity"); + let mut statement = db.prepare( + "SELECT type,name,tbl_name,sql FROM sqlite_schema WHERE tbl_name<>?1 ORDER BY type,name", + )?; + let mut rows = statement.query([AUDIT])?; + let mut tables = Vec::new(); + let mut digest = Sha256::new(); + while let Some(row) = rows.next()? { + let kind: String = row.get(0)?; + let name: String = row.get(1)?; + let table: String = row.get(2)?; + let sql: Option = row.get(3)?; + ensure!( + matches!(kind.as_str(), "table" | "index" | "trigger") + && !(kind == "trigger" && table == "reconcile_meta") + && !sql + .as_deref() + .unwrap_or_default() + .to_ascii_uppercase() + .contains("VIRTUAL TABLE"), + "unexpected journal schema program" + ); + for s in [ + kind.as_str(), + name.as_str(), + table.as_str(), + sql.as_deref().unwrap_or_default(), + ] { + include(&mut digest, 0, s.as_bytes()); + } + if kind == "table" { + ensure!( + tables.len() < 256 + && !name.is_empty() + && name.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'_'), + "unsupported journal table" + ); + tables.push(name); + } + } + for table in tables { + include(&mut digest, 1, table.as_bytes()); + let mut q = db.prepare(&format!("SELECT rowid,* FROM \"{table}\" ORDER BY rowid"))?; + let cols: Vec<_> = q.column_names().iter().map(|s| s.to_string()).collect(); + let mut rows = q.query([])?; + while let Some(row) = rows.next()? { + include(&mut digest, 2, &[]); + for (i, name) in cols.iter().enumerate() { + let value = row.get_ref(i)?; + if table == "reconcile_meta" && name == "fault" { + ensure!( + value == ValueRef::Null || value == ValueRef::Text(FAULT.as_bytes()), + "foreign fault" + ); + include(&mut digest, 3, FAULT.as_bytes()); + continue; + } + match value { + ValueRef::Null => include(&mut digest, 4, &[]), + ValueRef::Integer(v) => include(&mut digest, 5, &v.to_le_bytes()), + ValueRef::Real(v) => include(&mut digest, 6, &v.to_bits().to_le_bytes()), + ValueRef::Text(bytes) => include(&mut digest, 7, bytes), + ValueRef::Blob(bytes) => include(&mut digest, 8, bytes), + } + } + } + } + Ok(format!("{:x}", digest.finalize())) +} + +pub struct LocalJournals<'a> { + pub agent: &'a mut Connection, + pub consumption: &'a Connection, + pub helper: &'a Connection, + pub agent_binding: &'a Binding, + pub helper_binding: &'a Binding, +} + +impl LocalJournals<'_> { + /// Only one database changes. Both service locks must span this transaction on Windows. + pub fn apply( + &mut self, + reviewed: &Reviewed, + now: impl Fn() -> DateTime, + ) -> Result<&'static str> { + let tx = self + .agent + .transaction_with_behavior(TransactionBehavior::Immediate)?; + let prior: Option = tx + .query_row( + "SELECT sql FROM sqlite_schema WHERE name=?1", + [AUDIT], + |r| r.get(0), + ) + .optional()?; + let applied = prior.is_some(); + if let Some(schema) = prior { + ensure!( + schema == AUDIT_SQL + && tx.query_row( + "SELECT count(*) FROM sqlite_schema WHERE tbl_name=?1", + [AUDIT], + |r| r.get::<_, usize>(0) + )? == 1, + "foreign archive" + ); + let identical:bool=tx.query_row("SELECT EXISTS(SELECT 1 FROM windows_human_checkpoint_recovery WHERE id=1 AND review_id=? AND receipt_id=? AND old_fault=? AND original_receipt=?)",params![reviewed.receipt.request_id.to_string(),reviewed.receipt.receipt_id.to_string(),FAULT,reviewed.original],|r|r.get(0))?; + ensure!(identical, "another recovery already exists"); + } + let original = verify_local_history( + &tx, + self.consumption, + self.helper, + self.agent_binding, + self.helper_binding, + (!applied).then_some(FAULT), + )?; + ensure!( + reviewed.receipt.witness["decisions"] == Value::Array(original), + "receipt differs from local original decisions" + ); + let current:bool=tx.query_row("SELECT EXISTS(SELECT 1 FROM reconcile_meta WHERE id=1 AND journal_id=? AND helper_id=? AND last_decision=? AND checkpoint=6756 AND helper_checkpoint=1 AND pending_request IS NULL)", params![reviewed.receipt.witness["agent_journal_id"].as_str().context("agent journal")?,reviewed.receipt.witness["helper_journal_id"].as_str().context("helper journal")?,LAST],|r|r.get(0))?; + ensure!(current, "unreviewed journal identities"); + let count: u64 = + self.helper + .query_row("SELECT count(*) FROM helper_sync_rows", [], |r| r.get(0))?; + ensure!(count == 0, "helper consumption rows"); + for db in [&*tx, self.consumption, self.helper] { + let n:i64=db.query_row("SELECT count(*) FROM sqlite_schema WHERE type='view' OR (type='table' AND instr(upper(sql),'VIRTUAL TABLE')>0)",[],|r|r.get(0))?; + ensure!(n == 0, "unexpected journal program"); + } + let health_rows: i64 = + tx.query_row("SELECT count(*) FROM update_health_inventory", [], |r| { + r.get(0) + })?; + ensure!(health_rows == 0, "unreviewed update grant"); + for sql in [ + "SELECT id,payload FROM events", + "SELECT id,payload FROM job_events", + ] { + let mut q = tx.prepare(sql)?; + let mut rows = q.query([])?; + while let Some(row) = rows.next()? { + let id: String = row.get(0)?; + let bytes = row.get_ref(1)?.as_blob()?; + ensure!(bytes.len() <= rmm_domain::MAX_MESSAGE, "event size"); + let e = Envelope::decode(bytes)?; + ensure!( + e.message_id == id && matches!(e.payload, Some(Payload::InventorySnapshot(_))), + "unreviewed event" + ); + } + } + if applied { + let saved: String = tx.query_row( + "SELECT inventory_sha256 FROM windows_human_checkpoint_recovery WHERE id=1", + [], + |r| r.get(0), + )?; + ensure!(inventory(&tx)? == saved, "archive inventory changed"); + return Ok("already applied"); + } + reviewed.timely(now())?; + let before = inventory(&tx)?; + tx.execute(AUDIT_SQL, [])?; + tx.execute( + "INSERT INTO windows_human_checkpoint_recovery VALUES(1,?,?,?,?,?,?)", + params![ + reviewed.receipt.request_id.to_string(), + reviewed.receipt.receipt_id.to_string(), + FAULT, + reviewed.original, + before, + now().to_rfc3339() + ], + )?; + ensure!(tx.execute("UPDATE reconcile_meta SET fault=NULL WHERE id=1 AND fault=?1 AND last_decision=?2 AND checkpoint=6756 AND generation=150 AND pending_request IS NULL",params![FAULT,LAST])?==1,"journal head changed"); + let cleared: bool = tx.query_row( + "SELECT fault IS NULL FROM reconcile_meta WHERE id=1", + [], + |r| r.get(0), + )?; + ensure!( + cleared && inventory(&tx)? == before, + "unrelated journal data changed" + ); + reviewed.timely(now())?; + tx.commit()?; + Ok("review archived; normal signed sync required") + } +} + +#[cfg(test)] +mod tests { + use super::*; + use chrono::Duration; + use ed25519_dalek::{Signer, SigningKey}; + use rmm_domain::{ + checkpoint_repair::inventory_sha256, + windows_sync_history::{RECEIPT_DOMAIN, case_witness}, + }; + use uuid::Uuid; + mod data { + include!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../agent-core/tests/support/windows_review_fixture.rs" + )); + } + fn signed(r: &Receipt, k: &SigningKey) -> Result> { + let payload = serde_json::to_vec(r)?; + Ok(serde_json::to_vec(&SignedReceipt { + signature: k.sign(&payload).to_bytes().to_vec(), + payload, + })?) + } + #[test] + fn archived_human_review_preserves_both_journals() -> Result<()> { + let (mut a, l, h, binding, key) = data::verified_pair()?; + let now = Utc::now(); + let mut witness = case_witness(); + let (journal, peer): (String, String) = a.query_row( + "SELECT journal_id,helper_id FROM reconcile_meta WHERE id=1", + [], + |r| Ok((r.get(0)?, r.get(1)?)), + )?; + witness["agent_journal_id"] = journal.into(); + witness["helper_journal_id"] = peer.into(); + witness["verification_key_id"] = hash(&key.verifying_key().to_bytes()).into(); + witness["tenant_id"] = binding.tenant_id.to_string().into(); + witness["asset_id"] = binding.asset_id.to_string().into(); + witness["decisions"] = + verify_local_history(&a, &l, &h, &binding, &binding, Some(FAULT))?.into(); + let r = Receipt { + domain: RECEIPT_DOMAIN.into(), + schema_version: 1, + request_id: Uuid::new_v4(), + receipt_id: Uuid::new_v4(), + key_id: hash(&key.verifying_key().to_bytes()), + issued_at: now, + valid_until: now + Duration::minutes(10), + witness: witness.clone(), + witness_sha256: inventory_sha256(&witness)?, + confirmed_by: format!("oidc:{}", "a".repeat(64)), + approval_origin: "human_webui".into(), + testsimulation: false, + ready: false, + helper_ready: false, + unlock: false, + }; + let raw = signed(&r, &key)?; + let ok = Reviewed::verify(raw.clone(), &binding, &binding, &witness)?; + for e in 0..7 { + let mut bad = r.clone(); + match e { + 0 => bad.testsimulation = true, + 1 => bad.ready = true, + 2 => bad.confirmed_by = "simulated-testprincipal-a".into(), + 3 => bad.approval_origin = "dev_test_browser_simulation".into(), + 4 => bad.unlock = true, + 5 => bad.witness["local_head_checkpoint"] = 6755.into(), + _ => bad.domain = "rmm.reconciliation-decision".into(), + } + assert!(Reviewed::verify(signed(&bad, &key)?, &binding, &binding, &witness).is_err()); + } + let foreign = SigningKey::from_bytes(&[7; 32]); + assert!(Reviewed::verify(signed(&r, &foreign)?, &binding, &binding, &witness).is_err()); + let mut different = binding.clone(); + different.public_key_hex = "00".repeat(32); + assert!(Reviewed::verify(raw.clone(), &binding, &different, &witness).is_err()); + let prior = inventory(&a)?; + let local_before = inventory(&l)?; + let helper_before = inventory(&h)?; + let mut db = LocalJournals { + agent: &mut a, + consumption: &l, + helper: &h, + agent_binding: &binding, + helper_binding: &binding, + }; + assert!(db.apply(&ok, || now + Duration::minutes(10)).is_err()); + db.agent.execute_batch("CREATE TRIGGER unexpected AFTER UPDATE ON reconcile_meta BEGIN DELETE FROM job_attempts; END;")?; + assert!(db.apply(&ok, || now).is_err()); + db.agent.execute_batch("DROP TRIGGER unexpected")?; + db.agent + .execute("INSERT INTO job_attempts VALUES('test')", [])?; + assert!(db.apply(&ok, || now).is_err()); + db.agent.execute("DELETE FROM job_attempts", [])?; + assert_eq!( + db.apply(&ok, || now)?, + "review archived; normal signed sync required" + ); + assert_eq!(inventory(db.agent)?, prior); + assert_eq!(inventory(&l)?, local_before); + assert_eq!(inventory(&h)?, helper_before); + let (fault, bytes): (String, Vec) = db.agent.query_row( + "SELECT old_fault,original_receipt FROM windows_human_checkpoint_recovery", + [], + |q| Ok((q.get(0)?, q.get(1)?)), + )?; + assert_eq!(fault, FAULT); + assert_eq!(bytes, raw); + let status: Option = + db.agent + .query_row("SELECT fault FROM reconcile_meta WHERE id=1", [], |q| { + q.get(0) + })?; + assert!(status.is_none()); + assert_eq!( + db.apply(&ok, || now + Duration::days(1))?, + "already applied" + ); + db.agent.execute_batch("CREATE TABLE unrelated(n)")?; + assert!(db.apply(&ok, || now).is_err()); + db.agent.execute_batch("DROP TABLE unrelated")?; + let mut other = r.clone(); + other.receipt_id = Uuid::new_v4(); + let other = Reviewed::verify(signed(&other, &key)?, &binding, &binding, &witness)?; + assert!(db.apply(&other, || now).is_err()); + db.agent + .execute("INSERT INTO job_attempts VALUES('later')", [])?; + assert!(db.apply(&ok, || now).is_err()); + Ok(()) + } +} diff --git a/crates/agent-windows/src/helper_intent.rs b/crates/agent-windows/src/helper_intent.rs index 2bd0a46..8f56283 100644 --- a/crates/agent-windows/src/helper_intent.rs +++ b/crates/agent-windows/src/helper_intent.rs @@ -233,6 +233,23 @@ impl Store { value.check()?; Ok(value) } + /// Verify the original protected journal and retain a read-only snapshot of its empty history. + pub fn open_empty_history_snapshot() -> Result { + let store = Self::open(false)?; + ensure!( + store.db.is_readonly(rusqlite::DatabaseName::Main)?, + "read-only intent snapshot required" + ); + store + .db + .execute_batch("PRAGMA trusted_schema=OFF; PRAGMA query_only=ON; BEGIN")?; + let count: usize = store.db.query_row( + "SELECT (SELECT count(*) FROM system_intents)+(SELECT count(*) FROM system_intent_mirrors)+(SELECT count(*) FROM system_intent_denial_resumes)", + [], |r|r.get(0), + )?; + ensure!(count == 0, "unreviewed SYSTEM delegation"); + Ok(store) + } pub fn check(&mut self) -> Result<()> { for file in &mut self.files { file.check()?; diff --git a/crates/agent-windows/src/helper_ipc.rs b/crates/agent-windows/src/helper_ipc.rs index d2fcb20..3d01f33 100644 --- a/crates/agent-windows/src/helper_ipc.rs +++ b/crates/agent-windows/src/helper_ipc.rs @@ -624,7 +624,8 @@ impl PinnedFile { ) -> Result { Self::open_impl(path, directory, readers, writers, write, false) } - pub(crate) fn open_read_shared( + /// Pin and check the object without opening a write-capable handle. + pub fn open_read_shared( path: &Path, directory: bool, readers: &[String], diff --git a/crates/domain/src/windows_sync_history.rs b/crates/domain/src/windows_sync_history.rs index 277afa1..4a8fcd5 100644 --- a/crates/domain/src/windows_sync_history.rs +++ b/crates/domain/src/windows_sync_history.rs @@ -40,16 +40,27 @@ impl Receipt { /// Compare a receipt to an independently produced historical witness, after signature verification. pub fn matches_reviewed_witness(&self, expected: &Value, now: DateTime) -> bool { let principal = self.confirmed_by.strip_prefix("oidc:"); - self.domain == RECEIPT_DOMAIN && self.schema_version == 1 - && !self.receipt_id.is_nil() && !self.request_id.is_nil() + self.domain == RECEIPT_DOMAIN + && self.schema_version == 1 + && !self.receipt_id.is_nil() + && !self.request_id.is_nil() && self.request_id != self.receipt_id - && !self.testsimulation && !self.ready && !self.helper_ready && !self.unlock + && !self.testsimulation + && !self.ready + && !self.helper_ready + && !self.unlock && self.approval_origin == "human_webui" - && principal.is_some_and(|s| s.len() == 64 && s.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))) - && self.issued_at <= now && now < self.valid_until + && principal.is_some_and(|s| { + s.len() == 64 + && s.bytes() + .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) + }) + && self.issued_at <= now + && now < self.valid_until && self.valid_until - self.issued_at <= Duration::minutes(10) && self.key_id == expected["verification_key_id"] && &self.witness == expected - && crate::checkpoint_repair::inventory_sha256(expected).is_ok_and(|h| h == self.witness_sha256) + && crate::checkpoint_repair::inventory_sha256(expected) + .is_ok_and(|h| h == self.witness_sha256) } } diff --git a/docs/windows-profile-acceptance.md b/docs/windows-profile-acceptance.md index 2468e7a..922c066 100644 --- a/docs/windows-profile-acceptance.md +++ b/docs/windows-profile-acceptance.md @@ -470,3 +470,15 @@ Die Konsole meldete einen bestandenen Test, null fehlgeschlagene und null gefilterte in 0,01 Sekunden. Alle SQLite-Daten waren synthetische In-Memory-Fixturen. Die tatsächlichen Agentjournale wurden dabei nicht repariert. Das ursprüngliche VM-Installationsmedium wurde wiederhergestellt. + +Das echte Windows-Operatorprogramm wurde anschließend über seinen regulären +lesenden Einstieg `read` auf der bestehenden VM ausgeführt. Es bestätigte +`verified contracted history; fault=HELPER_CHECKPOINT_REQUIRED`. Dabei las es +die vorhandenen drei Journale und beide geschützten Schlüsselbindungen. +EXE-SHA-256 +`6ea40e8e85dc0d01927c4be5a01bc7a18afce1d3313ebbf080713a621188d558`. +Release-Build und Windows-Clippy mit `-D warnings` bestanden. Der normale +Apply-Einstieg ist vorbereitet und verlangt die unabhängige menschliche +Quittung, gestoppte Dienste, beide gehaltenen Prozesslocks, die unveränderten +Originaljournale und den passenden passiven Konfigurationsstand. Er wurde +auf dieser Installation nicht ausgeführt.