mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-26 19:05:13 +00:00
feat(remote): license each track locally with --cdm-only over remote
This commit is contained in:
@@ -472,7 +472,7 @@ Make a download job. It requires `service` and `title_id`. Every other field is
|
||||
| `skip_dl` | boolean | `false` | Only fetch keys, do not download. |
|
||||
| `all_drm` | boolean | `false` | License each track with both Widevine and PlayReady. Needs a CDM for each DRM system. Key vaults are read first; `cdm_only: true` sends a challenge for each system. The server refuses it with `cdm`, which selects one device. |
|
||||
| `export` | boolean | `false` | Export manifest/keys/subs to JSON. |
|
||||
| `cdm_only` | boolean | `null` | Force CDM-only (`true`) or vault-only (`false`) key retrieval. |
|
||||
| `cdm_only` | boolean | `null` | Force CDM-only (`true`) or vault-only (`false`) key retrieval. With `remote`, `true` licenses every track with the CDM of this server and uses no CDM or vault of the remote server. |
|
||||
| `proxy` / `no_proxy` / `no_proxy_download` / `proxy_download` | string / bool / bool / string | `null` / `false` / `false` / `null` | Proxy controls. `proxy` and `proxy_download` must be full proxy URIs on a public host unless the API key has `server_proxy`. A Control D resolver, `controld://<resolver>@dns.controld.com`, counts as a full proxy URI: the server runs a forwarder for it. |
|
||||
| `no_folder` / `no_source` / `no_mux` | boolean | `false` | Output/mux controls. |
|
||||
| `sample` | boolean/string | `null` | Download a short sample and write it with a `SAMPLE` tag on the filename in a `Sample` folder inside the output folder. `true` is 60 seconds from 2 minutes in; `"0-60"` is a window in seconds. |
|
||||
@@ -956,6 +956,7 @@ POST /api/session/{id}/segments → resolve segment URLs / DRM / headers per tra
|
||||
POST /api/session/{id}/segment_filter → HLS segments the service drops (ads, bumpers)
|
||||
POST /api/session/{id}/samples → decrypt cbcs samples of a track on the server
|
||||
POST /api/session/{id}/license → proxy or server-CDM DRM licensing
|
||||
POST /api/session/{id}/keys → store the content keys the client proved on a track
|
||||
POST /api/session/{id}/keys/bad → report a server-vault content key that did not decrypt
|
||||
DELETE /api/session/{id} → tear down, harvest updated cache
|
||||
```
|
||||
@@ -1245,6 +1246,19 @@ A slow answer arrives as a [slow response](#slow-responses).
|
||||
| `404` | `NO_CONTENT` | Server CDM produced no keys. |
|
||||
| `422` | `SERVICE_ERROR` | The service aborted during licensing. |
|
||||
|
||||
### `POST /api/session/{session_id}/keys`
|
||||
|
||||
Store the content keys that the client proved on a track and that the server did not serve to this remote session. The server stores a content key only for a KID that a track of the remote session names and that no local server vault holds a content key for. It never stores a pair flagged bad, and it never removes a flag. The server answers when its local vaults hold the pairs, and sends them to its other vaults after the answer. The client sends each key of a licence when the licence returns, and each vault key after its decode check passes.
|
||||
|
||||
```json
|
||||
{ "track_id": "<track_id>", "keys": { "<kid_hex>": "<key_hex>" } }
|
||||
```
|
||||
|
||||
| Status | Error code | Meaning |
|
||||
| --- | --- | --- |
|
||||
| `200` | - | `{}`, whatever the server stored. |
|
||||
| `404` | `SESSION_NOT_FOUND` | Unknown remote session. |
|
||||
|
||||
### `POST /api/session/{session_id}/keys/bad`
|
||||
|
||||
Report a content key from `vault_keys` that did not decrypt the track. The server flags the pair in its local vaults and reports it to the vault that served it, and the next licence for that KID reaches the CDM. When the CDM returns the same pair, the server removes the flag. The client never learns the server vault names.
|
||||
|
||||
@@ -207,6 +207,7 @@ request and response in full.
|
||||
| `POST` | `/api/session/{session_id}/segment_filter` | Server-side HLS segment filter results for one track. |
|
||||
| `POST` | `/api/session/{session_id}/samples` | Server-side cbcs sample decryption for one track. |
|
||||
| `POST` | `/api/session/{session_id}/license` | Proxy or server-side DRM licensing. |
|
||||
| `POST` | `/api/session/{session_id}/keys` | Store the content keys the client proved on a track. |
|
||||
| `POST` | `/api/session/{session_id}/keys/bad` | Report a server-vault content key that did not decrypt. |
|
||||
| `GET` | `/api/session/{session_id}/channel` | WebSocket of the remote session channel: prompts, CDM calls, logs, login state. |
|
||||
| `GET` | `/api/session/{session_id}/logs` | Drain the service's server-side log output. |
|
||||
|
||||
@@ -461,6 +461,7 @@ The server mounts all these routes, even in `--remote-only` mode. Paths use the
|
||||
| `POST` | `/api/session/{id}/segment_filter` | Unwanted HLS segment URIs for one track (ads, bumpers) |
|
||||
| `POST` | `/api/session/{id}/samples` | Decrypt the cbcs samples of a track the service decrypts itself |
|
||||
| `POST` | `/api/session/{id}/license` | DRM licensing (proxy or server CDM) |
|
||||
| `POST` | `/api/session/{id}/keys` | Store the content keys the client proved on a track |
|
||||
| `POST` | `/api/session/{id}/keys/bad` | Report a server-vault content key that did not decrypt |
|
||||
| `GET` | `/api/session/{id}/channel` | WebSocket of the [remote session channel](#the-remote-session-channel): the messages the server starts, and the client's answers; `?since=` is the last log `seq` the client has |
|
||||
| `GET` | `/api/session/{id}/logs` | Drain the service's server-side log output (polling fallback) |
|
||||
|
||||
@@ -962,7 +962,7 @@ unshackle dl -w S01 --slow 30-60 EXAMPLE 81234567
|
||||
By default, unshackle checks your **key vaults** first and only asks a **CDM** to license
|
||||
a content key when the vault misses. You can force one side or the other:
|
||||
|
||||
- `--cdm-only`: only use the CDM (skip vaults). Over a `server_cdm` remote session the flag does not reach the server, whose vault shortcut still runs; it only skips the client's decode check on a server key.
|
||||
- `--cdm-only`: only use the CDM (skip vaults). Over `--remote`, your own CDM licenses each track, and the run uses neither the server CDM nor the server vault. It needs a local CDM, and a remote session on the server's device fails.
|
||||
- `--cdm <name>`: use the named CDM device for this run, ignoring the `cdm` config mapping (including its quality and Widevine/PlayReady sub-entries). Over `--remote`, that device licenses the remote session, not the server CDM.
|
||||
- `--vaults-only`: only use key vaults and never license through the CDM. A missing
|
||||
content key fails.
|
||||
|
||||
@@ -545,7 +545,7 @@ control this trade-off on the `dl` command:
|
||||
| Flag | Effect |
|
||||
|------|--------|
|
||||
| `--vaults-only` | Never send a license request; use only cached/vault keys. Fails if a content key is missing. |
|
||||
| `--cdm-only` | Ignore vaults for sourcing keys and always perform a fresh license request. Over a `server_cdm` remote session the server still reads its own vaults; the flag only skips the client's decode check on the key it gets back. |
|
||||
| `--cdm-only` | Ignore vaults for sourcing keys and always perform a fresh license request. Over `--remote`, your own CDM licenses each track, and the run uses neither the server CDM nor the server vault. A remote session on the server's device fails, and so does a run with no local CDM. |
|
||||
| `--cdm <name>` | Use the named CDM device for this run instead of the one the `cdm` config maps for the service. Over `--remote`, that device licenses the remote session, not the server CDM. |
|
||||
|
||||
See [key vaults](vaults.md) for how to configure vault backends.
|
||||
|
||||
@@ -241,7 +241,7 @@ def no_decrypt(monkeypatch) -> list[tuple[object, bool]]:
|
||||
"""
|
||||
calls: list[tuple[object, bool]] = []
|
||||
|
||||
def decrypt_track(drm, path, licence=None, track_kid=None, decrypt=True):
|
||||
def decrypt_track(drm, path, licence=None, track_kid=None, decrypt=True, track=None):
|
||||
calls.append((drm, decrypt))
|
||||
|
||||
for module in (segment_pipeline, hls_module):
|
||||
|
||||
@@ -20,6 +20,7 @@ def remote_keys(
|
||||
svc.client_licensed = set(client_licensed)
|
||||
svc.deferred_refusals = {}
|
||||
svc.server_vault_keys = dict(server_vault_keys or {})
|
||||
svc.served_keys = set()
|
||||
svc.server_vault = ServerVault(svc)
|
||||
svc.ctx = SimpleNamespace(obj=SimpleNamespace(cdm=local_cdm, cdm_for=None))
|
||||
return svc
|
||||
|
||||
@@ -1470,6 +1470,160 @@
|
||||
},
|
||||
"status": 422
|
||||
},
|
||||
"POST /api/session/{session_id}/keys no key": {
|
||||
"body": {
|
||||
"message": "Secret Key is Empty.",
|
||||
"status": 401
|
||||
},
|
||||
"content_type": "application/json",
|
||||
"leading_newlines": false,
|
||||
"log": [],
|
||||
"stats": {
|
||||
"error": null,
|
||||
"late_status": null
|
||||
},
|
||||
"status": 401
|
||||
},
|
||||
"POST /api/session/{session_id}/keys not an object": {
|
||||
"body": {
|
||||
"error_code": "INVALID_INPUT",
|
||||
"message": "The request body must be a JSON object (ref REF)",
|
||||
"ref": "REF",
|
||||
"status": "error",
|
||||
"timestamp": "TIMESTAMP"
|
||||
},
|
||||
"content_type": "application/json",
|
||||
"leading_newlines": false,
|
||||
"log": [
|
||||
"Error ref REF: INVALID_INPUT 400 POST /api/session/pinned-session/keys service=- user=test\u2026: The request body must be a JSON object"
|
||||
],
|
||||
"stats": {
|
||||
"error": {
|
||||
"code": "INVALID_INPUT",
|
||||
"message": "The request body must be a JSON object",
|
||||
"ref": "REF"
|
||||
},
|
||||
"late_status": null
|
||||
},
|
||||
"status": 400
|
||||
},
|
||||
"POST /api/session/{session_id}/keys not authenticated": {
|
||||
"body": {
|
||||
"details": {
|
||||
"auth_status": "authenticating"
|
||||
},
|
||||
"error_code": "INVALID_INPUT",
|
||||
"message": "Session authentication not complete (status: authenticating) (ref REF)",
|
||||
"ref": "REF",
|
||||
"status": "error",
|
||||
"timestamp": "TIMESTAMP"
|
||||
},
|
||||
"content_type": "application/json",
|
||||
"leading_newlines": false,
|
||||
"log": [
|
||||
"Error ref REF: INVALID_INPUT 400 POST /api/session/pinned-session/keys service=EXAMPLE user=test\u2026: Session authentication not complete (status: authenticating)"
|
||||
],
|
||||
"stats": {
|
||||
"error": {
|
||||
"code": "INVALID_INPUT",
|
||||
"message": "Session authentication not complete (status: authenticating)",
|
||||
"ref": "REF"
|
||||
},
|
||||
"late_status": null
|
||||
},
|
||||
"status": 400
|
||||
},
|
||||
"POST /api/session/{session_id}/keys not json": {
|
||||
"body": {
|
||||
"details": {
|
||||
"error": "Expecting property name enclosed in double quotes: line 1 column 2 (char 1)"
|
||||
},
|
||||
"error_code": "INVALID_INPUT",
|
||||
"message": "Invalid JSON request body (ref REF)",
|
||||
"ref": "REF",
|
||||
"status": "error",
|
||||
"timestamp": "TIMESTAMP"
|
||||
},
|
||||
"content_type": "application/json",
|
||||
"leading_newlines": false,
|
||||
"log": [
|
||||
"Error ref REF: INVALID_INPUT 400 POST /api/session/pinned-session/keys service=- user=test\u2026: Invalid JSON request body"
|
||||
],
|
||||
"stats": {
|
||||
"error": {
|
||||
"code": "INVALID_INPUT",
|
||||
"message": "Invalid JSON request body",
|
||||
"ref": "REF"
|
||||
},
|
||||
"late_status": null
|
||||
},
|
||||
"status": 400
|
||||
},
|
||||
"POST /api/session/{session_id}/keys plain before the handler's try": {
|
||||
"body": {
|
||||
"error_code": "INTERNAL_ERROR",
|
||||
"message": "Internal server error (ref REF)",
|
||||
"ref": "REF",
|
||||
"status": "error",
|
||||
"timestamp": "TIMESTAMP"
|
||||
},
|
||||
"content_type": "application/json",
|
||||
"leading_newlines": false,
|
||||
"log": [],
|
||||
"stats": {
|
||||
"raised": true
|
||||
},
|
||||
"status": 422
|
||||
},
|
||||
"POST /api/session/{session_id}/keys unknown session": {
|
||||
"body": {
|
||||
"details": {
|
||||
"session_id": "pinned-session"
|
||||
},
|
||||
"error_code": "SESSION_NOT_FOUND",
|
||||
"message": "Session not found or expired: pinned-session (ref REF)",
|
||||
"ref": "REF",
|
||||
"status": "error",
|
||||
"timestamp": "TIMESTAMP"
|
||||
},
|
||||
"content_type": "application/json",
|
||||
"leading_newlines": false,
|
||||
"log": [
|
||||
"Error ref REF: SESSION_NOT_FOUND 404 POST /api/session/pinned-session/keys service=- user=test\u2026: Session not found or expired: pinned-session"
|
||||
],
|
||||
"stats": {
|
||||
"error": {
|
||||
"code": "SESSION_NOT_FOUND",
|
||||
"message": "Session not found or expired: pinned-session",
|
||||
"ref": "REF"
|
||||
},
|
||||
"late_status": null
|
||||
},
|
||||
"status": 404
|
||||
},
|
||||
"POST /api/session/{session_id}/keys wrong owner": {
|
||||
"body": {
|
||||
"error_code": "FORBIDDEN",
|
||||
"message": "Session access denied (ref REF)",
|
||||
"ref": "REF",
|
||||
"status": "error",
|
||||
"timestamp": "TIMESTAMP"
|
||||
},
|
||||
"content_type": "application/json",
|
||||
"leading_newlines": false,
|
||||
"log": [
|
||||
"Error ref REF: FORBIDDEN 403 POST /api/session/pinned-session/keys service=EXAMPLE user=test\u2026: Session access denied"
|
||||
],
|
||||
"stats": {
|
||||
"error": {
|
||||
"code": "FORBIDDEN",
|
||||
"message": "Session access denied",
|
||||
"ref": "REF"
|
||||
},
|
||||
"late_status": null
|
||||
},
|
||||
"status": 403
|
||||
},
|
||||
"POST /api/session/{session_id}/keys/bad no key": {
|
||||
"body": {
|
||||
"message": "Secret Key is Empty.",
|
||||
@@ -2584,6 +2738,39 @@
|
||||
},
|
||||
"status": 422
|
||||
},
|
||||
"keys api": {
|
||||
"body": {},
|
||||
"content_type": "application/json",
|
||||
"leading_newlines": false,
|
||||
"log": [],
|
||||
"stats": {
|
||||
"error": null,
|
||||
"late_status": null
|
||||
},
|
||||
"status": 200
|
||||
},
|
||||
"keys exit": {
|
||||
"body": {},
|
||||
"content_type": "application/json",
|
||||
"leading_newlines": false,
|
||||
"log": [],
|
||||
"stats": {
|
||||
"error": null,
|
||||
"late_status": null
|
||||
},
|
||||
"status": 200
|
||||
},
|
||||
"keys plain": {
|
||||
"body": {},
|
||||
"content_type": "application/json",
|
||||
"leading_newlines": false,
|
||||
"log": [],
|
||||
"stats": {
|
||||
"error": null,
|
||||
"late_status": null
|
||||
},
|
||||
"status": 200
|
||||
},
|
||||
"license batch api": {
|
||||
"body": {
|
||||
"details": {
|
||||
|
||||
@@ -57,7 +57,7 @@ def client_calls() -> tuple[set[tuple[str, str]], set[str]]:
|
||||
for call in ast.walk(function):
|
||||
if not (isinstance(call, ast.Call) and isinstance(call.func, ast.Attribute) and call.args):
|
||||
continue
|
||||
if call.func.attr == "request" and isinstance(call.args[0], ast.Constant) and len(call.args) > 1:
|
||||
if call.func.attr in ("request", "send") and isinstance(call.args[0], ast.Constant) and len(call.args) > 1:
|
||||
method, target = str(call.args[0].value).upper(), call.args[1]
|
||||
elif call.func.attr in CLIENT_METHODS:
|
||||
method, target = CLIENT_METHODS[call.func.attr], call.args[0]
|
||||
@@ -115,6 +115,7 @@ def test_the_wire_values_stay_what_older_peers_send():
|
||||
"SEGMENT_FILTER_ROUTE": "/api/session/{session_id}/segment_filter",
|
||||
"SAMPLES_ROUTE": "/api/session/{session_id}/samples",
|
||||
"LICENSE_ROUTE": "/api/session/{session_id}/license",
|
||||
"KEYS_ROUTE": "/api/session/{session_id}/keys",
|
||||
"BAD_KEY_ROUTE": "/api/session/{session_id}/keys/bad",
|
||||
"LOGS_ROUTE": "/api/session/{session_id}/logs",
|
||||
"PROMPT_ROUTE": "/api/session/{session_id}/prompt",
|
||||
@@ -205,6 +206,7 @@ def properties(schema: Optional[dict]) -> set[str]:
|
||||
("POST", protocol.TRACKS_ROUTE, protocol.TracksRequest, None),
|
||||
("POST", protocol.SEGMENT_FILTER_ROUTE, protocol.SegmentFilterRequest, protocol.SegmentFilterReply),
|
||||
("POST", protocol.LICENSE_ROUTE, protocol.LicenseRequest, protocol.LicenseReply),
|
||||
("POST", protocol.KEYS_ROUTE, protocol.TrackKeys, None),
|
||||
("POST", protocol.BAD_KEY_ROUTE, protocol.BadKeyReport, None),
|
||||
("GET", protocol.LOGS_ROUTE, None, protocol.LogsReply),
|
||||
("GET", protocol.PROMPT_ROUTE, None, protocol.PromptReply),
|
||||
|
||||
@@ -30,6 +30,7 @@ from unshackle.core.api.stats import stats, stats_middleware
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.remote_protocol import (
|
||||
BAD_KEY_ROUTE,
|
||||
KEYS_ROUTE,
|
||||
LICENSE_ROUTE,
|
||||
LOGS_ROUTE,
|
||||
PROMPT_ROUTE,
|
||||
@@ -111,6 +112,7 @@ BODIES: dict[str, Any] = {
|
||||
SEGMENT_FILTER_ROUTE: {"track_id": "v1"},
|
||||
LICENSE_ROUTE: {"track_id": "v1", "challenge": "AAAA"},
|
||||
BAD_KEY_ROUTE: {"kid": "00" * 16, "key": "11" * 16},
|
||||
KEYS_ROUTE: {"track_id": "v1", "keys": {"22" * 16: "33" * 16}},
|
||||
PROMPT_ROUTE: {"response": "1234"},
|
||||
"/api/list-titles": {"service": "EXAMPLE", "title_id": "title-0001"},
|
||||
"/api/list-tracks": {"service": "EXAMPLE", "title_id": "title-0001"},
|
||||
@@ -118,7 +120,15 @@ BODIES: dict[str, Any] = {
|
||||
"/api/download/jobs/{job_id}/input": {"response": "1234"},
|
||||
"/api/remote/logins/{login_id}/input": {"response": "1234"},
|
||||
}
|
||||
AUTHENTICATED_ROUTES = [TITLES_ROUTE, TRACKS_ROUTE, SEGMENTS_ROUTE, SEGMENT_FILTER_ROUTE, LICENSE_ROUTE, BAD_KEY_ROUTE]
|
||||
AUTHENTICATED_ROUTES = [
|
||||
TITLES_ROUTE,
|
||||
TRACKS_ROUTE,
|
||||
SEGMENTS_ROUTE,
|
||||
SEGMENT_FILTER_ROUTE,
|
||||
LICENSE_ROUTE,
|
||||
BAD_KEY_ROUTE,
|
||||
KEYS_ROUTE,
|
||||
]
|
||||
SAMPLES = fill(SAMPLES_ROUTE) + "?track_id=v1&entry=1"
|
||||
|
||||
|
||||
@@ -199,6 +209,13 @@ def fault_cases() -> dict[str, Case]:
|
||||
session=Faulty(),
|
||||
patch={"load_server_vaults": Faulty(kind).fail},
|
||||
)
|
||||
cases[f"keys {kind}"] = Case(
|
||||
"POST",
|
||||
fill(KEYS_ROUTE),
|
||||
BODIES[KEYS_ROUTE],
|
||||
session=Faulty(),
|
||||
patch={"load_server_vaults": Faulty(kind).fail},
|
||||
)
|
||||
cases[f"prompt get {kind}"] = Case("GET", fill(PROMPT_ROUTE), session=Faulty(input_bridge=Faulty(kind)))
|
||||
cases[f"prompt submit {kind}"] = Case(
|
||||
"POST",
|
||||
|
||||
@@ -219,8 +219,8 @@ def test_cdm_only_still_reuses_keys_from_the_run_cache():
|
||||
assert vaults.pushes == [{NEW: "k_new"}]
|
||||
|
||||
|
||||
def test_cdm_only_trusts_server_vault_keys():
|
||||
"""--cdm-only skips the vault checks, so a server vault key is not sourced for a decode check."""
|
||||
def test_a_forced_licence_trusts_server_vault_keys():
|
||||
"""A forced licence (cdm_only=True, as --all-drm passes) does not name the server vault as a source, so no decode check."""
|
||||
from unshackle.core.remote_service import ServerVault
|
||||
|
||||
vaults = FakeVaults()
|
||||
|
||||
@@ -0,0 +1,330 @@
|
||||
"""Over a remote session, the content keys a decrypt proved go back to the server, which keeps only what it lacks.
|
||||
|
||||
Over ``--cdm-only`` the session runs on the client's own device and asks the server for no key.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from typing import Any, Optional
|
||||
from uuid import UUID
|
||||
|
||||
import click
|
||||
import pytest
|
||||
from pywidevine.pssh import PSSH
|
||||
|
||||
from tests.core.key_resolver import key_table, resolver
|
||||
from tests.remote.key_source import remote_keys
|
||||
from tests.remote.sessions import session_entry
|
||||
from unshackle.core import remote_channel
|
||||
from unshackle.core.api import handlers
|
||||
from unshackle.core.cdm.detect import cdm_type_stub
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.drm import Widevine, key_resolution
|
||||
from unshackle.core.remote_service import RemoteService
|
||||
from unshackle.core.vaults import Vaults
|
||||
from unshackle.vaults.SQLite import SQLite
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
LICENSED = UUID("11111111-2222-3333-4444-555555555555")
|
||||
VAULTED = UUID("22222222-2222-3333-4444-555555555555")
|
||||
SERVED = UUID("33333333-2222-3333-4444-555555555555")
|
||||
HELD = UUID("44444444-2222-3333-4444-555555555555")
|
||||
FLAGGED = UUID("55555555-2222-3333-4444-555555555555")
|
||||
UNNAMED = UUID("66666666-2222-3333-4444-555555555555")
|
||||
LATE = UUID("77777777-2222-3333-4444-555555555555")
|
||||
NULL = UUID("88888888-2222-3333-4444-555555555555")
|
||||
KEY = "ab" * 16
|
||||
OTHER_KEY = "cd" * 16
|
||||
|
||||
|
||||
class Remote(SQLite):
|
||||
"""A second SQLite file standing in for a remote vault."""
|
||||
|
||||
local = False
|
||||
|
||||
|
||||
def client(posts: list) -> RemoteService:
|
||||
svc = remote_keys(server_cdm=False)
|
||||
svc._session_id = "sess"
|
||||
svc._track_alias = {"v1": "v9"}
|
||||
svc.client = SimpleNamespace(
|
||||
send=lambda method, endpoint, timeout, background, json: posts.append((method, endpoint, background, json))
|
||||
)
|
||||
return svc
|
||||
|
||||
|
||||
def test_the_server_vault_posts_only_the_pairs_the_server_did_not_serve() -> None:
|
||||
posts: list = []
|
||||
svc = client(posts)
|
||||
svc.note_vault_keys({SERVED.hex: KEY}, set())
|
||||
|
||||
assert svc.server_vault.add_keys("EXAMPLE", {LICENSED: KEY, SERVED: KEY}, SimpleNamespace(id="v1")) == 0
|
||||
svc.server_vault.add_keys("EXAMPLE", {SERVED: KEY}, SimpleNamespace(id="v1"))
|
||||
|
||||
assert posts == [("post", "/api/session/sess/keys", True, {"track_id": "v9", "keys": {LICENSED.hex: KEY}})]
|
||||
|
||||
|
||||
def test_a_pair_the_server_accepted_is_not_posted_again() -> None:
|
||||
posts: list = []
|
||||
svc = client(posts)
|
||||
svc.client.send = lambda method, endpoint, timeout, background, json: posts.append(json) or SimpleNamespace(ok=True)
|
||||
|
||||
svc.server_vault.add_keys("EXAMPLE", {LICENSED: KEY}, SimpleNamespace(id="v1"))
|
||||
svc.server_vault.add_keys("EXAMPLE", {LICENSED: KEY, VAULTED: KEY}, SimpleNamespace(id="v1"))
|
||||
|
||||
assert [post["keys"] for post in posts] == [{LICENSED.hex: KEY}, {VAULTED.hex: KEY}]
|
||||
|
||||
|
||||
def test_every_key_of_a_licence_goes_to_the_server_vault_without_a_decrypt(monkeypatch) -> None:
|
||||
licensed = {LICENSED: KEY, LATE: OTHER_KEY}
|
||||
monkeypatch.setattr(Widevine, "get_content_keys", lambda self, **_: setattr(self, "content_keys", dict(licensed)))
|
||||
pushed: list = []
|
||||
source = remote_keys(server_cdm=False)
|
||||
source.server_vault = SimpleNamespace(add_keys=lambda service, keys, track: pushed.append((keys, track)))
|
||||
keys = resolver(tag="EXAMPLE", source=source)
|
||||
drm = Widevine(pssh=PSSH.new(system_id=PSSH.SystemId.Widevine, key_ids=[LICENSED]))
|
||||
track = SimpleNamespace(id="v1", drm=[drm])
|
||||
|
||||
keys.licence_for(track, None, key_table())(drm, track_kid=LICENSED)
|
||||
keys.wait_vault_writes()
|
||||
|
||||
assert pushed == [(licensed, track)]
|
||||
|
||||
|
||||
def test_a_failed_post_is_dropped_and_logs_nothing(caplog: pytest.LogCaptureFixture) -> None:
|
||||
caplog.set_level(logging.DEBUG)
|
||||
svc = client([])
|
||||
|
||||
def refused(method: str, endpoint: str, timeout: float, background: bool, json: Any) -> None:
|
||||
raise ConnectionError("EXAMPLE server down")
|
||||
|
||||
svc.client.send = refused
|
||||
svc.server_vault.add_keys("EXAMPLE", {LICENSED: KEY}, SimpleNamespace(id="v1"))
|
||||
|
||||
assert caplog.records == []
|
||||
|
||||
|
||||
def test_every_served_pair_is_remembered_whatever_its_source() -> None:
|
||||
svc = remote_keys()
|
||||
svc.note_vault_keys({VAULTED.hex: KEY, SERVED.hex: OTHER_KEY}, {VAULTED.hex})
|
||||
assert svc.served_keys == {(VAULTED, KEY), (SERVED, OTHER_KEY)}
|
||||
|
||||
|
||||
def decrypt(
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
ffmpeg: Any,
|
||||
decodes: bool = True,
|
||||
track: Any = "track",
|
||||
flagged: Optional[dict] = None,
|
||||
licence: Any = None,
|
||||
) -> list:
|
||||
"""Decrypt a track that holds a licence key, a vault key and a null key; return what reached the server vault."""
|
||||
monkeypatch.setattr(key_resolution.binaries, "FFMPEG", ffmpeg)
|
||||
monkeypatch.setattr(key_resolution, "ffmpeg_decodes", lambda path, start=None, seconds=3, video=None: decodes)
|
||||
local = SQLite("local", tmp_path / "local.db")
|
||||
local.add_key("EXAMPLE", VAULTED, OTHER_KEY)
|
||||
vaults = Vaults("EXAMPLE")
|
||||
vaults.vaults = [local]
|
||||
assert vaults.get_key(VAULTED) == (OTHER_KEY, local)
|
||||
pushed: list = []
|
||||
source = SimpleNamespace(
|
||||
server_cdm=False,
|
||||
server_vault=SimpleNamespace(add_keys=lambda service, keys, track: pushed.append((keys, track))),
|
||||
)
|
||||
keys = resolver(vaults, tag="EXAMPLE", source=source)
|
||||
vaults.flagged.update((flagged or {}).items())
|
||||
path = tmp_path / "video.mp4"
|
||||
path.write_bytes(b"cipher")
|
||||
content_keys = {LICENSED: KEY, VAULTED: OTHER_KEY, NULL: "0" * 32, **(flagged or {})}
|
||||
drm = SimpleNamespace(content_keys=content_keys, decrypt=lambda path: None)
|
||||
try:
|
||||
keys.decrypt_verified(drm, path, licence, LICENSED, track=track)
|
||||
finally:
|
||||
keys.wait_vault_writes()
|
||||
return pushed
|
||||
|
||||
|
||||
def test_a_passed_decode_sends_the_licence_keys_and_the_checked_vault_keys(tmp_path, monkeypatch) -> None:
|
||||
assert decrypt(tmp_path, monkeypatch, "ffmpeg") == [({LICENSED: KEY, VAULTED: OTHER_KEY}, "track")]
|
||||
|
||||
|
||||
def test_without_ffmpeg_a_vault_key_is_not_sent(tmp_path, monkeypatch) -> None:
|
||||
assert decrypt(tmp_path, monkeypatch, None) == [({LICENSED: KEY}, "track")]
|
||||
|
||||
|
||||
def test_a_failed_decode_sends_nothing(tmp_path, monkeypatch) -> None:
|
||||
with pytest.raises(ValueError):
|
||||
decrypt(tmp_path, monkeypatch, "ffmpeg", decodes=False)
|
||||
|
||||
|
||||
def test_a_flagged_pair_is_replaced_before_anything_is_sent(tmp_path, monkeypatch) -> None:
|
||||
def licence(drm: Any, track_kid: UUID) -> None:
|
||||
drm.content_keys[FLAGGED] = OTHER_KEY
|
||||
|
||||
pushed = decrypt(tmp_path, monkeypatch, "ffmpeg", flagged={FLAGGED: KEY}, licence=licence)
|
||||
assert pushed == [({LICENSED: KEY, VAULTED: OTHER_KEY, FLAGGED: OTHER_KEY}, "track")]
|
||||
|
||||
|
||||
def test_a_decrypt_without_a_track_sends_nothing(tmp_path, monkeypatch) -> None:
|
||||
assert decrypt(tmp_path, monkeypatch, "ffmpeg", track=None) == []
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def server(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> SimpleNamespace:
|
||||
"""A remote session whose tracks name every KID but UNNAMED, over a local vault and a remote one."""
|
||||
late = SimpleNamespace(id="v2", drm=None)
|
||||
tracks = {
|
||||
"v1": SimpleNamespace(id="v1", drm=[SimpleNamespace(kids=[LICENSED, SERVED, HELD, FLAGGED])]),
|
||||
"v2": late,
|
||||
}
|
||||
entry = session_entry(service_tag="EXAMPLE", tracks=tracks)
|
||||
entry.served_keys[SERVED.hex] = (KEY, "cdm")
|
||||
local = SQLite("local", tmp_path / "local.db")
|
||||
remote = Remote("remote", tmp_path / "remote.db")
|
||||
remote.add_key("EXAMPLE", HELD, OTHER_KEY)
|
||||
vaults = Vaults("EXAMPLE")
|
||||
vaults.vaults = [local, remote]
|
||||
vaults.flag_bad_key(FLAGGED, KEY)
|
||||
ensured: list = []
|
||||
|
||||
async def validated(session_id: str, request: Any) -> Any:
|
||||
return entry
|
||||
|
||||
def ensure(track: Any, session: Any = None, init_data: Any = None) -> None:
|
||||
ensured.append(track.id)
|
||||
track.drm = [SimpleNamespace(kids=[LATE])]
|
||||
|
||||
monkeypatch.setattr(handlers, "get_validated_session", validated)
|
||||
monkeypatch.setattr(handlers, "require_authenticated", lambda session: None)
|
||||
monkeypatch.setattr(handlers, "load_server_vaults", lambda name: vaults)
|
||||
monkeypatch.setattr(handlers, "ensure_track_drm", ensure)
|
||||
return SimpleNamespace(local=local, remote=remote, ensured=ensured)
|
||||
|
||||
|
||||
async def settled() -> None:
|
||||
"""Wait for the push to the remote vaults, which runs after the answer."""
|
||||
await asyncio.get_running_loop().shutdown_default_executor()
|
||||
|
||||
|
||||
async def test_the_server_stores_only_a_named_kid_no_local_vault_holds(server, caplog) -> None:
|
||||
caplog.set_level(logging.INFO, logger="api")
|
||||
posted = {kid.hex: KEY for kid in (LICENSED, SERVED, HELD, FLAGGED, UNNAMED, LATE)}
|
||||
|
||||
resp = await handlers.session_keys_handler({"track_id": "v2", "keys": {**posted, "nope": "zz"}}, "sess")
|
||||
|
||||
await settled()
|
||||
|
||||
assert (resp.status, json.loads(resp.body)) == (200, {})
|
||||
assert server.ensured == ["v2"]
|
||||
for vault in (server.local, server.remote):
|
||||
assert vault.get_key(LICENSED, "EXAMPLE") == KEY
|
||||
assert vault.get_key(LATE, "EXAMPLE") == KEY
|
||||
assert vault.get_key(UNNAMED, "EXAMPLE") is None
|
||||
assert vault.get_key(SERVED, "EXAMPLE") is None
|
||||
assert server.remote.get_key(HELD, "EXAMPLE") == OTHER_KEY
|
||||
assert server.local.get_key(HELD, "EXAMPLE") == KEY
|
||||
assert server.local.is_bad_key(FLAGGED, KEY)
|
||||
assert [r.getMessage() for r in caplog.records if r.name == "api"] == [
|
||||
"Session sess sent 3 client content key(s) to the server vaults"
|
||||
]
|
||||
|
||||
|
||||
async def test_the_server_answers_before_the_remote_vaults_take_the_keys(server, monkeypatch) -> None:
|
||||
release = threading.Event()
|
||||
real = server.remote.add_keys
|
||||
|
||||
def slow(service: str, kid_keys: dict) -> int:
|
||||
release.wait(10)
|
||||
return real(service, kid_keys)
|
||||
|
||||
monkeypatch.setattr(server.remote, "add_keys", slow)
|
||||
await handlers.session_keys_handler({"track_id": "v2", "keys": {LICENSED.hex: KEY}}, "sess")
|
||||
|
||||
assert server.local.get_key(LICENSED, "EXAMPLE") == KEY
|
||||
assert server.remote.get_key(LICENSED, "EXAMPLE") is None
|
||||
release.set()
|
||||
await settled()
|
||||
assert server.remote.get_key(LICENSED, "EXAMPLE") == KEY
|
||||
|
||||
|
||||
async def test_a_local_vault_that_cannot_answer_counts_as_holding_the_kid(server, monkeypatch) -> None:
|
||||
real = server.local.get_key
|
||||
|
||||
def down(kid: Any, service: str) -> Any:
|
||||
if kid == LICENSED:
|
||||
raise OSError("EXAMPLE vault file locked")
|
||||
return real(kid, service)
|
||||
|
||||
monkeypatch.setattr(server.local, "get_key", down)
|
||||
await handlers.session_keys_handler({"track_id": "v2", "keys": {LICENSED.hex: KEY, LATE.hex: KEY}}, "sess")
|
||||
await settled()
|
||||
assert server.remote.get_key(LICENSED, "EXAMPLE") is None
|
||||
assert server.remote.get_key(LATE, "EXAMPLE") == KEY
|
||||
|
||||
|
||||
async def test_the_server_answers_empty_when_it_stores_nothing(server, caplog) -> None:
|
||||
caplog.set_level(logging.INFO, logger="api")
|
||||
resp = await handlers.session_keys_handler({"track_id": ["v1"], "keys": {UNNAMED.hex: KEY}}, "sess")
|
||||
assert (resp.status, json.loads(resp.body)) == (200, {})
|
||||
assert [r for r in caplog.records if r.levelno >= logging.INFO] == []
|
||||
|
||||
|
||||
def cdm_only_client(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, cdm: Any, created: dict) -> RemoteService:
|
||||
"""A real RemoteService for a ``--cdm-only`` run whose server answers session create with ``created``."""
|
||||
monkeypatch.setattr(config, "credentials", {})
|
||||
monkeypatch.setattr(config.directories, "cookies", tmp_path / "cookies")
|
||||
monkeypatch.setattr(config.directories, "cache", tmp_path / "cache")
|
||||
monkeypatch.setattr(
|
||||
remote_channel,
|
||||
"open_channel",
|
||||
lambda service: SimpleNamespace(
|
||||
in_flight=None, close=lambda: None, drain_logs=lambda: None, keep_alive=lambda: None
|
||||
),
|
||||
)
|
||||
obj = SimpleNamespace(cdm=cdm, cdm_entry=False, proxy_providers=[])
|
||||
parent = click.Context(click.Command("dl"), obj=obj)
|
||||
parent.params = {"no_proxy": True, "cdm_only": True}
|
||||
ctx = click.Context(click.Command("EXAMPLE"), parent=parent, obj=obj)
|
||||
svc = RemoteService(ctx, "EXAMPLE", "example-1", "http://server", "key", {"_server_cdm": True})
|
||||
posts: list = []
|
||||
svc.client = SimpleNamespace(
|
||||
tunnel=None, post=lambda endpoint, data, expect=(): posts.append(data) or created, delete=lambda endpoint: {}
|
||||
)
|
||||
svc.posts = posts
|
||||
return svc
|
||||
|
||||
|
||||
def test_cdm_only_declines_the_server_cdm_and_its_vault(monkeypatch, tmp_path) -> None:
|
||||
created = {"session_id": "sess", "server_cdm": False, "server_vault": True}
|
||||
svc = cdm_only_client(monkeypatch, tmp_path, cdm_type_stub("widevine"), created)
|
||||
try:
|
||||
svc.authenticate()
|
||||
assert svc.posts[0]["server_cdm"] is False
|
||||
assert (svc.server_cdm, svc._server_vault) == (False, False)
|
||||
svc.resolve_server_keys(SimpleNamespace(tracks=SimpleNamespace(videos=["v"], audio=[])))
|
||||
assert len(svc.posts) == 1
|
||||
finally:
|
||||
svc.close()
|
||||
|
||||
|
||||
def test_cdm_only_without_a_local_cdm_fails_before_the_session(monkeypatch, tmp_path) -> None:
|
||||
svc = cdm_only_client(monkeypatch, tmp_path, None, {})
|
||||
with pytest.raises(click.ClickException, match="needs a local CDM for EXAMPLE"):
|
||||
svc.authenticate()
|
||||
assert svc.posts == []
|
||||
|
||||
|
||||
def test_cdm_only_on_the_server_device_fails(monkeypatch, tmp_path) -> None:
|
||||
created = {"session_id": "sess", "server_cdm": True, "server_device": True}
|
||||
svc = cdm_only_client(monkeypatch, tmp_path, cdm_type_stub("widevine"), created)
|
||||
try:
|
||||
with pytest.raises(click.ClickException, match="runs on the server's device"):
|
||||
svc.authenticate()
|
||||
finally:
|
||||
svc.close()
|
||||
@@ -2848,7 +2848,7 @@ class dl:
|
||||
for track in drm_tracks:
|
||||
drm = track.get_drm_for_cdm(self.cdm)
|
||||
if drm and hasattr(drm, "decrypt"):
|
||||
self.keys.decrypt_verified(drm, track.path, prepare_drm_for(track))
|
||||
self.keys.decrypt_verified(drm, track.path, prepare_drm_for(track), track=track)
|
||||
if not isinstance(drm, MonaLisa):
|
||||
# MonaLisa decrypts per segment; its decrypt() here is a no-op
|
||||
assert_fragments_decrypted(track.path)
|
||||
@@ -3421,6 +3421,7 @@ class dl:
|
||||
if cookie_file:
|
||||
self.save_cookies(cookie_file, service.session.cookies)
|
||||
|
||||
self.keys.wait_vault_writes()
|
||||
if hasattr(service, "close"):
|
||||
service.close()
|
||||
|
||||
@@ -3430,7 +3431,6 @@ class dl:
|
||||
run_context["folder"] = str(folder)
|
||||
dispatch("success", "run", run_context, postscript)
|
||||
|
||||
self.keys.wait_vault_writes()
|
||||
if export_path:
|
||||
self.log_export_summary()
|
||||
if self.skipped_titles:
|
||||
|
||||
@@ -42,7 +42,7 @@ from unshackle.core.dl_options import (
|
||||
cast_dl_params,
|
||||
forwarded_dl_params,
|
||||
)
|
||||
from unshackle.core.drm import BlowfishStripe, cbcs, is_null_key
|
||||
from unshackle.core.drm import BlowfishStripe, cbcs, is_null_key, real_kids
|
||||
from unshackle.core.launch import served_context
|
||||
from unshackle.core.manifests.snapshot import capture
|
||||
from unshackle.core.providers.anilist import parse_anilist_ref
|
||||
@@ -64,6 +64,7 @@ from unshackle.core.remote_protocol import (
|
||||
SessionCreated,
|
||||
SessionInfo,
|
||||
TitlesReply,
|
||||
TrackKeys,
|
||||
TracksReply,
|
||||
TracksRequest,
|
||||
)
|
||||
@@ -5291,6 +5292,71 @@ async def session_bad_key_handler(
|
||||
return web.json_response({"flagged": True})
|
||||
|
||||
|
||||
async def session_keys_handler(data: TrackKeys, session_id: str, request: Optional[web.Request] = None) -> web.Response:
|
||||
"""Store the content keys a client proved on a track of this remote session in the server vaults.
|
||||
|
||||
The server takes a KID only when a track of the remote session names it and no local server vault holds a
|
||||
content key for it, and never a pair flagged bad or one it served, so a client can add a missing content key but
|
||||
never replace or unflag one. It answers once the local vaults hold the pairs and pushes them to the other vaults
|
||||
after, so the client never waits on a remote vault. The reply is always empty, so the client learns nothing.
|
||||
"""
|
||||
session = await get_validated_session(session_id, request)
|
||||
require_authenticated(session)
|
||||
|
||||
track_id, posted = data.get("track_id"), data.get("keys")
|
||||
pairs = {
|
||||
str(kid).replace("-", "").lower(): key.lower()
|
||||
for kid, key in (posted.items() if isinstance(posted, dict) else ())
|
||||
if isinstance(key, str) and re.fullmatch(r"[0-9a-fA-F]{32}", key)
|
||||
}
|
||||
if not pairs:
|
||||
return web.json_response({})
|
||||
service = session.service_instance
|
||||
|
||||
def named_kids() -> set[str]:
|
||||
track = session.tracks.get(track_id) if isinstance(track_id, str) else None
|
||||
if track is not None:
|
||||
ensure_track_drm(track, getattr(service, "session", None))
|
||||
return {kid.hex for t in list(session.tracks.values()) for drm in t.drm or [] for kid in real_kids(drm)}
|
||||
|
||||
def store(named: set[str]) -> tuple[Any, Dict[Any, str]]:
|
||||
vaults = load_server_vaults(service.__class__.__name__)
|
||||
local = [vault for vault in vaults.vaults if vault.local]
|
||||
|
||||
def held(vault: Any, kid: uuid.UUID) -> bool:
|
||||
"""Whether ``vault`` holds a content key for ``kid``. A failed lookup counts as held, a vault with no read access as empty."""
|
||||
try:
|
||||
return bool(vault.get_key(kid, vaults.service))
|
||||
except (PermissionError, NotImplementedError):
|
||||
return False
|
||||
except Exception:
|
||||
return True
|
||||
|
||||
new: Dict[Any, str] = {}
|
||||
for kid_hex, key in pairs.items():
|
||||
if kid_hex not in named or session.served_keys.get(kid_hex, ("",))[0].lower() == key:
|
||||
continue
|
||||
kid = uuid.UUID(hex=kid_hex)
|
||||
if not vaults.is_flagged(kid, key) and not any(held(vault, kid) for vault in local):
|
||||
new[kid] = key
|
||||
if new and sum(vaults.push_keys(vault, new) for vault in local if not vault.no_push):
|
||||
log.info(
|
||||
f"Session {sanitize_log(session_id[:12])} sent {len(new)} client content key(s) to the server vaults"
|
||||
)
|
||||
return vaults, new
|
||||
|
||||
try:
|
||||
async with session.lock:
|
||||
named = await asyncio.to_thread(named_kids)
|
||||
vaults, new = await asyncio.to_thread(store, named)
|
||||
remote = [vault for vault in vaults.vaults if not vault.local and not vault.no_push]
|
||||
if new and remote:
|
||||
asyncio.get_running_loop().run_in_executor(None, lambda: [vaults.push_keys(vault, new) for vault in remote])
|
||||
except (Exception, SystemExit) as e:
|
||||
log.debug(f"Session {sanitize_log(session_id[:12])} content keys not stored: {e!r}")
|
||||
return web.json_response({})
|
||||
|
||||
|
||||
async def session_info_handler(session_id: str, request: Optional[web.Request] = None) -> web.Response:
|
||||
"""Make sure that the remote session is valid, and get the remote session info."""
|
||||
session = await get_validated_session(session_id, request)
|
||||
|
||||
@@ -63,6 +63,7 @@ from unshackle.core.api.handlers import (
|
||||
session_create_handler,
|
||||
session_delete_handler,
|
||||
session_info_handler,
|
||||
session_keys_handler,
|
||||
session_license_handler,
|
||||
session_logs_handler,
|
||||
session_prompt_get_handler,
|
||||
@@ -82,6 +83,7 @@ from unshackle.core.remote_protocol import (
|
||||
BAD_KEY_ROUTE,
|
||||
CHANNEL_ROUTE,
|
||||
HEALTH_ROUTE,
|
||||
KEYS_ROUTE,
|
||||
LICENSE_ROUTE,
|
||||
LOGS_ROUTE,
|
||||
PROMPT_ROUTE,
|
||||
@@ -1146,7 +1148,7 @@ async def download(request: web.Request) -> web.Response:
|
||||
description: Export manifest, DRM init data, keys, and track info to a JSON file in the exports directory (default - false)
|
||||
cdm_only:
|
||||
type: boolean
|
||||
description: Only use CDM for content key retrieval (true) or only vaults (false) (default - None)
|
||||
description: Only use CDM for content key retrieval (true) or only vaults (false). With `remote`, true licenses every track with the CDM of this server and uses no CDM or vault of the remote server (default - None)
|
||||
cdm:
|
||||
type: string
|
||||
description: CDM device name on the server to license with, overriding the cdm config mapping. Requires serve.cdm_overrides to allow it (default - None)
|
||||
@@ -2483,6 +2485,52 @@ async def session_bad_key(request: web.Request) -> web.Response:
|
||||
return await session_bad_key_handler(data, session_id, request)
|
||||
|
||||
|
||||
@api_handler
|
||||
async def session_keys(request: web.Request) -> web.Response:
|
||||
"""
|
||||
Store the content keys a client proved on a track in the server vaults.
|
||||
---
|
||||
summary: Store proven content keys
|
||||
description: >-
|
||||
The client decrypted a track and the output decoded. It sends the content keys that the server
|
||||
did not serve to this remote session. The server stores a content key only for a KID that a
|
||||
track of the remote session names and that no server vault holds a content key for, and never
|
||||
a pair flagged bad. The reply is always empty.
|
||||
parameters:
|
||||
- name: session_id
|
||||
in: path
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required:
|
||||
- track_id
|
||||
- keys
|
||||
properties:
|
||||
track_id:
|
||||
type: string
|
||||
description: The track the keys decrypted
|
||||
keys:
|
||||
type: object
|
||||
description: Content key as hex, by KID as hex
|
||||
additionalProperties:
|
||||
type: string
|
||||
responses:
|
||||
'200':
|
||||
description: An empty object, whatever the server stored
|
||||
'404':
|
||||
description: Remote session not found
|
||||
"""
|
||||
session_id = request.match_info["session_id"]
|
||||
data = await json_body(request)
|
||||
return await session_keys_handler(data, session_id, request)
|
||||
|
||||
|
||||
@api_handler
|
||||
async def session_info(request: web.Request) -> web.Response:
|
||||
"""
|
||||
@@ -3460,6 +3508,7 @@ ROUTES: list[tuple[str, str, Handler, bool]] = [
|
||||
("POST", SEGMENT_FILTER_ROUTE, session_segment_filter, True),
|
||||
("POST", SAMPLES_ROUTE, session_samples, True),
|
||||
("POST", LICENSE_ROUTE, session_license, True),
|
||||
("POST", KEYS_ROUTE, session_keys, True),
|
||||
("POST", BAD_KEY_ROUTE, session_bad_key, True),
|
||||
("GET", LOGS_ROUTE, session_logs, True),
|
||||
("GET", PROMPT_ROUTE, session_prompt_get, True),
|
||||
|
||||
@@ -131,6 +131,7 @@ class ContentKeyResolver:
|
||||
licence: Optional[Callable] = None,
|
||||
track_kid: Optional[UUID] = None,
|
||||
decrypt: bool = True,
|
||||
track: Optional[AnyTrack] = None,
|
||||
) -> None:
|
||||
"""Decrypt the file, and when a vault supplied a content key, prove the output decodes.
|
||||
|
||||
@@ -152,6 +153,9 @@ class ContentKeyResolver:
|
||||
With ``decrypt=False`` the downloader already decrypted the segments in place, so a
|
||||
failure can only flag and raise; the next run skips the flagged pair.
|
||||
|
||||
After a decrypt that passes, the server key source's vault gets the proven content keys of
|
||||
``track``: each licence key, and each vault key the decode check passed.
|
||||
|
||||
Before the decrypt, each KID the DRM names without a content key is licensed when the file
|
||||
uses it, or when the file cannot be mapped, because ``_prepare_drm`` licensed only for the track's KID.
|
||||
"""
|
||||
@@ -231,6 +235,13 @@ class ContentKeyResolver:
|
||||
windows = kid_map.windows if kid_map else {}
|
||||
video = kid_map.video if kid_map else None
|
||||
|
||||
def proven(passed: dict[UUID, Vault]) -> dict[Union[UUID, str], str]:
|
||||
"""The licence keys and the vault keys in ``passed``, without null keys; a flagged pair never gets here."""
|
||||
sourced = vault_kids()
|
||||
return {
|
||||
kid: key for kid, key in keys.items() if (kid in passed or kid not in sourced) and not is_null_key(key)
|
||||
}
|
||||
|
||||
def window_decodes(start: float, end: float) -> bool:
|
||||
return ffmpeg_decodes(path, start=start, seconds=end - start if end > start else 0.5, video=video)
|
||||
|
||||
@@ -286,6 +297,11 @@ class ContentKeyResolver:
|
||||
]
|
||||
)
|
||||
self.vaults.report_replaced(keys)
|
||||
server_vault = self.source.server_vault if self.source and track is not None else None
|
||||
if server_vault is not None:
|
||||
self._flush_vault_writes(
|
||||
[partial(server_vault.add_keys, self.tag, proven(kids if checked else {}), track)]
|
||||
)
|
||||
return
|
||||
bad = {kid: drop(kid) for kid in {*failed, *stale}}
|
||||
for kid, key in bad.items():
|
||||
@@ -367,9 +383,6 @@ class ContentKeyResolver:
|
||||
elif kid not in self.LICENSE_KEY_CACHE:
|
||||
self.LICENSE_KEY_CACHE[kid] = server_key
|
||||
self._flush_vault_writes([partial(self._cache_keys_to_vaults, {kid: server_key})])
|
||||
self.log.debug(
|
||||
f"{vault.name} holds a different key for {kid.hex} than the server, testing it first"
|
||||
)
|
||||
|
||||
def _cache_resolved_keys(self, source: "ServerKeySource", title: Title_T) -> None:
|
||||
"""Cache the keys a batch licence or an import put on the tracks.
|
||||
@@ -550,6 +563,7 @@ class ContentKeyResolver:
|
||||
``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.
|
||||
"""
|
||||
pssh: Optional[str] = None
|
||||
if isinstance(drm, ClearKeyCENC):
|
||||
@@ -667,12 +681,13 @@ class ContentKeyResolver:
|
||||
drop_null_keys(drm)
|
||||
drm.content_keys.update(from_vaults)
|
||||
self.LICENSE_KEY_CACHE.update(drm.content_keys)
|
||||
pending_vault_writes.append(
|
||||
partial(
|
||||
self._cache_keys_to_vaults,
|
||||
{k: v for k, v in drm.content_keys.items() if k not in from_vaults},
|
||||
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:
|
||||
pending_vault_writes.append(
|
||||
partial(server_vault.add_keys, self.tag, cast(dict[Union[UUID, str], str], licensed), track)
|
||||
)
|
||||
)
|
||||
|
||||
if track_kid and track_kid not in drm.content_keys:
|
||||
msg = f"No Content Key for KID {track_kid.hex} was returned in the License"
|
||||
|
||||
@@ -38,6 +38,7 @@ def decrypt_track(
|
||||
licence: Optional[Callable] = None,
|
||||
track_kid: Optional[UUID] = None,
|
||||
decrypt: bool = True,
|
||||
track: Any = None,
|
||||
) -> None:
|
||||
"""Decrypt ``path`` with ``drm`` through the installed hook, or directly when there is none.
|
||||
|
||||
@@ -45,7 +46,7 @@ def decrypt_track(
|
||||
then only checks the result, because there is no ciphertext left to retry with.
|
||||
"""
|
||||
if DECRYPT_HOOK:
|
||||
DECRYPT_HOOK(drm, path, licence, track_kid, decrypt)
|
||||
DECRYPT_HOOK(drm, path, licence, track_kid, decrypt, track=track)
|
||||
elif decrypt:
|
||||
drm.decrypt(path)
|
||||
|
||||
|
||||
@@ -677,6 +677,11 @@ class ImportService:
|
||||
"""Always None: no server vault serves an import."""
|
||||
return None
|
||||
|
||||
@property
|
||||
def server_vault(self) -> None:
|
||||
"""Always None: an import has no server to push content keys to."""
|
||||
return None
|
||||
|
||||
def resolve_server_keys(self, title: Title_T) -> None:
|
||||
"""Inject exported keys into the selected encrypted tracks by KID (no network).
|
||||
|
||||
|
||||
@@ -985,7 +985,7 @@ class HLS:
|
||||
assert decrypted_init is not None
|
||||
map_data = (map_data[0], decrypted_init)
|
||||
merge(to=merged_path, via=files, delete=True, include_map_data=True)
|
||||
decrypt_track(drm, merged_path, license_widevine, decrypt=not segment_decrypter)
|
||||
decrypt_track(drm, merged_path, license_widevine, decrypt=not segment_decrypter, track=track)
|
||||
assert_fragments_decrypted(merged_path)
|
||||
merged_path.rename(decrypted_path)
|
||||
else:
|
||||
|
||||
@@ -201,7 +201,7 @@ def decrypt_output(track: AnyTrack, ctx: DownloadContext, drm: DRM_T, decrypt: b
|
||||
`decrypt=False` means a SegmentDecrypter already decrypted the segments, so only the check runs.
|
||||
"""
|
||||
ctx.progress(downloaded="Decrypting", completed=0, total=None)
|
||||
decrypt_track(drm, ctx.save_path, ctx.license_widevine, decrypt=decrypt)
|
||||
decrypt_track(drm, ctx.save_path, ctx.license_widevine, decrypt=decrypt, track=track)
|
||||
assert_fragments_decrypted(ctx.save_path)
|
||||
track.drm = None
|
||||
events.emit(events.Types.TRACK_DECRYPTED, track=track, drm=drm, segment=None)
|
||||
|
||||
@@ -22,6 +22,7 @@ SEGMENTS_ROUTE = SESSION_ROUTE + "/segments"
|
||||
SEGMENT_FILTER_ROUTE = SESSION_ROUTE + "/segment_filter"
|
||||
SAMPLES_ROUTE = SESSION_ROUTE + "/samples"
|
||||
LICENSE_ROUTE = SESSION_ROUTE + "/license"
|
||||
KEYS_ROUTE = SESSION_ROUTE + "/keys"
|
||||
BAD_KEY_ROUTE = SESSION_ROUTE + "/keys/bad"
|
||||
LOGS_ROUTE = SESSION_ROUTE + "/logs"
|
||||
PROMPT_ROUTE = SESSION_ROUTE + "/prompt"
|
||||
@@ -207,6 +208,11 @@ class BadKeyReport(TypedDict):
|
||||
key: str
|
||||
|
||||
|
||||
class TrackKeys(TypedDict):
|
||||
track_id: str
|
||||
keys: dict[str, str]
|
||||
|
||||
|
||||
class PromptReply(TypedDict, total=False):
|
||||
"""The login state of a remote session, and the prompt or CDM call that waits for the client."""
|
||||
|
||||
|
||||
@@ -57,6 +57,7 @@ from unshackle.core.proxies.resolve import is_loopback
|
||||
from unshackle.core.remote_protocol import (
|
||||
BAD_KEY_ROUTE,
|
||||
HEALTH_ROUTE,
|
||||
KEYS_ROUTE,
|
||||
LICENSE_ROUTE,
|
||||
SAMPLES_ROUTE,
|
||||
SEARCH_ROUTE,
|
||||
@@ -79,6 +80,7 @@ from unshackle.core.remote_protocol import (
|
||||
SessionCreate,
|
||||
SessionCreated,
|
||||
TitlesReply,
|
||||
TrackKeys,
|
||||
TracksReply,
|
||||
TracksRequest,
|
||||
)
|
||||
@@ -121,6 +123,7 @@ RETRY_AFTER_LOCK = Lock()
|
||||
RATE_LIMIT_TRIES = 3
|
||||
TUNNEL_SLOT_POLL = 15
|
||||
PROBE_TIMEOUT = 30.0
|
||||
KEYS_TIMEOUT = 5.0
|
||||
REOPEN_WAIT = 1800.0 # seconds a lost session waits for its server to come back; covers a deploy's whole drain
|
||||
|
||||
|
||||
@@ -826,14 +829,18 @@ class ServerKeySource(Protocol):
|
||||
def vault_source(self, kid: UUID, key: str) -> Optional[Vault]:
|
||||
"""The server vault when it served ``key`` for ``kid``, else None. That content key must pass a decrypt check."""
|
||||
|
||||
@property
|
||||
def server_vault(self) -> Optional["ServerVault"]:
|
||||
"""The server's vaults, which take the content keys a decrypt proved, or None."""
|
||||
|
||||
|
||||
class ServerVault(Vault):
|
||||
"""The server's vaults as one source seen from the client: it can only be reported against.
|
||||
"""The server's vaults as one source for the client, which reports bad pairs to it and pushes proven ones.
|
||||
|
||||
``decrypt_verified`` needs a Vault to hold in ``Vaults.sources`` so a server-supplied
|
||||
content key gets the same decode check as a local vault key. The client never learns
|
||||
which server vault answered and can neither read nor write it, so every method returns
|
||||
nothing. A bad verdict goes to the server at once, so its next licence skips the pair.
|
||||
which server vault answered and cannot read it. A bad verdict goes to the server at once,
|
||||
so its next licence skips the pair. ``add_keys`` pushes the proven keys the server did not serve.
|
||||
"""
|
||||
|
||||
report_now = True
|
||||
@@ -851,7 +858,23 @@ class ServerVault(Vault):
|
||||
def add_key(self, service: str, kid: Union[UUID, str], key: str) -> bool:
|
||||
return False
|
||||
|
||||
def add_keys(self, service: str, kid_keys: dict[Union[UUID, str], str]) -> int:
|
||||
def add_keys(self, service: str, kid_keys: dict[Union[UUID, str], str], track: Optional[AnyTrack] = None) -> int:
|
||||
"""Post the pairs of ``track`` the server neither served nor accepted; always 0, as it does not say what it stored.
|
||||
|
||||
It runs on the vault writer thread and is silent: it drops a failed post and logs nothing. The wait is
|
||||
short, as the server writes its local vaults before it answers and its other vaults after.
|
||||
"""
|
||||
remote = self.service
|
||||
pairs = ((UUID(str(kid)), key) for kid, key in kid_keys.items())
|
||||
keys = {kid.hex: key for kid, key in pairs if (kid, key) not in remote.served_keys}
|
||||
session_id = remote._session_id
|
||||
if keys and track is not None and session_id:
|
||||
body = TrackKeys(track_id=remote.server_track_id(track.id), keys=keys)
|
||||
with contextlib.suppress(Exception):
|
||||
if remote.client.send(
|
||||
"post", KEYS_ROUTE.format(session_id=session_id), KEYS_TIMEOUT, background=True, json=body
|
||||
).ok:
|
||||
remote.served_keys.update((UUID(hex=kid), key) for kid, key in keys.items())
|
||||
return 0
|
||||
|
||||
def get_services(self) -> Iterator[str]:
|
||||
@@ -908,6 +931,7 @@ class RemoteService:
|
||||
self.client_licensed: set[str] = set() # track ids this machine's device licenses by challenge relay
|
||||
self.deferred_refusals: Dict[str, str] = {}
|
||||
self.server_vault_keys: Dict[UUID, str] = {}
|
||||
self.served_keys: set[tuple[UUID, str]] = set()
|
||||
self.server_vault = ServerVault(self)
|
||||
self._segment_filters: Dict[str, Callable[[Any], bool]] = {}
|
||||
self._sample_decrypt_tracks: set[str] = set()
|
||||
@@ -1141,6 +1165,9 @@ class RemoteService:
|
||||
# sent with the server CDM too: a capped server hands the tracks above its cap to this device
|
||||
cdm = self.local_cdm
|
||||
cdm_name = self.ctx.parent and self.ctx.parent.params.get("cdm_name")
|
||||
cdm_only = bool(self.ctx.parent and self.ctx.parent.params.get("cdm_only"))
|
||||
if cdm_only and cdm is None:
|
||||
raise click.ClickException(f"--cdm-only over --remote needs a local CDM for {self.service_tag}")
|
||||
cdm_entry = cdm is not None and self.ctx.obj.cdm_entry and self._server_cdm is None
|
||||
if not (cdm_entry or cdm_name or self._server_cdm is not None) and ci_get(config.cdm, self.service_tag):
|
||||
self.log.warning(
|
||||
@@ -1150,7 +1177,7 @@ class RemoteService:
|
||||
if cdm is not None:
|
||||
from unshackle.core.cdm.detect import is_playready_cdm
|
||||
|
||||
if cdm_entry or cdm_name:
|
||||
if cdm_entry or cdm_name or cdm_only:
|
||||
self._server_cdm = False
|
||||
if self._server_cdm is False:
|
||||
create_data["server_cdm"] = False
|
||||
@@ -1195,6 +1222,10 @@ class RemoteService:
|
||||
if "server_cdm" in result:
|
||||
self.adopt_session_cdm(bool(result["server_cdm"]), result.get("server_cdm_max_height"))
|
||||
self._server_device = bool(result.get("server_device"))
|
||||
if cdm_only and self._server_device:
|
||||
raise click.ClickException(
|
||||
f"--cdm-only cannot license {self.service_tag}: the remote session runs on the server's device"
|
||||
)
|
||||
if cdm_entry and self._server_cdm is False and not self._server_device:
|
||||
self.log.info(
|
||||
f"The cdm config has an entry for {self.service_tag}, so your own device licenses "
|
||||
@@ -1205,7 +1236,7 @@ class RemoteService:
|
||||
self._server_cdm = True
|
||||
whose = "the server vault or yours" if vault else "your vaults only"
|
||||
self.log.info(f"This session runs on the server's device: keys come from {whose}")
|
||||
self._server_vault = vault and not self._server_cdm
|
||||
self._server_vault = vault and not self._server_cdm and not cdm_only
|
||||
# without the server vault grant the server refuses every key request, so none is sent
|
||||
self._local_vaults_only = self._server_device and not vault
|
||||
|
||||
@@ -1679,9 +1710,10 @@ class RemoteService:
|
||||
return self.server_vault if self.server_vault_keys.get(kid) == key else None
|
||||
|
||||
def note_vault_keys(self, keys: Dict[str, str], vault_kids: set[str]) -> None:
|
||||
"""Remember which of the served keys a server vault supplied, and forget the rest."""
|
||||
"""Remember every served pair, and which of them a server vault supplied. ``served_keys`` also takes each pair the server accepted."""
|
||||
for kid_hex, key in keys.items():
|
||||
kid = UUID(hex=kid_hex)
|
||||
self.served_keys.add((kid, key))
|
||||
if kid_hex in vault_kids:
|
||||
self.server_vault_keys[kid] = key
|
||||
else:
|
||||
|
||||
@@ -886,7 +886,7 @@ class Track:
|
||||
|
||||
if drm:
|
||||
progress(downloaded="Decrypting", completed=0, total=None)
|
||||
decrypt_track(drm, save_path, prepare_drm, track_kid)
|
||||
decrypt_track(drm, save_path, prepare_drm, track_kid, track=self)
|
||||
if not isinstance(drm, BlowfishStripe):
|
||||
assert_fragments_decrypted(save_path)
|
||||
self.drm = None
|
||||
|
||||
Reference in New Issue
Block a user