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:
Lucas RayanandClaude Opus 5.5 committed 2026-11-04 19:51:42 -03:00
1 parent a90ff81650
commit 2b1bc63340
11 files changed
+2455 -79

No files matched your search

+272 -70
View File
@@ -1,22 +1,27 @@
use crate::auth_http::{self, blocking, require_auth, ApiError, JsonBody};
use crate::transport::Transport;
use acaua_core::auth::AuthService;
use acaua_core::fusion::Alert;
use acaua_core::storage::{DatasetSummary, Storage};
use acaua_core::update::UpdateStatus;
use acaua_core::zeek::{self, AnalysisReport};
use acaua_core::{update, Result};
use axum::body::Body;
use axum::extract::{Query, State};
use axum::http::{header, StatusCode, Uri};
use axum::extract::{DefaultBodyLimit, Query, State};
use axum::http::{header, Method, StatusCode, Uri};
use axum::middleware::from_fn_with_state;
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post};
use axum::routing::{delete, get, patch, post, MethodRouter};
use axum::{Json, Router};
use rust_embed::RustEmbed;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::net::SocketAddr;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use tokio::net::TcpListener;
use tokio::sync::Semaphore;
use tower_http::compression::CompressionLayer;
use tower_http::cors::CorsLayer;
use tower_http::trace::TraceLayer;
const LOGO: &[u8] = include_bytes!("../../../logo.png");
@@ -26,15 +31,211 @@ const LOGO: &[u8] = include_bytes!("../../../logo.png");
struct Assets;
#[derive(Clone)]
struct AppState {
pub struct AppState {
storage: Arc<Storage>,
last_report: Arc<std::sync::Mutex<Option<AnalysisReport>>>,
last_report: Arc<Mutex<Option<AnalysisReport>>>,
pub auth: Arc<AuthService>,
pub transport: Arc<Transport>,
pub argon2: Arc<Semaphore>,
}
impl AppState {
pub fn new(storage: Arc<Storage>, auth: Arc<AuthService>, transport: Transport) -> Self {
Self {
storage,
last_report: Arc::new(Mutex::new(None)),
auth,
transport: Arc::new(transport),
argon2: Arc::new(Semaphore::new(auth_http::ARGON2_CONCURRENCY)),
}
}
/// The report is replaced whole, so a poisoned lock still holds a valid one.
fn report(&self) -> MutexGuard<'_, Option<AnalysisReport>> {
self.last_report
.lock()
.unwrap_or_else(PoisonError::into_inner)
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Verb {
Get,
Post,
Patch,
Delete,
}
impl Verb {
/// `HEAD` follows `GET`, as in the router.
fn matches(self, method: &Method) -> bool {
match self {
Verb::Get => *method == Method::GET || *method == Method::HEAD,
Verb::Post => *method == Method::POST,
Verb::Patch => *method == Method::PATCH,
Verb::Delete => *method == Method::DELETE,
}
}
}
/// What a non-public route asks of the caller. There is no public level on
/// purpose: a route is public only by being written into `PUBLIC_ROUTES`.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Access {
/// Any session or token; a read token still cannot mutate.
Authenticated,
/// A browser session: an API token, whatever its scope, is refused.
Session,
/// As `Session`, or the pending token of a first login.
SessionOrPending,
/// Administrator role, and Admin scope when through a token.
Admin,
}
pub struct RouteDef {
pub verb: Verb,
pub path: &'static str,
pub access: Access,
handler: fn() -> MethodRouter<AppState>,
}
const fn route(
verb: Verb,
path: &'static str,
access: Access,
handler: fn() -> MethodRouter<AppState>,
) -> RouteDef {
RouteDef {
verb,
path,
access,
handler,
}
}
/// The one source of routes: `build_app` registers exactly these. Access for
/// entries also in `PUBLIC_ROUTES` is never consulted.
pub const ALL_ROUTES: &[RouteDef] = {
use auth_http as a;
use Access::{Admin, Authenticated, Session, SessionOrPending};
use Verb::{Delete, Get, Patch, Post};
&[
route(Get, "/api/health", Authenticated, || get(health)),
route(Get, "/login.html", Authenticated, || get(asset)),
route(Get, "/login.js", Authenticated, || get(asset)),
route(Get, "/app.css", Authenticated, || get(asset)),
route(Get, "/logo.png", Authenticated, || get(logo)),
route(Get, "/i18n.js", Authenticated, || get(asset)),
route(Get, "/i18n-en.js", Authenticated, || get(asset)),
route(Get, "/api/auth/state", Authenticated, || get(a::auth_state)),
route(Post, "/api/auth/bootstrap", Authenticated, || {
post(a::bootstrap)
}),
route(Post, "/api/auth/login", Authenticated, || post(a::login)),
route(Post, "/api/auth/mfa", Authenticated, || post(a::mfa)),
route(
Post,
"/api/auth/password-change-required",
Authenticated,
|| post(a::password_change_required),
),
route(Post, "/api/auth/logout", Session, || post(a::logout)),
route(Post, "/api/auth/reauth", Session, || post(a::reauth)),
route(Post, "/api/auth/password", Session, || {
post(a::change_password)
}),
route(Post, "/api/auth/mfa/disable", Session, || {
post(a::mfa_disable)
}),
route(Post, "/api/auth/enroll/start", SessionOrPending, || {
post(a::enroll_start)
}),
route(Post, "/api/auth/enroll/confirm", SessionOrPending, || {
post(a::enroll_confirm)
}),
route(Get, "/api/auth/sessions", Authenticated, || {
get(a::sessions_list)
}),
route(Delete, "/api/auth/sessions", Authenticated, || {
delete(a::sessions_revoke)
}),
route(Get, "/api/auth/tokens", Authenticated, || {
get(a::tokens_list)
}),
route(Post, "/api/auth/tokens", Session, || post(a::tokens_create)),
route(Delete, "/api/auth/tokens", Authenticated, || {
delete(a::tokens_revoke)
}),
route(Get, "/api/admin/users", Admin, || get(a::users_list)),
route(Post, "/api/admin/users", Admin, || post(a::users_create)),
route(Patch, "/api/admin/users", Admin, || {
patch(a::users_set_role)
}),
route(Delete, "/api/admin/users", Admin, || {
delete(a::users_delete)
}),
route(Get, "/api/admin/audit", Admin, || get(a::audit)),
route(Post, "/api/analyze", Admin, || post(analyze)),
route(Get, "/api/status", Authenticated, || get(status)),
route(Get, "/api/alerts", Authenticated, || get(alerts)),
route(Get, "/api/update", Authenticated, || get(update_check)),
route(Get, "/relatorio", Authenticated, || get(report_page)),
]
};
/// Everything reachable without a credential. Exact matches only.
pub const PUBLIC_ROUTES: &[(Verb, &str)] = &[
(Verb::Get, "/api/health"),
(Verb::Get, "/login.html"),
(Verb::Get, "/login.js"),
(Verb::Get, "/app.css"),
(Verb::Get, "/logo.png"),
(Verb::Get, "/i18n.js"),
(Verb::Get, "/i18n-en.js"),
(Verb::Get, "/api/auth/state"),
(Verb::Post, "/api/auth/bootstrap"),
(Verb::Post, "/api/auth/login"),
(Verb::Post, "/api/auth/mfa"),
(Verb::Post, "/api/auth/password-change-required"),
];
pub fn is_public(method: &Method, path: &str) -> bool {
PUBLIC_ROUTES
.iter()
.any(|(verb, p)| *p == path && verb.matches(method))
}
/// The public files: shared, cacheable, and holding nothing per-user.
pub fn is_public_asset(method: &Method, path: &str) -> bool {
!path.starts_with("/api/") && is_public(method, path)
}
/// Paths outside the table (the asset fallback) need a credential too.
pub fn access_of(method: &Method, path: &str) -> Access {
ALL_ROUTES
.iter()
.find(|r| r.path == path && r.verb.matches(method))
.map_or(Access::Authenticated, |r| r.access)
}
pub fn build_app(state: AppState) -> Router {
let mut router = Router::new();
for r in ALL_ROUTES {
router = router.route(r.path, (r.handler)());
}
router
.fallback(asset)
// Bounds every `Json` extractor before anything looks at the input.
.layer(DefaultBodyLimit::max(auth_http::MAX_BODY_BYTES))
.layer(from_fn_with_state(state.clone(), require_auth))
.with_state(state)
.layer(CompressionLayer::new())
.layer(TraceLayer::new_for_http())
}
#[derive(Serialize)]
struct Health {
status: &'static str,
version: &'static str,
}
#[derive(Serialize)]
@@ -55,26 +256,27 @@ struct AnalyzeRequest {
}
async fn health() -> Json<Health> {
Json(Health {
status: "ok",
version: env!("CARGO_PKG_VERSION"),
})
Json(Health { status: "ok" })
}
async fn status(State(state): State<AppState>) -> Json<Status> {
Json(Status {
async fn status(State(state): State<AppState>) -> std::result::Result<Json<Status>, ApiError> {
let storage = state.storage.clone();
let dataset = blocking(move || {
Ok(storage
.summary()
.unwrap_or_else(|_| DatasetSummary::empty()))
})
.await?;
Ok(Json(Status {
version: env!("CARGO_PKG_VERSION"),
mode: "serve",
dataset: state
.storage
.summary()
.unwrap_or_else(|_| DatasetSummary::empty()),
})
dataset,
}))
}
async fn alerts(State(state): State<AppState>) -> Json<Vec<Alert>> {
let report_lock = state.last_report.lock().unwrap();
let list = report_lock
let list = state
.report()
.as_ref()
.map(|r| r.alerts.clone())
.unwrap_or_default();
@@ -83,23 +285,25 @@ async fn alerts(State(state): State<AppState>) -> Json<Vec<Alert>> {
async fn analyze(
State(state): State<AppState>,
Json(request): Json<AnalyzeRequest>,
) -> std::result::Result<Json<AnalysisReport>, (StatusCode, Json<ErrorBody>)> {
zeek::analyze_dir(&request.path, state.storage.root())
.map(|report| {
if let Ok(mut lock) = state.last_report.lock() {
*lock = Some(report.clone());
}
Json(report)
})
.map_err(|error| {
(
StatusCode::BAD_REQUEST,
Json(ErrorBody {
error: error.to_string(),
}),
)
})
JsonBody(request): JsonBody<AnalyzeRequest>,
) -> Response {
let root = state.storage.root().to_path_buf();
let outcome =
tokio::task::spawn_blocking(move || zeek::analyze_dir(&request.path, &root)).await;
match outcome {
Ok(Ok(report)) => {
*state.report() = Some(report.clone());
Json(report).into_response()
}
Ok(Err(error)) => (
StatusCode::BAD_REQUEST,
Json(ErrorBody {
error: error.to_string(),
}),
)
.into_response(),
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
}
}
/// Executive report of the latest analysis (`?tlp=` picks the TLP label).
@@ -107,7 +311,7 @@ async fn report_page(
State(state): State<AppState>,
Query(query): Query<HashMap<String, String>>,
) -> Response {
let lock = state.last_report.lock().unwrap();
let lock = state.report();
let Some(report) = lock.as_ref() else {
return (
StatusCode::NOT_FOUND,
@@ -124,17 +328,19 @@ async fn report_page(
([(header::CONTENT_TYPE, "text/html; charset=utf-8")], html).into_response()
}
async fn update_check() -> std::result::Result<Json<UpdateStatus>, (StatusCode, Json<ErrorBody>)> {
update::check(env!("CARGO_PKG_VERSION"))
.map(Json)
.map_err(|error| {
(
StatusCode::BAD_GATEWAY,
Json(ErrorBody {
error: error.to_string(),
}),
)
})
async fn update_check() -> Response {
let outcome = tokio::task::spawn_blocking(|| update::check(env!("CARGO_PKG_VERSION"))).await;
match outcome {
Ok(Ok(status)) => Json::<UpdateStatus>(status).into_response(),
Ok(Err(error)) => (
StatusCode::BAD_GATEWAY,
Json(ErrorBody {
error: error.to_string(),
}),
)
.into_response(),
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
}
}
async fn logo() -> impl IntoResponse {
@@ -180,27 +386,23 @@ async fn shutdown_signal() {
pub async fn serve(bind: &str, data_dir: PathBuf) -> Result<()> {
let _ = tracing_subscriber::fmt().try_init();
std::fs::create_dir_all(&data_dir)?;
let state = AppState {
storage: Arc::new(Storage::open(&data_dir)?),
last_report: Arc::new(std::sync::Mutex::new(None)),
};
let app = Router::new()
.route("/api/health", get(health))
.route("/api/status", get(status))
.route("/api/alerts", get(alerts))
.route("/api/analyze", post(analyze))
.route("/api/update", get(update_check))
.route("/relatorio", get(report_page))
.route("/logo.png", get(logo))
.fallback(asset)
.with_state(state)
.layer(CompressionLayer::new())
.layer(CorsLayer::new())
.layer(TraceLayer::new_for_http());
let auth = Arc::new(AuthService::open(&data_dir, None)?);
if let Some(code) = auth.ensure_bootstrap(auth_http::unix_now())? {
eprintln!("Acauã: código de configuração inicial (válido por 1 hora): {code}");
}
let state = AppState::new(Arc::new(Storage::open(&data_dir)?), auth, Transport::Local);
let app = build_app(state);
let listener = TcpListener::bind(bind).await?;
println!("Acauã listening on http://{bind}");
axum::serve(listener, app)
.with_graceful_shutdown(shutdown_signal())
.await?;
axum::serve(
listener,
app.into_make_service_with_connect_info::<SocketAddr>(),
)
.with_graceful_shutdown(shutdown_signal())
.await?;
Ok(())
}
#[cfg(test)]
#[path = "web_tests.rs"]
mod tests;