fix(security): block tailnet SSRF, gate the quality probe, strip job secrets

- security_utils: accept only is_global addresses (100.64.0.0/10, the
  Tailscale range, went through is_private), judging IPv4-mapped / 6to4 /
  Teredo / NAT64 IPv6 by the IPv4 inside.
- /api/process validates the URL (public host, one YouTube video) before
  anything fetches it, and the quality probe now runs after the metering
  step (balance, job limit, hourly probe cap); a low-quality confirm or a
  too-short source hands the reservation back. quality_probe.py checks the
  same itself, passes noplaylist and no longer disables TLS verification.
- Metered whole-video URL jobs carry SOURCE_CAP_MINUTES = reserved minutes
  (job env + resume manifest); main.py cuts a download clearly longer than
  that, so a server cannot answer the probe short and the download long.
- main.py / quality_probe.py get child_env(): the server secrets (Stripe,
  JWT, DB, SMTP, Telegram, R2, AgentLedger, managed keys) are dropped; a
  test fails if the pipeline ever reads one.
- /api/social/user no longer logs the whole Upload-Post profile list.
- Owner checks on /api/thumbnail/generate, /api/thumbnail/publish/status
  (dashboard now polls with apiFetch) and /api/render/{id}; /video/{id}
  and /gallery escape every interpolated value and drop non-http URLs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
victorcavero14 2026-09-23 01:02:54 +02:00
parent 8de011ed36
commit 4bcdc36a6f
7 changed files with 715 additions and 61 deletions

231
app.py
View file

