Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 97 additions & 2 deletions pkgs/lab-ops-hub/container/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -397,8 +397,11 @@ def validate_crawl_url(raw):
)
# A public DNS name; literal-IP policy does not apply.
# A percent-decoded host is fetched in its decoded form.
# The returned form is WHATWG-normalized (#633).
return _url_with_encoded_components(
_url_with_host(u, host) if percent_decoded else raw
_normalize_validated_url(
_url_with_host(u, host) if percent_decoded else raw
)
)
embedded = _embedded_ipv4(ip)
if embedded is not None:
Expand Down Expand Up @@ -449,7 +452,9 @@ def validate_crawl_url(raw):
canonical = (
_canonical_ipv6(ip) if isinstance(ip, ipaddress.IPv6Address) else str(ip)
)
return _url_with_encoded_components(_url_with_host(u, canonical))
return _url_with_encoded_components(
_normalize_validated_url(_url_with_host(u, canonical))
)


def _judge_a_label(label, host):
Expand Down Expand Up @@ -731,6 +736,96 @@ def _url_with_host(u, new_host):
return u._replace(netloc=prefix + new_host).geturl()


_ASCII_LOWER = str.maketrans("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")

# WHATWG dot segments (#633): a path segment is a single-dot segment
# when it is "." or "%2e", and a double-dot segment when it is "..",
# ".%2e", "%2e." or "%2e%2e" — the percent spellings in any case. A
# longer spelling ("%2e%2e%2e", "%252e%252e") is ordinary data, not a
# dot segment: only the exact segment matches count, so a literal
# "%252e" segment (an encoded "%2e") is never double-decoded into one.
_SINGLE_DOT_SEGMENTS = (".", "%2e")
_DOUBLE_DOT_SEGMENTS = ("..", ".%2e", "%2e.", "%2e%2e")


def _resolve_dot_segments(path):
# Resolve a path's dot segments the way WHATWG URL parsing does
# (#633): a single-dot segment is dropped, a double-dot segment
# drops the previous segment with it, and neither may climb above
# the root — "/a/b/../../../c" is "/c", not an error. A trailing
# dot segment becomes an empty final segment ("/a/." is "/a/",
# "/a/.." is "/", "//%2e" is "//"). Empty segments are ordinary
# segments: "//" survives, and a double-dot segment after one
# pops that empty segment ("/a//../b" is "/a/b"), matching the
# Worker's serializer.
parts = path.split("/")
out = []
for i, seg in enumerate(parts):
low = seg.lower()
if low in _DOUBLE_DOT_SEGMENTS:
if out and not (len(out) == 1 and out[0] == ""):
out.pop()
if i == len(parts) - 1:
out.append("")
continue
if low in _SINGLE_DOT_SEGMENTS:
if i == len(parts) - 1:
out.append("")
continue
out.append(seg)
return "/".join(out)


def _normalize_validated_url(url):
# Return a validated URL in the WHATWG-normalized form the Worker
# returns (#633), so both crawlers record — and fetch — the same
# URL for the same target: dot segments in the path resolved,
# the host lowercased, and the port canonicalized (the scheme's
# default port dropped, leading zeros on any other port stripped,
# an empty port's colon dropped). Only ASCII case folds in the
# host: the IDN spelling itself is deliberately kept, as before
# (judged in mapped form, fetched via IDNA — #615); urlparse has
# already lowercased the scheme. The path's ";params" tail is
# rejoined before resolving: urlparse splits it off the last
# segment, but WHATWG treats ";..." as part of that segment, so
# a trailing "..;foo" is data, not a double-dot segment.
u = urlparse(url)
netloc = u.netloc
if "@" in netloc:
userinfo, _, hostport = netloc.rpartition("@")
prefix = userinfo + "@"
else:
prefix, hostport = "", netloc
if hostport.startswith("["):
end = hostport.find("]")
host_norm = "[" + hostport[1:end].translate(_ASCII_LOWER) + "]"
rest = hostport[end + 1 :]
port_span = rest[1:] if rest.startswith(":") else None
elif ":" in hostport:
host_span, _, port_span = hostport.partition(":")
host_norm = host_span.translate(_ASCII_LOWER)
else:
host_norm = hostport.translate(_ASCII_LOWER)
port_span = None
port_norm = ""
if port_span:
if port_span.isdigit():
port = int(port_span)
is_default = (u.scheme == "http" and port == 80) or (
u.scheme == "https" and port == 443
)
if not is_default:
port_norm = f":{port}"
else:
port_norm = f":{port_span}"
full_path = u.path + (f";{u.params}" if u.params else "")
return u._replace(
netloc=f"{prefix}{host_norm}{port_norm}",
path=_resolve_dot_segments(full_path),
params="",
).geturl()


