Guest state: provisioned-but-not-set-up reads 'invited', never 'active'
A guest invitation provisions immediately, but the Cloudron account is not ACCEPTED until the guest clicks the setup link (inviteAccepted=false, no username) — until then they cannot log in, so no surface may read them as active. guest_invite_pending() derives it from the same Cloudron signal the overview's activated flag uses; unseen-record (users fetch failed) is never pending, so the state falls back instead of asserting what the data does not show. /admin/overview: guest rows report state='invited' with an 'awaiting setup' reason (invite date named when the ledger has it); /broker/guests trail entries carry state='invited' the same way, status stays the ledger record of record. Display/state semantics only — access rules, the $2 cap and the expiry box are unchanged. Tests: new test_guest_invited_state.py (derivation, overview flip, fetch-failure fallback, member rows untouched, trail state); test_guest_requests.py gains the trail invited/accepted assertions and a constructible-but-loud fake client so the stubbed users fetch runs.
This commit is contained in:
1 parent
f592e5b7b5
commit
88ca8bfe18
3 files changed
+414
-10
No files matched your search
@@ -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=<ledger status> 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()
|
||||
@@ -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"]))
|
||||
|
||||
Reference in new issue
Block a user