Files
member-portal/tests/test_guest_requests.py
T
inference-bot 285aa66525 Guest invites provision immediately: remove the member approval gate
Operator decision 2026-11-08: the remaining protections (active member,
1 guest per inviter per rolling 30 days, one guest per recipient ever,
no existing portal row, MANUAL_MEMBERS refusal, the $2 cap and the
GUEST_DAYS box) are sufficient without the approval step.

* POST /broker/guests provisions through provision_guest_member at once —
  no pending state; no guest_requests row is ever written.
* GUEST_AUTO_APPROVE flag removed (the live env never carried it).
* guest_request_guard keeps the member-path rules and drops the
  trial-era pending-request checks; the 30-day window is counted from
  the guests ledger.
* GET /admin/guest-requests + approve/reject removed; GET /admin/guest-ledger
  serves the panel's duplicate-send guard.
* The member trail keeps legacy rejected requests as history only.

Built on the sibling $2-cap commit 6be8e2d.
2026-11-08 20:20:30 +00:00

391 lines
17 KiB
Python

#!/usr/bin/env python3
"""Member self-serve guest invitations — structurally isolated from live services.
WHY THIS EXISTS
The member path creates REAL guest accounts ($2 of credits, Cloudron users,
invitation email) IMMEDIATELY on a valid request (operator decision,
2026-11-08: the trial-era approval gate is gone — nothing waits, nothing is
pending). Every path proven here runs against a FIXTURE database with the
network layer REPLACED BY A RAISING GUARD: any code path that tries to reach
Cloudron, LiteLLM, OC, Listmonk, Loomio, Matrix or SMTP outside the stubs
fails the test loudly instead of acting on live systems.
IMMEDIATE PROVISIONING (POST /broker/guests, member broker identity)
1. A valid member invitation provisions at once through the FULL guest
pipeline: row marked account_type='guest', the $2 non-expiring credit,
the LiteLLM cap at $2, guest_expires_at set (the 60-day box), a guests
ledger row inviter → recipient, the invitation email (the INVITING
member named in it), and the newsletter subscription.
2. NO guest_requests row is written — no pending state exists anywhere.
3. The member's own trail shows the new guest (active) and the rolling
window flips them ineligible with next_eligible_at.
PROTECTIONS (member path — every rule still enforced)
4. A SECOND invitation by the same member inside the rolling 30-day
window is refused (one guest per member per month — the window is
counted from the guests ledger).
5. A recipient who is an EXISTING MEMBER is refused.
6. A recipient with a PRIOR guest (ledger row) is refused.
7. A recipient on MANUAL_MEMBERS is refused.
8. A non-member (no portal row) and a GUEST account are refused — only
members invite guests.
9. Re-inviting an address that was just provisioned is refused (one guest
per recipient ever — the moved-state guard behind the endpoint).
10. The GATE IS GONE: the app defines no guest-request approve/reject
routes and no GUEST_AUTO_APPROVE flag — nothing to approve anywhere.
LEGACY HISTORY
11. A rejected request from the trial period still shows in the member's
trail (history only); a rejected request blocks nothing.
PANEL LEDGER FEED
12. GET /admin/guest-ledger serves the guests ledger (the panel's
duplicate-send guard reads it).
Runnable: python3 tests/test_guest_requests.py (from the repo root)
"""
import asyncio
import base64
import os
import sys
import tempfile
from datetime import datetime, timedelta, timezone
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 ""))
class _NoNetwork:
"""Guard: ANY httpx client construction inside the test is a failure."""
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 = _NoNetwork
# --- recorders (same contract as test_guest_lifecycle) ---------------------- #
calls = {"group": [], "budget": [], "email": [], "listmonk": [], "loomio": 0,
"matrix": 0}
async def rec_group(user_id, group_id=None):
calls["group"].append((user_id, group_id or m.MEMBERS_GROUP_ID))
def rec_email(to, subject, text_body=None, html_body=None):
calls["email"].append((to, subject, text_body or ""))
return True
async def rec_listmonk(email, subscribe):
calls["listmonk"].append((email, bool(subscribe)))
async def rec_loomio():
calls["loomio"] += 1
async def rec_matrix():
calls["matrix"] += 1
async def fake_team_id(email):
return "team-" + email
async def fake_get_or_create_team(email, budget, budget_duration="30d"):
return "team-fixture"
async def fake_create_key(email, budget, team_id):
return "***"
async def fake_user_create(email, name):
return "uid-fixture"
async def fake_invite_link(user_id):
return "https://my.example/setupaccount.html?inviteToken=x"
async def fake_activated(user_id):
return False
def fake_team_db(team_id):
return {"max_budget": None, "spend": 0.0, "budget_reset_at": None}
m.cloudron_set_group = rec_group
m.cloudron_set_active = rec_group
m.cloudron_create_user = fake_user_create
m.cloudron_get_invite_link = fake_invite_link
m.cloudron_is_activated = fake_activated
m.litellm_get_or_create_team = fake_get_or_create_team
m.litellm_create_key = fake_create_key
m.litellm_team_id_for_email = fake_team_id
m.litellm_update_team_budget = async_rec_budget = (lambda *a: None) # replaced below
m.get_team_budget_from_db = fake_team_db
m.send_email = rec_email
m.listmonk_sync = rec_listmonk
m.sync_loomio_memberships = rec_loomio
m.sync_matrix_space = rec_matrix
async def rec_budget(team_id, budget):
calls["budget"].append((team_id, round(float(budget), 2)))
m.litellm_update_team_budget = rec_budget
# --- 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_member(conn, email, account_type="member", active=1):
conn.execute(
"INSERT INTO members (email, key_token, cloudron_user_id, slug, active, "
"balance, credit_balance, account_type) "
"VALUES (?, 'enc', 'uid-' || ?, '', ?, ?, 0, ?)",
(email, email, active, m.MEMBER_BUDGET, account_type),
)
def main():
m.get_db().close() # create + migrate the fixture schema
conn = m.get_db()
m._ensure_allowance_tables(conn)
inviter = "member-one@x.org"
seed_member(conn, inviter, active=1)
conn.execute("UPDATE members SET slug = 'member-one' WHERE email = ?", (inviter,))
conn.commit()
conn.close()
# --- 1-3. a valid invitation PROVISIONS IMMEDIATELY ----------------------
reset = lambda: calls.update({"group": [], "budget": [], "email": [],
"listmonk": [], "loomio": 0, "matrix": 0})
reset()
conn = m.get_db()
refusal = m.guest_request_guard(conn, inviter, "friend@x.org")
check("guard: passes for an active member + fresh recipient",
refusal is None, str(refusal))
conn.close()
async def post_guest(email_addr, recipient, name=""):
"""Drive the POST /broker/guests handler directly (auth is stubbed)."""
m._verify_broker_secret = lambda request: email_addr
return await m.broker_guest_invite(
make_request("POST", {"email": recipient, "name": name}))
outcome = asyncio.run(post_guest(inviter, "friend@x.org", "Friend"))
check("invite: status is provisioned (immediate, nothing pending)",
outcome.get("status") == "provisioned", str(outcome))
check("invite: no pending_approval status anywhere in the response",
"pending" not in str(outcome).lower(), str(outcome))
check("invite: response carries the cap and the box",
outcome.get("budget") == m.GUEST_BUDGET
and outcome.get("expires_in_days") == int(m.GUEST_DAYS), str(outcome))
conn = m.get_db()
acct = conn.execute(
"SELECT account_type, balance, credit_balance, guest_expires_at "
"FROM members WHERE email = ?", ("friend@x.org",)).fetchone()
check("invite: recipient row marked guest",
acct and acct[0] == "guest", str(acct))
check("invite: allowance balance 0 (the $2 is all credit)",
acct and acct[1] == 0.0, str(acct))
check("invite: $2 non-expiring credit granted",
acct and acct[2] == m.GUEST_BUDGET, str(acct))
check("invite: 60-day box set (guest_expires_at)",
acct and bool(acct[3]), str(acct))
if acct and acct[3]:
exp = datetime.strptime(str(acct[3])[:19], "%Y-%m-%d %H:%M:%S")
delta = exp - datetime.now(timezone.utc).replace(tzinfo=None)
check("invite: expiry sits ~GUEST_DAYS out",
timedelta(0) < delta <= timedelta(days=int(m.GUEST_DAYS)),
str(acct[3]))
ledger = conn.execute(
"SELECT inviter_email, recipient_email, status FROM guests "
"WHERE recipient_email = 'friend@x.org'").fetchall()
check("invite: ledger row inviter → recipient (active)",
ledger and ledger[0][0] == inviter and ledger[0][2] == "active", str(ledger))
reqs = conn.execute("SELECT COUNT(*) FROM guest_requests").fetchone()[0]
check("invite: NO guest_requests row written (no pending state exists)",
reqs == 0, str(reqs))
conn.close()
check("invite: LiteLLM cap set to the guest budget (one-time)",
calls["budget"] == [("team-fixture", round(m.GUEST_BUDGET, 2))],
str(calls["budget"]))
check("invite: Cloudron user created into the guests group",
calls["group"] and calls["group"][0][1] == m.GUESTS_GROUP_ID, str(calls["group"]))
check("invite: invitation email sent to the recipient AT ONCE",
len(calls["email"]) == 1 and calls["email"][0][0] == "friend@x.org",
str(calls["email"]))
check("invite: invitation email NAMES the inviting member",
"member-one" in calls["email"][0][2], str(calls["email"]))
check("invite: newsletter subscribe fired",
calls["listmonk"] == [("friend@x.org", True)], str(calls["listmonk"]))
check("invite: NO Loomio/Matrix invites", not calls["loomio"] and not calls["matrix"])
# --- 3. the member's own trail shows the guest + the closed window -------
m._verify_broker_secret = lambda request: inviter
view = asyncio.run(m.broker_guest_list(make_request("GET")))
guests = [t for t in view["trail"] if t.get("kind") == "guest"]
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: no pending entries in the member's trail",
not any(t.get("status") == "pending" for t in view["trail"]),
str(view["trail"]))
check("trail: member is not eligible inside the 30-day window",
view["eligible"] is False, str(view["eligible"]))
check("trail: next_eligible_at given", bool(view["next_eligible_at"]),
str(view["next_eligible_at"]))
# --- 4. second invitation inside the window: refused (1/month) -----------
conn = m.get_db()
refusal = m.guest_request_guard(conn, inviter, "friend2@x.org")
check("limit: second guest within 30 days refused",
refusal is not None and "30 days" in refusal, str(refusal))
# another member may still invite a DIFFERENT recipient
seed_member(conn, "member-two@x.org", active=1)
conn.commit()
refusal = m.guest_request_guard(conn, "member-two@x.org", "other@x.org")
check("limit: a DIFFERENT member is not blocked by someone else's guest",
refusal is None, str(refusal))
conn.close()
# --- 5-8. recipient-side + inviter-side refusal paths ---------------------
conn = m.get_db()
seed_member(conn, "existing@x.org", account_type="member", active=1)
conn.commit()
refusal = m.guest_request_guard(conn, "member-two@x.org", "existing@x.org")
check("refusal: existing member as recipient", refusal is not None, str(refusal))
conn.execute(
"INSERT INTO guests (inviter_email, recipient_email, created_at, status) "
"VALUES ('member-two@x.org', 'prior@x.org', datetime('now'), 'active')")
conn.commit()
refusal = m.guest_request_guard(conn, "member-two@x.org", "prior@x.org")
check("refusal: prior guest (ledger) as recipient", refusal is not None, str(refusal))
conn.close()
old_manual = set(m.MANUAL_MEMBERS)
m.MANUAL_MEMBERS = {"manual@x.org"}
conn = m.get_db()
refusal = m.guest_request_guard(conn, "member-two@x.org", "manual@x.org")
check("refusal: recipient on MANUAL_MEMBERS", refusal is not None, str(refusal))
conn.close()
m.MANUAL_MEMBERS = old_manual
# --- 8. only members reach the member path -------------------------------
conn = m.get_db()
# a non-member: no portal row at all → guest_provision_guard refuses
refusal = m.guest_request_guard(conn, "stranger@x.org", "someone@x.org")
check("refusal: non-member inviter", refusal is not None, str(refusal))
seed_member(conn, "guest-acct@x.org", account_type="guest", active=1)
conn.commit()
refusal = m.guest_request_guard(conn, "guest-acct@x.org", "someone@x.org")
check("refusal: a GUEST cannot invite guests", refusal is not None, str(refusal))
conn.close()
# --- 9. re-inviting a just-provisioned address is refused (moved state) --
reset()
conn = m.get_db()
seed_member(conn, "member-three@x.org", active=1)
conn.commit()
conn.close()
try:
asyncio.run(post_guest("member-three@x.org", "friend@x.org"))
check("moved-state: duplicate invite refused", False, "no exception raised")
except Exception as e:
code = getattr(e, "status_code", None)
check("moved-state: duplicate invite refused (429)",
code == 429 and "already received a guest account" in str(getattr(e, "detail", e)),
str(e))
conn = m.get_db()
reqs = conn.execute("SELECT COUNT(*) FROM guest_requests").fetchone()[0]
check("moved-state: still NO pending state written", reqs == 0, str(reqs))
conn.close()
# --- 10. the gate is GONE from the app -----------------------------------
paths = {getattr(r, "path", "") for r in m.app.routes}
gone = [p for p in paths if "guest-requests" in p]
check("gate gone: no guest-request routes remain on the app",
not gone, str(sorted(gone)))
check("gate gone: GUEST_AUTO_APPROVE no longer exists",
not hasattr(m, "GUEST_AUTO_APPROVE"), str(getattr(m, "GUEST_AUTO_APPROVE", None)))
# --- 11. legacy rejected history shows in the trail; blocks nothing ------
conn = m.get_db()
conn.execute(
"INSERT INTO guest_requests (inviter_email, recipient_email, status, decided_at, note) "
"VALUES (?, 'rejected-back-then@x.org', 'rejected', datetime('now'), 'not right now')",
(inviter,))
conn.commit()
conn.close()
m._verify_broker_secret = lambda request: inviter
view = asyncio.run(m.broker_guest_list(make_request("GET")))
rej = [t for t in view["trail"] if t.get("kind") == "request"
and t.get("recipient") == "rejected-back-then@x.org"]
check("legacy: a rejected request still shows in the trail (history)",
len(rej) == 1 and rej[0]["status"] == "rejected", str(view["trail"]))
check("legacy: no pending entries ever appear in the trail",
not any(t.get("status") == "pending" for t in view["trail"]),
str(view["trail"]))
conn = m.get_db()
# (member-three is already seeded and active with a fresh recipient; the
# point is a legacy rejection blocks nothing)
refusal = m.guest_request_guard(conn, "member-three@x.org", "fresh@x.org")
check("legacy: a legacy rejection does not count against anyone's window",
refusal is None, str(refusal))
conn.close()
# --- 12. the panel's ledger feed -----------------------------------------
fed = asyncio.run(m.admin_guest_ledger(
make_request("GET", headers={"X-Admin-Token": "test-admin-token"})))
recips = [r["recipient"] for r in fed.get("ledger", [])]
check("ledger feed: serves the guests ledger for the panel's guard",
"friend@x.org" in recips and "prior@x.org" in recips, str(fed))
check("ledger feed: no pending key in the payload",
"pending" not in fed and "decided" not in fed, str(sorted(fed.keys())))
print()
passed = sum(1 for _, ok, _ in results if ok)
print(f"{passed}/{len(results)} checks passed")
return 0 if passed == len(results) else 1
if __name__ == "__main__":
sys.exit(main())