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:
1 parent
93184b6011
commit
0293d66c1e
2 files changed
+781
-1
No files matched your search
+347
-1
@@ -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):
|
||||
|
||||
Reference in new issue
Block a user