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