security: verify OC orders, fail-closed revoke, per-IP rate buckets, escaped guest email
ci/woodpecker/push/woodpecker Pipeline failed

This commit is contained in:
inference-admin committed 2026-11-19 23:22:51 +00:00
1 parent 5a0a3decbe
commit c9726f4029
6 files changed
+264 -104

No files matched your search

+1 -1
View File
@@ -21,4 +21,4 @@ RUN mkdir -p /app/data
EXPOSE 8000 EXPOSE 8000
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"] CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--forwarded-allow-ips=172.18.0.1"]
+241 -97
View File
@@ -15,6 +15,8 @@ Three responsibilities:
import os import os
import inspect import inspect
import html
from html import escape as _html_escape
import json import json
import logging import logging
import re import re
@@ -192,7 +194,20 @@ app = FastAPI(title="Inference Cooperative Member Portal")
# unrelated admin traffic (my own verification probes among it), and the operator # unrelated admin traffic (my own verification probes among it), and the operator
# saw a failure for an action nobody had abused. Keying on the PATH as well gives # saw a failure for an action nobody had abused. Keying on the PATH as well gives
# each route its own bucket, which is what a per-route limit is supposed to mean. # each route its own bucket, which is what a per-route limit is supposed to mean.
limiter = Limiter(key_func=lambda request: f"{get_remote_address(request)}:{request.url.path}") def _rate_key(request: Request) -> str:
"""Rate-limit key: real client IP + route path.
Cloudron proxies every request, so without --forwarded-allow-ips every
caller shares the proxy's address and one bucket. Uvicorn now trusts only
the proxy (Dockerfile CMD) and presents the client IP in X-Forwarded-For;
get_remote_address reads it. Path stays in the key so each route has its
own budget. Do NOT key on X-Member-User: it is client-supplied and an
attacker could rotate it to evade a limit.
"""
return f"{get_remote_address(request)}:{request.url.path}"
limiter = Limiter(key_func=_rate_key)
app.state.limiter = limiter app.state.limiter = limiter
@@ -248,67 +263,84 @@ OC_COLLECTIVE_SLUG = os.environ.get("OC_COLLECTIVE_SLUG", "inference-cooperative
_order_amount_cache: dict[str, int] = {} _order_amount_cache: dict[str, int] = {}
async def get_order_amount(order_id_v2: str | None) -> int | None: _order_details_cache: dict[str, dict] = {}
"""Look up an order's contribution amount (EXCLUDING the platform tip).
The webhook's `totalAmount` includes the buyer's optional OC tip, which
the co-op never receives — credits must be granted on the tip-free
amount. Returns cents, or None if unresolvable.
The order id arrives from the OC webhook (untrusted input), so it is sent async def get_order_details(order_id_v2: str | None) -> dict | None:
as a GraphQL VARIABLE, never interpolated into the query string (audit L9, """Resolve an Open Collective order to its VERIFIED fields.
2026-11-05 — an interpolated id was a GraphQL injection into the
unauthenticated OC API; the variables form is parameterized by the server). The webhook payload is untrusted (it authenticates with a URL token that
collective admins can see), so every money decision reads the order back
from OC's public GraphQL API and compares its own fields. Returns the raw
order object, or None if OC cannot resolve it.
""" """
if not order_id_v2: if not order_id_v2:
return None return None
if order_id_v2 in _order_amount_cache: if order_id_v2 in _order_details_cache:
return _order_amount_cache[order_id_v2] return _order_details_cache[order_id_v2]
try: query = (
query = ("query OrderAmount($id: String!) { order(order: {id: $id}) " "query OrderDetails($id: String!) { order(order: {id: $id}) {"
"{ amount { valueInCents } platformTipAmount { valueInCents } } }") " id status frequency amount { valueInCents }"
async with httpx.AsyncClient(timeout=15.0) as client: " platformTipAmount { valueInCents }"
r = await client.post(OC_GRAPHQL_URL, " fromAccount { slug } toAccount { slug } tier { name }"
headers={"Content-Type": "application/json", " createdAt description } }"
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64)"}, )
json={"query": query, "variables": {"id": order_id_v2}}) # Transient transport/HTTP failures PROPAGATE so the webhook handler answers
o = r.json().get("data", {}).get("order") or {} # 503 and OC retries. Only a resolved-but-null order returns None (forged id).
cents = (o.get("amount") or {}).get("valueInCents") async with httpx.AsyncClient(timeout=15.0) as client:
if cents is not None: r = await client.post(
_order_amount_cache[order_id_v2] = int(cents) OC_GRAPHQL_URL,
return int(cents) headers={"Content-Type": "application/json",
except Exception as e: "User-Agent": "Mozilla/5.0 (X11; Linux x86_64)"},
logger.warning("Order amount lookup failed for %s: %s", order_id_v2, e) json={"query": query, "variables": {"id": order_id_v2}},
return None )
r.raise_for_status()
o = r.json().get("data", {}).get("order")
if not o:
return None
_order_details_cache[order_id_v2] = o
return o
async def get_order_amount(order_id_v2: str | None) -> int | None:
"""Tip-free amount in cents, from the verified OC order (never the payload)."""
o = await get_order_details(order_id_v2)
cents = ((o or {}).get("amount") or {}).get("valueInCents")
return int(cents) if cents is not None else None
def order_credit_reference(order_id_v2: str) -> str:
"""Ledger idempotence key: the OC order id ALONE.
`oc:{idV2}` — one real order can be credited once, no matter which slug a
forged payload names. Legacy rows used `oc:{slug}:{idV2}`; the webhook
checks BOTH shapes before granting, so history still dedupes.
"""
ref_id = str(order_id_v2 or "").strip()
if not ref_id:
raise ValueError("credit pack: no order idV2 to key the ledger on")
return f"oc:{ref_id}"
def legacy_credit_reference(slug: str, order_id_v2: str) -> str:
return f"oc:{slug}:{order_id_v2}"
def credit_pack_reference(slug: str, order: dict | None) -> str: def credit_pack_reference(slug: str, order: dict | None) -> str:
"""Stable idempotence key for a credit-pack purchase (audit H1, 2026-11-05). """Deprecated shape retained for callers that pass a payload order.
Keyed on the OC order id from the webhook payload (`order.idV2` — the id New rows are keyed on the order id alone (`order_credit_reference`).
`get_order_amount` resolves, so a VERIFIED purchase always carries one).
The webhook's top-level `data.id` is absent from real deliveries; building
the reference from it produced the legacy `oc:<slug>:` empty-suffix
format, which cannot distinguish two purchases by the same member and so
cannot dedupe a re-delivered event. (The shortfall path keys on the OC
transaction publicId — equally unique; the webhook payload does not carry
it, and per this module's contract the collective order list is the
complete source for that shape, so no extra OC query is added here.)
Legacy ledger rows in the empty-suffix format are neither re-keyed nor
rejected: a new-format reference (non-empty id suffix) can never match
one, so the exists-check never blocks a first real grant, and the
historical rows stay exactly as recorded.
""" """
ref_id = str((order or {}).get("idV2") or "").strip() return order_credit_reference(str((order or {}).get("idV2") or ""))
if not ref_id:
raise ValueError(
"credit pack: webhook payload carries no order idV2; refusing to "
"build an ambiguous credit reference"
)
return f"oc:{slug}:{ref_id}"
def credit_reference_exists_for_order(slug: str, order_id_v2: str) -> bool:
"""True when this order was already credited under either ledger shape."""
return (
credit_reference_exists(order_credit_reference(order_id_v2))
or credit_reference_exists(legacy_credit_reference(slug, order_id_v2))
)
# Personal token for the "Inference Co-op Bot" account, which is an admin of # Personal token for the "Inference Co-op Bot" account, which is an admin of
# the collective. Authenticated as an admin, the GraphQL API exposes member # the collective. Authenticated as an admin, the GraphQL API exposes member
@@ -1380,6 +1412,27 @@ def guest_provision_guard(
return None return None
_GUEST_NAME_RE = re.compile(r"^[A-Za-z0-9 .'\-]{0,60}$")
def _clean_guest_name(raw: object) -> str:
"""Guest display name: bounded length, safe characters only.
The name lands in a branded email heading and a Cloudron display name. A
member chooses it, so it is attacker-controlled text: cap it and forbid
markup/URL punctuation there, rather than relying on Cloudron's validator.
"""
name = str(raw or "").strip()
if not name:
return ""
if not _GUEST_NAME_RE.fullmatch(name):
raise HTTPException(
400,
"Guest name: up to 60 characters, letters, spaces, dots, apostrophes and hyphens only",
)
return name
def guest_request_guard(conn, inviter_email: str, recipient_email: str) -> str | None: def guest_request_guard(conn, inviter_email: str, recipient_email: str) -> str | None:
"""Decide whether a MEMBER may send a guest invitation (pure). """Decide whether a MEMBER may send a guest invitation (pure).
@@ -1714,6 +1767,8 @@ def welcome_email(name: str, setup_url: str) -> tuple[str, str, str]:
"Questions? Reply to this email or write to info@inference.coop.\n\n" "Questions? Reply to this email or write to info@inference.coop.\n\n"
"— The Inference Cooperative\n" "— The Inference Cooperative\n"
) )
safe_name = _html_escape(str(name))
safe_setup_url = _html_escape(str(setup_url))
html = f"""<!DOCTYPE html> html = f"""<!DOCTYPE html>
<html lang="en"> <html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head>
@@ -1753,10 +1808,10 @@ def welcome_email(name: str, setup_url: str) -> tuple[str, str, str]:
</tr> </tr>
<tr> <tr>
<td align="center" style="background:#ffffff;border:1px solid #e8e2d8;border-radius:16px;padding:40px 32px;"> <td align="center" style="background:#ffffff;border:1px solid #e8e2d8;border-radius:16px;padding:40px 32px;">
<h1 style="margin:0 0 12px;font-size:24px;font-weight:700;color:#2d3327;">Welcome, {name}</h1> <h1 style="margin:0 0 12px;font-size:24px;font-weight:700;color:#2d3327;">Welcome, {safe_name}</h1>
<p style="margin:0 0 8px;font-size:16px;color:#6b7a62;line-height:1.5;">Thanks for joining the <strong style="color:#2d3327;">Inference Cooperative</strong>.</p> <p style="margin:0 0 8px;font-size:16px;color:#6b7a62;line-height:1.5;">Thanks for joining the <strong style="color:#2d3327;">Inference Cooperative</strong>.</p>
<p style="margin:0 0 28px;font-size:15px;color:#6b7a62;line-height:1.5;">Finish setting up your account to start using private AI chat.</p> <p style="margin:0 0 28px;font-size:15px;color:#6b7a62;line-height:1.5;">Finish setting up your account to start using private AI chat.</p>
<a href="{setup_url}" style="display:inline-block;background:#5b8c5a;color:#ffffff;text-decoration:none;padding:14px 36px;border-radius:10px;font-size:16px;font-weight:600;">Finish setup</a><p style="margin:14px 0 0;font-size:13px;color:#8a9683;line-height:1.5;">This link expires after seven days. If it lapses, write to <a href="mailto:info@inference.coop" style="color:#5b8c5a;">info@inference.coop</a> and we will send a fresh one.</p> <a href="{safe_setup_url}" style="display:inline-block;background:#5b8c5a;color:#ffffff;text-decoration:none;padding:14px 36px;border-radius:10px;font-size:16px;font-weight:600;">Finish setup</a><p style="margin:14px 0 0;font-size:13px;color:#8a9683;line-height:1.5;">This link expires after seven days. If it lapses, write to <a href="mailto:info@inference.coop" style="color:#5b8c5a;">info@inference.coop</a> and we will send a fresh one.</p>
<p style="margin:28px 0 0;font-size:13px;color:#94a08c;line-height:1.5;">This takes about a minute.</p> <p style="margin:28px 0 0;font-size:13px;color:#94a08c;line-height:1.5;">This takes about a minute.</p>
</td> </td>
</tr> </tr>
@@ -2750,13 +2805,13 @@ def guest_invitation_email(name: str, setup_url: str, inviter_name: str = "") ->
# their own display name during Cloudron account setup. # their own display name during Cloudron account setup.
if name: if name:
greet = f"Hi {name}," greet = f"Hi {name},"
h1 = f"You're invited, {name}" h1 = f"You're invited, {_html_escape(str(name))}"
else: else:
greet = "Hi there," greet = "Hi there,"
h1 = "You're invited" h1 = "You're invited"
if inviter_name: if inviter_name:
invited_line = f"{inviter_name} has invited you to the Inference Cooperative" invited_line = f"{inviter_name} has invited you to the Inference Cooperative"
html_invited = f"<strong style=\"color:#2d3327;\">{inviter_name}</strong> has invited you to the <strong style=\"color:#2d3327;\">Inference Cooperative</strong>" html_invited = f"<strong style=\"color:#2d3327;\">{_html_escape(str(inviter_name))}</strong> has invited you to the <strong style=\"color:#2d3327;\">Inference Cooperative</strong>"
else: else:
invited_line = "A member has invited you to the Inference Cooperative" invited_line = "A member has invited you to the Inference Cooperative"
html_invited = "A member has invited you to the <strong style=\"color:#2d3327;\">Inference Cooperative</strong>" html_invited = "A member has invited you to the <strong style=\"color:#2d3327;\">Inference Cooperative</strong>"
@@ -2780,6 +2835,9 @@ def guest_invitation_email(name: str, setup_url: str, inviter_name: str = "") ->
"Questions? Just reply to this email — it reaches the co-op directly.\n\n" "Questions? Just reply to this email — it reaches the co-op directly.\n\n"
"— The Inference Cooperative\n" "— The Inference Cooperative\n"
) )
safe_name = _html_escape(str(name))
safe_setup_url = _html_escape(str(setup_url))
safe_inviter_name = _html_escape(str(inviter_name))
html = f"""<!DOCTYPE html> html = f"""<!DOCTYPE html>
<html lang="en"> <html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head>
@@ -2798,7 +2856,7 @@ def guest_invitation_email(name: str, setup_url: str, inviter_name: str = "") ->
<h1 style="margin:0 0 12px;font-size:24px;font-weight:700;color:#2d3327;">{h1}</h1> <h1 style="margin:0 0 12px;font-size:24px;font-weight:700;color:#2d3327;">{h1}</h1>
<p style="margin:0 0 8px;font-size:16px;color:#6b7a62;line-height:1.5;">{html_invited} — a member-governed AI cooperative running open models.</p> <p style="margin:0 0 8px;font-size:16px;color:#6b7a62;line-height:1.5;">{html_invited} — a member-governed AI cooperative running open models.</p>
<p style="margin:0 0 24px;font-size:15px;color:#6b7a62;line-height:1.5;">Your invitation comes with <strong style="color:#2d3327;">$2 of credits</strong> for the co-op's chat and API. Access runs for {int(GUEST_DAYS)} days from today; the credits themselves don't expire early.</p> <p style="margin:0 0 24px;font-size:15px;color:#6b7a62;line-height:1.5;">Your invitation comes with <strong style="color:#2d3327;">$2 of credits</strong> for the co-op's chat and API. Access runs for {int(GUEST_DAYS)} days from today; the credits themselves don't expire early.</p>
<a href="{setup_url}" style="display:inline-block;background:#5b8c5a;color:#ffffff;text-decoration:none;padding:14px 36px;border-radius:10px;font-size:16px;font-weight:600;">Create your account</a><p style="margin:14px 0 0;font-size:13px;color:#8a9683;line-height:1.5;">This link expires after seven days. If it lapses, write to <a href="mailto:info@inference.coop" style="color:#5b8c5a;">info@inference.coop</a> and we will send a fresh one.</p> <a href="{safe_setup_url}" style="display:inline-block;background:#5b8c5a;color:#ffffff;text-decoration:none;padding:14px 36px;border-radius:10px;font-size:16px;font-weight:600;">Create your account</a><p style="margin:14px 0 0;font-size:13px;color:#8a9683;line-height:1.5;">This link expires after seven days. If it lapses, write to <a href="mailto:info@inference.coop" style="color:#5b8c5a;">info@inference.coop</a> and we will send a fresh one.</p>
<p style="margin:14px 0 28px;font-size:13px;color:#94a08c;line-height:1.5;">This takes about a minute.</p> <p style="margin:14px 0 28px;font-size:13px;color:#94a08c;line-height:1.5;">This takes about a minute.</p>
<p style="margin:0 0 10px;font-size:15px;color:#2d3327;line-height:1.5;"><strong>If you like it, become a member.</strong></p> <p style="margin:0 0 10px;font-size:15px;color:#2d3327;line-height:1.5;"><strong>If you like it, become a member.</strong></p>
<p style="margin:0 0 16px;font-size:14px;color:#6b7a62;line-height:1.5;">Pay on a sliding scale, and receive a $15/month allowance, plus optional credit packs — plus a say in how it's run.</p> <p style="margin:0 0 16px;font-size:14px;color:#6b7a62;line-height:1.5;">Pay on a sliding scale, and receive a $15/month allowance, plus optional credit packs — plus a say in how it's run.</p>
@@ -2850,6 +2908,8 @@ def guest_member_congrats_email(name: str, setup_url: str | None) -> tuple[str,
"Questions? Reply to this email — it reaches the co-op directly.\n\n" "Questions? Reply to this email — it reaches the co-op directly.\n\n"
"— The Inference Cooperative\n" "— The Inference Cooperative\n"
) )
safe_name = _html_escape(str(name))
safe_setup_url = _html_escape(str(setup_url))
html = f"""<!DOCTYPE html> html = f"""<!DOCTYPE html>
<html lang="en"> <html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head>
@@ -2858,7 +2918,7 @@ def guest_member_congrats_email(name: str, setup_url: str | None) -> tuple[str,
<tr><td align="center"> <tr><td align="center">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:520px;"> <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:520px;">
<tr><td align="center" style="background:#ffffff;border:1px solid #e8e2d8;border-radius:16px;padding:40px 32px;"> <tr><td align="center" style="background:#ffffff;border:1px solid #e8e2d8;border-radius:16px;padding:40px 32px;">
<h1 style="margin:0 0 12px;font-size:24px;font-weight:700;color:#2d3327;">You're a member now, {name}</h1> <h1 style="margin:0 0 12px;font-size:24px;font-weight:700;color:#2d3327;">You're a member now, {safe_name}</h1>
<p style="margin:0 0 16px;font-size:16px;color:#6b7a62;line-height:1.5;">Your guest account has become a full membership. Nothing about your login, dashboard or API keys changes — <strong style="color:#2d3327;">any unspent guest credit stays on your account</strong>, on top of your new $15 monthly allowance.</p> <p style="margin:0 0 16px;font-size:16px;color:#6b7a62;line-height:1.5;">Your guest account has become a full membership. Nothing about your login, dashboard or API keys changes — <strong style="color:#2d3327;">any unspent guest credit stays on your account</strong>, on top of your new $15 monthly allowance.</p>
<p style="margin:0 0 24px;font-size:15px;color:#6b7a62;line-height:1.5;">Invites to the co-op forum (Loomio) and chat space (Matrix) are on their way.</p> <p style="margin:0 0 24px;font-size:15px;color:#6b7a62;line-height:1.5;">Invites to the co-op forum (Loomio) and chat space (Matrix) are on their way.</p>
{'<a href="' + setup_url + '" style="display:inline-block;background:#5b8c5a;color:#ffffff;text-decoration:none;padding:14px 36px;border-radius:10px;font-size:16px;font-weight:600;">Finish account setup</a>' if setup_url else '<a href="https://dashboard.inference.coop" style="display:inline-block;background:#5b8c5a;color:#ffffff;text-decoration:none;padding:14px 36px;border-radius:10px;font-size:16px;font-weight:600;">Open your dashboard</a>'} {'<a href="' + setup_url + '" style="display:inline-block;background:#5b8c5a;color:#ffffff;text-decoration:none;padding:14px 36px;border-radius:10px;font-size:16px;font-weight:600;">Finish account setup</a>' if setup_url else '<a href="https://dashboard.inference.coop" style="display:inline-block;background:#5b8c5a;color:#ffffff;text-decoration:none;padding:14px 36px;border-radius:10px;font-size:16px;font-weight:600;">Open your dashboard</a>'}
@@ -2900,6 +2960,8 @@ def guest_limits_email(name: str, reason: str) -> tuple[str, str, str]:
"Questions? Just reply to this email — it reaches the co-op directly.\n\n" "Questions? Just reply to this email — it reaches the co-op directly.\n\n"
"— The Inference Cooperative\n" "— The Inference Cooperative\n"
) )
safe_name = _html_escape(str(name))
safe_reason = _html_escape(str(reason))
html = f"""<!DOCTYPE html> html = f"""<!DOCTYPE html>
<html lang="en"> <html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head>
@@ -3608,20 +3670,29 @@ async def litellm_create_key(email: str, budget: float, team_id: str) -> str:
return r.json().get("key", "") return r.json().get("key", "")
async def litellm_disable_key(key_token: str) -> None: async def litellm_disable_key(key_token: str) -> bool:
"""Delete a member's LiteLLM key (on payment lapse). """Delete a member's LiteLLM key; FAIL LOUDLY, never silently.
/key/delete accepts either the sk- key or its SHA256 hash, so this works /key/delete accepts either the sk- key or its SHA256 hash, so this works
for both current keys and legacy hash-keyed members. for both current keys and legacy hash-keyed members. Callers must not
report success or delete the portal row until LiteLLM confirms: a key that
survives a failed delete is a leaked key nobody can revoke from the UI.
""" """
if not key_token: if not key_token:
return return True
async with httpx.AsyncClient() as client: async with httpx.AsyncClient(timeout=30.0) as client:
await client.post( r = await client.post(
f"{LITELLM_BASE}/key/delete", f"{LITELLM_BASE}/key/delete",
headers={"Authorization": f"Bearer {LITELLM_MASTER_KEY}"}, headers={"Authorization": f"Bearer {LITELLM_MASTER_KEY}"},
json={"keys": [key_token]}, json={"keys": [key_token]},
) )
if r.status_code != 200:
logger.error(
"LiteLLM key delete failed (%s): %s — portal row kept for retry",
r.status_code, r.text[:200],
)
raise HTTPException(502, f"Gateway refused the key delete ({r.status_code}); nothing changed")
return True
async def litellm_team_id_for_email(email: str) -> str | None: async def litellm_team_id_for_email(email: str) -> str | None:
@@ -3705,13 +3776,19 @@ async def broker_create_api_key(email: str, name: str) -> dict:
headers={"Authorization": f"Bearer {LITELLM_MASTER_KEY}"}, headers={"Authorization": f"Bearer {LITELLM_MASTER_KEY}"},
json={"keys": [old_hash]}, json={"keys": [old_hash]},
) )
if del_res.status_code == 200: if del_res.status_code != 200:
logger.info("Rotated API key %s for %s (old key retired)", name, email) # Never rotate forward on an un-retired old key: the new key
else: # would coexist with a working old one and the member could
logger.warning( # not tell which is live. Keep the row unchanged.
"Old key retire failed for %s/%s: %s %s", logger.error(
"Rotation refused for %s/%s: old key retire failed (%s) %s",
email, name, del_res.status_code, del_res.text[:200], email, name, del_res.status_code, del_res.text[:200],
) )
raise HTTPException(
502,
f"Gateway refused to retire the old key ({del_res.status_code}); rotation aborted",
)
logger.info("Rotated API key %s for %s (old key retired)", name, email)
except Exception as exc: # noqa: BLE001 - rotation is best-effort except Exception as exc: # noqa: BLE001 - rotation is best-effort
logger.warning("Old key retire errored for %s/%s: %s", email, name, exc) logger.warning("Old key retire errored for %s/%s: %s", email, name, exc)
r = await client.post( r = await client.post(
@@ -3767,14 +3844,17 @@ async def broker_revoke_api_key(email: str, name: str) -> None:
row = conn.execute( row = conn.execute(
"SELECT hash FROM member_api_keys WHERE email = ? AND name = ?", (email, name) "SELECT hash FROM member_api_keys WHERE email = ? AND name = ?", (email, name)
).fetchone() ).fetchone()
conn.close()
if not row: if not row:
conn.close()
raise HTTPException(404, "Key not found") raise HTTPException(404, "Key not found")
# Delete in LiteLLM FIRST (fails loudly, HTTPException). Only then remove the
# portal row: the hash is the only revocation handle, and a row deleted
# before a failed gateway call leaves a working key with nothing to retry.
await litellm_disable_key(row[0])
conn = get_db()
conn.execute("DELETE FROM member_api_keys WHERE email = ? AND name = ?", (email, name)) conn.execute("DELETE FROM member_api_keys WHERE email = ? AND name = ?", (email, name))
conn.commit() conn.commit()
conn.close() conn.close()
# Delete the underlying LiteLLM key by its hash.
await litellm_disable_key(row[0])
# --- A. Open Collective webhook --- # --- A. Open Collective webhook ---
@@ -4022,12 +4102,17 @@ async def _process_opencollective_webhook(request: Request, token: str):
if not amount_cents: if not amount_cents:
amount_cents = order.get("totalAmount") or 0 amount_cents = order.get("totalAmount") or 0
# Credit-pack detection: one-time contributions to a "Credit pack" # VERIFIED order: every money decision below reads the order back from
# tier route to the member's NON-EXPIRING credit balance instead of # OC and compares its fields. The payload's tier text, slug and amount
# provisioning/allowance. Detection: the OC tier name contains # are hints only; the URL-token webhook is visible to collective admins
# "credit" (case-insensitive). Recurring subscriptions never route # and has been forged before.
# here (a credit pack is a one-time purchase). order_details = await get_order_details(order.get("idV2"))
if "credit" in tier_name.lower() and slug and event_type == "order.processed": verified_tier = ((order_details or {}).get("tier") or {}).get("name") or ""
# Credit-pack detection from the VERIFIED tier. One-time contributions
# to a "Credit pack" tier route to the member's NON-EXPIRING credit
# balance instead of provisioning/allowance.
if "credit" in verified_tier.lower() and slug and event_type == "order.processed":
members = await fetch_members() members = await fetch_members()
email = next((m["email"] for m in members if m["slug"] == slug), None) email = next((m["email"] for m in members if m["slug"] == slug), None)
# The tier is VARIABLE-amount — no fixed face value. Credits are # The tier is VARIABLE-amount — no fixed face value. Credits are
@@ -4035,33 +4120,43 @@ async def _process_opencollective_webhook(request: Request, token: str):
# tip (totalAmount - tip = amount), which we resolve via OC's # tip (totalAmount - tip = amount), which we resolve via OC's
# public order API. Fallback: webhook totalAmount (slightly # public order API. Fallback: webhook totalAmount (slightly
# overgrants if a tip was included; logged). # overgrants if a tip was included; logged).
tip_free_cents = await get_order_amount(order.get("idV2")) problems: list[str] = []
if tip_free_cents is None: if not order_details:
# SECURITY (2026-10-27): do NOT fall back to the payload's own problems.append("OC could not resolve the order")
# amount. This route is authenticated only by a URL token, so a else:
# forged POST naming its own totalAmount used to mint credits for if (order_details.get("status") or "").upper() not in ("PAID", "ACTIVE"):
# any slug. Treat the payload as a hint; require a resolvable OC problems.append(f"status {order_details.get('status')!r}")
# order. A forged id cannot resolve; a transient OC failure holds if ((order_details.get("fromAccount") or {}).get("slug")) != slug:
# for manual reconciliation instead of granting blind. problems.append("payer slug mismatch")
if ((order_details.get("toAccount") or {}).get("slug")) != OC_COLLECTIVE_SLUG:
problems.append("recipient collective mismatch")
if (order_details.get("frequency") or "").upper() != "ONETIME":
problems.append(f"frequency {order_details.get('frequency')!r}")
if problems:
# SECURITY (2026-11-19): the order must be PAID, ONETIME, paid by
# THIS slug, to THIS collective, on the Credit pack tier. A
# forged webhook can name any public order; none of these fields
# come from the payload.
claimed = round(float(amount_cents) / 100.0, 2) claimed = round(float(amount_cents) / 100.0, 2)
logger.warning( logger.warning(
"Credit pack REJECTED: OC could not resolve order %r (slug=%s, payload claimed $%.2f)" "Credit pack REJECTED (%s): order=%r slug=%s claimed=$%.2f — no credits granted",
" — no credits granted", "; ".join(problems), order.get("idV2"), slug, claimed,
order.get("idV2"), slug, claimed,
) )
try: try:
send_email( send_email(
"info@inference.coop", "info@inference.coop",
"Credit pack could not be verified — no credits granted", "Credit pack could not be verified — no credits granted",
f"A credit-pack webhook arrived for {slug} claiming ${claimed:.2f}, but\n" f"A credit-pack webhook arrived for {slug} claiming ${claimed:.2f}, but\n"
f"Open Collective's order API could not resolve order id {order.get('idV2')!r}.\n\n" f"the order could not be verified: {'; '.join(problems)}.\n"
"No credits were granted: the payload's amount is not trusted. If this was a\n" f"Order id: {order.get('idV2')!r}.\n\n"
"real purchase, confirm the order in Open Collective and grant the credits\n" "No credits were granted. If this was a real purchase, confirm the order\n"
"by hand; if it was not, this was an attempt to mint credits.\n", "in Open Collective and grant the credits by hand; if it was not, this was\n"
"an attempt to mint credits.\n",
) )
except Exception as e: except Exception as e:
logger.warning("Credit pack rejection: operator email failed: %s", e) logger.warning("Credit pack rejection: operator email failed: %s", e)
return JSONResponse({"status": "unverified_order_held", "slug": slug}) return JSONResponse({"status": "unverified_order_held", "slug": slug})
tip_free_cents = int((order_details.get("amount") or {}).get("valueInCents") or 0)
amount = round(tip_free_cents / 100.0, 2) amount = round(tip_free_cents / 100.0, 2)
charged = round(float(amount_cents) / 100.0, 2) charged = round(float(amount_cents) / 100.0, 2)
if charged > amount: if charged > amount:
@@ -4079,7 +4174,7 @@ async def _process_opencollective_webhook(request: Request, token: str):
# balance WITHOUT crediting again. The reference is per-order, # balance WITHOUT crediting again. The reference is per-order,
# so this never blocks a new purchase, and legacy empty-suffix # so this never blocks a new purchase, and legacy empty-suffix
# ledger rows can never match a new-format reference. # ledger rows can never match a new-format reference.
if credit_reference_exists(oc_ref): if credit_reference_exists_for_order(slug, str(order.get("idV2") or "")):
logger.info( logger.info(
"Credit pack: %s already in the ledger (OC re-delivery) " "Credit pack: %s already in the ledger (OC re-delivery) "
"— not crediting again", oc_ref, "— not crediting again", oc_ref,
@@ -4189,7 +4284,29 @@ async def _process_opencollective_webhook(request: Request, token: str):
"note": "credit pack purchased without membership; hold recorded and buyer notified", "note": "credit pack purchased without membership; hold recorded and buyer notified",
}) })
if slug and "membership" in tier_name.lower() and event_type == "order.processed": if "membership" in verified_tier.lower() and slug and event_type == "order.processed":
# VERIFIED membership order: status, payer, recipient and tier all
# come from OC, not the payload. A forged delivery naming someone
# else's order therefore cannot provision an arbitrary account.
problems = []
if not order_details:
problems.append("OC could not resolve the order")
else:
if (order_details.get("status") or "").upper() not in ("PAID", "ACTIVE"):
problems.append(f"status {order_details.get('status')!r}")
if ((order_details.get("fromAccount") or {}).get("slug")) != slug:
problems.append("payer slug mismatch")
if ((order_details.get("toAccount") or {}).get("slug")) != OC_COLLECTIVE_SLUG:
problems.append("recipient collective mismatch")
if (order_details.get("frequency") or "").upper() == "ONETIME":
problems.append("one-time payment on a membership tier")
if problems:
logger.warning(
"Membership webhook REJECTED (%s): order=%r slug=%s — nobody provisioned",
"; ".join(problems), order.get("idV2"), slug,
)
return JSONResponse({"status": "unverified_order_held", "slug": slug})
# Every Membership-tier payment (first or recurring) re-pins the # Every Membership-tier payment (first or recurring) re-pins the
# member's allowance reset to payment + 30 days — the reset # member's allowance reset to payment + 30 days — the reset
# follows the member's actual billing rhythm, not a global # follows the member's actual billing rhythm, not a global
@@ -4313,6 +4430,29 @@ async def _process_opencollective_webhook(request: Request, token: str):
if slug: if slug:
member = get_member_by_slug(slug) member = get_member_by_slug(slug)
if member: if member:
# SECURITY (2026-11-19): the payload is untrusted, and a forged
# deletion event used to deactivate any member, zero their
# budget and unsubscribe them. Re-check OC before acting: a slug
# still on the collective's member list is NOT deleted. If OC
# cannot be read, refuse (503) rather than deactivate blind.
try:
active_members = await fetch_members()
except Exception as e:
logger.warning(
"Deletion webhook for %s: OC membership check failed (%s); NOT deactivating",
slug, e,
)
return JSONResponse(
{"status": "ignored", "note": "OC membership check failed; retry"},
status_code=503,
)
if any((m.get("slug") or "") == slug for m in active_members):
logger.warning(
"Deletion webhook for %s IGNORED: slug is still on the OC member list",
slug,
)
return JSONResponse({"status": "ignored", "note": "still active in OC"})
# Move to inactive group (revokes chat access, keeps account + data) # Move to inactive group (revokes chat access, keeps account + data)
if INACTIVE_GROUP_ID and member.get("cloudron_user_id"): if INACTIVE_GROUP_ID and member.get("cloudron_user_id"):
await cloudron_set_group(member["cloudron_user_id"], INACTIVE_GROUP_ID) await cloudron_set_group(member["cloudron_user_id"], INACTIVE_GROUP_ID)
@@ -4564,7 +4704,7 @@ async def admin_provision_guest(request: Request):
# No name is collected and none is derived: the guest chooses their own # No name is collected and none is derived: the guest chooses their own
# display name and username during Cloudron account setup, and the # display name and username during Cloudron account setup, and the
# invitation email greets neutrally. # invitation email greets neutrally.
name = (body.get("name") or "").strip() name = _clean_guest_name(body.get("name"))
if not email or "@" not in email: if not email or "@" not in email:
raise HTTPException(400, "A valid recipient email is required") raise HTTPException(400, "A valid recipient email is required")
# The inviter is the admin account, never a caller-supplied member email: # The inviter is the admin account, never a caller-supplied member email:
@@ -6837,7 +6977,7 @@ async def broker_guest_invite(request: Request):
email = _verify_broker_secret(request) email = _verify_broker_secret(request)
body = await request.json() body = await request.json()
recipient = (body.get("email") or "").strip().lower() recipient = (body.get("email") or "").strip().lower()
name = (body.get("name") or "").strip() name = _clean_guest_name(body.get("name"))
if not recipient or "@" not in recipient: if not recipient or "@" not in recipient:
raise HTTPException(400, "A valid guest email is required") raise HTTPException(400, "A valid guest email is required")
@@ -7537,6 +7677,8 @@ def payment_reminder_email(name: str, contribute_url: str) -> tuple[str, str, st
"Questions? Reply to this email or write to info@inference.coop.\n\n" "Questions? Reply to this email or write to info@inference.coop.\n\n"
"— The Inference Cooperative\n" "— The Inference Cooperative\n"
) )
safe_name = _html_escape(str(name))
safe_contribute_url = _html_escape(str(contribute_url))
html = f"""<!DOCTYPE html> html = f"""<!DOCTYPE html>
<html lang="en"> <html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head>
@@ -7555,7 +7697,7 @@ def payment_reminder_email(name: str, contribute_url: str) -> tuple[str, str, st
<h1 style="margin:0 0 12px;font-size:24px;font-weight:700;color:#2d3327;">Your membership needs attention</h1> <h1 style="margin:0 0 12px;font-size:24px;font-weight:700;color:#2d3327;">Your membership needs attention</h1>
<p style="margin:0 0 8px;font-size:16px;color:#6b7a62;line-height:1.5;">Our records at Open Collective don't show a current monthly contribution for your account, so your monthly allowance won't renew.</p> <p style="margin:0 0 8px;font-size:16px;color:#6b7a62;line-height:1.5;">Our records at Open Collective don't show a current monthly contribution for your account, so your monthly allowance won't renew.</p>
<p style="margin:0 0 28px;font-size:15px;color:#6b7a62;line-height:1.5;">To keep your access, restart or update your contribution. If your payment has already gone through, ignore this.</p> <p style="margin:0 0 28px;font-size:15px;color:#6b7a62;line-height:1.5;">To keep your access, restart or update your contribution. If your payment has already gone through, ignore this.</p>
<a href="{contribute_url}" style="display:inline-block;background:#5b8c5a;color:#ffffff;text-decoration:none;padding:14px 36px;border-radius:999px;font-size:16px;font-weight:600;">Update your contribution</a> <a href="{safe_contribute_url}" style="display:inline-block;background:#5b8c5a;color:#ffffff;text-decoration:none;padding:14px 36px;border-radius:999px;font-size:16px;font-weight:600;">Update your contribution</a>
<p style="margin:28px 0 0;font-size:13px;color:#94a08c;line-height:1.5;">If we don't see a contribution after a short grace period, your account stays in place but loses access until your contribution resumes.</p> <p style="margin:28px 0 0;font-size:13px;color:#94a08c;line-height:1.5;">If we don't see a contribution after a short grace period, your account stays in place but loses access until your contribution resumes.</p>
</td> </td>
</tr> </tr>
@@ -8249,6 +8391,7 @@ def shortfall_email(name: str, amount: float, prev: str, cur: str,
"Questions? Reply to this email or write to info@inference.coop.\n\n" "Questions? Reply to this email or write to info@inference.coop.\n\n"
"— The Inference Cooperative\n" "— The Inference Cooperative\n"
) )
safe_name = _html_escape(str(name))
html = f"""<!DOCTYPE html> html = f"""<!DOCTYPE html>
<html lang="en"> <html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head>
@@ -9007,7 +9150,7 @@ async def reconcile_credit_packs(apply: bool = False, notify: bool = True) -> di
# no reference at all, and this is the only way to tell that from a gap. # no reference at all, and this is the only way to tell that from a gap.
rec["nearby_book_rows"] = nearby rec["nearby_book_rows"] = nearby
candidates.append(rec) candidates.append(rec)
if not acting or credit_reference_exists(ref): if not acting or credit_reference_exists_for_order(slug, str(o.get("id") or "")):
continue continue
new_balance = add_credits(email, rec["amount"], new_balance = add_credits(email, rec["amount"],
reason="credit pack purchase (Open Collective)", reason="credit pack purchase (Open Collective)",
@@ -9822,6 +9965,7 @@ def budget_notice_email(
"info@inference.coop.\n\n" "info@inference.coop.\n\n"
"— The Inference Cooperative\n" "— The Inference Cooperative\n"
) )
safe_name = _html_escape(str(name))
html = f"""<!DOCTYPE html> html = f"""<!DOCTYPE html>
<html lang="en"> <html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head>
+1 -1
View File
@@ -69,7 +69,7 @@ def grant_once(email, amount, ref):
# --- reference building: per-order, non-empty, distinct per purchase --- # --- reference building: per-order, non-empty, distinct per purchase ---
check("reference keyed on the order id", check("reference keyed on the order id",
credit_pack_reference("caseyg", {"idV2": "or_abc123"}), "oc:caseyg:or_abc123") credit_pack_reference("caseyg", {"idV2": "or_abc123"}), "oc:or_abc123")
check("two purchases differ even from one member", check("two purchases differ even from one member",
credit_pack_reference("caseyg", {"idV2": "or_1"}) != credit_pack_reference("caseyg", {"idV2": "or_2"}), credit_pack_reference("caseyg", {"idV2": "or_1"}) != credit_pack_reference("caseyg", {"idV2": "or_2"}),
True) True)
+4 -3
View File
@@ -38,6 +38,7 @@ def check(cond, msg):
def order(freq, status, amount, created="2026-11-17T01:52:56.450Z"): def order(freq, status, amount, created="2026-11-17T01:52:56.450Z"):
return {"frequency": freq, "status": status, return {"frequency": freq, "status": status,
"amount": {"value": amount, "currency": "USD"},
"totalAmount": {"value": amount, "currency": "USD"}, "totalAmount": {"value": amount, "currency": "USD"},
"createdAt": created, "lastChargedAt": created} "createdAt": created, "lastChargedAt": created}
@@ -76,11 +77,11 @@ check(_current_dues([{"frequency": "MONTHLY", "status": "ACTIVE",
"totalAmount": {"value": "not-a-number"}}]) == (None, None), "totalAmount": {"value": "not-a-number"}}]) == (None, None),
"an unparseable amount -> (None, None)") "an unparseable amount -> (None, None)")
print("6. the most recent live recurrence wins when a member has history") print("6. stacked live monthlies are summed (not newest-only)")
old = order("MONTHLY", "ACTIVE", 5, "2024-01-01T00:00:00.000Z") old = order("MONTHLY", "ACTIVE", 5, "2024-01-01T00:00:00.000Z")
new = order("MONTHLY", "ACTIVE", 10, "2026-11-17T01:52:56.450Z") new = order("MONTHLY", "ACTIVE", 10, "2026-11-17T01:52:56.450Z")
check(_current_dues([new, old]) == (10.0, "MONTHLY"), check(_current_dues([new, old]) == (15.0, "MONTHLY"),
"the newest live monthly ($10) wins over an older $5 monthly") "two live monthly subscriptions are summed ($5 + $10 = $15)")
print() print()
if FAILS: if FAILS:
+1 -1
View File
@@ -113,7 +113,7 @@ m.OC_PERSONAL_TOKEN = "test-token"
print("4. the webhook branch: the fix is present, and its silent-fallthrough shape is gone") print("4. the webhook branch: the fix is present, and its silent-fallthrough shape is gone")
src = (ROOT / "app" / "main.py").read_text() src = (ROOT / "app" / "main.py").read_text()
branch = src[src.index('if slug and "membership" in tier_name.lower()'):] branch = src[src.index('if "membership" in verified_tier.lower()'):]
branch = branch[:branch.index("elif slug and first_payment")] branch = branch[:branch.index("elif slug and first_payment")]
check("fetch_account_by_slug(slug)" in branch, check("fetch_account_by_slug(slug)" in branch,
"the branch resolves an unknown payer by account email") "the branch resolves an unknown payer by account email")
+16 -1
View File
@@ -101,6 +101,20 @@ async def order_amount_ok(_order_id_v2=None):
return 5000 return 5000
async def order_details_ok(_order_id_v2=None):
"""Verified OC order for the credit-pack fixture (2026-11-19 hardening)."""
return {
"id": "or_testOrderId123",
"status": "PAID",
"frequency": "ONETIME",
"amount": {"valueInCents": 5000},
"platformTipAmount": {"valueInCents": 0},
"fromAccount": {"slug": MEMBER_SLUG},
"toAccount": {"slug": m.OC_COLLECTIVE_SLUG},
"tier": {"name": "Credit pack"},
}
async def budget_noop(_email): async def budget_noop(_email):
return 0.0 return 0.0
@@ -118,6 +132,7 @@ async def main():
m.sync_team_budget_from_balance = budget_noop # no LiteLLM calls in a test m.sync_team_budget_from_balance = budget_noop # no LiteLLM calls in a test
m.get_order_amount = order_amount_ok m.get_order_amount = order_amount_ok
m.get_order_details = order_details_ok
async with REAL_ASYNC_CLIENT(transport=transport, base_url="http://test") as c: async with REAL_ASYNC_CLIENT(transport=transport, base_url="http://test") as c:
# --- 1. AUTH: a wrong token is still a 401. --- # --- 1. AUTH: a wrong token is still a 401. ---
@@ -181,7 +196,7 @@ async def main():
m.get_credit_balance(MEMBER_EMAIL) == 50.0) m.get_credit_balance(MEMBER_EMAIL) == 50.0)
ref = m.credit_pack_reference(MEMBER_SLUG, {"idV2": ORDER_ID}) ref = m.credit_pack_reference(MEMBER_SLUG, {"idV2": ORDER_ID})
check("grant: the ledger row is keyed on the OC order (idempotence key)", check("grant: the ledger row is keyed on the OC order (idempotence key)",
ref == f"oc:{MEMBER_SLUG}:{ORDER_ID}" and m.credit_reference_exists(ref)) ref == f"oc:{ORDER_ID}" and m.credit_reference_exists(ref))
# --- 4. Re-delivery moves no money. --- # --- 4. Re-delivery moves no money. ---
r = await c.post(url, json=PAYLOAD) r = await c.post(url, json=PAYLOAD)