feat: qualify bound configure-only recovery runtime on cloud VM
Rust development slice / linux (push) Failing after 6s

This commit is contained in:
2026-11-13 18:07:46 +01:00
parent b24314da9e
commit 2230235dfb
21 changed files with 1749 additions and 80 deletions
+182 -7
View File
@@ -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<rmm_domain::apt_transaction::AptNativeRecovery>,
pub observed_at: chrono::DateTime<chrono::Utc>,
pub fixture_package: Option<FixturePackage>,
pub baseline_sha256: String,
@@ -106,6 +108,16 @@ pub struct PlanningReceipt {
}
impl PlanningResult {
pub fn validate(&self, now: chrono::DateTime<chrono::Utc>) -> 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<Response> {
pub fn planning(socket: &Path, binding: &Binding, pin: &Pin) -> Result<Response> {
probe_operation(socket, binding, pin, "apt_planning_v1")
}
pub fn planning_for_recovery(socket: &Path, binding: &Binding, pin: &Pin) -> Result<Response> {
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<PlanningResult> {
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<Vec<u8>> {
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),