use crate::jobs::Error; use axum::{ Json, Router, extract::{Path, State}, http::{HeaderMap, StatusCode}, routing::post, }; use serde::Deserialize; use serde_json::{Value, json}; use sqlx::{Postgres, Transaction}; use uuid::Uuid; #[derive(Deserialize)] #[serde(deny_unknown_fields)] pub struct Reason { reason: String, } #[derive(Deserialize)] #[serde(deny_unknown_fields)] pub struct Stop { stopped: bool, reason: String, } pub fn routes(r: Router) -> Router { r.route( "/api/v1/tenants/{tenant}/devices/{asset}/revocation", post(revoke_device), ) .route( "/api/v1/tenants/{tenant}/operation-plans/{plan}/revocation", post(revoke_plan), ) .route("/api/v1/tenants/{tenant}/execution-stop", post(stop)) } async fn context<'a>( s: &'a crate::State, h: &HeaderMap, t: Uuid, permission: &str, reason: &str, ) -> Result<(crate::auth::Principal, Transaction<'a, Postgres>), Error> { let p = s .auth .principal(s, h, true) .await .map_err(|status| Error(status, crate::auth::error_code(status)))?; crate::jobs::scope(&p, t, true)?; if p.session_hash.is_none() { return Err(Error(StatusCode::FORBIDDEN, "INTERACTIVE_AUTH_REQUIRED")); } if reason.is_empty() || reason.len() > 1024 { return Err(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR")); } let mut tx = rmm_persistence::tenant_tx(&s.pool, t).await?; crate::permissions::require_principal(&mut tx, &p, permission).await?; Ok((p, tx)) } async fn audit( tx: &mut Transaction<'_, Postgres>, p: &crate::auth::Principal, event: &str, data: Value, ) -> Result<(), Error> { sqlx::query("INSERT INTO audit_events VALUES($1,$2,$3,$4,$5,now())").bind(p.tenant).bind(Uuid::new_v4()).bind(&p.name).bind(event).bind(json!({"decision":data,"session_hash":p.session_hash,"approval_origin":p.approval_origin(),"testsimulation":p.testsimulation})).execute(&mut **tx).await?; Ok(()) } pub async fn revoke_device( State(s): State, h: HeaderMap, Path((t, asset)): Path<(Uuid, Uuid)>, Json(i): Json, ) -> Result, Error> { let (p, mut tx) = context(&s, &h, t, "devices:revoke", &i.reason).await?; let n=sqlx::query("UPDATE agent_installations SET revoked_at=COALESCE(revoked_at,now()),connection_generation=connection_generation+1,previous_certificate_sha256=NULL,previous_certificate_until=NULL WHERE asset_id=$1").bind(asset).execute(&mut *tx).await?.rows_affected(); 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?; audit( &mut tx, &p, "device_revoked", json!({"asset_id":asset,"reason":i.reason}), ) .await?; tx.commit().await?; Ok(Json(json!({"asset_id":asset,"revoked":true}))) } pub async fn revoke_plan( State(s): State, h: HeaderMap, Path((t, plan)): Path<(Uuid, Uuid)>, Json(i): Json, ) -> Result, Error> { let (p, mut tx) = context(&s, &h, t, "plans:revoke", &i.reason).await?; let op:Option=sqlx::query_scalar("UPDATE approval_requests SET approval_state='revoked' WHERE plan_id=$1 AND approval_state IN ('pending_approval','approved','revoked') RETURNING operation_id").bind(plan).fetch_optional(&mut *tx).await?; let op = op.ok_or(Error(StatusCode::NOT_FOUND, "NOT_FOUND"))?; sqlx::query( "UPDATE authorizations SET revoked_at=COALESCE(revoked_at,now()) WHERE operation_id=$1", ) .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?; audit( &mut tx, &p, "plan_revoked", json!({"plan_id":plan,"operation_id":op,"reason":i.reason}), ) .await?; tx.commit().await?; Ok(Json(json!({"operation_id":op,"approval_state":"revoked"}))) } pub async fn stop( State(s): State, h: HeaderMap, Path(t): Path, Json(i): Json, ) -> Result, Error> { let (p, mut tx) = context(&s, &h, t, "tenant:stop", &i.reason).await?; sqlx::query("UPDATE tenants SET changes_stopped=$1") .bind(i.stopped) .execute(&mut *tx) .await?; audit( &mut tx, &p, "tenant_execution_stop", json!({"stopped":i.stopped,"reason":i.reason}), ) .await?; tx.commit().await?; Ok(Json(json!({"tenant_id":t,"changes_stopped":i.stopped}))) }