Files
rust-discovery/crates/domain/src/apt_transaction.rs
T
2026-11-13 18:07:46 +01:00

533 lines
21 KiB
Rust

//! Contract for the isolated APT provider. V2 is intentionally a separate job
//! codec: legacy v1 helper parsers MUST reject it until explicitly implemented.
use crate::jobs::{Action, ArtifactReference, JobPayload, hash};
use serde::{Deserialize, Serialize};
pub const INSTALL_RECIPE: &str = "rmm-apt-fixture-install-1.0";
pub const UPDATE_RECIPE: &str = "rmm-apt-fixture-update-1.1";
pub const INSTALL_SHA: &str = "74036ae81223deab3aae994fd2a2a695af408741777e1ce17dcb4e32f1235867";
pub const UPDATE_SHA: &str = "ef67c9fe0ba1443fcfe465768e1204763063c369a2a1da04af6027d8a9c00491";
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ResolvedAptTransaction {
pub schema_version: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub operation: Option<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>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
#[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,
}
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)]
#[serde(deny_unknown_fields)]
pub struct AptNativeRetry {
pub schema_version: u32,
pub previous_grant_id: uuid::Uuid,
pub previous_attempt_id: uuid::Uuid,
pub bootstrap_marker_sha256: String,
}
impl AptNativeRetry {
pub fn validate(&self) -> bool {
self.schema_version == 1
&& !self.previous_grant_id.is_nil()
&& !self.previous_attempt_id.is_nil()
&& digest(&self.bootstrap_marker_sha256)
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
#[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<AptNativeRetry>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub native_recovery: Option<AptNativeRecovery>,
}
impl ResolvedAptTransaction {
pub fn validate_fixture(&self) -> bool {
if 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
|| !digest(&self.status_fingerprint)
|| !digest(&self.baseline_sha256)
{
return false;
}
let package = &self.packages[0];
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"
&& package.architecture == "all"
&& package.old_version.as_deref() == old
&& package.new_version == new
&& package.origin == "rmm-test"
&& package.sha256 == sha
&& package.size == 20672
&& package.archive_path
== format!(
"/var/lib/rmm-apt-transaction/archives/{}.deb",
package.sha256
)
}
}
impl AptExecutionManifest {
pub fn validate(&self) -> bool {
self.kind == "rmm.apt.helper-action"
&& 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!(
self.action.as_str(),
"apt-native-acceptance" | "apt-execute"
)
&& self.execution_profile == "dev-test"
&& self.transaction_bytes.len() <= 1024 * 1024
&& !self.transaction_bytes.is_empty()
&& hash(&self.transaction_bytes) == self.transaction_sha256
&& [
&self.transaction_sha256,
&self.provider_sha256,
&self.hook_sha256,
&self.apt_config_sha256,
&self.runtime_sha256,
]
.iter()
.all(|s| digest(s))
&& !self.test_result_id.is_empty()
&& self.test_result_id.len() <= 128
&& self
.test_result_id
.bytes()
.all(|c| c.is_ascii_alphanumeric() || b"_.-".contains(&c))
&& self.resolved_apt_transaction.validate_fixture()
&& serde_json::from_slice::<ResolvedAptTransaction>(&self.transaction_bytes)
.is_ok_and(|parsed| parsed == self.resolved_apt_transaction)
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AptArchiveReference {
pub package: String,
pub architecture: String,
pub version: String,
pub artifact: ArtifactReference,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PinnedAptTransaction {
pub schema_version: u32,
pub expectation_bytes: Vec<u8>,
pub expectation_sha256: String,
pub baseline: ArtifactReference,
pub archives: Vec<AptArchiveReference>,
pub provider_code_sha256: String,
pub hook_code_sha256: String,
pub apt_config_sha256: String,
pub native_acceptance_evidence_id: String,
}
fn digest(s: &str) -> bool {
s.len() == 64
&& s.bytes()
.all(|c| c.is_ascii_digit() || b"abcdef".contains(&c))
}
fn label(s: &str) -> bool {
!s.is_empty()
&& s.len() <= 255
&& !s.starts_with('-')
&& s.bytes()
.all(|c| c.is_ascii_alphanumeric() || b"_.:+~-".contains(&c))
}
impl PinnedAptTransaction {
pub fn validate(&self) -> Result<AptExpectation, &'static str> {
if self.schema_version != 1
|| self.expectation_bytes.is_empty()
|| self.expectation_bytes.len() > 1024 * 1024
|| hash(&self.expectation_bytes) != self.expectation_sha256
|| ![
&self.expectation_sha256,
&self.baseline.sha256,
&self.provider_code_sha256,
&self.hook_code_sha256,
&self.apt_config_sha256,
]
.iter()
.all(|s| digest(s))
|| self.baseline.artifact_id.is_nil()
|| self.baseline.size_bytes == 0
|| self.native_acceptance_evidence_id.is_empty()
|| self.native_acceptance_evidence_id.len() > 255
{
return Err("INVALID_APT_BINDING");
}
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)
|| !label(&expectation.recipe_version)
|| !label(&expectation.resolver_config_version)
|| !digest(&expectation.status_fingerprint)
|| expectation.baseline_sha256 != self.baseline.sha256
|| expectation.packages.is_empty()
|| expectation.packages.len() > 128
|| self.archives.len() != expectation.packages.len()
{
return Err("INVALID_APT_CLOSURE");
}
let mut keys = std::collections::BTreeSet::new();
for package in &expectation.packages {
if !label(&package.name)
|| !label(&package.new_version)
|| package
.old_version
.as_ref()
.is_some_and(|v| !label(v) || v == &package.new_version)
|| !matches!(package.architecture.as_str(), "amd64" | "all")
|| !digest(&package.sha256)
|| package.size == 0
|| package.size > 256 * 1024 * 1024
|| package.archive_path
!= format!(
"/var/lib/rmm-apt-transaction/archives/{}.deb",
package.sha256
)
|| !keys.insert((&package.name, &package.architecture))
{
return Err("INVALID_APT_PACKAGE");
}
let matching = self
.archives
.iter()
.filter(|a| {
a.package == package.name
&& a.architecture == package.architecture
&& a.version == package.new_version
&& a.artifact.sha256 == package.sha256
&& a.artifact.size_bytes == package.size
&& !a.artifact.artifact_id.is_nil()
})
.collect::<Vec<_>>();
if matching.len() != 1
|| !(package.origin == "rmm-test"
|| package.origin == format!("catalog:{}", matching[0].artifact.artifact_id))
{
return Err("APT_ARCHIVE_BINDING");
}
}
Ok(expectation)
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ResolvedAptJobPayloadV2 {
pub schema_version: u32,
pub job: JobPayload,
pub transaction: PinnedAptTransaction,
}
impl ResolvedAptJobPayloadV2 {
pub fn validate(&self) -> Result<(), &'static str> {
let e = self.transaction.validate()?;
if self.schema_version != 2
|| self.job.schema_version != 1
|| self.job.execution_identity != "root"
|| !self.job.action.validate()
{
return Err("APT_JOB_PROFILE");
}
match &self.job.action {
Action::EnsurePackage {
provider,
package,
version,
recipe_version,
..
} if provider == "apt"
&& recipe_version == &e.recipe_version
&& e.packages
.iter()
.any(|p| &p.name == package && &p.new_version == version) =>
{
Ok(())
}
Action::ApplyUpdates {
provider,
packages,
reboot_policy,
..
} if provider == "apt"
&& reboot_policy == "never"
&& packages.iter().all(|selection| {
e.packages
.iter()
.any(|p| selection == &format!("{}={}", p.name, p.new_version))
}) =>
{
Ok(())
}
_ => Err("APT_JOB_CLOSURE_MISMATCH"),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use uuid::Uuid;
#[test]
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(),
resolver_config_version: "rmm-apt-local-v1".into(),
no_reboot: true,
status_fingerprint: hash(b"status"),
baseline_sha256: hash(b"baseline"),
packages: vec![PackageArchive {
name: "rmm-mvp-test".into(),
architecture: "all".into(),
old_version: None,
new_version: "1.0".into(),
origin: "rmm-test".into(),
sha256: INSTALL_SHA.into(),
size: 20672,
archive_path: format!("/var/lib/rmm-apt-transaction/archives/{INSTALL_SHA}.deb"),
}],
};
let bytes = crate::jobs::encode(&t).unwrap();
let m = AptExecutionManifest {
kind: "rmm.apt.helper-action".into(),
schema_version: 2,
action: "apt-native-acceptance".into(),
execution_profile: "dev-test".into(),
transaction_sha256: hash(&bytes),
resolved_apt_transaction: t,
transaction_bytes: bytes,
provider_sha256: hash(b"provider"),
hook_sha256: hash(b"hook"),
apt_config_sha256: hash(b"config"),
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()
.as_object()
.unwrap()
.contains_key("native_retry")
);
let mut retry = m.clone();
retry.schema_version = 3;
assert!(!retry.validate());
retry.native_retry = Some(AptNativeRetry {
schema_version: 1,
previous_grant_id: Uuid::new_v4(),
previous_attempt_id: Uuid::new_v4(),
bootstrap_marker_sha256: hash(b"immutable original marker"),
});
assert!(retry.validate());
let encoded_retry = crate::jobs::encode(&retry).unwrap();
let parsed_retry: AptExecutionManifest = serde_json::from_slice(&encoded_retry).unwrap();
assert_eq!(crate::jobs::encode(&parsed_retry).unwrap(), encoded_retry);
retry.schema_version = 2;
assert!(!retry.validate());
retry.schema_version = 3;
retry.action = "apt-execute".into();
assert!(!retry.validate());
retry.action = "apt-native-acceptance".into();
retry.native_retry.as_mut().unwrap().previous_attempt_id = Uuid::nil();
assert!(!retry.validate());
let a = Action::AptNativeAcceptance {
recipe_id: INSTALL_RECIPE.into(),
recipe_version: "1".into(),
apt_manifest: m.clone(),
};
assert!(a.validate());
assert_eq!(a.name(), "apt_native_acceptance");
let encoded = crate::jobs::encode(&a).unwrap();
let decoded: Action = serde_json::from_slice(&encoded).unwrap();
assert_eq!(crate::jobs::encode(&decoded).unwrap(), encoded);
let mut bad = m.clone();
bad.resolved_apt_transaction.packages[0].new_version = "1.1".into();
assert!(!bad.validate());
let raw = String::from_utf8(crate::jobs::encode(&m).unwrap()).unwrap();
let duplicate = raw.replacen('{', "{\"schema_version\":2,", 1);
assert!(serde_json::from_str::<AptExecutionManifest>(&duplicate).is_err());
let legacy=br#"{"action":"ensure_package","provider":"apt","package":"fixture","version":"1","architecture":"amd64","recipe_version":"1","installation_context":"system"}"#;
let legacy_action: Action = serde_json::from_slice(legacy).unwrap();
assert_eq!(crate::jobs::encode(&legacy_action).unwrap(), legacy);
assert!(!legacy_action.validate());
assert!(legacy_action.validate_plan_shape());
}
#[test]
fn closure_bytes_archives_and_code_are_bound() {
let sha = hash(b"archive");
let baseline = hash(b"baseline");
let archive = ArtifactReference {
artifact_id: Uuid::new_v4(),
sha256: sha.clone(),
size_bytes: 7,
};
let expectation = AptExpectation {
schema_version: 1,
operation: None,
recipe_id: "fixture".into(),
recipe_version: "1".into(),
platform: "ubuntu-24.04-amd64".into(),
resolver_config_version: "rmm-apt-local-v1".into(),
no_reboot: true,
status_fingerprint: hash(b"status"),
baseline_sha256: baseline.clone(),
packages: vec![AptExpectedPackage {
name: "rmm-mvp-test".into(),
architecture: "all".into(),
old_version: None,
new_version: "1.0".into(),
origin: "rmm-test".into(),
sha256: sha.clone(),
size: 7,
archive_path: format!("/var/lib/rmm-apt-transaction/archives/{sha}.deb"),
}],
};
let bytes = crate::jobs::encode(&expectation).unwrap();
let mut t = PinnedAptTransaction {
schema_version: 1,
expectation_sha256: hash(&bytes),
expectation_bytes: bytes,
baseline: ArtifactReference {
artifact_id: Uuid::new_v4(),
sha256: baseline,
size_bytes: 8,
},
archives: vec![AptArchiveReference {
package: "rmm-mvp-test".into(),
architecture: "all".into(),
version: "1.0".into(),
artifact: archive,
}],
provider_code_sha256: hash(b"code"),
hook_code_sha256: hash(b"hook"),
apt_config_sha256: hash(b"config"),
native_acceptance_evidence_id: "native-record-required".into(),
};
assert!(t.validate().is_ok());
t.archives[0].artifact.sha256 = hash(b"other");
assert_eq!(t.validate().unwrap_err(), "APT_ARCHIVE_BINDING");
}
}