From cc5c93596d0864c526b69a4f7efca805599b6ea1 Mon Sep 17 00:00:00 2001 From: Kevin Janssen Date: Sat, 14 Nov 2026 15:55:45 +0100 Subject: [PATCH 1/7] feat: add pure signed agent release verifier without apply authority --- Cargo.lock | 13 + Cargo.toml | 2 +- crates/updater/Cargo.toml | 14 + crates/updater/src/lib.rs | 12 + crates/updater/src/manifest.rs | 385 +++++++++++++++ crates/updater/tests/fixtures/release_v1.json | 1 + crates/updater/tests/release_contract.rs | 317 +++++++++++++ docs/agent-updater-proposal.md | 442 ++++++++++++++++++ 8 files changed, 1185 insertions(+), 1 deletion(-) create mode 100644 crates/updater/Cargo.toml create mode 100644 crates/updater/src/lib.rs create mode 100644 crates/updater/src/manifest.rs create mode 100644 crates/updater/tests/fixtures/release_v1.json create mode 100644 crates/updater/tests/release_contract.rs create mode 100644 docs/agent-updater-proposal.md diff --git a/Cargo.lock b/Cargo.lock index 08bd7ff..2a283d4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2364,6 +2364,19 @@ dependencies = [ "uuid", ] +[[package]] +name = "rmm-updater" +version = "0.1.0" +dependencies = [ + "anyhow", + "ed25519-dalek", + "hex", + "serde", + "serde_json", + "sha2 0.10.9", + "uuid", +] + [[package]] name = "rsa" version = "0.9.10" diff --git a/Cargo.toml b/Cargo.toml index ffa935a..1101ac5 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"] +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"] [workspace.package] version = "0.1.0" diff --git a/crates/updater/Cargo.toml b/crates/updater/Cargo.toml new file mode 100644 index 0000000..ed2c5b9 --- /dev/null +++ b/crates/updater/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "rmm-updater" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +anyhow.workspace = true +ed25519-dalek = "=2.2.0" +hex.workspace = true +serde.workspace = true +serde_json.workspace = true +sha2.workspace = true +uuid.workspace = true diff --git a/crates/updater/src/lib.rs b/crates/updater/src/lib.rs new file mode 100644 index 0000000..385637f --- /dev/null +++ b/crates/updater/src/lib.rs @@ -0,0 +1,12 @@ +//! Pure release verification. This crate does not install, stage, start services, +//! grant approval, persist antirollback state, or trust keys from the network. +//! +//! See docs/agent-updater-proposal.md for the separate, unfinished integration. + +mod manifest; + +pub use manifest::{ + ActiveRelease, ArtifactDescriptor, ArtifactRole, MAX_ARTIFACT_BYTES, MAX_MANIFEST_BYTES, + Platform, RELEASE_SIGNATURE_DOMAIN, ReleaseManifest, ReleaseRelation, SignedRelease, + TrustedContext, TrustedUpdateKey, UpdateKeyring, VerifiedRelease, verify_release, +}; diff --git a/crates/updater/src/manifest.rs b/crates/updater/src/manifest.rs new file mode 100644 index 0000000..df5ba57 --- /dev/null +++ b/crates/updater/src/manifest.rs @@ -0,0 +1,385 @@ +use std::{collections::BTreeMap, io::Read}; + +use anyhow::{Context, Result, bail, ensure}; +use ed25519_dalek::{Signature, VerifyingKey}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use uuid::Uuid; + +pub const MAX_MANIFEST_BYTES: usize = 16 * 1024; +/// Verification limit for a FUTURE update-specific streaming transport. +/// The existing server artifact route only permits 256 KiB and is unchanged. +pub const MAX_ARTIFACT_BYTES: u64 = 256 * 1024 * 1024; +pub const RELEASE_SIGNATURE_DOMAIN: &[u8] = b"rmm.agent-release.v1\0"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum Platform { + #[serde(rename = "x86_64-unknown-linux-gnu")] + LinuxX64, + #[serde(rename = "x86_64-pc-windows-msvc")] + WindowsX64, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ArtifactRole { + Agent, + Helper, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ArtifactDescriptor { + pub role: ArtifactRole, + pub artifact_id: Uuid, + pub sha256: String, + pub bytes: u64, +} + +/// Exact field order defines codec version 1; no maps or floating point fields. +/// These public types describe UNTRUSTED metadata, never update authority. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ReleaseManifest { + pub schema_version: u32, + pub release_id: Uuid, + pub release_sequence: u64, + pub version: String, + pub platform: Platform, + pub published_at: u64, + pub expires_at: u64, + pub protocol_major: u32, + pub state_schema: u32, + pub minimum_updater_version: u32, + pub artifacts: [ArtifactDescriptor; 2], +} + +/// Already-decoded, bounded transport input. No algorithm negotiation exists. +pub struct SignedRelease<'a> { + pub schema_version: u32, + pub key_id: &'a str, + pub payload_bytes: &'a [u8], + pub signature: &'a [u8], +} + +/// Provisioned update trust, not a key returned by a manifest/job/server request. +/// Construction validates raw keys and IDs; it does not authenticate provisioning. +pub struct TrustedUpdateKey { + key: VerifyingKey, + key_id: String, + platform: Platform, + first_sequence: u64, + last_sequence: u64, + revoked: bool, +} + +impl TrustedUpdateKey { + pub fn new( + public_key: [u8; 32], + platform: Platform, + first_sequence: u64, + last_sequence: u64, + revoked: bool, + ) -> Result { + let key = VerifyingKey::from_bytes(&public_key).context("invalid update public key")?; + ensure!(!key.is_weak(), "weak update public key"); + ensure!( + first_sequence > 0 && last_sequence >= first_sequence, + "invalid key sequence range" + ); + Ok(Self { + key, + key_id: digest(&public_key), + platform, + first_sequence, + last_sequence, + revoked, + }) + } + + pub fn key_id(&self) -> &str { + &self.key_id + } +} + +pub struct UpdateKeyring { + generation: u64, + keys: BTreeMap, +} + +impl UpdateKeyring { + pub fn new(generation: u64, keys: Vec) -> Result { + ensure!( + generation > 0 && !keys.is_empty() && keys.len() <= 16, + "invalid provisioned keyring" + ); + let mut indexed = BTreeMap::new(); + for key in keys { + ensure!(!indexed.contains_key(key.key_id()), "duplicate update key"); + indexed.insert(key.key_id.clone(), key); + } + Ok(Self { + generation, + keys: indexed, + }) + } +} + +#[derive(Clone, Debug)] +pub struct ActiveRelease { + pub sequence: u64, + pub manifest_sha256: String, +} + +/// Must be obtained from authenticated local state and a trusted clock. +/// No boolean `approved`/`ready` is accepted or produced here. Persistence, +/// rollback detection and independent sync remain the caller's responsibility. +pub struct TrustedContext { + pub platform: Platform, + pub now_utc_seconds: u64, + pub keyring_generation: u64, + pub protocol_major: u32, + pub state_schema: u32, + pub updater_version: u32, + pub minimum_release_sequence: u64, + pub active_release: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ReleaseRelation { + AboveActivationFloor, + /// Metadata identity only: neither actual binary health nor a job Noop proof. + SameActiveManifest, +} + +/// Private construction proves only release metadata validity at verification. +/// Holding this value grants NO permission to download, stop, install or start. +pub struct VerifiedRelease { + manifest: ReleaseManifest, + manifest_sha256: String, + key_id: String, + keyring_generation: u64, + relation: ReleaseRelation, +} + +impl VerifiedRelease { + pub fn manifest(&self) -> &ReleaseManifest { + &self.manifest + } + + pub fn manifest_sha256(&self) -> &str { + &self.manifest_sha256 + } + + pub fn key_id(&self) -> &str { + &self.key_id + } + + pub fn keyring_generation(&self) -> u64 { + self.keyring_generation + } + + pub fn relation(&self) -> ReleaseRelation { + self.relation + } + + /// Verify a complete reader with a fixed 32 KiB buffer and no file writes. + /// A caller supplying a socket/pipe must enforce its own timeout and permit. + /// Descriptors come only from this verified release, never caller input. + pub fn verify_artifact(&self, role: ArtifactRole, mut reader: impl Read) -> Result<()> { + let descriptor = match role { + ArtifactRole::Agent => &self.manifest.artifacts[0], + ArtifactRole::Helper => &self.manifest.artifacts[1], + }; + let mut buffer = [0_u8; 32 * 1024]; + let mut remaining = descriptor.bytes; + let mut hasher = Sha256::new(); + while remaining > 0 { + let limit = remaining.min(buffer.len() as u64) as usize; + let size = match reader.read(&mut buffer[..limit]) { + Ok(size) => size, + Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue, + Err(error) => return Err(error).context("release artifact read failed"), + }; + ensure!(size > 0, "release artifact truncated"); + hasher.update(&buffer[..size]); + remaining -= size as u64; + } + loop { + match reader.read(&mut buffer[..1]) { + Ok(0) => break, + Ok(_) => bail!("release artifact has extra bytes"), + Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue, + Err(error) => return Err(error).context("release artifact EOF check failed"), + } + } + ensure!( + hex::encode(hasher.finalize()) == descriptor.sha256, + "release artifact hash mismatch" + ); + Ok(()) + } +} + +pub fn verify_release( + signed: SignedRelease<'_>, + keyring: &UpdateKeyring, + context: &TrustedContext, +) -> Result { + ensure!( + signed.schema_version == 1, + "unsupported release envelope schema" + ); + ensure!( + !signed.payload_bytes.is_empty() && signed.payload_bytes.len() <= MAX_MANIFEST_BYTES, + "release manifest size limit" + ); + ensure!(is_digest(signed.key_id), "invalid update key ID"); + ensure!( + keyring.generation == context.keyring_generation, + "update trust generation mismatch" + ); + let key = keyring + .keys + .get(signed.key_id) + .context("untrusted update key")?; + ensure!( + !key.revoked && key.platform == context.platform, + "update key revoked or wrong platform" + ); + let signature = + Signature::from_slice(signed.signature).context("invalid release signature size")?; + let mut message = + Vec::with_capacity(RELEASE_SIGNATURE_DOMAIN.len() + signed.payload_bytes.len()); + message.extend_from_slice(RELEASE_SIGNATURE_DOMAIN); + message.extend_from_slice(signed.payload_bytes); + key.key + .verify_strict(&message, &signature) + .context("release signature rejected")?; + + let manifest: ReleaseManifest = + serde_json::from_slice(signed.payload_bytes).context("invalid release manifest schema")?; + ensure!( + serde_json::to_vec(&manifest)? == signed.payload_bytes, + "noncanonical release manifest" + ); + validate_manifest(&manifest, context)?; + ensure!( + (key.first_sequence..=key.last_sequence).contains(&manifest.release_sequence), + "release outside update key sequence range" + ); + let manifest_sha256 = digest(signed.payload_bytes); + let relation = match &context.active_release { + Some(active) => { + ensure!( + active.sequence > 0 + && is_digest(&active.manifest_sha256) + && active.sequence <= context.minimum_release_sequence, + "invalid trusted active release state" + ); + if manifest.release_sequence == active.sequence { + ensure!( + manifest_sha256 == active.manifest_sha256, + "release sequence content conflict" + ); + ReleaseRelation::SameActiveManifest + } else { + ensure!( + manifest.release_sequence > context.minimum_release_sequence, + "release is not above activation floor" + ); + ReleaseRelation::AboveActivationFloor + } + } + None => { + ensure!( + manifest.release_sequence > context.minimum_release_sequence, + "release is not above activation floor" + ); + ReleaseRelation::AboveActivationFloor + } + }; + Ok(VerifiedRelease { + manifest, + manifest_sha256, + key_id: signed.key_id.to_owned(), + keyring_generation: keyring.generation, + relation, + }) +} + +fn validate_manifest(manifest: &ReleaseManifest, context: &TrustedContext) -> Result<()> { + ensure!( + manifest.schema_version == 1, + "unsupported release manifest schema" + ); + ensure!( + !manifest.release_id.is_nil() && manifest.release_sequence > 0, + "invalid release identity" + ); + ensure!( + !manifest.version.is_empty() + && manifest.version.len() <= 64 + && manifest + .version + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || b".-+_".contains(&byte)), + "invalid release version label" + ); + ensure!( + manifest.platform == context.platform, + "release platform mismatch" + ); + ensure!( + manifest.published_at <= context.now_utc_seconds + && manifest.expires_at > context.now_utc_seconds + && manifest.expires_at > manifest.published_at, + "release outside trusted validity interval" + ); + ensure!( + context.protocol_major > 0 && manifest.protocol_major == context.protocol_major, + "incompatible release protocol" + ); + ensure!( + context.state_schema > 0 && manifest.state_schema == context.state_schema, + "incompatible release state schema" + ); + ensure!( + manifest.minimum_updater_version > 0 + && manifest.minimum_updater_version <= context.updater_version, + "updater version unsupported" + ); + ensure!( + manifest.release_sequence >= context.minimum_release_sequence, + "release below activation floor" + ); + ensure!( + manifest.artifacts[0].role == ArtifactRole::Agent + && manifest.artifacts[1].role == ArtifactRole::Helper, + "release requires ordered agent and helper artifacts" + ); + ensure!( + manifest.artifacts[0].artifact_id != manifest.artifacts[1].artifact_id, + "duplicate release artifact ID" + ); + for artifact in &manifest.artifacts { + ensure!( + !artifact.artifact_id.is_nil() + && is_digest(&artifact.sha256) + && (1..=MAX_ARTIFACT_BYTES).contains(&artifact.bytes), + "invalid release artifact descriptor" + ); + } + Ok(()) +} + +fn digest(bytes: &[u8]) -> String { + hex::encode(Sha256::digest(bytes)) +} + +fn is_digest(value: &str) -> bool { + value.len() == 64 + && value + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) +} diff --git a/crates/updater/tests/fixtures/release_v1.json b/crates/updater/tests/fixtures/release_v1.json new file mode 100644 index 0000000..052ee18 --- /dev/null +++ b/crates/updater/tests/fixtures/release_v1.json @@ -0,0 +1 @@ +{"schema_version":1,"release_id":"00000000-0000-0000-0000-000000000001","release_sequence":4,"version":"0.2.0","platform":"x86_64-unknown-linux-gnu","published_at":90,"expires_at":110,"protocol_major":1,"state_schema":1,"minimum_updater_version":1,"artifacts":[{"role":"agent","artifact_id":"00000000-0000-0000-0000-000000000002","sha256":"8a24d82ccecfb6de46d0fd3488549b3c6757a4c05aab0a4b15c1b73e47000dbc","bytes":11},{"role":"helper","artifact_id":"00000000-0000-0000-0000-000000000003","sha256":"dd4e40b8a4de19a3b9143d926178927aea04ba0316f44f7fde254ecd51931d22","bytes":12}]} \ No newline at end of file diff --git a/crates/updater/tests/release_contract.rs b/crates/updater/tests/release_contract.rs new file mode 100644 index 0000000..97356ce --- /dev/null +++ b/crates/updater/tests/release_contract.rs @@ -0,0 +1,317 @@ +use std::io::{self, Cursor, Read}; + +use ed25519_dalek::{Signer, SigningKey}; +use rmm_updater::*; +use sha2::{Digest, Sha256}; +use uuid::Uuid; + +fn hash(bytes: &[u8]) -> String { + hex::encode(Sha256::digest(bytes)) +} + +fn key(revoked: bool, first: u64, last: u64) -> TrustedUpdateKey { + TrustedUpdateKey::new( + SigningKey::from_bytes(&[41; 32]).verifying_key().to_bytes(), + Platform::LinuxX64, + first, + last, + revoked, + ) + .unwrap() +} + +fn context() -> TrustedContext { + TrustedContext { + platform: Platform::LinuxX64, + now_utc_seconds: 100, + keyring_generation: 7, + protocol_major: 1, + state_schema: 1, + updater_version: 1, + minimum_release_sequence: 3, + active_release: Some(ActiveRelease { + sequence: 3, + manifest_sha256: hash(b"previous immutable manifest"), + }), + } +} + +fn manifest() -> ReleaseManifest { + ReleaseManifest { + schema_version: 1, + release_id: Uuid::from_u128(1), + release_sequence: 4, + version: "0.2.0".into(), + platform: Platform::LinuxX64, + published_at: 90, + expires_at: 110, + protocol_major: 1, + state_schema: 1, + minimum_updater_version: 1, + artifacts: [ + ArtifactDescriptor { + role: ArtifactRole::Agent, + artifact_id: Uuid::from_u128(2), + sha256: hash(b"agent image"), + bytes: 11, + }, + ArtifactDescriptor { + role: ArtifactRole::Helper, + artifact_id: Uuid::from_u128(3), + sha256: hash(b"helper image"), + bytes: 12, + }, + ], + } +} + +fn verify_bytes(payload: &[u8], context: &TrustedContext) -> anyhow::Result { + let signer = SigningKey::from_bytes(&[41; 32]); + let mut message = RELEASE_SIGNATURE_DOMAIN.to_vec(); + message.extend_from_slice(payload); + let signature = signer.sign(&message).to_bytes(); + let pinned = key(false, 1, 20); + let key_id = pinned.key_id().to_owned(); + verify_release( + SignedRelease { + schema_version: 1, + key_id: &key_id, + payload_bytes: payload, + signature: &signature, + }, + &UpdateKeyring::new(7, vec![pinned]).unwrap(), + context, + ) +} + +fn verify(manifest: &ReleaseManifest, context: &TrustedContext) -> anyhow::Result { + verify_bytes(&serde_json::to_vec(manifest).unwrap(), context) +} + +#[test] +fn canonical_release_and_exact_role_bytes_are_metadata_only() { + let payload = serde_json::to_vec(&manifest()).unwrap(); + assert_eq!(payload, include_bytes!("fixtures/release_v1.json")); + let checked = verify_bytes(&payload, &context()).unwrap(); + assert_eq!(checked.manifest_sha256(), hash(&payload)); + assert_eq!(checked.keyring_generation(), 7); + assert_eq!(checked.key_id(), key(false, 1, 20).key_id()); + assert_eq!(checked.manifest().release_sequence, 4); + assert_eq!(checked.relation(), ReleaseRelation::AboveActivationFloor); + checked + .verify_artifact(ArtifactRole::Agent, Cursor::new(b"agent image")) + .unwrap(); + checked + .verify_artifact(ArtifactRole::Helper, Cursor::new(b"helper image")) + .unwrap(); + assert!( + checked + .verify_artifact(ArtifactRole::Agent, Cursor::new(b"helper image")) + .is_err() + ); +} + +#[test] +fn signature_domain_bytes_unknown_key_and_revocation_are_independent() { + let payload = serde_json::to_vec(&manifest()).unwrap(); + let signer = SigningKey::from_bytes(&[41; 32]); + let mut message = RELEASE_SIGNATURE_DOMAIN.to_vec(); + message.extend_from_slice(&payload); + let signature = signer.sign(&message).to_bytes(); + let pinned = key(false, 1, 20); + let key_id = pinned.key_id().to_owned(); + let run = |bytes: &[u8], signature: &[u8], id: &str, revoked, first, last| { + verify_release( + SignedRelease { + schema_version: 1, + key_id: id, + payload_bytes: bytes, + signature, + }, + &UpdateKeyring::new(7, vec![key(revoked, first, last)]).unwrap(), + &context(), + ) + }; + assert!(run(&payload, &signature, &key_id, false, 1, 20).is_ok()); + let mut changed = payload.clone(); + changed[0] = b'['; + assert!(run(&changed, &signature, &key_id, false, 1, 20).is_err()); + assert!( + run( + &payload, + &signer.sign(&payload).to_bytes(), + &key_id, + false, + 1, + 20 + ) + .is_err() + ); + let foreign = SigningKey::from_bytes(&[42; 32]).sign(&message).to_bytes(); + assert!(run(&payload, &foreign, &key_id, false, 1, 20).is_err()); + assert!(run(&payload, &signature[..63], &key_id, false, 1, 20).is_err()); + assert!(run(&payload, &signature, &hash(b"job key"), false, 1, 20).is_err()); + assert!(run(&payload, &signature, &key_id, true, 1, 20).is_err()); + assert!(run(&payload, &signature, &key_id, false, 5, 20).is_err()); + assert!(run(&payload, &signature, &key_id, false, 1, 3).is_err()); +} + +#[test] +fn signed_noncanonical_unknown_duplicate_and_oversize_payloads_are_rejected() { + let payload = String::from_utf8(serde_json::to_vec(&manifest()).unwrap()).unwrap(); + for changed in [ + format!(" {payload}"), + payload.replacen(":1,", ": 1,", 1), + payload.replacen("{", "{\"untrusted\":true,", 1), + payload.replacen("{", "{\"schema_version\":1,", 1), + payload.replacen("\"bytes\":11", "\"bytes\":11,\"path\":\"/etc/passwd\"", 1), + payload.replacen("\"release_sequence\":4", "\"release_sequence\":4.0", 1), + payload.replacen("x86_64-unknown-linux-gnu", "aarch64-unknown-linux-gnu", 1), + ] { + assert!(verify_bytes(changed.as_bytes(), &context()).is_err()); + } + assert!(verify_bytes(&vec![b' '; MAX_MANIFEST_BYTES + 1], &context()).is_err()); + assert!(verify_bytes(b"", &context()).is_err()); +} + +#[test] +fn incompatible_clock_platform_state_protocol_and_trust_contexts_are_rejected() { + let mut ctx = context(); + ctx.keyring_generation = 6; + assert!(verify(&manifest(), &ctx).is_err()); + ctx = context(); + ctx.platform = Platform::WindowsX64; + assert!(verify(&manifest(), &ctx).is_err()); + for now in [89, 110, 111] { + ctx = context(); + ctx.now_utc_seconds = now; + assert!(verify(&manifest(), &ctx).is_err()); + } + let changes: [fn(&mut ReleaseManifest); 7] = [ + |m| m.schema_version = 2, + |m| m.platform = Platform::WindowsX64, + |m| m.protocol_major = 2, + |m| m.state_schema = 2, + |m| m.minimum_updater_version = 2, + |m| m.minimum_updater_version = 0, + |m| m.published_at = m.expires_at, + ]; + for change in changes { + let mut m = manifest(); + change(&mut m); + assert!(verify(&m, &context()).is_err()); + } +} + +#[test] +fn monotone_floor_same_sequence_conflict_and_postrollback_state_are_preserved() { + let mut ctx = context(); + let mut m = manifest(); + m.release_sequence = 2; + assert!(verify(&m, &ctx).is_err()); + m.release_sequence = 3; + assert!(verify(&m, &ctx).is_err()); + ctx.active_release.as_mut().unwrap().manifest_sha256 = hash(&serde_json::to_vec(&m).unwrap()); + assert_eq!( + verify(&m, &ctx).unwrap().relation(), + ReleaseRelation::SameActiveManifest + ); + m.version = "modified same sequence".into(); + assert!(verify(&m, &ctx).is_err()); + // A code rollback never lowers the remembered successfully activated floor. + ctx.minimum_release_sequence = 5; + assert!(verify(&manifest(), &ctx).is_err()); + ctx = context(); + ctx.minimum_release_sequence = 2; + assert!(verify(&manifest(), &ctx).is_err()); + ctx.active_release = None; + ctx.minimum_release_sequence = 4; + assert!(verify(&manifest(), &ctx).is_err()); +} + +#[test] +fn descriptor_roles_ids_bounds_and_digest_encoding_are_strict() { + let changes: [fn(&mut ReleaseManifest); 10] = [ + |m| m.release_id = Uuid::nil(), + |m| m.release_sequence = 0, + |m| m.version.clear(), + |m| m.version = "https://attacker.invalid/latest".into(), + |m| m.artifacts[0].artifact_id = Uuid::nil(), + |m| m.artifacts[1].artifact_id = m.artifacts[0].artifact_id, + |m| m.artifacts.swap(0, 1), + |m| m.artifacts[0].bytes = 0, + |m| m.artifacts[0].bytes = MAX_ARTIFACT_BYTES + 1, + |m| m.artifacts[0].sha256 = m.artifacts[0].sha256.to_uppercase(), + ]; + for change in changes { + let mut m = manifest(); + change(&mut m); + assert!(verify(&m, &context()).is_err()); + } +} + +#[test] +fn artifact_eof_extra_bytes_hash_and_io_errors_never_verify() { + let checked = verify(&manifest(), &context()).unwrap(); + for bytes in [b"agent imag".as_slice(), b"agent image!", b"agent imagX"] { + assert!( + checked + .verify_artifact(ArtifactRole::Agent, Cursor::new(bytes)) + .is_err() + ); + } + struct FailingReader; + impl Read for FailingReader { + fn read(&mut self, _: &mut [u8]) -> io::Result { + Err(io::Error::new(io::ErrorKind::PermissionDenied, "fixture")) + } + } + assert!( + checked + .verify_artifact(ArtifactRole::Agent, FailingReader) + .is_err() + ); +} + +#[test] +fn streamed_large_release_verifies_with_fixed_read_window() { + struct BoundedReader { + remaining: u64, + largest_read: usize, + } + impl Read for BoundedReader { + fn read(&mut self, output: &mut [u8]) -> io::Result { + self.largest_read = self.largest_read.max(output.len()); + assert!(output.len() <= 32 * 1024); + let size = self.remaining.min(output.len() as u64) as usize; + output[..size].fill(19); + self.remaining -= size as u64; + Ok(size) + } + } + let bytes = vec![19; 512 * 1024 + 7]; + let mut m = manifest(); + m.artifacts[0].bytes = bytes.len() as u64; + m.artifacts[0].sha256 = hash(&bytes); + let checked = verify(&m, &context()).unwrap(); + let mut reader = BoundedReader { + remaining: bytes.len() as u64, + largest_read: 0, + }; + checked + .verify_artifact(ArtifactRole::Agent, &mut reader) + .unwrap(); + assert_eq!(reader.remaining, 0); + assert_eq!(reader.largest_read, 32 * 1024); +} + +#[test] +fn keyring_rejects_weak_keys_duplicates_empty_sets_and_invalid_ranges() { + assert!(TrustedUpdateKey::new([0; 32], Platform::LinuxX64, 1, 10, false).is_err()); + let public = SigningKey::from_bytes(&[41; 32]).verifying_key().to_bytes(); + assert!(TrustedUpdateKey::new(public, Platform::LinuxX64, 0, 10, false).is_err()); + assert!(TrustedUpdateKey::new(public, Platform::LinuxX64, 10, 9, false).is_err()); + assert!(UpdateKeyring::new(0, vec![key(false, 1, 20)]).is_err()); + assert!(UpdateKeyring::new(1, vec![]).is_err()); + assert!(UpdateKeyring::new(1, vec![key(false, 1, 20), key(false, 1, 20)]).is_err()); +} diff --git a/docs/agent-updater-proposal.md b/docs/agent-updater-proposal.md new file mode 100644 index 0000000..116d659 --- /dev/null +++ b/docs/agent-updater-proposal.md @@ -0,0 +1,442 @@ +# Agent-Selbstupdate: kleinster zusätzlicher Schnitt + +Stand 2026-11-14, **Integrationsvorschlag mit implementiertem reinem Prüfkern**, +keine neue Produktnorm und kein Installations-/VM-Nachweis. Basis: +Spezifikation1.19, Kapitel0,4,13,16,19,22,25. +Der User möchte den Agent-Autoupdater jetzt parallel zur Skriptkonsole. Damit +wird ausschließlich dieser Teil aus M7 vorgezogen; Restore, HA, Relay und Lasttest +werden dadurch keine zusätzlichen MVP-Aufgaben. APT-/MSI-Fixturerezepte verwalten +andere Software und implementieren **keinen Agent-Selbstupdater**. + +## Verhalten und Genehmigung + +Der installierte Agent prüft regelmäßig, ob ein passendes, freigegebenes Release +vorliegt. Der erste Vorschlag ist ein täglicher passiver Metadatencheck mit +Jitter, zusätzlich beim Prozessstart, über den bereits konfigurierten Server. +Dies sammelt ausschließlich feste Release-Metadaten und startet keinen Job, +Installer, Download beliebiger URLs oder Codewechsel. Fehlende Konfiguration +meldet `not_configured`, abgelaufene Metadaten `unknown` samt Zeitpunkt/Fehler. + +Ein Update erhält eine eigene typisierte Aktion `update_agent`. UI/MCP dürfen +einen festen Plan vorbereiten und als `pending_approval` beantragen. Der Plan +bindet pro Gerät Release-Manifesthash, Artefakte, exakten Vorgänger, Plattform, +Versuch, Frist, Parallelitätsgrenze und erlaubte einmalige Wiederherstellung. +WebUI-Genehmigung, aktuelle Startprüfung und dauerhafter Einmalverbrauch bleiben +erforderlich. Ein Mensch kann einen festen Rollout gemeinsam genehmigen; +`latest`, zukünftige Versionen, Wildcardziele und periodische Selbstfreigabe +sind keine zulässigen ausführbaren Parameter. `updates:apply` wird zusätzlich +zu den jeweiligen Root-/SYSTEM-Rechten geprüft; eine Policy begrenzt nur. + +Der UI-Text muss Agent-/Helper-Dienstunterbrechung und mögliche Management- +Unterbrechung anzeigen. Dieser Schnitt fordert keinen Hostreboot an und darf +keinen Installer wählen, der ungeplant neu startet. Notwendiger Hostreboot +verlangt einen eigenen festen genehmigten Job. Automatischer Versionscheck, +freigegebener Rollout und bestätigter Updateerfolg bleiben getrennte Zustände. + +## Festes Releaseformat1 + +Ein Release besteht zunächst aus genau zwei Rohdateien: Agent und privilegierter +Helper. Kein Archiv, Postinstall-Skript, freier Pfad oder beliebiges Kommando. +Linux verwendet `x86_64-unknown-linux-gnu`, Windows +`x86_64-pc-windows-msvc`. Die Plattformkennung ist eine geschlossene Auswahl. +Ein neuer Updater selbst ist **nicht** Teil dieses ersten Selbstupdatepfads. +APT-/MSI-Pakete können später denselben signierten Vertrag umschließen; der +erste Rohbinaryschnitt darf nicht als APT-/MSI-Upgrade beworben werden. + +Das Envelope enthält `schema_version=1`, `key_id`, `payload_bytes` und +`signature` (feste Ed25519-Signatur,64Bytes). Für JSON-Transport werden +`payload_bytes` und `signature` als kanonisches Base64url ohne Padding übertragen, +keine unbeschränkten Zahlenarrays. Der erste Bibliothekskern nimmt bereits +dekodierte begrenzte Bytes entgegen; die spätere Transportintegration muss das +Envelope vor Decodierung begrenzen. Der Payload ist streng typisiertes +JSON mit festen Feld-/Listenreihenfolgen, ohne unbekannte Felder, doppelte Keys, +Floats oder alternative Encodingform. Nach Parsen muss exakt dieselbe kanonische +Serialisierung entstehen. Signaturbytes sind die Domäne +`rmm.agent-release.v1\0` gefolgt von den unveränderten Payloadbytes. Der +Manifesthash ist SHA256 derselben Payloadbytes. Verifikation begrenzt das +Payload vor Parsen auf16KiB und verwendet `verify_strict` aus dem schon gepinnten +`ed25519-dalek=2.2.0`; keine Algorithmusverhandlung. + +| Payloadfeld | Festgelegte Bedeutung | +|---|---| +| `schema_version` | Genau1 | +| `release_id` | UUID; unveränderlicher veröffentlichter Datensatz | +| `release_sequence` | Positive monotone Veröffentlichungsnummer je Plattform; Versionsvergleich nutzt diese Nummer | +| `version` | Sichtbare nichtleere ASCII-Versionskennung; kein lexikografischer Semververgleich | +| `platform` | Eine der beiden festen x64-Plattformkennungen | +| `published_at`, `expires_at` | UTC-Epochsekunden, gültig nur mit vertrauenswürdigem Clockkontext | +| `protocol_major` | Exakte unterstützte Hauptversion; die erste Stufe erlaubt nur dieselbe aktuelle Version | +| `state_schema` | Exakte kompatible Zustandsversion; erste Stufe erlaubt **keine** Zustandsmigration | +| `minimum_updater_version` | Positive numerische Implementierungsversion des unabhängigen Updaters | +| `artifacts` | Genau Agent, danach Helper; je `role`, unveränderliche `artifact_id`, SHA256 und Länge | + +Artefakthashes sind64kleine Hexzeichen; Längen positiv und höchstens256MiB pro +Datei. Artefakt-UUIDs dürfen nicht doppelt sein. Rollen sind `agent` und `helper`, +keine eigenen Dateinamen aus dem Netzwerk. Die Veröffentlichung ist erst +verfügbar, wenn beide vollständigen Dateien existieren und deren Hash/Länge +mit dem signierten Manifest übereinstimmen. Serverkatalog und Tenantberechtigung +bestimmen Sichtbarkeit; das Manifest selbst verleiht keinerlei Ausführungsrecht. + +## Vertrauen, Ablauf und Versionsschutz + +Update-, Job-/Grant- und Geräte-/TLS-Schlüssel sind getrennt. Lokaler Bootstrap +provisioniert einen root-/SYSTEM-geschützten Update-Keyring mit SHA256-Key-ID, +rohem32Byte-Publickey, Plattformbindung und zulässigem Sequenzbereich. Kein +Schlüssel aus einem Job, Manifest oder Download wird automatisch vertrauenswürdig. +Veraltete/gesperrte Keys verweigern auch eine ansonsten passende Signatur. + +Erste kleine Stufe unterstützt Rotation/Widerruf durch kontrollierte, separat +provisionierte Keyringgeneration; neue Generation muss größer sein, alte +Schlüssel werden nicht implizit übernommen. Dynamisches Online-Rootrotation- +Protokoll ist noch offen und wird nicht als TUF-Implementierung ausgegeben. +Dies hat eine konkrete Grenze: Ein lange isolierter Client kennt einen späteren +Widerruf erst bei frischer authentisierter Trustprovisionierung. Daher beginnt +ohne frischen Kontakt und aktuellen Trustkontext kein Apply. + +Lokal gibt es getrennt (a) die aktuell aktive Manifest-ID/Sequenz, (b) die höchste +erfolgreich aktivierte Sequenz als Antirollbackgrenze, (c) den höchsten gesehenen +Katalogstand für Replaydiagnose und (d) einen offenen Übergabeintent. Bloßes +Ansehen eines neuen Releases autorisiert keine Wirkung. Ein älteres Release +unter der bestätigten Antirollbackgrenze ist niemals ein neues Updateziel. +Gleiche Sequenz mit anderen Manifestbytes ist ein Konflikt; dieselben Bytes sind +ein Metadatenduplikat, keine neue Wirkung. Versionslabels allein reichen nicht. + +`verify_release` prüft ausschließlich **zukünftige Updatekandidaten**. Nach +einem Code-Rollback (`active=3`, bestätigter Floor=5) verweigert diese Funktion +auch das aktive Manifest3 als erneutes Updateziel. Das bedeutet keine Korruption +oder Ungesundheit der aktuell laufenden Version. Passive Anzeige und Health +verwenden den gesonderten geschützten `InstalledReleaseRecord` mit explizitem +Rollbackstatus; sie dürfen diese Kandidatenprüfung nicht als Current-Healthcheck +verwenden. `SameActiveManifest` ist nur oberhalb/auf dem unveränderten Floor +erreichbar und bleibt ausschließlich ein Metadatenvergleich. + +Die einzige Rückkehr zu einer niedrigeren aktiven Sequenz ist die im selben +genehmigten Versuch vorab gebundene letzte bekannte Codeversion, deren Dateien +noch unverändert lokal vorhanden sind. Die Antirollbackgrenze wird dabei nicht +gesenkt. Widerrufene/ausdrücklich verbotene Vorgänger werden auch als Rollback +verweigert. Ein späteres Downgrade verlangt einen getrennten Recoveryvertrag. + +## Servertransport und UI/MCP-Vertrag + +Vorgeschlagener zusätzlicher lesender Endpunkt: +`GET /agent/v1/releases/current?platform=`, über vorhandenes +Geräte-mTLS, ohne Redirects, höchstens32KiB Envelope, Serverzeit und Katalog- +beobachtungszeit getrennt. Antwort enthält einen signierten festen Manifestenvelope +oder explizites `not_configured`/keine angebotene Version. Kein neuer öffentlicher +Login oder allgemein adressierbarer Installerdownload. Ein veraltetes aber noch +gültiges Manifest ist durch reine TLS-/Hashprüfung allein nicht als aktuellste +Version beweisbar; der Check meldet nur die tatsächlich beobachtete Version. + +Der vorhandene geräte-/Job-/Versuch-gebundene +`/agent/v1/artifacts/{artifact_id}`-Pfad kann derzeit nur Artefakte bis256KiB +beziehen: `LocalArtifacts::put/get` **und** das SQL-`CHECK` in +`migrations/0006_catalog.sql` begrenzen sie entsprechend. Sein512KiB- +Chunklimit erweitert weder Store noch SQL und lädt heute das ganze Objekt in +einen `Vec`. +**Damit kann er Agentbinaries nicht transportieren.** Die bis256MiB großen +Deskriptoren des neuen reinen Prüfkerns sind für eine noch offene, ausdrücklich +Update-spezifische begrenzte Streaming-Erweiterung vorgesehen. Weder Import, +Downloadroute noch Serverlimit werden in diesem Schnitt verändert. Spätere +Integration muss dieselben Geräte-/Job-/Versuchs- und exakten Manifestbindungen +auch für große Streams durchgehend erhalten. Kein vom LLM gelieferter +Downloadhost, TCP-Override, Dateipfad oder TLS-Ausnahmeschalter. +Der zukünftige Download wird gestreamt und vor Verwendung gegen +Länge/SHA256 geprüft; Zusatzbytes und vorzeitiges EOF verweigern. Nach Reconnect +stammt neue Startautorität immer aus dem normalen Plan-/Grantpfad. + +`operations.plan(action=update_agent)` erhält nur die gespeicherte Release-ID +und feste Ziele; Server löst unveränderliche Bytes aus dem berechtigten Katalog +auf und bindet tatsächlichen gespeicherten Vorgänger sowie beide Artefakte. +`operations.submit` bleibt Antrag; `jobs.get` zeigt Staging, Übergabe, +Dienstprüfung, erhaltene Identität, Rollback und tatsächlichen Ausgang. Vor +Genehmigung zeigt WebUI alle Hashes, Versionen, Rechte und Ausfall-/Rollbackgrenzen. +Neue Datenverträge sind mit dem Skriptkonsolen-Eigentümer abzustimmen; dieser +Vorschlag ändert noch keine Domain-/Protokoll-/Server-/Webdatei. + +## Unabhängiger Worker und erhaltende Übergabe + +Der Netzwerkagent bleibt unprivilegiert. Ein kleiner separat installierter +Updater wird unter Root/SYSTEM mit restriktiver IPC/Peerprüfung angesteuert. +Er prüft selbst Releasekey, Manifest, exakten Originaljob/-grant, aktuelle +Identitäts-/Zuordnungs-/Boot-/Clock-/Syncbindung und lokalen Policykontext. +Die schon vorhandenen Helperprüfungen dürfen nicht durch bloßes `approved=true` +oder einen Dateimarker ersetzt werden. Sein eigener Journal-/Verbrauchsbezug +muss vor Start serverseitig bekannt und unabhängig synchronisiert sein. + +Der Updater startet nicht aus der gerade zu ersetzenden Agent-/Helperdatei und +überlebt deren Stop. Geräteweite Locks serialisieren Paketmanager, Updates, +Root-/SYSTEM-Skriptwartung und Reboots. Offene oder unbekannte Versuche sperren +die erste Updateversion; keine Aktualisierung mitten in einer Wirkung. + +1. Exakten Vorgänger, Trust-/Policy-/Serviceidentitäten, freie Kapazität und + Zustandskompatibilität prüfen. Geschützte Stagingdateien create-only auf + demselben Dateisystem; Files und Verzeichniseinträge dauerhaft flushen. +2. Manifest und beide Dateien unabhängig prüfen; keine Wirkung vor Genehmigung. + Ein Downloadfehler vor Übergabe bleibt belegter Nichtstart der Aktivierung. +3. Vor Stop/Swap dauerhaften Intent mit Originaljob/Versuch/Grant und allen + Vorherzeugen schreiben, Grant/Versuch einmalig verbrauchen. Nach unklarem + Ausgang ausschließlich Zustand desselben Intents lesen, nie Execute wiederholen. +4. Dienste geordnet einmal stoppen; aktive handles/Locks und SQLiteintegrität + prüfen. Identitäten, Geräteschlüssel, Zertifikats-/Rotationstore, Konfiguration, + ACLs, DBinodes/FileIDs, Originaltabellen/-zeilen, Journale/Signaturen und offene + Outbox bleiben erhalten. Private Schlüsselbytes werden nicht exportiert. +5. Für den ersten Aktivierungsschnitt empfehle ich **bestehende feste + Service-Imagepfade erhalten**. Der unabhängige Updater stoppt und bestätigt + beide Dienste, tauscht alle gebundenen Code-/Pin-Dateien unter den Locks, + prüft vollständig die neue Kombination und startet erst dann einen Dienst. + So läuft kein altes/neues Paar gleichzeitig, obwohl die Dateiersetzungen + **kein atomarer Dateisystem-Bundleswap** sind. Der dauerhafte Intent benennt + jede bereits erfolgte Ersetzung; ein Absturz lässt beide Dienste bis zum + eindeutig belegten Abschluss oder Code-Rollback gesperrt. Vorhandene Runner + zeigen dieses Wartungsfenster bereits, sind aber noch kein Selfupdater. + Ein neuer Launcher würde Service-PID-/Image-/Peerprüfungen verändern und ist + für diesen ersten Schnitt unnötig. Ein einzelner atomarer Versionsselector + bleibt eine spätere Alternative mit eigener vollständiger Qualifikation. +6. Neue Dienste einmal starten; actual Imagehash/Identität, passive Heartbeats, + bestätigtes Inventar und erfolgreiches signiertes Sync mit geschlossenen + Effectgates bis zum vollständigen Abgleich nachweisen. `Running` allein reicht + nicht. Erst dann aktives Release/Antirollbackgrenze dauerhaft bestätigen. +7. Bekannter Fehlstart darf genau die vorab gebundene Codeversion einmal + zurückselektieren und starten; derselbe aktuelle Datenzustand bleibt liegen. + Keine DB-/Ledger-/Generation-/Clock-/ACLrücksetzung. Fehlender/unklarer + Rückkehrnachweis bleibt `unknown`, keine Schleife automatischer Startversuche. + +Vorhandene SSH-Bootstraprunner (`vm_runtime_upgrade.py`, +`cloud_shared_core_upgrade_v2.py`, `windows/runtime_feature_upgrade.py`) zeigen +nützliche erhaltene DB-/Inode-/FileID-/Schlüsselmetadatenprüfungen und dauerhafte +einmalige Intents. Sie sind administrative Einzeltools, keine ausgelieferten +Selfupdater und keine Ersatzgenehmigung dieses Produktpfads. Frühere fehlerhafte +Verifierberichte bleiben historisch; neue Abnahme muss konkrete aktuelle Daten +binden, einschließlich vorhandener zulässiger Hardlinkpublikationen. + +## Kleinster prüfbarer Quellschnitt und danach offene Arbeit + +Nach Entwurfsreview implementiert: neue kleine `crates/updater`-Bibliothek, +keine Daemonhülle. Dateien `Cargo.toml`, `src/lib.rs`, `src/manifest.rs` und +neun gezielte Vertragsprüfungen mit vollständiger kanonischer Goldenfixture. +Root-`Cargo.toml`/`Cargo.lock` nur für Workspacebindung; keine neuen fremden +Paketversionen. Alle benutzten Abhängigkeiten waren bereits im Lockfile. +Implementierte Funktion: bounded canonical manifest decode, strikte Ed25519-Verifikation gegen +getrennten übergebenen Keyring, Plattform-/Clock-/Kompatibilitäts-/Versionsprüfung +und begrenzte Streaming-Hash-/Längenprüfung von Artefakten. Keine Aktivierung, +kein Netzwerk, keine generische OS-Dateischreib-API. Ein validiertes Objekt +beweist nur gültige Releasebytes; dessen API darf weder Approval noch Startgrant +behaupten oder aus dessen Besitz ein Applyrecht ableiten. + +Der Kern wurde mit echten lokalen Signaturen und manipulierten/alten/falschen +Releasebytes geprüft, ohne einen Agenten auf dem Notebook zu starten. +Danach bleiben explizit offen: Serverkatalog/Veröffentlichung und echter +Releasekeybetrieb, täglicher Agentcheck und gespeicherte Updatebeobachtung, +typisierte Plan-/Grant-/UI-/MCP-Bindung, getrennte Updater-Verbrauchssynchronisation, +geschütztes OS-Staging, unabhängiger Updaterbootstrap, mehrstufiger Dateiaustausch, +Health-/Rollbackpfad, echte Linux-VM-Abnahme zuerst und Windows-VM-Abnahme danach. +Ein Bibliotheksbuild ist weder Autoupdaterinstallation noch AT-26-/MVP-Erfolg. + +Tatsächlich ausgeführt: vollständige Pflichtnormen gelesen und vorhandene +Upgrade-/Kryptoverträge untersucht; eigener isolierter Worktree ab287a784. +Der vorhandene Dockerbuilder mit Rust1.99.1 wurde offline, ohne Netzwerk und +mit nur lesbarem Quellmount verwendet, eigener Targetausgabe. Image-ID: +`sha256:9a76ad3744ebfdddae96ca10001ce8291c1b332fb54c8df5eea0e8e999ac6fc6`. +Alle folgenden Prüfungen bestanden für `x86_64-unknown-linux-gnu`: + +```text +cargo fmt --manifest-path /src/Cargo.toml -p rmm-updater -- --check +cargo clippy --manifest-path /src/Cargo.toml --locked --offline --target x86_64-unknown-linux-gnu -p rmm-updater --all-targets -- -D warnings +cargo test --manifest-path /src/Cargo.toml --locked --offline --target x86_64-unknown-linux-gnu -p rmm-updater --all-targets --release +``` + +Neun ausgeführte Vertragsprüfungen bestanden ohne Skip. Sie prüfen feste +kanonische Bytes, echte domänengetrennte Ed25519-Signaturen, falschen/gesperrten +Key und dessen Sequenzbereich, unbekannte/doppelte Felder,16KiB-Grenze, +Plattform/Clock/Trustgeneration/Protokoll/Zustand/Updaterkompatibilität, +Versionsfloor und gleichen Sequenzkonflikt, exakt zwei Artefaktrollen, +Hash-/EOF-/IOfehler sowie512KiB+7Bytes mit tatsächlichem32KiB-Readlimit. +Der verwendete private Testsignierschlüssel ist ausschließlich eine feste +öffentliche Testfixture und wird nie als Vertrauensanker ausgeliefert. + +Lokaler Beleg (gitignored): `devstate/agent-updater/local-qualification.json` +bindet Quellen, Image-ID, tatsächliche Befehle/Loghashes und alle neun Testnamen. +Die Linux-Release-Testexe ist1544584Bytes groß, SHA256 +`e3a1a3140da09de2f86055faa45faf7ba05ddddc2d92d23fef3df03a63bf2999`. +Das ist ein lokaler Container-/Vertragsnachweis, **kein Cloud-VM-Nachweis**. +Native Linux-Test-VM vor Windows, Serverintegration und tatsächlicher +genehmigter Codewechsel bleiben offen. Kein Installer-/VM-Aufruf, keine +Dienständerung, keine Freigabe und kein RMM-Job durch diesen Quellschnitt. + +## Nächster Integrationsschnitt zur Freigabe: fester Codepaar-Updatejob + +Die folgende Änderungsliste ist **nur Entwurf, nicht implementiert**. Sie +ersetzt keine Sourcefreigabe, Bootstrapabstimmung oder native Abnahme. Mit dem +Skriptkonsolen-Eigentümer abgestimmt: `update_agent`, `agent.update.apply/1` +und `updates:apply` kollidieren nicht mit `full_maintenance_v1`. Dessen separater +Helperpfad und das allgemeine/APT-Profil bleiben getrennt; alle benutzen dieselbe +geräteweite Wirkungssperre und erhaltene Verbrauchshistorie. + +### 1. Unveränderliche Action und Planbindung + +Vorgeschlagene additive `Action::UpdateAgent { update: ResolvedAgentUpdate }`, +eigener Modulvertrag `crates/domain/src/agent_update.rs`. Kein Aufruf von +`run_script`, APT oder MSI. Alte Action-/Job-/Plan-/Grantbytes bleiben exakt +erhalten. `JobPayload` behält seine bestehenden IDs, Identitätsgenerationen, +Zeitgrenzen und Limits; `ExecutionPermit.action` lautet `update_agent` und +bindet wie bisher den gesamten `job_payload_hash`. Vor Genehmigung erzeugt +der Server die vollständigen Bytes je festem Ziel/Versuch. + +`ResolvedAgentUpdate` hat in dieser festen kanonischen Feldreihenfolge: + +| Feld | Typ und Bindung | +|---|---| +| `schema_version` | Genau1 | +| `profile` | Genau `fixed_code_pair_v1` | +| `release_envelope` | Schema1, Update-Key-ID, Payload/Signatur als Base64url ohne Padding; keine freien URLs | +| `release_envelope_sha256` | SHA256 des kanonischen vollständigen Envelopes, einschließlich Signatur/Key-ID | +| `manifest_sha256` | SHA256 der dekodierten exakten Release-Payloadbytes | +| `predecessor` | Feste Release-ID, Sequenz, Manifesthash, `installed_record_sha256`, Agent-/Helperhash | +| `updater` | Exakter installierter Updaterbinaryhash, lokale Policyhash, Keyringgeneration und Keyringhash | +| `peer_pin_transition` | Typisierte Plattformvariante, feste Vorher-/Nachher-Settings-/Pinhashes; siehe unten | +| `recovery` | Genau `restore_exact_predecessor_once` | +| `health_profile` | Genau `mtls_inventory_sync_v1` | +| `health_timeout_seconds` | Genau180 im ersten Schnitt; gesamter Job maximal600Sekunden | +| `no_reboot` | Genau `true` | + +Die beiden Artefakte und ihre Reihenfolge kommen ausschließlich aus dem signierten +Manifest. `artifact_ids` als zusätzliche Requestparameter sind für diese Action +verboten. Der Plan enthält je Job/Versuch genau die beiden daraus abgeleiteten +`JobArtifactReference`s; generisches Nachladen weiterer Dateien ist verweigert. +Weil die bisherigen Resolver kleine `artifacts` voraussetzen, erhält ausschließlich +`update_agent` einen eigenen Resolver gegen den Updatekatalog. Alte Resolver und +ihre Grenzen bleiben bestehen. Fehlende/doppelte/fremde Referenzen, geänderter +Vorgänger oder ein von der Plattform abweichendes Release sperren bereits Planung +und nochmals Submit, WebUI-Genehmigung, Revalidation, Startgrant und Download. +Der vollständige Job muss weiter in die vorhandene64KiB-Helpergrenze passen. + +Erste Einrichtung importiert die tatsächlich installierte bekannte Codepaar- +Baseline als separat release-signierten Datensatz mit eigener Sequenz, prüft +ihre Dateien und provisioniert daraus `InstalledReleaseRecord` und Floor. +Dadurch besitzt auch das erste Update einen exakten bekannten Vorgänger; kein +`unknown`, frei vom Agenten behaupteter Hash oder ungeprüftes Legacy-Downgrade. +Dies ist Teil des gesonderten erhaltenden Updaterbootstraps, kein Codeupdate. + +Windows benötigt einen festen Pure-Renderer: ausschließlich +`Settings.agent.binary_sha256` und `Settings.helper.binary_sha256` werden aus +den Zielartefakten ersetzt; alle Rechte, Dienste, Identitäten, Pfade, Runtime- +und Clockflags bleiben gleich. Der daraus kanonisch abgeleitete Settingshash +und öffentliche `Pin`-Hash stehen **vor Genehmigung** fest. Grundlage ist ein +typisierter aktueller öffentlicher Deploymentbeleg des bestehenden Helpers, +keine Secretdatei. Der lokale Updater prüft vor/nach unabhängig, dass exakt diese +beiden Felder geändert werden. Der Server darf nur die exakt genehmigte neue +Code-/Policybindung aktivieren; dadurch entstehen keine neuen Aktionsrechte. +Linux verwendet bei unverändert codeunabhängigen Generalpins die Variante +`unchanged_general_pin_v1`. APT-Akzeptanzbelege werden nicht neu signiert oder +als für neue Codebytes gültig ausgegeben; gegebenenfalls bleibt APT geschlossen. +Nicht unterstützte weitere Pinprofile sperren dieses erste Update, statt sie +automatisch mitzunehmen oder neue Akzeptanznachweise zu erfinden. + +### 2. Rechte, Beobachtung und Capability + +Planurheber und Freigeber benötigen jeweils die üblichen Operationsrechte plus +`updates:apply` und Linux `root:execute` beziehungsweise Windows `system:execute`. +`scripts:execute` wird nicht daraus abgeleitet. Eine zusätzliche versionierte +zentrale/local-Updaterpolicy begrenzt exakte Geräte-/Generations-/Principal-, +Updater-/Keyring-/Manifest-/Vorgänger- und Pinbindungen. Standard bleibt deny. +Die WebUI zeigt Ziel und Vorgänger, beide Binärhashes, Rechte, Unterbrechung, +Rollback, Pinänderung und Fristen; MCP verwendet nur Plan/Submit/Status. + +`agent.update.check/1` wird nach tatsächlich funktionierendem reinem Metadaten- +Check gemeldet. `agent.update.apply/1` erst nach nativer aktueller Qualifikation +des installierten unabhängigen Updaters, IPC-/Peer-/Lock-/Ledgerprüfung und +bestätigtem signiertem Sync. Ein Librarybuild erzeugt keine Capability. Check +speichert Quelle, tatsächlich beobachteten Manifesthash, Zeit, Qualität und +`available`/`same`/`not_configured`/`error`; er lädt keine großen Dateien und +legt weder Jobs noch Outbox für Wirkungen an. `rolled_back` beim installierten +Record ist von der angebotenen Kandidatenversion getrennt sichtbar. + +### 3. Begrenzter Releasekatalog und eigener großer Artefaktpfad + +Neue immutable Tenanttabellen `agent_releases` und `agent_release_artifacts` +mit zusammengesetzten Tenant-FKs, RLS/FORCE-RLS und ohne UPDATE/DELETE für die +Anwendungsrolle. Release-ID/Sequenz/Plattform sind eindeutig; Publizieren +verifiziert Signatur, kanonische Bytes, Rolle, Länge und Hash beider Dateien. +Keine Änderung am262144Byte-`CHECK` der bestehenden `artifacts`-Tabelle. +Ein tenantgebundener `AgentReleaseStore` arbeitet mit bereits geprüften +content-addressierten, unveränderlichen Objekten und begrenzten Readhandles; +kein `get()->Vec` für bis256MiB. Publikation ist ein Plattformbetriebsrecht, +kein vom Modell befüllbarer allgemeiner Upload-/Signierdienst. + +Neuer `GET /agent/v1/update-artifacts/{artifact_id}` mit `job_id`, `attempt_id`, +`offset`, `length`: Geräte-mTLS, genau genehmigter aktueller `update_agent`-Job, +aktuelle Tenant-/Geräte-/Generations-/Rechte-/Planbindung und exakt eine der +beiden Referenzen. Jeder Chunk prüft diese Bindung erneut; höchstens512KiB, +Gesamtobjekt höchstens256MiB, begrenzte Parallelität/IOzeit und kein Redirect. +`Content-Range`, Gesamtgröße und SHA256 sind an den Deskriptor gebunden. +Server verifiziert Objektidentität/-länge vor Read und streamt begrenzt; +Agent/Updater prüft unabhängig den vollständigen Gesamt-SHA256 und exaktes EOF. +Nach Antwortverlust dürfen nur fehlende Downloadbytes desselben geschützten +Stagingobjekts weiterbezogen werden, niemals ein neuer Installer-/Aktivierungs- +versuch. Eine fortgesetzte Datei wird vor Verwendung vollständig neu gehasht. + +### 4. Stabiler Updater, einmalige Übergabe und Absturzverhalten + +Separat bootstrapped stabiles Updaterbinary; dieser erste Updatejob verändert +es nicht. Feste Linux-UID-/Windows-Dienst-SID-/PID-/Image-/ACLprüfungen, keine +vom Agenten gewählten Programme/Pfade. Bestehende Agent-/Helper-Servicepfade +bleiben erhalten. Alle tatsächlich installierten Profile, die dieselbe +Helperbinary verwenden, müssen im fest provisionierten Dienstset stehen und +vor Austausch bestätigt gestoppt sein; unbekanntes Profil verweigert. Der +Updater gehört selbst nicht zu diesem Stopset. + +Die erste Empfehlung ist **denselben bestehenden Helperverbrauchsledger und +`executor.lock`** zu verwenden, wie heute schon mehrere Helperprofile, statt +einen ungebundenen neuen Ready-/SQLitepfad zu eröffnen. Bootstrap fügt nur eigene +append-only Updateintents hinzu, ohne alte Zeilen/Schemaobjekte zu ersetzen. +Updater prüft seinen aktuellen Prozess-/Boot-/Clock-/Signatur-/Syncbezug selbst; +ein anderer Prozess vererbt keine Bereitschaft. Ob der vorhandene gemeinsame +Helpersnapshot dies ohne Wireerweiterung vollständig bindet, ist vor Runtime- +Code anhand `HelperSync`/`ExecutorLedgerGuard` zu prüfen. Falls nicht, bleibt +Apply geschlossen bis zu einer separat versionierten Participantbindung; +kein weiterer Journal-ID-Slot wird stillschweigend in alten Tags versteckt. + +Der Updater darf seinen eigenen Updateversuch nach Verbrauch als einzigen +offenen Versuch führen; jeder **andere** offene/unknown-/unsettled-Versuch +sperrt. Root-/SYSTEM-Wartungsskripte und Paket-/Rebootwirkungen verwenden +dieselbe Sperre. Nach Übergabe überlebt der Updater Agent-/Helperstop und +journalisiert im eigenen erhaltenen Intent die folgenden Phasen: + +| Phase | Dauerhafter Beleg und zulässige Folgerung nach Absturz | +|---|---| +| `staged_verified` | Nur geprüfte Dateien vorhanden, noch kein Stop/Swap; Nichtstart nur mit unabhängig belegtem Nichtdispatch | +| `handoff_consumed` | Originaljob/Grant/Versuch und vollständige Vorherzeugen fest, kein zweites Execute | +| `stop_intent` / `all_stopped` | Einmaliger Stop angekündigt/bestätigt; unklare Dienste erst lesen, nicht blind erneut stoppen/starten | +| `replace_intent(role)` / `replaced(role)` | Jede einzelne Code-/Pinersetzung bindet Original-/Zielhash, ACL und retained Backup; tatsächliche Datei entscheidet über Teilzustand | +| `pair_verified` | Gesamtes neues Code-/Pinset vollständig geprüft, vor jedem neuen Dienststart | +| `start_intent(service)` / `started(service)` | Jeder Start nur einmal, tatsächliche SCM-/systemd-/PID-/Imagebelege, kein Retry bei verlorenem Reply | +| `health_verified` | Neues mTLS, tatsächlicher Codepaarbeleg, Inventar-ACK und signierter Sync für selben Originalversuch innerhalb180Sekunden | +| `rollback_intent` / `rollback_verified` | Ausschließlich gebundene Originalcode-/Pinbytes einmal zurück, gleicher aktueller Datenzustand und unveränderter Floor | +| `outcome_persisted` | Originalerfolg oder bekannter Fehlstart samt Rollbackresultat dauernd gespeichert; unverändert bis ACK erneut übermitteln | + +Anwendungsweite Effectgates bleiben während Wechsel und Health geschlossen; +der eigene bereits verbrauchte Updateversuch darf gezielt abgeglichen werden, +ohne dadurch neue allgemeine Starts zu erlauben. Sonst würde die eigene offene +Updatezeile Health-Sync dauerhaft blockieren. Nach frischem Prozessstart ist +kein alter Gate-/Leasezustand gültig. Ein unbekannter Teiltausch/Start bleibt +`unknown`; Recovery liest vorhandene Dateien/Intents und darf daraus keine +neue Wirkungserlaubnis konstruieren. Allgemeines Resume bei ungeklärtem +Dispatch und Endlosschleifen automatischer Rollbacks gehören nicht dazu. + +### 5. Konkrete Datei-/Abnahmefolge nach erneutem Review + +| Lieferung | Geplanter enger Dateiscope und überprüfbares Ergebnis | +|---|---| +| Gemeinsamer Vertrag | Additives `domain/src/agent_update.rs`, zugehörige `Action`-Matches und Golden-/Legacyfixtures; `updater` bleibt eigenständiger Verifier, keine OSwirkung | +| Katalog und feste Planung | Neue Migration, `server/src/agent_releases.rs`, eigener Store/Streaminghandler, begrenzte Ergänzungen in `jobs`, `job_gateway`, Policy und MCPschema; alte Paketlimits bleiben bestehen | +| Passive Agentbeobachtung | Bestehende Transport-/Inventarworker ergänzen festen Releasecheck und gespeicherte Beobachtung; keine angeforderte Liveaktion als Telemetrie tarnen | +| Geschlossener Updaterworker | Neues unabhängiges Binary/OSadapter und versionierte Bootstrapdefinition, feste IPC/Locks/Ledger/Intents/Pinrenderer; keine offenen neuen Capabilities vor Qualifikation | +| Linux-Abnahme zuerst | Reine Kernunits nativ auf Cloud-Linux; danach ein fixes WebUI-genehmigtes Update samt getrennten belegten Fehler-/Redelivery-/Stateerhaltungsfällen | +| Windows danach | Native Kern-/IPC-/SCM-/Pin-/Codepaar-/Rollbackabnahme auf Windowsgast, dieselbe WebUI-/Tenantgrenze; keine Notebookdienste | + +Vor Runtimefreigabe sind vor allem gemeinsamer Syncteilnehmer, exakt erlaubte +Pinprofile und erfolgreiche Health bei ausschließlich eigenem offenen +Updateversuch zu entscheiden. Diese Liste enthält keine neue Terminalengine, +generischen Paketprovider, Keyrotationplattform, Restorefunktion oder weiteren +Produktumfang. Alle genannten Dateien/Befehle/Abnahmen dieses Abschnitts sind +**geplant, nicht ausgeführt**. From 668369a1f2a3d559a1703070f3b086c7b5c28dcb Mon Sep 17 00:00:00 2001 From: Kevin Janssen Date: Sat, 14 Nov 2026 16:04:42 +0100 Subject: [PATCH 2/7] test: prove signed updater verifier contracts on cloud Linux --- deploy/agent_updater_contract_acceptance.py | 313 ++++++++++++++++++++ docs/agent-updater-native-contracts.md | 89 ++++++ docs/agent-updater-proposal.md | 10 +- 3 files changed, 409 insertions(+), 3 deletions(-) create mode 100644 deploy/agent_updater_contract_acceptance.py create mode 100644 docs/agent-updater-native-contracts.md diff --git a/deploy/agent_updater_contract_acceptance.py b/deploy/agent_updater_contract_acceptance.py new file mode 100644 index 0000000..48b0615 --- /dev/null +++ b/deploy/agent_updater_contract_acceptance.py @@ -0,0 +1,313 @@ +#!/usr/bin/env python3 +"""Native Linux-first qualification of the pure updater verifier, never Apply. + +prepare-local packages the already-qualified test executable without rebuilding. +Only the parent orchestrator runs linux/readback-linux, explicitly. No daemon, +product configuration, enrollment, key, policy, database or RMM job is touched. +""" +import argparse +import base64 +import hashlib +import inspect +import json +import os +from pathlib import Path +import re +import stat +import subprocess +import uuid + +import windows_msi_contract_acceptance as common + +ROOT = Path(__file__).resolve().parents[1] +STATE = ROOT / 'devstate/agent-updater-native' +PROFILE = 'agent-updater-pure-contracts-v1' +CORE_COMMIT = 'cc5c93596d0864c526b69a4f7efca805599b6ea1' +IMAGE = 'sha256:9a76ad3744ebfdddae96ca10001ce8291c1b332fb54c8df5eea0e8e999ac6fc6' +REMOTE = '/var/lib/rmm-agent-updater-contracts' +ARTIFACT_SHA = 'e3a1a3140da09de2f86055faa45faf7ba05ddddc2d92d23fef3df03a63bf2999' +ARTIFACT_BYTES = 1544584 +EXPECTED = sorted([ + 'canonical_release_and_exact_role_bytes_are_metadata_only', + 'signature_domain_bytes_unknown_key_and_revocation_are_independent', + 'signed_noncanonical_unknown_duplicate_and_oversize_payloads_are_rejected', + 'incompatible_clock_platform_state_protocol_and_trust_contexts_are_rejected', + 'monotone_floor_same_sequence_conflict_and_postrollback_state_are_preserved', + 'descriptor_roles_ids_bounds_and_digest_encoding_are_strict', + 'artifact_eof_extra_bytes_hash_and_io_errors_never_verify', + 'streamed_large_release_verifies_with_fixed_read_window', + 'keyring_rejects_weak_keys_duplicates_empty_sets_and_invalid_ranges', +]) +require = common.require +save = common.save +load = common.load +private = common.private +sha = common.sha + + +def setup(): + os.umask(0o077) + STATE.mkdir(mode=0o700, exist_ok=True) + private(STATE, True) + + +def sources(): + """Only actual core/compiler inputs; later docs/runner commits do not rebuild.""" + names = {'Cargo.toml', 'Cargo.lock'} + names.update(str(p.relative_to(ROOT)) for p in (ROOT / 'crates/updater').rglob('*') if p.is_file()) + result = {} + for name in sorted(names): + path = ROOT / name + require(path.is_file() and not path.is_symlink(), 'fixed regular core source') + committed = subprocess.run(['git', 'show', CORE_COMMIT + ':' + name], cwd=ROOT, capture_output=True, check=True).stdout + require(hashlib.sha256(committed).hexdigest() == sha(path), 'original reviewed core source') + result[name] = sha(path) + return result + + +def driver_sources(): + return {name: sha(ROOT / name) for name in ( + 'deploy/agent_updater_contract_acceptance.py', + 'deploy/windows_msi_contract_acceptance.py', + 'deploy/vm_access_check.py', + )} + + +def remote_source_sha(): + return hashlib.sha256(inspect.getsource(linux_case).encode()).hexdigest() + + +def prepare(qualification): + setup() + require(qualification.absolute() == ROOT / 'devstate/agent-updater/local-qualification.json', 'existing fixed local qualification') + old = load(qualification) + expected_sources = sources() + require(old['profile'] == PROFILE and old['image_id'] == IMAGE and old['target'] == 'x86_64-unknown-linux-gnu' + and old['sources'] == expected_sources and old['test_count'] == 9 and old['tests'] == EXPECTED + and old['native_cloud_vm_tested'] is False and old['agent_started'] is False and old['activation_implemented'] is False, + 'original nine local checks only') + for label in ('fmt', 'clippy', 'tests'): + check = old['checks'][label] + require(check['exit_code'] == 0 and check['log_sha256'] == sha(qualification.parent / (label + '.log')) + and check['command'][0] == 'docker' and IMAGE in check['command'], 'original local command receipt') + common.check_output((qualification.parent / 'tests.log').read_bytes(), 9) + item = old['artifact'] + original = Path(item['path']) + expected = ROOT / 'devstate/agent-updater/target/x86_64-unknown-linux-gnu/release/deps/release_contract-2aa0a51dd0c5c97d' + meta = original.lstat() + require(original == expected and stat.S_ISREG(meta.st_mode) and meta.st_nlink == 1 and meta.st_uid in (0, os.getuid()) + and item['sha256'] == sha(original) == ARTIFACT_SHA and item['bytes'] == meta.st_size == ARTIFACT_BYTES, + 'original qualified link, never rebuilt') + folder = STATE / ('prepared-' + str(uuid.uuid4())) + folder.mkdir(mode=0o700) + artifact = folder / 'updater-contracts' + fd = os.open(artifact, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) + with os.fdopen(fd, 'wb') as output: + output.write(original.read_bytes()); output.flush(); os.fsync(output.fileno()) + require(sha(artifact) == ARTIFACT_SHA and artifact.read_bytes()[:6] == b'\x7fELF\x02\x01' + and artifact.read_bytes()[18:20] == b'\x3e\0', 'same Linux x64 delivery bytes') + def inspect_elf(*args): + return common.command(['docker', 'run', '--rm', '--network', 'none', '--read-only', + '-v', str(artifact) + ':/unit:ro', '--entrypoint', 'readelf', IMAGE, *args, '/unit'], folder).decode() + versions = inspect_elf('--version-info') + dynamic = inspect_elf('-d') + glibc = sorted(set(re.findall(r'GLIBC_(\d+\.\d+)', versions)), key=lambda n: tuple(map(int, n.split('.')))) + require(glibc and tuple(map(int, glibc[-1].split('.'))) <= (2, 34), 'known Cloud Linux GLIBC compatibility') + manifest = dict(schema_version=1, profile=PROFILE, core_commit=CORE_COMMIT, + local_qualification_path=str(qualification.absolute()), local_qualification_sha256=sha(qualification), + core_sources=expected_sources, driver_sources=driver_sources(), remote_source_sha256=remote_source_sha(), + artifact=dict(path=str(artifact), sha256=sha(artifact), bytes=artifact.stat().st_size, + glibc_max=glibc[-1], needed=sorted(re.findall(r'Shared library: \[([^\]]+)\]', dynamic))), + test_names=EXPECTED, test_count=9, test_executable_rebuilt=False, + local_only=True, native_cloud_vm_tested=False, agent_started=False, activation_implemented=False) + save(folder / 'manifest.json', manifest) + print(json.dumps(dict(manifest=str(folder / 'manifest.json'), manifest_sha256=sha(folder / 'manifest.json'), + tests=9, rebuilt=False, native_executed=False))) + + +def verified(path, new_case): + path = path.absolute() + require(path.name == 'manifest.json' and path.parent.parent == STATE + and re.fullmatch(r'prepared-[0-9a-f-]{36}', path.parent.name), 'fixed native manifest path') + private(path.parent, True) + value = load(path) + require(value['schema_version'] == 1 and value['profile'] == PROFILE and value['core_commit'] == CORE_COMMIT + and value['driver_sources'] == driver_sources() and value['remote_source_sha256'] == remote_source_sha() + and value['test_names'] == EXPECTED and value['test_count'] == 9 + and value['test_executable_rebuilt'] is False and value['native_cloud_vm_tested'] is False, + 'original reviewed core and native driver') + if new_case: + require(value['core_sources'] == sources(), 'new native case needs same core') + item = value['artifact'] + require(Path(item['path']) == path.parent / 'updater-contracts' + and item['sha256'] == ARTIFACT_SHA and item['bytes'] == ARTIFACT_BYTES, 'fixed delivery tuple') + private(item['path']) + require(sha(item['path']) == ARTIFACT_SHA and Path(item['path']).stat().st_size == ARTIFACT_BYTES, + 'retained immutable delivery') + return value + + +def linux_case(p): + """Sent only by the parent to the fixed Cloud Linux bootstrap endpoint.""" + import resource + ident = str(uuid.UUID(p['id'])) + require(ident == p['id'] and p['profile'] == 'agent-updater-pure-contracts-v1' + and p['action'] in ('prepare', 'run', 'read') and p['test_count'] == 9 and len(p['names']) == 9, + 'fixed pure updater case') + require(os.geteuid() == 0 and os.uname().machine == 'x86_64', 'fixed Cloud Linux bootstrap architecture') + root = Path('/var/lib/rmm-agent-updater-contracts') + def safe(path, directory, executable=False): + item = path.lstat() + require(item.st_uid == 0 and stat.S_IMODE(item.st_mode) == (0o700 if directory else 0o500 if executable else 0o600) + and (stat.S_ISDIR(item.st_mode) if directory else stat.S_ISREG(item.st_mode) and item.st_nlink == 1), 'private unit object') + def write(path, value): + fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600) + with os.fdopen(fd, 'w') as output: + json.dump(value, output); output.flush(); os.fsync(output.fileno()) + directory = os.open(path.parent, os.O_DIRECTORY | os.O_RDONLY) + try: os.fsync(directory) + finally: os.close(directory) + def read(path): + safe(path, False); require(path.stat().st_size <= 2 * 1024 * 1024, 'bounded original unit receipt') + return json.loads(path.read_bytes()) + os.umask(0o077) + case = root / ident + if p['action'] == 'read' and not case.exists(): + return dict(id=ident, status='remote_case_absent') + if p['action'] == 'prepare': + if not root.exists(): root.mkdir(mode=0o700) + safe(root, True); case.mkdir(mode=0o700); write(case / 'intent.json', p) + return dict(id=ident, prepared=True) + safe(root, True); safe(case, True) + original = read(case / 'intent.json') + require({k:v for k,v in p.items() if k != 'action'} == {k:v for k,v in original.items() if k != 'action'}, 'exact original unit intent') + if p['action'] == 'read': + if (case / 'result.json').exists(): return read(case / 'result.json') + partial = {name:read(case / name) for name in ('listing.json',) if (case / name).exists()} + return dict(id=ident, status='started_without_result' if (case / 'started.json').exists() else 'prepared_without_start', partial=partial) + write(case / 'started.json', dict(execute_once=True, manifest_sha256=p['manifest_sha256'])) + binary = case / 'updater-contracts'; safe(binary, False) + require(binary.stat().st_size == p['artifact']['bytes'] == 1544584 + and hashlib.sha256(binary.read_bytes()).hexdigest() == p['artifact']['sha256'] == 'e3a1a3140da09de2f86055faa45faf7ba05ddddc2d92d23fef3df03a63bf2999', 'exact reviewed updater test executable') + binary.chmod(0o500); safe(binary, False, True) + temporary = case / 'tmp'; temporary.mkdir(mode=0o700) + env = {'PATH':'/usr/bin:/bin', 'LANG':'C.UTF-8', 'LC_ALL':'C.UTF-8', 'TMPDIR':str(temporary), 'RUST_BACKTRACE':'0'} + def limits(): + resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + resource.setrlimit(resource.RLIMIT_CPU, (15, 15)) + resource.setrlimit(resource.RLIMIT_FSIZE, (1048576, 1048576)) + resource.setrlimit(resource.RLIMIT_AS, (256 * 1024 * 1024, 256 * 1024 * 1024)) + require(subprocess.run(['/usr/bin/unshare','--net','--','/usr/bin/true'], env=env, capture_output=True, timeout=3).returncode == 0, 'isolated network namespace required') + listed = subprocess.run(['/usr/bin/unshare','--net','--',str(binary),'--list','--format','terse'], cwd=case, + env=env, capture_output=True, timeout=5, preexec_fn=limits) + require(listed.returncode == 0 and len(listed.stdout) <= 65536 and not listed.stderr, 'bounded actual test list') + lines = listed.stdout.decode().splitlines() + require(all(not line.strip() or __import__('re').fullmatch(r'[A-Za-z0-9_:]+: test', line) for line in lines), 'terse fixed test names only') + actual = sorted(line[:-6] for line in lines if line.endswith(': test')) + write(case / 'listing.json', dict(names=actual, sha256=p['artifact']['sha256'], exit_code=listed.returncode)) + require(actual == p['names'] and len(set(actual)) == 9, 'all nine exact names before test execution') + write(case / 'tests-started.json', dict(execute_once=True)) + with (case / 'stdout.bin').open('xb') as output, (case / 'stderr.bin').open('xb') as errors: + timed = False + try: + code = subprocess.run(['/usr/bin/unshare','--net','--',str(binary),'--test-threads=1'], cwd=case, env=env, + stdin=subprocess.DEVNULL, stdout=output, stderr=errors, timeout=20, preexec_fn=limits).returncode + except subprocess.TimeoutExpired: timed = True; code = None + output.flush(); errors.flush(); os.fsync(output.fileno()); os.fsync(errors.fileno()) + raw, errors = [(case / name).read_bytes() for name in ('stdout.bin', 'stderr.bin')] + require(len(raw) <= 1048576 and len(errors) <= 1048576, 'bounded original native output') + result = dict(id=ident, profile=p['profile'], platform='linux', manifest_sha256=p['manifest_sha256'], + runner_sha256=p['runner_sha256'], remote_source_sha256=p['remote_source_sha256'], core_commit=p['core_commit'], + artifact=p['artifact'], names=actual, exit_code=code, timed_out=timed, + stdout_b64=base64.b64encode(raw).decode(), stderr_b64=base64.b64encode(errors).decode(), + network_namespace=True, environment_cleared=True, list_before_run=True, + product_state_writes=False, rmm_jobs=False, activation_implemented=False) + write(case / 'result.json', result) + return result + + +def rpc(prefix, payload, folder): + code = 'import os,json,subprocess,base64,hashlib,uuid\nfrom pathlib import Path\nimport stat\n' + code += inspect.getsource(common.require) + '\n' + inspect.getsource(linux_case) + code += '\ntry:\n print(json.dumps(linux_case(' + repr(payload) + ')))\nexcept Exception as e:\n print(json.dumps(dict(bootstrap_error=True,error_class=type(e).__name__)))\n' + return common.transport(prefix, 'python3 -', code.encode(), folder) + + +def check_result(value, payload): + for name in ('id', 'profile', 'manifest_sha256', 'runner_sha256', 'remote_source_sha256', 'core_commit', 'artifact'): + require(value.get(name) == payload[name], 'complete native original tuple') + require(value.get('platform') == 'linux' and value.get('names') == EXPECTED and value.get('exit_code') == 0 + and value.get('timed_out') is False and value.get('product_state_writes') is False and value.get('rmm_jobs') is False + and value.get('activation_implemented') is False and value.get('network_namespace') is True + and value.get('environment_cleared') is True and value.get('list_before_run') is True, 'all pure native constraints') + raw = base64.b64decode(value['stdout_b64'], validate=True) + errors = base64.b64decode(value['stderr_b64'], validate=True) + require(len(raw) <= 1048576 and not errors, 'bounded clean native output') + common.check_output(raw, 9) + + +def execute(path, access_root, case_id): + is_readback = case_id is not None + setup(); path = path.absolute(); manifest = verified(path, new_case=not is_readback) + # This reads access configuration only when the parent explicitly runs native. + prefix = common.access_settings(access_root, 'linux') + if case_id is None: + case_id = str(uuid.uuid4()); folder = STATE / case_id; folder.mkdir(mode=0o700) + payload = dict(id=case_id, profile=PROFILE, manifest_sha256=sha(path), runner_sha256=sha(__file__), + remote_source_sha256=remote_source_sha(), core_commit=CORE_COMMIT, test_count=9, names=EXPECTED, + artifact={name:manifest['artifact'][name] for name in ('sha256', 'bytes')}) + save(folder / 'intent.json', dict(payload=payload, manifest_path=str(path), access_root=str(access_root))) + save(folder / 'started-local.json', dict(no_retry=True)) + else: + require(str(uuid.UUID(case_id)) == case_id, 'original canonical case') + folder = STATE / case_id; private(folder, True) + original = load(folder / 'intent.json'); load(folder / 'started-local.json') + require(original['manifest_path'] == str(path) and original['access_root'] == str(access_root), 'same-case access and manifest') + payload = original['payload'] + require(payload['id'] == case_id and payload['runner_sha256'] == sha(__file__) + and payload['manifest_sha256'] == sha(path) and payload['remote_source_sha256'] == remote_source_sha(), 'unchanged same-case runner') + if not case_id or not (folder / 'intent.json').exists(): + raise RuntimeError('missing create-once local intent') + # Readback never resumes upload or run, even after a lost prepare reply. + if not is_readback: + prepared = rpc(prefix, dict(payload, action='prepare'), folder) + save(folder / 'prepared-remote.json', prepared) + require(prepared == dict(id=case_id, prepared=True), 'fresh fixed remote scratch case') + common.upload(prefix, manifest['artifact'], REMOTE + '/' + case_id + '/updater-contracts', folder, 'updater-contracts') + result = rpc(prefix, dict(payload, action='read' if is_readback else 'run'), folder) + save(folder / ('readback-' + str(uuid.uuid4()) + '.json'), result) + if result.get('status'): + require(is_readback and result.get('id') == case_id and result['status'] in ('remote_case_absent','prepared_without_start','started_without_result'), 'read-only original partial status') + print(json.dumps(dict(verified=False, case_id=case_id, status=result['status'], retry_allowed=False))); return + check_result(result, payload) + proof = dict(verified=True, core_commit=CORE_COMMIT, manifest_sha256=sha(path), case_id=case_id, native=result) + proof_path = path.parent / 'linux-passed.json' + if proof_path.exists(): require(load(proof_path) == proof, 'preserve original native proof') + else: save(proof_path, proof) + print(json.dumps(dict(verified=True, case_id=case_id, tests=9, proof=str(proof_path), proof_sha256=sha(proof_path), activation_tested=False))) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('action', choices=('prepare-local','linux','readback-linux')) + parser.add_argument('--qualification', type=Path) + parser.add_argument('--manifest', type=Path) + parser.add_argument('--case') + parser.add_argument('--access-root', type=Path) + parser.add_argument('--execute-native-tests', action='store_true') + args = parser.parse_args() + if args.action == 'prepare-local': + require(args.qualification and not (args.manifest or args.case or args.access_root or args.execute_native_tests), 'prepare packages only existing local unit artifact') + prepare(args.qualification) + else: + require(args.manifest and args.access_root and not args.qualification, 'explicit original manifest and access root') + if args.action == 'linux': require(args.execute_native_tests and not args.case, 'explicit new native unit invocation') + else: require(args.case and not args.execute_native_tests, 'readback never executes tests') + execute(args.manifest, args.access_root, args.case) + + +if __name__ == '__main__': + try: main() + except Exception as error: + print(json.dumps(dict(error='AGENT_UPDATER_NATIVE_QUALIFICATION_INCOMPLETE', error_class=type(error).__name__, details_suppressed=True))) + raise SystemExit(2) from None diff --git a/docs/agent-updater-native-contracts.md b/docs/agent-updater-native-contracts.md new file mode 100644 index 0000000..f40f8df --- /dev/null +++ b/docs/agent-updater-native-contracts.md @@ -0,0 +1,89 @@ +# Reinen Updater-Prüfkern zuerst auf Cloud-Linux qualifizieren + +Stand 2026-11-14: Runner implementiert, lokal vorbereitet und anschließend vom +Eltern-Orchestrator **auf der Cloud-Linux-VM ausgeführt:9/9 bestanden**. +Dieser Schritt prüft ausschließlich die neun bereits lokal +bestandenen Verifierverträge. Er installiert weder Updater noch Agent/Helper, +öffnet keine Capability und führt keine Update-/Installer-/Skript-/RMM-Jobs aus. + +`deploy/agent_updater_contract_acceptance.py` bindet den unabhängig geprüften +Kerncommit `cc5c93596d0864c526b69a4f7efca805599b6ea1`, bestehende lokale +Qualification, Sourcehashes und unveränderte Testexe. Änderungen an späterer +Dokumentation erzeugen keinen falschen Rebuildbedarf. NativeDriver und die +wiederverwendeten geprüften SSH-/Receipt-Helpers erhalten eigene Sourcehashes. +Ein neuer Driverstand macht alte vorbereitete Manifeste absichtlich ungültig. + +Tatsächlich lokal ausgeführt: + +```text +python3 deploy/agent_updater_contract_acceptance.py --help +python3 deploy/agent_updater_contract_acceptance.py prepare-local --qualification /home/kevin/Schreibtisch/Coding/rust-discovery-agent-updater/devstate/agent-updater/local-qualification.json +``` + +Das bestehende Testimage wurde **nicht neu gebaut oder erneut ausgeführt**. +Originalbytes wurden create-only in den neuen geschützten Vorbereitungsordner +kopiert. Nur `readelf` lief im gepinnten Offline-Dockerimage. ELF-x64, maximale +GLIBC2.34 und benötigte dynamische Bibliotheken wurden ermittelt; native +Lader-/Ausführungsfähigkeit bleibt bis zum VM-Lauf offen. + +Lokales Manifest: +`devstate/agent-updater-native/prepared-37b4146d-cbef-431a-aa4a-9827841b8482/manifest.json`, +SHA256 `a7f0903cea77c36c4d40df5ad486161c10e55bb9a9135629a555ffafd411d521`. +Testexe unverändert1544584Bytes, SHA256 +`e3a1a3140da09de2f86055faa45faf7ba05ddddc2d92d23fef3df03a63bf2999`. +Python-/erzeugte Remotequellsyntax sowie sechs Ergebnis-Verweigerungsfälle, +Readback-ohne-Upload/-Run und fehlendes Native-Opt-in wurden lokal mit +Transport-Mocks geprüft; keine SSH-Verbindung und kein erneuter Unitlauf. + +**Anschließend tatsächlich durch den Eltern-Orchestrator ausgeführt:** + +```text +python3 deploy/agent_updater_contract_acceptance.py linux --manifest /home/kevin/Schreibtisch/Coding/rust-discovery-agent-updater/devstate/agent-updater-native/prepared-37b4146d-cbef-431a-aa4a-9827841b8482/manifest.json --access-root /home/kevin/Schreibtisch/Coding/rust-discovery --execute-native-tests +``` + +Der Runner liest erst bei diesem expliziten Aufruf die bereits vorhandene streng +geparste Linuxzugangskonfiguration aus dem Maincheckout. Ausschließlich der feste +Cloudclient `root@116.203.20.85`, vorhandener SSH-Key und bestätigter Hostkey sind +zulässig. Keine Zugangsdaten im Argument-/Ergebnispayload oder Chat. + +Remote wird ein neuer rootprivater Fall unter +`/var/lib/rmm-agent-updater-contracts/` einmal angelegt. Die exakt gehashte +Testexe muss vor Start alle neun erwarteten Testnamen melden. Sie läuft mit +geleerter Umgebung, eigener Scratchdirectory, Netzwerknamespace und CPU-/RAM-/ +Outputlimits. Vor dem einzigen Lauf steht der dauerhafte Create-once-Startmarker. +Bei verlorenem Reply niemals `linux` erneut ausführen oder neu hochladen. +Die ursprüngliche UUID steht im lokalen +`devstate/agent-updater-native//intent.json`; anschließend ausschließlich: + +```text +python3 deploy/agent_updater_contract_acceptance.py readback-linux --manifest /home/kevin/Schreibtisch/Coding/rust-discovery-agent-updater/devstate/agent-updater-native/prepared-37b4146d-cbef-431a-aa4a-9827841b8482/manifest.json --access-root /home/kevin/Schreibtisch/Coding/rust-discovery --case +``` + +Readback liest Ergebnis oder tatsächlichen Teilstatus desselben Falls. Es darf +weder Upload noch Unitstart fortsetzen. Fehlender/unklarer Abschluss bleibt +`verified=false`, `retry_allowed=false`. Erst vollständig geprüfte Original- +Ergebnisse9/9 ohne Skip schreiben `linux-passed.json`. Dieser Nachweis ist auch +dann **nur native Kernqualifikation**, keine erfolgreiche Agentaktualisierung, +WebUI-Abnahme, Windowsqualifikation oder Produktdienst-/Capabilityfreigabe. + +## Tatsächlicher Cloud-Linux-Nachweis + +Rootfall `420d53da-6e34-4e04-b871-0b571d8d3fc4` auf dem festgelegten Cloudclient +`116.203.20.85`: Der Runner prüfte zuerst die vollständige tatsächliche Liste +der neun erwarteten Tests und führte danach exakt diese neun ohne Skip aus. +Exitcode0, kein Timeout und keine Fehlerausgabe. Geleerte Umgebung, +Netzwerknamespace und unveränderte gehashte Originaltestexe sind im Ergebnis +gebunden. Keine Produktzustandsänderung und kein RMM-Job durch diese Units. + +Der geschützte lokale Beleg `linux-passed.json` neben dem oben genannten +Manifest wurde zurückgelesen und unabhängig gegen erwarteten Fall, +Manifest-/Artefakthashes und alle neun Testnamen geprüft. Proof-SHA256: +`bb98bdbd010d23e2905cdffa37b2ad38639b43c770ed2efafd7fa9ac8a22f9d4`. +Die tatsächliche VM-Ausführung erfolgte durch Root; der Verifier-Subagent +führte weiterhin keine eigene SSH-/VM-Aktion aus. + +Damit ist der **reine Linux-Prüfkern nativ qualifiziert**. Windows-Build und +native Windows-Units sind getrennt noch offen. Selbstupdateinstallation, +Releasekatalog/Streamingtransport, feste Plan-/Grant-/WebUI-Bindung, +Updaterprozess und Code-/Pin-Aktivierung/Health/Rollback bleiben unverändert +offen. Dieser Erfolg bescheinigt keinen vollständigen Agent-Autoupdater. diff --git a/docs/agent-updater-proposal.md b/docs/agent-updater-proposal.md index 116d659..d4c7012 100644 --- a/docs/agent-updater-proposal.md +++ b/docs/agent-updater-proposal.md @@ -259,9 +259,13 @@ bindet Quellen, Image-ID, tatsächliche Befehle/Loghashes und alle neun Testname Die Linux-Release-Testexe ist1544584Bytes groß, SHA256 `e3a1a3140da09de2f86055faa45faf7ba05ddddc2d92d23fef3df03a63bf2999`. Das ist ein lokaler Container-/Vertragsnachweis, **kein Cloud-VM-Nachweis**. -Native Linux-Test-VM vor Windows, Serverintegration und tatsächlicher -genehmigter Codewechsel bleiben offen. Kein Installer-/VM-Aufruf, keine -Dienständerung, keine Freigabe und kein RMM-Job durch diesen Quellschnitt. +Der danach durch Root ausgeführte eigene Native-Linux-Schritt bestand9/9 +auf der Cloud-Test-VM, Fall `420d53da-6e34-4e04-b871-0b571d8d3fc4`, +Proof-SHA256 `bb98bdbd010d23e2905cdffa37b2ad38639b43c770ed2efafd7fa9ac8a22f9d4`. +Details und klare Grenzen: [Native Kernqualifikation](agent-updater-native-contracts.md). +Windows, Serverintegration und tatsächlicher genehmigter Codewechsel bleiben +offen. Kein Installer, keine Dienständerung, keine Freigabe und kein RMM-Job +durch diesen reinen Prüfkern; der Subagent führte keine eigene VM-Aktion aus. ## Nächster Integrationsschnitt zur Freigabe: fester Codepaar-Updatejob From d6043e85760c4f77986dbb0dfc073286ce7e29c6 Mon Sep 17 00:00:00 2001 From: Kevin Janssen Date: Sat, 14 Nov 2026 16:07:16 +0100 Subject: [PATCH 3/7] docs: keep cloud client address in private access configuration --- docs/agent-updater-native-contracts.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/agent-updater-native-contracts.md b/docs/agent-updater-native-contracts.md index f40f8df..2afbf04 100644 --- a/docs/agent-updater-native-contracts.md +++ b/docs/agent-updater-native-contracts.md @@ -43,7 +43,7 @@ python3 deploy/agent_updater_contract_acceptance.py linux --manifest /home/kevin Der Runner liest erst bei diesem expliziten Aufruf die bereits vorhandene streng geparste Linuxzugangskonfiguration aus dem Maincheckout. Ausschließlich der feste -Cloudclient `root@116.203.20.85`, vorhandener SSH-Key und bestätigter Hostkey sind +Cloudclient als root auf der festgelegten Linux-Test-VM, vorhandener SSH-Key und bestätigter Hostkey sind zulässig. Keine Zugangsdaten im Argument-/Ergebnispayload oder Chat. Remote wird ein neuer rootprivater Fall unter @@ -69,7 +69,7 @@ WebUI-Abnahme, Windowsqualifikation oder Produktdienst-/Capabilityfreigabe. ## Tatsächlicher Cloud-Linux-Nachweis Rootfall `420d53da-6e34-4e04-b871-0b571d8d3fc4` auf dem festgelegten Cloudclient -`116.203.20.85`: Der Runner prüfte zuerst die vollständige tatsächliche Liste +der Linux-Test-VM: Der Runner prüfte zuerst die vollständige tatsächliche Liste der neun erwarteten Tests und führte danach exakt diese neun ohne Skip aus. Exitcode0, kein Timeout und keine Fehlerausgabe. Geleerte Umgebung, Netzwerknamespace und unveränderte gehashte Originaltestexe sind im Ergebnis From c8461ab963f942e267770404d72506ab920ddda1 Mon Sep 17 00:00:00 2001 From: Kevin Janssen Date: Sat, 14 Nov 2026 16:17:43 +0100 Subject: [PATCH 4/7] test: qualify pure updater verifier on Windows after cloud Linux --- deploy/agent_updater_windows_contracts.py | 236 ++++++++++++++++++++++ docs/agent-updater-proposal.md | 9 +- docs/agent-updater-windows-contracts.md | 103 ++++++++++ 3 files changed, 346 insertions(+), 2 deletions(-) create mode 100644 deploy/agent_updater_windows_contracts.py create mode 100644 docs/agent-updater-windows-contracts.md diff --git a/deploy/agent_updater_windows_contracts.py b/deploy/agent_updater_windows_contracts.py new file mode 100644 index 0000000..40d4a72 --- /dev/null +++ b/deploy/agent_updater_windows_contracts.py @@ -0,0 +1,236 @@ +#!/usr/bin/env python3 +"""Crossbuild/package pure Windows-GNU updater units after actual Cloud Linux9. + +No MSVC, installed agent, LocalService/SYSTEM, updater Apply or VM proof is +created by build-local. Only the parent invokes native Windows explicitly. +The original Linux driver and its same-case readback remain unchanged. +""" +import argparse +import base64 +import hashlib +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import uuid + +import agent_updater_contract_acceptance as linux + +ROOT = Path(__file__).resolve().parents[1] +STATE = ROOT / 'devstate/agent-updater-windows' +PROFILE = 'agent-updater-pure-windows-gnu-v1' +TARGET = 'x86_64-pc-windows-gnu' +IMAGE = 'sha256:1b2fd985d2c1fcc3545ace602405dc68fa899201bd8a73fa319ff96377203fa9' +LINUX_PROOF = ROOT / 'devstate/agent-updater-native/prepared-37b4146d-cbef-431a-aa4a-9827841b8482/linux-passed.json' +LINUX_PROOF_SHA = 'bb98bdbd010d23e2905cdffa37b2ad38639b43c770ed2efafd7fa9ac8a22f9d4' +LINUX_MANIFEST_SHA = 'a7f0903cea77c36c4d40df5ad486161c10e55bb9a9135629a555ffafd411d521' +require, save, load, private, sha = linux.require, linux.save, linux.load, linux.private, linux.sha + + +def setup(): + os.umask(0o077) + STATE.mkdir(mode=0o700, exist_ok=True) + private(STATE, True) + + +def linux_proof(): + require(sha(LINUX_PROOF) == LINUX_PROOF_SHA and sha(LINUX_PROOF.parent / 'manifest.json') == LINUX_MANIFEST_SHA, + 'original actual Cloud Linux proof and manifest') + proof = load(LINUX_PROOF) + manifest = linux.verified(LINUX_PROOF.parent / 'manifest.json', new_case=False) + intent = load(linux.STATE / proof['case_id'] / 'intent.json') + require(proof['verified'] is True and proof['core_commit'] == linux.CORE_COMMIT + and proof['manifest_sha256'] == LINUX_MANIFEST_SHA and proof['case_id'] == '420d53da-6e34-4e04-b871-0b571d8d3fc4' + and manifest['test_names'] == linux.EXPECTED, 'actual Linux-first original nine units') + linux.check_result(proof['native'], intent['payload']) + return manifest + + +def driver_sources(): + result = linux.driver_sources() + result['deploy/agent_updater_windows_contracts.py'] = sha(__file__) + return result + + +def script_sha(): + return hashlib.sha256(WINDOWS.encode()).hexdigest() + + +def build(): + setup(); linux_proof() + before = linux.sources() + folder = STATE / ('build-' + str(uuid.uuid4())); folder.mkdir(mode=0o700) + target = STATE / 'target'; target.mkdir(mode=0o700, exist_ok=True); private(target, True) + save(folder / 'intent.json', dict(core_commit=linux.CORE_COMMIT, core_sources=before, + driver_sources=driver_sources(), windows_script_sha256=script_sha(), target=TARGET, image=IMAGE, + linux_proof_sha256=LINUX_PROOF_SHA, expected_names=linux.EXPECTED, no_vm=True, no_apply=True)) + common = ['docker','run','--rm','--network','none','--read-only','--tmpfs','/tmp:rw,size=512m', + '-v',str(ROOT)+':/src:ro','-v',str(target)+':/target','-e','CARGO_TARGET_DIR=/target', + '--entrypoint','cargo',IMAGE] + options = ['--manifest-path','/src/Cargo.toml','--locked','--offline','--target',TARGET,'-p','rmm-updater'] + linux.common.command(common + ['clippy'] + options + ['--all-targets','--','-D','warnings'], folder) + raw = linux.common.command(common + ['test'] + options + ['--release','--test','release_contract','--no-run','--message-format=json'], folder) + linked = [] + for line in raw.splitlines(): + try: value = json.loads(line) + except ValueError: continue + if value.get('reason') == 'compiler-artifact' and value.get('executable') and value.get('target',{}).get('name') == 'release_contract' and value.get('profile',{}).get('test'): + linked.append(target / Path(value['executable']).relative_to('/target')) + require(len(linked) == 1 and linked[0].suffix == '.exe', 'exact single Windows GNU unit executable') + original = folder / 'updater-contracts.linked.exe'; delivery = folder / 'updater-contracts.exe' + for path in (original, delivery): + shutil.copyfile(linked[0], path); path.chmod(0o600) + original_hash = sha(original) + linux.common.command(['docker','run','--rm','--network','none','--read-only','-v',str(folder)+':/artifacts', + '--entrypoint','x86_64-w64-mingw32-strip',IMAGE,'--strip-debug','/artifacts/updater-contracts.exe'], folder) + require(sha(linked[0]) == sha(original) == original_hash, 'original Windows link retained') + data = delivery.read_bytes(); offset = int.from_bytes(data[60:64], 'little') + require(data[:2] == b'MZ' and data[offset:offset+6] == b'PE\0\0\x64\x86' and len(data) <= 16 * 1024 * 1024, 'bounded PE x64 test delivery') + details = linux.common.command(['docker','run','--rm','--network','none','--read-only','-v',str(delivery)+':/unit:ro', + '--entrypoint','x86_64-w64-mingw32-objdump',IMAGE,'-p','/unit'], folder).decode() + imports = sorted(set(re.findall(r'DLL Name:\s+(\S+)', details))) + allowed = {'advapi32.dll','api-ms-win-core-synch-l1-2-0.dll','bcrypt.dll','bcryptprimitives.dll','crypt32.dll','kernel32.dll','msvcrt.dll','ntdll.dll','userenv.dll','ws2_32.dll'} + require(imports and {name.lower() for name in imports}.issubset(allowed), 'only reviewed Windows system DLL imports') + require(linux.sources() == before, 'unchanged actual Linux-qualified core') + manifest = dict(schema_version=1, profile=PROFILE, target=TARGET, image=IMAGE, core_commit=linux.CORE_COMMIT, + core_sources=before, driver_sources=driver_sources(), windows_script_sha256=script_sha(), + linux_proof_sha256=LINUX_PROOF_SHA, linux_manifest_sha256=LINUX_MANIFEST_SHA, + expected_names=linux.EXPECTED, expected_count=9, windows_list_actual=False, + artifact=dict(path=str(delivery),sha256=sha(delivery),bytes=delivery.stat().st_size,imports=imports), + linked=dict(path=str(original),sha256=original_hash), debug_stripped_delivery=True, + clippy_D_warnings=True, native_windows_executed=False, native_msvc_runtime_qualified=False, + agent_started=False, product_state_writes=False, rmm_jobs=False, activation_implemented=False) + save(folder / 'manifest.json', manifest) + print(json.dumps(dict(manifest=str(folder / 'manifest.json'),manifest_sha256=sha(folder / 'manifest.json'), + artifact=manifest['artifact'], windows_tests_expected=9, native_windows_executed=False, msvc_qualified=False))) + + +def verified(path, new_case): + path = path.absolute() + require(path.name == 'manifest.json' and path.parent.parent == STATE + and re.fullmatch(r'build-[0-9a-f-]{36}',path.parent.name), 'fixed Windows-GNU manifest') + private(path.parent, True) + value = load(path) + require(value['schema_version'] == 1 and value['profile'] == PROFILE and value['target'] == TARGET and value['image'] == IMAGE + and value['core_commit'] == linux.CORE_COMMIT and value['driver_sources'] == driver_sources() + and value['windows_script_sha256'] == script_sha() and value['linux_proof_sha256'] == LINUX_PROOF_SHA + and value['linux_manifest_sha256'] == LINUX_MANIFEST_SHA and value['expected_names'] == linux.EXPECTED + and value['expected_count'] == 9 and value['windows_list_actual'] is False and value['clippy_D_warnings'] is True + and value['native_windows_executed'] is False and value['native_msvc_runtime_qualified'] is False, + 'original Linux-first pure unit scope') + if new_case: + linux_proof(); require(value['core_sources'] == linux.sources(), 'same original qualified core') + for field, name in (('artifact','updater-contracts.exe'),('linked','updater-contracts.linked.exe')): + item = value[field]; require(Path(item['path']) == path.parent / name, 'fixed retained artifact name') + private(item['path']); require(sha(item['path']) == item['sha256'], 'retained exact Windows bytes') + require(Path(value['artifact']['path']).stat().st_size == value['artifact']['bytes'], 'exact PE length') + return value + + +WINDOWS = r''' +$ErrorActionPreference='Stop' +$p=([Console]::In.ReadLine()|ConvertFrom-Json) +if([string]([guid]$p.id)-cne$p.id-or$p.profile-cne'agent-updater-pure-windows-gnu-v1'-or$p.action-notin@('prepare','run','read')-or$p.manifest_sha256-notmatch'^[a-f0-9]{64}$'-or$p.linux_proof_sha256-cne'bb98bdbd010d23e2905cdffa37b2ad38639b43c770ed2efafd7fa9ac8a22f9d4'-or$p.names.Count-ne9){throw 'Fixed Linux-first pure updater unit case'} +$root='C:\ProgramData\RustDiscoveryBootstrap';$case=Join-Path $root ('agent-updater-contracts-'+$p.id) +function Test-RmmUnitPrivate($path,$dir){$i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-ne$dir-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Unit path type'};$a=Get-Acl -LiteralPath $path;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Private unit owner'};$rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Empty private ACL'};foreach($e in $rules){if($e.AccessControlType-ne'Allow'-or$e.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')-or($e.PropagationFlags-band[Security.AccessControl.PropagationFlags]::InheritOnly)){throw 'Broad private unit ACL'}}} +function Write-RmmUnitNew($path,$value){$f=[IO.File]::Open($path,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read);try{$b=[Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 16 -Compress));$f.Write($b,0,$b.Length);$f.Flush($true)}finally{$f.Dispose()}} +function Get-RmmUnitJson($path){Test-RmmUnitPrivate $path $false;if((Get-Item -LiteralPath $path).Length-gt2097152){throw 'Receipt bound'};return(Get-Content -LiteralPath $path -Raw|ConvertFrom-Json)} +function Test-RmmUnitIntent($old){foreach($name in @('id','profile','manifest_sha256','runner_sha256','windows_script_sha256','core_commit','linux_proof_sha256')){if($old.$name-cne$p.$name){throw 'Original unit intent'}};if($old.artifact.sha256-cne$p.artifact.sha256-or$old.artifact.bytes-ne$p.artifact.bytes-or(@($old.names)-join"`n")-cne(@($p.names)-join"`n")){throw 'Original artifact/test tuple'}} +if($p.action-eq'read'-and!(Test-Path -LiteralPath $case)){@{id=$p.id;status='remote_case_absent'}|ConvertTo-Json -Compress;exit 0} +Test-RmmUnitPrivate $root $true +if($p.action-eq'prepare'){if(Test-Path -LiteralPath $case){throw 'Existing case retained'};New-Item -ItemType Directory -Path $case|Out-Null;Test-RmmUnitPrivate $case $true;Write-RmmUnitNew (Join-Path $case 'intent.json') $p;@{id=$p.id;prepared=$true}|ConvertTo-Json -Compress;exit 0} +Test-RmmUnitPrivate $case $true;Test-RmmUnitIntent (Get-RmmUnitJson (Join-Path $case 'intent.json')) +if($p.action-eq'read'){$result=Join-Path $case 'result.json';if(Test-Path -LiteralPath $result){Get-RmmUnitJson $result|ConvertTo-Json -Depth 16 -Compress;exit 0};$status=if(Test-Path -LiteralPath (Join-Path $case 'started.json')){'started_without_result'}else{'prepared_without_start'};$partial=@{};$listed=Join-Path $case 'listing.json';if(Test-Path -LiteralPath $listed){$partial.listing=Get-RmmUnitJson $listed};@{id=$p.id;status=$status;partial=$partial}|ConvertTo-Json -Depth 16 -Compress;exit 0} +function Invoke-RmmUnit($exe,[string]$arguments){$s=New-Object Diagnostics.ProcessStartInfo;$s.FileName=$exe;$s.Arguments=$arguments;$s.UseShellExecute=$false;$s.CreateNoWindow=$true;$s.WorkingDirectory=$case;$s.RedirectStandardOutput=$true;$s.RedirectStandardError=$true;$systemRoot=$env:WINDIR;$s.EnvironmentVariables.Clear();$s.EnvironmentVariables['SystemRoot']=$systemRoot;$s.EnvironmentVariables['WINDIR']=$systemRoot;$s.EnvironmentVariables['PATH']=$systemRoot+'\System32';$s.EnvironmentVariables['TEMP']=$script:temp;$s.EnvironmentVariables['TMP']=$script:temp;$s.EnvironmentVariables['RUST_BACKTRACE']='0';$c=New-Object Diagnostics.Process;$c.StartInfo=$s;if(!$c.Start()){throw 'Own unit start'};try{$o=$c.StandardOutput.ReadToEndAsync();$e=$c.StandardError.ReadToEndAsync();$timed=$false;if(!$c.WaitForExit(20000)){$timed=$true;$c.Kill();if(!$c.WaitForExit(2000)){throw 'Own test process did not exit'}};if(!$o.Wait(2000)-or!$e.Wait(2000)-or$o.Result.Length-gt1048576-or$e.Result.Length-gt1048576){throw 'Bounded unit output'};return @{exit_code=$c.ExitCode;timed_out=$timed;stdout_b64=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($o.Result));stderr_b64=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($e.Result))}}finally{$c.Dispose()}} +Write-RmmUnitNew (Join-Path $case 'started.json') @{execute_once=$true;manifest_sha256=$p.manifest_sha256} +$exe=Join-Path $case 'updater-contracts.exe';Test-RmmUnitPrivate $exe $false +if($p.artifact.sha256-notmatch'^[a-f0-9]{64}$'-or(Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLowerInvariant()-cne$p.artifact.sha256-or(Get-Item -LiteralPath $exe).Length-ne$p.artifact.bytes-or$p.artifact.bytes-gt16777216){throw 'Exact bounded Windows GNU PE'} +$script:temp=Join-Path $case 'tmp';New-Item -ItemType Directory -Path $script:temp|Out-Null;Test-RmmUnitPrivate $script:temp $true +$list=Invoke-RmmUnit $exe '--list --format terse';if($list.exit_code-ne0-or$list.timed_out-or$list.stderr_b64){throw 'Actual Windows test list'} +$text=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($list.stdout_b64));$unexpected=@($text-split'\r?\n'|Where-Object{$_.Trim()-and$_-notmatch'^[A-Za-z0-9_:]+: test$'});if($unexpected.Count){throw 'Only exact test names'} +[string[]]$names=@($text-split'\r?\n'|Where-Object{$_-match': test$'}|ForEach-Object{$_-replace': test$',''});[Array]::Sort($names,[StringComparer]::Ordinal) +Write-RmmUnitNew (Join-Path $case 'listing.json') @{names=$names;sha256=$p.artifact.sha256;listed=$list} +if($names.Count-ne9-or($names-join"`n")-cne(@($p.names)-join"`n")){throw 'All nine names before tests'} +Write-RmmUnitNew (Join-Path $case 'tests-started.json') @{execute_tests_once=$true} +$run=Invoke-RmmUnit $exe '--test-threads=1' +$value=@{id=$p.id;profile=$p.profile;platform='windows-gnu';manifest_sha256=$p.manifest_sha256;runner_sha256=$p.runner_sha256;windows_script_sha256=$p.windows_script_sha256;core_commit=$p.core_commit;linux_proof_sha256=$p.linux_proof_sha256;artifact=$p.artifact;names=$names;run=$run;list_before_run=$true;environment_cleared=$true;bootstrap_administrator_units=$true;local_service_proof=$false;system_proof=$false;msvc_runtime_qualified=$false;product_state_writes=$false;rmm_jobs=$false;activation_implemented=$false} +Write-RmmUnitNew (Join-Path $case 'result.json') $value;$value|ConvertTo-Json -Depth 16 -Compress +''' + + +def rpc(prefix, payload, folder): + script = 'try {\n' + WINDOWS + '\n} catch {[pscustomobject]@{bootstrap_error=$true;error_id=$_.FullyQualifiedErrorId;line=$_.InvocationInfo.ScriptLineNumber}|ConvertTo-Json -Compress;exit 1}' + command = 'powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand ' + base64.b64encode(script.encode('utf-16le')).decode() + return linux.common.transport(prefix, command, (json.dumps(payload) + '\n').encode(), folder) + + +def check_result(value, payload): + for field in ('id','profile','manifest_sha256','runner_sha256','windows_script_sha256','core_commit','linux_proof_sha256','artifact'): + require(value.get(field) == payload[field], 'complete original Windows unit tuple') + require(value.get('platform') == 'windows-gnu' and value.get('names') == linux.EXPECTED + and value.get('list_before_run') is True and value.get('environment_cleared') is True + and value.get('bootstrap_administrator_units') is True and value.get('local_service_proof') is False + and value.get('system_proof') is False and value.get('msvc_runtime_qualified') is False + and value.get('product_state_writes') is False and value.get('rmm_jobs') is False + and value.get('activation_implemented') is False, 'pure GNU bootstrap unit scope only') + run = value['run']; require(run['exit_code'] == 0 and run['timed_out'] is False, 'native unit completion') + raw = base64.b64decode(run['stdout_b64'], validate=True); errors = base64.b64decode(run['stderr_b64'], validate=True) + require(len(raw) <= 1048576 and not errors, 'bounded clean original output') + linux.common.check_output(raw, 9) + + +def execute(path, access_root, case_id): + setup(); path = path.absolute(); readback = case_id is not None + manifest = verified(path, new_case=not readback) + prefix = linux.common.access_settings(access_root, 'windows') + if not readback: + case_id = str(uuid.uuid4()); folder = STATE / case_id; folder.mkdir(mode=0o700) + payload = dict(id=case_id, profile=PROFILE, manifest_sha256=sha(path), runner_sha256=sha(__file__), + windows_script_sha256=script_sha(), core_commit=linux.CORE_COMMIT, linux_proof_sha256=LINUX_PROOF_SHA, + names=linux.EXPECTED, artifact={field:manifest['artifact'][field] for field in ('sha256','bytes')}) + save(folder / 'intent.json',dict(payload=payload,manifest_path=str(path),access_root=str(access_root))) + save(folder / 'started-local.json',dict(no_retry=True)) + else: + require(str(uuid.UUID(case_id)) == case_id, 'canonical original Windows case') + folder = STATE / case_id; private(folder,True); original = load(folder / 'intent.json'); load(folder / 'started-local.json') + require(original['manifest_path'] == str(path) and original['access_root'] == str(access_root), 'same original manifest/access') + payload = original['payload']; require(payload['id'] == case_id and payload['manifest_sha256'] == sha(path) + and payload['runner_sha256'] == sha(__file__) and payload['windows_script_sha256'] == script_sha(), 'same original runner') + if not readback: + prepared = rpc(prefix,dict(payload,action='prepare'),folder); save(folder / 'prepared-remote.json',prepared) + require(prepared == dict(id=case_id,prepared=True), 'new fixed private Windows case') + linux.common.upload(prefix,manifest['artifact'],'/C:/ProgramData/RustDiscoveryBootstrap/agent-updater-contracts-'+case_id+'/updater-contracts.exe',folder,'updater-contracts') + result = rpc(prefix,dict(payload,action='read' if readback else 'run'),folder) + save(folder / ('readback-'+str(uuid.uuid4())+'.json'),result) + if result.get('status'): + require(readback and result.get('id') == case_id and result['status'] in ('remote_case_absent','prepared_without_start','started_without_result'), 'original read-only partial status') + print(json.dumps(dict(verified=False,case_id=case_id,status=result['status'],retry_allowed=False))); return + check_result(result,payload) + proof = dict(verified=True,manifest_sha256=sha(path),linux_proof_sha256=LINUX_PROOF_SHA,case_id=case_id,native=result) + destination = path.parent / 'windows-gnu-passed.json' + if destination.exists(): require(load(destination) == proof, 'preserve original Windows unit proof') + else: save(destination,proof) + print(json.dumps(dict(verified=True,case_id=case_id,tests=9,proof=str(destination),proof_sha256=sha(destination),msvc_qualified=False,apply_tested=False))) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('action',choices=('build-local','windows','readback-windows')) + parser.add_argument('--manifest',type=Path); parser.add_argument('--access-root',type=Path); parser.add_argument('--case') + parser.add_argument('--execute-native-tests',action='store_true'); args = parser.parse_args() + if args.action == 'build-local': + require(not(args.manifest or args.access_root or args.case or args.execute_native_tests),'crossbuild only'); build() + else: + require(args.manifest and args.access_root,'original Windows unit manifest and access root') + if args.action == 'windows': require(args.execute_native_tests and not args.case,'explicit new native units') + else: require(args.case and not args.execute_native_tests,'readback never starts tests') + execute(args.manifest,args.access_root,args.case) + + +if __name__ == '__main__': + try: main() + except Exception as error: + print(json.dumps(dict(error='AGENT_UPDATER_WINDOWS_UNIT_INCOMPLETE',error_class=type(error).__name__,details_suppressed=True))) + raise SystemExit(2) from None diff --git a/docs/agent-updater-proposal.md b/docs/agent-updater-proposal.md index d4c7012..1aa96e2 100644 --- a/docs/agent-updater-proposal.md +++ b/docs/agent-updater-proposal.md @@ -1,7 +1,8 @@ # Agent-Selbstupdate: kleinster zusätzlicher Schnitt Stand 2026-11-14, **Integrationsvorschlag mit implementiertem reinem Prüfkern**, -keine neue Produktnorm und kein Installations-/VM-Nachweis. Basis: +keine neue Produktnorm und kein Installations-/Applynachweis. Die reinen +Linux-/Windows-Kernnachweise sind unten getrennt verlinkt. Basis: Spezifikation1.19, Kapitel0,4,13,16,19,22,25. Der User möchte den Agent-Autoupdater jetzt parallel zur Skriptkonsole. Damit wird ausschließlich dieser Teil aus M7 vorgezogen; Restore, HA, Relay und Lasttest @@ -263,7 +264,11 @@ Der danach durch Root ausgeführte eigene Native-Linux-Schritt bestand9/9 auf der Cloud-Test-VM, Fall `420d53da-6e34-4e04-b871-0b571d8d3fc4`, Proof-SHA256 `bb98bdbd010d23e2905cdffa37b2ad38639b43c770ed2efafd7fa9ac8a22f9d4`. Details und klare Grenzen: [Native Kernqualifikation](agent-updater-native-contracts.md). -Windows, Serverintegration und tatsächlicher genehmigter Codewechsel bleiben +Danach bestand derselbe Prüfkern als Windows-GNU-Unitbinary9/9 auf dem +Windowsgast, Fall `1a6dba2a-0db3-4aa8-8e21-dafcaabf85e3`, Proof-SHA256 +`fc6ef028f0d71639b940914d2cf66e809ed96f9803b4b0b10ea63c6e08978493`; +[separater Nachweis](agent-updater-windows-contracts.md), kein MSVC-/Dienstbeleg. +Serverintegration und tatsächlicher genehmigter Codewechsel bleiben offen. Kein Installer, keine Dienständerung, keine Freigabe und kein RMM-Job durch diesen reinen Prüfkern; der Subagent führte keine eigene VM-Aktion aus. diff --git a/docs/agent-updater-windows-contracts.md b/docs/agent-updater-windows-contracts.md new file mode 100644 index 0000000..334ecc7 --- /dev/null +++ b/docs/agent-updater-windows-contracts.md @@ -0,0 +1,103 @@ +# Windows-GNU-Pack für den reinen Updater-Prüfkern + +Stand 2026-11-14: Derselbe unveränderte Prüfkern aus `cc5c935` wurde nach dem +tatsächlichen Cloud-Linux-Ergebnis9/9 für `x86_64-pc-windows-gnu` gebaut. +**Anschließend nativ auf der Windows-Test-VM:9/9 bestanden.** Dies ist weder ein MSVC-Build noch +ein Nachweis für Agentdienst, LocalService/SYSTEM, Zeitvertrauen oder Apply. + +Der neue separate Runner `deploy/agent_updater_windows_contracts.py` bindet +den vollständigen tatsächlichen Linuxproof +`bb98bdbd010d23e2905cdffa37b2ad38639b43c770ed2efafd7fa9ac8a22f9d4`, +dessen Originalmanifest und die vollständigen neun Testnamen. Der bestehende +Linux-Runner `22e7e0a8…` bleibt unverändert; sein ursprüngliches Samecase- +Readback wird durch diese neue Windowsquelle nicht geändert. + +Tatsächlich lokal ausgeführt: + +```text +python3 deploy/agent_updater_windows_contracts.py build-local +``` + +Gepinntes Offline-Dockerimage mit Rust1.99.1 und GNU-Windows-Toolchain: +`sha256:1b2fd985d2c1fcc3545ace602405dc68fa899201bd8a73fa319ff96377203fa9`. +Quellmount nur lesbar, eigener Targetordner. Windows-Clippy für alle Targets +mit `-D warnings` und Release-Link der einzigen `release_contract`-Testexe +bestanden; kein neuer Fremddep und keine Kernquelländerung. Die ungestrippte +Originaldatei bleibt neben der gesonderten debuggestrippten Auslieferung erhalten. + +Erster Packfall `build-f15c6c7d-5ff3-421d-b568-2ef0d3c5b649` blieb nach +erfolgreichem Clippy/Link ohne Manifest stehen: Die enge DLL-Prüfung kannte das +von Rust-std importierte `api-ms-win-core-synch-l1-2-0.dll` noch nicht. Nur dieses +beobachtete Windows-API-Set wurde zusätzlich zugelassen. Ein neuer lokaler +Packfall verwendete dieselben unveränderten Kernquellen und gecachten Linkbytes; +alte Reports bleiben erhalten. Keine Windows-Unit wurde dabei ausgeführt. + +Aktueller Packmanifest: +`devstate/agent-updater-windows/build-5a9b7b49-39ba-4d34-b627-b3298886aa18/manifest.json`, +SHA256 `341e58c254b0848b0553ddf6cd04bb7c322e73752c9a2c87f1d2162991648bf8`. +PE-x64-Auslieferung2537309Bytes, SHA256 +`6c1d3d679c8558c50049c51755784863fc38f57c77c80e6ef005d89f09542396`. +Importe: `KERNEL32.dll`, `USERENV.dll`, `WS2_32.dll`, +`api-ms-win-core-synch-l1-2-0.dll`, `bcryptprimitives.dll`, `msvcrt.dll`, +`ntdll.dll`. Das sind beobachtete Imports, kein bestandener Loadernachweis. + +Python-Syntax, unveränderter vollständiger Linuxproof, sechs Ergebnis- +Verweigerungsfälle, ausschließlich lesendes Samecase-Readback ohne Upload +und fehlendes Native-Opt-in wurden lokal geprüft. Der geschützte Beleg +`local-driver-guards.json` liegt beim Manifest. Kein SSH, keine Zugangsdaten- +abfrage, kein Notebookagent und keine VM-/Dienst-/Policy-/RMM-Jobaktion. +Der Orchestrator prüfte anschließend die vollständige Remotequelle mit dem +vorhandenen lokalen PowerShell-AST-Parser erfolgreich. Der tatsächlich erzeugte +SSH-Prozessaufruf umfasst17874Zeichen und liegt unter der32767Zeichen-Grenze. +Der Verifier-Subagent führte weiterhin keine eigene SSH-/VM-Aktion aus. + +**Nach Sourceprüfung tatsächlich durch den Eltern-Orchestrator auf der +festgelegten Windows-Test-VM ausgeführt:** + +```text +python3 deploy/agent_updater_windows_contracts.py windows --manifest /home/kevin/Schreibtisch/Coding/rust-discovery-agent-updater/devstate/agent-updater-windows/build-5a9b7b49-39ba-4d34-b627-b3298886aa18/manifest.json --access-root /home/kevin/Schreibtisch/Coding/rust-discovery --execute-native-tests +``` + +Nur dieser explizite Aufruf liest den bestehenden privaten Zugang über +`credentials/server.conf`, `credentials/windows-dev-access.json` und den +bestätigten Windows-Hostkey. Keine Zugangsdaten oder Transportpräfixe in diesem +Beleg. Er erzeugt einen neuen privaten Bootstrap-Scratchfall und überprüft +vor dem einzigen Testlauf tatsächlich alle neun erwarteten Namen. Die Tests +laufen als Bootstrapadministrator mit geleerter Umgebung und begrenzter +Laufzeit/Ausgabe. Ein dauerhaftes Create-once-Intent verhindert Wiederholung. + +Nach Antwortverlust niemals neu starten oder neu hochladen; die ursprüngliche +UUID steht im lokalen `devstate/agent-updater-windows//intent.json`. +Ausschließlich desselben Falls lesend abgleichen: + +```text +python3 deploy/agent_updater_windows_contracts.py readback-windows --manifest /home/kevin/Schreibtisch/Coding/rust-discovery-agent-updater/devstate/agent-updater-windows/build-5a9b7b49-39ba-4d34-b627-b3298886aa18/manifest.json --access-root /home/kevin/Schreibtisch/Coding/rust-discovery --case +``` + +Erst ein vollständiger tatsächlicher9/9-Beleg ohne Skip erzeugt +`windows-gnu-passed.json`. Auch dieser Erfolg qualifiziert nur den reinen +GNU-Prüfkern auf dem Windowsgast, keine installierte +Selbstupdatefunktion oder MSVC-Agentlaufzeit. Normreview, Releasekatalog, +Streaming-/Plan-/WebUI-Bindung und eigenständiger Updater mit erhaltendem +Code-/Pin-Austausch bleiben ausdrücklich offen. + +## Tatsächliche native Windows-GNU-Ergebnisse + +Rootfall `1a6dba2a-0db3-4aa8-8e21-dafcaabf85e3`: Tatsächliche Liste aller neun +gebundenen Testnamen zuerst geprüft, anschließend9/9 ohne Skip bestanden, +Exitcode0, kein Timeout und keine Fehlerausgabe. Die Nativeexe entspricht +exakt der oben genannten Auslieferung und ist an den ursprünglichen tatsächlichen +Linuxproof gebunden. Geschützter Beleg `windows-gnu-passed.json` neben dem +Packmanifest, SHA256 +`fc6ef028f0d71639b940914d2cf66e809ed96f9803b4b0b10ea63c6e08978493`. +Der Beleg wurde gegen Fall, Manifest, Linuxproof, Artefakt und alle neun Namen +zurückgeprüft. + +Das tatsächliche Ergebnis weist ausdrücklich `local_service_proof=false`, +`system_proof=false`, `msvc_runtime_qualified=false`, `rmm_jobs=false` und +`activation_implemented=false` aus. Die Units liefen ausschließlich im eigenen +Bootstrap-Scratchfall; keine Agent-/Helperinstallation oder Policyänderung. +Damit ist derselbe reine Prüfkern **zuerst auf Cloud-Linux, danach auf dem +Windowsgast als GNU-Unitbinary** nativ qualifiziert. Der Autoupdater selbst +bleibt bis zur gesonderten Runtime-/Genehmigungs-/Health-/Rollbackintegration +unimplementiert. From 3543e07779b2bfda2b51dff8f113a66eda762d38 Mon Sep 17 00:00:00 2001 From: Kevin Janssen Date: Sat, 14 Nov 2026 16:27:22 +0100 Subject: [PATCH 5/7] docs: bind updater health design to preserved pending handoff --- docs/agent-updater-native-contracts.md | 6 ++- docs/agent-updater-proposal.md | 66 ++++++++++++++++++++++++++ 2 files changed, 70 insertions(+), 2 deletions(-) diff --git a/docs/agent-updater-native-contracts.md b/docs/agent-updater-native-contracts.md index 2afbf04..8a70ede 100644 --- a/docs/agent-updater-native-contracts.md +++ b/docs/agent-updater-native-contracts.md @@ -82,8 +82,10 @@ Manifest-/Artefakthashes und alle neun Testnamen geprüft. Proof-SHA256: Die tatsächliche VM-Ausführung erfolgte durch Root; der Verifier-Subagent führte weiterhin keine eigene SSH-/VM-Aktion aus. -Damit ist der **reine Linux-Prüfkern nativ qualifiziert**. Windows-Build und -native Windows-Units sind getrennt noch offen. Selbstupdateinstallation, +Damit ist der **reine Linux-Prüfkern nativ qualifiziert**. Der danach getrennt +ausgeführte Windows-GNU-Schritt bestand ebenfalls9/9; tatsächlicher Beleg und +Grenzen stehen in [Windows-Kernqualifikation](agent-updater-windows-contracts.md). +Selbstupdateinstallation, Releasekatalog/Streamingtransport, feste Plan-/Grant-/WebUI-Bindung, Updaterprozess und Code-/Pin-Aktivierung/Health/Rollback bleiben unverändert offen. Dieser Erfolg bescheinigt keinen vollständigen Agent-Autoupdater. diff --git a/docs/agent-updater-proposal.md b/docs/agent-updater-proposal.md index 1aa96e2..dcbf2a3 100644 --- a/docs/agent-updater-proposal.md +++ b/docs/agent-updater-proposal.md @@ -449,3 +449,69 @@ Updateversuch zu entscheiden. Diese Liste enthält keine neue Terminalengine, generischen Paketprovider, Keyrotationplattform, Restorefunktion oder weiteren Produktumfang. Alle genannten Dateien/Befehle/Abnahmen dieses Abschnitts sind **geplant, nicht ausgeführt**. + +## Geprüftes Runtimegate: eigener offener Versuch und Health + +Sourcebefund, **Entwurf ohne Produktänderung**: `HelperSync::apply` in +`crates/agent-core/src/helper_reconcile.rs:482` darf einen gültigen negativen +signierten Abgleich dauerhaft übernehmen. Die Startlease bleibt geschlossen: +`apply_inner` verlangt definitive Outcomes für sämtliche Zeilen und +`can_start` zusätzlich null offene `consumed.result IS NULL`-Zeilen +(`:575`, `:666`, `:696`). Deshalb darf Update-Health niemals allgemeines +`ready=true` voraussetzen oder trotz eigener offener Zeile erzeugen. + +Der normale Wiederabgleich macht gestartete unvollständige Versuche bewusst +unknown (`agent-core/src/reconcile.rs:233`, `server/src/synchronization.rs:717`) +und `ClientSync::confirm_helper` verweigert offene Helperwirkungen (`:127`). +Dies zu ignorieren wäre keine Healthimplementierung. Benötigt wird ein neuer, +ausdrücklicher **dauerhafter `pending/inflight`-Handoffvertrag** des genau +genehmigten Updateversuchs. Er muss kontrollierte Eigentümer-/Prozessübergaben +von einer tatsächlich unklaren Wirkung unterscheiden, ohne frühere Unknown- +Events, definitive Unknown-Outcomes, Startzeugen oder Deadlines umzuschreiben. +Fehlender Owner-/Handoff-/Zeitnachweis bleibt unknown und geschlossen; ein +späterer Healthbeleg heilt ihn nicht und berechtigt keinen erneuten Start. + +Windows hält `LedgerGuard` während der gesamten Helper-Dienstlebensdauer +(`agent-windows/src/helper_system.rs:222`, `:822`). Der separate Updater kann +denselben echten Lock daher nicht gleichzeitig erwerben und über den neuen +Helperstart halten. Empfohlener enger Pfad: alter Helper prüft Originalgrant +und verbraucht genau einmal, speichert immutable Delegations-/Ownerintent; +stabiler Updater übernimmt denselben Ledger ausschließlich während bestätigtem +Helperstop, prüft/tauscht Code+Pins und gibt die Ownership vor dem neuen +Helperstart ausdrücklich zurück. Der neue Helper hält danach wieder seinen +bestehenden Guard. Kein globaler Umbau zu schwächeren Locks pro Einzelrequest. + +Vorhandene IPC vertraut ausschließlich dem Netzwerkagenten: Linux verweigert +Root-Peers ausdrücklich (`privileged-helper/src/main.rs:92`), Windows bindet +Agent-Service-SID/SCM-PID/Peerimage (`agent-windows/src/helper_ipc.rs:227`). +Ein Updater darf sich nicht als dieser Agent ausgeben. Er benötigt eine neue +eng typisierte **lokale Participantbindung** mit festem eigenem Dienst, +UID/SID, tatsächlichem PID-/Image-/Prozessgeburts-/Policybeleg und ausschließlich +Original-Handoff, Healthbezug und Finalisierung dieses einen Versuchs. Root +oder SYSTEM allein sind kein ausreichender Peerbeleg. Bestehende ACL-/FileID- +Prüfungen dürfen dabei nicht stillschweigend gelockert werden. + +Gemeinsames erhaltenes Helperledger und aktueller Sync-Wirevertrag reichen für +die Historie grundsätzlich; eine zweite ungebundene Server-Journal-ID ist +für diesen Pfad nicht erforderlich. Ein negativer aktueller SignedSync ist +nur Kontrollkettennachweis. Zusätzlich vorgeschlagen: ein **evidenz-only** +signierter `UpdateHealthReceipt` mit eigener Domäne, Originalplan/Job/Versuch/ +Grant, Manifest/Codepaar/Pins, Ownernonce, Boot/Verbindung, tatsächlich +angewandtem SignedSync und frisch serverseitig gespeicherten Inventarbelegen. +Er ist weder ExecutionPermit noch Startlease, reaktiviert keine Genehmigung +und verlängert weder Originalstart- noch Health-/Gesamtdeadline. + +Erst nach unabhängigem lokalem Code-/Peer-/Intenterhaltungsnachweis und gültigem +Receipt dürfte der neue Helper das **noch ausstehende ursprüngliche** definitive +Outcome create-once speichern. Originale Signaturen/Events bleiben erhalten; +generisches Ersetzen eines vorhandenen Unknown-Outcomes ist ausdrücklich +ausgeschlossen (`ledger::persist_outcome`/Completion-CAS). Anschließend sollen +vorhandene Helper→Agent-Spiegelung und normaler signierter Abgleich die gleiche +Outcome-Bytefolge übernehmen und gezielt entsperren +(`agent-core/src/reconcile.rs:898`, `helper_reconcile.rs:616`). Die vorhandenen +Reboot-Sonderregeln für geänderte Outcomebytes werden nicht auf Updates +verallgemeinert (`helper_reconcile.rs:1312`, `reconcile.rs:1237`). + +Vor Applycode sind Pending-/Inflight-Lebenszyklus, Ownershipwechsel, neue lokale +IPC-/ACLbindung und die rein beweisende Receiptsemantik normativ zu prüfen. +Dieser Befund ist **keine Freigabe oder Implementierung** dieser Erweiterungen. From a2efb7990be6f3180c9cb6d458d76c9092d9a631 Mon Sep 17 00:00:00 2001 From: Kevin Janssen Date: Sat, 14 Nov 2026 19:27:52 +0100 Subject: [PATCH 6/7] Add typed updater handoff and preserving Linux Full renderer Keep release verifier and native drivers unchanged. Independently reviewed as an isolated contract after provisioned-file-key correction; eight local release contracts and format/clippy checks pass. Runtime persistence, approvals, service ownership, apply and rollback remain unimplemented. --- Cargo.lock | 13 + Cargo.toml | 2 +- crates/updater-handoff/Cargo.toml | 14 + crates/updater-handoff/src/lib.rs | 713 ++++++++++++++++++ crates/updater-handoff/src/linux_full.rs | 309 ++++++++ .../updater-handoff/tests/handoff_contract.rs | 639 ++++++++++++++++ docs/agent-updater-handoff.md | 190 +++++ docs/agent-updater-proposal.md | 9 + 8 files changed, 1888 insertions(+), 1 deletion(-) create mode 100644 crates/updater-handoff/Cargo.toml create mode 100644 crates/updater-handoff/src/lib.rs create mode 100644 crates/updater-handoff/src/linux_full.rs create mode 100644 crates/updater-handoff/tests/handoff_contract.rs create mode 100644 docs/agent-updater-handoff.md diff --git a/Cargo.lock b/Cargo.lock index 2a283d4..908c03f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2377,6 +2377,19 @@ dependencies = [ "uuid", ] +[[package]] +name = "rmm-updater-handoff" +version = "0.1.0" +dependencies = [ + "anyhow", + "ed25519-dalek", + "hex", + "serde", + "serde_json", + "sha2 0.10.9", + "uuid", +] + [[package]] name = "rsa" version = "0.9.10" diff --git a/Cargo.toml b/Cargo.toml index 1101ac5..5c3db0b 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"] +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"] [workspace.package] version = "0.1.0" diff --git a/crates/updater-handoff/Cargo.toml b/crates/updater-handoff/Cargo.toml new file mode 100644 index 0000000..bab8050 --- /dev/null +++ b/crates/updater-handoff/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "rmm-updater-handoff" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +anyhow.workspace = true +ed25519-dalek = "=2.2.0" +hex.workspace = true +serde.workspace = true +serde_json = { workspace = true, features = ["raw_value"] } +sha2.workspace = true +uuid.workspace = true diff --git a/crates/updater-handoff/src/lib.rs b/crates/updater-handoff/src/lib.rs new file mode 100644 index 0000000..c9328e2 --- /dev/null +++ b/crates/updater-handoff/src/lib.rs @@ -0,0 +1,713 @@ +//! Draft, effect-free helper/updater handoff contract. No approval, grant, +//! service operation, lock acquisition, persistence or general start lease. +//! +//! A platform adapter must authenticate the original request, atomically store +//! consumption + its exact existing start witness + the handoff in the SAME +//! helper ledger, and durably append each event before performing its action. +//! This module validates retained bytes and sequencing; it cannot attest OS +//! observations or make an uncommitted in-memory event durable. + +use anyhow::{Context, Result, ensure}; +use ed25519_dalek::{Signature, VerifyingKey}; +use serde::{Deserialize, Serialize, de::DeserializeOwned}; +use sha2::{Digest, Sha256}; +use uuid::Uuid; + +mod linux_full; +pub use linux_full::{LinuxFullTransition, LinuxFullTransitionProof, render_linux_full}; + +pub const MAX_RECORD_BYTES: usize = 16 * 1024; +pub const MAX_EVENT_BYTES: usize = 16 * 1024; +pub const MAX_EVENTS: usize = 16; +pub const HEALTH_DOMAIN: &[u8] = b"rmm.agent-update-health.v1\0"; + +/// All fields below are untrusted wire data, never authorization capabilities. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AttemptBinding { + pub tenant_id: Uuid, + pub asset_id: Uuid, + pub agent_id: Uuid, + pub enrollment_generation: u64, + pub assignment_version: u64, + pub plan_id: Uuid, + pub plan_sha256: String, + pub job_id: Uuid, + pub attempt_id: Uuid, + pub job_payload_sha256: String, + pub grant_id: Uuid, + pub authorization_id: Uuid, + pub original_request_sha256: String, + pub original_start_witness_sha256: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CodePair { + pub manifest_sha256: String, + pub agent_sha256: String, + pub helper_sha256: String, + pub pin_sha256: String, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Service { + LinuxAgent, + LinuxGeneralHelper, + LinuxAptHelper, + LinuxFullHelper, + WindowsAgent, + WindowsHelper, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum PinTransition { + UnchangedLinuxGeneralV1, + LinuxGeneralFullV1, + WindowsCodePairV1, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum FileRole { + AgentBinary, + HelperBinary, + LinuxFullConfig, + LinuxFullPin, + WindowsSettings, + WindowsPin, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct FileTransition { + pub role: FileRole, + pub old_sha256: String, + pub new_sha256: String, +} + +/// Hashes bind the retained, authenticated baseline; they are not substitutes +/// for reading original rows/signatures/inodes through pinned OS handles. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Handoff { + pub schema_version: u32, + pub attempt: AttemptBinding, + pub agent_journal_id: Uuid, + pub helper_journal_id: Uuid, + pub helper_checkpoint: u64, + pub previous_decision_id: Uuid, + pub boot_id: Uuid, + pub connection_generation: u64, + pub owner_nonce: Uuid, + pub updater_sha256: String, + pub updater_policy_sha256: String, + pub predecessor_record_sha256: String, + pub retained_state_sha256: String, + pub ledger_identity_sha256: String, + pub staged_files_sha256: String, + pub predecessor: CodePair, + pub target: CodePair, + pub pin_transition: PinTransition, + pub pin_transition_sha256: String, + pub files: Vec, + /// Exact provisioned order. All installed helper profiles must be present. + pub stop_set: Vec, + pub consumed_at: u64, + pub finish_before: u64, +} + +impl Handoff { + pub fn validate(&self) -> Result<()> { + ensure!(self.schema_version == 1, "HANDOFF_SCHEMA"); + for id in [ + self.attempt.tenant_id, + self.attempt.asset_id, + self.attempt.agent_id, + self.attempt.plan_id, + self.attempt.job_id, + self.attempt.attempt_id, + self.attempt.grant_id, + self.attempt.authorization_id, + self.agent_journal_id, + self.helper_journal_id, + self.previous_decision_id, + self.boot_id, + self.owner_nonce, + ] { + ensure!(!id.is_nil(), "HANDOFF_NIL_ID"); + } + ensure!( + self.attempt.enrollment_generation > 0 + && self.attempt.assignment_version > 0 + && self.connection_generation > 0, + "HANDOFF_GENERATION" + ); + for hash in [ + &self.attempt.plan_sha256, + &self.attempt.job_payload_sha256, + &self.attempt.original_request_sha256, + &self.attempt.original_start_witness_sha256, + &self.updater_sha256, + &self.updater_policy_sha256, + &self.predecessor_record_sha256, + &self.retained_state_sha256, + &self.ledger_identity_sha256, + &self.staged_files_sha256, + &self.pin_transition_sha256, + ] { + digest(hash)?; + } + for pair in [&self.predecessor, &self.target] { + for hash in [ + &pair.manifest_sha256, + &pair.agent_sha256, + &pair.helper_sha256, + &pair.pin_sha256, + ] { + digest(hash)?; + } + } + ensure!( + self.predecessor.manifest_sha256 != self.target.manifest_sha256, + "HANDOFF_SAME_RELEASE" + ); + ensure!( + self.consumed_at > 0 + && self.finish_before > self.consumed_at + && self.finish_before - self.consumed_at <= 600, + "HANDOFF_DEADLINE" + ); + let roles: Vec<_> = self.files.iter().map(|file| file.role).collect(); + let expected_roles = match self.pin_transition { + PinTransition::UnchangedLinuxGeneralV1 => { + vec![FileRole::AgentBinary, FileRole::HelperBinary] + } + PinTransition::LinuxGeneralFullV1 => vec![ + FileRole::AgentBinary, + FileRole::HelperBinary, + FileRole::LinuxFullConfig, + FileRole::LinuxFullPin, + ], + PinTransition::WindowsCodePairV1 => vec![ + FileRole::AgentBinary, + FileRole::HelperBinary, + FileRole::WindowsSettings, + FileRole::WindowsPin, + ], + }; + ensure!(roles == expected_roles, "HANDOFF_FILE_SET"); + for file in &self.files { + digest(&file.old_sha256)?; + digest(&file.new_sha256)?; + } + ensure!( + self.files[0].old_sha256 == self.predecessor.agent_sha256 + && self.files[0].new_sha256 == self.target.agent_sha256 + && self.files[1].old_sha256 == self.predecessor.helper_sha256 + && self.files[1].new_sha256 == self.target.helper_sha256, + "HANDOFF_FILE_IMAGE_BINDING" + ); + if self.files.len() == 4 { + ensure!( + self.files[3].old_sha256 == self.predecessor.pin_sha256 + && self.files[3].new_sha256 == self.target.pin_sha256, + "HANDOFF_FILE_PIN_BINDING" + ); + } + match self.pin_transition { + PinTransition::UnchangedLinuxGeneralV1 => { + ensure!( + self.stop_set == [Service::LinuxAgent, Service::LinuxGeneralHelper] + || self.stop_set + == [ + Service::LinuxAgent, + Service::LinuxGeneralHelper, + Service::LinuxAptHelper + ], + "HANDOFF_UNSUPPORTED_SERVICE_SET" + ); + ensure!( + self.predecessor.pin_sha256 == self.target.pin_sha256, + "HANDOFF_LINUX_PIN_CHANGED" + ); + } + PinTransition::LinuxGeneralFullV1 => ensure!( + self.stop_set + == [ + Service::LinuxAgent, + Service::LinuxGeneralHelper, + Service::LinuxFullHelper + ] + || self.stop_set + == [ + Service::LinuxAgent, + Service::LinuxGeneralHelper, + Service::LinuxFullHelper, + Service::LinuxAptHelper + ], + "HANDOFF_UNSUPPORTED_SERVICE_SET" + ), + PinTransition::WindowsCodePairV1 => ensure!( + self.stop_set == [Service::WindowsAgent, Service::WindowsHelper], + "HANDOFF_UNSUPPORTED_SERVICE_SET" + ), + } + Ok(()) + } + + pub fn bytes(&self) -> Result> { + self.validate()?; + let bytes = serde_json::to_vec(self)?; + ensure!(bytes.len() <= MAX_RECORD_BYTES, "HANDOFF_TOO_LARGE"); + Ok(bytes) + } +} + +/// Concrete process birth, not an unqualified PID or a service's Running flag. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Process { + pub pid: u32, + pub birth: u64, + pub image_sha256: String, +} + +impl Process { + fn validate(&self, expected_image: &str) -> Result<()> { + ensure!( + self.pid > 0 && self.birth > 0 && self.image_sha256 == expected_image, + "HANDOFF_PROCESS_BINDING" + ); + Ok(()) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct StartedService { + pub service: Service, + pub process: Process, +} + +/// The server signs evidence only. `ready` MUST be false while the original +/// handoff remains inflight; this receipt is never an ExecutionPermit. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct HealthReceipt { + pub schema_version: u32, + pub handoff_sha256: String, + pub owner_nonce: Uuid, + pub boot_id: Uuid, + pub helper_journal_id: Uuid, + pub agent_journal_id: Uuid, + pub connection_generation: u64, + pub service_processes: Vec, + pub ledger_identity_sha256: String, + pub signed_sync_decision_id: Uuid, + pub signed_sync_request_sha256: String, + pub signed_sync_response_sha256: String, + pub signed_sync_applied_at: u64, + pub ready: bool, + pub inventory_message_id: Uuid, + pub inventory_received_at: u64, + pub inventory_ack_sha256: String, + pub issued_at: u64, + pub valid_until: u64, +} + +/// Already decoded, bounded input; a network adapter must also bound encoding. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SignedHealth { + pub payload: Vec, + pub signature: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "phase", rename_all = "snake_case", deny_unknown_fields)] +pub enum Evidence { + StopIntent, + AllStopped { + observation_sha256: String, + }, + UpdaterOwnsLedger { + process: Process, + ledger_identity_sha256: String, + }, + ReplaceIntent { + role: FileRole, + }, + Replaced { + role: FileRole, + observed_sha256: String, + }, + PairVerified { + pair: CodePair, + retained_state_sha256: String, + }, + /// This append must be flushed under the updater guard; the guard is then + /// dropped BEFORE starting the new helper, which reacquires the SAME lock. + LedgerReturnIntent, + ServicesStarted { + services: Vec, + ledger_identity_sha256: String, + observation_sha256: String, + }, + HealthVerified { + receipt: SignedHealth, + }, + /// Only the new helper's existing outcome-CAS may persist this outcome. + /// It must still reject any pre-existing definitive Unknown/outcome. + OutcomePersisted { + outcome_sha256: String, + }, + Unknown { + reason: UnknownReason, + }, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum UnknownReason { + OwnerLost, + BootChanged, + DeadlineExpired, + StopUncertain, + ReplaceUncertain, + StartUncertain, + StateChanged, + HealthUnproven, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Event { + pub schema_version: u32, + pub handoff_sha256: String, + pub sequence: u32, + pub previous_sha256: String, + pub observed_at: u64, + pub boot_id: Uuid, + pub evidence: Evidence, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Phase { + HandoffConsumed, + StopIntent, + AllStopped, + UpdaterOwnsLedger, + ReplaceIntent, + Replaced, + PairVerified, + LedgerReturnIntent, + ServicesStarted, + HealthVerified, + OutcomePersisted, + Unknown, +} + +/// Retained journal view. No method returns a start grant, ready flag, retry, +/// rollback or instruction to perform a service/file operation after a crash. +pub struct Journal { + handoff: Handoff, + handoff_hash: String, + head_hash: String, + count: u32, + phase: Phase, + replaced: usize, + observed_at: u64, + started: Option<(Vec, u64)>, + health_key: VerifyingKey, +} + +impl Journal { + /// The caller independently verifies this record against the ORIGINAL + /// consumed row/start witness, participant policy and retained state. + pub fn open(record: &[u8], health_public_key: [u8; 32]) -> Result { + let handoff: Handoff = canonical(record, MAX_RECORD_BYTES)?; + handoff.validate()?; + let health_key = VerifyingKey::from_bytes(&health_public_key)?; + ensure!(!health_key.is_weak(), "HANDOFF_WEAK_HEALTH_KEY"); + let handoff_hash = sha256(record); + Ok(Self { + observed_at: handoff.consumed_at, + handoff, + head_hash: handoff_hash.clone(), + handoff_hash, + count: 0, + phase: Phase::HandoffConsumed, + replaced: 0, + started: None, + health_key, + }) + } + + pub fn phase(&self) -> Phase { + self.phase + } + pub fn head_sha256(&self) -> &str { + &self.head_hash + } + pub fn handoff_sha256(&self) -> &str { + &self.handoff_hash + } + + /// Prepare exact bytes for a bounded append-only CAS transaction against + /// `head_sha256`. Returning bytes is NOT proof that this transaction ran. + pub fn prepare(&self, observed_at: u64, evidence: Evidence) -> Result> { + let event = Event { + schema_version: 1, + handoff_sha256: self.handoff_hash.clone(), + sequence: self.count + 1, + previous_sha256: self.head_hash.clone(), + observed_at, + boot_id: self.handoff.boot_id, + evidence, + }; + self.validate_event(&event)?; + let bytes = serde_json::to_vec(&event)?; + ensure!(bytes.len() <= MAX_EVENT_BYTES, "HANDOFF_EVENT_TOO_LARGE"); + Ok(bytes) + } + + /// Strict historical replay. The platform must check durable head/rowcount, + /// inode/FileID and original ledger lineage to detect omitted suffixes. + pub fn replay(&mut self, bytes: &[u8]) -> Result<()> { + let event: Event = canonical(bytes, MAX_EVENT_BYTES)?; + let next = self.validate_event(&event)?; + if matches!(event.evidence, Evidence::Replaced { .. }) { + self.replaced += 1; + } + if let Evidence::ServicesStarted { services, .. } = event.evidence { + self.started = Some((services, event.observed_at)); + } + self.phase = next; + self.observed_at = event.observed_at; + self.count = event.sequence; + self.head_hash = sha256(bytes); + Ok(()) + } + + fn validate_event(&self, event: &Event) -> Result { + ensure!( + event.schema_version == 1 + && event.handoff_sha256 == self.handoff_hash + && event.sequence == self.count + 1 + && (event.sequence as usize) <= MAX_EVENTS + && event.previous_sha256 == self.head_hash, + "HANDOFF_EVENT_CHAIN" + ); + ensure!( + !matches!(self.phase, Phase::Unknown | Phase::OutcomePersisted), + "HANDOFF_TERMINAL" + ); + ensure!( + event.boot_id == self.handoff.boot_id && event.observed_at >= self.observed_at, + "HANDOFF_BOOT_OR_CLOCK" + ); + if matches!(event.evidence, Evidence::Unknown { .. }) { + return Ok(Phase::Unknown); + } + ensure!( + event.observed_at < self.handoff.finish_before, + "HANDOFF_EXPIRED" + ); + let next = match (&self.phase, &event.evidence) { + (Phase::HandoffConsumed, Evidence::StopIntent) => Phase::StopIntent, + (Phase::StopIntent, Evidence::AllStopped { observation_sha256 }) => { + digest(observation_sha256)?; + Phase::AllStopped + } + ( + Phase::AllStopped, + Evidence::UpdaterOwnsLedger { + process, + ledger_identity_sha256, + }, + ) => { + process.validate(&self.handoff.updater_sha256)?; + ensure!( + ledger_identity_sha256 == &self.handoff.ledger_identity_sha256, + "HANDOFF_LEDGER_IDENTITY_CHANGED" + ); + Phase::UpdaterOwnsLedger + } + (Phase::UpdaterOwnsLedger | Phase::Replaced, Evidence::ReplaceIntent { role }) => { + ensure!( + self.handoff + .files + .get(self.replaced) + .is_some_and(|file| file.role == *role), + "HANDOFF_REPLACE_ORDER" + ); + Phase::ReplaceIntent + } + ( + Phase::ReplaceIntent, + Evidence::Replaced { + role, + observed_sha256, + }, + ) => { + ensure!( + self.handoff.files.get(self.replaced).is_some_and( + |file| file.role == *role && file.new_sha256 == *observed_sha256 + ), + "HANDOFF_REPLACEMENT_BINDING" + ); + Phase::Replaced + } + ( + Phase::Replaced, + Evidence::PairVerified { + pair, + retained_state_sha256, + }, + ) => { + ensure!( + self.replaced == self.handoff.files.len(), + "HANDOFF_PAIR_INCOMPLETE" + ); + ensure!( + pair == &self.handoff.target + && retained_state_sha256 == &self.handoff.retained_state_sha256, + "HANDOFF_PAIR_OR_STATE_CHANGED" + ); + Phase::PairVerified + } + (Phase::PairVerified, Evidence::LedgerReturnIntent) => Phase::LedgerReturnIntent, + ( + Phase::LedgerReturnIntent, + Evidence::ServicesStarted { + services, + ledger_identity_sha256, + observation_sha256, + }, + ) => { + ensure!( + ledger_identity_sha256 == &self.handoff.ledger_identity_sha256, + "HANDOFF_LEDGER_IDENTITY_CHANGED" + ); + let expected: Vec<_> = self + .handoff + .stop_set + .iter() + .copied() + .filter(|service| *service != 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" + ); + let image = + if matches!(service.service, Service::LinuxAgent | Service::WindowsAgent) { + &self.handoff.target.agent_sha256 + } else { + &self.handoff.target.helper_sha256 + }; + service.process.validate(image)?; + ensure!( + !services[..index] + .iter() + .any(|prior| prior.process.pid == service.process.pid), + "HANDOFF_PROCESS_REUSE" + ); + } + digest(observation_sha256)?; + Phase::ServicesStarted + } + (Phase::ServicesStarted, Evidence::HealthVerified { receipt }) => { + self.verify_health(receipt, event.observed_at)?; + Phase::HealthVerified + } + (Phase::HealthVerified, Evidence::OutcomePersisted { outcome_sha256 }) => { + digest(outcome_sha256)?; + Phase::OutcomePersisted + } + _ => anyhow::bail!("HANDOFF_PHASE_ORDER"), + }; + Ok(next) + } + + fn verify_health(&self, signed: &SignedHealth, at: u64) -> Result<()> { + let receipt: HealthReceipt = canonical(&signed.payload, 4096)?; + let signature = + Signature::from_slice(&signed.signature).context("HANDOFF_HEALTH_SIGNATURE_LENGTH")?; + let mut message = HEALTH_DOMAIN.to_vec(); + message.extend_from_slice(&signed.payload); + self.health_key + .verify_strict(&message, &signature) + .context("HANDOFF_HEALTH_SIGNATURE")?; + let (services, started_at) = self.started.as_ref().context("HANDOFF_START_MISSING")?; + ensure!( + receipt.schema_version == 1 + && receipt.handoff_sha256 == self.handoff_hash + && receipt.owner_nonce == self.handoff.owner_nonce + && receipt.boot_id == self.handoff.boot_id + && receipt.helper_journal_id == self.handoff.helper_journal_id + && receipt.agent_journal_id == self.handoff.agent_journal_id + && receipt.connection_generation > self.handoff.connection_generation + && receipt.service_processes == *services + && receipt.ledger_identity_sha256 == self.handoff.ledger_identity_sha256 + && !receipt.ready, + "HANDOFF_HEALTH_BINDING" + ); + ensure!( + !receipt.signed_sync_decision_id.is_nil() && !receipt.inventory_message_id.is_nil(), + "HANDOFF_HEALTH_ID" + ); + for hash in [ + &receipt.signed_sync_request_sha256, + &receipt.signed_sync_response_sha256, + &receipt.inventory_ack_sha256, + ] { + digest(hash)?; + } + ensure!( + receipt.signed_sync_applied_at >= *started_at + && receipt.inventory_received_at >= *started_at + && receipt.issued_at >= receipt.signed_sync_applied_at + && receipt.issued_at >= receipt.inventory_received_at + && receipt.issued_at <= at + && at < receipt.valid_until + && receipt.valid_until <= self.handoff.finish_before + && at.checked_sub(*started_at).is_some_and(|age| age < 180), + "HANDOFF_HEALTH_NOT_FRESH" + ); + Ok(()) + } +} + +pub fn sha256(bytes: &[u8]) -> String { + hex::encode(Sha256::digest(bytes)) +} + +fn digest(hash: &str) -> Result<()> { + ensure!( + hash.len() == 64 + && hash + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)), + "HANDOFF_DIGEST" + ); + Ok(()) +} + +fn canonical(bytes: &[u8], limit: usize) -> Result { + ensure!( + !bytes.is_empty() && bytes.len() <= limit, + "HANDOFF_BYTE_LIMIT" + ); + let value = serde_json::from_slice::(bytes)?; + ensure!(serde_json::to_vec(&value)? == bytes, "HANDOFF_NONCANONICAL"); + Ok(value) +} diff --git a/crates/updater-handoff/src/linux_full.rs b/crates/updater-handoff/src/linux_full.rs new file mode 100644 index 0000000..fe2506d --- /dev/null +++ b/crates/updater-handoff/src/linux_full.rs @@ -0,0 +1,309 @@ +//! Closed renderer for the existing Linux Full helper Config -> Policy -> +//! GeneralPin schema2. Definitions are deliberately a versioned snapshot until +//! integration can use the reviewed runtime types. No arbitrary JSON patch, +//! paths, key loading, permission migration, service operation or publication. + +use crate::{digest, sha256}; +use anyhow::{Result, ensure}; +use ed25519_dalek::VerifyingKey; +use serde::{Deserialize, Serialize}; +use serde_json::value::RawValue; +use uuid::Uuid; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Binding { + tenant_id: Uuid, + asset_id: Uuid, + agent_id: Uuid, + enrollment_generation: u64, + assignment_version: u64, + public_key_hex: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Identity { + tenant_id: Uuid, + asset_id: Uuid, + agent_id: Uuid, + enrollment_generation: u64, + assignment_version: u64, + signing_key_id: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +enum FullProfile { + #[serde(rename = "full_maintenance_v1")] + FullMaintenanceV1, +} + +#[derive(Clone, Debug, PartialEq, Eq, Deserialize)] +#[serde(deny_unknown_fields)] +struct Config { + profile: FullProfile, + binding: Binding, + #[serde(default)] + signing_key_file: Option, + agent_uid: u32, + socket_gid: u32, + socket: String, + state: String, + allowed_services: Vec, + allow_reboot: bool, + allow_root_scripts: bool, + allowed_script_profiles: Vec, + helper_binary_sha256: String, + /// Full Config forbids an APT provider; any non-null value is rejected. + #[serde(default)] + apt_provider: Option<()>, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Policy { + schema_version: u32, + profile: FullProfile, + identity: Identity, + allowed_services: Vec, + allow_root_scripts: bool, + allow_reboot: bool, + allowed_script_profiles: Vec, + helper_binary_sha256: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Pin { + schema_version: u32, + profile: FullProfile, + identity: Identity, + policy_sha256: String, + helper_binary_sha256: String, +} + +/// Only value spans of these named TOP-LEVEL fields are selected. Full typed +/// decoding first rejects unknown/duplicate fields, including nested objects. +#[derive(Deserialize)] +struct ConfigSpans<'a> { + #[serde(borrow)] + helper_binary_sha256: &'a RawValue, +} +#[derive(Deserialize)] +struct PinSpans<'a> { + #[serde(borrow)] + policy_sha256: &'a RawValue, + #[serde(borrow)] + helper_binary_sha256: &'a RawValue, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct LinuxFullTransitionProof { + pub schema_version: u32, + pub old_config_sha256: String, + pub new_config_sha256: String, + pub old_pin_sha256: String, + pub new_pin_sha256: String, + pub old_policy_sha256: String, + pub new_policy_sha256: String, + pub old_helper_sha256: String, + pub new_helper_sha256: String, + pub effective_signing_key_id: String, +} + +/// Private construction preserves correspondence between rendered bytes and +/// their fixed proof. Wire proof fields remain untrusted once transported. +pub struct LinuxFullTransition { + proof: LinuxFullTransitionProof, + new_config: Vec, + new_pin: Vec, +} + +impl LinuxFullTransition { + pub fn proof(&self) -> &LinuxFullTransitionProof { + &self.proof + } + pub fn new_config_bytes(&self) -> &[u8] { + &self.new_config + } + pub fn new_pin_bytes(&self) -> &[u8] { + &self.new_pin + } + pub fn sha256(&self) -> Result { + Ok(sha256(&serde_json::to_vec(&self.proof)?)) + } +} + +/// The adapter must compare old bytes to the exact protected deployed files, +/// bind BOTH returned raw-file hashes in the immutable job before approval, +/// and independently recheck the same closed transition before/after swap. +/// General/APT bytes and central rights/scopes are never rendered or changed. +/// `provisioned_signing_key` must be independently authenticated from the +/// already provisioned public-key record/pinned identity by the adapter. +/// Parsing a VerifyingKey alone does NOT authenticate its provisioning. +/// This pure function never opens `signing_key_file` or modifies inline keys. +pub fn render_linux_full( + config_bytes: &[u8], + pin_bytes: &[u8], + target_helper: &str, + provisioned_signing_key: &VerifyingKey, +) -> Result { + ensure!( + !config_bytes.is_empty() + && config_bytes.len() <= 16384 + && !pin_bytes.is_empty() + && pin_bytes.len() <= 8192, + "FULL_RENDER_LIMIT" + ); + digest(target_helper)?; + let config: Config = serde_json::from_slice(config_bytes)?; + let pin: Pin = serde_json::from_slice(pin_bytes)?; + digest(&config.helper_binary_sha256)?; + ensure!( + !provisioned_signing_key.is_weak(), + "FULL_RENDER_WEAK_SIGNING_KEY" + ); + let effective_public_key = hex::encode(provisioned_signing_key.as_bytes()); + if let Some(path) = &config.signing_key_file { + ensure!(path.starts_with('/'), "FULL_RENDER_KEY_PATH_ABSOLUTE"); + ensure!( + config.binding.public_key_hex.is_empty() + || config.binding.public_key_hex == effective_public_key, + "FULL_RENDER_PROVISIONED_KEY_MISMATCH" + ); + } else { + ensure!( + config.binding.public_key_hex == effective_public_key, + "FULL_RENDER_INLINE_KEY_REQUIRED" + ); + } + ensure!( + config.helper_binary_sha256 != target_helper, + "FULL_RENDER_SAME_IMAGE" + ); + ensure!( + !config.binding.tenant_id.is_nil() + && !config.binding.asset_id.is_nil() + && !config.binding.agent_id.is_nil() + && config.binding.enrollment_generation > 0 + && config.binding.assignment_version > 0, + "FULL_RENDER_IDENTITY" + ); + ensure!( + config.allowed_services.is_empty() + && !config.allow_reboot + && config.allow_root_scripts + && config.allowed_script_profiles == [FullProfile::FullMaintenanceV1] + && config.apt_provider.is_none() + && config.state == "/var/lib/rmm-helper" + && config.socket.starts_with('/') + && config.socket != "/run/rmm-apt-helper/helper.sock" + && config.agent_uid > 0 + && config.socket_gid > 0, + "FULL_RENDER_PROFILE" + ); + let identity = Identity { + tenant_id: config.binding.tenant_id, + asset_id: config.binding.asset_id, + agent_id: config.binding.agent_id, + enrollment_generation: config.binding.enrollment_generation, + assignment_version: config.binding.assignment_version, + signing_key_id: sha256(provisioned_signing_key.as_bytes()), + }; + let mut policy = Policy { + schema_version: 2, + profile: FullProfile::FullMaintenanceV1, + identity, + allowed_services: config.allowed_services.clone(), + allow_root_scripts: config.allow_root_scripts, + allow_reboot: config.allow_reboot, + allowed_script_profiles: config.allowed_script_profiles.clone(), + helper_binary_sha256: config.helper_binary_sha256.clone(), + }; + let old_policy_sha256 = sha256(&serde_json::to_vec(&policy)?); + ensure!( + pin.schema_version == 2 + && pin.identity == policy.identity + && pin.helper_binary_sha256 == config.helper_binary_sha256 + && pin.policy_sha256 == old_policy_sha256, + "FULL_RENDER_PIN_BINDING" + ); + policy.helper_binary_sha256 = target_helper.into(); + let new_policy_sha256 = sha256(&serde_json::to_vec(&policy)?); + let config_spans: ConfigSpans<'_> = serde_json::from_slice(config_bytes)?; + let pin_spans: PinSpans<'_> = serde_json::from_slice(pin_bytes)?; + let new_config = replace_spans( + config_bytes, + vec![(config_spans.helper_binary_sha256, target_helper)], + )?; + let new_pin = replace_spans( + pin_bytes, + vec![ + (pin_spans.helper_binary_sha256, target_helper), + (pin_spans.policy_sha256, &new_policy_sha256), + ], + )?; + let rendered_config: Config = serde_json::from_slice(&new_config)?; + let rendered_pin: Pin = serde_json::from_slice(&new_pin)?; + let mut expected_config = config.clone(); + expected_config.helper_binary_sha256 = target_helper.into(); + let mut expected_pin = pin; + expected_pin.helper_binary_sha256 = target_helper.into(); + expected_pin.policy_sha256.clone_from(&new_policy_sha256); + ensure!( + rendered_config == expected_config && rendered_pin == expected_pin, + "FULL_RENDER_UNEXPECTED_CHANGE" + ); + Ok(LinuxFullTransition { + proof: LinuxFullTransitionProof { + schema_version: 1, + old_config_sha256: sha256(config_bytes), + new_config_sha256: sha256(&new_config), + old_pin_sha256: sha256(pin_bytes), + new_pin_sha256: sha256(&new_pin), + old_policy_sha256, + new_policy_sha256, + old_helper_sha256: config.helper_binary_sha256, + new_helper_sha256: target_helper.into(), + effective_signing_key_id: sha256(provisioned_signing_key.as_bytes()), + }, + new_config, + new_pin, + }) +} + +fn replace_spans(bytes: &[u8], values: Vec<(&RawValue, &str)>) -> Result> { + let mut spans = Vec::new(); + for (raw, replacement) in values { + let raw = raw.get(); + let start = (raw.as_ptr() as usize) + .checked_sub(bytes.as_ptr() as usize) + .ok_or_else(|| anyhow::anyhow!("FULL_RENDER_SPAN"))?; + let end = start + .checked_add(raw.len()) + .ok_or_else(|| anyhow::anyhow!("FULL_RENDER_SPAN"))?; + ensure!( + bytes.get(start..end) == Some(raw.as_bytes()) + && raw.len() == 66 + && raw.starts_with('"') + && raw.ends_with('"'), + "FULL_RENDER_HASH_ENCODING" + ); + digest(&raw[1..65])?; + spans.push((start, end, format!("\"{replacement}\""))); + } + spans.sort_by_key(|span| span.0); + ensure!( + spans.windows(2).all(|p| p[0].1 <= p[1].0), + "FULL_RENDER_SPAN_OVERLAP" + ); + let mut rendered = Vec::with_capacity(bytes.len()); + let mut cursor = 0; + for (start, end, replacement) in spans { + rendered.extend_from_slice(&bytes[cursor..start]); + rendered.extend_from_slice(replacement.as_bytes()); + cursor = end; + } + rendered.extend_from_slice(&bytes[cursor..]); + Ok(rendered) +} diff --git a/crates/updater-handoff/tests/handoff_contract.rs b/crates/updater-handoff/tests/handoff_contract.rs new file mode 100644 index 0000000..c3eacb7 --- /dev/null +++ b/crates/updater-handoff/tests/handoff_contract.rs @@ -0,0 +1,639 @@ +use ed25519_dalek::{Signer, SigningKey}; +use rmm_updater_handoff::*; +use serde_json::{Value, json}; +use uuid::Uuid; + +fn id(n: u128) -> Uuid { + Uuid::from_u128(n) +} +fn h(n: u8) -> String { + format!("{n:02x}").repeat(32) +} +fn process(pid: u32, image: &str) -> Process { + Process { + pid, + birth: u64::from(pid) + 1000, + image_sha256: image.into(), + } +} +fn handoff() -> Handoff { + Handoff { + schema_version: 1, + attempt: AttemptBinding { + tenant_id: id(1), + asset_id: id(2), + agent_id: id(3), + enrollment_generation: 1, + assignment_version: 2, + plan_id: id(4), + plan_sha256: h(1), + job_id: id(5), + attempt_id: id(6), + job_payload_sha256: h(2), + grant_id: id(7), + authorization_id: id(8), + original_request_sha256: h(3), + original_start_witness_sha256: h(4), + }, + agent_journal_id: id(9), + helper_journal_id: id(10), + helper_checkpoint: 7, + previous_decision_id: id(11), + boot_id: id(12), + connection_generation: 20, + owner_nonce: id(13), + updater_sha256: h(5), + updater_policy_sha256: h(6), + predecessor_record_sha256: h(7), + retained_state_sha256: h(8), + ledger_identity_sha256: h(22), + staged_files_sha256: h(9), + predecessor: CodePair { + manifest_sha256: h(10), + agent_sha256: h(11), + helper_sha256: h(12), + pin_sha256: h(13), + }, + target: CodePair { + manifest_sha256: h(14), + agent_sha256: h(15), + helper_sha256: h(16), + pin_sha256: h(17), + }, + pin_transition: PinTransition::LinuxGeneralFullV1, + pin_transition_sha256: h(18), + files: vec![ + FileTransition { + role: FileRole::AgentBinary, + old_sha256: h(11), + new_sha256: h(15), + }, + FileTransition { + role: FileRole::HelperBinary, + old_sha256: h(12), + new_sha256: h(16), + }, + FileTransition { + role: FileRole::LinuxFullConfig, + old_sha256: h(19), + new_sha256: h(20), + }, + FileTransition { + role: FileRole::LinuxFullPin, + old_sha256: h(13), + new_sha256: h(17), + }, + ], + stop_set: vec![ + Service::LinuxAgent, + Service::LinuxGeneralHelper, + Service::LinuxFullHelper, + ], + consumed_at: 100, + finish_before: 700, + } +} +fn key() -> SigningKey { + SigningKey::from_bytes(&[73; 32]) +} +fn open(handoff: &Handoff) -> Journal { + Journal::open(&handoff.bytes().unwrap(), key().verifying_key().to_bytes()).unwrap() +} +fn append(journal: &mut Journal, at: u64, evidence: Evidence) -> Vec { + let bytes = journal.prepare(at, evidence).unwrap(); + journal.replay(&bytes).unwrap(); + bytes +} +fn services(handoff: &Handoff) -> Vec { + handoff + .stop_set + .iter() + .filter(|s| **s != Service::LinuxAptHelper) + .enumerate() + .map(|(i, service)| StartedService { + service: *service, + process: process( + 50 + i as u32, + if *service == Service::LinuxAgent { + &handoff.target.agent_sha256 + } else { + &handoff.target.helper_sha256 + }, + ), + }) + .collect() +} +fn until_started(journal: &mut Journal, handoff: &Handoff) -> Vec> { + let mut events = vec![ + append(journal, 101, Evidence::StopIntent), + append( + journal, + 102, + Evidence::AllStopped { + observation_sha256: h(21), + }, + ), + append( + journal, + 103, + Evidence::UpdaterOwnsLedger { + process: process(40, &handoff.updater_sha256), + ledger_identity_sha256: h(22), + }, + ), + ]; + for file in &handoff.files { + events.push(append( + journal, + 104, + Evidence::ReplaceIntent { role: file.role }, + )); + events.push(append( + journal, + 104, + Evidence::Replaced { + role: file.role, + observed_sha256: file.new_sha256.clone(), + }, + )); + } + events.push(append( + journal, + 105, + Evidence::PairVerified { + pair: handoff.target.clone(), + retained_state_sha256: handoff.retained_state_sha256.clone(), + }, + )); + events.push(append(journal, 106, Evidence::LedgerReturnIntent)); + events.push(append( + journal, + 107, + Evidence::ServicesStarted { + services: services(handoff), + ledger_identity_sha256: h(22), + observation_sha256: h(23), + }, + )); + events +} +fn receipt(journal: &Journal, handoff: &Handoff) -> HealthReceipt { + HealthReceipt { + schema_version: 1, + handoff_sha256: journal.handoff_sha256().into(), + owner_nonce: handoff.owner_nonce, + boot_id: handoff.boot_id, + helper_journal_id: handoff.helper_journal_id, + agent_journal_id: handoff.agent_journal_id, + connection_generation: 21, + service_processes: services(handoff), + ledger_identity_sha256: h(22), + signed_sync_decision_id: id(14), + signed_sync_request_sha256: h(24), + signed_sync_response_sha256: h(25), + signed_sync_applied_at: 108, + ready: false, + inventory_message_id: id(15), + inventory_received_at: 108, + inventory_ack_sha256: h(26), + issued_at: 109, + valid_until: 200, + } +} +fn signed(receipt: &HealthReceipt, domain: &[u8], key: &SigningKey) -> SignedHealth { + let payload = serde_json::to_vec(receipt).unwrap(); + let mut bytes = domain.to_vec(); + bytes.extend_from_slice(&payload); + SignedHealth { + payload, + signature: key.sign(&bytes).to_bytes().to_vec(), + } +} + +#[test] +fn full_linux_three_service_handoff_replays_exactly_sixteen_events() { + let handoff = handoff(); + 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_EVENTS); + assert_eq!(journal.phase(), Phase::OutcomePersisted); + let mut reopened = open(&handoff); + for event in events { + reopened.replay(&event).unwrap(); + } + assert_eq!(journal.head_sha256(), reopened.head_sha256()); + assert_eq!(reopened.phase(), Phase::OutcomePersisted); + assert!(reopened.prepare(112, Evidence::StopIntent).is_err()); +} + +#[test] +fn no_ownership_before_stop_no_partial_pair_no_start_before_return() { + let handoff = handoff(); + let mut journal = open(&handoff); + assert!( + journal + .prepare( + 101, + Evidence::UpdaterOwnsLedger { + process: process(40, &handoff.updater_sha256), + ledger_identity_sha256: h(22) + } + ) + .is_err() + ); + append(&mut journal, 101, Evidence::StopIntent); + append( + &mut journal, + 102, + Evidence::AllStopped { + observation_sha256: h(21), + }, + ); + append( + &mut journal, + 103, + Evidence::UpdaterOwnsLedger { + process: process(40, &handoff.updater_sha256), + ledger_identity_sha256: h(22), + }, + ); + assert!( + journal + .prepare( + 104, + Evidence::PairVerified { + pair: handoff.target.clone(), + retained_state_sha256: handoff.retained_state_sha256.clone() + } + ) + .is_err() + ); + assert!( + journal + .prepare( + 104, + Evidence::ReplaceIntent { + role: FileRole::HelperBinary + } + ) + .is_err() + ); + for file in &handoff.files { + append( + &mut journal, + 104, + Evidence::ReplaceIntent { role: file.role }, + ); + assert!( + journal + .prepare( + 104, + Evidence::Replaced { + role: file.role, + observed_sha256: h(99) + } + ) + .is_err() + ); + append( + &mut journal, + 104, + Evidence::Replaced { + role: file.role, + observed_sha256: file.new_sha256.clone(), + }, + ); + } + append( + &mut journal, + 105, + Evidence::PairVerified { + pair: handoff.target.clone(), + retained_state_sha256: handoff.retained_state_sha256.clone(), + }, + ); + assert!( + journal + .prepare( + 106, + Evidence::ServicesStarted { + services: services(&handoff), + ledger_identity_sha256: h(22), + observation_sha256: h(23) + } + ) + .is_err() + ); + append(&mut journal, 106, Evidence::LedgerReturnIntent); + let mut incomplete = services(&handoff); + incomplete.pop(); + assert!( + journal + .prepare( + 107, + Evidence::ServicesStarted { + services: incomplete, + ledger_identity_sha256: h(22), + observation_sha256: h(23) + } + ) + .is_err() + ); +} + +#[test] +fn event_chain_clock_limits_and_canonical_bytes_fail_closed() { + let handoff = handoff(); + let mut journal = open(&handoff); + let event = journal.prepare(101, Evidence::StopIntent).unwrap(); + for field in [ + "handoff_sha256", + "previous_sha256", + "boot_id", + "sequence", + "observed_at", + ] { + let mut value: Value = serde_json::from_slice(&event).unwrap(); + value[field] = match field { + "sequence" => json!(2), + "observed_at" => json!(99), + "boot_id" => json!(id(99)), + _ => json!(h(99)), + }; + let parsed: Event = serde_json::from_value(value).unwrap(); + assert!( + journal + .replay(&serde_json::to_vec(&parsed).unwrap()) + .is_err(), + "{field}" + ); + } + let mut whitespace = event.clone(); + whitespace.push(b' '); + assert!(journal.replay(&whitespace).is_err()); + assert!(journal.replay(&vec![b' '; MAX_EVENT_BYTES + 1]).is_err()); + assert!(journal.prepare(700, Evidence::StopIntent).is_err()); + journal.replay(&event).unwrap(); + assert!(journal.replay(&event).is_err()); + assert_eq!(journal.phase(), Phase::StopIntent); +} + +#[test] +fn health_is_domain_bound_fresh_evidence_and_never_opens_ready() { + let handoff = handoff(); + let mut journal = open(&handoff); + until_started(&mut journal, &handoff); + let baseline = receipt(&journal, &handoff); + for change in 0..11 { + let mut receipt = baseline.clone(); + match change { + 0 => receipt.ready = true, + 1 => receipt.owner_nonce = id(99), + 2 => receipt.boot_id = id(99), + 3 => receipt.helper_journal_id = id(99), + 4 => receipt.connection_generation = 20, + 5 => receipt.signed_sync_applied_at = 106, + 6 => receipt.inventory_received_at = 106, + 7 => receipt.service_processes[1].process.birth += 1, + 8 => receipt.valid_until = 110, + 9 => receipt.handoff_sha256 = h(99), + _ => receipt.issued_at = 111, + } + assert!( + journal + .prepare( + 110, + Evidence::HealthVerified { + receipt: signed(&receipt, HEALTH_DOMAIN, &key()) + } + ) + .is_err(), + "change {change}" + ); + } + assert!( + journal + .prepare( + 110, + Evidence::HealthVerified { + receipt: signed(&baseline, b"rmm.execution-permit.v1\0", &key()) + } + ) + .is_err() + ); + assert!( + journal + .prepare( + 110, + Evidence::HealthVerified { + receipt: signed(&baseline, HEALTH_DOMAIN, &SigningKey::from_bytes(&[74; 32])) + } + ) + .is_err() + ); + let mut late = baseline; + late.issued_at = 287; + late.valid_until = 400; + assert!( + journal + .prepare( + 287, + Evidence::HealthVerified { + receipt: signed(&late, HEALTH_DOMAIN, &key()) + } + ) + .is_err() + ); + append( + &mut journal, + 701, + Evidence::Unknown { + reason: UnknownReason::DeadlineExpired, + }, + ); + assert_eq!(journal.phase(), Phase::Unknown); + assert!( + journal + .prepare( + 702, + Evidence::HealthVerified { + receipt: signed(&late, HEALTH_DOMAIN, &key()) + } + ) + .is_err() + ); + assert!(journal.prepare(702, Evidence::StopIntent).is_err()); +} + +#[test] +fn closed_service_sets_reject_omitted_full_and_apt_restart() { + let mut handoff = handoff(); + handoff.stop_set.pop(); + assert!(handoff.bytes().is_err()); + handoff.stop_set.push(Service::LinuxFullHelper); + handoff.stop_set.push(Service::LinuxAptHelper); + let mut journal = open(&handoff); + until_started(&mut journal, &handoff); + assert_eq!(journal.phase(), Phase::ServicesStarted); + handoff.files[3].new_sha256 = h(99); + assert!(handoff.bytes().is_err()); +} + +fn full_files() -> (Vec, Vec) { + let public_key = hex::encode(key().verifying_key().as_bytes()); + let identity = json!({"tenant_id":id(1),"asset_id":id(2),"agent_id":id(3), + "enrollment_generation":1,"assignment_version":2,"signing_key_id":sha256(&hex::decode(&public_key).unwrap())}); + // Exact Policy codec order copied from runtime control::Policy schema2. + let policy = format!( + "{{\"schema_version\":2,\"profile\":\"full_maintenance_v1\",\"identity\":{{\"tenant_id\":\"{}\",\"asset_id\":\"{}\",\"agent_id\":\"{}\",\"enrollment_generation\":1,\"assignment_version\":2,\"signing_key_id\":\"{}\"}},\"allowed_services\":[],\"allow_root_scripts\":true,\"allow_reboot\":false,\"allowed_script_profiles\":[\"full_maintenance_v1\"],\"helper_binary_sha256\":\"{}\"}}", + id(1), + id(2), + id(3), + identity["signing_key_id"].as_str().unwrap(), + h(12) + ); + let config = json!({"profile":"full_maintenance_v1", "binding":{"tenant_id":id(1),"asset_id":id(2), + "agent_id":id(3),"enrollment_generation":1,"assignment_version":2,"public_key_hex":public_key}, + "signing_key_file":format!("/etc/rmm/{}/public-key.json",h(12)),"agent_uid":993,"socket_gid":984, + "socket":"/run/rmm-full-helper/helper.sock","state":"/var/lib/rmm-helper","allowed_services":[], + "allow_reboot":false,"allow_root_scripts":true,"allowed_script_profiles":["full_maintenance_v1"], + "helper_binary_sha256":h(12)}); + let pin = json!({"schema_version":2,"profile":"full_maintenance_v1","identity":identity, + "policy_sha256":sha256(policy.as_bytes()),"helper_binary_sha256":h(12)}); + ( + serde_json::to_vec_pretty(&config).unwrap(), + serde_json::to_vec_pretty(&pin).unwrap(), + ) +} + +fn render_linux_full( + config: &[u8], + pin: &[u8], + target: &str, +) -> anyhow::Result { + rmm_updater_handoff::render_linux_full(config, pin, target, &key().verifying_key()) +} + +#[test] +fn full_renderer_binds_provisioned_file_key_without_inserting_it_into_raw_config() { + let (inline_config, pin) = full_files(); + let mut file_config: Value = serde_json::from_slice(&inline_config).unwrap(); + file_config["binding"]["public_key_hex"] = json!(""); + let bytes = serde_json::to_vec_pretty(&file_config).unwrap(); + let transition = render_linux_full(&bytes, &pin, &h(16)).unwrap(); + let actual: Value = serde_json::from_slice(transition.new_config_bytes()).unwrap(); + assert_eq!(actual["binding"]["public_key_hex"], ""); + assert_eq!(actual["signing_key_file"], file_config["signing_key_file"]); + assert_eq!( + transition.proof().effective_signing_key_id, + sha256(key().verifying_key().as_bytes()) + ); + let expected = String::from_utf8(bytes.clone()).unwrap().replace( + &format!("\"helper_binary_sha256\": \"{}\"", h(12)), + &format!("\"helper_binary_sha256\": \"{}\"", h(16)), + ); + assert_eq!(transition.new_config_bytes(), expected.as_bytes()); + let inline = render_linux_full(&inline_config, &pin, &h(16)).unwrap(); + assert_eq!( + transition.proof().new_policy_sha256, + inline.proof().new_policy_sha256 + ); + assert_eq!(transition.new_pin_bytes(), inline.new_pin_bytes()); + let foreign_key = SigningKey::from_bytes(&[74; 32]).verifying_key(); + assert!(rmm_updater_handoff::render_linux_full(&bytes, &pin, &h(16), &foreign_key).is_err()); + assert!( + rmm_updater_handoff::render_linux_full(&inline_config, &pin, &h(16), &foreign_key).is_err() + ); + file_config + .as_object_mut() + .unwrap() + .remove("signing_key_file"); + assert!(render_linux_full(&serde_json::to_vec(&file_config).unwrap(), &pin, &h(16)).is_err()); + file_config["signing_key_file"] = json!("relative-key.json"); + assert!(render_linux_full(&serde_json::to_vec(&file_config).unwrap(), &pin, &h(16)).is_err()); +} + +#[test] +fn full_renderer_changes_only_named_hash_spans_preserving_all_other_raw_bytes() { + let (config, pin) = full_files(); + let transition = render_linux_full(&config, &pin, &h(16)).unwrap(); + assert_eq!(transition.proof().old_config_sha256, sha256(&config)); + let before: Value = serde_json::from_slice(&config).unwrap(); + let after: Value = serde_json::from_slice(transition.new_config_bytes()).unwrap(); + assert_eq!(before["signing_key_file"], after["signing_key_file"]); + assert!(after["signing_key_file"].as_str().unwrap().contains(&h(12))); + let needle = format!("\"helper_binary_sha256\": \"{}\"", h(12)); + let expected = String::from_utf8(config) + .unwrap() + .replace(&needle, &format!("\"helper_binary_sha256\": \"{}\"", h(16))); + assert_eq!(transition.new_config_bytes(), expected.as_bytes()); + let old_pin = String::from_utf8(pin).unwrap(); + let expected = old_pin + .replace(&needle, &format!("\"helper_binary_sha256\": \"{}\"", h(16))) + .replace( + &transition.proof().old_policy_sha256, + &transition.proof().new_policy_sha256, + ); + assert_eq!(transition.new_pin_bytes(), expected.as_bytes()); + assert_eq!(transition.sha256().unwrap().len(), 64); + assert!( + render_linux_full( + transition.new_config_bytes(), + transition.new_pin_bytes(), + &h(17) + ) + .is_ok() + ); +} + +#[test] +fn full_renderer_rejects_foreign_pins_unknown_duplicate_escaped_and_privilege_changes() { + let (config, pin) = full_files(); + for field in [ + "allow_reboot", + "allowed_services", + "allowed_script_profiles", + "profile", + "apt_provider", + ] { + let mut value: Value = serde_json::from_slice(&config).unwrap(); + value[field] = match field { + "allow_reboot" => json!(true), + "allowed_services" => json!(["other.service"]), + "allowed_script_profiles" => Value::Null, + "profile" => json!("general"), + _ => json!({}), + }; + assert!( + render_linux_full(&serde_json::to_vec(&value).unwrap(), &pin, &h(16)).is_err(), + "{field}" + ); + } + let mut foreign: Value = serde_json::from_slice(&pin).unwrap(); + foreign["identity"]["agent_id"] = json!(id(99)); + assert!(render_linux_full(&config, &serde_json::to_vec(&foreign).unwrap(), &h(16)).is_err()); + let mut unknown: Value = serde_json::from_slice(&config).unwrap(); + unknown["binding"]["new_field"] = json!(true); + assert!(render_linux_full(&serde_json::to_vec(&unknown).unwrap(), &pin, &h(16)).is_err()); + let text = String::from_utf8(config).unwrap(); + let duplicate = text.replacen("{", "{\"helper_binary_sha256\":\"0000000000000000000000000000000000000000000000000000000000000000\",",1); + assert!(render_linux_full(duplicate.as_bytes(), &pin, &h(16)).is_err()); + let escaped = text.replace( + &format!("\"helper_binary_sha256\": \"{}\"", h(12)), + &format!("\"helper_binary_sha256\": \"\\u0030{}\"", &h(12)[1..]), + ); + assert!(render_linux_full(escaped.as_bytes(), &pin, &h(16)).is_err()); +} diff --git a/docs/agent-updater-handoff.md b/docs/agent-updater-handoff.md new file mode 100644 index 0000000..2e09b43 --- /dev/null +++ b/docs/agent-updater-handoff.md @@ -0,0 +1,190 @@ +# Reviewstand: erhaltene Helper-/Updater-Übergabe + +2026-11-14. **Isolierter Quellvertrag, keine Produktnorm oder Applyruntime.** +Basis: vollständige Spezifikation1.19, vollständige1.20-/PD-Ergänzung des +Skriptconsole-Worktrees und [bisheriger Vorschlag](agent-updater-proposal.md). +Root hat den engen Kernel und den Fullrenderer zur Ausarbeitung beauftragt; +Runtimeintegration, Zielaktionen und Veröffentlichung erfolgen erst nach +dessen Koordination. Linux-first und die tatsächliche WebUI-Grenze gelten. + +Die neue Crate `rmm-updater-handoff` verändert weder den qualifizierten +Releaseverifier noch die beiden vorhandenen nativen Verifier-Abnahmerunner. +Sie enthält keinen Installer, Dateischreiber, Dienststart, IPC-Server, +Netzwerkclient, SQLiteadapter, Approver oder neuen Server-Journalslot. +Aus einem gültigen Handoff oder Healthreceipt entsteht keine Startberechtigung. + +## Konkreter Vorwärtsvertrag + +`Handoff` bindet ursprünglichen Tenant/Asset/Agent, beide Generationen, +Plan-/Job-/Versuchs-/Grant-/Authorization-IDs, exakte Originalrequest- und +Startzeugenhashes, beide vorhandenen Journal-IDs, Helpercheckpoint und letzten +signierten Entscheid, Boot, ursprüngliche Verbindungsgeneration, einmalige +Ownernonce, stabilen Updater-/Policyhash, Vorgängerrecord, erhaltene Zustands- +und Stagingzeugen sowie Vorgänger-/Zielcodepaar. Der Rendererbeleg und alle +benannten alten/neuen Dateihashes sind unveränderlicher Bestandteil. + +Die Helperintegration muss Verbrauch, bestehenden exakten Startzeugen und +Handoff **in derselben vorhandenen Ledgertransaktion** persistieren. Eine +zusätzliche Transaktion nach `ledger::begin_execution` wäre unzureichend: +ein Crash könnte einen Verbrauch ohne bestimmbaren Owner hinterlassen. +Jeder andere offene/Unknown-Versuch verweigert die Übergabe. Das Handoff +ersetzt weder den Originaljob/-grant noch dessen unabhängige Prüfung. + +Die Writergrenze ist ausdrücklich Bestandteil dieses Vertrags: Der alte +Helper persistiert auch den Stopintent vor der Übergabeantwort. Solange er +seinen lebenslangen Windowsguard hält, schreibt der Updater kein Event in +den gemeinsamen Ledger. Nach Stop/Guardübernahme kann der Updater All-stopped +und Ownership zusammen transaktional anhängen. Nach dauerhaftem Rückgabeintent +und tatsächlicher Guardabgabe stammen die weiteren Start-/Health-/Outcome- +Events ausschließlich vom neuen Helper unter dessen Guard. Der Updater +erhält nur die eng typisierte lokale Bridge; kein freies Ledger-Schreibrecht +parallel zum neuen Helper. Ein einheitlicher Ledger-/Lock-Inode-/FileID-Hash +ist vor Übergabe fest gebunden und wird bei Übernahme, neuem Servicepeer und +Health erneut verglichen; bloß ein gleichnamiger Dateipfad reicht nicht. + +Der begrenzte Journalcodec prüft kanonische Bytes, Hashvorgänger, monotone +Sequenz/Zeit und höchstens16Events. Für Linux Full sind dies genau: + +1. Stopintent, unabhängiger All-stopped-Zeuge, bestätigter Besitz des gleichen + Helperledgers durch den konkreten stabilen Updaterprozess. +2. Jeweils ein Intent und ein bestätigter Nachhash für Agent, Helper, + Fullconfig und Fullpin; keine neue Dienstgeneration vor vollständigem Paar. +3. Neues Code-/Pinpaar und erhaltener Zustandszeuge vollständig bestätigt. +4. Dauerhafter Ledger-Rückgabeintent unter gehaltenem Guard, danach Guard + tatsächlich abgeben; erst anschließend darf der neue Helper denselben + Guard erwerben und starten. +5. Konkrete neue Serviceprozesse mit Imagehash, PID und Prozessgeburt, + anschließend signierter Healthbeleg und ursprüngliches Outcome-CAS. + +Der Codec nimmt nur Beobachtungen entgegen. `prepare` liefert Bytes für ein +append-only CAS gegen den bestehenden Head, **keinen Haltbarkeitsnachweis**. +Der Plattformadapter muss Flush/Commit vor Wirkung, echte Service-/Peer- +und Guardbeobachtungen, Dateihandles/ACLs sowie ursprüngliche SQLrows und +Signaturen prüfen. Historischer Replay allein erkennt keinen abgeschnittenen +Suffix; er muss gegen den erhaltenen dauerhaften Head, Rowcount und +Ledger-/Inode-/FileID-/Kontrollkettenbeleg geprüft werden. Ein unbekannter +Stop/Teilwechsel/Start bleibt lesend zu diagnostizieren, kein erneuter Execute. +Ein expliziter Unknown ist im neuen Updatekernel terminal und wird durch +spätere Health nicht geheilt. Bestehende allgemeine Outcome-CAS-Regeln bleiben. + +## Fullhelper bleibt Teil des ersten Linux-Applyziels + +Die tatsächliche Zieltopologie hat General, Full und Agent aktiv. Daher ist +Full kein pauschaler Ausschluss. `linux_general_full_v1` erhält ein geschlossenes +Stopset Agent/General/Full; ein bereits installierter APT-Reader kann zusätzlich +als vierter Dienst im Stopset stehen, **nie im Startset**. Alle tatsächlich +installierten Shared-Ledger-Reader müssen vor Austausch erkannt und gestoppt +sein. Unbekannte Profile und ausgelassene Fullservices verweigern den Schnitt. +Agent/General/Full erhalten dieselbe neue Codepaargeneration vor Restart. +Die alte APT-Unqualifikation/-Deaktivierung bleibt bestehen; kein alter +Acceptancebeleg wird umgeschrieben oder auf die neue Helperdatei übertragen. +Zukünftiger APT-Start benötigt eine gesonderte passende Qualifikation. + +`render_linux_full` akzeptiert ausschließlich das bekannte Full-Configschema, +die daraus in fester Feldreihenfolge abgeleitete `control::Policy` Schema2 +und den zugehörigen `GeneralPin` Schema2. Alte Binär-/Policy-/Identitybindungen +werden vorher geprüft. Die Rendererdefinitionen sind eine explizite +Schemamomentaufnahme; Integration muss sie gegen die tatsächlichen Typen aus +dem1.20-Quellstand vergleichen, bevor sie Runtime werden. + +Der unabhängige Quellenreview fand einen echten Kompatibilitätsfehler des +ersten Entwurfs: Die aktuelle Full-Rawconfig enthält einen leeren Inlinekey +und einen `signing_key_file`-Pfad; die Runtime ergänzt den effektiven öffentlichen +Key vor der Policyhashbildung. Der reine Renderer erhält deshalb jetzt den +bereits provisionierten, **extern authentisierten** öffentlichen Signierkey +als expliziten Parameter. Er öffnet keine Datei. Bei vorhandenem absolutem +Keypfad darf der Raw-Inlinekey leer oder genau gleich sein; ohne Keypfad ist +der gleiche Inlinekey Pflicht. Effektive Policy und Pin werden wie in der +Runtime aus diesem Key abgeleitet; Raw-Inlinekey und Pfad bleiben unverändert. +Der Transitionbeleg bindet zusätzlich `effective_signing_key_id`. Ein bloß +geparstes `VerifyingKey`-Objekt authentisiert keine Provisionierung; der spätere +Adapter muss den Input unabhängig gegen die vorhandene geschützte Keydatei +und die gebundene öffentliche Identität prüfen. Eine neue lokale Vertragsprobe +belegt den Filekeyfall und gleiche Policy-/Pinbytes zum Inlinefall. Dies ist +weiterhin kein Lesen der realen Keydatei oder nativer Renderer-Nachweis. + +Der Renderer ändert nur benannte Top-Level-Wertspans: + +- Config: `helper_binary_sha256`. +- Pin: `helper_binary_sha256` und daraus exakt neu berechnetes `policy_sha256`. + +Alle anderen **rohen Config-/Pinbytes** bleiben erhalten, einschließlich +Formatierung, Identity, öffentlicher Schlüssel, Keypfad, UID/GID, Socket, +Statepfad und Rechtefelder. Er nutzt begrenzte typisierte Deserialisierung +und geborgte `RawValue`-Spans; keine globale Stringersetzung, kein JSONpatch. +Ein gleicher Hash innerhalb eines anderen Feldes bleibt erhalten. +Unbekannte/duplizierte Felder, abweichende Policy, zusätzliche Profile/Services, +fremde Identität und escaped Hashwerte werden verweigert. + +Der `LinuxFullTransition` bindet alte/neue Rawconfig-, Rawpin-, Policy- und +Helperhashes. Exakte Zielbytes samt Beleg müssen vor der WebUI-Genehmigung im +festen Plan aufgelöst und später unabhängig erneut geprüft werden. General- +und APT-Konfigurationen werden nicht gerendert. Die zentrale Fullscope wird +**nicht migriert**; künftige Fulljobs bleiben ohne neue konkrete Scopebindung +deny. Ein Codewechsel erteilt keine neuen Rechte. + +## Enger Health- und Syncanschluss + +Die eigene offene Updatezeile darf **keinen allgemeinen Readyzustand** erzeugen. +`HealthReceipt` ist separat domänengebunden (`rmm.agent-update-health.v1\0`), +mit strengem Ed25519 geprüft und an den gesamten Handoffhash, Ownernonce, +Boot, beide erhaltenen Journale, neue Verbindungsgeneration und sämtliche +konkreten neuen Agent-/Helperprozesse gebunden. Er enthält exakte Hashes des +tatsächlich angewandten SignedSync-Requests/-Responses, Decision-ID und +frisches Inventar samt ACK-Hash. `ready=true` wird ausdrücklich verweigert. +Sync und Inventarempfang müssen nach den bestätigten neuen Dienststarts +liegen. Health ist nur innerhalb180Sekunden gültig, Gesamtfrist höchstens600; +kein Receipt verlängert sie. Der öffentliche Verifikationsschlüssel wird +extern vertrauenswürdig provisioniert, nie aus dem Receipt übernommen. + +Noch vor Integration normativ zu bestätigen: + +| Anschluss | Erforderliche enge Änderung | +|---|---| +| `ledger::begin_execution` | Additive atomare Handoffanlage mit Originalverbrauch/-start im selben Ledger; keine Ersatzzeilen und kein Reset | +| Helper-/Agent-Startup | Nur exakt vollständiges, lebendes, gleichbootiges, fristgebundenes Updatehandoff als `inflight` erkennen; vorhandenes Unknown niemals umschreiben | +| `HelperSync`/Server-Sync | Typed Inflightdatensatz desselben Versuchs bei weiterhin geschlossenem Ready abgleichen; Originalkontrollkette erhalten | +| `ClientSync::confirm_helper` | Bestehende allgemeine Unresolved-Sperre erhalten; neuer expliziter read-only Updatekontrollpfad darf keine Startlease setzen | +| Lokales IPC | Eigener fest provisionierter Updaterparticipant mit Dienst-/UID/SID-/PID-/Geburts-/Imagebindung; Root/SYSTEM allein reicht nicht | +| Healthroute | Tatsächlich gespeicherter neuer Geräte-mTLS-/Inventory-/Syncbeleg; lokale aktuelle Peer-/Code-/Stateprüfung plus exaktes Receipt vergleichen | +| Finalisierung | Neuer Helper speichert ausschließlich das noch fehlende Originaloutcome per unverändertem CAS; danach bestehende Spiegelung/normaler Sync | + +Keine dieser Runtimeänderungen ist durch den isolierten Kernel implementiert. +Insbesondere ist ein Hash im Receipt kein Ersatz für die unabhängige Prüfung +des zugehörigen aktuellen lokalen Kontroll-/Inventarbelegs. Rotation/Revoke- +und Trustprovisionierung müssen den aktuellen sowie historischen Prüfkontext +beibehalten; der Kernel implementiert keinen neuen Trustdienst. + +Offen bleiben außerdem genehmigte typisierte Action/Plan/Grant-/UI-/MCP- +Integration, Updatekatalog und begrenzter eigener Streamingpfad, OSstaging, +stabiler Updaterbootstrap, Dienst-/Dateiaustausch, einmaliger zulässiger +Vorgängercode-Rollback, tatsächliche Linux-Abnahme und danach Windows. +Windows-Codepaar-/Settingsrenderer und Rollbackzustände sind hier **nicht** +implementiert. Der ursprüngliche reine Linux9-/Windows9-Verifiernachweis +bleibt unverändert; diese neuen Verträge haben noch keinen VM-Nachweis. + +## Tatsächlich ausgeführte lokale Prüfungen + +Offlinecontainer aus vorhandenem Image +`sha256:9a76ad3744ebfdddae96ca10001ce8291c1b332fb54c8df5eea0e8e999ac6fc6`. +Kein Server oder Agent auf dem Notebook gestartet, keine Ziel-/Policyaktion. + +```text +cargo check --manifest-path /src/Cargo.toml --offline -p rmm-updater-handoff +cargo fmt --manifest-path /src/Cargo.toml -p rmm-updater-handoff +cargo test --manifest-path /src/Cargo.toml --locked --offline -p rmm-updater-handoff --all-targets --release +cargo clippy --manifest-path /src/Cargo.toml --locked --offline -p rmm-updater-handoff --all-targets -- -D warnings +``` + +Bestanden: Check, Formatierung, Clippy ohne Warnungen und acht gezielte +Vertragsprüfungen ohne Skip. Diese prüfen den vollständigen16-Event-Fullpfad, +Originalketten-/Clock-/Limitgrenzen, Stop-/Lock-/Austausch-/Restartreihenfolge, +fehlende Fullprozesse/APT-Ausschluss, echte getrennte Healthsignaturen, +stale/fremde/ready-Health und terminalen Unknown sowie Rawbyteerhaltung, +extern gebundene File-/Inline-Signierkeys und feindliche Fullrenderer-Eingaben. +Nur lokale Vertragsnachweise; kein +Bootstrapping, dauerhafter SQLite-Commit, nativer Dienst-/Apply-/Rollback- +oder Produktionsnachweis. Der erste Formatbefehl scheiterte vor Cargo an +einem nicht überschriebenen Image-Entrypoint; mit `--entrypoint cargo` +anschließend tatsächlich ausgeführt. Keine Tests als Folge dieses Fehlers +erfunden oder Zielaktion wiederholt. diff --git a/docs/agent-updater-proposal.md b/docs/agent-updater-proposal.md index dcbf2a3..cb043a4 100644 --- a/docs/agent-updater-proposal.md +++ b/docs/agent-updater-proposal.md @@ -272,6 +272,15 @@ Serverintegration und tatsächlicher genehmigter Codewechsel bleiben offen. Kein Installer, keine Dienständerung, keine Freigabe und kein RMM-Job durch diesen reinen Prüfkern; der Subagent führte keine eigene VM-Aktion aus. +Zusätzlicher lokaler Reviewstand nach1.20: ein isolierter typisierter +Handoff-/Healthkernel und geschlossener Linux-Fullrenderer sind implementiert, +ohne den qualifizierten Verifier oder Runtime zu ändern. Die tatsächliche +Linuxzieltopologie General+Full+Agent wird ausdrücklich berücksichtigt; +Full bleibt kein pauschaler Ausschluss. Konkreter Vertrag, acht lokale +Prüfungen, notwendige Reviewentscheidungen und weiterhin fehlende Integration: +[Erhaltende Handoffgrenze](agent-updater-handoff.md). Dies ist keine neue +Produktnorm, Zielinstallation oder native Applyabnahme. + ## Nächster Integrationsschnitt zur Freigabe: fester Codepaar-Updatejob Die folgende Änderungsliste ist **nur Entwurf, nicht implementiert**. Sie From 1e89c4577f9055c49b6988fa091339232b112f26 Mon Sep 17 00:00:00 2001 From: Kevin Janssen Date: Sat, 14 Nov 2026 21:48:21 +0100 Subject: [PATCH 7/7] Add gated agent update planning, preserved handoff and Linux worker ports --- Cargo.lock | 45 + Cargo.toml | 2 +- Rust_RMM_Implementierungsspezifikation.md | 137 +- crates/agent-core/Cargo.toml | 4 + crates/agent-core/src/auth.rs | 5 + crates/agent-core/src/helper_reconcile.rs | 290 +- crates/agent-core/src/ledger.rs | 28 +- crates/agent-core/src/lib.rs | 1 + crates/agent-core/src/reconcile.rs | 204 +- crates/agent-core/src/update_handoff.rs | 1161 ++ crates/agent-core/tests/contracts.rs | 1 + crates/agent-core/tests/helper_reconcile.rs | 575 + crates/agent-core/tests/reconcile.rs | 4 + crates/agent-windows/src/helper_runtime.rs | 3 + crates/agent-windows/src/runtime.rs | 54 +- crates/agent/src/helper_sync.rs | 37 +- crates/agent/src/main.rs | 48 +- crates/agent/src/runtime_tests.rs | 1 + crates/agent/tests/reconcile.rs | 3 + crates/domain/Cargo.toml | 2 + crates/domain/examples/agent_update_golden.rs | 158 + crates/domain/src/agent_update.rs | 782 + .../domain/src/agent_update_provisioning.rs | 286 + crates/domain/src/inventory_document.rs | 92 + crates/domain/src/jobs.rs | 53 +- crates/domain/src/lib.rs | 2 + crates/domain/src/reconciliation.rs | 17 + crates/privileged-helper/src/apt/tests.rs | 1 + .../src/apt_configured_reconcile.rs | 1 + crates/privileged-helper/src/apt_reconcile.rs | 1 + crates/privileged-helper/src/tests.rs | 1 + crates/privileged-helper/tests/reconcile.rs | 2 + crates/protocol/src/jobs.rs | 3 + crates/server/Cargo.toml | 6 + crates/server/src/agent_service.rs | 6 +- crates/server/src/agent_update_health.rs | 595 + crates/server/src/agent_update_policy.rs | 180 + crates/server/src/agent_updates.rs | 873 + crates/server/src/catalog.rs | 4 + crates/server/src/job_gateway.rs | 31 +- crates/server/src/jobs.rs | 192 +- crates/server/src/main.rs | 7 + crates/server/src/mcp.rs | 19 +- crates/server/src/root_policy.rs | 3 + crates/server/src/synchronization.rs | 157 +- crates/server/src/update_artifact_store.rs | 285 + crates/updater-linux/Cargo.toml | 16 + crates/updater-linux/src/files.rs | 613 + crates/updater-linux/src/ipc.rs | 388 + crates/updater-linux/src/lib.rs | 90 + crates/updater-linux/src/process.rs | 239 + crates/updater-linux/src/services.rs | 552 + crates/updater-linux/src/tests.rs | 158 + crates/updater-worker/Cargo.toml | 24 + crates/updater-worker/src/clock.rs | 43 + crates/updater-worker/src/fence.rs | 119 + crates/updater-worker/src/files.rs | 197 + crates/updater-worker/src/full.rs | 185 + crates/updater-worker/src/ledger.rs | 335 + crates/updater-worker/src/lib.rs | 12 + crates/updater-worker/src/original.rs | 191 + crates/updater-worker/src/participants.rs | 78 + crates/updater-worker/src/retained.rs | 163 + crates/updater-worker/src/trust.rs | 428 + docs/agent-updater-handoff-linux-results.md | 59 + docs/agent-updater-handoff.md | 41 + docs/agent-updater-linux-native-results.md | 123 + docs/agent-updater-linux-port.md | 206 + docs/agent-updater-runtime-source.md | 62 + docs/agent-updater-server-console.md | 219 + docs/agent-updater-worker.md | 111 + docs/development.md | 21 +- docs/project-decisions.md | 46 +- migrations/0015_agent_update_catalog.sql | 49 + proto/agent.proto | 2 +- tests/agent_update/codec-golden.json | 13652 ++++++++++++++++ tests/agent_update/server-catalog.sql | 62 + web/src/agent-updates.test.tsx | 68 + web/src/agent-updates.ts | 124 + web/src/api.ts | 8 +- web/src/main.tsx | 64 +- web/src/safety.ts | 11 + 82 files changed, 25052 insertions(+), 69 deletions(-) create mode 100644 crates/agent-core/src/update_handoff.rs create mode 100644 crates/domain/examples/agent_update_golden.rs create mode 100644 crates/domain/src/agent_update.rs create mode 100644 crates/domain/src/agent_update_provisioning.rs create mode 100644 crates/server/src/agent_update_health.rs create mode 100644 crates/server/src/agent_update_policy.rs create mode 100644 crates/server/src/agent_updates.rs create mode 100644 crates/server/src/update_artifact_store.rs create mode 100644 crates/updater-linux/Cargo.toml create mode 100644 crates/updater-linux/src/files.rs create mode 100644 crates/updater-linux/src/ipc.rs create mode 100644 crates/updater-linux/src/lib.rs create mode 100644 crates/updater-linux/src/process.rs create mode 100644 crates/updater-linux/src/services.rs create mode 100644 crates/updater-linux/src/tests.rs create mode 100644 crates/updater-worker/Cargo.toml create mode 100644 crates/updater-worker/src/clock.rs create mode 100644 crates/updater-worker/src/fence.rs create mode 100644 crates/updater-worker/src/files.rs create mode 100644 crates/updater-worker/src/full.rs create mode 100644 crates/updater-worker/src/ledger.rs create mode 100644 crates/updater-worker/src/lib.rs create mode 100644 crates/updater-worker/src/original.rs create mode 100644 crates/updater-worker/src/participants.rs create mode 100644 crates/updater-worker/src/retained.rs create mode 100644 crates/updater-worker/src/trust.rs create mode 100644 docs/agent-updater-handoff-linux-results.md create mode 100644 docs/agent-updater-linux-native-results.md create mode 100644 docs/agent-updater-linux-port.md create mode 100644 docs/agent-updater-runtime-source.md create mode 100644 docs/agent-updater-server-console.md create mode 100644 docs/agent-updater-worker.md create mode 100644 migrations/0015_agent_update_catalog.sql create mode 100644 tests/agent_update/codec-golden.json create mode 100644 tests/agent_update/server-catalog.sql create mode 100644 web/src/agent-updates.test.tsx create mode 100644 web/src/agent-updates.ts diff --git a/Cargo.lock b/Cargo.lock index 908c03f..0a0fade 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2205,6 +2205,7 @@ name = "rmm-agent-core" version = "0.1.0" dependencies = [ "anyhow", + "base64 0.22.1", "chrono", "ed25519-dalek", "hex", @@ -2212,6 +2213,7 @@ dependencies = [ "prost", "rmm-domain", "rmm-protocol", + "rmm-updater-handoff", "rusqlite", "serde", "serde_json", @@ -2263,8 +2265,10 @@ dependencies = [ name = "rmm-domain" version = "0.1.0" dependencies = [ + "base64 0.22.1", "chrono", "hex", + "rmm-updater-handoff", "schemars", "serde", "serde_json", @@ -2338,9 +2342,12 @@ dependencies = [ "anyhow", "async-trait", "axum", + "base64 0.22.1", "chrono", + "futures-util", "hex", "hyper-util", + "libc", "openssl", "prost", "reqwest", @@ -2349,6 +2356,8 @@ dependencies = [ "rmm-oidc-auth", "rmm-persistence", "rmm-protocol", + "rmm-updater", + "rmm-updater-handoff", "rustls", "rustls-pemfile", "schemars", @@ -2390,6 +2399,42 @@ dependencies = [ "uuid", ] +[[package]] +name = "rmm-updater-linux" +version = "0.1.0" +dependencies = [ + "anyhow", + "hex", + "libc", + "rmm-domain", + "rmm-updater-handoff", + "serde", + "serde_json", + "sha2 0.10.9", + "uuid", +] + +[[package]] +name = "rmm-updater-worker" +version = "0.1.0" +dependencies = [ + "anyhow", + "base64 0.22.1", + "chrono", + "ed25519-dalek", + "hex", + "libc", + "rmm-agent-core", + "rmm-domain", + "rmm-updater", + "rmm-updater-handoff", + "rmm-updater-linux", + "rusqlite", + "serde", + "serde_json", + "uuid", +] + [[package]] name = "rsa" version = "0.9.10" diff --git a/Cargo.toml b/Cargo.toml index 5c3db0b..a253138 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"] +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"] [workspace.package] version = "0.1.0" diff --git a/Rust_RMM_Implementierungsspezifikation.md b/Rust_RMM_Implementierungsspezifikation.md index 7505da6..06d04c6 100644 --- a/Rust_RMM_Implementierungsspezifikation.md +++ b/Rust_RMM_Implementierungsspezifikation.md @@ -1,6 +1,6 @@ # Rust RMM: Architektur und Implementierungsspezifikation -Version 1.20 · 2026-11-14 · Sprache: Deutsch +Version 1.21 · 2026-11-14 · Sprache: Deutsch **Zweck:** Vollständige, eigenständig nutzbare Grundlage für die Implementierung einer mandantenfähigen Plattform zur Inventarisierung, Überwachung und Fernadministration von Kundengeräten durch eine Coding-KI und ein Entwicklungsteam. @@ -41,6 +41,12 @@ Dienst-/Paketprofile erhalten dadurch keine zusätzliche Erlaubnis. Batchstatus und abschließende begrenzte Rohbyteausgabe verwenden die bestehende Jobstrecke; interaktive PTY-/ConPTY-Sitzungen bleiben späterer eigener Umfang. +1.20 → 1.21 (2026-11-14): Auf ausdrücklichen Userwunsch wird ausschließlich +Agent-Selbstupdate ausM7 parallel vorgezogen. Signiertes festes Agent-/Helper- +Codepaar, eigener großer Artefaktpfad, WebUI-gebundener Updatejob und erhaltende +Helper-/Updater-Übergabe mit geschlossenem Inflight-/Healthkontrollpfad werden +präzisiert. Das ist keine native Applyabnahme oder Freigabe weitererM7-Themen. + ## Inhaltsverzeichnis - [0 Auftrag und verbindliche Produktanforderungen](#0-auftrag-und-verbindliche-produktanforderungen) @@ -130,6 +136,135 @@ Deploymentdaten, offene Konfiguration und reale Nachweise: ### 0.1 Auftrag an die implementierende KI +**Userentscheidung Version1.21 — signiertes Agent-Selbstupdate parallel:** +APT-/MSI-Paketfixtures sind kein Agent-Autoupdater. Der User zieht diesen engen +Teil ausM7 parallel vor; Restore, HA, Relay und weitere Betriebsreife werden +hierdurch nicht zusätzlich beauftragt. Jeder Aktivierungsversuch ist die neue +typisierte Aktion `update_agent` mit `fixed_code_pair_v1`, persistentem +`pending_approval` und tatsächlicher WebUI-Genehmigung gemäß0.1. Ersteller und +Freigeber brauchen aktuell `updates:apply` sowie getrennt `root:execute` oder +`system:execute`. Es gibt keine automatische Freigabe, zukünftiges `latest`, +Wildcardziele oder periodische Selbstaktivierung. Der Plan bindet exakten +release-signierten Manifestenvelope, Plattform, Vorgängerrecord/Codepaar, +Updater-/Policy-/Keyringhashes und Generation, getrennten Healthpublickey samt +Originalhash seines geschützten lokalen öffentlichen Pins, beide Artefakte, Pintransition, +festen Versuch, Fristen und einmalige erlaubte Vorgängercode-Rückkehr. + +Erstes Format: genau zwei Rohbinaries Agent und gemeinsamer Helper, getrennte +Update-/Job-/TLS-Schlüssel, kanonische domänengetrennte Ed25519-Releases. +Der stabile separat provisionierte Updater ist nicht selbst Updateartefakt. +Kein Archiv, Postinstall-Skript, freier Ziel-/Downloadpfad oder Hostreboot. +Bestehender256KiB-Paketartefaktstore bleibt unverändert; nur eigener +Updatekatalog/-stream erlaubt bis256MiB je gebundener Datei und512KiB je Chunk. +Geräte-mTLS, Tenant, genau genehmigter Job/Versuch, beide Manifestreferenzen und +aktuelle begrenzende Admission gelten auch beim Download. Beide Dateien müssen +vollständig gestreamt, auf exaktes EOF/Länge/Hash geprüft und geschützt gestaged +sein **vor** Aktivierungsverbrauch/Handoff; danach ist der Admissiondownload +kein Resume-, Health- oder neuer Startpfad. + +Reiner Metadatencheck beim Start und täglich ist passiv. Ein eigener +`InventorySnapshot`-Scope `agent.update`/Capability `agent.update/1` meldet +höchstens alle60s tatsächlichen Updatezustand; er stempelt kein Baseinventar +frisch und löst keinen CIM-/Vollinventarzwang aus. Qualifizierte +`agent.update.check/1` und `agent.update.apply/1` sind zusätzliche tatsächliche +Fähigkeiten, keine Folge des Schemas oder eines Builds. Fehlende Provisionierung +meldet `not_configured`, ohne scheinbaren Vorgänger/Preview. Planung benutzt +nur frische gespeicherte typisierte, Boot-/Generations-/SignedSync-gebundene +Beobachtung und genau eine lokal unabhängig gerenderte Kandidatenpreview. +Kein vom Modell gelieferter Vorgänger oder Pin. Zentrale/lokale Updatepolicy +bleiben getrennt und standardmäßig deny; Full-/SCM-/APT-Rechte werden nicht +übertragen. Linux berücksichtigt General, Full und Agent; vorhandener APT- +Reader gehört ins geschlossene Stopset und bleibt inaktiv/unqualifiziert. +Der Fullrenderer ändert ausschließlich benannte Helperhash-Wertspans und den +abgeleiteten Policyhash; alle übrigen rohen Config-/Pinbytes bleiben erhalten. +Bei filebasiertem Signierkey wird der bereits provisionierte öffentliche Key +extern authentisiert übergeben, ohne den leeren Raw-Inlinekey zu ersetzen. + +Vor dem ersten Apply ist ein gesonderter erhaltender Bootstrap auf ein bereits +Update-/Handoff-/Inflight-decoderkompatibles Agent-/General-/Fullpaar samt +stabilem Updater und qualifizierter Provisionierung erforderlich. **Das alte +1.20-Paar ist nach neuen Updatezeilen kein zulässiges Rollbackziel.** Erst die +kompatible tatsächlich qualifizierte Baseline erhält einen separat +release-signierten InstalledRecord/Floor. Manifest-/Protokoll-/Zustandsvertrag +und historische Journaldecoder müssen erhalten bleiben; keine Rückkehr zu +alten Decoderbytes durch einen Daten-/Ledger-/Generationreset. Aktive Version, +bestätigter Antirollbackfloor und angebotener Kandidat bleiben getrennt. +Ein zulässiger Code-Rollback verändert weder Datenzustand noch Floor; widerrufene +oder verbotene Vorgänger werden auch hierfür verweigert. + +Auf Linux ist ausschließlich der ausdrücklich provisionierte Fullhelper der +ursprüngliche Updateautorizer sowie Owner-/Healthguard. Der Generalhelper bleibt +während dieses Inflightfalls geschlossen; fehlende eigene Zuständigkeit darf den +Originalversuch nicht zu Unknown herabstufen. Gegenseitige Imageprüfung muss unter +den tatsächlichen Dienst-Capabilities funktionieren. Kein CAP_SYS_PTRACE-Zusatz +oder aufgeweichter Generaldienst als Umgehung einer nicht erlaubten /proc-Prüfung. + +Der alte unabhängig prüfende Helper schreibt Verbrauch, exakten bestehenden +Startzeugen, immutable Handoff, konkreten Delegationszeugen (stabiler +Updaterdienst/PID/Prozessgeburt/Image und ursprünglicher Helper) sowie Stopintent +in **einer Transaktion desselben erhaltenen Helperledgers**. Vorher kein Stop +oder Austausch. `ExecutionPermitPayload.agent_update_plan_id` wird ausschließlich +für diese Aktion zusätzlich signiert; bei allen anderen Aktionen fehlt das +Feld vollständig und erhält alte Grantbytes. Plan-ID/Hash, Job/Versuch/Grant, +Ownernonce, Boot, vorhandene Journal-/Kontrollketten und Dateiidentitäten bleiben +fest gebunden. Jeder andere offene/Unknown-Versuch verweigert Admission. + +Der Updater übernimmt den echten bestehenden Executorlock und denselben Ledger +nur während alle installierten Reader bestätigt gestoppt sind. Austausch ist +kein atomarer Bundleswap: jeder Code-/Pin-Schritt bekommt dauerhaften Intent und +belegte Nachlese. Vor neuem Helperstart wird der dauerhafte Rückgabeintent +committet und der Guard tatsächlich abgegeben. Danach schreibt der neue Helper +unter seinem Guard. Geschlossene native Unterintents und Nachbeobachtungen +liegen append-only mit FK am selben Originalhandoff, nicht in einem neuen +Verbrauchs-/Serverjournal. Rückgabeintent und genau einmal reservierte Startfolge +General→Full→Agent committen gemeinsam vor Lockabgabe; diese Zeilen erlauben +keinen späteren Dispatch oder Resume durch einen neu gestarteten Worker. +Bis `ServicesStarted` bleibt der konkrete lebende stabile +Updater logischer Owner, auch im Rückgabe-/Startupgap; danach sind die neuen +konkreten Helperprozesse nachzuweisen. Fehlende/lost Owner-, Boot-, Zeit- oder +Effektzeugen bleiben `unknown`. Read-only-Reconciliation ist weder Execute- +Resume noch allgemeines Unknown-Healing; ursprüngliche Signaturen, Zeilen, +Outcomes, PKI und DB-/Lock-Dateiidentitäten werden nicht ersetzt. + +Ein ausschließlich an diesen Originalversuch gebundener Inflightbeleg wird +additiv in `SyncAttempt.update_handoff_bytes` (Tag14) übertragen. Ein optionaler +signierter `AttemptDecision.update_inflight` bestätigt nur den exakten erhaltenen +Präfix bei `ready=false`, `helper_ready=false`, `unlock=false` und ohne Outcome. +Fachlicher Jobzustand bleibt `running`; sämtliche neuen Starts bleiben gesperrt. +Die gezielte read-only Helperquittung darf keine Startlease eröffnen. Bereits +persistiertes Unknown, fehlende Originale oder zurückgesetzte Präfixe dürfen +hierdurch nicht nachträglich zu Inflight werden. Kein weiterer ungebundener +Server-Journalslot wird eingeführt. + +Health benötigt lokal belegtes vollständiges Code-/Pinpaar, erhaltene Zustände, +konkrete neue Serviceprozesse und neu authentisierten Agentkontakt samt frisch +serverseitig gespeichertem Inventar/ACK und tatsächlich angewandtem SignedSync. +Der gesonderte signierte `rmm.agent-update-health.v1`-Beleg verwendet einen +separat provisionierten Healthsignierschlüssel; Jobsigner-/TLS-/Releasekeys sind +kein Fallback. Der vor Genehmigung gebundene öffentliche Healthpin wird lokal +unabhängig authentisiert und im ursprünglichen Handoffkontext erhalten. Der +Beleg ist evidence-only, +bindet Originalhandoff/Owner/Boot/Codepaar/Prozesse/Kontroll- und Inventarzeugen +und bleibt Ready=false. Er verlängert weder180sHealth- noch600sGesamtfrist und +reaktiviert keine Genehmigung. Der tatsächlich inventarbestätigende originale +SignedSyncResponse wird als Inventar-ACK gehasht; eine gespeicherte nächste +SignedSyncRequest-Runde muss beide lokal angewandten Vorentscheidungen belegen. +Die bestätigende Serverzeit ist nur obere Applyzeitgrenze; der Helper gleicht +seine eigenen erhaltenen Rawbytes und Applyzeit unabhängig ab. Nach Health +werden InstalledRecord und Floor gemeinsam als ein neuer geschützter Record +mit erhaltenem Vorgänger und einmaligen nativen Intents publiziert. Erst danach +darf der neue Helper das noch fehlende +Originaloutcome create-once per bestehendem CAS speichern; vorhandenes Unknown +wird nicht überschrieben. Vorhandene Spiegelung und normaler signierter Sync +übernehmen exakt diese Bytes und lösen die gleiche ursprüngliche Sperre. + +Dieser Abschnitt normiert den beauftragten engen Vertrag. Teilquellen/Units, +OS-Port, tatsächliche Kernel-/VMnachweise und noch fehlender ausgelieferter +Worker/Bootstrap/Apply sind getrennt in `docs/agent-updater-proposal.md`, +`docs/agent-updater-handoff.md` und `docs/agent-updater-linux-port.md` dokumentiert. +Keine Capability oder Native-/Produktionsfreigabe allein aus dieser Norm ableiten. + + **Userentscheidung Version1.20 — vollständige genehmigte Skriptkonsole zuerst:** Die KI darf über MCP gespeicherte Geräte-/Telemetriedaten im erlaubten Mandanten lesen, vollständige Shell-/PowerShell-Skripte schreiben und feste Aufträge als diff --git a/crates/agent-core/Cargo.toml b/crates/agent-core/Cargo.toml index 810367e..1ce161f 100644 --- a/crates/agent-core/Cargo.toml +++ b/crates/agent-core/Cargo.toml @@ -18,9 +18,13 @@ serde_json.workspace = true uuid.workspace = true rmm-domain = { path = "../domain" } rmm-protocol = { path = "../protocol" } +rmm-updater-handoff = { path = "../updater-handoff" } rusqlite = { version = "0.32.1", features = ["bundled"] } ed25519-dalek = "=2.2.0" +[dev-dependencies] +base64 = "=0.22.1" + [target.'cfg(unix)'.dependencies] openssl = { workspace = true, optional = true } diff --git a/crates/agent-core/src/auth.rs b/crates/agent-core/src/auth.rs index 736c965..ea4e9c2 100644 --- a/crates/agent-core/src/auth.rs +++ b/crates/agent-core/src/auth.rs @@ -121,6 +121,11 @@ impl Binding { && p.job_id == job.job_id && p.attempt_id == job.attempt_id && p.action == job.action.name() + && if matches!(job.action, rmm_domain::jobs::Action::UpdateAgent { .. }) { + p.agent_update_plan_id.is_some_and(|id| !id.is_nil()) + } else { + p.agent_update_plan_id.is_none() + } && p.execution_identity == job.execution_identity && p.max_runtime_seconds == job.max_runtime_seconds, "PERMIT_BINDING" diff --git a/crates/agent-core/src/helper_reconcile.rs b/crates/agent-core/src/helper_reconcile.rs index 43313d1..61c2943 100644 --- a/crates/agent-core/src/helper_reconcile.rs +++ b/crates/agent-core/src/helper_reconcile.rs @@ -26,6 +26,23 @@ pub trait BootSource { /// The guard remains held through snapshot/apply/admission/consumption/effect. pub trait ExecutorLedgerGuard { fn check(&self, db: &Connection) -> Result<()>; + /// Only the specifically provisioned update authorizer may judge a live + /// owner. General readers stay closed without changing the original attempt. + fn is_update_owner_authority(&self) -> bool { + false + } + /// Default-deny live owner attestation for the one typed update handoff. + /// Implement only after qualifying fixed service/PID/birth/image and the + /// original immutable delegation under this SAME actual executor guard. + fn check_update_owner( + &self, + _handoff: &rmm_updater_handoff::Handoff, + _delegation: &rmm_domain::agent_update::UpdateDelegation, + _phase: rmm_updater_handoff::Phase, + _events: &[rmm_updater_handoff::Event], + ) -> Result<()> { + anyhow::bail!("UPDATE_OWNER_NOT_QUALIFIED") + } } /// OS adapter contract, not an IPC assertion. The implementation must pin the /// live helper PID/creation and ledger/lock file identities, and independently @@ -120,6 +137,8 @@ pub struct LocalAttempt { pub outcome_bytes: Vec, /// Hash of the exact root-owned Request containing original job/permit bytes. pub original_request_sha256: String, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub update_handoff_bytes: Vec, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields)] @@ -238,6 +257,78 @@ impl HelperSync { self.verify_no_start_anchor(db, guard, &anchor, clock, boot)?; Ok(anchor) } + /// Consume exactly the approved update attempt and delegate its ORIGINAL + /// effect once. This is the only entry into update handoff persistence; + /// the independent live helper gate and all existing checks remain intact. + pub fn begin_update_handoff( + &mut self, + db: &mut Connection, + guard: &impl crate::update_handoff::UpdateAdmissionGuard, + generation: u64, + prepared: &crate::update_handoff::PreparedHandoff<'_>, + clock: &impl Clock, + boot: &impl BootSource, + ) -> Result<()> { + let crate::update_handoff::PreparedHandoff { + request, + handoff, + recorded_at, + .. + } = *prepared; + ensure!( + self.can_start(db, guard, generation, clock, boot), + "UPDATE_HELPER_READY_REQUIRED" + ); + let now = clock.now()?; + ensure!( + recorded_at <= now && now - recorded_at <= chrono::Duration::seconds(1), + "UPDATE_STALE_PREPARED_HANDOFF" + ); + let (job, permit) = self.binding.verify_with(request, now, &self.verifier)?; + ensure!( + matches!(job.action, Action::UpdateAgent { .. }) + && job.execution_identity == self.identity.as_str(), + "UPDATE_HELPER_IDENTITY" + ); + let meta = metadata(db)?; + let lease = self + .lease + .as_ref() + .context("UPDATE_HELPER_READY_REQUIRED")?; + ensure!( + handoff.helper_journal_id == meta.journal_id + && handoff.helper_checkpoint == meta.checkpoint + && Some(handoff.agent_journal_id) == meta.agent_journal + && Some(handoff.previous_decision_id) == meta.decision + && handoff.previous_decision_id == lease.decision_id + && handoff.connection_generation == generation + && handoff.boot_id == boot.current_boot()?, + "UPDATE_HANDOFF_SYNC_BINDING" + ); + let public_key = guard.health_public_key()?; + ensure!( + rmm_domain::agent_update::job_health_public_key(&job).map_err(anyhow::Error::msg)? + == public_key, + "UPDATE_HEALTH_PIN_BINDING" + ); + crate::update_handoff::consume(db, guard, &permit, prepared, public_key, &|tx| { + let fresh_now = clock.now()?; + ensure!( + self.can_start(tx, guard, generation, clock, boot) + && fresh_now >= recorded_at + && fresh_now - recorded_at <= chrono::Duration::seconds(1) + && boot.current_boot()? == handoff.boot_id, + "UPDATE_ADMISSION_CHANGED_BEFORE_CONSUMPTION" + ); + let (_, fresh) = self + .binding + .verify_with(request, fresh_now, &self.verifier)?; + ensure!(fresh == permit, "UPDATE_ORIGINAL_GRANT_CHANGED"); + Ok(()) + })?; + self.close(); + Ok(()) + } /// Deny-only: the grant may be expired, but no historical timestamp is ever /// passed to an execute verifier. Existing consumption is immutable. A new /// c/start/no-effect outcome is committed atomically and remains locked for @@ -410,7 +501,18 @@ impl HelperSync { ensure!(meta.checkpoint == highest, "HELPER_CHECKPOINT_ROLLBACK"); ensure!(generation >= meta.generation, "STALE_HELPER_CONNECTION"); validate_history(&tx, &self.binding, &meta, generation, &self.verifier)?; - let attempts = load_rows(&tx, &self.binding, true, self.identity, &self.verifier)?; + let attempts = load_rows( + &tx, + &self.binding, + true, + self.identity, + &self.verifier, + Some(LiveUpdateContext { + guard, + now, + boot: boot_id, + }), + )?; ensure!(attempts.len() <= 256, "HELPER_SYNC_CAPACITY"); let fingerprint = ledger_fingerprint(&tx)?; // Two independently gated profiles share one signed helper checkpoint. @@ -512,6 +614,14 @@ impl HelperSync { .as_ref() .context("FRESH_PROCESS_SNAPSHOT_REQUIRED")?; let decision = verify(&self.verifier, &self.binding, response, now)?; + ensure!( + !decision + .attempts + .iter() + .any(|d| d.update_inflight.is_some()) + || (!decision.ready && !decision.helper_ready), + "UPDATE_INFLIGHT_CANNOT_READY" + ); let request = RequestView::decode(raw_request)?; let current_boot = boot.current_boot()?; ensure!( @@ -571,7 +681,7 @@ impl HelperSync { if let Some(old)=tx.query_row("SELECT response,request,fingerprint FROM helper_sync_decisions WHERE decision_id=?1",[decision.decision_id.to_string()],|r|Ok((r.get::<_,Vec>(0)?,r.get::<_,Vec>(1)?,r.get::<_,String>(2)?))).optional()? { ensure!(old.0==serde_json::to_vec(response)? && old.1==raw_request && meta.decision==Some(decision.decision_id) && ledger_fingerprint(&tx)?==old.2,"HELPER_REPLAY_OR_LEDGER_CHANGED"); - let rows=load_rows(&tx,&self.binding,false, self.identity, &self.verifier)?; + let rows=load_rows(&tx,&self.binding,false, self.identity, &self.verifier,Some(LiveUpdateContext {guard,now,boot:current_boot}))?; let ready=decision.ready && decision.helper_ready && rows.iter().all(|row|definitive(row) && decision.attempts.iter().any(|d|d.job_id==row.job_id && d.attempt_id==row.attempt_id && d.outcome_state==row.state && d.outcome_sha256.as_deref()==Some(row.outcome_sha256.as_str()))) @@ -591,7 +701,18 @@ impl HelperSync { ledger_fingerprint(&tx)? == capture.fingerprint, "LOCAL_LEDGER_CHANGED_DURING_SYNC" ); - let rows = load_rows(&tx, &self.binding, false, self.identity, &self.verifier)?; + let rows = load_rows( + &tx, + &self.binding, + false, + self.identity, + &self.verifier, + Some(LiveUpdateContext { + guard, + now, + boot: current_boot, + }), + )?; ensure!( serde_json::to_vec(&rows)? == serde_json::to_vec(&capture.snapshot.attempts)?, "LOCAL_SNAPSHOT_CHANGED_DURING_SYNC" @@ -658,7 +779,18 @@ impl HelperSync { !decision.attempts.iter().any(|d| recovery_reason(&d.reason)), "SIGNED_LEDGER_RECOVERY_REQUIRED" ); - let after = load_rows(&tx, &self.binding, true, self.identity, &self.verifier)?; + let after = load_rows( + &tx, + &self.binding, + true, + self.identity, + &self.verifier, + Some(LiveUpdateContext { + guard, + now, + boot: current_boot, + }), + )?; let fingerprint = ledger_fingerprint(&tx)?; tx.execute("INSERT INTO helper_sync_decisions(decision_id,checkpoint,response,request,fingerprint) VALUES(?1,?2,?3,?4,?5)",params![decision.decision_id.to_string(),decision.helper_checkpoint,serde_json::to_vec(response)?,raw_request,fingerprint])?; tx.execute("UPDATE helper_sync_meta SET last_decision=?1,fault=COALESCE(fault,?2),agent_journal_id=?3,agent_checkpoint=?4 WHERE id=1",params![decision.decision_id.to_string(),fault,decision.journal_id.to_string(),decision.checkpoint])?; @@ -988,7 +1120,7 @@ pub fn verify_checkpoint_repair_history_with( previous_checkpoint = checkpoint; previous_agent_checkpoint = decision.checkpoint; } - let _ = load_rows(db, binding, false, identity, verifier)?; + let _ = load_rows(db, binding, false, identity, verifier, None)?; if let Some((r, e)) = links { verify_checkpoint_repair_links(db, binding, r, e, verifier)?; } @@ -1129,18 +1261,62 @@ fn ledger_rows(db: &Connection) -> Result> { .collect::>()?) } fn ledger_fingerprint(db: &Connection) -> Result { - Ok(hash(&serde_json::to_vec(&ledger_rows(db)?)?)) + let rows = ledger_rows(db)?; + 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 statement=db.prepare("SELECT h.grant_id,h.record_sha256,h.head_sha256,h.event_count,h.phase,d.witness_sha256 FROM agent_update_handoffs h JOIN agent_update_delegations d USING(grant_id) ORDER BY h.grant_id")?; + type UpdateRow = (String, String, String, u32, String, String); + let updates = statement + .query_map([], |r| { + Ok(( + r.get(0)?, + r.get(1)?, + r.get(2)?, + r.get(3)?, + r.get(4)?, + r.get(5)?, + )) + })? + .collect::>>()?; + if !updates.is_empty() { + let mut claims=db.prepare("SELECT grant_id,effect_key,claim,claim_sha256 FROM agent_update_native_claims ORDER BY grant_id,effect_key")?; + type NativeClaimRow = (String, String, Vec, String); + let claims = claims + .query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)))? + .collect::>>()?; + let mut observations=db.prepare("SELECT grant_id,effect_key,claim_sha256,observation_sha256,observed_at FROM agent_update_native_observations ORDER BY grant_id,effect_key")?; + type NativeObservationRow = (String, String, String, String, String); + let observations = observations + .query_map([], |r| { + Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?)) + })? + .collect::>>()?; + return Ok(hash(&serde_json::to_vec(&( + rows, + updates, + claims, + observations, + ))?)); + } + } + Ok(hash(&serde_json::to_vec(&rows)?)) } fn canonical(bytes: &[u8]) -> Result> { let o: ReconciledOutcome = serde_json::from_slice(bytes)?; Ok(canonical_outcome_bytes(&o)?) } +struct LiveUpdateContext<'a> { + guard: &'a dyn ExecutorLedgerGuard, + now: DateTime, + boot: Uuid, +} fn load_rows( db: &Connection, binding: &Binding, refresh: bool, identity: HelperIdentity, verifier: &impl Ed25519Verifier, + live: Option>, ) -> Result> { let mut result = Vec::new(); for (grant, agent, generation, job_id, attempt_id, finished, start, last) in ledger_rows(db)? { @@ -1169,15 +1345,66 @@ fn load_rows( if let (Some(a), Some(b)) = (&finished, &last) { ensure!(canonical(a)? == canonical(b)?, "LOCAL_OUTCOME_CONFLICT"); } - let outcome_bytes = last + let mut outcome_bytes = last .as_deref() .or(finished.as_deref()) .map(canonical) .transpose()? .unwrap_or_default(); ensure!(outcome_bytes.len() <= 512 * 1024, "LOCAL_OUTCOME_SIZE"); + let mut update_proof = + if outcome_bytes.is_empty() && matches!(job.action, Action::UpdateAgent { .. }) { + crate::update_handoff::proof_locked(db, permit.grant_id)? + } else { + None + }; + if let Some(proof) = &update_proof { + let key = rmm_domain::agent_update::job_health_public_key(&job) + .map_err(anyhow::Error::msg)?; + let (handoff, journal) = crate::update_handoff::verify_inflight_proof(proof, key)?; + if let Some(live) = &live { + ensure!( + live.guard.is_update_owner_authority(), + "UPDATE_OWNER_AUTHORITY_REQUIRED" + ); + let decoded = proof.decode().map_err(anyhow::Error::msg)?; + let events = decoded + .events + .iter() + .map(|raw| serde_json::from_slice::(raw)) + .collect::, _>>()?; + let reason = if live.boot != handoff.boot_id { + Some(rmm_updater_handoff::UnknownReason::BootChanged) + } else if u64::try_from(live.now.timestamp())? >= handoff.finish_before { + Some(rmm_updater_handoff::UnknownReason::DeadlineExpired) + } else if live + .guard + .check_update_owner(&handoff, &proof.delegation, journal.phase(), &events) + .is_err() + { + Some(rmm_updater_handoff::UnknownReason::OwnerLost) + } else { + None + }; + if let Some(reason) = reason { + ensure!(refresh, "UPDATE_OWNER_LOST_FRESH_CAPTURE_REQUIRED"); + outcome_bytes = crate::update_handoff::mark_unknown_locked( + db, + &permit, + u64::try_from(live.now.timestamp())?, + reason, + )?; + update_proof = None; + } + } + } let state = if outcome_bytes.is_empty() { - "unknown".to_string() + if update_proof.is_some() { + "running" + } else { + "unknown" + } + .to_string() } else { let o: ReconciledOutcome = serde_json::from_slice(&outcome_bytes)?; o.state @@ -1185,7 +1412,13 @@ fn load_rows( ensure!( matches!( state.as_str(), - "unknown" | "awaiting_reboot" | "succeeded" | "failed" | "cancelled" | "expired" + "unknown" + | "awaiting_reboot" + | "succeeded" + | "failed" + | "cancelled" + | "expired" + | "running" ), "UNKNOWN_LOCAL_STATE" ); @@ -1210,6 +1443,10 @@ fn load_rows( } } let mut row = LocalAttempt { + update_handoff_bytes: update_proof + .map(|p| p.bytes().map_err(anyhow::Error::msg)) + .transpose()? + .unwrap_or_default(), job_id: job.job_id, attempt_id: job.attempt_id, job_payload_hash: hash(&request.job_bytes), @@ -1280,12 +1517,37 @@ fn validate_summary(row: &LocalAttempt, a: &AttemptView) -> Result<()> { && a.revision >= row.revision && a.original_boot_id == row.original_boot_id.to_string() && a.outcome_sha256 == row.outcome_sha256 + && a.update_handoff_bytes == row.update_handoff_bytes && (a.outcome_bytes.is_empty() || a.outcome_bytes == row.outcome_bytes), "ROOT_SNAPSHOT_REQUEST_MISMATCH" ); Ok(()) } fn validate_decision(row: &LocalAttempt, a: &AttemptView, d: &AttemptDecision) -> Result<()> { + if !row.update_handoff_bytes.is_empty() { + let proof = + rmm_domain::agent_update::UpdateInflightProof::from_bytes(&row.update_handoff_bytes) + .map_err(anyhow::Error::msg)?; + let raw = proof.decode().map_err(anyhow::Error::msg)?; + let h: rmm_updater_handoff::Handoff = serde_json::from_slice(&raw.handoff_record)?; + let expected = rmm_domain::agent_update::UpdateInflightDecision { + handoff_sha256: proof.delegation.handoff_sha256.clone(), + delegation_sha256: hash(&serde_json::to_vec(&proof.delegation)?), + head_sha256: proof.head_sha256, + owner_nonce: h.owner_nonce, + finish_before: h.finish_before, + }; + ensure!( + d.update_inflight.as_ref() == Some(&expected) + && d.outcome_state == "running" + && !d.unlock + && d.outcome_bytes.is_empty() + && d.outcome_sha256.is_none(), + "UPDATE_SIGNED_INFLIGHT_BINDING" + ); + } else { + ensure!(d.update_inflight.is_none(), "UPDATE_INFLIGHT_NOT_LOCAL"); + } ensure!( d.job_payload_hash == row.job_payload_hash && d.grant_id == Some(row.grant_id) @@ -1389,6 +1651,7 @@ struct AttemptView { original_boot_id: String, outcome_sha256: String, outcome_bytes: Vec, + update_handoff_bytes: Vec, } enum Field<'a> { Number(u64), @@ -1517,7 +1780,7 @@ impl AttemptView { let mut seen = BTreeSet::new(); for (tag, value) in fields(raw)? { ensure!( - (1..=13).contains(&tag) && seen.insert(tag), + (1..=14).contains(&tag) && seen.insert(tag), "PROTOBUF_ATTEMPT_FIELD" ); match tag { @@ -1540,6 +1803,13 @@ impl AttemptView { r.outcome_bytes = bytes(value)?; ensure!(r.outcome_bytes.len() <= 512 * 1024, "SYNC_OUTCOME_SIZE"); } + 14 => { + r.update_handoff_bytes = bytes(value)?; + rmm_domain::agent_update::UpdateInflightProof::from_bytes( + &r.update_handoff_bytes, + ) + .map_err(anyhow::Error::msg)?; + } _ => unreachable!(), } } diff --git a/crates/agent-core/src/ledger.rs b/crates/agent-core/src/ledger.rs index 50d93b7..8ed7cff 100644 --- a/crates/agent-core/src/ledger.rs +++ b/crates/agent-core/src/ledger.rs @@ -42,7 +42,7 @@ pub fn consume(db: &mut rusqlite::Connection, p: &ExecutionPermitPayload) -> Res tx.commit()?; Ok(()) } -fn consume_in(db: &rusqlite::Connection, p: &ExecutionPermitPayload) -> Result<()> { +pub(crate) fn consume_in(db: &rusqlite::Connection, p: &ExecutionPermitPayload) -> Result<()> { let unresolved: i64 = db.query_row( "SELECT count(*) FROM consumed WHERE result IS NULL", [], @@ -182,7 +182,7 @@ pub(crate) fn record_no_start_in( persist_outcome_in(db, p, &outcome)?; Ok(outcome) } -fn validate_start_request(p: &ExecutionPermitPayload, request: &Request) -> Result<()> { +pub(crate) fn validate_start_request(p: &ExecutionPermitPayload, request: &Request) -> Result<()> { ensure!( request.job_bytes.len() <= 65536 && request.permit_bytes.len() <= 8192 @@ -227,7 +227,7 @@ pub fn persist_outcome( tx.commit()?; Ok(()) } -fn persist_outcome_in( +pub(crate) fn persist_outcome_in( db: &rusqlite::Connection, p: &ExecutionPermitPayload, outcome: &Outcome, @@ -310,6 +310,22 @@ pub fn save_start( previous_boot_id: Uuid, recorded_at: DateTime, ) -> Result<()> { + let bytes = start_witness_bytes(permit, request, previous_boot_id, recorded_at)?; + db.execute( + "INSERT INTO execution_evidence(grant_id,start) VALUES(?1,?2)", + rusqlite::params![permit.grant_id.to_string(), bytes], + )?; + Ok(()) +} + +/// Exact existing start codec, also used to bind the immutable update handoff +/// before atomic consumption. This does not persist or authorize anything. +pub fn start_witness_bytes( + _permit: &ExecutionPermitPayload, + request: &Request, + previous_boot_id: Uuid, + recorded_at: DateTime, +) -> Result> { let job: JobPayload = serde_json::from_slice(&request.job_bytes)?; ensure!(!previous_boot_id.is_nil(), "ORIGINAL_BOOT_MISSING"); let deadline = match job.action { @@ -322,9 +338,5 @@ pub fn save_start( let evidence = serde_json::json!({"previous_boot_id":previous_boot_id.to_string(), "reserved_at":recorded_at,"reconnect_deadline":deadline,"request":request, "reauthentication_required":true,"postconditions_passed":false}); - db.execute( - "INSERT INTO execution_evidence(grant_id,start) VALUES(?1,?2)", - rusqlite::params![permit.grant_id.to_string(), serde_json::to_vec(&evidence)?], - )?; - Ok(()) + Ok(serde_json::to_vec(&evidence)?) } diff --git a/crates/agent-core/src/lib.rs b/crates/agent-core/src/lib.rs index eaa79ca..fb3488f 100644 --- a/crates/agent-core/src/lib.rs +++ b/crates/agent-core/src/lib.rs @@ -8,3 +8,4 @@ pub mod helper_reconcile; pub mod jobs; pub mod ledger; pub mod reconcile; +pub mod update_handoff; diff --git a/crates/agent-core/src/reconcile.rs b/crates/agent-core/src/reconcile.rs index 204c85a..851cd46 100644 --- a/crates/agent-core/src/reconcile.rs +++ b/crates/agent-core/src/reconcile.rs @@ -142,6 +142,66 @@ impl ClientSync { gate.helper = None; Ok(()) } + /// Typed read-only ACK for exactly the own original update handoff. It + /// clears only the control delivery acknowledgement; both start flags stay + /// false and can_start remains false for ALL jobs, including this attempt. + pub fn confirm_update_helper(&mut self, snapshot: &HelperSnapshot) -> Result<()> { + let gate = self.gate.as_mut().context("NO_SIGNED_DECISION")?; + let expected = gate.helper.context("NO_HELPER_APPLY_PENDING")?; + ensure!( + !gate.ready + && !gate.helper_ready + && snapshot.journal_id == expected.0 + && snapshot.checkpoint == expected.1 + && snapshot.previous_decision_id == Some(expected.2), + "UPDATE_CONTROL_NOT_APPLIED" + ); + let updates: Vec<_> = snapshot + .attempts + .iter() + .filter(|a| !a.update_handoff_bytes.is_empty()) + .collect(); + ensure!(updates.len() == 1, "UPDATE_CONTROL_EXACTLY_ONE_REQUIRED"); + let local = updates[0]; + let requested = gate + .request + .attempts + .iter() + .find(|a| a.job_id == local.job_id && a.attempt_id == local.attempt_id) + .context("UPDATE_CONTROL_NOT_REQUESTED")?; + ensure!( + local.state == "running" + && local.consumption == "consumed" + && local.outcome_bytes.is_empty() + && local.update_handoff_bytes == requested.update_handoff_bytes + && local.grant_id == requested.grant_id + && local.job_payload_hash == requested.job_payload_hash, + "UPDATE_CONTROL_CHANGED" + ); + let decision: ReconcileDecisionPayload = + serde_json::from_slice(&gate.response.decision_bytes)?; + ensure!( + decision + .attempts + .iter() + .any(|d| d.job_id.to_string() == local.job_id + && d.attempt_id.to_string() == local.attempt_id + && d.update_inflight.is_some() + && !d.unlock), + "UPDATE_CONTROL_NOT_SIGNED" + ); + ensure!( + snapshot + .attempts + .iter() + .filter(|a| a.job_id != local.job_id || a.attempt_id != local.attempt_id) + .all(|a| terminal(&a.state) + || (a.state == "accepted" && a.consumption == "unconsumed")), + "UPDATE_OTHER_EFFECT_UNRESOLVED" + ); + gate.helper = None; + Ok(()) + } pub fn prepare( &mut self, db: &mut Connection, @@ -216,7 +276,7 @@ impl ClientSync { ingest_helper( &tx, ledger, - &self.binding, + (&self.binding, &self.verifier), &channel, h, now, @@ -230,7 +290,17 @@ impl ClientSync { )?; // A possibly started attempt is NEVER returned to accepted. Preserve // revisions and results; only ambiguous no-result states become unknown. - tx.execute("UPDATE job_attempts SET state='unknown',revision=revision+1 WHERE state IN ('requesting','running','verifying') AND NOT EXISTS(SELECT 1 FROM reconcile_results r WHERE r.job=job_attempts.job AND r.attempt=job_attempts.attempt AND r.revision>=job_attempts.revision)",[])?; + let inflight: Vec<_> = helper + .into_iter() + .flat_map(|h| h.attempts.iter()) + .filter(|a| !a.update_handoff_bytes.is_empty()) + .collect(); + ensure!(inflight.len() <= 1, "UPDATE_MULTIPLE_INFLIGHT"); + if let Some(update) = inflight.first() { + tx.execute("UPDATE job_attempts SET state='unknown',revision=revision+1 WHERE state IN ('requesting','running','verifying') AND NOT (job=?1 AND attempt=?2) AND NOT EXISTS(SELECT 1 FROM reconcile_results r WHERE r.job=job_attempts.job AND r.attempt=job_attempts.attempt AND r.revision>=job_attempts.revision)",params![update.job_id,update.attempt_id])?; + } else { + tx.execute("UPDATE job_attempts SET state='unknown',revision=revision+1 WHERE state IN ('requesting','running','verifying') AND NOT EXISTS(SELECT 1 FROM reconcile_results r WHERE r.job=job_attempts.job AND r.attempt=job_attempts.attempt AND r.revision>=job_attempts.revision)",[])?; + } let mut attempts = attempts(&tx, ledger, &self.binding)?; if let Some(h) = helper { merge_helper(&mut attempts, h)?; @@ -436,7 +506,8 @@ impl ClientSync { safe = false; continue; } - let outcome = validate_attempt(&job, &offer, local, d, channel.boot_id)?; + let outcome = + validate_attempt(&job, &offer, local, d, channel.boot_id, &self.binding, now)?; safe &= (d.outcome_state == "accepted" && local.consumption == "unconsumed" && local.grant_id.is_empty()) @@ -866,6 +937,7 @@ fn attempts(db: &Connection, ledger: &Connection, binding: &Binding) -> Result Result, identity: HelperIdentity, ) -> Result<()> { + let (binding, verifier) = binding_and_verifier; let mut statement = db.prepare("SELECT job,attempt,offer FROM job_attempts")?; for row in statement.query_map([], |r| { Ok(( @@ -952,6 +1025,65 @@ fn ingest_helper( "HELPER_ATTEMPT_BINDING" ); if h.outcome_bytes.is_empty() { + if !h.update_handoff_bytes.is_empty() { + let header = + validate_update_summary(binding, &job, &offer, h, channel.boot_id, now)?; + ensure!( + header.helper_journal_id == helper.journal_id + && header.agent_journal_id == metadata(db)?.journal_id, + "UPDATE_HELPER_JOURNAL_BINDING" + ); + let state: String = db.query_row( + "SELECT state FROM job_attempts WHERE job=?1 AND attempt=?2", + params![h.job_id, h.attempt_id], + |r| r.get(0), + )?; + ensure!( + matches!( + state.as_str(), + "accepted" | "requesting" | "running" | "verifying" + ), + "UPDATE_CANNOT_HEAL_UNKNOWN" + ); + type OriginalEvidence = ( + String, + u64, + String, + String, + Vec, + Option>, + Option>, + ); + let original:Option=ledger.query_row( + "SELECT c.agent,c.generation,c.job,c.attempt,e.start,e.outcome,c.result FROM execution_evidence e JOIN consumed c USING(grant_id) WHERE grant_id=?1",[&h.grant_id], + |r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?,r.get(4)?,r.get(5)?,r.get(6)?))).optional()?; + let (agent, generation, job_id, attempt_id, start, outcome, result) = + original.context("UPDATE_LOCAL_ORIGINAL_MISSING")?; + ensure!( + agent == binding.agent_id.to_string() + && generation == binding.enrollment_generation + && job_id == h.job_id + && attempt_id == h.attempt_id, + "UPDATE_LOCAL_CONSUMPTION_BINDING" + ); + ensure!( + outcome.is_none() && result.is_none(), + "UPDATE_CANNOT_REPLACE_OUTCOME" + ); + let start: serde_json::Value = serde_json::from_slice(&start)?; + let request: crate::auth::Request = + serde_json::from_value(start["request"].clone())?; + let permit: rmm_domain::jobs::ExecutionPermitPayload = + serde_json::from_slice(&request.permit_bytes)?; + binding.verify_with(&request, permit.not_before, verifier)?; + ensure!( + hash(&serde_json::to_vec(&request)?) == header.attempt.original_request_sha256 + && permit.grant_id == header.attempt.grant_id + && permit.agent_update_plan_id == Some(header.attempt.plan_id), + "UPDATE_LOCAL_ORIGINAL_CHANGED" + ); + db.execute("UPDATE job_attempts SET state='running',revision=MAX(revision,?3) WHERE job=?1 AND attempt=?2",params![h.job_id,h.attempt_id,h.revision])?; + } continue; } let o: ReconciledOutcome = serde_json::from_slice(&h.outcome_bytes)?; @@ -1084,6 +1216,13 @@ fn merge_helper(local: &mut [SyncAttempt], helper: &HelperSnapshot) -> Result<() "HELPER_ATTEMPT_BINDING" ); if h.consumption != "unconsumed" { + if !h.update_handoff_bytes.is_empty() { + ensure!( + h.state == "running" && a.state == "running" && a.outcome_bytes.is_empty(), + "UPDATE_CANNOT_HEAL_UNKNOWN" + ); + a.update_handoff_bytes.clone_from(&h.update_handoff_bytes); + } a.grant_id = h.grant_id.clone(); a.consumption = h.consumption.clone(); ensure!( @@ -1101,6 +1240,42 @@ fn merge_helper(local: &mut [SyncAttempt], helper: &HelperSnapshot) -> Result<() } Ok(()) } +fn validate_update_summary( + _binding: &Binding, + job: &JobPayload, + offer: &JobOffer, + local: &SyncAttempt, + boot: Uuid, + now: DateTime, +) -> Result { + let proof = + rmm_domain::agent_update::UpdateInflightProof::from_bytes(&local.update_handoff_bytes) + .map_err(anyhow::Error::msg)?; + let key = rmm_domain::agent_update::job_health_public_key(job).map_err(anyhow::Error::msg)?; + let (h, _) = + rmm_domain::agent_update::verify_inflight_proof(&proof, key).map_err(anyhow::Error::msg)?; + let now = u64::try_from(now.timestamp())?; + ensure!( + rmm_domain::agent_update::handoff_matches_job(&h, job) + && h.boot_id == boot + && h.attempt.grant_id.to_string() == local.grant_id + && h.attempt.authorization_id.to_string() == offer.authorization_id + && h.attempt.plan_sha256 == offer.plan_hash + && h.attempt.job_payload_sha256 == offer.job_payload_hash + && local.original_boot_id == boot.to_string() + && local.consumption == "consumed" + && local.state == "running" + && local.outcome_bytes.is_empty() + && local.outcome_sha256.is_empty() + && local.result.is_none() + && local.result_envelope.is_none() + && h.consumed_at <= now + && now < h.finish_before, + "UPDATE_INFLIGHT_SUMMARY_BINDING" + ); + Ok(h) +} + pub fn verify_response( binding: &Binding, request: &SyncRequest, @@ -1176,6 +1351,8 @@ fn validate_attempt( local: &SyncAttempt, d: &AttemptDecision, boot: Uuid, + binding: &Binding, + now: DateTime, ) -> Result>> { ensure!( d.job_payload_hash == offer.job_payload_hash @@ -1199,6 +1376,25 @@ fn validate_attempt( !terminal(&local.state) || d.outcome_state == local.state, "TERMINAL_STATE_REGRESSION" ); + if d.update_inflight.is_some() || !local.update_handoff_bytes.is_empty() { + validate_update_summary(binding, job, offer, local, boot, now)?; + let proof = + rmm_domain::agent_update::UpdateInflightProof::from_bytes(&local.update_handoff_bytes) + .map_err(anyhow::Error::msg)?; + let key = + rmm_domain::agent_update::job_health_public_key(job).map_err(anyhow::Error::msg)?; + let expected = + rmm_domain::agent_update::inflight_decision(&proof, key).map_err(anyhow::Error::msg)?; + ensure!( + d.update_inflight.as_ref() == Some(&expected) + && d.outcome_state == "running" + && !d.unlock + && d.outcome_bytes.is_empty() + && d.outcome_sha256.is_none(), + "UPDATE_INFLIGHT_DECISION_CHANGED" + ); + return Ok(None); + } if d.outcome_state == "accepted" { ensure!( local.state == "accepted" diff --git a/crates/agent-core/src/update_handoff.rs b/crates/agent-core/src/update_handoff.rs new file mode 100644 index 0000000..cf743e2 --- /dev/null +++ b/crates/agent-core/src/update_handoff.rs @@ -0,0 +1,1161 @@ +//! Append-only storage in the EXISTING protected helper consumption ledger. +//! No effects, generic Unknown healing, second journal ID or start lease. +//! Admission is only callable through HelperSync's independently checked gate. +use crate::{ + auth::{Outcome, Request}, + helper_reconcile::ExecutorLedgerGuard, + ledger, +}; +use anyhow::{Context, Result, ensure}; +use chrono::{DateTime, Utc}; +use rmm_domain::agent_update::UpdateDelegation; +use rmm_domain::jobs::{Action, ExecutionPermitPayload, JobPayload, hash}; +use rmm_updater_handoff::{Event, Evidence, Handoff, Journal, Phase, UnknownReason}; +use rusqlite::{Connection, OptionalExtension, TransactionBehavior, params}; +use uuid::Uuid; + +/// Trusted LOCAL adapter, never an IPC-supplied approved/ready boolean. It +/// authenticates the stable updater peer, immutable staging/pins/keyring, +/// release signatures/floor, exact existing file IDs and local update policy. +/// It must not stop services or replace files while validating admission. +pub trait UpdateAdmissionGuard: ExecutorLedgerGuard { + /// Independently loaded from the fixed protected local provisioning pin. + fn health_public_key(&self) -> Result<[u8; 32]>; + fn verify_prepared_update( + &self, + original: &Request, + handoff: &Handoff, + delegation: &UpdateDelegation, + now: DateTime, + ) -> Result<()>; +} + +/// Role comes from an authenticated concrete local participant, not IPC data. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Participant { + OriginalHelper, + StableUpdater, + NewHelper, +} +pub trait UpdateParticipantGuard: ExecutorLedgerGuard { + fn participant(&self) -> Participant; + fn verify_native_effect( + &self, + _handoff: &Handoff, + _delegation: &UpdateDelegation, + _effect: &NativeEffect, + _stage: NativeEffectStage, + ) -> Result<()> { + anyhow::bail!("UPDATE_NATIVE_EFFECT_NOT_QUALIFIED") + } + /// Recheck fixed service/PID/birth/image, original boot, SAME file IDs, + /// current clock/deadline and evidence-specific protected observations. + /// Health additionally compares receipt contents with the actually applied + /// current signed sync and received inventory ACK. No service/file effect. + fn verify_update_event( + &self, + handoff: &Handoff, + delegation: &UpdateDelegation, + event: &Event, + ) -> Result<()>; +} + +/// Bootstrap/create-only schema extension. Caller holds the actual existing +/// executor guard. This does not alter old schema objects, rows or file IDs. +pub fn initialize(db: &Connection, guard: &impl ExecutorLedgerGuard) -> Result<()> { + guard.check(db)?; + db.execute_batch( + "CREATE TABLE IF NOT EXISTS agent_update_handoffs( + grant_id TEXT PRIMARY KEY REFERENCES consumed(grant_id), record BLOB NOT NULL, + record_sha256 TEXT NOT NULL, health_public_key BLOB NOT NULL, head_sha256 TEXT NOT NULL, + event_count INTEGER NOT NULL, phase TEXT NOT NULL); + CREATE TABLE IF NOT EXISTS agent_update_delegations( + grant_id TEXT PRIMARY KEY REFERENCES agent_update_handoffs(grant_id), + witness BLOB NOT NULL, witness_sha256 TEXT NOT NULL); + CREATE TABLE IF NOT EXISTS agent_update_handoff_events( + grant_id TEXT NOT NULL REFERENCES agent_update_handoffs(grant_id), sequence INTEGER NOT NULL, + event BLOB NOT NULL, event_sha256 TEXT NOT NULL, PRIMARY KEY(grant_id,sequence)); + CREATE TABLE IF NOT EXISTS agent_update_native_claims( + grant_id TEXT NOT NULL REFERENCES agent_update_handoffs(grant_id),effect_key TEXT NOT NULL, + claim BLOB NOT NULL,claim_sha256 TEXT NOT NULL,PRIMARY KEY(grant_id,effect_key)); + CREATE TABLE IF NOT EXISTS agent_update_native_observations( + grant_id TEXT NOT NULL,effect_key TEXT NOT NULL,claim_sha256 TEXT NOT NULL, + observation_sha256 TEXT NOT NULL,observed_at TEXT NOT NULL,PRIMARY KEY(grant_id,effect_key), + FOREIGN KEY(grant_id,effect_key) REFERENCES agent_update_native_claims(grant_id,effect_key));", + )?; + Ok(()) +} + +/// Prepared exact local bytes, not an authorization. HelperSync independently +/// checks fresh live admission before these bytes can be consumed. +pub struct PreparedHandoff<'a> { + pub request: &'a Request, + pub handoff: &'a Handoff, + pub delegation: &'a UpdateDelegation, + pub recorded_at: DateTime, +} + +pub(crate) fn consume( + db: &mut Connection, + guard: &impl UpdateAdmissionGuard, + permit: &ExecutionPermitPayload, + prepared: &PreparedHandoff<'_>, + health_public_key: [u8; 32], + check_fresh: &impl Fn(&Connection) -> Result<()>, +) -> Result<()> { + let PreparedHandoff { + request, + handoff, + delegation, + recorded_at: now, + } = *prepared; + guard.check(db)?; + ledger::validate_start_request(permit, request)?; + let job: JobPayload = serde_json::from_slice(&request.job_bytes)?; + let Action::UpdateAgent { update } = &job.action else { + anyhow::bail!("UPDATE_ACTION_REQUIRED"); + }; + ensure!( + update.validate() && update.execution_identity() == Some(job.execution_identity.as_str()), + "UPDATE_ACTION_INVALID" + ); + ensure!( + rmm_domain::agent_update::job_health_public_key(&job).map_err(anyhow::Error::msg)? + == health_public_key + && guard.health_public_key()? == health_public_key, + "UPDATE_HEALTH_PIN_BINDING" + ); + let record = handoff.bytes()?; + let mut journal = Journal::open(&record, health_public_key)?; + ensure!( + delegation.validate() + && delegation.handoff_sha256 == hash(&record) + && delegation.owner_nonce == handoff.owner_nonce + && delegation.boot_id == handoff.boot_id + && delegation.prepared_at == now + && delegation.updater.image_sha256 == handoff.updater_sha256 + && delegation.original_helper.image_sha256 == handoff.predecessor.helper_sha256, + "UPDATE_DELEGATION_BINDING" + ); + let delegation_bytes = serde_json::to_vec(delegation)?; + let at = u64::try_from(now.timestamp())?; + let start = ledger::start_witness_bytes(permit, request, handoff.boot_id, now)?; + ensure!( + handoff.attempt.tenant_id == permit.tenant_id + && handoff.attempt.asset_id == permit.asset_id + && handoff.attempt.agent_id == permit.agent_id + && handoff.attempt.enrollment_generation == permit.enrollment_generation + && handoff.attempt.assignment_version == permit.assignment_version + && handoff.attempt.job_id == permit.job_id + && handoff.attempt.attempt_id == permit.attempt_id + && handoff.attempt.grant_id == permit.grant_id + && handoff.attempt.authorization_id == permit.authorization_id + && Some(handoff.attempt.plan_id) == permit.agent_update_plan_id + && handoff.attempt.plan_sha256 == permit.plan_hash + && handoff.attempt.job_payload_sha256 == permit.job_payload_hash + && handoff.attempt.original_request_sha256 == hash(&serde_json::to_vec(request)?) + && handoff.attempt.original_start_witness_sha256 == hash(&start) + && handoff.consumed_at == at + && handoff.finish_before == at.checked_add(600).context("UPDATE_DEADLINE_OVERFLOW")? + && permit.max_runtime_seconds == 600, + "UPDATE_ORIGINAL_BINDING" + ); + let manifest = update.manifest().map_err(anyhow::Error::msg)?; + ensure!( + rmm_domain::agent_update::handoff_matches_job(handoff, &job), + "UPDATE_EXACT_JOB_TRANSITION_BINDING" + ); + ensure!( + handoff.target.manifest_sha256 == update.manifest_sha256 + && handoff.target.agent_sha256 == manifest.artifacts[0].sha256 + && handoff.target.helper_sha256 == manifest.artifacts[1].sha256 + && handoff.predecessor.manifest_sha256 == update.predecessor.manifest_sha256 + && handoff.predecessor.agent_sha256 == update.predecessor.agent_sha256 + && handoff.predecessor.helper_sha256 == update.predecessor.helper_sha256 + && handoff.predecessor_record_sha256 == update.predecessor.installed_record_sha256 + && handoff.updater_sha256 == update.updater.binary_sha256 + && handoff.updater_policy_sha256 == update.updater.policy_sha256 + && handoff.pin_transition_sha256 + == hash(&serde_json::to_vec(&update.peer_pin_transition)?), + "UPDATE_CODEPAIR_BINDING" + ); + guard.verify_prepared_update(request, handoff, delegation, now)?; + let stop_intent = journal.prepare(at, Evidence::StopIntent)?; + journal.replay(&stop_intent)?; + // Consumption, exact legacy start, immutable handoff and first stop intent + // commit together. Any failed INSERT rolls ALL of them back. + let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?; + guard.check(&tx)?; + guard.verify_prepared_update(request, handoff, delegation, now)?; + check_fresh(&tx)?; + ledger::consume_in(&tx, permit)?; + ledger::save_start(&tx, permit, request, handoff.boot_id, now)?; + tx.execute("INSERT INTO agent_update_handoffs(grant_id,record,record_sha256,health_public_key,head_sha256,event_count,phase) + VALUES(?1,?2,?3,?4,?5,1,'stop_intent')",params![permit.grant_id.to_string(),record, + journal.handoff_sha256(),health_public_key.to_vec(),journal.head_sha256()])?; + tx.execute( + "INSERT INTO agent_update_delegations(grant_id,witness,witness_sha256) VALUES(?1,?2,?3)", + params![ + permit.grant_id.to_string(), + delegation_bytes, + hash(&delegation_bytes) + ], + )?; + tx.execute("INSERT INTO agent_update_handoff_events(grant_id,sequence,event,event_sha256) VALUES(?1,1,?2,?3)", + params![permit.grant_id.to_string(),stop_intent,hash(&stop_intent)])?; + tx.commit()?; + Ok(()) +} + +/// Read-only replay under the current authenticated guard. Original immutable +/// start, consumption, rows, event hashes, count and stored head all agree. +/// This returns neither a Ready lease nor permission to resume an OS effect. +pub fn read(db: &Connection, guard: &impl ExecutorLedgerGuard, grant: Uuid) -> Result { + guard.check(db)?; + read_locked(db, grant) +} +pub(crate) fn read_locked(db: &Connection, grant: Uuid) -> Result { + type Row = ( + Vec, + String, + Vec, + String, + u32, + String, + Vec, + Option>, + Option>, + ); + let row: Option = db.query_row("SELECT h.record,h.record_sha256,h.health_public_key,h.head_sha256,h.event_count,h.phase, + e.start,e.outcome,c.result FROM agent_update_handoffs h JOIN consumed c USING(grant_id) + JOIN execution_evidence e USING(grant_id) WHERE h.grant_id=?1",[grant.to_string()],|r| + Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?,r.get(4)?,r.get(5)?,r.get(6)?,r.get(7)?,r.get(8)?))) + .optional()?; + let (record, record_hash, key, head, count, phase, start, outcome, result) = + row.context("UPDATE_HANDOFF_MISSING")?; + ensure!( + hash(&record) == record_hash && key.len() == 32, + "UPDATE_HANDOFF_RECORD_CHANGED" + ); + let handoff: Handoff = serde_json::from_slice(&record)?; + ensure!( + handoff.attempt.grant_id == grant + && hash(&start) == handoff.attempt.original_start_witness_sha256, + "UPDATE_HANDOFF_ORIGINAL_CHANGED" + ); + let consumed: (String, u64, String, String) = db.query_row( + "SELECT agent,generation,job,attempt FROM consumed WHERE grant_id=?1", + [grant.to_string()], + |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)), + )?; + ensure!( + consumed.0 == handoff.attempt.agent_id.to_string() + && consumed.1 == handoff.attempt.enrollment_generation + && consumed.2 == handoff.attempt.job_id.to_string() + && consumed.3 == handoff.attempt.attempt_id.to_string(), + "UPDATE_HANDOFF_CONSUMED_CHANGED" + ); + let start_value: serde_json::Value = serde_json::from_slice(&start)?; + let original: Request = serde_json::from_value(start_value["request"].clone())?; + let original_job: JobPayload = serde_json::from_slice(&original.job_bytes)?; + ensure!( + rmm_domain::agent_update::job_health_public_key(&original_job) + .map_err(anyhow::Error::msg)? + .as_slice() + == key.as_slice(), + "UPDATE_STORED_HEALTH_KEY_CHANGED" + ); + let delegation = read_delegation(db, grant)?; + ensure!( + delegation.handoff_sha256 == record_hash + && delegation.owner_nonce == handoff.owner_nonce + && delegation.boot_id == handoff.boot_id + && delegation.updater.image_sha256 == handoff.updater_sha256 + && delegation.original_helper.image_sha256 == handoff.predecessor.helper_sha256, + "UPDATE_DELEGATION_BINDING" + ); + // Native intents are subordinate immutable rows, not another consumption + // or execution journal. Replaying them never authorizes dispatch. + let mut native=db.prepare("SELECT effect_key,claim,claim_sha256 FROM agent_update_native_claims WHERE grant_id=?1 ORDER BY effect_key")?; + let native_rows = native.query_map([grant.to_string()], |r| { + Ok(( + r.get::<_, String>(0)?, + r.get::<_, Vec>(1)?, + r.get::<_, String>(2)?, + )) + })?; + let mut native_count = 0; + for row in native_rows { + native_count += 1; + let (effect_key, raw, digest) = row?; + let claim: NativeEffectClaim = serde_json::from_slice(&raw)?; + ensure!( + native_count <= 17 + && raw.len() <= 2048 + && hash(&raw) == digest + && serde_json::to_vec(&claim)? == raw + && claim.grant_id == grant + && claim.owner_nonce == handoff.owner_nonce + && native_key(&claim.effect)? == effect_key + && rmm_domain::agent_update::digest(&claim.head_sha256), + "UPDATE_NATIVE_HISTORY_CHANGED" + ); + } + let invalid:u64=db.query_row("SELECT count(*) FROM agent_update_native_observations o LEFT JOIN agent_update_native_claims c ON c.grant_id=o.grant_id AND c.effect_key=o.effect_key WHERE o.grant_id=?1 AND (c.claim_sha256 IS NULL OR c.claim_sha256<>o.claim_sha256)",[grant.to_string()],|r|r.get(0))?; + ensure!(invalid == 0, "UPDATE_NATIVE_OBSERVATION_BINDING"); + let mut journal = Journal::open( + &record, + key.try_into() + .map_err(|_| anyhow::anyhow!("UPDATE_HEALTH_KEY"))?, + )?; + let mut statement = db.prepare("SELECT sequence,event,event_sha256 FROM agent_update_handoff_events WHERE grant_id=?1 ORDER BY sequence")?; + let rows = statement.query_map([grant.to_string()], |r| { + Ok(( + r.get::<_, u32>(0)?, + r.get::<_, Vec>(1)?, + r.get::<_, String>(2)?, + )) + })?; + let mut observed = 0; + let mut stored_outcome_hash = None; + for row in rows { + let (sequence, event, event_hash) = row?; + observed += 1; + ensure!( + sequence == observed && hash(&event) == event_hash, + "UPDATE_HANDOFF_EVENT_CHANGED" + ); + journal.replay(&event)?; + let parsed: Event = serde_json::from_slice(&event)?; + if let Evidence::OutcomePersisted { outcome_sha256 } = parsed.evidence { + stored_outcome_hash = Some(outcome_sha256); + } + } + ensure!( + observed == count && journal.head_sha256() == head && phase == phase_name(journal.phase()), + "UPDATE_HANDOFF_HEAD_CHANGED" + ); + if journal.phase() == Phase::OutcomePersisted { + ensure!( + outcome + .as_ref() + .is_some_and(|bytes| stored_outcome_hash.as_ref() == Some(&hash(bytes))), + "UPDATE_HANDOFF_FINAL_OUTCOME_MISSING_OR_CHANGED" + ); + } + if outcome.is_some() || result.is_some() { + ensure!( + matches!(journal.phase(), Phase::OutcomePersisted | Phase::Unknown), + "UPDATE_HANDOFF_OUTCOME_CONFLICT" + ); + if let (Some(a), Some(b)) = (outcome, result) { + ensure!(a == b, "UPDATE_HANDOFF_OUTCOME_CONFLICT"); + } + } + Ok(journal) +} + +/// Only metadata under an already checked helper executor guard. Live owner, +/// clock and boot checks remain required at capture/apply, never inferred here. +pub(crate) fn proof_locked( + db: &Connection, + grant: Uuid, +) -> Result> { + 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 { + return Ok(None); + } + let record: Option> = db + .query_row( + "SELECT record FROM agent_update_handoffs WHERE grant_id=?1", + [grant.to_string()], + |r| r.get(0), + ) + .optional()?; + let Some(record) = record else { + return Ok(None); + }; + let journal = read_locked(db, grant)?; + if matches!(journal.phase(), Phase::Unknown | Phase::OutcomePersisted) { + return Ok(None); + } + let mut statement = db.prepare( + "SELECT event FROM agent_update_handoff_events WHERE grant_id=?1 ORDER BY sequence", + )?; + let events = statement + .query_map([grant.to_string()], |r| r.get::<_, Vec>(0))? + .collect::>>()?; + Ok(Some( + rmm_domain::agent_update::UpdateInflightProof::from_raw( + &record, + read_delegation(db, grant)?, + &events, + journal.head_sha256().into(), + ) + .map_err(anyhow::Error::msg)?, + )) +} + +/// Shared pure validator, still no OS owner attestation or readiness claim. +pub fn verify_inflight_proof( + proof: &rmm_domain::agent_update::UpdateInflightProof, + health_key: [u8; 32], +) -> Result<(Handoff, Journal)> { + rmm_domain::agent_update::verify_inflight_proof(proof, health_key).map_err(anyhow::Error::msg) +} +pub fn inflight_decision( + proof: &rmm_domain::agent_update::UpdateInflightProof, + health_key: [u8; 32], +) -> Result { + rmm_domain::agent_update::inflight_decision(proof, health_key).map_err(anyhow::Error::msg) +} + +/// CAS append only. The actual participant/OS adapter authenticates which +/// writer owns the SAME guard and which raw observations support this event. +/// Callers cannot mutate original rows or replace an existing terminal outcome. +pub fn append( + db: &mut Connection, + guard: &impl UpdateParticipantGuard, + grant: Uuid, + expected_head: &str, + event: &[u8], +) -> Result<()> { + let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?; + let mut journal = read(&tx, guard, grant)?; + ensure!( + journal.head_sha256() == expected_head, + "UPDATE_HANDOFF_CAS_CONFLICT" + ); + let parsed: Event = serde_json::from_slice(event)?; + ensure!( + !matches!( + parsed.evidence, + Evidence::OutcomePersisted { .. } | Evidence::Unknown { .. } + ), + "UPDATE_TERMINAL_REQUIRES_OUTCOME_CAS" + ); + verify_writer(&tx, guard, grant, &parsed)?; + journal.replay(event)?; + append_in(&tx, grant, expected_head, event, &parsed, &journal)?; + tx.commit()?; + Ok(()) +} + +pub fn read_delegation(db: &Connection, grant: Uuid) -> Result { + let (raw, expected): (Vec, String) = db.query_row( + "SELECT witness,witness_sha256 FROM agent_update_delegations WHERE grant_id=?1", + [grant.to_string()], + |r| Ok((r.get(0)?, r.get(1)?)), + )?; + ensure!( + raw.len() <= 8192 && hash(&raw) == expected, + "UPDATE_DELEGATION_CHANGED" + ); + let delegation: UpdateDelegation = serde_json::from_slice(&raw)?; + ensure!( + delegation.validate() && serde_json::to_vec(&delegation)? == raw, + "UPDATE_DELEGATION_INVALID" + ); + Ok(delegation) +} + +fn verify_writer( + db: &Connection, + guard: &impl UpdateParticipantGuard, + grant: Uuid, + event: &Event, +) -> Result<()> { + let raw: Vec = db.query_row( + "SELECT record FROM agent_update_handoffs WHERE grant_id=?1", + [grant.to_string()], + |r| r.get(0), + )?; + let handoff: Handoff = serde_json::from_slice(&raw)?; + let expected = match event.evidence { + Evidence::AllStopped { .. } + | Evidence::UpdaterOwnsLedger { .. } + | Evidence::ReplaceIntent { .. } + | Evidence::Replaced { .. } + | Evidence::PairVerified { .. } + | Evidence::LedgerReturnIntent => Participant::StableUpdater, + Evidence::ServicesStarted { .. } + | Evidence::HealthVerified { .. } + | Evidence::OutcomePersisted { .. } => Participant::NewHelper, + Evidence::Unknown { .. } => guard.participant(), + Evidence::StopIntent => anyhow::bail!("UPDATE_STOP_ALREADY_ATOMICALLY_STORED"), + }; + ensure!(guard.participant() == expected, "UPDATE_WRITER_ROLE"); + let require_observed = |effect: NativeEffect| -> Result<()> { + let count:u64=db.query_row("SELECT count(*) FROM agent_update_native_observations WHERE grant_id=?1 AND effect_key=?2",params![grant.to_string(),native_key(&effect)?],|r|r.get(0))?; + ensure!(count == 1, "UPDATE_NATIVE_OBSERVATION_REQUIRED"); + Ok(()) + }; + match &event.evidence { + Evidence::AllStopped { .. } => { + for service in [ + NativeService::Agent, + NativeService::General, + NativeService::Full, + ] { + if handoff.stop_set.contains(&native_service(service)) { + require_observed(NativeEffect::StopService { service })?; + } + } + } + Evidence::Replaced { role, .. } => { + let role = match role { + rmm_updater_handoff::FileRole::AgentBinary => NativeFileRole::AgentBinary, + rmm_updater_handoff::FileRole::HelperBinary => NativeFileRole::HelperBinary, + rmm_updater_handoff::FileRole::LinuxFullConfig => NativeFileRole::FullConfig, + rmm_updater_handoff::FileRole::LinuxFullPin => NativeFileRole::FullPin, + _ => anyhow::bail!("UPDATE_NATIVE_PLATFORM_UNQUALIFIED"), + }; + require_observed(NativeEffect::PublishReplacement { role })?; + } + Evidence::ServicesStarted { .. } => { + for service in [ + NativeService::General, + NativeService::Full, + NativeService::Agent, + ] { + require_observed(NativeEffect::StartService { service })?; + } + } + _ => {} + } + guard.verify_update_event(&handoff, &read_delegation(db, grant)?, event) +} + +fn append_in( + tx: &Connection, + grant: Uuid, + expected_head: &str, + event: &[u8], + parsed: &Event, + journal: &Journal, +) -> Result<()> { + tx.execute("INSERT INTO agent_update_handoff_events(grant_id,sequence,event,event_sha256) VALUES(?1,?2,?3,?4)", + params![grant.to_string(),parsed.sequence,event,hash(event)])?; + ensure!(tx.execute("UPDATE agent_update_handoffs SET head_sha256=?2,event_count=?3,phase=?4 WHERE grant_id=?1 AND head_sha256=?5", + params![grant.to_string(),journal.head_sha256(),parsed.sequence,phase_name(journal.phase()),expected_head])? == 1,"UPDATE_HANDOFF_CAS_CONFLICT"); + Ok(()) +} + +/// Final outcome and its handoff event commit atomically. Does NOT set +/// consumed.result or create a Ready lease: normal signed mirroring/sync must +/// still agree with the exact bytes. Existing Unknown cannot be overwritten. +pub fn finalize( + db: &mut Connection, + guard: &impl UpdateParticipantGuard, + permit: &ExecutionPermitPayload, + expected_head: &str, + observed_at: u64, + outcome: &Outcome, +) -> Result<()> { + ensure!( + guard.participant() == Participant::NewHelper + && outcome.state == "succeeded" + && !outcome.reboot_required, + "UPDATE_FINAL_OUTCOME_PROFILE" + ); + let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?; + let mut journal = read(&tx, guard, permit.grant_id)?; + let records:u64=tx.query_row("SELECT count(*) FROM agent_update_native_observations WHERE grant_id=?1 AND effect_key IN ('save_installed_record','publish_installed_record')",[permit.grant_id.to_string()],|r|r.get(0))?; + ensure!(records == 2, "UPDATE_INSTALLED_RECORD_NOT_CONFIRMED"); + ensure!( + journal.head_sha256() == expected_head && journal.phase() == Phase::HealthVerified, + "UPDATE_FINAL_HEAD_OR_PHASE" + ); + let outcome_bytes = ledger::persist_outcome_in(&tx, permit, outcome)?; + let event = journal.prepare( + observed_at, + Evidence::OutcomePersisted { + outcome_sha256: hash(&outcome_bytes), + }, + )?; + let parsed: Event = serde_json::from_slice(&event)?; + verify_writer(&tx, guard, permit.grant_id, &parsed)?; + journal.replay(&event)?; + append_in( + &tx, + permit.grant_id, + expected_head, + &event, + &parsed, + &journal, + )?; + tx.commit()?; + Ok(()) +} + +/// Persist uncertainty once under the same original consumption. No release, +/// new start, result rewrite or transition back out of Unknown is provided. +pub fn mark_unknown( + db: &mut Connection, + guard: &impl UpdateParticipantGuard, + permit: &ExecutionPermitPayload, + expected_head: &str, + observed_at: u64, + reason: UnknownReason, +) -> Result<()> { + let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?; + let mut journal = read(&tx, guard, permit.grant_id)?; + ensure!( + journal.head_sha256() == expected_head, + "UPDATE_UNKNOWN_HEAD_CHANGED" + ); + let event = journal.prepare(observed_at, Evidence::Unknown { reason })?; + let parsed: Event = serde_json::from_slice(&event)?; + verify_writer(&tx, guard, permit.grant_id, &parsed)?; + ledger::persist_outcome_in(&tx, permit, &Outcome::unknown("AGENT_UPDATE_UNCERTAIN"))?; + journal.replay(&event)?; + append_in( + &tx, + permit.grant_id, + expected_head, + &event, + &parsed, + &journal, + )?; + tx.commit()?; + Ok(()) +} + +/// Called only by independently verifying helper capture under its existing +/// IMMEDIATE transaction/guard after a live owner/boot/deadline check failed. +/// It creates uncertainty, never effects or a successful result. +pub(crate) fn mark_unknown_locked( + db: &Connection, + permit: &ExecutionPermitPayload, + observed_at: u64, + reason: UnknownReason, +) -> Result> { + let mut journal = read_locked(db, permit.grant_id)?; + let head = journal.head_sha256().to_owned(); + let event = journal.prepare(observed_at, Evidence::Unknown { reason })?; + let parsed: Event = serde_json::from_slice(&event)?; + let outcome = ledger::persist_outcome_in( + db, + permit, + &Outcome::unknown("AGENT_UPDATE_OWNER_OR_DEADLINE_UNPROVEN"), + )?; + journal.replay(&event)?; + append_in(db, permit.grant_id, &head, &event, &parsed, &journal)?; + Ok(outcome) +} + +fn phase_name(phase: Phase) -> &'static str { + match phase { + Phase::HandoffConsumed => "handoff_consumed", + Phase::StopIntent => "stop_intent", + Phase::AllStopped => "all_stopped", + Phase::UpdaterOwnsLedger => "updater_owns_ledger", + Phase::ReplaceIntent => "replace_intent", + Phase::Replaced => "replaced", + Phase::PairVerified => "pair_verified", + Phase::LedgerReturnIntent => "ledger_return_intent", + Phase::ServicesStarted => "services_started", + Phase::HealthVerified => "health_verified", + Phase::OutcomePersisted => "outcome_persisted", + Phase::Unknown => "unknown", + } +} + +/// Closed native sub-effects, subordinate to the original consumed attempt. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(tag = "effect", rename_all = "snake_case", deny_unknown_fields)] +pub enum NativeEffect { + StopService { + service: NativeService, + }, + SavePredecessor { + role: NativeFileRole, + }, + PublishReplacement { + role: NativeFileRole, + }, + RestorePredecessor { + role: NativeFileRole, + }, + StartService { + service: NativeService, + }, + ReturnLedger, + SaveInstalledRecord { + old_sha256: String, + new_sha256: String, + }, + PublishInstalledRecord { + old_sha256: String, + new_sha256: String, + }, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum NativeService { + Agent, + General, + Full, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum NativeFileRole { + AgentBinary, + HelperBinary, + FullConfig, + FullPin, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum NativeEffectStage { + Claim, + Observe, + ReserveFutureStart, +} +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(deny_unknown_fields)] +pub struct NativeEffectClaim { + grant_id: Uuid, + owner_nonce: Uuid, + head_sha256: String, + effect: NativeEffect, + claimed_at: DateTime, +} +impl NativeEffectClaim { + pub fn grant_id(&self) -> Uuid { + self.grant_id + } + pub fn owner_nonce(&self) -> Uuid { + self.owner_nonce + } + pub fn head_sha256(&self) -> &str { + &self.head_sha256 + } + pub fn effect(&self) -> &NativeEffect { + &self.effect + } + pub fn claimed_at(&self) -> DateTime { + self.claimed_at + } +} +pub struct PreparedReturnClaims { + pub return_ledger: NativeEffectClaim, + pub starts: [NativeEffectClaim; 3], +} +fn native_context( + db: &Connection, + guard: &impl UpdateParticipantGuard, + grant: Uuid, + now: DateTime, +) -> Result<(Handoff, UpdateDelegation, Journal)> { + let journal = read(db, guard, grant)?; + let raw: Vec = db.query_row( + "SELECT record FROM agent_update_handoffs WHERE grant_id=?1", + [grant.to_string()], + |r| r.get(0), + )?; + let h: Handoff = serde_json::from_slice(&raw)?; + let d = read_delegation(db, grant)?; + let seconds = u64::try_from(now.timestamp())?; + ensure!( + seconds >= h.consumed_at + && seconds < h.finish_before + && !matches!(journal.phase(), Phase::Unknown | Phase::OutcomePersisted), + "UPDATE_NATIVE_DEADLINE_OR_TERMINAL" + ); + Ok((h, d, journal)) +} +fn native_role(role: NativeFileRole) -> rmm_updater_handoff::FileRole { + use rmm_updater_handoff::FileRole as F; + match role { + NativeFileRole::AgentBinary => F::AgentBinary, + NativeFileRole::HelperBinary => F::HelperBinary, + NativeFileRole::FullConfig => F::LinuxFullConfig, + NativeFileRole::FullPin => F::LinuxFullPin, + } +} +fn native_service(service: NativeService) -> rmm_updater_handoff::Service { + use rmm_updater_handoff::Service as S; + match service { + NativeService::Agent => S::LinuxAgent, + NativeService::General => S::LinuxGeneralHelper, + NativeService::Full => S::LinuxFullHelper, + } +} +fn native_key(effect: &NativeEffect) -> Result { + match effect { + NativeEffect::SaveInstalledRecord { .. } => Ok("save_installed_record".into()), + NativeEffect::PublishInstalledRecord { .. } => Ok("publish_installed_record".into()), + _ => Ok(serde_json::to_string(effect)?), + } +} +fn insert_native_claim( + db: &Connection, + h: &Handoff, + head: &str, + effect: NativeEffect, + now: DateTime, +) -> Result { + let count: u64 = db.query_row( + "SELECT count(*) FROM agent_update_native_claims WHERE grant_id=?1", + [h.attempt.grant_id.to_string()], + |r| r.get(0), + )?; + ensure!(count < 17, "UPDATE_NATIVE_EFFECT_LIMIT"); + let claim = NativeEffectClaim { + grant_id: h.attempt.grant_id, + owner_nonce: h.owner_nonce, + head_sha256: head.into(), + effect, + claimed_at: now, + }; + let raw = serde_json::to_vec(&claim)?; + db.execute("INSERT INTO agent_update_native_claims(grant_id,effect_key,claim,claim_sha256) VALUES(?1,?2,?3,?4)",params![claim.grant_id.to_string(),native_key(&claim.effect)?,raw,hash(&raw)])?; + Ok(claim) +} +/// A duplicate intent is a hard denial, never a dispatch/resume instruction. +pub fn claim_native_effect( + db: &mut Connection, + guard: &impl UpdateParticipantGuard, + grant: Uuid, + expected_head: &str, + effect: &NativeEffect, + now: DateTime, +) -> Result { + let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?; + let (h, d, j) = native_context(&tx, guard, grant, now)?; + ensure!( + j.head_sha256() == expected_head, + "UPDATE_HANDOFF_CAS_CONFLICT" + ); + match effect { + NativeEffect::StopService { service } => ensure!( + guard.participant() == Participant::OriginalHelper + && j.phase() == Phase::StopIntent + && h.stop_set.contains(&native_service(*service)), + "UPDATE_NATIVE_STOP_ROLE" + ), + NativeEffect::SavePredecessor { role } | NativeEffect::PublishReplacement { role } => { + ensure!( + guard.participant() == Participant::StableUpdater + && j.phase() == Phase::ReplaceIntent, + "UPDATE_NATIVE_REPLACE_ROLE" + ); + let last:Vec=tx.query_row("SELECT event FROM agent_update_handoff_events WHERE grant_id=?1 ORDER BY sequence DESC LIMIT 1",[grant.to_string()],|r|r.get(0))?; + ensure!( + serde_json::from_slice::(&last)?.evidence + == Evidence::ReplaceIntent { + role: native_role(*role) + }, + "UPDATE_NATIVE_REPLACE_FILE" + ); + if matches!(effect, NativeEffect::PublishReplacement { .. }) { + let save = native_key(&NativeEffect::SavePredecessor { role: *role })?; + let count:u64=tx.query_row("SELECT count(*) FROM agent_update_native_observations WHERE grant_id=?1 AND effect_key=?2",params![grant.to_string(),save],|r|r.get(0))?; + ensure!(count == 1, "UPDATE_NATIVE_SAVE_NOT_OBSERVED"); + } + } + NativeEffect::SaveInstalledRecord { + old_sha256, + new_sha256, + } + | NativeEffect::PublishInstalledRecord { + old_sha256, + new_sha256, + } => { + ensure!( + guard.participant() == Participant::NewHelper + && j.phase() == Phase::HealthVerified + && *old_sha256 == h.predecessor_record_sha256 + && rmm_domain::agent_update::digest(new_sha256) + && old_sha256 != new_sha256, + "UPDATE_NATIVE_INSTALLED_RECORD_BINDING" + ); + if matches!(effect, NativeEffect::PublishInstalledRecord { .. }) { + let save = native_key(&NativeEffect::SaveInstalledRecord { + old_sha256: old_sha256.clone(), + new_sha256: new_sha256.clone(), + })?; + let count:u64=tx.query_row("SELECT count(*) FROM agent_update_native_observations WHERE grant_id=?1 AND effect_key=?2",params![grant.to_string(),save],|r|r.get(0))?; + ensure!(count == 1, "UPDATE_NATIVE_RECORD_SAVE_NOT_OBSERVED"); + require_matching_record_save(&tx, grant, old_sha256, new_sha256)?; + } + } + // Rollback needs its own qualified event transition; never infer it + // from an uncertain replacement or silently restart the predecessor. + NativeEffect::RestorePredecessor { .. } + | NativeEffect::StartService { .. } + | NativeEffect::ReturnLedger => anyhow::bail!("UPDATE_NATIVE_SPECIAL_TRANSITION_REQUIRED"), + } + guard.verify_native_effect(&h, &d, effect, NativeEffectStage::Claim)?; + let result = insert_native_claim(&tx, &h, expected_head, effect.clone(), now)?; + guard.check(&tx)?; + tx.commit()?; + Ok(result) +} +pub fn observe_native_effect( + db: &mut Connection, + guard: &impl UpdateParticipantGuard, + claim: &NativeEffectClaim, + observation_sha256: &str, + now: DateTime, +) -> Result<()> { + ensure!( + rmm_domain::agent_update::digest(observation_sha256), + "UPDATE_NATIVE_OBSERVATION_HASH" + ); + let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?; + let (h, d, j) = native_context(&tx, guard, claim.grant_id, now)?; + ensure!( + h.owner_nonce == claim.owner_nonce && now >= claim.claimed_at, + "UPDATE_NATIVE_CLAIM_BINDING" + ); + let raw: Vec = tx.query_row( + "SELECT claim FROM agent_update_native_claims WHERE grant_id=?1 AND effect_key=?2", + params![claim.grant_id.to_string(), native_key(&claim.effect)?], + |r| r.get(0), + )?; + ensure!( + raw == serde_json::to_vec(claim)?, + "UPDATE_NATIVE_CLAIM_CHANGED" + ); + match claim.effect { + NativeEffect::StopService { .. } => ensure!( + guard.participant() == Participant::StableUpdater + && matches!( + j.phase(), + Phase::StopIntent | Phase::AllStopped | Phase::UpdaterOwnsLedger + ), + "UPDATE_NATIVE_STOP_OBSERVER" + ), + NativeEffect::StartService { .. } => ensure!( + guard.participant() == Participant::NewHelper && j.phase() == Phase::LedgerReturnIntent, + "UPDATE_NATIVE_START_OBSERVER" + ), + NativeEffect::SavePredecessor { .. } | NativeEffect::PublishReplacement { .. } => ensure!( + guard.participant() == Participant::StableUpdater + && j.phase() == Phase::ReplaceIntent + && j.head_sha256() == claim.head_sha256, + "UPDATE_NATIVE_FILE_OBSERVER" + ), + NativeEffect::SaveInstalledRecord { .. } | NativeEffect::PublishInstalledRecord { .. } => { + ensure!( + guard.participant() == Participant::NewHelper + && j.phase() == Phase::HealthVerified + && j.head_sha256() == claim.head_sha256, + "UPDATE_NATIVE_RECORD_OBSERVER" + ) + } + NativeEffect::ReturnLedger | NativeEffect::RestorePredecessor { .. } => { + anyhow::bail!("UPDATE_NATIVE_OBSERVATION_NOT_SUPPORTED") + } + } + guard.verify_native_effect(&h, &d, &claim.effect, NativeEffectStage::Observe)?; + tx.execute("INSERT INTO agent_update_native_observations(grant_id,effect_key,claim_sha256,observation_sha256,observed_at) VALUES(?1,?2,?3,?4,?5)",params![claim.grant_id.to_string(),native_key(&claim.effect)?,hash(&raw),observation_sha256,now.to_rfc3339()])?; + guard.check(&tx)?; + tx.commit()?; + Ok(()) +} +/// ReturnIntent and exactly one future start sequence commit together while +/// the updater still holds the SAME lock. Returned values are evidence only; +/// only the live original worker's non-clone execution token may dispatch them. +pub fn prepare_return_and_starts( + db: &mut Connection, + guard: &impl UpdateParticipantGuard, + grant: Uuid, + expected_head: &str, + return_event: &[u8], + now: DateTime, +) -> Result { + let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?; + let (h, d, mut j) = native_context(&tx, guard, grant, now)?; + ensure!( + guard.participant() == Participant::StableUpdater + && j.phase() == Phase::PairVerified + && j.head_sha256() == expected_head, + "UPDATE_NATIVE_RETURN_ROLE" + ); + ensure!( + h.stop_set + .contains(&rmm_updater_handoff::Service::LinuxFullHelper), + "UPDATE_NATIVE_FULL_PROFILE_REQUIRED" + ); + let missing:u64=tx.query_row("SELECT count(*) FROM agent_update_native_claims c LEFT JOIN agent_update_native_observations o ON c.grant_id=o.grant_id AND c.effect_key=o.effect_key WHERE c.grant_id=?1 AND o.effect_key IS NULL",[grant.to_string()],|r|r.get(0))?; + ensure!(missing == 0, "UPDATE_NATIVE_UNOBSERVED_EFFECT"); + let parsed: Event = serde_json::from_slice(return_event)?; + ensure!( + parsed.evidence == Evidence::LedgerReturnIntent + && parsed.observed_at == u64::try_from(now.timestamp())?, + "UPDATE_NATIVE_RETURN_EVENT" + ); + verify_writer(&tx, guard, grant, &parsed)?; + guard.verify_native_effect( + &h, + &d, + &NativeEffect::ReturnLedger, + NativeEffectStage::Claim, + )?; + for service in [ + NativeService::General, + NativeService::Full, + NativeService::Agent, + ] { + guard.verify_native_effect( + &h, + &d, + &NativeEffect::StartService { service }, + NativeEffectStage::ReserveFutureStart, + )?; + } + j.replay(return_event)?; + append_in(&tx, grant, expected_head, return_event, &parsed, &j)?; + let return_ledger = + insert_native_claim(&tx, &h, j.head_sha256(), NativeEffect::ReturnLedger, now)?; + let mut starts = Vec::new(); + for service in [ + NativeService::General, + NativeService::Full, + NativeService::Agent, + ] { + starts.push(insert_native_claim( + &tx, + &h, + j.head_sha256(), + NativeEffect::StartService { service }, + now, + )?); + } + guard.check(&tx)?; + tx.commit()?; + Ok(PreparedReturnClaims { + return_ledger, + starts: starts + .try_into() + .map_err(|_| anyhow::anyhow!("UPDATE_NATIVE_START_COUNT"))?, + }) +} + +/// Additive Fullhelper-only bridge. No freely chosen paths, command, event or +/// current-ready assertion can cross this protocol. +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] +#[serde(deny_unknown_fields)] +pub struct NativeControlRequest { + pub operation: String, + pub schema_version: u32, + pub challenge: Uuid, + pub tenant_id: Uuid, + pub asset_id: Uuid, + pub agent_id: Uuid, + pub enrollment_generation: u64, + pub assignment_version: u64, + pub grant_id: Uuid, + pub owner_nonce: Uuid, + pub handoff_sha256: String, + pub method: NativeControlOperation, +} +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] +#[serde(tag = "method", rename_all = "snake_case", deny_unknown_fields)] +pub enum NativeControlOperation { + ReadOriginal, + ClaimStop { + expected_head_sha256: String, + service: NativeService, + }, + ObserveStarts, + Health { + receipt: rmm_updater_handoff::SignedHealth, + }, +} +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] +#[serde(deny_unknown_fields)] +pub struct NativeControlReply { + pub schema_version: u32, + pub challenge: Uuid, + pub tenant_id: Uuid, + pub asset_id: Uuid, + pub agent_id: Uuid, + pub enrollment_generation: u64, + pub assignment_version: u64, + pub grant_id: Uuid, + pub owner_nonce: Uuid, + pub handoff_sha256: String, + pub ready: bool, + pub proof: rmm_domain::agent_update::UpdateInflightProof, + pub claim: Option, + /// Only ReadOriginal; exact retained execution_evidence.start bytes, + /// bounded to 512KiB before canonical Base64url encoding, never rewritten. + pub original_start_base64url: Option, +} + +fn require_matching_record_save( + db: &Connection, + grant: Uuid, + old_sha256: &str, + new_sha256: &str, +) -> Result<()> { + let (raw,digest,observed_claim):(Vec,String,String)=db.query_row( + "SELECT c.claim,c.claim_sha256,o.claim_sha256 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='save_installed_record'", + [grant.to_string()],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?)))?; + let claim: NativeEffectClaim = serde_json::from_slice(&raw)?; + ensure!( + hash(&raw) == digest + && digest == observed_claim + && serde_json::to_vec(&claim)? == raw + && claim.grant_id == grant + && claim.effect + == NativeEffect::SaveInstalledRecord { + old_sha256: old_sha256.into(), + new_sha256: new_sha256.into() + }, + "UPDATE_NATIVE_RECORD_PUBLISH_PAIR_CHANGED" + ); + Ok(()) +} +#[cfg(test)] +mod native_record_tests { + use super::*; + #[test] + fn record_publish_requires_exact_saved_record_even_when_original_head_did_not_change() { + let db = Connection::open_in_memory().unwrap(); + db.execute_batch("CREATE TABLE agent_update_native_claims(grant_id TEXT,effect_key TEXT,claim BLOB,claim_sha256 TEXT); CREATE TABLE agent_update_native_observations(grant_id TEXT,effect_key TEXT,claim_sha256 TEXT);").unwrap(); + let grant = Uuid::new_v4(); + let head = "12".repeat(32); + let old = "34".repeat(32); + let new = "56".repeat(32); + let claim = NativeEffectClaim { + grant_id: grant, + owner_nonce: Uuid::new_v4(), + head_sha256: head.clone(), + effect: NativeEffect::SaveInstalledRecord { + old_sha256: old.clone(), + new_sha256: new.clone(), + }, + claimed_at: Utc::now(), + }; + let raw = serde_json::to_vec(&claim).unwrap(); + let digest = hash(&raw); + db.execute( + "INSERT INTO agent_update_native_claims VALUES(?1,'save_installed_record',?2,?3)", + params![grant.to_string(), raw, digest], + ) + .unwrap(); + db.execute( + "INSERT INTO agent_update_native_observations VALUES(?1,'save_installed_record',?2)", + params![grant.to_string(), digest], + ) + .unwrap(); + require_matching_record_save(&db, grant, &old, &new).unwrap(); + assert!(require_matching_record_save(&db, grant, &old, &"78".repeat(32)).is_err()); + let stored: Vec = db + .query_row("SELECT claim FROM agent_update_native_claims", [], |r| { + r.get(0) + }) + .unwrap(); + assert_eq!(stored, raw); + assert_eq!( + serde_json::from_slice::(&stored) + .unwrap() + .head_sha256, + head + ); + } +} diff --git a/crates/agent-core/tests/contracts.rs b/crates/agent-core/tests/contracts.rs index f6d05f2..ecf10b8 100644 --- a/crates/agent-core/tests/contracts.rs +++ b/crates/agent-core/tests/contracts.rs @@ -51,6 +51,7 @@ fn fixture() -> (Binding, Request, ExecutionPermitPayload, DateTime) { }; let job_bytes = encode(&job).unwrap(); let permit = ExecutionPermitPayload { + agent_update_plan_id: None, domain: "rmm.execution-permit".into(), schema_version: 1, grant_id: Uuid::from_u128(7), diff --git a/crates/agent-core/tests/helper_reconcile.rs b/crates/agent-core/tests/helper_reconcile.rs index c1f091d..3a481d4 100644 --- a/crates/agent-core/tests/helper_reconcile.rs +++ b/crates/agent-core/tests/helper_reconcile.rs @@ -122,6 +122,7 @@ fn denial_case() -> ( max_output_bytes: 4096, }; let permit = ExecutionPermitPayload { + agent_update_plan_id: None, domain: "rmm.execution-permit".into(), schema_version: 1, grant_id: Uuid::new_v4(), @@ -594,6 +595,7 @@ impl Fixture { .attempts .iter() .map(|a| AttemptDecision { + update_inflight: None, job_id: a.job_id, attempt_id: a.attempt_id, job_payload_hash: a.job_payload_hash.clone(), @@ -673,6 +675,7 @@ impl Fixture { max_output_bytes: 4096, }; let permit = ExecutionPermitPayload { + agent_update_plan_id: None, domain: "rmm.execution-permit".into(), schema_version: 1, grant_id: Uuid::new_v4(), @@ -957,6 +960,9 @@ fn request( text(8, &a.original_boot_id.to_string(), &mut row); text(11, &a.outcome_sha256, &mut row); blob(12, &a.outcome_bytes, &mut row); + if !a.update_handoff_bytes.is_empty() { + blob(14, &a.update_handoff_bytes, &mut row); + } blob(6, &row, &mut out); } num(8, 1, &mut out); @@ -1399,3 +1405,572 @@ fn root_and_system_are_distinct_explicit_helper_domains() { let changed = sync.with_helper_identity(HelperIdentity::Root); assert!(!changed.can_start(&system.db, &system.guard, 1, &system.clock, &system.boot)); } + +// Test-only update admission port. This verifies fixture identity/bytes, NOT +// real update trust files, service ownership, OS locks or a WebUI approval. +struct TestUpdateGuard { + ledger: ExecutorGuard, + handoff_hash: String, + delegation: rmm_domain::agent_update::UpdateDelegation, + owner_alive: bool, + owner_authority: bool, + health_public_key: [u8; 32], +} +impl ExecutorLedgerGuard for TestUpdateGuard { + fn is_update_owner_authority(&self) -> bool { + self.owner_authority + } + fn check(&self, db: &Connection) -> anyhow::Result<()> { + self.ledger.check(db) + } + fn check_update_owner( + &self, + handoff: &rmm_updater_handoff::Handoff, + delegation: &rmm_domain::agent_update::UpdateDelegation, + _: rmm_updater_handoff::Phase, + _: &[rmm_updater_handoff::Event], + ) -> anyhow::Result<()> { + anyhow::ensure!( + self.owner_alive + && hash(&handoff.bytes()?) == self.handoff_hash + && delegation == &self.delegation, + "TEST_OWNER_LOST" + ); + Ok(()) + } +} +impl rmm_agent_core::update_handoff::UpdateAdmissionGuard for TestUpdateGuard { + fn health_public_key(&self) -> anyhow::Result<[u8; 32]> { + Ok(self.health_public_key) + } + fn verify_prepared_update( + &self, + _: &Request, + handoff: &rmm_updater_handoff::Handoff, + delegation: &rmm_domain::agent_update::UpdateDelegation, + _: DateTime, + ) -> anyhow::Result<()> { + anyhow::ensure!( + hash(&handoff.bytes()?) == self.handoff_hash && delegation == &self.delegation, + "TEST_HANDOFF_CHANGED" + ); + Ok(()) + } +} +fn update_case() -> ( + Fixture, + HelperSync, + Request, + rmm_updater_handoff::Handoff, + TestUpdateGuard, +) { + use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; + use rmm_domain::agent_update as u; + use rmm_updater_handoff as h; + let mut f = Fixture::new(); + let mut sync = f.sync(); + rmm_agent_core::update_handoff::initialize(&f.db, &f.guard).unwrap(); + let snapshot = f.snapshot(&mut sync, 7); + let raw = f.request(&snapshot); + let ready = f.decision(&snapshot, &raw, 7, true); + assert!(f.apply(&mut sync, &ready, &raw).unwrap().ready); + let digest = |n: u8| format!("{n:02x}").repeat(32); + let mut manifest: u::ReleaseManifest = serde_json::from_slice(include_bytes!( + "../../updater/tests/fixtures/release_v1.json" + )) + .unwrap(); + manifest.published_at = f.clock.now.timestamp() as u64 - 1; + manifest.expires_at = f.clock.now.timestamp() as u64 + 3600; + let payload = encode(&manifest).unwrap(); + let release_key = SigningKey::from_bytes(&[43; 32]); + let mut signed = b"rmm.agent-release.v1\0".to_vec(); + signed.extend_from_slice(&payload); + let envelope = u::ReleaseEnvelope { + schema_version: 1, + key_id: hash(release_key.verifying_key().as_bytes()), + payload_bytes: URL_SAFE_NO_PAD.encode(&payload), + signature: URL_SAFE_NO_PAD.encode(release_key.sign(&signed).to_bytes()), + }; + let update = u::ResolvedAgentUpdate { + schema_version: 1, + profile: u::UpdateProfile::FixedCodePairV1, + release_envelope_sha256: envelope.sha256().unwrap(), + manifest_sha256: hash(&payload), + release_envelope: envelope, + predecessor: u::Predecessor { + release_id: Uuid::from_u128(99), + release_sequence: 3, + manifest_sha256: digest(1), + installed_record_sha256: digest(2), + agent_sha256: digest(3), + helper_sha256: digest(4), + }, + updater: u::UpdaterBinding { + binary_sha256: digest(5), + policy_sha256: digest(6), + keyring_generation: 1, + keyring_sha256: digest(7), + health_public_key_hex: hex::encode( + SigningKey::from_bytes(&[44; 32]).verifying_key().to_bytes(), + ), + health_key_pin_sha256: digest(10), + }, + peer_pin_transition: u::PeerPinTransition::UnchangedGeneralPinV1 { + general_pin_sha256: digest(8), + }, + recovery: u::Recovery::RestoreExactPredecessorOnce, + health_profile: u::HealthProfile::MtlsInventorySyncV1, + health_timeout_seconds: 180, + no_reboot: true, + }; + assert!(update.validate()); + let job = JobPayload { + schema_version: 1, + tenant_id: f.binding.tenant_id, + asset_id: f.binding.asset_id, + agent_id: f.binding.agent_id, + enrollment_generation: 1, + assignment_version: 3, + job_id: Uuid::new_v4(), + attempt_id: Uuid::new_v4(), + action: Action::UpdateAgent { + update: Box::new(update.clone()), + }, + execution_identity: "root".into(), + not_before: f.clock.now - Duration::seconds(1), + start_before: f.clock.now + Duration::minutes(5), + max_runtime_seconds: 600, + max_output_bytes: 4096, + }; + let permit = ExecutionPermitPayload { + agent_update_plan_id: Some(Uuid::from_u128(1001)), + domain: "rmm.execution-permit".into(), + schema_version: 1, + grant_id: Uuid::new_v4(), + authorization_id: Uuid::new_v4(), + tenant_id: job.tenant_id, + asset_id: job.asset_id, + agent_id: job.agent_id, + enrollment_generation: 1, + assignment_version: 3, + job_id: job.job_id, + attempt_id: job.attempt_id, + plan_hash: digest(9), + job_payload_hash: hash(&encode(&job).unwrap()), + action: "update_agent".into(), + execution_identity: "root".into(), + not_before: f.clock.now - Duration::seconds(1), + start_before: f.clock.now + Duration::seconds(59), + max_runtime_seconds: 600, + key_id: hash(f.key.verifying_key().as_bytes()), + }; + let permit_bytes = encode(&permit).unwrap(); + let request = Request { + job_bytes: encode(&job).unwrap(), + permit_bytes: permit_bytes.clone(), + signature: f.key.sign(&permit_bytes).to_bytes().to_vec(), + plan_hash: permit.plan_hash.clone(), + authorization_id: permit.authorization_id, + }; + let handoff = h::Handoff { + schema_version: 1, + attempt: h::AttemptBinding { + tenant_id: job.tenant_id, + asset_id: job.asset_id, + agent_id: job.agent_id, + enrollment_generation: 1, + assignment_version: 3, + plan_id: Uuid::from_u128(1001), + plan_sha256: permit.plan_hash, + job_id: job.job_id, + attempt_id: job.attempt_id, + job_payload_sha256: permit.job_payload_hash, + grant_id: permit.grant_id, + authorization_id: permit.authorization_id, + original_request_sha256: hash(&encode(&request).unwrap()), + original_start_witness_sha256: hash( + &rmm_agent_core::ledger::start_witness_bytes( + &serde_json::from_slice(&request.permit_bytes).unwrap(), + &request, + f.boot.0, + f.clock.now, + ) + .unwrap(), + ), + }, + agent_journal_id: f.agent_journal, + helper_journal_id: snapshot.journal_id, + helper_checkpoint: snapshot.checkpoint, + previous_decision_id: ready.decision_id, + boot_id: f.boot.0, + connection_generation: 7, + owner_nonce: Uuid::new_v4(), + updater_sha256: update.updater.binary_sha256, + updater_policy_sha256: update.updater.policy_sha256, + predecessor_record_sha256: update.predecessor.installed_record_sha256, + retained_state_sha256: digest(10), + ledger_identity_sha256: digest(11), + staged_files_sha256: digest(12), + predecessor: h::CodePair { + manifest_sha256: update.predecessor.manifest_sha256, + agent_sha256: update.predecessor.agent_sha256.clone(), + helper_sha256: update.predecessor.helper_sha256.clone(), + pin_sha256: digest(8), + }, + target: h::CodePair { + manifest_sha256: update.manifest_sha256, + agent_sha256: manifest.artifacts[0].sha256.clone(), + helper_sha256: manifest.artifacts[1].sha256.clone(), + pin_sha256: digest(8), + }, + pin_transition: h::PinTransition::UnchangedLinuxGeneralV1, + pin_transition_sha256: hash(&encode(&update.peer_pin_transition).unwrap()), + files: vec![ + h::FileTransition { + role: h::FileRole::AgentBinary, + old_sha256: update.predecessor.agent_sha256, + new_sha256: manifest.artifacts[0].sha256.clone(), + }, + h::FileTransition { + role: h::FileRole::HelperBinary, + old_sha256: update.predecessor.helper_sha256, + new_sha256: manifest.artifacts[1].sha256.clone(), + }, + ], + stop_set: vec![h::Service::LinuxAgent, h::Service::LinuxGeneralHelper], + consumed_at: f.clock.now.timestamp() as u64, + finish_before: f.clock.now.timestamp() as u64 + 600, + }; + let guard = TestUpdateGuard { + ledger: ExecutorGuard { + directory: f.dir.clone(), + }, + handoff_hash: hash(&handoff.bytes().unwrap()), + owner_alive: true, + owner_authority: true, + health_public_key: SigningKey::from_bytes(&[44; 32]).verifying_key().to_bytes(), + delegation: u::UpdateDelegation { + schema_version: 1, + handoff_sha256: hash(&handoff.bytes().unwrap()), + owner_nonce: handoff.owner_nonce, + boot_id: handoff.boot_id, + prepared_at: f.clock.now, + updater: u::ParticipantIdentity { + role: u::ParticipantRole::LinuxUpdater, + pid: 600, + birth: 1000, + image_sha256: handoff.updater_sha256.clone(), + security_principal: "uid:0".into(), + service_instance_sha256: digest(14), + }, + original_helper: u::ParticipantIdentity { + role: u::ParticipantRole::LinuxGeneralHelper, + pid: 700, + birth: 2000, + image_sha256: handoff.predecessor.helper_sha256.clone(), + security_principal: "uid:0".into(), + service_instance_sha256: digest(15), + }, + }, + }; + (f, sync, request, handoff, guard) +} +#[test] +fn update_handoff_consumption_start_and_stop_intent_are_one_transaction() { + for trigger in [ + "", + "CREATE TRIGGER deny_handoff BEFORE INSERT ON agent_update_handoffs BEGIN SELECT RAISE(ABORT,'test'); END;", + "CREATE TRIGGER deny_event BEFORE INSERT ON agent_update_handoff_events BEGIN SELECT RAISE(ABORT,'test'); END;", + ] { + let (mut f, mut sync, request, handoff, guard) = update_case(); + f.db.execute_batch(trigger).unwrap(); + let result = sync.begin_update_handoff( + &mut f.db, + &guard, + 7, + &rmm_agent_core::update_handoff::PreparedHandoff { + request: &request, + handoff: &handoff, + delegation: &guard.delegation, + recorded_at: f.clock.now, + }, + &f.clock, + &f.boot, + ); + assert_eq!(result.is_ok(), trigger.is_empty(), "{result:?}"); + for table in [ + "consumed", + "execution_evidence", + "agent_update_handoffs", + "agent_update_delegations", + "agent_update_handoff_events", + ] { + let count: u32 = + f.db.query_row(&format!("SELECT count(*) FROM {table}"), [], |r| r.get(0)) + .unwrap(); + assert_eq!(count, if trigger.is_empty() { 1 } else { 0 }, "{table}"); + } + if trigger.is_empty() { + let journal = + rmm_agent_core::update_handoff::read(&f.db, &guard, handoff.attempt.grant_id) + .unwrap(); + assert_eq!(journal.phase(), rmm_updater_handoff::Phase::StopIntent); + assert!(!sync.can_start(&f.db, &guard, 7, &f.clock, &f.boot)); + assert!( + sync.begin_update_handoff( + &mut f.db, + &guard, + 7, + &rmm_agent_core::update_handoff::PreparedHandoff { + request: &request, + handoff: &handoff, + delegation: &guard.delegation, + recorded_at: f.clock.now + }, + &f.clock, + &f.boot + ) + .is_err() + ); + } + } +} + +#[test] +fn update_inflight_negative_control_keeps_every_start_closed_and_owner_loss_is_terminal() { + let (mut f, mut sync, request, handoff, mut guard) = update_case(); + let prepared = rmm_agent_core::update_handoff::PreparedHandoff { + request: &request, + handoff: &handoff, + delegation: &guard.delegation, + recorded_at: f.clock.now, + }; + sync.begin_update_handoff(&mut f.db, &guard, 7, &prepared, &f.clock, &f.boot) + .unwrap(); + let original: Vec = + f.db.query_row( + "SELECT start FROM execution_evidence WHERE grant_id=?1", + [handoff.attempt.grant_id.to_string()], + |r| r.get(0), + ) + .unwrap(); + f.clock.now += Duration::seconds(1); + let mut fresh = f.sync(); + let snapshot = fresh + .snapshot(&mut f.db, &guard, 8, &f.clock, &f.boot) + .unwrap(); + assert_eq!(snapshot.attempts[0].state, "running"); + assert!(!snapshot.attempts[0].update_handoff_bytes.is_empty()); + let raw = f.request(&snapshot); + let mut decision = f.decision(&snapshot, &raw, 8, false); + let proof = rmm_domain::agent_update::UpdateInflightProof::from_bytes( + &snapshot.attempts[0].update_handoff_bytes, + ) + .unwrap(); + let attempt = &mut decision.attempts[0]; + attempt.outcome_state = "running".into(); + attempt.update_inflight = + Some(rmm_domain::agent_update::inflight_decision(&proof, guard.health_public_key).unwrap()); + attempt.reason = "AGENT_UPDATE_INFLIGHT".into(); + let signed = f.sign(&decision); + let applied = fresh + .apply(&mut f.db, &guard, &signed, &raw, &f.clock, &f.boot) + .unwrap(); + assert!(!applied.ready && applied.unlocked_grants.is_empty()); + assert!(!fresh.can_start(&f.db, &guard, 8, &f.clock, &f.boot)); + assert_eq!( + f.db.query_row::( + "SELECT count(*) FROM execution_evidence WHERE outcome IS NOT NULL", + [], + |r| r.get(0) + ) + .unwrap(), + 0 + ); + // A nondesignated General reader cannot attest this Full-owned update, + // and must never turn that lack of authority into terminal Unknown. + guard.owner_authority = false; + guard.owner_alive = false; + assert!( + fresh + .snapshot(&mut f.db, &guard, 8, &f.clock, &f.boot) + .is_err() + ); + assert_eq!( + rmm_agent_core::update_handoff::read(&f.db, &guard, handoff.attempt.grant_id) + .unwrap() + .phase(), + rmm_updater_handoff::Phase::StopIntent + ); + guard.owner_authority = true; + f.clock.now += Duration::seconds(1); + let lost = fresh + .snapshot(&mut f.db, &guard, 8, &f.clock, &f.boot) + .unwrap(); + assert_eq!(lost.attempts[0].state, "unknown"); + assert!(lost.attempts[0].update_handoff_bytes.is_empty()); + assert_eq!( + rmm_agent_core::update_handoff::read(&f.db, &guard, handoff.attempt.grant_id) + .unwrap() + .phase(), + rmm_updater_handoff::Phase::Unknown + ); + guard.owner_alive = true; + let retained = fresh + .snapshot(&mut f.db, &guard, 8, &f.clock, &f.boot) + .unwrap(); + assert_eq!( + retained.attempts[0].outcome_bytes, + lost.attempts[0].outcome_bytes + ); + assert_eq!(retained.attempts[0].state, "unknown"); + assert_eq!( + f.db.query_row::, _, _>( + "SELECT start FROM execution_evidence WHERE grant_id=?1", + [handoff.attempt.grant_id.to_string()], + |r| r.get(0) + ) + .unwrap(), + original + ); + assert_eq!( + f.db.query_row::( + "SELECT count(*) FROM consumed WHERE result IS NULL", + [], + |r| r.get(0) + ) + .unwrap(), + 1 + ); +} + +impl rmm_agent_core::update_handoff::UpdateParticipantGuard for TestUpdateGuard { + fn participant(&self) -> rmm_agent_core::update_handoff::Participant { + rmm_agent_core::update_handoff::Participant::OriginalHelper + } + fn verify_update_event( + &self, + _: &rmm_updater_handoff::Handoff, + _: &rmm_domain::agent_update::UpdateDelegation, + _: &rmm_updater_handoff::Event, + ) -> anyhow::Result<()> { + anyhow::bail!("TEST_NATIVE_INTENTS_ONLY_NO_OS_EFFECTS") + } + fn verify_native_effect( + &self, + h: &rmm_updater_handoff::Handoff, + d: &rmm_domain::agent_update::UpdateDelegation, + _: &rmm_agent_core::update_handoff::NativeEffect, + _: rmm_agent_core::update_handoff::NativeEffectStage, + ) -> anyhow::Result<()> { + anyhow::ensure!( + self.owner_alive + && self.owner_authority + && hash(&h.bytes()?) == self.handoff_hash + && d == &self.delegation, + "TEST_NATIVE_DENIED" + ); + Ok(()) + } +} +#[test] +fn native_stop_intent_is_original_head_bound_create_once_and_transactional() { + use rmm_agent_core::update_handoff as u; + for fail_insert in [false, true] { + let (mut f, mut sync, request, handoff, mut guard) = update_case(); + sync.begin_update_handoff( + &mut f.db, + &guard, + 7, + &u::PreparedHandoff { + request: &request, + handoff: &handoff, + delegation: &guard.delegation, + recorded_at: f.clock.now, + }, + &f.clock, + &f.boot, + ) + .unwrap(); + let head = u::read(&f.db, &guard, handoff.attempt.grant_id) + .unwrap() + .head_sha256() + .to_owned(); + let effect = u::NativeEffect::StopService { + service: u::NativeService::Agent, + }; + assert!( + u::claim_native_effect( + &mut f.db, + &guard, + handoff.attempt.grant_id, + &"0".repeat(64), + &effect, + f.clock.now + ) + .is_err() + ); + guard.owner_alive = false; + assert!( + u::claim_native_effect( + &mut f.db, + &guard, + handoff.attempt.grant_id, + &head, + &effect, + f.clock.now + ) + .is_err() + ); + guard.owner_alive = true; + if fail_insert { + f.db.execute_batch("CREATE TRIGGER deny_native BEFORE INSERT ON agent_update_native_claims BEGIN SELECT RAISE(ABORT,'test'); END;").unwrap(); + } + let result = u::claim_native_effect( + &mut f.db, + &guard, + handoff.attempt.grant_id, + &head, + &effect, + f.clock.now, + ); + assert_eq!(result.is_ok(), !fail_insert); + if let Ok(claim) = result { + assert_eq!(claim.grant_id(), handoff.attempt.grant_id); + assert_eq!(claim.owner_nonce(), handoff.owner_nonce); + assert_eq!(claim.head_sha256(), head); + assert_eq!(claim.effect(), &effect); + assert!( + u::claim_native_effect( + &mut f.db, + &guard, + handoff.attempt.grant_id, + &head, + &effect, + f.clock.now + ) + .is_err() + ); + } + assert_eq!( + f.db.query_row::( + "SELECT count(*) FROM agent_update_native_claims", + [], + |r| r.get(0) + ) + .unwrap(), + u32::from(!fail_insert) + ); + assert_eq!( + f.db.query_row::("SELECT count(*) FROM consumed", [], |r| r.get(0)) + .unwrap(), + 1 + ); + assert_eq!( + u::read(&f.db, &guard, handoff.attempt.grant_id) + .unwrap() + .head_sha256(), + head + ); + } +} diff --git a/crates/agent-core/tests/reconcile.rs b/crates/agent-core/tests/reconcile.rs index df4b492..490421a 100644 --- a/crates/agent-core/tests/reconcile.rs +++ b/crates/agent-core/tests/reconcile.rs @@ -125,6 +125,7 @@ impl Fixture { "succeeded" | "failed" | "cancelled" | "expired" ); AttemptDecision { + update_inflight: None, job_id: job.job_id, attempt_id: job.attempt_id, job_payload_hash: local.job_payload_hash.clone(), @@ -249,6 +250,7 @@ impl Fixture { let mut grant = None; if consume { let p = ExecutionPermitPayload { + agent_update_plan_id: None, domain: "rmm.execution-permit".into(), schema_version: 1, grant_id: Uuid::new_v4(), @@ -370,6 +372,7 @@ fn authenticated_helper_outcome_is_imported_as_new_durable_evidence_not_reexecut checkpoint: 3, previous_decision_id: None, attempts: vec![SyncAttempt { + update_handoff_bytes: Vec::new(), job_id: offer.job_id.clone(), attempt_id: offer.attempt_id.clone(), job_payload_hash: offer.job_payload_hash.clone(), @@ -1175,6 +1178,7 @@ fn system_helper_import_requires_explicit_system_identity_and_never_root_alias() checkpoint: 3, previous_decision_id: None, attempts: vec![SyncAttempt { + update_handoff_bytes: Vec::new(), job_id: offer.job_id.clone(), attempt_id: offer.attempt_id.clone(), job_payload_hash: offer.job_payload_hash.clone(), diff --git a/crates/agent-windows/src/helper_runtime.rs b/crates/agent-windows/src/helper_runtime.rs index 765afd7..aa5e95c 100644 --- a/crates/agent-windows/src/helper_runtime.rs +++ b/crates/agent-windows/src/helper_runtime.rs @@ -613,6 +613,7 @@ pub fn map_snapshot(s: &Snapshot) -> HelperSnapshot { .attempts .iter() .map(|a| SyncAttempt { + update_handoff_bytes: a.update_handoff_bytes.clone(), job_id: a.job_id.to_string(), attempt_id: a.attempt_id.to_string(), job_payload_hash: a.job_payload_hash.clone(), @@ -874,6 +875,7 @@ mod tests { ); // Pure mirror-binding negatives, not a signature/OS authentication proof. let permit = rmm_domain::jobs::ExecutionPermitPayload { + agent_update_plan_id: None, domain: "rmm.execution-permit".into(), schema_version: 1, grant_id: id, @@ -900,6 +902,7 @@ mod tests { .unwrap(); let bytes = rmm_domain::reconciliation::canonical_outcome_bytes(&canonical).unwrap(); let row = rmm_agent_core::helper_reconcile::LocalAttempt { + update_handoff_bytes: Vec::new(), job_id: id, attempt_id: id, job_payload_hash: permit.job_payload_hash.clone(), diff --git a/crates/agent-windows/src/runtime.rs b/crates/agent-windows/src/runtime.rs index 7b358cb..6c463fa 100644 --- a/crates/agent-windows/src/runtime.rs +++ b/crates/agent-windows/src/runtime.rs @@ -489,12 +489,17 @@ impl Agent { ensure!(expected == generation, "HELPER_CHANNEL_CHANGED"); let snapshot = task.await??; self.helper_anchor = snapshot.no_start_anchor; - self.sync - .as_mut() - .context("SYNC_NOT_CONFIGURED")? - .confirm_helper(&rmm_agent_windows::helper_runtime::map_snapshot( - &snapshot.raw, - ))?; + let mapped = rmm_agent_windows::helper_runtime::map_snapshot(&snapshot.raw); + let sync = self.sync.as_mut().context("SYNC_NOT_CONFIGURED")?; + if mapped + .attempts + .iter() + .any(|a| !a.update_handoff_bytes.is_empty()) + { + sync.confirm_update_helper(&mapped)?; + } else { + sync.confirm_helper(&mapped)?; + } self.open_fence(generation)?; } } @@ -602,6 +607,7 @@ impl Agent { } fn capabilities(&self) -> Vec { let mut caps: Vec = CAPABILITIES.iter().map(|c| c.to_string()).collect(); + caps.push("agent.update/1".into()); if self.config.enable_jobs && self.binding.is_some() && native::require_local_service().is_ok() @@ -1243,6 +1249,36 @@ impl Agent { self.journal.save(&envelope) } } + fn queue_update_observation(&mut self, generation: u64) -> Result<()> { + if self.journal.count()? > 0 || !jobs::events(self.journal.connection())?.is_empty() { + return Ok(()); + } + // Schema support is passive only; no qualified updater/helper observer + // is configured by this source checkpoint, so apply remains closed. + let observation = rmm_domain::agent_update::AgentUpdateObservation::not_configured( + rmm_domain::agent_update::Platform::WindowsX64, + Utc::now(), + ); + let data = serde_json::to_vec(&serde_json::json!({"agent_update":observation}))?; + let envelope = self.envelope( + generation, + Payload::InventorySnapshot(InventorySnapshot { + snapshot_id: Uuid::new_v4().to_string(), + scope: "agent.update".into(), + schema_version: 1, + chunk_index: 0, + chunk_count: 1, + sha256: Sha256::digest(&data).to_vec(), + data, + completeness: "partial".into(), + }), + )?; + if self.binding.is_some() { + jobs::event(self.journal.connection(), &envelope) + } else { + self.journal.save(&envelope) + } + } async fn session(&mut self, stop: &AtomicBool) -> Result<()> { self.close_gate(); let result = self.session_inner(stop).await; @@ -1296,6 +1332,7 @@ impl Agent { "SERVER_LIMITS" ); self.queue_inventory(generation)?; + self.queue_update_observation(generation)?; self.replay(&channel, generation).await?; let mut needs_sync = self.sync.is_some(); if self.sync.is_some() && self.running.is_none() { @@ -1309,6 +1346,7 @@ impl Agent { let mut capabilities_at = Instant::now(); let mut replay = Instant::now() - Duration::from_secs(10); let mut inventory = Instant::now(); + let mut update_at = Instant::now(); let mut heartbeat = Instant::now() - Duration::from_secs(60); let mut heartbeat_after = Duration::from_secs(30); let mut tick = tokio::time::interval(Duration::from_secs(1)); @@ -1422,6 +1460,10 @@ impl Agent { self.queue_inventory(generation)?; inventory = Instant::now(); } + if !stop.load(Ordering::SeqCst) && update_at.elapsed() >= Duration::from_secs(60) { + self.queue_update_observation(generation)?; + update_at = Instant::now(); + } } Ok(()) } diff --git a/crates/agent/src/helper_sync.rs b/crates/agent/src/helper_sync.rs index 42068de..e7f5d09 100644 --- a/crates/agent/src/helper_sync.rs +++ b/crates/agent/src/helper_sync.rs @@ -25,6 +25,7 @@ fn map(s: &root::Snapshot) -> reconcile::HelperSnapshot { .attempts .iter() .map(|a| SyncAttempt { + update_handoff_bytes: a.update_handoff_bytes.clone(), job_id: a.job_id.to_string(), attempt_id: a.attempt_id.to_string(), job_payload_hash: a.job_payload_hash.clone(), @@ -115,7 +116,12 @@ impl Helpers { for _ in 0..3 { let mut snapshots = vec![]; let mut inodes = None; - for e in &self.endpoints { + // Full is the only provisioned update owner authority. General + // cannot inspect its broader process capability context; it must + // stay closed without classifying the original effect Unknown. + let mut ordered: Vec<_> = self.endpoints.iter().collect(); + ordered.sort_by_key(|e| e.profile != "full_maintenance_v1"); + for e in ordered { let q = control::Request::Snapshot { challenge: Uuid::new_v4(), identity: readiness::Identity::from_binding(&self.binding)?, @@ -128,7 +134,19 @@ impl Helpers { ensure!(old == ids, "HELPERS_MUST_SHARE_LEDGER_AND_LOCK"); } inodes = Some(ids); - snapshots.push(r.snapshot.context("HELPER_SNAPSHOT_REQUIRED")?); + let snapshot = r.snapshot.context("HELPER_SNAPSHOT_REQUIRED")?; + if snapshot + .attempts + .iter() + .any(|a| !a.update_handoff_bytes.is_empty()) + { + ensure!( + e.profile == "full_maintenance_v1", + "UPDATE_FULL_OWNER_REQUIRED" + ); + return Ok(Some(map(&snapshot))); + } + snapshots.push(snapshot); } let first = &snapshots[0]; if snapshots.iter().all(|s| { @@ -150,7 +168,20 @@ impl Helpers { ) -> Result> { use prost::Message; let mut applied: Option = None; - for e in &self.endpoints { + let update_control = request + .attempts + .iter() + .any(|a| !a.update_handoff_bytes.is_empty()); + let endpoints: Vec<_> = self + .endpoints + .iter() + .filter(|e| !update_control || e.profile == "full_maintenance_v1") + .collect(); + ensure!( + !update_control || endpoints.len() == 1, + "UPDATE_FULL_OWNER_REQUIRED" + ); + for e in endpoints { let q = control::Request::Apply { challenge: Uuid::new_v4(), identity: readiness::Identity::from_binding(&self.binding)?, diff --git a/crates/agent/src/main.rs b/crates/agent/src/main.rs index 7c64279..891342a 100644 --- a/crates/agent/src/main.rs +++ b/crates/agent/src/main.rs @@ -184,6 +184,15 @@ impl Agent { .as_mut() .context("SYNC_REQUIRED")? .confirm_helper(&snapshot)?; + } else if snapshot + .attempts + .iter() + .any(|a| !a.update_handoff_bytes.is_empty()) + { + self.sync + .as_mut() + .context("SYNC_REQUIRED")? + .confirm_update_helper(&snapshot)?; } } if self.ready(generation, false) { @@ -389,7 +398,11 @@ impl Agent { }) } fn capabilities(&self) -> Vec { - let mut capabilities = vec!["linux.base/1".into(), "heartbeat/1".into()]; + let mut capabilities = vec![ + "linux.base/1".into(), + "heartbeat/1".into(), + "agent.update/1".into(), + ]; if self.binding.is_some() { capabilities.push("rmm.sync.v1".into()); } @@ -435,6 +448,33 @@ impl Agent { let _ = sender.blocking_send(result); }); } + fn queue_update_observation(&mut self, generation: u64) -> Result<()> { + if !storage::passive_collection_ready(&self.db)? { + return Ok(()); + } + // Until the separately qualified protected updater/helper observer is + // provisioned, report its real absence; never infer apply readiness from + // this schema support or the agent's own code/build version. + let observation = rmm_domain::agent_update::AgentUpdateObservation::not_configured( + rmm_domain::agent_update::Platform::LinuxX64, + Utc::now(), + ); + let data = serde_json::to_vec(&serde_json::json!({"agent_update":observation}))?; + let envelope = self.envelope( + generation, + Payload::InventorySnapshot(rmm_protocol::InventorySnapshot { + snapshot_id: Uuid::new_v4().to_string(), + scope: "agent.update".into(), + schema_version: 1, + chunk_index: 0, + chunk_count: 1, + sha256: Sha256::digest(&data).to_vec(), + data, + completeness: "partial".into(), + }), + )?; + jobs::event(&self.db, &envelope) + } fn inventory_envelope( &mut self, generation: u64, @@ -507,6 +547,7 @@ impl Agent { storage::clear_pending(&self.db)?; } self.queue_inventory(); + self.queue_update_observation(generation)?; self.replay(&ws, generation).await?; let mut needs_sync = false; if self.sync.is_some() @@ -518,6 +559,7 @@ impl Agent { } eprintln!("authenticated channel established; inventory queued for durable acknowledgment"); let mut inventory_at = Instant::now(); + let mut update_at = Instant::now(); let mut heartbeat_at = Instant::now(); let mut heartbeat_after = Duration::from_millis(rand::random_range(27_000..33_000)); let mut tick = tokio::time::interval(Duration::from_secs(5)); @@ -648,6 +690,10 @@ impl Agent { // Planning pins must be refreshed before the 90-second stored-data // planning limit. One inflight blocking collector bounds pressure; // heartbeats never perform this metadata work. + if update_at.elapsed() >= Duration::from_secs(60) { + self.queue_update_observation(generation)?; + update_at = Instant::now(); + } if inventory_at.elapsed() >= Duration::from_secs(60) { self.queue_inventory(); inventory_at = Instant::now(); diff --git a/crates/agent/src/runtime_tests.rs b/crates/agent/src/runtime_tests.rs index 84dea28..f17a2c3 100644 --- a/crates/agent/src/runtime_tests.rs +++ b/crates/agent/src/runtime_tests.rs @@ -60,6 +60,7 @@ fn new_process_persists_interruption_before_helper_io_without_unlock_or_repeat() max_output_bytes: 4096, }; let permit = ExecutionPermitPayload { + agent_update_plan_id: None, domain: "rmm.execution-permit".into(), schema_version: 1, grant_id: Uuid::new_v4(), diff --git a/crates/agent/tests/reconcile.rs b/crates/agent/tests/reconcile.rs index 3882a54..2a5843c 100644 --- a/crates/agent/tests/reconcile.rs +++ b/crates/agent/tests/reconcile.rs @@ -115,6 +115,7 @@ impl Fixture { "succeeded" | "failed" | "cancelled" | "expired" ); AttemptDecision { + update_inflight: None, job_id: job.job_id, attempt_id: job.attempt_id, job_payload_hash: local.job_payload_hash.clone(), @@ -242,6 +243,7 @@ impl Fixture { let mut grant = None; if consume { let p = ExecutionPermitPayload { + agent_update_plan_id: None, domain: "rmm.execution-permit".into(), schema_version: 1, grant_id: Uuid::new_v4(), @@ -359,6 +361,7 @@ fn authenticated_helper_outcome_is_imported_as_new_durable_evidence_not_reexecut checkpoint: 3, previous_decision_id: None, attempts: vec![SyncAttempt { + update_handoff_bytes: Vec::new(), job_id: offer.job_id.clone(), attempt_id: offer.attempt_id.clone(), job_payload_hash: offer.job_payload_hash.clone(), diff --git a/crates/domain/Cargo.toml b/crates/domain/Cargo.toml index e25379d..402a2c9 100644 --- a/crates/domain/Cargo.toml +++ b/crates/domain/Cargo.toml @@ -11,3 +11,5 @@ hex.workspace = true uuid.workspace = true chrono.workspace = true schemars.workspace = true +base64 = "=0.22.1" +rmm-updater-handoff = { path = "../updater-handoff" } diff --git a/crates/domain/examples/agent_update_golden.rs b/crates/domain/examples/agent_update_golden.rs new file mode 100644 index 0000000..3ef01b9 --- /dev/null +++ b/crates/domain/examples/agent_update_golden.rs @@ -0,0 +1,158 @@ +//! Codec fixtures only: the synthetic signature is deliberately NOT release +//! authority. These payloads must never be enrolled, published or executed. +use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; +use rmm_domain::{agent_update::*, jobs::*}; +use serde_json::json; +use uuid::Uuid; +fn id(last: u32) -> Uuid { + Uuid::parse_str(&format!("11111111-1111-4111-8111-{last:012x}")).unwrap() +} +fn fixture(platform: Platform, full: bool) -> serde_json::Value { + let m = ReleaseManifest { + schema_version: 1, + release_id: id(10), + release_sequence: 2, + version: "0.1.1-test".into(), + platform, + published_at: 1_790_000_000, + expires_at: 2_000_000_000, + protocol_major: 1, + state_schema: 1, + minimum_updater_version: 1, + artifacts: [ + ArtifactDescriptor { + role: ArtifactRole::Agent, + artifact_id: id(11), + sha256: "02".repeat(32), + bytes: 3_000_007, + }, + ArtifactDescriptor { + role: ArtifactRole::Helper, + artifact_id: id(12), + sha256: "04".repeat(32), + bytes: 2_000_009, + }, + ], + }; + let manifest = encode(&m).unwrap(); + let envelope = ReleaseEnvelope { + schema_version: 1, + key_id: "aa".repeat(32), + payload_bytes: URL_SAFE_NO_PAD.encode(&manifest), + signature: URL_SAFE_NO_PAD.encode([1_u8; 64]), + }; + let transition = match platform { + Platform::LinuxX64 if full => PeerPinTransition::LinuxGeneralFullV1 { + general_pin_sha256: "10".repeat(32), + full: LinuxFullTransition { + schema_version: 1, + old_config_sha256: "11".repeat(32), + new_config_sha256: "12".repeat(32), + old_pin_sha256: "13".repeat(32), + new_pin_sha256: "14".repeat(32), + old_policy_sha256: "15".repeat(32), + new_policy_sha256: "16".repeat(32), + old_helper_sha256: "03".repeat(32), + new_helper_sha256: "04".repeat(32), + effective_signing_key_id: "17".repeat(32), + }, + }, + Platform::LinuxX64 => PeerPinTransition::UnchangedGeneralPinV1 { + general_pin_sha256: "10".repeat(32), + }, + Platform::WindowsX64 => PeerPinTransition::WindowsCodePairV1 { + old_settings_sha256: "11".repeat(32), + new_settings_sha256: "12".repeat(32), + old_pin_sha256: "13".repeat(32), + new_pin_sha256: "14".repeat(32), + }, + }; + let update = ResolvedAgentUpdate { + schema_version: 1, + profile: UpdateProfile::FixedCodePairV1, + release_envelope_sha256: envelope.sha256().unwrap(), + release_envelope: envelope, + manifest_sha256: hash(&manifest), + predecessor: Predecessor { + release_id: id(9), + release_sequence: 1, + manifest_sha256: "20".repeat(32), + installed_record_sha256: "21".repeat(32), + agent_sha256: "01".repeat(32), + helper_sha256: "03".repeat(32), + }, + updater: UpdaterBinding { + binary_sha256: "30".repeat(32), + policy_sha256: "31".repeat(32), + keyring_generation: 1, + keyring_sha256: "32".repeat(32), + health_public_key_hex: "33".repeat(32), + health_key_pin_sha256: "34".repeat(32), + }, + peer_pin_transition: transition, + recovery: Recovery::RestoreExactPredecessorOnce, + health_profile: HealthProfile::MtlsInventorySyncV1, + health_timeout_seconds: 180, + no_reboot: true, + }; + assert!(update.validate()); + let job = JobPayload { + schema_version: 1, + tenant_id: id(1), + asset_id: id(2), + agent_id: id(3), + enrollment_generation: 1, + assignment_version: 1, + job_id: id(4), + attempt_id: id(5), + action: Action::UpdateAgent { + update: Box::new(update), + }, + execution_identity: match platform { + Platform::LinuxX64 => "root", + Platform::WindowsX64 => "system", + } + .into(), + not_before: "2030-01-01T12:00:00Z".parse().unwrap(), + start_before: "2030-01-01T12:10:00Z".parse().unwrap(), + max_runtime_seconds: 600, + max_output_bytes: 65536, + }; + let job_hash = hash(&encode(&job).unwrap()); + let plan = PlanPayload { + schema_version: 1, + plan_id: id(6), + tenant_id: id(1), + principal: "codec-fixture-only".into(), + reason: "Nur Codec: vollständiges Codepaar – keine Releasefreigabe".into(), + jobs: vec![PlannedJob { + payload: job.clone(), + job_payload_hash: job_hash.clone(), + script_sha256: None, + }], + max_parallel: 1, + halt_after_failures: 1, + recipe_references: Vec::new(), + artifact_references: m + .artifacts + .iter() + .map(|a| JobArtifactReference { + job_id: job.job_id, + attempt_id: job.attempt_id, + artifact: ArtifactReference { + artifact_id: a.artifact_id, + sha256: a.sha256.clone(), + size_bytes: a.bytes, + }, + }) + .collect(), + }; + let raw = encode(&plan).unwrap(); + json!({"fixture_kind":"codec_only_synthetic_signature_never_publish_or_execute","plan_id":plan.plan_id,"plan_hash":hash(&raw),"payload":plan,"plan_payload":plan, + "plan_payload_bytes":raw,"resolved_targets":[{"asset_id":job.asset_id,"agent_id":job.agent_id}],"excluded_targets":[],"jobs":[{"job_id":job.job_id,"attempt_id":job.attempt_id,"asset_id":job.asset_id,"agent_id":job.agent_id,"job_payload_hash":job_hash,"script_sha256":null,"payload":job}], + "authorization_status":"required","approval_state":"pending_approval","expires_at":job.start_before}) +} +fn main() { + let fixtures = json!({"linux_general":fixture(Platform::LinuxX64,false),"linux_full":fixture(Platform::LinuxX64,true),"windows_pair":fixture(Platform::WindowsX64,false)}); + println!("{}", serde_json::to_string_pretty(&fixtures).unwrap()); +} diff --git a/crates/domain/src/agent_update.rs b/crates/domain/src/agent_update.rs new file mode 100644 index 0000000..f8ed398 --- /dev/null +++ b/crates/domain/src/agent_update.rs @@ -0,0 +1,782 @@ +//! Fixed signed agent code-pair jobs. These decoded wire types validate shape +//! and exact bindings only: signature, trust, clock, policy, approval and local +//! observed predecessor remain independent admission requirements. +use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; +use serde::{Deserialize, Serialize}; +use uuid::Uuid; + +pub const APPLY_CAPABILITY: &str = "agent.update.apply/1"; +pub const CHECK_CAPABILITY: &str = "agent.update.check/1"; +pub const MAX_ARTIFACT_BYTES: u64 = 256 * 1024 * 1024; + +/// Provisioning DTO only. The OS adapter must independently authenticate its +/// protected file, exact raw hash and generation; this type grants no trust. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct UpdateKeyringFile { + pub schema_version: u32, + pub generation: u64, + pub keys: Vec, +} +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct UpdateKeyringEntry { + pub public_key_hex: String, + pub platform: Platform, + pub first_sequence: u64, + pub last_sequence: u64, + pub revoked: bool, +} +impl UpdateKeyringFile { + pub fn validate(&self) -> bool { + self.schema_version == 1 + && self.generation > 0 + && !self.keys.is_empty() + && self.keys.len() <= 16 + && self.keys.iter().all(|key| { + digest(&key.public_key_hex) + && key.first_sequence > 0 + && key.last_sequence >= key.first_sequence + }) + && self.keys.iter().enumerate().all(|(i, key)| { + !self.keys[..i] + .iter() + .any(|prior| prior.public_key_hex == key.public_key_hex) + }) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +pub enum Platform { + #[serde(rename = "x86_64-unknown-linux-gnu")] + LinuxX64, + #[serde(rename = "x86_64-pc-windows-msvc")] + WindowsX64, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum ArtifactRole { + Agent, + Helper, +} +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ArtifactDescriptor { + pub role: ArtifactRole, + pub artifact_id: Uuid, + pub sha256: String, + pub bytes: u64, +} +/// Exact version1 field order shared with the frozen pure release verifier. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ReleaseManifest { + pub schema_version: u32, + pub release_id: Uuid, + pub release_sequence: u64, + pub version: String, + pub platform: Platform, + pub published_at: u64, + pub expires_at: u64, + pub protocol_major: u32, + pub state_schema: u32, + pub minimum_updater_version: u32, + pub artifacts: [ArtifactDescriptor; 2], +} +impl ReleaseManifest { + pub fn validate(&self) -> bool { + self.schema_version == 1 + && !self.release_id.is_nil() + && self.release_sequence > 0 + && !self.version.is_empty() + && self.version.len() <= 64 + && self + .version + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b".-+_".contains(&b)) + && self.expires_at > self.published_at + && self.protocol_major > 0 + && self.state_schema > 0 + && self.minimum_updater_version > 0 + && self.artifacts[0].role == ArtifactRole::Agent + && self.artifacts[1].role == ArtifactRole::Helper + && self.artifacts[0].artifact_id != self.artifacts[1].artifact_id + && self.artifacts.iter().all(|a| { + !a.artifact_id.is_nil() + && digest(&a.sha256) + && a.bytes > 0 + && a.bytes <= MAX_ARTIFACT_BYTES + }) + } +} +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ReleaseEnvelope { + pub schema_version: u32, + pub key_id: String, + /// Canonical Base64url, no padding; decoded payload at most16KiB. + pub payload_bytes: String, + /// Canonical Base64url of exactly64 signature bytes. + pub signature: String, +} +pub struct DecodedRelease { + pub payload_bytes: Vec, + pub signature: Vec, + pub manifest: ReleaseManifest, +} +/// Exact pre-existing helper Request field order. Shared read-only linkage for +/// authoritative server reconciliation, never an alternative execute request. +#[derive(Serialize)] +pub struct OriginalHelperRequest<'a> { + pub job_bytes: &'a [u8], + pub permit_bytes: &'a [u8], + pub signature: &'a [u8], + pub plan_hash: &'a str, + pub authorization_id: Uuid, +} +impl ReleaseEnvelope { + pub fn decode(&self) -> Result { + if self.schema_version != 1 + || !digest(&self.key_id) + || self.payload_bytes.len() > 21846 + || self.signature.len() != 86 + { + return Err("UPDATE_ENVELOPE_LIMIT"); + } + let payload = URL_SAFE_NO_PAD + .decode(&self.payload_bytes) + .map_err(|_| "UPDATE_PAYLOAD_BASE64")?; + let signature = URL_SAFE_NO_PAD + .decode(&self.signature) + .map_err(|_| "UPDATE_SIGNATURE_BASE64")?; + if payload.is_empty() + || payload.len() > 16384 + || signature.len() != 64 + || URL_SAFE_NO_PAD.encode(&payload) != self.payload_bytes + || URL_SAFE_NO_PAD.encode(&signature) != self.signature + { + return Err("UPDATE_NONCANONICAL_BASE64"); + } + let manifest: ReleaseManifest = + serde_json::from_slice(&payload).map_err(|_| "UPDATE_MANIFEST_SCHEMA")?; + if !manifest.validate() + || serde_json::to_vec(&manifest).map_err(|_| "UPDATE_MANIFEST_CODEC")? != payload + { + return Err("UPDATE_MANIFEST_NONCANONICAL"); + } + Ok(DecodedRelease { + payload_bytes: payload, + signature, + manifest, + }) + } + pub fn sha256(&self) -> Result { + serde_json::to_vec(self).map(|bytes| crate::jobs::hash(&bytes)) + } +} +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct Predecessor { + pub release_id: Uuid, + pub release_sequence: u64, + pub manifest_sha256: String, + pub installed_record_sha256: String, + pub agent_sha256: String, + pub helper_sha256: String, +} +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct UpdaterBinding { + pub binary_sha256: String, + pub policy_sha256: String, + pub keyring_generation: u64, + pub keyring_sha256: String, + pub health_public_key_hex: String, + pub health_key_pin_sha256: String, +} +/// Raw Config/Pin bytes reside in the protected fixed staging record. Their +/// exact hashes and effective provisioned key ID are bound BEFORE approval. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct LinuxFullTransition { + pub schema_version: u32, + pub old_config_sha256: String, + pub new_config_sha256: String, + pub old_pin_sha256: String, + pub new_pin_sha256: String, + pub old_policy_sha256: String, + pub new_policy_sha256: String, + pub old_helper_sha256: String, + pub new_helper_sha256: String, + pub effective_signing_key_id: String, +} +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[serde(tag = "profile", rename_all = "snake_case", deny_unknown_fields)] +pub enum PeerPinTransition { + UnchangedGeneralPinV1 { + general_pin_sha256: String, + }, + LinuxGeneralFullV1 { + general_pin_sha256: String, + full: LinuxFullTransition, + }, + WindowsCodePairV1 { + old_settings_sha256: String, + new_settings_sha256: String, + old_pin_sha256: String, + new_pin_sha256: String, + }, +} +impl PeerPinTransition { + fn validate(&self, platform: Platform, predecessor: &Predecessor, target_helper: &str) -> bool { + match self { + Self::UnchangedGeneralPinV1 { general_pin_sha256 } => { + platform == Platform::LinuxX64 && digest(general_pin_sha256) + } + Self::LinuxGeneralFullV1 { + general_pin_sha256, + full, + } => { + platform == Platform::LinuxX64 + && digest(general_pin_sha256) + && full.schema_version == 1 + && full.old_helper_sha256 == predecessor.helper_sha256 + && full.new_helper_sha256 == target_helper + && [ + &full.old_config_sha256, + &full.new_config_sha256, + &full.old_pin_sha256, + &full.new_pin_sha256, + &full.old_policy_sha256, + &full.new_policy_sha256, + &full.effective_signing_key_id, + ] + .iter() + .all(|h| digest(h)) + && full.old_config_sha256 != full.new_config_sha256 + && full.old_pin_sha256 != full.new_pin_sha256 + } + Self::WindowsCodePairV1 { + old_settings_sha256, + new_settings_sha256, + old_pin_sha256, + new_pin_sha256, + } => { + platform == Platform::WindowsX64 + && [ + old_settings_sha256, + new_settings_sha256, + old_pin_sha256, + new_pin_sha256, + ] + .iter() + .all(|h| digest(h)) + && old_settings_sha256 != new_settings_sha256 + && old_pin_sha256 != new_pin_sha256 + } + } + } +} +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +pub enum UpdateProfile { + #[serde(rename = "fixed_code_pair_v1")] + FixedCodePairV1, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +pub enum Recovery { + #[serde(rename = "restore_exact_predecessor_once")] + RestoreExactPredecessorOnce, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +pub enum HealthProfile { + #[serde(rename = "mtls_inventory_sync_v1")] + MtlsInventorySyncV1, +} +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ResolvedAgentUpdate { + pub schema_version: u32, + pub profile: UpdateProfile, + pub release_envelope: ReleaseEnvelope, + pub release_envelope_sha256: String, + pub manifest_sha256: String, + pub predecessor: Predecessor, + pub updater: UpdaterBinding, + pub peer_pin_transition: PeerPinTransition, + pub recovery: Recovery, + pub health_profile: HealthProfile, + pub health_timeout_seconds: u32, + pub no_reboot: bool, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum ObservationQuality { + Valid, + Unknown, + NotConfigured, + Error, +} +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct CandidatePreview { + pub release_id: Uuid, + pub manifest_sha256: String, + pub peer_pin_transition: PeerPinTransition, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum ParticipantRole { + LinuxUpdater, + WindowsUpdater, + LinuxGeneralHelper, + LinuxFullHelper, + WindowsHelper, +} +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ParticipantIdentity { + pub role: ParticipantRole, + pub pid: u32, + /// Exact native process creation identity, not a rounded wall clock/PID. + pub birth: u64, + pub image_sha256: String, + /// uid:0 on Linux, S-1-5-18 on Windows; local policy also pins service SID. + pub security_principal: String, + /// Protected service-unit/SCM/PID/image/creation observation hash. + pub service_instance_sha256: String, +} +impl ParticipantIdentity { + pub fn validate(&self) -> bool { + self.pid > 0 + && self.birth > 0 + && digest(&self.image_sha256) + && digest(&self.service_instance_sha256) + && self.security_principal + == match self.role { + ParticipantRole::LinuxUpdater + | ParticipantRole::LinuxGeneralHelper + | ParticipantRole::LinuxFullHelper => "uid:0", + ParticipantRole::WindowsUpdater | ParticipantRole::WindowsHelper => "S-1-5-18", + } + } +} +/// Explicit immutable runtime owner witness, atomically retained WITH the +/// existing original consumption/start/handoff before stopping any service. +/// Both identities come from authenticated local OS peers, never JSON claims. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct UpdateDelegation { + pub schema_version: u32, + pub handoff_sha256: String, + pub owner_nonce: Uuid, + pub boot_id: Uuid, + pub prepared_at: chrono::DateTime, + pub updater: ParticipantIdentity, + pub original_helper: ParticipantIdentity, +} +impl UpdateDelegation { + pub fn validate(&self) -> bool { + self.schema_version == 1 + && digest(&self.handoff_sha256) + && !self.owner_nonce.is_nil() + && !self.boot_id.is_nil() + && self.updater.validate() + && self.original_helper.validate() + && self.updater.pid != self.original_helper.pid + && matches!( + (self.updater.role, self.original_helper.role), + ( + ParticipantRole::LinuxUpdater, + ParticipantRole::LinuxGeneralHelper | ParticipantRole::LinuxFullHelper + ) | ( + ParticipantRole::WindowsUpdater, + ParticipantRole::WindowsHelper + ) + ) + } +} + +/// A bounded exact retained journal prefix, never an outcome/start grant. All +/// binary fields are canonical Base64url to avoid nested JSON numeric arrays. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct UpdateInflightProof { + pub schema_version: u32, + pub handoff_record: String, + pub delegation: UpdateDelegation, + pub events: Vec, + pub head_sha256: String, +} +pub struct DecodedInflightProof { + pub handoff_record: Vec, + pub events: Vec>, +} +impl UpdateInflightProof { + pub fn from_raw( + record: &[u8], + delegation: UpdateDelegation, + events: &[Vec], + head: String, + ) -> Result { + let proof = Self { + schema_version: 1, + handoff_record: URL_SAFE_NO_PAD.encode(record), + delegation, + events: events + .iter() + .map(|bytes| URL_SAFE_NO_PAD.encode(bytes)) + .collect(), + head_sha256: head, + }; + proof.decode()?; + Ok(proof) + } + pub fn decode(&self) -> Result { + if self.schema_version != 1 + || !self.delegation.validate() + || !digest(&self.head_sha256) + || self.events.is_empty() + || self.events.len() > 16 + || self.handoff_record.len() > 21846 + { + return Err("UPDATE_INFLIGHT_LIMIT"); + } + fn bounded(value: &str) -> Result, &'static str> { + if value.is_empty() || value.len() > 21846 { + return Err("UPDATE_INFLIGHT_BYTE_LIMIT"); + } + let raw = URL_SAFE_NO_PAD + .decode(value) + .map_err(|_| "UPDATE_INFLIGHT_BASE64")?; + if raw.is_empty() || raw.len() > 16384 || URL_SAFE_NO_PAD.encode(&raw) != value { + return Err("UPDATE_INFLIGHT_BASE64"); + } + Ok(raw) + } + Ok(DecodedInflightProof { + handoff_record: bounded(&self.handoff_record)?, + events: self + .events + .iter() + .map(|event| bounded(event)) + .collect::, _>>()?, + }) + } + pub fn bytes(&self) -> Result, &'static str> { + self.decode()?; + let bytes = serde_json::to_vec(self).map_err(|_| "UPDATE_INFLIGHT_CODEC")?; + if bytes.len() > 384 * 1024 { + return Err("UPDATE_INFLIGHT_SIZE"); + } + Ok(bytes) + } + pub fn from_bytes(bytes: &[u8]) -> Result { + if bytes.len() > 384 * 1024 { + return Err("UPDATE_INFLIGHT_SIZE"); + } + let proof: Self = serde_json::from_slice(bytes).map_err(|_| "UPDATE_INFLIGHT_SCHEMA")?; + if proof.bytes()? != bytes { + return Err("UPDATE_INFLIGHT_NONCANONICAL"); + } + Ok(proof) + } +} +/// Evidence-only acknowledgement of the exact inflight prefix. It can appear +/// only with ready/helper_ready=false, no outcome and unlock=false. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct UpdateInflightDecision { + pub handoff_sha256: String, + pub delegation_sha256: String, + pub head_sha256: String, + pub owner_nonce: Uuid, + pub finish_before: u64, +} +/// Standard passive observation, not a user-triggered live query or approval. +/// A valid preview comes from the authenticated read-only privileged helper +/// after independent release/trust/floor/config/pin verification; no staging or +/// binary download. Device mTLS provides provenance, not hardware attestation. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct AgentUpdateObservation { + pub schema_version: u32, + pub platform: Platform, + pub observed_at: chrono::DateTime, + pub quality: ObservationQuality, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub predecessor: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub updater: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub activation_floor: Option, + pub rolled_back: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub helper_observation_sha256: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub signed_sync_decision_id: Option, + pub candidate_previews: Vec, +} +impl AgentUpdateObservation { + pub fn not_configured(platform: Platform, observed_at: chrono::DateTime) -> Self { + // Passive envelope timestamps have millisecond precision. Keep the inner + // observation at that same measured precision, never after its envelope. + let observed_at = observed_at + - chrono::Duration::nanoseconds(i64::from( + observed_at.timestamp_subsec_nanos() % 1_000_000, + )); + Self { + schema_version: 1, + platform, + observed_at, + quality: ObservationQuality::NotConfigured, + predecessor: None, + updater: None, + activation_floor: None, + rolled_back: false, + helper_observation_sha256: None, + signed_sync_decision_id: None, + candidate_previews: Vec::new(), + } + } + pub fn validate(&self) -> bool { + if self.schema_version != 1 || self.candidate_previews.len() > 1 { + return false; + } + if self.quality != ObservationQuality::Valid { + return self.predecessor.is_none() + && self.updater.is_none() + && self.activation_floor.is_none() + && !self.rolled_back + && self.helper_observation_sha256.is_none() + && self.signed_sync_decision_id.is_none() + && self.candidate_previews.is_empty(); + } + let (Some(p), Some(u), Some(floor), Some(proof), Some(decision)) = ( + &self.predecessor, + &self.updater, + self.activation_floor, + &self.helper_observation_sha256, + self.signed_sync_decision_id, + ) else { + return false; + }; + !p.release_id.is_nil() + && p.release_sequence > 0 + && floor >= p.release_sequence + && self.rolled_back == (floor > p.release_sequence) + && digest(proof) + && !decision.is_nil() + && [ + &p.manifest_sha256, + &p.installed_record_sha256, + &p.agent_sha256, + &p.helper_sha256, + &u.binary_sha256, + &u.policy_sha256, + &u.keyring_sha256, + &u.health_public_key_hex, + &u.health_key_pin_sha256, + ] + .iter() + .all(|h| digest(h)) + && u.keyring_generation > 0 + && self.candidate_previews.iter().all(|c| { + !c.release_id.is_nil() && c.release_id != p.release_id && digest(&c.manifest_sha256) + }) + } +} +impl ResolvedAgentUpdate { + pub fn manifest(&self) -> Result { + self.release_envelope.decode().map(|d| d.manifest) + } + pub fn validate(&self) -> bool { + let Ok(decoded) = self.release_envelope.decode() else { + return false; + }; + let m = decoded.manifest; + self.schema_version == 1 + && self.health_timeout_seconds == 180 + && self.no_reboot + && self + .release_envelope + .sha256() + .is_ok_and(|hash| hash == self.release_envelope_sha256) + && crate::jobs::hash(&decoded.payload_bytes) == self.manifest_sha256 + && !self.predecessor.release_id.is_nil() + && self.predecessor.release_id != m.release_id + && self.predecessor.release_sequence > 0 + && self.predecessor.release_sequence < m.release_sequence + && [ + &self.predecessor.manifest_sha256, + &self.predecessor.installed_record_sha256, + &self.predecessor.agent_sha256, + &self.predecessor.helper_sha256, + &self.updater.binary_sha256, + &self.updater.policy_sha256, + &self.updater.keyring_sha256, + &self.updater.health_public_key_hex, + &self.updater.health_key_pin_sha256, + ] + .iter() + .all(|h| digest(h)) + && self.updater.keyring_generation > 0 + && self.peer_pin_transition.validate( + m.platform, + &self.predecessor, + &m.artifacts[1].sha256, + ) + } + pub fn execution_identity(&self) -> Option<&'static str> { + self.manifest().ok().map(|m| match m.platform { + Platform::LinuxX64 => "root", + Platform::WindowsX64 => "system", + }) + } +} +pub fn digest(hash: &str) -> bool { + hash.len() == 64 + && hash + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) +} + +/// Shared pure receipt/prefix validation. Does not authenticate OS observations, +/// establish a live owner, heal an Unknown or grant any start permission. +pub fn verify_inflight_proof( + proof: &UpdateInflightProof, + health_key: [u8; 32], +) -> Result<(rmm_updater_handoff::Handoff, rmm_updater_handoff::Journal), String> { + use rmm_updater_handoff::{Handoff, Journal, Phase}; + let raw = proof.decode().map_err(str::to_string)?; + let mut journal = Journal::open(&raw.handoff_record, health_key).map_err(|e| e.to_string())?; + let handoff: Handoff = + serde_json::from_slice(&raw.handoff_record).map_err(|e| e.to_string())?; + if proof.delegation.handoff_sha256 != journal.handoff_sha256() + || proof.delegation.owner_nonce != handoff.owner_nonce + || proof.delegation.boot_id != handoff.boot_id + || proof.delegation.updater.image_sha256 != handoff.updater_sha256 + || proof.delegation.original_helper.image_sha256 != handoff.predecessor.helper_sha256 + || u64::try_from(proof.delegation.prepared_at.timestamp()).ok() != Some(handoff.consumed_at) + { + return Err("UPDATE_INFLIGHT_DELEGATION_BINDING".into()); + } + for event in raw.events { + journal.replay(&event).map_err(|e| e.to_string())?; + } + if journal.head_sha256() != proof.head_sha256 + || matches!(journal.phase(), Phase::Unknown | Phase::OutcomePersisted) + { + return Err("UPDATE_INFLIGHT_TERMINAL_OR_HEAD".into()); + } + Ok((handoff, journal)) +} +pub fn inflight_decision( + proof: &UpdateInflightProof, + health_key: [u8; 32], +) -> Result { + let (handoff, _) = verify_inflight_proof(proof, health_key)?; + Ok(UpdateInflightDecision { + handoff_sha256: proof.delegation.handoff_sha256.clone(), + delegation_sha256: crate::jobs::hash( + &serde_json::to_vec(&proof.delegation).map_err(|e| e.to_string())?, + ), + head_sha256: proof.head_sha256.clone(), + owner_nonce: handoff.owner_nonce, + finish_before: handoff.finish_before, + }) +} + +/// Exact immutable plan/job/release linkage, in addition to signature/prefix +/// verification. No current OS predecessor or permission is inferred here. +pub fn handoff_matches_job( + h: &rmm_updater_handoff::Handoff, + job: &crate::jobs::JobPayload, +) -> bool { + let crate::jobs::Action::UpdateAgent { update } = &job.action else { + return false; + }; + let Ok(manifest) = update.manifest() else { + return false; + }; + let Ok(job_bytes) = serde_json::to_vec(job) else { + return false; + }; + let Ok(pin_bytes) = serde_json::to_vec(&update.peer_pin_transition) else { + return false; + }; + let common = h.attempt.tenant_id == job.tenant_id + && h.attempt.asset_id == job.asset_id + && h.attempt.agent_id == job.agent_id + && h.attempt.enrollment_generation == job.enrollment_generation + && h.attempt.assignment_version == job.assignment_version + && h.attempt.job_id == job.job_id + && h.attempt.attempt_id == job.attempt_id + && h.attempt.job_payload_sha256 == crate::jobs::hash(&job_bytes) + && h.updater_sha256 == update.updater.binary_sha256 + && h.updater_policy_sha256 == update.updater.policy_sha256 + && h.predecessor_record_sha256 == update.predecessor.installed_record_sha256 + && h.predecessor.manifest_sha256 == update.predecessor.manifest_sha256 + && h.predecessor.agent_sha256 == update.predecessor.agent_sha256 + && h.predecessor.helper_sha256 == update.predecessor.helper_sha256 + && h.target.manifest_sha256 == update.manifest_sha256 + && h.target.agent_sha256 == manifest.artifacts[0].sha256 + && h.target.helper_sha256 == manifest.artifacts[1].sha256 + && h.pin_transition_sha256 == crate::jobs::hash(&pin_bytes); + if !common { + return false; + } + use rmm_updater_handoff::{FileRole, PinTransition}; + match (&update.peer_pin_transition, h.pin_transition) { + ( + PeerPinTransition::UnchangedGeneralPinV1 { general_pin_sha256 }, + PinTransition::UnchangedLinuxGeneralV1, + ) => { + h.predecessor.pin_sha256 == *general_pin_sha256 + && h.target.pin_sha256 == *general_pin_sha256 + } + (PeerPinTransition::LinuxGeneralFullV1 { full, .. }, PinTransition::LinuxGeneralFullV1) => { + h.predecessor.pin_sha256 == full.old_pin_sha256 + && h.target.pin_sha256 == full.new_pin_sha256 + && h.files.get(2).is_some_and(|f| { + f.role == FileRole::LinuxFullConfig + && f.old_sha256 == full.old_config_sha256 + && f.new_sha256 == full.new_config_sha256 + }) + } + ( + PeerPinTransition::WindowsCodePairV1 { + old_settings_sha256, + new_settings_sha256, + old_pin_sha256, + new_pin_sha256, + }, + PinTransition::WindowsCodePairV1, + ) => { + h.predecessor.pin_sha256 == *old_pin_sha256 + && h.target.pin_sha256 == *new_pin_sha256 + && h.files.get(2).is_some_and(|f| { + f.role == FileRole::WindowsSettings + && f.old_sha256 == *old_settings_sha256 + && f.new_sha256 == *new_settings_sha256 + }) + } + _ => false, + } +} + +/// The ORIGINAL signed update plan fixes a separately provisioned health key. +/// Parsing this public value alone does not provision local trust. +pub fn job_health_public_key(job: &crate::jobs::JobPayload) -> Result<[u8; 32], &'static str> { + let crate::jobs::Action::UpdateAgent { update } = &job.action else { + return Err("UPDATE_ACTION_REQUIRED"); + }; + if !update.validate() { + return Err("UPDATE_ACTION_INVALID"); + } + hex::decode(&update.updater.health_public_key_hex) + .map_err(|_| "UPDATE_HEALTH_KEY")? + .try_into() + .map_err(|_| "UPDATE_HEALTH_KEY") +} diff --git a/crates/domain/src/agent_update_provisioning.rs b/crates/domain/src/agent_update_provisioning.rs new file mode 100644 index 0000000..3c61315 --- /dev/null +++ b/crates/domain/src/agent_update_provisioning.rs @@ -0,0 +1,286 @@ +//! Protected updater provisioning codecs only. Parsing is not authentication. +//! Callers must authenticate original file bytes/owners, verify signatures and +//! enforce retained history, current policy, revocation and monotonic floor. +use crate::{ + agent_update::{Platform, ReleaseEnvelope, digest}, + jobs::hash, +}; +use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; +use serde::{Deserialize, Serialize}; +use uuid::Uuid; + +pub const BASELINE_SIGNATURE_DOMAIN: &[u8] = b"rmm.agent-update-baseline.v1\0"; +pub const MAX_RECORD_BYTES: usize = 32 * 1024; +pub const MAX_POLICY_BYTES: usize = 64 * 1024; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct HealthKeyPin { + pub schema_version: u32, + pub key_id: String, + pub public_key_hex: String, +} +impl HealthKeyPin { + /// Shape/hash only; the independent crypto verifier must reject weak keys. + pub fn public_key(&self) -> Result<[u8; 32], &'static str> { + if self.schema_version != 1 || !digest(&self.public_key_hex) || !digest(&self.key_id) { + return Err("UPDATE_HEALTH_PIN_SHAPE"); + } + let raw: [u8; 32] = hex::decode(&self.public_key_hex) + .map_err(|_| "UPDATE_HEALTH_PIN_KEY")? + .try_into() + .map_err(|_| "UPDATE_HEALTH_PIN_KEY")?; + if hash(&raw) != self.key_id { + return Err("UPDATE_HEALTH_PIN_ID"); + } + Ok(raw) + } + pub fn validate(&self) -> bool { + self.public_key().is_ok() + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] +pub enum ActivationEvidence { + Bootstrap { + qualification_receipt_sha256: String, + }, + Updated { + handoff_sha256: String, + signed_health_sha256: String, + }, +} +impl ActivationEvidence { + fn validate(&self) -> bool { + match self { + Self::Bootstrap { + qualification_receipt_sha256, + } => digest(qualification_receipt_sha256), + Self::Updated { + handoff_sha256, + signed_health_sha256, + } => digest(handoff_sha256) && digest(signed_health_sha256), + } + } +} + +/// Current local record. A release signature authenticates its manifest, not +/// these activation fields. The initial record additionally needs the separate +/// baseline signature below; subsequent changes need the original guarded CAS +/// and independently verified Health evidence. No floor may be inferred here. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct InstalledReleaseRecord { + pub schema_version: u32, + pub profile: String, + pub platform: Platform, + pub release_envelope: ReleaseEnvelope, + pub manifest_sha256: String, + pub activation_floor: u64, + pub activated_at: u64, + pub previous_record_sha256: Option, + pub activation_evidence: ActivationEvidence, + pub rolled_back: bool, +} +impl InstalledReleaseRecord { + pub fn validate(&self) -> bool { + let Ok(release) = self.release_envelope.decode() else { + return false; + }; + if self.schema_version != 1 + || self.profile != "decoder_compatible_handoff_v1" + || self.platform != release.manifest.platform + || self.manifest_sha256 != hash(&release.payload_bytes) + || self.activation_floor == 0 + || self.activated_at == 0 + || self + .previous_record_sha256 + .as_ref() + .is_some_and(|v| !digest(v)) + || !self.activation_evidence.validate() + { + return false; + } + match &self.activation_evidence { + ActivationEvidence::Bootstrap { .. } => { + self.previous_record_sha256.is_none() + && !self.rolled_back + && self.activation_floor == release.manifest.release_sequence + } + ActivationEvidence::Updated { .. } => { + self.previous_record_sha256.is_some() + && if self.rolled_back { + self.activation_floor >= release.manifest.release_sequence + } else { + self.activation_floor == release.manifest.release_sequence + } + } + } + } + pub fn bytes(&self) -> Result, &'static str> { + if !self.validate() { + return Err("UPDATE_INSTALLED_RECORD_SHAPE"); + } + let raw = serde_json::to_vec(self).map_err(|_| "UPDATE_INSTALLED_RECORD_CODEC")?; + if raw.len() > MAX_RECORD_BYTES { + return Err("UPDATE_INSTALLED_RECORD_LIMIT"); + } + Ok(raw) + } + pub fn from_bytes(raw: &[u8]) -> Result { + if raw.is_empty() || raw.len() > MAX_RECORD_BYTES { + return Err("UPDATE_INSTALLED_RECORD_LIMIT"); + } + let record: Self = + serde_json::from_slice(raw).map_err(|_| "UPDATE_INSTALLED_RECORD_CODEC")?; + if record.bytes()? != raw { + return Err("UPDATE_INSTALLED_RECORD_NONCANONICAL"); + } + Ok(record) + } +} + +/// Offline release-key signature over BASELINE_SIGNATURE_DOMAIN followed by the +/// exact canonical initial InstalledReleaseRecord bytes. This codec checks no +/// signature. The key must come from independently protected update trust. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SignedBaselineRecord { + pub schema_version: u32, + pub key_id: String, + pub payload_bytes: String, + pub signature: String, +} +pub struct DecodedBaselineRecord { + pub payload_bytes: Vec, + pub signature: [u8; 64], + pub record: InstalledReleaseRecord, +} +impl SignedBaselineRecord { + pub fn decode(&self) -> Result { + if self.schema_version != 1 + || !digest(&self.key_id) + || self.payload_bytes.is_empty() + || self.payload_bytes.len() > 4 * MAX_RECORD_BYTES.div_ceil(3) + || self.signature.len() != 86 + { + return Err("UPDATE_BASELINE_LIMIT"); + } + let raw = URL_SAFE_NO_PAD + .decode(&self.payload_bytes) + .map_err(|_| "UPDATE_BASELINE_CODEC")?; + let signature = URL_SAFE_NO_PAD + .decode(&self.signature) + .map_err(|_| "UPDATE_BASELINE_SIGNATURE")?; + if URL_SAFE_NO_PAD.encode(&raw) != self.payload_bytes + || URL_SAFE_NO_PAD.encode(&signature) != self.signature + { + return Err("UPDATE_BASELINE_NONCANONICAL"); + } + let signature: [u8; 64] = signature + .try_into() + .map_err(|_| "UPDATE_BASELINE_SIGNATURE")?; + let record = InstalledReleaseRecord::from_bytes(&raw)?; + if !matches!( + &record.activation_evidence, + ActivationEvidence::Bootstrap { .. } + ) { + return Err("UPDATE_INITIAL_BASELINE_REQUIRED"); + } + Ok(DecodedBaselineRecord { + payload_bytes: raw, + signature, + record, + }) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct LocalServicePin { + pub unit: String, + /// Same protected unit/drop-in composition digest as the native OS port; + /// not merely the hash of the principal unit file. + pub unit_sha256: String, +} + +/// Local-only protected policy. No member is copied from a model/job/request. +/// Its OWN raw hash is external (UpdaterBinding.policy_sha256); storing that +/// digest inside this document would create a circular hash dependency. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct LocalUpdatePolicy { + pub schema_version: u32, + pub profile: String, + pub tenant_id: Uuid, + pub asset_id: Uuid, + pub agent_id: Uuid, + pub enrollment_generation: u64, + pub assignment_version: u64, + pub ledger_path: String, + pub lock_path: String, + pub installed_record_path: String, + pub keyring_path: String, + pub health_pin_path: String, + pub services: Vec, + pub updater_service: LocalServicePin, + pub updater_binary_sha256: String, + pub initial_baseline: SignedBaselineRecord, + pub initial_record_sha256: String, + pub initial_manifest_sha256: String, + pub initial_activation_floor: u64, +} +impl LocalUpdatePolicy { + pub fn validate(&self) -> bool { + const SERVICES: [&str; 3] = [ + "rmm-agent-remote.service", + "rmm-helper-cloud.service", + "rmm-full-maintenance-helper.service", + ]; + let Ok(baseline) = self.initial_baseline.decode() else { + return false; + }; + let names: Vec<_> = self.services.iter().map(|v| v.unit.as_str()).collect(); + 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" + && (names == SERVICES + || names + == [ + SERVICES[0], + SERVICES[1], + SERVICES[2], + "rmm-apt-helper.service", + ]) + && self.services.iter().all(|v| digest(&v.unit_sha256)) + && self.updater_service.unit == "rmm-agent-updater.service" + && 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 + } + /// Return the parsed policy AND its ORIGINAL raw hash. Config whitespace is + /// not normalized into a different job pin. No authenticity is implied. + pub fn from_bytes(raw: &[u8]) -> Result<(Self, String), &'static str> { + if raw.is_empty() || raw.len() > MAX_POLICY_BYTES { + return Err("UPDATE_LOCAL_POLICY_LIMIT"); + } + let policy: Self = serde_json::from_slice(raw).map_err(|_| "UPDATE_LOCAL_POLICY_CODEC")?; + if !policy.validate() { + return Err("UPDATE_LOCAL_POLICY_SHAPE"); + } + Ok((policy, hash(raw))) + } +} diff --git a/crates/domain/src/inventory_document.rs b/crates/domain/src/inventory_document.rs index 47b15dc..d37e43c 100644 --- a/crates/domain/src/inventory_document.rs +++ b/crates/domain/src/inventory_document.rs @@ -24,6 +24,25 @@ pub fn validate_for_scope( now: DateTime, scope: &str, ) -> Result { + if scope == "agent.update" { + if bytes.len() > 65536 { + return Err("AGENT_UPDATE_INVENTORY_SIZE"); + } + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct UpdateInventory { + agent_update: crate::agent_update::AgentUpdateObservation, + } + let update: UpdateInventory = + serde_json::from_slice(bytes).map_err(|_| "INVALID_AGENT_UPDATE_OBSERVATION")?; + if !update.agent_update.validate() + || update.agent_update.observed_at - now > chrono::Duration::seconds(45) + || now - update.agent_update.observed_at > chrono::Duration::hours(72) + { + return Err("INVALID_AGENT_UPDATE_OBSERVATION"); + } + return serde_json::from_slice(bytes).map_err(|_| "INVALID_AGENT_UPDATE_OBSERVATION"); + } let prefix = match scope { "linux.base" => "linux.", "windows.base" => "windows.", @@ -34,6 +53,31 @@ pub fn validate_for_scope( } let value: Value = serde_json::from_slice(bytes).map_err(|_| "INVALID_INVENTORY_JSON")?; let mut base = value.as_object().cloned().ok_or("INVENTORY_OBJECT")?; + if let Some(update) = base.remove("agent_update") { + // Decode the original bytes as well: Value alone would discard duplicate + // fields before the strict new metadata DTO could reject them. + #[derive(Deserialize)] + struct UpdateField { + agent_update: crate::agent_update::AgentUpdateObservation, + } + let typed: UpdateField = + serde_json::from_slice(bytes).map_err(|_| "INVALID_AGENT_UPDATE_OBSERVATION")?; + if serde_json::to_value(&typed.agent_update) + .map_err(|_| "INVALID_AGENT_UPDATE_OBSERVATION")? + != update + || !typed.agent_update.validate() + || typed.agent_update.platform + != if scope == "linux.base" { + crate::agent_update::Platform::LinuxX64 + } else { + crate::agent_update::Platform::WindowsX64 + } + || typed.agent_update.observed_at - now > chrono::Duration::seconds(45) + || now - typed.agent_update.observed_at > chrono::Duration::hours(72) + { + return Err("INVALID_AGENT_UPDATE_OBSERVATION"); + } + } let observations = base.remove("observations"); let started = base.remove("collection_started_at"); let completed = base.remove("collection_completed_at"); @@ -231,3 +275,51 @@ mod tests { } } } + +#[cfg(test)] +mod agent_update_tests { + use super::*; + use crate::agent_update::{AgentUpdateObservation, Platform}; + #[test] + fn update_scope_is_separate_bounded_strict_and_never_restamps_base_inventory() { + let now = Utc::now(); + let observation = AgentUpdateObservation::not_configured(Platform::LinuxX64, now); + let value = serde_json::json!({"agent_update":observation}); + let bytes = serde_json::to_vec(&value).unwrap(); + assert_eq!( + validate_for_scope(&bytes, now, "agent.update").unwrap(), + value + ); + assert!(validate_for_scope(&bytes, now, "linux.base").is_err()); + let object = serde_json::to_string(&observation).unwrap(); + let duplicate = format!("{{\"agent_update\":{object},\"agent_update\":{object}}}"); + assert!(validate_for_scope(duplicate.as_bytes(), now, "agent.update").is_err()); + let mut false_valid = value.clone(); + false_valid["agent_update"]["quality"] = serde_json::json!("valid"); + assert!( + validate_for_scope( + &serde_json::to_vec(&false_valid).unwrap(), + now, + "agent.update" + ) + .is_err() + ); + let mut mixed = value; + mixed["hostname"] = serde_json::json!("pretend-new-base"); + assert!( + validate_for_scope(&serde_json::to_vec(&mixed).unwrap(), now, "agent.update").is_err() + ); + let future = AgentUpdateObservation::not_configured( + Platform::LinuxX64, + now + chrono::Duration::seconds(46), + ); + assert!( + validate_for_scope( + &serde_json::to_vec(&serde_json::json!({"agent_update":future})).unwrap(), + now, + "agent.update" + ) + .is_err() + ); + } +} diff --git a/crates/domain/src/jobs.rs b/crates/domain/src/jobs.rs index e1a44aa..107b5a7 100644 --- a/crates/domain/src/jobs.rs +++ b/crates/domain/src/jobs.rs @@ -181,6 +181,9 @@ pub enum Action { recipe_version: String, apt_manifest: crate::apt_transaction::AptExecutionManifest, }, + UpdateAgent { + update: Box, + }, Reboot { reason: String, reconnect_timeout_seconds: u32, @@ -198,6 +201,7 @@ impl Action { Self::ApplyUpdates { .. } => "apply_updates", Self::AptNativeAcceptance { .. } => "apt_native_acceptance", Self::Reboot { .. } => "reboot", + Self::UpdateAgent { .. } => "update_agent", } } pub fn validate(&self) -> bool { @@ -334,6 +338,7 @@ impl Action { && recipe_id == &m.resolved_apt_transaction.recipe_id && recipe_version == &m.resolved_apt_transaction.recipe_version } + Self::UpdateAgent { update } => update.validate(), Self::Reboot { reason, reconnect_timeout_seconds, @@ -374,6 +379,9 @@ impl Action { ) } pub fn valid_execution_identity(&self, identity: &str) -> bool { + if let Self::UpdateAgent { update } = self { + return update.execution_identity() == Some(identity); + } !self.full_maintenance() || matches!( (identity, self.script_platform()), @@ -387,6 +395,8 @@ impl Action { /// its inner Event Log calls retain their own cooperative <=5s deadline. pub fn valid_job_limits(&self, runtime_seconds: u32, output_bytes: u32) -> bool { (1..=3600).contains(&runtime_seconds) + && (!matches!(self, Self::UpdateAgent { .. }) + || (runtime_seconds == 600 && output_bytes <= 65536)) && (!self.full_maintenance() || (output_bytes <= 65536 && runtime_seconds @@ -417,7 +427,9 @@ impl Action { /// Shared plan/revalidation/start gate. Passive Windows never implies job support. pub fn available_for(&self, identity: &str, capabilities: &[String]) -> bool { if !self.valid_execution_identity(identity) - || (identity == "system" && !self.valid_helper_denial_shape(identity)) + || (identity == "system" + && !self.valid_helper_denial_shape(identity) + && !matches!(self, Self::UpdateAgent { .. })) { return false; } @@ -436,6 +448,40 @@ impl Action { return false; } match self { + Self::UpdateAgent { update } => { + let linux = update.execution_identity() == Some("root"); + update.validate() + && has(crate::agent_update::APPLY_CAPABILITY) + && has("rmm.sync.v1") + && has(if linux { + "linux.base/1" + } else { + "windows.base/1" + }) + && !has(if linux { + "windows.base/1" + } else { + "linux.base/1" + }) + && has(if linux { + "helper.root.v1" + } else { + "helper.system.v1" + }) + && has(&format!("{}:update_agent", identity)) + && has(&format!( + "updater.binary.sha256:{}", + update.updater.binary_sha256 + )) + && has(&format!( + "updater.policy.sha256:{}", + update.updater.policy_sha256 + )) + && has(&format!( + "helper.binary.sha256:{}", + update.predecessor.helper_sha256 + )) + } Self::RunScript { interpreter, windows_execution_profile, @@ -652,6 +698,10 @@ pub struct ExecutionPermitPayload { pub start_before: DateTime, pub max_runtime_seconds: u32, pub key_id: String, + /// Only update_agent needs its actual plan ID in the local durable handoff. + /// Omitted on every legacy action, preserving original signed grant bytes. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub agent_update_plan_id: Option, } #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "snake_case")] @@ -1190,6 +1240,7 @@ mod tests { let id = Uuid::nil(); let epoch = DateTime::::from_timestamp(0, 0).unwrap(); let p = ExecutionPermitPayload { + agent_update_plan_id: None, domain: "rmm.execution-permit".into(), schema_version: 1, grant_id: id, diff --git a/crates/domain/src/lib.rs b/crates/domain/src/lib.rs index 78a3fd1..e87677c 100644 --- a/crates/domain/src/lib.rs +++ b/crates/domain/src/lib.rs @@ -1,4 +1,6 @@ use serde::{Deserialize, Serialize}; +pub mod agent_update; +pub mod agent_update_provisioning; pub mod apt_transaction; pub mod checkpoint_repair; pub mod inventory_document; diff --git a/crates/domain/src/reconciliation.rs b/crates/domain/src/reconciliation.rs index 68ce0c8..2cb9a80 100644 --- a/crates/domain/src/reconciliation.rs +++ b/crates/domain/src/reconciliation.rs @@ -58,6 +58,8 @@ pub struct AttemptDecision { pub original_boot_id: Option, pub unlock: bool, pub reason: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub update_inflight: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields)] @@ -100,6 +102,21 @@ impl ReconcileDecisionPayload { && self.attempts.len() <= 256 && self.acknowledged_message_ids.len() <= 256 && (!self.helper_ready || self.ready) + && self.attempts.iter().all(|attempt| { + attempt.update_inflight.as_ref().is_none_or(|update| { + !self.ready + && !self.helper_ready + && !attempt.unlock + && attempt.outcome_state == "running" + && attempt.outcome_bytes.is_empty() + && attempt.outcome_sha256.is_none() + && crate::agent_update::digest(&update.handoff_sha256) + && crate::agent_update::digest(&update.delegation_sha256) + && crate::agent_update::digest(&update.head_sha256) + && !update.owner_nonce.is_nil() + && update.finish_before > 0 + }) + }) } } #[cfg(test)] diff --git a/crates/privileged-helper/src/apt/tests.rs b/crates/privileged-helper/src/apt/tests.rs index fc9cb23..6adc490 100644 --- a/crates/privileged-helper/src/apt/tests.rs +++ b/crates/privileged-helper/src/apt/tests.rs @@ -492,6 +492,7 @@ fn signed_request() -> ( }; let bytes = encode(&job).unwrap(); let permit = ExecutionPermitPayload { + agent_update_plan_id: None, domain: "rmm.execution-permit".into(), schema_version: 1, grant_id: Uuid::new_v4(), diff --git a/crates/privileged-helper/src/apt_configured_reconcile.rs b/crates/privileged-helper/src/apt_configured_reconcile.rs index 75b5f0a..b442afc 100644 --- a/crates/privileged-helper/src/apt_configured_reconcile.rs +++ b/crates/privileged-helper/src/apt_configured_reconcile.rs @@ -522,6 +522,7 @@ mod tests { "not_before":now,"start_before":now+chrono::Duration::minutes(15),"max_runtime_seconds":300,"max_output_bytes":65536, "action":{"action":"apt_native_acceptance","recipe_id":apt::INSTALL_RECIPE,"recipe_version":"1","apt_manifest":manifest}})).unwrap(); let permit = ExecutionPermitPayload { + agent_update_plan_id: None, domain: "rmm.execution-permit".into(), schema_version: 1, grant_id: TARGET_GRANT.parse().unwrap(), diff --git a/crates/privileged-helper/src/apt_reconcile.rs b/crates/privileged-helper/src/apt_reconcile.rs index 116654e..9b778e8 100644 --- a/crates/privileged-helper/src/apt_reconcile.rs +++ b/crates/privileged-helper/src/apt_reconcile.rs @@ -716,6 +716,7 @@ mod tests { "not_before":now,"start_before":now+chrono::Duration::minutes(15),"max_runtime_seconds":300,"max_output_bytes":65536})).unwrap(); let job_bytes = encode(&job).unwrap(); let permit = ExecutionPermitPayload { + agent_update_plan_id: None, domain: "rmm.execution-permit".into(), schema_version: 1, grant_id: Uuid::new_v4(), diff --git a/crates/privileged-helper/src/tests.rs b/crates/privileged-helper/src/tests.rs index 8b062d8..634238a 100644 --- a/crates/privileged-helper/src/tests.rs +++ b/crates/privileged-helper/src/tests.rs @@ -44,6 +44,7 @@ fn fixture() -> ( }; let bytes = encode(&job).unwrap(); let permit = ExecutionPermitPayload { + agent_update_plan_id: None, domain: "rmm.execution-permit".into(), schema_version: 1, grant_id: Uuid::new_v4(), diff --git a/crates/privileged-helper/tests/reconcile.rs b/crates/privileged-helper/tests/reconcile.rs index 42f8292..b8bd383 100644 --- a/crates/privileged-helper/tests/reconcile.rs +++ b/crates/privileged-helper/tests/reconcile.rs @@ -160,6 +160,7 @@ impl Fixture { .attempts .iter() .map(|a| AttemptDecision { + update_inflight: None, job_id: a.job_id, attempt_id: a.attempt_id, job_payload_hash: a.job_payload_hash.clone(), @@ -242,6 +243,7 @@ impl Fixture { max_output_bytes: 4096, }; let permit = ExecutionPermitPayload { + agent_update_plan_id: None, domain: "rmm.execution-permit".into(), schema_version: 1, grant_id: Uuid::new_v4(), diff --git a/crates/protocol/src/jobs.rs b/crates/protocol/src/jobs.rs index d62061d..716dae5 100644 --- a/crates/protocol/src/jobs.rs +++ b/crates/protocol/src/jobs.rs @@ -55,6 +55,9 @@ pub struct SyncAttempt { pub outcome_bytes: Vec, #[prost(message, optional, tag = "13")] pub result_envelope: Option, + /// Canonical bounded UpdateInflightProof; empty preserves legacy bytes. + #[prost(bytes = "vec", tag = "14")] + pub update_handoff_bytes: Vec, } #[derive(Clone, PartialEq, Message)] pub struct SyncResponse { diff --git a/crates/server/Cargo.toml b/crates/server/Cargo.toml index 2cb6848..4a4616d 100644 --- a/crates/server/Cargo.toml +++ b/crates/server/Cargo.toml @@ -31,3 +31,9 @@ async-trait = "0.1" secrecy = "0.10" url = { version = "2", features = ["serde"] } reqwest.workspace = true +rmm-updater = { path = "../updater" } +base64 = "0.22.1" +futures-util.workspace = true +libc = "0.2" + +rmm-updater-handoff = { path = "../updater-handoff" } diff --git a/crates/server/src/agent_service.rs b/crates/server/src/agent_service.rs index 837da5a..7c75dc9 100644 --- a/crates/server/src/agent_service.rs +++ b/crates/server/src/agent_service.rs @@ -145,8 +145,10 @@ pub async fn ingest( } Some(Payload::InventorySnapshot(s)) => { ensure!( - matches!(s.scope.as_str(), "linux.base" | "windows.base") - && s.schema_version == 1 + matches!( + s.scope.as_str(), + "linux.base" | "windows.base" | "agent.update" + ) && s.schema_version == 1 && s.chunk_count == 1 && s.chunk_index == 0 && s.completeness == "partial" diff --git a/crates/server/src/agent_update_health.rs b/crates/server/src/agent_update_health.rs new file mode 100644 index 0000000..d8e9a99 --- /dev/null +++ b/crates/server/src/agent_update_health.rs @@ -0,0 +1,595 @@ +//! Evidence for one original update, never admission, approval or readiness. +//! +//! The server checks its retained job, signed control history and inventory. +//! Concrete local file/process/ledger observations still require the separately +//! authenticated helper guard; device mTLS is not OS attestation. +use crate::jobs::Error; +use axum::{ + Extension, Json, Router, + extract::{DefaultBodyLimit, State}, + http::{HeaderMap, StatusCode}, + routing::post, +}; +use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; +use chrono::{DateTime, Utc}; +use openssl::{ + pkey::{Id, PKey, Private}, + sign::{Signer, Verifier}, +}; +use prost::Message; +use rmm_domain::{ + agent_update::{self as update, UpdateInflightProof}, + jobs::{Action, ExecutionPermitPayload, JobPayload, PlanPayload, encode, hash}, + reconciliation::ReconcileDecisionPayload, +}; +use rmm_protocol::{Envelope, Payload, SyncRequest, SyncResponse}; +use rmm_updater_handoff::{Event, Evidence, HEALTH_DOMAIN, HealthReceipt, Phase, SignedHealth}; +use serde::Deserialize; +use serde_json::{Value, json}; +use sqlx::{Postgres, Row, Transaction}; +use std::path::Path; +use uuid::Uuid; + +const RAW_LIMIT: usize = rmm_domain::MAX_MESSAGE; +const ENCODED_LIMIT: usize = 4 * RAW_LIMIT.div_ceil(3); + +fn denied() -> Error { + Error(StatusCode::CONFLICT, "AGENT_UPDATE_HEALTH_UNPROVEN") +} +fn require(ok: bool) -> Result<(), Error> { + if !ok { + return Err(denied()); + } + Ok(()) +} + +pub fn gateway_routes(router: Router) -> Router { + router.route( + "/agent/v1/update-health", + post(issue).layer(DefaultBodyLimit::max(5 * 1024 * 1024)), + ) +} + +/// Canonical original bytes, not caller-selected health fields or timestamps. +/// The confirming request must already be retained by the normal sync route; +/// both its previous-decision links attest application of the earlier control. +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct HealthRequest { + proof: UpdateInflightProof, + applied_sync_request_base64url: String, + confirming_sync_request_base64url: String, + inventory_envelope_base64url: String, +} + +fn message(encoded: &str) -> Result<(M, Vec), Error> { + require(!encoded.is_empty() && encoded.len() <= ENCODED_LIMIT)?; + let raw = URL_SAFE_NO_PAD.decode(encoded).map_err(|_| denied())?; + require(!raw.is_empty() && raw.len() <= RAW_LIMIT && URL_SAFE_NO_PAD.encode(&raw) == encoded)?; + let value = M::decode(raw.as_slice()).map_err(|_| denied())?; + // No duplicate fields, hidden unknown fields or alternate protobuf bytes. + require(value.encode_to_vec() == raw)?; + Ok((value, raw)) +} + +fn health_signer() -> Result, Error> { + let path = std::env::var("RMM_AGENT_UPDATE_HEALTH_KEY_FILE").map_err(|_| denied())?; + require(Path::new(&path).is_absolute())?; + let raw = crate::agent_updates::protected_file(Path::new(&path), 16384)?; + let key = PKey::private_key_from_pem(&raw).map_err(|_| denied())?; + require(key.id() == Id::ED25519)?; + Ok(key) +} + +/// Separately provisioned health key. Never generated or learned from a job, +/// request, release, receipt or device. The original job's public identity is +/// compared below; it never supplies the signing key itself. +fn public_key(signer: &PKey) -> Result<[u8; 32], Error> { + signer + .raw_public_key() + .map_err(|_| denied())? + .try_into() + .map_err(|_| denied()) +} + +fn verify_job_signature(state: &crate::State, raw: &[u8], signature: &[u8]) -> Result<(), Error> { + let public = PKey::public_key_from_raw_bytes(&state.job_signer.public_key()?, Id::ED25519) + .map_err(|_| denied())?; + require( + signature.len() == 64 + && Verifier::new_without_digest(&public) + .map_err(|_| denied())? + .verify_oneshot(signature, raw) + .map_err(|_| denied())?, + ) +} + +struct StoredSync { + decision: ReconcileDecisionPayload, + response: Vec, + created_at: DateTime, +} + +async fn stored_sync( + state: &crate::State, + tx: &mut Transaction<'_, Postgres>, + agent: Uuid, + request: &SyncRequest, + raw: &[u8], + now: DateTime, +) -> Result { + let id = Uuid::parse_str(&request.request_id).map_err(|_| denied())?; + let row = sqlx::query("SELECT payload,signature,request_hash,created_at FROM sync_checkpoints WHERE agent_id=$1 AND request_id=$2") + .bind(agent).bind(id).fetch_optional(&mut **tx).await?.ok_or_else(denied)?; + let bytes: Vec = row.get("payload"); + let signature: Vec = row.get("signature"); + require(bytes.len() <= 512 * 1024 && row.get::("request_hash") == hash(raw))?; + verify_job_signature(state, &bytes, &signature)?; + let decision: ReconcileDecisionPayload = serde_json::from_slice(&bytes)?; + require( + encode(&decision)? == bytes + && decision.valid_profile(now) + && decision.key_id == state.job_signer.key_id + && decision.request_id == id + && decision.request_hash == hash(raw) + && decision.journal_id.to_string() == request.journal_id + && decision.checkpoint == request.checkpoint + && decision + .helper_journal_id + .map(|id| id.to_string()) + .as_deref() + == Some(request.helper_journal_id.as_str()) + && decision.helper_checkpoint == request.helper_checkpoint + && request.journal_complete, + )?; + Ok(StoredSync { + decision, + response: SyncResponse { + decision_bytes: bytes, + signature, + } + .encode_to_vec(), + created_at: row.get("created_at"), + }) +} + +fn confirming_application(request: &SyncRequest, prior: &ReconcileDecisionPayload) -> bool { + request.previous_request_id.is_empty() + && request.previous_decision_id == prior.decision_id.to_string() + && request.helper_previous_decision_id == prior.decision_id.to_string() + && request.journal_id == prior.journal_id.to_string() + && request.helper_journal_id + == prior + .helper_journal_id + .map(|id| id.to_string()) + .unwrap_or_default() + && request.checkpoint > prior.checkpoint + && request.helper_checkpoint > prior.helper_checkpoint +} + +fn exact_prefix( + request: &SyncRequest, + decision: &ReconcileDecisionPayload, + proof: &UpdateInflightProof, + header: &rmm_updater_handoff::Handoff, + health_key: [u8; 32], +) -> Result<(), Error> { + let job = header.attempt.job_id; + let attempt = header.attempt.attempt_id; + let local = request + .attempts + .iter() + .filter(|a| a.job_id == job.to_string() && a.attempt_id == attempt.to_string()) + .collect::>(); + let signed = decision + .attempts + .iter() + .filter(|a| a.job_id == job && a.attempt_id == attempt) + .collect::>(); + require(local.len() == 1 && signed.len() == 1 && !decision.ready && !decision.helper_ready)?; + let local = local[0]; + let signed = signed[0]; + let expected = update::inflight_decision(proof, health_key).map_err(|_| denied())?; + require( + local.update_handoff_bytes == proof.bytes().map_err(|_| denied())? + && local.job_payload_hash == header.attempt.job_payload_sha256 + && local.grant_id == header.attempt.grant_id.to_string() + && local.consumption == "consumed" + && local.state == "running" + && local.original_boot_id == header.boot_id.to_string() + && local.outcome_bytes.is_empty() + && local.outcome_sha256.is_empty() + && local.result.is_none() + && local.result_envelope.is_none() + && signed.update_inflight.as_ref() == Some(&expected) + && signed.grant_id == Some(header.attempt.grant_id) + && signed.authorization_id == Some(header.attempt.authorization_id) + && signed.plan_hash.as_deref() == Some(header.attempt.plan_sha256.as_str()) + && signed.job_payload_hash == header.attempt.job_payload_sha256 + && signed.action == "update_agent" + && signed.outcome_state == "running" + && !signed.unlock + && signed.outcome_bytes.is_empty() + && signed.outcome_sha256.is_none() + && request.attempts.iter().all(|a| { + (a.job_id == job.to_string() && a.attempt_id == attempt.to_string()) + || a.update_handoff_bytes.is_empty() + }) + && decision.attempts.iter().all(|a| { + (a.job_id == job && a.attempt_id == attempt) + || (a.update_inflight.is_none() + && matches!( + a.outcome_state.as_str(), + "accepted" | "succeeded" | "failed" | "cancelled" | "expired" + )) + }), + ) +} + +async fn issue( + State(state): State, + Extension(peer): Extension, + headers: HeaderMap, + Json(input): Json, +) -> Result, Error> { + require(!headers.contains_key("authorization"))?; + let (tenant, agent) = crate::agent_http::identity(&state, peer) + .await + .map_err(|status| Error(status, "DEVICE_MTLS_REQUIRED"))?; + let signer = health_signer()?; + let health_public = public_key(&signer)?; + require(health_public.as_slice() != state.job_signer.public_key()?.as_slice())?; + 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 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 started_at = last.observed_at; + let (applied_request, applied_raw) = + message::(&input.applied_sync_request_base64url)?; + let (confirming_request, confirming_raw) = + message::(&input.confirming_sync_request_base64url)?; + let (inventory, _) = message::(&input.inventory_envelope_base64url)?; + let now = Utc::now(); + let seconds = u64::try_from(now.timestamp()).map_err(|_| denied())?; + require( + header.attempt.tenant_id == tenant + && header.attempt.agent_id == agent + && header.finish_before == header.consumed_at.checked_add(600).ok_or_else(denied)? + && started_at >= header.consumed_at + && started_at <= seconds + && seconds < header.finish_before + && seconds - started_at < 180, + )?; + let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant).await?; + crate::agent_service::control_lock(&mut tx, tenant, agent).await?; + let row = 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.payload AS permit_payload,g.signature AS permit_signature,i.asset_id,i.enrollment_generation,i.assignment_version,i.connection_generation,i.connection_boot_id,i.sync_ready,i.helper_sync_ready,i.sequence_regressed,i.sync_recovery_required,s.journal_id,s.helper_journal_id,s.decision_id,s.checkpoint,s.helper_checkpoint 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 JOIN agent_installations i ON i.tenant_id=j.tenant_id AND i.agent_id=j.agent_id JOIN agent_sync_state s ON s.tenant_id=i.tenant_id AND s.agent_id=i.agent_id WHERE j.tenant_id=$1 AND j.agent_id=$2 AND j.job_id=$3 AND j.attempt_id=$4 AND g.grant_id=$5 AND a.approval_state='approved' AND z.revoked_at IS NULL AND i.revoked_at IS NULL FOR SHARE OF j,i,z") + .bind(tenant).bind(agent).bind(header.attempt.job_id).bind(header.attempt.attempt_id).bind(header.attempt.grant_id) + .fetch_optional(&mut *tx).await?.ok_or_else(denied)?; + require( + matches!( + row.get::("state").as_str(), + "running" | "verifying" + ) && row.get::, _>("result").is_none() + && !row.get::("cancel_requested") + && row.get::("start_reserved") + && !row.get::("sync_ready") + && !row.get::("helper_sync_ready") + && !row.get::("sequence_regressed") + && !row.get::("sync_recovery_required") + && row.get::("asset_id") == header.attempt.asset_id + && row.get::("enrollment_generation") + == i64::try_from(header.attempt.enrollment_generation).map_err(|_| denied())? + && row.get::("assignment_version") + == i64::try_from(header.attempt.assignment_version).map_err(|_| denied())? + && row.get::, _>("connection_boot_id") == Some(header.boot_id) + && row.get::("journal_id") == header.agent_journal_id + && row.get::, _>("helper_journal_id") == Some(header.helper_journal_id), + )?; + let generation = + u64::try_from(row.get::("connection_generation")).map_err(|_| denied())?; + require(generation > header.connection_generation)?; + let job_bytes: Vec = row.get("payload"); + let job: JobPayload = serde_json::from_slice(&job_bytes)?; + let Action::UpdateAgent { update: action } = &job.action else { + return Err(denied()); + }; + require( + action.validate() + && update::handoff_matches_job(&header, &job) + && action.updater.health_public_key_hex == hex::encode(health_public) + && hash(&job_bytes) == row.get::("payload_hash") + && action.release_envelope.key_id != health_key_id, + )?; + let plan_bytes: Vec = row.get("plan_payload"); + let plan: PlanPayload = serde_json::from_slice(&plan_bytes)?; + crate::agent_updates::validate_job_binding(&plan, &job)?; + require( + hash(&plan_bytes) == row.get::("plan_hash") + && hash(&plan_bytes) == header.attempt.plan_sha256 + && plan.plan_id == header.attempt.plan_id + && row.get::("plan_id") == plan.plan_id + && row.get::("authorization_id") == header.attempt.authorization_id, + )?; + let permission = + crate::root_policy::execution_permission(&job.execution_identity).ok_or_else(denied)?; + let approver: String = row.get("approver"); + for principal in [&plan.principal, &approver] { + crate::permissions::require(&mut tx, principal, "updates:apply").await?; + crate::permissions::require(&mut tx, principal, permission).await?; + } + let permit_bytes: Vec = row.get("permit_payload"); + let permit_signature: Vec = row.get("permit_signature"); + verify_job_signature(&state, &permit_bytes, &permit_signature)?; + let permit: ExecutionPermitPayload = serde_json::from_slice(&permit_bytes)?; + let original = update::OriginalHelperRequest { + job_bytes: &job_bytes, + permit_bytes: &permit_bytes, + signature: &permit_signature, + plan_hash: &permit.plan_hash, + authorization_id: permit.authorization_id, + }; + require( + permit.domain == "rmm.execution-permit" + && permit.schema_version == 1 + && permit.key_id == state.job_signer.key_id + && permit.agent_update_plan_id == Some(plan.plan_id) + && permit.tenant_id == tenant + && permit.asset_id == header.attempt.asset_id + && permit.agent_id == agent + && permit.enrollment_generation == header.attempt.enrollment_generation + && permit.assignment_version == header.attempt.assignment_version + && permit.job_id == header.attempt.job_id + && permit.attempt_id == header.attempt.attempt_id + && permit.execution_identity == job.execution_identity + && permit.grant_id == header.attempt.grant_id + && permit.authorization_id == header.attempt.authorization_id + && permit.plan_hash == header.attempt.plan_sha256 + && permit.job_payload_hash == hash(&job_bytes) + && permit.action == "update_agent" + && permit.max_runtime_seconds == 600 + && input.proof.delegation.prepared_at >= permit.not_before + && input.proof.delegation.prepared_at < permit.start_before + && hash(&encode(&original)?) == header.attempt.original_request_sha256, + )?; + let applied = stored_sync(&state, &mut tx, agent, &applied_request, &applied_raw, now).await?; + let confirming = stored_sync( + &state, + &mut tx, + agent, + &confirming_request, + &confirming_raw, + now, + ) + .await?; + require( + confirming_application(&confirming_request, &applied.decision) + && row.get::("decision_id") == confirming.decision.decision_id + && row.get::("checkpoint") + == i64::try_from(confirming.decision.checkpoint).map_err(|_| denied())? + && row.get::("helper_checkpoint") + == i64::try_from(confirming.decision.helper_checkpoint).map_err(|_| denied())?, + )?; + for (request, saved) in [ + (&applied_request, &applied), + (&confirming_request, &confirming), + ] { + let decision = &saved.decision; + require( + decision.tenant_id == tenant + && decision.asset_id == header.attempt.asset_id + && decision.agent_id == agent + && decision.enrollment_generation == header.attempt.enrollment_generation + && decision.assignment_version == header.attempt.assignment_version + && request.assignment_version == header.attempt.assignment_version + && decision.boot_id == header.boot_id + && decision.connection_generation == generation + && decision.journal_id == header.agent_journal_id + && decision.helper_journal_id == Some(header.helper_journal_id) + && u64::try_from(decision.issued_at.timestamp()).map_err(|_| denied())? + >= started_at + && u64::try_from(saved.created_at.timestamp()).map_err(|_| denied())? >= started_at, + )?; + exact_prefix(request, decision, &input.proof, &header, health_public)?; + } + let Payload::InventorySnapshot(snapshot) = inventory.payload.as_ref().ok_or_else(denied)? + else { + return Err(denied()); + }; + require( + inventory.protocol_major == 1 + && inventory.agent_id == agent.to_string() + && inventory.enrollment_generation == header.attempt.enrollment_generation + && inventory.connection_generation == generation + && inventory.boot_id == header.boot_id.to_string() + && inventory.sequence > 0 + && snapshot.schema_version == 1 + && snapshot.chunk_count == 1 + && snapshot.chunk_index == 0 + && snapshot.completeness == "partial" + && snapshot.data.len() <= 512 * 1024 + && snapshot.sha256 == hex::decode(hash(&snapshot.data)).map_err(|_| denied())?, + )?; + let scope = match action.manifest().map_err(|_| denied())?.platform { + update::Platform::LinuxX64 => "linux.base", + update::Platform::WindowsX64 => "windows.base", + }; + // Health requires a fresh real base inventory of the restarted platform; + // a not_configured update observation cannot stand in for that evidence. + require(snapshot.scope == scope)?; + let inventory_data = + rmm_domain::inventory_document::validate_for_scope(&snapshot.data, now, &snapshot.scope) + .map_err(|_| denied())?; + let mut normalized = inventory.clone(); + normalized.connection_generation = 0; + let inventory_hash = hash(&normalized.encode_to_vec()); + let inventory_row = sqlx::query("SELECT message_id,observed_at,received_at,source_id,quality,completeness,data FROM observations WHERE tenant_id=$1 AND agent_id=$2 AND boot_id=$3 AND message_id=ANY($4) AND payload_sha256=$5") + .bind(tenant).bind(agent).bind(header.boot_id).bind(&applied.decision.acknowledged_message_ids).bind(&inventory_hash) + .fetch_all(&mut *tx).await?; + require(inventory_row.len() == 1)?; + let inventory_row = &inventory_row[0]; + let inventory_id: Uuid = inventory_row.get("message_id"); + let observed: DateTime = inventory_row.get("observed_at"); + let received: DateTime = inventory_row.get("received_at"); + require( + inventory.message_id == inventory_id.to_string() + && inventory.observed_at == observed.timestamp_millis() + && inventory_row.get::("source_id") == snapshot.scope + && inventory_row.get::("quality") == "valid" + && inventory_row.get::("completeness") == "partial" + && inventory_row.get::("data") == inventory_data + && observed <= received + && received <= applied.created_at + && u64::try_from(observed.timestamp()).map_err(|_| denied())? >= started_at + && u64::try_from(received.timestamp()).map_err(|_| denied())? >= started_at, + )?; + // All IDs/timestamps below come from the verified retained records. The + // confirming server round is an upper bound on actual local apply time, + // not a claim to have remotely observed a local clock or OS process. + let issued_at = u64::try_from(Utc::now().timestamp()).map_err(|_| denied())?; + let valid_until = header + .finish_before + .min(started_at.checked_add(180).ok_or_else(denied)?) + .min(u64::try_from(applied.decision.valid_until.timestamp()).map_err(|_| denied())?) + .min(u64::try_from(confirming.decision.valid_until.timestamp()).map_err(|_| denied())?); + require(issued_at < valid_until)?; + let receipt = HealthReceipt { + schema_version: 1, + handoff_sha256: input.proof.delegation.handoff_sha256.clone(), + owner_nonce: header.owner_nonce, + boot_id: header.boot_id, + helper_journal_id: header.helper_journal_id, + agent_journal_id: header.agent_journal_id, + connection_generation: generation, + service_processes: services.clone(), + ledger_identity_sha256: header.ledger_identity_sha256.clone(), + signed_sync_decision_id: applied.decision.decision_id, + signed_sync_request_sha256: hash(&applied_raw), + signed_sync_response_sha256: hash(&applied.response), + signed_sync_applied_at: u64::try_from(confirming.decision.issued_at.timestamp()) + .map_err(|_| denied())?, + ready: false, + inventory_message_id: inventory_id, + inventory_received_at: u64::try_from(received.timestamp()).map_err(|_| denied())?, + inventory_ack_sha256: hash(&applied.response), + issued_at, + valid_until, + }; + let witness_hash = hash(&encode(&( + input.proof.head_sha256.as_str(), + hash(&applied_raw), + 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?; + if let Some(cached) = cached { + require( + cached["witness_sha256"] == witness_hash && cached["health_key_id"] == health_key_id, + )?; + let original: SignedHealth = serde_json::from_value(cached["receipt"].clone())?; + journal + .prepare( + issued_at, + Evidence::HealthVerified { + receipt: original.clone(), + }, + ) + .map_err(|_| denied())?; + tx.commit().await?; + return Ok(Json(original)); + } + let payload = encode(&receipt)?; + require(payload.len() <= 4096)?; + let mut message = HEALTH_DOMAIN.to_vec(); + message.extend_from_slice(&payload); + let signature = Signer::new_without_digest(&signer) + .map_err(|_| denied())? + .sign_oneshot_to_vec(&message) + .map_err(|_| denied())?; + let signed = SignedHealth { payload, signature }; + // Reuse the exact pure kernel verification before publishing any receipt; + // prepare is read-only and does not append a local event or mutate a job. + journal + .prepare( + issued_at, + Evidence::HealthVerified { + receipt: signed.clone(), + }, + ) + .map_err(|_| denied())?; + sqlx::query("INSERT INTO audit_events(tenant_id,event_id,principal,event_type,data) VALUES($1,$2,$3,'agent_update_health',$4)") + .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})) + .execute(&mut *tx).await?; + tx.commit().await?; + Ok(Json(signed)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn original_protobuf_bytes_are_bounded_and_canonical() { + let request = SyncRequest { + request_id: Uuid::new_v4().to_string(), + ..Default::default() + }; + let raw = request.encode_to_vec(); + assert!(message::(&URL_SAFE_NO_PAD.encode(&raw)).is_ok()); + let mut duplicate = raw.clone(); + duplicate.extend_from_slice(&raw); + assert!(message::(&URL_SAFE_NO_PAD.encode(duplicate)).is_err()); + assert!(message::("").is_err()); + assert!(message::(&"A".repeat(ENCODED_LIMIT + 1)).is_err()); + assert!(message::(&format!("{}=", URL_SAFE_NO_PAD.encode(raw))).is_err()); + } + + #[test] + fn pending_request_or_agent_only_ack_never_proves_helper_application() { + let decision_id = Uuid::new_v4(); + let agent_journal = Uuid::new_v4(); + let helper_journal = Uuid::new_v4(); + let prior: ReconcileDecisionPayload = serde_json::from_value(json!({ + "domain":"rmm.reconciliation-decision", "schema_version":1, + "decision_id":decision_id, "request_id":Uuid::new_v4(), "request_hash":"ab".repeat(32), + "tenant_id":Uuid::new_v4(), "asset_id":Uuid::new_v4(), "agent_id":Uuid::new_v4(), + "enrollment_generation":1, "assignment_version":1, "connection_generation":2, + "boot_id":Uuid::new_v4(), "journal_id":agent_journal, "checkpoint":10, + "helper_journal_id":helper_journal, "helper_checkpoint":20, + "issued_at":"2026-11-14T12:00:00Z", "valid_until":"2026-11-14T12:01:00Z", + "ready":false, "helper_ready":false, "reason":"AGENT_UPDATE_INFLIGHT", + "attempts":[], "acknowledged_message_ids":[], "key_id":"cd".repeat(32) + })) + .unwrap(); + let original = SyncRequest { + previous_decision_id: decision_id.to_string(), + helper_previous_decision_id: decision_id.to_string(), + journal_id: agent_journal.to_string(), + helper_journal_id: helper_journal.to_string(), + checkpoint: 11, + helper_checkpoint: 21, + ..Default::default() + }; + assert!(confirming_application(&original, &prior)); + let mut only_agent = original.clone(); + only_agent.helper_previous_decision_id.clear(); + assert!(!confirming_application(&only_agent, &prior)); + let mut pending = original.clone(); + pending.previous_request_id = prior.request_id.to_string(); + assert!(!confirming_application(&pending, &prior)); + let mut stale_helper = original.clone(); + stale_helper.helper_checkpoint = prior.helper_checkpoint; + assert!(!confirming_application(&stale_helper, &prior)); + let mut replaced_helper = original; + replaced_helper.helper_journal_id = Uuid::new_v4().to_string(); + assert!(!confirming_application(&replaced_helper, &prior)); + } +} diff --git a/crates/server/src/agent_update_policy.rs b/crates/server/src/agent_update_policy.rs new file mode 100644 index 0000000..7680c2b --- /dev/null +++ b/crates/server/src/agent_update_policy.rs @@ -0,0 +1,180 @@ +//! Separate deny-only opt-in. Legacy Root/SCM/MSI/script policies grant no update. +use crate::jobs::Error; +use axum::http::StatusCode; +use chrono::{DateTime, Utc}; +use rmm_domain::{ + agent_update::{ResolvedAgentUpdate, digest}, + jobs::{Action, JobPayload}, +}; +use serde::Deserialize; +use sqlx::{Postgres, Transaction}; +use uuid::Uuid; + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Policy { + schema_version: u32, + profile: String, + expires_at: DateTime, + scopes: Vec, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Scope { + tenant_id: Uuid, + asset_id: Uuid, + agent_id: Uuid, + enrollment_generation: u64, + assignment_version: u64, + principals: Vec, + helper_policy_sha256: String, + helper_binary_sha256: String, + updater_binary_sha256: String, + updater_policy_sha256: String, + keyring_generation: u64, + keyring_sha256: String, + health_public_key_hex: String, + health_key_pin_sha256: String, + allowed_manifest_sha256: Vec, + allowed_predecessor_record_sha256: Vec, + acceptance_evidence_id: String, +} +impl Scope { + fn valid(&self) -> bool { + !self.tenant_id.is_nil() + && !self.asset_id.is_nil() + && !self.agent_id.is_nil() + && self.enrollment_generation > 0 + && self.assignment_version > 0 + && self.keyring_generation > 0 + && !self.principals.is_empty() + && self.principals.len() <= 16 + && self + .principals + .iter() + .all(|p| !p.is_empty() && p.len() <= 256) + && [ + &self.helper_policy_sha256, + &self.helper_binary_sha256, + &self.updater_binary_sha256, + &self.updater_policy_sha256, + &self.keyring_sha256, + &self.health_public_key_hex, + &self.health_key_pin_sha256, + ] + .iter() + .all(|h| digest(h)) + && [ + &self.allowed_manifest_sha256, + &self.allowed_predecessor_record_sha256, + ] + .iter() + .all(|list| { + !list.is_empty() + && list.len() <= 16 + && list.iter().all(|h| digest(h)) + && list.iter().collect::>().len() == list.len() + }) + && !self.acceptance_evidence_id.trim().is_empty() + && self.acceptance_evidence_id.len() <= 512 + } + fn permits( + &self, + principal: &str, + job: &JobPayload, + update: &ResolvedAgentUpdate, + caps: &[String], + ) -> bool { + if !self.valid() + || !update.validate() + || !job.action.available_for(&job.execution_identity, caps) + || !job + .action + .valid_job_limits(job.max_runtime_seconds, job.max_output_bytes) + || update.execution_identity() != Some(job.execution_identity.as_str()) + || self.tenant_id != job.tenant_id + || self.asset_id != job.asset_id + || self.agent_id != job.agent_id + || self.enrollment_generation != job.enrollment_generation + || self.assignment_version != job.assignment_version + || !self.principals.iter().any(|p| p == principal) + || self.helper_binary_sha256 != update.predecessor.helper_sha256 + || self.updater_binary_sha256 != update.updater.binary_sha256 + || self.updater_policy_sha256 != update.updater.policy_sha256 + || self.keyring_generation != update.updater.keyring_generation + || self.keyring_sha256 != update.updater.keyring_sha256 + || self.health_public_key_hex != update.updater.health_public_key_hex + || self.health_key_pin_sha256 != update.updater.health_key_pin_sha256 + || !self + .allowed_manifest_sha256 + .contains(&update.manifest_sha256) + || !self + .allowed_predecessor_record_sha256 + .contains(&update.predecessor.installed_record_sha256) + { + return false; + } + let helper = match job.execution_identity.as_str() { + "root" => "helper.root.v1", + "system" => "helper.system.v1", + _ => return false, + }; + [ + "update_agent".into(), + "agent.update.apply/1".into(), + "rmm.sync.v1".into(), + helper.into(), + format!("{}:update_agent", job.execution_identity), + format!("helper.policy.sha256:{}", self.helper_policy_sha256), + format!("helper.binary.sha256:{}", self.helper_binary_sha256), + format!("updater.binary.sha256:{}", self.updater_binary_sha256), + format!("updater.policy.sha256:{}", self.updater_policy_sha256), + ] + .iter() + .all(|needed| caps.contains(needed)) + } +} +pub async fn authorize( + tx: &mut Transaction<'_, Postgres>, + principal: &str, + job: &JobPayload, +) -> Result<(), Error> { + let Action::UpdateAgent { update } = &job.action else { + return Err(Error(StatusCode::FORBIDDEN, "AGENT_UPDATE_POLICY_DENIED")); + }; + let identity = crate::root_policy::execution_permission(&job.execution_identity) + .ok_or(Error(StatusCode::FORBIDDEN, "EXECUTION_IDENTITY_DENIED"))?; + crate::permissions::require(tx, principal, identity).await?; + crate::permissions::require(tx, principal, "updates:apply").await?; + if std::env::var("RMM_PROFILE").as_deref() != Ok("development") { + return Err(Error(StatusCode::CONFLICT, "AGENT_UPDATE_NOT_CONFIGURED")); + } + let path = std::env::var("RMM_AGENT_UPDATE_POLICY_FILE") + .map_err(|_| Error(StatusCode::CONFLICT, "AGENT_UPDATE_NOT_CONFIGURED"))?; + let raw = crate::agent_updates::protected_file(std::path::Path::new(&path), 65536)?; + let policy: Policy = serde_json::from_slice(&raw) + .map_err(|_| Error(StatusCode::CONFLICT, "AGENT_UPDATE_POLICY_INVALID"))?; + if policy.schema_version != 1 + || policy.profile != "development" + || policy.expires_at <= Utc::now() + || policy.scopes.is_empty() + || policy.scopes.len() > 64 + || policy.scopes.iter().any(|s| !s.valid()) + { + return Err(Error(StatusCode::CONFLICT, "AGENT_UPDATE_POLICY_DENIED")); + } + let caps:serde_json::Value=sqlx::query_scalar("SELECT capabilities FROM agent_installations WHERE agent_id=$1 AND asset_id=$2 AND revoked_at IS NULL AND enrollment_generation=$3 AND assignment_version=$4") + .bind(job.agent_id).bind(job.asset_id).bind(i64::try_from(job.enrollment_generation).map_err(|_|Error(StatusCode::CONFLICT,"BINDING_MISMATCH"))?) + .bind(i64::try_from(job.assignment_version).map_err(|_|Error(StatusCode::CONFLICT,"BINDING_MISMATCH"))?).fetch_optional(&mut **tx).await?.ok_or(Error(StatusCode::CONFLICT,"AUTHORIZATION_REVOKED"))?; + let caps: Vec = serde_json::from_value(caps)?; + if !policy + .scopes + .iter() + .any(|scope| scope.permits(principal, job, update, &caps)) + { + return Err(Error(StatusCode::FORBIDDEN, "AGENT_UPDATE_POLICY_DENIED")); + } + crate::agent_updates::check_update(tx, update).await?; + crate::agent_updates::validate_current_target(tx, job).await?; + Ok(()) +} diff --git a/crates/server/src/agent_updates.rs b/crates/server/src/agent_updates.rs new file mode 100644 index 0000000..f526c54 --- /dev/null +++ b/crates/server/src/agent_updates.rs @@ -0,0 +1,873 @@ +//! Tenant release publication and update-only bounded object transport. +//! Catalog metadata and passive checks never create/approve an execution job. +use crate::{ + jobs::Error, + update_artifact_store::{MAX_CHUNK_BYTES, UpdateArtifacts}, +}; +use axum::{ + Extension, Json, Router, + body::Body, + extract::{Path, Query, State}, + http::{HeaderMap, HeaderValue, StatusCode}, + response::{IntoResponse, Response}, + routing::{get, post}, +}; +use futures_util::StreamExt; +use rmm_domain::{ + agent_update::{ArtifactDescriptor, Platform, ReleaseEnvelope, ReleaseManifest}, + jobs::{ArtifactReference, encode, hash}, +}; +use serde::Deserialize; +use serde_json::{Value, json}; +use sqlx::{Postgres, Row, Transaction}; +use std::{ + fs, + io::Read, + os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt}, + path::Path as FsPath, + time::{Duration, Instant}, +}; +use uuid::Uuid; + +fn fail(code: &'static str) -> Error { + Error(StatusCode::CONFLICT, code) +} +fn missing() -> Error { + Error(StatusCode::NOT_FOUND, "NOT_FOUND") +} +fn invalid() -> Error { + Error(StatusCode::BAD_REQUEST, "INVALID_AGENT_RELEASE") +} +pub fn platform_name(platform: Platform) -> &'static str { + match platform { + Platform::LinuxX64 => "x86_64-unknown-linux-gnu", + Platform::WindowsX64 => "x86_64-pc-windows-msvc", + } +} +pub fn protected_file(path: &FsPath, maximum: u64) -> Result, Error> { + let key_path = + std::env::var("RMM_JOB_KEY_FILE").map_err(|_| fail("AGENT_UPDATE_NOT_CONFIGURED"))?; + let key_meta = + fs::symlink_metadata(key_path).map_err(|_| fail("AGENT_UPDATE_NOT_CONFIGURED"))?; + if !key_meta.is_file() || key_meta.mode() & 0o077 != 0 { + return Err(fail("AGENT_UPDATE_NOT_CONFIGURED")); + } + let owner = key_meta.uid(); + let mut file = fs::OpenOptions::new() + .read(true) + .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC) + .open(path) + .map_err(|_| fail("AGENT_UPDATE_NOT_CONFIGURED"))?; + let m = file + .metadata() + .map_err(|_| fail("AGENT_UPDATE_NOT_CONFIGURED"))?; + let parent = fs::symlink_metadata( + path.parent() + .ok_or_else(|| fail("AGENT_UPDATE_NOT_CONFIGURED"))?, + ) + .map_err(|_| fail("AGENT_UPDATE_NOT_CONFIGURED"))?; + if !m.is_file() + || m.uid() != owner + || m.mode() & 0o777 != 0o600 + || m.nlink() != 1 + || m.len() == 0 + || m.len() > maximum + || !parent.is_dir() + || parent.uid() != owner + || parent.permissions().mode() & 0o022 != 0 + { + return Err(fail("AGENT_UPDATE_NOT_CONFIGURED")); + } + let mut raw = Vec::new(); + (&mut file) + .take(maximum + 1) + .read_to_end(&mut raw) + .map_err(|_| fail("AGENT_UPDATE_NOT_CONFIGURED"))?; + let after = file + .metadata() + .map_err(|_| fail("AGENT_UPDATE_NOT_CONFIGURED"))?; + if raw.len() as u64 != m.len() + || ( + m.dev(), + m.ino(), + m.len(), + m.uid(), + m.mode(), + m.ctime(), + m.ctime_nsec(), + m.mtime(), + m.mtime_nsec(), + ) != ( + after.dev(), + after.ino(), + after.len(), + after.uid(), + after.mode(), + after.ctime(), + after.ctime_nsec(), + after.mtime(), + after.mtime_nsec(), + ) + { + return Err(fail("AGENT_UPDATE_NOT_CONFIGURED")); + } + Ok(raw) +} +pub fn store() -> Result { + let key = std::env::var("RMM_JOB_KEY_FILE").map_err(|_| fail("AGENT_UPDATE_NOT_CONFIGURED"))?; + let path = FsPath::new(&key); + let metadata = fs::symlink_metadata(path).map_err(|_| fail("AGENT_UPDATE_NOT_CONFIGURED"))?; + if !metadata.is_file() || metadata.permissions().mode() & 0o077 != 0 { + return Err(fail("AGENT_UPDATE_NOT_CONFIGURED")); + } + Ok(UpdateArtifacts::new( + &std::env::var("RMM_PROFILE").unwrap_or_default(), + path.parent() + .ok_or_else(|| fail("AGENT_UPDATE_NOT_CONFIGURED"))? + .join("agent-update-artifacts"), + metadata.uid(), + )?) +} +fn verifier_platform(platform: Platform) -> rmm_updater::Platform { + match platform { + Platform::LinuxX64 => rmm_updater::Platform::LinuxX64, + Platform::WindowsX64 => rmm_updater::Platform::WindowsX64, + } +} +pub fn verify_envelope( + envelope: &ReleaseEnvelope, + binding: Option<&rmm_domain::agent_update::UpdaterBinding>, +) -> Result { + let decoded = envelope.decode().map_err(|_| invalid())?; + let path = std::env::var("RMM_AGENT_UPDATE_KEYRING_FILE") + .map_err(|_| fail("AGENT_UPDATE_NOT_CONFIGURED"))?; + let raw = protected_file(FsPath::new(&path), 16384)?; + let config: rmm_domain::agent_update::UpdateKeyringFile = + serde_json::from_slice(&raw).map_err(|_| fail("AGENT_UPDATE_TRUST_INVALID"))?; + if !config.validate() + || binding.is_some_and(|b| { + b.keyring_generation != config.generation || b.keyring_sha256 != hash(&raw) + }) + { + return Err(fail("AGENT_UPDATE_TRUST_INVALID")); + } + let mut keys = Vec::new(); + for key in config.keys { + if !rmm_domain::agent_update::digest(&key.public_key_hex) { + return Err(fail("AGENT_UPDATE_TRUST_INVALID")); + } + let raw = + hex::decode(key.public_key_hex).map_err(|_| fail("AGENT_UPDATE_TRUST_INVALID"))?; + keys.push( + rmm_updater::TrustedUpdateKey::new( + raw.try_into() + .map_err(|_| fail("AGENT_UPDATE_TRUST_INVALID"))?, + verifier_platform(key.platform), + key.first_sequence, + key.last_sequence, + key.revoked, + ) + .map_err(|_| fail("AGENT_UPDATE_TRUST_INVALID"))?, + ); + } + let keyring = rmm_updater::UpdateKeyring::new(config.generation, keys) + .map_err(|_| fail("AGENT_UPDATE_TRUST_INVALID"))?; + let context = rmm_updater::TrustedContext { + platform: verifier_platform(decoded.manifest.platform), + now_utc_seconds: chrono::Utc::now() + .timestamp() + .try_into() + .map_err(|_| invalid())?, + keyring_generation: config.generation, + protocol_major: 1, + state_schema: 1, + updater_version: 1, + minimum_release_sequence: 0, + active_release: None, + }; + let verified = rmm_updater::verify_release( + rmm_updater::SignedRelease { + schema_version: envelope.schema_version, + key_id: &envelope.key_id, + payload_bytes: &decoded.payload_bytes, + signature: &decoded.signature, + }, + &keyring, + &context, + ) + .map_err(|_| invalid())?; + if verified.manifest_sha256() != hash(&decoded.payload_bytes) { + return Err(invalid()); + } + Ok(decoded.manifest) +} +pub fn routes(router: Router) -> Router { + router + .route( + "/api/v1/tenants/{tenant}/agent-releases", + get(list).post(import), + ) + .route( + "/api/v1/tenants/{tenant}/agent-update-artifacts", + post(upload), + ) +} +pub fn gateway_routes(router: Router) -> Router { + router + .route("/agent/v1/releases/current", get(current)) + .route("/agent/v1/update-artifacts/{artifact}", get(download)) +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct UploadDescriptor { + artifact_id: Uuid, + sha256: String, + size_bytes: u64, +} +pub async fn upload( + State(s): State, + h: HeaderMap, + Path(t): Path, + Query(input): Query, + body: Body, +) -> Result, Error> { + let (p, tx) = crate::catalog::context(&s, &h, t, true).await?; + if input.artifact_id.is_nil() + || !rmm_domain::agent_update::digest(&input.sha256) + || !(1..=rmm_updater::MAX_ARTIFACT_BYTES).contains(&input.size_bytes) + || h.get("content-type").and_then(|v| v.to_str().ok()) != Some("application/octet-stream") + || h.get("content-length") + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.parse::().ok()) + != Some(input.size_bytes) + { + return Err(invalid()); + } + tx.rollback().await?; + // Authentication/CSRF/tenant checks precede body reads. No unbounded body Vec. + let store = store()?; + let mut staged = store.begin(t, &input.sha256, input.size_bytes)?; + let deadline = Instant::now() + Duration::from_secs(180); + let mut stream = body.into_data_stream(); + loop { + if Instant::now() >= deadline { + return Err(Error( + StatusCode::REQUEST_TIMEOUT, + "AGENT_UPDATE_IMPORT_TIMEOUT", + )); + } + let frame = tokio::time::timeout( + deadline.saturating_duration_since(Instant::now()), + stream.next(), + ) + .await + .map_err(|_| Error(StatusCode::REQUEST_TIMEOUT, "AGENT_UPDATE_IMPORT_TIMEOUT"))?; + if Instant::now() >= deadline { + return Err(Error( + StatusCode::REQUEST_TIMEOUT, + "AGENT_UPDATE_IMPORT_TIMEOUT", + )); + } + let Some(frame) = frame else { break }; + let bytes = frame.map_err(|_| invalid())?; + for chunk in bytes.chunks(32768) { + staged.append(chunk)?; + } + if Instant::now() >= deadline { + return Err(Error( + StatusCode::REQUEST_TIMEOUT, + "AGENT_UPDATE_IMPORT_TIMEOUT", + )); + } + } + let (current_principal, mut tx) = crate::catalog::context(&s, &h, t, true).await?; + if current_principal.name != p.name { + return Err(Error(StatusCode::FORBIDDEN, "FORBIDDEN")); + } + if Instant::now() >= deadline { + return Err(Error( + StatusCode::REQUEST_TIMEOUT, + "AGENT_UPDATE_IMPORT_TIMEOUT", + )); + } + staged.finish(&store, t)?; + sqlx::query("INSERT INTO agent_update_artifacts(tenant_id,artifact_id,sha256,size_bytes) VALUES($1,$2,$3,$4) ON CONFLICT DO NOTHING") + .bind(t).bind(input.artifact_id).bind(&input.sha256).bind(input.size_bytes as i64).execute(&mut *tx).await?; + let actual = + sqlx::query("SELECT sha256,size_bytes FROM agent_update_artifacts WHERE artifact_id=$1") + .bind(input.artifact_id) + .fetch_one(&mut *tx) + .await?; + if actual.get::("sha256") != input.sha256 + || actual.get::("size_bytes") as u64 != input.size_bytes + { + return Err(fail("AGENT_UPDATE_ARTIFACT_CONFLICT")); + } + sqlx::query("INSERT INTO audit_events VALUES($1,$2,$3,'agent_update_artifact_imported',$4,now())") + .bind(t).bind(Uuid::new_v4()).bind(p.name).bind(json!({"artifact_id":input.artifact_id,"sha256":input.sha256,"size_bytes":input.size_bytes,"testsimulation":p.testsimulation})).execute(&mut *tx).await?; + tx.commit().await?; + Ok(Json( + json!({"artifact_id":input.artifact_id,"sha256":input.sha256,"size_bytes":input.size_bytes}), + )) +} +pub async fn checked_release( + tx: &mut Transaction<'_, Postgres>, + id: Uuid, +) -> Result<(ReleaseEnvelope, ReleaseManifest), Error> { + let row = sqlx::query("SELECT envelope,envelope_sha256,manifest_sha256 FROM agent_update_releases WHERE release_id=$1") + .bind(id).fetch_optional(&mut **tx).await?.ok_or_else(missing)?; + let raw: Vec = row.get("envelope"); + let envelope: ReleaseEnvelope = serde_json::from_slice(&raw)?; + let manifest = verify_envelope(&envelope, None)?; + if encode(&envelope)? != raw + || hash(&raw) != row.get::("envelope_sha256") + || hash(&envelope.decode().map_err(|_| invalid())?.payload_bytes) + != row.get::("manifest_sha256") + || manifest.release_id != id + { + return Err(fail("AGENT_UPDATE_CATALOG_INTEGRITY")); + } + Ok((envelope, manifest)) +} +pub async fn resolve_artifacts( + tx: &mut Transaction<'_, Postgres>, + tenant: Uuid, + descriptors: &[ArtifactDescriptor; 2], +) -> Result, Error> { + let store = store()?; + let mut refs = Vec::new(); + for d in descriptors { + let actual = sqlx::query( + "SELECT sha256,size_bytes FROM agent_update_artifacts WHERE artifact_id=$1", + ) + .bind(d.artifact_id) + .fetch_optional(&mut **tx) + .await? + .ok_or_else(missing)?; + if actual.get::("sha256") != d.sha256 + || actual.get::("size_bytes") as u64 != d.bytes + { + return Err(fail("AGENT_UPDATE_ARTIFACT_BINDING")); + } + store.verify(tenant, &d.sha256, d.bytes)?; + refs.push(ArtifactReference { + artifact_id: d.artifact_id, + sha256: d.sha256.clone(), + size_bytes: d.bytes, + }); + } + Ok(refs) +} +pub async fn import( + State(s): State, + h: HeaderMap, + Path(t): Path, + Json(envelope): Json, +) -> Result, Error> { + let (p, mut tx) = crate::catalog::context(&s, &h, t, true).await?; + let raw = encode(&envelope)?; + if raw.len() > 32768 { + return Err(invalid()); + } + let m = verify_envelope(&envelope, None)?; + let sequence = i64::try_from(m.release_sequence).map_err(|_| invalid())?; + resolve_artifacts(&mut tx, t, &m.artifacts).await?; + let manifest_sha = hash(&envelope.decode().map_err(|_| invalid())?.payload_bytes); + sqlx::query("INSERT INTO agent_update_releases(tenant_id,release_id,platform,release_sequence,manifest_sha256,envelope_sha256,envelope,agent_artifact_id,agent_sha256,agent_bytes,helper_artifact_id,helper_sha256,helper_bytes) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)") + .bind(t).bind(m.release_id).bind(platform_name(m.platform)).bind(sequence).bind(&manifest_sha).bind(hash(&raw)).bind(raw) + .bind(m.artifacts[0].artifact_id).bind(&m.artifacts[0].sha256).bind(m.artifacts[0].bytes as i64) + .bind(m.artifacts[1].artifact_id).bind(&m.artifacts[1].sha256).bind(m.artifacts[1].bytes as i64).execute(&mut *tx).await?; + sqlx::query("INSERT INTO audit_events VALUES($1,$2,$3,'agent_update_release_imported',$4,now())").bind(t).bind(Uuid::new_v4()).bind(p.name) + .bind(json!({"release_id":m.release_id,"manifest_sha256":manifest_sha,"testsimulation":p.testsimulation})).execute(&mut *tx).await?; + tx.commit().await?; + Ok(Json( + json!({"release_id":m.release_id,"manifest_sha256":manifest_sha,"release_envelope":envelope,"manifest":m}), + )) +} +pub async fn list_for( + s: &crate::State, + p: &crate::auth::Principal, + tenant: Uuid, + query: crate::pagination::PageQuery, +) -> Result { + crate::jobs::scope(p, tenant, false)?; + let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?; + crate::permissions::require_principal(&mut tx, p, "operations:read").await?; + let mut page = + crate::pagination::Cursor::parse(s, p, "catalog:agent-releases:release_id:asc", query) + .map_err(|status| Error(status, "VALIDATION_ERROR"))?; + let rows = sqlx::query("SELECT release_id,envelope,envelope_sha256,manifest_sha256 FROM agent_update_releases WHERE release_id>$1 AND created_at<=$2 ORDER BY release_id LIMIT $3") + .bind(page.last).bind(page.as_of).bind(i64::from(page.limit)+1).fetch_all(&mut *tx).await?; + let truncated = rows.len() > usize::from(page.limit); + let next = if truncated { + Some( + page.next(s, rows[usize::from(page.limit) - 1].get("release_id")) + .map_err(|status| Error(status, "VALIDATION_ERROR"))?, + ) + } else { + None + }; + let mut items = Vec::new(); + for row in rows.iter().take(usize::from(page.limit)) { + let raw: Vec = row.get("envelope"); + let envelope: ReleaseEnvelope = serde_json::from_slice(&raw)?; + let decoded = envelope.decode().map_err(|_| invalid())?; + if encode(&envelope)? != raw + || hash(&raw) != row.get::("envelope_sha256") + || hash(&decoded.payload_bytes) != row.get::("manifest_sha256") + || decoded.manifest.release_id != row.get::("release_id") + { + return Err(fail("AGENT_UPDATE_CATALOG_INTEGRITY")); + } + // Stored expired metadata remains readable and is explicitly not apply authority. + items.push(json!({"release_id":decoded.manifest.release_id,"manifest_sha256":hash(&decoded.payload_bytes),"release_envelope":envelope,"manifest":decoded.manifest,"signature_and_time_valid":verify_envelope(&envelope,None).is_ok()})); + } + tx.commit().await?; + Ok( + json!({"items":items,"next_cursor":next,"completeness":if truncated {"partial"}else{"complete"},"truncated":truncated,"as_of":page.as_of}), + ) +} +async fn list( + State(s): State, + h: HeaderMap, + Path(t): Path, + Query(query): Query, +) -> Result, Error> { + let p = s + .auth + .principal(&s, &h, false) + .await + .map_err(|status| Error(status, crate::auth::error_code(status)))?; + Ok(Json(list_for(&s, &p, t, query).await?)) +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Current { + platform: Platform, +} +async fn device( + s: &crate::State, + peer: crate::Peer, + headers: &HeaderMap, +) -> Result<(Uuid, Uuid), Error> { + if headers.contains_key("authorization") { + return Err(Error(StatusCode::UNAUTHORIZED, "DEVICE_MTLS_REQUIRED")); + } + crate::agent_http::identity(s, peer) + .await + .map_err(|status| Error(status, "UNAUTHENTICATED")) +} +async fn current( + State(s): State, + Extension(peer): Extension, + headers: HeaderMap, + Query(q): Query, +) -> Result, Error> { + let (tenant, agent) = device(&s, peer, &headers).await?; + let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?; + let caps: Value = sqlx::query_scalar( + "SELECT capabilities FROM agent_installations WHERE agent_id=$1 AND revoked_at IS NULL", + ) + .bind(agent) + .fetch_one(&mut *tx) + .await?; + let caps: Vec = serde_json::from_value(caps)?; + let expected = match q.platform { + Platform::LinuxX64 => "linux.base/1", + Platform::WindowsX64 => "windows.base/1", + }; + if !caps.iter().any(|c| c == expected) { + return Err(missing()); + } + let ids:Vec=sqlx::query_scalar("SELECT release_id FROM agent_update_releases WHERE platform=$1 ORDER BY release_sequence DESC LIMIT 1").bind(platform_name(q.platform)).fetch_all(&mut *tx).await?; + let release = if let Some(id) = ids.first() { + let (envelope, manifest) = checked_release(&mut tx, *id).await?; + resolve_artifacts(&mut tx, tenant, &manifest.artifacts).await?; + Some(json!({"release_envelope":envelope,"manifest":manifest})) + } else { + None + }; + tx.commit().await?; + Ok(Json( + json!({"status":if release.is_some(){"available"}else{"not_configured"},"release":release,"observed_at":chrono::Utc::now(),"server_time":chrono::Utc::now(),"job_created":false}), + )) +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Chunk { + job_id: Uuid, + attempt_id: Uuid, + #[serde(default)] + offset: u64, + length: Option, +} +async fn download( + State(s): State, + Extension(peer): Extension, + headers: HeaderMap, + Path(id): Path, + Query(q): Query, +) -> Result { + let (tenant, agent) = device(&s, peer, &headers).await?; + let length = q.length.unwrap_or(MAX_CHUNK_BYTES); + if !(1..=MAX_CHUNK_BYTES).contains(&length) { + return Err(invalid()); + } + let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?; + let row=sqlx::query("SELECT j.payload,p.payload AS plan_payload,p.plan_hash,z.principal AS approver,i.asset_id,i.enrollment_generation,i.assignment_version FROM jobs j JOIN operations o ON o.tenant_id=j.tenant_id AND o.operation_id=j.operation_id JOIN authorizations z ON z.tenant_id=o.tenant_id AND z.authorization_id=o.authorization_id JOIN approval_requests r ON r.tenant_id=j.tenant_id AND r.operation_id=j.operation_id JOIN operation_plans p ON p.tenant_id=r.tenant_id AND p.plan_id=r.plan_id JOIN agent_installations i ON i.tenant_id=j.tenant_id AND i.agent_id=j.agent_id WHERE j.agent_id=$1 AND j.job_id=$2 AND j.attempt_id=$3 AND j.state IN ('queued','accepted','running','verifying') AND r.approval_state='approved' AND z.revoked_at IS NULL AND p.expires_at>now() AND i.revoked_at IS NULL") + .bind(agent).bind(q.job_id).bind(q.attempt_id).fetch_optional(&mut *tx).await?.ok_or_else(missing)?; + let job: rmm_domain::jobs::JobPayload = + serde_json::from_slice(&row.get::, _>("payload"))?; + let raw: Vec = row.get("plan_payload"); + if hash(&raw) != row.get::("plan_hash") { + return Err(fail("PLAN_HASH_MISMATCH")); + } + let plan: rmm_domain::jobs::PlanPayload = serde_json::from_slice(&raw)?; + validate_job_binding(&plan, &job)?; + let rmm_domain::jobs::Action::UpdateAgent { update } = &job.action else { + return Err(missing()); + }; + crate::root_policy::authorize(&mut tx, &plan.principal, &job).await?; + crate::root_policy::authorize(&mut tx, &row.get::("approver"), &job).await?; + check_update(&mut tx, update).await?; + if job.tenant_id != tenant + || job.agent_id != agent + || job.asset_id != row.get::("asset_id") + || job.enrollment_generation != row.get::("enrollment_generation") as u64 + || job.assignment_version != row.get::("assignment_version") as u64 + { + return Err(missing()); + } + let manifest = update.manifest().map_err(|_| invalid())?; + let descriptor = manifest + .artifacts + .iter() + .find(|a| a.artifact_id == id) + .ok_or_else(missing)?; + if q.offset >= descriptor.bytes { + return Err(Error( + StatusCode::RANGE_NOT_SATISFIABLE, + "INVALID_ARTIFACT_RANGE", + )); + } + tx.commit().await?; + let bytes = store()?.read_chunk( + tenant, + &descriptor.sha256, + descriptor.bytes, + q.offset, + length, + )?; + let end = q.offset + bytes.len() as u64; + let partial = q.offset > 0 || end < descriptor.bytes; + let mut response = ( + if partial { + StatusCode::PARTIAL_CONTENT + } else { + StatusCode::OK + }, + bytes, + ) + .into_response(); + let h = response.headers_mut(); + for (name, value) in [ + ("content-type", "application/octet-stream"), + ("content-disposition", "attachment"), + ("x-content-type-options", "nosniff"), + ("accept-ranges", "bytes"), + ] { + h.insert(name, HeaderValue::from_static(value)); + } + h.insert( + "x-artifact-sha256", + HeaderValue::from_str(&descriptor.sha256).map_err(|_| invalid())?, + ); + if partial { + h.insert( + "content-range", + HeaderValue::from_str(&format!( + "bytes {}-{}/{}", + q.offset, + end - 1, + descriptor.bytes + )) + .map_err(|_| invalid())?, + ); + } + Ok(response) +} + +pub async fn check_update( + tx: &mut Transaction<'_, Postgres>, + update: &rmm_domain::agent_update::ResolvedAgentUpdate, +) -> Result<(), Error> { + if !update.validate() { + return Err(invalid()); + } + let manifest = verify_envelope(&update.release_envelope, Some(&update.updater))?; + let (envelope, stored) = checked_release(tx, manifest.release_id).await?; + if envelope != update.release_envelope || stored != manifest { + return Err(fail("AGENT_UPDATE_CATALOG_BINDING")); + } + Ok(()) +} +pub fn validate_plan_bindings(plan: &rmm_domain::jobs::PlanPayload) -> Result<(), Error> { + use rmm_domain::jobs::Action; + let updates = plan + .jobs + .iter() + .filter(|j| matches!(j.payload.action, Action::UpdateAgent { .. })) + .count(); + if updates == 0 { + return Ok(()); + } + if updates != plan.jobs.len() + || !plan.recipe_references.is_empty() + || plan.artifact_references.len() != updates * 2 + { + return Err(fail("AGENT_UPDATE_ARTIFACT_BINDING")); + } + for fixed in &plan.jobs { + let Action::UpdateAgent { update } = &fixed.payload.action else { + return Err(invalid()); + }; + let m = update.manifest().map_err(|_| invalid())?; + let refs = plan + .artifact_references + .iter() + .filter(|r| { + r.job_id == fixed.payload.job_id && r.attempt_id == fixed.payload.attempt_id + }) + .collect::>(); + if !update.validate() + || !fixed.payload.action.valid_job_limits( + fixed.payload.max_runtime_seconds, + fixed.payload.max_output_bytes, + ) + || plan.tenant_id != fixed.payload.tenant_id + || update.execution_identity() != Some(fixed.payload.execution_identity.as_str()) + || refs.len() != 2 + || refs + .iter() + .zip(m.artifacts.iter()) + .any(|(actual, expected)| { + actual.artifact + != ArtifactReference { + artifact_id: expected.artifact_id, + sha256: expected.sha256.clone(), + size_bytes: expected.bytes, + } + }) + || hash(&encode(&fixed.payload)?) != fixed.job_payload_hash + || fixed.script_sha256.is_some() + || plan + .jobs + .iter() + .filter(|other| { + other.payload.job_id == fixed.payload.job_id + || other.payload.attempt_id == fixed.payload.attempt_id + }) + .count() + != 1 + { + return Err(fail("AGENT_UPDATE_ARTIFACT_BINDING")); + } + } + Ok(()) +} +pub fn validate_job_binding( + plan: &rmm_domain::jobs::PlanPayload, + job: &rmm_domain::jobs::JobPayload, +) -> Result<(), Error> { + if !matches!(job.action, rmm_domain::jobs::Action::UpdateAgent { .. }) { + return Err(missing()); + } + validate_plan_bindings(plan)?; + let actual = encode(job)?; + let fixed = plan + .jobs + .iter() + .filter(|j| j.payload.job_id == job.job_id && j.payload.attempt_id == job.attempt_id) + .collect::>(); + if fixed.len() != 1 + || encode(&fixed[0].payload)? != actual + || fixed[0].job_payload_hash != hash(&actual) + { + return Err(fail("AGENT_UPDATE_ARTIFACT_BINDING")); + } + Ok(()) +} + +/// Only saved, authenticated passive observations are consulted. This never +/// asks a device for live data and never accepts caller-provided predecessor pins. +pub async fn resolve_target( + tx: &mut Transaction<'_, Postgres>, + asset: Uuid, + release_id: Uuid, +) -> Result { + use rmm_domain::agent_update::{ + AgentUpdateObservation, HealthProfile, ObservationQuality, Recovery, ResolvedAgentUpdate, + UpdateProfile, + }; + let row=sqlx::query("SELECT i.tenant_id,i.asset_id,i.agent_id,i.enrollment_generation,i.assignment_version,i.connection_generation,i.connection_boot_id,i.last_contact_at,i.sync_ready,i.helper_sync_ready,i.restore_blocked,i.sync_recovery_required,i.sequence_regressed,o.boot_id,o.observed_at,o.received_at,o.quality,o.completeness,o.data,s.journal_id,s.helper_journal_id FROM agent_installations i JOIN agent_sync_state s ON s.tenant_id=i.tenant_id AND s.agent_id=i.agent_id JOIN LATERAL (SELECT boot_id,observed_at,received_at,quality,completeness,data FROM observations WHERE tenant_id=i.tenant_id AND agent_id=i.agent_id AND source_id IN ('linux.base','windows.base','agent.update') ORDER BY observed_at DESC,received_at DESC LIMIT 1) o ON true WHERE i.asset_id=$1 AND i.revoked_at IS NULL") + .bind(asset).fetch_all(&mut **tx).await?; + if row.len() != 1 { + return Err(fail("AGENT_UPDATE_STATE_NOT_CONFIGURED")); + } + let row = &row[0]; + let now = chrono::Utc::now(); + let observed: chrono::DateTime = row.get("observed_at"); + let received: chrono::DateTime = row.get("received_at"); + let contact: Option> = row.get("last_contact_at"); + if row.get::("quality") != "valid" + || row.get::("completeness") != "partial" + || !row.get::("sync_ready") + || !row.get::("helper_sync_ready") + || row.get::("restore_blocked") + || row.get::("sync_recovery_required") + || row.get::("sequence_regressed") + || row.get::, _>("connection_boot_id") != Some(row.get("boot_id")) + || contact.is_none_or(|t| t > now || t < now - chrono::Duration::seconds(90)) + || observed > now + || received > now + || observed < now - chrono::Duration::minutes(5) + || received < now - chrono::Duration::minutes(5) + { + return Err(fail("AGENT_UPDATE_STATE_STALE")); + } + let data: Value = row.get("data"); + let observation: AgentUpdateObservation = serde_json::from_value( + data.get("agent_update") + .cloned() + .ok_or_else(|| fail("AGENT_UPDATE_STATE_NOT_CONFIGURED"))?, + )?; + if !observation.validate() + || observation.quality != ObservationQuality::Valid + || observation.observed_at > observed + || observation.observed_at < now - chrono::Duration::minutes(5) + { + return Err(fail("AGENT_UPDATE_STATE_STALE")); + } + let checkpoint=sqlx::query("SELECT payload,created_at,connection_generation,journal_id FROM sync_checkpoints WHERE agent_id=$1 AND decision_id=$2") + .bind(row.get::("agent_id")).bind(observation.signed_sync_decision_id).fetch_optional(&mut **tx).await?.ok_or_else(||fail("AGENT_UPDATE_SYNC_PROVENANCE"))?; + let original: rmm_domain::reconciliation::ReconcileDecisionPayload = + serde_json::from_slice(&checkpoint.get::, _>("payload"))?; + if !original.valid_profile(observation.observed_at) + || !original.ready + || !original.helper_ready + || original.tenant_id != row.get::("tenant_id") + || original.asset_id != asset + || original.agent_id != row.get::("agent_id") + || original.boot_id != row.get::("boot_id") + || original.connection_generation != row.get::("connection_generation") as u64 + || original.enrollment_generation != row.get::("enrollment_generation") as u64 + || original.assignment_version != row.get::("assignment_version") as u64 + || original.journal_id != row.get::("journal_id") + || original.helper_journal_id != row.get::, _>("helper_journal_id") + || checkpoint.get::, _>("created_at") + > observation.observed_at + { + return Err(fail("AGENT_UPDATE_SYNC_PROVENANCE")); + } + let (envelope, manifest) = checked_release(tx, release_id).await?; + let manifest_sha = hash(&envelope.decode().map_err(|_| invalid())?.payload_bytes); + let preview = observation + .candidate_previews + .iter() + .find(|c| c.release_id == release_id && c.manifest_sha256 == manifest_sha) + .ok_or_else(|| fail("AGENT_UPDATE_PREVIEW_NOT_CONFIGURED"))?; + if observation.platform != manifest.platform + || observation + .activation_floor + .is_none_or(|floor| manifest.release_sequence <= floor) + { + return Err(fail("AGENT_UPDATE_PREDECESSOR_MISMATCH")); + } + let update = ResolvedAgentUpdate { + schema_version: 1, + profile: UpdateProfile::FixedCodePairV1, + release_envelope_sha256: envelope.sha256()?, + release_envelope: envelope, + manifest_sha256: manifest_sha, + predecessor: observation.predecessor.ok_or_else(invalid)?, + updater: observation.updater.ok_or_else(invalid)?, + peer_pin_transition: preview.peer_pin_transition.clone(), + recovery: Recovery::RestoreExactPredecessorOnce, + health_profile: HealthProfile::MtlsInventorySyncV1, + health_timeout_seconds: 180, + no_reboot: true, + }; + if !update.validate() { + return Err(fail("AGENT_UPDATE_PREDECESSOR_MISMATCH")); + } + verify_envelope(&update.release_envelope, Some(&update.updater))?; + Ok(update) +} +pub async fn validate_current_target( + tx: &mut Transaction<'_, Postgres>, + job: &rmm_domain::jobs::JobPayload, +) -> Result<(), Error> { + let rmm_domain::jobs::Action::UpdateAgent { update } = &job.action else { + return Err(invalid()); + }; + let current = resolve_target( + tx, + job.asset_id, + update.manifest().map_err(|_| invalid())?.release_id, + ) + .await?; + if ¤t != update.as_ref() { + return Err(fail("AGENT_UPDATE_PREDECESSOR_MISMATCH")); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn actual_codec_pair_plan_requires_exact_per_attempt_artifact_authority() { + let fixtures: Value = serde_json::from_str(include_str!( + "../../../tests/agent_update/codec-golden.json" + )) + .unwrap(); + for name in ["linux_general", "linux_full", "windows_pair"] { + let fixture = &fixtures[name]; + let raw: Vec = + serde_json::from_value(fixture["plan_payload_bytes"].clone()).unwrap(); + let plan: rmm_domain::jobs::PlanPayload = serde_json::from_slice(&raw).unwrap(); + assert_eq!(encode(&plan).unwrap(), raw); + let job = &plan.jobs[0].payload; + validate_job_binding(&plan, job).unwrap(); + for variant in 0..5 { + let mut bad = plan.clone(); + match variant { + 0 => bad.artifact_references.clear(), + 1 => bad + .artifact_references + .push(bad.artifact_references[0].clone()), + 2 => bad.artifact_references[0].artifact.artifact_id = Uuid::new_v4(), + 3 => bad.artifact_references[0].attempt_id = Uuid::new_v4(), + _ => bad.jobs[0].payload.max_runtime_seconds = 601, + } + assert!(validate_job_binding(&bad, job).is_err()); + } + } + } + #[test] + fn plan_request_accepts_release_id_but_never_user_supplied_local_bindings() { + let mut value = json!({"tenant_id":"11111111-1111-4111-8111-111111111111","action":"update_agent","targets":{"asset_ids":["11111111-1111-4111-8111-111111111112"]}, + "parameters":{"release_id":"11111111-1111-4111-8111-111111111113","execution_identity":"root","timeout_seconds":600,"max_output_bytes":65536}, + "schedule":{"not_before":"2030-01-01T12:00:00Z","start_before":"2030-01-01T12:10:00Z","offline_policy":"wait_until_deadline"},"rollout":{"max_parallel":1,"halt_after_failures":1},"reason":"codec only"}); + let parsed: crate::jobs::PlanRequest = serde_json::from_value(value.clone()).unwrap(); + assert!(matches!(parsed, crate::jobs::PlanRequest::AgentUpdate(_))); + // The old synchronous resolver cannot manufacture local state. + assert!( + parsed + .resolve(Uuid::parse_str(value["tenant_id"].as_str().unwrap()).unwrap()) + .is_err() + ); + value["parameters"]["predecessor"] = json!({"installed_record_sha256":"00".repeat(32)}); + assert!(serde_json::from_value::(value).is_err()); + } +} diff --git a/crates/server/src/catalog.rs b/crates/server/src/catalog.rs index 413f513..e01e057 100644 --- a/crates/server/src/catalog.rs +++ b/crates/server/src/catalog.rs @@ -47,6 +47,10 @@ pub async fn references( tx: &mut Transaction<'_, Postgres>, action: &rmm_domain::jobs::Action, ) -> Result, Error> { + if let rmm_domain::jobs::Action::UpdateAgent { update } = action { + crate::agent_updates::check_update(tx, update).await?; + return Ok(Vec::new()); + } if let Some(manifest) = action.windows_msi() { if !action.validate() { return Err(Error( diff --git a/crates/server/src/job_gateway.rs b/crates/server/src/job_gateway.rs index f309032..1a3864f 100644 --- a/crates/server/src/job_gateway.rs +++ b/crates/server/src/job_gateway.rs @@ -507,7 +507,10 @@ pub async fn permit( let payload: JobPayload = serde_json::from_slice(&row.get::, _>("payload"))?; let plan: PlanPayload = serde_json::from_slice(&row.get::, _>("plan_payload"))?; let capabilities: Vec = serde_json::from_value(row.get("capabilities"))?; - if crate::windows_msi_catalog::validate_job_binding(&plan, &payload).is_err() { + if crate::windows_msi_catalog::validate_job_binding(&plan, &payload).is_err() + || (matches!(payload.action, Action::UpdateAgent { .. }) + && crate::agent_updates::validate_job_binding(&plan, &payload).is_err()) + { return Ok(denied("WINDOWS_MSI_BINDING_MISMATCH")); } if row.get::("bound_asset") != payload.asset_id @@ -624,9 +627,20 @@ pub async fn permit( .filter(|r| r.job_id == payload.job_id && r.attempt_id == payload.attempt_id) .map(|r| r.artifact.artifact_id) .collect::>(); - let artifacts = crate::catalog::resolve_artifacts(&mut tx, tenant, &artifact_ids) + let artifacts = if let Action::UpdateAgent { update } = &payload.action { + crate::agent_updates::resolve_artifacts( + &mut tx, + tenant, + &update + .manifest() + .map_err(|_| anyhow::anyhow!("invalid agent release"))? + .artifacts, + ) .await - .map_err(|_| anyhow::anyhow!("artifact unavailable"))?; + } else { + crate::catalog::resolve_artifacts(&mut tx, tenant, &artifact_ids).await + } + .map_err(|_| anyhow::anyhow!("artifact unavailable"))?; if plan .artifact_references .iter() @@ -646,6 +660,9 @@ pub async fn permit( || (matches!(payload.action, Action::RunScript { .. }) && (!crate::permissions::allowed(&mut tx, &plan.principal, "scripts:execute").await? || !crate::permissions::allowed(&mut tx, &approver, "scripts:execute").await?)) + || (matches!(payload.action, Action::UpdateAgent { .. }) + && (!crate::permissions::allowed(&mut tx, &plan.principal, "updates:apply").await? + || !crate::permissions::allowed(&mut tx, &approver, "updates:apply").await?)) { return Ok(denied("AUTHORIZATION_REVOKED")); } @@ -692,6 +709,8 @@ pub async fn permit( return Ok(denied("RESOURCE_LOCKED")); } let grant = ExecutionPermitPayload { + agent_update_plan_id: matches!(payload.action, Action::UpdateAgent { .. }) + .then_some(plan.plan_id), domain: "rmm.execution-permit".into(), schema_version: 1, grant_id: Uuid::new_v4(), @@ -756,11 +775,15 @@ pub async fn next( }; let payload: JobPayload = serde_json::from_slice(&row.get::, _>("payload"))?; let caps: Vec = serde_json::from_value(row.get("capabilities"))?; - if payload.action.windows_msi().is_some() { + if payload.action.windows_msi().is_some() + || matches!(payload.action, Action::UpdateAgent { .. }) + { let raw: Vec = row.get("plan_payload"); let plan: PlanPayload = serde_json::from_slice(&raw)?; if hash(&raw) != row.get::("plan_hash") || crate::windows_msi_catalog::validate_job_binding(&plan, &payload).is_err() + || (matches!(payload.action, Action::UpdateAgent { .. }) + && crate::agent_updates::validate_job_binding(&plan, &payload).is_err()) || crate::catalog::check(&mut tx, &payload.action) .await .is_err() diff --git a/crates/server/src/jobs.rs b/crates/server/src/jobs.rs index 2d83716..5b3f4f8 100644 --- a/crates/server/src/jobs.rs +++ b/crates/server/src/jobs.rs @@ -121,11 +121,36 @@ pub struct PlanInput { #[derive(Clone, Deserialize, schemars::JsonSchema)] #[serde(untagged)] pub enum PlanRequest { + AgentUpdate(Box), Typed(Box), Web(Box), } #[derive(Clone, Deserialize, schemars::JsonSchema)] #[serde(deny_unknown_fields)] +pub struct AgentUpdatePlanInput { + tenant_id: Uuid, + action: AgentUpdateRequestAction, + targets: Targets, + parameters: AgentUpdateParameters, + schedule: WebSchedule, + rollout: Rollout, + reason: String, +} +#[derive(Clone, Deserialize, schemars::JsonSchema)] +pub enum AgentUpdateRequestAction { + #[serde(rename = "update_agent")] + UpdateAgent, +} +#[derive(Clone, Deserialize, schemars::JsonSchema)] +#[serde(deny_unknown_fields)] +struct AgentUpdateParameters { + release_id: Uuid, + execution_identity: String, + timeout_seconds: u32, + max_output_bytes: u32, +} +#[derive(Clone, Deserialize, schemars::JsonSchema)] +#[serde(deny_unknown_fields)] pub struct WebPlanInput { tenant_id: Uuid, action: String, @@ -204,6 +229,12 @@ struct WebParameters { impl PlanRequest { pub fn resolve(self, tenant: Uuid) -> Result { let w = match self { + Self::AgentUpdate(_) => { + return Err(Error( + StatusCode::BAD_REQUEST, + "AGENT_UPDATE_RELEASE_ID_REQUIRED", + )); + } Self::Typed(t) => return Ok(*t), Self::Web(w) => *w, }; @@ -325,6 +356,68 @@ impl PlanRequest { }) } } +/// Both HTTP and MCP resolve update jobs only from a fixed catalog release and +/// saved authenticated per-device observations. Caller-supplied local pins are +/// never an alternative route to the typed immutable execution payload. +pub async fn plan_request( + state: &crate::State, + p: &Principal, + tenant: Uuid, + request: PlanRequest, +) -> Result { + let PlanRequest::AgentUpdate(input) = request else { + return plan(state, p, tenant, request.resolve(tenant)?).await; + }; + scope(p, tenant, true)?; + if input.tenant_id != tenant { + return Err(missing()); + } + if input.schedule.offline_policy != "wait_until_deadline" + || input.parameters.release_id.is_nil() + || input.targets.asset_ids.is_empty() + || input.targets.asset_ids.len() > 100 + { + return Err(fail("VALIDATION_ERROR")); + } + let _ = &input.action; + let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant).await?; + crate::permissions::require_principal(&mut tx, p, "operations:plan").await?; + crate::permissions::require_principal(&mut tx, p, "updates:apply").await?; + let mut updates = std::collections::BTreeMap::new(); + for asset in &input.targets.asset_ids { + let update = + crate::agent_updates::resolve_target(&mut tx, *asset, input.parameters.release_id) + .await?; + if update.execution_identity() != Some(input.parameters.execution_identity.as_str()) { + return Err(fail("EXECUTION_IDENTITY_DENIED")); + } + updates.insert(*asset, update); + } + tx.commit().await?; + let first = updates + .values() + .next() + .ok_or_else(|| fail("NOT_FOUND"))? + .clone(); + let resolved = PlanInput { + targets: input.targets, + action: Action::UpdateAgent { + update: Box::new(first), + }, + script_variants: Vec::new(), + execution_identity: input.parameters.execution_identity, + schedule: Schedule { + not_before: input.schedule.not_before, + start_before: input.schedule.start_before, + }, + max_runtime_seconds: input.parameters.timeout_seconds, + max_output_bytes: input.parameters.max_output_bytes, + rollout: input.rollout, + reason: input.reason, + artifact_ids: Vec::new(), + }; + plan_resolved(state, p, tenant, resolved, Some(updates)).await +} fn validate_variants(variants: &[Variant]) -> Result<()> { if variants.is_empty() || variants.len() > 2 { return Err(fail("AMBIGUOUS_TARGET")); @@ -427,6 +520,23 @@ pub async fn plan( p: &Principal, tenant: Uuid, input: PlanInput, +) -> Result { + if matches!(input.action, Action::UpdateAgent { .. }) { + return Err(Error( + StatusCode::BAD_REQUEST, + "AGENT_UPDATE_RELEASE_ID_REQUIRED", + )); + } + plan_resolved(state, p, tenant, input, None).await +} +async fn plan_resolved( + state: &crate::State, + p: &Principal, + tenant: Uuid, + input: PlanInput, + updates: Option< + std::collections::BTreeMap, + >, ) -> Result { scope(p, tenant, true)?; let now = Utc::now(); @@ -495,11 +605,27 @@ pub async fn plan( if matches!(input.action, Action::RunScript { .. }) { crate::permissions::require_principal(&mut tx, p, "scripts:execute").await?; } + if matches!(input.action, Action::UpdateAgent { .. }) { + crate::permissions::require_principal(&mut tx, p, "updates:apply").await?; + } if matches!(input.action, Action::QueryLogs { .. }) { crate::permissions::require_principal(&mut tx, p, "logs:read").await?; } let recipe_references = crate::catalog::references(&mut tx, &input.action).await?; - let artifacts = if input.action.windows_msi().is_some() { + let artifacts = if let Action::UpdateAgent { update } = &input.action { + if !input.artifact_ids.is_empty() { + return Err(fail("AGENT_UPDATE_EXACT_ARTIFACT_REQUIRED")); + } + crate::agent_updates::resolve_artifacts( + &mut tx, + tenant, + &update + .manifest() + .map_err(|_| fail("INVALID_AGENT_RELEASE"))? + .artifacts, + ) + .await? + } else if input.action.windows_msi().is_some() { crate::windows_msi_catalog::automatic_artifacts(&mut tx, tenant, &input.action).await? } else { crate::catalog::resolve_artifacts(&mut tx, tenant, &input.artifact_ids).await? @@ -516,7 +642,18 @@ pub async fn plan( } let row = &rows[0]; let caps = capabilities(row.get("capabilities"))?; - let action = target_action(&input, &caps)?; + let action = if let Some(updates) = &updates { + Action::UpdateAgent { + update: Box::new( + updates + .get(&asset) + .ok_or_else(|| fail("AGENT_UPDATE_STATE_NOT_CONFIGURED"))? + .clone(), + ), + } + } else { + target_action(&input, &caps)? + }; if !action.valid_job_limits(input.max_runtime_seconds, input.max_output_bytes) { return Err(fail("VALIDATION_ERROR")); } @@ -577,6 +714,7 @@ pub async fn plan( artifact_references, }; crate::windows_msi_catalog::validate_plan_bindings(&payload)?; + crate::agent_updates::validate_plan_bindings(&payload)?; let bytes = encode(&payload)?; let plan_hash = hash(&bytes); sqlx::query("INSERT INTO operation_plans(tenant_id,plan_id,principal,payload,plan_hash,expires_at) VALUES($1,$2,$3,$4,$5,$6)").bind(tenant).bind(payload.plan_id).bind(&p.name).bind(&bytes).bind(&plan_hash).bind(input.schedule.start_before).execute(&mut *tx).await?; @@ -612,17 +750,32 @@ async fn load_plan( } async fn recheck(tx: &mut Transaction<'_, Postgres>, plan: &PlanPayload) -> Result<()> { crate::windows_msi_catalog::validate_plan_bindings(plan)?; + crate::agent_updates::validate_plan_bindings(plan)?; policy(tx).await?; - let current_artifacts = crate::catalog::resolve_artifacts( - tx, - plan.tenant_id, - &plan - .artifact_references - .iter() - .map(|r| r.artifact.artifact_id) - .collect::>(), - ) - .await?; + let current_artifacts = if let Some(Action::UpdateAgent { update }) = + plan.jobs.first().map(|j| &j.payload.action) + { + crate::agent_updates::resolve_artifacts( + tx, + plan.tenant_id, + &update + .manifest() + .map_err(|_| fail("INVALID_AGENT_RELEASE"))? + .artifacts, + ) + .await? + } else { + crate::catalog::resolve_artifacts( + tx, + plan.tenant_id, + &plan + .artifact_references + .iter() + .map(|r| r.artifact.artifact_id) + .collect::>(), + ) + .await? + }; for reference in &plan.artifact_references { if !current_artifacts.contains(&reference.artifact) || !plan.jobs.iter().any(|j| { @@ -640,6 +793,13 @@ async fn recheck(tx: &mut Transaction<'_, Postgres>, plan: &PlanPayload) -> Resu { crate::permissions::require(tx, &plan.principal, "scripts:execute").await?; } + if plan + .jobs + .iter() + .any(|j| matches!(j.payload.action, Action::UpdateAgent { .. })) + { + crate::permissions::require(tx, &plan.principal, "updates:apply").await?; + } if plan .jobs .iter() @@ -736,6 +896,9 @@ pub async fn submit( if matches!(job.payload.action, Action::RunScript { .. }) { crate::permissions::require_principal(&mut tx, p, "scripts:execute").await?; } + if matches!(job.payload.action, Action::UpdateAgent { .. }) { + crate::permissions::require_principal(&mut tx, p, "updates:apply").await?; + } if matches!(job.payload.action, Action::QueryLogs { .. }) { crate::permissions::require_principal(&mut tx, p, "logs:read").await?; } @@ -847,6 +1010,9 @@ async fn authorize_http( if matches!(job.payload.action, Action::RunScript { .. }) { crate::permissions::require_principal(&mut tx, &p, "scripts:execute").await?; } + if matches!(job.payload.action, Action::UpdateAgent { .. }) { + crate::permissions::require_principal(&mut tx, &p, "updates:apply").await?; + } if let Some(permission) = crate::root_policy::execution_permission(&job.payload.execution_identity) { @@ -993,7 +1159,7 @@ async fn plan_http( Json(i): Json, ) -> Result> { let p = principal(&s, &h, true).await?; - Ok(Json(plan(&s, &p, t, i.resolve(t)?).await?)) + Ok(Json(plan_request(&s, &p, t, i).await?)) } async fn submit_http( State(s): State, diff --git a/crates/server/src/main.rs b/crates/server/src/main.rs index 042ce15..35c3893 100644 --- a/crates/server/src/main.rs +++ b/crates/server/src/main.rs @@ -1,6 +1,9 @@ mod agent_artifacts; mod agent_http; mod agent_service; +mod agent_update_health; +mod agent_update_policy; +mod agent_updates; mod api; mod artifact_store; mod auth; @@ -21,6 +24,7 @@ mod root_policy; mod scheduler; mod synchronization; mod tls; +mod update_artifact_store; mod windows_msi_catalog; mod windows_policy; @@ -157,6 +161,8 @@ async fn main() -> Result<()> { } let mut routes = Router::new().route("/healthz", get(|| async { "ok" })); if role.gateway() { + routes = agent_updates::gateway_routes(routes); + routes = agent_update_health::gateway_routes(routes); routes = routes .route("/agent/v1/enroll", post(gateway::enroll)) .route("/agent/v1/messages", post(agent_http::messages)) @@ -189,6 +195,7 @@ async fn main() -> Result<()> { routes = jobs::routes(routes); routes = controls::routes(routes); routes = catalog::routes(routes); + routes = agent_updates::routes(routes); routes = routes .route("/api/v1/tenants/{tenant}/health", get(monitoring::health)) .route( diff --git a/crates/server/src/mcp.rs b/crates/server/src/mcp.rs index 71ec61e..bc563cc 100644 --- a/crates/server/src/mcp.rs +++ b/crates/server/src/mcp.rs @@ -91,6 +91,10 @@ fn tools() -> Vec { "inventory.get_device", "Read stored inventory of one authorized device.", ), + tool::( + "updates.list_releases", + "Read immutable signed agent release metadata for the authorized tenant; never approves or applies an update.", + ), tool::( "monitoring.get_health", "Stored presence and health; unknown is not healthy.", @@ -206,7 +210,20 @@ impl Adapter { } "operations.plan" => { let i: Plan = parse(args)?; - crate::jobs::plan(&self.state, &p, i.tenant_id, i.input.resolve(i.tenant_id)?).await + crate::jobs::plan_request(&self.state, &p, i.tenant_id, i.input).await + } + "updates.list_releases" => { + let i: Devices = parse(args)?; + crate::agent_updates::list_for( + &self.state, + &p, + i.tenant_id, + crate::pagination::PageQuery { + cursor: i.cursor, + limit: i.limit, + }, + ) + .await } "operations.submit" => { let i: Submit = parse(args)?; diff --git a/crates/server/src/root_policy.rs b/crates/server/src/root_policy.rs index 5b24733..2b4e983 100644 --- a/crates/server/src/root_policy.rs +++ b/crates/server/src/root_policy.rs @@ -326,6 +326,9 @@ pub async fn authorize( principal: &str, job: &JobPayload, ) -> Result<(), Error> { + if matches!(job.action, Action::UpdateAgent { .. }) { + return crate::agent_update_policy::authorize(tx, principal, job).await; + } match job.execution_identity.as_str() { "system" => return crate::windows_policy::authorize(tx, principal, job).await, "agent_service" => return Ok(()), diff --git a/crates/server/src/synchronization.rs b/crates/server/src/synchronization.rs index 250f330..5ec65f7 100644 --- a/crates/server/src/synchronization.rs +++ b/crates/server/src/synchronization.rs @@ -372,6 +372,23 @@ pub async fn reconcile( reason = "HELPER_CHECKPOINT_REQUIRED".into(); chain_valid = false; } + let previous_payload: Option> = if let Some(old) = &previous { + sqlx::query_scalar( + "SELECT payload FROM sync_checkpoints WHERE agent_id=$1 AND decision_id=$2", + ) + .bind(agent) + .bind(old.get::("decision_id")) + .fetch_optional(&mut **tx) + .await? + } else { + None + }; + let previous_update_decisions: Vec = previous_payload + .as_deref() + .map(serde_json::from_slice::) + .transpose()? + .map(|p| p.attempts) + .unwrap_or_default(); let mut locals = BTreeMap::new(); for local in &r.attempts { let id = Uuid::parse_str(&local.job_id)?; @@ -389,6 +406,10 @@ pub async fn reconcile( "invalid attempt summary" ); i64::try_from(local.revision)?; + if !local.update_handoff_bytes.is_empty() { + rmm_domain::agent_update::UpdateInflightProof::from_bytes(&local.update_handoff_bytes) + .map_err(anyhow::Error::msg)?; + } ensure!( matches!( local.state.as_str(), @@ -451,6 +472,7 @@ pub async fn reconcile( Some(local.outcome_sha256.clone()) }; let mut decision = AttemptDecision { + update_inflight: None, job_id, attempt_id: attempt, job_payload_hash: local.job_payload_hash.clone(), @@ -510,7 +532,7 @@ pub async fn reconcile( ready = false; } let grant = sqlx::query( - "SELECT grant_id,payload,created_at FROM execution_permits WHERE job_id=$1 AND attempt_id=$2", + "SELECT grant_id,payload,signature,created_at FROM execution_permits WHERE job_id=$1 AND attempt_id=$2", ) .bind(job_id) .bind(attempt) @@ -554,6 +576,138 @@ pub async fn reconcile( decisions.push(decision); continue; } + if !local.update_handoff_bytes.is_empty() { + use rmm_domain::agent_update as update; + ensure!( + chain_valid + && r.journal_complete + && reserved + && grant_matches + && helper_journal.is_some() + && matches!( + server_state.as_str(), + "queued" | "accepted" | "running" | "verifying" + ) + && row.get::, _>("result").is_none() + && local.state == "running" + && local.consumption == "consumed" + && local.outcome_bytes.is_empty() + && local.outcome_sha256.is_empty() + && local.result.is_none() + && local.result_envelope.is_none(), + "UPDATE_INFLIGHT_NOT_ORIGINAL_ACTIVE_ATTEMPT" + ); + let proof = update::UpdateInflightProof::from_bytes(&local.update_handoff_bytes) + .map_err(anyhow::Error::msg)?; + let key = update::job_health_public_key(&payload).map_err(anyhow::Error::msg)?; + let (header, _) = + update::verify_inflight_proof(&proof, key).map_err(anyhow::Error::msg)?; + let grant = grant.as_ref().context("UPDATE_ORIGINAL_GRANT_REQUIRED")?; + let permit_bytes: Vec = grant.get("payload"); + let signature: Vec = grant.get("signature"); + let permit: ExecutionPermitPayload = serde_json::from_slice(&permit_bytes)?; + let job_bytes: Vec = row.get("payload"); + let original = update::OriginalHelperRequest { + job_bytes: &job_bytes, + permit_bytes: &permit_bytes, + signature: &signature, + plan_hash: &permit.plan_hash, + authorization_id: permit.authorization_id, + }; + let authorized_plan:Option=sqlx::query_scalar("SELECT plan_id FROM authorizations WHERE tenant_id=$1 AND authorization_id=$2 AND plan_hash=$3") + .bind(tenant).bind(permit.authorization_id).bind(&permit.plan_hash).fetch_optional(&mut **tx).await?; + let original_sync: Vec = sqlx::query_scalar( + "SELECT payload FROM sync_checkpoints WHERE agent_id=$1 AND decision_id=$2", + ) + .bind(agent) + .bind(header.previous_decision_id) + .fetch_optional(&mut **tx) + .await? + .context("UPDATE_ORIGINAL_READY_SYNC_REQUIRED")?; + let original_sync: ReconcileDecisionPayload = serde_json::from_slice(&original_sync)?; + ensure!( + original_sync.ready + && original_sync.helper_ready + && original_sync.agent_id == agent + && original_sync.tenant_id == tenant + && original_sync.journal_id == header.agent_journal_id + && original_sync.helper_journal_id == Some(header.helper_journal_id) + && original_sync.helper_checkpoint == header.helper_checkpoint + && original_sync.boot_id == header.boot_id + && original_sync.connection_generation == header.connection_generation + && original_sync.issued_at <= proof.delegation.prepared_at + && proof.delegation.prepared_at < original_sync.valid_until, + "UPDATE_ORIGINAL_READY_SYNC_BINDING" + ); + let seconds = u64::try_from(Utc::now().timestamp())?; + ensure!( + update::handoff_matches_job(&header, &payload) + && header.boot_id == boot + && header.attempt.plan_id + == authorized_plan.context("UPDATE_ORIGINAL_PLAN_REQUIRED")? + && permit.agent_update_plan_id == Some(header.attempt.plan_id) + && header.agent_journal_id == journal_id + && Some(header.helper_journal_id) == helper_journal + && header.helper_checkpoint <= r.helper_checkpoint + && header.connection_generation <= e.connection_generation + && header.attempt.grant_id == permit.grant_id + && header.attempt.authorization_id == permit.authorization_id + && header.attempt.plan_sha256 == permit.plan_hash + && header.attempt.job_payload_sha256 == permit.job_payload_hash + && header.attempt.original_request_sha256 + == hash(&serde_json::to_vec(&original)?) + && permit.action == "update_agent" + && permit.max_runtime_seconds == 600 + && permit.key_id == state.job_signer.key_id + && header.finish_before + == header + .consumed_at + .checked_add(600) + .context("UPDATE_DEADLINE_OVERFLOW")? + && header.consumed_at <= seconds + && seconds < header.finish_before + && proof.delegation.prepared_at >= permit.not_before + && proof.delegation.prepared_at < permit.start_before + && local.original_boot_id == boot.to_string(), + "UPDATE_INFLIGHT_ORIGINAL_BINDING" + ); + let ack = update::inflight_decision(&proof, key).map_err(anyhow::Error::msg)?; + if let Some(old) = previous_update_decisions + .iter() + .find(|d| d.job_id == job_id && d.attempt_id == attempt) + .and_then(|d| d.update_inflight.as_ref()) + { + let decoded = proof.decode().map_err(anyhow::Error::msg)?; + ensure!( + old.handoff_sha256 == ack.handoff_sha256 + && old.delegation_sha256 == ack.delegation_sha256 + && old.owner_nonce == ack.owner_nonce + && old.finish_before == ack.finish_before + && (hash(&decoded.handoff_record) == old.head_sha256 + || decoded + .events + .iter() + .any(|bytes| hash(bytes) == old.head_sha256)), + "UPDATE_INFLIGHT_PREFIX_REGRESSION" + ); + } + 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", + ) + .bind(job_id) + .bind(i64::try_from(revision)?) + .execute(&mut **tx) + .await?; + decision.revision = revision; + decision.outcome_state = "running".into(); + decision.update_inflight = Some(ack); + decision.reason = "AGENT_UPDATE_INFLIGHT".into(); + decision.unlock = false; + ready = false; + decisions.push(decision); + continue; + } // A free script with no bound postcondition never becomes successful by // merely asserting a new state after unknown effect. let manual = server_state == "unknown" @@ -1286,6 +1440,7 @@ mod tests { #[test] fn accepted_is_not_a_new_attempt_or_grant() { let mut local = SyncAttempt { + update_handoff_bytes: Vec::new(), state: "accepted".into(), consumption: "unconsumed".into(), ..Default::default() diff --git a/crates/server/src/update_artifact_store.rs b/crates/server/src/update_artifact_store.rs new file mode 100644 index 0000000..4c69a54 --- /dev/null +++ b/crates/server/src/update_artifact_store.rs @@ -0,0 +1,285 @@ +//! Separate bounded binary store. Existing 256KiB package artifacts are unchanged. +//! A completed object is published only after complete length/hash verification. +use anyhow::{Result, ensure}; +use sha2::{Digest, Sha256}; +use std::{ + fs::{self, File, OpenOptions}, + io::{Read, Seek, SeekFrom, Write}, + os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt}, + path::{Path, PathBuf}, +}; +use uuid::Uuid; + +pub const MAX_CHUNK_BYTES: u32 = 512 * 1024; +pub struct UpdateArtifacts { + root: PathBuf, + owner: u32, +} +pub struct Staging { + file: File, + temporary: PathBuf, + final_path: PathBuf, + parent: PathBuf, + expected_hash: String, + expected_size: u64, + written: u64, + hasher: Sha256, +} +fn descriptor(hash: &str, bytes: u64) -> bool { + rmm_domain::agent_update::digest(hash) && (1..=rmm_updater::MAX_ARTIFACT_BYTES).contains(&bytes) +} +fn directory(path: &Path, owner: u32) -> Result<()> { + let m = fs::symlink_metadata(path)?; + ensure!( + m.is_dir() && m.uid() == owner && m.mode() & 0o777 == 0o700, + "private update store directory" + ); + Ok(()) +} +fn regular(file: &File, owner: u32, expected_size: u64) -> Result { + let m = file.metadata()?; + ensure!( + m.is_file() + && m.uid() == owner + && m.mode() & 0o777 == 0o600 + && m.nlink() == 1 + && m.len() == expected_size, + "immutable update object metadata" + ); + Ok(m) +} +impl UpdateArtifacts { + pub fn new(profile: &str, root: PathBuf, owner: u32) -> Result { + ensure!( + profile == "development", + "update object adapter is development-only" + ); + match fs::create_dir(&root) { + Ok(()) => fs::set_permissions(&root, fs::Permissions::from_mode(0o700))?, + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {} + Err(e) => return Err(e.into()), + } + directory(&root, owner)?; + Ok(Self { root, owner }) + } + fn parent(&self, tenant: Uuid) -> Result { + ensure!(!tenant.is_nil(), "update tenant identity"); + directory(&self.root, self.owner)?; + let parent = self.root.join(tenant.to_string()); + match fs::create_dir(&parent) { + Ok(()) => { + fs::set_permissions(&parent, fs::Permissions::from_mode(0o700))?; + File::open(&self.root)?.sync_all()?; + } + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {} + Err(e) => return Err(e.into()), + } + directory(&parent, self.owner)?; + Ok(parent) + } + pub fn begin(&self, tenant: Uuid, hash: &str, bytes: u64) -> Result { + ensure!(descriptor(hash, bytes), "bounded update object descriptor"); + let parent = self.parent(tenant)?; + let temporary = parent.join(format!(".staging-{}", Uuid::new_v4())); + let file = OpenOptions::new() + .create_new(true) + .write(true) + .mode(0o600) + .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC) + .open(&temporary)?; + Ok(Staging { + file, + temporary, + final_path: parent.join(hash), + parent, + expected_hash: hash.into(), + expected_size: bytes, + written: 0, + hasher: Sha256::new(), + }) + } + fn verified_file(&self, tenant: Uuid, hash: &str, bytes: u64) -> Result { + ensure!(descriptor(hash, bytes), "bounded update object descriptor"); + let parent = self.parent(tenant)?; + let mut file = OpenOptions::new() + .read(true) + .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC) + .open(parent.join(hash))?; + let before = regular(&file, self.owner, bytes)?; + let mut hasher = Sha256::new(); + let mut buffer = [0_u8; 32768]; + let mut seen = 0; + loop { + let n = file.read(&mut buffer)?; + if n == 0 { + break; + } + seen += n as u64; + ensure!(seen <= bytes, "update object additional bytes"); + hasher.update(&buffer[..n]); + } + let after = regular(&file, self.owner, bytes)?; + ensure!( + seen == bytes + && hex::encode(hasher.finalize()) == hash + && ( + before.dev(), + before.ino(), + before.ctime(), + before.ctime_nsec(), + before.mtime(), + before.mtime_nsec() + ) == ( + after.dev(), + after.ino(), + after.ctime(), + after.ctime_nsec(), + after.mtime(), + after.mtime_nsec() + ), + "complete immutable update object integrity" + ); + file.seek(SeekFrom::Start(0))?; + Ok(file) + } + pub fn verify(&self, tenant: Uuid, hash: &str, bytes: u64) -> Result<()> { + self.verified_file(tenant, hash, bytes).map(|_| ()) + } + pub fn read_chunk( + &self, + tenant: Uuid, + hash: &str, + bytes: u64, + offset: u64, + length: u32, + ) -> Result> { + ensure!( + offset < bytes && (1..=MAX_CHUNK_BYTES).contains(&length), + "bounded update range" + ); + let mut file = self.verified_file(tenant, hash, bytes)?; + let before = regular(&file, self.owner, bytes)?; + file.seek(SeekFrom::Start(offset))?; + let mut chunk = vec![0; (bytes - offset).min(length as u64) as usize]; + file.read_exact(&mut chunk)?; + let after = regular(&file, self.owner, bytes)?; + ensure!( + ( + before.dev(), + before.ino(), + before.ctime(), + before.ctime_nsec(), + before.mtime(), + before.mtime_nsec() + ) == ( + after.dev(), + after.ino(), + after.ctime(), + after.ctime_nsec(), + after.mtime(), + after.mtime_nsec() + ), + "update object changed during bounded range" + ); + Ok(chunk) + } +} +impl Staging { + pub fn append(&mut self, chunk: &[u8]) -> Result<()> { + ensure!( + !chunk.is_empty() + && chunk.len() <= MAX_CHUNK_BYTES as usize + && self.written + chunk.len() as u64 <= self.expected_size, + "bounded update import chunk" + ); + self.file.write_all(chunk)?; + self.hasher.update(chunk); + self.written += chunk.len() as u64; + Ok(()) + } + pub fn finish(mut self, store: &UpdateArtifacts, tenant: Uuid) -> Result<()> { + ensure!( + self.written == self.expected_size + && hex::encode(self.hasher.clone().finalize()) == self.expected_hash, + "complete update import hash/length" + ); + self.file.flush()?; + self.file.sync_all()?; + if let Err(e) = fs::hard_link(&self.temporary, &self.final_path) { + ensure!( + e.kind() == std::io::ErrorKind::AlreadyExists, + "update publication failed" + ); + store.verify(tenant, &self.expected_hash, self.expected_size)?; + } + fs::remove_file(&self.temporary)?; + File::open(&self.parent)?.sync_all()?; + store.verify(tenant, &self.expected_hash, self.expected_size)?; + Ok(()) + } +} +impl Drop for Staging { + fn drop(&mut self) { + // Only this create-once temporary object, never a published object/job. + let _ = fs::remove_file(&self.temporary); + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn large_update_stream_preserves_legacy_bound_and_denies_corruption_or_foreign_tenant() { + let root = std::env::temp_dir().join(format!("rmm-update-store-{}", Uuid::new_v4())); + fs::create_dir(&root).unwrap(); + fs::set_permissions(&root, fs::Permissions::from_mode(0o700)).unwrap(); + let owner = fs::metadata(&root).unwrap().uid(); + let store = UpdateArtifacts::new("development", root.clone(), owner).unwrap(); + assert!(UpdateArtifacts::new("production", root.clone(), owner).is_err()); + let tenant = Uuid::new_v4(); + let bytes = vec![37_u8; 300_007]; + let hash = rmm_domain::jobs::hash(&bytes); + let mut staging = store.begin(tenant, &hash, bytes.len() as u64).unwrap(); + for chunk in bytes.chunks(32768) { + staging.append(chunk).unwrap(); + } + staging.finish(&store, tenant).unwrap(); + assert_eq!( + store + .read_chunk(tenant, &hash, bytes.len() as u64, 299_999, 16) + .unwrap(), + bytes[299_999..] + ); + assert!( + store + .read_chunk(Uuid::new_v4(), &hash, bytes.len() as u64, 0, 32) + .is_err() + ); + assert!( + store + .read_chunk(tenant, &hash, bytes.len() as u64, bytes.len() as u64, 1) + .is_err() + ); + assert!( + store + .read_chunk(tenant, &hash, bytes.len() as u64, 0, MAX_CHUNK_BYTES + 1) + .is_err() + ); + assert!(store.begin(tenant, "../escape", 1).is_err()); + // An incomplete object is never published, including a clean early EOF. + let truncated = rmm_domain::jobs::hash(b"truncated"); + let mut short = store.begin(tenant, &truncated, 9).unwrap(); + short.append(b"trunc").unwrap(); + assert!(short.finish(&store, tenant).is_err()); + assert!(!root.join(tenant.to_string()).join(truncated).exists()); + let object = root.join(tenant.to_string()).join(&hash); + fs::write(&object, vec![38_u8; bytes.len()]).unwrap(); + assert!(store.verify(tenant, &hash, bytes.len() as u64).is_err()); + // Existing small package storage retains its own 256KiB boundary. + use crate::artifact_store::ArtifactStore; + let legacy = + crate::artifact_store::LocalArtifacts::new("development", root.join("legacy")).unwrap(); + assert!(legacy.put(tenant, &bytes).is_err()); + fs::remove_dir_all(root).unwrap(); + } +} diff --git a/crates/updater-linux/Cargo.toml b/crates/updater-linux/Cargo.toml new file mode 100644 index 0000000..7a7e0e2 --- /dev/null +++ b/crates/updater-linux/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "rmm-updater-linux" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +anyhow.workspace = true +hex.workspace = true +libc = "0.2.177" +serde.workspace = true +serde_json.workspace = true +sha2.workspace = true +uuid.workspace = true +rmm-domain = { path = "../domain" } +rmm-updater-handoff = { path = "../updater-handoff" } diff --git a/crates/updater-linux/src/files.rs b/crates/updater-linux/src/files.rs new file mode 100644 index 0000000..0f29d85 --- /dev/null +++ b/crates/updater-linux/src/files.rs @@ -0,0 +1,613 @@ +//! Capability-relative held files. No network-provided path or global JSON +//! replacement. Existing bound hardlinks are retained; new stages have nlink1. +use crate::{Budget, DurableEffectFence, Effect, digest, valid_digest}; +use anyhow::{Context, Result, ensure}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::{ + ffi::{CString, OsStr}, + fs::{File, Metadata}, + io::{Read, Seek, SeekFrom, Write}, + os::{ + fd::{AsRawFd, FromRawFd}, + unix::{ffi::OsStrExt, fs::MetadataExt}, + }, + path::{Component, Path, PathBuf}, +}; +use uuid::Uuid; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Role { + Agent, + Helper, + FullConfig, + FullPin, +} +impl Role { + pub fn handoff_role(self) -> rmm_updater_handoff::FileRole { + match self { + Self::Agent => rmm_updater_handoff::FileRole::AgentBinary, + Self::Helper => rmm_updater_handoff::FileRole::HelperBinary, + Self::FullConfig => rmm_updater_handoff::FileRole::LinuxFullConfig, + Self::FullPin => rmm_updater_handoff::FileRole::LinuxFullPin, + } + } + pub fn target(self) -> &'static str { + match self { + Self::Agent => "/usr/local/libexec/rmm-agent-remote", + Self::Helper => "/usr/local/libexec/rmm-privileged-helper", + Self::FullConfig => "/etc/rmm-remote/helper-full-maintenance.json", + Self::FullPin => "/etc/rmm-remote/full-maintenance-helper-proof.json", + } + } + fn label(self) -> &'static str { + match self { + Self::Agent => "agent", + Self::Helper => "helper", + Self::FullConfig => "full-config", + Self::FullPin => "full-pin", + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Identity { + pub device: u64, + pub inode: u64, + pub uid: u32, + pub gid: u32, + pub mode: u32, + pub links: u64, +} +impl Identity { + fn of(m: &Metadata) -> Self { + Self { + device: m.dev(), + inode: m.ino(), + uid: m.uid(), + gid: m.gid(), + mode: m.mode(), + links: m.nlink(), + } + } +} +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct FileProof { + pub identity: Identity, + pub bytes: u64, + pub sha256: String, +} + +fn name(value: &OsStr) -> Result { + let bytes = value.as_bytes(); + ensure!( + !bytes.is_empty() && bytes != b"." && bytes != b".." && !bytes.contains(&b'/'), + "UPDATE_BASENAME" + ); + Ok(CString::new(bytes)?) +} +fn openat(parent: &File, value: &OsStr, flags: i32, mode: u32) -> Result { + let value = name(value)?; + // SAFETY: valid owned directory fd and NUL-terminated one-component name; + // successful descriptor is immediately transferred into exactly one File. + let fd = unsafe { + libc::openat( + parent.as_raw_fd(), + value.as_ptr(), + flags | libc::O_CLOEXEC | libc::O_NOFOLLOW, + mode, + ) + }; + ensure!( + fd >= 0, + "UPDATE_OPENAT: {}", + std::io::Error::last_os_error() + ); + Ok(unsafe { File::from_raw_fd(fd) }) +} + +pub struct Directory { + fd: File, + path: PathBuf, + identity: Identity, +} +impl Directory { + /// All ancestors are held while opening their child with O_NOFOLLOW. A + /// writable ancestor (including /tmp) is deliberately not an install root. + pub fn open(path: &Path, owner: u32, private: bool) -> Result { + ensure!(path.is_absolute(), "UPDATE_ABSOLUTE_DIRECTORY"); + let mut fd = File::open("/")?; + let components: Vec<_> = path.components().collect(); + for (i, component) in components.iter().enumerate().skip(1) { + let Component::Normal(value) = component else { + anyhow::bail!("UPDATE_DIRECTORY_COMPONENT") + }; + fd = openat(&fd, value, libc::O_RDONLY | libc::O_DIRECTORY, 0)?; + let m = fd.metadata()?; + ensure!( + m.is_dir() + && m.uid() == if i + 1 == components.len() { owner } else { 0 } + && m.mode() & 0o022 == 0, + "UPDATE_PROTECTED_DIRECTORY" + ); + } + let m = fd.metadata()?; + ensure!( + m.uid() == owner && (!private || m.mode() & 0o077 == 0), + "UPDATE_PRIVATE_DIRECTORY" + ); + Ok(Self { + identity: Identity::of(&m), + fd, + path: path.to_path_buf(), + }) + } + pub fn identity(&self) -> &Identity { + &self.identity + } + pub fn verify(&self) -> Result<()> { + let current = Self::open(&self.path, self.identity.uid, false)?; + ensure!( + current.identity == self.identity + && Identity::of(&self.fd.metadata()?) == self.identity, + "UPDATE_DIRECTORY_REPLACED" + ); + Ok(()) + } + pub fn file(&self, basename: &OsStr, expected: &FileProof, max: u64) -> Result { + self.verify()?; + let mut held = HeldFile { + fd: openat(&self.fd, basename, libc::O_RDONLY | libc::O_NONBLOCK, 0)?, + proof: expected.clone(), + }; + held.verify(max)?; + self.named(basename, &held.proof.identity)?; + Ok(held) + } + pub fn inspect(&self, basename: &OsStr, owner: u32, max: u64) -> Result { + self.verify()?; + let mut fd = openat(&self.fd, basename, libc::O_RDONLY | libc::O_NONBLOCK, 0)?; + let m = fd.metadata()?; + ensure!( + m.is_file() + && m.uid() == owner + && m.mode() & 0o022 == 0 + && m.nlink() > 0 + && m.len() <= max, + "UPDATE_PROTECTED_FILE" + ); + let hash = hash_file(&mut fd, max)?; + let proof = FileProof { + identity: Identity::of(&m), + bytes: m.len(), + sha256: hash, + }; + let mut result = HeldFile { fd, proof }; + result.verify(max)?; + self.named(basename, &result.proof.identity)?; + Ok(result) + } + fn named(&self, basename: &OsStr, expected: &Identity) -> Result<()> { + let file = openat(&self.fd, basename, libc::O_PATH, 0)?; + ensure!( + Identity::of(&file.metadata()?) == *expected, + "UPDATE_NAMED_INODE_CHANGED" + ); + Ok(()) + } + fn absent(&self, basename: &OsStr) -> Result<()> { + let value = name(basename)?; + let mut m = std::mem::MaybeUninit::::uninit(); + // SAFETY: live dirfd, valid basename, properly sized writable stat. + let rc = unsafe { + libc::fstatat( + self.fd.as_raw_fd(), + value.as_ptr(), + m.as_mut_ptr(), + libc::AT_SYMLINK_NOFOLLOW, + ) + }; + ensure!( + rc < 0 && std::io::Error::last_os_error().raw_os_error() == Some(libc::ENOENT), + "UPDATE_DESTINATION_EXISTS" + ); + Ok(()) + } + fn sync(&self) -> Result<()> { + self.fd.sync_all()?; + Ok(()) + } + fn rename_new(&self, from: &OsStr, to: &OsStr) -> Result<()> { + let a = name(from)?; + let b = name(to)?; + // SAFETY: same held directory, valid component strings; NOREPLACE + // forbids overwriting an unexpected target including a dangling link. + let rc = unsafe { + libc::renameat2( + self.fd.as_raw_fd(), + a.as_ptr(), + self.fd.as_raw_fd(), + b.as_ptr(), + libc::RENAME_NOREPLACE, + ) + }; + ensure!( + rc == 0, + "UPDATE_RENAME: {}", + std::io::Error::last_os_error() + ); + self.sync() + } +} + +pub struct HeldFile { + fd: File, + proof: FileProof, +} +impl HeldFile { + pub fn proof(&self) -> &FileProof { + &self.proof + } + pub fn verify(&mut self, max: u64) -> Result<()> { + let m = self.fd.metadata()?; + ensure!( + m.is_file() + && Identity::of(&m) == self.proof.identity + && m.len() == self.proof.bytes + && self.proof.bytes <= max + && valid_digest(&self.proof.sha256), + "UPDATE_HELD_FILE_CHANGED" + ); + ensure!( + hash_file(&mut self.fd, max)? == self.proof.sha256, + "UPDATE_HELD_HASH_CHANGED" + ); + let after = self.fd.metadata()?; + ensure!( + Identity::of(&m) == Identity::of(&after) + && m.len() == after.len() + && m.mtime_nsec() == after.mtime_nsec() + && m.mtime() == after.mtime() + && m.ctime() == after.ctime() + && m.ctime_nsec() == after.ctime_nsec(), + "UPDATE_FILE_CHANGED_DURING_HASH" + ); + Ok(()) + } + pub fn bytes(&mut self, max: u64) -> Result> { + self.verify(max)?; + self.fd.seek(SeekFrom::Start(0))?; + let mut bytes = Vec::with_capacity(self.proof.bytes as usize); + Read::by_ref(&mut self.fd) + .take(max + 1) + .read_to_end(&mut bytes)?; + ensure!( + bytes.len() as u64 == self.proof.bytes && digest(&bytes) == self.proof.sha256, + "UPDATE_READ_CHANGED" + ); + self.verify(max)?; + Ok(bytes) + } +} +fn hash_file(fd: &mut File, max: u64) -> Result { + ensure!(max <= 256 * 1024 * 1024, "UPDATE_HASH_LIMIT"); + fd.seek(SeekFrom::Start(0))?; + let mut hash = Sha256::new(); + let mut buffer = [0; 32768]; + let mut total = 0u64; + loop { + let n = fd.read(&mut buffer)?; + if n == 0 { + break; + } + total = total.checked_add(n as u64).context("UPDATE_HASH_LIMIT")?; + ensure!(total <= max, "UPDATE_HASH_LIMIT"); + hash.update(&buffer[..n]); + } + Ok(hex::encode(hash.finalize())) +} + +/// File creation is confined to the SAME held installation directory. The +/// private fields bind successful EOF/hash/mode checking to subsequent swap. +pub struct Staged { + role: Role, + nonce: Uuid, + basename: String, + file: HeldFile, + target: String, + original: FileProof, +} +/// All descriptors remain untrusted input until the exact protected predecessor +/// and the approved target hashes have been independently checked by runtime. +pub struct StageDescriptor<'a> { + pub role: Role, + pub nonce: Uuid, + pub original: &'a FileProof, + pub expected_sha: &'a str, + pub length: u64, +} +impl Staged { + /// Stage only after the embedding agent has a real fixed approved job and + /// authorized download. This function alone grants no stop/swap authority. + pub fn write( + dir: &Directory, + descriptor: StageDescriptor<'_>, + source: &mut impl Read, + budget: &Budget, + ) -> Result { + let StageDescriptor { + role, + nonce, + original, + expected_sha, + length, + } = descriptor; + ensure!( + !nonce.is_nil() + && valid_digest(expected_sha) + && length > 0 + && length <= 256 * 1024 * 1024, + "UPDATE_STAGE_DESCRIPTOR" + ); + ensure!( + original.identity.uid == 0 && original.identity.mode & 0o022 == 0, + "UPDATE_ORIGINAL_METADATA" + ); + let target = Path::new(role.target()) + .file_name() + .context("UPDATE_TARGET")? + .to_str() + .context("UPDATE_TARGET")? + .to_owned(); + ensure!( + Path::new(role.target()).parent() == Some(dir.path.as_path()), + "UPDATE_FIXED_ROLE_DIRECTORY" + ); + dir.file(OsStr::new(&target), original, 256 * 1024 * 1024)?; + let basename = format!(".rmm-update-{nonce}-{}.stage", role.label()); + budget.check()?; + let mut fd = openat( + &dir.fd, + OsStr::new(&basename), + libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL, + 0o600, + )?; + let mut remaining = length; + let mut hash = Sha256::new(); + let mut buffer = [0; 32768]; + while remaining > 0 { + budget.check()?; + let take = remaining.min(buffer.len() as u64) as usize; + let n = source.read(&mut buffer[..take])?; + ensure!(n > 0, "UPDATE_STAGE_SHORT"); + fd.write_all(&buffer[..n])?; + hash.update(&buffer[..n]); + remaining -= n as u64; + } + let mut tail = [0; 1]; + ensure!( + source.read(&mut tail)? == 0 && hex::encode(hash.finalize()) == expected_sha, + "UPDATE_STAGE_HASH_OR_EXCESS" + ); + budget.check()?; + // SAFETY: owned regular newly created file. Preserve old owner/group + // and all mode bits; binaries/configs are not made more permissive. + ensure!( + unsafe { libc::fchown(fd.as_raw_fd(), original.identity.uid, original.identity.gid) } + == 0, + "UPDATE_STAGE_OWNER" + ); + ensure!( + unsafe { libc::fchmod(fd.as_raw_fd(), original.identity.mode & 0o7777) } == 0, + "UPDATE_STAGE_MODE" + ); + fd.sync_all()?; + dir.sync()?; + drop(fd); + let file = dir.inspect(OsStr::new(&basename), 0, 256 * 1024 * 1024)?; + ensure!( + file.proof.identity.links == 1 + && file.proof.sha256 == expected_sha + && file.proof.bytes == length, + "UPDATE_STAGE_VERIFIED" + ); + Ok(Self { + role, + nonce, + basename, + file, + target, + original: original.clone(), + }) + } + pub fn proof(&self) -> &FileProof { + self.file.proof() + } + /// Two separately fenced namespace changes; a crash in between leaves the + /// original backup and stage intact. This method NEVER retries or resumes. + pub fn install( + mut self, + dir: &Directory, + guard: &LedgerGuard<'_>, + budget: &Budget, + fence: &mut impl DurableEffectFence, + ) -> Result { + guard.verify_for_effect(budget)?; + dir.verify()?; + self.file.verify(256 * 1024 * 1024)?; + dir.file(OsStr::new(&self.target), &self.original, 256 * 1024 * 1024)?; + let backup = format!(".rmm-update-{}-{}.previous", self.nonce, self.role.label()); + dir.absent(OsStr::new(&backup))?; + let save = Effect::SavePredecessor { role: self.role }; + fence.before_effect(&save)?; + guard.verify_for_effect(budget)?; + dir.named(OsStr::new(&self.target), &self.original.identity)?; + dir.named(OsStr::new(&self.basename), &self.file.proof.identity)?; + dir.rename_new(OsStr::new(&self.target), OsStr::new(&backup))?; + dir.file(OsStr::new(&backup), &self.original, 256 * 1024 * 1024)?; + fence.after_effect(&save, &digest(&serde_json::to_vec(&self.original)?))?; + let publish = Effect::PublishReplacement { role: self.role }; + fence.before_effect(&publish)?; + guard.verify_for_effect(budget)?; + dir.named(OsStr::new(&self.basename), &self.file.proof.identity)?; + dir.absent(OsStr::new(&self.target))?; + dir.rename_new(OsStr::new(&self.basename), OsStr::new(&self.target))?; + let current = dir.file( + OsStr::new(&self.target), + &self.file.proof, + 256 * 1024 * 1024, + )?; + fence.after_effect(&publish, &digest(&serde_json::to_vec(current.proof())?))?; + Ok(Installed { + role: self.role, + target: self.target, + backup, + old: self.original, + new: current.proof, + }) + } +} +pub struct Installed { + pub role: Role, + target: String, + backup: String, + old: FileProof, + new: FileProof, +} +impl Installed { + pub fn old(&self) -> &FileProof { + &self.old + } + pub fn new_file(&self) -> &FileProof { + &self.new + } + /// A rollback is NOT inferred from a failed health check. Only a separately + /// bound rollback fence may authorize it; unknown intermediate state denies. + pub fn restore( + self, + dir: &Directory, + guard: &LedgerGuard<'_>, + budget: &Budget, + fence: &mut impl DurableEffectFence, + ) -> Result<()> { + guard.verify_for_effect(budget)?; + dir.file(OsStr::new(&self.target), &self.new, 256 * 1024 * 1024)?; + dir.file(OsStr::new(&self.backup), &self.old, 256 * 1024 * 1024)?; + let displaced = self.backup.replace(".previous", ".rejected"); + dir.absent(OsStr::new(&displaced))?; + let effect = Effect::RestorePredecessor { role: self.role }; + fence.before_effect(&effect)?; + guard.verify_for_effect(budget)?; + dir.rename_new(OsStr::new(&self.target), OsStr::new(&displaced))?; + // No existing target can be overwritten; both code generations remain. + guard.verify_for_effect(budget)?; + dir.rename_new(OsStr::new(&self.backup), OsStr::new(&self.target))?; + dir.file(OsStr::new(&self.target), &self.old, 256 * 1024 * 1024)?; + fence.after_effect(&effect, &digest(&serde_json::to_vec(&self.old)?)) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct LedgerIdentity { + pub ledger: Identity, + pub lock: Identity, +} +impl LedgerIdentity { + pub fn sha256(&self) -> Result { + Ok(digest(&serde_json::to_vec(self)?)) + } +} + +/// Existing lock only: no create, truncate or alternate database. Acquire only +/// after the caller independently confirmed every installed reader stopped. +pub struct LedgerGuard<'a> { + ledger: File, + lock: File, + directory: Directory, + identity: LedgerIdentity, + stopped: &'a crate::services::StoppedServices, +} +impl<'a> LedgerGuard<'a> { + pub fn acquire( + stopped: &'a crate::services::StoppedServices, + identity: &LedgerIdentity, + budget: &Budget, + ) -> Result { + stopped.verify_still_stopped(budget)?; + let directory = Directory::open(Path::new("/var/lib/rmm-helper"), 0, true)?; + let ledger = openat( + &directory.fd, + OsStr::new("consumption.sqlite"), + libc::O_RDONLY | libc::O_NONBLOCK, + 0, + )?; + let lock = openat( + &directory.fd, + OsStr::new("executor.lock"), + libc::O_RDWR | libc::O_NONBLOCK, + 0, + )?; + let actual = LedgerIdentity { + ledger: Identity::of(&ledger.metadata()?), + lock: Identity::of(&lock.metadata()?), + }; + ensure!( + actual == *identity + && ledger.metadata()?.is_file() + && lock.metadata()?.is_file() + && actual.ledger.uid == 0 + && actual.lock.uid == 0, + "UPDATE_LEDGER_IDENTITY" + ); + ensure!( + unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0, + "UPDATE_LEDGER_BUSY" + ); + let result = Self { + ledger, + lock, + directory, + identity: actual, + stopped, + }; + result.verify_for_effect(budget)?; + Ok(result) + } + pub fn identity(&self) -> &LedgerIdentity { + &self.identity + } + pub fn verify(&self) -> Result<()> { + self.directory.verify()?; + ensure!( + Identity::of(&self.ledger.metadata()?) == self.identity.ledger + && Identity::of(&self.lock.metadata()?) == self.identity.lock, + "UPDATE_LEDGER_HELD_IDENTITY" + ); + self.directory + .named(OsStr::new("consumption.sqlite"), &self.identity.ledger)?; + self.directory + .named(OsStr::new("executor.lock"), &self.identity.lock) + } + pub fn verify_for_effect(&self, budget: &Budget) -> Result<()> { + self.verify()?; + self.stopped.verify_still_stopped(budget) + } + /// Caller must first COMMIT the exact LedgerReturnIntent. This consumes the + /// guard, so it cannot be retained accidentally across the helper start. + pub fn release(self, budget: &Budget, fence: &mut impl DurableEffectFence) -> Result<()> { + self.verify_for_effect(budget)?; + fence.before_effect(&Effect::ReturnLedger)?; + self.verify_for_effect(budget)?; + drop(self); + Ok(()) + } +} +impl Drop for LedgerGuard<'_> { + fn drop(&mut self) { + unsafe { libc::flock(self.lock.as_raw_fd(), libc::LOCK_UN) }; + } +} diff --git a/crates/updater-linux/src/ipc.rs b/crates/updater-linux/src/ipc.rs new file mode 100644 index 0000000..2c1218f --- /dev/null +++ b/crates/updater-linux/src/ipc.rs @@ -0,0 +1,388 @@ +//! One bounded local request, authenticated BEFORE parsing/dispatch. This +//! transport cannot approve, create a grant or choose a path/command/service. +use crate::{ + Budget, + files::Directory, + services::{HeldService, Service, Systemd}, +}; +use anyhow::{Result, ensure}; +use rmm_domain::agent_update::ParticipantIdentity; +use serde::{Deserialize, Serialize}; +use std::{ + fs, + io::{Read, Write}, + os::{ + fd::AsRawFd, + unix::{ + fs::{MetadataExt, PermissionsExt}, + net::{UnixListener, UnixStream}, + }, + }, + path::Path, + time::{Duration, Instant}, +}; +use uuid::Uuid; + +const MAX_FRAME: usize = 32768; +const SOCKET: &str = "/run/rmm-agent-updater/control.sock"; + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(tag = "method", rename_all = "snake_case", deny_unknown_fields)] +pub enum Request { + /// Live service identity only. Not a readiness/approval/start response. + Describe {}, + /// Refers to the ORIGINAL immutable handoff already committed together + /// with consumption. Engine must reject a duplicate or unknown dispatch. + Activate { + grant_id: Uuid, + owner_nonce: Uuid, + handoff_sha256: String, + }, + Read { + grant_id: Uuid, + owner_nonce: Uuid, + handoff_sha256: String, + }, + /// Signed evidence bytes only; Engine independently checks actual local + /// sync/inventory/service/ledger state before the original Outcome CAS. + Health { + grant_id: Uuid, + owner_nonce: Uuid, + handoff_sha256: String, + payload_base64url: String, + signature_base64url: String, + }, +} +impl Request { + fn validate(&self) -> Result<()> { + match self { + Self::Describe {} => Ok(()), + Self::Activate { + grant_id, + owner_nonce, + handoff_sha256, + } + | Self::Read { + grant_id, + owner_nonce, + handoff_sha256, + } + | Self::Health { + grant_id, + owner_nonce, + handoff_sha256, + .. + } => { + ensure!( + !grant_id.is_nil() + && !owner_nonce.is_nil() + && crate::valid_digest(handoff_sha256), + "UPDATE_IPC_BINDING" + ); + if let Self::Health { + payload_base64url, + signature_base64url, + .. + } = self + { + ensure!( + !payload_base64url.is_empty() + && payload_base64url.len() <= 21846 + && signature_base64url.len() == 86, + "UPDATE_IPC_HEALTH_LIMIT" + ); + ensure!( + payload_base64url + .bytes() + .chain(signature_base64url.bytes()) + .all(|b| b.is_ascii_alphanumeric() || b"-_".contains(&b)), + "UPDATE_IPC_BASE64URL" + ); + } + Ok(()) + } + } + } +} +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Response { + pub schema_version: u32, + pub state: State, + /// Always false: this local protocol never publishes ordinary readiness. + pub ready: bool, + pub updater: ParticipantIdentity, + pub head_sha256: Option, +} +#[derive(Clone, Copy, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum State { + Described, + Inflight, + OutcomePersisted, + Unknown, + NotConfigured, +} + +/// Trusted embedding runtime. MUST bind every request to the actual original +/// request/signature/handoff/delegation in the existing helper ledger, enforce +/// one dispatch and its current authenticated participant, and implement all +/// independent clock/trust/health/preservation checks. No default engine. +pub trait Engine { + fn handle(&mut self, peer: &ParticipantIdentity, request: Request) -> Result; +} + +pub struct Listener { + socket: UnixListener, + directory: Directory, + inode: u64, + device: u64, +} +impl Listener { + /// Bootstrap must create the fixed private directory separately. Existing + /// sockets are never unlinked/reused, including after an ambiguous restart. + pub fn bind() -> Result { + ensure!( + unsafe { libc::geteuid() } == 0, + "UPDATE_IPC_ROOT_SERVICE_REQUIRED" + ); + let directory = Directory::open(Path::new("/run/rmm-agent-updater"), 0, true)?; + directory.verify()?; + let socket = UnixListener::bind(SOCKET)?; + fs::set_permissions(SOCKET, fs::Permissions::from_mode(0o600))?; + let m = fs::symlink_metadata(SOCKET)?; + use std::os::unix::fs::FileTypeExt; + ensure!( + m.file_type().is_socket() + && m.uid() == 0 + && m.mode() & 0o777 == 0o600 + && m.nlink() == 1, + "UPDATE_IPC_PRIVATE_SOCKET" + ); + directory.verify()?; + Ok(Self { + socket, + directory, + inode: m.ino(), + device: m.dev(), + }) + } + pub fn serve_one( + &self, + helpers: &Systemd, + budget: &Budget, + engine: &mut impl Engine, + ) -> Result<()> { + budget.check()?; + self.directory.verify()?; + let m = fs::symlink_metadata(SOCKET)?; + ensure!( + m.dev() == self.device + && m.ino() == self.inode + && m.uid() == 0 + && m.mode() & 0o777 == 0o600, + "UPDATE_IPC_SOCKET_CHANGED" + ); + // Poll bounds accept independently of whether any helper connects. + let mut poll = libc::pollfd { + fd: self.socket.as_raw_fd(), + events: libc::POLLIN, + revents: 0, + }; + let result = unsafe { libc::poll(&mut poll, 1, 100) }; + ensure!( + result > 0 && poll.revents == libc::POLLIN, + "UPDATE_IPC_NO_REQUEST" + ); + let (stream, _) = self.socket.accept()?; + let peer = helpers.authenticate_helper_peer(&stream, budget)?; + let mut stream = SocketIo::new(stream, budget); + let request = read_request(&mut stream)?; + budget.check()?; + let response = engine.handle(&peer, request)?; + stream.deadline = Instant::now() + Duration::from_secs(5); + ensure!( + response.schema_version == 1 + && !response.ready + && response.updater.validate() + && response.updater.role == rmm_domain::agent_update::ParticipantRole::LinuxUpdater + && response + .head_sha256 + .as_ref() + .is_none_or(|h| crate::valid_digest(h)), + "UPDATE_IPC_RESPONSE" + ); + let raw = serde_json::to_vec(&response)?; + ensure!( + !raw.is_empty() && raw.len() <= MAX_FRAME, + "UPDATE_IPC_RESPONSE_LIMIT" + ); + stream.write_all(&(raw.len() as u32).to_be_bytes())?; + stream.write_all(&raw)?; + stream.flush()?; + Ok(()) + } +} +fn read_request(stream: &mut impl Read) -> Result { + let mut header = [0; 4]; + stream.read_exact(&mut header)?; + let length = u32::from_be_bytes(header) as usize; + ensure!(length > 0 && length <= MAX_FRAME, "UPDATE_IPC_FRAME_LIMIT"); + let mut raw = vec![0; length]; + stream.read_exact(&mut raw)?; + let value: Request = serde_json::from_slice(&raw)?; + value.validate()?; + Ok(value) +} + +/// Client transport does not retry a mutating Activate after any IO error. +/// Caller must independently verify updater against the fixed service pins. +pub fn exchange( + stream: UnixStream, + updater: &HeldService, + budget: &Budget, + request: &Request, +) -> Result { + budget.check()?; + ensure!( + updater.proof().service == Service::Updater, + "UPDATE_IPC_UPDATER_ROLE" + ); + let authenticated = updater.authenticate_peer(&stream, budget)?; + request.validate()?; + let raw = serde_json::to_vec(request)?; + ensure!(raw.len() <= MAX_FRAME, "UPDATE_IPC_FRAME_LIMIT"); + let mut stream = SocketIo::new(stream, budget); + stream.write_all(&(raw.len() as u32).to_be_bytes())?; + stream.write_all(&raw)?; + stream.flush()?; + let mut length = [0; 4]; + stream.read_exact(&mut length)?; + let length = u32::from_be_bytes(length) as usize; + ensure!( + length > 0 && length <= MAX_FRAME, + "UPDATE_IPC_RESPONSE_LIMIT" + ); + let mut bytes = vec![0; length]; + stream.read_exact(&mut bytes)?; + let response: Response = serde_json::from_slice(&bytes)?; + ensure!( + response.schema_version == 1 + && !response.ready + && response.updater == authenticated + && response + .head_sha256 + .as_ref() + .is_none_or(|h| crate::valid_digest(h)), + "UPDATE_IPC_NOT_READY_OR_WRONG_UPDATER" + ); + updater.verify(budget)?; + Ok(response) +} + +/// A kernel timeout restarts after each successful byte. Also bound the whole +/// frame, including a slow sender. The enclosing job budget is never renewed. +struct SocketIo<'a> { + stream: UnixStream, + budget: &'a Budget, + deadline: Instant, +} +impl<'a> SocketIo<'a> { + fn new(stream: UnixStream, budget: &'a Budget) -> Self { + Self { + stream, + budget, + deadline: Instant::now() + Duration::from_secs(5), + } + } + fn remaining(&self) -> std::io::Result { + let original = self.budget.remaining().map_err(std::io::Error::other)?; + let duration = self + .deadline + .saturating_duration_since(Instant::now()) + .min(original); + if duration.is_zero() { + return Err(std::io::Error::new( + std::io::ErrorKind::TimedOut, + "UPDATE_IPC_FRAME_DEADLINE", + )); + } + Ok(duration) + } +} +impl Read for SocketIo<'_> { + fn read(&mut self, bytes: &mut [u8]) -> std::io::Result { + self.stream.set_read_timeout(Some(self.remaining()?))?; + self.stream.read(bytes) + } +} +impl Write for SocketIo<'_> { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.stream.set_write_timeout(Some(self.remaining()?))?; + self.stream.write(bytes) + } + fn flush(&mut self) -> std::io::Result<()> { + self.remaining()?; + self.stream.flush() + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn framing_denies_large_duplicate_unknown_and_unbound_requests_before_dispatch() { + let frame = |raw: &[u8]| { + let mut b = (raw.len() as u32).to_be_bytes().to_vec(); + b.extend_from_slice(raw); + b + }; + assert!(matches!( + read_request(&mut frame(br#"{"method":"describe"}"#).as_slice()).unwrap(), + Request::Describe {} + )); + for raw in [br#"{"method":"describe","method":"describe"}"#.as_slice(),br#"{"method":"describe","approved":true}"#.as_slice(),br#"{"method":"execute","command":"anything"}"#.as_slice(),br#"{"method":"activate","grant_id":"00000000-0000-0000-0000-000000000000","owner_nonce":"00000000-0000-0000-0000-000000000000","handoff_sha256":"invalid"}"#.as_slice()]{assert!(read_request(&mut frame(raw).as_slice()).is_err());} + assert!(read_request(&mut 32769u32.to_be_bytes().as_slice()).is_err()); + assert!(read_request(&mut 0u32.to_be_bytes().as_slice()).is_err()); + } + #[test] + fn partial_socket_frame_does_not_extend_its_total_deadline() { + for (original, frame) in [ + (Duration::from_secs(1), Duration::from_millis(5)), + (Duration::from_millis(5), Duration::from_secs(5)), + ] { + assert_fragmented_request_expires(original, frame); + } + } + fn assert_fragmented_request_expires(original: Duration, frame: Duration) { + let (left, mut right) = UnixStream::pair().unwrap(); + let boot = fs::read_to_string("/proc/sys/kernel/random/boot_id") + .unwrap() + .trim() + .parse() + .unwrap(); + let (written, wait_written) = std::sync::mpsc::channel(); + let (proceed, wait_proceed) = std::sync::mpsc::channel(); + let sender = std::thread::spawn(move || { + let raw = br#"{"method":"describe"}"#; + right.write_all(&(raw.len() as u32).to_be_bytes()).unwrap(); + right.write_all(&raw[..1]).unwrap(); + written.send(()).unwrap(); + wait_proceed.recv().unwrap(); + for byte in &raw[1..] { + std::thread::sleep(Duration::from_millis(2)); + if right.write_all(&[*byte]).is_err() { + break; + } + } + }); + wait_written.recv().unwrap(); + let budget = Budget::new(boot, original).unwrap(); + let mut receiver = SocketIo::new(left, &budget); + receiver.deadline = Instant::now() + frame; + proceed.send(()).unwrap(); + assert!(read_request(&mut receiver).is_err()); + drop(receiver); + sender.join().unwrap(); + } +} diff --git a/crates/updater-linux/src/lib.rs b/crates/updater-linux/src/lib.rs new file mode 100644 index 0000000..b4128ff --- /dev/null +++ b/crates/updater-linux/src/lib.rs @@ -0,0 +1,90 @@ +//! Linux OS primitives for the separately provisioned stable updater. +//! +//! These are not an approval, executable daemon or update capability. Every +//! mutating primitive requires the embedding worker's durable effect fence; +//! lost replies never resume an operation. No process-name/PID-only fallback. +#![cfg(target_os = "linux")] + +pub mod files; +pub mod ipc; +pub mod process; +pub mod services; + +use anyhow::{Result, ensure}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::time::{Duration, Instant}; +use uuid::Uuid; + +/// One original handoff's local deadline. Constructed after independent live +/// approval/clock/signature/boot/participant checks; possession is no authority. +pub struct Budget { + boot_id: Uuid, + until: Instant, +} +impl Budget { + pub fn new(boot_id: Uuid, remaining: Duration) -> Result { + ensure!( + !boot_id.is_nil() && !remaining.is_zero() && remaining <= Duration::from_secs(600), + "UPDATE_BUDGET" + ); + let result = Self { + boot_id, + until: Instant::now() + .checked_add(remaining) + .ok_or_else(|| anyhow::anyhow!("UPDATE_BUDGET"))?, + }; + result.check()?; + Ok(result) + } + pub fn check(&self) -> Result<()> { + ensure!(Instant::now() < self.until, "UPDATE_DEADLINE"); + ensure!( + std::fs::read_to_string("/proc/sys/kernel/random/boot_id")? + .trim() + .parse::()? + == self.boot_id, + "UPDATE_BOOT_CHANGED" + ); + Ok(()) + } + pub(crate) fn remaining(&self) -> Result { + self.check()?; + let remaining = self.until.saturating_duration_since(Instant::now()); + ensure!(!remaining.is_zero(), "UPDATE_DEADLINE"); + Ok(remaining) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "effect", rename_all = "snake_case", deny_unknown_fields)] +pub enum Effect { + StopService { service: services::Service }, + SavePredecessor { role: files::Role }, + PublishReplacement { role: files::Role }, + StartService { service: services::Service }, + RestorePredecessor { role: files::Role }, + ReturnLedger, +} + +/// MUST perform fresh original-handoff, owner, clock, boot and retained-file +/// checks and COMMIT a create-once intent before returning. No permissive +/// implementation is provided. Effects are in addition to the core ledger's +/// typed event sequence; they never create/replace the original consumption. +pub trait DurableEffectFence { + fn before_effect(&mut self, effect: &Effect) -> Result<()>; + fn after_effect(&mut self, effect: &Effect, observation_sha256: &str) -> Result<()>; +} + +pub(crate) fn digest(bytes: &[u8]) -> String { + hex::encode(Sha256::digest(bytes)) +} +pub(crate) fn valid_digest(value: &str) -> bool { + value.len() == 64 + && value + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) +} + +#[cfg(test)] +mod tests; diff --git a/crates/updater-linux/src/process.rs b/crates/updater-linux/src/process.rs new file mode 100644 index 0000000..664f755 --- /dev/null +++ b/crates/updater-linux/src/process.rs @@ -0,0 +1,239 @@ +//! Held Linux process identity: pidfd + proc directory + executable descriptor. +//! A vanished/reused PID is never accepted as the original participant. +use crate::{digest, valid_digest}; +use anyhow::{Result, ensure}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::{ + ffi::CString, + fs::File, + io::Read, + os::{ + fd::{AsRawFd, FromRawFd}, + unix::fs::{FileExt, MetadataExt}, + }, +}; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ProcessProof { + pub pid: u32, + pub birth: u64, + pub uid: u32, + pub gid: u32, + pub image_sha256: String, +} +pub struct HeldProcess { + pidfd: File, + proc: File, + image: File, + proof: ProcessProof, +} + +fn proc_file(dir: &File, name: &str) -> Result { + let name = CString::new(name)?; + let fd = unsafe { + libc::openat( + dir.as_raw_fd(), + name.as_ptr(), + libc::O_RDONLY | libc::O_CLOEXEC | libc::O_NOFOLLOW, + ) + }; + ensure!( + fd >= 0, + "UPDATE_PROCESS_READ: {}", + std::io::Error::last_os_error() + ); + Ok(unsafe { File::from_raw_fd(fd) }) +} +fn bytes(dir: &File, name: &str) -> Result> { + let fd = proc_file(dir, name)?; + let mut raw = Vec::new(); + fd.take(65537).read_to_end(&mut raw)?; + ensure!(raw.len() <= 65536, "UPDATE_PROC_LIMIT"); + Ok(raw) +} +fn birth(dir: &File) -> Result { + let raw = bytes(dir, "stat")?; + let raw = std::str::from_utf8(&raw)?; + let (_, fields) = raw + .rsplit_once(") ") + .ok_or_else(|| anyhow::anyhow!("UPDATE_PROC_STAT"))?; + let birth = fields + .split_ascii_whitespace() + .nth(19) + .ok_or_else(|| anyhow::anyhow!("UPDATE_PROC_STAT"))? + .parse()?; + ensure!(birth > 0, "UPDATE_PROCESS_BIRTH"); + Ok(birth) +} +fn ids(dir: &File) -> Result<(u32, u32)> { + let raw = bytes(dir, "status")?; + let raw = std::str::from_utf8(&raw)?; + let row = |key: &str| -> Result { + let rows: Vec<_> = raw + .lines() + .filter_map(|line| line.strip_prefix(key)) + .collect(); + ensure!(rows.len() == 1, "UPDATE_PROCESS_IDS"); + let values: Vec = rows[0] + .split_ascii_whitespace() + .map(str::parse) + .collect::>()?; + ensure!( + values.len() == 4 && values.iter().all(|v| *v == values[0]), + "UPDATE_PROCESS_IDS" + ); + Ok(values[0]) + }; + Ok((row("Uid:")?, row("Gid:")?)) +} +fn image_hash(image: &File) -> Result { + let m = image.metadata()?; + ensure!( + m.is_file() && m.uid() == 0 && m.mode() & 0o022 == 0 && m.len() <= 256 * 1024 * 1024, + "UPDATE_PROCESS_IMAGE" + ); + let mut hash = Sha256::new(); + let mut buf = [0; 32768]; + let mut n = 0u64; + loop { + let read = image.read_at(&mut buf, n)?; + if read == 0 { + break; + } + n += read as u64; + ensure!(n <= 256 * 1024 * 1024, "UPDATE_PROCESS_IMAGE_LIMIT"); + hash.update(&buf[..read]); + } + let after = image.metadata()?; + ensure!( + m.dev() == after.dev() + && m.ino() == after.ino() + && m.len() == after.len() + && m.mtime() == after.mtime() + && m.mtime_nsec() == after.mtime_nsec() + && m.ctime() == after.ctime() + && m.ctime_nsec() == after.ctime_nsec(), + "UPDATE_PROCESS_IMAGE_CHANGED" + ); + Ok(hex::encode(hash.finalize())) +} + +fn process_image(proc: &File) -> Result { + // Follow only this kernel magic link through the already held proc dir. + let exe = CString::new("exe")?; + let fd = unsafe { + libc::openat( + proc.as_raw_fd(), + exe.as_ptr(), + libc::O_RDONLY | libc::O_CLOEXEC, + ) + }; + ensure!(fd >= 0, "UPDATE_PROCESS_IMAGE_OPEN"); + Ok(unsafe { File::from_raw_fd(fd) }) +} +fn same_image(left: &File, right: &File) -> Result { + let a = left.metadata()?; + let b = right.metadata()?; + Ok(a.dev() == b.dev() && a.ino() == b.ino()) +} + +impl HeldProcess { + pub fn open(pid: u32, uid: u32, gid: u32, expected_image: &str) -> Result { + ensure!( + pid > 1 && valid_digest(expected_image), + "UPDATE_PROCESS_DESCRIPTOR" + ); + // SAFETY: pidfd_open returns a new descriptor or -1. Unsupported + // kernels fail closed; no fallback to kill(pid) or name matching. + let fd = unsafe { libc::syscall(libc::SYS_pidfd_open, pid, 0) }; + ensure!( + fd >= 0, + "UPDATE_PIDFD_UNAVAILABLE: {}", + std::io::Error::last_os_error() + ); + let pidfd = unsafe { File::from_raw_fd(fd as i32) }; + let path = CString::new(format!("/proc/{pid}"))?; + let fd = unsafe { + libc::open( + path.as_ptr(), + libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC, + ) + }; + ensure!(fd >= 0, "UPDATE_PROC_DIRECTORY"); + let proc = unsafe { File::from_raw_fd(fd) }; + let start = birth(&proc)?; + let actual_ids = ids(&proc)?; + // /proc/PID/exe is deliberately followed only through this held kernel + // proc directory; it is not a caller-controlled filesystem symlink. + let image = process_image(&proc)?; + let sha = image_hash(&image)?; + ensure!( + actual_ids == (uid, gid) && sha == expected_image && birth(&proc)? == start, + "UPDATE_PROCESS_BINDING" + ); + let result = Self { + pidfd, + proc, + image, + proof: ProcessProof { + pid, + birth: start, + uid, + gid, + image_sha256: sha, + }, + }; + result.verify()?; + Ok(result) + } + pub fn proof(&self) -> &ProcessProof { + &self.proof + } + pub fn exited(&self) -> Result { + let mut p = libc::pollfd { + fd: self.pidfd.as_raw_fd(), + events: libc::POLLIN, + revents: 0, + }; + let result = unsafe { libc::poll(&mut p, 1, 0) }; + ensure!( + result >= 0 && p.revents & (libc::POLLNVAL | libc::POLLERR) == 0, + "UPDATE_PIDFD_POLL" + ); + Ok(result > 0 && p.revents & (libc::POLLIN | libc::POLLHUP) != 0) + } + pub fn verify(&self) -> Result<()> { + ensure!( + !self.exited()? + && birth(&self.proc)? == self.proof.birth + && ids(&self.proc)? == (self.proof.uid, self.proof.gid), + "UPDATE_PROCESS_EXITED_OR_CHANGED" + ); + // pidfd, creation time and credentials all survive execve(). Rebind + // BOTH before and after hashing to the executable currently selected + // by this exact held proc directory, never merely the old image FD. + let current = process_image(&self.proc)?; + ensure!( + same_image(¤t, &self.image)? + && image_hash(&self.image)? == self.proof.image_sha256 + && image_hash(¤t)? == self.proof.image_sha256, + "UPDATE_PROCESS_IMAGE_CHANGED" + ); + let after = process_image(&self.proc)?; + ensure!( + same_image(&after, ¤t)? + && same_image(&after, &self.image)? + && !self.exited()? + && birth(&self.proc)? == self.proof.birth + && ids(&self.proc)? == (self.proof.uid, self.proof.gid), + "UPDATE_PROCESS_IMAGE_CHANGED" + ); + Ok(()) + } + pub fn sha256(&self) -> Result { + self.verify()?; + Ok(digest(&serde_json::to_vec(&self.proof)?)) + } +} diff --git a/crates/updater-linux/src/services.rs b/crates/updater-linux/src/services.rs new file mode 100644 index 0000000..e1474e5 --- /dev/null +++ b/crates/updater-linux/src/services.rs @@ -0,0 +1,552 @@ +//! Closed systemd service set; status is corroborated with held kernel process +//! identity. No shell, enable/reboot, global kill or repeated stop/start. +use crate::{ + Budget, DurableEffectFence, Effect, digest, + process::{HeldProcess, ProcessProof}, +}; +use anyhow::{Result, ensure}; +use serde::{Deserialize, Serialize}; +use std::{ + collections::BTreeMap, + fs::File, + io::Read, + os::fd::{AsRawFd, FromRawFd}, + os::unix::net::UnixStream, + process::{Child, Command, Stdio}, + thread, + time::{Duration, Instant}, +}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Service { + Agent, + General, + Full, + Apt, + Updater, +} +impl Service { + fn handoff_service(self) -> Result { + Ok(match self { + Self::Agent => rmm_updater_handoff::Service::LinuxAgent, + Self::General => rmm_updater_handoff::Service::LinuxGeneralHelper, + Self::Full => rmm_updater_handoff::Service::LinuxFullHelper, + Self::Apt => rmm_updater_handoff::Service::LinuxAptHelper, + Self::Updater => anyhow::bail!("UPDATE_UPDATER_NOT_IN_TARGET_SET"), + }) + } + pub fn unit(self) -> &'static str { + match self { + Self::Agent => "rmm-agent-remote.service", + Self::General => "rmm-helper-cloud.service", + Self::Full => "rmm-full-maintenance-helper.service", + Self::Apt => "rmm-apt-helper.service", + Self::Updater => "rmm-agent-updater.service", + } + } + fn uid(self) -> u32 { + if self == Self::Agent { 993 } else { 0 } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ServiceProof { + pub service: Service, + pub invocation_id: String, + pub enabled: String, + pub process: ProcessProof, + pub unit_sha256: String, +} +pub struct HeldService { + proof: ServiceProof, + process: HeldProcess, +} +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ServicePolicy { + pub service: Service, + pub image_sha256: String, + pub unit_sha256: String, +} + +pub struct Systemd { + policies: Vec, +} +impl Systemd { + pub fn observe_updater(pin: ServicePolicy, budget: &Budget) -> Result { + ensure!( + pin.service == Service::Updater + && crate::valid_digest(&pin.image_sha256) + && crate::valid_digest(&pin.unit_sha256), + "UPDATE_UPDATER_PINS" + ); + Self { + policies: vec![pin], + } + .observe(Service::Updater, budget) + } + /// Full is an ordinary required participant in the current Linux topology; + /// APT may additionally be installed but is never in the restart set. + pub fn new(policies: Vec) -> Result { + let services: Vec<_> = policies.iter().map(|p| p.service).collect(); + ensure!( + services == [Service::Agent, Service::General, Service::Full] + || services + == [ + Service::Agent, + Service::General, + Service::Full, + Service::Apt + ], + "UPDATE_CLOSED_SERVICE_SET" + ); + ensure!( + policies.iter().all( + |p| crate::valid_digest(&p.image_sha256) && crate::valid_digest(&p.unit_sha256) + ), + "UPDATE_SERVICE_PINS" + ); + ensure!( + policies[1].image_sha256 == policies[2].image_sha256, + "UPDATE_HELPER_PAIR_MISMATCH" + ); + Ok(Self { policies }) + } + pub fn authenticate_helper_peer( + &self, + socket: &UnixStream, + budget: &Budget, + ) -> Result { + for service in [Service::General, Service::Full] { + let held = self.observe(service, budget)?; + if let Ok(peer) = held.authenticate_peer(socket, budget) { + return Ok(peer); + } + } + anyhow::bail!("UPDATE_HELPER_PEER_NOT_BOUND") + } + fn status(service: Service, budget: &Budget) -> Result> { + budget.check()?; + let output = command( + &[ + "show", + service.unit(), + "-p", + "LoadState", + "-p", + "ActiveState", + "-p", + "MainPID", + "-p", + "InvocationID", + "-p", + "UnitFileState", + "-p", + "FragmentPath", + "-p", + "DropInPaths", + ], + budget, + )?; + let text = std::str::from_utf8(&output)?; + let mut fields = BTreeMap::new(); + for row in text.lines() { + let (k, v) = row + .split_once('=') + .ok_or_else(|| anyhow::anyhow!("UPDATE_SYSTEMD_RESPONSE"))?; + ensure!( + fields.insert(k.into(), v.into()).is_none(), + "UPDATE_SYSTEMD_DUPLICATE" + ); + } + ensure!( + fields.len() == 8 && fields.get("LoadState").is_some_and(|v| v == "loaded"), + "UPDATE_SYSTEMD_LOADED" + ); + Ok(fields) + } + pub fn observe(&self, service: Service, budget: &Budget) -> Result { + let pin = self + .policies + .iter() + .find(|p| p.service == service) + .ok_or_else(|| anyhow::anyhow!("UPDATE_SERVICE_NOT_PINNED"))?; + let first = Self::status(service, budget)?; + ensure!( + first.get("ActiveState").is_some_and(|s| s == "active"), + "UPDATE_SERVICE_INACTIVE" + ); + let pid = first + .get("MainPID") + .ok_or_else(|| anyhow::anyhow!("UPDATE_SERVICE_PID"))? + .parse()?; + let invocation_id = first + .get("InvocationID") + .ok_or_else(|| anyhow::anyhow!("UPDATE_SERVICE_INSTANCE"))? + .to_owned(); + ensure!( + invocation_id.len() == 32 && invocation_id.bytes().all(|b| b.is_ascii_hexdigit()), + "UPDATE_SERVICE_INSTANCE" + ); + // Unit composition must be independently provisioned. No unrecognized + // drop-in is silently ignored or inherited as an update permission. + let unit_sha = unit_composition(&first)?; + ensure!(unit_sha == pin.unit_sha256, "UPDATE_UNIT_CHANGED"); + let process = HeldProcess::open( + pid, + service.uid(), + if service == Service::Updater { 0 } else { 984 }, + &pin.image_sha256, + )?; + ensure!( + Self::status(service, budget)? == first, + "UPDATE_SERVICE_CHANGED_DURING_OBSERVATION" + ); + process.verify()?; + Ok(HeldService { + proof: ServiceProof { + service, + invocation_id, + enabled: first["UnitFileState"].clone(), + process: process.proof().clone(), + unit_sha256: unit_sha, + }, + process, + }) + } + pub fn stop_all( + self, + budget: &Budget, + fence: &mut impl DurableEffectFence, + ) -> Result { + let mut original = Vec::new(); + for pin in &self.policies { + if pin.service == Service::Apt { + let s = Self::status(Service::Apt, budget)?; + ensure!( + s["ActiveState"] == "inactive" + && s["MainPID"] == "0" + && s["UnitFileState"] == "disabled" + && unit_composition(&s)? == pin.unit_sha256, + "UPDATE_APT_MUST_REMAIN_CLOSED" + ); + } else { + original.push(self.observe(pin.service, budget)?); + } + } + for held in &original { + held.process.verify()?; + let effect = Effect::StopService { + service: held.proof.service, + }; + fence.before_effect(&effect)?; + budget.check()?; + command(&["--no-block", "stop", held.proof.service.unit()], budget)?; + loop { + budget.check()?; + let state = Self::status(held.proof.service, budget)?; + if state["ActiveState"] == "inactive" + && state["MainPID"] == "0" + && held.process.exited()? + { + break; + } + ensure!( + state["MainPID"] == "0" + || state["MainPID"] == held.proof.process.pid.to_string(), + "UPDATE_STOP_PID_CHANGED" + ); + thread::sleep(Duration::from_millis(20)); + } + fence.after_effect(&effect, &digest(&serde_json::to_vec(&held.proof)?))?; + } + let result = StoppedServices { + systemd: self, + original, + }; + result.verify_still_stopped(budget)?; + Ok(result) + } +} +impl HeldService { + pub fn started_proof(&self, budget: &Budget) -> Result { + self.verify(budget)?; + ensure!( + self.proof.service != Service::Apt, + "UPDATE_APT_NOT_IN_START_SET" + ); + Ok(rmm_updater_handoff::StartedService { + service: self.proof.service.handoff_service()?, + process: rmm_updater_handoff::Process { + pid: self.proof.process.pid, + birth: self.proof.process.birth, + image_sha256: self.proof.process.image_sha256.clone(), + }, + }) + } + pub fn proof(&self) -> &ServiceProof { + &self.proof + } + pub fn verify(&self, budget: &Budget) -> Result<()> { + self.process.verify()?; + let current = Systemd::status(self.proof.service, budget)?; + ensure!( + current["ActiveState"] == "active" + && current["MainPID"] == self.proof.process.pid.to_string() + && current["InvocationID"] == self.proof.invocation_id + && current["UnitFileState"] == self.proof.enabled + && unit_composition(¤t)? == self.proof.unit_sha256, + "UPDATE_SERVICE_BINDING_CHANGED" + ); + self.process.verify() + } + /// Authenticate the actual local connection independently of request JSON. + /// Root alone is insufficient; the fixed service's held pidfd must match. + pub fn authenticate_peer( + &self, + socket: &UnixStream, + budget: &Budget, + ) -> Result { + use rmm_domain::agent_update::{ParticipantIdentity, ParticipantRole}; + self.verify(budget)?; + let mut peer = std::mem::MaybeUninit::::uninit(); + let mut len = std::mem::size_of::() as libc::socklen_t; + // SAFETY: live Unix socket, correctly sized writable ucred and length. + let result = unsafe { + libc::getsockopt( + socket.as_raw_fd(), + libc::SOL_SOCKET, + libc::SO_PEERCRED, + peer.as_mut_ptr().cast(), + &mut len, + ) + }; + ensure!( + result == 0 && len as usize == std::mem::size_of::(), + "UPDATE_PEER_CREDENTIALS" + ); + let peer = unsafe { peer.assume_init() }; + ensure!( + peer.pid > 0 + && peer.pid as u32 == self.proof.process.pid + && peer.uid == 0 + && peer.gid == self.proof.process.gid, + "UPDATE_PEER_SERVICE_BINDING" + ); + let role = match self.proof.service { + Service::Updater => ParticipantRole::LinuxUpdater, + Service::General => ParticipantRole::LinuxGeneralHelper, + Service::Full => ParticipantRole::LinuxFullHelper, + _ => anyhow::bail!("UPDATE_PARTICIPANT_ROLE"), + }; + self.verify(budget)?; + Ok(ParticipantIdentity { + role, + pid: self.proof.process.pid, + birth: self.proof.process.birth, + image_sha256: self.proof.process.image_sha256.clone(), + security_principal: "uid:0".into(), + service_instance_sha256: digest(&serde_json::to_vec(&self.proof)?), + }) + } +} + +pub struct StoppedServices { + systemd: Systemd, + original: Vec, +} +impl StoppedServices { + pub fn verify_still_stopped(&self, budget: &Budget) -> Result<()> { + for pin in &self.systemd.policies { + let s = Systemd::status(pin.service, budget)?; + ensure!( + s["ActiveState"] == "inactive" + && s["MainPID"] == "0" + && unit_composition(&s)? == pin.unit_sha256, + "UPDATE_READER_NOT_STOPPED" + ); + if pin.service == Service::Apt { + ensure!( + s["UnitFileState"] == "disabled", + "UPDATE_APT_MUST_REMAIN_CLOSED" + ); + } + } + ensure!( + self.original + .iter() + .all(|s| s.process.exited().unwrap_or(false)), + "UPDATE_OLD_PROCESS_STILL_LIVE" + ); + Ok(()) + } + pub fn proofs(&self) -> Vec { + self.original.iter().map(|s| s.proof.clone()).collect() + } + /// The embedding fence MUST verify the exact PairVerified and durable + /// LedgerReturnIntent, released same guard and new target hashes first. + pub fn start_once( + self, + new: Systemd, + budget: &Budget, + fence: &mut impl DurableEffectFence, + ) -> Result> { + self.verify_still_stopped(budget)?; + ensure!( + self.systemd + .policies + .iter() + .map(|p| p.service) + .eq(new.policies.iter().map(|p| p.service)), + "UPDATE_START_SET_CHANGED" + ); + let mut started = Vec::new(); + for service in [Service::General, Service::Full, Service::Agent] { + let effect = Effect::StartService { service }; + fence.before_effect(&effect)?; + budget.check()?; + command(&["--no-block", "start", service.unit()], budget)?; + loop { + budget.check()?; + let state = Systemd::status(service, budget)?; + if state["ActiveState"] == "active" && state["MainPID"] != "0" { + let held = new.observe(service, budget)?; + ensure!( + !self + .original + .iter() + .any(|old| old.proof.process.pid == held.proof.process.pid), + "UPDATE_PROCESS_REUSE" + ); + fence.after_effect(&effect, &digest(&serde_json::to_vec(&held.proof)?))?; + started.push(held); + break; + } + ensure!( + state["ActiveState"] == "activating" || state["ActiveState"] == "active", + "UPDATE_START_UNPROVEN" + ); + thread::sleep(Duration::from_millis(20)); + } + } + // Return in the canonical Handoff stop-set order, not actual start order. + started.sort_by_key(|s| s.proof.service); + Ok(started) + } +} + +fn unit_composition(fields: &BTreeMap) -> Result { + use crate::files::Directory; + use std::{ffi::OsStr, path::Path}; + let fragment = fields + .get("FragmentPath") + .ok_or_else(|| anyhow::anyhow!("UPDATE_UNIT_FRAGMENT"))?; + let mut paths = vec![fragment.as_str()]; + paths.extend( + fields + .get("DropInPaths") + .ok_or_else(|| anyhow::anyhow!("UPDATE_UNIT_DROPINS"))? + .split_ascii_whitespace(), + ); + let mut proof = Vec::new(); + for path in paths { + let path = Path::new(path); + ensure!(path.is_absolute(), "UPDATE_UNIT_PATH"); + let directory = Directory::open( + path.parent() + .ok_or_else(|| anyhow::anyhow!("UPDATE_UNIT_PARENT"))?, + 0, + false, + )?; + let file = directory.inspect(path.file_name().unwrap_or(OsStr::new("")), 0, 65536)?; + proof.push((path.to_string_lossy().into_owned(), file.proof().clone())); + } + Ok(digest(&serde_json::to_vec(&proof)?)) +} + +struct OwnedCommand { + child: Child, + pidfd: File, +} +impl Drop for OwnedCommand { + fn drop(&mut self) { + // Signal this exact retained kernel process, including on every early + // error. An exited child cannot turn the descriptor into another PID. + unsafe { + libc::syscall( + libc::SYS_pidfd_send_signal, + self.pidfd.as_raw_fd(), + libc::SIGKILL, + 0usize, + 0, + ) + }; + let _ = self.child.wait(); + } +} +fn drain(stream: &mut dyn Read, buffer: &mut Vec) -> Result<()> { + let mut bytes = [0; 1024]; + loop { + match stream.read(&mut bytes) { + Ok(0) => break, + Ok(n) => { + ensure!(buffer.len() + n <= 16384, "UPDATE_COMMAND_OUTPUT_LIMIT"); + buffer.extend_from_slice(&bytes[..n]); + } + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break, + Err(e) => return Err(e.into()), + } + } + Ok(()) +} +fn command(args: &[&str], budget: &Budget) -> Result> { + budget.check()?; + let mut child = Command::new("/usr/bin/systemctl") + .args(["--system", "--no-ask-password", "--no-pager"]) + .args(args) + .env_clear() + .env("PATH", "/usr/bin:/bin") + .env("LC_ALL", "C") + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn()?; + // A live Child has not been reaped, so this pidfd cannot target a reused PID. + let raw = unsafe { libc::syscall(libc::SYS_pidfd_open, child.id(), 0) }; + if raw < 0 { + let _ = child.kill(); + let _ = child.wait(); + anyhow::bail!("UPDATE_COMMAND_PIDFD_UNAVAILABLE"); + } + let pidfd = unsafe { File::from_raw_fd(raw as i32) }; + let mut owned = OwnedCommand { child, pidfd }; + let deadline = Instant::now() + Duration::from_secs(10); + let mut stdout = owned.child.stdout.take().unwrap(); + let mut stderr = owned.child.stderr.take().unwrap(); + for fd in [stdout.as_raw_fd(), stderr.as_raw_fd()] { + ensure!( + unsafe { libc::fcntl(fd, libc::F_SETFL, libc::O_NONBLOCK) } >= 0, + "UPDATE_COMMAND_NONBLOCK" + ); + } + let mut out = Vec::new(); + let mut error = Vec::new(); + loop { + drain(&mut stdout, &mut out)?; + drain(&mut stderr, &mut error)?; + if let Some(status) = owned.child.try_wait()? { + drain(&mut stdout, &mut out)?; + drain(&mut stderr, &mut error)?; + ensure!(status.success(), "UPDATE_SYSTEMD_COMMAND_FAILED"); + return Ok(out); + } + if budget.check().is_err() || Instant::now() >= deadline { + // Kill only our held systemctl client. A request may already have + // reached systemd: the embedding worker must record Unknown. + anyhow::bail!("UPDATE_SYSTEMD_REPLY_UNKNOWN"); + } + thread::sleep(Duration::from_millis(5)); + } +} diff --git a/crates/updater-linux/src/tests.rs b/crates/updater-linux/src/tests.rs new file mode 100644 index 0000000..bfbfe40 --- /dev/null +++ b/crates/updater-linux/src/tests.rs @@ -0,0 +1,158 @@ +//! Real OS adverse cases, confined to a new /run unit fixture and owned sleep +//! child. Never calls systemctl, real install paths, RMM ledger or networking. +use crate::{ + Budget, digest, + files::{Directory, FileProof}, + process::HeldProcess, +}; +use std::{ + ffi::OsStr, + fs::{self, OpenOptions}, + io::Write, + os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt, symlink}, + path::PathBuf, + process::{Command, Stdio}, + time::{Duration, Instant}, +}; +use uuid::Uuid; + +struct Fixture(PathBuf); +impl Fixture { + fn new() -> Self { + assert_eq!( + unsafe { libc::geteuid() }, + 0, + "Run OS contract tests in the isolated root-owned test container, never as a host daemon" + ); + let path = PathBuf::from(format!("/run/rmm-updater-os-unit-{}", Uuid::new_v4())); + fs::create_dir(&path).unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o700)).unwrap(); + Self(path) + } + fn dir(&self) -> Directory { + Directory::open(&self.0, 0, true).unwrap() + } + fn file(&self, name: &str, bytes: &[u8]) { + let mut file = OpenOptions::new() + .create_new(true) + .write(true) + .mode(0o600) + .open(self.0.join(name)) + .unwrap(); + file.write_all(bytes).unwrap(); + file.sync_all().unwrap(); + } +} +impl Drop for Fixture { + fn drop(&mut self) { + fs::remove_dir_all(&self.0).unwrap(); + } +} + +#[test] +fn held_file_rejects_symlink_and_replaced_name_but_preserves_bound_hardlinks() { + let f = Fixture::new(); + f.file("original", b"original-public-fixture"); + fs::hard_link(f.0.join("original"), f.0.join("historical-alias")).unwrap(); + let dir = f.dir(); + let mut held = dir.inspect(OsStr::new("original"), 0, 1024).unwrap(); + assert_eq!(held.proof().identity.links, 2); + let proof: FileProof = held.proof().clone(); + assert_eq!(held.bytes(1024).unwrap(), b"original-public-fixture"); + symlink("original", f.0.join("symlink")).unwrap(); + assert!(dir.inspect(OsStr::new("symlink"), 0, 1024).is_err()); + fs::rename(f.0.join("original"), f.0.join("retained")).unwrap(); + f.file("original", b"replacement"); + assert!(dir.file(OsStr::new("original"), &proof, 1024).is_err()); + assert_eq!(held.bytes(1024).unwrap(), b"original-public-fixture"); + assert_eq!( + fs::metadata(f.0.join("retained")).unwrap().ino(), + proof.identity.inode + ); + assert_eq!( + fs::read(f.0.join("historical-alias")).unwrap(), + b"original-public-fixture" + ); + fs::set_permissions(f.0.join("original"), fs::Permissions::from_mode(0o622)).unwrap(); + assert!(dir.inspect(OsStr::new("original"), 0, 1024).is_err()); + assert!(Directory::open(&f.0.join("symlink"), 0, true).is_err()); +} + +#[test] +fn pidfd_image_birth_account_and_exit_are_independently_observed() { + let image = fs::read("/usr/bin/sleep").unwrap(); + let sha = digest(&image); + let mut child = Command::new("/usr/bin/sleep").arg("60").spawn().unwrap(); + let process = HeldProcess::open(child.id(), 0, 0, &sha).unwrap(); + process.verify().unwrap(); + assert!(!process.exited().unwrap()); + assert!(HeldProcess::open(child.id(), 1, 0, &sha).is_err()); + assert!(HeldProcess::open(child.id(), 0, 0, &"0".repeat(64)).is_err()); + let before = process.proof().clone(); + child.kill().unwrap(); + child.wait().unwrap(); + let deadline = Instant::now() + Duration::from_secs(2); + while !process.exited().unwrap() { + assert!(Instant::now() < deadline); + std::thread::yield_now(); + } + assert!(process.verify().is_err()); + assert_eq!(process.proof(), &before); + let boot = fs::read_to_string("/proc/sys/kernel/random/boot_id") + .unwrap() + .trim() + .parse() + .unwrap(); + assert!(Budget::new(Uuid::nil(), Duration::from_secs(1)).is_err()); + assert!(Budget::new(boot, Duration::from_secs(601)).is_err()); + let budget = Budget::new(boot, Duration::from_millis(100)).unwrap(); + std::thread::sleep(Duration::from_millis(150)); + assert!(budget.check().is_err()); +} + +#[test] +fn same_pid_exec_rejects_changed_image_despite_retained_pidfd_birth_and_credentials() { + struct ChildCleanup(std::process::Child); + impl Drop for ChildCleanup { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } + } + let old_image = fs::read("/usr/bin/bash").unwrap(); + let new_image = fs::read("/usr/bin/sleep").unwrap(); + let mut child = ChildCleanup( + Command::new("/usr/bin/bash") + .env_clear() + .args(["-c", "read -r token; exec /usr/bin/sleep 60"]) + .stdin(Stdio::piped()) + .spawn() + .unwrap(), + ); + let held = HeldProcess::open(child.0.id(), 0, 0, &digest(&old_image)).unwrap(); + let before = held.proof().clone(); + held.verify().unwrap(); + child.0.stdin.take().unwrap().write_all(b"go\n").unwrap(); + let deadline = Instant::now() + Duration::from_secs(3); + let fresh = loop { + assert!( + Instant::now() < deadline, + "owned fixture child never completed exec" + ); + match HeldProcess::open(child.0.id(), 0, 0, &digest(&new_image)) { + Ok(process) => break process, + Err(_) => std::thread::yield_now(), + } + }; + assert_eq!(fresh.proof().pid, before.pid); + assert_eq!(fresh.proof().birth, before.birth); + assert_eq!( + (fresh.proof().uid, fresh.proof().gid), + (before.uid, before.gid) + ); + assert_ne!(fresh.proof().image_sha256, before.image_sha256); + assert!(!held.exited().unwrap()); + assert!(held.verify().is_err()); + child.0.kill().unwrap(); + child.0.wait().unwrap(); +} diff --git a/crates/updater-worker/Cargo.toml b/crates/updater-worker/Cargo.toml new file mode 100644 index 0000000..0db04c4 --- /dev/null +++ b/crates/updater-worker/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "rmm-updater-worker" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +anyhow.workspace = true +chrono.workspace = true +hex.workspace = true +serde.workspace = true +serde_json.workspace = true +uuid.workspace = true +libc = "0.2.177" +rusqlite = { version = "0.32.1", features = ["bundled"] } +ed25519-dalek = "=2.2.0" +rmm-domain = { path = "../domain" } +rmm-agent-core = { path = "../agent-core" } +rmm-updater = { path = "../updater" } +rmm-updater-handoff = { path = "../updater-handoff" } +rmm-updater-linux = { path = "../updater-linux" } + +[dev-dependencies] +base64 = "=0.22.1" diff --git a/crates/updater-worker/src/clock.rs b/crates/updater-worker/src/clock.rs new file mode 100644 index 0000000..f901acf --- /dev/null +++ b/crates/updater-worker/src/clock.rs @@ -0,0 +1,43 @@ +//! Current native clock evidence, independent of agent/IPC timestamps. +use anyhow::{Result, ensure}; +use chrono::{DateTime, Utc}; +use rmm_agent_core::reconcile::SyncClock; +use std::time::Instant; + +pub struct NativeClock { + wall: DateTime, + monotonic: Instant, +} +impl NativeClock { + pub fn new() -> Result { + let value = Self { + wall: Utc::now(), + monotonic: Instant::now(), + }; + value.now()?; + Ok(value) + } +} +impl SyncClock for NativeClock { + fn now(&self) -> Result> { + let mut timex = std::mem::MaybeUninit::::zeroed(); + // modes=0 is strictly a read-only kernel synchronization/error query. + let status = unsafe { libc::adjtimex(timex.as_mut_ptr()) }; + let timex = unsafe { timex.assume_init() }; + ensure!( + status >= 0 + && status != libc::TIME_ERROR + && timex.status & libc::STA_UNSYNC == 0 + && timex.maxerror >= 0 + && timex.maxerror <= 5_000_000, + "UPDATE_CLOCK_UNTRUSTED" + ); + let now = Utc::now(); + let elapsed = i64::try_from(self.monotonic.elapsed().as_millis())?; + ensure!( + ((now - self.wall).num_milliseconds() - elapsed).unsigned_abs() <= 5000, + "UPDATE_CLOCK_CHANGED" + ); + Ok(now) + } +} diff --git a/crates/updater-worker/src/fence.rs b/crates/updater-worker/src/fence.rs new file mode 100644 index 0000000..2cba657 --- /dev/null +++ b/crates/updater-worker/src/fence.rs @@ -0,0 +1,119 @@ +//! Concrete durable Save/Publish fence against the ORIGINAL helper ledger. +//! One live forward pass; construction cannot resume a partial ReplaceIntent. +use crate::ledger::OwnedLedger; +use anyhow::{Result, ensure}; +use rmm_agent_core::update_handoff::{NativeEffect, NativeEffectClaim, NativeFileRole}; +use rmm_updater_handoff::{Evidence, Phase}; +use rmm_updater_linux::{DurableEffectFence, Effect, files::Role}; + +fn native_role(role: Role) -> NativeFileRole { + match role { + Role::Agent => NativeFileRole::AgentBinary, + Role::Helper => NativeFileRole::HelperBinary, + Role::FullConfig => NativeFileRole::FullConfig, + Role::FullPin => NativeFileRole::FullPin, + } +} +pub struct LedgerFence<'w, 'a, 's> { + ledger: &'w mut OwnedLedger<'a, 's>, + pending: Option<(Effect, NativeEffectClaim)>, + saved: Option, + poisoned: bool, +} +impl<'w, 'a, 's> LedgerFence<'w, 'a, 's> { + pub fn new(ledger: &'w mut OwnedLedger<'a, 's>) -> Result { + ensure!( + ledger.journal()?.phase() == Phase::UpdaterOwnsLedger, + "UPDATE_NO_FENCE_RESUME" + ); + Ok(Self { + ledger, + pending: None, + saved: None, + poisoned: false, + }) + } + /// A failed native call must poison/drop this fence. No reentry/retry API. + pub fn finish(self) -> Result<()> { + ensure!( + !self.poisoned + && self.pending.is_none() + && self.saved.is_none() + && self.ledger.journal()?.phase() == Phase::Replaced, + "UPDATE_FENCE_INCOMPLETE" + ); + self.ledger.verify_pair()?; + Ok(()) + } + fn claim(&mut self, effect: &Effect) -> Result<()> { + ensure!( + !self.poisoned && self.pending.is_none(), + "UPDATE_FENCE_REENTRY" + ); + // Poison BEFORE a fallible commit or OS operation. Only a fully + // observed matching callback can return the live pass to idle. + self.poisoned = true; + let native = match *effect { + Effect::SavePredecessor { role } => { + ensure!(self.saved.is_none(), "UPDATE_SAVE_ORDER"); + self.ledger.append_observed(Evidence::ReplaceIntent { + role: role.handoff_role(), + })?; + NativeEffect::SavePredecessor { + role: native_role(role), + } + } + Effect::PublishReplacement { role } => { + ensure!(self.saved == Some(role), "UPDATE_PUBLISH_WITHOUT_SAVE"); + NativeEffect::PublishReplacement { + role: native_role(role), + } + } + _ => anyhow::bail!("UPDATE_OWNED_FENCE_EFFECT_NOT_ALLOWED"), + }; + let claim = self.ledger.claim_native(&native)?; + self.pending = Some((effect.clone(), claim)); + Ok(()) + } + fn observe(&mut self, effect: &Effect, observation: &str) -> Result<()> { + let Some((expected, claim)) = self.pending.take() else { + anyhow::bail!("UPDATE_EFFECT_NOT_CLAIMED") + }; + ensure!( + self.poisoned && expected == *effect, + "UPDATE_EFFECT_CALLBACK_CHANGED" + ); + let (role, replaced) = match *effect { + Effect::SavePredecessor { role } => (role, false), + Effect::PublishReplacement { role } => (role, true), + _ => anyhow::bail!("UPDATE_OWNED_FENCE_EFFECT_NOT_ALLOWED"), + }; + ensure!( + self.ledger + .native_observation_sha256(role.handoff_role(), replaced)? + == observation, + "UPDATE_NATIVE_OBSERVATION_CHANGED" + ); + self.ledger.observe_native(&claim, observation)?; + if replaced { + let observed_sha256 = self.ledger.target_sha256(role.handoff_role())?; + self.ledger.append_observed(Evidence::Replaced { + role: role.handoff_role(), + observed_sha256, + })?; + self.saved = None; + } else { + self.saved = Some(role); + } + self.poisoned = false; + Ok(()) + } +} +impl DurableEffectFence for LedgerFence<'_, '_, '_> { + fn before_effect(&mut self, effect: &Effect) -> Result<()> { + self.claim(effect) + } + fn after_effect(&mut self, effect: &Effect, observation_sha256: &str) -> Result<()> { + self.observe(effect, observation_sha256) + } +} diff --git a/crates/updater-worker/src/files.rs b/crates/updater-worker/src/files.rs new file mode 100644 index 0000000..11182d3 --- /dev/null +++ b/crates/updater-worker/src/files.rs @@ -0,0 +1,197 @@ +//! Exact fixed target/stage proofs, captured before atomic consumption and +//! independently reread under the existing lock before each native operation. +use anyhow::{Context, Result, ensure}; +use rmm_domain::jobs::hash; +use rmm_updater_handoff::{FileRole, Handoff}; +use rmm_updater_linux::{ + Budget, + files::{Directory, FileProof, Role, Staged}, +}; +use serde::Serialize; +use std::{ffi::OsStr, path::Path}; +use uuid::Uuid; + +const ROLES: [Role; 4] = [Role::Agent, Role::Helper, Role::FullConfig, Role::FullPin]; +fn label(role: Role) -> &'static str { + match role { + Role::Agent => "agent", + Role::Helper => "helper", + Role::FullConfig => "full-config", + Role::FullPin => "full-pin", + } +} +fn role(role: FileRole) -> Result { + match role { + FileRole::AgentBinary => Ok(Role::Agent), + FileRole::HelperBinary => Ok(Role::Helper), + FileRole::LinuxFullConfig => Ok(Role::FullConfig), + FileRole::LinuxFullPin => Ok(Role::FullPin), + _ => anyhow::bail!("UPDATE_LINUX_FILE_ROLE"), + } +} +#[derive(Serialize)] +struct Proof { + role: Role, + original: FileProof, + staged: FileProof, +} +pub struct FileWitnesses { + files: Vec, + nonce: Uuid, + sha256: String, +} +impl FileWitnesses { + /// Exactly Agent, Helper, Fullconfig, Fullpin, all fully staged. Reopening + /// each fixed stage name also rejects a mislabeled `Staged` object. + pub fn capture(stages: &[Staged; 4], nonce: Uuid, budget: &Budget) -> Result { + ensure!(!nonce.is_nil(), "UPDATE_STAGE_NONCE"); + let mut files = Vec::new(); + for (role, stage) in ROLES.iter().copied().zip(stages) { + budget.check()?; + let path = Path::new(role.target()); + let directory = + Directory::open(path.parent().context("UPDATE_TARGET_PARENT")?, 0, false)?; + let original = directory.inspect( + path.file_name().context("UPDATE_TARGET_NAME")?, + 0, + 256 * 1024 * 1024, + )?; + directory.file( + OsStr::new(&format!(".rmm-update-{nonce}-{}.stage", label(role))), + stage.proof(), + 256 * 1024 * 1024, + )?; + ensure!( + stage.proof().identity.links == 1 + && stage.proof().identity.uid == original.proof().identity.uid + && stage.proof().identity.gid == original.proof().identity.gid + && stage.proof().identity.mode == original.proof().identity.mode, + "UPDATE_STAGE_METADATA_CHANGED" + ); + files.push(Proof { + role, + original: original.proof().clone(), + staged: stage.proof().clone(), + }); + } + let digest = hash(&serde_json::to_vec(&files)?); + Ok(Self { + files, + nonce, + sha256: digest, + }) + } + pub fn sha256(&self) -> &str { + &self.sha256 + } + pub fn bind(&self, handoff: &Handoff) -> Result<()> { + ensure!( + handoff.files.len() == 4 + && handoff.owner_nonce == self.nonce + && handoff.staged_files_sha256 == self.sha256, + "UPDATE_FILESET_BINDING" + ); + for (file, plan) in self.files.iter().zip(&handoff.files) { + ensure!( + plan.role == file.role.handoff_role() + && plan.old_sha256 == file.original.sha256 + && plan.new_sha256 == file.staged.sha256, + "UPDATE_FILESET_PLAN_CHANGED" + ); + } + Ok(()) + } + pub fn verify_original_and_stage(&self, which: FileRole, budget: &Budget) -> Result<()> { + let file = self.file(which)?; + budget.check()?; + let path = Path::new(file.role.target()); + let dir = Directory::open(path.parent().context("UPDATE_TARGET_PARENT")?, 0, false)?; + dir.file( + path.file_name().context("UPDATE_TARGET_NAME")?, + &file.original, + 256 * 1024 * 1024, + )?; + dir.file( + OsStr::new(&format!( + ".rmm-update-{}-{}.stage", + self.nonce, + label(file.role) + )), + &file.staged, + 256 * 1024 * 1024, + )?; + Ok(()) + } + pub fn verify_replaced(&self, which: FileRole, budget: &Budget) -> Result<()> { + let file = self.file(which)?; + budget.check()?; + let path = Path::new(file.role.target()); + let dir = Directory::open(path.parent().context("UPDATE_TARGET_PARENT")?, 0, false)?; + dir.file( + path.file_name().context("UPDATE_TARGET_NAME")?, + &file.staged, + 256 * 1024 * 1024, + )?; + dir.file( + OsStr::new(&format!( + ".rmm-update-{}-{}.previous", + self.nonce, + label(file.role) + )), + &file.original, + 256 * 1024 * 1024, + )?; + Ok(()) + } + pub fn verify_saved(&self, which: FileRole, budget: &Budget) -> Result<()> { + let file = self.file(which)?; + budget.check()?; + let path = Path::new(file.role.target()); + let dir = Directory::open(path.parent().context("UPDATE_TARGET_PARENT")?, 0, false)?; + dir.file( + OsStr::new(&format!( + ".rmm-update-{}-{}.previous", + self.nonce, + label(file.role) + )), + &file.original, + 256 * 1024 * 1024, + )?; + dir.file( + OsStr::new(&format!( + ".rmm-update-{}-{}.stage", + self.nonce, + label(file.role) + )), + &file.staged, + 256 * 1024 * 1024, + )?; + ensure!( + std::fs::symlink_metadata(path) + .is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound), + "UPDATE_PUBLISH_TARGET_NOT_ABSENT" + ); + dir.verify() + } + pub fn native_observation_sha256(&self, which: FileRole, replaced: bool) -> Result { + let file = self.file(which)?; + Ok(hash(&serde_json::to_vec(if replaced { + &file.staged + } else { + &file.original + })?)) + } + pub fn verify_pair(&self, budget: &Budget) -> Result<()> { + for file in &self.files { + self.verify_replaced(file.role.handoff_role(), budget)?; + } + Ok(()) + } + fn file(&self, which: FileRole) -> Result<&Proof> { + let role = role(which)?; + self.files + .iter() + .find(|f| f.role == role) + .context("UPDATE_FILE_NOT_BOUND") + } +} diff --git a/crates/updater-worker/src/full.rs b/crates/updater-worker/src/full.rs new file mode 100644 index 0000000..28e6b85 --- /dev/null +++ b/crates/updater-worker/src/full.rs @@ -0,0 +1,185 @@ +//! Exact protected Full raw files and the independently provisioned public +//! signing-key record. This is a closed renderer, never a JSON patch/ACL change. +use anyhow::{Context, Result, ensure}; +use ed25519_dalek::VerifyingKey; +use rmm_domain::{ + agent_update::{PeerPinTransition, ResolvedAgentUpdate}, + jobs::hash, +}; +use rmm_updater_handoff::{LinuxFullTransition, render_linux_full}; +use rmm_updater_linux::{ + Budget, + files::{Directory, HeldFile, Role, StageDescriptor, Staged}, +}; +use serde::Deserialize; +use std::{ + ffi::OsStr, + path::{Path, PathBuf}, +}; +use uuid::Uuid; + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct SigningKeyRecord { + key_id: String, + algorithm: String, + schema_version: u32, + public_key_hex: String, +} +pub struct FullFiles { + directory: Directory, + config: HeldFile, + pin: HeldFile, + key_directory: Directory, + key_file: HeldFile, + key_path: PathBuf, + rendered: LinuxFullTransition, +} +impl FullFiles { + /// `job_key_path` and `job_key_raw_sha256` come from independently protected + /// LOCAL policy, not an update job, IPC request or manifest. The exact key + /// identity is additionally bound to the approved Full transition proof. + pub fn open( + update: &ResolvedAgentUpdate, + job_key_path: &Path, + job_key_raw_sha256: &str, + budget: &Budget, + ) -> Result { + budget.check()?; + ensure!( + update.validate() && job_key_path.is_absolute(), + "UPDATE_FULL_INPUT" + ); + let PeerPinTransition::LinuxGeneralFullV1 { full, .. } = &update.peer_pin_transition else { + anyhow::bail!("UPDATE_FULL_REQUIRED") + }; + let key_directory = Directory::open( + job_key_path.parent().context("UPDATE_FULL_KEY_PARENT")?, + 0, + false, + )?; + let mut key_file = key_directory.inspect( + job_key_path.file_name().context("UPDATE_FULL_KEY_NAME")?, + 0, + 4096, + )?; + ensure!( + key_file.proof().sha256 == job_key_raw_sha256, + "UPDATE_FULL_KEY_RAW_HASH" + ); + let key: SigningKeyRecord = serde_json::from_slice(&key_file.bytes(4096)?)?; + let raw = hex::decode(&key.public_key_hex)?; + ensure!( + key.schema_version == 1 + && key.algorithm == "Ed25519" + && key.key_id == hash(&raw) + && key.key_id == full.effective_signing_key_id, + "UPDATE_FULL_KEY_IDENTITY" + ); + let key = VerifyingKey::from_bytes( + &raw.try_into() + .map_err(|_| anyhow::anyhow!("UPDATE_FULL_KEY_SIZE"))?, + )?; + ensure!(!key.is_weak(), "UPDATE_FULL_WEAK_KEY"); + let directory = Directory::open(Path::new("/etc/rmm-remote"), 0, false)?; + let mut config = directory.inspect(OsStr::new("helper-full-maintenance.json"), 0, 16384)?; + let mut pin = + directory.inspect(OsStr::new("full-maintenance-helper-proof.json"), 0, 8192)?; + ensure!( + config.proof().sha256 == full.old_config_sha256 + && pin.proof().sha256 == full.old_pin_sha256, + "UPDATE_FULL_OLD_RAW_CHANGED" + ); + let config_bytes = config.bytes(16384)?; + // The renderer authenticates the effective public key but deliberately + // does not load it. Bind the actual raw Config's key path independently. + let value: serde_json::Value = serde_json::from_slice(&config_bytes)?; + if let Some(path) = value.get("signing_key_file").and_then(|v| v.as_str()) { + ensure!( + Path::new(path) == job_key_path, + "UPDATE_FULL_KEY_PATH_CHANGED" + ); + } else { + ensure!( + value["binding"]["public_key_hex"].as_str() == Some(&hex::encode(key.as_bytes())), + "UPDATE_FULL_INLINE_KEY_CHANGED" + ); + } + let rendered = render_linux_full( + &config_bytes, + &pin.bytes(8192)?, + &full.new_helper_sha256, + &key, + )?; + ensure!( + serde_json::to_vec(rendered.proof())? == serde_json::to_vec(full)?, + "UPDATE_FULL_RENDER_DIFFERS_FROM_APPROVED" + ); + budget.check()?; + Ok(Self { + directory, + config, + pin, + key_directory, + key_file, + key_path: job_key_path.to_owned(), + rendered, + }) + } + pub fn verify_original(&mut self, budget: &Budget) -> Result<()> { + budget.check()?; + self.directory.verify()?; + self.key_directory.verify()?; + self.config.verify(16384)?; + self.pin.verify(8192)?; + self.key_file.verify(4096)?; + self.directory.file( + OsStr::new("helper-full-maintenance.json"), + self.config.proof(), + 16384, + )?; + self.directory.file( + OsStr::new("full-maintenance-helper-proof.json"), + self.pin.proof(), + 8192, + )?; + self.key_directory.file( + self.key_path.file_name().context("UPDATE_FULL_KEY_NAME")?, + self.key_file.proof(), + 4096, + )?; + Ok(()) + } + /// Only after real WebUI approval and independent live original-grant / + /// download checks by the enclosing admission path. No activation here. + pub fn stage(&mut self, owner_nonce: Uuid, budget: &Budget) -> Result<[Staged; 2]> { + self.verify_original(budget)?; + let mut config = self.rendered.new_config_bytes(); + let mut pin = self.rendered.new_pin_bytes(); + let config = Staged::write( + &self.directory, + StageDescriptor { + role: Role::FullConfig, + nonce: owner_nonce, + original: self.config.proof(), + expected_sha: &self.rendered.proof().new_config_sha256, + length: config.len() as u64, + }, + &mut config, + budget, + )?; + let pin = Staged::write( + &self.directory, + StageDescriptor { + role: Role::FullPin, + nonce: owner_nonce, + original: self.pin.proof(), + expected_sha: &self.rendered.proof().new_pin_sha256, + length: pin.len() as u64, + }, + &mut pin, + budget, + )?; + Ok([config, pin]) + } +} diff --git a/crates/updater-worker/src/ledger.rs b/crates/updater-worker/src/ledger.rs new file mode 100644 index 0000000..2751869 --- /dev/null +++ b/crates/updater-worker/src/ledger.rs @@ -0,0 +1,335 @@ +//! The one existing SQLite file, opened without CREATE only after the real +//! OS guard confirms every reader stopped. This module performs no bootstrap, +//! consumption, schema reset, outcome healing or readiness transition. +use crate::{ + clock::NativeClock, files::FileWitnesses, original::Original, participants::StableParticipant, + retained::RetainedSet, trust::TrustState, +}; +use anyhow::{Result, ensure}; +use rmm_agent_core::{ + auth::Binding, + helper_reconcile::ExecutorLedgerGuard, + reconcile::SyncClock, + update_handoff::{ + self, NativeEffect, NativeEffectClaim, NativeEffectStage, NativeFileRole, Participant, + UpdateParticipantGuard, + }, +}; +use rmm_domain::agent_update::UpdateDelegation; +use rmm_domain::jobs::hash; +use rmm_updater_handoff::{Event, Evidence, Handoff, Journal, Phase}; +use rmm_updater_linux::services::StoppedServices; +use rmm_updater_linux::{Budget, files::LedgerGuard}; +use rusqlite::{Connection, OpenFlags}; +use std::time::Duration; + +const LEDGER: &str = "/var/lib/rmm-helper/consumption.sqlite"; + +pub struct OwnedGuard<'a, 'stopped> { + os: &'a LedgerGuard<'stopped>, + original: &'a Original, + binding: &'a Binding, + clock: &'a NativeClock, + budget: &'a Budget, + updater: &'a StableParticipant, + retained: &'a RetainedSet, + files: &'a FileWitnesses, + stopped: &'a StoppedServices, + trust: &'a TrustState, + sqlite_handle: usize, +} +pub struct OwnedInputs<'a, 'stopped> { + pub os: &'a LedgerGuard<'stopped>, + pub original: &'a Original, + pub binding: &'a Binding, + pub clock: &'a NativeClock, + pub budget: &'a Budget, + pub updater: &'a StableParticipant, + pub retained: &'a RetainedSet, + pub files: &'a FileWitnesses, + pub stopped: &'a StoppedServices, + pub trust: &'a TrustState, +} +pub struct OwnedLedger<'a, 'stopped> { + db: Connection, + guard: OwnedGuard<'a, 'stopped>, +} +impl<'a, 'stopped> OwnedLedger<'a, 'stopped> { + pub fn open(input: OwnedInputs<'a, 'stopped>) -> Result { + input.os.verify_for_effect(input.budget)?; + ensure!( + input.os.identity().sha256()? == input.original.handoff().ledger_identity_sha256 + && input.retained.sha256() == input.original.handoff().retained_state_sha256, + "UPDATE_OWNED_LEDGER_OR_STATE_BINDING" + ); + let db = Connection::open_with_flags( + LEDGER, + OpenFlags::SQLITE_OPEN_READ_WRITE | OpenFlags::SQLITE_OPEN_NO_MUTEX, + )?; + db.busy_timeout(Duration::ZERO)?; + // Per-connection durability/finite capacity, preserving DELETE journal + // mode, all existing schema/rows, and the already held file identities. + let mode: String = db.query_row("PRAGMA journal_mode", [], |r| r.get(0))?; + let sync: u32 = db.query_row("PRAGMA synchronous", [], |r| r.get(0))?; + ensure!( + mode == "delete" && sync >= 2, + "UPDATE_LEDGER_DURABILITY_REQUIRED" + ); + input.files.bind(input.original.handoff())?; + let guard = OwnedGuard { + os: input.os, + original: input.original, + binding: input.binding, + clock: input.clock, + budget: input.budget, + updater: input.updater, + retained: input.retained, + files: input.files, + stopped: input.stopped, + trust: input.trust, + sqlite_handle: unsafe { db.handle() } as usize, + }; + guard.check(&db)?; + // Replay the complete original retained chain and its durable head. + update_handoff::read(&db, &guard, input.original.permit().grant_id)?; + db.execute_batch("PRAGMA foreign_keys=ON")?; + rmm_agent_core::ledger::bounded_journal_capacity(&db)?; + Ok(Self { db, guard }) + } + pub fn journal(&self) -> Result { + update_handoff::read(&self.db, &self.guard, self.guard.original.permit().grant_id) + } + pub fn append_observed(&mut self, evidence: Evidence) -> Result<()> { + let journal = self.journal()?; + let event = journal.prepare( + u64::try_from(self.guard.clock.now()?.timestamp())?, + evidence, + )?; + update_handoff::append( + &mut self.db, + &self.guard, + self.guard.original.permit().grant_id, + journal.head_sha256(), + &event, + ) + } + pub fn claim_native(&mut self, effect: &NativeEffect) -> Result { + let journal = self.journal()?; + update_handoff::claim_native_effect( + &mut self.db, + &self.guard, + self.guard.original.permit().grant_id, + journal.head_sha256(), + effect, + self.guard.clock.now()?, + ) + } + pub fn observe_native(&mut self, claim: &NativeEffectClaim, observation: &str) -> Result<()> { + update_handoff::observe_native_effect( + &mut self.db, + &self.guard, + claim, + observation, + self.guard.clock.now()?, + ) + } + pub fn native_observation_sha256( + &self, + role: rmm_updater_handoff::FileRole, + replaced: bool, + ) -> Result { + self.guard.files.native_observation_sha256(role, replaced) + } + pub fn target_sha256(&self, role: rmm_updater_handoff::FileRole) -> Result { + self.guard + .original + .handoff() + .files + .iter() + .find(|f| f.role == role) + .map(|f| f.new_sha256.clone()) + .ok_or_else(|| anyhow::anyhow!("UPDATE_TARGET_ROLE")) + } + pub fn verify_pair(&self) -> Result<()> { + self.guard.files.verify_pair(self.guard.budget) + } + /// Close the actual SQLite connection BEFORE returning the OS flock. An + /// open/failed-close connection never produces a released-ledger witness. + pub fn close(self) -> Result<()> { + self.guard.check(&self.db)?; + self.db.close().map_err(|(_, e)| e)?; + self.guard.os.verify_for_effect(self.guard.budget) + } +} +impl ExecutorLedgerGuard for OwnedGuard<'_, '_> { + fn check(&self, db: &Connection) -> Result<()> { + self.os.verify_for_effect(self.budget)?; + ensure!( + unsafe { db.handle() } as usize == self.sqlite_handle, + "UPDATE_SQLITE_CONNECTION_CHANGED" + ); + let path: String = db.query_row( + "SELECT file FROM pragma_database_list WHERE name='main'", + [], + |r| r.get(0), + )?; + ensure!(path == LEDGER, "UPDATE_SQLITE_PATH_CHANGED"); + self.original + .check_current(self.binding, self.clock, self.budget)?; + self.trust.recheck(self.original, self.clock)?; + self.updater + .verify_delegation(self.original.delegation(), self.budget)?; + self.retained.verify()?; + let grant = self.original.permit().grant_id.to_string(); + let start: Vec = db.query_row( + "SELECT start FROM execution_evidence WHERE grant_id=?1", + [&grant], + |r| r.get(0), + )?; + ensure!( + start == self.original.start_bytes(), + "UPDATE_RETAINED_START_CHANGED" + ); + let unresolved: u64 = db.query_row( + "SELECT count(*) FROM consumed WHERE result IS NULL AND grant_id<>?1", + [grant], + |r| r.get(0), + )?; + ensure!(unresolved == 0, "UPDATE_OTHER_UNRESOLVED_ATTEMPT"); + self.os.verify_for_effect(self.budget) + } + fn check_update_owner( + &self, + handoff: &Handoff, + delegation: &UpdateDelegation, + phase: Phase, + _events: &[Event], + ) -> Result<()> { + ensure!( + !matches!( + phase, + Phase::HandoffConsumed + | Phase::ServicesStarted + | Phase::HealthVerified + | Phase::OutcomePersisted + | Phase::Unknown + ) && handoff.bytes()? == self.original.handoff().bytes()? + && delegation == self.original.delegation(), + "UPDATE_OWNED_WRITER_CONTEXT_CHANGED" + ); + self.os.verify_for_effect(self.budget)?; + self.updater.verify_delegation(delegation, self.budget) + } +} +impl UpdateParticipantGuard for OwnedGuard<'_, '_> { + fn participant(&self) -> Participant { + Participant::StableUpdater + } + fn verify_update_event( + &self, + handoff: &Handoff, + delegation: &UpdateDelegation, + event: &Event, + ) -> Result<()> { + ensure!( + handoff.bytes()? == self.original.handoff().bytes()? + && delegation == self.original.delegation(), + "UPDATE_EVENT_ORIGINAL_CHANGED" + ); + self.original + .check_current(self.binding, self.clock, self.budget)?; + self.updater.verify_delegation(delegation, self.budget)?; + self.os.verify_for_effect(self.budget)?; + self.retained.verify()?; + match &event.evidence { + Evidence::AllStopped { observation_sha256 } => { + self.stopped.verify_still_stopped(self.budget)?; + ensure!( + *observation_sha256 == hash(&serde_json::to_vec(&self.stopped.proofs())?), + "UPDATE_ALL_STOPPED_OBSERVATION" + ); + } + Evidence::UpdaterOwnsLedger { + process, + ledger_identity_sha256, + } => ensure!( + process.pid == delegation.updater.pid + && process.birth == delegation.updater.birth + && process.image_sha256 == delegation.updater.image_sha256 + && *ledger_identity_sha256 == self.os.identity().sha256()?, + "UPDATE_OWNER_EVENT_OBSERVATION" + ), + Evidence::ReplaceIntent { role } => { + self.files.verify_original_and_stage(*role, self.budget)? + } + Evidence::Replaced { + role, + observed_sha256, + } => { + self.files.verify_replaced(*role, self.budget)?; + ensure!( + handoff + .files + .iter() + .any(|f| f.role == *role && f.new_sha256 == *observed_sha256), + "UPDATE_REPLACED_OBSERVATION" + ); + } + Evidence::PairVerified { + pair, + retained_state_sha256, + } => { + self.files.verify_pair(self.budget)?; + ensure!( + *pair == handoff.target && retained_state_sha256 == self.retained.sha256(), + "UPDATE_PAIR_OBSERVATION" + ); + } + Evidence::LedgerReturnIntent => self.files.verify_pair(self.budget)?, + _ => anyhow::bail!("UPDATE_EVENT_WRITER_NOT_ALLOWED"), + } + Ok(()) + } + fn verify_native_effect( + &self, + handoff: &Handoff, + delegation: &UpdateDelegation, + effect: &NativeEffect, + stage: NativeEffectStage, + ) -> Result<()> { + ensure!( + handoff.bytes()? == self.original.handoff().bytes()? + && delegation == self.original.delegation(), + "UPDATE_NATIVE_ORIGINAL_CHANGED" + ); + self.original + .check_current(self.binding, self.clock, self.budget)?; + self.updater.verify_delegation(delegation, self.budget)?; + self.os.verify_for_effect(self.budget)?; + self.retained.verify()?; + let role = |role: &NativeFileRole| match role { + NativeFileRole::AgentBinary => rmm_updater_handoff::FileRole::AgentBinary, + NativeFileRole::HelperBinary => rmm_updater_handoff::FileRole::HelperBinary, + NativeFileRole::FullConfig => rmm_updater_handoff::FileRole::LinuxFullConfig, + NativeFileRole::FullPin => rmm_updater_handoff::FileRole::LinuxFullPin, + }; + match (effect, stage) { + (NativeEffect::SavePredecessor { role: r }, NativeEffectStage::Claim) => { + self.files.verify_original_and_stage(role(r), self.budget)? + } + (NativeEffect::SavePredecessor { role: r }, NativeEffectStage::Observe) + | (NativeEffect::PublishReplacement { role: r }, NativeEffectStage::Claim) => { + self.files.verify_saved(role(r), self.budget)? + } + (NativeEffect::PublishReplacement { role: r }, NativeEffectStage::Observe) => { + self.files.verify_replaced(role(r), self.budget)? + } + (NativeEffect::ReturnLedger, NativeEffectStage::Claim) + | (NativeEffect::StartService { .. }, NativeEffectStage::ReserveFutureStart) => { + self.files.verify_pair(self.budget)? + } + _ => anyhow::bail!("UPDATE_NATIVE_OWNED_EFFECT_DENIED"), + } + Ok(()) + } +} diff --git a/crates/updater-worker/src/lib.rs b/crates/updater-worker/src/lib.rs new file mode 100644 index 0000000..459c617 --- /dev/null +++ b/crates/updater-worker/src/lib.rs @@ -0,0 +1,12 @@ +//! Concrete, original-attempt-bound Linux worker. No approval or retry path. +#![cfg(target_os = "linux")] + +pub mod clock; +pub mod fence; +pub mod files; +pub mod full; +pub mod ledger; +pub mod original; +pub mod participants; +pub mod retained; +pub mod trust; diff --git a/crates/updater-worker/src/original.rs b/crates/updater-worker/src/original.rs new file mode 100644 index 0000000..029c8c2 --- /dev/null +++ b/crates/updater-worker/src/original.rs @@ -0,0 +1,191 @@ +//! Independently reverify the retained ORIGINAL request, never an IPC-supplied +//! approval bit, a replacement request or a renewed start window. +use anyhow::{Result, ensure}; +use rmm_agent_core::{ + auth::{Binding, Request}, + reconcile::SyncClock, +}; +use rmm_domain::{ + agent_update::{ParticipantRole, ResolvedAgentUpdate, UpdateDelegation}, + jobs::{Action, ExecutionPermitPayload, JobPayload, hash}, +}; +use rmm_updater_handoff::{Handoff, PinTransition, Service}; +use rmm_updater_linux::Budget; + +pub struct Original { + request: Request, + permit: ExecutionPermitPayload, + job: JobPayload, + update: ResolvedAgentUpdate, + handoff: Handoff, + delegation: UpdateDelegation, + start_bytes: Vec, +} +impl Original { + /// `start_bytes` must come from execution_evidence.start in the SAME + /// existing guarded ledger. This is validation only; callers must re-read + /// and compare that immutable row at each subsequent guarded operation. + pub fn verify( + binding: &Binding, + start_bytes: &[u8], + record: &[u8], + delegation: UpdateDelegation, + clock: &impl SyncClock, + budget: &Budget, + ) -> Result { + ensure!( + !start_bytes.is_empty() + && start_bytes.len() <= 512 * 1024 + && !record.is_empty() + && record.len() <= rmm_updater_handoff::MAX_RECORD_BYTES, + "UPDATE_ORIGINAL_LIMIT" + ); + budget.check()?; + let handoff: Handoff = serde_json::from_slice(record)?; + handoff.validate()?; + ensure!( + handoff.bytes()? == record + && delegation.validate() + && delegation.handoff_sha256 == hash(record) + && delegation.owner_nonce == handoff.owner_nonce + && delegation.boot_id == handoff.boot_id + && delegation.updater.role == ParticipantRole::LinuxUpdater + && delegation.updater.image_sha256 == handoff.updater_sha256 + && delegation.original_helper.image_sha256 == handoff.predecessor.helper_sha256 + && u64::try_from(delegation.prepared_at.timestamp())? == handoff.consumed_at, + "UPDATE_ORIGINAL_DELEGATION" + ); + let start: serde_json::Value = serde_json::from_slice(start_bytes)?; + let request: Request = serde_json::from_value(start["request"].clone())?; + ensure!( + hash(start_bytes) == handoff.attempt.original_start_witness_sha256 + && hash(&serde_json::to_vec(&request)?) == handoff.attempt.original_request_sha256, + "UPDATE_ORIGINAL_START_CHANGED" + ); + // Original consumption happened at the immutable prepared_at. It must + // have had a valid live start grant THEN. Current checks below constrain + // this one already consumed attempt; they grant no new start window. + let (job, permit) = binding.verify(&request, delegation.prepared_at)?; + ensure!( + rmm_agent_core::ledger::start_witness_bytes( + &permit, + &request, + handoff.boot_id, + delegation.prepared_at + )? == start_bytes + && std::fs::read_to_string("/proc/sys/kernel/random/boot_id")? + .trim() + .parse::()? + == handoff.boot_id, + "UPDATE_ORIGINAL_START_OR_BOOT_CHANGED" + ); + ensure!( + job.execution_identity == "root" + && permit.action == "update_agent" + && Some(handoff.attempt.plan_id) == permit.agent_update_plan_id + && handoff.attempt.tenant_id == permit.tenant_id + && handoff.attempt.asset_id == permit.asset_id + && handoff.attempt.agent_id == permit.agent_id + && handoff.attempt.enrollment_generation == permit.enrollment_generation + && handoff.attempt.assignment_version == permit.assignment_version + && handoff.attempt.job_id == permit.job_id + && handoff.attempt.attempt_id == permit.attempt_id + && handoff.attempt.grant_id == permit.grant_id + && handoff.attempt.authorization_id == permit.authorization_id + && handoff.attempt.plan_sha256 == permit.plan_hash + && handoff.attempt.job_payload_sha256 == permit.job_payload_hash, + "UPDATE_ORIGINAL_JOB_BINDING" + ); + let Action::UpdateAgent { update } = &job.action else { + anyhow::bail!("UPDATE_ACTION_REQUIRED") + }; + ensure!( + rmm_domain::agent_update::handoff_matches_job(&handoff, &job) + && update.validate() + && update.manifest_sha256 == handoff.target.manifest_sha256 + && update.predecessor.manifest_sha256 == handoff.predecessor.manifest_sha256 + && update.predecessor.agent_sha256 == handoff.predecessor.agent_sha256 + && update.predecessor.helper_sha256 == handoff.predecessor.helper_sha256 + && update.predecessor.installed_record_sha256 == handoff.predecessor_record_sha256 + && update.updater.binary_sha256 == handoff.updater_sha256 + && update.updater.policy_sha256 == handoff.updater_policy_sha256 + && matches!(handoff.pin_transition, PinTransition::LinuxGeneralFullV1) + && (handoff.stop_set + == [ + Service::LinuxAgent, + Service::LinuxGeneralHelper, + Service::LinuxFullHelper + ] + || handoff.stop_set + == [ + Service::LinuxAgent, + Service::LinuxGeneralHelper, + Service::LinuxFullHelper, + Service::LinuxAptHelper + ]), + "UPDATE_ORIGINAL_CODE_POLICY_BINDING" + ); + let update = update.as_ref().clone(); + let decoded = update + .release_envelope + .decode() + .map_err(anyhow::Error::msg)?; + ensure!( + decoded.manifest.artifacts[0].sha256 == handoff.target.agent_sha256 + && decoded.manifest.artifacts[1].sha256 == handoff.target.helper_sha256, + "UPDATE_ORIGINAL_TARGET_PAIR" + ); + let result = Self { + request, + permit, + job, + update, + handoff, + delegation, + start_bytes: start_bytes.to_vec(), + }; + result.check_current(binding, clock, budget)?; + Ok(result) + } + pub fn check_current( + &self, + binding: &Binding, + clock: &impl SyncClock, + budget: &Budget, + ) -> Result<()> { + budget.check()?; + let now = clock.now()?; + ensure!( + now >= self.delegation.prepared_at + && u64::try_from(now.timestamp())? < self.handoff.finish_before + && now + < self.job.start_before + + chrono::Duration::seconds(i64::from(self.job.max_runtime_seconds)) + && self.handoff.finish_before + <= self.handoff.consumed_at + u64::from(self.job.max_runtime_seconds), + "UPDATE_ORIGINAL_EXPIRED" + ); + let (job, permit) = binding.verify(&self.request, self.delegation.prepared_at)?; + ensure!( + serde_json::to_vec(&job)? == serde_json::to_vec(&self.job)? + && serde_json::to_vec(&permit)? == serde_json::to_vec(&self.permit)?, + "UPDATE_ORIGINAL_CHANGED" + ); + Ok(()) + } + pub fn handoff(&self) -> &Handoff { + &self.handoff + } + pub fn delegation(&self) -> &UpdateDelegation { + &self.delegation + } + pub fn update(&self) -> &ResolvedAgentUpdate { + &self.update + } + pub fn permit(&self) -> &ExecutionPermitPayload { + &self.permit + } + pub fn start_bytes(&self) -> &[u8] { + &self.start_bytes + } +} diff --git a/crates/updater-worker/src/participants.rs b/crates/updater-worker/src/participants.rs new file mode 100644 index 0000000..438aff5 --- /dev/null +++ b/crates/updater-worker/src/participants.rs @@ -0,0 +1,78 @@ +//! Concrete native service/process binding. A denied /proc read is a denial; +//! UID0, process names and installed file hashes are never image fallbacks. +use anyhow::{Result, ensure}; +use rmm_domain::{ + agent_update::{ParticipantIdentity, ParticipantRole, UpdateDelegation}, + jobs::hash, +}; +use rmm_updater_linux::{ + Budget, + services::{HeldService, Service, ServicePolicy, Systemd}, +}; + +pub struct StableParticipant { + held: HeldService, + identity: ParticipantIdentity, +} +impl StableParticipant { + pub fn observe(policy: ServicePolicy, budget: &Budget) -> Result { + let held = Systemd::observe_updater(policy, budget)?; + let proof = held.proof(); + ensure!( + proof.process.pid == std::process::id() + && proof.process.uid == 0 + && proof.process.gid == 0, + "UPDATE_WORKER_MUST_BE_EXACT_STABLE_SERVICE" + ); + let identity = ParticipantIdentity { + role: ParticipantRole::LinuxUpdater, + pid: proof.process.pid, + birth: proof.process.birth, + image_sha256: proof.process.image_sha256.clone(), + security_principal: "uid:0".into(), + service_instance_sha256: hash(&serde_json::to_vec(proof)?), + }; + ensure!(identity.validate(), "UPDATE_WORKER_IDENTITY"); + Ok(Self { held, identity }) + } + pub fn verify_delegation(&self, delegation: &UpdateDelegation, budget: &Budget) -> Result<()> { + self.held.verify(budget)?; + ensure!( + delegation.validate() && delegation.updater == self.identity, + "UPDATE_WORKER_DELEGATION_CHANGED" + ); + Ok(()) + } + pub fn identity(&self) -> &ParticipantIdentity { + &self.identity + } +} + +/// Before stopping the independently checking original helper, compare its +/// actual concrete process instance with the immutable atomic delegation. +pub fn verify_original_helper( + services: &Systemd, + delegation: &UpdateDelegation, + budget: &Budget, +) -> Result { + ensure!(delegation.validate(), "UPDATE_ORIGINAL_DELEGATION"); + let service = match delegation.original_helper.role { + ParticipantRole::LinuxGeneralHelper => Service::General, + ParticipantRole::LinuxFullHelper => Service::Full, + _ => anyhow::bail!("UPDATE_ORIGINAL_LINUX_HELPER_REQUIRED"), + }; + let held = services.observe(service, budget)?; + let proof = held.proof(); + let expected = &delegation.original_helper; + ensure!( + proof.process.pid == expected.pid + && proof.process.birth == expected.birth + && proof.process.image_sha256 == expected.image_sha256 + && proof.process.uid == 0 + && expected.security_principal == "uid:0" + && hash(&serde_json::to_vec(proof)?) == expected.service_instance_sha256, + "UPDATE_ORIGINAL_HELPER_INSTANCE_CHANGED" + ); + held.verify(budget)?; + Ok(held) +} diff --git a/crates/updater-worker/src/retained.rs b/crates/updater-worker/src/retained.rs new file mode 100644 index 0000000..97dc8e8 --- /dev/null +++ b/crates/updater-worker/src/retained.rs @@ -0,0 +1,163 @@ +//! Held state identities without reading/exporting private key contents. +//! Paths must come from independently provisioned LOCAL policy, never IPC/jobs. +use anyhow::{Context, Result, ensure}; +use rmm_domain::jobs::hash; +use rmm_updater_linux::files::{Directory, Identity}; +use serde::{Deserialize, Serialize}; +use std::{ + fs::File, + os::unix::fs::{MetadataExt, OpenOptionsExt}, + path::{Path, PathBuf}, +}; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Retention { + /// Journal content is expected to advance, but the actual file stays held. + MutableDatabase, + /// Keys/configs remain byte-unread: additionally bind size/mtime/ctime. + ImmutableMetadata, +} +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct RetainedFileSpec { + pub path: PathBuf, + pub parent_uid: u32, + pub identity: Identity, + pub retention: Retention, +} +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +struct Stamp { + size: u64, + mtime: i64, + mtime_nsec: i64, + ctime: i64, + ctime_nsec: i64, +} +impl Stamp { + fn of(meta: &std::fs::Metadata) -> Self { + Self { + size: meta.len(), + mtime: meta.mtime(), + mtime_nsec: meta.mtime_nsec(), + ctime: meta.ctime(), + ctime_nsec: meta.ctime_nsec(), + } + } +} +struct HeldState { + spec: RetainedFileSpec, + directory: Directory, + file: File, + stamp: Stamp, +} +pub struct RetainedSet { + files: Vec, + digest: String, +} +impl RetainedSet { + pub fn capture(specs: Vec) -> Result { + ensure!( + !specs.is_empty() && specs.len() <= 64, + "UPDATE_RETAINED_FILESET_LIMIT" + ); + let mut files = Vec::new(); + for spec in specs { + ensure!( + spec.path.is_absolute() + && spec.path.components().all(|c| matches!( + c, + std::path::Component::RootDir | std::path::Component::Normal(_) + )) + && !files.iter().any(|v: &HeldState| v.spec.path == spec.path), + "UPDATE_RETAINED_PATH" + ); + // No state-reset/namespace substitution and no effect code files in + // this preservation set. Historical bound hardlinks are allowed. + ensure!( + ![ + rmm_updater_linux::files::Role::Agent, + rmm_updater_linux::files::Role::Helper, + rmm_updater_linux::files::Role::FullConfig, + rmm_updater_linux::files::Role::FullPin + ] + .iter() + .any(|role| Path::new(role.target()) == spec.path), + "UPDATE_RETAINED_CODE_PATH" + ); + let parent = spec.path.parent().context("UPDATE_RETAINED_PARENT")?; + let directory = Directory::open(parent, spec.parent_uid, false)?; + let file = std::fs::OpenOptions::new() + .read(true) + .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC) + .open(&spec.path)?; + let stamp = Stamp::of(&file.metadata()?); + let held = HeldState { + spec, + directory, + file, + stamp, + }; + held.verify()?; + files.push(held); + } + let serial: Vec<_> = files + .iter() + .map(|f| { + ( + &f.spec, + if f.spec.retention == Retention::ImmutableMetadata { + Some(&f.stamp) + } else { + None + }, + ) + }) + .collect(); + let digest = hash(&serde_json::to_vec(&serial)?); + Ok(Self { files, digest }) + } + pub fn sha256(&self) -> &str { + &self.digest + } + pub fn verify(&self) -> Result<()> { + for file in &self.files { + file.verify()?; + } + Ok(()) + } +} +fn identity(meta: &std::fs::Metadata) -> Identity { + Identity { + device: meta.dev(), + inode: meta.ino(), + uid: meta.uid(), + gid: meta.gid(), + mode: meta.mode(), + links: meta.nlink(), + } +} +impl HeldState { + fn verify(&self) -> Result<()> { + self.directory.verify()?; + let held = self.file.metadata()?; + let named = std::fs::symlink_metadata(&self.spec.path)?; + ensure!( + held.is_file() + && named.is_file() + && !named.file_type().is_symlink() + && identity(&held) == self.spec.identity + && identity(&named) == self.spec.identity + && held.mode() & 0o022 == 0 + && held.nlink() > 0, + "UPDATE_RETAINED_IDENTITY_CHANGED" + ); + if self.spec.retention == Retention::ImmutableMetadata { + ensure!( + Stamp::of(&held) == self.stamp && Stamp::of(&named) == self.stamp, + "UPDATE_RETAINED_METADATA_CHANGED" + ); + } + self.directory.verify() + } +} diff --git a/crates/updater-worker/src/trust.rs b/crates/updater-worker/src/trust.rs new file mode 100644 index 0000000..c3c58f9 --- /dev/null +++ b/crates/updater-worker/src/trust.rs @@ -0,0 +1,428 @@ +//! Actual protected local policy/keyring/health/baseline verification. No key +//! returned in a job/manifest is promoted to trust and no floor is guessed. +use crate::{clock::NativeClock, original::Original}; +use anyhow::{Context, Result, ensure}; +use ed25519_dalek::{Signature, VerifyingKey}; +use rmm_agent_core::{auth::Binding, reconcile::SyncClock}; +use rmm_domain::{ + agent_update::{Platform, UpdateKeyringFile}, + agent_update_provisioning::{ + ActivationEvidence, BASELINE_SIGNATURE_DOMAIN, HealthKeyPin, InstalledReleaseRecord, + LocalUpdatePolicy, + }, + jobs::hash, +}; +use rmm_updater::{ + ActiveRelease, Platform as ReleasePlatform, SignedRelease, TrustedContext, TrustedUpdateKey, + UpdateKeyring, verify_release, +}; +use rmm_updater_linux::files::{Directory, HeldFile}; +use std::{ffi::OsStr, path::Path}; + +struct Protected { + dir: Directory, + file: HeldFile, + name: String, + max: u64, +} +impl Protected { + fn read(path: &Path, max: u64) -> Result<(Self, Vec)> { + let dir = Directory::open(path.parent().context("UPDATE_TRUST_PARENT")?, 0, false)?; + let name = path + .file_name() + .context("UPDATE_TRUST_NAME")? + .to_str() + .context("UPDATE_TRUST_NAME")? + .to_owned(); + let mut file = dir.inspect(OsStr::new(&name), 0, max)?; + let raw = file.bytes(max)?; + Ok(( + Self { + dir, + file, + name, + max, + }, + raw, + )) + } + fn verify(&self) -> Result<()> { + self.dir + .file(OsStr::new(&self.name), self.file.proof(), self.max)?; + Ok(()) + } +} +pub struct TrustState { + protected: Vec, + policy: LocalUpdatePolicy, + installed: InstalledReleaseRecord, + keyring: UpdateKeyring, + health_public_key: [u8; 32], +} +impl TrustState { + pub fn load(original: &Original, binding: &Binding, clock: &NativeClock) -> Result { + let update = original.update(); + let mut protected = Vec::new(); + let (file, raw) = Protected::read(Path::new("/etc/rmm-agent-updater/policy.json"), 65536)?; + let (policy, policy_hash) = + LocalUpdatePolicy::from_bytes(&raw).map_err(anyhow::Error::msg)?; + ensure!( + policy_hash == update.updater.policy_sha256 + && policy.tenant_id == binding.tenant_id + && policy.asset_id == binding.asset_id + && policy.agent_id == binding.agent_id + && policy.enrollment_generation == binding.enrollment_generation + && policy.assignment_version == binding.assignment_version + && policy.updater_binary_sha256 == update.updater.binary_sha256, + "UPDATE_PROTECTED_POLICY_CHANGED" + ); + protected.push(file); + let (file, raw) = Protected::read(Path::new(&policy.keyring_path), 16384)?; + let keys: UpdateKeyringFile = serde_json::from_slice(&raw)?; + ensure!( + keys.validate() + && keys.generation == update.updater.keyring_generation + && hash(&raw) == update.updater.keyring_sha256, + "UPDATE_PROTECTED_KEYRING_CHANGED" + ); + protected.push(file); + let job_key = hex::decode(&binding.public_key_hex)?; + let mut trusted = Vec::new(); + let mut baseline_key = None; + for entry in &keys.keys { + ensure!(entry.platform == Platform::LinuxX64, "UPDATE_KEY_PLATFORM"); + let public: [u8; 32] = hex::decode(&entry.public_key_hex)? + .try_into() + .map_err(|_| anyhow::anyhow!("UPDATE_KEY_SIZE"))?; + ensure!( + public.as_slice() != job_key, + "UPDATE_JOB_RELEASE_KEYS_NOT_SEPARATE" + ); + if hash(&public) == policy.initial_baseline.key_id { + baseline_key = Some((entry, public)); + } + trusted.push(TrustedUpdateKey::new( + public, + ReleasePlatform::LinuxX64, + entry.first_sequence, + entry.last_sequence, + entry.revoked, + )?); + } + let keyring = UpdateKeyring::new(keys.generation, trusted)?; + let baseline = policy + .initial_baseline + .decode() + .map_err(anyhow::Error::msg)?; + let (baseline_entry, public) = baseline_key.context("UPDATE_BASELINE_KEY_NOT_TRUSTED")?; + ensure!( + !baseline_entry.revoked + && baseline + .record + .release_envelope + .decode() + .map_err(anyhow::Error::msg)? + .manifest + .release_sequence + >= baseline_entry.first_sequence + && baseline + .record + .release_envelope + .decode() + .map_err(anyhow::Error::msg)? + .manifest + .release_sequence + <= baseline_entry.last_sequence, + "UPDATE_BASELINE_KEY_REVOKED_OR_RANGE" + ); + let public = VerifyingKey::from_bytes(&public)?; + ensure!(!public.is_weak(), "UPDATE_BASELINE_WEAK_KEY"); + let mut message = BASELINE_SIGNATURE_DOMAIN.to_vec(); + message.extend_from_slice(&baseline.payload_bytes); + public.verify_strict(&message, &Signature::from_bytes(&baseline.signature))?; + let (file, raw) = Protected::read(Path::new(&policy.health_pin_path), 4096)?; + let health: HealthKeyPin = serde_json::from_slice(&raw)?; + let health_public_key = health.public_key().map_err(anyhow::Error::msg)?; + ensure!( + !VerifyingKey::from_bytes(&health_public_key)?.is_weak() + && hash(&raw) == update.updater.health_key_pin_sha256 + && hex::encode(health_public_key) == update.updater.health_public_key_hex + && health_public_key.as_slice() != job_key + && keys + .keys + .iter() + .all(|key| key.public_key_hex != hex::encode(health_public_key)), + "UPDATE_HEALTH_KEY_NOT_SEPARATE_OR_CHANGED" + ); + protected.push(file); + let (file, raw) = Protected::read(Path::new(&policy.installed_record_path), 32768)?; + ensure!( + hash(&raw) == update.predecessor.installed_record_sha256, + "UPDATE_INSTALLED_RECORD_CHANGED" + ); + let installed = InstalledReleaseRecord::from_bytes(&raw).map_err(anyhow::Error::msg)?; + // This first concrete activation is bootstrap-bound. A future Updated + // predecessor must have its complete guarded Health/record chain proved; + // never accept its mutable fields merely because parsing succeeded. + ensure!( + matches!( + installed.activation_evidence, + ActivationEvidence::Bootstrap { .. } + ) && raw == baseline.payload_bytes + && hash(&raw) == policy.initial_record_sha256 + && installed.activation_floor == policy.initial_activation_floor, + "UPDATE_INSTALLED_CHAIN_NOT_QUALIFIED" + ); + let active = installed + .release_envelope + .decode() + .map_err(anyhow::Error::msg)?; + ensure!( + active.manifest.release_id == update.predecessor.release_id + && active.manifest.release_sequence == update.predecessor.release_sequence + && installed.manifest_sha256 == update.predecessor.manifest_sha256 + && active.manifest.artifacts[0].sha256 == update.predecessor.agent_sha256 + && active.manifest.artifacts[1].sha256 == update.predecessor.helper_sha256, + "UPDATE_INSTALLED_PREDECESSOR_BINDING" + ); + verify_installed_release(&keyring, &installed, keys.generation)?; + verify( + &keyring, + &update.release_envelope, + &TrustedContext { + platform: ReleasePlatform::LinuxX64, + now_utc_seconds: u64::try_from(clock.now()?.timestamp())?, + keyring_generation: keys.generation, + protocol_major: active.manifest.protocol_major, + state_schema: active.manifest.state_schema, + updater_version: 1, + minimum_release_sequence: installed.activation_floor, + active_release: Some(ActiveRelease { + sequence: active.manifest.release_sequence, + manifest_sha256: installed.manifest_sha256.clone(), + }), + }, + )?; + protected.push(file); + Ok(Self { + protected, + policy, + installed, + keyring, + health_public_key, + }) + } + pub fn recheck(&self, original: &Original, clock: &NativeClock) -> Result<()> { + for file in &self.protected { + file.verify()?; + } + let active = self + .installed + .release_envelope + .decode() + .map_err(anyhow::Error::msg)?; + verify( + &self.keyring, + &original.update().release_envelope, + &TrustedContext { + platform: ReleasePlatform::LinuxX64, + now_utc_seconds: u64::try_from(clock.now()?.timestamp())?, + keyring_generation: original.update().updater.keyring_generation, + protocol_major: active.manifest.protocol_major, + state_schema: active.manifest.state_schema, + updater_version: 1, + minimum_release_sequence: self.installed.activation_floor, + active_release: Some(ActiveRelease { + sequence: active.manifest.release_sequence, + manifest_sha256: self.installed.manifest_sha256.clone(), + }), + }, + ) + } + pub fn policy(&self) -> &LocalUpdatePolicy { + &self.policy + } + pub fn health_public_key(&self) -> [u8; 32] { + self.health_public_key + } +} +fn verify( + keyring: &UpdateKeyring, + envelope: &rmm_domain::agent_update::ReleaseEnvelope, + context: &TrustedContext, +) -> Result<()> { + let decoded = envelope.decode().map_err(anyhow::Error::msg)?; + verify_release( + SignedRelease { + schema_version: envelope.schema_version, + key_id: &envelope.key_id, + payload_bytes: &decoded.payload_bytes, + signature: &decoded.signature, + }, + keyring, + context, + )?; + Ok(()) +} + +fn verify_installed_release( + keyring: &UpdateKeyring, + installed: &InstalledReleaseRecord, + generation: u64, +) -> Result<()> { + let active = installed + .release_envelope + .decode() + .map_err(anyhow::Error::msg)?; + verify( + keyring, + &installed.release_envelope, + &TrustedContext { + platform: ReleasePlatform::LinuxX64, + now_utc_seconds: installed.activated_at, + keyring_generation: generation, + protocol_major: active.manifest.protocol_major, + state_schema: active.manifest.state_schema, + updater_version: 1, + minimum_release_sequence: installed.activation_floor, + active_release: Some(ActiveRelease { + sequence: active.manifest.release_sequence, + manifest_sha256: installed.manifest_sha256.clone(), + }), + }, + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; + use ed25519_dalek::{Signer, SigningKey}; + use rmm_domain::agent_update::{ + ArtifactDescriptor, ArtifactRole, ReleaseEnvelope, ReleaseManifest, + }; + use rmm_domain::agent_update_provisioning::SignedBaselineRecord; + use uuid::Uuid; + + fn release(sequence: u64, published: u64, expires: u64) -> ReleaseEnvelope { + let signer = SigningKey::from_bytes(&[83; 32]); // public TEST fixture only + let manifest = ReleaseManifest { + schema_version: 1, + release_id: Uuid::from_u128(u128::from(sequence)), + release_sequence: sequence, + version: format!("test-{sequence}"), + platform: Platform::LinuxX64, + published_at: published, + expires_at: expires, + protocol_major: 1, + state_schema: 1, + minimum_updater_version: 1, + artifacts: [ + ArtifactDescriptor { + role: ArtifactRole::Agent, + artifact_id: Uuid::from_u128(101), + sha256: hash(b"test agent"), + bytes: 10, + }, + ArtifactDescriptor { + role: ArtifactRole::Helper, + artifact_id: Uuid::from_u128(102), + sha256: hash(b"test helper"), + bytes: 11, + }, + ], + }; + let raw = serde_json::to_vec(&manifest).unwrap(); + let mut signed = rmm_updater::RELEASE_SIGNATURE_DOMAIN.to_vec(); + signed.extend_from_slice(&raw); + ReleaseEnvelope { + schema_version: 1, + key_id: hash(signer.verifying_key().as_bytes()), + payload_bytes: URL_SAFE_NO_PAD.encode(raw), + signature: URL_SAFE_NO_PAD.encode(signer.sign(&signed).to_bytes()), + } + } + #[test] + fn separately_signed_baseline_at_floor_is_historical_only_and_candidate_stays_strict() { + let signer = SigningKey::from_bytes(&[83; 32]); + let keyring = UpdateKeyring::new( + 7, + vec![ + TrustedUpdateKey::new( + signer.verifying_key().to_bytes(), + ReleasePlatform::LinuxX64, + 1, + 20, + false, + ) + .unwrap(), + ], + ) + .unwrap(); + let envelope = release(7, 90, 110); + let record = InstalledReleaseRecord { + schema_version: 1, + profile: "decoder_compatible_handoff_v1".into(), + platform: Platform::LinuxX64, + manifest_sha256: hash(&envelope.decode().unwrap().payload_bytes), + release_envelope: envelope, + activation_floor: 7, + activated_at: 95, + previous_record_sha256: None, + activation_evidence: ActivationEvidence::Bootstrap { + qualification_receipt_sha256: hash(b"local synthetic qualification receipt"), + }, + rolled_back: false, + }; + let raw = record.bytes().unwrap(); + let mut message = BASELINE_SIGNATURE_DOMAIN.to_vec(); + message.extend_from_slice(&raw); + let baseline = SignedBaselineRecord { + schema_version: 1, + key_id: hash(signer.verifying_key().as_bytes()), + payload_bytes: URL_SAFE_NO_PAD.encode(&raw), + signature: URL_SAFE_NO_PAD.encode(signer.sign(&message).to_bytes()), + }; + let decoded = baseline.decode().unwrap(); + signer + .verifying_key() + .verify_strict(&message, &Signature::from_bytes(&decoded.signature)) + .unwrap(); + assert_eq!(decoded.payload_bytes, raw); + // Exercise the ACTUAL production context builder, where None at the + // confirmed floor previously rejected every legitimate initial record. + verify_installed_release(&keyring, &decoded.record, 7).unwrap(); + let candidate_context = TrustedContext { + platform: ReleasePlatform::LinuxX64, + now_utc_seconds: 200, + keyring_generation: 7, + protocol_major: 1, + state_schema: 1, + updater_version: 1, + minimum_release_sequence: 7, + active_release: Some(ActiveRelease { + sequence: 7, + manifest_sha256: record.manifest_sha256.clone(), + }), + }; + verify(&keyring, &release(8, 190, 210), &candidate_context).unwrap(); + assert!(verify(&keyring, &release(7, 190, 210), &candidate_context).is_err()); + assert!(verify(&keyring, &record.release_envelope, &candidate_context).is_err()); + assert!(verify(&keyring, &release(6, 190, 210), &candidate_context).is_err()); + let revoked = UpdateKeyring::new( + 7, + vec![ + TrustedUpdateKey::new( + signer.verifying_key().to_bytes(), + ReleasePlatform::LinuxX64, + 1, + 20, + true, + ) + .unwrap(), + ], + ) + .unwrap(); + assert!(verify_installed_release(&revoked, &record, 7).is_err()); + } +} diff --git a/docs/agent-updater-handoff-linux-results.md b/docs/agent-updater-handoff-linux-results.md new file mode 100644 index 0000000..5647130 --- /dev/null +++ b/docs/agent-updater-handoff-linux-results.md @@ -0,0 +1,59 @@ +# Updater-Handoffkernel: tatsächlicher Cloud-Linux-Nachweis + +2026-11-14. Ausschließlich der isolierte Kernel aus Commit +`a2efb79` wurde geprüft. Kein Installer, kein Agent-Selbstaustausch und keine +RMM-Jobgenehmigung sind Teil dieses Schritts. + +Der unabhängig geprüfte Runner `deploy/updater_handoff_linux_acceptance.py`, +SHA256 `502ba0d6f5a653dae21ddc871f069e61cbe4217d67e28708d1c0cad8347826f1`, +prüft die acht originalen Gitblobs gegen den lokalen Qualifikationsbeleg +`e924471166e68629d27d6adae51ebac05a77f04426cdd427e844a9dfb4920f70`. +Die native Unitexe hat2261368Byte und SHA256 +`0c80a2107fff96d9e30aa02b1cb56071a0f7e2be2acb1bec6794324205af9c7a`. +Später parallel bearbeitete Runtimequellen wurden nicht erneut gebaut oder als +bereits nativ qualifiziert behandelt. + +## Tatsächlich ausgeführt + +Fall `03ddcaa5-84a7-4722-bfd3-55702c7bb67b`: feste Linux-x86-64-Unitexe einmal +auf die Cloud-Linux-VM übertragen, vollständige Testliste ohne Filter geprüft, +danach genau ein Lauf als UID/GID65534 mit geleerten Zusatzgruppen und +`no-new-privs`. Kein RMM-Agent läuft auf dem Notebook. Der Prozess verwendete +keine RMM-IPC-, Approval-, Dienststeuerungs- oder Applyroute. + +**8 bestanden,0 fehlgeschlagen,0 ignoriert,0 gefiltert.** Erfasst sind: + +- geschlossene General/Full/Agent-Dienstmenge und Verweigerung eines APT-Restarts; +- kanonische Eventkette, feste Zeit-/Mengengrenzen und vollständiger16-Eventpfad; +- Erhaltung der Full-Rawbytes einschließlich des tatsächlich provisionierten + öffentlichen Filekeys ohne Einsetzen in das leere Inlinefeld; +- Verweigerung fremder Pins sowie unbekannter, doppelter oder escaped Felder; +- getrennte frische Healthsignatur, unverändertes `ready:false` und terminales Unknown; +- Besitz erst nach Stop, vollständiges Dateipaar und Rückgabe vor Restart. + +Vorher/nachher gleich: drei tatsächliche Agent-/General-/Full-Prozessgenerationen +mit PID, Prozessgeburt, Image und Konten; vier bekannte Config-/Pin-/Unitdateien +mit Rohhash und Metadaten; drei DB- und die vorhandene Executorlock-Dateiidentität; +Boot und weiterhin deaktivierter/inaktiver APT-Dienst. Ein separater rein +lesender Same-case-Aufruf bestätigte danach den gespeicherten Erfolg und +diesen aktuellen Zustand. Die Zielwirkung beschränkte sich auf den eigenen +Unitfall unter `/var/tmp/rmm-updater-handoff-` und den Testprozess. + +## Grenzen und nächste Arbeit + +Prozessgeburt/PID wurden beobachtet, kein durchgehender nativer Prozesshandle +gehalten. Die Erhaltung prüft bekannte Kontrollbytes und Dateiidentitäten, +keine vollständige SQL-/PKI-Historie. Lokale Belege flushen ihre Datei; +der bestehende lokale Transporthelper fsynct nicht zusätzlich das Elternverzeichnis. +Der exklusive Remote-Fall und Einmalmarker sperren normale Wiederholung. +Bei verlorenem Reply gilt ausschließlich Same-case-Readback, kein neuer Run. + +Dies ist ein nativer **Vertragskernnachweis**, kein Apply-, dauerhafter +SQLite-/Inflight-, IPC-, Dienststop-/Dateitausch-/Health-/Rollbacknachweis und +kein Windowsnachweis. Die tatsächliche Updateaction mit Katalog, Streaming, +MCP, fester WebUI-Genehmigung und unabhängiger Runtime wird parallel integriert. +Der bestehende Releaseverifier und seine ursprünglichen Native-Runner wurden +nicht verändert. Private Intents, Transportrückgaben und Originalausgaben +liegen gitignoriert unter `devstate/updater-handoff-native/03ddcaa5…/`. +Endbeleg-SHA256 `3a390ab47f63f2be58ab56728a7382909ae5249f5217d6f312455c4b497c64e3`, +separater Readback `388f86d5563cb53e48cd87a9a7c9ce10b02b695bfe195e574b769798fb960e66`. diff --git a/docs/agent-updater-handoff.md b/docs/agent-updater-handoff.md index 2e09b43..c0a75d6 100644 --- a/docs/agent-updater-handoff.md +++ b/docs/agent-updater-handoff.md @@ -188,3 +188,44 @@ oder Produktionsnachweis. Der erste Formatbefehl scheiterte vor Cargo an einem nicht überschriebenen Image-Entrypoint; mit `--entrypoint cargo` anschließend tatsächlich ausgeführt. Keine Tests als Folge dieses Fehlers erfunden oder Zielaktion wiederholt. + +## Fortschreibung: koordinierter Quellencheckpoint1.21 + +Der ursprüngliche a2efb79-Kernel und dessen Belegbytes bleiben unverändert. +Sein tatsächlicher enger Linux8-Nachweis steht in +[agent-updater-handoff-linux-results.md](agent-updater-handoff-linux-results.md). +Die darauf aufbauende Coreintegration speichert Originalverbrauch, bestehenden +Startzeugen, Handoff, konkrete Delegation und Stopintent in einer IMMEDIATE- +Transaktion des vorhandenen Ledgers. Sie überträgt einen typisierten begrenzten +Präfix in Protofeld14 und bestätigt ihn ausschließlich bei beiden Readyflags=false +und unlock=false. Persistiertes Unknown bleibt terminal. Leere neue Felder +lassen die alten Grant-/Decision-/Startcodecbytes unverändert. + +Der Originalplan bindet separat provisionierten Healthpublickey und Rawpinhash; +Admission liest den lokalen Pin unabhängig, historische Prüfung benutzt diesen +Originalkontext. Server-Health verlangt originale gespeicherte SignedSync- und +Baseinventarbytes samt bestätigender Folgerunde; sie eröffnet keine Admission. +Der konkrete Helper muss dieselben lokal tatsächlich angewandten Bytes und +Applyzeit innerhalb der belegten Zeitspanne unabhängig nachweisen. + +Linux Full ist vorgesehener ursprünglicher Autorizer/Owner-/Healthguard. +General bleibt in diesem Fall geschlossen und darf Nichtzuständigkeit nicht +als OwnerLost terminalisieren. Das ist nötig, weil die tatsächlichen General- +Capabilities keine Imageprüfung eines breiter berechtigten Fullprozesses erlauben. +Kein Generalhärtungs-/Capabilitywechsel ist implementiert oder freigegeben. + +Native Unterintents und Nachlesezeilen hängen im selben Ledger am Originalgrant. +Feste Stop-/Dateischritte sind create-once, Rückgabe und genau drei Startclaims +committen atomar. Nur ein weiterhin lebender ursprünglicher Worker darf die +reservierte Folge nach tatsächlicher Lockabgabe einmal dispatchen. Neue Full- +Helper bestätigen echte Start-/Health-/Recordbeobachtungen unter ihrem Guard. +InstalledRecord/Floorcodec und separat signierter Bootstrapbaselinecodec sind +reine Parsingverträge und ersetzen keine Trust-, Floor- oder OSprüfung. + +Offen bleiben reale enge Fullbridge-/Owner-/Healthadapter, passive gültige +Updatezustände/Kandidaten, vollständige erhaltende Baselineprovisionierung, +Workerdispatch und End-to-End-Apply. Restore bleibt ausdrücklich verweigert: +der eingefrorene Vorwärtskernel hat noch keinen qualifizierten Rollbackpfad. +Der Agent meldet bis zur echten Provisionierung nur agent.update/not_configured; +keine Applyfähigkeit aus Build/Katalog/Unitnachweis. Kein VM-Apply oder +Windows-Applynachweis dieses Checkpoints. diff --git a/docs/agent-updater-linux-native-results.md b/docs/agent-updater-linux-native-results.md new file mode 100644 index 0000000..877bb86 --- /dev/null +++ b/docs/agent-updater-linux-native-results.md @@ -0,0 +1,123 @@ +# Linux-Updaterport: nativer Fünfertest bestanden + +2026-11-14. Dieser Schritt prüft ausschließlich die fünf isolierten OS-Units +des Linuxports. **Auf der Cloud-VM als UID0 bestanden:5/5, kein Skip/Filter.** Kein Apply-, Autoupdater- oder +Windows-Erfolgsnachweis. Der einmalige Lauf und der separate lesende Originalfall-Readback sind +abgeschlossen. + +## Feste Herkunft und Testmenge + +Der neue Runner `deploy/updater_linux_native_acceptance.py` kopiert beim lokalen +`prepare` die 22 Originalinputs aus dem eingefrorenen Korrektursnapshot +`devstate/updater-linux-execfix-aa106c58-8c96-4c8a-8490-635b1d143f07/source` +im benachbarten Updaterworktree. Er prüft deren einzelne Hashes und Längen gegen +den unveränderten Intent mit SHA256 +`4921dac74d57931ad1973b4e64409d231e02ab0cb264b35113292fc295840ad3`. +Kein Lesen aktueller WIP-Quellen oder Ersatz durch andere Gitblobs. +Der unabhängig geprüfte lokale Receipt ist +`f705ba03e5043a411fc3a0642197fc4f16da8627e1e5cbfbac78ed125ecb650c`; +die feste vorhandene Testexe hat1538320Byte und SHA256 +`b11b57e6399dcfcfb255619a8fba558beea6a57e4f1ee997ee9c63c769a1e882`. +Der Runner baut keine neue Exe. Sein eigener Hash, die Transportquellen und die +22 kopierten Inputs werden in einem eigenen lokalen Fallmanifest gebunden und +vor jedem späteren Aufruf erneut geprüft. + +Die komplette native Testliste muss vor Ausführung exakt diese fünf Namen haben: + +- `ipc::tests::framing_denies_large_duplicate_unknown_and_unbound_requests_before_dispatch` +- `ipc::tests::partial_socket_frame_does_not_extend_its_total_deadline` +- `tests::held_file_rejects_symlink_and_replaced_name_but_preserves_bound_hardlinks` +- `tests::pidfd_image_birth_account_and_exit_are_independently_observed` +- `tests::same_pid_exec_rejects_changed_image_despite_retained_pidfd_birth_and_credentials` + +Die letzte Probe hält tatsächlich dieselbe PID, Prozessgeburt und UID/GID beim +Wechsel von eigenem Bash zu eigenem Sleep. Sie verlangt die Ablehnung des alten +Imagebelegs. Lokal bestand die korrigierte Generation5/5; die zusätzliche Probe +scheiterte mit dem ursprünglichen Processcode gezielt an dieser Ablehnung. +Diese bestehenden lokalen Ergebnisse wurden nur gelesen, nicht erneut gebaut +oder ausgeführt und nicht zu einem nativen Cloudnachweis umgedeutet. + +## Enger Zielumfang und Ausführung + +Root ist hier erforderlich: Die vorhandenen Testquellen verlangen UID0, +erstellen eigene geschützte UUID-Verzeichnisse unter `/run` und prüfen eigene +UID/GID0-Prozesse. Der feste Prozess startet mit geleerten Zusatzgruppen, +`no-new-privs` und bereinigter Umgebung. Er benötigt weder Capabilities aus dem +RMM-Protokoll noch eine Dienstinstallation. Die Tests verwenden eigene Dateien, +Hardlinks, Symlinks, Socketpairs und eigene Bash-/Sleep-Kinder. Sie öffnen keinen +Updaterlistener, kein RMM-Ledger und keine tatsächlichen Installationsziele. +Der Runner hält seine eigenen Kommandogruppen bis zur Bereinigung gegen +PIDwiederverwendung fest und beendet bei Timeout ausschließlich diese Gruppen. + +Der Operator verwendet den bestehenden streng geprüften Cloud-Linux-SSH-Pfad +aus Main. Der Runner liest Credentials ausschließlich bei `execute`/`read` +über den vorhandenen Parser, keine kopierten Credentials, keine Hostkeyausnahme. +Nur die gebundene Testexe wird größenbegrenzt übertragen und auf der VM erneut +gehasht. Das neue Remoteverzeichnis ist exklusiv +`/var/tmp/rmm-updater-linux-os-`, Rootbesitz,0700. Binärdatei und Belege +werden create-only geschrieben und geflusht, einschließlich Elternverzeichnis. + +Vorher/nachher werden Ubuntu24.04/x86-64 und Boot, die drei tatsächlichen +Agent-/General-/Full-Prozessgenerationen mit Konten/Image/InvocationID, vier +bekannte geschützte Config-/Pin-/Unitdateien mit Rohhash/Metadaten sowie drei +DB- und eine Executorlock-Dateiidentität verglichen. APT muss weiterhin +inaktiv und deaktiviert sein. `systemctl show` wird ausschließlich lesend +verwendet; kein Start/Stop/Enable, kein Paketbefehl und kein Reboot. + +Tatsächlich einmalig ausgeführt (Originalfall +`ec030323-85df-4b38-9e70-87be330033c2`): + +```sh +python3 deploy/updater_linux_native_acceptance.py prepare +python3 deploy/updater_linux_native_acceptance.py execute --case ec030323-85df-4b38-9e70-87be330033c2 +python3 deploy/updater_linux_native_acceptance.py read --case ec030323-85df-4b38-9e70-87be330033c2 +``` + +Ein exklusiver lokaler Executeeintrag wird vor SSH dauerhaft geschrieben. +Bei verlorenem Reply ausschließlich denselben Fall lesen. Keine Wiederholung, +keine neue Testgeneration und kein neuer Fall zur Umgehung eines unklaren Laufs. +Fehlt ein Endbeleg, meldet Readback dies ausdrücklich; daraus entsteht kein +Erfolg. Der Remote-Einmalmarker und exklusive Ordner verweigern ebenfalls einen +zweiten Lauf. Ein vollständiger Erfolg verlangt5/5 ohne Ignored/Filter sowie +unveränderte Vor-/Nachzeugen und getrennten lesenden Readback. + +## Tatsächlich lokal geprüft und verbleibende Grenzen + +Python-Syntax, begrenzte Ausgabeerfassung, eigener Timeout samt +Kommandogruppenbereinigung und die feste Base64-Transferlänge wurden lokal +geprüft. Keine VM-/SSH-/Serveraktion, kein RMM-Job, keine WebUI-Genehmigung und +kein neuer Cargo-Build/-Test durch diesen Vorbereitungsschritt. + +Die Zeugen vergleichen bekannte Kontrollbytes und Dateiidentitäten, keine +vollständigen SQL-/PKI-Historien. Die drei Dienstprozesse werden vor und nach +beobachtet; der Runner hält deren Handles nicht durchgehend. Die innerhalb der +Unit geprüften pidfds betreffen ausschließlich eigene Fixtureprozesse. +Rootausführung eines vorab geprüften Testbinary ist keine Betriebssandbox. +Fehlschlag kann eigene Fixtureverzeichnisse hinterlassen; kein automatisches +Löschen oder Wiederholen nach unklarem Ende. + +Der isolierte Linuxport besitzt weiterhin keine vollständige ledgergebundene +Engine/Fence, keinen dauerhaften Updaterdienst und keinen freigegebenen +Dateipaarwechsel. Dienststop, Ledgerübergabe, Staging/Swap, Health, Rückgabe und +Rollback des tatsächlichen Agentupdates bleiben eigene offene Integration und +anschließende WebUI-genehmigte Linux-first-Abnahme. Der bestehende Acht-Kernel- +Runner, sein nativer Nachweis und die ursprünglichen Releaseverifier-Runner +bleiben unverändert. + +## Tatsächlicher nativer Endbeleg + +Der geprüfte Runner SHA256 `a13e3554d27fce14848ff30e2d86430bb462f45d19fcd9acca78480c970eeb38` +übertrug ausschließlich die feste Testexe, prüfte zuerst die vollständige +Fünferliste und führte sie einmal aus. Ergebnis5/5,0ignored/filtered, Exit0, +kein stderr. Der separate Readback meldet denselben abgeschlossenen Fall +und identische aktuelle Vor-/Nachzeugen. + +Execute-Beleg SHA256 `2b8bff59f158a204f669f1df9b022fac0024248de3fe035a1f11b7f532574a1a`; +Readback SHA256 `e9bdfed8919f283a917ebf06d5354832df8634a5cbb44210cdca6684e425931a`. +Die Rohbelege und22 eingefrorenen Inputs bleiben gitignoriert. + +Die Full-Helper-Unit war und bleibt aktiv, aber für Autostart deaktiviert. +Dieser isolierte Unitlauf ändert diese Einstellung nicht und belegt keine +Bereitschaft nach einem Neustart. Keine RMM-Jobs oder Servicekontrolle. +Der MVP einschließlich Windows und vollständigem Selbstupdater ist weiterhin +nicht abgeschlossen. diff --git a/docs/agent-updater-linux-port.md b/docs/agent-updater-linux-port.md new file mode 100644 index 0000000..f1a68cc --- /dev/null +++ b/docs/agent-updater-linux-port.md @@ -0,0 +1,206 @@ +# Linux-OS-Port des unabhängigen Updaters + +Stand2026-11-14: neue Bibliothek `rmm-updater-linux`, auf Auftrag des Hauptagenten +isoliert neben Domain/Core und Server/WebUI implementiert. **Noch kein laufender +Updaterdienst und keine Applyabnahme.** Native Linux-first-Abnahme und sämtliche +Zielaktionen bleiben beim Hauptagenten. Der vorhandene Releaseverifier, dessen +Native-Runner sowie der separat qualifizierte achtteilige Handoffkernel bleiben +unverändert. + +**Aktueller lokaler Quellenstand nach unabhängigem Review:** Der weiter unten +erhaltene4-Fälle-Beleg ist historisch. Ein echter Same-PID-Exec-Bindungsfehler +wurde korrigiert, mit dem alten Code reproduziert und im neuen lokalen +5-Fälle-Nachweis geschlossen. Dieser lokale Schritt allein ist kein nativer +VM- oder Applynachweis; die danach separat durch Root ausgeführte native +OS-Unitqualifikation ist am Ende ergänzt. + +## Implementierte Betriebssystemstrecke + +`files` öffnet jede Verzeichniskomponente mit gehaltenem `openat`-Dirfd, +`O_NOFOLLOW` und `O_CLOEXEC`. Rootgeschützte installierte Verzeichnisse dürfen +keine gruppen-/weltbeschreibbaren Vorfahren haben. Dateiprüfungen binden +Device/Inode, UID/GID, Modus, vorhandene Linkzahl, Länge und SHA256; Hashing +benutzt höchstens32KiB Lesepuffer. Historisch gebundene Hardlinks werden nicht +pauschal verboten. Neue Stages haben genau einen Link. + +Die vier Produktionsziele sind geschlossen: Agent, gemeinsame Helperbinary, +Fullkonfiguration und Fullpin. Aus einem Request kommt kein Zielpfad. +Staging entsteht exklusiv im **gleichen gehaltenen Installationsverzeichnis**, +mit exaktem EOF/Längen-/Hashnachweis, ursprünglichen Besitz-/Moduswerten und +Datei-/Directory-fsync. Fehlerhafte/partielle Stages bleiben erhalten und +werden nicht automatisch wiederverwendet oder gelöscht. Der eingebettete +Downloadreader muss selbst IOzeit und Kanalabbruch begrenzen; die Bibliothek +prüft das ursprüngliche Boot-/Monotonbudget zwischen IOschritten, kann aber +keinen beliebig blockierenden fremden `Read`-Aufruf unterbrechen. + +Ein Austausch verlangt einen tatsächlich gehaltenen `LedgerGuard`. Vor jedem +Namespaceeingriff werden dessen aktuelle Dateiidentität, weiterhin gestoppte +Reader und Budget geprüft. Der Vorgänger wird mit `RENAME_NOREPLACE` unter +seinem erhaltenen Inode auf einen festen Backupnamen verschoben; danach wird +die verifizierte Stage ebenfalls ohne Überschreiben an den Originalpfad +verschoben. Jede Phase benötigt vorher den dauerhaften `DurableEffectFence`. +Ein Crash zwischen den Renames ist ausdrücklich **kein atomarer Bundleswap**: +Vorgänger und Stage bleiben nachlesbar, neuer Execute-/Resumeversuch verboten. +Ein zulässiges einmaliges Rollback benötigt eine eigene vorab gebundene Fence; +es erhält beide Codegenerationen und verändert keine Zustandsdatei oder Floor. + +`process` bindet echte `pidfd`s, ein gehaltenes `/proc/PID`-Verzeichnis, +Prozessgeburt, alle UID/GIDwerte und ein gehaltenes Rootimage. Exithinweise +und nachträgliche Abweichung verweigern. Imagehashing verwendet `pread`, damit +parallele Nachlese keinen gemeinsam verschobenen Dateioffset verwendet. +Nicht unterstützte Kernel erhalten keinen PID-/Prozessnamenfallback. +Vor und nach dem Hashen wird das **aktuell ausgewählte** `/proc/PID/exe` +erneut durch das gehaltene Proc-Verzeichnis geöffnet und per Device/Inode +gegen das ursprüngliche Image gebunden; Geburt, Konten und pidfd werden +danach nochmals geprüft. Ein noch lesbarer alter Image-FD allein genügt nicht: +`execve` behält PID, Geburt und Credentials, wechselt aber die Codegeneration. + +`services` kennt ausschließlich Agent/General/Full und optional den bereits +inaktiven, deaktivierten APT-Reader. General und Full müssen dieselbe +Helpergeneration haben. Geladene Unit und sämtliche Drop-ins werden als +geschützte Fileproofs gebunden; Running/PID/Invocation-ID, native Prozesszeugen +und tatsächliche Konten werden unabhängig nachgelesen. Ein Rootpeer genügt +nicht: `SO_PEERCRED` muss zur aktuellen konkreten Helper-/Updater-Dienstinstanz +mit gehaltenem Prozess passen. Der stabile Updater ist getrennt, UID/GID0, +und gehört niemals zum Stopset. + +Stop und Start benutzen feste argv an `/usr/bin/systemctl`, keine Shell oder +freien Kommandos. Es gibt keine Enable-, Reboot- oder APT-Startoperation. +Stop startet genau eine Systemdanforderung pro gebundenem alten Dienst und +beobachtet danach dessen tatsächliches Ende. Nach vollständigem Code-/Pinpaar +und Ledger-Rückgabe startet der enge Anschluss General, Full und Agent einmal. +Timeout des eigenen Clients beendet nur dessen gehaltenen pidfd-Prozess; +Systemd kann den Auftrag bereits übernommen haben. **Jeder Fehler nach +möglicher Übergabe bleibt unklar; nie still wiederholen oder als Nichtstart +ausgeben.** + +`LedgerGuard` öffnet ausschließlich vorhandene `consumption.sqlite` und +`executor.lock` unter `/var/lib/rmm-helper`. Kein Create/Truncate, kein neuer +Journal-ID-Slot. Exklusive `flock`-Übernahme erfolgt erst nach bestätigtem Stop +aller installierten Reader und bindet beide exakten Dateiidentitäten. Die +Lebensdauer leiht `StoppedServices`; ein gleichzeitiger Start derselben +Kontrollinstanz ist so ausgeschlossen. Vor Abgabe muss die eingebettete Fence +den ursprünglichen `LedgerReturnIntent` dauerhaft gespeichert haben. + +## Lokaler Kanal und noch fehlende Integration + +Der implementierte IPC-Transport bindet ausschließlich den vorher separat +provisionierten privaten Rootpfad `/run/rmm-agent-updater/control.sock`. +Vorhandene Sockets werden weder entfernt noch wiederverwendet. Vor Parsing und +Dispatch wird der tatsächliche aktuelle Helperdienst mit SO_PEERCRED und +gehaltenen Prozess-/Unitzeugen authentisiert. Der Client authentisiert den +fest provisionierten Updater unabhängig vor dem Senden und vergleicht seine +Antwort mit genau diesem Participantbeleg. Ein begrenzter Längenheader erlaubt +höchstens32KiB und eine Anfrage pro Verbindung. Methods sind Describe, Activate, +Read und Health; keine Approval-, Pfad-, Befehls- oder neue Startgranterteilung. +`ready` bleibt zwingend false. Activate-IOfehler erlaubt ausschließlich Read. + +Es wird bewusst **keine permissive Engine/Fence und kein unfertiges Daemonbinary** +ausgeliefert. Der Core-Eigentümer integriert Originalsignaturen, aktuelle +TrustedClock/Trustpolicy, immutable Handoff/Delegation im bestehenden Ledger, +alleinigen logischen Owner, feste Staging-/Fullrendererzeugen und den +evidenz-only SignedSync-/Inventarhealthbeleg. Die beiden nativen Rename-Intents +pro Datei sind zusätzliche vorhandene-ledger-gebundene Effectintents, keine +Verdoppelung der begrenzten16 Handoffevents. Ein verlorener Writer oder +definitives Unknown wird niemals durch diese OSbeobachtungen geheilt. + +Noch offen: konkrete Core-Fence-/Engineimplementierung, monotone Floor- und +InstalledRecordpublikation, Dienstbootstrap/stabiles Binary, tatsächliche +Systemd-/IPC-/Staging-/Dateitausch-/Rückgabekette und zulässiger Rollback im +WebUI-genehmigten Updateversuch. Der Loopback-/Rootbootstrapweg ist keine +Jobgenehmigung. Notebook bleibt ausschließlich Entwicklungsrechner. + +## Tatsächlich lokal geprüft + +Isolierter Offline-Buildcontainer aus dem vorhandenen Image +`sha256:9a76ad3744ebfdddae96ca10001ce8291c1b332fb54c8df5eea0e8e999ac6fc6`. +Private eingefrorene Quellkopie mit nur Domain/Handoff/Linuxport als +Workspacemembers, unveränderten Dependencyversionen; der private Lock wurde +dort offline aufgelöst, ursprünglicher Workspace/Lock durch diesen Subagenten +nicht verändert. Eigener Targetpfad `devstate/agent-updater-linux/target`. + +Bestanden: Releasebuild und **4/4** Prüfungen, keine Skips/Filter, Clippy mit +`-D warnings`, Formatcheck. Die beiden echten OSprüfungen betreffen ausschließlich +neue private `/run`-Unitfixtures und einen eigenen gehaltenen Sleep-Prozess: +Symlink-/Namensersatz-/Modusverweigerung, erhaltene gebundene Hardlinks, +PID-/Geburts-/Image-/Konten-/Exitbindung und ursprüngliche Deadline. Der dritte +Fall verweigert übergroße, doppelte, unbekannte und ungebundene IPCfelder. +Der vierte nutzt ausschließlich ein lokales Unix-Socketpaar und belegt, dass +fragmentierte Nachrichten die feste Gesamtlesefrist nicht durch einzelne +erfolgreiche Bytes verlängern können; es läuft kein lauschender IPCserver. +Die ursprüngliche Jobfrist begrenzt dabei auch jeden einzelnen blockierenden +Socketaufruf; der zweite Teilfall belegt die kürzere Jobfrist gegenüber der +längeren Framefrist. +Dabei fand er einen echten Serde-Fehler: eine leere Unitvariante ignorierte +Zusatzfelder; die strikte leere Structvariante ist korrigiert und nachgeprüft. +Erster Compilerlauf meldete einen mehrdeutigen `File::by_ref`; typisiert +korrigiert. Clippy forderte einen typisierten Stagingdescriptor statt acht +einzelner Argumente; kein Lint wurde unterdrückt. + +Keine lokale oder native Dienst-/IPCserversitzung, kein Aufruf von Systemd, +kein Zugriff auf echte RMM-Zieldateien, kein Releaseapply und keine VM-Aktion. +Diese Nachweise sind keine Abnahme der noch fehlenden Runtimeintegration. + +Der create-only Nachweis liegt privat unter +`devstate/agent-updater-linux/qualification-19449c78-6919-4e25-8750-cd3c450fb68e/`. +Er bindet die tatsächlich verwendete eingefrorene Quellkopie, Befehle, +Exitcodes und stdout/stderr. Linuxport-Quellsatz: +`699276d3d3e467143d8ccf0fcb3b51949d3c2fffb1f7d0f0a167239ea2b10404`; +Receipt: `ff569473d0ca8179948429f1fc78404e09c1666e4053b6efe672edf079696adc`; +qualifiziertes lokales Unitbinary: +`25e9de040b8a461291efb9566c02b6b3c2cb98d032ae8d071278dbbc0b2642cf`. +Der frühere lokale 3-Fälle-Nachweis bleibt unverändert als historischer Stand +erhalten und qualifiziert diese neuere Quelle nicht. + +## Fortschreibung: Same-PID-Exec-Gegenbeleg und Korrektur + +Der unabhängige Review fand, dass `HeldProcess::verify` zunächst nur das alte +gehaltene Image erneut hashte. Ein `execve` im gleichen Prozess blieb dadurch +unentdeckt. Die Korrektur bindet das aktuelle Kernel-Exeziel vor und nach dem +Hashen an den ursprünglichen Dateizeugen und prüft die übrige Prozessidentität +erneut. Es gibt keinen Prozessnamen-/PID-Fallback oder gelockerten Proc-Zugriff. + +Die neue echte OSprobe startet ausschließlich einen eigenen Bashprozess, +öffnet dessen pidfd/Image/Geburts-/UID-/GIDzeugnisse und lässt ihn über seine +eigene Pipe nach `/usr/bin/sleep` execen. Ein neuer unabhängiger Zeuge bestätigt +dieselbe PID, Geburt und Konten, ein weiter lebendes pidfd sowie den tatsächlich +geänderten Imagehash. Der alte Zeuge muss verweigern. Die Kindumgebung ist +geleert; ein RAII-Wächter beendet und wartet ausschließlich dieses eigene Kind +auch bei einem Testpanic. Keine RMM-Dienste oder fremden PIDs werden berührt. + +Tatsächlich lokal ausgeführt, isolierter Offlinecontainer mit eingefrorener +Domain-/Handoff-/Linuxport-Quellkopie: korrigiert **5/5 ohne Skips/Filter**, Clippy +`-D warnings` und Formatcheck bestanden. Danach wurde ausschließlich in dieser +privaten Kopie `process.rs` durch die Originalquelle des erhaltenen4er-Belegs +ersetzt. Die neue Execprobe scheiterte erwartungsgemäß mit Exit101 genau an +`held.verify().is_err()`. Nach Rückkehr zur korrigierten Quelle bestanden erneut +alle5Fälle. Das ursprüngliche4er-Receipt und dessen Binärdatei bleiben erhalten. +Enger unabhängiger Re-Review des Fixes und seiner Belege: **PASS**. + +Neuer create-only Beleg: +`devstate/updater-linux-execfix-aa106c58-8c96-4c8a-8490-635b1d143f07/receipt.json`, +SHA256 `f705ba03e5043a411fc3a0642197fc4f16da8627e1e5cbfbac78ed125ecb650c`. +Finale lokale Unitexe:1538320Bytes, SHA256 +`b11b57e6399dcfcfb255619a8fba558beea6a57e4f1ee997ee9c63c769a1e882`. +Snapshot und ursprüngliche Logs einschließlich des erwarteten Gegenfehlers +bleiben privat erhalten. Nicht ausgeführt: VM, Systemd, IPCserver, Daemon, +Releaseapply oder Deployment. Gerade der tatsächliche Generalhelperkontext +kann andere Proc-/Capabilitygrenzen besitzen; ein isolierter Rootcontainer +qualifiziert diesen noch nicht. Fehlender Proc-/Imagezugriff muss verweigern, +keine Sandboxlockerung aus diesem lokalen Erfolg ableiten. + +## Anschließend tatsächlich auf Cloud-Linux geprüft + +Root führte die eingefrorene finale5er-Unitexe anschließend separat auf der +festgelegten Linux-Cloud-VM als UID0 aus: Fall +`ec030323-85df-4b38-9e70-87be330033c2`, genau5bestanden,0Skips/Filter. +Eine getrennte Same-case-Nachlese war identisch. Keine RMM-Jobs, kein Apply, +keine Dienststeuerung oder Änderung der laufenden Agent-/Helpergenerationen. +Der Fullhelper blieb aktiv, seine Unit weiterhin disabled; daraus folgt kein +Autostartnachweis. Der vollständige von Root veröffentlichte Originalbericht +wird bytegleich übernommen: [Native Linux-OS5](agent-updater-linux-native-results.md) +(Maincommit `c35c440`). Historische lokale Belege bleiben unverändert. + +Das ist ein nativer OS-Unitnachweis, ausdrücklich **keine Qualifikation des +restriktiven tatsächlichen Generalhelper-Dienstkontexts**, der konkreten +IPC-Peers, Engine/Fence oder Releaseaktivierung. Diese Gates bleiben offen. diff --git a/docs/agent-updater-runtime-source.md b/docs/agent-updater-runtime-source.md new file mode 100644 index 0000000..f5d3b2c --- /dev/null +++ b/docs/agent-updater-runtime-source.md @@ -0,0 +1,62 @@ +# Koordinierter Updater-Quellencheckpoint1.21 + +2026-11-14. Dieser Checkpoint verbindet den unveränderten signierten Verifier, +den eingefrorenen Handoffkernel, Linux-OSports sowie Domain-/Core-/Protokoll-, +Server-/MCP-/WebUI-Quellen. Er enthält keine ausgelieferte Applyruntime und +keinen erfolgreichen Updatejob auf der Cloud-VM. + +Implementiert sind der feste Updateplan mit zwei eigenen streambaren Artefakten, +immutable Tenantkatalog, zusätzliche deny-only Rechte-/Policyprüfung für Ersteller +und Freigeber, genaue WebUI-Byte-/Hashanzeige und der eigene passive agent.update- +Scope. Der Agent meldet dafür derzeit ausschließlich not_configured; qualifizierte +Apply-/Checkcapabilities werden daraus nicht abgeleitet. Der vorhandene kleine +Paketartefaktpfad bleibt unverändert. + +Im bestehenden Helperledger werden Verbrauch, alter Startzeuge, Handoff, +Delegation und Stopintent atomar gespeichert. Typisierte Inflightkontrolle hält +beide Readyflags und Unlock geschlossen. Native Unterintents sind create-once, +rollen-/Head-/Nonce-gebunden und erhalten Originalhistorie. Getrennter geschützter +Healthkey und Originalplanpin ersetzen jede frühere Jobsignerannahme. Die neue +Serverroute prüft gespeicherte Original-Sync-/Baseinventarbelege; der konkrete +lokale Fullguard muss diese unabhängig gegen eigene tatsächlich angewandte +Rawbytes und Applyzeit prüfen. General ist dafür nicht zuständig und darf ein +Originalupdate aus diesem Grund nicht zu Unknown machen. + +Der Worker enthält echte geschützte Dateizeugen, historischen Originalrequest- +Replay, Uhr-/Boot-/Deadlineprüfung, tatsächliche Prozess-/Dienstidentitäten, +Originalledger- und native Dateieffektzäune sowie lokale Trust-/Baselineprüfung. +Diese Bibliotheksbausteine sind kein aktivierter Daemon oder qualifizierter +End-to-End-Dispatcher. + +Lokal tatsächlich ausgeführt im vorhandenen Rust-Buildcontainer, Netzwerk aus: + +- Gemeinsamer all-targets Check für Agent, Windowsquellen unter Linux-cfg, + privilegierten Helper, Worker und Server: PASS. +- Core64, Domain23 und Server45 Tests: PASS; fünf vorhandene Server-DB-Harnesstests + ausdrücklich ignored. Diese5 sind kein DB-Abnahmenachweis. +- Betroffene gemeinsame all-targets Clippyprüfung mit -D warnings: PASS. +- Formatprüfung der betroffenen Pakete: PASS. +- Echter separat baseline-/release-signierter Worker-Gegenfall:1/1 PASS. + Exakte historische aktive Sequenz/Manifest bestehen; gleiche oder niedrigere + Kandidaten am unveränderten Floor, Ablauf und Keywiderruf verweigern. + Private Rückmutation auf den früheren Fehler active_release=None scheitert + reproduziert mit Exit101. Das ist ein lokaler Trusttest, keine VM-Anwendung. + +Lokale Befehls-/Logbelege liegen geschützt im ignorierten Verzeichnis +`devstate/updater-checkpoint-090e6ad9-c88e-4f38-b6e1-f7fc1f189244/`. +Die getrennte Deliveryqualifikation dokumentiert PostgreSQL15-Migrations-/RLS- +und Webprüfungen in [agent-updater-server-console.md](agent-updater-server-console.md). +Der tatsächliche Linux8-Kernel- und Linux5-OSnachweis ist separat in +[agent-updater-handoff-linux-results.md](agent-updater-handoff-linux-results.md) +und [agent-updater-linux-native-results.md](agent-updater-linux-native-results.md) +dokumentiert. Root-OSfixtures ersetzen keinen General-/Full-Dienstkontextnachweis. +Historische Belege bleiben unverändert. + +Für eine wirkliche erste Anwendung fehlen weiterhin die enge Fullbridge mit +qualifizierter Owner-/Healthguard-Implementierung, atomar übergebene live +Workerdispatchstrecke, Record-/Floorpublikation, erhaltende1.21-kompatible +Bootstrapbaseline, gültiger passiver Kandidatenzustand, ein neuer konkreter +WebUI-genehmigter Linux-Apply sowie dessen unabhängiger Health-/Erhaltungsnachweis. +Restore/Rollback bleibt deny, weil der unveränderte Vorwärtskernel noch keinen +qualifizierten Rückweg besitzt. Windowsapply ist separat offen. Kein Zielhost +wurde durch diesen lokalen Checkpoint installiert, gestoppt oder aktualisiert. diff --git a/docs/agent-updater-server-console.md b/docs/agent-updater-server-console.md new file mode 100644 index 0000000..e1bff1b --- /dev/null +++ b/docs/agent-updater-server-console.md @@ -0,0 +1,219 @@ +# Agent-Selbstupdate: Serverkatalog, Transport und feste WebUI-Pläne + +2026-11-14, isolierter Quellenstand im Updaterbranch. Server und WebUI sind +implementiert und lokal geprüft; **kein Deployment, kein nativer Applylauf und +noch kein aktiver Autoupdater**. Der beauftragte Schnitt verwendet ein eigenes +signiertes Agent-/Helper-Codepaar, keine APT-/MSI-Fixture und kein Wartungsskript. +Domain, lokale Helper-/Handoffruntime und signierter Inflightabgleich werden +getrennt integriert. Die Produktentscheidung und Zielabnahme bleiben beim +Hauptagenten; diese Seite ersetzt weder dessen Review noch die Linux-first-Gates. + +## Planung und unveränderte Genehmigungsgrenze + +HTTP und MCP benutzen dieselbe neue `plan_request`-Auflösung. Für +`action="update_agent"` sind ausschließlich folgende Aktionsparameter erlaubt: + +```json +{ + "release_id": "11111111-1111-4111-8111-111111111111", + "execution_identity": "root", + "timeout_seconds": 600, + "max_output_bytes": 65536 +} +``` + +Dies ist ein synthetisches Schemafragment, kein ausführbarer Auftrag. Feste +Asset-IDs, Fristen, Rolloutlimits und Grund stehen wie bisher daneben. Keine +freien URLs, Dateipfade, Artefaktlisten, Vorgänger, Updater- oder Peerpins vom +Aufrufer. Auch der alte typisierte `PlanInput` erlaubt keine alternative +Einreichung eines selbst zusammengestellten `ResolvedAgentUpdate`. + +Der Server löst den festen Releasekatalog und je Ziel die letzte gespeicherte +`agent_update`-Beobachtung auf. Neben dem bestehenden Baseinventar akzeptiert er +gezielt den eigenen passiven Scope/Source `agent.update` mit Schema1 und exakt +`{"agent_update": AgentUpdateObservation}` als Daten. Der normale authentisierte +Ingest verlangt die angebotene Capability `agent.update/1`; Tenant, Agent, Boot +und Generationen stammen weiterhin ausschließlich aus dem geprüften Envelope. +Die eigene 60s-Quelle behauptet kein neues Windows-Baseinventar und löst keine +angeforderte Liveerhebung aus. Verlangt werden gültige Quelle/Qualität, höchstens fünf +Minuten alte Erhebung/Empfang/Updatebeobachtung, frischer Kontakt, gleicher +aktueller Boot, unveränderte Identitätsgenerationen, bestätigter Agent-/Helpersync +und keine Restore-/Sequence-/Recoverysperre. Die bezeichnete ursprüngliche +signierte Syncentscheidung muss im erhaltenen Servercheckpoint existieren, +bei der Beobachtung gültig gewesen sein und zu Boot, Verbindungsgeneration, +Gerät und beiden aktuellen Journalidentitäten passen. Ein neuerer normaler +Sync macht die historische Entscheidung nicht nachträglich zu einer neuen Lease. + +Genau die passende passive Kandidatenpreview bindet Zielrelease und typisierten +Peerpinübergang. Der Release liegt über dem beobachteten Aktivierungsfloor. +Fehlende, alte oder widersprüchliche Beobachtung ergibt keine Planung und wird +nicht durch eine Liveabfrage oder angenommene Baseline ergänzt. Geräte-mTLS +liefert Herkunft, keine unabhängige Hardware-/OS-Attestierung; der privilegierte +Updater muss sämtliche lokalen Bindungen vor Wirkung erneut selbst prüfen. + +Der gespeicherte Plan enthält sämtliche festen Updatejobs mit exakten +Release-/Envelopehashes, Vorgänger-/InstalledRecordhash, Agent-/Helperdateien, +Updater-/Policy-/Keyringbindung, Konfigurations-/Peerpinübergang und einmaligem +zulässigem Vorgängercode-Rollback. Je Versuch werden exakt die zwei signierten +Artefaktreferenzen abgeleitet. Fehlende, zusätzliche, doppelte oder fremde +Referenzen verweigern Revalidation, Zustellung, Grant und Download. +Die Updaterbindung enthält zusätzlich den festen separaten Health-Publickey +`health_public_key_hex` und dessen `health_key_pin_sha256`. Beide stehen in den +kanonischen Planbytes direkt nach dem Keyringhash, werden vollständig angezeigt +und von der eigenen deny-only-Policy exakt verglichen. Das ersetzt weder den +Jobsignierschlüssel noch erlaubt es einen Fallback auf ihn. Der signierte +Executionpermit bezeichnet ausschließlich bei Updatejobs zusätzlich die +ursprüngliche Plan-ID; ältere Aktionen behalten ihre ursprünglichen Grantbytes. + +Ersteller und Freigeber benötigen aktuell `updates:apply` sowie getrennt +`root:execute` oder `system:execute`. Das erteilt keine Genehmigung. +`operations.submit` bleibt der unveränderte persistente Antrag +`pending_approval`, vor der interaktiven WebUI-Genehmigung ohne Jobs/Outbox/ +JobOffer/Grant. Die vorhandene Autorisierungs- und Auditschicht wird nicht +ersetzt; kein neuer Approve-API-/MCP-/DB-Pfad. Aktualisierte Rechte, Capabilities, +Scope, Releasevertrauen und gespeicherte Vorgänger werden weiter geprüft. + +## Getrenntes Vertrauen und deny-only-Policy + +`RMM_AGENT_UPDATE_KEYRING_FILE` verweist auf eine separat provisionierte, +geschützte Datei mit dem gemeinsamen `UpdateKeyringFile`-Schema1: +Generation und höchstens16 Publickeys, jeweils Plattform, Sequenzbereich und +Widerrufsflag. Der Server prüft Eigentümer wie beim vorhandenen Jobsignierschlüssel, +0600, reguläre einzelne Datei ohne Symlink sowie nicht fremdschreibbaren Elternpfad; +begrenzt eingelesene Originalbytes und gehaltene Dateimetadaten werden verglichen. +Der vollständige Rawhash/Generation muss zur festen Updaterbindung passen. +Keine Schlüssel aus einem Job, Download oder Katalogeintrag werden vertraut. + +Verifikation benutzt den unveränderten bereits nativ qualifizierten reinen +`rmm-updater`-Verifier: feste Ed25519-Domäne, kanonische Manifestbytes, +Signatur, Plattform, Gültigkeit und kompatibles Protokoll/Zustandsschema. +Die serverseitige Kandidatenprüfung ersetzt den lokalen Aktivierungsfloor nicht. + +Die eigene Datei `RMM_AGENT_UPDATE_POLICY_FILE` ist im ersten Entwicklungsprofil +ein ausdrückliches Schema1-Opt-in mit Ablauf und höchstens64 festen Scopes. +Jeder Scope bindet Tenant/Asset/Agent/Generationen, aktuelle Principals, +qualifizierte Helperpolicy/-binary, Updaterbinary/-policy, Keyringgeneration/-hash, +separaten Health-Publickey/-Pin, +erlaubte konkrete Manifest-/Vorgängerrecordhashes und Abnahmenachweis-ID. +Fehlend, falsch, abgelaufen oder Produktion ohne passenden Adapter bleibt deny. +Bestehende General-, Fullskript-, SCM-, MSI- und APT-Policies erteilen dadurch +keine Updateerlaubnis. Kein Codepfad provisioniert diese Dateien oder Mitgliedschaften. + +Zusätzlich sind die abgestimmten tatsächlichen Capabilities erforderlich: +`update_agent`, `agent.update.apply/1`, `rmm.sync.v1`, unabhängiger Root-/SYSTEM- +Helper, `root:update_agent` beziehungsweise `system:update_agent` und konkrete +Helper-/Updatercode-/Updaterpolicyhashes. Quelle oder Build allein öffnet sie nicht. + +## Eigene große Artefakte und passive Metadaten + +Migration0015 legt nur die getrennten Tabellen `agent_update_artifacts` und +`agent_update_releases` an. Beide haben erzwungene Tenant-RLS, zusammengesetzte +Tenant-/Artefakt-/Hash-/Längen-Fremdschlüssel und unveränderliche Inhalte. +Die Anwendungsrolle besitzt nur SELECT/INSERT, keine Tabellen und kein RLS-Bypass. +Alte APT-/MSI-Artefakttabelle, Route, SQLgrenze und Store bleiben bei256KiB. + +| Pfad | Vertrag | +| --- | --- | +| `POST /api/v1/tenants/{tenant}/agent-update-artifacts?artifact_id=…&sha256=…&size_bytes=…` | Interaktive Katalogverwaltung mit CSRF und `catalog:write`; binärer Stream mit exakter Content-Length, höchstens256MiB und180s; kein Job | +| `POST /api/v1/tenants/{tenant}/agent-releases` | Strikter signierter Envelope; Veröffentlichung erst nach vollständiger Prüfung beider bereits importierter Dateien; kein Job | +| `GET /api/v1/tenants/{tenant}/agent-releases` / MCP `updates.list_releases` | Gespeicherte feste Metadaten, berechtigt und paginiert; abgelaufene Metadaten bleiben lesbar und gesondert gekennzeichnet | +| `GET /agent/v1/releases/current?platform=…` | Geräte-mTLS und passende Plattform; tatsächlich beobachtetes höchstes Katalogrelease oder `not_configured`; kein Nachweis weltweiter Aktualität und kein Apply | +| `GET /agent/v1/update-artifacts/{artifact}?job_id=…&attempt_id=…&offset=…&length=…` | Geräte-mTLS, genehmigter fester Job/Versuch, aktuelle Rechte/Policy/Identität und exakte Manifestreferenz; höchstens512KiB je Antwort | + +Upload liest kein vollständiges Binary in einen Vec: feste32KiB-Schreibstücke, +bounded Hash/Längenzählung, create-only privates Staging, Flush vor unveränderlicher +Publikation. Frühes EOF, Zusatzbytes und Hashabweichung verweigern Veröffentlichung. +Die feste180s-Frist wird ausdrücklich vor und nach jedem Streampoll, nach der +Frameverarbeitung sowie vor Veröffentlichung geprüft. Damit können auch sofort +verfügbare oder leere Frames den Ablauf nicht umgehen; das eigene unveröffentlichte +Staging wird beim Abbruch über den vorhandenen Drop entfernt. +Während des Streams wird keine SQLtransaktion gehalten; vor Veröffentlichung +werden interaktive Berechtigung und CSRF erneut geprüft. Unterbrochene eigene +Stagingdateien werden entfernt; Prozess-/Hostcrash kann verwaiste eigene +Stagingdateien hinterlassen, ohne daraus ein veröffentlichtes Objekt zu machen. + +Download benutzt ein gehaltenes reguläres No-follow-Handle und prüft vollständige +Länge/Hash mit32KiB-Puffer, dann den begrenzten Bereich und Dateimetadaten. +Das lädt kein vollständiges großes Objekt in RAM; der erste einfache Adapter +hashprüft das Objekt allerdings pro Chunk erneut. Der Client muss weiterhin vor +Staging/Verwendung unabhängig vollständige Länge, EOF und Releasehash prüfen, +ohne Redirect oder beliebigen Downloadhost. Produktionsobjektspeicher und +weitergehende Durchsatzoptimierung sind kein behaupteter Nachweis dieses Adapters. + +## WebUI und tatsächliche lokale Prüfungen + +Die WebUI bietet eine feste Release-ID und zeigt gespeicherte Releases sowie +alle Update-/Rollbackbindungen vor Genehmigung. Sie prüft ursprüngliche +Planhashbytes, rekonstruiert den gesamten kanonischen Updateplan und Jobhash, +dekodiert den kanonischen Envelope und prüft Manifest-/Envelopehashes und +genau zwei Artefakte je Versuch. Byte-/Ansichtsänderung sperrt die Freigabe. +Signaturprüfung gegen provisionierte Schlüssel bleibt Server/Helperaufgabe; +die Anzeige eines Key-ID-Feldes behauptet keine eigene UI-Vertrauenskette. +Ein getrenntes Katalogformular nimmt den signierten Envelope und genau zwei +Dateiauswahlen entgegen. Der Browser übergibt die Filebodies direkt, ohne im +Anwendungscode ein vollständiges Binary-ArrayBuffer anzulegen. Der Server +prüft die vollständigen Hashes und Längen. Erst zwei bestätigte Importbelege +führen zur getrennten Veröffentlichung der signierten Metadaten. Fehlgeschlagene +Schritte erzeugen keine automatischen Retries oder Installationsjobs; tatsächliche +Teilimportbelege bleiben im Fehlerzustand sichtbar. Sitzungs-/CSRFdaten bleiben +im normalen Browserkontext, kein Tokenexport für einen separaten Approver. + +Tatsächlich lokal ausgeführt, kein RMM-Server oder -Agent auf dem Notebook: + +- Server `cargo check --locked --offline -p rmm-server` bestanden. +- Server `cargo test --locked --offline -p rmm-server --bin rmm-server`: + **43bestanden,0fehlgeschlagen,5bestehende DB-Fälle ausdrücklich ignoriert**. + Einschließlich vollständigem echten Rustcodec-Plan, exakter per-Versuch- + Artefaktmenge, verweigerten freien lokalen Pins und großem Store mit + Trunkierungs-/Korruptions-/Fremdtenant-/Legacygrößengrenzen. +- Server Clippy für alle Targets mit `-D warnings` und gezielte Formatierung + bestanden. Unveränderter Verifier und alte nativen Runner nicht umgeschrieben. +- Web Typecheck, Vitebuild und **54/54Tests** bestanden, davon fünf neue + gezielte Updateprüfungen mit tatsächlichen Rustcodec-Fixtures. Diese enthalten + ausdrücklich synthetische Signaturen und dürfen niemals publiziert/ausgeführt + oder als Kryptografie-/Releasequalifikation ausgegeben werden. + Der zusätzliche Filetransportfall verweigert falsche Länge und widersprüchliche + Importbelege und prüft direkte Filebodyübergabe an die feste gleiche Origin; + dies ist noch kein Browser-/Netzwerk- oder nativer großer Streamnachweis. +- Frischer isolierter PostgreSQL17.6 ohne Netzwerk/Ports: Migrationen1–15 als + Nicht-Superuser-Migrator ausgeführt; Tenant-RLS, fehlender und nach Commit + zurückgesetzter Kontext, Cross-Tenant-FKs, App-UPDATE-/DELETEverweigerung, + unveränderliche Inhalte auch gegenüber dem Migrator und null neue Jobs, + Outbox, Grants/Autorisierungen bestanden. Eigener Testcontainer entfernt. + Fall `postgres-19cdb94c…`, ResultatSHA256 + `bbb649a184e59a645f638d39f2e3182df6aef39353bff0bf43712f03297c99ce`. + Dieser SQLnachweis ersetzt die fünf ausgelassenen anderen DB-Fälle nicht. + +Anfänglicher Web-Typecheck erreichte wegen fehlendem `tsc` noch keine Prüfung; +nach `npm ci --offline --ignore-scripts` liefen die genannten Prüfungen wirklich. +Ein zwischenzeitlicher `--locked`-Lauf verweigerte vor Compile die noch nicht +abgestimmte Workspace-Lockfortschreibung; erst der koordinierte Lockstand wurde +geprüft. Keine Paketversion wurde für diese Ergänzung gezielt hochgezogen. + +Der unabhängige Review des Server-/WebUI-Abschnitts fand keine kritischen Blocker +an Binding, Autorisierung, Genehmigungsgrenze, RLS oder Store. Die dabei benannten +engen Ergänzungen betreffen die ausdrückliche Uploadfrist und die eigene passive +Updaterquelle; Gesamtintegration und Zielabnahme bleiben davon getrennt. +Nach diesen beiden Änderungen wurden Servercheck und Clippy für alle Servertargets +mit unverändertem Lock/offline und `-D warnings` erneut tatsächlich bestanden; +`git diff --check` war sauber. Für diese erste Ergänzung blieb die WebUI +unverändert und wurde nicht erneut gebaut oder getestet. Ein180s-Netzwerklauf +wurde für diese kleine Quellenergänzung nicht +ausgeführt; die vier ausdrücklichen Deadlineprüfungen sind Quellencodebefund, +kein behaupteter nativer Last-/Zeitnachweis. + +Beim folgenden separaten Healthkey-Vertragsnachtrag wurden die drei Codec-Fixtures +erneut direkt aus dem erweiterten Rustbeispiel erzeugt. Die WebUI bekam dafür die +strikte kanonische Feldfolge und verlangt beide Healthbindungen. Tatsächlich +erneut bestanden: Web-Typecheck, Vitebuild, die fünf relevanten Update-Webtests +einschließlich Anzeige beider Healthfelder sowie Server-Clippy aller Targets mit +`-D warnings`, unverändertem Lock und offline und die beiden gezielten +`agent_updates::tests` mit den neu erzeugten Rustcodecbytes. Die übrigen49Webtests wurden nach +diesem begrenzten Nachtrag nicht erneut ausgeführt; der frühere54/54-Lauf bleibt +als früherer Nachweis ausgewiesen. Keine native Health-/Applyprüfung daraus abgeleitet. + +**Noch offen:** Vollständiger aktueller +Linuxruntime-/Handoff-/Health-/Rollbackanschluss, echte signierte Releaseveröffentlichung, +qualifizierter Updaterbootstrap und Linux-first-VM-/WebUI-Applyabnahme; danach +Windows. Produktionsadapter, Dauerbetrieb und Kapazität sind nicht abgenommen. +Alle Zielaktionen und Genehmigungen bleiben ausschließlich beim Hauptagenten. diff --git a/docs/agent-updater-worker.md b/docs/agent-updater-worker.md new file mode 100644 index 0000000..5a00abb --- /dev/null +++ b/docs/agent-updater-worker.md @@ -0,0 +1,111 @@ +# Linux-Worker: konkreter Zwischenstand + +2026-11-14, Spezifikation1.21. `crates/updater-worker` ergänzt die eingefrorenen +Linux-OS-Primitiven; es ist noch kein ausgelieferter Updaterdienst und keine +Applycapability. Keine Zielaktion oder Genehmigung durch diesen Quellschnitt. + +## Implementiert + +`NativeClock` verwendet eine tatsächlich lesende `adjtimex`-Abfrage samt +Synchronisations-/Fehlergrenze und vergleicht die laufende Wanduhr mit dem +monotonen ursprünglichen Prozessbezug. IPC-/Serverzeit ist kein Ersatz. + +`Original` prüft den erhaltenen Originalrequest einschließlich Originalsignatur +bei dessen unveränderlichem Verbrauchszeitpunkt. Exakte Rekonstruktion des alten +Startzeugen, Plan-/Job-/Versuchs-/Grant-/Authorizationbindung, Generationen, +Codepaar, Fulltransition und ursprünglicher Boot müssen stimmen. Aktuelle Uhr, +Boot und Gesamtfrist bleiben vor späteren Schritten verpflichtend; der alte +Startzeitpunkt ist ausdrücklich kein erneuertes Startfenster. + +`RetainedSet` hält Dateideskriptoren und Parent-/Dateiidentitäten. Für Schlüssel +und Konfiguration werden zusätzliche Metadatenstempel verglichen, ohne private +Schlüsselbytes zu lesen oder auszugeben; mutable Datenbanken dürfen bei gleicher +Dateiidentität fortschreiten. Die konkrete vollständig erforderliche Dateiliste +muss aus separat geprüfter lokaler Provisionierung kommen. Eine Teilmenge ist +kein vollständiger History-/PKI-Erhaltungsnachweis. + +`FullFiles` liest die konkreten geschützten Rawconfig-/Rawpinbytes sowie die +unabhängig provisionierte öffentliche Jobsignierkeydatei. Der vorhandene reine +Fullrenderer muss exakt den vor WebUI-Genehmigung gebundenen Transitionbeleg +ergeben. Nur dessen exakte Config-/Pinbytes werden create-only gestaged. + +`StableParticipant` verlangt den tatsächlichen eigenen MainPID des festen +Updaterdiensts mit Prozessgeburt, aktuellem Image, Konto und Unitkomposition. +Die ursprüngliche konkrete Helperinstanz wird ebenso gegen die atomare +Delegation geprüft. `/proc`-/Capabilityfehler werden verweigert; kein UID0-, +Prozessname- oder installierter-Dateipfad-Fallback. Getrennte tatsächliche +General-/Full-/Updater-Dienstkontexte sind noch nativ zu qualifizieren. + +`TrustState` lädt ausschließlich geschützte feste Policy-/Keyring-/Healthpin- +und InstalledRecord-Dateien. Originale rohe Hashes bleiben maßgeblich. Die +initiale Baseline benötigt ihre gesonderte Ed25519-Domänensignatur; aktuelle +Schlüsselwiderrufe/-bereiche und Releaseverifikation werden unabhängig geprüft. +Health-/Release-/Jobkeys werden getrennt geprüft. Die erste Aktivierung bleibt +an den separat signierten Bootstraprecord gebunden. Ein `Updated`-Vorgänger +wird bis zur vollständigen Record-/Health-Historyprüfung ausdrücklich verweigert. +Keine Floorableitung aus einem bloß geparsten Record, kein Releaseprivatkey +auf dem Client. Die getrennte TLS-Keyprovisionierung bleibt ein Bootstrapgate. + +`FileWitnesses` bindet die vier tatsächlich vorhandenen Original-/Stageproofs. +Es liest vor jedem einzelnen Schritt unabhängig Original, Stage, erhaltenes +Backup oder neues Ziel nach. Historisch gebundene Hardlinks werden erhalten. + +`OwnedLedger` öffnet ausschließlich die vorhandene `consumption.sqlite` ohne +CREATE, nachdem ein echter Linux-OS-Guard alle installierten Reader gestoppt +bestätigt hat. Derselbe Ledger-/Lockinode, Originalstart, vollständiger +Handoffhead und null weitere offene Verbräuche bleiben Pflicht. Der konkrete +Coreguard verifiziert tatsächliche Prozesse, Dateien und Statezeugnisse vor +append-only Handoff-CAS und nativen Effectintents im selben Ledger. + +`LedgerFence` verwendet die konkreten Core-APIs `claim_native_effect` und +`observe_native_effect`. Pro Datei bleibt genau ein Kernel-ReplaceIntent; +SavePredecessor und PublishReplacement erhalten getrennte dauerhafte native +Intents und Nachlese. Ein fehlgeschlagener/mehrdeutiger Schritt vergiftet den +laufenden Fence; keine Resume-/Retrykonstruktion aus einem Teilintent. + +## Offen und standardmäßig verweigert + +Vollständige Engine/Daemonhülle und originale aktivierungsgebundene Stageaufnahme, +Full-Control-Bridge vor Stop, drei Stopbeobachtungen vor AllStopped, atomare +Rückgabe-/Startreservation, tatsächliche Guardabgabe vor einmaligen Starts, +neuer Full-Observer und tatsächlicher Health-/Outcomeanschluss sind noch offen. +Floor-/InstalledRecordpublikation braucht zusätzlich die geschlossenen +originalen nativen Intents nach Health und erhaltende Record-CAS. Folgeupdates +brauchen vollständige geschützte Record-/Health-Historyverifikation. + +Der eingefrorene Vorwärtskernel hat noch keinen qualifizierten Rollbackübergang. +`RestorePredecessor` bleibt deshalb auch bei vorab gebundener Recoveryoption +verweigert; Fehler/Unknown erteilen keinen impliziten Rollback oder Neustart. +Das ist eine offene Apply-/Produktanforderung, kein abgeschlossener Updater. + +## Tatsächliche lokale Prüfung + +Offlinecontainer aus bestehendem Image +`sha256:9a76ad3744ebfdddae96ca10001ce8291c1b332fb54c8df5eea0e8e999ac6fc6`. +Der konkrete Ledger-/Native-Fenceanschluss hat +`cargo check --locked --offline -p rmm-updater-worker --all-targets` +tatsächlich bestanden. Der vollständige aktuelle Checkpoint einschließlich +TrustState bestand danach Clippy mit `-D warnings` für alle Crate-Targets. +Ein Box-Typfehler und zwei unnötige `as_ref`-Aufrufe wurden +korrigiert, ohne Typ- oder Lintunterdrückung. + +Der unabhängige Rootreview fand danach einen konkreten historischen +Baselineblocker: `active_release=None` bei `floor=baseline_sequence` +verweigert im unveränderten Frozenverifier jede legitime Baseline. Die tatsächliche +historische Prüfung bindet jetzt die exakte aktive Baseline-Sequenz und deren +Manifesthash; der Floor bleibt unverändert und Kandidaten bleiben aktuell. +Der gezielte reale Ed25519-Gegenbeleg benutzt einen kanonischen separat +baseline-signierten InstalledRecord und echte Release-Signaturen. Die private +Rückmutation auf den alten `None`-Kontext scheiterte erwartungsgemäß genau an der +Baselineprüfung (Exit101); derselbe Release-Test mit Korrektur bestand **1/1**. +Neuer aktueller Kandidat oberhalb des Floors besteht, gleiche/niedrigere Sequenz +mit anderen Bytes, abgelaufenes Angebot und widerrufener Baselinekey werden +verweigert. Release-Test, Clippy `-D warnings` und Formatcheck bestanden aus +derselben privaten Quellkopie. Kein Frozenverifier wurde dafür verändert. +Privater Nachweis: +`devstate/agent-updater-worker/baseline-fix-1fcc8bb2-57fe-4425-b166-f416dc1b4703/`. + +Keine Engine gestartet, kein systemd-Aufruf, keine echte Zieldatei geändert, +keine VM/SSH-/Job-/WebUI-Aktion und kein nativer Worker-/Applynachweis. +Der native Linux-OS5-Nachweis qualifiziert weiterhin dessen eigene eingefrorene +Primitiven und ersetzt keine Worker-/Dienstkontextabnahme. diff --git a/docs/development.md b/docs/development.md index 87933e9..1b10fb3 100644 --- a/docs/development.md +++ b/docs/development.md @@ -1,6 +1,6 @@ # Linux-first-Entwicklung und reale VM-Abnahme -Stand: 2026-11-14 · Spezifikation 1.20. Das begrenzte Linux-MVP ist inzwischen +Stand: 2026-11-14 · Spezifikation 1.21. Das begrenzte Linux-MVP ist inzwischen dokumentiert abgenommen; aktuelle Nachweise stehen in [handover.md](handover.md). Die getrennte Windows-SYSTEM-Grenze ist in Spezifikation0.1 und [windows-system-policy.md](windows-system-policy.md) präzisiert; Quellen-/Build- @@ -17,6 +17,25 @@ Deploymentnachweise: [server-deployment.md](server-deployment.md). Die folgenden PC-Server-/Reverse-Tunnel-Abläufe und Nachweise sind historisch. TLS/mTLS, Credentialschutz, Linux-first und WebUI-Plangenehmigung gelten weiter. +## Enger paralleler Agentupdater (Version1.21) + +Der User hat signiertes Agent-Selbstupdate parallel vorgezogen. Es bleibt ein +festes Release-/Vorgänger-/Versuchs-/Planhashpaket mit tatsächlicher WebUI- +Genehmigung; passive Metadaten/Updatezustände sind keine Jobs. Neuer +`agent.update`-Scope liefert eigene tatsächliche Beobachtungszeiten und darf +kein altes Linux-/Windows-Baseinventar frischstempeln. Beide Binaries werden +vollständig vor Handoff gestaged; anschließender read-only Inflight-/Health- +Kontrollpfad eröffnet keine Admission oder neue Startlease. + +Vor Zielarbeit: kompatible erhaltende Bootstrap-/Baselineprovisionierung, +unabhängiger Source-Review, Linux-first-Units/OSports und danach ein konkreter +WebUI-genehmigter Apply mit State-/PKI-/Historyerhaltung und erlaubtem Code- +Rollback. Root koordiniert alle Zielaktionen. Notebook bleibt nur Entwicklung. +Aktuelle Teilnachweise und fehlende Runtimegates: +[Handoff](agent-updater-handoff.md), [Linuxport](agent-updater-linux-port.md), +[Server/UI](agent-updater-server-console.md). Keine Applycapability aus einem +Build oder Katalogeintrag ableiten; fehlende Qualifikation bleibt deny. + ## Vorrang: genehmigte Batch-Skriptkonsole (Version1.20) Der User priorisiert vollständige Shell-/PowerShell-Skripte über MCP/UI mit diff --git a/docs/project-decisions.md b/docs/project-decisions.md index d137cda..96aea52 100644 --- a/docs/project-decisions.md +++ b/docs/project-decisions.md @@ -1,6 +1,50 @@ # Verbindliche Projektentscheidungen -Stand: **2026-11-14**, Spezifikation **1.20** (`Rust_RMM_Implementierungsspezifikation.md`). Die ausdrücklichen normativen Entscheidungen in Kapitel 0 haben Vorrang vor früheren Architekturannahmen. Version 1.6 ersetzt die lokale Servertopologie durch den dedizierten Internetserver; Version 1.7 präzisiert das Notebook als reinen Entwicklungsrechner; Version 1.8 erlaubt vorgezogene parallele Windows-Entwicklung. +Stand: **2026-11-14**, Spezifikation **1.21** (`Rust_RMM_Implementierungsspezifikation.md`). Die ausdrücklichen normativen Entscheidungen in Kapitel 0 haben Vorrang vor früheren Architekturannahmen. Version 1.6 ersetzt die lokale Servertopologie durch den dedizierten Internetserver; Version 1.7 präzisiert das Notebook als reinen Entwicklungsrechner; Version 1.8 erlaubt vorgezogene parallele Windows-Entwicklung. + +## Präzisierung des engen Updatervertrags (Version1.21) + +Healthsignatur und vor Genehmigung gebundener lokaler öffentlicher Healthpin +verwenden einen separat provisionierten Schlüssel; kein Jobsignerfallback. +Auf Linux autorisiert und prüft Full den Updateowner. General bleibt während +des Inflightfalls geschlossen, ohne aus Nichtzuständigkeit Unknown zu erzeugen. +Keine Capabilitylockerung umgeht die tatsächliche Prozessimageprüfung. +Native Dateiteilintents und Stop-/Startbeobachtungen gehören append-only an den +Originalhandoff im selben Ledger. ReturnIntent und feste Startreservation +committen vor Lockabgabe; keine Zeile erlaubt späteren Workerresume. +Details und offene Runtimegrenzen stehen in Spezifikation0.1 und +[agent-updater-handoff.md](agent-updater-handoff.md). + +## Agent-Selbstupdate parallel, eng gebunden (Version1.21) + +Auf ausdrücklichen Userwunsch wird ausschließlich der signierte Agentupdater +parallel ausM7 vorgezogen. `update_agent` bleibt fester, tatsächlich WebUI- +genehmigter Job mit `updates:apply` plus Root-/SYSTEM-Recht für beide Akteure, +separatem immutable Releasekatalog und zwei gebundenen Rohbinaries. Altes +Paketlimit bleibt bestehen; Update-only-Streaming ist keine allgemeine +Installer-/Dateiupload-/Rootskriptfreigabe. Passive Beobachtung `agent.update` +alle60s ist von Baseinventar und täglichem Releasecheck getrennt; fehlende +Provisionierung/Qualifikation erzeugt `not_configured`, niemals Applybereitschaft. + +Der verbindliche Handoff-/Owner-/Inflight-/Healthvertrag steht in Kapitel0.1. +Atomarer Originalverbrauch+Start+Handoff+Delegation+Stopintent im erhaltenen +Helperledger, echter gemeinsamer Lock nur während Helperstop, Rückgabe vor +neuem Helperstart und exakter eigener Inflightabgleich bei Ready=false sind +Pflicht. Kein zusätzlicher ungebundener Server-Journalslot oder Unknown-Healing. +Die nur für diese Aktion signierte `agent_update_plan_id` erhält alte Grantbytes +bei allen anderen Aktionen. Fullpins werden eng aus konkreten geschützten +Rawbytes gerendert; zentrale Fullrechte werden nicht automatisch migriert. + +Erste Baseline und erlaubtes Rollback müssen bereits die neue Update-/Handoff- +Historie dekodieren können. Das aktuelle1.20-Codepaar ist daher kein späteres +Rollbackziel. Erhaltender kompatibler Bootstrap, separat release-signierter +InstalledRecord/Floor und tatsächliche Linux-first-Qualifikation sind vor dem +ersten Apply erforderlich. Keine Daten-/PKI-/Generation-/Journalrücksetzung. + +Quelle ist kein Applynachweis: isolierter Verifier/Handoffkernel und lokale +OS-/SQL-/UIteile sind getrennt dokumentiert. Unabhängige Reviews und tatsächliche +Messwerte stehen in den verlinkten Updaterberichten; Workerinstallation, +genehmigter realer Codewechsel und Windowsnachweis bleiben eigene Gates. ## Skriptkonsole und vollständige Hostwartung (Version1.20) diff --git a/migrations/0015_agent_update_catalog.sql b/migrations/0015_agent_update_catalog.sql new file mode 100644 index 0000000..ee95a8d --- /dev/null +++ b/migrations/0015_agent_update_catalog.sql @@ -0,0 +1,49 @@ +-- Separate large update objects. Legacy APT/MSI object limits are unchanged. +CREATE TABLE agent_update_artifacts ( + tenant_id uuid NOT NULL REFERENCES tenants, + artifact_id uuid NOT NULL, + sha256 text NOT NULL CHECK(sha256 ~ '^[0-9a-f]{64}$'), + size_bytes bigint NOT NULL CHECK(size_bytes BETWEEN 1 AND 268435456), + created_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY(tenant_id,artifact_id), + UNIQUE(tenant_id,artifact_id,sha256,size_bytes) +); +CREATE TABLE agent_update_releases ( + tenant_id uuid NOT NULL REFERENCES tenants, + release_id uuid NOT NULL, + platform text NOT NULL CHECK(platform IN ('x86_64-unknown-linux-gnu','x86_64-pc-windows-msvc')), + release_sequence bigint NOT NULL CHECK(release_sequence>0), + manifest_sha256 text NOT NULL CHECK(manifest_sha256 ~ '^[0-9a-f]{64}$'), + envelope_sha256 text NOT NULL CHECK(envelope_sha256 ~ '^[0-9a-f]{64}$'), + envelope bytea NOT NULL CHECK(octet_length(envelope) BETWEEN 1 AND 32768), + agent_artifact_id uuid NOT NULL, + agent_sha256 text NOT NULL, + agent_bytes bigint NOT NULL, + helper_artifact_id uuid NOT NULL, + helper_sha256 text NOT NULL, + helper_bytes bigint NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY(tenant_id,release_id), + UNIQUE(tenant_id,platform,release_sequence), + UNIQUE(tenant_id,manifest_sha256), + CHECK(agent_artifact_id<>helper_artifact_id), + FOREIGN KEY(tenant_id,agent_artifact_id,agent_sha256,agent_bytes) + REFERENCES agent_update_artifacts(tenant_id,artifact_id,sha256,size_bytes), + FOREIGN KEY(tenant_id,helper_artifact_id,helper_sha256,helper_bytes) + REFERENCES agent_update_artifacts(tenant_id,artifact_id,sha256,size_bytes) +); +ALTER TABLE agent_update_artifacts ENABLE ROW LEVEL SECURITY; +ALTER TABLE agent_update_artifacts FORCE ROW LEVEL SECURITY; +CREATE POLICY tenant_scope ON agent_update_artifacts + USING (tenant_id::text=current_setting('app.tenant_id',true)) + WITH CHECK (tenant_id::text=current_setting('app.tenant_id',true)); +ALTER TABLE agent_update_releases ENABLE ROW LEVEL SECURITY; +ALTER TABLE agent_update_releases FORCE ROW LEVEL SECURITY; +CREATE POLICY tenant_scope ON agent_update_releases + USING (tenant_id::text=current_setting('app.tenant_id',true)) + WITH CHECK (tenant_id::text=current_setting('app.tenant_id',true)); +GRANT SELECT,INSERT ON agent_update_artifacts,agent_update_releases TO rmm_app; +CREATE TRIGGER immutable_content BEFORE UPDATE OR DELETE ON agent_update_artifacts + FOR EACH ROW EXECUTE FUNCTION immutable_plan(); +CREATE TRIGGER immutable_content BEFORE UPDATE OR DELETE ON agent_update_releases + FOR EACH ROW EXECUTE FUNCTION immutable_plan(); diff --git a/proto/agent.proto b/proto/agent.proto index 9e87db8..411c867 100644 --- a/proto/agent.proto +++ b/proto/agent.proto @@ -47,7 +47,7 @@ message Ack { string message_id = 1; } message MessageBatch { uint32 protocol_major=1; repeated Envelope messages=2; } message PollRequest { Envelope envelope=1; uint32 wait_seconds=2; } message SyncRequest { string request_id=1; string journal_id=2; uint64 checkpoint=3; string previous_decision_id=4; uint64 assignment_version=5; repeated SyncAttempt attempts=6; repeated string durable_message_ids=7; bool journal_complete=8; string helper_journal_id=9; uint64 helper_checkpoint=10; string helper_previous_decision_id=11; string previous_request_id=12; } -message SyncAttempt { string job_id=1; string attempt_id=2; string job_payload_hash=3; string grant_id=4; string consumption=5; string state=6; uint64 revision=7; string original_boot_id=8; JobResult result=9; string result_message_id=10; string outcome_sha256=11; bytes outcome_bytes=12; Envelope result_envelope=13; } +message SyncAttempt { string job_id=1; string attempt_id=2; string job_payload_hash=3; string grant_id=4; string consumption=5; string state=6; uint64 revision=7; string original_boot_id=8; JobResult result=9; string result_message_id=10; string outcome_sha256=11; bytes outcome_bytes=12; Envelope result_envelope=13; bytes update_handoff_bytes=14; } message SyncResponse { bytes decision_bytes=1; bytes signature=2; } message JobOffer { string job_id=1; string attempt_id=2; string authorization_id=3; string plan_hash=4; string job_payload_hash=5; bytes payload_bytes=6; } message JobAccepted { string job_id=1; string attempt_id=2; string job_payload_hash=3; string journal_proof=4; } diff --git a/tests/agent_update/codec-golden.json b/tests/agent_update/codec-golden.json new file mode 100644 index 0000000..ef55c62 --- /dev/null +++ b/tests/agent_update/codec-golden.json @@ -0,0 +1,13652 @@ +{ + "linux_full": { + "approval_state": "pending_approval", + "authorization_status": "required", + "excluded_targets": [], + "expires_at": "2030-01-01T12:10:00Z", + "fixture_kind": "codec_only_synthetic_signature_never_publish_or_execute", + "jobs": [ + { + "agent_id": "11111111-1111-4111-8111-000000000003", + "asset_id": "11111111-1111-4111-8111-000000000002", + "attempt_id": "11111111-1111-4111-8111-000000000005", + "job_id": "11111111-1111-4111-8111-000000000004", + "job_payload_hash": "903d5279297c7427704a461ce77f42ace50ed8f5597ed95d8509169647725217", + "payload": { + "action": { + "action": "update_agent", + "update": { + "health_profile": "mtls_inventory_sync_v1", + "health_timeout_seconds": 180, + "manifest_sha256": "4e9400ee6cb362431781735fa7752a8947c5911f6309e29835e8b4d105f80576", + "no_reboot": true, + "peer_pin_transition": { + "full": { + "effective_signing_key_id": "1717171717171717171717171717171717171717171717171717171717171717", + "new_config_sha256": "1212121212121212121212121212121212121212121212121212121212121212", + "new_helper_sha256": "0404040404040404040404040404040404040404040404040404040404040404", + "new_pin_sha256": "1414141414141414141414141414141414141414141414141414141414141414", + "new_policy_sha256": "1616161616161616161616161616161616161616161616161616161616161616", + "old_config_sha256": "1111111111111111111111111111111111111111111111111111111111111111", + "old_helper_sha256": "0303030303030303030303030303030303030303030303030303030303030303", + "old_pin_sha256": "1313131313131313131313131313131313131313131313131313131313131313", + "old_policy_sha256": "1515151515151515151515151515151515151515151515151515151515151515", + "schema_version": 1 + }, + "general_pin_sha256": "1010101010101010101010101010101010101010101010101010101010101010", + "profile": "linux_general_full_v1" + }, + "predecessor": { + "agent_sha256": "0101010101010101010101010101010101010101010101010101010101010101", + "helper_sha256": "0303030303030303030303030303030303030303030303030303030303030303", + "installed_record_sha256": "2121212121212121212121212121212121212121212121212121212121212121", + "manifest_sha256": "2020202020202020202020202020202020202020202020202020202020202020", + "release_id": "11111111-1111-4111-8111-000000000009", + "release_sequence": 1 + }, + "profile": "fixed_code_pair_v1", + "recovery": "restore_exact_predecessor_once", + "release_envelope": { + "key_id": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "payload_bytes": "eyJzY2hlbWFfdmVyc2lvbiI6MSwicmVsZWFzZV9pZCI6IjExMTExMTExLTExMTEtNDExMS04MTExLTAwMDAwMDAwMDAwYSIsInJlbGVhc2Vfc2VxdWVuY2UiOjIsInZlcnNpb24iOiIwLjEuMS10ZXN0IiwicGxhdGZvcm0iOiJ4ODZfNjQtdW5rbm93bi1saW51eC1nbnUiLCJwdWJsaXNoZWRfYXQiOjE3OTAwMDAwMDAsImV4cGlyZXNfYXQiOjIwMDAwMDAwMDAsInByb3RvY29sX21ham9yIjoxLCJzdGF0ZV9zY2hlbWEiOjEsIm1pbmltdW1fdXBkYXRlcl92ZXJzaW9uIjoxLCJhcnRpZmFjdHMiOlt7InJvbGUiOiJhZ2VudCIsImFydGlmYWN0X2lkIjoiMTExMTExMTEtMTExMS00MTExLTgxMTEtMDAwMDAwMDAwMDBiIiwic2hhMjU2IjoiMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMiIsImJ5dGVzIjozMDAwMDA3fSx7InJvbGUiOiJoZWxwZXIiLCJhcnRpZmFjdF9pZCI6IjExMTExMTExLTExMTEtNDExMS04MTExLTAwMDAwMDAwMDAwYyIsInNoYTI1NiI6IjA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQiLCJieXRlcyI6MjAwMDAwOX1dfQ", + "schema_version": 1, + "signature": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ" + }, + "release_envelope_sha256": "267565acb1e47a9bd199ed72d259f1a34ecf64686339d26eaff218ecf4bc755b", + "schema_version": 1, + "updater": { + "binary_sha256": "3030303030303030303030303030303030303030303030303030303030303030", + "health_key_pin_sha256": "3434343434343434343434343434343434343434343434343434343434343434", + "health_public_key_hex": "3333333333333333333333333333333333333333333333333333333333333333", + "keyring_generation": 1, + "keyring_sha256": "3232323232323232323232323232323232323232323232323232323232323232", + "policy_sha256": "3131313131313131313131313131313131313131313131313131313131313131" + } + } + }, + "agent_id": "11111111-1111-4111-8111-000000000003", + "asset_id": "11111111-1111-4111-8111-000000000002", + "assignment_version": 1, + "attempt_id": "11111111-1111-4111-8111-000000000005", + "enrollment_generation": 1, + "execution_identity": "root", + "job_id": "11111111-1111-4111-8111-000000000004", + "max_output_bytes": 65536, + "max_runtime_seconds": 600, + "not_before": "2030-01-01T12:00:00Z", + "schema_version": 1, + "start_before": "2030-01-01T12:10:00Z", + "tenant_id": "11111111-1111-4111-8111-000000000001" + }, + "script_sha256": null + } + ], + "payload": { + "artifact_references": [ + { + "artifact": { + "artifact_id": "11111111-1111-4111-8111-00000000000b", + "sha256": "0202020202020202020202020202020202020202020202020202020202020202", + "size_bytes": 3000007 + }, + "attempt_id": "11111111-1111-4111-8111-000000000005", + "job_id": "11111111-1111-4111-8111-000000000004" + }, + { + "artifact": { + "artifact_id": "11111111-1111-4111-8111-00000000000c", + "sha256": "0404040404040404040404040404040404040404040404040404040404040404", + "size_bytes": 2000009 + }, + "attempt_id": "11111111-1111-4111-8111-000000000005", + "job_id": "11111111-1111-4111-8111-000000000004" + } + ], + "halt_after_failures": 1, + "jobs": [ + { + "job_payload_hash": "903d5279297c7427704a461ce77f42ace50ed8f5597ed95d8509169647725217", + "payload": { + "action": { + "action": "update_agent", + "update": { + "health_profile": "mtls_inventory_sync_v1", + "health_timeout_seconds": 180, + "manifest_sha256": "4e9400ee6cb362431781735fa7752a8947c5911f6309e29835e8b4d105f80576", + "no_reboot": true, + "peer_pin_transition": { + "full": { + "effective_signing_key_id": "1717171717171717171717171717171717171717171717171717171717171717", + "new_config_sha256": "1212121212121212121212121212121212121212121212121212121212121212", + "new_helper_sha256": "0404040404040404040404040404040404040404040404040404040404040404", + "new_pin_sha256": "1414141414141414141414141414141414141414141414141414141414141414", + "new_policy_sha256": "1616161616161616161616161616161616161616161616161616161616161616", + "old_config_sha256": "1111111111111111111111111111111111111111111111111111111111111111", + "old_helper_sha256": "0303030303030303030303030303030303030303030303030303030303030303", + "old_pin_sha256": "1313131313131313131313131313131313131313131313131313131313131313", + "old_policy_sha256": "1515151515151515151515151515151515151515151515151515151515151515", + "schema_version": 1 + }, + "general_pin_sha256": "1010101010101010101010101010101010101010101010101010101010101010", + "profile": "linux_general_full_v1" + }, + "predecessor": { + "agent_sha256": "0101010101010101010101010101010101010101010101010101010101010101", + "helper_sha256": "0303030303030303030303030303030303030303030303030303030303030303", + "installed_record_sha256": "2121212121212121212121212121212121212121212121212121212121212121", + "manifest_sha256": "2020202020202020202020202020202020202020202020202020202020202020", + "release_id": "11111111-1111-4111-8111-000000000009", + "release_sequence": 1 + }, + "profile": "fixed_code_pair_v1", + "recovery": "restore_exact_predecessor_once", + "release_envelope": { + "key_id": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "payload_bytes": "eyJzY2hlbWFfdmVyc2lvbiI6MSwicmVsZWFzZV9pZCI6IjExMTExMTExLTExMTEtNDExMS04MTExLTAwMDAwMDAwMDAwYSIsInJlbGVhc2Vfc2VxdWVuY2UiOjIsInZlcnNpb24iOiIwLjEuMS10ZXN0IiwicGxhdGZvcm0iOiJ4ODZfNjQtdW5rbm93bi1saW51eC1nbnUiLCJwdWJsaXNoZWRfYXQiOjE3OTAwMDAwMDAsImV4cGlyZXNfYXQiOjIwMDAwMDAwMDAsInByb3RvY29sX21ham9yIjoxLCJzdGF0ZV9zY2hlbWEiOjEsIm1pbmltdW1fdXBkYXRlcl92ZXJzaW9uIjoxLCJhcnRpZmFjdHMiOlt7InJvbGUiOiJhZ2VudCIsImFydGlmYWN0X2lkIjoiMTExMTExMTEtMTExMS00MTExLTgxMTEtMDAwMDAwMDAwMDBiIiwic2hhMjU2IjoiMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMiIsImJ5dGVzIjozMDAwMDA3fSx7InJvbGUiOiJoZWxwZXIiLCJhcnRpZmFjdF9pZCI6IjExMTExMTExLTExMTEtNDExMS04MTExLTAwMDAwMDAwMDAwYyIsInNoYTI1NiI6IjA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQiLCJieXRlcyI6MjAwMDAwOX1dfQ", + "schema_version": 1, + "signature": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ" + }, + "release_envelope_sha256": "267565acb1e47a9bd199ed72d259f1a34ecf64686339d26eaff218ecf4bc755b", + "schema_version": 1, + "updater": { + "binary_sha256": "3030303030303030303030303030303030303030303030303030303030303030", + "health_key_pin_sha256": "3434343434343434343434343434343434343434343434343434343434343434", + "health_public_key_hex": "3333333333333333333333333333333333333333333333333333333333333333", + "keyring_generation": 1, + "keyring_sha256": "3232323232323232323232323232323232323232323232323232323232323232", + "policy_sha256": "3131313131313131313131313131313131313131313131313131313131313131" + } + } + }, + "agent_id": "11111111-1111-4111-8111-000000000003", + "asset_id": "11111111-1111-4111-8111-000000000002", + "assignment_version": 1, + "attempt_id": "11111111-1111-4111-8111-000000000005", + "enrollment_generation": 1, + "execution_identity": "root", + "job_id": "11111111-1111-4111-8111-000000000004", + "max_output_bytes": 65536, + "max_runtime_seconds": 600, + "not_before": "2030-01-01T12:00:00Z", + "schema_version": 1, + "start_before": "2030-01-01T12:10:00Z", + "tenant_id": "11111111-1111-4111-8111-000000000001" + }, + "script_sha256": null + } + ], + "max_parallel": 1, + "plan_id": "11111111-1111-4111-8111-000000000006", + "principal": "codec-fixture-only", + "reason": "Nur Codec: vollständiges Codepaar – keine Releasefreigabe", + "schema_version": 1, + "tenant_id": "11111111-1111-4111-8111-000000000001" + }, + "plan_hash": "54aeec173c9a995f9ba22b3092616a1beff7f758d0d173b45184386a206ff75a", + "plan_id": "11111111-1111-4111-8111-000000000006", + "plan_payload": { + "artifact_references": [ + { + "artifact": { + "artifact_id": "11111111-1111-4111-8111-00000000000b", + "sha256": "0202020202020202020202020202020202020202020202020202020202020202", + "size_bytes": 3000007 + }, + "attempt_id": "11111111-1111-4111-8111-000000000005", + "job_id": "11111111-1111-4111-8111-000000000004" + }, + { + "artifact": { + "artifact_id": "11111111-1111-4111-8111-00000000000c", + "sha256": "0404040404040404040404040404040404040404040404040404040404040404", + "size_bytes": 2000009 + }, + "attempt_id": "11111111-1111-4111-8111-000000000005", + "job_id": "11111111-1111-4111-8111-000000000004" + } + ], + "halt_after_failures": 1, + "jobs": [ + { + "job_payload_hash": "903d5279297c7427704a461ce77f42ace50ed8f5597ed95d8509169647725217", + "payload": { + "action": { + "action": "update_agent", + "update": { + "health_profile": "mtls_inventory_sync_v1", + "health_timeout_seconds": 180, + "manifest_sha256": "4e9400ee6cb362431781735fa7752a8947c5911f6309e29835e8b4d105f80576", + "no_reboot": true, + "peer_pin_transition": { + "full": { + "effective_signing_key_id": "1717171717171717171717171717171717171717171717171717171717171717", + "new_config_sha256": "1212121212121212121212121212121212121212121212121212121212121212", + "new_helper_sha256": "0404040404040404040404040404040404040404040404040404040404040404", + "new_pin_sha256": "1414141414141414141414141414141414141414141414141414141414141414", + "new_policy_sha256": "1616161616161616161616161616161616161616161616161616161616161616", + "old_config_sha256": "1111111111111111111111111111111111111111111111111111111111111111", + "old_helper_sha256": "0303030303030303030303030303030303030303030303030303030303030303", + "old_pin_sha256": "1313131313131313131313131313131313131313131313131313131313131313", + "old_policy_sha256": "1515151515151515151515151515151515151515151515151515151515151515", + "schema_version": 1 + }, + "general_pin_sha256": "1010101010101010101010101010101010101010101010101010101010101010", + "profile": "linux_general_full_v1" + }, + "predecessor": { + "agent_sha256": "0101010101010101010101010101010101010101010101010101010101010101", + "helper_sha256": "0303030303030303030303030303030303030303030303030303030303030303", + "installed_record_sha256": "2121212121212121212121212121212121212121212121212121212121212121", + "manifest_sha256": "2020202020202020202020202020202020202020202020202020202020202020", + "release_id": "11111111-1111-4111-8111-000000000009", + "release_sequence": 1 + }, + "profile": "fixed_code_pair_v1", + "recovery": "restore_exact_predecessor_once", + "release_envelope": { + "key_id": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "payload_bytes": "eyJzY2hlbWFfdmVyc2lvbiI6MSwicmVsZWFzZV9pZCI6IjExMTExMTExLTExMTEtNDExMS04MTExLTAwMDAwMDAwMDAwYSIsInJlbGVhc2Vfc2VxdWVuY2UiOjIsInZlcnNpb24iOiIwLjEuMS10ZXN0IiwicGxhdGZvcm0iOiJ4ODZfNjQtdW5rbm93bi1saW51eC1nbnUiLCJwdWJsaXNoZWRfYXQiOjE3OTAwMDAwMDAsImV4cGlyZXNfYXQiOjIwMDAwMDAwMDAsInByb3RvY29sX21ham9yIjoxLCJzdGF0ZV9zY2hlbWEiOjEsIm1pbmltdW1fdXBkYXRlcl92ZXJzaW9uIjoxLCJhcnRpZmFjdHMiOlt7InJvbGUiOiJhZ2VudCIsImFydGlmYWN0X2lkIjoiMTExMTExMTEtMTExMS00MTExLTgxMTEtMDAwMDAwMDAwMDBiIiwic2hhMjU2IjoiMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMiIsImJ5dGVzIjozMDAwMDA3fSx7InJvbGUiOiJoZWxwZXIiLCJhcnRpZmFjdF9pZCI6IjExMTExMTExLTExMTEtNDExMS04MTExLTAwMDAwMDAwMDAwYyIsInNoYTI1NiI6IjA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQiLCJieXRlcyI6MjAwMDAwOX1dfQ", + "schema_version": 1, + "signature": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ" + }, + "release_envelope_sha256": "267565acb1e47a9bd199ed72d259f1a34ecf64686339d26eaff218ecf4bc755b", + "schema_version": 1, + "updater": { + "binary_sha256": "3030303030303030303030303030303030303030303030303030303030303030", + "health_key_pin_sha256": "3434343434343434343434343434343434343434343434343434343434343434", + "health_public_key_hex": "3333333333333333333333333333333333333333333333333333333333333333", + "keyring_generation": 1, + "keyring_sha256": "3232323232323232323232323232323232323232323232323232323232323232", + "policy_sha256": "3131313131313131313131313131313131313131313131313131313131313131" + } + } + }, + "agent_id": "11111111-1111-4111-8111-000000000003", + "asset_id": "11111111-1111-4111-8111-000000000002", + "assignment_version": 1, + "attempt_id": "11111111-1111-4111-8111-000000000005", + "enrollment_generation": 1, + "execution_identity": "root", + "job_id": "11111111-1111-4111-8111-000000000004", + "max_output_bytes": 65536, + "max_runtime_seconds": 600, + "not_before": "2030-01-01T12:00:00Z", + "schema_version": 1, + "start_before": "2030-01-01T12:10:00Z", + "tenant_id": "11111111-1111-4111-8111-000000000001" + }, + "script_sha256": null + } + ], + "max_parallel": 1, + "plan_id": "11111111-1111-4111-8111-000000000006", + "principal": "codec-fixture-only", + "reason": "Nur Codec: vollständiges Codepaar – keine Releasefreigabe", + "schema_version": 1, + "tenant_id": "11111111-1111-4111-8111-000000000001" + }, + "plan_payload_bytes": [ + 123, + 34, + 115, + 99, + 104, + 101, + 109, + 97, + 95, + 118, + 101, + 114, + 115, + 105, + 111, + 110, + 34, + 58, + 49, + 44, + 34, + 112, + 108, + 97, + 110, + 95, + 105, + 100, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 45, + 49, + 49, + 49, + 49, + 45, + 52, + 49, + 49, + 49, + 45, + 56, + 49, + 49, + 49, + 45, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 54, + 34, + 44, + 34, + 116, + 101, + 110, + 97, + 110, + 116, + 95, + 105, + 100, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 45, + 49, + 49, + 49, + 49, + 45, + 52, + 49, + 49, + 49, + 45, + 56, + 49, + 49, + 49, + 45, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 49, + 34, + 44, + 34, + 112, + 114, + 105, + 110, + 99, + 105, + 112, + 97, + 108, + 34, + 58, + 34, + 99, + 111, + 100, + 101, + 99, + 45, + 102, + 105, + 120, + 116, + 117, + 114, + 101, + 45, + 111, + 110, + 108, + 121, + 34, + 44, + 34, + 114, + 101, + 97, + 115, + 111, + 110, + 34, + 58, + 34, + 78, + 117, + 114, + 32, + 67, + 111, + 100, + 101, + 99, + 58, + 32, + 118, + 111, + 108, + 108, + 115, + 116, + 195, + 164, + 110, + 100, + 105, + 103, + 101, + 115, + 32, + 67, + 111, + 100, + 101, + 112, + 97, + 97, + 114, + 32, + 226, + 128, + 147, + 32, + 107, + 101, + 105, + 110, + 101, + 32, + 82, + 101, + 108, + 101, + 97, + 115, + 101, + 102, + 114, + 101, + 105, + 103, + 97, + 98, + 101, + 34, + 44, + 34, + 106, + 111, + 98, + 115, + 34, + 58, + 91, + 123, + 34, + 112, + 97, + 121, + 108, + 111, + 97, + 100, + 34, + 58, + 123, + 34, + 115, + 99, + 104, + 101, + 109, + 97, + 95, + 118, + 101, + 114, + 115, + 105, + 111, + 110, + 34, + 58, + 49, + 44, + 34, + 116, + 101, + 110, + 97, + 110, + 116, + 95, + 105, + 100, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 45, + 49, + 49, + 49, + 49, + 45, + 52, + 49, + 49, + 49, + 45, + 56, + 49, + 49, + 49, + 45, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 49, + 34, + 44, + 34, + 97, + 115, + 115, + 101, + 116, + 95, + 105, + 100, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 45, + 49, + 49, + 49, + 49, + 45, + 52, + 49, + 49, + 49, + 45, + 56, + 49, + 49, + 49, + 45, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 50, + 34, + 44, + 34, + 97, + 103, + 101, + 110, + 116, + 95, + 105, + 100, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 45, + 49, + 49, + 49, + 49, + 45, + 52, + 49, + 49, + 49, + 45, + 56, + 49, + 49, + 49, + 45, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 51, + 34, + 44, + 34, + 101, + 110, + 114, + 111, + 108, + 108, + 109, + 101, + 110, + 116, + 95, + 103, + 101, + 110, + 101, + 114, + 97, + 116, + 105, + 111, + 110, + 34, + 58, + 49, + 44, + 34, + 97, + 115, + 115, + 105, + 103, + 110, + 109, + 101, + 110, + 116, + 95, + 118, + 101, + 114, + 115, + 105, + 111, + 110, + 34, + 58, + 49, + 44, + 34, + 106, + 111, + 98, + 95, + 105, + 100, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 45, + 49, + 49, + 49, + 49, + 45, + 52, + 49, + 49, + 49, + 45, + 56, + 49, + 49, + 49, + 45, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 52, + 34, + 44, + 34, + 97, + 116, + 116, + 101, + 109, + 112, + 116, + 95, + 105, + 100, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 45, + 49, + 49, + 49, + 49, + 45, + 52, + 49, + 49, + 49, + 45, + 56, + 49, + 49, + 49, + 45, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 53, + 34, + 44, + 34, + 97, + 99, + 116, + 105, + 111, + 110, + 34, + 58, + 123, + 34, + 97, + 99, + 116, + 105, + 111, + 110, + 34, + 58, + 34, + 117, + 112, + 100, + 97, + 116, + 101, + 95, + 97, + 103, + 101, + 110, + 116, + 34, + 44, + 34, + 117, + 112, + 100, + 97, + 116, + 101, + 34, + 58, + 123, + 34, + 115, + 99, + 104, + 101, + 109, + 97, + 95, + 118, + 101, + 114, + 115, + 105, + 111, + 110, + 34, + 58, + 49, + 44, + 34, + 112, + 114, + 111, + 102, + 105, + 108, + 101, + 34, + 58, + 34, + 102, + 105, + 120, + 101, + 100, + 95, + 99, + 111, + 100, + 101, + 95, + 112, + 97, + 105, + 114, + 95, + 118, + 49, + 34, + 44, + 34, + 114, + 101, + 108, + 101, + 97, + 115, + 101, + 95, + 101, + 110, + 118, + 101, + 108, + 111, + 112, + 101, + 34, + 58, + 123, + 34, + 115, + 99, + 104, + 101, + 109, + 97, + 95, + 118, + 101, + 114, + 115, + 105, + 111, + 110, + 34, + 58, + 49, + 44, + 34, + 107, + 101, + 121, + 95, + 105, + 100, + 34, + 58, + 34, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 34, + 44, + 34, + 112, + 97, + 121, + 108, + 111, + 97, + 100, + 95, + 98, + 121, + 116, + 101, + 115, + 34, + 58, + 34, + 101, + 121, + 74, + 122, + 89, + 50, + 104, + 108, + 98, + 87, + 70, + 102, + 100, + 109, + 86, + 121, + 99, + 50, + 108, + 118, + 98, + 105, + 73, + 54, + 77, + 83, + 119, + 105, + 99, + 109, + 86, + 115, + 90, + 87, + 70, + 122, + 90, + 86, + 57, + 112, + 90, + 67, + 73, + 54, + 73, + 106, + 69, + 120, + 77, + 84, + 69, + 120, + 77, + 84, + 69, + 120, + 76, + 84, + 69, + 120, + 77, + 84, + 69, + 116, + 78, + 68, + 69, + 120, + 77, + 83, + 48, + 52, + 77, + 84, + 69, + 120, + 76, + 84, + 65, + 119, + 77, + 68, + 65, + 119, + 77, + 68, + 65, + 119, + 77, + 68, + 65, + 119, + 89, + 83, + 73, + 115, + 73, + 110, + 74, + 108, + 98, + 71, + 86, + 104, + 99, + 50, + 86, + 102, + 99, + 50, + 86, + 120, + 100, + 87, + 86, + 117, + 89, + 50, + 85, + 105, + 79, + 106, + 73, + 115, + 73, + 110, + 90, + 108, + 99, + 110, + 78, + 112, + 98, + 50, + 52, + 105, + 79, + 105, + 73, + 119, + 76, + 106, + 69, + 117, + 77, + 83, + 49, + 48, + 90, + 88, + 78, + 48, + 73, + 105, + 119, + 105, + 99, + 71, + 120, + 104, + 100, + 71, + 90, + 118, + 99, + 109, + 48, + 105, + 79, + 105, + 74, + 52, + 79, + 68, + 90, + 102, + 78, + 106, + 81, + 116, + 100, + 87, + 53, + 114, + 98, + 109, + 57, + 51, + 98, + 105, + 49, + 115, + 97, + 87, + 53, + 49, + 101, + 67, + 49, + 110, + 98, + 110, + 85, + 105, + 76, + 67, + 74, + 119, + 100, + 87, + 74, + 115, + 97, + 88, + 78, + 111, + 90, + 87, + 82, + 102, + 89, + 88, + 81, + 105, + 79, + 106, + 69, + 51, + 79, + 84, + 65, + 119, + 77, + 68, + 65, + 119, + 77, + 68, + 65, + 115, + 73, + 109, + 86, + 52, + 99, + 71, + 108, + 121, + 90, + 88, + 78, + 102, + 89, + 88, + 81, + 105, + 79, + 106, + 73, + 119, + 77, + 68, + 65, + 119, + 77, + 68, + 65, + 119, + 77, + 68, + 65, + 115, + 73, + 110, + 66, + 121, + 98, + 51, + 82, + 118, + 89, + 50, + 57, + 115, + 88, + 50, + 49, + 104, + 97, + 109, + 57, + 121, + 73, + 106, + 111, + 120, + 76, + 67, + 74, + 122, + 100, + 71, + 70, + 48, + 90, + 86, + 57, + 122, + 89, + 50, + 104, + 108, + 98, + 87, + 69, + 105, + 79, + 106, + 69, + 115, + 73, + 109, + 49, + 112, + 98, + 109, + 108, + 116, + 100, + 87, + 49, + 102, + 100, + 88, + 66, + 107, + 89, + 88, + 82, + 108, + 99, + 108, + 57, + 50, + 90, + 88, + 74, + 122, + 97, + 87, + 57, + 117, + 73, + 106, + 111, + 120, + 76, + 67, + 74, + 104, + 99, + 110, + 82, + 112, + 90, + 109, + 70, + 106, + 100, + 72, + 77, + 105, + 79, + 108, + 116, + 55, + 73, + 110, + 74, + 118, + 98, + 71, + 85, + 105, + 79, + 105, + 74, + 104, + 90, + 50, + 86, + 117, + 100, + 67, + 73, + 115, + 73, + 109, + 70, + 121, + 100, + 71, + 108, + 109, + 89, + 87, + 78, + 48, + 88, + 50, + 108, + 107, + 73, + 106, + 111, + 105, + 77, + 84, + 69, + 120, + 77, + 84, + 69, + 120, + 77, + 84, + 69, + 116, + 77, + 84, + 69, + 120, + 77, + 83, + 48, + 48, + 77, + 84, + 69, + 120, + 76, + 84, + 103, + 120, + 77, + 84, + 69, + 116, + 77, + 68, + 65, + 119, + 77, + 68, + 65, + 119, + 77, + 68, + 65, + 119, + 77, + 68, + 66, + 105, + 73, + 105, + 119, + 105, + 99, + 50, + 104, + 104, + 77, + 106, + 85, + 50, + 73, + 106, + 111, + 105, + 77, + 68, + 73, + 119, + 77, + 106, + 65, + 121, + 77, + 68, + 73, + 119, + 77, + 106, + 65, + 121, + 77, + 68, + 73, + 119, + 77, + 106, + 65, + 121, + 77, + 68, + 73, + 119, + 77, + 106, + 65, + 121, + 77, + 68, + 73, + 119, + 77, + 106, + 65, + 121, + 77, + 68, + 73, + 119, + 77, + 106, + 65, + 121, + 77, + 68, + 73, + 119, + 77, + 106, + 65, + 121, + 77, + 68, + 73, + 119, + 77, + 106, + 65, + 121, + 77, + 68, + 73, + 119, + 77, + 106, + 65, + 121, + 77, + 68, + 73, + 119, + 77, + 106, + 65, + 121, + 77, + 68, + 73, + 119, + 77, + 105, + 73, + 115, + 73, + 109, + 74, + 53, + 100, + 71, + 86, + 122, + 73, + 106, + 111, + 122, + 77, + 68, + 65, + 119, + 77, + 68, + 65, + 51, + 102, + 83, + 120, + 55, + 73, + 110, + 74, + 118, + 98, + 71, + 85, + 105, + 79, + 105, + 74, + 111, + 90, + 87, + 120, + 119, + 90, + 88, + 73, + 105, + 76, + 67, + 74, + 104, + 99, + 110, + 82, + 112, + 90, + 109, + 70, + 106, + 100, + 70, + 57, + 112, + 90, + 67, + 73, + 54, + 73, + 106, + 69, + 120, + 77, + 84, + 69, + 120, + 77, + 84, + 69, + 120, + 76, + 84, + 69, + 120, + 77, + 84, + 69, + 116, + 78, + 68, + 69, + 120, + 77, + 83, + 48, + 52, + 77, + 84, + 69, + 120, + 76, + 84, + 65, + 119, + 77, + 68, + 65, + 119, + 77, + 68, + 65, + 119, + 77, + 68, + 65, + 119, + 89, + 121, + 73, + 115, + 73, + 110, + 78, + 111, + 89, + 84, + 73, + 49, + 78, + 105, + 73, + 54, + 73, + 106, + 65, + 48, + 77, + 68, + 81, + 119, + 78, + 68, + 65, + 48, + 77, + 68, + 81, + 119, + 78, + 68, + 65, + 48, + 77, + 68, + 81, + 119, + 78, + 68, + 65, + 48, + 77, + 68, + 81, + 119, + 78, + 68, + 65, + 48, + 77, + 68, + 81, + 119, + 78, + 68, + 65, + 48, + 77, + 68, + 81, + 119, + 78, + 68, + 65, + 48, + 77, + 68, + 81, + 119, + 78, + 68, + 65, + 48, + 77, + 68, + 81, + 119, + 78, + 68, + 65, + 48, + 77, + 68, + 81, + 119, + 78, + 68, + 65, + 48, + 77, + 68, + 81, + 119, + 78, + 68, + 65, + 48, + 77, + 68, + 81, + 105, + 76, + 67, + 74, + 105, + 101, + 88, + 82, + 108, + 99, + 121, + 73, + 54, + 77, + 106, + 65, + 119, + 77, + 68, + 65, + 119, + 79, + 88, + 49, + 100, + 102, + 81, + 34, + 44, + 34, + 115, + 105, + 103, + 110, + 97, + 116, + 117, + 114, + 101, + 34, + 58, + 34, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 34, + 125, + 44, + 34, + 114, + 101, + 108, + 101, + 97, + 115, + 101, + 95, + 101, + 110, + 118, + 101, + 108, + 111, + 112, + 101, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 50, + 54, + 55, + 53, + 54, + 53, + 97, + 99, + 98, + 49, + 101, + 52, + 55, + 97, + 57, + 98, + 100, + 49, + 57, + 57, + 101, + 100, + 55, + 50, + 100, + 50, + 53, + 57, + 102, + 49, + 97, + 51, + 52, + 101, + 99, + 102, + 54, + 52, + 54, + 56, + 54, + 51, + 51, + 57, + 100, + 50, + 54, + 101, + 97, + 102, + 102, + 50, + 49, + 56, + 101, + 99, + 102, + 52, + 98, + 99, + 55, + 53, + 53, + 98, + 34, + 44, + 34, + 109, + 97, + 110, + 105, + 102, + 101, + 115, + 116, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 52, + 101, + 57, + 52, + 48, + 48, + 101, + 101, + 54, + 99, + 98, + 51, + 54, + 50, + 52, + 51, + 49, + 55, + 56, + 49, + 55, + 51, + 53, + 102, + 97, + 55, + 55, + 53, + 50, + 97, + 56, + 57, + 52, + 55, + 99, + 53, + 57, + 49, + 49, + 102, + 54, + 51, + 48, + 57, + 101, + 50, + 57, + 56, + 51, + 53, + 101, + 56, + 98, + 52, + 100, + 49, + 48, + 53, + 102, + 56, + 48, + 53, + 55, + 54, + 34, + 44, + 34, + 112, + 114, + 101, + 100, + 101, + 99, + 101, + 115, + 115, + 111, + 114, + 34, + 58, + 123, + 34, + 114, + 101, + 108, + 101, + 97, + 115, + 101, + 95, + 105, + 100, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 45, + 49, + 49, + 49, + 49, + 45, + 52, + 49, + 49, + 49, + 45, + 56, + 49, + 49, + 49, + 45, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 57, + 34, + 44, + 34, + 114, + 101, + 108, + 101, + 97, + 115, + 101, + 95, + 115, + 101, + 113, + 117, + 101, + 110, + 99, + 101, + 34, + 58, + 49, + 44, + 34, + 109, + 97, + 110, + 105, + 102, + 101, + 115, + 116, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 34, + 44, + 34, + 105, + 110, + 115, + 116, + 97, + 108, + 108, + 101, + 100, + 95, + 114, + 101, + 99, + 111, + 114, + 100, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 34, + 44, + 34, + 97, + 103, + 101, + 110, + 116, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 34, + 44, + 34, + 104, + 101, + 108, + 112, + 101, + 114, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 34, + 125, + 44, + 34, + 117, + 112, + 100, + 97, + 116, + 101, + 114, + 34, + 58, + 123, + 34, + 98, + 105, + 110, + 97, + 114, + 121, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 34, + 44, + 34, + 112, + 111, + 108, + 105, + 99, + 121, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 34, + 44, + 34, + 107, + 101, + 121, + 114, + 105, + 110, + 103, + 95, + 103, + 101, + 110, + 101, + 114, + 97, + 116, + 105, + 111, + 110, + 34, + 58, + 49, + 44, + 34, + 107, + 101, + 121, + 114, + 105, + 110, + 103, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 34, + 44, + 34, + 104, + 101, + 97, + 108, + 116, + 104, + 95, + 112, + 117, + 98, + 108, + 105, + 99, + 95, + 107, + 101, + 121, + 95, + 104, + 101, + 120, + 34, + 58, + 34, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 34, + 44, + 34, + 104, + 101, + 97, + 108, + 116, + 104, + 95, + 107, + 101, + 121, + 95, + 112, + 105, + 110, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 34, + 125, + 44, + 34, + 112, + 101, + 101, + 114, + 95, + 112, + 105, + 110, + 95, + 116, + 114, + 97, + 110, + 115, + 105, + 116, + 105, + 111, + 110, + 34, + 58, + 123, + 34, + 112, + 114, + 111, + 102, + 105, + 108, + 101, + 34, + 58, + 34, + 108, + 105, + 110, + 117, + 120, + 95, + 103, + 101, + 110, + 101, + 114, + 97, + 108, + 95, + 102, + 117, + 108, + 108, + 95, + 118, + 49, + 34, + 44, + 34, + 103, + 101, + 110, + 101, + 114, + 97, + 108, + 95, + 112, + 105, + 110, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 34, + 44, + 34, + 102, + 117, + 108, + 108, + 34, + 58, + 123, + 34, + 115, + 99, + 104, + 101, + 109, + 97, + 95, + 118, + 101, + 114, + 115, + 105, + 111, + 110, + 34, + 58, + 49, + 44, + 34, + 111, + 108, + 100, + 95, + 99, + 111, + 110, + 102, + 105, + 103, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 34, + 44, + 34, + 110, + 101, + 119, + 95, + 99, + 111, + 110, + 102, + 105, + 103, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 34, + 44, + 34, + 111, + 108, + 100, + 95, + 112, + 105, + 110, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 34, + 44, + 34, + 110, + 101, + 119, + 95, + 112, + 105, + 110, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 34, + 44, + 34, + 111, + 108, + 100, + 95, + 112, + 111, + 108, + 105, + 99, + 121, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 49, + 53, + 49, + 53, + 49, + 53, + 49, + 53, + 49, + 53, + 49, + 53, + 49, + 53, + 49, + 53, + 49, + 53, + 49, + 53, + 49, + 53, + 49, + 53, + 49, + 53, + 49, + 53, + 49, + 53, + 49, + 53, + 49, + 53, + 49, + 53, + 49, + 53, + 49, + 53, + 49, + 53, + 49, + 53, + 49, + 53, + 49, + 53, + 49, + 53, + 49, + 53, + 49, + 53, + 49, + 53, + 49, + 53, + 49, + 53, + 49, + 53, + 49, + 53, + 34, + 44, + 34, + 110, + 101, + 119, + 95, + 112, + 111, + 108, + 105, + 99, + 121, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 49, + 54, + 49, + 54, + 49, + 54, + 49, + 54, + 49, + 54, + 49, + 54, + 49, + 54, + 49, + 54, + 49, + 54, + 49, + 54, + 49, + 54, + 49, + 54, + 49, + 54, + 49, + 54, + 49, + 54, + 49, + 54, + 49, + 54, + 49, + 54, + 49, + 54, + 49, + 54, + 49, + 54, + 49, + 54, + 49, + 54, + 49, + 54, + 49, + 54, + 49, + 54, + 49, + 54, + 49, + 54, + 49, + 54, + 49, + 54, + 49, + 54, + 49, + 54, + 34, + 44, + 34, + 111, + 108, + 100, + 95, + 104, + 101, + 108, + 112, + 101, + 114, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 34, + 44, + 34, + 110, + 101, + 119, + 95, + 104, + 101, + 108, + 112, + 101, + 114, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 34, + 44, + 34, + 101, + 102, + 102, + 101, + 99, + 116, + 105, + 118, + 101, + 95, + 115, + 105, + 103, + 110, + 105, + 110, + 103, + 95, + 107, + 101, + 121, + 95, + 105, + 100, + 34, + 58, + 34, + 49, + 55, + 49, + 55, + 49, + 55, + 49, + 55, + 49, + 55, + 49, + 55, + 49, + 55, + 49, + 55, + 49, + 55, + 49, + 55, + 49, + 55, + 49, + 55, + 49, + 55, + 49, + 55, + 49, + 55, + 49, + 55, + 49, + 55, + 49, + 55, + 49, + 55, + 49, + 55, + 49, + 55, + 49, + 55, + 49, + 55, + 49, + 55, + 49, + 55, + 49, + 55, + 49, + 55, + 49, + 55, + 49, + 55, + 49, + 55, + 49, + 55, + 49, + 55, + 34, + 125, + 125, + 44, + 34, + 114, + 101, + 99, + 111, + 118, + 101, + 114, + 121, + 34, + 58, + 34, + 114, + 101, + 115, + 116, + 111, + 114, + 101, + 95, + 101, + 120, + 97, + 99, + 116, + 95, + 112, + 114, + 101, + 100, + 101, + 99, + 101, + 115, + 115, + 111, + 114, + 95, + 111, + 110, + 99, + 101, + 34, + 44, + 34, + 104, + 101, + 97, + 108, + 116, + 104, + 95, + 112, + 114, + 111, + 102, + 105, + 108, + 101, + 34, + 58, + 34, + 109, + 116, + 108, + 115, + 95, + 105, + 110, + 118, + 101, + 110, + 116, + 111, + 114, + 121, + 95, + 115, + 121, + 110, + 99, + 95, + 118, + 49, + 34, + 44, + 34, + 104, + 101, + 97, + 108, + 116, + 104, + 95, + 116, + 105, + 109, + 101, + 111, + 117, + 116, + 95, + 115, + 101, + 99, + 111, + 110, + 100, + 115, + 34, + 58, + 49, + 56, + 48, + 44, + 34, + 110, + 111, + 95, + 114, + 101, + 98, + 111, + 111, + 116, + 34, + 58, + 116, + 114, + 117, + 101, + 125, + 125, + 44, + 34, + 101, + 120, + 101, + 99, + 117, + 116, + 105, + 111, + 110, + 95, + 105, + 100, + 101, + 110, + 116, + 105, + 116, + 121, + 34, + 58, + 34, + 114, + 111, + 111, + 116, + 34, + 44, + 34, + 110, + 111, + 116, + 95, + 98, + 101, + 102, + 111, + 114, + 101, + 34, + 58, + 34, + 50, + 48, + 51, + 48, + 45, + 48, + 49, + 45, + 48, + 49, + 84, + 49, + 50, + 58, + 48, + 48, + 58, + 48, + 48, + 90, + 34, + 44, + 34, + 115, + 116, + 97, + 114, + 116, + 95, + 98, + 101, + 102, + 111, + 114, + 101, + 34, + 58, + 34, + 50, + 48, + 51, + 48, + 45, + 48, + 49, + 45, + 48, + 49, + 84, + 49, + 50, + 58, + 49, + 48, + 58, + 48, + 48, + 90, + 34, + 44, + 34, + 109, + 97, + 120, + 95, + 114, + 117, + 110, + 116, + 105, + 109, + 101, + 95, + 115, + 101, + 99, + 111, + 110, + 100, + 115, + 34, + 58, + 54, + 48, + 48, + 44, + 34, + 109, + 97, + 120, + 95, + 111, + 117, + 116, + 112, + 117, + 116, + 95, + 98, + 121, + 116, + 101, + 115, + 34, + 58, + 54, + 53, + 53, + 51, + 54, + 125, + 44, + 34, + 106, + 111, + 98, + 95, + 112, + 97, + 121, + 108, + 111, + 97, + 100, + 95, + 104, + 97, + 115, + 104, + 34, + 58, + 34, + 57, + 48, + 51, + 100, + 53, + 50, + 55, + 57, + 50, + 57, + 55, + 99, + 55, + 52, + 50, + 55, + 55, + 48, + 52, + 97, + 52, + 54, + 49, + 99, + 101, + 55, + 55, + 102, + 52, + 50, + 97, + 99, + 101, + 53, + 48, + 101, + 100, + 56, + 102, + 53, + 53, + 57, + 55, + 101, + 100, + 57, + 53, + 100, + 56, + 53, + 48, + 57, + 49, + 54, + 57, + 54, + 52, + 55, + 55, + 50, + 53, + 50, + 49, + 55, + 34, + 44, + 34, + 115, + 99, + 114, + 105, + 112, + 116, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 110, + 117, + 108, + 108, + 125, + 93, + 44, + 34, + 109, + 97, + 120, + 95, + 112, + 97, + 114, + 97, + 108, + 108, + 101, + 108, + 34, + 58, + 49, + 44, + 34, + 104, + 97, + 108, + 116, + 95, + 97, + 102, + 116, + 101, + 114, + 95, + 102, + 97, + 105, + 108, + 117, + 114, + 101, + 115, + 34, + 58, + 49, + 44, + 34, + 97, + 114, + 116, + 105, + 102, + 97, + 99, + 116, + 95, + 114, + 101, + 102, + 101, + 114, + 101, + 110, + 99, + 101, + 115, + 34, + 58, + 91, + 123, + 34, + 106, + 111, + 98, + 95, + 105, + 100, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 45, + 49, + 49, + 49, + 49, + 45, + 52, + 49, + 49, + 49, + 45, + 56, + 49, + 49, + 49, + 45, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 52, + 34, + 44, + 34, + 97, + 116, + 116, + 101, + 109, + 112, + 116, + 95, + 105, + 100, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 45, + 49, + 49, + 49, + 49, + 45, + 52, + 49, + 49, + 49, + 45, + 56, + 49, + 49, + 49, + 45, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 53, + 34, + 44, + 34, + 97, + 114, + 116, + 105, + 102, + 97, + 99, + 116, + 34, + 58, + 123, + 34, + 97, + 114, + 116, + 105, + 102, + 97, + 99, + 116, + 95, + 105, + 100, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 45, + 49, + 49, + 49, + 49, + 45, + 52, + 49, + 49, + 49, + 45, + 56, + 49, + 49, + 49, + 45, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 98, + 34, + 44, + 34, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 34, + 44, + 34, + 115, + 105, + 122, + 101, + 95, + 98, + 121, + 116, + 101, + 115, + 34, + 58, + 51, + 48, + 48, + 48, + 48, + 48, + 55, + 125, + 125, + 44, + 123, + 34, + 106, + 111, + 98, + 95, + 105, + 100, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 45, + 49, + 49, + 49, + 49, + 45, + 52, + 49, + 49, + 49, + 45, + 56, + 49, + 49, + 49, + 45, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 52, + 34, + 44, + 34, + 97, + 116, + 116, + 101, + 109, + 112, + 116, + 95, + 105, + 100, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 45, + 49, + 49, + 49, + 49, + 45, + 52, + 49, + 49, + 49, + 45, + 56, + 49, + 49, + 49, + 45, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 53, + 34, + 44, + 34, + 97, + 114, + 116, + 105, + 102, + 97, + 99, + 116, + 34, + 58, + 123, + 34, + 97, + 114, + 116, + 105, + 102, + 97, + 99, + 116, + 95, + 105, + 100, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 45, + 49, + 49, + 49, + 49, + 45, + 52, + 49, + 49, + 49, + 45, + 56, + 49, + 49, + 49, + 45, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 99, + 34, + 44, + 34, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 34, + 44, + 34, + 115, + 105, + 122, + 101, + 95, + 98, + 121, + 116, + 101, + 115, + 34, + 58, + 50, + 48, + 48, + 48, + 48, + 48, + 57, + 125, + 125, + 93, + 125 + ], + "resolved_targets": [ + { + "agent_id": "11111111-1111-4111-8111-000000000003", + "asset_id": "11111111-1111-4111-8111-000000000002" + } + ] + }, + "linux_general": { + "approval_state": "pending_approval", + "authorization_status": "required", + "excluded_targets": [], + "expires_at": "2030-01-01T12:10:00Z", + "fixture_kind": "codec_only_synthetic_signature_never_publish_or_execute", + "jobs": [ + { + "agent_id": "11111111-1111-4111-8111-000000000003", + "asset_id": "11111111-1111-4111-8111-000000000002", + "attempt_id": "11111111-1111-4111-8111-000000000005", + "job_id": "11111111-1111-4111-8111-000000000004", + "job_payload_hash": "cd5b1505127c17c9e1960c6859d91abb263b55aa610e0cd2b961c51d9e104050", + "payload": { + "action": { + "action": "update_agent", + "update": { + "health_profile": "mtls_inventory_sync_v1", + "health_timeout_seconds": 180, + "manifest_sha256": "4e9400ee6cb362431781735fa7752a8947c5911f6309e29835e8b4d105f80576", + "no_reboot": true, + "peer_pin_transition": { + "general_pin_sha256": "1010101010101010101010101010101010101010101010101010101010101010", + "profile": "unchanged_general_pin_v1" + }, + "predecessor": { + "agent_sha256": "0101010101010101010101010101010101010101010101010101010101010101", + "helper_sha256": "0303030303030303030303030303030303030303030303030303030303030303", + "installed_record_sha256": "2121212121212121212121212121212121212121212121212121212121212121", + "manifest_sha256": "2020202020202020202020202020202020202020202020202020202020202020", + "release_id": "11111111-1111-4111-8111-000000000009", + "release_sequence": 1 + }, + "profile": "fixed_code_pair_v1", + "recovery": "restore_exact_predecessor_once", + "release_envelope": { + "key_id": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "payload_bytes": "eyJzY2hlbWFfdmVyc2lvbiI6MSwicmVsZWFzZV9pZCI6IjExMTExMTExLTExMTEtNDExMS04MTExLTAwMDAwMDAwMDAwYSIsInJlbGVhc2Vfc2VxdWVuY2UiOjIsInZlcnNpb24iOiIwLjEuMS10ZXN0IiwicGxhdGZvcm0iOiJ4ODZfNjQtdW5rbm93bi1saW51eC1nbnUiLCJwdWJsaXNoZWRfYXQiOjE3OTAwMDAwMDAsImV4cGlyZXNfYXQiOjIwMDAwMDAwMDAsInByb3RvY29sX21ham9yIjoxLCJzdGF0ZV9zY2hlbWEiOjEsIm1pbmltdW1fdXBkYXRlcl92ZXJzaW9uIjoxLCJhcnRpZmFjdHMiOlt7InJvbGUiOiJhZ2VudCIsImFydGlmYWN0X2lkIjoiMTExMTExMTEtMTExMS00MTExLTgxMTEtMDAwMDAwMDAwMDBiIiwic2hhMjU2IjoiMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMiIsImJ5dGVzIjozMDAwMDA3fSx7InJvbGUiOiJoZWxwZXIiLCJhcnRpZmFjdF9pZCI6IjExMTExMTExLTExMTEtNDExMS04MTExLTAwMDAwMDAwMDAwYyIsInNoYTI1NiI6IjA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQiLCJieXRlcyI6MjAwMDAwOX1dfQ", + "schema_version": 1, + "signature": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ" + }, + "release_envelope_sha256": "267565acb1e47a9bd199ed72d259f1a34ecf64686339d26eaff218ecf4bc755b", + "schema_version": 1, + "updater": { + "binary_sha256": "3030303030303030303030303030303030303030303030303030303030303030", + "health_key_pin_sha256": "3434343434343434343434343434343434343434343434343434343434343434", + "health_public_key_hex": "3333333333333333333333333333333333333333333333333333333333333333", + "keyring_generation": 1, + "keyring_sha256": "3232323232323232323232323232323232323232323232323232323232323232", + "policy_sha256": "3131313131313131313131313131313131313131313131313131313131313131" + } + } + }, + "agent_id": "11111111-1111-4111-8111-000000000003", + "asset_id": "11111111-1111-4111-8111-000000000002", + "assignment_version": 1, + "attempt_id": "11111111-1111-4111-8111-000000000005", + "enrollment_generation": 1, + "execution_identity": "root", + "job_id": "11111111-1111-4111-8111-000000000004", + "max_output_bytes": 65536, + "max_runtime_seconds": 600, + "not_before": "2030-01-01T12:00:00Z", + "schema_version": 1, + "start_before": "2030-01-01T12:10:00Z", + "tenant_id": "11111111-1111-4111-8111-000000000001" + }, + "script_sha256": null + } + ], + "payload": { + "artifact_references": [ + { + "artifact": { + "artifact_id": "11111111-1111-4111-8111-00000000000b", + "sha256": "0202020202020202020202020202020202020202020202020202020202020202", + "size_bytes": 3000007 + }, + "attempt_id": "11111111-1111-4111-8111-000000000005", + "job_id": "11111111-1111-4111-8111-000000000004" + }, + { + "artifact": { + "artifact_id": "11111111-1111-4111-8111-00000000000c", + "sha256": "0404040404040404040404040404040404040404040404040404040404040404", + "size_bytes": 2000009 + }, + "attempt_id": "11111111-1111-4111-8111-000000000005", + "job_id": "11111111-1111-4111-8111-000000000004" + } + ], + "halt_after_failures": 1, + "jobs": [ + { + "job_payload_hash": "cd5b1505127c17c9e1960c6859d91abb263b55aa610e0cd2b961c51d9e104050", + "payload": { + "action": { + "action": "update_agent", + "update": { + "health_profile": "mtls_inventory_sync_v1", + "health_timeout_seconds": 180, + "manifest_sha256": "4e9400ee6cb362431781735fa7752a8947c5911f6309e29835e8b4d105f80576", + "no_reboot": true, + "peer_pin_transition": { + "general_pin_sha256": "1010101010101010101010101010101010101010101010101010101010101010", + "profile": "unchanged_general_pin_v1" + }, + "predecessor": { + "agent_sha256": "0101010101010101010101010101010101010101010101010101010101010101", + "helper_sha256": "0303030303030303030303030303030303030303030303030303030303030303", + "installed_record_sha256": "2121212121212121212121212121212121212121212121212121212121212121", + "manifest_sha256": "2020202020202020202020202020202020202020202020202020202020202020", + "release_id": "11111111-1111-4111-8111-000000000009", + "release_sequence": 1 + }, + "profile": "fixed_code_pair_v1", + "recovery": "restore_exact_predecessor_once", + "release_envelope": { + "key_id": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "payload_bytes": "eyJzY2hlbWFfdmVyc2lvbiI6MSwicmVsZWFzZV9pZCI6IjExMTExMTExLTExMTEtNDExMS04MTExLTAwMDAwMDAwMDAwYSIsInJlbGVhc2Vfc2VxdWVuY2UiOjIsInZlcnNpb24iOiIwLjEuMS10ZXN0IiwicGxhdGZvcm0iOiJ4ODZfNjQtdW5rbm93bi1saW51eC1nbnUiLCJwdWJsaXNoZWRfYXQiOjE3OTAwMDAwMDAsImV4cGlyZXNfYXQiOjIwMDAwMDAwMDAsInByb3RvY29sX21ham9yIjoxLCJzdGF0ZV9zY2hlbWEiOjEsIm1pbmltdW1fdXBkYXRlcl92ZXJzaW9uIjoxLCJhcnRpZmFjdHMiOlt7InJvbGUiOiJhZ2VudCIsImFydGlmYWN0X2lkIjoiMTExMTExMTEtMTExMS00MTExLTgxMTEtMDAwMDAwMDAwMDBiIiwic2hhMjU2IjoiMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMiIsImJ5dGVzIjozMDAwMDA3fSx7InJvbGUiOiJoZWxwZXIiLCJhcnRpZmFjdF9pZCI6IjExMTExMTExLTExMTEtNDExMS04MTExLTAwMDAwMDAwMDAwYyIsInNoYTI1NiI6IjA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQiLCJieXRlcyI6MjAwMDAwOX1dfQ", + "schema_version": 1, + "signature": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ" + }, + "release_envelope_sha256": "267565acb1e47a9bd199ed72d259f1a34ecf64686339d26eaff218ecf4bc755b", + "schema_version": 1, + "updater": { + "binary_sha256": "3030303030303030303030303030303030303030303030303030303030303030", + "health_key_pin_sha256": "3434343434343434343434343434343434343434343434343434343434343434", + "health_public_key_hex": "3333333333333333333333333333333333333333333333333333333333333333", + "keyring_generation": 1, + "keyring_sha256": "3232323232323232323232323232323232323232323232323232323232323232", + "policy_sha256": "3131313131313131313131313131313131313131313131313131313131313131" + } + } + }, + "agent_id": "11111111-1111-4111-8111-000000000003", + "asset_id": "11111111-1111-4111-8111-000000000002", + "assignment_version": 1, + "attempt_id": "11111111-1111-4111-8111-000000000005", + "enrollment_generation": 1, + "execution_identity": "root", + "job_id": "11111111-1111-4111-8111-000000000004", + "max_output_bytes": 65536, + "max_runtime_seconds": 600, + "not_before": "2030-01-01T12:00:00Z", + "schema_version": 1, + "start_before": "2030-01-01T12:10:00Z", + "tenant_id": "11111111-1111-4111-8111-000000000001" + }, + "script_sha256": null + } + ], + "max_parallel": 1, + "plan_id": "11111111-1111-4111-8111-000000000006", + "principal": "codec-fixture-only", + "reason": "Nur Codec: vollständiges Codepaar – keine Releasefreigabe", + "schema_version": 1, + "tenant_id": "11111111-1111-4111-8111-000000000001" + }, + "plan_hash": "254eb38a2ed8e18dd4885b6fedf844a577e6b18bcf71cab730ab2853bd64e2a1", + "plan_id": "11111111-1111-4111-8111-000000000006", + "plan_payload": { + "artifact_references": [ + { + "artifact": { + "artifact_id": "11111111-1111-4111-8111-00000000000b", + "sha256": "0202020202020202020202020202020202020202020202020202020202020202", + "size_bytes": 3000007 + }, + "attempt_id": "11111111-1111-4111-8111-000000000005", + "job_id": "11111111-1111-4111-8111-000000000004" + }, + { + "artifact": { + "artifact_id": "11111111-1111-4111-8111-00000000000c", + "sha256": "0404040404040404040404040404040404040404040404040404040404040404", + "size_bytes": 2000009 + }, + "attempt_id": "11111111-1111-4111-8111-000000000005", + "job_id": "11111111-1111-4111-8111-000000000004" + } + ], + "halt_after_failures": 1, + "jobs": [ + { + "job_payload_hash": "cd5b1505127c17c9e1960c6859d91abb263b55aa610e0cd2b961c51d9e104050", + "payload": { + "action": { + "action": "update_agent", + "update": { + "health_profile": "mtls_inventory_sync_v1", + "health_timeout_seconds": 180, + "manifest_sha256": "4e9400ee6cb362431781735fa7752a8947c5911f6309e29835e8b4d105f80576", + "no_reboot": true, + "peer_pin_transition": { + "general_pin_sha256": "1010101010101010101010101010101010101010101010101010101010101010", + "profile": "unchanged_general_pin_v1" + }, + "predecessor": { + "agent_sha256": "0101010101010101010101010101010101010101010101010101010101010101", + "helper_sha256": "0303030303030303030303030303030303030303030303030303030303030303", + "installed_record_sha256": "2121212121212121212121212121212121212121212121212121212121212121", + "manifest_sha256": "2020202020202020202020202020202020202020202020202020202020202020", + "release_id": "11111111-1111-4111-8111-000000000009", + "release_sequence": 1 + }, + "profile": "fixed_code_pair_v1", + "recovery": "restore_exact_predecessor_once", + "release_envelope": { + "key_id": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "payload_bytes": "eyJzY2hlbWFfdmVyc2lvbiI6MSwicmVsZWFzZV9pZCI6IjExMTExMTExLTExMTEtNDExMS04MTExLTAwMDAwMDAwMDAwYSIsInJlbGVhc2Vfc2VxdWVuY2UiOjIsInZlcnNpb24iOiIwLjEuMS10ZXN0IiwicGxhdGZvcm0iOiJ4ODZfNjQtdW5rbm93bi1saW51eC1nbnUiLCJwdWJsaXNoZWRfYXQiOjE3OTAwMDAwMDAsImV4cGlyZXNfYXQiOjIwMDAwMDAwMDAsInByb3RvY29sX21ham9yIjoxLCJzdGF0ZV9zY2hlbWEiOjEsIm1pbmltdW1fdXBkYXRlcl92ZXJzaW9uIjoxLCJhcnRpZmFjdHMiOlt7InJvbGUiOiJhZ2VudCIsImFydGlmYWN0X2lkIjoiMTExMTExMTEtMTExMS00MTExLTgxMTEtMDAwMDAwMDAwMDBiIiwic2hhMjU2IjoiMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMiIsImJ5dGVzIjozMDAwMDA3fSx7InJvbGUiOiJoZWxwZXIiLCJhcnRpZmFjdF9pZCI6IjExMTExMTExLTExMTEtNDExMS04MTExLTAwMDAwMDAwMDAwYyIsInNoYTI1NiI6IjA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQiLCJieXRlcyI6MjAwMDAwOX1dfQ", + "schema_version": 1, + "signature": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ" + }, + "release_envelope_sha256": "267565acb1e47a9bd199ed72d259f1a34ecf64686339d26eaff218ecf4bc755b", + "schema_version": 1, + "updater": { + "binary_sha256": "3030303030303030303030303030303030303030303030303030303030303030", + "health_key_pin_sha256": "3434343434343434343434343434343434343434343434343434343434343434", + "health_public_key_hex": "3333333333333333333333333333333333333333333333333333333333333333", + "keyring_generation": 1, + "keyring_sha256": "3232323232323232323232323232323232323232323232323232323232323232", + "policy_sha256": "3131313131313131313131313131313131313131313131313131313131313131" + } + } + }, + "agent_id": "11111111-1111-4111-8111-000000000003", + "asset_id": "11111111-1111-4111-8111-000000000002", + "assignment_version": 1, + "attempt_id": "11111111-1111-4111-8111-000000000005", + "enrollment_generation": 1, + "execution_identity": "root", + "job_id": "11111111-1111-4111-8111-000000000004", + "max_output_bytes": 65536, + "max_runtime_seconds": 600, + "not_before": "2030-01-01T12:00:00Z", + "schema_version": 1, + "start_before": "2030-01-01T12:10:00Z", + "tenant_id": "11111111-1111-4111-8111-000000000001" + }, + "script_sha256": null + } + ], + "max_parallel": 1, + "plan_id": "11111111-1111-4111-8111-000000000006", + "principal": "codec-fixture-only", + "reason": "Nur Codec: vollständiges Codepaar – keine Releasefreigabe", + "schema_version": 1, + "tenant_id": "11111111-1111-4111-8111-000000000001" + }, + "plan_payload_bytes": [ + 123, + 34, + 115, + 99, + 104, + 101, + 109, + 97, + 95, + 118, + 101, + 114, + 115, + 105, + 111, + 110, + 34, + 58, + 49, + 44, + 34, + 112, + 108, + 97, + 110, + 95, + 105, + 100, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 45, + 49, + 49, + 49, + 49, + 45, + 52, + 49, + 49, + 49, + 45, + 56, + 49, + 49, + 49, + 45, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 54, + 34, + 44, + 34, + 116, + 101, + 110, + 97, + 110, + 116, + 95, + 105, + 100, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 45, + 49, + 49, + 49, + 49, + 45, + 52, + 49, + 49, + 49, + 45, + 56, + 49, + 49, + 49, + 45, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 49, + 34, + 44, + 34, + 112, + 114, + 105, + 110, + 99, + 105, + 112, + 97, + 108, + 34, + 58, + 34, + 99, + 111, + 100, + 101, + 99, + 45, + 102, + 105, + 120, + 116, + 117, + 114, + 101, + 45, + 111, + 110, + 108, + 121, + 34, + 44, + 34, + 114, + 101, + 97, + 115, + 111, + 110, + 34, + 58, + 34, + 78, + 117, + 114, + 32, + 67, + 111, + 100, + 101, + 99, + 58, + 32, + 118, + 111, + 108, + 108, + 115, + 116, + 195, + 164, + 110, + 100, + 105, + 103, + 101, + 115, + 32, + 67, + 111, + 100, + 101, + 112, + 97, + 97, + 114, + 32, + 226, + 128, + 147, + 32, + 107, + 101, + 105, + 110, + 101, + 32, + 82, + 101, + 108, + 101, + 97, + 115, + 101, + 102, + 114, + 101, + 105, + 103, + 97, + 98, + 101, + 34, + 44, + 34, + 106, + 111, + 98, + 115, + 34, + 58, + 91, + 123, + 34, + 112, + 97, + 121, + 108, + 111, + 97, + 100, + 34, + 58, + 123, + 34, + 115, + 99, + 104, + 101, + 109, + 97, + 95, + 118, + 101, + 114, + 115, + 105, + 111, + 110, + 34, + 58, + 49, + 44, + 34, + 116, + 101, + 110, + 97, + 110, + 116, + 95, + 105, + 100, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 45, + 49, + 49, + 49, + 49, + 45, + 52, + 49, + 49, + 49, + 45, + 56, + 49, + 49, + 49, + 45, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 49, + 34, + 44, + 34, + 97, + 115, + 115, + 101, + 116, + 95, + 105, + 100, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 45, + 49, + 49, + 49, + 49, + 45, + 52, + 49, + 49, + 49, + 45, + 56, + 49, + 49, + 49, + 45, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 50, + 34, + 44, + 34, + 97, + 103, + 101, + 110, + 116, + 95, + 105, + 100, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 45, + 49, + 49, + 49, + 49, + 45, + 52, + 49, + 49, + 49, + 45, + 56, + 49, + 49, + 49, + 45, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 51, + 34, + 44, + 34, + 101, + 110, + 114, + 111, + 108, + 108, + 109, + 101, + 110, + 116, + 95, + 103, + 101, + 110, + 101, + 114, + 97, + 116, + 105, + 111, + 110, + 34, + 58, + 49, + 44, + 34, + 97, + 115, + 115, + 105, + 103, + 110, + 109, + 101, + 110, + 116, + 95, + 118, + 101, + 114, + 115, + 105, + 111, + 110, + 34, + 58, + 49, + 44, + 34, + 106, + 111, + 98, + 95, + 105, + 100, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 45, + 49, + 49, + 49, + 49, + 45, + 52, + 49, + 49, + 49, + 45, + 56, + 49, + 49, + 49, + 45, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 52, + 34, + 44, + 34, + 97, + 116, + 116, + 101, + 109, + 112, + 116, + 95, + 105, + 100, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 45, + 49, + 49, + 49, + 49, + 45, + 52, + 49, + 49, + 49, + 45, + 56, + 49, + 49, + 49, + 45, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 53, + 34, + 44, + 34, + 97, + 99, + 116, + 105, + 111, + 110, + 34, + 58, + 123, + 34, + 97, + 99, + 116, + 105, + 111, + 110, + 34, + 58, + 34, + 117, + 112, + 100, + 97, + 116, + 101, + 95, + 97, + 103, + 101, + 110, + 116, + 34, + 44, + 34, + 117, + 112, + 100, + 97, + 116, + 101, + 34, + 58, + 123, + 34, + 115, + 99, + 104, + 101, + 109, + 97, + 95, + 118, + 101, + 114, + 115, + 105, + 111, + 110, + 34, + 58, + 49, + 44, + 34, + 112, + 114, + 111, + 102, + 105, + 108, + 101, + 34, + 58, + 34, + 102, + 105, + 120, + 101, + 100, + 95, + 99, + 111, + 100, + 101, + 95, + 112, + 97, + 105, + 114, + 95, + 118, + 49, + 34, + 44, + 34, + 114, + 101, + 108, + 101, + 97, + 115, + 101, + 95, + 101, + 110, + 118, + 101, + 108, + 111, + 112, + 101, + 34, + 58, + 123, + 34, + 115, + 99, + 104, + 101, + 109, + 97, + 95, + 118, + 101, + 114, + 115, + 105, + 111, + 110, + 34, + 58, + 49, + 44, + 34, + 107, + 101, + 121, + 95, + 105, + 100, + 34, + 58, + 34, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 34, + 44, + 34, + 112, + 97, + 121, + 108, + 111, + 97, + 100, + 95, + 98, + 121, + 116, + 101, + 115, + 34, + 58, + 34, + 101, + 121, + 74, + 122, + 89, + 50, + 104, + 108, + 98, + 87, + 70, + 102, + 100, + 109, + 86, + 121, + 99, + 50, + 108, + 118, + 98, + 105, + 73, + 54, + 77, + 83, + 119, + 105, + 99, + 109, + 86, + 115, + 90, + 87, + 70, + 122, + 90, + 86, + 57, + 112, + 90, + 67, + 73, + 54, + 73, + 106, + 69, + 120, + 77, + 84, + 69, + 120, + 77, + 84, + 69, + 120, + 76, + 84, + 69, + 120, + 77, + 84, + 69, + 116, + 78, + 68, + 69, + 120, + 77, + 83, + 48, + 52, + 77, + 84, + 69, + 120, + 76, + 84, + 65, + 119, + 77, + 68, + 65, + 119, + 77, + 68, + 65, + 119, + 77, + 68, + 65, + 119, + 89, + 83, + 73, + 115, + 73, + 110, + 74, + 108, + 98, + 71, + 86, + 104, + 99, + 50, + 86, + 102, + 99, + 50, + 86, + 120, + 100, + 87, + 86, + 117, + 89, + 50, + 85, + 105, + 79, + 106, + 73, + 115, + 73, + 110, + 90, + 108, + 99, + 110, + 78, + 112, + 98, + 50, + 52, + 105, + 79, + 105, + 73, + 119, + 76, + 106, + 69, + 117, + 77, + 83, + 49, + 48, + 90, + 88, + 78, + 48, + 73, + 105, + 119, + 105, + 99, + 71, + 120, + 104, + 100, + 71, + 90, + 118, + 99, + 109, + 48, + 105, + 79, + 105, + 74, + 52, + 79, + 68, + 90, + 102, + 78, + 106, + 81, + 116, + 100, + 87, + 53, + 114, + 98, + 109, + 57, + 51, + 98, + 105, + 49, + 115, + 97, + 87, + 53, + 49, + 101, + 67, + 49, + 110, + 98, + 110, + 85, + 105, + 76, + 67, + 74, + 119, + 100, + 87, + 74, + 115, + 97, + 88, + 78, + 111, + 90, + 87, + 82, + 102, + 89, + 88, + 81, + 105, + 79, + 106, + 69, + 51, + 79, + 84, + 65, + 119, + 77, + 68, + 65, + 119, + 77, + 68, + 65, + 115, + 73, + 109, + 86, + 52, + 99, + 71, + 108, + 121, + 90, + 88, + 78, + 102, + 89, + 88, + 81, + 105, + 79, + 106, + 73, + 119, + 77, + 68, + 65, + 119, + 77, + 68, + 65, + 119, + 77, + 68, + 65, + 115, + 73, + 110, + 66, + 121, + 98, + 51, + 82, + 118, + 89, + 50, + 57, + 115, + 88, + 50, + 49, + 104, + 97, + 109, + 57, + 121, + 73, + 106, + 111, + 120, + 76, + 67, + 74, + 122, + 100, + 71, + 70, + 48, + 90, + 86, + 57, + 122, + 89, + 50, + 104, + 108, + 98, + 87, + 69, + 105, + 79, + 106, + 69, + 115, + 73, + 109, + 49, + 112, + 98, + 109, + 108, + 116, + 100, + 87, + 49, + 102, + 100, + 88, + 66, + 107, + 89, + 88, + 82, + 108, + 99, + 108, + 57, + 50, + 90, + 88, + 74, + 122, + 97, + 87, + 57, + 117, + 73, + 106, + 111, + 120, + 76, + 67, + 74, + 104, + 99, + 110, + 82, + 112, + 90, + 109, + 70, + 106, + 100, + 72, + 77, + 105, + 79, + 108, + 116, + 55, + 73, + 110, + 74, + 118, + 98, + 71, + 85, + 105, + 79, + 105, + 74, + 104, + 90, + 50, + 86, + 117, + 100, + 67, + 73, + 115, + 73, + 109, + 70, + 121, + 100, + 71, + 108, + 109, + 89, + 87, + 78, + 48, + 88, + 50, + 108, + 107, + 73, + 106, + 111, + 105, + 77, + 84, + 69, + 120, + 77, + 84, + 69, + 120, + 77, + 84, + 69, + 116, + 77, + 84, + 69, + 120, + 77, + 83, + 48, + 48, + 77, + 84, + 69, + 120, + 76, + 84, + 103, + 120, + 77, + 84, + 69, + 116, + 77, + 68, + 65, + 119, + 77, + 68, + 65, + 119, + 77, + 68, + 65, + 119, + 77, + 68, + 66, + 105, + 73, + 105, + 119, + 105, + 99, + 50, + 104, + 104, + 77, + 106, + 85, + 50, + 73, + 106, + 111, + 105, + 77, + 68, + 73, + 119, + 77, + 106, + 65, + 121, + 77, + 68, + 73, + 119, + 77, + 106, + 65, + 121, + 77, + 68, + 73, + 119, + 77, + 106, + 65, + 121, + 77, + 68, + 73, + 119, + 77, + 106, + 65, + 121, + 77, + 68, + 73, + 119, + 77, + 106, + 65, + 121, + 77, + 68, + 73, + 119, + 77, + 106, + 65, + 121, + 77, + 68, + 73, + 119, + 77, + 106, + 65, + 121, + 77, + 68, + 73, + 119, + 77, + 106, + 65, + 121, + 77, + 68, + 73, + 119, + 77, + 106, + 65, + 121, + 77, + 68, + 73, + 119, + 77, + 106, + 65, + 121, + 77, + 68, + 73, + 119, + 77, + 105, + 73, + 115, + 73, + 109, + 74, + 53, + 100, + 71, + 86, + 122, + 73, + 106, + 111, + 122, + 77, + 68, + 65, + 119, + 77, + 68, + 65, + 51, + 102, + 83, + 120, + 55, + 73, + 110, + 74, + 118, + 98, + 71, + 85, + 105, + 79, + 105, + 74, + 111, + 90, + 87, + 120, + 119, + 90, + 88, + 73, + 105, + 76, + 67, + 74, + 104, + 99, + 110, + 82, + 112, + 90, + 109, + 70, + 106, + 100, + 70, + 57, + 112, + 90, + 67, + 73, + 54, + 73, + 106, + 69, + 120, + 77, + 84, + 69, + 120, + 77, + 84, + 69, + 120, + 76, + 84, + 69, + 120, + 77, + 84, + 69, + 116, + 78, + 68, + 69, + 120, + 77, + 83, + 48, + 52, + 77, + 84, + 69, + 120, + 76, + 84, + 65, + 119, + 77, + 68, + 65, + 119, + 77, + 68, + 65, + 119, + 77, + 68, + 65, + 119, + 89, + 121, + 73, + 115, + 73, + 110, + 78, + 111, + 89, + 84, + 73, + 49, + 78, + 105, + 73, + 54, + 73, + 106, + 65, + 48, + 77, + 68, + 81, + 119, + 78, + 68, + 65, + 48, + 77, + 68, + 81, + 119, + 78, + 68, + 65, + 48, + 77, + 68, + 81, + 119, + 78, + 68, + 65, + 48, + 77, + 68, + 81, + 119, + 78, + 68, + 65, + 48, + 77, + 68, + 81, + 119, + 78, + 68, + 65, + 48, + 77, + 68, + 81, + 119, + 78, + 68, + 65, + 48, + 77, + 68, + 81, + 119, + 78, + 68, + 65, + 48, + 77, + 68, + 81, + 119, + 78, + 68, + 65, + 48, + 77, + 68, + 81, + 119, + 78, + 68, + 65, + 48, + 77, + 68, + 81, + 119, + 78, + 68, + 65, + 48, + 77, + 68, + 81, + 105, + 76, + 67, + 74, + 105, + 101, + 88, + 82, + 108, + 99, + 121, + 73, + 54, + 77, + 106, + 65, + 119, + 77, + 68, + 65, + 119, + 79, + 88, + 49, + 100, + 102, + 81, + 34, + 44, + 34, + 115, + 105, + 103, + 110, + 97, + 116, + 117, + 114, + 101, + 34, + 58, + 34, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 34, + 125, + 44, + 34, + 114, + 101, + 108, + 101, + 97, + 115, + 101, + 95, + 101, + 110, + 118, + 101, + 108, + 111, + 112, + 101, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 50, + 54, + 55, + 53, + 54, + 53, + 97, + 99, + 98, + 49, + 101, + 52, + 55, + 97, + 57, + 98, + 100, + 49, + 57, + 57, + 101, + 100, + 55, + 50, + 100, + 50, + 53, + 57, + 102, + 49, + 97, + 51, + 52, + 101, + 99, + 102, + 54, + 52, + 54, + 56, + 54, + 51, + 51, + 57, + 100, + 50, + 54, + 101, + 97, + 102, + 102, + 50, + 49, + 56, + 101, + 99, + 102, + 52, + 98, + 99, + 55, + 53, + 53, + 98, + 34, + 44, + 34, + 109, + 97, + 110, + 105, + 102, + 101, + 115, + 116, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 52, + 101, + 57, + 52, + 48, + 48, + 101, + 101, + 54, + 99, + 98, + 51, + 54, + 50, + 52, + 51, + 49, + 55, + 56, + 49, + 55, + 51, + 53, + 102, + 97, + 55, + 55, + 53, + 50, + 97, + 56, + 57, + 52, + 55, + 99, + 53, + 57, + 49, + 49, + 102, + 54, + 51, + 48, + 57, + 101, + 50, + 57, + 56, + 51, + 53, + 101, + 56, + 98, + 52, + 100, + 49, + 48, + 53, + 102, + 56, + 48, + 53, + 55, + 54, + 34, + 44, + 34, + 112, + 114, + 101, + 100, + 101, + 99, + 101, + 115, + 115, + 111, + 114, + 34, + 58, + 123, + 34, + 114, + 101, + 108, + 101, + 97, + 115, + 101, + 95, + 105, + 100, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 45, + 49, + 49, + 49, + 49, + 45, + 52, + 49, + 49, + 49, + 45, + 56, + 49, + 49, + 49, + 45, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 57, + 34, + 44, + 34, + 114, + 101, + 108, + 101, + 97, + 115, + 101, + 95, + 115, + 101, + 113, + 117, + 101, + 110, + 99, + 101, + 34, + 58, + 49, + 44, + 34, + 109, + 97, + 110, + 105, + 102, + 101, + 115, + 116, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 34, + 44, + 34, + 105, + 110, + 115, + 116, + 97, + 108, + 108, + 101, + 100, + 95, + 114, + 101, + 99, + 111, + 114, + 100, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 34, + 44, + 34, + 97, + 103, + 101, + 110, + 116, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 34, + 44, + 34, + 104, + 101, + 108, + 112, + 101, + 114, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 34, + 125, + 44, + 34, + 117, + 112, + 100, + 97, + 116, + 101, + 114, + 34, + 58, + 123, + 34, + 98, + 105, + 110, + 97, + 114, + 121, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 34, + 44, + 34, + 112, + 111, + 108, + 105, + 99, + 121, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 34, + 44, + 34, + 107, + 101, + 121, + 114, + 105, + 110, + 103, + 95, + 103, + 101, + 110, + 101, + 114, + 97, + 116, + 105, + 111, + 110, + 34, + 58, + 49, + 44, + 34, + 107, + 101, + 121, + 114, + 105, + 110, + 103, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 34, + 44, + 34, + 104, + 101, + 97, + 108, + 116, + 104, + 95, + 112, + 117, + 98, + 108, + 105, + 99, + 95, + 107, + 101, + 121, + 95, + 104, + 101, + 120, + 34, + 58, + 34, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 34, + 44, + 34, + 104, + 101, + 97, + 108, + 116, + 104, + 95, + 107, + 101, + 121, + 95, + 112, + 105, + 110, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 34, + 125, + 44, + 34, + 112, + 101, + 101, + 114, + 95, + 112, + 105, + 110, + 95, + 116, + 114, + 97, + 110, + 115, + 105, + 116, + 105, + 111, + 110, + 34, + 58, + 123, + 34, + 112, + 114, + 111, + 102, + 105, + 108, + 101, + 34, + 58, + 34, + 117, + 110, + 99, + 104, + 97, + 110, + 103, + 101, + 100, + 95, + 103, + 101, + 110, + 101, + 114, + 97, + 108, + 95, + 112, + 105, + 110, + 95, + 118, + 49, + 34, + 44, + 34, + 103, + 101, + 110, + 101, + 114, + 97, + 108, + 95, + 112, + 105, + 110, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 34, + 125, + 44, + 34, + 114, + 101, + 99, + 111, + 118, + 101, + 114, + 121, + 34, + 58, + 34, + 114, + 101, + 115, + 116, + 111, + 114, + 101, + 95, + 101, + 120, + 97, + 99, + 116, + 95, + 112, + 114, + 101, + 100, + 101, + 99, + 101, + 115, + 115, + 111, + 114, + 95, + 111, + 110, + 99, + 101, + 34, + 44, + 34, + 104, + 101, + 97, + 108, + 116, + 104, + 95, + 112, + 114, + 111, + 102, + 105, + 108, + 101, + 34, + 58, + 34, + 109, + 116, + 108, + 115, + 95, + 105, + 110, + 118, + 101, + 110, + 116, + 111, + 114, + 121, + 95, + 115, + 121, + 110, + 99, + 95, + 118, + 49, + 34, + 44, + 34, + 104, + 101, + 97, + 108, + 116, + 104, + 95, + 116, + 105, + 109, + 101, + 111, + 117, + 116, + 95, + 115, + 101, + 99, + 111, + 110, + 100, + 115, + 34, + 58, + 49, + 56, + 48, + 44, + 34, + 110, + 111, + 95, + 114, + 101, + 98, + 111, + 111, + 116, + 34, + 58, + 116, + 114, + 117, + 101, + 125, + 125, + 44, + 34, + 101, + 120, + 101, + 99, + 117, + 116, + 105, + 111, + 110, + 95, + 105, + 100, + 101, + 110, + 116, + 105, + 116, + 121, + 34, + 58, + 34, + 114, + 111, + 111, + 116, + 34, + 44, + 34, + 110, + 111, + 116, + 95, + 98, + 101, + 102, + 111, + 114, + 101, + 34, + 58, + 34, + 50, + 48, + 51, + 48, + 45, + 48, + 49, + 45, + 48, + 49, + 84, + 49, + 50, + 58, + 48, + 48, + 58, + 48, + 48, + 90, + 34, + 44, + 34, + 115, + 116, + 97, + 114, + 116, + 95, + 98, + 101, + 102, + 111, + 114, + 101, + 34, + 58, + 34, + 50, + 48, + 51, + 48, + 45, + 48, + 49, + 45, + 48, + 49, + 84, + 49, + 50, + 58, + 49, + 48, + 58, + 48, + 48, + 90, + 34, + 44, + 34, + 109, + 97, + 120, + 95, + 114, + 117, + 110, + 116, + 105, + 109, + 101, + 95, + 115, + 101, + 99, + 111, + 110, + 100, + 115, + 34, + 58, + 54, + 48, + 48, + 44, + 34, + 109, + 97, + 120, + 95, + 111, + 117, + 116, + 112, + 117, + 116, + 95, + 98, + 121, + 116, + 101, + 115, + 34, + 58, + 54, + 53, + 53, + 51, + 54, + 125, + 44, + 34, + 106, + 111, + 98, + 95, + 112, + 97, + 121, + 108, + 111, + 97, + 100, + 95, + 104, + 97, + 115, + 104, + 34, + 58, + 34, + 99, + 100, + 53, + 98, + 49, + 53, + 48, + 53, + 49, + 50, + 55, + 99, + 49, + 55, + 99, + 57, + 101, + 49, + 57, + 54, + 48, + 99, + 54, + 56, + 53, + 57, + 100, + 57, + 49, + 97, + 98, + 98, + 50, + 54, + 51, + 98, + 53, + 53, + 97, + 97, + 54, + 49, + 48, + 101, + 48, + 99, + 100, + 50, + 98, + 57, + 54, + 49, + 99, + 53, + 49, + 100, + 57, + 101, + 49, + 48, + 52, + 48, + 53, + 48, + 34, + 44, + 34, + 115, + 99, + 114, + 105, + 112, + 116, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 110, + 117, + 108, + 108, + 125, + 93, + 44, + 34, + 109, + 97, + 120, + 95, + 112, + 97, + 114, + 97, + 108, + 108, + 101, + 108, + 34, + 58, + 49, + 44, + 34, + 104, + 97, + 108, + 116, + 95, + 97, + 102, + 116, + 101, + 114, + 95, + 102, + 97, + 105, + 108, + 117, + 114, + 101, + 115, + 34, + 58, + 49, + 44, + 34, + 97, + 114, + 116, + 105, + 102, + 97, + 99, + 116, + 95, + 114, + 101, + 102, + 101, + 114, + 101, + 110, + 99, + 101, + 115, + 34, + 58, + 91, + 123, + 34, + 106, + 111, + 98, + 95, + 105, + 100, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 45, + 49, + 49, + 49, + 49, + 45, + 52, + 49, + 49, + 49, + 45, + 56, + 49, + 49, + 49, + 45, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 52, + 34, + 44, + 34, + 97, + 116, + 116, + 101, + 109, + 112, + 116, + 95, + 105, + 100, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 45, + 49, + 49, + 49, + 49, + 45, + 52, + 49, + 49, + 49, + 45, + 56, + 49, + 49, + 49, + 45, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 53, + 34, + 44, + 34, + 97, + 114, + 116, + 105, + 102, + 97, + 99, + 116, + 34, + 58, + 123, + 34, + 97, + 114, + 116, + 105, + 102, + 97, + 99, + 116, + 95, + 105, + 100, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 45, + 49, + 49, + 49, + 49, + 45, + 52, + 49, + 49, + 49, + 45, + 56, + 49, + 49, + 49, + 45, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 98, + 34, + 44, + 34, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 34, + 44, + 34, + 115, + 105, + 122, + 101, + 95, + 98, + 121, + 116, + 101, + 115, + 34, + 58, + 51, + 48, + 48, + 48, + 48, + 48, + 55, + 125, + 125, + 44, + 123, + 34, + 106, + 111, + 98, + 95, + 105, + 100, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 45, + 49, + 49, + 49, + 49, + 45, + 52, + 49, + 49, + 49, + 45, + 56, + 49, + 49, + 49, + 45, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 52, + 34, + 44, + 34, + 97, + 116, + 116, + 101, + 109, + 112, + 116, + 95, + 105, + 100, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 45, + 49, + 49, + 49, + 49, + 45, + 52, + 49, + 49, + 49, + 45, + 56, + 49, + 49, + 49, + 45, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 53, + 34, + 44, + 34, + 97, + 114, + 116, + 105, + 102, + 97, + 99, + 116, + 34, + 58, + 123, + 34, + 97, + 114, + 116, + 105, + 102, + 97, + 99, + 116, + 95, + 105, + 100, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 45, + 49, + 49, + 49, + 49, + 45, + 52, + 49, + 49, + 49, + 45, + 56, + 49, + 49, + 49, + 45, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 99, + 34, + 44, + 34, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 34, + 44, + 34, + 115, + 105, + 122, + 101, + 95, + 98, + 121, + 116, + 101, + 115, + 34, + 58, + 50, + 48, + 48, + 48, + 48, + 48, + 57, + 125, + 125, + 93, + 125 + ], + "resolved_targets": [ + { + "agent_id": "11111111-1111-4111-8111-000000000003", + "asset_id": "11111111-1111-4111-8111-000000000002" + } + ] + }, + "windows_pair": { + "approval_state": "pending_approval", + "authorization_status": "required", + "excluded_targets": [], + "expires_at": "2030-01-01T12:10:00Z", + "fixture_kind": "codec_only_synthetic_signature_never_publish_or_execute", + "jobs": [ + { + "agent_id": "11111111-1111-4111-8111-000000000003", + "asset_id": "11111111-1111-4111-8111-000000000002", + "attempt_id": "11111111-1111-4111-8111-000000000005", + "job_id": "11111111-1111-4111-8111-000000000004", + "job_payload_hash": "3c78ca7a1f29191236a132e195f2379d8b9ad57ed3f05218f31e234be60d491a", + "payload": { + "action": { + "action": "update_agent", + "update": { + "health_profile": "mtls_inventory_sync_v1", + "health_timeout_seconds": 180, + "manifest_sha256": "0a821a915cc9cd954801c1d6feca591fbe853bc4781376a84982a997484e3166", + "no_reboot": true, + "peer_pin_transition": { + "new_pin_sha256": "1414141414141414141414141414141414141414141414141414141414141414", + "new_settings_sha256": "1212121212121212121212121212121212121212121212121212121212121212", + "old_pin_sha256": "1313131313131313131313131313131313131313131313131313131313131313", + "old_settings_sha256": "1111111111111111111111111111111111111111111111111111111111111111", + "profile": "windows_code_pair_v1" + }, + "predecessor": { + "agent_sha256": "0101010101010101010101010101010101010101010101010101010101010101", + "helper_sha256": "0303030303030303030303030303030303030303030303030303030303030303", + "installed_record_sha256": "2121212121212121212121212121212121212121212121212121212121212121", + "manifest_sha256": "2020202020202020202020202020202020202020202020202020202020202020", + "release_id": "11111111-1111-4111-8111-000000000009", + "release_sequence": 1 + }, + "profile": "fixed_code_pair_v1", + "recovery": "restore_exact_predecessor_once", + "release_envelope": { + "key_id": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "payload_bytes": "eyJzY2hlbWFfdmVyc2lvbiI6MSwicmVsZWFzZV9pZCI6IjExMTExMTExLTExMTEtNDExMS04MTExLTAwMDAwMDAwMDAwYSIsInJlbGVhc2Vfc2VxdWVuY2UiOjIsInZlcnNpb24iOiIwLjEuMS10ZXN0IiwicGxhdGZvcm0iOiJ4ODZfNjQtcGMtd2luZG93cy1tc3ZjIiwicHVibGlzaGVkX2F0IjoxNzkwMDAwMDAwLCJleHBpcmVzX2F0IjoyMDAwMDAwMDAwLCJwcm90b2NvbF9tYWpvciI6MSwic3RhdGVfc2NoZW1hIjoxLCJtaW5pbXVtX3VwZGF0ZXJfdmVyc2lvbiI6MSwiYXJ0aWZhY3RzIjpbeyJyb2xlIjoiYWdlbnQiLCJhcnRpZmFjdF9pZCI6IjExMTExMTExLTExMTEtNDExMS04MTExLTAwMDAwMDAwMDAwYiIsInNoYTI1NiI6IjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIiLCJieXRlcyI6MzAwMDAwN30seyJyb2xlIjoiaGVscGVyIiwiYXJ0aWZhY3RfaWQiOiIxMTExMTExMS0xMTExLTQxMTEtODExMS0wMDAwMDAwMDAwMGMiLCJzaGEyNTYiOiIwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0IiwiYnl0ZXMiOjIwMDAwMDl9XX0", + "schema_version": 1, + "signature": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ" + }, + "release_envelope_sha256": "1e510550d2ce0ca00ada743228a166e975a661301941c1063a5b7eabe43f95e9", + "schema_version": 1, + "updater": { + "binary_sha256": "3030303030303030303030303030303030303030303030303030303030303030", + "health_key_pin_sha256": "3434343434343434343434343434343434343434343434343434343434343434", + "health_public_key_hex": "3333333333333333333333333333333333333333333333333333333333333333", + "keyring_generation": 1, + "keyring_sha256": "3232323232323232323232323232323232323232323232323232323232323232", + "policy_sha256": "3131313131313131313131313131313131313131313131313131313131313131" + } + } + }, + "agent_id": "11111111-1111-4111-8111-000000000003", + "asset_id": "11111111-1111-4111-8111-000000000002", + "assignment_version": 1, + "attempt_id": "11111111-1111-4111-8111-000000000005", + "enrollment_generation": 1, + "execution_identity": "system", + "job_id": "11111111-1111-4111-8111-000000000004", + "max_output_bytes": 65536, + "max_runtime_seconds": 600, + "not_before": "2030-01-01T12:00:00Z", + "schema_version": 1, + "start_before": "2030-01-01T12:10:00Z", + "tenant_id": "11111111-1111-4111-8111-000000000001" + }, + "script_sha256": null + } + ], + "payload": { + "artifact_references": [ + { + "artifact": { + "artifact_id": "11111111-1111-4111-8111-00000000000b", + "sha256": "0202020202020202020202020202020202020202020202020202020202020202", + "size_bytes": 3000007 + }, + "attempt_id": "11111111-1111-4111-8111-000000000005", + "job_id": "11111111-1111-4111-8111-000000000004" + }, + { + "artifact": { + "artifact_id": "11111111-1111-4111-8111-00000000000c", + "sha256": "0404040404040404040404040404040404040404040404040404040404040404", + "size_bytes": 2000009 + }, + "attempt_id": "11111111-1111-4111-8111-000000000005", + "job_id": "11111111-1111-4111-8111-000000000004" + } + ], + "halt_after_failures": 1, + "jobs": [ + { + "job_payload_hash": "3c78ca7a1f29191236a132e195f2379d8b9ad57ed3f05218f31e234be60d491a", + "payload": { + "action": { + "action": "update_agent", + "update": { + "health_profile": "mtls_inventory_sync_v1", + "health_timeout_seconds": 180, + "manifest_sha256": "0a821a915cc9cd954801c1d6feca591fbe853bc4781376a84982a997484e3166", + "no_reboot": true, + "peer_pin_transition": { + "new_pin_sha256": "1414141414141414141414141414141414141414141414141414141414141414", + "new_settings_sha256": "1212121212121212121212121212121212121212121212121212121212121212", + "old_pin_sha256": "1313131313131313131313131313131313131313131313131313131313131313", + "old_settings_sha256": "1111111111111111111111111111111111111111111111111111111111111111", + "profile": "windows_code_pair_v1" + }, + "predecessor": { + "agent_sha256": "0101010101010101010101010101010101010101010101010101010101010101", + "helper_sha256": "0303030303030303030303030303030303030303030303030303030303030303", + "installed_record_sha256": "2121212121212121212121212121212121212121212121212121212121212121", + "manifest_sha256": "2020202020202020202020202020202020202020202020202020202020202020", + "release_id": "11111111-1111-4111-8111-000000000009", + "release_sequence": 1 + }, + "profile": "fixed_code_pair_v1", + "recovery": "restore_exact_predecessor_once", + "release_envelope": { + "key_id": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "payload_bytes": "eyJzY2hlbWFfdmVyc2lvbiI6MSwicmVsZWFzZV9pZCI6IjExMTExMTExLTExMTEtNDExMS04MTExLTAwMDAwMDAwMDAwYSIsInJlbGVhc2Vfc2VxdWVuY2UiOjIsInZlcnNpb24iOiIwLjEuMS10ZXN0IiwicGxhdGZvcm0iOiJ4ODZfNjQtcGMtd2luZG93cy1tc3ZjIiwicHVibGlzaGVkX2F0IjoxNzkwMDAwMDAwLCJleHBpcmVzX2F0IjoyMDAwMDAwMDAwLCJwcm90b2NvbF9tYWpvciI6MSwic3RhdGVfc2NoZW1hIjoxLCJtaW5pbXVtX3VwZGF0ZXJfdmVyc2lvbiI6MSwiYXJ0aWZhY3RzIjpbeyJyb2xlIjoiYWdlbnQiLCJhcnRpZmFjdF9pZCI6IjExMTExMTExLTExMTEtNDExMS04MTExLTAwMDAwMDAwMDAwYiIsInNoYTI1NiI6IjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIiLCJieXRlcyI6MzAwMDAwN30seyJyb2xlIjoiaGVscGVyIiwiYXJ0aWZhY3RfaWQiOiIxMTExMTExMS0xMTExLTQxMTEtODExMS0wMDAwMDAwMDAwMGMiLCJzaGEyNTYiOiIwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0IiwiYnl0ZXMiOjIwMDAwMDl9XX0", + "schema_version": 1, + "signature": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ" + }, + "release_envelope_sha256": "1e510550d2ce0ca00ada743228a166e975a661301941c1063a5b7eabe43f95e9", + "schema_version": 1, + "updater": { + "binary_sha256": "3030303030303030303030303030303030303030303030303030303030303030", + "health_key_pin_sha256": "3434343434343434343434343434343434343434343434343434343434343434", + "health_public_key_hex": "3333333333333333333333333333333333333333333333333333333333333333", + "keyring_generation": 1, + "keyring_sha256": "3232323232323232323232323232323232323232323232323232323232323232", + "policy_sha256": "3131313131313131313131313131313131313131313131313131313131313131" + } + } + }, + "agent_id": "11111111-1111-4111-8111-000000000003", + "asset_id": "11111111-1111-4111-8111-000000000002", + "assignment_version": 1, + "attempt_id": "11111111-1111-4111-8111-000000000005", + "enrollment_generation": 1, + "execution_identity": "system", + "job_id": "11111111-1111-4111-8111-000000000004", + "max_output_bytes": 65536, + "max_runtime_seconds": 600, + "not_before": "2030-01-01T12:00:00Z", + "schema_version": 1, + "start_before": "2030-01-01T12:10:00Z", + "tenant_id": "11111111-1111-4111-8111-000000000001" + }, + "script_sha256": null + } + ], + "max_parallel": 1, + "plan_id": "11111111-1111-4111-8111-000000000006", + "principal": "codec-fixture-only", + "reason": "Nur Codec: vollständiges Codepaar – keine Releasefreigabe", + "schema_version": 1, + "tenant_id": "11111111-1111-4111-8111-000000000001" + }, + "plan_hash": "c27ead7aa9b00acc61a1b69b40bed453a749831725249c848280fb7b1e48b8d4", + "plan_id": "11111111-1111-4111-8111-000000000006", + "plan_payload": { + "artifact_references": [ + { + "artifact": { + "artifact_id": "11111111-1111-4111-8111-00000000000b", + "sha256": "0202020202020202020202020202020202020202020202020202020202020202", + "size_bytes": 3000007 + }, + "attempt_id": "11111111-1111-4111-8111-000000000005", + "job_id": "11111111-1111-4111-8111-000000000004" + }, + { + "artifact": { + "artifact_id": "11111111-1111-4111-8111-00000000000c", + "sha256": "0404040404040404040404040404040404040404040404040404040404040404", + "size_bytes": 2000009 + }, + "attempt_id": "11111111-1111-4111-8111-000000000005", + "job_id": "11111111-1111-4111-8111-000000000004" + } + ], + "halt_after_failures": 1, + "jobs": [ + { + "job_payload_hash": "3c78ca7a1f29191236a132e195f2379d8b9ad57ed3f05218f31e234be60d491a", + "payload": { + "action": { + "action": "update_agent", + "update": { + "health_profile": "mtls_inventory_sync_v1", + "health_timeout_seconds": 180, + "manifest_sha256": "0a821a915cc9cd954801c1d6feca591fbe853bc4781376a84982a997484e3166", + "no_reboot": true, + "peer_pin_transition": { + "new_pin_sha256": "1414141414141414141414141414141414141414141414141414141414141414", + "new_settings_sha256": "1212121212121212121212121212121212121212121212121212121212121212", + "old_pin_sha256": "1313131313131313131313131313131313131313131313131313131313131313", + "old_settings_sha256": "1111111111111111111111111111111111111111111111111111111111111111", + "profile": "windows_code_pair_v1" + }, + "predecessor": { + "agent_sha256": "0101010101010101010101010101010101010101010101010101010101010101", + "helper_sha256": "0303030303030303030303030303030303030303030303030303030303030303", + "installed_record_sha256": "2121212121212121212121212121212121212121212121212121212121212121", + "manifest_sha256": "2020202020202020202020202020202020202020202020202020202020202020", + "release_id": "11111111-1111-4111-8111-000000000009", + "release_sequence": 1 + }, + "profile": "fixed_code_pair_v1", + "recovery": "restore_exact_predecessor_once", + "release_envelope": { + "key_id": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "payload_bytes": "eyJzY2hlbWFfdmVyc2lvbiI6MSwicmVsZWFzZV9pZCI6IjExMTExMTExLTExMTEtNDExMS04MTExLTAwMDAwMDAwMDAwYSIsInJlbGVhc2Vfc2VxdWVuY2UiOjIsInZlcnNpb24iOiIwLjEuMS10ZXN0IiwicGxhdGZvcm0iOiJ4ODZfNjQtcGMtd2luZG93cy1tc3ZjIiwicHVibGlzaGVkX2F0IjoxNzkwMDAwMDAwLCJleHBpcmVzX2F0IjoyMDAwMDAwMDAwLCJwcm90b2NvbF9tYWpvciI6MSwic3RhdGVfc2NoZW1hIjoxLCJtaW5pbXVtX3VwZGF0ZXJfdmVyc2lvbiI6MSwiYXJ0aWZhY3RzIjpbeyJyb2xlIjoiYWdlbnQiLCJhcnRpZmFjdF9pZCI6IjExMTExMTExLTExMTEtNDExMS04MTExLTAwMDAwMDAwMDAwYiIsInNoYTI1NiI6IjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIwMjAyMDIiLCJieXRlcyI6MzAwMDAwN30seyJyb2xlIjoiaGVscGVyIiwiYXJ0aWZhY3RfaWQiOiIxMTExMTExMS0xMTExLTQxMTEtODExMS0wMDAwMDAwMDAwMGMiLCJzaGEyNTYiOiIwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0MDQwNDA0IiwiYnl0ZXMiOjIwMDAwMDl9XX0", + "schema_version": 1, + "signature": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ" + }, + "release_envelope_sha256": "1e510550d2ce0ca00ada743228a166e975a661301941c1063a5b7eabe43f95e9", + "schema_version": 1, + "updater": { + "binary_sha256": "3030303030303030303030303030303030303030303030303030303030303030", + "health_key_pin_sha256": "3434343434343434343434343434343434343434343434343434343434343434", + "health_public_key_hex": "3333333333333333333333333333333333333333333333333333333333333333", + "keyring_generation": 1, + "keyring_sha256": "3232323232323232323232323232323232323232323232323232323232323232", + "policy_sha256": "3131313131313131313131313131313131313131313131313131313131313131" + } + } + }, + "agent_id": "11111111-1111-4111-8111-000000000003", + "asset_id": "11111111-1111-4111-8111-000000000002", + "assignment_version": 1, + "attempt_id": "11111111-1111-4111-8111-000000000005", + "enrollment_generation": 1, + "execution_identity": "system", + "job_id": "11111111-1111-4111-8111-000000000004", + "max_output_bytes": 65536, + "max_runtime_seconds": 600, + "not_before": "2030-01-01T12:00:00Z", + "schema_version": 1, + "start_before": "2030-01-01T12:10:00Z", + "tenant_id": "11111111-1111-4111-8111-000000000001" + }, + "script_sha256": null + } + ], + "max_parallel": 1, + "plan_id": "11111111-1111-4111-8111-000000000006", + "principal": "codec-fixture-only", + "reason": "Nur Codec: vollständiges Codepaar – keine Releasefreigabe", + "schema_version": 1, + "tenant_id": "11111111-1111-4111-8111-000000000001" + }, + "plan_payload_bytes": [ + 123, + 34, + 115, + 99, + 104, + 101, + 109, + 97, + 95, + 118, + 101, + 114, + 115, + 105, + 111, + 110, + 34, + 58, + 49, + 44, + 34, + 112, + 108, + 97, + 110, + 95, + 105, + 100, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 45, + 49, + 49, + 49, + 49, + 45, + 52, + 49, + 49, + 49, + 45, + 56, + 49, + 49, + 49, + 45, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 54, + 34, + 44, + 34, + 116, + 101, + 110, + 97, + 110, + 116, + 95, + 105, + 100, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 45, + 49, + 49, + 49, + 49, + 45, + 52, + 49, + 49, + 49, + 45, + 56, + 49, + 49, + 49, + 45, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 49, + 34, + 44, + 34, + 112, + 114, + 105, + 110, + 99, + 105, + 112, + 97, + 108, + 34, + 58, + 34, + 99, + 111, + 100, + 101, + 99, + 45, + 102, + 105, + 120, + 116, + 117, + 114, + 101, + 45, + 111, + 110, + 108, + 121, + 34, + 44, + 34, + 114, + 101, + 97, + 115, + 111, + 110, + 34, + 58, + 34, + 78, + 117, + 114, + 32, + 67, + 111, + 100, + 101, + 99, + 58, + 32, + 118, + 111, + 108, + 108, + 115, + 116, + 195, + 164, + 110, + 100, + 105, + 103, + 101, + 115, + 32, + 67, + 111, + 100, + 101, + 112, + 97, + 97, + 114, + 32, + 226, + 128, + 147, + 32, + 107, + 101, + 105, + 110, + 101, + 32, + 82, + 101, + 108, + 101, + 97, + 115, + 101, + 102, + 114, + 101, + 105, + 103, + 97, + 98, + 101, + 34, + 44, + 34, + 106, + 111, + 98, + 115, + 34, + 58, + 91, + 123, + 34, + 112, + 97, + 121, + 108, + 111, + 97, + 100, + 34, + 58, + 123, + 34, + 115, + 99, + 104, + 101, + 109, + 97, + 95, + 118, + 101, + 114, + 115, + 105, + 111, + 110, + 34, + 58, + 49, + 44, + 34, + 116, + 101, + 110, + 97, + 110, + 116, + 95, + 105, + 100, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 45, + 49, + 49, + 49, + 49, + 45, + 52, + 49, + 49, + 49, + 45, + 56, + 49, + 49, + 49, + 45, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 49, + 34, + 44, + 34, + 97, + 115, + 115, + 101, + 116, + 95, + 105, + 100, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 45, + 49, + 49, + 49, + 49, + 45, + 52, + 49, + 49, + 49, + 45, + 56, + 49, + 49, + 49, + 45, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 50, + 34, + 44, + 34, + 97, + 103, + 101, + 110, + 116, + 95, + 105, + 100, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 45, + 49, + 49, + 49, + 49, + 45, + 52, + 49, + 49, + 49, + 45, + 56, + 49, + 49, + 49, + 45, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 51, + 34, + 44, + 34, + 101, + 110, + 114, + 111, + 108, + 108, + 109, + 101, + 110, + 116, + 95, + 103, + 101, + 110, + 101, + 114, + 97, + 116, + 105, + 111, + 110, + 34, + 58, + 49, + 44, + 34, + 97, + 115, + 115, + 105, + 103, + 110, + 109, + 101, + 110, + 116, + 95, + 118, + 101, + 114, + 115, + 105, + 111, + 110, + 34, + 58, + 49, + 44, + 34, + 106, + 111, + 98, + 95, + 105, + 100, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 45, + 49, + 49, + 49, + 49, + 45, + 52, + 49, + 49, + 49, + 45, + 56, + 49, + 49, + 49, + 45, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 52, + 34, + 44, + 34, + 97, + 116, + 116, + 101, + 109, + 112, + 116, + 95, + 105, + 100, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 45, + 49, + 49, + 49, + 49, + 45, + 52, + 49, + 49, + 49, + 45, + 56, + 49, + 49, + 49, + 45, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 53, + 34, + 44, + 34, + 97, + 99, + 116, + 105, + 111, + 110, + 34, + 58, + 123, + 34, + 97, + 99, + 116, + 105, + 111, + 110, + 34, + 58, + 34, + 117, + 112, + 100, + 97, + 116, + 101, + 95, + 97, + 103, + 101, + 110, + 116, + 34, + 44, + 34, + 117, + 112, + 100, + 97, + 116, + 101, + 34, + 58, + 123, + 34, + 115, + 99, + 104, + 101, + 109, + 97, + 95, + 118, + 101, + 114, + 115, + 105, + 111, + 110, + 34, + 58, + 49, + 44, + 34, + 112, + 114, + 111, + 102, + 105, + 108, + 101, + 34, + 58, + 34, + 102, + 105, + 120, + 101, + 100, + 95, + 99, + 111, + 100, + 101, + 95, + 112, + 97, + 105, + 114, + 95, + 118, + 49, + 34, + 44, + 34, + 114, + 101, + 108, + 101, + 97, + 115, + 101, + 95, + 101, + 110, + 118, + 101, + 108, + 111, + 112, + 101, + 34, + 58, + 123, + 34, + 115, + 99, + 104, + 101, + 109, + 97, + 95, + 118, + 101, + 114, + 115, + 105, + 111, + 110, + 34, + 58, + 49, + 44, + 34, + 107, + 101, + 121, + 95, + 105, + 100, + 34, + 58, + 34, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 34, + 44, + 34, + 112, + 97, + 121, + 108, + 111, + 97, + 100, + 95, + 98, + 121, + 116, + 101, + 115, + 34, + 58, + 34, + 101, + 121, + 74, + 122, + 89, + 50, + 104, + 108, + 98, + 87, + 70, + 102, + 100, + 109, + 86, + 121, + 99, + 50, + 108, + 118, + 98, + 105, + 73, + 54, + 77, + 83, + 119, + 105, + 99, + 109, + 86, + 115, + 90, + 87, + 70, + 122, + 90, + 86, + 57, + 112, + 90, + 67, + 73, + 54, + 73, + 106, + 69, + 120, + 77, + 84, + 69, + 120, + 77, + 84, + 69, + 120, + 76, + 84, + 69, + 120, + 77, + 84, + 69, + 116, + 78, + 68, + 69, + 120, + 77, + 83, + 48, + 52, + 77, + 84, + 69, + 120, + 76, + 84, + 65, + 119, + 77, + 68, + 65, + 119, + 77, + 68, + 65, + 119, + 77, + 68, + 65, + 119, + 89, + 83, + 73, + 115, + 73, + 110, + 74, + 108, + 98, + 71, + 86, + 104, + 99, + 50, + 86, + 102, + 99, + 50, + 86, + 120, + 100, + 87, + 86, + 117, + 89, + 50, + 85, + 105, + 79, + 106, + 73, + 115, + 73, + 110, + 90, + 108, + 99, + 110, + 78, + 112, + 98, + 50, + 52, + 105, + 79, + 105, + 73, + 119, + 76, + 106, + 69, + 117, + 77, + 83, + 49, + 48, + 90, + 88, + 78, + 48, + 73, + 105, + 119, + 105, + 99, + 71, + 120, + 104, + 100, + 71, + 90, + 118, + 99, + 109, + 48, + 105, + 79, + 105, + 74, + 52, + 79, + 68, + 90, + 102, + 78, + 106, + 81, + 116, + 99, + 71, + 77, + 116, + 100, + 50, + 108, + 117, + 90, + 71, + 57, + 51, + 99, + 121, + 49, + 116, + 99, + 51, + 90, + 106, + 73, + 105, + 119, + 105, + 99, + 72, + 86, + 105, + 98, + 71, + 108, + 122, + 97, + 71, + 86, + 107, + 88, + 50, + 70, + 48, + 73, + 106, + 111, + 120, + 78, + 122, + 107, + 119, + 77, + 68, + 65, + 119, + 77, + 68, + 65, + 119, + 76, + 67, + 74, + 108, + 101, + 72, + 66, + 112, + 99, + 109, + 86, + 122, + 88, + 50, + 70, + 48, + 73, + 106, + 111, + 121, + 77, + 68, + 65, + 119, + 77, + 68, + 65, + 119, + 77, + 68, + 65, + 119, + 76, + 67, + 74, + 119, + 99, + 109, + 57, + 48, + 98, + 50, + 78, + 118, + 98, + 70, + 57, + 116, + 89, + 87, + 112, + 118, + 99, + 105, + 73, + 54, + 77, + 83, + 119, + 105, + 99, + 51, + 82, + 104, + 100, + 71, + 86, + 102, + 99, + 50, + 78, + 111, + 90, + 87, + 49, + 104, + 73, + 106, + 111, + 120, + 76, + 67, + 74, + 116, + 97, + 87, + 53, + 112, + 98, + 88, + 86, + 116, + 88, + 51, + 86, + 119, + 90, + 71, + 70, + 48, + 90, + 88, + 74, + 102, + 100, + 109, + 86, + 121, + 99, + 50, + 108, + 118, + 98, + 105, + 73, + 54, + 77, + 83, + 119, + 105, + 89, + 88, + 74, + 48, + 97, + 87, + 90, + 104, + 89, + 51, + 82, + 122, + 73, + 106, + 112, + 98, + 101, + 121, + 74, + 121, + 98, + 50, + 120, + 108, + 73, + 106, + 111, + 105, + 89, + 87, + 100, + 108, + 98, + 110, + 81, + 105, + 76, + 67, + 74, + 104, + 99, + 110, + 82, + 112, + 90, + 109, + 70, + 106, + 100, + 70, + 57, + 112, + 90, + 67, + 73, + 54, + 73, + 106, + 69, + 120, + 77, + 84, + 69, + 120, + 77, + 84, + 69, + 120, + 76, + 84, + 69, + 120, + 77, + 84, + 69, + 116, + 78, + 68, + 69, + 120, + 77, + 83, + 48, + 52, + 77, + 84, + 69, + 120, + 76, + 84, + 65, + 119, + 77, + 68, + 65, + 119, + 77, + 68, + 65, + 119, + 77, + 68, + 65, + 119, + 89, + 105, + 73, + 115, + 73, + 110, + 78, + 111, + 89, + 84, + 73, + 49, + 78, + 105, + 73, + 54, + 73, + 106, + 65, + 121, + 77, + 68, + 73, + 119, + 77, + 106, + 65, + 121, + 77, + 68, + 73, + 119, + 77, + 106, + 65, + 121, + 77, + 68, + 73, + 119, + 77, + 106, + 65, + 121, + 77, + 68, + 73, + 119, + 77, + 106, + 65, + 121, + 77, + 68, + 73, + 119, + 77, + 106, + 65, + 121, + 77, + 68, + 73, + 119, + 77, + 106, + 65, + 121, + 77, + 68, + 73, + 119, + 77, + 106, + 65, + 121, + 77, + 68, + 73, + 119, + 77, + 106, + 65, + 121, + 77, + 68, + 73, + 119, + 77, + 106, + 65, + 121, + 77, + 68, + 73, + 119, + 77, + 106, + 65, + 121, + 77, + 68, + 73, + 105, + 76, + 67, + 74, + 105, + 101, + 88, + 82, + 108, + 99, + 121, + 73, + 54, + 77, + 122, + 65, + 119, + 77, + 68, + 65, + 119, + 78, + 51, + 48, + 115, + 101, + 121, + 74, + 121, + 98, + 50, + 120, + 108, + 73, + 106, + 111, + 105, + 97, + 71, + 86, + 115, + 99, + 71, + 86, + 121, + 73, + 105, + 119, + 105, + 89, + 88, + 74, + 48, + 97, + 87, + 90, + 104, + 89, + 51, + 82, + 102, + 97, + 87, + 81, + 105, + 79, + 105, + 73, + 120, + 77, + 84, + 69, + 120, + 77, + 84, + 69, + 120, + 77, + 83, + 48, + 120, + 77, + 84, + 69, + 120, + 76, + 84, + 81, + 120, + 77, + 84, + 69, + 116, + 79, + 68, + 69, + 120, + 77, + 83, + 48, + 119, + 77, + 68, + 65, + 119, + 77, + 68, + 65, + 119, + 77, + 68, + 65, + 119, + 77, + 71, + 77, + 105, + 76, + 67, + 74, + 122, + 97, + 71, + 69, + 121, + 78, + 84, + 89, + 105, + 79, + 105, + 73, + 119, + 78, + 68, + 65, + 48, + 77, + 68, + 81, + 119, + 78, + 68, + 65, + 48, + 77, + 68, + 81, + 119, + 78, + 68, + 65, + 48, + 77, + 68, + 81, + 119, + 78, + 68, + 65, + 48, + 77, + 68, + 81, + 119, + 78, + 68, + 65, + 48, + 77, + 68, + 81, + 119, + 78, + 68, + 65, + 48, + 77, + 68, + 81, + 119, + 78, + 68, + 65, + 48, + 77, + 68, + 81, + 119, + 78, + 68, + 65, + 48, + 77, + 68, + 81, + 119, + 78, + 68, + 65, + 48, + 77, + 68, + 81, + 119, + 78, + 68, + 65, + 48, + 77, + 68, + 81, + 119, + 78, + 68, + 65, + 48, + 73, + 105, + 119, + 105, + 89, + 110, + 108, + 48, + 90, + 88, + 77, + 105, + 79, + 106, + 73, + 119, + 77, + 68, + 65, + 119, + 77, + 68, + 108, + 57, + 88, + 88, + 48, + 34, + 44, + 34, + 115, + 105, + 103, + 110, + 97, + 116, + 117, + 114, + 101, + 34, + 58, + 34, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 69, + 66, + 65, + 81, + 34, + 125, + 44, + 34, + 114, + 101, + 108, + 101, + 97, + 115, + 101, + 95, + 101, + 110, + 118, + 101, + 108, + 111, + 112, + 101, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 49, + 101, + 53, + 49, + 48, + 53, + 53, + 48, + 100, + 50, + 99, + 101, + 48, + 99, + 97, + 48, + 48, + 97, + 100, + 97, + 55, + 52, + 51, + 50, + 50, + 56, + 97, + 49, + 54, + 54, + 101, + 57, + 55, + 53, + 97, + 54, + 54, + 49, + 51, + 48, + 49, + 57, + 52, + 49, + 99, + 49, + 48, + 54, + 51, + 97, + 53, + 98, + 55, + 101, + 97, + 98, + 101, + 52, + 51, + 102, + 57, + 53, + 101, + 57, + 34, + 44, + 34, + 109, + 97, + 110, + 105, + 102, + 101, + 115, + 116, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 48, + 97, + 56, + 50, + 49, + 97, + 57, + 49, + 53, + 99, + 99, + 57, + 99, + 100, + 57, + 53, + 52, + 56, + 48, + 49, + 99, + 49, + 100, + 54, + 102, + 101, + 99, + 97, + 53, + 57, + 49, + 102, + 98, + 101, + 56, + 53, + 51, + 98, + 99, + 52, + 55, + 56, + 49, + 51, + 55, + 54, + 97, + 56, + 52, + 57, + 56, + 50, + 97, + 57, + 57, + 55, + 52, + 56, + 52, + 101, + 51, + 49, + 54, + 54, + 34, + 44, + 34, + 112, + 114, + 101, + 100, + 101, + 99, + 101, + 115, + 115, + 111, + 114, + 34, + 58, + 123, + 34, + 114, + 101, + 108, + 101, + 97, + 115, + 101, + 95, + 105, + 100, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 45, + 49, + 49, + 49, + 49, + 45, + 52, + 49, + 49, + 49, + 45, + 56, + 49, + 49, + 49, + 45, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 57, + 34, + 44, + 34, + 114, + 101, + 108, + 101, + 97, + 115, + 101, + 95, + 115, + 101, + 113, + 117, + 101, + 110, + 99, + 101, + 34, + 58, + 49, + 44, + 34, + 109, + 97, + 110, + 105, + 102, + 101, + 115, + 116, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 34, + 44, + 34, + 105, + 110, + 115, + 116, + 97, + 108, + 108, + 101, + 100, + 95, + 114, + 101, + 99, + 111, + 114, + 100, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 34, + 44, + 34, + 97, + 103, + 101, + 110, + 116, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 48, + 49, + 34, + 44, + 34, + 104, + 101, + 108, + 112, + 101, + 114, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 34, + 125, + 44, + 34, + 117, + 112, + 100, + 97, + 116, + 101, + 114, + 34, + 58, + 123, + 34, + 98, + 105, + 110, + 97, + 114, + 121, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 51, + 48, + 34, + 44, + 34, + 112, + 111, + 108, + 105, + 99, + 121, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 34, + 44, + 34, + 107, + 101, + 121, + 114, + 105, + 110, + 103, + 95, + 103, + 101, + 110, + 101, + 114, + 97, + 116, + 105, + 111, + 110, + 34, + 58, + 49, + 44, + 34, + 107, + 101, + 121, + 114, + 105, + 110, + 103, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 51, + 50, + 34, + 44, + 34, + 104, + 101, + 97, + 108, + 116, + 104, + 95, + 112, + 117, + 98, + 108, + 105, + 99, + 95, + 107, + 101, + 121, + 95, + 104, + 101, + 120, + 34, + 58, + 34, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 34, + 44, + 34, + 104, + 101, + 97, + 108, + 116, + 104, + 95, + 107, + 101, + 121, + 95, + 112, + 105, + 110, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 51, + 52, + 34, + 125, + 44, + 34, + 112, + 101, + 101, + 114, + 95, + 112, + 105, + 110, + 95, + 116, + 114, + 97, + 110, + 115, + 105, + 116, + 105, + 111, + 110, + 34, + 58, + 123, + 34, + 112, + 114, + 111, + 102, + 105, + 108, + 101, + 34, + 58, + 34, + 119, + 105, + 110, + 100, + 111, + 119, + 115, + 95, + 99, + 111, + 100, + 101, + 95, + 112, + 97, + 105, + 114, + 95, + 118, + 49, + 34, + 44, + 34, + 111, + 108, + 100, + 95, + 115, + 101, + 116, + 116, + 105, + 110, + 103, + 115, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 34, + 44, + 34, + 110, + 101, + 119, + 95, + 115, + 101, + 116, + 116, + 105, + 110, + 103, + 115, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 49, + 50, + 34, + 44, + 34, + 111, + 108, + 100, + 95, + 112, + 105, + 110, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 49, + 51, + 34, + 44, + 34, + 110, + 101, + 119, + 95, + 112, + 105, + 110, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 49, + 52, + 34, + 125, + 44, + 34, + 114, + 101, + 99, + 111, + 118, + 101, + 114, + 121, + 34, + 58, + 34, + 114, + 101, + 115, + 116, + 111, + 114, + 101, + 95, + 101, + 120, + 97, + 99, + 116, + 95, + 112, + 114, + 101, + 100, + 101, + 99, + 101, + 115, + 115, + 111, + 114, + 95, + 111, + 110, + 99, + 101, + 34, + 44, + 34, + 104, + 101, + 97, + 108, + 116, + 104, + 95, + 112, + 114, + 111, + 102, + 105, + 108, + 101, + 34, + 58, + 34, + 109, + 116, + 108, + 115, + 95, + 105, + 110, + 118, + 101, + 110, + 116, + 111, + 114, + 121, + 95, + 115, + 121, + 110, + 99, + 95, + 118, + 49, + 34, + 44, + 34, + 104, + 101, + 97, + 108, + 116, + 104, + 95, + 116, + 105, + 109, + 101, + 111, + 117, + 116, + 95, + 115, + 101, + 99, + 111, + 110, + 100, + 115, + 34, + 58, + 49, + 56, + 48, + 44, + 34, + 110, + 111, + 95, + 114, + 101, + 98, + 111, + 111, + 116, + 34, + 58, + 116, + 114, + 117, + 101, + 125, + 125, + 44, + 34, + 101, + 120, + 101, + 99, + 117, + 116, + 105, + 111, + 110, + 95, + 105, + 100, + 101, + 110, + 116, + 105, + 116, + 121, + 34, + 58, + 34, + 115, + 121, + 115, + 116, + 101, + 109, + 34, + 44, + 34, + 110, + 111, + 116, + 95, + 98, + 101, + 102, + 111, + 114, + 101, + 34, + 58, + 34, + 50, + 48, + 51, + 48, + 45, + 48, + 49, + 45, + 48, + 49, + 84, + 49, + 50, + 58, + 48, + 48, + 58, + 48, + 48, + 90, + 34, + 44, + 34, + 115, + 116, + 97, + 114, + 116, + 95, + 98, + 101, + 102, + 111, + 114, + 101, + 34, + 58, + 34, + 50, + 48, + 51, + 48, + 45, + 48, + 49, + 45, + 48, + 49, + 84, + 49, + 50, + 58, + 49, + 48, + 58, + 48, + 48, + 90, + 34, + 44, + 34, + 109, + 97, + 120, + 95, + 114, + 117, + 110, + 116, + 105, + 109, + 101, + 95, + 115, + 101, + 99, + 111, + 110, + 100, + 115, + 34, + 58, + 54, + 48, + 48, + 44, + 34, + 109, + 97, + 120, + 95, + 111, + 117, + 116, + 112, + 117, + 116, + 95, + 98, + 121, + 116, + 101, + 115, + 34, + 58, + 54, + 53, + 53, + 51, + 54, + 125, + 44, + 34, + 106, + 111, + 98, + 95, + 112, + 97, + 121, + 108, + 111, + 97, + 100, + 95, + 104, + 97, + 115, + 104, + 34, + 58, + 34, + 51, + 99, + 55, + 56, + 99, + 97, + 55, + 97, + 49, + 102, + 50, + 57, + 49, + 57, + 49, + 50, + 51, + 54, + 97, + 49, + 51, + 50, + 101, + 49, + 57, + 53, + 102, + 50, + 51, + 55, + 57, + 100, + 56, + 98, + 57, + 97, + 100, + 53, + 55, + 101, + 100, + 51, + 102, + 48, + 53, + 50, + 49, + 56, + 102, + 51, + 49, + 101, + 50, + 51, + 52, + 98, + 101, + 54, + 48, + 100, + 52, + 57, + 49, + 97, + 34, + 44, + 34, + 115, + 99, + 114, + 105, + 112, + 116, + 95, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 110, + 117, + 108, + 108, + 125, + 93, + 44, + 34, + 109, + 97, + 120, + 95, + 112, + 97, + 114, + 97, + 108, + 108, + 101, + 108, + 34, + 58, + 49, + 44, + 34, + 104, + 97, + 108, + 116, + 95, + 97, + 102, + 116, + 101, + 114, + 95, + 102, + 97, + 105, + 108, + 117, + 114, + 101, + 115, + 34, + 58, + 49, + 44, + 34, + 97, + 114, + 116, + 105, + 102, + 97, + 99, + 116, + 95, + 114, + 101, + 102, + 101, + 114, + 101, + 110, + 99, + 101, + 115, + 34, + 58, + 91, + 123, + 34, + 106, + 111, + 98, + 95, + 105, + 100, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 45, + 49, + 49, + 49, + 49, + 45, + 52, + 49, + 49, + 49, + 45, + 56, + 49, + 49, + 49, + 45, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 52, + 34, + 44, + 34, + 97, + 116, + 116, + 101, + 109, + 112, + 116, + 95, + 105, + 100, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 45, + 49, + 49, + 49, + 49, + 45, + 52, + 49, + 49, + 49, + 45, + 56, + 49, + 49, + 49, + 45, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 53, + 34, + 44, + 34, + 97, + 114, + 116, + 105, + 102, + 97, + 99, + 116, + 34, + 58, + 123, + 34, + 97, + 114, + 116, + 105, + 102, + 97, + 99, + 116, + 95, + 105, + 100, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 45, + 49, + 49, + 49, + 49, + 45, + 52, + 49, + 49, + 49, + 45, + 56, + 49, + 49, + 49, + 45, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 98, + 34, + 44, + 34, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 48, + 50, + 34, + 44, + 34, + 115, + 105, + 122, + 101, + 95, + 98, + 121, + 116, + 101, + 115, + 34, + 58, + 51, + 48, + 48, + 48, + 48, + 48, + 55, + 125, + 125, + 44, + 123, + 34, + 106, + 111, + 98, + 95, + 105, + 100, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 45, + 49, + 49, + 49, + 49, + 45, + 52, + 49, + 49, + 49, + 45, + 56, + 49, + 49, + 49, + 45, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 52, + 34, + 44, + 34, + 97, + 116, + 116, + 101, + 109, + 112, + 116, + 95, + 105, + 100, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 45, + 49, + 49, + 49, + 49, + 45, + 52, + 49, + 49, + 49, + 45, + 56, + 49, + 49, + 49, + 45, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 53, + 34, + 44, + 34, + 97, + 114, + 116, + 105, + 102, + 97, + 99, + 116, + 34, + 58, + 123, + 34, + 97, + 114, + 116, + 105, + 102, + 97, + 99, + 116, + 95, + 105, + 100, + 34, + 58, + 34, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 45, + 49, + 49, + 49, + 49, + 45, + 52, + 49, + 49, + 49, + 45, + 56, + 49, + 49, + 49, + 45, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 99, + 34, + 44, + 34, + 115, + 104, + 97, + 50, + 53, + 54, + 34, + 58, + 34, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 48, + 52, + 34, + 44, + 34, + 115, + 105, + 122, + 101, + 95, + 98, + 121, + 116, + 101, + 115, + 34, + 58, + 50, + 48, + 48, + 48, + 48, + 48, + 57, + 125, + 125, + 93, + 125 + ], + "resolved_targets": [ + { + "agent_id": "11111111-1111-4111-8111-000000000003", + "asset_id": "11111111-1111-4111-8111-000000000002" + } + ] + } +} diff --git a/tests/agent_update/server-catalog.sql b/tests/agent_update/server-catalog.sql new file mode 100644 index 0000000..e177b4c --- /dev/null +++ b/tests/agent_update/server-catalog.sql @@ -0,0 +1,62 @@ +-- Isolated fresh PostgreSQL contract only; no product job/approval or signature +-- claim. Run as the migration identity after migrations 1..15 on a test DB. +SET ROLE rmm_app; +BEGIN; +SELECT set_config('app.tenant_id','11111111-1111-4111-8111-111111111111',true); +INSERT INTO agent_update_artifacts(tenant_id,artifact_id,sha256,size_bytes) VALUES + ('11111111-1111-4111-8111-111111111111','aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaa1',repeat('a',64),300001), + ('11111111-1111-4111-8111-111111111111','aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaa2',repeat('b',64),300003); +INSERT INTO agent_update_releases(tenant_id,release_id,platform,release_sequence,manifest_sha256,envelope_sha256,envelope,agent_artifact_id,agent_sha256,agent_bytes,helper_artifact_id,helper_sha256,helper_bytes) + VALUES('11111111-1111-4111-8111-111111111111','aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaa3','x86_64-unknown-linux-gnu',1,repeat('c',64),repeat('d',64),'{}','aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaa1',repeat('a',64),300001,'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaa2',repeat('b',64),300003); +COMMIT; +BEGIN; +SELECT set_config('app.tenant_id','22222222-2222-4222-8222-222222222222',true); +DO $$ BEGIN + IF (SELECT count(*) FROM agent_update_artifacts)<>0 OR (SELECT count(*) FROM agent_update_releases)<>0 THEN RAISE EXCEPTION 'foreign tenant visible'; END IF; + BEGIN + INSERT INTO agent_update_artifacts(tenant_id,artifact_id,sha256,size_bytes) VALUES('11111111-1111-4111-8111-111111111111','bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbb1',repeat('e',64),12); + RAISE EXCEPTION 'foreign tenant insert accepted'; + EXCEPTION WHEN insufficient_privilege THEN NULL; END; + BEGIN + INSERT INTO agent_update_releases(tenant_id,release_id,platform,release_sequence,manifest_sha256,envelope_sha256,envelope,agent_artifact_id,agent_sha256,agent_bytes,helper_artifact_id,helper_sha256,helper_bytes) + VALUES('22222222-2222-4222-8222-222222222222','bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbb3','x86_64-unknown-linux-gnu',1,repeat('c',64),repeat('d',64),'{}','aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaa1',repeat('a',64),300001,'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaa2',repeat('b',64),300003); + RAISE EXCEPTION 'cross tenant artifact foreign key accepted'; + EXCEPTION WHEN foreign_key_violation THEN NULL; END; +END $$; +COMMIT; +-- No tenant setting survived the preceding transaction on this same connection. +DO $$ BEGIN + IF (SELECT count(*) FROM agent_update_artifacts)<>0 OR (SELECT count(*) FROM agent_update_releases)<>0 THEN RAISE EXCEPTION 'tenant context leaked after commit'; END IF; + IF EXISTS(SELECT 1 FROM pg_roles WHERE rolname=current_user AND (rolsuper OR rolbypassrls)) OR EXISTS(SELECT 1 FROM pg_tables WHERE schemaname='public' AND tableowner=current_user) THEN RAISE EXCEPTION 'unsafe application role'; END IF; +END $$; +BEGIN; +SELECT set_config('app.tenant_id','11111111-1111-4111-8111-111111111111',true); +DO $$ BEGIN + IF (SELECT count(*) FROM agent_update_artifacts)<>2 OR (SELECT count(*) FROM agent_update_releases)<>1 THEN RAISE EXCEPTION 'own immutable catalog missing'; END IF; + BEGIN + UPDATE agent_update_artifacts SET sha256=repeat('f',64); + RAISE EXCEPTION 'application update accepted'; + EXCEPTION WHEN insufficient_privilege THEN NULL; END; + BEGIN + DELETE FROM agent_update_releases; + RAISE EXCEPTION 'application delete accepted'; + EXCEPTION WHEN insufficient_privilege THEN NULL; END; + IF (SELECT count(*) FROM jobs)<>0 OR (SELECT count(*) FROM outbox)<>0 OR (SELECT count(*) FROM execution_permits)<>0 OR (SELECT count(*) FROM authorizations)<>0 THEN RAISE EXCEPTION 'catalog created execution authority'; END IF; +END $$; +COMMIT; +RESET ROLE; +SET ROLE rmm_migrator; +BEGIN; +SELECT set_config('app.tenant_id','11111111-1111-4111-8111-111111111111',true); +DO $$ BEGIN + BEGIN + UPDATE agent_update_artifacts SET sha256=repeat('f',64); + RAISE EXCEPTION USING ERRCODE='XX000',MESSAGE='migration owner bypassed immutable object trigger'; + EXCEPTION WHEN raise_exception THEN NULL; END; + BEGIN + DELETE FROM agent_update_releases; + RAISE EXCEPTION USING ERRCODE='XX000',MESSAGE='migration owner bypassed immutable release trigger'; + EXCEPTION WHEN raise_exception THEN NULL; END; +END $$; +COMMIT; +SELECT 'agent-update-catalog-rls-immutable-no-execution: PASS'; diff --git a/web/src/agent-updates.test.tsx b/web/src/agent-updates.test.tsx new file mode 100644 index 0000000..8f117d2 --- /dev/null +++ b/web/src/agent-updates.test.tsx @@ -0,0 +1,68 @@ +import { readFileSync } from 'node:fs'; +import { expect, it, vi } from 'vitest'; +import { renderToStaticMarkup } from 'react-dom/server'; +import { PlanInput, record, RecordValue, Session, validateInput } from './api'; +import { sha256, validateSensitiveInput, verifyPlanIntegrity } from './safety'; +import { verifyScriptPlan } from './script-console'; +import { agentUpdateApprovalBlockers, agentUpdatePlanJobs, verifyAgentUpdatePlan, uploadAgentUpdateArtifact } from './agent-updates'; +vi.mock('react-dom/client', () => ({ createRoot: () => ({ render: vi.fn() }) })); +// Actual rmm-domain serde/codec output; synthetic signatures are NOT update trust. +const golden = JSON.parse(readFileSync(new URL('../../tests/agent_update/codec-golden.json', import.meta.url), 'utf8')) as Record; +const fixture = (name = 'linux_full') => structuredClone(golden[name]!) as RecordValue; +async function rehashed(change: (raw: RecordValue) => void): Promise { + const p = fixture(), raw = record(p.payload); change(raw); + const bytes = new TextEncoder().encode(JSON.stringify(raw)); p.plan_payload_bytes = Array.from(bytes); p.plan_hash = await sha256(bytes); + p.payload = raw; p.plan_payload = structuredClone(raw); return p; +} +it('verifies actual Rust Linux General/Full and Windows code-pair plan bytes before display', async () => { + for (const name of Object.keys(golden)) { + const p = fixture(name); expect(agentUpdateApprovalBlockers(p)).not.toEqual([]); + await verifyPlanIntegrity(p); await verifyScriptPlan(p); await verifyAgentUpdatePlan(p); + const jobs = agentUpdatePlanJobs(p); expect(jobs).toHaveLength(1); expect(jobs[0]!.identity).toBe(name === 'windows_pair' ? 'system' : 'root'); + expect(jobs[0]!.update.no_reboot).toBe(true); expect(agentUpdateApprovalBlockers(p)).toEqual([]); + jobs[0]!.update.no_reboot = false; expect(agentUpdatePlanJobs(p)[0]!.update.no_reboot).toBe(true); + } +}); +it('rejects even rehashed missing/extra artifact authority and inconsistent displayed or changed bytes', async () => { + for (const change of [(p: RecordValue) => { (p.artifact_references as unknown[]).pop(); }, (p: RecordValue) => { (p.artifact_references as unknown[]).push(structuredClone((p.artifact_references as unknown[])[0])); }]) { + await expect(verifyAgentUpdatePlan(await rehashed(change))).rejects.toThrow('Codepaarmenge'); + } + const p = fixture(); record(record((p.jobs as unknown[])[0]).payload).execution_identity = 'agent_service'; + await expect(verifyAgentUpdatePlan(p)).rejects.toThrow('Zielpreview'); + const q = fixture(); await verifyAgentUpdatePlan(q); q.resolved_targets = []; + expect(agentUpdateApprovalBlockers(q)).not.toEqual([]); + const during = fixture(), checking = verifyAgentUpdatePlan(during); during.plan_hash = 'f'.repeat(64); await expect(checking).rejects.toThrow(); +}); +it('shows all fixed update/recovery bindings without an approval or network side effect', async () => { + const fetch = vi.fn(); vi.stubGlobal('fetch', fetch); vi.stubGlobal('document', { getElementById: () => ({}) }); + try { + const { AgentUpdatePlanNotice } = await import('./main'); const p = fixture(); + expect(renderToStaticMarkup()).toContain('role="alert"'); + await verifyAgentUpdatePlan(p); const job = agentUpdatePlanJobs(p)[0]!, html = renderToStaticMarkup(); + for (const value of ['root', job.jobId, job.attemptId, job.assetId, job.jobHash, String(job.update.manifest_sha256), 'linux_general_full_v1', 'restore_exact_predecessor_once', 'keyring_sha256', 'health_public_key_hex', 'health_key_pin_sha256', '600s', '180s', 'Kein Hostneustart', 'unknown']) expect(html).toContain(value); + expect(html).not.toMatch(/<(button|input|form)\b/); expect(fetch).not.toHaveBeenCalled(); + } finally { vi.unstubAllGlobals(); } +}); +it('accepts only a release ID and separate update/root or update/SYSTEM rights at planning', async () => { + const input: PlanInput = { tenant_id: 'tenant', action: 'update_agent', targets: { asset_ids: ['asset'] }, parameters: { release_id: '11111111-1111-4111-8111-111111111111', execution_identity: 'root', timeout_seconds: 600, max_output_bytes: 65536 }, schedule: { not_before: new Date().toISOString(), start_before: new Date(Date.now() + 60000).toISOString(), offline_policy: 'wait_until_deadline' }, rollout: { max_parallel: 1, halt_after_failures: 1 }, reason: 'codec only' }; + const auth: Session = { principal: { id: 'unit', display_name: 'unit', simulated: true }, csrf_token: 'unit', tenants: [], permissions: ['updates:apply', 'root:execute'] }; + validateInput(input); await validateSensitiveInput(input, auth); + for (const permissions of [[], ['root:execute'], ['updates:apply'], ['updates:apply', 'system:execute'], ['scripts:execute', 'root:execute']]) await expect(validateSensitiveInput(input, { ...auth, permissions })).rejects.toThrow(); + for (const parameters of [{ ...input.parameters, predecessor: {} }, { ...input.parameters, execution_identity: 'agent_service' }, { ...input.parameters, timeout_seconds: 601 }, { ...input.parameters, max_output_bytes: 65537 }]) expect(() => validateInput({ ...input, parameters })).toThrow(); + expect(() => validateInput({ ...input, artifact_ids: [] })).toThrow(); +}); +it('streams only the selected File to its same-origin descriptor and rejects conflicting receipts', async () => { + const file = new File(['abc'], 'agent-code-only'), arrayBuffer = vi.spyOn(file, 'arrayBuffer').mockRejectedValue(new Error('application must not load the full binary')); + const descriptor = { artifact_id: '11111111-1111-4111-8111-111111111111', sha256: 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad', bytes: 3 }; + const reply = { artifact_id: descriptor.artifact_id, sha256: descriptor.sha256, size_bytes: 3 }; + const fetch = vi.fn().mockResolvedValue({ ok: true, status: 200, json: async () => reply }); vi.stubGlobal('fetch', fetch); + try { + expect(await uploadAgentUpdateArtifact('tenant', descriptor, file, 'unit-csrf')).toEqual(reply); + expect(fetch).toHaveBeenCalledWith(expect.stringMatching(/^\/api\/v1\/tenants\/tenant\/agent-update-artifacts\?/), expect.objectContaining({ body: file, credentials: 'same-origin', redirect: 'error', headers: { 'Content-Type': 'application/octet-stream', 'X-CSRF-Token': 'unit-csrf' } })); + expect(arrayBuffer).not.toHaveBeenCalled(); + await expect(uploadAgentUpdateArtifact('tenant', descriptor, new File(['abcd'], 'wrong-length'), 'unit-csrf')).rejects.toThrow('Dateigröße'); + expect(fetch).toHaveBeenCalledTimes(1); + fetch.mockResolvedValue({ ok: true, status: 200, json: async () => ({ ...reply, size_bytes: 4 }) }); + await expect(uploadAgentUpdateArtifact('tenant', descriptor, file, 'unit-csrf')).rejects.toThrow('Importbeleg'); + } finally { vi.unstubAllGlobals(); } +}); diff --git a/web/src/agent-updates.ts b/web/src/agent-updates.ts new file mode 100644 index 0000000..a3798a9 --- /dev/null +++ b/web/src/agent-updates.ts @@ -0,0 +1,124 @@ +import { ApiError, record, RecordValue, text, tenantPath } from './api'; + +export const agentUpdateWarning = 'AGENT-SELBSTUPDATE: Agent und privilegierte Helper werden vorübergehend gestoppt; die Geräteverwaltung kann ausfallen. Genau dieses signierte Codepaar und der gespeicherte Vorgänger sind gebunden. Einmalige Rückkehr nur zum erlaubten exakten Vorgängercode; keine Rücksetzung von Datenbank, Identität oder Historie. Kein Hostneustart und keine automatische Genehmigung. Ein unklarer Ausgang bleibt unknown.'; +function exact(value: RecordValue, fields: string[]) { if (Object.keys(value).some(k => !fields.includes(k)) || fields.some(k => !Object.hasOwn(value, k))) throw new Error('Agentupdate: vollständige bekannte Schemafelder erforderlich'); } +function integer(value: unknown, minimum = 1, maximum = Number.MAX_SAFE_INTEGER): number { if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < minimum || value > maximum) throw new Error('Agentupdate: festes Ganzzahllimit erforderlich'); return value; } +function digest(value: unknown): string { const hash = text(value, 'Agentupdate-SHA256'); if (!/^[a-f0-9]{64}$/.test(hash)) throw new Error('Agentupdate: exakter SHA256 erforderlich'); return hash; } +function uuid(value: unknown): string { const id = text(value, 'Agentupdate-ID'); if (!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(id) || id === '00000000-0000-0000-0000-000000000000') throw new Error('Agentupdate: feste UUID erforderlich'); return id; } +function same(left: unknown, right: unknown): boolean { + const canonical = (v: unknown): string => Array.isArray(v) ? `[${v.map(canonical).join(',')}]` : v && typeof v === 'object' ? `{${Object.entries(v).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, x]) => `${JSON.stringify(k)}:${canonical(x)}`).join(',')}}` : JSON.stringify(v); + return canonical(left) === canonical(right); +} +async function hash(bytes: Uint8Array): Promise { return Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)), n => n.toString(16).padStart(2, '0')).join(''); } +const utf8 = (value: unknown): Uint8Array => new TextEncoder().encode(JSON.stringify(value)); +function base64url(value: unknown, maximum: number): Uint8Array { + if (typeof value !== 'string' || !value || value.length > maximum || !/^[A-Za-z0-9_-]+$/.test(value)) throw new Error('Agentupdate: kanonisches Base64url erforderlich'); + const bytes = Uint8Array.from(atob(value.replaceAll('-', '+').replaceAll('_', '/') + '='.repeat((4 - value.length % 4) % 4)), c => c.charCodeAt(0)); + if (btoa(String.fromCharCode(...bytes)).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '') !== value) throw new Error('Agentupdate: nichtkanonisches Base64url'); + return bytes; +} +export interface ReleaseView { envelope: RecordValue; manifest: RecordValue; bytes: Uint8Array } +export function releaseEnvelope(value: unknown): ReleaseView { + const envelope = record(value); exact(envelope, ['schema_version', 'key_id', 'payload_bytes', 'signature']); + if (envelope.schema_version !== 1) throw new Error('Agentupdate: unbekanntes Envelopeschema'); + const bytes = base64url(envelope.payload_bytes, 21846), signature = base64url(envelope.signature, 86); + if (!bytes.length || bytes.length > 16384 || signature.length !== 64) throw new Error('Agentupdate: Manifest-/Signaturlimit'); + const m = record(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes))); + exact(m, ['schema_version', 'release_id', 'release_sequence', 'version', 'platform', 'published_at', 'expires_at', 'protocol_major', 'state_schema', 'minimum_updater_version', 'artifacts']); + if (m.schema_version !== 1 || !['x86_64-unknown-linux-gnu', 'x86_64-pc-windows-msvc'].includes(String(m.platform)) || typeof m.version !== 'string' || !/^[A-Za-z0-9.+_-]{1,64}$/.test(m.version) + || !Array.isArray(m.artifacts) || m.artifacts.length !== 2) throw new Error('Agentupdate: festes x64-Codepaar erforderlich'); + const artifacts = m.artifacts.map((value, index) => { const a = record(value); exact(a, ['role', 'artifact_id', 'sha256', 'bytes']); if (a.role !== ['agent', 'helper'][index]) throw new Error('Agentupdate: Agent-/Helperreihenfolge'); return { role: a.role, artifact_id: uuid(a.artifact_id), sha256: digest(a.sha256), bytes: integer(a.bytes, 1, 268435456) }; }); + if (artifacts[0]!.artifact_id === artifacts[1]!.artifact_id) throw new Error('Agentupdate: doppelte Artefakt-ID'); + const manifest = { schema_version: 1, release_id: uuid(m.release_id), release_sequence: integer(m.release_sequence), version: m.version, platform: m.platform, published_at: integer(m.published_at, 0), expires_at: integer(m.expires_at), protocol_major: integer(m.protocol_major), state_schema: integer(m.state_schema), minimum_updater_version: integer(m.minimum_updater_version), artifacts }; + if (manifest.expires_at <= manifest.published_at || new TextDecoder().decode(utf8(manifest)) !== new TextDecoder('utf-8', { fatal: true }).decode(bytes)) throw new Error('Agentupdate: exakte kanonische Manifestbytes erforderlich'); + return { envelope: { schema_version: 1, key_id: digest(envelope.key_id), payload_bytes: envelope.payload_bytes, signature: envelope.signature }, manifest, bytes }; +} +export async function verifyReleaseMetadata(value: unknown, expectedHash: unknown): Promise { + const release = releaseEnvelope(value); if (await hash(release.bytes) !== digest(expectedHash)) throw new Error('Agentupdate: Kataloghash widerspricht originalen Manifestbytes'); return release; +} +/** Browser sends the File body directly. It does not allocate a complete binary + * ArrayBuffer or export a session/token. Server verifies complete hash and EOF. */ +export async function uploadAgentUpdateArtifact(tenantId: string, descriptor: RecordValue, file: File, csrf: string): Promise { + const id = uuid(descriptor.artifact_id), expectedHash = digest(descriptor.sha256), size = integer(descriptor.bytes, 1, 268435456); + if (file.size !== size || !csrf) throw new Error('Agentupdate: ausgewählte Dateigröße oder interaktive Sitzung stimmt nicht'); + const query = new URLSearchParams({ artifact_id: id, sha256: expectedHash, size_bytes: String(size) }); + const response = await fetch(tenantPath(tenantId, `/agent-update-artifacts?${query}`), { method: 'POST', credentials: 'same-origin', cache: 'no-store', redirect: 'error', headers: { 'Content-Type': 'application/octet-stream', 'X-CSRF-Token': csrf }, body: file }); + const result = record(await response.json()); + if (!response.ok) throw new ApiError(response.status, String(result.code ?? 'HTTP_ERROR'), String(result.message ?? 'Import fehlgeschlagen'), String(result.correlation_id ?? '')); + exact(result, ['artifact_id', 'sha256', 'size_bytes']); + if (result.artifact_id !== id || result.sha256 !== expectedHash || result.size_bytes !== size) throw new Error('Agentupdate: Importbeleg widerspricht festem Artefakt'); + return result; +} +/** Shape only; signatures remain independently checked against provisioned trust + * at server and local helper. No public key from a job is trusted by the UI. */ +export function validateAgentUpdateAction(value: unknown, identity: unknown): RecordValue { + const action = record(value); exact(action, ['action', 'update']); if (action.action !== 'update_agent') throw new Error('Agentupdate: typisierte Aktion erforderlich'); + const u = record(action.update); exact(u, ['schema_version', 'profile', 'release_envelope', 'release_envelope_sha256', 'manifest_sha256', 'predecessor', 'updater', 'peer_pin_transition', 'recovery', 'health_profile', 'health_timeout_seconds', 'no_reboot']); + if (u.schema_version !== 1 || u.profile !== 'fixed_code_pair_v1' || u.recovery !== 'restore_exact_predecessor_once' || u.health_profile !== 'mtls_inventory_sync_v1' || u.health_timeout_seconds !== 180 || u.no_reboot !== true) throw new Error('Agentupdate: fester Apply-/Health-/No-Reboot-Vertrag erforderlich'); + const release = releaseEnvelope(u.release_envelope), linux = release.manifest.platform === 'x86_64-unknown-linux-gnu'; + if (identity !== (linux ? 'root' : 'system')) throw new Error('Agentupdate: Plattform und Root-/SYSTEM-Identität widersprechen sich'); + const old = record(u.predecessor); exact(old, ['release_id', 'release_sequence', 'manifest_sha256', 'installed_record_sha256', 'agent_sha256', 'helper_sha256']); + const predecessor = { release_id: uuid(old.release_id), release_sequence: integer(old.release_sequence), manifest_sha256: digest(old.manifest_sha256), installed_record_sha256: digest(old.installed_record_sha256), agent_sha256: digest(old.agent_sha256), helper_sha256: digest(old.helper_sha256) }; + if (predecessor.release_id === release.manifest.release_id || predecessor.release_sequence >= Number(release.manifest.release_sequence)) throw new Error('Agentupdate: exakter älterer Vorgänger erforderlich'); + const binding = record(u.updater); exact(binding, ['binary_sha256', 'policy_sha256', 'keyring_generation', 'keyring_sha256', 'health_public_key_hex', 'health_key_pin_sha256']); + const updater = { binary_sha256: digest(binding.binary_sha256), policy_sha256: digest(binding.policy_sha256), keyring_generation: integer(binding.keyring_generation), keyring_sha256: digest(binding.keyring_sha256), health_public_key_hex: digest(binding.health_public_key_hex), health_key_pin_sha256: digest(binding.health_key_pin_sha256) }; + const p = record(u.peer_pin_transition); let transition: RecordValue; + if (p.profile === 'unchanged_general_pin_v1') { exact(p, ['profile', 'general_pin_sha256']); if (!linux) throw new Error('Agentupdate: Linux-Pinprofil auf Windows'); transition = { profile: p.profile, general_pin_sha256: digest(p.general_pin_sha256) }; } + else if (p.profile === 'linux_general_full_v1') { + exact(p, ['profile', 'general_pin_sha256', 'full']); if (!linux) throw new Error('Agentupdate: Linux-Fullprofil auf Windows'); + const f = record(p.full); exact(f, ['schema_version', 'old_config_sha256', 'new_config_sha256', 'old_pin_sha256', 'new_pin_sha256', 'old_policy_sha256', 'new_policy_sha256', 'old_helper_sha256', 'new_helper_sha256', 'effective_signing_key_id']); + if (f.schema_version !== 1) throw new Error('Agentupdate: unbekanntes Fullpinschema'); + const full = { schema_version: 1, old_config_sha256: digest(f.old_config_sha256), new_config_sha256: digest(f.new_config_sha256), old_pin_sha256: digest(f.old_pin_sha256), new_pin_sha256: digest(f.new_pin_sha256), old_policy_sha256: digest(f.old_policy_sha256), new_policy_sha256: digest(f.new_policy_sha256), old_helper_sha256: digest(f.old_helper_sha256), new_helper_sha256: digest(f.new_helper_sha256), effective_signing_key_id: digest(f.effective_signing_key_id) }; + if (full.old_helper_sha256 !== predecessor.helper_sha256 || full.new_helper_sha256 !== record((release.manifest.artifacts as unknown[])[1]).sha256 || full.old_config_sha256 === full.new_config_sha256 || full.old_pin_sha256 === full.new_pin_sha256) throw new Error('Agentupdate: Fullpin-Codepaarbindung fehlt'); + transition = { profile: p.profile, general_pin_sha256: digest(p.general_pin_sha256), full }; + } else if (p.profile === 'windows_code_pair_v1') { + exact(p, ['profile', 'old_settings_sha256', 'new_settings_sha256', 'old_pin_sha256', 'new_pin_sha256']); if (linux) throw new Error('Agentupdate: Windows-Pinprofil auf Linux'); + transition = { profile: p.profile, old_settings_sha256: digest(p.old_settings_sha256), new_settings_sha256: digest(p.new_settings_sha256), old_pin_sha256: digest(p.old_pin_sha256), new_pin_sha256: digest(p.new_pin_sha256) }; + if (transition.old_settings_sha256 === transition.new_settings_sha256 || transition.old_pin_sha256 === transition.new_pin_sha256) throw new Error('Agentupdate: unveränderte Windows-Pinübergabe'); + } else throw new Error('Agentupdate: unbekannter Peerpinübergang'); + return { action: 'update_agent', update: { schema_version: 1, profile: 'fixed_code_pair_v1', release_envelope: release.envelope, release_envelope_sha256: digest(u.release_envelope_sha256), manifest_sha256: digest(u.manifest_sha256), predecessor, updater, peer_pin_transition: transition, recovery: 'restore_exact_predecessor_once', health_profile: 'mtls_inventory_sync_v1', health_timeout_seconds: 180, no_reboot: true } }; +} +export interface UpdatePlanJob { assetId: string; agentId: string; jobId: string; attemptId: string; identity: string; jobHash: string; update: RecordValue; manifest: RecordValue } +const verified = new WeakMap(); +const snapshot = (plan: RecordValue) => JSON.stringify(plan); +export async function verifyAgentUpdatePlan(plan: RecordValue): Promise { + const before = snapshot(plan), raw = plan.plan_payload_bytes; + if (!Array.isArray(raw) || !raw.length || raw.length > 1048576 || raw.some(n => !Number.isInteger(n) || n < 0 || n > 255) || await hash(new Uint8Array(raw)) !== digest(plan.plan_hash)) throw new Error('Agentupdate: gespeicherte Planbytes/Hash fehlen'); + const original = new TextDecoder('utf-8', { fatal: true }).decode(new Uint8Array(raw)), parsed = record(JSON.parse(original)); + if (!Array.isArray(parsed.jobs)) throw new Error('Agentupdate: feste Jobs fehlen'); + const list = parsed.jobs.map(value => record(value)); + if (!list.some(job => record(record(job.payload).action).action === 'update_agent')) { if (snapshot(plan) !== before) throw new Error('Plan während Prüfung verändert'); verified.set(plan, { snapshot: before, jobs: [] }); return; } + exact(parsed, ['schema_version', 'plan_id', 'tenant_id', 'principal', 'reason', 'jobs', 'max_parallel', 'halt_after_failures', 'artifact_references']); + if (parsed.schema_version !== 1 || !list.length || list.length > 100 || !Array.isArray(parsed.artifact_references) || parsed.artifact_references.length !== list.length * 2) throw new Error('Agentupdate: vollständige feste Codepaarmenge erforderlich'); + const jobs: UpdatePlanJob[] = [], payloads: RecordValue[] = [], fixedJobs: RecordValue[] = [], refs: RecordValue[] = [], seen = new Set(); + for (const job of list) { + exact(job, ['payload', 'job_payload_hash', 'script_sha256']); const p = record(job.payload); + exact(p, ['schema_version', 'tenant_id', 'asset_id', 'agent_id', 'enrollment_generation', 'assignment_version', 'job_id', 'attempt_id', 'action', 'execution_identity', 'not_before', 'start_before', 'max_runtime_seconds', 'max_output_bytes']); + const assetId = uuid(p.asset_id), jobId = uuid(p.job_id), attemptId = uuid(p.attempt_id), identity = text(p.execution_identity, 'Identität'); + if (p.schema_version !== 1 || p.tenant_id !== parsed.tenant_id || seen.has(assetId) || seen.has(jobId) || seen.has(attemptId) || job.script_sha256 !== null || p.max_runtime_seconds !== 600) throw new Error('Agentupdate: feste Geräte-/Versuchsbindung oder Gesamtbudget fehlt'); + [assetId, jobId, attemptId].forEach(id => seen.add(id)); integer(p.max_output_bytes, 1, 65536); + const action = validateAgentUpdateAction(p.action, identity), update = record(action.update), release = releaseEnvelope(update.release_envelope); + if (await hash(release.bytes) !== update.manifest_sha256 || await hash(utf8(release.envelope)) !== update.release_envelope_sha256) throw new Error('Agentupdate: originale Manifest-/Envelopehashbindung fehlt'); + const notBefore = text(p.not_before, 'Startzeit'), startBefore = text(p.start_before, 'Startfrist'); + if (!Number.isFinite(Date.parse(notBefore)) || !Number.isFinite(Date.parse(startBefore)) || Date.parse(startBefore) <= Date.parse(notBefore) || startBefore !== plan.expires_at) throw new Error('Agentupdate: feste Fristen widersprechen sich'); + const payload = { schema_version: 1, tenant_id: uuid(p.tenant_id), asset_id: assetId, agent_id: uuid(p.agent_id), enrollment_generation: integer(p.enrollment_generation), assignment_version: integer(p.assignment_version), job_id: jobId, attempt_id: attemptId, action, execution_identity: identity, not_before: notBefore, start_before: startBefore, max_runtime_seconds: 600, max_output_bytes: p.max_output_bytes }; + if (await hash(utf8(payload)) !== digest(job.job_payload_hash)) throw new Error('Agentupdate: feste Jobpayloadbytes stimmen nicht'); + payloads.push(payload); fixedJobs.push({ payload, job_payload_hash: job.job_payload_hash, script_sha256: null }); + for (const value of release.manifest.artifacts as unknown[]) { const a = record(value); refs.push({ job_id: jobId, attempt_id: attemptId, artifact: { artifact_id: a.artifact_id, sha256: a.sha256, size_bytes: a.bytes } }); } + jobs.push({ assetId, agentId: payload.agent_id, jobId, attemptId, identity, jobHash: String(job.job_payload_hash), update, manifest: release.manifest }); + } + if (!same(refs, parsed.artifact_references)) throw new Error('Agentupdate: zusätzliche/fehlende/doppelte Artefaktberechtigung'); + const rebuilt = { schema_version: 1, plan_id: uuid(parsed.plan_id), tenant_id: uuid(parsed.tenant_id), principal: text(parsed.principal, 'Antragsteller'), reason: text(parsed.reason, 'Begründung'), jobs: fixedJobs, max_parallel: integer(parsed.max_parallel, 1, 10), halt_after_failures: integer(parsed.halt_after_failures), artifact_references: refs }; + if (new TextDecoder().decode(utf8(rebuilt)) !== original || plan.plan_id !== parsed.plan_id) throw new Error('Agentupdate: exakte kanonische Planbytes erforderlich'); + for (const alias of ['payload', 'plan_payload']) if (plan[alias] !== undefined && !same(plan[alias], parsed)) throw new Error('Agentupdate: Planansicht widerspricht gespeicherten Bytes'); + if (!Array.isArray(plan.jobs) || plan.jobs.length !== jobs.length || !Array.isArray(plan.resolved_targets) || plan.resolved_targets.length !== jobs.length) throw new Error('Agentupdate: vollständige Zielansicht fehlt'); + for (let index = 0; index < jobs.length; index++) { + const fixed = jobs[index]!, view = record(plan.jobs[index]), target = record(plan.resolved_targets[index]); + if (!same(view.payload, payloads[index]) || view.job_payload_hash !== fixed.jobHash || ['asset_id', 'agent_id', 'job_id', 'attempt_id'].some(field => view[field] !== undefined && view[field] !== record(payloads[index])[field]) + || Object.keys(target).some(key => !['asset_id', 'agent_id'].includes(key)) || target.asset_id !== fixed.assetId || target.agent_id !== fixed.agentId) throw new Error('Agentupdate: Zielpreview widerspricht gespeicherten Bytes'); + } + if (snapshot(plan) !== before) throw new Error('Agentupdate: Plan während Prüfung verändert'); + verified.set(plan, { snapshot: before, jobs }); +} +export function agentUpdatePlanJobs(plan: RecordValue): UpdatePlanJob[] { const result = verified.get(plan); if (!result || result.snapshot !== snapshot(plan)) throw new Error('Agentupdateplan nicht unverändert verifiziert'); return structuredClone(result.jobs); } +export function agentUpdateApprovalBlockers(plan: RecordValue): string[] { try { agentUpdatePlanJobs(plan); return []; } catch (error) { return [error instanceof Error ? error.message : 'Agentupdateplan nicht verifiziert']; } } diff --git a/web/src/api.ts b/web/src/api.ts index 64e2d6e..dfc4a66 100644 --- a/web/src/api.ts +++ b/web/src/api.ts @@ -57,7 +57,7 @@ export const tenantPath = (id: string, suffix = '') => `/api/v1/tenants/${encode export const objectId = (r: RecordValue, kind: string) => text(r[`${kind}_id`] ?? r.id, `${kind}_id`); export const pretty = (v: unknown) => JSON.stringify(v, null, 2); -export const actions = ['run_script', 'refresh_inventory', 'query_logs', 'set_service_state', 'ensure_package', 'apply_updates', 'reboot', 'apt_native_acceptance'] as const; +export const actions = ['run_script', 'refresh_inventory', 'query_logs', 'set_service_state', 'ensure_package', 'apply_updates', 'reboot', 'apt_native_acceptance', 'update_agent'] as const; export type Action = typeof actions[number]; export const windowsPowerShellRemoteSignedProfile = 'powershell_51_remote_signed' as const; export const fullMaintenanceScriptProfile = 'full_maintenance_v1' as const; @@ -193,6 +193,12 @@ export function validateInput(input: PlanInput): void { if (profile === fullMaintenanceScriptProfile && (Number(input.parameters.timeout_seconds) > (variants.some(v => record(v).os_family === 'windows') ? 120 : 300) || Number(input.parameters.max_output_bytes) > 65536)) throw new Error('Vollwartung: Linux höchstens300s / Windows höchstens120s und65536Ausgabebytes'); } if (!['agent_service', 'root', 'system'].includes(String(input.parameters.execution_identity))) throw new Error('Explizite Ausführungsidentität erforderlich'); + if (input.action === 'update_agent') { + const p = input.parameters; + if (Object.keys(p).some(key => !['release_id', 'execution_identity', 'timeout_seconds', 'max_output_bytes'].includes(key)) || input.artifact_ids !== undefined + || !['root', 'system'].includes(String(p.execution_identity)) || p.timeout_seconds !== 600 || Number(p.max_output_bytes) > 65536) throw new Error('Agentupdate: nur feste Release-ID, Root/SYSTEM,600s/64KiB; keine freien Pins/Artefakte'); + msiUuid(p.release_id); return; + } if (input.parameters.execution_identity === 'system') { if (input.action === 'run_script') { if (privilegedScriptProfile(input.parameters, 'system') !== fullMaintenanceScriptProfile) throw new Error('SYSTEM-Skript benötigt ausdrücklich full_maintenance_v1'); diff --git a/web/src/main.tsx b/web/src/main.tsx index d6a328a..2aa2e24 100644 --- a/web/src/main.tsx +++ b/web/src/main.tsx @@ -7,9 +7,23 @@ import { allowed, availableActions, parseStrictJson, powerShellApprovalBlockers, import { Login } from './login'; import { ConsoleOutput, outputText } from './console-output'; import { scriptApprovalBlockers, scriptPlanJobs, verifyScriptPlan } from './script-console'; +import { agentUpdateWarning, agentUpdatePlanJobs, agentUpdateApprovalBlockers, verifyAgentUpdatePlan, verifyReleaseMetadata, releaseEnvelope, uploadAgentUpdateArtifact } from './agent-updates'; const errorText = (error: unknown) => error instanceof Error ? error.message : 'Unbekannter Fehler'; export function JsonView({ value, label = 'Vollständige Daten' }: { value: unknown; label?: string }) { return
{label}
{pretty(value)}
; } +export function AgentUpdatePlanNotice({ plan }: { plan: RecordValue }) { + try { + const jobs = agentUpdatePlanJobs(plan); if (!jobs.length) return null; + return

Vollständige feste Agent-Selbstupdates ({jobs.length})

{agentUpdateWarning}

+ {jobs.map(job =>

Asset {job.assetId}

Agent: {job.agentId} · Job: {job.jobId} · Versuch: {job.attemptId} · Identität: {job.identity}

+

Release: {String(job.manifest.release_id)} · Version: {String(job.manifest.version)} · Plattform: {String(job.manifest.platform)} · Sequenz: {String(job.manifest.release_sequence)}

+

Manifest-SHA256: {String(job.update.manifest_sha256)} · Job-SHA256: {job.jobHash}

+

Die folgenden Vorgänger-, Codepaar-, Updater-, Keyring- und Peerpinbindungen stammen vollständig aus den unveränderten gespeicherten Planbytes. Gesamtbudget600s, Healthfrist180s; keine allgemeine Reparatur oder neue Freigabe.

+ +
)} +
; + } catch { return ; } +} export function ScriptPlanNotice({ plan }: { plan: RecordValue }) { try { const jobs = scriptPlanJobs(plan); if (!jobs.length) return null; @@ -88,6 +102,7 @@ function Devices({ tenantId, auth, selected, setSelected }: { tenantId: string; } const initialParameters: Record = { run_script: {}, refresh_inventory: { scope: 'linux.base' }, query_logs: { unit: '', since: '', until: '', max_lines: 1000 }, set_service_state: { unit: '', state: 'running' }, ensure_package: { provider: 'apt', recipe_version: '', package: '', version: '', architecture: 'amd64', installation_context: 'system', apt_manifest: null }, apply_updates: { provider: 'apt', packages: [], reboot_policy: 'never', apt_manifest: null }, reboot: { reason: '', dependency_group: '', reconnect_timeout_seconds: 300 }, apt_native_acceptance: { recipe_id: 'rmm-apt-fixture-install-1.0', recipe_version: '1', apt_manifest: null }, + update_agent: { release_id: '' }, }; function Planner({ tenantId, auth, selected, showPlan }: { tenantId: string; auth: Session; selected: string[]; showPlan: (id: string) => void }) { const [scriptPlatform, setScriptPlatform] = useState('linux'), [mixedVariants, setMixedVariants] = useState('[]'); @@ -102,16 +117,17 @@ function Planner({ tenantId, auth, selected, showPlan }: { tenantId: string; aut validateInput(input); await validateSensitiveInput(input, auth); const plan = record(await request(tenantPath(tenantId, '/operation-plans'), { body: input, csrf: auth.csrf_token })); showPlan(objectId(plan, 'plan')); } catch (e) { setError(errorText(e)); } finally { setBusy(false); } }}> + {action === 'update_agent' &&

{agentUpdateWarning} Nur parameters.release_id aus dem Katalog; keine freien Vorgänger-, Dateipfad-, Artefakt- oder Policywerte. Gesamtbudget600s, Ausgabelimit höchstens65536Bytes. Fehlende frische Gerätepreview ergibt keine Planung.

} {action === 'query_logs' &&

Windows-MVP nur Quelle windows.eventlog.application.rustdiscovery-mvp-test, Kanal Application, Provider RustDiscovery-MVP-Test, agent_service. Festes UTC-Fenster höchstens24h,1–1000Events,1024–65536Bytes,äußere Joblaufzeit10–120s; inneres kooperatives Abfragebudget höchstens5000ms. Keine freie Kanal-/XPathauswahl und keine Bookmarkfortschreibung. Linux behält seine feste Journalunit.

} {action === 'apt_native_acceptance' &&

NUR SIMULIERTE DEV/TEST-NATIVABNAHME. In Vorbereitung; Backend/Helper/Scope müssen diese eigene Aktion unterstützen. Nur rmm-apt-fixture-install-1.0 oder rmm-apt-fixture-update-1.1, Rezeptversion 1, vollständiges Schema-2-Manifest. null/Platzhalter sind nicht konfiguriert, keine Produktionsaktion, keine automatische Ausführung.

} {action === 'run_script' ? <>{scriptPlatform === 'mixed' ?