Search / tests /backend /test_security.py
vomebook
Preserve backend coverage proof and align Reader release fixtures
32e3f00
Raw History Blame Contribute Delete
10.3 kB
from __future__ import annotations
import unittest
IMPORT_ERROR = None
try:
from backend import app
except ModuleNotFoundError as exc: # pragma: no cover
app = None
IMPORT_ERROR = exc
@unittest.skipIf(app is None, f"app dependencies unavailable: {IMPORT_ERROR}")
class SecurityContractTests(unittest.TestCase):
def test_download_host_allowlist_rejects_confusable_hosts(self):
allowed = ["https://huggingface.co/x", "https://datasets.huggingface.co/x", "https://hf-mirror.com/x"]
rejected = ["http://huggingface.co/x", "https://huggingface.co.evil.test/x", "https://huggingface.co:444/x", "https://user@huggingface.co/x"]
for url in allowed:
self.assertEqual(app.validate_download_url(url), url)
for url in rejected:
with self.assertRaises(ValueError):
app.validate_download_url(url)
def test_voiceofml_source_scope_and_mirror_normalization(self):
self.assertEqual(app.validate_voiceofml_source_url("https://hf-mirror.com/datasets/VoiceOfML/A/resolve/main/x"), "https://huggingface.co/datasets/VoiceOfML/A/resolve/main/x")
rejected = [
"https://huggingface.co/datasets/Other/A/resolve/main/x",
"https://huggingface.co/datasets/VoiceOfML/%2e%2e/Other/resolve/main/x",
"https://huggingface.co/datasets/VoiceOfML/../Other/resolve/main/x",
"https://huggingface.co/datasets/VoiceOfML/A/resolve/main/x?download=1",
"https://huggingface.co/datasets/VoiceOfML/A/resolve/main/x#fragment",
"https://huggingface.co/datasets/VoiceOfML/A/resolve/main/a%5cb",
"https://huggingface.co/datasets/VoiceOfML/A/resolve/main/%252e%252e/secret",
"https://huggingface.co/datasets/VoiceOfML/A/resolve/main/%255csecret",
"https://huggingface.co/datasets/VoiceOfML/A/resolve/main/%2500secret",
]
for url in rejected:
with self.subTest(url=url), self.assertRaises(ValueError):
app.validate_voiceofml_source_url(url)
def test_reader_source_scope_is_limited_to_voiceofml_originals(self):
original = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/%E4%B9%A6.txt"
raw = "https://huggingface.co/datasets/VoiceOfML/Test/raw/main/%E4%B9%A6.txt"
self.assertEqual(app.validate_reader_source_url(original), original)
self.assertEqual(app.validate_reader_source_url(raw), raw)
# The deleted vomebook/Reader-Assets dataset is no longer a Reader source,
# including object paths it formerly accepted; converted assets use buckets.
root = "https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/"
asset = root + "objects/aa/" + "b" * 64 + "/libreoffice-pdf-v2/document.pdf"
chapter_base = root + "objects/aa/" + "b" * 64 + "/foliate-original-v1/epub-chapters"
removed = [
asset,
root + "objects/aa/" + "b" * 64 + "/page-manifest.json",
root + "objects/aa/" + "b" * 64 + "/pages/page-000001.webp",
root + "objects/aa/" + "b" * 64 + "/docx-native-v1/document.docx",
root + "objects/aa/" + "b" * 64 + "/sanitized-html-v1/document.html",
root + "objects/aa/" + "b" * 64 + "/ffmpeg-video-mp4-h264-aac-v1/video.mp4",
chapter_base + "/chapter-manifest.json",
chapter_base + "/chapters/chapter-0001.xhtml",
chapter_base + "/resources/OEBPS/images/x.png",
chapter_base + "/resources/style.css",
chapter_base + "/epub-search-index.json.gz",
root + "pdf_manifest.json",
root + "reader_assets.json.gz",
asset.replace("huggingface.co", "hf-mirror.com", 1),
asset.replace("/vomebook/", "/%2576omebook/", 1),
]
rejected = [
"https://huggingface.co/datasets/Other/Test/resolve/main/book.pdf",
original + "?download=1",
original.replace("/main/", "/dev/"),
original.replace("%E4%B9%A6.txt", "%2e%2e/secret.txt"),
chapter_base + "/resources/%2e%2e/secret.png",
asset + "?download=1",
]
for url in removed + rejected:
with self.subTest(url=url), self.assertRaises(ValueError):
app.validate_reader_source_url(url)
def test_reader_accepts_only_fixed_revision_pdf_or_djvu_sources(self):
from backend import upstream_http
prefix = 'https://huggingface.co/datasets/VoiceOfML/Test/resolve/'
revision = 'a' * 40
for name in ('%E4%B9%A6.pdf', 'dir/book.djvu'):
url = prefix + revision + '/' + name
self.assertEqual(upstream_http.validate_reader_source_url(url), url)
for url in (prefix + 'mainly/book.pdf', prefix + 'a' * 39 + '/book.pdf',
prefix + revision + '/book.txt', prefix + revision + '/../book.pdf',
prefix + revision + '/%252e%252e/book.pdf', prefix + revision + '/a//book.pdf',
prefix + revision + '/book%3Fother.pdf', prefix + revision + '/book%23other.pdf',
prefix + revision + '/book.pdf?download=1', prefix + revision + '/book.pdf#x',
'https://huggingface.co/datasets/Other/Test/resolve/' + revision + '/book.pdf',
'https://huggingface.co:444/datasets/VoiceOfML/Test/resolve/' + revision + '/book.pdf'):
with self.subTest(url=url), self.assertRaises(ValueError):
upstream_http.validate_reader_source_url(url)
def test_reader_asset_object_path_grammar_stays_strict(self):
# Sidecar object paths keep the grammar formerly enforced on dataset URLs.
root = "objects/aa/" + "b" * 64
chapters = root + "/foliate-original-v1/epub-chapters"
for path in (
root + "/libreoffice-pdf-v2/document.pdf", root + "/page-manifest.json",
root + "/pages/page-000001.webp", root + "/docx-native-v1/document.docx",
root + "/sanitized-html-v1/document.html", root + "/ffmpeg-video-mp4-h264-aac-v1/video.mp4",
chapters + "/chapter-manifest.json", chapters + "/chapters/chapter-0001.xhtml",
chapters + "/resources/OEBPS/images/x.png", chapters + "/epub-search-index.json.gz",
):
with self.subTest(path=path):
self.assertIsNotNone(app.READER_ASSET_PATH_RE.fullmatch(path))
for path in (
chapters + "/chapters/chapter-1.xhtml", chapters + "/chapters/chapter-0001.txt",
chapters + "/other/evil.xhtml", chapters + "/chapter-manifest.json/extra",
root + "/libreoffice-pdf-v2/document.pdf/extra", root + "/pages/page-000001.png",
root + "/pages/page-1.webp", "reader_assets.json.gz",
):
with self.subTest(path=path):
self.assertIsNone(app.READER_ASSET_PATH_RE.fullmatch(path))
def test_reader_bucket_redirects_allow_only_source_or_signed_storage(self):
source = "https://huggingface.co/buckets/vomebook/pdf-pages-v2/resolve/derived/x/document.pdf"
allowed = [source, "https://cas-bridge.xethub.hf.co/xet-bridge-us/signed",
"https://cdn-lfs.hf.co/signed", "https://us.aws.cdn.hf.co/signed"]
rejected = [
"https://attacker.hf.co/secret", "https://unknown.xethub.hf.co/x",
"https://datasets.huggingface.co/x", "https://hf-mirror.com/x",
"https://huggingface.co/buckets/vomebook/reader-assets-v2/resolve/other.pdf",
"https://cas-bridge.xethub.hf.co:444/x", "http://cas-bridge.xethub.hf.co/x",
"https://user@cas-bridge.xethub.hf.co/x", "https://cas-bridge.xethub.hf.co/x#fragment",
]
for url in allowed:
self.assertEqual(app.validate_reader_bucket_redirect_url(url, source), url)
for url in rejected:
with self.subTest(url=url), self.assertRaises(ValueError):
app.validate_reader_bucket_redirect_url(url, source)
def test_archive_name_sanitization_removes_paths_controls_and_limits_length(self):
self.assertEqual(app.sanitize_archive_name("../../secret\x00\\book.pdf"), "book.pdf")
self.assertEqual(len(app.sanitize_archive_name("x" * 500)), app.MAX_ARCHIVE_NAME_LENGTH)
self.assertEqual(app.sanitize_archive_name("../"), "file")
self.assertEqual(app.sanitize_archive_name("书" * 500 + ".DjVu"),
"书" * (app.MAX_ARCHIVE_NAME_LENGTH - 5) + ".DjVu")
from backend.download.domain.filename import sanitize_archive_name
self.assertEqual(sanitize_archive_name("verylong.extension", 4), "very")
self.assertEqual(sanitize_archive_name("verylong.", 4), "very")
def test_archive_name_matches_original_with_live_length_limit(self):
import ast
import hashlib
from pathlib import Path
from unittest.mock import patch
from backend.download.domain.filename import sanitize_archive_name
source = (Path(__file__).resolve().parents[2]
/ 'scripts/coverage-anchors/backend-typing-new-app.py.snapshot').read_bytes()
self.assertEqual(hashlib.sha256(source).hexdigest(),
'02350a36d2f22c20ba82bfedae564b7b6186ec3d884952e9ccd33f3ed6122b98')
node = next(node for node in ast.parse(source).body
if isinstance(node, ast.FunctionDef) and node.name == 'sanitize_archive_name')
for limit in (1, 12, 240):
namespace = {'MAX_ARCHIVE_NAME_LENGTH': limit}
exec(compile(ast.Module(body=[node], type_ignores=[]), '<original-filename>', 'exec'), namespace)
for value in (None, False, 0, '../', '.', '..', ' ', '../../secret\x00\\book.pdf',
"书 '%.pdf\r\n", 'a\x7fb', '书' * 500):
with self.subTest(limit=limit, value=value), patch.object(app, 'MAX_ARCHIVE_NAME_LENGTH', limit):
expected = namespace['sanitize_archive_name'](value)
self.assertEqual(app.sanitize_archive_name(value), expected)
self.assertEqual(sanitize_archive_name(value, limit), expected)
if __name__ == "__main__":
unittest.main()