Member self-serve guest invitations with a trial approval gate

POST /broker/guests (member broker identity — guests cannot reach it) creates
a guest REQUEST; GET /broker/guests returns the member's invitation allowance
(rolling one-per-30-days, counting pending + approved requests) and their own
guest trail. guest_request_guard enforces every existing protection plus the
member-side ones: recipient never an existing member, a prior guest, a pending
request, or a MANUAL_MEMBERS address; the inviter's window counts requests too.

Trial gate (GUEST_AUTO_APPROVE, default off): requests land PENDING in the new
guest_requests table; the operator approves or rejects them via
GET/POST /admin/guest-requests (X-Admin-Token). Approval fires the full
provision_guest_member pipeline (Cloudron user, $5 credit, GUEST_DAYS box,
invitation email naming the inviter, newsletter, ledger row); a guard refusal
at approve-time is recorded on the request and surfaced. The member sees
pending/not-approved status in their own trail — the recipient is contacted
only on approval. With the flag on, a member's request provisions
immediately, no code change needed.

38-check fixture suite (tests/test_guest_requests.py) proves the gate, every
refusal path, the approve/reject actions and auto-approve with the network
replaced by a raising guard.
This commit is contained in:
inference-bot committed 2026-11-08 02:42:56 +00:00
1 parent 93184b6011
commit 0293d66c1e
2 files changed
+781 -1

No files matched your search

