2056 lines
84 KiB
Rust
2056 lines
84 KiB
Rust
//! Shared application services. HTTP/MCP adapters only establish a Principal and
|
|
//! delegate here. No transport-specific approval shortcut exists.
|
|
use crate::auth::Principal;
|
|
use axum::{
|
|
Json, Router,
|
|
extract::{Path, State},
|
|
http::{HeaderMap, StatusCode},
|
|
response::{IntoResponse, Response},
|
|
routing::{get, post},
|
|
};
|
|
use chrono::{DateTime, Utc};
|
|
use rmm_domain::jobs::*;
|
|
use serde::{Deserialize, Serialize};
|
|
use serde_json::{Value, json};
|
|
use sqlx::{Postgres, Row, Transaction};
|
|
use uuid::Uuid;
|
|
|
|
#[derive(Debug)]
|
|
pub struct Error(pub StatusCode, pub &'static str);
|
|
impl From<sqlx::Error> for Error {
|
|
fn from(_: sqlx::Error) -> Self {
|
|
Self(StatusCode::SERVICE_UNAVAILABLE, "DEPENDENCY_UNAVAILABLE")
|
|
}
|
|
}
|
|
impl From<anyhow::Error> for Error {
|
|
fn from(_: anyhow::Error) -> Self {
|
|
Self(StatusCode::SERVICE_UNAVAILABLE, "DEPENDENCY_UNAVAILABLE")
|
|
}
|
|
}
|
|
impl From<serde_json::Error> for Error {
|
|
fn from(_: serde_json::Error) -> Self {
|
|
Self(StatusCode::BAD_REQUEST, "VALIDATION_ERROR")
|
|
}
|
|
}
|
|
impl IntoResponse for Error {
|
|
fn into_response(self) -> Response {
|
|
(self.0,Json(json!({"code":self.1,"message":"operation could not be completed","retryable":self.0.is_server_error(),"correlation_id":Uuid::new_v4(),"details":{}}))).into_response()
|
|
}
|
|
}
|
|
type Result<T> = std::result::Result<T, Error>;
|
|
fn fail(code: &'static str) -> Error {
|
|
Error(StatusCode::CONFLICT, code)
|
|
}
|
|
fn missing() -> Error {
|
|
Error(StatusCode::NOT_FOUND, "NOT_FOUND")
|
|
}
|
|
pub fn scope(p: &Principal, tenant: Uuid, write: bool) -> Result<()> {
|
|
if p.tenant != tenant {
|
|
return Err(missing());
|
|
}
|
|
if write && !p.operator {
|
|
return Err(Error(StatusCode::FORBIDDEN, "FORBIDDEN"));
|
|
}
|
|
Ok(())
|
|
}
|
|
pub(crate) async fn principal(
|
|
state: &crate::State,
|
|
h: &HeaderMap,
|
|
write: bool,
|
|
) -> Result<Principal> {
|
|
state
|
|
.auth
|
|
.principal(state, h, write)
|
|
.await
|
|
.map_err(|s| Error(s, crate::auth::error_code(s)))
|
|
}
|
|
pub fn routes(r: Router<crate::State>) -> Router<crate::State> {
|
|
r.route("/api/v1/tenants/{tenant}/operation-plans", post(plan_http))
|
|
.route(
|
|
"/api/v1/tenants/{tenant}/operation-plans/{plan}",
|
|
get(plan_get_http),
|
|
)
|
|
.route(
|
|
"/api/v1/tenants/{tenant}/operation-plans/{plan}/submit",
|
|
post(submit_http),
|
|
)
|
|
.route(
|
|
"/api/v1/tenants/{tenant}/operation-plans/{plan}/authorizations",
|
|
post(authorize_http),
|
|
)
|
|
.route("/api/v1/tenants/{tenant}/operations", get(operations_http))
|
|
.route(
|
|
"/api/v1/tenants/{tenant}/operations/{operation}",
|
|
get(operation_http),
|
|
)
|
|
.route("/api/v1/tenants/{tenant}/jobs/{job}", get(job_http))
|
|
.route(
|
|
"/api/v1/tenants/{tenant}/jobs/{job}/cancel",
|
|
post(cancel_http),
|
|
)
|
|
.route(
|
|
"/api/v1/tenants/{tenant}/jobs/{job}/unknown-closure",
|
|
post(close_unknown_http),
|
|
)
|
|
}
|
|
#[derive(Clone, Deserialize, Serialize, schemars::JsonSchema)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct Targets {
|
|
pub asset_ids: Vec<Uuid>,
|
|
}
|
|
#[derive(Clone, Deserialize, Serialize, schemars::JsonSchema)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct Schedule {
|
|
pub not_before: DateTime<Utc>,
|
|
pub start_before: DateTime<Utc>,
|
|
}
|
|
#[derive(Clone, Deserialize, Serialize, schemars::JsonSchema)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct Rollout {
|
|
pub max_parallel: u32,
|
|
pub halt_after_failures: u32,
|
|
}
|
|
#[derive(Clone, Deserialize, Serialize, schemars::JsonSchema)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct PlanInput {
|
|
pub targets: Targets,
|
|
pub action: Action,
|
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
|
pub script_variants: Vec<Variant>,
|
|
pub execution_identity: String,
|
|
pub schedule: Schedule,
|
|
pub max_runtime_seconds: u32,
|
|
pub max_output_bytes: u32,
|
|
pub rollout: Rollout,
|
|
pub reason: String,
|
|
#[serde(default)]
|
|
pub artifact_ids: Vec<Uuid>,
|
|
}
|
|
#[derive(Clone, Deserialize, schemars::JsonSchema)]
|
|
#[serde(untagged)]
|
|
pub enum PlanRequest {
|
|
AgentUpdate(Box<AgentUpdatePlanInput>),
|
|
Typed(Box<PlanInput>),
|
|
Web(Box<WebPlanInput>),
|
|
}
|
|
#[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,
|
|
}
|
|
#[derive(Clone, Deserialize, schemars::JsonSchema)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct WebPlanInput {
|
|
tenant_id: Uuid,
|
|
action: String,
|
|
targets: Targets,
|
|
parameters: WebParameters,
|
|
schedule: WebSchedule,
|
|
rollout: Rollout,
|
|
reason: String,
|
|
#[serde(default)]
|
|
artifact_ids: Vec<Uuid>,
|
|
}
|
|
#[derive(Clone, Deserialize, schemars::JsonSchema)]
|
|
#[serde(deny_unknown_fields)]
|
|
struct WebSchedule {
|
|
not_before: DateTime<Utc>,
|
|
start_before: DateTime<Utc>,
|
|
offline_policy: String,
|
|
}
|
|
#[derive(Clone, Deserialize, Serialize, schemars::JsonSchema)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct Variant {
|
|
os_family: String,
|
|
interpreter: String,
|
|
encoding: String,
|
|
script_utf8: String,
|
|
#[serde(
|
|
default,
|
|
deserialize_with = "rmm_domain::jobs::deserialize_windows_execution_profile",
|
|
skip_serializing_if = "Option::is_none"
|
|
)]
|
|
#[schemars(with = "WindowsExecutionProfile")]
|
|
windows_execution_profile: Option<WindowsExecutionProfile>,
|
|
}
|
|
#[derive(Clone, Deserialize, Serialize, schemars::JsonSchema)]
|
|
#[serde(deny_unknown_fields)]
|
|
struct WebParameters {
|
|
#[serde(
|
|
default,
|
|
deserialize_with = "deserialize_privileged_script_profile",
|
|
skip_serializing_if = "Option::is_none"
|
|
)]
|
|
#[schemars(with = "PrivilegedScriptProfile")]
|
|
privileged_script_profile: Option<PrivilegedScriptProfile>,
|
|
execution_identity: String,
|
|
timeout_seconds: u32,
|
|
max_output_bytes: u32,
|
|
variants: Option<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(t) => return Ok(*t),
|
|
Self::Web(w) => *w,
|
|
};
|
|
if w.tenant_id != tenant {
|
|
return Err(missing());
|
|
}
|
|
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")),
|
|
};
|
|
// 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(),
|
|
execution_identity: p.execution_identity,
|
|
schedule: Schedule {
|
|
not_before: w.schedule.not_before,
|
|
start_before: w.schedule.start_before,
|
|
},
|
|
max_runtime_seconds: p.timeout_seconds,
|
|
max_output_bytes: p.max_output_bytes,
|
|
rollout: w.rollout,
|
|
reason: w.reason,
|
|
artifact_ids: w.artifact_ids,
|
|
})
|
|
}
|
|
}
|
|
/// 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.
|
|
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
|
|
}
|
|
fn validate_variants(variants: &[Variant]) -> Result<()> {
|
|
if variants.is_empty() || variants.len() > 2 {
|
|
return Err(fail("AMBIGUOUS_TARGET"));
|
|
}
|
|
let mut platforms = std::collections::HashSet::new();
|
|
for v in variants {
|
|
let action = Action::RunScript {
|
|
interpreter: v.interpreter.clone(),
|
|
script_utf8: v.script_utf8.clone(),
|
|
arguments: vec![],
|
|
expected_stdout: None,
|
|
windows_execution_profile: v.windows_execution_profile,
|
|
privileged_script_profile: None,
|
|
};
|
|
if v.encoding != "utf-8"
|
|
|| action.script_platform() != Some(v.os_family.as_str())
|
|
|| !action.validate()
|
|
{
|
|
return Err(fail("UNSUPPORTED_CAPABILITY"));
|
|
}
|
|
if !platforms.insert(v.os_family.as_str()) {
|
|
return Err(fail("AMBIGUOUS_TARGET"));
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
fn capabilities(value: Value) -> Result<Vec<String>> {
|
|
serde_json::from_value(value).map_err(|_| fail("UNSUPPORTED_CAPABILITY"))
|
|
}
|
|
fn target_action(input: &PlanInput, caps: &[String]) -> Result<Action> {
|
|
if !input
|
|
.action
|
|
.valid_execution_identity(&input.execution_identity)
|
|
|| (input.execution_identity == "system"
|
|
&& matches!(input.action, Action::RunScript { .. })
|
|
&& !input.action.full_maintenance())
|
|
{
|
|
return Err(fail("VALIDATION_ERROR"));
|
|
}
|
|
if input.script_variants.is_empty() {
|
|
return Ok(input.action.clone());
|
|
}
|
|
validate_variants(&input.script_variants)?;
|
|
let Action::RunScript {
|
|
interpreter,
|
|
script_utf8,
|
|
arguments,
|
|
expected_stdout,
|
|
windows_execution_profile,
|
|
privileged_script_profile,
|
|
} = &input.action
|
|
else {
|
|
return Err(fail("VALIDATION_ERROR"));
|
|
};
|
|
let first = &input.script_variants[0];
|
|
if interpreter != &first.interpreter
|
|
|| script_utf8 != &first.script_utf8
|
|
|| windows_execution_profile != &first.windows_execution_profile
|
|
|| (input.execution_identity == "root"
|
|
&& input
|
|
.script_variants
|
|
.iter()
|
|
.any(|v| v.windows_execution_profile.is_some()))
|
|
{
|
|
return Err(fail("VALIDATION_ERROR"));
|
|
}
|
|
let platform = match (
|
|
caps.iter().any(|c| c == "linux.base/1"),
|
|
caps.iter().any(|c| c == "windows.base/1"),
|
|
) {
|
|
(true, false) => "linux",
|
|
(false, true) => "windows",
|
|
_ => return Err(fail("UNSUPPORTED_CAPABILITY")),
|
|
};
|
|
let v = input
|
|
.script_variants
|
|
.iter()
|
|
.find(|v| v.os_family == platform)
|
|
.ok_or_else(|| fail("UNSUPPORTED_CAPABILITY"))?;
|
|
Ok(Action::RunScript {
|
|
interpreter: v.interpreter.clone(),
|
|
script_utf8: v.script_utf8.clone(),
|
|
arguments: arguments.clone(),
|
|
expected_stdout: expected_stdout.clone(),
|
|
windows_execution_profile: v.windows_execution_profile,
|
|
privileged_script_profile: *privileged_script_profile,
|
|
})
|
|
}
|
|
async fn policy(tx: &mut Transaction<'_, Postgres>) -> Result<()> {
|
|
let stopped: bool = sqlx::query_scalar("SELECT changes_stopped FROM tenants")
|
|
.fetch_one(&mut **tx)
|
|
.await?;
|
|
if stopped {
|
|
return Err(fail("POLICY_DENIED"));
|
|
}
|
|
Ok(())
|
|
}
|
|
pub async fn plan(
|
|
state: &crate::State,
|
|
p: &Principal,
|
|
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
|
|
}
|
|
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)?;
|
|
let now = Utc::now();
|
|
if input.targets.asset_ids.is_empty()
|
|
|| input.targets.asset_ids.len() > 100
|
|
|| !input.action.validate_plan_shape()
|
|
|| !input
|
|
.action
|
|
.valid_execution_identity(&input.execution_identity)
|
|
|| !matches!(
|
|
input.execution_identity.as_str(),
|
|
"agent_service" | "root" | "system"
|
|
)
|
|
|| !(1..=3600).contains(&input.max_runtime_seconds)
|
|
|| input.max_output_bytes == 0
|
|
|| input.max_output_bytes > 262144
|
|
|| input.schedule.start_before <= now
|
|
|| input.schedule.not_before >= input.schedule.start_before
|
|
|| input.schedule.start_before > now + chrono::Duration::days(7)
|
|
|| input.reason.is_empty()
|
|
|| input.reason.len() > 2048
|
|
|| !(1..=10).contains(&input.rollout.max_parallel)
|
|
|| input.rollout.halt_after_failures == 0
|
|
{
|
|
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();
|
|
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant).await?;
|
|
policy(&mut tx).await?;
|
|
crate::permissions::require_principal(&mut tx, p, "operations:plan").await?;
|
|
if let Some(permission) = crate::root_policy::execution_permission(&input.execution_identity) {
|
|
crate::permissions::require_principal(&mut tx, p, permission).await?;
|
|
}
|
|
if matches!(input.action, Action::AptNativeAcceptance { .. }) {
|
|
crate::permissions::require_principal(&mut tx, p, "apt:native_acceptance").await?;
|
|
}
|
|
if matches!(input.action, Action::RunScript { .. }) {
|
|
crate::permissions::require_principal(&mut tx, p, "scripts:execute").await?;
|
|
}
|
|
if matches!(input.action, Action::UpdateAgent { .. }) {
|
|
crate::permissions::require_principal(&mut tx, p, "updates:apply").await?;
|
|
}
|
|
if matches!(input.action, Action::QueryLogs { .. }) {
|
|
crate::permissions::require_principal(&mut tx, p, "logs:read").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 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?;
|
|
if rows.len() != 1 {
|
|
return Err(fail(if rows.is_empty() {
|
|
"NOT_FOUND"
|
|
} else {
|
|
"AMBIGUOUS_TARGET"
|
|
}));
|
|
}
|
|
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)?
|
|
};
|
|
if !action.valid_job_limits(input.max_runtime_seconds, input.max_output_bytes) {
|
|
return Err(fail("VALIDATION_ERROR"));
|
|
}
|
|
if !action.available_for(&input.execution_identity, &caps) {
|
|
return Err(fail("UNSUPPORTED_CAPABILITY"));
|
|
}
|
|
let payload = JobPayload {
|
|
schema_version: 1,
|
|
tenant_id: tenant,
|
|
asset_id: asset,
|
|
agent_id: row.get("agent_id"),
|
|
enrollment_generation: row.get::<i64, _>("enrollment_generation") as u64,
|
|
assignment_version: row.get::<i64, _>("assignment_version") as u64,
|
|
job_id: Uuid::new_v4(),
|
|
attempt_id: Uuid::new_v4(),
|
|
action,
|
|
execution_identity: input.execution_identity.clone(),
|
|
not_before: input.schedule.not_before,
|
|
start_before: input.schedule.start_before,
|
|
max_runtime_seconds: input.max_runtime_seconds,
|
|
max_output_bytes: input.max_output_bytes,
|
|
};
|
|
let script_sha256 = if let Action::RunScript { script_utf8, .. } = &payload.action {
|
|
Some(hash(script_utf8.as_bytes()))
|
|
} else {
|
|
None
|
|
};
|
|
crate::root_policy::authorize(&mut tx, &p.name, &payload).await?;
|
|
if encode(&payload)?.len() > 65536 {
|
|
return Err(Error(StatusCode::PAYLOAD_TOO_LARGE, "QUOTA_EXCEEDED"));
|
|
}
|
|
jobs.push(PlannedJob {
|
|
job_payload_hash: hash(&encode(&payload)?),
|
|
payload,
|
|
script_sha256,
|
|
});
|
|
}
|
|
let artifact_references = jobs
|
|
.iter()
|
|
.flat_map(|job| {
|
|
artifacts.iter().map(|artifact| JobArtifactReference {
|
|
job_id: job.payload.job_id,
|
|
attempt_id: job.payload.attempt_id,
|
|
artifact: artifact.clone(),
|
|
})
|
|
})
|
|
.collect();
|
|
let payload = PlanPayload {
|
|
schema_version: 1,
|
|
plan_id: Uuid::new_v4(),
|
|
tenant_id: tenant,
|
|
principal: p.name.clone(),
|
|
reason: input.reason,
|
|
jobs,
|
|
max_parallel: input.rollout.max_parallel,
|
|
halt_after_failures: input.rollout.halt_after_failures,
|
|
recipe_references,
|
|
artifact_references,
|
|
script_revision,
|
|
};
|
|
crate::script_library::validate_plan_bindings(&payload)?;
|
|
crate::windows_msi_catalog::validate_plan_bindings(&payload)?;
|
|
crate::agent_updates::validate_plan_bindings(&payload)?;
|
|
let bytes = encode(&payload)?;
|
|
let plan_hash = hash(&bytes);
|
|
sqlx::query("INSERT INTO operation_plans(tenant_id,plan_id,principal,payload,plan_hash,expires_at) VALUES($1,$2,$3,$4,$5,$6)").bind(tenant).bind(payload.plan_id).bind(&p.name).bind(&bytes).bind(&plan_hash).bind(input.schedule.start_before).execute(&mut *tx).await?;
|
|
tx.commit().await?;
|
|
plan_view(&payload, &plan_hash, None, &bytes)
|
|
}
|
|
fn plan_view(
|
|
plan: &PlanPayload,
|
|
hash: &str,
|
|
approval: Option<String>,
|
|
bytes: &[u8],
|
|
) -> Result<Value> {
|
|
let jobs=plan.jobs.iter().map(|j|json!({"job_id":j.payload.job_id,"attempt_id":j.payload.attempt_id,"asset_id":j.payload.asset_id,"agent_id":j.payload.agent_id,"job_payload_hash":j.job_payload_hash,"script_sha256":j.script_sha256,"payload":j.payload})).collect::<Vec<_>>();
|
|
Ok(
|
|
json!({"plan_id":plan.plan_id,"plan_hash":hash,"payload":plan,"plan_payload":plan,"plan_payload_bytes":bytes,"resolved_targets":plan.jobs.iter().map(|j|json!({"asset_id":j.payload.asset_id,"agent_id":j.payload.agent_id})).collect::<Vec<_>>(),"excluded_targets":[],"jobs":jobs,"authorization_status":if plan.jobs.iter().all(|j|j.payload.action.validate()){"required"}else{"unsupported_manifest_required"},"approval_state":approval,"expires_at":plan.jobs.first().map(|j|j.payload.start_before)}),
|
|
)
|
|
}
|
|
async fn load_plan(
|
|
tx: &mut Transaction<'_, Postgres>,
|
|
id: Uuid,
|
|
) -> Result<(PlanPayload, String, Vec<u8>)> {
|
|
let r = sqlx::query("SELECT payload,plan_hash FROM operation_plans WHERE plan_id=$1")
|
|
.bind(id)
|
|
.fetch_optional(&mut **tx)
|
|
.await?
|
|
.ok_or_else(missing)?;
|
|
let bytes: Vec<u8> = r.get("payload");
|
|
let h: String = r.get("plan_hash");
|
|
if hash(&bytes) != h {
|
|
return Err(fail("PLAN_HASH_MISMATCH"));
|
|
}
|
|
Ok((serde_json::from_slice(&bytes)?, h, bytes))
|
|
}
|
|
async fn recheck(tx: &mut Transaction<'_, Postgres>, plan: &PlanPayload) -> Result<()> {
|
|
crate::script_library::validate_plan_bindings(plan)?;
|
|
crate::windows_msi_catalog::validate_plan_bindings(plan)?;
|
|
crate::agent_updates::validate_plan_bindings(plan)?;
|
|
policy(tx).await?;
|
|
let current_artifacts = if let Some(Action::UpdateAgent { update }) =
|
|
plan.jobs.first().map(|j| &j.payload.action)
|
|
{
|
|
crate::agent_updates::resolve_artifacts(
|
|
tx,
|
|
plan.tenant_id,
|
|
&update
|
|
.manifest()
|
|
.map_err(|_| fail("INVALID_AGENT_RELEASE"))?
|
|
.artifacts,
|
|
)
|
|
.await?
|
|
} else {
|
|
crate::catalog::resolve_artifacts(
|
|
tx,
|
|
plan.tenant_id,
|
|
&plan
|
|
.artifact_references
|
|
.iter()
|
|
.map(|r| r.artifact.artifact_id)
|
|
.collect::<Vec<_>>(),
|
|
)
|
|
.await?
|
|
};
|
|
for reference in &plan.artifact_references {
|
|
if !current_artifacts.contains(&reference.artifact)
|
|
|| !plan.jobs.iter().any(|j| {
|
|
j.payload.job_id == reference.job_id && j.payload.attempt_id == reference.attempt_id
|
|
})
|
|
{
|
|
return Err(fail("ARTIFACT_BINDING_MISMATCH"));
|
|
}
|
|
}
|
|
crate::permissions::require(tx, &plan.principal, "operations:plan").await?;
|
|
if plan
|
|
.jobs
|
|
.iter()
|
|
.any(|j| matches!(j.payload.action, Action::RunScript { .. }))
|
|
{
|
|
crate::permissions::require(tx, &plan.principal, "scripts:execute").await?;
|
|
}
|
|
if plan
|
|
.jobs
|
|
.iter()
|
|
.any(|j| matches!(j.payload.action, Action::UpdateAgent { .. }))
|
|
{
|
|
crate::permissions::require(tx, &plan.principal, "updates:apply").await?;
|
|
}
|
|
if plan
|
|
.jobs
|
|
.iter()
|
|
.any(|j| matches!(j.payload.action, Action::QueryLogs { .. }))
|
|
{
|
|
crate::permissions::require(tx, &plan.principal, "logs:read").await?;
|
|
}
|
|
let mut references = Vec::new();
|
|
for job in &plan.jobs {
|
|
if !job.payload.action.valid_job_limits(
|
|
job.payload.max_runtime_seconds,
|
|
job.payload.max_output_bytes,
|
|
) {
|
|
return Err(fail("VALIDATION_ERROR"));
|
|
}
|
|
if !job.payload.action.validate() {
|
|
return Err(Error(StatusCode::CONFLICT, "APT_MANIFEST_REQUIRED"));
|
|
}
|
|
crate::root_policy::authorize(tx, &plan.principal, &job.payload).await?;
|
|
crate::catalog::check(tx, &job.payload.action).await?;
|
|
references.extend(crate::catalog::references(tx, &job.payload.action).await?);
|
|
if job.payload.start_before <= Utc::now() {
|
|
return Err(fail("PLAN_EXPIRED"));
|
|
}
|
|
let r=sqlx::query("SELECT enrollment_generation,assignment_version,capabilities FROM agent_installations WHERE agent_id=$1 AND asset_id=$2 AND revoked_at IS NULL FOR SHARE").bind(job.payload.agent_id).bind(job.payload.asset_id).fetch_optional(&mut **tx).await?.ok_or_else(||fail("AUTHORIZATION_REVOKED"))?;
|
|
if r.get::<i64, _>("assignment_version") as u64 != job.payload.assignment_version
|
|
|| r.get::<i64, _>("enrollment_generation") as u64 != job.payload.enrollment_generation
|
|
{
|
|
return Err(fail("AUTHORIZATION_REVOKED"));
|
|
}
|
|
let caps = capabilities(r.get("capabilities"))?;
|
|
if !job
|
|
.payload
|
|
.action
|
|
.available_for(&job.payload.execution_identity, &caps)
|
|
{
|
|
return Err(fail("UNSUPPORTED_CAPABILITY"));
|
|
}
|
|
if let Action::RunScript { script_utf8, .. } = &job.payload.action
|
|
&& job.script_sha256.as_deref() != Some(hash(script_utf8.as_bytes()).as_str())
|
|
{
|
|
return Err(fail("PLAN_HASH_MISMATCH"));
|
|
}
|
|
if hash(&encode(&job.payload)?) != job.job_payload_hash {
|
|
return Err(fail("PLAN_HASH_MISMATCH"));
|
|
}
|
|
}
|
|
references.sort();
|
|
references.dedup();
|
|
if references != plan.recipe_references {
|
|
return Err(fail("RECIPE_BINDING_MISMATCH"));
|
|
}
|
|
Ok(())
|
|
}
|
|
#[derive(Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct Submit {
|
|
pub idempotency_key: String,
|
|
}
|
|
pub async fn submit(
|
|
state: &crate::State,
|
|
p: &Principal,
|
|
tenant: Uuid,
|
|
id: Uuid,
|
|
input: Submit,
|
|
) -> Result<Value> {
|
|
scope(p, tenant, true)?;
|
|
if input.idempotency_key.is_empty() || input.idempotency_key.len() > 128 {
|
|
return Err(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"));
|
|
}
|
|
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant).await?;
|
|
// Serialize idempotency and same-plan submit, including competing principals.
|
|
crate::permissions::require_principal(&mut tx, p, "operations:submit").await?;
|
|
crate::permissions::require_principal(&mut tx, p, "operations:read").await?;
|
|
sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1,0))")
|
|
.bind(format!(
|
|
"submit:{tenant}:{}:{}",
|
|
p.name, input.idempotency_key
|
|
))
|
|
.execute(&mut *tx)
|
|
.await?;
|
|
sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1,0))")
|
|
.bind(format!("plan-submit:{tenant}:{id}"))
|
|
.execute(&mut *tx)
|
|
.await?;
|
|
sqlx::query("SELECT plan_id FROM operation_plans WHERE plan_id=$1")
|
|
.bind(id)
|
|
.fetch_optional(&mut *tx)
|
|
.await?
|
|
.ok_or_else(missing)?;
|
|
let request_hash = hash(id.as_bytes());
|
|
let (plan, _, _) = load_plan(&mut tx, id).await?;
|
|
for job in &plan.jobs {
|
|
if matches!(job.payload.action, Action::RunScript { .. }) {
|
|
crate::permissions::require_principal(&mut tx, p, "scripts:execute").await?;
|
|
}
|
|
if matches!(job.payload.action, Action::UpdateAgent { .. }) {
|
|
crate::permissions::require_principal(&mut tx, p, "updates:apply").await?;
|
|
}
|
|
if matches!(job.payload.action, Action::QueryLogs { .. }) {
|
|
crate::permissions::require_principal(&mut tx, p, "logs:read").await?;
|
|
}
|
|
if let Some(permission) =
|
|
crate::root_policy::execution_permission(&job.payload.execution_identity)
|
|
{
|
|
crate::permissions::require_principal(&mut tx, p, permission).await?;
|
|
crate::root_policy::authorize(&mut tx, &p.name, &job.payload).await?;
|
|
}
|
|
if matches!(job.payload.action, Action::AptNativeAcceptance { .. }) {
|
|
crate::permissions::require_principal(&mut tx, p, "apt:native_acceptance").await?;
|
|
}
|
|
}
|
|
if let Some(row)=sqlx::query("SELECT request_hash,operation_id FROM operation_submissions WHERE principal=$1 AND idempotency_key=$2").bind(&p.name).bind(&input.idempotency_key).fetch_optional(&mut *tx).await? {
|
|
if row.get::<String,_>("request_hash")!=request_hash{return Err(fail("IDEMPOTENCY_CONFLICT"))}
|
|
let op=row.get("operation_id");tx.commit().await?;return operation(state,p,tenant,op).await;
|
|
}
|
|
if let Some(op) =
|
|
sqlx::query_scalar::<_, Uuid>("SELECT operation_id FROM approval_requests WHERE plan_id=$1")
|
|
.bind(id)
|
|
.fetch_optional(&mut *tx)
|
|
.await?
|
|
{
|
|
sqlx::query("INSERT INTO operation_submissions VALUES($1,$2,$3,$4,$5)")
|
|
.bind(tenant)
|
|
.bind(&p.name)
|
|
.bind(&input.idempotency_key)
|
|
.bind(&request_hash)
|
|
.bind(op)
|
|
.execute(&mut *tx)
|
|
.await?;
|
|
tx.commit().await?;
|
|
return operation(state, p, tenant, op).await;
|
|
}
|
|
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?;
|
|
sqlx::query("INSERT INTO operation_submissions VALUES($1,$2,$3,$4,$5)")
|
|
.bind(tenant)
|
|
.bind(&p.name)
|
|
.bind(&input.idempotency_key)
|
|
.bind(&request_hash)
|
|
.bind(op)
|
|
.execute(&mut *tx)
|
|
.await?;
|
|
tx.commit().await?;
|
|
operation(state, p, tenant, op).await
|
|
}
|
|
#[derive(Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
struct Authorize {
|
|
plan_hash: String,
|
|
#[serde(default = "approve_decision")]
|
|
decision: String,
|
|
}
|
|
fn approve_decision() -> String {
|
|
"approve".into()
|
|
}
|
|
async fn authorize_http(
|
|
State(state): State<crate::State>,
|
|
h: HeaderMap,
|
|
Path((tenant, id)): Path<(Uuid, Uuid)>,
|
|
Json(input): Json<Authorize>,
|
|
) -> Result<Json<Value>> {
|
|
let p = principal(&state, &h, true).await?;
|
|
scope(&p, tenant, true)?;
|
|
let session = p
|
|
.session_hash
|
|
.as_ref()
|
|
.ok_or(Error(StatusCode::FORBIDDEN, "INTERACTIVE_AUTH_REQUIRED"))?;
|
|
if !matches!(input.decision.as_str(), "approve" | "reject") {
|
|
return Err(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"));
|
|
}
|
|
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant).await?;
|
|
let row = sqlx::query(
|
|
"SELECT operation_id,approval_state FROM approval_requests WHERE plan_id=$1 FOR UPDATE",
|
|
)
|
|
.bind(id)
|
|
.fetch_optional(&mut *tx)
|
|
.await?
|
|
.ok_or_else(missing)?;
|
|
crate::permissions::require_principal(&mut tx, &p, "plans:approve").await?;
|
|
let op: Uuid = row.get("operation_id");
|
|
let status: String = row.get("approval_state");
|
|
let (plan, ph, _) = load_plan(&mut tx, id).await?;
|
|
if ph != input.plan_hash {
|
|
return Err(fail("PLAN_HASH_MISMATCH"));
|
|
}
|
|
if status == "approved" && input.decision == "approve" {
|
|
tx.commit().await?;
|
|
return Ok(Json(operation(&state, &p, tenant, op).await?));
|
|
}
|
|
if status != "pending_approval" {
|
|
return Err(fail("AUTHORIZATION_REVOKED"));
|
|
}
|
|
if input.decision == "reject" {
|
|
sqlx::query("UPDATE approval_requests SET approval_state='rejected' WHERE operation_id=$1")
|
|
.bind(op)
|
|
.execute(&mut *tx)
|
|
.await?;
|
|
} else {
|
|
recheck(&mut tx, &plan).await?;
|
|
// Both requester and approver retain explicit operator rights: the only
|
|
// shipped dev principals are fixed-scope and cannot grant memberships.
|
|
if !requester_enabled(&state, &plan.principal, tenant) {
|
|
return Err(fail("AUTHORIZATION_REVOKED"));
|
|
}
|
|
for job in &plan.jobs {
|
|
if matches!(job.payload.action, Action::RunScript { .. }) {
|
|
crate::permissions::require_principal(&mut tx, &p, "scripts:execute").await?;
|
|
}
|
|
if matches!(job.payload.action, Action::UpdateAgent { .. }) {
|
|
crate::permissions::require_principal(&mut tx, &p, "updates:apply").await?;
|
|
}
|
|
if let Some(permission) =
|
|
crate::root_policy::execution_permission(&job.payload.execution_identity)
|
|
{
|
|
crate::permissions::require_principal(&mut tx, &p, permission).await?;
|
|
}
|
|
crate::root_policy::authorize(&mut tx, &p.name, &job.payload).await?;
|
|
}
|
|
let authorization = Uuid::new_v4();
|
|
sqlx::query("INSERT INTO authorizations(tenant_id,authorization_id,operation_id,plan_id,plan_hash,principal,session_hash,approval_origin,testsimulation,policy_version) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,1)").bind(tenant).bind(authorization).bind(op).bind(id).bind(&ph).bind(&p.name).bind(session).bind(p.approval_origin()).bind(p.testsimulation).execute(&mut *tx).await?;
|
|
sqlx::query("INSERT INTO operations VALUES($1,$2,$3)")
|
|
.bind(tenant)
|
|
.bind(op)
|
|
.bind(authorization)
|
|
.execute(&mut *tx)
|
|
.await?;
|
|
for j in &plan.jobs {
|
|
sqlx::query("INSERT INTO jobs(tenant_id,job_id,attempt_id,operation_id,agent_id,asset_id,payload,payload_hash,resource) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9)").bind(tenant).bind(j.payload.job_id).bind(j.payload.attempt_id).bind(op).bind(j.payload.agent_id).bind(j.payload.asset_id).bind(encode(&j.payload)?).bind(&j.job_payload_hash).bind(j.payload.action.resource()).execute(&mut *tx).await?;
|
|
sqlx::query("INSERT INTO outbox(tenant_id,job_id,attempt_id) VALUES($1,$2,$3)")
|
|
.bind(tenant)
|
|
.bind(j.payload.job_id)
|
|
.bind(j.payload.attempt_id)
|
|
.execute(&mut *tx)
|
|
.await?;
|
|
}
|
|
sqlx::query("UPDATE approval_requests SET approval_state='approved' WHERE operation_id=$1")
|
|
.bind(op)
|
|
.execute(&mut *tx)
|
|
.await?;
|
|
}
|
|
sqlx::query("INSERT INTO audit_events VALUES($1,$2,$3,'plan_authorization',$4,now())").bind(tenant).bind(Uuid::new_v4()).bind(&p.name).bind(json!({"plan_id":id,"plan_hash":ph,"operation_id":op,"decision":input.decision,"approval_origin":p.approval_origin(),"testsimulation":p.testsimulation,"profile":std::env::var("RMM_PROFILE").unwrap_or_default()})).execute(&mut *tx).await?;
|
|
tx.commit().await?;
|
|
Ok(Json(operation(&state, &p, tenant, op).await?))
|
|
}
|
|
pub fn requester_enabled(state: &crate::State, name: &str, tenant: Uuid) -> bool {
|
|
state.auth.operator_enabled(name, tenant)
|
|
}
|
|
pub async fn operation(
|
|
state: &crate::State,
|
|
p: &Principal,
|
|
tenant: Uuid,
|
|
id: Uuid,
|
|
) -> Result<Value> {
|
|
scope(p, tenant, false)?;
|
|
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant).await?;
|
|
crate::permissions::require_principal(&mut tx, p, "operations:read").await?;
|
|
let row=sqlx::query("SELECT r.plan_id,r.approval_state,p.payload,p.plan_hash,p.expires_at FROM approval_requests r JOIN operation_plans p USING(tenant_id,plan_id) WHERE operation_id=$1").bind(id).fetch_optional(&mut *tx).await?.ok_or_else(missing)?;
|
|
let plan: PlanPayload = serde_json::from_slice(&row.get::<Vec<u8>, _>("payload"))?;
|
|
let mut approval: String = row.get("approval_state");
|
|
if approval == "pending_approval" && row.get::<DateTime<Utc>, _>("expires_at") <= Utc::now() {
|
|
approval = "expired".into();
|
|
sqlx::query("UPDATE approval_requests SET approval_state='expired' WHERE operation_id=$1 AND approval_state='pending_approval'").bind(id).execute(&mut *tx).await?;
|
|
}
|
|
let jobs=sqlx::query("SELECT job_id,attempt_id,state,cancel_requested,revision,pending_reason FROM jobs WHERE operation_id=$1 ORDER BY job_id LIMIT 101").bind(id).fetch_all(&mut *tx).await?;
|
|
let mut counts = serde_json::Map::new();
|
|
for j in &jobs {
|
|
let s: String = j.get("state");
|
|
let n = counts.get(&s).and_then(Value::as_u64).unwrap_or(0) + 1;
|
|
counts.insert(s, json!(n));
|
|
}
|
|
let n = jobs.len() as u64;
|
|
let c = |s: &str| counts.get(s).and_then(Value::as_u64).unwrap_or(0);
|
|
let execution = if n == 0 {
|
|
None
|
|
} else {
|
|
Some(if c("unknown") > 0 {
|
|
"needs_attention"
|
|
} else if c("succeeded") == n {
|
|
"succeeded"
|
|
} else if c("succeeded")
|
|
+ c("failed")
|
|
+ c("cancelled")
|
|
+ c("expired")
|
|
+ c("closed_unknown")
|
|
== n
|
|
{
|
|
if c("succeeded") > 0 {
|
|
"partially_succeeded"
|
|
} else if c("cancelled") == n {
|
|
"cancelled"
|
|
} else {
|
|
"failed"
|
|
}
|
|
} else if c("running") + c("verifying") + c("awaiting_reboot") > 0 {
|
|
"running"
|
|
} else {
|
|
"queued"
|
|
})
|
|
};
|
|
let items = jobs.iter().map(job_summary).collect::<Vec<_>>();
|
|
tx.commit().await?;
|
|
Ok(
|
|
json!({"operation_id":id,"plan_id":plan.plan_id,"plan_hash":row.get::<String,_>("plan_hash"),"approval_state":approval,"state":approval,"planned_job_count":plan.jobs.len(),"job_count":n,"execution_state":execution,"counts":counts,"jobs":items}),
|
|
)
|
|
}
|
|
fn job_view(r: &sqlx::postgres::PgRow) -> Value {
|
|
let mut result = job_summary(r);
|
|
result["result"] = r.get::<Option<Value>, _>("result").unwrap_or(Value::Null);
|
|
result
|
|
}
|
|
fn job_summary(r: &sqlx::postgres::PgRow) -> Value {
|
|
json!({"job_id":r.get::<Uuid,_>("job_id"),"attempt_id":r.get::<Uuid,_>("attempt_id"),"state":r.get::<String,_>("state"),"cancel_requested":r.get::<bool,_>("cancel_requested"),"revision":r.get::<i64,_>("revision"),"pending_reason":r.get::<Option<String>,_>("pending_reason")})
|
|
}
|
|
pub async fn job(state: &crate::State, p: &Principal, tenant: Uuid, id: Uuid) -> Result<Value> {
|
|
scope(p, tenant, false)?;
|
|
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant).await?;
|
|
crate::permissions::require_principal(&mut tx, p, "operations:read").await?;
|
|
let r = sqlx::query(
|
|
"SELECT job_id,attempt_id,state,cancel_requested,revision,result,pending_reason FROM jobs WHERE job_id=$1",
|
|
)
|
|
.bind(id)
|
|
.fetch_optional(&mut *tx)
|
|
.await?
|
|
.ok_or_else(missing)?;
|
|
tx.commit().await?;
|
|
Ok(job_view(&r))
|
|
}
|
|
#[derive(Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct Cancel {
|
|
pub reason: String,
|
|
}
|
|
pub async fn cancel(
|
|
state: &crate::State,
|
|
p: &Principal,
|
|
tenant: Uuid,
|
|
id: Uuid,
|
|
input: Cancel,
|
|
) -> Result<Value> {
|
|
scope(p, tenant, true)?;
|
|
if input.reason.is_empty() || input.reason.len() > 1024 {
|
|
return Err(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"));
|
|
}
|
|
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant).await?;
|
|
sqlx::query("UPDATE jobs SET cancel_requested=true,state=CASE WHEN state='queued' AND NOT start_reserved THEN 'cancelled' ELSE state END WHERE job_id=$1").bind(id).execute(&mut *tx).await?;
|
|
crate::permissions::require_principal(&mut tx, p, "jobs:cancel").await?;
|
|
sqlx::query("INSERT INTO audit_events VALUES($1,$2,$3,'cancel_requested',$4,now())")
|
|
.bind(tenant)
|
|
.bind(Uuid::new_v4())
|
|
.bind(&p.name)
|
|
.bind(json!({"job_id":id,"reason":input.reason}))
|
|
.execute(&mut *tx)
|
|
.await?;
|
|
tx.commit().await?;
|
|
job(state, p, tenant, id).await
|
|
}
|
|
async fn plan_http(
|
|
State(s): State<crate::State>,
|
|
h: HeaderMap,
|
|
Path(t): Path<Uuid>,
|
|
Json(i): Json<PlanRequest>,
|
|
) -> Result<Json<Value>> {
|
|
let p = principal(&s, &h, true).await?;
|
|
Ok(Json(plan_request(&s, &p, t, i).await?))
|
|
}
|
|
async fn submit_http(
|
|
State(s): State<crate::State>,
|
|
h: HeaderMap,
|
|
Path((t, id)): Path<(Uuid, Uuid)>,
|
|
Json(i): Json<Submit>,
|
|
) -> Result<Json<Value>> {
|
|
let p = principal(&s, &h, true).await?;
|
|
Ok(Json(submit(&s, &p, t, id, i).await?))
|
|
}
|
|
async fn plan_get_http(
|
|
State(s): State<crate::State>,
|
|
h: HeaderMap,
|
|
Path((t, id)): Path<(Uuid, Uuid)>,
|
|
) -> Result<Json<Value>> {
|
|
let p = principal(&s, &h, false).await?;
|
|
scope(&p, t, false)?;
|
|
let mut tx = rmm_persistence::tenant_tx(&s.pool, t).await?;
|
|
let (plan, hash, bytes) = load_plan(&mut tx, id).await?;
|
|
crate::permissions::require_principal(&mut tx, &p, "operations:read").await?;
|
|
let approval: Option<String> =
|
|
sqlx::query_scalar("SELECT approval_state FROM approval_requests WHERE plan_id=$1")
|
|
.bind(id)
|
|
.fetch_optional(&mut *tx)
|
|
.await?;
|
|
tx.commit().await?;
|
|
Ok(Json(plan_view(&plan, &hash, approval, &bytes)?))
|
|
}
|
|
async fn operation_http(
|
|
State(s): State<crate::State>,
|
|
h: HeaderMap,
|
|
Path((t, id)): Path<(Uuid, Uuid)>,
|
|
) -> Result<Json<Value>> {
|
|
let p = principal(&s, &h, false).await?;
|
|
Ok(Json(operation(&s, &p, t, id).await?))
|
|
}
|
|
async fn job_http(
|
|
State(s): State<crate::State>,
|
|
h: HeaderMap,
|
|
Path((t, id)): Path<(Uuid, Uuid)>,
|
|
) -> Result<Json<Value>> {
|
|
let p = principal(&s, &h, false).await?;
|
|
Ok(Json(job(&s, &p, t, id).await?))
|
|
}
|
|
#[derive(Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct CloseUnknown {
|
|
pub attempt_id: Uuid,
|
|
pub revision: i64,
|
|
pub reason: String,
|
|
}
|
|
/// Human WebUI only: accept an unknown attempt as unresolved and final. The
|
|
/// effect stays unknown; there is no retry, new grant or reinterpretation.
|
|
pub async fn close_unknown(
|
|
state: &crate::State,
|
|
p: &Principal,
|
|
tenant: Uuid,
|
|
id: Uuid,
|
|
input: CloseUnknown,
|
|
) -> Result<Value> {
|
|
scope(p, tenant, true)?;
|
|
let session = p
|
|
.session_hash
|
|
.clone()
|
|
.ok_or(Error(StatusCode::FORBIDDEN, "INTERACTIVE_AUTH_REQUIRED"))?;
|
|
if input.reason.trim().is_empty() || input.reason.len() > 1024 {
|
|
return Err(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"));
|
|
}
|
|
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant).await?;
|
|
crate::permissions::require_principal(&mut tx, p, "plans:approve").await?;
|
|
let row = sqlx::query(
|
|
"SELECT attempt_id,state,revision,result FROM jobs WHERE job_id=$1 FOR UPDATE",
|
|
)
|
|
.bind(id)
|
|
.fetch_optional(&mut *tx)
|
|
.await?
|
|
.ok_or_else(missing)?;
|
|
if row.get::<Uuid, _>("attempt_id") != input.attempt_id
|
|
|| row.get::<i64, _>("revision") != input.revision
|
|
{
|
|
return Err(fail("JOB_CHANGED"));
|
|
}
|
|
if row.get::<String, _>("state") != "unknown" {
|
|
return Err(fail("JOB_NOT_UNKNOWN"));
|
|
}
|
|
let original: Option<Value> = row.get("result");
|
|
let grant: Option<Uuid> = sqlx::query_scalar(
|
|
"SELECT grant_id FROM execution_permits WHERE job_id=$1 AND attempt_id=$2",
|
|
)
|
|
.bind(id)
|
|
.bind(input.attempt_id)
|
|
.fetch_optional(&mut *tx)
|
|
.await?;
|
|
let closure = Uuid::new_v4();
|
|
sqlx::query("INSERT INTO job_unknown_closures(tenant_id,closure_id,job_id,attempt_id,grant_id,original_state,original_revision,original_result,principal,session_hash,approval_origin,testsimulation,reason) VALUES($1,$2,$3,$4,$5,'unknown',$6,$7,$8,$9,$10,$11,$12)")
|
|
.bind(tenant).bind(closure).bind(id).bind(input.attempt_id).bind(grant)
|
|
.bind(input.revision).bind(&original).bind(&p.name).bind(&session)
|
|
.bind(p.approval_origin()).bind(p.testsimulation).bind(&input.reason)
|
|
.execute(&mut *tx).await?;
|
|
let original_sha256 = original
|
|
.as_ref()
|
|
.map(|v| rmm_domain::jobs::hash(&serde_json::to_vec(v).unwrap_or_default()));
|
|
let result = json!({"stdout":[],"stderr":[],"exit_code":null,"output_truncated":false,"reboot_required":false,
|
|
"error_code":"OPERATOR_CLOSED_UNKNOWN","grant_id":grant.map(|g|g.to_string()).unwrap_or_default(),
|
|
"evidence":{"postconditions_passed":false,"effect":"unknown","closed_by_human":true,"closure_id":closure,
|
|
"original_state":"unknown","original_revision":input.revision,"original_result_sha256":original_sha256,
|
|
"retry":false,"approval_origin":p.approval_origin(),"testsimulation":p.testsimulation}});
|
|
sqlx::query("UPDATE jobs SET state='closed_unknown',revision=revision+1,result=$2,pending_reason=NULL WHERE job_id=$1 AND state='unknown'")
|
|
.bind(id)
|
|
.bind(&result)
|
|
.execute(&mut *tx)
|
|
.await?;
|
|
sqlx::query("INSERT INTO audit_events VALUES($1,$2,$3,'job_unknown_closed',$4,now())")
|
|
.bind(tenant)
|
|
.bind(Uuid::new_v4())
|
|
.bind(&p.name)
|
|
.bind(json!({"job_id":id,"attempt_id":input.attempt_id,"grant_id":grant,"closure_id":closure,
|
|
"original_revision":input.revision,"reason":input.reason,"session_hash":session,
|
|
"approval_origin":p.approval_origin(),"testsimulation":p.testsimulation}))
|
|
.execute(&mut *tx)
|
|
.await?;
|
|
tx.commit().await?;
|
|
job(state, p, tenant, id).await
|
|
}
|
|
async fn close_unknown_http(
|
|
State(s): State<crate::State>,
|
|
h: HeaderMap,
|
|
Path((t, id)): Path<(Uuid, Uuid)>,
|
|
Json(i): Json<CloseUnknown>,
|
|
) -> Result<Json<Value>> {
|
|
let p = principal(&s, &h, true).await?;
|
|
Ok(Json(close_unknown(&s, &p, t, id, i).await?))
|
|
}
|
|
async fn cancel_http(
|
|
State(s): State<crate::State>,
|
|
h: HeaderMap,
|
|
Path((t, id)): Path<(Uuid, Uuid)>,
|
|
Json(i): Json<Cancel>,
|
|
) -> Result<Json<Value>> {
|
|
let p = principal(&s, &h, true).await?;
|
|
Ok(Json(cancel(&s, &p, t, id, i).await?))
|
|
}
|
|
async fn operations_http(
|
|
State(s): State<crate::State>,
|
|
h: HeaderMap,
|
|
Path(t): Path<Uuid>,
|
|
axum::extract::Query(query): axum::extract::Query<crate::pagination::PageQuery>,
|
|
) -> Result<Json<Value>> {
|
|
let p = principal(&s, &h, false).await?;
|
|
scope(&p, t, false)?;
|
|
let mut tx = rmm_persistence::tenant_tx(&s.pool, t).await?;
|
|
crate::permissions::require_principal(&mut tx, &p, "operations:read").await?;
|
|
let mut page = crate::pagination::Cursor::parse(&s, &p, "operations:operation_id:asc", query)
|
|
.map_err(|status| Error(status, "VALIDATION_ERROR"))?;
|
|
let ids:Vec<Uuid>=sqlx::query_scalar("SELECT operation_id FROM approval_requests WHERE operation_id>$1 AND created_at<=$2 ORDER BY operation_id LIMIT $3").bind(page.last).bind(page.as_of).bind(i64::from(page.limit)+1).fetch_all(&mut *tx).await?;
|
|
tx.commit().await?;
|
|
let truncated = ids.len() > usize::from(page.limit);
|
|
let next = if truncated {
|
|
Some(
|
|
page.next(&s, ids[usize::from(page.limit) - 1])
|
|
.map_err(|status| Error(status, "VALIDATION_ERROR"))?,
|
|
)
|
|
} else {
|
|
None
|
|
};
|
|
let mut items = Vec::new();
|
|
for id in ids.into_iter().take(usize::from(page.limit)) {
|
|
items.push(operation(&s, &p, t, id).await?)
|
|
}
|
|
Ok(Json(
|
|
json!({"items":items,"next_cursor":next,"completeness":if truncated{"partial"}else{"complete"},"truncated":truncated,"as_of":page.as_of}),
|
|
))
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod windows_contract_tests {
|
|
use super::*;
|
|
use chrono::Duration;
|
|
fn input() -> PlanInput {
|
|
let tenant = Uuid::new_v4();
|
|
let now = Utc::now();
|
|
serde_json::from_value::<PlanRequest>(json!({"tenant_id":tenant,"action":"run_script","targets":{"asset_ids":[Uuid::new_v4()]},"parameters":{"execution_identity":"agent_service","timeout_seconds":60,"max_output_bytes":4096,"variants":[{"os_family":"linux","interpreter":"posix_sh","encoding":"utf-8","script_utf8":"printf hi\n"},{"os_family":"windows","interpreter":"powershell","encoding":"utf-8","script_utf8":"Write-Output 'hi'\r\n"}]},"schedule":{"not_before":now,"start_before":now+chrono::Duration::minutes(10),"offline_policy":"wait_until_deadline"},"rollout":{"max_parallel":1,"halt_after_failures":1},"reason":"fixed mixed plan"})).unwrap().resolve(tenant).unwrap()
|
|
}
|
|
#[test]
|
|
fn exact_fixed_variants_and_typed_bypass_denials() {
|
|
assert!(capabilities(json!(["windows.base/1", 42])).is_err());
|
|
assert!(capabilities(json!({"run_script": true})).is_err());
|
|
let mut i = input();
|
|
let linux = target_action(&i, &["linux.base/1".into()]).unwrap();
|
|
assert_eq!(linux, i.action);
|
|
let windows = target_action(&i, &["windows.base/1".into()]).unwrap();
|
|
assert_eq!(windows.script_platform(), Some("windows"));
|
|
assert!(
|
|
matches!(windows,Action::RunScript{ref script_utf8,..} if script_utf8.as_bytes()==b"Write-Output 'hi'\r\n")
|
|
);
|
|
assert!(target_action(&i, &[]).is_err());
|
|
assert!(target_action(&i, &["linux.base/1".into(), "windows.base/1".into()]).is_err());
|
|
i.script_variants.push(i.script_variants[0].clone());
|
|
assert!(target_action(&i, &["linux.base/1".into()]).is_err());
|
|
let mut i = input();
|
|
i.script_variants[1].interpreter = "bash".into();
|
|
assert!(target_action(&i, &["windows.base/1".into()]).is_err());
|
|
let mut i = input();
|
|
i.script_variants[0].script_utf8.push('x');
|
|
assert!(target_action(&i, &["linux.base/1".into()]).is_err());
|
|
let mut i = input();
|
|
i.script_variants.remove(1);
|
|
assert!(target_action(&i, &["windows.base/1".into()]).is_err());
|
|
}
|
|
#[test]
|
|
fn fixed_windows_log_web_contract_denies_extra_source_parameters() {
|
|
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)
|
|
);
|
|
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)
|
|
);
|
|
}
|
|
}
|
|
#[test]
|
|
fn full_maintenance_web_profile_is_action_wide_strict_and_identity_bound() {
|
|
let request = serde_json::json!({"tenant_id":Uuid::nil(),"action":"run_script","targets":{"asset_ids":[Uuid::nil()]},"parameters":{"execution_identity":"system","timeout_seconds":30,"max_output_bytes":4096,"privileged_script_profile":"full_maintenance_v1","variants":[{"os_family":"windows","interpreter":"powershell","encoding":"utf-8","script_utf8":"Write-Output 'hi'\r\n","windows_execution_profile":"powershell_51_remote_signed"}]},"schedule":{"not_before":"2026-11-14T12:00:00Z","start_before":"2026-11-14T13:00:00Z","offline_policy":"wait_until_deadline"},"rollout":{"max_parallel":1,"halt_after_failures":1},"reason":"codec only"});
|
|
let resolved = serde_json::from_value::<PlanRequest>(request.clone())
|
|
.unwrap()
|
|
.resolve(Uuid::nil())
|
|
.unwrap();
|
|
let action = target_action(&resolved, &["windows.base/1".into()]).unwrap();
|
|
assert!(action.full_maintenance());
|
|
let mut invalid = resolved.clone();
|
|
invalid.execution_identity = "agent_service".into();
|
|
assert!(target_action(&invalid, &["windows.base/1".into()]).is_err());
|
|
for value in [
|
|
serde_json::Value::Null,
|
|
serde_json::json!("unknown"),
|
|
serde_json::json!({"full_maintenance_v1":null}),
|
|
] {
|
|
let mut request = request.clone();
|
|
request["parameters"]["privileged_script_profile"] = value;
|
|
assert!(serde_json::from_value::<PlanRequest>(request).is_err());
|
|
}
|
|
}
|
|
#[test]
|
|
fn remote_signed_fixed_variants_bind_profile_without_linux_inheritance() {
|
|
let mut i = input();
|
|
let legacy_linux = encode(&i.action).unwrap();
|
|
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),
|
|
privileged_script_profile: None,
|
|
..
|
|
}
|
|
));
|
|
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 schema = schemars::schema_for!(Variant).to_value();
|
|
assert_eq!(
|
|
schema["properties"]["windows_execution_profile"],
|
|
json!({"$ref":"#/$defs/WindowsExecutionProfile"})
|
|
);
|
|
assert!(
|
|
!schema["required"]
|
|
.as_array()
|
|
.unwrap()
|
|
.contains(&json!("windows_execution_profile"))
|
|
);
|
|
assert_eq!(schema["$defs"]["WindowsExecutionProfile"]["type"], "string");
|
|
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() {
|
|
let admin = sqlx::PgPool::connect(&std::env::var("RMM_TEST_REPAIR_ADMIN_URL").unwrap())
|
|
.await
|
|
.unwrap();
|
|
let pool = sqlx::PgPool::connect(&std::env::var("RMM_TEST_REPAIR_APP_URL").unwrap())
|
|
.await
|
|
.unwrap();
|
|
rmm_persistence::verify_application_role(&pool)
|
|
.await
|
|
.unwrap();
|
|
let tenant = Uuid::new_v4();
|
|
sqlx::query("INSERT INTO tenants(tenant_id,name) VALUES($1,'isolated Windows contract')")
|
|
.bind(tenant)
|
|
.execute(&admin)
|
|
.await
|
|
.unwrap();
|
|
let principal = Principal {
|
|
tenant,
|
|
name: "windows-contract".into(),
|
|
operator: true,
|
|
session_hash: None,
|
|
csrf: None,
|
|
scopes: None,
|
|
testsimulation: false,
|
|
identity: None,
|
|
tenants: vec![tenant],
|
|
};
|
|
sqlx::query("INSERT INTO memberships VALUES($1,$2,'automation',ARRAY['operations:plan','operations:submit','operations:read','scripts:execute'],NULL)").bind(tenant).bind(&principal.name).execute(&admin).await.unwrap();
|
|
let windows_caps = json!([
|
|
"windows.base/1",
|
|
"rmm.sync.v1",
|
|
"run_script",
|
|
"script.powershell/1"
|
|
]);
|
|
let mut assets = Vec::new();
|
|
let mut agents = Vec::new();
|
|
for caps in [json!(["linux.base/1", "run_script"]), windows_caps.clone()] {
|
|
let asset = Uuid::new_v4();
|
|
let agent = Uuid::new_v4();
|
|
assets.push(asset);
|
|
agents.push(agent);
|
|
sqlx::query("INSERT INTO assets(tenant_id,asset_id) VALUES($1,$2)")
|
|
.bind(tenant)
|
|
.bind(asset)
|
|
.execute(&admin)
|
|
.await
|
|
.unwrap();
|
|
sqlx::query("INSERT INTO agent_installations(tenant_id,agent_id,asset_id,certificate_sha256,capabilities,connection_generation) VALUES($1,$2,$3,$4,$5,1)").bind(tenant).bind(agent).bind(asset).bind(hash(agent.as_bytes())).bind(caps).execute(&admin).await.unwrap();
|
|
}
|
|
let temp = std::path::PathBuf::from(format!("/tmp/windows-contract-{}", Uuid::new_v4()));
|
|
let state = crate::State {
|
|
pool,
|
|
signer: None,
|
|
viewer_a: [0; 32],
|
|
viewer_b: [1; 32],
|
|
auth: std::sync::Arc::new(crate::auth::Auth::from_env("development").await.unwrap()),
|
|
job_signer: std::sync::Arc::new(
|
|
crate::job_signer::JobSigner::load_or_create(&temp.join("key.pem")).unwrap(),
|
|
),
|
|
};
|
|
crate::script_library::tests::revision_plan_contract(&state, &principal, assets[0], assets[1])
|
|
.await;
|
|
let mut request = input();
|
|
request.targets.asset_ids = assets.clone();
|
|
let view = plan(&state, &principal, tenant, request.clone())
|
|
.await
|
|
.unwrap();
|
|
let id = Uuid::parse_str(view["plan_id"].as_str().unwrap()).unwrap();
|
|
let original: Vec<u8> =
|
|
sqlx::query_scalar("SELECT payload FROM operation_plans WHERE plan_id=$1")
|
|
.bind(id)
|
|
.fetch_one(&admin)
|
|
.await
|
|
.unwrap();
|
|
let bound: PlanPayload = serde_json::from_slice(&original).unwrap();
|
|
assert_eq!(bound.jobs.len(), 2);
|
|
for job in &bound.jobs {
|
|
assert_eq!(hash(&encode(&job.payload).unwrap()), job.job_payload_hash);
|
|
let expected = if job.payload.asset_id == assets[0] {
|
|
"linux"
|
|
} else {
|
|
"windows"
|
|
};
|
|
assert_eq!(job.payload.action.script_platform(), Some(expected));
|
|
}
|
|
let pending = submit(
|
|
&state,
|
|
&principal,
|
|
tenant,
|
|
id,
|
|
Submit {
|
|
idempotency_key: "fixed-mixed".into(),
|
|
},
|
|
)
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(pending["approval_state"], "pending_approval");
|
|
assert_eq!(pending["job_count"], 0);
|
|
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
|
|
.await
|
|
.unwrap();
|
|
recheck(&mut tx, &bound).await.unwrap();
|
|
tx.rollback().await.unwrap();
|
|
sqlx::query("UPDATE agent_installations SET capabilities=$2 WHERE agent_id=$1")
|
|
.bind(agents[1])
|
|
.bind(json!(["windows.base/1", "run_script", "rmm.sync.v1"]))
|
|
.execute(&admin)
|
|
.await
|
|
.unwrap();
|
|
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(
|
|
recheck(&mut tx, &bound).await.unwrap_err().1,
|
|
"UNSUPPORTED_CAPABILITY"
|
|
);
|
|
tx.rollback().await.unwrap();
|
|
assert_eq!(
|
|
plan(&state, &principal, tenant, request.clone())
|
|
.await
|
|
.unwrap_err()
|
|
.1,
|
|
"UNSUPPORTED_CAPABILITY"
|
|
);
|
|
sqlx::query("UPDATE agent_installations SET capabilities=$2 WHERE agent_id=$1")
|
|
.bind(agents[1])
|
|
.bind(&windows_caps)
|
|
.execute(&admin)
|
|
.await
|
|
.unwrap();
|
|
let mut changed = bound.clone();
|
|
changed.jobs[0].script_sha256 = Some("00".repeat(32));
|
|
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();
|
|
// 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())
|
|
.await
|
|
.unwrap_err()
|
|
.1,
|
|
"UNSUPPORTED_CAPABILITY"
|
|
);
|
|
request.targets.asset_ids = vec![assets[0]];
|
|
plan(&state, &principal, tenant, request).await.unwrap();
|
|
assert_eq!(
|
|
plan(&state, &principal, Uuid::new_v4(), input())
|
|
.await
|
|
.unwrap_err()
|
|
.1,
|
|
"NOT_FOUND"
|
|
);
|
|
assert!(
|
|
crate::job_gateway::next(&state, tenant, agents[1], 1)
|
|
.await
|
|
.unwrap()
|
|
.is_none()
|
|
);
|
|
let now = Utc::now();
|
|
let mut logs = input();
|
|
logs.targets.asset_ids = vec![assets[1]];
|
|
logs.script_variants.clear();
|
|
logs.max_runtime_seconds = 30;
|
|
logs.action = Action::QueryLogs {
|
|
unit: WINDOWS_EVENT_LOG_FIXTURE_SOURCE.into(),
|
|
since: now - Duration::hours(1),
|
|
until: now,
|
|
max_lines: 1000,
|
|
};
|
|
assert_eq!(
|
|
plan(&state, &principal, tenant, logs.clone())
|
|
.await
|
|
.unwrap_err()
|
|
.1,
|
|
"FORBIDDEN"
|
|
);
|
|
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"),
|
|
json!(WINDOWS_EVENT_LOG_FIXTURE_CAPABILITY),
|
|
]);
|
|
sqlx::query("UPDATE agent_installations SET capabilities=$2 WHERE agent_id=$1")
|
|
.bind(agents[1])
|
|
.bind(json!(log_caps))
|
|
.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 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(
|
|
&state,
|
|
&principal,
|
|
tenant,
|
|
log_id,
|
|
Submit {
|
|
idempotency_key: "fixed-event-log".into(),
|
|
},
|
|
)
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(pending["approval_state"], "pending_approval");
|
|
assert_eq!(pending["job_count"], 0);
|
|
let mut changed = log_bound.clone();
|
|
if let Action::QueryLogs { max_lines, .. } = &mut changed.jobs[0].payload.action {
|
|
*max_lines = 999;
|
|
}
|
|
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();
|
|
let mut changed = log_bound.clone();
|
|
changed.jobs[0].payload.max_output_bytes = 65537;
|
|
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(
|
|
recheck(&mut tx, &changed).await.unwrap_err().1,
|
|
"VALIDATION_ERROR"
|
|
);
|
|
tx.rollback().await.unwrap();
|
|
log_caps.retain(|cap| cap != WINDOWS_EVENT_LOG_FIXTURE_CAPABILITY);
|
|
sqlx::query("UPDATE agent_installations SET capabilities=$2 WHERE agent_id=$1")
|
|
.bind(agents[1])
|
|
.bind(json!(log_caps))
|
|
.execute(&admin)
|
|
.await
|
|
.unwrap();
|
|
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(
|
|
recheck(&mut tx, &log_bound).await.unwrap_err().1,
|
|
"UNSUPPORTED_CAPABILITY"
|
|
);
|
|
tx.rollback().await.unwrap();
|
|
sqlx::query("UPDATE memberships SET permissions=array_remove(permissions,'logs:read') WHERE principal=$1").bind(&principal.name).execute(&admin).await.unwrap();
|
|
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(
|
|
recheck(&mut tx, &log_bound).await.unwrap_err().1,
|
|
"FORBIDDEN"
|
|
);
|
|
tx.rollback().await.unwrap();
|
|
// MSI metadata only: real migration/RLS/FKs and pending-only planning.
|
|
// This ignored test runs alone in the dedicated isolated PostgreSQL process.
|
|
// Opaque bytes deliberately are NOT an authored/installed MSI fixture.
|
|
use crate::artifact_store::ArtifactStore;
|
|
use std::os::unix::fs::PermissionsExt;
|
|
let key_path = temp.join("key.pem");
|
|
let policy_path = temp.join("system-msi.json");
|
|
let settings = [
|
|
("RMM_PROFILE", "development".to_string()),
|
|
("RMM_JOB_KEY_FILE", key_path.display().to_string()),
|
|
("RMM_DEV_SYSTEM_ENABLED", "true".to_string()),
|
|
(
|
|
"RMM_DEV_SYSTEM_POLICY_FILE",
|
|
policy_path.display().to_string(),
|
|
),
|
|
];
|
|
let previous = settings
|
|
.iter()
|
|
.map(|(key, _)| (*key, std::env::var_os(key)))
|
|
.collect::<Vec<_>>();
|
|
for (key, value) in &settings {
|
|
unsafe {
|
|
std::env::set_var(key, value);
|
|
}
|
|
}
|
|
let artifact_id = Uuid::new_v4();
|
|
let opaque = b"metadata-contract-not-an-executable-msi";
|
|
let artifact_sha = crate::catalog::store()
|
|
.unwrap()
|
|
.put(tenant, opaque)
|
|
.unwrap();
|
|
let manifest = crate::windows_msi_catalog::test_manifest(
|
|
artifact_id,
|
|
&artifact_sha,
|
|
opaque.len() as u64,
|
|
);
|
|
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
|
|
.await
|
|
.unwrap();
|
|
sqlx::query("INSERT INTO artifacts(tenant_id,artifact_id,sha256,size_bytes,media_type) VALUES($1,$2,$3,$4,'application/octet-stream')")
|
|
.bind(tenant).bind(artifact_id).bind(&artifact_sha).bind(opaque.len() as i64).execute(&mut *tx).await.unwrap();
|
|
let catalog_id = crate::windows_msi_catalog::store_recipe(&mut tx, tenant, &manifest)
|
|
.await
|
|
.unwrap();
|
|
tx.commit().await.unwrap();
|
|
let other = Uuid::new_v4();
|
|
sqlx::query("INSERT INTO tenants(tenant_id,name) VALUES($1,'other MSI tenant')")
|
|
.bind(other)
|
|
.execute(&admin)
|
|
.await
|
|
.unwrap();
|
|
let mut foreign = rmm_persistence::tenant_tx(&state.pool, other)
|
|
.await
|
|
.unwrap();
|
|
let count: i64 = sqlx::query_scalar("SELECT count(*) FROM windows_msi_recipes")
|
|
.fetch_one(&mut *foreign)
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(count, 0);
|
|
assert!(
|
|
crate::windows_msi_catalog::references(&mut foreign, &manifest)
|
|
.await
|
|
.is_err()
|
|
);
|
|
foreign.rollback().await.unwrap();
|
|
let row=sqlx::query("INSERT INTO windows_msi_recipes(tenant_id,catalog_id,recipe_id,recipe_version,recipe_sha256,artifact_id,artifact_sha256,artifact_bytes,payload) VALUES($1,$2,$3,'1',$4,$5,$6,$7,$8)")
|
|
.bind(other).bind(Uuid::new_v4()).bind(&manifest.recipe.recipe_id).bind(&manifest.recipe_sha256)
|
|
.bind(artifact_id).bind(&artifact_sha).bind(opaque.len() as i64).bind(encode(&manifest.recipe).unwrap()).execute(&admin).await;
|
|
assert!(row.is_err()); // database-level composite tenant/artifact FK
|
|
assert!(
|
|
sqlx::query("UPDATE windows_msi_recipes SET recipe_sha256=$2 WHERE catalog_id=$1")
|
|
.bind(catalog_id)
|
|
.bind("cd".repeat(32))
|
|
.execute(&admin)
|
|
.await
|
|
.is_err()
|
|
);
|
|
assert!(
|
|
sqlx::query("DELETE FROM windows_msi_recipes WHERE catalog_id=$1")
|
|
.bind(catalog_id)
|
|
.execute(&admin)
|
|
.await
|
|
.is_err()
|
|
);
|
|
sqlx::query("UPDATE memberships SET permissions=array_append(permissions,'system:execute') WHERE tenant_id=$1 AND principal=$2").bind(tenant).bind(&principal.name).execute(&admin).await.unwrap();
|
|
let caps = json!([
|
|
"windows.base/1",
|
|
"rmm.sync.v1",
|
|
"helper.system.v1",
|
|
"ensure_package",
|
|
"system:ensure_package",
|
|
rmm_domain::windows_execution::MSI_CAPABILITY,
|
|
format!("helper.policy.sha256:{}", "ab".repeat(32)),
|
|
format!("helper.binary.sha256:{}", "cd".repeat(32))
|
|
]);
|
|
sqlx::query("UPDATE agent_installations SET capabilities=$2 WHERE agent_id=$1")
|
|
.bind(agents[1])
|
|
.bind(&caps)
|
|
.execute(&admin)
|
|
.await
|
|
.unwrap();
|
|
let system = json!({"schema_version":2,"profile":"development","expires_at":Utc::now()+Duration::minutes(10),"scopes":[{
|
|
"tenant_id":tenant,"asset_id":assets[1],"agent_id":agents[1],"enrollment_generation":1,"assignment_version":1,
|
|
"principals":[principal.name],"helper_policy_sha256":"ab".repeat(32),"helper_binary_sha256":"cd".repeat(32),
|
|
"acceptance_evidence_id":Uuid::new_v4(),"allowed_services":[],"max_runtime_seconds":120,"allowed_msi_recipe_sha256":[manifest.recipe_sha256]}]});
|
|
std::fs::write(&policy_path, encode(&system).unwrap()).unwrap();
|
|
std::fs::set_permissions(&policy_path, std::fs::Permissions::from_mode(0o600)).unwrap();
|
|
let mut package = input();
|
|
package.targets.asset_ids = vec![assets[1]];
|
|
package.script_variants.clear();
|
|
package.execution_identity = "system".into();
|
|
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)
|
|
.await
|
|
.unwrap();
|
|
let fixed: PlanPayload = serde_json::from_slice(&raw).unwrap();
|
|
assert_eq!(fixed.artifact_references.len(), 1);
|
|
assert_eq!(
|
|
fixed.artifact_references[0].artifact.artifact_id,
|
|
artifact_id
|
|
);
|
|
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
|
|
.await
|
|
.unwrap();
|
|
recheck(&mut tx, &fixed).await.unwrap();
|
|
tx.rollback().await.unwrap();
|
|
for case in 0..4 {
|
|
let mut bad = fixed.clone();
|
|
match case {
|
|
0 => bad.artifact_references.clear(),
|
|
1 => bad
|
|
.artifact_references
|
|
.push(bad.artifact_references[0].clone()),
|
|
2 => bad.artifact_references[0].artifact.size_bytes += 1,
|
|
_ => bad.artifact_references[0].artifact.artifact_id = Uuid::new_v4(),
|
|
};
|
|
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
|
|
.await
|
|
.unwrap();
|
|
assert!(recheck(&mut tx, &bad).await.is_err());
|
|
tx.rollback().await.unwrap();
|
|
}
|
|
let pending = submit(
|
|
&state,
|
|
&principal,
|
|
tenant,
|
|
package_id,
|
|
Submit {
|
|
idempotency_key: "fixed-msi-metadata".into(),
|
|
},
|
|
)
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(pending["approval_state"], "pending_approval");
|
|
assert_eq!(pending["job_count"], 0);
|
|
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
|
|
.unwrap();
|
|
assert_eq!(recheck(&mut tx, &fixed).await.unwrap_err().1, "FORBIDDEN");
|
|
tx.rollback().await.unwrap();
|
|
for (key, value) in previous {
|
|
unsafe {
|
|
match value {
|
|
Some(value) => std::env::set_var(key, value),
|
|
None => std::env::remove_var(key),
|
|
}
|
|
}
|
|
}
|
|
let counts:(i64,i64,i64)=sqlx::query_as("SELECT (SELECT count(*) FROM jobs WHERE tenant_id=$1),(SELECT count(*) FROM outbox WHERE tenant_id=$1),(SELECT count(*) FROM execution_permits WHERE tenant_id=$1)").bind(tenant).fetch_one(&admin).await.unwrap();
|
|
assert_eq!(counts, (0, 0, 0));
|
|
let after: Vec<u8> =
|
|
sqlx::query_scalar("SELECT payload FROM operation_plans WHERE plan_id=$1")
|
|
.bind(id)
|
|
.fetch_one(&admin)
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(original, after);
|
|
std::fs::remove_dir_all(temp).unwrap();
|
|
}
|
|
}
|