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, AcauaError, Result}; use axum::body::Body; use axum::extract::Request; use axum::extract::{DefaultBodyLimit, Query, State}; use axum::http::{header, HeaderValue, Method, StatusCode, Uri}; use axum::middleware::{from_fn, from_fn_with_state, Next}; use axum::response::{IntoResponse, Response}; use axum::routing::{delete, get, patch, post, MethodRouter}; use axum::{Json, Router}; use axum_server::tls_rustls::RustlsConfig; use axum_server::Handle; use rust_embed::RustEmbed; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::net::SocketAddr; use std::path::PathBuf; use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; use std::time::Duration; use tokio::net::TcpListener; use tokio::sync::Semaphore; use tower_http::compression::CompressionLayer; use tower_http::trace::TraceLayer; const LOGO: &[u8] = include_bytes!("../../../logo.png"); #[derive(RustEmbed)] #[folder = "../../apps/gui/ui/"] struct Assets; #[derive(Clone)] pub struct AppState { storage: Arc, last_report: Arc>>, pub auth: Arc, pub transport: Arc, pub argon2: Arc, } impl AppState { pub fn new(storage: Arc, auth: Arc, 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> { 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, /// Administrator in a session that reauthenticated recently, never a /// token: otherwise a hijacked session could create an admin outliving it. AdminRecentSession, } pub struct RouteDef { pub verb: Verb, pub path: &'static str, pub access: Access, handler: fn() -> MethodRouter, } const fn route( verb: Verb, path: &'static str, access: Access, handler: fn() -> MethodRouter, ) -> 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, AdminRecentSession, 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", AdminRecentSession, || { post(a::users_create) }), route(Patch, "/api/admin/users", AdminRecentSession, || { patch(a::users_set_role) }), route(Delete, "/api/admin/users", AdminRecentSession, || { 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)) .layer(from_fn_with_state(state.clone(), hsts)) .layer(from_fn(security_headers)) .with_state(state) .layer(CompressionLayer::new()) .layer(TraceLayer::new_for_http()) } /// Adds `Strict-Transport-Security` when the transport is HTTPS. It sits /// outside `require_auth`, so refusals carry it too. async fn hsts(State(state): State, req: Request, next: Next) -> Response { let mut response = next.run(req).await; if state.transport.hsts() { response.headers_mut().insert( header::STRICT_TRANSPORT_SECURITY, HeaderValue::from_static("max-age=31536000"), ); } response } /// `style-src 'unsafe-inline'` is the narrowest that works: the report carries /// its stylesheet inline and Paged.js adds `