feat(drm): license a plugin DRM at the licence step and over --remote with the client's plugin device

This commit is contained in:
imSp4rky
2026-12-03 15:51:42 -07:00
parent f1f91a7d5c
commit 0536056ed6
24 changed files with 803 additions and 136 deletions
+3 -1
View File
@@ -232,7 +232,9 @@ accepted URL/ID formats and options there.
to classify it. These work correctly for local *and* remote CDMs, so never
hand-roll an `isinstance` check. Services often pick a device profile or
manifest endpoint based on which DRM the CDM speaks. A service whose DRM
plugin licenses locally gets its device from `ctx.obj.cdm_for("<plugin id>")`.
plugin licenses locally puts only the plugin data on the track: unshackle
licenses it at the licence step. To pick streams by the device, read the
device with `ctx.obj.cdm_for("<plugin id>")`.
`ctx.obj.cdm_for` is `None` where nothing licenses, for example in a search.
### `authenticate`: optional login
+2 -2
View File
@@ -999,7 +999,7 @@ the newlines must go out at once.
### `POST /api/session/create`
Make a remote session for a service and title. Authentication runs asynchronously in the background. This call returns immediately with `status: "authenticating"`, and you then poll the prompt endpoint. The body accepts `service` and `title_id` (both required). It also accepts a broad set of optional keys, because the body allows `additionalProperties`. These are `session_id`, `credentials` (`{username, password, extra?}`), `cookies` (base64 of zlib-compressed Netscape cookie file), `proxy`, `no_proxy`, `profile`, `cache` (map of forwarded cache files, keyed by the file path relative to the service cache directory with `/` separators and no `.json` suffix, so a nested key such as `session_web/<sha1>` lands in a subdirectory), `client_region`, `proxy_region`, `cdm_type`, `range_`, `vcodec`, `quality`, `best_available`, `dl_params`, `client`, and any service CLI options. `proxy_region` is the country code the client resolved `proxy` from; the server matches it against its own accounts. `client` is a freeform object the dashboard shows as sent (the CLI puts `version`, `code_hash`, `platform` and a redacted `argv` in it); the server ignores it above 4096 bytes of JSON.
Make a remote session for a service and title. Authentication runs asynchronously in the background. This call returns immediately with `status: "authenticating"`, and you then poll the prompt endpoint. The body accepts `service` and `title_id` (both required). It also accepts a broad set of optional keys, because the body allows `additionalProperties`. These are `session_id`, `credentials` (`{username, password, extra?}`), `cookies` (base64 of zlib-compressed Netscape cookie file), `proxy`, `no_proxy`, `profile`, `cache` (map of forwarded cache files, keyed by the file path relative to the service cache directory with `/` separators and no `.json` suffix, so a nested key such as `session_web/<sha1>` lands in a subdirectory), `client_region`, `proxy_region`, `cdm_type`, `range_`, `vcodec`, `quality`, `best_available`, `dl_params`, `plugins`, `client`, and any service CLI options. `plugins` maps the id of each DRM plugin that the client loads to `{version, device?}`; `device` holds the plain values of the device attributes that the plugin names in `device_facts`. The server refuses a title with a track of a plugin that is not in `plugins` (or a body with no `plugins`) on `POST /api/session/{id}/tracks` with `DRM_ERROR`, and gives `device` to the service only in a remote session that the client's device licenses. A `plugins` value over 16384 bytes of JSON, or of another shape, gets `INVALID_INPUT`. `proxy_region` is the country code the client resolved `proxy` from; the server matches it against its own accounts. `client` is a freeform object the dashboard shows as sent (the CLI puts `version`, `code_hash`, `platform` and a redacted `argv` in it); the server ignores it above 4096 bytes of JSON.
`session_id` is the ID that you give the remote session, so that you can delete it before this call answers. It must be the canonical text of a version 4 UUID. Without it, the server makes the ID. A remote session with your ID ends when you send no request for it and open no channel within 150s of the create. A second create with the same ID from the same API key and IP ends the first one if the first one has not answered, and replaces its remote session when the new one is stored. A second create that fails leaves that remote session open.
@@ -1262,7 +1262,7 @@ A slow answer arrives as a [slow response](#slow-responses).
| `track_id` / `track_ids` | Single track, or a batch of tracks. |
| `challenge` | Base64 CDM challenge (proxy mode). |
| `pssh` | Base64 PSSH. Server-CDM mode licenses this PSSH. Proxy mode gives it to the service licence callback as `pssh` (Widevine) or `pssh_b64` (PlayReady), the PSSH of the header the challenge is for. A proxy-mode PSSH that names a KID the track does not carry goes to no callback. |
| `drm_type` | `widevine` (default), `playready`, or the id of a DRM plugin that both peers load. In server-CDM mode the server's `cdm` mapping for the service decides the DRM system and the response `drm_type` names the system that licensed. A mapping with a device for each system takes the system of the device the remote session loaded. With no mapping, the client's value decides when the track carries that system; else a system the track carries decides, PlayReady first. The tracks response `server_cdm_type` names the system the same order gives for the title's tracks. A track whose DRM is a whole-file cipher takes `clearkeyctr` with no `pssh`: the service on the server licenses it. A track of a DRM plugin that licenses locally takes the plugin id with no `pssh` and `mode` `server_cdm`: the server answers in `keys` with the content key that its service licensed, and only in a session that uses the server CDM. |
| `drm_type` | `widevine` (default), `playready`, or the id of a DRM plugin that both peers load. In server-CDM mode the server's `cdm` mapping for the service decides the DRM system and the response `drm_type` names the system that licensed. A mapping with a device for each system takes the system of the device the remote session loaded. With no mapping, the client's value decides when the track carries that system; else a system the track carries decides, PlayReady first. The tracks response `server_cdm_type` names the system the same order gives for the title's tracks. A track whose DRM is a whole-file cipher takes `clearkeyctr` with no `pssh`: the service on the server licenses it. A track of a DRM plugin that licenses locally takes the plugin id with no `pssh` and `mode` `server_cdm`: the server answers in `keys` with the content key from a server vault or from a licence of its own plugin device, only in a session that uses the server CDM, and only under the licence cap (`SERVER_CDM_CAPPED` above it). |
| `mode` | `proxy` (default) or `server_cdm`. |
| `clear_tracks` (response) | Requested track ids that carry no DRM, so they have no keys. Absent when every requested track is encrypted. |
| `file_keys` (response) | Content keys of whole-file ciphers, by track id, for a single track and for a batch. Absent when no requested track holds such a cipher. |
+3 -1
View File
@@ -497,7 +497,9 @@ session when the new one is stored, and the server answers the ID of another API
`no_proxy`, `profile`, `cache` (a map of `filename → base64(zlib(bytes))`),
`client_region`, `server_cdm` (`false` when the user picked the local CDM), `cdm_type`, `cdm_security_level`, `cdm_relay` (`true` when the client
answers CDM calls; a plugin `cdm_type` gets no relay), `cdm_system_id` and `cdm_device_type` (Widevine only), `service_config`
(the identity config keys the service lists in `client_config`), `client` (a freeform identity
(the identity config keys the service lists in `client_config`), `plugins` (the version of each DRM plugin of the
client and the values of the plugin device attributes that the plugin names in `device_facts`; see
[endpoints](endpoints.md#post-apisessioncreate)), `client` (a freeform identity
object the dashboard shows as sent), and the track-selection hints `range_`, `vcodec`,
`quality`, `best_available`, `generate_dv`, plus arbitrary service CLI options
(`additionalProperties: true`).
+1 -1
View File
@@ -456,7 +456,7 @@ service to talk to the platform's license server. unshackle recognizes six DRM c
| `PlayReady` | PlayReady | CDM challenge (WRM header) → license server → content keys (`.prd` device) |
| `ClearKeyCENC` | W3C `org.w3.clearkey` or W3C common PSSH over CENC | JSON KID request → JWK set; no CDM |
| `ClearKey` | HLS AES-128 | content key fetched directly from a URI; no CDM, no challenge |
| `CustomDRM` | a system that a DRM plugin adds | `CustomDRM("<plugin id>", kids=..., data=...)`. For a plugin that holds its key, put the key in `data`. For a plugin that licenses locally, call `drm.license(cdm)` with a device of the plugin from `load_cdm`. The plugin decrypts. Its README names the `data` it reads |
| `CustomDRM` | a system that a DRM plugin adds | `CustomDRM("<plugin id>", kids=..., data=...)`. For a plugin that holds its key, put the key in `data`. For a plugin that licenses locally, put only the data the plugin reads: unshackle licenses it at the licence step. The plugin decrypts. Its README names the `data` it reads |
| `ClearKeyCTR` | AES-128-CTR over a whole file | the service gives the IV and licenses the content key at the licence step; no CDM, no license server |
!!! warning "`ClearKey` vs `ClearKeyCENC`"
+17 -7
View File
@@ -612,7 +612,8 @@ stops with `No DRM plugin '<id>' is installed`.
A plugin sets the facts of its system: its id, its label, how it gets the content key, and how it
decrypts. The service gives the content key of a plugin that holds its key. A plugin device licenses
a plugin that licenses locally. A plugin decrypts each segment and then the merged file, or the
a plugin that licenses locally, at the licence step of a download, after the vault lookup, as for a CDM
track: `--list` sends no licence, and `--vaults-only` and `--cdm-only` apply. A plugin decrypts each segment and then the merged file, or the
merged file once. The README of each plugin gives its device files, its tools and its limits.
- **Devices:** a plugin device file is `<name><suffix>`, with the suffix that the plugin sets. A plugin
@@ -622,12 +623,21 @@ merged file once. The README of each plugin gives its device files, its tools an
its [`cdm`](#selecting-which-device-to-use-the-cdm-config) entry names no device of that system.
To use another device, name it under the plugin id in the `cdm` mapping, as you name a device
under `widevine`.
- **`--remote`:** the server and each client must load the same plugin. The server sends the plugin
id, the KIDs, the label and the data that the plugin lets a peer carry; never a content key or a
path. A client without the plugin stops the title with `Unknown DRM type '<id>' from the server`.
The server sends the content key of a plugin DRM that licenses locally
only in a remote session that uses the server CDM. The server loads the plugin device, so a client
needs no device.
- **`--remote`:** the server and each client must load the same plugin. When a client opens a
remote session, it sends the id and the version of each plugin it loads. For a plugin device, it also sends
the values of the device attributes that the plugin names (for example the security level), never a
path or a device file. The server sends the plugin id, the KIDs, the label and the data that the
plugin lets a peer carry; never a content key or a path. The server refuses a title with a track of
a plugin that the client did not send with `This title needs the DRM plugin '<id>', which your
unshackle does not have`, before it sends the track list. A client that sends no plugin list (an
older unshackle) gets `This title needs the DRM plugin '<id>', and your unshackle sends no plugin
list`. In a remote session that the client's device licenses, the service on the server reads the
values that the client sent, so it picks the data that the client's device can license.
In a remote session that uses the server CDM, the server licenses a plugin DRM that licenses locally
with its own plugin device, under the licence cap of the API key. With `--cdm-only`, in a session
that the client licenses, and for a track above the cap, the client licenses with its own plugin
device. The plugin data can be bound to the device that the service on the server read, so a
different client device can fail to read it.
- **Export:** an export writes a plugin DRM under the plugin id, with the same fields as `--remote`.
An import without the plugin stops with `Unknown DRM system '<id>' in the export`.
- **Decode check:** FFmpeg checks the content key of a plugin DRM that licenses locally after the
+6 -4
View File
@@ -205,8 +205,10 @@ def test_a_served_service_gets_a_device_by_system_only_where_the_server_licenses
else:
launch_session("EXAMPLE", "t", {}, licensor=licensor)
cdm_for = seen["ctx"].obj.cdm_for
before = list(loads)
assert (cdm_for is not None) == served
if cdm_for:
cdm_for("example")
assert loads[-1] == ("EXAMPLE", None, "example")
gives = cdm_for("example") if cdm_for else None
assert (loads[len(before) :] == [("EXAMPLE", None, "example")]) == served
if not served:
assert gives is None
+101
View File
@@ -0,0 +1,101 @@
"""A plugin DRM licenses at the licence step of content-key resolution, like a CDM track: vaults first, then a device."""
from __future__ import annotations
from pathlib import Path
from types import SimpleNamespace
from typing import Any
from uuid import UUID
import click
import pytest
from tests.core.key_resolver import MemoryVault, key_table, resolver, vaults_of
from tests.drm_plugins import ExampleDevice
from unshackle.core.drm import CustomDRM
from unshackle.core.tracks import Video
from unshackle.core.tracks.track import Track
pytestmark = pytest.mark.unit
KID = UUID(hex="0123456789abcdef0123456789abcdef")
KEY = "5a" * 16
@pytest.fixture
def device(tmp_path: Path) -> ExampleDevice:
path = tmp_path / "EXAMPLE_DEVICE.exd"
path.write_bytes(bytes.fromhex(KEY))
return ExampleDevice(path)
def plugin_track(data: dict[str, Any] | None = None) -> Video:
drm = CustomDRM("example", data={"ticket": KID.hex} if data is None else data)
return Video(
id_="vid",
url="https://example.test/v.m3u8",
language="en",
descriptor=Track.Descriptor.HLS,
height=1080,
drm=[drm],
)
def run_licence(track: Video, vault: MemoryVault, device: Any, loads: list, **flags: Any) -> CustomDRM:
"""Run the licence step of ``track`` with ``vault``; ``loads`` records each device the run loads."""
def cdm_for(system: str, quality: int | None = None) -> Any:
loads.append((system, quality))
return device
keys = resolver(vaults_of(vault), cdm_for=cdm_for, **flags)
drm = track.drm[0]
keys.licence_for(track, SimpleNamespace(tracks=SimpleNamespace(videos=[track])), key_table())(drm)
keys.wait_vault_writes()
return drm
def test_the_drm_reads_its_kids_from_the_plugin_data_before_any_licence(example_plugins: None) -> None:
assert plugin_track().drm[0].kids == [KID]
def test_a_vault_key_stands_in_for_the_licence_and_loads_no_device(example_plugins: None, device: Any) -> None:
loads: list = []
drm = run_licence(plugin_track(), MemoryVault({KID: KEY}), device, loads)
assert drm.content_keys == {KID: KEY} and loads == []
def test_a_vault_miss_licenses_with_the_plugin_device_and_stores_the_key(example_plugins: None, device: Any) -> None:
loads: list = []
vault = MemoryVault()
drm = run_licence(plugin_track(), vault, device, loads)
assert drm.content_keys == {KID: KEY} and loads == [("example", None)]
assert vault.asked == [KID] and vault.added == {KID: KEY}
def test_vaults_only_stops_a_miss_before_the_device(example_plugins: None, device: Any) -> None:
loads: list = []
with pytest.raises(click.ClickException, match=f"^No Vault has a Key for {KID.hex} and --vaults-only was used$"):
run_licence(plugin_track(), MemoryVault(), device, loads, vaults_only=True)
assert loads == []
def test_cdm_only_licenses_with_the_device_and_asks_no_vault(example_plugins: None, device: Any) -> None:
loads: list = []
vault = MemoryVault({KID: "00" * 16})
drm = run_licence(plugin_track(), vault, device, loads, cdm_only=True)
assert drm.content_keys == {KID: KEY} and vault.asked == [] and loads == [("example", None)]
def test_a_run_without_a_plugin_device_stops_the_track_with_one_line(example_plugins: None) -> None:
with pytest.raises(click.ClickException, match="^No EXAMPLE device to license track vid$"):
run_licence(plugin_track(), MemoryVault(), None, [])
def test_a_drm_whose_data_names_no_kid_stops_the_track_with_one_line(example_plugins: None, device: Any) -> None:
with pytest.raises(click.ClickException, match="^The EXAMPLE DRM of track vid names no KID$"):
run_licence(plugin_track({}), MemoryVault(), device, [])
+12 -4
View File
@@ -1074,8 +1074,10 @@ def every_drm() -> list:
def local_plugin_drm() -> CustomDRM:
"""A plugin DRM that a device licensed: its content key and its ticket never leave the machine."""
drm = CustomDRM("example", kids=[VIDEO_KID], display_id="EXAMPLE-1", data={"ticket": "server only"})
"""A plugin DRM that a device licensed: its ticket crosses as licence data, its content key and its other data never do."""
drm = CustomDRM(
"example", kids=[VIDEO_KID], display_id="EXAMPLE-1", data={"ticket": VIDEO_KID.hex, "secret": "server only"}
)
drm.content_keys[VIDEO_KID] = VIDEO_KEY
return drm
@@ -1085,7 +1087,13 @@ def test_rest_drm_of_each_system(example_plugins: None) -> None:
assert serialize_drm(drm) == [
*REST_VIDEO["drm"],
{"type": "other", "kids": [], "label": "OTHER", "data": {"key": HELD_KEY.hex()}},
{"type": "example", "kids": [VIDEO_KID.hex], "label": "EXAMPLE", "display_id": "EXAMPLE-1"},
{
"type": "example",
"kids": [VIDEO_KID.hex],
"label": "EXAMPLE",
"display_id": "EXAMPLE-1",
"data": {"ticket": VIDEO_KID.hex},
},
{
"type": "clearkeyctr",
"key": HELD_KEY.hex(),
@@ -1129,7 +1137,7 @@ def test_reconstruct_rest_drm(example_plugins: None) -> None:
"label": "EXAMPLE",
"kids": [VIDEO_KID.hex],
"display_id": "EXAMPLE-1",
"data": {},
"data": {"ticket": VIDEO_KID.hex},
},
{"class": "ClearKeyCTR", "kids": [], "content_keys": {}},
]
+9
View File
@@ -37,6 +37,11 @@ def licence(drm: CustomDRM, cdm: ExampleDevice) -> None:
drm.content_keys[kid] = cdm.path.read_bytes().hex()
def kids(drm: CustomDRM) -> list[UUID]:
"""The EXAMPLE ticket is the hex of its KID."""
return [UUID(hex=drm.data["ticket"])] if "ticket" in drm.data else []
def finish(drm: CustomDRM, path: Path, track: Any) -> bool:
FINISHED.append(path)
return True
@@ -61,8 +66,12 @@ EXAMPLE = DrmPlugin(
decrypt=decrypt,
finish=finish,
licence=licence,
kids=kids,
wire_data=("ticket",),
device_suffix=".exd",
load_device=ExampleDevice,
version="1.0",
device_facts=("device_name",),
)
OTHER = DrmPlugin(
id="other",
+109 -27
View File
@@ -1,7 +1,9 @@
"""A plugin DRM HLS track over --remote: the server licenses with the DRM its service built, the client decrypts it.
"""A plugin DRM HLS track over --remote: the licence runs at the licence step, on the server or on the client.
The service builds the DRM on the server; only its KIDs, label and display id cross with the track list, and the
content key comes through the licence route. The client decrypts each segment with its own copy of the plugin.
The service records only the plugin data (a ticket) on the DRM; its KIDs, label, display id and the data the plugin
lets a peer carry cross with the track list. The server licenses with its own plugin device under the Licensing mode
and the Licence cap, as for a CDM track; a client-device session, --cdm-only and a refused track license with the
client's own plugin device. The client decrypts each segment with its own copy of the plugin.
"""
from __future__ import annotations
@@ -18,13 +20,14 @@ import pytest
import requests
from tests.core.key_resolver import MemoryVault, key_table, resolver, vaults_of
from tests.drm_plugins import FINISHED, xor
from tests.drm_plugins import FINISHED, ExampleDevice, xor
from tests.remote.key_source import one_title, remote_session
from tests.remote.sessions import session_entry
from unshackle.core import plugins
from unshackle.core.api import handlers, server_keys
from unshackle.core.api.errors import APIError
from unshackle.core.api.key_policy import KeyPolicy
from unshackle.core.cdm.detect import cdm_type_stub
from unshackle.core.constants import DOWNLOAD_CANCELLED
from unshackle.core.drm import CustomDRM
from unshackle.core.manifests.hls import HLS
@@ -51,45 +54,67 @@ def cancel_flag() -> Iterator[None]:
DOWNLOAD_CANCELLED.clear()
@pytest.fixture
def device(tmp_path: Path) -> ExampleDevice:
"""An EXAMPLE device whose licence gives KEY."""
path = tmp_path / "EXAMPLE_DEVICE.exd"
path.write_bytes(bytes.fromhex(KEY))
return ExampleDevice(path)
@pytest.fixture
def server_track(example_plugins: None) -> Video:
"""The track the service built on the server: its plugin DRM holds the content key and a server-only ticket."""
drm = CustomDRM("example", kids=[KID], display_id="EXAMPLE-1", data={"ticket": "EXAMPLE-TICKET"})
drm.content_keys[KID] = KEY
"""The track the service built on the server: its plugin DRM holds the ticket and no content key."""
drm = CustomDRM("example", display_id="EXAMPLE-1", data={"ticket": KID.hex})
track = Video(
id_="vid",
url="https://example.test/seg0.ts",
language="en",
descriptor=Track.Descriptor.HLS,
codec=Video.Codec.HEVC,
height=2160,
drm=[drm],
)
track.data["hls"] = {"playlist_text": PLAYLIST}
return track
def server_of(track: Video, licensor: Licensor = Licensor.SERVER_CDM) -> Any:
"""A remote session on the server that holds the track."""
service = SimpleNamespace(fairplay_bridge=lambda: None, session=None)
return session_entry(service_instance=service, tracks={"vid": track}, licensing=LicensingMode(licensor))
def devices(device: Any) -> Any:
"""A cdm_for that gives ``device`` for its plugin system and a stub of any other system."""
return lambda system, quality=None: device if system == "example" else cdm_type_stub(system)
def client_of(server: Any, posts: list[dict]) -> Any:
def server_of(track: Video, licensing: LicensingMode | Licensor = Licensor.SERVER_CDM, device: Any = None) -> Any:
"""A remote session on the server that holds the track, whose service gets ``device`` for the plugin."""
obj = SimpleNamespace(cdm_for=devices(device) if device else None)
service = SimpleNamespace(fairplay_bridge=lambda: None, session=None, ctx=SimpleNamespace(obj=obj))
mode = licensing if isinstance(licensing, LicensingMode) else LicensingMode(licensing)
return session_entry(service_instance=service, tracks={"vid": track}, licensing=mode)
def client_of(server: Any, posts: list[dict], device: Any = None) -> Any:
"""A client of the server session whose licence requests run the licence route of the server."""
remote = remote_session(None, {})
remote.licensing = server.licensing
remote.ctx.obj.cdm_for = devices(device) if device else None
def post(endpoint: str, payload: dict, expect: Any = ()) -> dict:
posts.append(payload)
return json.loads(handlers.license_response(payload, server, "sess", None).text)
try:
return json.loads(handlers.license_response(payload, server, "sess", None).text)
except APIError as e:
if e.error_code not in expect:
raise
return {"error_code": e.error_code, "details": e.details}
remote.client = SimpleNamespace(post=post)
return remote
def track_list(track: Video) -> str:
"""The track list entry of the server, which never holds the content key or the ticket."""
"""The track list entry of the server: the ticket crosses as licence data, the content key never does."""
payload = json.dumps(serialize_video_track(track, include_url=True))
assert KEY not in payload and "EXAMPLE-TICKET" not in payload
assert KEY not in payload
return payload
@@ -124,13 +149,14 @@ def download(track: Video, tmp_path: Path, licence: Any, downloader: Any = segme
def test_the_batch_licence_keys_the_client_copy_and_the_client_plugin_decrypts(
server_track: Video, tmp_path: Path
server_track: Video, device: ExampleDevice, tmp_path: Path
) -> None:
posts: list[dict] = []
remote = client_of(server_of(server_track), posts)
server = server_of(server_track, device=device)
remote = client_of(server, posts)
track = rebuilt(server_track)
drm = track.drm[0]
assert isinstance(drm, CustomDRM) and (drm.kid, drm.key, drm.data) == (KID, None, {})
assert isinstance(drm, CustomDRM) and (drm.kid, drm.key, drm.data) == (KID, None, {"ticket": KID.hex})
vault = MemoryVault()
keys = resolver(vaults_of(vault))
@@ -142,12 +168,15 @@ def test_the_batch_licence_keys_the_client_copy_and_the_client_plugin_decrypts(
assert download(track, tmp_path, keys.licence_for(track, title, key_table())) == b"".join(PLAIN)
assert [post.get("track_ids") for post in posts] == [["vid"]]
assert vault.added == {KID: KEY}
assert server.served_keys == {KID.hex: (KEY, "cdm")}
assert FINISHED == [tmp_path / "video.ts"]
def test_a_track_the_batch_did_not_key_asks_the_licence_route_for_it(server_track: Video, tmp_path: Path) -> None:
def test_a_track_the_batch_did_not_key_asks_the_licence_route_for_it(
server_track: Video, device: ExampleDevice, tmp_path: Path
) -> None:
posts: list[dict] = []
remote = client_of(server_of(server_track), posts)
remote = client_of(server_of(server_track, device=device), posts)
track = rebuilt(server_track)
keys = resolver()
keys.source = remote
@@ -158,35 +187,88 @@ def test_a_track_the_batch_did_not_key_asks_the_licence_route_for_it(server_trac
assert posts == [{"drm_type": "example", "mode": "server_cdm", "track_id": "vid"}]
def test_the_licence_cap_refuses_a_plugin_track_above_it(server_track: Video, device: ExampleDevice) -> None:
"""A content key the service already holds, as one that licensed while it listed the tracks, stays behind the cap."""
server_track.drm[0].license(device)
server = server_of(server_track, LicensingMode(Licensor.SERVER_CDM, max_height=1080), device)
batch = server_keys.resolve_batch(server, ["vid"], "widevine", KeyPolicy())
assert batch.keys == {} and batch.capped_tracks["vid"]["max_height"] == 1080
with pytest.raises(APIError) as e:
handlers.license_response(
{"mode": "server_cdm", "drm_type": "example", "track_id": "vid"}, server, "sess", None
)
assert e.value.error_code is APIErrorCode.SERVER_CDM_CAPPED
assert not server.served_keys
def test_a_track_above_the_cap_licenses_with_the_client_plugin_device(
server_track: Video, device: ExampleDevice, tmp_path: Path
) -> None:
posts: list[dict] = []
server = server_of(server_track, LicensingMode(Licensor.SERVER_CDM, max_height=1080), device)
remote = client_of(server, posts, device)
track = rebuilt(server_track)
keys = resolver(cdm_for=devices(device))
keys.source = remote
title = one_title(track)
keys.take_server_keys(title) # type: ignore[arg-type]
assert download(track, tmp_path, keys.licence_for(track, title, key_table())) == b"".join(PLAIN)
assert remote.licenses_locally(track) and not server.served_keys
def test_cdm_only_licenses_a_plugin_track_with_the_client_plugin_device(
server_track: Video, device: ExampleDevice, tmp_path: Path
) -> None:
posts: list[dict] = []
server = server_of(server_track, Licensor.CLIENT_DEVICE)
remote = client_of(server, posts, device)
track = rebuilt(server_track)
vault = MemoryVault({KID: "00" * 16})
keys = resolver(vaults_of(vault), cdm_for=devices(device), cdm_only=True)
keys.source = remote
title = one_title(track)
keys.take_server_keys(title) # type: ignore[arg-type]
assert download(track, tmp_path, keys.licence_for(track, title, key_table())) == b"".join(PLAIN)
assert posts == [] and vault.asked == []
@pytest.mark.parametrize("licensor", [Licensor.CLIENT_DEVICE, Licensor.LENT_DEVICE])
def test_the_server_gives_no_key_outside_a_server_cdm_session(server_track: Video, licensor: Licensor) -> None:
server = server_of(server_track, licensor)
def test_the_server_gives_no_key_outside_a_server_cdm_session(
server_track: Video, device: ExampleDevice, licensor: Licensor
) -> None:
server = server_of(server_track, licensor, device)
assert server_keys.resolve_batch(server, ["vid"], "widevine", KeyPolicy()).keys == {}
with pytest.raises(APIError, match="not enabled"):
handlers.license_response(
{"mode": "server_cdm", "drm_type": "example", "track_id": "vid"}, server, "sess", None
)
assert not server.served_keys
assert not server.served_keys and not server_track.drm[0].content_keys
def test_a_client_device_session_decrypts_with_the_key_of_a_client_vault(server_track: Video, tmp_path: Path) -> None:
remote = client_of(server_of(server_track, Licensor.CLIENT_DEVICE), [])
track = rebuilt(server_track)
keys = resolver(vaults_of(MemoryVault({KID: KEY})))
keys = resolver(vaults_of(MemoryVault({KID: KEY})), cdm_for=lambda *_: pytest.fail("a device was loaded"))
keys.source = remote
assert download(track, tmp_path, keys.licence_for(track, one_title(track), key_table())) == b"".join(PLAIN)
def test_a_refused_licence_stops_the_track_before_its_segments(server_track: Video, tmp_path: Path) -> None:
def test_a_client_without_a_plugin_device_stops_the_track_before_its_segments(
server_track: Video, tmp_path: Path
) -> None:
remote = client_of(server_of(server_track, Licensor.CLIENT_DEVICE), [])
track = rebuilt(server_track)
keys = resolver()
keys = resolver(cdm_for=lambda *_: None)
keys.source = remote
licence = keys.licence_for(track, one_title(track), key_table())
with pytest.raises(click.ClickException, match="^The server sent no EXAMPLE content key for track vid$"):
with pytest.raises(click.ClickException, match="^No EXAMPLE device to license track vid$"):
download(track, tmp_path, licence, lambda **_: pytest.fail("a segment was requested"))
@@ -169,6 +169,7 @@ def test_session_transport_keys_are_the_create_body():
"best_available",
"generate_dv",
"dl_params",
"plugins",
}
@@ -737,7 +737,7 @@ def _sent_create_data(parent_params: dict, service_params: dict) -> dict:
def test_open_session_posts_what_session_request_builds() -> None:
parent = {"profile": "work", "lang": ["en"], "range_": [Video.Range.DV], "quality": [1080]}
data = _sent_create_data(parent, {"lang": 3})
sent = {k: v for k, v in data.items() if k not in ("service", "title_id", "client", "session_id")}
sent = {k: v for k, v in data.items() if k not in ("service", "title_id", "client", "session_id", "plugins")}
assert sent == session_request({"no_proxy": True, **parent}, {"lang": 3})
assert sent["dl_params"]["lang"] == ["en"]
+1 -1
View File
@@ -326,7 +326,7 @@ async def test_every_response_carries_a_generic_server_header(make_app, aiohttp_
async def test_services_load_errors_go_to_the_admin_key_only(
make_app, aiohttp_client, monkeypatch: pytest.MonkeyPatch
make_app, aiohttp_client, monkeypatch: pytest.MonkeyPatch, example_service: None
) -> None:
from unshackle.core import services as services_module
from unshackle.core.api import routes
+260
View File
@@ -0,0 +1,260 @@
"""The remote session names the client's DRM plugins: the server refuses a title the client cannot decrypt before it
lists the tracks, and a stand-in of the client's plugin device carries the device facts the client sent.
"""
from __future__ import annotations
import asyncio
import json
from pathlib import Path
from types import SimpleNamespace
from typing import Any
import click
import pytest
from tests.drm_plugins import ExampleDevice
from tests.remote.key_source import remote_session
from tests.remote.sessions import launch_session, stub_service_build
from unshackle.core.api import handlers, key_policy
from unshackle.core.api import session_store as store_mod
from unshackle.core.api.errors import APIError
from unshackle.core.cdm.detect import cdm_system
from unshackle.core.drm import CustomDRM
from unshackle.core.remote_protocol import APIErrorCode, Licensor
from unshackle.core.tracks import Tracks, Video
from unshackle.core.tracks.track import Track
pytestmark = [pytest.mark.unit, pytest.mark.usefixtures("example_plugins")]
DEVICE_FACTS = {"device_name": "EXAMPLE_DEVICE"}
WIDEVINE_CDM = SimpleNamespace(is_playready=False)
class _SentCreate(Exception):
pass
def sent_create(cdm_for: Any, local_cdm: Any = WIDEVINE_CDM) -> dict:
"""The session create body that a client whose ``cdm_for`` gives its plugin devices sends."""
def post(path: str, data: dict) -> dict:
raise _SentCreate(data)
svc = remote_session(local_cdm, {})
svc.ctx.obj.cdm_for = cdm_for
svc.ctx.obj.cdm_entry = False
svc.licensing = None
svc._server_cdm_request = None
svc.service_tag = "EXAMPLE"
svc.title_id = "t1"
svc._server_accounts = {"global": True}
svc._service_params = {}
svc._client_config = None
svc.ctx.parent = SimpleNamespace(params={"no_proxy": True})
svc.client = SimpleNamespace(post=post)
with pytest.raises(_SentCreate) as exc:
svc.authenticate()
return exc.value.args[0]
def test_the_create_body_lists_each_plugin_with_its_version_and_device_facts(tmp_path: Path) -> None:
path = tmp_path / "EXAMPLE_DEVICE.exd"
path.write_bytes(b"\x5a")
device = ExampleDevice(path)
data = sent_create(lambda system, quality=None: device if system == "example" else None)
assert data["plugins"] == {"example": {"version": "1.0", "device": DEVICE_FACTS}, "other": {"version": ""}}
assert str(tmp_path) not in json.dumps(data["plugins"])
def test_a_client_with_no_local_device_sends_no_device_facts() -> None:
data = sent_create(lambda system, quality=None: pytest.fail("a device was loaded"), local_cdm=None)
assert data["plugins"] == {"example": {"version": "1.0"}, "other": {"version": ""}}
def test_a_plugin_device_that_does_not_load_sends_no_facts(caplog: pytest.LogCaptureFixture) -> None:
def broken(system: str, quality: int | None = None) -> Any:
raise ValueError("EXAMPLE device file is damaged")
data = sent_create(broken)
assert data["plugins"] == {"example": {"version": "1.0"}, "other": {"version": ""}}
assert "EXAMPLE device file is damaged" in caplog.text
@pytest.mark.parametrize(
"plugins",
[
["example"],
{"example": "1.0"},
{"example": {"version": 1}},
{"example": {"device": ["v5"]}},
{"example": {"device": {"name": {"nested": True}}}},
{"example": {"device": {"name": ["v5"]}}},
{"example": {"device": {"blob": "x" * 20000}}},
],
)
def test_a_malformed_plugin_list_is_refused(plugins: Any) -> None:
with pytest.raises(APIError) as e:
handlers.client_plugins(plugins)
assert e.value.error_code == APIErrorCode.INVALID_INPUT
def test_an_old_client_sends_no_plugin_list() -> None:
assert handlers.client_plugins(None) is None
assert handlers.client_plugins({"example": {"version": "1.0"}}) == {"example": {"version": "1.0"}}
assert handlers.client_plugins({"example": {"device": {"name": None}}}) == {"example": {"device": {"name": None}}}
def plugin_tracks() -> Tracks:
track = Video(
id_="vid",
url="https://example.test/seg0.ts",
language="en",
descriptor=Track.Descriptor.HLS,
codec=Video.Codec.HEVC,
height=2160,
drm=[CustomDRM("example", data={"ticket": "00" * 16})],
)
return Tracks([track])
def tracks_reply(client_plugins: Any) -> tuple[Any, Any]:
"""The answer of the tracks route for a title with an EXAMPLE plugin track (its body or its APIError), and the session."""
class StubService:
session = SimpleNamespace(headers={}, cookies=[])
def fairplay_bridge(self) -> None:
return None
def get_tracks(self, title: Any) -> Tracks:
return plugin_tracks()
def get_chapters(self, title: Any) -> list:
return []
def decrypts_samples(self, track: Any) -> bool:
return False
async def run() -> tuple[Any, Any]:
store = store_mod.get_session_store()
entry = await store.create(
service_tag="EXAMPLE",
service_instance=StubService(),
session_id="plugins",
client_plugins=client_plugins,
)
entry.title_map = {"t1": "EXAMPLE title"}
try:
resp = await handlers.session_tracks_handler({"title_id": "t1"}, "plugins")
answer: Any = json.loads(resp.text)
except APIError as e:
answer = e
finally:
await store.delete("plugins")
return answer, entry
return asyncio.run(run())
@pytest.mark.parametrize(
("client_plugins", "message"),
[
(None, "This title needs the DRM plugin 'example', and your unshackle sends no plugin list"),
({"other": {"version": ""}}, "This title needs the DRM plugin 'example', which your unshackle does not have"),
],
)
def test_a_client_that_cannot_decrypt_the_title_is_refused_before_the_track_list(
client_plugins: Any, message: str
) -> None:
refusal, entry = tracks_reply(client_plugins)
assert isinstance(refusal, APIError)
assert (refusal.error_code, refusal.message) == (APIErrorCode.DRM_ERROR, message)
assert entry.tracks == {}
def test_a_client_with_the_plugin_gets_the_track_list() -> None:
body, entry = tracks_reply({"example": {"version": "1.0"}})
assert [track["id"] for track in body["video"]] == ["vid"]
assert list(entry.tracks) == ["vid"]
def test_the_create_route_keeps_the_client_plugin_list(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
class Service:
_input_bridge = None
log = None
cache = None
def authenticate(self, cookies: Any, credential: Any) -> None:
pass
monkeypatch.setattr(handlers.config.directories, "cache", tmp_path)
monkeypatch.setattr(handlers, "validate_service", lambda service, request=None: service)
monkeypatch.setattr(handlers, "resolve_handler_proxy", lambda *args: (None, []))
monkeypatch.setattr(handlers, "server_account_for", lambda *args: False)
monkeypatch.setattr(handlers.Services, "load", lambda service: Service)
stub_service_build(monkeypatch, Service)
listed = {"example": {"version": "1.0", "device": DEVICE_FACTS}}
async def run() -> Any:
resp = await handlers.session_create_handler({"service": "EXAMPLE", "title_id": "t", "plugins": listed})
session_id = json.loads(resp.body)["session_id"]
entry = store_mod.get_session_store().peek(session_id)
await store_mod.get_session_store().delete(session_id)
return entry
assert asyncio.run(run()).client_plugins == listed
def launched_cdm_for(monkeypatch: pytest.MonkeyPatch, licensor: Licensor, client_plugins: Any) -> Any:
"""The ``cdm_for`` that the service of a remote session gets on the server."""
seen: dict[str, Any] = {}
monkeypatch.setattr(key_policy, "load_service_config", lambda tag: {})
monkeypatch.setattr(handlers, "load_full_cdm", lambda service, profile, cdm_type, cfg: f"server {cdm_type}")
monkeypatch.setattr(handlers.Services, "load", lambda tag: SimpleNamespace())
def instantiate(parent_ctx: click.Context, *rest: Any) -> Any:
seen["cdm_for"] = parent_ctx.obj.cdm_for
return SimpleNamespace()
monkeypatch.setattr(handlers, "instantiate_service", instantiate)
launch_session("EXAMPLE", "t", {"cdm_type": "widevine"}, licensor=licensor, client_plugins=client_plugins)
return seen["cdm_for"]
def test_a_client_device_session_gives_the_service_a_stand_in_with_the_client_device_facts(
monkeypatch: pytest.MonkeyPatch,
) -> None:
sent = {"example": {"version": "1.0", "device": {**DEVICE_FACTS, "path": "/client/EXAMPLE_DEVICE.exd"}}}
cdm_for = launched_cdm_for(monkeypatch, Licensor.CLIENT_DEVICE, sent)
stub = cdm_for("example")
assert cdm_system(stub) == "example"
assert stub.device_name == "EXAMPLE_DEVICE"
assert not hasattr(stub, "path")
assert cdm_for("other") is None
assert cdm_for("unknown") is None
assert cdm_system(cdm_for("widevine")) == "widevine"
assert cdm_for("playready") is None
def test_a_fact_the_client_did_not_send_is_none_on_the_stand_in(monkeypatch: pytest.MonkeyPatch) -> None:
cdm_for = launched_cdm_for(monkeypatch, Licensor.CLIENT_DEVICE, {"example": {"version": "1.0", "device": {}}})
assert cdm_for("example").device_name is None
def test_a_client_device_session_with_no_device_facts_gives_no_plugin_device(monkeypatch: pytest.MonkeyPatch) -> None:
cdm_for = launched_cdm_for(monkeypatch, Licensor.CLIENT_DEVICE, {"example": {"version": "1.0"}})
assert cdm_for("example") is None
def test_a_server_cdm_session_keeps_the_server_device(monkeypatch: pytest.MonkeyPatch) -> None:
sent = {"example": {"version": "1.0", "device": DEVICE_FACTS}}
cdm_for = launched_cdm_for(monkeypatch, Licensor.SERVER_CDM, sent)
assert cdm_for("example") == "server example"
+65 -9
View File
@@ -49,7 +49,7 @@ from unshackle.core.api.session_store import (
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_type_stub
from unshackle.core.cdm.detect import cdm_system, cdm_type_stub
from unshackle.core.cdm.loader import default_device, device_system
from unshackle.core.config import config
from unshackle.core.dl_options import DEFAULT_DOWNLOAD_PARAMS
@@ -58,10 +58,12 @@ 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.remote_protocol import (
DEVICE_FACT_TYPES,
HEALTH_ROUTE,
APIErrorCode,
AuthStatus,
BadKeyReport,
ClientPlugin,
LicenseReply,
LicenseRequest,
LicensingMode,
@@ -85,6 +87,7 @@ from unshackle.core.services import Services
from unshackle.core.session import RnetSession
from unshackle.core.title_source import service_licence
from unshackle.core.titles import Episode, Song
from unshackle.core.tracks import Tracks
from unshackle.core.tunnel import (
HEARTBEAT,
MAX_MESSAGE,
@@ -849,6 +852,7 @@ class SessionLaunch:
licensing: LicensingMode
input_bridge: InputBridge
cache_dir: str
client_plugins: dict[str, ClientPlugin] | None = None
class Launched(NamedTuple):
@@ -924,6 +928,18 @@ def launch_served(
"""The server's device of ``system``, for a service that licenses with it itself, as a plugin DRM does."""
return load_full_cdm(service, profile, system, key_config)
listed_plugins = (session.client_plugins if session else None) or {}
def client_cdm_for(system: str, quality: int | None = None) -> Any:
"""A stand-in of the client's device of the plugin ``system``, with the device facts the client sent.
A built-in system gets the session's device when it is of that system, as ``ctx.obj.cdm`` holds it.
"""
if not plugins.get(system):
return cdm if cdm_system(cdm) == system else None
device = listed_plugins.get(system, {}).get("device")
return None if device is None else cdm_type_stub(system, facts=device)
anonymous = purpose == SEARCH and getattr(service_module, "ANONYMOUS_SEARCH", False)
cookies, credential = (
(None, None) if anonymous else server_login_material(data, service, account, profile, session is not None)
@@ -941,7 +957,7 @@ def launch_served(
cdm=cdm,
proxy_providers=proxy_providers,
profile=profile,
cdm_for=server_cdm_for if server_licenses else None,
cdm_for=server_cdm_for if server_licenses else client_cdm_for if session else None,
),
data,
keys,
@@ -2815,6 +2831,43 @@ def client_config_overlay(
return merged, identity
MAX_CLIENT_PLUGINS_BYTES = 16384
def client_plugins(listed: Any) -> dict[str, ClientPlugin] | None:
"""The DRM plugins that a remote client listed when it created the remote session; None for a client too old to list them."""
if listed is None:
return None
def well_formed(entry: Any) -> bool:
device = entry.get("device", {}) if isinstance(entry, dict) else None
return (
isinstance(device, dict)
and isinstance(entry.get("version", ""), str)
and all(isinstance(value, DEVICE_FACT_TYPES) for value in device.values())
)
if not (
isinstance(listed, dict)
and all(map(well_formed, listed.values()))
and len(json.dumps(listed)) <= MAX_CLIENT_PLUGINS_BYTES
):
raise APIError(
APIErrorCode.INVALID_INPUT,
f"plugins must be an object of plugin versions and device facts under {MAX_CLIENT_PLUGINS_BYTES} bytes",
)
return listed
def refuse_missing_plugins(session: Any, tracks: Tracks) -> None:
"""Refuse a title with a plugin DRM track that the remote client cannot decrypt, before its track list goes out."""
listed = session.client_plugins
needed = {drm.plugin_id for t in [*tracks.videos, *tracks.audio] if (drm := custom_drm(t))}
if missing := sorted(needed - set(listed or ())):
why = "and your unshackle sends no plugin list" if listed is None else "which your unshackle does not have"
raise APIError(APIErrorCode.DRM_ERROR, f"This title needs the DRM plugin {missing[0]!r}, {why}")
def client_device_cdm(
data: dict[str, Any], input_bridge: InputBridge | None, server_device: Callable[[], Any] | None = None
) -> Any:
@@ -2933,12 +2986,13 @@ async def create_session(
log.info(f"Using server account '{sanitize_log(profile or 'default')}' for {normalized_service}")
licensing = session_licensing(policy, normalized_service, data)
listed_plugins = client_plugins(data.get("plugins"))
bridge = InputBridge()
log_buffer = None if server_account else SessionLogBuffer()
service_class_name = getattr(Services.load(normalized_service), "__name__", normalized_service)
purpose = SessionLaunch(
(proxy_param, proxy_providers), policy, server_account, licensing, bridge, session_cache_dir
(proxy_param, proxy_providers), policy, server_account, licensing, bridge, session_cache_dir, listed_plugins
)
def build_service() -> Launched:
@@ -2972,6 +3026,7 @@ async def create_session(
input_bridge=bridge,
log_buffer=log_buffer,
pending=pending,
client_plugins=listed_plugins,
)
if store.peek(session_id) is not session:
pending.refuse()
@@ -3154,6 +3209,7 @@ async def session_tracks_handler(
finally:
session.touch()
refuse_missing_plugins(session, tracks)
session.add_tracks(str(title_id), tracks)
SessionStore.publish_update(session)
@@ -3201,6 +3257,8 @@ async def session_tracks_handler(
)
return web.json_response({**reply, **snapshot, **session_fields})
except APIError:
raise
except (Exception, SystemExit) as e:
log.exception(f"Error getting tracks for title {sanitize_log(title_id)}")
debug_mode = request.app.get("debug_api", False) if request else False
@@ -3664,12 +3722,10 @@ def license_response(data: LicenseRequest, session: Any, session_id: str, reques
service = session.service_instance
custom = custom_drm(track)
if custom is not None and device_licensed(custom) and mode == "server_cdm":
if vault_only:
raise APIError(
APIErrorCode.FORBIDDEN, "Server licensing is not enabled for this session on this service"
)
return web.json_response(LicenseReply(keys=server_keys.served_custom_keys(session, custom)))
if device_licensed(custom) and mode == "server_cdm":
plugin_sources: dict[str, str] = {}
keys = server_keys.plugin_keys(session, track, custom, plugin_sources)
return web.json_response(LicenseReply(keys=keys, vault_keys=list(plugin_sources)))
cipher = whole_file_cipher(track)
if cipher is not None and (mode == "server_cdm" or cipher.key is not None):
+23
View File
@@ -2103,6 +2103,25 @@ async def session_create(request: web.Request) -> web.Response:
description: |
The client's own identity config for the service. The server takes only the keys
the service lists in `client_config`, and only when the client's device licenses.
plugins:
type: object
description: |
The client's DRM plugins by id. A client that sends none gets no track list for a
title with a plugin DRM track. A value over 16384 bytes of JSON, or of another
shape, is INVALID_INPUT.
additionalProperties:
type: object
properties:
version:
type: string
device:
type: object
additionalProperties: true
description: |
The plain values of the device attributes that the plugin names in
`device_facts`, from the plugin device that the client licenses with.
The server gives them to the service only in a remote session that the
client's device licenses.
client:
type: object
additionalProperties: true
@@ -2280,6 +2299,10 @@ async def session_tracks(request: web.Request) -> web.Response:
arrives as the error body with status 200.
'404':
description: Remote session or title not found
'422':
description: >-
DRM_ERROR when a track of the title needs a DRM plugin that the client did not list in
`plugins` when it created the remote session, or the client sent no `plugins` list.
"""
session_id = request.match_info["session_id"]
data = await json_body(request)
+44 -10
View File
@@ -15,7 +15,7 @@ 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.detect import cdm_system, plugin_device
from unshackle.core.cdm.loader import device_system
from unshackle.core.drm import CustomDRM, custom_drm, device_licensed, held_key, is_null_key, whole_file_cipher
from unshackle.core.drm.discovery import drm_from_init_segment, ensure_track_drm, fetch_init_segment, track_pssh
@@ -479,10 +479,35 @@ def note_served_keys(session: Any, keys: dict[str, str], sources: dict[str, str]
session.served_keys[kid] = (key, sources.get(kid, "cdm"))
def served_custom_keys(session: Any, drm: CustomDRM) -> dict[str, str]:
"""The content keys of a plugin DRM the service licensed on the server, recorded as served by its device."""
keys = {kid.hex: key for kid, key in drm.content_keys.items()}
note_served_keys(session, keys, {})
def plugin_keys(
session: Any, track: Any, drm: CustomDRM, sources: dict[str, str], shared: dict[str, Any] | None = None
) -> dict[str, str]:
"""The content keys of a plugin DRM track: a server vault that holds its KIDs, else a licence with the server's
device of the plugin, which the service gets through ``cdm_for``.
It raises the refusal of ``live_licence_refusal`` before a live licence, as for a CDM track, and records the
keys as served. ``sources`` gets the vault name of each content key a server vault supplied. A licence content key
is not cached to the server vaults: it is unproven until the client decodes the track.
"""
service = session.service_instance
if drm.kids and (hit := check_vaults(drm.kids, service.__class__.__name__, shared=shared)):
keys, found = hit
sources.update(found)
else:
if refusal := live_licence_refusal(session, track):
raise refusal
cdm = once(
{} if shared is None else shared,
("plugin device", drm.plugin_id),
lambda: plugin_device(service.ctx.obj.cdm_for, drm.plugin_id),
)
if cdm is None:
raise APIError(APIErrorCode.DRM_ERROR, f"The server has no {drm.label} device for this service")
drm.license(cdm)
keys = {kid.hex: key for kid, key in drm.content_keys.items() if not is_null_key(key)}
if not keys:
raise APIError(APIErrorCode.NO_CONTENT, f"The {drm.label} licence returned no content keys")
note_served_keys(session, keys, sources)
return keys
@@ -632,9 +657,9 @@ class BatchKeys:
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 of a locally licensed plugin DRM gets the key of the DRM its
service built, in a server CDM session only. A track without a licensed DRM, or with a plugin DRM that holds its
content key, is listed as clear, and a track the server must not license live is listed as capped with its refusal details.
A whole-file cipher track gets its file key; a track of a locally licensed plugin DRM gets its keys from
``plugin_keys``. A track without a licensed DRM, or with a plugin DRM that holds its content key, 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)
@@ -646,8 +671,17 @@ def resolve_batch(session: Any, track_ids: Iterable[str], drm_type: str, policy:
continue
custom = custom_drm(track)
if device_licensed(custom):
if session.licensing.server_cdm and custom.content_keys:
batch.keys[tid] = served_custom_keys(session, custom)
sources: dict[str, str] = {}
try:
keys = plugin_keys(session, track, custom, sources, resolver.shared)
except (Exception, SystemExit) as e:
if isinstance(e, APIError) and e.error_code is APIErrorCode.SERVER_CDM_CAPPED:
batch.capped_tracks[tid] = e.details
else:
resolver.warn(f"Failed to license track {track_log_label(track)}: {redact_all(str(e))}")
continue
batch.keys[tid] = keys
batch.vault_keys.extend(sources)
continue
svc_session = getattr(service, "session", None)
+4 -1
View File
@@ -28,7 +28,7 @@ from unshackle.core.api.input_bridge import AUTH_INPUT_TIMEOUT, InputBridge
from unshackle.core.api.sanitize import sanitize_log
from unshackle.core.api.session_channel import SessionChannel, drain_message
from unshackle.core.config import config
from unshackle.core.remote_protocol import APIErrorCode, AuthStatus, LicensingMode, Licensor
from unshackle.core.remote_protocol import APIErrorCode, AuthStatus, ClientPlugin, LicensingMode, Licensor
from unshackle.core.tracks import Track, Tracks
if TYPE_CHECKING:
@@ -81,6 +81,7 @@ class SessionEntry:
presence: ClientPresence = field(default_factory=ClientPresence, repr=False, compare=False)
auth_error: str | None = None
client: dict[str, Any] = field(default_factory=dict) # version/argv/platform the client reported
client_plugins: dict[str, ClientPlugin] | None = None # None: a client too old to list its DRM plugins
actions: deque[dict[str, Any]] = field(default_factory=lambda: deque(maxlen=500))
created_at: datetime = field(default_factory=lambda: datetime.now(UTC))
last_accessed: datetime = field(default_factory=lambda: datetime.now(UTC))
@@ -310,6 +311,7 @@ class SessionStore:
input_bridge: InputBridge | None = None,
log_buffer: Any | None = None,
pending: PendingCreate | None = None,
client_plugins: dict[str, ClientPlugin] | None = None,
) -> SessionEntry:
"""Make a new remote session, complete with every field the dashboard shows, and announce it.
@@ -346,6 +348,7 @@ class SessionStore:
licensing=licensing,
client_auth=client_auth,
client=client or {},
client_plugins=client_plugins,
input_bridge=input_bridge,
log_buffer=log_buffer,
presence=ClientPresence(named=pending is not None and pending.named),
+15 -3
View File
@@ -7,26 +7,38 @@ see ``loader.find_device``.
from __future__ import annotations
from collections.abc import Mapping
from types import SimpleNamespace
from typing import Any
from unshackle.core import plugins
def cdm_type_stub(cdm_type: str, security_level: int | None = None) -> SimpleNamespace:
def cdm_type_stub(
cdm_type: str, security_level: int | None = None, facts: Mapping[str, Any] | None = None
) -> SimpleNamespace:
"""A CDM stand-in that only carries its DRM system, for when another machine holds the device.
``security_level`` lets a service pick a robustness tier; the attribute is absent when unknown.
A plugin id gives a stand-in of that plugin's system.
A plugin id gives a stand-in of that plugin's system, with the ``facts`` that the plugin names in ``device_facts``.
"""
stub = SimpleNamespace(is_playready=cdm_type == "playready")
if plugins.get(cdm_type):
if plugin := plugins.get(cdm_type):
stub.drm_system = cdm_type
if facts is not None:
for name in plugin.device_facts:
setattr(stub, name, facts.get(name))
if security_level is not None:
stub.security_level = security_level
return stub
def plugin_device(cdm_for: Any, plugin_id: str) -> Any:
"""The device that ``cdm_for`` gives for the DRM plugin ``plugin_id``; None when it gives none of that plugin."""
cdm = cdm_for(plugin_id) if cdm_for else None
return cdm if cdm_system(cdm) == plugin_id else None
def cdm_system(cdm: Any) -> str | None:
"""``playready``, ``widevine`` or a plugin id for a CDM object; None for no CDM or one of no known system."""
if cdm is None:
+11 -1
View File
@@ -17,9 +17,17 @@ class CustomDRM:
"""The DRM of a track whose system a plugin adds: plain data that can cross the wire and the export.
It holds the plugin id, its label, KIDs, a display id, the content keys and the plugin's own JSON
``data``; never a callable or a path. A plugin id that no loaded plugin has stops the track.
``data``; never a callable or a path. A plugin id that no loaded plugin has stops the track. With no ``kids``
given, the plugin reads them from ``data``.
"""
class Exceptions:
class CEKNotFound(click.ClickException):
error_code = APIErrorCode.DRM_ERROR
class EmptyLicense(click.ClickException):
error_code = APIErrorCode.DRM_ERROR
def __init__(
self,
plugin: str,
@@ -38,6 +46,8 @@ class CustomDRM:
self.display_id: str | None = display_id
self.data: dict[str, Any] = data or {}
self.content_keys: dict[UUID, str] = {}
if not self.kids and found.kids is not None:
self.kids = list(found.kids(self))
@property
def plugin_id(self) -> str:
+28 -37
View File
@@ -21,7 +21,7 @@ from rich.text import Text
from rich.tree import Tree
from unshackle.core import binaries
from unshackle.core.cdm.detect import cdm_system, is_playready_cdm
from unshackle.core.cdm.detect import cdm_system, is_playready_cdm, plugin_device
from unshackle.core.console import console
from unshackle.core.constants import DOWNLOAD_CANCELLED, AnyTrack, DownloadCancelled
from unshackle.core.drm import (
@@ -652,7 +652,7 @@ class ContentKeyResolver:
def _license_drm(
self,
drm: ClearKeyCENC | Widevine | PlayReady,
drm: ClearKeyCENC | Widevine | PlayReady | CustomDRM,
get_keys: Callable[[], None],
track: AnyTrack,
title: Title_T,
@@ -661,18 +661,20 @@ class ContentKeyResolver:
cdm_only: bool,
force: bool,
) -> None:
"""Give a Widevine, PlayReady or ClearKey DRM its content keys: run cache, then key vaults, then ``get_keys``.
"""Give a Widevine, PlayReady, ClearKey or plugin DRM its content keys: run cache, then key vaults, then ``get_keys``.
A held key for ``track_kid`` skips the licence, as the file is encrypted with that KID;
``decrypt_verified`` licenses any other KID the file turns out to use.
``force`` skips the run cache, so the licence runs again for each KID no vault answers.
A licence can answer a KID with a blank or null key; a vault key for that KID wins.
Every content key of the licence goes to the vaults and to the server key source's vault at once; for a
bridged DRM, the server key source's vault gets them only once ``decrypt_verified`` passes the track.
bridged DRM or a plugin DRM, the server key source's vault gets them only once ``decrypt_verified`` passes the track.
"""
pssh: str | None = None
if isinstance(drm, ClearKeyCENC):
name = "ClearKey"
elif isinstance(drm, CustomDRM):
name, pssh = drm.label, drm.display_id
else:
name = type(drm).__name__
pssh = drm.pssh.dumps() if isinstance(drm, Widevine) else drm.pssh_b64 or ""
@@ -791,7 +793,7 @@ class ContentKeyResolver:
licensed = {k: v for k, v in drm.content_keys.items() if k not in from_vaults}
pending_vault_writes.append(partial(self._cache_keys_to_vaults, licensed))
server_vault = self.source.server_vault if self.source else None
if server_vault is not None and not getattr(drm, "bridged", False):
if server_vault is not None and not (getattr(drm, "bridged", False) or device_licensed(drm)):
pending_vault_writes.append(
partial(server_vault.add_keys, self.tag, cast(dict[UUID | str, str], licensed), track)
)
@@ -819,6 +821,18 @@ class ContentKeyResolver:
label += f" {source}"
tree.add(label)
def _plugin_licence(self, drm: CustomDRM, track: AnyTrack) -> None:
"""License a plugin DRM with this machine's device of its plugin, which loads only when no content-key source answered.
The device is the one a service reads with no quality while it lists, as the plugin data can be bound to it.
"""
cdm = plugin_device(self.cdms.cdm_for, drm.plugin_id)
if cdm is None:
raise coded(
click.ClickException(f"No {drm.label} device to license track {track.id}"), APIErrorCode.DRM_ERROR
)
drm.license(cdm)
def _service_licence(self, drm_system: str | None = None, **kwargs: Any) -> Any:
"""Call the service's licence function, or its FairPlay bridge hook, for the track's DRM system (``service_licence``).
@@ -1095,44 +1109,21 @@ class ContentKeyResolver:
else:
raise ValueError(f"Title needs a {name} CDM but {self.tag} is configured with {other}.")
if isinstance(drm, (Widevine, PlayReady, ClearKeyCENC)):
if isinstance(drm, (Widevine, PlayReady, ClearKeyCENC, CustomDRM)):
if isinstance(drm, ClearKeyCENC):
clearkey_licence = partial(self.service.get_clearkey_license, title=title, track=track)
get_keys = partial(drm.get_content_keys, licence=clearkey_licence, session=self.service.session)
elif isinstance(drm, CustomDRM):
if not drm.kids:
raise coded(
click.ClickException(f"The {drm.label} DRM of track {track.id} names no KID"),
APIErrorCode.DRM_ERROR,
)
get_keys = partial(self._plugin_licence, drm, track)
track_kid = track_kid or drm.kid
else:
certificate = partial(self.service.get_widevine_service_certificate, title=title, track=track)
get_keys = partial(drm.get_content_keys, cdm=track_cdm, licence=licence, certificate=certificate)
self._license_drm(drm, get_keys, track, title, track_kid, table, cdm_only, force)
if self.export:
self.export(title, track, drm)
elif isinstance(drm, CustomDRM):
if not drm.content_keys:
self._take_known_keys(drm, drm.kids, track, track_kid, None)
if not drm.content_keys:
raise coded(
click.ClickException(
f"No {drm.label} content key for track {track.id} from a vault or the server CDM"
),
APIErrorCode.DRM_ERROR,
)
with self.drm_lock(drm):
id_part = (
[(f"({truncate_pssh_for_display(drm.display_id, drm.label)})", "text")] if drm.display_id else []
)
cek_tree = Tree(Text.assemble((drm.label, "cyan"), *id_part, overflow="fold"))
pre_existing_tree = next(
(x for x in table.columns[0].cells if isinstance(x, Tree) and x.label == cek_tree.label), None
)
if pre_existing_tree:
cek_tree = pre_existing_tree
for kid_, key in drm.content_keys.items():
self._add_key_label(cek_tree, kid_, key, track_kid=kid_) # every plugin key is the track's own
if cek_tree.children and not pre_existing_tree:
table.add_row()
table.add_row(cek_tree)
if self.export:
self.export(title, track, drm)
+13 -3
View File
@@ -21,6 +21,7 @@ from typing import TYPE_CHECKING, Any, Literal
if TYPE_CHECKING:
from importlib.resources.abc import Traversable
from uuid import UUID
from unshackle.core.drm.custom import CustomDRM
@@ -40,12 +41,18 @@ class DrmPlugin:
cipher that is not CENC: no KID to probe and no fragment to check. ``mode`` "segment" decrypts each
segment as it lands, several at once, then calls ``finish`` on the merged file; "track" decrypts the merged file once.
``decrypt`` writes only its destination path, whatever its name.
``wire_data`` names the keys of ``CustomDRM.data`` that a peer and an export may carry. ``finish`` returns
False for a track that the cipher leaves clear: its merged file proves no content key, so it gets no decode check.
``wire_data`` names the keys of ``CustomDRM.data`` that a peer and an export may carry: licence data, never a
server secret. ``kids`` reads the KIDs from that data before any licence, so a vault can answer first, and may
set the ``display_id`` of the DRM; ``licence`` runs at the licence step of a download with a device of this
plugin. ``finish`` returns False for a track that the cipher leaves clear: its merged file proves no content key,
so it gets no decode check.
The CDM that ``load_device`` builds may carry a ``device_name`` for the load log.
``devices`` gives the plugin's own folder of device files (``importlib.resources``, so a zip works too), searched
after the operator's device folders; a call per lookup keeps a zip plugin closed. ``default_device`` names the
device a service gets when its config names none of this system.
``version`` goes to a remote server with the id. ``device_facts`` names the device attributes a service may read
to pick streams; a remote client sends their values, never a path or a device file, so that a server whose session
the client's device licenses gives the service a stand-in with them.
"""
id: str
@@ -60,7 +67,10 @@ class DrmPlugin:
devices: Callable[[], Traversable] | None = None
default_device: str | None = None
licence: Callable[[CustomDRM, Any], None] | None = None
kids: Callable[[CustomDRM], list[UUID]] | None = None
finish: Callable[[CustomDRM, Path, Any], bool] | None = None
version: str = ""
device_facts: tuple[str, ...] = ()
def __post_init__(self) -> None:
if not ID.fullmatch(self.id) or self.id in BUILT_IN:
@@ -71,7 +81,7 @@ class DrmPlugin:
raise ValueError(f"Bad mode of DRM plugin {self.id!r}")
if bool(self.device_suffix) != (self.load_device is not None):
raise ValueError(f"DRM plugin {self.id!r} needs both device_suffix and load_device, or neither")
if (self.devices is not None or self.default_device) and not self.device_suffix:
if (self.devices is not None or self.default_device or self.device_facts) and not self.device_suffix:
raise ValueError(f"DRM plugin {self.id!r} has devices but no device_suffix")
+11
View File
@@ -120,6 +120,16 @@ class ClientInfo(TypedDict):
argv: str
DEVICE_FACT_TYPES = (str, int, float, bool, type(None))
class ClientPlugin(TypedDict, total=False):
"""A DRM plugin of a remote client: its version, and the facts of the plugin device the client licenses with."""
version: str
device: dict[str, Any]
class SessionCreate(ClientLogin, total=False):
"""The body of a remote session creation."""
@@ -149,6 +159,7 @@ class SessionCreate(ClientLogin, total=False):
best_available: bool
generate_dv: bool
dl_params: dict[str, Any]
plugins: dict[str, ClientPlugin]
client: ClientInfo
+63 -23
View File
@@ -44,7 +44,7 @@ from unshackle.core.config import config
from unshackle.core.console import SyncLive, console
from unshackle.core.constants import AnyTrack, DownloadCancelled, RunCancel
from unshackle.core.credential import Credential
from unshackle.core.drm import CustomDRM, cbcs, real_kids
from unshackle.core.drm import CustomDRM, cbcs, custom_drm, real_kids
from unshackle.core.drm.cenc import PLACEHOLDER_KIDS
from unshackle.core.drm.discovery import track_pssh
from unshackle.core.launch import launch_keys
@@ -52,6 +52,7 @@ from unshackle.core.manifests.snapshot import match_track
from unshackle.core.proxies.resolve import is_loopback
from unshackle.core.remote_protocol import (
BAD_KEY_ROUTE,
DEVICE_FACT_TYPES,
HEALTH_ROUTE,
KEYS_ROUTE,
LICENSE_ROUTE,
@@ -69,6 +70,7 @@ from unshackle.core.remote_protocol import (
BadKeyReport,
ClientErrorKind,
ClientLogin,
ClientPlugin,
LicenseReply,
LicenseRequest,
LicensingMode,
@@ -123,6 +125,35 @@ SESSION_LOST = (
)
# what a recovering call can meet on its way, so these log only once the recovery fails
RECOVERABLE = (*SESSION_LOST, APIErrorCode.SERVER_DRAINING)
def session_plugins(cdm_for: Callable[..., Any] | None) -> dict[str, ClientPlugin]:
"""Each DRM plugin of this machine for a remote session create: its version, and the facts of its device.
A fact is the plain value of an attribute that the plugin names in ``device_facts``, never a path or a device file.
"""
from unshackle.core import plugins
from unshackle.core.cdm.detect import plugin_device
listed: dict[str, ClientPlugin] = {}
for plugin in plugins.plugins().values():
entry = ClientPlugin(version=plugin.version)
if plugin.device_facts:
try:
device = plugin_device(cdm_for, plugin.id)
except Exception as e:
log.warning(f"The {plugin.label} device did not load: {e}")
device = None
if device is not None:
entry["device"] = {
name: value
for name in plugin.device_facts
if isinstance(value := getattr(device, name, None), DEVICE_FACT_TYPES)
}
listed[plugin.id] = entry
return listed
RETRY_AFTER_MAX = 3600
RETRY_AFTER_LOCK = Lock()
RATE_LIMIT_TRIES = 3
@@ -1154,6 +1185,7 @@ class RemoteService(TitleSource):
**login,
**route,
**session_request(params, self._service_params),
"plugins": session_plugins(getattr(self.ctx.obj, "cdm_for", None) if cdm is not None else None),
}
if cdm is not None:
from unshackle.core.cdm.detect import cdm_system
@@ -1625,7 +1657,7 @@ class RemoteService(TitleSource):
media playlist names the DRM and the downloader honours ``drm_preference``. On the server's device
there is no such licence: the error names ``kid``, else each KID of ``drm`` with no content key.
"""
from unshackle.core.cdm.detect import cdm_label, cdm_system
from unshackle.core.cdm.detect import cdm_label, cdm_system, plugin_device
if refusal.get("reason") == "server_device":
vaults = (
@@ -1654,29 +1686,37 @@ class RemoteService(TitleSource):
why = "The server vault holds no content key for this track"
else:
why = "The server CDM refused this track"
cdm = self.local_cdm
if cdm is None:
raise coded(
click.ClickException(f"{why}, and {track} needs a local CDM to license it"), APIErrorCode.DRM_ERROR
)
drm_class = cdm_label(cdm)
height = getattr(track, "height", None)
systems = {d.__class__.__name__ for d in track.drm or ()}
if systems and drm_class not in systems:
other = "Widevine" if drm_class == "PlayReady" else "PlayReady"
if not (
other in systems
and self.ctx.obj.cdm_for
and cdm_system(self.ctx.obj.cdm_for(other.lower(), height)) == other.lower()
):
label = f"the {height}p track" if height else str(track)
hint = f"; pass -q {height} to start the session on your device" if cap and height else ""
have = " and ".join(sorted(systems))
raise click.ClickException(
f"{why}, and {label} has only {have} DRM, which your local {drm_class} CDM cannot license{hint}"
if (custom := custom_drm(track)) is not None:
drm_class = custom.label
if plugin_device(self.ctx.obj.cdm_for, custom.plugin_id) is None:
raise coded(
click.ClickException(f"{why}, and {track} needs a {drm_class} device to license it"),
APIErrorCode.DRM_ERROR,
)
drm_class = other
track.drm_preference = drm_class.lower()
else:
cdm = self.local_cdm
if cdm is None:
raise coded(
click.ClickException(f"{why}, and {track} needs a local CDM to license it"), APIErrorCode.DRM_ERROR
)
drm_class = cdm_label(cdm)
systems = {d.__class__.__name__ for d in track.drm or ()}
if systems and drm_class not in systems:
other = "Widevine" if drm_class == "PlayReady" else "PlayReady"
if not (
other in systems
and self.ctx.obj.cdm_for
and cdm_system(self.ctx.obj.cdm_for(other.lower(), height)) == other.lower()
):
label = f"the {height}p track" if height else str(track)
hint = f"; pass -q {height} to start the session on your device" if cap and height else ""
have = " and ".join(sorted(systems))
raise click.ClickException(
f"{why}, and {label} has only {have} DRM, which your local {drm_class} CDM cannot license{hint}"
)
drm_class = other
track.drm_preference = drm_class.lower()
self.client_licensed.add(str(track.id))
from unshackle.core.api.progress import track_log_label