security: reject hostile tokens cleanly and record webhook sources

secrets.compare_digest raises TypeError on str containing non-ASCII, so a
webhook path token or header token with one answered 503/500 instead of
401/403 — a scanner manufactured a false money-critical alert on 2026-11-20.
Compare UTF-8 bytes through _secret_eq and fail closed on empty.

webhook_failures now stores ip and user_agent; the sweep email names each
source and distinguishes a probe from an Open Collective delivery.
This commit is contained in:
inference-admin committed 2026-11-20 20:08:12 +00:00
1 parent 347f2cf720
commit 34f2eeddd7
3 files changed
+223 -24

No files matched your search

+70 -23
View File
@@ -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")