diff --git a/crates/mesh/src/gltf.rs b/crates/mesh/src/gltf.rs index c92051b84..d074f1ed1 100644 --- a/crates/mesh/src/gltf.rs +++ b/crates/mesh/src/gltf.rs @@ -120,6 +120,16 @@ pub fn uri_decode(s: &str) -> String { String::from_utf8_lossy(&percent_decode(s)).into_owned() } +/// Percent-decode a URI, rejecting decoded bytes that are not UTF-8. +/// +/// As with [`uri_decode`], incomplete or non-hex escapes stay literal and `+` stays +/// `+`. This does not validate or confine a filesystem path; callers must retain +/// their own reference policy. Decoding is linear and output is no larger than input. +/// Use this instead of the lossy decoder when a resolver requires exact UTF-8 names. +pub fn uri_decode_strict(s: &str) -> Option { + String::from_utf8(percent_decode(s)).ok() +} + /// [`uri_decode`] as bytes, so escaped bytes that are not UTF-8 survive. fn percent_decode(s: &str) -> Vec { let b = s.as_bytes(); diff --git a/crates/mesh/src/tests/gltf.rs b/crates/mesh/src/tests/gltf.rs index 8892fe241..c47b911df 100644 --- a/crates/mesh/src/tests/gltf.rs +++ b/crates/mesh/src/tests/gltf.rs @@ -950,3 +950,32 @@ fn morph_targets_and_other_scenes_are_named_in_warnings() { let s = parse(&one_mesh(&b, plain.clone())).unwrap(); assert!(s.warnings.is_empty(), "{:?}", s.warnings); } + +#[test] +fn strict_uri_decoding_preserves_exact_names_and_rejects_invalid_utf8() { + use crate::gltf::uri_decode_strict; + for (input, expected) in [ + ("", Some("")), + ("a+b", Some("a+b")), + ("a%20b", Some("a b")), + ("é/%E2%82%AC", Some("é/€")), + ("%", Some("%")), + ("%2", Some("%2")), + ("%GG", Some("%GG")), + ("%252e%252e", Some("%2e%2e")), + ("%2e%2e%2fmesh.bin", Some("../mesh.bin")), + ("%00", Some("\0")), + ("%FF", None), + ("%C0%AF", None), + ("%ED%A0%80", None), + ("%E2%82", None), + ] { + assert_eq!(uri_decode_strict(input).as_deref(), expected, "{input}"); + } + // Keep the existing API's replacement-character behavior unchanged. + assert_eq!(uri_decode("%FF"), "�"); + let input = "%41%GG+é".repeat(100_000); + let decoded = uri_decode_strict(&input).unwrap(); + assert_eq!(decoded, "A%GG+é".repeat(100_000)); + assert!(decoded.len() <= input.len()); +}