Plan device actions exclusively as approved scripts and provide reboot library revisions
This commit is contained in:
+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
|
||||
|
||||
Reference in New Issue
Block a user