forked from kenzuya/unshackle
refactor(api): move server key resolution into server_keys and name the tracks reply's DRM system from the licence order
This commit is contained in:
+41
-665
@@ -17,14 +17,14 @@ from dataclasses import dataclass, field
|
||||
from functools import partial
|
||||
from http.cookiejar import CookieJar
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, Optional
|
||||
from typing import Any, Optional
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
import click
|
||||
from aiohttp import web
|
||||
|
||||
from unshackle.core import login
|
||||
from unshackle.core.api import licence_cap
|
||||
from unshackle.core.api import licence_cap, server_keys
|
||||
from unshackle.core.api.compression import InflateLimitError, safe_inflate
|
||||
from unshackle.core.api.errors import APIError, categorize_exception, handle_api_exception
|
||||
from unshackle.core.api.input_bridge import InputBridge, NoUserBridge
|
||||
@@ -44,12 +44,12 @@ from unshackle.core.api.session_store import SessionEntry, SessionStore
|
||||
from unshackle.core.binaries import binary_version
|
||||
from unshackle.core.cacher import Cacher
|
||||
from unshackle.core.cdm.choice import choose_cdm, drm_system
|
||||
from unshackle.core.cdm.detect import cdm_system, cdm_type_stub
|
||||
from unshackle.core.cdm.detect import cdm_type_stub
|
||||
from unshackle.core.cdm.loader import device_system
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.dl_options import DEFAULT_DOWNLOAD_PARAMS
|
||||
from unshackle.core.drm import WHOLE_FILE_DRM, cbcs, is_null_key, real_kids, whole_file_cipher
|
||||
from unshackle.core.drm.discovery import drm_from_init_segment, ensure_track_drm, fetch_init_segment, track_pssh
|
||||
from unshackle.core.drm import cbcs, real_kids, whole_file_cipher
|
||||
from unshackle.core.drm.discovery import ensure_track_drm
|
||||
from unshackle.core.launch import LaunchKeys, served_context
|
||||
from unshackle.core.manifests.snapshot import capture
|
||||
from unshackle.core.proxies.resolve import REGION_QUERY, initialize_proxy_providers, is_loopback, resolve_proxy
|
||||
@@ -104,9 +104,6 @@ from unshackle.core.wire import (
|
||||
stamp_service_flags,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from unshackle.core.vaults import Vaults
|
||||
|
||||
log = logging.getLogger("api")
|
||||
|
||||
|
||||
@@ -986,25 +983,6 @@ def session_licensing(policy: KeyPolicy, service: str, data: dict[str, Any]) ->
|
||||
return LicensingMode(Licensor.NO_DEVICE, max_height)
|
||||
|
||||
|
||||
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.
|
||||
|
||||
Only a live licence spends the server's device, so a vault hit always passes.
|
||||
"""
|
||||
licensing = session.licensing
|
||||
if licensing.server_device:
|
||||
return APIError(
|
||||
APIErrorCode.SERVER_CDM_CAPPED,
|
||||
"This session runs on the server's device, so its keys come only from a vault.",
|
||||
details={"reason": "server_device"},
|
||||
)
|
||||
if not licensing.server_cdm:
|
||||
return licence_cap.capped_error(
|
||||
"This session licenses with your own device, so the server CDM makes no licence for it."
|
||||
)
|
||||
return licence_cap.track_refusal(licensing.max_height, track)
|
||||
|
||||
|
||||
_account_counters: dict[str, int] = {}
|
||||
# the event loop holds only weak references to tasks, so a running login task needs a strong one
|
||||
_auth_tasks: set["asyncio.Task[None]"] = set()
|
||||
@@ -1333,14 +1311,6 @@ def listed_titles(titles: Any) -> list[Any]:
|
||||
return list(titles) if hasattr(titles, "__iter__") and not isinstance(titles, str) else [titles]
|
||||
|
||||
|
||||
def drm_preference_name(track: Any) -> str | None:
|
||||
"""The track's drm_preference as a full DRM system name, "widevine" or "playready"; None when unset."""
|
||||
preference = getattr(track, "drm_preference", None)
|
||||
if not preference:
|
||||
return None
|
||||
return {"wv": "widevine", "pr": "playready"}.get(preference, preference)
|
||||
|
||||
|
||||
async def search_handler(data: dict[str, Any], request: web.Request | None = None) -> web.Response:
|
||||
"""Answer the request to find titles."""
|
||||
service_tag = data.get("service")
|
||||
@@ -3151,36 +3121,15 @@ async def session_tracks_handler(
|
||||
session_headers, session_cookies = client_session_auth(session)
|
||||
|
||||
policy = session_policy(session, request)
|
||||
app_config = policy.cdm_config()
|
||||
has_wv = bool(policy.devices("devices"))
|
||||
has_pr = bool(policy.devices("playready_devices"))
|
||||
|
||||
service_tag = session.service_tag
|
||||
config_cdm_type = detect_cdm_type_for_service(service_tag, app_config)
|
||||
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)
|
||||
config_cdm_type = cdm_system(loaded) or "widevine"
|
||||
|
||||
track_has_wv = any(
|
||||
d.__class__.__name__ == "Widevine" for t in list(tracks.videos) + list(tracks.audio) if t.drm for d in t.drm
|
||||
candidates = await asyncio.to_thread(
|
||||
server_keys.server_drm_candidates,
|
||||
session.service_tag,
|
||||
policy,
|
||||
"",
|
||||
[*tracks.videos, *tracks.audio],
|
||||
server_keys.loaded_cdm_system(session),
|
||||
)
|
||||
track_has_pr = any(
|
||||
d.__class__.__name__ == "PlayReady"
|
||||
for t in list(tracks.videos) + list(tracks.audio)
|
||||
if t.drm
|
||||
for d in t.drm
|
||||
)
|
||||
|
||||
if config_cdm_type:
|
||||
server_cdm_type = config_cdm_type
|
||||
elif track_has_pr and has_pr:
|
||||
server_cdm_type = "playready"
|
||||
elif track_has_wv and has_wv:
|
||||
server_cdm_type = "widevine"
|
||||
elif has_wv:
|
||||
server_cdm_type = "widevine"
|
||||
else:
|
||||
server_cdm_type = "playready"
|
||||
server_cdm_type = candidates[0] if candidates else "playready"
|
||||
|
||||
def serialize() -> dict[str, list]:
|
||||
"""The track and attachment lists, off the event loop: an attachment can be a 20 MB file."""
|
||||
@@ -3319,21 +3268,6 @@ def resolve_server_cdm(service: str, profile: str | None, cdm_type: str | None,
|
||||
return None
|
||||
|
||||
|
||||
def detect_cdm_type_for_service(service: str, app_config: Any) -> str | None:
|
||||
"""The DRM system config.cdm settles for a service; None when the mapping leaves it open.
|
||||
|
||||
A mapping that names one system gets that system. A device name gets the type of the
|
||||
device ``resolve_device_name`` returns for it, so the routes plan with the device they
|
||||
load. A mapping that names a device for both systems settles nothing.
|
||||
"""
|
||||
choice = choose_cdm(app_config.cdm, service, view="licence")
|
||||
if choice.systems:
|
||||
return choice.system
|
||||
if choice.name:
|
||||
return device_system(choice.name, app_config)
|
||||
return None
|
||||
|
||||
|
||||
def require_authenticated(session: SessionEntry) -> None:
|
||||
"""Raise if the remote session has not finished authenticating."""
|
||||
status = session.auth_status
|
||||
@@ -3604,391 +3538,6 @@ def resolve_handler_proxy(
|
||||
return proxy_param, proxy_providers
|
||||
|
||||
|
||||
def find_title_for_track(track_id: str, session: Any) -> Any:
|
||||
"""Find the title object that owns a given track."""
|
||||
for t_id, tracks_dict in session.tracks_by_title.items():
|
||||
if track_id in tracks_dict:
|
||||
return session.title_map.get(t_id)
|
||||
if session.title_map:
|
||||
return session.title_map.get(session.current_title_id) or next(iter(session.title_map.values()))
|
||||
return None
|
||||
|
||||
|
||||
def resolve_device_name(policy: KeyPolicy, drm_type: str, service_tag: str = "") -> str:
|
||||
"""Get the CDM device name, checking the service's cdm mapping first.
|
||||
|
||||
Resolution order:
|
||||
1. the key's own ``cdm`` entry for the service, else ``config.cdm[service_tag]``
|
||||
2. the key's ``devices`` / ``playready_devices``
|
||||
"""
|
||||
cdm_name = choose_cdm(policy.cdm_config().cdm, service_tag, drm=drm_type, view="licence").name
|
||||
if cdm_name:
|
||||
return cdm_name
|
||||
|
||||
if drm_type == "playready":
|
||||
device_name = next(iter(policy.devices("playready_devices")), None)
|
||||
if not device_name:
|
||||
raise APIError(APIErrorCode.INVALID_INPUT, "No PlayReady device configured for this API key")
|
||||
else:
|
||||
device_name = next(iter(policy.devices("devices")), None)
|
||||
if not device_name:
|
||||
raise APIError(APIErrorCode.INVALID_INPUT, "No Widevine device configured for this API key")
|
||||
return device_name
|
||||
|
||||
|
||||
def vault_candidates(client_drm_type: str) -> list[str]:
|
||||
"""Both DRM systems, the client's first: a vault lookup needs only the KIDs, whatever device made the manifest."""
|
||||
first = client_drm_type if client_drm_type in ("widevine", "playready") else "widevine"
|
||||
return [first, "playready" if first == "widevine" else "widevine"]
|
||||
|
||||
|
||||
def server_drm_candidates(
|
||||
service_tag: str,
|
||||
policy: KeyPolicy,
|
||||
client_drm_type: str,
|
||||
track: Any,
|
||||
warn: Callable[[str], None] = log.warning,
|
||||
) -> list[str]:
|
||||
"""The DRM systems the server can license a track with, in the order to try them.
|
||||
|
||||
The server's config.cdm mapping goes first; with no mapping, the client's choice goes
|
||||
first. A system stays only when the device the server would load for it is of that
|
||||
system, so the route never plans a licence that fails on the wrong device type. The
|
||||
track's own drm_preference moves its system to the front when the server has it.
|
||||
"""
|
||||
app_config = policy.cdm_config()
|
||||
server_type = detect_cdm_type_for_service(service_tag, app_config)
|
||||
first = server_type or (client_drm_type if client_drm_type in ("widevine", "playready") else "widevine")
|
||||
candidates: list[str] = []
|
||||
for drm_type in (first, *(system for system in ("widevine", "playready") if system != first)):
|
||||
try:
|
||||
device_name = resolve_device_name(policy, drm_type, service_tag)
|
||||
except APIError:
|
||||
continue
|
||||
if device_system(device_name, app_config) in (None, drm_type):
|
||||
candidates.append(drm_type)
|
||||
|
||||
preferred = drm_preference_name(track)
|
||||
if preferred:
|
||||
if preferred in candidates:
|
||||
candidates.remove(preferred)
|
||||
candidates.insert(0, preferred)
|
||||
else:
|
||||
warn(
|
||||
f"Track {track_log_label(track)} wants {preferred} DRM "
|
||||
"but the server has no device for it, using the configured DRM instead"
|
||||
)
|
||||
return candidates
|
||||
|
||||
|
||||
def pick_server_pssh(track: Any, candidates: list[str]) -> tuple[str, str] | None:
|
||||
"""`(drm_type, pssh)` for the first candidate the track carries a header for; None when it has none.
|
||||
|
||||
A track with only a PlayReady header still licenses under the Widevine device: the
|
||||
Widevine DRM class converts the PlayReady PSSH on construction.
|
||||
"""
|
||||
for candidate in candidates:
|
||||
pssh_str = track_pssh(track, candidate)
|
||||
if not pssh_str and candidate == "widevine":
|
||||
pssh_str = track_pssh(track, "playready")
|
||||
if pssh_str:
|
||||
log.info(
|
||||
f"Track {track_log_label(track)} has only a PlayReady PSSH, licensing it with the Widevine device"
|
||||
)
|
||||
if pssh_str:
|
||||
return candidate, pssh_str
|
||||
return None
|
||||
|
||||
|
||||
def load_server_vaults(service_name: str) -> "Vaults":
|
||||
"""Load server vaults from config.key_vaults; a vault that fails to load is left out."""
|
||||
from unshackle.core.services import Services
|
||||
from unshackle.core.vaults import load_config_vaults
|
||||
|
||||
return load_config_vaults(Services.get_vault_tag(service_name))[0]
|
||||
|
||||
|
||||
def once(shared: dict[Any, Any], key: Any, make: Callable[[], Any]) -> Any:
|
||||
"""``make()`` the first time ``key`` is asked for in ``shared``, the stored value after that."""
|
||||
if key not in shared:
|
||||
shared[key] = make()
|
||||
return shared[key]
|
||||
|
||||
|
||||
def check_vaults(
|
||||
kids: list, service_name: str, shared: dict[str, Any] | None = None, track_kid: uuid.UUID | None = None
|
||||
) -> tuple[dict[str, str], dict[str, str]] | None:
|
||||
"""Examine the server vaults for existing content keys that match the KIDs.
|
||||
|
||||
Returns `(KID:KEY, KID:vault name)` when every KID is found, or with ``track_kid`` when that
|
||||
KID is found, with the other KIDs the vaults hold; None otherwise. The vault name travels to
|
||||
the client, which is the only side that can prove the content key decrypts.
|
||||
"""
|
||||
try:
|
||||
vaults = once({} if shared is None else shared, "vaults", lambda: load_server_vaults(service_name))
|
||||
if not vaults:
|
||||
return None
|
||||
keys: dict[str, str] = {}
|
||||
sources: dict[str, str] = {}
|
||||
wanted = [kid if isinstance(kid, uuid.UUID) else uuid.UUID(hex=str(kid)) for kid in kids]
|
||||
if track_kid:
|
||||
wanted = [track_kid, *(kid for kid in wanted if kid != track_kid)]
|
||||
for kid_uuid in wanted:
|
||||
content_key, vault_used = vaults.get_key(kid_uuid)
|
||||
if content_key:
|
||||
keys[kid_uuid.hex] = content_key
|
||||
sources[kid_uuid.hex] = vault_used.name if vault_used else "unknown"
|
||||
elif track_kid in (None, kid_uuid):
|
||||
return None
|
||||
if keys:
|
||||
log.info(f"Vault hit: {len(keys)} key(s) from server vaults, skipping CDM")
|
||||
return keys, sources
|
||||
# vault lookup is a best-effort shortcut before the CDM; any failure falls through to licensing
|
||||
except Exception as e:
|
||||
log.debug(f"Server vault lookup failed: {e!r}")
|
||||
return None
|
||||
|
||||
|
||||
CACHED_PAIRS: set[tuple[str, str, str]] = set()
|
||||
|
||||
|
||||
def cache_to_vaults(keys: dict[str, str], service_name: str, shared: dict[str, Any] | None = None) -> None:
|
||||
"""Cache the content keys of a CDM licence to the server vaults.
|
||||
|
||||
A PlayReady licence always runs, and a Widevine licence runs when one PSSH KID has no content
|
||||
key in a vault, so the same content keys come back on every request for a title. This process
|
||||
does not send a pair again after every vault accepted it. A pair a client reported as bad
|
||||
leaves that set, and is unflagged when the CDM returns it.
|
||||
"""
|
||||
from uuid import UUID
|
||||
|
||||
try:
|
||||
new = {kid: key for kid, key in keys.items() if (service_name, kid, key) not in CACHED_PAIRS}
|
||||
if not new:
|
||||
return
|
||||
vaults = once({} if shared is None else shared, "vaults", lambda: load_server_vaults(service_name))
|
||||
if not vaults:
|
||||
return
|
||||
|
||||
key_map = {UUID(hex=kid): key for kid, key in new.items()}
|
||||
for kid in vaults.clear_licensed_flags(key_map):
|
||||
log.info(f"Unflagged {kid.hex}:{key_map[kid]}, the CDM returned it")
|
||||
cached = vaults.add_keys(key_map)
|
||||
if vaults.stored_everywhere(cached):
|
||||
CACHED_PAIRS.update((service_name, kid, key) for kid, key in new.items())
|
||||
if cached:
|
||||
log.info(f"Cached {len(key_map)} key(s) to {cached}/{len(vaults)} server vault(s)")
|
||||
except (Exception, SystemExit) as e:
|
||||
log.warning(f"Failed to cache keys to vaults: {e}")
|
||||
|
||||
|
||||
def track_injected_keys(track: Any, drm_class: str) -> dict[str, str]:
|
||||
"""`KID:KEY` pairs a service wrote onto the track's own DRM objects of `drm_class`.
|
||||
|
||||
Some services skip the CDM exchange: the licence callback fetches the keys itself,
|
||||
writes them into ``track.drm[0].content_keys`` and returns a value the CDM cannot
|
||||
parse. ``dl.py`` accepts that failed parse because the object it licensed holds the
|
||||
keys. The server licenses a rebuilt object, so it reads the track's objects instead.
|
||||
"""
|
||||
keys: dict[str, str] = {}
|
||||
for drm in getattr(track, "drm", None) or []:
|
||||
if drm.__class__.__name__ != drm_class:
|
||||
continue
|
||||
for kid, key in (getattr(drm, "content_keys", None) or {}).items():
|
||||
keys[kid.hex if hasattr(kid, "hex") else str(kid).replace("-", "")] = key
|
||||
return keys
|
||||
|
||||
|
||||
def license_with_track_fallback(drm: Any, track: Any, **kwargs: Any) -> dict[str, str]:
|
||||
"""Run `drm.get_content_keys`, merge in the keys the service put on the track itself, and drop the null keys."""
|
||||
try:
|
||||
drm.get_content_keys(**kwargs)
|
||||
except Exception:
|
||||
if not track_injected_keys(track, drm.__class__.__name__):
|
||||
raise
|
||||
keys = {
|
||||
**track_injected_keys(track, drm.__class__.__name__),
|
||||
**{kid.hex: key for kid, key in drm.content_keys.items()},
|
||||
}
|
||||
return {kid: key for kid, key in keys.items() if not is_null_key(key)}
|
||||
|
||||
|
||||
def client_track_kid(kid_hex: Any, track: Any) -> uuid.UUID | None:
|
||||
"""The KID a client asks the server CDM for, when the track's DRM names it; None for any other value."""
|
||||
if not isinstance(kid_hex, str):
|
||||
return None
|
||||
try:
|
||||
kid = uuid.UUID(hex=kid_hex)
|
||||
except ValueError:
|
||||
return None
|
||||
return kid if any(kid in (getattr(d, "kids", None) or []) for d in getattr(track, "drm", None) or []) else None
|
||||
|
||||
|
||||
def pssh_kids(pssh_b64: str, drm_type: str) -> set:
|
||||
"""The KIDs a base64 PSSH names, for either DRM system."""
|
||||
if drm_type == "playready":
|
||||
from pyplayready.system.pssh import PSSH as PlayReadyPSSH
|
||||
|
||||
from unshackle.core.drm import PlayReady
|
||||
|
||||
return set(PlayReady(pssh=PlayReadyPSSH(base64.b64decode(pssh_b64)), pssh_b64=pssh_b64).kids)
|
||||
from pywidevine.pssh import PSSH as WvPSSH
|
||||
|
||||
from unshackle.core.drm import Widevine
|
||||
|
||||
return set(Widevine(pssh=WvPSSH(pssh_b64)).kids)
|
||||
|
||||
|
||||
def require_track_pssh(track: Any, pssh_b64: str, drm_type: str) -> None:
|
||||
"""Reject a client PSSH that names a KID the track does not carry.
|
||||
|
||||
The server CDM path answers from the vault before any license exchange, so an
|
||||
unchecked PSSH would make the key vault answer with content keys for any title. The
|
||||
track's own PSSH passes as it is, so a header without KIDs still licenses.
|
||||
"""
|
||||
if pssh_b64 == track_pssh(track, drm_type):
|
||||
return
|
||||
try:
|
||||
client_kids = pssh_kids(pssh_b64, drm_type)
|
||||
except Exception:
|
||||
raise APIError(APIErrorCode.INVALID_INPUT, "The pssh parameter is not a valid PSSH box") from None
|
||||
track_kids = {kid for drm in (getattr(track, "drm", None) or []) for kid in (getattr(drm, "kids", None) or [])}
|
||||
if not client_kids or not track_kids or not client_kids <= track_kids:
|
||||
raise APIError(
|
||||
APIErrorCode.FORBIDDEN,
|
||||
"The pssh parameter does not belong to this track.",
|
||||
details={"track_id": str(getattr(track, "id", ""))},
|
||||
)
|
||||
|
||||
|
||||
def handle_single_server_cdm(
|
||||
service: Any,
|
||||
title: Any,
|
||||
track: Any,
|
||||
pssh_b64: str | None,
|
||||
drm_type: str,
|
||||
request: web.Request | None,
|
||||
sources: dict[str, str] | None = None,
|
||||
refusal: APIError | None = None,
|
||||
vault_only: bool = False,
|
||||
shared: dict[str, Any] | None = None,
|
||||
track_kid: uuid.UUID | None = None,
|
||||
policy: KeyPolicy | None = None,
|
||||
) -> dict[str, str]:
|
||||
"""Do the single-track server_cdm licensing with the DRM class get_content_keys() flow.
|
||||
|
||||
``sources`` is filled with the vault name for every returned content key a server vault
|
||||
supplied. A content key the CDM licensed gets no entry. A vault answers in place of the licence
|
||||
when it holds ``track_kid``, the KID the track is encrypted with, or else every KID of the header.
|
||||
PlayReady without ``track_kid`` always licenses, as its licence can carry keys its header does not name.
|
||||
It raises ``refusal`` before a live licence. With ``vault_only`` no server device is involved.
|
||||
``shared`` keeps the vaults and CDMs one ``license_response`` call built, for its next track.
|
||||
"""
|
||||
import base64
|
||||
|
||||
from unshackle.core.cdm import load_cdm
|
||||
from unshackle.core.cdm.detect import is_playready_cdm, is_widevine_cdm
|
||||
|
||||
ensure_track_drm(track, getattr(service, "session", None))
|
||||
shared = {} if shared is None else shared
|
||||
service_name = service.__class__.__name__
|
||||
|
||||
if not pssh_b64:
|
||||
pssh_b64 = track_pssh(track, drm_type)
|
||||
if not pssh_b64:
|
||||
raise APIError(APIErrorCode.INVALID_INPUT, "No PSSH available for server_cdm licensing")
|
||||
|
||||
def from_vaults(kids: Iterable[uuid.UUID]) -> dict[str, str] | None:
|
||||
"""The vault keys for ``kids`` (see ``check_vaults``), with their sources noted."""
|
||||
hit = check_vaults(list(kids), service_name, shared=shared, track_kid=track_kid)
|
||||
if hit and sources is not None:
|
||||
sources.update(hit[1])
|
||||
return hit[0] if hit else None
|
||||
|
||||
if vault_only:
|
||||
if vault_keys := from_vaults(pssh_kids(pssh_b64, drm_type)):
|
||||
return vault_keys
|
||||
raise refusal or APIError(APIErrorCode.NO_CONTENT, "The server vault holds no content key for this track")
|
||||
|
||||
if policy is None:
|
||||
policy = request_policy(request)
|
||||
|
||||
if drm_type == "playready":
|
||||
from pyplayready.system.pssh import PSSH as PlayReadyPSSH
|
||||
|
||||
from unshackle.core.drm import PlayReady
|
||||
|
||||
pr_pssh = PlayReadyPSSH(base64.b64decode(pssh_b64))
|
||||
siblings = [d for d in (getattr(track, "drm", None) or []) if isinstance(d, PlayReady)]
|
||||
manifest_kid = next((getattr(d, "kid", None) for d in siblings if getattr(d, "kid", None)), None)
|
||||
pr_drm = PlayReady(pssh=pr_pssh, pssh_b64=pssh_b64, kid=manifest_kid)
|
||||
if siblings:
|
||||
pr_drm.absorb(*siblings)
|
||||
|
||||
# Gate on the caller's CDM device first: no device, no keys from the vault or CDM.
|
||||
device_name = resolve_device_name(policy, drm_type, service_name)
|
||||
|
||||
if track_kid and (vault_keys := from_vaults(pr_drm.kids)):
|
||||
return vault_keys
|
||||
if refusal:
|
||||
raise refusal
|
||||
|
||||
cdm = once(shared, ("cdm", device_name), lambda: load_cdm(device_name, service_name=service_name))
|
||||
if not is_playready_cdm(cdm):
|
||||
raise APIError(APIErrorCode.INVALID_INPUT, f"CDM device '{device_name}' is not a PlayReady device")
|
||||
keys = license_with_track_fallback(
|
||||
pr_drm,
|
||||
track,
|
||||
cdm=cdm,
|
||||
certificate=lambda challenge, **_: None,
|
||||
licence=lambda **kw: service.get_playready_license(
|
||||
**declared_kwargs(service.get_playready_license, {**kw, "title": title, "track": track})
|
||||
),
|
||||
)
|
||||
elif drm_type == "widevine":
|
||||
from pywidevine.pssh import PSSH as WvPSSH
|
||||
|
||||
from unshackle.core.drm import Widevine
|
||||
|
||||
wv_pssh = WvPSSH(pssh_b64)
|
||||
wv_drm = Widevine(pssh=wv_pssh)
|
||||
|
||||
# Gate on the caller's CDM device first so a caller with no device cannot
|
||||
# harvest server-side keys from the vault fallback below.
|
||||
device_name = resolve_device_name(policy, drm_type, service_name)
|
||||
|
||||
if vault_keys := from_vaults(wv_drm.kids):
|
||||
return vault_keys
|
||||
if refusal:
|
||||
raise refusal
|
||||
|
||||
cdm = once(shared, ("cdm", device_name), lambda: load_cdm(device_name, service_name=service_name))
|
||||
if not is_widevine_cdm(cdm):
|
||||
raise APIError(APIErrorCode.INVALID_INPUT, f"CDM device '{device_name}' is not a Widevine device")
|
||||
keys = license_with_track_fallback(
|
||||
wv_drm,
|
||||
track,
|
||||
cdm=cdm,
|
||||
certificate=lambda challenge, **_: service.get_widevine_service_certificate(
|
||||
challenge=challenge, title=title, track=track
|
||||
),
|
||||
licence=lambda **kw: service.get_widevine_license(
|
||||
**declared_kwargs(service.get_widevine_license, {**kw, "title": title, "track": track})
|
||||
),
|
||||
)
|
||||
else:
|
||||
raise APIError(
|
||||
APIErrorCode.INVALID_PARAMETERS,
|
||||
f"Unsupported DRM type for server_cdm: {drm_type}",
|
||||
)
|
||||
|
||||
if not keys:
|
||||
raise APIError(APIErrorCode.NO_CONTENT, "Server CDM returned no content keys")
|
||||
|
||||
cache_to_vaults(keys, service_name, shared=shared)
|
||||
return keys
|
||||
|
||||
|
||||
def handle_proxy_license(
|
||||
service: Any,
|
||||
title: Any,
|
||||
@@ -4191,178 +3740,20 @@ def license_response(data: LicenseRequest, session: Any, session_id: str, reques
|
||||
)
|
||||
|
||||
if mode == "server_cdm" and track_ids:
|
||||
policy = session_policy(session, request)
|
||||
service = session.service_instance
|
||||
service_tag = session.service_tag
|
||||
|
||||
all_keys: dict[str, dict[str, str]] = {}
|
||||
vault_keys: list[str] = []
|
||||
clear_tracks: list[str] = []
|
||||
file_keys: dict[str, str] = {}
|
||||
drm_types: dict[str, str] = {}
|
||||
keys_by_pssh: dict[tuple, dict[str, str]] = {}
|
||||
shared: dict[str, Any] = {}
|
||||
sources_by_pssh: dict[tuple, dict[str, str]] = {}
|
||||
drm_type_by_pssh: dict[tuple, str] = {}
|
||||
actual_drm_type: str | None = None
|
||||
capped_tracks: dict[str, dict[str, Any]] = {}
|
||||
|
||||
def pssh_set(track: Any) -> tuple:
|
||||
"""Every PSSH and KID the track carries, as the rest of the cache key.
|
||||
|
||||
Two tracks can share their first PSSH and still need different licences,
|
||||
because the server licenses every header the track holds and asks for every
|
||||
KID the manifest named on it.
|
||||
"""
|
||||
drms = getattr(track, "drm", None) or []
|
||||
return (
|
||||
tuple(sorted(str(getattr(d, "pssh_b64", "") or "") for d in drms)),
|
||||
tuple(sorted(str(kid) for d in drms for kid in (getattr(d, "kids", None) or []))),
|
||||
)
|
||||
|
||||
def warn(message: str) -> None:
|
||||
"""Log on the server and copy into the remote session buffer the client drains.
|
||||
|
||||
The buffer takes only ``service.log``, so a licensing failure raised
|
||||
here would otherwise reach the client as a bare "no content keys".
|
||||
"""
|
||||
log.warning(message)
|
||||
if session.log_buffer:
|
||||
session.log_buffer.append(logging.WARNING, message)
|
||||
|
||||
def license_track(
|
||||
track: Any, title: Any, candidates: list, track_kid: uuid.UUID | None
|
||||
) -> tuple[dict[str, str], str | None, str | None]:
|
||||
"""`(keys, drm_type, pssh)` for the track's current DRM, licensing once per unique PSSH.
|
||||
|
||||
A cached vault answer that lacks ``track_kid`` is asked again for that KID. A track the server
|
||||
must not license live goes into ``capped_tracks`` with no keys, and its PSSH stays uncached,
|
||||
as a track under the cap can share it.
|
||||
"""
|
||||
picked = pick_server_pssh(track, candidates)
|
||||
if not picked:
|
||||
warn(f"No PSSH on track {track_log_label(track)} for {', '.join(candidates) or 'any CDM'}")
|
||||
return {}, None, None
|
||||
candidate, pssh_str = picked
|
||||
|
||||
cache_key = (pssh_str, pssh_set(track))
|
||||
cached = keys_by_pssh.get(cache_key)
|
||||
from_vault = bool(cached) and set(cached or {}) <= set(sources_by_pssh.get(cache_key, {}))
|
||||
if cached is None or (track_kid and track_kid.hex not in cached and from_vault):
|
||||
keys_by_pssh.setdefault(cache_key, {})
|
||||
sources_by_pssh.setdefault(cache_key, {})
|
||||
try:
|
||||
keys = handle_single_server_cdm(
|
||||
service,
|
||||
title,
|
||||
track,
|
||||
pssh_str,
|
||||
candidate,
|
||||
request,
|
||||
sources_by_pssh[cache_key],
|
||||
live_licence_refusal(session, track),
|
||||
vault_only=vault_only,
|
||||
shared=shared,
|
||||
track_kid=track_kid,
|
||||
policy=policy,
|
||||
)
|
||||
if keys:
|
||||
keys_by_pssh[cache_key] = {**keys_by_pssh[cache_key], **keys}
|
||||
drm_type_by_pssh[cache_key] = candidate
|
||||
except SystemExit:
|
||||
warn(f"Service exited while resolving keys for track {track_log_label(track)}, skipping")
|
||||
except Exception as e:
|
||||
if isinstance(e, APIError) and e.error_code is APIErrorCode.SERVER_CDM_CAPPED:
|
||||
del keys_by_pssh[cache_key], sources_by_pssh[cache_key]
|
||||
capped_tracks[str(track.id)] = e.details
|
||||
return {}, None, pssh_str
|
||||
warn(f"Failed to resolve keys for track {track_log_label(track)}: {redact_all(str(e))}")
|
||||
return keys_by_pssh[cache_key], drm_type_by_pssh.get(cache_key), pssh_str
|
||||
|
||||
for tid in track_ids:
|
||||
track = session.tracks.get(tid)
|
||||
if not track:
|
||||
continue
|
||||
|
||||
svc_session = getattr(service, "session", None)
|
||||
init_data = fetch_init_segment(track, svc_session)
|
||||
ensure_track_drm(track, svc_session, init_data)
|
||||
cipher = whole_file_cipher(track)
|
||||
if cipher is not None:
|
||||
if not vault_only:
|
||||
try:
|
||||
file_keys[tid] = cipher.content_key().hex()
|
||||
except (Exception, SystemExit) as e:
|
||||
warn(f"Failed to license track {track_log_label(track)}: {redact_all(str(e))}")
|
||||
continue
|
||||
if not track.drm or all(isinstance(d, WHOLE_FILE_DRM) for d in track.drm):
|
||||
log.info(f"Track {track_log_label(track)} needs no licence, so it has no keys to resolve")
|
||||
clear_tracks.append(tid)
|
||||
continue
|
||||
|
||||
title = find_title_for_track(tid, session)
|
||||
# with no server device in play, the client's DRM system is the one its vault keys are for
|
||||
candidates = (
|
||||
vault_candidates(drm_type)
|
||||
if vault_only
|
||||
else server_drm_candidates(service_tag, policy, drm_type, track, warn)
|
||||
)
|
||||
|
||||
probed: uuid.UUID | None = None
|
||||
if init_data:
|
||||
try:
|
||||
probed = track.get_key_id(init_data)
|
||||
except Exception as e:
|
||||
log.debug(f"KID probe failed for {sanitize_log(tid[:12])}: {e!r}")
|
||||
keys, track_drm_type, pssh_str = license_track(track, title, candidates, probed)
|
||||
# a refused track still tries its init segment PSSH, where a server vault can hold the key
|
||||
refusal = capped_tracks.pop(tid, None)
|
||||
|
||||
if probed and probed.hex not in keys:
|
||||
manifest_drm = track.drm
|
||||
track.drm = drm_from_init_segment(track, init_data=init_data) or manifest_drm
|
||||
init_keys, init_drm_type, init_pssh = license_track(track, title, candidates, probed)
|
||||
init_refusal = capped_tracks.pop(tid, None)
|
||||
if init_pssh != pssh_str:
|
||||
log.info(
|
||||
f"The manifest PSSH gave no content key for KID {probed.hex} of track "
|
||||
f"{track_log_label(track)}, tried the init segment PSSH"
|
||||
)
|
||||
if probed.hex in init_keys:
|
||||
keys, track_drm_type, pssh_str = init_keys, init_drm_type, init_pssh
|
||||
refusal = None
|
||||
else:
|
||||
track.drm = manifest_drm
|
||||
refusal = refusal or init_refusal
|
||||
if not refusal:
|
||||
warn(f"No content key for KID {probed.hex} of track {track_log_label(track)}")
|
||||
if refusal:
|
||||
capped_tracks[tid] = refusal
|
||||
continue
|
||||
|
||||
if keys:
|
||||
all_keys[tid] = keys
|
||||
sources = sources_by_pssh.get((pssh_str, pssh_set(track)), {}) if pssh_str is not None else {}
|
||||
note_served_keys(session, keys, sources)
|
||||
if sources:
|
||||
vault_keys.extend(sources)
|
||||
if keys and track_drm_type:
|
||||
drm_types[tid] = track_drm_type
|
||||
actual_drm_type = track_drm_type
|
||||
|
||||
response = LicenseReply(keys=all_keys)
|
||||
if clear_tracks:
|
||||
response["clear_tracks"] = clear_tracks
|
||||
if file_keys:
|
||||
response["file_keys"] = file_keys
|
||||
if vault_keys:
|
||||
response["vault_keys"] = vault_keys
|
||||
if actual_drm_type:
|
||||
response["drm_type"] = actual_drm_type
|
||||
if drm_types:
|
||||
response["drm_types"] = drm_types
|
||||
if capped_tracks:
|
||||
response["capped_tracks"] = capped_tracks
|
||||
batch = server_keys.resolve_batch(session, track_ids, drm_type, session_policy(session, request))
|
||||
response = LicenseReply(keys=batch.keys)
|
||||
if batch.clear_tracks:
|
||||
response["clear_tracks"] = batch.clear_tracks
|
||||
if batch.file_keys:
|
||||
response["file_keys"] = batch.file_keys
|
||||
if batch.vault_keys:
|
||||
response["vault_keys"] = batch.vault_keys
|
||||
if batch.drm_type:
|
||||
response["drm_type"] = batch.drm_type
|
||||
if batch.drm_types:
|
||||
response["drm_types"] = batch.drm_types
|
||||
if batch.capped_tracks:
|
||||
response["capped_tracks"] = batch.capped_tracks
|
||||
return web.json_response(response)
|
||||
|
||||
if not track_id:
|
||||
@@ -4377,7 +3768,7 @@ def license_response(data: LicenseRequest, session: Any, session_id: str, reques
|
||||
)
|
||||
|
||||
try:
|
||||
title = find_title_for_track(track_id, session)
|
||||
title = server_keys.find_title_for_track(track_id, session)
|
||||
service = session.service_instance
|
||||
|
||||
cipher = whole_file_cipher(track)
|
||||
@@ -4402,19 +3793,15 @@ def license_response(data: LicenseRequest, session: Any, session_id: str, reques
|
||||
# The server's config.cdm mapping decides the DRM system, as in the batch path.
|
||||
# The client only knows its own local device, which the server never uses here.
|
||||
policy = session_policy(session, request)
|
||||
candidates = (
|
||||
vault_candidates(drm_type)
|
||||
if vault_only
|
||||
else server_drm_candidates(session.service_tag, policy, drm_type, track)
|
||||
)
|
||||
picked = pick_server_pssh(track, candidates)
|
||||
candidates = server_keys.licence_candidates(session, policy, drm_type, track)
|
||||
picked = server_keys.pick_server_pssh(track, candidates)
|
||||
if not picked:
|
||||
raise APIError(
|
||||
APIErrorCode.INVALID_INPUT,
|
||||
f"No PSSH on track {track_log_label(track)} for {', '.join(candidates) or 'any CDM'}",
|
||||
)
|
||||
server_drm_type, server_pssh = picked
|
||||
asked_kid = client_track_kid(data.get("kid"), track)
|
||||
asked_kid = server_keys.client_track_kid(data.get("kid"), track)
|
||||
if pssh_b64 and server_drm_type != drm_type:
|
||||
log.info(
|
||||
f"Client asked for {sanitize_log(drm_type)} on track {track_log_label(track)}, "
|
||||
@@ -4422,35 +3809,34 @@ def license_response(data: LicenseRequest, session: Any, session_id: str, reques
|
||||
)
|
||||
pssh_b64 = None
|
||||
if pssh_b64:
|
||||
require_track_pssh(track, pssh_b64, drm_type)
|
||||
server_keys.require_track_pssh(track, pssh_b64, drm_type)
|
||||
if drm_type == "playready":
|
||||
track.pr_pssh = pssh_b64
|
||||
key_sources: dict[str, str] = {}
|
||||
keys = handle_single_server_cdm(
|
||||
keys = server_keys.handle_single_server_cdm(
|
||||
service,
|
||||
title,
|
||||
track,
|
||||
pssh_b64 or server_pssh,
|
||||
server_drm_type,
|
||||
request,
|
||||
policy,
|
||||
key_sources,
|
||||
live_licence_refusal(session, track),
|
||||
server_keys.live_licence_refusal(session, track),
|
||||
vault_only=vault_only,
|
||||
track_kid=asked_kid,
|
||||
policy=policy,
|
||||
)
|
||||
log.info(f"Server CDM resolved {len(keys)} key(s) for track {track_log_label(track)}")
|
||||
note_served_keys(session, keys, key_sources)
|
||||
server_keys.note_served_keys(session, keys, key_sources)
|
||||
return web.json_response(LicenseReply(keys=keys, vault_keys=list(key_sources), drm_type=server_drm_type))
|
||||
|
||||
if pssh_b64:
|
||||
require_track_pssh(track, pssh_b64, drm_type)
|
||||
server_keys.require_track_pssh(track, pssh_b64, drm_type)
|
||||
if drm_type == "playready":
|
||||
track.pr_pssh = pssh_b64
|
||||
|
||||
certificate = data.get("is_certificate") is True
|
||||
if licensing.server_device and not certificate:
|
||||
denied = live_licence_refusal(session, track)
|
||||
denied = server_keys.live_licence_refusal(session, track)
|
||||
if denied:
|
||||
raise denied
|
||||
return handle_proxy_license(service, title, track, challenge_b64, drm_type, certificate=certificate)
|
||||
@@ -4474,16 +3860,6 @@ def license_response(data: LicenseRequest, session: Any, session_id: str, reques
|
||||
)
|
||||
|
||||
|
||||
def note_served_keys(session: Any, keys: dict[str, str], sources: dict[str, str]) -> None:
|
||||
"""Remember every KID:KEY the remote session handed out and which server vault supplied it.
|
||||
|
||||
The vault name stays on the server: a bad-key report names only the pair, and the
|
||||
server looks the source up here to flag its own row.
|
||||
"""
|
||||
for kid, key in keys.items():
|
||||
session.served_keys[kid] = (key, sources.get(kid, "cdm"))
|
||||
|
||||
|
||||
async def session_bad_key_handler(
|
||||
data: BadKeyReport, session_id: str, request: web.Request | None = None
|
||||
) -> web.Response:
|
||||
@@ -4510,11 +3886,11 @@ async def session_bad_key_handler(
|
||||
return web.json_response({"flagged": False})
|
||||
|
||||
service_name = session.service_instance.__class__.__name__
|
||||
vaults = load_server_vaults(service_name)
|
||||
vaults = server_keys.load_server_vaults(service_name)
|
||||
|
||||
await asyncio.to_thread(vaults.flag_served, UUID(hex=kid), served_key, source)
|
||||
session.served_keys.pop(kid, None)
|
||||
CACHED_PAIRS.discard((service_name, kid, served_key))
|
||||
server_keys.CACHED_PAIRS.discard((service_name, kid, served_key))
|
||||
log.warning(
|
||||
f"Client proved {kid}:{served_key} from vault {sanitize_log(source)} wrong, flagged in the server vaults"
|
||||
)
|
||||
@@ -4549,7 +3925,7 @@ async def session_keys_handler(data: TrackKeys, session_id: str, request: web.Re
|
||||
return {kid.hex for t in list(session.tracks.values()) for drm in t.drm or [] for kid in real_kids(drm)}
|
||||
|
||||
def store(named: set[str]) -> tuple[Any, dict[Any, str]]:
|
||||
vaults = load_server_vaults(service.__class__.__name__)
|
||||
vaults = server_keys.load_server_vaults(service.__class__.__name__)
|
||||
new: dict[Any, str] = {}
|
||||
for kid_hex, key in pairs.items():
|
||||
if kid_hex not in named or session.served_keys.get(kid_hex, ("",))[0].lower() == key:
|
||||
|
||||
@@ -0,0 +1,684 @@
|
||||
"""Server keys for a remote session: the vault lookup, the cap and the server CDM licence of each track."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import logging
|
||||
import uuid
|
||||
from collections.abc import Callable, Iterable, Sequence
|
||||
from dataclasses import dataclass, field
|
||||
from typing import TYPE_CHECKING, Any, NamedTuple
|
||||
|
||||
from unshackle.core.api import licence_cap
|
||||
from unshackle.core.api.errors import APIError
|
||||
from unshackle.core.api.key_policy import KeyPolicy
|
||||
from unshackle.core.api.progress import track_log_label
|
||||
from unshackle.core.api.sanitize import sanitize_log
|
||||
from unshackle.core.cdm.choice import SYSTEMS, choose_cdm
|
||||
from unshackle.core.cdm.detect import cdm_system
|
||||
from unshackle.core.cdm.loader import device_system
|
||||
from unshackle.core.drm import WHOLE_FILE_DRM, is_null_key, whole_file_cipher
|
||||
from unshackle.core.drm.discovery import drm_from_init_segment, ensure_track_drm, fetch_init_segment, track_pssh
|
||||
from unshackle.core.remote_protocol import APIErrorCode
|
||||
from unshackle.core.utilities import declared_kwargs
|
||||
from unshackle.core.utils.redact import redact_all
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from unshackle.core.api.session_store import SessionEntry
|
||||
from unshackle.core.vaults import Vaults
|
||||
|
||||
log = logging.getLogger("api")
|
||||
|
||||
|
||||
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.
|
||||
|
||||
Only a live licence spends the server's device, so a vault hit always passes.
|
||||
"""
|
||||
licensing = session.licensing
|
||||
if licensing.server_device:
|
||||
return APIError(
|
||||
APIErrorCode.SERVER_CDM_CAPPED,
|
||||
"This session runs on the server's device, so its keys come only from a vault.",
|
||||
details={"reason": "server_device"},
|
||||
)
|
||||
if not licensing.server_cdm:
|
||||
return licence_cap.capped_error(
|
||||
"This session licenses with your own device, so the server CDM makes no licence for it."
|
||||
)
|
||||
return licence_cap.track_refusal(licensing.max_height, track)
|
||||
|
||||
|
||||
def drm_preference_name(track: Any) -> str | None:
|
||||
"""The track's drm_preference as a full DRM system name, "widevine" or "playready"; None when unset."""
|
||||
preference = getattr(track, "drm_preference", None)
|
||||
if not preference:
|
||||
return None
|
||||
return {"wv": "widevine", "pr": "playready"}.get(preference, preference)
|
||||
|
||||
|
||||
def detect_cdm_type_for_service(service: str, app_config: Any) -> str | None:
|
||||
"""The DRM system config.cdm settles for a service; None when the mapping leaves it open.
|
||||
|
||||
A mapping that names one system gets that system. A device name gets the type of the
|
||||
device ``resolve_device_name`` returns for it, so the routes plan with the device they
|
||||
load. A mapping that names a device for both systems settles nothing.
|
||||
"""
|
||||
choice = choose_cdm(app_config.cdm, service, view="licence")
|
||||
if choice.systems:
|
||||
return choice.system
|
||||
if choice.name:
|
||||
return device_system(choice.name, app_config)
|
||||
return None
|
||||
|
||||
|
||||
def find_title_for_track(track_id: str, session: Any) -> Any:
|
||||
"""Find the title object that owns a given track."""
|
||||
for t_id, tracks_dict in session.tracks_by_title.items():
|
||||
if track_id in tracks_dict:
|
||||
return session.title_map.get(t_id)
|
||||
if session.title_map:
|
||||
return session.title_map.get(session.current_title_id) or next(iter(session.title_map.values()))
|
||||
return None
|
||||
|
||||
|
||||
def resolve_device_name(policy: KeyPolicy, drm_type: str, service_tag: str = "") -> str:
|
||||
"""Get the CDM device name, checking the service's cdm mapping first.
|
||||
|
||||
Resolution order:
|
||||
1. the key's own ``cdm`` entry for the service, else ``config.cdm[service_tag]``
|
||||
2. the key's ``devices`` / ``playready_devices``
|
||||
"""
|
||||
cdm_name = choose_cdm(policy.cdm_config().cdm, service_tag, drm=drm_type, view="licence").name
|
||||
if cdm_name:
|
||||
return cdm_name
|
||||
|
||||
if drm_type == "playready":
|
||||
device_name = next(iter(policy.devices("playready_devices")), None)
|
||||
if not device_name:
|
||||
raise APIError(APIErrorCode.INVALID_INPUT, "No PlayReady device configured for this API key")
|
||||
else:
|
||||
device_name = next(iter(policy.devices("devices")), None)
|
||||
if not device_name:
|
||||
raise APIError(APIErrorCode.INVALID_INPUT, "No Widevine device configured for this API key")
|
||||
return device_name
|
||||
|
||||
|
||||
def vault_candidates(client_drm_type: str) -> list[str]:
|
||||
"""Both DRM systems, the client's first: a vault lookup needs only the KIDs, whatever device made the manifest."""
|
||||
first = client_drm_type if client_drm_type in ("widevine", "playready") else "widevine"
|
||||
return [first, "playready" if first == "widevine" else "widevine"]
|
||||
|
||||
|
||||
def loaded_cdm_system(session: Any) -> str | None:
|
||||
"""The DRM system of the device the session's service was built on, in a server CDM session; None otherwise."""
|
||||
if not session.licensing.server_cdm:
|
||||
return None
|
||||
return cdm_system(getattr(getattr(getattr(session.service_instance, "ctx", None), "obj", None), "cdm", None))
|
||||
|
||||
|
||||
def server_drm_candidates(
|
||||
service_tag: str, policy: KeyPolicy, client_drm_type: str, tracks: Sequence[Any], loaded: str | None = None
|
||||
) -> list[str]:
|
||||
"""The DRM systems the server can license ``tracks`` with, in the order to try them.
|
||||
|
||||
The server's config.cdm mapping goes first. A mapping with a device for each system puts the system of
|
||||
the ``loaded`` device first, else the client's choice. Otherwise, or with neither known, the client's choice
|
||||
goes first when the tracks carry it, then a system they carry, PlayReady before Widevine. A system
|
||||
stays only when the device the server would load for it is of that system, so the route never
|
||||
plans a licence that fails on the wrong device type.
|
||||
"""
|
||||
app_config = policy.cdm_config()
|
||||
client = client_drm_type if client_drm_type in SYSTEMS else None
|
||||
settled = detect_cdm_type_for_service(service_tag, app_config)
|
||||
if settled:
|
||||
order = [settled]
|
||||
elif (loaded or client) and choose_cdm(app_config.cdm, service_tag).both:
|
||||
order = [loaded or client or ""]
|
||||
else:
|
||||
carried = {d.__class__.__name__.lower() for t in tracks for d in (getattr(t, "drm", None) or [])}
|
||||
order = [system for system in (client or "", "playready", "widevine") if system in carried]
|
||||
order.append(client or "widevine")
|
||||
candidates: list[str] = []
|
||||
for drm_type in dict.fromkeys([*order, *SYSTEMS]):
|
||||
try:
|
||||
device_name = resolve_device_name(policy, drm_type, service_tag)
|
||||
except APIError:
|
||||
continue
|
||||
if device_system(device_name, app_config) in (None, drm_type):
|
||||
candidates.append(drm_type)
|
||||
return candidates
|
||||
|
||||
|
||||
def licence_candidates(
|
||||
session: Any, policy: KeyPolicy, client_drm_type: str, track: Any, warn: Callable[[str], None] = log.warning
|
||||
) -> list[str]:
|
||||
"""The DRM systems to license ``track`` with in ``session``, in the order to try them.
|
||||
|
||||
With no server device in play, the client's DRM system is the one its vault keys are for. Else
|
||||
the track's own drm_preference moves its system to the front when the server has it.
|
||||
"""
|
||||
if session.licensing.vault_only:
|
||||
return vault_candidates(client_drm_type)
|
||||
candidates = server_drm_candidates(
|
||||
session.service_tag, policy, client_drm_type, [track], loaded_cdm_system(session)
|
||||
)
|
||||
preferred = drm_preference_name(track)
|
||||
if preferred:
|
||||
if preferred in candidates:
|
||||
candidates.remove(preferred)
|
||||
candidates.insert(0, preferred)
|
||||
else:
|
||||
warn(
|
||||
f"Track {track_log_label(track)} wants {preferred} DRM "
|
||||
"but the server has no device for it, using the configured DRM instead"
|
||||
)
|
||||
return candidates
|
||||
|
||||
|
||||
def pick_server_pssh(track: Any, candidates: list[str]) -> tuple[str, str] | None:
|
||||
"""`(drm_type, pssh)` for the first candidate the track carries a header for; None when it has none.
|
||||
|
||||
A track with only a PlayReady header still licenses under the Widevine device: the
|
||||
Widevine DRM class converts the PlayReady PSSH on construction.
|
||||
"""
|
||||
for candidate in candidates:
|
||||
pssh_str = track_pssh(track, candidate)
|
||||
if not pssh_str and candidate == "widevine":
|
||||
pssh_str = track_pssh(track, "playready")
|
||||
if pssh_str:
|
||||
log.info(
|
||||
f"Track {track_log_label(track)} has only a PlayReady PSSH, licensing it with the Widevine device"
|
||||
)
|
||||
if pssh_str:
|
||||
return candidate, pssh_str
|
||||
return None
|
||||
|
||||
|
||||
def load_server_vaults(service_name: str) -> Vaults:
|
||||
"""Load server vaults from config.key_vaults; a vault that fails to load is left out."""
|
||||
from unshackle.core.services import Services
|
||||
from unshackle.core.vaults import load_config_vaults
|
||||
|
||||
return load_config_vaults(Services.get_vault_tag(service_name))[0]
|
||||
|
||||
|
||||
def once(shared: dict[Any, Any], key: Any, make: Callable[[], Any]) -> Any:
|
||||
"""``make()`` the first time ``key`` is asked for in ``shared``, the stored value after that."""
|
||||
if key not in shared:
|
||||
shared[key] = make()
|
||||
return shared[key]
|
||||
|
||||
|
||||
def check_vaults(
|
||||
kids: list, service_name: str, shared: dict[str, Any] | None = None, track_kid: uuid.UUID | None = None
|
||||
) -> tuple[dict[str, str], dict[str, str]] | None:
|
||||
"""Examine the server vaults for existing content keys that match the KIDs.
|
||||
|
||||
Returns `(KID:KEY, KID:vault name)` when every KID is found, or with ``track_kid`` when that
|
||||
KID is found, with the other KIDs the vaults hold; None otherwise. The vault name travels to
|
||||
the client, which is the only side that can prove the content key decrypts.
|
||||
"""
|
||||
try:
|
||||
vaults = once({} if shared is None else shared, "vaults", lambda: load_server_vaults(service_name))
|
||||
if not vaults:
|
||||
return None
|
||||
keys: dict[str, str] = {}
|
||||
sources: dict[str, str] = {}
|
||||
wanted = [kid if isinstance(kid, uuid.UUID) else uuid.UUID(hex=str(kid)) for kid in kids]
|
||||
if track_kid:
|
||||
wanted = [track_kid, *(kid for kid in wanted if kid != track_kid)]
|
||||
for kid_uuid in wanted:
|
||||
content_key, vault_used = vaults.get_key(kid_uuid)
|
||||
if content_key:
|
||||
keys[kid_uuid.hex] = content_key
|
||||
sources[kid_uuid.hex] = vault_used.name if vault_used else "unknown"
|
||||
elif track_kid in (None, kid_uuid):
|
||||
return None
|
||||
if keys:
|
||||
log.info(f"Vault hit: {len(keys)} key(s) from server vaults, skipping CDM")
|
||||
return keys, sources
|
||||
# vault lookup is a best-effort shortcut before the CDM; any failure falls through to licensing
|
||||
except Exception as e:
|
||||
log.debug(f"Server vault lookup failed: {e!r}")
|
||||
return None
|
||||
|
||||
|
||||
CACHED_PAIRS: set[tuple[str, str, str]] = set()
|
||||
|
||||
|
||||
def cache_to_vaults(keys: dict[str, str], service_name: str, shared: dict[str, Any] | None = None) -> None:
|
||||
"""Cache the content keys of a CDM licence to the server vaults.
|
||||
|
||||
A PlayReady licence always runs, and a Widevine licence runs when one PSSH KID has no content
|
||||
key in a vault, so the same content keys come back on every request for a title. This process
|
||||
does not send a pair again after every vault accepted it. A pair a client reported as bad
|
||||
leaves that set, and is unflagged when the CDM returns it.
|
||||
"""
|
||||
from uuid import UUID
|
||||
|
||||
try:
|
||||
new = {kid: key for kid, key in keys.items() if (service_name, kid, key) not in CACHED_PAIRS}
|
||||
if not new:
|
||||
return
|
||||
vaults = once({} if shared is None else shared, "vaults", lambda: load_server_vaults(service_name))
|
||||
if not vaults:
|
||||
return
|
||||
|
||||
key_map = {UUID(hex=kid): key for kid, key in new.items()}
|
||||
for kid in vaults.clear_licensed_flags(key_map):
|
||||
log.info(f"Unflagged {kid.hex}:{key_map[kid]}, the CDM returned it")
|
||||
cached = vaults.add_keys(key_map)
|
||||
if vaults.stored_everywhere(cached):
|
||||
CACHED_PAIRS.update((service_name, kid, key) for kid, key in new.items())
|
||||
if cached:
|
||||
log.info(f"Cached {len(key_map)} key(s) to {cached}/{len(vaults)} server vault(s)")
|
||||
except (Exception, SystemExit) as e:
|
||||
log.warning(f"Failed to cache keys to vaults: {e}")
|
||||
|
||||
|
||||
def track_injected_keys(track: Any, drm_class: str) -> dict[str, str]:
|
||||
"""`KID:KEY` pairs a service wrote onto the track's own DRM objects of `drm_class`.
|
||||
|
||||
Some services skip the CDM exchange: the licence callback fetches the keys itself,
|
||||
writes them into ``track.drm[0].content_keys`` and returns a value the CDM cannot
|
||||
parse. ``dl.py`` accepts that failed parse because the object it licensed holds the
|
||||
keys. The server licenses a rebuilt object, so it reads the track's objects instead.
|
||||
"""
|
||||
keys: dict[str, str] = {}
|
||||
for drm in getattr(track, "drm", None) or []:
|
||||
if drm.__class__.__name__ != drm_class:
|
||||
continue
|
||||
for kid, key in (getattr(drm, "content_keys", None) or {}).items():
|
||||
keys[kid.hex if hasattr(kid, "hex") else str(kid).replace("-", "")] = key
|
||||
return keys
|
||||
|
||||
|
||||
def license_with_track_fallback(drm: Any, track: Any, **kwargs: Any) -> dict[str, str]:
|
||||
"""Run `drm.get_content_keys`, merge in the keys the service put on the track itself, and drop the null keys."""
|
||||
try:
|
||||
drm.get_content_keys(**kwargs)
|
||||
except Exception:
|
||||
if not track_injected_keys(track, drm.__class__.__name__):
|
||||
raise
|
||||
keys = {
|
||||
**track_injected_keys(track, drm.__class__.__name__),
|
||||
**{kid.hex: key for kid, key in drm.content_keys.items()},
|
||||
}
|
||||
return {kid: key for kid, key in keys.items() if not is_null_key(key)}
|
||||
|
||||
|
||||
def client_track_kid(kid_hex: Any, track: Any) -> uuid.UUID | None:
|
||||
"""The KID a client asks the server CDM for, when the track's DRM names it; None for any other value."""
|
||||
if not isinstance(kid_hex, str):
|
||||
return None
|
||||
try:
|
||||
kid = uuid.UUID(hex=kid_hex)
|
||||
except ValueError:
|
||||
return None
|
||||
return kid if any(kid in (getattr(d, "kids", None) or []) for d in getattr(track, "drm", None) or []) else None
|
||||
|
||||
|
||||
def pssh_kids(pssh_b64: str, drm_type: str) -> set:
|
||||
"""The KIDs a base64 PSSH names, for either DRM system."""
|
||||
if drm_type == "playready":
|
||||
from pyplayready.system.pssh import PSSH as PlayReadyPSSH
|
||||
|
||||
from unshackle.core.drm import PlayReady
|
||||
|
||||
return set(PlayReady(pssh=PlayReadyPSSH(base64.b64decode(pssh_b64)), pssh_b64=pssh_b64).kids)
|
||||
from pywidevine.pssh import PSSH as WvPSSH
|
||||
|
||||
from unshackle.core.drm import Widevine
|
||||
|
||||
return set(Widevine(pssh=WvPSSH(pssh_b64)).kids)
|
||||
|
||||
|
||||
def require_track_pssh(track: Any, pssh_b64: str, drm_type: str) -> None:
|
||||
"""Reject a client PSSH that names a KID the track does not carry.
|
||||
|
||||
The server CDM path answers from the vault before any license exchange, so an
|
||||
unchecked PSSH would make the key vault answer with content keys for any title. The
|
||||
track's own PSSH passes as it is, so a header without KIDs still licenses.
|
||||
"""
|
||||
if pssh_b64 == track_pssh(track, drm_type):
|
||||
return
|
||||
try:
|
||||
client_kids = pssh_kids(pssh_b64, drm_type)
|
||||
except Exception:
|
||||
raise APIError(APIErrorCode.INVALID_INPUT, "The pssh parameter is not a valid PSSH box") from None
|
||||
track_kids = {kid for drm in (getattr(track, "drm", None) or []) for kid in (getattr(drm, "kids", None) or [])}
|
||||
if not client_kids or not track_kids or not client_kids <= track_kids:
|
||||
raise APIError(
|
||||
APIErrorCode.FORBIDDEN,
|
||||
"The pssh parameter does not belong to this track.",
|
||||
details={"track_id": str(getattr(track, "id", ""))},
|
||||
)
|
||||
|
||||
|
||||
def handle_single_server_cdm(
|
||||
service: Any,
|
||||
title: Any,
|
||||
track: Any,
|
||||
pssh_b64: str | None,
|
||||
drm_type: str,
|
||||
policy: KeyPolicy,
|
||||
sources: dict[str, str] | None = None,
|
||||
refusal: APIError | None = None,
|
||||
vault_only: bool = False,
|
||||
shared: dict[str, Any] | None = None,
|
||||
track_kid: uuid.UUID | None = None,
|
||||
) -> dict[str, str]:
|
||||
"""Do the single-track server_cdm licensing with the DRM class get_content_keys() flow.
|
||||
|
||||
``sources`` is filled with the vault name for every returned content key a server vault
|
||||
supplied. A content key the CDM licensed gets no entry. A vault answers in place of the licence
|
||||
when it holds ``track_kid``, the KID the track is encrypted with, or else every KID of the header.
|
||||
PlayReady without ``track_kid`` always licenses, as its licence can carry keys its header does not name.
|
||||
It raises ``refusal`` before a live licence. With ``vault_only`` no server device is involved.
|
||||
``shared`` keeps the vaults and CDMs that one call of the licence route loaded, for its next track.
|
||||
"""
|
||||
from unshackle.core.cdm import load_cdm
|
||||
from unshackle.core.cdm.detect import is_playready_cdm, is_widevine_cdm
|
||||
|
||||
ensure_track_drm(track, getattr(service, "session", None))
|
||||
shared = {} if shared is None else shared
|
||||
service_name = service.__class__.__name__
|
||||
|
||||
if not pssh_b64:
|
||||
pssh_b64 = track_pssh(track, drm_type)
|
||||
if not pssh_b64:
|
||||
raise APIError(APIErrorCode.INVALID_INPUT, "No PSSH available for server_cdm licensing")
|
||||
|
||||
def from_vaults(kids: Iterable[uuid.UUID]) -> dict[str, str] | None:
|
||||
"""The vault keys for ``kids`` (see ``check_vaults``), with their sources noted."""
|
||||
hit = check_vaults(list(kids), service_name, shared=shared, track_kid=track_kid)
|
||||
if hit and sources is not None:
|
||||
sources.update(hit[1])
|
||||
return hit[0] if hit else None
|
||||
|
||||
if vault_only:
|
||||
if vault_keys := from_vaults(pssh_kids(pssh_b64, drm_type)):
|
||||
return vault_keys
|
||||
raise refusal or APIError(APIErrorCode.NO_CONTENT, "The server vault holds no content key for this track")
|
||||
|
||||
if drm_type == "playready":
|
||||
from pyplayready.system.pssh import PSSH as PlayReadyPSSH
|
||||
|
||||
from unshackle.core.drm import PlayReady
|
||||
|
||||
pr_pssh = PlayReadyPSSH(base64.b64decode(pssh_b64))
|
||||
siblings = [d for d in (getattr(track, "drm", None) or []) if isinstance(d, PlayReady)]
|
||||
manifest_kid = next((getattr(d, "kid", None) for d in siblings if getattr(d, "kid", None)), None)
|
||||
pr_drm = PlayReady(pssh=pr_pssh, pssh_b64=pssh_b64, kid=manifest_kid)
|
||||
if siblings:
|
||||
pr_drm.absorb(*siblings)
|
||||
|
||||
# Gate on the caller's CDM device first: no device, no keys from the vault or CDM.
|
||||
device_name = resolve_device_name(policy, drm_type, service_name)
|
||||
|
||||
if track_kid and (vault_keys := from_vaults(pr_drm.kids)):
|
||||
return vault_keys
|
||||
if refusal:
|
||||
raise refusal
|
||||
|
||||
cdm = once(shared, ("cdm", device_name), lambda: load_cdm(device_name, service_name=service_name))
|
||||
if not is_playready_cdm(cdm):
|
||||
raise APIError(APIErrorCode.INVALID_INPUT, f"CDM device '{device_name}' is not a PlayReady device")
|
||||
keys = license_with_track_fallback(
|
||||
pr_drm,
|
||||
track,
|
||||
cdm=cdm,
|
||||
certificate=lambda challenge, **_: None,
|
||||
licence=lambda **kw: service.get_playready_license(
|
||||
**declared_kwargs(service.get_playready_license, {**kw, "title": title, "track": track})
|
||||
),
|
||||
)
|
||||
elif drm_type == "widevine":
|
||||
from pywidevine.pssh import PSSH as WvPSSH
|
||||
|
||||
from unshackle.core.drm import Widevine
|
||||
|
||||
wv_pssh = WvPSSH(pssh_b64)
|
||||
wv_drm = Widevine(pssh=wv_pssh)
|
||||
|
||||
# Gate on the caller's CDM device first so a caller with no device cannot
|
||||
# harvest server-side keys from the vault fallback below.
|
||||
device_name = resolve_device_name(policy, drm_type, service_name)
|
||||
|
||||
if vault_keys := from_vaults(wv_drm.kids):
|
||||
return vault_keys
|
||||
if refusal:
|
||||
raise refusal
|
||||
|
||||
cdm = once(shared, ("cdm", device_name), lambda: load_cdm(device_name, service_name=service_name))
|
||||
if not is_widevine_cdm(cdm):
|
||||
raise APIError(APIErrorCode.INVALID_INPUT, f"CDM device '{device_name}' is not a Widevine device")
|
||||
keys = license_with_track_fallback(
|
||||
wv_drm,
|
||||
track,
|
||||
cdm=cdm,
|
||||
certificate=lambda challenge, **_: service.get_widevine_service_certificate(
|
||||
challenge=challenge, title=title, track=track
|
||||
),
|
||||
licence=lambda **kw: service.get_widevine_license(
|
||||
**declared_kwargs(service.get_widevine_license, {**kw, "title": title, "track": track})
|
||||
),
|
||||
)
|
||||
else:
|
||||
raise APIError(
|
||||
APIErrorCode.INVALID_PARAMETERS,
|
||||
f"Unsupported DRM type for server_cdm: {drm_type}",
|
||||
)
|
||||
|
||||
if not keys:
|
||||
raise APIError(APIErrorCode.NO_CONTENT, "Server CDM returned no content keys")
|
||||
|
||||
cache_to_vaults(keys, service_name, shared=shared)
|
||||
return keys
|
||||
|
||||
|
||||
def note_served_keys(session: Any, keys: dict[str, str], sources: dict[str, str]) -> None:
|
||||
"""Remember every KID:KEY the remote session handed out and which server vault supplied it.
|
||||
|
||||
The vault name stays on the server: a bad-key report names only the pair, and the
|
||||
server looks the source up here to flag its own row.
|
||||
"""
|
||||
for kid, key in keys.items():
|
||||
session.served_keys[kid] = (key, sources.get(kid, "cdm"))
|
||||
|
||||
|
||||
def pssh_set(track: Any) -> tuple:
|
||||
"""Every PSSH and KID the track carries, as the rest of the cache key.
|
||||
|
||||
Two tracks can share their first PSSH and still need different licences,
|
||||
because the server licenses every header the track holds and asks for every
|
||||
KID the manifest named on it.
|
||||
"""
|
||||
drms = getattr(track, "drm", None) or []
|
||||
return (
|
||||
tuple(sorted(str(getattr(d, "pssh_b64", "") or "") for d in drms)),
|
||||
tuple(sorted(str(kid) for d in drms for kid in (getattr(d, "kids", None) or []))),
|
||||
)
|
||||
|
||||
|
||||
class ResolvedTrack(NamedTuple):
|
||||
"""One track's server keys, the DRM system and PSSH they came from, their vault sources, and a cap refusal."""
|
||||
|
||||
keys: dict[str, str]
|
||||
drm_type: str | None
|
||||
pssh: str | None
|
||||
sources: dict[str, str]
|
||||
refusal: dict[str, Any] | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class ServerKeys:
|
||||
"""The server keys of one call of the licence route: one vault load, one CDM per device, one licence per PSSH."""
|
||||
|
||||
session: Any
|
||||
policy: KeyPolicy
|
||||
shared: dict[Any, Any] = field(default_factory=dict)
|
||||
keys_by_pssh: dict[tuple, dict[str, str]] = field(default_factory=dict)
|
||||
sources_by_pssh: dict[tuple, dict[str, str]] = field(default_factory=dict)
|
||||
drm_type_by_pssh: dict[tuple, str] = field(default_factory=dict)
|
||||
|
||||
def warn(self, message: str) -> None:
|
||||
"""Log on the server and copy into the remote session buffer the client drains.
|
||||
|
||||
The buffer takes only ``service.log``, so a licensing failure raised
|
||||
here would otherwise reach the client as a bare "no content keys".
|
||||
"""
|
||||
log.warning(message)
|
||||
if self.session.log_buffer:
|
||||
self.session.log_buffer.append(logging.WARNING, message)
|
||||
|
||||
def license_pssh(self, track: Any, title: Any, candidates: list[str], track_kid: uuid.UUID | None) -> ResolvedTrack:
|
||||
"""The keys of the track's current DRM, licensing once per unique PSSH.
|
||||
|
||||
A cached vault answer that lacks ``track_kid`` is asked again for that KID. A track the server
|
||||
must not license live gets no keys and the refusal details, and its PSSH stays uncached,
|
||||
as a track under the cap can share it.
|
||||
"""
|
||||
picked = pick_server_pssh(track, candidates)
|
||||
if not picked:
|
||||
self.warn(f"No PSSH on track {track_log_label(track)} for {', '.join(candidates) or 'any CDM'}")
|
||||
return ResolvedTrack({}, None, None, {})
|
||||
candidate, pssh_str = picked
|
||||
|
||||
cache_key = (pssh_str, pssh_set(track))
|
||||
cached = self.keys_by_pssh.get(cache_key)
|
||||
from_vault = bool(cached) and set(cached or {}) <= set(self.sources_by_pssh.get(cache_key, {}))
|
||||
if cached is None or (track_kid and track_kid.hex not in cached and from_vault):
|
||||
self.keys_by_pssh.setdefault(cache_key, {})
|
||||
self.sources_by_pssh.setdefault(cache_key, {})
|
||||
try:
|
||||
keys = handle_single_server_cdm(
|
||||
self.session.service_instance,
|
||||
title,
|
||||
track,
|
||||
pssh_str,
|
||||
candidate,
|
||||
self.policy,
|
||||
self.sources_by_pssh[cache_key],
|
||||
live_licence_refusal(self.session, track),
|
||||
vault_only=self.session.licensing.vault_only,
|
||||
shared=self.shared,
|
||||
track_kid=track_kid,
|
||||
)
|
||||
if keys:
|
||||
self.keys_by_pssh[cache_key] = {**self.keys_by_pssh[cache_key], **keys}
|
||||
self.drm_type_by_pssh[cache_key] = candidate
|
||||
except SystemExit:
|
||||
self.warn(f"Service exited while resolving keys for track {track_log_label(track)}, skipping")
|
||||
except Exception as e:
|
||||
if isinstance(e, APIError) and e.error_code is APIErrorCode.SERVER_CDM_CAPPED:
|
||||
del self.keys_by_pssh[cache_key], self.sources_by_pssh[cache_key]
|
||||
return ResolvedTrack({}, None, pssh_str, {}, e.details)
|
||||
self.warn(f"Failed to resolve keys for track {track_log_label(track)}: {redact_all(str(e))}")
|
||||
return ResolvedTrack(
|
||||
self.keys_by_pssh[cache_key],
|
||||
self.drm_type_by_pssh.get(cache_key),
|
||||
pssh_str,
|
||||
self.sources_by_pssh.get(cache_key, {}),
|
||||
)
|
||||
|
||||
def resolve_track(
|
||||
self,
|
||||
track: Any,
|
||||
title: Any,
|
||||
candidates: list[str],
|
||||
probed_kid: uuid.UUID | None,
|
||||
init_data: bytes | None = None,
|
||||
) -> ResolvedTrack:
|
||||
"""The track's keys; when they lack ``probed_kid``, the KID read from ``init_data``, its init segment PSSH is tried.
|
||||
|
||||
A refused track tries the init segment PSSH too, where a server vault can hold the content key. The track keeps
|
||||
the init segment DRM only when that PSSH gave the KID, and the refusal stays when neither did.
|
||||
"""
|
||||
result = self.license_pssh(track, title, candidates, probed_kid)
|
||||
if not probed_kid or probed_kid.hex in result.keys:
|
||||
return result
|
||||
|
||||
manifest_drm = track.drm
|
||||
track.drm = drm_from_init_segment(track, init_data=init_data) or manifest_drm
|
||||
init = self.license_pssh(track, title, candidates, probed_kid)
|
||||
if init.pssh != result.pssh:
|
||||
log.info(
|
||||
f"The manifest PSSH gave no content key for KID {probed_kid.hex} of track "
|
||||
f"{track_log_label(track)}, tried the init segment PSSH"
|
||||
)
|
||||
if probed_kid.hex in init.keys:
|
||||
return init
|
||||
track.drm = manifest_drm
|
||||
refusal = result.refusal or init.refusal
|
||||
if not refusal:
|
||||
self.warn(f"No content key for KID {probed_kid.hex} of track {track_log_label(track)}")
|
||||
return result._replace(refusal=refusal)
|
||||
|
||||
|
||||
@dataclass
|
||||
class BatchKeys:
|
||||
"""The server keys of a batch call of the licence route by track ID, and the tracks the server did not key."""
|
||||
|
||||
keys: dict[str, dict[str, str]] = field(default_factory=dict)
|
||||
vault_keys: list[str] = field(default_factory=list)
|
||||
clear_tracks: list[str] = field(default_factory=list)
|
||||
file_keys: dict[str, str] = field(default_factory=dict)
|
||||
drm_types: dict[str, str] = field(default_factory=dict)
|
||||
drm_type: str | None = None
|
||||
capped_tracks: dict[str, dict[str, Any]] = field(default_factory=dict)
|
||||
|
||||
|
||||
def resolve_batch(session: Any, track_ids: Iterable[str], drm_type: str, policy: KeyPolicy) -> BatchKeys:
|
||||
"""The server keys of each track in ``track_ids`` the remote session holds, with the client's ``drm_type``.
|
||||
|
||||
A whole-file cipher track gets its file key, a track without a licensed DRM is listed as clear, and a
|
||||
track the server must not license live is listed as capped with its refusal details.
|
||||
``drm_type`` of the result is the system of the last keyed track.
|
||||
"""
|
||||
resolver = ServerKeys(session, policy)
|
||||
batch = BatchKeys()
|
||||
service = session.service_instance
|
||||
for tid in track_ids:
|
||||
track = session.tracks.get(tid)
|
||||
if not track:
|
||||
continue
|
||||
|
||||
svc_session = getattr(service, "session", None)
|
||||
init_data = fetch_init_segment(track, svc_session)
|
||||
ensure_track_drm(track, svc_session, init_data)
|
||||
cipher = whole_file_cipher(track)
|
||||
if cipher is not None:
|
||||
if not session.licensing.vault_only:
|
||||
try:
|
||||
batch.file_keys[tid] = cipher.content_key().hex()
|
||||
except (Exception, SystemExit) as e:
|
||||
resolver.warn(f"Failed to license track {track_log_label(track)}: {redact_all(str(e))}")
|
||||
continue
|
||||
if not track.drm or all(isinstance(d, WHOLE_FILE_DRM) for d in track.drm):
|
||||
log.info(f"Track {track_log_label(track)} needs no licence, so it has no keys to resolve")
|
||||
batch.clear_tracks.append(tid)
|
||||
continue
|
||||
|
||||
title = find_title_for_track(tid, session)
|
||||
candidates = licence_candidates(session, policy, drm_type, track, resolver.warn)
|
||||
probed: uuid.UUID | None = None
|
||||
if init_data:
|
||||
try:
|
||||
probed = track.get_key_id(init_data)
|
||||
except Exception as e:
|
||||
log.debug(f"KID probe failed for {sanitize_log(tid[:12])}: {e!r}")
|
||||
result = resolver.resolve_track(track, title, candidates, probed, init_data)
|
||||
if result.refusal:
|
||||
batch.capped_tracks[tid] = result.refusal
|
||||
continue
|
||||
|
||||
if result.keys:
|
||||
batch.keys[tid] = result.keys
|
||||
note_served_keys(session, result.keys, result.sources)
|
||||
batch.vault_keys.extend(result.sources)
|
||||
if result.drm_type:
|
||||
batch.drm_types[tid] = result.drm_type
|
||||
batch.drm_type = result.drm_type
|
||||
return batch
|
||||
Reference in New Issue
Block a user