clipwright/tests/test_source_access.py
juancarlos.cavero 87adf88daa fix(source): stop serving the untouched original without a credential
GET /api/source streams the file we downloaded, not a derived clip, and it was
open on the reasoning that the UUID job id is the capability. That makes the
product a public YouTube downloader wearing a UUID, which is the characterisation
worth avoiding, and one leaked id in a log or a referer opens someone else's
video.

A <video src> cannot carry an Authorization header, which is why it was open in
the first place, so the owner mints a short-lived signed URL from
/api/source-url and hands the player that. The endpoint takes the signature or
falls back to the owner check. Self-host and ownerless BYOK jobs are untouched:
no owner to check, no secret to sign with. The owner lookup is gated on
BILLING_ENABLED because it falls through to a full rescan of the output
directory, which off billing would run on every preview and buy nothing.

Both minters go through _signed_source_url. The EDL feeds ClipEditor's source
monitor the same way and was built as a bare path, which works in self-host and
in every test and 404s in cloud. The regression test asserts the endpoint calls
the minter rather than comparing strings: off billing the helper returns that
same bare path, so a string comparison passes just as happily with the bug in.
Verified by putting the bug back and watching it fail.

The frontend mints at render, not when the session is persisted, or localStorage
would hold a token that expired overnight.

SOURCE_RETENTION_SECONDS can age the retained download out ahead of the clips it
produced, and defaults to the job clock, so nothing changes until someone sets
it. Lowering it is not free: the EDL, rerender, scenes and reframe endpoints all
read that file and answer 409 once it is gone.

Claude-Session: https://claude.ai/code/session_01WyFE2wXi8quZR6nLRRLDgE
2026-08-29 17:19:39 +02:00

178 lines
7.6 KiB
Python