# WHATWG's per-component percent-encode sets for the ASCII punctuation
# the generic rule below does not already cover, probed against the
# Worker's URL serializer (#618). The sets differ per component: the
Expand Down
27 changes: 27 additions & 0 deletions pkgs/lab-ops-hub/test/lib.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,33 @@ test("validateCrawlUrl percent-encodes C0 controls, space and DEL outside the ho
}
});

test("validateCrawlUrl returns dot segments, host case and ports normalized (#633)", () => {
// The Worker's returned form is the reference the container validator
// mirrors: WHATWG resolves dot segments (literal and %2e spellings),
// lowercases the host, and drops the scheme's default port.
const cases: Array<[string, string]> = [
["http://example.com/a/../b", "http://example.com/b"],
["http://example.com/%2e%2e/admin", "http://example.com/admin"],
["http://example.com/a/%2e%2e/b", "http://example.com/b"],
["http://example.com/a/.", "http://example.com/a/"],
["http://example.com/a/..", "http://example.com/"],
["http://example.com//%2e", "http://example.com//"],
["HTTP://EXAMPLE.COM/Path", "http://example.com/Path"],
["http://example.com:80/x", "http://example.com/x"],
["https://example.com:443/x", "https://example.com/x"],
["http://example.com:080/x", "http://example.com/x"],
["http://example.com:08080/x", "http://example.com:8080/x"],
["http://user:pass@EXAMPLE.com:80/", "http://user:pass@example.com/"],
// Data, not dot segments: double-encoded spellings stay verbatim.
["http://example.com/%252e%252e/admin", "http://example.com/%252e%252e/admin"],
];
for (const [raw, expected] of cases) {
const r = validateCrawlUrl(raw);
assert.equal(r.ok, true, raw);
if (r.ok) assert.equal(r.url, expected, raw);
}
});

