Files
unshackle/tests/core/test_hls_keys.py
T

467 lines
17 KiB
Python

"""The key tags and the init segment that apply to each wanted segment, at ``key_spans`` and in ``HLS.download_track``.
python-m3u8 puts an EXT-X-KEY on the next segment only. A ``--sample`` or an OnSegmentFilter that skipped that segment
made a track with a Widevine or PlayReady CDM write AES-128 ciphertext with no error. The downloads here run on real
AES-128 segments from a localhost server and compare the output with the plaintext.
"""
from __future__ import annotations
from collections.abc import Iterator, Sequence
from pathlib import Path
from typing import Any
from uuid import UUID
import m3u8
import pytest
import requests
from tests.core.test_clearkey import encrypt as aes_cbc
from tests.core.test_hls_licence_only_key_rotation import key_tag
from tests.core.test_resume_hls_integration import server as server # noqa: F401
from unshackle.core.cdm.detect import cdm_type_stub
from unshackle.core.config import config
from unshackle.core.constants import DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY
from unshackle.core.drm import Widevine
from unshackle.core.manifests import hls as hls_module
from unshackle.core.manifests.hls import HLS
from unshackle.core.manifests.hls_keys import key_spans
from unshackle.core.tracks import Audio
from unshackle.core.tracks.track import DownloadContext, Track
PLAIN = [bytes([0x41 + i]) * 752 for i in range(6)]
INIT = b"INIT" * 20
SEQUENCE = 7
KEYS = {"k1": bytes(range(16)), "k2": bytes(range(16, 32))}
K1, K2 = (f'#EXT-X-KEY:METHOD=AES-128,URI="{name}"' for name in KEYS)
NONE = "#EXT-X-KEY:METHOD=NONE"
MAP = '#EXT-X-MAP:URI="init.mp4"'
DISCONTINUITY_SEQUENCE = "#EXT-X-DISCONTINUITY-SEQUENCE:0"
SKD = '#EXT-X-KEY:METHOD=SAMPLE-AES,URI="skd://keys.example/a",KEYFORMAT="com.apple.streamingkeydelivery"'
KID_A, KID_B = UUID(int=0xA1), UUID(int=0xB2)
WV_A, WV_B = key_tag(KID_A), key_tag(KID_B)
def playlist(tags: dict[int, list[str]]) -> str:
"""A media playlist of 6 second segments, with `tags` before the segment of each index."""
lines = ["#EXTM3U", "#EXT-X-VERSION:6", "#EXT-X-TARGETDURATION:6", f"#EXT-X-MEDIA-SEQUENCE:{SEQUENCE}"]
for i in range(len(PLAIN)):
lines += [*tags.get(i, []), "#EXTINF:6.0,", f"s{i}.ts"]
return "\n".join([*lines, "#EXT-X-ENDLIST", ""])
@pytest.mark.parametrize(
"tags, wanted, expected",
[
pytest.param({}, range(6), [(0, [], None)], id="no-tag"),
pytest.param({0: [K1]}, range(6), [(0, ["k1"], None)], id="one-key"),
pytest.param({0: [K1]}, [2, 3], [(0, ["k1"], None)], id="tag-before-the-window"),
pytest.param({2: [K1]}, range(6), [(0, [], None), (2, ["k1"], None)], id="clear-lead"),
pytest.param({2: [K1]}, [0, 1], [(0, [], None)], id="tag-after-the-window"),
pytest.param(
{0: [K1], 3: [K2]}, [0, 1, 4, 5], [(0, ["k1"], None), (2, ["k2"], None)], id="second-tag-on-a-skipped"
),
pytest.param({0: [K1], 3: [K2]}, [0, 1, 2], [(0, ["k1"], None)], id="second-key-covers-none"),
pytest.param({0: [K1], 3: [K2]}, [4], [(0, ["k2"], None)], id="first-key-covers-none"),
pytest.param({0: [K1], 2: [NONE], 4: [K1]}, [0, 1, 4, 5], [(0, ["k1"], None)], id="clear-ad-tagged-again"),
pytest.param({0: [K1], 2: [K2], 4: [K1]}, [0, 1, 4, 5], [(0, ["k1"], None)], id="keyed-ad-tagged-again"),
pytest.param({0: [K1], 2: [NONE]}, [0, 1, 4], [(0, ["k1"], None), (2, [None], None)], id="clear-ad-not-tagged"),
pytest.param({0: [K1], 2: [K1]}, range(6), [(0, ["k1"], None)], id="same-tag-again"),
pytest.param({0: [SKD, WV_A]}, [3], [(0, ["skd", "data"], None)], id="two-systems"),
pytest.param(
{0: [MAP, K1], 3: [MAP.replace("init", "next")]},
[1, 4],
[(0, ["k1"], "init.mp4"), (1, ["k1"], "next.mp4")],
id="second-init",
),
pytest.param({0: [K1, DISCONTINUITY_SEQUENCE]}, range(6), [(0, ["k1"], None)], id="lost-tag"),
pytest.param({0: [SKD, K1, DISCONTINUITY_SEQUENCE]}, range(6), [(0, ["skd", "k1"], None)], id="lost-tags"),
pytest.param({0: [K1, DISCONTINUITY_SEQUENCE]}, [2], [(0, ["k1"], None)], id="lost-tag-before-the-window"),
pytest.param(
{0: [K1, DISCONTINUITY_SEQUENCE], 3: [K2]},
range(6),
[(0, ["k1"], None), (3, ["k2"], None)],
id="lost-tag-then-a-key",
),
pytest.param({0: [K1, DISCONTINUITY_SEQUENCE, K2]}, range(6), [(0, ["k2"], None)], id="lost-tag-replaced"),
pytest.param({0: [K1]}, [], [], id="nothing-wanted"),
],
)
def test_key_spans(tags: dict[int, list[str]], wanted: Any, expected: list[Any]) -> None:
manifest = m3u8.loads(playlist(tags), uri="https://example.test/media.m3u8")
spans = key_spans(manifest, [manifest.segments[i] for i in wanted])
found = [
(s.start, [k.uri and k.uri.split(":")[0] for k in s.keys], s.init_section and s.init_section.uri) for s in spans
]
assert found == expected
def test_dropped_tags_leave_no_span_with_a_key() -> None:
manifest = m3u8.loads(playlist({0: [SKD, DISCONTINUITY_SEQUENCE]}))
assert HLS.drop_unsupported_keys(manifest)
assert [span.keys for span in key_spans(manifest, manifest.segments)] == [[]]
def keys_requested(server: Any) -> list[str]:
return [path[1:] for path in server.requests if path[1:] in KEYS]
@pytest.fixture(autouse=True)
def clean_run(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:
"""No state of an earlier download, and no check of CENC output: those segments are plaintext."""
monkeypatch.setattr(hls_module, "check_decrypted", lambda *args: None)
DOWNLOAD_CANCELLED.clear()
yield
DOWNLOAD_CANCELLED.clear()
DOWNLOAD_LICENCE_ONLY.clear()
def encrypt(i: int, key: str | None) -> bytes:
"""Segment `i` under `key`, with the media sequence number as its IV."""
if key is None:
return PLAIN[i]
return aes_cbc(PLAIN[i], KEYS[key], (SEQUENCE + i).to_bytes(16, "big"))
def download(
server: Any,
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
tags: dict[int, list[str]],
keys: Sequence[str | None] = (None,) * len(PLAIN),
*,
cdm: Any,
sample: tuple[int, int] | None = None,
drop: tuple[int, ...] = (),
licence: Any = None,
) -> bytes:
"""Run HLS.download_track on segments encrypted with `keys` and return the output."""
server.routes |= {"/init.mp4": INIT, **{f"/{name}": key for name, key in KEYS.items()}}
server.routes["/media.m3u8"] = playlist(tags).encode()
for i, key in enumerate(keys):
server.routes[f"/s{i}.ts"] = encrypt(i, key)
track = Audio(
url=f"http://127.0.0.1:{server.server_address[1]}/media.m3u8",
language="en",
descriptor=Track.Descriptor.HLS,
codec=Audio.Codec.AAC,
)
track.OnSegmentFilter = lambda segment: segment.uri in {f"s{i}.ts" for i in drop}
monkeypatch.setattr(config, "sample", sample)
ctx = DownloadContext(
save_path=tmp_path / "audio.ts",
save_dir=tmp_path / "audio_segments",
progress=lambda **_: None,
session=requests.Session(),
license_widevine=licence or (lambda drm, track_kid=None: pytest.fail("a licence was requested")),
cdm=cdm,
max_workers=2,
)
HLS.download_track(track, ctx)
return ctx.save_path.read_bytes() if ctx.save_path.exists() else b""
ONE_KEY: list[str | None] = ["k1"] * 6
TWO_KEYS: list[str | None] = ["k1"] * 3 + ["k2"] * 3
@pytest.mark.parametrize("cdm", ["widevine", "playready", None])
@pytest.mark.parametrize(
"tags, keys, sample, drop, wanted, requested",
[
pytest.param({0: [K1]}, ONE_KEY, None, (), range(6), ["k1"], id="whole-track"),
pytest.param({0: [K1]}, ONE_KEY, (12, 24), (), [2, 3], ["k1"], id="sample-past-the-tag"),
pytest.param({0: [K1]}, ONE_KEY, None, (0,), range(1, 6), ["k1"], id="filter-drops-the-tagged-segment"),
pytest.param({0: [K1]}, ONE_KEY, (6, 12), (0,), [2], ["k1"], id="filter-and-sample"),
pytest.param({0: [K1], 3: [K2]}, TWO_KEYS, (24, 30), (), [4], ["k2"], id="sample-in-the-second-key"),
pytest.param({0: [K1], 3: [K2]}, TWO_KEYS, (0, 18), (), [0, 1, 2], ["k1"], id="sample-in-the-first-key"),
pytest.param(
{0: [K1], 3: [K2]}, TWO_KEYS, None, (3,), [0, 1, 2, 4, 5], ["k1", "k2"], id="filter-drops-the-second-tag"
),
pytest.param({0: [K1], 3: [K2]}, TWO_KEYS, None, (0, 1, 2), [3, 4, 5], ["k2"], id="filter-drops-the-first-key"),
pytest.param(
{0: [K1], 2: [NONE], 4: [K1]},
["k1", "k1", None, None, "k1", "k1"],
None,
(2, 3),
[0, 1, 4, 5],
["k1"],
id="clear-ad-dropped",
),
pytest.param(
{0: [K1], 2: [K2], 4: [K1]},
["k1", "k1", "k2", "k2", "k1", "k1"],
None,
(2, 3),
[0, 1, 4, 5],
["k1"],
id="keyed-ad-dropped",
),
pytest.param(
{0: [K1], 3: [NONE]},
["k1", "k1", "k1", None, None, None],
None,
(3,),
[0, 1, 2, 4, 5],
["k1"],
id="filter-drops-the-none-tag",
),
pytest.param(
{0: [K1, DISCONTINUITY_SEQUENCE]},
ONE_KEY,
None,
(),
range(6),
["k1"],
id="tag-before-discontinuity-sequence",
),
],
)
def test_aes_128_output_is_the_plaintext(
server: Any,
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
cdm: str | None,
tags: dict[int, list[str]],
keys: list[str | None],
sample: tuple[int, int] | None,
drop: tuple[int, ...],
wanted: Any,
requested: list[str],
) -> None:
stub = cdm_type_stub(cdm) if cdm else None
output = download(server, tmp_path, monkeypatch, tags, keys, cdm=stub, sample=sample, drop=drop)
assert output == b"".join(PLAIN[i] for i in wanted)
assert keys_requested(server) == requested
def test_aes_128_fmp4_is_decrypted_past_the_tag(server: Any, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""One init segment and no tag in the window is also the shape that a rolling merge takes."""
monkeypatch.setattr(config, "merge_segments", True)
output = download(
server,
tmp_path,
monkeypatch,
{0: [MAP, K1]},
ONE_KEY,
cdm=cdm_type_stub("widevine"),
sample=(12, 24),
)
assert output == INIT + PLAIN[2] + PLAIN[3]
TWO_WV = {0: [WV_A], 3: [WV_B]}
@pytest.mark.parametrize(
"sample, drop, kids",
[
pytest.param(None, (), [KID_A, KID_B], id="whole-track"),
pytest.param(None, (3,), [KID_A, KID_B], id="filter-drops-the-second-tag"),
pytest.param((24, 30), (), [KID_B], id="sample-in-the-second-key"),
pytest.param((0, 18), (), [KID_A], id="sample-in-the-first-key"),
pytest.param(None, (0, 1, 2), [KID_B], id="filter-drops-the-first-key"),
pytest.param(None, (3, 4, 5), [KID_A], id="filter-drops-the-second-key"),
],
)
@pytest.mark.parametrize("licence_only", [True, False], ids=["licence-only", "download"])
def test_only_the_keys_of_the_wanted_segments_are_licensed_and_applied(
server: Any,
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
licence_only: bool,
sample: tuple[int, int] | None,
drop: tuple[int, ...],
kids: list[UUID],
) -> None:
licensed: list[UUID | None] = []
decrypted: list[UUID] = []
def licence(drm: Widevine, track_kid: UUID | None = None) -> None:
licensed.append(track_kid)
drm.content_keys.update({kid: "01" * 16 for kid in drm.kids})
monkeypatch.setattr(
hls_module, "decrypt_track", lambda drm, path, *args, **kwargs: decrypted.append(next(iter(drm.content_keys)))
)
if licence_only:
DOWNLOAD_LICENCE_ONLY.set()
download(
server,
tmp_path,
monkeypatch,
TWO_WV,
cdm=cdm_type_stub("widevine"),
sample=sample,
drop=drop,
licence=licence,
)
assert licensed == kids
assert decrypted == ([] if licence_only else kids)
@pytest.mark.parametrize("drop", [(), (3,)], ids=["no-filter", "filter-drops-the-second-tag"])
def test_each_key_decrypts_behind_its_own_init_segment(
server: Any, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, drop: tuple[int, ...]
) -> None:
"""A dropped EXT-X-DISCONTINUITY starts no new block, so the key change alone separates the two init segments."""
monkeypatch.setattr(Audio, "get_key_id", lambda self, data: None)
server.routes |= {"/first.mp4": b"first", "/later.mp4": b"later"}
first, later = (MAP.replace("init", name) for name in ("first", "later"))
heads: list[bytes] = []
monkeypatch.setattr(
hls_module, "decrypt_track", lambda drm, path, *args, **kwargs: heads.append(path.read_bytes()[:5])
)
monkeypatch.setattr(HLS, "merge_segments", lambda segments, save_path, progress: save_path.touch())
download(
server,
tmp_path,
monkeypatch,
{0: [first, WV_A], 3: ["#EXT-X-DISCONTINUITY", later, WV_B]},
cdm=cdm_type_stub("widevine"),
drop=drop,
licence=lambda drm, track_kid=None: None,
)
assert heads == [b"first", b"later"]
@pytest.mark.parametrize("mapped", [True, False], ids=["two-keys-one-init", "one-key-no-init"])
def test_a_rotation_or_a_missing_init_segment_keeps_the_post_merge(
server: Any, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, mapped: bool
) -> None:
"""A rolling merge decrypts the whole file with the content keys of the first licence only."""
monkeypatch.setattr(config, "merge_segments", True)
monkeypatch.setattr(Audio, "get_key_id", lambda self, data: None)
rolling: list[bool] = []
fetch = hls_module.fetch_segments
monkeypatch.setattr(
hls_module,
"fetch_segments",
lambda *args, **kwargs: rolling.append(kwargs["rolling"]) or fetch(*args, **kwargs),
)
monkeypatch.setattr(hls_module, "decrypt_track", lambda *args, **kwargs: None)
download(
server,
tmp_path,
monkeypatch,
{0: [MAP, WV_A], 3: [WV_B]} if mapped else {0: [WV_A]},
cdm=cdm_type_stub("widevine"),
licence=lambda drm, track_kid=None: None,
)
assert rolling == [False]
def test_the_first_key_of_the_wanted_segments_is_licensed_before_a_segment_request(
server: Any, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
hits: list[list[str]] = []
monkeypatch.setattr(hls_module, "decrypt_track", lambda *args, **kwargs: None)
download(
server,
tmp_path,
monkeypatch,
{0: [WV_A]},
cdm=cdm_type_stub("widevine"),
sample=(12, 24),
licence=lambda drm, track_kid=None: hits.append(list(server.requests)),
)
assert hits == [["/media.m3u8"]]
@pytest.mark.parametrize(
"lead, sample, drop",
[
pytest.param(WV_A, (24, 30), (), id="sample-in-the-second-key"),
pytest.param("", None, (), id="clear-lead"),
pytest.param("", None, (0,), id="filter-in-the-clear-lead"),
],
)
def test_the_first_licence_reads_the_init_segment_of_its_own_key(
server: Any,
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
lead: str,
sample: tuple[int, int] | None,
drop: tuple[int, ...],
) -> None:
"""The Key ID comes from the init segment of the licensed key, not from the first one of the playlist."""
DOWNLOAD_LICENCE_ONLY.set()
monkeypatch.setattr(Audio, "get_key_id", lambda self, data: {b"first": KID_A, b"later": KID_B}[data])
server.routes |= {"/first.mp4": b"first", "/later.mp4": b"later"}
first, later = (MAP.replace("init", name) for name in ("first", "later"))
licensed: list[UUID | None] = []
download(
server,
tmp_path,
monkeypatch,
{0: [first, lead], 3: [later, WV_B]},
cdm=cdm_type_stub("widevine"),
sample=sample,
drop=drop,
licence=lambda drm, track_kid=None: licensed.append(track_kid),
)
assert licensed == [KID_B]
assert "/first.mp4" not in server.requests
@pytest.mark.parametrize(
"tags",
[
pytest.param({0: [MAP, SKD]}, id="first-segment"),
pytest.param({0: [MAP, SKD, DISCONTINUITY_SEQUENCE]}, id="lost"),
pytest.param({0: [MAP, WV_A], 3: [SKD]}, id="second-key"),
],
)
@pytest.mark.parametrize("cdm", ["widevine", None])
def test_a_tag_unshackle_cannot_license_is_refused_before_a_segment(
server: Any, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, cdm: str | None, tags: dict[int, list[str]]
) -> None:
with pytest.raises(NotImplementedError, match="None of the key systems are supported"):
download(
server,
tmp_path,
monkeypatch,
tags,
cdm=cdm_type_stub(cdm) if cdm else None,
)
assert not [path for path in server.requests if path.endswith(".ts")]
def test_a_lost_tag_is_bridged_with_the_first_init_segment(
server: Any, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(Audio, "get_key_id", lambda self, data: {INIT: KID_A, b"later": KID_B}[data])
server.routes["/later.mp4"] = b"later"
DOWNLOAD_LICENCE_ONLY.set()
licensed: list[UUID | None] = []
download(
server,
tmp_path,
monkeypatch,
{0: [MAP, SKD, DISCONTINUITY_SEQUENCE], 3: ["#EXT-X-DISCONTINUITY", MAP.replace("init", "later")]},
cdm=cdm_type_stub("widevine"),
licence=lambda drm, track_kid=None: licensed.append(track_kid),
)
assert licensed == [KID_A]