fix(drm): stop a bridged FairPlay track whose server-CDM answer or licence key does not decrypt it

This commit is contained in:
imSp4rky
2026-12-01 21:07:27 -07:00
parent ed6ed02033
commit cefd5295ac
15 changed files with 350 additions and 25 deletions
@@ -0,0 +1,110 @@
"""The decode check of the content keys that a licence gives a bridged FairPlay-only track."""
from __future__ import annotations
from pathlib import Path
from types import SimpleNamespace
from uuid import UUID
import pytest
from tests.core.key_resolver import resolver, vaults_of
from tests.core.test_vault_bad_keys import BAD, GOOD, KID, FakeDRM, Remote
from unshackle.core.drm import key_resolution
from unshackle.core.drm.key_resolution import ContentKeyResolver
from unshackle.core.vaults import Vaults
from unshackle.vaults.SQLite import SQLite
pytestmark = pytest.mark.unit
TRACK = SimpleNamespace(id="vid")
class BridgedDRM(FakeDRM):
"""A DRM that names KID."""
def __init__(self, keys: dict[UUID, str], bridged: bool = True) -> None:
super().__init__(keys)
self.kids = [KID]
self.bridged = bridged
@pytest.fixture
def decodes(monkeypatch: pytest.MonkeyPatch) -> list[Path]:
"""Each file the decode check reads; only a file decrypted with GOOD decodes."""
checked: list[Path] = []
def ffmpeg_decodes(path: Path, start: float | None = None, seconds: float = 3, video: bool | None = None) -> bool:
checked.append(path)
return path.read_bytes() == b"plain:" + GOOD.encode()
monkeypatch.setattr(key_resolution.binaries, "FFMPEG", "ffmpeg")
monkeypatch.setattr(key_resolution, "ffmpeg_decodes", ffmpeg_decodes)
return checked
def check(tmp_path: Path, drm: BridgedDRM, vaults: Vaults | None = None, decrypt: bool = True) -> Path:
"""Decrypt a file with ``drm`` through ``decrypt_verified``, with a licence that gives GOOD.
Without ``decrypt`` the file is already plain, as after per-segment decryption.
"""
path = tmp_path / "track.mp4"
path.write_bytes(b"cipher" if decrypt else b"plain:" + drm.content_keys[KID].encode())
keys = resolver(vaults, tag="SVC")
ContentKeyResolver.LICENSE_KEY_CACHE.update(drm.content_keys)
def licence(drm: BridgedDRM, track_kid: UUID | None = None) -> None:
drm.content_keys[KID] = GOOD
try:
keys.decrypt_verified(drm, path, licence, KID, decrypt, TRACK) # type: ignore[arg-type]
finally:
keys.wait_vault_writes()
return path
@pytest.mark.parametrize("decrypt", [True, False], ids=["decrypt", "segments-decrypted"])
def test_a_licence_key_of_a_bridged_track_that_does_not_decode_stops_the_track(
tmp_path: Path, decodes: list[Path], decrypt: bool
) -> None:
local = SQLite("local", tmp_path / "local.db")
local.add_key("SVC", KID, BAD)
vaults = vaults_of(local, service="SVC")
with pytest.raises(ValueError, match=f"^The licence content key of KID {KID.hex} does not decrypt track vid$"):
check(tmp_path, BridgedDRM({KID: BAD}), vaults, decrypt)
assert decodes and not (tmp_path / "track.mp4").exists()
assert local.is_bad_key(KID, BAD) and local.get_key(KID, "SVC") is None
assert KID not in ContentKeyResolver.LICENSE_KEY_CACHE
def test_a_licence_key_of_a_bridged_track_that_decodes_is_kept(tmp_path: Path, decodes: list[Path]) -> None:
local = SQLite("local", tmp_path / "local.db")
path = check(tmp_path, BridgedDRM({KID: GOOD}), vaults_of(local, service="SVC"))
assert decodes and path.read_bytes() == b"plain:" + GOOD.encode()
assert not local.is_bad_key(KID, GOOD)
def test_a_licence_key_of_a_track_that_is_not_bridged_is_not_decoded(tmp_path: Path, decodes: list[Path]) -> None:
path = check(tmp_path, BridgedDRM({KID: BAD}, bridged=False))
assert not decodes and path.read_bytes() == b"plain:" + BAD.encode()
def test_a_bad_vault_key_of_a_bridged_track_gives_way_to_the_licence_key_which_is_checked(
tmp_path: Path, decodes: list[Path]
) -> None:
poisoned = Remote("poisoned", tmp_path / "poisoned.db")
poisoned.add_key("SVC", KID, BAD)
vaults = vaults_of(SQLite("local", tmp_path / "local.db"), poisoned, service="SVC")
drm = BridgedDRM({})
drm.content_keys[KID] = vaults.get_key(KID)[0] # type: ignore[assignment]
path = check(tmp_path, drm, vaults)
assert drm.decrypted_with == [{KID: BAD}, {KID: GOOD}]
assert path.read_bytes() == b"plain:" + GOOD.encode()
assert len(decodes) == 2 and vaults.vaults[0].is_bad_key(KID, BAD)
@@ -0,0 +1,166 @@
"""A FairPlay-only HLS track on the server CDM: the stub of the client names the key IDs that the server bridged."""
from __future__ import annotations
import dataclasses
from collections.abc import Callable, Iterator
from pathlib import Path
from types import SimpleNamespace
from typing import Any
from uuid import UUID
import pytest
from tests.core.key_resolver import key_table, resolver
from tests.core.test_hls_service_drm_keys import (
KID,
OTHER_KID,
ROTATION,
SKD_KEY,
WIDEVINE_KEY,
InitServer,
download,
hls_video,
playlist,
rotation_server,
)
from tests.remote.key_source import one_title, remote_session
from tests.remote.sessions import session_entry
from unshackle.core.api import server_keys
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 PlayReady, Widevine, cenc
from unshackle.core.tracks import Video
pytestmark = pytest.mark.unit
KEY = "ab" * 16
OTHER_KEY = "cd" * 16
FAIRPLAY_ONLY = playlist(SKD_KEY)
@pytest.fixture(autouse=True)
def no_ffprobe(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:
"""No FFprobe, and a licence failure that cancels the run does not reach the next test."""
monkeypatch.setattr(cenc, "ffprobe", lambda data: {})
yield
DOWNLOAD_CANCELLED.clear()
def server_answer(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
text: str,
licence: dict[UUID, str],
system: str = "playready",
origin: Callable[[], InitServer] = InitServer,
) -> dict[str, Any]:
"""The batch answer of the server CDM for one HLS video of ``text``, whose licence holds ``licence``.
The server service has the FairPlay bridge hook and serves an init segment with an all-zero tenc KID and a pssh
box for KID. Each field of the batch goes into the answer when it is not empty, as the licence route sends it.
"""
monkeypatch.setattr("unshackle.core.tracks.track.utf8_text", lambda response: text)
monkeypatch.setattr(server_keys, "licence_candidates", lambda *args: [system])
monkeypatch.setattr(server_keys, "find_title_for_track", lambda *args: None)
monkeypatch.setattr(
server_keys, "handle_single_server_cdm", lambda *args, **kwargs: {k.hex: v for k, v in licence.items()}
)
service = SimpleNamespace(session=origin(), fairplay_bridge=lambda: print)
session = session_entry(service_instance=service, tracks={"vid": hls_video(tmp_path, text)})
batch = server_keys.resolve_batch(session, ["vid"], system, KeyPolicy())
return {name: value for name, value in dataclasses.asdict(batch).items() if value}
def licence_on_the_client(
tmp_path: Path,
text: str,
answer: dict[str, Any],
licence: dict[UUID, str],
origin: Callable[[], InitServer] = InitServer,
asked: list[UUID | None] | None = None,
) -> Video:
"""Take the server answer as dl does, then run the licence step of the download; return the track.
A single-track licence of the server CDM answers with ``licence`` and lands in ``asked``.
"""
def license_track(track: Video, drm: Any, kid: UUID | None = None) -> dict[UUID, str]:
if asked is not None:
asked.append(kid)
return dict(licence)
remote = remote_session(None, answer)
remote.license_track = license_track # type: ignore[method-assign,assignment]
track = hls_video(tmp_path, text)
track.id = "vid"
title = one_title(track)
remote.resolve_server_keys(title) # type: ignore[arg-type]
keys = resolver(cdm=cdm_type_stub("playready"))
keys.source = remote
download(track, None, keys.licence_for(track, title, key_table()), True, origin()) # type: ignore[arg-type]
return track
def test_an_answer_without_the_content_key_of_a_bridged_track_stops_it(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""The licence holds a content key for another KID only; with the all-zero tenc KID it would decrypt the track."""
licence = {OTHER_KID: OTHER_KEY}
answer = server_answer(monkeypatch, tmp_path, FAIRPLAY_ONLY, licence)
with pytest.raises(PlayReady.Exceptions.CEKNotFound, match=f"No Content Key for KID {KID.hex} "):
licence_on_the_client(tmp_path, FAIRPLAY_ONLY, answer, licence)
def test_the_stub_of_a_bridged_track_names_the_key_ids_of_the_server(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
licence = {OTHER_KID: OTHER_KEY, KID: KEY}
answer = server_answer(monkeypatch, tmp_path, FAIRPLAY_ONLY, licence)
track = licence_on_the_client(tmp_path, FAIRPLAY_ONLY, answer, licence)
assert answer["bridge_kids"] == {"vid": [KID.hex]}
[drm] = track.drm or []
assert isinstance(drm, PlayReady) and drm.bridged
assert drm.kids == [KID] and drm.content_keys == licence
def test_the_stub_of_a_track_the_server_did_not_bridge_is_unchanged(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
answer = server_answer(monkeypatch, tmp_path, playlist(WIDEVINE_KEY), {KID: KEY}, "widevine")
remote = remote_session(None, answer)
track = hls_video(tmp_path, playlist(WIDEVINE_KEY))
track.id = "vid"
remote.resolve_server_keys(one_title(track)) # type: ignore[arg-type]
[drm] = track.drm or []
assert "bridge_kids" not in answer
assert isinstance(drm, Widevine) and not drm.bridged
def test_a_rotation_asks_the_server_cdm_for_a_key_id_its_answer_lacks(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
answer = server_answer(monkeypatch, tmp_path, ROTATION, {KID: KEY}, origin=rotation_server)
asked: list[UUID | None] = []
track = licence_on_the_client(tmp_path, ROTATION, answer, {OTHER_KID: OTHER_KEY}, rotation_server, asked)
assert answer["bridge_kids"] == {"vid": [KID.hex, OTHER_KID.hex]}
assert asked == [OTHER_KID]
[drm] = track.drm or []
assert isinstance(drm, PlayReady) and drm.content_keys == {KID: KEY, OTHER_KID: OTHER_KEY}
def test_a_rotation_without_a_later_content_key_stops_before_a_segment(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
answer = server_answer(monkeypatch, tmp_path, ROTATION, {KID: KEY}, origin=rotation_server)
with pytest.raises(PlayReady.Exceptions.CEKNotFound, match=f"No Content Key for KID {OTHER_KID.hex} "):
licence_on_the_client(tmp_path, ROTATION, answer, {}, rotation_server)
+5 -2
View File
@@ -81,7 +81,9 @@ def test_a_pair_the_server_accepted_is_not_posted_again() -> None:
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:
@pytest.mark.parametrize("bridged", [False, True], ids=["licence", "bridged-licence"])
def test_every_key_of_a_licence_goes_to_the_server_vault_without_a_decrypt(monkeypatch, bridged: bool) -> None:
"""A bridged licence key waits for the decode check in ``decrypt_verified``."""
licensed = {LICENSED: KEY, LATE: OTHER_KEY}
monkeypatch.setattr(Widevine, "get_content_keys", lambda self, **_: setattr(self, "content_keys", dict(licensed)))
pushed: list = []
@@ -89,12 +91,13 @@ def test_every_key_of_a_licence_goes_to_the_server_vault_without_a_decrypt(monke
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]))
drm.bridged = bridged
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)]
assert pushed == ([] if bridged else [(licensed, track)])
def test_a_failed_post_is_dropped_and_logs_nothing(caplog: pytest.LogCaptureFixture) -> None: