#!/usr/bin/env python3 """Regression test: hostile tokens must be a clean 401/403, never a 500/503. WHY THIS EXISTS On 2026-11-20 a scanner (192.238.226.25) POSTed to the Open Collective webhook URL with a path token containing a non-ASCII character. `secrets.compare_digest` REFUSES str containing non-ASCII with TypeError: comparing strings with non-ASCII characters is not supported so the auth check crashed before rejecting the request. The wrapper turned that into a 503, the portal recorded it as an OC delivery that might have cost a member money, and the sweep emailed info@ a false money-critical alarm. The same crash produced 500s on /admin/* and /broker/* from the same scanner. The guards proven here: COMPARISON 1. `_secret_eq` compares arbitrary UTF-8 input and returns a bool; the raw `compare_digest` is proven to raise, so the regression is real. 2. Empty never matches (a missing secret fails closed). STATUS CODES 3. A webhook token with non-ASCII chars answers 401 — not 503 — and does not ask OC to retry. 4. Non-ASCII in the admin, broker and sync-token headers answers 401/403, not 500. ORIGIN RECORDING 5. The refused delivery is recorded with its source address and user-agent. 6. The failure report names the source in the email body and says a non-OC source is a probe, not a purchase. Runnable: python3 tests/test_auth_probe_hardening.py (from the repo root) """ import asyncio import os import secrets import sys import tempfile import httpx os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "fixture.db") os.environ["WEBHOOK_TOKEN"] = "test-webhook-token" os.environ["ADMIN_TOKEN"] = "test-admin-token" os.environ["ADMIN_TOKEN_LEGACY"] = "0" os.environ["BROKER_SECRET"] = "test-broker-secret" os.environ["LIBRECHAT_SYNC_TOKEN"] = "test-sync-token" sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import app.main as m # noqa: E402 REAL_ASYNC_CLIENT = httpx.AsyncClient UA = "probe-test/1.0" NON_ASCII = "tøken-ø" results = [] def check(name, ok): results.append((name, ok)) SENT = [] def fake_send(to, subject, body, *a, **k): SENT.append({"to": to, "subject": subject, "body": body}) async def main(): m.get_db().close() # create + migrate the fixture schema # --- 1. The raw stdlib call really does raise: this is the bug. --- raised = False try: secrets.compare_digest(NON_ASCII, NON_ASCII) except TypeError: raised = True check("baseline: secrets.compare_digest raises on non-ASCII str", raised) check("helper: identical ASCII secrets match", m._secret_eq("abc", "abc") is True) check("helper: identical non-ASCII secrets match", m._secret_eq(NON_ASCII, NON_ASCII) is True) check("helper: different non-ASCII secrets do not match", m._secret_eq(NON_ASCII, "test-webhook-token") is False) check("helper: empty never matches (fail closed)", m._secret_eq("", "") is False and m._secret_eq("x", "") is False) transport = httpx.ASGITransport(app=m.app, client=("192.238.226.25", 44321)) async with REAL_ASYNC_CLIENT(transport=transport, base_url="http://test") as c: # --- 3. Hostile webhook token: 401, not 503. --- r = await c.post(f"/webhook/opencollective/{NON_ASCII}", json={"type": "order.processed", "data": {}}, headers={"user-agent": UA}) check(f"webhook: non-ASCII token answers 401 (got {r.status_code})", r.status_code == 401) body = r.json() if r.headers.get("content-type", "").startswith("application/json") else {} check("webhook: the refusal does NOT ask OC to retry", body.get("retry") is not True) # --- 5. The refusal is recorded with source + user-agent. --- conn = m.get_db() row = conn.execute( "SELECT status, detail, ip, user_agent FROM webhook_failures " "ORDER BY id DESC LIMIT 1").fetchone() conn.close() check(f"record: the 401 is stored (got {row})", row is not None and row[0] == 401) check("record: the row names the invalid token, not an exception", row is not None and row[1] == "Invalid webhook token") check(f"record: the source address is stored (got {row and row[2]!r})", bool(row and row[2] == "192.238.226.25")) check(f"record: the user-agent is stored (got {row and row[3]!r})", bool(row and row[3] == UA)) # --- 4. Hostile header tokens: auth rejection, never 500. --- for label, path, header in ( ("admin", "/admin/aliases", "x-admin-token"), ("broker", "/broker/keys", "x-broker-secret"), ("sync", "/admin/librechat/keys", "x-sync-token"), ): # httpx encodes str header values as ASCII and refuses non-ASCII; # send the UTF-8 bytes, which is what a hostile client can send. r = await c.get(path, headers=[ (header.encode("ascii"), NON_ASCII.encode("utf-8")), (b"user-agent", UA.encode("utf-8")), ]) check(f"{label}: non-ASCII header token answers 401/403, not 500 " f"(got {r.status_code})", r.status_code in (401, 403)) # --- 6. The report names the source and calls a non-OC source a probe. --- SENT.clear() m.send_email = fake_send rep = m.webhook_failure_report() check(f"report: reported the refused delivery (got {rep.get('status')})", rep.get("status") == "reported") text = SENT[0]["body"] if SENT else "" check(f"report: the body names the source (got {text[:120]!r})", "[source " in text) check("report: the body distinguishes a probe from an OC purchase", "probe, not a purchase" in text) check("report: the body still explains the token-mismatch case", "WEBHOOK_TOKEN" in text) asyncio.run(main()) fails = sum(not ok for _, ok in results) for name, ok in results: print(f" [{'PASS' if ok else 'FAIL'}] {name}") print(f"\n{len(results) - fails}/{len(results)} passed") sys.exit(1 if fails else 0)