activation hook: fire Loomio+Matrix syncs at first broker login

New members were skipped by the syncs until their Cloudron account was
activated (deliberately - never invite a half-created account), but nothing
fired the syncs at the moment they DID activate: the 3x/day sweep was the
only pickup, so a newly-activated member could wait hours for forum/space
access (limdingwen waited ~5h on 2026-11-06).

Hook the broker identity path (_verify_broker_secret): after an active
member resolves, if loomio_invited_at is still null, confirm their Cloudron
account is activated (inviteAccepted, fail-CLOSED - an unreadable user list
never fires) and run the same idempotent syncs the sweep runs, as a
background task off the response. Established members pay one indexed
SELECT; concurrent first-logins collapse into one run via an inflight flag;
each service is independently best-effort so a Loomio outage cannot block
the Matrix invite or the response.

Tests: tests/test_first_login_sync.py (18 checks, fixture db + stubbed
network). Also fix test_allowance_shortfall, whose expected exclusion
reference still asserted the pre-a88ca86 placeholder.

Sweep, provisioning and deactivation paths are untouched.
This commit is contained in:
inference-bot committed 2026-11-06 19:51:12 +00:00
1 parent a88ca860d4
commit ed66d73327
4 files changed
+348 -2

No files matched your search

+126
View File
@@ -3891,6 +3891,127 @@ async def admin_model_usage(request: Request, days: int = 0):
# own keys — never another member's, and never the chat key.
# --- First-login service sync (activation hook) ---
# A newly provisioned member is deliberately skipped by the Loomio/Matrix syncs
# until their Cloudron account is activated (so a half-created account is never
# invited), and the 3x/day sweep was the only thing that picked them up AFTER
# they did activate — a new member could wait hours for forum/space access.
# The broker identity path is where the member first presents themselves after
# setting up (the dashboard calls it on first login), so it is the natural
# trigger: when a broker-authenticated, active member resolves AND their Loomio
# invite is still outstanding, confirm their Cloudron account is now activated
# and, only then, fire the same idempotent syncs the sweep runs. The syncs run
# as a background task, so no response ever waits on Loomio or Matrix.
_first_login_sync_inflight = False
def _member_slug(email: str) -> str:
"""Member slug for log lines (slugs survive log redaction; emails don't)."""
try:
conn = get_db()
row = conn.execute(
"SELECT slug FROM members WHERE email = ?", (email,)
).fetchone()
conn.close()
return (row[0] if row and row[0] else "") or "<slug-unset>"
except Exception:
return "<slug-unset>"
async def _member_cloudron_activated(email: str) -> bool:
"""True only when the member's Cloudron account is CONFIRMED activated.
Fail-CLOSED on purpose: if the Cloudron user list cannot be read (or the
member is not on it), report not-activated and let the 3x/day sweep try
later. The hook must never be the path that invites a half-created account,
so unlike the sweep's fail-open roster filter, an unverifiable activation
state means "do not fire".
"""
async with httpx.AsyncClient(timeout=15.0) as client:
users = await cloudron_fetch_all_users(client)
if not users:
return False
for u in users:
if (u.get("email") or "").lower() == email.lower():
return bool(u.get("inviteAccepted"))
return False
async def _first_login_service_sync(email: str) -> None:
"""Fire the Loomio + Matrix Space syncs for a newly-activated member.
Runs as a background task off the broker request (a Loomio outage must
never block a dashboard). The syncs are the SAME idempotent functions the
sweep and provisioning run — guarded by members.loomio_invited_at and the
live-roster pre-check — so a re-fire cannot double-invite. Best-effort:
any failure is logged and swallowed; the sweep remains the backstop.
"""
global _first_login_sync_inflight
slug = _member_slug(email)
try:
if not await _member_cloudron_activated(email):
logger.info(
"first-login sync: %s Cloudron account not yet activated; not "
"firing (the sweep covers it later)", slug,
)
return
# Each service independently best-effort: a Loomio outage must never
# stop the Matrix invite (or vice versa), and neither may raise out of
# this background task.
for label, sync_fn in (
("Loomio", sync_loomio_memberships),
("Matrix", sync_matrix_space),
):
try:
logger.info("first-login sync: firing %s sync for %s", label, slug)
await sync_fn()
except Exception:
logger.warning(
"first-login sync: %s sync for %s failed (non-fatal; the "
"sweep covers later)", label, slug, exc_info=True,
)
logger.info(
"first-login sync: done for %s (loomio_invited_at=%s)",
slug, get_loomio_invited_at(email),
)
except Exception:
logger.warning(
"first-login sync for %s failed (non-fatal; sweep covers later)",
slug, exc_info=True,
)
finally:
_first_login_sync_inflight = False
def maybe_first_login_service_sync(email: str) -> None:
"""Cheap gate on the broker hot path; never raises.
Established members (loomio_invited_at set) cost one indexed SELECT and
return. A never-invited member schedules the sync as a background task.
While one first-login sync is in flight, further gate hits do nothing: the
syncs are full-roster reconciles, so the running pass already covers every
pending member.
"""
global _first_login_sync_inflight
try:
if get_loomio_invited_at(email):
return # established member — zero further work
if _first_login_sync_inflight:
return # a sync is already running; it covers every pending member
loop = asyncio.get_running_loop()
except Exception:
return # the gate must never break the broker response
_first_login_sync_inflight = True
try:
loop.create_task(_first_login_service_sync(email))
except Exception:
_first_login_sync_inflight = False
logger.warning(
"first-login sync could not be scheduled (non-fatal)", exc_info=True,
)
def _verify_broker_secret(request: Request) -> str:
"""Return the authenticated member's email, or 401.
@@ -3918,6 +4039,11 @@ def _verify_broker_secret(request: Request) -> str:
# The member must be active in our DB before they can manage keys.
if not get_member_key(email):
raise HTTPException(403, "No active membership")
# Activation hook: if this active member's service invites are still
# outstanding AND their Cloudron account is now activated, fire the Loomio
# + Matrix syncs (background task; established members cost one SELECT).
# Best-effort by construction — it must never affect this response.
maybe_first_login_service_sync(email)
return email