From 5802f245c0e1e777e8ab83b024166825ea0269e3 Mon Sep 17 00:00:00 2001 From: Roland Date: Thu, 15 Oct 2026 18:07:09 -0600 Subject: [PATCH] Data URI placeholders cannot be forged by page text The placeholder was a fixed string, so a page containing placeholder-like text could index past the payloads (IndexError, failing the archive on the native path) or repeat a placeholder to copy a large image into the output many times. Each extraction now uses a random token, and text that is not a known placeholder is left as-is. Co-Authored-By: Claude Opus 5.5 --- docker/archive/main.py | 21 +++++++++++++-------- modules/archive/lib.py | 23 ++++++++++++++--------- modules/archive/test/test_lib.py | 20 ++++++++++++++++++++ 3 files changed, 47 insertions(+), 17 deletions(-) diff --git a/docker/archive/main.py b/docker/archive/main.py index 175d8330..74574340 100644 --- a/docker/archive/main.py +++ b/docker/archive/main.py @@ -12,6 +12,7 @@ import os import os.path import pathlib import re +import secrets import signal import subprocess import sys @@ -190,26 +191,30 @@ async def call_single_file(url, compress: bool = False) -> (bytes, bytes): # The prefix and payload of a base64 data URI. Keep in sync with modules/archive/lib.py. BASE64_DATA_URI = re.compile(rb'(data:[^,;\s"\'()]*(?:;[^,;\s"\'()]*)*;base64,)([A-Za-z0-9+/]+=*)') -DATA_URI_PLACEHOLDER = re.compile(r'WROLPIDATAURI(\d+)X') +DATA_URI_PLACEHOLDER = re.compile(r'WROLPIDATAURI[0-9a-f]{32}N\d+X') -def strip_data_uris(html: bytes) -> (bytes, list): +def strip_data_uris(html: bytes) -> (bytes, dict): """Replace each base64 data URI payload with a placeholder; readability-extractor takes minutes on a - page of large inline images (SingleFile inlines every image). Returns the HTML and the payloads.""" - payloads = list() + page of large inline images (SingleFile inlines every image). Returns the HTML and the payloads by + placeholder. The placeholder holds a random token, so text in the page cannot be mistaken for one.""" + token = secrets.token_hex(16) + payloads = dict() def replace(match): - payloads.append(match.group(2)) - return match.group(1) + f'WROLPIDATAURI{len(payloads) - 1}X'.encode() + placeholder = f'WROLPIDATAURI{token}N{len(payloads)}X' + payloads[placeholder] = match.group(2) + return match.group(1) + placeholder.encode() return BASE64_DATA_URI.sub(replace, html), payloads -def restore_data_uris(readability: dict, payloads: list) -> dict: +def restore_data_uris(readability: dict, payloads: dict) -> dict: """Put the payloads removed by `strip_data_uris` back into the readability output.""" for key, value in readability.items(): if isinstance(value, str): - readability[key] = DATA_URI_PLACEHOLDER.sub(lambda m: payloads[int(m.group(1))].decode(), value) + readability[key] = DATA_URI_PLACEHOLDER.sub( + lambda m: payloads[m.group(0)].decode() if m.group(0) in payloads else m.group(0), value) return readability diff --git a/modules/archive/lib.py b/modules/archive/lib.py index fe3fe4d2..55cc5a2a 100644 --- a/modules/archive/lib.py +++ b/modules/archive/lib.py @@ -5,13 +5,14 @@ import json import os import pathlib import re +import secrets import shlex import tempfile import zipfile from dataclasses import dataclass, field from datetime import datetime from json import JSONDecodeError -from typing import Optional, Tuple, List, Union +from typing import Optional, Tuple, List, Union, Dict from urllib.parse import urlparse import pytz @@ -1560,26 +1561,30 @@ async def search_domains_by_name(session: Session, name: str, limit: int = 5) -> # The prefix and payload of a base64 data URI. Keep in sync with docker/archive/main.py. BASE64_DATA_URI = re.compile(rb'(data:[^,;\s"\'()]*(?:;[^,;\s"\'()]*)*;base64,)([A-Za-z0-9+/]+=*)') -DATA_URI_PLACEHOLDER = re.compile(r'WROLPIDATAURI(\d+)X') +DATA_URI_PLACEHOLDER = re.compile(r'WROLPIDATAURI[0-9a-f]{32}N\d+X') -def strip_data_uris(html: bytes) -> Tuple[bytes, List[bytes]]: +def strip_data_uris(html: bytes) -> Tuple[bytes, Dict[str, bytes]]: """Replace each base64 data URI payload with a placeholder; readability-extractor takes minutes on a - page of large inline images (SingleFile inlines every image). Returns the HTML and the payloads.""" - payloads = list() + page of large inline images (SingleFile inlines every image). Returns the HTML and the payloads by + placeholder. The placeholder holds a random token, so text in the page cannot be mistaken for one.""" + token = secrets.token_hex(16) + payloads = dict() def replace(match): - payloads.append(match.group(2)) - return match.group(1) + f'WROLPIDATAURI{len(payloads) - 1}X'.encode() + placeholder = f'WROLPIDATAURI{token}N{len(payloads)}X' + payloads[placeholder] = match.group(2) + return match.group(1) + placeholder.encode() return BASE64_DATA_URI.sub(replace, html), payloads -def restore_data_uris(readability: dict, payloads: List[bytes]) -> dict: +def restore_data_uris(readability: dict, payloads: Dict[str, bytes]) -> dict: """Put the payloads removed by `strip_data_uris` back into the readability output.""" for key, value in readability.items(): if isinstance(value, str): - readability[key] = DATA_URI_PLACEHOLDER.sub(lambda m: payloads[int(m.group(1))].decode(), value) + readability[key] = DATA_URI_PLACEHOLDER.sub( + lambda m: payloads[m.group(0)].decode() if m.group(0) in payloads else m.group(0), value) return readability diff --git a/modules/archive/test/test_lib.py b/modules/archive/test/test_lib.py index 59d08df6..c912b752 100644 --- a/modules/archive/test/test_lib.py +++ b/modules/archive/test/test_lib.py @@ -1493,3 +1493,23 @@ async def test_html_to_readability_data_uris(test_directory): f'' assert readability['textContent'] == 'Some text' assert readability['title'] == 'Title' + + +@pytest.mark.asyncio +async def test_html_to_readability_forged_placeholder(): + """Placeholder-like text already in a page is not treated as a placeholder; it cannot index past the + payloads or duplicate an image into the output.""" + png = 'iVBORw0KGgo' + 'A' * 5000 + html = f'

WROLPIDATAURI0X WROLPIDATAURI99X

' + + async def fake_run_command(cmd, *args, **kwargs): + page = pathlib.Path(cmd[3]).read_text() + stdout = json.dumps({'content': page, 'textContent': 'WROLPIDATAURI0X WROLPIDATAURI99X'}).encode() + return CommandResult(return_code=0, cancelled=False, stdout=stdout, stderr=b'', elapsed=0) + + with mock.patch('modules.archive.lib.run_command', fake_run_command): + readability = await lib.html_to_readability(html, 'https://example.com') + + assert readability['content'] == html + assert readability['content'].count(png) == 1 + assert readability['textContent'] == 'WROLPIDATAURI0X WROLPIDATAURI99X'