"""Access control on the one endpoint that serves the untouched original.
/api/source streams the file we downloaded, not a derived clip, so an open
version of it is a public downloader wearing a UUID. A <video src> cannot send
an Authorization header, so the owner mints a signed URL from /api/source-url
and hands the player that.
BILLING_ENABLED=0 here (conftest), which is the self-host branch: no owner to
check and no secret to sign with, so the open path must keep working exactly as
before. That regression is most of what these tests are for.
"""
import asyncio
import json
import time
import httpx
import pytest
app_module = pytest.importorskip("app")
JOB_ID = "source-access-test-job"
def _get(path):
async def _do():
transport = httpx.ASGITransport(app=app_module.app)
async with httpx.AsyncClient(transport=transport,
base_url="http://testserver") as client:
return await client.get(path)
return asyncio.run(_do())
@pytest.fixture()
def job(tmp_path, monkeypatch):
"""A URL-style job: the retained download sits in the job dir and is named
by ``source_video`` in the metadata, which is what _locate_source reads."""
out_root = tmp_path / "output"
job_dir = out_root / JOB_ID
job_dir.mkdir(parents=True)
(tmp_path / "uploads").mkdir()
monkeypatch.setattr(app_module, "OUTPUT_DIR", str(out_root))
monkeypatch.setattr(app_module, "UPLOAD_DIR", str(tmp_path / "uploads"))
(job_dir / "source.mp4").write_bytes(b"not really a video")
# One clip and a word timeline, so the EDL endpoint has something to answer
# with: the invariant test below is worthless if it skips.
(job_dir / "x_metadata.json").write_text(json.dumps({
"source_video": "source.mp4",
"transcript": {
"language": "en",
"segments": [{
"start": 0.0, "end": 30.0, "text": "hello world",
"words": [{"word": "hello", "start": 10.0, "end": 10.4},
{"word": "world", "start": 11.0, "end": 11.4}],
}],
},
"shorts": [{
"start": 10.0, "end": 20.0, "title": "clip", "score": 90,
"video_url": "/videos/x/clip_1.mp4",
}],
}))
# Also in memory: the EDL endpoint answers from the live job record, so a
# fixture that only writes disk makes this file order-dependent — the test
# below passed only because an earlier one had triggered a disk recovery.
app_module.jobs[JOB_ID] = {
"status": "completed",
"logs": [],
"result": {"clips": [{
"start": 10.0, "end": 20.0, "title": "clip", "score": 90,
"video_url": "/videos/x/clip_1.mp4",
}]},
"user_id": None,
"watermark": False,
}
try:
yield job_dir
finally:
app_module.jobs.pop(JOB_ID, None)
class TestSelfHostStaysOpen:
def test_source_is_served_without_a_token(self, job):
r = _get(f"/api/source/{JOB_ID}")
assert r.status_code == 200
assert r.content == b"not really a video"
def test_source_url_hands_back_the_plain_path(self, job):
r = _get(f"/api/source-url/{JOB_ID}")
assert r.status_code == 200
# No secret to sign with off-billing, so no query string to mint.
assert r.json()["url"] == f"/api/source/{JOB_ID}"
def test_missing_source_is_a_404_not_a_500(self, tmp_path, monkeypatch):
monkeypatch.setattr(app_module, "OUTPUT_DIR", str(tmp_path))
monkeypatch.setattr(app_module, "UPLOAD_DIR", str(tmp_path))
assert _get("/api/source/nobody-home").status_code == 404
class TestSignature:
def test_binds_the_job_and_the_expiry(self):
exp = int(time.time()) + 60
sig = app_module._source_signature(JOB_ID, exp)
# A signature that travelled to another job, or that was stretched to a
# later expiry, must not verify — otherwise one leaked link opens
# everything, forever.
assert app_module._source_signature("other-job", exp) != sig
assert app_module._source_signature(JOB_ID, exp + 1) != sig
assert app_module._source_signature(JOB_ID, exp) == sig
def test_is_opaque(self):
exp = int(time.time()) + 60
sig = app_module._source_signature(JOB_ID, exp)
assert len(sig) == 32
assert JOB_ID not in sig and str(exp) not in sig
def test_a_stale_expiry_is_not_accepted(self, job):
# The endpoint only trusts a signature while exp is in the future; the
# check is `exp > now`, so a past one falls through to the owner check.
past = int(time.time()) - 1
r = _get(f"/api/source/{JOB_ID}?exp={past}&sig={app_module._source_signature(JOB_ID, past)}")
# Self-host has no owner, so it still serves — what matters is that the
# stale signature was not what let it through.
assert r.status_code == 200
assert not (past > time.time())
class TestRetainedSourceSweep:
"""SOURCE_RETENTION_SECONDS drops the retained download ahead of the job."""
def test_is_a_no_op_at_the_default(self, job, monkeypatch):
# Default equals the job clock: the source lives and dies with its job,
# exactly as before the knob existed.
monkeypatch.setattr(app_module, "SOURCE_RETENTION_SECONDS",
app_module.JOB_RETENTION_SECONDS)
assert list(app_module._sweep_retained_sources()) == []
assert (job / "source.mp4").exists()
def test_drops_the_download_once_it_is_older_than_the_knob(self, job, monkeypatch):
monkeypatch.setattr(app_module, "SOURCE_RETENTION_SECONDS", 60)
monkeypatch.setattr(app_module, "JOB_RETENTION_SECONDS", 3600)
assert list(app_module._sweep_retained_sources(now=time.time() + 120)) == [JOB_ID]
assert not (job / "source.mp4").exists()
# The clips and the metadata are the deliverable and must survive.
assert (job / "x_metadata.json").exists()
def test_keeps_a_download_that_is_still_young(self, job, monkeypatch):
monkeypatch.setattr(app_module, "SOURCE_RETENTION_SECONDS", 3600)
monkeypatch.setattr(app_module, "JOB_RETENTION_SECONDS", 86400)
assert list(app_module._sweep_retained_sources()) == []
assert (job / "source.mp4").exists()
def test_survives_a_job_dir_with_no_metadata(self, tmp_path, monkeypatch):
monkeypatch.setattr(app_module, "OUTPUT_DIR", str(tmp_path))
monkeypatch.setattr(app_module, "SOURCE_RETENTION_SECONDS", 1)
monkeypatch.setattr(app_module, "JOB_RETENTION_SECONDS", 3600)
(tmp_path / "half-written-job").mkdir()
(tmp_path / "loose-file.txt").write_text("not a job dir")
assert list(app_module._sweep_retained_sources(now=time.time() + 120)) == []
def test_every_source_url_the_browser_gets_comes_from_one_place(job, monkeypatch):
"""The clip editor renders edl.source.url straight into a <video src>.
It was built as a bare /api/source path while the preview used a signed
one: fine in self-host, a 404 in cloud, where the tag cannot authenticate.
The assertion has to be that the endpoint CALLS the minter, not that the
string matches: off-billing _signed_source_url returns that very same bare
path, so comparing the two strings passes just as happily with the bug in
place. Verified by putting the bug back and watching this fail.
"""
monkeypatch.setattr(app_module, "_signed_source_url",
lambda job_id: f"/signed/{job_id}")
r = _get(f"/api/clip/{JOB_ID}/0/edl")
assert r.status_code == 200, r.text
assert r.json()["source"]["available"] is True
assert r.json()["source"]["url"] == f"/signed/{JOB_ID}"