feat(auth): deny-by-default HTTP layer
A global middleware wraps the router and its fallback: only PUBLIC_ROUTES answer without a credential, and unknown paths look like protected ones. Adds cookie sessions with per-session CSRF, scoped Bearer tokens, the /api/auth and /api/admin handlers, Transport for client IP and Secure, and pending-token enrollment re-checked inside one store update. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
a90ff81650
commit
2b1bc63340
11 files changed
+2455
-79
No files matched your search
@@ -0,0 +1,891 @@
|
||||
//! 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, 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::time::{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;
|
||||
|
||||
/// 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<AcauaError> for ApiError {
|
||||
fn from(e: AcauaError) -> Self {
|
||||
ApiError::Core(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<AuthFailure> 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::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<T>(pub T);
|
||||
|
||||
impl<S: Send + Sync, T: DeserializeOwned> FromRequest<S> for JsonBody<T> {
|
||||
type Rejection = ApiError;
|
||||
|
||||
async fn from_request(req: Request, state: &S) -> Result<Self, ApiError> {
|
||||
Json::<T>::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<T, F>(f: F) -> Result<T, ApiError>
|
||||
where
|
||||
T: Send + 'static,
|
||||
F: FnOnce() -> Result<T, AcauaError> + 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<T, F>(state: &AppState, f: F) -> Result<T, ApiError>
|
||||
where
|
||||
T: Send + 'static,
|
||||
F: FnOnce() -> Result<T, AcauaError> + Send + 'static,
|
||||
{
|
||||
let _permit = state.argon2.acquire().await.map_err(|_| internal())?;
|
||||
blocking(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<S: Send + Sync> FromRequestParts<S> for Auth {
|
||||
type Rejection = ApiError;
|
||||
|
||||
async fn from_request_parts(parts: &mut Parts, _: &S) -> Result<Self, ApiError> {
|
||||
parts
|
||||
.extensions
|
||||
.get::<Auth>()
|
||||
.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<String> {
|
||||
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<Option<Credential>, 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<AppState>, mut req: Request, next: Next) -> Response {
|
||||
let method = req.method().clone();
|
||||
let path = req.uri().path().to_string();
|
||||
let peer = req
|
||||
.extensions()
|
||||
.get::<ConnectInfo<SocketAddr>>()
|
||||
.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<ApiError> 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)?,
|
||||
}
|
||||
|
||||
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<T>(result: Result<T, ApiError>) -> Result<T, Refusal> {
|
||||
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<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
role: Option<Role>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
csrf: Option<String>,
|
||||
}
|
||||
|
||||
pub async fn auth_state(
|
||||
State(state): State<AppState>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Json<StateReply>, 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,
|
||||
username: Some(p.username),
|
||||
role: Some(p.role),
|
||||
csrf: Some(csrf),
|
||||
},
|
||||
None => StateReply {
|
||||
setup_required,
|
||||
authenticated: false,
|
||||
username: None,
|
||||
role: None,
|
||||
csrf: None,
|
||||
},
|
||||
}))
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct BootstrapBody {
|
||||
code: String,
|
||||
username: String,
|
||||
password: String,
|
||||
}
|
||||
|
||||
pub async fn bootstrap(
|
||||
State(state): State<AppState>,
|
||||
JsonBody(b): JsonBody<BootstrapBody>,
|
||||
) -> Result<Response, ApiError> {
|
||||
let auth = state.auth.clone();
|
||||
let now = unix_now();
|
||||
let pending = hashing(&state, move || {
|
||||
auth.complete_bootstrap(&b.code, &b.username, &b.password, 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<AppState>,
|
||||
Extension(ClientIp(ip)): Extension<ClientIp>,
|
||||
JsonBody(b): JsonBody<LoginBody>,
|
||||
) -> Result<Response, ApiError> {
|
||||
let auth = state.auth.clone();
|
||||
let now = unix_now();
|
||||
let step = hashing(&state, move || {
|
||||
auth.login(&b.username, &b.password, ip, now)
|
||||
})
|
||||
.await?;
|
||||
Ok(step_reply(&state, &step))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct MfaBody {
|
||||
pending: String,
|
||||
code: String,
|
||||
}
|
||||
|
||||
pub async fn mfa(
|
||||
State(state): State<AppState>,
|
||||
JsonBody(b): JsonBody<MfaBody>,
|
||||
) -> Result<Response, ApiError> {
|
||||
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<AppState>,
|
||||
JsonBody(b): JsonBody<RequiredPasswordBody>,
|
||||
) -> Result<Response, ApiError> {
|
||||
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<String, ApiError> {
|
||||
parts
|
||||
.get::<SessionToken>()
|
||||
.map(|t| t.0.clone())
|
||||
.ok_or_else(unauthenticated)
|
||||
}
|
||||
|
||||
pub async fn logout(State(state): State<AppState>, req: Request) -> Result<Response, ApiError> {
|
||||
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<String>,
|
||||
}
|
||||
|
||||
pub async fn reauth(
|
||||
State(state): State<AppState>,
|
||||
Auth(p): Auth,
|
||||
Extension(SessionToken(token)): Extension<SessionToken>,
|
||||
JsonBody(b): JsonBody<ReauthBody>,
|
||||
) -> Result<Response, ApiError> {
|
||||
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<AppState>,
|
||||
Auth(p): Auth,
|
||||
Extension(SessionToken(token)): Extension<SessionToken>,
|
||||
JsonBody(b): JsonBody<PasswordBody>,
|
||||
) -> Result<Response, ApiError> {
|
||||
let auth = state.auth.clone();
|
||||
let now = unix_now();
|
||||
hashing(&state, move || {
|
||||
auth.change_password(&p.user_id, &b.current, &b.new, Some(&token), 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<S: Send + Sync> FromRequestParts<S> for EnrollActor {
|
||||
type Rejection = ApiError;
|
||||
|
||||
async fn from_request_parts(parts: &mut Parts, _: &S) -> Result<Self, ApiError> {
|
||||
if let Some(PendingToken(token)) = parts.extensions.get::<PendingToken>() {
|
||||
return Ok(EnrollActor::Pending(token.clone()));
|
||||
}
|
||||
let Auth(p) = parts
|
||||
.extensions
|
||||
.get::<Auth>()
|
||||
.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<TotpEnrollment> 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<AppState>,
|
||||
actor: EnrollActor,
|
||||
) -> Result<Response, ApiError> {
|
||||
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<AppState>,
|
||||
actor: EnrollActor,
|
||||
JsonBody(b): JsonBody<CodeBody>,
|
||||
) -> Result<Response, ApiError> {
|
||||
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, 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<AppState>,
|
||||
Auth(p): Auth,
|
||||
Extension(SessionToken(token)): Extension<SessionToken>,
|
||||
) -> Result<Response, ApiError> {
|
||||
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), now)).await?;
|
||||
Ok(ok_reply())
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct OwnerQuery {
|
||||
user_id: Option<String>,
|
||||
}
|
||||
|
||||
/// The core's listings take no actor: the check lives here.
|
||||
fn listing_target(p: &Principal, asked: Option<String>) -> Result<String, ApiError> {
|
||||
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<AppState>,
|
||||
Auth(p): Auth,
|
||||
Query(q): Query<OwnerQuery>,
|
||||
) -> Result<Response, ApiError> {
|
||||
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<AppState>,
|
||||
Auth(p): Auth,
|
||||
JsonBody(b): JsonBody<IdBody>,
|
||||
) -> Result<Response, ApiError> {
|
||||
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<AppState>,
|
||||
Auth(p): Auth,
|
||||
Query(q): Query<OwnerQuery>,
|
||||
) -> Result<Response, ApiError> {
|
||||
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<AppState>,
|
||||
Auth(p): Auth,
|
||||
JsonBody(b): JsonBody<TokenBody>,
|
||||
) -> Result<Response, ApiError> {
|
||||
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<AppState>,
|
||||
Auth(p): Auth,
|
||||
JsonBody(b): JsonBody<IdBody>,
|
||||
) -> Result<Response, ApiError> {
|
||||
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 `require_admin`) ----------------
|
||||
|
||||
pub async fn users_list(State(state): State<AppState>) -> Result<Response, ApiError> {
|
||||
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<AppState>,
|
||||
Auth(p): Auth,
|
||||
JsonBody(b): JsonBody<NewUserBody>,
|
||||
) -> Result<Response, ApiError> {
|
||||
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<AppState>,
|
||||
Auth(p): Auth,
|
||||
JsonBody(b): JsonBody<RoleBody>,
|
||||
) -> Result<Response, ApiError> {
|
||||
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<AppState>,
|
||||
Auth(p): Auth,
|
||||
JsonBody(b): JsonBody<IdBody>,
|
||||
) -> Result<Response, ApiError> {
|
||||
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<usize>,
|
||||
}
|
||||
|
||||
pub async fn audit(
|
||||
State(state): State<AppState>,
|
||||
Query(q): Query<AuditQuery>,
|
||||
) -> Result<Response, ApiError> {
|
||||
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())
|
||||
}
|
||||
Reference in new issue
Block a user