The invite stamp meant 'handed to Loomio once, EVER', so a member whose membership was later revoked (a lapse that was reversed) or who deleted their Loomio account was recorded as invited and never invited again. - Stamp only the addresses Loomio actually returns in added_emails; an address accepted in the payload but not added stays eligible. - Clear the stamp for an ACTIVE member stamped-but-absent from the live roster; the invite itself waits one pass so a single stale page cannot become an invite. - Cap stamp clearing per pass (LOOMIO_RECONCILE_MAX, default 10): more stamped-but-absent members means a short roster read, not a mass re-invite. - loomio_opt_out exempts members who deliberately left. - Username fix falls back to the portal slug when a handle is already taken (Loomio handles are instance-global; every OC alias resolves to opencollective).
This commit is contained in:
1 parent
146bfaf45e
commit
ffed06d492
3 files changed
+376
-28
No files matched your search
+86
-10
@@ -51,6 +51,7 @@ deletes = [] # every b3 membership DELETE url
|
||||
ROSTER = {} # email -> membership id currently in the group
|
||||
GET_FAILS = False # exercise fail-closed
|
||||
DELETE_STATUS = 200 # toggle to prove 404 tolerance
|
||||
ADDED_OMIT = set() # emails the fake Loomio accepts but does NOT add
|
||||
|
||||
|
||||
class FakeResp:
|
||||
@@ -88,7 +89,8 @@ class FakeClient:
|
||||
|
||||
async def post(self, url, headers=None, json=None):
|
||||
posts.append({"url": url, "json": json or {}})
|
||||
return FakeResp(200, {"added_emails": (json or {}).get("emails", [])})
|
||||
sent = (json or {}).get("emails", [])
|
||||
return FakeResp(200, {"added_emails": [e for e in sent if e not in ADDED_OMIT]})
|
||||
|
||||
async def delete(self, url, headers=None):
|
||||
deletes.append(url)
|
||||
@@ -119,7 +121,7 @@ def check(name, ok):
|
||||
|
||||
|
||||
async def main():
|
||||
global GET_FAILS, ROSTER, DELETE_STATUS
|
||||
global GET_FAILS, ROSTER, DELETE_STATUS, ADDED_OMIT
|
||||
m.get_db().close() # create + migrate the fixture schema
|
||||
conn = m.get_db()
|
||||
for e in ("new@x.org", "old@x.org", "member@x.org"):
|
||||
@@ -130,6 +132,7 @@ async def main():
|
||||
cols = [r[1] for r in m.get_db().execute("PRAGMA table_info(members)").fetchall()]
|
||||
m.get_db().close()
|
||||
check("migration: members.loomio_invited_at exists", "loomio_invited_at" in cols)
|
||||
check("migration: members.loomio_opt_out exists", "loomio_opt_out" in cols)
|
||||
|
||||
m.get_active_member_emails = fake_active
|
||||
m.filter_loomio_activated = fake_activated
|
||||
@@ -156,17 +159,30 @@ async def main():
|
||||
check("add: remove_absent is NEVER sent (no re-add path)", "remove_absent" not in body)
|
||||
check("add: the newly-invited address is recorded",
|
||||
m.get_loomio_invited_at("new@x.org") is not None)
|
||||
check("reconcile: a stamped-but-absent member's stamp is cleared (not yet re-invited)",
|
||||
m.get_loomio_invited_at("old@x.org") is None)
|
||||
check("add: nothing removed when nobody has lapsed", deletes == [])
|
||||
|
||||
# --- 2. Second run adds nobody again. ---
|
||||
# --- 2. Second run: the cleared member is invited once, then recorded. ---
|
||||
ROSTER = {"member@x.org": 10, "keep@x.org": 2, "new@x.org": 99} # Loomio now has new@
|
||||
posts.clear(); deletes.clear()
|
||||
await m.sync_loomio_memberships()
|
||||
body = posts[0]["json"] if posts else {}
|
||||
check("reconcile: the cleared member is re-invited on the next pass",
|
||||
body.get("emails") == ["old@x.org"])
|
||||
check("reconcile: the re-invite is recorded", m.get_loomio_invited_at("old@x.org") is not None)
|
||||
check("reconcile: a present member is never re-invited",
|
||||
"member@x.org" not in (body.get("emails") or []))
|
||||
|
||||
# --- 2b. Third run: nothing left to invite. ---
|
||||
ROSTER = {"member@x.org": 10, "keep@x.org": 2, "new@x.org": 99, "old@x.org": 88}
|
||||
posts.clear(); deletes.clear()
|
||||
await m.sync_loomio_memberships()
|
||||
check("double-run: no second invite", posts == [])
|
||||
check("double-run: no removals", deletes == [])
|
||||
|
||||
# --- 3. REMOVE path: a lapsed member is removed exactly once. ---
|
||||
ROSTER = {"member@x.org": 10, "keep@x.org": 2, "new@x.org": 99, "lapsed@x.org": 77}
|
||||
ROSTER = {"member@x.org": 10, "keep@x.org": 2, "new@x.org": 99, "old@x.org": 88, "lapsed@x.org": 77}
|
||||
posts.clear(); deletes.clear()
|
||||
await m.sync_loomio_memberships()
|
||||
check("remove: the lapsed member is removed exactly once",
|
||||
@@ -180,7 +196,7 @@ async def main():
|
||||
all("keep@x.org" not in (p["json"].get("emails") or []) for p in posts))
|
||||
|
||||
# --- 4. Second run after the removal changes nothing. ---
|
||||
ROSTER = {"member@x.org": 10, "keep@x.org": 2, "new@x.org": 99} # lapsed gone
|
||||
ROSTER = {"member@x.org": 10, "keep@x.org": 2, "new@x.org": 99, "old@x.org": 88} # lapsed gone
|
||||
posts.clear(); deletes.clear()
|
||||
await m.sync_loomio_memberships()
|
||||
check("remove double-run: nothing removed again", deletes == [])
|
||||
@@ -188,7 +204,7 @@ async def main():
|
||||
|
||||
# --- 5. A re-run against a STALE roster (member already gone) must not error:
|
||||
# Loomio answers 404 for an absent membership, which is success. ---
|
||||
ROSTER = {"member@x.org": 10, "keep@x.org": 2, "lapsed@x.org": 77}
|
||||
ROSTER = {"member@x.org": 10, "keep@x.org": 2, "old@x.org": 88, "lapsed@x.org": 77}
|
||||
DELETE_STATUS = 404
|
||||
posts.clear(); deletes.clear()
|
||||
err = None
|
||||
@@ -201,7 +217,7 @@ async def main():
|
||||
DELETE_STATUS = 200
|
||||
|
||||
# --- 6. FAIL CLOSED: an unreadable roster stops BOTH phases. ---
|
||||
ROSTER = {"lapsed@x.org": 77}
|
||||
ROSTER = {"lapsed@x.org": 77, "old@x.org": 88}
|
||||
GET_FAILS = True
|
||||
posts.clear(); deletes.clear()
|
||||
await m.sync_loomio_memberships()
|
||||
@@ -218,10 +234,10 @@ async def main():
|
||||
m.LOOMIO_SYNC_ENABLED = True
|
||||
|
||||
# --- 8. Recording is idempotent — an existing timestamp is never overwritten. ---
|
||||
first = m.get_loomio_invited_at("old@x.org")
|
||||
m.mark_loomio_invited("old@x.org")
|
||||
first = m.get_loomio_invited_at("member@x.org")
|
||||
m.mark_loomio_invited("member@x.org")
|
||||
check("mark_loomio_invited never overwrites an existing timestamp",
|
||||
m.get_loomio_invited_at("old@x.org") == first)
|
||||
m.get_loomio_invited_at("member@x.org") == first)
|
||||
|
||||
# --- 9. remove_loomio_membership status handling (200/204/404 ok, 500 not). ---
|
||||
async with FakeClient() as c:
|
||||
@@ -231,6 +247,66 @@ async def main():
|
||||
check("remove_loomio_membership: 500 is a failure", not await m.remove_loomio_membership(c, 1))
|
||||
DELETE_STATUS = 200
|
||||
|
||||
# --- 10. OPT-OUT: a member who deliberately left is never re-invited. ---
|
||||
conn = m.get_db()
|
||||
conn.execute("INSERT OR REPLACE INTO members (email, active, loomio_opt_out) VALUES (?, 1, 1)",
|
||||
("left@x.org",))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
m.mark_loomio_invited("left@x.org")
|
||||
|
||||
async def active_with_left():
|
||||
return ["member@x.org", "left@x.org"]
|
||||
|
||||
m.get_active_member_emails = active_with_left
|
||||
ROSTER = {"member@x.org": 10, "keep@x.org": 2}
|
||||
posts.clear(); deletes.clear()
|
||||
await m.sync_loomio_memberships()
|
||||
check("opt-out: a member who left is not re-invited", posts == [])
|
||||
check("opt-out: their stamp is left intact", m.get_loomio_invited_at("left@x.org") is not None)
|
||||
|
||||
# --- 11. RECONCILE CAP: many stamped-but-absent members mean a bad roster
|
||||
# read, not a mass re-invite. Nothing is cleared. ---
|
||||
many = [f"miss{n}@x.org" for n in range(1, m.LOOMIO_RECONCILE_MAX + 2)]
|
||||
conn = m.get_db()
|
||||
for e in many:
|
||||
conn.execute("INSERT OR REPLACE INTO members (email, active) VALUES (?, 1)", (e,))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
for e in many:
|
||||
m.mark_loomio_invited(e)
|
||||
|
||||
async def active_with_many():
|
||||
return ["member@x.org"] + many
|
||||
|
||||
m.get_active_member_emails = active_with_many
|
||||
ROSTER = {"member@x.org": 10, "keep@x.org": 2}
|
||||
posts.clear(); deletes.clear()
|
||||
await m.sync_loomio_memberships()
|
||||
check("cap: an over-cap stamp reconciliation sends no invites", posts == [])
|
||||
check("cap: stamps are untouched when the cap is exceeded",
|
||||
all(m.get_loomio_invited_at(e) is not None for e in many))
|
||||
|
||||
# --- 12. NOT ADDED: if Loomio accepts the payload but adds nothing for an
|
||||
# address, it must stay unstamped and eligible. ---
|
||||
conn = m.get_db()
|
||||
conn.execute("INSERT OR REPLACE INTO members (email, active) VALUES (?, 1)", ("lost@x.org",))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
async def active_with_lost():
|
||||
return ["member@x.org", "lost@x.org"]
|
||||
|
||||
m.get_active_member_emails = active_with_lost
|
||||
ADDED_OMIT = {"lost@x.org"}
|
||||
ROSTER = {"member@x.org": 10, "keep@x.org": 2}
|
||||
posts.clear(); deletes.clear()
|
||||
await m.sync_loomio_memberships()
|
||||
check("not-added: the address is sent", posts and posts[0]["json"]["emails"] == ["lost@x.org"])
|
||||
check("not-added: an address Loomio did not add stays unstamped",
|
||||
m.get_loomio_invited_at("lost@x.org") is None)
|
||||
ADDED_OMIT = set()
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
fails = sum(not ok for _, ok in results)
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Regression test: Loomio handle collisions are resolved, not left mangled.
|
||||
|
||||
WHY THIS EXISTS
|
||||
Loomio usernames are unique per INSTANCE, not per group. The rename pass
|
||||
derives a target from the Cloudron username (the OAuth uid) or, before first
|
||||
SSO login, from the email local part. Both can collide with a handle someone
|
||||
else already holds:
|
||||
* a plain Cloudron username — "matt" is held by another member;
|
||||
* Open Collective aliases — every OC member's address starts
|
||||
"opencollective@", so the local part resolves to "opencollective" and
|
||||
collides with whichever OC member took it first.
|
||||
A 422 "username has already been taken" must fall back to the member's portal
|
||||
slug (name-based, e.g. "matt-h"), never leave the member on an autogenerated
|
||||
handle.
|
||||
|
||||
Runnable: python3 tests/test_loomio_usernames.py (from the repo root)
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import asyncio
|
||||
|
||||
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "fixture.db")
|
||||
os.environ["LOOMIO_API_KEY"] = "test-user-key"
|
||||
os.environ["LOOMIO_B3_KEY"] = "test-server-key"
|
||||
os.environ["LOOMIO_GROUP_ID"] = "1"
|
||||
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"]
|
||||
|
||||
TAKEN = {"matt", "opencollective"}
|
||||
|
||||
|
||||
class FakeResp:
|
||||
def __init__(self, status=200, payload=None):
|
||||
self.status_code = status
|
||||
self._payload = payload or {}
|
||||
self.text = str(payload or {})
|
||||
|
||||
def raise_for_status(self):
|
||||
if self.status_code >= 400:
|
||||
raise RuntimeError(f"HTTP {self.status_code}")
|
||||
|
||||
def json(self):
|
||||
return self._payload
|
||||
|
||||
|
||||
USERS = [
|
||||
{"id": 300, "username": "matthiehnouk8f", "email": "matt@mattharwood.com",
|
||||
"identities": [{"identity_type": "oauth", "uid": "matt"}]},
|
||||
{"id": 313, "username": "opencollectivewbvgr", "email": "opencollective@jeremiahlee.com",
|
||||
"identities": []},
|
||||
{"id": 9, "username": "joshuaztanxk2", "email": "joshua.z.tan@example.org",
|
||||
"identities": [{"identity_type": "oauth", "uid": "joshua.z.tan"}]},
|
||||
{"id": 5, "username": "amarino", "email": "amarino@solo.ist",
|
||||
"identities": [{"identity_type": "oauth", "uid": "amarino"}]},
|
||||
]
|
||||
|
||||
|
||||
class FakeClient:
|
||||
def __init__(self, *a, **k):
|
||||
self.patches = []
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *a):
|
||||
return False
|
||||
|
||||
async def get(self, url, headers=None, params=None):
|
||||
return FakeResp(200, {"users": USERS})
|
||||
|
||||
async def patch(self, url, headers=None, json=None):
|
||||
uid = int(url.rsplit("/", 1)[-1])
|
||||
name = (json or {}).get("username")
|
||||
self.patches.append((uid, name))
|
||||
if name in TAKEN:
|
||||
return FakeResp(422, {"errors": {"username": ["has already been taken"]}})
|
||||
return FakeResp(200, {"user": {"id": uid, "username": name}})
|
||||
|
||||
|
||||
results = []
|
||||
|
||||
|
||||
def check(name, ok):
|
||||
results.append((name, ok))
|
||||
|
||||
|
||||
async def main():
|
||||
conn = m.get_db() # create + migrate
|
||||
for email, slug in (
|
||||
("matt@mattharwood.com", "matt-h"),
|
||||
("opencollective@jeremiahlee.com", "jeremiah-lee"),
|
||||
("joshua.z.tan@example.org", "joshua-z-tan"),
|
||||
("amarino@solo.ist", "amarino"),
|
||||
):
|
||||
conn.execute("INSERT OR REPLACE INTO members (email, slug) VALUES (?, ?)", (email, slug))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
client = FakeClient()
|
||||
out = await m.loomio_fix_usernames(client)
|
||||
by_uid = {}
|
||||
for uid, name in client.patches:
|
||||
by_uid.setdefault(uid, []).append(name)
|
||||
|
||||
# Matt Harwood: Cloudron uid "matt" is taken -> portal slug "matt-h".
|
||||
check("collision: the taken Cloudron username is tried first",
|
||||
by_uid.get(300, [])[0] == "matt")
|
||||
check("collision: falls back to the portal slug",
|
||||
by_uid.get(300) == ["matt", "matt-h"])
|
||||
|
||||
# Jeremiah Lee: OC alias local part "opencollective" is taken -> slug.
|
||||
check("collision: an OC alias local part is tried first",
|
||||
by_uid.get(313, [])[0] == "opencollective")
|
||||
check("collision: an OC alias collision falls back to the slug",
|
||||
by_uid.get(313) == ["opencollective", "jeremiah-lee"])
|
||||
|
||||
# Joshua Tan: a dot-containing uid is sanitized, not passed through.
|
||||
check("sanitize: a dotted uid becomes a legal handle",
|
||||
by_uid.get(9) == ["joshua_z_tan"])
|
||||
|
||||
# A human-chosen handle is out of scope and never renamed.
|
||||
check("skip: a hand-chosen handle is never renamed", 5 not in by_uid)
|
||||
check("summary: three handled, one skipped",
|
||||
out == {"fixed": 3, "skipped": 1})
|
||||
|
||||
# No patch ever sends an illegal character.
|
||||
check("sanitize: every attempted handle is Loomio-legal",
|
||||
all(n and n == m._loomio_safe_username(n) for _, names in by_uid.items() for n in names))
|
||||
|
||||
|
||||
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)
|
||||
Reference in new issue
Block a user