refactor(remote): hold who licenses a remote session as one licensing mode

This commit is contained in:
imSp4rky
2026-11-29 10:16:08 -07:00
parent d4af4c77f4
commit efd8ca65c7
18 changed files with 458 additions and 160 deletions
+3 -1
View File
@@ -4,6 +4,7 @@ from types import SimpleNamespace
from typing import Any from typing import Any
from uuid import UUID from uuid import UUID
from unshackle.core.remote_protocol import LicensingMode, Licensor
from unshackle.core.remote_service import RemoteService, ServerVault from unshackle.core.remote_service import RemoteService, ServerVault
from unshackle.core.title_source import KeyArrival from unshackle.core.title_source import KeyArrival
@@ -15,7 +16,8 @@ def remote_keys(
) -> RemoteService: ) -> RemoteService:
"""A RemoteService with only the state dl reads through ServerKeySource, and no server.""" """A RemoteService with only the state dl reads through ServerKeySource, and no server."""
svc = RemoteService.__new__(RemoteService) svc = RemoteService.__new__(RemoteService)
svc._server_cdm = server_cdm if server_cdm is not None:
svc.licensing = LicensingMode(Licensor.SERVER_CDM if server_cdm else Licensor.CLIENT_DEVICE)
svc.server_cdm_type = server_cdm_type svc.server_cdm_type = server_cdm_type
svc.client_licensed = set() svc.client_licensed = set()
svc.deferred_refusals = {} svc.deferred_refusals = {}
+2 -1
View File
@@ -4,6 +4,7 @@ from types import SimpleNamespace
from typing import Any from typing import Any
from unshackle.core.api.session_store import SessionEntry from unshackle.core.api.session_store import SessionEntry
from unshackle.core.remote_protocol import LicensingMode, Licensor
def session_entry(**fields: Any) -> SessionEntry: def session_entry(**fields: Any) -> SessionEntry:
@@ -13,7 +14,7 @@ def session_entry(**fields: Any) -> SessionEntry:
"session_id": "sess", "session_id": "sess",
"service_tag": "EXAMPLE", "service_tag": "EXAMPLE",
"service_instance": SimpleNamespace(), "service_instance": SimpleNamespace(),
"server_cdm": True, "licensing": LicensingMode(Licensor.SERVER_CDM),
**fields, **fields,
} }
) )
+10 -9
View File
@@ -20,7 +20,7 @@ from unshackle.core.api.errors import APIError
from unshackle.core.api.input_bridge import InputBridge from unshackle.core.api.input_bridge import InputBridge
from unshackle.core.cdm.client_relay import ClientDeviceCdm, answer_cdm_call from unshackle.core.cdm.client_relay import ClientDeviceCdm, answer_cdm_call
from unshackle.core.launch import served_context from unshackle.core.launch import served_context
from unshackle.core.remote_protocol import APIErrorCode, AuthStatus from unshackle.core.remote_protocol import APIErrorCode, AuthStatus, LicensingMode, Licensor
from unshackle.core.run_plan import served_plan from unshackle.core.run_plan import served_plan
from unshackle.core.utils.click_types import ContextData from unshackle.core.utils.click_types import ContextData
@@ -244,7 +244,7 @@ def test_a_lent_server_device_marks_the_stand_in() -> None:
def test_a_lent_device_session_never_licenses_live() -> None: def test_a_lent_device_session_never_licenses_live() -> None:
refusal = handlers.live_licence_refusal(session_entry(server_device=True, server_cdm=False), object()) refusal = handlers.live_licence_refusal(session_entry(licensing=LicensingMode(Licensor.LENT_DEVICE)), object())
assert refusal is not None assert refusal is not None
assert refusal.details == {"reason": "server_device"} assert refusal.details == {"reason": "server_device"}
@@ -252,7 +252,7 @@ def test_a_lent_device_session_never_licenses_live() -> None:
def test_a_vault_only_miss_raises_the_refusal(monkeypatch: pytest.MonkeyPatch) -> 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, "check_vaults", lambda kids, service, **_: None)
monkeypatch.setattr(handlers, "ensure_track_drm", lambda *a, **k: None) monkeypatch.setattr(handlers, "ensure_track_drm", lambda *a, **k: None)
refusal = handlers.live_licence_refusal(session_entry(server_device=True), object()) refusal = handlers.live_licence_refusal(session_entry(licensing=LicensingMode(Licensor.LENT_DEVICE)), object())
with pytest.raises(APIError) as caught: with pytest.raises(APIError) as caught:
handlers.handle_single_server_cdm( handlers.handle_single_server_cdm(
SimpleNamespace(), SimpleNamespace(),
@@ -434,8 +434,7 @@ def test_a_client_map_entry_replaces_the_server_entry_of_the_same_number() -> No
def lent_device_session() -> Any: def lent_device_session() -> Any:
return session_entry( return session_entry(
server_cdm=False, licensing=LicensingMode(Licensor.LENT_DEVICE),
server_device=True,
client_auth=True, client_auth=True,
cache_tag="_sessions/abc/sid/EXAMPLE1", cache_tag="_sessions/abc/sid/EXAMPLE1",
service_instance=SimpleNamespace( service_instance=SimpleNamespace(
@@ -488,9 +487,7 @@ def test_a_lent_device_without_the_vault_grant_asks_the_server_for_no_key() -> N
svc = object.__new__(RemoteService) svc = object.__new__(RemoteService)
svc.log = logging.getLogger("test") svc.log = logging.getLogger("test")
svc._session_id = "sid" svc._session_id = "sid"
svc._server_cdm = True svc.licensing = LicensingMode(Licensor.LENT_DEVICE)
svc._server_device = True
svc._local_vaults_only = True
svc.client_licensed = set() svc.client_licensed = set()
svc.deferred_refusals = {} svc.deferred_refusals = {}
svc.client = SimpleNamespace(post=lambda *a, **k: pytest.fail("the server refuses every key request")) svc.client = SimpleNamespace(post=lambda *a, **k: pytest.fail("the server refuses every key request"))
@@ -544,7 +541,11 @@ def test_cancel_wakes_a_call_waiting_for_a_client() -> None:
@pytest.mark.parametrize( @pytest.mark.parametrize(
("fields", "forbidden"), ("fields", "forbidden"),
[({"server_cdm": False}, True), ({"server_cdm": False, "server_vault": True}, False), ({}, False)], [
({"licensing": LicensingMode(Licensor.CLIENT_DEVICE)}, True),
({"licensing": LicensingMode(Licensor.CLIENT_DEVICE, server_vault=True)}, False),
({}, False),
],
) )
def test_the_server_licence_route_follows_the_licensing_mode( def test_the_server_licence_route_follows_the_licensing_mode(
monkeypatch: pytest.MonkeyPatch, fields: dict, forbidden: bool monkeypatch: pytest.MonkeyPatch, fields: dict, forbidden: bool
+37 -1
View File
@@ -13,7 +13,7 @@ from unshackle.core.api.errors import APIError
from unshackle.core.api.key_policy import KeyPolicy from unshackle.core.api.key_policy import KeyPolicy
from unshackle.core.api.session_store import get_session_store from unshackle.core.api.session_store import get_session_store
from unshackle.core.config import config from unshackle.core.config import config
from unshackle.core.remote_protocol import AuthStatus from unshackle.core.remote_protocol import AuthStatus, LicensingMode, Licensor
@pytest.fixture @pytest.fixture
@@ -163,6 +163,42 @@ def test_a_session_keeps_identity_keys_from_the_client_unless_the_identity_is_th
assert sent_back == returned assert sent_back == returned
def test_a_service_on_the_lent_device_makes_a_lent_device_session(server, monkeypatch):
class Service(_Service):
_input_bridge = log = cache = None
ctx = SimpleNamespace(obj=SimpleNamespace(cdm=SimpleNamespace(lent=True)))
def authenticate(self, cookies, credential):
self.cache.get("keys/device1").set("identity")
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, "request_policy", lambda request: KeyPolicy({"server_vault": True}))
monkeypatch.setattr(handlers, "choose_session_cdm", lambda *args: (False, None))
monkeypatch.setattr(handlers.Services, "load", lambda service: Service)
monkeypatch.setattr(handlers, "create_service_instance", lambda *args, **kwargs: (Service(), "x", None))
async def run():
data = {"service": "EXAMPLE", "title_id": "t", "cookies": "x", "cdm_type": "widevine", "cdm_relay": True}
reply = json.loads((await handlers.session_create_handler(data)).body)
session = get_session_store().peek(reply["session_id"])
try:
for _ in range(250):
if session.auth_status != AuthStatus.AUTHENTICATING:
break
await asyncio.sleep(0.02)
return reply, session, set(handlers.collect_cache_files(session.cache_tag))
finally:
await get_session_store().delete(session.session_id)
reply, session, cache = asyncio.run(run())
assert session.licensing == LicensingMode(Licensor.LENT_DEVICE, server_vault=True)
assert (reply["server_cdm"], reply["server_device"], reply["server_vault"]) == (False, True, True)
assert "keys/device1" not in cache
def test_a_reload_checks_key_devices_against_the_new_config(server, monkeypatch): def test_a_reload_checks_key_devices_against_the_new_config(server, monkeypatch):
monkeypatch.setattr(handlers.Services, "get_tags", staticmethod(lambda: ["EXAMPLE"])) monkeypatch.setattr(handlers.Services, "get_tags", staticmethod(lambda: ["EXAMPLE"]))
fresh = SimpleNamespace(remote_cdm=[{"name": "new_remote", "device_type": "PLAYREADY"}]) fresh = SimpleNamespace(remote_cdm=[{"name": "new_remote", "device_type": "PLAYREADY"}])
+127
View File
@@ -0,0 +1,127 @@
"""A remote session's licensing mode: one value that the server decides at session create and the client adopts."""
import logging
from types import SimpleNamespace
import pytest
from unshackle.core.api import handlers
from unshackle.core.api.key_policy import KeyPolicy
from unshackle.core.remote_protocol import LicensingMode, Licensor
from unshackle.core.remote_service import RemoteService
pytestmark = pytest.mark.unit
SERVER_CDM = LicensingMode(Licensor.SERVER_CDM, 1080)
CLIENT_DEVICE = LicensingMode(Licensor.CLIENT_DEVICE, server_vault=True)
LENT_DEVICE = LicensingMode(Licensor.LENT_DEVICE)
NO_DEVICE = LicensingMode(Licensor.NO_DEVICE)
@pytest.mark.parametrize(
("mode", "answers"),
[
(SERVER_CDM, {"server_cdm", "keys_from_server", "reads_server_keys"}),
(CLIENT_DEVICE, {"client_device", "client_identity", "vault_only", "reads_server_keys", "vault_first"}),
(LENT_DEVICE, {"server_device", "client_device", "vault_only", "keys_from_server", "local_vaults_only"}),
(NO_DEVICE, {"vault_only"}),
],
ids=["server-cdm", "client-device", "lent-device", "no-device"],
)
def test_each_mode_answers_the_licensing_questions(mode, answers):
questions = (
"server_cdm",
"server_device",
"client_device",
"client_identity",
"vault_only",
"keys_from_server",
"reads_server_keys",
"vault_first",
"local_vaults_only",
)
assert {q for q in questions if getattr(mode, q)} == answers
@pytest.mark.parametrize("licensor", [Licensor.SERVER_CDM, Licensor.NO_DEVICE])
def test_only_a_client_device_session_reads_the_server_vault(licensor):
with pytest.raises(ValueError, match="cannot read the server vault"):
LicensingMode(licensor, server_vault=True)
def test_only_a_client_device_session_can_take_the_lent_device():
assert CLIENT_DEVICE.lent() == LicensingMode(Licensor.LENT_DEVICE, server_vault=True)
with pytest.raises(ValueError, match="no client device"):
SERVER_CDM.lent()
@pytest.mark.parametrize(
("mode", "adopted"),
[
(SERVER_CDM, SERVER_CDM),
(CLIENT_DEVICE, CLIENT_DEVICE),
(CLIENT_DEVICE.lent(), CLIENT_DEVICE.lent()),
(LicensingMode(Licensor.CLIENT_DEVICE, 1080), LicensingMode(Licensor.CLIENT_DEVICE, 1080)),
(NO_DEVICE, LicensingMode(Licensor.CLIENT_DEVICE)),
],
)
def test_the_client_reads_the_mode_back_from_the_older_fields(mode, adopted):
fields = mode.created_fields()
assert set(fields) == {"server_cdm", "server_cdm_max_height", "server_vault", "server_device"}
assert LicensingMode.from_created({"session_id": "s", **fields}) == adopted
def test_an_older_server_reply_with_vault_and_server_cdm_is_a_server_cdm_session():
assert LicensingMode.from_created({"server_cdm": True, "server_vault": True}) == LicensingMode(Licensor.SERVER_CDM)
@pytest.mark.parametrize(
("choice", "data", "policy", "mode"),
[
((True, 1080), {"cdm_type": "widevine", "cdm_relay": True}, {}, SERVER_CDM),
((False, None), {"cdm_type": "widevine", "cdm_relay": True}, {"server_vault": True}, CLIENT_DEVICE),
((False, None), {"cdm_type": "widevine", "cdm_relay": True}, {}, LicensingMode(Licensor.CLIENT_DEVICE)),
((False, 1080), {"cdm_type": "widevine"}, {}, LicensingMode(Licensor.CLIENT_DEVICE, 1080)),
((False, None), {"cdm_type": "widevine"}, {"server_vault": True}, NO_DEVICE),
((False, None), {}, {"server_vault": True}, NO_DEVICE),
],
ids=["server-cdm", "relay-vault", "relay", "capped-old-client", "old-client", "no-device"],
)
def test_session_create_decides_one_mode(choice, data, policy, mode, monkeypatch):
monkeypatch.setattr(handlers, "choose_session_cdm", lambda *args: choice)
assert handlers.session_licensing(KeyPolicy(policy), "EXAMPLE", data) == mode
@pytest.mark.parametrize(
("held", "request_", "reply", "mode", "fallback"),
[
(None, None, True, LicensingMode(Licensor.SERVER_CDM), False),
(None, True, False, LicensingMode(Licensor.CLIENT_DEVICE), True),
(None, False, True, LicensingMode(Licensor.CLIENT_DEVICE), False),
(SERVER_CDM, None, False, LicensingMode(Licensor.CLIENT_DEVICE, 1080), True),
(LENT_DEVICE, None, False, LENT_DEVICE, False),
(SERVER_CDM, None, True, SERVER_CDM, False),
],
ids=["older-server", "older-server-refuses", "declined", "reopen-on-older-server", "lent", "same"],
)
def test_the_tracks_reply_settles_the_mode_an_older_server_left_out(held, request_, reply, mode, fallback, caplog):
service = object.__new__(RemoteService)
service.__dict__.update(
licensing=held,
_server_cdm_request=request_,
_tracks_by_title={},
_chapters_by_title={},
_title_alias={},
_sample_decrypt_tracks=set(),
_session_id="s",
service_tag="EXAMPLE",
ctx=SimpleNamespace(obj=None),
log=logging.getLogger("test"),
client=SimpleNamespace(post=lambda path, body: {"server_cdm": reply}, probe=lambda endpoint: {}),
drain_server_logs=lambda: None,
)
service.session = SimpleNamespace(headers={})
with caplog.at_level(logging.INFO):
service.get_tracks(SimpleNamespace(id="t1"))
assert service.licensing == mode
assert ("falling back to the local CDM" in caplog.text) is fallback
@@ -724,7 +724,7 @@ def _remote_service(parent_params: dict, service_params: dict) -> RemoteService:
svc.service_tag = "EXAMPLE" svc.service_tag = "EXAMPLE"
svc.title_id = "t1" svc.title_id = "t1"
svc._server_accounts = {"global": True} svc._server_accounts = {"global": True}
svc._server_cdm = True svc._server_cdm_request = True
svc._service_params = service_params svc._service_params = service_params
svc.session = requests.Session() svc.session = requests.Session()
svc.log = logging.getLogger("test") svc.log = logging.getLogger("test")
@@ -12,6 +12,7 @@ from uuid import UUID
import pytest import pytest
from tests.remote.key_source import remote_keys from tests.remote.key_source import remote_keys
from unshackle.core.remote_protocol import LicensingMode, Licensor
pytestmark = pytest.mark.unit pytestmark = pytest.mark.unit
@@ -87,7 +88,7 @@ def test_response_type_refreshes_the_server_type():
def test_proxy_mode_keeps_the_callers_type(): def test_proxy_mode_keeps_the_callers_type():
svc = _service("widevine", {"license": "bGlj"}) svc = _service("widevine", {"license": "bGlj"})
svc._server_cdm = False svc.licensing = LicensingMode(Licensor.CLIENT_DEVICE)
svc.drain_server_logs = lambda: None svc.drain_server_logs = lambda: None
track = SimpleNamespace(id="vid", drm=[_PlayReady(), _Widevine()]) track = SimpleNamespace(id="vid", drm=[_PlayReady(), _Widevine()])
@@ -104,7 +105,7 @@ def test_a_refused_relayed_licence_raises_a_click_exception_with_the_server_mess
from unshackle.core.remote_service import RemoteError from unshackle.core.remote_service import RemoteError
svc = _service("widevine", {}) svc = _service("widevine", {})
svc._server_cdm = False svc.licensing = LicensingMode(Licensor.CLIENT_DEVICE)
svc.drain_server_logs = lambda: None svc.drain_server_logs = lambda: None
def refuse(endpoint, payload, expect=()): def refuse(endpoint, payload, expect=()):
@@ -43,6 +43,8 @@ from unshackle.core.remote_protocol import (
TRACKS_ROUTE, TRACKS_ROUTE,
APIErrorCode, APIErrorCode,
AuthStatus, AuthStatus,
LicensingMode,
Licensor,
) )
from unshackle.core.titles.movie import Movie from unshackle.core.titles.movie import Movie
@@ -281,7 +283,7 @@ async def open_session(stand_in: Faulty, owner: str, status: AuthStatus) -> None
stand_in, stand_in,
session_id=SESSION, session_id=SESSION,
owner_key=owner, owner_key=owner,
server_cdm=True, licensing=LicensingMode(Licensor.SERVER_CDM),
input_bridge=bridge, input_bridge=bridge,
log_buffer=getattr(stand_in, "log_buffer", None), log_buffer=getattr(stand_in, "log_buffer", None),
) )
@@ -20,6 +20,7 @@ from unshackle.core.api import handlers
from unshackle.core.api.errors import APIError from unshackle.core.api.errors import APIError
from unshackle.core.drm import BlowfishStripe, ClearKeyCTR from unshackle.core.drm import BlowfishStripe, ClearKeyCTR
from unshackle.core.drm.cenc import drm_stub from unshackle.core.drm.cenc import drm_stub
from unshackle.core.remote_protocol import LicensingMode, Licensor
from unshackle.core.remote_service import RemoteError, RemoteService from unshackle.core.remote_service import RemoteError, RemoteService
pytestmark = pytest.mark.unit pytestmark = pytest.mark.unit
@@ -237,7 +238,7 @@ def test_resolve_server_keys_does_not_warn_for_clear_tracks(monkeypatch):
svc = remote_service() svc = remote_service()
warnings: list = [] warnings: list = []
svc.log = SimpleNamespace(warning=lambda msg, *a, **k: warnings.append(msg), debug=lambda *a, **k: None) svc.log = SimpleNamespace(warning=lambda msg, *a, **k: warnings.append(msg), debug=lambda *a, **k: None)
svc._server_cdm = True svc.licensing = LicensingMode(Licensor.SERVER_CDM)
svc.drain_server_logs = lambda: None svc.drain_server_logs = lambda: None
svc.client = SimpleNamespace(post=lambda ep, data: {"keys": {}, "clear_tracks": ["a-1"]}) svc.client = SimpleNamespace(post=lambda ep, data: {"keys": {}, "clear_tracks": ["a-1"]})
@@ -257,7 +258,7 @@ def test_resolve_server_keys_takes_the_key_of_a_whole_file_cipher():
"""The server licensed the track's whole-file cipher: the client takes its key and keeps the cipher.""" """The server licensed the track's whole-file cipher: the client takes its key and keeps the cipher."""
svc = remote_service() svc = remote_service()
svc.log = SimpleNamespace(warning=lambda msg, *a, **k: pytest.fail(msg), debug=lambda *a, **k: None) svc.log = SimpleNamespace(warning=lambda msg, *a, **k: pytest.fail(msg), debug=lambda *a, **k: None)
svc._server_cdm = True svc.licensing = LicensingMode(Licensor.SERVER_CDM)
svc.drain_server_logs = lambda: None svc.drain_server_logs = lambda: None
svc.client = SimpleNamespace(post=lambda ep, data: {"keys": {}, "file_keys": {"v-1": "aa" * 16}}) svc.client = SimpleNamespace(post=lambda ep, data: {"keys": {}, "file_keys": {"v-1": "aa" * 16}})
cipher = ClearKeyCTR(None, bytes(range(16)), b"OggS") cipher = ClearKeyCTR(None, bytes(range(16)), b"OggS")
@@ -272,7 +273,7 @@ def test_license_file_asks_the_server_for_the_key_of_a_whole_file_cipher():
"""A whole-file cipher can only be licensed by the service on the server.""" """A whole-file cipher can only be licensed by the service on the server."""
svc = remote_service() svc = remote_service()
svc.log = SimpleNamespace(warning=lambda *a, **k: None, debug=lambda *a, **k: None) svc.log = SimpleNamespace(warning=lambda *a, **k: None, debug=lambda *a, **k: None)
svc._server_cdm = True svc.licensing = LicensingMode(Licensor.SERVER_CDM)
sent = [] sent = []
svc.client = SimpleNamespace(post=lambda ep, data, **kw: sent.append(data) or {"file_keys": {"v-1": "bb" * 16}}) svc.client = SimpleNamespace(post=lambda ep, data, **kw: sent.append(data) or {"file_keys": {"v-1": "bb" * 16}})
cipher = ClearKeyCTR(None, bytes(range(16)), b"OggS") cipher = ClearKeyCTR(None, bytes(range(16)), b"OggS")
@@ -286,8 +287,8 @@ def test_license_file_asks_the_server_for_the_key_of_a_whole_file_cipher():
@pytest.mark.parametrize( @pytest.mark.parametrize(
("grants", "answer", "message"), ("grants", "answer", "message"),
[ [
({"_server_cdm": False}, None, "needs a server licence"), ({"licensing": LicensingMode(Licensor.CLIENT_DEVICE)}, None, "needs a server licence"),
({"_local_vaults_only": True}, None, "needs a server licence"), ({"licensing": LicensingMode(Licensor.LENT_DEVICE)}, None, "needs a server licence"),
({}, {"keys": {}}, "sent no content key"), ({}, {"keys": {}}, "sent no content key"),
({}, RemoteError("Content key tool not found: tool", "SERVICE_ERROR"), "Content key tool not found"), ({}, RemoteError("Content key tool not found: tool", "SERVICE_ERROR"), "Content key tool not found"),
], ],
@@ -296,7 +297,7 @@ def test_license_file_asks_the_server_for_the_key_of_a_whole_file_cipher():
def test_a_cipher_the_server_does_not_license_raises(grants, answer, message): def test_a_cipher_the_server_does_not_license_raises(grants, answer, message):
"""A whole-file cipher the server gives no key for stops the track with one DRM error before its download.""" """A whole-file cipher the server gives no key for stops the track with one DRM error before its download."""
svc = remote_service() svc = remote_service()
svc._server_cdm = True svc.licensing = LicensingMode(Licensor.SERVER_CDM)
for name, value in grants.items(): for name, value in grants.items():
setattr(svc, name, value) setattr(svc, name, value)
@@ -358,7 +359,7 @@ def resolve(manifest_drm, drm_type="widevine"):
"""Run resolve_server_keys for one track the server answers with its own key and a sibling.""" """Run resolve_server_keys for one track the server answers with its own key and a sibling."""
svc = remote_service() svc = remote_service()
svc.log = SimpleNamespace(warning=lambda *a, **k: None, debug=lambda *a, **k: None) svc.log = SimpleNamespace(warning=lambda *a, **k: None, debug=lambda *a, **k: None)
svc._server_cdm = True svc.licensing = LicensingMode(Licensor.SERVER_CDM)
svc.drain_server_logs = lambda: None svc.drain_server_logs = lambda: None
keys = {CDM_KID.hex: "bb" * 16, KID.hex: "aa" * 16} keys = {CDM_KID.hex: "bb" * 16, KID.hex: "aa" * 16}
svc.client = SimpleNamespace(post=lambda ep, data: {"keys": {"v-1": keys}, "drm_type": drm_type}) svc.client = SimpleNamespace(post=lambda ep, data: {"keys": {"v-1": keys}, "drm_type": drm_type})
@@ -419,11 +420,10 @@ def test_a_cdm_licence_unflags_a_pair_a_client_reported(monkeypatch, tmp_path):
assert local.get_key(KID, "SVC") == "ab" * 16 assert local.get_key(KID, "SVC") == "ab" * 16
async def batch_answer(monkeypatch, track, vault_only=False, request=None, server_device=False): async def batch_answer(monkeypatch, track, request=None, licensing=None):
"""The server's licence answer for one track, with every CDM call stubbed out.""" """The server's licence answer for one track, with every CDM call stubbed out."""
session = session_entry(service_tag="SVC", tracks={"aud": track}) licensing = licensing or LicensingMode(Licensor.SERVER_CDM)
session.server_cdm, session.server_vault = not vault_only, vault_only session = session_entry(service_tag="SVC", tracks={"aud": track}, licensing=licensing)
session.server_device = server_device
async def validated(sid, req): async def validated(sid, req):
return session return session
@@ -475,26 +475,33 @@ async def test_the_server_batch_answers_a_cipher_that_already_holds_its_key(monk
assert (body["file_keys"], "clear_tracks" in body) == ({"aud": "dd" * 16}, False) assert (body["file_keys"], "clear_tracks" in body) == ({"aud": "dd" * 16}, False)
@pytest.mark.parametrize("refusal", ["vault_only", "server_device"]) NO_LIVE_LICENCES = pytest.mark.parametrize(
async def test_a_session_without_live_licences_licenses_no_cipher(monkeypatch, refusal): "licensing",
[LicensingMode(Licensor.CLIENT_DEVICE, server_vault=True), LicensingMode(Licensor.LENT_DEVICE, server_vault=True)],
ids=["vault_only", "server_device"],
)
@NO_LIVE_LICENCES
async def test_a_session_without_live_licences_licenses_no_cipher(monkeypatch, licensing):
"""A session the server makes no live licence for gets no key of a whole-file cipher and no clear mark.""" """A session the server makes no live licence for gets no key of a whole-file cipher and no clear mark."""
cipher = ClearKeyCTR(lambda: pytest.fail("licensed a cipher"), bytes(range(16)), b"OggS") cipher = ClearKeyCTR(lambda: pytest.fail("licensed a cipher"), bytes(range(16)), b"OggS")
track = SimpleNamespace(id="aud", drm=[cipher]) track = SimpleNamespace(id="aud", drm=[cipher])
body = await batch_answer(monkeypatch, track, **{refusal: True}) body = await batch_answer(monkeypatch, track, licensing=licensing)
assert body == {"keys": {}} assert body == {"keys": {}}
@pytest.mark.parametrize("refusal", ["vault_only", "server_device"]) @NO_LIVE_LICENCES
async def test_one_licence_request_refuses_a_cipher_without_live_licences(monkeypatch, refusal): async def test_one_licence_request_refuses_a_cipher_without_live_licences(monkeypatch, licensing):
"""The single-track route answers FORBIDDEN for a cipher with no key in a session without live licences.""" """The single-track route answers FORBIDDEN for a cipher with no key in a session without live licences."""
cipher = ClearKeyCTR(lambda: pytest.fail("licensed a cipher"), bytes(range(16)), b"OggS") cipher = ClearKeyCTR(lambda: pytest.fail("licensed a cipher"), bytes(range(16)), b"OggS")
track = SimpleNamespace(id="aud", drm=[cipher]) track = SimpleNamespace(id="aud", drm=[cipher])
request = {"mode": "server_cdm", "track_id": "aud", "drm_type": "clearkeyctr"} request = {"mode": "server_cdm", "track_id": "aud", "drm_type": "clearkeyctr"}
with pytest.raises(APIError) as refused: with pytest.raises(APIError) as refused:
await batch_answer(monkeypatch, track, request=request, **{refusal: True}) await batch_answer(monkeypatch, track, request=request, licensing=licensing)
assert refused.value.error_code == "FORBIDDEN" assert refused.value.error_code == "FORBIDDEN"
+35 -32
View File
@@ -22,7 +22,7 @@ from unshackle.core.api.errors import APIError
from unshackle.core.api.key_policy import KeyPolicy from unshackle.core.api.key_policy import KeyPolicy
from unshackle.core.config import cdm_entry_names_device from unshackle.core.config import cdm_entry_names_device
from unshackle.core.drm import Widevine from unshackle.core.drm import Widevine
from unshackle.core.remote_protocol import APIErrorCode from unshackle.core.remote_protocol import APIErrorCode, LicensingMode, Licensor
from unshackle.core.remote_service import RemoteClient, RemoteService from unshackle.core.remote_service import RemoteClient, RemoteService
from unshackle.core.tracks import Audio, Video from unshackle.core.tracks import Audio, Video
@@ -111,10 +111,9 @@ def test_above_the_cap_without_a_device_is_refused_at_create():
@pytest.mark.parametrize( @pytest.mark.parametrize(
("session", "track", "refused"), ("session", "track", "refused"),
[ [
(session_entry(server_cdm_max_height=1080), video(2160), True), (session_entry(licensing=LicensingMode(Licensor.SERVER_CDM, 1080)), video(2160), True),
(session_entry(server_cdm_max_height=1080), video(1080), False), (session_entry(licensing=LicensingMode(Licensor.SERVER_CDM, 1080)), video(1080), False),
(session_entry(server_cdm_max_height=None), video(2160), False), (session_entry(licensing=LicensingMode(Licensor.CLIENT_DEVICE, 1080)), video(720), True),
(session_entry(server_cdm=False, server_cdm_max_height=1080), video(720), True),
(session_entry(), video(2160), False), (session_entry(), video(2160), False),
], ],
) )
@@ -147,13 +146,17 @@ def single(refusal):
def test_a_vault_hit_is_served_above_the_cap(widevine_env, monkeypatch): 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"})) monkeypatch.setattr(handlers, "check_vaults", lambda kids, name, **_: ({"11" * 16: "key"}, {"11" * 16: "sqlite"}))
refusal = handlers.live_licence_refusal(session_entry(server_cdm_max_height=1080), video(2160)) refusal = handlers.live_licence_refusal(
session_entry(licensing=LicensingMode(Licensor.SERVER_CDM, 1080)), video(2160)
)
assert single(refusal) == {"11" * 16: "key"} assert single(refusal) == {"11" * 16: "key"}
def test_a_vault_miss_raises_the_refusal_before_the_device_loads(widevine_env, monkeypatch): def test_a_vault_miss_raises_the_refusal_before_the_device_loads(widevine_env, monkeypatch):
monkeypatch.setattr(handlers, "check_vaults", lambda kids, name, **_: None) monkeypatch.setattr(handlers, "check_vaults", lambda kids, name, **_: None)
refusal = handlers.live_licence_refusal(session_entry(server_cdm_max_height=1080), video(2160)) refusal = handlers.live_licence_refusal(
session_entry(licensing=LicensingMode(Licensor.SERVER_CDM, 1080)), video(2160)
)
with pytest.raises(APIError) as ei: with pytest.raises(APIError) as ei:
single(refusal) single(refusal)
assert ei.value is refusal assert ei.value is refusal
@@ -224,8 +227,7 @@ def test_a_server_vault_miss_without_the_local_drm_system_fails_at_once():
"""Only a server-CDM session reads the local vaults before the licence, so a server-vault session raises at once.""" """Only a server-CDM session reads the local vaults before the licence, so a server-vault session raises at once."""
track = capped_track() track = capped_track()
svc = remote_session(PR_DEVICE, {"keys": {}, "capped_tracks": {"vid": {}}}) svc = remote_session(PR_DEVICE, {"keys": {}, "capped_tracks": {"vid": {}}})
svc._server_cdm = False svc.licensing = LicensingMode(Licensor.CLIENT_DEVICE, server_vault=True)
svc._server_vault = True
with pytest.raises(click.ClickException, match="server vault") as ei: with pytest.raises(click.ClickException, match="server vault") as ei:
svc.resolve_server_keys(one_title(track)) svc.resolve_server_keys(one_title(track))
assert "-q" not in ei.value.message assert "-q" not in ei.value.message
@@ -294,7 +296,9 @@ def playready_env(monkeypatch):
def test_playready_raises_the_refusal_before_the_device_loads(playready_env): def test_playready_raises_the_refusal_before_the_device_loads(playready_env):
refusal = handlers.live_licence_refusal(session_entry(server_cdm_max_height=1080), video(2160)) refusal = handlers.live_licence_refusal(
session_entry(licensing=LicensingMode(Licensor.SERVER_CDM, 1080)), video(2160)
)
with pytest.raises(APIError) as ei: with pytest.raises(APIError) as ei:
handlers.handle_single_server_cdm( handlers.handle_single_server_cdm(
SimpleNamespace(), SimpleNamespace(), video(2160), "cHNzaA==", "playready", None, {}, refusal SimpleNamespace(), SimpleNamespace(), video(2160), "cHNzaA==", "playready", None, {}, refusal
@@ -329,7 +333,7 @@ def media(kind, tid, drm, **attrs):
@pytest.fixture @pytest.fixture
def licence_env(monkeypatch): def licence_env(monkeypatch):
"""A capped remote session and a stand-in server licence that honours the refusal like the real one.""" """A capped remote session and a stand-in server licence that honours the refusal like the real one."""
session = session_entry(service_tag="EXAMPLE1", server_cdm_max_height=1080) session = session_entry(service_tag="EXAMPLE1", licensing=LicensingMode(Licensor.SERVER_CDM, 1080))
calls: list = [] calls: list = []
vault = {} vault = {}
@@ -452,7 +456,7 @@ def test_the_tracks_response_echoes_the_session_choice(monkeypatch):
service_tag="EXAMPLE1", service_instance=StubService(), session_id="capped", owner_key=None service_tag="EXAMPLE1", service_instance=StubService(), session_id="capped", owner_key=None
) )
entry.title_map = {"t1": "Title"} entry.title_map = {"t1": "Title"}
entry.server_cdm = False entry.licensing = LicensingMode(Licensor.CLIENT_DEVICE)
try: try:
resp = await handlers.session_tracks_handler({"title_id": "t1"}, "capped") resp = await handlers.session_tracks_handler({"title_id": "t1"}, "capped")
return json.loads(resp.body) return json.loads(resp.body)
@@ -600,7 +604,8 @@ def sent_create(server_cdm, cdm_name=None, local_cdm=WIDEVINE_CDM, cdm_entry=Fal
handlers.config.cdm = cdm_map or {} handlers.config.cdm = cdm_map or {}
svc = remote_session(local_cdm, {}) svc = remote_session(local_cdm, {})
svc.ctx.obj.cdm_entry = cdm_entry svc.ctx.obj.cdm_entry = cdm_entry
svc._server_cdm = server_cdm svc.licensing = None
svc._server_cdm_request = server_cdm
svc.service_tag = "EXAMPLE1" svc.service_tag = "EXAMPLE1"
svc.title_id = "t1" svc.title_id = "t1"
svc._server_accounts = {"global": True} svc._server_accounts = {"global": True}
@@ -628,17 +633,17 @@ def test_the_client_declines_the_server_cdm_when_the_user_picked_a_device(server
assert (data.get("server_cdm") is False) is declines assert (data.get("server_cdm") is False) is declines
assert data["cdm_type"] == "widevine" assert data["cdm_type"] == "widevine"
assert svc._server_cdm is (False if declines else server_cdm) assert svc._server_cdm_request is (False if declines else server_cdm)
# the server built the service, so its answer is final # the server built the service, so its answer is final
svc.adopt_session_cdm(True, None) svc.adopt_session_cdm(LicensingMode(Licensor.SERVER_CDM), svc._server_cdm_request)
assert svc._server_cdm is True assert svc.expected_server_cdm is True
def test_a_device_loaded_from_the_services_cdm_entry_declines_the_server_cdm(): def test_a_device_loaded_from_the_services_cdm_entry_declines_the_server_cdm():
svc, data = sent_create(None, cdm_entry=True, cdm_map={"EXAMPLE1": "my_device"}) svc, data = sent_create(None, cdm_entry=True, cdm_map={"EXAMPLE1": "my_device"})
assert data["server_cdm"] is False assert data["server_cdm"] is False
assert svc._server_cdm is False assert svc._server_cdm_request is False
def test_server_cdm_true_outranks_the_services_cdm_entry(caplog): def test_server_cdm_true_outranks_the_services_cdm_entry(caplog):
@@ -646,7 +651,7 @@ def test_server_cdm_true_outranks_the_services_cdm_entry(caplog):
svc, data = sent_create(True, cdm_entry=True, cdm_map={"EXAMPLE1": "my_device"}) svc, data = sent_create(True, cdm_entry=True, cdm_map={"EXAMPLE1": "my_device"})
assert "server_cdm" not in data assert "server_cdm" not in data
assert data["cdm_relay"] is True assert data["cdm_relay"] is True
assert svc._server_cdm is True assert svc._server_cdm_request is True
assert not caplog.text assert not caplog.text
@@ -661,7 +666,7 @@ def test_a_device_loaded_from_the_default_cdm_entry_does_not_decline(caplog):
with caplog.at_level(logging.WARNING): with caplog.at_level(logging.WARNING):
svc, data = sent_create(True, cdm_map={"default": "my_device", "EXAMPLE2": "other"}) svc, data = sent_create(True, cdm_map={"default": "my_device", "EXAMPLE2": "other"})
assert "server_cdm" not in data assert "server_cdm" not in data
assert svc._server_cdm is True assert svc._server_cdm_request is True
assert not caplog.text assert not caplog.text
@@ -670,7 +675,7 @@ def test_a_cdm_entry_that_did_not_load_the_device_warns_and_does_not_decline(loc
with caplog.at_level(logging.WARNING): with caplog.at_level(logging.WARNING):
svc, data = sent_create(None, local_cdm=local_cdm, cdm_map={"example1": {">=1080": "my_device"}}) svc, data = sent_create(None, local_cdm=local_cdm, cdm_map={"example1": {">=1080": "my_device"}})
assert "server_cdm" not in data assert "server_cdm" not in data
assert svc._server_cdm is None assert svc._server_cdm_request is None
assert "cdm entry for EXAMPLE1" in caplog.text assert "cdm entry for EXAMPLE1" in caplog.text
@@ -706,7 +711,7 @@ def test_a_client_with_no_device_does_not_decline():
def created(answer, monkeypatch): def created(answer, monkeypatch):
"""Run ``authenticate()`` to its end for a device the service's cdm entry loaded.""" """Run ``authenticate()`` to its end for a device the service's cdm entry loaded."""
svc, _ = sent_create(None, cdm_entry=True, cdm_map={"EXAMPLE1": "my_device"}) svc, _ = sent_create(None, cdm_entry=True, cdm_map={"EXAMPLE1": "my_device"})
svc._server_cdm = None svc._server_cdm_request = None
svc.client = SimpleNamespace(post=lambda path, data: {"session_id": "sess", **answer}) svc.client = SimpleNamespace(post=lambda path, data: {"session_id": "sess", **answer})
svc.close = lambda: None svc.close = lambda: None
channel = SimpleNamespace(keep_alive=lambda: None, drain_logs=lambda: None, in_flight=None) channel = SimpleNamespace(keep_alive=lambda: None, drain_logs=lambda: None, in_flight=None)
@@ -718,14 +723,14 @@ def created(answer, monkeypatch):
def test_the_client_says_when_a_cdm_entry_gave_the_licensing_to_its_device(caplog, monkeypatch): def test_the_client_says_when_a_cdm_entry_gave_the_licensing_to_its_device(caplog, monkeypatch):
with caplog.at_level(logging.INFO): with caplog.at_level(logging.INFO):
svc = created({"server_cdm": False}, monkeypatch) svc = created({"server_cdm": False}, monkeypatch)
assert svc._server_cdm is False assert svc.expected_server_cdm is False
assert "cdm config has an entry for EXAMPLE1" in caplog.text assert "cdm config has an entry for EXAMPLE1" in caplog.text
def test_the_client_does_not_claim_its_device_when_the_server_keeps_the_server_cdm(caplog, monkeypatch): def test_the_client_does_not_claim_its_device_when_the_server_keeps_the_server_cdm(caplog, monkeypatch):
with caplog.at_level(logging.INFO): with caplog.at_level(logging.INFO):
svc = created({"server_cdm": True, "server_cdm_max_height": 1080}, monkeypatch) svc = created({"server_cdm": True, "server_cdm_max_height": 1080}, monkeypatch)
assert svc._server_cdm is True assert svc.expected_server_cdm is True
assert "your own device is not used" in caplog.text assert "your own device is not used" in caplog.text
assert "cdm config has an entry" not in caplog.text assert "cdm config has an entry" not in caplog.text
@@ -752,17 +757,15 @@ def test_dl_records_whether_the_services_cdm_entry_named_the_loaded_device(cdm,
def test_a_declined_server_cdm_that_the_server_keeps_is_reported(max_height, caplog): def test_a_declined_server_cdm_that_the_server_keeps_is_reported(max_height, caplog):
svc = remote_session(SimpleNamespace(is_playready=False), {}) svc = remote_session(SimpleNamespace(is_playready=False), {})
svc.service_tag = "EXAMPLE1" svc.service_tag = "EXAMPLE1"
svc._server_cdm = False
with caplog.at_level(logging.INFO): with caplog.at_level(logging.INFO):
svc.adopt_session_cdm(True, max_height) svc.adopt_session_cdm(LicensingMode(Licensor.SERVER_CDM, max_height), False)
assert svc._server_cdm is True assert svc.expected_server_cdm is True
assert "your own device is not used" in caplog.text assert "your own device is not used" in caplog.text
assert "pass a higher -q" not in caplog.text assert "pass a higher -q" not in caplog.text
caplog.clear() caplog.clear()
svc._server_cdm = True
with caplog.at_level(logging.WARNING): with caplog.at_level(logging.WARNING):
svc.adopt_session_cdm(True, max_height) svc.adopt_session_cdm(LicensingMode(Licensor.SERVER_CDM, max_height), True)
assert "your own device is not used" not in caplog.text assert "your own device is not used" not in caplog.text
@@ -772,8 +775,8 @@ def test_a_refused_server_cdm_warns_only_when_no_cdm_entry_loaded_the_fallback(c
svc.service_tag = "EXAMPLE1" svc.service_tag = "EXAMPLE1"
svc.ctx.obj.cdm_entry = cdm_entry svc.ctx.obj.cdm_entry = cdm_entry
with caplog.at_level(logging.INFO): with caplog.at_level(logging.INFO):
svc.adopt_session_cdm(False, None) svc.adopt_session_cdm(LicensingMode(Licensor.CLIENT_DEVICE), True)
assert svc._server_cdm is False assert svc.expected_server_cdm is False
[record] = [r for r in caplog.records if "falling back to the local CDM" in r.getMessage()] [record] = [r for r in caplog.records if "falling back to the local CDM" in r.getMessage()]
assert record.levelno == level assert record.levelno == level
@@ -804,7 +807,7 @@ def test_a_per_service_server_cdm_overrides_the_server_entry(
) )
finally: finally:
RemoteService.__name__ = name # the constructor renames the class RemoteService.__name__ = name # the constructor renames the class
assert svc._server_cdm is expected assert svc._server_cdm_request is expected
assert handlers.config.services.get("EXAMPLE1") == ({"title_map": {"a": "b"}} if apply_overrides else None) assert handlers.config.services.get("EXAMPLE1") == ({"title_map": {"a": "b"}} if apply_overrides else None)
assert live["EXAMPLE1"] == {**service_entry, "title_map": {"a": "b"}} assert live["EXAMPLE1"] == {**service_entry, "title_map": {"a": "b"}}
@@ -822,7 +825,7 @@ def test_a_per_service_entry_matches_the_tag_in_any_case(config_key, tag, monkey
svc = remote_mod.make_remote_service(SimpleNamespace(obj=None), None, tag, "t1", {}) svc = remote_mod.make_remote_service(SimpleNamespace(obj=None), None, tag, "t1", {})
finally: finally:
RemoteService.__name__ = name # the constructor renames the class RemoteService.__name__ = name # the constructor renames the class
assert svc._server_cdm is False assert svc._server_cdm_request is False
assert svc._anonymous_search is True assert svc._anonymous_search is True
assert handlers.config.services == {tag: {"title_map": {"a": "b"}}} assert handlers.config.services == {tag: {"title_map": {"a": "b"}}}
@@ -25,6 +25,7 @@ from unshackle.core.api import handlers, key_policy
from unshackle.core.api.errors import APIError from unshackle.core.api.errors import APIError
from unshackle.core.api.key_policy import KeyPolicy from unshackle.core.api.key_policy import KeyPolicy
from unshackle.core.cdm.choice import choose_cdm from unshackle.core.cdm.choice import choose_cdm
from unshackle.core.remote_protocol import LicensingMode, Licensor
pytestmark = pytest.mark.unit pytestmark = pytest.mark.unit
@@ -273,7 +274,7 @@ def test_the_tracks_response_names_the_system_of_the_loaded_device(monkeypatch,
service_tag="EXAMPLE1", service_instance=StubService(), session_id="both", owner_key=None service_tag="EXAMPLE1", service_instance=StubService(), session_id="both", owner_key=None
) )
entry.title_map = {"t1": "Title"} entry.title_map = {"t1": "Title"}
entry.server_cdm = True entry.licensing = LicensingMode(Licensor.SERVER_CDM)
try: try:
resp = await handlers.session_tracks_handler({"title_id": "t1"}, "both") resp = await handlers.session_tracks_handler({"title_id": "t1"}, "both")
return json.loads(resp.body) return json.loads(resp.body)
+1 -1
View File
@@ -301,7 +301,7 @@ def test_cdm_only_declines_the_server_cdm_and_its_vault(monkeypatch, tmp_path) -
try: try:
svc.authenticate() svc.authenticate()
assert svc.posts[0]["server_cdm"] is False assert svc.posts[0]["server_cdm"] is False
assert (svc.key_arrival, svc._server_vault) == (KeyArrival.CALLBACK, False) assert (svc.key_arrival, svc.licensing.vault_first) == (KeyArrival.CALLBACK, False)
svc.resolve_server_keys(SimpleNamespace(tracks=SimpleNamespace(videos=["v"], audio=[]))) svc.resolve_server_keys(SimpleNamespace(tracks=SimpleNamespace(videos=["v"], audio=[])))
assert len(svc.posts) == 1 assert len(svc.posts) == 1
finally: finally:
+2 -1
View File
@@ -12,6 +12,7 @@ import requests
import responses import responses
from langcodes import Language from langcodes import Language
from unshackle.core.remote_protocol import LicensingMode, Licensor
from unshackle.core.remote_service import RemoteClient, RemoteError, RemoteService, quiet from unshackle.core.remote_service import RemoteClient, RemoteError, RemoteService, quiet
from unshackle.core.tracks import Audio from unshackle.core.tracks import Audio
from unshackle.core.tracks.track import Track from unshackle.core.tracks.track import Track
@@ -49,7 +50,7 @@ def make_service() -> RemoteService:
service._title_alias = {} service._title_alias = {}
service._track_alias = {} service._track_alias = {}
service._current_title = None service._current_title = None
service._server_cdm = service._server_device = service._server_vault = False service.licensing = LicensingMode(Licensor.CLIENT_DEVICE)
return service return service
+1 -1
View File
@@ -124,7 +124,7 @@ def test_remote_get_tracks_scopes_server_cookies():
_chapters_by_title={}, _chapters_by_title={},
_title_alias={}, _title_alias={},
_sample_decrypt_tracks=set(), _sample_decrypt_tracks=set(),
_server_cdm=None, _server_cdm_request=None,
session=requests.Session(), session=requests.Session(),
_session_id="s", _session_id="s",
service_tag="EXAMPLE", service_tag="EXAMPLE",
+36 -31
View File
@@ -60,6 +60,8 @@ from unshackle.core.remote_protocol import (
BadKeyReport, BadKeyReport,
LicenseReply, LicenseReply,
LicenseRequest, LicenseRequest,
LicensingMode,
Licensor,
LogsReply, LogsReply,
PromptAnswer, PromptAnswer,
PromptReply, PromptReply,
@@ -971,22 +973,36 @@ def choose_session_cdm(policy: KeyPolicy, service: str, data: dict[str, Any]) ->
return licence_cap.session_fits(cap, service, data.get("quality"), bool(data.get("cdm_type"))), cap return licence_cap.session_fits(cap, service, data.get("quality"), bool(data.get("cdm_type"))), cap
def session_licensing(policy: KeyPolicy, service: str, data: dict[str, Any]) -> LicensingMode:
"""The licensing mode of a new remote session, before the service is built.
An older client that sends no ``cdm_relay`` gets no client device outside a capped session.
"""
use_server_cdm, max_height = choose_session_cdm(policy, service, data)
if use_server_cdm:
return LicensingMode(Licensor.SERVER_CDM, max_height)
if data.get("cdm_type") and (max_height is not None or data.get("cdm_relay") is True):
return LicensingMode(Licensor.CLIENT_DEVICE, max_height, policy.allows("server_vault", service))
return LicensingMode(Licensor.NO_DEVICE, max_height)
def live_licence_refusal(session: SessionEntry, track: Any) -> APIError | None: def live_licence_refusal(session: SessionEntry, track: Any) -> APIError | None:
"""Why the server CDM must not make a live licence for ``track`` in ``session``; None when it may. """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. Only a live licence spends the server's device, so a vault hit always passes.
""" """
if session.server_device: licensing = session.licensing
if licensing.server_device:
return APIError( return APIError(
APIErrorCode.SERVER_CDM_CAPPED, APIErrorCode.SERVER_CDM_CAPPED,
"This session runs on the server's device, so its keys come only from a vault.", "This session runs on the server's device, so its keys come only from a vault.",
details={"reason": "server_device"}, details={"reason": "server_device"},
) )
if not session.server_cdm: if not licensing.server_cdm:
return licence_cap.capped_error( return licence_cap.capped_error(
"This session licenses with your own device, so the server CDM makes no licence for it." "This session licenses with your own device, so the server CDM makes no licence for it."
) )
return licence_cap.track_refusal(session.server_cdm_max_height, track) return licence_cap.track_refusal(licensing.max_height, track)
_account_counters: dict[str, int] = {} _account_counters: dict[str, int] = {}
@@ -2861,13 +2877,7 @@ async def session_create_handler(data: dict[str, Any], request: web.Request | No
profile = next_server_profile(normalized_service, region) profile = next_server_profile(normalized_service, region)
log.info(f"Using server account '{sanitize_log(profile or 'default')}' for {normalized_service}") log.info(f"Using server account '{sanitize_log(profile or 'default')}' for {normalized_service}")
use_server_cdm, max_height = choose_session_cdm(policy, normalized_service, data) licensing = session_licensing(policy, normalized_service, data)
# an old client without cdm_relay keeps the server's device outside a capped session
client_device = (
not use_server_cdm
and bool(data.get("cdm_type"))
and (max_height is not None or data.get("cdm_relay") is True)
)
bridge = InputBridge() bridge = InputBridge()
log_buffer = None if server_account else SessionLogBuffer() log_buffer = None if server_account else SessionLogBuffer()
service_class_name = getattr(Services.load(normalized_service), "__name__", normalized_service) service_class_name = getattr(Services.load(normalized_service), "__name__", normalized_service)
@@ -2882,8 +2892,8 @@ async def session_create_handler(data: dict[str, Any], request: web.Request | No
proxy_providers, proxy_providers,
profile, profile,
server_account=server_account, server_account=server_account,
server_cdm=use_server_cdm, server_cdm=licensing.server_cdm,
client_device=client_device, client_device=licensing.client_device,
input_bridge=bridge, input_bridge=bridge,
policy=policy, policy=policy,
) )
@@ -2894,7 +2904,8 @@ async def session_create_handler(data: dict[str, Any], request: web.Request | No
# the service asked for the server's device in __init__, so the session never licenses live # the service asked for the server's device in __init__, so the session never licenses live
stand_in = getattr(getattr(getattr(service_instance, "ctx", None), "obj", None), "cdm", None) stand_in = getattr(getattr(getattr(service_instance, "ctx", None), "obj", None), "cdm", None)
server_device = getattr(stand_in, "lent", False) is True if getattr(stand_in, "lent", False) is True:
licensing = licensing.lent()
cache_tag = f"_accounts/{normalized_service}/{profile or 'default'}" if server_account else session_cache_dir cache_tag = f"_accounts/{normalized_service}/{profile or 'default'}" if server_account else session_cache_dir
if server_account: if server_account:
session_cache_tag = None session_cache_tag = None
@@ -2905,7 +2916,7 @@ async def session_create_handler(data: dict[str, Any], request: web.Request | No
api_key, api_key,
policy, policy,
temporary=not server_account, temporary=not server_account,
client_identity=client_device and not server_device, client_identity=licensing.client_identity,
) )
cache_data = data.get("cache", {}) cache_data = data.get("cache", {})
@@ -2924,10 +2935,7 @@ async def session_create_handler(data: dict[str, Any], request: web.Request | No
server_account=(profile or "default") if server_account else None, server_account=(profile or "default") if server_account else None,
cache_tag=session_cache_tag, cache_tag=session_cache_tag,
policy=policy, policy=policy,
server_cdm=use_server_cdm, licensing=licensing,
server_cdm_max_height=max_height,
server_vault=client_device and policy.allows("server_vault", normalized_service),
server_device=server_device,
client_auth=not server_account client_auth=not server_account
and (cookies is not None or credential is not None or bool(cache_data and session_cache_tag)), 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. # Echoed to every dashboard viewer, so cap what an arbitrary client can push into it.
@@ -2965,10 +2973,7 @@ async def session_create_handler(data: dict[str, Any], request: web.Request | No
service=normalized_service, service=normalized_service,
status=AuthStatus.AUTHENTICATING, status=AuthStatus.AUTHENTICATING,
server_account=server_account, server_account=server_account,
server_cdm=use_server_cdm, **licensing.created_fields(),
server_cdm_max_height=max_height,
server_vault=session.server_vault,
server_device=session.server_device,
) )
) )
@@ -3073,7 +3078,7 @@ def client_owns_login(session: SessionEntry) -> bool:
A remote session on the server's lent device logs in with the server's device identity, so its tokens stay there. 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 session.server_device return bool(session.client_auth) and not session.licensing.server_device
def scrub_secret_keys(value: Any) -> Any: def scrub_secret_keys(value: Any) -> Any:
@@ -3152,7 +3157,7 @@ async def session_tracks_handler(
service_tag = session.service_tag service_tag = session.service_tag
config_cdm_type = detect_cdm_type_for_service(service_tag, app_config) config_cdm_type = detect_cdm_type_for_service(service_tag, app_config)
if not config_cdm_type and session.server_cdm and choose_cdm(app_config.cdm, service_tag).both: if not config_cdm_type and session.licensing.server_cdm and choose_cdm(app_config.cdm, service_tag).both:
loaded = getattr(getattr(getattr(service_instance, "ctx", None), "obj", None), "cdm", None) loaded = getattr(getattr(getattr(service_instance, "ctx", None), "obj", None), "cdm", None)
config_cdm_type = cdm_system(loaded) or "widevine" config_cdm_type = cdm_system(loaded) or "widevine"
@@ -3188,7 +3193,7 @@ async def session_tracks_handler(
session_headers=session_headers, session_headers=session_headers,
session_cookies=cookie_values(session_cookies), session_cookies=cookie_values(session_cookies),
session_cookie_jar=session_cookies, session_cookie_jar=session_cookies,
server_cdm=session.server_cdm, server_cdm=session.licensing.server_cdm,
server_cdm_type=server_cdm_type, server_cdm_type=server_cdm_type,
sample_decrypt_tracks=[ sample_decrypt_tracks=[
str(t.id) for t in [*tracks.videos, *tracks.audio] if service_instance.decrypts_samples(t) str(t.id) for t in [*tracks.videos, *tracks.audio] if service_instance.decrypts_samples(t)
@@ -4175,10 +4180,10 @@ def license_response(data: LicenseRequest, session: Any, session_id: str, reques
drm_type = data.get("drm_type", "widevine") drm_type = data.get("drm_type", "widevine")
mode = data.get("mode", "proxy") mode = data.get("mode", "proxy")
# a session the client's device licenses reaches the server vault only; its live licences stay client-side licensing = session.licensing
vault_only = not session.server_cdm vault_only = licensing.vault_only
if mode == "server_cdm" and not ( if mode == "server_cdm" and not (
session.server_vault if vault_only else request_policy(request).allows("server_cdm", session.service_tag) licensing.server_vault if vault_only else request_policy(request).allows("server_cdm", session.service_tag)
): ):
raise APIError( raise APIError(
APIErrorCode.FORBIDDEN, APIErrorCode.FORBIDDEN,
@@ -4284,7 +4289,7 @@ def license_response(data: LicenseRequest, session: Any, session_id: str, reques
ensure_track_drm(track, svc_session, init_data) ensure_track_drm(track, svc_session, init_data)
cipher = whole_file_cipher(track) cipher = whole_file_cipher(track)
if cipher is not None: if cipher is not None:
if not (vault_only or session.server_device): if not vault_only:
try: try:
file_keys[tid] = cipher.content_key().hex() file_keys[tid] = cipher.content_key().hex()
except (Exception, SystemExit) as e: except (Exception, SystemExit) as e:
@@ -4377,7 +4382,7 @@ def license_response(data: LicenseRequest, session: Any, session_id: str, reques
cipher = whole_file_cipher(track) cipher = whole_file_cipher(track)
if cipher is not None and (mode == "server_cdm" or cipher.key is not None): if cipher is not None and (mode == "server_cdm" or cipher.key is not None):
if (vault_only or session.server_device) and cipher.key is None: if vault_only and cipher.key is None:
raise APIError( raise APIError(
APIErrorCode.FORBIDDEN, "Server licensing is not enabled for this session on this service" APIErrorCode.FORBIDDEN, "Server licensing is not enabled for this session on this service"
) )
@@ -4444,7 +4449,7 @@ def license_response(data: LicenseRequest, session: Any, session_id: str, reques
track.pr_pssh = pssh_b64 track.pr_pssh = pssh_b64
certificate = data.get("is_certificate") is True certificate = data.get("is_certificate") is True
if session.server_device and not certificate: if licensing.server_device and not certificate:
denied = live_licence_refusal(session, track) denied = live_licence_refusal(session, track)
if denied: if denied:
raise denied raise denied
+7 -15
View File
@@ -22,13 +22,14 @@ from unshackle.core.api.input_bridge import AUTH_INPUT_TIMEOUT, InputBridge
from unshackle.core.api.sanitize import sanitize_log from unshackle.core.api.sanitize import sanitize_log
from unshackle.core.api.session_channel import SessionChannel, drain_message from unshackle.core.api.session_channel import SessionChannel, drain_message
from unshackle.core.config import config from unshackle.core.config import config
from unshackle.core.remote_protocol import AuthStatus from unshackle.core.remote_protocol import AuthStatus, LicensingMode, Licensor
from unshackle.core.tracks import Track, Tracks from unshackle.core.tracks import Track, Tracks
if TYPE_CHECKING: if TYPE_CHECKING:
from unshackle.core.api.key_policy import KeyPolicy from unshackle.core.api.key_policy import KeyPolicy
log = logging.getLogger("api.session") log = logging.getLogger("api.session")
NO_DEVICE = LicensingMode(Licensor.NO_DEVICE)
DRAIN_WARNING = "This server restarts for an update after the open downloads finish; this download continues" DRAIN_WARNING = "This server restarts for an update after the open downloads finish; this download continues"
@@ -54,10 +55,7 @@ class SessionEntry:
owner_key: str | None = None # X-Secret-Key that owns this session owner_key: str | None = None # X-Secret-Key that owns this session
cache_tag: str | None = None cache_tag: str | None = None
server_account: str | None = None # profile name when the server lent its own account server_account: str | None = None # profile name when the server lent its own account
server_cdm: bool = False # False: the client's own device licenses this session licensing: LicensingMode = NO_DEVICE
server_cdm_max_height: int | None = 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
client_auth: bool = False # the login is the client's: it succeeded without a server account client_auth: bool = False # the login is the client's: it succeeded without a server account
policy: KeyPolicy | None = field(default=None, repr=False) # the API key policy the session was created with policy: KeyPolicy | None = field(default=None, repr=False) # the API key policy the session was created with
input_bridge: InputBridge | None = None input_bridge: InputBridge | None = None
@@ -126,8 +124,8 @@ class SessionEntry:
"auth_status": self.auth_status.value, "auth_status": self.auth_status.value,
"auth_error": self.auth_error, "auth_error": self.auth_error,
"server_account": self.server_account, "server_account": self.server_account,
"server_cdm": self.server_cdm, "server_cdm": self.licensing.server_cdm,
"server_cdm_max_height": self.server_cdm_max_height, "server_cdm_max_height": self.licensing.max_height,
"log_seq": self.log_buffer.last_seq if self.log_buffer else 0, "log_seq": self.log_buffer.last_seq if self.log_buffer else 0,
"client": self.client, "client": self.client,
**({"actions": list(self.actions)} if include_actions else {}), **({"actions": list(self.actions)} if include_actions else {}),
@@ -194,10 +192,7 @@ class SessionStore:
server_account: str | None = None, server_account: str | None = None,
cache_tag: str | None = None, cache_tag: str | None = None,
policy: KeyPolicy | None = None, policy: KeyPolicy | None = None,
server_cdm: bool = False, licensing: LicensingMode = NO_DEVICE,
server_cdm_max_height: int | None = None,
server_vault: bool = False,
server_device: bool = False,
client_auth: bool = False, client_auth: bool = False,
client: dict[str, Any] | None = None, client: dict[str, Any] | None = None,
input_bridge: InputBridge | None = None, input_bridge: InputBridge | None = None,
@@ -231,10 +226,7 @@ class SessionStore:
server_account=server_account, server_account=server_account,
cache_tag=cache_tag, cache_tag=cache_tag,
policy=policy, policy=policy,
server_cdm=server_cdm, licensing=licensing,
server_cdm_max_height=server_cdm_max_height,
server_vault=server_vault,
server_device=server_device,
client_auth=client_auth, client_auth=client_auth,
client=client or {}, client=client or {},
input_bridge=input_bridge, input_bridge=input_bridge,
+101
View File
@@ -8,6 +8,7 @@ older peer.
from __future__ import annotations from __future__ import annotations
from dataclasses import dataclass, replace
from enum import Enum, StrEnum from enum import Enum, StrEnum
from typing import Any, NotRequired, TypedDict, TypeVar from typing import Any, NotRequired, TypedDict, TypeVar
@@ -163,6 +164,106 @@ class SessionCreated(TypedDict, total=False):
server_device: bool server_device: bool
class Licensor(StrEnum):
"""Who licenses a remote session."""
SERVER_CDM = "server_cdm"
"""The server's device licenses live, up to the licence cap."""
CLIENT_DEVICE = "client_device"
"""The client's own device licenses, and the service sees a stand-in for it."""
LENT_DEVICE = "lent_device"
"""The client's stand-in lent the server's device to the service, so the keys come only from a vault."""
NO_DEVICE = "no_device"
"""No server CDM, and no client device that the service can see."""
@dataclass(frozen=True)
class LicensingMode:
"""Who licenses a remote session, its licence cap and its access to the server vault, fixed at session create.
Only a client-device session, lent or not, can read the server vault. The wire keeps the older fields
``server_cdm``, ``server_cdm_max_height``, ``server_vault`` and ``server_device``.
"""
licensor: Licensor
max_height: int | None = None
server_vault: bool = False
def __post_init__(self) -> None:
if self.server_vault and not self.client_device:
raise ValueError(f"A {self.licensor} session cannot read the server vault")
@classmethod
def from_created(cls, reply: SessionCreated) -> LicensingMode:
"""The mode that the reply to a remote session creation gives."""
vault = bool(reply.get("server_vault"))
if reply.get("server_device"):
return cls(Licensor.LENT_DEVICE, reply.get("server_cdm_max_height"), vault)
if reply.get("server_cdm"):
return cls(Licensor.SERVER_CDM, reply.get("server_cdm_max_height"))
return cls(Licensor.CLIENT_DEVICE, reply.get("server_cdm_max_height"), vault)
def created_fields(self) -> SessionCreated:
"""The licensing fields of the reply to a remote session creation."""
return SessionCreated(
server_cdm=self.server_cdm,
server_cdm_max_height=self.max_height,
server_vault=self.server_vault,
server_device=self.server_device,
)
def lent(self) -> LicensingMode:
"""This client-device mode after the service took the server's device in its place."""
if self.licensor is not Licensor.CLIENT_DEVICE:
raise ValueError(f"A {self.licensor} session has no client device to lend the server's device")
return replace(self, licensor=Licensor.LENT_DEVICE)
@property
def server_cdm(self) -> bool:
"""True when the server's device can license live."""
return self.licensor is Licensor.SERVER_CDM
@property
def server_device(self) -> bool:
"""True when the service runs on the server's lent device."""
return self.licensor is Licensor.LENT_DEVICE
@property
def client_device(self) -> bool:
"""True when the service gets the stand-in for the client's device, lent or not."""
return self.licensor in (Licensor.CLIENT_DEVICE, Licensor.LENT_DEVICE)
@property
def client_identity(self) -> bool:
"""True when the device identity that the service builds is the client's own."""
return self.licensor is Licensor.CLIENT_DEVICE
@property
def vault_only(self) -> bool:
"""True when the server keys come only from a vault, so both DRM systems are candidates."""
return not self.server_cdm
@property
def keys_from_server(self) -> bool:
"""True when dl takes the content keys from the server and not from the challenge relay."""
return self.licensor in (Licensor.SERVER_CDM, Licensor.LENT_DEVICE)
@property
def reads_server_keys(self) -> bool:
"""True when the client asks the server for keys: its CDM licenses, or the API key reads the server vault."""
return self.server_cdm or self.server_vault
@property
def vault_first(self) -> bool:
"""True when the server vault answers before the client's own device licenses."""
return self.licensor is Licensor.CLIENT_DEVICE and self.server_vault
@property
def local_vaults_only(self) -> bool:
"""True for a lent-device session whose API key cannot read the server vault."""
return self.server_device and not self.server_vault
class TracksRequest(TypedDict): class TracksRequest(TypedDict):
title_id: str title_id: str
+63 -45
View File
@@ -19,6 +19,7 @@ import shlex
import sys import sys
import time import time
from collections.abc import Callable, Iterable, Iterator, Mapping from collections.abc import Callable, Iterable, Iterator, Mapping
from dataclasses import replace
from functools import partial from functools import partial
from http.cookiejar import CookieJar from http.cookiejar import CookieJar
from threading import Lock, local from threading import Lock, local
@@ -72,6 +73,8 @@ from unshackle.core.remote_protocol import (
ClientLogin, ClientLogin,
LicenseReply, LicenseReply,
LicenseRequest, LicenseRequest,
LicensingMode,
Licensor,
SegmentFilterReply, SegmentFilterReply,
SegmentFilterRequest, SegmentFilterRequest,
SegmentsRequest, SegmentsRequest,
@@ -841,6 +844,10 @@ class RemoteService(TitleSource):
server_cdm_type: str = "widevine" server_cdm_type: str = "widevine"
channel: Channel | None = None channel: Channel | None = None
licensing: LicensingMode | None = None
"""The server's answer to who licenses this remote session; an older server gives it in the tracks reply."""
_server_cdm_request: bool | None = None
"""This client's own server CDM choice; None leaves it to the server."""
def __init__( def __init__(
self, self,
@@ -903,10 +910,7 @@ class RemoteService(TitleSource):
record_requests(self.session) record_requests(self.session)
svc_config = services_config.get(service_tag, {}) svc_config = services_config.get(service_tag, {})
self._server_cdm: bool | None = services_config.get("_server_cdm") self._server_cdm_request = services_config.get("_server_cdm")
self._server_vault = False
self._server_device = False
self._local_vaults_only = False
self._server_accounts: dict | None = services_config.get("_server_accounts") self._server_accounts: dict | None = services_config.get("_server_accounts")
self._anonymous_search = bool(services_config.get("_anonymous_search")) self._anonymous_search = bool(services_config.get("_anonymous_search"))
# read before apply_service_config merges the server's values into the same section # read before apply_service_config merges the server's values into the same section
@@ -1109,8 +1113,9 @@ class RemoteService(TitleSource):
cdm_only = bool(self.ctx.parent and self.ctx.parent.params.get("cdm_only")) cdm_only = bool(self.ctx.parent and self.ctx.parent.params.get("cdm_only"))
if cdm_only and cdm is None: if cdm_only and cdm is None:
raise click.ClickException(f"--cdm-only over --remote needs a local CDM for {self.service_tag}") raise click.ClickException(f"--cdm-only over --remote needs a local CDM for {self.service_tag}")
cdm_entry = cdm is not None and self.ctx.obj.cdm_entry and self._server_cdm is None expected = self.expected_server_cdm
if not (cdm_entry or cdm_name or self._server_cdm is not None) and ci_get(config.cdm, self.service_tag): cdm_entry = cdm is not None and self.ctx.obj.cdm_entry and expected is None
if not (cdm_entry or cdm_name or expected is not None) and ci_get(config.cdm, self.service_tag):
self.log.warning( self.log.warning(
f"The cdm entry for {self.service_tag} did not load a device for this remote session, " f"The cdm entry for {self.service_tag} did not load a device for this remote session, "
"so the server decides who licenses it" "so the server decides who licenses it"
@@ -1119,8 +1124,8 @@ class RemoteService(TitleSource):
from unshackle.core.cdm.detect import cdm_system from unshackle.core.cdm.detect import cdm_system
if cdm_entry or cdm_name or cdm_only: if cdm_entry or cdm_name or cdm_only:
self._server_cdm = False self._server_cdm_request = expected = False
if self._server_cdm is False: if expected is False:
create_data["server_cdm"] = False create_data["server_cdm"] = False
create_data["cdm_type"] = cdm_system(cdm) or "widevine" create_data["cdm_type"] = cdm_system(cdm) or "widevine"
level = getattr(cdm, "security_level", None) level = getattr(cdm, "security_level", None)
@@ -1161,25 +1166,21 @@ class RemoteService(TitleSource):
atexit.register(self.close) atexit.register(self.close)
# an older server omits the field, and the tracks response settles it # an older server omits the field, and the tracks response settles it
if "server_cdm" in result: if "server_cdm" in result:
self.adopt_session_cdm(bool(result["server_cdm"]), result.get("server_cdm_max_height")) answer = LicensingMode.from_created(result)
self._server_device = bool(result.get("server_device")) self.adopt_session_cdm(replace(answer, server_vault=False) if cdm_only else answer, expected)
if cdm_only and self._server_device: lent = bool(self.licensing and self.licensing.server_device)
if cdm_only and lent:
raise click.ClickException( raise click.ClickException(
f"--cdm-only cannot license {self.service_tag}: the remote session runs on the server's device" f"--cdm-only cannot license {self.service_tag}: the remote session runs on the server's device"
) )
if cdm_entry and self._server_cdm is False and not self._server_device: if cdm_entry and self.expected_server_cdm is False:
self.log.info( self.log.info(
f"The cdm config has an entry for {self.service_tag}, so your own device licenses " f"The cdm config has an entry for {self.service_tag}, so your own device licenses "
"this remote session and not the server CDM" "this remote session and not the server CDM"
) )
vault = bool(result.get("server_vault")) if lent:
if self._server_device: whose = "your vaults only" if self.local_vaults_only else "the server vault or yours"
self._server_cdm = True
whose = "the server vault or yours" if vault else "your vaults only"
self.log.info(f"This session runs on the server's device: keys come from {whose}") self.log.info(f"This session runs on the server's device: keys come from {whose}")
self._server_vault = vault and not self._server_cdm and not cdm_only
# without the server vault grant the server refuses every key request, so none is sent
self._local_vaults_only = self._server_device and not vault
from unshackle.core.remote_channel import open_channel from unshackle.core.remote_channel import open_channel
@@ -1199,7 +1200,12 @@ class RemoteService(TitleSource):
@property @property
def local_vaults_only(self) -> bool: def local_vaults_only(self) -> bool:
"""True for a remote session on the server's device whose API key cannot read the server vault.""" """True for a remote session on the server's device whose API key cannot read the server vault."""
return getattr(self, "_local_vaults_only", False) return self.licensing is not None and self.licensing.local_vaults_only
@property
def expected_server_cdm(self) -> bool | None:
"""Whether the server gives this remote session its keys: the server's answer, else this client's request."""
return self.licensing.keys_from_server if self.licensing else self._server_cdm_request
def report_local_fallback(self) -> None: def report_local_fallback(self) -> None:
"""Say the local CDM licenses because the server CDM is not granted. """Say the local CDM licenses because the server CDM is not granted.
@@ -1212,27 +1218,26 @@ class RemoteService(TitleSource):
"falling back to the local CDM" "falling back to the local CDM"
) )
def adopt_session_cdm(self, server_cdm: bool, max_height: int | None) -> None: def adopt_session_cdm(self, answer: LicensingMode, expected: bool | None) -> None:
"""Take the server's choice of who licenses this remote session, and say why when a cap made it. """Take the server's choice of who licenses this remote session, and say why when a cap made it.
A remote session on the server's lent device keeps the server-CDM flow: dl checks the local vaults, then asks the A remote session on the server's lent device keeps the server-CDM flow: dl checks the local vaults, then asks the
server, which answers only from its vault. ``_server_cdm`` is False on entry when the user picked the local server, which answers only from its vault. ``expected`` is False when the user picked the local device, so a
device, so a server that keeps its own CDM gets a warning. server that keeps its own CDM gets a warning.
""" """
if getattr(self, "_server_device", False): was_lent = self.licensing is not None and self.licensing.server_device
self._server_cdm = True self.licensing = answer
if was_lent:
return return
if self._server_cdm is False and server_cdm: if expected is False and answer.server_cdm:
self._server_cdm = True
self.log.warning("The server CDM licenses this remote session, so your own device is not used") self.log.warning("The server CDM licenses this remote session, so your own device is not used")
return return
if self._server_cdm and not server_cdm and max_height is None: if expected and not answer.server_cdm and answer.max_height is None:
self.report_local_fallback() self.report_local_fallback()
self._server_cdm = server_cdm if answer.max_height is None:
if max_height is None:
return return
message = cap_note(max_height) message = cap_note(answer.max_height)
if not server_cdm: if not answer.server_cdm:
message += "; licensing with your own device" message += "; licensing with your own device"
elif self.local_cdm is not None: elif self.local_cdm is not None:
message += "; pass a higher -q to license above it with your own device" message += "; pass a higher -q to license above it with your own device"
@@ -1293,12 +1298,20 @@ class RemoteService(TitleSource):
time.sleep(random.uniform(delay / 2, delay)) # nosec B311 time.sleep(random.uniform(delay / 2, delay)) # nosec B311
delay = min(delay * 2, 30.0) delay = min(delay * 2, 30.0)
def licence_path(self) -> object:
"""Where this remote session takes its keys from, which a reopened session must keep.
A lent-device session that loses the server vault goes on with the local vaults only.
"""
licensing = self.licensing
return (licensing.licensor, licensing.vault_first) if licensing else self._server_cdm_request
def reopen(self) -> bool: def reopen(self) -> bool:
"""Open a new remote session after the server lost this one, and load the current title's tracks on it again. """Open a new remote session after the server lost this one, and load the current title's tracks on it again.
A track the new remote session gives another id keeps its old one here, and calls translate it. A track the new remote session gives another id keeps its old one here, and calls translate it.
""" """
grants = (self._server_cdm, self._server_device, self._server_vault) grants = self.licence_path()
self.close_channel() self.close_channel()
self._session_id = None self._session_id = None
if self.client.tunnel: # the server forgot the tunnel too if self.client.tunnel: # the server forgot the tunnel too
@@ -1334,7 +1347,7 @@ class RemoteService(TitleSource):
if e.kind not in RECOVERABLE: if e.kind not in RECOVERABLE:
raise raise
return False return False
if (self._server_cdm, self._server_device, self._server_vault) != grants: if self.licence_path() != grants:
raise RemoteError( raise RemoteError(
"The new remote session licenses differently from the lost one", ClientErrorKind.GRANTS_CHANGED "The new remote session licenses differently from the lost one", ClientErrorKind.GRANTS_CHANGED
) )
@@ -1430,11 +1443,15 @@ class RemoteService(TitleSource):
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))
if self._server_cdm is None: if self.licensing is None:
self._server_cdm = server_cdm request = self._server_cdm_request
elif self._server_cdm and not server_cdm: if request and not server_cdm:
self._server_cdm = False self.report_local_fallback()
server_cdm = server_cdm and request is not False
self.licensing = LicensingMode(Licensor.SERVER_CDM if server_cdm else Licensor.CLIENT_DEVICE)
elif self.licensing.server_cdm and not server_cdm:
self.licensing = replace(self.licensing, licensor=Licensor.CLIENT_DEVICE)
self.report_local_fallback() self.report_local_fallback()
self.server_cdm_type = session_fields.get("server_cdm_type", "widevine") self.server_cdm_type = session_fields.get("server_cdm_type", "widevine")
self._sample_decrypt_tracks.update(session_fields.get("sample_decrypt_tracks") or []) self._sample_decrypt_tracks.update(session_fields.get("sample_decrypt_tracks") or [])
@@ -1517,7 +1534,8 @@ class RemoteService(TitleSource):
# track ids can repeat across titles, so a refusal for the last title must not carry over # track ids can repeat across titles, so a refusal for the last title must not carry over
self.client_licensed.clear() self.client_licensed.clear()
self.deferred_refusals.clear() self.deferred_refusals.clear()
if not (self._server_cdm or getattr(self, "_server_vault", False)) or self.local_vaults_only: licensing = self.licensing
if licensing is None or not licensing.reads_server_keys:
return return
from uuid import UUID from uuid import UUID
@@ -1527,7 +1545,7 @@ class RemoteService(TitleSource):
return return
drm_type = self.server_cdm_type drm_type = self.server_cdm_type
if getattr(self, "_server_vault", False): if licensing.vault_first:
from unshackle.core.cdm.detect import cdm_system from unshackle.core.cdm.detect import cdm_system
drm_type = cdm_system(self.local_cdm) or "widevine" drm_type = cdm_system(self.local_cdm) or "widevine"
@@ -1600,7 +1618,7 @@ class RemoteService(TitleSource):
try: try:
self.license_locally(track, refusal) self.license_locally(track, refusal)
except click.ClickException as e: except click.ClickException as e:
if not self._server_cdm: if not licensing.keys_from_server:
raise raise
self.deferred_refusals[str(track.id)] = e.message self.deferred_refusals[str(track.id)] = e.message
self.log.debug(f"{e.message}; trying the local vaults first") self.log.debug(f"{e.message}; trying the local vaults first")
@@ -1625,7 +1643,7 @@ class RemoteService(TitleSource):
cap = refusal.get("max_height") cap = refusal.get("max_height")
if cap: if cap:
why = cap_note(cap) why = cap_note(cap)
elif getattr(self, "_server_vault", False): elif self.licensing and self.licensing.vault_first:
why = "The server vault holds no content key for this track" why = "The server vault holds no content key for this track"
else: else:
why = "The server CDM refused this track" why = "The server CDM refused this track"
@@ -1660,7 +1678,7 @@ class RemoteService(TitleSource):
@property @property
def key_arrival(self) -> KeyArrival: def key_arrival(self) -> KeyArrival:
"""``SERVER`` when the server CDM licenses this remote session, else ``CALLBACK``: the challenge relay.""" """``SERVER`` when the server CDM licenses this remote session, else ``CALLBACK``: the challenge relay."""
return KeyArrival.SERVER if self._server_cdm else KeyArrival.CALLBACK return KeyArrival.SERVER if self.expected_server_cdm else KeyArrival.CALLBACK
@property @property
def key_source(self) -> RemoteService: def key_source(self) -> RemoteService:
@@ -1788,7 +1806,7 @@ class RemoteService(TitleSource):
def license_file(self, track: AnyTrack) -> str: def license_file(self, track: AnyTrack) -> str:
"""The content key the server licenses for the whole-file cipher of ``track``, or raise ClickException.""" """The content key the server licenses for the whole-file cipher of ``track``, or raise ClickException."""
if self.local_vaults_only or not self._server_cdm: if self.local_vaults_only or not self.expected_server_cdm:
raise coded( raise coded(
click.ClickException(f"Track {track.id} needs a server licence that this session does not allow"), click.ClickException(f"Track {track.id} needs a server licence that this session does not allow"),
APIErrorCode.DRM_ERROR, APIErrorCode.DRM_ERROR,