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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Add a host-gated `SITE_JS_PATCHES` mechanism to `JsRewriter`, fixing MDN's `<interactive-example>` widget missing a deterministic `permalink` attribute (#394)
- Polyfill `crypto.randomUUID()` when missing in a non-secure context (plain HTTP, non-`localhost`) (#391)
- Polyfill `crypto.subtle.digest()` (SHA-1/SHA-256) when missing in a non-secure context (#393)
- `ArticleUrlRewriter.normalize()` no longer decodes a percent-encoded `/` (`%2F`) in the path into a literal `/`, fixing a content collision between e.g. `/foo%2Fbar` (one segment, containing a literal `/`) and `/foo/bar` (two segments), which used to normalize to the same ZIM path (#396)
- `ArticleUrlRewriter.escape_dot_segments()` now also escapes a literal `_.`/`_..` (and further escaped forms like `__.`/`__..`) segment with one more leading `_`, fixing a content collision with the escaped form of an actual `.`/`..` dot-segment, which used to normalize to the same ZIM path (#396)

### Changed

Expand Down
60 changes: 54 additions & 6 deletions src/zimscraperlib/rewriting/url_rewriting.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,13 @@
might be absorbed by a web server, ...
. This is valid : "foo/part with space/bar?key=value"
. This is NOT valid : "foo/part%20with%20space/bar%3Fkey%3Dvalue"
- the one exception is a percent-encoded `/` (`%2F`) in the path: it is kept encoded
(as `%2F`, uppercase) instead of being decoded to a literal `/`, because decoding it
would make it indistinguishable from an actual path separator. Without this
exception, two genuinely different resources would normalize to the same ZIM path:
"/foo%2Fbar" (one segment, containing a literal `/`) and "/foo/bar" (two segments)
are both valid ZIM paths on their own, but they must stay distinct, as
"foo%2Fbar" and "foo/bar" respectively, instead of both becoming "foo/bar"
- even having multiple ? in a ZIM path is valid
. This is valid :
"foo/part/file with ? and +?who=Chip&Dale&question=It there any + here?"
Expand All @@ -30,8 +37,13 @@
either disappear or be misinterpreted as a navigation instruction instead of being
kept as a literal entry name. Such segments are therefore escaped by prefixing them
with a `_`, e.g. path `a/../b` becomes `a/_../b`. This only applies to segments that
are exactly `.` or `..`; look-alikes such as `a/foo../b` or `a/..foo/b` are left
untouched since they are not dot-segments.
are exactly zero or more `_` followed by exactly `.` or `..`; look-alikes such as
`a/foo../b` or `a/..foo/b` are left untouched since they are not dot-segments. A
segment that is already of this escaped form in the original URL (e.g. a literal `_.`
or `_..` segment) is escaped the same way, with one more leading `_`, so it never
collides with the escaped form of an actual dot-segment: `.` becomes `_.`, a literal
`_.` becomes `__.`, a literal `__.` becomes `___.`, and so on (the same ladder applies
to `..`: `_..` becomes `__..`, a literal `__..` becomes `___..`, and so on).

On top of that, fuzzy rules are applied on the ZIM path:
For instance a path "https://www.youtube.com/youtubei/v1/foo/baz/things?key=value
Expand Down Expand Up @@ -79,6 +91,28 @@ class AdditionalRule:
]


_ENCODED_SLASH_RX = re.compile(r"%2f", re.IGNORECASE)


def _unquote_path(path: str) -> str:
"""Unquote a path, keeping a percent-encoded '/' (`%2F`) encoded

Unlike a plain `unquote(path)`, an encoded `/` is left encoded (normalized to
uppercase `%2F`) instead of being decoded to a literal `/`, so that it stays
distinguishable from an actual path separator: decoding it would otherwise
collide two genuinely different resources into the same ZIM path, e.g.
"/foo%2Fbar" (one segment, containing a literal `/`) and "/foo/bar" (two
segments) would otherwise both become "foo/bar".

The path is split on the still-encoded `%2F` occurrences first, and each piece
is unquoted independently, rather than decoding everything except `%2F` in a
single pass. `%2F` being a fixed-width, ASCII-only percent-triplet, splitting on
it this way can never cut into a different, multi-byte percent-encoded
sequence, so each piece is always a complete, independently decodable run.
"""
return "%2F".join(unquote(part) for part in _ENCODED_SLASH_RX.split(path))


def _remove_dot_segments(path: str) -> str:
"""Remove '.' and '..' segments from a path, per RFC 3986 section 5.2.4

Expand Down Expand Up @@ -447,6 +481,11 @@ def _relative_path(cls, path: str, start: str) -> str:
relative_path = "./" + relative_path
return relative_path

#: A segment which is a run of zero or more `_` followed by exactly one or two
#: `.`: either an actual dot-segment (no leading `_`) or a previous application
#: of this same escaping (one or more leading `_`).
_DOT_SEGMENT_RX: ClassVar[re.Pattern[str]] = re.compile(r"^_*\.{1,2}$")

@classmethod
def escape_dot_segments(cls, path: str) -> str:
"""Escape '.' and '..' path segments so they are not resolved as navigation
Expand All @@ -456,11 +495,18 @@ def escape_dot_segments(cls, path: str) -> str:
keep such a segment as a literal entry name instead, so it is prefixed with
a `_`, which is not itself special in a ZIM path.

A segment which is already of this escaped form in the original URL (e.g. a
literal `_.` or `_..` segment) is escaped the same way, with one more
leading `_` (e.g. `_.` becomes `__.`, and a further literal `__.` would
become `___.`), so that it never collides with the escaped form of an
actual dot-segment.

Segments which only look like a dot-segment (e.g. `foo..`, `..foo`, `...`)
are not dot-segments and are left untouched.
"""
return "/".join(
f"_{part}" if part in (".", "..") else part for part in path.split("/")
f"_{part}" if cls._DOT_SEGMENT_RX.match(part) else part
for part in path.split("/")
)

@classmethod
Expand Down Expand Up @@ -501,7 +547,8 @@ def normalize(cls, url: HttpUrl) -> ZimPath:
path is not encoded at all, as required by the ZIM specification.

Decoding is done differently for the hostname (decoded with puny encoding) and
the path and querystring (both decoded with url decoding).
the path and querystring (both decoded with url decoding), except for an
encoded '/' (%2F) in the path which is kept encoded, see `_unquote_path`.

The final transformation is the application of fuzzy rules (sourced from wabac)
to transform some URLs into replay URLs and drop some useless stuff.
Expand All @@ -528,8 +575,9 @@ def normalize(cls, url: HttpUrl) -> ZimPath:

if path:
# unquote the path so that it is stored unencoded in the ZIM as required by
# ZIM specification
path = unquote(path)
# ZIM specification, except for an encoded '/' (%2F) which is kept encoded,
# see `_unquote_path`
path = _unquote_path(path)
else:
# if path is empty, we need a "/" to remove ambiguities, e.g.
# https://example.com and https://example.com/ must all lead to the same ZIM
Expand Down
56 changes: 56 additions & 0 deletions tests/rewriting/test_url_rewriting.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
RewriteResult,
ZimPath,
_remove_dot_segments, # pyright: ignore[reportPrivateUsage]
_unquote_path, # pyright: ignore[reportPrivateUsage]
_urljoin, # pyright: ignore[reportPrivateUsage]
)

Expand Down Expand Up @@ -129,6 +130,33 @@ class TestNormalize:
("https://example.com/foo../bar", "example.com/foo../bar"),
("https://example.com/..foo/bar", "example.com/..foo/bar"),
("https://example.com/...", "example.com/..."),
# a literal `_.`/`_..` segment is escaped the same way, with one more
# leading `_`, so it never collides with the escaped form of an actual
# dot-segment
("https://example.com/a/_./b", "example.com/a/__./b"),
("https://example.com/a/_../b", "example.com/a/__../b"),
("https://example.com/a/__./b", "example.com/a/___./b"),
# an encoded `/` (%2F) in the path is kept encoded (and normalized to
# uppercase) instead of being decoded to a literal `/`, so it stays
# distinguishable from an actual path separator
(
"http://example.com/foo%2Fbar",
"example.com/foo%2Fbar",
),
(
"http://example.com/foo%2fbar",
"example.com/foo%2Fbar",
),
(
"http://example.com/foo/bar",
"example.com/foo/bar",
),
# other percent-encoded characters around an encoded `/`, including
# multi-byte UTF-8 sequences, are still properly decoded
(
"http://example.com/r%C3%A9sum%C3%A9%2Fr%C3%A9sum%C3%A9",
"example.com/résumé%2Frésumé",
),
],
)
def test_normalize(self, url: str, zim_path: str):
Expand All @@ -153,6 +181,18 @@ class TestEscapeDotSegments:
("a/foo../b", "a/foo../b"),
("a/..foo/b", "a/..foo/b"),
("a/.../b", "a/.../b"),
# a literal `_.`/`_..` segment (i.e. already of the escaped form) is
# escaped the same way, with one more leading `_`, forming a ladder that
# never collides across levels
("a/_./b", "a/__./b"),
("a/_../b", "a/__../b"),
("a/__./b", "a/___./b"),
("a/__../b", "a/___../b"),
("_.", "__."),
("_..", "__.."),
# three dots is not a dot-segment and is never escaped, so a literal
# `_...` segment is never produced by this escaping and stays untouched
("a/_.../b", "a/_.../b"),
],
)
def test_escape_dot_segments(self, path: str, expected: str):
Expand Down Expand Up @@ -1369,6 +1409,22 @@ def test_remove_dot_segments_rejects_path_without_leading_slash():
_remove_dot_segments("foo/bar")


@pytest.mark.parametrize(
"path,expected",
[
("/foo/bar", "/foo/bar"),
("/foo%2Fbar", "/foo%2Fbar"),
("/foo%2fbar", "/foo%2Fbar"), # normalized to uppercase
("/foo%2F%2Fbar", "/foo%2F%2Fbar"),
("/r%C3%A9sum%C3%A9%2Fr%C3%A9sum%C3%A9", "/résumé%2Frésumé"),
("/%24%2F%24", "/$%2F$"),
("", ""),
],
)
def test_unquote_path(path: str, expected: str):
assert _unquote_path(path) == expected


def _resolve_relative_reference(base_url: str, reference: str) -> str:
"""Resolve a relative-path reference as browsers do (RFC 3986 section 5.2)

Expand Down