use std::borrow::Cow;
use std::fmt::Write as _;
use proptest::prelude::*;
use super::java::{JavaParts, Reading, parts};
use super::percent::{BadEscape, Mode, PercentError, Plus, Utf8, decode};
use super::{UriRef, extension, split};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Want {
reading: Reading,
scheme: Option<&'static str>,
user_info: Option<&'static str>,
host: Option<&'static str>,
port: Option<u32>,
path: Option<&'static str>,
extension: Option<&'static str>,
query: Option<&'static str>,
fragment: Option<&'static str>,
}
const URI: Want = Want {
reading: Reading::Uri,
scheme: None,
user_info: None,
host: None,
port: None,
path: None,
extension: None,
query: None,
fragment: None,
};
const URL: Want = Want {
reading: Reading::Url,
..URI
};
const OPAQUE: Want = Want {
reading: Reading::Opaque,
..URI
};
const fn path(path: &'static str) -> Want {
Want {
path: Some(path),
..URI
}
}
type Seen = (Want, Option<String>, Option<String>, Option<String>);
fn seen(p: &JavaParts<'_>) -> Seen {
let decoded_path = p.decoded_path().map(Cow::into_owned);
let ext = decoded_path
.as_deref()
.and_then(extension)
.map(str::to_owned);
let query = p.decoded_query().map(Cow::into_owned);
let shape = Want {
reading: p.reading,
scheme: p.scheme.map(leak),
user_info: p.user_info.map(leak),
host: p.host.map(leak),
port: p.port,
path: None,
extension: None,
query: None,
fragment: p.fragment.map(leak),
};
(shape, decoded_path, ext, query)
}
fn leak(s: &str) -> &'static str {
Box::leak(s.to_owned().into_boxed_str())
}
#[test]
#[allow(clippy::too_many_lines, reason = "one table of 51 cases")]
fn java_parts_read_as_the_jdk_does() {
let cases: Vec<(&str, Option<Want>)> = vec![
("/config/", Some(path("/config/"))),
("/", Some(path("/"))),
(
"http://172.16.200.55/virus/eicar.com",
Some(Want {
scheme: Some("http"),
host: Some("172.16.200.55"),
path: Some("/virus/eicar.com"),
extension: Some("com"),
..URI
}),
),
(
"/ips/sig1.pdf",
Some(Want {
extension: Some("pdf"),
..path("/ips/sig1.pdf")
}),
),
(
"/api/v2/monitor/system/usb-log?vdom=root",
Some(Want {
query: Some("vdom=root"),
..path("/api/v2/monitor/system/usb-log")
}),
),
(
"/api/v2/cmdb/log.analyzer/setting?vdom=root",
Some(Want {
query: Some("vdom=root"),
..path("/api/v2/cmdb/log.analyzer/setting")
}),
),
("subdomain.domain.tld", Some(path("subdomain.domain.tld"))),
("url.com", Some(path("url.com"))),
(
"https://172.16.200.88/dlp/files/report.pdf",
Some(Want {
scheme: Some("https"),
host: Some("172.16.200.88"),
path: Some("/dlp/files/report.pdf"),
extension: Some("pdf"),
..URI
}),
),
(
"https://bob:hunter2@example.com:8443/a?b=1#c",
Some(Want {
scheme: Some("https"),
user_info: Some("bob:hunter2"),
host: Some("example.com"),
port: Some(8443),
path: Some("/a"),
query: Some("b=1"),
fragment: Some("c"),
..URI
}),
),
(
"https://u@ex.com:8443/a/b.php?q=1#f",
Some(Want {
scheme: Some("https"),
user_info: Some("u"),
host: Some("ex.com"),
port: Some(8443),
path: Some("/a/b.php"),
extension: Some("php"),
query: Some("q=1"),
fragment: Some("f"),
..URI
}),
),
(
"http://[2001:db8::1]:8080/x",
Some(Want {
scheme: Some("http"),
host: Some("[2001:db8::1]"),
port: Some(8080),
path: Some("/x"),
..URI
}),
),
(
"http://[2001:db8::1]/x",
Some(Want {
scheme: Some("http"),
host: Some("[2001:db8::1]"),
path: Some("/x"),
..URI
}),
),
(
"http://[fe80::1%25eth0]/a",
Some(Want {
scheme: Some("http"),
host: Some("[fe80::1%25eth0]"),
path: Some("/a"),
..URI
}),
),
(
"mongodb://mongo-1:27017,mongo-2:27018/?replicaSet=rs0",
Some(Want {
scheme: Some("mongodb"),
path: Some("/"),
query: Some("replicaSet=rs0"),
..URI
}),
),
(
"http://example.com:80-/a",
Some(Want {
scheme: Some("http"),
path: Some("/a"),
..URI
}),
),
(
"http://my_host.example.com/a",
Some(Want {
scheme: Some("http"),
path: Some("/a"),
..URI
}),
),
(
"http://host-.example.com/a",
Some(Want {
scheme: Some("http"),
path: Some("/a"),
..URI
}),
),
(
"http://a.1/x",
Some(Want {
scheme: Some("http"),
path: Some("/x"),
..URI
}),
),
(
"https://www.CAF\u{e9}.com",
Some(Want {
scheme: Some("https"),
path: Some(""),
..URI
}),
),
(
"HTTP://EXAMPLE.COM/",
Some(Want {
scheme: Some("HTTP"),
host: Some("EXAMPLE.COM"),
path: Some("/"),
..URI
}),
),
(
"https://example.com:443",
Some(Want {
scheme: Some("https"),
host: Some("example.com"),
port: Some(443),
path: Some(""),
..URI
}),
),
(
"https://89.160.20.112:12443/api/v1/deployments",
Some(Want {
scheme: Some("https"),
host: Some("89.160.20.112"),
port: Some(12443),
path: Some("/api/v1/deployments"),
..URI
}),
),
(
"http://www.example.org/download/eicar.com.txt",
Some(Want {
scheme: Some("http"),
host: Some("www.example.org"),
path: Some("/download/eicar.com.txt"),
extension: Some("txt"),
..URI
}),
),
(
"https://example.com/config/",
Some(Want {
scheme: Some("https"),
host: Some("example.com"),
path: Some("/config/"),
..URI
}),
),
(
"http://h/p?Extra=%255b%2522x%2522%255d",
Some(Want {
scheme: Some("http"),
host: Some("h"),
path: Some("/p"),
query: Some("Extra=%5b%22x%22%5d"),
..URI
}),
),
(
"http://example.com/admin/..%2F..%2F..%2Fdirectory/file",
Some(Want {
scheme: Some("http"),
host: Some("example.com"),
path: Some("/admin/../../../directory/file"),
..URI
}),
),
(
"http://h/p?q=a+b&q=c",
Some(Want {
scheme: Some("http"),
host: Some("h"),
path: Some("/p"),
query: Some("q=a+b&q=c"),
..URI
}),
),
(
"http://h/p%FF",
Some(Want {
scheme: Some("http"),
host: Some("h"),
path: Some("/p\u{fffd}"),
..URI
}),
),
(
"http://example.com/a?f[0]=x%20y",
Some(Want {
scheme: Some("http"),
host: Some("example.com"),
path: Some("/a"),
query: Some("f[0]=x y"),
..URI
}),
),
(
"http://example.com/a[1]?q=x%20y",
Some(Want {
scheme: Some("http"),
host: Some("example.com"),
path: Some("/a[1]"),
query: Some("q=x%20y"),
..URL
}),
),
(
"http://h/p?bad=%ZZ",
Some(Want {
scheme: Some("http"),
host: Some("h"),
path: Some("/p"),
query: Some("bad=%ZZ"),
..URL
}),
),
(
"http://h/a b",
Some(Want {
scheme: Some("http"),
host: Some("h"),
path: Some("/a b"),
..URL
}),
),
(
"http://exam[ple.com/a",
Some(Want {
scheme: Some("http"),
host: Some("exam[ple.com"),
path: Some("/a"),
..URL
}),
),
(
"https:// ",
Some(Want {
scheme: Some("https"),
path: Some(""),
..URL
}),
),
(
"file:///a b:c",
Some(Want {
scheme: Some("file"),
path: Some("/a b:c"),
..URL
}),
),
(
"http://example.com?q=1",
Some(Want {
scheme: Some("http"),
host: Some("example.com"),
path: Some(""),
query: Some("q=1"),
..URI
}),
),
(
"?q=1",
Some(Want {
query: Some("q=1"),
..URI
}),
),
("/a/b:c", Some(path("/a/b:c"))),
(
"blob:chrome-extension://abcdef/1234-5678",
Some(Want {
scheme: Some("blob"),
..OPAQUE
}),
),
(
"mailto:someone@example.com#top",
Some(Want {
scheme: Some("mailto"),
fragment: Some("top"),
..OPAQUE
}),
),
("", None),
("89.160.20.156:8080/maf.html", None),
("hxxp://bad[.]example[.]com/malware/drop", None),
(
"http://[81.2.69.142:80]/vendor/phpunit/src/eval-stdin.php",
None,
),
("http://internal-service-alb.example.com:80-/ ", None),
("h ttp://example.com/a", None),
("http://h:80-/ ", None),
(
"mongodb://m1:27017,m2:27018/?replicaSet=rs0",
Some(Want {
scheme: Some("mongodb"),
path: Some("/"),
query: Some("replicaSet=rs0"),
..URI
}),
),
(
"http://example.com/admin/..%2F..%2Ffile",
Some(Want {
scheme: Some("http"),
host: Some("example.com"),
path: Some("/admin/../../file"),
..URI
}),
),
(
"blob:chrome-extension://abcdef/1234",
Some(Want {
scheme: Some("blob"),
..OPAQUE
}),
),
];
for (input, want) in cases {
let got = parts(input);
let Some(want) = want else {
assert_eq!(got, None, "input: {input:?}");
continue;
};
let got = got.unwrap_or_else(|| panic!("no parts for {input:?}"));
let (shape, decoded_path, ext, query) = seen(&got);
let want_shape = Want {
path: None,
extension: None,
query: None,
..want
};
assert_eq!(shape, want_shape, "input: {input:?}");
assert_eq!(decoded_path.as_deref(), want.path, "path of {input:?}");
assert_eq!(ext.as_deref(), want.extension, "extension of {input:?}");
assert_eq!(query.as_deref(), want.query, "query of {input:?}");
}
}
#[test]
fn java_hosts_that_read_as_a_server() {
for (input, host) in [
("http://localhost:8080/a", "localhost"),
("http://example.com./a", "example.com."),
("http://a-b.c-d.example/a", "a-b.c-d.example"),
("http://010.1.1.1/a", "010.1.1.1"),
("http://1a.example/a", "1a.example"),
("http://255.255.255.255/a", "255.255.255.255"),
("http://256.1.1.1.x/a", "256.1.1.1.x"),
("http://[2001:db8::1]:80/a", "[2001:db8::1]"),
("http://a/b", "a"),
("http://9/b", "9"),
] {
let got = parts(input).and_then(|p| p.host);
assert_eq!(got, Some(host), "input: {input}");
}
for input in [
"http://256.1.1.1/a",
"http://1.2.3/a",
"http://-a.example/a",
"http://a..b/a",
"http://./a",
"http://1.2.3.4.5/a",
"http://h:+80/a",
] {
let got = parts(input).map(|p| (p.reading, p.host, p.port));
assert_eq!(got, Some((Reading::Uri, None, None)), "input: {input}");
}
}
#[test]
fn java_user_info_splits_at_its_first_colon() {
let cases = [
(
"https://bob:hunter2@example.com/",
Some("bob"),
Some("hunter2"),
),
("https://bob@example.com/", Some("bob"), None),
("https://bob:a:b@example.com/", Some("bob"), Some("a:b")),
("https://:pw@example.com/", Some(""), Some("pw")),
("https://example.com/", None, None),
];
for (input, username, password) in cases {
let p = parts(input).unwrap_or_else(|| panic!("no parts for {input}"));
assert_eq!(
(p.username(), p.password()),
(username, password),
"{input}"
);
}
}
#[test]
fn java_parts_borrow_when_nothing_decodes() {
let p = parts("http://h/a/b?q=1").unwrap();
assert!(matches!(p.decoded_path(), Some(Cow::Borrowed("/a/b"))));
assert!(matches!(p.decoded_query(), Some(Cow::Borrowed("q=1"))));
}
fn rebuild(u: &UriRef<'_>) -> String {
let mut out = String::new();
if let Some(scheme) = u.scheme {
out.push_str(scheme);
out.push(':');
}
if let Some(host) = u.host {
out.push_str("//");
if let Some(info) = u.user_info {
out.push_str(info);
out.push('@');
}
out.push_str(host);
if let Some(port) = u.port {
out.push(':');
out.push_str(port);
}
}
out.push_str(u.path);
if let Some(query) = u.query {
out.push('?');
out.push_str(query);
}
if let Some(fragment) = u.fragment {
out.push('#');
out.push_str(fragment);
}
out
}
type Split = (
Option<&'static str>,
Option<&'static str>,
Option<&'static str>,
Option<&'static str>,
&'static str,
Option<&'static str>,
Option<&'static str>,
);
#[test]
fn split_takes_any_reference_apart() {
let cases: &[(&str, Split)] = &[
(
"https://u:p@h:8/a?q#f",
(
Some("https"),
Some("u:p"),
Some("h"),
Some("8"),
"/a",
Some("q"),
Some("f"),
),
),
("/a/b", (None, None, None, None, "/a/b", None, None)),
("", (None, None, None, None, "", None, None)),
("a:b", (Some("a"), None, None, None, "b", None, None)),
("1a:b", (None, None, None, None, "1a:b", None, None)),
("//h", (None, None, Some("h"), None, "", None, None)),
("x://", (Some("x"), None, Some(""), None, "", None, None)),
(
"x://a@b@c:",
(Some("x"), Some("a@b"), Some("c"), Some(""), "", None, None),
),
(
"x://[::1]",
(Some("x"), None, Some("[::1]"), None, "", None, None),
),
(
"x://[::1]:9/",
(Some("x"), None, Some("[::1]"), Some("9"), "/", None, None),
),
(
"a?b#c?d",
(None, None, None, None, "a", Some("b"), Some("c?d")),
),
("a#b?c", (None, None, None, None, "a", None, Some("b?c"))),
("/a:b", (None, None, None, None, "/a:b", None, None)),
(":a", (None, None, None, None, ":a", None, None)),
];
for (input, want) in cases {
let u = split(input);
let got = (
u.scheme,
u.user_info,
u.host,
u.port,
u.path,
u.query,
u.fragment,
);
assert_eq!(&got, want, "input: {input:?}");
assert_eq!(rebuild(&u), *input);
}
}
#[test]
fn extension_is_the_last_segments_suffix() {
for (input, want) in [
("/virus/eicar.com", Some("com")),
("/a/b.tar.gz", Some("gz")),
("/config/", None),
("/a.b/c", None),
("/a.", None),
("/.profile", Some("profile")),
("subdomain.domain.tld", None),
("", None),
("/\u{e9}.\u{e9}", Some("\u{e9}")),
] {
assert_eq!(extension(input), want, "input: {input:?}");
}
}
const STRICT: Mode = Mode {
plus: Plus::Space,
bad_escape: BadEscape::Error,
utf8: Utf8::Error,
};
#[test]
fn percent_decode_by_mode() {
use PercentError::{BadEscape as Bad, Utf8 as NotUtf8};
type Answer = Result<&'static str, PercentError>;
let cases: &[(&str, Answer, Answer, Answer, Answer)] = &[
("a+b", Ok("a b"), Ok("a+b"), Ok("a+b"), Ok("a b")),
("a%20b", Ok("a b"), Ok("a b"), Ok("a b"), Ok("a b")),
(
"%C3%A9",
Ok("\u{e9}"),
Ok("\u{e9}"),
Ok("\u{e9}"),
Ok("\u{e9}"),
),
(
"%c3%a9",
Ok("\u{e9}"),
Ok("\u{e9}"),
Ok("\u{e9}"),
Ok("\u{e9}"),
),
(
"100%",
Err(Bad { at: 3 }),
Err(Bad { at: 3 }),
Ok("100%"),
Err(Bad { at: 3 }),
),
(
"%zz",
Err(Bad { at: 0 }),
Err(Bad { at: 0 }),
Ok("%zz"),
Err(Bad { at: 0 }),
),
(
"%4",
Err(Bad { at: 0 }),
Err(Bad { at: 0 }),
Ok("%4"),
Err(Bad { at: 0 }),
),
(
"%+5",
Err(Bad { at: 0 }),
Err(Bad { at: 0 }),
Ok("%+5"),
Err(Bad { at: 0 }),
),
(
"%-5",
Err(Bad { at: 0 }),
Err(Bad { at: 0 }),
Ok("%-5"),
Err(Bad { at: 0 }),
),
(
"%%41",
Err(Bad { at: 0 }),
Err(Bad { at: 0 }),
Ok("%A"),
Err(Bad { at: 0 }),
),
(
"%\u{e9}1",
Err(Bad { at: 0 }),
Err(Bad { at: 0 }),
Ok("%\u{e9}1"),
Err(Bad { at: 0 }),
),
(
"%FF",
Ok("\u{fffd}"),
Ok("\u{fffd}"),
Ok("\u{fffd}"),
Err(NotUtf8 { valid_up_to: 0 }),
),
(
"ab%C3+%A9",
Ok("ab\u{fffd} \u{fffd}"),
Ok("ab\u{fffd}+\u{fffd}"),
Ok("ab\u{fffd}+\u{fffd}"),
Err(NotUtf8 { valid_up_to: 2 }),
),
(
"\u{e9}%41",
Ok("\u{e9}A"),
Ok("\u{e9}A"),
Ok("\u{e9}A"),
Ok("\u{e9}A"),
),
("abc", Ok("abc"), Ok("abc"), Ok("abc"), Ok("abc")),
("", Ok(""), Ok(""), Ok(""), Ok("")),
];
for (input, form, uri, lenient, strict) in cases {
for (mode, want) in [
(Mode::FORM, form),
(Mode::URI, uri),
(Mode::LENIENT, lenient),
(STRICT, strict),
] {
let got = decode(input, mode);
assert_eq!(
got.as_deref().map_err(|e| *e),
*want,
"{input:?} under {mode:?}"
);
}
}
}
#[test]
fn percent_decode_borrows_what_does_not_change() {
for (input, mode) in [
("abc", Mode::FORM),
("a+b", Mode::URI),
("100%", Mode::LENIENT),
("%zz+", Mode::LENIENT),
("", STRICT),
] {
assert!(
matches!(decode(input, mode), Ok(Cow::Borrowed(_))),
"{input:?} under {mode:?}"
);
}
assert!(matches!(decode("a+b", Mode::FORM), Ok(Cow::Owned(_))));
}
fn reference(text: &str, mode: Mode) -> Result<String, PercentError> {
let bytes = text.as_bytes();
let mut out = Vec::new();
let mut i = 0;
while i < bytes.len() {
let b = bytes[i];
if b == b'+' && mode.plus == Plus::Space {
out.push(b' ');
i += 1;
} else if b == b'%' {
let pair = bytes
.get(i + 1..i + 3)
.and_then(|h| std::str::from_utf8(h).ok());
match pair.filter(|h| h.bytes().all(|c| c.is_ascii_hexdigit())) {
Some(h) => {
out.push(u8::from_str_radix(h, 16).unwrap());
i += 3;
}
None if mode.bad_escape == BadEscape::Keep => {
out.push(b'%');
i += 1;
}
None => return Err(PercentError::BadEscape { at: i }),
}
} else {
out.push(b);
i += 1;
}
}
match String::from_utf8(out) {
Ok(s) => Ok(s),
Err(e) if mode.utf8 == Utf8::Error => Err(PercentError::Utf8 {
valid_up_to: e.utf8_error().valid_up_to(),
}),
Err(e) => Ok(String::from_utf8_lossy(e.as_bytes()).into_owned()),
}
}
fn modes() -> impl Strategy<Value = Mode> {
(any::<bool>(), any::<bool>(), any::<bool>()).prop_map(|(plus, keep, replace)| Mode {
plus: if plus { Plus::Space } else { Plus::Literal },
bad_escape: if keep {
BadEscape::Keep
} else {
BadEscape::Error
},
utf8: if replace { Utf8::Replace } else { Utf8::Error },
})
}
fn escapish() -> impl Strategy<Value = String> {
proptest::string::string_regex(
"([%+]|%[0-9a-fA-F]{2}|%[0-9a-zA-Z+-]|[a-f0-9]|\u{e9}|\u{1f600}| ){0,24}",
)
.unwrap()
}
fn crate_lossy(text: &str) -> String {
percent_encoding::percent_decode_str(text)
.decode_utf8_lossy()
.into_owned()
}
fn crate_form(text: &str) -> String {
form_urlencoded::parse(text.as_bytes())
.next()
.map(|(key, _)| key.into_owned())
.unwrap_or_default()
}
fn any_text() -> impl Strategy<Value = String> {
prop_oneof![escapish(), any::<String>()]
}
proptest! {
#[test]
fn percent_decode_matches_the_byte_walk(text in escapish(), mode in modes()) {
let got = decode(&text, mode).map(Cow::into_owned);
prop_assert_eq!(got, reference(&text, mode));
}
#[test]
fn percent_decode_matches_the_byte_walk_on_any_text(text in any::<String>(), mode in modes()) {
let got = decode(&text, mode).map(Cow::into_owned);
prop_assert_eq!(got, reference(&text, mode));
}
#[test]
fn percent_decode_inverts_an_encode(
text in any::<String>(),
picks in proptest::collection::vec(any::<bool>(), 0..64),
) {
let mut encoded = String::new();
for (i, b) in text.bytes().enumerate() {
if b == b'%' || b == b'+' || !b.is_ascii() || picks.get(i).copied().unwrap_or(false) {
write!(encoded, "%{b:02X}").unwrap();
} else {
encoded.push(char::from(b));
}
}
for mode in [Mode::FORM, Mode::URI, Mode::LENIENT, STRICT] {
let decoded = decode(&encoded, mode);
prop_assert_eq!(decoded.as_deref(), Ok(text.as_str()));
}
}
#[test]
fn lenient_and_uri_match_percent_encoding(text in any_text()) {
let oracle = crate_lossy(&text);
prop_assert_eq!(decode(&text, Mode::LENIENT).map(Cow::into_owned), Ok(oracle.clone()));
if let Ok(got) = decode(&text, Mode::URI) {
prop_assert_eq!(got.into_owned(), oracle);
}
}
#[test]
fn form_matches_form_urlencoded(
text in any_text().prop_filter("one key", |t| !t.contains(['&', '='])),
) {
let oracle = crate_form(&text);
let keep = Mode { bad_escape: BadEscape::Keep, ..Mode::FORM };
prop_assert_eq!(decode(&text, keep).map(Cow::into_owned), Ok(oracle.clone()));
if let Ok(got) = decode(&text, Mode::FORM) {
prop_assert_eq!(got.into_owned(), oracle);
}
}
#[test]
fn split_rebuilds_the_text(text in any::<String>()) {
prop_assert_eq!(rebuild(&split(&text)), text);
}
#[test]
fn java_parts_borrow_the_text(
text in proptest::string::string_regex("[a-z0-9:/?#@\\[\\]%. _+\u{e9}-]{0,32}").unwrap(),
) {
let range = text.as_bytes().as_ptr_range();
if let Some(p) = parts(&text) {
let spans = [p.scheme, p.user_info, p.host, p.path, p.query, p.fragment];
for part in spans.into_iter().flatten() {
let span = part.as_bytes().as_ptr_range();
prop_assert!(range.start <= span.start && span.end <= range.end);
}
let _ = (p.decoded_path(), p.decoded_query());
}
}
}