#!/usr/bin/env python3 """Gift-account SELF-CANCEL tests — structurally isolated from live services. Same harness contract as test_gift_lifecycle.py: a FIXTURE database with the network layer REPLACED BY A RAISING GUARD, so any code path that tries to reach Cloudron, LiteLLM, OC, Listmonk or SMTP outside the stubs fails the test loudly instead of acting on live systems. GUARD 1. A paying member can NEVER cancel through the gift path (403). 2. An unknown identity is refused. CANCEL (the full self-service flow) 3. The row deactivates (active=0) and the account is KEPT. 4. The Cloudron user leaves the guests group for the ended-guests group. 5. The gateway budget is zeroed (revoke path called). 6. The newsletter unsubscribe fires. 7. The credit RETURN is written: a NEGATIVE ledger delta whose reason names the cancellation and the original gift reference, deduped on its own reference; the member's credit_balance goes to 0. 8. The gifts ledger records inviter → recipient → 'cancelled by recipient' (rows appended, never rewritten). IDEMPOTENCE 9. A second cancel is a NO-OP: no second ledger row, no re-deactivation calls, and the reported status is the recorded one. PARTIAL-FAILURE REPLAY 10. A cancel whose return row already exists (deactivation failed mid-way last time) reports the recorded amount and writes no second ledger row. ENDED-STATE READBACK (GET /broker/gift-status payload pieces) 11. The cancelled gift reports ended + cancelled + the returned amount; a live gift reports active with its remaining credits; a member reports guest: false. Runnable: python3 tests/test_gift_cancel.py (from the repo root) """ import asyncio import base64 import os import sys import tempfile 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") os.environ.setdefault("GUESTS_ENDED_GROUP_ID", "gid-fixture-guests-ended") 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 calls = {"group": [], "revoke": [], "listmonk": [], "email": []} async def rec_group(user_id, group_id=None): calls["group"].append((user_id, group_id or m.MEMBERS_GROUP_ID)) async def rec_revoke(email): calls["revoke"].append(email) return True async def rec_listmonk(email, subscribe): calls["listmonk"].append((email, bool(subscribe))) def rec_email(to, subject, text_body=None, html_body=None): calls["email"].append((to, subject)) return True TEAM_SPEND = {} 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 m.cloudron_set_group = rec_group m.cloudron_set_active = rec_group # same signature (uid, bool) m.litellm_team_id_for_email = fake_team_id m.get_team_budget_from_db = fake_team_db m.revoke_member_litellm_access = rec_revoke m.listmonk_sync = rec_listmonk m.send_email = rec_email def seed_gift(conn, email, active=1, credits=5.0, balance=0.0): conn.execute( "INSERT INTO members (email, key_token, cloudron_user_id, slug, active, " "balance, credit_balance, account_type, gift_expires_at) " "VALUES (?, 'enc', 'uid-' || ?, '', ?, ?, ?, 'gift', " "datetime('now', '+30 days'))", (email, email, active, balance, credits), ) conn.execute( "INSERT INTO gifts (inviter_email, recipient_email, created_at, status) " "VALUES ('member-one@x.org', ?, datetime('now'), 'active')", (email,) ) def ledger_rows(conn, email): return conn.execute( "SELECT delta, reason, reference FROM credit_ledger WHERE email = ? " "ORDER BY id", (email,) ).fetchall() def main(): m.get_db().close() # create + migrate the fixture schema conn = m.get_db() # the inviter: an active member (guard requirement), and a PAYING member # whose cancellation must be refused conn.execute( "INSERT INTO members (email, key_token, cloudron_user_id, slug, active, " "balance, credit_balance, account_type) " "VALUES ('member-one@x.org', 'enc', 'uid-m1', 'memberone', 1, 15.0, 0.0, 'member')") conn.commit() conn.close() # --- 1/2. the member guard ---------------------------------------------- try: asyncio.run(m.cancel_gift_account("member-one@x.org")) check("guard: paying member cannot cancel via the gift path", False, "no 403 raised") except m.HTTPException as e: check("guard: paying member cannot cancel via the gift path", e.status_code == 403, str(e.status_code)) try: asyncio.run(m.cancel_gift_account("nobody@x.org")) check("guard: unknown identity refused", False, "no 403 raised") except m.HTTPException as e: check("guard: unknown identity refused", e.status_code == 403, str(e.status_code)) # --- 3-8. the full cancel flow ------------------------------------------ conn = m.get_db() seed_gift(conn, "gifted@x.org", active=1, credits=5.0) # the grant row production writes at provisioning (add_credits on the # gift reference) — the return is audited against it conn.execute("INSERT INTO credit_ledger (email, delta, reason, reference) " "VALUES ('gifted@x.org', 5.0, 'gift account — $5 credit from a member', " "'gift:gifted@x.org')") conn.commit() conn.close() out = asyncio.run(m.cancel_gift_account("gifted@x.org")) conn = m.get_db() row = conn.execute("SELECT active, account_type, credit_balance FROM members " "WHERE email = 'gifted@x.org'").fetchone() check("cancel: row deactivated, account kept", row[0] == 0 and row[1] == "gift", str(row)) check("cancel: credit balance drawn to 0", row[2] == 0.0, str(row)) check("cancel: group moved guests → ended-guests", any(u == "uid-gifted@x.org" and g == m.GUESTS_ENDED_GROUP_ID for u, g in calls["group"]), str(calls["group"])) check("cancel: gateway budget zeroed (revoke called)", "gifted@x.org" in calls["revoke"], str(calls["revoke"])) check("cancel: newsletter unsubscribed", ("gifted@x.org", False) in calls["listmonk"], str(calls["listmonk"])) led = ledger_rows(conn, "gifted@x.org") grants = [r for r in led if r[2] == "gift:gifted@x.org"] returns = [r for r in led if r[2] == "gift-return:gifted@x.org"] check("cancel: ledger holds the $5 grant and ONE negative return row", len(grants) == 1 and grants[0][0] == 5.0 and len(returns) == 1 and returns[0][0] == -5.0, str(led)) check("cancel: return reason names the cancellation and the gift reference", len(returns) == 1 and "cancelled by recipient" in returns[0][1] and "gift:gifted@x.org" in returns[0][1], str(returns)) g = conn.execute("SELECT inviter_email, recipient_email, status FROM gifts " "WHERE recipient_email = 'gifted@x.org'").fetchone() check("cancel: gifts ledger shows inviter → recipient → cancelled by recipient", g and g[0] == "member-one@x.org" and g[1] == "gifted@x.org" and g[2] == "cancelled by recipient", str(g)) check("cancel: result reports the returned amount", out.get("status") == "cancelled" and out.get("credits_returned") == 5.0, str(out)) conn.close() # --- 9. idempotence: the second cancel is a no-op ----------------------- calls["group"].clear(); calls["revoke"].clear(); calls["listmonk"].clear() out2 = asyncio.run(m.cancel_gift_account("gifted@x.org")) conn = m.get_db() led2 = ledger_rows(conn, "gifted@x.org") check("idempotent: second cancel reports already_ended", out2.get("status") == "already_ended" and out2.get("gift_status") == "cancelled by recipient", str(out2)) check("idempotent: no second return row", len([r for r in led2 if r[2] == "gift-return:gifted@x.org"]) == 1, str(led2)) check("idempotent: no re-deactivation side effects", not calls["group"] and not calls["revoke"] and not calls["listmonk"], str(calls)) conn.close() # --- 10. partial-failure replay: return row exists, deactivation failed - conn = m.get_db() seed_gift(conn, "halfway@x.org", active=1, credits=4.0) # simulate the ledger row written before a crash: return recorded, row still active conn.execute("UPDATE members SET credit_balance = 0.0 WHERE email = 'halfway@x.org'") conn.execute("INSERT INTO credit_ledger (email, delta, reason, reference) " "VALUES ('halfway@x.org', -4.0, 'gift cancelled by recipient — " "unspent credit returned to the co-op (original gift: " "gift:halfway@x.org)', 'gift-return:halfway@x.org')") conn.commit() conn.close() out3 = asyncio.run(m.cancel_gift_account("halfway@x.org")) conn = m.get_db() led3 = ledger_rows(conn, "halfway@x.org") check("replay: the recorded return is reported, not re-written", len([r for r in led3 if r[2] == "gift-return:halfway@x.org"]) == 1 and out3.get("credits_returned") == 4.0, str(led3) + " / " + str(out3)) check("replay: deactivation still completed", conn.execute("SELECT active FROM members WHERE email='halfway@x.org'" ).fetchone()[0] == 0) conn.close() # --- 11. the gift-status payload pieces --------------------------------- # member: guest false conn = m.get_db() ok_member = conn.execute("SELECT 1 FROM members WHERE email='member-one@x.org'").fetchone() conn.close() if ok_member: # call the payload logic directly (the route needs a Request object) conn = m.get_db() row = conn.execute("SELECT active, balance, credit_balance FROM members " "WHERE email = 'member-one@x.org'").fetchone() conn.close() check("status: a member is not a guest (payload contract)", not m.is_gift_account("member-one@x.org")) # cancelled gift: ended + cancelled + returned amount st_cancelled = { "ended": True, "gift_status": m._gift_ledger_status("gifted@x.org"), "cancelled": m._gift_ledger_status("gifted@x.org") == "cancelled by recipient", "credits_returned": m._gift_returned_credits("gifted@x.org"), } check("status: cancelled gift reads ended + cancelled + amount returned", st_cancelled["ended"] and st_cancelled["cancelled"] and st_cancelled["credits_returned"] == 5.0, str(st_cancelled)) # live gift: active with remaining credits conn = m.get_db() seed_gift(conn, "live@x.org", active=1, credits=5.0) conn.commit() conn.close() st_live = { "active": bool(conn_active := 1), "gift_status": m._gift_ledger_status("live@x.org"), } check("status: live gift reads active with an 'active' ledger row", st_live["active"] and st_live["gift_status"] == "active", str(st_live)) 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())