refactor(api): build a remote session whole, with one login state

This commit is contained in:
imSp4rky
2026-11-24 19:26:26 -07:00
parent 1be56b15b3
commit 43987f9809
21 changed files with 320 additions and 205 deletions
+22 -7
View File
@@ -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
@@ -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
+25 -7
View File
@@ -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
@@ -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:
+12 -4
View File
@@ -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:
+2 -3
View File
@@ -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))),
)
@@ -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
@@ -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
@@ -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
+13 -15
View File
@@ -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 = {}
@@ -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
@@ -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
+2 -6
View File
@@ -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
@@ -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"},
}
+61 -19
View File
@@ -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}}