diff --git a/crates/agent-core/src/helper_reconcile.rs b/crates/agent-core/src/helper_reconcile.rs index 5b4f0a9..c760aad 100644 --- a/crates/agent-core/src/helper_reconcile.rs +++ b/crates/agent-core/src/helper_reconcile.rs @@ -204,6 +204,10 @@ impl HelperSync { self.lease = None; self.capture = None; } + /// Read-only bound of the existing confirmed lease; creates no readiness. + pub fn validity_deadline(&self) -> Option> { + self.lease.as_ref().map(|lease| lease.until) + } pub fn active_generation(&self) -> Option { self.lease.as_ref().map(|lease| lease.generation) } diff --git a/crates/agent-core/src/lib.rs b/crates/agent-core/src/lib.rs index cb6a414..c7f6fb4 100644 --- a/crates/agent-core/src/lib.rs +++ b/crates/agent-core/src/lib.rs @@ -10,3 +10,4 @@ pub mod ledger; pub mod reconcile; pub mod update_handoff; pub mod update_health_inventory; +pub mod update_health_sync; diff --git a/crates/agent-core/src/update_health_sync.rs b/crates/agent-core/src/update_health_sync.rs new file mode 100644 index 0000000..ba8f314 --- /dev/null +++ b/crates/agent-core/src/update_health_sync.rs @@ -0,0 +1,323 @@ +//! Read-only original HelperSync evidence. Exact UTC bodies, not quantized +//! receipt scalars, bound the real local application time. Creates no lease. +use crate::{ + auth::Binding, + helper_reconcile::{ExecutorLedgerGuard, SignedResponse}, + reconcile::{Channel, verify_response}, + update_handoff::{self, AppliedUpdateSync}, +}; +use anyhow::{Context, Result, ensure}; +use chrono::{DateTime, Utc}; +use prost::Message; +use rmm_domain::{ + agent_update::{UpdateInflightProof, inflight_decision, verify_inflight_proof}, + jobs::hash, + reconciliation::ReconcileDecisionPayload, +}; +use rmm_protocol::{SyncRequest, SyncResponse}; +use rmm_updater_handoff::{Handoff, HealthReceipt, Phase}; +use rusqlite::Connection; +use uuid::Uuid; + +/// No deserializer or external construction. Raw request/response hashes and +/// actual local application come from the SAME guarded existing helper ledger. +pub struct Round { + applied: AppliedUpdateSync, + request: SyncRequest, + decision: ReconcileDecisionPayload, +} +impl Round { + pub fn applied(&self) -> &AppliedUpdateSync { + &self.applied + } + pub fn decision(&self) -> &ReconcileDecisionPayload { + &self.decision + } +} +pub fn read_round( + db: &Connection, + guard: &impl ExecutorLedgerGuard, + binding: &Binding, + grant: Uuid, + id: Uuid, +) -> Result { + guard.check(db)?; + let (request_len, response_len): (usize, usize) = db.query_row( + "SELECT length(request),length(response) FROM helper_sync_decisions WHERE decision_id=?1", + [id.to_string()], + |r| Ok((r.get(0)?, r.get(1)?)), + )?; + ensure!( + request_len > 0 + && request_len <= rmm_domain::MAX_MESSAGE + && response_len > 0 + && response_len <= 4 * rmm_domain::MAX_MESSAGE + 1024, + "UPDATE_HEALTH_STORED_SYNC_SIZE" + ); + let applied = update_handoff::read_applied_sync(db, guard, grant, id)?; + let (raw, signed): (Vec, Vec) = db.query_row( + "SELECT request,response FROM helper_sync_decisions WHERE decision_id=?1", + [id.to_string()], + |r| Ok((r.get(0)?, r.get(1)?)), + )?; + let request = SyncRequest::decode(raw.as_slice())?; + let signed: SignedResponse = serde_json::from_slice(&signed)?; + let response = SyncResponse { + decision_bytes: signed.decision_bytes, + signature: signed.signature, + }; + ensure!( + request.encode_to_vec() == raw + && hash(&raw) == applied.request_sha256 + && hash(&response.encode_to_vec()) == applied.response_protobuf_sha256, + "UPDATE_HEALTH_STORED_SYNC_BYTES" + ); + let unverified: ReconcileDecisionPayload = serde_json::from_slice(&response.decision_bytes)?; + // Historical verification only. Current clock/owner/boot/policy remain the + // calling Fullguard's independent prerequisites, never renewed by this read. + let decision = verify_response( + binding, + &request, + &Channel { + boot_id: unverified.boot_id, + connection_generation: unverified.connection_generation, + }, + &response, + unverified.issued_at, + )?; + ensure!( + decision.decision_id == id && serde_json::to_vec(&decision)? == response.decision_bytes, + "UPDATE_HEALTH_ORIGINAL_SYNC_CODEC" + ); + guard.check(db)?; + Ok(Round { + applied, + request, + decision, + }) +} +pub struct VerifiedSpan { + applied: AppliedUpdateSync, + lower: DateTime, + upper: DateTime, +} +impl VerifiedSpan { + pub fn applied(&self) -> &AppliedUpdateSync { + &self.applied + } + pub fn lower(&self) -> DateTime { + self.lower + } + pub fn upper(&self) -> DateTime { + self.upper + } +} +pub fn verified_span( + db: &Connection, + guard: &impl ExecutorLedgerGuard, + binding: &Binding, + header: &Handoff, + receipt: &HealthReceipt, + health_key: [u8; 32], +) -> Result { + guard.check(db)?; + let applied = read_round( + db, + guard, + binding, + header.attempt.grant_id, + receipt.signed_sync_decision_id, + )?; + ensure!( + applied.applied.request_sha256 == receipt.signed_sync_request_sha256 + && applied.applied.response_protobuf_sha256 == receipt.signed_sync_response_sha256 + && receipt.inventory_ack_sha256 == applied.applied.response_protobuf_sha256 + && applied + .decision + .acknowledged_message_ids + .contains(&receipt.inventory_message_id), + "UPDATE_HEALTH_ORIGINAL_APPLIED_OR_ACK" + ); + let prefix = services_prefix(&applied, header, receipt, health_key)?; + let original_prefix = UpdateInflightProof::from_bytes(&prefix).map_err(anyhow::Error::msg)?; + let current = update_handoff::current_proof(db, guard, header.attempt.grant_id)? + .context("UPDATE_HEALTH_ORIGINAL_CURRENT_PREFIX_MISSING")?; + ensure!( + original_prefix.delegation == current.delegation + && original_prefix.events.len() <= current.events.len() + && current.events[..original_prefix.events.len()] == original_prefix.events, + "UPDATE_HEALTH_ORIGINAL_PREFIX_NOT_RETAINED" + ); + let invalid:usize=db.query_row("SELECT count(*) FROM agent_update_sync_applied WHERE grant_id=?1 AND length(decision_id)<>36",[header.attempt.grant_id.to_string()],|r|r.get(0))?; + ensure!(invalid == 0, "UPDATE_HEALTH_ORIGINAL_SYNC_ID_SIZE"); + let mut query=db.prepare("SELECT decision_id FROM agent_update_sync_applied WHERE grant_id=?1 ORDER BY decision_id LIMIT 1025")?; + let ids = query + .query_map([header.attempt.grant_id.to_string()], |r| { + r.get::<_, String>(0) + })? + .collect::>>()?; + ensure!(ids.len() <= 1024, "UPDATE_HEALTH_ORIGINAL_SYNC_LIMIT"); + let mut confirming = None; + for id in ids { + let id: Uuid = id.parse()?; + if id == receipt.signed_sync_decision_id { + continue; + } + let (len,): (usize,) = db.query_row( + "SELECT length(request) FROM helper_sync_decisions WHERE decision_id=?1", + [id.to_string()], + |r| Ok((r.get(0)?,)), + )?; + ensure!( + len > 0 && len <= rmm_domain::MAX_MESSAGE, + "UPDATE_HEALTH_CONFIRMING_SIZE" + ); + let raw: Vec = db.query_row( + "SELECT request FROM helper_sync_decisions WHERE decision_id=?1", + [id.to_string()], + |r| r.get(0), + )?; + let request = SyncRequest::decode(raw.as_slice())?; + if request.previous_decision_id != receipt.signed_sync_decision_id.to_string() + || request.helper_previous_decision_id != receipt.signed_sync_decision_id.to_string() + { + continue; + } + // Hash/signature/application checks are mandatory AFTER this cheap + // candidate selection too. Caller request fields never prove an apply. + let round = read_round(db, guard, binding, header.attempt.grant_id, id)?; + ensure!( + services_prefix(&round, header, receipt, health_key)? == prefix && confirming.is_none(), + "UPDATE_HEALTH_CONFIRMING_PREFIX_OR_FORK" + ); + confirming = Some(round); + } + let confirming = confirming.context("UPDATE_HEALTH_ACTUAL_CONFIRMING_ROUND_MISSING")?; + require_exact_span( + applied.decision.issued_at, + applied.applied.applied_at, + confirming.decision.issued_at, + receipt.signed_sync_applied_at, + )?; + ensure!( + applied.applied.applied_at < applied.decision.valid_until, + "UPDATE_HEALTH_ACTUAL_APPLY_EXPIRED" + ); + guard.check(db)?; + Ok(VerifiedSpan { + applied: applied.applied, + lower: applied.decision.issued_at, + upper: confirming.decision.issued_at, + }) +} +fn services_prefix( + round: &Round, + header: &Handoff, + receipt: &HealthReceipt, + key: [u8; 32], +) -> Result> { + let request = &round.request; + let decision = &round.decision; + ensure!( + !decision.ready + && !decision.helper_ready + && request.journal_complete + && decision.connection_generation == receipt.connection_generation + && decision.boot_id == header.boot_id + && request.journal_id == header.agent_journal_id.to_string() + && request.helper_journal_id == header.helper_journal_id.to_string(), + "UPDATE_HEALTH_CONFIRMING_CHANNEL" + ); + let mut local = request.attempts.iter().filter(|a| { + a.job_id == header.attempt.job_id.to_string() + && a.attempt_id == header.attempt.attempt_id.to_string() + }); + let local = local + .next() + .context("UPDATE_HEALTH_ORIGINAL_ATTEMPT_MISSING")? + .clone(); + ensure!( + request + .attempts + .iter() + .filter(|a| a.job_id == header.attempt.job_id.to_string() + && a.attempt_id == header.attempt.attempt_id.to_string()) + .count() + == 1, + "UPDATE_HEALTH_ORIGINAL_ATTEMPT_DUPLICATE" + ); + let proof = + UpdateInflightProof::from_bytes(&local.update_handoff_bytes).map_err(anyhow::Error::msg)?; + let (observed, journal) = verify_inflight_proof(&proof, key).map_err(anyhow::Error::msg)?; + ensure!( + observed.bytes()? == header.bytes()? + && journal.phase() == Phase::ServicesStarted + && local.grant_id == header.attempt.grant_id.to_string() + && local.consumption == "consumed" + && local.state == "running" + && local.job_payload_hash == header.attempt.job_payload_sha256 + && 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(), + "UPDATE_HEALTH_ORIGINAL_INFLIGHT" + ); + let signed = decision + .attempts + .iter() + .filter(|a| a.job_id == header.attempt.job_id && a.attempt_id == header.attempt.attempt_id) + .collect::>(); + ensure!(signed.len() == 1, "UPDATE_HEALTH_SIGNED_ATTEMPT"); + let signed = signed[0]; + ensure!( + signed.update_inflight.as_ref() + == Some(&inflight_decision(&proof, key).map_err(anyhow::Error::msg)?) + && 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.execution_identity == "root" + && signed.outcome_state == "running" + && !signed.unlock + && signed.outcome_bytes.is_empty() + && signed.outcome_sha256.is_none(), + "UPDATE_HEALTH_SIGNED_ORIGINAL_INFLIGHT" + ); + Ok(local.update_handoff_bytes) +} +fn require_exact_span( + lower: DateTime, + actual: DateTime, + upper: DateTime, + wire_floor: u64, +) -> Result<()> { + ensure!( + lower <= actual && actual <= upper && wire_floor == u64::try_from(upper.timestamp())?, + "UPDATE_HEALTH_EXACT_ACTUAL_APPLY_SPAN" + ); + Ok(()) +} +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn same_floor_does_not_admit_a_one_nanosecond_early_or_late_apply() { + let base = DateTime::from_timestamp(1000, 0).unwrap(); + let lower = base + chrono::Duration::nanoseconds(100_000_001); + let upper = base + chrono::Duration::nanoseconds(200_000_001); + assert_eq!(lower.timestamp(), upper.timestamp()); + require_exact_span(lower, lower, upper, 1000).unwrap(); + require_exact_span(lower, upper, upper, 1000).unwrap(); + assert!( + require_exact_span(lower, lower - chrono::Duration::nanoseconds(1), upper, 1000) + .is_err() + ); + assert!( + require_exact_span(lower, upper + chrono::Duration::nanoseconds(1), upper, 1000) + .is_err() + ); + assert!(require_exact_span(lower, lower, upper, 1001).is_err()); + } +} diff --git a/crates/agent-core/tests/helper_reconcile.rs b/crates/agent-core/tests/helper_reconcile.rs index 19349ab..86a3b8a 100644 --- a/crates/agent-core/tests/helper_reconcile.rs +++ b/crates/agent-core/tests/helper_reconcile.rs @@ -984,11 +984,13 @@ fn clean_ready_shared_lock_and_reopen_start_closed() { let mut f = Fixture::new(); let mut sync = f.sync(); assert!(!sync.can_start(&f.db, &f.guard, 1, &f.clock, &f.boot)); + assert_eq!(sync.validity_deadline(), None); let snapshot = f.snapshot(&mut sync, 1); let raw = f.request(&snapshot); let d = f.decision(&snapshot, &raw, 1, true); let applied = f.apply(&mut sync, &d, &raw).unwrap(); assert!(applied.ready); + assert_eq!(sync.validity_deadline(), Some(d.valid_until)); assert_eq!(sync.active_generation(), Some(1)); assert_eq!(applied.snapshot.previous_decision_id, Some(d.decision_id)); assert!(applied.unlocked_grants.is_empty()); @@ -1004,6 +1006,7 @@ fn clean_ready_shared_lock_and_reopen_start_closed() { .is_err() ); sync.close(); + assert_eq!(sync.validity_deadline(), None); assert!(!sync.can_start(&f.db, &f.guard, 1, &f.clock, &f.boot)); } #[test] @@ -1784,6 +1787,17 @@ fn update_inflight_negative_control_keeps_every_start_closed_and_owner_loss_is_t decision.decision_id, ) .unwrap(); + let retained_round = rmm_agent_core::update_health_sync::read_round( + &f.db, + &guard, + &f.binding, + handoff.attempt.grant_id, + decision.decision_id, + ) + .unwrap(); + assert_eq!(retained_round.applied(), &local_apply); + assert_eq!(retained_round.decision().issued_at, decision.issued_at); + assert_eq!(retained_round.decision().valid_until, decision.valid_until); assert_eq!(local_apply.applied_at, f.clock.now); assert_eq!(local_apply.request_sha256, hash(&raw)); let proto = rmm_protocol::SyncResponse { diff --git a/crates/privileged-helper/src/update_guard.rs b/crates/privileged-helper/src/update_guard.rs index 9836e67..6eb0fc3 100644 --- a/crates/privileged-helper/src/update_guard.rs +++ b/crates/privileged-helper/src/update_guard.rs @@ -335,38 +335,15 @@ impl<'a> FullUpdateGuard<'a> { "UPDATE_HEALTH_CURRENT_LOCAL_CHANNEL_REQUIRED" ); self.verify_current_services(&receipt.service_processes)?; - let applied = update_handoff::read_applied_sync( + let span = rmm_agent_core::update_health_sync::verified_span( db, self.executor, - self.original.permit().grant_id, - receipt.signed_sync_decision_id, + self.binding, + self.original.handoff(), + &receipt, + self.trust.health_public_key(), )?; - ensure!( - applied.request_sha256 == receipt.signed_sync_request_sha256 - && applied.response_protobuf_sha256 == receipt.signed_sync_response_sha256 - && receipt.inventory_ack_sha256 == applied.response_protobuf_sha256, - "UPDATE_LOCAL_APPLIED_RAW_BINDING" - ); - let response_raw: Vec = db.query_row( - "SELECT response FROM helper_sync_decisions WHERE decision_id=?1", - [receipt.signed_sync_decision_id.to_string()], - |r| r.get(0), - )?; - let response: rmm_agent_core::helper_reconcile::SignedResponse = - serde_json::from_slice(&response_raw)?; - let decision: rmm_domain::reconciliation::ReconcileDecisionPayload = - serde_json::from_slice(&response.decision_bytes)?; - let applied_seconds = u64::try_from(applied.applied_at.timestamp())?; - ensure!( - applied_seconds >= u64::try_from(decision.issued_at.timestamp())? - && applied_seconds <= receipt.signed_sync_applied_at - && !decision.ready - && !decision.helper_ready - && decision - .acknowledged_message_ids - .contains(&receipt.inventory_message_id), - "UPDATE_ACTUAL_LOCAL_APPLY_OR_INVENTORY_ACK" - ); + let applied = span.applied().clone(); verify_local_inventory(&self.witnesses, &self.original, &receipt)?; Ok(VerifiedHealth { signed_sha256: hash(&serde_json::to_vec(signed)?), diff --git a/crates/updater-worker/src/agent_startup.rs b/crates/updater-worker/src/agent_startup.rs new file mode 100644 index 0000000..f6ddff3 --- /dev/null +++ b/crates/updater-worker/src/agent_startup.rs @@ -0,0 +1,210 @@ +//! Existing Agent singleton fence. No create, ACL change or Root-ledger alias. +//! The agent holds this exact lock before opening BOTH of its SQLite files. +use crate::retained::{RetainedSet, Retention}; +use anyhow::{Context, Result, ensure}; +use rmm_updater_linux::{ + Budget, + files::{Directory, Identity}, + services::StoppedServices, +}; +use std::{ + fs::{File, OpenOptions}, + os::{ + fd::AsRawFd, + unix::fs::{MetadataExt, OpenOptionsExt}, + }, + path::Path, +}; + +const PARENT: &str = "/var/lib/rmm-agent-remote"; +const PATH: &str = "/var/lib/rmm-agent-remote/agent.lock"; + +pub struct BoundAgentLock { + directory: Directory, + file: File, + expected: Identity, +} +impl BoundAgentLock { + /// Open/bind before any stop, so a missing preservation witness cannot be + /// discovered only after stopping the Agent. Reading never takes its lock. + pub fn bind(retained: &RetainedSet) -> Result { + retained.verify()?; + let specs = retained.specs(); + let spec = specs + .iter() + .find(|s| s.path == Path::new(PATH)) + .context("UPDATE_AGENT_LOCK_WITNESS_REQUIRED")?; + ensure!( + spec.retention == Retention::ImmutableMetadata + && spec.parent_uid == 993 + && spec.identity.uid == 993 + && spec.identity.gid == 984 + && spec.identity.mode & 0o7777 == 0o600 + && spec.identity.links == 1, + "UPDATE_AGENT_LOCK_PROVISIONING" + ); + let directory = Directory::open(Path::new(PARENT), 993, true)?; + let file = OpenOptions::new() + .read(true) + .write(true) + .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC) + .open(PATH)?; + let result = Self { + directory, + file, + expected: spec.identity.clone(), + }; + result.verify()?; + Ok(result) + } + fn verify(&self) -> Result<()> { + self.directory.verify()?; + let held = self.file.metadata()?; + let named = std::fs::symlink_metadata(PATH)?; + ensure!( + held.is_file() + && held.len() == 0 + && named.is_file() + && !named.file_type().is_symlink() + && identity(&held) == self.expected + && identity(&named) == self.expected, + "UPDATE_AGENT_LOCK_IDENTITY_CHANGED" + ); + Ok(()) + } + pub fn identity(&self) -> &Identity { + &self.expected + } + /// Real, fresh stopped-service proof precedes the existing nonblocking + /// singleton acquisition. A running/restarted Agent makes this fail closed. + pub fn acquire(self, stopped: &StoppedServices, budget: &Budget) -> Result { + stopped.verify_still_stopped(budget)?; + let result = self.acquire_existing()?; + stopped.verify_still_stopped(budget)?; + Ok(result) + } + fn acquire_existing(self) -> Result { + self.verify()?; + ensure!( + unsafe { libc::flock(self.file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0, + "UPDATE_AGENT_STARTUP_BUSY" + ); + let result = HeldAgentLock { bound: self }; + result.verify()?; + Ok(result) + } +} +pub struct HeldAgentLock { + bound: BoundAgentLock, +} +impl HeldAgentLock { + pub fn verify(&self) -> Result<()> { + self.bound.verify() + } + pub fn identity(&self) -> &Identity { + self.bound.identity() + } + /// Only the live Engine calls this after SQLite close and actual original + /// Root flock return, before the explicit once-only service start sequence. + pub(crate) fn return_after_root_release(self, budget: &Budget) -> Result<()> { + budget.check()?; + self.verify()?; + ensure!( + unsafe { libc::flock(self.bound.file.as_raw_fd(), libc::LOCK_UN) } == 0, + "UPDATE_AGENT_STARTUP_RETURN_FAILED" + ); + Ok(()) + } +} +impl Drop for HeldAgentLock { + fn drop(&mut self) { + unsafe { + libc::flock(self.bound.file.as_raw_fd(), libc::LOCK_UN); + } + } +} +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(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::retained::RetainedFileSpec; + use std::os::unix::fs::PermissionsExt; + struct Cleanup; + impl Drop for Cleanup { + fn drop(&mut self) { + std::fs::remove_dir_all(PARENT).unwrap(); + } + } + #[test] + fn existing_agent_lock_blocks_aliases_and_rejects_samebyte_inode_substitution() { + // Private network-none/root container fixture ONLY; no host path/test. + assert_eq!(unsafe { libc::geteuid() }, 0); + assert!(!Path::new(PARENT).exists()); + std::fs::create_dir_all(PARENT).unwrap(); + let _cleanup = Cleanup; + std::fs::set_permissions(PARENT, std::fs::Permissions::from_mode(0o700)).unwrap(); + let file = OpenOptions::new() + .create_new(true) + .read(true) + .write(true) + .mode(0o600) + .open(PATH) + .unwrap(); + for path in [PARENT, PATH] { + let path = std::ffi::CString::new(path).unwrap(); + assert_eq!(unsafe { libc::chown(path.as_ptr(), 993, 984) }, 0); + } + let retained = RetainedSet::capture(vec![RetainedFileSpec { + path: Path::new(PATH).to_owned(), + parent_uid: 993, + identity: identity(&file.metadata().unwrap()), + retention: Retention::ImmutableMetadata, + }]) + .unwrap(); + let bound = BoundAgentLock::bind(&retained).unwrap(); + // The existing Agent's separately opened descriptor owns the lock. + assert_eq!( + unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) }, + 0 + ); + assert!(bound.acquire_existing().is_err()); + assert_eq!(unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_UN) }, 0); + let held = BoundAgentLock::bind(&retained) + .unwrap() + .acquire_existing() + .unwrap(); + assert_ne!( + unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) }, + 0 + ); + held.verify().unwrap(); + std::fs::rename(PATH, Path::new(PARENT).join("agent.lock.previous")).unwrap(); + let replacement = OpenOptions::new() + .create_new(true) + .read(true) + .write(true) + .mode(0o600) + .open(PATH) + .unwrap(); + let path = std::ffi::CString::new(PATH).unwrap(); + assert_eq!(unsafe { libc::chown(path.as_ptr(), 993, 984) }, 0); + assert_eq!(replacement.metadata().unwrap().len(), 0); + assert!(held.verify().is_err()); + assert!(BoundAgentLock::bind(&retained).is_err()); + drop(held); + assert_eq!( + unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) }, + 0 + ); + } +} diff --git a/crates/updater-worker/src/bridge.rs b/crates/updater-worker/src/bridge.rs index 6de328b..d0c8546 100644 --- a/crates/updater-worker/src/bridge.rs +++ b/crates/updater-worker/src/bridge.rs @@ -53,7 +53,7 @@ pub struct BridgeContext<'a> { } pub struct FullBridge<'a> { context: BridgeContext<'a>, - prefix: UpdateInflightProof, + prefix: Option, poisoned: bool, finalized: bool, } @@ -76,7 +76,27 @@ impl<'a> FullBridge<'a> { ); Ok(Self { context, - prefix, + prefix: Some(prefix), + poisoned: false, + finalized: false, + }) + } + /// First read obtains the actual original prefix from the authenticated + /// Full process/ledger. No event is synthesized from a caller's header. + pub fn original(context: BridgeContext<'a>) -> Result { + ensure!( + context.generation == Generation::Original, + "UPDATE_BRIDGE_ORIGINAL_ONLY" + ); + context.handoff.validate()?; + ensure!( + context.delegation.handoff_sha256 == rmm_domain::jobs::hash(&context.handoff.bytes()?) + && context.delegation.owner_nonce == context.handoff.owner_nonce, + "UPDATE_BRIDGE_ORIGINAL_HEADER" + ); + Ok(Self { + context, + prefix: None, poisoned: false, finalized: false, }) @@ -87,8 +107,21 @@ impl<'a> FullBridge<'a> { .updater .verify_delegation(context.delegation, context.budget)?; context.budget.check()?; - let (_, journal) = verify_inflight_proof(&self.prefix, context.health_public_key) - .map_err(anyhow::Error::msg)?; + if self.prefix.is_none() { + ensure!( + matches!(method, NativeControlOperation::ReadOriginal), + "UPDATE_BRIDGE_ORIGINAL_READ_REQUIRED" + ); + } + let journal = self + .prefix + .as_ref() + .map(|prefix| { + verify_inflight_proof(prefix, context.health_public_key) + .map(|(_, journal)| journal) + .map_err(anyhow::Error::msg) + }) + .transpose()?; match &method { NativeControlOperation::ReadOriginal => {} NativeControlOperation::ClaimStop { @@ -96,31 +129,43 @@ impl<'a> FullBridge<'a> { .. } => ensure!( context.generation == Generation::Original - && journal.phase() == Phase::StopIntent - && *expected_head_sha256 == self.prefix.head_sha256, + && journal + .as_ref() + .is_some_and(|j| j.phase() == Phase::StopIntent) + && Some(expected_head_sha256.as_str()) + == self.prefix.as_ref().map(|p| p.head_sha256.as_str()), "UPDATE_BRIDGE_CLAIM_PHASE" ), NativeControlOperation::ObserveStarts { .. } => ensure!( context.generation == Generation::Replacement - && journal.phase() == Phase::LedgerReturnIntent, + && journal + .as_ref() + .is_some_and(|j| j.phase() == Phase::LedgerReturnIntent), "UPDATE_BRIDGE_START_PHASE" ), NativeControlOperation::Health { receipt } => { ensure!( context.generation == Generation::Replacement - && journal.phase() == Phase::ServicesStarted, + && journal + .as_ref() + .is_some_and(|j| j.phase() == Phase::ServicesStarted), "UPDATE_BRIDGE_HEALTH_PHASE" ); - journal.prepare( - u64::try_from(context.clock.now()?.timestamp())?, - rmm_updater_handoff::Evidence::HealthVerified { - receipt: receipt.clone(), - }, - )?; + journal + .as_ref() + .context("UPDATE_BRIDGE_ORIGINAL_READ_REQUIRED")? + .prepare( + u64::try_from(context.clock.now()?.timestamp())?, + rmm_updater_handoff::Evidence::HealthVerified { + receipt: receipt.clone(), + }, + )?; } NativeControlOperation::Finalize => ensure!( context.generation == Generation::Replacement - && journal.phase() == Phase::HealthVerified, + && journal + .as_ref() + .is_some_and(|j| j.phase() == Phase::HealthVerified), "UPDATE_BRIDGE_FINAL_PHASE" ), } @@ -270,8 +315,11 @@ impl<'a> FullBridge<'a> { ensure!( handoff.bytes()? == context.handoff.bytes()? && proof.delegation == *context.delegation - && proof.events.len() >= self.prefix.events.len() - && proof.events[..self.prefix.events.len()] == self.prefix.events, + && self + .prefix + .as_ref() + .is_none_or(|prior| proof.events.len() >= prior.events.len() + && proof.events[..prior.events.len()] == prior.events), "UPDATE_BRIDGE_PROOF_ROLLBACK_OR_CHANGED" ); match request.method { @@ -315,7 +363,7 @@ impl<'a> FullBridge<'a> { ), NativeControlOperation::Finalize => unreachable!(), } - self.prefix = proof.clone(); + self.prefix = Some(proof.clone()); } context.budget.check()?; if matches!(request.method, NativeControlOperation::Finalize) { @@ -331,8 +379,11 @@ impl<'a> FullBridge<'a> { original_outcome, }) } - pub fn head_sha256(&self) -> &str { - &self.prefix.head_sha256 + pub fn head_sha256(&self) -> Result<&str> { + self.prefix + .as_ref() + .map(|p| p.head_sha256.as_str()) + .context("UPDATE_BRIDGE_ORIGINAL_READ_REQUIRED") } pub fn observe_starts( &mut self, diff --git a/crates/updater-worker/src/engine.rs b/crates/updater-worker/src/engine.rs new file mode 100644 index 0000000..a6c67c3 --- /dev/null +++ b/crates/updater-worker/src/engine.rs @@ -0,0 +1,605 @@ +//! One live original-attempt pass. Activation queues only; the fixed listener +//! must finish its reply before this runtime can stop the calling Fullhelper. +//! No daemon entrypoint, admission/capability registration or restart recovery. +use crate::{ + agent_startup::BoundAgentLock, + bridge::{BridgeContext, FullBridge, Generation}, + bundle, + clock::NativeClock, + fence::LedgerFence, + ledger::{OwnedInputs, OwnedLedger}, + original::Original, + participants::{StableParticipant, verify_original_helper}, + retained::RetainedSet, + returned, + trust::TrustState, +}; +use anyhow::{Context, Result, ensure}; +use rmm_agent_core::{ + auth::Binding, + reconcile::SyncClock, + update_handoff::{NativeControlOperation, NativeEffect, NativeEffectClaim, NativeService}, +}; +use rmm_domain::{ + agent_update::{ParticipantIdentity, ParticipantRole, UpdateInflightProof}, + agent_update_provisioning::{HealthKeyPin, InstalledReleaseRecord, LocalUpdatePolicy}, + jobs::hash, +}; +use rmm_updater_handoff::{Evidence, Phase, Process}; +use rmm_updater_linux::{ + Budget, DurableEffectFence, Effect, + files::{Directory, HeldFile, LedgerGuard, Role}, + ipc::{self, Request, Response, State}, + services::{Service, ServicePolicy, ServiceProof, Systemd}, +}; +use std::{ffi::OsStr, path::Path, time::Duration}; +use uuid::Uuid; + +struct Protected { + directory: Directory, + file: HeldFile, + name: String, + max: u64, +} +impl Protected { + fn read(path: &str, max: u64) -> Result<(Self, Vec)> { + let path = Path::new(path); + let directory = Directory::open(path.parent().context("UPDATE_ENGINE_PARENT")?, 0, false)?; + let name = path + .file_name() + .context("UPDATE_ENGINE_NAME")? + .to_str() + .context("UPDATE_ENGINE_NAME")? + .to_owned(); + let mut file = directory.inspect(OsStr::new(&name), 0, max)?; + let raw = file.bytes(max)?; + Ok(( + Self { + directory, + file, + name, + max, + }, + raw, + )) + } + fn verify(&self) -> Result<()> { + self.directory + .file(OsStr::new(&self.name), self.file.proof(), self.max)?; + Ok(()) + } +} + +/// Construct only in the separately provisioned stable service, with the +/// independently protected original job Binding. It offers no approval API. +pub struct Runtime { + binding: Binding, + policy: LocalUpdatePolicy, + policy_sha256: String, + installed: InstalledReleaseRecord, + installed_sha256: String, + health_key: [u8; 32], + health_pin_sha256: String, + protected: Vec, + old_policies: Vec, + updater: StableParticipant, + clock: NativeClock, + queued: Option, + accepted: bool, + failed: bool, + terminal: bool, + head: Option, +} +struct Queued { + agent_startup: BoundAgentLock, + original: Original, + witnesses: bundle::Loaded, + trust: TrustState, + budget: Budget, + proof: UpdateInflightProof, +} +impl Runtime { + pub fn new(binding: Binding) -> Result { + let clock = NativeClock::new()?; + let budget = observation_budget()?; + let (policy_file, raw) = Protected::read("/etc/rmm-agent-updater/policy.json", 65536)?; + let (policy, policy_sha256) = + LocalUpdatePolicy::from_bytes(&raw).map_err(anyhow::Error::msg)?; + ensure!( + 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, + "UPDATE_ENGINE_LOCAL_IDENTITY" + ); + let (record_file, raw) = Protected::read(&policy.installed_record_path, 32768)?; + let installed = InstalledReleaseRecord::from_bytes(&raw).map_err(anyhow::Error::msg)?; + let installed_sha256 = hash(&raw); + let old_policies = service_policies(&policy, &installed, None)?; + let (health_file, raw) = Protected::read(&policy.health_pin_path, 4096)?; + let health: HealthKeyPin = serde_json::from_slice(&raw)?; + let health_key = health.public_key().map_err(anyhow::Error::msg)?; + let updater = StableParticipant::observe( + ServicePolicy { + service: Service::Updater, + image_sha256: policy.updater_binary_sha256.clone(), + unit_sha256: policy.updater_service.unit_sha256.clone(), + }, + &budget, + )?; + Ok(Self { + binding, + policy, + policy_sha256, + installed, + installed_sha256, + health_key, + health_pin_sha256: hash(&raw), + protected: vec![policy_file, record_file, health_file], + old_policies, + updater, + clock, + queued: None, + accepted: false, + failed: false, + terminal: false, + head: None, + }) + } + /// A lost activation reply disables this live runtime before any stop. + /// Drive is deliberately private: it cannot run inside Engine::handle. + pub fn serve_one(&mut self, listener: &ipc::Listener) -> Result<()> { + self.require_reader_registry_and_census()?; + ensure!(!self.failed && !self.terminal, "UPDATE_ENGINE_CLOSED"); + let services = Systemd::new(self.old_policies.clone())?; + let budget = observation_budget()?; + if let Err(error) = listener.serve_one(&services, &budget, self) { + if self.queued.take().is_some() { + self.failed = true; + } + return Err(error); + } + if let Some(queued) = self.queued.take() { + // serve_one has written/flushed the bounded reply and dropped its + // accepted stream. Only now may the original Full process stop. + match self.drive(queued) { + Ok(()) => self.terminal = true, + Err(error) => { + self.failed = true; + return Err(error); + } + } + } + Ok(()) + } + fn require_reader_registry_and_census(&self) -> Result<()> { + // This is an explicit source-checkpoint barrier, not a caller boolean + // or a known-unit-list substitute. Replace only with the real protected + // bootstrap registry + complete live FD/maps census and both locks. + anyhow::bail!("UPDATE_READER_CENSUS_NOT_CONFIGURED") + } + fn enqueue( + &mut self, + peer: &ParticipantIdentity, + grant: Uuid, + nonce: Uuid, + handoff_sha: &str, + ) -> Result<()> { + ensure!( + !self.accepted && self.queued.is_none() && !self.failed && !self.terminal, + "UPDATE_ENGINE_NO_RETRY_OR_RESUME" + ); + // Fuse before any fallible original admission. Even an uncertain reply + // cannot dispatch this handoff for a second time in this process. + self.accepted = true; + for file in &self.protected { + file.verify()?; + } + let header = bundle::read_header(grant, nonce, handoff_sha)?; + ensure!( + peer.role == ParticipantRole::LinuxFullHelper + && *peer == header.delegation.original_helper + && header.handoff.updater_sha256 == self.policy.updater_binary_sha256 + && header.handoff.updater_policy_sha256 == self.policy_sha256 + && header.handoff.predecessor_record_sha256 == self.installed_sha256, + "UPDATE_ENGINE_ORIGINAL_PARTICIPANTS_OR_POLICY" + ); + let finish = + chrono::DateTime::from_timestamp(i64::try_from(header.handoff.finish_before)?, 0) + .context("UPDATE_ENGINE_FINISH")?; + let budget = Budget::new( + header.handoff.boot_id, + (finish - self.clock.now()?).to_std()?, + )?; + let services = Systemd::new(self.old_policies.clone())?; + verify_original_helper(&services, &header.delegation, &budget)?; + self.updater + .verify_delegation(&header.delegation, &budget)?; + let mut bridge = FullBridge::original(BridgeContext { + handoff: &header.handoff, + delegation: &header.delegation, + services: &services, + updater: &self.updater, + clock: &self.clock, + budget: &budget, + health_public_key: self.health_key, + generation: Generation::Original, + })?; + let reply = bridge.call(NativeControlOperation::ReadOriginal)?; + let proof = reply.proof.context("UPDATE_ENGINE_ORIGINAL_PROOF")?; + let original = Original::verify( + &self.binding, + &reply + .original_start + .context("UPDATE_ENGINE_ORIGINAL_START")?, + &header.handoff.bytes()?, + header.delegation, + &self.clock, + &budget, + )?; + let (_, journal) = rmm_domain::agent_update::verify_inflight_proof(&proof, self.health_key) + .map_err(anyhow::Error::msg)?; + ensure!( + journal.phase() == Phase::StopIntent, + "UPDATE_ENGINE_NOT_A_FRESH_HANDOFF" + ); + let trust = TrustState::load(&original, &self.binding, &self.clock)?; + ensure!( + trust.health_public_key() == self.health_key + && original.update().updater.health_key_pin_sha256 == self.health_pin_sha256 + && serde_json::to_vec(trust.policy())? == serde_json::to_vec(&self.policy)?, + "UPDATE_ENGINE_TRUST_CHANGED" + ); + let witnesses = bundle::read_for_handoff(original.handoff())?; + witnesses.files.reopen_stages(original.handoff(), &budget)?; + witnesses.retained.verify()?; + let agent_startup = BoundAgentLock::bind(&witnesses.retained)?; + self.head = Some(proof.head_sha256.clone()); + self.queued = Some(Queued { + agent_startup, + original, + witnesses, + trust, + budget, + proof, + }); + Ok(()) + } + fn drive(&mut self, queued: Queued) -> Result<()> { + let Queued { + agent_startup, + original, + witnesses, + trust, + budget, + proof, + } = queued; + original.check_current(&self.binding, &self.clock, &budget)?; + trust.recheck(&original, &self.clock)?; + let services = Systemd::new(self.old_policies.clone())?; + let old = [Service::Agent, Service::General, Service::Full] + .into_iter() + .map(|s| services.observe(s, &budget).map(|h| h.proof().clone())) + .collect::>>()?; + let mut bridge = FullBridge::new( + BridgeContext { + handoff: original.handoff(), + delegation: original.delegation(), + services: &services, + updater: &self.updater, + clock: &self.clock, + budget: &budget, + health_public_key: self.health_key, + generation: Generation::Original, + }, + proof, + )?; + let mut claims = Vec::new(); + for service in [ + NativeService::Agent, + NativeService::General, + NativeService::Full, + ] { + let expected_head_sha256 = bridge.head_sha256()?.to_owned(); + claims.push( + bridge + .call(NativeControlOperation::ClaimStop { + expected_head_sha256, + service, + })? + .claim + .context("UPDATE_ENGINE_STOP_CLAIM")?, + ); + } + drop(bridge); + let mut stop_fence = StopFence { + original: &original, + binding: &self.binding, + clock: &self.clock, + budget: &budget, + updater: &self.updater, + trust: &trust, + retained: &witnesses.retained, + claims, + old, + next: 0, + pending: false, + poisoned: false, + }; + let stopped = services.stop_all(&budget, &mut stop_fence)?; + let claims = stop_fence.finish()?; + let agent_startup = agent_startup.acquire(&stopped, &budget)?; + let os = LedgerGuard::acquire(&stopped, &witnesses.ledger, &budget)?; + let mut ledger = OwnedLedger::open(OwnedInputs { + os: &os, + original: &original, + binding: &self.binding, + clock: &self.clock, + budget: &budget, + updater: &self.updater, + retained: &witnesses.retained, + files: &witnesses.files, + stopped: &stopped, + trust: &trust, + })?; + for (claim, old) in claims.iter().zip(stopped.proofs()) { + ledger.observe_native(claim, &hash(&serde_json::to_vec(&old)?))?; + } + ledger.append_observed(Evidence::AllStopped { + observation_sha256: hash(&serde_json::to_vec(&stopped.proofs())?), + })?; + ledger.append_observed(Evidence::UpdaterOwnsLedger { + process: Process { + pid: self.updater.identity().pid, + birth: self.updater.identity().birth, + image_sha256: self.updater.identity().image_sha256.clone(), + }, + ledger_identity_sha256: witnesses.ledger.sha256()?, + })?; + // Do not hold a second connection before all readers really stopped. + let swap = (|| -> Result<()> { + let stages = witnesses.files.reopen_stages(original.handoff(), &budget)?; + let mut fence = LedgerFence::new(&mut ledger)?; + for (stage, role) in + stages + .into_iter() + .zip([Role::Agent, Role::Helper, Role::FullConfig, Role::FullPin]) + { + let directory = Directory::open( + Path::new(role.target()) + .parent() + .context("UPDATE_ENGINE_TARGET_PARENT")?, + 0, + false, + )?; + stage.install(&directory, &os, &budget, &mut fence)?; + } + fence.finish()?; + ledger.append_observed(Evidence::PairVerified { + pair: original.handoff().target.clone(), + retained_state_sha256: original.handoff().retained_state_sha256.clone(), + }) + })(); + if let Err(error) = swap { + // Exactly one best-effort ORIGINAL Unknown CAS while we still own + // the real guard. Failure is preserved; no restoration or retry. + let _ = ledger.mark_unknown( + u64::try_from(self.clock.now()?.timestamp())?, + rmm_updater_handoff::UnknownReason::ReplaceUncertain, + ); + return Err(error); + } + let prepared = ledger.prepare_return_and_close()?; + let reservation = prepared.bind(returned::Inputs { + original: &original, + binding: &self.binding, + clock: &self.clock, + budget: &budget, + updater: &self.updater, + retained: &witnesses.retained, + files: &witnesses.files, + trust: &trust, + })?; + let target_policies = service_policies(&self.policy, &self.installed, Some(&original))?; + let target = Systemd::new(target_policies.clone())?; + let observer = Systemd::new(target_policies)?; + let mut bridge = FullBridge::new( + BridgeContext { + handoff: original.handoff(), + delegation: original.delegation(), + services: &observer, + updater: &self.updater, + clock: &self.clock, + budget: &budget, + health_public_key: self.health_key, + generation: Generation::Replacement, + }, + reservation.proof().clone(), + )?; + let mut fence = reservation.start_fence(&observer, &mut bridge); + agent_startup.verify()?; + os.release(&budget, &mut fence)?; + agent_startup.return_after_root_release(&budget)?; + let started = stopped.start_once(target, &budget, &mut fence)?; + fence.finish()?; + bridge.observe_starts(&started)?; + loop { + original.check_current(&self.binding, &self.clock, &budget)?; + self.updater + .verify_delegation(original.delegation(), &budget)?; + witnesses.retained.verify()?; + for service in &started { + service.verify(&budget)?; + } + let reply = bridge.call(NativeControlOperation::ReadOriginal)?; + let proof = reply.proof.context("UPDATE_ENGINE_HEALTH_PROOF")?; + self.head = Some(proof.head_sha256.clone()); + let (_, journal) = + rmm_domain::agent_update::verify_inflight_proof(&proof, self.health_key) + .map_err(anyhow::Error::msg)?; + match journal.phase() { + Phase::ServicesStarted => std::thread::sleep(Duration::from_millis(100)), + Phase::HealthVerified => { + bridge.call(NativeControlOperation::Finalize)?; + self.head = None; + return Ok(()); + } + _ => anyhow::bail!("UPDATE_ENGINE_HEALTH_PREFIX_CHANGED"), + } + } + } +} +impl ipc::Engine for Runtime { + fn handle(&mut self, peer: &ParticipantIdentity, request: Request) -> Result { + ensure!(!self.failed && !self.terminal, "UPDATE_ENGINE_CLOSED"); + self.updater + .identity() + .validate() + .then_some(()) + .context("UPDATE_ENGINE_IDENTITY")?; + let state = match request { + Request::Describe {} => State::Described, + Request::Activate { + grant_id, + owner_nonce, + handoff_sha256, + } => { + self.enqueue(peer, grant_id, owner_nonce, &handoff_sha256)?; + State::Inflight + } + // Health travels through the existing independently validating + // new Fullhelper path. This daemon accepts no duplicate authority. + _ => anyhow::bail!("UPDATE_ENGINE_UNSUPPORTED_CONTROL"), + }; + Ok(Response { + schema_version: 1, + state, + ready: false, + updater: self.updater.identity().clone(), + head_sha256: self.head.clone(), + }) + } +} + +struct StopFence<'a> { + original: &'a Original, + binding: &'a Binding, + clock: &'a NativeClock, + budget: &'a Budget, + updater: &'a StableParticipant, + trust: &'a TrustState, + retained: &'a RetainedSet, + claims: Vec, + old: Vec, + next: usize, + pending: bool, + poisoned: bool, +} +impl StopFence<'_> { + fn current(&self) -> Result<()> { + self.original + .check_current(self.binding, self.clock, self.budget)?; + self.updater + .verify_delegation(self.original.delegation(), self.budget)?; + self.trust.recheck(self.original, self.clock)?; + self.retained.verify() + } + fn finish(self) -> Result> { + ensure!( + !self.poisoned && !self.pending && self.next == 3, + "UPDATE_ENGINE_STOP_INCOMPLETE" + ); + self.current()?; + Ok(self.claims) + } +} +impl DurableEffectFence for StopFence<'_> { + fn before_effect(&mut self, effect: &Effect) -> Result<()> { + ensure!( + !self.poisoned && !self.pending && self.next < 3, + "UPDATE_ENGINE_STOP_NO_RETRY" + ); + self.poisoned = true; + self.current()?; + let service = [Service::Agent, Service::General, Service::Full][self.next]; + let native = [ + NativeService::Agent, + NativeService::General, + NativeService::Full, + ][self.next]; + let claim = &self.claims[self.next]; + ensure!( + *effect == Effect::StopService { service } + && claim.effect() == &NativeEffect::StopService { service: native } + && claim.grant_id() == self.original.permit().grant_id + && claim.owner_nonce() == self.original.handoff().owner_nonce, + "UPDATE_ENGINE_STOP_RESERVATION_CHANGED" + ); + self.pending = true; + Ok(()) + } + fn after_effect(&mut self, effect: &Effect, observation: &str) -> Result<()> { + ensure!( + self.poisoned + && self.pending + && self.next < 3 + && *effect + == Effect::StopService { + service: self.old[self.next].service + } + && observation == hash(&serde_json::to_vec(&self.old[self.next])?), + "UPDATE_ENGINE_STOP_OBSERVATION_CHANGED" + ); + self.current()?; + self.next += 1; + self.pending = false; + self.poisoned = false; + Ok(()) + } +} +fn observation_budget() -> Result { + Budget::new( + std::fs::read_to_string("/proc/sys/kernel/random/boot_id")? + .trim() + .parse()?, + Duration::from_secs(5), + ) +} +fn service_policies( + policy: &LocalUpdatePolicy, + installed: &InstalledReleaseRecord, + original: Option<&Original>, +) -> Result> { + let release = installed + .release_envelope + .decode() + .map_err(anyhow::Error::msg)?; + policy + .services + .iter() + .zip([ + Service::Agent, + Service::General, + Service::Full, + Service::Apt, + ]) + .map(|(pin, service)| { + ensure!(pin.unit == service.unit(), "UPDATE_ENGINE_SERVICE_SET"); + let image_sha256 = match (service, original) { + (Service::Agent, Some(o)) => o.handoff().target.agent_sha256.clone(), + (Service::General | Service::Full | Service::Apt, Some(o)) => { + o.handoff().target.helper_sha256.clone() + } + (Service::Agent, None) => release.manifest.artifacts[0].sha256.clone(), + (_, None) => release.manifest.artifacts[1].sha256.clone(), + _ => anyhow::bail!("UPDATE_ENGINE_SERVICE_ROLE"), + }; + Ok(ServicePolicy { + service, + image_sha256, + unit_sha256: pin.unit_sha256.clone(), + }) + }) + .collect() +} diff --git a/crates/updater-worker/src/history.rs b/crates/updater-worker/src/history.rs index 19e9c80..9adc109 100644 --- a/crates/updater-worker/src/history.rs +++ b/crates/updater-worker/src/history.rs @@ -1316,6 +1316,94 @@ mod tests { active, } } + #[test] + fn public_record_builder_binds_actual_original_key_and_exact_health_head() { + let f = fixture(); + let (grant, record, start):(String,Vec,Vec)=f.db.query_row( + "SELECT h.grant_id,h.record,e.start FROM agent_update_handoffs h JOIN execution_evidence e USING(grant_id)", + [],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?))).unwrap(); + let grant: Uuid = grant.parse().unwrap(); + let delegation = update_handoff::read_delegation(&f.db, grant).unwrap(); + let original = + crate::original::Original::verify_retained(&f.binding, &start, &record, delegation) + .unwrap(); + let key: [u8; 32] = hex::decode(&original.update().updater.health_public_key_hex) + .unwrap() + .try_into() + .unwrap(); + let mut journal = Journal::open(&record, key).unwrap(); + let mut wrong_journal = Journal::open( + &record, + SigningKey::from_bytes(&[88; 32]).verifying_key().to_bytes(), + ) + .unwrap(); + let mut statement = + f.db.prepare("SELECT event FROM agent_update_handoff_events ORDER BY sequence") + .unwrap(); + let events = statement + .query_map([], |r| r.get::<_, Vec>(0)) + .unwrap() + .collect::>>() + .unwrap(); + let mut health_raw = None; + let mut wrong_health_raw = None; + for raw in events { + let event: Event = serde_json::from_slice(&raw).unwrap(); + if let Evidence::HealthVerified { receipt } = &event.evidence { + journal.replay(&raw).unwrap(); + let mut wrong = receipt.clone(); + let mut message = HEALTH_DOMAIN.to_vec(); + message.extend_from_slice(&wrong.payload); + wrong.signature = SigningKey::from_bytes(&[88; 32]) + .sign(&message) + .to_bytes() + .to_vec(); + let forged = wrong_journal + .prepare( + event.observed_at, + Evidence::HealthVerified { receipt: wrong }, + ) + .unwrap(); + wrong_journal.replay(&forged).unwrap(); + wrong_health_raw = Some(forged); + health_raw = Some(raw); + break; + } + journal.replay(&raw).unwrap(); + wrong_journal.replay(&raw).unwrap(); + } + let health_raw = health_raw.unwrap(); + let built = crate::record::BuiltRecord::build(&original, &f.initial, &journal, &health_raw) + .unwrap(); + assert_eq!(built.raw(), f.active); + assert_eq!(built.sha256(), hash(&f.active)); + // A complete kernel Journal can be constructed with the wrong external + // key. The public builder must independently enforce the ORIGINAL job. + assert!( + crate::record::BuiltRecord::build( + &original, + &f.initial, + &wrong_journal, + &wrong_health_raw.unwrap() + ) + .is_err() + ); + let mut changed: Event = serde_json::from_slice(&health_raw).unwrap(); + changed.observed_at += 1; + assert!( + crate::record::BuiltRecord::build( + &original, + &f.initial, + &journal, + &serde_json::to_vec(&changed).unwrap() + ) + .is_err() + ); + assert!( + crate::record::BuiltRecord::build(&original, &f.active, &journal, &health_raw).is_err() + ); + } + #[test] fn completed_history_rejects_file_only_rollback_forks_and_tampered_activation_without_writes() { let f = fixture(); diff --git a/crates/updater-worker/src/lib.rs b/crates/updater-worker/src/lib.rs index c09a4db..52a59d1 100644 --- a/crates/updater-worker/src/lib.rs +++ b/crates/updater-worker/src/lib.rs @@ -1,9 +1,11 @@ //! Concrete, original-attempt-bound Linux worker. No approval or retry path. #![cfg(target_os = "linux")] +pub mod agent_startup; pub mod bridge; pub mod bundle; pub mod clock; +pub mod engine; pub mod fence; pub mod files; pub mod full; diff --git a/docs/agent-updater-health-client.md b/docs/agent-updater-health-client.md index 1fcac49..fd21da9 100644 --- a/docs/agent-updater-health-client.md +++ b/docs/agent-updater-health-client.md @@ -87,3 +87,31 @@ gegeben; dieser prüft eigene Control-/Inventar-/Prozesszeugen unabhängig. Der zuerst qualifizierte Deliveryschnitt oben bleibt historisch. Änderungen und tatsächliche lokale Folgeprüfungen sowie offene native Gates stehen in [agent-updater-runtime-source.md](agent-updater-runtime-source.md). + +## Exakte lokale Applyspanne statt Sekundenquantisierung + +Nachtrag2026-11-15: Der unveränderte eingefrorene Healthreceipt enthält +`signed_sync_applied_at` weiterhin als `u64` und unverändert als +`floor(confirming.issued_at)`. Dieser Scalar erteilt keine Zeitfreigabe. +Der neue lesende Coregetter `update_health_sync::read_round` prüft bounded +die vorhandenen Originalrequest-Protobufs, SignedResponsebytes und tatsächlich +im selben HelperSync-Commit gespeicherten Appliedwitnesses. Die bestehende +Signatur-/Kontextprüfung läuft unabhängig erneut; es wird weder ein ACKboolean +noch eine Callerzeit akzeptiert und kein Journal/Ready/Lease neu geschrieben. + +`verified_span` findet genau ein tatsächlich angewandtes bestätigendes D2 mit +beiden vorherigen Decision-IDs gleich D1, derselben Originalgeräte-/Boot-/ +Verbindungsbindung und identischem ServicesStarted-Präfix. Dieser Präfix muss +auch unverändert im aktuellen Originalhandoff enthalten sein. Der Fullguard +prüft jetzt `D1.issued_at <= actual_local_applied_at <= D2.issued_at` mit +den exakten ursprünglichen DateTimes. Erst danach folgt die bestehende lokale +Inventar-/Dienst-/Originalhealthprüfung. Der u64-Wert wird ausschließlich auf +Gleichheit mit dem ursprünglichen D2-Sekundenfloor geprüft. + +Der enge tatsächliche Grenzfall akzeptiert beide exakten Endpunkte und verweigert +eine um1ns zu frühe oder zu späte Anwendung trotz identischem Sekundenfloor. +Der vorhandene vollständige negative HelperSyncfall prüft zusätzlich den echten +Original-Roundgetter nach Signatur-/Applypersistierung. Lokaler Quell-/Testbeleg: +`devstate/updater-health-exact-span-6879f7cc-f284-4f50-b3e6-de321f3af6a2/`. +Kein nativer Health-/Applynachweis und keine Änderung an Frozenreceipt-/ +Kernelbytes oder an der WebUI-Grenze. diff --git a/docs/agent-updater-runtime-source.md b/docs/agent-updater-runtime-source.md index 12ae6bb..31eadfc 100644 --- a/docs/agent-updater-runtime-source.md +++ b/docs/agent-updater-runtime-source.md @@ -130,3 +130,14 @@ und ursprüngliche Admissionstrecke, qualifizierte passive Kandidatenbeobachtung geschlossene Readercensus, unklare Record-I/O-Namespace-Adjudikation und der vor der ersten Baseline notwendige V2-Rückweg bleiben offen. Applyfähigkeit bleibt unveröffentlicht; kein Cloud-VM-Apply, kein Produktfertig- oder Produktionsnachweis. + +## Nachtrag2026-11-15: gesperrte Worker-Drivefolge + +Nach dem gepushten gemeinsamen Checkpoint8e93c9e und dem erhaltenden Mainmerge +07d6118 ist die bisher offene Enginefolge als konkrete Workerquelle verbunden. +Ihr Eintritt bleibt explizit `UPDATE_READER_CENSUS_NOT_CONFIGURED`; weder +Daemonentrypoint noch Job-/Applycapability wird aktiviert. Die genaue +Queue-/Reply-/Stop-/Lock-/Swap-/Start-/Healthfolge und vorhandene separate +Agent-Singletonsperre stehen in [worker](agent-updater-worker.md). Der neu +geprüfte öffentliche Recordbuilder löst die zuvor dort genannte fehlende +positive authentisierte Eingangsprobe. Keine reale Applyabnahme folgt daraus. diff --git a/docs/agent-updater-worker.md b/docs/agent-updater-worker.md index 23f8927..c1dc025 100644 --- a/docs/agent-updater-worker.md +++ b/docs/agent-updater-worker.md @@ -158,3 +158,49 @@ keine echte UI-/Job-/Service-/Rootguardwirkung und umgehen ausdrücklich den öffentlichen authentisierten BuiltRecordeingang. Aktueller Source-/Nachweisstand und restliche Engine-/Admission-/Rollback-/Nativegates: [Runtimefortschreibung](agent-updater-runtime-source.md). + +## Einmalige Queue-/Drivefolge und vorhandene Agent-Singletonsperre + +Am2026-11-15 liegt `worker::engine::Runtime` als noch gesperrter Quellschnitt +vor. Der vorhandene IPC-Activatehandler queuet ausschließlich den originalen +Handoff; die private Drivefolge ist erst nach vollständig geschriebenem Reply +und geschlossener Accepted-Verbindung erreichbar. Eine verlorene Antwort +verwirft die Queue und sperrt dieselbe Runtime. Die erste Fullbridge-Lesung +übernimmt den tatsächlich authentisierten Originalpräfix; vorher sind alle +mutierenden Methoden gesperrt und kein Event wird aus Headerdaten erfunden. + +Die Folge verbindet Originalsignatur-/Policy-/Floor-/Dateibeobachtungen, alle +drei Full-Stopclaims vor irgendeinem Stop, die tatsächlichen Stopbeobachtungen +im Originalledger nach Guardübernahme, AllStopped/Owns, vier getrennte +Save-/Publishpaare, Pair, Return-/Startreservation, tatsächlichen DBclose und +flockdrop, General→Full→Agent und neue Full-Start-/Health-/Recordbestätigung. +Es gibt keinen Resume oder Restore. Ein Fehler bei den Fileübergängen versucht +unter dem noch gehaltenen Originalguard genau einen Unknown-CAS und startet +keinen Dienst neu. Native Dienst-/Fehlerfolgen sind damit noch nicht bewiesen. + +Zusätzlich wird die vorhandene `/var/lib/rmm-agent-remote/agent.lock` aus dem +OriginalRetainedSet gebunden: unveränderter Inode, UID993/GID984/0600/nlink1, +0Bytes und privater Parent. Nach echtem StoppedServices-Beleg nimmt der Worker +diese vorhandene Sperre exklusiv ohne CREATE. Sie bleibt über Root-DB/Swap/ +DBclose/Rootlockreturn gehalten und wird vor der festen Startfolge zurückgegeben. +Der Agent hält schon heute seine ursprüngliche Singletondatei vor beiden +Agent-SQLiteöffnungen; keine ACL, Agentdatei oder Sperrrolle wurde geändert. + +**Explizite Sperre dieses Checkpoints:** `Runtime::serve_one` verweigert mit +`UPDATE_READER_CENSUS_NOT_CONFIGURED`. Geschützte kompatible Bootstrapregistry +plus vollständige aktuelle PID-/FD-/maps-Census und Nachstopbeobachtung unter +beiden tatsächlichen Sperren fehlen noch. Eine bekannte Unitliste ersetzt +keinen Census. Keine CLI oder RMM-Admission ruft diese Runtime auf; Applycaps +bleiben geschlossen. Ebenso offen: Staging-/Downloadproducer, passiver gültiger +Updatezustand, V2-Rollbackvertrag vor dem ersten Bootstrap, Unsicherheits- +Namespaces, qualifizierte Dienstkontexte und tatsächlicher Linux-Apply. + +Lokaler Nachweis liegt unter +`devstate/updater-engine-source-6a8bb902-4db4-4d93-8843-450ba1dd5622/`. +Der7er-Workerlauf umfasst jetzt auch den **öffentlichen** BuiltRecordbuilder: +Originalsignierter Job und echte vollständig signierte History ergeben exakt +die erwarteten Rawrecordbytes. Ein für einen fremden externen Healthkey gültiger +Journal bleibt unter dem Originaljobkey unzulässig; geänderter Head/prior wird +verweigert. Ein separater echter Container-FS-Fall belegt die Agent-Singleton- +Aliasblockade und Ablehnung eines gleichbyteigen Inodeersatzes. Dies sind lokale +Krypto-/FS-Verträge; sie führen die Queue-/Drive-/Dienstfolge nicht aus.