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.
This commit is contained in:
inference-bot committed 2026-11-08 20:20:30 +00:00
1 parent f1a86d9d76
commit 285aa66525
3 files changed
+195 -401

No files matched your search

+10 -14
View File
@@ -72,22 +72,18 @@ guest per recipient ever; the inviter must be an active member; an existing
portal row under the recipient address is refused. Guests are subscribed to
the newsletter and invited to NOTHING else (no Loomio, no Matrix).
**Member self-serve invitations (trial gate).** `POST /broker/guests` (the
member-dashboard broker identity — a guest identity fails it) lets a MEMBER
**Member self-serve invitations (provision immediately).** `POST /broker/guests`
(the member-dashboard broker identity — a guest identity fails it) lets a MEMBER
invite a guest from their dashboard: `{"email", "name"}`. The same guards run
BEFORE anything is created (`guest_request_guard`: everything above, plus the
recipient is never a `MANUAL_MEMBERS` address or an already-pending request,
and the inviter's rolling window counts pending + approved REQUESTS too).
With `GUEST_AUTO_APPROVE` **off** (the default) the request lands PENDING in
the `guest_requests` table and the operator approves or rejects it from the
panel — `GET /admin/guest-requests` (queue + ledger, pending vs approved in
one view), `POST /admin/guest-requests/{id}/approve` (fires the full guest
pipeline above; every guard re-runs and a moved-state refusal is recorded on
the request) or `.../reject`. The recipient is contacted only on approval;
the inviting member sees pending/not-approved in their own trail via
`GET /broker/guests`. With `GUEST_AUTO_APPROVE=1` a member's request
provisions immediately — flipping the gate is an env change, not a code
change.
recipient is never a `MANUAL_MEMBERS` address), and a valid invitation
**provisions immediately** — the approval gate was removed on 2026-11-08 as
operator policy; the remaining protections (active member, one guest per
inviter per rolling 30 days, one guest per recipient ever, the $2 cap and the
`GUEST_DAYS` box) were judged sufficient. `provision_guest_member` re-runs
every guard, so a moved-state refusal still refuses. The member sees their
invitation trail — each guest with its status and expiry — via
`GET /broker/guests`.
**Sweep safety.** `reconcile_memberships()` never deactivates a guest for
lacking an OC contribution. A guest lapses only by its own rules, handled by
+48 -206
View File
@@ -355,13 +355,12 @@ GUEST_PER_INVITER_DAYS = float(os.environ.get("GUEST_PER_INVITER_DAYS", "30"))
# guests ledger, and admin invites are NOT bound by the member's
# one-per-30-days cap (admins are not members).
ADMIN_INVITER_EMAIL = os.environ.get("ADMIN_INVITER_EMAIL", "info@inference.coop").strip().lower()
# 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")
# MEMBER-initiated guest invitations provision IMMEDIATELY (operator decision,
# 2026-11-08 — the trial-era approval gate, including its GUEST_AUTO_APPROVE
# env flag, was removed). The guest pipeline's own guards are the protections:
# active-member inviter, one guest per inviter per rolling 30 days, one guest
# per recipient ever, no existing portal row, plus the member-path rule that
# the recipient is never a MANUAL_MEMBERS address.
# The Cloudron "guests" group: guest accounts land here. The chat and dashboard
# apps' access restrictions list BOTH members and guests, so a guest reaches
@@ -988,11 +987,11 @@ 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.
# Guest REQUESTS — LEGACY history from the trial-approval period. The
# approval gate was removed on 2026-11-08: a member's invitation
# provisions immediately, straight into the guests ledger above. The
# table is kept so the historical trail (decided requests) still reads;
# nothing writes to it any more.
conn.execute(
"CREATE TABLE IF NOT EXISTS guest_requests ("
"id INTEGER PRIMARY KEY AUTOINCREMENT, "
@@ -1193,45 +1192,25 @@ def guest_provision_guard(
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.
The member-invite guard. Runs everything guest_provision_guard enforces
(active member inviter, one guest per inviter per rolling window, one
guest per recipient ever, no existing portal row) plus the member-path
rule: the recipient is not on MANUAL_MEMBERS — manually-provisioned
accounts are co-op insiders, never guest targets.
A REJECTED request counts as neither: nothing was ever sent, and the
operator's gate still sits in front of every actual send.
(The trial-era pending-request rules are gone with the approval gate:
invitations provision immediately, and the one-per-30-days window is
counted from the guests ledger by guest_provision_guard.)
Returns None when the request may proceed, else a human-readable refusal.
Returns None when the invitation 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
@@ -4321,46 +4300,29 @@ async def admin_gift_convert_alias(request: Request):
# ---------------------------------------------------------------------------
# Guest-request approval (the member self-serve trial gate).
# Guests ledger (the approval gate was removed on 2026-11-08: member
# invitations provision immediately, so there is nothing to approve).
# ---------------------------------------------------------------------------
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")
@app.get("/admin/guest-ledger")
@limiter.limit("60/minute")
async def admin_guest_requests(request: Request):
"""The member guest-request queue and the guests ledger, for the panel.
async def admin_guest_ledger(request: Request):
"""The guests ledger, for the panel's duplicate-send guard.
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.
Authenticated by the X-Admin-Token header. Returns the guests ledger
(inviter → recipient, newest first) so the panel can refuse a second
guest for an address that already holds an ACTIVE account BEFORE calling
/admin/provision-guest. The portal's own recipient-side guards remain
the last authority behind it.
"""
_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}
@@ -4369,92 +4331,6 @@ async def admin_guest_requests(request: Request):
}
@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, $2 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 "", 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):
@@ -6162,7 +6038,7 @@ async def broker_cancel_gift_alias(request: Request):
# ---------------------------------------------------------------------------
# Member self-serve guest invitations (trial gate: operator approval).
# Member self-serve guest invitations (provision immediately, 2026-11-08).
# ---------------------------------------------------------------------------
@app.get("/broker/guests")
@@ -6173,12 +6049,13 @@ async def broker_guest_list(request: Request):
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).
GUEST_PER_INVITER_DAYS rule, counted from the guests ledger (a
legacy approved request carries its own ledger row);
* trail — every invitation this member has made, newest first: legacy
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).
"""
email = _verify_broker_secret(request)
conn = get_db()
@@ -6193,19 +6070,13 @@ async def broker_guest_list(request: Request):
(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(
last_sent = 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:
@@ -6217,7 +6088,7 @@ async def broker_guest_list(request: Request):
pass
trail = []
for rid, recipient, rname, created, decided, status, note in requests:
if status in ("pending", "rejected"):
if status == "rejected":
trail.append({
"kind": "request", "request_id": rid, "recipient": recipient,
"name": rname, "created_at": created, "decided_at": decided,
@@ -6231,7 +6102,6 @@ async def broker_guest_list(request: Request):
"eligible": eligible,
"per_inviter_days": int(GUEST_PER_INVITER_DAYS),
"next_eligible_at": next_eligible_at,
"auto_approve": bool(GUEST_AUTO_APPROVE),
"trail": trail,
}
@@ -6245,20 +6115,14 @@ async def broker_guest_invite(request: Request):
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, $2 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.
per member per rolling GUEST_PER_INVITER_DAYS, recipient never an existing
member or a prior guest, and never a MANUAL_MEMBERS address. A valid
invitation PROVISIONS IMMEDIATELY (operator decision, 2026-11-08 — the
trial-era approval gate is gone): provision_guest_member is the same
pipeline the operator's /admin/provision-guest runs (Cloudron user in the
guests group, $2 non-expiring credit, GUEST_DAYS time box, invitation
email naming the inviter, newsletter subscribe, ledger row) and re-runs
every guard, so a moved-state refusal still refuses.
"""
email = _verify_broker_secret(request)
body = await request.json()
@@ -6273,28 +6137,6 @@ async def broker_guest_invite(request: Request):
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, email)
return {
"status": "provisioned", "account_type": "guest", "email": recipient,
+137 -181
View File
@@ -1,47 +1,43 @@
#!/usr/bin/env python3
"""Member self-serve guest requests — structurally isolated from live services.
"""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) 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.
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.
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.
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.
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.
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)
"""
@@ -62,9 +58,6 @@ 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 = []
@@ -201,59 +194,100 @@ def main():
conn.commit()
conn.close()
# --- 1. the trial gate: a member's request waits PENDING ----------------
# --- 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("request: guard passes for an active member + fresh recipient",
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("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"])
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))
# --- 2. the member's own trail shows the pending request ----------------
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")))
check("trail: pending request visible to the member",
len(view["trail"]) == 1 and view["trail"][0]["status"] == "pending",
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 while a request is pending",
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"]))
# --- 3. second request while pending: refused (window counts requests) --
# --- 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 request while one is pending refused",
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 request",
check("limit: a DIFFERENT member is not blocked by someone else's guest",
refusal is None, str(refusal))
conn.close()
# --- 4-7. recipient-side refusal paths -----------------------------------
# --- 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()
@@ -265,15 +299,6 @@ def main():
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"}
@@ -294,135 +319,66 @@ def main():
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.
# --- 9. re-inviting a just-provisioned address is refused (moved state) --
reset()
conn = m.get_db()
conn.execute(
"INSERT INTO guest_requests (inviter_email, recipient_email, status) "
"VALUES (?, 'existing@x.org', 'pending')", (inviter,))
seed_member(conn, "member-three@x.org", active=1)
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")
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("decided-twice: re-approve refused (409)", code == 409, str(e))
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()
# --- 12. rejection -------------------------------------------------------
reset()
# --- 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) "
"VALUES (?, 'rejected-target@x.org', 'pending')", (inviter,))
"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()
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 ------------
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()
refusal = m.guest_request_guard(conn, "member-three@x.org", "fresh-after-reject@x.org")
check("reject: new request allowed after a rejection",
# (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()
# --- 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
# --- 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)