audit: harden math rendering (XSS), URL/SSRF/image caps, API auth (SEC-01/02/03/06/09)

This commit is contained in:
adm committed 2026-11-27 18:13:18 +01:00
1 parent 4cdc4334d8
commit b8e1a07e77
3 files changed
+300 -19

No files matched your search

+104 -7
View File
@@ -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"));
}
}
+138 -8
View File
@@ -132,7 +132,11 @@ pub fn materialize(sources: &[String]) -> Result<Vec<PathBuf>, ImageError> {
/// Bytes of one source: base64 data URL, http(s) fetch, or local file path.
fn load_bytes(src: &str) -> Result<Vec<u8>, ImageError> {
if let Some(rest) = src.strip_prefix("data:") {
if src
.get(..5)
.is_some_and(|s| s.eq_ignore_ascii_case("data:"))
{
let rest = &src[5..];
let (meta, data) = rest
.split_once(',')
.ok_or_else(|| ImageError::Unsupported("malformed data URL".into()))?;
@@ -141,15 +145,63 @@ fn load_bytes(src: &str) -> Result<Vec<u8>, ImageError> {
"only base64 data URLs are supported".into(),
));
}
// Cap the encoded length BEFORE decoding: base64 inflates ~4/3, so a
// giant data URL must not allocate gigabytes (OOM DoS).
if data.len() as u64 > MAX_IMAGE_BYTES * 4 / 3 + 16 {
return Err(ImageError::Decode(
"data URL exceeds the image size cap".into(),
));
}
return base64::engine::general_purpose::STANDARD
.decode(data)
.map_err(|e| ImageError::Decode(e.to_string()));
}
if src.starts_with("http://") || src.starts_with("https://") {
// Scheme match is case-insensitive: `HTTP://…` must fetch (through the SSRF
// guard), not fall through to a local file read.
let is_http = src
.get(..7)
.is_some_and(|s| s.eq_ignore_ascii_case("http://"))
|| src
.get(..8)
.is_some_and(|s| s.eq_ignore_ascii_case("https://"));
if is_http {
return fetch_http(src);
}
let path = src.strip_prefix("file://").unwrap_or(src);
std::fs::read(path).map_err(|e| ImageError::Io(format!("{path}: {e}")))
let path = if src
.get(..7)
.is_some_and(|s| s.eq_ignore_ascii_case("file://"))
{
&src[7..]
} else {
src
};
// Same fd for check and read (no TOCTOU symlink swap); only regular files,
// size-bounded: a device (`/dev/zero`) would exhaust memory, a multi-GB file
// would OOM. `take` caps the read even if the file grows between check/read.
let file = std::fs::File::open(path).map_err(|e| ImageError::Io(format!("{path}: {e}")))?;
let meta = file
.metadata()
.map_err(|e| ImageError::Io(format!("{path}: {e}")))?;
if !meta.is_file() {
return Err(ImageError::Unsupported(format!(
"{path}: not a regular file"
)));
}
if meta.len() > MAX_IMAGE_BYTES {
return Err(ImageError::Decode(format!(
"{path}: exceeds the image size cap"
)));
}
let mut buf = Vec::new();
file.take(MAX_IMAGE_BYTES + 1)
.read_to_end(&mut buf)
.map_err(|e| ImageError::Io(format!("{path}: {e}")))?;
if buf.len() as u64 > MAX_IMAGE_BYTES {
return Err(ImageError::Decode(format!(
"{path}: exceeds the image size cap"
)));
}
Ok(buf)
}
/// Fetch an http(s) image with a timeout and a size cap. Blocks literal
@@ -163,6 +215,9 @@ fn fetch_http(src: &str) -> Result<Vec<u8>, ImageError> {
}
let agent: ureq::Agent = ureq::Agent::config_builder()
.timeout_global(Some(FETCH_TIMEOUT))
// Do not follow redirects: a 3xx to an internal host (169.254.169.254,
// 127.0.0.1) would bypass the lexical SSRF guard on the initial URL.
.max_redirects(0)
.build()
.new_agent();
let mut resp = agent
@@ -192,18 +247,47 @@ fn is_blocked_host(url: &str) -> bool {
None => host.split(':').next().unwrap_or(host), // host:port
};
let host = host.to_ascii_lowercase();
// A trailing FQDN dot (`localhost.`) is the same host: strip it.
let host = host.trim_end_matches('.');
if host == "localhost" || host.ends_with(".local") || host.ends_with(".internal") {
return true;
}
match host.parse::<std::net::IpAddr>() {
Ok(std::net::IpAddr::V4(v4)) => {
v4.is_loopback() || v4.is_private() || v4.is_link_local() || v4.is_unspecified()
}
Ok(std::net::IpAddr::V6(v6)) => v6.is_loopback() || v6.is_unspecified(),
Ok(std::net::IpAddr::V4(v4)) => is_non_global_v4(v4),
Ok(std::net::IpAddr::V6(v6)) => is_non_global_v6(v6),
Err(_) => false,
}
}
/// IPv4 addresses that are not globally routable: loopback, private, link-local,
/// unspecified, broadcast, multicast, 0/8 "this network", and CGNAT 100.64/10
/// (used by Tailscale).
fn is_non_global_v4(v4: std::net::Ipv4Addr) -> bool {
let o = v4.octets();
v4.is_loopback()
|| v4.is_private()
|| v4.is_link_local()
|| v4.is_unspecified()
|| v4.is_broadcast()
|| v4.is_multicast()
|| o[0] == 0
|| (o[0] == 100 && (o[1] & 0xc0) == 64) // 100.64.0.0/10 CGNAT
}
/// IPv6 non-global addresses, judging IPv4-mapped (`::ffff:a.b.c.d`) by their
/// IPv4 target so `http://[::ffff:127.0.0.1]/` cannot slip past the guard.
fn is_non_global_v6(v6: std::net::Ipv6Addr) -> bool {
if let Some(v4) = v6.to_ipv4_mapped() {
return is_non_global_v4(v4);
}
let seg = v6.segments();
v6.is_loopback()
|| v6.is_unspecified()
|| (seg[0] & 0xfe00) == 0xfc00 // fc00::/7 ULA
|| (seg[0] & 0xffc0) == 0xfe80 // fe80::/10 link-local
|| (seg[0] & 0xff00) == 0xff00 // ff00::/8 multicast
}
/// Keep JPEG/PNG/BMP/GIF as-is; convert anything else to PNG via the image crate.
fn normalize(data: Vec<u8>) -> Result<(Vec<u8>, &'static str), ImageError> {
if let Some(ext) = sniff(&data) {
@@ -246,6 +330,7 @@ mod tests {
"http://[::1]/x.png",
"http://user@127.0.0.1/x.png",
"http://foo.local/x.png",
"http://localhost./x.png",
] {
assert!(is_blocked_host(url), "{url} should be blocked");
}
@@ -253,4 +338,49 @@ mod tests {
assert!(!is_blocked_host(url), "{url} should be allowed");
}
}
#[test]
fn ssrf_guard_blocks_mapped_ula_cgnat() {
for url in [
"http://[::ffff:127.0.0.1]/x.png",
"http://[::ffff:10.0.0.1]/x.png",
"http://[::ffff:169.254.169.254]/x.png",
"http://[fc00::1]/x.png",
"http://[fe80::1]/x.png",
"http://100.64.0.1/x.png",
"http://224.0.0.1/x.png",
"http://255.255.255.255/x.png",
] {
assert!(is_blocked_host(url), "{url} should be blocked");
}
// A globally routable IPv4-mapped address is still allowed.
assert!(!is_blocked_host("http://[::ffff:8.8.8.8]/x.png"));
}
#[test]
fn http_scheme_is_case_insensitive() {
assert!(is_blocked_host("HTTP://127.0.0.1/x.png"));
// load_bytes routes HTTP:// through fetch_http (which refuses loopback),
// not through a local file read.
let err = load_bytes("HTTP://127.0.0.1/x.png").unwrap_err();
assert!(matches!(err, ImageError::Fetch(_)), "{err:?}");
}
#[test]
fn oversized_data_url_is_refused_before_decode() {
let big = "A".repeat((MAX_IMAGE_BYTES * 4 / 3 + 17) as usize);
let src = format!("data:image/png;base64,{big}");
let err = load_bytes(&src).unwrap_err();
assert!(matches!(err, ImageError::Decode(_)), "{err:?}");
}
#[test]
fn non_regular_file_is_refused() {
// /dev/zero is a char device: refused before reading (std::fs::read would
// otherwise allocate until OOM). Guarded for non-Unix hosts.
if std::path::Path::new("/dev/zero").exists() {
let err = load_bytes("/dev/zero").unwrap_err();
assert!(matches!(err, ImageError::Unsupported(_)), "{err:?}");
}
}
}
+58 -4
View File
@@ -62,11 +62,22 @@ pub fn markdown_to_safe_html(text: &str) -> String {
}
/// Render a LaTeX fragment to MathML. `display` selects block (`$$…$$`) vs inline
/// (`$…$`) mode. On the rare writer error we fall back to escaped source in a
/// `<code>` so nothing is lost; invalid LaTeX is flagged inline by the crate.
/// (`$…$`) mode. Invalid LaTeX falls back to escaped source in a `<code>`.
///
/// Safety: `pulldown-latex` renders a parse error as
/// `<merror><mtext>…raw source window…</mtext></merror>` and does NOT escape that
/// window (its `Err` branch writes `e.to_string()` verbatim, unlike normal text).
/// `<mtext>` is an HTML text integration point, so a crafted malformed fragment
/// can smuggle a live `<img>`/`<svg>` into `innerHTML` (stored XSS). Writing to a
/// `String` never fails, so `push_mathml` returns `Ok` even on a parse error — the
/// writer-error fallback below would never fire. We therefore collect the events
/// first and fall back to escaped source on ANY parse error.
fn render_math(latex: &str, display: bool) -> String {
let storage = Storage::new();
let parser = pulldown_latex::Parser::new(latex, &storage);
let events: Result<Vec<_>, _> = pulldown_latex::Parser::new(latex, &storage).collect();
let Ok(events) = events else {
return format!("<code>{}</code>", escape_html(latex));
};
let config = RenderConfig {
display_mode: if display {
DisplayMode::Block
@@ -76,7 +87,8 @@ fn render_math(latex: &str, display: bool) -> String {
..RenderConfig::default()
};
let mut out = String::new();
match push_mathml(&mut out, parser, config) {
let events = events.into_iter().map(Ok::<_, std::convert::Infallible>);
match push_mathml(&mut out, events, config) {
Ok(()) => out,
Err(_) => format!("<code>{}</code>", escape_html(latex)),
}
@@ -89,6 +101,17 @@ fn render_math(latex: &str, display: bool) -> String {
fn safe_url(url: &str) -> String {
let cleaned: String = url.chars().filter(|c| !c.is_control()).collect();
let trimmed = cleaned.trim();
// Protocol-relative URLs (`//host/…`) inherit the page scheme and can point
// off-origin: block them so a model-written image/link cannot beacon to an
// attacker host. The WHATWG URL parser also treats `\\`, `/\`, `\/` as
// scheme-relative on http(s) pages, so block those spellings too.
if trimmed.starts_with("//")
|| trimmed.starts_with("\\\\")
|| trimmed.starts_with("/\\")
|| trimmed.starts_with("\\/")
{
return String::new();
}
if let Some(colon) = trimmed.find(':') {
let scheme = &trimmed[..colon];
let looks_like_scheme = scheme
@@ -207,5 +230,36 @@ mod tests {
assert_eq!(safe_url("data:text/html,x"), "");
assert_eq!(safe_url("vbscript:x"), "");
assert_eq!(safe_url("file:///etc/passwd"), "");
// Protocol-relative URLs are blocked (off-origin beacon / hijacking),
// including the backslash spellings the WHATWG parser normalizes.
assert_eq!(safe_url("//evil.com/pixel.png"), "");
assert_eq!(safe_url("//evil.com"), "");
assert_eq!(safe_url("\\\\evil.com"), "");
assert_eq!(safe_url("/\\evil.com"), "");
assert_eq!(safe_url("\\/evil.com"), "");
}
#[test]
fn malformed_latex_math_cannot_inject_live_html() {
// pulldown-latex writes the raw source window of a parse error into
// <mtext> unescaped; <mtext> is an HTML integration point. These must
// fall back to escaped <code>, never a live <img>/<svg> or <merror>.
for src in [
"$<img/src=1 onerror=alert(1)#$",
"$$#<svg onload=alert(1)>#$$",
"$\\frac{<img src=x onerror=alert(2)>}{#}$",
] {
let html = markdown_to_safe_html(src);
assert!(!html.contains("<img"), "live img leaked: {html}");
assert!(!html.contains("<svg"), "live svg leaked: {html}");
assert!(!html.contains("<merror"), "raw error window leaked: {html}");
assert!(html.contains("<code>"), "expected escaped fallback: {html}");
}
}
#[test]
fn protocol_relative_image_is_stripped() {
let html = markdown_to_safe_html("![x](//evil.com/pixel.png)");
assert!(!html.contains("//evil.com"), "{html}");
}
}