Skip to content
Open
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Fixed

- Recover inline base64 data missing its `data:` scheme prefix (relative, root-relative, HTTP-resolved, `//<mediatype>/...`, and `data://...`) across URL, HTML, and CSS rewriting, skip `__wb_orig_*` and JS module notifications for `data:` URLs, and avoid splitting `srcset` entries on commas inside inline data URIs (openzim/warc2zim#472, #420)

## [5.6.0] - 2026-11-20

### Added
Expand Down
67 changes: 53 additions & 14 deletions src/zimscraperlib/rewriting/html.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
HTTP_EQUIV_REDIRECT_RE = re.compile(
r"^\s*(?P<interval>.*?)\s*;\s*url\s*=\s*(?P<url>.*?)\s*$"
)
_SRCSET_BASE64_MARKER_RE = re.compile(r";base64,", re.IGNORECASE)


class RewritenHtml(NamedTuple):
Expand Down Expand Up @@ -86,9 +87,10 @@ def get_original_attr_values(
(openzim/warc2zim#413).

Nothing is recorded for an attribute that had no value, that rewriting left
alone, or that already carries its original. That last is HTML rewritten
twice: the attribute already present is the true original, and a second
would both duplicate it and win, since a browser takes the first.
alone, that already carries its original, or whose rewritten value starts
with ``data:`` (a recovered ``data:`` URI would otherwise duplicate a large
inline payload and cause wombat's ``getAttribute`` override to return the
broken original).
"""
recorded: list[AttrNameAndValue] = []
for attr_name in WB_ORIG_ATTRIBUTES:
Expand All @@ -99,7 +101,7 @@ def get_original_attr_values(
if not original:
continue
rewritten = get_attr_value_from(rewritten_attrs, attr_name)
if rewritten is None or rewritten == original:
if rewritten is None or rewritten == original or rewritten.startswith("data:"):
continue
recorded.append((orig_name, original))
return recorded
Expand Down Expand Up @@ -659,20 +661,55 @@ def rewrite_href_src_attributes( # noqa: PLR0917
if (
attr_name not in ("href", "src", "poster")
or not attr_value
or attr_value.startswith("data:")
or (attr_value[:5].lower() == "data:" and attr_value[:7].lower() != "data://")
):
return
result = url_rewriter(attr_value, base_href=base_href, rewrite_all_url=tag != "a")
if (
notify_js_module
and result.zim_path is not None
and get_html_rewrite_context(tag=tag, attrs=attrs) == "js-module"
):
notify_js_module(url_rewriter.get_item_path(attr_value, base_href=base_href))
return (
attr_name,
url_rewriter(
attr_value, base_href=base_href, rewrite_all_url=tag != "a"
).rewriten_url,
)
notify_js_module(result.zim_path)
return (attr_name, result.rewriten_url)


def _split_srcset_entries(srcset: str) -> list[str]:
"""Split a srcset attribute into individual image candidate strings.

Unlike ``str.split(",")``, commas inside a ``data:`` URI or introducing the
payload of an unprefixed ``<mediatype>;base64,<payload>`` URI are not treated
as candidate separators.
"""
entries: list[str] = []
pos = 0
length = len(srcset)
while pos < length:
while pos < length and srcset[pos] in " \t\n\r\f,":
pos += 1
if pos >= length:
break
start = pos
ws = pos
while ws < length and srcset[ws] not in " \t\n\r\f":
ws += 1
url_chunk = srcset[start:ws]
if marker := _SRCSET_BASE64_MARKER_RE.search(url_chunk):
search_from = start + marker.end()
elif url_chunk[:5].lower() == "data:":
search_from = ws
while search_from > start and srcset[search_from - 1] == ",":
search_from -= 1
else:
search_from = start

sep = srcset.find(",", search_from)
if sep == -1:
entries.append(srcset[start:].strip())
break
entries.append(srcset[start:sep].strip())
pos = sep + 1
return entries


@rules.rewrite_attribute()
Expand All @@ -685,10 +722,12 @@ def rewrite_srcset_attribute(
"""Rewrite srcset attributes"""
if attr_name != "srcset" or not attr_value:
return
value_list = attr_value.split(",")
value_list = _split_srcset_entries(attr_value)
if not value_list:
return
new_value_list: list[str] = []
for value in value_list:
url, *other = value.strip().split(" ", maxsplit=1)
url, *other = value.split(maxsplit=1)
new_url = url_rewriter(url, base_href=base_href).rewriten_url
new_value = " ".join([new_url, *other])
new_value_list.append(new_value)
Expand Down
98 changes: 98 additions & 0 deletions src/zimscraperlib/rewriting/url_rewriting.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,97 @@
return "%2F".join(quote(part, safe="/") for part in path.split("%2F"))


_BASE64_MARKER_RE = re.compile(r";base64,", re.IGNORECASE)
_MIME_SUBTYPE_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9.+-]*")
_MIME_PARAM_RE = re.compile(r"[A-Za-z0-9-]+(?:=[^\s;]+)?")
_NON_B64_RE = re.compile(r"[^A-Za-z0-9+/]")

# Official IANA top-level media types seen in inline data URIs.
_VALID_MEDIA_TYPES = frozenset(
{
"application",
"audio",
"example",
"font",
"haptics",
"image",
"message",
"model",
"multipart",
"text",
"video",
}
)


def _recover_missing_data_url(item_url: str) -> str | None:

Check notice on line 191 in src/zimscraperlib/rewriting/url_rewriting.py

View check run for this annotation

codefactor.io / CodeFactor

Complex Method

Complexity is 25 (lines 191-256).
"""Recover inline base64 data missing its ``data:`` scheme prefix.

Detects relative (``image/jpeg;base64,...``), root-relative
(``/image/png;base64,...``), HTTP-resolved
(``https://example.com/node/image/jpeg;base64,...``), and malformed
``data://...`` values, stripping any fake prefix and stray whitespace in the
base64 payload. Returns ``None`` when ``item_url`` already has a valid
``data:`` scheme or is not a recognizable malformed inline base64 payload.
"""
prefix_lower = item_url[:7].lower()
if prefix_lower.startswith("data:") and not prefix_lower.startswith("data://"):
return None

marker_match = _BASE64_MARKER_RE.search(item_url)
if not marker_match:
return None

before = item_url[: marker_match.start()]
payload = item_url[marker_match.end() :]

if "?" in before or "#" in before:
return None

parts = urlsplit(before)
if parts.scheme == "data" and before[:7].lower() == "data://":
candidate_path = before[7:].lstrip("/")
elif parts.scheme == "" and parts.netloc.lower() in _VALID_MEDIA_TYPES:
candidate_path = parts.netloc + parts.path
elif parts.scheme in ("", "http", "https"):
candidate_path = parts.path
else:
return None

prefix, sep, subtype_and_params = candidate_path.rpartition("/")
if not sep or not subtype_and_params:
return None
mime_type = prefix.rpartition("/")[2]
if not mime_type:
return None
mediatype = f"{mime_type}/{subtype_and_params}"

subtype_essence, has_params, mime_params = subtype_and_params.partition(";")
if mime_type.lower() not in _VALID_MEDIA_TYPES:
return None
if not _MIME_SUBTYPE_RE.fullmatch(subtype_essence):
return None
if has_params and (
not mime_params
or not all(_MIME_PARAM_RE.fullmatch(param) for param in mime_params.split(";"))
):
return None

stripped_payload = "".join(payload.split())
if not stripped_payload:
return None
if stripped_payload.endswith("=="):
core = stripped_payload[:-2]
elif stripped_payload.endswith("="):
core = stripped_payload[:-1]
else:
core = stripped_payload
if not core or _NON_B64_RE.search(core):
return None

return f"data:{mediatype};base64,{stripped_payload}"


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

Expand Down Expand Up @@ -386,6 +477,13 @@
try:
item_url = item_url.strip()

if (recovered := _recover_missing_data_url(item_url)) is not None:
return RewriteResult(
absolute_url=recovered,
rewriten_url=recovered,
zim_path=None,
)

item_absolute_url = _urljoin(
_urljoin(self.article_url.value, base_href), item_url
)
Expand Down
46 changes: 46 additions & 0 deletions tests/rewriting/test_css_rewriting.py
Original file line number Diff line number Diff line change
Expand Up @@ -280,3 +280,49 @@ def test_unterminated_string_ending_in_escaped_quote():
rewriter.rewrite(r'.test { content: "unterminated\" }')
== r'.test { content: "unterminated\" }}'
)


@pytest.mark.parametrize(
"input_css, expected_css",
[
pytest.param(
"p { background: url(image/png;base64,iVBORw0KGgo=); }",
"p { background: url(data:image/png;base64,iVBORw0KGgo=); }",
id="unquoted_relative_base64",
),
pytest.param(
'p { background: url("image/png;base64,iVBORw0KGgo="); }',
'p { background: url("data:image/png;base64,iVBORw0KGgo="); }',
id="quoted_relative_base64",
),
pytest.param(
"p { background: "
"url('https://istmat.org/node/image/jpeg;base64,/9j/4AAQSkZJRg=='); }",
'p { background: url("data:image/jpeg;base64,/9j/4AAQSkZJRg=="); }',
id="quoted_http_resolved_base64",
),
pytest.param(
"p { background: url(data://image/png;base64,iVBORw0KGgo=); }",
"p { background: url(data:image/png;base64,iVBORw0KGgo=); }",
id="data_double_slash_base64",
),
pytest.param(
'p { background: url("image/png;base64,iVBOR w0KG go="); }',
'p { background: url("data:image/png;base64,iVBORw0KGgo="); }',
id="whitespace_in_base64",
),
pytest.param(
"p { width= } div { background: url(image/png;base64,iVBORw0KGgo=)}",
"p { width= } div { background: url(data:image/png;base64,iVBORw0KGgo=)}",
id="fallback_regex_rewriter_base64",
),
],
)
def test_css_recover_missing_data_prefix(input_css: str, expected_css: str):
assert (
CssRewriter(
ArticleUrlRewriter(article_url=HttpUrl("https://istmat.org/node/42")),
base_href=None,
).rewrite(input_css)
== expected_css
)
Loading