feat: snapshot Linux-first RMM MVP and pause handover
Rust development slice / linux (push) Failing after 1m10s
Rust development slice / linux (push) Failing after 1m10s
This commit is contained in:
@@ -0,0 +1,893 @@
|
||||
//! 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 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,
|
||||
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.schema_version == 1
|
||||
&& 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.recipe_id.as_str() {
|
||||
INSTALL_RECIPE => (None, "1.0", INSTALL_SHA),
|
||||
UPDATE_RECIPE => (Some("1.0"), "1.1", UPDATE_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,
|
||||
}
|
||||
|
||||
#[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 {
|
||||
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 {
|
||||
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"
|
||||
&& m.schema_version == 2
|
||||
&& 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(())
|
||||
}
|
||||
|
||||
impl PreparedApt {
|
||||
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)?;
|
||||
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 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)?;
|
||||
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 {
|
||||
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;
|
||||
Reference in New Issue
Block a user