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": {}},
]