Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

fix(headers): respect quoted strings when splitting header parameters

Athul Nambiareeb2ae6179e0
diff --git a/Cargo.lock b/Cargo.lock
index 649df7810..beeb9ab30 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2139,6 +2139,7 @@ version = "0.1.0"
dependencies = [
"encoding_rs",
"moli-charset-parser",
+ "moli-header-field",
]
[[package]]
@@ -2209,6 +2210,7 @@ version = "0.1.0"
dependencies = [
"anyhow",
"httpdate",
+ "moli-header-field",
"rustc-hash",
"serde",
"serde_json",
@@ -2385,7 +2387,6 @@ dependencies = [
"axum",
"base64 0.22.1",
"chromiumoxide_cdp",
- "content_disposition",
"data-url",
"http",
"indexmap",
@@ -2397,6 +2398,7 @@ dependencies = [
"moli-css-parse",
"moli-encoding",
"moli-fetch",
+ "moli-header-field",
"moli-image",
"moli-page-types",
"moli-protocol-cdp",
diff --git a/moli-encoding/Cargo.toml b/moli-encoding/Cargo.toml
index d4b8edf0d..2a49e0f20 100644
--- a/moli-encoding/Cargo.toml
+++ b/moli-encoding/Cargo.toml
@@ -7,6 +7,7 @@ edition = "2024"
[dependencies]
encoding_rs = "0.8"
moli-charset-parser = { path = "../moli-charset-parser" }
+moli-header-field = { path = "../moli-header-field" }
[lints]
workspace = true
diff --git a/moli-encoding/src/labels.rs b/moli-encoding/src/labels.rs
index f0a6df86f..99973bac1 100644
--- a/moli-encoding/src/labels.rs
+++ b/moli-encoding/src/labels.rs
@@ -1,24 +1,39 @@
use encoding_rs::Encoding;
+use moli_header_field::{split_outside_quoted_strings, unquote_parameter_value};
pub fn encoding_for_label(label: &str) -> Option<&'static Encoding> {
Encoding::for_label(label.trim().as_bytes())
}
+/// The `charset` parameter of a `Content-Type` value.
+///
+/// Parameters are separated by the `;` characters outside a quoted string, and
+/// a quoted value has its quoting backslashes removed, so a `charset` written
+/// inside another parameter's quoted string is not read as a parameter here.
pub fn charset_from_content_type(value: &str) -> Option<String> {
- for parameter in value.split(';').skip(1) {
- let parameter = parameter.trim();
- let Some((name, value)) = parameter.split_once('=') else {
+ // The first segment is the media type itself, not a parameter.
+ for parameter in split_outside_quoted_strings(value, ';').into_iter().skip(1) {
+ let Some((name, parameter_value)) = parameter.split_once('=') else {
continue;
};
if !name.trim().eq_ignore_ascii_case("charset") {
continue;
}
- let value = value
- .trim()
- .trim_matches(|ch| ch == '"' || ch == '\'')
- .trim();
- if !value.is_empty() {
- return Some(value.to_owned());
+ let parameter_value = parameter_value.trim();
+ let charset = if parameter_value.starts_with('"') {
+ // Delimiters are already gone, so any `"` left is data produced by
+ // an escaped quote and must not be trimmed away.
+ unquote_parameter_value(parameter_value).into_owned()
+ } else {
+ // Apostrophe delimiters are not a quoted string, but receivers
+ // have long tolerated them here, so keep stripping them.
+ parameter_value
+ .trim_matches(|ch| ch == '"' || ch == '\'')
+ .trim()
+ .to_owned()
+ };
+ if !charset.is_empty() {
+ return Some(charset);
}
}
None
diff --git a/moli-encoding/src/tests.rs b/moli-encoding/src/tests.rs
index 91c4b7bf1..d305a0b29 100644
--- a/moli-encoding/src/tests.rs
+++ b/moli-encoding/src/tests.rs
@@ -665,3 +665,92 @@ fn bom_less_utf16be_truncated_not_detected() {
assert_eq!(encoding, "windows-1252");
assert_eq!(text, "\0<\0?");
}
+
+#[test]
+fn header_charset_stays_inside_another_parameters_quoted_string() {
+ assert_eq!(
+ charset_from_content_type("text/html; boundary=\"; charset=gbk\""),
+ None
+ );
+ let headers = vec![(
+ "Content-Type".to_owned(),
+ "text/html; boundary=\"; charset=gbk\"".to_owned(),
+ )];
+ assert_eq!(
+ decode_html_document(b"<p>hi</p>", &headers).1,
+ "windows-1252"
+ );
+}
+
+#[test]
+fn header_charset_is_not_displaced_by_an_escaped_quote() {
+ assert_eq!(
+ charset_from_content_type("text/html; name=\"a\\\"; charset=gbk\"; charset=utf-8")
+ .as_deref(),
+ Some("utf-8")
+ );
+}
+
+#[test]
+fn header_charset_removes_quoting_backslashes() {
+ assert_eq!(
+ charset_from_content_type("text/html; charset=\"utf\\-8\"").as_deref(),
+ Some("utf-8")
+ );
+ let headers = vec![(
+ "Content-Type".to_owned(),
+ "text/html; charset=\"utf\\-8\"".to_owned(),
+ )];
+ assert_eq!(decode_html_document(b"<p>hi</p>", &headers).1, "UTF-8");
+}
+
+#[test]
+fn header_charset_keeps_its_existing_tolerances() {
+ for header in [
+ "text/html; charset=utf-8",
+ "text/html;charset=utf-8",
+ "TEXT/HTML; CHARSET=UTF-8",
+ "text/html; charset = utf-8 ",
+ "text/html; charset=\"utf-8\"",
+ "text/html;charset=utf-8;",
+ "text/html; charset='utf-8'",
+ "text/html; charset=\"utf-8",
+ ] {
+ assert_eq!(
+ charset_from_content_type(header)
+ .as_deref()
+ .and_then(encoding_for_label)
+ .map(Encoding::name),
+ Some("UTF-8"),
+ "header={header}"
+ );
+ }
+ assert_eq!(charset_from_content_type("text/html"), None);
+ assert_eq!(charset_from_content_type("text/html; charset="), None);
+ assert_eq!(charset_from_content_type("charset=utf-8"), None);
+ assert_eq!(
+ charset_from_content_type("text/html; charset=gbk; boundary=x").as_deref(),
+ Some("gbk")
+ );
+}
+
+#[test]
+fn header_charset_recovers_after_a_stray_quote() {
+ // WPT MIME case: the `"` does not open a parameter value, so the following
+ // `;` still separates parameters and the real charset is found.
+ assert_eq!(
+ charset_from_content_type("text/html;\";charset=gbk").as_deref(),
+ Some("gbk")
+ );
+}
+
+#[test]
+fn header_charset_keeps_an_escaped_quote_as_data() {
+ // The quoted value is `utf-8"`, which is not a valid label. Trimming the
+ // data quote would manufacture a valid one.
+ let label = charset_from_content_type("text/html; charset=\"utf-8\\\"\"")
+ .expect("a parameter value is present");
+
+ assert_eq!(label, "utf-8\"");
+ assert!(encoding_for_label(&label).is_none());
+}
diff --git a/moli-header-field/src/lib.rs b/moli-header-field/src/lib.rs
index c909e2561..cfd0c91d0 100644
--- a/moli-header-field/src/lib.rs
+++ b/moli-header-field/src/lib.rs
@@ -10,8 +10,10 @@
//! also admits MIME `tspecials` other than space, semicolon, and quote, matching
//! Blink rather than defining another standards-compliance mode.
+mod parameters;
mod tokenizer;
+pub use parameters::{split_outside_quoted_strings, unquote_parameter_value};
pub use tokenizer::{HeaderFieldTokenMode, HeaderFieldTokenizer};
#[cfg(test)]
diff --git a/moli-header-field/src/parameters.rs b/moli-header-field/src/parameters.rs
new file mode 100644
index 000000000..436955dcb
--- /dev/null
+++ b/moli-header-field/src/parameters.rs
@@ -0,0 +1,93 @@
+use std::borrow::Cow;
+
+/// Splits `value` on every `separator` that is not inside a quoted parameter
+/// value.
+///
+/// Structured header field values carry their parameters after a separator —
+/// `;` after a media type, `,` between list members — but a quoted value may
+/// contain that separator without ending the parameter it belongs to. Plain
+/// splitting lets such a separator escape the quoted value, so text that is
+/// part of one parameter is read as a parameter of its own.
+///
+/// Quoting only begins where a parameter value begins, which is the first
+/// non-whitespace character after `=`. A `"` anywhere else is ordinary data
+/// and does not open a quoted string, so a stray quote cannot swallow the rest
+/// of the field and hide the parameters behind it.
+///
+/// `separator` must be an ASCII character. A UTF-8 continuation byte can never
+/// equal one, so every returned slice falls on a character boundary.
+pub fn split_outside_quoted_strings(value: &str, separator: char) -> Vec<&str> {
+ debug_assert!(
+ separator.is_ascii(),
+ "a non-ASCII separator cannot be matched bytewise"
+ );
+ let separator = separator as u8;
+ let bytes = value.as_bytes();
+ let mut segments = Vec::new();
+ let mut segment_start = 0;
+ let mut at_value_start = false;
+ let mut inside_quotes = false;
+ let mut index = 0;
+
+ while index < bytes.len() {
+ let byte = bytes[index];
+
+ if inside_quotes {
+ if byte == b'\\' {
+ // Step over the escaped byte so a quoted `\"` does not close
+ // the value.
+ index += 2;
+ continue;
+ }
+ if byte == b'"' {
+ inside_quotes = false;
+ }
+ index += 1;
+ continue;
+ }
+
+ if byte == separator {
+ segments.push(&value[segment_start..index]);
+ segment_start = index + 1;
+ at_value_start = false;
+ } else if byte == b'=' {
+ at_value_start = true;
+ } else if byte == b'"' && at_value_start {
+ inside_quotes = true;
+ at_value_start = false;
+ } else if !matches!(byte, b' ' | b'\t') || !at_value_start {
+ // Whitespace between `=` and the value keeps the value still to
+ // come; anything else means the value was not quoted.
+ at_value_start = false;
+ }
+ index += 1;
+ }
+
+ segments.push(&value[segment_start.min(value.len())..]);
+ segments
+}
+
+/// Removes a quoted value's delimiters and its quoting backslashes.
+///
+/// A value that is not quoted is returned as-is. An unterminated quoted value
+/// yields everything that was read rather than discarding the parameter, and a
+/// trailing `\` with nothing to escape is kept, so a malformed value is not
+/// quietly turned into a well-formed one.
+pub fn unquote_parameter_value(raw: &str) -> Cow<'_, str> {
+ let Some(quoted) = raw.strip_prefix('"') else {
+ return Cow::Borrowed(raw);
+ };
+ let mut unquoted = String::with_capacity(quoted.len());
+ let mut characters = quoted.chars();
+ while let Some(character) = characters.next() {
+ match character {
+ '"' => return Cow::Owned(unquoted),
+ '\\' => match characters.next() {
+ Some(escaped) => unquoted.push(escaped),
+ None => unquoted.push('\\'),
+ },
+ _ => unquoted.push(character),
+ }
+ }
+ Cow::Owned(unquoted)
+}
diff --git a/moli-header-field/src/tests.rs b/moli-header-field/src/tests.rs
index 948c1ef8a..75fd6ec7e 100644
--- a/moli-header-field/src/tests.rs
+++ b/moli-header-field/src/tests.rs
@@ -122,3 +122,105 @@ fn consume_before_any_match_stops_without_consuming_the_separator() {
Some("beta")
);
}
+
+#[test]
+fn separators_inside_a_quoted_string_do_not_split() {
+ assert_eq!(
+ split_outside_quoted_strings("text/html; boundary=\"; charset=gbk\"", ';'),
+ vec!["text/html", " boundary=\"; charset=gbk\""]
+ );
+ assert_eq!(
+ split_outside_quoted_strings("private=\"Set-Cookie, X-Auth\", max-age=60", ','),
+ vec!["private=\"Set-Cookie, X-Auth\"", " max-age=60"]
+ );
+}
+
+#[test]
+fn an_escaped_quote_does_not_close_a_quoted_string() {
+ assert_eq!(
+ split_outside_quoted_strings("attachment; name=\"a\\\"; x=1\"; y=2", ';'),
+ vec!["attachment", " name=\"a\\\"; x=1\"", " y=2"]
+ );
+}
+
+#[test]
+fn splitting_without_quotes_matches_a_plain_split() {
+ for value in [
+ "text/html; charset=utf-8",
+ "a;b;c",
+ "",
+ ";",
+ "trailing;",
+ ";leading",
+ ] {
+ assert_eq!(
+ split_outside_quoted_strings(value, ';'),
+ value.split(';').collect::<Vec<_>>(),
+ "value={value}"
+ );
+ }
+}
+
+#[test]
+fn an_unterminated_quoted_string_runs_to_the_end() {
+ assert_eq!(
+ split_outside_quoted_strings("text/html; charset=\"gbk; q=1", ';'),
+ vec!["text/html", " charset=\"gbk; q=1"]
+ );
+}
+
+#[test]
+fn quoted_values_lose_their_delimiters_and_backslashes() {
+ assert_eq!(unquote_parameter_value("\"utf-8\""), "utf-8");
+ assert_eq!(unquote_parameter_value("\"utf\\-8\""), "utf-8");
+ assert_eq!(unquote_parameter_value("\"a\\\"b\""), "a\"b");
+ // Not a quoted string, so it is returned untouched.
+ assert_eq!(unquote_parameter_value("utf-8"), "utf-8");
+ assert_eq!(unquote_parameter_value("'utf-8'"), "'utf-8'");
+ // Unterminated keeps what was read.
+ assert_eq!(unquote_parameter_value("\"gbk"), "gbk");
+}
+
+#[test]
+fn multibyte_values_keep_character_boundaries() {
+ let value = "text/plain; name=\"café; x\"; charset=utf-8";
+ assert_eq!(
+ split_outside_quoted_strings(value, ';'),
+ vec!["text/plain", " name=\"café; x\"", " charset=utf-8"]
+ );
+ assert_eq!(unquote_parameter_value("\"caf\\é\""), "café");
+}
+
+#[test]
+fn a_quote_outside_a_parameter_value_is_ordinary_data() {
+ // A `"` that does not open a parameter value must not swallow the rest of
+ // the field, or the parameters behind it become invisible.
+ assert_eq!(
+ split_outside_quoted_strings("text/html;\";charset=gbk", ';'),
+ vec!["text/html", "\"", "charset=gbk"]
+ );
+ assert_eq!(
+ split_outside_quoted_strings("a\"b;c", ';'),
+ vec!["a\"b", "c"]
+ );
+}
+
+#[test]
+fn whitespace_between_equals_and_a_quoted_value_still_opens_it() {
+ assert_eq!(
+ split_outside_quoted_strings("text/html; boundary = \"; x\"; charset=utf-8", ';'),
+ vec!["text/html", " boundary = \"; x\"", " charset=utf-8"]
+ );
+}
+
+#[test]
+fn a_trailing_backslash_is_kept_rather_than_dropped() {
+ // Dropping it would turn a malformed value into a well-formed one.
+ assert_eq!(unquote_parameter_value("\"31536000\\"), "31536000\\");
+ assert_eq!(unquote_parameter_value("\"a\\"), "a\\");
+}
+
+#[test]
+fn an_escaped_quote_survives_as_data() {
+ assert_eq!(unquote_parameter_value("\"utf-8\\\"\""), "utf-8\"");
+}
diff --git a/moli-http-cache/Cargo.toml b/moli-http-cache/Cargo.toml
index 594c9f80e..bd125a894 100644
--- a/moli-http-cache/Cargo.toml
+++ b/moli-http-cache/Cargo.toml
@@ -7,6 +7,7 @@ edition = "2024"
[dependencies]
anyhow = "1.0.100"
httpdate = "1.0.3"
+moli-header-field = { path = "../moli-header-field" }
serde = { version = "1.0.228", features = ["derive"] }
serde_json = "1.0.145"
rustc-hash = "2.1.1"
diff --git a/moli-http-cache/src/policy.rs b/moli-http-cache/src/policy.rs
index 972a54cfd..bcf027e08 100644
--- a/moli-http-cache/src/policy.rs
+++ b/moli-http-cache/src/policy.rs
@@ -1,4 +1,5 @@
use httpdate::parse_http_date;
+use moli_header_field::{split_outside_quoted_strings, unquote_parameter_value};
use url::Url;
/// Cache storage and freshness policy derived from response headers.
@@ -20,11 +21,18 @@ pub fn response_cache_policy(headers: &[(String, String)]) -> HttpCacheResponseP
for (name, value) in headers {
if name.eq_ignore_ascii_case("cache-control") {
- for directive in value.split(',').map(str::trim) {
+ // A quoted directive argument may contain `,`, as in
+ // `private="Set-Cookie, X-Auth"`, so splitting on every comma
+ // would read the argument's own text as further directives.
+ for directive in split_outside_quoted_strings(value, ',')
+ .into_iter()
+ .map(str::trim)
+ {
let (directive_name, directive_value) = directive
.split_once('=')
- .map(|(name, value)| (name.trim(), Some(value.trim().trim_matches('"'))))
+ .map(|(name, value)| (name.trim(), Some(unquote_parameter_value(value.trim()))))
.unwrap_or((directive, None));
+ let directive_value = directive_value.as_deref();
if directive_name.eq_ignore_ascii_case("no-store")
|| directive_name.eq_ignore_ascii_case("private")
{
@@ -139,7 +147,7 @@ fn cached_response_is_fresh_immutable_at(
&& headers
.iter()
.filter(|(name, _)| name.eq_ignore_ascii_case("cache-control"))
- .flat_map(|(_, value)| value.split(','))
+ .flat_map(|(_, value)| split_outside_quoted_strings(value, ','))
.map(str::trim)
.any(|directive| {
directive
@@ -161,19 +169,22 @@ pub fn request_header_requires_validation(name: &str, value: &str) -> bool {
}
pub fn request_cache_control_requires_validation(value: &str) -> bool {
- value.split(',').map(str::trim).any(|directive| {
- let (name, value) = directive
- .split_once('=')
- .map(|(name, value)| (name.trim(), Some(value.trim().trim_matches('"'))))
- .unwrap_or((directive, None));
- name.eq_ignore_ascii_case("no-cache")
- || (name.eq_ignore_ascii_case("max-age") && value == Some("0"))
- })
+ split_outside_quoted_strings(value, ',')
+ .into_iter()
+ .map(str::trim)
+ .any(|directive| {
+ let (name, value) = directive
+ .split_once('=')
+ .map(|(name, value)| (name.trim(), Some(unquote_parameter_value(value.trim()))))
+ .unwrap_or((directive, None));
+ name.eq_ignore_ascii_case("no-cache")
+ || (name.eq_ignore_ascii_case("max-age") && value.as_deref() == Some("0"))
+ })
}
pub fn request_pragma_requires_validation(value: &str) -> bool {
- value
- .split(',')
+ split_outside_quoted_strings(value, ',')
+ .into_iter()
.map(str::trim)
.any(|directive| directive.eq_ignore_ascii_case("no-cache"))
}
@@ -230,4 +241,69 @@ mod tests {
Some(100)
));
}
+
+ #[test]
+ fn quoted_directive_arguments_do_not_leak_further_directives() {
+ // RFC 9111 lets `private` and `no-cache` carry a quoted field list,
+ // and that list may contain commas. Splitting on every comma read the
+ // list's own text as further directives.
+ assert!(!request_cache_control_requires_validation(
+ "max-age=600, private=\"Set-Cookie, X-Auth\""
+ ));
+ assert!(request_cache_control_requires_validation(
+ "max-age=600, no-cache=\"Set-Cookie, X-Auth\""
+ ));
+ // A directive name appearing inside a quoted argument is not a
+ // directive of its own.
+ assert!(!request_cache_control_requires_validation(
+ "max-age=600, private=\"a, no-cache, b\""
+ ));
+ }
+
+ #[test]
+ fn response_policy_ignores_directives_inside_a_quoted_argument() {
+ let headers = vec![(
+ "Cache-Control".to_owned(),
+ "max-age=600, community=\"x, no-store, y\"".to_owned(),
+ )];
+
+ assert!(response_cache_policy(&headers).store);
+ }
+
+ #[test]
+ fn response_policy_still_honours_real_directives() {
+ for value in [
+ "no-store",
+ "private",
+ "max-age=0, no-store",
+ "no-store, max-age=600",
+ ] {
+ let headers = vec![("Cache-Control".to_owned(), value.to_owned())];
+ assert!(!response_cache_policy(&headers).store, "value={value}");
+ }
+ let headers = vec![(
+ "Cache-Control".to_owned(),
+ "private=\"Set-Cookie\"".to_owned(),
+ )];
+ assert!(!response_cache_policy(&headers).store);
+ }
+
+ #[test]
+ fn quoted_pragma_arguments_do_not_leak_directives() {
+ assert!(!request_pragma_requires_validation(
+ "token=\"a, no-cache, b\""
+ ));
+ assert!(request_pragma_requires_validation("no-cache"));
+ }
+
+ #[test]
+ fn a_trailing_backslash_does_not_manufacture_a_freshness_lifetime() {
+ // `31536000\` is malformed and must not parse as one year.
+ let headers = vec![(
+ "Cache-Control".to_owned(),
+ "max-age=\"31536000\\".to_owned(),
+ )];
+
+ assert_eq!(response_cache_policy(&headers).expires_at_unix_ms, None);
+ }
}
diff --git a/moli-protocol/Cargo.toml b/moli-protocol/Cargo.toml
index 2c7e2691d..26c5269d7 100644
--- a/moli-protocol/Cargo.toml
+++ b/moli-protocol/Cargo.toml
@@ -14,6 +14,7 @@ base64 = "0.22"
indexmap = "2.6"
moli-bounded-buffer = { path = "../moli-bounded-buffer" }
moli-core = { path = "../moli-core" }
+moli-header-field = { path = "../moli-header-field" }
moli-page-types = { path = "../moli-page-types" }
moli-browser-profile = { path = "../moli-browser-profile" }
moli-cookie-jar = { path = "../moli-cookie-jar" }
@@ -42,7 +43,6 @@ v8 = "146.8.0"
time = "0.3"
chromiumoxide_cdp = "0.9.1"
data-url = "0.3.2"
-content_disposition = "0.4.0"
moli-crypto = { path = "../moli-crypto" }
http = "1"
sanitize-filename = "=0.6.0"
diff --git a/moli-protocol/src/conn/downloads.rs b/moli-protocol/src/conn/downloads.rs
index c593a604a..a94886cb7 100644
--- a/moli-protocol/src/conn/downloads.rs
+++ b/moli-protocol/src/conn/downloads.rs
@@ -6,11 +6,11 @@ use std::{
sync::Arc,
};
-use content_disposition::parse_content_disposition;
use http::HeaderName;
use moli_core::network::ResourceRequestClient;
use moli_core::page::RendererPendingDownloadActivation;
use moli_fetch::{FetchCancelHandle, Request};
+use moli_header_field::{split_outside_quoted_strings, unquote_parameter_value};
use moli_web_mime::response_headers_indicate_attachment_download;
use parking_lot::Mutex;
use sanitize_filename::Options;
@@ -1373,36 +1373,47 @@ fn filename_from_headers(headers: &[(String, String)]) -> Option<String> {
}
fn filename_from_content_disposition(value: &str) -> Option<String> {
+ let mut plain = None;
let mut extended = None;
let mut saw_extended = false;
- let mut saw_plain = false;
- for part in value.split(';').skip(1) {
+ // A `;` inside a quoted string does not start a new parameter. Splitting on
+ // every `;` let text inside a quoted `filename` be read as a parameter of
+ // its own, so a site that echoes an attacker-supplied name into the header
+ // could smuggle a `filename*` and choose the extension the file is saved
+ // under.
+ for part in split_outside_quoted_strings(value, ';').into_iter().skip(1) {
let part = part.trim();
- if let Some(raw) = part.strip_prefix("filename*=") {
+ if let Some(raw) = strip_parameter_name(part, "filename*") {
saw_extended = true;
extended = decode_extended_filename(raw);
- continue;
- }
- if part.strip_prefix("filename=").is_some() {
- saw_plain = true;
+ } else if let Some(raw) = strip_parameter_name(part, "filename") {
+ plain = Some(unquote_parameter_value(raw.trim()).into_owned());
}
}
if extended.is_some() {
return extended;
}
- if saw_extended && !saw_plain {
+ if saw_extended && plain.is_none() {
return None;
}
- parse_content_disposition(value)
- .params
- .get("filename")
- .and_then(|filename| non_empty_filename(filename))
+ plain
+ .as_deref()
+ .and_then(non_empty_filename)
.map(sanitize_filename)
}
+/// Strips a case-insensitive `name=` prefix from one parameter.
+fn strip_parameter_name<'a>(part: &'a str, name: &str) -> Option<&'a str> {
+ let rest = part
+ .get(..name.len())?
+ .eq_ignore_ascii_case(name)
+ .then(|| &part[name.len()..])?;
+ rest.trim_start().strip_prefix('=')
+}
+
fn decode_extended_filename(raw: &str) -> Option<String> {
let raw = raw.trim().trim_matches('"');
let mut parts = raw.splitn(3, '\'');
@@ -1877,6 +1888,31 @@ mod tests {
);
}
+ #[test]
+ fn content_disposition_ignores_filename_star_inside_a_quoted_filename() {
+ // RFC 6266: the whole quoted string is the `filename` value, and there
+ // is no `filename*` parameter here at all. Reading the inner text as
+ // one let a site that echoes an attacker-supplied name into the header
+ // choose the extension the file is saved under.
+ let filename = filename_from_content_disposition(
+ "attachment; filename=\"a;filename*=UTF-8''evil.exe\"",
+ );
+
+ // The saved name is the quoted string itself, with `*` removed by
+ // the Windows-safe sanitizer rather than by the parameter scan.
+ assert_ne!(filename.as_deref(), Some("evil.exe"));
+ assert_eq!(filename.as_deref(), Some("a;filename=UTF-8''evil.exe"));
+ }
+
+ #[test]
+ fn content_disposition_still_reads_a_real_filename_star_after_a_quoted_filename() {
+ let filename = filename_from_content_disposition(
+ "attachment; filename=\"plain;name.txt\"; filename*=UTF-8''%E4%B8%AD%E6%96%87.txt",
+ );
+
+ assert_eq!(filename.as_deref(), Some("中文.txt"));
+ }
+
#[test]
fn content_disposition_prefers_filename_star_when_present() {
let filename = filename_from_content_disposition(