Organize device inventory by customer and restrict token access to its audience

This commit is contained in:
2026-11-17 21:55:24 +01:00
parent aeb9adc649
commit 0afaca1d64
39 changed files with 1950 additions and 225 deletions
+96
View File
@@ -0,0 +1,96 @@
//! Customer directory administration. Customer IDs are the existing tenant IDs.
use crate::{auth::Principal, jobs::Error};
use axum::{
Json,
extract::{Path, State},
http::{HeaderMap, StatusCode},
};
use serde::Deserialize;
use serde_json::{Value, json};
use sqlx::{Postgres, Transaction};
use uuid::Uuid;
pub fn database_error(e: sqlx::Error) -> Error {
match e.as_database_error().and_then(|e| e.code()).as_deref() {
Some("23505") => Error(StatusCode::CONFLICT, "CUSTOMER_ALREADY_EXISTS"),
Some("42501") => Error(StatusCode::FORBIDDEN, "FORBIDDEN"),
Some("22023") => Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"),
_ => e.into(),
}
}
pub async fn can_manage(
p: &Principal,
tx: &mut Transaction<'_, Postgres>,
) -> Result<bool, sqlx::Error> {
if p.testsimulation
|| p.session_hash.is_none()
|| p.csrf.is_none()
|| !p.name.starts_with("local:")
{
return Ok(false);
}
sqlx::query_scalar("SELECT is_customer_admin($1)")
.bind(&p.name)
.fetch_one(&mut **tx)
.await
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Input {
name: String,
}
pub async fn create(
State(state): State<crate::State>,
headers: HeaderMap,
Json(input): Json<Input>,
) -> Result<Json<Value>, Error> {
manage(&state, &headers, input, None).await
}
pub async fn rename(
State(state): State<crate::State>,
Path(id): Path<Uuid>,
headers: HeaderMap,
Json(input): Json<Input>,
) -> Result<Json<Value>, Error> {
manage(&state, &headers, input, Some(id)).await
}
async fn manage(
state: &crate::State,
headers: &HeaderMap,
input: Input,
existing: Option<Uuid>,
) -> Result<Json<Value>, Error> {
let p = state
.auth
.principal(state, headers, true)
.await
.map_err(|s| Error(s, crate::auth::error_code(s)))?;
if input.name.is_empty()
|| input.name.trim() != input.name
|| input.name.chars().count() > 120
|| input.name.chars().any(char::is_control)
{
return Err(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"));
}
if existing.is_some_and(|id| id != p.tenant) {
return Err(Error(StatusCode::NOT_FOUND, "NOT_FOUND"));
}
let mut tx = rmm_persistence::tenant_tx(&state.pool, p.tenant).await?;
if !can_manage(&p, &mut tx).await? {
return Err(Error(StatusCode::FORBIDDEN, "CUSTOMER_ADMIN_REQUIRED"));
}
let id = existing.unwrap_or_else(Uuid::new_v4);
sqlx::query("SELECT manage_customer($1,$2,$3,$4)")
.bind(&p.name)
.bind(id)
.bind(&input.name)
.bind(existing.is_none())
.execute(&mut *tx)
.await
.map_err(database_error)?;
tx.commit().await?;
Ok(Json(json!({"tenant_id":id,"name":input.name})))
}