mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-12-05 07:25:08 +00:00
refactor(cdm): leave key vault reads and writes to content-key resolution in an HTTP CDM run
This commit is contained in:
@@ -421,7 +421,7 @@ remote_cdm:
|
||||
|
||||
The `custom_api` type supports much more: request/response field remapping,
|
||||
transforms (base64/hex/JSON encoding, `kid:key` parsing), conditional parameters,
|
||||
success/error detection, and vault-backed caching. Its full schema is for developers
|
||||
and success/error detection. Its full schema is for developers
|
||||
who integrate a bespoke CDM API. See the developer note below.
|
||||
|
||||
!!! note "Developer: full `custom_api` schema"
|
||||
@@ -435,7 +435,6 @@ who integrate a bespoke CDM API. See the developer note below.
|
||||
`conditional_params`, `transforms`, `nested_params`, `exclude_params`) and
|
||||
`response_mapping` (`fields`, `transforms`, `response_types`,
|
||||
`success_conditions`, `error_fields`, `key_fields`)
|
||||
- `caching` (`enabled`, `use_vaults`, `check_cached_first`)
|
||||
- `legacy` and `timeout`
|
||||
|
||||
unshackle infers PlayReady mode when `device.type == PLAYREADY` or the device name
|
||||
|
||||
@@ -94,7 +94,7 @@ A list of remote CDM definitions. unshackle matches each entry by its `name` (re
|
||||
| `type` | Backend | Key fields |
|
||||
|--------|---------|-----------|
|
||||
| `decrypt_labs` | Decrypt Labs KeyXtractor | `host`, `device_name`, `secret` ([fields](#remote-cdm-decrypt-labs)) |
|
||||
| `custom_api` | Fully YAML-configurable remote API | `host` (required), `device`, `auth`, `endpoints`, `request_mapping`, `response_mapping`, `caching`, `timeout` ([fields](#remote-cdm-custom-api)) |
|
||||
| `custom_api` | Fully YAML-configurable remote API | `host` (required), `device`, `auth`, `endpoints`, `request_mapping`, `response_mapping`, `timeout` ([fields](#remote-cdm-custom-api)) |
|
||||
| *(none)*, `Device Type: PLAYREADY` | pyplayready `RemoteCdm` | `host`, `secret`, `device_name`, `security_level` (default 3000) |
|
||||
| *(none)*, otherwise | pywidevine `RemoteCdm` | `host`, `secret`, `device_name`, `device_type`, `system_id`, `security_level` (default 3000) |
|
||||
|
||||
@@ -151,7 +151,6 @@ unshackle uses PlayReady mode when `device_type` is `PLAYREADY` or `device_name`
|
||||
| `endpoints` | dict | `get_request` and `decrypt_response`, each `{path, method, timeout}` |
|
||||
| `request_mapping` | dict | Per endpoint: `param_names`, `static_params`, `conditional_params`, `transforms`, `nested_params`, `exclude_params` |
|
||||
| `response_mapping` | dict | Per endpoint: `fields`, `transforms`, `response_types`, `success_conditions`, `error_fields`, `key_fields` |
|
||||
| `caching` | dict | `enabled`, `use_vaults`, `check_cached_first` |
|
||||
| `legacy` | dict | Legacy mode options. |
|
||||
| `timeout` | int | Default `30`. Request timeout in seconds. |
|
||||
|
||||
|
||||
@@ -9,7 +9,6 @@ key pair and a blocking request to its host.
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -32,7 +31,7 @@ def builds(monkeypatch) -> list[tuple[str, str]]:
|
||||
"""Record every ``load_cdm`` call and hand back a fresh stub for each one."""
|
||||
calls: list[tuple[str, str]] = []
|
||||
|
||||
def fake_load_cdm(cdm_name: str, *, service_name: str = "", vaults: Any | None = None) -> StubCdm:
|
||||
def fake_load_cdm(cdm_name: str, *, service_name: str = "") -> StubCdm:
|
||||
calls.append((cdm_name, service_name))
|
||||
return StubCdm(cdm_name, service_name)
|
||||
|
||||
|
||||
+101
-20
@@ -1,8 +1,10 @@
|
||||
"""The shared bookkeeping of the HTTP CDMs: sessions, vault and cached keys, and their merge with licence keys."""
|
||||
"""The shared bookkeeping of the HTTP CDMs: sessions, API cache keys and their merge with licence keys; the key vaults stay with content-key resolution."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
from collections.abc import Callable
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
from uuid import UUID
|
||||
|
||||
@@ -10,11 +12,13 @@ import pytest
|
||||
from pywidevine.cdm import Cdm as WidevineCdm
|
||||
from pywidevine.pssh import PSSH
|
||||
|
||||
from tests.core.key_resolver import MemoryVault, vaults_of
|
||||
from tests.core.key_resolver import MemoryVault, key_table, resolver, vaults_of
|
||||
from tests.core.test_playready_multi_header import _drm, _wrm_header
|
||||
from unshackle.core.cdm.custom_remote_cdm import CustomRemoteCDM, CustomRemoteCDMExceptions
|
||||
from unshackle.core.cdm.decrypt_labs_remote_cdm import DecryptLabsRemoteCDM, DecryptLabsRemoteCDMExceptions
|
||||
from unshackle.core.cdm.http_cdm import HttpCdm, HttpCdmExceptions
|
||||
from unshackle.core.drm import Widevine
|
||||
from unshackle.core.cdm.loader import load_remote_cdm
|
||||
from unshackle.core.drm import PlayReady, Widevine
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
@@ -30,9 +34,9 @@ class StubCdm(HttpCdm):
|
||||
self,
|
||||
cached: list[dict[str, Any]] | None = None,
|
||||
licence: list[dict[str, Any]] | None = None,
|
||||
vaults: Any = None,
|
||||
device: str = "L3",
|
||||
) -> None:
|
||||
super().__init__("https://cdm.test/", "L3", None, "EXAMPLE", vaults, {})
|
||||
super().__init__("https://cdm.example/", device, None, "EXAMPLE", {})
|
||||
self.cached = cached
|
||||
self.licence = licence or []
|
||||
self.challenges = 0
|
||||
@@ -61,6 +65,14 @@ def key(kid: UUID, value: str) -> dict[str, str]:
|
||||
return {"kid": kid.hex, "key": value, "type": "CONTENT"}
|
||||
|
||||
|
||||
def widevine(*kids: UUID) -> Widevine:
|
||||
return Widevine(pssh=PSSH.new(system_id=PSSH.SystemId.Widevine, key_ids=list(kids)), kid=kids[-1])
|
||||
|
||||
|
||||
def playready(*kids: UUID) -> PlayReady:
|
||||
return _drm(_wrm_header(*kids))
|
||||
|
||||
|
||||
def licensed(cdm: StubCdm, *kids: UUID) -> dict[UUID, str]:
|
||||
"""Run one challenge and licence round and return the content keys of the session."""
|
||||
session_id = cdm.open()
|
||||
@@ -70,19 +82,6 @@ def licensed(cdm: StubCdm, *kids: UUID) -> dict[UUID, str]:
|
||||
return {k.kid: k.key.hex() for k in cdm.get_keys(session_id, "CONTENT")}
|
||||
|
||||
|
||||
def test_vaults_holding_every_kid_skip_the_api() -> None:
|
||||
cdm = StubCdm(vaults=vaults_of(MemoryVault({KID_A: KEY_A, KID_B: KEY_B})))
|
||||
assert licensed(cdm, KID_A, KID_B) == {KID_A: KEY_A, KID_B: KEY_B}
|
||||
assert cdm.challenges == 0
|
||||
|
||||
|
||||
def test_a_vault_key_wins_over_the_licence_and_licence_keys_go_to_the_vaults() -> None:
|
||||
vault = MemoryVault({KID_A: KEY_A})
|
||||
cdm = StubCdm(licence=[key(KID_A, KEY_X), key(KID_B, KEY_B), key(KID_B, KEY_X)], vaults=vaults_of(vault))
|
||||
assert licensed(cdm, KID_A, KID_B) == {KID_A: KEY_A, KID_B: KEY_B}
|
||||
assert vault.added == {KID_A: KEY_A, KID_B: KEY_B}
|
||||
|
||||
|
||||
def test_cached_keys_covering_every_kid_need_no_licence() -> None:
|
||||
cdm = StubCdm(cached=[key(KID_A, KEY_A)])
|
||||
assert licensed(cdm, KID_A) == {KID_A: KEY_A}
|
||||
@@ -108,7 +107,7 @@ def test_widevine_skips_the_licence_when_the_cdm_holds_cached_keys() -> None:
|
||||
def licence(**_: Any) -> bytes:
|
||||
raise AssertionError("no licence request when the cache holds every key")
|
||||
|
||||
drm = Widevine(pssh=PSSH.new(system_id=PSSH.SystemId.Widevine, key_ids=[KID_A]), kid=KID_A)
|
||||
drm = widevine(KID_A)
|
||||
cdm = StubCdm(cached=[key(KID_A, KEY_A)])
|
||||
drm.get_content_keys(cdm, certificate=lambda **_: None, licence=licence)
|
||||
assert drm.content_keys == {KID_A: KEY_A}
|
||||
@@ -143,8 +142,90 @@ class L1StubCdm(StubCdm):
|
||||
|
||||
|
||||
def test_widevine_gives_a_listed_device_the_common_privacy_certificate_when_the_service_has_none() -> None:
|
||||
drm = Widevine(pssh=PSSH.new(system_id=PSSH.SystemId.Widevine, key_ids=[KID_A]), kid=KID_A)
|
||||
drm = widevine(KID_A)
|
||||
cdm = L1StubCdm()
|
||||
drm.get_content_keys(cdm, certificate=lambda **_: None, licence=lambda **_: b"licence")
|
||||
assert base64.b64decode(cdm.sent[0]["service_certificate"]) == base64.b64decode(WidevineCdm.common_privacy_cert)
|
||||
assert drm.content_keys == {KID_A: KEY_A}
|
||||
|
||||
|
||||
SYSTEMS = pytest.mark.parametrize(
|
||||
("make_drm", "device"), [(widevine, "L3"), (playready, "SL3000")], ids=["widevine", "playready"]
|
||||
)
|
||||
|
||||
|
||||
def resolve(drm: Widevine | PlayReady, cdm: StubCdm, vaults: Any, track_kid: UUID) -> int:
|
||||
"""License ``drm`` for ``track_kid`` as dl does and return the number of licence requests to the service."""
|
||||
keys = resolver(vaults, cdm=cdm)
|
||||
sent: list[int] = []
|
||||
|
||||
def licence(**_: Any) -> str:
|
||||
sent.append(1)
|
||||
return "<License>licence</License>"
|
||||
|
||||
keys.service.get_widevine_license = keys.service.get_playready_license = licence
|
||||
keys.licence_for(SimpleNamespace(drm=[drm]), None, key_table(), False)(drm, track_kid=track_kid)
|
||||
keys.wait_vault_writes()
|
||||
return len(sent)
|
||||
|
||||
|
||||
@SYSTEMS
|
||||
def test_each_vault_is_asked_once_and_gets_one_push(make_drm: Callable[..., Any], device: str) -> None:
|
||||
stores = [
|
||||
MemoryVault(name="local"),
|
||||
MemoryVault(local=False, name="remote"),
|
||||
MemoryVault(local=False, name="other"),
|
||||
]
|
||||
vaults = vaults_of(*stores)
|
||||
cdm = StubCdm(licence=[key(KID_A, KEY_A)], device=device)
|
||||
assert resolve(make_drm(KID_A), cdm, vaults, KID_A) == 1
|
||||
for store in stores:
|
||||
assert store.asked == [KID_A], store.name
|
||||
assert store.pushes == [{KID_A: KEY_A}], store.name
|
||||
|
||||
|
||||
@SYSTEMS
|
||||
def test_a_vault_key_no_decode_proved_is_in_no_push(make_drm: Callable[..., Any], device: str) -> None:
|
||||
stores = [MemoryVault(name="local"), MemoryVault({KID_A: KEY_X}, local=False, name="remote")]
|
||||
stores.append(MemoryVault(local=False, name="other"))
|
||||
vaults = vaults_of(*stores)
|
||||
cdm = StubCdm(licence=[key(KID_B, KEY_B)], device=device)
|
||||
drm = make_drm(KID_A, KID_B)
|
||||
assert resolve(drm, cdm, vaults, KID_B) == 1
|
||||
assert drm.content_keys == {KID_A: KEY_X, KID_B: KEY_B}
|
||||
assert [push for store in stores for push in store.pushes if KID_A in push] == []
|
||||
|
||||
|
||||
@SYSTEMS
|
||||
def test_a_vault_key_and_the_api_cache_covering_the_track_send_no_licence(
|
||||
make_drm: Callable[..., Any], device: str
|
||||
) -> None:
|
||||
vaults = vaults_of(MemoryVault(name="local"), MemoryVault({KID_A: KEY_A}, local=False, name="remote"))
|
||||
cdm = StubCdm(cached=[key(KID_B, KEY_B)], licence=[key(KID_A, KEY_A), key(KID_B, KEY_B)], device=device)
|
||||
drm = make_drm(KID_A, KID_B)
|
||||
assert resolve(drm, cdm, vaults, KID_B) == 0
|
||||
assert drm.content_keys == {KID_A: KEY_A, KID_B: KEY_B}
|
||||
assert cdm.required == [[KID_B.hex]]
|
||||
|
||||
|
||||
@SYSTEMS
|
||||
def test_a_licence_without_the_vault_kid_is_not_sent_again(make_drm: Callable[..., Any], device: str) -> None:
|
||||
vaults = vaults_of(MemoryVault({KID_B: KEY_B}, name="local"))
|
||||
cdm = StubCdm(licence=[key(KID_A, KEY_A)], device=device)
|
||||
drm = make_drm(KID_A, KID_B)
|
||||
assert resolve(drm, cdm, vaults, KID_A) == 1
|
||||
assert drm.content_keys == {KID_A: KEY_A, KID_B: KEY_B}
|
||||
|
||||
|
||||
def test_a_caching_block_in_a_remote_cdm_entry_still_loads() -> None:
|
||||
entry = {"type": "custom_api", "host": "https://cdm.example", "caching": {"enabled": True, "use_vaults": True}}
|
||||
cdm = load_remote_cdm("EXAMPLE_CDM", entry, "widevine", "EXAMPLE")
|
||||
assert isinstance(cdm, CustomRemoteCDM)
|
||||
|
||||
|
||||
def test_playready_keeps_its_required_kids_when_every_kid_is_known() -> None:
|
||||
drm = playready(KID_A)
|
||||
drm.content_keys[KID_A] = KEY_A
|
||||
cdm = StubCdm(cached=[], licence=[key(KID_A, KEY_A)], device="SL3000")
|
||||
drm._license_header(cdm, drm.pssh.wrm_headers[0], drm.pssh_b64, [KID_A], lambda **_: "<License>licence</License>")
|
||||
assert cdm.required == [[KID_A.hex]]
|
||||
|
||||
@@ -3038,7 +3038,7 @@ class dl:
|
||||
if not isinstance(cdm_name, str):
|
||||
from unshackle.core.cdm import load_cdm
|
||||
|
||||
return load_cdm(cdm_name, service_name=service, vaults=self.vaults)
|
||||
return load_cdm(cdm_name, service_name=service)
|
||||
return self.load_named_cdm(service, profile, cdm_name)
|
||||
|
||||
def load_named_cdm(self, service: str, profile: str | None, cdm_name: str) -> Any:
|
||||
@@ -3050,5 +3050,5 @@ class dl:
|
||||
|
||||
cache_key = (service, profile, cdm_name)
|
||||
if cache_key not in cdm_cache:
|
||||
cdm_cache[cache_key] = load_cdm(cdm_name, service_name=service, vaults=self.vaults)
|
||||
cdm_cache[cache_key] = load_cdm(cdm_name, service_name=service)
|
||||
return cdm_cache[cache_key]
|
||||
|
||||
@@ -8,7 +8,6 @@ from requests import Session
|
||||
|
||||
from unshackle.core import __version__
|
||||
from unshackle.core.cdm.http_cdm import HttpCdm, HttpCdmExceptions, b64_or_utf8
|
||||
from unshackle.core.vaults import Vaults
|
||||
|
||||
CustomRemoteCDMExceptions = HttpCdmExceptions
|
||||
|
||||
@@ -30,7 +29,6 @@ class CustomRemoteCDM(HttpCdm):
|
||||
- Transform engine (base64, hex, JSON, custom content key formats)
|
||||
- Condition evaluation (response type detection, success validation)
|
||||
- Compatible with both Widevine and PlayReady DRM schemes
|
||||
- Vault integration for intelligent content key caching
|
||||
|
||||
Configuration Philosophy:
|
||||
- 90% of new CDM providers: YAML config only
|
||||
@@ -54,13 +52,11 @@ class CustomRemoteCDM(HttpCdm):
|
||||
self,
|
||||
host: str,
|
||||
service_name: str | None = None,
|
||||
vaults: Vaults | None = None,
|
||||
device: dict[str, Any] | None = None,
|
||||
auth: dict[str, Any] | None = None,
|
||||
endpoints: dict[str, Any] | None = None,
|
||||
request_mapping: dict[str, Any] | None = None,
|
||||
response_mapping: dict[str, Any] | None = None,
|
||||
caching: dict[str, Any] | None = None,
|
||||
legacy: dict[str, Any] | None = None,
|
||||
timeout: int = 30,
|
||||
**kwargs: Any,
|
||||
@@ -70,14 +66,12 @@ class CustomRemoteCDM(HttpCdm):
|
||||
|
||||
Args:
|
||||
host: Base URL for the CDM API
|
||||
service_name: Service tag for content key caching and vault operations
|
||||
vaults: Vaults instance for local content key caching
|
||||
service_name: Service tag that each challenge request sends to the API
|
||||
device: Device configuration (name, type, system_id, security_level)
|
||||
auth: Authentication configuration (type, credentials, headers)
|
||||
endpoints: Endpoint configuration (paths, methods, timeouts)
|
||||
request_mapping: Request transformation rules (param names, static params, transforms)
|
||||
response_mapping: Response parsing rules (field locations, type detection, success conditions)
|
||||
caching: Caching configuration (enabled, use_vaults, and the other caching keys)
|
||||
legacy: Legacy mode configuration
|
||||
timeout: Default request timeout in seconds
|
||||
**kwargs: Additional configuration options for future extensibility
|
||||
@@ -90,7 +84,6 @@ class CustomRemoteCDM(HttpCdm):
|
||||
device.get("name", "ChromeCDM"),
|
||||
self.device_type_str,
|
||||
service_name,
|
||||
vaults,
|
||||
{"User-Agent": f"unshackle-custom-cdm/{__version__}", **self.auth_config.get("custom_headers", {})},
|
||||
)
|
||||
self.timeout = timeout
|
||||
@@ -135,8 +128,6 @@ class CustomRemoteCDM(HttpCdm):
|
||||
|
||||
self.response_mapping = response_mapping or {}
|
||||
|
||||
caching = caching or {}
|
||||
self.use_vaults = caching.get("use_vaults", True) and self.vaults is not None
|
||||
self.apply_authentication(self._http_session)
|
||||
|
||||
def get_nested_field(self, data: dict[str, Any], field_path: str, default: Any = None) -> Any:
|
||||
|
||||
@@ -7,7 +7,6 @@ import requests
|
||||
|
||||
from unshackle.core import __version__
|
||||
from unshackle.core.cdm.http_cdm import HttpCdm, HttpCdmExceptions
|
||||
from unshackle.core.vaults import Vaults
|
||||
|
||||
DecryptLabsRemoteCDMExceptions = HttpCdmExceptions
|
||||
|
||||
@@ -24,7 +23,6 @@ class DecryptLabsRemoteCDM(HttpCdm):
|
||||
host: str = "https://keyxtractor.decryptlabs.com",
|
||||
device_name: str = "ChromeCDM",
|
||||
service_name: str | None = None,
|
||||
vaults: Vaults | None = None,
|
||||
device_type: str | None = None,
|
||||
system_id: int | None = None,
|
||||
security_level: int | None = None,
|
||||
@@ -37,8 +35,7 @@ class DecryptLabsRemoteCDM(HttpCdm):
|
||||
secret: Decrypt Labs API key (matches config format)
|
||||
host: Decrypt Labs API host URL (matches config format)
|
||||
device_name: DRM system device name. Widevine takes ChromeCDM, L1, L2 or L3, and PlayReady takes SL2 or SL3
|
||||
service_name: Service tag for content key caching and vault operations
|
||||
vaults: Vaults instance for local content key caching
|
||||
service_name: Service tag that each challenge request sends to the API
|
||||
device_type: Device type (CHROME, ANDROID, PLAYREADY) - for compatibility
|
||||
system_id: System ID - for compatibility
|
||||
security_level: Security level - for compatibility
|
||||
@@ -50,7 +47,6 @@ class DecryptLabsRemoteCDM(HttpCdm):
|
||||
device_name,
|
||||
device_type,
|
||||
service_name,
|
||||
vaults,
|
||||
{"decrypt-labs-api-key": secret, "User-Agent": f"unshackle-decrypt-labs-cdm/{__version__}"},
|
||||
)
|
||||
if self._is_playready:
|
||||
@@ -103,7 +99,7 @@ class DecryptLabsRemoteCDM(HttpCdm):
|
||||
if data.get("message") == "success" and "challenge" in data:
|
||||
return self._keep_challenge(session, base64.b64decode(data["challenge"]), data["session_id"])
|
||||
|
||||
session["keys"] = cached_keys + session.get("vault_keys", [])
|
||||
session["keys"] = cached_keys
|
||||
return b""
|
||||
|
||||
if message_type == "license-request" or "challenge" in data:
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
"""The shared part of the CDMs that drive a device behind an HTTP API.
|
||||
|
||||
``HttpCdm`` keeps the CDM sessions, the PSSH and required KIDs of each CDM session, the content keys from
|
||||
the vaults and from the API cache, and the merge of those content keys with the licence keys. An adapter sends
|
||||
its own API's requests in ``_request_challenge`` and ``_request_keys``.
|
||||
the API cache, and the merge of those content keys with the licence keys. An adapter sends its own API's
|
||||
requests in ``_request_challenge`` and ``_request_keys``. The key vaults are not read or written here:
|
||||
content-key resolution does that.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -11,7 +12,7 @@ import base64
|
||||
import secrets
|
||||
from abc import ABC, abstractmethod
|
||||
from collections.abc import Sequence
|
||||
from typing import TYPE_CHECKING, Any
|
||||
from typing import Any
|
||||
from uuid import UUID
|
||||
|
||||
from pyplayready.system.wrmheader import WRMHeader
|
||||
@@ -21,10 +22,6 @@ from pywidevine.key import Key
|
||||
from requests import RequestException, Session
|
||||
|
||||
from unshackle.core.cdm.loader import system_of
|
||||
from unshackle.core.vault import is_null_key
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from unshackle.core.vaults import Vaults
|
||||
|
||||
|
||||
def kid_uuid(kid: str | UUID) -> UUID:
|
||||
@@ -87,7 +84,7 @@ class HttpCdm(ABC):
|
||||
"""A Widevine or PlayReady CDM whose device sits behind an HTTP API.
|
||||
|
||||
The DRM classes give each CDM session its PSSH (``set_pssh_b64``) and the KIDs they need
|
||||
(``set_required_kids``). A challenge is empty when the vaults or the API cache already hold
|
||||
(``set_required_kids``). A challenge is empty when the API cache already holds
|
||||
every required key, and ``has_cached_keys`` then says so.
|
||||
"""
|
||||
|
||||
@@ -103,14 +100,11 @@ class HttpCdm(ABC):
|
||||
device_name: str,
|
||||
device_type: str | None,
|
||||
service_name: str | None,
|
||||
vaults: Vaults | None,
|
||||
headers: dict[str, str],
|
||||
) -> None:
|
||||
self.host = host.rstrip("/")
|
||||
self.device_name = device_name
|
||||
self.service_name = service_name or ""
|
||||
self.vaults = vaults
|
||||
self.use_vaults = True
|
||||
self._is_playready = system_of(device_type, device_name) == "playready"
|
||||
if device_type:
|
||||
self.device_type = self.get_device_type_enum(device_type)
|
||||
@@ -137,7 +131,7 @@ class HttpCdm(ABC):
|
||||
self._session(session_id)["pssh_b64"] = pssh_b64
|
||||
|
||||
def set_required_kids(self, kids: Sequence[str | UUID], session_id: bytes) -> None:
|
||||
"""Store the KIDs a CDM session needs, so that content keys from the vaults or the API cache can skip the licence."""
|
||||
"""Store the KIDs a CDM session needs, so that content keys from the API cache can skip the licence."""
|
||||
self._session(session_id)["required_kids"] = [kid_hex(kid) for kid in kids]
|
||||
|
||||
def generate_session_id(self) -> bytes:
|
||||
@@ -238,15 +232,12 @@ class HttpCdm(ABC):
|
||||
def get_license_challenge(
|
||||
self, session_id: bytes, pssh_or_wrm: Any, license_type: str = "STREAMING", privacy_mode: bool = True
|
||||
) -> bytes:
|
||||
"""Make a licence challenge, or return empty bytes when the vaults or the API cache hold every required key.
|
||||
"""Make a licence challenge, or return empty bytes when the API cache holds every required key.
|
||||
|
||||
Raises InvalidSession for an unknown ID, and ``requests.RequestException`` when the API fails.
|
||||
"""
|
||||
session = self._session(session_id)
|
||||
session["init_data"] = self.get_init_data_from_pssh(pssh_or_wrm, session.get("pssh_b64"))
|
||||
required = session.get("required_kids")
|
||||
if self._keys_from_vaults(session, required):
|
||||
return b""
|
||||
body: dict[str, Any] = {"scheme": self.device_name, "init_data": session["init_data"]}
|
||||
if self.service_name:
|
||||
body["service"] = self.service_name
|
||||
@@ -254,38 +245,17 @@ class HttpCdm(ABC):
|
||||
body["service_certificate"] = base64.b64encode(session["service_certificate"]).decode("utf-8")
|
||||
return self._request_challenge(session, body, license_type, privacy_mode)
|
||||
|
||||
def _keys_from_vaults(self, session: dict[str, Any], required: list[str] | None) -> bool:
|
||||
"""Look up the required KIDs in the vaults; True when they hold every one."""
|
||||
if not (self.use_vaults and self.vaults and required):
|
||||
return False
|
||||
vault_keys = []
|
||||
for kid in required:
|
||||
try:
|
||||
key, _ = self.vaults.get_key(kid_uuid(kid))
|
||||
except (ValueError, TypeError):
|
||||
continue
|
||||
if not is_null_key(key):
|
||||
vault_keys.append({"kid": kid, "key": key, "type": "CONTENT"})
|
||||
if not vault_keys:
|
||||
return False
|
||||
if set(required) <= {k["kid"] for k in vault_keys}:
|
||||
session["keys"] = vault_keys
|
||||
return True
|
||||
session["vault_keys"] = vault_keys
|
||||
return False
|
||||
|
||||
def _take_cached_keys(self, session: dict[str, Any], cached_keys: list[dict[str, Any]]) -> bool:
|
||||
"""Keep the keys the API cache returned; True when they and the vault keys cover every required KID.
|
||||
"""Keep the keys the API cache returned; True when they cover every required KID.
|
||||
|
||||
Otherwise the cached keys wait in the CDM session for ``parse_license`` to merge with the licence keys.
|
||||
"""
|
||||
required = session.get("required_kids")
|
||||
available = [*cached_keys, *session.get("vault_keys", [])]
|
||||
have = {kid_hex(k["kid"]) for k in available}
|
||||
have = {kid_hex(k["kid"]) for k in cached_keys}
|
||||
if required and set(required) - have:
|
||||
session["cached_keys"] = cached_keys
|
||||
return False
|
||||
session["keys"] = available
|
||||
session["keys"] = cached_keys
|
||||
return True
|
||||
|
||||
def _keep_challenge(self, session: dict[str, Any], challenge: bytes, remote_session_id: Any) -> bytes:
|
||||
@@ -318,9 +288,9 @@ class HttpCdm(ABC):
|
||||
"""Send the licence to the API and return the keys it holds; the adapter's wire form."""
|
||||
|
||||
def parse_license(self, session_id: bytes, license_message: bytes | str) -> None:
|
||||
"""Have the API read a licence, then merge its keys with the vault and cached keys of the CDM session.
|
||||
"""Have the API read a licence, then merge its keys with the cached keys of the CDM session.
|
||||
|
||||
A content key from the vaults or the API cache wins over a licence key with the same KID. A CDM session
|
||||
A content key from the API cache wins over a licence key with the same KID. A CDM session
|
||||
that already holds its final keys and has no cached keys left to merge makes this a no-op.
|
||||
"""
|
||||
session = self._session(session_id)
|
||||
@@ -348,7 +318,7 @@ class HttpCdm(ABC):
|
||||
},
|
||||
)
|
||||
|
||||
all_keys = [*session.get("vault_keys", []), *(session.get("cached_keys") or [])]
|
||||
all_keys = list(session.get("cached_keys") or [])
|
||||
have = {kid_hex(k["kid"]) for k in all_keys}
|
||||
for key in license_keys:
|
||||
kid = kid_hex(key["kid"])
|
||||
@@ -358,18 +328,6 @@ class HttpCdm(ABC):
|
||||
|
||||
session["keys"] = all_keys
|
||||
session.pop("cached_keys", None)
|
||||
session.pop("vault_keys", None)
|
||||
|
||||
if self.use_vaults and self.vaults and all_keys:
|
||||
key_dict: dict[UUID | str, str] = {}
|
||||
for key in all_keys:
|
||||
if key["type"] == "CONTENT":
|
||||
try:
|
||||
key_dict[kid_uuid(key["kid"])] = key["key"]
|
||||
except (ValueError, TypeError):
|
||||
continue
|
||||
if key_dict:
|
||||
self.vaults.add_keys(key_dict)
|
||||
|
||||
def get_keys(self, session_id: bytes, type_: str | None = None) -> list[Key]:
|
||||
"""The keys of a CDM session; only the keys of type ``type_`` when it is set."""
|
||||
|
||||
@@ -96,7 +96,6 @@ def load_cdm(
|
||||
cdm_name: str,
|
||||
*,
|
||||
service_name: str = "",
|
||||
vaults: Any | None = None,
|
||||
) -> Any:
|
||||
"""Build the CDM a device name names: a remote CDM for a ``remote_cdm`` entry, else the local device.
|
||||
|
||||
@@ -106,11 +105,11 @@ def load_cdm(
|
||||
if device is None:
|
||||
raise ValueError(f"{cdm_name} does not exist or is not a file")
|
||||
if isinstance(device.source, dict):
|
||||
return load_remote_cdm(cdm_name, device.source, device.system, service_name, vaults)
|
||||
return load_remote_cdm(cdm_name, device.source, device.system, service_name)
|
||||
return load_local_cdm(cdm_name, device.system, device.source)
|
||||
|
||||
|
||||
def load_remote_cdm(name: str, entry: dict[str, Any], system: str, service_name: str, vaults: Any | None) -> Any:
|
||||
def load_remote_cdm(name: str, entry: dict[str, Any], system: str, service_name: str) -> Any:
|
||||
"""Build a remote CDM from its ``remote_cdm`` entry."""
|
||||
from unshackle.core.config import config
|
||||
|
||||
@@ -128,12 +127,12 @@ def load_remote_cdm(name: str, entry: dict[str, Any], system: str, service_name:
|
||||
raise ValueError(
|
||||
f"No secret provided for DecryptLabs CDM '{name}' and no global decrypt_labs_api_key configured"
|
||||
)
|
||||
return DecryptLabsRemoteCDM(service_name=service_name, vaults=vaults, **cdm_api)
|
||||
return DecryptLabsRemoteCDM(service_name=service_name, **cdm_api)
|
||||
|
||||
if cdm_type == "custom_api":
|
||||
from unshackle.core.cdm.custom_remote_cdm import CustomRemoteCDM
|
||||
|
||||
return CustomRemoteCDM(service_name=service_name, vaults=vaults, **cdm_api)
|
||||
return CustomRemoteCDM(service_name=service_name, **cdm_api)
|
||||
|
||||
from unshackle.core.cdm.unprobed_remote_cdm import UnprobedPlayReadyRemoteCdm, UnprobedWidevineRemoteCdm
|
||||
|
||||
|
||||
@@ -254,7 +254,8 @@ class PlayReady(CencDrm):
|
||||
if isinstance(cdm, HttpCdm):
|
||||
if pssh_b64:
|
||||
cdm.set_pssh_b64(pssh_b64, session_id=session_id)
|
||||
cdm.set_required_kids(required_kids, session_id=session_id)
|
||||
missing = [kid for kid in required_kids if kid not in self.content_keys] or required_kids
|
||||
cdm.set_required_kids(missing, session_id=session_id)
|
||||
|
||||
challenge = cdm.get_license_challenge(session_id, header)
|
||||
|
||||
|
||||
@@ -107,7 +107,8 @@ class Widevine(CencDrm):
|
||||
cdm.set_service_certificate(session_id, cert)
|
||||
|
||||
if isinstance(cdm, HttpCdm):
|
||||
cdm.set_required_kids(self.kids, session_id=session_id)
|
||||
missing = [k for k in self.kids if k not in self.content_keys]
|
||||
cdm.set_required_kids(missing, session_id=session_id)
|
||||
|
||||
challenge = cdm.get_license_challenge(session_id, self.pssh)
|
||||
|
||||
@@ -143,20 +144,21 @@ class Widevine(CencDrm):
|
||||
response_size=len(license_res) if license_res else 0,
|
||||
)
|
||||
|
||||
self.content_keys = {key.kid: key.key.hex() for key in cdm.get_keys(session_id, "CONTENT")}
|
||||
keys = {key.kid: key.key.hex() for key in cdm.get_keys(session_id, "CONTENT")}
|
||||
self.content_keys.update(keys)
|
||||
|
||||
if self.content_keys:
|
||||
if keys:
|
||||
log_event(
|
||||
"drm_content_keys",
|
||||
level="INFO",
|
||||
message=f"Recovered {len(self.content_keys)} Widevine content key(s)",
|
||||
message=f"Recovered {len(keys)} Widevine content key(s)",
|
||||
drm_type="Widevine",
|
||||
kid=kid.hex,
|
||||
key_count=len(self.content_keys),
|
||||
keys=[{"kid": k.hex, "key": v} for k, v in self.content_keys.items()],
|
||||
key_count=len(keys),
|
||||
keys=[{"kid": k.hex, "key": v} for k, v in keys.items()],
|
||||
)
|
||||
|
||||
if not self.content_keys:
|
||||
if not keys:
|
||||
raise Widevine.Exceptions.EmptyLicense("No Content Keys were within the License")
|
||||
|
||||
if kid not in self.content_keys:
|
||||
|
||||
Reference in New Issue
Block a user