Filter orders before pagination and expose recorded decisions and result links
This commit is contained in:
@@ -66,6 +66,7 @@ pub(super) async fn summaries(
|
||||
"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"),
|
||||
"decision":row.get::<Option<Value>,_>("decision"),
|
||||
}));
|
||||
}
|
||||
Ok(items)
|
||||
|
||||
@@ -240,7 +240,16 @@ pub async fn detail(
|
||||
item["recent_jobs"] = if p.permits_scope("operations:read")
|
||||
&& crate::permissions::allowed(&mut tx, &p.name, "operations:read").await?
|
||||
{
|
||||
sqlx::query_scalar::<_,Value>("SELECT jsonb_build_object('job_id',j.job_id,'operation_id',j.operation_id,'state',j.state,'created_at',r.created_at) FROM jobs j JOIN approval_requests r USING(tenant_id,operation_id) WHERE j.tenant_id=$1 AND j.asset_id=$2 AND j.agent_id=$3 ORDER BY r.created_at DESC,j.job_id LIMIT 20")
|
||||
sqlx::query_scalar::<_, Value>(
|
||||
"SELECT jsonb_build_object(
|
||||
'job_id', j.job_id, 'operation_id', j.operation_id, 'state', j.state, 'created_at', r.created_at,
|
||||
'title', coalesce(nullif(plan_view.payload#>>'{script_revision,name}', ''), nullif(btrim(plan_view.payload->>'reason'), '')),
|
||||
'action', convert_from(j.payload, 'UTF8')::jsonb#>>'{action,action}')
|
||||
FROM jobs j JOIN approval_requests r USING (tenant_id, operation_id)
|
||||
JOIN operation_plans p USING (tenant_id, plan_id)
|
||||
CROSS JOIN LATERAL (SELECT convert_from(p.payload, 'UTF8')::jsonb AS payload) AS plan_view
|
||||
WHERE j.tenant_id=$1 AND j.asset_id=$2 AND j.agent_id=$3
|
||||
ORDER BY r.created_at DESC, j.job_id LIMIT 20")
|
||||
.bind(tenant).bind(asset).bind(row.get::<Uuid,_>("agent_id")).fetch_all(&mut *tx).await?.into()
|
||||
} else {
|
||||
Value::Null
|
||||
|
||||
@@ -1348,12 +1348,17 @@ enum OrderSort {
|
||||
Recent,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[derive(Default, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct OrderListQuery {
|
||||
sort: Option<OrderSort>,
|
||||
cursor: Option<String>,
|
||||
limit: Option<u16>,
|
||||
q: Option<String>,
|
||||
device: Option<String>,
|
||||
status: Option<String>,
|
||||
from: Option<DateTime<Utc>>,
|
||||
until: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
async fn operations_http(
|
||||
@@ -1363,16 +1368,48 @@ async fn operations_http(
|
||||
axum::extract::Query(query): axum::extract::Query<OrderListQuery>,
|
||||
) -> Result<Json<Value>> {
|
||||
let p = principal(&s, &h, false).await?;
|
||||
order_list(&s, &p, t, query).await.map(Json)
|
||||
}
|
||||
|
||||
async fn order_list(
|
||||
s: &crate::State,
|
||||
p: &Principal,
|
||||
t: Uuid,
|
||||
query: OrderListQuery,
|
||||
) -> Result<Value> {
|
||||
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 recent = matches!(query.sort, Some(OrderSort::Recent));
|
||||
let q = query.q.as_deref().map(str::trim).filter(|q| !q.is_empty());
|
||||
let device = query.device.as_deref().map(str::trim).filter(|q| !q.is_empty());
|
||||
let status = query.status.as_deref();
|
||||
if [q, device].into_iter().flatten().any(|s| s.len() > 256 || s.chars().any(char::is_control))
|
||||
|| status.is_some_and(|s| !matches!(s, "pending_approval" | "approved" | "rejected" | "expired"
|
||||
| "revoked" | "queued" | "running" | "succeeded" | "partially_succeeded"
|
||||
| "failed" | "cancelled" | "needs_attention"))
|
||||
|| query.from.zip(query.until).is_some_and(|(start, end)| start >= end)
|
||||
{
|
||||
return Err(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"));
|
||||
}
|
||||
let filtered = q.is_some() || device.is_some() || status.is_some() || query.from.is_some() || query.until.is_some();
|
||||
let recent = filtered || matches!(query.sort, Some(OrderSort::Recent));
|
||||
let ordering = if recent { "operations:created_at:desc" } else { "operations:operation_id:asc" };
|
||||
let mut page = crate::pagination::Cursor::parse(&s, &p, ordering, crate::pagination::PageQuery {
|
||||
let device_names = device.is_some() && p.permits_scope("inventory:read")
|
||||
&& crate::permissions::allowed(&mut tx, &p.name, "inventory:read").await?;
|
||||
let cursor_scope = if filtered {
|
||||
format!("{ordering}:{}", hash(json!([q,device,status,query.from,query.until,device_names]).to_string().as_bytes()))
|
||||
} else { ordering.to_owned() };
|
||||
let mut page = crate::pagination::Cursor::parse(&s, &p, &cursor_scope, crate::pagination::PageQuery {
|
||||
cursor: query.cursor, limit: query.limit,
|
||||
}).map_err(|status| Error(status, "VALIDATION_ERROR"))?;
|
||||
let limit = i64::from(page.limit) + 1;
|
||||
let ids: Vec<(Uuid, DateTime<Utc>)> = if recent {
|
||||
let ids: Vec<(Uuid, DateTime<Utc>)> = if filtered {
|
||||
sqlx::query_as(include_str!("order_filter.sql"))
|
||||
.bind(page.as_of).bind(page.last_created_at).bind(page.last)
|
||||
.bind(query.from).bind(query.until).bind(q).bind(status).bind(device)
|
||||
.bind(device.and_then(|s| Uuid::parse_str(s).ok())).bind(device_names).bind(limit)
|
||||
.fetch_all(&mut *tx).await?
|
||||
} else if recent {
|
||||
sqlx::query_as("SELECT operation_id,created_at FROM approval_requests WHERE created_at<=$1
|
||||
AND ($2::timestamptz IS NULL OR (created_at,operation_id)<($2,$3))
|
||||
ORDER BY created_at DESC,operation_id DESC LIMIT $4")
|
||||
@@ -1399,9 +1436,9 @@ async fn operations_http(
|
||||
for (id, _) in ids.into_iter().take(usize::from(page.limit)) {
|
||||
items.push(operation(&s, &p, t, id).await?)
|
||||
}
|
||||
Ok(Json(
|
||||
Ok(
|
||||
json!({"items":items,"next_cursor":next,"completeness":if truncated{"partial"}else{"complete"},"truncated":truncated,"as_of":page.as_of}),
|
||||
))
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
SELECT r.operation_id, r.created_at
|
||||
FROM approval_requests r JOIN operation_plans p USING (tenant_id, plan_id)
|
||||
CROSS JOIN LATERAL (SELECT convert_from(p.payload, 'UTF8')::jsonb AS payload) AS plan_view
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT count(*) AS total, count(*) FILTER (WHERE state = 'unknown') AS unresolved,
|
||||
count(*) FILTER (WHERE state = 'succeeded') AS succeeded,
|
||||
count(*) FILTER (WHERE state = 'cancelled') AS cancelled,
|
||||
count(*) FILTER (WHERE state IN ('succeeded','failed','cancelled','expired','closed_unknown')) AS terminal,
|
||||
count(*) FILTER (WHERE state IN ('running','verifying','awaiting_reboot')) AS active
|
||||
FROM jobs j WHERE j.tenant_id = r.tenant_id AND j.operation_id = r.operation_id
|
||||
AND $7::text IS NOT NULL AND r.approval_state = 'approved'
|
||||
) execution ON true
|
||||
WHERE r.created_at <= $1
|
||||
AND ($2::timestamptz IS NULL OR (r.created_at, r.operation_id) < ($2, $3))
|
||||
AND ($4::timestamptz IS NULL OR r.created_at >= $4)
|
||||
AND ($5::timestamptz IS NULL OR r.created_at < $5)
|
||||
AND ($6::text IS NULL OR
|
||||
strpos(lower(coalesce(plan_view.payload#>>'{script_revision,name}', '')), lower($6)) > 0 OR
|
||||
strpos(lower(coalesce(plan_view.payload->>'reason', '')), lower($6)) > 0)
|
||||
AND ($7::text IS NULL OR $7 = CASE
|
||||
WHEN r.approval_state = 'pending_approval' AND p.expires_at <= now() THEN 'expired'
|
||||
WHEN r.approval_state <> 'approved' OR execution.total = 0 THEN r.approval_state
|
||||
WHEN execution.unresolved > 0 THEN 'needs_attention'
|
||||
WHEN execution.succeeded = execution.total THEN 'succeeded'
|
||||
WHEN execution.terminal = execution.total THEN CASE
|
||||
WHEN execution.succeeded > 0 THEN 'partially_succeeded'
|
||||
WHEN execution.cancelled = execution.total THEN 'cancelled' ELSE 'failed' END
|
||||
WHEN execution.active > 0 THEN 'running' ELSE 'queued'
|
||||
END)
|
||||
AND ($8::text IS NULL OR EXISTS (
|
||||
SELECT 1 FROM jsonb_array_elements(plan_view.payload->'jobs') AS job
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT o.data->>'hostname' AS hostname FROM observations o
|
||||
WHERE $10 AND o.tenant_id = r.tenant_id AND o.agent_id = (job#>>'{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
|
||||
WHERE job#>>'{payload,asset_id}' = $9::uuid::text
|
||||
OR strpos(lower(coalesce(inventory.hostname, '')), lower($8)) > 0
|
||||
))
|
||||
ORDER BY r.created_at DESC, r.operation_id DESC LIMIT $11
|
||||
@@ -13,9 +13,31 @@ SELECT p.tenant_id, p.name AS customer_name, p.plan_id, p.plan_hash,
|
||||
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,
|
||||
CASE
|
||||
WHEN decision.event_id IS NOT NULL THEN jsonb_build_object(
|
||||
'principal', decision.principal, 'at', decision.created_at,
|
||||
'testsimulation', decision.data->'testsimulation' = 'true'::jsonb)
|
||||
WHEN r.approval_state = 'approved' AND authorization.authorization_id IS NOT NULL THEN jsonb_build_object(
|
||||
'principal', authorization.principal, 'at', authorization.created_at,
|
||||
'testsimulation', authorization.testsimulation)
|
||||
END AS decision,
|
||||
coalesce(targets.items, '[]'::jsonb) AS targets
|
||||
FROM selected p
|
||||
LEFT JOIN approval_requests r USING (tenant_id,plan_id)
|
||||
LEFT JOIN authorizations authorization ON authorization.tenant_id = p.tenant_id
|
||||
AND authorization.operation_id = r.operation_id AND authorization.plan_id = p.plan_id
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT e.event_id, e.principal, e.created_at, e.data
|
||||
FROM audit_events e
|
||||
WHERE e.tenant_id = p.tenant_id AND e.data->>'operation_id' = r.operation_id::text
|
||||
AND e.event_type IN ('plan_revoked', 'plan_authorization')
|
||||
AND ((r.approval_state = 'revoked' AND e.event_type = 'plan_revoked')
|
||||
OR (e.event_type = 'plan_authorization' AND e.data->>'plan_id' = p.plan_id::text
|
||||
AND e.data->>'plan_hash' = p.plan_hash
|
||||
AND e.data->>'decision' = CASE r.approval_state WHEN 'approved' THEN 'approve' WHEN 'rejected' THEN 'reject' END))
|
||||
ORDER BY e.created_at, e.event_id
|
||||
LIMIT 1
|
||||
) decision ON true
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT jsonb_agg(jsonb_build_object(
|
||||
'asset_id', j#>>'{payload,asset_id}', 'agent_id', j#>>'{payload,agent_id}',
|
||||
|
||||
Reference in New Issue
Block a user