"""L1 API core: the /api/process submit matrix. The worker never runs here (ASGITransport skips lifespan), so every assertion is about the QUEUED record: validation branches, the chosen ingest path, the env overrides handed to the child, the attestation, and the on-disk resume manifest. URL tests stub ``assert_public_url`` (the autouse no-network guard would abort a real DNS lookup) and/or ``_probe_youtube_quality``; IP-literal URLs exercise the real SSRF guard without touching DNS. """ import json import os import pytest pytestmark = pytest.mark.e2e WATCH = "https://www.youtube.com/watch?v=abcdefghijk" KEY = {"X-Gemini-Key": "test-key"} @pytest.fixture def allow_urls(monkeypatch): """Let hostname URLs pass the SSRF guard without a DNS lookup.""" import clipwright.core.security_utils as security_utils monkeypatch.setattr(security_utils, "assert_public_url", lambda url: url) def _job(client, resp): assert resp.status_code == 200, resp.text body = resp.json() assert "job_id" in body return body["job_id"] async def _submit_json(client, body): return await client.post("/api/process", json=body, headers=KEY) async def _submit_file(client, data, files, headers=KEY): return await client.post("/api/process", data=data, files=files, headers=headers) # --------------------------------------------------------------------------- # # Happy paths: one per ingest source # --------------------------------------------------------------------------- # async def test_submit_url_queues_with_attestation_and_manifest( client, app_state, allow_urls, monkeypatch): monkeypatch.delenv("PUBLIC_API_URL", raising=False) resp = await _submit_json(client, {"url": WATCH, "acknowledged": True}) job_id = _job(client, resp) job = app_state.app.jobs[job_id] assert job["status"] == "queued" assert WATCH in job["cmd"] and "--keep-original" in job["cmd"] assert job["env"]["GEMINI_API_KEY"] == "test-key" assert job["attestation"]["acknowledged"] is True assert job["attestation"]["source"] == "url" assert job["attestation"]["ip"] # client host (testserver / 127.0.0.1) manifest = json.loads((app_state.out / job_id / ".resume.json").read_text()) assert manifest["cmd"] == job["cmd"] assert manifest["priority"] == 2 # Queued, not run: the queue holds exactly this one entry. assert app_state.app.job_queue.qsize() == 1 async def test_submit_multipart_file(client, app_state, media_factory): resp = await _submit_file( client, {"acknowledged": "true"}, {"file": ("clip.mp4", media_factory.six.read_bytes(), "video/mp4")}, ) job_id = _job(client, resp) job = app_state.app.jobs[job_id] input_path = job["cmd"][job["cmd"].index("-i") + 1] assert os.path.dirname(input_path) == str(app_state.up) assert os.path.basename(input_path).startswith(job_id) assert os.path.basename(input_path).endswith("clip.mp4") assert os.path.exists(input_path) assert job["attestation"]["source"] == "file" async def test_submit_completed_upload_id(client, app_state, media_factory): reserved = await client.post("/api/uploads", json={"filename": "clip.mp4"}) uid = reserved.json()["upload_id"] assert (await client.put(f"/api/uploads/{uid}", content=media_factory.six.read_bytes())).status_code == 200 resp = await _submit_json(client, {"upload_id": uid, "acknowledged": True}) job_id = _job(client, resp) job = app_state.app.jobs[job_id] input_path = job["cmd"][job["cmd"].index("-i") + 1] assert os.path.exists(input_path) assert os.path.basename(input_path) == f"{job_id}_clip.mp4" assert uid not in app_state.app.pending_uploads assert job["attestation"]["source"] == "upload_id" async def test_submit_thumbnail_session_id(client, app_state, media_factory, monkeypatch): sid = "sess-e2e" app_state.app.thumbnail_sessions[sid] = { "user_id": None, "video_path": str(media_factory.six), "transcript_ready": False, "transcript": None, } resp = await _submit_json(client, {"thumbnail_session_id": sid, "acknowledged": True}) job_id = _job(client, resp) job = app_state.app.jobs[job_id] assert "-i" in job["cmd"] assert os.path.exists(job["cmd"][job["cmd"].index("-i") + 1]) assert job["attestation"]["source"] == "thumbnail_session" async def test_submit_thumbnail_session_missing_404(client, app_state): resp = await _submit_json(client, {"thumbnail_session_id": "nope", "acknowledged": True}) assert resp.status_code == 404 # --------------------------------------------------------------------------- # # Validation branches # --------------------------------------------------------------------------- # async def test_submit_without_input_is_400(client): resp = await _submit_json(client, {"acknowledged": True}) assert resp.status_code == 400 assert "Must provide URL, File or upload_id" in resp.json()["detail"] async def test_submit_without_ack_is_400(client, allow_urls): resp = await _submit_json(client, {"url": WATCH}) assert resp.status_code == 400 assert "confirm you own the content" in resp.json()["detail"] async def test_submit_without_key_is_400(client, media_factory, monkeypatch): monkeypatch.delenv("GEMINI_API_KEY", raising=False) monkeypatch.delenv("LLM_BASE_URL", raising=False) monkeypatch.delenv("LLM_PROVIDER", raising=False) resp = await _submit_file( client, {"acknowledged": "true"}, {"file": ("clip.mp4", media_factory.six.read_bytes(), "video/mp4")}, headers={}, ) assert resp.status_code == 400 assert resp.json()["detail"] == "Missing X-Gemini-Key header" async def test_submit_without_key_but_local_llm_queues( client, app_state, media_factory, monkeypatch): monkeypatch.delenv("GEMINI_API_KEY", raising=False) monkeypatch.setenv("LLM_PROVIDER", "openai") monkeypatch.setenv("LLM_BASE_URL", "http://127.0.0.1:9") resp = await _submit_file( client, {"acknowledged": "true"}, {"file": ("clip.mp4", media_factory.six.read_bytes(), "video/mp4")}, headers={}, ) job_id = _job(client, resp) # A local-LLM job must not leak a stale Google key into the child env. assert "GEMINI_API_KEY" not in app_state.app.jobs[job_id]["env"] async def test_submit_youtube_disabled_is_403(client, app_state, allow_urls, monkeypatch): monkeypatch.setattr(app_state.app, "DISABLE_YOUTUBE_URL", True) resp = await _submit_json(client, {"url": WATCH, "acknowledged": True}) assert resp.status_code == 403 assert "disabled on this deployment" in resp.json()["detail"] async def test_submit_playlist_is_400(client, allow_urls): resp = await _submit_json(client, { "url": "https://www.youtube.com/playlist?list=PLabc", "acknowledged": True, }) assert resp.status_code == 400 assert "playlist" in resp.json()["detail"] async def test_submit_ssrf_url_is_400(client): # Real guard, IP literal -> no DNS, rejected as non-public. resp = await _submit_json(client, { "url": "http://169.254.169.254/latest/meta-data", "acknowledged": True, }) assert resp.status_code == 400 assert "can't be processed" in resp.json()["detail"] async def test_submit_short_source_is_400(client, app_state, allow_urls, monkeypatch): monkeypatch.setattr(app_state.app, "MIN_SOURCE_SECONDS", 45) monkeypatch.setattr(app_state.app, "QUALITY_GATE_MIN_HEIGHT", 0) async def probe(url): return {"duration": 10, "max_height": 1080} monkeypatch.setattr(app_state.app, "_probe_youtube_quality", probe) resp = await _submit_json(client, {"url": WATCH, "acknowledged": True}) assert resp.status_code == 400 assert "10s" in resp.json()["detail"] # The aborted job dir must not linger (only the thumbnails mount remains). assert [p.name for p in app_state.out.iterdir()] == ["thumbnails"] async def test_quality_gate_needs_confirmation_then_force_low_quality( client, app_state, allow_urls, monkeypatch): monkeypatch.setattr(app_state.app, "QUALITY_GATE_MIN_HEIGHT", 720) monkeypatch.setattr(app_state.app, "MIN_SOURCE_SECONDS", 0) async def probe(url): return {"duration": 600, "max_height": 480} monkeypatch.setattr(app_state.app, "_probe_youtube_quality", probe) first = await _submit_json(client, {"url": WATCH, "acknowledged": True}) assert first.status_code == 200 assert first.json()["needs_confirmation"] is True assert first.json()["quality_check"]["max_height"] == 480 assert first.json()["quality_check"]["min_height"] == 720 assert app_state.app.jobs == {} forced = await _submit_json(client, { "url": WATCH, "acknowledged": True, "force_low_quality": True, }) job_id = _job(client, forced) assert app_state.app.jobs[job_id]["status"] == "queued" async def test_submit_bad_webhook_is_400(client, media_factory): resp = await _submit_file( client, {"acknowledged": "true", "webhook_url": "http://127.0.0.1/hook"}, {"file": ("clip.mp4", media_factory.six.read_bytes(), "video/mp4")}, ) assert resp.status_code == 400 assert "Invalid webhook_url" in resp.json()["detail"] async def test_target_clips_validation(client, media_factory): bad_type = await _submit_file( client, {"acknowledged": "true", "target_clips": "lots"}, {"file": ("clip.mp4", media_factory.six.read_bytes(), "video/mp4")}, ) assert bad_type.status_code == 400 assert "target_clips must be a number" in bad_type.json()["detail"] out_of_range = await _submit_file( client, {"acknowledged": "true", "target_clips": "0"}, {"file": ("clip.mp4", media_factory.six.read_bytes(), "video/mp4")}, ) assert out_of_range.status_code == 400 assert "target_clips must be between 1 and 31" in out_of_range.json()["detail"] async def test_target_clips_accepts_raised_ceiling( client, app_state, media_factory): # The ceiling was raised from 15 to 31; the top of the new band must queue # with the override the selector reads, and 32 must still be rejected. resp = await _submit_file( client, {"acknowledged": "true", "target_clips": "31"}, {"file": ("clip.mp4", media_factory.six.read_bytes(), "video/mp4")}, ) job_id = _job(client, resp) env = app_state.app.jobs[job_id]["env"] assert env["CLIP_TARGET_MIN"] == "31" and env["CLIP_TARGET_MAX"] == "31" too_many = await _submit_file( client, {"acknowledged": "true", "target_clips": "32"}, {"file": ("clip.mp4", media_factory.six.read_bytes(), "video/mp4")}, ) assert too_many.status_code == 400 assert "target_clips must be between 1 and 31" in too_many.json()["detail"] async def test_clip_range_validation(client, media_factory): too_short = await _submit_file( client, {"acknowledged": "true", "clip_min_seconds": "2"}, {"file": ("clip.mp4", media_factory.six.read_bytes(), "video/mp4")}, ) assert too_short.status_code == 400 assert "clip_min_seconds must be between 5 and 175" in too_short.json()["detail"] inverted = await _submit_file( client, {"acknowledged": "true", "clip_min_seconds": "10", "clip_max_seconds": "12"}, {"file": ("clip.mp4", media_factory.six.read_bytes(), "video/mp4")}, ) assert inverted.status_code == 400 assert "at least 5s above" in inverted.json()["detail"] # --------------------------------------------------------------------------- # # Env mapping: layouts, hooks, captions, format, generation controls # --------------------------------------------------------------------------- # async def test_env_mapping_for_layouts_hooks_captions_and_format( client, app_state, media_factory): resp = await _submit_file( client, { "acknowledged": "true", "layouts": "split,auto", "auto_hook": "true", "auto_hook_style": "classic", "captions": "false", "output_format": "vertical", "target_clips": "3", "clip_min_seconds": "10", "clip_max_seconds": "30", }, {"file": ("clip.mp4", media_factory.six.read_bytes(), "video/mp4")}, ) job_id = _job(client, resp) env = app_state.app.jobs[job_id]["env"] assert env["SPLIT_LAYOUT"] == "1" assert env["SPEAKER_SIGNAL"] == "1" # implied by split assert env["AUTO_LAYOUT"] == "1" assert env["AUTO_HOOK"] == "1" assert env["AUTO_HOOK_STYLE"] == "classic" assert env["AUTO_CAPTIONS"] == "0" assert env["CLIP_TARGET_MIN"] == "3" and env["CLIP_TARGET_MAX"] == "3" assert env["CLIP_MIN_SECONDS"] == "10.0" assert env["CLIP_MAX_SECONDS"] == "30.0" assert "--format" in app_state.app.jobs[job_id]["cmd"] assert app_state.app.jobs[job_id]["cmd"][ app_state.app.jobs[job_id]["cmd"].index("--format") + 1] == "vertical" async def test_layout_none_switches_picker_off(client, app_state, media_factory): resp = await _submit_file( client, {"acknowledged": "true", "layouts": "none"}, {"file": ("clip.mp4", media_factory.six.read_bytes(), "video/mp4")}, ) job_id = _job(client, resp) assert app_state.app.jobs[job_id]["env"]["AUTO_LAYOUT"] == "0" async def test_unknown_output_format_is_normalised_to_auto(client, app_state, media_factory): resp = await _submit_file( client, {"acknowledged": "true", "output_format": "widescreen"}, {"file": ("clip.mp4", media_factory.six.read_bytes(), "video/mp4")}, ) job_id = _job(client, resp) assert "--format" not in app_state.app.jobs[job_id]["cmd"]