repos: harden README search against untrusted READMEs

A README comes from an untrusted remote.

* Escape the README headline: snippet() marks matches with control
  characters, the text is HTML-escaped, then the markers become <b>.
  Headlines are rendered as HTML (HeadlineText).
* Never follow a symlinked README (O_NOFOLLOW, regular files only).
* Convert markdown line by line with linear-time patterns.  The old
  multiline patterns backtracked polynomially; a README of blank lines
  never finished, and runs of `<!--`, `![` or `<` were quadratic.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Roland 2026-10-06 11:07:36 -06:00
parent 5c80ad7ba4
commit 5506dc0a88
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
2 changed files with 129 additions and 19 deletions

View file

@ -1,8 +1,10 @@
import asyncio
import html
import os
import pathlib
import re
import shutil
import stat
from dataclasses import dataclass, field
from typing import List, Optional, Tuple
from urllib.parse import urlparse
@ -174,32 +176,66 @@ def find_readme(directory: pathlib.Path) -> Optional[str]:
MARKDOWN_SUFFIXES = ('.md', '.markdown')
MARKDOWN_PATTERNS = [
(re.compile(r'<!--.*?-->', re.DOTALL), ' '),
(re.compile(r'<[^>\n]+>'), ' '), # HTML tags.
(re.compile(r'^\s*\[[^\]]+\]:\s*\S+.*$', re.MULTILINE), ''), # Link reference definitions.
(re.compile(r'!\[([^\]]*)\]\([^)]*\)'), r'\1'), # Images (and badges) become their alt text.
(re.compile(r'\[([^\]]*)\]\([^)]*\)'), r'\1'), # Links become their text.
(re.compile(r'^\s*(```|~~~).*$', re.MULTILINE), ''), # Code fences.
(re.compile(r'^\s{0,3}#{1,6}\s*', re.MULTILINE), ''), # Headings.
(re.compile(r'^\s{0,3}>\s?', re.MULTILINE), ''), # Block quotes.
(re.compile(r'^\s*\|?[\s:|-]+\|[\s:|-]*$', re.MULTILINE), ''), # Table separator rows.
# A README is untrusted; every pattern here must run in linear time. Each bracketed run stops at the next
# opening bracket, so scans from different starting points never overlap.
INLINE_MARKDOWN_PATTERNS = [
(re.compile(r'<[^<>\n]*>'), ' '), # HTML tags.
(re.compile(r'!\[([^\[\]\n]*)\]\([^()\n]*\)'), r'\1'), # Images (and badges) become their alt text.
(re.compile(r'\[([^\[\]\n]*)\]\([^()\n]*\)'), r'\1'), # Links become their text.
(re.compile(r'[*`|]+'), ' '), # Emphasis, inline code, table cells.
(re.compile(r'[ \t]+'), ' '),
(re.compile(r'\n\s*\n+'), '\n'),
]
HEADING_RE = re.compile(r'#{1,6}(?=\s|$)')
LINK_REFERENCE_RE = re.compile(r'\[[^\[\]]+\]:\s')
TABLE_SEPARATOR_CHARACTERS = set('|:- \t')
def _remove_html_comments(text: str) -> str:
parts, position = [], 0
while (comment := text.find('<!--', position)) != -1:
parts.append(text[position:comment])
end = text.find('-->', comment + 4)
if end == -1:
return ''.join(parts)
parts.append(' ')
position = end + 3
parts.append(text[position:])
return ''.join(parts)
def markdown_to_text(text: str) -> str:
"""Remove markdown syntax so search snippets read as plain text."""
lines = []
for line in _remove_html_comments(text).splitlines():
stripped = line.strip()
if stripped.startswith(('```', '~~~')) or LINK_REFERENCE_RE.match(stripped):
continue
if '-' in stripped and set(stripped) <= TABLE_SEPARATOR_CHARACTERS:
continue # A table separator row, or a horizontal rule.
stripped = stripped.lstrip('>').strip()
if heading := HEADING_RE.match(stripped):
stripped = stripped[heading.end():].strip()
for pattern, replacement in INLINE_MARKDOWN_PATTERNS:
stripped = pattern.sub(replacement, stripped)
if stripped := stripped.strip():
lines.append(stripped)
return '\n'.join(lines)
def read_readme_text(path: pathlib.Path) -> Optional[str]:
"""Read a README as plain text for search; markdown syntax is removed so snippets read well."""
"""Read a README as plain text for search; markdown syntax is removed so snippets read well.
A symlink is never followed (it could point outside the repo)."""
try:
with path.open('rb') as fh:
text = fh.read(FILE_MAX_TEXT_SIZE).decode(errors='replace')
except (FileNotFoundError, IsADirectoryError):
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
except OSError:
return None
with os.fdopen(fd, 'rb') as fh:
if not stat.S_ISREG(os.fstat(fh.fileno()).st_mode):
return None
text = fh.read(FILE_MAX_TEXT_SIZE).decode(errors='replace')
if path.suffix.lower() in MARKDOWN_SUFFIXES:
for pattern, replacement in MARKDOWN_PATTERNS:
text = pattern.sub(replacement, text)
text = markdown_to_text(text)
return text.strip() or None
@ -364,7 +400,8 @@ def _repo_search_sql(search_str: Optional[str], tag_names: Optional[List[str]])
if len(tag_names) > 1:
# A Repo has one Tag.
return None
search = fts.repository_search_join(search_str) if search_str else None
search = fts.repository_search_join(search_str, start=HIGHLIGHT_START, stop=HIGHLIGHT_STOP) \
if search_str else None
if search is None and (search_str and search_str.strip() or not tag_names):
# Nothing usable to search, or nothing to filter by.
return None
@ -400,10 +437,22 @@ def search_repos(session: Session, search_str: str = None, tag_names: List[str]
repos = session.query(Repository).options(*Repository.json_options()) \
.filter(Repository.id.in_([i[0] for i in rows])).all()
repos = {i.id: i for i in repos}
results = [dict(repos[id_].__json__(), readme_headline=headline) for id_, headline, _ in rows if id_ in repos]
results = [dict(repos[id_].__json__(), readme_headline=_safe_headline(headline))
for id_, headline, _ in rows if id_ in repos]
return results, rows[0][2]
# Highlight markers which cannot be confused with HTML. See `_safe_headline`.
HIGHLIGHT_START, HIGHLIGHT_STOP = '\x02', '\x03'
def _safe_headline(headline: Optional[str]) -> Optional[str]:
"""A README is untrusted and its headline is rendered as HTML: escape it, then mark the matches with <b>."""
if not headline:
return headline
return html.escape(headline).replace(HIGHLIGHT_START, '<b>').replace(HIGHLIGHT_STOP, '</b>')
def count_repos(session: Session, search_str: str = None, tag_names: List[str] = None) -> int:
"""The number of Repos `search_repos` would find."""
query = _repo_search_sql(search_str, tag_names)

View file

@ -1,5 +1,6 @@
import json
import sqlite3
import time
from http import HTTPStatus
import pytest
@ -127,3 +128,63 @@ async def test_search_api(test_session, async_client, test_wrolpi_config):
request, response = await async_client.post('/api/search_suggestions', content=json.dumps(dict(search_str='kiw')))
assert response.json['repos'] == [
dict(id=kiwix.id, name='kiwix-tools', tag_name='software', location=f'/repos/{kiwix.id}')]
@pytest.mark.asyncio
async def test_readme_headline_is_escaped(test_session, async_client, test_wrolpi_config):
"""A README comes from an untrusted remote; its headline is rendered as HTML, so only the highlight is markup."""
repo = lib.create_repository(test_session, 'https://github.com/a/b')
set_readme(test_session, repo, 'zim <img src=x onerror="alert(1)"> &amp; <b>bold</b>')
repos, _ = lib.search_repos(test_session, 'zim')
assert repos[0]['readme_headline'] == \
'<b>zim</b> &lt;img src=x onerror=&quot;alert(1)&quot;&gt; &amp;amp; &lt;b&gt;bold&lt;/b&gt;'
def test_read_readme_text_refuses_symlinks(tmp_path):
secret = tmp_path / 'secret.txt'
secret.write_text('secret')
readme = tmp_path / 'README.md'
readme.symlink_to(secret)
assert lib.read_readme_text(readme) is None
assert lib.find_readme(tmp_path) is None
@pytest.mark.parametrize('text', [
'|' + ' ' * 100_000 + 'x',
'-' * 100_000 + 'x',
'<!--' * 25_000,
'![' * 50_000,
'[' * 50_000 + '(' * 50_000,
'<' * 100_000,
'\n' + ' \n' * 50_000 + 'x',
'#' * 100_000,
'> ' * 50_000,
])
def test_markdown_to_text_is_linear(text):
"""A README is untrusted; converting the largest README must never take long."""
start = time.monotonic()
lib.markdown_to_text(text)
assert time.monotonic() - start < 1
def test_markdown_to_text():
readme = '''# Kiwix Tools <!-- hidden
comment -->
[![CI](https://x/badge.svg)](https://ci) **Kiwix** is an *offline* reader. See [the docs](https://docs).
| a | b |
|---|---|
| 1 | 2 |
```bash
kiwix-serve --port 80
```
> quoted
[ref]: https://example.com
---
#hashtag
'''
assert lib.markdown_to_text(readme) == \
'Kiwix Tools\nCI Kiwix is an offline reader. See the docs.\na b\n1 2\nkiwix-serve --port 80\nquoted\n#hashtag'