From 1b8acf06ea84883771a89d6aec7482588c560cf0 Mon Sep 17 00:00:00 2001 From: Kevin Janssen Date: Sun, 15 Nov 2026 23:50:29 +0100 Subject: [PATCH] Bind the simulated Windows echo review to one persistent job scope --- crates/domain/src/lib.rs | 1 + crates/domain/src/windows_echo_probe.rs | 167 ++++++ crates/server/src/main.rs | 2 + .../server/src/windows_checkpoint_review.rs | 94 +++- crates/server/src/windows_echo_probe.rs | 518 ++++++++++++++++++ docs/windows-profile-acceptance.md | 17 + migrations/0018_windows_echo_probe.sql | 121 ++++ tests/windows_checkpoint_review_database.py | 6 +- 8 files changed, 915 insertions(+), 11 deletions(-) create mode 100644 crates/domain/src/windows_echo_probe.rs create mode 100644 crates/server/src/windows_echo_probe.rs create mode 100644 migrations/0018_windows_echo_probe.sql diff --git a/crates/domain/src/lib.rs b/crates/domain/src/lib.rs index 7484ea0..5210b6d 100644 --- a/crates/domain/src/lib.rs +++ b/crates/domain/src/lib.rs @@ -6,6 +6,7 @@ pub mod checkpoint_repair; pub mod inventory_document; pub mod jobs; pub mod reconciliation; +pub mod windows_echo_probe; pub mod windows_execution; pub mod windows_sync_history; diff --git a/crates/domain/src/windows_echo_probe.rs b/crates/domain/src/windows_echo_probe.rs new file mode 100644 index 0000000..8b8f88c --- /dev/null +++ b/crates/domain/src/windows_echo_probe.rs @@ -0,0 +1,167 @@ +//! One LocalService echo on the named Windows development guest. +use crate::{ + checkpoint_repair::inventory_sha256, + jobs::{Action, JobPayload, PlanPayload, WindowsExecutionProfile, encode, hash}, +}; +use chrono::{DateTime, Duration, Utc}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use uuid::Uuid; + +pub const DOMAIN: &str = "rmm.dev.windows-echo-probe.v1"; +pub const SCRIPT: &str = "Write-Output 'Zeitprofil-Test'\r\n"; +pub const OUTPUT: &str = "Zeitprofil-Test\r\n"; +pub const AGENT: Uuid = Uuid::from_u128(0x63ea15b20643403db5b4cba1288dbea3); +pub const ASSET: Uuid = Uuid::from_u128(0xa176520e8a914e93a78b8e7620f430e0); +pub const TENANT: Uuid = Uuid::from_u128(0x11111111111141118111111111111111); +pub const TEST_PRINCIPAL: &str = "simulated-testprincipal-a"; + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct ProbeScope { + pub tenant_id: Uuid, + pub asset_id: Uuid, + pub agent_id: Uuid, + pub operation_id: Uuid, + pub plan_id: Uuid, + pub plan_hash: String, + pub job_id: Uuid, + pub attempt_id: Uuid, + pub job_payload_hash: String, + pub script_sha256: String, + pub enrollment_generation: u64, + pub assignment_version: u64, + pub execution_identity: String, + pub max_runtime_seconds: u32, + pub max_output_bytes: u32, + pub not_before: DateTime, + pub start_before: DateTime, +} + +fn fixed_job(p: &JobPayload) -> bool { + p.schema_version == 1 + && (p.tenant_id, p.asset_id, p.agent_id) == (TENANT, ASSET, AGENT) + && (p.enrollment_generation, p.assignment_version) == (1, 1) + && p.execution_identity == "agent_service" + && !p.job_id.is_nil() + && !p.attempt_id.is_nil() + && p.job_id != p.attempt_id + && (p.max_runtime_seconds, p.max_output_bytes) == (60, 65536) + && p.not_before < p.start_before + && p.start_before - p.not_before <= Duration::minutes(15) + && matches!(&p.action, Action::RunScript { + interpreter, script_utf8, arguments, expected_stdout: Some(output), + windows_execution_profile: Some(WindowsExecutionProfile::PowerShell51RemoteSigned), + privileged_script_profile: None, + } if interpreter=="powershell" && script_utf8==SCRIPT && arguments.is_empty() && output==OUTPUT) +} + +impl ProbeScope { + pub fn from_plan(plan: &PlanPayload, operation_id: Uuid) -> Option { + let [job] = plan.jobs.as_slice() else { + return None; + }; + let p = &job.payload; + if plan.schema_version != 1 + || plan.tenant_id != TENANT + || plan.plan_id.is_nil() + || operation_id.is_nil() + || plan.principal != format!("automation:{TENANT}") + || (plan.max_parallel, plan.halt_after_failures) != (1, 1) + || !plan.recipe_references.is_empty() + || !plan.artifact_references.is_empty() + || !fixed_job(p) + || hash(&encode(p).ok()?) != job.job_payload_hash + || job.script_sha256.as_deref() != Some(hash(SCRIPT.as_bytes()).as_str()) + { + return None; + } + Some(Self { + tenant_id: p.tenant_id, + asset_id: p.asset_id, + agent_id: p.agent_id, + operation_id, + plan_id: plan.plan_id, + plan_hash: hash(&encode(plan).ok()?), + job_id: p.job_id, + attempt_id: p.attempt_id, + job_payload_hash: job.job_payload_hash.clone(), + script_sha256: hash(SCRIPT.as_bytes()), + enrollment_generation: p.enrollment_generation, + assignment_version: p.assignment_version, + execution_identity: p.execution_identity.clone(), + max_runtime_seconds: p.max_runtime_seconds, + max_output_bytes: p.max_output_bytes, + not_before: p.not_before, + start_before: p.start_before, + }) + } + pub fn matches_job(&self, p: &JobPayload) -> bool { + fixed_job(p) + && !self.operation_id.is_nil() + && !self.plan_id.is_nil() + && self.plan_hash.len() == 64 + && self + .plan_hash + .bytes() + .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) + && (self.tenant_id, self.asset_id, self.agent_id) + == (p.tenant_id, p.asset_id, p.agent_id) + && (self.enrollment_generation, self.assignment_version) + == (p.enrollment_generation, p.assignment_version) + && (self.job_id, self.attempt_id) == (p.job_id, p.attempt_id) + && self.execution_identity == p.execution_identity + && (self.max_runtime_seconds, self.max_output_bytes) + == (p.max_runtime_seconds, p.max_output_bytes) + && (self.not_before, self.start_before) == (p.not_before, p.start_before) + && self.script_sha256 == hash(SCRIPT.as_bytes()) + && encode(p).is_ok_and(|b| hash(&b) == self.job_payload_hash) + } + pub fn digest(&self) -> Option { + inventory_sha256(&serde_json::to_value(self).ok()?).ok() + } +} +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ProbeReceipt { + pub domain: String, + pub schema_version: u32, + pub request_id: Uuid, + pub receipt_id: Uuid, + pub witness: Value, + pub witness_sha256: String, + pub scope: ProbeScope, + pub scope_sha256: String, + pub job_payload_bytes: Vec, + pub key_id: String, + pub issued_at: DateTime, + pub valid_until: DateTime, + pub confirmed_by: String, + pub approval_origin: String, + pub testsimulation: bool, +} +impl ProbeReceipt { + /// The caller separately verifies the signature and installed, immutable scope. + pub fn matches_reviewed_witness(&self, expected: &Value, now: DateTime) -> bool { + self.domain == DOMAIN + && self.schema_version == 1 + && !self.request_id.is_nil() + && !self.receipt_id.is_nil() + && self.request_id != self.receipt_id + && &self.witness == expected + && self.key_id == expected["verification_key_id"] + && inventory_sha256(expected).is_ok_and(|v| v == self.witness_sha256) + && self.testsimulation + && self.approval_origin == "dev_test_browser_simulation" + && self.confirmed_by == TEST_PRINCIPAL + && self.issued_at <= now + && now < self.valid_until + && self.valid_until <= self.scope.start_before + && self.valid_until - self.issued_at <= Duration::minutes(10) + && self.scope.digest().as_deref() == Some(&self.scope_sha256) + && hash(&self.job_payload_bytes) == self.scope.job_payload_hash + && serde_json::from_slice::(&self.job_payload_bytes).is_ok_and(|j| { + self.scope.matches_job(&j) && encode(&j).is_ok_and(|b| b == self.job_payload_bytes) + }) + } +} diff --git a/crates/server/src/main.rs b/crates/server/src/main.rs index c7f28d8..2297cf4 100644 --- a/crates/server/src/main.rs +++ b/crates/server/src/main.rs @@ -27,6 +27,7 @@ mod synchronization; mod tls; mod update_artifact_store; mod windows_checkpoint_review; +mod windows_echo_probe; mod windows_msi_catalog; mod windows_policy; @@ -185,6 +186,7 @@ async fn main() -> Result<()> { if dev { routes = routes.route("/auth/dev/login", post(auth::login)); routes = windows_checkpoint_review::routes(routes); + routes = windows_echo_probe::routes(routes); } routes = routes .route("/auth/config", get(auth::configuration)) diff --git a/crates/server/src/windows_checkpoint_review.rs b/crates/server/src/windows_checkpoint_review.rs index 7a34690..f577be2 100644 --- a/crates/server/src/windows_checkpoint_review.rs +++ b/crates/server/src/windows_checkpoint_review.rs @@ -27,8 +27,8 @@ type Result = std::result::Result; const CASE_AGENT: Uuid = Uuid::from_u128(0x63ea15b20643403db5b4cba1288dbea3); const CASE_ASSET: Uuid = Uuid::from_u128(0xa176520e8a914e93a78b8e7620f430e0); const CASE_TENANT: Uuid = Uuid::from_u128(0x11111111111141118111111111111111); -const FIRST: Uuid = Uuid::from_u128(0xb6a3101f68ad41c8be4e4c7c2bc963d6); -const DENIED: Uuid = Uuid::from_u128(0x0633a4de7e524e5da2a159fb134817fe); +pub(super) const FIRST: Uuid = Uuid::from_u128(0xb6a3101f68ad41c8be4e4c7c2bc963d6); +pub(super) const DENIED: Uuid = Uuid::from_u128(0x0633a4de7e524e5da2a159fb134817fe); const CERTIFICATE: &str = "c55aa8214cb8d60382fe453bddd56c6e46fa79b61ccefda502e001be56bb5075"; fn changed() -> Error { @@ -54,7 +54,12 @@ pub fn routes(r: Router) -> Router { get(download), ) } -async fn access(s: &crate::State, h: &HeaderMap, t: Uuid, write: bool) -> Result { +pub(super) async fn access( + s: &crate::State, + h: &HeaderMap, + t: Uuid, + write: bool, +) -> Result { let p = s .auth .principal(s, h, write) @@ -181,6 +186,23 @@ async fn verify_case( s: &crate::State, w: &Value, promoted: bool, +) -> Result<()> { + verify_case_state(tx, s, w, promoted, false).await +} +pub(super) async fn verify_probe_case( + tx: &mut Transaction<'_, Postgres>, + s: &crate::State, + w: &Value, + promoted: bool, +) -> Result<()> { + verify_case_state(tx, s, w, promoted, true).await +} +async fn verify_case_state( + tx: &mut Transaction<'_, Postgres>, + s: &crate::State, + w: &Value, + promoted: bool, + probe: bool, ) -> Result<()> { crate::agent_service::control_lock(tx, CASE_TENANT, CASE_AGENT).await?; let dev=sqlx::query("SELECT asset_id,certificate_sha256,enrollment_generation,assignment_version,connection_generation,connection_boot_id,capabilities,revoked_at IS NULL AS active,restore_blocked,sequence_regressed,sync_recovery_required,sync_required @@ -201,8 +223,36 @@ async fn verify_case( || !dev.get::("restore_blocked") || dev.get::("sequence_regressed") || dev.get::("sync_recovery_required") - || dev.get::("sync_required") - || caps != ["agent.update/1", "heartbeat/1", "windows.base/1"] + || if probe { + !dev.get::("sync_required") + || ![ + "windows.base/1", + "windows.echo-probe/1", + "run_script", + "rmm.sync.v1", + "script.powershell/1", + "script.powershell.process_remote_signed/1", + ] + .iter() + .all(|k| caps.iter().any(|c| c == k)) + || caps.iter().any(|k| { + ![ + "windows.base/1", + "windows.echo-probe/1", + "run_script", + "rmm.sync.v1", + "script.powershell/1", + "script.powershell.process_remote_signed/1", + "heartbeat/1", + "agent.update/1", + "refresh_inventory", + ] + .contains(&k.as_str()) + }) + } else { + dev.get::("sync_required") + || caps != ["agent.update/1", "heartbeat/1", "windows.base/1"] + } { return Err(changed()); } @@ -441,13 +491,21 @@ mod tests { } } - #[tokio::test] - #[ignore = "requires a fresh isolated PostgreSQL database"] - async fn isolated_windows_checkpoint_human_review() { - let admin = sqlx::PgPool::connect(&std::env::var("RMM_TEST_REPAIR_ADMIN_URL").unwrap()) + async fn fixture( + admin_var: &str, + app_var: &str, + ) -> ( + sqlx::PgPool, + crate::State, + Principal, + Value, + Uuid, + std::path::PathBuf, + ) { + let admin = sqlx::PgPool::connect(&std::env::var(admin_var).unwrap()) .await .unwrap(); - let pool = sqlx::PgPool::connect(&std::env::var("RMM_TEST_REPAIR_APP_URL").unwrap()) + let pool = sqlx::PgPool::connect(&std::env::var(app_var).unwrap()) .await .unwrap(); rmm_persistence::verify_application_role(&pool) @@ -529,6 +587,22 @@ mod tests { .bind(CASE_TENANT).bind(&p.name).execute(&admin).await.unwrap(); sqlx::query("INSERT INTO windows_checkpoint_reviews(tenant_id,request_id,asset_id,agent_id,witness,witness_sha256,requested_by) VALUES($1,$2,$3,$4,$5,$6,'fixture-submitter')") .bind(CASE_TENANT).bind(request).bind(CASE_ASSET).bind(CASE_AGENT).bind(&w).bind(&digest).execute(&admin).await.unwrap(); + (admin, s, p, w, request, tmp) + } + #[tokio::test] + #[ignore = "requires a fresh isolated PostgreSQL database"] + async fn isolated_windows_echo_scope() { + let (admin, s, p, w, _, tmp) = + fixture("RMM_TEST_ECHO_ADMIN_URL", "RMM_TEST_ECHO_APP_URL").await; + crate::windows_echo_probe::test_fixed_echo(&admin, &s, p, w).await; + std::fs::remove_dir_all(tmp).unwrap(); + } + #[tokio::test] + #[ignore = "requires a fresh isolated PostgreSQL database"] + async fn isolated_windows_checkpoint_human_review() { + let (admin, s, p, w, request, tmp) = + fixture("RMM_TEST_REPAIR_ADMIN_URL", "RMM_TEST_REPAIR_APP_URL").await; + let digest = inventory_sha256(&w).unwrap(); let confirmation = || Confirmation { reviewed: true, witness_sha256: digest.clone(), diff --git a/crates/server/src/windows_echo_probe.rs b/crates/server/src/windows_echo_probe.rs new file mode 100644 index 0000000..ffeed98 --- /dev/null +++ b/crates/server/src/windows_echo_probe.rs @@ -0,0 +1,518 @@ +//! Bind the development checkpoint intervention to a single immutable LocalService echo. +//! The scope outlives its signed transport receipt and is also enforced by PostgreSQL. +use crate::{ + auth::Principal, + jobs::Error, + windows_checkpoint_review::{access, verify_probe_case}, +}; +use axum::{ + Json, Router, + extract::{Path, State}, + http::{HeaderMap, StatusCode}, + routing::{get, post}, +}; +use chrono::{DateTime, Duration, Utc}; +use openssl::{ + pkey::{Id, PKey}, + sign::Verifier, +}; +use rmm_domain::{ + checkpoint_repair::{SignedReceipt, inventory_sha256}, + jobs::{PlanPayload, encode, hash}, + windows_echo_probe::{AGENT, ASSET, DOMAIN, ProbeReceipt, ProbeScope, TENANT, TEST_PRINCIPAL}, + windows_sync_history::case_witness, +}; +use serde::Deserialize; +use serde_json::{Value, json}; +use sqlx::{Postgres, Row, Transaction}; +use uuid::Uuid; + +type Result = std::result::Result; +fn mismatch() -> Error { + Error(StatusCode::CONFLICT, "WINDOWS_ECHO_SCOPE_MISMATCH") +} +fn forbidden() -> Error { + Error(StatusCode::FORBIDDEN, "DEV_TEST_WEBUI_REQUIRED") +} +fn missing() -> Error { + Error(StatusCode::NOT_FOUND, "NOT_FOUND") +} +pub fn routes(r: Router) -> Router { + r.route( + "/api/v1/tenants/{tenant}/windows-echo-probe/{operation}", + get(read), + ) + .route( + "/api/v1/tenants/{tenant}/windows-echo-probe/{operation}/confirm", + post(confirm), + ) + .route( + "/api/v1/tenants/{tenant}/windows-echo-probe/{operation}/receipt", + get(download), + ) +} +fn browser(p: &Principal) -> Result<&str> { + if p.name != TEST_PRINCIPAL + || p.tenant != TENANT + || !p.testsimulation + || !p.operator + || p.identity.is_some() + || p.scopes.is_some() + || p.csrf.is_none() + { + return Err(forbidden()); + } + p.session_hash.as_deref().ok_or_else(forbidden) +} +async fn reviewer(tx: &mut Transaction<'_, Postgres>, p: &Principal) -> Result<()> { + browser(p)?; + let allowed: bool = sqlx::query_scalar("SELECT lock_windows_echo_probe_reviewer()") + .fetch_one(&mut **tx) + .await?; + if !allowed { + return Err(forbidden()); + } + Ok(()) +} + +struct Review { + scope: ProbeScope, + raw_job: Vec, + request_id: Uuid, + witness: Value, + witness_hash: String, + scope_hash: String, + existing: Option<(Uuid, DateTime, SignedReceipt)>, +} +impl Review { + fn view(&self) -> Value { + json!({"scope":self.scope,"scope_sha256":self.scope_hash,"witness_sha256":self.witness_hash,"witness":self.witness, + "receipt_id":self.existing.as_ref().map(|r|r.0),"valid_until":self.existing.as_ref().map(|r|r.1)}) + } +} +async fn review( + tx: &mut Transaction<'_, Postgres>, + s: &crate::State, + op: Uuid, + expected: &Value, +) -> Result { + // Same control lock ordering as jobs and checkpoint recovery. + crate::agent_service::control_lock(tx, TENANT, AGENT).await?; + let r = sqlx::query( + "SELECT o.payload,o.plan_hash,a.approval_state,w.request_id,w.witness,w.witness_sha256 + FROM approval_requests a JOIN operation_plans o USING(tenant_id,plan_id) + JOIN windows_checkpoint_reviews w ON w.tenant_id=a.tenant_id AND w.agent_id=$3 + WHERE a.tenant_id=$1 AND a.operation_id=$2 FOR UPDATE OF a", + ) + .bind(TENANT) + .bind(op) + .bind(AGENT) + .fetch_optional(&mut **tx) + .await? + .ok_or_else(missing)?; + if r.get::("approval_state") != "pending_approval" { + return Err(mismatch()); + } + let plan_bytes: Vec = r.get("payload"); + let plan: PlanPayload = serde_json::from_slice(&plan_bytes)?; + let scope = ProbeScope::from_plan(&plan, op).ok_or_else(mismatch)?; + if scope.plan_hash != r.get::("plan_hash") + || hash(&plan_bytes) != scope.plan_hash + || scope.start_before <= Utc::now() + { + return Err(mismatch()); + } + let witness: Value = r.get("witness"); + let witness_hash = inventory_sha256(&witness)?; + if &witness != expected || witness_hash != r.get::("witness_sha256") { + return Err(mismatch()); + } + let scope_hash = scope.digest().ok_or_else(mismatch)?; + let stored=sqlx::query("SELECT operation_id,receipt_id,valid_until,receipt,signature FROM windows_echo_probe_scopes WHERE tenant_id=$1") + .bind(TENANT).fetch_optional(&mut **tx).await?; + let mut existing = None; + if let Some(old) = stored { + if old.get::("operation_id") != op { + return Err(mismatch()); + } + let signed = SignedReceipt { + payload: old.get("receipt"), + signature: old.get("signature"), + }; + let receipt: ProbeReceipt = serde_json::from_slice(&signed.payload)?; + let key = PKey::public_key_from_raw_bytes(&s.job_signer.public_key()?, Id::ED25519) + .map_err(|_| mismatch())?; + if !Verifier::new_without_digest(&key) + .map_err(|_| mismatch())? + .verify_oneshot(&signed.signature, &signed.payload) + .map_err(|_| mismatch())? + || !receipt.matches_reviewed_witness(expected, Utc::now()) + || receipt.scope != scope + || receipt.receipt_id != old.get::("receipt_id") + || receipt.request_id != r.get::("request_id") + || receipt.valid_until.timestamp_micros() + != old + .get::, _>("valid_until") + .timestamp_micros() + { + return Err(mismatch()); + } + existing = Some((receipt.receipt_id, receipt.valid_until, signed)); + } + verify_probe_case(tx, s, &witness, existing.is_some()).await?; + Ok(Review { + raw_job: encode(&plan.jobs[0].payload)?, + scope, + scope_hash, + request_id: r.get("request_id"), + witness, + witness_hash, + existing, + }) +} +async fn read( + State(s): State, + Path((tenant, op)): Path<(Uuid, Uuid)>, + h: HeaderMap, +) -> Result> { + let p = access(&s, &h, tenant, false).await?; + let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?; + crate::permissions::require_principal(&mut tx, &p, "operations:read").await?; + let info = review(&mut tx, &s, op, &case_witness()).await?.view(); + tx.commit().await?; + Ok(Json(info)) +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Confirmation { + reviewed: bool, + scope_sha256: String, + witness_sha256: String, +} +async fn confirm( + State(s): State, + Path((tenant, op)): Path<(Uuid, Uuid)>, + h: HeaderMap, + Json(input): Json, +) -> Result> { + let p = access(&s, &h, tenant, true).await?; + confirm_review(&s, &p, op, input, &case_witness()).await +} +async fn confirm_review( + s: &crate::State, + p: &Principal, + op: Uuid, + input: Confirmation, + expected: &Value, +) -> Result> { + let session = browser(p)?; + if !input.reviewed { + return Err(Error(StatusCode::BAD_REQUEST, "REVIEW_REQUIRED")); + } + let mut tx = rmm_persistence::tenant_tx(&s.pool, p.tenant).await?; + reviewer(&mut tx, p).await?; + let mut r = review(&mut tx, s, op, expected).await?; + if input.scope_sha256 != r.scope_hash || input.witness_sha256 != r.witness_hash { + return Err(mismatch()); + } + if r.existing.is_none() { + let now = Utc::now(); + let receipt = ProbeReceipt { + domain: DOMAIN.into(), + schema_version: 1, + request_id: r.request_id, + receipt_id: Uuid::new_v4(), + witness: r.witness.clone(), + witness_sha256: r.witness_hash.clone(), + scope: r.scope.clone(), + scope_sha256: r.scope_hash.clone(), + job_payload_bytes: r.raw_job.clone(), + key_id: s.job_signer.key_id.clone(), + issued_at: now, + valid_until: std::cmp::min(now + Duration::minutes(10), r.scope.start_before), + confirmed_by: p.name.clone(), + approval_origin: p.approval_origin().into(), + testsimulation: true, + }; + if !receipt.matches_reviewed_witness(expected, now) { + return Err(mismatch()); + } + let raw = serde_json::to_vec(&receipt)?; + let signed = SignedReceipt { + signature: s.job_signer.sign(&raw)?, + payload: raw, + }; + sqlx::query("INSERT INTO windows_echo_probe_scopes(tenant_id,asset_id,agent_id,operation_id,plan_id,plan_hash,job_id,attempt_id,job_bytes,job_hash,request_id,receipt_id,receipt,signature,confirmed_by,session_hash,issued_at,valid_until) + VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18)") + .bind(TENANT).bind(ASSET).bind(AGENT).bind(op).bind(r.scope.plan_id).bind(&r.scope.plan_hash).bind(r.scope.job_id).bind(r.scope.attempt_id) + .bind(&r.raw_job).bind(&r.scope.job_payload_hash).bind(r.request_id).bind(receipt.receipt_id).bind(&signed.payload).bind(&signed.signature) + .bind(&p.name).bind(session).bind(now).bind(receipt.valid_until).execute(&mut *tx).await?; + // Only after installing the immutable scope in the same transaction. + if sqlx::query("UPDATE agent_sync_state SET checkpoint=6756,decision_id=$4 WHERE tenant_id=$1 AND agent_id=$2 AND checkpoint=6755 AND decision_id=$3 AND helper_checkpoint=1") + .bind(TENANT).bind(AGENT).bind(crate::windows_checkpoint_review::FIRST).bind(crate::windows_checkpoint_review::DENIED) + .execute(&mut *tx).await?.rows_affected()!=1{return Err(mismatch());} + sqlx::query("INSERT INTO audit_events(tenant_id,event_id,principal,event_type,data) VALUES($1,$2,$3,'windows_echo_probe_scoped',$4)") + .bind(TENANT).bind(receipt.receipt_id).bind(&p.name).bind(json!({"scope":r.scope,"scope_sha256":r.scope_hash, + "receipt_sha256":hash(&signed.payload),"request_id":r.request_id,"witness_sha256":r.witness_hash, + "approval_origin":p.approval_origin(),"testsimulation":true})).execute(&mut *tx).await?; + r.existing = Some((receipt.receipt_id, receipt.valid_until, signed)); + } + tx.commit().await?; + Ok(Json(r.view())) +} +async fn download( + State(s): State, + Path((tenant, op)): Path<(Uuid, Uuid)>, + h: HeaderMap, +) -> Result> { + let p = access(&s, &h, tenant, false).await?; + let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?; + reviewer(&mut tx, &p).await?; + let r = review(&mut tx, &s, op, &case_witness()) + .await? + .existing + .ok_or_else(missing)?; + tx.commit().await?; + Ok(Json(r.2)) +} + +#[cfg(test)] +pub(super) async fn test_fixed_echo( + admin: &sqlx::PgPool, + s: &crate::State, + mut p: Principal, + w: Value, +) { + use rmm_domain::{ + jobs::{Action, JobPayload, PlannedJob, WindowsExecutionProfile}, + windows_echo_probe::{OUTPUT, SCRIPT}, + }; + p.name = TEST_PRINCIPAL.into(); + p.testsimulation = true; + p.identity = None; + let op = Uuid::new_v4(); + let now = Utc::now(); + let job = JobPayload { + schema_version: 1, + tenant_id: TENANT, + asset_id: ASSET, + agent_id: AGENT, + enrollment_generation: 1, + assignment_version: 1, + job_id: Uuid::new_v4(), + attempt_id: Uuid::new_v4(), + action: Action::RunScript { + interpreter: "powershell".into(), + script_utf8: SCRIPT.into(), + arguments: vec![], + expected_stdout: Some(OUTPUT.into()), + windows_execution_profile: Some(WindowsExecutionProfile::PowerShell51RemoteSigned), + privileged_script_profile: None, + }, + execution_identity: "agent_service".into(), + not_before: now, + start_before: now + Duration::minutes(15), + max_runtime_seconds: 60, + max_output_bytes: 65536, + }; + let raw = encode(&job).unwrap(); + let mut plan = PlanPayload { + schema_version: 1, + tenant_id: TENANT, + plan_id: Uuid::new_v4(), + principal: format!("automation:{TENANT}"), + reason: "Echo fixture".into(), + jobs: vec![PlannedJob { + payload: job.clone(), + job_payload_hash: hash(&raw), + script_sha256: Some(hash(SCRIPT.as_bytes())), + }], + max_parallel: 1, + halt_after_failures: 1, + recipe_references: vec![], + artifact_references: vec![], + }; + let scope = ProbeScope::from_plan(&plan, op).unwrap(); + for field in [ + "execution_identity", + "script", + "args", + "attempt", + "duplicate", + "output", + ] { + let mut other = plan.clone(); + let j = &mut other.jobs[0].payload; + match field { + "execution_identity" => j.execution_identity = "system".into(), + "attempt" => j.attempt_id = Uuid::new_v4(), + "output" => j.max_output_bytes += 1, + "script" | "args" => { + if let Action::RunScript { + arguments, + script_utf8, + .. + } = &mut j.action + { + if field == "args" { + arguments.push("extra".into()); + } else { + *script_utf8 = "Write-Output 'anderer Test'".into(); + } + } + } + _ => {} + } + other.jobs[0].job_payload_hash = hash(&encode(&other.jobs[0].payload).unwrap()); + if field == "duplicate" { + other.jobs.push(other.jobs[0].clone()); + } + if field != "attempt" { + assert!(ProbeScope::from_plan(&other, op).is_none()); + } + if field != "duplicate" { + assert!(!scope.matches_job(&other.jobs[0].payload)); + } + } + let bytes = encode(&plan).unwrap(); + sqlx::query("INSERT INTO operation_plans(tenant_id,plan_id,principal,payload,plan_hash,expires_at) VALUES($1,$2,$3,$4,$5,$6)") + .bind(TENANT).bind(plan.plan_id).bind(&plan.principal).bind(&bytes).bind(&scope.plan_hash).bind(job.start_before).execute(admin).await.unwrap(); + sqlx::query("INSERT INTO approval_requests(tenant_id,operation_id,plan_id,principal,idempotency_key,request_hash) VALUES($1,$2,$3,$4,'echo','synthetic')") + .bind(TENANT).bind(op).bind(plan.plan_id).bind(&plan.principal).execute(admin).await.unwrap(); + sqlx::query( + "UPDATE agent_installations SET sync_required=true,capabilities=$1 WHERE agent_id=$2", + ) + .bind(json!([ + "windows.base/1", + "heartbeat/1", + "windows.echo-probe/1", + "script.powershell/1", + "run_script", + "rmm.sync.v1", + "script.powershell.process_remote_signed/1" + ])) + .bind(AGENT) + .execute(admin) + .await + .unwrap(); + let input = || Confirmation { + reviewed: true, + witness_sha256: inventory_sha256(&w).unwrap(), + scope_sha256: scope.digest().unwrap(), + }; + let mut wrong = input(); + wrong.scope_sha256 = "00".repeat(32); + assert_eq!( + confirm_review(s, &p, op, wrong, &w).await.unwrap_err().1, + "WINDOWS_ECHO_SCOPE_MISMATCH" + ); + let mut bearer = p.clone(); + bearer.session_hash = None; + assert_eq!( + confirm_review(s, &bearer, op, input(), &w) + .await + .unwrap_err() + .0, + StatusCode::FORBIDDEN + ); + let first = confirm_review(s, &p, op, input(), &w).await.unwrap().0; + assert_eq!(first["scope_sha256"], scope.digest().unwrap()); + assert_eq!( + confirm_review(s, &p, op, input(), &w).await.unwrap().0, + first + ); + let state:(bool,bool,bool)=sqlx::query_as("SELECT restore_blocked,sync_ready,helper_sync_ready FROM agent_installations WHERE agent_id=$1").bind(AGENT).fetch_one(admin).await.unwrap(); + assert_eq!(state, (true, false, false)); + let count:i64=sqlx::query_scalar("SELECT (SELECT count(*) FROM jobs)+(SELECT count(*) FROM authorizations)+(SELECT count(*) FROM execution_permits)").fetch_one(admin).await.unwrap(); + assert_eq!(count, 0); + // Even a former server binary with table-level INSERT reaches the persistent trigger. + let authorization = Uuid::new_v4(); + sqlx::query("INSERT INTO authorizations(tenant_id,authorization_id,operation_id,plan_id,plan_hash,principal,session_hash,approval_origin,testsimulation,policy_version) VALUES($1,$2,$3,$4,$5,$6,$7,'dev_test_browser_simulation',true,1)") + .bind(TENANT).bind(authorization).bind(op).bind(plan.plan_id).bind(&scope.plan_hash).bind(TEST_PRINCIPAL).bind("aa".repeat(32)).execute(admin).await.unwrap(); + sqlx::query("INSERT INTO operations VALUES($1,$2,$3)") + .bind(TENANT) + .bind(op) + .bind(authorization) + .execute(admin) + .await + .unwrap(); + let insert = "INSERT INTO jobs(tenant_id,job_id,attempt_id,operation_id,agent_id,asset_id,payload,payload_hash,resource) VALUES($1,$2,$3,$4,$5,$6,$7,$8,'script')"; + plan.jobs[0].payload.execution_identity = "system".into(); + let alternate = encode(&plan.jobs[0].payload).unwrap(); + let err = sqlx::query(insert) + .bind(TENANT) + .bind(job.job_id) + .bind(job.attempt_id) + .bind(op) + .bind(AGENT) + .bind(ASSET) + .bind(&alternate) + .bind(hash(&alternate)) + .execute(admin) + .await + .unwrap_err(); + assert!(err.to_string().contains("WINDOWS_ECHO_SCOPE_MISMATCH")); + let mut tx = rmm_persistence::tenant_tx(&s.pool, TENANT).await.unwrap(); + sqlx::query(insert) + .bind(TENANT) + .bind(job.job_id) + .bind(job.attempt_id) + .bind(op) + .bind(AGENT) + .bind(ASSET) + .bind(&raw) + .bind(hash(&raw)) + .execute(&mut *tx) + .await + .unwrap(); + sqlx::query("INSERT INTO outbox(tenant_id,job_id,attempt_id) VALUES($1,$2,$3)") + .bind(TENANT) + .bind(job.job_id) + .bind(job.attempt_id) + .execute(&mut *tx) + .await + .unwrap(); + sqlx::query("UPDATE outbox SET lease_until=now()+interval '30 seconds' WHERE job_id=$1") + .bind(job.job_id) + .execute(&mut *tx) + .await + .unwrap(); + tx.commit().await.unwrap(); + let grant = Uuid::new_v4(); + let g = json!({"domain":"rmm.execution-permit","schema_version":1,"grant_id":grant,"authorization_id":authorization, + "tenant_id":TENANT,"asset_id":ASSET,"agent_id":AGENT,"enrollment_generation":1,"assignment_version":1, + "job_id":job.job_id,"attempt_id":job.attempt_id,"plan_hash":scope.plan_hash,"job_payload_hash":scope.job_payload_hash, + "action":"run_script","execution_identity":"agent_service","not_before":now,"start_before":now+Duration::seconds(60), + "max_runtime_seconds":60,"key_id":s.job_signer.key_id}); + let insert_grant = "INSERT INTO execution_permits(tenant_id,grant_id,job_id,attempt_id,payload,signature) VALUES($1,$2,$3,$4,$5,$6)"; + for valid in [false, true] { + let mut g = g.clone(); + if !valid { + g["execution_identity"] = json!("system"); + } + let b = serde_json::to_vec(&g).unwrap(); + let signature = s.job_signer.sign(&b).unwrap(); + let mut tx = rmm_persistence::tenant_tx(&s.pool, TENANT).await.unwrap(); + let result = sqlx::query(insert_grant) + .bind(TENANT) + .bind(grant) + .bind(job.job_id) + .bind(job.attempt_id) + .bind(b) + .bind(signature) + .execute(&mut *tx) + .await; + if valid { + result.unwrap(); + tx.commit().await.unwrap(); + } else { + assert!( + result + .unwrap_err() + .to_string() + .contains("WINDOWS_ECHO_SCOPE_MISMATCH") + ); + tx.rollback().await.unwrap(); + } + } +} diff --git a/docs/windows-profile-acceptance.md b/docs/windows-profile-acceptance.md index 02f0f27..0b0e039 100644 --- a/docs/windows-profile-acceptance.md +++ b/docs/windows-profile-acceptance.md @@ -557,3 +557,20 @@ Cloud-Linux-VM als UID 65534 mit `no_new_privs` und eigenem Netzwerk-Namespace. die erhaltene Historie und die Ablehnung fremder Jobangebote. Ein Test bestand, einer wurde gefiltert, Exit 0 und leeres stderr. Beleg-SHA-256 `54aa6430c0b1eb2415ee3f888b015c05faa536d07d96f4bacf01152f1236b7db`. + +Die getrennte serverseitige Echo-Review-Strecke bestand drei isolierte +PostgreSQL-Fälle einschließlich Migration bis 0018. Sie akzeptierte die +exakten Outbox-/Lease-/Permitdaten des gebundenen LocalService-Auftrags und +wies abweichende SYSTEM-Daten auch über die Datenbankgrenze ab. Unmittelbar +nach der simulierten Review-Bestätigung blieben Jobs, Jobgenehmigungen und +Startpermits null, die normale Restore-Sperre blieb gesetzt. Erst der +reguläre spätere Sync und die separate Jobplangenehmigung sind dafür zuständig. +Server-Clippy einschließlich betroffener Tests bestand mit `-D warnings`. + +Der neue Gasttest bestand danach auf Windows 11 nativ mit einem bestandenen +und einem gefilterten Test in 0,01 Sekunden. Testprogramm-SHA-256 +`ae35c1b9b36683efa9718572d3c6ad3e0321df1226639fa608234a435a787100`. +Die gegenwärtige Mitgliedschaft des vorhandenen simulierten Principals wurde +auf dem Projektserver lesend als `test_human`, nicht widerrufen und mit +`plans:approve` bestätigt. Neue zusätzliche Anmeldedaten sind für diesen +begrenzten Testpfad nicht erforderlich. diff --git a/migrations/0018_windows_echo_probe.sql b/migrations/0018_windows_echo_probe.sql new file mode 100644 index 0000000..4b2329c --- /dev/null +++ b/migrations/0018_windows_echo_probe.sql @@ -0,0 +1,121 @@ +-- This table can narrow one previously blocked guest to one immutable test plan. +-- Its lifetime is independent of the receipt expiry, API process and gateway image. +CREATE TABLE windows_echo_probe_scopes ( + tenant_id uuid PRIMARY KEY CHECK (tenant_id='11111111-1111-4111-8111-111111111111'), + asset_id uuid NOT NULL CHECK (asset_id='a176520e-8a91-4e93-a78b-8e7620f430e0'), + agent_id uuid NOT NULL CHECK (agent_id='63ea15b2-0643-403d-b5b4-cba1288dbea3'), + operation_id uuid NOT NULL, plan_id uuid NOT NULL, plan_hash text NOT NULL, + job_id uuid NOT NULL, attempt_id uuid NOT NULL, + job_bytes bytea NOT NULL, job_hash text NOT NULL CHECK (job_hash=encode(sha256(job_bytes),'hex')), + request_id uuid NOT NULL, receipt_id uuid NOT NULL, + receipt bytea NOT NULL, signature bytea NOT NULL CHECK (octet_length(signature)=64), + confirmed_by text NOT NULL CHECK (confirmed_by='simulated-testprincipal-a'), + session_hash text NOT NULL CHECK (session_hash ~ '^[0-9a-f]{64}$'), + issued_at timestamptz NOT NULL, valid_until timestamptz NOT NULL + CHECK (valid_until>issued_at AND valid_until<=issued_at+interval '10 minutes'), + FOREIGN KEY (tenant_id,plan_id,plan_hash) REFERENCES operation_plans(tenant_id,plan_id,plan_hash), + FOREIGN KEY (tenant_id,operation_id) REFERENCES approval_requests(tenant_id,operation_id), + FOREIGN KEY (tenant_id,request_id) REFERENCES windows_checkpoint_reviews(tenant_id,request_id), + FOREIGN KEY (tenant_id,agent_id) REFERENCES agent_installations(tenant_id,agent_id), + FOREIGN KEY (tenant_id,asset_id) REFERENCES assets(tenant_id,asset_id) +); +ALTER TABLE windows_echo_probe_scopes ENABLE ROW LEVEL SECURITY; +ALTER TABLE windows_echo_probe_scopes FORCE ROW LEVEL SECURITY; +CREATE POLICY tenant_scope ON windows_echo_probe_scopes USING (tenant_id::text=current_setting('app.tenant_id',true)) + WITH CHECK (tenant_id::text=current_setting('app.tenant_id',true)); +GRANT SELECT,INSERT ON windows_echo_probe_scopes TO rmm_app; +CREATE TRIGGER immutable_content BEFORE UPDATE OR DELETE ON windows_echo_probe_scopes + FOR EACH ROW EXECUTE FUNCTION immutable_plan(); + +CREATE FUNCTION check_windows_echo_probe_scope() RETURNS trigger LANGUAGE plpgsql +SET search_path=pg_catalog,public AS $$ +DECLARE p jsonb; r record; a jsonb; +BEGIN + SELECT ar.plan_id,ar.approval_state,op.payload AS plan INTO STRICT r FROM approval_requests ar + JOIN operation_plans op USING(tenant_id,plan_id) + WHERE ar.tenant_id=NEW.tenant_id AND ar.operation_id=NEW.operation_id FOR UPDATE OF ar; + p=convert_from(NEW.job_bytes,'UTF8')::jsonb; + a=jsonb_build_object('action','run_script','interpreter','powershell', + 'script_utf8',E'Write-Output ''Zeitprofil-Test''\r\n','arguments','[]'::jsonb, + 'expected_stdout',E'Zeitprofil-Test\r\n','windows_execution_profile','powershell_51_remote_signed'); + IF r.approval_state!='pending_approval' OR r.plan_id!=NEW.plan_id + OR jsonb_array_length(convert_from(r.plan,'UTF8')::jsonb->'jobs') IS DISTINCT FROM 1 + OR convert_from(r.plan,'UTF8')::jsonb#>'{jobs,0,payload}' IS DISTINCT FROM p + OR p->'action' IS DISTINCT FROM a OR p->>'execution_identity' IS DISTINCT FROM 'agent_service' + OR p->>'max_runtime_seconds' IS DISTINCT FROM '60' OR p->>'max_output_bytes' IS DISTINCT FROM '65536' + OR p->>'agent_id' IS DISTINCT FROM NEW.agent_id::text OR p->>'asset_id' IS DISTINCT FROM NEW.asset_id::text + OR p->>'tenant_id' IS DISTINCT FROM NEW.tenant_id::text OR p->>'job_id' IS DISTINCT FROM NEW.job_id::text + OR p->>'attempt_id' IS DISTINCT FROM NEW.attempt_id::text + OR EXISTS(SELECT FROM jobs WHERE tenant_id=NEW.tenant_id AND (agent_id=NEW.agent_id OR asset_id=NEW.asset_id)) + THEN RAISE EXCEPTION 'WINDOWS_ECHO_SCOPE_MISMATCH'; END IF; + RETURN NEW; +END $$; +CREATE TRIGGER validate_windows_echo_scope BEFORE INSERT ON windows_echo_probe_scopes + FOR EACH ROW EXECUTE FUNCTION check_windows_echo_probe_scope(); + +-- The old gateway reads outbox/permits through foreign keys to immutable job +-- payloads. Blocking every other job row at its creation also protects old code. +CREATE FUNCTION restrict_windows_echo_probe_job() RETURNS trigger LANGUAGE plpgsql +SET search_path=pg_catalog,public AS $$ +DECLARE s windows_echo_probe_scopes%ROWTYPE; +BEGIN + IF NEW.tenant_id='11111111-1111-4111-8111-111111111111' AND + (NEW.agent_id='63ea15b2-0643-403d-b5b4-cba1288dbea3' OR NEW.asset_id='a176520e-8a91-4e93-a78b-8e7620f430e0') THEN + SELECT * INTO s FROM windows_echo_probe_scopes WHERE tenant_id=NEW.tenant_id; + IF FOUND AND (s.operation_id,s.job_id,s.attempt_id,s.agent_id,s.asset_id,s.job_hash,s.job_bytes) + IS DISTINCT FROM (NEW.operation_id,NEW.job_id,NEW.attempt_id,NEW.agent_id,NEW.asset_id,NEW.payload_hash,NEW.payload) + THEN RAISE EXCEPTION 'WINDOWS_ECHO_SCOPE_MISMATCH'; END IF; + END IF; + RETURN NEW; +END $$; +CREATE TRIGGER restrict_windows_echo_job BEFORE INSERT OR UPDATE OF payload,payload_hash,job_id,attempt_id,agent_id,asset_id,operation_id,tenant_id ON jobs + FOR EACH ROW EXECUTE FUNCTION restrict_windows_echo_probe_job(); + +CREATE FUNCTION lock_windows_echo_probe_reviewer() RETURNS boolean LANGUAGE sql SECURITY DEFINER +SET search_path=pg_catalog,public AS $$ + SELECT EXISTS(SELECT FROM public.memberships WHERE tenant_id='11111111-1111-4111-8111-111111111111' + AND tenant_id::text=current_setting('app.tenant_id',true) AND principal='simulated-testprincipal-a' + AND kind='test_human' AND revoked_at IS NULL AND 'plans:approve'=ANY(permissions) FOR SHARE); +$$; +REVOKE ALL ON FUNCTION lock_windows_echo_probe_reviewer() FROM PUBLIC; +GRANT EXECUTE ON FUNCTION lock_windows_echo_probe_reviewer() TO rmm_app; + +-- Outbox leases and permit persistence traverse this guard on both current +-- and earlier gateway binaries, in their existing authorization transaction. +CREATE FUNCTION restrict_windows_echo_delivery() RETURNS trigger LANGUAGE plpgsql +SET search_path=pg_catalog,public AS $$ +DECLARE s windows_echo_probe_scopes%ROWTYPE; j jobs%ROWTYPE; approval authorizations%ROWTYPE; g jsonb; payload jsonb; +BEGIN + IF NEW.tenant_id!='11111111-1111-4111-8111-111111111111' THEN RETURN NEW; END IF; + SELECT * INTO s FROM windows_echo_probe_scopes WHERE tenant_id=NEW.tenant_id; + IF NOT FOUND THEN RETURN NEW; END IF; + SELECT * INTO STRICT j FROM jobs WHERE tenant_id=NEW.tenant_id AND job_id=NEW.job_id AND attempt_id=NEW.attempt_id; + IF j.agent_id!=s.agent_id AND j.asset_id!=s.asset_id THEN RETURN NEW; END IF; + SELECT * INTO STRICT approval FROM authorizations WHERE tenant_id=NEW.tenant_id AND operation_id=s.operation_id; + IF (s.operation_id,s.job_id,s.attempt_id,s.agent_id,s.asset_id,s.job_hash,s.job_bytes) + IS DISTINCT FROM (j.operation_id,j.job_id,j.attempt_id,j.agent_id,j.asset_id,j.payload_hash,j.payload) + OR (approval.plan_hash,approval.plan_id,approval.principal,approval.approval_origin,approval.testsimulation) + IS DISTINCT FROM (s.plan_hash,s.plan_id,'simulated-testprincipal-a'::text,'dev_test_browser_simulation'::text,true) + OR approval.revoked_at IS NOT NULL + THEN RAISE EXCEPTION 'WINDOWS_ECHO_SCOPE_MISMATCH'; END IF; + IF TG_TABLE_NAME='execution_permits' THEN + g=convert_from(NEW.payload,'UTF8')::jsonb; + payload=convert_from(j.payload,'UTF8')::jsonb; + IF (g->>'grant_id',g->>'job_id',g->>'attempt_id',g->>'agent_id',g->>'asset_id',g->>'tenant_id',g->>'plan_hash',g->>'job_payload_hash',g->>'authorization_id') + IS DISTINCT FROM (NEW.grant_id::text,s.job_id::text,s.attempt_id::text,s.agent_id::text,s.asset_id::text,s.tenant_id::text,s.plan_hash,s.job_hash,approval.authorization_id::text) + OR g->>'domain' IS DISTINCT FROM 'rmm.execution-permit' OR g->>'schema_version' IS DISTINCT FROM '1' + OR g->>'action' IS DISTINCT FROM 'run_script' OR g->>'execution_identity' IS DISTINCT FROM 'agent_service' + OR g->>'enrollment_generation' IS DISTINCT FROM '1' OR g->>'assignment_version' IS DISTINCT FROM '1' + OR g->>'max_runtime_seconds' IS DISTINCT FROM '60' OR g->>'not_before' IS NULL OR g->>'start_before' IS NULL + OR (g->>'not_before')::timestamptz < (payload->>'not_before')::timestamptz + OR (g->>'start_before')::timestamptz > (payload->>'start_before')::timestamptz + OR (g->>'start_before')::timestamptz <= (g->>'not_before')::timestamptz + OR (g->>'start_before')::timestamptz > (g->>'not_before')::timestamptz + interval '60 seconds' + THEN RAISE EXCEPTION 'WINDOWS_ECHO_SCOPE_MISMATCH'; END IF; + END IF; + RETURN NEW; +END $$; +CREATE TRIGGER restrict_windows_echo_offer BEFORE INSERT OR UPDATE OF lease_until ON outbox + FOR EACH ROW EXECUTE FUNCTION restrict_windows_echo_delivery(); +CREATE TRIGGER restrict_windows_echo_permit BEFORE INSERT ON execution_permits + FOR EACH ROW EXECUTE FUNCTION restrict_windows_echo_delivery(); diff --git a/tests/windows_checkpoint_review_database.py b/tests/windows_checkpoint_review_database.py index 56137d8..d2feb96 100644 --- a/tests/windows_checkpoint_review_database.py +++ b/tests/windows_checkpoint_review_database.py @@ -44,16 +44,20 @@ def main(): raise RuntimeError('Existing record lost during recovery migration') if sql("SELECT count(*) FROM memberships WHERE 'recovery:confirm'=ANY(permissions);").strip() != b'0': raise RuntimeError('Migration implicitly granted human recovery permission') + # Both modes need the same observed identity and independent original head. + sql('CREATE DATABASE rmm_echo TEMPLATE postgres;') output=command(['docker','run','--rm','--network','container:'+NAME, '--read-only','--tmpfs','/tmp:rw,size=512m','-v',str(ROOT)+':/src:ro', '-v',str(ROOT/'devstate/windows-server-contract/target')+':/target','-e','CARGO_TARGET_DIR=/target', '-e','RMM_TEST_REPAIR_ADMIN_URL=postgres://postgres@127.0.0.1/postgres', + '-e','RMM_TEST_ECHO_ADMIN_URL=postgres://postgres@127.0.0.1/rmm_echo', + '-e','RMM_TEST_ECHO_APP_URL=postgres://rmm_app@127.0.0.1/rmm_echo', '-e','RMM_TEST_REPAIR_APP_URL=postgres://rmm_app@127.0.0.1/postgres', '--entrypoint','cargo','rust-discovery-windows-tls-full:local', 'test','--locked','--offline','-p','rmm-server','windows_checkpoint_review::tests', '--','--include-ignored','--nocapture'],timeout=300) print(output.decode()) - print('PASS isolated synthetic human review, signed denial checkpoint, denial of simulated principals, idempotence and zero jobs/permits.') + print('PASS isolated human review and dev echo scope, signed receipts, idempotence, fixed job/offer/permit and rejection of alternate execution identities.') finally: subprocess.run(['docker','rm','-f',NAME],capture_output=True)