feat(api): require an admin token for configuration changes
Group CRUD decides what the scanner sweeps, yet any client that reached the API could change it. Writes now need XEXEU_ADMIN_TOKEN (or a token generated at startup and printed as a ?token= link, like sabia ui), compared in constant time, and a browser Origin must match Host. The dashboard keeps the token for the tab and asks for it on 401. Reads are unchanged. Also track .env.example: '.env*' in .gitignore had kept it out of the repository, although the README tells operators to copy it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
36eadabc7c
commit
90ece32dac
17 files changed
+369
-28
No files matched your search
@@ -0,0 +1,168 @@
|
||||
//! Admin token for the API routes that change state (group CRUD).
|
||||
//!
|
||||
//! Reads stay open, as before: the dashboard is meant to sit on loopback or
|
||||
//! behind a reverse proxy. Writes decide what the scanner sweeps, so they need
|
||||
//! the admin token in `Authorization: Bearer <token>` or `X-Xexeu-Token`, and a
|
||||
//! browser `Origin`, when sent, must match `Host` (CSRF).
|
||||
//!
|
||||
//! The token comes from `--admin-token`/`XEXEU_ADMIN_TOKEN`; without one, a
|
||||
//! random token is generated at startup and printed once, the same way
|
||||
//! `sabia ui` hands out its session token.
|
||||
|
||||
use std::fs::File;
|
||||
use std::io::Read;
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::extract::{Request, State};
|
||||
use axum::http::{header, HeaderMap, Method, StatusCode};
|
||||
use axum::middleware::Next;
|
||||
use axum::response::{IntoResponse, Response};
|
||||
|
||||
/// Shortest token accepted from configuration; shorter ones are guessable.
|
||||
pub const MIN_TOKEN_LEN: usize = 16;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AdminToken(Arc<str>);
|
||||
|
||||
impl AdminToken {
|
||||
pub fn new(token: &str) -> Self {
|
||||
Self(Arc::from(token))
|
||||
}
|
||||
|
||||
/// 32 random bytes from the kernel, hex-encoded.
|
||||
pub fn generate() -> std::io::Result<Self> {
|
||||
let mut bytes = [0u8; 32];
|
||||
File::open("/dev/urandom")?.read_exact(&mut bytes)?;
|
||||
let hex: String = bytes.iter().map(|b| format!("{b:02x}")).collect();
|
||||
Ok(Self::new(&hex))
|
||||
}
|
||||
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.0
|
||||
}
|
||||
|
||||
/// Constant-time comparison: the time taken does not reveal how many
|
||||
/// leading characters of a guess were right.
|
||||
pub fn matches(&self, candidate: &str) -> bool {
|
||||
let expected = self.0.as_bytes();
|
||||
let candidate = candidate.as_bytes();
|
||||
let mut diff = expected.len() ^ candidate.len();
|
||||
for (index, byte) in expected.iter().enumerate() {
|
||||
diff |= usize::from(byte ^ candidate.get(index).copied().unwrap_or(0));
|
||||
}
|
||||
diff == 0
|
||||
}
|
||||
}
|
||||
|
||||
/// Token sent by the client, from `Authorization: Bearer` or `X-Xexeu-Token`.
|
||||
fn presented_token(headers: &HeaderMap) -> Option<&str> {
|
||||
if let Some(value) = headers.get("x-xexeu-token").and_then(|v| v.to_str().ok()) {
|
||||
return Some(value.trim());
|
||||
}
|
||||
headers
|
||||
.get(header::AUTHORIZATION)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|v| v.strip_prefix("Bearer "))
|
||||
.map(str::trim)
|
||||
}
|
||||
|
||||
/// `true` when there is no `Origin` (non-browser client) or its host matches `Host`.
|
||||
fn same_origin(headers: &HeaderMap) -> bool {
|
||||
let Some(origin) = headers.get(header::ORIGIN).and_then(|v| v.to_str().ok()) else {
|
||||
return true;
|
||||
};
|
||||
let Some(host) = headers.get(header::HOST).and_then(|v| v.to_str().ok()) else {
|
||||
return false;
|
||||
};
|
||||
let origin_host = origin
|
||||
.split_once("://")
|
||||
.map(|(_, rest)| rest)
|
||||
.unwrap_or(origin)
|
||||
.trim_end_matches('/');
|
||||
origin_host.eq_ignore_ascii_case(host)
|
||||
}
|
||||
|
||||
fn is_write(method: &Method) -> bool {
|
||||
!matches!(*method, Method::GET | Method::HEAD | Method::OPTIONS)
|
||||
}
|
||||
|
||||
pub async fn require_admin(
|
||||
State(token): State<AdminToken>,
|
||||
request: Request,
|
||||
next: Next,
|
||||
) -> Response {
|
||||
if is_write(request.method()) {
|
||||
let headers = request.headers();
|
||||
if !same_origin(headers) {
|
||||
return (StatusCode::FORBIDDEN, "origem da requisição não confere").into_response();
|
||||
}
|
||||
match presented_token(headers) {
|
||||
Some(candidate) if token.matches(candidate) => {}
|
||||
_ => {
|
||||
return (
|
||||
StatusCode::UNAUTHORIZED,
|
||||
[(header::WWW_AUTHENTICATE, "Bearer")],
|
||||
"token de administração ausente ou inválido",
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
next.run(request).await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use axum::http::HeaderValue;
|
||||
|
||||
#[test]
|
||||
fn matches_only_the_exact_token() {
|
||||
let token = AdminToken::new("abcdef0123456789");
|
||||
assert!(token.matches("abcdef0123456789"));
|
||||
assert!(!token.matches("abcdef012345678"));
|
||||
assert!(!token.matches("abcdef01234567890"));
|
||||
assert!(!token.matches("Abcdef0123456789"));
|
||||
assert!(!token.matches(""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_tokens_are_long_and_distinct() {
|
||||
let a = AdminToken::generate().unwrap();
|
||||
let b = AdminToken::generate().unwrap();
|
||||
assert_eq!(a.as_str().len(), 64);
|
||||
assert_ne!(a.as_str(), b.as_str());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_bearer_and_custom_header() {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
header::AUTHORIZATION,
|
||||
HeaderValue::from_static("Bearer xyz"),
|
||||
);
|
||||
assert_eq!(presented_token(&headers), Some("xyz"));
|
||||
headers.insert("x-xexeu-token", HeaderValue::from_static("abc"));
|
||||
assert_eq!(presented_token(&headers), Some("abc"));
|
||||
headers.clear();
|
||||
headers.insert(header::AUTHORIZATION, HeaderValue::from_static("Basic xyz"));
|
||||
assert_eq!(presented_token(&headers), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn origin_must_match_host() {
|
||||
let mut headers = HeaderMap::new();
|
||||
assert!(same_origin(&headers));
|
||||
headers.insert(header::HOST, HeaderValue::from_static("127.0.0.1:8788"));
|
||||
headers.insert(
|
||||
header::ORIGIN,
|
||||
HeaderValue::from_static("http://127.0.0.1:8788"),
|
||||
);
|
||||
assert!(same_origin(&headers));
|
||||
headers.insert(
|
||||
header::ORIGIN,
|
||||
HeaderValue::from_static("https://evil.example"),
|
||||
);
|
||||
assert!(!same_origin(&headers));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user