feat(drm): decrypt plugin segments as they land on the fetch_segments decrypter seam

This commit is contained in:
imSp4rky
2026-12-03 15:51:42 -07:00
parent e9adc50594
commit f1f91a7d5c
14 changed files with 309 additions and 84 deletions
+7 -3
View File
@@ -16,6 +16,7 @@ from tests.core.key_resolver import MemoryVault, resolver, vaults_of
from tests.core.test_rolling_merge_hls_ism import _Handler, base, make_ctx
from tests.drm_plugins import EXAMPLE, xor
from unshackle.core import binaries, plugins
from unshackle.core.config import config
from unshackle.core.constants import DOWNLOAD_CANCELLED
from unshackle.core.drm import CustomDRM, key_resolution, verify
from unshackle.core.manifests import HLS
@@ -27,9 +28,12 @@ KEY, WRONG = "a5" * 16, "5a" * 16
PLAIN = [b"EXAMPLE clear segment %d. " % i * 8 for i in range(3)]
@pytest.fixture
def server(monkeypatch: pytest.MonkeyPatch, example_plugins: None) -> Iterator[ThreadingHTTPServer]:
"""An HLS playlist of EXAMPLE segments; ffmpeg "decodes" a file only when it is the plaintext."""
@pytest.fixture(params=[False, True], ids=["post-merge", "rolling"])
def server(
request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch, example_plugins: None
) -> Iterator[ThreadingHTTPServer]:
"""An HLS playlist of EXAMPLE segments, merged after or during the download; ffmpeg "decodes" only the plaintext."""
monkeypatch.setattr(config, "merge_segments", request.param)
monkeypatch.setattr(binaries, "FFMPEG", Path("ffmpeg"))
monkeypatch.setattr(verify, "kid_windows", lambda path: None)
monkeypatch.setattr(key_resolution, "ffmpeg_decodes", lambda path, **kw: path.read_bytes() == b"".join(PLAIN))
+18 -1
View File
@@ -13,7 +13,7 @@ from tests.core.test_hls_kid_from_init import keyed_segment, no_kid_pssh, playli
from tests.core.test_hls_service_drm_keys import KID, OTHER_KID, SKD_KEY, encrypted_init
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.drm import CustomDRM, PlayReady, Widevine, cenc
from unshackle.core.manifests.hls import HLS
from unshackle.core.manifests.hls_key_plan import HlsKeyPlan
from unshackle.core.tracks import Video
@@ -170,6 +170,23 @@ def test_one_init_segment_and_one_key_tag_make_a_single_init_track(text: str, si
assert plan.single_init(manifest.segments) is single
@pytest.mark.parametrize(
"text, single",
[
pytest.param(playlist("#EXTINF:6.0,\nseg.ts\n"), True, id="no-init-segment"),
pytest.param(playlist("#EXT-X-KEY:METHOD=NONE\n#EXTINF:6.0,\nseg.ts\n"), True, id="method-none"),
pytest.param(playlist("#EXTINF:6.0,\nseg.ts\n", "#EXTINF:6.0,\nnext.ts\n"), False, id="discontinuity"),
],
)
def test_a_cipher_that_is_not_cenc_needs_no_init_segment_or_key_tag(
example_plugins: None, text: str, single: bool
) -> None:
plan, _ = plan_of(text)
plan.drm = CustomDRM("example")
assert plan.single_init(m3u8.loads(text).segments) is single
@pytest.mark.parametrize("system, drm_class", [("playready", PlayReady), ("widevine", Widevine)])
def test_a_track_with_only_fairplay_tags_is_bridged_and_keeps_no_tag(system: str, drm_class: type) -> None:
text = playlist(f'#EXT-X-MAP:URI="a.mp4"\n{SKD_KEY}\n#EXTINF:6.0,\nseg.m4s\n')
+127 -5
View File
@@ -222,6 +222,16 @@ class FakeDRM:
kids = [KID]
CIPHER = [b"CIPHER%d" % i + b"X" * (50 + i) for i in range(len(PARTS))]
def keyed_example() -> CustomDRM:
"""An EXAMPLE plugin DRM that holds the content key of KID."""
drm = CustomDRM("example", kids=[KID])
drm.content_keys[KID] = "00" * 16
return drm
class FakeSegmentDecrypter:
"""Per-segment decryption that hands each segment straight back, with a fixed decrypted init."""
@@ -292,7 +302,7 @@ def test_ism_encrypted_rolling_matches_post_merge(server, tmp_path, monkeypatch)
def test_hls_segment_decrypt_rolling_writes_decrypted_init(server, tmp_path, monkeypatch):
monkeypatch.setattr(hls_module, "can_use", lambda *a, **kw: True)
monkeypatch.setattr(hls_module, "SegmentDecrypter", FakeSegmentDecrypter)
monkeypatch.setattr(hls_module, "make_decrypter", FakeSegmentDecrypter)
decrypted = no_decrypt(monkeypatch)
def make():
@@ -333,7 +343,7 @@ def test_dash_hands_the_drm_to_the_decrypt_step(server, tmp_path, monkeypatch):
@pytest.mark.parametrize("merge_segments", [False, True], ids=["post-merge", "rolling"])
def test_dash_segment_decrypt_writes_decrypted_init_and_only_checks(server, tmp_path, monkeypatch, merge_segments):
monkeypatch.setattr(dash_module, "can_use", lambda *a, **kw: True)
monkeypatch.setattr(dash_module, "SegmentDecrypter", FakeSegmentDecrypter)
monkeypatch.setattr(dash_module, "make_decrypter", FakeSegmentDecrypter)
monkeypatch.setattr(config, "merge_segments", merge_segments)
decrypted = no_decrypt(monkeypatch)
track = dash_track(server)
@@ -345,6 +355,31 @@ def test_dash_segment_decrypt_writes_decrypted_init_and_only_checks(server, tmp_
assert [decrypt for _, decrypt in decrypted] == [False]
@pytest.mark.parametrize("merge_segments", [False, True], ids=["post-merge", "rolling"])
def test_dash_segment_plugin_decrypts_each_segment_then_finishes(
server, tmp_path, monkeypatch, example_plugins, merge_segments
):
monkeypatch.setattr(config, "merge_segments", merge_segments)
monkeypatch.setattr(
plugins,
"PLUGINS",
{
"example": dataclasses.replace(
EXAMPLE, decrypt=lambda drm, src, dst: dst.write_bytes(src.read_bytes().upper())
)
},
)
decrypted = no_decrypt(monkeypatch)
drm = keyed_example()
track = dash_track(server)
track.drm = [drm]
ctx = make_ctx(tmp_path, "dash.mp4")
DASH.download_track(track, ctx)
assert ctx.save_path.read_bytes() == INIT + b"".join(PARTS).upper()
assert FINISHED == [ctx.save_path]
assert decrypted == [(drm, False)]
@pytest.mark.parametrize("site", ["session-drm", "plugin"])
def test_hls_licence_failure_cancels_the_other_tracks(server, tmp_path, example_plugins, site):
drm = CustomDRM("example") if site == "plugin" else widevine()
@@ -391,7 +426,7 @@ def test_hls_plugin_decrypts_every_segment_once(server, tmp_path, monkeypatch, e
hook = resolver(vaults_of(MemoryVault())).decrypt_verified if hooked else None
monkeypatch.setattr(verify, "DECRYPT_HOOK", hook)
monkeypatch.setattr(key_resolution, "ffmpeg_decodes", lambda *args, **kwargs: True)
parts = [b"CIPHER%d" % i + b"X" * (50 + i) for i in range(len(PARTS))]
parts = CIPHER
for i, part in enumerate(parts):
server.routes[f"/part{i}.m4s"] = part
lines = ["#EXTM3U", "#EXT-X-VERSION:6", "#EXT-X-TARGETDURATION:4"]
@@ -406,8 +441,7 @@ def test_hls_plugin_decrypts_every_segment_once(server, tmp_path, monkeypatch, e
lines += ["#EXTINF:4.0,", f"part{i}.m4s"]
server.routes["/v.m3u8"] = "\n".join([*lines, "#EXT-X-ENDLIST"]).encode()
track = Video(url=f"{base(server)}v.m3u8", language="en", codec=Video.Codec.HEVC, descriptor=Video.Descriptor.HLS)
drm = CustomDRM("example", kids=[KID])
drm.content_keys[KID] = "00" * 16
drm = keyed_example()
track.drm = [drm]
ctx = make_ctx(tmp_path, "plugin.mp4")
@@ -420,6 +454,94 @@ def test_hls_plugin_decrypts_every_segment_once(server, tmp_path, monkeypatch, e
assert len(FINISHED) == (mode == "segment")
def plugin_track(srv, parts: list[bytes], method_none: bool = False) -> Video:
"""An HLS track of `parts` with no init segment, whose EXAMPLE plugin DRM holds its content key."""
for i, part in enumerate(parts):
srv.routes[f"/part{i}.ts"] = part
lines = ["#EXTM3U", "#EXT-X-VERSION:3", "#EXT-X-TARGETDURATION:4"]
if method_none:
lines.append("#EXT-X-KEY:METHOD=NONE")
for i in range(len(parts)):
lines += ["#EXTINF:4.0,", f"part{i}.ts"]
srv.routes["/ts.m3u8"] = "\n".join([*lines, "#EXT-X-ENDLIST"]).encode()
track = Video(url=f"{base(srv)}ts.m3u8", language="en", codec=Video.Codec.HEVC, descriptor=Video.Descriptor.HLS)
drm = keyed_example()
track.drm = [drm]
return track
@pytest.mark.parametrize("merge_segments", [False, True])
@pytest.mark.parametrize("method_none", [False, True])
def test_hls_segment_plugin_decrypts_as_segments_land(
server, tmp_path, monkeypatch, example_plugins, merge_segments, method_none
):
"""A segment plugin decrypts on the decrypter pool, joins the rolling merge, and finishes before the decode check."""
monkeypatch.setattr(config, "merge_segments", merge_segments)
order: list[str] = []
threads: set[str] = set()
def run_tool(drm, src, dst):
threads.add(threading.current_thread().name)
dst.write_bytes(src.read_bytes().swapcase())
def finish(drm, path, track):
order.append("finish")
return True
monkeypatch.setattr(plugins, "PLUGINS", {"example": dataclasses.replace(EXAMPLE, decrypt=run_tool, finish=finish)})
def decrypt_track(drm, path, licence=None, track_kid=None, decrypt=True, track=None):
order.append(f"check decrypt={decrypt}")
for module in (segment_pipeline, hls_module):
monkeypatch.setattr(module, "decrypt_track", decrypt_track)
parts = CIPHER
ctx = make_ctx(tmp_path, "plugin.ts")
ctx.license_widevine = lambda *a, **kw: None
HLS.download_track(plugin_track(server, parts, method_none), ctx)
assert ctx.save_path.read_bytes() == b"".join(parts).swapcase()
assert threading.main_thread().name not in threads
assert order == ["finish", "check decrypt=False"]
assert ("Merging" in ctx.statuses) is not merge_segments
assert not ctx.save_dir.exists() or not list(ctx.save_dir.glob("*"))
def test_hls_segment_plugin_resumes_with_its_clear_segments(server, tmp_path, monkeypatch, example_plugins):
"""A failed segment plugin download keeps its decrypted segments, and the next run decrypts only the others."""
monkeypatch.setattr(config, "continue_downloads", True)
runs: list[bytes] = []
fail = threading.Event()
fail.set()
others_done = threading.Event()
def run_tool(drm, src, dst):
data = src.read_bytes()
if fail.is_set() and data.startswith(b"CIPHER3"):
others_done.wait(10)
raise RuntimeError("EXAMPLE decrypt failed")
dst.write_bytes(data.swapcase())
runs.append(data[:7])
if len(runs) == len(parts) - 1:
others_done.set()
monkeypatch.setattr(plugins, "PLUGINS", {"example": dataclasses.replace(EXAMPLE, decrypt=run_tool)})
no_decrypt(monkeypatch)
parts = CIPHER
ctx = make_ctx(tmp_path, "plugin.ts")
ctx.license_widevine = lambda *a, **kw: None
with pytest.raises(RuntimeError, match="EXAMPLE decrypt failed"):
HLS.download_track(plugin_track(server, parts), ctx)
kept = {int(path.stem) for path in ctx.save_dir.rglob("*.clear")}
assert kept == {0, 1, 2, 4}
fail.clear()
runs.clear()
HLS.download_track(plugin_track(server, parts), ctx)
assert runs == [b"CIPHER3"]
assert ctx.save_path.read_bytes() == b"".join(parts).swapcase()
def test_hls_aes128_keeps_post_merge(server, tmp_path, monkeypatch):
# AES-128 with no IV attribute: each segment's IV is its media sequence number
for i, part in enumerate(PARTS):
+2
View File
@@ -138,6 +138,7 @@ def test_a_mode_that_cannot_resume_withdraws_the_sidecar(tmp_path, keep):
(Video.Descriptor.HLS, DownloadMode(aes128=True), False),
(Video.Descriptor.HLS, DownloadMode(drm=ClearKeyCENC(kids=[KID])), False),
(Video.Descriptor.HLS, DownloadMode(drm=ClearKey(key=bytes(16))), False),
(Video.Descriptor.HLS, DownloadMode(segment_keys=KEY_ARGS, drm=ClearKey(key=bytes(16))), True),
],
ids=[
"dash",
@@ -154,6 +155,7 @@ def test_a_mode_that_cannot_resume_withdraws_the_sidecar(tmp_path, keep):
"hls-aes128",
"hls-clearkey-cenc",
"hls-clearkey",
"hls-segment-decrypt-other-drm",
],
)
def test_resume_verdict(tmp_path, keep, descriptor, mode, resumable):