#!/usr/bin/env python3 """Regression test: the first-login service-sync hook (activation path). WHY THIS EXISTS New members were deliberately skipped by the Loomio/Matrix syncs until their Cloudron account was activated (never invite a half-created account), but nothing fired the syncs at the moment they DID activate — the 3x/day sweep was the pickup, so a member could wait hours for forum/space access. The hook on the broker identity path closes that gap. The guards that must hold are proven here on a FIXTURE db with the network STUBBED: CHEAP GATE 1. An established member (loomio_invited_at set) schedules NOTHING and triggers no Cloudron call — one SELECT, zero further work. ACTIVATION FILTER (fail-closed) 2. A never-invited member whose Cloudron account is NOT activated fires no sync — never invite a half-created account. 3. A member Cloudron does not know fires no sync. 4. An unreadable Cloudron user list fires no sync (fail-closed — unlike the sweep's fail-open roster filter, the hook decides whether to fire at all, so it must be sure). FIRES 5. A never-invited member whose Cloudron account IS activated fires BOTH syncs (Loomio then Matrix) exactly once, as a background task. SAFETY 6. A sync failure is swallowed and logged; the inflight flag clears so a later gate hit can retry (sweep remains the backstop). 7. While a sync is in flight, further gate hits schedule nothing (the full-roster reconcile already covers every pending member). 8. The gate NEVER raises — even when its own DB read fails, the broker response must be untouched. Runnable: python3 tests/test_first_login_sync.py (from the repo root) """ import os import sys import tempfile import asyncio os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "fixture.db") 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): results.append((name, ok)) async def drain(): """Await every task the gate scheduled, so assertions are deterministic.""" cur = asyncio.current_task() pending = [t for t in asyncio.all_tasks() if t is not cur] if pending: await asyncio.gather(*pending, return_exceptions=True) CLOUDRON_USERS = [] # what the (stubbed) Cloudron user list returns cloudron_calls = 0 sync_calls = [] # ("loomio"|"matrix") in fire order sync_gate = None # optional asyncio.Event: hold the sync in flight async def fake_fetch_users(client=None): global cloudron_calls cloudron_calls += 1 if CLOUDRON_USERS is None: return None return CLOUDRON_USERS async def fake_loomio_sync(): sync_calls.append("loomio") if sync_gate is not None: await sync_gate.wait() async def fake_matrix_sync(): sync_calls.append("matrix") async def boom_loomio_sync(): raise RuntimeError("simulated Loomio outage") async def main(): global CLOUDRON_USERS, cloudron_calls, sync_calls, sync_gate m.get_db().close() # create + migrate the fixture schema conn = m.get_db() for slug, email in (("est", "est@x.org"), ("new", "new@x.org"), ("pending", "pending@x.org"), ("ghost", "ghost@x.org")): conn.execute( "INSERT OR REPLACE INTO members (email, slug, active) VALUES (?, ?, 1)", (email, slug), ) conn.commit() conn.close() m.cloudron_fetch_all_users = fake_fetch_users m.sync_loomio_memberships = fake_loomio_sync m.sync_matrix_space = fake_matrix_sync # --- 1. CHEAP GATE: an established member schedules nothing at all. --- m.mark_loomio_invited("est@x.org") cloudron_calls = 0 sync_calls = [] m.maybe_first_login_service_sync("est@x.org") await drain() check("established member: no sync scheduled", sync_calls == []) check("established member: no Cloudron call", cloudron_calls == 0) check("established member: inflight flag stays clear", m._first_login_sync_inflight is False) # --- 2. ACTIVATION FILTER: account not activated -> never fires. --- CLOUDRON_USERS = [{"email": "new@x.org", "inviteAccepted": False}] cloudron_calls = 0 sync_calls = [] m.maybe_first_login_service_sync("new@x.org") await drain() check("not-activated member: no sync fired", sync_calls == []) check("not-activated member: activation WAS checked", cloudron_calls == 1) check("not-activated member: inflight flag cleared", m._first_login_sync_inflight is False) # --- 3. Unknown to Cloudron -> never fires. --- CLOUDRON_USERS = [{"email": "other@x.org", "inviteAccepted": True}] sync_calls = [] m.maybe_first_login_service_sync("ghost@x.org") await drain() check("member unknown to Cloudron: no sync fired", sync_calls == []) # --- 4. FAIL CLOSED: unreadable Cloudron user list -> never fires. --- CLOUDRON_USERS = None sync_calls = [] m.maybe_first_login_service_sync("new@x.org") await drain() check("cloudron outage: no sync fired (fail-closed)", sync_calls == []) check("cloudron outage: inflight flag cleared", m._first_login_sync_inflight is False) # --- 5. FIRES: activated + outstanding invites -> both syncs, once each. --- CLOUDRON_USERS = [{"email": "NEW@x.org", "inviteAccepted": True}] # case-insensitive sync_calls = [] m.maybe_first_login_service_sync("new@x.org") await drain() check("activated member: Loomio sync fired first, then Matrix", sync_calls == ["loomio", "matrix"]) check("activated member: inflight flag cleared after the run", m._first_login_sync_inflight is False) # --- 6. SAFETY: a sync failure is swallowed; the gate stays usable. --- m.sync_loomio_memberships = boom_loomio_sync sync_calls = [] m.maybe_first_login_service_sync("new@x.org") err = None try: await drain() except Exception as e: # pragma: no cover err = e check("loomio outage: nothing escapes the background task", err is None) check("loomio outage: matrix still attempted", sync_calls == ["matrix"]) check("loomio outage: inflight flag cleared for the next attempt", m._first_login_sync_inflight is False) m.sync_loomio_memberships = fake_loomio_sync # --- 7. INFLIGHT: a second gate hit while a sync runs schedules nothing. --- sync_gate = asyncio.Event() sync_calls = [] m.maybe_first_login_service_sync("new@x.org") # task starts, blocks in loomio stub await asyncio.sleep(0) # let it reach the blocking stub check("inflight: flag is set while the sync runs", m._first_login_sync_inflight is True) m.maybe_first_login_service_sync("pending@x.org") # second member, same moment m.maybe_first_login_service_sync("new@x.org") # same member again sync_gate.set() await drain() check("inflight: exactly ONE sync ran for three gate hits", sync_calls == ["loomio", "matrix"]) sync_gate = None # --- 8. The gate NEVER raises, even if its own DB read fails. --- real_invited = m.get_loomio_invited_at def broken_invited(_email): raise RuntimeError("simulated DB failure") m.get_loomio_invited_at = broken_invited err = None try: m.maybe_first_login_service_sync("new@x.org") await drain() except Exception as e: err = e check("gate swallows its own DB failure (broker response untouched)", err is None) check("gate DB failure schedules nothing", sync_calls == ["loomio", "matrix"]) m.get_loomio_invited_at = real_invited asyncio.run(main()) fails = sum(not ok for _, ok in results) for name, ok in results: print(f" [{'PASS' if ok else 'FAIL'}] {name}") print(f"\n{len(results) - fails}/{len(results)} passed") sys.exit(1 if fails else 0)