Files
rust-discovery/crates/server/src/controls.rs
T

279 lines
11 KiB
Rust

use crate::jobs::Error;
use axum::{
Json, Router,
extract::{Path, Query, State},
http::{HeaderMap, StatusCode},
routing::{delete, 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<crate::State>) -> Router<crate::State> {
r.route(
"/api/v1/tenants/{tenant}/devices/{asset}/revocation",
post(revoke_device),
)
.route("/api/v1/tenants/{tenant}/devices/{asset}", delete(remove_device))
.route(
"/api/v1/tenants/{tenant}/devices/{asset}/hypervisor",
post(assign_hypervisor),
)
.route(
"/api/v1/tenants/{tenant}/devices/{asset}/archive",
post(archive_device),
)
.route(
"/api/v1/tenants/{tenant}/operation-plans/{plan}/revocation",
post(revoke_plan),
)
.route(
"/api/v1/tenants/{tenant}/execution-stop",
post(stop).get(stop_status),
)
}
async fn stop_status(
State(s): State<crate::State>,
h: HeaderMap,
Path(tenant): Path<Uuid>,
) -> Result<Json<Value>, Error> {
let principal = crate::jobs::principal(&s, &h, false).await?;
crate::jobs::scope(&principal, tenant, false)?;
if principal.session_hash.is_none() {
return Err(Error(StatusCode::FORBIDDEN, "INTERACTIVE_AUTH_REQUIRED"));
}
let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?;
if !principal.permits_scope("operations:read")
|| !crate::permissions::allowed(&mut tx, &principal.name, "operations:read").await?
{
crate::permissions::require_principal(&mut tx, &principal, "tenant:stop").await?;
}
let stopped: bool = sqlx::query_scalar("SELECT changes_stopped FROM tenants WHERE tenant_id=$1")
.bind(tenant)
.fetch_optional(&mut *tx)
.await?
.ok_or(Error(StatusCode::NOT_FOUND, "NOT_FOUND"))?;
tx.commit().await?;
Ok(Json(json!({"tenant_id":tenant,"changes_stopped":stopped})))
}
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(())
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Archive {
archived: bool,
}
async fn archive_device(
State(s): State<crate::State>,
h: HeaderMap,
Path((tenant, asset)): Path<(Uuid, Uuid)>,
Json(input): Json<Archive>,
) -> Result<Json<Value>, Error> {
let event = if input.archived {
"device_archived"
} else {
"device_restored"
};
let (p, mut tx) = context(&s, &h, tenant, "devices:revoke", event).await?;
let current: Option<chrono::DateTime<chrono::Utc>> = sqlx::query_scalar(
"SELECT archived_at FROM assets WHERE tenant_id=$1 AND asset_id=$2 FOR UPDATE",
)
.bind(tenant)
.bind(asset)
.fetch_optional(&mut *tx)
.await?
.ok_or(Error(StatusCode::NOT_FOUND, "NOT_FOUND"))?;
if current.is_some() != input.archived {
sqlx::query("UPDATE assets SET archived_at=CASE WHEN $3 THEN now() END WHERE tenant_id=$1 AND asset_id=$2")
.bind(tenant).bind(asset).bind(input.archived).execute(&mut *tx).await?;
audit(&mut tx, &p, event, json!({"asset_id":asset})).await?;
}
tx.commit().await?;
Ok(Json(json!({"asset_id":asset, "archived":input.archived})))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Pairing {
agent_id: Uuid,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct HypervisorAssignment {
// null clears the relation. A missing field is a malformed update.
#[serde(deserialize_with = "required_hypervisor_value")]
hypervisor_asset_id: Option<Uuid>,
}
fn required_hypervisor_value<'de, D: serde::Deserializer<'de>>(value: D) -> Result<Option<Uuid>, D::Error> {
Option::deserialize(value)
}
async fn assign_hypervisor(
State(s): State<crate::State>,
h: HeaderMap,
Path((tenant, asset)): Path<(Uuid, Uuid)>,
Query(pair): Query<Pairing>,
Json(input): Json<HypervisorAssignment>,
) -> Result<Json<Value>, Error> {
const EVENT: &str = "device_hypervisor_assigned";
let (p, mut tx) = context(&s, &h, tenant, "devices:revoke", EVENT).await?;
crate::permissions::require_principal(&mut tx, &p, "inventory:read").await?;
// Match the asset lock order for simultaneous edits of the same two devices.
let ids = [asset, input.hypervisor_asset_id.unwrap_or(asset)];
let rows: Vec<(Uuid, Option<Uuid>)> = sqlx::query_as(
"SELECT asset_id,hypervisor_asset_id FROM assets
WHERE tenant_id=$1 AND asset_id=ANY($2) ORDER BY asset_id FOR UPDATE",
)
.bind(tenant).bind(ids.as_slice()).fetch_all(&mut *tx).await?;
let previous = rows.into_iter().find(|(id, _)| *id == asset)
.ok_or(Error(StatusCode::NOT_FOUND, "NOT_FOUND"))?.1;
crate::devices::validate_vm_host_assignment(
&mut tx, tenant, asset, pair.agent_id, input.hypervisor_asset_id,
).await?;
if previous != input.hypervisor_asset_id {
sqlx::query("UPDATE assets SET hypervisor_asset_id=$3 WHERE tenant_id=$1 AND asset_id=$2")
.bind(tenant).bind(asset).bind(input.hypervisor_asset_id).execute(&mut *tx).await?;
audit(&mut tx, &p, EVENT, json!({"asset_id":asset,"agent_id":pair.agent_id,
"previous_hypervisor_asset_id":previous,"hypervisor_asset_id":input.hypervisor_asset_id})).await?;
}
tx.commit().await?;
Ok(Json(json!({"asset_id":asset,"hypervisor_asset_id":input.hypervisor_asset_id})))
}
async fn remove_device(
State(s): State<crate::State>,
h: HeaderMap,
Path((tenant, asset)): Path<(Uuid, Uuid)>,
Query(pairing): Query<Pairing>,
) -> Result<StatusCode, Error> {
let (p, mut tx) = context(&s, &h, tenant, "devices:revoke", "device_deleted").await?;
let status: String = sqlx::query_scalar("SELECT remove_revoked_device($1,$2,$3,$4)")
.bind(tenant).bind(asset).bind(pairing.agent_id).bind(&p.name)
.fetch_one(&mut *tx).await?;
match status.as_str() {
"deleted" => audit(&mut tx, &p, "device_deleted",
json!({"asset_id":asset, "agent_id":pairing.agent_id})).await?,
"absent" => (),
"active" => return Err(Error(StatusCode::CONFLICT, "DEVICE_REVOCATION_REQUIRED")),
"busy" => return Err(Error(StatusCode::CONFLICT, "DEVICE_HAS_OPEN_WORK")),
"forbidden" => return Err(Error(StatusCode::FORBIDDEN, "FORBIDDEN")),
_ => return Err(Error(StatusCode::INTERNAL_SERVER_ERROR, "DEVICE_DELETION_FAILED")),
}
tx.commit().await?;
Ok(StatusCode::NO_CONTENT)
}
pub async fn revoke_device(
State(s): State<crate::State>,
h: HeaderMap,
Path((t, asset)): Path<(Uuid, Uuid)>,
Query(selection): Query<crate::devices::DetailQuery>,
Json(i): Json<Reason>,
) -> Result<Json<Value>, 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 AND ($2::uuid IS NULL OR agent_id=$2)").bind(asset).bind(selection.agent_id).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 ($2::uuid IS NULL OR agent_id=$2) AND state NOT IN ('succeeded','failed','cancelled','expired','closed_unknown')").bind(asset).bind(selection.agent_id).execute(&mut *tx).await?;
audit(
&mut tx,
&p,
"device_revoked",
json!({"asset_id":asset,"agent_id":selection.agent_id,"reason":i.reason}),
)
.await?;
tx.commit().await?;
Ok(Json(json!({"asset_id":asset,"revoked":true})))
}
pub async fn revoke_plan(
State(s): State<crate::State>,
h: HeaderMap,
Path((t, plan)): Path<(Uuid, Uuid)>,
Json(i): Json<Reason>,
) -> Result<Json<Value>, Error> {
let (p, mut tx) = context(&s, &h, t, "plans:revoke", &i.reason).await?;
let op:Option<Uuid>=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','closed_unknown')").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<crate::State>,
h: HeaderMap,
Path(t): Path<Uuid>,
Json(i): Json<Stop>,
) -> Result<Json<Value>, 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})))
}