diff --git a/Rust_RMM_Implementierungsspezifikation.md b/Rust_RMM_Implementierungsspezifikation.md index 5b3f70d..c56fc2c 100644 --- a/Rust_RMM_Implementierungsspezifikation.md +++ b/Rust_RMM_Implementierungsspezifikation.md @@ -1,6 +1,6 @@ # Rust RMM: Architektur und Implementierungsspezifikation -Version 1.10 · 2026-11-13 · Sprache: Deutsch +Version 1.11 · 2026-11-13 · Sprache: Deutsch **Zweck:** Vollständige, eigenständig nutzbare Grundlage für die Implementierung einer mandantenfähigen Plattform zur Inventarisierung, Überwachung und Fernadministration von Kundengeräten durch eine Coding-KI und ein Entwicklungsteam. @@ -66,6 +66,21 @@ Deploymentdaten, offene Konfiguration und reale Nachweise: ### 0.1 Auftrag an die implementierende KI +**Technische Präzisierung Version 1.11 — neuer Configure-only-Plan:** +Nach unabhängig belegtem und durch normalen signierten RootSync abgeschlossenem +Fehler „Fixture1.0 ausschließlich entpackt“ darf ein neuer fester WebUI-Plan +allein dieses Paket konfigurieren. Manifestschema4 bindet ursprünglichen +Grant/Versuch und unveränderlichen Partial-Proof; Transaktionsschema2 verlangt +explizit `operation=configure_only` und alte/neue Version1.0. Frische vollständige +Teilzustandsplanung hat eine eigene authentisierte Operation/Inventarquelle; +normale Planung und Baseline bleiben strikt. Tatsächlicher v3-Hook und dpkg- +Aufruf dürfen ausschließlich die Konfiguration dieses exakten Pakets enthalten, +kein Unpack, Pending, Triggerlauf oder Fremdpaket. Eigene Create-once- +Recoverymarker/-Nachweise; alte Marker und History bleiben erhalten. Dies +bescheinigt keine nachträgliche frische Installationsabnahme. Danach braucht ein +Upgrade1.0→1.1 einen eigenen neuen festen WebUI-Plan und native Nachprüfung; +gewünschte Noops werden getrennt und ehrlich als Noops abgenommen. + **Technische Präzisierung Version 1.10 — wirkungslose Kontrollkettenreparatur:** Ein nachweislich nicht serverseitig persistierter Sync-Request darf im expliziten Entwicklungsprofil über ein eng begrenztes Root-Bootstrapwerkzeug abgeglichen diff --git a/crates/agent/src/apt.rs b/crates/agent/src/apt.rs index aa71bb2..82c5a6c 100644 --- a/crates/agent/src/apt.rs +++ b/crates/agent/src/apt.rs @@ -41,6 +41,14 @@ fn status(binding: &Binding) -> Result { std::env::var_os("RMM_APT_HELPER_SOCKET").context("APT_HELPER_SOCKET_NOT_CONFIGURED")?; readiness::probe(Path::new(&socket), binding, &pin) } +fn recovery_status(binding: &Binding) -> Result { + let path = + std::env::var_os("RMM_APT_HELPER_PROOF_FILE").context("APT_RECOVERY_PIN_REQUIRED")?; + let pin = readiness::Pin::read(Path::new(&path), binding)?; + let socket = + std::env::var_os("RMM_APT_HELPER_SOCKET").context("APT_RECOVERY_SOCKET_REQUIRED")?; + readiness::planning_for_recovery(Path::new(&socket), binding, &pin) +} pub fn capabilities_from(response: &readiness::Response) -> Vec { if response.profile != "apt_only" { return vec![]; @@ -62,7 +70,7 @@ pub fn capabilities_from(response: &readiness::Response) -> Vec { result } pub fn capabilities(binding: &Binding) -> Vec { - status(binding) + let normal = status(binding) .map(|s| { let mut caps = capabilities_from(&s); if !caps.is_empty() { @@ -82,6 +90,21 @@ pub fn capabilities(binding: &Binding) -> Vec { } caps }) + .unwrap_or_default(); + if !normal.is_empty() { + return normal; + } + recovery_status(binding) + .map(|s| { + vec![ + "apt_native_acceptance".into(), + "root:apt_native_acceptance".into(), + "helper.root.v1".into(), + format!("helper.policy.sha256:{}", s.provider_stack_sha256), + "apt.manifest.v2".into(), + "apt.native-acceptance.v1".into(), + ] + }) .unwrap_or_default() } @@ -95,13 +118,15 @@ pub fn planning_observation(binding: Option<&Binding>) -> serde_json::Value { let pin = readiness::Pin::read(Path::new(&path), binding)?; let socket = std::env::var_os("RMM_APT_HELPER_SOCKET").context("APT_PLANNING_NOT_CONFIGURED")?; - readiness::planning(Path::new(&socket), binding, &pin)? + readiness::planning(Path::new(&socket), binding, &pin) + .or_else(|_| readiness::planning_for_recovery(Path::new(&socket), binding, &pin))? .planning .context("APT_PLANNING_UNAVAILABLE") })(); match result { Ok(planning) => { - serde_json::json!({"scope":"linux.apt.planning", "source_id":"root-helper:apt_planning_v1", + let recovery = planning.native_recovery.is_some(); + serde_json::json!({"scope":if recovery{"linux.apt.recovery-planning"}else{"linux.apt.planning"}, "source_id":if recovery{"root-helper:apt_recovery_planning_v1"}else{"root-helper:apt_planning_v1"}, "observed_at":planning.observed_at, "quality":"valid", "completeness":"complete", "truncated":false, "data":planning}) } Err(_) => { @@ -125,6 +150,28 @@ fn recipe_ready(job: &JobPayload, response: &readiness::Response) -> Result<()> )?; manifest.resolved_apt_transaction.validate_fixture()?; let recipe = &manifest.resolved_apt_transaction.recipe_id; + if let Some(reference) = &manifest.native_recovery { + let planning = response + .planning + .as_ref() + .context("APT_RECOVERY_PLANNING_REQUIRED")?; + planning.validate(chrono::Utc::now())?; + ensure!( + job.action.name() == "apt_native_acceptance" + && manifest.schema_version == 4 + && manifest.action == "apt-native-acceptance" + && planning.native_recovery.as_ref() == Some(reference) + && planning.baseline_sha256 == manifest.resolved_apt_transaction.baseline_sha256 + && planning.status_fingerprint + == manifest.resolved_apt_transaction.status_fingerprint + && planning.runtime_sha256 == manifest.runtime_sha256 + && planning.provider_sha256 == manifest.provider_sha256 + && planning.hook_sha256 == manifest.hook_sha256 + && planning.apt_config_sha256 == manifest.apt_config_sha256, + "APT_RECOVERY_FRESH_PLAN_BINDING" + ); + return Ok(()); + } if job.action.name() == "apt_native_acceptance" { ensure!( manifest.action == "apt-native-acceptance" @@ -145,7 +192,17 @@ fn recipe_ready(job: &JobPayload, response: &readiness::Response) -> Result<()> Ok(()) } pub fn supported(binding: &Binding, job: &JobPayload) -> bool { - status(binding).and_then(|s| recipe_ready(job, &s)).is_ok() + job_status(binding, job) + .and_then(|s| recipe_ready(job, &s)) + .is_ok() +} +fn job_status(binding: &Binding, job: &JobPayload) -> Result { + if matches!(&job.action,rmm_domain::jobs::Action::AptNativeAcceptance{apt_manifest,..}if apt_manifest.native_recovery.is_some()) + { + recovery_status(binding) + } else { + status(binding) + } } pub fn invoke(binding: &Binding, job: &JobPayload, request: &Request) -> Result { let socket = socket_for( @@ -154,7 +211,7 @@ pub fn invoke(binding: &Binding, job: &JobPayload, request: &Request) -> Result< std::env::var_os("RMM_APT_HELPER_SOCKET"), )?; if provider::is_apt_action(job) { - recipe_ready(job, &status(binding)?)?; + recipe_ready(job, &job_status(binding, job)?)?; } rmm_privileged_helper::invoke(&socket, request, job.max_runtime_seconds) } diff --git a/crates/domain/src/apt_transaction.rs b/crates/domain/src/apt_transaction.rs index 4e0b42b..9e42dff 100644 --- a/crates/domain/src/apt_transaction.rs +++ b/crates/domain/src/apt_transaction.rs @@ -10,6 +10,8 @@ pub const UPDATE_SHA: &str = "ef67c9fe0ba1443fcfe465768e1204763063c369a2a1da04af #[serde(deny_unknown_fields)] pub struct ResolvedAptTransaction { pub schema_version: u32, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub operation: Option, pub recipe_id: String, pub recipe_version: String, pub platform: String, @@ -33,6 +35,29 @@ pub struct PackageArchive { } pub type AptExpectation = ResolvedAptTransaction; pub type AptExpectedPackage = PackageArchive; +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, schemars::JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum AptTransactionOperation { + ConfigureOnly, +} +/// One new explicitly approved configure-only job after a proven partial +/// fixture effect. This does not retry the old consumed attempt. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, schemars::JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct AptNativeRecovery { + pub schema_version: u32, + pub previous_grant_id: uuid::Uuid, + pub previous_attempt_id: uuid::Uuid, + pub partial_proof_sha256: String, +} +impl AptNativeRecovery { + pub fn validate(&self) -> bool { + self.schema_version == 1 + && !self.previous_grant_id.is_nil() + && !self.previous_attempt_id.is_nil() + && digest(&self.partial_proof_sha256) + } +} /// One explicitly approved recovery of a fixture acceptance that failed before /// the trusted pre-dpkg hook. The original create-once marker remains intact. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, schemars::JsonSchema)] @@ -69,11 +94,12 @@ pub struct AptExecutionManifest { pub test_result_id: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub native_retry: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub native_recovery: Option, } impl ResolvedAptTransaction { pub fn validate_fixture(&self) -> bool { - if self.schema_version != 1 - || self.recipe_version != "1" + if self.recipe_version != "1" || self.platform != "ubuntu-24.04-amd64" || self.resolver_config_version != "rmm-apt-local-v1" || !self.no_reboot @@ -84,9 +110,16 @@ impl ResolvedAptTransaction { return false; } let package = &self.packages[0]; - let (old, new, sha) = match self.recipe_id.as_str() { - INSTALL_RECIPE => (None, "1.0", INSTALL_SHA), - UPDATE_RECIPE => (Some("1.0"), "1.1", UPDATE_SHA), + let (old, new, sha) = match ( + self.schema_version, + &self.operation, + self.recipe_id.as_str(), + ) { + (1, None, INSTALL_RECIPE) => (None, "1.0", INSTALL_SHA), + (1, None, UPDATE_RECIPE) => (Some("1.0"), "1.1", UPDATE_SHA), + (2, Some(AptTransactionOperation::ConfigureOnly), INSTALL_RECIPE) => { + (Some("1.0"), "1.0", INSTALL_SHA) + } _ => return false, }; package.name == "rmm-mvp-test" @@ -106,9 +139,23 @@ impl ResolvedAptTransaction { impl AptExecutionManifest { pub fn validate(&self) -> bool { self.kind == "rmm.apt.helper-action" - && match (&self.native_retry, self.schema_version) { - (None, 2) => true, - (Some(retry), 3) => self.action == "apt-native-acceptance" && retry.validate(), + && match ( + &self.native_retry, + &self.native_recovery, + self.schema_version, + ) { + (None, None, 2) => self.resolved_apt_transaction.operation.is_none(), + (Some(retry), None, 3) => { + self.action == "apt-native-acceptance" + && retry.validate() + && self.resolved_apt_transaction.operation.is_none() + } + (None, Some(recovery), 4) => { + self.action == "apt-native-acceptance" + && recovery.validate() + && self.resolved_apt_transaction.operation + == Some(AptTransactionOperation::ConfigureOnly) + } _ => false, } && matches!( @@ -197,6 +244,7 @@ impl PinnedAptTransaction { let expectation: AptExpectation = serde_json::from_slice(&self.expectation_bytes) .map_err(|_| "INVALID_APT_EXPECTATION")?; if expectation.schema_version != 1 + || expectation.operation.is_some() || expectation.platform != "ubuntu-24.04-amd64" || !expectation.no_reboot || !label(&expectation.recipe_id) @@ -312,6 +360,7 @@ mod tests { fn helper_schema_two_roundtrip_and_strict_action_binding() { let t = ResolvedAptTransaction { schema_version: 1, + operation: None, recipe_id: INSTALL_RECIPE.into(), recipe_version: "1".into(), platform: "ubuntu-24.04-amd64".into(), @@ -345,8 +394,36 @@ mod tests { runtime_sha256: hash(b"runtime"), test_result_id: "fixture-test-1".into(), native_retry: None, + native_recovery: None, }; assert!(m.validate()); + let mut recovery = m.clone(); + recovery.schema_version = 4; + recovery.native_recovery = Some(AptNativeRecovery { + schema_version: 1, + previous_grant_id: Uuid::new_v4(), + previous_attempt_id: Uuid::new_v4(), + partial_proof_sha256: hash(b"closed partial"), + }); + recovery.resolved_apt_transaction.schema_version = 2; + recovery.resolved_apt_transaction.operation = Some(AptTransactionOperation::ConfigureOnly); + recovery.resolved_apt_transaction.packages[0].old_version = Some("1.0".into()); + recovery.transaction_bytes = + crate::jobs::encode(&recovery.resolved_apt_transaction).unwrap(); + recovery.transaction_sha256 = hash(&recovery.transaction_bytes); + assert!(recovery.validate()); + let mut disguised = recovery.clone(); + disguised.schema_version = 2; + assert!(!disguised.validate()); + disguised = recovery.clone(); + disguised.action = "apt-execute".into(); + assert!(!disguised.validate()); + disguised = recovery.clone(); + disguised.native_recovery = None; + assert!(!disguised.validate()); + let mut equal_normal = m.resolved_apt_transaction.clone(); + equal_normal.packages[0].old_version = Some("1.0".into()); + assert!(!equal_normal.validate_fixture()); assert!( !serde_json::to_value(&m) .unwrap() @@ -408,6 +485,7 @@ mod tests { }; let expectation = AptExpectation { schema_version: 1, + operation: None, recipe_id: "fixture".into(), recipe_version: "1".into(), platform: "ubuntu-24.04-amd64".into(), diff --git a/crates/privileged-helper/src/apt.rs b/crates/privileged-helper/src/apt.rs index 2e1e77e..4df7686 100644 --- a/crates/privileged-helper/src/apt.rs +++ b/crates/privileged-helper/src/apt.rs @@ -70,6 +70,8 @@ pub struct PackageArchive { #[serde(deny_unknown_fields)] pub struct ResolvedAptTransaction { pub schema_version: u32, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub operation: Option, pub recipe_id: String, pub recipe_version: String, pub platform: String, @@ -82,8 +84,7 @@ pub struct ResolvedAptTransaction { impl ResolvedAptTransaction { pub fn validate_fixture(&self) -> Result<()> { ensure!( - self.schema_version == 1 - && self.recipe_version == "1" + self.recipe_version == "1" && self.platform == "ubuntu-24.04-amd64" && self.resolver_config_version == "rmm-apt-local-v1" && self.no_reboot @@ -93,9 +94,18 @@ impl ResolvedAptTransaction { sha(&self.status_fingerprint)?; sha(&self.baseline_sha256)?; let p = &self.packages[0]; - let (old, new, expected_hash) = match self.recipe_id.as_str() { - INSTALL_RECIPE => (None, "1.0", INSTALL_SHA), - UPDATE_RECIPE => (Some("1.0"), "1.1", UPDATE_SHA), + let (old, new, expected_hash) = match ( + self.schema_version, + &self.operation, + self.recipe_id.as_str(), + ) { + (1, None, INSTALL_RECIPE) => (None, "1.0", INSTALL_SHA), + (1, None, UPDATE_RECIPE) => (Some("1.0"), "1.1", UPDATE_SHA), + ( + 2, + Some(rmm_domain::apt_transaction::AptTransactionOperation::ConfigureOnly), + INSTALL_RECIPE, + ) => (Some("1.0"), "1.0", INSTALL_SHA), _ => bail!("APT_RECIPE_NOT_CONFIGURED"), }; ensure!( @@ -133,6 +143,8 @@ pub struct AptExecutionManifest { pub test_result_id: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub native_retry: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub native_recovery: Option, } #[derive(Deserialize)] @@ -299,11 +311,20 @@ fn validate_manifest( config.validate()?; ensure!( m.kind == "rmm.apt.helper-action" - && match (&m.native_retry, m.schema_version) { - (None, 2) => true, - (Some(retry), 3) => { - action == "apt_native_acceptance" && retry.validate() + && match (&m.native_retry, &m.native_recovery, m.schema_version) { + (None, None, 2) => m.resolved_apt_transaction.operation.is_none(), + (Some(retry), None, 3) => { + action == "apt_native_acceptance" + && retry.validate() + && m.resolved_apt_transaction.operation.is_none() } + (None, Some(recovery), 4) => + action == "apt_native_acceptance" + && recovery.validate() + && m.resolved_apt_transaction.operation + == Some( + rmm_domain::apt_transaction::AptTransactionOperation::ConfigureOnly + ), _ => false, } && m.execution_profile == config.execution_profile @@ -600,6 +621,10 @@ impl PreparedApt { /// Read-only prerequisite under the caller's device ExecutorGuard. A new /// signed retry does not clear an unknown effect or change an old record. pub fn verify_retry_history(&self, db: &rusqlite::Connection) -> Result<()> { + if self.manifest.native_recovery.is_some() { + self.recovery_partial(db)?; + return Ok(()); + } let Some(retry) = &self.manifest.native_retry else { return Ok(()); }; @@ -647,6 +672,44 @@ impl PreparedApt { self.verify_retry_evidence(db, &evidence) } + fn recovery_partial( + &self, + db: &rusqlite::Connection, + ) -> Result { + let reference = self + .manifest + .native_recovery + .as_ref() + .context("APT_RECOVERY_REFERENCE_REQUIRED")?; + let prior = crate::apt_reconcile::closed_partial(db, &self.binding, Some(reference))?; + ensure!( + self.manifest.schema_version == 4 + && self.manifest.action == "apt-native-acceptance" + && self.manifest.execution_profile == "dev-test" + && reference.previous_grant_id != self.permit.grant_id + && reference.previous_attempt_id != self.job.attempt_id + && prior.job_id != self.job.job_id + && prior.authorization_id != self.permit.authorization_id + && prior.plan_sha256 != self.permit.plan_hash + && prior.previous_start_before <= self.permit.not_before + && self.manifest.resolved_apt_transaction.baseline_sha256 == prior.baseline_sha256 + && self.manifest.resolved_apt_transaction.status_fingerprint + == prior.status_fingerprint, + "APT_RECOVERY_NEW_APPROVED_BINDING" + ); + for name in [ + format!("recovery-attempt-{}.json", reference.previous_grant_id), + format!("recovery-{}.json", reference.previous_grant_id), + format!("pending-recovery-{}.json", reference.previous_grant_id), + ] { + ensure!( + absent_nofollow(&Path::new(BASE).join(name))?, + "APT_RECOVERY_ALREADY_ATTEMPTED" + ); + } + Ok(prior) + } + fn verify_retry_evidence( &self, db: &rusqlite::Connection, @@ -901,6 +964,11 @@ impl PreparedApt { fn stage(&self, db: &rusqlite::Connection, ledger_id: &str) -> Result { verify_installation()?; verify_prefetched(&self.manifest, &self.permit)?; + let partial = if self.manifest.native_recovery.is_some() { + Some(self.recovery_partial(db)?) + } else { + None + }; let remaining = (self.permit.start_before - Utc::now()) .num_nanoseconds() .context("APT_DEADLINE_RANGE")?; @@ -959,6 +1027,9 @@ impl PreparedApt { 1024 * 1024, )?; write_once(&active.join("baseline.json"), &baseline, 0o600)?; + if let Some(partial) = partial { + write_once(&active.join("partial-proof.json"), &partial.proof, 0o600)?; + } let config = Command::new("/usr/bin/python3") .args(["-I", CODE, "print-config"]) .env_clear() @@ -1098,11 +1169,31 @@ fn map_driver_result( "APT_FIXTURE_PAYLOAD_EVIDENCE" ); if bootstrap { - sha(result - .evidence - .get("native_record_sha256") - .and_then(|v| v.as_str()) - .context("APT_NATIVE_RECORD")?)?; + if let Some(recovery) = &m.native_recovery { + ensure!( + result.evidence.get("native_recovery") == Some(&serde_json::json!(true)) + && result.evidence.get("partial_proof_sha256") + == Some(&serde_json::json!(recovery.partial_proof_sha256)) + && result.evidence.get("native_record_sha256").is_none(), + "APT_RECOVERY_SEPARATE_RECORD_REQUIRED" + ); + sha(result + .evidence + .get("recovery_record_sha256") + .and_then(|v| v.as_str()) + .context("APT_RECOVERY_RECORD")?)?; + } else { + ensure!( + result.evidence.get("native_recovery").is_none() + && result.evidence.get("recovery_record_sha256").is_none(), + "APT_RECOVERY_WRONG_ACTION" + ); + sha(result + .evidence + .get("native_record_sha256") + .and_then(|v| v.as_str()) + .context("APT_NATIVE_RECORD")?)?; + } ensure!( result.evidence.get("test_result_id") == Some(&serde_json::json!(m.test_result_id)), diff --git a/crates/privileged-helper/src/apt/tests.rs b/crates/privileged-helper/src/apt/tests.rs index e30c0e8..c734b13 100644 --- a/crates/privileged-helper/src/apt/tests.rs +++ b/crates/privileged-helper/src/apt/tests.rs @@ -3,6 +3,46 @@ use openssl::{pkey::PKey, sign::Signer}; use rmm_domain::jobs::{Action, encode}; use uuid::Uuid; +#[test] +fn configure_only_is_explicit_native_recovery_and_never_install_acceptance() { + let (config, mut m) = manifest(true); + m.schema_version = 4; + m.native_recovery = Some(rmm_domain::apt_transaction::AptNativeRecovery { + schema_version: 1, + previous_grant_id: Uuid::new_v4(), + previous_attempt_id: Uuid::new_v4(), + partial_proof_sha256: hash(b"partial"), + }); + m.resolved_apt_transaction.schema_version = 2; + m.resolved_apt_transaction.operation = + Some(rmm_domain::apt_transaction::AptTransactionOperation::ConfigureOnly); + m.resolved_apt_transaction.packages[0].old_version = Some("1.0".into()); + m.transaction_bytes = serde_json::to_vec(&m.resolved_apt_transaction).unwrap(); + m.transaction_sha256 = hash(&m.transaction_bytes); + validate_manifest(&m, "apt_native_acceptance", &config).unwrap(); + assert!(validate_manifest(&m, "ensure_package", &config).is_err()); + let mut evidence = serde_json::json!({"test_acceptance":true,"noProductionEvidence":true,"native_recovery":true,"recovery_record_sha256":hash(b"recovery record"),"partial_proof_sha256":hash(b"partial"),"test_result_id":m.test_result_id,"effect_armed_ledger_id":"ledger","packages":[{"name":"rmm-mvp-test","architecture":"all","version":"1.0"}],"snapshot_sha256":hash(b"snapshot"),"fixture_payload_sha256":hash(b"1.0\n"),"reboot_required":false}); + let encode_result = |e: &serde_json::Value| { + serde_json::to_vec(&serde_json::json!({"effect_state":"verified","code":"POSTCONDITIONS_VERIFIED","evidence":e})).unwrap() + }; + assert_eq!( + map_driver_result(&encode_result(&evidence), Some(0), true, &m, "ledger") + .unwrap() + .state, + "succeeded" + ); + evidence["native_record_sha256"] = serde_json::json!(hash(b"fake install acceptance")); + assert!(map_driver_result(&encode_result(&evidence), Some(0), true, &m, "ledger").is_err()); + evidence + .as_object_mut() + .unwrap() + .remove("native_record_sha256"); + evidence["partial_proof_sha256"] = serde_json::json!(hash(b"other")); + assert!(map_driver_result(&encode_result(&evidence), Some(0), true, &m, "ledger").is_err()); + m.schema_version = 2; + assert!(validate_manifest(&m, "apt_native_acceptance", &config).is_err()); +} + #[test] fn actual_domain_native_action_roundtrips_exact_signed_manifest_to_helper() { let (binding, mut request, key, now) = signed_request(); @@ -352,6 +392,7 @@ fn consumed_parent_row_and_original_start_request_are_mandatory() { fn manifest(bootstrap: bool) -> (ProviderConfig, AptExecutionManifest) { let transaction = ResolvedAptTransaction { schema_version: 1, + operation: None, recipe_id: INSTALL_RECIPE.into(), recipe_version: "1".into(), platform: "ubuntu-24.04-amd64".into(), @@ -398,6 +439,7 @@ fn manifest(bootstrap: bool) -> (ProviderConfig, AptExecutionManifest) { runtime_sha256: config.runtime_sha256.clone(), test_result_id: "fixture-test-1".into(), native_retry: None, + native_recovery: None, }; (config, manifest) } diff --git a/crates/privileged-helper/src/apt_reconcile.rs b/crates/privileged-helper/src/apt_reconcile.rs index e994a13..fe0a78e 100644 --- a/crates/privileged-helper/src/apt_reconcile.rs +++ b/crates/privileged-helper/src/apt_reconcile.rs @@ -132,6 +132,120 @@ struct LedgerRow { start: Vec, outcome: Vec, } +pub struct ClosedPartial { + pub reference: rmm_domain::apt_transaction::AptNativeRecovery, + pub proof: Vec, + pub job_id: Uuid, + pub authorization_id: Uuid, + pub plan_sha256: String, + pub previous_start_before: DateTime, + pub baseline_sha256: String, + pub status_fingerprint: String, +} +/// Only a previously classified partial whose exact outcome was closed by +/// signed RootSync can seed a new, separately approved configure-only job. +pub fn closed_partial( + db: &Connection, + binding: &Binding, + wanted: Option<&rmm_domain::apt_transaction::AptNativeRecovery>, +) -> Result { + closed_partial_from(db, binding, wanted, read_evidence) +} +fn closed_partial_from( + db: &Connection, + binding: &Binding, + wanted: Option<&rmm_domain::apt_transaction::AptNativeRecovery>, + read: impl Fn() -> Result>>, +) -> Result { + let mut q=db.prepare("SELECT c.rowid,c.grant_id,c.agent,c.generation,c.job,c.attempt,e.start,c.result,e.outcome,p.original_request_sha256,p.previous_outcome_sha256,p.previous_outcome,p.proof_sha256,p.proof,p.classified_outcome,p.checked_at_ms FROM apt_partial_reconciliations p JOIN consumed c USING(grant_id) JOIN execution_evidence e USING(grant_id) ORDER BY c.rowid")?; + let rows = q + .query_map([], |r| { + Ok(( + LedgerRow { + rowid: r.get(0)?, + grant: r.get(1)?, + agent: r.get(2)?, + generation: r.get(3)?, + job: r.get(4)?, + attempt: r.get(5)?, + start: r.get(6)?, + outcome: r.get(11)?, + }, + r.get::<_, Option>>(7)?, + r.get::<_, Option>>(8)?, + r.get::<_, String>(9)?, + r.get::<_, String>(10)?, + r.get::<_, String>(12)?, + r.get::<_, Vec>(13)?, + r.get::<_, Vec>(14)?, + r.get::<_, i64>(15)?, + )) + })? + .collect::>>()?; + ensure!(rows.len() <= 256, "APT_RECOVERY_PROOF_LIMIT"); + let mut found = None; + for (row, result, outcome, request_sha, old_sha, proof_sha, proof, classified, checked) in rows + { + if wanted.is_some_and(|w| w.previous_grant_id.to_string() != row.grant) { + continue; + } + let Some(c) = eligible(binding, row)? else { + continue; + }; + let reference = rmm_domain::apt_transaction::AptNativeRecovery { + schema_version: 1, + previous_grant_id: c.probe.grant_id, + previous_attempt_id: c.probe.attempt_id, + partial_proof_sha256: proof_sha.clone(), + }; + ensure!( + wanted.is_none_or(|w| w == &reference) + && reference.validate() + && hash(&proof) == proof_sha + && hash(&c.original_outcome) == old_sha + && hash(&serde_json::to_vec(&c.request)?) == request_sha, + "APT_RECOVERY_IMMUTABLE_PROOF" + ); + let result: Outcome = + serde_json::from_slice(&result.context("APT_RECOVERY_PRIOR_UNRESOLVED")?)?; + let classified_value: Value = serde_json::from_slice(&classified)?; + ensure!( + result.state == "failed" + && result.error_code == CODE + && !result.reboot_required + && serde_json::to_value(&result)? == classified_value + && serde_json::from_slice::( + &outcome.context("APT_RECOVERY_PRIOR_OUTCOME")? + )? == classified_value, + "APT_RECOVERY_PRIOR_NOT_CLOSED_PARTIAL" + ); + let p: PartialProof = serde_json::from_slice(&proof)?; + ensure!(p.checked_at_ms == checked, "APT_RECOVERY_PROOF_TIME"); + let files = read()?; + verify_proof( + &c, + &files, + &ProbeOutput { + effect_state: "known_failed".into(), + code: CODE.into(), + proof: p.clone(), + }, + DateTime::from_timestamp_millis(checked).context("APT_RECOVERY_PROOF_TIME")?, + )?; + ensure!(found.is_none(), "APT_RECOVERY_AMBIGUOUS_PROOFS"); + found = Some(ClosedPartial { + reference, + proof, + job_id: c.probe.job_id, + authorization_id: c.probe.authorization_id, + plan_sha256: c.probe.plan_sha256, + previous_start_before: c.permit.start_before, + baseline_sha256: p.observed_snapshot_sha256, + status_fingerprint: p.status_fingerprint, + }); + } + found.context("APT_RECOVERY_CLOSED_PROOF_REQUIRED") +} fn digest(s: &str) -> bool { s.len() == 64 && s.bytes() @@ -176,6 +290,9 @@ fn eligible(binding: &Binding, row: LedgerRow) -> Result> { else { return Ok(None); }; + if apt_manifest.schema_version != 3 || apt_manifest.native_retry.is_none() { + return Ok(None); + } ensure!( recipe_id == apt::INSTALL_RECIPE && recipe_version == "1" @@ -847,4 +964,38 @@ mod tests { classified ); } + #[test] + fn new_recovery_requires_exact_closed_partial_signed_history_and_immutable_proof() { + let (binding, row, files, now) = fixture(); + let c = eligible(&binding, row.clone()).unwrap().unwrap(); + let proof = output(&c, &files, now).proof; + let mut db = Connection::open_in_memory().unwrap(); + db.execute_batch("CREATE TABLE consumed(grant_id TEXT PRIMARY KEY,agent TEXT,generation INTEGER,job TEXT,attempt TEXT,result BLOB);CREATE TABLE execution_evidence(grant_id TEXT PRIMARY KEY,start BLOB,outcome BLOB);").unwrap(); + db.execute("INSERT INTO consumed(rowid,grant_id,agent,generation,job,attempt,result) VALUES(?1,?2,?3,?4,?5,?6,NULL)",params![row.rowid,row.grant,row.agent,row.generation,row.job,row.attempt]).unwrap(); + db.execute( + "INSERT INTO execution_evidence VALUES(?1,?2,?3)", + params![row.grant, row.start, row.outcome], + ) + .unwrap(); + persist(&mut db, &c, &proof).unwrap(); + assert!(closed_partial_from(&db, &binding, None, || Ok(files.clone())).is_err()); + db.execute( + "UPDATE consumed SET result=(SELECT outcome FROM execution_evidence)", + [], + ) + .unwrap(); + let closed = closed_partial_from(&db, &binding, None, || Ok(files.clone())).unwrap(); + assert_eq!(closed.reference.previous_grant_id, c.probe.grant_id); + assert_eq!(closed.reference.previous_attempt_id, c.probe.attempt_id); + assert_eq!(closed.baseline_sha256, proof.observed_snapshot_sha256); + let mut changed = closed.reference.clone(); + changed.previous_attempt_id = Uuid::new_v4(); + assert!(closed_partial_from(&db, &binding, Some(&changed), || Ok(files.clone())).is_err()); + let mut changed_files = files.clone(); + changed_files.insert("signed-action.json".into(), b"{}".to_vec()); + assert!(closed_partial_from(&db, &binding, None, || Ok(changed_files.clone())).is_err()); + db.execute("UPDATE apt_partial_reconciliations SET proof=x'7b7d'", []) + .unwrap(); + assert!(closed_partial_from(&db, &binding, None, || Ok(files.clone())).is_err()); + } } diff --git a/crates/privileged-helper/src/readiness.rs b/crates/privileged-helper/src/readiness.rs index c7a7f7a..e6ecd21 100644 --- a/crates/privileged-helper/src/readiness.rs +++ b/crates/privileged-helper/src/readiness.rs @@ -76,6 +76,8 @@ pub struct Response { #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct PlanningResult { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub native_recovery: Option, pub observed_at: chrono::DateTime, pub fixture_package: Option, pub baseline_sha256: String, @@ -106,6 +108,16 @@ pub struct PlanningReceipt { } impl PlanningResult { pub fn validate(&self, now: chrono::DateTime) -> Result<()> { + if let Some(reference) = &self.native_recovery { + ensure!( + reference.validate() + && self + .fixture_package + .as_ref() + .is_some_and(|p| p.version == "1.0" && p.status == "install ok unpacked"), + "APT_RECOVERY_PLANNING_SCOPE" + ); + } ensure!( self.observed_at <= now && now - self.observed_at < chrono::Duration::seconds(30) @@ -235,18 +247,28 @@ pub fn validate_response(request: &Request, response: &Response) -> Result<()> { ensure!( matches!( request.operation.as_str(), - "apt_readiness_v1" | "apt_planning_v1" + "apt_readiness_v1" | "apt_planning_v1" | "apt_recovery_planning_v1" ), "APT_PROBE_OPERATION" ); if let Some(planning) = &response.planning { ensure!( - request.operation == "apt_planning_v1", + matches!( + request.operation.as_str(), + "apt_planning_v1" | "apt_recovery_planning_v1" + ), "APT_PLANNING_OPERATION" ); planning.validate(chrono::Utc::now())?; + ensure!( + (request.operation == "apt_recovery_planning_v1") == planning.native_recovery.is_some(), + "APT_RECOVERY_PLANNING_OPERATION" + ); } - if request.operation == "apt_planning_v1" { + if matches!( + request.operation.as_str(), + "apt_planning_v1" | "apt_recovery_planning_v1" + ) { ensure!( response.planning.is_some() && !response.fixture_acceptance_ready @@ -292,6 +314,9 @@ pub fn probe(socket: &Path, binding: &Binding, pin: &Pin) -> Result { pub fn planning(socket: &Path, binding: &Binding, pin: &Pin) -> Result { probe_operation(socket, binding, pin, "apt_planning_v1") } +pub fn planning_for_recovery(socket: &Path, binding: &Binding, pin: &Pin) -> Result { + probe_operation(socket, binding, pin, "apt_recovery_planning_v1") +} fn probe_operation( socket: &Path, binding: &Binding, @@ -368,7 +393,7 @@ pub fn answer( ensure!( matches!( request.operation.as_str(), - "apt_readiness_v1" | "apt_planning_v1" + "apt_readiness_v1" | "apt_planning_v1" | "apt_recovery_planning_v1" ) && !request.challenge.is_nil() && request.identity == Identity::from_binding(binding)?, "APT_PROBE_REQUEST_BINDING" @@ -378,11 +403,21 @@ pub fn answer( stack == request.expected_stack_sha256, "APT_PROBE_STACK_MISMATCH" ); - if request.operation == "apt_planning_v1" { + if matches!( + request.operation.as_str(), + "apt_planning_v1" | "apt_recovery_planning_v1" + ) { // A metadata-only process is bounded separately from package execution. // Missing/unsafe/dirty/unprefetched state closes only this observation. - let planning: PlanningResult = - serde_json::from_slice(&rmm_agent_linux::apt_planning_metadata()?)?; + let planning: PlanningResult = if request.operation == "apt_recovery_planning_v1" { + recovery_planning(ledger, binding)? + } else { + serde_json::from_slice(&rmm_agent_linux::apt_planning_metadata()?)? + }; + ensure!( + (request.operation == "apt_recovery_planning_v1") == planning.native_recovery.is_some(), + "APT_RECOVERY_PLANNING_OPERATION" + ); planning.validate(chrono::Utc::now())?; ensure!( planning.runtime_sha256 == config.runtime_sha256 @@ -475,14 +510,154 @@ pub fn answer( Ok(response) } +fn recovery_planning(ledger: &rusqlite::Connection, binding: &Binding) -> Result { + use anyhow::Context; + use std::{ + os::unix::process::CommandExt, + process::{Command, Stdio}, + time::{Duration, Instant}, + }; + ensure!( + ledger.query_row( + "SELECT count(*) FROM consumed WHERE result IS NULL", + [], + |r| r.get::<_, u64>(0) + )? == 0, + "APT_RECOVERY_PLANNING_UNRESOLVED" + ); + apt::verify_installation()?; + let partial = crate::apt_reconcile::closed_partial(ledger, binding, None)?; + let proof: serde_json::Value = serde_json::from_slice(&partial.proof)?; + let input = serde_json::to_vec( + &serde_json::json!({"native_recovery":partial.reference,"proof":proof}), + )?; + ensure!( + input.len() <= 1024 * 1024, + "APT_RECOVERY_PLANNING_INPUT_LIMIT" + ); + let mut child = Command::new("/usr/bin/python3") + .args(["-I", apt::CODE, "recovery-planning"]) + .env_clear() + .env("PATH", "/usr/sbin:/usr/bin:/sbin:/bin") + .env("LC_ALL", "C") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .process_group(0) + .spawn()?; + let result = (|| -> Result> { + let mut stdin = Some(child.stdin.take().context("APT_RECOVERY_PLANNING_STDIN")?); + let mut stdout = child + .stdout + .take() + .context("APT_RECOVERY_PLANNING_STDOUT")?; + for fd in [ + stdin + .as_ref() + .context("APT_RECOVERY_PLANNING_STDIN")? + .as_raw_fd(), + stdout.as_raw_fd(), + ] { + let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) }; + ensure!( + flags >= 0 + && unsafe { libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) } >= 0, + "APT_RECOVERY_PLANNING_PIPE" + ); + } + let deadline = Instant::now() + Duration::from_secs(4); + let mut written = 0; + let mut output = vec![]; + let mut exited = None; + let mut eof = false; + loop { + ensure!(Instant::now() < deadline, "APT_RECOVERY_PLANNING_TIMEOUT"); + if let Some(pipe) = stdin.as_mut() { + match pipe.write(&input[written..]) { + Ok(n) => written += n, + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {} + Err(e) => return Err(e.into()), + }; + if written == input.len() { + stdin = None; + } + } + let mut buf = [0; 4096]; + for _ in 0..16 { + match stdout.read(&mut buf) { + Ok(0) => { + eof = true; + break; + } + Ok(n) => { + ensure!( + output.len() + n <= 32768, + "APT_RECOVERY_PLANNING_OUTPUT_LIMIT" + ); + output.extend_from_slice(&buf[..n]); + } + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break, + Err(e) => return Err(e.into()), + } + } + if exited.is_none() { + exited = child.try_wait()?; + } + if eof && let Some(status) = exited { + ensure!( + status.success() && written == input.len(), + "APT_RECOVERY_PLANNING_FAILED" + ); + return Ok(output); + } + std::thread::sleep(Duration::from_millis(5)); + } + })(); + unsafe { + libc::kill(-(child.id() as i32), libc::SIGKILL); + } + let _ = child.wait(); + let planning: PlanningResult = serde_json::from_slice(&result?)?; + ensure!( + planning.native_recovery.as_ref() == Some(&partial.reference) + && planning.baseline_sha256 == partial.baseline_sha256 + && planning.status_fingerprint == partial.status_fingerprint, + "APT_RECOVERY_PLANNING_PROOF_BINDING" + ); + Ok(planning) +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn recovery_planning_is_a_distinct_bound_partial_observation() { + let mut p = planning_fixture(); + let r = rmm_domain::apt_transaction::AptNativeRecovery { + schema_version: 1, + previous_grant_id: Uuid::new_v4(), + previous_attempt_id: Uuid::new_v4(), + partial_proof_sha256: "a".repeat(64), + }; + p.native_recovery = Some(r); + assert!(p.validate(chrono::Utc::now()).is_err()); + p.fixture_package = Some(FixturePackage { + version: "1.0".into(), + status: "install ok unpacked".into(), + }); + p.validate(chrono::Utc::now()).unwrap(); + p.fixture_package.as_mut().unwrap().status = "install ok installed".into(); + assert!(p.validate(chrono::Utc::now()).is_err()); + p.fixture_package.as_mut().unwrap().status = "install ok unpacked".into(); + p.native_recovery.as_mut().unwrap().previous_grant_id = Uuid::nil(); + assert!(p.validate(chrono::Utc::now()).is_err()); + } fn planning_fixture() -> PlanningResult { let raw = include_str!("../../../tests/apt_transaction/fixtures/planning-canonical.json").trim(); let runtime = serde_json::from_str(raw).unwrap(); PlanningResult { + native_recovery: None, observed_at: chrono::Utc::now(), fixture_package: None, baseline_sha256: "b".repeat(64), diff --git a/deploy/browser/cloud_apt_acceptance.cjs b/deploy/browser/cloud_apt_acceptance.cjs index 40769d7..909b7b2 100644 --- a/deploy/browser/cloud_apt_acceptance.cjs +++ b/deploy/browser/cloud_apt_acceptance.cjs @@ -12,14 +12,15 @@ function readPrivate(file) { return JSON.parse(fs.readFileSync(file, 'utf8')); } function checkAction(p, expected) { - const native = ['apt_install_retry', 'apt_native_update'].includes(expected.case); - const version = expected.case === 'apt_install_retry' ? '1.0' : '1.1'; + const recovery = expected.case === 'apt_configure_recovery'; + const native = recovery || ['apt_install_retry', 'apt_native_update'].includes(expected.case); + const version = recovery || expected.case === 'apt_install_retry' ? '1.0' : '1.1'; const recipe = version === '1.0' ? 'rmm-apt-fixture-install-1.0' : 'rmm-apt-fixture-update-1.1'; const action = p.action; const m = action.apt_manifest; const tx = m.resolved_apt_transaction; assert(action.action === (native ? 'apt_native_acceptance' : expected.case)); assert(p.execution_identity === 'root' && p.max_runtime_seconds === 300 && p.max_output_bytes === 65536); assert(m.type === 'rmm.apt.helper-action' && m.execution_profile === 'dev-test' && m.action === (native ? 'apt-native-acceptance' : 'apt-execute')); - assert(m.schema_version === (expected.case === 'apt_install_retry' ? 3 : 2)); + assert(m.schema_version === (recovery ? 4 : expected.case === 'apt_install_retry' ? 3 : 2)); assert(tx.recipe_id === recipe && tx.recipe_version === '1' && tx.no_reboot === true && tx.packages.length === 1); const pkg = tx.packages[0]; const sha = version === '1.0' ? '74036ae81223deab3aae994fd2a2a695af408741777e1ce17dcb4e32f1235867' : 'ef67c9fe0ba1443fcfe465768e1204763063c369a2a1da04af6027d8a9c00491'; @@ -27,6 +28,13 @@ function checkAction(p, expected) { assert(crypto.createHash('sha256').update(Buffer.from(m.transaction_bytes)).digest('hex') === m.transaction_sha256); assert(equal(JSON.parse(Buffer.from(m.transaction_bytes)), tx)); assert(equal(m, expected.request.parameters.apt_manifest)); + if (recovery) { + assert(tx.schema_version === 2 && tx.operation === 'configure_only' && pkg.old_version === '1.0'); + assert(m.native_retry === undefined && m.native_recovery.schema_version === 1); + assert(m.native_recovery.previous_grant_id === '31ef5e5e-5dbd-4428-a9a1-cbd15de2f5a0'); + assert(m.native_recovery.previous_attempt_id !== p.attempt_id); + assert(m.native_recovery.partial_proof_sha256 === 'dc3bf3870ea77c12f9291bac712c53ae72194eaec980a8646155a7fb5c0dbe21'); + } else assert(tx.schema_version === 1 && tx.operation === undefined); if (expected.case === 'apt_install_retry') { assert(m.native_retry.schema_version === 1 && m.native_retry.bootstrap_marker_sha256 === 'ec84aa4df8065f0b54b282bd273a6f342f07a6d47312289608389d05c7fb6053'); assert(m.native_retry.previous_attempt_id !== p.attempt_id); @@ -34,7 +42,7 @@ function checkAction(p, expected) { } (async () => { const file = path.resolve(process.argv[2]); const expected = readPrivate(file); - assert(expected.profile === 'dev/test' && ['apt_install_retry', 'apt_native_update', 'ensure_package', 'apply_updates'].includes(expected.case) && expected.expected_principal === 'simulated-testprincipal-a'); + assert(expected.profile === 'dev/test' && ['apt_configure_recovery', 'apt_install_retry', 'apt_native_update', 'ensure_package', 'apply_updates'].includes(expected.case) && expected.expected_principal === 'simulated-testprincipal-a'); const login = readPrivate(path.join(root, 'credentials/server-browser-login.json')); const browsers = path.join(root, 'web/node_modules/.cache/playwright-browsers'); const version = fs.readdirSync(browsers).find(x => /^chromium-/.test(x)); diff --git a/deploy/cloud_apt_recovery.py b/deploy/cloud_apt_recovery.py new file mode 100644 index 0000000..3b18f3f --- /dev/null +++ b/deploy/cloud_apt_recovery.py @@ -0,0 +1,120 @@ +#!/usr/bin/env python3 +"""Exact configure-only recovery followed by separate fixture upgrade/noops.""" +import argparse +import datetime as dt +import hashlib +import json +import os +import time +import uuid + +import cloud_apt_retry as prior +import cloud_root_evidence +import cloud_root_policy + +cloud=prior.cloud +require=cloud.require +BASE=cloud.ROOT/'devstate/cloud-apt-recovery' +STATE=BASE/'cases' +CASES=('apt_configure_recovery','apt_native_update','ensure_package','apply_updates') + + +def recovery_request(device,target): + m=cloud.contract;data=prior.adapters.planning_from_device(device,recovery=True) + closed=m.protected_json(BASE/'readonly-central-result.json')['result'] + reference=dict(schema_version=1,previous_grant_id=closed['result']['grant_id'],previous_attempt_id=closed['attempt_id'], + partial_proof_sha256=closed['result']['evidence']['apt']['reconciliation_proof_sha256']) + require(closed['state']=='failed' and closed['result']['error_code']=='APT_PARTIAL_UNCONFIGURED_VERIFIED' and + data['native_recovery']==reference,'exact previously closed partial reference') + pin=prior.adapters.PINS['1.0'];start=m.now();receipt=data['prefetch'][pin] + require(receipt['schema_version']==1 and receipt['sha256']==pin and receipt['size']==20672 and + receipt['sealed_at_ms']<=int(start.timestamp()*1000),'actual pregrant archive receipt') + tx=dict(schema_version=2,operation='configure_only',recipe_id='rmm-apt-fixture-install-1.0',recipe_version='1', + platform='ubuntu-24.04-amd64',resolver_config_version='rmm-apt-local-v1',no_reboot=True, + status_fingerprint=data['status_fingerprint'],baseline_sha256=data['baseline_sha256'],packages=[ + dict(name='rmm-mvp-test',architecture='all',old_version='1.0',new_version='1.0',origin='rmm-test',sha256=pin, + size=20672,archive_path='/var/lib/rmm-apt-transaction/archives/'+pin+'.deb')]) + raw=prior.adapters.canonical(tx) + manifest=dict(type='rmm.apt.helper-action',schema_version=4,action='apt-native-acceptance',execution_profile='dev-test', + transaction_sha256=hashlib.sha256(raw).hexdigest(),resolved_apt_transaction=tx,transaction_bytes=list(raw), + native_recovery=reference,test_result_id='configure-recovery-'+uuid.uuid4().hex, + **{k:data[k] for k in ('provider_sha256','hook_sha256','apt_config_sha256','runtime_sha256')}) + m.validate_apt_manifest(manifest) + return dict(tenant_id=target['tenant_id'],action='apt_native_acceptance',targets=dict(asset_ids=[target['asset_id']]), + parameters=dict(execution_identity='root',timeout_seconds=300,max_output_bytes=65536, + recipe_id=tx['recipe_id'],recipe_version='1',apt_manifest=manifest), + schedule=m.schedule(start,start+dt.timedelta(minutes=15)),rollout=dict(max_parallel=1,halt_after_failures=1), + reason='Configure ONLY the exactly proven unpacked fixture1.0; new attempt and separate recovery record; no unpack, pending packages, reinstall or reboot') + + +def enable(): + m=cloud.contract;require(prior.prior.evidence('gate')['unresolved']==0,'no unresolved attempt') + ready=m.protected_json(BASE/'configure-runtime.json') + require(ready['completed'] and ready['readiness_only'] and ready['preserved_state'] and not ready['native_acceptance'], + 'qualified native probe, no invented package acceptance') + target=prior.prior.identity();pin=ready['apt_pin'];identity=pin['identity'] + require(all(identity[k]==target[k] for k in target),'same permanent Cloud VM') + endpoint=cloud.bootstrap.rpc('linux-vm.conf',prior.switch_endpoint,dict(id=str(uuid.uuid4()),enabled=True, + agent_id=target['agent_id'],binary_sha256=ready['helper_sha256'])) + m.write_private(BASE/'recovery-endpoint-enabled.json',endpoint) + peers=cloud.bootstrap.rpc('linux-vm.conf',cloud_root_evidence.inspect_helpers,target) + require(peers['ledger']['faults']==0 and peers['apt']['provider_stack_sha256']==pin['provider_stack_sha256'], + 'actual fixed helper peer and stack') + scope={k:identity[k] for k in ('tenant_id','asset_id','agent_id','enrollment_generation','assignment_version')} + scope.update(principals=['simulated-testprincipal-a'],helper_policy_sha256=pin['provider_stack_sha256'], + acceptance_evidence_id='cloud-configure-recovery-probe:'+ready['readiness_sha256'],allowed_services=[],allow_root_scripts=False,allow_reboot=False, + apt=dict(allow_native_acceptance=True,allow_execute=True,runtime_sha256=ready['runtime_sha256'], + apt_config_sha256=ready['apt_config_sha256'],provider_sha256=ready['provider_sha256'], + hook_sha256=hashlib.sha256((cloud.ROOT/'tools/apt-transaction/hook').read_bytes()).hexdigest())) + policy=dict(schema_version=1,profile='development',expires_at=(m.now()+dt.timedelta(hours=1)).isoformat(),scopes=[scope]) + old=m.protected_json(cloud.ROOT/'devstate/cloud-logs/policy-closed.json') + record=cloud.bootstrap.rpc('server.conf',prior.replace_policy,dict(id=str(uuid.uuid4()),previous_sha256=old['policy_sha256'],policy=policy)) + m.write_private(BASE/'recovery-policy.json',dict(record,policy=policy)) + print('Fixed APT runtime endpoint and expiring limits enabled; no job or approval created') + + +def accept(case): + m=cloud.contract;target=prior.prior.identity() + require(prior.prior.evidence('gate')['unresolved']==0,'no unresolved attempt') + # A maintenance restart only refreshes passive inventory from the preserved + # agent; it never issues a package diagnostic or executes a job. + deadline=time.monotonic()+90 + while True: + device=cloud.Backend().call('inventory.get_device',{k:target[k] for k in ('tenant_id','asset_id')}) + try: + data=prior.adapters.planning_from_device(device,recovery=case=='apt_configure_recovery') + break + except m.GuardError: + require(time.monotonic().json`, +`pending-recovery-.json`, and `recovery-.json`. +Original/retry markers, signed histories and the original unknown proof remain +intact. Recovery produces `native_recovery:true`, `recovery_record_sha256` and +`partial_proof_sha256`; it creates no fresh-install acceptance record or +`native_record_sha256`. A later separately approved native 1.1 upgrade must +provide the ordinary acceptance evidence for the changed provider/runtime. + +Local actual APT 2.6.2, with a vetoing collector and independently guarded fake +dpkg, emitted only the exact configure action/target; real and copied package +status stayed unchanged. This is **local regression evidence**, not Cloud-VM +recovery acceptance. Native deployment, UI approval and execution remain the +parent's next acceptance step. + ## Explicit one-attempt recovery (schema 3, 2026-11-13) Schema 2 keeps its exact old encoding (the optional field is omitted). Schema 3 diff --git a/tools/apt-transaction/README.md b/tools/apt-transaction/README.md index b221112..0215f6a 100644 --- a/tools/apt-transaction/README.md +++ b/tools/apt-transaction/README.md @@ -1,11 +1,21 @@ # Root-helper APT transaction provider / explicit first native acceptance -**Current 2026-11-13:** Cloud fixture retry reached armed hook and APT exit 0, -but independent verification found an unpacked/unconfigured package; outcome -remains **unknown**, with all original/retry tombstones and ledger preserved. -No native acceptance record, package repair or further retry. Root test policy +**Current 2026-11-13:** The Cloud fixture retry reached armed hook and APT exit 0, +leaving fixture 1.0 unpacked/unconfigured. An original-bound readonly proof and +normal signed RootSync now classified that original attempt as **failed** +(`APT_PARTIAL_UNCONFIGURED_VERIFIED`), preserving all histories/tombstones. +No native acceptance record or package repair exists. Root test policy remains closed. Detailed real evidence: `../../docs/implementation-status.md`. +The configure-only recovery path, requiring its own new fixed WebUI approval, is implemented in source +(schema 4 manifest, transaction schema 2), with a dedicated passive recovery +projection and separate immutable recovery records. Its qualified runtime is now installed and its actual Cloud copied-database +sandbox readiness probe passed, preserving original state. **No configure-only +package effect or native package acceptance has yet run.** All **75 Python tests passed** in the offline readonly +unprivileged container, including actual APT 2.6.2 configure-only protocol and +guarded fake-dpkg arguments with unchanged real/copied status. See +[`HELPER-CONTRACT.md`](HELPER-CONTRACT.md) for the precise recovery boundary. + Source configuration now disables APT's `dpkg::selection::remove::approved` rewrite, retaining the exact package's Configure operation while both pending modes remain disabled and hook-pinned. Upstream explanation: @@ -13,8 +23,8 @@ modes remain disabled and hook-pinned. Upstream explanation: Local actual APT 2.6.2 regression in an offline readonly unprivileged container proved unpack + exact `--configure rmm-mvp-test:all`, no `--pending` or foreign target; independent dpkg guard simulated effects, real/copied status unchanged. -67 Python tests passed with this opt-in regression. **This source correction -is not deployed or natively accepted on the Cloud VM.** No automatic repair, +67 Python tests passed with this opt-in regression. **This correction is now installed and sandbox-probed on the Cloud VM; +its native package effect remains unaccepted.** No automatic repair, marker reset or implicit unknown-resolution is introduced. Older sections below describe historical increments; current operational status is the linked log. diff --git a/tools/apt-transaction/apt_transaction.py b/tools/apt-transaction/apt_transaction.py index 54dd3c1..b4ef9f2 100644 --- a/tools/apt-transaction/apt_transaction.py +++ b/tools/apt-transaction/apt_transaction.py @@ -196,16 +196,19 @@ class PackageArchive: archive_path: str @classmethod - def parse(cls, obj): + def parse(cls, obj, configure_only=False): exact(obj, 'name architecture old_version new_version origin sha256 size archive_path') token(obj['name'], NAME, 'PACKAGE_NAME') require(not FORBIDDEN.match(obj['name']), 'PROTECTED_PACKAGE') require(obj['architecture'] in ('amd64', 'all'), 'ARCHITECTURE') token(obj['new_version'], VERSION, 'VERSION') + if configure_only: + require(obj['old_version'] == obj['new_version'] == '1.0', 'RECOVERY_VERSION') if obj['old_version'] is not None: token(obj['old_version'], VERSION, 'VERSION') # Debian ordering, not lexical/semver ordering. Read-only argv. - require(subprocess.run(['/usr/bin/dpkg', '--compare-versions', obj['old_version'], + require((obj['old_version'] == obj['new_version'] == '1.0') if configure_only else + subprocess.run(['/usr/bin/dpkg', '--compare-versions', obj['old_version'], 'lt', obj['new_version']], env=ENV, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0, @@ -229,12 +232,16 @@ class ResolvedAptTransaction: status_fingerprint: str baseline_sha256: str packages: Tuple[PackageArchive, ...] + operation: Optional[str] = None @classmethod def parse(cls, obj): + version = obj.get('schema_version') if type(obj) is dict else None exact(obj, 'schema_version recipe_id recipe_version platform resolver_config_version ' - 'no_reboot status_fingerprint baseline_sha256 packages') - require(type(obj['schema_version']) is int and obj['schema_version'] == 1, 'SCHEMA_VERSION') + 'no_reboot status_fingerprint baseline_sha256 packages' + (' operation' if version == 2 else '')) + require(type(version) is int and version in (1, 2), 'SCHEMA_VERSION') + configure_only = version == 2 + require(not configure_only or obj['operation'] == 'configure_only', 'TRANSACTION_OPERATION') token(obj['recipe_id'], IDENT, 'RECIPE_ID') token(obj['recipe_version'], IDENT, 'RECIPE_VERSION') require(obj['platform'] == 'ubuntu-24.04-amd64', 'UNSUPPORTED_PLATFORM') @@ -244,9 +251,12 @@ class ResolvedAptTransaction: token(obj['baseline_sha256'], HASH, 'FINGERPRINT') require(type(obj['packages']) is list and 0 < len(obj['packages']) <= MAX_PACKAGES, 'PACKAGE_COUNT') - packages = tuple(PackageArchive.parse(p) for p in obj['packages']) + packages = tuple(PackageArchive.parse(p, configure_only=configure_only) for p in obj['packages']) require(len({(p.name, p.architecture) for p in packages}) == len(packages), 'DUPLICATE_PACKAGE') - return cls(**{**obj, 'packages': packages}) + transaction = cls(**{**obj, 'packages': packages}) + if configure_only: + fixture_scope(transaction) + return transaction @dataclass(frozen=True) @@ -336,6 +346,10 @@ def fixture_scope(transaction): 'FIXTURE_RECIPE') require(len(transaction.packages) == 1, 'FIXTURE_CLOSURE') old, new = FIXTURE_RECIPES[transaction.recipe_id] + if transaction.operation == 'configure_only': + require(transaction.schema_version == 2 and transaction.recipe_id == 'rmm-apt-fixture-install-1.0', + 'RECOVERY_FIXED_RECIPE') + old = new = '1.0' package = transaction.packages[0] require(package.name == 'rmm-mvp-test' and package.architecture == 'all' and package.origin == 'rmm-test' and package.old_version == old and package.new_version == new, @@ -370,14 +384,20 @@ def load_signed_action(transaction, context): manifest_keys += ('resolved_apt_transaction provider_sha256 hook_sha256 apt_config_sha256 ' 'runtime_sha256 test_result_id transaction_bytes') version = action.get('schema_version') if type(action) is dict else None - exact(action, manifest_keys + (' native_retry' if version == 3 else '')) + exact(action, manifest_keys + (' native_retry' if version == 3 else ' native_recovery' if version == 4 else '')) require(action['type'] == 'rmm.apt.helper-action' and - type(version) is int and version in (2, 3), + type(version) is int and version in (2, 3, 4), 'SIGNED_ACTION_SCHEMA') if version == 3: validate_retry_reference(action['native_retry']) require(context.action == 'apt-native-acceptance' and context.execution_profile == 'dev-test', 'RETRY_NATIVE_TEST_ONLY') + if version == 4: + validate_recovery_reference(action['native_recovery']) + require(context.action == 'apt-native-acceptance' and context.execution_profile == 'dev-test' and + transaction.operation == 'configure_only', 'RECOVERY_NATIVE_CONFIGURE_ONLY') + else: + require(transaction.operation is None, 'RECOVERY_MANIFEST_REQUIRED') expected_bytes = sealed_read(ACTIVE / 'expectation.json') require(type(action['transaction_bytes']) is list and len(action['transaction_bytes']) <= 65536 and all(type(value) is int and 0 <= value <= 255 for value in action['transaction_bytes']) and @@ -418,6 +438,11 @@ def check_native_gate(transaction, context, action, runtime, native_acceptance): 'DEDICATED_HELPER_ACTION_REQUIRED') path = record_path(transaction) if native_acceptance: + if action.get('native_recovery') is not None: + verify_recovery_reference(transaction, context, action) + require(not os.path.lexists(BASE / ('recovery-' + action['native_recovery']['previous_grant_id'] + '.json')), + 'RECOVERY_ALREADY_RECORDED') + return require(not path.exists(), 'ACCEPTANCE_ALREADY_RECORDED') return proof = json_bytes(sealed_read(path)) @@ -486,6 +511,92 @@ def validate_retry_reference(ref): token(ref['bootstrap_marker_sha256'], HASH, 'RETRY_MARKER_HASH') +def validate_recovery_reference(ref): + exact(ref, 'schema_version previous_grant_id previous_attempt_id partial_proof_sha256') + require(type(ref['schema_version']) is int and ref['schema_version'] == 1, 'RECOVERY_SCHEMA') + for key in ('previous_grant_id', 'previous_attempt_id'): + value = ref[key] + require(type(value) is str and str(uuid.UUID(value)) == value and uuid.UUID(value).int != 0, + 'RECOVERY_ID') + token(ref['partial_proof_sha256'], HASH, 'RECOVERY_PROOF_HASH') + + +def validate_partial_proof(proof): + exact(proof, 'schema_version type transaction_sha256 job_payload_sha256 effect_armed_ledger_id ' + 'grant_id job_id attempt_id authorization_id plan_sha256 original_evidence_sha256 ' + 'original_baseline_sha256 observed_snapshot_sha256 status_fingerprint fixture_payload_sha256 ' + 'snapshot checked_at_ms partial_effect postconditions_passed reboot_required') + require(type(proof['schema_version']) is int and proof['schema_version'] == 1 and + proof['type'] == 'rmm.apt.partial-reconciliation' and proof['partial_effect'] is True and + proof['postconditions_passed'] is False and proof['reboot_required'] is False and + type(proof['checked_at_ms']) is int and proof['checked_at_ms'] > 0, 'RECOVERY_PROOF_TYPE') + for key in ('transaction_sha256', 'job_payload_sha256', 'plan_sha256', 'original_evidence_sha256', + 'original_baseline_sha256', 'observed_snapshot_sha256', 'status_fingerprint', 'fixture_payload_sha256'): + token(proof[key], HASH, 'RECOVERY_PROOF_HASH') + for key in ('grant_id','job_id','attempt_id','authorization_id'): + value = proof[key] + require(type(value) is str and str(uuid.UUID(value)) == value and uuid.UUID(value).int != 0, + 'RECOVERY_PROOF_ID') + token(proof['effect_armed_ledger_id'], IDENT, 'RECOVERY_PROOF_LEDGER') + require(type(proof['snapshot']) is dict and + digest(canonical(proof['snapshot'])) == proof['observed_snapshot_sha256'] and + proof['snapshot'].get('rmm-mvp-test:all') == {'version':'1.0','status':'install ok unpacked'} and + proof['fixture_payload_sha256'] == digest(b'1.0\n'), 'RECOVERY_PROOF_SNAPSHOT') + + +def verify_recovery_reference(transaction, context, action): + """Only immutable linkage here; current state is checked before the hook. + + RootHelper additionally requires this proof in its original shared SQLite + ledger with terminal classified failure and the original verified Request. + Caller-provided JSON or a root-owned file alone never grants authority. + """ + ref = action['native_recovery']; validate_recovery_reference(ref) + require(context.action == 'apt-native-acceptance' and context.execution_profile == 'dev-test' and + action['schema_version'] == 4 and transaction.schema_version == 2 and + transaction.operation == 'configure_only', 'RECOVERY_DEDICATED_ACTION') + fixture_scope(transaction) + raw_proof = sealed_read(ACTIVE / 'partial-proof.json') + proof = json_bytes(raw_proof); validate_partial_proof(proof) + require(raw_proof == canonical(proof) and digest(raw_proof) == ref['partial_proof_sha256'] and + proof['grant_id'] == ref['previous_grant_id'] and proof['attempt_id'] == ref['previous_attempt_id'], + 'RECOVERY_IMMUTABLE_PROOF_BINDING') + require(context.grant_id != proof['grant_id'] and context.attempt_id != proof['attempt_id'] and + context.job_id != proof['job_id'] and context.authorization_id != proof['authorization_id'] and + context.plan_sha256 != proof['plan_sha256'], 'RECOVERY_NEW_APPROVAL_REQUIRED') + require(transaction.baseline_sha256 == proof['observed_snapshot_sha256'] and + transaction.status_fingerprint == proof['status_fingerprint'] and + sealed_read(ACTIVE / 'baseline.json') == canonical(proof['snapshot']), 'RECOVERY_BASELINE_BINDING') + previous = BASE / 'history' / ref['previous_grant_id'] + secure_path(previous, directory=True, private=True) + names = ('context.json','signed-action.json','expectation.json','baseline.json','launch.json', + 'native-prechecks.json','sandbox-ready.json','sandbox-result.json','hook-armed.json') + historical = {name: sealed_read(previous / name) for name in names} + for prefix in ('bootstrap-attempt-', 'bootstrap-retry-'): + name = prefix + 'rmm-apt-fixture-install-1.0.json' + historical[name] = sealed_read(BASE / name) + require(digest(canonical({name:digest(raw) for name,raw in historical.items()})) == + proof['original_evidence_sha256'], 'RECOVERY_HISTORY_CHANGED') + old = VerifiedHelperContext.parse(json_bytes(historical['context.json'])) + require(all(getattr(old, key) == proof[key] for key in + ('transaction_sha256','job_payload_sha256','effect_armed_ledger_id','grant_id', + 'job_id','attempt_id','authorization_id','plan_sha256')) and + digest(historical['signed-action.json']) == proof['job_payload_sha256'] and + digest(historical['expectation.json']) == proof['transaction_sha256'] and + digest(historical['baseline.json']) == proof['original_baseline_sha256'], + 'RECOVERY_ORIGINAL_CONTEXT_BINDING') + old_job = json_bytes(historical['signed-action.json']) + new_job = json_bytes(sealed_read(ACTIVE / 'signed-action.json')) + require(all(old_job[key] == new_job[key] for key in + ('tenant_id','asset_id','agent_id','enrollment_generation','assignment_version')) and + digest(sealed_read(previous / 'apt.conf')) == old_job['action']['apt_manifest']['apt_config_sha256'], + 'RECOVERY_ORIGINAL_TARGET_OR_CONFIG') + require(not os.path.lexists(BASE / 'acceptance-rmm-apt-fixture-install-1.0.json') and + not os.path.lexists(BASE / 'pending-acceptance-rmm-apt-fixture-install-1.0.json'), + 'RECOVERY_NOT_INSTALL_ACCEPTANCE') + return proof + + def historical_retry_evidence(transaction, context, action): """Recheck immutable no-handoff evidence, never turn unknown into failed. @@ -549,6 +660,10 @@ def historical_retry_evidence(transaction, context, action): def bootstrap_binding(transaction, context, action): binding = attempt_binding(context) + if action.get('native_recovery') is not None: + verify_recovery_reference(transaction, context, action) + binding.update(native_recovery=action['native_recovery']) + return BASE / ('recovery-attempt-' + action['native_recovery']['previous_grant_id'] + '.json'), binding if action.get('native_retry') is not None: binding.update(native_retry=action['native_retry'], previous_evidence_sha256= historical_retry_evidence(transaction, context, action)) @@ -664,8 +779,16 @@ def complete_acceptance(transaction, context, action, runtime, evidence): 'completed_at_ms': time.time_ns() // 1000000} # Stage+fsync complete bytes before publishing. Failed writes never leave a # parseable final partial record. An existing final record is never replaced. - path = record_path(transaction) - staged = BASE / ('pending-acceptance-' + transaction.recipe_id + '.json') + recovery = action.get('native_recovery') + if recovery is not None: + verify_recovery_reference(transaction, context, action) + proof.update(schema_version=1, type='rmm.apt.native-recovery', operation='configure_only', + native_recovery=recovery) + path = BASE / ('recovery-' + recovery['previous_grant_id'] + '.json') + staged = BASE / ('pending-recovery-' + recovery['previous_grant_id'] + '.json') + else: + path = record_path(transaction) + staged = BASE / ('pending-acceptance-' + transaction.recipe_id + '.json') durable_once(staged, proof) linked = False try: @@ -681,6 +804,11 @@ def complete_acceptance(transaction, context, action, runtime, evidence): path.unlink() raise # Retain staged bytes as an immutable record witness; never reset attempts. + if recovery is not None: + return {'test_acceptance': True, 'noProductionEvidence': True, 'native_recovery': True, + 'recovery_record_sha256': digest(canonical(proof)), + 'partial_proof_sha256': recovery['partial_proof_sha256'], + 'test_result_id': action['test_result_id']} return {'test_acceptance': True, 'noProductionEvidence': True, 'native_record_sha256': digest(canonical(proof)), 'test_result_id': action['test_result_id']} @@ -747,6 +875,12 @@ def parse_protocol3(data): def validate_actions(transaction, actions): + if transaction.operation == 'configure_only': + fixture_scope(transaction) + require(len(actions) == 1 and actions[0] == Action( + 'rmm-mvp-test', '1.0', 'all', 'none', '=', '1.0', 'all', 'none', '**CONFIGURE**'), + 'RECOVERY_CONFIGURE_ACTION_ONLY') + return expected = {(p.name, p.architecture): p for p in transaction.packages} seen = set() for action in actions: @@ -876,7 +1010,13 @@ def installed_snapshot(): def check_current_baseline(transaction, baseline): require(digest(canonical(baseline)) == transaction.baseline_sha256, 'BASELINE_HASH') require(status_fingerprint() == transaction.status_fingerprint, 'STATUS_FINGERPRINT') - require(installed_snapshot() == baseline, 'STATUS_BASELINE_CHANGED') + snapshot = partial_installed_snapshot() if transaction.operation == 'configure_only' else installed_snapshot() + require(snapshot == baseline, 'STATUS_BASELINE_CHANGED') + if transaction.operation == 'configure_only': + fixture_scope(transaction) + require(baseline.get('rmm-mvp-test:all') == {'version': '1.0', 'status': 'install ok unpacked'} and + sealed_read(Path('/usr/share/rmm-mvp-test/version'), limit=32) == b'1.0\n', + 'RECOVERY_PARTIAL_PRECONDITION') def check_preconditions(transaction, baseline): @@ -884,7 +1024,8 @@ def check_preconditions(transaction, baseline): for p in transaction.packages: current = baseline.get(p.name + ':' + p.architecture) require((current is None if p.old_version is None else - current == {'version': p.old_version, 'status': 'install ok installed'}), + current == {'version': p.old_version, 'status': + 'install ok unpacked' if transaction.operation == 'configure_only' else 'install ok installed'}), 'PACKAGE_PRECONDITION') @@ -933,6 +1074,10 @@ DPkg::Tools::Options::/usr/lib/rmm-apt-transaction/hook::InfoFD "0"; def apt_argv(transaction): + if transaction.operation == 'configure_only': + fixture_scope(transaction) + return ['/usr/bin/apt-get', '--yes', '--no-remove', '--no-install-recommends', + 'install', '--', 'rmm-mvp-test=1.0'] # APT's --no-download also prevents the local file method from resolving # its Install filename (v3 emits **ERROR**). Permit local acquisition of # the already sealed/hash-checked archive. Empty sources, fixed paths and @@ -1445,7 +1590,10 @@ def execute(request, native_acceptance=False): check_current_baseline(transaction, baseline) for package in transaction.packages: verify_archive(package) - require(run_read(['/usr/bin/dpkg', '--audit']) == b'', 'DPKG_AUDIT') + # The exact bound unpacked fixture is the declared recovery input; + # ordinary jobs continue to require a clean audit before mutation. + if transaction.operation != 'configure_only': + require(run_read(['/usr/bin/dpkg', '--audit']) == b'', 'DPKG_AUDIT') context.check_deadline() if not native_acceptance: evidence = verified_no_change(transaction, baseline, context) @@ -1475,7 +1623,8 @@ def execute(request, native_acceptance=False): if not armed: # Trusted fixed config makes a missing hook a veto, not an # after-the-fact substitute for pre-dpkg validation. - require(installed_snapshot() == baseline, 'MISSING_HOOK_WITH_CHANGE') + current = partial_installed_snapshot() if transaction.operation == 'configure_only' else installed_snapshot() + require(current == baseline, 'MISSING_HOOK_WITH_CHANGE') return {'effect_state': 'known_failed', 'code': 'HOOK_NOT_HANDED_OFF', 'evidence': {'test_acceptance': True, 'noProductionEvidence': True} if native_acceptance else {}} @@ -1561,7 +1710,38 @@ def prepare_baseline_store(): 'native_acceptance_created': False} +def recovery_planning(request): + """Fresh passive projection of one ledger-verified, closed partial failure. + + Rust verifies the signed original request, terminal failure and immutable + SQLite proof before invoking this fixed mode. No job or execution is made. + """ + exact(request, 'native_recovery proof') + ref, proof = request['native_recovery'], request['proof'] + validate_recovery_reference(ref) + validate_partial_proof(proof) + require(digest(canonical(proof)) == ref['partial_proof_sha256'] and + proof['grant_id'] == ref['previous_grant_id'] and + proof['attempt_id'] == ref['previous_attempt_id'], 'RECOVERY_PLANNING_PROOF_BINDING') + fields = ('transaction_sha256 job_payload_sha256 effect_armed_ledger_id grant_id ' + 'job_id attempt_id authorization_id plan_sha256') + current = verify_partial({key: proof[key] for key in fields.split()})['proof'] + require({key: value for key, value in current.items() if key != 'checked_at_ms'} == + {key: value for key, value in proof.items() if key != 'checked_at_ms'}, + 'RECOVERY_PLANNING_STATE_CHANGED') + require(not os.path.lexists(BASE / ('recovery-attempt-' + ref['previous_grant_id'] + '.json')) and + not os.path.lexists(BASE / ('recovery-' + ref['previous_grant_id'] + '.json')), + 'RECOVERY_ALREADY_ATTEMPTED') + result = _planning_status(proof) + result['native_recovery'] = ref + return result + + def planning_status(): + return _planning_status() + + +def _planning_status(recovery_proof=None): """Fixed passive fixture projection; complete dpkg state remains root-private. Only content-addressed, fsynced helper metadata may be created here. No @@ -1574,7 +1754,11 @@ def planning_status(): require(not observe_host_frontend_lock() and not observe_host_frontend_lock(Path('/var/lib/dpkg/lock')), 'FOREIGN_PACKAGE_LOCK') fingerprint = status_fingerprint() # Vetoes dirty updates/pending triggers. - snapshot = installed_snapshot() + snapshot_reader = partial_installed_snapshot if recovery_proof is not None else installed_snapshot + snapshot = snapshot_reader() + if recovery_proof is not None: + require(snapshot == recovery_proof['snapshot'] and fingerprint == recovery_proof['status_fingerprint'], + 'RECOVERY_PLANNING_STATE_CHANGED') runtime = runtime_identity() prefetch = {} for version in ('1.0', '1.1'): @@ -1590,7 +1774,7 @@ def planning_status(): type(receipt['sealed_at_ms']) is int and 0 < receipt['sealed_at_ms'] <= time.time_ns() // 1000000, 'PREFETCH_RECEIPT') prefetch[sha] = receipt - require(status_fingerprint() == fingerprint and installed_snapshot() == snapshot, + require(status_fingerprint() == fingerprint and snapshot_reader() == snapshot, 'PLANNING_STATE_CHANGED') require(not observe_host_frontend_lock() and not observe_host_frontend_lock(Path('/var/lib/dpkg/lock')), 'FOREIGN_PACKAGE_LOCK') @@ -1615,7 +1799,7 @@ def planning_status(): else: durable_once(path, snapshot) # Do not publish a stale baseline if state changed during fsync. - require(status_fingerprint() == fingerprint and installed_snapshot() == snapshot, + require(status_fingerprint() == fingerprint and snapshot_reader() == snapshot, 'PLANNING_STATE_CHANGED') return {'observed_at': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()), 'fixture_package': snapshot.get('rmm-mvp-test:all'), @@ -1839,6 +2023,8 @@ def main(): sys.stdout.buffer.write(canonical(prepare_baseline_store()) + b'\n') elif mode == 'planning-status': sys.stdout.buffer.write(canonical(planning_status()) + b'\n') + elif mode == 'recovery-planning': + sys.stdout.buffer.write(canonical(recovery_planning(json_bytes(sys.stdin.buffer.read(MAX_INPUT + 1)))) + b'\n') elif mode == 'probe-native': sys.stdout.buffer.write(canonical(probe_native()) + b'\n') elif mode == 'probe-worker':