Deploy scoped SYSTEM nonstart review and record preserved native rollback
Rust development slice / linux (push) Failing after 7s

This commit is contained in:
2026-11-16 17:46:54 +01:00
parent ee88b4fe64
commit fe483a1570
15 changed files with 1802 additions and 3 deletions
+2
View File
@@ -85,3 +85,5 @@ mod tests {
assert!(!ServerRole::Gateway.api());
}
}
pub mod windows_system_nonstart;
@@ -0,0 +1,235 @@
//! Exact reviewed SYSTEM nonstart/grant and connection221 closure; no job authority.
use crate::{
checkpoint_repair::{SignedDecision, inventory_sha256},
jobs::hash,
windows_echo_probe::{AGENT, ASSET, TENANT, TEST_PRINCIPAL},
};
use chrono::{DateTime, Duration, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
pub const DOMAIN: &str = "rmm.dev.windows-system-nonstart-221.v1";
pub const FIRST: Uuid = Uuid::from_u128(0x193b951ba3aa46e29f481a57f315078e);
pub const SECOND: Uuid = Uuid::from_u128(0x0442c73282264c2596157f007e24b269);
pub const FIRST_REQUEST: Uuid = Uuid::from_u128(0xf07ea08e84f248f484766921057db9af);
pub const SECOND_REQUEST: Uuid = Uuid::from_u128(0x09952f6d45f3433082f387ebf363eb3b);
pub const BOOT: Uuid = Uuid::from_u128(0xa9ad08955a968f2c8fb6cfdc2d5225ea);
pub const JOB: Uuid = Uuid::from_u128(0x940478735088433bbc1b490d3eafe0da);
pub const ATTEMPT: Uuid = Uuid::from_u128(0xf071e6d6863542f792fa533c681edd8b);
pub const GRANT: Uuid = Uuid::from_u128(0x97e705b8fb2b415884d9d90595d1ce6e);
pub const UNKNOWN_SHA256: &str = "1f284b66578d61c4364cc0060a67ce9b467e1d661ed8885804391b51a6f18b1a";
pub const HELPER_IMAGE: &str = "0502d6c87bd74c99f1665f3cc4b9d74b8e31d0f829d2ce1a1597d72e9be1e726";
pub const SCRIPT_SOURCE: &str = "a3563e1aa8327b2e7046c7cdfb4f45ac213fec6ff7d477820ea2676a266c1695";
pub const ERROR_CODE: &str = "WINDOWS_SYSTEM_NONSTART_CONFIRMED_221";
pub const MAX_WITNESS_BYTES: usize = 768 * 1024;
pub const FILE_ROLES: [&str; 6] = [
"telemetry",
"consumption",
"agent_lock",
"helper_ledger",
"helper_lock",
"system_intents",
];
pub use crate::windows_sync_alignment::{Counts, NativeFile};
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct Witness {
pub schema_version: u32,
pub tenant_id: Uuid,
pub asset_id: Uuid,
pub agent_id: Uuid,
pub enrollment_generation: u64,
pub assignment_version: u64,
pub boot_id: Uuid,
pub connection_generation: u64,
pub agent_journal_id: Uuid,
pub helper_journal_id: Uuid,
pub agent_checkpoint: u64,
pub helper_checkpoint: u64,
pub agent_last_decision: Uuid,
pub helper_last_decision: Uuid,
pub verification_key_id: String,
pub verification_public_key_hex: String,
pub binding_sha256: String,
pub helper_binding_sha256: String,
pub files: [NativeFile; 6],
pub agent_inventory_sha256: String,
pub consumption_inventory_sha256: String,
pub helper_inventory_sha256: String,
pub intent_inventory_sha256: String,
pub counts: Counts,
pub original_requests: [Vec<u8>; 2],
pub original_responses: [SignedDecision; 2],
pub target_job_offer: Vec<u8>,
pub agent_start: Vec<u8>,
pub helper_start: Vec<u8>,
pub agent_outcome: Vec<u8>,
pub helper_outcome: Vec<u8>,
pub intent: Vec<u8>,
pub nonstart: NonstartProof,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct NonstartProof {
pub helper_pid: u32,
pub helper_birth_filetime: String,
pub helper_image_sha256: String,
pub system_script_source_sha256: String,
pub read_share_error: u32,
pub read_write_share_passed: bool,
pub state_directory_file_id: [u32; 3],
pub evidence_sha256: Vec<String>,
}
impl NonstartProof {
pub fn valid(&self) -> bool {
self.helper_pid == 1304
&& self.helper_birth_filetime == "134393135436289391"
&& self.helper_image_sha256 == HELPER_IMAGE
&& self.system_script_source_sha256 == SCRIPT_SOURCE
&& self.read_share_error == 32
&& self.read_write_share_passed
&& self.state_directory_file_id != [0; 3]
&& !self.evidence_sha256.is_empty()
&& self.evidence_sha256.len() <= 16
&& self
.evidence_sha256
.iter()
.all(|v| crate::agent_update::digest(v))
}
}
impl Witness {
pub fn digest(&self) -> Option<String> {
inventory_sha256(&serde_json::to_value(self).ok()?).ok()
}
pub fn valid(&self) -> bool {
let digest = crate::agent_update::digest;
self.schema_version == 1
&& (self.tenant_id, self.asset_id, self.agent_id) == (TENANT, ASSET, AGENT)
&& self.enrollment_generation == 1
&& self.assignment_version == 1
&& self.boot_id == BOOT
&& self.connection_generation == 221
&& !self.agent_journal_id.is_nil()
&& !self.helper_journal_id.is_nil()
&& self.agent_journal_id != self.helper_journal_id
&& self.agent_checkpoint == 10784
&& self.helper_checkpoint >= 413
&& self.agent_last_decision == SECOND
&& self.helper_last_decision == FIRST
&& [
&self.verification_key_id,
&self.verification_public_key_hex,
&self.binding_sha256,
&self.helper_binding_sha256,
&self.agent_inventory_sha256,
&self.consumption_inventory_sha256,
&self.helper_inventory_sha256,
&self.intent_inventory_sha256,
]
.iter()
.all(|h| digest(h))
&& self.binding_sha256 == self.helper_binding_sha256
&& hex::decode(&self.verification_public_key_hex)
.is_ok_and(|k| hash(&k) == self.verification_key_id)
&& self.files.iter().zip(FILE_ROLES).all(|(f, role)| {
f.role == role
&& match (&f.file_id, &f.sha256) {
(Some(id), Some(h)) => *id != [0; 3] && digest(h),
(None, None) => role == "system_intents",
_ => false,
}
})
&& self.counts
== (Counts {
agent_jobs: 4,
agent_consumed: 3,
agent_starts: 3,
agent_outcomes: 3,
helper_consumed: 1,
helper_starts: 1,
helper_outcomes: 1,
system_intents: 1,
})
&& self
.original_requests
.iter()
.all(|v| !v.is_empty() && v.len() <= 65536)
&& self.original_responses.iter().all(|v| {
!v.decision_bytes.is_empty()
&& v.decision_bytes.len() <= 65536
&& v.signature.len() == 64
})
&& [
&self.target_job_offer,
&self.agent_start,
&self.helper_start,
&self.agent_outcome,
&self.helper_outcome,
&self.intent,
]
.iter()
.all(|v| !v.is_empty() && v.len() <= 131072)
&& hash(&self.agent_outcome) == UNKNOWN_SHA256
&& hash(&self.helper_outcome) == UNKNOWN_SHA256
&& self.nonstart.valid()
&& serde_json::to_vec(self).is_ok_and(|v| v.len() <= MAX_WITNESS_BYTES)
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Receipt {
pub domain: String,
pub schema_version: u32,
pub receipt_id: Uuid,
pub request_id: Uuid,
pub witness: Witness,
pub witness_sha256: String,
pub server_transport_generation: u64,
pub key_id: String,
pub issued_at: DateTime<Utc>,
pub valid_until: DateTime<Utc>,
pub confirmed_by: String,
pub approval_origin: String,
pub testsimulation: bool,
pub ready: bool,
pub helper_ready: bool,
pub unlock: bool,
}
impl Receipt {
pub fn valid(&self, now: DateTime<Utc>) -> bool {
self.domain == DOMAIN
&& self.schema_version == 1
&& !self.receipt_id.is_nil()
&& !self.request_id.is_nil()
&& self.receipt_id != self.request_id
&& self.server_transport_generation >= 221
&& self.witness.valid()
&& self.witness.digest().as_deref() == Some(self.witness_sha256.as_str())
&& self.key_id == self.witness.verification_key_id
&& self.confirmed_by == TEST_PRINCIPAL
&& self.approval_origin == "dev_test_browser_simulation"
&& self.testsimulation
&& !self.ready
&& !self.helper_ready
&& !self.unlock
&& self.issued_at <= now
&& now < self.valid_until
&& self.valid_until > self.issued_at
&& self.valid_until - self.issued_at <= Duration::minutes(5)
}
}
pub fn failed_outcome(
receipt_id: Uuid,
receipt_sha256: &str,
) -> crate::reconciliation::ReconciledOutcome {
crate::reconciliation::ReconciledOutcome {
state: "failed".into(),
stdout: vec![],
stderr: vec![],
exit_code: None,
output_truncated: false,
reboot_required: false,
error_code: ERROR_CODE.into(),
evidence: serde_json::json!({"postconditions_passed":false,"not_started":true,"original_unknown_sha256":UNKNOWN_SHA256,"administrative_receipt_id":receipt_id,"administrative_receipt_sha256":receipt_sha256}),
}
}
+3
View File
@@ -177,6 +177,9 @@ pub async fn event(
"known failure requires structured reason"
);
}
if r.error_code == rmm_domain::windows_system_nonstart::ERROR_CODE {
crate::windows_system_nonstart::validate_result(tx, tenant, agent, r, &evidence).await?;
}
if outcome == JobState::Succeeded {
ensure!(
evidence.get("postconditions_passed") == Some(&json!(true)),
+2
View File
@@ -30,6 +30,7 @@ mod windows_checkpoint_review;
mod windows_echo_probe;
mod windows_echo_completion;
mod windows_sync_alignment;
mod windows_system_nonstart;
mod windows_msi_catalog;
mod windows_policy;
@@ -191,6 +192,7 @@ async fn main() -> Result<()> {
routes = windows_echo_probe::routes(routes);
routes = windows_echo_completion::routes(routes);
routes = windows_sync_alignment::routes(routes);
routes = windows_system_nonstart::routes(routes);
}
routes = routes
.route("/auth/config", get(auth::configuration))
+3
View File
@@ -713,6 +713,9 @@ pub async fn reconcile(
decisions.push(decision);
continue;
}
if job_id == rmm_domain::windows_system_nonstart::JOB && local.state == "failed" {
crate::windows_system_nonstart::reconcile_failed(tx, tenant, agent, local, r, chain_valid && helper_ready).await?;
}
// A free script with no bound postcondition never becomes successful by
// merely asserting a new state after unknown effect.
let manual = server_state == "unknown"
@@ -0,0 +1,735 @@
//! Exact connection-221 interactive administrative closure. No job/readiness writes.
use crate::{auth::Principal, jobs::Error, windows_checkpoint_review::access};
use axum::{
Json, Router,
extract::{Path, State},
http::{HeaderMap, StatusCode},
routing::{get, post},
};
use chrono::{Duration, SubsecRound, Utc};
use openssl::{
pkey::{Id, PKey},
sign::Verifier,
};
use prost::Message;
use rmm_domain::{
checkpoint_repair::{SignedReceipt, inventory_sha256},
jobs::{ExecutionPermitPayload, JobPayload, PlanPayload, encode, hash},
reconciliation::ReconcileDecisionPayload,
windows_echo_probe::{AGENT, ASSET, TENANT, TEST_PRINCIPAL},
windows_system_nonstart::{self as profile, Receipt, Witness},
};
use rmm_protocol::{JobOffer, SyncRequest};
use serde::Deserialize;
use serde_json::{Value, json};
use sqlx::{Postgres, Row, Transaction};
use uuid::Uuid;
type Result<T> = std::result::Result<T, Error>;
fn mismatch() -> Error {
Error(StatusCode::CONFLICT, "WINDOWS_SYSTEM_NONSTART_MISMATCH")
}
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(Error(StatusCode::FORBIDDEN, "DEV_TEST_WEBUI_REQUIRED"));
}
p.session_hash
.as_deref()
.ok_or(Error(StatusCode::FORBIDDEN, "DEV_TEST_WEBUI_REQUIRED"))
}
pub fn routes(r: Router<crate::State>) -> Router<crate::State> {
r.route(
"/api/v1/tenants/{tenant}/windows-system-nonstart-221",
get(read).post(submit),
)
.route(
"/api/v1/tenants/{tenant}/windows-system-nonstart-221/{request}/confirm",
post(confirm),
)
.route(
"/api/v1/tenants/{tenant}/windows-system-nonstart-221/{request}/receipt",
get(download),
)
}
fn verify(s: &crate::State, bytes: &[u8], signature: &[u8]) -> Result<()> {
let key = PKey::public_key_from_raw_bytes(&s.job_signer.public_key()?, Id::ED25519)
.map_err(|_| mismatch())?;
if bytes.len() > profile::MAX_WITNESS_BYTES + 8192
|| signature.len() != 64
|| !Verifier::new_without_digest(&key)
.map_err(|_| mismatch())?
.verify_oneshot(signature, bytes)
.map_err(|_| mismatch())?
{
return Err(mismatch());
}
Ok(())
}
const JOB: Uuid = Uuid::from_u128(0x940478735088433bbc1b490d3eafe0da);
const ATTEMPT: Uuid = Uuid::from_u128(0xf071e6d6863542f792fa533c681edd8b);
const GRANT: Uuid = Uuid::from_u128(0x97e705b8fb2b415884d9d90595d1ce6e);
const FIRST: Uuid = Uuid::from_u128(0x193b951ba3aa46e29f481a57f315078e);
const SECOND: Uuid = Uuid::from_u128(0x0442c73282264c2596157f007e24b269);
const BOOT: Uuid = Uuid::from_u128(0xa9ad08955a968f2c8fb6cfdc2d5225ea);
const UNKNOWN_SHA: &str = "1f284b66578d61c4364cc0060a67ce9b467e1d661ed8885804391b51a6f18b1a";
#[derive(Deserialize, serde::Serialize)]
#[serde(deny_unknown_fields)]
struct OriginalRequest {
job_bytes: Vec<u8>,
permit_bytes: Vec<u8>,
signature: Vec<u8>,
plan_hash: String,
authorization_id: Uuid,
}
fn original(w: &Witness, i: usize) -> Result<(SyncRequest, ReconcileDecisionPayload)> {
let raw = &w.original_requests[i];
let r = SyncRequest::decode(raw.as_slice()).map_err(|_| mismatch())?;
let d: ReconcileDecisionPayload =
serde_json::from_slice(&w.original_responses[i].decision_bytes)?;
let (id, rid, cp, hcp) = if i == 0 {
(
FIRST,
Uuid::from_u128(0xf07ea08e84f248f484766921057db9af),
10783,
412,
)
} else {
(
SECOND,
Uuid::from_u128(0x09952f6d45f3433082f387ebf363eb3b),
10784,
413,
)
};
if r.encode_to_vec() != *raw
|| r.request_id != rid.to_string()
|| r.journal_id != w.agent_journal_id.to_string()
|| r.helper_journal_id != w.helper_journal_id.to_string()
|| r.assignment_version != 1
|| r.checkpoint != cp
|| r.helper_checkpoint != hcp
|| !r.journal_complete
|| (i == 1 && r.previous_decision_id != FIRST.to_string())
|| !d.valid_profile(d.issued_at)
|| d.decision_id != id
|| d.request_id != rid
|| d.request_hash != hash(raw)
|| (d.tenant_id, d.asset_id, d.agent_id) != (TENANT, ASSET, AGENT)
|| d.enrollment_generation != 1
|| d.assignment_version != 1
|| d.boot_id != BOOT
|| d.connection_generation != 221
|| d.journal_id != w.agent_journal_id
|| d.helper_journal_id != Some(w.helper_journal_id)
|| d.checkpoint != cp
|| d.helper_checkpoint != hcp
|| d.key_id != w.verification_key_id
|| !d.attempts.iter().any(|a| {
a.job_id == JOB
&& a.attempt_id == ATTEMPT
&& a.grant_id == Some(GRANT)
&& a.outcome_state == "unknown"
&& !a.unlock
})
|| d.attempts.iter().any(|a| a.update_inflight.is_some())
{
return Err(mismatch());
}
Ok((r, d))
}
async fn validate(
tx: &mut Transaction<'_, Postgres>,
s: &crate::State,
w: &Witness,
expected_transport: Option<i64>,
) -> Result<i64> {
if !w.valid()
|| w.verification_key_id != s.job_signer.key_id
|| hex::encode(s.job_signer.public_key()?) != w.verification_public_key_hex
{
return Err(mismatch());
}
crate::agent_service::control_lock(tx, TENANT, AGENT).await?;
let dev=sqlx::query("SELECT asset_id,enrollment_generation,assignment_version,connection_generation,connection_boot_id,revoked_at,sequence_regressed,sync_recovery_required,restore_blocked FROM agent_installations WHERE tenant_id=$1 AND agent_id=$2 FOR UPDATE").bind(TENANT).bind(AGENT).fetch_one(&mut **tx).await?;
if dev.get::<Uuid, _>("asset_id") != ASSET
|| dev.get::<i64, _>("enrollment_generation") != 1
|| dev.get::<i64, _>("assignment_version") != 1
|| dev.get::<i64, _>("connection_generation") < 221
|| expected_transport.is_some_and(|g| dev.get::<i64, _>("connection_generation") != g)
|| dev.get::<Option<Uuid>, _>("connection_boot_id") != Some(BOOT)
|| dev
.get::<Option<chrono::DateTime<Utc>>, _>("revoked_at")
.is_some()
|| dev.get::<bool, _>("sequence_regressed")
|| dev.get::<bool, _>("sync_recovery_required")
|| !dev.get::<bool, _>("restore_blocked")
{
return Err(mismatch());
}
let state=sqlx::query("SELECT journal_id,checkpoint,decision_id,helper_journal_id,helper_checkpoint FROM agent_sync_state WHERE tenant_id=$1 AND agent_id=$2 FOR SHARE").bind(TENANT).bind(AGENT).fetch_one(&mut **tx).await?;
if state.get::<Uuid, _>("journal_id") != w.agent_journal_id
|| state.get::<i64, _>("checkpoint") != 10784
|| state.get::<Uuid, _>("decision_id") != SECOND
|| state.get::<Option<Uuid>, _>("helper_journal_id") != Some(w.helper_journal_id)
|| state.get::<i64, _>("helper_checkpoint") != 413
{
return Err(mismatch());
}
for i in 0..2 {
let (r, d) = original(w, i)?;
verify(
s,
&w.original_responses[i].decision_bytes,
&w.original_responses[i].signature,
)?;
let row=sqlx::query("SELECT request_hash,journal_id,checkpoint,connection_generation,payload,signature FROM sync_checkpoints WHERE tenant_id=$1 AND agent_id=$2 AND decision_id=$3 AND request_id=$4").bind(TENANT).bind(AGENT).bind(d.decision_id).bind(d.request_id).fetch_one(&mut **tx).await?;
if row.get::<String, _>("request_hash") != hash(&r.encode_to_vec())
|| row.get::<Uuid, _>("journal_id") != w.agent_journal_id
|| row.get::<i64, _>("checkpoint")
!= i64::try_from(d.checkpoint).map_err(|_| mismatch())?
|| row.get::<i64, _>("connection_generation") != 221
|| row.get::<Vec<u8>, _>("payload") != w.original_responses[i].decision_bytes
|| row.get::<Vec<u8>, _>("signature") != w.original_responses[i].signature
{
return Err(mismatch());
}
}
validate_job(tx, s, w).await?;
Ok(dev.get::<i64, _>("connection_generation"))
}
async fn validate_job(
tx: &mut Transaction<'_, Postgres>,
s: &crate::State,
w: &Witness,
) -> Result<()> {
let jobs=sqlx::query("SELECT job_id,attempt_id,state FROM jobs WHERE tenant_id=$1 AND agent_id=$2 ORDER BY job_id FOR SHARE").bind(TENANT).bind(AGENT).fetch_all(&mut **tx).await?;
let expected = [
(
"0a50aae9-a784-4535-b62f-ef24c301d546",
"78295f74-4565-459a-87b0-641a8b95feec",
"expired",
),
(
"5f1ffef4-2bb6-4c7e-a3a0-fb619144b4f8",
"ebb387cf-ebb1-4609-a318-32f44d774d11",
"succeeded",
),
(
"645ad11b-9ecd-4efe-8f92-8ad2fb6ed5cf",
"e2ee25cd-0e23-4c3c-aaa2-3048d232622a",
"succeeded",
),
(
"94047873-5088-433b-bc1b-490d3eafe0da",
"f071e6d6-8635-42f7-92fa-533c681edd8b",
"unknown",
),
];
if jobs.len() != 4
|| jobs.iter().zip(expected).any(|(r, (j, a, state))| {
r.get::<Uuid, _>("job_id").to_string() != j
|| r.get::<Uuid, _>("attempt_id").to_string() != a
|| r.get::<String, _>("state") != state
})
{
return Err(mismatch());
}
let n:i64=sqlx::query_scalar("SELECT count(*) FROM execution_permits p JOIN jobs j ON j.tenant_id=p.tenant_id AND j.job_id=p.job_id WHERE j.tenant_id=$1 AND j.agent_id=$2").bind(TENANT).bind(AGENT).fetch_one(&mut **tx).await?;
if n != 3 {
return Err(mismatch());
}
let row=sqlx::query("SELECT j.operation_id,j.asset_id,j.payload,j.payload_hash,j.start_reserved,j.cancel_requested,j.result,a.authorization_id,p.payload AS plan_payload,p.plan_hash FROM jobs j JOIN authorizations a ON a.tenant_id=j.tenant_id AND a.operation_id=j.operation_id JOIN operation_plans p ON p.tenant_id=a.tenant_id AND p.plan_id=a.plan_id AND p.plan_hash=a.plan_hash WHERE j.tenant_id=$1 AND j.agent_id=$2 AND j.job_id=$3 AND j.attempt_id=$4 AND a.revoked_at IS NULL AND a.principal=$5 AND a.approval_origin='dev_test_browser_simulation' AND a.testsimulation FOR SHARE OF j,a").bind(TENANT).bind(AGENT).bind(JOB).bind(ATTEMPT).bind(TEST_PRINCIPAL).fetch_one(&mut **tx).await?;
let offer = JobOffer::decode(w.target_job_offer.as_slice()).map_err(|_| mismatch())?;
let job: JobPayload = serde_json::from_slice(&offer.payload_bytes)?;
let plan_raw: Vec<u8> = row.get("plan_payload");
let plan: PlanPayload = serde_json::from_slice(&plan_raw)?;
if offer.encode_to_vec() != w.target_job_offer
|| offer.job_id != JOB.to_string()
|| offer.attempt_id != ATTEMPT.to_string()
|| row.get::<Uuid, _>("operation_id") != Uuid::from_u128(0xce1b969b66b24548a28c7e81943507c4)
|| row.get::<Uuid, _>("asset_id") != ASSET
|| !row.get::<bool, _>("start_reserved")
|| row.get::<bool, _>("cancel_requested")
|| row.get::<Vec<u8>, _>("payload") != offer.payload_bytes
|| row.get::<String, _>("payload_hash") != hash(&offer.payload_bytes)
|| offer.job_payload_hash != hash(&offer.payload_bytes)
|| offer.authorization_id != row.get::<Uuid, _>("authorization_id").to_string()
|| offer.plan_hash != row.get::<String, _>("plan_hash")
|| offer.plan_hash != "9afc2bacefd937199bf6407c12b1f7c5cad933cd875514f651afcca9eb9fae43"
|| hash(&plan_raw) != offer.plan_hash
|| encode(&plan)? != plan_raw
|| plan.tenant_id != TENANT
|| plan.jobs.len() != 1
|| plan.jobs[0].payload != job
|| plan.jobs[0].job_payload_hash != offer.job_payload_hash
|| (
job.tenant_id,
job.asset_id,
job.agent_id,
job.job_id,
job.attempt_id,
) != (TENANT, ASSET, AGENT, JOB, ATTEMPT)
|| job.enrollment_generation != 1
|| job.assignment_version != 1
|| job.execution_identity != "system"
{
return Err(mismatch());
}
let rmm_domain::jobs::Action::RunScript { script_utf8, .. } = &job.action else {
return Err(mismatch());
};
if hash(script_utf8.as_bytes())
!= "880930d2b5d903a8ee8f4a9d3acad6162ef994b1822d7381c8468230bcf4a86c"
{
return Err(mismatch());
}
let grant=sqlx::query("SELECT grant_id,payload,signature FROM execution_permits WHERE tenant_id=$1 AND job_id=$2 AND attempt_id=$3").bind(TENANT).bind(JOB).bind(ATTEMPT).fetch_one(&mut **tx).await?;
let raw: Vec<u8> = grant.get("payload");
let signature: Vec<u8> = grant.get("signature");
verify(s, &raw, &signature)?;
let g: ExecutionPermitPayload = serde_json::from_slice(&raw)?;
if g.grant_id != GRANT
|| grant.get::<Uuid, _>("grant_id") != GRANT
|| g.key_id != w.verification_key_id
|| (g.tenant_id, g.asset_id, g.agent_id, g.job_id, g.attempt_id)
!= (TENANT, ASSET, AGENT, JOB, ATTEMPT)
|| g.enrollment_generation != 1
|| g.assignment_version != 1
|| g.execution_identity != "system"
|| g.action != "run_script"
|| g.agent_update_plan_id.is_some()
|| g.job_payload_hash != offer.job_payload_hash
|| g.plan_hash != offer.plan_hash
|| g.authorization_id.to_string() != offer.authorization_id
{
return Err(mismatch());
}
for (start, known) in [
(
&w.agent_start,
"f6134c00143b0939a92d2690b8c3a034d332d47241c65a812dcf8f78ead9cfcc",
),
(
&w.helper_start,
"cf83fc9acbfc1429cca452498c44282f7748d852d73b8221bc0721af60e276d9",
),
] {
let value: Value = serde_json::from_slice(start)?;
let request: OriginalRequest = serde_json::from_value(value["request"].clone())?;
if hash(start) != known
|| hash(&serde_json::to_vec(&request)?)
!= "09aa6be3617017e4169f9d83fbfc4cbef43712513a02229a8360dd6a708ee69c"
|| request.job_bytes != offer.payload_bytes
|| request.permit_bytes != raw
|| request.signature != signature
|| request.plan_hash != offer.plan_hash
|| request.authorization_id != g.authorization_id
{
return Err(mismatch());
}
}
for raw in [&w.agent_outcome, &w.helper_outcome] {
let outcome: Value = serde_json::from_slice(raw)?;
if hash(raw) != UNKNOWN_SHA
|| outcome["state"] != "unknown"
|| outcome["error_code"] != "SYSTEM_SCRIPT_EFFECT_UNRESOLVED"
|| outcome["exit_code"] != Value::Null
|| outcome["stdout"] != json!([])
|| outcome["stderr"] != json!([])
|| outcome["output_truncated"] != false
|| outcome["reboot_required"] != false
|| outcome["evidence"] != json!({"postconditions_passed":false})
{
return Err(mismatch());
}
}
if hash(&w.intent) != "31c9ddc35a7c09de9e8ec75c835e3dca9e8a816bc031b4b1c1396bd3a2ea46df"
|| w.nonstart.helper_pid != 1304
|| w.nonstart.helper_image_sha256
!= "0502d6c87bd74c99f1665f3cc4b9d74b8e31d0f829d2ce1a1597d72e9be1e726"
|| w.nonstart.system_script_source_sha256
!= "a3563e1aa8327b2e7046c7cdfb4f45ac213fec6ff7d477820ea2676a266c1695"
|| w.nonstart.read_share_error != 32
|| !w.nonstart.read_write_share_passed
{
return Err(mismatch());
}
let result: Value = row.get::<Option<Value>, _>("result").ok_or_else(mismatch)?;
if result["grant_id"] != GRANT.to_string()
|| result["stdout"] != json!([])
|| result["stderr"] != json!([])
|| result["exit_code"] != Value::Null
|| result["error_code"] != "SYNC_EFFECT_UNRESOLVED"
|| result["source_id"] != "authoritative_sync"
{
return Err(mismatch());
}
Ok(())
}
async fn stored(tx: &mut Transaction<'_, Postgres>) -> Result<Option<(Uuid, Witness, i64)>> {
let row = sqlx::query(
"SELECT request_id,witness,server_transport_generation FROM windows_system_nonstart_reviews WHERE tenant_id=$1",
)
.bind(TENANT)
.fetch_optional(&mut **tx)
.await?;
row.map(|r| {
Ok((
r.get("request_id"),
serde_json::from_value(r.get("witness"))?,
r.get("server_transport_generation"),
))
})
.transpose()
}
async fn view(tx: &mut Transaction<'_, Postgres>, id: Uuid, w: &Witness) -> Result<Value> {
let row=sqlx::query("SELECT payload FROM windows_system_nonstart_receipts WHERE tenant_id=$1 AND request_id=$2 ORDER BY issued_at DESC,receipt_id DESC LIMIT 1").bind(TENANT).bind(id).fetch_optional(&mut **tx).await?;
let receipt = row
.map(|r| serde_json::from_slice::<Value>(&r.get::<Vec<u8>, _>("payload")))
.transpose()?;
let transport:i64=sqlx::query_scalar("SELECT server_transport_generation FROM windows_system_nonstart_reviews WHERE tenant_id=$1 AND request_id=$2").bind(TENANT).bind(id).fetch_one(&mut **tx).await?;
Ok(
json!({"request_id":id,"witness":w,"witness_sha256":w.digest(),"server_transport_generation":transport,"receipt":receipt}),
)
}
async fn read(
State(s): State<crate::State>,
Path(t): Path<Uuid>,
h: HeaderMap,
) -> Result<Json<Value>> {
let p = access(&s, &h, t, false).await?;
let mut tx = rmm_persistence::tenant_tx(&s.pool, t).await?;
crate::permissions::require_principal(&mut tx, &p, "inventory:read").await?;
let result = if let Some((id, w, transport)) = stored(&mut tx).await? {
validate(&mut tx, &s, &w, Some(transport)).await?;
view(&mut tx, id, &w).await?
} else {
json!({"request_id":null})
};
tx.commit().await?;
Ok(Json(result))
}
async fn submit(
State(s): State<crate::State>,
Path(t): Path<Uuid>,
h: HeaderMap,
Json(w): Json<Witness>,
) -> Result<Json<Value>> {
let p = access(&s, &h, t, true).await?;
browser(&p)?;
let mut tx = rmm_persistence::tenant_tx(&s.pool, t).await?;
crate::permissions::require_principal(&mut tx, &p, "inventory:read").await?;
let transport = validate(&mut tx, &s, &w, None).await?;
let id = if let Some((id, old, old_transport)) = stored(&mut tx).await? {
if old != w || old_transport != transport {
return Err(mismatch());
}
id
} else {
let id = Uuid::new_v4();
let digest = w.digest().ok_or_else(mismatch)?;
sqlx::query("INSERT INTO windows_system_nonstart_reviews(tenant_id,request_id,agent_id,witness,witness_sha256,submitted_by,server_transport_generation) VALUES($1,$2,$3,$4,$5,$6,$7)").bind(t).bind(id).bind(AGENT).bind(serde_json::to_value(&w)?).bind(&digest).bind(&p.name).bind(transport).execute(&mut *tx).await?;
sqlx::query("INSERT INTO audit_events(tenant_id,event_id,principal,event_type,data) VALUES($1,$2,$3,'windows_system_nonstart_submitted',$4)").bind(t).bind(id).bind(&p.name).bind(json!({"witness_sha256":digest,"connection_generation":221,"server_transport_generation":transport,"job_id":JOB,"attempt_id":ATTEMPT,"grant_id":GRANT,"approval_origin":p.approval_origin(),"testsimulation":true,"ready":false,"helper_ready":false,"unlock":false})).execute(&mut *tx).await?;
id
};
let result = view(&mut tx, id, &w).await?;
tx.commit().await?;
Ok(Json(result))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Confirmation {
reviewed: bool,
witness_sha256: String,
}
async fn confirm(
State(s): State<crate::State>,
Path((t, id)): Path<(Uuid, Uuid)>,
h: HeaderMap,
Json(input): Json<Confirmation>,
) -> Result<Json<Value>> {
let p = access(&s, &h, t, true).await?;
let session = browser(&p)?;
if !input.reviewed {
return Err(Error(StatusCode::BAD_REQUEST, "REVIEW_REQUIRED"));
}
let mut tx = rmm_persistence::tenant_tx(&s.pool, t).await?;
let allowed: bool = sqlx::query_scalar("SELECT lock_windows_echo_probe_reviewer()")
.fetch_one(&mut *tx)
.await?;
if !allowed {
return Err(Error(StatusCode::FORBIDDEN, "DEV_TEST_WEBUI_REQUIRED"));
}
let (actual, w, transport) = stored(&mut tx)
.await?
.ok_or(Error(StatusCode::NOT_FOUND, "NOT_FOUND"))?;
if actual != id || w.digest().as_deref() != Some(input.witness_sha256.as_str()) {
return Err(mismatch());
}
validate(&mut tx, &s, &w, Some(transport)).await?;
let now = Utc::now().trunc_subsecs(6);
let original=sqlx::query("SELECT state,revision,result FROM jobs WHERE tenant_id=$1 AND agent_id=$2 AND job_id=$3 AND attempt_id=$4 FOR SHARE").bind(t).bind(AGENT).bind(JOB).bind(ATTEMPT).fetch_one(&mut *tx).await?;
let original_state: String = original.get("state");
let original_revision: i64 = original.get("revision");
let original_result: Value = original
.get::<Option<Value>, _>("result")
.ok_or_else(mismatch)?;
if original_state != "unknown" {
return Err(mismatch());
}
let r = Receipt {
domain: profile::DOMAIN.into(),
schema_version: 1,
receipt_id: Uuid::new_v4(),
request_id: id,
witness: w.clone(),
server_transport_generation: u64::try_from(transport).map_err(|_| mismatch())?,
witness_sha256: input.witness_sha256,
key_id: s.job_signer.key_id.clone(),
issued_at: now,
valid_until: now + Duration::minutes(5),
confirmed_by: p.name.clone(),
approval_origin: p.approval_origin().into(),
testsimulation: true,
ready: false,
helper_ready: false,
unlock: false,
};
if !r.valid(now) {
return Err(mismatch());
}
let payload = serde_json::to_vec(&r)?;
let signature = s.job_signer.sign(&payload)?;
sqlx::query("INSERT INTO windows_system_nonstart_receipts(tenant_id,request_id,receipt_id,witness_sha256,payload,signature,confirmed_by,session_hash,issued_at,valid_until,original_job_state,original_job_revision,original_job_result) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)").bind(t).bind(id).bind(r.receipt_id).bind(&r.witness_sha256).bind(&payload).bind(signature).bind(&p.name).bind(session).bind(now).bind(r.valid_until).bind(&original_state).bind(original_revision).bind(&original_result).execute(&mut *tx).await?;
sqlx::query("INSERT INTO audit_events(tenant_id,event_id,principal,event_type,data) VALUES($1,$2,$3,'windows_system_nonstart_confirmed',$4)").bind(t).bind(r.receipt_id).bind(&p.name).bind(json!({"request_id":id,"witness_sha256":r.witness_sha256,"receipt_sha256":hash(&payload),"approval_origin":r.approval_origin,"testsimulation":true,"ready":false,"helper_ready":false,"unlock":false,"connection_generation":221,"server_transport_generation":transport,"job_id":JOB,"attempt_id":ATTEMPT,"grant_id":GRANT,"original_job_state":original_state,"original_job_revision":original_revision,"original_job_result":original_result,"original_job_result_sha256":inventory_sha256(&original_result)?})).execute(&mut *tx).await?;
let result = view(&mut tx, id, &w).await?;
tx.commit().await?;
Ok(Json(result))
}
/// Validate only the newly explicit administrative FAILED/nonstart result.
/// The immutable original permit anchors its signing key. Historical receipt
/// validity is checked at issuance; it is never interpreted as a current lease.
pub async fn validate_result(
tx: &mut Transaction<'_, Postgres>,
tenant: Uuid,
agent: Uuid,
result: &rmm_protocol::JobResult,
evidence: &Value,
) -> anyhow::Result<()> {
use anyhow::{Context, ensure};
ensure!(
(tenant, agent) == (TENANT, AGENT)
&& result.job_id == JOB.to_string()
&& result.attempt_id == ATTEMPT.to_string()
&& result.grant_id == GRANT.to_string(),
"WINDOWS_SYSTEM_NONSTART_RESULT_BINDING"
);
let id: Uuid = evidence["administrative_receipt_id"]
.as_str()
.context("WINDOWS_SYSTEM_NONSTART_RECEIPT_REQUIRED")?
.parse()?;
let row=sqlx::query("SELECT payload,signature,original_job_state,original_job_result FROM windows_system_nonstart_receipts WHERE tenant_id=$1 AND receipt_id=$2").bind(tenant).bind(id).fetch_one(&mut **tx).await?;
let signed = SignedReceipt {
payload: row.get("payload"),
signature: row.get("signature"),
};
let r: Receipt = serde_json::from_slice(&signed.payload)?;
let permit:Vec<u8>=sqlx::query_scalar("SELECT payload FROM execution_permits WHERE tenant_id=$1 AND job_id=$2 AND attempt_id=$3 AND grant_id=$4").bind(tenant).bind(JOB).bind(ATTEMPT).bind(GRANT).fetch_one(&mut **tx).await?;
let permit: ExecutionPermitPayload = serde_json::from_slice(&permit)?;
let public = hex::decode(&r.witness.verification_public_key_hex)?;
ensure!(
r.valid(r.issued_at)
&& r.receipt_id == id
&& r.key_id == permit.key_id
&& hash(&public) == permit.key_id
&& permit.grant_id == GRANT
&& serde_json::to_vec(&r)? == signed.payload
&& signed.signature.len() == 64,
"WINDOWS_SYSTEM_NONSTART_RECEIPT_BINDING"
);
let key = PKey::public_key_from_raw_bytes(&public, Id::ED25519)?;
ensure!(
Verifier::new_without_digest(&key)?.verify_oneshot(&signed.signature, &signed.payload)?,
"WINDOWS_SYSTEM_NONSTART_RECEIPT_SIGNATURE"
);
let receipt_sha256 = hash(&serde_json::to_vec(&signed)?);
let expected = profile::failed_outcome(id, &receipt_sha256);
ensure!(
result.state == expected.state
&& result.stdout == expected.stdout
&& result.stderr == expected.stderr
&& result.exit_code == expected.exit_code
&& result.output_truncated == expected.output_truncated
&& result.reboot_required == expected.reboot_required
&& result.error_code == expected.error_code
&& *evidence == expected.evidence
&& row.get::<String, _>("original_job_state") == "unknown"
&& row.get::<Value, _>("original_job_result")["grant_id"] == GRANT.to_string(),
"WINDOWS_SYSTEM_NONSTART_EXACT_FAILED_RESULT"
);
Ok(())
}
/// Only a new, otherwise valid normal Sync may derive this exact FAILED result.
/// Both native ledgers' independently checked derived snapshot is represented by
/// the canonical outcome bytes. The old Unknown rows and server result remain
/// archived in the signed witness/immutable receipt and the audit below.
pub async fn reconcile_failed(
tx: &mut Transaction<'_, Postgres>,
tenant: Uuid,
agent: Uuid,
local: &rmm_protocol::SyncAttempt,
request: &SyncRequest,
normal_chain: bool,
) -> anyhow::Result<()> {
use anyhow::{Context, ensure};
use rmm_domain::reconciliation::{ReconciledOutcome, canonical_outcome_bytes};
ensure!(
normal_chain
&& (tenant, agent) == (TENANT, AGENT)
&& local.job_id == JOB.to_string()
&& local.attempt_id == ATTEMPT.to_string()
&& local.grant_id == GRANT.to_string()
&& local.consumption == "consumed"
&& local.state == "failed"
&& local.revision == 3
&& local.original_boot_id == BOOT.to_string(),
"WINDOWS_SYSTEM_NONSTART_SYNC_BINDING"
);
ensure!(
!local.outcome_bytes.is_empty() && local.outcome_bytes.len() <= 65536,
"WINDOWS_SYSTEM_NONSTART_SYNC_BYTES"
);
let outcome: ReconciledOutcome = serde_json::from_slice(&local.outcome_bytes)?;
ensure!(
canonical_outcome_bytes(&outcome)? == local.outcome_bytes
&& hash(&local.outcome_bytes) == local.outcome_sha256
&& outcome.error_code == profile::ERROR_CODE,
"WINDOWS_SYSTEM_NONSTART_SYNC_CANONICAL"
);
let result = rmm_protocol::JobResult {
job_id: local.job_id.clone(),
attempt_id: local.attempt_id.clone(),
revision: local.revision,
state: outcome.state.clone(),
grant_id: local.grant_id.clone(),
stdout: outcome.stdout.clone(),
stderr: outcome.stderr.clone(),
output_truncated: outcome.output_truncated,
reboot_required: outcome.reboot_required,
exit_code: outcome.exit_code,
evidence_json: serde_json::to_string(&outcome.evidence)?,
error_code: outcome.error_code.clone(),
};
validate_result(tx, tenant, agent, &result, &outcome.evidence).await?;
let id: Uuid = outcome.evidence["administrative_receipt_id"]
.as_str()
.context("WINDOWS_SYSTEM_NONSTART_RECEIPT_REQUIRED")?
.parse()?;
let archive=sqlx::query("SELECT payload,original_job_revision,original_job_result FROM windows_system_nonstart_receipts WHERE tenant_id=$1 AND receipt_id=$2").bind(tenant).bind(id).fetch_one(&mut **tx).await?;
let receipt: Receipt = serde_json::from_slice(&archive.get::<Vec<u8>, _>("payload"))?;
ensure!(
request.journal_id == receipt.witness.agent_journal_id.to_string()
&& request.helper_journal_id == receipt.witness.helper_journal_id.to_string()
&& request.checkpoint > receipt.witness.agent_checkpoint
&& request.helper_checkpoint > receipt.witness.helper_checkpoint
&& request.journal_complete,
"WINDOWS_SYSTEM_NONSTART_FRESH_NORMAL_SNAPSHOTS"
);
let expected = json!({"stdout":result.stdout,"stderr":result.stderr,"output_truncated":false,"reboot_required":false,"exit_code":null,"evidence":outcome.evidence,"error_code":profile::ERROR_CODE,"grant_id":GRANT,"source_id":"administrative_nonstart_sync"});
let row=sqlx::query("SELECT state,revision,result,start_reserved,cancel_requested FROM jobs WHERE tenant_id=$1 AND agent_id=$2 AND job_id=$3 AND attempt_id=$4 FOR UPDATE").bind(tenant).bind(agent).bind(JOB).bind(ATTEMPT).fetch_one(&mut **tx).await?;
ensure!(
row.get::<bool, _>("start_reserved") && !row.get::<bool, _>("cancel_requested"),
"WINDOWS_SYSTEM_NONSTART_ORIGINAL_RESERVATION"
);
if row.get::<String, _>("state") == "failed" {
ensure!(
row.get::<i64, _>("revision") == 3
&& row.get::<Option<Value>, _>("result") == Some(expected),
"WINDOWS_SYSTEM_NONSTART_FINAL_IDENTITY"
);
return Ok(());
}
ensure!(
row.get::<String, _>("state") == "unknown"
&& row.get::<i64, _>("revision") == archive.get::<i64, _>("original_job_revision")
&& row.get::<i64, _>("revision") == 2
&& row.get::<Option<Value>, _>("result")
== Some(archive.get::<Value, _>("original_job_result"))
&& request.helper_previous_decision_id == SECOND.to_string(),
"WINDOWS_SYSTEM_NONSTART_ORIGINAL_UNKNOWN_RETAINED"
);
sqlx::query("INSERT INTO audit_events(tenant_id,event_id,principal,event_type,data) VALUES($1,$2,'signed-sync','windows_system_nonstart_reconciled',$3)").bind(tenant).bind(Uuid::new_v4()).bind(json!({"job_id":JOB,"attempt_id":ATTEMPT,"grant_id":GRANT,"receipt_id":id,"original_unknown_sha256":UNKNOWN_SHA,"original_server_result":row.get::<Option<Value>,_>("result"),"original_server_revision":2,"derived_outcome_sha256":local.outcome_sha256,"agent_checkpoint":request.checkpoint,"helper_checkpoint":request.helper_checkpoint,"job_authority":false})).execute(&mut **tx).await?;
sqlx::query("UPDATE jobs SET state='failed',revision=3,result=$4,pending_reason=NULL WHERE tenant_id=$1 AND agent_id=$2 AND job_id=$3 AND attempt_id=$5 AND state='unknown' AND revision=2").bind(tenant).bind(agent).bind(JOB).bind(expected).bind(ATTEMPT).execute(&mut **tx).await?;
Ok(())
}
async fn download(
State(s): State<crate::State>,
Path((t, id)): Path<(Uuid, Uuid)>,
h: HeaderMap,
) -> Result<Json<SignedReceipt>> {
let p = access(&s, &h, t, false).await?;
browser(&p)?;
let mut tx = rmm_persistence::tenant_tx(&s.pool, t).await?;
crate::permissions::require_principal(&mut tx, &p, "plans:approve").await?;
let (actual, w, transport) = stored(&mut tx)
.await?
.ok_or(Error(StatusCode::NOT_FOUND, "NOT_FOUND"))?;
if actual != id {
return Err(mismatch());
}
validate(&mut tx, &s, &w, Some(transport)).await?;
let row=sqlx::query("SELECT payload,signature FROM windows_system_nonstart_receipts WHERE tenant_id=$1 AND request_id=$2 ORDER BY issued_at DESC,receipt_id DESC LIMIT 1").bind(t).bind(id).fetch_optional(&mut *tx).await?.ok_or(Error(StatusCode::NOT_FOUND,"NOT_FOUND"))?;
let signed = SignedReceipt {
payload: row.get("payload"),
signature: row.get("signature"),
};
verify(&s, &signed.payload, &signed.signature)?;
let r: Receipt = serde_json::from_slice(&signed.payload)?;
if !r.valid(Utc::now()) || r.witness != w {
return Err(Error(
StatusCode::CONFLICT,
"WINDOWS_SYSTEM_NONSTART_EXPIRED",
));
}
tx.commit().await?;
Ok(Json(signed))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn administrative_confirmation_requires_actual_scoped_browser_session() {
let p = Principal {
name: TEST_PRINCIPAL.into(),
tenant: TENANT,
operator: true,
csrf: Some("csrf".into()),
session_hash: Some("ab".repeat(32)),
scopes: None,
testsimulation: true,
identity: None,
tenants: vec![TENANT],
};
assert!(browser(&p).is_ok());
for mutation in 0..5 {
let mut bad = p.clone();
match mutation {
0 => bad.session_hash = None,
1 => bad.csrf = None,
2 => bad.scopes = Some(Default::default()),
3 => bad.testsimulation = false,
_ => bad.operator = false,
};
assert_eq!(browser(&bad).unwrap_err().0, StatusCode::FORBIDDEN);
}
}
}
@@ -0,0 +1,89 @@
// Actual dev/test UI interactions only. No approval API, DB write or fetch injection.
const fs = require('node:fs'), path = require('node:path'), crypto = require('node:crypto');
const assert = require('node:assert/strict');
const root = path.resolve(__dirname, '../..');
const { chromium } = require(path.join(root, 'web/node_modules/playwright'));
function privateJson(file) {
const stat = fs.lstatSync(file);
assert(stat.isFile() && !stat.isSymbolicLink() && stat.uid === process.getuid() && (stat.mode & 511) === 384 && stat.size <= 2 * 1024 * 1024);
return JSON.parse(fs.readFileSync(file, 'utf8'));
}
function canonical(value) {
if (Array.isArray(value)) return '[' + value.map(canonical).join(',') + ']';
if (value && typeof value === 'object') return '{' + Object.keys(value).sort().map(k => JSON.stringify(k) + ':' + canonical(value[k])).join(',') + '}';
return JSON.stringify(value);
}
const sha = value => crypto.createHash('sha256').update(value).digest('hex');
(async () => {
const mode = process.argv[2], expected = privateJson(path.resolve(process.argv[3]));
assert(['submit', 'confirm'].includes(mode));
assert(expected.profile === 'dev/test' && expected.case === 'windows_system_nonstart_221');
const witness = privateJson(path.resolve(expected.witness_path));
assert(witness.connection_generation === 221 && witness.agent_checkpoint === 10784 && witness.helper_checkpoint >= 413);
assert(witness.agent_last_decision === '0442c732-8226-4c25-9615-7f007e24b269' && witness.helper_last_decision === '193b951b-a3aa-46e2-9f48-1a57f315078e');
assert(witness.nonstart.helper_pid === 1304 && witness.nonstart.read_share_error === 32 && witness.nonstart.read_write_share_passed === true);
assert(sha(Buffer.from(canonical(witness))) === expected.witness_sha256);
assert(sha(Buffer.from(witness.agent_outcome)) === '1f284b66578d61c4364cc0060a67ce9b467e1d661ed8885804391b51a6f18b1a');
assert.deepEqual(witness.agent_outcome, witness.helper_outcome);
const folder = path.resolve(expected.output_directory), folderStat = fs.lstatSync(folder);
assert(folder.startsWith(path.join(root, 'devstate') + path.sep) && folderStat.isDirectory() && !folderStat.isSymbolicLink() && folderStat.uid === process.getuid() && (folderStat.mode & 511) === 448);
const login = privateJson(path.join(root, 'credentials/server-browser-login.json'));
const versions = path.join(root, 'web/node_modules/.cache/playwright-browsers');
const version = fs.readdirSync(versions).find(n => /^chromium-/.test(n));
const executablePath = ['chrome-linux/chrome', 'chrome-linux64/chrome'].map(n => path.join(versions, version, n)).find(fs.existsSync);
const browser = await chromium.launch({ headless: true, executablePath,
env: { ...process.env, HOME: path.join(root, 'web/node_modules/.cache/cloud-acceptance/home') } });
try {
const page = await browser.newPage({ ignoreHTTPSErrors: false });
await page.goto('https://localhost:18443/');
await page.getByLabel('Benutzername').fill(login.username);
await page.getByLabel('Passwort', { exact: true }).fill(login.password);
const sessionResponse = page.waitForResponse(r => new URL(r.url()).pathname === '/auth/session' && r.status() === 200);
await page.getByRole('button', { name: 'Anmelden', exact: true }).click();
const session = await (await sessionResponse).json();
assert(session.principal === 'simulated-testprincipal-a' && session.testsimulation === true && session.approval_origin === 'dev_test_browser_simulation');
await page.getByRole('status').filter({ hasText: 'SIMULIERT' }).waitFor();
await page.getByRole('row').filter({ hasText: 'a176520e-8a91-4e93-a78b-8e7620f430e0' }).getByRole('button').click();
const section = page.getByRole('region', { name: 'Administrativer SYSTEM-Nichtstartabschluss 221', exact: true });
await section.waitFor();
if (mode === 'submit') {
await section.getByLabel('Nativer Nichtstartzeuge 221', { exact: true }).fill(JSON.stringify(witness));
await section.getByRole('button', { name: 'Zeugen einreichen und Originale serverseitig prüfen', exact: true }).click();
} else {
await section.getByRole('button', { name: 'Gespeicherten administrativen Fall prüfen', exact: true }).click();
}
await section.getByText('Vollständige Originalbelege und Dateibindungen', { exact: true }).click();
const preview = section.getByLabel('Geprüfter SYSTEM-Nichtstartzeuge', { exact: true });
await preview.waitFor(); const review = JSON.parse(await preview.innerText());
assert.deepEqual(review.witness, witness); assert(review.witness_sha256 === expected.witness_sha256);
assert(Number.isSafeInteger(review.server_transport_generation) && review.server_transport_generation >= 221);
if (expected.server_transport_generation !== undefined) assert(review.server_transport_generation === expected.server_transport_generation);
const record = { actual_simulated_ui: true, mode, witness_sha256: review.witness_sha256, server_transport_generation: review.server_transport_generation, request_id: review.request_id, confirmed: false, job_approved: false };
if (mode === 'confirm') {
const button = section.getByRole('button', { name: 'SIMULIERT: Exakten SYSTEM-Nichtstart 221 bestätigen', exact: true });
assert(await button.isDisabled());
await section.getByRole('checkbox', { name: 'Ich habe genau den Fall 221', exact: false }).check();
await button.click();
const link = section.getByRole('link', { name: 'Signierte administrative Quittung herunterladen', exact: true });
await link.waitFor(); const downloadEvent = page.waitForEvent('download'); await link.click();
const download = await downloadEvent, output = path.join(folder, 'windows-system-nonstart-221-receipt.json');
assert(!fs.existsSync(output)); await download.saveAs(output); fs.chmodSync(output, 384);
const signed = privateJson(output), receipt = JSON.parse(Buffer.from(signed.payload).toString('utf8'));
assert(receipt.domain === 'rmm.dev.windows-system-nonstart-221.v1' && receipt.schema_version === 1);
assert.deepEqual(receipt.witness, witness); assert(receipt.witness_sha256 === expected.witness_sha256 && receipt.server_transport_generation === review.server_transport_generation);
assert(receipt.confirmed_by === 'simulated-testprincipal-a' && receipt.testsimulation === true && receipt.approval_origin === 'dev_test_browser_simulation');
assert(receipt.ready === false && receipt.helper_ready === false && receipt.unlock === false);
assert(Date.parse(receipt.valid_until) > Date.now() + 60000 && Date.parse(receipt.valid_until) - Date.parse(receipt.issued_at) <= 300000);
const publicRaw = Buffer.from(witness.verification_public_key_hex, 'hex');
assert(sha(publicRaw) === receipt.key_id);
const publicKey = crypto.createPublicKey({ key: Buffer.concat([Buffer.from('302a300506032b6570032100', 'hex'), publicRaw]), format: 'der', type: 'spki' });
assert(crypto.verify(null, Buffer.from(signed.payload), publicKey, Buffer.from(signed.signature)));
Object.assign(record, { confirmed: true, receipt_id: receipt.receipt_id, receipt_file: output,
canonical_signed_receipt_sha256: sha(Buffer.from(JSON.stringify({ payload: signed.payload, signature: signed.signature }))),
ready: false, helper_ready: false, unlock: false });
}
fs.writeFileSync(path.join(folder, 'system-nonstart-ui-' + mode + '.json'), JSON.stringify(record, null, 2), { mode: 384, flag: 'wx' });
await page.getByRole('button', { name: 'Abmelden', exact: true }).click();
console.log('PASS actual simulated WebUI ' + mode + '; administrative nonstart only, no job approval');
} finally { await browser.close(); }
})().catch(error => { console.log('SYSTEM_NONSTART_UI_INCOMPLETE:' + error.constructor.name); process.exitCode = 1; });
+111
View File
@@ -0,0 +1,111 @@
#!/usr/bin/env python3
"""Freeze only the approved Windows221 server closure; build without deployment."""
import argparse
import gzip
import inspect
import io
import json
import os
from pathlib import Path
import subprocess
import tarfile
import uuid
import server_build_only as build
def freeze(source, web):
os.umask(0o077)
source = source.resolve()
web = web.resolve()
assert source.is_relative_to(build.ROOT / 'devstate')
assert web.is_relative_to(build.ROOT / 'devstate')
baseline = build.ROOT / 'devstate/server-build-only/a48f78614e2e/package/source'
allowed = {
'crates/domain/src/lib.rs',
'crates/domain/src/windows_system_nonstart.rs',
'crates/server/src/main.rs',
'crates/server/src/job_gateway.rs',
'crates/server/src/synchronization.rs',
'crates/server/src/windows_system_nonstart.rs',
'migrations/0021_windows_system_nonstart.sql',
'web/src/main.tsx',
'web/src/system-nonstart-review.tsx',
'web/src/system-nonstart-review.test.tsx',
'web/src/system-nonstart-review.test.ts',
}
def regular_files(folder):
result = {}
for path in sorted(folder.rglob('*')):
assert not path.is_symlink(), 'Frozen closure must not contain symlinks'
if path.is_file():
assert path.stat().st_size <= 16 * 1024 * 1024
result[str(path.relative_to(folder))] = path.read_bytes()
return result
original = regular_files(baseline)
frozen = regular_files(source)
assert set(original) <= set(frozen), 'No baseline source removal'
changed = {name for name, raw in frozen.items() if original.get(name) != raw}
assert changed <= allowed and 'crates/server/src/windows_system_nonstart.rs' in changed
assert 'migrations/0021_windows_system_nonstart.sql' in changed
assert any(b'windows-system-nonstart-221' in raw for raw in regular_files(web).values())
before = build.ssh(inspect.getsource(build.preflight).replace(
'PARAMETERS', repr({'builder': build.BUILDER})) + '\nprint(__import__("json").dumps(preflight()))\n')
assert before['disk_available_bytes'] > 8 * 1024**3
ident = uuid.uuid4().hex[:12]
folder = build.ROOT / 'devstate/server-build-only' / ident
folder.mkdir(mode=0o700, parents=True)
files = {'source/' + name: raw for name, raw in frozen.items()}
inputs = {name: build.sha(raw) for name, raw in frozen.items()}
assert regular_files(source) == frozen, 'Source closure drift'
files['inputs.sha256'] = ''.join(h + ' ' + n + '\n' for n, h in inputs.items()).encode()
files['Dockerfile'] = (
'FROM ' + build.BUILDER + ' AS build\nWORKDIR /src\n'
'COPY source/ /src/\nCOPY inputs.sha256 /tmp/rmm-build-inputs.sha256\n'
'RUN sha256sum -c /tmp/rmm-build-inputs.sha256 && '
'cargo clippy --offline --locked -p rmm-server -p rmm-time-broker-linux '
'--all-targets -- -D warnings && '
'cargo build --offline --locked --release -p rmm-server -p rmm-time-broker-linux --bins\n'
'FROM ' + before['units']['api']['image'] + '\n'
'COPY --from=build /src/target/release/rmm-server /usr/local/bin/rmm-server\n'
'COPY --from=build /src/target/release/rmm-time-broker-linux /usr/local/bin/rmm-time-broker-linux\n'
).encode()
for name, raw in regular_files(web).items():
files['web/' + name] = raw
manifest = {
'schema_version': 1, 'release': 'server221-' + ident,
'git_base': subprocess.check_output(['git', 'rev-parse', 'HEAD'], text=True).strip(),
'builder': build.BUILDER, 'preflight': before, 'source_files': inputs,
'baseline_source_manifest': 'a48f78614e2e', 'changed_source_files': sorted(changed),
'web': {n[4:]: build.sha(raw) for n, raw in files.items() if n.startswith('web/')},
'file_hashes': {n: build.sha(raw) for n, raw in files.items()},
'build_only': True, 'runtime_deployment': False, 'migration_executed': False,
}
files['manifest.json'] = json.dumps(manifest, sort_keys=True, indent=2).encode()
for name, raw in files.items():
build.write(folder / 'package' / name, raw)
buffer = io.BytesIO()
with tarfile.open(fileobj=buffer, mode='w') as archive:
for name, raw in sorted(files.items()):
member = tarfile.TarInfo(name)
member.size = len(raw)
member.mode = 0o400
archive.addfile(member, io.BytesIO(raw))
raw = gzip.compress(buffer.getvalue(), mtime=0)
build.write(folder / 'package.tar.gz', raw)
sealed = dict(release=manifest['release'], sha256=build.sha(raw),
manifest_sha256=build.sha(files['manifest.json']), bytes=len(raw), source_count=len(inputs))
build.write(folder / 'sealed.json', json.dumps(sealed, sort_keys=True, indent=2).encode())
params = {**sealed, 'worker': inspect.getsource(build.worker).replace('PARAMETERS', repr(sealed)) + '\nworker()\n'}
result = build.ssh(inspect.getsource(build.stage).replace('PARAMETERS', repr(params))
+ '\nprint(__import__("json").dumps(stage()))\n', raw=raw)
build.write(folder / 'stage-result.json', json.dumps(result, sort_keys=True, indent=2).encode())
print(json.dumps(dict(folder=str(folder), sealed=sealed, stage=result)))
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--source', required=True, type=Path)
parser.add_argument('--web', required=True, type=Path)
args = parser.parse_args()
freeze(args.source, args.web)
+164
View File
@@ -0,0 +1,164 @@
#!/usr/bin/env python3
"""Deploy the scoped Windows221 closure build; preserve runtime, jobs and broker."""
import argparse
import inspect
import json
from pathlib import Path
import server_build_only as build
def remote():
from pathlib import Path
import subprocess,json,os,hashlib,stat,time,ssl,http.client,socket,tempfile
p=PARAMETERS;root=Path('/opt/rust-discovery');case=root/'devstate'/p['case'];pkg=case/'package'
def sha(raw):return hashlib.sha256(raw).hexdigest()
def encoded(v):return json.dumps(v,sort_keys=True,separators=(',',':')).encode()
def run(args,timeout=40):return subprocess.check_output(args,stderr=subprocess.DEVNULL,text=True,timeout=timeout).strip()
def once(path,value):
raw=encoded(value)
with path.open('xb') as stream:stream.write(raw);stream.flush();os.fsync(stream.fileno())
def docker(role):return json.loads(run(['docker','inspect','rust-discovery-server-'+role+'-1']))[0]
def actual(c):return dict(id=c['Id'],image=c['Image'],started_at=c['State']['StartedAt'],restart_count=c['RestartCount'],running=c['State']['Running'])
def shape(c):
conf,host=c['Config'],c['HostConfig']
value={'user':conf['User'],'env':sorted(conf['Env']),'entrypoint':conf['Entrypoint'],'cmd':conf['Cmd'],'working_dir':conf['WorkingDir'],
'mounts':sorted(c['Mounts'],key=lambda m:m['Destination']),'binds':sorted(host.get('Binds')or[]),'networks':sorted(c['NetworkSettings']['Networks']),
'labels':{k:v for k,v in (conf.get('Labels')or{}).items() if not k.startswith('com.docker.compose.')},
'host':{k:host.get(k) for k in ('ReadonlyRootfs','PortBindings','CapDrop','CapAdd','SecurityOpt','RestartPolicy','Privileged','NetworkMode','IpcMode','PidMode','Devices','UsernsMode')}}
return sha(encoded(value))
def sql(query):return run(['docker','exec','rust-discovery-server-postgres-1','psql','-XqAt','-v','ON_ERROR_STOP=1','-U','postgres','-d','rmm','-c',query],15)
def migrations():
values=sql("SELECT version,encode(checksum,'hex'),success FROM _sqlx_migrations ORDER BY version").splitlines()
actual_map={}
for row in values:
version,checksum,success=row.split('|');assert success=='t';actual_map[int(version)]=checksum
expected={int(x.name[:4]):hashlib.sha384(x.read_bytes()).hexdigest() for x in (pkg/'source/migrations').glob('*.sql')}
assert actual_map==expected or actual_map=={k:v for k,v in expected.items() if k<21}
return max(actual_map)
def counts():
return json.loads(sql("SELECT json_build_object('jobs',(SELECT count(*) FROM jobs),'grants',(SELECT count(*) FROM execution_permits),'authorizations',(SELECT count(*) FROM authorizations),'outbox',(SELECT count(*) FROM outbox),'echo_completion',(SELECT count(*) FROM windows_echo_completions),'windows_jobs',(SELECT count(*) FROM jobs WHERE agent_id='63ea15b2-0643-403d-b5b4-cba1288dbea3'),'windows_grants',(SELECT count(*) FROM execution_permits p JOIN jobs j USING(tenant_id,job_id,attempt_id) WHERE j.agent_id='63ea15b2-0643-403d-b5b4-cba1288dbea3'))"))
def windows():
return json.loads(sql("SELECT json_build_object('generation',i.connection_generation,'boot',i.connection_boot_id,'revoked',i.revoked_at,'journal',s.journal_id,'checkpoint',s.checkpoint,'decision',s.decision_id,'helper_journal',s.helper_journal_id,'helper_checkpoint',s.helper_checkpoint) FROM agent_installations i JOIN agent_sync_state s USING(tenant_id,agent_id) WHERE i.agent_id='63ea15b2-0643-403d-b5b4-cba1288dbea3'"))
def passive_units():
return {name:run(['systemctl','show',name,'--property=MainPID,ActiveState,SubState,ExecMainStartTimestampMonotonic,NRestarts']) for name in ('rmm-time-broker.service','chrony.service')}
def protected_metadata():
records={}
for base in ('devstate/pki','devstate/api-pki','devstate/jobs','devstate/root-policy'):
path=root/base
for item in [path,*sorted(path.rglob('*'))]:
meta=item.lstat();assert not item.is_symlink() and (stat.S_ISDIR(meta.st_mode)or stat.S_ISREG(meta.st_mode))
records[str(item)]={k:getattr(meta,'st_'+k) for k in ('dev','ino','uid','gid','mode','nlink','size','mtime_ns','ctime_ns')}
for item in (Path('/run/rmm-time-source'),Path('/run/rmm-time-source/broker.sock')):
if item.exists():
meta=item.lstat();records[str(item)]={k:getattr(meta,'st_'+k)for k in('dev','ino','uid','gid','mode','nlink')}
return sha(encoded(records))
def assert_role(role,c):
port={'api':'18443','gateway':'18444'}[role];conf,host=c['Config'],c['HostConfig']
assert c['State']['Running'] and c['RestartCount']==0 and conf['User']=='10001:10001'
assert host['PortBindings']=={'18443/tcp':[{'HostIp':'127.0.0.1','HostPort':port}]} and host['ReadonlyRootfs'] and host['CapDrop']==['ALL'] and host['SecurityOpt']==['no-new-privileges:true']
if role=='gateway':assert any(m['Destination']=='/run/rmm-time-source' and m['Source']=='/run/rmm-time-source' and m['RW']is False for m in c['Mounts'])
def request(role,path):
if role=='api':connection=http.client.HTTPSConnection('localhost',18443,context=ssl.create_default_context(cafile=str(root/'devstate/api-pki/ca.pem')),timeout=3)
else:
class Checked(http.client.HTTPSConnection):
def connect(self):self.sock=self._context.wrap_socket(socket.create_connection(('127.0.0.1',18444),timeout=self.timeout),server_hostname='discovery.ease-technologies.de')
connection=Checked('discovery.ease-technologies.de',18444,context=ssl.create_default_context(cafile=str(root/'devstate/pki/ca.pem')),timeout=3)
try:connection.request('GET',path);response=connection.getresponse();return response.status,response.read(2*1024*1024)
finally:connection.close()
assert os.uname().machine=='aarch64' and os.geteuid()==0
assert not any(n in os.environ for n in ('DOCKER_HOST','DOCKER_CONTEXT','COMPOSE_FILE','COMPOSE_PROJECT_NAME','COMPOSE_PROFILES'))
assert sha((pkg/'manifest.json').read_bytes())==p['manifest']
manifest=json.loads((pkg/'manifest.json').read_text());built=json.loads((case/'build.receipt.json').read_text())
assert built['exit_code']==0 and built['image']==p['image'] and built['architecture']=='arm64' and built['runtime_unchanged']
assert all(sha((pkg/n).read_bytes())==h for n,h in manifest['file_hashes'].items())
before_path=case/'deployment221-before.json'
if p['action']=='preflight':
assert not before_path.exists()
current={role:docker(role)for role in('api','gateway','postgres')}
assert {r:actual(c)for r,c in current.items()}==built['runtime_after']
for role in('api','gateway'):assert_role(role,current[role])
assert current['postgres']['HostConfig']['PortBindings']in({},None)
labels=current['api']['Config']['Labels'];assert labels['com.docker.compose.project']=='rust-discovery-server'
files=labels['com.docker.compose.project.config_files'].split(',');assert len(files) in (7,8)
assert all(Path(f).is_file() and not Path(f).is_symlink() and Path(f).is_relative_to(root)for f in files)
base=['docker','compose','--project-name','rust-discovery-server','--project-directory',str(root/'deploy'),'--env-file',str(root/'devstate/.env')]
for f in files:base+=['-f',f]
old=json.loads(run(base+['config','--format','json']))
overlay=case/'deployment221-images.compose.yaml';raw=('services:\n'+''.join(' '+role+':\n image: '+p['image']+'\n pull_policy: never\n'for role in('api','gateway','migrate'))).encode()
if overlay.exists():assert overlay.read_bytes()==raw
else:
with overlay.open('xb')as stream:stream.write(raw)
compose=base+['-f',str(overlay)];new=json.loads(run(compose+['config','--format','json']))
expected=json.loads(json.dumps(old))
for role in('api','gateway','migrate'):expected['services'][role]['image']=p['image'];expected['services'][role]['pull_policy']='never'
assert expected==new,'Unexpected compose semantics change'
candidate=json.loads(run(['docker','image','inspect',p['image']]))[0]['Config']
for role in('api','gateway'):
service=new['services'][role];env=dict(x.split('=',1)for x in(candidate.get('Env')or[]));env.update(service.get('environment')or{})
assert sorted(k+'='+str(v)for k,v in env.items())==sorted(current[role]['Config']['Env'])
assert service.get('user',candidate.get('User',''))==current[role]['Config']['User']
assert (candidate['Entrypoint']if service.get('entrypoint')is None else service['entrypoint'])==current[role]['Config']['Entrypoint']
assert (candidate.get('Cmd')if service.get('command')is None else service['command'])==current[role]['Config']['Cmd']
schema_before=migrations();assert schema_before in (20,21)
w=windows();assert w['generation']>=221 and w['boot']=='a9ad0895-5a96-8f2c-8fb6-cfdc2d5225ea'and w['decision']=='0442c732-8226-4c25-9615-7f007e24b269'and w['checkpoint']==10784 and w['helper_checkpoint']==413 and w['revoked']is None
state={'actual':{r:actual(c)for r,c in current.items()},'shape':{r:shape(c)for r,c in current.items()},'compose':compose,'compose_sha256':sha(encoded(new)),'files_sha256':{f:sha(Path(f).read_bytes())for f in files},'overlay_sha256':sha(raw),'counts':counts(),'windows':w,'protected_sha256':protected_metadata(),'passive_units':passive_units(),'web_before':{str(f.relative_to(root/'web/dist')):sha(f.read_bytes())for f in(root/'web/dist').rglob('*')if f.is_file()}}
once(before_path,state);return {'preflight':True,'migration':schema_before,'image':p['image'],'compose_only_image_changes':True,'environment_identical':True,'loopback_only':True,'windows':w,'counts':state['counts'],'root_uid':10001,'secrets_logged':False}
before=json.loads(before_path.read_text());compose=before['compose']
assert all(sha(Path(f).read_bytes())==h for f,h in before['files_sha256'].items())
assert sha(Path(compose[-1]).read_bytes())==before['overlay_sha256']
assert sha(encoded(json.loads(run(compose+['config','--format','json']))))==before['compose_sha256']
assert actual(docker('postgres'))==before['actual']['postgres'] and shape(docker('postgres'))==before['shape']['postgres']
assert passive_units()==before['passive_units'] and protected_metadata()==before['protected_sha256']
assert counts()==before['counts'] and windows()==before['windows']
def check_apps(new):
for role in('api','gateway'):
c=docker(role);assert_role(role,c);assert shape(c)==before['shape'][role]
assert (c['Image']==p['image']and c['Id']!=before['actual'][role]['id'])if new else actual(c)==before['actual'][role]
if p['action']=='migrate':
assert migrations()==20;check_apps(False);once(case/'deployment221-migration-intent.json',{'image':p['image'],'migration':21})
log=case/'deployment221-migration.log'
with log.open('xb')as stream:r=subprocess.run(compose+['run','--no-deps','-T','--rm','--name','rmm-server221-migrate-21','migrate'],stdout=stream,stderr=subprocess.STDOUT,timeout=60)
assert r.returncode==0 and migrations()==21;check_apps(False)
assert sql('SELECT count(*) FROM windows_system_nonstart_reviews')=='0' and sql('SELECT count(*) FROM windows_system_nonstart_receipts')=='0'
elif p['action']=='apps':
assert migrations()==21;check_apps(False);once(case/'deployment221-apps-intent.json',{'image':p['image'],'before':before['actual']})
with(case/'deployment221-apps.log').open('xb')as stream:r=subprocess.run(compose+['up','-d','--no-deps','--no-build','--pull','never','api','gateway'],stdout=stream,stderr=subprocess.STDOUT,timeout=60)
assert r.returncode==0
for _ in range(30):
try:
assert request('api','/healthz')==(200,b'ok')and request('gateway','/healthz')==(200,b'ok');break
except Exception:time.sleep(.25)
else:raise RuntimeError('TLS-validated application health did not become ready')
check_apps(True)
for role in('api','gateway'):assert run(['docker','exec','rust-discovery-server-'+role+'-1','sha256sum','/usr/local/bin/rmm-server']).split()[0]==built['binaries']['rmm-server']['sha256']
elif p['action']=='web':
assert migrations()==21;check_apps(True);once(case/'deployment221-web-intent.json',{'web':manifest['web']})
current={str(f.relative_to(root/'web/dist')):sha(f.read_bytes())for f in(root/'web/dist').rglob('*')if f.is_file()};assert current==before['web_before']
for name,h in sorted(manifest['web'].items(),key=lambda v:v[0]=='index.html'):
src=pkg/'web'/name;assert sha(src.read_bytes())==h;dst=root/'web/dist'/name;assert not dst.is_symlink()and dst.parent.resolve()==dst.parent
if dst.exists()and sha(dst.read_bytes())==h:continue
if name!='index.html':assert not dst.exists()
with tempfile.NamedTemporaryFile(dir=dst.parent,delete=False)as stream:
temp=Path(stream.name);os.fchmod(stream.fileno(),0o644);stream.write(src.read_bytes());stream.flush();os.fsync(stream.fileno())
os.replace(temp,dst)
assert request('api','/')[0]==200 and sha(request('api','/')[1])==manifest['web']['index.html']
elif p['action']=='verify':
assert migrations()==21;check_apps(True)
assert all(sha((root/'web/dist'/n).read_bytes())==h for n,h in manifest['web'].items())
assert request('api','/healthz')==(200,b'ok')and request('gateway','/healthz')==(200,b'ok')
assert request('api','/api/v1/tenants/11111111-1111-4111-8111-111111111111/windows-system-nonstart-221')[0]==401
else:raise RuntimeError('unknown fixed deployment action')
assert counts()==before['counts'] and windows()==before['windows'] and passive_units()==before['passive_units'] and protected_metadata()==before['protected_sha256']
assert actual(docker('postgres'))==before['actual']['postgres']
result={'action':p['action'],'image':p['image'],'migration':migrations(),'api':actual(docker('api')),'gateway':actual(docker('gateway')),'postgres_unchanged':True,'broker_chrony_unchanged':True,'protected_pki_jobkey_policy_metadata_unchanged':True,'counts':counts(),'windows':windows(),'environment_mounts_uid_security_loopback_unchanged':True,'job_authority_created':False}
once(case/('deployment221-'+p['action']+'-result.json'),result);return result
def main():
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('action',choices=('preflight','migrate','apps','web','verify'));parser.add_argument('--build-folder',required=True,type=Path);args=parser.parse_args()
folder=args.build_folder.resolve();assert folder.is_relative_to(build.ROOT/'devstate/server-build-only')
sealed=json.loads((folder/'sealed.json').read_text());receipt=json.loads((folder/'local-build-receipt.json').read_text());assert sealed['release'].startswith('server221-') and receipt['release']==sealed['release'] and receipt['exit_code']==0 and receipt['runtime_unchanged']
p={'case':sealed['release'],'image':receipt['image'],'manifest':sealed['manifest_sha256'],'action':args.action}
code=inspect.getsource(remote).replace('PARAMETERS',repr(p))+'\ntry:\n print(__import__("json").dumps(remote()))\nexcept Exception as error:\n import traceback\n print(__import__("json").dumps({"error_class":type(error).__name__,"frames":[{"function":f.name,"line":f.lineno}for f in traceback.extract_tb(error.__traceback__)]}))\n'
result=build.ssh(code,timeout=90)
if 'error_class'in result:print(json.dumps(result));raise RuntimeError('Deployment incomplete; redacted frame diagnostics above')
target=folder/('local-deployment-'+args.action+'.json');build.write(target,json.dumps(result,sort_keys=True,indent=2).encode());print(json.dumps(result))
if __name__=='__main__':main()
@@ -0,0 +1,228 @@
{
"schema_version": 1,
"scope": "approved_windows_SYSTEM_nonstart221_server_UI_and_first_native_attempt",
"server_build": {
"architecture": "arm64",
"binaries": {
"rmm-server": {
"bytes": 27758128,
"path": "/opt/rust-discovery/devstate/server221-3844ef400522/rmm-server",
"sha256": "9472678a8223321f49d49f804ac331e2c90f888785c85ad14636df58ea69410e"
},
"rmm-time-broker-linux": {
"bytes": 1072816,
"path": "/opt/rust-discovery/devstate/server221-3844ef400522/rmm-time-broker-linux",
"sha256": "da8e6644b221f012322ce26f8a58c0ad4e7e8980d0648f5037d6ea99d8be599a"
}
},
"build_only": true,
"exit_code": 0,
"image": "sha256:f0f3b79153e1ecd9f878cd0436a3a48238a8296f71790cf89f20efe1073b8b86",
"migration_executed": false,
"release": "server221-3844ef400522",
"runtime_after": {
"api": {
"id": "bcd0b56332a778ade2ecedaf3325824f3928ec8510f5bbb0d7d76bd3864eebe9",
"image": "sha256:b540435a7a8a0b42c7f023a3985bb00f8df76a009e3cb642ff0446260ecb3446",
"restart_count": 0,
"running": true,
"started_at": "2026-11-16T16:02:57.787830852Z"
},
"gateway": {
"id": "0bade50974cba5eea918bc053fa071bd22b9a626a59aa2f52e098f359de0523e",
"image": "sha256:b540435a7a8a0b42c7f023a3985bb00f8df76a009e3cb642ff0446260ecb3446",
"restart_count": 0,
"running": true,
"started_at": "2026-11-16T16:02:57.788860951Z"
},
"postgres": {
"id": "3ce274d1794aa189309b24147d63a67ae8f420663bd021628fbe8bb9ed9ec4dc",
"image": "sha256:f3bd19c606e442c3d7bdfa8002e03fe260a1023351e0ea4598032022b68dd6e3",
"restart_count": 0,
"running": true,
"started_at": "2026-11-13T09:46:28.43499101Z"
}
},
"runtime_before": {
"api": {
"id": "bcd0b56332a778ade2ecedaf3325824f3928ec8510f5bbb0d7d76bd3864eebe9",
"image": "sha256:b540435a7a8a0b42c7f023a3985bb00f8df76a009e3cb642ff0446260ecb3446",
"restart_count": 0,
"running": true,
"started_at": "2026-11-16T16:02:57.787830852Z"
},
"gateway": {
"id": "0bade50974cba5eea918bc053fa071bd22b9a626a59aa2f52e098f359de0523e",
"image": "sha256:b540435a7a8a0b42c7f023a3985bb00f8df76a009e3cb642ff0446260ecb3446",
"restart_count": 0,
"running": true,
"started_at": "2026-11-16T16:02:57.788860951Z"
},
"postgres": {
"id": "3ce274d1794aa189309b24147d63a67ae8f420663bd021628fbe8bb9ed9ec4dc",
"image": "sha256:f3bd19c606e442c3d7bdfa8002e03fe260a1023351e0ea4598032022b68dd6e3",
"restart_count": 0,
"running": true,
"started_at": "2026-11-13T09:46:28.43499101Z"
}
},
"runtime_deployment": false,
"runtime_unchanged": true,
"source_manifest_sha256": "b2436e416c66e3388779f8aebddecdc46a9e3da6e582d3bc75928d07bb8e9b5b",
"tag": "rust-discovery-server:server221-3844ef400522"
},
"server_deployment": {
"action": "verify",
"api": {
"id": "d589e4100c3826320958788489908943c6f6e860df275ed2616ba7ea273470fd",
"image": "sha256:f0f3b79153e1ecd9f878cd0436a3a48238a8296f71790cf89f20efe1073b8b86",
"restart_count": 0,
"running": true,
"started_at": "2026-11-16T16:23:40.035959069Z"
},
"broker_chrony_unchanged": true,
"counts": {
"authorizations": 35,
"echo_completion": 1,
"grants": 30,
"jobs": 35,
"outbox": 35,
"windows_grants": 3,
"windows_jobs": 4
},
"environment_mounts_uid_security_loopback_unchanged": true,
"gateway": {
"id": "e778410788b2bfe5c004289831798d13780f2435e8511d9430ade549cc26097c",
"image": "sha256:f0f3b79153e1ecd9f878cd0436a3a48238a8296f71790cf89f20efe1073b8b86",
"restart_count": 0,
"running": true,
"started_at": "2026-11-16T16:23:40.038057027Z"
},
"image": "sha256:f0f3b79153e1ecd9f878cd0436a3a48238a8296f71790cf89f20efe1073b8b86",
"job_authority_created": false,
"migration": 21,
"postgres_unchanged": true,
"protected_pki_jobkey_policy_metadata_unchanged": true,
"windows": {
"boot": "a9ad0895-5a96-8f2c-8fb6-cfdc2d5225ea",
"checkpoint": 10784,
"decision": "0442c732-8226-4c25-9615-7f007e24b269",
"generation": 301,
"helper_checkpoint": 413,
"helper_journal": "cb4db2c6-a1b2-4fb3-be9d-1f677de0de2b",
"journal": "3dd1dfb5-d586-472a-af28-7fd4d203e90b",
"revoked": null
}
},
"actual_UI_submit": {
"actual_simulated_ui": true,
"mode": "submit",
"witness_sha256": "b92a51bb272285b570f31015bde82ccd713db71e15edd802f468d3df2b354170",
"server_transport_generation": 301,
"request_id": "3ca781c9-2952-4668-8b0b-34ec2a45462a",
"confirmed": false,
"job_approved": false
},
"actual_UI_confirm": {
"actual_simulated_ui": true,
"mode": "confirm",
"witness_sha256": "b92a51bb272285b570f31015bde82ccd713db71e15edd802f468d3df2b354170",
"server_transport_generation": 301,
"request_id": "3ca781c9-2952-4668-8b0b-34ec2a45462a",
"confirmed": true,
"job_approved": false,
"receipt_id": "4e2fdd7d-8344-46f5-bd0d-707abd6016cb",
"canonical_signed_receipt_sha256": "d2cd66f272ce6b94ef9887d6fa7a6df16e79cab055d96f0d3148b0b81ef91f69",
"ready": false,
"helper_ready": false,
"unlock": false
},
"actual_six_file_archive": {
"original_files_changed": false,
"archive_directory": "C:\\ProgramData\\RustDiscoveryBootstrap\\system-nonstart-221-originals",
"files": [
{
"sha256": "02b8968b8eae77302f10b64a3d6bfb0b0b574ce26bd50e236a3e968c4236f213",
"bytes": 11591680,
"sddl": "O:BAG:BAD:P(A;;FA;;;SY)(A;;FA;;;BA)",
"role": "telemetry"
},
{
"sha256": "461cc2d9ac1e60d1333970ddff4d92465450502e4bc4223cb7f720d0f3c4a8a0",
"bytes": 958464,
"sddl": "O:BAG:BAD:P(A;;FA;;;SY)(A;;FA;;;BA)",
"role": "consumption"
},
{
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"bytes": 0,
"sddl": "O:BAG:BAD:P(A;;FA;;;SY)(A;;FA;;;BA)",
"role": "agent_lock"
},
{
"sha256": "ce75dd67bb8191bfc3d671c5c1d5cb3a35f559a4aa5ee79b9cda0a28fdeec430",
"bytes": 3993600,
"sddl": "O:BAG:BAD:P(A;;FA;;;SY)(A;;FA;;;BA)",
"role": "helper_ledger"
},
{
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"bytes": 0,
"sddl": "O:BAG:BAD:P(A;;FA;;;SY)(A;;FA;;;BA)",
"role": "helper_lock"
},
{
"sha256": "88f2286fa332c78d70308cb97823af9750f8718f4bdc08645418414f69963e4c",
"bytes": 49152,
"sddl": "O:BAG:BAD:P(A;;FA;;;SY)(A;;FA;;;BA)",
"role": "system_intents"
}
],
"schema_version": 1,
"job_executed": false,
"product_sql_rows_changed": false,
"utc": "2026-11-16T16:27:58.0953404Z"
},
"Linux_auth_contract": {
"exit_code": 0,
"stdout": "{\"effects\":false,\"product_databases_opened\":false,\"valid_actual_signed_receipt\":true,\"wrong_grant_rejected\":true,\"wrong_original_hash_rejected\":true,\"wrong_signature_rejected\":true}\n",
"stderr": "",
"binary_sha256": "f0afd19db26cae56687448f34801c131689e8cc628f54ee59278a5fa4023ace1",
"native_platform": "cloud-linux-x86_64",
"uid": 65534,
"isolated_network": true,
"no_new_privs": true,
"verified": true
},
"Windows_auth_contract": {
"native_platform": "windows11-amd64",
"sdk_sha256": "49b3e3ec1ecf0d333bc84e170842e1e6c072fb86872740a745a9b7d9bcacd0ae",
"actual_result": {
"effects": false,
"product_databases_opened": false,
"valid_actual_signed_receipt": true,
"wrong_grant_rejected": true,
"wrong_original_hash_rejected": true,
"wrong_signature_rejected": true
},
"at_utc": "2026-11-16T16:31:05.480080+00:00"
},
"first_native_apply": {
"stdout": "",
"actual_native_apply_invoked_once": true,
"utc": "2026-11-16T16:31:46.8973668Z",
"stderr_bytes": 992,
"exit_code": 1
},
"native_apply_error_code": "ROOT_ROW_CHANGED_WITHOUT_SNAPSHOT",
"independent_rollback_proof": {
"native_witness_canonical_sha256": "b92a51bb272285b570f31015bde82ccd713db71e15edd802f468d3df2b354170",
"all_four_original_database_inventories_unchanged": true,
"all_six_physical_file_hashes_and_ids_unchanged": true,
"original_unknown_unchanged": true,
"role_restarted": false
},
"native_closure_completed": false,
"new_SYSTEM_job_completed": false,
"original_grant_reexecuted": false
}
+51 -2
View File
@@ -30,10 +30,59 @@ Der exakt verwendete [Stopquelltext](../deploy/windows/Stop-OriginalNonstart221P
bleibt über seinen SHA mit dem tatsächlich verwendeten öffentlichen Payload
gebunden. Keine Zugangsdaten oder privaten Schlüssel wurden exportiert.
## Server und tatsächliche WebUI bestätigt; erste Anwendung zurückgerollt
API und Gateway betreiben seit17:23:40MEZ Imagef0f3b791… und Migration21.
Die eingefrorene Closure basiert auf dem tatsächlich vorher betriebenen
Server205-Quellstand mit ausschließlich zehn Änderungen für diesen Fall.
Ein zunächst eingesetzter Standb540… scheiterte bei der UI-Einreichung an
unzulässigen FOR-SHARE-Sperren auf unveränderlichen Tabellen. Drei unnötige
Sperren wurden entfernt. Der tatsächliche isolierte rmm_app-Rollenvertrag
reproduzierte die alten42501-Fehler und bestätigte die korrigierten Lesepfade;
keine UPDATE-Rechte oder Unveränderlichkeitstrigger wurden geändert.
TLS-/401-Prüfung, tatsächliche Laufzeitkonfiguration, Loopbackports und
Sandbox bestanden. Datenbankcontainer, Chrony, Broker, Schlüssel-/Policy-
Metadaten und sämtliche Job-/Grant-/Autorisierungszahlen blieben unverändert.
Der Nichtstartzeuge wurde tatsächlich in der sichtbar simulierten WebUI
eingereicht und die administrative Quittung4e2fdd7d… um17:29:23MEZ bestätigt.
Sie genehmigte keinen Auftrag und meldet ready/helper_ready/unlock=false.
Zusätzlich zu den ausgewählten Originalbelegen wurden alle vier Original-
SQLite-Dateien und beide Lockdateien mit exakten Witness-Hashes in ein
separates nur für SYSTEM/Administratoren zugängliches VM-Archiv kopiert.
Die Originaldateien blieben dabei unverändert. Der tatsächliche reine
Receiptvertrag bestand zuerst isoliert auf CloudLinux und danach auf Windows:
valide Signatur und Originaldaten angenommen; falsche Signatur, falscher
lokaler Grant und falsche lokale Originalbytes verweigert. Keine Produktdatenbank
oder Wirkung war Bestandteil dieser Vertragsprüfungen.
Der einmalige native Anwendungsversuch49b3… endete um17:31:46MEZ mit Exit1/
ROOT_ROW_CHANGED_WITHOUT_SNAPSHOT: Nach dem abgeleiteten Abschluss war die
interne helper_sync_rows-Projektion noch nicht aktualisiert. Sämtliche drei
Transaktionen wurden zurückgerollt. Ein neuer unabhängiger nativer reiner
Lesezeuge ergab danach wieder exakt denselben kanonischen Witnesshashb92a…,
alle vier Inventare und alle sechs physischen Filehashes und IDs unverändert.
Keine Rolle wurde gestartet und kein alter Grant erneut verwendet.
Der eng korrigierte Operatorpfad muss die normale abgeleitete Projektion
gezielt aktualisieren und alle Abschlussprüfungen bereits vor dem ersten
Commit bestehen. Die zusätzliche unabhängige Nachprüfung bleibt erforderlich.
Der erste Versuch und seine abgelaufene Quittung bleiben erhalten. Eine neue
Anwendung folgt ausschließlich nach belegtem wirkungslosem Rücklauf, korrigiertem
Werkzeug und neuer tatsächlicher WebUI-Bestätigung für denselben unveränderten
Witness. Die zwei normalen SignedSync-Unlockpfade müssen ebenfalls das signierte
Zusatzresultat lesen und die ursprünglichen Unknownbytes erhalten; bloßes
Maskieren in einem Snapshot reicht nicht. Der entsprechende Runtimezwischenbau
0db51c10/1c334ea8 ist deshalb noch nicht auf der VM installiert.
[Öffentliche tatsächliche Ergebnisse](evidence/windows-system-nonstart-221-server-ui.json).
## Noch nicht als abgeschlossen ausgewiesen
Der administrative WebUI-Beleg, seine native Anwendung und unabhängige
Nachprüfung stehen noch aus. Ebenso fehlen die Installation des korrigierten
Die erfolgreiche native Anwendung des administrativen WebUI-Belegs und ihre
unabhängige Nachprüfung stehen noch aus. Ebenso fehlen die Installation des korrigierten
Paares, dessen frische eigene Zeit-/SignedSync-Belege sowie der neue tatsächliche
WebUI-genehmigte SYSTEM-PowerShell-Erfolg. Der ursprüngliche Auftrag bleibt
bis zum belegten Zusatzabschluss Unknown. Andere MVP-Arbeiten bleiben angehalten.
@@ -0,0 +1,75 @@
-- Explicit connection-221 administrative closure only. No reconciliation,
-- grant, ready state, job, offer or original-history mutation is performed.
CREATE TABLE windows_system_nonstart_reviews (
tenant_id uuid PRIMARY KEY CHECK(tenant_id='11111111-1111-4111-8111-111111111111'),
request_id uuid NOT NULL UNIQUE,
agent_id uuid NOT NULL CHECK(agent_id='63ea15b2-0643-403d-b5b4-cba1288dbea3'),
witness jsonb NOT NULL,
witness_sha256 text NOT NULL CHECK(witness_sha256 ~ '^[0-9a-f]{64}$'),
server_transport_generation bigint NOT NULL CHECK(server_transport_generation>=221),
submitted_by text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE(tenant_id,request_id),
FOREIGN KEY(tenant_id,agent_id) REFERENCES agent_installations(tenant_id,agent_id),
CHECK(witness->>'schema_version'='1' AND witness->>'tenant_id'=tenant_id::text
AND witness->>'agent_id'=agent_id::text
AND witness->>'asset_id'='a176520e-8a91-4e93-a78b-8e7620f430e0'
AND witness->>'connection_generation'='221'
AND witness->>'boot_id'='a9ad0895-5a96-8f2c-8fb6-cfdc2d5225ea'
AND witness->>'agent_last_decision'='0442c732-8226-4c25-9615-7f007e24b269'
AND witness->>'helper_last_decision'='193b951b-a3aa-46e2-9f48-1a57f315078e')
);
CREATE TABLE windows_system_nonstart_receipts (
tenant_id uuid NOT NULL,
request_id uuid NOT NULL,
receipt_id uuid PRIMARY KEY,
witness_sha256 text NOT NULL CHECK(witness_sha256 ~ '^[0-9a-f]{64}$'),
payload 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,
original_job_state text NOT NULL CHECK(original_job_state='unknown'),
original_job_revision bigint NOT NULL CHECK(original_job_revision>=1),
original_job_result jsonb NOT NULL CHECK(original_job_result->>'grant_id'='97e705b8-fb2b-4158-84d9-d90595d1ce6e'),
valid_until timestamptz NOT NULL CHECK(valid_until>issued_at AND valid_until<=issued_at+interval '5 minutes'),
FOREIGN KEY(tenant_id,request_id) REFERENCES windows_system_nonstart_reviews(tenant_id,request_id)
);
DO $$ DECLARE t text; BEGIN
FOREACH t IN ARRAY ARRAY['windows_system_nonstart_reviews','windows_system_nonstart_receipts'] LOOP
EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY',t);
EXECUTE format('ALTER TABLE %I FORCE ROW LEVEL SECURITY',t);
EXECUTE format('CREATE POLICY tenant_scope ON %I USING(tenant_id::text=current_setting(''app.tenant_id'',true)) WITH CHECK(tenant_id::text=current_setting(''app.tenant_id'',true))',t);
EXECUTE format('GRANT SELECT,INSERT ON %I TO rmm_app',t);
EXECUTE format('CREATE TRIGGER immutable_content BEFORE UPDATE OR DELETE ON %I FOR EACH ROW EXECUTE FUNCTION immutable_plan()',t);
END LOOP;
END $$;
CREATE FUNCTION check_windows_system_nonstart_receipt() RETURNS trigger LANGUAGE plpgsql
SET search_path=pg_catalog,public AS $$
DECLARE w windows_system_nonstart_reviews%ROWTYPE; r jsonb; j jobs%ROWTYPE;
BEGIN
SELECT * INTO STRICT w FROM windows_system_nonstart_reviews WHERE tenant_id=NEW.tenant_id AND request_id=NEW.request_id;
r=convert_from(NEW.payload,'UTF8')::jsonb;
SELECT * INTO STRICT j FROM jobs WHERE tenant_id=NEW.tenant_id AND job_id='94047873-5088-433b-bc1b-490d3eafe0da' AND attempt_id='f071e6d6-8635-42f7-92fa-533c681edd8b';
IF j.state IS DISTINCT FROM NEW.original_job_state OR j.revision IS DISTINCT FROM NEW.original_job_revision OR j.result IS DISTINCT FROM NEW.original_job_result THEN RAISE EXCEPTION 'WINDOWS_SYSTEM_NONSTART_ORIGINAL_CHANGED'; END IF;
IF r->>'domain' IS DISTINCT FROM 'rmm.dev.windows-system-nonstart-221.v1'
OR r->>'schema_version' IS DISTINCT FROM '1'
OR r->>'request_id' IS DISTINCT FROM NEW.request_id::text
OR r->>'receipt_id' IS DISTINCT FROM NEW.receipt_id::text
OR r->>'witness_sha256' IS DISTINCT FROM NEW.witness_sha256
OR r->>'server_transport_generation' IS DISTINCT FROM w.server_transport_generation::text
OR NEW.witness_sha256 IS DISTINCT FROM w.witness_sha256
OR r->'witness' IS DISTINCT FROM w.witness
OR r->>'confirmed_by' IS DISTINCT FROM NEW.confirmed_by
OR r->>'approval_origin' IS DISTINCT FROM 'dev_test_browser_simulation'
OR r->'testsimulation' IS DISTINCT FROM 'true'::jsonb
OR r->'ready' IS DISTINCT FROM 'false'::jsonb
OR r->'helper_ready' IS DISTINCT FROM 'false'::jsonb
OR r->'unlock' IS DISTINCT FROM 'false'::jsonb
OR (r->>'issued_at')::timestamptz IS DISTINCT FROM NEW.issued_at
OR (r->>'valid_until')::timestamptz IS DISTINCT FROM NEW.valid_until
THEN RAISE EXCEPTION 'WINDOWS_SYSTEM_NONSTART_MISMATCH'; END IF;
RETURN NEW;
END $$;
CREATE TRIGGER validate_nonstart_receipt BEFORE INSERT ON windows_system_nonstart_receipts
FOR EACH ROW EXECUTE FUNCTION check_windows_system_nonstart_receipt();
+2 -1
View File
@@ -9,6 +9,7 @@ import { RecoveryReview, recoveryAsset, recoveryTenant } from './recovery-review
import { EchoProbeReview } from './echo-probe-review';
import { EchoCompletionReview } from './echo-completion-review';
import { SyncAlignmentReview } from './sync-alignment-review';
import { SystemNonstartReview } from './system-nonstart-review';
import { Login } from './login';
import { ConsoleOutput, outputText } from './console-output';
import { scriptApprovalBlockers, scriptPlanJobs, verifyScriptPlan } from './script-console';
@@ -114,7 +115,7 @@ function Devices({ tenantId, auth, selected, setSelected }: { tenantId: string;
<p>Fester Auswahlsnapshot ({selected.length}): {selected.join(', ') || 'keine Ziele'}</p>
{asset && <article><h3>Inventardetail {asset}</h3><ErrorBox error={detail.error}/>{detail.data && <><CatalogCheckNotice device={detail.data}/><JsonView value={detail.data} label="Inventar, Capabilities, Metriken, Dienste, Software, Updates, Logs und Quellen (soweit geliefert)"/></>}<AdminControl auth={auth} path={tenantPath(tenantId, `/devices/${encodeURIComponent(asset)}/revocation`)} permission="devices:revoke" title="Geräteidentität widerrufen" warning="ACHTUNG: Widerruf unterbricht die Geräteverwaltung und sperrt neue Starts. Kein Entfernen aus einer Liste, kein Rollback. Wiederaufnahme erfordert einen gesonderten sicheren Enrollment-/Recoveryprozess." done={detail.reload}/></article>}
{tenantId === recoveryTenant && asset === recoveryAsset && allowed(auth, 'inventory:read') &&
<><SyncAlignmentReview key={auth.principal.id + '-alignment'} auth={auth}/><EchoProbeReview key={auth.principal.id + '-probe'} auth={auth}/><EchoCompletionReview key={auth.principal.id + '-completion'} auth={auth}/><RecoveryReview key={auth.principal.id} auth={auth}/></>}
<><SystemNonstartReview key={auth.principal.id + '-system-nonstart-221'} auth={auth}/><SyncAlignmentReview key={auth.principal.id + '-alignment'} auth={auth}/><EchoProbeReview key={auth.principal.id + '-probe'} auth={auth}/><EchoCompletionReview key={auth.principal.id + '-completion'} auth={auth}/><RecoveryReview key={auth.principal.id} auth={auth}/></>}
</section>;
}
const initialParameters: Record<Action, RecordValue> = {
+22
View File
@@ -0,0 +1,22 @@
import { expect, it } from 'vitest';
import { canonicalJson } from './api';
import { sha256 } from './safety';
import { nonstartReview } from './system-nonstart-review';
it('binds the exact 221 witness and refuses job authority, altered history and extended receipts', async () => {
const witness = { schema_version: 1, tenant_id: '11111111-1111-4111-8111-111111111111', asset_id: 'a176520e-8a91-4e93-a78b-8e7620f430e0', agent_id: '63ea15b2-0643-403d-b5b4-cba1288dbea3',
enrollment_generation: 1, assignment_version: 1, connection_generation: 221, boot_id: 'a9ad0895-5a96-8f2c-8fb6-cfdc2d5225ea', agent_checkpoint: 10784, helper_checkpoint: 420,
agent_last_decision: '0442c732-8226-4c25-9615-7f007e24b269', helper_last_decision: '193b951b-a3aa-46e2-9f48-1a57f315078e', verification_key_id: 'a'.repeat(64),
nonstart: { helper_pid: 1304, read_share_error: 32, read_write_share_passed: true, helper_image_sha256: '0502d6c87bd74c99f1665f3cc4b9d74b8e31d0f829d2ce1a1597d72e9be1e726', system_script_source_sha256: 'a3563e1aa8327b2e7046c7cdfb4f45ac213fec6ff7d477820ea2676a266c1695' },
counts: { agent_jobs: 4, agent_consumed: 3, agent_starts: 3, agent_outcomes: 3, helper_consumed: 1, helper_starts: 1, helper_outcomes: 1, system_intents: 1 } };
const witness_sha256 = await sha256(new TextEncoder().encode(canonicalJson(witness)));
const request_id = '78009224-dcb3-4877-a519-8bf3284d0572';
const receipt = { domain: 'rmm.dev.windows-system-nonstart-221.v1', schema_version: 1, request_id, server_transport_generation:287, witness, witness_sha256, key_id: witness.verification_key_id,
issued_at: '2026-11-16T12:00:00Z', valid_until: '2026-11-16T12:05:00Z', confirmed_by: 'simulated-testprincipal-a', approval_origin: 'dev_test_browser_simulation', testsimulation: true, ready: false, helper_ready: false, unlock: false };
const view = { request_id, server_transport_generation:287, witness, witness_sha256, receipt };
expect((await nonstartReview(view)).witness_sha256).toBe(witness_sha256);
for (const changed of [{ ready: true }, { helper_ready: true }, { unlock: true }, { testsimulation: false }, { confirmed_by: 'Administrator' }, { valid_until: '2026-11-16T12:05:01Z' }, { witness: { ...witness, helper_checkpoint: 412 } }]) {
await expect(nonstartReview({ ...view, receipt: { ...receipt, ...changed } })).rejects.toThrow();
}
await expect(nonstartReview({ ...view, witness: { ...witness, connection_generation: 205 } })).rejects.toThrow();
await expect(nonstartReview({ ...view, witness: { ...witness, counts: { ...witness.counts, helper_consumed: 2 } } })).rejects.toThrow();
});
+80
View File
@@ -0,0 +1,80 @@
import React, { useState } from 'react';
import { canonicalJson, pretty, record, RecordValue, request, Session, tenantPath } from './api';
import { allowed, sha256 } from './safety';
const tenant = '11111111-1111-4111-8111-111111111111';
const asset = 'a176520e-8a91-4e93-a78b-8e7620f430e0';
const agent = '63ea15b2-0643-403d-b5b4-cba1288dbea3';
interface Review { request_id: string; witness: RecordValue; witness_sha256: string; server_transport_generation:number; receipt: RecordValue | null }
export async function nonstartReview(value: unknown): Promise<Review> {
const r = record(value), w = record(r.witness);
if (typeof r.request_id !== 'string' || typeof r.witness_sha256 !== 'string' || !Number.isSafeInteger(r.server_transport_generation) || Number(r.server_transport_generation)<221 ||
w.schema_version !== 1 || w.tenant_id !== tenant || w.asset_id !== asset || w.agent_id !== agent ||
canonicalJson(w.counts) !== canonicalJson({ agent_jobs: 4, agent_consumed: 3, agent_starts: 3, agent_outcomes: 3, helper_consumed: 1, helper_starts: 1, helper_outcomes: 1, system_intents: 1 }) ||
w.connection_generation !== 221 || w.enrollment_generation !== 1 || w.assignment_version !== 1 ||
w.boot_id !== 'a9ad0895-5a96-8f2c-8fb6-cfdc2d5225ea' || w.agent_checkpoint !== 10784 ||
typeof w.helper_checkpoint !== 'number' || w.helper_checkpoint < 413 ||
w.agent_last_decision !== '0442c732-8226-4c25-9615-7f007e24b269' ||
w.helper_last_decision !== '193b951b-a3aa-46e2-9f48-1a57f315078e' ||
record(w.nonstart).helper_pid !== 1304 || record(w.nonstart).read_share_error !== 32 || record(w.nonstart).read_write_share_passed !== true ||
record(w.nonstart).helper_image_sha256 !== '0502d6c87bd74c99f1665f3cc4b9d74b8e31d0f829d2ce1a1597d72e9be1e726' ||
record(w.nonstart).system_script_source_sha256 !== 'a3563e1aa8327b2e7046c7cdfb4f45ac213fec6ff7d477820ea2676a266c1695' ||
await sha256(new TextEncoder().encode(canonicalJson(w))) !== r.witness_sha256 ||
!(r.receipt === null || (typeof r.receipt === 'object' && !Array.isArray(r.receipt)))) {
throw new Error('Der administrative Zeuge passt nicht zum ausdrücklich freigegebenen Fall 221.');
}
if (r.receipt !== null) {
const receipt = record(r.receipt);
const issued = typeof receipt.issued_at === 'string' ? Date.parse(receipt.issued_at) : NaN;
const until = typeof receipt.valid_until === 'string' ? Date.parse(receipt.valid_until) : NaN;
if (receipt.domain !== 'rmm.dev.windows-system-nonstart-221.v1' || receipt.schema_version !== 1 ||
receipt.request_id !== r.request_id || receipt.witness_sha256 !== r.witness_sha256 || receipt.server_transport_generation!==r.server_transport_generation ||
canonicalJson(receipt.witness) !== canonicalJson(w) || receipt.key_id !== w.verification_key_id ||
receipt.confirmed_by !== 'simulated-testprincipal-a' || receipt.approval_origin !== 'dev_test_browser_simulation' ||
receipt.testsimulation !== true || receipt.ready !== false || receipt.helper_ready !== false || receipt.unlock !== false ||
!Number.isFinite(issued) || !Number.isFinite(until) || until <= issued || until - issued > 300000) {
throw new Error('Die administrative Quittung hat eine unzulässige Bindung oder behauptet Bereitschaft.');
}
}
return r as unknown as Review;
}
export function SystemNonstartReview({ auth }: { auth: Session }) {
const [review, setReview] = useState<Review | null>(null), [checked, setChecked] = useState(false);
const [input, setInput] = useState(''), [busy, setBusy] = useState(false), [error, setError] = useState('');
const eligible = auth.principal.simulated && auth.principal.id === 'simulated-testprincipal-a' && !!auth.csrf_token && allowed(auth, 'plans:approve');
const path = tenantPath(tenant, '/windows-system-nonstart-221');
async function load(submit: boolean) {
setBusy(true); setChecked(false); setError(''); setReview(null);
try {
const result = await request(path, submit ? { csrf: auth.csrf_token, body: JSON.parse(input) as RecordValue } : {});
if (record(result).request_id === null) throw new Error('Noch kein unabhängig erfasster Zeuge eingereicht.');
setReview(await nonstartReview(result));
} catch (e) { setError(String(e)); } finally { setBusy(false); }
}
async function confirm() {
if (!eligible || !checked || !review || busy) return;
setBusy(true); setChecked(false); setError('');
try { setReview(await nonstartReview(await request(path + '/' + encodeURIComponent(review.request_id) + '/confirm', {
csrf: auth.csrf_token, body: { reviewed: true, witness_sha256: review.witness_sha256 } })));
} catch (e) { setReview(null); setError(String(e)); } finally { setBusy(false); }
}
return <section aria-label="Administrativer SYSTEM-Nichtstartabschluss 221">
<h3>Administrativer SYSTEM-Nichtstartabschluss 221</h3>
<p>Dieser ausdrücklich freigegebene Eingriff betrifft nur SYSTEM-Job 94047873…, Versuch f071e6d6…, Grant 97e705b8… und Kontrollspalt 221. Beide ursprünglichen Unknown-Outcomes, Starts, Intent, Originalsignaturen und Journalidentitäten bleiben erhalten. Ein zusätzlicher geprüfter Nichtstartbeleg darf ausschließlich fehlgeschlagen ableiten, niemals Erfolg. Er genehmigt keinen Auftrag und keinen Wiederholungsversuch. Beide Rollen müssen danach einen neuen regulären signierten Abgleich bestehen.</p>
<label>Unabhängiger nativer Zeuge (JSON)<textarea aria-label="Nativer Nichtstartzeuge 221" value={input} disabled={busy} onChange={e => setInput(e.target.value)}/></label>
<button disabled={busy || !input || !auth.csrf_token} onClick={() => void load(true)}>Zeugen einreichen und Originale serverseitig prüfen</button>{' '}
<button disabled={busy} onClick={() => void load(false)}>Gespeicherten administrativen Fall prüfen</button>
{error && <p role="alert">{error}</p>}
{review && <>
<p>Historischer Kontrollspalt 221 · aktueller Servertransport {review.server_transport_generation} · Agentcheckpoint 10784 · tatsächlicher Helpercheckpoint {String(review.witness.helper_checkpoint)} · vier feste Jobs · ursprüngliches Unknown bleibt erhalten · nur abgeleiteter Nichtstart/failed · keine neue Startfreigabe</p>
<p>Geprüfter Zeugenhash: <code>{review.witness_sha256}</code></p>
<details><summary>Vollständige Originalbelege und Dateibindungen</summary><pre aria-label="Geprüfter SYSTEM-Nichtstartzeuge">{pretty(review)}</pre></details>
{review.receipt && <p>Letzte Quittung gültig bis {String(review.receipt.valid_until)}. Ein erneuter Klick erzeugt ausschließlich eine neue befristete administrative Quittung für denselben unveränderten Zeugen.</p>}
{eligible && <>
<label><input type="checkbox" checked={checked} disabled={busy} onChange={e => setChecked(e.target.checked)}/>
Ich habe genau den Fall 221, die erhaltenen Originalsignaturen, Dateibindungen und Nichtstartbeweiskette einschließlich Originalhelper 1304 und Sharingfehler 32 geprüft. Ich bestätige ausschließlich den zusätzlichen fehlgeschlagenen Nichtstartabschluss für Job 94047873/Grant 97e705b8 und Kontrollspalt 221, ohne Erfolg, Bereitschaft oder Jobfreigabe.</label>
<button disabled={busy || !checked} onClick={() => void confirm()}>SIMULIERT: Exakten SYSTEM-Nichtstart 221 bestätigen</button>
</>}
{review.receipt && eligible && <a href={path + '/' + encodeURIComponent(review.request_id) + '/receipt'} download="windows-system-nonstart-221.json">Signierte administrative Quittung herunterladen</a>}
</>}
</section>;
}