Rename gift to guest throughout: routes, ledger table, account_type values, env names, emails, tests
Pure rename, no behaviour change, matching the renamed panel and dashboard builds. Includes one-time idempotent migrations for existing databases (gifts->guests table, gift_expires_at->guest_expires_at column, account_type 'gift'->'guest' values, gift_lapse_notices->guest_lapse_notices) and four transitional alias routes (admin/provision-gift, admin/gift-convert, broker/gift-status, broker/cancel-gift) so pre-rename dashboard/panel builds keep working until they are redeployed.
This commit is contained in:
1 parent
8af8e39c0b
commit
27f9cc06b2
5 files changed
+493
-447
No files matched your search
@@ -0,0 +1,367 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Guest-account lifecycle tests — structurally isolated from live services.
|
||||
|
||||
WHY THIS EXISTS
|
||||
Guest accounts (operator feature, 2026-11-08) touch money ($5 of credits),
|
||||
Cloudron groups and email. 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.
|
||||
|
||||
GUARDS (abuse protection — one guest per inviter per 30d, one per recipient)
|
||||
1. An inviter who is not an active member is refused.
|
||||
2. A SECOND guest by the same inviter within the window is refused.
|
||||
3. A recipient who already received a guest (ledger) or already has a
|
||||
portal row is refused.
|
||||
PROVISION
|
||||
4. The full guest pipeline marks the row (account_type='guest', balance 0,
|
||||
credit_balance 5, guest_expires_at set, anchor day kept), records
|
||||
inviter → recipient in the guests ledger, subscribes the newsletter,
|
||||
and sends the guest welcome email — no Loomio/Matrix calls.
|
||||
CONVERT (guest → member)
|
||||
5. Group moves guests → members; allowance set to MEMBER_BUDGET; the
|
||||
unspent guest credit carries; the cap lifts to allowance + credits
|
||||
(15 + 5); the anchor day is KEPT; the congrats email goes out; the
|
||||
guests-ledger row becomes 'converted'; Loomio + Matrix syncs fire.
|
||||
LIFECYCLE (sweep pass)
|
||||
6. An EXPIRED guest (past guest_expires_at, credits remaining) is
|
||||
deactivated by the sweep: row active=0, group → inactive, budget
|
||||
zeroed, newsletter unsubscribed, ledger status 'expired'.
|
||||
7. A DEPLETED guest (spend reached the credits) is deactivated likewise,
|
||||
status 'depleted'.
|
||||
8. A healthy guest (not expired, credits left) is left untouched.
|
||||
|
||||
Runnable: python3 tests/test_guest_lifecycle.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.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"]
|
||||
|
||||
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 -------------------------------------------------------------- #
|
||||
calls = {"group": [], "budget": [], "pin": [], "email": [], "listmonk": [],
|
||||
"loomio": 0, "matrix": 0, "revoke": [], "owui": [], "subscribe": []}
|
||||
|
||||
|
||||
async def rec_group(user_id, group_id=None):
|
||||
calls["group"].append((user_id, group_id or m.MEMBERS_GROUP_ID))
|
||||
|
||||
|
||||
async def rec_budget(team_id, budget):
|
||||
calls["budget"].append((team_id, round(float(budget), 2)))
|
||||
|
||||
|
||||
async def rec_pin(team_id, reset_at):
|
||||
calls["pin"].append((team_id, str(reset_at)))
|
||||
|
||||
|
||||
def rec_email(to, subject, text_body=None, html_body=None):
|
||||
calls["email"].append((to, subject))
|
||||
return True # send_email's contract: truthy = the send left the building
|
||||
|
||||
|
||||
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 rec_revoke(email):
|
||||
calls["revoke"].append(email)
|
||||
return True
|
||||
|
||||
|
||||
async def rec_owui(uid):
|
||||
calls["owui"].append(uid)
|
||||
return True
|
||||
|
||||
|
||||
CALL_KEYS = ("group", "budget", "pin", "email", "listmonk", "loomio", "matrix",
|
||||
"revoke", "owui", "subscribe")
|
||||
|
||||
|
||||
def reset_calls():
|
||||
for k in CALL_KEYS:
|
||||
calls[k] = 0 if k in ("loomio", "matrix") else []
|
||||
|
||||
|
||||
TEAM_SPEND = {} # team_id -> cycle spend (default 0.0)
|
||||
|
||||
|
||||
def fake_team_db(team_id):
|
||||
return {"max_budget": None, "spend": TEAM_SPEND.get(team_id, 0.0),
|
||||
"budget_reset_at": None}
|
||||
|
||||
|
||||
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 "sk-fixture-key"
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
m.cloudron_set_group = rec_group
|
||||
m.cloudron_set_active = rec_group # same signature (uid, bool); recorded nowhere critical
|
||||
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 = rec_budget
|
||||
m.litellm_pin_reset_date = rec_pin
|
||||
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
|
||||
m.revoke_member_litellm_access = rec_revoke
|
||||
m.owui_add_to_members_group = rec_owui
|
||||
|
||||
|
||||
def seed_member(conn, email, account_type="member", active=1, balance=None,
|
||||
credits=None, anchor=None, expires=None, slug=""):
|
||||
conn.execute(
|
||||
"INSERT INTO members (email, key_token, cloudron_user_id, slug, active, "
|
||||
"balance, credit_balance, account_type, anchor_day, guest_expires_at) "
|
||||
"VALUES (?, 'enc', 'uid-' || ?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
(email, email, slug, active,
|
||||
balance if balance is not None else m.MEMBER_BUDGET,
|
||||
credits if credits is not None else 0.0,
|
||||
account_type, anchor, expires),
|
||||
)
|
||||
|
||||
|
||||
def row_of(conn, email, col):
|
||||
return conn.execute(f"SELECT {col} FROM members WHERE email = ?", (email,)).fetchone()[0]
|
||||
|
||||
|
||||
def main():
|
||||
m.get_db().close() # create + migrate the fixture schema
|
||||
conn = m.get_db()
|
||||
m._ensure_allowance_tables(conn) # anchor_day column (as production does)
|
||||
conn.close()
|
||||
inviter = "member-one@x.org"
|
||||
|
||||
# --- 1. inviter must be an active member -------------------------------
|
||||
conn = m.get_db()
|
||||
seed_member(conn, inviter, active=1)
|
||||
conn.commit()
|
||||
conn.close()
|
||||
conn = m.get_db()
|
||||
check("guard: non-member inviter refused",
|
||||
m.guest_provision_guard(conn, "stranger@x.org", "friend@x.org") is not None)
|
||||
check("guard: active member inviter allowed",
|
||||
m.guest_provision_guard(conn, inviter, "friend@x.org") is None)
|
||||
# --- 2. one guest per inviter per 30 days -------------------------------
|
||||
conn.execute(
|
||||
"INSERT INTO guests (inviter_email, recipient_email, created_at, status) "
|
||||
"VALUES (?, 'friend@x.org', datetime('now'), 'active')", (inviter,))
|
||||
conn.commit()
|
||||
refusal = m.guest_provision_guard(conn, inviter, "friend2@x.org")
|
||||
check("guard: second guest within 30 days refused", refusal is not None and "30 days" in refusal,
|
||||
str(refusal))
|
||||
# backdate the ledger row: outside the window the inviter may guest again
|
||||
conn.execute("UPDATE guests SET created_at = datetime('now', '-31 days')")
|
||||
check("guard: guest allowed again after the window",
|
||||
m.guest_provision_guard(conn, inviter, "friend2@x.org") is None)
|
||||
# --- 3. one guest per recipient ever ------------------------------------
|
||||
conn.execute("UPDATE guests SET recipient_email = 'friend2@x.org'")
|
||||
conn.commit()
|
||||
refusal = m.guest_provision_guard(conn, inviter, "friend2@x.org")
|
||||
check("guard: recipient already in ledger refused", refusal is not None, str(refusal))
|
||||
seed_member(conn, "existing@x.org", account_type="member", active=1)
|
||||
conn.commit()
|
||||
check("guard: existing member as recipient refused",
|
||||
m.guest_provision_guard(conn, inviter, "existing@x.org") is not None)
|
||||
conn.close()
|
||||
|
||||
# --- 4. the full guest pipeline (provision_guest_member) ------------------
|
||||
reset_calls()
|
||||
asyncio.run(m.provision_guest_member("invited@x.org", "Invited Friend", inviter))
|
||||
conn = m.get_db()
|
||||
check("provision: row marked guest", row_of(conn, "invited@x.org", "account_type") == "guest")
|
||||
check("provision: allowance balance 0", row_of(conn, "invited@x.org", "balance") == 0.0)
|
||||
check("provision: $5 credit", row_of(conn, "invited@x.org", "credit_balance") == 5.0)
|
||||
check("provision: guest_expires_at set", bool(row_of(conn, "invited@x.org", "guest_expires_at")))
|
||||
check("provision: group = guests group",
|
||||
calls["group"] and calls["group"][0][1] == m.GUESTS_GROUP_ID, str(calls["group"]))
|
||||
check("provision: cap set to 5.00 (one-time)",
|
||||
(calls["budget"] and calls["budget"][0][1] == 5.0), str(calls["budget"]))
|
||||
check("provision: invitation email sent (merged invite + welcome)",
|
||||
any("invited to the Inference Cooperative" in s for _, s in calls["email"]), str(calls["email"]))
|
||||
check("provision: newsletter subscribed",
|
||||
("invited@x.org", True) in calls["listmonk"], str(calls["listmonk"]))
|
||||
check("provision: NO loomio/matrix calls", calls["loomio"] == 0 and calls["matrix"] == 0)
|
||||
g = conn.execute("SELECT inviter_email, recipient_email, status FROM guests "
|
||||
"WHERE recipient_email = 'invited@x.org'").fetchone()
|
||||
check("provision: guests ledger records inviter→recipient",
|
||||
bool(g) and g[0] == inviter and g[1] == "invited@x.org" and g[2] == "active", str(g))
|
||||
conn.close()
|
||||
|
||||
# --- 5. conversion (guest → member) -------------------------------------
|
||||
reset_calls()
|
||||
anchor_before = row_of(m.get_db(), "invited@x.org", "anchor_day")
|
||||
asyncio.run(m.convert_guest_to_member("invited@x.org", "Invited Friend", "invitedfriend"))
|
||||
conn = m.get_db()
|
||||
check("convert: account_type back to member",
|
||||
row_of(conn, "invited@x.org", "account_type") == "member")
|
||||
check("convert: allowance lifted to MEMBER_BUDGET",
|
||||
row_of(conn, "invited@x.org", "balance") == m.MEMBER_BUDGET)
|
||||
check("convert: unspent guest credit carried",
|
||||
row_of(conn, "invited@x.org", "credit_balance") == 5.0)
|
||||
check("convert: group moved to members",
|
||||
calls["group"] and calls["group"][0][1] == m.MEMBERS_GROUP_ID, str(calls["group"]))
|
||||
check("convert: cap lifted to 20.00 (15 + 5 credits)",
|
||||
(calls["budget"] and calls["budget"][0][1] == m.MEMBER_BUDGET + 5.0), str(calls["budget"]))
|
||||
check("convert: anchor day kept", row_of(conn, "invited@x.org", "anchor_day") == anchor_before)
|
||||
check("convert: congrats email sent",
|
||||
any("member now" in s for _, s in calls["email"]), str(calls["email"]))
|
||||
check("convert: Loomio + Matrix syncs fired", calls["loomio"] == 1 and calls["matrix"] == 1)
|
||||
check("convert: guests ledger status converted",
|
||||
conn.execute("SELECT status FROM guests WHERE recipient_email='invited@x.org'"
|
||||
).fetchone()[0] == "converted")
|
||||
check("convert: expiry cleared", row_of(conn, "invited@x.org", "guest_expires_at") is None)
|
||||
conn.close()
|
||||
|
||||
# --- 6/7/8. lifecycle sweep: expired / depleted / healthy ---------------
|
||||
past = (datetime.now(timezone.utc) - timedelta(days=1)).isoformat()
|
||||
future = (datetime.now(timezone.utc) + timedelta(days=30)).isoformat()
|
||||
conn = m.get_db()
|
||||
seed_member(conn, "expired@x.org", account_type="guest", active=1, balance=0.0,
|
||||
credits=5.0, anchor=8, expires=past)
|
||||
seed_member(conn, "healthy@x.org", account_type="guest", active=1, balance=0.0,
|
||||
credits=5.0, anchor=8, expires=future)
|
||||
seed_member(conn, "depleted@x.org", account_type="guest", active=1, balance=0.0,
|
||||
credits=5.0, anchor=8, expires=future)
|
||||
# A guest whose guest ended BEFORE the reaching-limits email shipped: the
|
||||
# sweep's catch-up pass must tell them exactly once.
|
||||
seed_member(conn, "already-gone@x.org", account_type="guest", active=0, balance=0.0,
|
||||
credits=5.0, anchor=8, expires=past)
|
||||
for e in ("expired@x.org", "healthy@x.org", "depleted@x.org", "already-gone@x.org"):
|
||||
conn.execute("INSERT INTO guests (inviter_email, recipient_email, guest_expires_at, status) "
|
||||
"VALUES (?, ?, ?, 'active')", (inviter, e, future))
|
||||
conn.execute("UPDATE guests SET status = 'expired' WHERE recipient_email = 'already-gone@x.org'")
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
TEAM_SPEND.clear() # healthy + expired have unspent credits
|
||||
reset_calls()
|
||||
out = asyncio.run(m.reconcile_guest_lifecycles())
|
||||
conn = m.get_db()
|
||||
check("lifecycle: expired guest deactivated by the sweep",
|
||||
row_of(conn, "expired@x.org", "active") == 0)
|
||||
check("lifecycle: expired guest group → inactive",
|
||||
any(e == "uid-expired@x.org" and g == m.INACTIVE_GROUP_ID
|
||||
for e, g in calls["group"]), str(calls["group"]))
|
||||
check("lifecycle: expired guest budget zeroed (revoke path called)",
|
||||
"expired@x.org" in calls["revoke"], str(calls["revoke"]))
|
||||
check("lifecycle: expired guest unsubscribed",
|
||||
("expired@x.org", False) in calls["listmonk"], str(calls["listmonk"]))
|
||||
check("lifecycle: ledger status 'expired'",
|
||||
conn.execute("SELECT status FROM guests WHERE recipient_email='expired@x.org'"
|
||||
).fetchone()[0] == "expired")
|
||||
check("lifecycle: healthy guest untouched",
|
||||
row_of(conn, "healthy@x.org", "active") == 1 and
|
||||
not any(e == "uid-healthy@x.org" for e, _ in calls["group"]))
|
||||
check("lifecycle: counts report expired=1 depleted=0",
|
||||
out.get("expired") == 1 and out.get("depleted") == 0, str(out))
|
||||
check("lifecycle: reaching-limits email sent once to the expired guest",
|
||||
sum(1 for to, s in calls["email"]
|
||||
if to == "expired@x.org" and "guest access has ended" in s) == 1,
|
||||
str(calls["email"]))
|
||||
check("lifecycle: catch-up told the pre-shutdown guest exactly once",
|
||||
sum(1 for to, s in calls["email"]
|
||||
if to == "already-gone@x.org" and "guest access has ended" in s) == 1,
|
||||
str(calls["email"]))
|
||||
check("lifecycle: notice counts in the sweep result",
|
||||
out.get("lapse_notices") == 2, str(out))
|
||||
conn.close()
|
||||
|
||||
TEAM_SPEND["team-depleted@x.org"] = 5.5 # depleted: spend reached the credits
|
||||
reset_calls()
|
||||
out = asyncio.run(m.reconcile_guest_lifecycles())
|
||||
conn = m.get_db()
|
||||
check("lifecycle: depleted guest deactivated",
|
||||
row_of(conn, "depleted@x.org", "active") == 0)
|
||||
check("lifecycle: depleted ledger status",
|
||||
conn.execute("SELECT status FROM guests WHERE recipient_email='depleted@x.org'"
|
||||
).fetchone()[0] == "depleted")
|
||||
check("lifecycle: healthy guest STILL untouched on second pass",
|
||||
row_of(conn, "healthy@x.org", "active") == 1)
|
||||
check("lifecycle: counts report depleted=1", out.get("depleted") == 1, str(out))
|
||||
check("lifecycle: depleted guest also told once",
|
||||
sum(1 for to, s in calls["email"]
|
||||
if to == "depleted@x.org" and "guest access has ended" in s) == 1,
|
||||
str(calls["email"]))
|
||||
check("lifecycle: ONCE per guest — second sweep sent no repeat notices",
|
||||
sum(1 for to, s in calls["email"] if "guest access has ended" in s) == 1
|
||||
and m.guest_lapse_notice_sent("expired@x.org")
|
||||
and m.guest_lapse_notice_sent("already-gone@x.org"),
|
||||
str(calls["email"]))
|
||||
check("lifecycle: healthy guest never emailed",
|
||||
not any(to == "healthy@x.org" for to, _ in calls["email"]), str(calls["email"]))
|
||||
conn.close()
|
||||
|
||||
failed = [r for r in results if not r[1]]
|
||||
print(f"\n{len(results) - len(failed)}/{len(results)} checks passed")
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in new issue
Block a user