feat(drm): add the whole-file aes-ctr cipher and paged aac rewrite

This commit is contained in:
imSp4rky
2026-11-27 01:11:13 -07:00
parent 8cf915fd71
commit 736f1cc731
22 changed files with 1269 additions and 45 deletions
+376
View File
@@ -0,0 +1,376 @@
"""Tests for the AES-CTR whole-file cipher (``unshackle.core.drm.clearkey_ctr``)."""
from __future__ import annotations
import os
from collections.abc import Iterator
from functools import partial
from pathlib import Path
from types import SimpleNamespace
from typing import Any
import pytest
import requests
from Cryptodome.Cipher import AES
from tests.core.key_resolver import key_table, resolver
from tests.core.test_paged_aac import FIRST, config_record, file, header
from unshackle.core import binaries
from unshackle.core.config import config
from unshackle.core.constants import DOWNLOAD_ALL_DRM, DOWNLOAD_CANCELLED
from unshackle.core.drm import PAGED_AAC, ClearKeyCTR
from unshackle.core.drm.paged_aac import to_adts
from unshackle.core.tracks import Audio, Track
from unshackle.core.tracks import track as track_module
from unshackle.core.wire import build_tracks, reconstruct_drm, serialize_audio_track, serialize_drm
KEY = bytes.fromhex("00112233445566778899aabbccddeeff")
IV = bytes.fromhex("72e067fbddcbcf77ebe8bc643f630d93")
MAGIC = b"OggS"
def ctr_encrypt(data: bytes) -> bytes:
"""Reference encryption: one counter stream over the whole file."""
return AES.new(KEY, AES.MODE_CTR, nonce=b"", initial_value=int.from_bytes(IV, "big")).encrypt(data)
def keyed(magic: bytes = MAGIC, skip: int = 0) -> ClearKeyCTR:
"""A cipher that holds its content key from the start."""
return ClearKeyCTR(None, IV, magic, skip, key=KEY)
def test_decrypt_round_trip(tmp_path: Path) -> None:
plain = MAGIC + os.urandom((1 << 20) * 3 + 123)
path = tmp_path / "track.ogg"
path.write_bytes(ctr_encrypt(plain))
assert path.read_bytes() != plain
ClearKeyCTR(lambda: KEY, IV, MAGIC).decrypt(path)
assert path.read_bytes() == plain
assert list(tmp_path.iterdir()) == [path]
def test_hex_strings_build_the_same_cipher(tmp_path: Path) -> None:
plain = MAGIC + os.urandom(5000)
path = tmp_path / "track.ogg"
path.write_bytes(ctr_encrypt(plain))
ClearKeyCTR(lambda: KEY.hex(), IV.hex(), MAGIC.hex()).decrypt(path)
assert path.read_bytes() == plain
def test_the_key_is_licensed_once_on_first_use(tmp_path: Path) -> None:
calls = []
def licence() -> bytes:
calls.append(1)
return KEY
cipher = ClearKeyCTR(licence, IV, MAGIC)
assert cipher.key is None
for name in ("a.ogg", "b.ogg"):
path = tmp_path / name
path.write_bytes(ctr_encrypt(MAGIC + os.urandom(100)))
cipher.decrypt(path)
assert calls == [1]
assert cipher.key == KEY
def test_other_lengths_are_refused() -> None:
with pytest.raises(ValueError, match="16-byte IV"):
ClearKeyCTR(lambda: KEY, IV + IV, MAGIC)
with pytest.raises(ValueError, match="16-byte key"):
ClearKeyCTR(lambda: KEY[:15], IV, MAGIC).content_key()
def test_no_signature_is_refused() -> None:
with pytest.raises(ValueError, match="signature"):
ClearKeyCTR(lambda: KEY, IV, b"")
def test_negative_skip_is_refused() -> None:
with pytest.raises(ValueError, match="skip"):
keyed(skip=-1)
@pytest.mark.parametrize("header_size", [167, (1 << 20) + 167], ids=["short", "longer-than-one-chunk"])
def test_skip_drops_a_header_in_front_of_the_media(tmp_path: Path, header_size: int) -> None:
header, plain = os.urandom(header_size), MAGIC + os.urandom((1 << 20) + 5)
path = tmp_path / "track.ogg"
path.write_bytes(ctr_encrypt(header + plain))
keyed(skip=header_size).decrypt(path)
assert path.read_bytes() == plain
assert list(tmp_path.iterdir()) == [path]
def test_skip_past_the_end_raises_and_keeps_the_input(tmp_path: Path) -> None:
encrypted = ctr_encrypt(MAGIC + os.urandom(10))
path = tmp_path / "track.ogg"
path.write_bytes(encrypted)
with pytest.raises(ValueError, match="does not start with"):
keyed(skip=1 << 21).decrypt(path)
assert path.read_bytes() == encrypted
def test_magic_accepts_the_expected_signature(tmp_path: Path) -> None:
path = tmp_path / "track.flac"
path.write_bytes(ctr_encrypt(b"fLaC" + os.urandom(5000)))
keyed(magic=b"fLaC").decrypt(path)
assert path.read_bytes().startswith(b"fLaC")
assert list(tmp_path.iterdir()) == [path]
TRIMMABLE = header(FIRST, total=7081, first_record=config_record(true=1000)) + FIRST
def test_a_paged_file_that_cannot_be_cut_becomes_one_adts_stream(tmp_path: Path) -> None:
paged = file(FIRST)
path = tmp_path / "track.m4a"
path.write_bytes(ctr_encrypt(paged))
keyed(PAGED_AAC).decrypt(path)
assert path.read_bytes() == to_adts(paged)
assert path.read_bytes().startswith(b"\xff\xf1")
assert list(tmp_path.iterdir()) == [path]
def test_a_paged_file_without_mp4box_becomes_one_adts_stream(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(binaries, "MP4Box", None)
path = tmp_path / "track.m4a"
path.write_bytes(ctr_encrypt(TRIMMABLE))
keyed(PAGED_AAC).decrypt(path)
assert path.read_bytes() == to_adts(TRIMMABLE)
assert list(tmp_path.iterdir()) == [path]
def test_a_paged_file_becomes_an_m4a_file_through_mp4box(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
calls: list[list[str]] = []
streams: list[bytes] = []
def step(args: list[str | Path], *, output: Path | None, label: str = "") -> bytes:
calls.append([str(arg) for arg in args])
streams.append(Path(args[4][:-4]).read_bytes())
output.write_bytes(b"M4A")
return b""
monkeypatch.setattr(binaries, "MP4Box", Path("MP4Box"))
monkeypatch.setattr("unshackle.core.drm.clearkey_ctr.run_step", step)
path = tmp_path / "track.m4a"
path.write_bytes(ctr_encrypt(TRIMMABLE))
keyed(PAGED_AAC).decrypt(path)
adts, output = Path(calls[0][4].removesuffix(":psx")), Path(calls[0][-1])
assert path.read_bytes() == b"M4A"
assert streams == [to_adts(TRIMMABLE)]
assert calls == [
[
"MP4Box",
"-for-test",
"--moovts=-1",
"-add",
f"{adts}:psx",
"-edits",
"1=re0-1000/44100,6081/44100",
"-new",
str(output),
]
]
assert adts.parent == output.parent == tmp_path and adts.suffix == ".aac" and output.suffix == ".m4a"
assert list(tmp_path.iterdir()) == [path]
def test_a_failed_mp4box_step_leaves_one_adts_stream(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
def fail(args: list[str | Path], *, output: Path | None, label: str = "") -> bytes:
raise RuntimeError(f"{label} failed: unknown option")
monkeypatch.setattr(binaries, "MP4Box", Path("MP4Box"))
monkeypatch.setattr("unshackle.core.drm.clearkey_ctr.run_step", fail)
path = tmp_path / "track.m4a"
path.write_bytes(ctr_encrypt(TRIMMABLE))
with caplog.at_level("WARNING", logger="unshackle.core.drm.clearkey_ctr"):
keyed(PAGED_AAC).decrypt(path)
assert path.read_bytes() == to_adts(TRIMMABLE)
assert list(tmp_path.iterdir()) == [path]
assert [r.getMessage() for r in caplog.records if r.levelname == "WARNING"] == [
"MP4Box failed on track.decrypted.m4a, wrote one ADTS stream"
]
def test_any_failure_after_the_decrypt_keeps_only_the_input(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
def full(path: Path) -> None:
raise OSError("No space left on device")
monkeypatch.setattr("unshackle.core.drm.clearkey_ctr.rewrite_paged", full)
encrypted = ctr_encrypt(TRIMMABLE)
path = tmp_path / "track.m4a"
path.write_bytes(encrypted)
with pytest.raises(OSError, match="No space"):
keyed(PAGED_AAC).decrypt(path)
assert list(tmp_path.iterdir()) == [path] and path.read_bytes() == encrypted
def test_a_broken_paged_file_raises_and_keeps_the_input(tmp_path: Path) -> None:
encrypted = ctr_encrypt(file(FIRST)[:-1])
path = tmp_path / "track.m4a"
path.write_bytes(encrypted)
with pytest.raises(ValueError, match="is truncated"):
keyed(PAGED_AAC).decrypt(path)
assert path.read_bytes() == encrypted
assert list(tmp_path.iterdir()) == [path]
@pytest.mark.parametrize("start", [b"fLaX", b"XLaC", b"OggS"])
def test_magic_mismatch_raises_and_keeps_the_input(tmp_path: Path, start: bytes) -> None:
encrypted = ctr_encrypt(start + os.urandom(5000))
path = tmp_path / "track.flac"
path.write_bytes(encrypted)
with pytest.raises(ValueError, match="does not start with"):
keyed(magic=b"fLaC").decrypt(path)
assert path.read_bytes() == encrypted
assert list(tmp_path.iterdir()) == [path]
def test_serialize_carries_no_key_until_the_cipher_is_licensed() -> None:
cipher = ClearKeyCTR(lambda: KEY, IV, MAGIC)
assert serialize_drm([cipher]) == [{"type": "clearkeyctr", "iv": IV.hex(), "magic": MAGIC.hex(), "skip": 0}]
assert cipher.key is None
def test_a_track_list_from_the_server_leaves_the_key_to_the_licence_step(tmp_path: Path) -> None:
plain = MAGIC + os.urandom(100)
rebuilt = reconstruct_drm([{"type": "clearkeyctr", "iv": IV.hex(), "magic": MAGIC.hex(), "skip": 167}])
cipher = rebuilt[0]
assert isinstance(cipher, ClearKeyCTR) and (cipher.key, cipher.licence, cipher.skip) == (None, None, 167)
path = tmp_path / "track.ogg"
path.write_bytes(ctr_encrypt(b"H" * 167 + plain))
with pytest.raises(ValueError, match="no content key"):
cipher.decrypt(path)
assert path.read_bytes() != plain
cipher.take_key(KEY)
cipher.decrypt(path)
assert path.read_bytes() == plain
def test_remote_tracks_keep_the_cipher() -> None:
track = Audio(
id_="a1",
url="https://example.test/a1",
language="en",
codec=Audio.Codec.OGG,
drm=[keyed(skip=167)],
)
rebuilt = build_tracks({"audio": [serialize_audio_track(track, include_url=True)]})
drm = rebuilt.audio[0].drm[0]
assert isinstance(drm, ClearKeyCTR)
assert (drm.key, drm.iv, drm.skip, drm.magic) == (KEY, IV, 167, MAGIC)
@pytest.mark.parametrize("all_drm", [False, True], ids=["one-drm", "all-drm"])
def test_url_download_decrypts_once_without_a_kid_probe(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, all_drm: bool
) -> None:
monkeypatch.setattr(config.directories, "temp", tmp_path)
monkeypatch.setattr(Track, "get_key_id", lambda *a, **k: pytest.fail("a counter-cipher file has no KID to probe"))
monkeypatch.setattr(Track, "get_init_segment", lambda *a, **k: pytest.fail("a counter-cipher file has no header"))
monkeypatch.setattr(
track_module, "assert_fragments_decrypted", lambda path: pytest.fail("a counter-cipher file has no fragments")
)
plain = os.urandom(70000 + 5)
def downloader(**kwargs: Any) -> Iterator[dict[str, Any]]:
(Path(kwargs["output_dir"]) / kwargs["filename"]).write_bytes(ctr_encrypt(b"H" * 167 + MAGIC + plain))
yield {"file_downloaded": Path(kwargs["output_dir"]) / kwargs["filename"]}
track = Audio(
id_="a1",
url="https://example.test/a1.ogg",
language="en",
codec=Audio.Codec.OGG,
drm=[ClearKeyCTR(lambda: KEY, IV, MAGIC, skip=167)],
downloader=downloader,
)
if all_drm:
DOWNLOAD_ALL_DRM.set()
try:
track.download(
session=requests.Session(), prepare_drm=partial(lambda *a, **kw: None), progress=partial(lambda **kw: None)
)
finally:
DOWNLOAD_CANCELLED.clear()
DOWNLOAD_ALL_DRM.clear()
assert track.path is not None and track.path.read_bytes() == MAGIC + plain
assert track.drm is None
def test_the_resolver_licenses_a_lazy_cipher_at_the_licence_step() -> None:
calls = []
def licence() -> bytes:
calls.append(1)
return KEY
cipher = ClearKeyCTR(licence, IV, MAGIC)
key_resolver = resolver()
track = SimpleNamespace(drm=[cipher])
key_resolver._prepare_drm(cipher, track, SimpleNamespace(), key_table())
assert calls == [1]
key_resolver._prepare_drm(cipher, track, SimpleNamespace(), key_table())
assert calls == [1]
def test_the_resolver_asks_the_server_for_the_key_of_a_pending_cipher() -> None:
cipher = ClearKeyCTR(None, IV, MAGIC)
asked = []
source = SimpleNamespace(license_file=lambda track: asked.append(track) or KEY.hex())
track = SimpleNamespace(drm=[cipher])
resolver(source=source)._prepare_drm(cipher, track, SimpleNamespace(), key_table())
assert asked == [track]
assert cipher.key == KEY
def test_a_cancelled_run_licenses_no_cipher() -> None:
from unshackle.core.constants import DownloadCancelled
cipher = ClearKeyCTR(lambda: pytest.fail("licensed after a cancel"), IV, MAGIC)
DOWNLOAD_CANCELLED.set()
try:
with pytest.raises(DownloadCancelled):
resolver()._prepare_drm(cipher, SimpleNamespace(drm=[cipher]), SimpleNamespace(), key_table())
finally:
DOWNLOAD_CANCELLED.clear()
+239
View File
@@ -0,0 +1,239 @@
"""Tests for the paged AAC container: its pages, the ADTS stream and the cut of an M4A file (``unshackle.core.drm.paged_aac``)."""
from __future__ import annotations
import struct
import pytest
from unshackle.core.drm.paged_aac import (
PAGED_AAC,
adts_header,
audio_config,
checksum,
cut,
first_frame,
frame_sizes,
pages,
to_adts,
)
HEADER_PAGE = bytes.fromhex(
"53704143800318700901006d7034614cd13b000244ac00ff1300080400eb8a08"
"00020000f47790698988807c798188788a6a9c6e8174947c7b897f778b7b7c88"
"7d7f807c8288777d7f79857789798177817c798479887a74857f837979828576"
"8076897a7d7c7e847a77916c8678867184818d72797792778c7c8277907f8479"
"7f758f67967c1d000000f03b0007200400030000000000000000c7b02a9d"
)
CONFIG = bytes.fromhex("eb8a0800")
HEADER, SHARED = 0x80, 0x01
def page(flags: int, records: list[bytes], number: bytes = b"", shared: bytes = b"") -> bytes:
"""One page of a paged file around ``records``: with ``shared``, each record is stored without its first byte."""
stored = [record[len(shared) :] for record in records]
table = b"".join(bytes([255] * (len(record) // 255) + [len(record) % 255]) for record in stored)
body = PAGED_AAC + bytes([flags, len(table)]) + number + table + shared + b"".join(stored)
return body + struct.pack("<I", checksum(body))
def config_record(config: bytes = CONFIG, true: int = 3920204, rate: int = 44100) -> bytes:
"""The first record of a header page, with the audio config at its end."""
return (
b"\x01\x00mp4a"
+ struct.pack("<I", true)
+ b"\x02"
+ struct.pack("<H", rate)
+ b"\x00\xff\x13\x00\x08"
+ struct.pack("<H", len(config))
+ config
)
def header(data: bytes = b"", total: int = 0, first_record: bytes | None = None) -> bytes:
"""A header page for ``data``.
Its records are the audio config, ``total`` samples with the byte length of ``data``, and one more that nothing reads.
"""
return page(
HEADER,
[
config_record() if first_record is None else first_record,
b"\x02" + bytes(103) + struct.pack("<II", total, len(data)),
b"\x03" + bytes(8),
],
)
def file(*data: bytes) -> bytes:
"""A paged file: a header page that declares the byte length of ``data``, then those pages."""
return header(b"".join(data)) + b"".join(data)
def adts_frames(stream: bytes) -> list[bytes]:
"""The frames of an ADTS stream, without their headers."""
frames, pos = [], 0
while pos < len(stream):
assert stream[pos : pos + 2] == b"\xff\xf1"
length = ((stream[pos + 3] & 3) << 11) | (stream[pos + 4] << 3) | (stream[pos + 5] >> 5)
frames.append(stream[pos + 7 : pos + length])
pos += length
return frames
def fletcher_32(data: bytes) -> int:
"""The page checksum by its definition, one word at a time."""
total = running = 0xFFFF
for word in (int.from_bytes(data[pos : pos + 2], "little") for pos in range(0, len(data), 2)):
total = (total + word) % 0xFFFF or 0xFFFF
running = (running + total) % 0xFFFF or 0xFFFF
return running << 16 | total
FIRST = page(0, [b"\x01abc", b"\x00de"], number=b"\x00\x01")
LATER = page(0, [b"\x01xy"], number=b"\x00\x04")
def test_the_header_page_of_a_real_file_passes_its_checksum() -> None:
assert checksum(HEADER_PAGE[:-4]) == 0x9D2AB0C7
assert checksum(b"") == 0xFFFFFFFF
@pytest.mark.parametrize("data", [b"\x01", b"\x01\x02\x03", bytes(6), b"\xff\xff" * 300, bytes(range(256))])
def test_the_checksum_matches_its_definition(data: bytes) -> None:
assert checksum(data) == fletcher_32(data)
def test_the_header_page_of_a_real_file_names_the_rate_and_the_channels() -> None:
flags, number, records = next(pages(HEADER_PAGE))
assert (flags, number) == (HEADER, 0)
assert [len(record) for record in records] == [24, 112, 9]
assert audio_config(records) == (7, 1)
def test_the_header_page_of_a_real_file_declares_the_length_of_its_data_pages() -> None:
with pytest.raises(ValueError, match="truncated: 158 bytes of 270501"):
to_adts(HEADER_PAGE)
def test_the_header_page_of_a_real_file_gives_the_cut_of_its_m4a_file() -> None:
assert cut(HEADER_PAGE) == (6081, 3920204, 44100)
@pytest.mark.parametrize(
("config", "true", "total", "expected"),
[
pytest.param(CONFIG, 1000, 7081, (6081, 1000, 44100), id="fits"),
pytest.param(CONFIG, 1000, 7080, None, id="one-sample-short"),
pytest.param(CONFIG, 0, 7081, None, id="no-samples"),
pytest.param(bytes.fromhex("138800"), 1000, 7081, None, id="aac-lc"),
],
)
def test_the_cut_needs_he_aacv2_and_a_sample_count_that_fits(
config: bytes, true: int, total: int, expected: tuple[int, int, int] | None
) -> None:
assert cut(header(FIRST, total=total, first_record=config_record(config, true=true)) + FIRST) == expected
def test_the_cut_reads_the_rate_of_the_header_page() -> None:
data = header(FIRST, total=7081, first_record=config_record(true=1000, rate=48000)) + FIRST
assert cut(data) == (6081, 1000, 48000)
def test_no_cut_comes_from_a_header_page_without_the_sample_counts() -> None:
assert cut(page(HEADER, [config_record(), b"\x02" + bytes(7)]) + FIRST) is None
def test_each_frame_gets_the_adts_header_of_the_header_page() -> None:
long = b"\x01" + bytes(range(256)) * 2
second = page(SHARED, [b"\x01xy", b"\x01z"], number=b"\x00\x03", shared=b"\x01")
stream = to_adts(file(page(0, [b"\x01abc", long], number=b"\x00\x01"), second))
assert stream[:7] == bytes.fromhex("fff15c40017ffc")
assert adts_frames(stream) == [b"\x01abc", long, b"\x01xy", b"\x01z"]
def test_a_stored_frame_of_255_bytes_laces_as_255_then_0() -> None:
shared = page(SHARED, [b"\xff" + bytes(255)], number=b"\x00\x01", shared=b"\xff")
assert shared[8:11] == bytes([255, 0, 255])
assert adts_frames(to_adts(file(shared))) == [b"\xff" + bytes(255)]
def test_a_lacing_entry_of_255_continues_the_frame() -> None:
assert frame_sizes(bytes([255, 3, 7])) == [258, 7]
@pytest.mark.parametrize(
("field", "expected"),
[
(b"\x00\x01", (1, 2)),
(b"\x81\x00\x00", (0x10000, 3)),
(b"\xc1\x00\x00\x00", (0x1000000, 4)),
(b"\xe0\x12\x34\x56\x78", (0x12345678, 5)),
],
)
def test_the_number_of_the_first_frame_grows_with_its_value(field: bytes, expected: tuple[int, int]) -> None:
assert first_frame(field, 0) == expected
def test_a_frame_too_long_for_adts_raises() -> None:
with pytest.raises(ValueError, match="too long for ADTS"):
adts_header(0x1FFF, 7, 1)
def test_an_empty_file_has_no_page() -> None:
assert list(pages(b"")) == []
@pytest.mark.parametrize("padding", [1, 2, 3, 4, 4096])
def test_zero_bytes_after_the_last_page_are_dropped(padding: int) -> None:
assert to_adts(file(FIRST) + bytes(padding)) == to_adts(file(FIRST))
@pytest.mark.parametrize(
("data", "reason"),
[
pytest.param(file(FIRST, FIRST), "out of sequence", id="repeated-page"),
pytest.param(file(FIRST, LATER), "out of sequence", id="skipped-page"),
pytest.param(file(FIRST)[:-1], "is truncated", id="cut-inside-a-page"),
pytest.param(file(FIRST, LATER)[: -len(LATER)], "is truncated", id="cut-at-a-page-boundary"),
pytest.param(file(FIRST)[:-4] + bytes(4), "Checksum mismatch", id="wrong-checksum"),
pytest.param(
file(FIRST).replace(PAGED_AAC + b"\x00", PAGED_AAC + b"\x02", 1), "no valid page", id="unknown-flag"
),
pytest.param(
file(page(HEADER, [bytes(10)], number=b"\x00\x01")), "no valid page", id="header-flag-on-a-data-page"
),
pytest.param(FIRST + header(), "no valid page", id="no-header-on-the-first-page"),
pytest.param(
header(FIRST + bytes(20)) + FIRST + bytes(20), "no valid page", id="zeros-inside-the-declared-length"
),
pytest.param(
file(PAGED_AAC + b"\x00\x01\x00\x01\xff" + bytes(255) + bytes(4)),
"continues past its page",
id="frame-past-the-page",
),
pytest.param(header(FIRST, first_record=bytes(24)) + FIRST, "no AudioSpecificConfig", id="no-audio-config"),
pytest.param(
header(FIRST, first_record=config_record(bytes.fromhex("200800"))) + FIRST,
"cannot carry",
id="aac-that-adts-cannot-carry",
),
pytest.param(header(), "no AAC frame", id="no-data-page"),
pytest.param(
file(page(0, [b"\x01" + bytes(0x1FFF)], number=b"\x00\x01")), "too long for ADTS", id="frame-too-long"
),
pytest.param(b"OggS" + bytes(200), "no valid page", id="not-a-paged-file"),
pytest.param(header()[:-1], "runs past the end", id="truncated-header"),
pytest.param(file(FIRST) + LATER, "not zero after", id="page-after-the-declared-end"),
pytest.param(file(FIRST) + b"\x01", "not zero after", id="byte-after-the-declared-end"),
pytest.param(page(HEADER, [config_record()]) + FIRST, "declares no length", id="no-length-record"),
],
)
def test_a_file_that_is_not_well_formed_raises(data: bytes, reason: str) -> None:
with pytest.raises(ValueError, match=reason):
to_adts(data)
+6 -4
View File
@@ -14,7 +14,7 @@ import pytest
from tests.core.test_all_drm import playready, widevine
from unshackle.core.constants import DOWNLOAD_CANCELLED
from unshackle.core.drm import ClearKey, ClearKeyCENC, MonaLisa, verify
from unshackle.core.drm import ClearKey, ClearKeyCENC, ClearKeyCTR, MonaLisa, verify
from unshackle.core.events import events
from unshackle.core.manifests.segment_pipeline import (
RollingMerge,
@@ -199,7 +199,7 @@ def test_a_short_rolling_merge_raises_and_removes_the_output(tmp_path):
check_merged(merger, 0, SimpleNamespace(id="EXAMPLE"), ctx, "EXAMPLE") # type: ignore[arg-type]
WV, PR, CKC, ML, AES = "Widevine", "PlayReady", "ClearKeyCENC", "MonaLisa", "ClearKey"
WV, PR, CKC, ML, AES, CTR = "Widevine", "PlayReady", "ClearKeyCENC", "MonaLisa", "ClearKey", "ClearKeyCTR"
PSSH_KID = UUID(hex="22222222222222222222222222222222")
PROBED_KID = UUID(hex="33333333333333333333333333333333")
URL, DASH_, HLS_, ISM_ = (Track.Descriptor.URL, Track.Descriptor.DASH, Track.Descriptor.HLS, Track.Descriptor.ISM)
@@ -216,6 +216,8 @@ def make_drm(system: str, monkeypatch: pytest.MonkeyPatch) -> Any:
if system == ML:
monkeypatch.setattr(MonaLisa, "extract_keys", lambda self: None)
return MonaLisa("EXAMPLE", Path("unused.mld"))
if system == CTR:
return ClearKeyCTR(None, bytes(16), b"OggS")
return ClearKey(key=bytes(16))
@@ -224,11 +226,11 @@ def licence_calls(tmp_path: Path) -> tuple[DownloadContext, list[tuple[Any, Any]
return make_ctx(tmp_path, license_widevine=lambda drm, track_kid: calls.append((drm, track_kid))), calls
LICENSED = {URL: {WV, PR, CKC}, DASH_: {WV, PR, CKC}, HLS_: {WV, PR, ML}, ISM_: {WV, PR}}
LICENSED = {URL: {WV, PR, CKC, CTR}, DASH_: {WV, PR, CKC}, HLS_: {WV, PR, ML}, ISM_: {WV, PR}}
@pytest.mark.parametrize("descriptor", list(LICENSED), ids=lambda d: d.name)
@pytest.mark.parametrize("system", [WV, PR, CKC, ML, AES])
@pytest.mark.parametrize("system", [WV, PR, CKC, ML, AES, CTR])
def test_the_licence_step_licenses_the_systems_each_manifest_kind_licensed(tmp_path, monkeypatch, descriptor, system):
ctx, calls = licence_calls(tmp_path)
drm = make_drm(system, monkeypatch)
+22 -3
View File
@@ -21,7 +21,7 @@ from tests.core.test_zero_kid_fallback import _playready_pssh
from unshackle.commands.dl import dl
from unshackle.core import wire
from unshackle.core.config import config
from unshackle.core.drm import BlowfishStripe, ClearKeyCENC, PlayReady, Widevine
from unshackle.core.drm import BlowfishStripe, ClearKeyCENC, ClearKeyCTR, PlayReady, Widevine
from unshackle.core.import_service import ImportService
from unshackle.core.titles import Episode, Movie, Song
from unshackle.core.titles.music import SONG_FIELDS
@@ -58,6 +58,7 @@ VIDEO_KID = UUID("00112233-4455-6677-8899-aabbccddeeff")
AUDIO_KID = UUID("ffeeddcc-bbaa-9988-7766-554433221100")
VIDEO_KEY = "0123456789abcdef0123456789abcdef"
BLOWFISH_KEY = bytes(range(16))
CTR_CIPHER = ClearKeyCTR(None, bytes(range(16, 32)), b"OggS", skip=7, key=bytes(range(16)))
class EXAMPLE:
@@ -995,11 +996,28 @@ def test_build_tracks_attaches_drm_preference_and_attachments() -> None:
assert [(a.name, a.url) for a in tracks.attachments] == [("P", "https://img.example/p.jpg")]
def every_drm() -> list:
return [
widevine(VIDEO_KID, keys=True),
playready(VIDEO_KID, AUDIO_KID),
BlowfishStripe(BLOWFISH_KEY),
CTR_CIPHER,
clearkey(),
]
def test_rest_drm_of_each_system() -> None:
drm = [widevine(VIDEO_KID, keys=True), playready(VIDEO_KID, AUDIO_KID), BlowfishStripe(BLOWFISH_KEY), clearkey()]
drm = every_drm()
assert serialize_drm(drm) == [
*REST_VIDEO["drm"],
{"type": "blowfishstripe", "key": "000102030405060708090a0b0c0d0e0f"},
{
"type": "clearkeyctr",
"key": BLOWFISH_KEY.hex(),
"iv": bytes(range(16, 32)).hex(),
"magic": "4f676753",
"skip": 7,
},
{"type": "clearkeycenc", "kids": ["00112233-4455-6677-8899-aabbccddeeff"]},
]
@@ -1023,12 +1041,13 @@ def test_export_drm_of_each_system() -> None:
def test_reconstruct_rest_drm() -> None:
drm = [widevine(VIDEO_KID, keys=True), playready(VIDEO_KID, AUDIO_KID), BlowfishStripe(BLOWFISH_KEY), clearkey()]
drm = every_drm()
rebuilt = reconstruct_drm(json_copy(serialize_drm(drm)))
assert [drm_fields(d) for d in rebuilt] == [
WIDEVINE_FIELDS,
PLAYREADY_FIELDS,
{"class": "BlowfishStripe", "kids": [], "content_keys": {}, "key": "000102030405060708090a0b0c0d0e0f"},
{"class": "ClearKeyCTR", "kids": [], "content_keys": {}},
]
@@ -10,20 +10,22 @@ import json
from types import SimpleNamespace
from uuid import UUID
import click
import pytest
from tests.remote.key_source import remote_keys
from tests.remote.key_source import one_title, remote_keys
from tests.remote.sessions import session_entry
from unshackle.core.api import handlers
from unshackle.core.api.errors import APIError
from unshackle.core.drm import BlowfishStripe
from unshackle.core.drm import BlowfishStripe, ClearKeyCTR
from unshackle.core.drm.cenc import drm_stub
from unshackle.core.remote_service import RemoteService
from unshackle.core.remote_service import RemoteError, RemoteService
pytestmark = pytest.mark.unit
KID = UUID("161219ec3df64e0eadbb3827c0ccc46d")
CDM_KID = UUID("43de497c6d1945f49acc2951696ec628")
KEYED_CIPHER = ClearKeyCTR(None, bytes(range(16, 32)), b"OggS", key=bytes(16))
def remote_service() -> RemoteService:
@@ -205,8 +207,12 @@ async def test_batch_asks_again_when_a_cached_vault_answer_lacks_the_track_kid(m
assert payload["keys"]["c"] == {KID.hex: "v", CDM_KID.hex: "c"}
@pytest.mark.parametrize("drm", [["drm"], []], ids=["with-drm", "clear"])
def test_the_server_reads_the_head_of_a_one_file_track_with_drm(drm):
@pytest.mark.parametrize(
("drm", "head"),
[(["drm"], b"head"), ([], None), ([BlowfishStripe(bytes(16))], None), ([KEYED_CIPHER], None)],
ids=["with-drm", "clear", "stripe", "ctr"],
)
def test_the_server_reads_the_head_of_a_one_file_track_with_drm(drm, head):
from unshackle.core.tracks import Video
fetched: list = []
@@ -218,9 +224,9 @@ def test_the_server_reads_the_head_of_a_one_file_track_with_drm(drm):
get_init_segment=lambda session: fetched.append(session) or b"head",
)
head = handlers.fetch_init_segment(track, "svc-session")
assert (head, fetched) == ((b"head", ["svc-session"]) if drm else (None, []))
assert (handlers.fetch_init_segment(track, "svc-session"), fetched) == (
(head, ["svc-session"]) if head else (None, [])
)
async def test_server_tells_a_remote_vault_only_when_it_served_the_pair(monkeypatch, session):
@@ -259,6 +265,67 @@ def test_resolve_server_keys_does_not_warn_for_clear_tracks(monkeypatch):
assert warnings == ["Server CDM returned no content keys for track simplenamespace (v-1)"]
def test_resolve_server_keys_takes_the_key_of_a_whole_file_cipher():
"""The server licensed the track's whole-file cipher: the client takes its key and keeps the cipher."""
svc = remote_service()
svc.log = SimpleNamespace(warning=lambda msg, *a, **k: pytest.fail(msg), debug=lambda *a, **k: None)
svc._server_cdm = True
svc.drain_server_logs = lambda: None
svc.client = SimpleNamespace(post=lambda ep, data: {"keys": {}, "file_keys": {"v-1": "aa" * 16}})
cipher = ClearKeyCTR(None, bytes(range(16)), b"OggS")
track = SimpleNamespace(id="v-1", drm=[cipher])
svc.resolve_server_keys(one_title(track))
assert track.drm == [cipher] and cipher.key == bytes.fromhex("aa" * 16)
def test_license_file_asks_the_server_for_the_key_of_a_whole_file_cipher():
"""A whole-file cipher can only be licensed by the service on the server."""
svc = remote_service()
svc.log = SimpleNamespace(warning=lambda *a, **k: None, debug=lambda *a, **k: None)
svc._server_cdm = True
sent = []
svc.client = SimpleNamespace(post=lambda ep, data, **kw: sent.append(data) or {"file_keys": {"v-1": "bb" * 16}})
cipher = ClearKeyCTR(None, bytes(range(16)), b"OggS")
track = SimpleNamespace(id="v-1", drm=[cipher])
assert svc.license_file(track) == "bb" * 16
assert sent == [{"mode": "server_cdm", "drm_type": "clearkeyctr", "track_id": "v-1"}]
@pytest.mark.parametrize(
("grants", "answer", "message"),
[
({"_server_cdm": False}, None, "needs a server licence"),
({"_local_vaults_only": True}, None, "needs a server licence"),
({}, {"keys": {}}, "sent no content key"),
({}, RemoteError("Content key tool not found: tool", "SERVICE_ERROR"), "Content key tool not found"),
],
ids=["no-grant", "server-device", "no-key", "refused"],
)
def test_a_cipher_the_server_does_not_license_raises(grants, answer, message):
"""A whole-file cipher the server gives no key for stops the track with one DRM error before its download."""
svc = remote_service()
svc._server_cdm = True
for name, value in grants.items():
setattr(svc, name, value)
def post(ep, data, **kw):
if isinstance(answer, BaseException):
raise answer
return answer if answer is not None else pytest.fail("asked the server")
svc.client = SimpleNamespace(post=post)
cipher = ClearKeyCTR(None, bytes(range(16)), b"OggS")
with pytest.raises(click.ClickException, match=message) as stopped:
svc.license_file(SimpleNamespace(id="v-1", drm=[cipher]))
assert stopped.value.error_code == "DRM_ERROR"
def resolve(manifest_drm, drm_type="widevine"):
"""Run resolve_server_keys for one track the server answers with its own key and a sibling."""
svc = remote_service()
@@ -324,10 +391,11 @@ def test_a_cdm_licence_unflags_a_pair_a_client_reported(monkeypatch, tmp_path):
assert local.get_key(KID, "SVC") == "ab" * 16
async def test_a_stripe_cipher_track_is_clear_and_never_licensed(monkeypatch):
"""A track whose only DRM needs no licence goes to clear_tracks and keeps its DRM for the client."""
track = SimpleNamespace(id="aud", drm=[BlowfishStripe(bytes(16))])
async def batch_answer(monkeypatch, track, vault_only=False, request=None, server_device=False):
"""The server's licence answer for one track, with every CDM call stubbed out."""
session = session_entry(service_tag="SVC", tracks={"aud": track})
session.server_cdm, session.server_vault = not vault_only, vault_only
session.server_device = server_device
async def validated(sid, req):
return session
@@ -340,13 +408,80 @@ async def test_a_stripe_cipher_track_is_clear_and_never_licensed(monkeypatch):
monkeypatch.setattr(handlers, "fetch_init_segment", lambda track, sess: None)
monkeypatch.setattr(handlers, "handle_single_server_cdm", lambda *a, **k: pytest.fail("licensed a clear track"))
monkeypatch.setattr(handlers.config, "serve", {"users": {}}, raising=False)
resp = await handlers.session_license_handler(
{"mode": "server_cdm", "track_ids": ["aud"], "drm_type": "widevine"}, "sess", None
request or {"mode": "server_cdm", "track_ids": ["aud"], "drm_type": "widevine"}, "sess", None
)
return json.loads(resp.body)
assert json.loads(resp.body)["clear_tracks"] == ["aud"]
assert isinstance(track.drm[0], BlowfishStripe)
async def test_a_stripe_cipher_that_holds_its_key_is_never_licensed(monkeypatch):
"""A track whose only DRM is a stripe cipher that holds its key is named as clear and licensed by nothing."""
cipher = BlowfishStripe(bytes(16))
track = SimpleNamespace(id="aud", drm=[cipher])
body = await batch_answer(monkeypatch, track)
assert body == {"keys": {}, "clear_tracks": ["aud"]}
assert track.drm[0] is cipher
async def test_the_server_batch_licenses_a_cipher_that_holds_no_key(monkeypatch):
"""A track whose whole-file cipher holds no key yet is licensed on the server and answered under file_keys."""
cipher = ClearKeyCTR(lambda: "aa" * 16, bytes(range(16)), b"OggS")
track = SimpleNamespace(id="aud", drm=[cipher])
body = await batch_answer(monkeypatch, track)
assert (body["keys"], body["file_keys"], "clear_tracks" in body) == ({}, {"aud": "aa" * 16}, False)
assert cipher.key == bytes.fromhex("aa" * 16)
async def test_the_server_batch_answers_a_cipher_that_already_holds_its_key(monkeypatch):
"""A track the server licensed before answers its key again and licenses nothing."""
cipher = ClearKeyCTR(lambda: pytest.fail("licensed a second time"), bytes(range(16)), b"OggS")
cipher.take_key("dd" * 16)
track = SimpleNamespace(id="aud", drm=[cipher])
body = await batch_answer(monkeypatch, track)
assert (body["file_keys"], "clear_tracks" in body) == ({"aud": "dd" * 16}, False)
@pytest.mark.parametrize("refusal", ["vault_only", "server_device"])
async def test_a_session_without_live_licences_licenses_no_cipher(monkeypatch, refusal):
"""A session the server makes no live licence for gets no key of a whole-file cipher and no clear mark."""
cipher = ClearKeyCTR(lambda: pytest.fail("licensed a cipher"), bytes(range(16)), b"OggS")
track = SimpleNamespace(id="aud", drm=[cipher])
body = await batch_answer(monkeypatch, track, **{refusal: True})
assert body == {"keys": {}}
@pytest.mark.parametrize("refusal", ["vault_only", "server_device"])
async def test_one_licence_request_refuses_a_cipher_without_live_licences(monkeypatch, refusal):
"""The single-track route answers FORBIDDEN for a cipher with no key in a session without live licences."""
cipher = ClearKeyCTR(lambda: pytest.fail("licensed a cipher"), bytes(range(16)), b"OggS")
track = SimpleNamespace(id="aud", drm=[cipher])
request = {"mode": "server_cdm", "track_id": "aud", "drm_type": "clearkeyctr"}
with pytest.raises(APIError) as refused:
await batch_answer(monkeypatch, track, request=request, **{refusal: True})
assert refused.value.error_code == "FORBIDDEN"
@pytest.mark.parametrize("mode", ["server_cdm", "proxy"])
async def test_one_licence_request_answers_the_key_of_a_cipher(monkeypatch, mode):
"""The single-track licence route answers the key of a whole-file cipher, licensed or not, and calls no CDM."""
cipher = ClearKeyCTR(lambda: "bb" * 16, bytes(range(16)), b"OggS")
if mode == "proxy":
cipher.take_key("cc" * 16)
track = SimpleNamespace(id="aud", drm=[cipher])
body = await batch_answer(monkeypatch, track, request={"mode": mode, "track_id": "aud", "drm_type": "clearkeyctr"})
assert body == {"file_keys": {"aud": ("cc" if mode == "proxy" else "bb") * 16}}
def test_the_server_licence_drops_a_null_key():