Files
member-portal/tests/test_guest_requests.py
T

435 lines
18 KiB
Python

#!/usr/bin/env python3
"""Member self-serve guest requests — structurally isolated from live services.
WHY THIS EXISTS
The member path creates REAL guest accounts ($2 of credits, Cloudron users,
invitation email) once approved, and the trial gate decides when. 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.
THE TRIAL GATE (default: requests wait for operator approval)
1. A member's request lands PENDING; nothing is provisioned, nothing is
emailed to the recipient, no network call is recorded.
2. The member's own trail shows the pending request.
PROTECTIONS (member path — every existing rule, plus the member-side ones)
3. A SECOND request by the same member while the first is pending is
refused (the rolling 30-day window counts pending requests too).
4. A recipient who is an EXISTING MEMBER is refused.
5. A recipient with a PRIOR guest (ledger row) is refused.
6. A recipient who ALREADY HAS A PENDING REQUEST (from another inviter)
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.
APPROVAL (the panel action)
9. Approve fires the FULL guest pipeline: row marked account_type='guest',
$2 credit, ledger row inviter → recipient, the invitation email (the
INVITING member named in it), newsletter subscribe — and the request
row becomes 'approved'.
10. Approving a request whose guard now refuses (state moved) records the
refusal on the request (status 'rejected') and raises it — no silent
drop.
11. A decided request cannot be approved or rejected twice (409).
REJECTION
12. Reject marks the request 'rejected' with the operator's note; the
member's trail carries it; NOTHING was sent to the recipient (no
network call recorded).
13. A rejected request does not count against the inviter's window (a new
request may be sent), but a rejected RECIPIENT is still protected by
the ledger/row rules once a guest actually exists.
AUTO-APPROVE (GUEST_AUTO_APPROVE=1)
14. With the flag on, a member's request provisions immediately through
the same pipeline — no pending row.
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"]
# The trial gate is read from the environment at import; the tests drive it
# directly (it is a module-level bool, the same value the endpoints read).
m.GUEST_AUTO_APPROVE = False
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. the trial gate: a member's request waits PENDING ----------------
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("request: 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("request: status is pending_approval",
outcome.get("status") == "pending_approval", str(outcome))
conn = m.get_db()
rows = conn.execute(
"SELECT id, inviter_email, recipient_email, status FROM guest_requests"
).fetchall()
check("request: one pending row recorded",
len(rows) == 1 and rows[0][3] == "pending", str(rows))
conn.close()
check("request: NOTHING provisioned (no cloudron user)", not calls["group"])
check("request: NOTHING emailed to the recipient", not calls["email"])
check("request: no newsletter subscription", not calls["listmonk"])
# --- 2. the member's own trail shows the pending request ----------------
m._verify_broker_secret = lambda request: inviter
view = asyncio.run(m.broker_guest_list(make_request("GET")))
check("trail: pending request visible to the member",
len(view["trail"]) == 1 and view["trail"][0]["status"] == "pending",
str(view["trail"]))
check("trail: member is not eligible while a request is pending",
view["eligible"] is False, str(view["eligible"]))
check("trail: next_eligible_at given", bool(view["next_eligible_at"]),
str(view["next_eligible_at"]))
# --- 3. second request while pending: refused (window counts requests) --
conn = m.get_db()
refusal = m.guest_request_guard(conn, inviter, "friend2@x.org")
check("limit: second request while one is pending 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 request",
refusal is None, str(refusal))
conn.close()
# --- 4-7. recipient-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.execute(
"INSERT INTO guest_requests (inviter_email, recipient_email, status) "
"VALUES ('member-two@x.org', 'waitlisted@x.org', 'pending')")
conn.commit()
seed_member(conn, "member-three@x.org", active=1)
conn.commit()
refusal = m.guest_request_guard(conn, "member-three@x.org", "waitlisted@x.org")
check("refusal: recipient with a pending request (any inviter)",
refusal is not None and "waiting" in refusal, 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. approval fires the FULL pipeline ---------------------------------
reset()
req_id = rows[0][0]
approved = asyncio.run(m.admin_guest_request_approve(
req_id, make_request("POST", headers={"X-Admin-Token": "test-admin-token"})))
check("approve: status approved", approved.get("status") == "approved",
str(approved))
conn = m.get_db()
acct = conn.execute(
"SELECT account_type, balance, credit_balance FROM members WHERE email = ?",
("friend@x.org",)).fetchone()
check("approve: recipient row marked guest", acct and acct[0] == "guest", str(acct))
check("approve: $2 non-expiring credit", acct and acct[2] == 2.0, str(acct))
ledger = conn.execute(
"SELECT inviter_email, recipient_email, status FROM guests WHERE recipient_email = 'friend@x.org'"
).fetchall()
check("approve: ledger row inviter → recipient",
ledger and ledger[0][0] == inviter and ledger[0][2] == "active", str(ledger))
reqs = conn.execute(
"SELECT status FROM guest_requests WHERE id = ?", (req_id,)).fetchone()
check("approve: request row marked approved", reqs and reqs[0] == "approved", str(reqs))
conn.close()
check("approve: invitation email sent to the recipient",
len(calls["email"]) == 1 and calls["email"][0][0] == "friend@x.org",
str(calls["email"]))
check("approve: invitation email NAMES the inviting member",
"member-one" in calls["email"][0][2], str(calls["email"]))
check("approve: newsletter subscribe fired", calls["listmonk"] == [("friend@x.org", True)],
str(calls["listmonk"]))
check("approve: NO Loomio/Matrix invites", not calls["loomio"] and not calls["matrix"])
# the email body names the inviter (the contract the member was promised)
conn = m.get_db()
conn.close()
# --- 10. approve on moved state records the refusal ----------------------
# Recipient signed up (a portal row appeared) after the request was made.
reset()
conn = m.get_db()
conn.execute(
"INSERT INTO guest_requests (inviter_email, recipient_email, status) "
"VALUES (?, 'existing@x.org', 'pending')", (inviter,))
conn.commit()
rid2 = conn.execute(
"SELECT id FROM guest_requests WHERE recipient_email = 'existing@x.org'"
).fetchone()[0]
conn.close()
try:
await_err = None
try:
asyncio.run(m.admin_guest_request_approve(rid2, make_request("POST", headers={"X-Admin-Token": "test-admin-token"})))
except Exception as e:
await_err = e
check("approve-on-moved-state: raises the refusal",
await_err is not None, "no exception raised")
conn = m.get_db()
st, note = conn.execute(
"SELECT status, note FROM guest_requests WHERE id = ?", (rid2,)
).fetchone()
check("approve-on-moved-state: request records the refusal",
st == "rejected" and note, f"{st} {note}")
conn.close()
finally:
pass
# --- 11. a decided request cannot be decided twice -----------------------
try:
asyncio.run(m.admin_guest_request_approve(req_id, make_request("POST", headers={"X-Admin-Token": "test-admin-token"})))
check("decided-twice: re-approve refused", False, "no exception")
except Exception as e:
code = getattr(e, "status_code", None)
check("decided-twice: re-approve refused (409)", code == 409, str(e))
# --- 12. rejection -------------------------------------------------------
reset()
conn = m.get_db()
conn.execute(
"INSERT INTO guest_requests (inviter_email, recipient_email, status) "
"VALUES (?, 'rejected-target@x.org', 'pending')", (inviter,))
conn.commit()
rid3 = conn.execute(
"SELECT id FROM guest_requests WHERE recipient_email = 'rejected-target@x.org'"
).fetchone()[0]
conn.close()
rejected = asyncio.run(m.admin_guest_request_reject(
rid3, make_request("POST", {"note": "not right now"},
headers={"X-Admin-Token": "test-admin-token"})))
check("reject: status rejected", rejected.get("status") == "rejected", str(rejected))
conn = m.get_db()
st, note = conn.execute(
"SELECT status, note FROM guest_requests WHERE id = ?", (rid3,)).fetchone()
check("reject: note recorded", st == "rejected" and note == "not right now",
f"{st} {note}")
conn.close()
check("reject: NOTHING sent to the recipient", not calls["email"] and not calls["group"])
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("recipient") == "rejected-target@x.org"]
check("reject: the member's trail carries 'rejected'",
rej and rej[0]["status"] == "rejected", str(rej))
# --- 13. a rejected request does not count against the window ------------
conn = m.get_db()
refusal = m.guest_request_guard(conn, "member-three@x.org", "fresh-after-reject@x.org")
check("reject: new request allowed after a rejection",
refusal is None, str(refusal))
conn.close()
# --- 14. GUEST_AUTO_APPROVE provisions immediately ------------------------
reset()
m.GUEST_AUTO_APPROVE = True
outcome = asyncio.run(post_guest("member-three@x.org", "instant@x.org", "Instant"))
check("auto-approve: provisions immediately",
outcome.get("status") == "provisioned", str(outcome))
check("auto-approve: full pipeline fired (email + listmonk + user)",
calls["email"] and calls["listmonk"] and calls["group"], str(calls))
conn = m.get_db()
pend = conn.execute(
"SELECT COUNT(*) FROM guest_requests WHERE recipient_email = 'instant@x.org'"
).fetchone()[0]
acct = conn.execute(
"SELECT account_type FROM members WHERE email = 'instant@x.org'"
).fetchone()
check("auto-approve: no pending row", pend == 0, str(pend))
check("auto-approve: recipient provisioned as guest",
acct and acct[0] == "guest", str(acct))
conn.close()
m.GUEST_AUTO_APPROVE = False
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())