diff --git a/app/main.py b/app/main.py index 6deea63..c45afa7 100644 --- a/app/main.py +++ b/app/main.py @@ -4681,14 +4681,16 @@ async def admin_overview(request: Request): "account_type, oc_email, guest_expires_at FROM members ORDER BY email" ).fetchall() # Guest inviter/expiry from the guests ledger (latest row per recipient) — - # the abuse-protection context the panel shows on the guest pill. + # the abuse-protection context the panel shows on the guest pill, plus the + # invite date for the invited (awaiting setup) reason line. guest_info: dict[str, dict] = {} try: for r in conn.execute( - "SELECT recipient_email, inviter_email, guest_expires_at, status " + "SELECT recipient_email, inviter_email, guest_expires_at, status, created_at " "FROM guests WHERE id IN (SELECT MAX(id) FROM guests GROUP BY recipient_email)" ).fetchall(): - guest_info[r[0]] = {"inviter": r[1], "expires": r[2], "status": r[3]} + guest_info[r[0]] = {"inviter": r[1], "expires": r[2], "status": r[3], + "sent": r[4]} except Exception as e: logger.warning("admin overview: guests ledger read failed: %s", e) conn.close() @@ -4777,6 +4779,20 @@ async def admin_overview(request: Request): spend, ) mstate, mstate_reason = member_membership_state(email, bool(active)) + if ((acct_type or "member") == "guest" and active + and guest_invite_pending(user_id, usernames, invite_accepted)): + # A provisioned-but-NOT-set-up guest: the invitation is out but the + # guest has not accepted it (inviteAccepted false / no username), so + # they cannot log in yet. Reads as 'invited' — never 'active' — + # until acceptance flips it. Display/state semantics only: access + # rules, the $2 cap and the expiry box are unchanged (an unaccepted + # guest cannot reach anything anyway — the setup link is the only + # door in). + sent = (guest_info.get(email) or {}).get("sent") + mstate = "invited" + mstate_reason = (f"awaiting setup — invite sent {str(sent)[:10]}, " + "not yet accepted" if sent else + "awaiting setup — invitation not yet accepted") entry = { "email": email, "all_time_spend": round(member_all_time, 2), @@ -6055,7 +6071,11 @@ async def broker_guest_list(request: Request): REJECTED requests from the trial-approval period (kept for history; nothing new is ever decided) plus every row in the guests ledger with what became of it (active, converted, expired, depleted, - cancelled by recipient). + cancelled by recipient). Each guest entry also carries `state` — + 'invited' while the guest has not accepted their Cloudron invite + (provisioned but awaiting setup, cannot log in yet), else the + ledger status; consumers should render `state` and fall back to + `status` only when it is absent (older payloads). """ email = _verify_broker_secret(request) conn = get_db() @@ -6065,8 +6085,10 @@ async def broker_guest_list(request: Request): (email,), ).fetchall() sent = conn.execute( - "SELECT recipient_email, created_at, status " - "FROM guests WHERE inviter_email = ? ORDER BY id DESC", + "SELECT g.recipient_email, g.created_at, g.status, " + "m.cloudron_user_id, m.active, m.account_type " + "FROM guests g LEFT JOIN members m ON m.email = g.recipient_email " + "WHERE g.inviter_email = ? ORDER BY g.id DESC", (email,), ).fetchall() window = f"-{int(GUEST_PER_INVITER_DAYS)} days" @@ -6077,6 +6099,24 @@ async def broker_guest_list(request: Request): ).fetchone()[0] conn.close() + # Invite acceptance per trail guest — the same Cloudron signal the admin + # overview uses (username + inviteAccepted). Fetched once, fail-soft: when + # the fetch fails the invited state is simply not claimed and the trail + # keeps showing the ledger status. + usernames: dict[str, str] = {} + invite_accepted: dict[str, bool] = {} + try: + async with httpx.AsyncClient(timeout=15.0) as client: + users = await cloudron_fetch_all_users(client) + if users is not None: + for u in users: + uid = u.get("id") + if u.get("username"): + usernames[uid] = u["username"] + invite_accepted[uid] = bool(u.get("inviteAccepted")) + except Exception as e: + logger.warning("broker guests: cloudron users fetch failed: %s", e) + eligible = last_sent is None next_eligible_at = None if not eligible: @@ -6094,9 +6134,18 @@ async def broker_guest_list(request: Request): "name": rname, "created_at": created, "decided_at": decided, "status": status, "note": note, }) - for recipient, created, status in sent: - trail.append({"kind": "guest", "recipient": recipient, - "created_at": created, "status": status}) + for recipient, created, status, user_id, g_active, g_type in sent: + entry = {"kind": "guest", "recipient": recipient, + "created_at": created, "status": status} + if ((g_type or "member") == "guest" and g_active + and guest_invite_pending(user_id, usernames, invite_accepted)): + # Provisioned but the invite is not accepted yet — display as + # 'invited', never 'active' (the guest cannot log in until they + # accept; the ledger status stays the trail's record of record). + entry["state"] = "invited" + else: + entry["state"] = status + trail.append(entry) trail.sort(key=lambda t: t.get("decided_at") or t["created_at"] or "", reverse=True) return { "eligible": eligible, @@ -6511,6 +6560,28 @@ def member_membership_state(email: str, active: bool) -> tuple[str, str]: return "active", "" +def guest_invite_pending(user_id, usernames: dict, invite_accepted: dict) -> bool: + """True when a guest's Cloudron invite is OUT but NOT yet accepted. + + The provisioned-but-not-set-up state: the Cloudron account exists (the + invitation email with the setup link went out) but the guest has not + clicked it — inviteAccepted is false and no username is chosen, so they + cannot log in yet. Derived the same way the overview's `activated` flag + is (username and inviteAccepted move in lockstep for invite-created + accounts); NOT accepted = inviteAccepted false AND no username. + + Only a SEEN user record can be pending: when the Cloudron users fetch + failed (or the user is unknown to it) the evidence is absent, and the + caller must fall back to the membership state rather than claim + 'invited' — never assert a state the data does not show. + """ + if not user_id: + return False + if user_id not in invite_accepted and user_id not in usernames: + return False + return not (invite_accepted.get(user_id, False) or bool(usernames.get(user_id))) + + def _parse_oc_dt(value): """Parse an Open Collective ISO timestamp ('…Z') into an aware datetime.""" diff --git a/tests/test_guest_invited_state.py b/tests/test_guest_invited_state.py new file mode 100644 index 0000000..0be8988 --- /dev/null +++ b/tests/test_guest_invited_state.py @@ -0,0 +1,291 @@ +#!/usr/bin/env python3 +"""Guest invited state — a provisioned-but-NOT-set-up guest never reads 'active'. + +WHY THIS EXISTS + A guest invitation provisions IMMEDIATELY (Cloudron user + invitation email + with the setup link), but the Cloudron account is not ACCEPTED until the + guest clicks that link (inviteAccepted=false, no username) — they cannot + log in yet. Every surface that reads the guest's state must therefore show + 'invited' (awaiting setup) at that point, never 'active', and flip to the + ordinary state only when the invite is accepted. Display/state semantics + only: access rules, the guest cap and the expiry box are unchanged. + + Every path here runs against a FIXTURE database with the network layer + REPLACED: any code path that reaches Cloudron/LiteLLM/OC/Listmonk outside + the stubs fails the test loudly instead of acting on live systems. + + 1. guest_invite_pending — the derivation itself: accepted, username-set, + unseen-record (fetch failed) and no-user-id cases. + 2. GET /admin/overview: a fresh guest (inviteAccepted=false, no + username) reports state='invited' with an 'awaiting setup' reason; + the guests ledger status stays the record of record. + 3. Simulated acceptance (inviteAccepted flips true, or a username is + chosen) → the same endpoint reports state='active'. + 4. A FAILED Cloudron users fetch never claims 'invited' — the row falls + back to the membership state rather than inventing a state the data + does not show. + 5. An established MEMBER row is untouched by the guest branch: state + 'active', empty reason, still in members[]. + 6. The member's trail (GET /broker/guests) carries state='invited' for + the un-accepted guest and state= once accepted. + + Runnable: python3 tests/test_guest_invited_state.py (from the repo root) +""" +import asyncio +import base64 +import os +import sys +import tempfile + +os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "fixture.db") +os.environ["PORTAL_KEK"] = base64.b64encode(bytes(32)).decode() +os.environ["ADMIN_TOKEN"] = "test-admin-token" # admin endpoints authenticate on this +os.environ.setdefault("GUESTS_GROUP_ID", "gid-fixture-guests") +os.environ.setdefault("MEMBERS_GROUP_ID", "gid-fixture-members") +os.environ.setdefault("INACTIVE_GROUP_ID", "gid-fixture-inactive") +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +import app.main as m # noqa: E402 + +m.DB_PATH = os.environ["DB_PATH"] + +results = [] + + +def check(name, ok, detail=""): + results.append((name, bool(ok), detail)) + print(("PASS " if ok else "FAIL ") + name + (f" [{detail}]" if detail and not ok else "")) + + +# --- Cloudron users fixture (the ONLY external signal this feature reads) --- # +CLOUDRON_USERS = { + "uid-guest@x.org": {"inviteAccepted": False, "username": None}, + "uid-member@x.org": {"inviteAccepted": True, "username": "established"}, +} + + +class _FakeResponse: + status_code = 200 + + def raise_for_status(self): + pass + + def json(self): + return [] # LiteLLM /team/list: no teams in this fixture + + +class _FakeClient: + """Answers only what admin_overview asks: cloudron_fetch_all_users (stubbed + separately) and the LiteLLM team/list GET (empty).""" + + def __init__(self, *a, **k): + pass + + async def __aenter__(self): + return self + + async def __aexit__(self, *a): + return False + + async def get(self, url, **k): + return _FakeResponse() + + +class _NoNetwork: + def __init__(self, *a, **k): + raise AssertionError("live network attempted during fixture test") + + def __call__(self, *a, **k): # pragma: no cover + raise AssertionError("live network attempted during fixture test") + + +m.httpx.AsyncClient = _FakeClient # ONLY _FakeClient.__init__-safe paths run + + +async def fetch_users_ok(client): + return [{"id": uid, "username": v.get("username"), + "inviteAccepted": v.get("inviteAccepted", False)} + for uid, v in CLOUDRON_USERS.items()] + + +async def fetch_users_broken(client): + return None # page 1 unresolvable — the documented fetch-failure shape + + +m.cloudron_fetch_all_users = fetch_users_ok +# The overview's all-time-spend query is a PG read — absent in the fixture and +# fail-soft by design; make that loud rather than implicit. +def _no_pg(*a, **k): + raise AssertionError("live PG attempted during fixture test") + + +m._pg_connect = _no_pg + + +# --- real Request objects (the slowapi limiter decorator requires them) ----- # +from starlette.requests import Request as StarletteRequest # noqa: E402 +import json as _json # noqa: E402 + + +def make_request(method="GET", body=None, headers=None): + raw = _json.dumps(body or {}).encode() + headers = dict(headers or {}) + if raw and "content-length" not in headers: + headers["content-length"] = str(len(raw)) + async def receive(): + return {"type": "http.request", "body": raw, "more_body": False} + scope = { + "type": "http", "method": method, "path": "/", "query_string": b"", + "headers": [(k.lower().encode(), v.encode()) for k, v in (headers or {}).items()], + "server": ("testserver", 80), "client": ("testclient", 123), + } + return StarletteRequest(scope, receive) + + +def seed_account(conn, email, account_type="member", active=1, uid=None): + conn.execute( + "INSERT INTO members (email, key_token, cloudron_user_id, slug, active, " + "balance, credit_balance, account_type) " + "VALUES (?, 'enc', ?, '', ?, ?, 0, ?)", + (email, uid or ("uid-" + email), active, 0.0, account_type), + ) + + +def seed_guest_ledger(conn, inviter, recipient, status="active"): + conn.execute( + "INSERT INTO guests (inviter_email, recipient_email, oc_reference, " + "guest_expires_at, status, created_at) " + "VALUES (?, ?, NULL, datetime('now', '+60 days'), ?, datetime('now'))", + (inviter, recipient, status), + ) + + +def main(): + m.get_db().close() # create + migrate the fixture schema + conn = m.get_db() + m._ensure_allowance_tables(conn) + + # --- 1. the derivation itself -------------------------------------------- + check("derive: accepted invite is not pending", + m.guest_invite_pending("u", {}, {"u": True}) is False) + check("derive: a chosen username counts as accepted (first login)", + m.guest_invite_pending("u", {"u": "theirname"}, {"u": False}) is False) + check("derive: un-accepted + no username IS pending", + m.guest_invite_pending("u", {}, {"u": False}) is True) + check("derive: a record we never saw is NOT pending (fetch failed)", + m.guest_invite_pending("u", {}, {}) is False) + check("derive: no user id is never pending", + m.guest_invite_pending(None, {}, {"u": False}) is False) + + # --- 2-5. /admin/overview -------------------------------------------------- + inviter = "info@inference.coop" # the admin path's inviter + seed_account(conn, "member@x.org", account_type="member", active=1) + seed_account(conn, "guest@x.org", account_type="guest", active=1) + seed_account(conn, "ended@x.org", account_type="guest", active=0) + seed_guest_ledger(conn, inviter, "guest@x.org") + seed_guest_ledger(conn, inviter, "ended@x.org", status="expired") + conn.commit() + conn.close() + + async def overview(): + return await m.admin_overview(make_request( + "GET", headers={"X-Admin-Token": "test-admin-token"})) + + data = asyncio.run(overview()) + g = [x for x in data["guests"] if x["email"] == "guest@x.org"][0] + check("overview: fresh guest listed under guests[], never members[]", + len(data["guests"]) == 2 and not any(x["email"] == "guest@x.org" for x in data["members"]), + str([x["email"] for x in data["guests"]])) + check("overview: un-accepted guest reads state='invited'", + g["state"] == "invited", str(g.get("state"))) + check("overview: invited reason is the awaiting-setup line", + str(g.get("state_reason", "")).startswith("awaiting setup"), + str(g.get("state_reason"))) + check("overview: ledger status still the record of record", + g.get("guest_status") == "active", str(g.get("guest_status"))) + check("overview: activated flag agrees (pending)", + g.get("activated") is False, str(g.get("activated"))) + ended = [x for x in data["guests"] if x["email"] == "ended@x.org"][0] + check("overview: an inactive guest still reads inactive (not invited)", + ended["state"] == "inactive", str(ended.get("state"))) + + # --- 3. simulated acceptance: the flip to active --------------------------- + CLOUDRON_USERS["uid-guest@x.org"]["inviteAccepted"] = True + data = asyncio.run(overview()) + g = [x for x in data["guests"] if x["email"] == "guest@x.org"][0] + check("overview: after acceptance the guest reads state='active'", + g["state"] == "active", str(g.get("state"))) + check("overview: accepted guest carries no awaiting-setup reason", + g.get("state_reason", "") == "", str(g.get("state_reason"))) + check("overview: activated flag agrees (yes)", + g.get("activated") is True, str(g.get("activated"))) + + # ...and the username-only variant (the guest finished setup by name): + CLOUDRON_USERS["uid-guest@x.org"]["inviteAccepted"] = False + CLOUDRON_USERS["uid-guest@x.org"]["username"] = "theirname" + data = asyncio.run(overview()) + g = [x for x in data["guests"] if x["email"] == "guest@x.org"][0] + check("overview: a chosen username alone flips the guest to active", + g["state"] == "active", str(g.get("state"))) + CLOUDRON_USERS["uid-guest@x.org"]["username"] = None + + # --- 4. a failed Cloudron fetch never claims 'invited' --------------------- + m.cloudron_fetch_all_users = fetch_users_broken + data = asyncio.run(overview()) + g = [x for x in data["guests"] if x["email"] == "guest@x.org"][0] + check("overview: users fetch failed → fallback state, never 'invited'", + g["state"] == "active" and g["state_reason"] == "", + f"{g.get('state')} / {g.get('state_reason')!r}") + m.cloudron_fetch_all_users = fetch_users_ok + + # --- 5. an established member's row is untouched ---------------------------- + data = asyncio.run(overview()) # fresh payload from the working fetch + mem = [x for x in data["members"] if x["email"] == "member@x.org"][0] + check("overview: established member state unchanged ('active', no reason)", + mem["state"] == "active" and mem["state_reason"] == "", + f"{mem.get('state')} / {mem.get('state_reason')!r}") + check("overview: established member activated (not caught by the guest branch)", + mem.get("activated") is True, str(mem.get("activated"))) + + # --- 6. the member's trail carries the same derivation ---------------------- + m._verify_broker_secret = lambda request: "member@x.org" + conn = m.get_db() + seed_guest_ledger(conn, "member@x.org", "friend@x.org") + seed_account(conn, "friend@x.org", account_type="guest", active=1) + conn.commit() + conn.close() + CLOUDRON_USERS["uid-friend@x.org"] = {"inviteAccepted": False, "username": None} + + view = asyncio.run(m.broker_guest_list(make_request("GET"))) + trail_guests = [t for t in view["trail"] if t.get("kind") == "guest"] + check("trail: un-accepted guest carries state='invited'", + len(trail_guests) == 1 and trail_guests[0]["state"] == "invited", + str(view["trail"])) + check("trail: ledger status still 'active' underneath", + trail_guests and trail_guests[0]["status"] == "active", str(view["trail"])) + + CLOUDRON_USERS["uid-friend@x.org"]["inviteAccepted"] = True + view = asyncio.run(m.broker_guest_list(make_request("GET"))) + trail_guests = [t for t in view["trail"] if t.get("kind") == "guest"] + check("trail: after acceptance state follows the ledger status", + trail_guests and trail_guests[0]["state"] == "active", str(view["trail"])) + + conn = m.get_db() + conn.execute("UPDATE members SET active = 0 WHERE email = 'friend@x.org'") + conn.execute("UPDATE guests SET status = 'expired' WHERE recipient_email = 'friend@x.org'") + conn.commit() + conn.close() + view = asyncio.run(m.broker_guest_list(make_request("GET"))) + trail_guests = [t for t in view["trail"] if t.get("kind") == "guest"] + check("trail: an ended guest shows its ledger status, never 'invited'", + trail_guests and trail_guests[0]["state"] == "expired", str(view["trail"])) + + failed = [name for name, ok, _ in results if not ok] + print() + print(f"{len(results) - len(failed)}/{len(results)} checks passed") + if failed: + print("FAILED: " + ", ".join(failed)) + sys.exit(1) + + +if __name__ == "__main__": + main() diff --git a/tests/test_guest_requests.py b/tests/test_guest_requests.py index 99f7b52..1da9d81 100644 --- a/tests/test_guest_requests.py +++ b/tests/test_guest_requests.py @@ -77,7 +77,42 @@ class _NoNetwork: raise AssertionError("live network attempted during fixture test") -m.httpx.AsyncClient = _NoNetwork +# The trail now derives each guest's invited/active state from the Cloudron +# user record, so it opens an httpx client around a STUBBED users fetch: the +# client is constructible but every real HTTP attempt still raises — the +# guard, kept. +class _FakeClient(_NoNetwork): + def __init__(self, *a, **k): + pass + + async def __aenter__(self): + return self + + async def __aexit__(self, *a): + return False + + async def get(self, *a, **k): + raise AssertionError("live network attempted during fixture test") + + async def post(self, *a, **k): + raise AssertionError("live network attempted during fixture test") + + +m.httpx.AsyncClient = _FakeClient + +# Cloudron users fixture for the invited-state derivation: the fixture guest's +# Cloudron user id is 'uid-fixture' (fake_user_create below) with the invite +# NOT yet accepted. Tests flip `inviteAccepted` to simulate acceptance. +CLOUDRON_USERS = {"uid-fixture": {"inviteAccepted": False, "username": None}} + + +async def fake_fetch_users(client): + return [{"id": uid, "username": v.get("username"), + "inviteAccepted": v.get("inviteAccepted", False)} + for uid, v in CLOUDRON_USERS.items()] + + +m.cloudron_fetch_all_users = fake_fetch_users # --- recorders (same contract as test_guest_lifecycle) ---------------------- # calls = {"group": [], "budget": [], "email": [], "listmonk": [], "loomio": 0, @@ -266,6 +301,13 @@ def main(): check("trail: the new guest visible to the member as active", len(guests) == 1 and guests[0]["recipient"] == "friend@x.org" and guests[0]["status"] == "active", str(view["trail"])) + check("trail: un-accepted invite shows state='invited' (never reads active)", + guests and guests[0]["state"] == "invited", str(guests)) + CLOUDRON_USERS["uid-fixture"]["inviteAccepted"] = True # simulate acceptance + view = asyncio.run(m.broker_guest_list(make_request("GET"))) + guests = [t for t in view["trail"] if t.get("kind") == "guest"] + check("trail: after acceptance the state follows the ledger (active)", + guests and guests[0]["state"] == "active", str(guests)) check("trail: no pending entries in the member's trail", not any(t.get("status") == "pending" for t in view["trail"]), str(view["trail"]))