Files
rust-discovery/crates/domain/src/jobs.rs
T
2026-11-14 00:52:40 +01:00

590 lines
22 KiB
Rust

//! 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" | "powershell")
&& (interpreter != "powershell"
|| script_utf8.is_ascii()
|| script_utf8.starts_with('\u{feff}'))
&& !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 } => {
matches!(scope.as_str(), "linux.base" | "windows.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)
}
}
}
/// Interpreter identity is part of the immutable action, never inferred at execution.
pub fn script_platform(&self) -> Option<&'static str> {
match self {
Self::RunScript { interpreter, .. } => match interpreter.as_str() {
"posix_sh" | "bash" => Some("linux"),
"powershell" => Some("windows"),
_ => None,
},
_ => None,
}
}
/// Shared plan/revalidation/start gate. Passive Windows never implies job support.
pub fn available_for(&self, identity: &str, capabilities: &[String]) -> bool {
let has = |cap: &str| capabilities.iter().any(|c| c == cap);
if !has(self.name()) {
return false;
}
match self {
Self::RunScript { interpreter, .. } if interpreter == "powershell" => {
identity == "agent_service"
&& has("windows.base/1")
&& !has("linux.base/1")
&& has("rmm.sync.v1")
&& has("script.powershell/1")
}
Self::RunScript { .. } => {
self.script_platform() == Some("linux")
&& has("linux.base/1")
&& !has("windows.base/1")
}
Self::RefreshInventory { scope } => {
(identity == "agent_service" || scope == "linux.base")
&& has(&format!("{scope}/1"))
&& !(has("linux.base/1") && has("windows.base/1"))
&& (scope != "windows.base" || has("rmm.sync.v1"))
}
_ => !has("windows.base/1"), // Windows adapters are separately qualified.
}
}
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 windows_interpreter_and_capability_contract() {
let mut action = Action::RunScript {
interpreter: "powershell".into(),
script_utf8: "Write-Output 'Hello'\r\n".into(),
arguments: vec![],
expected_stdout: Some("Hello\r\n".into()),
};
let caps: Vec<String> = [
"windows.base/1",
"rmm.sync.v1",
"run_script",
"script.powershell/1",
]
.into_iter()
.map(str::to_string)
.collect();
assert!(action.validate());
assert!(action.available_for("agent_service", &caps));
for missing in 0..caps.len() {
let mut short = caps.clone();
short.remove(missing);
assert!(!action.available_for("agent_service", &short));
}
assert!(!action.available_for("root", &caps));
assert!(!action.available_for("SYSTEM", &caps));
assert!(!action.available_for(
"agent_service",
&["linux.base/1".into(), "run_script".into()]
));
let mut both = caps.clone();
both.push("linux.base/1".into());
assert!(!action.available_for("agent_service", &both));
if let Action::RunScript {
interpreter,
script_utf8,
..
} = &mut action
{
*script_utf8 = "Write-Output 'é'".into();
assert!(interpreter == "powershell");
}
assert!(!action.validate());
if let Action::RunScript { script_utf8, .. } = &mut action {
*script_utf8 = "\u{feff}Write-Output 'é'\r\n".into();
}
assert!(action.validate());
let bytes = encode(&action).unwrap();
assert_eq!(serde_json::from_slice::<Action>(&bytes).unwrap(), action);
if let Action::RunScript { interpreter, .. } = &mut action {
*interpreter = "pwsh".into();
}
assert!(!action.validate());
assert!(!action.available_for("agent_service", &caps));
let refresh = Action::RefreshInventory {
scope: "windows.base".into(),
};
assert!(refresh.validate());
assert!(refresh.available_for(
"agent_service",
&[
"windows.base/1".into(),
"rmm.sync.v1".into(),
"refresh_inventory".into()
]
));
assert!(!refresh.available_for(
"root",
&[
"windows.base/1".into(),
"rmm.sync.v1".into(),
"refresh_inventory".into()
]
));
}
#[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());
}
}