diff --git a/tests/core/test_widevine_get_content_keys.py b/tests/core/test_widevine_get_content_keys.py index a24b0a61..41b92510 100644 --- a/tests/core/test_widevine_get_content_keys.py +++ b/tests/core/test_widevine_get_content_keys.py @@ -93,3 +93,15 @@ def test_an_empty_challenge_raises_instead_of_licensing() -> None: drm.get_content_keys( cdm=FakeCdm(challenge=b""), certificate=lambda **_: None, licence=_licence_for(get_widevine_license) ) + + +def test_a_licence_the_cdm_cannot_parse_is_one_line() -> None: + import click + from pywidevine.exceptions import InvalidLicenseMessage + + class JunkCdm(FakeCdm): + def parse_license(self, session_id: str, response: Any) -> None: + raise InvalidLicenseMessage("Could not parse license_message as a SignedMessage") + + with pytest.raises(click.ClickException, match=KID.hex): + _drm().get_content_keys(JunkCdm(), certificate=lambda **_: None, licence=lambda **_: b"junk licence") diff --git a/tests/remote/unit/test_download_gates_redaction.py b/tests/remote/unit/test_download_gates_redaction.py index 75f96bb8..d5684b14 100644 --- a/tests/remote/unit/test_download_gates_redaction.py +++ b/tests/remote/unit/test_download_gates_redaction.py @@ -88,7 +88,7 @@ def test_to_dict_redacts_again_only_when_an_error_field_changes(monkeypatch): calls = [] real = download_manager._redact_text - monkeypatch.setattr(download_manager, "_redact_text", lambda text, params: calls.append(text) or real(text, params)) + monkeypatch.setattr(download_manager, "_redact_text", lambda text, *rest: calls.append(text) or real(text, *rest)) job = DownloadJob( job_id="j1", status=JobStatus.FAILED, diff --git a/tests/remote/unit/test_handlers_serialize.py b/tests/remote/unit/test_handlers_serialize.py index f264d342..b0411335 100644 --- a/tests/remote/unit/test_handlers_serialize.py +++ b/tests/remote/unit/test_handlers_serialize.py @@ -91,6 +91,7 @@ def subtitle(**overrides) -> Subtitle: [ ("hello\nworld", "helloworld"), ("a\r\nb\x00c", "abc"), + ("\x1b[31mred\x1b[0m", "[31mred[0m"), ("clean", "clean"), (12345, "12345"), ], diff --git a/tests/remote/unit/test_malformed_input.py b/tests/remote/unit/test_malformed_input.py new file mode 100644 index 00000000..71178e82 --- /dev/null +++ b/tests/remote/unit/test_malformed_input.py @@ -0,0 +1,208 @@ +"""Malformed input from a client or a server gets a one-line refusal, never an internal error or a traceback.""" + +from __future__ import annotations + +import base64 +import logging +from collections import deque +from threading import Lock +from types import SimpleNamespace +from typing import Any + +import pytest +import requests +from aiohttp import web +from click.testing import CliRunner + +from unshackle.core import remote_service +from unshackle.core.api import handlers +from unshackle.core.api.errors import APIError, APIErrorCode +from unshackle.core.api.routes import setup_routes +from unshackle.core.remote_service import RemoteClient, RemoteError, RemoteService + +pytestmark = pytest.mark.unit + + +async def test_a_body_that_is_not_an_object_is_invalid_input(aiohttp_client: Any) -> None: + app = web.Application() + app["config"] = {"users": {}} + app["debug_api"] = False + setup_routes(app) + client = await aiohttp_client(app) + for body in (b"[1, 2]", b"null", b'"x"', b"5"): + resp = await client.post("/api/session/create", data=body, headers={"Content-Type": "application/json"}) + assert resp.status == 400 + assert (await resp.json())["error_code"] == "INVALID_INPUT" + + +def test_a_cache_value_that_is_not_compressed_is_invalid_input(tmp_path: Any, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(handlers.config.directories, "cache", tmp_path) + with pytest.raises(APIError) as e: + handlers.write_client_cache({"token": base64.b64encode(b"plain").decode()}, "tag") + assert e.value.error_code == APIErrorCode.INVALID_INPUT + + +def test_a_challenge_that_is_not_base64_is_invalid_input() -> None: + with pytest.raises(APIError) as e: + handlers.handle_proxy_license(None, None, None, "!!notb64", "widevine") + assert e.value.error_code == APIErrorCode.INVALID_INPUT + + +async def test_segments_refuse_track_ids_that_are_not_strings(monkeypatch: pytest.MonkeyPatch) -> None: + async def session(*_: Any) -> Any: + return SimpleNamespace(tracks={}) + + monkeypatch.setattr(handlers, "get_validated_session", session) + monkeypatch.setattr(handlers, "require_authenticated", lambda _: None) + with pytest.raises(APIError) as e: + await handlers.session_segments_handler({"track_ids": [{"a": 1}]}, "sid") + assert e.value.error_code == APIErrorCode.INVALID_INPUT + + +async def test_a_client_owner_key_does_not_reach_the_job(monkeypatch: pytest.MonkeyPatch) -> None: + from unshackle.core.api import download_manager + + made: dict[str, Any] = {} + + class Manager: + async def start_workers(self) -> None: + return None + + def create_job(self, service: str, title_id: str, owner_key: Any = None, **params: Any) -> Any: + made.update(params, owner=owner_key) + raise RuntimeError("stop") + + monkeypatch.setattr(handlers, "validate_service", lambda tag, request=None: tag) + monkeypatch.setattr(handlers.Services, "load", lambda tag: object()) + monkeypatch.setattr(download_manager, "get_download_manager", lambda: Manager()) + await handlers.download_handler({"service": "EXAMPLE", "title_id": "t", "owner_key": "OTHER"}) + assert made["owner"] == "anonymous" + assert "owner_key" not in made + + +def remote_answer(monkeypatch: pytest.MonkeyPatch, text: str) -> RemoteClient: + client = RemoteClient("http://server.example", "key") + resp = requests.Response() + resp.status_code = 200 + resp._content = text.encode() + resp.headers["Content-Type"] = "application/json" + monkeypatch.setattr(client.session, "get", lambda *a, **k: resp) + return client + + +@pytest.mark.parametrize("text", ["not json", "[1, 2]", '{"video": [']) +def test_a_server_answer_that_is_not_a_json_object_is_one_remote_error( + monkeypatch: pytest.MonkeyPatch, text: str +) -> None: + with pytest.raises(RemoteError): + remote_answer(monkeypatch, text).get("/api/session/s/titles") + + +@pytest.mark.parametrize("answer", [{"titles": ["x"]}, {"titles": [{"type": "episode", "season": "x"}]}]) +def test_malformed_titles_from_the_server_are_one_remote_error(answer: dict[str, Any]) -> None: + service = RemoteService.__new__(RemoteService) + service._titles = None + service.service_tag = "EXAMPLE" + service.title_id = "t" + service.session_call = lambda call: answer # type: ignore[method-assign] + service.drain_server_logs = lambda: None # type: ignore[method-assign] + with pytest.raises(RemoteError): + service.get_titles() + + +@pytest.mark.parametrize("answer", [{"video": None}, {"video": [{"bitrate": "x1"}]}, {"attachments": [5]}]) +def test_malformed_tracks_from_the_server_are_one_remote_error(answer: dict[str, Any]) -> None: + from unshackle.core.titles import Movie + + service = RemoteService.__new__(RemoteService) + service._tracks_by_title = {} + service._title_alias = {} + service.server_draining = lambda: False # type: ignore[method-assign] + service.session_call = lambda call: answer # type: ignore[method-assign] + service.drain_server_logs = lambda: None # type: ignore[method-assign] + with pytest.raises(RemoteError): + service.get_tracks(Movie(id_="title-1", service=RemoteService, name="Name")) + + +async def test_full_mode_logs_no_rejected_key_and_answers_405( + monkeypatch: pytest.MonkeyPatch, aiohttp_client: Any, caplog: pytest.LogCaptureFixture +) -> None: + from unshackle.commands.serve import serve + from unshackle.core.config import config as cfg + + captured: dict[str, Any] = {} + monkeypatch.setattr(web, "run_app", lambda app, **kwargs: captured.update(app=app)) + monkeypatch.setattr(cfg, "serve", {"api_secret": "admin-key", "users": {"user-key": {"username": "a"}}}) + result = CliRunner().invoke(serve, ["--no-playready"]) + assert result.exit_code == 0, result.output + client = await aiohttp_client(captured["app"]) + with caplog.at_level(logging.DEBUG): + resp = await client.get("/api/services", headers={"X-Secret-Key": "WRONG-key-example"}) + assert resp.status == 401 + assert "WRONG-key-example" not in caplog.text + assert (await client.put("/api/download", headers={"X-Secret-Key": "user-key"})).status == 405 + + +@pytest.mark.parametrize("title_id", [5, ["a"]]) +async def test_a_title_id_that_is_not_a_string_is_invalid_input(title_id: Any) -> None: + with pytest.raises(APIError) as e: + await handlers.download_handler({"service": "EXAMPLE", "title_id": title_id}) + assert e.value.error_code == APIErrorCode.INVALID_INPUT + + +@pytest.mark.parametrize("wanted", ["zzz", "S01E05-S01E02", [5], {"a": 1}]) +async def test_garbage_wanted_is_invalid_input_at_submit(wanted: Any) -> None: + with pytest.raises(APIError) as e: + await handlers.download_handler({"service": "EXAMPLE", "title_id": "t", "wanted": wanted}) + assert e.value.error_code == APIErrorCode.INVALID_INPUT + + +@pytest.mark.parametrize("wanted", ["S01E01", "s1e1-s1e3, 2x4", ["1x1", "!1x1.2"]]) +def test_good_wanted_passes_at_submit(wanted: Any) -> None: + assert handlers.wanted_refusal(wanted) is None + + +def test_a_job_error_hides_the_configured_credential(monkeypatch: pytest.MonkeyPatch) -> None: + from datetime import datetime + + from unshackle.core.api.download_manager import DownloadJob, JobStatus + + monkeypatch.setattr(handlers.config, "credentials", {"EXAMPLE": {"default": "user:EXAMPLE-pass-123"}}) + job = DownloadJob("j1", JobStatus.FAILED, datetime(2026, 1, 1), "EXAMPLE", "t", {}) + job.error_message = "login failed with EXAMPLE-pass-123" + assert "EXAMPLE-pass-123" not in job.to_dict(include_full_details=True)["error_message"] + + +def test_decrypting_without_content_keys_is_one_line(tmp_path: Any) -> None: + import click + + from unshackle.core.drm.decrypters import decrypt_cenc + + with pytest.raises(click.ClickException): + decrypt_cenc(SimpleNamespace(content_keys={}), tmp_path / "x.mp4", "Widevine") + + +def test_a_session_create_answer_without_a_session_id_is_one_remote_error() -> None: + with pytest.raises(RemoteError, match="malformed session"): + with remote_service.malformed_answer("session"): + raise TypeError("session_id is not a string") + + +def test_server_text_loses_its_control_characters() -> None: + error = RemoteError("Server error [X]: \x1b[31mred\x1b[0m\r\n[forged] INFO ok", "UNKNOWN") + assert "\x1b" not in error.message and "\n" not in error.message and "\r" not in error.message + + +def test_relayed_server_logs_lose_their_control_characters(monkeypatch: pytest.MonkeyPatch) -> None: + service = RemoteService.__new__(RemoteService) + service._session_id = "sid" + service._log_seq = 0 + service._recent_logs = deque(maxlen=5) + service._log_drain_lock = Lock() + seen: list[str] = [] + service.log = SimpleNamespace(log=lambda level, message: seen.append(message)) # type: ignore[assignment] + service.client = SimpleNamespace( + get_optional=lambda _: {"logs": [{"level": "INFO", "message": "a\x1b[2Jb\nc"}], "last_seq": 1} + ) + service.drain_server_logs() + assert seen == ["a[2Jb\nc"] diff --git a/unshackle/commands/serve.py b/unshackle/commands/serve.py index cee437a6..e65226ec 100644 --- a/unshackle/commands/serve.py +++ b/unshackle/commands/serve.py @@ -556,9 +556,9 @@ def serve( return limited if serve_playready_flag and request.path in ("/playready", "/playready/"): response = await handler(request) - elif secret_key and not request.headers.get("X-Secret-Key"): - if not known: - return web.json_response({"status": 401, "message": "Secret Key is Invalid."}, status=401) + elif secret_key and not known: + return web.json_response({"status": 401, "message": "Secret Key is Invalid."}, status=401) + elif secret_key and (request.path.startswith("/api/") or not request.headers.get("X-Secret-Key")): response = await handler(request) else: response = await pywidevine_serve.authentication(request, handler) diff --git a/unshackle/core/api/download_manager.py b/unshackle/core/api/download_manager.py index c02e0d73..f63a6812 100644 --- a/unshackle/core/api/download_manager.py +++ b/unshackle/core/api/download_manager.py @@ -49,11 +49,18 @@ def redact_parameters(parameters: Dict[str, Any]) -> Dict[str, Any]: return redacted -def secret_values(parameters: Dict[str, Any]) -> List[str]: - """Raw secret strings carried in job parameters, longest first, for scrubbing free text.""" +def secret_values(parameters: Dict[str, Any], service: Optional[str] = None) -> List[str]: + """Raw secret strings carried in job parameters and the credentials configured for ``service``, longest first.""" if not isinstance(parameters, dict): return [] secrets: List[str] = [] + if service: + from unshackle.core.config import config + + configured = (config.credentials or {}).get(service) + for value in configured.values() if isinstance(configured, dict) else [configured]: + if isinstance(value, str): + secrets.extend(secret_values({"credential": value})) for key in ("credential", "password", "token", "api_key"): value = parameters.get(key) if isinstance(value, str) and value: @@ -77,10 +84,10 @@ def owner_id(api_key: Optional[str]) -> Optional[str]: return hashlib.sha256(api_key.encode()).hexdigest()[:16] -def _redact_text(text: Optional[str], parameters: Dict[str, Any]) -> Optional[str]: +def _redact_text(text: Optional[str], parameters: Dict[str, Any], service: Optional[str] = None) -> Optional[str]: """Mask proxy userinfo and any known parameter secrets that leaked into a free-text field (error message / details / traceback / job worker stderr) before the API returns the field.""" - return redact_text(text, secret_values(parameters)) + return redact_text(text, secret_values(parameters, service)) class JobStatus(Enum): @@ -183,7 +190,10 @@ class DownloadJob: names = ("error_message", "error_details", "error_traceback", "worker_stderr") self.redacted = ( raw, - {name: redact_path(_redact_text(text, self.parameters)) for name, text in zip(names, raw)}, + { + name: redact_path(_redact_text(text, self.parameters, self.service)) + for name, text in zip(names, raw) + }, ) result.update( { @@ -237,7 +247,7 @@ def record_job_history(job: DownloadJob) -> None: "output_files": job.output_files, "skipped_titles": job.skipped_titles, "parameters": redact_parameters(job.parameters), - "error_message": _redact_text(job.error_message, job.parameters), + "error_message": _redact_text(job.error_message, job.parameters, job.service), } try: path = history_path() @@ -867,7 +877,9 @@ class DownloadQueueManager: except Exception as e: job.status = JobStatus.FAILED job.error_message = str(e) - log.error(f"Job {job.job_id} failed: {e}") + log.error( + f"Job {job.job_id} failed: {_redact_text(job.error_message, job.parameters, job.service)}" + ) finally: job.completed_time = datetime.now() record_job_history(job) @@ -905,7 +917,7 @@ class DownloadQueueManager: job.error_code = job.error_code or api_error.error_code.value job.error_traceback = job.error_traceback or traceback.format_exc() - log.error(f"Download failed for job {job.job_id}: {e}") + log.error(f"Download failed for job {job.job_id}: {_redact_text(str(e), job.parameters, job.service)}") raise def worker_speed_limit(self) -> Optional[float]: @@ -1045,8 +1057,8 @@ class DownloadQueueManager: # A service can echo a credential or a proxy URL into its output, so scrub it before # it reaches the log as well, not only the API response. - safe_stdout = _redact_text(stdout.strip(), job.parameters) - safe_stderr = _redact_text(stderr.strip(), job.parameters) + safe_stdout = _redact_text(stdout.strip(), job.parameters, job.service) + safe_stderr = _redact_text(stderr.strip(), job.parameters, job.service) if stdout.strip(): log.debug(f"Worker stdout for job {job.job_id}: {safe_stdout}") if stderr.strip(): diff --git a/unshackle/core/api/handlers.py b/unshackle/core/api/handlers.py index 1595c6b8..77b18717 100644 --- a/unshackle/core/api/handlers.py +++ b/unshackle/core/api/handlers.py @@ -328,7 +328,12 @@ def write_client_cache(cache_data: Any, cache_tag: str) -> None: continue if not isinstance(content, str): raise APIError(APIErrorCode.INVALID_INPUT, "cache values must be base64 strings") - decompressed = safe_inflate(base64.b64decode(content)).decode("utf-8") + try: + decompressed = safe_inflate(base64.b64decode(content)).decode("utf-8") + except (ValueError, zlib.error): + raise APIError( + APIErrorCode.INVALID_INPUT, f"cache value {sanitize_log(key)} is not compressed text" + ) from 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 @@ -1894,6 +1899,23 @@ def resolve_vcodec(value: Any) -> Optional[list]: raise APIError(APIErrorCode.INVALID_INPUT, f"Invalid vcodec: {e.format_message()}") +def wanted_refusal(wanted: Any) -> Optional[str]: + """Why the job worker could not parse ``wanted``, or None when it can.""" + if not wanted: + return None + from unshackle.core.utils.click_types import SeasonRange + + tokens = re.split(r"\s*[,;]\s*", wanted) if isinstance(wanted, str) else wanted + if not isinstance(tokens, list) or not all(isinstance(t, str) for t in tokens): + return "wanted must be a string or a list of strings" + try: + if any(not re.match(r"^!?\d+x\d+(\.\d+)?$", t) for t in tokens): + SeasonRange().parse_tokens(*tokens) + except (click.BadParameter, ValueError) as e: + return f"Invalid wanted parameter: {e}" + return None + + def validate_download_parameters(data: Dict[str, Any]) -> Optional[str]: """ Validate download parameters and return error message if invalid. @@ -2180,6 +2202,10 @@ async def download_handler(data: Dict[str, Any], request: Optional[web.Request] require_fields(data, "service", "title_id") service_tag = data["service"] title_id = data["title_id"] + if not isinstance(title_id, str): + raise APIError(APIErrorCode.INVALID_INPUT, "title_id must be a string", details={"title_id": title_id}) + if refusal := wanted_refusal(data.get("wanted")): + raise APIError(APIErrorCode.INVALID_INPUT, refusal, details={"wanted": data.get("wanted")}) server, info, data = await relay_target(data, request) normalized_service = info["tag"] if info else validate_service(service_tag, request) @@ -2219,7 +2245,7 @@ async def download_handler(data: Dict[str, Any], request: Optional[web.Request] cast_or_refuse(cli_params, click.Context(click.Command(normalized_service)), sent) service_params = {**defaults, **sent} - filtered_params = {k: v for k, v in data.items() if k not in ["service", "title_id"]} + filtered_params = {k: v for k, v in data.items() if k not in ["service", "title_id", "owner_key"]} # Overlay any dl-relevant keys from `serve:` config (e.g. downloads, workers) so the API # respects server-side defaults without each client having to send them. serve_overrides = { @@ -3937,6 +3963,8 @@ async def session_segments_handler( track_ids = data.get("track_ids", []) if not track_ids: raise APIError(APIErrorCode.INVALID_INPUT, "Missing required parameter: track_ids") + if not isinstance(track_ids, list) or not all(isinstance(t, str) for t in track_ids): + raise APIError(APIErrorCode.INVALID_INPUT, "track_ids must be an array of strings") try: result: Dict[str, Any] = {} @@ -4881,7 +4909,10 @@ def handle_proxy_license( if not challenge_b64: raise APIError(APIErrorCode.INVALID_INPUT, "Missing required parameter: challenge") - challenge_bytes = base64.b64decode(challenge_b64) + try: + challenge_bytes = base64.b64decode(challenge_b64) + except (TypeError, ValueError): + raise APIError(APIErrorCode.INVALID_INPUT, "challenge is not base64") from None if drm_type not in ("widevine", "playready"): raise APIError( diff --git a/unshackle/core/api/routes.py b/unshackle/core/api/routes.py index bb758ebf..a67b94c5 100644 --- a/unshackle/core/api/routes.py +++ b/unshackle/core/api/routes.py @@ -157,11 +157,14 @@ def api_handler(handler: Handler) -> Handler: async def json_body(request: web.Request) -> Any: - """The request's JSON body; raises INVALID_INPUT when it does not parse.""" + """The request's JSON object; raises INVALID_INPUT when it does not parse or is not an object.""" try: - return await request.json() + data = await request.json() except Exception as e: raise APIError(APIErrorCode.INVALID_INPUT, "Invalid JSON request body", details={"error": str(e)}) from e + if not isinstance(data, dict): + raise APIError(APIErrorCode.INVALID_INPUT, "The request body must be a JSON object") + return data HEARTBEAT_INTERVAL = 30.0 diff --git a/unshackle/core/api/sanitize.py b/unshackle/core/api/sanitize.py index e37c4056..c172e31c 100644 --- a/unshackle/core/api/sanitize.py +++ b/unshackle/core/api/sanitize.py @@ -11,9 +11,13 @@ MAX_CACHE_KEY_DEPTH = 8 MAX_SESSION_CACHE_KEYS = 64 -def sanitize_log(value: object) -> str: - """Sanitise a value for safe logging by removing newlines and control characters.""" - return str(value).replace("\n", "").replace("\r", "").replace("\x00", "") +CONTROL_CHARS = re.compile(r"[\x00-\x1f\x7f-\x9f]") +CONTROL_CHARS_BUT_LF = re.compile(r"[\x00-\x09\x0b-\x1f\x7f-\x9f]") + + +def sanitize_log(value: object, keep_lines: bool = False) -> str: + """Remove control characters, and so ANSI escapes, from a value; newlines too unless ``keep_lines``.""" + return (CONTROL_CHARS_BUT_LF if keep_lines else CONTROL_CHARS).sub("", str(value)) def safe_cache_key(key: object) -> Optional[str]: diff --git a/unshackle/core/drm/decrypters.py b/unshackle/core/drm/decrypters.py index 837c4603..2f0861ed 100644 --- a/unshackle/core/drm/decrypters.py +++ b/unshackle/core/drm/decrypters.py @@ -9,6 +9,7 @@ from time import monotonic from typing import Any, Callable from uuid import UUID +import click from rich.text import Text from unshackle.core import binaries @@ -41,7 +42,7 @@ def mp4decrypt_or_shaka(drm: Any, path: Path) -> None: def decrypt_cenc(drm: Any, path: Path, drm_type: str) -> None: """Decrypt ``path`` in place with the decrypter ``decrypter_for`` picks, using the content keys of ``drm``.""" if not drm.content_keys: - raise ValueError("Cannot decrypt a Track without any Content Keys...") + raise click.ClickException(f"Cannot decrypt the {drm_type} track: no content keys") if not path or not path.exists(): raise ValueError("Tried to decrypt a file that does not exist.") diff --git a/unshackle/core/drm/key_resolution.py b/unshackle/core/drm/key_resolution.py index 7a2f8930..533655f6 100644 --- a/unshackle/core/drm/key_resolution.py +++ b/unshackle/core/drm/key_resolution.py @@ -630,7 +630,9 @@ class ContentKeyResolver: f"Licence failed, using the {len(drm.content_keys)} known key(s): {redact_secrets(str(e))}" ) else: - if isinstance(e, (drm.Exceptions.EmptyLicense, drm.Exceptions.CEKNotFound)): + if isinstance( + e, (drm.Exceptions.EmptyLicense, drm.Exceptions.CEKNotFound, click.ClickException) + ): msg = str(e) else: msg = f"An exception occurred in the Service's license function: {e}" diff --git a/unshackle/core/drm/widevine.py b/unshackle/core/drm/widevine.py index d50a7d3a..8b5a7538 100644 --- a/unshackle/core/drm/widevine.py +++ b/unshackle/core/drm/widevine.py @@ -5,10 +5,12 @@ from pathlib import Path from typing import Any, Callable, Optional, Union from uuid import UUID +import click import m3u8 from construct import Container from pymp4.parser import Box from pywidevine.cdm import Cdm as WidevineCdm +from pywidevine.exceptions import InvalidLicenseMessage from pywidevine.pssh import PSSH from unshackle.core.config import config @@ -247,7 +249,12 @@ class Widevine: kid_count=len(self.kids), ) license_res = call_licence(licence, challenge, pssh=self.pssh, session_id=session_id) - cdm.parse_license(session_id, license_res) + try: + cdm.parse_license(session_id, license_res) + except InvalidLicenseMessage: + raise click.ClickException( + f"The licence server sent no usable Widevine licence for KID {kid.hex}" + ) from None log_event( "drm_license_response", level="DEBUG", diff --git a/unshackle/core/remote_service.py b/unshackle/core/remote_service.py index c1c161b1..2f499a4f 100644 --- a/unshackle/core/remote_service.py +++ b/unshackle/core/remote_service.py @@ -138,6 +138,15 @@ def recovering() -> Iterator[None]: _mute.recovering = False +@contextlib.contextmanager +def malformed_answer(what: str) -> Iterator[None]: + """Turn a server answer that does not decode into one RemoteError line instead of a traceback.""" + try: + yield + except (AttributeError, KeyError, TypeError, ValueError) as e: + raise RemoteError(f"The remote server sent malformed {what}: {e}", ClientErrorKind.UNKNOWN) from None + + @contextlib.contextmanager def quiet() -> Iterator[None]: """Log this thread's RemoteErrors at debug level, because the caller reports them.""" @@ -181,11 +190,13 @@ class RemoteError(SystemExit): """ def __init__(self, message: str, kind: str) -> None: + from unshackle.core.api.sanitize import sanitize_log + super().__init__(1) - self.message = message + self.message = sanitize_log(message) self.kind = kind muted = _mute.quiet or (_mute.recovering and kind in RECOVERABLE) - (log.debug if muted else log.error)(message) + (log.debug if muted else log.error)(self.message) def __str__(self) -> str: return self.message @@ -274,9 +285,15 @@ class RemoteClient: detail = resp.json() except ValueError: if resp.status_code < 400: - raise + raise RemoteError( + f"The remote server answered {endpoint} with a body that is not JSON", ClientErrorKind.UNKNOWN + ) detail = {} - late_error = isinstance(detail, dict) and detail.get("status") == "error" and "error_code" in detail + if not isinstance(detail, dict): + raise RemoteError( + f"The remote server answered {endpoint} with JSON that is not an object", ClientErrorKind.UNKNOWN + ) + late_error = detail.get("status") == "error" and "error_code" in detail if resp.status_code >= 400 or late_error: page_title = re.search(r"