Add versioned script library, reconcile permit refusals and compact helper captures
This commit is contained in:
@@ -74,7 +74,7 @@ pub async fn revoke_device(
|
||||
if n == 0 {
|
||||
return Err(Error(StatusCode::NOT_FOUND, "NOT_FOUND"));
|
||||
}
|
||||
sqlx::query("UPDATE jobs SET cancel_requested=true WHERE asset_id=$1 AND state NOT IN ('succeeded','failed','cancelled','expired')").bind(asset).execute(&mut *tx).await?;
|
||||
sqlx::query("UPDATE jobs SET cancel_requested=true WHERE asset_id=$1 AND state NOT IN ('succeeded','failed','cancelled','expired','closed_unknown')").bind(asset).execute(&mut *tx).await?;
|
||||
audit(
|
||||
&mut tx,
|
||||
&p,
|
||||
@@ -100,7 +100,7 @@ pub async fn revoke_plan(
|
||||
.bind(op)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query("UPDATE jobs SET cancel_requested=true,state=CASE WHEN NOT start_reserved AND state='queued' THEN 'cancelled' ELSE state END WHERE operation_id=$1 AND state NOT IN ('succeeded','failed','cancelled','expired')").bind(op).execute(&mut *tx).await?;
|
||||
sqlx::query("UPDATE jobs SET cancel_requested=true,state=CASE WHEN NOT start_reserved AND state='queued' THEN 'cancelled' ELSE state END WHERE operation_id=$1 AND state NOT IN ('succeeded','failed','cancelled','expired','closed_unknown')").bind(op).execute(&mut *tx).await?;
|
||||
audit(
|
||||
&mut tx,
|
||||
&p,
|
||||
|
||||
@@ -526,6 +526,7 @@ pub async fn permit(
|
||||
payload_bytes: vec![],
|
||||
signature: vec![],
|
||||
denial_code: code.into(),
|
||||
unreserved_request: None,
|
||||
};
|
||||
let row=sqlx::query("SELECT j.*,a.authorization_id,a.revoked_at,a.principal AS approver,p.plan_hash,p.payload AS plan_payload,r.approval_state,i.enrollment_generation,i.assignment_version,i.asset_id AS bound_asset,i.capabilities,i.revoked_at AS device_revoked,i.connection_generation,t.changes_stopped FROM jobs j JOIN operations o ON o.tenant_id=j.tenant_id AND o.operation_id=j.operation_id JOIN authorizations a ON a.tenant_id=o.tenant_id AND a.authorization_id=o.authorization_id JOIN approval_requests r ON r.tenant_id=j.tenant_id AND r.operation_id=j.operation_id JOIN operation_plans p ON p.tenant_id=j.tenant_id AND p.plan_id=r.plan_id JOIN agent_installations i ON i.tenant_id=j.tenant_id AND i.agent_id=j.agent_id JOIN tenants t ON t.tenant_id=j.tenant_id WHERE j.job_id=$1 AND j.attempt_id=$2 AND j.agent_id=$3 FOR UPDATE OF j").bind(Uuid::parse_str(&r.job_id)?).bind(Uuid::parse_str(&r.attempt_id)?).bind(agent).fetch_optional(&mut *tx).await?;
|
||||
let Some(row) = row else {
|
||||
@@ -584,6 +585,13 @@ pub async fn permit(
|
||||
{
|
||||
return Ok(denied("BINDING_MISMATCH"));
|
||||
}
|
||||
// The locked row belongs to this request and has no start reservation.
|
||||
// Echo the binding only after both checks, so a client can safely return
|
||||
// this particular offer to scheduling after a fresh signed reconciliation.
|
||||
let denied = |code: &str| ExecutionPermit {
|
||||
unreserved_request: Some(r.clone()),
|
||||
..denied(code)
|
||||
};
|
||||
let now = Utc::now();
|
||||
if !payload
|
||||
.action
|
||||
@@ -702,7 +710,7 @@ pub async fn permit(
|
||||
)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
let concurrent:i64=sqlx::query_scalar("SELECT count(*) FROM jobs WHERE start_reserved AND state NOT IN ('succeeded','failed','cancelled','expired')").fetch_one(&mut *tx).await?;
|
||||
let concurrent:i64=sqlx::query_scalar("SELECT count(*) FROM jobs WHERE start_reserved AND state NOT IN ('succeeded','failed','cancelled','expired','closed_unknown')").fetch_one(&mut *tx).await?;
|
||||
if hourly >= i64::from(limits.0) || concurrent >= i64::from(limits.1) {
|
||||
return Ok(denied("QUOTA_EXCEEDED"));
|
||||
}
|
||||
@@ -710,7 +718,7 @@ pub async fn permit(
|
||||
dependency_group, ..
|
||||
} = &payload.action
|
||||
{
|
||||
let busy:bool=sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM jobs WHERE start_reserved AND state NOT IN ('succeeded','failed','cancelled','expired') AND (convert_from(payload,'UTF8')::jsonb->'action'->>'dependency_group'=$1 OR convert_from(payload,'UTF8')::jsonb->'action'->>'action'='reboot'))").bind(dependency_group).fetch_one(&mut *tx).await?;
|
||||
let busy:bool=sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM jobs WHERE start_reserved AND state NOT IN ('succeeded','failed','cancelled','expired','closed_unknown') AND (convert_from(payload,'UTF8')::jsonb->'action'->>'dependency_group'=$1 OR convert_from(payload,'UTF8')::jsonb->'action'->>'action'='reboot'))").bind(dependency_group).fetch_one(&mut *tx).await?;
|
||||
if busy {
|
||||
return Ok(denied("RESOURCE_LOCKED"));
|
||||
}
|
||||
@@ -727,11 +735,11 @@ pub async fn permit(
|
||||
.bind(row.get::<Uuid, _>("operation_id"))
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
let active:i64=sqlx::query_scalar("SELECT count(*) FROM jobs WHERE operation_id=$1 AND start_reserved AND state NOT IN ('succeeded','failed','cancelled','expired')").bind(row.get::<Uuid,_>("operation_id")).fetch_one(&mut *tx).await?;
|
||||
let active:i64=sqlx::query_scalar("SELECT count(*) FROM jobs WHERE operation_id=$1 AND start_reserved AND state NOT IN ('succeeded','failed','cancelled','expired','closed_unknown')").bind(row.get::<Uuid,_>("operation_id")).fetch_one(&mut *tx).await?;
|
||||
if failures >= i64::from(plan.halt_after_failures) || active >= i64::from(plan.max_parallel) {
|
||||
return Ok(denied("ROLLOUT_PAUSED"));
|
||||
}
|
||||
let locked:bool=sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM jobs WHERE agent_id=$1 AND start_reserved AND state NOT IN ('succeeded','failed','cancelled','expired'))").bind(agent).fetch_one(&mut *tx).await?;
|
||||
let locked:bool=sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM jobs WHERE agent_id=$1 AND start_reserved AND state NOT IN ('succeeded','failed','cancelled','expired','closed_unknown'))").bind(agent).fetch_one(&mut *tx).await?;
|
||||
if locked {
|
||||
return Ok(denied("RESOURCE_LOCKED"));
|
||||
}
|
||||
@@ -776,6 +784,7 @@ pub async fn permit(
|
||||
payload_bytes: bytes,
|
||||
signature,
|
||||
denial_code: String::new(),
|
||||
unreserved_request: None,
|
||||
})
|
||||
}
|
||||
pub async fn next(
|
||||
|
||||
+23
-18
@@ -53,7 +53,11 @@ pub fn scope(p: &Principal, tenant: Uuid, write: bool) -> Result<()> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
async fn principal(state: &crate::State, h: &HeaderMap, write: bool) -> Result<Principal> {
|
||||
pub(crate) async fn principal(
|
||||
state: &crate::State,
|
||||
h: &HeaderMap,
|
||||
write: bool,
|
||||
) -> Result<Principal> {
|
||||
state
|
||||
.auth
|
||||
.principal(state, h, write)
|
||||
@@ -420,7 +424,7 @@ pub async fn plan_request(
|
||||
reason: input.reason,
|
||||
artifact_ids: Vec::new(),
|
||||
};
|
||||
plan_resolved(state, p, tenant, resolved, Some(updates)).await
|
||||
plan_resolved(state, p, tenant, resolved, Some(updates), None).await
|
||||
}
|
||||
fn validate_variants(variants: &[Variant]) -> Result<()> {
|
||||
if variants.is_empty() || variants.len() > 2 {
|
||||
@@ -531,9 +535,9 @@ pub async fn plan(
|
||||
"AGENT_UPDATE_RELEASE_ID_REQUIRED",
|
||||
));
|
||||
}
|
||||
plan_resolved(state, p, tenant, input, None).await
|
||||
plan_resolved(state, p, tenant, input, None, None).await
|
||||
}
|
||||
async fn plan_resolved(
|
||||
pub(crate) async fn plan_resolved(
|
||||
state: &crate::State,
|
||||
p: &Principal,
|
||||
tenant: Uuid,
|
||||
@@ -541,6 +545,7 @@ async fn plan_resolved(
|
||||
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();
|
||||
@@ -716,6 +721,7 @@ async fn plan_resolved(
|
||||
halt_after_failures: input.rollout.halt_after_failures,
|
||||
recipe_references,
|
||||
artifact_references,
|
||||
script_revision,
|
||||
};
|
||||
crate::windows_msi_catalog::validate_plan_bindings(&payload)?;
|
||||
crate::agent_updates::validate_plan_bindings(&payload)?;
|
||||
@@ -1085,11 +1091,7 @@ pub async fn operation(
|
||||
"needs_attention"
|
||||
} else if c("succeeded") == n {
|
||||
"succeeded"
|
||||
} else if c("succeeded")
|
||||
+ c("failed")
|
||||
+ c("cancelled")
|
||||
+ c("expired")
|
||||
+ c("closed_unknown")
|
||||
} else if c("succeeded") + c("failed") + c("cancelled") + c("expired") + c("closed_unknown")
|
||||
== n
|
||||
{
|
||||
if c("succeeded") > 0 {
|
||||
@@ -1240,13 +1242,12 @@ pub async fn close_unknown(
|
||||
}
|
||||
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)?;
|
||||
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
|
||||
{
|
||||
@@ -1286,9 +1287,11 @@ pub async fn close_unknown(
|
||||
.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,
|
||||
.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}))
|
||||
"approval_origin":p.approval_origin(),"testsimulation":p.testsimulation}),
|
||||
)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
@@ -1569,6 +1572,8 @@ mod windows_contract_tests {
|
||||
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())
|
||||
|
||||
@@ -23,6 +23,7 @@ mod pagination;
|
||||
mod permissions;
|
||||
mod root_policy;
|
||||
mod scheduler;
|
||||
mod script_library;
|
||||
mod synchronization;
|
||||
mod tls;
|
||||
mod update_artifact_store;
|
||||
@@ -205,6 +206,7 @@ async fn main() -> Result<()> {
|
||||
.route("/api/v1/tenants/{tenant}/devices", get(api::devices_page))
|
||||
.route("/api/v1/tenants/{tenant}/devices/{asset}", get(api::device));
|
||||
routes = jobs::routes(routes);
|
||||
routes = script_library::routes(routes);
|
||||
routes = controls::routes(routes);
|
||||
routes = catalog::routes(routes);
|
||||
routes = agent_updates::routes(routes);
|
||||
|
||||
@@ -72,6 +72,19 @@ struct Cancel {
|
||||
#[derive(Deserialize, schemars::JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Empty {}
|
||||
#[derive(Deserialize, schemars::JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct PublishScript {
|
||||
tenant_id: Uuid,
|
||||
input: crate::script_library::Publish,
|
||||
}
|
||||
#[derive(Deserialize, schemars::JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct PlanScript {
|
||||
tenant_id: Uuid,
|
||||
revision_id: Uuid,
|
||||
input: crate::script_library::Selection,
|
||||
}
|
||||
fn tool<T: schemars::JsonSchema>(name: &'static str, description: &'static str) -> Tool {
|
||||
let schema = schemars::schema_for!(T).to_value();
|
||||
let map = schema.as_object().cloned().unwrap_or_default();
|
||||
@@ -91,6 +104,18 @@ fn tools() -> Vec<Tool> {
|
||||
"inventory.get_device",
|
||||
"Read stored inventory of one authorized device.",
|
||||
),
|
||||
tool::<Devices>(
|
||||
"scripts.list",
|
||||
"Read tenant script revisions, including the exact script and execution identity.",
|
||||
),
|
||||
tool::<PublishScript>(
|
||||
"scripts.publish",
|
||||
"Save an immutable script revision. Use expected_version zero for a new name or the current version to publish an edit.",
|
||||
),
|
||||
tool::<PlanScript>(
|
||||
"scripts.plan",
|
||||
"Plan the selected immutable script revision against fixed assets. Submit the returned plan for WebUI approval via operations.submit.",
|
||||
),
|
||||
tool::<Devices>(
|
||||
"updates.list_releases",
|
||||
"Read immutable signed agent release metadata for the authorized tenant; never approves or applies an update.",
|
||||
@@ -208,6 +233,28 @@ impl Adapter {
|
||||
let i: crate::monitoring::LogQuery = parse(args)?;
|
||||
crate::monitoring::query(&self.state, &p, i).await
|
||||
}
|
||||
"scripts.list" => {
|
||||
let i: Devices = parse(args)?;
|
||||
crate::script_library::list(
|
||||
&self.state,
|
||||
&p,
|
||||
i.tenant_id,
|
||||
crate::pagination::PageQuery {
|
||||
cursor: i.cursor,
|
||||
limit: i.limit,
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
"scripts.publish" => {
|
||||
let i: PublishScript = parse(args)?;
|
||||
crate::script_library::publish(&self.state, &p, i.tenant_id, i.input).await
|
||||
}
|
||||
"scripts.plan" => {
|
||||
let i: PlanScript = parse(args)?;
|
||||
crate::script_library::plan(&self.state, &p, i.tenant_id, i.revision_id, i.input)
|
||||
.await
|
||||
}
|
||||
"operations.plan" => {
|
||||
let i: Plan = parse(args)?;
|
||||
crate::jobs::plan_request(&self.state, &p, i.tenant_id, i.input).await
|
||||
|
||||
@@ -0,0 +1,359 @@
|
||||
//! Tenant-owned script revisions. Selection materializes an ordinary immutable
|
||||
//! script plan; submitting and approving it use the existing job lifecycle.
|
||||
use crate::{
|
||||
auth::Principal,
|
||||
jobs::{self, Error, PlanInput, Rollout, Schedule, Targets},
|
||||
pagination::{Cursor, PageQuery},
|
||||
};
|
||||
use axum::{
|
||||
Json, Router,
|
||||
extract::{Path, Query, State},
|
||||
http::{HeaderMap, StatusCode},
|
||||
routing::{get, post},
|
||||
};
|
||||
use rmm_domain::jobs::{
|
||||
Action, PrivilegedScriptProfile, ScriptRevisionReference, WindowsExecutionProfile, hash,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::Row;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Clone, Deserialize, schemars::JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Publish {
|
||||
pub name: String,
|
||||
pub expected_version: i32,
|
||||
pub interpreter: String,
|
||||
pub execution_identity: String,
|
||||
pub script_utf8: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, schemars::JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Selection {
|
||||
pub targets: Targets,
|
||||
pub schedule: Schedule,
|
||||
pub rollout: Rollout,
|
||||
pub reason: String,
|
||||
pub max_runtime_seconds: u32,
|
||||
pub max_output_bytes: u32,
|
||||
}
|
||||
|
||||
fn script(interpreter: &str, identity: &str, body: String) -> Result<Action, Error> {
|
||||
let action = Action::RunScript {
|
||||
interpreter: interpreter.to_owned(),
|
||||
script_utf8: body,
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
windows_execution_profile: (interpreter == "powershell")
|
||||
.then_some(WindowsExecutionProfile::PowerShell51RemoteSigned),
|
||||
privileged_script_profile: (identity != "agent_service")
|
||||
.then_some(PrivilegedScriptProfile::FullMaintenanceV1),
|
||||
};
|
||||
if !action.validate()
|
||||
|| !action.valid_execution_identity(identity)
|
||||
|| !matches!(identity, "agent_service" | "root" | "system")
|
||||
{
|
||||
return Err(Error(StatusCode::BAD_REQUEST, "INVALID_SCRIPT_REVISION"));
|
||||
}
|
||||
Ok(action)
|
||||
}
|
||||
|
||||
fn view(r: &sqlx::postgres::PgRow) -> Value {
|
||||
let body: String = r.get("script_utf8");
|
||||
json!({"revision_id":r.get::<Uuid,_>("revision_id"),"name":r.get::<String,_>("name"),
|
||||
"version":r.get::<i32,_>("version"),"interpreter":r.get::<String,_>("interpreter"),
|
||||
"execution_identity":r.get::<String,_>("execution_identity"),"script_sha256":hash(body.as_bytes()),
|
||||
"script_utf8":body,"created_at":r.get::<chrono::DateTime<chrono::Utc>,_>("created_at"),
|
||||
"created_by":r.get::<String,_>("created_by")})
|
||||
}
|
||||
|
||||
pub async fn list(
|
||||
s: &crate::State,
|
||||
p: &Principal,
|
||||
tenant: Uuid,
|
||||
q: PageQuery,
|
||||
) -> Result<Value, Error> {
|
||||
jobs::scope(p, tenant, false)?;
|
||||
let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?;
|
||||
crate::permissions::require_principal(&mut tx, p, "operations:read").await?;
|
||||
let mut page = Cursor::parse(s, p, "script-library:revision-id", q)
|
||||
.map_err(|s| Error(s, "VALIDATION_ERROR"))?;
|
||||
let rows=sqlx::query("SELECT * FROM script_revisions WHERE revision_id>$1 AND created_at<=$2 ORDER BY revision_id LIMIT $3")
|
||||
.bind(page.last).bind(page.as_of).bind(i64::from(page.limit)+1).fetch_all(&mut *tx).await?;
|
||||
let shown = rows
|
||||
.iter()
|
||||
.take(usize::from(page.limit))
|
||||
.map(view)
|
||||
.collect::<Vec<_>>();
|
||||
let truncated = rows.len() > shown.len();
|
||||
let next = if truncated {
|
||||
Some(
|
||||
page.next(s, rows[shown.len() - 1].get("revision_id"))
|
||||
.map_err(|s| Error(s, "CURSOR_ERROR"))?,
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
tx.commit().await?;
|
||||
Ok(
|
||||
json!({"items":shown,"as_of":page.as_of,"next_cursor":next,"truncated":truncated,"completeness":if truncated {"partial"} else {"complete"}}),
|
||||
)
|
||||
}
|
||||
|
||||
pub async fn publish(
|
||||
s: &crate::State,
|
||||
p: &Principal,
|
||||
tenant: Uuid,
|
||||
input: Publish,
|
||||
) -> Result<Value, Error> {
|
||||
jobs::scope(p, tenant, true)?;
|
||||
if input.name.trim() != input.name
|
||||
|| input.name.is_empty()
|
||||
|| input.name.chars().count() > 120
|
||||
|| input.name.chars().any(char::is_control)
|
||||
|| !(0..i32::MAX).contains(&input.expected_version)
|
||||
{
|
||||
return Err(Error(StatusCode::BAD_REQUEST, "INVALID_SCRIPT_REVISION"));
|
||||
}
|
||||
script(
|
||||
&input.interpreter,
|
||||
&input.execution_identity,
|
||||
input.script_utf8.clone(),
|
||||
)?;
|
||||
let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?;
|
||||
crate::permissions::require_principal(&mut tx, p, "operations:plan").await?;
|
||||
crate::permissions::require_principal(&mut tx, p, "scripts:execute").await?;
|
||||
// Same predecessor implies the same next version. The unique constraint
|
||||
// serializes concurrent publishers without a mutable "latest" row.
|
||||
let version = input.expected_version + 1;
|
||||
let inserted=sqlx::query("INSERT INTO script_revisions(tenant_id,name,version,interpreter,execution_identity,script_utf8,created_by)
|
||||
SELECT $1,$2,$3,$4,$5,$6,$7 WHERE COALESCE((SELECT max(version) FROM script_revisions WHERE name=$2),0)=$8
|
||||
ON CONFLICT (tenant_id,name,version) DO NOTHING RETURNING *")
|
||||
.bind(tenant).bind(&input.name).bind(version).bind(&input.interpreter)
|
||||
.bind(&input.execution_identity).bind(&input.script_utf8).bind(&p.name)
|
||||
.bind(input.expected_version).fetch_optional(&mut *tx).await?;
|
||||
let row=match inserted{
|
||||
Some(r)=>r,
|
||||
None=>sqlx::query("SELECT * FROM script_revisions WHERE name=$1 AND version=$2 AND interpreter=$3 AND execution_identity=$4 AND script_utf8=$5 AND created_by=$6")
|
||||
.bind(input.name).bind(version).bind(input.interpreter).bind(input.execution_identity)
|
||||
.bind(input.script_utf8).bind(&p.name).fetch_optional(&mut *tx).await?
|
||||
.ok_or(Error(StatusCode::CONFLICT,"SCRIPT_REVISION_CONFLICT"))?
|
||||
};
|
||||
tx.commit().await?;
|
||||
Ok(view(&row))
|
||||
}
|
||||
|
||||
pub async fn plan(
|
||||
s: &crate::State,
|
||||
p: &Principal,
|
||||
tenant: Uuid,
|
||||
id: Uuid,
|
||||
input: Selection,
|
||||
) -> Result<Value, Error> {
|
||||
jobs::scope(p, tenant, true)?;
|
||||
let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?;
|
||||
crate::permissions::require_principal(&mut tx, p, "operations:plan").await?;
|
||||
crate::permissions::require_principal(&mut tx, p, "scripts:execute").await?;
|
||||
let row = sqlx::query("SELECT * FROM script_revisions WHERE revision_id=$1")
|
||||
.bind(id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?
|
||||
.ok_or(Error(StatusCode::NOT_FOUND, "NOT_FOUND"))?;
|
||||
tx.commit().await?;
|
||||
let body: String = row.get("script_utf8");
|
||||
let reference = ScriptRevisionReference {
|
||||
revision_id: id,
|
||||
name: row.get("name"),
|
||||
version: row.get("version"),
|
||||
script_sha256: hash(body.as_bytes()),
|
||||
};
|
||||
let identity: String = row.get("execution_identity");
|
||||
let action = script(row.get("interpreter"), &identity, body)?;
|
||||
let plan = PlanInput {
|
||||
targets: input.targets,
|
||||
action,
|
||||
script_variants: vec![],
|
||||
execution_identity: identity,
|
||||
schedule: input.schedule,
|
||||
max_runtime_seconds: input.max_runtime_seconds,
|
||||
max_output_bytes: input.max_output_bytes,
|
||||
rollout: input.rollout,
|
||||
reason: input.reason,
|
||||
artifact_ids: vec![],
|
||||
};
|
||||
jobs::plan_resolved(s, p, tenant, plan, None, Some(reference)).await
|
||||
}
|
||||
|
||||
pub fn routes(r: Router<crate::State>) -> Router<crate::State> {
|
||||
r.route(
|
||||
"/api/v1/tenants/{tenant}/script-revisions",
|
||||
get(list_http).post(publish_http),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/tenants/{tenant}/script-revisions/{revision}/plan",
|
||||
post(plan_http),
|
||||
)
|
||||
}
|
||||
async fn list_http(
|
||||
State(s): State<crate::State>,
|
||||
h: HeaderMap,
|
||||
Path(t): Path<Uuid>,
|
||||
Query(q): Query<PageQuery>,
|
||||
) -> Result<Json<Value>, Error> {
|
||||
let p = jobs::principal(&s, &h, false).await?;
|
||||
Ok(Json(list(&s, &p, t, q).await?))
|
||||
}
|
||||
async fn publish_http(
|
||||
State(s): State<crate::State>,
|
||||
h: HeaderMap,
|
||||
Path(t): Path<Uuid>,
|
||||
Json(i): Json<Publish>,
|
||||
) -> Result<Json<Value>, Error> {
|
||||
let p = jobs::principal(&s, &h, true).await?;
|
||||
Ok(Json(publish(&s, &p, t, i).await?))
|
||||
}
|
||||
async fn plan_http(
|
||||
State(s): State<crate::State>,
|
||||
h: HeaderMap,
|
||||
Path((t, id)): Path<(Uuid, Uuid)>,
|
||||
Json(i): Json<Selection>,
|
||||
) -> Result<Json<Value>, Error> {
|
||||
let p = jobs::principal(&s, &h, true).await?;
|
||||
Ok(Json(plan(&s, &p, t, id, i).await?))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests {
|
||||
use super::*;
|
||||
use chrono::{Duration, Utc};
|
||||
|
||||
/// Shared isolated PostgreSQL fixture in tests/windows_plan_database.py.
|
||||
pub(crate) async fn revision_plan_contract(
|
||||
s: &crate::State,
|
||||
p: &Principal,
|
||||
linux: Uuid,
|
||||
windows: Uuid,
|
||||
) {
|
||||
let tenant = p.tenant;
|
||||
let initial = list(s, p, tenant, PageQuery::default()).await.unwrap();
|
||||
let template = &initial["items"][0];
|
||||
assert_eq!(template["name"], "Windows-Updates installieren");
|
||||
assert_eq!(template["interpreter"], "powershell");
|
||||
let native = script(
|
||||
"powershell",
|
||||
"system",
|
||||
template["script_utf8"].as_str().unwrap().into(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(native.full_maintenance());
|
||||
|
||||
let v1 = Publish {
|
||||
name: "Agentversion".into(),
|
||||
expected_version: 0,
|
||||
interpreter: "posix_sh".into(),
|
||||
execution_identity: "agent_service".into(),
|
||||
script_utf8: "printf '1\\n'\n".into(),
|
||||
};
|
||||
let first = publish(s, p, tenant, v1.clone()).await.unwrap();
|
||||
let retry = publish(s, p, tenant, v1.clone()).await.unwrap();
|
||||
assert_eq!(first, retry);
|
||||
let id = Uuid::parse_str(first["revision_id"].as_str().unwrap()).unwrap();
|
||||
let mut v2 = Publish {
|
||||
script_utf8: "printf '2\\n'\n".into(),
|
||||
..v1.clone()
|
||||
};
|
||||
assert_eq!(
|
||||
publish(s, p, tenant, v2.clone()).await.unwrap_err().0,
|
||||
StatusCode::CONFLICT
|
||||
);
|
||||
v2.expected_version = 1;
|
||||
let second = publish(s, p, tenant, v2).await.unwrap();
|
||||
assert_ne!(first["revision_id"], second["revision_id"]);
|
||||
assert_eq!(second["version"], 2);
|
||||
assert!(
|
||||
list(s, p, Uuid::new_v4(), PageQuery::default())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
|
||||
let mut foreign = rmm_persistence::tenant_tx(&s.pool, Uuid::new_v4())
|
||||
.await
|
||||
.unwrap();
|
||||
let visible: i64 =
|
||||
sqlx::query_scalar("SELECT count(*) FROM script_revisions WHERE revision_id=$1")
|
||||
.bind(id)
|
||||
.fetch_one(&mut *foreign)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(visible, 0);
|
||||
foreign.rollback().await.unwrap();
|
||||
let mut own = rmm_persistence::tenant_tx(&s.pool, tenant).await.unwrap();
|
||||
assert!(
|
||||
sqlx::query(
|
||||
"UPDATE script_revisions SET script_utf8='replacement' WHERE revision_id=$1"
|
||||
)
|
||||
.bind(id)
|
||||
.execute(&mut *own)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
own.rollback().await.unwrap();
|
||||
|
||||
let selection = |asset| Selection {
|
||||
targets: Targets {
|
||||
asset_ids: vec![asset],
|
||||
},
|
||||
schedule: Schedule {
|
||||
not_before: Utc::now(),
|
||||
start_before: Utc::now() + Duration::minutes(30),
|
||||
},
|
||||
rollout: Rollout {
|
||||
max_parallel: 1,
|
||||
halt_after_failures: 1,
|
||||
},
|
||||
reason: "isolated library contract".into(),
|
||||
max_runtime_seconds: 60,
|
||||
max_output_bytes: 4096,
|
||||
};
|
||||
assert_eq!(
|
||||
plan(s, p, tenant, id, selection(windows))
|
||||
.await
|
||||
.unwrap_err()
|
||||
.1,
|
||||
"UNSUPPORTED_CAPABILITY"
|
||||
);
|
||||
let planned = plan(s, p, tenant, id, selection(linux)).await.unwrap();
|
||||
let plan_id = Uuid::parse_str(planned["plan_id"].as_str().unwrap()).unwrap();
|
||||
let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await.unwrap();
|
||||
let bytes: Vec<u8> =
|
||||
sqlx::query_scalar("SELECT payload FROM operation_plans WHERE plan_id=$1")
|
||||
.bind(plan_id)
|
||||
.fetch_one(&mut *tx)
|
||||
.await
|
||||
.unwrap();
|
||||
tx.commit().await.unwrap();
|
||||
let bound: rmm_domain::jobs::PlanPayload = serde_json::from_slice(&bytes).unwrap();
|
||||
let reference = bound.script_revision.unwrap();
|
||||
assert_eq!(reference.revision_id, id);
|
||||
assert_eq!(reference.version, 1);
|
||||
assert_eq!(reference.script_sha256, hash(v1.script_utf8.as_bytes()));
|
||||
assert!(
|
||||
matches!(&bound.jobs[0].payload.action, Action::RunScript { script_utf8, .. } if script_utf8 == &v1.script_utf8)
|
||||
);
|
||||
let response = jobs::submit(
|
||||
s,
|
||||
p,
|
||||
tenant,
|
||||
plan_id,
|
||||
jobs::Submit {
|
||||
idempotency_key: "fixed-library".into(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response["approval_state"], "pending_approval");
|
||||
assert_eq!(response["job_count"], 0);
|
||||
}
|
||||
}
|
||||
@@ -330,6 +330,7 @@ pub(super) async fn test_fixed_echo(
|
||||
max_parallel: 1,
|
||||
halt_after_failures: 1,
|
||||
recipe_references: vec![],
|
||||
script_revision: None,
|
||||
artifact_references: vec![],
|
||||
};
|
||||
let scope = ProbeScope::from_plan(&plan, op).unwrap();
|
||||
@@ -515,5 +516,5 @@ pub(super) async fn test_fixed_echo(
|
||||
tx.rollback().await.unwrap();
|
||||
}
|
||||
}
|
||||
crate::windows_echo_completion::test_completed_echo(admin,s,&p,&w).await;
|
||||
crate::windows_echo_completion::test_completed_echo(admin, s, &p, &w).await;
|
||||
}
|
||||
|
||||
@@ -348,6 +348,7 @@ mod tests {
|
||||
max_parallel: 1,
|
||||
halt_after_failures: 1,
|
||||
recipe_references: vec![reference(&m)],
|
||||
script_revision: None,
|
||||
artifact_references: vec![JobArtifactReference {
|
||||
job_id: job.job_id,
|
||||
attempt_id: job.attempt_id,
|
||||
|
||||
Reference in New Issue
Block a user