feat: add approval bound full maintenance script console and executors
Rust development slice / linux (push) Failing after 6s

This commit is contained in:
2026-11-14 16:35:11 +01:00
parent 287a784c8f
commit ff78b6a498
51 changed files with 8880 additions and 278 deletions
+1
View File
@@ -519,6 +519,7 @@ mod tests {
arguments: vec![],
expected_stdout: None,
windows_execution_profile: None,
privileged_script_profile: None,
},
execution_identity: "agent_service".into(),
not_before: c.issued_at,
+18 -1
View File
@@ -292,6 +292,21 @@ fn windows_event_log_success_evidence(
// The profile records the requested process option, never an effective GPO policy.
fn script_profile_evidence(action: &Action, evidence: &Value) -> Result<()> {
if action.full_maintenance() {
let Action::RunScript { script_utf8, .. } = action else {
unreachable!()
};
ensure!(
evidence["privileged_script_profile"] == "full_maintenance_v1"
&& evidence["script_sha256"] == hash(script_utf8.as_bytes())
&& match action.script_platform() {
Some("linux") => evidence["execution_uid"] == 0,
Some("windows") => evidence["execution_sid"] == "S-1-5-18",
_ => false,
},
"full maintenance identity/profile evidence mismatch"
);
}
if let Action::RunScript {
script_utf8,
windows_execution_profile: Some(WindowsExecutionProfile::PowerShell51RemoteSigned),
@@ -411,6 +426,7 @@ mod script_profile_tests {
arguments: vec![],
expected_stdout: None,
windows_execution_profile: Some(WindowsExecutionProfile::PowerShell51RemoteSigned),
privileged_script_profile: None,
};
let evidence = json!({"windows_execution_profile":"powershell_51_remote_signed",
"execution_policy":"process_remote_signed_requested", "execution_policy_requested":"RemoteSigned",
@@ -628,7 +644,8 @@ pub async fn permit(
if !crate::permissions::allowed(&mut tx, &approver, "plans:approve").await?
|| !crate::permissions::allowed(&mut tx, &plan.principal, "operations:submit").await?
|| (matches!(payload.action, Action::RunScript { .. })
&& !crate::permissions::allowed(&mut tx, &plan.principal, "scripts:execute").await?)
&& (!crate::permissions::allowed(&mut tx, &plan.principal, "scripts:execute").await?
|| !crate::permissions::allowed(&mut tx, &approver, "scripts:execute").await?))
{
return Ok(denied("AUTHORIZATION_REVOKED"));
}
+50 -1
View File
@@ -162,6 +162,13 @@ pub struct Variant {
#[derive(Clone, Deserialize, Serialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
struct WebParameters {
#[serde(
default,
deserialize_with = "deserialize_privileged_script_profile",
skip_serializing_if = "Option::is_none"
)]
#[schemars(with = "PrivilegedScriptProfile")]
privileged_script_profile: Option<PrivilegedScriptProfile>,
execution_identity: String,
timeout_seconds: u32,
max_output_bytes: u32,
@@ -230,6 +237,7 @@ impl PlanRequest {
arguments: p.arguments.clone().unwrap_or_default(),
expected_stdout: p.expected_stdout.clone(),
windows_execution_profile: v.windows_execution_profile,
privileged_script_profile: p.privileged_script_profile,
}
}
"refresh_inventory" => Action::RefreshInventory {
@@ -329,6 +337,7 @@ fn validate_variants(variants: &[Variant]) -> Result<()> {
arguments: vec![],
expected_stdout: None,
windows_execution_profile: v.windows_execution_profile,
privileged_script_profile: None,
};
if v.encoding != "utf-8"
|| action.script_platform() != Some(v.os_family.as_str())
@@ -346,6 +355,15 @@ fn capabilities(value: Value) -> Result<Vec<String>> {
serde_json::from_value(value).map_err(|_| fail("UNSUPPORTED_CAPABILITY"))
}
fn target_action(input: &PlanInput, caps: &[String]) -> Result<Action> {
if !input
.action
.valid_execution_identity(&input.execution_identity)
|| (input.execution_identity == "system"
&& matches!(input.action, Action::RunScript { .. })
&& !input.action.full_maintenance())
{
return Err(fail("VALIDATION_ERROR"));
}
if input.script_variants.is_empty() {
return Ok(input.action.clone());
}
@@ -356,6 +374,7 @@ fn target_action(input: &PlanInput, caps: &[String]) -> Result<Action> {
arguments,
expected_stdout,
windows_execution_profile,
privileged_script_profile,
} = &input.action
else {
return Err(fail("VALIDATION_ERROR"));
@@ -364,7 +383,7 @@ fn target_action(input: &PlanInput, caps: &[String]) -> Result<Action> {
if interpreter != &first.interpreter
|| script_utf8 != &first.script_utf8
|| windows_execution_profile != &first.windows_execution_profile
|| (input.execution_identity != "agent_service"
|| (input.execution_identity == "root"
&& input
.script_variants
.iter()
@@ -391,6 +410,7 @@ fn target_action(input: &PlanInput, caps: &[String]) -> Result<Action> {
arguments: arguments.clone(),
expected_stdout: expected_stdout.clone(),
windows_execution_profile: v.windows_execution_profile,
privileged_script_profile: *privileged_script_profile,
})
}
async fn policy(tx: &mut Transaction<'_, Postgres>) -> Result<()> {
@@ -413,6 +433,9 @@ pub async fn plan(
if input.targets.asset_ids.is_empty()
|| input.targets.asset_ids.len() > 100
|| !input.action.validate_plan_shape()
|| !input
.action
.valid_execution_identity(&input.execution_identity)
|| !matches!(
input.execution_identity.as_str(),
"agent_service" | "root" | "system"
@@ -821,6 +844,9 @@ async fn authorize_http(
return Err(fail("AUTHORIZATION_REVOKED"));
}
for job in &plan.jobs {
if matches!(job.payload.action, Action::RunScript { .. }) {
crate::permissions::require_principal(&mut tx, &p, "scripts:execute").await?;
}
if let Some(permission) =
crate::root_policy::execution_permission(&job.payload.execution_identity)
{
@@ -1116,6 +1142,28 @@ mod windows_contract_tests {
}
}
#[test]
fn full_maintenance_web_profile_is_action_wide_strict_and_identity_bound() {
let request = serde_json::json!({"tenant_id":Uuid::nil(),"action":"run_script","targets":{"asset_ids":[Uuid::nil()]},"parameters":{"execution_identity":"system","timeout_seconds":30,"max_output_bytes":4096,"privileged_script_profile":"full_maintenance_v1","variants":[{"os_family":"windows","interpreter":"powershell","encoding":"utf-8","script_utf8":"Write-Output 'hi'\r\n","windows_execution_profile":"powershell_51_remote_signed"}]},"schedule":{"not_before":"2026-11-14T12:00:00Z","start_before":"2026-11-14T13:00:00Z","offline_policy":"wait_until_deadline"},"rollout":{"max_parallel":1,"halt_after_failures":1},"reason":"codec only"});
let resolved = serde_json::from_value::<PlanRequest>(request.clone())
.unwrap()
.resolve(Uuid::nil())
.unwrap();
let action = target_action(&resolved, &["windows.base/1".into()]).unwrap();
assert!(action.full_maintenance());
let mut invalid = resolved.clone();
invalid.execution_identity = "agent_service".into();
assert!(target_action(&invalid, &["windows.base/1".into()]).is_err());
for value in [
serde_json::Value::Null,
serde_json::json!("unknown"),
serde_json::json!({"full_maintenance_v1":null}),
] {
let mut request = request.clone();
request["parameters"]["privileged_script_profile"] = value;
assert!(serde_json::from_value::<PlanRequest>(request).is_err());
}
}
#[test]
fn remote_signed_fixed_variants_bind_profile_without_linux_inheritance() {
let mut i = input();
let legacy_linux = encode(&i.action).unwrap();
@@ -1130,6 +1178,7 @@ mod windows_contract_tests {
windows,
Action::RunScript {
windows_execution_profile: Some(WindowsExecutionProfile::PowerShell51RemoteSigned),
privileged_script_profile: None,
..
}
));
+59 -4
View File
@@ -28,9 +28,19 @@ struct RootScope {
assignment_version: u64,
principals: Vec<String>,
helper_policy_sha256: String,
#[serde(
default,
deserialize_with = "rmm_domain::jobs::deserialize_optional_sha256"
)]
helper_binary_sha256: Option<String>,
acceptance_evidence_id: String,
allowed_services: Vec<String>,
allow_root_scripts: bool,
#[serde(
default,
deserialize_with = "rmm_domain::jobs::deserialize_script_profiles"
)]
allowed_script_profiles: Option<Vec<rmm_domain::jobs::PrivilegedScriptProfile>>,
allow_reboot: bool,
#[serde(default)]
apt: Option<RootAptPolicy>,
@@ -96,6 +106,9 @@ impl RootPolicy {
}
fn required_permissions(job: &JobPayload, sensitive_log: bool) -> Vec<&'static str> {
let mut permissions = vec!["root:execute"];
if matches!(job.action, Action::RunScript { .. }) {
permissions.push("scripts:execute");
}
if matches!(job.action, Action::AptNativeAcceptance { .. }) {
permissions.push("apt:native_acceptance");
}
@@ -205,7 +218,21 @@ impl RootScope {
&& (20..=3600).contains(&job.max_runtime_seconds)
&& (1..=65536).contains(&job.max_output_bytes)
}
Action::RunScript { .. } => self.allow_root_scripts && job.max_runtime_seconds <= 300,
Action::RunScript { .. } => {
self.allow_root_scripts
&& job.max_runtime_seconds <= 300
&& job.action.valid_execution_identity(&job.execution_identity)
&& (!job.action.full_maintenance()
|| (self.helper_binary_sha256.as_ref().is_some_and(|h| {
capabilities.contains(&format!("helper.binary.sha256:{h}"))
}) && self.allowed_script_profiles.as_ref().is_some_and(|v| {
v.contains(
&rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1,
)
}) && capabilities
.iter()
.any(|c| c == rmm_domain::jobs::FULL_MAINTENANCE_CAPABILITY)))
}
Action::SetServiceState { unit, state } => {
self.allowed_services.contains(unit)
&& matches!(state.as_str(), "running" | "stopped")
@@ -265,7 +292,12 @@ fn load() -> Result<RootPolicy, Error> {
}
let policy: RootPolicy =
serde_json::from_slice(&fs::read(path).map_err(|_| disabled())?).map_err(|_| disabled())?;
if policy.schema_version != 1
if !matches!(policy.schema_version, 1 | 2)
|| (policy.schema_version == 1
&& policy
.scopes
.iter()
.any(|s| s.allowed_script_profiles.is_some() || s.helper_binary_sha256.is_some()))
|| policy.profile != "development"
|| policy.expires_at <= Utc::now()
|| policy.scopes.is_empty()
@@ -342,7 +374,7 @@ mod tests {
fn no_capability_or_relabel_shortcut() {
let id = Uuid::new_v4();
let now = Utc::now();
let job = JobPayload {
let mut job = JobPayload {
schema_version: 1,
tenant_id: id,
asset_id: id,
@@ -357,6 +389,7 @@ mod tests {
arguments: vec![],
expected_stdout: None,
windows_execution_profile: None,
privileged_script_profile: None,
},
execution_identity: "root".into(),
not_before: now,
@@ -364,7 +397,7 @@ mod tests {
max_runtime_seconds: 60,
max_output_bytes: 1024,
};
let scope = RootScope {
let mut scope = RootScope {
tenant_id: id,
asset_id: id,
agent_id: id,
@@ -372,9 +405,11 @@ mod tests {
assignment_version: 1,
principals: vec!["selected".into()],
helper_policy_sha256: "ab".repeat(32),
helper_binary_sha256: None,
acceptance_evidence_id: "native-test-record".into(),
allowed_services: vec![],
allow_root_scripts: true,
allowed_script_profiles: None,
allow_reboot: false,
apt: None,
root_logs: None,
@@ -389,6 +424,26 @@ mod tests {
assert!(scope.permits("selected", &job, &caps, None));
assert!(!scope.permits("automation", &job, &caps, None));
assert!(!scope.permits("selected", &job, &caps[..4], None));
if let Action::RunScript {
privileged_script_profile,
..
} = &mut job.action
{
*privileged_script_profile =
Some(rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1);
}
assert!(!scope.permits("selected", &job, &caps, None));
scope.allowed_script_profiles = Some(vec![
rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1,
]);
assert!(!scope.permits("selected", &job, &caps, None));
let mut caps = caps;
caps.push(rmm_domain::jobs::FULL_MAINTENANCE_CAPABILITY.into());
assert!(!scope.permits("selected", &job, &caps, None));
scope.helper_binary_sha256 = Some("cd".repeat(32));
assert!(!scope.permits("selected", &job, &caps, None));
caps.push(format!("helper.binary.sha256:{}", "cd".repeat(32)));
assert!(scope.permits("selected", &job, &caps, None));
let mut windows = caps;
windows.push("windows.base/1".into());
assert!(!scope.permits("selected", &job, &windows, None));
+80 -6
View File
@@ -40,6 +40,11 @@ struct SystemScope {
#[serde(default, deserialize_with = "strict_optional_hashes")]
allowed_msi_recipe_sha256: Option<Vec<String>>,
max_runtime_seconds: u32,
#[serde(
default,
deserialize_with = "rmm_domain::jobs::deserialize_script_profiles"
)]
allowed_script_profiles: Option<Vec<rmm_domain::jobs::PrivilegedScriptProfile>>,
}
fn strict_optional_hashes<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
where
@@ -106,6 +111,10 @@ impl SystemScope {
.len()
== hashes.len()
})
&& self
.allowed_script_profiles
.as_deref()
.is_none_or(|v| v == [rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1])
&& (1..=120).contains(&self.max_runtime_seconds)
}
fn permits(
@@ -114,6 +123,7 @@ impl SystemScope {
job: &JobPayload,
capabilities: &[String],
allow_msi: bool,
allow_scripts: bool,
) -> bool {
let has = |cap: &str| capabilities.iter().any(|c| c == cap);
self.valid()
@@ -145,6 +155,20 @@ impl SystemScope {
&& has("system:set_service_state")
&& has("set_service_state")
}
Action::RunScript { .. } => {
allow_scripts
&& job.action.full_maintenance()
&& self.allowed_script_profiles.as_ref().is_some_and(|v| {
v.contains(
&rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1,
)
})
&& job.action.validate()
&& job
.action
.valid_job_limits(job.max_runtime_seconds, job.max_output_bytes)
&& job.action.available_for("system", capabilities)
}
_ if allow_msi => job.action.windows_msi().is_some_and(|m| {
job.action.validate()
&& job
@@ -164,12 +188,17 @@ impl SystemScope {
}
impl SystemPolicy {
fn valid(&self, now: DateTime<Utc>) -> bool {
matches!(self.schema_version, 1 | 2)
&& (self.schema_version == 2
matches!(self.schema_version, 1..=3)
&& (self.schema_version >= 2
|| self
.scopes
.iter()
.all(|scope| scope.allowed_msi_recipe_sha256.is_none()))
&& (self.schema_version == 3
|| self
.scopes
.iter()
.all(|scope| scope.allowed_script_profiles.is_none()))
&& self.profile == "development"
&& self.expires_at > now
&& !self.scopes.is_empty()
@@ -184,10 +213,15 @@ impl SystemPolicy {
now: DateTime<Utc>,
) -> bool {
self.valid(now)
&& self
.scopes
.iter()
.any(|scope| scope.permits(principal, job, capabilities, self.schema_version == 2))
&& self.scopes.iter().any(|scope| {
scope.permits(
principal,
job,
capabilities,
self.schema_version >= 2,
self.schema_version == 3,
)
})
}
}
fn disabled() -> Error {
@@ -310,6 +344,9 @@ pub async fn authorize(
}
// Independent DB permission; root:execute never implies this scope.
crate::permissions::require(tx, principal, "system:execute").await?;
if matches!(job.action, Action::RunScript { .. }) {
crate::permissions::require(tx, principal, "scripts:execute").await?;
}
let policy = load()?;
let caps:serde_json::Value=sqlx::query_scalar("SELECT capabilities FROM agent_installations WHERE tenant_id=$1 AND agent_id=$2 AND asset_id=$3 AND revoked_at IS NULL AND enrollment_generation=$4 AND assignment_version=$5").bind(job.tenant_id).bind(job.agent_id).bind(job.asset_id).bind(i64::try_from(job.enrollment_generation).map_err(|_|Error(StatusCode::CONFLICT,"BINDING_MISMATCH"))?).bind(i64::try_from(job.assignment_version).map_err(|_|Error(StatusCode::CONFLICT,"BINDING_MISMATCH"))?).fetch_optional(&mut **tx).await?.ok_or(Error(StatusCode::CONFLICT,"AUTHORIZATION_REVOKED"))?;
let capabilities: Vec<String> = serde_json::from_value(caps)?;
@@ -422,6 +459,42 @@ mod tests {
assert!(!policy.permits("selected", &job, &caps, policy.expires_at));
}
#[test]
fn full_script_requires_v3_explicit_scope_and_does_not_inherit_scm_or_msi() {
let (mut policy, mut job, mut caps) = fixture();
job.action = 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: Some(
rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1,
),
};
caps.extend([
"run_script".into(),
"system:run_script".into(),
"script.powershell/1".into(),
rmm_domain::jobs::FULL_MAINTENANCE_CAPABILITY.into(),
]);
for version in [1, 2, 3] {
policy.schema_version = version;
assert!(!policy.permits("selected", &job, &caps, Utc::now()));
}
policy.scopes[0].allowed_script_profiles = Some(vec![
rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1,
]);
for version in [1, 2] {
policy.schema_version = version;
assert!(!policy.permits("selected", &job, &caps, Utc::now()));
}
policy.schema_version = 3;
assert!(policy.permits("selected", &job, &caps, Utc::now()));
assert!(!policy.permits("foreign", &job, &caps, Utc::now()));
caps.retain(|c| c != rmm_domain::jobs::FULL_MAINTENANCE_CAPABILITY);
assert!(!policy.permits("selected", &job, &caps, Utc::now()));
}
#[test]
fn narrow_scm_ceiling_denies_unreviewed_effects_and_provider_inputs() {
let (mut policy, mut job, caps) = fixture();
let now = Utc::now();
@@ -443,6 +516,7 @@ mod tests {
arguments: vec![],
expected_stdout: None,
windows_execution_profile: None,
privileged_script_profile: None,
};
assert!(!policy.permits("selected", &job, &caps, now));
job.action = Action::SetServiceState {