diff --git a/README.md b/README.md index 26fea1c..1a3d908 100644 --- a/README.md +++ b/README.md @@ -224,7 +224,10 @@ Four jobs run inside the container via `CloudronManifest.json` → `addons.sched webhook wrapper, including the 401 that means the webhook URL and `WEBHOOK_TOKEN` disagree) and the sweep emails `info@` **once per new batch** via a marker in `portal_state`, so a wrong token does not mail every sweep while - the rows stay queryable. This replaces the log-scraping watcher that used to run + the rows stay queryable. Each row carries the source IP and user-agent, and the + email names the source: Open Collective posts from its own hosts, so a refusal + from an unrelated address is a probe, not a purchase. This replaces the + log-scraping watcher that used to run on the operator's machine: the portal handles every delivery, so the portal is what must notice and report a failure. (It also removes the dependency on a log buffer with only hours of memory — when the 2026-11-13 $10 purchase was diff --git a/app/main.py b/app/main.py index 9d3f14d..a80b2eb 100644 --- a/app/main.py +++ b/app/main.py @@ -245,6 +245,29 @@ BROKER_SECRET = os.environ.get("BROKER_SECRET", "") # is the standard way to authenticate them. WEBHOOK_TOKEN = os.environ.get("WEBHOOK_TOKEN", "") + +def _secret_eq(provided: str | None, expected: str | None) -> bool: + """Constant-time secret comparison that cannot raise on hostile input. + + `secrets.compare_digest()` refuses `str` containing non-ASCII with + `TypeError`. Tokens arrive from URL paths and headers, so ANY caller can + supply such a value: on 2026-11-20 a scanner POSTed a webhook path token + containing non-ASCII and turned an auth rejection into a 503 (and the same + crash produced 500s on admin/broker routes). Compare UTF-8 bytes instead — + any input, however malformed, is simply unequal, and the answer stays a + clean 401/403. Empty never matches: a missing secret must fail closed. + """ + if not provided or not expected: + return False + try: + return secrets.compare_digest( + provided.encode("utf-8", "surrogatepass"), + expected.encode("utf-8", "surrogatepass"), + ) + except (UnicodeError, TypeError): + return False + + # SECURITY (2026-10-27 member disclosure): the /admin/* token is SEPARATE from # WEBHOOK_TOKEN. WEBHOOK_TOKEN must sit in the Open Collective webhook URL (OC's # generic webhooks cannot send headers), so anything that learns that URL — an OC @@ -997,9 +1020,9 @@ def _verify_admin_token(request: Request) -> None: places we do not control, and it used to unlock all of /admin/*. """ provided = request.headers.get("x-admin-token", "") - if ADMIN_TOKEN and secrets.compare_digest(provided, ADMIN_TOKEN): + if ADMIN_TOKEN and _secret_eq(provided, ADMIN_TOKEN): return - if ADMIN_TOKEN_LEGACY and WEBHOOK_TOKEN and secrets.compare_digest(provided, WEBHOOK_TOKEN): + if ADMIN_TOKEN_LEGACY and WEBHOOK_TOKEN and _secret_eq(provided, WEBHOOK_TOKEN): logger.warning( "admin auth: caller used the legacy WEBHOOK_TOKEN — move it to" " ADMIN_TOKEN, then set ADMIN_TOKEN_LEGACY=0" @@ -1275,9 +1298,19 @@ def get_db() -> sqlite3.Connection: "at TEXT NOT NULL, " "status INTEGER NOT NULL, " "event_type TEXT, " - "detail TEXT" + "detail TEXT, " + "ip TEXT DEFAULT '', " + "user_agent TEXT DEFAULT ''" ")" ) + # Migration: source address + user-agent. Without them a refusal cannot be + # told apart by origin — the 2026-11-20 batch looked like an OC token + # mismatch when every row came from one scanner. Existing rows keep ''. + wf_cols = [r[1] for r in conn.execute("PRAGMA table_info(webhook_failures)").fetchall()] + if "ip" not in wf_cols: + conn.execute("ALTER TABLE webhook_failures ADD COLUMN ip TEXT DEFAULT ''") + if "user_agent" not in wf_cols: + conn.execute("ALTER TABLE webhook_failures ADD COLUMN user_agent TEXT DEFAULT ''") # Small key/value store for the portal's own bookkeeping (e.g. "the last # webhook failure id we have already reported"). Deliberately not a settings # table: nothing here is configuration. @@ -4083,7 +4116,8 @@ def _state_set(conn, key: str, value: str) -> None: "ON CONFLICT(key) DO UPDATE SET value = excluded.value", (key, str(value))) -def record_webhook_failure(status: int, event_type: str = "", detail: str = "") -> None: +def record_webhook_failure(status: int, event_type: str = "", detail: str = "", + ip: str = "", user_agent: str = "") -> None: """Record a delivery the portal did not accept — the SYSTEM owns noticing these. WHY THIS EXISTS: the alert for a failed Open Collective delivery used to live @@ -4103,9 +4137,11 @@ def record_webhook_failure(status: int, event_type: str = "", detail: str = "") try: conn = get_db() conn.execute( - "INSERT INTO webhook_failures (at, status, event_type, detail) VALUES (?,?,?,?)", + "INSERT INTO webhook_failures " + "(at, status, event_type, detail, ip, user_agent) VALUES (?,?,?,?,?,?)", (datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S"), int(status), - (event_type or "")[:64], (detail or "")[:400])) + (event_type or "")[:64], (detail or "")[:400], + (ip or "")[:64], (user_agent or "")[:200])) conn.execute("DELETE FROM webhook_failures WHERE id NOT IN " "(SELECT id FROM webhook_failures ORDER BY id DESC LIMIT 200)") conn.commit() @@ -4148,10 +4184,11 @@ def webhook_failure_report(notify: bool = True) -> dict: conn = get_db() last_id = int(_state_get(conn, WEBHOOK_FAILURE_MARKER, "0") or "0") rows = [ - {"id": r[0], "at": r[1], "status": r[2], "event_type": r[3], "detail": r[4]} + {"id": r[0], "at": r[1], "status": r[2], "event_type": r[3], + "detail": r[4], "ip": r[5], "user_agent": r[6]} for r in conn.execute( - "SELECT id, at, status, event_type, detail FROM webhook_failures " - "WHERE id > ? ORDER BY id", (last_id,))] + "SELECT id, at, status, event_type, detail, ip, user_agent " + "FROM webhook_failures WHERE id > ? ORDER BY id", (last_id,))] conn.close() except Exception as e: # noqa: BLE001 logger.warning("webhook failure report failed: %s", e) @@ -4164,6 +4201,7 @@ def webhook_failure_report(notify: bool = True) -> dict: f" {r['at']} HTTP {r['status']} " f"{r['event_type'] or '(event type unknown)'}" + (f" — {r['detail']}" if r["detail"] else "") + + (f" [source {r['ip']}]" if r["ip"] else " [source not recorded]") for r in rows ] logger.error("OC webhook: %d delivery(ies) were not accepted since the last report:\n%s", @@ -4179,6 +4217,10 @@ def webhook_failure_report(notify: bool = True) -> dict: + "\n\nA 401/403/404 means the webhook URL and WEBHOOK_TOKEN disagree — the " "delivery never reached the handler. Any other status means we took it and " "then errored; if the payload was an order, confirm the member was credited. " + "Each line names its source address: Open Collective posts from its own " + "hosts (the successful deliveries in the log name them), so a request from " + "any other address is a probe, not a purchase — its payload was never " + "handled and nothing is owed for it. " "The sweep's credit-pack reconciliation reads Open Collective's own orders " "and grants anything missing, so a failed purchase repairs itself; this notice " "is for the failures it cannot see.\n" @@ -4233,17 +4275,22 @@ async def opencollective_webhook(request: Request, token: str): await request.body() except Exception: # noqa: BLE001 pass + ip = request.client.host if request.client else "" + user_agent = request.headers.get("user-agent", "") try: return await _process_opencollective_webhook(request, token) except HTTPException as e: # A 401/403/404 means the delivery never reached the handler: the webhook # URL and WEBHOOK_TOKEN disagree. Still a 401 to OC, but now the SYSTEM - # records it, so a misconfigured webhook stops being invisible. + # records it — with its source — so a misconfigured webhook stops being + # invisible and a probe cannot masquerade as an OC failure. if e.status_code in (401, 403, 404): - record_webhook_failure(e.status_code, _peek_event_type(request), str(e.detail)) + record_webhook_failure(e.status_code, _peek_event_type(request), + str(e.detail), ip, user_agent) raise except Exception as e: # noqa: BLE001 - record_webhook_failure(503, _peek_event_type(request), f"{type(e).__name__}: {e}") + record_webhook_failure(503, _peek_event_type(request), f"{type(e).__name__}: {e}", + ip, user_agent) logger.exception( "OC webhook: handler failed (%s: %s) — answering 503 so OC retries; " "if the payload was an order, confirm the member was credited", @@ -4262,7 +4309,7 @@ async def _process_opencollective_webhook(request: Request, token: str): generic webhooks are not HMAC-signed, so a secret URL is the standard way to authenticate them). """ - if not WEBHOOK_TOKEN or not secrets.compare_digest(token, WEBHOOK_TOKEN): + if not WEBHOOK_TOKEN or not _secret_eq(token, WEBHOOK_TOKEN): raise HTTPException(401, "Invalid webhook token") payload = await request.json() @@ -4982,7 +5029,7 @@ async def resend_guest_setup_email(email: str) -> dict: @app.post("/admin/guest-invites/resend") async def admin_guest_resend(request: Request): """Body: {"email": "guest@..."} — one fresh setup link.""" - if not ADMIN_TOKEN or not secrets.compare_digest( + if not ADMIN_TOKEN or not _secret_eq( request.headers.get("x-admin-token", ""), ADMIN_TOKEN ): raise HTTPException(401, "Invalid admin token") @@ -4996,7 +5043,7 @@ async def admin_guest_resend(request: Request): @app.post("/admin/guest-invites/resend-stale") async def admin_guest_resend_stale(request: Request): """Resend every unaccepted guest invite older than `days` (default 7).""" - if not ADMIN_TOKEN or not secrets.compare_digest( + if not ADMIN_TOKEN or not _secret_eq( request.headers.get("x-admin-token", ""), ADMIN_TOKEN ): raise HTTPException(401, "Invalid admin token") @@ -5360,7 +5407,7 @@ def _alias_map(conn) -> dict: @app.get("/admin/aliases") async def admin_aliases_list(request: Request): - if not ADMIN_TOKEN or not secrets.compare_digest( + if not ADMIN_TOKEN or not _secret_eq( request.headers.get("x-admin-token", ""), ADMIN_TOKEN ): raise HTTPException(401, "Invalid admin token") @@ -5377,7 +5424,7 @@ async def admin_aliases_list(request: Request): @app.post("/admin/aliases") async def admin_aliases_add(request: Request): """Body: {"slug": "incognito-…", "email": "member@…"}. Idempotent on slug.""" - if not ADMIN_TOKEN or not secrets.compare_digest( + if not ADMIN_TOKEN or not _secret_eq( request.headers.get("x-admin-token", ""), ADMIN_TOKEN ): raise HTTPException(401, "Invalid admin token") @@ -6511,7 +6558,7 @@ def _verify_broker_secret(request: Request) -> str: if not BROKER_SECRET: raise HTTPException(503, "Broker secret not configured") provided = request.headers.get("x-broker-secret", "") - if not secrets.compare_digest(provided, BROKER_SECRET): + if not _secret_eq(provided, BROKER_SECRET): raise HTTPException(401, "Invalid broker secret") identity = ( request.headers.get("x-member-email") @@ -6569,7 +6616,7 @@ def _verify_broker_guest_identity(request: Request) -> str: if not BROKER_SECRET: raise HTTPException(503, "Broker secret not configured") provided = request.headers.get("x-broker-secret", "") - if not secrets.compare_digest(provided, BROKER_SECRET): + if not _secret_eq(provided, BROKER_SECRET): raise HTTPException(401, "Invalid broker secret") identity = ( request.headers.get("x-member-email") @@ -6819,7 +6866,7 @@ async def broker_verify_matrix_mxid(request: Request, background: BackgroundTask clear_mxid_pending(email) return JSONResponse({"error": "That code expired — request a new one"}, status_code=410) - if not secrets.compare_digest(code_hash, _mxid_code_hash(email, mxid, code)): + if not _secret_eq(code_hash, _mxid_code_hash(email, mxid, code)): return JSONResponse({"error": "That code is not correct"}, status_code=400) old_mxid = get_member_matrix_mxid(email) @@ -7176,7 +7223,7 @@ def _verify_broker_identity_any_state(request: Request) -> str: if not BROKER_SECRET: raise HTTPException(503, "Broker secret not configured") provided = request.headers.get("x-broker-secret", "") - if not secrets.compare_digest(provided, BROKER_SECRET): + if not _secret_eq(provided, BROKER_SECRET): raise HTTPException(401, "Invalid broker secret") identity = (request.headers.get("x-member-email") or request.headers.get("x-member-user") or "").strip() if not identity: @@ -10209,7 +10256,7 @@ def _verify_sync_signature(request: Request) -> None: raise HTTPException(401, "Sync timestamp outside the allowed window") msg = f"{ts}\n{request.url.path}\n{request.url.query or ''}" expected = hmac.new(secret.encode("utf-8"), msg.encode("utf-8"), hashlib.sha256).hexdigest() - if not secrets.compare_digest(sig, expected): + if not _secret_eq(sig, expected): raise HTTPException(401, "Invalid sync signature") @@ -10224,7 +10271,7 @@ def _verify_sync_token(request: Request) -> None: if not expected: raise HTTPException(503, "Sync token not configured") provided = request.headers.get("x-sync-token", "") - if not secrets.compare_digest(provided, expected): + if not _secret_eq(provided, expected): raise HTTPException(401, "Invalid sync token") diff --git a/tests/test_auth_probe_hardening.py b/tests/test_auth_probe_hardening.py new file mode 100644 index 0000000..01e811d --- /dev/null +++ b/tests/test_auth_probe_hardening.py @@ -0,0 +1,149 @@ +#!/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)