From 43987f98094ad69057096b4a7b3370e8a65096d4 Mon Sep 17 00:00:00 2001 From: imSp4rky Date: Tue, 24 Nov 2026 19:26:26 -0700 Subject: [PATCH] refactor(api): build a remote session whole, with one login state --- docs/dev/rest-api/remote-sessions.md | 11 ++- tests/remote/sessions.py | 19 +++++ tests/remote/unit/test_client_device_cdm.py | 29 +++++-- tests/remote/unit/test_extract_pssh_strict.py | 10 +-- tests/remote/unit/test_input_bridge.py | 32 ++++++-- .../unit/test_remote_service_helpers.py | 5 +- tests/remote/unit/test_route_error_replies.py | 16 +++- tests/remote/unit/test_segment_filter.py | 5 +- .../unit/test_server_cdm_absorb_routes.py | 29 +------ .../unit/test_server_cdm_key_verification.py | 22 ++--- .../unit/test_server_cdm_manifest_kid.py | 11 +-- .../remote/unit/test_server_cdm_max_height.py | 28 +++---- tests/remote/unit/test_server_cdm_multikey.py | 10 +-- .../unit/test_server_cdm_type_override.py | 10 +-- tests/remote/unit/test_session_channel.py | 8 +- tests/remote/unit/test_session_reporting.py | 40 +++++++++ tests/remote/unit/test_session_store.py | 80 +++++++++++++----- tests/test_client_session_auth.py | 14 +++- unshackle/core/api/handlers.py | 81 +++++++------------ unshackle/core/api/input_bridge.py | 16 ++-- unshackle/core/api/session_store.py | 49 +++++++++-- 21 files changed, 320 insertions(+), 205 deletions(-) create mode 100644 tests/remote/sessions.py diff --git a/docs/dev/rest-api/remote-sessions.md b/docs/dev/rest-api/remote-sessions.md index ccdb9809..2751ce48 100644 --- a/docs/dev/rest-api/remote-sessions.md +++ b/docs/dev/rest-api/remote-sessions.md @@ -529,7 +529,7 @@ layer. - `AuthStatus` values: `authenticating`, `pending_input`, `authenticated`, `failed`. - `InputBridge.request_input(prompt, timeout=600)` blocks the sync auth thread on a `threading.Event` until `submit_response()` or `cancel()` fires. -- A timeout raises `TimeoutError` and marks the remote session `FAILED`. +- A timeout raises `TimeoutError`. The remote session becomes `FAILED` when that error ends the login. - A prompt after authentication (in `get_titles()`, `get_tracks()` or licensing) goes to the client on an open remote session channel. Without the channel it raises `RuntimeError` at once: the client polls for prompts only during authentication, so no answer can come. @@ -538,7 +538,7 @@ layer. fails then, because no client is listening. A fetched call waits 60 seconds for its answer. The call leaves the auth status as it was. An answer never marks the remote session as client-authenticated. - `AUTH_INPUT_TIMEOUT = 600.0` seconds. This is also the TTL granted to - `AUTHENTICATING` / `PENDING_INPUT` sessions in the store. + `AUTHENTICATING` sessions in the store. A remote session that waits on a prompt stays `AUTHENTICATING`. `GET /api/session/{id}/prompt` returns one of: @@ -605,11 +605,10 @@ Source: `unshackle/core/api/session_store.py`. A singleton you get from `serve.max_sessions` (default `100`) are read as properties, so config changes take effect without recreating the store. - **`create()`** evicts the least-recently-accessed remote session of the API key that holds the most when at capacity, - then stores a new `SessionEntry`. It defaults `auth_status` to `AUTHENTICATED`, and - the `create` handler overrides it to `AUTHENTICATING`. + then stores a complete `SessionEntry` from the fields of the `create` handler and publishes the `create` event. - **`get()`** refreshes `last_accessed` through `touch()`. It returns `None` (and deletes the entry) if an authenticated remote session has been idle longer than the - TTL. Remote sessions in `AUTHENTICATING` / `PENDING_INPUT` are exempt from TTL expiry. + TTL. Remote sessions in `AUTHENTICATING` are exempt from TTL expiry. - **`cleanup_expired()`** runs every 60s: authenticated remote sessions expire at `ttl`, in-flight-auth remote sessions expire at `AUTH_INPUT_TIMEOUT`. The removal of a remote session cancels its `InputBridge` and deletes its cache directory (pruning @@ -629,7 +628,7 @@ Source: `unshackle/core/api/session_store.py`. A singleton you get from | `creator_ip` | IP recorded at create time for IP-binding checks | | `cache_tag` | Per-session cache directory tag | | `input_bridge` | `InputBridge` for interactive auth, if any | -| `auth_status` / `auth_error` | Current `AuthStatus` and last error message | +| `auth_status` / `auth_error` | Current `AuthStatus`, read from `input_bridge` (`AUTHENTICATED` without one), and last error message | | `created_at` / `last_accessed` | Timestamps; `last_accessed` drives TTL and LRU eviction | ### Per-session cache namespacing diff --git a/tests/remote/sessions.py b/tests/remote/sessions.py new file mode 100644 index 00000000..79db1ed7 --- /dev/null +++ b/tests/remote/sessions.py @@ -0,0 +1,19 @@ +"""A real remote session entry for the tests that call the session and licence handlers directly.""" + +from types import SimpleNamespace +from typing import Any + +from unshackle.core.api.session_store import SessionEntry + + +def session_entry(**fields: Any) -> SessionEntry: + """A remote session that the server CDM licenses, unless *fields* set another :class:`SessionEntry` value.""" + return SessionEntry( + **{ + "session_id": "sess", + "service_tag": "EXAMPLE", + "service_instance": SimpleNamespace(), + "server_cdm": True, + **fields, + } + ) diff --git a/tests/remote/unit/test_client_device_cdm.py b/tests/remote/unit/test_client_device_cdm.py index 36acd1d5..959f7a8d 100644 --- a/tests/remote/unit/test_client_device_cdm.py +++ b/tests/remote/unit/test_client_device_cdm.py @@ -14,11 +14,12 @@ import pytest from pywidevine import DeviceTypes from pywidevine.pssh import PSSH +from tests.remote.sessions import session_entry from unshackle.core.api import handlers from unshackle.core.api.errors import APIError from unshackle.core.api.input_bridge import InputBridge from unshackle.core.cdm.client_relay import ClientDeviceCdm, answer_cdm_call -from unshackle.core.remote_protocol import AuthStatus +from unshackle.core.remote_protocol import APIErrorCode, AuthStatus pytestmark = pytest.mark.unit @@ -104,7 +105,7 @@ def test_the_client_refuses_a_challenge_for_the_other_drm_system() -> None: def test_a_cdm_call_after_authentication_leaves_the_status_alone() -> None: bridge = InputBridge() - bridge.status = AuthStatus.AUTHENTICATED + bridge.login_status = AuthStatus.AUTHENTICATED result: list[dict] = [] worker = threading.Thread(target=lambda: result.append(bridge.request_cdm({"op": "challenge"}, timeout=5))) worker.start() @@ -240,7 +241,7 @@ def test_a_lent_server_device_marks_the_stand_in() -> None: def test_a_lent_device_session_never_licenses_live() -> None: - refusal = handlers.live_licence_refusal(SimpleNamespace(server_device=True, server_cdm=False), object()) + refusal = handlers.live_licence_refusal(session_entry(server_device=True, server_cdm=False), object()) assert refusal is not None assert refusal.details == {"reason": "server_device"} @@ -248,7 +249,7 @@ def test_a_lent_device_session_never_licenses_live() -> None: def test_a_vault_only_miss_raises_the_refusal(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(handlers, "check_vaults", lambda kids, service, **_: None) monkeypatch.setattr(handlers, "ensure_track_drm", lambda *a, **k: None) - refusal = handlers.live_licence_refusal(SimpleNamespace(server_device=True), object()) + refusal = handlers.live_licence_refusal(session_entry(server_device=True), object()) with pytest.raises(APIError) as caught: handlers.handle_single_server_cdm( SimpleNamespace(), @@ -354,11 +355,11 @@ def test_a_client_map_entry_replaces_the_server_entry_of_the_same_number() -> No def lent_device_session() -> Any: - return SimpleNamespace( + return session_entry( + server_cdm=False, server_device=True, client_auth=True, cache_tag="_sessions/abc/sid/EXAMPLE1", - input_bridge=None, service_instance=SimpleNamespace( session=SimpleNamespace( headers={"Authorization": "Bearer server", "User-Agent": "ua"}, @@ -430,7 +431,7 @@ def test_every_service_context_defaults_quality_to_a_list(extra: Any) -> None: def test_a_call_no_client_fetches_fails_fast_and_restores_the_status() -> None: bridge = InputBridge() - bridge.status = AuthStatus.AUTHENTICATED + bridge.login_status = AuthStatus.AUTHENTICATED started = time.monotonic() with pytest.raises(TimeoutError, match="none is listening"): bridge.request_cdm({"op": "challenge"}, timeout=30, pickup=0.2) @@ -461,3 +462,17 @@ def test_cancel_wakes_a_call_waiting_for_a_client() -> None: with pytest.raises(RuntimeError, match="cancelled"): bridge.request_cdm({"op": "challenge"}, timeout=30, pickup=20) assert time.monotonic() - started < 5 + + +@pytest.mark.parametrize( + ("fields", "forbidden"), + [({"server_cdm": False}, True), ({"server_cdm": False, "server_vault": True}, False), ({}, False)], +) +def test_the_server_licence_route_follows_the_licensing_mode( + monkeypatch: pytest.MonkeyPatch, fields: dict, forbidden: bool +) -> None: + """A session that the client's device licenses reaches the server licence route only for the server vault.""" + monkeypatch.setattr(handlers, "server_cdm_allowed", lambda request, service: True) + with pytest.raises(APIError) as caught: + handlers.license_response({"mode": "server_cdm", "track_id": "none"}, session_entry(**fields), "sess", None) + assert (caught.value.error_code is APIErrorCode.FORBIDDEN) is forbidden diff --git a/tests/remote/unit/test_extract_pssh_strict.py b/tests/remote/unit/test_extract_pssh_strict.py index 9c0ff262..71b41391 100644 --- a/tests/remote/unit/test_extract_pssh_strict.py +++ b/tests/remote/unit/test_extract_pssh_strict.py @@ -5,12 +5,12 @@ loop licensed a PlayReady-only track as Widevine by accident. A Widevine device license PlayReady-only content, but only as a deliberate step in the batch loop. """ -import asyncio import json from types import SimpleNamespace import pytest +from tests.remote.sessions import session_entry from unshackle.core.api import handlers pytestmark = pytest.mark.unit @@ -44,13 +44,7 @@ def test_extractor_is_type_strict(): async def _run_batch(monkeypatch, tracks, cdm_type, calls): - session = SimpleNamespace( - lock=asyncio.Lock(), - service_tag="EXAMPLE", - service_instance=SimpleNamespace(), - served_keys={}, - tracks=SimpleNamespace(get=tracks.get), - ) + session = session_entry(tracks=tracks) async def fake_get_session(session_id, request): return session diff --git a/tests/remote/unit/test_input_bridge.py b/tests/remote/unit/test_input_bridge.py index cc417e99..f3ccc040 100644 --- a/tests/remote/unit/test_input_bridge.py +++ b/tests/remote/unit/test_input_bridge.py @@ -4,6 +4,7 @@ from __future__ import annotations import threading import time +from types import SimpleNamespace import pytest @@ -51,7 +52,24 @@ def test_request_input_times_out() -> None: bridge = InputBridge() with pytest.raises(TimeoutError, match="No client response"): bridge.request_input("hello", timeout=0.6) - assert bridge.status is AuthStatus.FAILED + assert bridge.status is AuthStatus.AUTHENTICATING + + +def test_a_prompt_after_a_timed_out_one_takes_its_answer() -> None: + """A login that catches the timeout and asks again gets the answer through the prompt routes.""" + bridge = InputBridge() + with pytest.raises(TimeoutError): + bridge.request_input("Code?", timeout=0.01) + offered = threading.Event() + bridge.channel = SimpleNamespace(offer=lambda ask: offered.set() or False, attached=False) # type: ignore[assignment] + answers: list[str] = [] + worker = threading.Thread(target=lambda: answers.append(bridge.request_input("Code again?", timeout=5))) + worker.start() + assert offered.wait(5) + assert bridge.status is AuthStatus.PENDING_INPUT + assert bridge.submit_response("1234") + worker.join(5) + assert answers == ["1234"] def test_cancel_before_request_raises_immediately() -> None: @@ -59,7 +77,7 @@ def test_cancel_before_request_raises_immediately() -> None: bridge.cancel() with pytest.raises(RuntimeError, match="cancelled"): bridge.request_input("hello", timeout=5) - assert bridge.status is AuthStatus.FAILED + assert bridge.status is AuthStatus.AUTHENTICATING # ending a session leaves its login state as it was def test_cancel_unblocks_pending_request() -> None: @@ -82,25 +100,25 @@ def test_cancel_unblocks_pending_request() -> None: bridge.cancel() t.join(timeout=2) assert exc and isinstance(exc[0], RuntimeError) - assert bridge.status is AuthStatus.FAILED + assert bridge.status is AuthStatus.AUTHENTICATING def test_get_pending_prompt_returns_none_outside_pending_state() -> None: bridge = InputBridge() - bridge.status = AuthStatus.AUTHENTICATED + bridge.login_status = AuthStatus.AUTHENTICATED assert bridge.get_pending_prompt() is None -def test_status_setter() -> None: +def test_login_status_setter() -> None: bridge = InputBridge() - bridge.status = AuthStatus.AUTHENTICATED + bridge.login_status = AuthStatus.AUTHENTICATED assert bridge.status is AuthStatus.AUTHENTICATED def test_request_input_after_authentication_fails_fast() -> None: """The client stops polling for prompts once authenticated, so a later prompt must not wait for an answer.""" bridge = InputBridge() - bridge.status = AuthStatus.AUTHENTICATED + bridge.login_status = AuthStatus.AUTHENTICATED with pytest.raises(RuntimeError, match="after authentication"): bridge.request_input("Pick a profile", timeout=5) assert bridge.status is AuthStatus.AUTHENTICATED diff --git a/tests/remote/unit/test_remote_service_helpers.py b/tests/remote/unit/test_remote_service_helpers.py index dd872da4..59638d87 100644 --- a/tests/remote/unit/test_remote_service_helpers.py +++ b/tests/remote/unit/test_remote_service_helpers.py @@ -6,6 +6,7 @@ from enum import Enum import pytest +from tests.remote.sessions import session_entry from unshackle.core.manifests.snapshot import match_track from unshackle.core.remote_service import RemoteService from unshackle.core.titles.episode import Episode @@ -517,7 +518,6 @@ async def test_session_delete_returns_nested_cache_keys(tmp_path, monkeypatch) - import base64 import json import zlib - from types import SimpleNamespace from unshackle.core.api import handlers, session_store @@ -529,7 +529,7 @@ async def test_session_delete_returns_nested_cache_keys(tmp_path, monkeypatch) - path.write_text(rel) monkeypatch.setattr(handlers.config.directories, "cache", tmp_path) - session = SimpleNamespace(cache_tag=cache_tag, client_auth=True, input_bridge=None) + session = session_entry(service_tag="TESTSVC", cache_tag=cache_tag, client_auth=True) async def fake_validated(session_id, request): return session @@ -545,6 +545,7 @@ async def test_session_delete_returns_nested_cache_keys(tmp_path, monkeypatch) - body = json.loads(response.body) assert set(body["cache"]) == {"tokens", "session_web/abc", "MSL/web/keys", "MSL/keys.v2"} assert zlib.decompress(base64.b64decode(body["cache"]["session_web/abc"])) == b"session_web/abc" + assert session.channel.ended def test_resolve_manifest_data_matches_across_per_range_manifests() -> None: diff --git a/tests/remote/unit/test_route_error_replies.py b/tests/remote/unit/test_route_error_replies.py index bb58c408..f35d2168 100644 --- a/tests/remote/unit/test_route_error_replies.py +++ b/tests/remote/unit/test_route_error_replies.py @@ -23,6 +23,7 @@ from unshackle.core.api import handlers, routes from unshackle.core.api.compression import compression_middleware from unshackle.core.api.errors import APIError from unshackle.core.api.handlers import api_key_authentication, dashboard_authentication +from unshackle.core.api.input_bridge import InputBridge from unshackle.core.api.routes import DASHBOARD_ROUTES, ROUTES, cors_middleware, no_5xx_middleware, setup_routes from unshackle.core.api.session_store import get_session_store from unshackle.core.api.stats import stats, stats_middleware @@ -248,8 +249,17 @@ def fault_cases() -> dict[str, Case]: async def open_session(stand_in: Faulty, owner: str, status: AuthStatus) -> None: - session = await get_session_store().create("EXAMPLE", stand_in, session_id=SESSION, owner_key=owner) - session.auth_status = status + bridge = getattr(stand_in, "input_bridge", None) or InputBridge() + bridge.login_status = status + session = await get_session_store().create( + "EXAMPLE", + stand_in, + session_id=SESSION, + owner_key=owner, + server_cdm=True, + input_bridge=bridge, + log_buffer=getattr(stand_in, "log_buffer", None), + ) session.title_map["title-0001"] = Movie(id_="title-0001", service=object, name="Film", year=2024, language=None) track = SimpleNamespace( id="v1", @@ -262,8 +272,6 @@ async def open_session(stand_in: Faulty, owner: str, status: AuthStatus) -> None session.tracks["v1"] = track # type: ignore[assignment] session.tracks_by_title["title-0001"] = {"v1": track} # type: ignore[dict-item] session.served_keys["00" * 16] = ("11" * 16, "pinned-vault") - session.input_bridge = getattr(stand_in, "input_bridge", None) - session.log_buffer = getattr(stand_in, "log_buffer", None) def masked(value: Any, ref: Optional[str]) -> Any: diff --git a/tests/remote/unit/test_segment_filter.py b/tests/remote/unit/test_segment_filter.py index 840d16a6..b461d9de 100644 --- a/tests/remote/unit/test_segment_filter.py +++ b/tests/remote/unit/test_segment_filter.py @@ -2,13 +2,13 @@ from __future__ import annotations -import asyncio import json from types import SimpleNamespace import pytest import responses +from tests.remote.sessions import session_entry from unshackle.core.api import handlers from unshackle.core.remote_service import RemoteClient, RemoteService @@ -29,8 +29,7 @@ BASE = "https://cdn.test/hls/media.m3u8" def make_session(monkeypatch, track): - session = SimpleNamespace( - lock=asyncio.Lock(), + session = session_entry( tracks={"t1": track}, service_instance=SimpleNamespace(session=SimpleNamespace(get=lambda url: SimpleNamespace(text=PLAYLIST))), ) diff --git a/tests/remote/unit/test_server_cdm_absorb_routes.py b/tests/remote/unit/test_server_cdm_absorb_routes.py index b6a5f13e..b20c9684 100644 --- a/tests/remote/unit/test_server_cdm_absorb_routes.py +++ b/tests/remote/unit/test_server_cdm_absorb_routes.py @@ -6,7 +6,6 @@ the first PSSH alone and so handed one track another track's narrower key set, a with no readable PSSH told the client nothing. """ -import asyncio import base64 import json from types import SimpleNamespace @@ -18,6 +17,7 @@ import pytest import unshackle.core.cdm as cdm_mod import unshackle.core.cdm.detect as detect_mod import unshackle.core.drm as drm_mod +from tests.remote.sessions import session_entry from unshackle.core.api import handlers pytestmark = pytest.mark.unit @@ -77,14 +77,7 @@ async def test_single_track_path_keeps_siblings(env, monkeypatch): id="vid", drm=[_FakePlayReady(pssh_b64=PSSH, kid=KID_A), _FakePlayReady(pssh_b64=PSSH, kid=KID_B)], ) - session = SimpleNamespace( - lock=asyncio.Lock(), - service_tag="EX", - service_instance=SimpleNamespace(), - served_keys={}, - tracks=SimpleNamespace(get={"vid": track}.get), - log_buffer=None, - ) + session = session_entry(service_tag="EX", tracks={"vid": track}) async def fake_get_session(sid, req): return session @@ -112,14 +105,7 @@ async def test_batch_cache_does_not_starve_second_track(env, monkeypatch): ], ) tracks = {"vid": vid, "aud": aud} - session = SimpleNamespace( - lock=asyncio.Lock(), - service_tag="EX", - service_instance=SimpleNamespace(), - served_keys={}, - tracks=SimpleNamespace(get=tracks.get), - log_buffer=None, - ) + session = session_entry(service_tag="EX", tracks=tracks) async def fake_get_session(sid, req): return session @@ -144,14 +130,7 @@ async def test_no_pssh_tells_the_client_why(env, monkeypatch): buf = SessionLogBuffer() track = SimpleNamespace(id="vid", drm=[object()]) - session = SimpleNamespace( - lock=asyncio.Lock(), - service_tag="EX", - service_instance=SimpleNamespace(), - served_keys={}, - tracks=SimpleNamespace(get={"vid": track}.get), - log_buffer=buf, - ) + session = session_entry(service_tag="EX", tracks={"vid": track}, log_buffer=buf) async def fake_get_session(sid, req): return session diff --git a/tests/remote/unit/test_server_cdm_key_verification.py b/tests/remote/unit/test_server_cdm_key_verification.py index f9dc8c8d..fa25be3b 100644 --- a/tests/remote/unit/test_server_cdm_key_verification.py +++ b/tests/remote/unit/test_server_cdm_key_verification.py @@ -13,9 +13,9 @@ from uuid import UUID import pytest from tests.remote.key_source import remote_keys +from tests.remote.sessions import session_entry from unshackle.core.api import handlers from unshackle.core.api.errors import APIError -from unshackle.core.api.session_store import SessionEntry from unshackle.core.drm import BlowfishStripe from unshackle.core.remote_service import RemoteService @@ -65,7 +65,7 @@ class _Vault: @pytest.fixture def session(monkeypatch): - entry = SessionEntry(session_id="sess", service_tag="SVC", service_instance=SimpleNamespace()) + entry = session_entry(service_tag="SVC") handlers.note_served_keys(entry, {KID.hex: "v", CDM_KID.hex: "c"}, {KID.hex: "sqlite"}) assert entry.served_keys == {KID.hex: ("v", "sqlite"), CDM_KID.hex: ("c", "cdm")} @@ -112,8 +112,7 @@ _WV.__name__ = "Widevine" async def test_batch_reports_vault_keys_from_the_init_segment_pssh(monkeypatch): """A vault hit on the init-segment PSSH retry must reach `vault_keys` like a manifest one.""" track = SimpleNamespace(id="vid", drm=[_WV("manifest", [KID])], get_key_id=lambda init: CDM_KID) - session = SessionEntry(session_id="sess", service_tag="SVC", service_instance=SimpleNamespace()) - session.tracks = {"vid": track} + session = session_entry(service_tag="SVC", tracks={"vid": track}) probed: list = [] @@ -167,11 +166,13 @@ async def test_batch_reports_vault_keys_from_the_init_segment_pssh(monkeypatch): async def test_batch_asks_again_when_a_cached_vault_answer_lacks_the_track_kid(monkeypatch): """Renditions that share a header: a vault answer for one track's KID does not serve a track with another KID.""" kids = {"a": KID, "b": CDM_KID, "c": CDM_KID} - session = SessionEntry(session_id="sess", service_tag="SVC", service_instance=SimpleNamespace()) - session.tracks = { - tid: SimpleNamespace(id=tid, drm=[_WV("shared", [KID, CDM_KID])], get_key_id=lambda init, k=kid: k) - for tid, kid in kids.items() - } + session = session_entry( + service_tag="SVC", + tracks={ + tid: SimpleNamespace(id=tid, drm=[_WV("shared", [KID, CDM_KID])], get_key_id=lambda init, k=kid: k) + for tid, kid in kids.items() + }, + ) asked: list = [] async def validated(sid, req): @@ -327,8 +328,7 @@ def test_a_cdm_licence_unflags_a_pair_a_client_reported(monkeypatch, tmp_path): async def test_a_stripe_cipher_track_is_clear_and_never_licensed(monkeypatch): """A track whose only DRM needs no licence goes to clear_tracks and keeps its DRM for the client.""" track = SimpleNamespace(id="aud", drm=[BlowfishStripe(bytes(16))]) - session = SessionEntry(session_id="sess", service_tag="SVC", service_instance=SimpleNamespace()) - session.tracks = {"aud": track} + session = session_entry(service_tag="SVC", tracks={"aud": track}) async def validated(sid, req): return session diff --git a/tests/remote/unit/test_server_cdm_manifest_kid.py b/tests/remote/unit/test_server_cdm_manifest_kid.py index 30b92a2c..60c556d5 100644 --- a/tests/remote/unit/test_server_cdm_manifest_kid.py +++ b/tests/remote/unit/test_server_cdm_manifest_kid.py @@ -8,7 +8,6 @@ named different KIDs got one licence; and a KID the licence did not cover was lo server alone. """ -import asyncio import base64 import json from types import SimpleNamespace @@ -21,6 +20,7 @@ from pyplayready.system.pssh import PSSH as RealPSSH import unshackle.core.cdm as cdm_mod import unshackle.core.cdm.detect as detect_mod import unshackle.core.drm as drm_mod +from tests.remote.sessions import session_entry from unshackle.core.api import handlers from unshackle.core.api.session_log import SessionLogBuffer from unshackle.core.drm import PlayReady @@ -102,14 +102,7 @@ def fake_playready(monkeypatch): def _session(tracks: dict, buf=None): - session = SimpleNamespace( - lock=asyncio.Lock(), - service_tag="EX", - service_instance=SimpleNamespace(), - served_keys={}, - tracks=SimpleNamespace(get=tracks.get), - log_buffer=buf, - ) + session = session_entry(service_tag="EX", tracks=tracks, log_buffer=buf) async def fake_get_session(sid, req): return session diff --git a/tests/remote/unit/test_server_cdm_max_height.py b/tests/remote/unit/test_server_cdm_max_height.py index 2dc8edd6..178b0b3c 100644 --- a/tests/remote/unit/test_server_cdm_max_height.py +++ b/tests/remote/unit/test_server_cdm_max_height.py @@ -14,11 +14,11 @@ import pywidevine.pssh as wv_pssh_mod import unshackle.core.drm as drm_mod from tests.core.key_resolver import key_table, resolver from tests.remote.key_source import CAPPED, PR_DEVICE, one_title, remote_keys, remote_session +from tests.remote.sessions import session_entry from unshackle.commands.dl import dl from unshackle.core import remote_channel from unshackle.core.api import handlers from unshackle.core.api.errors import APIError -from unshackle.core.api.session_store import SessionEntry from unshackle.core.config import cdm_entry_names_device from unshackle.core.drm import Widevine from unshackle.core.remote_protocol import APIErrorCode @@ -122,13 +122,13 @@ def test_bad_quality_is_invalid_input(): @pytest.mark.parametrize( ("session", "track", "refused"), [ - (SimpleNamespace(server_cdm=True, server_cdm_max_height=1080), video(2160), True), - (SimpleNamespace(server_cdm=True, server_cdm_max_height=1080), video(1080), False), - (SimpleNamespace(server_cdm=True, server_cdm_max_height=1080), video(None), False), - (SimpleNamespace(server_cdm=True, server_cdm_max_height=1080), Audio.__new__(Audio), False), - (SimpleNamespace(server_cdm=True, server_cdm_max_height=None), video(2160), False), - (SimpleNamespace(server_cdm=False, server_cdm_max_height=1080), video(720), True), - (SimpleNamespace(), video(2160), False), # a session from before the cap existed + (session_entry(server_cdm_max_height=1080), video(2160), True), + (session_entry(server_cdm_max_height=1080), video(1080), False), + (session_entry(server_cdm_max_height=1080), video(None), False), + (session_entry(server_cdm_max_height=1080), Audio.__new__(Audio), False), + (session_entry(server_cdm_max_height=None), video(2160), False), + (session_entry(server_cdm=False, server_cdm_max_height=1080), video(720), True), + (session_entry(), video(2160), False), ], ) def test_live_licence_refusal(session, track, refused): @@ -160,13 +160,13 @@ def single(refusal): def test_a_vault_hit_is_served_above_the_cap(widevine_env, monkeypatch): monkeypatch.setattr(handlers, "check_vaults", lambda kids, name, **_: ({"11" * 16: "key"}, {"11" * 16: "sqlite"})) - refusal = handlers.live_licence_refusal(SimpleNamespace(server_cdm_max_height=1080), video(2160)) + refusal = handlers.live_licence_refusal(session_entry(server_cdm_max_height=1080), video(2160)) assert single(refusal) == {"11" * 16: "key"} def test_a_vault_miss_raises_the_refusal_before_the_device_loads(widevine_env, monkeypatch): monkeypatch.setattr(handlers, "check_vaults", lambda kids, name, **_: None) - refusal = handlers.live_licence_refusal(SimpleNamespace(server_cdm_max_height=1080), video(2160)) + refusal = handlers.live_licence_refusal(session_entry(server_cdm_max_height=1080), video(2160)) with pytest.raises(APIError) as ei: single(refusal) assert ei.value is refusal @@ -267,7 +267,7 @@ def test_a_null_service_in_the_cap_map_falls_through_to_the_default(monkeypatch) def test_an_ultrawide_track_is_measured_as_the_smallest_quality_that_selects_it(): """-q matches a height or a 16:9 width, so a track passes the cap when either one is inside it.""" - session = SimpleNamespace(server_cdm=True, server_cdm_max_height=1080) + session = session_entry(server_cdm_max_height=1080) assert handlers.live_licence_refusal(session, video(1600, 3840)) is not None assert handlers.live_licence_refusal(session, video(None, 3840)) is not None assert handlers.live_licence_refusal(session, video(1080, 2560)) is None # -q 1080 selects it @@ -357,7 +357,7 @@ def playready_env(monkeypatch): def test_playready_raises_the_refusal_before_the_device_loads(playready_env): - refusal = handlers.live_licence_refusal(SimpleNamespace(server_cdm_max_height=1080), video(2160)) + refusal = handlers.live_licence_refusal(session_entry(server_cdm_max_height=1080), video(2160)) with pytest.raises(APIError) as ei: handlers.handle_single_server_cdm( SimpleNamespace(), SimpleNamespace(), video(2160), "cHNzaA==", "playready", None, {}, refusal @@ -392,9 +392,7 @@ def media(kind, tid, drm, **attrs): @pytest.fixture def licence_env(monkeypatch): """A capped remote session and a stand-in server licence that honours the refusal like the real one.""" - session = SessionEntry(session_id="sess", service_tag="EXAMPLE1", service_instance=SimpleNamespace()) - session.server_cdm = True - session.server_cdm_max_height = 1080 + session = session_entry(service_tag="EXAMPLE1", server_cdm_max_height=1080) calls: list = [] vault = {} diff --git a/tests/remote/unit/test_server_cdm_multikey.py b/tests/remote/unit/test_server_cdm_multikey.py index c68da068..4e216a4d 100644 --- a/tests/remote/unit/test_server_cdm_multikey.py +++ b/tests/remote/unit/test_server_cdm_multikey.py @@ -6,7 +6,6 @@ instead of short-circuiting on a vault hit for the PSSH KID alone, and the batch path must give each track the full bundle without borrowing another PSSH's keys. """ -import asyncio import base64 import json from types import SimpleNamespace @@ -19,6 +18,7 @@ import pywidevine.pssh as wv_pssh_mod import unshackle.core.cdm as cdm_mod import unshackle.core.cdm.detect as detect_mod import unshackle.core.drm as drm_mod +from tests.remote.sessions import session_entry from unshackle.core.api import handlers pytestmark = pytest.mark.unit @@ -118,13 +118,7 @@ async def test_batch_shares_full_bundle_per_pssh(monkeypatch): track_pssh = {"vid": pssh_a, "aud": pssh_a, "vid2": pssh_b} tracks = {tid: SimpleNamespace(id=tid, drm=[object()]) for tid in track_pssh} - session = SimpleNamespace( - lock=asyncio.Lock(), - service_tag="EXAMPLE", - service_instance=SimpleNamespace(), - served_keys={}, - tracks=SimpleNamespace(get=tracks.get), - ) + session = session_entry(tracks=tracks) async def fake_get_session(session_id, request): return session diff --git a/tests/remote/unit/test_server_cdm_type_override.py b/tests/remote/unit/test_server_cdm_type_override.py index c458e38b..8e55e17e 100644 --- a/tests/remote/unit/test_server_cdm_type_override.py +++ b/tests/remote/unit/test_server_cdm_type_override.py @@ -20,6 +20,7 @@ import pywidevine.pssh as wv_pssh_mod import unshackle.core.cdm as cdm_mod import unshackle.core.cdm.detect as detect_mod import unshackle.core.drm as drm_mod +from tests.remote.sessions import session_entry from unshackle.core.api import handlers from unshackle.core.api.errors import APIError from unshackle.core.cdm.choice import choose_cdm @@ -75,14 +76,7 @@ def _session(track): get_widevine_license=lambda **k: b"", get_playready_license=lambda **k: b"", ) - return SimpleNamespace( - lock=asyncio.Lock(), - service_tag="EXAMPLE", - service_instance=service, - served_keys={}, - tracks=SimpleNamespace(get={"vid": track}.get), - log_buffer=None, - ) + return session_entry(service_instance=service, tracks={"vid": track}) @pytest.fixture diff --git a/tests/remote/unit/test_session_channel.py b/tests/remote/unit/test_session_channel.py index 8fb8cec5..762fb64e 100644 --- a/tests/remote/unit/test_session_channel.py +++ b/tests/remote/unit/test_session_channel.py @@ -40,11 +40,7 @@ class FakeSocket: def entry_with_logs(count: int) -> SessionEntry: - entry = SessionEntry("s", "EXAMPLE", None) - entry.log_buffer = SessionLogBuffer() - entry.log_buffer.listener = entry.channel.log - entry.input_bridge = InputBridge() - entry.input_bridge.channel = entry.channel + entry = SessionEntry("s", "EXAMPLE", None, log_buffer=SessionLogBuffer(), input_bridge=InputBridge()) for n in range(count): entry.log_buffer.append(logging.INFO, f"EXAMPLE line {n + 1}") return entry @@ -73,7 +69,7 @@ async def test_the_backlog_goes_before_a_record_logged_while_the_old_socket_clos break await asyncio.sleep(0.01) assert log_seqs(new) == [3, 4, 5] - assert {"type": "status", "status": "authenticated"} in new.sent + assert {"type": "status", "status": "authenticating"} in new.sent await new.close() await serving assert not entry.channel.attached diff --git a/tests/remote/unit/test_session_reporting.py b/tests/remote/unit/test_session_reporting.py index e99af4e5..ee6575eb 100644 --- a/tests/remote/unit/test_session_reporting.py +++ b/tests/remote/unit/test_session_reporting.py @@ -143,3 +143,43 @@ def test_tracks_handler_marks_the_title_live_before_it_fetches(monkeypatch: pyte await store.delete("live") asyncio.run(run()) + + +def test_the_create_event_carries_the_session_as_created(monkeypatch: pytest.MonkeyPatch, tmp_path: Any) -> None: + """The dashboard learns a new session with its licensing mode, client and login state, not the defaults.""" + import json + + from unshackle.core.api import handlers + from unshackle.core.api.events import bus + from unshackle.core.config import config + + class Service: + _input_bridge = None + log = None + cache = None + + def authenticate(self, cookies: Any, credential: Any) -> None: + pass + + monkeypatch.setattr(config.directories, "cache", tmp_path) + monkeypatch.setattr(handlers, "validate_service", lambda service, request=None: service) + monkeypatch.setattr(handlers, "resolve_handler_proxy", lambda *args: (None, [])) + monkeypatch.setattr(handlers, "server_account_for", lambda *args: False) + monkeypatch.setattr(handlers, "choose_session_cdm", lambda *args: (True, 1080)) + monkeypatch.setattr(handlers.Services, "load", lambda service: Service) + monkeypatch.setattr(handlers, "create_service_instance", lambda *a, **k: (Service(), None, None)) + + async def run() -> list: + mark = bus.seq + body = {"service": "EXAMPLE", "title_id": "t", "client": {"version": "1.0"}} + resp = await handlers.session_create_handler(body) + await store_mod.get_session_store().delete(json.loads(resp.body)["session_id"]) + return [e["data"] for e in bus.since(mark) if e["event"] == "session" and e["data"]["action"] == "create"] + + (created,) = asyncio.run(run()) + assert {k: created[k] for k in ("auth_status", "server_cdm", "server_cdm_max_height", "client")} == { + "auth_status": "authenticating", + "server_cdm": True, + "server_cdm_max_height": 1080, + "client": {"version": "1.0"}, + } diff --git a/tests/remote/unit/test_session_store.py b/tests/remote/unit/test_session_store.py index 457f160b..89f86388 100644 --- a/tests/remote/unit/test_session_store.py +++ b/tests/remote/unit/test_session_store.py @@ -3,7 +3,9 @@ from __future__ import annotations import asyncio +import threading import time +from types import SimpleNamespace import pytest @@ -53,13 +55,14 @@ async def test_get_touches_last_accessed(store: SessionStore) -> None: async def test_delete_removes_and_cancels_bridge(store: SessionStore) -> None: - entry = await store.create("CRAV", _FakeService()) - entry.input_bridge = InputBridge() - assert entry.input_bridge.status is AuthStatus.AUTHENTICATING + entry = await store.create("EXAMPLE", _FakeService(), input_bridge=InputBridge()) deleted = await store.delete(entry.session_id) assert deleted is True - assert entry.input_bridge.status is AuthStatus.FAILED # cancelled + with pytest.raises(RuntimeError, match="cancelled"): + entry.input_bridge.ensure_active() + assert entry.channel.ended + assert entry.auth_status is AuthStatus.AUTHENTICATING # the delete event reports the login state as it was assert store.session_count == 0 @@ -88,25 +91,32 @@ async def test_session_with_work_in_progress_does_not_expire(store: SessionStore assert await store.get("busy") is entry -async def test_cleanup_expired_keeps_pending_input_under_grace(store: SessionStore) -> None: - """Sessions awaiting user input get a longer grace period (10 min) than authenticated TTL.""" - entry = await store.create("EXAMPLE", _FakeService()) - entry.input_bridge = InputBridge() - entry.auth_status = AuthStatus.PENDING_INPUT +async def test_cleanup_expired_keeps_a_login_under_grace(store: SessionStore) -> None: + """A session that still logs in, a prompt included, gets a longer grace period (10 min) than authenticated TTL.""" + from datetime import datetime, timedelta, timezone + + entry = await store.create("EXAMPLE", _FakeService(), input_bridge=InputBridge()) + entry.last_accessed = datetime.now(timezone.utc) - timedelta(seconds=store.ttl + 1) removed = await store.cleanup_expired() assert removed == 0 assert store.session_count == 1 -async def test_cleanup_expired_drops_pending_input_past_grace(store: SessionStore) -> None: +async def test_get_keeps_a_login_past_the_ttl(store: SessionStore) -> None: + from datetime import datetime, timedelta, timezone + + entry = await store.create("EXAMPLE", _FakeService(), input_bridge=InputBridge()) + entry.last_accessed = datetime.now(timezone.utc) - timedelta(seconds=store.ttl + 1) + assert await store.get(entry.session_id) is entry + + +async def test_cleanup_expired_drops_a_login_past_grace(store: SessionStore) -> None: """The auth-state grace is the single AUTH_INPUT_TIMEOUT rule, not a separate magic number.""" from datetime import datetime, timedelta, timezone from unshackle.core.api.input_bridge import AUTH_INPUT_TIMEOUT - entry = await store.create("EXAMPLE", _FakeService()) - entry.input_bridge = InputBridge() - entry.auth_status = AuthStatus.PENDING_INPUT + entry = await store.create("EXAMPLE", _FakeService(), input_bridge=InputBridge()) entry.last_accessed = datetime.now(timezone.utc) - timedelta(seconds=AUTH_INPUT_TIMEOUT + 1) removed = await store.cleanup_expired() assert removed == 1 @@ -114,14 +124,13 @@ async def test_cleanup_expired_drops_pending_input_past_grace(store: SessionStor async def test_cancel_all_bridges(store: SessionStore) -> None: - a = await store.create("EXAMPLE", _FakeService()) - b = await store.create("DEMO", _FakeService()) - a.input_bridge = InputBridge() - b.input_bridge = InputBridge() + a = await store.create("EXAMPLE", _FakeService(), input_bridge=InputBridge()) + b = await store.create("DEMO", _FakeService(), input_bridge=InputBridge()) await store.cancel_all_bridges() - assert a.input_bridge.status is AuthStatus.FAILED - assert b.input_bridge.status is AuthStatus.FAILED + for entry in (a, b): + with pytest.raises(RuntimeError, match="cancelled"): + entry.input_bridge.ensure_active() async def test_get_session_store_returns_singleton() -> None: @@ -287,3 +296,36 @@ async def test_live_session_on_same_tag_keeps_it_busy(store: SessionStore, monke assert await store.delete(second.session_id) await asyncio.sleep(0.05) assert applied == [{"EXAMPLE"}, set()] + + +def test_the_login_state_is_the_one_its_bridge_holds(monkeypatch: pytest.MonkeyPatch) -> None: + """A waiting prompt keeps the session authenticating; the bridge alone moves it to authenticated or failed.""" + entry = SessionEntry("s", "EXAMPLE", None, input_bridge=InputBridge()) + bridge = entry.input_bridge + assert bridge.channel is entry.channel + offered = threading.Event() + monkeypatch.setattr(entry.channel, "offer", lambda ask: offered.set() or False) + answers: list[str] = [] + worker = threading.Thread(target=lambda: answers.append(bridge.request_input("Code?"))) + worker.start() + assert offered.wait(5) + assert bridge.status is AuthStatus.PENDING_INPUT + assert entry.auth_status is AuthStatus.AUTHENTICATING + assert bridge.submit_response("1234") + worker.join(5) + assert answers == ["1234"] + + bridge.login_status = AuthStatus.AUTHENTICATED + assert entry.summary()["auth_status"] == "authenticated" + bridge.login_status = AuthStatus.FAILED + assert entry.summary()["auth_status"] == "failed" + assert SessionEntry("s", "EXAMPLE", None).auth_status is AuthStatus.AUTHENTICATED + + +def test_add_tracks_registers_every_track_of_a_title() -> None: + entry = SessionEntry("s", "EXAMPLE", None) + video, audio, subtitle, other = (SimpleNamespace(id=i) for i in ("v", "a", "s", "o")) + entry.add_tracks("t1", SimpleNamespace(videos=[video], audio=[audio], subtitles=[subtitle])) # type: ignore[arg-type] + entry.add_tracks("t2", SimpleNamespace(videos=[other], audio=[], subtitles=[])) # type: ignore[arg-type] + assert entry.tracks == {"v": video, "a": audio, "s": subtitle, "o": other} + assert entry.tracks_by_title == {"t1": {"v": video, "a": audio, "s": subtitle}, "t2": {"o": other}} diff --git a/tests/test_client_session_auth.py b/tests/test_client_session_auth.py index aa98e7a9..ffe8cadc 100644 --- a/tests/test_client_session_auth.py +++ b/tests/test_client_session_auth.py @@ -3,6 +3,7 @@ from types import SimpleNamespace import pytest import requests +from tests.remote.sessions import session_entry from unshackle.core.api.errors import APIError from unshackle.core.api.handlers import client_session_auth, resolve_handler_proxy, scrub_track_data from unshackle.core.remote_service import apply_session_cookies @@ -11,7 +12,7 @@ from unshackle.core.remote_service import apply_session_cookies def _session(client_auth): cookie = SimpleNamespace(name="sid", value="secret", domain=".example.com", path="/") svc = SimpleNamespace(headers={"Authorization": "Bearer x", "User-Agent": "ua"}, cookies=[cookie]) - return SimpleNamespace(service_instance=SimpleNamespace(session=svc), client_auth=client_auth) + return session_entry(service_instance=SimpleNamespace(session=svc), client_auth=client_auth) def test_client_login_keeps_auth(): @@ -65,7 +66,7 @@ def test_rnet_session_sends_client_and_set_cookies(): svc.cookies.set("sid", "stale", domain=".example.com") svc.cookies.set("cdn", "c", domain="cdn.other.net") svc.export_origin_cookies = lambda: {"https://www.example.com": "sid=live; cf=1"} - _, cookies = client_session_auth(SimpleNamespace(service_instance=SimpleNamespace(session=svc), client_auth=True)) + _, cookies = client_session_auth(session_entry(service_instance=SimpleNamespace(session=svc), client_auth=True)) assert {(c["name"], c["value"], c["domain"]) for c in cookies} == { ("sid", "live", "www.example.com"), ("cf", "1", "www.example.com"), @@ -228,7 +229,7 @@ def test_dashboard_logs_redact_path(): def test_server_login_strips_nested_and_unlisted_secrets(): headers, _ = client_session_auth( - SimpleNamespace( + session_entry( service_instance=SimpleNamespace( session=SimpleNamespace(headers={"X-Api-Key": "k", "Accept": "*"}, cookies=[]) ), @@ -353,6 +354,13 @@ def test_client_auth_follows_login_provenance(monkeypatch, tmp_path, data, answe assert session.client_auth is expected +def test_a_failed_login_reports_its_error(monkeypatch, tmp_path): + from unshackle.core.remote_protocol import AuthStatus + + session = _run_session(monkeypatch, tmp_path, {}, "CODE", fail=True) + assert (session.auth_status, session.auth_error) == (AuthStatus.FAILED, "bad code") + + def test_prompt_post_rejects_response_the_bridge_refused(monkeypatch): import asyncio diff --git a/unshackle/core/api/handlers.py b/unshackle/core/api/handlers.py index 41e82acb..ce72c4fe 100644 --- a/unshackle/core/api/handlers.py +++ b/unshackle/core/api/handlers.py @@ -30,13 +30,12 @@ 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.session_channel import status_message from unshackle.core.api.session_log import SessionLogBuffer, SessionLogMirror, capture_service_logs -from unshackle.core.api.session_store import SessionStore +from unshackle.core.api.session_store import SessionEntry, SessionStore from unshackle.core.binaries import binary_version from unshackle.core.cacher import Cacher from unshackle.core.cdm.choice import choose_cdm, drm_system from unshackle.core.cdm.detect import cdm_type_stub, is_playready_cdm from unshackle.core.config import config, load_yaml -from unshackle.core.constants import AnyTrack from unshackle.core.dl_options import ( DEFAULT_DOWNLOAD_PARAMS, DL_OPTION_API_NAMES, @@ -1217,21 +1216,21 @@ def choose_session_cdm( ) -def live_licence_refusal(session: Any, track: Any) -> Optional[APIError]: +def live_licence_refusal(session: SessionEntry, track: Any) -> Optional[APIError]: """Why the server CDM must not make a live licence for ``track`` in ``session``; None when it may. Only a live licence spends the server's device, so a vault hit always passes. A track measures as the smallest ``-q`` that selects it: the lower of its height and the 16:9 height of its width. """ - if getattr(session, "server_device", False): + if session.server_device: return APIError( APIErrorCode.SERVER_CDM_CAPPED, "This session runs on the server's device, so its keys come only from a vault.", details={"reason": "server_device"}, ) - if getattr(session, "server_cdm", None) is False: + if not session.server_cdm: return capped_error("This session licenses with your own device, so the server CDM makes no licence for it.") - cap = getattr(session, "server_cdm_max_height", None) + cap = session.server_cdm_max_height height = getattr(track, "height", None) if isinstance(track, Video) else None width = getattr(track, "width", None) if isinstance(track, Video) else None measures = [m for m in (height, int(width * 9 / 16) if width else None) if m] @@ -3621,6 +3620,7 @@ async def session_create_handler(data: Dict[str, Any], request: Optional[web.Req service_instance._input_bridge = bridge + client = data.get("client") store = get_session_store() session = await store.create( normalized_service, @@ -3629,38 +3629,30 @@ async def session_create_handler(data: Dict[str, Any], request: Optional[web.Req 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, + user_config=user_config, + server_cdm=use_server_cdm, + server_cdm_max_height=max_height, + server_vault=client_device and server_vault_allowed(request, 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, ) - session.cache_tag = session_cache_tag - session.user_config = user_config - session.server_cdm = use_server_cdm - session.server_cdm_max_height = max_height - session.server_vault = client_device and server_vault_allowed(request, normalized_service) - session.server_device = server_device - session.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. - if isinstance(data.get("client"), dict) and len(json.dumps(data["client"], default=str)) <= 4096: - session.client = data["client"] - session.input_bridge = bridge - session.log_buffer = log_buffer - session.auth_status = AuthStatus.AUTHENTICATING - bridge.channel = session.channel - if log_buffer: - log_buffer.listener = session.channel.log async def run_auth() -> None: try: await asyncio.to_thread(service_instance.authenticate, cookies, credential) if not server_account: session.client_auth = True - session.auth_status = AuthStatus.AUTHENTICATED - bridge.status = AuthStatus.AUTHENTICATED + bridge.login_status = AuthStatus.AUTHENTICATED except (Exception, SystemExit) as e: log.exception("Auth failed for session %s", session_id) - session.auth_status = AuthStatus.FAILED session.auth_error = redact_secrets(str(e)) - bridge.status = AuthStatus.FAILED + bridge.login_status = AuthStatus.FAILED finally: session.channel.send(status_message(session)) if store.peek(session_id) is not session: @@ -3779,12 +3771,12 @@ def session_user_config(session: Any, request: Optional[web.Request]) -> Dict[st return pinned if isinstance(pinned, dict) else serve_user_config(caller_key(request)) -def client_owns_login(session: Any) -> bool: +def client_owns_login(session: SessionEntry) -> bool: """Whether the login state of ``session`` is the client's to take back. A remote session on the server's lent device logs in with the server's device identity, so its tokens stay there. """ - return bool(session.client_auth) and not getattr(session, "server_device", False) + return bool(session.client_auth) and not session.server_device def scrub_secret_keys(value: Any) -> Any: @@ -3842,18 +3834,7 @@ async def session_tracks_handler( finally: session.touch() - title_tracks: Dict[str, Any] = {} - track: AnyTrack - for track in tracks.videos: - title_tracks[str(track.id)] = track - session.tracks[str(track.id)] = track - for track in tracks.audio: - title_tracks[str(track.id)] = track - session.tracks[str(track.id)] = track - for track in tracks.subtitles: - title_tracks[str(track.id)] = track - session.tracks[str(track.id)] = track - session.tracks_by_title[str(title_id)] = title_tracks + session.add_tracks(str(title_id), tracks) SessionStore.publish_update(session) try: @@ -4071,15 +4052,15 @@ def detect_cdm_type(cdm_name: str, app_config: Any) -> Optional[str]: return None -def require_authenticated(session: Any) -> None: +def require_authenticated(session: SessionEntry) -> None: """Raise if the remote session has not finished authenticating.""" - status = getattr(session, "auth_status", None) + status = session.auth_status if status == AuthStatus.FAILED: raise APIError( APIErrorCode.AUTH_FAILED, f"Authentication failed: {session.auth_error or 'unknown error'}", ) - if status in (AuthStatus.AUTHENTICATING, AuthStatus.PENDING_INPUT): + if status == AuthStatus.AUTHENTICATING: raise APIError( APIErrorCode.INVALID_INPUT, f"Session authentication not complete (status: {status.value})", @@ -5044,9 +5025,9 @@ def license_response( mode = data.get("mode", "proxy") # a session the client's device licenses reaches the server vault only; its live licences stay client-side - vault_only = getattr(session, "server_cdm", None) is False + vault_only = not session.server_cdm if mode == "server_cdm" and not ( - getattr(session, "server_vault", False) if vault_only else server_cdm_allowed(request, session.service_tag) + session.server_vault if vault_only else server_cdm_allowed(request, session.service_tag) ): raise APIError( APIErrorCode.FORBIDDEN, @@ -5287,7 +5268,7 @@ def license_response( track.pr_pssh = pssh_b64 certificate = data.get("is_certificate") is True - if getattr(session, "server_device", False) and not certificate: + if session.server_device and not certificate: denied = live_licence_refusal(session, track) if denied: raise denied @@ -5394,9 +5375,7 @@ async def session_delete_handler(session_id: str, request: Optional[web.Request] session = await get_validated_session(session_id, request) store = get_session_store() - if session.input_bridge: - session.input_bridge.cancel() - + session.end() cache_tag = session.cache_tag cache_data = collect_cache_files(cache_tag) if cache_tag and client_owns_login(session) else {} diff --git a/unshackle/core/api/input_bridge.py b/unshackle/core/api/input_bridge.py index 8a7bb8fe..548e7a34 100644 --- a/unshackle/core/api/input_bridge.py +++ b/unshackle/core/api/input_bridge.py @@ -20,7 +20,7 @@ if TYPE_CHECKING: from unshackle.core.api.session_channel import SessionChannel # Seconds the server waits for a remote client to answer an input prompt before -# giving up; also the TTL SessionStore grants AUTHENTICATING/PENDING_INPUT sessions. +# giving up; also the TTL SessionStore grants AUTHENTICATING sessions. AUTH_INPUT_TIMEOUT = 600.0 CDM_CALL_TIMEOUT = 60.0 # A listening client polls every few seconds, so a CDM call nobody fetches in this time has no client behind it. @@ -92,9 +92,6 @@ class InputBridge: try: # cancel() and an answer both set the event, so a single wait returns on signal-or-cancel if not ask.answered.wait(timeout=timeout): - with self._lock: - if self._status != AuthStatus.AUTHENTICATED: - self._status = AuthStatus.FAILED raise TimeoutError(f"No client response for prompt within {timeout}s") with self._lock: if self._cancelled: @@ -223,7 +220,6 @@ class InputBridge: """Cancel the bridge, unblocking any waiting service thread.""" with self._lock: self._cancelled = True - self._status = AuthStatus.FAILED asks = list(self._asks.values()) for ask in asks: ask.picked_up.set() @@ -243,8 +239,14 @@ class InputBridge: return AuthStatus.PENDING_INPUT return self._status - @status.setter - def status(self, value: AuthStatus) -> None: + @property + def login_status(self) -> AuthStatus: + """The login state alone: a waiting ask does not make it ``pending_input``.""" + with self._lock: + return self._status + + @login_status.setter + def login_status(self, value: AuthStatus) -> None: with self._lock: self._status = value diff --git a/unshackle/core/api/session_store.py b/unshackle/core/api/session_store.py index 9b0c4d6b..3f1f4c4e 100644 --- a/unshackle/core/api/session_store.py +++ b/unshackle/core/api/session_store.py @@ -22,7 +22,7 @@ from unshackle.core.api.sanitize import sanitize_log from unshackle.core.api.session_channel import SessionChannel, drain_message from unshackle.core.config import config from unshackle.core.remote_protocol import AuthStatus -from unshackle.core.tracks import Track +from unshackle.core.tracks import Track, Tracks log = logging.getLogger("api.session") @@ -50,7 +50,7 @@ class SessionEntry: owner_key: Optional[str] = None # X-Secret-Key that owns this session cache_tag: Optional[str] = None server_account: Optional[str] = None # profile name when the server lent its own account - server_cdm: Optional[bool] = None # False: the client's own device licenses this session + server_cdm: bool = False # False: the client's own device licenses this session server_cdm_max_height: Optional[int] = None server_vault: bool = False # a session the client's device licenses may still take keys from the server vault server_device: bool = False # its service runs on the server's lent device, so keys come only from a vault @@ -59,13 +59,29 @@ class SessionEntry: input_bridge: Optional[InputBridge] = None log_buffer: Optional[Any] = None # SessionLogBuffer mirroring the service's self.log channel: SessionChannel = field(default_factory=SessionChannel, repr=False, compare=False) - auth_status: AuthStatus = AuthStatus.AUTHENTICATED auth_error: Optional[str] = None client: Dict[str, Any] = field(default_factory=dict) # version/argv/platform the client reported actions: Deque[Dict[str, Any]] = field(default_factory=lambda: deque(maxlen=500)) created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc)) last_accessed: datetime = field(default_factory=lambda: datetime.now(timezone.utc)) + def __post_init__(self) -> None: + if self.input_bridge is not None: + self.input_bridge.channel = self.channel + if self.log_buffer is not None: + self.log_buffer.listener = self.channel.log + + @property + def auth_status(self) -> AuthStatus: + """The login state, which the input bridge holds; a remote session with no bridge has no login to wait on.""" + return self.input_bridge.login_status if self.input_bridge else AuthStatus.AUTHENTICATED + + def add_tracks(self, title_id: str, tracks: Tracks) -> None: + """Register the video, audio and subtitle tracks of a title, so the later routes find each one by its id.""" + title_tracks: Dict[str, Track] = {str(t.id): t for t in [*tracks.videos, *tracks.audio, *tracks.subtitles]} + self.tracks.update(title_tracks) + self.tracks_by_title[title_id] = title_tracks + def touch(self) -> None: """Update last_accessed timestamp.""" self.last_accessed = datetime.now(timezone.utc) @@ -168,11 +184,22 @@ class SessionStore: service_tag: str, service_instance: Any, session_id: Optional[str] = None, + *, owner_key: Optional[str] = None, creator_ip: Optional[str] = None, server_account: Optional[str] = None, + cache_tag: Optional[str] = None, + user_config: Optional[Dict[str, Any]] = None, + server_cdm: bool = False, + server_cdm_max_height: Optional[int] = None, + server_vault: bool = False, + server_device: bool = False, + client_auth: bool = False, + client: Optional[Dict[str, Any]] = None, + input_bridge: Optional[InputBridge] = None, + log_buffer: Optional[Any] = None, ) -> SessionEntry: - """Make a new remote session with an authenticated service instance.""" + """Make a new remote session, complete with every field the dashboard shows, and announce it.""" evicted_tag: Optional[str] = None async with self._lock: max_sessions = self.max_sessions @@ -198,6 +225,16 @@ class SessionStore: owner_key=owner_key, creator_ip=creator_ip, server_account=server_account, + cache_tag=cache_tag, + user_config=user_config, + server_cdm=server_cdm, + server_cdm_max_height=server_cdm_max_height, + server_vault=server_vault, + server_device=server_device, + client_auth=client_auth, + client=client or {}, + input_bridge=input_bridge, + log_buffer=log_buffer, ) self._sessions[session_id] = entry _publish("create", entry) @@ -213,7 +250,7 @@ class SessionStore: return None expired = False - if not entry.in_use and entry.auth_status not in (AuthStatus.AUTHENTICATING, AuthStatus.PENDING_INPUT): + if not entry.in_use and entry.auth_status != AuthStatus.AUTHENTICATING: elapsed = (datetime.now(timezone.utc) - entry.last_accessed).total_seconds() if elapsed > self.ttl: log.info(f"Session {sanitize_log(session_id)} expired (elapsed={elapsed:.0f}s, ttl={self.ttl}s)") @@ -257,7 +294,7 @@ class SessionStore: if entry.in_use: continue elapsed = (now - entry.last_accessed).total_seconds() - if entry.auth_status in (AuthStatus.AUTHENTICATING, AuthStatus.PENDING_INPUT): + if entry.auth_status == AuthStatus.AUTHENTICATING: if elapsed > AUTH_INPUT_TIMEOUT: expired.append(sid) elif elapsed > self.ttl: