diff --git a/app/main.py b/app/main.py index 02a1a2a..88fb691 100644 --- a/app/main.py +++ b/app/main.py @@ -17,7 +17,9 @@ import os import inspect import html from html import escape as _html_escape +import ipaddress import json +import urllib.parse import logging import re import sqlite3 @@ -256,6 +258,10 @@ ADMIN_TOKEN_LEGACY = os.environ.get("ADMIN_TOKEN_LEGACY", "0") != "0" OC_GRAPHQL_URL = "https://opencollective.com/api/graphql/v2" OC_COLLECTIVE_SLUG = os.environ.get("OC_COLLECTIVE_SLUG", "inference-cooperative") +# No-tier BACKERs count as members only if they joined BEFORE the Membership +# tier existed (2026-09-06). Post-tier no-tier backers are one-time donors, +# not members (security report 5.3). +LEGACY_NO_TIER_BEFORE = os.environ.get("LEGACY_NO_TIER_BEFORE", "2026-09-06") # Cache of order idV2 -> tip-free contribution amount in cents, resolved via # OC's PUBLIC GraphQL API (no token needed; our personal token lacks the @@ -541,6 +547,11 @@ MATRIX_INVITE_ROOMS = [r.strip() for r in os.environ.get("MATRIX_INVITE_ROOMS", # Legacy alias kept for compatibility: extra member-facing rooms appended to the # invite set above (superseded by MATRIX_INVITE_ROOMS). MATRIX_EXTRA_ROOMS = [r.strip() for r in os.environ.get("MATRIX_EXTRA_ROOMS", "").split(",") if r.strip()] +# Minimum days between external Matrix account changes (0 disables the throttle). +try: + MATRIX_MXID_CHANGE_DAYS = float(os.environ.get("MATRIX_MXID_CHANGE_DAYS", "7") or 7) +except ValueError: + MATRIX_MXID_CHANGE_DAYS = 7.0 LOOMIO_GROUP_ID = os.environ.get("LOOMIO_GROUP_ID", "") # Operator accounts that must always remain in the Loomio group (never removed # by the remove_absent reconciliation), comma-separated. @@ -1081,6 +1092,9 @@ def get_db() -> sqlite3.Connection: # account is invited. At most one extra MXID per member. if "matrix_mxid" not in cols: conn.execute("ALTER TABLE members ADD COLUMN matrix_mxid TEXT") + # 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: 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 @@ -1661,7 +1675,9 @@ async def fetch_members() -> list[dict]: # Admins (the co-op itself) always count. BACKERs must be on the # Membership tier; no-tier BACKERs are legacy contributors from before # tiers existed — grandfathered as members. - if role == "ADMIN" or "membership" in tier.lower() or tier == "": + joined = (n.get("createdAt") or "")[:10] + legacy_no_tier = bool(joined) and joined < LEGACY_NO_TIER_BEFORE + if role == "ADMIN" or "membership" in tier.lower() or legacy_no_tier: result.append({ "email": email, "name": acct.get("name") or email.split("@")[0], @@ -1884,17 +1900,31 @@ def get_member_matrix_mxid(email: str) -> str: return (row[0] or "").strip() if row else "" -def set_member_matrix_mxid(email: str, mxid: str) -> None: - """Set (or clear) the member's optional extra Matrix MXID.""" +def set_member_matrix_mxid(email: str, mxid: str, changed_at: str | None = None) -> None: + """Set (or clear) the member's optional extra Matrix MXID. + + changed_at records a real CHANGE (not an idempotent re-save), which the + broker route uses to throttle external-account swaps. + """ conn = get_db() conn.execute( - "UPDATE members SET matrix_mxid = ? WHERE email = ?", - (mxid.strip() if mxid else "", email), + "UPDATE members SET matrix_mxid = ?, " + "matrix_mxid_changed_at = COALESCE(?, matrix_mxid_changed_at) WHERE email = ?", + (mxid.strip() if mxid else "", changed_at, email), ) conn.commit() conn.close() +def get_matrix_mxid_changed_at(email: str) -> str | None: + conn = get_db() + row = conn.execute( + "SELECT matrix_mxid_changed_at FROM members WHERE email = ?", (email,) + ).fetchone() + conn.close() + return row[0] if row else None + + def _loomio_safe_username(raw) -> str | None: """Sanitize a candidate into a Loomio-legal username. @@ -2599,6 +2629,20 @@ def cloudron_fetch_all_users_sync() -> list[dict]: return users +async def cloudron_email_exists(email: str) -> bool: + """True when ANY Cloudron user already has this email. + + Guest provisioning must refuse these: cloudron_create_user returns the + existing account, and a group change on a steward/operator/bot account + would strip access it never should have touched. + """ + target = (email or "").strip().lower() + if not target: + return False + users = cloudron_fetch_all_users_sync() + return any(((u.get("email") or "").strip().lower()) == target for u in users) + + async def cloudron_create_user(email: str, name: str) -> str: """Create (or return existing) Cloudron user, assigned to the members group. @@ -2654,6 +2698,42 @@ async def cloudron_set_group(user_id: str, group_id: str | None = None) -> None: r.raise_for_status() +async def cloudron_user_group_ids(user_id: str) -> list[str]: + async with httpx.AsyncClient(timeout=20.0) as client: + r = await client.get(f"{CLOUDRON_API}/api/v1/users/{user_id}", headers=cloudron_headers()) + r.raise_for_status() + return list(r.json().get("groupIds") or []) + + +async def cloudron_switch_group( + user_id: str, + add_gid: str | None = None, + remove_gids: tuple[str, ...] = (), +) -> None: + """Add one group and remove named ones, PRESERVING every other group. + + Replacing the whole list (PUT with one gid) stripped stewards/managers + groups from accounts that were never the target of the change — a lapsed + steward lost `stewards` and never got it back, and a guest invite could + overwrite any existing account's groups. This reads the current set first. + """ + if not user_id or (not add_gid and not remove_gids): + return + current = await cloudron_user_group_ids(user_id) + targets = [g for g in current if g not in remove_gids] + if add_gid and add_gid not in targets: + targets.append(add_gid) + if targets == current: + return + async with httpx.AsyncClient(timeout=20.0) as client: + r = await client.put( + f"{CLOUDRON_API}/api/v1/users/{user_id}/groups", + headers=cloudron_headers(), + json={"groupIds": targets}, + ) + r.raise_for_status() + + async def cloudron_set_active(user_id: str, active: bool) -> None: async with httpx.AsyncClient() as client: r = await client.put( @@ -2740,7 +2820,7 @@ async def provision_member(email: str, name: str, slug: str = "") -> str: if is_guest_account(email): return await convert_guest_to_member(email, name, slug) user_id = await cloudron_create_user(email, name) - await cloudron_set_group(user_id) + await cloudron_switch_group(user_id, MEMBERS_GROUP_ID, (INACTIVE_GROUP_ID, GUESTS_GROUP_ID)) await cloudron_set_active(user_id, True) balance = get_member_balance(email) team_id = await litellm_get_or_create_team(email, balance) @@ -3029,8 +3109,24 @@ async def provision_guest_member( if not GUESTS_GROUP_ID: raise HTTPException(503, "GUESTS_GROUP_ID is not configured on the portal app") + # SECURITY (2026-11-19): a guest invite must never land on an EXISTING + # Cloudron account. cloudron_create_user returns the existing user, and a + # group change on a steward/operator/bot account would strip its access. + # Refuse before creating or touching anything. + try: + if await cloudron_email_exists(email): + raise HTTPException( + 409, + "That email already belongs to a Cloudron account — guest invitations need a new address", + ) + except HTTPException: + raise + except Exception as e: + logger.error("Guest guard: Cloudron user list failed (%s); refusing invite", e) + raise HTTPException(503, "Could not verify whether that address already has an account") + user_id = await cloudron_create_user(email, name) - await cloudron_set_group(user_id, GUESTS_GROUP_ID) + await cloudron_switch_group(user_id, GUESTS_GROUP_ID, (INACTIVE_GROUP_ID,)) await cloudron_set_active(user_id, True) # One-time $2 team: budget_duration None means LiteLLM never resets it. @@ -3133,8 +3229,8 @@ async def convert_guest_to_member(email: str, name: str, slug: str = "") -> str: raise HTTPException(404, f"No portal row for {email}") user_id = row[0] - # 1. Group move: guests → members (idempotent PUT; default = members group). - await cloudron_set_group(user_id) + # 1. Group move: guests → members, preserving other groups (e.g. stewards). + await cloudron_switch_group(user_id, MEMBERS_GROUP_ID, (GUESTS_GROUP_ID, GUESTS_ENDED_GROUP_ID, INACTIVE_GROUP_ID)) # 2. Row: full member with the standard allowance. Unspent guest credits # simply stay in credit_balance. anchor_day is untouched: their join @@ -3326,7 +3422,7 @@ async def reconcile_guest_lifecycles() -> dict: if reason is None: continue if INACTIVE_GROUP_ID and user_id: - await cloudron_set_group(user_id, INACTIVE_GROUP_ID) + await cloudron_switch_group(user_id, INACTIVE_GROUP_ID, (MEMBERS_GROUP_ID,)) deactivate_member(email) await revoke_member_litellm_access(email) await listmonk_sync(email, subscribe=False) @@ -3479,7 +3575,7 @@ async def cancel_guest_account(email: str) -> dict: deactivate_member(email) ended_group = GUESTS_ENDED_GROUP_ID or INACTIVE_GROUP_ID if ended_group and user_id: - await cloudron_set_group(user_id, ended_group) + await cloudron_switch_group(user_id, ended_group, (GUESTS_GROUP_ID,)) await revoke_member_litellm_access(email) await listmonk_sync(email, subscribe=False) @@ -4463,7 +4559,7 @@ async def _process_opencollective_webhook(request: Request, token: str): # Move to inactive group (revokes chat access, keeps account + data) if INACTIVE_GROUP_ID and member.get("cloudron_user_id"): - await cloudron_set_group(member["cloudron_user_id"], INACTIVE_GROUP_ID) + await cloudron_switch_group(member["cloudron_user_id"], INACTIVE_GROUP_ID, (MEMBERS_GROUP_ID,)) # Mark inactive in our DB (key injector will refuse requests) deactivate_member(member["email"]) await revoke_member_litellm_access(member["email"]) @@ -6438,6 +6534,46 @@ def local_mxid_for_email(email: str) -> str: return "" + +async def revoke_mxid_from_member_rooms(mxid: str) -> None: + """Remove an external MXID from every room the portal invites members to. + + Called when a member REPLACES or CLEARS their external Matrix account: the + old identity must not linger in the members-only Space. Best-effort (the + nightly sync reconciles), but every failure is logged. + """ + if not mxid or not MATRIX_BOT_TOKEN: + return + headers = {"Authorization": f"Bearer {MATRIX_BOT_TOKEN}", "Content-Type": "application/json"} + async with httpx.AsyncClient(timeout=30.0) as client: + for room in member_invite_rooms(): + enc = urllib.parse.quote(room, safe="") + try: + r = await client.get( + f"{MATRIX_HOMESERVER}/_matrix/client/v3/rooms/{enc}/joined_members", + headers=headers) + if r.status_code == 200 and mxid in (r.json().get("joined") or {}): + await client.post( + f"{MATRIX_HOMESERVER}/_matrix/client/v3/rooms/{enc}/kick", + headers=headers, json={"user_id": mxid, + "reason": "This Matrix account was replaced on the dashboard"}) + logger.info("Matrix: retired replaced external MXID %s from %s", mxid, room) + continue + r2 = await client.get( + f"{MATRIX_HOMESERVER}/_matrix/client/v3/rooms/{enc}/members", + headers=headers, params={"membership": "invite"}) + if r2.status_code == 200 and any( + m.get("state_key") == mxid for m in (r2.json().get("chunk") or [])): + await client.put( + f"{MATRIX_HOMESERVER}/_matrix/client/v3/rooms/{enc}/state/m.room.member/" + f"{urllib.parse.quote(mxid, safe='')}", + headers=headers, json={"membership": "leave", + "reason": "This Matrix account was replaced on the dashboard"}) + logger.info("Matrix: revoked stale invite for replaced MXID %s in %s", mxid, room) + except Exception as e: # noqa: BLE001 - one room must not stop the rest + logger.warning("Matrix: could not retire MXID %s from %s: %s", mxid, room, e) + + @app.post("/broker/matrix-mxid") @limiter.limit("30/minute") async def broker_set_matrix_mxid(request: Request): @@ -6452,7 +6588,35 @@ async def broker_set_matrix_mxid(request: Request): return JSONResponse( {"error": "Enter a Matrix ID like @username:server.org"}, status_code=400 ) - set_member_matrix_mxid(email, mxid) + old_mxid = get_member_matrix_mxid(email) + 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. + changed_at = get_matrix_mxid_changed_at(email) + if changed_at: + try: + last = datetime.fromisoformat(changed_at.replace("Z", "+00:00")) + if last.tzinfo is None: + last = last.replace(tzinfo=timezone.utc) + if datetime.now(timezone.utc) - last < timedelta(days=MATRIX_MXID_CHANGE_DAYS): + raise HTTPException( + 429, + f"You can change your Matrix account once every " + f"{int(MATRIX_MXID_CHANGE_DAYS)} days", + ) + except HTTPException: + raise + 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"): + 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). invite_sent = True @@ -7232,7 +7396,7 @@ async def reconcile_memberships() -> dict: if email not in active_emails and not is_manual_member(email): try: if INACTIVE_GROUP_ID and user_id: - await cloudron_set_group(user_id, INACTIVE_GROUP_ID) + await cloudron_switch_group(user_id, INACTIVE_GROUP_ID, (MEMBERS_GROUP_ID,)) deactivate_member(email) await revoke_member_litellm_access(email) await listmonk_sync(email, subscribe=False) @@ -8100,7 +8264,7 @@ async def reconcile_allowances(send: bool = False) -> dict: "SELECT cloudron_user_id FROM members WHERE email = ?", (email,) ).fetchone() if INACTIVE_GROUP_ID and urow and urow[0]: - await cloudron_set_group(urow[0], INACTIVE_GROUP_ID) + await cloudron_switch_group(urow[0], INACTIVE_GROUP_ID, (MEMBERS_GROUP_ID,)) deactivate_member(email) await revoke_member_litellm_access(email) await listmonk_sync(email, subscribe=False) @@ -9814,6 +9978,14 @@ async def admin_newsletter_reconcile(request: Request): return await listmonk_reconcile() +def _is_ip(value: str) -> bool: + try: + ipaddress.ip_address(value) + return True + except ValueError: + return False + + def _verify_sync_token(request: Request) -> None: """Authenticate the LibreChat key-sync feed via X-Sync-Token. @@ -9852,15 +10024,30 @@ async def admin_librechat_keys(request: Request): """ _verify_sync_token(request) + # SECURITY (2026-11-19): the token alone cannot distinguish the sandbox + # from a stolen-token caller because both arrive through the Cloudron + # proxy. Restrict the feed to the internal network. X-Forwarded-For's LAST + # hop is the address Cloudron's proxy saw; a public address is refused. + xff = (request.headers.get("x-forwarded-for") or "").strip() + if xff: + last = xff.split(",")[-1].strip() + try: + addr = ipaddress.ip_address(last) + internal = addr.is_private or addr.is_loopback + except ValueError: + internal = False + if not internal: + logger.warning("librechat key feed REFUSED for non-internal address %s", last) + raise HTTPException(403, "Internal network only") + conn = get_db() rows = conn.execute( "SELECT email, key_token FROM members WHERE active = 1 AND key_token != ''" ).fetchall() conn.close() logger.warning( - "librechat key feed served: %d member key(s) to %s (ua=%s)", - len(rows), request.client.host if request.client else "?", - (request.headers.get("user-agent") or "?")[:60], + "librechat key feed served: %d member key(s) to %s", + len(rows), (request.headers.get("x-forwarded-for") or (request.client.host if request.client else "?")).split(",")[-1].strip(), ) return { "members": [ diff --git a/tests/test_guest_lifecycle.py b/tests/test_guest_lifecycle.py index b514916..e081815 100644 --- a/tests/test_guest_lifecycle.py +++ b/tests/test_guest_lifecycle.py @@ -75,6 +75,19 @@ calls = {"group": [], "budget": [], "pin": [], "email": [], "listmonk": [], "loomio": 0, "matrix": 0, "revoke": [], "owui": [], "subscribe": []} +async def fake_fetch_users(client): + # No existing Cloudron account for the fixture addresses. + return [] + + +async def fake_email_exists(email): + return False + + +async def rec_switch(user_id, add_gid=None, remove_gids=()): + calls["group"].append((user_id, add_gid)) + + async def rec_group(user_id, group_id=None): calls["group"].append((user_id, group_id or m.MEMBERS_GROUP_ID)) @@ -155,6 +168,9 @@ async def fake_activated(user_id): return False +m.cloudron_fetch_all_users = fake_fetch_users +m.cloudron_email_exists = fake_email_exists +m.cloudron_switch_group = rec_switch m.cloudron_set_group = rec_group m.cloudron_set_active = rec_group # same signature (uid, bool); recorded nowhere critical m.cloudron_create_user = fake_user_create diff --git a/tests/test_guest_requests.py b/tests/test_guest_requests.py index 1da9d81..baabd31 100644 --- a/tests/test_guest_requests.py +++ b/tests/test_guest_requests.py @@ -119,6 +119,17 @@ calls = {"group": [], "budget": [], "email": [], "listmonk": [], "loomio": 0, "matrix": 0} +async def fake_email_exists(email): + return False + + +m.cloudron_email_exists = fake_email_exists + + +async def rec_switch(user_id, add_gid=None, remove_gids=()): + calls["group"].append((user_id, add_gid)) + + async def rec_group(user_id, group_id=None): calls["group"].append((user_id, group_id or m.MEMBERS_GROUP_ID)) @@ -168,6 +179,7 @@ def fake_team_db(team_id): return {"max_budget": None, "spend": 0.0, "budget_reset_at": None} +m.cloudron_switch_group = rec_switch m.cloudron_set_group = rec_group m.cloudron_set_active = rec_group m.cloudron_create_user = fake_user_create