mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-29 12:35:13 +00:00
fix(remote): answer malformed input with one line and keep secrets out of logs
This commit is contained in:
@@ -93,3 +93,15 @@ def test_an_empty_challenge_raises_instead_of_licensing() -> None:
|
|||||||
drm.get_content_keys(
|
drm.get_content_keys(
|
||||||
cdm=FakeCdm(challenge=b""), certificate=lambda **_: None, licence=_licence_for(get_widevine_license)
|
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")
|
||||||
|
|||||||
@@ -88,7 +88,7 @@ def test_to_dict_redacts_again_only_when_an_error_field_changes(monkeypatch):
|
|||||||
|
|
||||||
calls = []
|
calls = []
|
||||||
real = download_manager._redact_text
|
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 = DownloadJob(
|
||||||
job_id="j1",
|
job_id="j1",
|
||||||
status=JobStatus.FAILED,
|
status=JobStatus.FAILED,
|
||||||
|
|||||||
@@ -91,6 +91,7 @@ def subtitle(**overrides) -> Subtitle:
|
|||||||
[
|
[
|
||||||
("hello\nworld", "helloworld"),
|
("hello\nworld", "helloworld"),
|
||||||
("a\r\nb\x00c", "abc"),
|
("a\r\nb\x00c", "abc"),
|
||||||
|
("\x1b[31mred\x1b[0m", "[31mred[0m"),
|
||||||
("clean", "clean"),
|
("clean", "clean"),
|
||||||
(12345, "12345"),
|
(12345, "12345"),
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -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"]
|
||||||
@@ -556,9 +556,9 @@ def serve(
|
|||||||
return limited
|
return limited
|
||||||
if serve_playready_flag and request.path in ("/playready", "/playready/"):
|
if serve_playready_flag and request.path in ("/playready", "/playready/"):
|
||||||
response = await handler(request)
|
response = await handler(request)
|
||||||
elif secret_key and not request.headers.get("X-Secret-Key"):
|
elif secret_key and not known:
|
||||||
if not known:
|
return web.json_response({"status": 401, "message": "Secret Key is Invalid."}, status=401)
|
||||||
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)
|
response = await handler(request)
|
||||||
else:
|
else:
|
||||||
response = await pywidevine_serve.authentication(request, handler)
|
response = await pywidevine_serve.authentication(request, handler)
|
||||||
|
|||||||
@@ -49,11 +49,18 @@ def redact_parameters(parameters: Dict[str, Any]) -> Dict[str, Any]:
|
|||||||
return redacted
|
return redacted
|
||||||
|
|
||||||
|
|
||||||
def secret_values(parameters: Dict[str, Any]) -> List[str]:
|
def secret_values(parameters: Dict[str, Any], service: Optional[str] = None) -> List[str]:
|
||||||
"""Raw secret strings carried in job parameters, longest first, for scrubbing free text."""
|
"""Raw secret strings carried in job parameters and the credentials configured for ``service``, longest first."""
|
||||||
if not isinstance(parameters, dict):
|
if not isinstance(parameters, dict):
|
||||||
return []
|
return []
|
||||||
secrets: List[str] = []
|
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"):
|
for key in ("credential", "password", "token", "api_key"):
|
||||||
value = parameters.get(key)
|
value = parameters.get(key)
|
||||||
if isinstance(value, str) and value:
|
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]
|
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
|
"""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."""
|
(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):
|
class JobStatus(Enum):
|
||||||
@@ -183,7 +190,10 @@ class DownloadJob:
|
|||||||
names = ("error_message", "error_details", "error_traceback", "worker_stderr")
|
names = ("error_message", "error_details", "error_traceback", "worker_stderr")
|
||||||
self.redacted = (
|
self.redacted = (
|
||||||
raw,
|
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(
|
result.update(
|
||||||
{
|
{
|
||||||
@@ -237,7 +247,7 @@ def record_job_history(job: DownloadJob) -> None:
|
|||||||
"output_files": job.output_files,
|
"output_files": job.output_files,
|
||||||
"skipped_titles": job.skipped_titles,
|
"skipped_titles": job.skipped_titles,
|
||||||
"parameters": redact_parameters(job.parameters),
|
"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:
|
try:
|
||||||
path = history_path()
|
path = history_path()
|
||||||
@@ -867,7 +877,9 @@ class DownloadQueueManager:
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
job.status = JobStatus.FAILED
|
job.status = JobStatus.FAILED
|
||||||
job.error_message = str(e)
|
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:
|
finally:
|
||||||
job.completed_time = datetime.now()
|
job.completed_time = datetime.now()
|
||||||
record_job_history(job)
|
record_job_history(job)
|
||||||
@@ -905,7 +917,7 @@ class DownloadQueueManager:
|
|||||||
job.error_code = job.error_code or api_error.error_code.value
|
job.error_code = job.error_code or api_error.error_code.value
|
||||||
job.error_traceback = job.error_traceback or traceback.format_exc()
|
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
|
raise
|
||||||
|
|
||||||
def worker_speed_limit(self) -> Optional[float]:
|
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
|
# 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.
|
# it reaches the log as well, not only the API response.
|
||||||
safe_stdout = _redact_text(stdout.strip(), job.parameters)
|
safe_stdout = _redact_text(stdout.strip(), job.parameters, job.service)
|
||||||
safe_stderr = _redact_text(stderr.strip(), job.parameters)
|
safe_stderr = _redact_text(stderr.strip(), job.parameters, job.service)
|
||||||
if stdout.strip():
|
if stdout.strip():
|
||||||
log.debug(f"Worker stdout for job {job.job_id}: {safe_stdout}")
|
log.debug(f"Worker stdout for job {job.job_id}: {safe_stdout}")
|
||||||
if stderr.strip():
|
if stderr.strip():
|
||||||
|
|||||||
@@ -328,7 +328,12 @@ def write_client_cache(cache_data: Any, cache_tag: str) -> None:
|
|||||||
continue
|
continue
|
||||||
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")
|
||||||
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):
|
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
|
||||||
@@ -1894,6 +1899,23 @@ def resolve_vcodec(value: Any) -> Optional[list]:
|
|||||||
raise APIError(APIErrorCode.INVALID_INPUT, f"Invalid vcodec: {e.format_message()}")
|
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]:
|
def validate_download_parameters(data: Dict[str, Any]) -> Optional[str]:
|
||||||
"""
|
"""
|
||||||
Validate download parameters and return error message if invalid.
|
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")
|
require_fields(data, "service", "title_id")
|
||||||
service_tag = data["service"]
|
service_tag = data["service"]
|
||||||
title_id = data["title_id"]
|
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)
|
server, info, data = await relay_target(data, request)
|
||||||
normalized_service = info["tag"] if info else validate_service(service_tag, 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)
|
cast_or_refuse(cli_params, click.Context(click.Command(normalized_service)), sent)
|
||||||
service_params = {**defaults, **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
|
# 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.
|
# respects server-side defaults without each client having to send them.
|
||||||
serve_overrides = {
|
serve_overrides = {
|
||||||
@@ -3937,6 +3963,8 @@ async def session_segments_handler(
|
|||||||
track_ids = data.get("track_ids", [])
|
track_ids = data.get("track_ids", [])
|
||||||
if not track_ids:
|
if not track_ids:
|
||||||
raise APIError(APIErrorCode.INVALID_INPUT, "Missing required parameter: 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:
|
try:
|
||||||
result: Dict[str, Any] = {}
|
result: Dict[str, Any] = {}
|
||||||
@@ -4881,7 +4909,10 @@ def handle_proxy_license(
|
|||||||
|
|
||||||
if not challenge_b64:
|
if not challenge_b64:
|
||||||
raise APIError(APIErrorCode.INVALID_INPUT, "Missing required parameter: challenge")
|
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"):
|
if drm_type not in ("widevine", "playready"):
|
||||||
raise APIError(
|
raise APIError(
|
||||||
|
|||||||
@@ -157,11 +157,14 @@ def api_handler(handler: Handler) -> Handler:
|
|||||||
|
|
||||||
|
|
||||||
async def json_body(request: web.Request) -> Any:
|
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:
|
try:
|
||||||
return await request.json()
|
data = await request.json()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise APIError(APIErrorCode.INVALID_INPUT, "Invalid JSON request body", details={"error": str(e)}) from 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
|
HEARTBEAT_INTERVAL = 30.0
|
||||||
|
|||||||
@@ -11,9 +11,13 @@ MAX_CACHE_KEY_DEPTH = 8
|
|||||||
MAX_SESSION_CACHE_KEYS = 64
|
MAX_SESSION_CACHE_KEYS = 64
|
||||||
|
|
||||||
|
|
||||||
def sanitize_log(value: object) -> str:
|
CONTROL_CHARS = re.compile(r"[\x00-\x1f\x7f-\x9f]")
|
||||||
"""Sanitise a value for safe logging by removing newlines and control characters."""
|
CONTROL_CHARS_BUT_LF = re.compile(r"[\x00-\x09\x0b-\x1f\x7f-\x9f]")
|
||||||
return str(value).replace("\n", "").replace("\r", "").replace("\x00", "")
|
|
||||||
|
|
||||||
|
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]:
|
def safe_cache_key(key: object) -> Optional[str]:
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ from time import monotonic
|
|||||||
from typing import Any, Callable
|
from typing import Any, Callable
|
||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
|
|
||||||
|
import click
|
||||||
from rich.text import Text
|
from rich.text import Text
|
||||||
|
|
||||||
from unshackle.core import binaries
|
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:
|
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``."""
|
"""Decrypt ``path`` in place with the decrypter ``decrypter_for`` picks, using the content keys of ``drm``."""
|
||||||
if not drm.content_keys:
|
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():
|
if not path or not path.exists():
|
||||||
raise ValueError("Tried to decrypt a file that does not exist.")
|
raise ValueError("Tried to decrypt a file that does not exist.")
|
||||||
|
|||||||
@@ -630,7 +630,9 @@ class ContentKeyResolver:
|
|||||||
f"Licence failed, using the {len(drm.content_keys)} known key(s): {redact_secrets(str(e))}"
|
f"Licence failed, using the {len(drm.content_keys)} known key(s): {redact_secrets(str(e))}"
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
if isinstance(e, (drm.Exceptions.EmptyLicense, drm.Exceptions.CEKNotFound)):
|
if isinstance(
|
||||||
|
e, (drm.Exceptions.EmptyLicense, drm.Exceptions.CEKNotFound, click.ClickException)
|
||||||
|
):
|
||||||
msg = str(e)
|
msg = str(e)
|
||||||
else:
|
else:
|
||||||
msg = f"An exception occurred in the Service's license function: {e}"
|
msg = f"An exception occurred in the Service's license function: {e}"
|
||||||
|
|||||||
@@ -5,10 +5,12 @@ from pathlib import Path
|
|||||||
from typing import Any, Callable, Optional, Union
|
from typing import Any, Callable, Optional, Union
|
||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
|
|
||||||
|
import click
|
||||||
import m3u8
|
import m3u8
|
||||||
from construct import Container
|
from construct import Container
|
||||||
from pymp4.parser import Box
|
from pymp4.parser import Box
|
||||||
from pywidevine.cdm import Cdm as WidevineCdm
|
from pywidevine.cdm import Cdm as WidevineCdm
|
||||||
|
from pywidevine.exceptions import InvalidLicenseMessage
|
||||||
from pywidevine.pssh import PSSH
|
from pywidevine.pssh import PSSH
|
||||||
|
|
||||||
from unshackle.core.config import config
|
from unshackle.core.config import config
|
||||||
@@ -247,7 +249,12 @@ class Widevine:
|
|||||||
kid_count=len(self.kids),
|
kid_count=len(self.kids),
|
||||||
)
|
)
|
||||||
license_res = call_licence(licence, challenge, pssh=self.pssh, session_id=session_id)
|
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(
|
log_event(
|
||||||
"drm_license_response",
|
"drm_license_response",
|
||||||
level="DEBUG",
|
level="DEBUG",
|
||||||
|
|||||||
@@ -138,6 +138,15 @@ def recovering() -> Iterator[None]:
|
|||||||
_mute.recovering = False
|
_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
|
@contextlib.contextmanager
|
||||||
def quiet() -> Iterator[None]:
|
def quiet() -> Iterator[None]:
|
||||||
"""Log this thread's RemoteErrors at debug level, because the caller reports them."""
|
"""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:
|
def __init__(self, message: str, kind: str) -> None:
|
||||||
|
from unshackle.core.api.sanitize import sanitize_log
|
||||||
|
|
||||||
super().__init__(1)
|
super().__init__(1)
|
||||||
self.message = message
|
self.message = sanitize_log(message)
|
||||||
self.kind = kind
|
self.kind = kind
|
||||||
muted = _mute.quiet or (_mute.recovering and kind in RECOVERABLE)
|
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:
|
def __str__(self) -> str:
|
||||||
return self.message
|
return self.message
|
||||||
@@ -274,9 +285,15 @@ class RemoteClient:
|
|||||||
detail = resp.json()
|
detail = resp.json()
|
||||||
except ValueError:
|
except ValueError:
|
||||||
if resp.status_code < 400:
|
if resp.status_code < 400:
|
||||||
raise
|
raise RemoteError(
|
||||||
|
f"The remote server answered {endpoint} with a body that is not JSON", ClientErrorKind.UNKNOWN
|
||||||
|
)
|
||||||
detail = {}
|
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:
|
if resp.status_code >= 400 or late_error:
|
||||||
page_title = re.search(r"<title>(.*?)</title>", resp.text, re.S) if not detail else None
|
page_title = re.search(r"<title>(.*?)</title>", resp.text, re.S) if not detail else None
|
||||||
fallback = f"HTTP {resp.status_code}: {page_title.group(1).strip()}" if page_title else resp.text
|
fallback = f"HTTP {resp.status_code}: {page_title.group(1).strip()}" if page_title else resp.text
|
||||||
@@ -1159,6 +1176,8 @@ class RemoteService:
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
result = cast(SessionCreated, self.client.post(SESSION_CREATE_ROUTE, create_data))
|
result = cast(SessionCreated, self.client.post(SESSION_CREATE_ROUTE, create_data))
|
||||||
|
if not isinstance(result.get("session_id"), str):
|
||||||
|
raise RemoteError("The remote server sent malformed session: no session_id", ClientErrorKind.UNKNOWN)
|
||||||
except BaseException:
|
except BaseException:
|
||||||
if local and self.client.tunnel: # no session, so close() never runs: free the tunnel now
|
if local and self.client.tunnel: # no session, so close() never runs: free the tunnel now
|
||||||
self.client.tunnel.stop()
|
self.client.tunnel.stop()
|
||||||
@@ -1399,11 +1418,14 @@ class RemoteService:
|
|||||||
return
|
return
|
||||||
if not resp:
|
if not resp:
|
||||||
return
|
return
|
||||||
|
from unshackle.core.api.sanitize import sanitize_log
|
||||||
|
|
||||||
level_names = logging.getLevelNamesMapping()
|
level_names = logging.getLevelNamesMapping()
|
||||||
for record in resp.get("logs", []):
|
for record in resp.get("logs", []):
|
||||||
level = level_names.get(str(record.get("level", "INFO")), logging.INFO)
|
level = level_names.get(str(record.get("level", "INFO")), logging.INFO)
|
||||||
self.log.log(level, str(record.get("message", "")))
|
message = sanitize_log(record.get("message", ""), keep_lines=True)
|
||||||
self._recent_logs.append(str(record.get("message", "")).strip())
|
self.log.log(level, message)
|
||||||
|
self._recent_logs.append(message.strip())
|
||||||
self._log_seq = int(resp.get("last_seq", self._log_seq))
|
self._log_seq = int(resp.get("last_seq", self._log_seq))
|
||||||
|
|
||||||
def poll_auth_completion(self, poll_interval: float = 2.0, timeout: float = 600.0) -> None:
|
def poll_auth_completion(self, poll_interval: float = 2.0, timeout: float = 600.0) -> None:
|
||||||
@@ -1448,7 +1470,9 @@ class RemoteService:
|
|||||||
continue
|
continue
|
||||||
|
|
||||||
if status == AuthStatus.PENDING_INPUT:
|
if status == AuthStatus.PENDING_INPUT:
|
||||||
prompt = resp.get("prompt") or "Enter input: "
|
from unshackle.core.api.sanitize import sanitize_log
|
||||||
|
|
||||||
|
prompt = sanitize_log(resp.get("prompt") or "Enter input: ", keep_lines=True)
|
||||||
bridge = self._input_bridge
|
bridge = self._input_bridge
|
||||||
try:
|
try:
|
||||||
user_response = bridge.request_input(prompt) if bridge else prompt_user(prompt)
|
user_response = bridge.request_input(prompt) if bridge else prompt_user(prompt)
|
||||||
@@ -1532,7 +1556,8 @@ class RemoteService:
|
|||||||
)
|
)
|
||||||
finally:
|
finally:
|
||||||
self.drain_server_logs()
|
self.drain_server_logs()
|
||||||
titles_list = [build_title(t, self.service_tag, self.title_id) for t in result.get("titles", [])]
|
with malformed_answer("titles"):
|
||||||
|
titles_list = [build_title(t, self.service_tag, self.title_id) for t in result.get("titles") or []]
|
||||||
first = titles_list[0] if titles_list else None
|
first = titles_list[0] if titles_list else None
|
||||||
if isinstance(first, Episode):
|
if isinstance(first, Episode):
|
||||||
self._titles = Series(titles_list)
|
self._titles = Series(titles_list)
|
||||||
@@ -1567,20 +1592,21 @@ class RemoteService:
|
|||||||
)
|
)
|
||||||
finally:
|
finally:
|
||||||
self.drain_server_logs()
|
self.drain_server_logs()
|
||||||
tracks = build_tracks(result)
|
with malformed_answer("tracks"):
|
||||||
|
tracks = build_tracks(result)
|
||||||
|
|
||||||
remote_title = result.get("title") or {}
|
remote_title = result.get("title") or {}
|
||||||
if remote_title:
|
if remote_title:
|
||||||
apply_title_fields(title, remote_title)
|
apply_title_fields(title, remote_title)
|
||||||
|
|
||||||
session_fields = cast(TracksReply, result)
|
session_fields = cast(TracksReply, result)
|
||||||
for k, v in session_fields.get("session_headers", {}).items():
|
for k, v in session_fields.get("session_headers", {}).items():
|
||||||
if k.lower() not in ("host", "content-length", "content-type"):
|
if k.lower() not in ("host", "content-length", "content-type"):
|
||||||
self._session.headers[k] = v
|
self._session.headers[k] = v
|
||||||
apply_session_cookies(self._session, result)
|
apply_session_cookies(self._session, result)
|
||||||
|
|
||||||
restore(tracks, result)
|
restore(tracks, result)
|
||||||
apply_service_track_data(tracks, result)
|
apply_service_track_data(tracks, result)
|
||||||
|
|
||||||
server_cdm = bool(session_fields.get("server_cdm", False)) or getattr(self, "_server_device", False)
|
server_cdm = bool(session_fields.get("server_cdm", False)) or getattr(self, "_server_device", False)
|
||||||
if self._server_cdm is None:
|
if self._server_cdm is None:
|
||||||
|
|||||||
Reference in New Issue
Block a user