@ -69,6 +69,36 @@ QUALITY_GATE_MIN_HEIGHT = int(os.environ.get("QUALITY_GATE_MIN_HEIGHT", "720"))
# failures were exactly this, one user retrying the same 24s video). # failures were exactly this, one user retrying the same 24s video).
MIN_SOURCE_SECONDS = int(os.environ.get("MIN_SOURCE_SECONDS", "45")) MIN_SOURCE_SECONDS = int(os.environ.get("MIN_SOURCE_SECONDS", "45"))
QUALITY_PROBE_SCRIPT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "quality_probe.py") QUALITY_PROBE_SCRIPT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "quality_probe.py")
# Server credentials the pipeline subprocesses (main.py, quality_probe.py) never
# read: main.py and everything it imports use GEMINI_API_KEY / LLM_* / the
# proxies / YOUTUBE_COOKIES and nothing from cloud/. A child that runs yt-dlp
# and ffmpeg on user-supplied URLs and files has no business holding the
# Stripe key, the JWT signing secret or the database password; one exploit
# in that stack would otherwise hand over all of them.
CHILD_ENV_DENYLIST = frozenset({
"DATABASE_URL", "POSTGRES_PASSWORD", "JWT_SECRET",
"STRIPE_SECRET_KEY", "STRIPE_WEBHOOK_SECRET",
"SMTP_USER", "SMTP_PASSWORD",
"TELEGRAM_BOT_TOKEN", "TELEGRAM_CHAT_ID",
"GOOGLE_CLIENT_SECRET",
"AGENTLEDGER_API_KEY",
"MANAGED_UPLOAD_POST_API_KEY", "MANAGED_GEMINI_API_KEY", "UPLOAD_POST_API_KEY",
"R2_ACCESS_KEY_ID", "R2_SECRET_ACCESS_KEY",
"AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY",
"OPENPANEL_CLIENT_SECRET", "ELEVENLABS_API_KEY",
})
def child_env(base=None):
"""A copy of the environment for a pipeline subprocess, minus the server
secrets in CHILD_ENV_DENYLIST. Callers add GEMINI_API_KEY themselves."""
env = dict(os.environ if base is None else base)
for name in CHILD_ENV_DENYLIST:
env.pop(name, None)
return env
DISABLE_YOUTUBE_URL = os.environ.get("DISABLE_YOUTUBE_URL", "false").lower() in ("1", "true", "yes") DISABLE_YOUTUBE_URL = os.environ.get("DISABLE_YOUTUBE_URL", "false").lower() in ("1", "true", "yes")
# Every log line in this module is emoji-prefixed, and a Windows console is # Every log line in this module is emoji-prefixed, and a Windows console is
@ -342,6 +372,7 @@ async def reserve_process_minutes(request, url, input_path, job_id, max_minutes=
# Probe input duration (blocking → run in a thread). When today's paid # Probe input duration (blocking → run in a thread). When today's paid
# traffic is over budget, the probe (and below, the job itself) runs # traffic is over budget, the probe (and below, the job itself) runs
# without the per-GB proxy: statics or nothing. # without the per-GB proxy: statics or nothing.
paid_allowed = True
try: try:
from cloud import proxy_ledger as _pl from cloud import proxy_ledger as _pl
paid_allowed = not await _pl.budget_exceeded() paid_allowed = not await _pl.budget_exceeded()
@ -379,6 +410,9 @@ async def reserve_process_minutes(request, url, input_path, job_id, max_minutes=
reserve, partial = plan_partial_minutes(minutes, balance["remaining"], max_minutes) reserve, partial = plan_partial_minutes(minutes, balance["remaining"], max_minutes)
try: try:
reservation_id = await _metering.reserve_minutes(user.id, reserve, job_id) reservation_id = await _metering.reserve_minutes(user.id, reserve, job_id)
# Read by process_endpoint for the download's safety cut
# (SOURCE_CAP_MINUTES); kept off the return tuple on purpose.
request.state.reserved_minutes = reserve
except _metering.QuotaExceeded as e: except _metering.QuotaExceeded as e:
_maybe_send_quota_email(user) _maybe_send_quota_email(user)
raise HTTPException(status_code=402, detail={ raise HTTPException(status_code=402, detail={
@ -1060,7 +1094,7 @@ def _install_drain_signal_handler():
def _write_resume_manifest(job_id, cmd, priority, user_id, reservation_id, watermark, def _write_resume_manifest(job_id, cmd, priority, user_id, reservation_id, watermark,
webhook_url=None, webhook_secret=None, base_url=None, webhook_url=None, webhook_secret=None, base_url=None,
partial=None): partial=None, source_cap_minutes=None):
try: try:
path = os.path.join(OUTPUT_DIR, job_id, _RESUME_FILE) path = os.path.join(OUTPUT_DIR, job_id, _RESUME_FILE)
with open(path, "w") as f: with open(path, "w") as f:
@ -1080,6 +1114,8 @@ def _write_resume_manifest(job_id, cmd, priority, user_id, reservation_id, water
# A resumed job downloads the source again, so the cut must # A resumed job downloads the source again, so the cut must
# travel with it: only these minutes were reserved. # travel with it: only these minutes were reserved.
"partial": partial, "partial": partial,
# Same reason for the whole-video jobs' safety cap.
"source_cap_minutes": source_cap_minutes,
}, f) }, f)
except Exception as e: except Exception as e:
print(f"⚠️ Could not write resume manifest for {job_id}: {e}") print(f"⚠️ Could not write resume manifest for {job_id}: {e}")
@ -1154,7 +1190,7 @@ def _resume_interrupted_jobs() -> set:
# Rebuild env from scratch — the manifest holds no secrets. Managed # Rebuild env from scratch — the manifest holds no secrets. Managed
# (cloud) jobs get the server key; self-host falls back to its env key. # (cloud) jobs get the server key; self-host falls back to its env key.
env = os.environ.copy() env = child_env()
try: try:
from cloud import proxy_ledger as _pl from cloud import proxy_ledger as _pl
if BILLING_ENABLED and _pl.budget_exceeded_sync(): if BILLING_ENABLED and _pl.budget_exceeded_sync():
@ -1175,6 +1211,10 @@ def _resume_interrupted_jobs() -> set:
env["MAX_SOURCE_MINUTES"] = str(partial["processed_minutes"]) env["MAX_SOURCE_MINUTES"] = str(partial["processed_minutes"])
else: else:
env.pop("MAX_SOURCE_MINUTES", None) env.pop("MAX_SOURCE_MINUTES", None)
if m.get("source_cap_minutes"):
env["SOURCE_CAP_MINUTES"] = str(m["source_cap_minutes"])
else:
env.pop("SOURCE_CAP_MINUTES", None)
m["attempts"] = attempts m["attempts"] = attempts
try: try:
@ -2418,7 +2458,7 @@ async def _probe_youtube_quality(url: str) -> dict:
try: try:
proc = subprocess.run( proc = subprocess.run(
[sys.executable, QUALITY_PROBE_SCRIPT, "--url", url], [sys.executable, QUALITY_PROBE_SCRIPT, "--url", url],
capture_output=True, timeout=75, capture_output=True, timeout=75, env=child_env(),
) )
return json.loads(proc.stdout.decode(errors="replace").strip() or "{}") return json.loads(proc.stdout.decode(errors="replace").strip() or "{}")
except Exception as e: except Exception as e:
@ -2429,6 +2469,59 @@ async def _probe_youtube_quality(url: str) -> dict:
return await loop.run_in_executor(None, _run) return await loop.run_in_executor(None, _run)
async def _validate_source_url(url: str):
"""400 unless ``url`` is safe to hand to yt-dlp: http(s) on a globally
routable host (security_utils) and, on YouTube, one video rather than a
search / playlist / channel page (yt_clients). The download and the
metering probe check the same things again; this is the one in front of
the quality probe, which used to have none."""
from security_utils import assert_public_url, UnsafeURLError
from yt_clients import youtube_non_video_reason
try:
await asyncio.get_event_loop().run_in_executor(None, assert_public_url, url)
except UnsafeURLError as e:
raise HTTPException(status_code=400, detail=f"This URL can't be processed: {e}")
reason = youtube_non_video_reason(url)
if reason:
raise HTTPException(status_code=400, detail=(
f"This link is {reason}. Paste the link of one video "
"(youtube.com/watch?v=... or youtu.be/...)."))
async def _quality_gate(url: str, force_low: bool):
"""Run the pre-flight probe: raises 400 for a too-short source, returns
the needs_confirmation response for a low-resolution one, else None."""
probe = await _probe_youtube_quality(url)
# Hard reject, no confirm-and-retry: a too-short source fails the same
# way on every retry, so letting the user force it just burns the job.
source_duration = int(probe.get("duration") or 0)
if MIN_SOURCE_SECONDS > 0 and 0 < source_duration < MIN_SOURCE_SECONDS:
_reject_short_source(source_duration)
max_height = int(probe.get("max_height") or 0)
if not force_low and QUALITY_GATE_MIN_HEIGHT > 0 \
and 0 < max_height < QUALITY_GATE_MIN_HEIGHT:
print(f"⚠️ Quality gate: only {max_height}p available for {url} — asking user first.")
return JSONResponse({
"needs_confirmation": True,
"quality_check": {
"max_height": max_height,
"min_height": QUALITY_GATE_MIN_HEIGHT,
"cookies_invalid": bool(probe.get("cookies_invalid")),
},
})
return None
async def _drop_unstarted_job(reservation_id, job_output_dir):
"""Undo a submission refused after its minutes were reserved."""
if reservation_id:
try:
await _metering.release_reservation(reservation_id)
except Exception as e:
print(f"⚠️ Could not release reservation {reservation_id}: {e}")
shutil.rmtree(job_output_dir, ignore_errors=True)
def _media_duration_seconds(path: str) -> float: def _media_duration_seconds(path: str) -> float:
"""Container duration via ffprobe; 0.0 on any failure (fail-open).""" """Container duration via ffprobe; 0.0 on any failure (fail-open)."""
try: try:
@ -2729,30 +2822,11 @@ async def process_endpoint(
if url and DISABLE_YOUTUBE_URL: if url and DISABLE_YOUTUBE_URL:
raise HTTPException(status_code=403, detail="YouTube URL ingest is disabled on this deployment. Please upload a file you own.") raise HTTPException(status_code=403, detail="YouTube URL ingest is disabled on this deployment. Please upload a file you own.")
# Pre-flight quality gate: probe the offered resolution BEFORE starting, so # Refuse a URL no server-side fetch may touch before anything fetches it:
# the user can abort (refresh cookies / update yt-dlp) instead of burning # the quality probe below used to run yt-dlp on it unvalidated (tailnet
# 20 min on a 360p-only source. Fail-open: any probe error starts normally. # hosts included) and ahead of the balance / rate checks.
# The probe also runs under force_low_quality so the short-source check if url:
# can't be bypassed through the quality-gate confirm. await _validate_source_url(url)
if url and (QUALITY_GATE_MIN_HEIGHT > 0 or MIN_SOURCE_SECONDS > 0):
probe = await _probe_youtube_quality(url)
# Hard reject, no confirm-and-retry: a too-short source fails the same
# way on every retry, so letting the user force it just burns the job.
source_duration = int(probe.get("duration") or 0)
if MIN_SOURCE_SECONDS > 0 and 0 < source_duration < MIN_SOURCE_SECONDS:
_reject_short_source(source_duration)
max_height = int(probe.get("max_height") or 0)
if not force_low and QUALITY_GATE_MIN_HEIGHT > 0 \
and 0 < max_height < QUALITY_GATE_MIN_HEIGHT:
print(f"⚠️ Quality gate: only {max_height}p available for {url} — asking user first.")
return JSONResponse({
"needs_confirmation": True,
"quality_check": {
"max_height": max_height,
"min_height": QUALITY_GATE_MIN_HEIGHT,
"cookies_invalid": bool(probe.get("cookies_invalid")),
},
})
# Capture attestation context for legal record (IP + timestamp + UA) # Capture attestation context for legal record (IP + timestamp + UA)
client_ip = request.client.host if request.client else "unknown" client_ip = request.client.host if request.client else "unknown"
@ -2779,7 +2853,7 @@ async def process_endpoint(
# running this server. Every job then dies on `import cv2`. The quality # running this server. Every job then dies on `import cv2`. The quality
# probe above already gets this right. # probe above already gets this right.
cmd = [sys.executable, "-u", "main.py"] # -u for unbuffered cmd = [sys.executable, "-u", "main.py"] # -u for unbuffered
env = os.environ.copy() env = child_env()
if not paid_allowed: if not paid_allowed:
# Daily paid-proxy budget hit: this job runs on the free routes only. # Daily paid-proxy budget hit: this job runs on the free routes only.
env.pop("PROXY_URL", None) env.pop("PROXY_URL", None)
@ -2930,6 +3004,35 @@ async def process_endpoint(
# Meter + reserve minutes for managed users (no-op for BYOK / self-host). # Meter + reserve minutes for managed users (no-op for BYOK / self-host).
user_id, priority, reservation_id, user_plan, partial = await reserve_process_minutes( user_id, priority, reservation_id, user_plan, partial = await reserve_process_minutes(
request, url, input_path, job_id, max_minutes=max_minutes) request, url, input_path, job_id, max_minutes=max_minutes)
# Pre-flight quality gate: probe the offered resolution BEFORE starting, so
# the user can abort (refresh cookies / update yt-dlp) instead of burning
# 20 min on a 360p-only source. Fail-open: any probe error starts normally.
# The probe also runs under force_low_quality so the short-source check
# can't be bypassed through the quality-gate confirm. It runs AFTER the
# metering step (entitlement, job limit, balance, the hourly probe cap), so
# an account with no minutes cannot use it as a free yt-dlp runner; a
# rejection hands the reservation back.
if url and (QUALITY_GATE_MIN_HEIGHT > 0 or MIN_SOURCE_SECONDS > 0):
try:
gate = await _quality_gate(url, force_low)
except BaseException:
await _drop_unstarted_job(reservation_id, job_output_dir)
raise
if gate is not None:
await _drop_unstarted_job(reservation_id, job_output_dir)
return gate
# A metered URL job never processes more than it paid for: the duration
# came from the metering probe, but the download is a second request and
# a server can answer it with a much longer file. main.py cuts anything
# clearly past the reserved minutes (partial jobs already carry a cut).
source_cap = getattr(request.state, "reserved_minutes", None)
if url and source_cap and not partial:
env["SOURCE_CAP_MINUTES"] = str(source_cap)
else:
env.pop("SOURCE_CAP_MINUTES", None)
source_cap = None
if partial: if partial:
# main.py cuts the source down to this many minutes before anything # main.py cuts the source down to this many minutes before anything
# reads it, so the whole pipeline (and the editor) sees a short video. # reads it, so the whole pipeline (and the editor) sees a short video.
@ -2978,7 +3081,8 @@ async def process_endpoint(
_write_resume_manifest(job_id, cmd, priority, user_id, reservation_id, _write_resume_manifest(job_id, cmd, priority, user_id, reservation_id,
watermark=jobs[job_id]['watermark'], watermark=jobs[job_id]['watermark'],
webhook_url=webhook_url, webhook_secret=webhook_secret, webhook_url=webhook_url, webhook_secret=webhook_secret,
base_url=api_base, partial=partial) base_url=api_base, partial=partial,
source_cap_minutes=source_cap)
_enqueue_job(job_id, priority) _enqueue_job(job_id, priority)
@ -4337,6 +4441,8 @@ async def _reframe_locked(req: ReframeRequest, request: Request, job, overrides)
# --- Remotion Render Proxy --- # --- Remotion Render Proxy ---
RENDER_SERVICE_URL = os.getenv("RENDER_SERVICE_URL", "http://renderer:3100") RENDER_SERVICE_URL = os.getenv("RENDER_SERVICE_URL", "http://renderer:3100")
# render id -> owner user id (None for self-host / BYOK), for the status poll.
_render_owners: Dict[str, Optional[str]] = {}
@app.post("/api/render") @app.post("/api/render")
async def proxy_render(request: Request): async def proxy_render(request: Request):
@ -4351,6 +4457,8 @@ async def proxy_render(request: Request):
async with httpx.AsyncClient(timeout=30.0) as client: async with httpx.AsyncClient(timeout=30.0) as client:
resp = await client.post(f"{RENDER_SERVICE_URL}/render", json=body) resp = await client.post(f"{RENDER_SERVICE_URL}/render", json=body)
result = resp.json() result = resp.json()
if isinstance(result, dict) and result.get("renderId"):
_render_owners[str(result["renderId"])] = await _owner_id(request)
if reservation_id: if reservation_id:
await _metering.commit_reservation(reservation_id) await _metering.commit_reservation(reservation_id)
return result return result
@ -4360,9 +4468,19 @@ async def proxy_render(request: Request):
raise HTTPException(status_code=502, detail=f"Render service unavailable: {e}") raise HTTPException(status_code=502, detail=f"Render service unavailable: {e}")
@app.get("/api/render/{render_id}") @app.get("/api/render/{render_id}")
async def proxy_render_status(render_id: str): async def proxy_render_status(render_id: str, request: Request):
"""Proxy render status polling to the Node.js Remotion render service.""" """Proxy render status polling to the Node.js Remotion render service."""
import httpx import httpx
# The id goes into the upstream path: ids are uuids, nothing else passes.
if not re.fullmatch(r"[A-Za-z0-9-]{1,64}", render_id or ""):
raise HTTPException(status_code=404, detail="Not found")
if BILLING_ENABLED:
# Only the account that started the render may poll it (and read its
# output URL). An id this instance never issued is refused rather than
# passed through.
if render_id not in _render_owners:
raise HTTPException(status_code=404, detail="Not found")
await _assert_job_owner(request, {"user_id": _render_owners[render_id]})
try: try:
async with httpx.AsyncClient(timeout=10.0) as client: async with httpx.AsyncClient(timeout=10.0) as client:
resp = await client.get(f"{RENDER_SERVICE_URL}/render/{render_id}") resp = await client.get(f"{RENDER_SERVICE_URL}/render/{render_id}")
@ -5149,7 +5267,10 @@ async def get_social_user(request: Request):
raise HTTPException(status_code=resp.status_code, detail=f"Failed to fetch user: {resp.text}") raise HTTPException(status_code=resp.status_code, detail=f"Failed to fetch user: {resp.text}")
data = resp.json() data = resp.json()
print(f"🔍 Upload-Post User Response: {data}") # Never log the body: on the managed key it lists every profile
# on the account (usernames, redirect URLs), ~2 MB per call.
_n = len(data.get('profiles') or []) if isinstance(data, dict) else 0
print(f"🔍 Upload-Post users: {_n} profiles")
user_id = None user_id = None
# The structure is {'success': True, 'profiles': [{'username': '...'}, ...]} # The structure is {'success': True, 'profiles': [{'username': '...'}, ...]}
@ -5698,6 +5819,11 @@ async def thumbnail_generate(
"error": "plan_required", "error": "plan_required",
"message": "AI thumbnail generation is available on paid plans.", "message": "AI thumbnail generation is available on paid plans.",
}) })
# The session carries someone's transcript, titles and frames: only its
# owner may generate from it (and be billed for it).
_sess = thumbnail_sessions.get(session_id)
if _sess is not None:
await _assert_job_owner(request, _sess)
# Clamp count # Clamp count
count = min(max(1, count), 6) count = min(max(1, count), 6)
@ -5890,7 +6016,8 @@ async def thumbnail_publish(
# Generate a unique ID for this publish job so the frontend can poll # Generate a unique ID for this publish job so the frontend can poll
publish_id = str(uuid.uuid4()) publish_id = str(uuid.uuid4())
publish_jobs[publish_id] = {"status": "uploading", "result": None, "error": None} publish_jobs[publish_id] = {"status": "uploading", "result": None, "error": None,
"user_id": session.get("user_id")}
def do_upload(): def do_upload():
"""Runs in a thread via BackgroundTasks — does the actual multipart upload.""" """Runs in a thread via BackgroundTasks — does the actual multipart upload."""
@ -5941,11 +6068,13 @@ async def thumbnail_publish(
@app.get("/api/thumbnail/publish/status/{publish_id}") @app.get("/api/thumbnail/publish/status/{publish_id}")
async def thumbnail_publish_status(publish_id: str): async def thumbnail_publish_status(publish_id: str, request: Request):
"""Poll the status of a background publish job.""" """Poll the status of a background publish job (owner only in cloud mode)."""
if publish_id not in publish_jobs: if publish_id not in publish_jobs:
raise HTTPException(status_code=404, detail="Publish job not found") raise HTTPException(status_code=404, detail="Publish job not found")
return publish_jobs[publish_id] record = publish_jobs[publish_id]
await _assert_job_owner(request, record)
return {k: v for k, v in record.items() if k != "user_id"}
# @app.get("/api/gallery/clips") # @app.get("/api/gallery/clips")
@ -6301,9 +6430,9 @@ async def gallery_html_page():
# reusing the result in both places is what produced `&amp;amp;`. # reusing the result in both places is what produced `&amp;amp;`.
raw_title = v.get("title", "Untitled") raw_title = v.get("title", "Untitled")
title = html_mod.escape(raw_title) title = html_mod.escape(raw_title)
video_url = v.get("video_url", "") video_url = html_mod.escape(_http_url_or_empty(v.get("video_url", "")))
actor_url = v.get("actor_url", "") actor_url = html_mod.escape(_http_url_or_empty(v.get("actor_url", "")))
video_id = v.get("video_id", "") video_id = html_mod.escape(str(v.get("video_id", "")))
duration = v.get("duration", 0) duration = v.get("duration", 0)
mode = v.get("video_mode", "") mode = v.get("video_mode", "")
product = html_mod.escape(v.get("product_name", "")) product = html_mod.escape(v.get("product_name", ""))
@ -6382,6 +6511,12 @@ h1{{font-size:28px;font-weight:700;padding:40px 20px 0;text-align:center}}
</body></html>''' </body></html>'''
def _http_url_or_empty(value) -> str:
"""``value`` if it is an http(s) URL, else "" (no javascript:/data:)."""
value = str(value or "").strip()
return value if re.match(r"(?i)^https?://", value) else ""
@app.get("/video/{video_id}", response_class=HTMLResponse) @app.get("/video/{video_id}", response_class=HTMLResponse)
async def video_html_page(video_id: str): async def video_html_page(video_id: str):
"""SEO individual video page with og:video meta tags.""" """SEO individual video page with og:video meta tags."""
@ -6399,14 +6534,20 @@ async def video_html_page(video_id: str):
title = html_mod.escape(raw_title) title = html_mod.escape(raw_title)
caption = html_mod.escape(raw_caption) caption = html_mod.escape(raw_caption)
narration = html_mod.escape(meta.get("full_narration", "")) narration = html_mod.escape(meta.get("full_narration", ""))
video_url = meta.get("video_url", "") # Everything below lands in markup, generated from user input (product
actor_url = meta.get("actor_url", "") # page scrape, Gemini output): escape it all, and only let http(s) URLs
# into src/href/content so a javascript: URL cannot ride along either.
raw_video_url = _http_url_or_empty(meta.get("video_url", ""))
raw_actor_url = _http_url_or_empty(meta.get("actor_url", ""))
video_url = html_mod.escape(raw_video_url)
actor_url = html_mod.escape(raw_actor_url)
duration = meta.get("duration", 0) duration = meta.get("duration", 0)
mode = meta.get("video_mode", "") mode = meta.get("video_mode", "")
product = html_mod.escape(meta.get("product_name", "")) product = html_mod.escape(meta.get("product_name", ""))
product_url = html_mod.escape(meta.get("product_url", "")) product_url = html_mod.escape(_http_url_or_empty(meta.get("product_url", "")))
language = meta.get("language", "en") raw_language = str(meta.get("language", "en") or "en")
hashtags = " ".join(meta.get("hashtags", [])) language = raw_language if re.fullmatch(r"[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})?", raw_language) else "en"
hashtags = html_mod.escape(" ".join(str(h) for h in (meta.get("hashtags") or [])))
cost = meta.get("cost_estimate", {}).get("total", 0) cost = meta.get("cost_estimate", {}).get("total", 0)
created = meta.get("created_at", "") created = meta.get("created_at", "")
actor_desc = html_mod.escape(meta.get("actor_description", "")) actor_desc = html_mod.escape(meta.get("actor_description", ""))
@ -6417,8 +6558,8 @@ async def video_html_page(video_id: str):
"@type": "VideoObject", "@type": "VideoObject",
"name": raw_title, "name": raw_title,
"description": raw_caption, "description": raw_caption,
"thumbnailUrl": actor_url, "thumbnailUrl": raw_actor_url,
"contentUrl": video_url, "contentUrl": raw_video_url,
"uploadDate": created, "uploadDate": created,
"duration": f"PT{int(duration)}S", "duration": f"PT{int(duration)}S",
"width": 1080, "width": 1080,

View file

@ -410,7 +410,7 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse
await new Promise((resolve, reject) => { await new Promise((resolve, reject) => {
const interval = setInterval(async () => { const interval = setInterval(async () => {
try { try {
const statusRes = await fetch(getApiUrl(`/api/thumbnail/publish/status/${publish_id}`)); const statusRes = await apiFetch(`/api/thumbnail/publish/status/${publish_id}`);
if (!statusRes.ok) { clearInterval(interval); reject(new Error('Status check failed')); return; } if (!statusRes.ok) { clearInterval(interval); reject(new Error('Status check failed')); return; }
const statusData = await statusRes.json(); const statusData = await statusRes.json();

22
main.py
View file

@ -724,7 +724,7 @@ def plan_download_attempts(direct_first, statics, paid, have_hd, youtube=True):
return plan return plan
def cap_source_duration(input_video, max_minutes): def cap_source_duration(input_video, max_minutes, safety=False):
"""Cut ``input_video`` down to its first ``max_minutes`` minutes, in place. """Cut ``input_video`` down to its first ``max_minutes`` minutes, in place.
Set through ``MAX_SOURCE_MINUTES`` by app.py when the user accepted the Set through ``MAX_SOURCE_MINUTES`` by app.py when the user accepted the
@ -738,6 +738,13 @@ def cap_source_duration(input_video, max_minutes):
Stream copy first (seconds, no quality loss; the cut lands on a packet Stream copy first (seconds, no quality loss; the cut lands on a packet
boundary a fraction of a second past N). If the container refuses a copy boundary a fraction of a second past N). If the container refuses a copy
the fallback re-encodes, which is slow but rare. the fallback re-encodes, which is slow but rare.
``safety=True`` is the whole-video case (``SOURCE_CAP_MINUTES``): the
reservation covered the duration the metering probe saw, rounded up, and
the cut only exists for a download that turns out clearly longer than
that (a server answering the probe and the download differently). So it
never cuts a file whose duration it cannot read, and it ignores anything
within 30 s of the cap.
""" """
try: try:
secs = float(max_minutes) * 60.0 secs = float(max_minutes) * 60.0
@ -753,7 +760,9 @@ def cap_source_duration(input_video, max_minutes):
cap.release() cap.release()
except Exception: except Exception:
duration = 0.0 duration = 0.0
if duration and duration <= secs + 1.0: if duration and duration <= secs + (30.0 if safety else 1.0):
return input_video
if safety and not duration:
return input_video return input_video
root, ext = os.path.splitext(input_video) root, ext = os.path.splitext(input_video)
tmp = f"{root}.capped{ext or '.mp4'}" tmp = f"{root}.capped{ext or '.mp4'}"
@ -768,6 +777,11 @@ def cap_source_duration(input_video, max_minutes):
subprocess.run(cmd, check=True, capture_output=True, timeout=3600) subprocess.run(cmd, check=True, capture_output=True, timeout=3600)
os.replace(tmp, input_video) os.replace(tmp, input_video)
shown = f"{int(math.ceil(duration / 60))}" if duration else "?" shown = f"{int(math.ceil(duration / 60))}" if duration else "?"
if safety:
print(f"✂️ The downloaded source runs {shown} min, longer than the "
f"{float(max_minutes):g} min measured and reserved at submit; "
f"clipping the first {float(max_minutes):g} min.")
else:
print(f"✂️ Clipping the first {float(max_minutes):g} min of {shown}: " print(f"✂️ Clipping the first {float(max_minutes):g} min of {shown}: "
f"that is what the plan's remaining minutes cover.") f"that is what the plan's remaining minutes cover.")
return input_video return input_video
@ -2024,6 +2038,10 @@ if __name__ == '__main__':
# cap_source_duration). Must run before anything reads the file. # cap_source_duration). Must run before anything reads the file.
if os.environ.get("MAX_SOURCE_MINUTES", "").strip(): if os.environ.get("MAX_SOURCE_MINUTES", "").strip():
input_video = cap_source_duration(input_video, os.environ["MAX_SOURCE_MINUTES"]) input_video = cap_source_duration(input_video, os.environ["MAX_SOURCE_MINUTES"])
elif os.environ.get("SOURCE_CAP_MINUTES", "").strip():
# Whole-video metered job: never process more than was reserved.
input_video = cap_source_duration(input_video, os.environ["SOURCE_CAP_MINUTES"],
safety=True)
# Layout choice is per SOURCE video, not per clip: one upload and one call # Layout choice is per SOURCE video, not per clip: one upload and one call
# instead of one per clip, and the answer is a property of the material # instead of one per clip, and the answer is a property of the material

View file

@ -38,6 +38,20 @@ def main() -> int:
args = parser.parse_args() args = parser.parse_args()
result = {"max_height": 0, "mode": None, "cookies_invalid": False, "duration": 0} result = {"max_height": 0, "mode": None, "cookies_invalid": False, "duration": 0}
# Same gates as the metering probe and the download (app.py also checks
# before spawning this): a URL on a private / tailnet address, or a
# YouTube page that is not one video, never reaches yt-dlp. The empty
# result is the fail-open "unknown", so the caller carries on and the
# real probe / download refuse the URL with their own message.
try:
from security_utils import assert_public_url
from yt_clients import youtube_non_video_reason
assert_public_url(args.url)
if youtube_non_video_reason(args.url):
raise ValueError("not a single video")
except Exception:
print(json.dumps(result))
return 0
try: try:
import yt_dlp import yt_dlp
@ -63,8 +77,10 @@ def main() -> int:
'logger': _CollectLogger(), 'logger': _CollectLogger(),
'socket_timeout': 20, 'socket_timeout': 20,
'retries': 2, 'retries': 2,
'nocheckcertificate': True,
'cachedir': False, 'cachedir': False,
# A watch?v=X&list=... link is the one video; without this
# yt-dlp walks the whole list (see cloud/metering.py).
'noplaylist': True,
} }
# yt-dlp's default player clients (tv_downgraded/web_safari with # yt-dlp's default player clients (tv_downgraded/web_safari with
# cookies, android_vr/web_safari anonymous) are the ones that still # cookies, android_vr/web_safari anonymous) are the ones that still

View file

@ -4,7 +4,8 @@ The app fetches user-supplied URLs server-side (yt-dlp downloads, SaaS landing
page scraping, actor-image download). Without a guard, a caller can point those page scraping, actor-image download). Without a guard, a caller can point those
at internal services or the cloud metadata endpoint (169.254.169.254) to read at internal services or the cloud metadata endpoint (169.254.169.254) to read
instance credentials. ``assert_public_url`` rejects non-HTTP(S) schemes and any instance credentials. ``assert_public_url`` rejects non-HTTP(S) schemes and any
host that resolves to a private / loopback / link-local / reserved address. host that resolves to anything but a globally routable address (private,
loopback, link-local, reserved, and the 100.64.0.0/10 range Tailscale uses).
""" """
from __future__ import annotations from __future__ import annotations
@ -37,18 +38,32 @@ class UnsafeURLError(ValueError):
def _ip_is_public(ip: str) -> bool: def _ip_is_public(ip: str) -> bool:
"""True only for globally routable unicast addresses.
``is_global`` rather than a list of ``is_private``/``is_loopback``/...:
that list missed 100.64.0.0/10 (carrier-grade NAT), which is exactly the
range Tailscale hands out, so a job URL could reach every host on the
tailnet (SSH on the other servers, the Coolify API) from the API
container. An allowlist of "global" fails closed on any range nobody
thought to name. IPv6 forms that carry an IPv4 address inside (mapped
``::ffff:a.b.c.d``, 6to4, Teredo, NAT64) are judged by that IPv4 address.
"""
try: try:
addr = ipaddress.ip_address(ip) addr = ipaddress.ip_address(str(ip).split("%", 1)[0])
except ValueError: except ValueError:
return False return False
return not ( if addr.version == 6:
addr.is_private embedded = addr.ipv4_mapped or addr.sixtofour
or addr.is_loopback if embedded is None and addr.teredo:
or addr.is_link_local embedded = addr.teredo[1]
or addr.is_reserved if embedded is None and addr in _NAT64:
or addr.is_multicast embedded = ipaddress.IPv4Address(int(addr) & 0xFFFFFFFF)
or addr.is_unspecified if embedded is not None and not _ip_is_public(str(embedded)):
) return False
return bool(addr.is_global) and not addr.is_multicast
_NAT64 = ipaddress.ip_network("64:ff9b::/96")
def assert_public_url(url: str) -> str: def assert_public_url(url: str) -> str:

View file

@ -0,0 +1,336 @@
"""Hardening from the 22-sep-2026 audit, pinned at the HTTP surface.
- /api/process refuses a tailnet / private URL before any probe runs, and the
quality probe runs only AFTER the metering step (balance, job limit, the
hourly probe cap), handing the reservation back when it refuses the job.
- A metered whole-video URL job carries SOURCE_CAP_MINUTES = the reserved
minutes, in the job env and in the resume manifest.
- main.py and the probe get an environment without the server secrets.
- Thumbnail publish status, thumbnail generation and render status are
owner-only in cloud mode.
- The public /video/{id} page escapes everything it interpolates.
"""
import asyncio
import json
import os
import httpx
import pytest
app_module = pytest.importorskip("app")
def _client_call(method, path, **kw):
async def _do():
transport = httpx.ASGITransport(app=app_module.app)
async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as c:
return await getattr(c, method)(path, **kw)
return asyncio.run(_do())
def _post_process(body):
return _client_call("post", "/api/process", json=body,
headers={"X-Gemini-Key": "test-key"})
@pytest.fixture()
def dirs(tmp_path, monkeypatch):
out_root = tmp_path / "output"
up_root = tmp_path / "uploads"
out_root.mkdir()
up_root.mkdir()
monkeypatch.setattr(app_module, "OUTPUT_DIR", str(out_root))
monkeypatch.setattr(app_module, "UPLOAD_DIR", str(up_root))
monkeypatch.setattr(app_module, "jobs", {})
monkeypatch.setattr(app_module, "job_queue", asyncio.PriorityQueue())
return out_root
@pytest.fixture()
def calls(monkeypatch):
"""Record the order of the metering step and the quality probe."""
order = []
async def _probe(url):
order.append("probe")
return order_probe_result[0]
async def _reserve(request, url, input_path, job_id, max_minutes=None):
order.append("reserve")
request.state.reserved_minutes = 12
return 7, 1, "res-1", "starter", None
released = []
class _FakeMetering:
@staticmethod
async def release_reservation(rid):
released.append(rid)
order_probe_result = [{"max_height": 1080, "duration": 600}]
monkeypatch.setattr(app_module, "_probe_youtube_quality", _probe)
monkeypatch.setattr(app_module, "reserve_process_minutes", _reserve)
monkeypatch.setattr(app_module, "_metering", _FakeMetering)
monkeypatch.setattr(app_module, "_validate_source_url", _allow_url)
return {"order": order, "released": released, "probe_result": order_probe_result}
async def _allow_url(url):
return None
# --------------------------------------------------------------------------- #
# /api/process: URL validation, probe ordering, reservation cap
# --------------------------------------------------------------------------- #
@pytest.mark.parametrize("url", [
"http://100.117.9.37:22/",
"http://100.81.170.50:8000/api/v1/applications",
"http://127.0.0.1:8000/health",
"file:///etc/passwd",
])
def test_unsafe_url_is_refused_before_any_probe(dirs, monkeypatch, url):
probed = []
async def _probe(u):
probed.append(u)
return {}
monkeypatch.setattr(app_module, "_probe_youtube_quality", _probe)
resp = _post_process({"url": url, "acknowledged": True})
assert resp.status_code == 400
assert probed == []
assert os.listdir(dirs) == []
def test_youtube_search_page_is_refused_before_any_probe(dirs, monkeypatch):
probed = []
async def _probe(u):
probed.append(u)
return {}
monkeypatch.setattr(app_module, "_probe_youtube_quality", _probe)
monkeypatch.setattr("security_utils.assert_public_url", lambda u: u)
resp = _post_process({"url": "https://www.youtube.com/results?search_query=x",
"acknowledged": True})
assert resp.status_code == 400
assert "search results" in resp.json()["detail"]
assert probed == []
def test_quality_probe_runs_after_metering(dirs, calls):
resp = _post_process({"url": "https://www.youtube.com/watch?v=ok", "acknowledged": True})
assert resp.status_code == 200, resp.text
assert calls["order"] == ["reserve", "probe"]
assert calls["released"] == []
def test_low_quality_confirmation_releases_the_reservation(dirs, calls):
calls["probe_result"][0] = {"max_height": 360, "duration": 600}
resp = _post_process({"url": "https://www.youtube.com/watch?v=lowq", "acknowledged": True})
assert resp.status_code == 200
assert resp.json()["needs_confirmation"] is True
assert calls["released"] == ["res-1"]
assert os.listdir(dirs) == [] # no orphan job dir
assert app_module.jobs == {}
def test_short_source_rejection_releases_the_reservation(dirs, calls):
calls["probe_result"][0] = {"max_height": 1080, "duration": 20}
resp = _post_process({"url": "https://www.youtube.com/watch?v=short", "acknowledged": True})
assert resp.status_code == 400
assert calls["released"] == ["res-1"]
assert os.listdir(dirs) == []
def test_metered_url_job_is_capped_at_the_reserved_minutes(dirs, calls):
resp = _post_process({"url": "https://www.youtube.com/watch?v=ok", "acknowledged": True})
job_id = resp.json()["job_id"]
job = app_module.jobs[job_id]
assert job["env"]["SOURCE_CAP_MINUTES"] == "12"
assert "MAX_SOURCE_MINUTES" not in job["env"]
manifest = json.load(open(os.path.join(dirs, job_id, app_module._RESUME_FILE)))
assert manifest["source_cap_minutes"] == 12
def test_resumed_job_keeps_its_safety_cap(dirs, monkeypatch):
monkeypatch.setattr(app_module, "INSTANCE_ID", "me")
monkeypatch.setattr(app_module, "_draining", False)
monkeypatch.setattr(app_module, "_running_jobs", set())
for name, cap in (("capped", 12), ("plain", None)):
d = dirs / name
d.mkdir()
(d / app_module._RESUME_FILE).write_text(json.dumps({
"cmd": ["python", "main.py"], "priority": 2, "user_id": None,
"reservation_id": f"res-{name}", "watermark": False, "attempts": 0,
"source_cap_minutes": cap,
}))
monkeypatch.setenv("SOURCE_CAP_MINUTES", "3") # a stale value must not leak in
app_module._resume_interrupted_jobs()
assert app_module.jobs["capped"]["env"]["SOURCE_CAP_MINUTES"] == "12"
assert "SOURCE_CAP_MINUTES" not in app_module.jobs["plain"]["env"]
# --------------------------------------------------------------------------- #
# Subprocess environment
# --------------------------------------------------------------------------- #
def test_child_env_drops_server_secrets(monkeypatch):
for name in ("STRIPE_SECRET_KEY", "JWT_SECRET", "DATABASE_URL", "SMTP_PASSWORD",
"TELEGRAM_BOT_TOKEN", "AGENTLEDGER_API_KEY", "R2_SECRET_ACCESS_KEY",
"MANAGED_UPLOAD_POST_API_KEY", "GOOGLE_CLIENT_SECRET"):
monkeypatch.setenv(name, "secret")
for name in ("YOUTUBE_COOKIES", "PROXY_URL", "STATIC_PROXY_URLS", "GEMINI_API_KEY",
"BGUTIL_SCRIPT_PATH", "FFMPEG_ENCODER", "WHISPER_MODEL"):
monkeypatch.setenv(name, "keep")
env = app_module.child_env()
for name in app_module.CHILD_ENV_DENYLIST:
assert name not in env
for name in ("YOUTUBE_COOKIES", "PROXY_URL", "STATIC_PROXY_URLS", "GEMINI_API_KEY",
"BGUTIL_SCRIPT_PATH", "FFMPEG_ENCODER", "WHISPER_MODEL"):
assert env[name] == "keep"
def test_pipeline_code_reads_none_of_the_dropped_secrets():
"""If main.py (or anything it imports) ever needs one of these, the
denylist would silently break jobs: fail here instead."""
import ast
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
local = {f[:-3] for f in os.listdir(root) if f.endswith(".py")}
seen, stack = set(), ["main", "quality_probe"]
while stack:
mod = stack.pop()
if mod in seen:
continue
seen.add(mod)
src = open(os.path.join(root, mod + ".py"), encoding="utf-8").read()
for name in app_module.CHILD_ENV_DENYLIST:
assert f'"{name}"' not in src and f"'{name}'" not in src, (mod, name)
for node in ast.walk(ast.parse(src)):
names = []
if isinstance(node, ast.Import):
names = [a.name.split(".")[0] for a in node.names]
elif isinstance(node, ast.ImportFrom) and node.module:
names = [node.module.split(".")[0]]
for n in names:
assert n != "cloud", f"{mod} imports cloud/, which reads server secrets"
if n in local:
stack.append(n)
def test_job_env_has_no_server_secrets(dirs, calls, monkeypatch):
monkeypatch.setenv("STRIPE_SECRET_KEY", "sk_live_x")
monkeypatch.setenv("JWT_SECRET", "jwt")
resp = _post_process({"url": "https://www.youtube.com/watch?v=ok", "acknowledged": True})
env = app_module.jobs[resp.json()["job_id"]]["env"]
assert "STRIPE_SECRET_KEY" not in env and "JWT_SECRET" not in env
assert env["GEMINI_API_KEY"] == "test-key"
# --------------------------------------------------------------------------- #
# Owner checks (cloud mode)
# --------------------------------------------------------------------------- #
class _User:
def __init__(self, uid):
self.id = uid
self.plan = "starter"
@pytest.fixture()
def cloud_as(monkeypatch):
who = {"user": None}
async def _from_request(request):
return who["user"]
monkeypatch.setattr(app_module, "BILLING_ENABLED", True)
monkeypatch.setattr(app_module, "_user_from_request", _from_request)
return who
def test_publish_status_is_owner_only(cloud_as, monkeypatch):
monkeypatch.setattr(app_module, "publish_jobs", {
"p1": {"status": "done", "result": {"ok": 1}, "error": None, "user_id": "owner"}})
cloud_as["user"] = _User("stranger")
assert _client_call("get", "/api/thumbnail/publish/status/p1").status_code == 404
cloud_as["user"] = None
assert _client_call("get", "/api/thumbnail/publish/status/p1").status_code == 404
cloud_as["user"] = _User("owner")
resp = _client_call("get", "/api/thumbnail/publish/status/p1")
assert resp.status_code == 200
assert resp.json() == {"status": "done", "result": {"ok": 1}, "error": None}
def test_render_status_is_owner_only(cloud_as, monkeypatch):
monkeypatch.setattr(app_module, "_render_owners", {"r-1": "owner"})
cloud_as["user"] = _User("stranger")
assert _client_call("get", "/api/render/r-1").status_code == 404
# An id this instance never issued is not proxied at all.
cloud_as["user"] = _User("owner")
assert _client_call("get", "/api/render/unknown-id").status_code == 404
def test_thumbnail_generate_refuses_someone_elses_session(cloud_as, monkeypatch):
async def _gemini(request):
return "k"
monkeypatch.setattr(app_module, "resolve_gemini", _gemini)
monkeypatch.setattr(app_module, "thumbnail_sessions", {"s-1": {"user_id": "owner"}})
cloud_as["user"] = _User("stranger")
resp = _client_call("post", "/api/thumbnail/generate",
data={"session_id": "s-1", "title": "t"})
assert resp.status_code == 404
# --------------------------------------------------------------------------- #
# /video/{id} escaping
# --------------------------------------------------------------------------- #
def test_video_page_escapes_everything(monkeypatch):
evil = '"><script>alert(1)</script>'
meta = {
"video_id": "v1", "title": "t", "caption": "c",
"video_url": "https://cdn.example.com/v.mp4" + evil,
"actor_url": "javascript:alert(1)",
"product_url": "javascript:alert(2)", "product_name": "p",
"hashtags": ["#ok", evil], "language": 'en"><script>',
"duration": 30, "cost_estimate": {"total": 1.0},
}
monkeypatch.setattr(app_module, "list_video_gallery", lambda n: [meta])
resp = _client_call("get", "/video/v1")
assert resp.status_code == 200
body = resp.text
assert "<script>alert(1)</script>" not in body
assert "javascript:" not in body
assert '<html lang="en">' in body
# --------------------------------------------------------------------------- #
# main.cap_source_duration(safety=True): the whole-video cap
# --------------------------------------------------------------------------- #
import shutil
import subprocess
@pytest.mark.skipif(not shutil.which("ffmpeg") or not shutil.which("ffprobe"),
reason="needs ffmpeg")
class TestSafetyCap:
@pytest.fixture()
def source(self, tmp_path):
main = pytest.importorskip("main")
path = tmp_path / "src.mp4"
subprocess.run([
"ffmpeg", "-y", "-loglevel", "error",
"-f", "lavfi", "-i", "testsrc=size=160x120:rate=25",
"-t", "150", "-c:v", "libx264", "-preset", "ultrafast", str(path)], check=True)
return main, str(path)
@staticmethod
def _seconds(path):
return float(subprocess.check_output([
"ffprobe", "-v", "error", "-show_entries", "format=duration",
"-of", "default=nw=1:nk=1", path]).decode().strip())
def test_a_download_clearly_longer_than_reserved_is_cut(self, source):
main, path = source
main.cap_source_duration(path, 1, safety=True)
assert 59 <= self._seconds(path) <= 62
def test_within_tolerance_is_left_alone(self, source):
main, path = source
main.cap_source_duration(path, 2.2, safety=True) # 132 s + 30 s tolerance
assert self._seconds(path) >= 149

128
tests/test_ssrf_guard.py Normal file
View file

@ -0,0 +1,128 @@
"""SSRF guard: nothing but globally routable addresses may be fetched.
The old check listed ranges (is_private, is_loopback, ...) and missed
100.64.0.0/10, the carrier-grade NAT block Tailscale assigns: a job URL
pointing at another server's tailnet address (SSH, the Coolify API) went
straight through. The quality probe also ran yt-dlp on the URL with no check
at all, before the balance and rate checks.
"""
import json
import socket
import sys
import types
import pytest
import security_utils
from security_utils import UnsafeURLError, assert_public_url
@pytest.mark.parametrize("ip", [
"100.117.9.37", # Tailscale (onepiece)
"100.64.0.1", # CGNAT, first address
"100.127.255.254", # CGNAT, last address
"10.0.0.1", "172.16.0.1", "192.168.1.1",
"127.0.0.1", "0.0.0.0", "169.254.169.254",
"192.0.0.1", "198.18.0.1", "224.0.0.1", "255.255.255.255",
"::1", "fe80::1", "fd7a:115c:a1e0::1", # Tailscale's IPv6 ULA
"::ffff:100.117.9.37", # IPv4-mapped tailnet address
"::ffff:127.0.0.1",
"2002:6475:925::1", # 6to4 wrapping 100.117.9.37
"64:ff9b::6475:925", # NAT64 wrapping 100.117.9.37
])
def test_non_global_addresses_are_refused(ip):
assert security_utils._ip_is_public(ip) is False
@pytest.mark.parametrize("ip", ["8.8.8.8", "142.250.184.14", "2606:4700:4700::1111"])
def test_global_addresses_pass(ip):
assert security_utils._ip_is_public(ip) is True
@pytest.mark.parametrize("url", [
"http://100.117.9.37/",
"http://100.81.170.50:8000/api/v1/applications",
"https://[::ffff:100.117.9.37]/",
"http://[fd7a:115c:a1e0::1]/",
])
def test_literal_tailnet_urls_are_refused(url):
with pytest.raises(UnsafeURLError):
assert_public_url(url)
def test_hostname_resolving_to_tailnet_is_refused(monkeypatch):
"""MagicDNS names (``onepiece``) or a public name pointed at 100.x."""
def fake_getaddrinfo(host, port, *a, **k):
return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("100.117.9.37", 0))]
monkeypatch.setattr(socket, "getaddrinfo", fake_getaddrinfo)
with pytest.raises(UnsafeURLError):
assert_public_url("https://videos.example.com/watch.mp4")
def test_hostname_with_one_bad_record_is_refused(monkeypatch):
def fake_getaddrinfo(host, port, *a, **k):
return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("93.184.216.34", 0)),
(socket.AF_INET6, socket.SOCK_STREAM, 6, "", ("::ffff:100.64.1.1", 0, 0, 0))]
monkeypatch.setattr(socket, "getaddrinfo", fake_getaddrinfo)
with pytest.raises(UnsafeURLError):
assert_public_url("https://videos.example.com/watch.mp4")
def test_public_hostname_passes(monkeypatch):
def fake_getaddrinfo(host, port, *a, **k):
return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("142.250.184.14", 0))]
monkeypatch.setattr(socket, "getaddrinfo", fake_getaddrinfo)
url = "https://www.youtube.com/watch?v=abc"
assert assert_public_url(url) == url
# --------------------------------------------------------------------------- #
# quality_probe.py: same gates, noplaylist, no disabled TLS checks
# --------------------------------------------------------------------------- #
class _FakeYDL:
seen = []
def __init__(self, opts):
self.opts = opts
_FakeYDL.seen.append(opts)
def __enter__(self):
return self
def __exit__(self, *a):
return False
def extract_info(self, url, download=False):
return {"formats": [{"height": 1080, "vcodec": "avc1"}], "duration": 600}
def _run_probe(monkeypatch, capsys, url):
import quality_probe
_FakeYDL.seen = []
monkeypatch.setitem(sys.modules, "yt_dlp", types.SimpleNamespace(YoutubeDL=_FakeYDL))
monkeypatch.setattr(sys, "argv", ["quality_probe.py", "--url", url])
assert quality_probe.main() == 0
return json.loads(capsys.readouterr().out.strip())
def test_probe_refuses_tailnet_url_without_running_ytdlp(monkeypatch, capsys):
out = _run_probe(monkeypatch, capsys, "http://100.117.9.37:22/")
assert out["max_height"] == 0 and out["duration"] == 0
assert _FakeYDL.seen == []
def test_probe_refuses_non_video_youtube_page(monkeypatch, capsys):
monkeypatch.setattr(security_utils, "assert_public_url", lambda u: u)
out = _run_probe(monkeypatch, capsys, "https://www.youtube.com/results?search_query=x")
assert out["max_height"] == 0
assert _FakeYDL.seen == []
def test_probe_runs_single_video_with_noplaylist(monkeypatch, capsys):
monkeypatch.setattr(security_utils, "assert_public_url", lambda u: u)
out = _run_probe(monkeypatch, capsys, "https://www.youtube.com/watch?v=abc&list=PL1")
assert out["max_height"] == 1080 and out["duration"] == 600
assert _FakeYDL.seen
for opts in _FakeYDL.seen:
assert opts["noplaylist"] is True
assert not opts.get("nocheckcertificate")