"""The debug_requests http_request entry in the JSONL debug log and the body files, for both HTTP session types.""" from __future__ import annotations import copy import importlib import json import logging import re import threading from collections.abc import Iterator from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from types import SimpleNamespace from typing import Any import m3u8 import pytest import requests as rq from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry from unshackle.core import service as service_module from unshackle.core import session as http_session from unshackle.core.config import Config, config from unshackle.core.manifests import DASH, HLS from unshackle.core.service import Service from unshackle.core.session import MaxRetriesError, RecordedSession, RnetSession, record_requests, unrecorded from unshackle.core.tracks.track import Track from unshackle.core.utilities import close_debug_logger, init_debug_logger from unshackle.core.utils import bitrate from unshackle.core.utils.xml import load_xml dl = importlib.import_module("unshackle.core.downloaders.requests") pytestmark = pytest.mark.unit BODY = b"x" * 64 class Server(ThreadingHTTPServer): allow_reuse_address = True daemon_threads = True def __init__(self) -> None: self.hits: list[str] = [] self.docs: dict[str, str | bytes] = {} self.types: dict[str, str] = {} self.lock = threading.Lock() super().__init__(("127.0.0.1", 0), Handler) self.host = f"127.0.0.1:{self.server_address[1]}" self.url = f"http://{self.host}" def handle_error(self, request: Any, client_address: Any) -> None: pass class Handler(BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" server: Server def log_message(self, *_: Any) -> None: pass def reply(self) -> None: if length := int(self.headers.get("Content-Length") or 0): self.rfile.read(length) path = self.path.partition("?")[0] with self.server.lock: first = path not in self.server.hits self.server.hits.append(path) if path == "/old": self.send_response(302) self.send_header("Location", "/new") self.send_header("Content-Length", "0") self.end_headers() return if path == "/busy" and first: self.send_response(503) self.send_header("Content-Length", "0") self.end_headers() return ranged = bool(self.headers.get("Range")) and not path.startswith("/plain") body = self.server.docs.get(path, BODY[:1] if ranged else BODY) body = body.encode() if isinstance(body, str) else body if path.startswith("/chunked"): self.send_response(200) self.send_header("Content-Type", self.server.types.get(path, "text/plain")) self.send_header("Transfer-Encoding", "chunked") self.end_headers() self.wfile.write(f"{len(body):x}\r\n".encode() + body + b"\r\n0\r\n\r\n") return self.send_response(206 if ranged else 200) if ranged: self.send_header("Content-Range", f"bytes 0-0/{len(BODY)}") if path in self.server.types: self.send_header("Content-Type", self.server.types[path]) if not (path.startswith("/plain") and self.command == "HEAD"): self.send_header("Content-Length", str(len(body))) self.end_headers() if self.command != "HEAD": self.wfile.write(body) do_GET = do_POST = do_PATCH = do_HEAD = reply @pytest.fixture def server() -> Iterator[Server]: srv = Server() thread = threading.Thread(target=srv.serve_forever, daemon=True) thread.start() yield srv srv.shutdown() srv.server_close() @pytest.fixture def debug_log(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[Path]: monkeypatch.setattr(config, "debug_requests", True) path = tmp_path / "debug.jsonl" init_debug_logger(log_path=path, enabled=True) yield path close_debug_logger() def records(path: Path) -> list[dict]: lines = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()] return [e for e in lines if e.get("operation") == "http_request"] def folder(path: Path) -> Path: return path.with_suffix("") def requests_session() -> rq.Session: session = rq.Session() adapter = HTTPAdapter(max_retries=Retry(total=2, backoff_factor=0, status_forcelist=[503])) session.mount("http://", adapter) record_requests(session) return session def rnet_session() -> RnetSession: session = RnetSession(backoff_factor=0) session.get_sleep_time = lambda *_: 0 # type: ignore[method-assign] return session def closed_port() -> str: srv = Server() srv.server_close() return srv.url SESSIONS = [pytest.param(requests_session, id="requests"), pytest.param(rnet_session, id="rnet")] @pytest.mark.parametrize("make_session", SESSIONS) def test_the_entry_masks_a_secret_query_value_and_names_the_body_file(server, debug_log, make_session): server.types["/api/items"] = "text/plain" make_session().get(f"{server.url}/api/items?id=5&access_token=SECRET123") (entry,) = records(debug_log) assert entry["request"] == { "method": "GET", "host": server.host, "path": "/api/items", "query": "id=5&access_token=***", "attempt": 1, } name = f"0001_GET_{server.host.replace(':', '_')}_items.txt" assert entry["response"] == {"status": 200, "size": len(BODY), "body_file": name} assert entry["duration_ms"] >= 0 assert entry["failure"] is None assert (folder(debug_log) / name).read_bytes() == BODY @pytest.mark.parametrize("make_session", SESSIONS) def test_a_retried_request_writes_one_entry_per_attempt(server, debug_log, make_session): make_session().get(f"{server.url}/busy") entries = records(debug_log) assert [(e["request"]["attempt"], e["response"]["status"]) for e in entries] == [(1, 503), (2, 200)] @pytest.mark.parametrize( ("make_session", "kwargs", "error"), [ pytest.param(requests_session, {}, rq.ConnectionError, id="requests"), pytest.param(rnet_session, {"max_retries": 0}, MaxRetriesError, id="rnet"), ], ) def test_a_failed_attempt_names_the_failure(debug_log, make_session, kwargs, error): with pytest.raises(error): make_session().get(f"{closed_port()}/gone", **kwargs) (entry,) = records(debug_log) assert entry["failure"] assert entry["response"]["status"] is None assert entry["request"]["path"] == "/gone" def test_a_redirect_writes_one_entry_per_hop(server, debug_log): requests_session().get(f"{server.url}/old") assert [(e["request"]["path"], e["response"]["status"]) for e in records(debug_log)] == [ ("/old", 302), ("/new", 200), ] def test_an_rnet_method_outside_the_retry_methods_is_recorded(server, debug_log): RnetSession(allowed_methods={"GET"}).patch(f"{server.url}/edit") (entry,) = records(debug_log) assert (entry["request"]["method"], entry["request"]["path"], entry["response"]["status"]) == ( "PATCH", "/edit", 200, ) @pytest.mark.parametrize("make_session", SESSIONS) def test_segment_and_probe_requests_are_not_recorded(server, debug_log, tmp_path, make_session): session = make_session() list(dl.download(url=f"{server.url}/segment", save_path=tmp_path / "seg.mp4", session=session)) dl.probe_ranged(f"{server.url}/probe", session) session.get(f"{server.url}/api") assert server.hits.count("/segment") == 1 and server.hits.count("/probe") == 1 assert [e["request"]["path"] for e in records(debug_log)] == ["/api"] @pytest.mark.parametrize("built_with_debug_requests", [True, False]) @pytest.mark.parametrize("make_session", SESSIONS) def test_a_debug_run_without_debug_requests_records_nothing( server, debug_log, monkeypatch, make_session, built_with_debug_requests ): monkeypatch.setattr(config, "debug_requests", built_with_debug_requests) session = make_session() monkeypatch.setattr(config, "debug_requests", False) session.get(f"{server.url}/api") session.get(f"{server.url}/busy") assert server.hits.count("/api") == 1 assert records(debug_log) == [] assert not folder(debug_log).exists() assert "session_start" in debug_log.read_text(encoding="utf-8") def test_record_requests_leaves_the_session_alone_without_debug_requests(monkeypatch): monkeypatch.setattr(config, "debug_requests", False) session = rq.Session() record_requests(session) assert type(session) is rq.Session def test_a_recorded_adapter_reads_through_and_copies(debug_log): session = requests_session() adapter = session.get_adapter("http://h") assert adapter.max_retries.total == 2 assert copy.copy(adapter).max_retries.total == 2 def test_the_service_session_records_only_with_debug_requests(monkeypatch): class Stop(Exception): pass stub = type("Stub", (Service,), dict.fromkeys(Service.__abstractmethods__, lambda *_: None)) ctx = SimpleNamespace(obj=SimpleNamespace(config={})) monkeypatch.setattr(service_module, "Cacher", lambda *_: (_ for _ in ()).throw(Stop())) for enabled in (True, False): monkeypatch.setattr(config, "debug_requests", enabled) instance = object.__new__(stub) with pytest.raises(Stop): Service.__init__(instance, ctx) # type: ignore[arg-type] assert isinstance(instance.session, RecordedSession) is enabled assert type(instance.session).__name__ == "TimeoutSession" JWT = "eyJhbGciOi.eyJzdWIi.c2ln" def test_the_rnet_console_line_keeps_the_query(server, debug_log, caplog): with caplog.at_level("DEBUG"): rnet_session().get(f"{server.url}/{JWT}/pts_0.mp4?sig=S2") (line,) = [r.getMessage() for r in caplog.records if " 200 " in r.getMessage()] assert f'"GET /{JWT}/pts_0.mp4?sig=S2 ' in line def body_of( server: Server, debug_log: Path, make_session: Any, path: str, kind: str | None, doc: str | bytes, **kw: Any ) -> tuple[str, bytes] | None: """The response body file name and bytes of one GET, or None when it wrote none.""" server.docs[path] = doc if kind: server.types[path] = kind make_session().get(f"{server.url}{path}", **kw) (entry,) = records(debug_log) name = entry["response"].get("body_file") return (name, (folder(debug_log) / name).read_bytes()) if name else None @pytest.mark.parametrize( ("path", "kind", "doc", "extension"), [ pytest.param("/a.txt", "text/plain", "error inside a 200", ".txt", id="text"), pytest.param( "/api/json", "application/json; charset=utf-8", '{"access_token": "TOKEN_VALUE"}', ".json", id="json" ), pytest.param("/jsonp", "application/x-javascript; charset=utf-8", 'callback({"sub":[]})', ".js", id="jsonp"), pytest.param("/problem", "application/problem+json", '{"title": "x"}', ".json", id="json-suffix"), pytest.param("/a.xml", "application/xml", "", ".xml", id="application-xml"), pytest.param("/error.mpd", "application/json", '{"error": 1}', ".json", id="json-at-manifest-path"), pytest.param("/v.m3u8", "text/plain", "#EXTM3U\n", ".m3u8", id="m3u8-path"), pytest.param("/m.xml", "text/xml", "", ".xml", id="xml"), pytest.param("/no-type", None, "plain words", ".bin", id="no-type"), pytest.param("/latin", "text/plain", "caf\xe9".encode("latin-1"), ".txt", id="not-utf8"), pytest.param("/licence", "application/octet-stream", b"\x08\x04\x12\xff\x00", ".bin", id="binary"), pytest.param("/a.png", "image/png", b"\x89PNG\r\n\x1a\n\x00", ".png", id="image"), pytest.param("/v/manifest.mpd", "application/dash+xml", "", ".mpd", id="mpd"), pytest.param("/master", "application/vnd.apple.mpegurl", "#EXTM3U\n", ".m3u8", id="m3u8"), ], ) @pytest.mark.parametrize("make_session", SESSIONS) def test_each_response_body_is_a_file_with_the_bytes_as_received( server, debug_log, make_session, path, kind, doc, extension ): name, data = body_of(server, debug_log, make_session, path, kind, doc) assert data == (doc if isinstance(doc, bytes) else doc.encode()) assert name.endswith(extension) assert "body" not in records(debug_log)[0]["response"] assert b"TOKEN_VALUE" not in debug_log.read_bytes() @pytest.mark.parametrize( ("path", "kind", "doc", "kw"), [ pytest.param("/api/stream", "application/json", '{"a": 1}', {"stream": True}, id="stream"), pytest.param("/events", "text/event-stream", "data: 1\n\n", {}, id="event-stream"), pytest.param("/empty", "application/json", "", {}, id="empty"), ], ) @pytest.mark.parametrize("make_session", SESSIONS) def test_no_body_file_for_a_streamed_or_empty_response(server, debug_log, make_session, path, kind, doc, kw): assert body_of(server, debug_log, make_session, path, kind, doc, **kw) is None assert not folder(debug_log).exists() @pytest.mark.parametrize( ("kw", "extension"), [ pytest.param({"data": {"username": "EXAMPLE", "password": "P4SSWORD"}}, ".bin", id="form"), pytest.param({"json": {"username": "EXAMPLE", "password": "P4SSWORD"}}, ".json", id="json"), ], ) @pytest.mark.parametrize("make_session", SESSIONS) def test_a_request_body_is_a_file_and_never_in_the_log(server, debug_log, make_session, kw, extension): server.types["/login"] = "application/json" server.docs["/login"] = '{"ok": true}' make_session().post(f"{server.url}/login", **kw) (entry,) = records(debug_log) stem = f"0001_POST_{server.host.replace(':', '_')}_login" assert (entry["request"]["body_file"], entry["response"]["body_file"]) == ( f"{stem}_request{extension}", f"{stem}.json", ) assert b"P4SSWORD" in (folder(debug_log) / entry["request"]["body_file"]).read_bytes() assert (folder(debug_log) / f"{stem}.json").read_bytes() == b'{"ok": true}' assert "P4SSWORD" not in debug_log.read_text(encoding="utf-8") assert "body" not in entry["request"] and "body" not in entry["response"] @pytest.mark.parametrize("make_session", SESSIONS) def test_a_bytes_request_body_is_kept_as_sent(server, debug_log, make_session): session = make_session() session.post(f"{server.url}/api/send", data=b"\x08\x04\x12") session.post(f"{server.url}/api/send") with_body, without_body = records(debug_log) assert (folder(debug_log) / with_body["request"]["body_file"]).read_bytes() == b"\x08\x04\x12" assert "body_file" not in without_body["request"] def test_a_bytes_content_type_never_fails_the_request(server, debug_log): response = requests_session().post( f"{server.url}/api/send", data="{}", headers={"Content-Type": b"application/json"} ) assert response.status_code == 200 assert records(debug_log)[-1]["request"]["body_error"].startswith("TypeError") @pytest.mark.parametrize("make_session", SESSIONS) def test_a_hostile_path_stays_inside_the_folder(server, debug_log, tmp_path, make_session): session = make_session() for path in ("/../..%2f", f"/{'a' * 300}:b*c%7Cd%3C%3E%22%5C"): session.get(f"{server.url}{path}") files = [p for p in tmp_path.rglob("*") if p.is_file()] names = [p.name for p in files if p != debug_log] assert len(names) == 2 assert all(p == debug_log or p.parent == folder(debug_log) for p in files) assert all(re.fullmatch(r"[A-Za-z0-9._-]{1,150}", name) for name in names) assert sorted(e["response"]["body_file"] for e in records(debug_log)) == sorted(names) @pytest.mark.parametrize("make_session", SESSIONS) def test_the_size_comes_from_the_body_without_a_content_length(server, debug_log, make_session): server.docs["/chunked"] = '{"a": 1}' server.types["/chunked"] = "application/json" make_session().get(f"{server.url}/chunked") assert records(debug_log)[-1]["response"]["size"] == len(server.docs["/chunked"]) @pytest.mark.parametrize("make_session", SESSIONS) def test_a_recorded_body_stays_readable_by_the_caller(server, debug_log, make_session): server.docs["/api/read"] = '{"a": 1}' server.types["/api/read"] = "application/json" session = make_session() assert session.get(f"{server.url}/api/read").json() == {"a": 1} assert b"".join(session.get(f"{server.url}/api/read").iter_content(3)) == b'{"a": 1}' with session.get(f"{server.url}/api/read", stream=True) as streamed: assert b"".join(streamed.iter_content(3)) == b'{"a": 1}' @pytest.mark.parametrize("make_session", SESSIONS) def test_a_body_over_the_limit_is_cut_and_marked(server, debug_log, monkeypatch, make_session): monkeypatch.setattr(config, "debug_requests_body_limit", 5) _, data = body_of(server, debug_log, make_session, "/api/long", "application/json", '{"xyzwvu": 1}') response = records(debug_log)[0]["response"] assert (data, response["body_size"], response["body_cut"]) == (b'{"xyz', 13, True) def test_a_failed_body_read_is_recorded_and_raised_again(debug_log): class Broken: status_code = 200 headers = {"content-type": "application/json"} @property def content(self) -> bytes: raise rq.exceptions.ChunkedEncodingError("cut short") response = Broken() with pytest.raises(rq.exceptions.ChunkedEncodingError): http_session.record_request("GET", "http://h/api", 1, response=response, body=True) (entry,) = records(debug_log) assert entry["response"]["body_error"].startswith("ChunkedEncodingError") @pytest.mark.parametrize(("value", "limit"), [(None, 0), ("5", 5), (-5, 0)]) def test_the_body_limit_is_a_byte_count(value, limit): assert Config(debug_requests_body_limit=value).debug_requests_body_limit == limit def serve_starts(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: from aiohttp import web from click.testing import CliRunner from unshackle.commands.serve import serve monkeypatch.setattr(web, "run_app", lambda *a, **kw: None) monkeypatch.setattr(config, "serve", {}) assert CliRunner().invoke(serve, ["--api-only", "--no-key"]).exit_code == 0 def worker_starts(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: from unshackle.core.api import download_worker monkeypatch.setattr(download_worker, "perform_download", lambda *a, **kw: []) monkeypatch.setattr(download_worker, "relay_prompts", lambda *a: None) payload = tmp_path / "payload.json" payload.write_text(json.dumps({"job_id": "j", "service": "EXAMPLE", "title_id": "t"}), encoding="utf-8") assert download_worker.main(["w", str(payload), str(tmp_path / "result.json")]) == 0 @pytest.mark.parametrize("start", [serve_starts, worker_starts], ids=["serve", "job-worker"]) @pytest.mark.parametrize("make_session", SESSIONS) def test_a_server_process_records_no_body(server, debug_log, monkeypatch, tmp_path, make_session, start): start(monkeypatch, tmp_path) make_session().post(f"{server.url}/api/json", json={"a": 1}) assert http_session.record_bodies is False assert records(debug_log)[0]["response"] == {"status": 200, "size": len(BODY)} assert "body_file" not in records(debug_log)[0]["request"] assert not folder(debug_log).exists() def test_serve_keeps_request_lines_out_of_the_dashboard_log(monkeypatch, tmp_path, caplog): from unshackle.core.api.stats import ring serve_starts(monkeypatch, tmp_path) with caplog.at_level(logging.DEBUG): for name in ("RnetSession", "urllib3.connectionpool", "EXAMPLE"): logging.getLogger(name).debug(f"EXAMPLE {name} line ?sig=S1") logging.getLogger("RnetSession").warning("EXAMPLE retry warning") lines = [r["msg"] for r in ring.since(0) if r["msg"].startswith("EXAMPLE")] assert lines == ["EXAMPLE EXAMPLE line ?sig=S1", "EXAMPLE retry warning"] def paths(path: Path) -> list[str]: return [e["request"]["path"] for e in records(path)] @pytest.mark.parametrize("make_session", SESSIONS) def test_hls_media_probes_are_not_recorded_but_the_playlist_is(server, debug_log, make_session): session = make_session() server.docs["/v.m3u8"] = '#EXTM3U\n#EXT-X-MAP:URI="init.mp4",BYTERANGE="1@0"\n#EXTINF:4,\nseg.ts\n#EXT-X-ENDLIST\n' HLS.probe_ts_info(f"{server.url}/v.m3u8", session) playlist = m3u8.loads(server.docs["/v.m3u8"], uri=f"{server.url}/v.m3u8") HLS.fetch_init_section(session, playlist.segments[0].init_section, 0) HLS.get_track_kid_from_init( SimpleNamespace(get_key_id=lambda _: None), # type: ignore[arg-type] HLS.init_reader(playlist, session), playlist.segments[0].init_section, ) assert (server.hits.count("/seg.ts"), server.hits.count("/init.mp4")) == (1, 2) assert paths(debug_log) == ["/v.m3u8"] assert len(list(folder(debug_log).iterdir())) == 1 @pytest.mark.parametrize("make_session", SESSIONS) def test_dash_init_reads_are_not_recorded_but_the_manifest_is(server, debug_log, monkeypatch, make_session): monkeypatch.setattr(Track, "get_key_id", lambda *_: None) session = make_session() server.docs["/manifest.mpd"] = f""" {server.url}/ file.mp4 """ DASH.from_url(f"{server.url}/manifest.mpd", session) tree = load_xml(server.docs["/manifest.mpd"].encode()) period = tree.find("Period") for rep in period.iter("Representation"): track = Track(url=f"{server.url}/manifest.mpd", language="en") DASH.get_period_segments( period, period.find("AdaptationSet"), rep, tree, track, track.url, session, window=(0, 1) ) assert [server.hits.count(p) for p in ("/init.mp4", "/file.mp4", "/list.mp4")] == [1, 2, 1] assert paths(debug_log) == ["/manifest.mpd"] assert [p.suffix for p in folder(debug_log).iterdir()] == [".mpd"] @pytest.mark.parametrize("make_session", SESSIONS) def test_bitrate_probes_are_not_recorded(server, debug_log, make_session): session = make_session() bitrate.ranged_get(f"{server.url}/a.mp4", session, "bytes=0-0") bitrate.probe_size(bitrate.Segment(f"{server.url}/plain-b.mp4", None, None, 0.0), session) assert server.hits == ["/a.mp4", "/plain-b.mp4", "/plain-b.mp4"] assert records(debug_log) == [] @pytest.mark.parametrize("make_session", SESSIONS) def test_track_init_and_sample_probes_are_not_recorded(server, debug_log, make_session): session = make_session() track = Track(url=f"{server.url}/c.mp4", language="en") track.get_init_segment(session=session) track.sample_byte_range(session) Track(url=f"{server.url}/plain-c.mp4", language="en").get_init_segment(session=session) assert (server.hits.count("/c.mp4"), server.hits.count("/plain-c.mp4")) == (4, 3) assert records(debug_log) == [] def test_an_unrecorded_probe_keeps_the_session_attributes(server, debug_log): class Own(rq.Session): def __init__(self) -> None: super().__init__() self.token = "T" def request(self, *args: Any, **kwargs: Any) -> rq.Response: kwargs["headers"] = {"X-Token": self.token} return super().request(*args, **kwargs) session = Own() record_requests(session) unrecorded(session, "get", f"{server.url}/probe") dl.probe_ranged(f"{server.url}/segment", session) session.get(f"{server.url}/api") assert paths(debug_log) == ["/api"]