+347 -1
View File
@@ -351,6 +351,13 @@ GUEST_BUDGET = float(os.environ.get("GUEST_BUDGET", "5.0"))
GUEST_DAYS = float(os.environ.get("GUEST_DAYS", "60"))
# One guest per inviting member per rolling 30 days (abuse protection).
GUEST_PER_INVITER_DAYS = float(os.environ.get("GUEST_PER_INVITER_DAYS", "30"))
# Trial-period approval gate for MEMBER-initiated guest invitations. Off (the
# default): a member's request waits in PENDING until the operator approves or
# rejects it in the panel. On: a member's request provisions immediately,
# through the same pipeline and guards. Flipping it later is an env change,
# not a code change.
GUEST_AUTO_APPROVE = os.environ.get("GUEST_AUTO_APPROVE", "").strip().lower() in (
"1", "true", "yes", "on")
# The Cloudron "guests" group: guest accounts land here. The chat and dashboard
# apps' access restrictions list BOTH members and guests, so a guest reaches
@@ -977,6 +984,22 @@ def get_db() -> sqlite3.Connection:
"guest_expires_at TEXT, "
"status TEXT DEFAULT 'active')"
)
# Guest REQUESTS — the member self-serve path's trial gate. A member's
# invitation lands here first; the operator approves (which fires the
# full guest pipeline and writes the ledger row above) or rejects it.
# PENDING requests are part of the abuse rules: they block the recipient
# address and count against the inviter's rolling window.
conn.execute(
"CREATE TABLE IF NOT EXISTS guest_requests ("
"id INTEGER PRIMARY KEY AUTOINCREMENT, "
"inviter_email TEXT NOT NULL, "
"recipient_email TEXT NOT NULL, "
"recipient_name TEXT, "
"created_at TEXT DEFAULT (datetime('now')), "
"decided_at TEXT, "
"status TEXT DEFAULT 'pending', "
"note TEXT)"
)
# Credit ledger: audit trail for every credit movement (purchases via the
# OC webhook, admin adjustments, spends drawn against credits). Money needs
# an audit trail.
@@ -1149,11 +1172,56 @@ def guest_provision_guard(conn, inviter_email: str, recipient_email: str) -> str
).fetchone()
if existing:
acct = existing[0] or "member"
return (f"{recipient} already has a portal row ({acct}) — guests are for "
return (f"{recipient} already has a portal row ({acct}) — guest access is for "
"new addresses; existing members and past guest accounts are refused")
return None
def guest_request_guard(conn, inviter_email: str, recipient_email: str) -> str | None:
"""Decide whether a MEMBER may send a guest invitation (pure).
Everything the guest pipeline enforces (guest_provision_guard: active
member inviter, one guest per inviter per rolling window, one guest per
recipient ever, no existing portal row) plus the member-path rules:
* the recipient is not on MANUAL_MEMBERS — manually-provisioned
accounts are co-op insiders, never guest targets;
* the recipient has no PENDING request already (from any inviter);
* the inviter's rolling GUEST_PER_INVITER_DAYS window counts REQUESTS
too — a pending or approved request sits inside the window, so the
one-per-30-days limit cannot be outrun by requesting twice while the
first is still waiting.
A REJECTED request counts as neither: nothing was ever sent, and the
operator's gate still sits in front of every actual send.
Returns None when the request may proceed, else a human-readable refusal.
"""
refusal = guest_provision_guard(conn, inviter_email, recipient_email)
if refusal:
return refusal
inviter = (inviter_email or "").strip().lower()
recipient = (recipient_email or "").strip().lower()
if recipient in MANUAL_MEMBERS:
return ("That address belongs to a manually-provisioned co-op account — "
"guest invitations are for people outside the co-op")
pending = conn.execute(
"SELECT COUNT(*) FROM guest_requests WHERE recipient_email = ? AND status = 'pending'",
(recipient,),
).fetchone()[0]
if pending:
return f"{recipient} already has a guest request waiting for approval"
recent = conn.execute(
"SELECT COUNT(*) FROM guest_requests WHERE inviter_email = ? "
"AND status IN ('pending', 'approved') "
"AND created_at >= datetime('now', ?)",
(inviter, f"-{int(GUEST_PER_INVITER_DAYS)} days"),
).fetchone()[0]
if recent:
return (f"You already sent a guest request in the last "
f"{int(GUEST_PER_INVITER_DAYS)} days — one guest per member per month")
return None
def add_credits(email: str, delta: float, reason: str, reference: str | None = None) -> float:
"""Adjust a member's credit balance and record the movement in the ledger.
@@ -4202,6 +4270,141 @@ async def admin_gift_convert_alias(request: Request):
return await admin_guest_convert(request)
# ---------------------------------------------------------------------------
# Guest-request approval (the member self-serve trial gate).
# ---------------------------------------------------------------------------
def _request_row(row) -> dict:
return {
"id": row[0], "inviter": row[1], "recipient": row[2],
"name": row[3], "created_at": row[4], "decided_at": row[5],
"status": row[6], "note": row[7],
}
@app.get("/admin/guest-requests")
@limiter.limit("60/minute")
async def admin_guest_requests(request: Request):
"""The member guest-request queue and the guests ledger, for the panel.
Authenticated by the X-Admin-Token header. Returns the PENDING requests
awaiting the operator's decision (oldest first), the recently DECIDED
ones (approved/rejected, newest first), and the guests ledger itself —
one view where pending vs approved (and every later state) is visible.
"""
_verify_admin_token(request)
conn = get_db()
pending = conn.execute(
"SELECT id, inviter_email, recipient_email, recipient_name, created_at, "
"decided_at, status, note FROM guest_requests WHERE status = 'pending' ORDER BY id"
).fetchall()
decided = conn.execute(
"SELECT id, inviter_email, recipient_email, recipient_name, created_at, "
"decided_at, status, note FROM guest_requests WHERE status != 'pending' "
"ORDER BY id DESC LIMIT 100"
).fetchall()
ledger = conn.execute(
"SELECT id, inviter_email, recipient_email, created_at, status "
"FROM guests ORDER BY id DESC LIMIT 100"
).fetchall()
conn.close()
return {
"pending": [_request_row(r) for r in pending],
"decided": [_request_row(r) for r in decided],
"ledger": [
{"id": i, "inviter": inv, "recipient": rec, "created_at": created,
"status": status}
for i, inv, rec, created, status in ledger
],
}
@app.post("/admin/guest-requests/{request_id}/approve")
@limiter.limit("20/minute")
async def admin_guest_request_approve(request_id: int, request: Request):
"""Approve a pending guest request — the trial gate's approval action.
Approval fires the FULL guest pipeline (provision_guest_member: Cloudron
user, $5 credit, GUEST_DAYS box, invitation email naming the inviter,
newsletter subscribe, ledger row) — the same path the operator's
/admin/provision-guest runs, so every guard re-runs. If state moved since
the request (the recipient signed up; another invitation landed), the
refusal is recorded on the request and surfaced — the queue never
silently drops a decision.
"""
_verify_admin_token(request)
conn = get_db()
row = conn.execute(
"SELECT id, inviter_email, recipient_email, recipient_name, status "
"FROM guest_requests WHERE id = ?", (request_id,)
).fetchone()
conn.close()
if not row:
raise HTTPException(404, f"No guest request #{request_id}")
_, inviter, recipient, name, status = row
if status != "pending":
raise HTTPException(409, f"Request #{request_id} is already {status}")
try:
user_id = await provision_guest_member(
recipient, name or recipient.split("@")[0], inviter)
except HTTPException as e:
conn = get_db()
conn.execute(
"UPDATE guest_requests SET status = 'rejected', "
"decided_at = datetime('now'), note = ? WHERE id = ?",
(str(e.detail), request_id),
)
conn.commit()
conn.close()
raise HTTPException(e.status_code, e.detail)
conn = get_db()
conn.execute(
"UPDATE guest_requests SET status = 'approved', "
"decided_at = datetime('now') WHERE id = ?", (request_id,)
)
conn.commit()
conn.close()
logger.info("Guest request #%s approved: %s invited %s (provisioned)",
request_id, inviter, recipient)
return {
"status": "approved", "request_id": request_id, "recipient": recipient,
"inviter": inviter, "user_id": user_id,
"budget": GUEST_BUDGET, "expires_in_days": int(GUEST_DAYS),
}
@app.post("/admin/guest-requests/{request_id}/reject")
@limiter.limit("20/minute")
async def admin_guest_request_reject(request_id: int, request: Request):
"""Reject a pending guest request (the trial gate's rejection action).
Nothing was ever sent to the recipient — no account, no email — so the
rejection tells only the INVITING member, through their own guest trail
(status 'not approved'). An optional note records why.
"""
_verify_admin_token(request)
body = await request.json() if request.headers.get("content-length", "0") not in ("", "0") else {}
note = (body.get("note") or "").strip() or None
conn = get_db()
row = conn.execute(
"SELECT id, status FROM guest_requests WHERE id = ?", (request_id,)
).fetchone()
if not row:
conn.close()
raise HTTPException(404, f"No guest request #{request_id}")
if row[1] != "pending":
conn.close()
raise HTTPException(409, f"Request #{request_id} is already {row[1]}")
conn.execute(
"UPDATE guest_requests SET status = 'rejected', "
"decided_at = datetime('now'), note = ? WHERE id = ?", (note, request_id)
)
conn.commit()
conn.close()
logger.info("Guest request #%s rejected", request_id)
return {"status": "rejected", "request_id": request_id, "note": note}
@app.post("/admin/org-link")
@limiter.limit("20/minute")
async def admin_org_link(request: Request):
@@ -5908,6 +6111,149 @@ async def broker_cancel_gift_alias(request: Request):
return await broker_cancel_guest(request)
# ---------------------------------------------------------------------------
# Member self-serve guest invitations (trial gate: operator approval).
# ---------------------------------------------------------------------------
@app.get("/broker/guests")
@limiter.limit("30/minute")
async def broker_guest_list(request: Request):
"""The caller's own guest-access view: invitation allowance + their trail.
Served through the member broker identity (a guest identity fails it —
only members invite guests). Returns:
* eligible / next_eligible_at — the rolling one-guest-per-member-per-
GUEST_PER_INVITER_DAYS rule, counting pending and approved REQUESTS
as well as sent guests (the same rule guest_request_guard enforces);
* trail — every invitation this member has made, newest first: pending
and rejected REQUESTS (an approved request IS its ledger row) plus
every row in the guests ledger with what became of it (active,
converted, expired, depleted, cancelled by recipient).
"""
email = _verify_broker_secret(request)
conn = get_db()
requests = conn.execute(
"SELECT id, recipient_email, recipient_name, created_at, decided_at, status, note "
"FROM guest_requests WHERE inviter_email = ? ORDER BY id DESC",
(email,),
).fetchall()
sent = conn.execute(
"SELECT recipient_email, created_at, status "
"FROM guests WHERE inviter_email = ? ORDER BY id DESC",
(email,),
).fetchall()
window = f"-{int(GUEST_PER_INVITER_DAYS)} days"
request_recent = conn.execute(
"SELECT MAX(created_at) FROM guest_requests WHERE inviter_email = ? "
"AND status IN ('pending', 'approved') AND created_at >= datetime('now', ?)",
(email, window),
).fetchone()[0]
ledger_recent = conn.execute(
"SELECT MAX(created_at) FROM guests WHERE inviter_email = ? "
"AND created_at >= datetime('now', ?)",
(email, window),
).fetchone()[0]
conn.close()
last_sent = max((t for t in (request_recent, ledger_recent) if t), default=None)
eligible = last_sent is None
next_eligible_at = None
if not eligible:
try:
anchor = datetime.strptime(str(last_sent)[:19], "%Y-%m-%d %H:%M:%S")
next_eligible_at = (anchor + timedelta(days=int(GUEST_PER_INVITER_DAYS))
).strftime("%Y-%m-%dT%H:%M:%SZ")
except ValueError:
pass
trail = []
for rid, recipient, rname, created, decided, status, note in requests:
if status in ("pending", "rejected"):
trail.append({
"kind": "request", "request_id": rid, "recipient": recipient,
"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})
trail.sort(key=lambda t: t.get("decided_at") or t["created_at"] or "", reverse=True)
return {
"eligible": eligible,
"per_inviter_days": int(GUEST_PER_INVITER_DAYS),
"next_eligible_at": next_eligible_at,
"auto_approve": bool(GUEST_AUTO_APPROVE),
"trail": trail,
}
@app.post("/broker/guests")
@limiter.limit("10/minute")
async def broker_guest_invite(request: Request):
"""Invite a guest, from the member dashboard (self-serve guest access).
Authenticated with the standard member broker identity — a GUEST identity
fails it, so only members reach here. Body: {"email": "<recipient>",
"name": "<optional display name>"}. Every protection runs BEFORE anything
is created (guest_request_guard): active-member inviter, one invitation
per member per rolling GUEST_PER_INVITER_DAYS (pending and approved
requests count), recipient never an existing member, a prior guest, a
pending request, or a MANUAL_MEMBERS address. The guest itself is
provisioned ONLY through provision_guest_member — the same pipeline the
operator's /admin/provision-guest runs (Cloudron user in the guests
group, $5 non-expiring credit, GUEST_DAYS time box, invitation email
naming the inviter, newsletter subscribe, ledger row).
Trial gate: with GUEST_AUTO_APPROVE off (the default) the request waits
in PENDING for the operator's approve/reject in the panel — nothing goes
to the recipient until it is approved, and the member sees 'pending
approval' in their dashboard trail. With it on, provisioning fires
immediately. The member is never emailed about a rejection; their trail
carries the status.
"""
email = _verify_broker_secret(request)
body = await request.json()
recipient = (body.get("email") or "").strip().lower()
name = (body.get("name") or "").strip()
if not recipient or "@" not in recipient:
raise HTTPException(400, "A valid guest email is required")
conn = get_db()
refusal = guest_request_guard(conn, email, recipient)
conn.close()
if refusal:
raise HTTPException(429, refusal)
if not GUEST_AUTO_APPROVE:
conn = get_db()
cur = conn.execute(
"INSERT INTO guest_requests (inviter_email, recipient_email, recipient_name) "
"VALUES (?, ?, ?)",
(email, recipient, name or None),
)
conn.commit()
request_id = cur.lastrowid
conn.close()
logger.info("Guest request #%s: %s invited %s (pending approval)",
request_id, email, recipient)
return {
"status": "pending_approval",
"request_id": request_id,
"recipient": recipient,
"name": name or None,
"note": ("Your guest request is waiting for a co-op approval. "
"Nothing has been sent yet — once it's approved, your "
"friend gets their account and invitation email, and "
"the status shows here."),
}
user_id = await provision_guest_member(
recipient, name or recipient.split("@")[0], email)
return {
"status": "provisioned", "account_type": "guest", "email": recipient,
"inviter": email, "user_id": user_id, "budget": GUEST_BUDGET,
"expires_in_days": int(GUEST_DAYS),
}
@app.get("/broker/metrics")
@limiter.limit("30/minute")
async def broker_metrics(request: Request, days: int = 90):
+434
View File
@@ -0,0 +1,434 @@
#!/usr/bin/env python3
"""Member self-serve guest requests — structurally isolated from live services.
WHY THIS EXISTS
The member path creates REAL guest accounts ($5 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',
$5 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: $5 non-expiring credit", acct and acct[2] == 5.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())