Bind approved Windows PowerShell process policy and prove Linux-first contracts
Rust development slice / linux (push) Failing after 6s

This commit is contained in:
2026-11-14 10:06:10 +01:00
parent 8a315706ea
commit abea4eb4d9
28 changed files with 1275 additions and 32 deletions
+31
View File
@@ -40,6 +40,7 @@ fn fixture() -> (Binding, Request, ExecutionPermitPayload, DateTime<Utc>) {
script_utf8: "printf 'Hello\\n'\n".into(),
arguments: vec![],
expected_stdout: Some("Hello\n".into()),
windows_execution_profile: None,
},
execution_identity: "agent_service".into(),
not_before: now - Duration::minutes(1),
@@ -170,6 +171,36 @@ fn exact_permit_bytes_time_and_all_identity_hash_bindings_are_required() {
let mut changed = request;
changed.signature.truncate(63);
assert!(binding.verify(&changed, now).is_err());
// Changing only the process policy is a payload mutation, even with the
// same script/attempt and a still valid original signature.
let (_, mut request, mut permit, _) = fixture();
let mut job: JobPayload = serde_json::from_slice(&request.job_bytes).unwrap();
job.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,
};
request.job_bytes = encode(&job).unwrap();
permit.job_payload_hash = hash(&request.job_bytes);
request.permit_bytes = encode(&permit).unwrap();
request.signature = key.sign(&request.permit_bytes).to_bytes().to_vec();
binding.verify(&request, now).unwrap();
if let Action::RunScript {
windows_execution_profile,
..
} = &mut job.action
{
*windows_execution_profile =
Some(rmm_domain::jobs::WindowsExecutionProfile::PowerShell51RemoteSigned);
}
request.job_bytes = encode(&job).unwrap();
assert!(binding.verify(&request, now).is_err());
permit.job_payload_hash = hash(&request.job_bytes);
request.permit_bytes = encode(&permit).unwrap();
request.signature = key.sign(&request.permit_bytes).to_bytes().to_vec();
binding.verify(&request, now).unwrap();
}
#[cfg(unix)]
@@ -867,6 +867,7 @@ fn script() -> Action {
script_utf8: "printf hello".into(),
arguments: vec![],
expected_stdout: Some("hello".into()),
windows_execution_profile: None,
}
}
fn success() -> ReconciledOutcome {
+1
View File
@@ -605,6 +605,7 @@ fn script() -> Action {
script_utf8: "printf hello".into(),
arguments: vec![],
expected_stdout: Some("hello".into()),
windows_execution_profile: None,
}
}
fn success() -> ReconciledOutcome {
+143 -13
View File
@@ -2,7 +2,7 @@
//! consumption are supplied by the shared core and the runtime, never bypassed.
use anyhow::{Result, ensure};
use rmm_agent_core::auth::Outcome;
use rmm_domain::jobs::{Action, JobPayload, hash};
use rmm_domain::jobs::{Action, JobPayload, WindowsExecutionProfile, hash};
use std::{
ffi::OsString,
fs::{File, OpenOptions},
@@ -11,6 +11,41 @@ use std::{
path::{Path, PathBuf},
sync::atomic::AtomicBool,
};
/// Implemented contract name only. Runtime publication still requires its own
/// native clock/boot/job qualification; this constant grants no capability.
pub const REMOTE_SIGNED_PROFILE_CAPABILITY: &str = "script.powershell.process_remote_signed/1";
fn script_arguments(job: &JobPayload, path: &Path) -> Result<Vec<OsString>> {
let Action::RunScript {
interpreter,
arguments,
windows_execution_profile,
..
} = &job.action
else {
anyhow::bail!("SCRIPT_REQUIRED")
};
ensure!(
job.execution_identity == "agent_service"
&& interpreter == "powershell"
&& job.action.validate(),
"WINDOWS_SCRIPT_PROFILE_BINDING"
);
let mut args: Vec<OsString> = ["-NoLogo", "-NoProfile", "-NonInteractive"]
.into_iter()
.map(OsString::from)
.collect();
if let Some(WindowsExecutionProfile::PowerShell51RemoteSigned) = windows_execution_profile {
args.extend([
OsString::from("-ExecutionPolicy"),
OsString::from("RemoteSigned"),
]);
}
args.push(OsString::from("-File"));
args.push(path.as_os_str().into());
args.extend(arguments.iter().map(OsString::from));
Ok(args)
}
use windows_sys::Win32::{
Storage::FileSystem::{
FILE_ATTRIBUTE_REPARSE_POINT, FILE_FLAG_OPEN_REPARSE_POINT, FILE_SHARE_READ,
@@ -47,6 +82,7 @@ pub struct Script {
_file: File,
cwd: PathBuf,
arguments: Vec<OsString>,
profile: Option<WindowsExecutionProfile>,
}
impl Script {
/// Preparation creates only a protected copy of approved bytes, no child.
@@ -56,7 +92,7 @@ impl Script {
let Action::RunScript {
interpreter,
script_utf8,
arguments,
windows_execution_profile,
..
} = &job.action
else {
@@ -95,18 +131,14 @@ impl Script {
hash(&std::fs::read(&path)?) == hash(script_utf8.as_bytes()),
"SCRIPT_BYTES_CHANGED"
);
let mut args: Vec<OsString> = ["-NoLogo", "-NoProfile", "-NonInteractive", "-File"]
.into_iter()
.map(OsString::from)
.collect();
args.push(path.clone().into_os_string());
args.extend(arguments.iter().map(OsString::from));
let args = script_arguments(job, &path)?;
Ok(Self {
executable: powershell()?,
path,
_file: file,
cwd: directory.to_path_buf(),
arguments: args,
profile: *windows_execution_profile,
})
}
pub fn run(self, job: &JobPayload, cancel: &AtomicBool) -> Result<Outcome> {
@@ -115,6 +147,7 @@ impl Script {
let Action::RunScript {
script_utf8,
expected_stdout,
windows_execution_profile,
..
} = &job.action
else {
@@ -124,6 +157,11 @@ impl Script {
std::fs::read(&self.path)? == script_utf8.as_bytes(),
"SCRIPT_BYTES_CHANGED"
);
ensure!(
self.profile == *windows_execution_profile
&& self.arguments == script_arguments(job, &self.path)?,
"WINDOWS_SCRIPT_PROFILE_CHANGED"
);
let output = crate::process::run(
&self.executable,
&self.arguments,
@@ -159,6 +197,17 @@ impl Script {
} else {
""
};
let mut evidence = serde_json::json!({"postconditions_passed":success,"interpreter":"powershell",
"script_sha256":hash(script_utf8.as_bytes()),"execution_sid":"S-1-5-19",
"output_encoding":"raw_native_bytes","comparison":"exact_utf8_bytes",
"execution_policy":"inherited","process_tree_bounded":true,
"cancel_requested":output.cancelled,"termination_does_not_prove_absence_of_effects":output.interrupted});
if self.profile.is_some() {
evidence["windows_execution_profile"] = serde_json::to_value(self.profile)?;
evidence["execution_policy"] = serde_json::json!("process_remote_signed_requested");
evidence["execution_policy_requested"] = serde_json::json!("RemoteSigned");
evidence["execution_policy_scope"] = serde_json::json!("process");
}
Ok(Outcome {
state: state.into(),
stdout: output.stdout,
@@ -167,11 +216,7 @@ impl Script {
output_truncated: output.truncated,
reboot_required: false,
error_code: code.into(),
evidence: serde_json::json!({"postconditions_passed":success,"interpreter":"powershell",
"script_sha256":hash(script_utf8.as_bytes()),"execution_sid":"S-1-5-19",
"output_encoding":"raw_native_bytes","comparison":"exact_utf8_bytes",
"execution_policy":"inherited","process_tree_bounded":true,
"cancel_requested":output.cancelled,"termination_does_not_prove_absence_of_effects":output.interrupted}),
evidence,
})
}
}
@@ -200,3 +245,88 @@ pub fn inventory(job: &JobPayload) -> Result<Outcome> {
"observed_at":chrono::Utc::now(),"completeness":"partial","execution_sid":"S-1-5-19"}),
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn powershell_policy_is_an_exact_job_profile_before_file_not_a_mutable_default() {
let id = uuid::Uuid::new_v4();
let now = chrono::Utc::now();
let mut job = JobPayload {
schema_version: 1,
tenant_id: id,
asset_id: id,
agent_id: id,
enrollment_generation: 1,
assignment_version: 1,
job_id: id,
attempt_id: id,
action: Action::RunScript {
interpreter: "powershell".into(),
script_utf8: "Write-Output 'fixed'\r\n".into(),
arguments: vec!["-ExecutionPolicy".into(), "Bypass".into()],
expected_stdout: None,
windows_execution_profile: None,
},
execution_identity: "agent_service".into(),
not_before: now,
start_before: now + chrono::Duration::seconds(60),
max_runtime_seconds: 30,
max_output_bytes: 4096,
};
let path = Path::new(r"C:\fixed state\approved.ps1");
let inherited = script_arguments(&job, path).unwrap();
assert_eq!(
inherited,
vec![
"-NoLogo",
"-NoProfile",
"-NonInteractive",
"-File",
r"C:\fixed state\approved.ps1",
"-ExecutionPolicy",
"Bypass"
]
.into_iter()
.map(OsString::from)
.collect::<Vec<_>>()
);
if let Action::RunScript {
windows_execution_profile,
..
} = &mut job.action
{
*windows_execution_profile = Some(WindowsExecutionProfile::PowerShell51RemoteSigned);
}
let args = script_arguments(&job, path).unwrap();
assert_eq!(
args[..6],
[
"-NoLogo",
"-NoProfile",
"-NonInteractive",
"-ExecutionPolicy",
"RemoteSigned",
"-File"
]
.map(OsString::from)
);
assert_eq!(args[6], path.as_os_str()); // approved arguments remain AFTER -File
assert_ne!(inherited, args);
let mut unknown = serde_json::to_value(&job.action).unwrap();
unknown["windows_execution_profile"] = serde_json::json!("Bypass");
assert!(serde_json::from_value::<Action>(unknown).is_err());
for identity in ["root", "system"] {
job.execution_identity = identity.into();
assert!(script_arguments(&job, path).is_err());
}
job.execution_identity = "agent_service".into();
for other in ["posix_sh", "bash", "pwsh"] {
if let Action::RunScript { interpreter, .. } = &mut job.action {
*interpreter = other.into();
}
assert!(script_arguments(&job, path).is_err());
}
}
}
+2
View File
@@ -684,6 +684,8 @@ impl Agent {
{
caps.extend(["rmm.sync.v1", "refresh_inventory"].map(str::to_string));
if rmm_agent_windows::actions::powershell().is_ok() {
// The process_remote_signed profile is implemented but remains
// unpublished until its separate native qualification passes.
caps.extend(["run_script", "script.powershell/1"].map(str::to_string));
}
}
+1
View File
@@ -353,6 +353,7 @@ mod tests {
script_utf8: "true".into(),
arguments: vec![],
expected_stdout: None,
windows_execution_profile: None,
},
execution_identity: "root".into(),
not_before: now,
+1
View File
@@ -50,6 +50,7 @@ fn new_process_persists_interruption_before_helper_io_without_unlock_or_repeat()
script_utf8: "printf 'fixture only; never executed\\n'".into(),
arguments: vec![],
expected_stdout: Some("fixture only; never executed\n".into()),
windows_execution_profile: None,
},
execution_identity: "root".into(),
not_before: now,
+1
View File
@@ -594,6 +594,7 @@ fn script() -> Action {
script_utf8: "printf hello".into(),
arguments: vec![],
expected_stdout: Some("hello".into()),
windows_execution_profile: None,
}
}
fn success() -> ReconciledOutcome {
+131 -4
View File
@@ -1,5 +1,6 @@
//! Version 1 codec: UTF-8 compact serde JSON of these structs, declaration field
//! order, explicit null options, ordered vectors, UTC RFC3339 timestamps. Hash the
//! 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};
@@ -13,6 +14,33 @@ pub fn encode<T: Serialize>(value: &T) -> Result<Vec<u8>, serde_json::Error> {
serde_json::to_vec(value)
}
/// 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<Option<WindowsExecutionProfile>, 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"],
)),
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)]
pub enum Action {
@@ -21,6 +49,12 @@ pub enum Action {
script_utf8: String,
arguments: Vec<String>,
expected_stdout: Option<String>,
#[serde(
default,
deserialize_with = "deserialize_windows_execution_profile",
skip_serializing_if = "Option::is_none"
)]
windows_execution_profile: Option<WindowsExecutionProfile>,
},
RefreshInventory {
scope: String,
@@ -99,8 +133,10 @@ impl Action {
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}'))
@@ -219,15 +255,25 @@ impl Action {
return false;
}
match self {
Self::RunScript { interpreter, .. } if interpreter == "powershell" => {
Self::RunScript {
interpreter,
windows_execution_profile,
..
} if interpreter == "powershell" => {
identity == "agent_service"
&& 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 { .. } => {
self.script_platform() == Some("linux")
Self::RunScript {
windows_execution_profile,
..
} => {
windows_execution_profile.is_none()
&& self.script_platform() == Some("linux")
&& has("linux.base/1")
&& !has("windows.base/1")
}
@@ -496,6 +542,7 @@ mod tests {
script_utf8: "Write-Output 'hi'\r\n".into(),
arguments: vec![],
expected_stdout: None,
windows_execution_profile: None,
};
let mut all = caps;
all.extend(["run_script".into(), "script.powershell/1".into()]);
@@ -505,6 +552,7 @@ mod tests {
script_utf8: "printf hi\n".into(),
arguments: vec![],
expected_stdout: None,
windows_execution_profile: None,
};
let reboot = Action::Reboot {
reason: "fixed test".into(),
@@ -526,6 +574,7 @@ mod tests {
script_utf8: "Write-Output 'Hello'\r\n".into(),
arguments: vec![],
expected_stdout: Some("Hello\r\n".into()),
windows_execution_profile: None,
};
let caps: Vec<String> = [
"windows.base/1",
@@ -601,6 +650,7 @@ mod tests {
script_utf8: "echo hi\n".into(),
arguments: vec![],
expected_stdout: None,
windows_execution_profile: None,
};
assert_eq!(
String::from_utf8(encode(&a).unwrap()).unwrap(),
@@ -613,6 +663,83 @@ mod tests {
);
}
#[test]
fn windows_remote_signed_profile_is_optional_exact_and_capability_bound() {
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::<Action>(&encoded).unwrap(), action);
let caps: Vec<String> = [
"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::<Action>(bad).is_err(), "{profile}");
// An opt-in profile is also never metadata on another action.
assert!(
serde_json::from_value::<Action>(serde_json::json!({
"action":"refresh_inventory", "scope":"windows.base",
"windows_execution_profile":profile
}))
.is_err()
);
}
}
#[test]
fn no_terminal_replay_or_unknown_restart() {
assert!(!JobState::Succeeded.allows(JobState::Running));
assert!(!JobState::Unknown.allows(JobState::Running));
@@ -481,6 +481,7 @@ fn signed_request() -> (
script_utf8: "true".into(),
arguments: vec![],
expected_stdout: None,
windows_execution_profile: None,
},
execution_identity: "root".into(),
not_before: now - chrono::Duration::seconds(1),
+1
View File
@@ -130,6 +130,7 @@ pub fn script(job: &JobPayload) -> Result<Outcome> {
script_utf8,
arguments,
expected_stdout,
windows_execution_profile: None,
} = &job.action
else {
anyhow::bail!("NOT_SCRIPT")
+1
View File
@@ -750,6 +750,7 @@ mod tests {
script_utf8: "true".into(),
arguments: vec![],
expected_stdout: None,
windows_execution_profile: None,
},
execution_identity: "agent_service".into(),
not_before: now,
+1
View File
@@ -33,6 +33,7 @@ fn fixture() -> (
script_utf8: "printf 'Hello World\\n'".into(),
arguments: vec![],
expected_stdout: Some("Hello World\n".into()),
windows_execution_profile: None,
},
execution_identity: "agent_service".into(),
not_before: now - chrono::Duration::seconds(60),
@@ -432,6 +432,7 @@ fn script() -> Action {
script_utf8: "printf hello".into(),
arguments: vec![],
expected_stdout: Some("hello".into()),
windows_execution_profile: None,
}
}
fn success() -> ReconciledOutcome {
+1
View File
@@ -518,6 +518,7 @@ mod tests {
script_utf8: "printf hello\\n".into(),
arguments: vec![],
expected_stdout: None,
windows_execution_profile: None,
},
execution_identity: "agent_service".into(),
not_before: c.issued_at,
+69
View File
@@ -191,6 +191,7 @@ pub async fn event(
ensure!(r.stdout == expected.as_bytes(), "expected output mismatch");
}
}
script_profile_evidence(&payload.action, &evidence)?;
if matches!(payload.action, Action::Reboot { .. }) {
crate::synchronization::verify_reboot_success(
tx, tenant, agent, e, &payload, r, &evidence,
@@ -224,6 +225,74 @@ pub async fn event(
.await?;
Ok(())
}
// The profile records the requested process option, never an effective GPO policy.
fn script_profile_evidence(action: &Action, evidence: &Value) -> Result<()> {
if let Action::RunScript {
script_utf8,
windows_execution_profile: Some(WindowsExecutionProfile::PowerShell51RemoteSigned),
..
} = action
{
ensure!(
evidence.get("windows_execution_profile")
== Some(&json!("powershell_51_remote_signed"))
&& evidence.get("execution_policy")
== Some(&json!("process_remote_signed_requested"))
&& evidence.get("execution_policy_requested") == Some(&json!("RemoteSigned"))
&& evidence.get("execution_policy_scope") == Some(&json!("process"))
&& evidence.get("script_sha256") == Some(&json!(hash(script_utf8.as_bytes()))),
"requested Windows process profile evidence mismatch"
);
}
Ok(())
}
#[cfg(test)]
mod script_profile_tests {
use super::*;
#[test]
fn requested_profile_success_evidence_is_exact_without_effective_policy_claim() {
let mut action = Action::RunScript {
interpreter: "powershell".into(),
script_utf8: "Write-Output 'hi'\r\n".into(),
arguments: vec![],
expected_stdout: None,
windows_execution_profile: Some(WindowsExecutionProfile::PowerShell51RemoteSigned),
};
let evidence = json!({"windows_execution_profile":"powershell_51_remote_signed",
"execution_policy":"process_remote_signed_requested", "execution_policy_requested":"RemoteSigned",
"execution_policy_scope":"process", "script_sha256":hash(b"Write-Output 'hi'\r\n")});
script_profile_evidence(&action, &evidence).unwrap();
for field in [
"windows_execution_profile",
"execution_policy",
"execution_policy_requested",
"execution_policy_scope",
"script_sha256",
] {
let mut changed = evidence.clone();
changed.as_object_mut().unwrap().remove(field);
assert!(
script_profile_evidence(&action, &changed).is_err(),
"{field}"
);
changed[field] = json!("different");
assert!(
script_profile_evidence(&action, &changed).is_err(),
"{field}"
);
}
if let Action::RunScript {
windows_execution_profile,
..
} = &mut action
{
*windows_execution_profile = None;
}
script_profile_evidence(&action, &json!({})).unwrap();
}
}
async fn locked_job(
tx: &mut Transaction<'_, Postgres>,
agent: Uuid,
+154 -1
View File
@@ -151,6 +151,12 @@ pub struct Variant {
interpreter: String,
encoding: String,
script_utf8: String,
#[serde(
default,
deserialize_with = "rmm_domain::jobs::deserialize_windows_execution_profile",
skip_serializing_if = "Option::is_none"
)]
windows_execution_profile: Option<WindowsExecutionProfile>,
}
#[derive(Clone, Deserialize, Serialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
@@ -213,6 +219,7 @@ impl PlanRequest {
script_utf8: v.script_utf8.clone(),
arguments: p.arguments.clone().unwrap_or_default(),
expected_stdout: p.expected_stdout.clone(),
windows_execution_profile: v.windows_execution_profile,
}
}
"refresh_inventory" => Action::RefreshInventory {
@@ -310,6 +317,7 @@ fn validate_variants(variants: &[Variant]) -> Result<()> {
script_utf8: v.script_utf8.clone(),
arguments: vec![],
expected_stdout: None,
windows_execution_profile: v.windows_execution_profile,
};
if v.encoding != "utf-8"
|| action.script_platform() != Some(v.os_family.as_str())
@@ -336,12 +344,21 @@ fn target_action(input: &PlanInput, caps: &[String]) -> Result<Action> {
script_utf8,
arguments,
expected_stdout,
windows_execution_profile,
} = &input.action
else {
return Err(fail("VALIDATION_ERROR"));
};
let first = &input.script_variants[0];
if interpreter != &first.interpreter || script_utf8 != &first.script_utf8 {
if interpreter != &first.interpreter
|| script_utf8 != &first.script_utf8
|| windows_execution_profile != &first.windows_execution_profile
|| (input.execution_identity != "agent_service"
&& input
.script_variants
.iter()
.any(|v| v.windows_execution_profile.is_some()))
{
return Err(fail("VALIDATION_ERROR"));
}
let platform = match (
@@ -362,6 +379,7 @@ fn target_action(input: &PlanInput, caps: &[String]) -> Result<Action> {
script_utf8: v.script_utf8.clone(),
arguments: arguments.clone(),
expected_stdout: expected_stdout.clone(),
windows_execution_profile: v.windows_execution_profile,
})
}
async fn policy(tx: &mut Transaction<'_, Postgres>) -> Result<()> {
@@ -1035,6 +1053,72 @@ mod windows_contract_tests {
i.script_variants.remove(1);
assert!(target_action(&i, &["windows.base/1".into()]).is_err());
}
#[test]
fn remote_signed_fixed_variants_bind_profile_without_linux_inheritance() {
let mut i = input();
let legacy_linux = encode(&i.action).unwrap();
i.script_variants[1].windows_execution_profile =
Some(WindowsExecutionProfile::PowerShell51RemoteSigned);
assert_eq!(
encode(&target_action(&i, &["linux.base/1".into()]).unwrap()).unwrap(),
legacy_linux
);
let windows = target_action(&i, &["windows.base/1".into()]).unwrap();
assert!(matches!(
windows,
Action::RunScript {
windows_execution_profile: Some(WindowsExecutionProfile::PowerShell51RemoteSigned),
..
}
));
assert!(!windows.available_for(
"agent_service",
&[
"windows.base/1".into(),
"rmm.sync.v1".into(),
"run_script".into(),
"script.powershell/1".into()
]
));
for identity in ["root", "system"] {
i.execution_identity = identity.into();
assert!(target_action(&i, &["linux.base/1".into()]).is_err());
}
i.execution_identity = "agent_service".into();
// Even the first Action must match the optional profile byte-for-byte.
i.script_variants.reverse();
i.action = windows;
assert!(target_action(&i, &["windows.base/1".into()]).is_ok());
if let Action::RunScript {
windows_execution_profile,
..
} = &mut i.action
{
*windows_execution_profile = None;
}
assert!(target_action(&i, &["windows.base/1".into()]).is_err());
i.script_variants[1].windows_execution_profile =
Some(WindowsExecutionProfile::PowerShell51RemoteSigned);
assert!(validate_variants(&i.script_variants).is_err());
let legacy = json!({"os_family":"windows", "interpreter":"powershell", "encoding":"utf-8", "script_utf8":"hi"});
let inherited: Variant = serde_json::from_value(legacy.clone()).unwrap();
assert!(inherited.windows_execution_profile.is_none());
assert_eq!(serde_json::to_value(inherited).unwrap(), legacy);
for profile in [
Value::Null,
json!(false),
json!(1),
json!([]),
json!({}),
json!({"powershell_51_remote_signed":null}),
json!("bypass"),
json!("powershell_7_remote_signed"),
] {
assert!(serde_json::from_value::<Variant>(json!({"os_family":"windows", "interpreter":"powershell", "encoding":"utf-8", "script_utf8":"hi", "windows_execution_profile":profile})).is_err());
assert!(serde_json::from_value::<WebParameters>(json!({"execution_identity":"agent_service", "timeout_seconds":60, "max_output_bytes":4096, "windows_execution_profile":profile})).is_err());
}
assert!(serde_json::from_value::<WebParameters>(json!({"execution_identity":"agent_service", "timeout_seconds":60, "max_output_bytes":4096, "windows_execution_profile":"powershell_51_remote_signed"})).is_err());
}
#[tokio::test]
#[ignore = "requires dedicated isolated PostgreSQL; tests/windows_plan_database.py"]
async fn windows_plan_caps_persisted_database() {
@@ -1175,6 +1259,75 @@ mod windows_contract_tests {
"PLAN_HASH_MISMATCH"
);
tx.rollback().await.unwrap();
// A process-profile plan needs the additional current capability. Its
// presence is rechecked at submit/approval just like interpreter support.
let mut profiled = request.clone();
profiled.script_variants[1].windows_execution_profile =
Some(WindowsExecutionProfile::PowerShell51RemoteSigned);
assert_eq!(
plan(&state, &principal, tenant, profiled.clone())
.await
.unwrap_err()
.1,
"UNSUPPORTED_CAPABILITY"
);
let mut profile_caps = windows_caps.as_array().unwrap().clone();
profile_caps.push(json!("script.powershell.process_remote_signed/1"));
sqlx::query("UPDATE agent_installations SET capabilities=$2 WHERE agent_id=$1")
.bind(agents[1])
.bind(json!(profile_caps))
.execute(&admin)
.await
.unwrap();
let view = plan(&state, &principal, tenant, profiled).await.unwrap();
let profile_id = Uuid::parse_str(view["plan_id"].as_str().unwrap()).unwrap();
let bytes: Vec<u8> =
sqlx::query_scalar("SELECT payload FROM operation_plans WHERE plan_id=$1")
.bind(profile_id)
.fetch_one(&admin)
.await
.unwrap();
let profile_bound: PlanPayload = serde_json::from_slice(&bytes).unwrap();
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
.await
.unwrap();
recheck(&mut tx, &profile_bound).await.unwrap();
tx.rollback().await.unwrap();
let mut changed = profile_bound.clone();
let windows_job = changed
.jobs
.iter_mut()
.find(|j| j.payload.asset_id == assets[1])
.unwrap();
if let Action::RunScript {
windows_execution_profile,
..
} = &mut windows_job.payload.action
{
*windows_execution_profile = None;
}
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
.await
.unwrap();
assert_eq!(
recheck(&mut tx, &changed).await.unwrap_err().1,
"PLAN_HASH_MISMATCH"
);
tx.rollback().await.unwrap();
sqlx::query("UPDATE agent_installations SET capabilities=$2 WHERE agent_id=$1")
.bind(agents[1])
.bind(&windows_caps)
.execute(&admin)
.await
.unwrap();
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
.await
.unwrap();
assert_eq!(
recheck(&mut tx, &profile_bound).await.unwrap_err().1,
"UNSUPPORTED_CAPABILITY"
);
tx.rollback().await.unwrap();
request.script_variants.clear();
assert_eq!(
plan(&state, &principal, tenant, request.clone())
+1
View File
@@ -356,6 +356,7 @@ mod tests {
script_utf8: "true\n".into(),
arguments: vec![],
expected_stdout: None,
windows_execution_profile: None,
},
execution_identity: "root".into(),
not_before: now,
+1
View File
@@ -393,6 +393,7 @@ mod tests {
script_utf8: "Write-Output 'hello'".into(),
arguments: vec![],
expected_stdout: None,
windows_execution_profile: None,
};
assert!(!policy.permits("selected", &job, &caps, now));
job.action = Action::SetServiceState {