//! Version 1 codec: UTF-8 compact serde JSON of these structs, declaration field //! order, explicit null legacy options (new opt-in fields omit None), 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(value: &T) -> Result, serde_json::Error> { serde_json::to_vec(value) } /// One explicitly qualified Event Log source, not an arbitrary channel/XPath. pub const WINDOWS_EVENT_LOG_FIXTURE_SOURCE: &str = "windows.eventlog.application.rustdiscovery-mvp-test"; pub const WINDOWS_EVENT_LOG_FIXTURE_CAPABILITY: &str = "logs.windows.eventlog.fixture/1"; pub const WINDOWS_EVENT_LOG_FIXTURE_CHANNEL: &str = "Application"; pub const WINDOWS_EVENT_LOG_FIXTURE_PROVIDER: &str = "RustDiscovery-MVP-Test"; /// Fixed per-job Windows PowerShell 5.1 option, never a machine/GPO policy. #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, schemars::JsonSchema)] pub enum WindowsExecutionProfile { #[serde(rename = "powershell_51_remote_signed")] PowerShell51RemoteSigned, } /// A missing field uses serde's default None. A present field must be the exact /// string: null and serde's externally-tagged enum object form are not profiles. pub fn deserialize_windows_execution_profile<'de, D>( deserializer: D, ) -> Result, D::Error> where D: serde::Deserializer<'de>, { let value = String::deserialize(deserializer)?; match value.as_str() { "powershell_51_remote_signed" => { Ok(Some(WindowsExecutionProfile::PowerShell51RemoteSigned)) } _ => Err(serde::de::Error::unknown_variant( &value, &["powershell_51_remote_signed"], )), } } /// Explicit authority for a separately qualified, fully privileged script. #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, schemars::JsonSchema)] pub enum PrivilegedScriptProfile { #[serde(rename = "full_maintenance_v1")] FullMaintenanceV1, } /// Bytes of the Windows Update Agent PowerShell template seeded by migration 0023. pub const WINDOWS_UPDATE_SCRIPT_UTF8: &str = include_str!("windows_update.ps1"); pub const WINDOWS_UPDATE_SCRIPT_SHA256: &str = "0fa5f513a06b6cf902a3f9ac1989987642c181eedd6c305b3912771bd10f2ebf"; pub const WINDOWS_UPDATE_MAX_SECONDS: u32 = 3600; pub const WINDOWS_UPDATE_IDENTITY_PROBE: &str = "Write-Output ([System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value)\n"; pub const WINDOWS_UPDATE_LONG_CAPABILITY: &str = "script.windows_update.long/1"; pub fn valid_windows_update_limit(limit: Option) -> bool { limit.is_none_or(|seconds| (121..=WINDOWS_UPDATE_MAX_SECONDS).contains(&seconds)) } /// Only the built-in template's final ASCII JSON object describes the host's /// restart state. Earlier lines can include per-update results and native titles. pub fn windows_update_reboot_report(stdout: &[u8]) -> Option { let summary = stdout .rsplit(|byte| *byte == b'\n') .map(<[u8]>::trim_ascii) .find(|line| !line.is_empty())?; let json: serde_json::Value = serde_json::from_slice(summary).ok()?; let obj = json.as_object()?; let reboot = obj.get("reboot_required")?.as_bool()?; (obj.len() == 2 && (obj.get("found").is_some_and(|v| v.is_u64()) || (reboot && obj.get("status").and_then(|v| v.as_str()) == Some("restart_pending")))) .then_some(reboot) } pub const FULL_MAINTENANCE_CAPABILITY: &str = "script.full_maintenance/1"; pub fn deserialize_privileged_script_profile<'de, D>( d: D, ) -> Result, D::Error> where D: serde::Deserializer<'de>, { let value = String::deserialize(d)?; match value.as_str() { "full_maintenance_v1" => Ok(Some(PrivilegedScriptProfile::FullMaintenanceV1)), _ => Err(serde::de::Error::unknown_variant( &value, &["full_maintenance_v1"], )), } } /// Optional metadata pins preserve old codecs when missing, reject null or /// noncanonical digests when explicitly supplied. pub fn deserialize_optional_sha256<'de, D>(d: D) -> Result, D::Error> where D: serde::Deserializer<'de>, { let value = String::deserialize(d)?; if value.len() != 64 || !value .bytes() .all(|b| b.is_ascii_digit() || b"abcdef".contains(&b)) { return Err(serde::de::Error::custom("lowercase SHA256 required")); } Ok(Some(value)) } /// Policy lists are strict when present; omission is deny, never a wildcard. pub fn deserialize_script_profiles<'de, D>( d: D, ) -> Result>, D::Error> where D: serde::Deserializer<'de>, { let values = Vec::::deserialize(d)?; if values.len() != 1 || values[0] != "full_maintenance_v1" { return Err(serde::de::Error::custom( "exact full_maintenance_v1 profile required", )); } Ok(Some(vec![PrivilegedScriptProfile::FullMaintenanceV1])) } /// Missing preserves Linux codecs; explicit null/nonobject is never a manifest. pub fn deserialize_windows_msi_manifest<'de, D>( deserializer: D, ) -> Result>, D::Error> where D: serde::Deserializer<'de>, { crate::windows_execution::ResolvedWindowsMsi::deserialize(deserializer) .map(|m| Some(Box::new(m))) } #[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, expected_stdout: Option, #[serde( default, deserialize_with = "deserialize_windows_execution_profile", skip_serializing_if = "Option::is_none" )] #[schemars(with = "WindowsExecutionProfile")] windows_execution_profile: Option, #[serde( default, deserialize_with = "deserialize_privileged_script_profile", skip_serializing_if = "Option::is_none" )] #[schemars(with = "PrivilegedScriptProfile")] privileged_script_profile: Option, }, RefreshInventory { scope: String, }, QueryLogs { unit: String, since: DateTime, until: DateTime, 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, #[serde(default, skip_serializing_if = "Option::is_none")] apt_manifest: Option, #[serde( default, deserialize_with = "deserialize_windows_msi_manifest", skip_serializing_if = "Option::is_none" )] #[schemars(with = "crate::windows_execution::ResolvedWindowsMsi")] windows_msi_manifest: Option>, }, ApplyUpdates { provider: String, packages: Vec, reboot_policy: String, #[serde(default, skip_serializing_if = "Option::is_none")] apt_manifest: Option, }, AptNativeAcceptance { recipe_id: String, recipe_version: String, apt_manifest: crate::apt_transaction::AptExecutionManifest, }, UpdateAgent { update: Box, }, 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", Self::UpdateAgent { .. } => "update_agent", } } 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, windows_execution_profile, .. } => { matches!(interpreter.as_str(), "posix_sh" | "bash" | "powershell") && (windows_execution_profile.is_none() || interpreter == "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 <= chrono::Duration::hours(24) && (u != WINDOWS_EVENT_LOG_FIXTURE_SOURCE || since.timestamp() >= 0) && *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, windows_msi_manifest: Some(m), } => { m.validate() && provider == "msi" && package == crate::windows_execution::MSI_PACKAGE_ID && version == &m.recipe.postcondition.product_version && architecture == "x64" && installation_context == "machine" && recipe_version == &m.recipe.recipe_version && recipe_id.as_ref() == Some(&m.recipe.recipe_id) && apt_manifest.is_none() } Self::EnsurePackage { provider, package, version, architecture, recipe_version, installation_context, recipe_id, apt_manifest, windows_msi_manifest: None, } => { 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::UpdateAgent { update } => update.validate(), 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 windows_msi(&self) -> Option<&crate::windows_execution::ResolvedWindowsMsi> { match self { Self::EnsurePackage { windows_msi_manifest: Some(m), .. } => Some(m.as_ref()), _ => None, } } pub fn valid_helper_denial_shape(&self, identity: &str) -> bool { (matches!(self,Self::SetServiceState{state,..} if matches!(state.as_str(),"running"|"stopped")) && self.validate()) || (identity == "system" && self.windows_msi().is_some() && self.validate()) || (identity == "system" && self.full_maintenance() && self.script_platform() == Some("windows") && self.validate()) || (identity == "system" && matches!( self, Self::Reboot { reconnect_timeout_seconds: crate::windows_reboot::RECONNECT_SECONDS, .. } ) && self.validate()) } pub fn full_maintenance(&self) -> bool { matches!( self, Self::RunScript { privileged_script_profile: Some(PrivilegedScriptProfile::FullMaintenanceV1), .. } ) } pub fn is_windows_update_template(&self) -> bool { self.exact_windows_maintenance_script(WINDOWS_UPDATE_SCRIPT_UTF8) } pub fn windows_update_or_identity_probe(&self) -> bool { self.is_windows_update_template() || self.exact_windows_maintenance_script(WINDOWS_UPDATE_IDENTITY_PROBE) } fn exact_windows_maintenance_script(&self, text: &str) -> bool { matches!(self, Self::RunScript { interpreter, script_utf8, arguments, expected_stdout: None, windows_execution_profile: Some(WindowsExecutionProfile::PowerShell51RemoteSigned), privileged_script_profile: Some(PrivilegedScriptProfile::FullMaintenanceV1), } if interpreter == "powershell" && arguments.is_empty() && script_utf8 == text) } pub fn windows_system_runtime_limit(&self, normal: u32, windows_update: Option) -> u32 { if self.is_windows_update_template() { windows_update.unwrap_or(normal) } else { normal } } pub fn valid_execution_identity(&self, identity: &str) -> bool { if let Self::UpdateAgent { update } = self { return update.execution_identity() == Some(identity); } !self.full_maintenance() || matches!( (identity, self.script_platform()), ("root", Some("linux")) | ("system", Some("windows")) ) } pub fn is_windows_event_log_fixture(&self) -> bool { matches!(self, Self::QueryLogs { unit, .. } if unit == WINDOWS_EVENT_LOG_FIXTURE_SOURCE) } /// The outer process budget includes authenticated worker startup/cleanup; /// its inner Event Log calls retain their own cooperative <=5s deadline. pub fn valid_job_limits(&self, runtime_seconds: u32, output_bytes: u32) -> bool { (1..=3600).contains(&runtime_seconds) && (!matches!(self, Self::UpdateAgent { .. }) || (runtime_seconds == 600 && output_bytes <= 65536)) && (!self.full_maintenance() || (output_bytes <= 65536 && runtime_seconds <= if self.script_platform() == Some("windows") { self.windows_system_runtime_limit(120, Some(WINDOWS_UPDATE_MAX_SECONDS)) } else { 300 })) && (self.windows_msi().is_none() || ((10..=120).contains(&runtime_seconds) && (1024..=65536).contains(&output_bytes))) && (1..=262144).contains(&output_bytes) && (!self.is_windows_event_log_fixture() || ((10..=120).contains(&runtime_seconds) && (1024..=65536).contains(&output_bytes))) } /// 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 { if !self.valid_execution_identity(identity) || (identity == "system" && !self.valid_helper_denial_shape(identity) && !matches!(self, Self::UpdateAgent { .. })) { return false; } let has = |cap: &str| capabilities.iter().any(|c| c == cap); if !has(self.name()) || (self.full_maintenance() && !((has(FULL_MAINTENANCE_CAPABILITY) || (self.windows_update_or_identity_probe() && has(WINDOWS_UPDATE_LONG_CAPABILITY))) && has("rmm.sync.v1") && has(&format!("{}:run_script", identity)) && has(if identity == "root" { "helper.root.v1" } else { "helper.system.v1" }))) { return false; } match self { Self::UpdateAgent { update } => { let linux = update.execution_identity() == Some("root"); update.validate() && has(crate::agent_update::APPLY_CAPABILITY) && has("rmm.sync.v1") && has(if linux { "linux.base/1" } else { "windows.base/1" }) && !has(if linux { "windows.base/1" } else { "linux.base/1" }) && has(if linux { "helper.root.v1" } else { "helper.system.v1" }) && has(&format!("{}:update_agent", identity)) && has(&format!( "updater.binary.sha256:{}", update.updater.binary_sha256 )) && has(&format!( "updater.policy.sha256:{}", update.updater.policy_sha256 )) && has(&format!( "helper.binary.sha256:{}", update.predecessor.helper_sha256 )) } Self::Reboot { reconnect_timeout_seconds, .. } if identity == "system" || has("windows.base/1") => { identity == "system" && *reconnect_timeout_seconds == crate::windows_reboot::RECONNECT_SECONDS && has("windows.base/1") && !has("linux.base/1") && has("rmm.sync.v1") && has("helper.system.v1") && has("system:reboot") && has(crate::windows_reboot::CAPABILITY) } Self::RunScript { interpreter, windows_execution_profile, .. } if interpreter == "powershell" => { (identity == "agent_service" || (identity == "system" && self.full_maintenance())) && has("windows.base/1") && !has("linux.base/1") && has("rmm.sync.v1") && has("script.powershell/1") && (windows_execution_profile.is_none() || has("script.powershell.process_remote_signed/1")) } Self::RunScript { windows_execution_profile, .. } => { windows_execution_profile.is_none() && 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")) } Self::EnsurePackage { .. } if self.windows_msi().is_some() || has("windows.base/1") => { self.windows_msi().is_some() && self.validate() && identity == "system" && has("windows.base/1") && !has("linux.base/1") && has("rmm.sync.v1") && has("helper.system.v1") && has("system:ensure_package") && has(crate::windows_execution::MSI_CAPABILITY) } Self::QueryLogs { unit, .. } if unit == WINDOWS_EVENT_LOG_FIXTURE_SOURCE || has("windows.base/1") => { identity == "agent_service" && unit == WINDOWS_EVENT_LOG_FIXTURE_SOURCE && has("windows.base/1") && !has("linux.base/1") && has("rmm.sync.v1") && has(WINDOWS_EVENT_LOG_FIXTURE_CAPABILITY) } Self::SetServiceState { state, .. } if identity == "system" || has("windows.base/1") => { identity == "system" && has("windows.base/1") && !has("linux.base/1") && has("rmm.sync.v1") && has("helper.system.v1") && has("system:set_service_state") && matches!(state.as_str(), "running" | "stopped") } _ => !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, windows_msi_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, pub start_before: DateTime, 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, } #[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, pub max_parallel: u32, pub halt_after_failures: u32, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub recipe_references: Vec, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub artifact_references: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] pub script_revision: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct ScriptRevisionReference { pub revision_id: Uuid, pub name: String, pub version: i32, pub script_sha256: String, } #[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, pub start_before: DateTime, pub max_runtime_seconds: u32, pub key_id: String, /// Only update_agent needs its actual plan ID in the local durable handoff. /// Omitted on every legacy action, preserving original signed grant bytes. #[serde(default, skip_serializing_if = "Option::is_none")] pub agent_update_plan_id: Option, } #[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, /// A human closed an unknown attempt in the WebUI. The effect stays /// unknown; the attempt is final and is never retried or reinterpreted. ClosedUnknown, } impl JobState { pub fn terminal(self) -> bool { matches!( self, Self::Succeeded | Self::Failed | Self::Cancelled | Self::Expired | Self::ClosedUnknown ) } 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_update_final_report_and_policy_are_exact() { assert_eq!( windows_update_reboot_report( b"ignored \xff\r\n{\"found\":1,\"reboot_required\":true}\r\n" ), Some(true) ); assert_eq!( windows_update_reboot_report(br#"{"reboot_required":false,"found":0}"#), Some(false) ); assert_eq!( windows_update_reboot_report(br#"{"reboot_required":true,"status":"restart_pending"}"#), Some(true) ); assert_eq!( windows_update_reboot_report(br#"{"id":"an update","reboot_required":true}"#), None ); assert_eq!(windows_update_reboot_report(b"partial"), None); assert!(!valid_windows_update_limit(Some(3601))); } #[test] fn windows_system_scm_is_explicit_and_preserves_linux_service_bytes() { let caps: Vec = [ "windows.base/1", "rmm.sync.v1", "helper.system.v1", "system:set_service_state", "set_service_state", ] .into_iter() .map(str::to_string) .collect(); for state in ["running", "stopped"] { let action = Action::SetServiceState { unit: "RmmDiscoveryFixtureService".into(), state: state.into(), }; assert!(action.validate() && action.available_for("system", &caps)); for missing in 0..caps.len() { let mut incomplete = caps.clone(); incomplete.remove(missing); assert!(!action.available_for("system", &incomplete)); } for identity in ["root", "agent_service", "SYSTEM"] { assert!(!action.available_for(identity, &caps)); } let mut mixed = caps.clone(); mixed.push("linux.base/1".into()); assert!(!action.available_for("system", &mixed)); assert!(!action.available_for( "system", &["linux.base/1".into(), "set_service_state".into()] )); } let restart = Action::SetServiceState { unit: "rmm-mvp-test.service".into(), state: "restarted".into(), }; assert!(!restart.available_for("system", &caps)); let linux = vec!["linux.base/1".into(), "set_service_state".into()]; for identity in ["root", "agent_service"] { assert!(restart.available_for(identity, &linux)); } assert_eq!( encode(&restart).unwrap(), br#"{"action":"set_service_state","unit":"rmm-mvp-test.service","state":"restarted"}"# ); let script = Action::RunScript { interpreter: "powershell".into(), script_utf8: "Write-Output 'hi'\r\n".into(), arguments: vec![], expected_stdout: None, windows_execution_profile: None, privileged_script_profile: None, }; let mut all = caps; all.extend(["run_script".into(), "script.powershell/1".into()]); assert!(!script.available_for("system", &all)); let posix = Action::RunScript { interpreter: "posix_sh".into(), script_utf8: "printf hi\n".into(), arguments: vec![], expected_stdout: None, windows_execution_profile: None, privileged_script_profile: None, }; let reboot = Action::Reboot { reason: "fixed test".into(), reconnect_timeout_seconds: 180, dependency_group: "one-test-vm".into(), }; let linux = ["linux.base/1", "run_script", "reboot"].map(str::to_string); assert!(!posix.available_for("system", &linux)); assert!(!reboot.available_for("system", &linux)); for identity in ["root", "agent_service"] { assert!(posix.available_for(identity, &linux)); assert!(reboot.available_for(identity, &linux)); } } #[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()), windows_execution_profile: None, privileged_script_profile: None, }; let caps: Vec = [ "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::(&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 full_maintenance_is_explicit_strict_identity_and_capability_bound() { let legacy = br#"{"action":"run_script","interpreter":"posix_sh","script_utf8":"id\n","arguments":[],"expected_stdout":null}"#; let mut action: Action = serde_json::from_slice(legacy).unwrap(); assert_eq!(encode(&action).unwrap(), legacy); for value in [ serde_json::Value::Null, serde_json::json!({"FullMaintenanceV1":null}), serde_json::json!("latest"), serde_json::json!(true), ] { let mut input: serde_json::Value = serde_json::from_slice(legacy).unwrap(); input["privileged_script_profile"] = value; assert!(serde_json::from_value::(input).is_err()); } if let Action::RunScript { privileged_script_profile, .. } = &mut action { *privileged_script_profile = Some(PrivilegedScriptProfile::FullMaintenanceV1); } assert!(action.validate()); assert!(action.valid_execution_identity("root")); assert!(!action.valid_execution_identity("agent_service")); assert!(!action.valid_execution_identity("system")); assert!(action.valid_job_limits(300, 65536)); assert!(!action.valid_job_limits(301, 65536)); assert!(!action.valid_job_limits(300, 65537)); let caps: Vec = [ "linux.base/1", "rmm.sync.v1", "helper.root.v1", "run_script", "root:run_script", FULL_MAINTENANCE_CAPABILITY, ] .into_iter() .map(str::to_owned) .collect(); assert!(action.available_for("root", &caps)); for missing in &caps { assert!( !action.available_for( "root", &caps .iter() .filter(|c| *c != missing) .cloned() .collect::>() ) ); } assert!(!action.available_for("agent_service", &caps)); if let Action::RunScript { interpreter, script_utf8, windows_execution_profile, .. } = &mut action { *interpreter = "powershell".into(); *script_utf8 = "Write-Output 'hi'\r\n".into(); *windows_execution_profile = Some(WindowsExecutionProfile::PowerShell51RemoteSigned); } assert!(action.valid_helper_denial_shape("system")); assert!(!action.valid_helper_denial_shape("root")); assert!(action.valid_job_limits(120, 65536)); assert!(!action.valid_job_limits(121, 65536)); let caps: Vec = [ "windows.base/1", "rmm.sync.v1", "helper.system.v1", "run_script", "system:run_script", "script.powershell/1", "script.powershell.process_remote_signed/1", FULL_MAINTENANCE_CAPABILITY, ] .into_iter() .map(str::to_owned) .collect(); assert!(action.available_for("system", &caps)); for missing in &caps { assert!( !action.available_for( "system", &caps .iter() .filter(|c| *c != missing) .cloned() .collect::>() ) ); } assert!(!action.available_for("root", &caps)); } #[test] fn script_console_golden_plans_use_actual_rust_codec() { let cases: Vec = serde_json::from_str(include_str!( "../../../tests/script_console/codec-golden.json" )) .unwrap(); assert_eq!(cases.len(), 3); for case in cases { let bytes: Vec = serde_json::from_value(case["plan_payload_bytes"].clone()).unwrap(); let plan: PlanPayload = serde_json::from_slice(&bytes).unwrap(); assert_eq!(encode(&plan).unwrap(), bytes); assert_eq!(hash(&bytes), case["plan_hash"]); let job = &plan.jobs[0]; let job_bytes = encode(&job.payload).unwrap(); assert_eq!( serde_json::to_value(&job_bytes).unwrap(), case["job_payload_bytes"] ); assert_eq!(hash(&job_bytes), job.job_payload_hash); assert_eq!(job.job_payload_hash, case["job_payload_hash"]); assert!(job.payload.action.validate()); assert!( job.payload .action .valid_execution_identity(&job.payload.execution_identity) ); let Action::RunScript { script_utf8, .. } = &job.payload.action else { panic!("script fixture") }; assert_eq!(hash(script_utf8.as_bytes()), case["script_sha256"]); } } #[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, windows_execution_profile: None, privileged_script_profile: 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 windows_remote_signed_profile_is_optional_exact_and_capability_bound() { let schema = schemars::schema_for!(Action).to_value(); let script_schema = schema["oneOf"] .as_array() .unwrap() .iter() .find(|variant| { variant["properties"] .get("windows_execution_profile") .is_some() }) .unwrap(); assert_eq!( script_schema["properties"]["windows_execution_profile"], serde_json::json!({"$ref":"#/$defs/WindowsExecutionProfile"}) ); assert!( !script_schema["required"] .as_array() .unwrap() .contains(&serde_json::json!("windows_execution_profile")) ); assert_eq!(schema["$defs"]["WindowsExecutionProfile"]["type"], "string"); let legacy = br#"{"action":"run_script","interpreter":"powershell","script_utf8":"Write-Output 'hi'\r\n","arguments":[],"expected_stdout":null}"#; let mut action: Action = serde_json::from_slice(legacy).unwrap(); assert_eq!(encode(&action).unwrap(), legacy); let inherited_hash = hash(legacy); if let Action::RunScript { windows_execution_profile, .. } = &mut action { *windows_execution_profile = Some(WindowsExecutionProfile::PowerShell51RemoteSigned); } let encoded = encode(&action).unwrap(); assert_eq!( String::from_utf8(encoded.clone()).unwrap(), String::from_utf8(legacy[..legacy.len() - 1].to_vec()).unwrap() + r#","windows_execution_profile":"powershell_51_remote_signed"}"# ); assert_ne!(hash(&encoded), inherited_hash); assert_eq!(serde_json::from_slice::(&encoded).unwrap(), action); let caps: Vec = [ "windows.base/1", "rmm.sync.v1", "run_script", "script.powershell/1", "script.powershell.process_remote_signed/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)); } for identity in ["root", "system", "SYSTEM"] { assert!(!action.available_for(identity, &caps)); } let mut mixed = caps.clone(); mixed.push("linux.base/1".into()); assert!(!action.available_for("agent_service", &mixed)); for interpreter in ["posix_sh", "bash", "pwsh"] { let mut invalid = action.clone(); if let Action::RunScript { interpreter: i, .. } = &mut invalid { *i = interpreter.into(); } assert!(!invalid.validate()); assert!(!invalid.available_for("agent_service", &caps)); assert!(!invalid.available_for("root", &["linux.base/1".into(), "run_script".into()])); } for profile in [ serde_json::Value::Null, serde_json::json!(false), serde_json::json!(1), serde_json::json!([]), serde_json::json!({}), serde_json::json!({"powershell_51_remote_signed": null}), serde_json::json!("bypass"), serde_json::json!("RemoteSigned"), serde_json::json!("powershell_7_remote_signed"), ] { let mut bad = serde_json::to_value(&action).unwrap(); bad["windows_execution_profile"] = profile.clone(); assert!(serde_json::from_value::(bad).is_err(), "{profile}"); // An opt-in profile is also never metadata on another action. assert!( serde_json::from_value::(serde_json::json!({ "action":"refresh_inventory", "scope":"windows.base", "windows_execution_profile":profile })) .is_err() ); } } #[test] fn windows_event_log_fixture_scope_limits_and_exact_24h_preserve_linux_bytes() { let since = DateTime::parse_from_rfc3339("2026-11-14T00:00:00Z") .unwrap() .with_timezone(&Utc); let mut action = Action::QueryLogs { unit: WINDOWS_EVENT_LOG_FIXTURE_SOURCE.into(), since, until: since + chrono::Duration::hours(24), max_lines: 1000, }; let caps: Vec = [ "windows.base/1", "rmm.sync.v1", "query_logs", WINDOWS_EVENT_LOG_FIXTURE_CAPABILITY, ] .into_iter() .map(str::to_string) .collect(); assert!(action.validate()); assert!(action.available_for("agent_service", &caps)); assert!(action.valid_job_limits(10, 1024)); assert!(action.valid_job_limits(120, 65536)); for (runtime, bytes) in [(9, 1024), (121, 1024), (10, 1023), (10, 65537)] { assert!(!action.valid_job_limits(runtime, bytes)); } for i in 0..caps.len() { let mut short = caps.clone(); short.remove(i); assert!(!action.available_for("agent_service", &short)); } for identity in ["root", "system", "SYSTEM"] { assert!(!action.available_for(identity, &caps)); } let mut mixed = caps.clone(); mixed.push("linux.base/1".into()); assert!(!action.available_for("agent_service", &mixed)); assert!(!action.available_for("root", &["linux.base/1".into(), "query_logs".into()])); for unit in [ "Application", "Security", "windows.eventlog.application.other", ] { let mut wrong = action.clone(); if let Action::QueryLogs { unit: u, .. } = &mut wrong { *u = unit.into(); } assert!(!wrong.available_for("agent_service", &caps)); } if let Action::QueryLogs { until, .. } = &mut action { *until += chrono::Duration::nanoseconds(1); } assert!(!action.validate()); let linux = Action::QueryLogs { unit: "rmm-test.service".into(), since, until: since + chrono::Duration::hours(24), max_lines: 1000, }; assert_eq!( String::from_utf8(encode(&linux).unwrap()).unwrap(), r#"{"action":"query_logs","unit":"rmm-test.service","since":"2026-11-14T00:00:00Z","until":"2026-11-15T00:00:00Z","max_lines":1000}"# ); assert!(linux.validate()); for identity in ["root", "agent_service"] { assert!(linux.available_for(identity, &["linux.base/1".into(), "query_logs".into()])); } let mut too_long = linux; if let Action::QueryLogs { until, .. } = &mut too_long { *until += chrono::Duration::minutes(59); } assert!(!too_long.validate()); let pre_epoch = Action::QueryLogs { unit: WINDOWS_EVENT_LOG_FIXTURE_SOURCE.into(), since: DateTime::from_timestamp(-1, 0).unwrap(), until: DateTime::from_timestamp(0, 0).unwrap(), max_lines: 1, }; assert!(!pre_epoch.validate()); } #[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::::from_timestamp(0, 0).unwrap(); let p = ExecutionPermitPayload { agent_update_plan_id: None, 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::(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()); } }