mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-12-01 13:35:09 +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:
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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]")
|
||||
|
||||
@@ -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 "
|
||||
|
||||
Reference in New Issue
Block a user