From 625e632b537a273a30b57adb364b3095e3666a70 Mon Sep 17 00:00:00 2001 From: imSp4rky Date: Thu, 26 Nov 2026 12:47:14 -0700 Subject: [PATCH] fix(api): cap the total size of a client cache upload and clean up after a refused session create --- docs/dev/rest-api/remote-sessions.md | 2 +- .../unit/test_remote_service_helpers.py | 117 +++++++++++++++--- unshackle/core/api/compression.py | 10 +- unshackle/core/api/handlers.py | 84 ++++++++----- unshackle/core/api/sanitize.py | 1 + unshackle/core/remote_service.py | 30 ++++- 6 files changed, 184 insertions(+), 60 deletions(-) diff --git a/docs/dev/rest-api/remote-sessions.md b/docs/dev/rest-api/remote-sessions.md index 0ed6b1ac..f1ee3cdb 100644 --- a/docs/dev/rest-api/remote-sessions.md +++ b/docs/dev/rest-api/remote-sessions.md @@ -666,7 +666,7 @@ suffix, which is the `Cacher` cache key the service reads it with: Both sides reject a cache key with a drive letter, a root, a `..` segment, an empty segment, or more than 8 segments before it becomes a path, so a peer cannot write outside the cache directory. Both sides also refuse a `cache` map with more than -256 entries, and the server refuses the request body of a remote session creation or of a search when it is larger than 8 MiB. The client gives a warning when it has more than 256 cache files to send. The server skips a cache key it cannot write, such as one that names an +256 entries, and the server refuses the request body of a remote session creation or of a search when it is larger than 8 MiB. The server also refuses a `cache` map whose files inflate to more than 16 MiB in total, with `400 INVALID_INPUT`. It checks every entry before it writes a file, and it removes the cache directory of a remote session creation that fails. The client gives a warning when it has more than 256 cache files or more than 16 MiB to send. It also stops saving the cache files that a server returns at 16 MiB. The server skips a cache key it cannot write, such as one that names an existing file as a directory, and logs a warning. ### Remote session info response diff --git a/tests/remote/unit/test_remote_service_helpers.py b/tests/remote/unit/test_remote_service_helpers.py index d281f90e..03f89580 100644 --- a/tests/remote/unit/test_remote_service_helpers.py +++ b/tests/remote/unit/test_remote_service_helpers.py @@ -2,6 +2,8 @@ from __future__ import annotations +import base64 +import zlib from enum import Enum import pytest @@ -30,6 +32,10 @@ from unshackle.core.wire import ( pytestmark = pytest.mark.unit +def blob(text: str) -> str: + return base64.b64encode(zlib.compress(text.encode())).decode("ascii") + + class _Color(Enum): RED = 1 BLUE = 2 @@ -384,6 +390,26 @@ def test_load_cache_files_warns_above_the_server_limit(tmp_path, monkeypatch, ca assert (f"has {count} files to send" in caplog.text) is warned +@pytest.mark.parametrize("size, warned", [(10, False), (11, True)]) +def test_load_cache_files_warns_above_the_server_byte_limit(tmp_path, monkeypatch, caplog, size, warned) -> None: + import logging + from types import SimpleNamespace + + from unshackle.core.config import config + + (tmp_path / "TESTSVC").mkdir() + (tmp_path / "TESTSVC" / "state.json").write_text("a" * size) + monkeypatch.setattr("unshackle.core.api.sanitize.MAX_SESSION_CACHE_BYTES", 10) + monkeypatch.setattr(config.directories, "cache", tmp_path) + monkeypatch.setattr(config, "credentials", {}) + stub = SimpleNamespace(service_tag="TESTSVC", log=logging.getLogger("test")) + + with caplog.at_level(logging.WARNING, logger="test"): + RemoteService.load_cache_files(stub, None) + + assert (f"has {size} bytes to send" in caplog.text) is warned + + def test_load_cache_files_forwards_nested_keys(tmp_path, monkeypatch) -> None: """A service that keeps its cache in subfolders (session_web/.json) must have those files forwarded under the Cacher key, and the credential filter must still apply @@ -434,9 +460,7 @@ def test_load_cache_files_forwards_nested_keys(tmp_path, monkeypatch) -> None: def test_save_returned_cache_writes_nested_keys_and_rejects_escapes(tmp_path, monkeypatch) -> None: - import base64 import logging - import zlib from types import SimpleNamespace from unshackle.core.config import config @@ -446,9 +470,6 @@ def test_save_returned_cache_writes_nested_keys_and_rejects_escapes(tmp_path, mo monkeypatch.setattr(config.directories, "cache", tmp_path) stub = SimpleNamespace(service_tag=tag, log=logging.getLogger("test")) - def blob(text: str) -> str: - return base64.b64encode(zlib.compress(text.encode())).decode("ascii") - RemoteService.save_returned_cache( stub, { @@ -497,6 +518,20 @@ def test_save_returned_cache_drops_other_profiles_files(tmp_path, monkeypatch) - assert sorted(p.name for p in (tmp_path / tag).iterdir()) == ["tokens.json", "tokens_work.json"] +def test_save_returned_cache_stops_at_the_total_byte_limit(tmp_path, monkeypatch) -> None: + import logging + from types import SimpleNamespace + + from unshackle.core.config import config + + monkeypatch.setattr("unshackle.core.api.sanitize.MAX_SESSION_CACHE_BYTES", 10) + monkeypatch.setattr(config.directories, "cache", tmp_path) + monkeypatch.setattr(config, "credentials", {}) + stub = SimpleNamespace(service_tag="TESTSVC", log=logging.getLogger("test")) + RemoteService.save_returned_cache(stub, {"first": blob('"1234"'), "second": blob('"5678"')}) + assert sorted(p.name for p in tmp_path.rglob("*.json")) == ["first.json"] + + def test_save_returned_cache_ignores_oversized_payload(tmp_path, monkeypatch) -> None: import logging from types import SimpleNamespace @@ -587,14 +622,44 @@ def test_resolve_manifest_data_matches_across_per_range_manifests() -> None: assert remote_hdr.data["ism"]["quality_level"].get("CodecPrivateData") == VIDEO_HEVC_PQ_CPD -def test_session_create_writes_nested_cache_and_skips_colliding_keys(tmp_path, monkeypatch) -> None: - """The server writes a nested key under the session cache dir with the ``.json`` - suffix appended, not substituted, and a key that collides with an existing file - (``x`` then ``x.json/y``) is skipped instead of failing the whole create.""" - import asyncio +def test_write_client_cache_writes_nested_keys_and_skips_colliding_keys(tmp_path, monkeypatch) -> None: + """A nested key gets the ``.json`` suffix appended, not substituted, and a key that collides with + an existing file (``x`` then ``x.json/y``) is skipped instead of failing the whole write.""" + from unshackle.core.api import handlers + + monkeypatch.setattr(handlers.config.directories, "cache", tmp_path) + handlers.write_client_cache( + {"x": blob('"flat"'), "x.json/y": blob('"collides"'), "MSL/keys.v2": blob('"dotted"')}, "t" + ) + + written = {p.name: p.read_text() for p in tmp_path.rglob("*.json") if p.is_file()} + assert written == {"x.json": '"flat"', "keys.v2.json": '"dotted"'} + + +@pytest.mark.parametrize("last", ["over_total", "not_compressed"]) +def test_write_client_cache_refuses_a_bad_map_before_it_writes_a_file(tmp_path, monkeypatch, last) -> None: import base64 + + from unshackle.core.api import handlers + from unshackle.core.api.errors import APIError, APIErrorCode + from unshackle.core.api.sanitize import MAX_SESSION_CACHE_BYTES + + monkeypatch.setattr(handlers.config.directories, "cache", tmp_path) + half = '"' + "a" * (MAX_SESSION_CACHE_BYTES // 2) + '"' + cache = {"first": blob('"ok"'), "big1": blob(half)} + cache["last"] = blob(half) if last == "over_total" else base64.b64encode(b"plain").decode() + + with pytest.raises(APIError) as e: + handlers.write_client_cache(cache, "t") + assert e.value.error_code == APIErrorCode.INVALID_INPUT + assert ("inflate to more than" in e.value.message) is (last == "over_total") + assert not any(tmp_path.iterdir()) + + +@pytest.mark.parametrize("stop_at", ["write", "store", "after_insert"]) +def test_a_session_create_that_fails_after_the_cache_write_leaves_no_cache_dir(tmp_path, monkeypatch, stop_at) -> None: + import asyncio import logging - import zlib from types import SimpleNamespace from unshackle.core.api import handlers @@ -602,10 +667,17 @@ def test_session_create_writes_nested_cache_and_skips_colliding_keys(tmp_path, m class Stop(Exception): pass - def blob(text: str) -> str: - return base64.b64encode(zlib.compress(text.encode())).decode("ascii") + real_write = handlers.write_client_cache + written: list[str] = [] + + def write_then_maybe_fail(cache_data, cache_tag): + real_write(cache_data, cache_tag) + written.extend(p.name for p in tmp_path.rglob("*.json")) + if stop_at == "write": + raise Stop() monkeypatch.setattr(handlers.config.directories, "cache", tmp_path) + monkeypatch.setattr(handlers, "write_client_cache", write_then_maybe_fail) monkeypatch.setattr(handlers, "validate_service", lambda service, request=None: service) monkeypatch.setattr(handlers, "resolve_handler_proxy", lambda *args: (None, [])) monkeypatch.setattr(handlers, "server_account_for", lambda *args: False) @@ -616,14 +688,21 @@ def test_session_create_writes_nested_cache_and_skips_colliding_keys(tmp_path, m lambda *args, **kwargs: (SimpleNamespace(log=logging.getLogger("Svc")), None, None), ) monkeypatch.setattr("unshackle.core.api.session_store.refuse_while_draining", lambda: None) - monkeypatch.setattr("unshackle.core.api.session_store.get_session_store", lambda: (_ for _ in ()).throw(Stop())) - cache = {"x": blob('"flat"'), "x.json/y": blob('"collides"'), "MSL/keys.v2": blob('"dotted"')} - response = asyncio.run(handlers.session_create_handler({"service": "TESTSVC", "title_id": "t", "cache": cache})) - assert response.status == 422 # the Stop stand-in fired after the cache write + class RefusingStore: + async def create(self, *args, **kwargs): + raise Stop() - written = {p.name: p.read_text() for p in tmp_path.rglob("*.json") if p.is_file()} - assert written == {"x.json": '"flat"', "keys.v2.json": '"dotted"'} + def peek(self, session_id): + return object() if stop_at == "after_insert" else None + + monkeypatch.setattr("unshackle.core.api.session_store.get_session_store", RefusingStore) + + data = {"service": "TESTSVC", "title_id": "t", "cache": {"token": blob('"t"')}} + response = asyncio.run(handlers.session_create_handler(data)) + assert response.status == 422 + assert written == ["token.json"] + assert bool(list(tmp_path.rglob("*.json"))) is (stop_at == "after_insert") class _SentCreate(Exception): diff --git a/unshackle/core/api/compression.py b/unshackle/core/api/compression.py index f2515b34..5fda44bc 100644 --- a/unshackle/core/api/compression.py +++ b/unshackle/core/api/compression.py @@ -15,15 +15,19 @@ MAX_INFLATE_BYTES = 64 * 1024 * 1024 # 64 MiB GZIP_THREAD_SIZE = 1024 * 1024 +class InflateLimitError(ValueError): + """The compressed payload expands beyond the allowed size.""" + + def safe_inflate(data: bytes, max_size: int = MAX_INFLATE_BYTES) -> bytes: - """zlib-decompress *data*, raising ValueError if the result would exceed *max_size*.""" + """zlib-decompress *data*, raising InflateLimitError if the result would exceed *max_size*.""" decompressor = zlib.decompressobj() out = decompressor.decompress(data, max_size + 1) if len(out) > max_size or decompressor.unconsumed_tail: - raise ValueError("compressed payload expands beyond allowed size") + raise InflateLimitError("compressed payload expands beyond allowed size") out += decompressor.flush() if len(out) > max_size: - raise ValueError("compressed payload expands beyond allowed size") + raise InflateLimitError("compressed payload expands beyond allowed size") return out diff --git a/unshackle/core/api/handlers.py b/unshackle/core/api/handlers.py index c59397a8..579159ca 100644 --- a/unshackle/core/api/handlers.py +++ b/unshackle/core/api/handlers.py @@ -24,12 +24,18 @@ import click from aiohttp import web from unshackle.core import login -from unshackle.core.api.compression import safe_inflate +from unshackle.core.api.compression import InflateLimitError, safe_inflate from unshackle.core.api.errors import APIError, categorize_exception, handle_api_exception from unshackle.core.api.input_bridge import InputBridge, NoUserBridge from unshackle.core.api.key_policy import KeyPolicy, api_keys, is_whole_number, named_services from unshackle.core.api.progress import track_log_label -from unshackle.core.api.sanitize import MAX_SESSION_CACHE_KEYS, safe_cache_key, safe_cache_payload, sanitize_log +from unshackle.core.api.sanitize import ( + MAX_SESSION_CACHE_BYTES, + MAX_SESSION_CACHE_KEYS, + safe_cache_key, + safe_cache_payload, + sanitize_log, +) from unshackle.core.api.session_channel import status_message from unshackle.core.api.session_log import SessionLogBuffer, SessionLogMirror, capture_service_logs from unshackle.core.api.session_store import SessionEntry, SessionStore @@ -237,13 +243,14 @@ def write_client_cache(cache_data: Any, cache_tag: str) -> None: Each cache key is a file path relative to that directory, and each value is the file as base64 of zlib-compressed bytes. The function skips an unsafe key, a file that names a type - other than a datetime or a file it cannot write, and raises INVALID_INPUT for a map that is not an - object, has too many entries, or holds a value that is not a string. + other than a datetime or a file it cannot write. It raises INVALID_INPUT, before it writes a file, for a + map that is not an object, has too many entries, holds a value that is not compressed text, or inflates + to more than ``MAX_SESSION_CACHE_BYTES`` in total. """ if not isinstance(cache_data, dict) or len(cache_data) > MAX_SESSION_CACHE_KEYS: raise APIError(APIErrorCode.INVALID_INPUT, f"cache must hold at most {MAX_SESSION_CACHE_KEYS} entries") - cache_dir = config.directories.cache / cache_tag - cache_dir.mkdir(parents=True, exist_ok=True) + files: dict[str, str] = {} + budget = MAX_SESSION_CACHE_BYTES for key, content in cache_data.items(): safe_name = safe_cache_key(key) if not safe_name: @@ -252,7 +259,13 @@ def write_client_cache(cache_data: Any, cache_tag: str) -> None: if not isinstance(content, str): raise APIError(APIErrorCode.INVALID_INPUT, "cache values must be base64 strings") try: - decompressed = safe_inflate(base64.b64decode(content)).decode("utf-8") + inflated = safe_inflate(base64.b64decode(content), budget) + budget -= len(inflated) + decompressed = inflated.decode("utf-8") + except InflateLimitError: + raise APIError( + APIErrorCode.INVALID_INPUT, f"cache files inflate to more than {MAX_SESSION_CACHE_BYTES} bytes" + ) from None except (ValueError, zlib.error): raise APIError( APIErrorCode.INVALID_INPUT, f"cache value {sanitize_log(key)} is not compressed text" @@ -260,12 +273,16 @@ def write_client_cache(cache_data: Any, cache_tag: str) -> None: if not safe_cache_payload(decompressed): log.warning(f"Rejecting session cache file {sanitize_log(key)}: it holds a type a peer may not send") continue + files[safe_name] = decompressed + cache_dir = config.directories.cache / cache_tag + cache_dir.mkdir(parents=True, exist_ok=True) + for safe_name, decompressed in files.items(): target = cache_dir / f"{safe_name}.json" try: target.parent.mkdir(parents=True, exist_ok=True) target.write_text(decompressed, encoding="utf-8") except OSError as e: - log.warning(f"Skipping session cache key {sanitize_log(key)}: {e}") + log.warning(f"Skipping session cache key {sanitize_log(safe_name)}: {e}") def collect_cache_files(cache_tag: str) -> dict[str, str]: @@ -2926,33 +2943,36 @@ async def session_create_handler(data: dict[str, Any], request: web.Request | No ) cache_data = data.get("cache", {}) - if cache_data and session_cache_tag: - await asyncio.to_thread(write_client_cache, cache_data, session_cache_tag) - service_instance._input_bridge = bridge - client = data.get("client") store = get_session_store() - session = await store.create( - normalized_service, - service_instance, - session_id=session_id, - owner_key=api_key, - creator_ip=request.remote if request else None, - server_account=(profile or "default") if server_account else None, - cache_tag=session_cache_tag, - policy=policy, - server_cdm=use_server_cdm, - server_cdm_max_height=max_height, - server_vault=client_device and policy.allows("server_vault", normalized_service), - server_device=server_device, - client_auth=not server_account - and (cookies is not None or credential is not None or bool(cache_data and session_cache_tag)), - # Echoed to every dashboard viewer, so cap what an arbitrary client can push into it. - client=client if isinstance(client, dict) and len(json.dumps(client, default=str)) <= 4096 else {}, - input_bridge=bridge, - log_buffer=log_buffer, - ) + try: + if cache_data and session_cache_tag: + await asyncio.to_thread(write_client_cache, cache_data, session_cache_tag) + session = await store.create( + normalized_service, + service_instance, + session_id=session_id, + owner_key=api_key, + creator_ip=request.remote if request else None, + server_account=(profile or "default") if server_account else None, + cache_tag=session_cache_tag, + policy=policy, + server_cdm=use_server_cdm, + server_cdm_max_height=max_height, + server_vault=client_device and policy.allows("server_vault", normalized_service), + server_device=server_device, + client_auth=not server_account + and (cookies is not None or credential is not None or bool(cache_data and session_cache_tag)), + # Echoed to every dashboard viewer, so cap what an arbitrary client can push into it. + client=client if isinstance(client, dict) and len(json.dumps(client, default=str)) <= 4096 else {}, + input_bridge=bridge, + log_buffer=log_buffer, + ) + except BaseException: + if store.peek(session_id) is None: + SessionStore.cleanup_cache_dir(session_cache_tag) + raise async def run_auth() -> None: try: diff --git a/unshackle/core/api/sanitize.py b/unshackle/core/api/sanitize.py index f3490c65..5f6ee77e 100644 --- a/unshackle/core/api/sanitize.py +++ b/unshackle/core/api/sanitize.py @@ -8,6 +8,7 @@ from pathlib import PureWindowsPath MAX_CACHE_KEY_DEPTH = 8 MAX_SESSION_CACHE_KEYS = 256 +MAX_SESSION_CACHE_BYTES = 16 * 1024 * 1024 CONTROL_CHARS = re.compile(r"[\x00-\x1f\x7f-\x9f]") diff --git a/unshackle/core/remote_service.py b/unshackle/core/remote_service.py index 04042ae6..6c90d19b 100644 --- a/unshackle/core/remote_service.py +++ b/unshackle/core/remote_service.py @@ -1827,8 +1827,13 @@ class RemoteService(TitleSource): if not cache_data: return - from unshackle.core.api.compression import safe_inflate - from unshackle.core.api.sanitize import MAX_SESSION_CACHE_KEYS, safe_cache_key, safe_cache_payload + from unshackle.core.api.compression import InflateLimitError, safe_inflate + from unshackle.core.api.sanitize import ( + MAX_SESSION_CACHE_BYTES, + MAX_SESSION_CACHE_KEYS, + safe_cache_key, + safe_cache_payload, + ) if len(cache_data) > MAX_SESSION_CACHE_KEYS: self.log.warning(f"Ignoring {len(cache_data)} cache files from server: more than {MAX_SESSION_CACHE_KEYS}") @@ -1839,6 +1844,7 @@ class RemoteService(TitleSource): relevant = cache_key_filter(self.service_tag, profile) saved = 0 + budget = MAX_SESSION_CACHE_BYTES for key, content in cache_data.items(): safe_name = safe_cache_key(key) if not safe_name: @@ -1848,7 +1854,8 @@ class RemoteService(TitleSource): self.log.debug(f"Ignoring cache file from the remote server for another profile: {safe_name}") continue try: - decompressed = safe_inflate(base64.b64decode(content)) + decompressed = safe_inflate(base64.b64decode(content), budget) + budget -= len(decompressed) if not safe_cache_payload(decompressed.decode("utf-8")): self.log.warning( f"Rejecting cache file '{safe_name}' from the server: it holds a type a peer may not send" @@ -1859,6 +1866,11 @@ class RemoteService(TitleSource): target.parent.mkdir(parents=True, exist_ok=True) target.write_bytes(decompressed) saved += 1 + except InflateLimitError: + self.log.warning( + f"Ignoring the rest of the cache files from server: more than {MAX_SESSION_CACHE_BYTES} bytes" + ) + break except Exception as e: self.log.warning(f"Failed to save returned cache file '{safe_name}': {e}") @@ -1878,7 +1890,7 @@ class RemoteService(TitleSource): """ import zlib - from unshackle.core.api.sanitize import MAX_SESSION_CACHE_KEYS, safe_cache_key + from unshackle.core.api.sanitize import MAX_SESSION_CACHE_BYTES, MAX_SESSION_CACHE_KEYS, safe_cache_key cache_dir = config.directories.cache / self.service_tag if not cache_dir.is_dir(): @@ -1886,6 +1898,7 @@ class RemoteService(TitleSource): relevant = cache_key_filter(self.service_tag, profile) files: dict[str, str] = {} + size = 0 for f in sorted(cache_dir.rglob("*.json")): key = f.relative_to(cache_dir).as_posix()[: -len(".json")] if f.stem.startswith("titles_") or not safe_cache_key(key): @@ -1893,7 +1906,14 @@ class RemoteService(TitleSource): if not relevant(key): self.log.debug(f"Withholding cache file from the remote server: {key}") continue - files[key] = base64.b64encode(zlib.compress(f.read_bytes())).decode("ascii") + content = f.read_bytes() + size += len(content) + files[key] = base64.b64encode(zlib.compress(content)).decode("ascii") + if size > MAX_SESSION_CACHE_BYTES: + self.log.warning( + f"The {self.service_tag} cache has {size} bytes to send and a remote server takes " + f"{MAX_SESSION_CACHE_BYTES}: remove old files from {cache_dir}" + ) if len(files) > MAX_SESSION_CACHE_KEYS: self.log.warning( f"The {self.service_tag} cache has {len(files)} files to send and a remote server takes "