test("validateCrawlUrl refuses non-http schemes and junk", () => {
assert.equal(validateCrawlUrl("ftp://example.com/").ok, false);
assert.equal(validateCrawlUrl("file:///etc/passwd").ok, false);
Expand Down
96 changes: 96 additions & 0 deletions pkgs/lab-ops-hub/test/test_container_validate.py
Original file line number Diff line number Diff line change
Expand Up @@ -930,6 +930,78 @@ def test_returns_ip_literals_in_canonical_form(self):
for raw, expected in cases.items():
self.assertEqual(validate_crawl_url(raw), expected, raw)

def test_returns_dot_segments_host_case_and_ports_normalized(self):
# The container returned dot segments, host case and default
# ports verbatim while the Worker returns the WHATWG-normalized
# form, so the two crawlers recorded — and fetched — different
# URLs for the same target (#633). The returned URL now
# resolves dot segments (literal and %2e spellings, any case),
# lowercases the host, and canonicalizes the port (the scheme's
# default dropped, leading zeros stripped). Verdicts are
# unchanged; query and fragment dot spellings are data.
cases = {
"http://example.com/a/../b": "http://example.com/b",
"http://example.com/a/./b": "http://example.com/a/b",
"http://example.com/%2e%2e/admin": "http://example.com/admin",
"http://example.com/a/%2e%2e/b": "http://example.com/b",
"http://example.com/%2e/%2e/x": "http://example.com/x",
"http://example.com/a/%2E/b": "http://example.com/a/b",
"http://example.com/a/b/../../../c": "http://example.com/c",
"http://example.com/a/.": "http://example.com/a/",
"http://example.com/a/..": "http://example.com/",
"http://example.com/a/%2e%2e": "http://example.com/",
"http://example.com//../x": "http://example.com/x",
"http://example.com//./x": "http://example.com//x",
"http://example.com/a//../b": "http://example.com/a/b",
"http://example.com//%2e": "http://example.com//",
"HTTP://EXAMPLE.COM/Path": "http://example.com/Path",
"http://example.com:80/x": "http://example.com/x",
"https://example.com:443/x": "https://example.com/x",
"http://example.com:080/x": "http://example.com/x",
"https://example.com:0443/x": "https://example.com/x",
"http://example.com:08080/x": "http://example.com:8080/x",
"http://user:pass@EXAMPLE.com:80/": "http://user:pass@example.com/",
"http://8.8.8.8:80/a/../b": "http://8.8.8.8/b",
"https://[2001:4860:4860::8888]:443/a/./b": (
"https://[2001:4860:4860::8888]/a/b"
),
"http://example.com/a/../b?x=/../y#/../z": (
"http://example.com/b?x=/../y#/../z"
),
}
for raw, expected in cases.items():
self.assertEqual(validate_crawl_url(raw), expected, raw)
# Data, not dot segments: longer or double-encoded spellings,
# ";" tails and empty segments pass through byte-identical.
for url in (
"http://example.com/foo/%2e%2e%2e/bar",
"http://example.com/%252e%252e/admin",
"http://example.com/a/..;foo",
"http://example.com/..;/x",
"http://example.com//a//b",
"http://example.com:443/x", # non-default for http
"https://example.com:80/x", # non-default for https
):
self.assertAccepted(url)
# Blocked targets in these spellings are refused by the
# ordinary checks, for the right reason.
self.assertRefused("http://127.0.0.1/a/../b")
self.assertRefused("http://LOCALHOST/a/../b")
self.assertRefused("http://127.0.0.1:80/x")

def test_redirect_handler_follows_the_normalized_target(self):
# Redirect targets inherit the normalization (#633): the
# handler validates the raw Location and fetches the form
# validate_crawl_url returns.
import urllib.request

handler = app._ValidatingRedirectHandler()
req = urllib.request.Request("http://example.com/")
followed = handler.redirect_request(
req, None, 302, "Found", {}, "http://EXAMPLE.org:80/a/../b"
)
self.assertEqual(followed.full_url, "http://example.org/b")

def test_percent_encodes_non_ascii_outside_the_host(self):
# WHATWG percent-encodes non-ASCII characters in the userinfo,
# path, query and fragment as UTF-8; urlparse hands them through
Expand Down Expand Up @@ -1190,6 +1262,30 @@ def test_fetches_percent_encoded_c0_targets(self):
self.assertEqual(status, 200)
self.assertIn(b"Missing Thing", raw)

def test_fetches_the_resolved_path_for_dot_segment_targets(self):
# #633: do_POST fetches the URL validate_crawl_url returns, so
# a dot-segment target must reach the server in its resolved
# form — the same path the Worker's WHATWG fetch requests —
# not the verbatim spelling urllib used to send. (Validation
# refuses loopback targets by design, so the validated public
# URL's origin is swapped for the local server's, keeping the
# exact validated path the container would fetch.)
validated = app.validate_crawl_url("http://example.com/a/../b")
self.assertEqual(validated, "http://example.com/b")
local = validated.replace("http://example.com", f"http://127.0.0.1:{self.port}")
self.seen.clear()
status, raw = app._fetch_crawl(local)
self.assertEqual(status, 200)
self.assertIn(b"Missing Thing", raw)
self.assertEqual(self.seen, [("/b", None)])
validated = app.validate_crawl_url("http://example.com/%2e%2e/admin")
self.assertEqual(validated, "http://example.com/admin")
local = validated.replace("http://example.com", f"http://127.0.0.1:{self.port}")
self.seen.clear()
status, _ = app._fetch_crawl(local)
self.assertEqual(status, 200)
self.assertEqual(self.seen, [("/admin", None)])

def test_fetches_userinfo_targets_with_basic_auth(self):
# #622: every userinfo spelling both validators accept 502'd
# in the container — urllib kept "user@host" as the hostname
Expand Down
Loading