From cafd13bca92b26a6595530c144d585f353a98ac9 Mon Sep 17 00:00:00 2001 From: Kevin Janssen Date: Mon, 16 Nov 2026 13:30:31 +0100 Subject: [PATCH] Deploy reviewed Windows sync alignment with schema 20 server Bind the administrative connection-205 review to original signed history and preserve closed readiness. Include the qualified server dependency closure, UI review, native ARM64 build provenance, and guarded deployment evidence. Migration, API/gateway replacement and TLS checks passed with unchanged job authority, protected mounts and time/database services; native Windows receipt application remains separate. --- Cargo.lock | 24 + Cargo.toml | 2 +- crates/agent-windows/Cargo.toml | 13 +- crates/domain/src/agent_update.rs | 26 +- .../domain/src/agent_update_provisioning.rs | 91 +- crates/domain/src/jobs.rs | 22 + crates/domain/src/lib.rs | 2 + crates/domain/src/windows_reboot.rs | 20 + crates/domain/src/windows_sync_alignment.rs | 310 +++++++ crates/server/src/agent_time.rs | 485 ++++++++++- crates/server/src/agent_update_health.rs | 36 +- crates/server/src/main.rs | 2 + crates/server/src/synchronization.rs | 5 + crates/server/src/windows_policy.rs | 71 +- crates/server/src/windows_sync_alignment.rs | 512 ++++++++++++ crates/time-attestation/src/lib.rs | 67 +- crates/time-broker-linux/src/native.rs | 1 + crates/update-history/Cargo.toml | 18 + crates/update-history/src/lib.rs | 775 ++++++++++++++++++ crates/updater-handoff/src/lib.rs | 299 ++++++- .../updater-handoff/tests/handoff_contract.rs | 243 +++++- crates/updater-worker/Cargo.toml | 8 + deploy/server_build_only.py | 137 ++++ deploy/server_deploy_205.py | 165 ++++ docs/evidence/server205-deployment.json | 57 ++ docs/updater-original-time-generation.md | 97 +++ ...ndows-sync-alignment-205-implementation.md | 207 +++++ migrations/0020_windows_sync_alignment.sql | 68 ++ web/src/api.ts | 8 + web/src/main.tsx | 16 +- web/src/safety.test.tsx | 13 + web/src/safety.ts | 10 +- web/src/sync-alignment-review.test.ts | 21 + web/src/sync-alignment-review.tsx | 77 ++ 34 files changed, 3865 insertions(+), 43 deletions(-) create mode 100644 crates/domain/src/windows_reboot.rs create mode 100644 crates/domain/src/windows_sync_alignment.rs create mode 100644 crates/server/src/windows_sync_alignment.rs create mode 100644 crates/update-history/Cargo.toml create mode 100644 crates/update-history/src/lib.rs create mode 100644 deploy/server_build_only.py create mode 100644 deploy/server_deploy_205.py create mode 100644 docs/evidence/server205-deployment.json create mode 100644 docs/updater-original-time-generation.md create mode 100644 docs/windows-sync-alignment-205-implementation.md create mode 100644 migrations/0020_windows_sync_alignment.sql create mode 100644 web/src/sync-alignment-review.test.ts create mode 100644 web/src/sync-alignment-review.tsx diff --git a/Cargo.lock b/Cargo.lock index 49f21ba..6097c6e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2242,11 +2242,13 @@ name = "rmm-agent-windows" version = "0.1.0" dependencies = [ "anyhow", + "base64 0.22.1", "cc", "chrono", "ed25519-dalek", "fs2", "futures-util", + "hex", "prost", "rand 0.9.5", "rcgen", @@ -2255,6 +2257,8 @@ dependencies = [ "rmm-domain", "rmm-protocol", "rmm-time-attestation", + "rmm-update-history", + "rmm-updater", "rmm-updater-handoff", "rusqlite", "rustls", @@ -2430,6 +2434,23 @@ dependencies = [ "uuid", ] +[[package]] +name = "rmm-update-history" +version = "0.1.0" +dependencies = [ + "anyhow", + "chrono", + "ed25519-dalek", + "hex", + "rmm-agent-core", + "rmm-domain", + "rmm-updater", + "rmm-updater-handoff", + "rusqlite", + "serde_json", + "uuid", +] + [[package]] name = "rmm-updater" version = "0.1.0" @@ -2481,8 +2502,11 @@ dependencies = [ "ed25519-dalek", "hex", "libc", + "prost", "rmm-agent-core", "rmm-domain", + "rmm-protocol", + "rmm-update-history", "rmm-updater", "rmm-updater-handoff", "rmm-updater-linux", diff --git a/Cargo.toml b/Cargo.toml index fdae001..7d4ed38 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [workspace] resolver = "2" exclude = ["crates/oidc-auth"] -members = ["crates/domain", "crates/protocol", "crates/persistence", "crates/server", "crates/agent-linux", "crates/agent-core", "crates/agent-windows", "crates/agent", "crates/privileged-helper", "crates/updater", "crates/updater-handoff", "crates/updater-linux", "crates/updater-worker", "crates/time-attestation", "crates/time-source-linux", "crates/time-broker-linux"] +members = ["crates/domain", "crates/protocol", "crates/persistence", "crates/server", "crates/agent-linux", "crates/agent-core", "crates/agent-windows", "crates/agent", "crates/privileged-helper", "crates/updater", "crates/updater-handoff", "crates/updater-linux", "crates/updater-worker", "crates/update-history", "crates/time-attestation", "crates/time-source-linux", "crates/time-broker-linux"] [workspace.package] version = "0.1.0" diff --git a/crates/agent-windows/Cargo.toml b/crates/agent-windows/Cargo.toml index b05d0ad..4e910fb 100644 --- a/crates/agent-windows/Cargo.toml +++ b/crates/agent-windows/Cargo.toml @@ -13,8 +13,14 @@ name = "rmm-helper-windows" path = "src/bin/rmm-helper-windows.rs" required-features = ["system-helper"] +[[bin]] +name = "rmm-updater-windows" +path = "src/bin/rmm-updater-windows.rs" +required-features = ["system-helper"] + [dependencies] anyhow.workspace = true +base64 = "=0.22.1" chrono.workspace = true futures-util.workspace = true prost.workspace = true @@ -33,6 +39,10 @@ rmm-agent-core = { path = "../agent-core" } rmm-protocol = { path = "../protocol" } rmm-time-attestation = { path = "../time-attestation" } rmm-updater-handoff = { path = "../updater-handoff" } +rmm-updater = { path = "../updater" } +hex.workspace = true +ed25519-dalek = "=2.2.0" +rmm-update-history = { path = "../update-history" } rusqlite = { version = "0.32.1", features = ["bundled"] } fs2 = "0.4.3" x509-parser = { version = "=0.18.1", features = ["verify"] } @@ -42,11 +52,10 @@ rcgen = { version = "=0.14.10", default-features = false, features = ["crypto", cc = "=1.11.1" [target.'cfg(windows)'.dependencies] -windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_ApplicationInstallationAndServicing", "Win32_System_EventLog", "Win32_System_Diagnostics_ToolHelp", "Win32_System_JobObjects", "Win32_System_Pipes", "Win32_System_SystemInformation", "Win32_System_Registry", "Win32_System_Memory", "Win32_System_Services", "Win32_System_Threading"] } +windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_ApplicationInstallationAndServicing", "Win32_System_EventLog", "Win32_System_Diagnostics_ToolHelp", "Win32_System_JobObjects", "Win32_System_Pipes", "Win32_System_SystemInformation", "Win32_System_Registry", "Win32_System_Memory", "Win32_System_Services", "Win32_System_Threading", "Win32_System_Shutdown"] } [[example]] name = "windows_reviewed_recovery" required-features = ["system-helper"] [dev-dependencies] -ed25519-dalek = "=2.2.0" diff --git a/crates/domain/src/agent_update.rs b/crates/domain/src/agent_update.rs index 3d2a2f0..86b0cec 100644 --- a/crates/domain/src/agent_update.rs +++ b/crates/domain/src/agent_update.rs @@ -492,7 +492,7 @@ impl UpdateInflightProof { || !self.delegation.validate() || !digest(&self.head_sha256) || self.events.is_empty() - || self.events.len() > 16 + || self.events.len() > rmm_updater_handoff::MAX_V2_EVENTS || self.handoff_record.len() > 21846 { return Err("UPDATE_INFLIGHT_LIMIT"); @@ -509,8 +509,30 @@ impl UpdateInflightProof { } Ok(raw) } + let handoff_record = bounded(&self.handoff_record)?; + if self.events.len() > rmm_updater_handoff::MAX_EVENTS { + let handoff: rmm_updater_handoff::Handoff = serde_json::from_slice(&handoff_record) + .map_err(|_| "UPDATE_INFLIGHT_WINDOWS_CLOCK_RECORD")?; + let limit = if handoff.schema_version == 2 { + rmm_updater_handoff::MAX_V2_EVENTS + } else if handoff.pin_transition + == rmm_updater_handoff::PinTransition::WindowsCodePairClockV1 + { + rmm_updater_handoff::MAX_WINDOWS_CLOCK_EVENTS + } else { + rmm_updater_handoff::MAX_EVENTS + }; + if self.events.len() > limit + || handoff + .bytes() + .map_err(|_| "UPDATE_INFLIGHT_WINDOWS_CLOCK_RECORD")? + != handoff_record + { + return Err("UPDATE_INFLIGHT_PROFILE_LIMIT"); + } + } Ok(DecodedInflightProof { - handoff_record: bounded(&self.handoff_record)?, + handoff_record, events: self .events .iter() diff --git a/crates/domain/src/agent_update_provisioning.rs b/crates/domain/src/agent_update_provisioning.rs index 4349e10..e557e2f 100644 --- a/crates/domain/src/agent_update_provisioning.rs +++ b/crates/domain/src/agent_update_provisioning.rs @@ -244,20 +244,14 @@ impl LocalUpdatePolicy { return false; }; let names: Vec<_> = self.services.iter().map(|v| v.unit.as_str()).collect(); - self.schema_version == 1 + let linux = self.schema_version == 1 && self.profile == "linux_general_full_v1" - && !self.tenant_id.is_nil() - && !self.asset_id.is_nil() - && !self.agent_id.is_nil() - && self.enrollment_generation > 0 - && self.assignment_version > 0 && self.ledger_path == "/var/lib/rmm-helper/consumption.sqlite" && self.lock_path == "/var/lib/rmm-helper/executor.lock" && self.installed_record_path == "/var/lib/rmm-agent-updater/installed-record.json" && self.keyring_path == "/etc/rmm-agent-updater/keyring.json" && self.health_pin_path == "/etc/rmm-agent-updater/health-key.json" && self.registry_path == "/etc/rmm-agent-updater/reader-registry.json" - && digest(&self.reader_registry_sha256) && (names == SERVICES || names == [ @@ -266,11 +260,30 @@ impl LocalUpdatePolicy { SERVICES[2], "rmm-apt-helper.service", ]) - && self.services.iter().all(|v| digest(&v.unit_sha256)) && self.updater_service.unit == "rmm-agent-updater.service" + && baseline.record.platform == Platform::LinuxX64; + let windows = self.schema_version == 2 + && self.profile == "windows_code_pair_clock_v1" + && self.ledger_path == r"C:\ProgramData\RustDiscoverySystem\state\ledger.sqlite" + && self.lock_path == r"C:\ProgramData\RustDiscoverySystem\state\executor.lock" + && self.installed_record_path + == r"C:\ProgramData\RustDiscoveryUpdater\installed-record.json" + && self.keyring_path == r"C:\ProgramData\RustDiscoveryUpdater\keyring.json" + && self.health_pin_path == r"C:\ProgramData\RustDiscoveryUpdater\health-key.json" + && self.registry_path == r"C:\ProgramData\RustDiscoveryUpdater\reader-registry.json" + && names == ["RmmDiscoveryWindows", "RmmDiscoverySystemHelper"] + && self.updater_service.unit == "RmmDiscoveryUpdater" + && baseline.record.platform == Platform::WindowsX64; + (linux || windows) + && !self.tenant_id.is_nil() + && !self.asset_id.is_nil() + && !self.agent_id.is_nil() + && self.enrollment_generation > 0 + && self.assignment_version > 0 + && digest(&self.reader_registry_sha256) + && self.services.iter().all(|v| digest(&v.unit_sha256)) && digest(&self.updater_service.unit_sha256) && digest(&self.updater_binary_sha256) - && baseline.record.platform == Platform::LinuxX64 && self.initial_record_sha256 == hash(&baseline.payload_bytes) && self.initial_manifest_sha256 == baseline.record.manifest_sha256 && self.initial_activation_floor == baseline.record.activation_floor @@ -288,3 +301,63 @@ impl LocalUpdatePolicy { Ok((policy, hash(raw))) } } + +/// Deterministic PUBLIC record metadata only. This does not authenticate an +/// original, a release, Health or policy, and grants no namespace/ledger access. +/// Each native private BuiltRecord constructor must first verify its actual +/// Original and signed Health independently, then retain its own effect guard. +pub fn assemble_updated_record( + update: &crate::agent_update::ResolvedAgentUpdate, + prior_raw: &[u8], + handoff_sha256: &str, + signed: &rmm_updater_handoff::SignedHealth, + receipt: &rmm_updater_handoff::HealthReceipt, +) -> Result { + if !update.validate() + || !digest(handoff_sha256) + || receipt.handoff_sha256 != handoff_sha256 + || receipt.ready + || signed.signature.len() != 64 + || serde_json::to_vec(receipt).map_err(|_| "UPDATE_RECORD_RECEIPT_CODEC")? != signed.payload + { + return Err("UPDATE_RECORD_INPUT"); + } + let prior = InstalledReleaseRecord::from_bytes(prior_raw)?; + let parent = prior.release_envelope.decode()?; + let target = update.manifest()?; + let old_sha256 = hash(prior_raw); + if prior.rolled_back + || old_sha256 != update.predecessor.installed_record_sha256 + || prior.manifest_sha256 != update.predecessor.manifest_sha256 + || parent.manifest.release_id != update.predecessor.release_id + || parent.manifest.release_sequence != update.predecessor.release_sequence + || parent.manifest.artifacts[0].sha256 != update.predecessor.agent_sha256 + || parent.manifest.artifacts[1].sha256 != update.predecessor.helper_sha256 + || prior.platform != target.platform + || target.release_sequence <= prior.activation_floor + || receipt.issued_at < prior.activated_at + { + return Err("UPDATE_RECORD_PREDECESSOR_OR_FLOOR"); + } + let record = InstalledReleaseRecord { + schema_version: 1, + profile: "decoder_compatible_handoff_v1".into(), + platform: target.platform, + release_envelope: update.release_envelope.clone(), + manifest_sha256: update.manifest_sha256.clone(), + activation_floor: target.release_sequence, + activated_at: receipt.issued_at, + previous_record_sha256: Some(old_sha256.clone()), + activation_evidence: ActivationEvidence::Updated { + handoff_sha256: handoff_sha256.into(), + signed_health_sha256: hash( + &serde_json::to_vec(signed).map_err(|_| "UPDATE_RECORD_HEALTH_CODEC")?, + ), + }, + rolled_back: false, + }; + if hash(&record.bytes()?) == old_sha256 { + return Err("UPDATE_RECORD_SAME_BYTES"); + } + Ok(record) +} diff --git a/crates/domain/src/jobs.rs b/crates/domain/src/jobs.rs index 107b5a7..d4bc6de 100644 --- a/crates/domain/src/jobs.rs +++ b/crates/domain/src/jobs.rs @@ -368,6 +368,15 @@ impl Action { && self.full_maintenance() && self.script_platform() == Some("windows") && self.validate()) + || (identity == "system" + && matches!( + self, + Self::Reboot { + reconnect_timeout_seconds: crate::windows_reboot::RECONNECT_SECONDS, + .. + } + ) + && self.validate()) } pub fn full_maintenance(&self) -> bool { matches!( @@ -482,6 +491,19 @@ impl Action { update.predecessor.helper_sha256 )) } + Self::Reboot { + reconnect_timeout_seconds, + .. + } if identity == "system" || has("windows.base/1") => { + identity == "system" + && *reconnect_timeout_seconds == crate::windows_reboot::RECONNECT_SECONDS + && has("windows.base/1") + && !has("linux.base/1") + && has("rmm.sync.v1") + && has("helper.system.v1") + && has("system:reboot") + && has(crate::windows_reboot::CAPABILITY) + } Self::RunScript { interpreter, windows_execution_profile, diff --git a/crates/domain/src/lib.rs b/crates/domain/src/lib.rs index a1ee984..e8842b8 100644 --- a/crates/domain/src/lib.rs +++ b/crates/domain/src/lib.rs @@ -7,7 +7,9 @@ pub mod inventory_document; pub mod jobs; pub mod reconciliation; pub mod windows_echo_probe; +pub mod windows_reboot; pub mod windows_echo_completion; +pub mod windows_sync_alignment; pub mod windows_execution; pub mod windows_sync_history; diff --git a/crates/domain/src/windows_reboot.rs b/crates/domain/src/windows_reboot.rs new file mode 100644 index 0000000..ff5aa85 --- /dev/null +++ b/crates/domain/src/windows_reboot.rs @@ -0,0 +1,20 @@ +//! The first Windows reboot capability is deliberately a fixed, separately +//! enabled SYSTEM action. Existing Linux Reboot payload bytes are unchanged. +use crate::jobs::{Action, JobPayload}; +pub const CAPABILITY: &str = "windows.reboot/1"; +pub const RECONNECT_SECONDS: u32 = 180; +pub const RUNTIME_SECONDS: u32 = 60; +pub const ANNOUNCEMENT_SECONDS: u32 = 5; +pub fn supported(job: &JobPayload) -> bool { + job.execution_identity == "system" + && job.max_runtime_seconds == RUNTIME_SECONDS + && (1..=65536).contains(&job.max_output_bytes) + && job.action.validate() + && matches!( + job.action, + Action::Reboot { + reconnect_timeout_seconds: RECONNECT_SECONDS, + .. + } + ) +} diff --git a/crates/domain/src/windows_sync_alignment.rs b/crates/domain/src/windows_sync_alignment.rs new file mode 100644 index 0000000..92e92df --- /dev/null +++ b/crates/domain/src/windows_sync_alignment.rs @@ -0,0 +1,310 @@ +//! Exact connection-205 administrative closure. Neither a lease nor 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-sync-admin-closed-alignment.v1"; +pub const FIRST: Uuid = Uuid::from_u128(0x1a4758ad0b39449e855116846851b09a); +pub const SECOND: Uuid = Uuid::from_u128(0x2af359c55b5c4992b4451c00e271a288); +pub const FIRST_REQUEST: Uuid = Uuid::from_u128(0x1f55d56f65b74e81bf8889c6765fe7a6); +pub const SECOND_REQUEST: Uuid = Uuid::from_u128(0xed99c35576214846b8d03f534096eed4); +pub const BOOT: Uuid = Uuid::from_u128(0xa9ad08955a968f2c8fb6cfdc2d5225ea); +pub const ECHO_JOB: Uuid = Uuid::from_u128(0x645ad11b9ecd4efe8f928ad2fb6ed5cf); +pub const ECHO_ATTEMPT: Uuid = Uuid::from_u128(0xe2ee25cd0e234c3caaa23048d232622a); +pub const EXPIRED_JOB: Uuid = Uuid::from_u128(0x0a50aae9a7844535b62fef24c301d546); +pub const EXPIRED_ATTEMPT: Uuid = Uuid::from_u128(0x78295f744565459a87b0641a8b95feec); +pub const MAX_WITNESS_BYTES: usize = 768 * 1024; +pub const FILE_ROLES: [&str; 6] = [ + "telemetry", + "consumption", + "agent_lock", + "helper_ledger", + "helper_lock", + "system_intents", +]; +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct NativeFile { + pub role: String, + /// Independently measured BY_HANDLE_FILE_INFORMATION volume/high/low tuple. + pub file_id: Option<[u32; 3]>, + pub sha256: Option, +} +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct Counts { + pub agent_jobs: u64, + pub agent_consumed: u64, + pub agent_starts: u64, + pub agent_outcomes: u64, + pub helper_consumed: u64, + pub helper_starts: u64, + pub helper_outcomes: u64, + pub system_intents: u64, +} +#[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 counts: Counts, + pub original_requests: [Vec; 2], + pub original_responses: [SignedDecision; 2], + pub echo_offer: Vec, + pub echo_start: Vec, + pub echo_outcome: Vec, + pub echo_result: Vec, + pub echo_completion_receipt: Vec, + pub expired_offer: Vec, +} +impl Witness { + pub fn digest(&self) -> Option { + 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 == 205 + && !self.agent_journal_id.is_nil() + && !self.helper_journal_id.is_nil() + && self.agent_journal_id != self.helper_journal_id + && self.agent_checkpoint == 10137 + && self.helper_checkpoint >= 148 + && 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, + ] + .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: 2, + agent_consumed: 1, + agent_starts: 1, + agent_outcomes: 1, + helper_consumed: 0, + helper_starts: 0, + helper_outcomes: 0, + system_intents: 0, + }) + && 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.echo_offer, + &self.echo_start, + &self.echo_outcome, + &self.echo_result, + &self.echo_completion_receipt, + &self.expired_offer, + ] + .iter() + .all(|v| !v.is_empty() && v.len() <= 131072) + && 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 key_id: String, + pub issued_at: DateTime, + pub valid_until: DateTime, + 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) -> 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.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) + } +} + +#[cfg(test)] +mod tests { + use super::*; + // Codec/profile fixture only: cryptographic original validation is independent. + fn witness() -> Witness { + Witness { + schema_version: 1, + tenant_id: TENANT, + asset_id: ASSET, + agent_id: AGENT, + enrollment_generation: 1, + assignment_version: 1, + boot_id: BOOT, + connection_generation: 205, + agent_journal_id: Uuid::from_u128(1), + helper_journal_id: Uuid::from_u128(2), + agent_checkpoint: 10137, + helper_checkpoint: 155, + agent_last_decision: SECOND, + helper_last_decision: FIRST, + verification_key_id: hash(&[0; 32]), + verification_public_key_hex: "00".repeat(32), + binding_sha256: "ab".repeat(32), + helper_binding_sha256: "ab".repeat(32), + files: std::array::from_fn(|i| NativeFile { + role: FILE_ROLES[i].into(), + file_id: Some([1, i as u32 + 1, 1]), + sha256: Some("cd".repeat(32)), + }), + agent_inventory_sha256: "ef".repeat(32), + consumption_inventory_sha256: "12".repeat(32), + helper_inventory_sha256: "34".repeat(32), + counts: Counts { + agent_jobs: 2, + agent_consumed: 1, + agent_starts: 1, + agent_outcomes: 1, + helper_consumed: 0, + helper_starts: 0, + helper_outcomes: 0, + system_intents: 0, + }, + original_requests: [vec![1], vec![2]], + original_responses: std::array::from_fn(|_| SignedDecision { + decision_bytes: vec![1], + signature: vec![0; 64], + }), + echo_offer: vec![1], + echo_start: vec![1], + echo_outcome: vec![1], + echo_result: vec![1], + echo_completion_receipt: vec![1], + expired_offer: vec![1], + } + } + #[test] + fn closed_profile_never_accepts_new_consumption_stale_capture_or_other_incident() { + let w = witness(); + assert!(w.valid()); + for mutation in 0..6 { + let mut bad = w.clone(); + match mutation { + 0 => bad.connection_generation = 150, + 1 => bad.helper_checkpoint = 147, + 2 => bad.counts.helper_consumed = 1, + 3 => bad.counts.agent_jobs = 3, + 4 => bad.agent_last_decision = FIRST, + _ => bad.files[0].file_id = None, + }; + assert!(!bad.valid()); + } + } + #[test] + fn receipt_is_exactly_bounded_and_cannot_be_readiness_or_real_human_approval() { + let w = witness(); + let now = Utc::now(); + let r = Receipt { + domain: DOMAIN.into(), + schema_version: 1, + receipt_id: Uuid::from_u128(3), + request_id: Uuid::from_u128(4), + witness_sha256: w.digest().unwrap(), + key_id: w.verification_key_id.clone(), + witness: w, + issued_at: now, + valid_until: now + Duration::minutes(5), + confirmed_by: TEST_PRINCIPAL.into(), + approval_origin: "dev_test_browser_simulation".into(), + testsimulation: true, + ready: false, + helper_ready: false, + unlock: false, + }; + assert!(r.valid(now)); + assert!(!r.valid(r.valid_until)); + assert!(!r.valid(now - Duration::nanoseconds(1))); + for mutation in 0..7 { + let mut bad = r.clone(); + match mutation { + 0 => bad.ready = true, + 1 => bad.helper_ready = true, + 2 => bad.unlock = true, + 3 => bad.testsimulation = false, + 4 => bad.valid_until += Duration::nanoseconds(1), + 5 => bad.confirmed_by = "Administrator".into(), + _ => bad.witness.helper_checkpoint += 1, + }; + assert!(!bad.valid(now)); + } + } +} diff --git a/crates/server/src/agent_time.rs b/crates/server/src/agent_time.rs index 52d6ee7..45f16bd 100644 --- a/crates/server/src/agent_time.rs +++ b/crates/server/src/agent_time.rs @@ -1,5 +1,6 @@ //! Passive protocol clock material only: never a sync decision or job grant. //! Context comes from current mTLS identity + locked tenant installation row. +use anyhow::{Context as _, ensure}; use axum::{ Extension, Json, Router, body::Bytes, @@ -7,14 +8,25 @@ use axum::{ http::{HeaderMap, StatusCode}, routing::post, }; +use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; +use chrono::Utc; +use rmm_domain::{ + agent_update::{self as update, UpdateDelegation}, + jobs::{Action, ExecutionPermitPayload, JobPayload, PlanPayload, encode, hash}, + reconciliation::ReconcileDecisionPayload, +}; use rmm_time_attestation::{Request, SignedAttestation}; +use rmm_updater_handoff::Handoff; +use serde::{Deserialize, Serialize}; use sqlx::Row; +use sqlx::{Postgres, Transaction}; use std::{os::unix::fs::MetadataExt, sync::OnceLock, time::Duration}; use tokio::{ io::{AsyncReadExt, AsyncWriteExt}, net::UnixStream, sync::Semaphore, }; +use uuid::Uuid; const SOCKET: &str = "/run/rmm-time-source/broker.sock"; const MAX_FRAME: usize = 8192; @@ -126,9 +138,16 @@ async fn issue( let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant) .await .map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?; + if c.role == rmm_time_attestation::Role::Updater { + // Same lock order as Hello/Sync/start reservation. The additional job + // checks below must not invert their installation/job row lock order. + crate::agent_service::control_lock(&mut tx, tenant, agent) + .await + .map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?; + } // No sync_ready precondition: the independent time check is needed before // the first signed reconciliation, including its strictly negative paths. - let row = sqlx::query("SELECT asset_id,enrollment_generation,assignment_version,connection_generation,connection_boot_id,capabilities FROM agent_installations WHERE tenant_id=$1 AND agent_id=$2 AND revoked_at IS NULL FOR SHARE") + let row = sqlx::query("SELECT asset_id,enrollment_generation,assignment_version,connection_generation,connection_boot_id,capabilities,sequence_regressed,sync_recovery_required FROM agent_installations WHERE tenant_id=$1 AND agent_id=$2 AND revoked_at IS NULL FOR SHARE") .bind(tenant).bind(agent).fetch_optional(&mut *tx).await .map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?.ok_or(StatusCode::FORBIDDEN)?; let same = row.get::("asset_id") == c.asset_id @@ -136,8 +155,6 @@ async fn issue( == Some(c.enrollment_generation) && u64::try_from(row.get::("assignment_version")).ok() == Some(c.assignment_generation) - && u64::try_from(row.get::("connection_generation")).ok() - == Some(c.connection_generation) && row.get::, _>("connection_boot_id") == Some(c.windows_boot_id) && row .get::("capabilities") @@ -146,14 +163,476 @@ async fn issue( if !same { return Err(StatusCode::CONFLICT); } + let current_generation = u64::try_from(row.get::("connection_generation")) + .map_err(|_| StatusCode::CONFLICT)?; + let original_deadline = if current_generation != c.connection_generation { + if row.get::("sequence_regressed") || row.get::("sync_recovery_required") + { + return Err(StatusCode::CONFLICT); + } + Some( + original_updater_bridge(s, &mut tx, c, current_generation) + .await + .map_err(|_| StatusCode::CONFLICT)?, + ) + } else { + None + }; // Hold the shared installation lock through this bounded local query: // revoke/reassignment/connection changes cannot race the signing moment. let response = tokio::time::timeout(Duration::from_millis(300), broker(&request)) .await .map_err(|_| StatusCode::SERVICE_UNAVAILABLE)? .map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?; + // A broker query never extends the original job's deadline. Discard its + // passive signature if the bound expired while this request was in flight. + if original_deadline.is_some_and(|finish| { + u64::try_from(Utc::now().timestamp()).map_or(true, |now| now >= finish) + }) { + return Err(StatusCode::CONFLICT); + } tx.commit() .await .map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?; Ok(Json(response)) } + +/// Public original metadata retained once by the EXISTING validated Sync path. +/// It supplies no new approval/start/ready authority and contains no key bytes. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct RetainedUpdaterContext { + schema_version: u32, + job_id: Uuid, + attempt_id: Uuid, + grant_id: Uuid, + handoff_sha256: String, + delegation_sha256: String, + handoff_base64url: String, + delegation_base64url: String, +} +impl RetainedUpdaterContext { + fn capture(h: &Handoff, d: &UpdateDelegation) -> anyhow::Result { + let handoff = h.bytes()?; + let delegation = serde_json::to_vec(d)?; + ensure!( + d.validate() + && d.handoff_sha256 == hash(&handoff) + && d.owner_nonce == h.owner_nonce + && d.boot_id == h.boot_id + && d.updater.image_sha256 == h.updater_sha256 + && d.original_helper.image_sha256 == h.predecessor.helper_sha256 + && u64::try_from(d.prepared_at.timestamp())? == h.consumed_at, + "TIME_UPDATE_ORIGINAL_DELEGATION" + ); + Ok(Self { + schema_version: 1, + job_id: h.attempt.job_id, + attempt_id: h.attempt.attempt_id, + grant_id: h.attempt.grant_id, + handoff_sha256: hash(&handoff), + delegation_sha256: hash(&delegation), + handoff_base64url: URL_SAFE_NO_PAD.encode(handoff), + delegation_base64url: URL_SAFE_NO_PAD.encode(delegation), + }) + } + fn open(&self) -> anyhow::Result<(Handoff, UpdateDelegation)> { + fn bytes(raw: &str, limit: usize) -> anyhow::Result> { + ensure!( + raw.len() <= limit.div_ceil(3) * 4, + "TIME_UPDATE_CONTEXT_SIZE" + ); + let decoded = URL_SAFE_NO_PAD.decode(raw)?; + ensure!( + !decoded.is_empty() + && decoded.len() <= limit + && URL_SAFE_NO_PAD.encode(&decoded) == raw, + "TIME_UPDATE_CONTEXT_BASE64" + ); + Ok(decoded) + } + let hraw = bytes(&self.handoff_base64url, 32768)?; + let draw = bytes(&self.delegation_base64url, 8192)?; + let h: Handoff = serde_json::from_slice(&hraw)?; + let d: UpdateDelegation = serde_json::from_slice(&draw)?; + ensure!( + h.bytes()? == hraw + && serde_json::to_vec(&d)? == draw + && Self::capture(&h, &d)? == *self, + "TIME_UPDATE_CONTEXT_BINDING" + ); + Ok((h, d)) + } +} +/// Call only AFTER the full original UpdateInflight proof/job/permit validation +/// in the same existing Sync transaction/control lock. Changed bytes under the +/// original grant are refused; no ON CONFLICT ignore or replacement. +pub(crate) async fn retain_validated_updater_context( + tx: &mut Transaction<'_, Postgres>, + h: &Handoff, + d: &UpdateDelegation, +) -> anyhow::Result<()> { + let value = serde_json::to_value(RetainedUpdaterContext::capture(h, d)?)?; + let existing=sqlx::query_scalar::<_,serde_json::Value>("SELECT data FROM audit_events WHERE tenant_id=$1 AND event_type='agent_update_original_context' AND data->>'grant_id'=$2 LIMIT 2") + .bind(h.attempt.tenant_id).bind(h.attempt.grant_id.to_string()).fetch_all(&mut **tx).await?; + ensure!( + existing.len() <= 1, + "TIME_UPDATE_DUPLICATE_ORIGINAL_CONTEXT" + ); + if let Some(old) = existing.first() { + ensure!(*old == value, "TIME_UPDATE_ORIGINAL_CONTEXT_CHANGED"); + return Ok(()); + } + sqlx::query("INSERT INTO audit_events VALUES($1,$2,'job-service','agent_update_original_context',$3,now())") + .bind(h.attempt.tenant_id).bind(Uuid::new_v4()).bind(value).execute(&mut **tx).await?; + Ok(()) +} +fn signed_bytes(s: &crate::State, raw: &[u8], signature: &[u8]) -> anyhow::Result<()> { + use openssl::{ + pkey::{Id, PKey}, + sign::Verifier, + }; + let key = PKey::public_key_from_raw_bytes(&s.job_signer.public_key()?, Id::ED25519)?; + ensure!( + signature.len() == 64 + && Verifier::new_without_digest(&key)?.verify_oneshot(signature, raw)?, + "TIME_UPDATE_SIGNATURE" + ); + Ok(()) +} +fn original_role_context( + c: &rmm_time_attestation::Context, + current: u64, + original: u64, + boot: Uuid, + image: &str, +) -> bool { + c.role == rmm_time_attestation::Role::Updater + && c.binding_schema == 2 + && c.helper_image_sha256.is_none() + && c.updater_image_sha256.as_deref() == Some(image) + && current > original + && c.connection_generation == original + && c.windows_boot_id == boot +} +async fn original_updater_bridge( + s: &crate::State, + tx: &mut Transaction<'_, Postgres>, + c: &rmm_time_attestation::Context, + current: u64, +) -> anyhow::Result { + ensure!( + c.role == rmm_time_attestation::Role::Updater + && c.binding_schema == 2 + && c.helper_image_sha256.is_none() + && current > c.connection_generation, + "TIME_CURRENT_GENERATION_REQUIRED" + ); + // An exact single active job is required, not a historical latest grant. + let rows=sqlx::query("SELECT j.payload,j.payload_hash,j.state,j.result,j.cancel_requested,j.start_reserved,p.payload AS plan_payload,p.plan_hash,z.authorization_id,z.plan_id,z.principal AS approver,g.grant_id,g.payload AS permit_payload,g.signature AS permit_signature FROM jobs j JOIN operations o USING(tenant_id,operation_id) JOIN authorizations z ON z.tenant_id=o.tenant_id AND z.authorization_id=o.authorization_id JOIN approval_requests a ON a.tenant_id=o.tenant_id AND a.operation_id=o.operation_id JOIN operation_plans p ON p.tenant_id=a.tenant_id AND p.plan_id=a.plan_id JOIN execution_permits g ON g.tenant_id=j.tenant_id AND g.job_id=j.job_id AND g.attempt_id=j.attempt_id WHERE j.tenant_id=$1 AND j.agent_id=$2 AND j.state IN ('running','verifying') AND a.approval_state='approved' AND z.revoked_at IS NULL LIMIT 2 FOR SHARE OF j,z,a") + .bind(c.tenant_id).bind(c.agent_id).fetch_all(&mut **tx).await?; + ensure!(rows.len() == 1, "TIME_UPDATE_ONE_ACTIVE_ORIGINAL_JOB"); + let row = &rows[0]; + ensure!( + row.get::, _>("result").is_none() + && !row.get::("cancel_requested") + && row.get::("start_reserved"), + "TIME_UPDATE_ORIGINAL_JOB_CLOSED" + ); + let raw: Vec = row.get("payload"); + ensure!(raw.len() <= 512 * 1024, "TIME_UPDATE_JOB_SIZE"); + let job: JobPayload = serde_json::from_slice(&raw)?; + let Action::UpdateAgent { update } = &job.action else { + anyhow::bail!("TIME_UPDATE_ACTION_REQUIRED") + }; + ensure!( + update.validate() + && update.execution_identity() == Some("system") + && job.execution_identity == "system" + && job.max_runtime_seconds == 600 + && encode(&job)? == raw + && hash(&raw) == row.get::("payload_hash") + && job.tenant_id == c.tenant_id + && job.asset_id == c.asset_id + && job.agent_id == c.agent_id + && job.enrollment_generation == c.enrollment_generation + && job.assignment_version == c.assignment_generation + && update.updater.binary_sha256 == c.updater_image_sha256.as_deref().unwrap_or(""), + "TIME_UPDATE_IMMUTABLE_JOB_BINDING" + ); + let plan_raw: Vec = row.get("plan_payload"); + ensure!( + plan_raw.len() <= rmm_domain::MAX_MESSAGE, + "TIME_UPDATE_PLAN_SIZE" + ); + let plan: PlanPayload = serde_json::from_slice(&plan_raw)?; + crate::agent_updates::validate_job_binding(&plan, &job) + .map_err(|_| anyhow::anyhow!("TIME_UPDATE_PLAN_BINDING"))?; + ensure!( + encode(&plan)? == plan_raw + && hash(&plan_raw) == row.get::("plan_hash") + && row.get::("plan_id") == plan.plan_id, + "TIME_UPDATE_APPROVED_PLAN" + ); + let grant: Vec = row.get("permit_payload"); + let signature: Vec = row.get("permit_signature"); + ensure!(grant.len() <= 32768, "TIME_UPDATE_PERMIT_SIZE"); + signed_bytes(s, &grant, &signature)?; + let permit: ExecutionPermitPayload = serde_json::from_slice(&grant)?; + ensure!( + encode(&permit)? == grant + && permit.domain == "rmm.execution-permit" + && permit.schema_version == 1 + && permit.key_id == s.job_signer.key_id + && permit.agent_update_plan_id == Some(plan.plan_id) + && permit.tenant_id == job.tenant_id + && permit.asset_id == job.asset_id + && permit.agent_id == job.agent_id + && permit.enrollment_generation == job.enrollment_generation + && permit.assignment_version == job.assignment_version + && permit.job_id == job.job_id + && permit.attempt_id == job.attempt_id + && permit.execution_identity == "system" + && permit.grant_id == row.get::("grant_id") + && permit.authorization_id == row.get::("authorization_id") + && permit.plan_hash == hash(&plan_raw) + && permit.job_payload_hash == hash(&raw) + && permit.action == "update_agent" + && permit.max_runtime_seconds == 600, + "TIME_UPDATE_SIGNED_ORIGINAL_PERMIT" + ); + let contexts=sqlx::query_scalar::<_,serde_json::Value>("SELECT data FROM audit_events WHERE tenant_id=$1 AND event_type='agent_update_original_context' AND data->>'grant_id'=$2 LIMIT 2") + .bind(c.tenant_id).bind(permit.grant_id.to_string()).fetch_all(&mut **tx).await?; + ensure!(contexts.len() == 1, "TIME_UPDATE_ORIGINAL_CONTEXT_REQUIRED"); + let retained: RetainedUpdaterContext = serde_json::from_value(contexts[0].clone())?; + let (h, d) = retained.open()?; + ensure!( + update::handoff_matches_job(&h, &job) + && original_role_context( + c, + current, + h.connection_generation, + h.boot_id, + &h.updater_sha256 + ) + && h.attempt.plan_id == plan.plan_id + && h.attempt.grant_id == permit.grant_id + && h.attempt.authorization_id == permit.authorization_id + && h.attempt.plan_sha256 == permit.plan_hash + && d.updater.role == update::ParticipantRole::WindowsUpdater + && d.original_helper.role == update::ParticipantRole::WindowsHelper + && d.updater.image_sha256 == update.updater.binary_sha256 + && d.prepared_at >= permit.not_before + && d.prepared_at < permit.start_before, + "TIME_UPDATE_ORIGINAL_HEADER_BINDING" + ); + let original = update::OriginalHelperRequest { + job_bytes: &raw, + permit_bytes: &grant, + signature: &signature, + plan_hash: &permit.plan_hash, + authorization_id: permit.authorization_id, + }; + ensure!( + h.attempt.original_request_sha256 == hash(&encode(&original)?), + "TIME_UPDATE_ORIGINAL_REQUEST" + ); + // The CURRENT authoritative checkpoint must retain this exact inflight + // acknowledgement. Never fall back to an older matching decision. + let sync=sqlx::query("SELECT c.payload,c.signature,c.decision_id,c.journal_id,c.checkpoint,c.connection_generation,s.helper_journal_id,s.helper_checkpoint FROM agent_sync_state s JOIN sync_checkpoints c ON c.tenant_id=s.tenant_id AND c.agent_id=s.agent_id AND c.decision_id=s.decision_id WHERE s.tenant_id=$1 AND s.agent_id=$2") + .bind(c.tenant_id).bind(c.agent_id).fetch_optional(&mut **tx).await?.context("TIME_UPDATE_SIGNED_ACK_REQUIRED")?; + let decision_raw: Vec = sync.get("payload"); + let decision_signature: Vec = sync.get("signature"); + ensure!(decision_raw.len() <= 512 * 1024, "TIME_UPDATE_SYNC_SIZE"); + signed_bytes(s, &decision_raw, &decision_signature)?; + let decision: ReconcileDecisionPayload = serde_json::from_slice(&decision_raw)?; + let now = Utc::now(); + ensure!( + encode(&decision)? == decision_raw + && decision.valid_profile(decision.issued_at) + && decision.issued_at <= now + && decision.key_id == s.job_signer.key_id + && !decision.ready + && !decision.helper_ready + && decision.tenant_id == c.tenant_id + && decision.asset_id == c.asset_id + && decision.agent_id == c.agent_id + && decision.enrollment_generation == c.enrollment_generation + && decision.assignment_version == c.assignment_generation + && decision.boot_id == h.boot_id + && decision.connection_generation >= h.connection_generation + && decision.connection_generation <= current + && decision.decision_id == sync.get::("decision_id") + && decision.journal_id == sync.get::("journal_id") + && decision.journal_id == h.agent_journal_id + && Some(h.helper_journal_id) == sync.get::, _>("helper_journal_id") + && decision.helper_journal_id == Some(h.helper_journal_id) + && u64::try_from(sync.get::("checkpoint"))? == decision.checkpoint + && u64::try_from(sync.get::("helper_checkpoint"))? + == decision.helper_checkpoint + && u64::try_from(sync.get::("connection_generation"))? + == decision.connection_generation, + "TIME_UPDATE_CURRENT_SIGNED_ACK_BINDING" + ); + let attempts = decision + .attempts + .iter() + .filter(|a| a.job_id == job.job_id && a.attempt_id == job.attempt_id) + .collect::>(); + ensure!(attempts.len() == 1, "TIME_UPDATE_ORIGINAL_ACK_ATTEMPT"); + let ack = attempts[0]; + let inflight = ack + .update_inflight + .as_ref() + .context("TIME_UPDATE_INFLIGHT_REQUIRED")?; + ensure!( + ack.job_payload_hash == hash(&raw) + && ack.grant_id == Some(permit.grant_id) + && ack.authorization_id == Some(permit.authorization_id) + && ack.plan_hash.as_deref() == Some(permit.plan_hash.as_str()) + && ack.action == "update_agent" + && ack.execution_identity == "system" + && ack.outcome_state == "running" + && ack.outcome_bytes.is_empty() + && ack.outcome_sha256.is_none() + && ack.previous_outcome_sha256.is_none() + && ack.original_boot_id == Some(h.boot_id) + && !ack.unlock + && ack.reason == "AGENT_UPDATE_INFLIGHT" + && inflight.handoff_sha256 == retained.handoff_sha256 + && inflight.delegation_sha256 == retained.delegation_sha256 + && inflight.owner_nonce == h.owner_nonce + && inflight.finish_before == h.finish_before + && update::digest(&inflight.head_sha256) + && h.finish_before + == h.consumed_at + .checked_add(600) + .context("TIME_UPDATE_ORIGINAL_DEADLINE")? + && u64::try_from(now.timestamp())? >= h.consumed_at + && u64::try_from(now.timestamp())? < h.finish_before, + "TIME_UPDATE_EXACT_ORIGINAL_ACK_AND_DEADLINE" + ); + let approver: String = row.get("approver"); + let mut actors = vec![plan.principal.as_str(), approver.as_str()]; + actors.sort(); + actors.dedup(); + let locked=sqlx::query_scalar::<_,String>("SELECT principal FROM memberships WHERE tenant_id=$1 AND principal=ANY($2) AND revoked_at IS NULL FOR SHARE") + .bind(c.tenant_id).bind(&actors).fetch_all(&mut **tx).await?; + ensure!(locked.len() == actors.len(), "TIME_UPDATE_CURRENT_ACTORS"); + for actor in actors { + for permission in ["updates:apply", "system:execute"] { + crate::permissions::require(tx, actor, permission) + .await + .map_err(|_| anyhow::anyhow!("TIME_UPDATE_CURRENT_PERMISSION"))?; + } + } + Ok(h.finish_before) +} + +#[cfg(test)] +mod original_generation_tests { + use super::*; + fn retained_fixture() -> RetainedUpdaterContext { + use serde_json::json; + let id = Uuid::new_v4(); + let old = "11".repeat(32); + let new = "22".repeat(32); + let roles = [ + "agent_binary", + "helper_binary", + "windows_settings", + "windows_pin", + "windows_time_profile", + ]; + let h:Handoff=serde_json::from_value(json!({"schema_version":2, + "attempt":{"tenant_id":id,"asset_id":id,"agent_id":id,"enrollment_generation":1,"assignment_version":1, + "plan_id":id,"plan_sha256":old,"job_id":id,"attempt_id":id,"job_payload_sha256":old, + "grant_id":id,"authorization_id":id,"original_request_sha256":old,"original_start_witness_sha256":old}, + "agent_journal_id":id,"helper_journal_id":id,"helper_checkpoint":1,"previous_decision_id":id, + "boot_id":id,"connection_generation":7,"owner_nonce":id,"updater_sha256":old,"updater_policy_sha256":old, + "predecessor_record_sha256":old,"retained_state_sha256":old,"ledger_identity_sha256":old,"staged_files_sha256":old, + "predecessor":{"manifest_sha256":old,"agent_sha256":old,"helper_sha256":old,"pin_sha256":old}, + "target":{"manifest_sha256":new,"agent_sha256":new,"helper_sha256":new,"pin_sha256":new}, + "pin_transition":"windows_code_pair_clock_v1","pin_transition_sha256":old, + "files":roles.iter().map(|role|json!({"role":role,"old_sha256":old,"new_sha256":new})).collect::>(), + "stop_set":["windows_agent","windows_helper"],"consumed_at":100,"finish_before":700})).unwrap(); + let d: UpdateDelegation = serde_json::from_value( + json!({"schema_version":1,"handoff_sha256":hash(&h.bytes().unwrap()), + "owner_nonce":id,"boot_id":id,"prepared_at":"1970-01-01T00:01:40Z", + "updater":{"role":"windows_updater","pid":2,"birth":1,"image_sha256":old, + "security_principal":"S-1-5-18","service_instance_sha256":old}, + "original_helper":{"role":"windows_helper","pid":3,"birth":1,"image_sha256":old, + "security_principal":"S-1-5-18","service_instance_sha256":old}}), + ) + .unwrap(); + RetainedUpdaterContext::capture(&h, &d).unwrap() + } + #[test] + fn retained_original_context_binds_canonical_header_delegation_and_grant_without_reconstruction() + { + let original = retained_fixture(); + let (h, d) = original.open().unwrap(); + assert_eq!(h.connection_generation, 7); + assert_eq!(h.finish_before, 700); + assert_eq!(h.owner_nonce, d.owner_nonce); + let mut changed = original.clone(); + changed.grant_id = Uuid::new_v4(); + assert!(changed.open().is_err()); + let mut changed = original.clone(); + changed.handoff_base64url.push('='); + assert!(changed.open().is_err()); + let mut changed = original.clone(); + let mut raw = vec![b' ']; + raw.extend_from_slice(&h.bytes().unwrap()); + changed.handoff_base64url = URL_SAFE_NO_PAD.encode(raw); + assert!(changed.open().is_err()); + let mut changed = original; + let mut other = d; + other.owner_nonce = Uuid::new_v4(); + let raw = serde_json::to_vec(&other).unwrap(); + changed.delegation_sha256 = hash(&raw); + changed.delegation_base64url = URL_SAFE_NO_PAD.encode(raw); + assert!(changed.open().is_err()); + } + #[test] + fn only_exact_original_updater_generation_can_bridge_current_agent_epoch() { + use rmm_time_attestation::{Context, Role}; + let boot = Uuid::new_v4(); + let image = "ab".repeat(32); + let mut c = Context { + tenant_id: Uuid::new_v4(), + asset_id: Uuid::new_v4(), + agent_id: Uuid::new_v4(), + enrollment_generation: 1, + assignment_generation: 1, + connection_generation: 7, + windows_boot_id: boot, + verifier_incarnation: Uuid::new_v4(), + role: Role::Updater, + helper_image_sha256: None, + binding_schema: 2, + updater_image_sha256: Some(image.clone()), + }; + c.validate().unwrap(); + assert!(original_role_context(&c, 8, 7, boot, &image)); + assert!(!original_role_context(&c, 8, 6, boot, &image)); + assert!(!original_role_context(&c, 7, 7, boot, &image)); + assert!(!original_role_context(&c, 6, 7, boot, &image)); + assert!(!original_role_context(&c, 8, 7, Uuid::new_v4(), &image)); + assert!(!original_role_context(&c, 8, 7, boot, &"cd".repeat(32))); + c.role = Role::Agent; + c.binding_schema = 1; + c.updater_image_sha256 = None; + c.validate().unwrap(); + assert!(!original_role_context(&c, 8, 7, boot, &image)); + c.role = Role::SystemHelper; + c.helper_image_sha256 = Some(image.clone()); + c.validate().unwrap(); + assert!(!original_role_context(&c, 8, 7, boot, &image)); + c.role = Role::Updater; + c.binding_schema = 2; + c.updater_image_sha256 = Some(image.clone()); + assert!(c.validate().is_err()); + assert!(!original_role_context(&c, 8, 7, boot, &image)); + } +} diff --git a/crates/server/src/agent_update_health.rs b/crates/server/src/agent_update_health.rs index d8e9a99..6579e90 100644 --- a/crates/server/src/agent_update_health.rs +++ b/crates/server/src/agent_update_health.rs @@ -242,11 +242,14 @@ async fn issue( let health_key_id = hash(&health_public); let (header, journal) = update::verify_inflight_proof(&input.proof, health_public).map_err(|_| denied())?; - require(journal.phase() == Phase::ServicesStarted)?; + let rollback = journal.phase() == Phase::RollbackServicesStarted; + require(journal.phase() == Phase::ServicesStarted || rollback)?; let decoded = input.proof.decode().map_err(|_| denied())?; let last: Event = serde_json::from_slice(decoded.events.last().ok_or_else(denied)?)?; - let Evidence::ServicesStarted { services, .. } = &last.evidence else { - return Err(denied()); + let services = match &last.evidence { + Evidence::ServicesStarted { services, .. } if !rollback => services, + Evidence::RollbackServicesStarted { services, .. } if rollback => services, + _ => return Err(denied()), }; let started_at = last.observed_at; let (applied_request, applied_raw) = @@ -485,8 +488,9 @@ async fn issue( hash(&confirming_raw), inventory_hash, ))?); - let cached: Option = sqlx::query_scalar("SELECT data FROM audit_events WHERE event_type='agent_update_health' AND data->>'grant_id'=$1 ORDER BY created_at LIMIT 1") - .bind(header.attempt.grant_id.to_string()).fetch_optional(&mut *tx).await?; + let code_generation = if rollback { "predecessor" } else { "candidate" }; + let cached: Option = sqlx::query_scalar("SELECT data FROM audit_events WHERE event_type='agent_update_health' AND data->>'grant_id'=$1 AND COALESCE(data->>'code_generation','candidate')=$2 ORDER BY created_at LIMIT 1") + .bind(header.attempt.grant_id.to_string()).bind(code_generation).fetch_optional(&mut *tx).await?; if let Some(cached) = cached { require( cached["witness_sha256"] == witness_hash && cached["health_key_id"] == health_key_id, @@ -495,8 +499,14 @@ async fn issue( journal .prepare( issued_at, - Evidence::HealthVerified { - receipt: original.clone(), + if rollback { + Evidence::RollbackHealthVerified { + receipt: original.clone(), + } + } else { + Evidence::HealthVerified { + receipt: original.clone(), + } }, ) .map_err(|_| denied())?; @@ -517,8 +527,14 @@ async fn issue( journal .prepare( issued_at, - Evidence::HealthVerified { - receipt: signed.clone(), + if rollback { + Evidence::RollbackHealthVerified { + receipt: signed.clone(), + } + } else { + Evidence::HealthVerified { + receipt: signed.clone(), + } }, ) .map_err(|_| denied())?; @@ -526,7 +542,7 @@ async fn issue( .bind(tenant).bind(Uuid::new_v4()).bind(format!("agent:{agent}")) .bind(json!({"grant_id":header.attempt.grant_id,"job_id":header.attempt.job_id,"attempt_id":header.attempt.attempt_id, "handoff_sha256":input.proof.delegation.handoff_sha256,"head_sha256":input.proof.head_sha256,"event_count":decoded.events.len(), - "health_key_id":health_key_id,"witness_sha256":witness_hash,"receipt":signed,"evidence_only":true,"ready":false})) + "health_key_id":health_key_id,"witness_sha256":witness_hash,"receipt":signed,"evidence_only":true,"ready":false,"code_generation":code_generation})) .execute(&mut *tx).await?; tx.commit().await?; Ok(Json(signed)) diff --git a/crates/server/src/main.rs b/crates/server/src/main.rs index bfd57b3..f4c40c6 100644 --- a/crates/server/src/main.rs +++ b/crates/server/src/main.rs @@ -29,6 +29,7 @@ mod update_artifact_store; mod windows_checkpoint_review; mod windows_echo_probe; mod windows_echo_completion; +mod windows_sync_alignment; mod windows_msi_catalog; mod windows_policy; @@ -189,6 +190,7 @@ async fn main() -> Result<()> { routes = windows_checkpoint_review::routes(routes); routes = windows_echo_probe::routes(routes); routes = windows_echo_completion::routes(routes); + routes = windows_sync_alignment::routes(routes); } routes = routes .route("/auth/config", get(auth::configuration)) diff --git a/crates/server/src/synchronization.rs b/crates/server/src/synchronization.rs index 5ec65f7..f9f12b9 100644 --- a/crates/server/src/synchronization.rs +++ b/crates/server/src/synchronization.rs @@ -691,6 +691,11 @@ pub async fn reconcile( "UPDATE_INFLIGHT_PREFIX_REGRESSION" ); } + // Retain the already fully validated original public context once + // in this same control-lock transaction. The clock bridge never + // infers the original generation/deadline from a historical grant. + crate::agent_time::retain_validated_updater_context(tx, &header, &proof.delegation) + .await?; let revision = local.revision.max(row.get::("revision") as u64); sqlx::query( "UPDATE jobs SET state='running',revision=GREATEST(revision,$2) WHERE job_id=$1", diff --git a/crates/server/src/windows_policy.rs b/crates/server/src/windows_policy.rs index d65b5fb..deaf4f7 100644 --- a/crates/server/src/windows_policy.rs +++ b/crates/server/src/windows_policy.rs @@ -45,6 +45,13 @@ struct SystemScope { deserialize_with = "rmm_domain::jobs::deserialize_script_profiles" )] allowed_script_profiles: Option>, + #[serde(default, deserialize_with = "strict_optional_reboot")] + allow_reboot: Option, +} +fn strict_optional_reboot<'de, D: serde::Deserializer<'de>>( + d: D, +) -> Result, D::Error> { + bool::deserialize(d).map(Some) } fn strict_optional_hashes<'de, D>(deserializer: D) -> Result>, D::Error> where @@ -124,6 +131,7 @@ impl SystemScope { capabilities: &[String], allow_msi: bool, allow_scripts: bool, + allow_reboot: bool, ) -> bool { let has = |cap: &str| capabilities.iter().any(|c| c == cap); self.valid() @@ -149,6 +157,12 @@ impl SystemScope { && (1..=self.max_runtime_seconds).contains(&job.max_runtime_seconds) && (1..=65536).contains(&job.max_output_bytes) && match &job.action { + Action::Reboot { .. } => { + allow_reboot + && self.allow_reboot == Some(true) + && rmm_domain::windows_reboot::supported(job) + && job.action.available_for("system", capabilities) + } Action::SetServiceState { unit, state } => { self.allowed_services.contains(unit) && matches!(state.as_str(), "running" | "stopped") @@ -188,17 +202,19 @@ impl SystemScope { } impl SystemPolicy { fn valid(&self, now: DateTime) -> bool { - matches!(self.schema_version, 1..=3) + matches!(self.schema_version, 1..=4) && (self.schema_version >= 2 || self .scopes .iter() .all(|scope| scope.allowed_msi_recipe_sha256.is_none())) - && (self.schema_version == 3 + && (self.schema_version >= 3 || self .scopes .iter() .all(|scope| scope.allowed_script_profiles.is_none())) + && (self.schema_version == 4 + || self.scopes.iter().all(|scope| scope.allow_reboot.is_none())) && self.profile == "development" && self.expires_at > now && !self.scopes.is_empty() @@ -219,7 +235,8 @@ impl SystemPolicy { job, capabilities, self.schema_version >= 2, - self.schema_version == 3, + self.schema_version >= 3, + self.schema_version == 4, ) }) } @@ -363,6 +380,54 @@ pub async fn authorize( mod tests { use super::*; use serde_json::json; + #[test] + fn reboot_needs_v4_independent_opt_in_capabilities_and_exact_fixed_window() { + let (mut p, mut job, mut caps) = fixture(); + job.action = Action::Reboot { + reason: "Einzelne Windows-MVP-Abnahme".into(), + dependency_group: "windows-mvp".into(), + reconnect_timeout_seconds: 180, + }; + job.max_runtime_seconds = 60; + p.scopes[0].max_runtime_seconds = 120; + caps.extend( + [ + "reboot", + "system:reboot", + rmm_domain::windows_reboot::CAPABILITY, + ] + .map(str::to_string), + ); + for version in 1..=4 { + p.schema_version = version; + assert!(!p.permits("selected", &job, &caps, Utc::now())); + } + p.scopes[0].allow_reboot = Some(true); + for version in 1..=3 { + p.schema_version = version; + assert!(!p.permits("selected", &job, &caps, Utc::now())); + } + p.schema_version = 4; + assert!(p.permits("selected", &job, &caps, Utc::now())); + assert!(!p.permits("foreign", &job, &caps, Utc::now())); + let complete = caps.clone(); + caps.retain(|c| c != "system:reboot"); + assert!(!p.permits("selected", &job, &caps, Utc::now())); + caps = complete; + job.execution_identity = "agent_service".into(); + assert!(!p.permits("selected", &job, &caps, Utc::now())); + job.execution_identity = "system".into(); + if let Action::Reboot { + reconnect_timeout_seconds, + .. + } = &mut job.action + { + *reconnect_timeout_seconds = 181; + } + assert!(!p.permits("selected", &job, &caps, Utc::now())); + let invalid = json!({"schema_version":4,"profile":"development","expires_at":Utc::now(),"scopes":[{"allow_reboot":null}]}); + assert!(serde_json::from_value::(invalid).is_err()); + } fn fixture() -> (SystemPolicy, JobPayload, Vec) { let id = Uuid::new_v4(); let now = Utc::now(); diff --git a/crates/server/src/windows_sync_alignment.rs b/crates/server/src/windows_sync_alignment.rs new file mode 100644 index 0000000..4075b71 --- /dev/null +++ b/crates/server/src/windows_sync_alignment.rs @@ -0,0 +1,512 @@ +//! Exact connection-205 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_completion::{Receipt as Completion, successful_outcome}, + windows_echo_probe::{AGENT, ASSET, TENANT, TEST_PRINCIPAL}, + windows_sync_alignment::{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 = std::result::Result; +fn mismatch() -> Error { + Error(StatusCode::CONFLICT, "WINDOWS_SYNC_ALIGNMENT_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) -> Router { + r.route( + "/api/v1/tenants/{tenant}/windows-sync-alignment", + get(read).post(submit), + ) + .route( + "/api/v1/tenants/{tenant}/windows-sync-alignment/{request}/confirm", + post(confirm), + ) + .route( + "/api/v1/tenants/{tenant}/windows-sync-alignment/{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(()) +} +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 { + (profile::FIRST, profile::FIRST_REQUEST, 10135, 134) + } else { + (profile::SECOND, profile::SECOND_REQUEST, 10137, 135) + }; + 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 != profile::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 != profile::BOOT + || d.connection_generation != 205 + || 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.update_inflight.is_some() + || ![ + (profile::ECHO_JOB, profile::ECHO_ATTEMPT), + (profile::EXPIRED_JOB, profile::EXPIRED_ATTEMPT), + ] + .contains(&(a.job_id, a.attempt_id)) + }) + { + return Err(mismatch()); + } + Ok((r, d)) +} +async fn validate(tx: &mut Transaction<'_, Postgres>, s: &crate::State, w: &Witness) -> Result<()> { + 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 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::("asset_id") != ASSET + || dev.get::("enrollment_generation") != 1 + || dev.get::("assignment_version") != 1 + || dev.get::("connection_generation") != 205 + || dev.get::, _>("connection_boot_id") != Some(profile::BOOT) + || dev + .get::>, _>("revoked_at") + .is_some() + || dev.get::("sequence_regressed") + || dev.get::("sync_recovery_required") + { + 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::("journal_id") != w.agent_journal_id + || state.get::("checkpoint") != 10137 + || state.get::("decision_id") != profile::SECOND + || state.get::, _>("helper_journal_id") != Some(w.helper_journal_id) + || state.get::("helper_checkpoint") != 135 + { + 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::("request_hash") != hash(&r.encode_to_vec()) + || row.get::("journal_id") != w.agent_journal_id + || row.get::("checkpoint") + != i64::try_from(d.checkpoint).map_err(|_| mismatch())? + || row.get::("connection_generation") != 205 + || row.get::, _>("payload") != w.original_responses[i].decision_bytes + || row.get::, _>("signature") != w.original_responses[i].signature + { + return Err(mismatch()); + } + } + validate_jobs(tx, s, w).await +} +async fn validate_jobs( + tx: &mut Transaction<'_, Postgres>, + s: &crate::State, + w: &Witness, +) -> Result<()> { + let jobs=sqlx::query("SELECT j.job_id,j.attempt_id,j.operation_id,j.asset_id,j.state,j.payload,j.payload_hash,j.result,a.authorization_id FROM jobs j JOIN authorizations a ON a.tenant_id=j.tenant_id AND a.operation_id=j.operation_id WHERE j.tenant_id=$1 AND j.agent_id=$2 ORDER BY j.job_id FOR SHARE OF j,a").bind(TENANT).bind(AGENT).fetch_all(&mut **tx).await?; + let total: i64 = + sqlx::query_scalar("SELECT count(*) FROM jobs WHERE tenant_id=$1 AND agent_id=$2") + .bind(TENANT) + .bind(AGENT) + .fetch_one(&mut **tx) + .await?; + if jobs.len() != 2 || total != 2 { + return Err(mismatch()); + } + let echo = jobs + .iter() + .find(|r| r.get::("job_id") == profile::ECHO_JOB) + .ok_or_else(mismatch)?; + let expired = jobs + .iter() + .find(|r| r.get::("job_id") == profile::EXPIRED_JOB) + .ok_or_else(mismatch)?; + for (row, raw, id, attempt, state) in [ + ( + echo, + &w.echo_offer, + profile::ECHO_JOB, + profile::ECHO_ATTEMPT, + "succeeded", + ), + ( + expired, + &w.expired_offer, + profile::EXPIRED_JOB, + profile::EXPIRED_ATTEMPT, + "expired", + ), + ] { + let offer = JobOffer::decode(raw.as_slice()).map_err(|_| mismatch())?; + let j: JobPayload = serde_json::from_slice(&offer.payload_bytes)?; + if offer.encode_to_vec() != *raw + || offer.job_id != id.to_string() + || offer.attempt_id != attempt.to_string() + || row.get::("attempt_id") != attempt + || row.get::("asset_id") != ASSET + || row.get::("state") != state + || row.get::, _>("payload") != offer.payload_bytes + || row.get::("payload_hash") != hash(&offer.payload_bytes) + || offer.job_payload_hash != hash(&offer.payload_bytes) + || offer.authorization_id != row.get::("authorization_id").to_string() + || (j.tenant_id, j.asset_id, j.agent_id, j.job_id, j.attempt_id) + != (TENANT, ASSET, AGENT, id, attempt) + || j.enrollment_generation != 1 + || j.assignment_version != 1 + || j.execution_identity != "agent_service" + { + return Err(mismatch()); + } + let plan_raw: Option> = sqlx::query_scalar("SELECT p.payload FROM authorizations a 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 a.tenant_id=$1 AND a.authorization_id=$2 AND a.operation_id=$3 AND a.plan_hash=$4 AND a.revoked_at IS NULL AND a.principal=$5 AND a.approval_origin='dev_test_browser_simulation' AND a.testsimulation") + .bind(TENANT).bind(row.get::("authorization_id")).bind(row.get::("operation_id")).bind(&offer.plan_hash).bind(TEST_PRINCIPAL).fetch_optional(&mut **tx).await?; + let plan_raw = plan_raw.ok_or_else(mismatch)?; + let plan: PlanPayload = serde_json::from_slice(&plan_raw)?; + if hash(&plan_raw) != offer.plan_hash + || encode(&plan)? != plan_raw + || plan.tenant_id != TENANT + || plan.jobs.len() != 1 + || plan.jobs[0].payload != j + || plan.jobs[0].job_payload_hash != offer.job_payload_hash + { + return Err(mismatch()); + } + } + let grant_count: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 grant_count != 1 { + 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(profile::ECHO_JOB).bind(profile::ECHO_ATTEMPT).fetch_one(&mut **tx).await?; + let graw: Vec = grant.get("payload"); + let gsig: Vec = grant.get("signature"); + verify(s, &graw, &gsig)?; + let g: ExecutionPermitPayload = serde_json::from_slice(&graw)?; + let start: Value = serde_json::from_slice(&w.echo_start)?; + let gbytes: Vec = serde_json::from_value(start["request"]["permit_bytes"].clone())?; + let gsignature: Vec = serde_json::from_value(start["request"]["signature"].clone())?; + let jbytes: Vec = serde_json::from_value(start["request"]["job_bytes"].clone())?; + let mut outcome = echo + .get::, _>("result") + .ok_or_else(mismatch)?; + if outcome["grant_id"] != g.grant_id.to_string() { + return Err(mismatch()); + } + outcome + .as_object_mut() + .ok_or_else(mismatch)? + .remove("grant_id"); + outcome["state"] = json!("succeeded"); + let native: Value = serde_json::from_slice(&w.echo_outcome)?; + let result: Value = serde_json::from_slice(&w.echo_result)?; + if gbytes != graw + || gsignature != gsig + || jbytes != echo.get::, _>("payload") + || native != result + || native != outcome + || !successful_outcome(&outcome) + || g.grant_id != grant.get::("grant_id") + || 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, + profile::ECHO_JOB, + profile::ECHO_ATTEMPT, + ) + || g.enrollment_generation != 1 + || g.assignment_version != 1 + || g.execution_identity != "agent_service" + || g.action != "run_script" + || g.agent_update_plan_id.is_some() + || g.job_payload_hash != echo.get::("payload_hash") + || g.authorization_id != echo.get::("authorization_id") + { + return Err(mismatch()); + } + let completion: SignedReceipt = serde_json::from_slice(&w.echo_completion_receipt)?; + verify(s, &completion.payload, &completion.signature)?; + let c: Completion = serde_json::from_slice(&completion.payload)?; + if !c.valid(c.issued_at) + || c.key_id != w.verification_key_id + || c.witness.scope.job_id != profile::ECHO_JOB + || c.witness.scope.attempt_id != profile::ECHO_ATTEMPT + || c.witness.boot_id != profile::BOOT + || c.witness.grant_id != g.grant_id + || c.witness.grant_payload_sha256 != hash(&graw) + || c.witness.grant_signature_sha256 != hash(&gsig) + || c.witness.outcome_sha256 != inventory_sha256(&outcome)? + { + return Err(mismatch()); + } + let retained = + sqlx::query("SELECT payload,signature FROM windows_echo_completions WHERE tenant_id=$1") + .bind(TENANT) + .fetch_one(&mut **tx) + .await?; + if retained.get::, _>("payload") != completion.payload + || retained.get::, _>("signature") != completion.signature + { + return Err(mismatch()); + } + Ok(()) +} +async fn stored(tx: &mut Transaction<'_, Postgres>) -> Result> { + let row = sqlx::query( + "SELECT request_id,witness FROM windows_sync_alignment_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"))?, + )) + }) + .transpose() +} +async fn view(tx: &mut Transaction<'_, Postgres>, id: Uuid, w: &Witness) -> Result { + let row=sqlx::query("SELECT payload FROM windows_sync_alignment_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::(&r.get::, _>("payload"))) + .transpose()?; + Ok(json!({"request_id":id,"witness":w,"witness_sha256":w.digest(),"receipt":receipt})) +} +async fn read( + State(s): State, + Path(t): Path, + h: HeaderMap, +) -> Result> { + 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)) = stored(&mut tx).await? { + validate(&mut tx, &s, &w).await?; + view(&mut tx, id, &w).await? + } else { + json!({"request_id":null}) + }; + tx.commit().await?; + Ok(Json(result)) +} +async fn submit( + State(s): State, + Path(t): Path, + h: HeaderMap, + Json(w): Json, +) -> Result> { + let p = access(&s, &h, t, true).await?; + let mut tx = rmm_persistence::tenant_tx(&s.pool, t).await?; + crate::permissions::require_principal(&mut tx, &p, "inventory:read").await?; + validate(&mut tx, &s, &w).await?; + let id = if let Some((id, old)) = stored(&mut tx).await? { + if old != w { + return Err(mismatch()); + } + id + } else { + let id = Uuid::new_v4(); + let digest = w.digest().ok_or_else(mismatch)?; + sqlx::query("INSERT INTO windows_sync_alignment_reviews(tenant_id,request_id,agent_id,witness,witness_sha256,submitted_by) VALUES($1,$2,$3,$4,$5,$6)").bind(t).bind(id).bind(AGENT).bind(serde_json::to_value(&w)?).bind(&digest).bind(&p.name).execute(&mut *tx).await?; + sqlx::query("INSERT INTO audit_events(tenant_id,event_id,principal,event_type,data) VALUES($1,$2,$3,'windows_sync_alignment_submitted',$4)").bind(t).bind(id).bind(&p.name).bind(json!({"witness_sha256":digest,"connection_generation":205,"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, + Path((t, id)): Path<(Uuid, Uuid)>, + h: HeaderMap, + Json(input): Json, +) -> Result> { + 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) = 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).await?; + let now = Utc::now().trunc_subsecs(6); + let r = Receipt { + domain: profile::DOMAIN.into(), + schema_version: 1, + receipt_id: Uuid::new_v4(), + request_id: id, + witness: w.clone(), + 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_sync_alignment_receipts(tenant_id,request_id,receipt_id,witness_sha256,payload,signature,confirmed_by,session_hash,issued_at,valid_until) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)").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).execute(&mut *tx).await?; + sqlx::query("INSERT INTO audit_events(tenant_id,event_id,principal,event_type,data) VALUES($1,$2,$3,'windows_sync_admin_closed_alignment_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":205})).execute(&mut *tx).await?; + let result = view(&mut tx, id, &w).await?; + tx.commit().await?; + Ok(Json(result)) +} +async fn download( + State(s): State, + Path((t, id)): Path<(Uuid, Uuid)>, + h: HeaderMap, +) -> Result> { + 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) = stored(&mut tx) + .await? + .ok_or(Error(StatusCode::NOT_FOUND, "NOT_FOUND"))?; + if actual != id { + return Err(mismatch()); + } + validate(&mut tx, &s, &w).await?; + let row=sqlx::query("SELECT payload,signature FROM windows_sync_alignment_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_SYNC_ALIGNMENT_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); + } + } +} diff --git a/crates/time-attestation/src/lib.rs b/crates/time-attestation/src/lib.rs index 25c430d..006bb20 100644 --- a/crates/time-attestation/src/lib.rs +++ b/crates/time-attestation/src/lib.rs @@ -22,6 +22,7 @@ const MAX_BYTES: usize = 8192; pub enum Role { Agent, SystemHelper, + Updater, } #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] @@ -38,6 +39,8 @@ pub struct Context { pub role: Role, pub helper_image_sha256: Option, pub binding_schema: u32, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub updater_image_sha256: Option, } impl Context { pub fn validate(&self) -> Result<()> { @@ -56,18 +59,30 @@ impl Context { ensure!( self.enrollment_generation > 0 && self.assignment_generation > 0 - && self.connection_generation > 0 - && self.binding_schema == 1, + && self.connection_generation > 0, "TIME_CONTEXT_GENERATION" ); match self.role { Role::Agent => ensure!( - self.helper_image_sha256.is_none(), + self.binding_schema == 1 + && self.helper_image_sha256.is_none() + && self.updater_image_sha256.is_none(), "TIME_AGENT_HELPER_IMAGE" ), Role::SystemHelper => { + ensure!( + self.binding_schema == 1 && self.updater_image_sha256.is_none(), + "TIME_HELPER_UPDATER_IMAGE" + ); exact_hex(self.helper_image_sha256.as_deref().unwrap_or(""), 32)?; } + Role::Updater => { + ensure!( + self.binding_schema == 2 && self.helper_image_sha256.is_none(), + "TIME_UPDATER_OWN_BINDING" + ); + exact_hex(self.updater_image_sha256.as_deref().unwrap_or(""), 32)?; + } } Ok(()) } @@ -482,7 +497,8 @@ mod tests { verifier_incarnation: Uuid::new_v4(), role, helper_image_sha256: (role == Role::SystemHelper).then(|| "ab".repeat(32)), - binding_schema: 1, + binding_schema: if role == Role::Updater { 2 } else { 1 }, + updater_image_sha256: (role == Role::Updater).then(|| "cd".repeat(32)), } } fn fixture(context: Context) -> (Verifier, SigningKey, Uuid) { @@ -528,6 +544,49 @@ mod tests { assert!(!result.allows_start(T + 11_000_000, T + 114_000_000)); } #[test] + fn updater_uses_own_role_image_nonce_and_preserves_legacy_context_bytes() { + let old = context(Role::Agent); + let encoded = serde_json::to_value(&old).unwrap(); + assert!(encoded.get("updater_image_sha256").is_none()); + let (mut verifier, key, server) = fixture(context(Role::Updater)); + let challenge = verifier.begin(sample(0)).unwrap(); + assert_eq!(challenge.request().context.binding_schema, 2); + assert!(challenge.request().context.helper_image_sha256.is_none()); + let signed = reply(&challenge, &key, server); + verifier + .finish(challenge, &signed, sample(70_000_000), || { + Ok(sample(80_000_000)) + }) + .unwrap(); + for mutation in [0, 1, 2] { + let mut context = context(Role::Updater); + match mutation { + 0 => context.binding_schema = 1, + 1 => context.helper_image_sha256 = Some("cd".repeat(32)), + _ => context.updater_image_sha256 = None, + } + assert!(context.validate().is_err()); + } + let (mut updater, key, server) = fixture(context(Role::Updater)); + let challenge = updater.begin(sample(0)).unwrap(); + let mut helper_request = challenge.request().clone(); + helper_request.context.role = Role::SystemHelper; + helper_request.context.binding_schema = 1; + helper_request.context.helper_image_sha256 = Some("cd".repeat(32)); + helper_request.context.updater_image_sha256 = None; + let mut wrong: Payload = + serde_json::from_str(&reply(&challenge, &key, server).payload).unwrap(); + wrong.request_sha256 = helper_request.sha256().unwrap(); + let wrong = sign(&wrong, &key).unwrap(); + assert!( + updater + .finish(challenge, &wrong, sample(70_000_000), || Ok(sample( + 80_000_000 + ))) + .is_err() + ); + } + #[test] fn tampering_wrong_role_nonce_key_and_delays_never_open() { for mutation in 0..7 { let (mut v, key, server) = fixture(context(Role::Agent)); diff --git a/crates/time-broker-linux/src/native.rs b/crates/time-broker-linux/src/native.rs index c51d129..50cb5af 100644 --- a/crates/time-broker-linux/src/native.rs +++ b/crates/time-broker-linux/src/native.rs @@ -711,6 +711,7 @@ mod tests { role: Role::Agent, helper_image_sha256: None, binding_schema: 1, + updater_image_sha256: None, }, } } diff --git a/crates/update-history/Cargo.toml b/crates/update-history/Cargo.toml new file mode 100644 index 0000000..a9db270 --- /dev/null +++ b/crates/update-history/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "rmm-update-history" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +anyhow.workspace = true +chrono.workspace = true +hex.workspace = true +serde_json.workspace = true +uuid.workspace = true +ed25519-dalek = "=2.2.0" +rusqlite = { version = "0.32.1", features = ["bundled"] } +rmm-domain = { path = "../domain" } +rmm-agent-core = { path = "../agent-core" } +rmm-updater = { path = "../updater" } +rmm-updater-handoff = { path = "../updater-handoff" } diff --git a/crates/update-history/src/lib.rs b/crates/update-history/src/lib.rs new file mode 100644 index 0000000..ea55d36 --- /dev/null +++ b/crates/update-history/src/lib.rs @@ -0,0 +1,775 @@ +//! Read-only current-version history verification under the actual retained +//! executor guard. Every input file must already have been independently opened +//! and authenticated by the local adapter. No request supplies trusted keys. +//! +//! This is admission-oriented verification: current release-key revocations +//! apply. It must NOT gate an Unknown-only historical adjudication. A changed +//! job-signing key needs an independently retained historical Binding; keys are +//! never learned from a job. There is no clock, dispatch, repair or resume here. +use anyhow::{Context, Result, ensure}; +use chrono::{DateTime, Utc}; +use ed25519_dalek::{Signature, VerifyingKey}; +use rmm_agent_core::{ + auth::{Binding, Outcome, Request}, + helper_reconcile::ExecutorLedgerGuard, + ledger, + update_handoff::{self, NativeEffect, NativeEffectClaim}, +}; +use rmm_domain::{ + agent_update::{self, Platform, ReleaseEnvelope, UpdateKeyringFile}, + agent_update_provisioning::{ + ActivationEvidence, BASELINE_SIGNATURE_DOMAIN, InstalledReleaseRecord, MAX_RECORD_BYTES, + SignedBaselineRecord, + }, + jobs::{Action, hash}, +}; +use rmm_updater::{ + ActiveRelease, Platform as ReleasePlatform, SignedRelease, TrustedContext, TrustedUpdateKey, + UpdateKeyring, verify_release, +}; +use rmm_updater_handoff::{Event, Evidence, Handoff, HealthReceipt, Phase, SignedHealth}; +use rusqlite::{Connection, OptionalExtension, params}; +use std::collections::{BTreeMap, BTreeSet}; +use uuid::Uuid; + +const MAX_RECORDS: usize = 64; +const MAX_TOTAL_BYTES: usize = 2 * 1024 * 1024; + +/// `predecessor_records` is an unordered exact set of intermediate records. +/// The signed initial record may optionally appear once. Missing, duplicate, +/// unused/forked or completed-but-omitted records are denied. V1 rollback and +/// historical job-key rotation without its trusted binding are unsupported. +pub fn verify_history( + db: &Connection, + guard: &impl ExecutorLedgerGuard, + binding: &Binding, + protected_keyring: &UpdateKeyringFile, + baseline: &SignedBaselineRecord, + predecessor_records: &[Vec], + active_raw: &[u8], +) -> Result { + guard.check(db)?; + ensure!(protected_keyring.validate(), "UPDATE_HISTORY_KEYRING"); + let initial = baseline.decode().map_err(anyhow::Error::msg)?; + ensure!( + matches!( + initial.record.platform, + Platform::LinuxX64 | Platform::WindowsX64 + ), + "UPDATE_HISTORY_PLATFORM" + ); + let keyring = current_keyring(protected_keyring)?; + let initial_release = initial + .record + .release_envelope + .decode() + .map_err(anyhow::Error::msg)?; + let entry = protected_keyring + .keys + .iter() + .find(|key| hex::decode(&key.public_key_hex).is_ok_and(|raw| hash(&raw) == baseline.key_id)) + .context("UPDATE_HISTORY_BASELINE_KEY_MISSING")?; + ensure!( + !entry.revoked + && entry.platform == initial.record.platform + && (entry.first_sequence..=entry.last_sequence) + .contains(&initial_release.manifest.release_sequence), + "UPDATE_HISTORY_BASELINE_KEY_REVOKED_OR_RANGE" + ); + let public: [u8; 32] = hex::decode(&entry.public_key_hex)? + .try_into() + .map_err(|_| anyhow::anyhow!("UPDATE_HISTORY_KEY_SIZE"))?; + let verifier = VerifyingKey::from_bytes(&public)?; + ensure!(!verifier.is_weak(), "UPDATE_HISTORY_WEAK_BASELINE_KEY"); + let mut signed = BASELINE_SIGNATURE_DOMAIN.to_vec(); + signed.extend_from_slice(&initial.payload_bytes); + verifier.verify_strict(&signed, &Signature::from_bytes(&initial.signature))?; + verify_record_release( + &keyring, + protected_keyring.generation, + &initial.record, + initial_release.manifest.protocol_major, + initial_release.manifest.state_schema, + )?; + + ensure!( + predecessor_records.len() < MAX_RECORDS + && !active_raw.is_empty() + && active_raw.len() <= MAX_RECORD_BYTES, + "UPDATE_HISTORY_RECORD_LIMIT" + ); + let mut total = active_raw + .len() + .checked_add(initial.payload_bytes.len()) + .context("UPDATE_HISTORY_SIZE")?; + let active = InstalledReleaseRecord::from_bytes(active_raw).map_err(anyhow::Error::msg)?; + let active_hash = hash(active_raw); + let baseline_hash = hash(&initial.payload_bytes); + let mut previous = BTreeMap::new(); + for raw in predecessor_records { + total = total + .checked_add(raw.len()) + .context("UPDATE_HISTORY_SIZE")?; + ensure!( + !raw.is_empty() && raw.len() <= MAX_RECORD_BYTES && total <= MAX_TOTAL_BYTES, + "UPDATE_HISTORY_SIZE" + ); + let digest = hash(raw); + ensure!( + digest != active_hash && previous.insert(digest, raw.as_slice()).is_none(), + "UPDATE_HISTORY_DUPLICATE" + ); + } + ensure!(total <= MAX_TOTAL_BYTES, "UPDATE_HISTORY_SIZE"); + let mut chain = vec![(active_hash, active_raw, active.clone())]; + while chain.last().context("UPDATE_HISTORY_EMPTY")?.0 != baseline_hash { + ensure!(chain.len() < MAX_RECORDS, "UPDATE_HISTORY_DEPTH"); + let current = &chain.last().context("UPDATE_HISTORY_EMPTY")?.2; + let digest = current + .previous_record_sha256 + .as_ref() + .context("UPDATE_HISTORY_PARENT_MISSING")?; + let raw = if *digest == baseline_hash { + if let Some(copy) = previous.remove(digest) { + ensure!( + copy == initial.payload_bytes, + "UPDATE_HISTORY_BASELINE_CHANGED" + ); + } + initial.payload_bytes.as_slice() + } else { + previous + .remove(digest) + .context("UPDATE_HISTORY_PARENT_MISSING")? + }; + ensure!( + !chain.iter().any(|(seen, _, _)| seen == digest), + "UPDATE_HISTORY_CYCLE" + ); + let record = InstalledReleaseRecord::from_bytes(raw).map_err(anyhow::Error::msg)?; + chain.push((digest.clone(), raw, record)); + } + ensure!( + previous.is_empty() + && chain.last().context("UPDATE_HISTORY_EMPTY")?.1 == initial.payload_bytes, + "UPDATE_HISTORY_UNUSED_OR_WRONG_ANCHOR" + ); + let mut grants = BTreeSet::new(); + for pair in chain.windows(2) { + let (digest, raw, record) = &pair[0]; + let (parent_digest, _, parent) = &pair[1]; + ensure!( + !record.rolled_back + && record.platform == parent.platform + && record.activation_floor > parent.activation_floor + && record.activated_at >= parent.activated_at, + "UPDATE_HISTORY_FLOOR_OR_ROLLBACK" + ); + verify_record_release( + &keyring, + protected_keyring.generation, + record, + initial_release.manifest.protocol_major, + initial_release.manifest.state_schema, + )?; + let grant = verify_update(db, guard, binding, raw, record, parent_digest, parent)?; + ensure!(grants.insert(grant), "UPDATE_HISTORY_REUSED_GRANT"); + ensure!(*digest == hash(raw), "UPDATE_HISTORY_RECORD_CHANGED"); + } + // Detect a record-file-only rollback/fork: every completed publication in + // this same device ledger must be present in the verified chain. + ensure!( + completed_update_grants(db, binding)? == grants, + "UPDATE_HISTORY_OMITTED_CONSUMPTION" + ); + let exists: bool = db.query_row("SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name='agent_update_handoffs')", [], |r| r.get(0))?; + if exists { + let mut query = db.prepare("SELECT h.grant_id,c.claim FROM agent_update_handoffs h LEFT JOIN agent_update_native_claims c ON c.grant_id=h.grant_id AND c.effect_key='publish_installed_record' WHERE h.phase='outcome_persisted' ORDER BY h.grant_id LIMIT 65")?; + let mut rows = query.query([])?; + let mut seen = BTreeSet::new(); + while let Some(row) = rows.next()? { + let grant: String = row.get(0)?; + let raw: Option> = row.get(1)?; + let raw = raw.context("UPDATE_HISTORY_PUBLICATION_MISSING")?; + ensure!( + raw.len() <= 2048 && seen.len() < MAX_RECORDS, + "UPDATE_HISTORY_PUBLICATION_LIMIT" + ); + let claim: NativeEffectClaim = serde_json::from_slice(&raw)?; + let grant = Uuid::parse_str(&grant)?; + ensure!( + claim.grant_id() == grant && grants.contains(&grant) && seen.insert(grant), + "UPDATE_HISTORY_OMITTED_PUBLICATION" + ); + } + ensure!(seen == grants, "UPDATE_HISTORY_MISSING_PUBLICATION"); + } else { + ensure!(grants.is_empty(), "UPDATE_HISTORY_MISSING_LEDGER"); + } + guard.check(db)?; + Ok(active) +} + +fn current_keyring(file: &UpdateKeyringFile) -> Result { + let mut keys = Vec::new(); + for key in &file.keys { + let public: [u8; 32] = hex::decode(&key.public_key_hex)? + .try_into() + .map_err(|_| anyhow::anyhow!("UPDATE_HISTORY_KEY_SIZE"))?; + keys.push(TrustedUpdateKey::new( + public, + match key.platform { + Platform::LinuxX64 => ReleasePlatform::LinuxX64, + Platform::WindowsX64 => ReleasePlatform::WindowsX64, + }, + key.first_sequence, + key.last_sequence, + key.revoked, + )?); + } + UpdateKeyring::new(file.generation, keys) +} + +/// The authoritative completed set starts at ORIGINAL consumptions, not at an +/// optional successor proof row. Stream a bounded local history, including old +/// non-update jobs, without exposing any request/script bytes outside here. +fn completed_update_grants(db: &Connection, binding: &Binding) -> Result> { + let mut query=db.prepare("SELECT c.grant_id,e.start,e.outcome,c.result FROM consumed c LEFT JOIN execution_evidence e USING(grant_id) WHERE c.result IS NOT NULL OR e.outcome IS NOT NULL ORDER BY c.grant_id LIMIT 4097")?; + let mut rows = query.query([])?; + let mut count = 0; + let mut bytes = 0usize; + let mut grants = BTreeSet::new(); + while let Some(row) = rows.next()? { + count += 1; + ensure!(count <= 4096, "UPDATE_HISTORY_CONSUMPTION_LIMIT"); + let grant: String = row.get(0)?; + let start: Option> = row.get(1)?; + let outcome: Option> = row.get(2)?; + let finished: Option> = row.get(3)?; + for raw in [&start, &outcome, &finished].into_iter().flatten() { + bytes = bytes + .checked_add(raw.len()) + .context("UPDATE_HISTORY_CONSUMPTION_SIZE")?; + ensure!( + raw.len() <= 512 * 1024 && bytes <= 16 * 1024 * 1024, + "UPDATE_HISTORY_CONSUMPTION_SIZE" + ); + } + let raw = outcome + .as_ref() + .or(finished.as_ref()) + .context("UPDATE_HISTORY_COMPLETION_MISSING")?; + if let (Some(a), Some(b)) = (&outcome, &finished) { + let a: rmm_domain::reconciliation::ReconciledOutcome = serde_json::from_slice(a)?; + let b: rmm_domain::reconciliation::ReconciledOutcome = serde_json::from_slice(b)?; + ensure!( + rmm_domain::reconciliation::canonical_outcome_bytes(&a)? + == rmm_domain::reconciliation::canonical_outcome_bytes(&b)?, + "UPDATE_HISTORY_COMPLETION_CHANGED" + ); + } + let value: Outcome = serde_json::from_slice(raw)?; + if value.state != "succeeded" { + continue; + } + let start = start.context("UPDATE_HISTORY_START_MISSING")?; + let start: serde_json::Value = serde_json::from_slice(&start)?; + let request: Request = serde_json::from_value(start["request"].clone())?; + let reserved_at: DateTime = serde_json::from_value(start["reserved_at"].clone())?; + let (job, permit) = binding.verify(&request, reserved_at)?; + ensure!( + permit.grant_id.to_string() == grant, + "UPDATE_HISTORY_CONSUMPTION_CHANGED" + ); + if matches!(job.action, Action::UpdateAgent { .. }) { + ensure!( + grants.len() < MAX_RECORDS && grants.insert(permit.grant_id), + "UPDATE_HISTORY_COMPLETION_LIMIT" + ); + } + } + Ok(grants) +} + +fn verify_record_release( + keys: &UpdateKeyring, + generation: u64, + record: &InstalledReleaseRecord, + baseline_protocol_major: u32, + baseline_state_schema: u32, +) -> Result<()> { + ensure!( + !record.rolled_back, + "UPDATE_HISTORY_V1_ROLLBACK_UNSUPPORTED" + ); + let decoded = record + .release_envelope + .decode() + .map_err(anyhow::Error::msg)?; + let platform = match record.platform { + Platform::LinuxX64 => ReleasePlatform::LinuxX64, + Platform::WindowsX64 => ReleasePlatform::WindowsX64, + }; + let envelope: &ReleaseEnvelope = &record.release_envelope; + verify_release( + SignedRelease { + schema_version: envelope.schema_version, + key_id: &envelope.key_id, + payload_bytes: &decoded.payload_bytes, + signature: &decoded.signature, + }, + keys, + &TrustedContext { + platform, + now_utc_seconds: record.activated_at, + keyring_generation: generation, + // Anchor compatibility to the separately signed, qualified + // bootstrap. A signed successor cannot attest its own decoder + // compatibility by supplying both sides of this comparison. + protocol_major: baseline_protocol_major, + state_schema: baseline_state_schema, + updater_version: 1, + minimum_release_sequence: record.activation_floor, + active_release: Some(ActiveRelease { + sequence: decoded.manifest.release_sequence, + manifest_sha256: record.manifest_sha256.clone(), + }), + }, + )?; + Ok(()) +} + +fn verify_update( + db: &Connection, + guard: &impl ExecutorLedgerGuard, + binding: &Binding, + raw_record: &[u8], + record: &InstalledReleaseRecord, + parent_hash: &str, + parent: &InstalledReleaseRecord, +) -> Result { + let ActivationEvidence::Updated { + handoff_sha256, + signed_health_sha256, + } = &record.activation_evidence + else { + anyhow::bail!("UPDATE_HISTORY_BOOTSTRAP_FORK"); + }; + let mut query = db.prepare("SELECT h.grant_id,h.record,e.start,e.outcome,c.result FROM agent_update_handoffs h JOIN execution_evidence e USING(grant_id) JOIN consumed c USING(grant_id) WHERE h.record_sha256=?1 LIMIT 2")?; + let values = query + .query_map([handoff_sha256], |r| { + Ok(( + r.get::<_, String>(0)?, + r.get::<_, Vec>(1)?, + r.get::<_, Vec>(2)?, + r.get::<_, Option>>(3)?, + r.get::<_, Option>>(4)?, + )) + })? + .collect::>>()?; + ensure!( + values.len() == 1, + "UPDATE_HISTORY_ORIGINAL_MISSING_OR_DUPLICATE" + ); + let (grant, raw_handoff, start, outcome, finished) = &values[0]; + ensure!( + raw_handoff.len() <= rmm_updater_handoff::MAX_RECORD_BYTES && start.len() <= 512 * 1024, + "UPDATE_HISTORY_ORIGINAL_LIMIT" + ); + let grant = Uuid::parse_str(grant)?; + let header: Handoff = serde_json::from_slice(raw_handoff)?; + ensure!( + header.bytes()? == *raw_handoff + && hash(raw_handoff) == *handoff_sha256 + && header.attempt.grant_id == grant + && header.predecessor_record_sha256 == parent_hash, + "UPDATE_HISTORY_ORIGINAL_BINDING" + ); + let start_value: serde_json::Value = serde_json::from_slice(start)?; + let reserved_at: DateTime = serde_json::from_value(start_value["reserved_at"].clone())?; + let request: Request = serde_json::from_value(start_value["request"].clone())?; + // Historical identity/signature/window verification only. Never a live + // execution verifier or a replacement start grant. + let (job, permit) = binding.verify(&request, reserved_at)?; + let Action::UpdateAgent { update } = &job.action else { + anyhow::bail!("UPDATE_HISTORY_JOB_ACTION"); + }; + let previous = parent + .release_envelope + .decode() + .map_err(anyhow::Error::msg)?; + ensure!( + job.execution_identity + == match record.platform { + Platform::LinuxX64 => "root", + Platform::WindowsX64 => "system", + } + && update.release_envelope == record.release_envelope + && agent_update::handoff_matches_job(&header, &job) + && header.attempt.grant_id == permit.grant_id + && header.attempt.job_payload_sha256 == permit.job_payload_hash + && header.attempt.plan_id + == permit.agent_update_plan_id.context("UPDATE_HISTORY_PLAN")? + && header.attempt.authorization_id == permit.authorization_id + && header.attempt.plan_sha256 == permit.plan_hash + && header.attempt.original_start_witness_sha256 == hash(start) + && header.attempt.original_request_sha256 == hash(&serde_json::to_vec(&request)?) + && header.consumed_at == u64::try_from(reserved_at.timestamp())? + && header.finish_before + == header + .consumed_at + .checked_add(600) + .context("UPDATE_HISTORY_DEADLINE")? + && ledger::start_witness_bytes(&permit, &request, header.boot_id, reserved_at)? + == *start + && update.predecessor.installed_record_sha256 == parent_hash + && update.predecessor.manifest_sha256 == parent.manifest_sha256 + && update.predecessor.release_id == previous.manifest.release_id + && update.predecessor.release_sequence == previous.manifest.release_sequence + && header.predecessor.manifest_sha256 == parent.manifest_sha256 + && header.predecessor.agent_sha256 == previous.manifest.artifacts[0].sha256 + && header.predecessor.helper_sha256 == previous.manifest.artifacts[1].sha256 + && header.target.manifest_sha256 == record.manifest_sha256, + "UPDATE_HISTORY_SIGNED_ORIGINAL_CHANGED" + ); + let (count,size):(u64,u64)=db.query_row("SELECT count(*),COALESCE(sum(length(event)),0) FROM (SELECT event FROM agent_update_handoff_events WHERE grant_id=?1 ORDER BY sequence LIMIT 17)", [grant.to_string()], |r|Ok((r.get(0)?,r.get(1)?)))?; + ensure!( + count <= 16 && size <= 16 * 16384, + "UPDATE_HISTORY_EVENT_LIMIT" + ); + let journal = update_handoff::read(db, guard, grant)?; + ensure!( + journal.phase() == Phase::OutcomePersisted, + "UPDATE_HISTORY_INCOMPLETE_OR_UNKNOWN" + ); + let (helper, agent): (String, Option) = db.query_row( + "SELECT journal_id,agent_journal_id FROM helper_sync_meta WHERE id=1", + [], + |r| Ok((r.get(0)?, r.get(1)?)), + )?; + ensure!( + helper == header.helper_journal_id.to_string() + && agent.as_deref() == Some(header.agent_journal_id.to_string().as_str()), + "UPDATE_HISTORY_LEDGER_LINEAGE" + ); + let mut events = db.prepare( + "SELECT event FROM agent_update_handoff_events WHERE grant_id=?1 ORDER BY sequence", + )?; + let events = events + .query_map([grant.to_string()], |r| r.get::<_, Vec>(0))? + .collect::>>()?; + complete_native_history(db, &header, &events, parent_hash, &hash(raw_record))?; + let mut health: Option<(SignedHealth, u64)> = None; + let mut final_at = None; + for raw in &events { + let event: Event = serde_json::from_slice(raw)?; + match event.evidence { + Evidence::HealthVerified { receipt } => { + ensure!(health.is_none(), "UPDATE_HISTORY_DOUBLE_HEALTH"); + health = Some((receipt, event.observed_at)); + } + Evidence::OutcomePersisted { outcome_sha256 } => { + let original = outcome.as_ref().context("UPDATE_HISTORY_OUTCOME_MISSING")?; + ensure!( + original.len() <= 512 * 1024 && hash(original) == outcome_sha256, + "UPDATE_HISTORY_OUTCOME_CHANGED" + ); + let value: Outcome = serde_json::from_slice(original)?; + ensure!( + value.state == "succeeded" + && !value.reboot_required + && finished.as_ref().is_none_or(|v| v == original), + "UPDATE_HISTORY_OUTCOME_NOT_SUCCESS" + ); + final_at = Some(event.observed_at); + } + _ => {} + } + } + let (health, verified_at) = health.context("UPDATE_HISTORY_HEALTH_MISSING")?; + let receipt: HealthReceipt = serde_json::from_slice(&health.payload)?; + ensure!( + hash(&serde_json::to_vec(&health)?) == *signed_health_sha256 + && record.activated_at == receipt.issued_at + && final_at.context("UPDATE_HISTORY_FINAL_MISSING")? >= verified_at, + "UPDATE_HISTORY_HEALTH_OR_ACTIVATION_CHANGED" + ); + // Journal replay already independently verified the health signature with + // the public key bound by this ORIGINAL signed job and checked its deadline. + let record_hash = hash(raw_record); + let saved = publication( + db, + grant, + "save_installed_record", + parent_hash, + &record_hash, + )?; + let published = publication( + db, + grant, + "publish_installed_record", + parent_hash, + &record_hash, + )?; + ensure!( + saved.0.timestamp() >= i64::try_from(verified_at)? + && published.0 >= saved.1 + && published.1.timestamp() + <= i64::try_from(final_at.context("UPDATE_HISTORY_FINAL_MISSING")?)?, + "UPDATE_HISTORY_PUBLICATION_ORDER" + ); + guard.check(db)?; + Ok(grant) +} + +fn complete_native_history( + db: &Connection, + header: &Handoff, + events: &[Vec], + old: &str, + new: &str, +) -> Result<()> { + use rmm_agent_core::update_handoff::{NativeFileRole as F, NativeService as S}; + let mut expected = BTreeSet::new(); + let (services, roles): (&[S], &[F]) = match header.pin_transition { + rmm_updater_handoff::PinTransition::LinuxGeneralFullV1 => ( + &[S::Agent, S::General, S::Full], + &[F::AgentBinary, F::HelperBinary, F::FullConfig, F::FullPin], + ), + rmm_updater_handoff::PinTransition::WindowsCodePairClockV1 => ( + &[S::WindowsAgent, S::WindowsHelper], + &[ + F::AgentBinary, + F::HelperBinary, + F::WindowsSettings, + F::WindowsPin, + F::WindowsTimeProfile, + ], + ), + _ => anyhow::bail!("UPDATE_HISTORY_UNSUPPORTED_NATIVE_PROFILE"), + }; + for service in services.iter().copied() { + expected.insert(serde_json::to_string(&NativeEffect::StopService { + service, + })?); + expected.insert(serde_json::to_string(&NativeEffect::StartService { + service, + })?); + } + for role in roles.iter().copied() { + expected.insert(serde_json::to_string(&NativeEffect::SavePredecessor { + role, + })?); + expected.insert(serde_json::to_string(&NativeEffect::PublishReplacement { + role, + })?); + } + expected.insert(serde_json::to_string(&NativeEffect::ReturnLedger)?); + expected.insert("save_installed_record".into()); + expected.insert("publish_installed_record".into()); + let parsed = events + .iter() + .map(|raw| Ok((hash(raw), serde_json::from_slice::(raw)?))) + .collect::>>()?; + let time = |predicate: &dyn Fn(&Evidence) -> bool| -> Result { + let entries = parsed + .values() + .filter(|event| predicate(&event.evidence)) + .collect::>(); + ensure!(entries.len() == 1, "UPDATE_HISTORY_NATIVE_PHASE_MISSING"); + Ok(entries[0].observed_at) + }; + let grant = header.attempt.grant_id.to_string(); + let mut query=db.prepare("SELECT c.effect_key,c.claim,c.claim_sha256,o.claim_sha256,o.observation_sha256,o.observed_at FROM agent_update_native_claims c LEFT JOIN agent_update_native_observations o USING(grant_id,effect_key) WHERE c.grant_id=?1 ORDER BY c.effect_key LIMIT 18")?; + let mut rows = query.query([grant])?; + let mut seen = BTreeSet::new(); + let mut return_group: Option<(String, DateTime)> = None; + while let Some(row) = rows.next()? { + let key: String = row.get(0)?; + let raw: Vec = row.get(1)?; + let digest: String = row.get(2)?; + ensure!( + seen.len() < 17 + && raw.len() <= 2048 + && hash(&raw) == digest + && expected.contains(&key) + && seen.insert(key.clone()), + "UPDATE_HISTORY_NATIVE_SET" + ); + let claim: NativeEffectClaim = serde_json::from_slice(&raw)?; + let expected_key = match claim.effect() { + NativeEffect::SaveInstalledRecord { + old_sha256, + new_sha256, + } => { + ensure!( + old_sha256 == old && new_sha256 == new, + "UPDATE_HISTORY_RECORD_PAIR" + ); + "save_installed_record".into() + } + NativeEffect::PublishInstalledRecord { + old_sha256, + new_sha256, + } => { + ensure!( + old_sha256 == old && new_sha256 == new, + "UPDATE_HISTORY_RECORD_PAIR" + ); + "publish_installed_record".into() + } + effect => serde_json::to_string(effect)?, + }; + let head = parsed + .get(claim.head_sha256()) + .context("UPDATE_HISTORY_NATIVE_HEAD_MISSING")?; + let expected_head = match claim.effect() { + NativeEffect::StopService { .. } => matches!(head.evidence, Evidence::StopIntent), + NativeEffect::StartService { .. } | NativeEffect::ReturnLedger => { + matches!(head.evidence, Evidence::LedgerReturnIntent) + } + NativeEffect::SaveInstalledRecord { .. } + | NativeEffect::PublishInstalledRecord { .. } => { + matches!(head.evidence, Evidence::HealthVerified { .. }) + } + NativeEffect::SavePredecessor { role } | NativeEffect::PublishReplacement { role } => { + let expected = match role { + F::AgentBinary => rmm_updater_handoff::FileRole::AgentBinary, + F::HelperBinary => rmm_updater_handoff::FileRole::HelperBinary, + F::FullConfig => rmm_updater_handoff::FileRole::LinuxFullConfig, + F::FullPin => rmm_updater_handoff::FileRole::LinuxFullPin, + F::WindowsSettings => rmm_updater_handoff::FileRole::WindowsSettings, + F::WindowsPin => rmm_updater_handoff::FileRole::WindowsPin, + F::WindowsTimeProfile => rmm_updater_handoff::FileRole::WindowsTimeProfile, + }; + matches!(head.evidence,Evidence::ReplaceIntent{role} if role==expected) + } + _ => false, + }; + ensure!( + key == expected_key + && expected_head + && serde_json::to_vec(&claim)? == raw + && claim.grant_id() == header.attempt.grant_id + && claim.owner_nonce() == header.owner_nonce + && u64::try_from(claim.claimed_at().timestamp())? >= head.observed_at + && u64::try_from(claim.claimed_at().timestamp())? >= header.consumed_at + && u64::try_from(claim.claimed_at().timestamp())? < header.finish_before, + "UPDATE_HISTORY_NATIVE_CLAIM_CHANGED" + ); + if matches!( + claim.effect(), + NativeEffect::ReturnLedger | NativeEffect::StartService { .. } + ) { + let group = (claim.head_sha256().to_owned(), claim.claimed_at()); + ensure!( + u64::try_from(group.1.timestamp())? == head.observed_at + && return_group.as_ref().is_none_or(|prior| prior == &group), + "UPDATE_HISTORY_RETURN_STARTS_NOT_ATOMIC" + ); + return_group = Some(group); + } + let observed: Option = row.get(3)?; + let observation: Option = row.get(4)?; + let when: Option = row.get(5)?; + if matches!(claim.effect(), NativeEffect::ReturnLedger) { + ensure!( + observed.is_none() && observation.is_none() && when.is_none(), + "UPDATE_HISTORY_FALSE_RETURN_OBSERVATION" + ); + } else { + ensure!( + observed.as_ref() == Some(&digest) + && observation + .as_ref() + .is_some_and(|v| agent_update::digest(v)), + "UPDATE_HISTORY_NATIVE_OBSERVATION" + ); + let when: DateTime = when.context("UPDATE_HISTORY_NATIVE_OBSERVATION")?.parse()?; + ensure!( + when >= claim.claimed_at() + && u64::try_from(when.timestamp())? < header.finish_before, + "UPDATE_HISTORY_NATIVE_OBSERVATION_TIME" + ); + let end = match claim.effect() { + NativeEffect::StopService { .. } => { + time(&|e| matches!(e, Evidence::AllStopped { .. }))? + } + NativeEffect::StartService { .. } => { + time(&|e| matches!(e, Evidence::ServicesStarted { .. }))? + } + NativeEffect::SaveInstalledRecord { .. } + | NativeEffect::PublishInstalledRecord { .. } => { + time(&|e| matches!(e, Evidence::OutcomePersisted { .. }))? + } + NativeEffect::SavePredecessor { role } + | NativeEffect::PublishReplacement { role } => { + let expected = match role { + F::AgentBinary => rmm_updater_handoff::FileRole::AgentBinary, + F::HelperBinary => rmm_updater_handoff::FileRole::HelperBinary, + F::FullConfig => rmm_updater_handoff::FileRole::LinuxFullConfig, + F::FullPin => rmm_updater_handoff::FileRole::LinuxFullPin, + F::WindowsSettings => rmm_updater_handoff::FileRole::WindowsSettings, + F::WindowsPin => rmm_updater_handoff::FileRole::WindowsPin, + F::WindowsTimeProfile => rmm_updater_handoff::FileRole::WindowsTimeProfile, + }; + time(&|e| matches!(e,Evidence::Replaced{role,..} if *role==expected))? + } + _ => anyhow::bail!("UPDATE_HISTORY_NATIVE_PHASE"), + }; + ensure!( + u64::try_from(when.timestamp())? <= end, + "UPDATE_HISTORY_NATIVE_LATE_OBSERVATION" + ); + if let NativeEffect::PublishReplacement { role } = claim.effect() { + let save = serde_json::to_string(&NativeEffect::SavePredecessor { role: *role })?; + let saved:String=db.query_row("SELECT observed_at FROM agent_update_native_observations WHERE grant_id=?1 AND effect_key=?2",params![header.attempt.grant_id.to_string(),save],|r|r.get(0))?; + let saved: DateTime = saved.parse()?; + ensure!( + saved <= claim.claimed_at(), + "UPDATE_HISTORY_NATIVE_PUBLISH_BEFORE_SAVE" + ); + } + } + } + ensure!(seen == expected, "UPDATE_HISTORY_NATIVE_HISTORY_MISSING"); + Ok(()) +} + +fn publication( + db: &Connection, + grant: Uuid, + effect: &str, + old: &str, + new: &str, +) -> Result<(DateTime, DateTime)> { + let value: Option<(Vec,String,String,String)> = db.query_row( + "SELECT c.claim,c.claim_sha256,o.claim_sha256,o.observed_at FROM agent_update_native_claims c JOIN agent_update_native_observations o USING(grant_id,effect_key) WHERE c.grant_id=?1 AND c.effect_key=?2", + params![grant.to_string(),effect], |r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?))).optional()?; + let (raw, digest, observed, at) = value.context("UPDATE_HISTORY_PUBLICATION_MISSING")?; + ensure!( + raw.len() <= 2048 && hash(&raw) == digest && digest == observed, + "UPDATE_HISTORY_PUBLICATION_CHANGED" + ); + let claim: NativeEffectClaim = serde_json::from_slice(&raw)?; + let expected = if effect == "save_installed_record" { + NativeEffect::SaveInstalledRecord { + old_sha256: old.into(), + new_sha256: new.into(), + } + } else { + NativeEffect::PublishInstalledRecord { + old_sha256: old.into(), + new_sha256: new.into(), + } + }; + let observed: DateTime = at.parse()?; + ensure!( + serde_json::to_vec(&claim)? == raw + && claim.grant_id() == grant + && claim.effect() == &expected + && observed >= claim.claimed_at(), + "UPDATE_HISTORY_PUBLICATION_PAIR" + ); + Ok((claim.claimed_at(), observed)) +} diff --git a/crates/updater-handoff/src/lib.rs b/crates/updater-handoff/src/lib.rs index 9cd1e0c..e6c56a2 100644 --- a/crates/updater-handoff/src/lib.rs +++ b/crates/updater-handoff/src/lib.rs @@ -19,6 +19,11 @@ pub use linux_full::{LinuxFullTransition, LinuxFullTransitionProof, render_linux pub const MAX_RECORD_BYTES: usize = 16 * 1024; pub const MAX_EVENT_BYTES: usize = 16 * 1024; pub const MAX_EVENTS: usize = 16; +/// Only the explicit five-file Windows clock transition needs two additional +/// ReplaceIntent/Replaced events. Historical profiles retain the 16-event cap. +pub const MAX_WINDOWS_CLOCK_EVENTS: usize = 18; +/// Explicit V2 allows one predecessor return under the original attempt. +pub const MAX_V2_EVENTS: usize = 40; pub const HEALTH_DOMAIN: &[u8] = b"rmm.agent-update-health.v1\0"; /// All fields below are untrusted wire data, never authorization capabilities. @@ -123,7 +128,7 @@ pub struct Handoff { impl Handoff { pub fn validate(&self) -> Result<()> { - ensure!(self.schema_version == 1, "HANDOFF_SCHEMA"); + ensure!(matches!(self.schema_version, 1 | 2), "HANDOFF_SCHEMA"); for id in [ self.attempt.tenant_id, self.attempt.asset_id, @@ -373,10 +378,55 @@ pub enum Evidence { OutcomePersisted { outcome_sha256: String, }, + RollbackIntent { + cause: RollbackCause, + failure_observation_sha256: String, + }, + RollbackStopped { + process: Process, + ledger_identity_sha256: String, + observation_sha256: String, + }, + RestoreIntent { + role: FileRole, + }, + CandidatePreserved { + role: FileRole, + observation_sha256: String, + }, + PredecessorRestored { + role: FileRole, + observed_sha256: String, + }, + PredecessorVerified { + pair: CodePair, + retained_state_sha256: String, + predecessor_record_sha256: String, + }, + RollbackLedgerReturnIntent, + RollbackServicesStarted { + services: Vec, + ledger_identity_sha256: String, + observation_sha256: String, + }, + RollbackHealthVerified { + receipt: SignedHealth, + }, + RollbackOutcomePersisted { + outcome_sha256: String, + }, Unknown { reason: UnknownReason, }, } +/// Native guards must independently attest the actual known failure. Missing +/// replies, uncertain replacement, lost owner and persisted Unknown are denied. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "cause", rename_all = "snake_case", deny_unknown_fields)] +pub enum RollbackCause { + StartupFailed { service: Service }, + HealthRejected, +} #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] @@ -415,6 +465,15 @@ pub enum Phase { LedgerReturnIntent, ServicesStarted, HealthVerified, + RollbackIntent, + RollbackStopped, + RestoreIntent, + CandidatePreserved, + PredecessorRestored, + PredecessorVerified, + RollbackLedgerReturnIntent, + RollbackServicesStarted, + RollbackHealthVerified, OutcomePersisted, Unknown, } @@ -431,6 +490,9 @@ pub struct Journal { observed_at: u64, started: Option<(Vec, u64)>, health_key: VerifyingKey, + updater: Option, + original_start_at: Option, + restored: usize, } impl Journal { @@ -452,6 +514,9 @@ impl Journal { replaced: 0, started: None, health_key, + updater: None, + original_start_at: None, + restored: 0, }) } @@ -464,6 +529,20 @@ impl Journal { pub fn handoff_sha256(&self) -> &str { &self.handoff_hash } + pub fn rollback_active(&self) -> bool { + matches!( + self.phase, + Phase::RollbackIntent + | Phase::RollbackStopped + | Phase::RestoreIntent + | Phase::CandidatePreserved + | Phase::PredecessorRestored + | Phase::PredecessorVerified + | Phase::RollbackLedgerReturnIntent + | Phase::RollbackServicesStarted + | Phase::RollbackHealthVerified + ) + } /// Prepare exact bytes for a bounded append-only CAS transaction against /// `head_sha256`. Returning bytes is NOT proof that this transaction ran. @@ -491,8 +570,19 @@ impl Journal { if matches!(event.evidence, Evidence::Replaced { .. }) { self.replaced += 1; } - if let Evidence::ServicesStarted { services, .. } = event.evidence { - self.started = Some((services, event.observed_at)); + if matches!(event.evidence, Evidence::PredecessorRestored { .. }) { + self.restored += 1; + } + if let Evidence::UpdaterOwnsLedger { ref process, .. } = event.evidence { + self.updater = Some(process.clone()); + } + if matches!(event.evidence, Evidence::LedgerReturnIntent) { + self.original_start_at = Some(event.observed_at); + } + if let Evidence::ServicesStarted { ref services, .. } + | Evidence::RollbackServicesStarted { ref services, .. } = event.evidence + { + self.started = Some((services.clone(), event.observed_at)); } self.phase = next; self.observed_at = event.observed_at; @@ -506,7 +596,14 @@ impl Journal { event.schema_version == 1 && event.handoff_sha256 == self.handoff_hash && event.sequence == self.count + 1 - && (event.sequence as usize) <= MAX_EVENTS + && (event.sequence as usize) + <= if self.handoff.schema_version == 2 { + MAX_V2_EVENTS + } else if self.handoff.pin_transition == PinTransition::WindowsCodePairClockV1 { + MAX_WINDOWS_CLOCK_EVENTS + } else { + MAX_EVENTS + } && event.previous_sha256 == self.head_hash, "HANDOFF_EVENT_CHAIN" ); @@ -642,11 +739,205 @@ impl Journal { digest(outcome_sha256)?; Phase::OutcomePersisted } + ( + Phase::LedgerReturnIntent | Phase::ServicesStarted, + Evidence::RollbackIntent { + cause, + failure_observation_sha256, + }, + ) => { + self.rollback_window(event.observed_at)?; + digest(failure_observation_sha256)?; + match cause { + RollbackCause::StartupFailed { service } => ensure!( + self.phase == Phase::LedgerReturnIntent + && self.handoff.stop_set.contains(service), + "HANDOFF_ROLLBACK_START_FAILURE" + ), + RollbackCause::HealthRejected => ensure!( + self.phase == Phase::ServicesStarted, + "HANDOFF_ROLLBACK_HEALTH_FAILURE" + ), + } + Phase::RollbackIntent + } + ( + Phase::RollbackIntent, + Evidence::RollbackStopped { + process, + ledger_identity_sha256, + observation_sha256, + }, + ) => { + self.rollback_window(event.observed_at)?; + ensure!( + self.updater.as_ref() == Some(process) + && ledger_identity_sha256 == &self.handoff.ledger_identity_sha256, + "HANDOFF_ROLLBACK_ORIGINAL_OWNER" + ); + digest(observation_sha256)?; + Phase::RollbackStopped + } + ( + Phase::RollbackStopped | Phase::PredecessorRestored, + Evidence::RestoreIntent { role }, + ) => { + self.rollback_window(event.observed_at)?; + ensure!( + self.handoff + .files + .iter() + .rev() + .nth(self.restored) + .is_some_and(|f| f.role == *role), + "HANDOFF_RESTORE_ORDER" + ); + Phase::RestoreIntent + } + ( + Phase::RestoreIntent, + Evidence::CandidatePreserved { + role, + observation_sha256, + }, + ) => { + self.rollback_window(event.observed_at)?; + ensure!( + self.handoff + .files + .iter() + .rev() + .nth(self.restored) + .is_some_and(|f| f.role == *role), + "HANDOFF_RESTORE_ORDER" + ); + digest(observation_sha256)?; + Phase::CandidatePreserved + } + ( + Phase::CandidatePreserved, + Evidence::PredecessorRestored { + role, + observed_sha256, + }, + ) => { + self.rollback_window(event.observed_at)?; + ensure!( + self.handoff + .files + .iter() + .rev() + .nth(self.restored) + .is_some_and(|f| f.role == *role && f.old_sha256 == *observed_sha256), + "HANDOFF_RESTORE_PREDECESSOR_HASH" + ); + Phase::PredecessorRestored + } + ( + Phase::PredecessorRestored, + Evidence::PredecessorVerified { + pair, + retained_state_sha256, + predecessor_record_sha256, + }, + ) => { + self.rollback_window(event.observed_at)?; + ensure!( + self.restored == self.handoff.files.len() + && pair == &self.handoff.predecessor + && retained_state_sha256 == &self.handoff.retained_state_sha256 + && predecessor_record_sha256 == &self.handoff.predecessor_record_sha256, + "HANDOFF_RESTORE_PAIR_OR_STATE_CHANGED" + ); + Phase::PredecessorVerified + } + (Phase::PredecessorVerified, Evidence::RollbackLedgerReturnIntent) => { + self.rollback_window(event.observed_at)?; + Phase::RollbackLedgerReturnIntent + } + ( + Phase::RollbackLedgerReturnIntent, + Evidence::RollbackServicesStarted { + services, + ledger_identity_sha256, + observation_sha256, + }, + ) => { + self.rollback_window(event.observed_at)?; + ensure!( + ledger_identity_sha256 == &self.handoff.ledger_identity_sha256, + "HANDOFF_LEDGER_IDENTITY_CHANGED" + ); + let expected: Vec<_> = self + .handoff + .stop_set + .iter() + .copied() + .filter(|s| *s != Service::LinuxAptHelper) + .collect(); + ensure!( + services.len() == expected.len(), + "HANDOFF_STARTED_SERVICE_SET" + ); + for (index, service) in services.iter().enumerate() { + ensure!( + service.service == expected[index], + "HANDOFF_STARTED_SERVICE_SET" + ); + service.process.validate( + if matches!(service.service, Service::LinuxAgent | Service::WindowsAgent) { + &self.handoff.predecessor.agent_sha256 + } else { + &self.handoff.predecessor.helper_sha256 + }, + )?; + ensure!( + !services[..index] + .iter() + .any(|p| p.process.pid == service.process.pid), + "HANDOFF_PROCESS_REUSE" + ); + ensure!( + self.started.as_ref().is_none_or(|(prior, _)| !prior + .iter() + .any(|p| p.process == service.process)), + "HANDOFF_RESTORE_OLD_PROCESS_REUSED" + ); + } + digest(observation_sha256)?; + Phase::RollbackServicesStarted + } + (Phase::RollbackServicesStarted, Evidence::RollbackHealthVerified { receipt }) => { + self.rollback_window(event.observed_at)?; + self.verify_health(receipt, event.observed_at)?; + Phase::RollbackHealthVerified + } + ( + Phase::RollbackHealthVerified, + Evidence::RollbackOutcomePersisted { outcome_sha256 }, + ) => { + self.rollback_window(event.observed_at)?; + digest(outcome_sha256)?; + Phase::OutcomePersisted + } _ => anyhow::bail!("HANDOFF_PHASE_ORDER"), }; Ok(next) } + fn rollback_window(&self, at: u64) -> Result<()> { + ensure!( + self.handoff.schema_version == 2 + && self + .original_start_at + .and_then(|start| at.checked_sub(start)) + .is_some_and(|age| age < 180) + && at < self.handoff.finish_before, + "HANDOFF_ROLLBACK_ORIGINAL_DEADLINE" + ); + Ok(()) + } + fn verify_health(&self, signed: &SignedHealth, at: u64) -> Result<()> { let receipt: HealthReceipt = canonical(&signed.payload, 4096)?; let signature = diff --git a/crates/updater-handoff/tests/handoff_contract.rs b/crates/updater-handoff/tests/handoff_contract.rs index ff3ffbd..a124223 100644 --- a/crates/updater-handoff/tests/handoff_contract.rs +++ b/crates/updater-handoff/tests/handoff_contract.rs @@ -139,7 +139,7 @@ fn services(handoff: &Handoff) -> Vec { service: *service, process: process( 50 + i as u32, - if *service == Service::LinuxAgent { + if matches!(service, Service::LinuxAgent | Service::WindowsAgent) { &handoff.target.agent_sha256 } else { &handoff.target.helper_sha256 @@ -263,6 +263,247 @@ fn full_linux_three_service_handoff_replays_exactly_sixteen_events() { assert_eq!(reopened.phase(), Phase::OutcomePersisted); assert!(reopened.prepare(112, Evidence::StopIntent).is_err()); } +#[test] +fn windows_clock_pair_replays_all_eighteen_events_and_cannot_drop_the_clock_file() { + let mut handoff = handoff(); + handoff.pin_transition = PinTransition::WindowsCodePairClockV1; + handoff.stop_set = vec![Service::WindowsAgent, Service::WindowsHelper]; + handoff.files[2].role = FileRole::WindowsSettings; + handoff.files[3].role = FileRole::WindowsPin; + handoff.files.push(FileTransition { + role: FileRole::WindowsTimeProfile, + old_sha256: h(28), + new_sha256: h(29), + }); + let mut journal = open(&handoff); + let mut events = until_started(&mut journal, &handoff); + let receipt = signed(&receipt(&journal, &handoff), HEALTH_DOMAIN, &key()); + events.push(append( + &mut journal, + 110, + Evidence::HealthVerified { receipt }, + )); + events.push(append( + &mut journal, + 111, + Evidence::OutcomePersisted { + outcome_sha256: h(27), + }, + )); + assert_eq!(events.len(), MAX_WINDOWS_CLOCK_EVENTS); + let mut reopened = open(&handoff); + for event in events { + reopened.replay(&event).unwrap(); + } + assert_eq!(reopened.phase(), Phase::OutcomePersisted); + assert_eq!(reopened.head_sha256(), journal.head_sha256()); + handoff.files.pop(); + assert!(handoff.validate().is_err()); +} +#[test] +fn v2_predecessor_return_keeps_original_attempt_state_owner_and_health_deadlines() { + let mut hnd = handoff(); + hnd.schema_version = 2; + let mut journal = open(&hnd); + let mut events = until_started(&mut journal, &hnd); + events.push(append( + &mut journal, + 111, + Evidence::RollbackIntent { + cause: RollbackCause::HealthRejected, + failure_observation_sha256: h(30), + }, + )); + let mut wrong_owner = process(40, &hnd.updater_sha256); + wrong_owner.birth += 1; + assert!( + journal + .prepare( + 112, + Evidence::RollbackStopped { + process: wrong_owner, + ledger_identity_sha256: h(22), + observation_sha256: h(31) + } + ) + .is_err() + ); + events.push(append( + &mut journal, + 112, + Evidence::RollbackStopped { + process: process(40, &hnd.updater_sha256), + ledger_identity_sha256: h(22), + observation_sha256: h(31), + }, + )); + assert!( + journal + .prepare( + 112, + Evidence::PredecessorVerified { + pair: hnd.predecessor.clone(), + retained_state_sha256: hnd.retained_state_sha256.clone(), + predecessor_record_sha256: hnd.predecessor_record_sha256.clone() + } + ) + .is_err() + ); + for file in hnd.files.iter().rev() { + events.push(append( + &mut journal, + 113, + Evidence::RestoreIntent { role: file.role }, + )); + events.push(append( + &mut journal, + 113, + Evidence::CandidatePreserved { + role: file.role, + observation_sha256: h(32), + }, + )); + assert!( + journal + .prepare( + 113, + Evidence::PredecessorRestored { + role: file.role, + observed_sha256: file.new_sha256.clone() + } + ) + .is_err() + ); + events.push(append( + &mut journal, + 113, + Evidence::PredecessorRestored { + role: file.role, + observed_sha256: file.old_sha256.clone(), + }, + )); + } + events.push(append( + &mut journal, + 114, + Evidence::PredecessorVerified { + pair: hnd.predecessor.clone(), + retained_state_sha256: hnd.retained_state_sha256.clone(), + predecessor_record_sha256: hnd.predecessor_record_sha256.clone(), + }, + )); + events.push(append( + &mut journal, + 115, + Evidence::RollbackLedgerReturnIntent, + )); + let predecessor: Vec<_> = hnd + .stop_set + .iter() + .enumerate() + .map(|(i, service)| StartedService { + service: *service, + process: process( + 70 + i as u32, + if matches!(service, Service::LinuxAgent | Service::WindowsAgent) { + &hnd.predecessor.agent_sha256 + } else { + &hnd.predecessor.helper_sha256 + }, + ), + }) + .collect(); + events.push(append( + &mut journal, + 116, + Evidence::RollbackServicesStarted { + services: predecessor.clone(), + ledger_identity_sha256: h(22), + observation_sha256: h(33), + }, + )); + let mut health = receipt(&journal, &hnd); + health.service_processes = predecessor; + health.signed_sync_applied_at = 117; + health.inventory_received_at = 117; + health.issued_at = 118; + health.valid_until = 500; + let proof = signed(&health, HEALTH_DOMAIN, &key()); + assert!( + journal + .prepare( + 286, + Evidence::RollbackHealthVerified { + receipt: proof.clone() + } + ) + .is_err() + ); + events.push(append( + &mut journal, + 119, + Evidence::RollbackHealthVerified { receipt: proof }, + )); + events.push(append( + &mut journal, + 120, + Evidence::RollbackOutcomePersisted { + outcome_sha256: h(34), + }, + )); + assert_eq!(events.len(), 33); + assert_eq!(journal.phase(), Phase::OutcomePersisted); + let mut reopened = open(&hnd); + for raw in &events { + reopened.replay(raw).unwrap(); + } + assert_eq!(reopened.head_sha256(), journal.head_sha256()); + assert!( + reopened + .prepare( + 121, + Evidence::RollbackIntent { + cause: RollbackCause::HealthRejected, + failure_observation_sha256: h(30) + } + ) + .is_err() + ); + let mut unknown = open(&hnd); + until_started(&mut unknown, &hnd); + append( + &mut unknown, + 111, + Evidence::Unknown { + reason: UnknownReason::OwnerLost, + }, + ); + assert!( + unknown + .prepare( + 112, + Evidence::RollbackIntent { + cause: RollbackCause::HealthRejected, + failure_observation_sha256: h(30) + } + ) + .is_err() + ); + hnd.schema_version = 1; + let mut legacy = open(&hnd); + until_started(&mut legacy, &hnd); + assert!( + legacy + .prepare( + 111, + Evidence::RollbackIntent { + cause: RollbackCause::HealthRejected, + failure_observation_sha256: h(30) + } + ) + .is_err() + ); +} #[test] fn no_ownership_before_stop_no_partial_pair_no_start_before_return() { diff --git a/crates/updater-worker/Cargo.toml b/crates/updater-worker/Cargo.toml index 84c4eaf..356ab9e 100644 --- a/crates/updater-worker/Cargo.toml +++ b/crates/updater-worker/Cargo.toml @@ -4,6 +4,10 @@ version.workspace = true edition.workspace = true license.workspace = true +[[bin]] +name = "rmm-agent-updater" +path = "src/main.rs" + [dependencies] anyhow.workspace = true chrono.workspace = true @@ -19,4 +23,8 @@ rmm-domain = { path = "../domain" } rmm-agent-core = { path = "../agent-core" } rmm-updater = { path = "../updater" } rmm-updater-handoff = { path = "../updater-handoff" } +rmm-update-history = { path = "../update-history" } rmm-updater-linux = { path = "../updater-linux" } + +prost.workspace = true +rmm-protocol = { path = "../protocol" } diff --git a/deploy/server_build_only.py b/deploy/server_build_only.py new file mode 100644 index 0000000..82e5ae0 --- /dev/null +++ b/deploy/server_build_only.py @@ -0,0 +1,137 @@ +#!/usr/bin/env python3 +"""Freeze public sources and build ARM64 server/broker only; never deploy/migrate.""" +import base64 +import gzip +import hashlib +import inspect +import io +import json +import os +from pathlib import Path +import shlex +import subprocess +import sys +import tarfile +import uuid +import vm_access_check as access +ROOT=Path(__file__).resolve().parents[1] +BUILDER='sha256:30ae3d90753bc39b0a98a897784c662aff9598ffab7a98a6298e8aa79145c2ec' + +def sha(raw):return hashlib.sha256(raw).hexdigest() +def write(path,raw): + path.parent.mkdir(mode=0o700,parents=True,exist_ok=True) + with path.open('xb') as f:f.write(raw);f.flush();os.fsync(f.fileno()) + path.chmod(0o600) +def ssh(code,raw=b'',timeout=45): + cfg=access.load_config(ROOT/'credentials/server.conf') + cmd=['ssh','-F','/dev/null','-T','-p',cfg.get('port','22'),'-o','StrictHostKeyChecking=yes','-o','BatchMode=yes','-o','IdentitiesOnly=yes','-o','ForwardAgent=no','-o','ClearAllForwardings=yes','-o','ConnectTimeout=7','-i',str(Path(cfg['ssh_key_path']).expanduser()),cfg['username']+'@'+cfg['address'],shlex.join(['python3','-I','-c',code])] + p=subprocess.run(cmd,input=raw,capture_output=True,timeout=timeout) + if p.returncode:raise RuntimeError('Build-only SSH operation failed; public diagnostics retained by caller') + return json.loads(p.stdout) +def preflight(): + import json,subprocess,os + assert os.uname().machine=='aarch64' and os.geteuid()==0 + def run(a):return subprocess.check_output(a,stderr=subprocess.DEVNULL,text=True,timeout=15) + builder=PARAMETERS['builder'];i=json.loads(run(['docker','image','inspect',builder]))[0] + assert i['Id']==builder and i['Architecture']=='arm64' and i['Os']=='linux' + units={} + for role in ('api','gateway','postgres'): + c=json.loads(run(['docker','inspect','rust-discovery-server-'+role+'-1']))[0] + units[role]={'id':c['Id'],'image':c['Image'],'started_at':c['State']['StartedAt'],'running':c['State']['Running'],'restart_count':c['RestartCount']} + stat=os.statvfs('/opt/rust-discovery/devstate') + return {'architecture':'aarch64','builder':builder,'units':units,'disk_available_bytes':stat.f_bavail*stat.f_frsize} +def stage(): + import io,json,hashlib,tarfile,subprocess,os,sys + from pathlib import Path + p=PARAMETERS;raw=sys.stdin.buffer.read(p['bytes']+1) + assert len(raw)==p['bytes'] and hashlib.sha256(raw).hexdigest()==p['sha256'] + root=Path('/opt/rust-discovery/devstate');case=root/p['release'];case.mkdir(mode=0o700);pkg=case/'package';pkg.mkdir(mode=0o700) + files={} + with tarfile.open(fileobj=io.BytesIO(raw),mode='r:gz') as archive: + for m in archive.getmembers(): + assert m.isfile() and not m.name.startswith('/') and '..' not in Path(m.name).parts and m.name not in files and m.size<=16*1024*1024 + files[m.name]=archive.extractfile(m).read() + assert len(files)<=1500 and sum(map(len,files.values()))<=32*1024*1024 + manifest=json.loads(files['manifest.json']);assert hashlib.sha256(files['manifest.json']).hexdigest()==p['manifest_sha256'] + assert set(files)=={'manifest.json'}|set(manifest['file_hashes']) + assert all(hashlib.sha256(files[n]).hexdigest()==h for n,h in manifest['file_hashes'].items()) + for name,content in files.items(): + path=pkg/name;path.parent.mkdir(mode=0o700,parents=True,exist_ok=True) + with path.open('xb') as stream:stream.write(content);stream.flush();os.fsync(stream.fileno()) + path.chmod(0o400) + with (case/'sealed.json').open('x') as stream:json.dump(p,stream) + with (case/'build-worker.py').open('xb') as stream:stream.write(p['worker'].encode()) + log=(case/'launcher.log').open('xb') + process=subprocess.Popen(['python3','-I',str(case/'build-worker.py')],stdin=subprocess.DEVNULL,stdout=log,stderr=subprocess.STDOUT,start_new_session=True,close_fds=True) + return {'release':p['release'],'case':str(case),'worker_pid':process.pid,'build_only':True,'runtime_deployment':False,'migration_executed':False} +def worker(): + from pathlib import Path + import subprocess,json,hashlib,os + p=PARAMETERS;case=Path('/opt/rust-discovery/devstate')/p['release'];pkg=case/'package';out=case/'build.receipt.json' + assert not out.exists() + def sha(b):return hashlib.sha256(b).hexdigest() + manifest=json.loads((pkg/'manifest.json').read_text());assert sha((pkg/'manifest.json').read_bytes())==p['manifest_sha256'] + assert all(sha((pkg/n).read_bytes())==h for n,h in manifest['file_hashes'].items()) + def run(a):return subprocess.check_output(a,stderr=subprocess.DEVNULL,text=True,timeout=30) + def state(): + result={} + for role in ('api','gateway','postgres'): + c=json.loads(run(['docker','inspect','rust-discovery-server-'+role+'-1']))[0] + result[role]={'id':c['Id'],'image':c['Image'],'started_at':c['State']['StartedAt'],'running':c['State']['Running'],'restart_count':c['RestartCount']} + return result + before=state();assert before==manifest['preflight']['units'];tag='rust-discovery-server:'+p['release'] + with (case/'build.log').open('xb') as log: + r=subprocess.run(['docker','build','--network=none','--pull=false','--iidfile',str(case/'image-id'),'-t',tag,str(pkg)],stdout=log,stderr=subprocess.STDOUT,env={**os.environ,'DOCKER_BUILDKIT':'0'},timeout=1800) + result={'exit_code':r.returncode,'release':p['release'],'tag':tag,'source_manifest_sha256':p['manifest_sha256'],'build_only':True,'runtime_deployment':False,'migration_executed':False} + if r.returncode==0: + image=(case/'image-id').read_text().strip();info=json.loads(run(['docker','image','inspect',image]))[0];assert info['Architecture']=='arm64' and info['Os']=='linux' + result.update(image=image,architecture='arm64',binaries={}) + for name in ('rmm-server','rmm-time-broker-linux'): + expected=run(['docker','run','--rm','--read-only','--cap-drop=ALL','--security-opt','no-new-privileges','--network','none','--entrypoint','sha256sum',image,'/usr/local/bin/'+name]).split()[0] + container=run(['docker','create','--read-only','--network','none','--cap-drop=ALL','--entrypoint','/bin/true',image]) + try: + path=case/name;subprocess.run(['docker','cp',container+':/usr/local/bin/'+name,str(path)],check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,timeout=30) + finally:run(['docker','rm',container]) + raw=path.read_bytes();assert raw[:6]==b'\x7fELF\x02\x01' and raw[18:20]==b'\xb7\x00' and sha(raw)==expected + path.chmod(0o500);result['binaries'][name]={'path':str(path),'bytes':len(raw),'sha256':expected} + assert all(sha((pkg/n).read_bytes())==h for n,h in manifest['file_hashes'].items()) + result['runtime_before']=before;result['runtime_after']=state();result['runtime_unchanged']=before==result['runtime_after'] + with out.open('x') as stream:json.dump(result,stream,sort_keys=True,indent=2);stream.flush();os.fsync(stream.fileno()) + +def freeze(): + os.umask(0o077);ident=uuid.uuid4().hex[:12];folder=ROOT/'devstate/server-build-only'/ident;folder.mkdir(mode=0o700,parents=True) + before=ssh(inspect.getsource(preflight).replace('PARAMETERS',repr({'builder':BUILDER}))+'\nprint(__import__("json").dumps(preflight()))\n') + assert before['disk_available_bytes']>8*1024**3 + names=subprocess.check_output(['git','ls-files','--cached','--others','--exclude-standard','-z'],cwd=ROOT).decode().split('\0') + names=sorted(set(n for n in names if n and (n.startswith(('crates/','proto/','migrations/','tools/','tests/','deploy/linux/','web/src/')) or n in ('Cargo.toml','Cargo.lock','rust-toolchain.toml','web/package.json','web/package-lock.json','web/tsconfig.json','web/index.html','web/vite.config.ts')))) + files={} + for name in names: + p=ROOT/name + assert p.is_file() and not p.is_symlink() and '__pycache__' not in p.parts and p.stat().st_size<=16*1024*1024 + files['source/'+name]=p.read_bytes() + assert all((ROOT/n).read_bytes()==files['source/'+n] for n in names),'source snapshot drift' + assert b'mod windows_sync_alignment;' in files['source/crates/server/src/main.rs'] + assert b'pub mod windows_sync_alignment;' in files['source/crates/domain/src/lib.rs'] + assert 'source/migrations/0020_windows_sync_alignment.sql' in files + inputs={n.removeprefix('source/'):sha(b) for n,b in files.items()} + files['inputs.sha256']=''.join(h+' '+n+'\n' for n,h in inputs.items()).encode() + files['Dockerfile']=('FROM '+BUILDER+' AS build\nWORKDIR /src\nCOPY source/ /src/\nCOPY inputs.sha256 /tmp/rmm-build-inputs.sha256\nRUN 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\nFROM '+before['units']['api']['image']+'\nCOPY --from=build /src/target/release/rmm-server /usr/local/bin/rmm-server\nCOPY --from=build /src/target/release/rmm-time-broker-linux /usr/local/bin/rmm-time-broker-linux\n').encode() + for path in sorted((ROOT/'web/dist').rglob('*')): + if path.is_file():assert not path.is_symlink();files['web/'+str(path.relative_to(ROOT/'web/dist'))]=path.read_bytes() + assert any(n.startswith('web/assets/') and b'windows-sync-alignment' in v for n,v in files.items()),'built WebUI must contain actual new route' + manifest={'schema_version':1,'release':'server205-'+ident,'git_base':subprocess.check_output(['git','rev-parse','HEAD'],cwd=ROOT,text=True).strip(),'builder':BUILDER,'preflight':before,'source_files':inputs,'web':{n[4:]:sha(b) for n,b in files.items() if n.startswith('web/')},'file_hashes':{n:sha(b) for n,b in files.items()},'windows_copied_only_not_qualified':True,'build_only':True,'runtime_deployment':False,'migration_executed':False} + files['manifest.json']=json.dumps(manifest,sort_keys=True,indent=2).encode() + package=folder/'package' + for name,raw in files.items():write(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);write(folder/'package.tar.gz',raw) + sealed={'release':manifest['release'],'sha256':sha(raw),'manifest_sha256':sha(files['manifest.json']),'bytes':len(raw),'source_count':len(inputs)} + write(folder/'sealed.json',json.dumps(sealed,sort_keys=True,indent=2).encode()) + params={**sealed,'worker':inspect.getsource(worker).replace('PARAMETERS',repr(sealed))+'\nworker()\n'} + result=ssh(inspect.getsource(stage).replace('PARAMETERS',repr(params))+'\nprint(__import__("json").dumps(stage()))\n',raw=raw) + write(folder/'stage-result.json',json.dumps(result,sort_keys=True,indent=2).encode()) + print(json.dumps({'folder':str(folder),'sealed':sealed,'stage':result})) +if __name__=='__main__':freeze() diff --git a/deploy/server_deploy_205.py b/deploy/server_deploy_205.py new file mode 100644 index 0000000..1132f86 --- /dev/null +++ b/deploy/server_deploy_205.py @@ -0,0 +1,165 @@ +#!/usr/bin/env python3 +"""Exact reviewed a48f ARM64 deployment; no jobs, Windows starts, or broker changes.""" +import argparse +import inspect +import json +from pathlib import Path +import server_build_only as build +CASE='server205-a48f78614e2e' +IMAGE='sha256:a7fc4243fee414ab6c85c5f4d207b6428005b77ab06903916138a83b4b74e1d4' +MANIFEST='7594ab8eda6cd3e75852ed03ed7033da32e8997898dce05b1b7584f8c14c12ff' + +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<20} + 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/'deployment205-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)==5 + 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/'deployment205-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'] + assert migrations()==19 + w=windows();assert w['generation']==205 and w['boot']=='a9ad0895-5a96-8f2c-8fb6-cfdc2d5225ea'and w['decision']=='2af359c5-5b5c-4992-b445-1c00e271a288'and w['checkpoint']==10137 and w['helper_checkpoint']==135 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':19,'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()==19;check_apps(False);once(case/'deployment205-migration-intent.json',{'image':p['image'],'migration':20}) + log=case/'deployment205-migration.log' + with log.open('xb')as stream:r=subprocess.run(compose+['run','--no-deps','-T','--rm','--name','rmm-server205-migrate-20','migrate'],stdout=stream,stderr=subprocess.STDOUT,timeout=60) + assert r.returncode==0 and migrations()==20;check_apps(False) + assert sql('SELECT count(*) FROM windows_sync_alignment_reviews')=='0' and sql('SELECT count(*) FROM windows_sync_alignment_receipts')=='0' + elif p['action']=='apps': + assert migrations()==20;check_apps(False);once(case/'deployment205-apps-intent.json',{'image':p['image'],'before':before['actual']}) + with(case/'deployment205-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()==20;check_apps(True);once(case/'deployment205-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()==20;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-sync-alignment')[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/('deployment205-'+p['action']+'-result.json'),result);return result + +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('action',choices=('preflight','migrate','apps','web','verify'));args=parser.parse_args() + p={'case':CASE,'image':IMAGE,'manifest':MANIFEST,'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=build.ROOT/'devstate/server-build-only/a48f78614e2e'/('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() diff --git a/docs/evidence/server205-deployment.json b/docs/evidence/server205-deployment.json new file mode 100644 index 0000000..12cfb2e --- /dev/null +++ b/docs/evidence/server205-deployment.json @@ -0,0 +1,57 @@ +{ + "action": "verify", + "admin_receipt_issued_by_deployment": false, + "api": { + "id": "b2c21b96878f603ab386c1eb5e68f7624911bfbe752ee3a39fda88d7dc0ad52c", + "image": "sha256:a7fc4243fee414ab6c85c5f4d207b6428005b77ab06903916138a83b4b74e1d4", + "restart_count": 0, + "running": true, + "started_at": "2026-11-16T12:26:14.452215053Z" + }, + "broker_binary_installed": false, + "broker_chrony_unchanged": true, + "counts": { + "authorizations": 33, + "echo_completion": 1, + "grants": 28, + "jobs": 33, + "outbox": 33, + "windows_grants": 1, + "windows_jobs": 2 + }, + "environment_mounts_uid_security_loopback_unchanged": true, + "gateway": { + "id": "d40af6702762b7fa4cfb00eb22ce47a83b4c83075c9b2e418c688f2b769f242c", + "image": "sha256:a7fc4243fee414ab6c85c5f4d207b6428005b77ab06903916138a83b4b74e1d4", + "restart_count": 0, + "running": true, + "started_at": "2026-11-16T12:26:14.447251562Z" + }, + "health_tls_chain_and_hostname_checked": true, + "image": "sha256:a7fc4243fee414ab6c85c5f4d207b6428005b77ab06903916138a83b4b74e1d4", + "job_authority_created": false, + "migration": 20, + "new_unauthenticated_admin_route_status": 401, + "postgres_unchanged": true, + "protected_pki_jobkey_policy_metadata_unchanged": true, + "schema_version": 1, + "scope": "actual_server205_deployment_not_native_windows_recovery", + "server_binary_sha256": "ef88115eb0184af83738f90fd4c9fd1e96d50eda128bc959909a623c47396559", + "source_manifest_sha256": "7594ab8eda6cd3e75852ed03ed7033da32e8997898dce05b1b7584f8c14c12ff", + "web": { + "assets/index-Be1zm1OZ.css": "916e8870d4e9a9553de452b3ff6c71671bb6a7a22355de0aff432db516a9f3e7", + "assets/index-CxYL42qF.js": "e171152786122c3f93c34cd2beaa75b5494bf71acae7a65a619ef9584a9f0e81", + "index.html": "d38d869fd65d0b0b5a8796e06c5f785b5be46657bc6f089ea9ceaaecf3d3383a" + }, + "windows": { + "boot": "a9ad0895-5a96-8f2c-8fb6-cfdc2d5225ea", + "checkpoint": 10137, + "decision": "2af359c5-5b5c-4992-b445-1c00e271a288", + "generation": 205, + "helper_checkpoint": 135, + "helper_journal": "cb4db2c6-a1b2-4fb3-be9d-1f677de0de2b", + "journal": "3dd1dfb5-d586-472a-af28-7fd4d203e90b", + "revoked": null + }, + "windows_service_started": false +} diff --git a/docs/updater-original-time-generation.md b/docs/updater-original-time-generation.md new file mode 100644 index 0000000..e78c725 --- /dev/null +++ b/docs/updater-original-time-generation.md @@ -0,0 +1,97 @@ +# Signierter Zeitvergleich des ursprünglichen Windows-Updaters + +Quellenstand 16. November 2026. Dies ist ein implementierter und lokal geprüfter +Vertrag, noch kein bereitgestellter Serverpfad und kein realer Updateerfolg. +Der stabile Updater behält seine ursprüngliche Verbindungsgeneration und +Prozessidentität. Der neue Agent erhöht beim regulären ClientHello die aktuelle +Servergeneration. Damit konnte der bisherige Zeitendpunkt einen weiterhin an +denselben Originalauftrag gebundenen Updater nicht mehr bedienen. + +## Enge Ausnahme für Zeitevidenz + +Der vorhandene aktuelle Identitätsvergleich bleibt für Tenant, Asset, Agent, +Enrollment, Assignment, Windows-Boot und Windows-Capability erhalten. Nur +`role=updater`, `binding_schema=2`, ohne Helperimage und mit genau dem im +Originalauftrag gespeicherten stabilen Updaterimage darf eine kleinere +ursprüngliche Generation benutzen. Agent und SYSTEM-Helper müssen weiterhin +die aktuelle Generation nennen. Zukunftsgeneration, anderer Boot, andere +Images, Sequenzrückgang und Sync-Recovery verweigern die Ausnahme. + +Der Server verlangt unter dem bestehenden Agent-Control-Lock genau einen +laufenden/verifizierenden ursprünglichen SYSTEM-Updateauftrag: unveränderte +Jobbytes und Hash, genehmigter unveränderlicher Plan, nicht widerrufene +Authorization, signierter ursprünglicher Grant, reservierter Start sowie weder +Cancel noch Ergebnis. Beide vorhandenen Planakteure benötigen weiterhin +`updates:apply` und `system:execute`; ihre Mitgliedschaften und die relevanten +Job-/Authorizationzeilen werden bis zum Abschluss des Zeitaufrufs lesend +gehalten. Die Zeitantwort erzeugt keine Genehmigung, Ready-Lease oder Wirkung. + +Ein bereits gespeicherter signierter Sync-Entscheid enthält Handoff-/Delegation- +und Head-Hashes, Ownernonce und Originalfrist, jedoch nicht den ursprünglichen +Header oder dessen Generation. Deshalb darf der Zeitpfad diese Daten nicht aus +einem alten Grantzeitpunkt oder irgendeinem historischen Ready-Entscheid raten. +Die bestehende vollständig verifizierende UpdateInflight-Syncstrecke speichert +nun **innerhalb derselben ursprünglichen Transaktion** genau einmal einen +zusätzlichen Auditdatensatz `agent_update_original_context` mit den kanonischen +öffentlichen Handoff-/Delegationbytes und Hashes. Unter demselben Grant sind +andere Bytes oder mehrere Datensätze ein Fehler. Keine Migration, kein neuer +Policy-Wireparameter und keine neue private Schlüsseldatei entstehen daraus. + +Die Ausnahme vergleicht diesen Originalbeleg mit dem **aktuell autoritativen** +gespeicherten und erneut signaturgeprüften Sync-Entscheid, dessen einzigem +passenden negativen UpdateInflight-Acknowledgement und dem Originalplan/-grant. +Header, Job, Versuch, Grant, Authorization, Plan, Boot, ursprüngliche Generation, +Ownernonce, Updaterimage und feste Frist müssen übereinstimmen. Ohne solchen +aktuellen Beleg keine Suche nach einem älteren passenden Entscheid und keine +Ersatzfrist. Die Frist bleibt exakt `consumed_at + 600`; ein Überschreiten +während des Brokeraufrufs verwirft dessen Antwort. Ein historisch verifizierter +Syncbeleg erneuert dabei keine abgelaufene Sync-Lease. Er bindet ausschließlich +die weiterhin laufende Originaloperation für diesen separaten Zeitvergleich. +Unknown, neuer Versuch oder Wiederaufnahme werden nicht autorisiert. + +Dies ist weiterhin mTLS-/signierte Protokollevidenz, keine serverseitige +OS-Prozessattestierung. Der tatsächliche Updater muss unabhängig seinen +gehaltenen Originalprozess, unveränderte geschützte lokale Policy und eigenen +Uhrkontext prüfen. Agent-/Helperzeitprofile werden dadurch nicht ersetzt. + +## Erster Beleg vor jedem Stop + +Vor dem ersten Stop muss der Server den Originalkontext bereits behalten und +der tatsächlich ursprüngliche Helper dessen signiertes UpdateInflight- +Acknowledgement bereits angewandt haben. Andernfalls würde der neue Agent die +Generation ändern, bevor ein ursprünglicher Abgleich belegbar ist. + +Die optionalen Felder `pre_stop_sync_request_base64url` und +`pre_stop_sync_response_base64url` im bestehenden `ReadOriginal` transportieren +nur diese tatsächlich behaltenen Rawbytes: ursprünglicher protobuf-SyncRequest +und vorhandenes JSON `SignedResponse`. Beide fehlen gemeinsam, solange noch kein +passender tatsächlich angewandter Beleg existiert. Andere Methoden dürfen diese +Felder nicht verwenden. Fehlende Felder behalten die bisherigen Wirebytes bei. + +Die Linux-Fullstrecke liest den aktuellen angewandten Entscheid aus dem +Originalledger, prüft die vorhandene originale Applyquittung, Signatur, +Rawrequest-/Responsehashes, False-Ready/Unlock sowie exakten Originalauftrag und +StopIntent. Der Worker verifiziert die Signatur und dieselben Bindungen nochmals +selbst und wartet bei fehlendem Beleg ausschließlich lesend innerhalb seiner +ursprünglichen Boot-/Owner-/Fristbindung. Vorher kein Stop und keine weitere +Aktivierung. Die Windows-Helper-/Workerstrecke verwendet denselben zusätzlichen +Beleg; deren native Bereitstellung wird separat nachgewiesen. + +## Tatsächlich lokal geprüft und verbleibende Abnahme + +- Server all-targets Check und Clippy mit `-D warnings`: bestanden. +- Zwei fokussierte Serververträge bestanden, 0 Fehler/ignoriert, 54 gefiltert: + ausschließlich exakte ursprüngliche Updatergeneration; kanonischer gespeicherter + Originalheader samt Delegation/Grant, Ablehnung von Padding, anderem Grant, + alternativen Headerbytes und geänderter Ownernonce. +- Gemeinsamer all-targets-Clippy-Lauf Server, privilegierter Linux-Helper und + Updater-Worker nach Einbindung des tatsächlichen Pre-Stop-Abgleichs bestanden. +- Formatierung und `git diff --check` bestanden. Ein vorangehender Teilcheck + meldete fehlende direkte Worker-Protokoll-/Prostabhängigkeiten; diese sind + ergänzt. Keine externen Bibliotheksversionen oder Prüfungen wurden unterdrückt. + +Noch nicht ausgeführt: isolierter SQL-/Broker-End-to-End-Fall dieses neuen Pfads, +Deployment, realer alter/neuer Generationswechsel eines genehmigten Updatejobs +und Windows-Updaterzeitnachweis unter dessen tatsächlichem Dienstkonto. Die +lokalen zwei Verträge ersetzen diese Nachweise nicht. Erst die reale Linux-first- +Strecke und anschließend Windows können den Updaterabschluss belegen. diff --git a/docs/windows-sync-alignment-205-implementation.md b/docs/windows-sync-alignment-205-implementation.md new file mode 100644 index 0000000..4fd169d --- /dev/null +++ b/docs/windows-sync-alignment-205-implementation.md @@ -0,0 +1,207 @@ +# Administrativer Kontrollabschluss für Verbindung 205 + +Stand 16. November 2026. Grundlage ist die ausdrückliche Userentscheidung in +Spezifikation 1.28 und der [konkrete Fall](windows-sync-alignment-205-proposal.md). +Dieser Text dokumentiert Quellen und lokale Prüfungen. Eine native Anwendung +oder tatsächliche WebUI-Bestätigung wird damit nicht behauptet. + +Der neue Domainvertrag `windows_sync_alignment` bindet ausschließlich den +bekannten Tenant, Asset, Agent, Boot und Verbindung 205: Agententscheidung +`2af359c5-5b5c-4992-b445-1c00e271a288`, Helperentscheidung +`1a4758ad-0b39-449e-8551-16846851b09a`, Agentcheckpoint 10137. Der tatsächliche +Helpercapturecheckpoint muss mindestens 148 sein und wird im Zeugen exakt +gebunden; er darf bei der Anwendung nicht auf den historischen Applycheckpoint +135 zurückgesetzt werden. Beide ursprünglichen Requests und signierten +Antworten bleiben als vollständige Originalbytes erhalten. + +Der streng typisierte native Zeuge enthält außerdem beide Journalidentitäten, +sechs konkrete Datei-/Lockrollen mit unabhängig gemessenen Windowsdatei-IDs und +Hashes, beide geschützten Bindings und den öffentlichen Verifikationskey, +drei kanonische vollständige Inventarhashes sowie feste Zähler. Er enthält die +ursprünglichen Echo-Offer-/Start-/Outcome-/Resultbytes, die signierte vorhandene +Echo-Abschlussquittung und das abgelaufene Offer ohne Grant. Der Zeuge ist keine +OS-Fernattestierung: der Server prüft seine gespeicherten Originale; der native +Operator muss Dateien, Datenbankinhalte, Locks, geschützte Bindings und alle +Inventare selbst erneut prüfen. Keine Schlüsselbytes gehören in den Zeugen. + +## WebUI und Server + +Der nur im expliziten Entwicklungsprofil registrierte Pfad ist +`/api/v1/tenants/{tenant}/windows-sync-alignment`: + +- `POST` reicht einen unabhängigen Zeugen ein und prüft ihn gegen die + Serverhistorie. Dies erzeugt ausschließlich einen unveränderlichen + administrativen Prüfantrag. +- `GET` liest den gespeicherten Antrag samt letzter Quittung. +- `/{request}/confirm` erfordert eine tatsächliche CSRF-geschützte + Browsersitzung des sichtbar simulierten Testprincipals. Die aktuelle aktive + Testhuman-Mitgliedschaft mit `plans:approve` bleibt bis zum Commit gesperrt. + MCP-/Automation-Scopes oder eine fehlende Sitzung verweigern die Bestätigung. +- `/{request}/receipt` liefert ausschließlich eine gültige signierte + administrative Quittung für exakt diesen Zeugen. + +Die separate Geräteansicht zeigt den vollständigen Zeugen und seinen +kanonischen Hash vor der ausdrücklichen Checkbox-/Buttonbestätigung. Jede +Quittung gilt höchstens fünf Minuten. Ein weiterer tatsächlicher Bestätigungsklick +kann eine neue befristete Quittung für denselben unveränderten Zeugen anfügen; +kein automatischer Refresh und keine Ersetzung alter Quittungen. Jede Quittung +und ihr Audit tragen `dev_test_browser_simulation`, den Testprincipal und +`testsimulation=true`. `ready`, `helper_ready` und `unlock` sind immer falsch. + +Der Server hält dieselbe Kontrollsperre wie der reguläre Abgleich und prüft +aktuelle Identität/Boot/Verbindung sowie den gespeicherten zweiten Head. Beide +ursprünglichen Entscheidungen werden kryptografisch gegen denselben aktuellen +gepinnten Job-Verifikationskey, ihre exakten gespeicherten Bytes und die +kanonisch dekodierten ursprünglichen Proto-Requests geprüft. Ausstellungszeit +wird nur für die **historische** Profilprüfung verwendet; es erfolgt kein +normaler Apply einer abgelaufenen Lease. + +Genau zwei vorhandene Jobs müssen zu den bekannten abgeschlossenen Versuchen +gehören: der erfolgreiche Echoauftrag mit genau einer ursprünglichen +signierten Startfreigabe und die abgelaufene Anfrage ohne Grant. Serverjobbytes +und Angebote müssen mit den unveränderlichen damals genehmigten Planbytes +übereinstimmen. Echo-Consumption/Start/Outcome werden mit der vorhandenen +signierten Abschlussquittung und dem gespeicherten Serverergebnis verbunden. +Ein weiterer Job/Grant, ein anderes Outcome oder abweichende Originale verweigern +diesen Weg. Der noch offene neue Skriptplan wird hierdurch weder genehmigt noch +verlängert. + +Migration 0020 fügt ausschließlich zwei neue Tabellen hinzu: unveränderliche +Prüfanträge und angefügte Quittungen. Beide verwenden erzwungene Tenant-RLS; +der Anwendungsrolle werden nur SELECT und INSERT erteilt. Immutable-Trigger +verweigern UPDATE/DELETE; der Quittungstrigger bindet Nutzlast, gespeicherten +Zeugen, fünfminütige Frist und alle drei falschen Bereitschaftswerte. Keine +alte Tabelle, Jobgenehmigung, Outbox oder reguläre Abgleichentscheidung wird +über diesen Pfad verändert. + +## Tatsächlich lokal geprüft + +- Domain und Server: `cargo clippy --locked --offline -p rmm-server -p + rmm-domain --all-targets -- -D warnings` erfolgreich im vorhandenen isolierten + Linuxbuilder, ohne Netzwerk und mit lesendem Source-Mount. +- Zwei Domainprüfungen bestanden: andere Vorfälle/Verbräuche/veraltete Captures + werden verweigert; Quittungen können keine Bereitschaft oder echte menschliche + Genehmigung behaupten und überschreiten ihre feste Fünfminutengrenze nicht. + Der Codecfixture ist ausdrücklich kein kryptografischer Nativenachweis. +- Ein Servertest bestand: Bestätigung erfordert die echte Browsersitzungsform; + fehlende CSRF/Sitzung, Automationsscopes und unpassender Principalstatus werden + verweigert. +- Web-Typecheck sowie zwei gezielte UItests (neuer Fall 205 und bestehender + Echoabschluss) bestanden. Der neue Test verweigert veränderte Geschichte, + erhöhte Wirkungszähler, andere Verbindung, Bereitschaft, unsichtbar behauptete + menschliche Genehmigung und verlängerte Quittungen. +- In einem separaten lokalen PostgreSQL-16-Container ohne Netzwerk oder + veröffentlichten Port wurden alle 20 Migrationen erfolgreich angewandt. + Beide neuen Tabellen haben erzwungene RLS, die App nur SELECT/INSERT und + die erwarteten drei Unveränderlichkeits-/Validierungstrigger. Danach standen + null Jobs und null ausgestellte Quittungen. Der Testcontainer wurde entfernt. + Beleg: `devstate/windows-sync-alignment-local/a54b4e41-4e95-48e7-84de-f6a9ecd6588c`. + +Noch separat nachzuweisen sind der unabhängig erzeugte native Originalzeuge, +seine tatsächliche serverseitige Prüfung, die echte simulierte WebUI-Interaktion, +die einmalige geschlossene native Anwendung bei gestoppten Diensten und +gehaltenen ursprünglichen Locks sowie der anschließende neue reguläre Abgleich +beider Rollen. Diese lokalen Prüfungen ersetzen keinen dieser Schritte. + +## Tatsächlicher nativer ARM64-Build, weiterhin ohne Bereitstellung + +Ein neuer öffentlicher Quellsatz samt gebauter WebUI wurde anschließend unter +`devstate/server-build-only/a48f78614e2e` eingefroren. Er enthält 398 öffentliche +Compiler-/Test-/Frontenddateien. Die 205-Domain-/Serverquellen und Migration 0020 +sind mit ihren oben geprüften Bytes enthalten. Mitkopierte Windowsquellen +stellen keinen Windows-Abnahmenachweis dar; spätere Windowsänderungen verändern +diesen bereits eingefrorenen Serverbuild nicht. + +Der Build lief tatsächlich auf dem ARM64-Server ausschließlich unter +`/opt/rust-discovery/devstate/server205-a48f78614e2e`. `docker build` verwendete +`--network=none --pull=false` und den zuvor unabhängig aus Docker-Metadaten als +ARM64/Linux bestätigten vorhandenen Builder +`sha256:30ae3d90753bc39b0a98a897784c662aff9598ffab7a98a6298e8aa79145c2ec`. +Dort bestanden Server und Zeitbroker `cargo clippy --locked --offline +--all-targets -- -D warnings`; beide Releaseprogramme wurden erfolgreich gebaut. +Die Programme wurden aus dem Image extrahiert, als tatsächliche AArch64-ELFs +geprüft und mit den im Image gemessenen Hashes verglichen. + +| Gegenstand | Tatsächlicher SHA-256 | +|---|---| +| Quellen-/Webmanifest | `7594ab8eda6cd3e75852ed03ed7033da32e8997898dce05b1b7584f8c14c12ff` | +| Übertragenes Paketarchiv | `10110359967db1cca67b879a6620f196f5449e187f8cf24d687867baeefaaf38` | +| Image `rust-discovery-server:server205-a48f78614e2e` | `a7fc4243fee414ab6c85c5f4d207b6428005b77ab06903916138a83b4b74e1d4` | +| `rmm-server`, 27.061.568 Byte | `ef88115eb0184af83738f90fd4c9fd1e96d50eda128bc959909a623c47396559` | +| `rmm-time-broker-linux`, 1.072.816 Byte | `da8e6644b221f012322ce26f8a58c0ad4e7e8980d0648f5037d6ea99d8be599a` | +| Nativer Buildbeleg | `a00c38fe68d01928167fbb0116c5e904aed29e89fa8d920ac89e833d2d8275f5` | +| Nativer vollständiger Buildlog | `1c5e3ab12a4c734d93d5c0dbd658bb1b0bf3fcb226a3ca0009dc7b7ea7b6c085` | + +Die Rohprogramme liegen auf dem Server unmittelbar im genannten Fallverzeichnis; +Quellen und Webartefakte unter `package/`. Öffentliche Originalbelege und Logs +sind zusätzlich lokal als `native-build.receipt.json`, `native-build.log` und +`native-build-worker.py` erhalten. Der Controller ist +`deploy/server_build_only.py`. Er führt weder Compose noch SQL aus und startet +kein Anwendungsprogramm. Nur `sha256sum` lief kurz in einem abgeschotteten +Artefaktcontainer. Die tatsächlichen API-, Gateway- und PostgreSQL-Container +hatten vor und nach dem Build dieselben IDs, Images, Startzeiten und +Restartzähler; `runtime_unchanged=true` ist separat gespeichert. Kein Brokerpfad, +Pin, Dienst, Mount oder Loopbackvertrag wurde geändert. Das neue Image und die +WebUI sind damit **gebaut, noch nicht durch diesen Schritt bereitgestellt**. + +Der vorangegangene erhaltene Fall `server205-68a4e912fe1c` endete mit Exit 101: +Der erste Paketfilter hatte die per Rust-`#[path]` eingebundene Datei +`tests/backend_root_logs.rs` nicht aufgenommen. Der vollständige öffentliche +`tests/`-Baum wurde ergänzt und ein neuer unveränderlicher Fall gebaut. Kein +Testtarget oder Clippyfehler wurde unterdrückt; der fehlgeschlagene Originalbeleg +bleibt erhalten. Das erfolgreiche Paket verwendet keinen fest codierten alten +Releasepfad und ersetzt keine bereits vorhandenen Rohartefakte. + +## Tatsächlich bereitgestellt: Migration 20, API, Gateway und WebUI + +Der anschließend ausdrücklich beauftragte Deployment-Abnahmeschritt ist +abgeschlossen. Vor jeder Mutation wurde die tatsächliche Composekette der +bestehenden API aus ihren Containerlabels gelesen und mit allen vorhandenen +Overlays erhalten. Eine zusätzliche feste Overlaydatei ändert ausschließlich +die Images von API, Gateway und Migrator auf das oben qualifizierte Image +`a7fc4243…` mit `pull_policy: never`. Das vollständige aufgelöste Composemodell +wurde auf genau diese drei Änderungen verglichen. Container-Environmentwerte +wurden ausschließlich intern verglichen; Protokolle enthalten nur ihre Hashes. +Bei der Vorprüfung wurde Compose-`entrypoint: null` korrekt als Vererbung des +unveränderten Image-Entrypoints normalisiert; es wurde kein Entrypoint geändert. + +Die echte Migration über das qualifizierte Migratorprogramm erhöhte den +geprüften SQLx-Stand von 19 auf 20. Alle bestehenden Migrationschecksummen +entsprachen exakt den eingefrorenen Quellen. Die zwei neuen Tabellen waren +anschließend leer; keine Quittung oder Jobgenehmigung wurde ausgestellt. +Danach wurden ausschließlich API und Gateway mit `up --no-deps --no-build +--pull never` neu erstellt. PostgreSQL, Chrony und der Zeitbroker wurden nicht +neu gestartet; Brokerbinary, -pins und -konfiguration blieben unverändert. + +Beide neuen Container laufen mit dem exakten Image +`sha256:a7fc4243fee414ab6c85c5f4d207b6428005b77ab06903916138a83b4b74e1d4`, +Startzeit 16. November 2026, 12:26:14 UTC, Restartzähler null. Ihre tatsächlichen +Serverbinaryhashes entsprechen `ef88115e…`. UID/GID 10001, vollständige Envwerte, +Mounts einschließlich des nur lesenden Brokersockets, Netzwerknamen, +Loopbackbindungen 127.0.0.1:18443/18444, Readonly-Rootfs, CapDrop ALL und +no-new-privileges wurden vor und nach dem Wechsel verglichen und erhalten. +PostgreSQL hat weiterhin keinen veröffentlichten Port und dieselbe +Containeridentität/Startzeit. Die tatsächlichen Prozess-/Startbelege von Broker +und Chrony sowie die Metadaten der ursprünglichen PKI-, Jobkey- und Policybäume +sind unverändert. + +API und Gateway lieferten tatsächlich HTTPS-Health 200 mit geprüftem CA-Vertrauen +und passendem Servernamen; der TCP-Override für den Gatewaytest veränderte nur +127.0.0.1:18444, SNI/Namensprüfung blieben +`discovery.ease-technologies.de`. Die neue Verwaltungsroute antwortete ohne +Anmeldung mit 401. Die neue WebUI wurde über unveränderliche Assetnamen und +zuletzt atomar ersetzten Index bereitgestellt; die tatsächlich über HTTPS +abgeholten Indexbytes entsprechen dem eingefrorenen Hash `d38d869f…`. + +Vorher und nachher bestanden unverändert 33 Jobs, 28 Grants, 33 Autorisierungen +und 33 Outboxeinträge. Windows blieb bei exakt zwei Jobs/einem ursprünglichen +Echo-Grant sowie Verbindung 205/Checkpoint 10137/Entscheidung `2af359c5…` und +Helperbezug 135. Dieser Schritt startete keinen Windowsdienst und erzeugte +keine Startfreigabe. Die tatsächliche administrative WebUI-Bestätigung und +native geschlossene Anwendung sind separate, anschließend koordinierte Schritte. + +Controller: `deploy/server_deploy_205.py`. Originale und Ergebnisbelege liegen +auf dem Server unter `server205-a48f78614e2e/deployment205-*` und lokal unter +`devstate/server-build-only/a48f78614e2e/local-deployment-*.json`. +Ein kompakter öffentlicher Abschlussbeleg steht in +`docs/evidence/server205-deployment.json`. diff --git a/migrations/0020_windows_sync_alignment.sql b/migrations/0020_windows_sync_alignment.sql new file mode 100644 index 0000000..4b93188 --- /dev/null +++ b/migrations/0020_windows_sync_alignment.sql @@ -0,0 +1,68 @@ +-- Explicit connection-205 administrative closure only. No reconciliation, +-- grant, ready state, job, offer or original-history mutation is performed. +CREATE TABLE windows_sync_alignment_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}$'), + 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'='205' + AND witness->>'boot_id'='a9ad0895-5a96-8f2c-8fb6-cfdc2d5225ea' + AND witness->>'agent_last_decision'='2af359c5-5b5c-4992-b445-1c00e271a288' + AND witness->>'helper_last_decision'='1a4758ad-0b39-449e-8551-16846851b09a') +); +CREATE TABLE windows_sync_alignment_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, + 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_sync_alignment_reviews(tenant_id,request_id) +); +DO $$ DECLARE t text; BEGIN + FOREACH t IN ARRAY ARRAY['windows_sync_alignment_reviews','windows_sync_alignment_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_sync_alignment_receipt() RETURNS trigger LANGUAGE plpgsql +SET search_path=pg_catalog,public AS $$ +DECLARE w windows_sync_alignment_reviews%ROWTYPE; r jsonb; +BEGIN + SELECT * INTO STRICT w FROM windows_sync_alignment_reviews WHERE tenant_id=NEW.tenant_id AND request_id=NEW.request_id; + r=convert_from(NEW.payload,'UTF8')::jsonb; + IF r->>'domain' IS DISTINCT FROM 'rmm.dev.windows-sync-admin-closed-alignment.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 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_SYNC_ALIGNMENT_MISMATCH'; END IF; + RETURN NEW; +END $$; +CREATE TRIGGER validate_alignment_receipt BEFORE INSERT ON windows_sync_alignment_receipts + FOR EACH ROW EXECUTE FUNCTION check_windows_sync_alignment_receipt(); diff --git a/web/src/api.ts b/web/src/api.ts index c58e70f..dba12b5 100644 --- a/web/src/api.ts +++ b/web/src/api.ts @@ -208,6 +208,10 @@ export function validateInput(input: PlanInput): void { if (input.action === 'run_script') { if (privilegedScriptProfile(input.parameters, 'system') !== fullMaintenanceScriptProfile) throw new Error('SYSTEM-Skript benötigt ausdrücklich full_maintenance_v1'); } else if (input.action === 'ensure_package') validateWindowsMsiInput(input); + else if (input.action === 'reboot') { + validateWindowsReboot(input.parameters.reason, input.parameters.dependency_group, input.parameters.reconnect_timeout_seconds, input.parameters.timeout_seconds, input.parameters.max_output_bytes); + if (Object.keys(input.parameters).some(k => !['execution_identity', 'reason', 'dependency_group', 'reconnect_timeout_seconds', 'timeout_seconds', 'max_output_bytes'].includes(k)) || (input.artifact_ids?.length ?? 0) !== 0) throw new Error('Windows-Neustart enthält fremde Parameter oder Artefakte'); + } else { if (input.action !== 'set_service_state') throw new Error('SYSTEM ausschließlich für typisierte eigene Windows-Fixturedienste oder feste MSI-Rezepte; keine SYSTEM-Shell'); validateSystemService(input.parameters.unit, input.parameters.state, input.parameters.timeout_seconds, input.parameters.max_output_bytes); @@ -233,6 +237,10 @@ export function validateSystemService(unit: unknown, state: unknown, runtime: un if (state !== 'running' && state !== 'stopped') throw new Error('SYSTEM-Dienstzustand ausschließlich running oder stopped'); if (typeof runtime !== 'number' || !Number.isSafeInteger(runtime) || runtime < 1 || runtime > 120 || typeof output !== 'number' || !Number.isSafeInteger(output) || output < 1 || output > 65536) throw new Error('SYSTEM-Dienstlimits maximal 120 s und 64 KiB'); } +export function validateWindowsReboot(reason: unknown, group: unknown, reconnect: unknown, runtime: unknown, output: unknown): void { + if (typeof reason !== 'string' || !reason.length || new TextEncoder().encode(reason).length > 1024 || typeof group !== 'string' || !/^[A-Za-z0-9_.@-]{1,255}$/.test(group) + || reconnect !== 180 || runtime !== 60 || typeof output !== 'number' || !Number.isSafeInteger(output) || output < 1 || output > 65536) throw new Error('Windows-SYSTEM-Neustart benötigt feste 180s Wiederkontakt, 60s Laufzeit und höchstens 64KiB Ausgabe'); +} /** These are immutable target definitions, never evidence of executable jobs. */ export function planTargetPreviews(plan: RecordValue): unknown[] | null { if (Array.isArray(plan.resolved_targets) && plan.resolved_targets.some(value => diff --git a/web/src/main.tsx b/web/src/main.tsx index 2bf83fd..701449b 100644 --- a/web/src/main.tsx +++ b/web/src/main.tsx @@ -8,6 +8,7 @@ import { allowed, availableActions, parseStrictJson, powerShellApprovalBlockers, 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 { Login } from './login'; import { ConsoleOutput, outputText } from './console-output'; import { scriptApprovalBlockers, scriptPlanJobs, verifyScriptPlan } from './script-console'; @@ -51,6 +52,16 @@ export function SystemPlanNotice({ plan }: { plan: RecordValue }) { if (!jobs.length) return null; return ; } +export function WindowsRebootPlanNotice({ plan }: { plan: RecordValue }) { + try { + const jobs = systemPlanJobs(plan).filter(p => record(p.action).action === 'reboot'); + if (!jobs.length) return null; + return ; + } catch { return ; } +} export function WindowsMsiPlanNotice({ plan }: { plan: RecordValue }) { try { const jobs = windowsMsiPlanJobs(plan); if (!jobs.length) return null; @@ -103,7 +114,7 @@ function Devices({ tenantId, auth, selected, setSelected }: { tenantId: string;

Fester Auswahlsnapshot ({selected.length}): {selected.join(', ') || 'keine Ziele'}

{asset &&

Inventardetail {asset}

{detail.data && <>}
} {tenantId === recoveryTenant && asset === recoveryAsset && allowed(auth, 'inventory:read') && - <>} + <>} ; } const initialParameters: Record = { @@ -200,6 +211,7 @@ function PlanDetail({ tenantId, id, auth, onOperation }: { tenantId: string; id:

Plan-ID: {id}

Exakter gespeicherter Planhash: {stringField(plan.data, 'plan_hash')}

Feste Ziele: {Array.isArray(plan.data.resolved_targets) ? plan.data.resolved_targets.length : 'unknown'}. Die folgenden Zielpreviews sind unveränderliche Plandefinitionen, keine ausführbaren Jobs oder angelegten Versuche. Diese entstehen erst nach Genehmigung.

+ @@ -232,7 +244,7 @@ function OperationDetail({ tenantId, id, auth, openPlan }: { tenantId: string; i function JobDetail({ tenantId, id, auth }: { tenantId: string; id: string; auth: Session }) { const job = useResource(async signal => record(await request(tenantPath(tenantId, `/jobs/${encodeURIComponent(id)}`), { signal })), [tenantId, id], true); const [error, setError] = useState(null), [busy, setBusy] = useState(false); - return

Job {id}

verifying = Nachprüfung läuft · unknown = Wirkung unklar, kein Retry · awaiting_reboot = autorisierter Folgejob nötig. cancel_requested ist kein bestätigter Abbruch, keine Rollbackzusage.

{job.data && <>} + return

Job {id}

verifying = Nachprüfung läuft · unknown = Wirkung unklar, kein Retry · awaiting_reboot = Neustart oder Wiederanmeldung zur Nachprüfung ausstehend. Neue Neustartjobs benötigen eine eigene Genehmigung. cancel_requested ist kein bestätigter Abbruch, keine Rollbackzusage.

{job.data && <>}
{ e.preventDefault(); const reason = new FormData(e.currentTarget).get('reason'); setBusy(true); setError(null); try { await request(tenantPath(tenantId, `/jobs/${encodeURIComponent(id)}/cancel`), { csrf: auth.csrf_token, body: { reason } }); job.reload(); } catch (e) { setError(errorText(e)); } finally { setBusy(false); } }}>
; } function Workspace({ auth, logout }: { auth: Session; logout: () => void }) { diff --git a/web/src/safety.test.tsx b/web/src/safety.test.tsx index 8f0c149..cbb2839 100644 --- a/web/src/safety.test.tsx +++ b/web/src/safety.test.tsx @@ -84,6 +84,19 @@ describe('immutable catalog and strict import contracts', () => { }); }); describe('root and dedicated dev-test APT actions', () => { + it('binds a SYSTEM reboot to the fixed native profile and rejects extra effects before approval', async () => { + const action = { action: 'reboot', reason: 'Windows-MVP', dependency_group: 'windows-mvp-single', reconnect_timeout_seconds: 180 }; + const value: PlanInput = { tenant_id: 't', action: 'reboot', targets: { asset_ids: ['asset'] }, parameters: { execution_identity: 'system', reason: action.reason, dependency_group: action.dependency_group, reconnect_timeout_seconds: 180, timeout_seconds: 60, max_output_bytes: 4096 }, schedule: { not_before: '', start_before: '', offline_policy: 'wait_until_deadline' }, rollout: { max_parallel: 1, halt_after_failures: 1 }, reason: 'unit' }; + await expect(validateSensitiveInput(value, auth)).rejects.toThrow('system:execute'); + await validateSensitiveInput(value, { ...auth, permissions: ['system:execute'] }); + const make = async (change: Record = {}) => { + const jobs = [{ payload: { execution_identity: 'system', asset_id: 'asset', action: { ...action, ...change }, max_runtime_seconds: 60, max_output_bytes: 4096 } }]; + const raw = new TextEncoder().encode(JSON.stringify({ jobs })); + return { jobs, plan_payload_bytes: Array.from(raw), plan_hash: await sha256(raw) }; + }; + await verifyPlanIntegrity(await make()); + for (const change of [{ reconnect_timeout_seconds: 181 }, { command: 'shutdown' }, { force: true }, { reason: '' }]) await expect(verifyPlanIntegrity(await make(change))).rejects.toThrow(); + }); it('requires independent system scope and verifies the exact bounded SYSTEM service plan', async () => { const value: PlanInput = { tenant_id: 't', action: 'set_service_state', targets: { asset_ids: ['asset'] }, parameters: { execution_identity: 'system', unit: 'RmmDiscoveryFixtureService', state: 'running', timeout_seconds: 30, max_output_bytes: 4096 }, schedule: { not_before: '', start_before: '', offline_policy: 'wait_until_deadline' }, rollout: { max_parallel: 1, halt_after_failures: 1 }, reason: 'unit only' }; for (const permissions of [undefined, [], ['root:execute']]) await expect(validateSensitiveInput(value, { ...auth, permissions })).rejects.toThrow('system:execute'); diff --git a/web/src/safety.ts b/web/src/safety.ts index ee8a299..5d04539 100644 --- a/web/src/safety.ts +++ b/web/src/safety.ts @@ -1,4 +1,4 @@ -import { Action, PlanInput, RecordValue, Session, planTargetPreviews, record, text, validateSystemService, windowsScriptProfile, logWindow, validateWindowsLogLimits, windowsEventLogFixtureSource, windowsEventLogFixtureChannel, windowsEventLogFixtureProvider, WindowsMsiManifest, MsiPostcondition, windowsMsi, windowsMsiManifest, windowsMsiAction, validateWindowsMsiInput, validateWindowsMsiLimits, msiUuid, fullMaintenanceScriptProfile, privilegedScriptProfile, validateScriptIdentityProfile } from './api'; +import { Action, PlanInput, RecordValue, Session, planTargetPreviews, record, text, validateSystemService, validateWindowsReboot, windowsScriptProfile, logWindow, validateWindowsLogLimits, windowsEventLogFixtureSource, windowsEventLogFixtureChannel, windowsEventLogFixtureProvider, WindowsMsiManifest, MsiPostcondition, windowsMsi, windowsMsiManifest, windowsMsiAction, validateWindowsMsiInput, validateWindowsMsiLimits, msiUuid, fullMaintenanceScriptProfile, privilegedScriptProfile, validateScriptIdentityProfile } from './api'; import { validateAgentUpdateAction } from './agent-updates'; export const hashPattern = /^[0-9a-f]{64}$/; @@ -85,8 +85,9 @@ export async function validateSensitiveInput(input: PlanInput, auth: Session) { if (!allowed(auth, 'system:execute')) throw new Error('system:execute unbekannt oder nicht erteilt; root:execute enthält dieses Recht nicht'); if (input.action === 'run_script') { if (privilegedScriptProfile(input.parameters, 'system') !== fullMaintenanceScriptProfile) throw new Error('SYSTEM ausschließlich für typisierte Aktionen oder explizit full_maintenance_v1'); - } else if (input.action !== 'set_service_state' && input.action !== 'ensure_package') throw new Error('SYSTEM ausschließlich für typisierte Dienstaktionen oder feste MSI-Rezepte'); + } else if (input.action !== 'set_service_state' && input.action !== 'ensure_package' && input.action !== 'reboot') throw new Error('SYSTEM ausschließlich für typisierte Dienstaktionen, feste MSI-Rezepte oder den gesonderten festen Neustart'); if (input.action === 'set_service_state') validateSystemService(input.parameters.unit, input.parameters.state, input.parameters.timeout_seconds, input.parameters.max_output_bytes); + if (input.action === 'reboot') validateWindowsReboot(input.parameters.reason, input.parameters.dependency_group, input.parameters.reconnect_timeout_seconds, input.parameters.timeout_seconds, input.parameters.max_output_bytes); } if (Object.prototype.hasOwnProperty.call(input.parameters, 'windows_msi_manifest') || (input.action === 'ensure_package' && input.parameters.execution_identity === 'system')) { const original = canonical(input), m = validateWindowsMsiInput(input); await verifyWindowsMsiManifest(m); @@ -362,6 +363,11 @@ export async function verifyPlanIntegrity(plan: RecordValue) { } for (const payload of systemJobs) { const action = record(payload.action); + if (action.action === 'reboot') { + exact(action, ['action', 'reason', 'dependency_group', 'reconnect_timeout_seconds']); + validateWindowsReboot(action.reason, action.dependency_group, action.reconnect_timeout_seconds, payload.max_runtime_seconds, payload.max_output_bytes); + continue; + } if (action.action === 'update_agent') { validateAgentUpdateAction(action, payload.execution_identity); if (payload.max_runtime_seconds !== 600 || typeof payload.max_output_bytes !== 'number' || !Number.isSafeInteger(payload.max_output_bytes) || payload.max_output_bytes < 1 || payload.max_output_bytes > 65536) throw new Error('SYSTEM-Agentupdate benötigt festes600s/64KiB-Budget'); diff --git a/web/src/sync-alignment-review.test.ts b/web/src/sync-alignment-review.test.ts new file mode 100644 index 0000000..2ff7597 --- /dev/null +++ b/web/src/sync-alignment-review.test.ts @@ -0,0 +1,21 @@ +import { expect, it } from 'vitest'; +import { canonicalJson } from './api'; +import { sha256 } from './safety'; +import { alignmentReview } from './sync-alignment-review'; +it('binds the exact 205 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: 205, boot_id: 'a9ad0895-5a96-8f2c-8fb6-cfdc2d5225ea', agent_checkpoint: 10137, helper_checkpoint: 155, + agent_last_decision: '2af359c5-5b5c-4992-b445-1c00e271a288', helper_last_decision: '1a4758ad-0b39-449e-8551-16846851b09a', verification_key_id: 'a'.repeat(64), + counts: { agent_jobs: 2, agent_consumed: 1, agent_starts: 1, agent_outcomes: 1, helper_consumed: 0, helper_starts: 0, helper_outcomes: 0, system_intents: 0 } }; + const witness_sha256 = await sha256(new TextEncoder().encode(canonicalJson(witness))); + const request_id = '78009224-dcb3-4877-a519-8bf3284d0572'; + const receipt = { domain: 'rmm.dev.windows-sync-admin-closed-alignment.v1', schema_version: 1, request_id, 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, witness, witness_sha256, receipt }; + expect((await alignmentReview(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: 134 } }]) { + await expect(alignmentReview({ ...view, receipt: { ...receipt, ...changed } })).rejects.toThrow(); + } + await expect(alignmentReview({ ...view, witness: { ...witness, connection_generation: 150 } })).rejects.toThrow(); + await expect(alignmentReview({ ...view, witness: { ...witness, counts: { ...witness.counts, helper_consumed: 1 } } })).rejects.toThrow(); +}); diff --git a/web/src/sync-alignment-review.tsx b/web/src/sync-alignment-review.tsx new file mode 100644 index 0000000..7d51c0a --- /dev/null +++ b/web/src/sync-alignment-review.tsx @@ -0,0 +1,77 @@ +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; receipt: RecordValue | null } +export async function alignmentReview(value: unknown): Promise { + const r = record(value), w = record(r.witness); + if (typeof r.request_id !== 'string' || typeof r.witness_sha256 !== 'string' || + w.schema_version !== 1 || w.tenant_id !== tenant || w.asset_id !== asset || w.agent_id !== agent || + canonicalJson(w.counts) !== canonicalJson({ agent_jobs: 2, agent_consumed: 1, agent_starts: 1, agent_outcomes: 1, helper_consumed: 0, helper_starts: 0, helper_outcomes: 0, system_intents: 0 }) || + w.connection_generation !== 205 || w.enrollment_generation !== 1 || w.assignment_version !== 1 || + w.boot_id !== 'a9ad0895-5a96-8f2c-8fb6-cfdc2d5225ea' || w.agent_checkpoint !== 10137 || + typeof w.helper_checkpoint !== 'number' || w.helper_checkpoint < 148 || + w.agent_last_decision !== '2af359c5-5b5c-4992-b445-1c00e271a288' || + w.helper_last_decision !== '1a4758ad-0b39-449e-8551-16846851b09a' || + 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 205.'); + } + 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-sync-admin-closed-alignment.v1' || receipt.schema_version !== 1 || + receipt.request_id !== r.request_id || receipt.witness_sha256 !== r.witness_sha256 || + 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 SyncAlignmentReview({ auth }: { auth: Session }) { + const [review, setReview] = useState(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-sync-alignment'); + 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 alignmentReview(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 alignmentReview(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
+

Administrativer Abschluss Windows-Verbindung 205

+

Dieser ausdrücklich begrenzte Eingriff erhält beide Originalentscheidungen, Identität, Journale und bisherige Jobhistorie. Er schließt ausschließlich den belegten wirkungslosen Kontrollspalt. Die Quittung erteilt keine Bereitschaft, Entsperrung oder Jobgenehmigung. Beide Rollen müssen danach einen neuen regulären signierten Abgleich bestehen.

+