diff --git a/src/services/subtitle_provider.py b/src/services/subtitle_provider.py index b9f71c4..dd27b5d 100644 --- a/src/services/subtitle_provider.py +++ b/src/services/subtitle_provider.py @@ -44,6 +44,7 @@ """ from __future__ import annotations +import json import logging from typing import Optional from src.services.http_client import tls_context @@ -135,15 +136,24 @@ async def fetch_best(*, anidb_id=None, anilist_id=None, tvdb_id=None, "response for %s — not one episode's dialogue", size / 1e6, params) return "" # definitive: this is not usable data - await resp.aread() + # A chunked answer carries no Content-Length: count while + # reading and stop at the cap, so it is never held whole. + buf = bytearray() + async for chunk in resp.aiter_bytes(): + buf += chunk + if len(buf) > _MAX_BYTES: + break + too_big = len(buf) > _MAX_BYTES r = resp + body = bytes(buf) + text = body.decode(r.encoding or "utf-8", errors="replace") # A 404 that returns an HTML error PAGE is a misconfigured base # URL, not an answer about this title. Treating it as "definitively # no subtitles" would stamp the whole library on the strength of a # typo — so anything that smells like a web page is transient, and # says so loudly enough to be found. ctype = (r.headers.get("content-type") or "").lower() - if "html" in ctype or r.text[:200].lstrip().lower().startswith( + if "html" in ctype or text[:200].lstrip().lower().startswith( ("= 400 and "json" in ctype: try: - err = r.json() + err = json.loads(body) except ValueError: err = {} if isinstance(err, dict) and "permanent" in err: @@ -172,11 +182,11 @@ async def fetch_best(*, anidb_id=None, anilist_id=None, tvdb_id=None, r.status_code) return None r.raise_for_status() - txt = r.text or "" - if len(txt) > _MAX_BYTES: # server sent no Content-Length - logger.info("[subtitle-provider] discarding a %.1f MB body " - "for %s", len(txt) / 1e6, params) + if too_big: # server sent no Content-Length + logger.info("[subtitle-provider] refusing a body over %.1f MB " + "for %s", _MAX_BYTES / 1e6, params) return "" + txt = text # A byte-order mark trips naive parsers; strip it defensively even # though a well-behaved service already does. if txt.startswith(""): diff --git a/tests/test_subtitle_provider_cap.py b/tests/test_subtitle_provider_cap.py new file mode 100644 index 0000000..f14c9d6 --- /dev/null +++ b/tests/test_subtitle_provider_cap.py @@ -0,0 +1,107 @@ +"""The self-hosted subtitle service's answer is capped while it streams. + +SECURITY.md ("Bodies from the outside") promises subtitle downloads are read +through a bound enforced *while* streaming, never buffered first and measured +after. ``subtitle_provider.fetch_best`` refused an oversized body only by its +Content-Length; a chunked answer (no Content-Length) was read whole into +memory and only then compared to the cap. These checks drive ``fetch_best`` +against a mock service and count how many bytes it pulled. + + python tests/test_subtitle_provider_cap.py +""" +from _harness import check # noqa: I001 - first: temp stores + +import asyncio + +import httpx + +from src.services import subtitle_provider as prov + +CAP = prov._MAX_BYTES +CHUNK = 64 * 1024 +SRT = "".join(f"{i}\n00:00:{i % 60:02d},000 --> 00:00:{i % 60:02d},900\n" + f"some words spoken here\n\n" for i in range(1, 40)) + + +class _Body(httpx.AsyncByteStream): + """A chunked body of ``total`` bytes that records how much was pulled.""" + + def __init__(self, total, fill=b"x"): + self.total, self.fill, self.pulled = total, fill, 0 + + async def __aiter__(self): + while self.pulled < self.total: + n = min(CHUNK, self.total - self.pulled) + self.pulled += n + yield self.fill * n + + +def _fetch(handler): + """Run fetch_best against ``handler`` (an httpx.MockTransport handler).""" + orig_conf, orig_client = prov._conf, httpx.AsyncClient + prov._conf = lambda: ("http://subs.test/api/v1", "k") + + class _Mocked(orig_client): + def __init__(self, *a, **k): + k["transport"] = httpx.MockTransport(handler) + super().__init__(*a, **k) + + httpx.AsyncClient = _Mocked + try: + return asyncio.run(prov.fetch_best(anidb_id=1, episode=1)) + finally: + prov._conf, httpx.AsyncClient = orig_conf, orig_client + + +def _serve(body, status=200, ctype="text/plain; charset=utf-8"): + return lambda req: httpx.Response(status, headers={"content-type": ctype}, + stream=body) + + +# -- the attack: a 20 MB chunked answer --------------------------------------- +big = _Body(20_000_000) +out = _fetch(_serve(big)) +check("an oversized chunked body is refused as definitive", out == "") +check(f"reading stops at the cap (pulled {big.pulled:,} bytes)", + big.pulled <= CAP + CHUNK) + +# -- the same with a server error: still transient, still bounded -------------- +err = _Body(20_000_000) +out = _fetch(_serve(err, status=500)) +check("an oversized 5xx stays transient", out is None) +check("an oversized 5xx is bounded too", err.pulled <= CAP + CHUNK) + +# -- an oversized HTML error page is a misconfiguration, not a verdict -------- +page = _Body(20_000_000, fill=b"<") +out = _fetch(_serve(page, status=404, ctype="text/html")) +check("an oversized HTML 404 is transient (wrong base URL)", out is None) + +# -- what must keep working ---------------------------------------------------- +class _Text(httpx.AsyncByteStream): + def __init__(self, data): + self.data = data + + async def __aiter__(self): + for i in range(0, len(self.data), 100): + yield self.data[i:i + 100] + + +check("a normal chunked subtitle is returned whole", + _fetch(_serve(_Text(("" + SRT).encode("utf-8")))) == SRT) +check("the response charset is honoured", + _fetch(_serve(_Text(SRT.replace("words", "wörds").encode("latin-1")), + ctype="text/plain; charset=latin-1")) + == SRT.replace("words", "wörds")) +check("a JSON permanent flag still settles the title", + _fetch(lambda req: httpx.Response( + 422, json={"error": "no such title", "permanent": True})) == "") +check("a JSON retryable flag stays transient", + _fetch(lambda req: httpx.Response( + 503, json={"error": "busy", "permanent": False})) is None) +check("a plain 404 is definitive", + _fetch(lambda req: httpx.Response(404, text="")) == "") +check("a Content-Length over the cap is refused before reading", + _fetch(lambda req: httpx.Response( + 200, headers={"content-length": str(CAP + 1)}, stream=_Body(0))) == "") + +check.done()