fix(metering): the duration probe carries the download's cookies

Ten probes in one hour on 4-sep paid the per-GB proxy 1.8 MB each because
all three static IPs answered 'Sign in to confirm you are not a bot' to the
ANONYMOUS probe, while the same IPs served the cookie-authenticated
download of those very videos without a complaint: a datacenter IP's
anonymous rate limit is low and we make ~400 YouTube hits a day from three
of them. The probe now writes YOUTUBE_COOKIES to a temp file and passes it
as cookiefile, exactly as download_youtube_video does, and removes it in a
finally (the chain walk moved into _probe_with_proxies so that file has one
obvious lifetime).

Claude-Session: https://claude.ai/code/session_014i9z6mLTy978uRCfSsMfBq
This commit is contained in:
juancarlos.cavero 2026-09-04 16:02:40 +02:00
parent a85a41bb6a
commit 3c9cc989f2
3 changed files with 91 additions and 8 deletions

View file

@ -346,7 +346,12 @@ errors), never for a private/removed/members-only video or a live stream
with no duration (those failed the same on every IP and used to cost ~1.7 MB
× 2 extractors each), and **never for a non-YouTube URL** (the download
plan already excluded those; Twitch, Kick, Rumble and product pages were
reaching it through the probe). `main.py` prints `PROXY_ROUTE=<json>` after
reaching it through the probe). The probe also carries `YOUTUBE_COOKIES`,
like the download does: an anonymous probe from the static IPs gets "Sign in
to confirm you're not a bot" in bursts (4-sep-2026: ~10 probes in one hour,
1.8 MB each on the per-GB proxy) because a datacenter IP's anonymous rate
limit is low and we make ~400 YouTube hits a day from three of them, while
the authenticated download sails through the same IPs. `main.py` prints `PROXY_ROUTE=<json>` after
every download (winner, paid bytes across all attempts including failed
paid ones, each free attempt's error); `app.py` persists it as a
`proxy_usage` row at job end and pages Telegram when the paid proxy carried

View file

@ -151,7 +151,6 @@ def probe_url_minutes(url: str, allow_paid: bool = True) -> float:
(main.py) so the probe behaves consistently with it and bills the same way.
Raises ValueError if the duration is unknown (e.g. live streams).
"""
import yt_dlp
# SSRF guard: reject non-http(s) / private / metadata hosts before probing.
from security_utils import assert_public_url
assert_public_url(url)
@ -195,18 +194,46 @@ def probe_url_minutes(url: str, allow_paid: bool = True) -> float:
)
static_errors: dict = {}
# A dead route in the chain is routine (the proxy watcher is what reports
# it, on Telegram); yt-dlp printing a full ERROR block per failed proxy per
# strategy would just flood the API log. The reason still reaches the caller
# through ``last_err`` below.
# Same cookies + PO token the download uses: an anonymous probe gets
# "Sign in to confirm you're not a bot" from the static IPs (4-sep-2026,
# all three, ~10 probes/day paying 1.8 MB each on the per-GB proxy)
# while the authenticated download sails through the same IPs.
cookies_env = os.environ.get("YOUTUBE_COOKIES")
ck_path = None
if cookies_env:
import tempfile
fd, ck_path = tempfile.mkstemp(prefix="probe_ck_", suffix=".txt")
with os.fdopen(fd, "w") as f:
f.write(cookies_env)
try:
return _probe_with_proxies(url, proxies, strategies, static_errors,
paid, ck_path)
finally:
if ck_path:
try:
os.remove(ck_path)
except OSError:
pass
def _probe_with_proxies(url, proxies, strategies, static_errors, paid, ck_path):
"""Walk the proxy chain (outer) x extractor strategies (inner) until one
reports a duration. Split out of ``probe_url_minutes`` so the temporary
cookie file has one obvious lifetime.
A dead route in the chain is routine (the proxy watcher is what reports it,
on Telegram); yt-dlp printing a full ERROR block per failed proxy per
strategy would just flood the API log, hence the quiet logger. The reason
still reaches the caller through ``last_err``.
"""
import yt_dlp
class _QuietLogger:
def debug(self, msg): pass
def info(self, msg): pass
def warning(self, msg): pass
def error(self, msg): pass
# Proxies outer, strategies inner: the paid proxy is only reached once every
# free route has failed on both extractors.
last_err = None
for proxy in proxies:
is_paid = bool(paid) and proxy == paid
@ -220,6 +247,8 @@ def probe_url_minutes(url: str, allow_paid: bool = True) -> float:
for extractor_args in strategies:
opts = {"skip_download": True, "quiet": True, "no_warnings": True,
"logger": _QuietLogger(), "extractor_args": extractor_args}
if ck_path:
opts["cookiefile"] = ck_path
if proxy:
opts["proxy"] = proxy
try:

View file

@ -6,6 +6,7 @@ counter, hourly log rotation). These pin the two leaks found and the ledger.
"""
import asyncio
import json
import os
import pytest
@ -292,3 +293,51 @@ class TestStaticProbeAgainstYouTube:
alerts, calls = self._client(monkeypatch, status=204, body="")
ok, _ = asyncio.run(alerts._probe_one("http://paid"))
assert ok and calls["url"].startswith("http://www.google.com")
def test_probe_uses_the_download_cookies(monkeypatch, tmp_path):
"""An anonymous probe gets "Sign in to confirm you're not a bot" from the
static IPs (4-sep-2026: ~10 probes/day, 1.8 MB each on the per-GB proxy)
while the cookie-authenticated download passes on those same IPs."""
monkeypatch.setenv("YOUTUBE_COOKIES", "# Netscape HTTP Cookie File\n.youtube.com\tTRUE\t/\tTRUE\t0\tSID\tx\n")
monkeypatch.setenv("STATIC_PROXY_URLS", "http://s1")
monkeypatch.delenv("PROXY_URL", raising=False)
monkeypatch.delenv("DIRECT_FIRST", raising=False)
monkeypatch.setenv("BGUTIL_SCRIPT_PATH", "")
monkeypatch.setenv("BGUTIL_BASE_URL", "")
seen = {}
class _FakeYDL:
def __init__(self, opts):
seen["cookiefile"] = opts.get("cookiefile")
def __enter__(self): return self
def __exit__(self, *a): return False
def extract_info(self, url, download=False):
# The cookie file must exist while the extraction runs.
assert seen["cookiefile"] and os.path.exists(seen["cookiefile"])
with open(seen["cookiefile"]) as f:
seen["body"] = f.read()
return {"duration": 300}
_patch_ydl(monkeypatch, _FakeYDL)
assert metering.probe_url_minutes("https://www.youtube.com/watch?v=x") == 5.0
assert "SID" in seen["body"]
# and it is cleaned up afterwards
assert not os.path.exists(seen["cookiefile"])
def test_probe_without_cookies_configured_still_works(monkeypatch):
monkeypatch.delenv("YOUTUBE_COOKIES", raising=False)
monkeypatch.delenv("STATIC_PROXY_URLS", raising=False)
monkeypatch.delenv("PROXY_URL", raising=False)
monkeypatch.setenv("BGUTIL_SCRIPT_PATH", "")
monkeypatch.setenv("BGUTIL_BASE_URL", "")
class _FakeYDL:
def __init__(self, opts): assert "cookiefile" not in opts
def __enter__(self): return self
def __exit__(self, *a): return False
def extract_info(self, url, download=False): return {"duration": 120}
_patch_ydl(monkeypatch, _FakeYDL)
assert metering.probe_url_minutes("https://www.youtube.com/watch?v=x") == 2.0