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

+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)