//! Optional passive helper control client. No SYSTEM action capability is //! advertised here. Each actual IPC runs on one bounded blocking lane. use crate::{helper_ipc as ipc, native}; use anyhow::{Context, Result, ensure}; use rmm_agent_core::{ auth::{Binding, Outcome, Request}, helper_reconcile::{NoStartAnchor, Snapshot}, reconcile::HelperSnapshot, }; use rmm_domain::jobs::{Action, JobPayload}; use rmm_protocol::{SyncAttempt, SyncResponse}; use serde_json::json; use std::{ io::{Read, Write}, path::Path, sync::Arc, time::Duration, }; use tokio::sync::Semaphore; #[path = "helper_intent.rs"] pub mod intent; pub const PIN_PATH: &str = r"C:\ProgramData\RustDiscoverySystem\agent-pin.json"; const PUBLIC_ROOT: &str = r"C:\ProgramData\RustDiscoverySystem"; const PROBE_FILE: &str = "helper-probe.json"; #[derive(Clone)] pub struct Client { pin: ipc::Pin, lane: Arc, } pub struct ControlSnapshot { pub raw: Snapshot, pub no_start_anchor: Option, } pub struct BoundOutcome { pub job_id: uuid::Uuid, pub attempt_id: uuid::Uuid, pub grant_id: uuid::Uuid, pub outcome: Outcome, } impl Client { /// Missing pin is deliberately passive. A present but invalid pin is refused; /// no endpoint/key/policy is discovered from the pipe itself. pub fn discover( agent_id: &str, asset_id: &str, binding: Option<&Binding>, lane: Arc, ) -> Result> { if !Path::new(PIN_PATH).try_exists()? { return Ok(None); } let readers = [ ipc::service_sid(crate::SERVICE_NAME)?, ipc::service_sid(ipc::HELPER_SERVICE)?, ]; let _root = ipc::PinnedFile::open_read_shared(Path::new(PUBLIC_ROOT), true, &readers, &[])?; let mut file = ipc::PinnedFile::open(Path::new(PIN_PATH), false, &readers, &[], false)?; ensure!(file.file.metadata()?.len() <= 16384, "HELPER_PIN_SIZE"); let mut bytes = Vec::new(); file.file.read_to_end(&mut bytes)?; let pin: ipc::Pin = serde_json::from_slice(&bytes)?; pin.validate()?; ensure!( pin.binding.agent_id.to_string() == agent_id && pin.binding.asset_id.to_string() == asset_id && pin.binding.enrollment_generation == binding.map_or(1, |b| b.enrollment_generation), "HELPER_ENROLLMENT_PIN_MISMATCH" ); if let Some(binding) = binding { ensure!( ipc::binding_hash(binding)? == ipc::binding_hash(&pin.binding)?, "HELPER_JOB_BINDING_MISMATCH" ); } Ok(Some(Self { pin, lane })) } pub async fn refresh( agent_id: String, asset_id: String, binding: Option, lane: Arc, state: std::path::PathBuf, ) -> Result> { let permit = lane .clone() .try_acquire_owned() .context("HELPER_CONTROL_BUSY")?; tokio::task::spawn_blocking(move || { let _permit = permit; let result=(|| { let client=Self::discover(&agent_id,&asset_id,binding.as_ref(),lane).context(ipc::Stage::DiscoverPin)?; if let Some(client)=&client {client.probe_blocking(&state)?;} Ok(client) })(); if result.is_err() || matches!(&result,Ok(None)) && state.join(PROBE_FILE).try_exists()? { let diagnostic=result.as_ref().err().map(ipc::diagnostic).unwrap_or(ipc::Diagnostic{stage:"discover_pin",code:"HELPER_PIN_NOT_CONFIGURED",win32:None}); write_current_probe(&state,&json!({"schema_version":1,"source":"actual_local_service_runtime","agent_process_id":std::process::id(),"agent_id":agent_id,"asset_id":asset_id,"observed_at":chrono::Utc::now(),"authenticated_pipe_exchange":false,"system_capability_advertised":false,"helper_ready":false,"no_jobs":true,"code":"HELPER_NOT_AVAILABLE","diagnostic":diagnostic}))?; } result }) .await? } fn check_pin(&self) -> Result<()> { let current = Self::discover( &self.pin.binding.agent_id.to_string(), &self.pin.binding.asset_id.to_string(), Some(&self.pin.binding), self.lane.clone(), )? .context("HELPER_PIN_REMOVED")?; ensure!( serde_json::to_vec(¤t.pin)? == serde_json::to_vec(&self.pin)?, "HELPER_PIN_CHANGED" ); Ok(()) } pub fn pin_hash(&self) -> &str { &self.pin.policy_sha256 } pub fn helper_binary_hash(&self) -> &str { &self.pin.helper.binary_sha256 } /// Import only independently authenticated raw helper evidence. c+start is /// atomic through the existing core API. A crash before outcome persistence /// stays locked; the next fresh snapshot repairs that exact start idempotently. pub fn mirror( &self, snapshot: &Snapshot, ledger: &mut rusqlite::Connection, observed_at: chrono::DateTime, ) -> Result> { use rmm_agent_core::{crypto::DalekVerifier, ledger as core_ledger}; use rusqlite::OptionalExtension; if !Path::new(intent::DB).try_exists()? { // Optional provisioning must not block the unprivileged provider. // Retained SYSTEM consumption, however, may never lose its store. let mut rows = ledger.prepare("SELECT start FROM execution_evidence")?; for row in rows.query_map([], |r| r.get::<_, Vec>(0))? { let value: serde_json::Value = serde_json::from_slice(&row?)?; let request: Request = serde_json::from_value(value["request"].clone())?; ensure!( self.pin.binding.job(&request.job_bytes)?.execution_identity != "system", "SYSTEM_INTENT_STORE_MISSING" ); } return Ok(Vec::new()); } let mut store = intent::Store::open(true)?; for intent in store.pending()? { self.pin.binding.verify_historical_for_denial_with( &intent.request, rmm_agent_core::auth::HelperIdentity::System, &DalekVerifier, )?; let job = self.pin.binding.job(&intent.request.job_bytes)?; let permit = intent.permit()?; ensure!( self.supports_system(&job) && intent.policy_sha256 == self.pin.policy_sha256 && intent.helper_binary_sha256 == self.pin.helper.binary_sha256 && snapshot.boot_id == intent.original_boot_id && snapshot.journal_id == intent.anchor.journal_id() && snapshot.checkpoint >= intent.anchor.checkpoint() && observed_at >= intent.recorded_at && observed_at >= snapshot.captured_at, "SYSTEM_MIRROR_CONTEXT" ); let mut matches = snapshot .attempts .iter() .filter(|a| a.job_id == job.job_id && a.attempt_id == job.attempt_id); let row = matches .next() .context("SYSTEM_DELEGATION_NO_HELPER_EVIDENCE")?; ensure!(matches.next().is_none(), "SYSTEM_DUPLICATE_HELPER_ATTEMPT"); let outcome = verified_mirror_row(row, &job, &permit, &intent.request, intent.original_boot_id)?; let existing:Option<(String,u64,String,String,Vec)>=ledger.query_row("SELECT c.agent,c.generation,c.job,c.attempt,e.start FROM consumed c JOIN execution_evidence e USING(grant_id) WHERE c.grant_id=?1",[permit.grant_id.to_string()],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?,r.get(4)?))).optional()?; if let Some((agent, generation, j, a, start)) = existing { let start: serde_json::Value = serde_json::from_slice(&start)?; let request: Request = serde_json::from_value(start["request"].clone())?; ensure!( agent == job.agent_id.to_string() && generation == job.enrollment_generation && j == job.job_id.to_string() && a == job.attempt_id.to_string() && serde_json::to_vec(&request)? == serde_json::to_vec(&intent.request)? && start["previous_boot_id"] == intent.original_boot_id.to_string() && serde_json::from_value::>( start["reserved_at"].clone() )? == intent.recorded_at, "SYSTEM_MIRROR_LOCAL_START_CONFLICT" ); } else { core_ledger::begin_execution( ledger, &permit, &intent.request, intent.original_boot_id, intent.recorded_at, )?; } core_ledger::persist_outcome(ledger, &permit, &outcome)?; store.mirrored(intent.id, &row.outcome_sha256, observed_at)?; } let mut unknowns = Vec::new(); for row in snapshot .attempts .iter() .filter(|row| row.state == "unknown") { let intent = store.by_grant(row.grant_id)?; self.pin.binding.verify_historical_for_denial_with( &intent.request, rmm_agent_core::auth::HelperIdentity::System, &DalekVerifier, )?; let job = self.pin.binding.job(&intent.request.job_bytes)?; let permit = intent.permit()?; ensure!( self.supports_system(&job) && intent.policy_sha256 == self.pin.policy_sha256 && intent.helper_binary_sha256 == self.pin.helper.binary_sha256 && snapshot.boot_id == intent.original_boot_id && snapshot.journal_id == intent.anchor.journal_id() && snapshot.checkpoint >= intent.anchor.checkpoint(), "SYSTEM_MIRROR_CONTEXT" ); let outcome = verified_mirror_row(row, &job, &permit, &intent.request, intent.original_boot_id)?; unknowns.push(BoundOutcome { job_id: job.job_id, attempt_id: job.attempt_id, grant_id: permit.grant_id, outcome, }); } store.check()?; Ok(unknowns) } async fn call(&self, operation: ipc::Operation) -> Result { self.call_bounded(operation, Duration::from_secs(5)).await } async fn time_call(&self, operation: ipc::Operation, timeout: Duration) -> Result { // Separate from the long Execute lane, retained process-wide even if a // caller/session is dropped while a blocking native call is outstanding. static TIME_LANE: std::sync::OnceLock> = std::sync::OnceLock::new(); let permit = TIME_LANE .get_or_init(|| Arc::new(Semaphore::new(1))) .clone() .try_acquire_owned() .context("HELPER_TIME_BUSY")?; let client = self.clone(); tokio::task::spawn_blocking(move || { let _permit = permit; client.check_pin()?; let call = ipc::Call::new(&client.pin, operation); let reply = ipc::exchange_time(&client.pin, &call, timeout)?; client.check_pin()?; Ok(reply) }) .await? } pub async fn time_begin(&self, generation: u64) -> Result { let reply = self .time_call( ipc::Operation::TimeBegin { generation }, Duration::from_secs(20), ) .await?; let ipc::ReplyBody::TimeChallenge { request } = reply.body else { anyhow::bail!("HELPER_TIME_BEGIN_DENIED"); }; request.validate()?; ensure!( request.context.role == rmm_time_attestation::Role::SystemHelper && request.context.connection_generation == generation && request.context.tenant_id == self.pin.binding.tenant_id && request.context.asset_id == self.pin.binding.asset_id && request.context.agent_id == self.pin.binding.agent_id && request.context.enrollment_generation == self.pin.binding.enrollment_generation && request.context.assignment_generation == self.pin.binding.assignment_version && request.context.helper_image_sha256.as_deref() == Some(self.pin.helper.binary_sha256.as_str()), "HELPER_TIME_REQUEST_BINDING" ); Ok(request) } pub async fn time_complete(&self, generation: u64, response_bytes: Vec) -> Result<()> { ensure!(response_bytes.len() <= 16384, "HELPER_TIME_RESPONSE_BOUND"); let reply = self .time_call( ipc::Operation::TimeComplete { generation, response_bytes, }, Duration::from_secs(1), ) .await?; ensure!( matches!(reply.body, ipc::ReplyBody::TimeCompleted {}), "HELPER_TIME_COMPLETE_DENIED" ); Ok(()) } pub async fn time_close(&self, generation: u64) -> Result<()> { let reply = self .time_call( ipc::Operation::TimeClose { generation }, Duration::from_secs(1), ) .await?; ensure!( matches!(reply.body, ipc::ReplyBody::TimeClosed {}), "HELPER_TIME_CLOSE_UNCONFIRMED" ); Ok(()) } async fn call_bounded( &self, operation: ipc::Operation, timeout: Duration, ) -> Result { let permit = self .lane .clone() .try_acquire_owned() .context("HELPER_CONTROL_BUSY")?; let client = self.clone(); tokio::task::spawn_blocking(move || { let _permit = permit; client.check_pin()?; let call = ipc::Call::new(&client.pin, operation); let reply = ipc::exchange(&client.pin, &call, timeout)?; client.check_pin()?; Ok(reply) }) .await? } fn probe_blocking(&self, state: &Path) -> Result<()> { self.check_pin().context(ipc::Stage::DiscoverPin)?; let pin = &self.pin; let call = ipc::Call::new(pin, ipc::Operation::Probe {}); let reply = ipc::exchange(pin, &call, Duration::from_secs(5))?; if let ipc::ReplyBody::Denied { code } = &reply.body { return Err(ipc::remote_denial(ipc::Stage::ClientReplyBinding, code)); } let ipc::ReplyBody::Probe { clock_qualified, ready, ledger, lock, } = reply.body else { anyhow::bail!("HELPER_PROBE_DENIED"); }; let value = json!({"schema_version":1,"source":"actual_local_service_runtime","agent_process_id":std::process::id(),"agent_service":crate::SERVICE_NAME,"agent_id":pin.binding.agent_id,"asset_id":pin.binding.asset_id,"challenge":reply.challenge,"observed_at":chrono::Utc::now(),"helper_service":ipc::HELPER_SERVICE,"verified_helper_user_sid":pin.helper.user_sid,"verified_helper_service_sid":pin.helper.service_sid,"helper_binary_sha256":reply.helper_binary_sha256,"policy_sha256":reply.policy_sha256,"authenticated_pipe_exchange":true,"client_service_pid_verified_by_helper":true,"ledger_file_id":ledger,"executor_lock_file_id":lock,"helper_clock_qualified":clock_qualified,"helper_ready":ready,"system_capability_advertised":false,"no_jobs":true}); self.check_pin()?; write_current_probe(state, &value).context(ipc::Stage::ClientReport) } /// Pure admission shape only; no capability or qualification is asserted. pub fn supports_system(&self, job: &JobPayload) -> bool { system_shape(job) && self.pin.binding.tenant_id == job.tenant_id && self.pin.binding.asset_id == job.asset_id && self.pin.binding.agent_id == job.agent_id && self.pin.binding.enrollment_generation == job.enrollment_generation && self.pin.binding.assignment_version == job.assignment_version } /// Delegate ONCE. A lost reply is unknown and must be recovered by signed /// Snapshot/Apply, never by resending Execute. A timed-out blocking call /// retains its one lane permit until it actually returns; no replacement. pub async fn delegate( &self, intent: intent::Intent, admit: impl Fn() -> Result<()> + Send + 'static, ) -> Result<()> { let job = self.pin.binding.job(&intent.request.job_bytes)?; ensure!( intent.connection_generation > 0 && self.supports_system(&job), "SYSTEM_TYPED_SERVICE_REQUIRED" ); let timeout = execution_timeout(job.max_runtime_seconds)?; let permit = self .lane .clone() .try_acquire_owned() .context("HELPER_CONTROL_BUSY")?; let client = self.clone(); tokio::time::timeout( timeout, tokio::task::spawn_blocking(move || { let _permit = permit; client.check_pin()?; let mut store = intent::Store::open(true)?; let (retained, _) = store.load(intent.id)?; ensure!( retained.digest()? == intent.digest()?, "SYSTEM_INTENT_CHANGED" ); let phase = store.decide(intent.id, admit().is_ok())?; let operation = match phase { intent::Phase::KnownNoDispatch => ipc::Operation::Abandon { anchor: Box::new(intent.anchor.clone()), request: intent.request.clone(), intent_id: intent.id, intent_sha256: intent.digest()?, }, intent::Phase::MayHaveDispatched => { admit()?; ipc::Operation::Execute { generation: intent.connection_generation, request: intent.request.clone(), } } intent::Phase::Prepared => anyhow::bail!("SYSTEM_INTENT_NOT_DURABLE"), }; let call = ipc::Call::new(&client.pin, operation); let reply = ipc::exchange(&client.pin, &call, timeout)?; client.check_pin()?; let outcome = match reply.body { ipc::ReplyBody::Executed { outcome } | ipc::ReplyBody::Abandoned { outcome } => outcome, _ => anyhow::bail!("SYSTEM_HELPER_DELEGATION_DENIED"), }; checked_outcome(&job, &outcome)?; // A reply is never the consumption/mirror witness. Every outcome, // including a successful reply, requires a fresh raw snapshot. Ok::<_, anyhow::Error>(()) }), ) .await .context("SYSTEM_HELPER_REPLY_UNKNOWN")?? } pub async fn resume_denial(&self, intent: intent::Intent) -> Result<()> { let store = intent::Store::open(false)?; let (retained, phase) = store.load(intent.id)?; ensure!( phase == intent::Phase::KnownNoDispatch && retained.digest()? == intent.digest()?, "SYSTEM_DENIAL_RESUME_BINDING" ); let operation = ipc::Operation::Abandon { anchor: Box::new(intent.anchor.clone()), request: intent.request.clone(), intent_id: intent.id, intent_sha256: intent.digest()?, }; // Receipt is persisted by the runtime before this method. A timeout // cannot release the blocking lane or cause another Abandon this process. let reply = tokio::time::timeout(Duration::from_secs(5), self.call(operation)) .await .context("SYSTEM_ABANDON_REPLY_UNKNOWN")??; ensure!( matches!(reply.body, ipc::ReplyBody::Abandoned { .. }), "SYSTEM_ABANDON_DENIED" ); Ok(()) } pub async fn snapshot(&self, generation: u64, boot: uuid::Uuid) -> Result { let reply = self.call(ipc::Operation::Snapshot { generation }).await?; let ipc::ReplyBody::Snapshot { snapshot } = reply.body else { anyhow::bail!("HELPER_SNAPSHOT_DENIED"); }; ensure!(snapshot.boot_id == boot, "HELPER_BOOT_MISMATCH"); Ok(ControlSnapshot { raw: snapshot, no_start_anchor: None, }) } pub async fn apply( &self, response: &SyncResponse, request_bytes: Vec, boot: uuid::Uuid, ) -> Result { let reply = self .call(ipc::Operation::Apply { response: rmm_agent_core::helper_reconcile::SignedResponse { decision_bytes: response.decision_bytes.clone(), signature: response.signature.clone(), }, request_bytes, }) .await?; let ipc::ReplyBody::Applied { snapshot, no_start_anchor, .. } = reply.body else { anyhow::bail!("HELPER_APPLY_DENIED"); }; ensure!(snapshot.boot_id == boot, "HELPER_BOOT_MISMATCH"); if let Some(anchor) = &no_start_anchor { ensure!( anchor.journal_id() == snapshot.journal_id && anchor.checkpoint() == snapshot.checkpoint && Some(anchor.decision_id()) == snapshot.previous_decision_id && anchor.boot_id() == boot, "SYSTEM_ANCHOR_SNAPSHOT_BINDING" ); } Ok(ControlSnapshot { raw: snapshot, no_start_anchor: no_start_anchor.map(|a| *a), }) } } fn verified_mirror_row( row: &rmm_agent_core::helper_reconcile::LocalAttempt, job: &JobPayload, permit: &rmm_domain::jobs::ExecutionPermitPayload, request: &Request, boot: uuid::Uuid, ) -> Result { use rmm_domain::{ jobs::hash, reconciliation::{ReconciledOutcome, canonical_outcome_bytes}, }; ensure!( row.job_id == job.job_id && row.attempt_id == job.attempt_id && row.job_payload_hash == permit.job_payload_hash && row.grant_id == permit.grant_id && row.authorization_id == permit.authorization_id && row.plan_hash == permit.plan_hash && row.action == permit.action && row.execution_identity == "system" && row.original_boot_id == boot && row.original_request_sha256 == hash(&serde_json::to_vec(request)?) && row.consumption == "consumed" && !row.outcome_bytes.is_empty(), "SYSTEM_MIRROR_ORIGINAL_TUPLE" ); let canonical: ReconciledOutcome = serde_json::from_slice(&row.outcome_bytes)?; ensure!( canonical_outcome_bytes(&canonical)? == row.outcome_bytes && hash(&row.outcome_bytes) == row.outcome_sha256 && canonical.state == row.state, "SYSTEM_MIRROR_CANONICAL_OUTCOME" ); let outcome: Outcome = serde_json::from_slice(&row.outcome_bytes)?; checked_outcome(job, &outcome)?; Ok(outcome) } fn system_shape(job: &JobPayload) -> bool { if job.action.full_maintenance() { return job.execution_identity == "system" && job.action.validate() && job.action.valid_execution_identity("system") && job .action .valid_job_limits(job.max_runtime_seconds, job.max_output_bytes); } if job.action.windows_msi().is_some() { return job.execution_identity == "system" && job.action.validate() && job .action .valid_job_limits(job.max_runtime_seconds, job.max_output_bytes); } job.execution_identity == "system" && (1..=120).contains(&job.max_runtime_seconds) && (1..=65536).contains(&job.max_output_bytes) && matches!(&job.action,Action::SetServiceState{unit,state} if unit.starts_with("RmmDiscoveryFixture")&&unit.len()>"RmmDiscoveryFixture".len()&&unit.len()<=80&&unit.bytes().all(|b|b.is_ascii_alphanumeric()||b"_-".contains(&b))&&matches!(state.as_str(),"running"|"stopped")) } fn execution_timeout(seconds: u32) -> Result { ensure!( (1..=120).contains(&seconds), "SYSTEM_EXECUTION_TIMEOUT_BOUND" ); Ok(Duration::from_secs(u64::from(seconds) + 5)) } pub(super) fn checked_outcome(job: &JobPayload, outcome: &Outcome) -> Result<()> { ensure!( matches!( outcome.state.as_str(), "succeeded" | "failed" | "cancelled" | "expired" | "unknown" ) && (job.action.windows_msi().is_some() || !outcome.reboot_required) && outcome .stdout .len() .checked_add(outcome.stderr.len()) .is_some_and(|n| n <= job.max_output_bytes as usize), "SYSTEM_EXECUTE_OUTCOME_SCOPE" ); if outcome.state == "succeeded" { if let Some(m) = job.action.windows_msi() { let e = &outcome.evidence; let after: crate::package::Snapshot = serde_json::from_value(e["after"].clone())?; let noop = e["already_desired"] == true; ensure!( job.action.validate() && e["provider"] == "windows.msi.fixture/1" && e["recipe_sha256"] == m.recipe_sha256 && e["artifact_sha256"] == m.recipe.artifact.sha256 && e["postconditions_passed"] == true && e["state"] == "succeeded" && e["exit_code"] == serde_json::to_value(outcome.exit_code)? && e["already_desired"].is_boolean() && !outcome.output_truncated && e["reboot_initiated"] == false && e["automatic_retry"] == false && after.desired(m), "SYSTEM_MSI_POSTCONDITION_BINDING" ); if noop { let before: crate::package::Snapshot = serde_json::from_value(e["before"].clone())?; ensure!( outcome.exit_code.is_none() && !outcome.reboot_required && e["installer_process_started"] == false && e["transaction_started"] == false && e["installer_reboot_required"].is_null() && before.desired(m), "SYSTEM_MSI_NOOP_BINDING" ); } else { ensure!( matches!(outcome.exit_code, Some(0 | 3010)) && e["installer_process_started"] == true && outcome.reboot_required == (outcome.exit_code == Some(3010)) && e["installer_reboot_required"] == outcome.reboot_required, "SYSTEM_MSI_EXIT_BINDING" ); } return Ok(()); } if job.action.full_maintenance() { let Action::RunScript { script_utf8, expected_stdout, windows_execution_profile, .. } = &job.action else { anyhow::bail!("SYSTEM_SCRIPT_REQUIRED") }; let e = &outcome.evidence; ensure!( system_shape(job) && outcome.exit_code == Some(0) && !outcome.output_truncated && !outcome.reboot_required && e["postconditions_passed"] == true && e["privileged_script_profile"] == "full_maintenance_v1" && e["execution_sid"] == "S-1-5-18" && e["script_sha256"] == rmm_domain::jobs::hash(script_utf8.as_bytes()) && expected_stdout .as_ref() .is_none_or(|s| outcome.stdout == s.as_bytes()), "SYSTEM_SCRIPT_POSTCONDITION_BINDING" ); if windows_execution_profile.is_some() { ensure!( e["windows_execution_profile"] == "powershell_51_remote_signed" && e["execution_policy_requested"] == "RemoteSigned" && e["execution_policy_scope"] == "process", "SYSTEM_SCRIPT_PROCESS_PROFILE_BINDING" ); } return Ok(()); } let Action::SetServiceState { unit, state } = &job.action else { anyhow::bail!("SYSTEM_TYPED_SERVICE_REQUIRED"); }; let wanted = if state == "running" { 4 } else { 1 }; ensure!( outcome.exit_code == Some(0) && !outcome.output_truncated && outcome.evidence["postconditions_passed"] == true && outcome.evidence["provider"] == "windows.scm/1" && outcome.evidence["service"] == unit.as_str() && outcome.evidence["requested_state"] == wanted && outcome.evidence["final_status"]["state"] == wanted, "SYSTEM_SERVICE_POSTCONDITION_BINDING" ); } Ok(()) } pub fn map_snapshot(s: &Snapshot) -> HelperSnapshot { HelperSnapshot { journal_id: s.journal_id, checkpoint: s.checkpoint, previous_decision_id: s.previous_decision_id, attempts: s .attempts .iter() .map(|a| SyncAttempt { update_handoff_bytes: a.update_handoff_bytes.clone(), job_id: a.job_id.to_string(), attempt_id: a.attempt_id.to_string(), job_payload_hash: a.job_payload_hash.clone(), grant_id: a.grant_id.to_string(), consumption: a.consumption.clone(), state: a.state.clone(), revision: a.revision, original_boot_id: a.original_boot_id.to_string(), outcome_sha256: a.outcome_sha256.clone(), outcome_bytes: a.outcome_bytes.clone(), ..Default::default() }) .collect(), } } #[cfg(test)] mod script_tests { use super::*; #[test] fn system_script_success_requires_exact_profile_identity_bytes_and_raw_output() { let mut job = msi_test_job(); job.action = Action::RunScript { interpreter: "powershell".into(), script_utf8: "Write-Output 'hi'\r\n".into(), arguments: vec![], expected_stdout: Some("hi\r\n".into()), windows_execution_profile: Some( rmm_domain::jobs::WindowsExecutionProfile::PowerShell51RemoteSigned, ), privileged_script_profile: Some( rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1, ), }; assert!(system_shape(&job)); let mut outcome = Outcome { state: "succeeded".into(), stdout: b"hi\r\n".to_vec(), stderr: vec![], exit_code: Some(0), output_truncated: false, reboot_required: false, error_code: String::new(), evidence: json!({"postconditions_passed":true,"privileged_script_profile":"full_maintenance_v1","execution_sid":"S-1-5-18","script_sha256":rmm_domain::jobs::hash(b"Write-Output 'hi'\r\n"),"windows_execution_profile":"powershell_51_remote_signed","execution_policy_requested":"RemoteSigned","execution_policy_scope":"process"}), }; checked_outcome(&job, &outcome).unwrap(); outcome.evidence["execution_sid"] = "S-1-5-19".into(); assert!(checked_outcome(&job, &outcome).is_err()); outcome.evidence["execution_sid"] = "S-1-5-18".into(); outcome.stdout = b"other".to_vec(); assert!(checked_outcome(&job, &outcome).is_err()); outcome.state = "unknown".into(); outcome.evidence = serde_json::Value::Null; checked_outcome(&job, &outcome).unwrap(); job.execution_identity = "root".into(); assert!(!system_shape(&job)); } } #[cfg(test)] pub(crate) fn msi_test_job() -> JobPayload { use rmm_domain::windows_execution::*; let recipe:WindowsMsiRecipe=serde_json::from_value(json!({"schema_version":1,"recipe_id":MSI_RECIPE_ID,"recipe_version":"1","platform":"windows","upgrade_code":MSI_UPGRADE_CODE,"architecture":"x64","context":"machine","command_profile":"fixture_quiet_no_reboot_v1","artifact":{"artifact_id":uuid::Uuid::from_u128(10),"sha256":"ab".repeat(32),"bytes":32768},"postcondition":{"product_code":MSI_PRODUCT_CODE,"product_version":MSI_VERSION,"payload_path":MSI_PAYLOAD,"payload_sha256":MSI_PAYLOAD_10_SHA256,"payload_bytes":33},"no_reboot":true})).unwrap(); let manifest = ResolvedWindowsMsi { recipe_sha256: recipe.sha256().unwrap(), recipe, }; let now = chrono::Utc::now(); let id = uuid::Uuid::from_u128(1); JobPayload { schema_version: 1, tenant_id: id, asset_id: id, agent_id: id, enrollment_generation: 1, assignment_version: 1, job_id: id, attempt_id: id, action: Action::EnsurePackage { provider: "msi".into(), package: MSI_PACKAGE_ID.into(), version: MSI_VERSION.into(), architecture: "x64".into(), recipe_version: "1".into(), installation_context: "machine".into(), recipe_id: Some(MSI_RECIPE_ID.into()), apt_manifest: None, windows_msi_manifest: Some(Box::new(manifest)), }, execution_identity: "system".into(), not_before: now, start_before: now + chrono::Duration::minutes(2), max_runtime_seconds: 30, max_output_bytes: 4096, } } fn write_current_probe(state: &Path, value: &serde_json::Value) -> Result<()> { write_report(state, PROBE_FILE, ".helper-probe.pending", value) } /// A historical observation by the agent. The helper lane calls this only after /// the authenticated peer has acknowledged its own signature verification. pub fn record_verified_time( state: &Path, request: &rmm_time_attestation::Request, response_sha256: &str, observed_at: chrono::DateTime, ) -> Result<()> { use sha2::{Digest, Sha256}; let (filename, pending) = match request.context.role { rmm_time_attestation::Role::Agent => ("agent-time-sample.json", ".agent-time.pending"), rmm_time_attestation::Role::SystemHelper => { ("helper-time-sample.json", ".helper-time.pending") } }; let value = json!({ "schema_version": 1, "agent_pid": std::process::id(), "observed_at": observed_at, "role": request.context.role, "windows_boot_id": request.context.windows_boot_id, "connection_generation": request.context.connection_generation, "verifier_incarnation": request.context.verifier_incarnation, "request_sha256": format!("{:x}", Sha256::digest(serde_json::to_vec(request)?)), "response_sha256": response_sha256 }); write_report(state, filename, pending, &value) } fn write_report(state: &Path, name: &str, pending: &str, value: &serde_json::Value) -> Result<()> { native::private_path(state, true)?; let path = state.join(name); if path.try_exists()? { native::private_path(&path, false)?; } let bytes = serde_json::to_vec(value)?; ensure!(bytes.len() <= 8192, "HELPER_PROBE_REPORT_LIMIT"); // One fixed create-only staging file bounds even interrupted-report state. // A leftover from a killed process is refused; it is never overwritten. let temporary = state.join(pending); let mut file = std::fs::OpenOptions::new() .write(true) .create_new(true) .open(&temporary)?; let written = (|| { native::private_path(&temporary, false)?; file.write_all(&bytes)?; file.sync_all()?; Ok::<_, anyhow::Error>(()) })(); drop(file); let result = written.and_then(|()| { std::fs::rename(&temporary, &path)?; native::private_path(&path, false) }); if result.is_err() { // Only our successfully create_new-opened staging file is eligible. let _ = std::fs::remove_file(&temporary); } result } #[cfg(test)] mod tests { use super::*; #[test] fn msi_scope_requires_bound_independent_postconditions_and_exact_noop_or_installer_exit() { let job = msi_test_job(); assert!(system_shape(&job)); let m = job.action.windows_msi().unwrap(); let p = &m.recipe.postcondition; let snapshot = crate::package::Snapshot { product_code: p.product_code.clone(), related_products: vec![p.product_code.clone()], product_state: Some("5".into()), product_version: Some(p.product_version.clone()), payload_sha256: Some(p.payload_sha256.clone()), payload_bytes: Some(p.payload_bytes), ..Default::default() }; let mut out = Outcome { state: "succeeded".into(), exit_code: Some(3010), reboot_required: true, evidence: json!({"provider":"windows.msi.fixture/1","recipe_sha256":m.recipe_sha256,"artifact_sha256":m.recipe.artifact.sha256,"postconditions_passed":true,"reboot_initiated":false,"automatic_retry":false,"already_desired":false,"state":"succeeded","exit_code":3010,"installer_process_started":true,"installer_reboot_required":true,"after":snapshot,"before":snapshot}), ..Outcome::unknown("") }; assert!(checked_outcome(&job, &out).is_ok()); out.reboot_required = false; assert!(checked_outcome(&job, &out).is_err()); out.reboot_required = true; out.evidence["after"]["payload_sha256"] = "cd".repeat(32).into(); assert!(checked_outcome(&job, &out).is_err()); out.evidence["after"] = serde_json::to_value(&snapshot).unwrap(); out.evidence["already_desired"] = true.into(); out.evidence["exit_code"] = serde_json::Value::Null; out.exit_code = None; out.reboot_required = false; out.evidence["installer_reboot_required"] = serde_json::Value::Null; out.evidence["installer_process_started"] = false.into(); out.evidence["transaction_started"] = false.into(); assert!(checked_outcome(&job, &out).is_ok()); out.exit_code = Some(0); assert!(checked_outcome(&job, &out).is_err()); out.state = "unknown".into(); out.reboot_required = true; out.exit_code = Some(1641); assert!(checked_outcome(&job, &out).is_ok()); } #[test] fn system_route_binds_original_request_shape_budget_and_reply_scope() { let id = uuid::Uuid::new_v4(); let now = chrono::Utc::now(); let mut job = JobPayload { schema_version: 1, tenant_id: id, asset_id: id, agent_id: id, enrollment_generation: 1, assignment_version: 1, job_id: id, attempt_id: id, action: Action::SetServiceState { unit: "RmmDiscoveryFixtureService".into(), state: "running".into(), }, execution_identity: "system".into(), not_before: now, start_before: now + chrono::Duration::seconds(60), max_runtime_seconds: 30, max_output_bytes: 1024, }; assert!(system_shape(&job)); for identity in ["root", "agent_service"] { job.execution_identity = identity.into(); assert!(!system_shape(&job)); } job.execution_identity = "system".into(); job.action = Action::SetServiceState { unit: "RmmDiscoveryFixtureService".into(), state: "restarted".into(), }; assert!(!system_shape(&job)); job.action = Action::SetServiceState { unit: "RmmDiscoveryWindows".into(), state: "stopped".into(), }; assert!(!system_shape(&job)); assert_eq!(execution_timeout(120).unwrap(), Duration::from_secs(125)); assert!(execution_timeout(0).is_err()); assert!(execution_timeout(121).is_err()); let mut outcome = Outcome::unknown("LOST_REPLY"); assert!(checked_outcome(&job, &outcome).is_ok()); outcome.reboot_required = true; assert!(checked_outcome(&job, &outcome).is_err()); outcome.reboot_required = false; outcome.stdout = vec![0; 1025]; assert!(checked_outcome(&job, &outcome).is_err()); job.action = Action::SetServiceState { unit: "RmmDiscoveryFixtureService".into(), state: "running".into(), }; outcome.stdout.clear(); outcome.state = "succeeded".into(); outcome.exit_code = Some(0); assert!(checked_outcome(&job, &outcome).is_err()); outcome.evidence = json!({"postconditions_passed":true,"provider":"windows.scm/1","service":"RmmDiscoveryFixtureService","requested_state":4,"final_status":{"state":4}}); assert!(checked_outcome(&job, &outcome).is_ok()); outcome.evidence["final_status"]["state"] = json!(1); assert!(checked_outcome(&job, &outcome).is_err()); let request = Request { job_bytes: vec![b' ', b'{', b'}', b'\n'], permit_bytes: vec![0, 1, 2, 255], signature: vec![7; 64], plan_hash: "ab".repeat(32), authorization_id: id, }; let operation = ipc::Operation::Execute { generation: 73, request: request.clone(), }; let ipc::Operation::Execute { generation, request: retained, } = serde_json::from_slice(&serde_json::to_vec(&operation).unwrap()).unwrap() else { panic!("typed execute required") }; assert_eq!(generation, 73); assert_eq!( serde_json::to_vec(&retained).unwrap(), serde_json::to_vec(&request).unwrap() ); // Pure mirror-binding negatives, not a signature/OS authentication proof. let permit = rmm_domain::jobs::ExecutionPermitPayload { agent_update_plan_id: None, domain: "rmm.execution-permit".into(), schema_version: 1, grant_id: id, authorization_id: id, tenant_id: id, asset_id: id, agent_id: id, enrollment_generation: 1, assignment_version: 1, job_id: id, attempt_id: id, plan_hash: request.plan_hash.clone(), job_payload_hash: rmm_domain::jobs::hash(&request.job_bytes), action: "set_service_state".into(), execution_identity: "system".into(), not_before: now, start_before: now + chrono::Duration::seconds(60), max_runtime_seconds: 30, key_id: "cd".repeat(32), }; let canonical: rmm_domain::reconciliation::ReconciledOutcome = serde_json::from_value( serde_json::to_value(Outcome::unknown("RETAINED_UNKNOWN")).unwrap(), ) .unwrap(); let bytes = rmm_domain::reconciliation::canonical_outcome_bytes(&canonical).unwrap(); let row = rmm_agent_core::helper_reconcile::LocalAttempt { update_handoff_bytes: Vec::new(), job_id: id, attempt_id: id, job_payload_hash: permit.job_payload_hash.clone(), grant_id: id, authorization_id: id, plan_hash: permit.plan_hash.clone(), action: permit.action.clone(), execution_identity: "system".into(), revision: 1, original_boot_id: id, consumption: "consumed".into(), state: "unknown".into(), outcome_sha256: rmm_domain::jobs::hash(&bytes), outcome_bytes: bytes, original_request_sha256: rmm_domain::jobs::hash(&serde_json::to_vec(&request).unwrap()), }; assert!(verified_mirror_row(&row, &job, &permit, &request, id).is_ok()); for field in [ "authorization_id", "original_request_sha256", "original_boot_id", "outcome_sha256", ] { let mut changed = serde_json::to_value(&row).unwrap(); changed[field] = if field.ends_with("sha256") { json!("ef".repeat(32)) } else { json!(uuid::Uuid::new_v4()) }; let changed = serde_json::from_value(changed).unwrap(); assert!( verified_mirror_row(&changed, &job, &permit, &request, id).is_err(), "{field}" ); } } }