feat: snapshot Linux-first RMM MVP and pause handover
Rust development slice / linux (push) Failing after 1m10s

This commit is contained in:
BuTzZ
2026-11-12 22:06:25 +01:00
commit 6c3203d725
194 changed files with 49234 additions and 0 deletions
+13
View File
@@ -0,0 +1,13 @@
[package]
name = "rmm-domain"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
serde.workspace = true
serde_json.workspace = true
sha2.workspace = true
hex.workspace = true
uuid.workspace = true
chrono.workspace = true
schemars.workspace = true
+401
View File
@@ -0,0 +1,401 @@
//! 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,
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(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,
}
impl ResolvedAptTransaction {
pub fn validate_fixture(&self) -> bool {
if 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
|| !digest(&self.status_fingerprint)
|| !digest(&self.baseline_sha256)
{
return false;
}
let package = &self.packages[0];
let (old, new, sha) = match self.recipe_id.as_str() {
INSTALL_RECIPE => (None, "1.0", INSTALL_SHA),
UPDATE_RECIPE => (Some("1.0"), "1.1", UPDATE_SHA),
_ => 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"
&& self.schema_version == 2
&& 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.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,
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(),
};
assert!(m.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,
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");
}
}
+117
View File
@@ -0,0 +1,117 @@
//! Additive bounded passive metadata; the strict original Inventory stays intact.
use chrono::{DateTime, Utc};
use serde::Deserialize;
use serde_json::Value;
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Observation {
scope: String,
source_id: String,
observed_at: DateTime<Utc>,
quality: String,
completeness: String,
truncated: bool,
error_code: Option<String>,
data: Value,
}
pub fn validate(bytes: &[u8], now: DateTime<Utc>) -> Result<Value, &'static str> {
if bytes.len() > 512 * 1024 {
return Err("INVENTORY_SIZE");
}
let value: Value = serde_json::from_slice(bytes).map_err(|_| "INVALID_INVENTORY_JSON")?;
let mut base = value.as_object().cloned().ok_or("INVENTORY_OBJECT")?;
let observations = base.remove("observations");
let started = base.remove("collection_started_at");
let completed = base.remove("collection_completed_at");
let inventory: crate::Inventory =
serde_json::from_value(Value::Object(base)).map_err(|_| "INVALID_BASE_INVENTORY")?;
if !inventory.validate() {
return Err("INVALID_BASE_INVENTORY");
}
if let Some(observations) = observations {
let started: DateTime<Utc> =
serde_json::from_value(started.ok_or("COLLECTION_WINDOW_REQUIRED")?)
.map_err(|_| "INVALID_COLLECTION_TIME")?;
let completed: DateTime<Utc> =
serde_json::from_value(completed.ok_or("COLLECTION_WINDOW_REQUIRED")?)
.map_err(|_| "INVALID_COLLECTION_TIME")?;
if started > completed
|| (completed - started).num_seconds() > 3600
|| (now - started).num_seconds() > 72 * 3600
|| (completed - now).num_seconds() > 45
{
return Err("INVALID_COLLECTION_WINDOW");
}
let observations = observations.as_array().ok_or("OBSERVATION_ARRAY")?;
if observations.len() > 32 {
return Err("OBSERVATION_COUNT");
}
let mut scopes = std::collections::BTreeSet::new();
for item in observations {
if serde_json::to_vec(item)
.map_err(|_| "INVALID_OBSERVATION")?
.len()
> 32768
{
return Err("OBSERVATION_SIZE");
}
let o: Observation =
serde_json::from_value(item.clone()).map_err(|_| "INVALID_OBSERVATION")?;
if !o.scope.starts_with("linux.")
|| o.scope.len() > 64
|| !o
.scope
.bytes()
.all(|c| c.is_ascii_lowercase() || b"._".contains(&c))
|| !scopes.insert(o.scope)
{
return Err("INVALID_OBSERVATION_SCOPE");
}
if o.source_id.is_empty()
|| o.source_id.len() > 255
|| o.source_id.contains('\0')
|| o.observed_at < started - chrono::Duration::seconds(1)
|| o.observed_at > completed + chrono::Duration::seconds(1)
|| !matches!(
o.quality.as_str(),
"valid" | "unknown" | "unsupported" | "permission_denied" | "error"
)
|| !matches!(o.completeness.as_str(), "complete" | "partial" | "unknown")
|| (o.truncated && o.completeness == "complete")
|| o.error_code.as_ref().is_some_and(|s| s.len() > 128)
|| (o.quality == "valid" && o.data.is_null())
{
return Err("INVALID_OBSERVATION_METADATA");
}
}
} else if started.is_some() || completed.is_some() {
return Err("OBSERVATIONS_REQUIRED");
}
Ok(value)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn base() -> Value {
json!({"os":"Linux","hostname":"fixture","architecture":"x86_64","root_total_bytes":2,"root_available_bytes":1,"root_available_inodes":1})
}
#[test]
fn additive_metadata_and_bounds() {
let now = Utc::now();
let mut v = base();
assert!(validate(&serde_json::to_vec(&v).unwrap(), now).is_ok());
v["observations"] = json!([{"scope":"linux.smart","source_id":"linux.smart","observed_at":now,"quality":"unsupported","completeness":"unknown","truncated":false,"error_code":"NOT_SUPPORTED","data":null}]);
v["collection_started_at"] = json!(now);
v["collection_completed_at"] = json!(now);
assert_eq!(validate(&serde_json::to_vec(&v).unwrap(), now).unwrap(), v);
v["observations"][0]["data"] = json!("x".repeat(32768));
assert_eq!(
validate(&serde_json::to_vec(&v).unwrap(), now).unwrap_err(),
"OBSERVATION_SIZE"
);
let mut unknown = base();
unknown["tenant_id"] = json!("forged");
assert!(validate(&serde_json::to_vec(&unknown).unwrap(), now).is_err());
}
}
+470
View File
@@ -0,0 +1,470 @@
//! Version 1 codec: UTF-8 compact serde JSON of these structs, declaration field
//! order, explicit null options, ordered vectors, UTC RFC3339 timestamps. Hash the
//! stored bytes, never a reconstructed API view. No floating point/map payloads.
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use uuid::Uuid;
pub fn hash(bytes: &[u8]) -> String {
hex::encode(Sha256::digest(bytes))
}
pub fn encode<T: Serialize>(value: &T) -> Result<Vec<u8>, serde_json::Error> {
serde_json::to_vec(value)
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)]
pub enum Action {
RunScript {
interpreter: String,
script_utf8: String,
arguments: Vec<String>,
expected_stdout: Option<String>,
},
RefreshInventory {
scope: String,
},
QueryLogs {
unit: String,
since: DateTime<Utc>,
until: DateTime<Utc>,
max_lines: u32,
},
SetServiceState {
unit: String,
state: String,
},
EnsurePackage {
provider: String,
package: String,
version: String,
architecture: String,
recipe_version: String,
installation_context: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
recipe_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
apt_manifest: Option<crate::apt_transaction::AptExecutionManifest>,
},
ApplyUpdates {
provider: String,
packages: Vec<String>,
reboot_policy: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
apt_manifest: Option<crate::apt_transaction::AptExecutionManifest>,
},
AptNativeAcceptance {
recipe_id: String,
recipe_version: String,
apt_manifest: crate::apt_transaction::AptExecutionManifest,
},
Reboot {
reason: String,
reconnect_timeout_seconds: u32,
dependency_group: String,
},
}
impl Action {
pub fn name(&self) -> &'static str {
match self {
Self::RunScript { .. } => "run_script",
Self::RefreshInventory { .. } => "refresh_inventory",
Self::QueryLogs { .. } => "query_logs",
Self::SetServiceState { .. } => "set_service_state",
Self::EnsurePackage { .. } => "ensure_package",
Self::ApplyUpdates { .. } => "apply_updates",
Self::AptNativeAcceptance { .. } => "apt_native_acceptance",
Self::Reboot { .. } => "reboot",
}
}
pub fn validate(&self) -> bool {
let valid_version = |s: &str| {
!s.is_empty()
&& s.len() <= 255
&& !s.starts_with('-')
&& s.bytes()
.all(|c| c.is_ascii_alphanumeric() || b".+~:-".contains(&c))
};
let unit = |s: &str| {
!s.is_empty()
&& s.len() <= 255
&& !s.starts_with('-')
&& s.bytes()
.all(|c| c.is_ascii_alphanumeric() || b"_.@:-".contains(&c))
};
match self {
Self::RunScript {
interpreter,
script_utf8,
arguments,
expected_stdout,
} => {
matches!(interpreter.as_str(), "posix_sh" | "bash")
&& !script_utf8.is_empty()
&& script_utf8.len() <= 32768
&& !script_utf8.contains('\0')
&& arguments.len() <= 32
&& arguments
.iter()
.all(|a| a.len() <= 4096 && !a.contains('\0'))
&& expected_stdout.as_ref().is_none_or(|s| s.len() <= 65536)
}
Self::RefreshInventory { scope } => scope == "linux.base",
Self::QueryLogs {
unit: u,
since,
until,
max_lines,
} => {
unit(u)
&& since < until
&& (*until - *since).num_hours() <= 24
&& *max_lines > 0
&& *max_lines <= 1000
}
Self::SetServiceState { unit: u, state } => {
unit(u) && matches!(state.as_str(), "running" | "stopped" | "restarted")
}
Self::EnsurePackage {
provider,
package,
version,
architecture,
recipe_version,
installation_context,
recipe_id,
apt_manifest,
} => {
provider == "apt"
&& unit(package)
&& valid_version(version)
&& matches!(architecture.as_str(), "amd64" | "all")
&& unit(recipe_version)
&& installation_context == "system"
&& apt_manifest.as_ref().is_some_and(|m| {
m.validate()
&& m.action == "apt-execute"
&& recipe_id.as_ref() == Some(&m.resolved_apt_transaction.recipe_id)
&& recipe_version == &m.resolved_apt_transaction.recipe_version
&& m.resolved_apt_transaction.packages.iter().any(|p| {
&p.name == package
&& &p.new_version == version
&& &p.architecture == architecture
})
})
}
Self::ApplyUpdates {
provider,
packages,
reboot_policy,
apt_manifest,
} => {
provider == "apt"
&& reboot_policy == "never"
&& !packages.is_empty()
&& packages.len() <= 100
&& apt_manifest.as_ref().is_some_and(|m| {
m.validate()
&& m.action == "apt-execute"
&& m.resolved_apt_transaction.recipe_id == "rmm-apt-fixture-update-1.1"
&& packages == &["rmm-mvp-test".to_string()]
})
}
Self::AptNativeAcceptance {
recipe_id,
recipe_version,
apt_manifest: m,
} => {
m.validate()
&& m.action == "apt-native-acceptance"
&& recipe_id == &m.resolved_apt_transaction.recipe_id
&& recipe_version == &m.resolved_apt_transaction.recipe_version
}
Self::Reboot {
reason,
reconnect_timeout_seconds,
dependency_group,
} => {
!reason.is_empty()
&& reason.len() <= 1024
&& (60..=3600).contains(reconnect_timeout_seconds)
&& unit(dependency_group)
}
}
}
pub fn resource(&self) -> &'static str {
match self {
Self::EnsurePackage { .. }
| Self::ApplyUpdates { .. }
| Self::AptNativeAcceptance { .. } => "package_manager",
_ => "device_execution",
}
}
/// Old immutable catalog previews remain readable/plannable, but are never
/// executable or submit/approval eligible without the signed schema-2 body.
pub fn validate_plan_shape(&self) -> bool {
match self {
Self::EnsurePackage {
provider,
package,
version,
architecture,
recipe_version,
installation_context,
recipe_id: None,
apt_manifest: None,
} => {
provider == "apt"
&& !package.is_empty()
&& package.len() <= 255
&& !package.starts_with('-')
&& package
.bytes()
.all(|c| c.is_ascii_alphanumeric() || b"_.:+-".contains(&c))
&& !version.is_empty()
&& version.len() <= 255
&& version
.bytes()
.all(|c| c.is_ascii_alphanumeric() || b".+~:-".contains(&c))
&& matches!(architecture.as_str(), "amd64" | "all")
&& !recipe_version.is_empty()
&& recipe_version.len() <= 255
&& installation_context == "system"
}
Self::ApplyUpdates {
provider,
packages,
reboot_policy,
apt_manifest: None,
} => {
provider == "apt"
&& reboot_policy == "never"
&& !packages.is_empty()
&& packages.len() <= 100
&& packages.iter().all(|s| {
s.split_once('=').is_some_and(|(n, v)| {
!n.is_empty()
&& !v.is_empty()
&& n.len() <= 255
&& v.len() <= 255
&& !n.starts_with('-')
&& n.bytes()
.all(|c| c.is_ascii_alphanumeric() || b"_.:+-".contains(&c))
&& v.bytes()
.all(|c| c.is_ascii_alphanumeric() || b".+~:-".contains(&c))
})
})
}
_ => self.validate(),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct JobPayload {
pub schema_version: u32,
pub tenant_id: Uuid,
pub asset_id: Uuid,
pub agent_id: Uuid,
pub enrollment_generation: u64,
pub assignment_version: u64,
pub job_id: Uuid,
pub attempt_id: Uuid,
pub action: Action,
pub execution_identity: String,
pub not_before: DateTime<Utc>,
pub start_before: DateTime<Utc>,
pub max_runtime_seconds: u32,
pub max_output_bytes: u32,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PlannedJob {
pub payload: JobPayload,
pub job_payload_hash: String,
pub script_sha256: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PlanPayload {
pub schema_version: u32,
pub plan_id: Uuid,
pub tenant_id: Uuid,
pub principal: String,
pub reason: String,
pub jobs: Vec<PlannedJob>,
pub max_parallel: u32,
pub halt_after_failures: u32,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub recipe_references: Vec<RecipeReference>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub artifact_references: Vec<JobArtifactReference>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
#[serde(deny_unknown_fields)]
pub struct ArtifactReference {
pub artifact_id: Uuid,
pub sha256: String,
pub size_bytes: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
#[serde(deny_unknown_fields)]
pub struct JobArtifactReference {
pub job_id: Uuid,
pub attempt_id: Uuid,
pub artifact: ArtifactReference,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
#[serde(deny_unknown_fields)]
pub struct RecipeReference {
pub package: String,
pub version: String,
pub architecture: String,
pub recipe_version: String,
pub sha256: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct ExecutionPermitPayload {
pub domain: String,
pub schema_version: u32,
pub grant_id: Uuid,
pub authorization_id: Uuid,
pub tenant_id: Uuid,
pub asset_id: Uuid,
pub agent_id: Uuid,
pub enrollment_generation: u64,
pub assignment_version: u64,
pub job_id: Uuid,
pub attempt_id: Uuid,
pub plan_hash: String,
pub job_payload_hash: String,
pub action: String,
pub execution_identity: String,
pub not_before: DateTime<Utc>,
pub start_before: DateTime<Utc>,
pub max_runtime_seconds: u32,
pub key_id: String,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum JobState {
Queued,
Accepted,
Running,
Verifying,
AwaitingReboot,
Succeeded,
Failed,
Cancelled,
Expired,
Unknown,
}
impl JobState {
pub fn terminal(self) -> bool {
matches!(
self,
Self::Succeeded | Self::Failed | Self::Cancelled | Self::Expired
)
}
pub fn allows(self, next: Self) -> bool {
use JobState::*;
match self {
Queued => matches!(next, Accepted | Cancelled | Expired | Failed),
Accepted => matches!(next, Running | Unknown | Cancelled | Expired | Failed),
Running => matches!(
next,
Verifying | AwaitingReboot | Failed | Cancelled | Unknown
),
Verifying => matches!(next, Succeeded | Failed | AwaitingReboot | Unknown),
AwaitingReboot => matches!(next, Verifying | Unknown | Failed),
Unknown => false,
_ => false,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn codec_golden_and_exact_script_bytes() {
let a = Action::RunScript {
interpreter: "posix_sh".into(),
script_utf8: "echo hi\n".into(),
arguments: vec![],
expected_stdout: None,
};
assert_eq!(
String::from_utf8(encode(&a).unwrap()).unwrap(),
r#"{"action":"run_script","interpreter":"posix_sh","script_utf8":"echo hi\n","arguments":[],"expected_stdout":null}"#
);
assert_ne!(hash(b"echo hi\n"), hash(b"echo hi\r\n"));
assert_eq!(
hash(b"abc"),
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
);
}
#[test]
fn no_terminal_replay_or_unknown_restart() {
assert!(!JobState::Succeeded.allows(JobState::Running));
assert!(!JobState::Unknown.allows(JobState::Running));
assert!(JobState::Accepted.allows(JobState::Unknown));
}
#[test]
fn permit_codec_golden_all_bindings() {
let id = Uuid::nil();
let epoch = DateTime::<Utc>::from_timestamp(0, 0).unwrap();
let p = ExecutionPermitPayload {
domain: "rmm.execution-permit".into(),
schema_version: 1,
grant_id: id,
authorization_id: id,
tenant_id: id,
asset_id: id,
agent_id: id,
enrollment_generation: 1,
assignment_version: 2,
job_id: id,
attempt_id: id,
plan_hash: "plan".into(),
job_payload_hash: "job".into(),
action: "run_script".into(),
execution_identity: "agent_service".into(),
not_before: epoch,
start_before: epoch,
max_runtime_seconds: 60,
key_id: "key".into(),
};
let golden = r#"{"domain":"rmm.execution-permit","schema_version":1,"grant_id":"00000000-0000-0000-0000-000000000000","authorization_id":"00000000-0000-0000-0000-000000000000","tenant_id":"00000000-0000-0000-0000-000000000000","asset_id":"00000000-0000-0000-0000-000000000000","agent_id":"00000000-0000-0000-0000-000000000000","enrollment_generation":1,"assignment_version":2,"job_id":"00000000-0000-0000-0000-000000000000","attempt_id":"00000000-0000-0000-0000-000000000000","plan_hash":"plan","job_payload_hash":"job","action":"run_script","execution_identity":"agent_service","not_before":"1970-01-01T00:00:00Z","start_before":"1970-01-01T00:00:00Z","max_runtime_seconds":60,"key_id":"key"}"#;
assert_eq!(encode(&p).unwrap(), golden.as_bytes());
assert_eq!(
serde_json::from_slice::<ExecutionPermitPayload>(golden.as_bytes()).unwrap(),
p
);
}
#[test]
fn additive_recipe_refs_preserve_legacy_plan_bytes() {
let legacy=br#"{"schema_version":1,"plan_id":"00000000-0000-0000-0000-000000000000","tenant_id":"00000000-0000-0000-0000-000000000000","principal":"fixture","reason":"legacy","jobs":[],"max_parallel":1,"halt_after_failures":1}"#;
let decoded: PlanPayload = serde_json::from_slice(legacy).unwrap();
assert!(decoded.recipe_references.is_empty());
assert_eq!(encode(&decoded).unwrap(), legacy);
}
#[test]
fn updates_require_exact_versions_and_never_implicit_reboot() {
let exact = Action::ApplyUpdates {
provider: "apt".into(),
packages: vec!["fixture=1:2.0~rc1+test".into()],
reboot_policy: "never".into(),
apt_manifest: None,
};
assert!(exact.validate_plan_shape());
assert!(!exact.validate());
let broad = Action::ApplyUpdates {
provider: "apt".into(),
packages: vec!["fixture".into()],
reboot_policy: "never".into(),
apt_manifest: None,
};
assert!(!broad.validate());
}
}
+78
View File
@@ -0,0 +1,78 @@
use serde::{Deserialize, Serialize};
pub mod apt_transaction;
pub mod inventory_document;
pub mod jobs;
pub mod reconciliation;
pub const TENANT_A: &str = "11111111-1111-4111-8111-111111111111";
pub const TENANT_B: &str = "22222222-2222-4222-8222-222222222222";
pub const MAX_MESSAGE: usize = 1024 * 1024;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ServerRole {
Api,
Gateway,
All,
}
impl ServerRole {
pub fn parse(value: &str) -> Result<Self, &'static str> {
match value {
"api" => Ok(Self::Api),
"gateway" => Ok(Self::Gateway),
"all" => Ok(Self::All),
_ => Err("unknown server role"),
}
}
pub fn api(self) -> bool {
matches!(self, Self::Api | Self::All)
}
pub fn gateway(self) -> bool {
matches!(self, Self::Gateway | Self::All)
}
}
/// No production authentication adapter is shipped in this development slice.
pub fn validate_profile(profile: &str, dev_auth: bool) -> Result<(), &'static str> {
match (profile, dev_auth) {
("development", true) => Ok(()),
_ => Err("explicit development profile and dev auth required; production disabled"),
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Inventory {
pub os: String,
pub hostname: String,
pub architecture: String,
pub root_total_bytes: u64,
pub root_available_bytes: u64,
pub root_available_inodes: u64,
}
impl Inventory {
pub fn validate(&self) -> bool {
!self.os.is_empty()
&& self.os.len() <= 4096
&& !self.hostname.is_empty()
&& self.hostname.len() <= 255
&& self.architecture.len() <= 64
&& self.root_total_bytes > 0
&& self.root_available_bytes <= self.root_total_bytes
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn production_never_accepts_development_auth() {
assert!(validate_profile("production", true).is_err());
assert!(validate_profile("production", false).is_err());
assert!(validate_profile("development", false).is_err());
assert!(validate_profile("development", true).is_ok());
assert!(ServerRole::parse("worker").is_err());
assert!(!ServerRole::Api.gateway());
assert!(!ServerRole::Gateway.api());
}
}
+166
View File
@@ -0,0 +1,166 @@
//! Signed reconciliation is NOT an execution permit. Verify the signature over
//! exact stored bytes first, then all bindings/time/checkpoint and local hashes.
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct ReconciledOutcome {
pub state: String,
pub stdout: Vec<u8>,
pub stderr: Vec<u8>,
pub exit_code: Option<i32>,
pub output_truncated: bool,
pub reboot_required: bool,
pub evidence: serde_json::Value,
pub error_code: String,
}
/// Codec 1: struct field order, explicit nulls, raw output bytes unchanged;
/// recursively lexical evidence-object keys, independent of serde feature flags.
pub fn canonical_outcome_bytes(outcome: &ReconciledOutcome) -> Result<Vec<u8>, serde_json::Error> {
fn ordered(value: serde_json::Value) -> serde_json::Value {
match value {
serde_json::Value::Object(map) => {
let mut fields = map.into_iter().collect::<Vec<_>>();
fields.sort_by(|a, b| a.0.cmp(&b.0));
let mut sorted = serde_json::Map::new();
for (key, value) in fields {
sorted.insert(key, ordered(value));
}
serde_json::Value::Object(sorted)
}
serde_json::Value::Array(values) => {
serde_json::Value::Array(values.into_iter().map(ordered).collect())
}
other => other,
}
}
let mut value = outcome.clone();
value.evidence = ordered(value.evidence);
serde_json::to_vec(&value)
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AttemptDecision {
pub job_id: Uuid,
pub attempt_id: Uuid,
pub job_payload_hash: String,
pub grant_id: Option<Uuid>,
pub authorization_id: Option<Uuid>,
pub plan_hash: Option<String>,
pub action: String,
pub execution_identity: String,
pub revision: u64,
pub outcome_state: String,
pub previous_outcome_sha256: Option<String>,
pub outcome_sha256: Option<String>,
pub outcome_bytes: Vec<u8>,
pub original_boot_id: Option<Uuid>,
pub unlock: bool,
pub reason: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ReconcileDecisionPayload {
pub domain: String,
pub schema_version: u32,
pub decision_id: Uuid,
pub request_id: Uuid,
pub request_hash: String,
pub tenant_id: Uuid,
pub asset_id: Uuid,
pub agent_id: Uuid,
pub enrollment_generation: u64,
pub assignment_version: u64,
pub connection_generation: u64,
pub boot_id: Uuid,
pub journal_id: Uuid,
pub checkpoint: u64,
pub helper_journal_id: Option<Uuid>,
pub helper_checkpoint: u64,
pub issued_at: DateTime<Utc>,
pub valid_until: DateTime<Utc>,
pub ready: bool,
pub helper_ready: bool,
pub reason: String,
pub attempts: Vec<AttemptDecision>,
pub acknowledged_message_ids: Vec<Uuid>,
pub key_id: String,
}
impl ReconcileDecisionPayload {
pub fn valid_profile(&self, now: DateTime<Utc>) -> bool {
self.domain == "rmm.reconciliation-decision"
&& self.schema_version == 1
&& !self.decision_id.is_nil()
&& !self.request_id.is_nil()
&& self.issued_at <= now
&& now < self.valid_until
&& self.valid_until > self.issued_at
&& (self.valid_until - self.issued_at).num_seconds() <= 60
&& self.attempts.len() <= 256
&& self.acknowledged_message_ids.len() <= 256
&& (!self.helper_ready || self.ready)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reconciliation_cannot_be_a_permit_or_unbounded_ticket() {
let id = Uuid::new_v4();
let now = Utc::now();
let mut d = ReconcileDecisionPayload {
domain: "rmm.reconciliation-decision".into(),
schema_version: 1,
decision_id: id,
request_id: id,
request_hash: "ab".repeat(32),
tenant_id: id,
asset_id: id,
agent_id: id,
enrollment_generation: 1,
assignment_version: 1,
connection_generation: 1,
boot_id: id,
journal_id: id,
checkpoint: 1,
helper_journal_id: None,
helper_checkpoint: 0,
issued_at: now,
valid_until: now + chrono::Duration::seconds(60),
ready: true,
helper_ready: false,
reason: "CONSISTENT".into(),
attempts: vec![],
acknowledged_message_ids: vec![],
key_id: "cd".repeat(32),
};
assert!(d.valid_profile(now));
d.domain = "rmm.execution-permit".into();
assert!(!d.valid_profile(now));
d.domain = "rmm.reconciliation-decision".into();
d.valid_until = now + chrono::Duration::seconds(61);
assert!(!d.valid_profile(now));
}
#[test]
fn outcome_codec_keeps_raw_output_and_sorts_evidence() {
let o = ReconciledOutcome {
state: "succeeded".into(),
stdout: vec![13, 10],
stderr: vec![],
exit_code: Some(0),
output_truncated: false,
reboot_required: false,
evidence: serde_json::from_str(r#"{"z":1,"a":{"y":2,"b":3}}"#).unwrap(),
error_code: String::new(),
};
let bytes = canonical_outcome_bytes(&o).unwrap();
let text = String::from_utf8(bytes.clone()).unwrap();
assert!(text.contains(r#""stdout":[13,10]"#));
assert!(text.contains(r#""evidence":{"a":{"b":3,"y":2},"z":1}"#));
assert_eq!(
canonical_outcome_bytes(&serde_json::from_slice(&bytes).unwrap()).unwrap(),
bytes
);
}
}