security: verify control of external MXIDs before inviting (one-time Matrix DM code)
ci/woodpecker/push/woodpecker Pipeline failed

This commit is contained in:
inference-admin committed 2026-11-20 00:01:23 +00:00
1 parent 96c0866c67
commit dc7c381bd8
1 file changed
+163 -12
+163 -12
View File
@@ -17,6 +17,7 @@ import os
import inspect
import html
from html import escape as _html_escape
import hashlib
import ipaddress
import json
import urllib.parse
@@ -1095,6 +1096,11 @@ def get_db() -> sqlite3.Connection:
# Migration: matrix_mxid_changed_at — throttles external-account changes.
if "matrix_mxid_changed_at" not in cols:
conn.execute("ALTER TABLE members ADD COLUMN matrix_mxid_changed_at TEXT")
# Migration: pending external-MXID verification. An external account is not
# invited until a one-time code sent to that MXID is entered on the dashboard.
for col in ("mxid_pending", "mxid_code_hash", "mxid_code_expires", "mxid_code_sent_at"):
if col not in cols:
conn.execute(f"ALTER TABLE members ADD COLUMN {col} TEXT")
# Migration: credit_balance — purchased, NON-EXPIRING credits (USD).
# Distinct from `balance` (the monthly allowance, which resets): credits
# carry over indefinitely and are spent only after the allowance is
@@ -1916,6 +1922,82 @@ def set_member_matrix_mxid(email: str, mxid: str, changed_at: str | None = None)
conn.close()
def set_mxid_pending(email: str, mxid: str, code_hash: str, expires: str, sent_at: str) -> None:
conn = get_db()
conn.execute(
"UPDATE members SET mxid_pending = ?, mxid_code_hash = ?, "
"mxid_code_expires = ?, mxid_code_sent_at = ? WHERE email = ?",
(mxid, code_hash, expires, sent_at, email),
)
conn.commit()
conn.close()
def get_mxid_pending(email: str):
conn = get_db()
row = conn.execute(
"SELECT mxid_pending, mxid_code_hash, mxid_code_expires, mxid_code_sent_at "
"FROM members WHERE email = ?", (email,)
).fetchone()
conn.close()
return row
def clear_mxid_pending(email: str) -> None:
conn = get_db()
conn.execute(
"UPDATE members SET mxid_pending = '', mxid_code_hash = '', "
"mxid_code_expires = '', mxid_code_sent_at = '' WHERE email = ?", (email,)
)
conn.commit()
conn.close()
def _mxid_code_hash(email: str, mxid: str, code: str) -> str:
return hashlib.sha256(f"{email}:{mxid}:{code}".encode("utf-8")).hexdigest()
async def send_mxid_verification(mxid: str, code: str) -> None:
"""DM a one-time code to the external MXID; raises if the invite fails."""
if not MATRIX_BOT_TOKEN:
raise RuntimeError("MATRIX_BOT_TOKEN is not configured")
headers = {"Authorization": f"Bearer {MATRIX_BOT_TOKEN}", "Content-Type": "application/json"}
async with httpx.AsyncClient(timeout=30.0) as client:
r = await client.post(
f"{MATRIX_HOMESERVER}/_matrix/client/v3/createRoom",
headers=headers,
json={
"preset": "trusted_private_chat",
"invite": [mxid],
"name": "Inference Cooperative verification",
"initial_state": [{
"type": "m.room.history_visibility",
"state_key": "",
"content": {"history_visibility": "shared"},
}],
},
)
if r.status_code not in (200, 201):
logger.warning("MXID verification: createRoom failed for %s (%s)", mxid, r.status_code)
raise RuntimeError(f"Matrix invite failed ({r.status_code})")
room_id = r.json().get("room_id")
enc = urllib.parse.quote(room_id, safe="")
body = (
"Inference Cooperative verification code: " + code + "\n\n"
"Enter this code on the member dashboard to attach this Matrix account. "
"It expires in 10 minutes. If you did not request this, ignore the message."
)
s = await client.put(
f"{MATRIX_HOMESERVER}/_matrix/client/v3/rooms/{enc}/send/m.room.message/"
f"{secrets.token_hex(8)}",
headers=headers,
json={"msgtype": "m.text", "body": body},
)
if s.status_code not in (200, 201):
logger.warning("MXID verification: send failed for %s (%s)", mxid, s.status_code)
raise RuntimeError(f"Matrix message failed ({s.status_code})")
def get_matrix_mxid_changed_at(email: str) -> str | None:
conn = get_db()
row = conn.execute(
@@ -6593,9 +6675,17 @@ async def broker_set_matrix_mxid(request: Request):
if mxid == old_mxid:
return {"status": "saved", "matrix_mxid": mxid, "invite_sent": True}
# Throttle changes: an external account can be swapped at most once per
# MATRIX_MXID_CHANGE_DAYS (default 7). Format-only validation lets a member
# point invites at anyone; time-bounding the churn limits the abuse.
# Clearing is always allowed: it revokes access and must not wait on a
# throttle or a verification DM.
if not mxid:
if old_mxid and not old_mxid.endswith(":inference.coop"):
await revoke_mxid_from_member_rooms(old_mxid)
set_member_matrix_mxid(email, "", changed_at=datetime.now(timezone.utc).isoformat())
clear_mxid_pending(email)
return {"status": "saved", "matrix_mxid": "", "invite_sent": False}
# Throttle successful changes: an external account can be swapped at most
# once per MATRIX_MXID_CHANGE_DAYS (default 7).
changed_at = get_matrix_mxid_changed_at(email)
if changed_at:
try:
@@ -6613,25 +6703,86 @@ async def broker_set_matrix_mxid(request: Request):
except ValueError:
pass # unparseable timestamp: do not lock the member out
# Retire the previous EXTERNAL identity before saving the new one.
if old_mxid and not old_mxid.endswith(":inference.coop"):
# Do not invite yet. Send a one-time code to the MXID first: format-only
# validation lets a member point invites at anyone, and the Space is
# readable by every member. Verify control before granting access.
pending = get_mxid_pending(email)
sent_at = pending[3] if pending else None
if sent_at:
try:
sent = datetime.fromisoformat(sent_at.replace("Z", "+00:00"))
if sent.tzinfo is None:
sent = sent.replace(tzinfo=timezone.utc)
if datetime.now(timezone.utc) - sent < timedelta(seconds=60):
raise HTTPException(429, "Wait a minute before requesting another code")
except HTTPException:
raise
except ValueError:
pass
code = f"{secrets.randbelow(10 ** 6):06d}"
try:
await send_mxid_verification(mxid, code)
except Exception as e:
logger.warning("matrix-mxid: verification DM failed: %s", e)
raise HTTPException(502, "Could not send a verification message to that Matrix account")
now = datetime.now(timezone.utc)
set_mxid_pending(
email, mxid, _mxid_code_hash(email, mxid, code),
(now + timedelta(minutes=10)).isoformat(), now.isoformat(),
)
return {
"status": "verification_required",
"matrix_mxid": mxid,
"expires_in": 600,
"message": "Enter the 6-digit code sent to that Matrix account",
}
@app.post("/broker/matrix-mxid/verify")
@limiter.limit("10/minute")
async def broker_verify_matrix_mxid(request: Request):
email = _verify_broker_secret(request)
if is_guest_account(email):
raise HTTPException(403, "Matrix chat is available to members")
body = await request.json()
code = (body.get("code") or "").strip()
if not re.fullmatch(r"\d{6}", code):
return JSONResponse({"error": "Enter the 6-digit code"}, status_code=400)
pending = get_mxid_pending(email)
mxid, code_hash, expires, _sent_at = pending if pending else ("", "", "", "")
if not mxid or not code_hash:
return JSONResponse({"error": "No pending Matrix change — save the account again"}, status_code=400)
try:
exp = datetime.fromisoformat(str(expires).replace("Z", "+00:00"))
if exp.tzinfo is None:
exp = exp.replace(tzinfo=timezone.utc)
if datetime.now(timezone.utc) > exp:
clear_mxid_pending(email)
return JSONResponse({"error": "That code expired — request a new one"}, status_code=410)
except ValueError:
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)):
return JSONResponse({"error": "That code is not correct"}, status_code=400)
old_mxid = get_member_matrix_mxid(email)
if old_mxid and old_mxid != mxid and not old_mxid.endswith(":inference.coop"):
await revoke_mxid_from_member_rooms(old_mxid)
set_member_matrix_mxid(email, mxid, changed_at=datetime.now(timezone.utc).isoformat())
# Invite the new account into the Space immediately (best-effort; the daily
# sync will also pick it up). Clear = no invite (just removes the mapping).
clear_mxid_pending(email)
invite_sent = True
if mxid:
try:
await sync_matrix_space()
except Exception as e:
logger.warning("matrix-mxid: immediate invite failed: %s", e)
logger.warning("matrix-mxid: verified invite failed: %s", e)
invite_sent = False
# invite_sent=False tells the dashboard the nightly sync will retry; the
# mapping is saved either way, so the member gets a confident confirmation.
return {"status": "saved", "matrix_mxid": mxid, "invite_sent": invite_sent}
def member_per_key_spend(email: str, team_id: str) -> list[dict]:
"""Per-key spend for a member, derived from LiteLLM spend LOGS.