mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-27 11:25:08 +00:00
fix(api): cap the total size of a client cache upload and clean up after a refused session create
This commit is contained in:
@@ -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
|
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
|
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
|
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.
|
existing file as a directory, and logs a warning.
|
||||||
|
|
||||||
### Remote session info response
|
### Remote session info response
|
||||||
|
|||||||
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import zlib
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
@@ -30,6 +32,10 @@ from unshackle.core.wire import (
|
|||||||
pytestmark = pytest.mark.unit
|
pytestmark = pytest.mark.unit
|
||||||
|
|
||||||
|
|
||||||
|
def blob(text: str) -> str:
|
||||||
|
return base64.b64encode(zlib.compress(text.encode())).decode("ascii")
|
||||||
|
|
||||||
|
|
||||||
class _Color(Enum):
|
class _Color(Enum):
|
||||||
RED = 1
|
RED = 1
|
||||||
BLUE = 2
|
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
|
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:
|
def test_load_cache_files_forwards_nested_keys(tmp_path, monkeypatch) -> None:
|
||||||
"""A service that keeps its cache in subfolders (session_web/<sha1>.json) must have
|
"""A service that keeps its cache in subfolders (session_web/<sha1>.json) must have
|
||||||
those files forwarded under the Cacher key, and the credential filter must still apply
|
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:
|
def test_save_returned_cache_writes_nested_keys_and_rejects_escapes(tmp_path, monkeypatch) -> None:
|
||||||
import base64
|
|
||||||
import logging
|
import logging
|
||||||
import zlib
|
|
||||||
from types import SimpleNamespace
|
from types import SimpleNamespace
|
||||||
|
|
||||||
from unshackle.core.config import config
|
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)
|
monkeypatch.setattr(config.directories, "cache", tmp_path)
|
||||||
stub = SimpleNamespace(service_tag=tag, log=logging.getLogger("test"))
|
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(
|
RemoteService.save_returned_cache(
|
||||||
stub,
|
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"]
|
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:
|
def test_save_returned_cache_ignores_oversized_payload(tmp_path, monkeypatch) -> None:
|
||||||
import logging
|
import logging
|
||||||
from types import SimpleNamespace
|
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
|
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:
|
def test_write_client_cache_writes_nested_keys_and_skips_colliding_keys(tmp_path, monkeypatch) -> None:
|
||||||
"""The server writes a nested key under the session cache dir with the ``.json``
|
"""A nested key gets the ``.json`` suffix appended, not substituted, and a key that collides with
|
||||||
suffix appended, not substituted, and a key that collides with an existing file
|
an existing file (``x`` then ``x.json/y``) is skipped instead of failing the whole write."""
|
||||||
(``x`` then ``x.json/y``) is skipped instead of failing the whole create."""
|
from unshackle.core.api import handlers
|
||||||
import asyncio
|
|
||||||
|
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
|
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 logging
|
||||||
import zlib
|
|
||||||
from types import SimpleNamespace
|
from types import SimpleNamespace
|
||||||
|
|
||||||
from unshackle.core.api import handlers
|
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):
|
class Stop(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def blob(text: str) -> str:
|
real_write = handlers.write_client_cache
|
||||||
return base64.b64encode(zlib.compress(text.encode())).decode("ascii")
|
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.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, "validate_service", lambda service, request=None: service)
|
||||||
monkeypatch.setattr(handlers, "resolve_handler_proxy", lambda *args: (None, []))
|
monkeypatch.setattr(handlers, "resolve_handler_proxy", lambda *args: (None, []))
|
||||||
monkeypatch.setattr(handlers, "server_account_for", lambda *args: False)
|
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),
|
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.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"')}
|
class RefusingStore:
|
||||||
response = asyncio.run(handlers.session_create_handler({"service": "TESTSVC", "title_id": "t", "cache": cache}))
|
async def create(self, *args, **kwargs):
|
||||||
assert response.status == 422 # the Stop stand-in fired after the cache write
|
raise Stop()
|
||||||
|
|
||||||
written = {p.name: p.read_text() for p in tmp_path.rglob("*.json") if p.is_file()}
|
def peek(self, session_id):
|
||||||
assert written == {"x.json": '"flat"', "keys.v2.json": '"dotted"'}
|
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):
|
class _SentCreate(Exception):
|
||||||
|
|||||||
@@ -15,15 +15,19 @@ MAX_INFLATE_BYTES = 64 * 1024 * 1024 # 64 MiB
|
|||||||
GZIP_THREAD_SIZE = 1024 * 1024
|
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:
|
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()
|
decompressor = zlib.decompressobj()
|
||||||
out = decompressor.decompress(data, max_size + 1)
|
out = decompressor.decompress(data, max_size + 1)
|
||||||
if len(out) > max_size or decompressor.unconsumed_tail:
|
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()
|
out += decompressor.flush()
|
||||||
if len(out) > max_size:
|
if len(out) > max_size:
|
||||||
raise ValueError("compressed payload expands beyond allowed size")
|
raise InflateLimitError("compressed payload expands beyond allowed size")
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -24,12 +24,18 @@ import click
|
|||||||
from aiohttp import web
|
from aiohttp import web
|
||||||
|
|
||||||
from unshackle.core import login
|
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.errors import APIError, categorize_exception, handle_api_exception
|
||||||
from unshackle.core.api.input_bridge import InputBridge, NoUserBridge
|
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.key_policy import KeyPolicy, api_keys, is_whole_number, named_services
|
||||||
from unshackle.core.api.progress import track_log_label
|
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_channel import status_message
|
||||||
from unshackle.core.api.session_log import SessionLogBuffer, SessionLogMirror, capture_service_logs
|
from unshackle.core.api.session_log import SessionLogBuffer, SessionLogMirror, capture_service_logs
|
||||||
from unshackle.core.api.session_store import SessionEntry, SessionStore
|
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
|
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
|
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
|
other than a datetime or a file it cannot write. It raises INVALID_INPUT, before it writes a file, for a
|
||||||
object, has too many entries, or holds a value that is not a string.
|
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:
|
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")
|
raise APIError(APIErrorCode.INVALID_INPUT, f"cache must hold at most {MAX_SESSION_CACHE_KEYS} entries")
|
||||||
cache_dir = config.directories.cache / cache_tag
|
files: dict[str, str] = {}
|
||||||
cache_dir.mkdir(parents=True, exist_ok=True)
|
budget = MAX_SESSION_CACHE_BYTES
|
||||||
for key, content in cache_data.items():
|
for key, content in cache_data.items():
|
||||||
safe_name = safe_cache_key(key)
|
safe_name = safe_cache_key(key)
|
||||||
if not safe_name:
|
if not safe_name:
|
||||||
@@ -252,7 +259,13 @@ def write_client_cache(cache_data: Any, cache_tag: str) -> None:
|
|||||||
if not isinstance(content, str):
|
if not isinstance(content, str):
|
||||||
raise APIError(APIErrorCode.INVALID_INPUT, "cache values must be base64 strings")
|
raise APIError(APIErrorCode.INVALID_INPUT, "cache values must be base64 strings")
|
||||||
try:
|
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):
|
except (ValueError, zlib.error):
|
||||||
raise APIError(
|
raise APIError(
|
||||||
APIErrorCode.INVALID_INPUT, f"cache value {sanitize_log(key)} is not compressed text"
|
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):
|
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")
|
log.warning(f"Rejecting session cache file {sanitize_log(key)}: it holds a type a peer may not send")
|
||||||
continue
|
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"
|
target = cache_dir / f"{safe_name}.json"
|
||||||
try:
|
try:
|
||||||
target.parent.mkdir(parents=True, exist_ok=True)
|
target.parent.mkdir(parents=True, exist_ok=True)
|
||||||
target.write_text(decompressed, encoding="utf-8")
|
target.write_text(decompressed, encoding="utf-8")
|
||||||
except OSError as e:
|
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]:
|
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", {})
|
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
|
service_instance._input_bridge = bridge
|
||||||
|
|
||||||
client = data.get("client")
|
client = data.get("client")
|
||||||
store = get_session_store()
|
store = get_session_store()
|
||||||
session = await store.create(
|
try:
|
||||||
normalized_service,
|
if cache_data and session_cache_tag:
|
||||||
service_instance,
|
await asyncio.to_thread(write_client_cache, cache_data, session_cache_tag)
|
||||||
session_id=session_id,
|
session = await store.create(
|
||||||
owner_key=api_key,
|
normalized_service,
|
||||||
creator_ip=request.remote if request else None,
|
service_instance,
|
||||||
server_account=(profile or "default") if server_account else None,
|
session_id=session_id,
|
||||||
cache_tag=session_cache_tag,
|
owner_key=api_key,
|
||||||
policy=policy,
|
creator_ip=request.remote if request else None,
|
||||||
server_cdm=use_server_cdm,
|
server_account=(profile or "default") if server_account else None,
|
||||||
server_cdm_max_height=max_height,
|
cache_tag=session_cache_tag,
|
||||||
server_vault=client_device and policy.allows("server_vault", normalized_service),
|
policy=policy,
|
||||||
server_device=server_device,
|
server_cdm=use_server_cdm,
|
||||||
client_auth=not server_account
|
server_cdm_max_height=max_height,
|
||||||
and (cookies is not None or credential is not None or bool(cache_data and session_cache_tag)),
|
server_vault=client_device and policy.allows("server_vault", normalized_service),
|
||||||
# Echoed to every dashboard viewer, so cap what an arbitrary client can push into it.
|
server_device=server_device,
|
||||||
client=client if isinstance(client, dict) and len(json.dumps(client, default=str)) <= 4096 else {},
|
client_auth=not server_account
|
||||||
input_bridge=bridge,
|
and (cookies is not None or credential is not None or bool(cache_data and session_cache_tag)),
|
||||||
log_buffer=log_buffer,
|
# 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:
|
async def run_auth() -> None:
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ from pathlib import PureWindowsPath
|
|||||||
|
|
||||||
MAX_CACHE_KEY_DEPTH = 8
|
MAX_CACHE_KEY_DEPTH = 8
|
||||||
MAX_SESSION_CACHE_KEYS = 256
|
MAX_SESSION_CACHE_KEYS = 256
|
||||||
|
MAX_SESSION_CACHE_BYTES = 16 * 1024 * 1024
|
||||||
|
|
||||||
|
|
||||||
CONTROL_CHARS = re.compile(r"[\x00-\x1f\x7f-\x9f]")
|
CONTROL_CHARS = re.compile(r"[\x00-\x1f\x7f-\x9f]")
|
||||||
|
|||||||
@@ -1827,8 +1827,13 @@ class RemoteService(TitleSource):
|
|||||||
if not cache_data:
|
if not cache_data:
|
||||||
return
|
return
|
||||||
|
|
||||||
from unshackle.core.api.compression import safe_inflate
|
from unshackle.core.api.compression import InflateLimitError, safe_inflate
|
||||||
from unshackle.core.api.sanitize import MAX_SESSION_CACHE_KEYS, safe_cache_key, safe_cache_payload
|
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:
|
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}")
|
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)
|
relevant = cache_key_filter(self.service_tag, profile)
|
||||||
|
|
||||||
saved = 0
|
saved = 0
|
||||||
|
budget = MAX_SESSION_CACHE_BYTES
|
||||||
for key, content in cache_data.items():
|
for key, content in cache_data.items():
|
||||||
safe_name = safe_cache_key(key)
|
safe_name = safe_cache_key(key)
|
||||||
if not safe_name:
|
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}")
|
self.log.debug(f"Ignoring cache file from the remote server for another profile: {safe_name}")
|
||||||
continue
|
continue
|
||||||
try:
|
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")):
|
if not safe_cache_payload(decompressed.decode("utf-8")):
|
||||||
self.log.warning(
|
self.log.warning(
|
||||||
f"Rejecting cache file '{safe_name}' from the server: it holds a type a peer may not send"
|
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.parent.mkdir(parents=True, exist_ok=True)
|
||||||
target.write_bytes(decompressed)
|
target.write_bytes(decompressed)
|
||||||
saved += 1
|
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:
|
except Exception as e:
|
||||||
self.log.warning(f"Failed to save returned cache file '{safe_name}': {e}")
|
self.log.warning(f"Failed to save returned cache file '{safe_name}': {e}")
|
||||||
|
|
||||||
@@ -1878,7 +1890,7 @@ class RemoteService(TitleSource):
|
|||||||
"""
|
"""
|
||||||
import zlib
|
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
|
cache_dir = config.directories.cache / self.service_tag
|
||||||
if not cache_dir.is_dir():
|
if not cache_dir.is_dir():
|
||||||
@@ -1886,6 +1898,7 @@ class RemoteService(TitleSource):
|
|||||||
|
|
||||||
relevant = cache_key_filter(self.service_tag, profile)
|
relevant = cache_key_filter(self.service_tag, profile)
|
||||||
files: dict[str, str] = {}
|
files: dict[str, str] = {}
|
||||||
|
size = 0
|
||||||
for f in sorted(cache_dir.rglob("*.json")):
|
for f in sorted(cache_dir.rglob("*.json")):
|
||||||
key = f.relative_to(cache_dir).as_posix()[: -len(".json")]
|
key = f.relative_to(cache_dir).as_posix()[: -len(".json")]
|
||||||
if f.stem.startswith("titles_") or not safe_cache_key(key):
|
if f.stem.startswith("titles_") or not safe_cache_key(key):
|
||||||
@@ -1893,7 +1906,14 @@ class RemoteService(TitleSource):
|
|||||||
if not relevant(key):
|
if not relevant(key):
|
||||||
self.log.debug(f"Withholding cache file from the remote server: {key}")
|
self.log.debug(f"Withholding cache file from the remote server: {key}")
|
||||||
continue
|
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:
|
if len(files) > MAX_SESSION_CACHE_KEYS:
|
||||||
self.log.warning(
|
self.log.warning(
|
||||||
f"The {self.service_tag} cache has {len(files)} files to send and a remote server takes "
|
f"The {self.service_tag} cache has {len(files)} files to send and a remote server takes "
|
||||||
|
|||||||
Reference in New Issue
Block a user