mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-25 01:16:18 -05:00
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 <noreply@anthropic.com>
This commit is contained in:
parent
7adef5d43e
commit
5802f245c0
3 changed files with 47 additions and 17 deletions
|
|
@ -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
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -1493,3 +1493,23 @@ async def test_html_to_readability_data_uris(test_directory):
|
|||
f'<img src="data:image/svg+xml,%3Csvg%3E%3C/svg%3E">'
|
||||
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'<p>WROLPIDATAURI0X WROLPIDATAURI99X</p><img src="data:image/png;base64,{png}">'
|
||||
|
||||
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'
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue