diff --git a/crates/agent-core/examples/windows_sync_history.rs b/crates/agent-core/examples/windows_sync_history.rs new file mode 100644 index 0000000..24d59f2 --- /dev/null +++ b/crates/agent-core/examples/windows_sync_history.rs @@ -0,0 +1,362 @@ +//! 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}, +}; +use rmm_domain::{jobs::hash, reconciliation::ReconcileDecisionPayload}; +use rmm_protocol::{Envelope, Payload, SyncRequest, SyncResponse}; +use rusqlite::{Connection, OpenFlags, params}; +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()?; + ensure!(!meta.file_type().is_symlink(), "unexpected symbolic link"); + #[cfg(windows)] + { + use std::os::windows::fs::MetadataExt; + ensure!( + meta.file_attributes() & 0x400 == 0, + "unexpected reparse point" + ); + } + } + let mut options = OpenOptions::new(); + options.read(true); + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + options.share_mode(3); // FILE_SHARE_READ | FILE_SHARE_WRITE, deny delete/rename. + } + let f = options.open(path)?; + ensure!(f.metadata()?.is_file(), "expected a regular file"); + Ok(f) +} + +struct Snapshot { + db: Connection, + _held: Vec, +} + +impl Snapshot { + fn open(path: &str) -> Result { + let mut file = held(Path::new(path))?; + let mut hdr = [0; 20]; + file.read_exact(&mut hdr)?; + ensure!(&hdr[..16] == b"SQLite format 3\0", "unexpected DB header"); + ensure!( + hdr[18] == hdr[19] && matches!(hdr[18], 1 | 2), + "unexpected DB mode" + ); + let mut handles = vec![file]; + if hdr[18] == 2 { + // Pin both original sidecars before the read-only SQLite connection opens. + for suffix in ["-wal", "-shm"] { + handles.push(held(Path::new(&format!("{path}{suffix}")))?); + } + } + let db = Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_ONLY)?; + db.execute_batch("PRAGMA query_only=ON; PRAGMA trusted_schema=OFF; BEGIN;")?; + ensure!( + db.is_readonly(rusqlite::DatabaseName::Main)?, + "read-only database required" + ); + Ok(Self { db, _held: handles }) + } +} + +fn inspect( + agent: &Connection, + local: &Connection, + 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 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 {}", + hash(&hex::decode(&binding.public_key_hex)?) + ); + println!("gen150 journals agree on {LAST}; helper decisions 1"); + println!("agent fault {FAULT}; jobs and consumptions 0"); + Ok(()) +} + +fn main() -> Result<()> { + ensure!( + cfg!(windows) && std::env::args_os().count() == 1, + "fixed Windows VM readback only" + ); + let mut bytes = Vec::new(); + held(Path::new(r"C:\ProgramData\RustDiscovery\binding.json"))? + .take(8193) + .read_to_end(&mut bytes)?; + ensure!( + bytes.len() <= 8192 && hash(&bytes) == BINDING_SHA256, + "unexpected public binding" + ); + let binding: Binding = serde_json::from_slice(&bytes)?; + let agent = Snapshot::open(r"C:\ProgramData\RustDiscovery\state\telemetry.sqlite") + .context("agent database")?; + let local = Snapshot::open(r"C:\ProgramData\RustDiscovery\state\consumption.sqlite") + .context("agent consumption")?; + let helper = Snapshot::open(r"C:\ProgramData\RustDiscoverySystem\state\ledger.sqlite") + .context("helper database")?; + inspect(&agent.db, &local.db, &helper.db, &binding) +} + +#[cfg(test)] +mod tests { + use super::*; + use chrono::{Duration, Utc}; + use ed25519_dalek::{Signer, SigningKey}; + + #[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()], + )?; + inspect(&a, &l, &h, &binding)?; + let mut foreign = binding.clone(); + foreign.public_key_hex = + hex::encode(SigningKey::from_bytes(&[14; 32]).verifying_key().to_bytes()); + assert!(inspect(&a, &l, &h, &foreign).is_err()); + l.execute( + "UPDATE reconcile_consumption SET response=x'01' WHERE decision_id=?", + [FIRST], + )?; + assert!(inspect(&a, &l, &h, &binding).is_err()); + Ok(()) + } +} diff --git a/docs/windows-profile-acceptance.md b/docs/windows-profile-acceptance.md index d2eaac3..c66811b 100644 --- a/docs/windows-profile-acceptance.md +++ b/docs/windows-profile-acceptance.md @@ -387,3 +387,12 @@ Ausführungszählern erfasste Prüfbeleg hat SHA-256 Zwei lokal veränderte Kopien derselben zweiten Serverlesung dienten als Negativproben. Der Prüfer verwarf eine ersetzte Signatur und ebenso einen fälschlich als gültigen Vorgänger eingetragenen Checkpoint 6756. + +Auf der Cloud-Linux-VM prüfte das Fixture +`tests::verifies_two_originals_and_rejects_changed_history` die +Journalgegenprüfung am 15. November um 21:38:31 UTC. Beide +Originalsignaturen der Testdaten bestanden. Das Fixture wies einen +fremden Schlüssel und eine veränderte Verbrauchsquittung ab. Ein Test +bestand mit Exit 0 als UID 65534 im eigenen Netzwerk-Namespace. +Fall `97130142-3ac3-4d7d-b086-f366e99d9a30`, SHA-256 des Belegs +`36368fb6325448e4d0e66e431542ac98e8ccc1d722e2ec32720daf0bba4e6870`.