1258 lines
49 KiB
Rust
1258 lines
49 KiB
Rust
//! Typed, root-only APT bridge. No network fetch, shell conversion or capability
|
|
//! advertisement. The public constructor always re-verifies the signed request.
|
|
use crate::{Binding, Outcome, Request, private_path};
|
|
use anyhow::{Context, Result, bail, ensure};
|
|
use chrono::{DateTime, Utc};
|
|
use rmm_domain::jobs::{ExecutionPermitPayload, JobPayload, hash};
|
|
use serde::{Deserialize, Serialize};
|
|
use serde_json::Value;
|
|
use std::{
|
|
collections::BTreeMap,
|
|
fs::{self, File, OpenOptions},
|
|
io::{Read, Write},
|
|
os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt},
|
|
path::{Path, PathBuf},
|
|
process::{Command, Stdio},
|
|
};
|
|
|
|
const BASE: &str = "/var/lib/rmm-apt-transaction";
|
|
pub const CODE: &str = "/usr/lib/rmm-apt-transaction/apt_transaction.py";
|
|
const HOOK: &str = "/usr/lib/rmm-apt-transaction/hook";
|
|
const PYTHON: &[u8] = include_bytes!("../../../tools/apt-transaction/apt_transaction.py");
|
|
const HOOK_BYTES: &[u8] = include_bytes!("../../../tools/apt-transaction/hook");
|
|
pub const INSTALL_RECIPE: &str = "rmm-apt-fixture-install-1.0";
|
|
pub const UPDATE_RECIPE: &str = "rmm-apt-fixture-update-1.1";
|
|
const INSTALL_SHA: &str = "74036ae81223deab3aae994fd2a2a695af408741777e1ce17dcb4e32f1235867";
|
|
const UPDATE_SHA: &str = "ef67c9fe0ba1443fcfe465768e1204763063c369a2a1da04af6027d8a9c00491";
|
|
|
|
#[derive(Clone, Debug, Deserialize, Serialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct ProviderConfig {
|
|
pub schema_version: u32,
|
|
pub execution_profile: String,
|
|
pub allow_fixture_bootstrap: bool,
|
|
pub allowed_recipes: Vec<String>,
|
|
pub runtime_sha256: String,
|
|
pub apt_config_sha256: String,
|
|
}
|
|
impl ProviderConfig {
|
|
pub fn validate(&self) -> Result<()> {
|
|
ensure!(
|
|
self.schema_version == 1 && self.execution_profile == "dev-test",
|
|
"APT_PROFILE_NOT_CONFIGURED"
|
|
);
|
|
ensure!(
|
|
!self.allowed_recipes.is_empty()
|
|
&& self.allowed_recipes.len() <= 2
|
|
&& self
|
|
.allowed_recipes
|
|
.iter()
|
|
.all(|r| matches!(r.as_str(), INSTALL_RECIPE | UPDATE_RECIPE)),
|
|
"APT_RECIPE_POLICY"
|
|
);
|
|
sha(&self.runtime_sha256)?;
|
|
sha(&self.apt_config_sha256)
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct PackageArchive {
|
|
pub name: String,
|
|
pub architecture: String,
|
|
pub old_version: Option<String>,
|
|
pub new_version: String,
|
|
pub origin: String,
|
|
pub sha256: String,
|
|
pub size: u64,
|
|
pub archive_path: String,
|
|
}
|
|
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct ResolvedAptTransaction {
|
|
pub schema_version: u32,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub operation: Option<rmm_domain::apt_transaction::AptTransactionOperation>,
|
|
pub recipe_id: String,
|
|
pub recipe_version: String,
|
|
pub platform: String,
|
|
pub resolver_config_version: String,
|
|
pub no_reboot: bool,
|
|
pub status_fingerprint: String,
|
|
pub baseline_sha256: String,
|
|
pub packages: Vec<PackageArchive>,
|
|
}
|
|
impl ResolvedAptTransaction {
|
|
pub fn validate_fixture(&self) -> Result<()> {
|
|
ensure!(
|
|
self.recipe_version == "1"
|
|
&& self.platform == "ubuntu-24.04-amd64"
|
|
&& self.resolver_config_version == "rmm-apt-local-v1"
|
|
&& self.no_reboot
|
|
&& self.packages.len() == 1,
|
|
"APT_TRANSACTION_SCOPE"
|
|
);
|
|
sha(&self.status_fingerprint)?;
|
|
sha(&self.baseline_sha256)?;
|
|
let p = &self.packages[0];
|
|
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!(
|
|
p.name == "rmm-mvp-test"
|
|
&& p.architecture == "all"
|
|
&& p.origin == "rmm-test"
|
|
&& p.old_version.as_deref() == old
|
|
&& p.new_version == new
|
|
&& p.sha256 == expected_hash
|
|
&& p.size == 20672
|
|
&& p.archive_path == format!("{BASE}/archives/{expected_hash}.deb"),
|
|
"APT_FIXTURE_BYTES_OR_CLOSURE"
|
|
);
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
/// Must be a field named `apt_manifest` of the signed domain Action. The full
|
|
/// transaction object AND its exact serialized bytes are part of those bytes.
|
|
#[derive(Clone, Debug, Deserialize, Serialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct AptExecutionManifest {
|
|
#[serde(rename = "type")]
|
|
pub kind: String,
|
|
pub schema_version: u32,
|
|
pub action: String,
|
|
pub execution_profile: String,
|
|
pub transaction_sha256: String,
|
|
pub resolved_apt_transaction: ResolvedAptTransaction,
|
|
pub transaction_bytes: Vec<u8>,
|
|
pub provider_sha256: String,
|
|
pub hook_sha256: String,
|
|
pub apt_config_sha256: String,
|
|
pub runtime_sha256: String,
|
|
pub test_result_id: String,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub native_retry: Option<rmm_domain::apt_transaction::AptNativeRetry>,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub native_recovery: Option<rmm_domain::apt_transaction::AptNativeRecovery>,
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
struct ActionCarrier {
|
|
action: String,
|
|
apt_manifest: Option<AptExecutionManifest>,
|
|
#[serde(flatten)]
|
|
parameters: BTreeMap<String, serde_json::Value>,
|
|
}
|
|
#[derive(Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
struct SignedJob {
|
|
schema_version: u32,
|
|
tenant_id: uuid::Uuid,
|
|
asset_id: uuid::Uuid,
|
|
agent_id: uuid::Uuid,
|
|
enrollment_generation: u64,
|
|
assignment_version: u64,
|
|
job_id: uuid::Uuid,
|
|
attempt_id: uuid::Uuid,
|
|
action: ActionCarrier,
|
|
execution_identity: String,
|
|
not_before: DateTime<Utc>,
|
|
start_before: DateTime<Utc>,
|
|
max_runtime_seconds: u32,
|
|
max_output_bytes: u32,
|
|
}
|
|
|
|
pub fn is_apt_action(job: &JobPayload) -> bool {
|
|
matches!(
|
|
job.action.name(),
|
|
"ensure_package" | "apply_updates" | "apt_native_acceptance"
|
|
)
|
|
}
|
|
pub fn policy_header(job: &JobPayload, config: &ProviderConfig) -> Result<()> {
|
|
config.validate()?;
|
|
ensure!(
|
|
is_apt_action(job) && job.execution_identity == "root" && job.max_runtime_seconds >= 180,
|
|
"APT_EXPLICIT_ROOT_AND_RUNTIME_REQUIRED"
|
|
);
|
|
ensure!(
|
|
job.action.name() != "apt_native_acceptance" || config.allow_fixture_bootstrap,
|
|
"APT_BOOTSTRAP_DENIED"
|
|
);
|
|
Ok(())
|
|
}
|
|
|
|
/// Opaque verified capability: callers cannot manufacture one from a manifest.
|
|
pub struct PreparedApt {
|
|
binding: Binding,
|
|
job: JobPayload,
|
|
permit: ExecutionPermitPayload,
|
|
request: Request,
|
|
manifest: AptExecutionManifest,
|
|
}
|
|
pub fn prepare(
|
|
binding: &Binding,
|
|
request: &Request,
|
|
config: &ProviderConfig,
|
|
now: DateTime<Utc>,
|
|
) -> Result<PreparedApt> {
|
|
let (job, permit) = binding.verify(request, now)?;
|
|
policy_header(&job, config)?;
|
|
let manifest = validate_signed_manifest(&job, &request.job_bytes, config)?;
|
|
verify_installation()?;
|
|
verify_prefetched(&manifest, &permit)?;
|
|
Ok(PreparedApt {
|
|
binding: binding.clone(),
|
|
job,
|
|
permit,
|
|
request: request.clone(),
|
|
manifest,
|
|
})
|
|
}
|
|
|
|
fn validate_signed_manifest(
|
|
job: &JobPayload,
|
|
bytes: &[u8],
|
|
config: &ProviderConfig,
|
|
) -> Result<AptExecutionManifest> {
|
|
let signed: SignedJob = serde_json::from_slice(bytes)?;
|
|
ensure!(
|
|
signed.schema_version == job.schema_version
|
|
&& signed.tenant_id == job.tenant_id
|
|
&& signed.asset_id == job.asset_id
|
|
&& signed.agent_id == job.agent_id
|
|
&& signed.enrollment_generation == job.enrollment_generation
|
|
&& signed.assignment_version == job.assignment_version
|
|
&& signed.job_id == job.job_id
|
|
&& signed.attempt_id == job.attempt_id
|
|
&& signed.execution_identity == job.execution_identity
|
|
&& signed.not_before == job.not_before
|
|
&& signed.start_before == job.start_before
|
|
&& signed.max_runtime_seconds == job.max_runtime_seconds
|
|
&& signed.max_output_bytes == job.max_output_bytes
|
|
&& signed.action.action == job.action.name(),
|
|
"APT_SIGNED_JOB_BINDING"
|
|
);
|
|
let manifest = signed
|
|
.action
|
|
.apt_manifest
|
|
.context("APT_MANIFEST_NOT_CONFIGURED")?;
|
|
validate_manifest(&manifest, job.action.name(), config)?;
|
|
// Domain deserialization must preserve the manifest, not ignore an unknown
|
|
// field. This is the explicit fail-closed gate until the additive domain
|
|
// contract lands. No separately supplied unsigned manifest is accepted.
|
|
let mut domain_action = serde_json::to_value(&job.action)?;
|
|
let embedded = domain_action
|
|
.as_object_mut()
|
|
.context("APT_ACTION_OBJECT")?
|
|
.remove("apt_manifest")
|
|
.context("APT_DOMAIN_MANIFEST_NOT_CONFIGURED")?;
|
|
let domain_manifest: AptExecutionManifest = serde_json::from_value(embedded)?;
|
|
ensure!(
|
|
serde_json::to_vec(&domain_manifest)? == serde_json::to_vec(&manifest)?,
|
|
"APT_DOMAIN_MANIFEST_MISMATCH"
|
|
);
|
|
let mut original = serde_json::to_value(signed.action.parameters)?;
|
|
original
|
|
.as_object_mut()
|
|
.context("APT_PARAMETERS")?
|
|
.insert("action".into(), serde_json::json!(job.action.name()));
|
|
ensure!(
|
|
original == domain_action,
|
|
"APT_PARAMETERS_ALIAS_OR_MISMATCH"
|
|
);
|
|
// Approved recipe identity is explicit outside the manifest too. Normal
|
|
// updates bind provider, selected package names and reboot policy as well.
|
|
let t = &manifest.resolved_apt_transaction;
|
|
if job.action.name() == "apply_updates" {
|
|
ensure!(
|
|
original.get("provider") == Some(&serde_json::json!("apt"))
|
|
&& original.get("packages") == Some(&serde_json::json!(["rmm-mvp-test"]))
|
|
&& original.get("reboot_policy") == Some(&serde_json::json!("never"))
|
|
&& t.recipe_id == UPDATE_RECIPE,
|
|
"APT_UPDATE_SELECTION"
|
|
);
|
|
} else {
|
|
ensure!(
|
|
original.get("recipe_id") == Some(&serde_json::json!(t.recipe_id))
|
|
&& original.get("recipe_version") == Some(&serde_json::json!(t.recipe_version)),
|
|
"APT_RECIPE_PARAMETER_BINDING"
|
|
);
|
|
if job.action.name() == "ensure_package" {
|
|
let package = &t.packages[0];
|
|
ensure!(
|
|
original.get("provider") == Some(&serde_json::json!("apt"))
|
|
&& original.get("package") == Some(&serde_json::json!(package.name))
|
|
&& original.get("version") == Some(&serde_json::json!(package.new_version))
|
|
&& original.get("architecture")
|
|
== Some(&serde_json::json!(package.architecture))
|
|
&& original.get("installation_context") == Some(&serde_json::json!("system")),
|
|
"APT_ENSURE_TARGET_BINDING"
|
|
);
|
|
}
|
|
}
|
|
Ok(manifest)
|
|
}
|
|
fn validate_manifest(
|
|
m: &AptExecutionManifest,
|
|
action: &str,
|
|
config: &ProviderConfig,
|
|
) -> Result<()> {
|
|
config.validate()?;
|
|
ensure!(
|
|
m.kind == "rmm.apt.helper-action"
|
|
&& 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
|
|
&& !m.test_result_id.is_empty()
|
|
&& m.test_result_id.len() <= 128
|
|
&& m.test_result_id
|
|
.bytes()
|
|
.all(|b| b.is_ascii_alphanumeric() || b"_.-".contains(&b)),
|
|
"APT_MANIFEST_SCHEMA"
|
|
);
|
|
let bootstrap = action == "apt_native_acceptance";
|
|
ensure!(
|
|
matches!(
|
|
action,
|
|
"ensure_package" | "apply_updates" | "apt_native_acceptance"
|
|
) && m.action
|
|
== if bootstrap {
|
|
"apt-native-acceptance"
|
|
} else {
|
|
"apt-execute"
|
|
}
|
|
&& (!bootstrap || config.allow_fixture_bootstrap),
|
|
"APT_DEDICATED_ACTION_BINDING"
|
|
);
|
|
m.resolved_apt_transaction.validate_fixture()?;
|
|
ensure!(
|
|
config
|
|
.allowed_recipes
|
|
.contains(&m.resolved_apt_transaction.recipe_id),
|
|
"APT_RECIPE_POLICY"
|
|
);
|
|
ensure!(
|
|
m.transaction_bytes.len() <= 65536 && hash(&m.transaction_bytes) == m.transaction_sha256,
|
|
"APT_TRANSACTION_EXACT_BYTES_HASH"
|
|
);
|
|
let decoded: ResolvedAptTransaction = serde_json::from_slice(&m.transaction_bytes)?;
|
|
ensure!(
|
|
decoded == m.resolved_apt_transaction,
|
|
"APT_NESTED_TRANSACTION_BINDING"
|
|
);
|
|
ensure!(
|
|
m.provider_sha256 == hash(PYTHON)
|
|
&& m.hook_sha256 == hash(HOOK_BYTES)
|
|
&& m.runtime_sha256 == config.runtime_sha256
|
|
&& m.apt_config_sha256 == config.apt_config_sha256,
|
|
"APT_APPROVED_CODE_OR_RUNTIME"
|
|
);
|
|
for value in [
|
|
&m.transaction_sha256,
|
|
&m.provider_sha256,
|
|
&m.hook_sha256,
|
|
&m.runtime_sha256,
|
|
&m.apt_config_sha256,
|
|
] {
|
|
sha(value)?;
|
|
}
|
|
Ok(())
|
|
}
|
|
fn sha(value: &str) -> Result<()> {
|
|
ensure!(
|
|
value.len() == 64
|
|
&& value
|
|
.bytes()
|
|
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)),
|
|
"APT_SHA256"
|
|
);
|
|
Ok(())
|
|
}
|
|
|
|
fn secure(path: &Path, uid: u32, private: bool, directory: bool) -> Result<()> {
|
|
ensure!(
|
|
path.is_absolute()
|
|
&& !path
|
|
.components()
|
|
.any(|c| matches!(c, std::path::Component::ParentDir)),
|
|
"APT_PATH"
|
|
);
|
|
for component in path.ancestors() {
|
|
let m = fs::symlink_metadata(component)?;
|
|
ensure!(
|
|
!m.file_type().is_symlink() && m.uid() == uid && m.mode() & 0o022 == 0,
|
|
"APT_UNSAFE_PATH_COMPONENT"
|
|
);
|
|
}
|
|
if private {
|
|
private_path(path, uid, directory)?;
|
|
}
|
|
let m = fs::symlink_metadata(path)?;
|
|
ensure!(
|
|
if directory { m.is_dir() } else { m.is_file() },
|
|
"APT_PATH_TYPE"
|
|
);
|
|
Ok(())
|
|
}
|
|
fn read_sealed(path: &Path, limit: u64) -> Result<Vec<u8>> {
|
|
secure(path, 0, false, false)?;
|
|
let mut f = OpenOptions::new()
|
|
.read(true)
|
|
.custom_flags(libc::O_NOFOLLOW)
|
|
.open(path)?;
|
|
ensure!(f.metadata()?.len() <= limit, "APT_FILE_LIMIT");
|
|
let mut bytes = vec![];
|
|
(&mut f).take(limit + 1).read_to_end(&mut bytes)?;
|
|
ensure!(bytes.len() as u64 <= limit, "APT_FILE_LIMIT");
|
|
Ok(bytes)
|
|
}
|
|
fn create_dir(path: &Path, mode: u32) -> Result<()> {
|
|
fs::DirBuilder::new().mode(mode).create(path)?;
|
|
File::open(path.parent().context("APT_PARENT")?)?.sync_all()?;
|
|
Ok(())
|
|
}
|
|
fn write_once(path: &Path, bytes: &[u8], mode: u32) -> Result<()> {
|
|
let mut f = OpenOptions::new()
|
|
.write(true)
|
|
.create_new(true)
|
|
.mode(mode)
|
|
.custom_flags(libc::O_NOFOLLOW)
|
|
.open(path)?;
|
|
f.write_all(bytes)?;
|
|
f.sync_all()?;
|
|
File::open(path.parent().context("APT_PARENT")?)?.sync_all()?;
|
|
Ok(())
|
|
}
|
|
fn json_once(path: &Path, value: &impl Serialize) -> Result<()> {
|
|
write_once(path, &serde_json::to_vec(value)?, 0o600)
|
|
}
|
|
|
|
#[derive(Serialize, Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
struct InstallMetadata {
|
|
schema_version: u32,
|
|
provider_sha256: String,
|
|
hook_sha256: String,
|
|
unit_sha256: String,
|
|
}
|
|
/// Administrator bootstrap only, not a network job. Compile-time known bytes,
|
|
/// fixed paths, create-only. Does not grant execution or create acceptance.
|
|
pub fn install_known_payloads() -> Result<()> {
|
|
ensure_root()?;
|
|
secure(Path::new("/usr/lib"), 0, false, true)?;
|
|
secure(Path::new("/var/lib"), 0, false, true)?;
|
|
create_dir(Path::new("/usr/lib/rmm-apt-transaction"), 0o755)?;
|
|
write_once(Path::new(CODE), PYTHON, 0o644)?;
|
|
write_once(Path::new(HOOK), HOOK_BYTES, 0o755)?;
|
|
secure(Path::new("/etc/systemd/system"), 0, false, true)?;
|
|
write_once(
|
|
Path::new(crate::readiness::UNIT_PATH),
|
|
crate::readiness::UNIT_BYTES,
|
|
0o644,
|
|
)?;
|
|
secure(Path::new("/usr/share"), 0, false, true)?;
|
|
create_dir(Path::new("/usr/share/rmm-mvp-test"), 0o755)?;
|
|
create_dir(Path::new(BASE), 0o700)?;
|
|
for dir in ["archives", "baselines", "history", "probes", "log", "state"] {
|
|
create_dir(&Path::new(BASE).join(dir), 0o700)?;
|
|
}
|
|
json_once(
|
|
&Path::new(BASE).join("install-metadata.json"),
|
|
&InstallMetadata {
|
|
schema_version: 2,
|
|
provider_sha256: hash(PYTHON),
|
|
hook_sha256: hash(HOOK_BYTES),
|
|
unit_sha256: hash(crate::readiness::UNIT_BYTES),
|
|
},
|
|
)
|
|
}
|
|
fn ensure_root() -> Result<()> {
|
|
// SAFETY: geteuid has no preconditions or pointers.
|
|
ensure!(unsafe { libc::geteuid() } == 0, "APT_ROOT_REQUIRED");
|
|
Ok(())
|
|
}
|
|
pub fn verify_installation() -> Result<()> {
|
|
ensure_root()?;
|
|
secure(Path::new(BASE), 0, true, true)?;
|
|
let metadata: InstallMetadata = serde_json::from_slice(&read_sealed(
|
|
&Path::new(BASE).join("install-metadata.json"),
|
|
4096,
|
|
)?)?;
|
|
ensure!(
|
|
metadata.schema_version == 2
|
|
&& metadata.provider_sha256 == hash(PYTHON)
|
|
&& metadata.hook_sha256 == hash(HOOK_BYTES)
|
|
&& metadata.unit_sha256 == hash(crate::readiness::UNIT_BYTES)
|
|
&& read_sealed(Path::new(crate::readiness::UNIT_PATH), 65536)?
|
|
== crate::readiness::UNIT_BYTES
|
|
&& read_sealed(Path::new(CODE), 1024 * 1024)? == PYTHON
|
|
&& read_sealed(Path::new(HOOK), 4096)? == HOOK_BYTES,
|
|
"APT_INSTALLATION_MISMATCH"
|
|
);
|
|
// Interpreter may be the distro's root-owned symlink, never a caller path.
|
|
secure(&fs::canonicalize("/usr/bin/python3")?, 0, false, false)
|
|
}
|
|
pub fn verify_controller_profile() -> Result<()> {
|
|
verify_installation()?;
|
|
let status = Command::new("/usr/bin/python3")
|
|
.args(["-I", CODE, "verify-controller"])
|
|
.env_clear()
|
|
.env("PATH", "/usr/bin:/bin")
|
|
.env("LC_ALL", "C")
|
|
.stdin(Stdio::null())
|
|
.stdout(Stdio::null())
|
|
.stderr(Stdio::null())
|
|
.status()?;
|
|
ensure!(status.success(), "APT_CONTROLLER_PROFILE_REQUIRED");
|
|
Ok(())
|
|
}
|
|
#[derive(Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
struct PrefetchReceipt {
|
|
schema_version: u32,
|
|
sha256: String,
|
|
size: u64,
|
|
sealed_at_ms: i64,
|
|
}
|
|
impl PrefetchReceipt {
|
|
fn validate(&self, package: &PackageArchive, grant_not_before_ms: i64) -> Result<()> {
|
|
ensure!(
|
|
self.schema_version == 1
|
|
&& self.sha256 == package.sha256
|
|
&& self.size == package.size
|
|
&& self.sealed_at_ms > 0
|
|
&& self.sealed_at_ms <= grant_not_before_ms,
|
|
"APT_PREFETCH_BEFORE_GRANT_REQUIRED"
|
|
);
|
|
Ok(())
|
|
}
|
|
}
|
|
fn verify_prefetched(m: &AptExecutionManifest, permit: &ExecutionPermitPayload) -> Result<()> {
|
|
for p in &m.resolved_apt_transaction.packages {
|
|
let bytes = read_sealed(Path::new(&p.archive_path), p.size)?;
|
|
let meta = fs::symlink_metadata(&p.archive_path)?;
|
|
ensure!(
|
|
bytes.len() as u64 == p.size && hash(&bytes) == p.sha256 && meta.nlink() == 1,
|
|
"APT_PREFETCH_HASH_SIZE_LINKS"
|
|
);
|
|
let receipt: PrefetchReceipt = serde_json::from_slice(&read_sealed(
|
|
&Path::new(BASE).join(format!("prefetch-{}.json", p.sha256)),
|
|
4096,
|
|
)?)?;
|
|
receipt.validate(p, permit.not_before.timestamp_millis())?;
|
|
}
|
|
let baseline = read_sealed(
|
|
&Path::new(BASE).join("baselines").join(format!(
|
|
"{}.json",
|
|
m.resolved_apt_transaction.baseline_sha256
|
|
)),
|
|
1024 * 1024,
|
|
)?;
|
|
ensure!(
|
|
hash(&baseline) == m.resolved_apt_transaction.baseline_sha256,
|
|
"APT_BASELINE_HASH"
|
|
);
|
|
Ok(())
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
struct BootstrapAttempt {
|
|
transaction_sha256: String,
|
|
job_payload_sha256: String,
|
|
grant_id: uuid::Uuid,
|
|
attempt_id: uuid::Uuid,
|
|
}
|
|
|
|
struct RetryEvidence {
|
|
marker: Vec<u8>,
|
|
context: Vec<u8>,
|
|
signed_action: Vec<u8>,
|
|
expectation: Vec<u8>,
|
|
baseline: Vec<u8>,
|
|
launch: Vec<u8>,
|
|
sandbox_result: Vec<u8>,
|
|
}
|
|
|
|
struct RetryLedgerRecord {
|
|
agent: String,
|
|
generation: u64,
|
|
job: String,
|
|
attempt: String,
|
|
result: Option<Vec<u8>>,
|
|
start: Vec<u8>,
|
|
outcome: Option<Vec<u8>>,
|
|
}
|
|
|
|
fn absent_nofollow(path: &Path) -> Result<bool> {
|
|
match fs::symlink_metadata(path) {
|
|
Ok(_) => Ok(false),
|
|
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(true),
|
|
Err(error) => Err(error.into()),
|
|
}
|
|
}
|
|
|
|
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(());
|
|
};
|
|
let recipe = &self.manifest.resolved_apt_transaction.recipe_id;
|
|
self.manifest.resolved_apt_transaction.validate_fixture()?;
|
|
let base = Path::new(BASE);
|
|
for name in [
|
|
format!("bootstrap-retry-{recipe}.json"),
|
|
format!("acceptance-{recipe}.json"),
|
|
format!("pending-acceptance-{recipe}.json"),
|
|
] {
|
|
ensure!(absent_nofollow(&base.join(name))?, "APT_RETRY_ALREADY_USED");
|
|
}
|
|
let active = base.join("active");
|
|
let history = base
|
|
.join("history")
|
|
.join(retry.previous_grant_id.to_string());
|
|
let active_is_prior = if absent_nofollow(&active)? {
|
|
false
|
|
} else {
|
|
secure(&active, 0, true, true)?;
|
|
let context: serde_json::Value =
|
|
serde_json::from_slice(&read_sealed(&active.join("context.json"), 8192)?)?;
|
|
context.get("grant_id") == Some(&serde_json::json!(retry.previous_grant_id))
|
|
};
|
|
ensure!(
|
|
!(active_is_prior && !absent_nofollow(&history)?),
|
|
"APT_RETRY_AMBIGUOUS_HISTORY"
|
|
);
|
|
let prior = if active_is_prior { active } else { history };
|
|
secure(&prior, 0, true, true)?;
|
|
ensure!(
|
|
absent_nofollow(&prior.join("hook-armed.json"))?,
|
|
"APT_RETRY_PRIOR_HOOK_ARMED"
|
|
);
|
|
let evidence = RetryEvidence {
|
|
marker: read_sealed(&base.join(format!("bootstrap-attempt-{recipe}.json")), 8192)?,
|
|
context: read_sealed(&prior.join("context.json"), 8192)?,
|
|
signed_action: read_sealed(&prior.join("signed-action.json"), 65536)?,
|
|
expectation: read_sealed(&prior.join("expectation.json"), 65536)?,
|
|
baseline: read_sealed(&prior.join("baseline.json"), 1024 * 1024)?,
|
|
launch: read_sealed(&prior.join("launch.json"), 8192)?,
|
|
sandbox_result: read_sealed(&prior.join("sandbox-result.json"), 8192)?,
|
|
};
|
|
self.verify_retry_evidence(db, &evidence)
|
|
}
|
|
|
|
fn recovery_partial(
|
|
&self,
|
|
db: &rusqlite::Connection,
|
|
) -> Result<crate::apt_reconcile::ClosedPartial> {
|
|
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,
|
|
evidence: &RetryEvidence,
|
|
) -> Result<()> {
|
|
let retry = self
|
|
.manifest
|
|
.native_retry
|
|
.as_ref()
|
|
.context("APT_RETRY_REQUIRED")?;
|
|
ensure!(
|
|
self.manifest.schema_version == 3
|
|
&& self.manifest.action == "apt-native-acceptance"
|
|
&& self.manifest.execution_profile == "dev-test"
|
|
&& retry.validate()
|
|
&& retry.previous_grant_id != self.permit.grant_id
|
|
&& retry.previous_attempt_id != self.job.attempt_id
|
|
&& hash(&evidence.marker) == retry.bootstrap_marker_sha256,
|
|
"APT_RETRY_BINDING"
|
|
);
|
|
let marker: BootstrapAttempt = serde_json::from_slice(&evidence.marker)?;
|
|
ensure!(
|
|
marker.grant_id == retry.previous_grant_id
|
|
&& marker.attempt_id == retry.previous_attempt_id
|
|
&& marker.job_payload_sha256 == hash(&evidence.signed_action)
|
|
&& marker.transaction_sha256 == hash(&evidence.expectation)
|
|
&& marker.transaction_sha256 == self.manifest.transaction_sha256
|
|
&& evidence.expectation == self.manifest.transaction_bytes,
|
|
"APT_RETRY_ORIGINAL_MARKER"
|
|
);
|
|
let prior: RetryLedgerRecord = db.query_row(
|
|
"SELECT c.agent,c.generation,c.job,c.attempt,c.result,e.start,e.outcome FROM consumed c JOIN execution_evidence e ON e.grant_id=c.grant_id WHERE c.grant_id=?1",
|
|
[retry.previous_grant_id.to_string()],
|
|
|row| Ok(RetryLedgerRecord {agent: row.get(0)?, generation: row.get(1)?,
|
|
job: row.get(2)?, attempt: row.get(3)?, result: row.get(4)?,
|
|
start: row.get(5)?, outcome: row.get(6)?}),
|
|
)?;
|
|
let result_bytes = prior.result.context("APT_RETRY_PREVIOUS_UNRESOLVED")?;
|
|
let result: Outcome = serde_json::from_slice(&result_bytes)?;
|
|
let recorded_outcome: serde_json::Value =
|
|
serde_json::from_slice(&prior.outcome.context("APT_RETRY_OUTCOME_REQUIRED")?)?;
|
|
ensure!(
|
|
prior.agent == self.job.agent_id.to_string()
|
|
&& prior.generation == self.job.enrollment_generation
|
|
&& prior.attempt == retry.previous_attempt_id.to_string()
|
|
&& prior.job != self.job.job_id.to_string()
|
|
&& result.state == "failed"
|
|
&& result.error_code == "HOOK_NOT_HANDED_OFF"
|
|
&& !result.reboot_required
|
|
&& result.evidence.get("test_acceptance") == Some(&serde_json::json!(true))
|
|
&& result.evidence.get("noProductionEvidence") == Some(&serde_json::json!(true))
|
|
&& recorded_outcome == serde_json::from_slice::<serde_json::Value>(&result_bytes)?,
|
|
"APT_RETRY_PREVIOUS_NOT_KNOWN_FAILED"
|
|
);
|
|
let start: serde_json::Value = serde_json::from_slice(&prior.start)?;
|
|
let request: Request = serde_json::from_value(
|
|
start
|
|
.get("request")
|
|
.context("APT_RETRY_START_REQUEST")?
|
|
.clone(),
|
|
)?;
|
|
let prior_permit: ExecutionPermitPayload = serde_json::from_slice(&request.permit_bytes)?;
|
|
// Historical verification validates the original signature/bindings at
|
|
// its original not-before time; it grants no present execution right.
|
|
let (prior_job, prior_permit) = self.binding.verify(&request, prior_permit.not_before)?;
|
|
ensure!(
|
|
prior_permit.grant_id == retry.previous_grant_id
|
|
&& prior_permit.start_before <= self.permit.not_before
|
|
&& prior_permit.authorization_id != self.permit.authorization_id
|
|
&& prior_permit.plan_hash != self.permit.plan_hash
|
|
&& prior_job.job_id.to_string() == prior.job
|
|
&& prior_job.attempt_id == retry.previous_attempt_id
|
|
&& prior_job.execution_identity == "root"
|
|
&& request.job_bytes == evidence.signed_action,
|
|
"APT_RETRY_PRIOR_SIGNED_REQUEST"
|
|
);
|
|
let rmm_domain::jobs::Action::AptNativeAcceptance {
|
|
recipe_id,
|
|
recipe_version,
|
|
apt_manifest,
|
|
} = &prior_job.action
|
|
else {
|
|
bail!("APT_RETRY_PRIOR_NATIVE_ACTION_REQUIRED");
|
|
};
|
|
ensure!(
|
|
apt_manifest.schema_version == 2
|
|
&& apt_manifest.native_retry.is_none()
|
|
&& recipe_id == &self.manifest.resolved_apt_transaction.recipe_id
|
|
&& recipe_version == &self.manifest.resolved_apt_transaction.recipe_version
|
|
&& apt_manifest.transaction_bytes == evidence.expectation
|
|
&& apt_manifest.transaction_sha256 == marker.transaction_sha256
|
|
&& hash(&evidence.baseline)
|
|
== self.manifest.resolved_apt_transaction.baseline_sha256,
|
|
"APT_RETRY_PRIOR_RECIPE_OR_BASELINE"
|
|
);
|
|
let context: serde_json::Value = serde_json::from_slice(&evidence.context)?;
|
|
for (name, expected) in [
|
|
("schema_version", serde_json::json!(2)),
|
|
(
|
|
"transaction_sha256",
|
|
serde_json::json!(marker.transaction_sha256),
|
|
),
|
|
(
|
|
"job_payload_sha256",
|
|
serde_json::json!(marker.job_payload_sha256),
|
|
),
|
|
("grant_id", serde_json::json!(prior_permit.grant_id)),
|
|
("job_id", serde_json::json!(prior_job.job_id)),
|
|
("attempt_id", serde_json::json!(prior_job.attempt_id)),
|
|
(
|
|
"authorization_id",
|
|
serde_json::json!(prior_permit.authorization_id),
|
|
),
|
|
("plan_sha256", serde_json::json!(prior_permit.plan_hash)),
|
|
("action", serde_json::json!("apt-native-acceptance")),
|
|
("execution_profile", serde_json::json!("dev-test")),
|
|
(
|
|
"not_before_ms",
|
|
serde_json::json!(prior_permit.not_before.timestamp_millis()),
|
|
),
|
|
(
|
|
"start_before_ms",
|
|
serde_json::json!(prior_permit.start_before.timestamp_millis()),
|
|
),
|
|
] {
|
|
ensure!(
|
|
context.get(name) == Some(&expected),
|
|
"APT_RETRY_PRIOR_CONTEXT"
|
|
);
|
|
}
|
|
let ledger_id = context
|
|
.get("effect_armed_ledger_id")
|
|
.context("APT_RETRY_PRIOR_LEDGER")?;
|
|
ensure!(
|
|
result.evidence.get("effect_armed_ledger_id") == Some(ledger_id),
|
|
"APT_RETRY_PRIOR_LEDGER"
|
|
);
|
|
ensure!(
|
|
serde_json::from_slice::<serde_json::Value>(&evidence.launch)?
|
|
== serde_json::json!({"transaction_sha256":marker.transaction_sha256,
|
|
"effect_armed_ledger_id":ledger_id})
|
|
&& serde_json::from_slice::<serde_json::Value>(&evidence.sandbox_result)?
|
|
== serde_json::json!({"transaction_sha256":marker.transaction_sha256,
|
|
"apt_exit_code":100,"reboot_required":false}),
|
|
"APT_RETRY_PRIOR_NO_EFFECT_PROOF"
|
|
);
|
|
Ok(())
|
|
}
|
|
|
|
fn verify_parent_consumption(&self, db: &rusqlite::Connection) -> Result<String> {
|
|
let row: (i64, String, u64, String, String, Option<Vec<u8>>) = db.query_row(
|
|
"SELECT rowid,agent,generation,job,attempt,result FROM consumed WHERE grant_id=?1",
|
|
[self.permit.grant_id.to_string()],
|
|
|r| {
|
|
Ok((
|
|
r.get(0)?,
|
|
r.get(1)?,
|
|
r.get(2)?,
|
|
r.get(3)?,
|
|
r.get(4)?,
|
|
r.get(5)?,
|
|
))
|
|
},
|
|
)?;
|
|
ensure!(
|
|
row.1 == self.job.agent_id.to_string()
|
|
&& row.2 == self.job.enrollment_generation
|
|
&& row.3 == self.job.job_id.to_string()
|
|
&& row.4 == self.job.attempt_id.to_string()
|
|
&& row.5.is_none(),
|
|
"APT_PARENT_CONSUMPTION_REQUIRED"
|
|
);
|
|
let start: Vec<u8> = db.query_row(
|
|
"SELECT start FROM execution_evidence WHERE grant_id=?1",
|
|
[self.permit.grant_id.to_string()],
|
|
|r| r.get(0),
|
|
)?;
|
|
let start: serde_json::Value = serde_json::from_slice(&start)?;
|
|
let saved: Request =
|
|
serde_json::from_value(start.get("request").context("APT_START_REQUEST")?.clone())?;
|
|
ensure!(
|
|
saved.job_bytes == self.request.job_bytes
|
|
&& saved.permit_bytes == self.request.permit_bytes
|
|
&& saved.signature == self.request.signature
|
|
&& saved.plan_hash == self.request.plan_hash
|
|
&& saved.authorization_id == self.request.authorization_id,
|
|
"APT_PARENT_START_BINDING"
|
|
);
|
|
Ok(format!("apt-{}-{}", self.permit.grant_id, row.0))
|
|
}
|
|
/// Requires the same request already consumed and save_start persisted in
|
|
/// the parent's own ledger. Unknown outcomes never fill consumed.result.
|
|
pub fn execute(self, db: &rusqlite::Connection) -> Result<Outcome> {
|
|
ensure_root()?;
|
|
let ledger_id = self.verify_parent_consumption(db)?;
|
|
self.verify_retry_history(db)?;
|
|
let active = self.stage(db, &ledger_id)?;
|
|
// No timeout killing the native package manager. Client timeout means
|
|
// unknown; this helper continues and journals the eventual real outcome.
|
|
let mut child = Command::new("/usr/bin/python3")
|
|
.args([
|
|
"-I",
|
|
CODE,
|
|
if self.manifest.action == "apt-native-acceptance" {
|
|
"native-acceptance"
|
|
} else {
|
|
"execute"
|
|
},
|
|
])
|
|
.env_clear()
|
|
.env("PATH", "/usr/sbin:/usr/bin:/sbin:/bin")
|
|
.env("LC_ALL", "C")
|
|
.stdin(Stdio::piped())
|
|
.stdout(Stdio::piped())
|
|
.stderr(Stdio::null())
|
|
.spawn()?;
|
|
let input = serde_json::json!({"transaction_sha256":self.manifest.transaction_sha256,"effect_armed_ledger_id":ledger_id});
|
|
let write_ok = child
|
|
.stdin
|
|
.take()
|
|
.context("APT_STDIN")?
|
|
.write_all(&serde_json::to_vec(&input)?)
|
|
.is_ok();
|
|
let mut bytes = vec![];
|
|
let mut output = child.stdout.take().context("APT_STDOUT")?;
|
|
let mut chunk = [0; 4096];
|
|
let mut overflow = false;
|
|
loop {
|
|
let count = output.read(&mut chunk)?;
|
|
if count == 0 {
|
|
break;
|
|
}
|
|
if bytes.len() + count <= 65536 {
|
|
bytes.extend_from_slice(&chunk[..count]);
|
|
} else {
|
|
overflow = true;
|
|
}
|
|
}
|
|
let status = child.wait()?;
|
|
if !write_ok || overflow {
|
|
return Ok(Outcome::unknown("APT_DRIVER_OUTPUT_OR_IPC_UNKNOWN"));
|
|
}
|
|
Ok(map_driver_result(
|
|
&bytes,
|
|
status.code(),
|
|
active.join("hook-armed.json").try_exists()?,
|
|
&self.manifest,
|
|
&ledger_id,
|
|
)
|
|
.unwrap_or_else(|_| Outcome::unknown("APT_DRIVER_RESULT_UNKNOWN")))
|
|
}
|
|
fn stage(&self, db: &rusqlite::Connection, ledger_id: &str) -> Result<PathBuf> {
|
|
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")?;
|
|
ensure!(
|
|
remaining > 0 && Utc::now() >= self.permit.not_before,
|
|
"APT_START_DEADLINE"
|
|
);
|
|
let active = Path::new(BASE).join("active");
|
|
if active.try_exists()? {
|
|
secure(&active, 0, true, true)?;
|
|
let prior: serde_json::Value =
|
|
serde_json::from_slice(&read_sealed(&active.join("context.json"), 8192)?)?;
|
|
let grant = prior
|
|
.get("grant_id")
|
|
.and_then(|v| v.as_str())
|
|
.context("APT_PRIOR_GRANT")?;
|
|
let grant: uuid::Uuid = grant.parse()?;
|
|
let result: Option<Vec<u8>> = db.query_row(
|
|
"SELECT result FROM consumed WHERE grant_id=?1",
|
|
[grant.to_string()],
|
|
|r| r.get(0),
|
|
)?;
|
|
let result: Outcome =
|
|
serde_json::from_slice(&result.context("APT_PREVIOUS_EFFECT_UNRESOLVED")?)?;
|
|
ensure!(
|
|
matches!(result.state.as_str(), "succeeded" | "failed"),
|
|
"APT_PREVIOUS_EFFECT_UNRESOLVED"
|
|
);
|
|
let history = Path::new(BASE).join("history");
|
|
secure(&history, 0, true, true)?;
|
|
let destination = history.join(grant.to_string());
|
|
ensure!(!destination.try_exists()?, "APT_HISTORY_EXISTS");
|
|
fs::rename(&active, destination)?;
|
|
File::open(history)?.sync_all()?;
|
|
File::open(BASE)?.sync_all()?;
|
|
}
|
|
create_dir(&active, 0o700)?;
|
|
for dir in ["empty", "lists", "cache"] {
|
|
create_dir(&active.join(dir), 0o700)?;
|
|
}
|
|
write_once(
|
|
&active.join("expectation.json"),
|
|
&self.manifest.transaction_bytes,
|
|
0o600,
|
|
)?;
|
|
write_once(
|
|
&active.join("signed-action.json"),
|
|
&self.request.job_bytes,
|
|
0o600,
|
|
)?;
|
|
let baseline = read_sealed(
|
|
&Path::new(BASE).join("baselines").join(format!(
|
|
"{}.json",
|
|
self.manifest.resolved_apt_transaction.baseline_sha256
|
|
)),
|
|
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()
|
|
.env("PATH", "/usr/bin:/bin")
|
|
.output()?;
|
|
ensure!(
|
|
config.status.success()
|
|
&& config.stdout.len() <= 16384
|
|
&& hash(&config.stdout) == self.manifest.apt_config_sha256,
|
|
"APT_CONFIG_BINDING"
|
|
);
|
|
write_once(&active.join("apt.conf"), &config.stdout, 0o600)?;
|
|
let mut time = std::mem::MaybeUninit::<libc::timespec>::zeroed();
|
|
// SAFETY: live correctly aligned output; read-only CLOCK_MONOTONIC query.
|
|
ensure!(
|
|
unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, time.as_mut_ptr()) } == 0,
|
|
"APT_MONOTONIC_CLOCK"
|
|
);
|
|
// SAFETY: clock_gettime initialized the timespec on success.
|
|
let time = unsafe { time.assume_init() };
|
|
// Recompute remaining time immediately at translation: staging/fsync
|
|
// cannot extend the signed UTC deadline into a fresh monotonic window.
|
|
let remaining = (self.permit.start_before - Utc::now())
|
|
.num_nanoseconds()
|
|
.context("APT_DEADLINE_RANGE")?;
|
|
ensure!(remaining > 0, "APT_START_DEADLINE");
|
|
let monotonic = i128::from(time.tv_sec) * 1_000_000_000
|
|
+ i128::from(time.tv_nsec)
|
|
+ i128::from(remaining);
|
|
json_once(
|
|
&active.join("context.json"),
|
|
&serde_json::json!({
|
|
"schema_version":2,"transaction_sha256":self.manifest.transaction_sha256,
|
|
"job_payload_sha256":hash(&self.request.job_bytes),"action":self.manifest.action,
|
|
"execution_profile":self.manifest.execution_profile,"effect_armed_ledger_id":ledger_id,
|
|
"grant_id":self.permit.grant_id,"job_id":self.job.job_id,"attempt_id":self.job.attempt_id,
|
|
"authorization_id":self.permit.authorization_id,"plan_sha256":self.permit.plan_hash,
|
|
"not_before_ms":self.permit.not_before.timestamp_millis(),"start_before_ms":self.permit.start_before.timestamp_millis(),
|
|
"boot_id":rmm_agent_linux::boot_id()?,"monotonic_start_before_ns":u64::try_from(monotonic)?
|
|
}),
|
|
)?;
|
|
Ok(active)
|
|
}
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
struct DriverResult {
|
|
effect_state: String,
|
|
code: String,
|
|
evidence: serde_json::Value,
|
|
}
|
|
fn map_driver_result(
|
|
bytes: &[u8],
|
|
exit: Option<i32>,
|
|
armed: bool,
|
|
m: &AptExecutionManifest,
|
|
ledger: &str,
|
|
) -> Result<Outcome> {
|
|
let result: DriverResult = serde_json::from_slice(bytes)?;
|
|
ensure!(
|
|
exit == Some(0) && !result.code.is_empty() && result.code.len() <= 128,
|
|
"APT_EXIT_NOT_RESULT"
|
|
);
|
|
let bootstrap = m.action == "apt-native-acceptance";
|
|
if bootstrap {
|
|
ensure!(
|
|
result.evidence.get("test_acceptance") == Some(&serde_json::json!(true))
|
|
&& result.evidence.get("noProductionEvidence") == Some(&serde_json::json!(true)),
|
|
"APT_TEST_AUDIT_FLAGS"
|
|
);
|
|
}
|
|
let state = match result.effect_state.as_str() {
|
|
"verified_no_change" => {
|
|
let p = &m.resolved_apt_transaction.packages[0];
|
|
ensure!(
|
|
!bootstrap
|
|
&& !armed
|
|
&& result.code == "POSTCONDITION_ALREADY_MET"
|
|
&& result.evidence.get("changed") == Some(&serde_json::json!(false))
|
|
&& result.evidence.get("already_desired") == Some(&serde_json::json!(true))
|
|
&& result.evidence.get("postcondition_already_met")
|
|
== Some(&serde_json::json!(true))
|
|
&& result.evidence.get("transaction_executed")
|
|
== Some(&serde_json::json!(false))
|
|
&& result.evidence.get("effect_armed_ledger_id")
|
|
== Some(&serde_json::json!(ledger))
|
|
&& result.evidence.get("packages")
|
|
== Some(
|
|
&serde_json::json!([{"name":p.name,"architecture":p.architecture,"version":p.new_version}])
|
|
)
|
|
&& result.evidence.get("snapshot_sha256")
|
|
== Some(&serde_json::json!(
|
|
m.resolved_apt_transaction.baseline_sha256
|
|
))
|
|
&& result.evidence.get("fixture_payload_sha256")
|
|
== Some(&serde_json::json!(hash(
|
|
format!("{}\n", p.new_version).as_bytes()
|
|
)))
|
|
&& result
|
|
.evidence
|
|
.get("reboot_required")
|
|
.and_then(|v| v.as_bool())
|
|
.is_some(),
|
|
"APT_NO_CHANGE_POSTCONDITIONS"
|
|
);
|
|
"succeeded"
|
|
}
|
|
"verified" => {
|
|
let p = &m.resolved_apt_transaction.packages[0];
|
|
ensure!(
|
|
armed
|
|
&& result.code == "POSTCONDITIONS_VERIFIED"
|
|
&& result.evidence.get("effect_armed_ledger_id")
|
|
== Some(&serde_json::json!(ledger))
|
|
&& result.evidence.get("packages")
|
|
== Some(
|
|
&serde_json::json!([{"name":p.name,"architecture":p.architecture,"version":p.new_version}])
|
|
)
|
|
&& result
|
|
.evidence
|
|
.get("reboot_required")
|
|
.and_then(|v| v.as_bool())
|
|
.is_some(),
|
|
"APT_POSTCONDITIONS"
|
|
);
|
|
sha(result
|
|
.evidence
|
|
.get("snapshot_sha256")
|
|
.and_then(|v| v.as_str())
|
|
.context("APT_SNAPSHOT")?)?;
|
|
ensure!(
|
|
result.evidence.get("fixture_payload_sha256")
|
|
== Some(&serde_json::json!(hash(
|
|
format!("{}\n", p.new_version).as_bytes()
|
|
))),
|
|
"APT_FIXTURE_PAYLOAD_EVIDENCE"
|
|
);
|
|
if bootstrap {
|
|
let before = result
|
|
.evidence
|
|
.get("host_reboot_required_before")
|
|
.and_then(Value::as_bool);
|
|
let after = result
|
|
.evidence
|
|
.get("host_reboot_required_after")
|
|
.and_then(Value::as_bool);
|
|
ensure!(
|
|
before.is_some()
|
|
&& before == after
|
|
&& after
|
|
== result
|
|
.evidence
|
|
.get("reboot_required")
|
|
.and_then(Value::as_bool)
|
|
&& result.evidence.get("reboot_required_introduced")
|
|
== Some(&serde_json::json!(false))
|
|
&& result
|
|
.evidence
|
|
.get("host_reboot_before_sha256")
|
|
.and_then(Value::as_str)
|
|
.is_some_and(|s| sha(s).is_ok()),
|
|
"APT_NATIVE_HOST_REBOOT_BASELINE_REQUIRED"
|
|
);
|
|
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)),
|
|
"APT_TEST_RESULT_BINDING"
|
|
);
|
|
}
|
|
"succeeded"
|
|
}
|
|
"known_failed" if !armed => "failed",
|
|
"known_failed" | "unknown" => "unknown",
|
|
_ => bail!("APT_UNKNOWN_EFFECT_STATE"),
|
|
};
|
|
Ok(Outcome {
|
|
state: state.into(),
|
|
stdout: vec![],
|
|
stderr: vec![],
|
|
exit_code: exit,
|
|
output_truncated: false,
|
|
reboot_required: result
|
|
.evidence
|
|
.get("reboot_required")
|
|
.and_then(|v| v.as_bool())
|
|
.unwrap_or(false),
|
|
evidence: serde_json::json!({"postconditions_passed":state=="succeeded","apt":result.evidence,"effect_armed_ledger_id":ledger,
|
|
"test_acceptance":bootstrap,"noProductionEvidence":true}),
|
|
error_code: if state == "succeeded" {
|
|
String::new()
|
|
} else {
|
|
result.code
|
|
},
|
|
})
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests;
|