audit: harden math rendering (XSS), URL/SSRF/image caps, API auth (SEC-01/02/03/06/09)
This commit is contained in:
1 parent
4cdc4334d8
commit
b8e1a07e77
3 files changed
+300
-19
No files matched your search
+104
-7
@@ -122,31 +122,57 @@ impl AuthConfig {
|
||||
.get(axum::http::header::HOST)
|
||||
.and_then(|h| h.to_str().ok())
|
||||
.unwrap_or("");
|
||||
let host = host.rsplit_once(':').map(|(h, _)| h).unwrap_or(host);
|
||||
self.allowed_hosts
|
||||
.iter()
|
||||
.any(|h| h.eq_ignore_ascii_case(host))
|
||||
// Strip the port. A bracketed IPv6 Host (`[::1]:8095` or `[::1]`) must
|
||||
// yield `::1`, not `[:` — rsplit_once(':') alone mangles it.
|
||||
let host = match host.strip_prefix('[') {
|
||||
Some(v6) => v6.split(']').next().unwrap_or(v6),
|
||||
None => host.rsplit_once(':').map(|(h, _)| h).unwrap_or(host),
|
||||
};
|
||||
self.allowed_hosts.iter().any(|h| {
|
||||
let h = h
|
||||
.strip_prefix('[')
|
||||
.and_then(|s| s.strip_suffix(']'))
|
||||
.unwrap_or(h);
|
||||
h.eq_ignore_ascii_case(host)
|
||||
})
|
||||
}
|
||||
|
||||
fn key_ok(&self, headers: &axum::http::HeaderMap) -> bool {
|
||||
let Some(key) = self.api_key.as_deref() else {
|
||||
// An empty/whitespace key is a misconfiguration, not "accept an empty
|
||||
// header": treat it as no key rather than letting `Bearer ` pass.
|
||||
let Some(key) = self.api_key.as_deref().filter(|k| !k.trim().is_empty()) else {
|
||||
return true;
|
||||
};
|
||||
if let Some(auth) = headers
|
||||
.get(axum::http::header::AUTHORIZATION)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
{
|
||||
if auth.strip_prefix("Bearer ").is_some_and(|t| t == key) {
|
||||
// The auth scheme is case-insensitive (RFC 9110); the token is not.
|
||||
if auth
|
||||
.get(..7)
|
||||
.is_some_and(|p| p.eq_ignore_ascii_case("Bearer "))
|
||||
&& ct_eq(&auth.as_bytes()[7..], key.as_bytes())
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
headers
|
||||
.get("x-api-key")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.is_some_and(|k| k == key)
|
||||
.is_some_and(|k| ct_eq(k.as_bytes(), key.as_bytes()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Constant-time byte equality (no timing side-channel on the API key), std-only.
|
||||
/// The length XOR is folded into the accumulator so unequal lengths still fail.
|
||||
fn ct_eq(a: &[u8], b: &[u8]) -> bool {
|
||||
let mut diff = a.len() ^ b.len();
|
||||
for (x, y) in a.iter().zip(b.iter()) {
|
||||
diff |= usize::from(*x ^ *y);
|
||||
}
|
||||
diff == 0
|
||||
}
|
||||
|
||||
/// Enforces the Host allowlist and (except on `/health`) the API key before any
|
||||
/// handler runs.
|
||||
async fn auth_middleware(
|
||||
@@ -362,3 +388,74 @@ async fn json_body<T: DeserializeOwned>(req: axum::extract::Request) -> Result<T
|
||||
serde_json::from_slice::<T>(&bytes)
|
||||
.map_err(|e| Error::bad_request(format!("invalid JSON body: {e}")))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use axum::http::{HeaderMap, HeaderName};
|
||||
|
||||
fn host_header(value: &str) -> HeaderMap {
|
||||
let mut h = HeaderMap::new();
|
||||
h.insert(axum::http::header::HOST, value.parse().unwrap());
|
||||
h
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_allowlist_parses_ipv6_and_ports() {
|
||||
let auth = AuthConfig {
|
||||
api_key: None,
|
||||
allowed_hosts: vec!["localhost".into(), "127.0.0.1".into(), "::1".into()],
|
||||
};
|
||||
assert!(auth.host_allowed(&host_header("localhost:8095")));
|
||||
assert!(auth.host_allowed(&host_header("127.0.0.1:8095")));
|
||||
assert!(auth.host_allowed(&host_header("[::1]:8095")));
|
||||
assert!(auth.host_allowed(&host_header("[::1]")));
|
||||
assert!(!auth.host_allowed(&host_header("evil.com:8095")));
|
||||
let open = AuthConfig {
|
||||
api_key: None,
|
||||
allowed_hosts: vec!["*".into()],
|
||||
};
|
||||
assert!(open.host_allowed(&host_header("anything.example")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn key_check_bearer_case_and_empty_key() {
|
||||
let auth = AuthConfig {
|
||||
api_key: Some("secret".into()),
|
||||
allowed_hosts: vec![],
|
||||
};
|
||||
let bearer = |v: &str| {
|
||||
let mut h = HeaderMap::new();
|
||||
h.insert(axum::http::header::AUTHORIZATION, v.parse().unwrap());
|
||||
h
|
||||
};
|
||||
assert!(auth.key_ok(&bearer("Bearer secret")));
|
||||
// RFC 9110: the auth scheme is case-insensitive.
|
||||
assert!(auth.key_ok(&bearer("bearer secret")));
|
||||
assert!(auth.key_ok(&bearer("BEARER secret")));
|
||||
assert!(!auth.key_ok(&bearer("Bearer nope")));
|
||||
let mut x = HeaderMap::new();
|
||||
x.insert(
|
||||
HeaderName::from_static("x-api-key"),
|
||||
"secret".parse().unwrap(),
|
||||
);
|
||||
assert!(auth.key_ok(&x));
|
||||
// An empty configured key is a misconfiguration -> treated as no auth,
|
||||
// never "accept an empty Bearer/x-api-key header".
|
||||
let empty = AuthConfig {
|
||||
api_key: Some("".into()),
|
||||
allowed_hosts: vec![],
|
||||
};
|
||||
assert!(empty.key_ok(&HeaderMap::new()));
|
||||
assert!(empty.key_ok(&bearer("Bearer ")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ct_eq_compares_bytes_without_early_exit() {
|
||||
assert!(ct_eq(b"secret", b"secret"));
|
||||
assert!(ct_eq(b"", b""));
|
||||
assert!(!ct_eq(b"secret", b"secreu"));
|
||||
assert!(!ct_eq(b"secret", b"secret2"));
|
||||
assert!(!ct_eq(b"", b"x"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user