From 10131f29adea9a2047f2c364a078914c77dae5b0 Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 02:11:45 -0600 Subject: [PATCH 1/5] fix(id): verify uploaded bytes against the declared image type (#5342) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit upload_handler trusted the multipart field's declared Content-Type: any bytes could be stored and served as an image of the declared type (probe: HTML declared image/png stored as evil.png and served as image/png). Verify the bytes before storing — magic signatures for png/jpeg/gif/webp/bmp/ico, an SVG document check after optional BOM/whitespace/XML prolog for image/svg+xml — and refuse mismatches with 400, storing nothing. The check runs after the existing size/empty checks so the #716 413 responses keep precedence. Existing upload fixtures now carry real PNG headers; new tests cover the probe case, mismatches for other declared types, and real headers for every allowed type. --- pkgs/id/src/web/routes.rs | 240 +++++++++++++++++++++++++++++++++++--- 1 file changed, 223 insertions(+), 17 deletions(-) diff --git a/pkgs/id/src/web/routes.rs b/pkgs/id/src/web/routes.rs index 808fa64445..2e69d0baef 100644 --- a/pkgs/id/src/web/routes.rs +++ b/pkgs/id/src/web/routes.rs @@ -80,6 +80,61 @@ fn mime_to_extension(mime: &str) -> &'static str { } } +/// Verify that uploaded bytes actually look like the image type the +/// multipart field declared (#5342). Before this check, `upload_handler` +/// trusted the declared Content-Type alone, so any bytes (HTML, script, +/// plain text) could be stored — and later served — as an image of the +/// declared type. Raster formats are recognised by their magic +/// signatures; SVG is text, so it is checked structurally by +/// [`svg_document_starts`]. This is a signature check, not a full format +/// decode: it stops type masquerading, it does not prove the rest of +/// the file is well-formed. +fn image_bytes_match_declared_type(content_type: &str, data: &[u8]) -> bool { + match content_type { + "image/png" => data.starts_with(&[0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A]), + "image/jpeg" => data.starts_with(&[0xFF, 0xD8, 0xFF]), + "image/gif" => data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a"), + "image/webp" => data.len() >= 12 && &data[0..4] == b"RIFF" && &data[8..12] == b"WEBP", + "image/bmp" => data.starts_with(b"BM"), + // ICO (type 1) and CUR (type 2) share the container header. + "image/x-icon" => { + data.starts_with(&[0x00, 0x00, 0x01, 0x00]) + || data.starts_with(&[0x00, 0x00, 0x02, 0x00]) + } + "image/svg+xml" => svg_document_starts(data), + _ => false, + } +} + +/// Whether `data` is an SVG document: after an optional UTF-8 BOM, +/// leading whitespace, and an optional `` prolog, the +/// document must open with an ` bool { + let mut rest = data; + if rest.starts_with(&[0xEF, 0xBB, 0xBF]) { + rest = &rest[3..]; + } + loop { + while rest.first().is_some_and(u8::is_ascii_whitespace) { + rest = &rest[1..]; + } + if rest.starts_with(b"") { + Some(end) => { + rest = &rest[end + 2..]; + continue; + } + None => return false, + } + } + break; + } + rest.starts_with(b"' || *b == b'/') +} + /// Query parameters for the file list (pagination + search). #[derive(Debug, Deserialize, Default)] pub struct FileListQuery { @@ -1825,6 +1880,18 @@ async fn upload_handler(State(state): State, mut multipart: Multipart) return (StatusCode::BAD_REQUEST, "Uploaded file is empty").into_response(); } + // #5342: the declared Content-Type above is caller-asserted; verify + // the bytes themselves carry that type's signature before storing, + // so the stored name/type metadata cannot claim a format the + // content does not have. A mismatch stores and tags nothing. + if !image_bytes_match_declared_type(&content_type, &data) { + return ( + StatusCode::BAD_REQUEST, + format!("Uploaded bytes do not match the declared image type: {content_type}"), + ) + .into_response(); + } + tracing::info!( "[routes] upload_handler: name={}, content_type={}, size={}", filename, @@ -2932,7 +2999,10 @@ mod upload_router_tests { let guard = state.upload_name_lock.lock().await; let barrier = Arc::new(tokio::sync::Barrier::new(3)); let mut tasks = Vec::new(); - for bytes in [b"first-bytes".as_slice(), b"second-bytes".as_slice()] { + for bytes in [ + b"\x89PNG\r\n\x1a\nfirst-bytes".as_slice(), + b"\x89PNG\r\n\x1a\nsecond-bytes".as_slice(), + ] { let router = router.clone(); let barrier = barrier.clone(); let body = multipart_body_named("image.png", "image/png", bytes); @@ -2958,10 +3028,10 @@ mod upload_router_tests { assert_ne!(images[0]["name"], images[1]["name"]); assert_ne!(images[0]["hash"], images[1]["hash"]); let listed = list_images(router.clone()).await; - for (image, bytes) in images - .iter() - .zip([b"first-bytes".as_slice(), b"second-bytes".as_slice()]) - { + for (image, bytes) in images.iter().zip([ + b"\x89PNG\r\n\x1a\nfirst-bytes".as_slice(), + b"\x89PNG\r\n\x1a\nsecond-bytes".as_slice(), + ]) { let name = image["name"].as_str().unwrap(); let hash = image["hash"].as_str().unwrap(); assert_eq!( @@ -3018,7 +3088,7 @@ mod upload_router_tests { let (router, _dir, _endpoint, _docs) = router().await; let (status, first) = upload( router.clone(), - multipart_body_named("image.png", "image/png", b"first-bytes"), + multipart_body_named("image.png", "image/png", b"\x89PNG\r\n\x1a\nfirst-bytes"), ) .await; assert_eq!(status, StatusCode::OK, "body: {first}"); @@ -3027,7 +3097,7 @@ mod upload_router_tests { let (status, second) = upload( router.clone(), - multipart_body_named("image.png", "image/png", b"second-bytes"), + multipart_body_named("image.png", "image/png", b"\x89PNG\r\n\x1a\nsecond-bytes"), ) .await; assert_eq!(status, StatusCode::OK, "body: {second}"); @@ -3041,7 +3111,7 @@ mod upload_router_tests { let (status, again) = upload( router.clone(), - multipart_body_named("image.png", "image/png", b"first-bytes"), + multipart_body_named("image.png", "image/png", b"\x89PNG\r\n\x1a\nfirst-bytes"), ) .await; assert_eq!(status, StatusCode::OK, "body: {again}"); @@ -3062,9 +3132,9 @@ mod upload_router_tests { assert_eq!(by_name("image-1.png")["hash"], second_hash); let (_, _, bytes) = get_blob(router.clone(), &format!("/blob/{first_hash}")).await; - assert_eq!(bytes, b"first-bytes"); + assert_eq!(bytes, b"\x89PNG\r\n\x1a\nfirst-bytes"); let (_, _, bytes) = get_blob(router, &format!("/blob/{second_hash}")).await; - assert_eq!(bytes, b"second-bytes"); + assert_eq!(bytes, b"\x89PNG\r\n\x1a\nsecond-bytes"); } // #1549: the nameless paste-{secs} fallback passes through the @@ -3075,13 +3145,13 @@ mod upload_router_tests { let (router, _dir, _endpoint, _docs) = router().await; let (status, first) = upload( router.clone(), - multipart_body_noname("image/png", b"nameless-one"), + multipart_body_noname("image/png", b"\x89PNG\r\n\x1a\nnameless-one"), ) .await; assert_eq!(status, StatusCode::OK, "body: {first}"); let (status, second) = upload( router.clone(), - multipart_body_noname("image/png", b"nameless-two"), + multipart_body_noname("image/png", b"\x89PNG\r\n\x1a\nnameless-two"), ) .await; assert_eq!(status, StatusCode::OK, "body: {second}"); @@ -3127,7 +3197,8 @@ mod upload_router_tests { #[tokio::test] async fn upload_exactly_max_image_size_succeeds() { let (router, _dir, _endpoint, _docs) = router().await; - let file = vec![b'y'; MAX_IMAGE_SIZE]; + let mut file = b"\x89PNG\r\n\x1a\n".to_vec(); + file.resize(MAX_IMAGE_SIZE, b'y'); let (status, body) = upload(router, multipart_body(&file)).await; assert_eq!(status, StatusCode::OK, "body: {body}"); assert!(body.contains("\"name\":\"photo.png\""), "body: {body}"); @@ -3161,13 +3232,17 @@ mod upload_router_tests { #[tokio::test] async fn blob_html_filename_param_is_not_served_as_html() { let (router, _dir, _endpoint, _docs) = router().await; - let (status, body) = upload(router.clone(), multipart_body(b"png-bytes")).await; + let (status, body) = upload( + router.clone(), + multipart_body(b"\x89PNG\r\n\x1a\npng-bytes"), + ) + .await; assert_eq!(status, StatusCode::OK, "body: {body}"); let hash = uploaded_hash(&body); let (status, headers, bytes) = get_blob(router, &format!("/blob/{hash}?filename=evil.html")).await; assert_eq!(status, StatusCode::OK); - assert_eq!(bytes, b"png-bytes"); + assert_eq!(bytes, b"\x89PNG\r\n\x1a\npng-bytes"); assert_eq!( header_str(&headers, "content-type"), Some("application/octet-stream") @@ -3189,7 +3264,11 @@ mod upload_router_tests { #[tokio::test] async fn blob_png_is_served_inline_with_protective_headers() { let (router, _dir, _endpoint, _docs) = router().await; - let (status, body) = upload(router.clone(), multipart_body(b"png-bytes")).await; + let (status, body) = upload( + router.clone(), + multipart_body(b"\x89PNG\r\n\x1a\npng-bytes"), + ) + .await; assert_eq!(status, StatusCode::OK, "body: {body}"); let hash = uploaded_hash(&body); let (status, headers, _bytes) = @@ -3239,7 +3318,7 @@ mod upload_router_tests { let (router, _dir, _endpoint, _docs) = router().await; let (status, body) = upload( router, - multipart_body_named("evil.html", "image/png", b"png-bytes"), + multipart_body_named("evil.html", "image/png", b"\x89PNG\r\n\x1a\npng-bytes"), ) .await; assert_eq!(status, StatusCode::OK, "body: {body}"); @@ -3285,6 +3364,133 @@ mod upload_router_tests { "archive.tar.gif" ); } + + #[test] + fn image_bytes_match_declared_type_accepts_real_headers_and_rejects_masquerades() { + assert!(image_bytes_match_declared_type( + "image/png", + b"\x89PNG\r\n\x1a\nrest" + )); + assert!(image_bytes_match_declared_type( + "image/jpeg", + b"\xff\xd8\xff\xe0rest" + )); + assert!(image_bytes_match_declared_type("image/gif", b"GIF87a-rest")); + assert!(image_bytes_match_declared_type("image/gif", b"GIF89a-rest")); + assert!(image_bytes_match_declared_type( + "image/webp", + b"RIFF\x04\x00\x00\x00WEBPrest" + )); + assert!(image_bytes_match_declared_type("image/bmp", b"BM-rest")); + assert!(image_bytes_match_declared_type( + "image/x-icon", + b"\x00\x00\x01\x00rest" + )); + assert!(image_bytes_match_declared_type( + "image/svg+xml", + b"" + )); + assert!(image_bytes_match_declared_type( + "image/svg+xml", + b"\xef\xbb\xbf \n" + )); + assert!(!image_bytes_match_declared_type( + "image/png", + b"" + )); + assert!(!image_bytes_match_declared_type( + "image/jpeg", + b"plain text" + )); + assert!(!image_bytes_match_declared_type( + "image/svg+xml", + b"" + )); + assert!(!image_bytes_match_declared_type("image/png", b"")); + assert!(!image_bytes_match_declared_type( + "image/webp", + b"RIFF\x04\x00\x00\x00WAVErest" + )); + } + + // #5342 (the probe that filed the issue): HTML/script bytes declared + // image/png were accepted, stored, and served as a PNG. They must + // now be refused 400, and nothing may be stored or listed. + #[tokio::test] + async fn upload_html_declared_as_png_is_refused_and_stores_nothing() { + let (router, _dir, _endpoint, _docs) = router().await; + let (status, body) = upload( + router.clone(), + multipart_body_named( + "evil.png", + "image/png", + b"", + ), + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST, "body: {body}"); + assert!( + body.contains("do not match the declared image type"), + "body: {body}" + ); + assert!(list_images(router).await.is_empty()); + } + + #[tokio::test] + async fn upload_mismatched_bytes_are_refused_for_other_declared_types() { + let (router, _dir, _endpoint, _docs) = router().await; + for (name, content_type, bytes) in [ + ("photo.jpg", "image/jpeg", b"plain text".as_slice()), + ("icon.svg", "image/svg+xml", b"not an svg".as_slice()), + ( + "anim.gif", + "image/gif", + b"\x89PNG\r\n\x1a\nnot-a-gif".as_slice(), + ), + ( + "pic.webp", + "image/webp", + b"RIFF\x04\x00\x00\x00WAVErest".as_slice(), + ), + ] { + let (status, body) = upload( + router.clone(), + multipart_body_named(name, content_type, bytes), + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{content_type}: {body}"); + } + assert!(list_images(router).await.is_empty()); + } + + #[tokio::test] + async fn upload_real_headers_for_each_allowed_type_are_accepted() { + let (router, _dir, _endpoint, _docs) = router().await; + for (name, content_type, bytes) in [ + ("a.png", "image/png", b"\x89PNG\r\n\x1a\nx".as_slice()), + ("a.jpg", "image/jpeg", b"\xff\xd8\xff\xe0x".as_slice()), + ("a.gif", "image/gif", b"GIF89ax".as_slice()), + ( + "a.webp", + "image/webp", + b"RIFF\x04\x00\x00\x00WEBPx".as_slice(), + ), + ("a.bmp", "image/bmp", b"BMx".as_slice()), + ("a.ico", "image/x-icon", b"\x00\x00\x01\x00x".as_slice()), + ( + "a.svg", + "image/svg+xml", + b"".as_slice(), + ), + ] { + let (status, body) = upload( + router.clone(), + multipart_body_named(name, content_type, bytes), + ) + .await; + assert_eq!(status, StatusCode::OK, "{content_type}: {body}"); + } + } } // ============================================================================= From 218f088b6f2a02f09223cfc0c8e13ca20bf42d61 Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 02:22:40 -0600 Subject: [PATCH 2/5] fix(id): accept legal SVG prolog constructs in the upload byte check (#5342) Codex P2 on PR #5357: valid SVGs whose root is preceded by a DOCTYPE or comments (e.g. doc/database_structure_20231217_074440.svg: XML declaration, SVG 1.1 DOCTYPE, Graphviz comments) were refused 400. svg_document_starts now skips processing instructions, comments, and DOCTYPE declarations (tracking an internal subset bracket depth) before requiring the bool { } } -/// Whether `data` is an SVG document: after an optional UTF-8 BOM, -/// leading whitespace, and an optional `` prolog, the -/// document must open with an `` or +/// another processing instruction, `` comments, and a +/// `` declaration (real-world SVGs carry all of these: +/// see `doc/database_structure_20231217_074440.svg`, a Graphviz export +/// with a declaration, an SVG 1.1 DOCTYPE, and comments before the +/// root) — the document must open with an ` bool { let mut rest = data; if rest.starts_with(&[0xEF, 0xBB, 0xBF]) { @@ -118,16 +122,39 @@ fn svg_document_starts(data: &[u8]) -> bool { while rest.first().is_some_and(u8::is_ascii_whitespace) { rest = &rest[1..]; } - if rest.starts_with(b"") { - Some(end) => { - rest = &rest[end + 2..]; - continue; + Some(end) => rest = &rest[end + 2..], + None => return false, + } + } else if rest.starts_with(b"") { + Some(end) => rest = &rest[end + 3..], + None => return false, + } + } else if rest.starts_with(b"` outside an `[ ... ]` internal subset. + let mut subset_depth = 0usize; + let mut end = None; + for (i, b) in rest.iter().enumerate() { + match b { + b'[' => subset_depth += 1, + b']' => subset_depth = subset_depth.saturating_sub(1), + b'>' if subset_depth == 0 => { + end = Some(i); + break; + } + _ => {} } + } + match end { + Some(end) => rest = &rest[end + 1..], None => return false, } + } else { + break; } - break; } rest.starts_with(b"\n" )); + // Codex P2 on PR #5357: legal prolog constructs — a DOCTYPE and + // comments, as in doc/database_structure_20231217_074440.svg — + // precede the root element of valid SVGs and must be accepted. + assert!(image_bytes_match_declared_type( + "image/svg+xml", + b"\n\n\n\n" + )); + assert!(image_bytes_match_declared_type( + "image/svg+xml", + b"b\"> ]>\n" + )); + assert!(!image_bytes_match_declared_type( + "image/svg+xml", + b"" + )); assert!(!image_bytes_match_declared_type( "image/png", b"" From 53388c8207e5909780d595dc45591ef0192e9dfc Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 02:33:36 -0600 Subject: [PATCH 3/5] fix(id): accept namespace-prefixed SVG roots in the upload byte check (#5342) Codex P2 on PR #5357 (round 2): a namespace-prefixed root such as was refused 400 although it is an SVG root and previously uploaded fine. The root check now reads the whole tag name and compares its local name (after any prefix) to svg, via svg_root_element_opens; and still fail. Tests cover the prefixed root and both lookalikes. --- pkgs/id/src/web/routes.rs | 50 +++++++++++++++++++++++++++++++++++---- 1 file changed, 45 insertions(+), 5 deletions(-) diff --git a/pkgs/id/src/web/routes.rs b/pkgs/id/src/web/routes.rs index d736def94e..c4218ddd92 100644 --- a/pkgs/id/src/web/routes.rs +++ b/pkgs/id/src/web/routes.rs @@ -112,7 +112,7 @@ fn image_bytes_match_declared_type(content_type: &str, data: &[u8]) -> bool { /// `` declaration (real-world SVGs carry all of these: /// see `doc/database_structure_20231217_074440.svg`, a Graphviz export /// with a declaration, an SVG 1.1 DOCTYPE, and comments before the -/// root) — the document must open with an ` bool { let mut rest = data; if rest.starts_with(&[0xEF, 0xBB, 0xBF]) { @@ -156,10 +156,36 @@ fn svg_document_starts(data: &[u8]) -> bool { break; } } - rest.starts_with(b"' || *b == b'/') + svg_root_element_opens(rest) +} + +/// Whether `rest` opens an element whose local name is `svg`: the +/// plain `` spelling, or a namespace-prefixed root such as +/// `` (Codex P2 on +/// PR #5357 — prefixed SVGs previously uploaded fine and the client +/// allowlist still accepts them). The tag name is read whole, so +/// `` and `` do not pass. +fn svg_root_element_opens(rest: &[u8]) -> bool { + if !rest.starts_with(b"<") + || rest.starts_with(b"' || *b == b'/') + .unwrap_or(name.len()); + if end == 0 { + return false; + } + let local_name = name[..end] + .rsplit(|b| *b == b':') + .next() + .unwrap_or(&name[..end]); + local_name == b"svg" } /// Query parameters for the file list (pagination + search). @@ -3436,6 +3462,20 @@ mod upload_router_tests { "image/svg+xml", b"" )); + // Codex P2 on PR #5357 (second round): a namespace-prefixed + // root is still an SVG root; lookalike tag names are not. + assert!(image_bytes_match_declared_type( + "image/svg+xml", + b"" + )); + assert!(!image_bytes_match_declared_type( + "image/svg+xml", + b"" + )); + assert!(!image_bytes_match_declared_type( + "image/svg+xml", + b"" + )); assert!(!image_bytes_match_declared_type( "image/png", b"" From 8de7ee1aebbd11c0377bc2518a205cd88478b4ac Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 02:45:02 -0600 Subject: [PATCH 4/5] fix(id): decode UTF-16 SVGs before the upload root check (#5342) Codex P2 on PR #5357 (round 3): an SVG encoded as UTF-16LE/BE is a valid image/svg+xml document, but its markup is not ASCII bytes, so the byte check refused it 400. decode_utf16_text recognises a UTF-16 BOM or the UTF-16 spelling of an opening <, decodes lossily, and the decoded text goes through the same prolog/root check. Tests encode an SVG document in UTF-16LE and UTF-16BE (with BOM), a no-BOM LE case, and a UTF-16 HTML masquerade (still refused). --- pkgs/id/src/web/routes.rs | 77 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 76 insertions(+), 1 deletion(-) diff --git a/pkgs/id/src/web/routes.rs b/pkgs/id/src/web/routes.rs index c4218ddd92..ef4a7c418f 100644 --- a/pkgs/id/src/web/routes.rs +++ b/pkgs/id/src/web/routes.rs @@ -101,11 +101,48 @@ fn image_bytes_match_declared_type(content_type: &str, data: &[u8]) -> bool { data.starts_with(&[0x00, 0x00, 0x01, 0x00]) || data.starts_with(&[0x00, 0x00, 0x02, 0x00]) } - "image/svg+xml" => svg_document_starts(data), + "image/svg+xml" => match decode_utf16_text(data) { + // An SVG encoded as UTF-16 (Codex P2 on PR #5357, round 3) + // is a valid image/svg+xml document whose markup is not + // ASCII bytes; decode it and run the same check on the text. + Some(decoded) => svg_document_starts(decoded.as_bytes()), + None => svg_document_starts(data), + }, _ => false, } } +/// Decode UTF-16 text when `data` carries one of its signatures: a +/// UTF-16LE (`FF FE`) or UTF-16BE (`FE FF`) byte-order mark, or the +/// UTF-16 spelling of an opening `<` (`3C 00` / `00 3C`) when there is +/// no BOM. Returns `None` for anything else (the caller then treats +/// the bytes as UTF-8/ASCII, as before). Lossy on unpaired surrogates — +/// only the prolog/root prefix is inspected afterwards. +fn decode_utf16_text(data: &[u8]) -> Option { + let (body, little_endian) = if data.starts_with(&[0xFF, 0xFE]) { + (&data[2..], true) + } else if data.starts_with(&[0xFE, 0xFF]) { + (&data[2..], false) + } else if data.starts_with(&[0x3C, 0x00]) { + (data, true) + } else if data.starts_with(&[0x00, 0x3C]) { + (data, false) + } else { + return None; + }; + let units: Vec = body + .chunks_exact(2) + .map(|c| { + if little_endian { + u16::from_le_bytes([c[0], c[1]]) + } else { + u16::from_be_bytes([c[0], c[1]]) + } + }) + .collect(); + Some(String::from_utf16_lossy(&units)) +} + /// Whether `data` is an SVG document: after an optional UTF-8 BOM and /// the legal XML prolog constructs — whitespace, `` or /// another processing instruction, `` comments, and a @@ -3476,6 +3513,44 @@ mod upload_router_tests { "image/svg+xml", b"" )); + // Codex P2 on PR #5357 (round 3): UTF-16-encoded SVGs are valid + // image/svg+xml documents; LE and BE, with and without a BOM, + // are decoded before the prolog/root check. + fn utf16(text: &str, little_endian: bool, bom: bool) -> Vec { + let mut out = Vec::new(); + if bom { + out.extend_from_slice(if little_endian { + b"\xff\xfe" + } else { + b"\xfe\xff" + }); + } + for unit in text.encode_utf16() { + out.extend_from_slice(&if little_endian { + unit.to_le_bytes() + } else { + unit.to_be_bytes() + }); + } + out + } + let svg_doc = "\n"; + assert!(image_bytes_match_declared_type( + "image/svg+xml", + &utf16(svg_doc, true, true) + )); + assert!(image_bytes_match_declared_type( + "image/svg+xml", + &utf16(svg_doc, false, true) + )); + assert!(image_bytes_match_declared_type( + "image/svg+xml", + &utf16("", true, false) + )); + assert!(!image_bytes_match_declared_type( + "image/svg+xml", + &utf16("", true, true) + )); assert!(!image_bytes_match_declared_type( "image/png", b"" From 14919855705896465e94e40dba8a52cb9e16d23d Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 02:56:01 -0600 Subject: [PATCH 5/5] fix(id): scan the SVG DOCTYPE quote- and comment-aware (#5342) Codex P2 on PR #5357 (round 4): the internal-subset scanner counted brackets inside quoted literals and comments, so a legal DOCTYPE such as never terminated and the SVG was refused 400. doctype_end now tracks quote and comment state alongside subset depth; only unquoted, uncommented brackets delimit the subset. Tests cover the quoted-bracket counterexample, a comment holding brackets inside the subset, and a rootless DOCTYPE (still refused, for the right reason). --- pkgs/id/src/web/routes.rs | 77 +++++++++++++++++++++++++++++++-------- 1 file changed, 62 insertions(+), 15 deletions(-) diff --git a/pkgs/id/src/web/routes.rs b/pkgs/id/src/web/routes.rs index ef4a7c418f..088d06b01a 100644 --- a/pkgs/id/src/web/routes.rs +++ b/pkgs/id/src/web/routes.rs @@ -171,21 +171,7 @@ fn svg_document_starts(data: &[u8]) -> bool { None => return false, } } else if rest.starts_with(b"` outside an `[ ... ]` internal subset. - let mut subset_depth = 0usize; - let mut end = None; - for (i, b) in rest.iter().enumerate() { - match b { - b'[' => subset_depth += 1, - b']' => subset_depth = subset_depth.saturating_sub(1), - b'>' if subset_depth == 0 => { - end = Some(i); - break; - } - _ => {} - } - } - match end { + match doctype_end(rest) { Some(end) => rest = &rest[end + 1..], None => return false, } @@ -196,6 +182,52 @@ fn svg_document_starts(data: &[u8]) -> bool { svg_root_element_opens(rest) } +/// Byte index of the `>` that ends a `` declaration at +/// the start of `rest`. The declaration ends at the first `>` that is +/// outside the `[ ... ]` internal subset, outside any quoted literal +/// (`"..."` / `'...'`), and outside any `` comment — +/// brackets and angle brackets inside quotes or comments are data, +/// not delimiters (Codex P2 on PR #5357, round 4: an entity value of +/// `"["` used to corrupt the subset depth and reject a legal SVG). +fn doctype_end(rest: &[u8]) -> Option { + let mut subset_depth = 0usize; + let mut quote: Option = None; + let mut in_comment = false; + let mut i = 0usize; + while i < rest.len() { + if in_comment { + if rest[i..].starts_with(b"-->") { + in_comment = false; + i += 3; + } else { + i += 1; + } + continue; + } + if let Some(q) = quote { + if rest[i] == q { + quote = None; + } + i += 1; + continue; + } + if rest[i..].starts_with(b" ]>\n" + )); + assert!(!image_bytes_match_declared_type( + "image/svg+xml", + b"]>" + )); assert!(!image_bytes_match_declared_type( "image/png", b""