//! The HTTP face of authentication: the global gate and the `/api/auth` and //! `/api/admin` handlers. Decisions about accounts stay in `acaua_core::auth`. //! //! The session token travels only in the cookie, and that cookie is only ever //! built from a `NewSession` the core issued. Request structs here hold //! passwords and codes, so none of them derives `Debug`. use crate::web::{access_of, is_public, is_public_asset, Access, AppState}; use acaua_core::auth::{ csrf_matches, csrf_token, AuthService, LoginAttempt, LoginStep, NewSession, PendingMfa, Principal, Role, Scope, TotpEnrollment, Via, }; use acaua_core::{AcauaError, AuthFailure}; use axum::extract::rejection::JsonRejection; use axum::extract::{ConnectInfo, FromRequest, FromRequestParts, Query, Request, State}; use axum::http::request::Parts; use axum::http::{header, HeaderMap, HeaderValue, Method, StatusCode}; use axum::middleware::Next; use axum::response::{IntoResponse, Response}; use axum::{Extension, Json}; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::sync::Arc; use std::time::{Duration, SystemTime, UNIX_EPOCH}; pub const MAX_BODY_BYTES: usize = 64 * 1024; pub const ARGON2_CONCURRENCY: usize = 8; const SESSION_COOKIE: &str = "acaua_session"; const CSRF_HEADER: &str = "x-acaua-csrf"; const PENDING_HEADER: &str = "x-acaua-pending"; const LOGIN_PAGE: &str = "/login.html"; const AUDIT_DEFAULT: usize = 200; const AUDIT_MAX: usize = 1000; /// The longest a login waits for a hashing permit. const LOGIN_QUEUE_WAIT: Duration = Duration::from_secs(30); /// A clock before 1970 fails closed: everything looks expired. pub fn unix_now() -> u64 { SystemTime::now() .duration_since(UNIX_EPOCH) .map(|d| d.as_secs()) .unwrap_or(u64::MAX) } // ---- Errors --------------------------------------------------------------- pub enum ApiError { Core(AcauaError), Fixed(StatusCode, &'static str), } impl From for ApiError { fn from(e: AcauaError) -> Self { ApiError::Core(e) } } impl From for ApiError { fn from(f: AuthFailure) -> Self { ApiError::Core(f.into()) } } fn internal() -> ApiError { ApiError::Fixed(StatusCode::INTERNAL_SERVER_ERROR, "internal error") } fn error_response(status: StatusCode, message: &str) -> Response { (status, Json(serde_json::json!({ "error": message }))).into_response() } fn failure_response(f: &AuthFailure) -> Response { use AuthFailure as F; let (status, message) = match f { F::InvalidCredentials => (StatusCode::UNAUTHORIZED, "invalid credentials"), F::Throttled { retry_after_secs } => { let mut r = error_response(StatusCode::TOO_MANY_REQUESTS, "too many attempts"); r.headers_mut() .insert(header::RETRY_AFTER, HeaderValue::from(*retry_after_secs)); return r; } F::SetupRequired => (StatusCode::CONFLICT, "setup required"), F::BootstrapInvalid => (StatusCode::UNAUTHORIZED, "invalid setup code"), F::LastAdmin => (StatusCode::CONFLICT, "the last administrator must remain"), F::MfaMandatory => (StatusCode::CONFLICT, "MFA is mandatory for administrators"), F::MfaNotEnabled => (StatusCode::CONFLICT, "MFA is not enabled"), F::EnrollmentNotStarted => (StatusCode::CONFLICT, "no enrollment in progress"), F::UsernameTaken => (StatusCode::CONFLICT, "username is already in use"), F::UserNotFound | F::NotFound => (StatusCode::NOT_FOUND, "not found"), F::ReauthRequired => (StatusCode::FORBIDDEN, "recent authentication required"), F::Forbidden => (StatusCode::FORBIDDEN, "forbidden"), other => { tracing::error!(error = %other, "authentication backend failure"); (StatusCode::INTERNAL_SERVER_ERROR, "internal error") } }; error_response(status, message) } impl IntoResponse for ApiError { fn into_response(self) -> Response { match self { ApiError::Fixed(status, message) => error_response(status, message), ApiError::Core(AcauaError::Auth(f)) => failure_response(&f), // Written by the core's validators; never echoes the input. ApiError::Core(AcauaError::InvalidInput(message)) => { error_response(StatusCode::BAD_REQUEST, &message) } ApiError::Core(other) => { tracing::error!(error = %other, "request failed"); error_response(StatusCode::INTERNAL_SERVER_ERROR, "internal error") } } } } /// `Json`, with fixed refusals: a parser message could quote the input. pub struct JsonBody(pub T); impl FromRequest for JsonBody { type Rejection = ApiError; async fn from_request(req: Request, state: &S) -> Result { Json::::from_request(req, state) .await .map(|Json(v)| JsonBody(v)) .map_err(|e: JsonRejection| { let status = e.status(); let message = match status { StatusCode::PAYLOAD_TOO_LARGE => "request body too large", StatusCode::UNSUPPORTED_MEDIA_TYPE => "expected application/json", _ => "invalid request", }; ApiError::Fixed(status, message) }) } } // ---- Blocking work -------------------------------------------------------- /// Store and audit calls take a file lock and fsync. pub async fn blocking(f: F) -> Result where T: Send + 'static, F: FnOnce() -> Result + Send + 'static, { match tokio::task::spawn_blocking(f).await { Ok(result) => result.map_err(ApiError::Core), Err(_) => Err(internal()), } } /// As `blocking`, for calls that run Argon2: its memory cost multiplies with /// concurrency, so only a few run at a time. async fn hashing(state: &AppState, f: F) -> Result where T: Send + 'static, F: FnOnce() -> Result + Send + 'static, { // The permit moves into the closure: a dropped request cancels this future // but not the blocking task, whose Argon2 run must keep its slot to the end. let permit = state .argon2 .clone() .acquire_owned() .await .map_err(|_| internal())?; blocking(move || { let _permit = permit; f() }) .await } // ---- Credentials ---------------------------------------------------------- /// The client address `Transport` allows us to believe. #[derive(Clone, Copy)] pub struct ClientIp(IpAddr); /// A session token proved valid by the gate. No `Debug`: it is a credential. #[derive(Clone)] pub struct SessionToken(String); #[derive(Clone)] pub struct PendingToken(String); /// The `Principal` the gate authenticated. The only way a handler gets one. #[derive(Clone)] pub struct Auth(pub Principal); impl FromRequestParts for Auth { type Rejection = ApiError; async fn from_request_parts(parts: &mut Parts, _: &S) -> Result { parts .extensions .get::() .cloned() .ok_or_else(unauthenticated) } } fn unauthenticated() -> ApiError { ApiError::Fixed(StatusCode::UNAUTHORIZED, "authentication required") } fn forbidden() -> ApiError { AuthFailure::Forbidden.into() } fn session_cookie_value(headers: &HeaderMap) -> Option { headers .get_all(header::COOKIE) .iter() .filter_map(|v| v.to_str().ok()) .flat_map(|v| v.split(';')) .find_map(|pair| { let (name, value) = pair.trim().split_once('=')?; (name == SESSION_COOKIE && !value.is_empty()).then(|| value.to_string()) }) } enum Credential { Bearer(String), Cookie(String), } /// An `Authorization` header decides alone: a bad one never falls back to the /// cookie. Only API tokens are valid there, so a session cannot skip CSRF. fn credential(headers: &HeaderMap) -> Result, ApiError> { if let Some(value) = headers.get(header::AUTHORIZATION) { let text = value.to_str().map_err(|_| unauthenticated())?; return match text.split_once(' ') { Some((scheme, token)) if scheme.eq_ignore_ascii_case("bearer") => { Ok(Some(Credential::Bearer(token.trim().to_string()))) } _ => Err(unauthenticated()), }; } Ok(session_cookie_value(headers).map(Credential::Cookie)) } fn is_safe(method: &Method) -> bool { matches!(*method, Method::GET | Method::HEAD) } pub fn require_admin(p: &Principal) -> Result<(), ApiError> { if p.role == Role::Admin && p.scope == Scope::Admin { Ok(()) } else { Err(forbidden()) } } /// A refused request. Browsers navigating to a page go to the login; the rest /// get the same 401, so unknown paths cannot be told from protected ones. fn deny(method: &Method, path: &str, headers: &HeaderMap) -> Response { let wants_html = headers .get(header::ACCEPT) .and_then(|v| v.to_str().ok()) .is_some_and(|v| v.contains("text/html")); if is_safe(method) && wants_html && !path.starts_with("/api/") { let mut r = StatusCode::SEE_OTHER.into_response(); r.headers_mut() .insert(header::LOCATION, HeaderValue::from_static(LOGIN_PAGE)); return r; } unauthenticated().into_response() } /// Wraps the whole router, fallback included, so anything not listed in /// `PUBLIC_ROUTES` needs a credential from the moment it exists. pub async fn require_auth(State(state): State, mut req: Request, next: Next) -> Response { let method = req.method().clone(); let path = req.uri().path().to_string(); let peer = req .extensions() .get::>() .map(|c| c.0.ip()) .unwrap_or(IpAddr::V4(Ipv4Addr::UNSPECIFIED)); let ip = state.transport.client_ip(peer, req.headers()); req.extensions_mut().insert(ClientIp(ip)); let mut response = if is_public(&method, &path) { next.run(req).await } else { match gate(&state, &method, &path, &mut req).await { Ok(()) => next.run(req).await, Err(Refusal::Unauthenticated) => deny(&method, &path, req.headers()), Err(Refusal::Other(e)) => e.into_response(), } }; if !is_public_asset(&method, &path) { response .headers_mut() .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store")); } response } enum Refusal { Unauthenticated, Other(ApiError), } impl From for Refusal { fn from(e: ApiError) -> Self { Refusal::Other(e) } } async fn gate( state: &AppState, method: &Method, path: &str, req: &mut Request, ) -> Result<(), Refusal> { let access = access_of(method, path); if access == Access::SessionOrPending { if let Some(value) = req.headers().get(PENDING_HEADER) { let token = value .to_str() .map_err(|_| Refusal::Unauthenticated)? .to_string(); let auth = state.auth.clone(); let checked = token.clone(); let now = unix_now(); authenticated(blocking(move || auth.pending_user(&checked, now)).await)?; // A custom header is never sent by a cross-site form: no CSRF here. req.extensions_mut().insert(PendingToken(token)); return Ok(()); } } let cred = credential(req.headers()) .map_err(|_| Refusal::Unauthenticated)? .ok_or(Refusal::Unauthenticated)?; let now = unix_now(); let auth = state.auth.clone(); let principal = match &cred { Credential::Bearer(token) => { let token = token.clone(); authenticated(blocking(move || auth.authenticate_token(&token, now)).await)? } Credential::Cookie(token) => { let token = token.clone(); authenticated(blocking(move || auth.authenticate_session(&token, now)).await)? } }; if let Credential::Cookie(token) = &cred { if !is_safe(method) { let sent = req .headers() .get(CSRF_HEADER) .and_then(|v| v.to_str().ok()) .unwrap_or(""); if !csrf_matches(token, sent) { return Err(ApiError::Fixed(StatusCode::FORBIDDEN, "invalid CSRF token").into()); } } } if principal.via == Via::Token && !is_safe(method) && principal.scope != Scope::Admin { return Err(forbidden().into()); } match access { Access::Authenticated => {} Access::Session | Access::SessionOrPending => { if principal.via != Via::Session { return Err(forbidden().into()); } } Access::Admin => require_admin(&principal)?, Access::AdminRecentSession => { require_admin(&principal)?; if principal.via != Via::Session { return Err(forbidden().into()); } if !principal.recent_auth { return Err(ApiError::from(AuthFailure::ReauthRequired).into()); } } } if let Credential::Cookie(token) = cred { req.extensions_mut().insert(SessionToken(token)); } req.extensions_mut().insert(Auth(principal)); Ok(()) } /// A rejected credential is a plain 401. A backend failure stays a 500: it /// still refuses, but must not look like a logout. fn authenticated(result: Result) -> Result { result.map_err(|e| match e { ApiError::Core(AcauaError::Auth(AuthFailure::InvalidCredentials)) => { Refusal::Unauthenticated } other => Refusal::Other(other), }) } // ---- Cookies and login replies -------------------------------------------- fn with_cookie(mut response: Response, cookie: String) -> Response { match HeaderValue::from_str(&cookie) { Ok(value) => { response.headers_mut().append(header::SET_COOKIE, value); response } Err(_) => internal().into_response(), } } fn cookie_attrs(state: &AppState) -> &'static str { if state.transport.cookie_secure() { "; Path=/; HttpOnly; SameSite=Strict; Secure" } else { "; Path=/; HttpOnly; SameSite=Strict" } } fn clear_cookie(state: &AppState, response: Response) -> Response { let attrs = cookie_attrs(state); with_cookie(response, format!("{SESSION_COOKIE}=; Max-Age=0{attrs}")) } /// The session reply. The token leaves the server only as this cookie. fn session_reply(state: &AppState, session: &NewSession) -> Response { let attrs = cookie_attrs(state); let max_age = session.expires_at.saturating_sub(unix_now()); let reply = Json(serde_json::json!({ "step": "session", "expires_at": session.expires_at, })); with_cookie( reply.into_response(), format!( "{SESSION_COOKIE}={}; Max-Age={max_age}{attrs}", session.token ), ) } fn pending_reply(step: &str, pending: &PendingMfa) -> Response { Json(serde_json::json!({ "step": step, "pending": pending.token, "expires_at": pending.expires_at, })) .into_response() } fn step_reply(state: &AppState, step: &acaua_core::auth::LoginStep) -> Response { use acaua_core::auth::LoginStep as L; match step { L::Session(s) => session_reply(state, s), L::MfaRequired(p) => pending_reply("mfa_required", p), L::MfaEnrollRequired(p) => pending_reply("mfa_enroll_required", p), L::PasswordChangeRequired(p) => pending_reply("password_change_required", p), } } // ---- Public handlers ------------------------------------------------------ #[derive(Serialize)] pub struct StateReply { setup_required: bool, authenticated: bool, #[serde(skip_serializing_if = "Option::is_none")] username: Option, #[serde(skip_serializing_if = "Option::is_none")] role: Option, #[serde(skip_serializing_if = "Option::is_none")] mfa_enabled: Option, #[serde(skip_serializing_if = "Option::is_none")] csrf: Option, } pub async fn auth_state( State(state): State, headers: HeaderMap, ) -> Result, ApiError> { let token = session_cookie_value(&headers); let auth = state.auth.clone(); let now = unix_now(); blocking(move || { let setup_required = !auth.has_admin()?; let session = token.and_then(|t| { let p = auth.authenticate_session(&t, now).ok()?; Some((p, csrf_token(&t))) }); Ok(Json(match session { Some((p, csrf)) => StateReply { setup_required, authenticated: true, mfa_enabled: Some(auth.mfa_enabled(&p.user_id)?), username: Some(p.username), role: Some(p.role), csrf: Some(csrf), }, None => StateReply { setup_required, authenticated: false, username: None, role: None, mfa_enabled: None, csrf: None, }, })) }) .await } #[derive(Deserialize)] pub struct BootstrapBody { code: String, username: String, password: String, } pub async fn bootstrap( State(state): State, Extension(ClientIp(ip)): Extension, JsonBody(b): JsonBody, ) -> Result { let auth = state.auth.clone(); let now = unix_now(); let pending = hashing(&state, move || { auth.complete_bootstrap(&b.code, &b.username, &b.password, ip, now) }) .await?; Ok(pending_reply("mfa_enroll_required", &pending)) } #[derive(Deserialize)] pub struct LoginBody { username: String, password: String, } pub async fn login( State(state): State, Extension(ClientIp(ip)): Extension, JsonBody(b): JsonBody, ) -> Result { let now = unix_now(); // Whatever can be refused without Argon2 is, before the queue for a permit, // or a flood of hopeless attempts would stand in front of the owner. let auth = state.auth.clone(); let username = b.username; let queued = blocking(move || { let attempt = auth.login_begin(&username, ip, now)?; Ok(QueuedLogin { auth, attempt: Some(attempt), }) }) .await?; let step = finish_queued(&state, queued, b.password, LOGIN_QUEUE_WAIT).await?; Ok(step_reply(&state, &step)) } /// Evaluates a queued login once a permit is free. Past `wait` it is refused /// like any other throttled attempt, and gives back what it reserved. pub(crate) async fn finish_queued( state: &AppState, mut queued: QueuedLogin, password: String, wait: Duration, ) -> Result { // Only the queue is timed: once the hash runs, it runs to its answer. Leaving // here drops `queued`, which gives back what the attempt reserved. let permit = match tokio::time::timeout(wait, state.argon2.clone().acquire_owned()).await { Ok(permit) => permit.map_err(|_| internal())?, Err(_) => { return Err(AuthFailure::Throttled { retry_after_secs: wait.as_secs().max(1), } .into()) } }; blocking(move || { let _permit = permit; let attempt = queued .attempt .take() .ok_or(AuthFailure::InvalidCredentials)?; // The clock now, not at arrival: the queue took time. queued.auth.login_finish(attempt, &password, unix_now()) }) .await } /// A login between its checks and its evaluation. A client that disconnects /// while queued made no guess, so what it reserved goes back. pub(crate) struct QueuedLogin { pub(crate) auth: Arc, pub(crate) attempt: Option, } impl Drop for QueuedLogin { fn drop(&mut self) { if let Some(attempt) = self.attempt.take() { self.auth.login_abandon(attempt); } } } #[derive(Deserialize)] pub struct MfaBody { pending: String, code: String, } pub async fn mfa( State(state): State, JsonBody(b): JsonBody, ) -> Result { let auth = state.auth.clone(); let now = unix_now(); let step = blocking(move || auth.confirm_mfa(&b.pending, &b.code, now)).await?; Ok(step_reply(&state, &step)) } #[derive(Deserialize)] pub struct RequiredPasswordBody { ticket: String, current: String, new: String, } pub async fn password_change_required( State(state): State, JsonBody(b): JsonBody, ) -> Result { let auth = state.auth.clone(); let now = unix_now(); let session = hashing(&state, move || { auth.change_required_password(&b.ticket, &b.current, &b.new, now) }) .await?; Ok(session_reply(&state, &session)) } // ---- Session handlers ----------------------------------------------------- fn ok_reply() -> Response { Json(serde_json::json!({ "ok": true })).into_response() } /// The session behind a `Via::Session` principal. fn session_token(parts: &axum::http::Extensions) -> Result { parts .get::() .map(|t| t.0.clone()) .ok_or_else(unauthenticated) } pub async fn logout(State(state): State, req: Request) -> Result { let token = session_token(req.extensions())?; let auth = state.auth.clone(); let now = unix_now(); blocking(move || auth.logout(&token, now)).await?; Ok(clear_cookie(&state, ok_reply())) } #[derive(Deserialize)] pub struct ReauthBody { password: String, code: Option, } pub async fn reauth( State(state): State, Auth(p): Auth, Extension(SessionToken(token)): Extension, JsonBody(b): JsonBody, ) -> Result { let auth = state.auth.clone(); let now = unix_now(); hashing(&state, move || { auth.reauthenticate(&p.user_id, &token, &b.password, b.code.as_deref(), now) }) .await?; Ok(ok_reply()) } #[derive(Deserialize)] pub struct PasswordBody { current: String, new: String, } pub async fn change_password( State(state): State, Auth(p): Auth, Extension(SessionToken(token)): Extension, Extension(ClientIp(ip)): Extension, JsonBody(b): JsonBody, ) -> Result { let auth = state.auth.clone(); let now = unix_now(); hashing(&state, move || { auth.change_password(&p.user_id, &b.current, &b.new, Some(&token), Some(ip), now) }) .await?; Ok(ok_reply()) } /// Who is enrolling: the first-login pending token, or a session that /// reauthenticated recently. pub enum EnrollActor { Pending(String), Session(Principal), } impl FromRequestParts for EnrollActor { type Rejection = ApiError; async fn from_request_parts(parts: &mut Parts, _: &S) -> Result { if let Some(PendingToken(token)) = parts.extensions.get::() { return Ok(EnrollActor::Pending(token.clone())); } let Auth(p) = parts .extensions .get::() .cloned() .ok_or_else(unauthenticated)?; if !p.recent_auth { return Err(AuthFailure::ReauthRequired.into()); } Ok(EnrollActor::Session(p)) } } #[derive(Serialize)] pub struct EnrollReply { uri: String, qr_png_base64: String, manual_key: String, } impl From for EnrollReply { fn from(e: TotpEnrollment) -> Self { Self { uri: e.uri, qr_png_base64: e.qr_png_base64, manual_key: e.manual_key, } } } pub async fn enroll_start( State(state): State, actor: EnrollActor, ) -> Result { let auth = state.auth.clone(); let now = unix_now(); let enrollment = blocking(move || match actor { EnrollActor::Pending(token) => auth.start_enrollment_pending(&token, now), EnrollActor::Session(p) => auth.start_enrollment(&p.user_id, now), }) .await?; Ok(Json(EnrollReply::from(enrollment)).into_response()) } #[derive(Deserialize)] pub struct CodeBody { code: String, } pub async fn enroll_confirm( State(state): State, Extension(ClientIp(ip)): Extension, actor: EnrollActor, JsonBody(b): JsonBody, ) -> Result { let auth = state.auth.clone(); let now = unix_now(); let from_session = matches!(actor, EnrollActor::Session(_)); let codes = blocking(move || match actor { EnrollActor::Pending(token) => auth.confirm_enrollment_pending(&token, &b.code, now), EnrollActor::Session(p) => auth.confirm_enrollment(&p.user_id, &b.code, Some(ip), now), }) .await?; let reply = Json(serde_json::json!({ "recovery_codes": codes })).into_response(); // Activation ends every session of the user, this one too. Ok(if from_session { clear_cookie(&state, reply) } else { reply }) } pub async fn mfa_disable( State(state): State, Auth(p): Auth, Extension(SessionToken(token)): Extension, Extension(ClientIp(ip)): Extension, ) -> Result { if !p.recent_auth { return Err(AuthFailure::ReauthRequired.into()); } let auth = state.auth.clone(); let now = unix_now(); blocking(move || auth.disable_mfa(&p.username, &p.user_id, Some(&token), Some(ip), now)) .await?; Ok(ok_reply()) } #[derive(Deserialize)] pub struct OwnerQuery { user_id: Option, } /// The core's listings take no actor: the check lives here. fn listing_target(p: &Principal, asked: Option) -> Result { match asked { Some(id) if id != p.user_id => { require_admin(p)?; Ok(id) } _ => Ok(p.user_id.clone()), } } pub async fn sessions_list( State(state): State, Auth(p): Auth, Query(q): Query, ) -> Result { let target = listing_target(&p, q.user_id)?; let auth = state.auth.clone(); let now = unix_now(); let list = blocking(move || auth.list_sessions(&target, now)).await?; Ok(Json(list).into_response()) } #[derive(Deserialize)] pub struct IdBody { id: String, } pub async fn sessions_revoke( State(state): State, Auth(p): Auth, JsonBody(b): JsonBody, ) -> Result { let auth = state.auth.clone(); let now = unix_now(); blocking(move || auth.revoke_session(&p, &b.id, now)).await?; Ok(ok_reply()) } pub async fn tokens_list( State(state): State, Auth(p): Auth, Query(q): Query, ) -> Result { let target = listing_target(&p, q.user_id)?; let auth = state.auth.clone(); let now = unix_now(); let list = blocking(move || auth.list_tokens(&target, now)).await?; Ok(Json(list).into_response()) } #[derive(Deserialize)] pub struct TokenBody { name: String, scope: Scope, expires_at: u64, } pub async fn tokens_create( State(state): State, Auth(p): Auth, JsonBody(b): JsonBody, ) -> Result { let auth = state.auth.clone(); let now = unix_now(); let made = blocking(move || auth.create_api_token(&p, &b.name, b.scope, b.expires_at, now)).await?; Ok(Json(serde_json::json!({ "id": made.id, "name": made.name, "token": made.token, "scope": made.scope, "expires_at": made.expires_at, })) .into_response()) } pub async fn tokens_revoke( State(state): State, Auth(p): Auth, JsonBody(b): JsonBody, ) -> Result { let auth = state.auth.clone(); let now = unix_now(); blocking(move || auth.revoke_token(&p, &b.id, now)).await?; Ok(ok_reply()) } // ---- Admin handlers (the gate already ran its admin check) ---------------- pub async fn users_list(State(state): State) -> Result { let auth = state.auth.clone(); let list = blocking(move || auth.list_users()).await?; Ok(Json(list).into_response()) } #[derive(Deserialize)] pub struct NewUserBody { username: String, password: String, role: Role, } pub async fn users_create( State(state): State, Auth(p): Auth, JsonBody(b): JsonBody, ) -> Result { let auth = state.auth.clone(); let now = unix_now(); let id = hashing(&state, move || { auth.create_user(&p.username, &b.username, &b.password, b.role, now) }) .await?; Ok(Json(serde_json::json!({ "id": id })).into_response()) } #[derive(Deserialize)] pub struct RoleBody { id: String, role: Role, } pub async fn users_set_role( State(state): State, Auth(p): Auth, JsonBody(b): JsonBody, ) -> Result { let auth = state.auth.clone(); let now = unix_now(); blocking(move || auth.set_role(&p.username, &b.id, b.role, now)).await?; Ok(ok_reply()) } pub async fn users_delete( State(state): State, Auth(p): Auth, JsonBody(b): JsonBody, ) -> Result { let auth = state.auth.clone(); let now = unix_now(); blocking(move || auth.delete_user(&p.username, &b.id, now)).await?; Ok(ok_reply()) } #[derive(Deserialize)] pub struct AuditQuery { limit: Option, } pub async fn audit( State(state): State, Query(q): Query, ) -> Result { let limit = q.limit.unwrap_or(AUDIT_DEFAULT).clamp(1, AUDIT_MAX); let auth = state.auth.clone(); let list = blocking(move || auth.audit_tail(limit)).await?; Ok(Json(list).into_response()) }