loomio: never invite an existing member (off by default + positive exclusion)
Incident 2026-11-04: a live run of sync_loomio_memberships() emailed a Loomio
invite notification to essentially the WHOLE membership (notification 744:
~83 in-app recipients, ~79 emails 'sent' 18:53-18:56 UTC). The sync handed
Loomio the full active-member list every run with no record of who had been
invited, relying on Loomio's add-if-absent semantics — which produced a
whole-group notification.
Guards now make a repeat impossible:
* LOOMIO_SYNC_ENABLED (off by default) — restoring LOOMIO_API_KEY alone no
longer re-arms the integration.
* members.loomio_invited_at — positive exclusion: an address is sent only if
it is neither in Loomio's current member list NOR ever handed over, and
each is recorded once. (The new column starts NULL for the ~89 members
already in Loomio, so the current-member check is what closes that gap.)
* FAIL CLOSED — no invite if Loomio's member list cannot be read.
* remove_absent is dropped: no evict-then-re-add (re-invite) path.
Tests: tests/test_loomio_guard.py (10/10).
This commit is contained in:
1 parent
947e4d3cf2
commit
120a24678d
2 files changed
+290
-26
No files matched your search
+123
-26
@@ -309,6 +309,12 @@ LOOMIO_API_KEY = os.environ.get("LOOMIO_API_KEY", "")
|
||||
# mangled auto-handle (email local-part + random suffix). The B3 users API
|
||||
# lets us rename them to the member's Cloudron username.
|
||||
LOOMIO_B3_KEY = os.environ.get("LOOMIO_B3_KEY", "")
|
||||
# Master switch for the Loomio membership sync. OFF unless explicitly enabled.
|
||||
# The sync's only effect is Loomio's invite notification, and a bad run emails
|
||||
# the whole group (incident 2026-11-04: notification 744 delivered to ~83
|
||||
# members). Restoring LOOMIO_API_KEY alone must NOT re-arm it — this flag has
|
||||
# to be set deliberately by the operator, once Loomio's purpose is decided.
|
||||
LOOMIO_SYNC_ENABLED = os.environ.get("LOOMIO_SYNC_ENABLED", "").strip().lower() in ("1", "true", "on", "yes")
|
||||
|
||||
# Matrix homeserver (self-hosted Synapse at matrix.inference.coop). The bot
|
||||
# account (admin) invites every active member to the co-op Space on sync.
|
||||
@@ -788,6 +794,13 @@ def get_db() -> sqlite3.Connection:
|
||||
# tier and deactivates it when the org's dues lapse.
|
||||
if "org_slug" not in cols:
|
||||
conn.execute("ALTER TABLE members ADD COLUMN org_slug TEXT")
|
||||
# Migration: loomio_invited_at — the first time this member's email was
|
||||
# handed to Loomio's membership API. Non-NULL means "already invited, never
|
||||
# invite again". This is the positive exclusion enforced by
|
||||
# sync_loomio_memberships: an existing member (already in Loomio, or already
|
||||
# invited) can never be sent a Loomio invite a second time.
|
||||
if "loomio_invited_at" not in cols:
|
||||
conn.execute("ALTER TABLE members ADD COLUMN loomio_invited_at 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.
|
||||
@@ -1240,6 +1253,32 @@ async def get_active_member_emails() -> list[str]:
|
||||
return [r[0] for r in rows]
|
||||
|
||||
|
||||
def get_loomio_invited_at(email: str) -> str | None:
|
||||
"""Return when `email` was first handed to Loomio, or None if never invited."""
|
||||
conn = get_db()
|
||||
row = conn.execute(
|
||||
"SELECT loomio_invited_at FROM members WHERE email = ?", (email,)
|
||||
).fetchone()
|
||||
conn.close()
|
||||
return row[0] if row else None
|
||||
|
||||
|
||||
def mark_loomio_invited(email: str) -> None:
|
||||
"""Record that `email` has been sent to Loomio at least once (idempotent).
|
||||
|
||||
Never overwrites an existing timestamp — the invariant is "has this email
|
||||
EVER been handed to Loomio", not "when was it last".
|
||||
"""
|
||||
conn = get_db()
|
||||
conn.execute(
|
||||
"UPDATE members SET loomio_invited_at = COALESCE(loomio_invited_at, datetime('now')) "
|
||||
"WHERE email = ?",
|
||||
(email,),
|
||||
)
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_member_matrix_mxid(email: str) -> str:
|
||||
"""Return the member's optional extra Matrix MXID, or "" if unset."""
|
||||
conn = get_db()
|
||||
@@ -1543,21 +1582,56 @@ async def matrix_member_mxids(client: httpx.AsyncClient):
|
||||
yield mxid, mxid
|
||||
|
||||
|
||||
async def sync_loomio_memberships() -> None:
|
||||
"""Reconcile the Loomio group to the current active-member list.
|
||||
async def fetch_loomio_member_emails(client: httpx.AsyncClient) -> set[str]:
|
||||
"""Return the emails Loomio already has in the group (lowercased).
|
||||
|
||||
Uses POST /api/b2/memberships with remove_absent=1, which adds new members
|
||||
and removes anyone not in the list. Operator accounts (LOOMIO_ALWAYS_KEEP)
|
||||
are always included so they are never removed.
|
||||
|
||||
Only members whose Cloudron account is already set up (inviteAccepted) are
|
||||
invited. Loomio's b2/memberships endpoint has no "silent invite" flag — it
|
||||
unconditionally emails a membership_created notification — so inviting a
|
||||
not-yet-activated member sends them a Loomio invite email before they've
|
||||
even created their account. Filtering to activated members prevents that;
|
||||
unactivated members are simply picked up on a later sync once they finish
|
||||
account setup.
|
||||
This is the 'has this member EVER been in that system' half of the positive
|
||||
exclusion. It must succeed before any invite is sent — see the fail-closed
|
||||
handling in sync_loomio_memberships.
|
||||
"""
|
||||
r = await client.get(
|
||||
f"{LOOMIO_BASE}/api/b2/memberships",
|
||||
headers={"Authorization": f"Bearer {LOOMIO_API_KEY}"},
|
||||
params={"group_id": int(LOOMIO_GROUP_ID)},
|
||||
)
|
||||
r.raise_for_status()
|
||||
data = r.json()
|
||||
return {
|
||||
(m.get("user_email") or "").lower()
|
||||
for m in data.get("memberships", [])
|
||||
if m.get("user_email")
|
||||
}
|
||||
|
||||
|
||||
async def sync_loomio_memberships() -> None:
|
||||
"""Add members to the Loomio group — NEVER re-invite an existing member.
|
||||
|
||||
SAFETY (incident 2026-11-04): a live run of this function emailed a Loomio
|
||||
invite notification to essentially the WHOLE membership. The guards below
|
||||
make a repeat impossible:
|
||||
|
||||
1. LOOMIO_SYNC_ENABLED must be ON. The integration is OFF by default, so
|
||||
restoring LOOMIO_API_KEY alone does NOT re-arm it; enabling it is a
|
||||
deliberate operator action.
|
||||
2. POSITIVE EXCLUSION — an address is only ever sent if it is neither
|
||||
currently in the Loomio group NOR recorded as previously handed to
|
||||
Loomio (members.loomio_invited_at). A member who is already in Loomio,
|
||||
or was ever invited, can never be invited again.
|
||||
3. FAIL CLOSED — if the current Loomio member list cannot be read, the sync
|
||||
skips entirely rather than sending a list it cannot verify.
|
||||
|
||||
Deliberately does NOT pass `remove_absent`: this sync only ADDS. Removing a
|
||||
lapsed member is a separate, explicit decision. Sending only the
|
||||
never-invited subset (instead of the full list with remove_absent=1) also
|
||||
removes the reconcile path that could evict a member on one run and then
|
||||
re-add — and therefore re-invite — them on the next.
|
||||
|
||||
Loomio's b2/memberships endpoint has no "silent invite" flag, so the only
|
||||
way to guarantee no invite is to send an address exactly once.
|
||||
"""
|
||||
if not LOOMIO_SYNC_ENABLED:
|
||||
logger.info("Loomio sync disabled (LOOMIO_SYNC_ENABLED is off); skipping")
|
||||
return
|
||||
if not LOOMIO_API_KEY or not LOOMIO_GROUP_ID:
|
||||
logger.warning("Loomio not configured; skipping membership sync")
|
||||
return
|
||||
@@ -1568,32 +1642,55 @@ async def sync_loomio_memberships() -> None:
|
||||
if keep not in emails:
|
||||
emails.append(keep)
|
||||
|
||||
# Only invite members who have completed Cloudron account setup. The
|
||||
# operator accounts (LOOMIO_ALWAYS_KEEP) bypass this filter — they must
|
||||
# stay in the group regardless of inviteAccepted (the bootstrap owner
|
||||
# account shows inviteAccepted: false forever even though it's functional).
|
||||
# Only members whose Cloudron account is already set up (inviteAccepted) —
|
||||
# never email a Loomio invite to someone who hasn't created their account
|
||||
# yet. Operator accounts bypass this filter (the bootstrap owner shows
|
||||
# inviteAccepted: false forever despite being functional).
|
||||
emails = await filter_loomio_activated(emails)
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
# FAIL CLOSED: never send a list we could not check against Loomio.
|
||||
try:
|
||||
current = await fetch_loomio_member_emails(client)
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
"Loomio sync: could not read current group members; skipping "
|
||||
"(fail-closed): %s", e,
|
||||
)
|
||||
return
|
||||
|
||||
# POSITIVE EXCLUSION: only addresses Loomio has never seen, and that we
|
||||
# have never handed over.
|
||||
fresh = [
|
||||
e for e in emails
|
||||
if e.lower() not in current and not get_loomio_invited_at(e)
|
||||
]
|
||||
if not fresh:
|
||||
logger.info(
|
||||
"Loomio sync: nobody new (all already in Loomio or already "
|
||||
"invited); nothing to send"
|
||||
)
|
||||
return
|
||||
|
||||
r = await client.post(
|
||||
f"{LOOMIO_BASE}/api/b2/memberships",
|
||||
headers={"Authorization": f"Bearer {LOOMIO_API_KEY}"},
|
||||
json={"group_id": int(LOOMIO_GROUP_ID), "emails": emails, "remove_absent": 1},
|
||||
json={"group_id": int(LOOMIO_GROUP_ID), "emails": fresh},
|
||||
)
|
||||
if r.status_code != 200:
|
||||
logger.warning("Loomio membership sync failed: %s %s", r.status_code, r.text[:200])
|
||||
return
|
||||
result = r.json()
|
||||
logger.info(
|
||||
"Loomio sync: added=%s removed=%s",
|
||||
result.get("added_emails", []),
|
||||
result.get("removed_emails", []),
|
||||
)
|
||||
added = result.get("added_emails", []) or []
|
||||
# Record EVERY address we sent, so it is never sent again — even if
|
||||
# Loomio didn't add it, or the membership is later revoked. A revoked
|
||||
# member is NOT a never-invited member, and must not be re-invited.
|
||||
for e in fresh:
|
||||
mark_loomio_invited(e)
|
||||
logger.info("Loomio sync: first-time invites sent (%d): %s", len(added), added)
|
||||
|
||||
# Fix auto-generated usernames (email+randomsuffix) → Cloudron username.
|
||||
# Runs after every sync so newly invited members get corrected within a day
|
||||
# (or immediately when the sync follows provisioning). Best-effort: no B3
|
||||
# key or API failure just logs and moves on.
|
||||
# Best-effort: no B3 key or an API failure just logs and moves on.
|
||||
if LOOMIO_B3_KEY:
|
||||
try:
|
||||
await loomio_fix_usernames(client)
|
||||
|
||||
Reference in new issue
Block a user