This commit is contained in:
Mateusz Gruszczyński committed 2026-10-21 14:39:51 +02:00
1 parent e037190c14
commit 5cb3b37627
37 files changed
+1031 -138

No files matched your search

+106
View File
@@ -91,6 +91,109 @@ impl MethodPolicy {
.flatten()
}
}
/// Per-vhost request Content-Type filtering. This inspects only headers and
/// deliberately never reads the body before deciding whether to reject it.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(default, deny_unknown_fields)]
pub struct ContentTypePolicy {
pub enabled: bool,
/// Exact media types (`multipart/form-data`) or type families (`image/*`).
pub blocked: Vec<String>,
}
/// MIME media type tokens use the HTTP tchar alphabet, excluding `*` here;
/// `type/*` is the only accepted wildcard form in configured patterns.
fn mime_token(value: &str) -> bool {
!value.is_empty()
&& value.len() <= 127
&& value
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || b"!#$%&'+-.^_`|~".contains(&byte))
}
impl ContentTypePolicy {
pub fn validate(&mut self) -> Result<()> {
ensure!(
self.blocked.len() <= 64,
"Content-Type policy allows at most 64 blocked media types"
);
let mut seen = std::collections::HashSet::new();
for value in &mut self.blocked {
*value = value.trim().to_ascii_lowercase();
let Some((kind, subtype)) = value.split_once('/') else {
anyhow::bail!("invalid blocked Content-Type: expected type/subtype");
};
ensure!(
mime_token(kind)
&& (subtype == "*" || mime_token(subtype))
&& value.len() <= 255,
"invalid blocked Content-Type: use type/subtype or type/* without parameters"
);
ensure!(
seen.insert(value.clone()),
"duplicate blocked Content-Type in policy"
);
}
ensure!(
!self.enabled || !self.blocked.is_empty(),
"enabled Content-Type policy requires at least one blocked media type"
);
Ok(())
}
/// Reject matching media types before body parsing, upstream routing, and cache lookup.
/// Multiple or malformed Content-Type values are ambiguous, so reject them
/// when filtering is enabled rather than let the backend interpret them differently.
/// An absent Content-Type header is not matched (the policy is not a body WAF).
pub fn blocks(&self, headers: &http::HeaderMap) -> bool {
if !self.enabled {
return false;
}
let mut values = headers.get_all(http::header::CONTENT_TYPE).iter();
let Some(raw) = values.next() else {
return false;
};
if values.next().is_some() {
return true;
}
let Ok(raw) = raw.to_str() else {
return true;
};
// A comma outside a quoted parameter indicates a combined/ambiguous
// header. RFC MIME parameters may legitimately contain quoted commas.
let mut quoted = false;
let mut escaped = false;
for byte in raw.bytes() {
if escaped {
escaped = false;
} else if quoted && byte == b'\\' {
escaped = true;
} else if byte == b'"' {
quoted = !quoted;
} else if byte == b',' && !quoted {
return true;
}
}
if quoted || escaped {
return true;
}
let media_type = raw.split(';').next().unwrap_or("").trim();
let Some((kind, subtype)) = media_type.split_once('/') else {
return true;
};
if !mime_token(kind) || !mime_token(subtype) {
return true;
}
self.blocked.iter().any(|blocked| {
if let Some(prefix) = blocked.strip_suffix("/*") {
kind.eq_ignore_ascii_case(prefix)
} else {
media_type.eq_ignore_ascii_case(blocked)
}
})
}
}
impl ProxyTimeouts {
pub fn validate(&self) -> Result<()> {
for (name, value, max) in [
@@ -248,6 +351,9 @@ pub struct Vhost {
/// Optional allow/block policy for HTTP methods. Vhost and location policies stack.
#[serde(default)]
pub method_policy: MethodPolicy,
/// Optional request Content-Type denylist (normal vhosts only in the panel).
#[serde(default)]
pub content_type_policy: ContentTypePolicy,
#[serde(default)]
pub basic_auth: crate::basic_auth::Settings,
pub id: String,
+52
View File
@@ -82,6 +82,58 @@ mod default_listener_tests {
);
}
#[test]
fn content_type_policy_defaults_off_and_normalizes_exact_and_wildcard_types() {
let old: ContentTypePolicy = serde_json::from_value(json!({})).unwrap();
assert!(!old.enabled);
assert!(!old.blocks(&http::HeaderMap::new()));
let mut policy: ContentTypePolicy = serde_json::from_value(json!({
"enabled": true, "blocked": [" Multipart/Form-Data ", "IMAGE/*", "application/problem+json"]
})).unwrap();
policy.validate().unwrap();
assert_eq!(policy.blocked, vec!["multipart/form-data", "image/*", "application/problem+json"]);
let header = |value: &'static str| {
let mut map = http::HeaderMap::new();
map.insert(http::header::CONTENT_TYPE, http::HeaderValue::from_static(value));
map
};
assert!(policy.blocks(&header("MULTIPART/FORM-DATA; boundary=abc123")));
assert!(policy.blocks(&header("multipart/form-data;charset=utf-8")));
assert!(policy.blocks(&header("multipart/form-data; boundary=\"a,b\"")));
assert!(policy.blocks(&header("image/png")));
assert!(policy.blocks(&header("application/problem+json")));
assert!(!policy.blocks(&header("application/json; charset=utf-8")));
assert!(!policy.blocks(&header("application/json; profile=\"a,b\"")));
assert!(policy.blocks(&header("application/json; profile=unquoted,second")));
assert!(policy.blocks(&header("application/json; profile=\"unterminated")));
assert!(!policy.blocks(&header("text/plain")));
assert!(!policy.blocks(&http::HeaderMap::new()));
let mut double = header("application/json");
double.append(http::header::CONTENT_TYPE, http::HeaderValue::from_static("multipart/form-data"));
assert!(policy.blocks(&double));
assert!(policy.blocks(&header("application/json, multipart/form-data")));
assert!(policy.blocks(&header("application/json / text")));
policy.enabled = false;
assert!(!policy.blocks(&header("multipart/form-data")));
assert!(!policy.blocks(&double));
}
#[test]
fn content_type_policy_rejects_invalid_entries_and_empty_enabled_policy() {
for entry in ["multipart", "*/form-data", "image/p*", "text/plain; charset=utf-8", "a/", "a//b", "image /png"] {
let mut policy = ContentTypePolicy { enabled: true, blocked: vec![entry.into()] };
assert!(policy.validate().is_err(), "accepted invalid pattern {entry}");
}
let mut empty = ContentTypePolicy { enabled: true, blocked: vec![] };
assert!(empty.validate().is_err());
let mut duplicate = ContentTypePolicy { enabled: true, blocked: vec!["TEXT/PLAIN".into(), " text/plain ".into()] };
assert!(duplicate.validate().is_err());
let mut many = ContentTypePolicy { enabled: true, blocked: vec!["text/plain".into(); 65] };
assert!(many.validate().is_err());
}
#[test]
fn method_policy_normalizes_and_enforces_allow_and_block_modes() {
let mut allow: MethodPolicy = serde_json::from_value(json!({
+1
View File
@@ -99,6 +99,7 @@ impl Vhost {
"certificate mismatch override requires an explicitly selected certificate"
);
self.method_policy.validate()?;
self.content_type_policy.validate()?;
ensure!(
!self.frontend.listener_ids.is_empty(),
"vhost requires at least one named listener"