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:
@@ -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