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
This commit is contained in:
juancarlos.cavero 2026-08-29 17:19:39 +02:00
parent 8c91403f22
commit 87adf88daa
3 changed files with 312 additions and 5 deletions

119
app.py
View file

@ -7,6 +7,8 @@ import threading
import json
import shutil
import glob
import hashlib
import hmac
import time
import zipfile
import math
@ -97,6 +99,17 @@ BILLING_ENABLED = os.environ.get("BILLING_ENABLED", "").lower() in ("1", "true",
JOB_RETENTION_SECONDS = int(
os.environ.get("JOB_RETENTION_SECONDS", "3600" if BILLING_ENABLED else "86400")
)
# The retained download of a URL job (--keep-original) is the one artifact that
# is a full copy of someone else's video rather than something we made, so it
# can be aged out ahead of the clips it produced. Defaults to the job clock,
# i.e. no change: dropping it earlier costs the clip editor, whose rerender,
# reframe, scenes and EDL endpoints all read that file and answer 409 once it
# is gone. Lower it only if you would rather lose in-session re-edits than
# keep the original around. Uploads are deliberately untouched: that file is
# the user's own content, which they attested to owning.
SOURCE_RETENTION_SECONDS = int(
os.environ.get("SOURCE_RETENTION_SECONDS", str(JOB_RETENTION_SECONDS))
)
# Force full pipeline logs to the client even under billing (local debugging).
DEBUG_LOGS = os.environ.get("DEBUG_LOGS", "").lower() in ("1", "true", "yes")
@ -986,6 +999,36 @@ def _enforce_output_size_cap():
print(f"🧹 Size cap: purged {job_id} ({size / 1024**2:.0f} MB)")
def _sweep_retained_sources(now=None):
"""Delete retained downloads older than SOURCE_RETENTION_SECONDS.
Only the ``source_video`` a URL job kept in its own directory: an upload is
the user's own file and ages out with the job like everything else. Yields
the job ids it emptied. A no-op unless the knob is set below the job clock.
"""
if SOURCE_RETENTION_SECONDS >= JOB_RETENTION_SECONDS:
return
now = time.time() if now is None else now
for job_id in os.listdir(OUTPUT_DIR):
if job_id == os.path.basename(THUMBNAILS_DIR):
continue
try:
metas = glob.glob(os.path.join(OUTPUT_DIR, job_id, "*_metadata.json"))
if not metas:
continue
with open(metas[0]) as f:
name = json.load(f).get('source_video')
if not name:
continue
src = os.path.join(OUTPUT_DIR, job_id, os.path.basename(name))
if (os.path.exists(src)
and now - os.path.getmtime(src) > SOURCE_RETENTION_SECONDS):
os.remove(src)
yield job_id
except Exception:
continue
async def cleanup_jobs():
"""Background task to remove old jobs and files."""
import time
@ -1010,6 +1053,9 @@ async def cleanup_jobs():
if job_id in jobs:
del jobs[job_id]
for job_id in _sweep_retained_sources(now):
print(f"🧹 Dropped retained source for job {job_id}")
# Hard disk cap. The time-based sweep above bounds the *age* of what
# we keep, not its size: a burst of long videos can fill the volume
# inside one retention window. Drop the oldest jobs until we're back
@ -2465,15 +2511,80 @@ def _locate_source(job_id: str):
return None
# How long a signed source URL stays valid. Long enough to survive an editing
# session and a page reload, short enough that a link leaked through a log, a
# referer or a shared screenshot is dead by the time anyone tries it.
SOURCE_URL_TTL_SECONDS = int(os.environ.get("SOURCE_URL_TTL_SECONDS", "21600"))
def _source_signature(job_id: str, exp: int) -> str:
"""HMAC tying a job id to an expiry, keyed on the app's JWT secret."""
secret = (_cloud_config.settings.jwt_secret if BILLING_ENABLED else "") or ""
msg = f"{job_id}:{exp}".encode()
return hmac.new(secret.encode(), msg, hashlib.sha256).hexdigest()[:32]
def _job_record(job_id: str):
"""The in-memory job record, or what the shared disk says about it."""
return jobs.get(job_id) or _job_view_from_disk(job_id)
def _signed_source_url(job_id: str) -> str:
"""The URL to hand a `<video>` tag for this job's source.
Every place that returns a source URL to the browser must go through here:
a caller that builds the bare path instead ships a player that cannot
authenticate, and the clip editor's source monitor 404s in cloud while
working perfectly in self-host and in every test.
"""
if not BILLING_ENABLED:
return f"/api/source/{job_id}"
exp = int(time.time()) + SOURCE_URL_TTL_SECONDS
return f"/api/source/{job_id}?exp={exp}&sig={_source_signature(job_id, exp)}"
@app.get("/api/source-url/{job_id}")
async def get_source_url(job_id: str, request: Request):
"""Mint a short-lived signed URL for this job's source video.
A `<video src>` cannot carry an Authorization header, which is why
/api/source was left open in the first place. So the owner asks for a
capability URL here, with the bearer token, and hands the player that.
"""
record = _job_record(job_id)
if record is not None:
await _assert_job_owner(request, record)
return {"url": _signed_source_url(job_id)}
@app.get("/api/source/{job_id}")
async def get_source_video(job_id: str):
async def get_source_video(job_id: str, request: Request,
exp: int = 0, sig: str = ""):
"""Stream a job's original source video for the live-analysis preview and
the clip editor's source monitor.
Uploaded sources are blob URLs in the browser and don't survive a reload,
so the recovered session points the preview here instead. Unauthenticated
like the /videos mount — the UUID job_id is the capability.
so the recovered session points the preview here instead.
This one endpoint serves the untouched original, which for a URL job is the
file we downloaded. Left open it is a public downloader wearing a UUID, so
a cloud job with an owner needs either a signed URL from /api/source-url or
a bearer token on the request. Self-host and ownerless BYOK jobs are
unchanged: there is no owner to check and no secret to sign with.
"""
signed = (
BILLING_ENABLED and sig
and exp > time.time()
and hmac.compare_digest(sig, _source_signature(job_id, exp))
)
# Gated on BILLING_ENABLED, not just on `signed`: _job_record falls through
# to _job_view_from_disk, which rescans the whole output directory. Off
# billing there is no owner to find, so that scan would run on every single
# preview load and buy nothing.
if not signed and BILLING_ENABLED:
record = _job_record(job_id)
if record is not None:
await _assert_job_owner(request, record)
source_path = _locate_source(job_id)
if not source_path:
raise HTTPException(status_code=404, detail="Source not found")
@ -3040,7 +3151,7 @@ async def get_clip_edl(job_id: str, clip_index: int, request: Request):
"words": words_out,
"source": {
"available": bool(source_path),
"url": f"/api/source/{job_id}" if source_path else None,
"url": _signed_source_url(job_id) if source_path else None,
"duration": source_duration,
"duration_estimated": duration_estimated,
},

View file

@ -1,6 +1,7 @@
import React, { useEffect, useState, useRef } from 'react';
import { Scan, Scissors, Activity, Radio, CheckCircle } from 'lucide-react';
import { getApiUrl } from '../config';
import { apiFetch } from '../lib/api';
const ProcessingAnimation = ({ media, isComplete, syncedTime, isSyncedPlaying, syncTrigger }) => {
const [videoSrc, setVideoSrc] = useState(null);
@ -18,8 +19,25 @@ const ProcessingAnimation = ({ media, isComplete, syncedTime, isSyncedPlaying, s
return () => URL.revokeObjectURL(url);
} else if (media.type === 'server') {
// Uploaded source served from the backend (survives a page reload).
// The payload is the plain /api/source/<job> path, because that is what
// gets persisted; the signed URL is minted here, at render, so a stored
// session never carries a token that has since expired. A <video> tag
// cannot send the bearer header itself, hence the round trip.
setIsYouTube(false);
setVideoSrc(getApiUrl(media.payload));
let cancelled = false;
const jobId = media.payload.split('/').pop();
(async () => {
try {
const res = await apiFetch(`/api/source-url/${jobId}`);
const { url } = await res.json();
if (!cancelled && url) setVideoSrc(getApiUrl(url));
} catch (e) {
// Self-host, or a backend without the endpoint: the open path still
// works there, and losing the preview is worse than an unsigned URL.
if (!cancelled) setVideoSrc(getApiUrl(media.payload));
}
})();
return () => { cancelled = true; };
} else if (media.type === 'url') {
setIsYouTube(true);
const videoId = getYouTubeId(media.payload);

178
tests/test_source_access.py Normal file
View file

@ -0,0 +1,178 @@
"""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}"