Plan device actions exclusively as approved scripts and provide reboot library revisions
This commit is contained in:
@@ -588,11 +588,14 @@ async fn installed(
|
||||
) -> Result<Response, Error> {
|
||||
let (tenant, agent) = device(&s, peer, &headers).await?;
|
||||
let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?;
|
||||
let row = sqlx::query("SELECT reported_agent_version,connection_generation,last_contact_at FROM agent_installations WHERE agent_id=$1 AND revoked_at IS NULL").bind(agent).fetch_one(&mut *tx).await?;
|
||||
let row = sqlx::query("SELECT asset_id,enrollment_generation,assignment_version,capabilities,reported_agent_version,connection_generation,last_contact_at FROM agent_installations WHERE agent_id=$1 AND revoked_at IS NULL").bind(agent).fetch_one(&mut *tx).await?;
|
||||
tx.commit().await?;
|
||||
Ok((
|
||||
[("cache-control", "private, no-store")],
|
||||
Json(json!({"agent_id":agent,
|
||||
Json(json!({"tenant_id":tenant,"asset_id":row.get::<Uuid,_>("asset_id"),"agent_id":agent,
|
||||
"enrollment_generation":row.get::<i64,_>("enrollment_generation"),
|
||||
"assignment_version":row.get::<i64,_>("assignment_version"),
|
||||
"capabilities":row.get::<Value,_>("capabilities"),
|
||||
"agent_version":row.get::<Option<String>,_>("reported_agent_version"),
|
||||
"connection_generation":row.get::<i64,_>("connection_generation"),
|
||||
"last_contact_at":row.get::<Option<chrono::DateTime<chrono::Utc>>,_>("last_contact_at")})),
|
||||
@@ -1256,19 +1259,17 @@ mod tests {
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn plan_request_accepts_release_id_but_never_user_supplied_local_bindings() {
|
||||
fn update_releases_are_not_device_job_plans() {
|
||||
let mut value = json!({"tenant_id":"11111111-1111-4111-8111-111111111111","action":"update_agent","targets":{"asset_ids":["11111111-1111-4111-8111-111111111112"]},
|
||||
"parameters":{"release_id":"11111111-1111-4111-8111-111111111113","execution_identity":"root","timeout_seconds":600,"max_output_bytes":65536},
|
||||
"schedule":{"not_before":"2030-01-01T12:00:00Z","start_before":"2030-01-01T12:10:00Z","offline_policy":"wait_until_deadline"},"rollout":{"max_parallel":1,"halt_after_failures":1},"reason":"codec only"});
|
||||
let parsed: crate::jobs::PlanRequest = serde_json::from_value(value.clone()).unwrap();
|
||||
assert!(matches!(parsed, crate::jobs::PlanRequest::AgentUpdate(_)));
|
||||
// The old synchronous resolver cannot manufacture local state.
|
||||
assert!(
|
||||
parsed
|
||||
.resolve(Uuid::parse_str(value["tenant_id"].as_str().unwrap()).unwrap())
|
||||
.is_err()
|
||||
);
|
||||
value["parameters"]["predecessor"] = json!({"installed_record_sha256":"00".repeat(32)});
|
||||
assert!(serde_json::from_value::<crate::jobs::PlanRequest>(value).is_err());
|
||||
let tenant = Uuid::parse_str(value["tenant_id"].as_str().unwrap()).unwrap();
|
||||
for local_binding in [false, true] {
|
||||
if local_binding {
|
||||
value["parameters"]["predecessor"] = json!({"installed_record_sha256":"00".repeat(32)});
|
||||
}
|
||||
let parsed: crate::jobs::PlanRequest = serde_json::from_value(value.clone()).unwrap();
|
||||
assert_eq!(parsed.resolve(tenant).err().unwrap().1, "SCRIPT_ACTION_REQUIRED");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -569,10 +569,12 @@ def run_agent():
|
||||
RMM_RELEASE_LOCK=str(ROOT / 'release.lock'),
|
||||
RMM_INSTALLED_RELEASE_VERSION=read(ROOT / 'current/manifest.json')['version'])
|
||||
folder = active_folder()
|
||||
os.environ.pop('RMM_SCRIPT_HELPER_RELEASE', None)
|
||||
if (folder / 'script-pin.json').is_file() and helper_state() in ('enabled', 'enabled-runtime'):
|
||||
os.environ.update(RMM_FULL_MAINTENANCE_HELPER_SOCKET=str(HELPER_SOCKET),
|
||||
RMM_FULL_MAINTENANCE_POLICY_FILE=str(folder / 'script-pin.json'),
|
||||
RMM_SCRIPT_HELPER_RELEASE=folder.name)
|
||||
pins = {'RMM_FULL_MAINTENANCE_HELPER_SOCKET': str(HELPER_SOCKET),
|
||||
'RMM_FULL_MAINTENANCE_POLICY_FILE': str(folder / 'script-pin.json')}
|
||||
if all(os.environ.get(name, value) == value for name, value in pins.items()):
|
||||
os.environ.update(pins, RMM_SCRIPT_HELPER_RELEASE=folder.name)
|
||||
exe = str(folder / 'agent')
|
||||
os.execv(exe, [exe])
|
||||
|
||||
@@ -681,7 +683,7 @@ def main():
|
||||
elif args.action == 'run-helper':
|
||||
require(os.geteuid() == 0, 'privileged script helper service required')
|
||||
folder = active_folder()
|
||||
os.environ['RMM_HELPER_CONFIG'] = str(folder / 'script-helper.json')
|
||||
os.environ.setdefault('RMM_HELPER_CONFIG', str(folder / 'script-helper.json'))
|
||||
os.execv(folder / 'helper', [str(folder / 'helper')])
|
||||
elif args.action == 'run-agent':
|
||||
run_agent()
|
||||
|
||||
+186
-341
@@ -128,42 +128,38 @@ pub struct PlanInput {
|
||||
#[serde(default)]
|
||||
pub artifact_ids: Vec<Uuid>,
|
||||
}
|
||||
#[derive(Clone, Deserialize, schemars::JsonSchema)]
|
||||
#[derive(Clone, Deserialize)]
|
||||
#[serde(untagged)]
|
||||
pub enum PlanRequest {
|
||||
AgentUpdate(Box<AgentUpdatePlanInput>),
|
||||
Typed(Box<PlanInput>),
|
||||
Web(Box<WebPlanInput>),
|
||||
// Earlier SDKs sent the fixed script action instead of platform variants.
|
||||
Typed(Box<PlanInput>),
|
||||
Retired {
|
||||
tenant_id: Uuid,
|
||||
#[serde(rename = "action", deserialize_with = "retired_action")]
|
||||
_action: (),
|
||||
},
|
||||
}
|
||||
|
||||
fn retired_action<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<(), D::Error> {
|
||||
if String::deserialize(d)? == "run_script" {
|
||||
return Err(serde::de::Error::custom("invalid run_script parameters"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Clone, Deserialize, schemars::JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct AgentUpdatePlanInput {
|
||||
tenant_id: Uuid,
|
||||
action: AgentUpdateRequestAction,
|
||||
targets: Targets,
|
||||
parameters: AgentUpdateParameters,
|
||||
schedule: WebSchedule,
|
||||
rollout: Rollout,
|
||||
reason: String,
|
||||
}
|
||||
#[derive(Clone, Deserialize, schemars::JsonSchema)]
|
||||
pub enum AgentUpdateRequestAction {
|
||||
#[serde(rename = "update_agent")]
|
||||
UpdateAgent,
|
||||
}
|
||||
#[derive(Clone, Deserialize, schemars::JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct AgentUpdateParameters {
|
||||
release_id: Uuid,
|
||||
execution_identity: String,
|
||||
timeout_seconds: u32,
|
||||
max_output_bytes: u32,
|
||||
enum ScriptActionName {
|
||||
#[serde(rename = "run_script")]
|
||||
RunScript,
|
||||
}
|
||||
|
||||
#[derive(Clone, Deserialize, schemars::JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct WebPlanInput {
|
||||
tenant_id: Uuid,
|
||||
action: String,
|
||||
#[serde(rename = "action")]
|
||||
_action: ScriptActionName,
|
||||
targets: Targets,
|
||||
parameters: WebParameters,
|
||||
schedule: WebSchedule,
|
||||
@@ -207,45 +203,25 @@ struct WebParameters {
|
||||
execution_identity: String,
|
||||
timeout_seconds: u32,
|
||||
max_output_bytes: u32,
|
||||
variants: Option<Vec<Variant>>,
|
||||
variants: Vec<Variant>,
|
||||
arguments: Option<Vec<String>>,
|
||||
expected_stdout: Option<String>,
|
||||
scope: Option<String>,
|
||||
unit: Option<String>,
|
||||
state: Option<String>,
|
||||
since: Option<DateTime<Utc>>,
|
||||
until: Option<DateTime<Utc>>,
|
||||
max_lines: Option<u32>,
|
||||
provider: Option<String>,
|
||||
package: Option<String>,
|
||||
version: Option<String>,
|
||||
architecture: Option<String>,
|
||||
recipe_version: Option<String>,
|
||||
recipe_id: Option<String>,
|
||||
apt_manifest: Option<rmm_domain::apt_transaction::AptExecutionManifest>,
|
||||
#[serde(
|
||||
default,
|
||||
deserialize_with = "rmm_domain::jobs::deserialize_windows_msi_manifest"
|
||||
)]
|
||||
#[schemars(with = "rmm_domain::windows_execution::ResolvedWindowsMsi")]
|
||||
windows_msi_manifest: Option<Box<rmm_domain::windows_execution::ResolvedWindowsMsi>>,
|
||||
installation_context: Option<String>,
|
||||
packages: Option<Vec<String>>,
|
||||
reboot_policy: Option<String>,
|
||||
reason: Option<String>,
|
||||
dependency_group: Option<String>,
|
||||
reconnect_timeout_seconds: Option<u32>,
|
||||
}
|
||||
|
||||
impl PlanRequest {
|
||||
pub fn resolve(self, tenant: Uuid) -> Result<PlanInput> {
|
||||
let w = match self {
|
||||
Self::AgentUpdate(_) => {
|
||||
return Err(Error(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"AGENT_UPDATE_RELEASE_ID_REQUIRED",
|
||||
));
|
||||
Self::Typed(input) => {
|
||||
require_script(&input.action)?;
|
||||
return Ok(*input);
|
||||
}
|
||||
Self::Retired { tenant_id, .. } => {
|
||||
return Err(if tenant_id == tenant {
|
||||
fail("SCRIPT_ACTION_REQUIRED")
|
||||
} else {
|
||||
missing()
|
||||
});
|
||||
}
|
||||
Self::Typed(t) => return Ok(*t),
|
||||
Self::Web(w) => *w,
|
||||
};
|
||||
if w.tenant_id != tenant {
|
||||
@@ -254,105 +230,21 @@ impl PlanRequest {
|
||||
if w.schedule.offline_policy != "wait_until_deadline" {
|
||||
return Err(fail("POLICY_DENIED"));
|
||||
}
|
||||
let parameters = serde_json::to_value(&w.parameters).map_err(Error::from)?;
|
||||
if w.action != "run_script" && w.parameters.variants.is_some() {
|
||||
return Err(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"));
|
||||
}
|
||||
let p = w.parameters;
|
||||
if p.windows_msi_manifest.is_some() && w.action != "ensure_package" {
|
||||
return Err(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"));
|
||||
}
|
||||
let required =
|
||||
|value: Option<String>| value.ok_or(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"));
|
||||
let action = match w.action.as_str() {
|
||||
"run_script" => {
|
||||
let variants = p
|
||||
.variants
|
||||
.as_ref()
|
||||
.ok_or(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"))?;
|
||||
validate_variants(variants)?;
|
||||
let v = &variants[0];
|
||||
Action::RunScript {
|
||||
interpreter: v.interpreter.clone(),
|
||||
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,
|
||||
privileged_script_profile: p.privileged_script_profile,
|
||||
}
|
||||
}
|
||||
"refresh_inventory" => Action::RefreshInventory {
|
||||
scope: required(p.scope)?,
|
||||
},
|
||||
"query_logs" => Action::QueryLogs {
|
||||
unit: required(p.unit)?,
|
||||
since: p
|
||||
.since
|
||||
.ok_or(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"))?,
|
||||
until: p
|
||||
.until
|
||||
.ok_or(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"))?,
|
||||
max_lines: p
|
||||
.max_lines
|
||||
.ok_or(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"))?,
|
||||
},
|
||||
"set_service_state" => Action::SetServiceState {
|
||||
unit: required(p.unit)?,
|
||||
state: required(p.state)?,
|
||||
},
|
||||
"ensure_package" => Action::EnsurePackage {
|
||||
provider: required(p.provider)?,
|
||||
package: required(p.package)?,
|
||||
version: required(p.version)?,
|
||||
architecture: required(p.architecture)?,
|
||||
recipe_version: required(p.recipe_version)?,
|
||||
installation_context: required(p.installation_context)?,
|
||||
recipe_id: p.recipe_id,
|
||||
apt_manifest: p.apt_manifest,
|
||||
windows_msi_manifest: p.windows_msi_manifest,
|
||||
},
|
||||
"apply_updates" => Action::ApplyUpdates {
|
||||
provider: required(p.provider)?,
|
||||
packages: p
|
||||
.packages
|
||||
.ok_or(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"))?,
|
||||
reboot_policy: required(p.reboot_policy)?,
|
||||
apt_manifest: p.apt_manifest,
|
||||
},
|
||||
"apt_native_acceptance" => Action::AptNativeAcceptance {
|
||||
recipe_id: required(p.recipe_id)?,
|
||||
recipe_version: required(p.recipe_version)?,
|
||||
apt_manifest: p
|
||||
.apt_manifest
|
||||
.ok_or(Error(StatusCode::BAD_REQUEST, "APT_MANIFEST_REQUIRED"))?,
|
||||
},
|
||||
"reboot" => Action::Reboot {
|
||||
reason: required(p.reason)?,
|
||||
dependency_group: required(p.dependency_group)?,
|
||||
reconnect_timeout_seconds: p
|
||||
.reconnect_timeout_seconds
|
||||
.ok_or(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"))?,
|
||||
},
|
||||
_ => return Err(fail("UNSUPPORTED_CAPABILITY")),
|
||||
validate_variants(&p.variants)?;
|
||||
let first = &p.variants[0];
|
||||
let action = Action::RunScript {
|
||||
interpreter: first.interpreter.clone(),
|
||||
script_utf8: first.script_utf8.clone(),
|
||||
arguments: p.arguments.unwrap_or_default(),
|
||||
expected_stdout: p.expected_stdout,
|
||||
windows_execution_profile: first.windows_execution_profile,
|
||||
privileged_script_profile: p.privileged_script_profile,
|
||||
};
|
||||
// Reject irrelevant non-null fields instead of silently discarding an
|
||||
// effect that the browser displayed. Common limits bind into JobPayload.
|
||||
let action_view = serde_json::to_value(&action)?;
|
||||
for (key, value) in parameters.as_object().into_iter().flatten() {
|
||||
if !value.is_null()
|
||||
&& !matches!(
|
||||
key.as_str(),
|
||||
"execution_identity" | "timeout_seconds" | "max_output_bytes" | "variants"
|
||||
)
|
||||
&& action_view.get(key).is_none()
|
||||
{
|
||||
return Err(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"));
|
||||
}
|
||||
}
|
||||
Ok(PlanInput {
|
||||
targets: w.targets,
|
||||
action,
|
||||
script_variants: p.variants.unwrap_or_default(),
|
||||
script_variants: p.variants,
|
||||
execution_identity: p.execution_identity,
|
||||
schedule: Schedule {
|
||||
not_before: w.schedule.not_before,
|
||||
@@ -366,68 +258,25 @@ impl PlanRequest {
|
||||
})
|
||||
}
|
||||
}
|
||||
/// Both HTTP and MCP resolve update jobs only from a fixed catalog release and
|
||||
/// saved authenticated per-device observations. Caller-supplied local pins are
|
||||
/// never an alternative route to the typed immutable execution payload.
|
||||
/// HTTP and MCP prepare the same tenant-scoped, immutable script plans.
|
||||
pub async fn plan_request(
|
||||
state: &crate::State,
|
||||
p: &Principal,
|
||||
tenant: Uuid,
|
||||
request: PlanRequest,
|
||||
) -> Result<Value> {
|
||||
let PlanRequest::AgentUpdate(input) = request else {
|
||||
return plan(state, p, tenant, request.resolve(tenant)?).await;
|
||||
};
|
||||
scope(p, tenant, true)?;
|
||||
if input.tenant_id != tenant {
|
||||
return Err(missing());
|
||||
}
|
||||
if input.schedule.offline_policy != "wait_until_deadline"
|
||||
|| input.parameters.release_id.is_nil()
|
||||
|| input.targets.asset_ids.is_empty()
|
||||
|| input.targets.asset_ids.len() > 100
|
||||
{
|
||||
return Err(fail("VALIDATION_ERROR"));
|
||||
}
|
||||
let _ = &input.action;
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant).await?;
|
||||
crate::permissions::require_principal(&mut tx, p, "operations:plan").await?;
|
||||
crate::permissions::require_principal(&mut tx, p, "updates:apply").await?;
|
||||
let mut updates = std::collections::BTreeMap::new();
|
||||
for asset in &input.targets.asset_ids {
|
||||
let update =
|
||||
crate::agent_updates::resolve_target(&mut tx, *asset, input.parameters.release_id)
|
||||
.await?;
|
||||
if update.execution_identity() != Some(input.parameters.execution_identity.as_str()) {
|
||||
return Err(fail("EXECUTION_IDENTITY_DENIED"));
|
||||
}
|
||||
updates.insert(*asset, update);
|
||||
}
|
||||
tx.commit().await?;
|
||||
let first = updates
|
||||
.values()
|
||||
.next()
|
||||
.ok_or_else(|| fail("NOT_FOUND"))?
|
||||
.clone();
|
||||
let resolved = PlanInput {
|
||||
targets: input.targets,
|
||||
action: Action::UpdateAgent {
|
||||
update: Box::new(first),
|
||||
},
|
||||
script_variants: Vec::new(),
|
||||
execution_identity: input.parameters.execution_identity,
|
||||
schedule: Schedule {
|
||||
not_before: input.schedule.not_before,
|
||||
start_before: input.schedule.start_before,
|
||||
},
|
||||
max_runtime_seconds: input.parameters.timeout_seconds,
|
||||
max_output_bytes: input.parameters.max_output_bytes,
|
||||
rollout: input.rollout,
|
||||
reason: input.reason,
|
||||
artifact_ids: Vec::new(),
|
||||
};
|
||||
plan_resolved(state, p, tenant, resolved, Some(updates), None).await
|
||||
plan(state, p, tenant, request.resolve(tenant)?).await
|
||||
}
|
||||
|
||||
fn require_script(action: &Action) -> Result<()> {
|
||||
if matches!(action, Action::RunScript { .. }) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(fail("SCRIPT_ACTION_REQUIRED"))
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_variants(variants: &[Variant]) -> Result<()> {
|
||||
if variants.is_empty() || variants.len() > 2 {
|
||||
return Err(fail("AMBIGUOUS_TARGET"));
|
||||
@@ -531,25 +380,17 @@ pub async fn plan(
|
||||
tenant: Uuid,
|
||||
input: PlanInput,
|
||||
) -> Result<Value> {
|
||||
if matches!(input.action, Action::UpdateAgent { .. }) {
|
||||
return Err(Error(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"AGENT_UPDATE_RELEASE_ID_REQUIRED",
|
||||
));
|
||||
}
|
||||
plan_resolved(state, p, tenant, input, None, None).await
|
||||
plan_resolved(state, p, tenant, input, None).await
|
||||
}
|
||||
pub(crate) async fn plan_resolved(
|
||||
state: &crate::State,
|
||||
p: &Principal,
|
||||
tenant: Uuid,
|
||||
input: PlanInput,
|
||||
updates: Option<
|
||||
std::collections::BTreeMap<Uuid, rmm_domain::agent_update::ResolvedAgentUpdate>,
|
||||
>,
|
||||
script_revision: Option<ScriptRevisionReference>,
|
||||
) -> Result<Value> {
|
||||
scope(p, tenant, true)?;
|
||||
require_script(&input.action)?;
|
||||
let now = Utc::now();
|
||||
if input.targets.asset_ids.is_empty()
|
||||
|| input.targets.asset_ids.len() > 100
|
||||
@@ -574,33 +415,6 @@ pub(crate) async fn plan_resolved(
|
||||
{
|
||||
return Err(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"));
|
||||
}
|
||||
if matches!(
|
||||
input.action,
|
||||
Action::AptNativeAcceptance { .. }
|
||||
| Action::EnsurePackage {
|
||||
apt_manifest: Some(_),
|
||||
..
|
||||
}
|
||||
| Action::ApplyUpdates {
|
||||
apt_manifest: Some(_),
|
||||
..
|
||||
}
|
||||
) && input.execution_identity != "root"
|
||||
{
|
||||
return Err(Error(StatusCode::FORBIDDEN, "ROOT_IDENTITY_REQUIRED"));
|
||||
}
|
||||
if input.action.windows_msi().is_some()
|
||||
&& (input.execution_identity != "system" || !input.artifact_ids.is_empty())
|
||||
{
|
||||
return Err(Error(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"WINDOWS_MSI_EXACT_ARTIFACT_REQUIRED",
|
||||
));
|
||||
}
|
||||
// Conservative policy: reboot is always serial, no provider-triggered reboot.
|
||||
if matches!(input.action, Action::Reboot { .. }) && input.rollout.max_parallel != 1 {
|
||||
return Err(fail("POLICY_DENIED"));
|
||||
}
|
||||
let mut ids = input.targets.asset_ids.clone();
|
||||
ids.sort();
|
||||
ids.dedup();
|
||||
@@ -610,25 +424,7 @@ pub(crate) async fn plan_resolved(
|
||||
for permission in execution_permissions(&input.action, &input.execution_identity) {
|
||||
crate::permissions::require_principal(&mut tx, p, permission).await?;
|
||||
}
|
||||
let recipe_references = crate::catalog::references(&mut tx, &input.action).await?;
|
||||
let artifacts = if let Action::UpdateAgent { update } = &input.action {
|
||||
if !input.artifact_ids.is_empty() {
|
||||
return Err(fail("AGENT_UPDATE_EXACT_ARTIFACT_REQUIRED"));
|
||||
}
|
||||
crate::agent_updates::resolve_artifacts(
|
||||
&mut tx,
|
||||
tenant,
|
||||
&update
|
||||
.manifest()
|
||||
.map_err(|_| fail("INVALID_AGENT_RELEASE"))?
|
||||
.artifacts,
|
||||
)
|
||||
.await?
|
||||
} else if input.action.windows_msi().is_some() {
|
||||
crate::windows_msi_catalog::automatic_artifacts(&mut tx, tenant, &input.action).await?
|
||||
} else {
|
||||
crate::catalog::resolve_artifacts(&mut tx, tenant, &input.artifact_ids).await?
|
||||
};
|
||||
let artifacts = crate::catalog::resolve_artifacts(&mut tx, tenant, &input.artifact_ids).await?;
|
||||
let mut jobs = Vec::new();
|
||||
for asset in ids {
|
||||
let rows=sqlx::query("SELECT agent_id,enrollment_generation,assignment_version,capabilities FROM agent_installations WHERE asset_id=$1 AND revoked_at IS NULL ORDER BY agent_id FOR SHARE").bind(asset).fetch_all(&mut *tx).await?;
|
||||
@@ -641,18 +437,7 @@ pub(crate) async fn plan_resolved(
|
||||
}
|
||||
let row = &rows[0];
|
||||
let caps = capabilities(row.get("capabilities"))?;
|
||||
let action = if let Some(updates) = &updates {
|
||||
Action::UpdateAgent {
|
||||
update: Box::new(
|
||||
updates
|
||||
.get(&asset)
|
||||
.ok_or_else(|| fail("AGENT_UPDATE_STATE_NOT_CONFIGURED"))?
|
||||
.clone(),
|
||||
),
|
||||
}
|
||||
} else {
|
||||
target_action(&input, &caps)?
|
||||
};
|
||||
let action = target_action(&input, &caps)?;
|
||||
if !action.valid_job_limits(input.max_runtime_seconds, input.max_output_bytes) {
|
||||
return Err(fail("VALIDATION_ERROR"));
|
||||
}
|
||||
@@ -709,7 +494,7 @@ pub(crate) async fn plan_resolved(
|
||||
jobs,
|
||||
max_parallel: input.rollout.max_parallel,
|
||||
halt_after_failures: input.rollout.halt_after_failures,
|
||||
recipe_references,
|
||||
recipe_references: Vec::new(),
|
||||
artifact_references,
|
||||
script_revision,
|
||||
};
|
||||
@@ -807,6 +592,7 @@ pub(crate) async fn authorize_approved_job(
|
||||
job: &JobPayload,
|
||||
row: &sqlx::postgres::PgRow,
|
||||
) -> Result<()> {
|
||||
require_script(&job.action)?;
|
||||
let participants = JobParticipants {
|
||||
planner: &plan.principal,
|
||||
submitter: row.get("submitter"),
|
||||
@@ -966,7 +752,8 @@ pub async fn submit(
|
||||
let request_hash = hash(id.as_bytes());
|
||||
let (plan, _, _) = load_plan(&mut tx, id).await?;
|
||||
for job in &plan.jobs {
|
||||
for permission in execution_permissions(&job.payload.action, &job.payload.execution_identity)
|
||||
for permission in
|
||||
execution_permissions(&job.payload.action, &job.payload.execution_identity)
|
||||
{
|
||||
crate::permissions::require_principal(&mut tx, p, permission).await?;
|
||||
}
|
||||
@@ -993,6 +780,9 @@ pub async fn submit(
|
||||
tx.commit().await?;
|
||||
return operation(state, p, tenant, op).await;
|
||||
}
|
||||
for job in &plan.jobs {
|
||||
require_script(&job.payload.action)?;
|
||||
}
|
||||
recheck(&mut tx, &plan).await?;
|
||||
let op = Uuid::new_v4();
|
||||
sqlx::query("INSERT INTO approval_requests(tenant_id,operation_id,plan_id,principal,idempotency_key,request_hash) VALUES($1,$2,$3,$4,$5,$6)").bind(tenant).bind(op).bind(id).bind(&p.name).bind(&input.idempotency_key).bind(&request_hash).execute(&mut *tx).await?;
|
||||
@@ -1029,8 +819,11 @@ pub(crate) async fn recheck_approval(
|
||||
submitter,
|
||||
approver: &approver.name,
|
||||
};
|
||||
participants.require_roles(state, tx, plan.tenant_id).await?;
|
||||
participants
|
||||
.require_roles(state, tx, plan.tenant_id)
|
||||
.await?;
|
||||
for job in &plan.jobs {
|
||||
require_script(&job.payload.action)?;
|
||||
if execution_permissions(&job.payload.action, &job.payload.execution_identity)
|
||||
.any(|permission| !approver.permits_scope(permission))
|
||||
{
|
||||
@@ -1118,8 +911,15 @@ pub async fn requester_enabled(
|
||||
if name.starts_with("mcp:") {
|
||||
crate::mcp_tokens::issuer_enabled(state, tx, name).await
|
||||
} else if name.starts_with("local:") {
|
||||
let Some(home)=state.auth.local.as_ref().and_then(|local|local.home(name)) else {return Ok(false);};
|
||||
sqlx::query_scalar("SELECT $3=ANY(local_customer_tenants($1,$2))").bind(name).bind(home).bind(tenant).fetch_one(&mut **tx).await
|
||||
let Some(home) = state.auth.local.as_ref().and_then(|local| local.home(name)) else {
|
||||
return Ok(false);
|
||||
};
|
||||
sqlx::query_scalar("SELECT $3=ANY(local_customer_tenants($1,$2))")
|
||||
.bind(name)
|
||||
.bind(home)
|
||||
.bind(tenant)
|
||||
.fetch_one(&mut **tx)
|
||||
.await
|
||||
} else {
|
||||
Ok(state.auth.operator_enabled(name, tenant))
|
||||
}
|
||||
@@ -1537,31 +1337,45 @@ mod windows_contract_tests {
|
||||
assert!(target_action(&i, &["windows.base/1".into()]).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn fixed_windows_log_web_contract_denies_extra_source_parameters() {
|
||||
fn new_plans_accept_only_scripts_in_both_wire_formats() {
|
||||
let tenant = Uuid::new_v4();
|
||||
let now = Utc::now();
|
||||
let value = json!({"tenant_id":tenant,"action":"query_logs","targets":{"asset_ids":[Uuid::new_v4()]},"parameters":{"execution_identity":"agent_service","timeout_seconds":30,"max_output_bytes":4096,"unit":WINDOWS_EVENT_LOG_FIXTURE_SOURCE,"since":now-Duration::hours(1),"until":now,"max_lines":1000},"schedule":{"not_before":now,"start_before":now+Duration::minutes(10),"offline_policy":"wait_until_deadline"},"rollout":{"max_parallel":1,"halt_after_failures":1},"reason":"fixed source"});
|
||||
let input = serde_json::from_value::<PlanRequest>(value.clone())
|
||||
.unwrap()
|
||||
.resolve(tenant)
|
||||
.unwrap();
|
||||
assert!(input.action.is_windows_event_log_fixture());
|
||||
assert!(input.action.validate());
|
||||
assert!(
|
||||
input
|
||||
.action
|
||||
.valid_job_limits(input.max_runtime_seconds, input.max_output_bytes)
|
||||
let typed = serde_json::to_value(input()).unwrap();
|
||||
let request: PlanRequest = serde_json::from_value(typed.clone()).unwrap();
|
||||
assert!(matches!(
|
||||
request.resolve(tenant).unwrap().action,
|
||||
Action::RunScript { .. }
|
||||
));
|
||||
let mut retired = typed;
|
||||
retired["action"] = json!({"action":"refresh_inventory", "scope":"linux.base"});
|
||||
let request: PlanRequest = serde_json::from_value(retired).unwrap();
|
||||
assert_eq!(
|
||||
request.resolve(tenant).err().unwrap().1,
|
||||
"SCRIPT_ACTION_REQUIRED"
|
||||
);
|
||||
assert!(input.script_variants.is_empty());
|
||||
for field in ["channel", "provider", "xpath", "bookmark"] {
|
||||
let mut bad = value.clone();
|
||||
bad["parameters"][field] = json!("arbitrary");
|
||||
assert!(
|
||||
serde_json::from_value::<PlanRequest>(bad)
|
||||
.map(|request| request.resolve(tenant).is_err())
|
||||
.unwrap_or(true)
|
||||
|
||||
for action in [
|
||||
"reboot",
|
||||
"query_logs",
|
||||
"set_service_state",
|
||||
"update_agent",
|
||||
"future-action",
|
||||
] {
|
||||
let old: PlanRequest = serde_json::from_value(
|
||||
json!({"tenant_id":tenant, "action":action, "parameters":{}}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
old.clone().resolve(tenant).err().unwrap().1,
|
||||
"SCRIPT_ACTION_REQUIRED"
|
||||
);
|
||||
assert_eq!(old.resolve(Uuid::new_v4()).err().unwrap().1, "NOT_FOUND");
|
||||
}
|
||||
assert!(
|
||||
serde_json::from_value::<PlanRequest>(
|
||||
json!({"tenant_id":tenant, "action":"run_script", "parameters":{"unit":"x"}})
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn full_maintenance_web_profile_is_action_wide_strict_and_identity_bound() {
|
||||
@@ -1664,6 +1478,58 @@ mod windows_contract_tests {
|
||||
}
|
||||
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());
|
||||
}
|
||||
// Restore a synthetic historical plan row for read/recheck tests. No job, approval,
|
||||
// outbox entry or start grant is created; current API callers cannot create such a plan.
|
||||
async fn historical_fixture(
|
||||
state: &crate::State,
|
||||
template: &PlanPayload,
|
||||
input: &PlanInput,
|
||||
) -> PlanPayload {
|
||||
let mut plan = template.clone();
|
||||
plan.plan_id = Uuid::new_v4();
|
||||
plan.jobs
|
||||
.retain(|job| job.payload.asset_id == input.targets.asset_ids[0]);
|
||||
assert_eq!(plan.jobs.len(), 1);
|
||||
let job = &mut plan.jobs[0];
|
||||
job.payload.job_id = Uuid::new_v4();
|
||||
job.payload.attempt_id = Uuid::new_v4();
|
||||
job.payload.action = input.action.clone();
|
||||
job.payload.execution_identity = input.execution_identity.clone();
|
||||
job.payload.max_runtime_seconds = input.max_runtime_seconds;
|
||||
job.payload.max_output_bytes = input.max_output_bytes;
|
||||
job.script_sha256 = None;
|
||||
job.job_payload_hash = hash(&encode(&job.payload).unwrap());
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, plan.tenant_id)
|
||||
.await
|
||||
.unwrap();
|
||||
plan.recipe_references = crate::catalog::references(&mut tx, &input.action)
|
||||
.await
|
||||
.unwrap();
|
||||
if input.action.windows_msi().is_some() {
|
||||
let artifacts = crate::windows_msi_catalog::automatic_artifacts(
|
||||
&mut tx,
|
||||
plan.tenant_id,
|
||||
&input.action,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
plan.artifact_references = artifacts
|
||||
.into_iter()
|
||||
.map(|artifact| JobArtifactReference {
|
||||
job_id: job.payload.job_id,
|
||||
attempt_id: job.payload.attempt_id,
|
||||
artifact,
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
let bytes = encode(&plan).unwrap();
|
||||
sqlx::query("INSERT INTO operation_plans(tenant_id,plan_id,principal,payload,plan_hash,expires_at) VALUES($1,$2,$3,$4,$5,$6)")
|
||||
.bind(plan.tenant_id).bind(plan.plan_id).bind(&plan.principal).bind(&bytes).bind(hash(&bytes)).bind(input.schedule.start_before)
|
||||
.execute(&mut *tx).await.unwrap();
|
||||
tx.commit().await.unwrap();
|
||||
plan
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires dedicated isolated PostgreSQL; tests/windows_plan_database.py"]
|
||||
async fn windows_plan_caps_persisted_database() {
|
||||
@@ -1824,8 +1690,10 @@ mod windows_contract_tests {
|
||||
.execute(&admin)
|
||||
.await
|
||||
.unwrap();
|
||||
crate::script_library::tests::revision_plan_contract(&state, &principal, assets[0], assets[1])
|
||||
.await;
|
||||
crate::script_library::tests::revision_plan_contract(
|
||||
&state, &principal, assets[0], assets[1],
|
||||
)
|
||||
.await;
|
||||
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> =
|
||||
@@ -1914,16 +1782,9 @@ mod windows_contract_tests {
|
||||
.await
|
||||
.unwrap_err()
|
||||
.1,
|
||||
"FORBIDDEN"
|
||||
"SCRIPT_ACTION_REQUIRED"
|
||||
);
|
||||
sqlx::query("UPDATE memberships SET permissions=array_append(permissions,'logs:read') WHERE principal=$1").bind(&principal.name).execute(&admin).await.unwrap();
|
||||
assert_eq!(
|
||||
plan(&state, &principal, tenant, logs.clone())
|
||||
.await
|
||||
.unwrap_err()
|
||||
.1,
|
||||
"UNSUPPORTED_CAPABILITY"
|
||||
);
|
||||
let mut log_caps = windows_caps.as_array().unwrap().clone();
|
||||
log_caps.extend([
|
||||
json!("query_logs"),
|
||||
@@ -1935,21 +1796,14 @@ mod windows_contract_tests {
|
||||
.execute(&admin)
|
||||
.await
|
||||
.unwrap();
|
||||
let view = plan(&state, &principal, tenant, logs).await.unwrap();
|
||||
let log_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(log_id)
|
||||
.fetch_one(&admin)
|
||||
.await
|
||||
.unwrap();
|
||||
let log_bound: PlanPayload = serde_json::from_slice(&bytes).unwrap();
|
||||
let log_bound = historical_fixture(&state, &bound, &logs).await;
|
||||
let log_id = log_bound.plan_id;
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
|
||||
.await
|
||||
.unwrap();
|
||||
recheck(&mut tx, &log_bound).await.unwrap();
|
||||
tx.rollback().await.unwrap();
|
||||
let pending = submit(
|
||||
let blocked = submit(
|
||||
&state,
|
||||
&principal,
|
||||
tenant,
|
||||
@@ -1959,9 +1813,8 @@ mod windows_contract_tests {
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(pending["approval_state"], "pending_approval");
|
||||
assert_eq!(pending["job_count"], 0);
|
||||
.unwrap_err();
|
||||
assert_eq!(blocked.1, "SCRIPT_ACTION_REQUIRED");
|
||||
let mut changed = log_bound.clone();
|
||||
if let Action::QueryLogs { max_lines, .. } = &mut changed.jobs[0].payload.action {
|
||||
*max_lines = 999;
|
||||
@@ -2122,21 +1975,14 @@ mod windows_contract_tests {
|
||||
package.action = crate::windows_msi_catalog::test_action(manifest.clone());
|
||||
package.max_runtime_seconds = 30;
|
||||
package.max_output_bytes = 4096;
|
||||
let mut extra = package.clone();
|
||||
extra.artifact_ids = vec![artifact_id];
|
||||
assert_eq!(
|
||||
plan(&state, &principal, tenant, extra).await.unwrap_err().1,
|
||||
"WINDOWS_MSI_EXACT_ARTIFACT_REQUIRED"
|
||||
);
|
||||
let view = plan(&state, &principal, tenant, package).await.unwrap();
|
||||
let package_id = Uuid::parse_str(view["plan_id"].as_str().unwrap()).unwrap();
|
||||
let raw: Vec<u8> =
|
||||
sqlx::query_scalar("SELECT payload FROM operation_plans WHERE plan_id=$1")
|
||||
.bind(package_id)
|
||||
.fetch_one(&admin)
|
||||
plan(&state, &principal, tenant, package.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
let fixed: PlanPayload = serde_json::from_slice(&raw).unwrap();
|
||||
.unwrap_err()
|
||||
.1,
|
||||
"SCRIPT_ACTION_REQUIRED"
|
||||
);
|
||||
let fixed = historical_fixture(&state, &bound, &package).await;
|
||||
assert_eq!(fixed.artifact_references.len(), 1);
|
||||
assert_eq!(
|
||||
fixed.artifact_references[0].artifact.artifact_id,
|
||||
@@ -2163,19 +2009,18 @@ mod windows_contract_tests {
|
||||
assert!(recheck(&mut tx, &bad).await.is_err());
|
||||
tx.rollback().await.unwrap();
|
||||
}
|
||||
let pending = submit(
|
||||
let blocked = submit(
|
||||
&state,
|
||||
&principal,
|
||||
tenant,
|
||||
package_id,
|
||||
fixed.plan_id,
|
||||
Submit {
|
||||
idempotency_key: "fixed-msi-metadata".into(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(pending["approval_state"], "pending_approval");
|
||||
assert_eq!(pending["job_count"], 0);
|
||||
.unwrap_err();
|
||||
assert_eq!(blocked.1, "SCRIPT_ACTION_REQUIRED");
|
||||
sqlx::query("UPDATE memberships SET permissions=array_remove(permissions,'system:execute') WHERE tenant_id=$1 AND principal=$2").bind(tenant).bind(&principal.name).execute(&admin).await.unwrap();
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
|
||||
.await
|
||||
|
||||
@@ -486,8 +486,8 @@ mod tests {
|
||||
assert_eq!(directory["items"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(directory["items"][0]["tenant_id"], a.to_string());
|
||||
let now = Utc::now();
|
||||
let forbidden_plan = json!({"tenant_id":b,"action":"refresh_inventory","targets":{"asset_ids":[asset]},
|
||||
"parameters":{"execution_identity":"agent_service","timeout_seconds":60,"max_output_bytes":4096,"scope":"base"},
|
||||
let forbidden_plan = json!({"tenant_id":b,"action":"run_script","targets":{"asset_ids":[asset]},
|
||||
"parameters":{"execution_identity":"agent_service","timeout_seconds":60,"max_output_bytes":4096,"variants":[{"os_family":"linux","interpreter":"posix_sh","encoding":"utf-8","script_utf8":":\n"}]},
|
||||
"schedule":{"not_before":now,"start_before":now+chrono::Duration::minutes(5),"offline_policy":"wait_until_deadline"},
|
||||
"rollout":{"max_parallel":1,"halt_after_failures":1},"reason":"test customer authorization"});
|
||||
for request in [
|
||||
|
||||
@@ -2,9 +2,14 @@
|
||||
//! Plan submission, interactive approval and signed start grants are unchanged.
|
||||
use crate::{jobs::Error, root_policy::RootScope, windows_policy::SystemScope};
|
||||
use axum::http::StatusCode;
|
||||
use rmm_domain::jobs::{Action, JobPayload};
|
||||
use rmm_domain::{
|
||||
agent_update::{ArtifactRole, Platform, ReleaseManifest, digest},
|
||||
jobs::{Action, FULL_MAINTENANCE_CAPABILITY, JobPayload},
|
||||
};
|
||||
use serde::Deserialize;
|
||||
use sqlx::{Postgres, Transaction};
|
||||
use std::{fs, os::unix::fs::MetadataExt, path::Path};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
@@ -12,6 +17,76 @@ struct Policy {
|
||||
schema_version: u8,
|
||||
linux: Vec<RootScope>,
|
||||
windows: Vec<SystemScope>,
|
||||
#[serde(default)]
|
||||
release_anchors: Vec<ReleaseAnchor>,
|
||||
}
|
||||
|
||||
/// Operator-pinned canonical bytes of an already authorized local policy.
|
||||
/// A signed pair changes only the two image digests and the Windows release directory.
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct ReleaseAnchor {
|
||||
agent_id: Uuid,
|
||||
release_id: Uuid,
|
||||
agent_sha256: String,
|
||||
helper_sha256: String,
|
||||
policy_json: String,
|
||||
}
|
||||
|
||||
impl ReleaseAnchor {
|
||||
fn policy_for(&self, manifest: &ReleaseManifest) -> Option<String> {
|
||||
if self.policy_json.len() > 8192
|
||||
|| self.release_id.is_nil()
|
||||
|| !digest(&self.agent_sha256)
|
||||
|| !digest(&self.helper_sha256)
|
||||
|| self.agent_sha256 == self.helper_sha256
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let next = |role| {
|
||||
manifest
|
||||
.artifacts
|
||||
.iter()
|
||||
.find(|a| a.role == role)
|
||||
.map(|a| a.sha256.as_str())
|
||||
};
|
||||
let mut raw = self.policy_json.clone();
|
||||
let mut replace = |from: String, to: String, count| {
|
||||
if raw.matches(&from).count() != count {
|
||||
return None;
|
||||
}
|
||||
raw = raw.replace(&from, &to);
|
||||
Some(())
|
||||
};
|
||||
let field = |name: &str, value: &str| format!(r#""{name}":"{value}""#);
|
||||
match manifest.platform {
|
||||
Platform::LinuxX64 => replace(
|
||||
field("helper_binary_sha256", &self.helper_sha256),
|
||||
field("helper_binary_sha256", next(ArtifactRole::Helper)?),
|
||||
1,
|
||||
)?,
|
||||
Platform::WindowsGnuX64 => {
|
||||
replace(
|
||||
field("binary_sha256", &self.agent_sha256),
|
||||
field("binary_sha256", next(ArtifactRole::Agent)?),
|
||||
1,
|
||||
)?;
|
||||
replace(
|
||||
field("binary_sha256", &self.helper_sha256),
|
||||
field("binary_sha256", next(ArtifactRole::Helper)?),
|
||||
1,
|
||||
)?;
|
||||
let directory = |release| format!(r"\\releases\\{release}\\");
|
||||
replace(
|
||||
directory(self.release_id),
|
||||
directory(manifest.release_id),
|
||||
2,
|
||||
)?;
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
Some(rmm_domain::jobs::hash(raw.as_bytes()))
|
||||
}
|
||||
}
|
||||
|
||||
fn invalid() -> Error {
|
||||
@@ -24,19 +99,72 @@ impl Policy {
|
||||
|| !job.action.full_maintenance()
|
||||
|| !job.action.validate()
|
||||
|| !job.action.available_for(&job.execution_identity, caps)
|
||||
|| !job.action.valid_job_limits(job.max_runtime_seconds, job.max_output_bytes)
|
||||
|| !job
|
||||
.action
|
||||
.valid_job_limits(job.max_runtime_seconds, job.max_output_bytes)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
match job.execution_identity.as_str() {
|
||||
"root" => self.linux.iter().any(|scope| scope.permits(principal, job, caps, None)),
|
||||
"system" => self.windows.iter().any(|scope| scope.permits(principal, job, caps, false, true, false)),
|
||||
"root" => self
|
||||
.linux
|
||||
.iter()
|
||||
.any(|scope| scope.permits(principal, job, caps, None)),
|
||||
"system" => self
|
||||
.windows
|
||||
.iter()
|
||||
.any(|scope| scope.permits(principal, job, caps, false, true, false)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn permits(principal: &str, job: &JobPayload, caps: &[String]) -> Result<bool, Error> {
|
||||
fn binding_error() -> Error {
|
||||
Error(StatusCode::CONFLICT, "SCRIPT_HELPER_BINDING_INVALID")
|
||||
}
|
||||
|
||||
// Multiple helper roles may coexist on older clients. For the release-managed
|
||||
// script profile we require exactly one unambiguous release, policy and binary.
|
||||
fn single_value<'a>(caps: &'a [String], prefix: &str) -> Result<&'a str, Error> {
|
||||
let mut values = caps.iter().filter_map(|c| c.strip_prefix(prefix));
|
||||
let value = values.next().ok_or_else(binding_error)?;
|
||||
if value.is_empty() || values.next().is_some() {
|
||||
return Err(binding_error());
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn check_pair(
|
||||
manifest: &ReleaseManifest,
|
||||
version: Option<&str>,
|
||||
identity: &str,
|
||||
caps: &[String],
|
||||
) -> Result<(), Error> {
|
||||
let platform = match identity {
|
||||
"root" => Platform::LinuxX64,
|
||||
"system" => Platform::WindowsGnuX64,
|
||||
_ => return Err(binding_error()),
|
||||
};
|
||||
let binary = single_value(caps, "helper.binary.sha256:")?;
|
||||
if version != Some(manifest.version.as_str())
|
||||
|| platform != manifest.platform
|
||||
|| !digest(single_value(caps, "helper.policy.sha256:")?)
|
||||
|| !manifest
|
||||
.artifacts
|
||||
.iter()
|
||||
.any(|a| a.role == ArtifactRole::Helper && a.sha256 == binary)
|
||||
{
|
||||
return Err(binding_error());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn permits(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
principal: &str,
|
||||
job: &JobPayload,
|
||||
caps: &[String],
|
||||
) -> Result<bool, Error> {
|
||||
if !job.action.full_maintenance() {
|
||||
return Ok(false);
|
||||
}
|
||||
@@ -53,9 +181,142 @@ pub(crate) fn permits(principal: &str, job: &JobPayload, caps: &[String]) -> Res
|
||||
let policy: Policy = serde_json::from_slice(&bytes).map_err(|_| invalid())?;
|
||||
if policy.schema_version != 1
|
||||
|| policy.linux.len() + policy.windows.len() > 64
|
||||
|| policy.release_anchors.len() > 64
|
||||
|| policy
|
||||
.release_anchors
|
||||
.iter()
|
||||
.any(|a| a.policy_json.len() > 8192)
|
||||
|| !policy.windows.iter().all(SystemScope::valid)
|
||||
{
|
||||
return Err(invalid());
|
||||
}
|
||||
Ok(policy.permits(principal, job, caps))
|
||||
let direct = policy.permits(principal, job, caps);
|
||||
if !caps
|
||||
.iter()
|
||||
.any(|cap| cap.starts_with("script.helper.release:"))
|
||||
{
|
||||
return Ok(direct);
|
||||
}
|
||||
{
|
||||
let release = Uuid::parse_str(single_value(caps, "script.helper.release:")?)
|
||||
.map_err(|_| binding_error())?;
|
||||
if !caps.iter().any(|cap| cap == FULL_MAINTENANCE_CAPABILITY) {
|
||||
return Err(binding_error());
|
||||
}
|
||||
let version: Option<String> = sqlx::query_scalar(
|
||||
"SELECT reported_agent_version FROM agent_installations WHERE tenant_id=$1 AND agent_id=$2 AND asset_id=$3 AND revoked_at IS NULL",
|
||||
)
|
||||
.bind(job.tenant_id)
|
||||
.bind(job.agent_id)
|
||||
.bind(job.asset_id)
|
||||
.fetch_optional(&mut **tx)
|
||||
.await?
|
||||
.flatten();
|
||||
let (_, manifest) = crate::agent_updates::checked_release(tx, release)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
if err.0.is_server_error() {
|
||||
err
|
||||
} else {
|
||||
binding_error()
|
||||
}
|
||||
})?;
|
||||
check_pair(&manifest, version.as_deref(), &job.execution_identity, caps)?;
|
||||
if direct {
|
||||
return Ok(true);
|
||||
}
|
||||
let current_policy = single_value(caps, "helper.policy.sha256:")?;
|
||||
for anchor in policy
|
||||
.release_anchors
|
||||
.iter()
|
||||
.filter(|a| a.agent_id == job.agent_id)
|
||||
{
|
||||
if anchor.policy_for(&manifest).as_deref() != Some(current_policy) {
|
||||
continue;
|
||||
}
|
||||
let original = rmm_domain::jobs::hash(anchor.policy_json.as_bytes());
|
||||
let mut pinned = caps.to_owned();
|
||||
pinned.retain(|c| {
|
||||
!c.starts_with("helper.binary.sha256:") && !c.starts_with("helper.policy.sha256:")
|
||||
});
|
||||
pinned.push(format!("helper.binary.sha256:{}", anchor.helper_sha256));
|
||||
pinned.push(format!("helper.policy.sha256:{original}"));
|
||||
if policy.permits(principal, job, &pinned) {
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(Error(StatusCode::FORBIDDEN, "SCRIPT_HELPER_SCOPE_DENIED"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use rmm_domain::agent_update::ArtifactDescriptor;
|
||||
|
||||
#[test]
|
||||
fn signed_helper_is_bound_to_platform_reported_version_and_unambiguous_local_pins() {
|
||||
let binary = "ab".repeat(32);
|
||||
let policy = "cd".repeat(32);
|
||||
let artifact = |role, sha256| ArtifactDescriptor {
|
||||
role,
|
||||
sha256,
|
||||
artifact_id: Uuid::new_v4(),
|
||||
bytes: 4096,
|
||||
};
|
||||
let m = ReleaseManifest {
|
||||
schema_version: 1,
|
||||
release_id: Uuid::new_v4(),
|
||||
release_sequence: 7,
|
||||
version: "0.1.12".into(),
|
||||
platform: Platform::WindowsGnuX64,
|
||||
published_at: 10,
|
||||
expires_at: 500,
|
||||
protocol_major: 1,
|
||||
state_schema: 1,
|
||||
minimum_updater_version: 2,
|
||||
artifacts: [
|
||||
artifact(ArtifactRole::Agent, "ef".repeat(32)),
|
||||
artifact(ArtifactRole::Helper, binary.clone()),
|
||||
],
|
||||
};
|
||||
// Rollover may substitute signed image pins and their release directory only.
|
||||
let previous = Uuid::new_v4();
|
||||
let original_agent = "12".repeat(32);
|
||||
let original_helper = "34".repeat(32);
|
||||
let windows = |release: Uuid, agent: &str, helper: &str, runtime: u32| {
|
||||
format!(
|
||||
r#"{{"agent":{{"binary":"C:\\releases\\{release}\\agent.exe","binary_sha256":"{agent}"}},"helper":{{"binary":"C:\\releases\\{release}\\helper.exe","binary_sha256":"{helper}"}},"max_runtime_seconds":{runtime}}}"#
|
||||
)
|
||||
};
|
||||
let mut anchor = ReleaseAnchor {
|
||||
agent_id: Uuid::new_v4(),
|
||||
release_id: previous,
|
||||
policy_json: windows(previous, &original_agent, &original_helper, 30),
|
||||
agent_sha256: original_agent,
|
||||
helper_sha256: original_helper,
|
||||
};
|
||||
let next_agent = &m.artifacts[0].sha256;
|
||||
let expected = |limit| {
|
||||
rmm_domain::jobs::hash(windows(m.release_id, next_agent, &binary, limit).as_bytes())
|
||||
};
|
||||
assert_eq!(anchor.policy_for(&m), Some(expected(30)));
|
||||
assert_ne!(anchor.policy_for(&m), Some(expected(120)));
|
||||
anchor
|
||||
.policy_json
|
||||
.push_str(&format!(r#","binary_sha256":"{}""#, anchor.helper_sha256));
|
||||
assert!(anchor.policy_for(&m).is_none());
|
||||
let mut caps = vec![
|
||||
format!("helper.binary.sha256:{binary}"),
|
||||
format!("helper.policy.sha256:{policy}"),
|
||||
];
|
||||
assert!(check_pair(&m, Some("0.1.12"), "system", &caps).is_ok());
|
||||
assert!(check_pair(&m, Some("0.1.11"), "system", &caps).is_err());
|
||||
assert!(check_pair(&m, Some("0.1.12"), "root", &caps).is_err());
|
||||
caps.push(format!("helper.binary.sha256:{binary}"));
|
||||
assert!(check_pair(&m, Some("0.1.12"), "system", &caps).is_err());
|
||||
caps.remove(0);
|
||||
caps[1] = format!("helper.binary.sha256:{policy}");
|
||||
assert!(check_pair(&m, Some("0.1.12"), "system", &caps).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,6 +58,7 @@ struct Device {
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Plan {
|
||||
tenant_id: Uuid,
|
||||
#[schemars(with = "crate::jobs::WebPlanInput")]
|
||||
input: crate::jobs::PlanRequest,
|
||||
}
|
||||
#[derive(Deserialize, schemars::JsonSchema)]
|
||||
@@ -138,11 +139,11 @@ fn tools() -> Vec<Tool> {
|
||||
),
|
||||
tool::<crate::monitoring::LogQuery>(
|
||||
"logs.query",
|
||||
"Read stored bounded log evidence, or request a live query as a pending approval operation.",
|
||||
"Read stored bounded log evidence. Use a script job for a fresh collection.",
|
||||
),
|
||||
tool::<Plan>(
|
||||
"operations.plan",
|
||||
"Persist immutable exact job plan. No executable jobs are created.",
|
||||
"Plan a run_script operation for selected devices. The stored script and target list require interactive approval.",
|
||||
),
|
||||
tool::<Submit>(
|
||||
"operations.submit",
|
||||
@@ -156,10 +157,6 @@ fn tools() -> Vec<Tool> {
|
||||
"jobs.cancel",
|
||||
"Request cancellation, not rollback or proof of termination.",
|
||||
),
|
||||
tool::<Tenant>(
|
||||
"sessions.request",
|
||||
"Unsupported until after MVP; never opens a shell.",
|
||||
),
|
||||
]
|
||||
}
|
||||
fn parse<T: serde::de::DeserializeOwned>(v: Value) -> Result<T, crate::jobs::Error> {
|
||||
@@ -400,3 +397,37 @@ pub fn routes(r: Router<crate::State>, state: crate::State) -> Router<crate::Sta
|
||||
r.nest_service("/mcp", service)
|
||||
.route_layer(middleware::from_fn_with_state(state, guard))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn plan_tool_advertises_the_script_wire_contract() {
|
||||
let tools = tools();
|
||||
let plan = tools
|
||||
.iter()
|
||||
.find(|tool| tool.name == "operations.plan")
|
||||
.unwrap();
|
||||
let schema = serde_json::to_string(&plan.input_schema).unwrap();
|
||||
for field in [
|
||||
"run_script",
|
||||
"script_utf8",
|
||||
"variants",
|
||||
"execution_identity",
|
||||
] {
|
||||
assert!(schema.contains(field), "{field}");
|
||||
}
|
||||
for retired in [
|
||||
"update_agent",
|
||||
"reboot",
|
||||
"query_logs",
|
||||
"apt_manifest",
|
||||
"windows_msi_manifest",
|
||||
"dependency_group",
|
||||
] {
|
||||
assert!(!schema.contains(retired), "{retired}");
|
||||
}
|
||||
assert!(tools.iter().all(|tool| tool.name != "sessions.request"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,7 +34,10 @@ pub struct LogQuery {
|
||||
pub since: DateTime<Utc>,
|
||||
pub until: DateTime<Utc>,
|
||||
pub max_lines: u32,
|
||||
#[serde(default)]
|
||||
#[schemars(skip)]
|
||||
pub live: bool,
|
||||
#[schemars(skip)]
|
||||
pub idempotency_key: Option<String>,
|
||||
}
|
||||
/// Both result endpoints use the reader's current token scope and tenant membership.
|
||||
@@ -83,89 +86,10 @@ pub async fn query(
|
||||
));
|
||||
}
|
||||
if i.live {
|
||||
let request_hash = rmm_domain::jobs::hash(&serde_json::to_vec(&i)?);
|
||||
let mut dedup = rmm_persistence::tenant_tx(&s.pool, i.tenant_id).await?;
|
||||
let key = i
|
||||
.idempotency_key
|
||||
.as_ref()
|
||||
.filter(|k| !k.is_empty() && k.len() <= 128)
|
||||
.ok_or(crate::jobs::Error(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"VALIDATION_ERROR",
|
||||
))?;
|
||||
if let Some(row)=sqlx::query("SELECT request_hash,plan_id FROM live_query_requests WHERE principal=$1 AND idempotency_key=$2").bind(&p.name).bind(key).fetch_optional(&mut *dedup).await?{
|
||||
if row.get::<String,_>("request_hash")!=request_hash{return Err(crate::jobs::Error(StatusCode::CONFLICT,"IDEMPOTENCY_CONFLICT"))}
|
||||
let plan=row.get("plan_id");let key=key.clone();dedup.commit().await?;
|
||||
return crate::jobs::submit(s,p,i.tenant_id,plan,crate::jobs::Submit{idempotency_key:key}).await;
|
||||
}
|
||||
dedup.commit().await?;
|
||||
let key = i.idempotency_key.ok_or(crate::jobs::Error(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"VALIDATION_ERROR",
|
||||
))?;
|
||||
let plan = crate::jobs::plan(
|
||||
s,
|
||||
p,
|
||||
i.tenant_id,
|
||||
crate::jobs::PlanInput {
|
||||
targets: crate::jobs::Targets {
|
||||
asset_ids: vec![i.asset_id],
|
||||
},
|
||||
action,
|
||||
script_variants: vec![],
|
||||
execution_identity: "agent_service".into(),
|
||||
schedule: crate::jobs::Schedule {
|
||||
not_before: Utc::now(),
|
||||
start_before: Utc::now() + chrono::Duration::hours(1),
|
||||
},
|
||||
max_runtime_seconds: 30,
|
||||
max_output_bytes: 262144,
|
||||
rollout: crate::jobs::Rollout {
|
||||
max_parallel: 1,
|
||||
halt_after_failures: 1,
|
||||
},
|
||||
reason: format!("Requested live logs for {}", i.unit),
|
||||
artifact_ids: vec![],
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
let id = plan["plan_id"]
|
||||
.as_str()
|
||||
.and_then(|v| Uuid::parse_str(v).ok())
|
||||
.ok_or(crate::jobs::Error(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"VALIDATION_ERROR",
|
||||
))?;
|
||||
let mut dedup = rmm_persistence::tenant_tx(&s.pool, i.tenant_id).await?;
|
||||
sqlx::query(
|
||||
"INSERT INTO live_query_requests VALUES($1,$2,$3,$4,$5) ON CONFLICT DO NOTHING",
|
||||
)
|
||||
.bind(i.tenant_id)
|
||||
.bind(&p.name)
|
||||
.bind(&key)
|
||||
.bind(&request_hash)
|
||||
.bind(id)
|
||||
.execute(&mut *dedup)
|
||||
.await?;
|
||||
let canonical=sqlx::query("SELECT request_hash,plan_id FROM live_query_requests WHERE principal=$1 AND idempotency_key=$2").bind(&p.name).bind(&key).fetch_one(&mut *dedup).await?;
|
||||
if canonical.get::<String, _>("request_hash") != request_hash {
|
||||
return Err(crate::jobs::Error(
|
||||
StatusCode::CONFLICT,
|
||||
"IDEMPOTENCY_CONFLICT",
|
||||
));
|
||||
}
|
||||
let id = canonical.get("plan_id");
|
||||
dedup.commit().await?;
|
||||
return crate::jobs::submit(
|
||||
s,
|
||||
p,
|
||||
i.tenant_id,
|
||||
id,
|
||||
crate::jobs::Submit {
|
||||
idempotency_key: key,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
return Err(crate::jobs::Error(
|
||||
StatusCode::CONFLICT,
|
||||
"SCRIPT_ACTION_REQUIRED",
|
||||
));
|
||||
}
|
||||
let mut tx = rmm_persistence::tenant_tx(&s.pool, i.tenant_id).await?;
|
||||
let access = LogReadAccess::for_principal(&mut tx, p).await?;
|
||||
|
||||
@@ -377,7 +377,7 @@ pub async fn authorize(
|
||||
}
|
||||
let caps:serde_json::Value=sqlx::query_scalar("SELECT capabilities FROM agent_installations WHERE agent_id=$1 AND asset_id=$2 AND revoked_at IS NULL AND enrollment_generation=$3 AND assignment_version=$4").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 caps: Vec<String> = serde_json::from_value(caps)?;
|
||||
if crate::managed_scripts::permits(principal, job, &caps)? {
|
||||
if crate::managed_scripts::permits(tx, principal, job, &caps).await? {
|
||||
return Ok(());
|
||||
}
|
||||
let policy = load()?;
|
||||
|
||||
@@ -186,7 +186,7 @@ pub async fn plan(
|
||||
reason: input.reason,
|
||||
artifact_ids: vec![],
|
||||
};
|
||||
jobs::plan_resolved(s, p, tenant, plan, None, Some(reference)).await
|
||||
jobs::plan_resolved(s, p, tenant, plan, Some(reference)).await
|
||||
}
|
||||
|
||||
pub(crate) fn validate_plan_bindings(plan: &rmm_domain::jobs::PlanPayload) -> Result<(), Error> {
|
||||
@@ -263,7 +263,20 @@ pub(crate) mod tests {
|
||||
let tenant = p.tenant;
|
||||
let initial = list(s, p, tenant, PageQuery::default()).await.unwrap();
|
||||
let items = initial["items"].as_array().unwrap();
|
||||
assert_eq!(items.len(), 13);
|
||||
assert_eq!(items.len(), 15);
|
||||
for (name, interpreter, identity) in [
|
||||
("Linux neu starten", "posix_sh", "root"),
|
||||
("Windows neu starten", "powershell", "system"),
|
||||
] {
|
||||
let revision = items.iter().find(|r| r["name"] == name).unwrap();
|
||||
assert_eq!(revision["version"], 1);
|
||||
assert_eq!(revision["interpreter"], interpreter);
|
||||
assert_eq!(revision["execution_identity"], identity);
|
||||
assert_eq!(
|
||||
revision["script_sha256"],
|
||||
hash(revision["script_utf8"].as_str().unwrap().as_bytes())
|
||||
);
|
||||
}
|
||||
let template = items
|
||||
.iter()
|
||||
.find(|item| item["name"] == "Windows-Updates installieren")
|
||||
|
||||
@@ -72,7 +72,8 @@ pub async fn references(
|
||||
checked(tx, m).await?;
|
||||
Ok(vec![reference(m)])
|
||||
}
|
||||
pub async fn automatic_artifacts(
|
||||
#[cfg(test)]
|
||||
pub(crate) async fn automatic_artifacts(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
tenant: Uuid,
|
||||
action: &Action,
|
||||
|
||||
@@ -38,6 +38,8 @@ pub(crate) struct SystemScope {
|
||||
acceptance_evidence_id: Uuid,
|
||||
allowed_services: Vec<String>,
|
||||
#[serde(default, deserialize_with = "strict_optional_hashes")]
|
||||
allowed_script_sha256: Option<Vec<String>>,
|
||||
#[serde(default, deserialize_with = "strict_optional_hashes")]
|
||||
allowed_msi_recipe_sha256: Option<Vec<String>>,
|
||||
max_runtime_seconds: u32,
|
||||
#[serde(
|
||||
@@ -97,6 +99,15 @@ impl SystemScope {
|
||||
.collect::<std::collections::BTreeSet<_>>()
|
||||
.len()
|
||||
== self.principals.len()
|
||||
&& self.allowed_script_sha256.as_ref().is_none_or(|hashes| {
|
||||
hashes.len() <= 64
|
||||
&& hashes.iter().all(|h| digest(h))
|
||||
&& hashes
|
||||
.iter()
|
||||
.collect::<std::collections::BTreeSet<_>>()
|
||||
.len()
|
||||
== hashes.len()
|
||||
})
|
||||
&& self.allowed_services.len() <= 16
|
||||
&& self
|
||||
.allowed_services
|
||||
@@ -178,8 +189,16 @@ impl SystemScope {
|
||||
&& has("system:set_service_state")
|
||||
&& has("set_service_state")
|
||||
}
|
||||
Action::RunScript { .. } => {
|
||||
Action::RunScript {
|
||||
script_utf8,
|
||||
arguments,
|
||||
..
|
||||
} => {
|
||||
allow_scripts
|
||||
&& self.allowed_script_sha256.as_ref().is_none_or(|hashes| {
|
||||
arguments.is_empty()
|
||||
&& hashes.contains(&rmm_domain::jobs::hash(script_utf8.as_bytes()))
|
||||
})
|
||||
&& job.action.full_maintenance()
|
||||
&& (self.allowed_script_profiles.as_ref().is_some_and(|v| {
|
||||
v.contains(
|
||||
@@ -376,7 +395,7 @@ pub async fn authorize(
|
||||
}
|
||||
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)?;
|
||||
if crate::managed_scripts::permits(principal, job, &capabilities)? {
|
||||
if crate::managed_scripts::permits(tx, principal, job, &capabilities).await? {
|
||||
return Ok(());
|
||||
}
|
||||
let policy = load()?;
|
||||
@@ -569,6 +588,27 @@ mod tests {
|
||||
policy.schema_version = 3;
|
||||
assert!(policy.permits("selected", &job, &caps, Utc::now()));
|
||||
assert!(!policy.permits("foreign", &job, &caps, Utc::now()));
|
||||
policy.scopes[0].allowed_script_sha256 = Some(vec![]);
|
||||
assert!(!policy.permits("selected", &job, &caps, Utc::now()));
|
||||
policy.scopes[0].allowed_script_sha256 =
|
||||
Some(vec![rmm_domain::jobs::hash(b"Write-Output 'hi'\r\n")]);
|
||||
assert!(policy.permits("selected", &job, &caps, Utc::now()));
|
||||
let mut changed = job.clone();
|
||||
if let Action::RunScript { arguments, .. } = &mut changed.action {
|
||||
arguments.push("unexpected".into());
|
||||
}
|
||||
assert!(!policy.permits("selected", &changed, &caps, Utc::now()));
|
||||
if let Action::RunScript {
|
||||
arguments,
|
||||
script_utf8,
|
||||
..
|
||||
} = &mut changed.action
|
||||
{
|
||||
arguments.clear();
|
||||
script_utf8.push(' ');
|
||||
}
|
||||
assert!(!policy.permits("selected", &changed, &caps, Utc::now()));
|
||||
policy.scopes[0].allowed_script_sha256 = None;
|
||||
let general = job.action.clone();
|
||||
job.action = Action::RunScript {
|
||||
interpreter: "powershell".into(),
|
||||
@@ -600,13 +640,25 @@ mod tests {
|
||||
}
|
||||
#[test]
|
||||
fn windows_update_window_accepts_only_the_two_fixed_scripts() {
|
||||
use rmm_domain::jobs::{PrivilegedScriptProfile, WindowsExecutionProfile, WINDOWS_UPDATE_IDENTITY_PROBE, WINDOWS_UPDATE_LONG_CAPABILITY, WINDOWS_UPDATE_SCRIPT_UTF8};
|
||||
use rmm_domain::jobs::{
|
||||
PrivilegedScriptProfile, WINDOWS_UPDATE_IDENTITY_PROBE, WINDOWS_UPDATE_LONG_CAPABILITY,
|
||||
WINDOWS_UPDATE_SCRIPT_UTF8, WindowsExecutionProfile,
|
||||
};
|
||||
let (mut policy, mut job, mut caps) = fixture();
|
||||
policy.schema_version = 3;
|
||||
let scope = &mut policy.scopes[0];
|
||||
scope.allowed_services.clear();
|
||||
scope.windows_update_max_runtime_seconds = Some(3600);
|
||||
caps.extend(["run_script", "system:run_script", "script.powershell/1", "script.powershell.process_remote_signed/1", WINDOWS_UPDATE_LONG_CAPABILITY].map(str::to_owned));
|
||||
caps.extend(
|
||||
[
|
||||
"run_script",
|
||||
"system:run_script",
|
||||
"script.powershell/1",
|
||||
"script.powershell.process_remote_signed/1",
|
||||
WINDOWS_UPDATE_LONG_CAPABILITY,
|
||||
]
|
||||
.map(str::to_owned),
|
||||
);
|
||||
for (script, seconds, expected) in [
|
||||
(WINDOWS_UPDATE_SCRIPT_UTF8, 3600, true),
|
||||
(WINDOWS_UPDATE_IDENTITY_PROBE, 30, true),
|
||||
@@ -614,13 +666,18 @@ mod tests {
|
||||
("Write-Output 12", 30, false),
|
||||
] {
|
||||
job.action = Action::RunScript {
|
||||
interpreter:"powershell".into(), script_utf8:script.into(),
|
||||
arguments:vec![], expected_stdout:None,
|
||||
windows_execution_profile:Some(WindowsExecutionProfile::PowerShell51RemoteSigned),
|
||||
privileged_script_profile:Some(PrivilegedScriptProfile::FullMaintenanceV1),
|
||||
interpreter: "powershell".into(),
|
||||
script_utf8: script.into(),
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
windows_execution_profile: Some(WindowsExecutionProfile::PowerShell51RemoteSigned),
|
||||
privileged_script_profile: Some(PrivilegedScriptProfile::FullMaintenanceV1),
|
||||
};
|
||||
job.max_runtime_seconds = seconds;
|
||||
assert_eq!(policy.permits("selected", &job, &caps, Utc::now()), expected);
|
||||
assert_eq!(
|
||||
policy.permits("selected", &job, &caps, Utc::now()),
|
||||
expected
|
||||
);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
|
||||
Reference in New Issue
Block a user