fix(drm): keep the input when a cbcs, ClearKey, stripe or segment decrypt fails

This commit is contained in:
imSp4rky
2026-11-28 18:27:40 -07:00
parent 79cc16d290
commit 5a2680d63d
8 changed files with 214 additions and 36 deletions
+33
View File
@@ -45,6 +45,39 @@ def test_decrypt_round_trip(tmp_path: Path) -> None:
assert list(tmp_path.iterdir()) == [path]
def refuse_replace(monkeypatch: pytest.MonkeyPatch) -> None:
def refuse(self: Path, target: Path) -> None:
raise PermissionError(target)
monkeypatch.setattr(Path, "replace", refuse)
def fail_chunk(monkeypatch: pytest.MonkeyPatch) -> None:
def fail(self: BlowfishStripe, chunk: bytes) -> bytes:
raise ValueError("bad chunk")
monkeypatch.setattr(BlowfishStripe, "decrypt_chunk", fail)
@pytest.mark.parametrize(
("break_step", "raises"),
[pytest.param(fail_chunk, ValueError, id="decrypt"), pytest.param(refuse_replace, PermissionError, id="replace")],
)
def test_a_failed_decrypt_keeps_the_input(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, break_step: Any, raises: type[BaseException]
) -> None:
path = tmp_path / "track.flac"
path.write_bytes(stripe_encrypt(os.urandom(CHUNK * 4)))
original = path.read_bytes()
break_step(monkeypatch)
with pytest.raises(raises):
BlowfishStripe(KEY).decrypt(path)
assert path.read_bytes() == original
assert list(tmp_path.iterdir()) == [path]
def test_short_trailing_chunk_untouched(tmp_path: Path) -> None:
# the last stripe starts at CHUNK * 3 and holds only 100 bytes, so it stays clear
plain = os.urandom(CHUNK * 3 + 100)
+64
View File
@@ -0,0 +1,64 @@
"""Tests for the in-process cbcs decrypt (``unshackle.core.drm.cbcs.decrypt_file``)."""
from __future__ import annotations
import struct
from pathlib import Path
from typing import Any
import pytest
from tests.core.test_kid_windows import A, box, full, movie
from unshackle.core.drm import cbcs
def cbcs_track(path: Path) -> bytes:
"""Write a cbcs track with one protected sample entry and no fragments, and return its bytes."""
tenc = full(b"tenc", b"\x00\x00\x01\x00" + A.bytes + b"\x10" + bytes(16), version=1)
schm = full(b"schm", b"cbcs" + struct.pack(">I", 0x10000))
entry = box(b"encv", bytes(78), box(b"sinf", box(b"frma", b"avc1"), schm, box(b"schi", tenc)))
data = movie(entry) + box(b"mdat", bytes(16))
path.write_bytes(data)
return data
def test_decrypt_replaces_the_input(tmp_path: Path) -> None:
path = tmp_path / "track.mp4"
cbcs_track(path)
cbcs.decrypt_file(path, lambda track, entry: bytes(16))
assert b"encv" not in path.read_bytes()
assert list(tmp_path.iterdir()) == [path]
def refuse_replace(monkeypatch: pytest.MonkeyPatch) -> None:
def refuse(self: Path, target: Path) -> None:
raise PermissionError(target)
monkeypatch.setattr(Path, "replace", refuse)
def fail_rewrite(monkeypatch: pytest.MonkeyPatch) -> None:
def fail(*args: Any) -> None:
raise ValueError("bad moov")
monkeypatch.setattr(cbcs, "strip_moov_protection", fail)
@pytest.mark.parametrize(
("break_step", "raises"),
[pytest.param(fail_rewrite, ValueError, id="rewrite"), pytest.param(refuse_replace, PermissionError, id="replace")],
)
def test_a_failed_decrypt_keeps_the_input(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, break_step: Any, raises: type[BaseException]
) -> None:
path = tmp_path / "track.mp4"
original = cbcs_track(path)
break_step(monkeypatch)
with pytest.raises(raises):
cbcs.decrypt_file(path, lambda track, entry: bytes(16))
assert path.read_bytes() == original
assert list(tmp_path.iterdir()) == [path]
+17
View File
@@ -13,6 +13,7 @@ Covers the correctness guards on the whole-segment AES-128-CBC path:
from __future__ import annotations
import base64
from pathlib import Path
import m3u8
import pytest
@@ -48,6 +49,22 @@ def test_valid_encrypted_segment_decrypts(tmp_path) -> None:
assert seg.read_bytes() == plaintext
def test_a_failed_swap_keeps_the_input(tmp_path, monkeypatch) -> None:
def refuse(self, target):
raise PermissionError(target)
seg = tmp_path / "0.ts"
seg.write_bytes(encrypt(b"the quick brown fox jumps over" * 4))
original = seg.read_bytes()
monkeypatch.setattr(Path, "replace", refuse)
with pytest.raises(PermissionError):
ClearKey(key=KEY, iv=IV).decrypt(seg)
assert seg.read_bytes() == original
assert list(tmp_path.iterdir()) == [seg]
def test_clear_ts_passes_through(tmp_path) -> None:
data = clear_ts()
seg = tmp_path / "0.ts"
+37
View File
@@ -125,6 +125,43 @@ def test_segment_decrypter_keys_from_the_init_segment(tmp_path: Path, stub_mp4de
assert f"1:{KEY}" in decrypter.key_args
@POSIX_STUBS
@pytest.mark.parametrize(
("output", "stderr", "raises"),
[
pytest.param(
b"partial", "ERROR: failed to process the file (-10)\n", subprocess.CalledProcessError, id="exit-0-error"
),
pytest.param(None, "", RuntimeError, id="exit-0-no-output"),
pytest.param(b"", "", RuntimeError, id="exit-0-empty-output"),
],
)
def test_a_failed_segment_decrypt_keeps_the_segment(
tmp_path: Path,
mp4decrypt_writes: Callable[[bytes | None, int, str], None],
output: bytes | None,
stderr: str,
raises: type[BaseException],
) -> None:
mp4decrypt_writes(output, 0, stderr)
drm = _widevine(A)
drm.content_keys[A] = KEY
segment_dir = tmp_path / "segments"
segment_dir.mkdir()
segment = segment_dir / "000.mp4"
segment.write_bytes(b"segment-0")
(segment_dir / "000.mp4.dec").write_bytes(b"stale")
decrypter = SegmentDecrypter(drm, movie(encv(A)), tmp_path / "work", workers=1)
decrypter.submit(segment)
with pytest.raises(raises) as caught:
decrypter.finish()
assert segment.read_bytes() == b"segment-0"
assert list(segment_dir.iterdir()) == [segment]
assert categorize_exception(caught.value).error_code == APIErrorCode.DRM_ERROR
@pytest.mark.parametrize(("key_kid", "usable"), [(A, True), (B, False)], ids=["track-kid-keyed", "other-kid-only"])
def test_segment_decrypt_needs_a_key_for_a_kidless_track(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, key_kid: UUID, usable: bool