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>
409 lines
13 KiB
Rust
409 lines
13 KiB
Rust
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::{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::{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, Mutex, MutexGuard, PoisonError};
|
|
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<Storage>,
|
|
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,
|
|
}
|
|
|
|
#[derive(Serialize)]
|
|
struct Status {
|
|
version: &'static str,
|
|
mode: &'static str,
|
|
dataset: DatasetSummary,
|
|
}
|
|
|
|
#[derive(Serialize)]
|
|
struct ErrorBody {
|
|
error: String,
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
struct AnalyzeRequest {
|
|
path: String,
|
|
}
|
|
|
|
async fn health() -> Json<Health> {
|
|
Json(Health { status: "ok" })
|
|
}
|
|
|
|
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,
|
|
}))
|
|
}
|
|
|
|
async fn alerts(State(state): State<AppState>) -> Json<Vec<Alert>> {
|
|
let list = state
|
|
.report()
|
|
.as_ref()
|
|
.map(|r| r.alerts.clone())
|
|
.unwrap_or_default();
|
|
Json(list)
|
|
}
|
|
|
|
async fn analyze(
|
|
State(state): State<AppState>,
|
|
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).
|
|
async fn report_page(
|
|
State(state): State<AppState>,
|
|
Query(query): Query<HashMap<String, String>>,
|
|
) -> Response {
|
|
let lock = state.report();
|
|
let Some(report) = lock.as_ref() else {
|
|
return (
|
|
StatusCode::NOT_FOUND,
|
|
[(header::CONTENT_TYPE, "text/html; charset=utf-8")],
|
|
"<!doctype html><meta charset=\"utf-8\"><title>Acauã</title><p>Nenhuma análise executada. Rode uma análise no painel e abra o relatório de novo.</p>",
|
|
)
|
|
.into_response();
|
|
};
|
|
let options = acaua_core::report::ReportOptions {
|
|
tlp: query.get("tlp").cloned().unwrap_or_else(|| "AMBER".into()),
|
|
issued_at: None,
|
|
};
|
|
let html = acaua_core::report::render_html_with(report, &options);
|
|
([(header::CONTENT_TYPE, "text/html; charset=utf-8")], html).into_response()
|
|
}
|
|
|
|
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 {
|
|
([(header::CONTENT_TYPE, "image/png")], Body::from(LOGO))
|
|
}
|
|
|
|
async fn asset(uri: Uri) -> Response {
|
|
let path = uri.path().trim_start_matches('/');
|
|
let path = if path.is_empty() { "index.html" } else { path };
|
|
match Assets::get(path) {
|
|
Some(file) => {
|
|
let mime = mime_guess::from_path(path).first_or_octet_stream();
|
|
Response::builder()
|
|
.header(header::CONTENT_TYPE, mime.as_ref())
|
|
.body(Body::from(file.data.into_owned()))
|
|
.unwrap_or_else(|_| StatusCode::INTERNAL_SERVER_ERROR.into_response())
|
|
}
|
|
None => (StatusCode::NOT_FOUND, "not found").into_response(),
|
|
}
|
|
}
|
|
|
|
async fn shutdown_signal() {
|
|
let interrupt = async {
|
|
let _ = tokio::signal::ctrl_c().await;
|
|
};
|
|
#[cfg(unix)]
|
|
let terminate = async {
|
|
match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
|
|
Ok(mut stream) => {
|
|
stream.recv().await;
|
|
}
|
|
Err(_) => std::future::pending::<()>().await,
|
|
}
|
|
};
|
|
#[cfg(not(unix))]
|
|
let terminate = std::future::pending::<()>();
|
|
tokio::select! {
|
|
_ = interrupt => {}
|
|
_ = terminate => {}
|
|
}
|
|
}
|
|
|
|
pub async fn serve(bind: &str, data_dir: PathBuf) -> Result<()> {
|
|
let _ = tracing_subscriber::fmt().try_init();
|
|
std::fs::create_dir_all(&data_dir)?;
|
|
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.into_make_service_with_connect_info::<SocketAddr>(),
|
|
)
|
|
.with_graceful_shutdown(shutdown_signal())
|
|
.await?;
|
|
Ok(())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
#[path = "web_tests.rs"]
|
|
mod tests;
|