Expose a permission-filtered approvals inbox and readable order summaries
This commit is contained in:
@@ -0,0 +1,226 @@
|
||||
//! Read-only approvals inbox and display metadata shared with order details.
|
||||
use crate::{
|
||||
auth::Principal,
|
||||
jobs::Error,
|
||||
pagination::{Cursor, PageQuery},
|
||||
};
|
||||
use axum::{
|
||||
Json,
|
||||
extract::{Query, State},
|
||||
http::{HeaderMap, StatusCode},
|
||||
};
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::{Postgres, Row, Transaction};
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Clone, Copy, Default, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Status {
|
||||
#[default]
|
||||
Pending,
|
||||
History,
|
||||
}
|
||||
|
||||
#[derive(Default, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Filters {
|
||||
tenant_id: Option<Uuid>,
|
||||
#[serde(default)]
|
||||
status: Status,
|
||||
limit: Option<u16>,
|
||||
cursor: Option<String>,
|
||||
#[serde(default)]
|
||||
count_only: bool,
|
||||
}
|
||||
|
||||
pub(super) async fn summaries(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
p: &Principal,
|
||||
ids: &[Uuid],
|
||||
) -> Result<HashMap<Uuid, Value>, Error> {
|
||||
let inventory = p.permits_scope("inventory:read")
|
||||
&& crate::permissions::allowed(tx, &p.name, "inventory:read").await?;
|
||||
let rows = sqlx::query(include_str!("order_summary.sql"))
|
||||
.bind(ids)
|
||||
.bind(inventory)
|
||||
.fetch_all(&mut **tx)
|
||||
.await?;
|
||||
let mut items = HashMap::with_capacity(rows.len());
|
||||
for row in rows {
|
||||
let action = row.get::<Option<String>, _>("action");
|
||||
let revision = row.get::<Option<Value>, _>("script_revision");
|
||||
let reason = row.get::<Option<String>, _>("reason");
|
||||
let title = revision
|
||||
.as_ref()
|
||||
.and_then(|r| r["name"].as_str())
|
||||
.or_else(|| reason.as_deref().filter(|s| !s.trim().is_empty()))
|
||||
.unwrap_or("Auftrag");
|
||||
let plan_id: Uuid = row.get("plan_id");
|
||||
items.insert(plan_id, json!({
|
||||
"title": title, "action": action, "reason": reason, "script_revision": revision,
|
||||
"tenant_id":row.get::<Uuid,_>("tenant_id"), "customer_name":row.get::<String,_>("customer_name"),
|
||||
"operation_id":row.get::<Option<Uuid>,_>("operation_id"), "plan_id":plan_id,
|
||||
"plan_hash":row.get::<String,_>("plan_hash"), "requester":row.get::<String,_>("requester"),
|
||||
"targets":row.get::<Value,_>("targets"), "created_at":row.get::<DateTime<Utc>,_>("created_at"),
|
||||
"expires_at":row.get::<DateTime<Utc>,_>("expires_at"), "approval_state":row.get::<Option<String>,_>("approval_state"),
|
||||
}));
|
||||
}
|
||||
Ok(items)
|
||||
}
|
||||
|
||||
pub(super) async fn summary(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
p: &Principal,
|
||||
plan: Uuid,
|
||||
) -> Result<Value, Error> {
|
||||
summaries(tx, p, &[plan])
|
||||
.await?
|
||||
.remove(&plan)
|
||||
.ok_or(Error(StatusCode::NOT_FOUND, "NOT_FOUND"))
|
||||
}
|
||||
|
||||
pub async fn inbox(
|
||||
State(s): State<crate::State>,
|
||||
h: HeaderMap,
|
||||
Query(q): Query<Filters>,
|
||||
) -> Result<Json<Value>, Error> {
|
||||
let p = crate::jobs::principal(&s, &h, false).await?;
|
||||
list(&s, &p, q).await.map(Json)
|
||||
}
|
||||
|
||||
type Key = (DateTime<Utc>, Uuid, Uuid, Uuid); // created_at, tenant_id, operation_id, plan_id
|
||||
|
||||
async fn select_tenant(tx: &mut Transaction<'_, Postgres>, tenant: Uuid) -> Result<(), Error> {
|
||||
sqlx::query("SELECT set_config('app.tenant_id',$1,true)")
|
||||
.bind(tenant.to_string())
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn list(s: &crate::State, p: &Principal, q: Filters) -> Result<Value, Error> {
|
||||
if p.session_hash.is_none() || !p.operator {
|
||||
return Err(Error(StatusCode::FORBIDDEN, "INTERACTIVE_AUTH_REQUIRED"));
|
||||
}
|
||||
if q.tenant_id.is_some_and(|id| !p.tenants.contains(&id)) {
|
||||
return Err(Error(StatusCode::NOT_FOUND, "NOT_FOUND"));
|
||||
}
|
||||
let mut tenants = p.tenants.clone();
|
||||
tenants.sort_unstable();
|
||||
tenants.dedup();
|
||||
|
||||
// Counts, page boundaries and rows must use the same memberships and
|
||||
// approval states. Only switch the transaction to an authenticated tenant.
|
||||
let mut tx = s.pool.begin().await?;
|
||||
sqlx::query("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY")
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
let mut permitted = Vec::new();
|
||||
let mut customers = Vec::new();
|
||||
for tenant in tenants {
|
||||
select_tenant(&mut tx, tenant).await?;
|
||||
if crate::permissions::allowed(&mut tx, &p.name, "operations:read").await?
|
||||
&& crate::permissions::allowed(&mut tx, &p.name, "plans:approve").await?
|
||||
{
|
||||
let name: String = sqlx::query_scalar("SELECT name FROM tenants WHERE tenant_id=$1")
|
||||
.bind(tenant)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
customers.push(json!({"tenant_id":tenant, "name":name}));
|
||||
permitted.push(tenant);
|
||||
}
|
||||
}
|
||||
if q.tenant_id
|
||||
.is_some_and(|tenant| !permitted.contains(&tenant))
|
||||
{
|
||||
return Err(Error(StatusCode::FORBIDDEN, "FORBIDDEN"));
|
||||
}
|
||||
let scope = format!(
|
||||
"approvals:{}",
|
||||
rmm_domain::jobs::hash(
|
||||
json!([q.tenant_id, q.status, permitted])
|
||||
.to_string()
|
||||
.as_bytes()
|
||||
)
|
||||
);
|
||||
let mut page = Cursor::parse(
|
||||
s,
|
||||
p,
|
||||
&scope,
|
||||
PageQuery {
|
||||
cursor: q.cursor,
|
||||
limit: q.limit,
|
||||
},
|
||||
)
|
||||
.map_err(|s| Error(s, crate::auth::error_code(s)))?;
|
||||
let cap = usize::from(page.limit);
|
||||
let mut pending_count = 0i64;
|
||||
let mut keys: Vec<Key> = Vec::new();
|
||||
for tenant in permitted
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|id| q.tenant_id.is_none_or(|t| t == *id))
|
||||
{
|
||||
select_tenant(&mut tx, tenant).await?;
|
||||
pending_count += sqlx::query_scalar::<_,i64>(
|
||||
"SELECT count(*) FROM approval_requests r JOIN operation_plans p USING(tenant_id,plan_id)
|
||||
WHERE r.created_at <= $1 AND r.approval_state='pending_approval' AND p.expires_at>now()"
|
||||
).bind(page.as_of).fetch_one(&mut *tx).await?;
|
||||
if q.count_only {
|
||||
continue;
|
||||
}
|
||||
let rows:Vec<Key> = sqlx::query_as(
|
||||
"SELECT r.created_at,r.tenant_id,r.operation_id,r.plan_id
|
||||
FROM approval_requests r JOIN operation_plans p USING(tenant_id,plan_id)
|
||||
WHERE r.created_at <= $1 AND (r.approval_state='pending_approval' AND p.expires_at>now()) = $2
|
||||
AND ($3::timestamptz IS NULL OR (r.created_at,r.tenant_id,r.operation_id)<($3,$4,$5))
|
||||
ORDER BY r.created_at DESC,r.tenant_id DESC,r.operation_id DESC LIMIT $6"
|
||||
).bind(page.as_of).bind(matches!(q.status,Status::Pending)).bind(page.last_created_at)
|
||||
.bind(page.last_tenant).bind(page.last).bind(i64::from(page.limit)+1).fetch_all(&mut *tx).await?;
|
||||
keys.extend(rows);
|
||||
keys.sort_unstable_by(|a, b| b.cmp(a));
|
||||
keys.truncate(cap + 1);
|
||||
}
|
||||
let truncated = keys.len() > cap;
|
||||
keys.truncate(cap);
|
||||
let next = if truncated {
|
||||
let (date, tenant, id, _) = keys[cap - 1];
|
||||
page.last_tenant = Some(tenant);
|
||||
page.last_created_at = Some(date);
|
||||
Some(
|
||||
page.next(s, id)
|
||||
.map_err(|s| Error(s, crate::auth::error_code(s)))?,
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut by_customer: BTreeMap<Uuid, Vec<Uuid>> = BTreeMap::new();
|
||||
for (_, tenant, _, plan) in &keys {
|
||||
by_customer.entry(*tenant).or_default().push(*plan);
|
||||
}
|
||||
let mut rows = HashMap::new();
|
||||
for (tenant, ids) in by_customer {
|
||||
select_tenant(&mut tx, tenant).await?;
|
||||
rows.extend(
|
||||
summaries(&mut tx, p, &ids)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|(id, row)| ((tenant, id), row)),
|
||||
);
|
||||
}
|
||||
let mut items = Vec::with_capacity(keys.len());
|
||||
for (_, tenant, _, plan) in keys {
|
||||
items.push(rows.remove(&(tenant, plan)).ok_or(Error(
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"DEPENDENCY_UNAVAILABLE",
|
||||
))?);
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(
|
||||
json!({"items":items,"customers":customers,"can_review":!permitted.is_empty(),"pending_count":pending_count,"next_cursor":next,"as_of":page.as_of,
|
||||
"truncated":truncated,"completeness":if truncated{"partial"}else{"complete"}}),
|
||||
)
|
||||
}
|
||||
+20
-13
@@ -65,7 +65,8 @@ pub(crate) async fn principal(
|
||||
.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))
|
||||
r.route("/api/v1/approvals", get(crate::approvals::inbox))
|
||||
.route("/api/v1/tenants/{tenant}/operation-plans", post(plan_http))
|
||||
.route(
|
||||
"/api/v1/tenants/{tenant}/operation-plans/{plan}",
|
||||
get(plan_get_http),
|
||||
@@ -1089,7 +1090,7 @@ pub async fn operation(
|
||||
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 jobs=sqlx::query("SELECT asset_id,agent_id,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");
|
||||
@@ -1126,10 +1127,15 @@ pub async fn operation(
|
||||
})
|
||||
};
|
||||
let items = jobs.iter().map(job_summary).collect::<Vec<_>>();
|
||||
let mut result = crate::approvals::summary(&mut tx, p, plan.plan_id).await?;
|
||||
result["state"] = json!(approval);
|
||||
result["planned_job_count"] = json!(plan.jobs.len());
|
||||
result["job_count"] = json!(n);
|
||||
result["execution_state"] = json!(execution);
|
||||
result["counts"] = json!(counts);
|
||||
result["jobs"] = json!(items);
|
||||
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}),
|
||||
)
|
||||
Ok(result)
|
||||
}
|
||||
fn job_view(r: &sqlx::postgres::PgRow) -> Value {
|
||||
let mut result = job_summary(r);
|
||||
@@ -1137,14 +1143,14 @@ fn job_view(r: &sqlx::postgres::PgRow) -> Value {
|
||||
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")})
|
||||
json!({"asset_id":r.get::<Uuid,_>("asset_id"),"agent_id":r.get::<Uuid,_>("agent_id"),"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",
|
||||
"SELECT asset_id,agent_id,job_id,attempt_id,state,cancel_requested,revision,result,pending_reason FROM jobs WHERE job_id=$1",
|
||||
)
|
||||
.bind(id)
|
||||
.fetch_optional(&mut *tx)
|
||||
@@ -1210,13 +1216,14 @@ async fn plan_get_http(
|
||||
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?;
|
||||
let metadata = crate::approvals::summary(&mut tx, &p, id).await?;
|
||||
let approval = metadata["approval_state"].as_str().map(str::to_owned);
|
||||
let mut view = plan_view(&plan, &hash, approval, &bytes)?;
|
||||
for (key, value) in metadata.as_object().into_iter().flatten() {
|
||||
view[key] = value.clone();
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(Json(plan_view(&plan, &hash, approval, &bytes)?))
|
||||
Ok(Json(view))
|
||||
}
|
||||
async fn operation_http(
|
||||
State(s): State<crate::State>,
|
||||
|
||||
@@ -8,6 +8,7 @@ mod agent_updates;
|
||||
mod api;
|
||||
mod devices;
|
||||
mod artifact_store;
|
||||
mod approvals;
|
||||
mod auth;
|
||||
mod local_auth;
|
||||
mod mcp_tokens;
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
-- Resolve display data only for the plans on the authorized page. Each target
|
||||
-- retains its immutable IDs even if the device has since changed its hostname.
|
||||
WITH selected AS MATERIALIZED (
|
||||
SELECT p.tenant_id, t.name, p.plan_id, p.plan_hash, p.expires_at, p.created_at,
|
||||
convert_from(p.payload, 'UTF8')::jsonb AS payload, p.principal
|
||||
FROM operation_plans p JOIN tenants t USING (tenant_id)
|
||||
WHERE p.plan_id = ANY($1)
|
||||
)
|
||||
SELECT p.tenant_id, p.name AS customer_name, p.plan_id, p.plan_hash,
|
||||
r.operation_id, coalesce(r.principal,p.principal) AS requester, p.expires_at,
|
||||
coalesce(r.created_at,p.created_at) AS created_at, p.payload->>'reason' AS reason,
|
||||
p.payload->'script_revision' AS script_revision,
|
||||
p.payload#>>'{jobs,0,payload,action,action}' AS action,
|
||||
CASE WHEN r.approval_state='pending_approval' AND p.expires_at <= now()
|
||||
THEN 'expired' ELSE r.approval_state END AS approval_state,
|
||||
coalesce(targets.items, '[]'::jsonb) AS targets
|
||||
FROM selected p
|
||||
LEFT JOIN approval_requests r USING (tenant_id,plan_id)
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT jsonb_agg(jsonb_build_object(
|
||||
'asset_id', j#>>'{payload,asset_id}', 'agent_id', j#>>'{payload,agent_id}',
|
||||
'hostname', inventory.hostname
|
||||
) ORDER BY ord) AS items
|
||||
FROM jsonb_array_elements(p.payload->'jobs') WITH ORDINALITY AS jobs(j,ord)
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT o.data->>'hostname' AS hostname FROM observations o
|
||||
WHERE $2 AND o.tenant_id=p.tenant_id AND o.agent_id=(j#>>'{payload,agent_id}')::uuid
|
||||
AND o.source_id IN ('linux.base','windows.base')
|
||||
ORDER BY o.observed_at DESC, o.received_at DESC, o.sequence DESC LIMIT 1
|
||||
) inventory ON true
|
||||
) targets ON true
|
||||
@@ -19,6 +19,8 @@ pub struct Cursor {
|
||||
pub last: Uuid,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub last_tenant: Option<Uuid>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub last_created_at: Option<DateTime<Utc>>,
|
||||
pub limit: u16,
|
||||
}
|
||||
impl Cursor {
|
||||
@@ -74,6 +76,7 @@ impl Cursor {
|
||||
as_of: Utc::now(),
|
||||
last: Uuid::nil(),
|
||||
last_tenant: None,
|
||||
last_created_at: None,
|
||||
limit: q.limit.unwrap_or(100),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
-- Count and page pending requests by customer without walking decided requests.
|
||||
CREATE INDEX approval_requests_pending_inbox ON approval_requests
|
||||
(tenant_id, created_at DESC, operation_id DESC) INCLUDE (plan_id)
|
||||
WHERE approval_state = 'pending_approval';
|
||||
|
||||
CREATE INDEX approval_requests_timeline ON approval_requests
|
||||
(tenant_id, created_at DESC, operation_id DESC) INCLUDE (plan_id, approval_state);
|
||||
Reference in New Issue
Block a user