Add versioned script library, reconcile permit refusals and compact helper captures
This commit is contained in:
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user