diff --git a/apps/board/app.py b/apps/board/app.py
index 8f9d53d..61f1ba5 100644
--- a/apps/board/app.py
+++ b/apps/board/app.py
@@ -118,6 +118,10 @@ def create_app(overrides: dict | None = None) -> Flask:
# For _person.html: the one login with no page behind it. A literal in the
# template would be the same string written twice, in two languages.
app.jinja_env.globals["tombstone_login"] = TOMBSTONE_LOGIN
+ # For member.html's role picker. The template asking the predicate is what
+ # keeps the picker from offering a role the handler will refuse — with two
+ # levels above admin, a hardcoded list can only be right for one of them.
+ app.jinja_env.globals["assignable_roles"] = members.assignable_roles
@app.context_processor
def _year():
diff --git a/apps/board/board.py b/apps/board/board.py
index e793907..80b5cb1 100644
--- a/apps/board/board.py
+++ b/apps/board/board.py
@@ -21,7 +21,7 @@ from flask import (Blueprint, abort, current_app, flash, g, redirect,
from . import auth, uploads
from .db import get_db
from .render import excerpt, to_html
-from .security import admin_required, login_required
+from .security import admin_required, is_at_least, login_required
bp = Blueprint("board", __name__)
@@ -31,7 +31,7 @@ BODY_MAX = 20_000
def is_admin() -> bool:
- return g.member["role"] in ("owner", "admin")
+ return is_at_least(g.member["role"], "admin")
def may_delete(row) -> bool:
diff --git a/apps/board/brand.py b/apps/board/brand.py
index 8b84ea5..d52bf93 100644
--- a/apps/board/brand.py
+++ b/apps/board/brand.py
@@ -12,6 +12,14 @@ drifts from it. That is what retires the comment: not by merging the two files
they are served by different things and each has to stand on its own — but by
making a divergence fail the build instead of going unnoticed for a month.
+### Whose screen this is
+
+**The superadministrator's, not an admin's.** The look and the identity are the
+platform's, and an admin is the association's committee — the same line that
+makes an admin account the superadministrator's to grant. An admin who wants the
+colours changed asks the person who installed this, which is the correct
+conversation to be having.
+
### The two destinations
One form, saved to two places, because the two halves cannot read the same
@@ -47,7 +55,7 @@ from flask import (Blueprint, Response, abort, current_app, flash, g, redirect,
from . import gitea, uploads
from .db import get_db
-from .security import admin_required
+from .security import superadmin_required
bp = Blueprint("brand", __name__)
@@ -364,7 +372,7 @@ def _read_picture(field: str, allowed: tuple[str, ...], errors: list[str]):
# --- routes ----------------------------------------------------------------
@bp.route("/gestion/marca", methods=["GET", "POST"])
-@admin_required
+@superadmin_required
def edit():
if request.method == "GET":
state = current()
@@ -439,7 +447,7 @@ def _store(stored: dict, css: str, logo, favicon, state: dict) -> None:
@bp.route("/gestion/marca/publicar", methods=["POST"])
-@admin_required
+@superadmin_required
def publish():
"""Try the commits again after the git server was unreachable."""
if _publish():
@@ -448,7 +456,7 @@ def publish():
@bp.route("/gestion/marca/restaurar", methods=["POST"])
-@admin_required
+@superadmin_required
def restore():
"""Back to the colours the site was built with.
diff --git a/apps/board/content.py b/apps/board/content.py
index d36609c..bbcdd2b 100644
--- a/apps/board/content.py
+++ b/apps/board/content.py
@@ -33,7 +33,7 @@ from flask import (Blueprint, abort, current_app, flash, g, redirect,
from . import gitea
from .db import get_db
from .render import to_html
-from .security import moderator_required
+from .security import is_at_least, moderator_required
# One list of accepted formats for the whole app, kept in the module that
# knows what each one looks like on the wire, so the editor and the board
# cannot drift apart about what a picture is.
@@ -233,7 +233,7 @@ def _collection_or_404(collection: str) -> dict:
if collection not in COLLECTIONS:
abort(404)
meta = COLLECTIONS[collection]
- if meta["role"] == "admin" and g.member["role"] not in ("owner", "admin"):
+ if meta["role"] == "admin" and not is_at_least(g.member["role"], "admin"):
abort(403)
return meta
@@ -242,7 +242,7 @@ def visible_collections() -> dict:
"""The collections this member may write to, for the tabs. A tab that only
ever produces a 403 is worse than no tab."""
return {name: meta for name, meta in COLLECTIONS.items()
- if meta["role"] != "admin" or g.member["role"] in ("owner", "admin")}
+ if meta["role"] != "admin" or is_at_least(g.member["role"], "admin")}
def _name_or_404(name: str) -> str:
diff --git a/apps/board/db.py b/apps/board/db.py
index a247864..95de582 100644
--- a/apps/board/db.py
+++ b/apps/board/db.py
@@ -65,7 +65,7 @@ def init_db(app) -> None:
for step in migrations.apply(db):
app.logger.info("Applied migration %s", step)
_ensure_tombstone(db)
- _seed_owner(db, app)
+ _seed_superadmin(db, app)
finally:
db.close()
@@ -79,35 +79,49 @@ def _ensure_tombstone(db: sqlite3.Connection) -> None:
)
-def _seed_owner(db: sqlite3.Connection, app) -> None:
- """Create the first owner from BOARD_OWNER, once.
+def _seed_superadmin(db: sqlite3.Connection, app) -> None:
+ """Create the first superadministrator from BOARD_OWNER, once.
- Deliberately refuses to change an existing owner. Were this to overwrite,
- anyone who could edit the environment could hand themselves ownership by
- restarting the container — which is a quieter privilege escalation than it
- looks, since editing a compose file draws far less attention than asking
- the owner for access.
+ Still `BOARD_OWNER` rather than a new name: it is the variable the server's
+ `.env` already carries, and an install that has to edit its environment to
+ survive an upgrade is an install that breaks on upgrade.
+
+ Deliberately refuses to change an existing superadministrator. Were this to
+ overwrite, anyone who could edit the environment could hand themselves the
+ platform by restarting the container — a quieter privilege escalation than
+ it looks, since editing a compose file draws far less attention than asking
+ for access.
+
+ **The `ON CONFLICT` below is the half worth reading twice.** It used to end
+ `SET role = 'owner'`, which was right while owner was the top of the tree.
+ Left that way after migration 7 it would have found the superadministrator's
+ login, matched the conflict, and demoted them back to owner on every
+ container restart — a privilege *reduction* arriving at the least convenient
+ moment and attributable to nothing anybody did. `members_one_superadmin`
+ would then have let somebody else take the chair.
"""
login = (app.config.get("OWNER_LOGIN") or "").strip()
- existing = db.execute("SELECT gitea_login FROM members WHERE role = 'owner'").fetchone()
+ existing = db.execute(
+ "SELECT gitea_login FROM members WHERE role = 'superadmin'").fetchone()
if existing:
if login and existing["gitea_login"].lower() != login.lower():
app.logger.warning(
- "BOARD_OWNER is %r but the owner is %r; leaving it alone. "
- "Transfer ownership from inside the app instead.",
+ "BOARD_OWNER is %r but the superadministrator is %r; leaving it "
+ "alone. Hand the platform on from inside the app instead.",
login, existing["gitea_login"],
)
return
if not login:
- app.logger.warning("No owner yet and BOARD_OWNER is unset — nobody can sign in.")
+ app.logger.warning("No superadministrator yet and BOARD_OWNER is unset — "
+ "nobody can sign in.")
return
db.execute(
"""INSERT INTO members (gitea_login, display_name, role, active)
- VALUES (?, ?, 'owner', 1)
- ON CONFLICT(gitea_login) DO UPDATE SET role = 'owner', active = 1""",
+ VALUES (?, ?, 'superadmin', 1)
+ ON CONFLICT(gitea_login) DO UPDATE SET role = 'superadmin', active = 1""",
(login, login),
)
- app.logger.info("Seeded %r as owner.", login)
+ app.logger.info("Seeded %r as superadministrator.", login)
diff --git a/apps/board/events.py b/apps/board/events.py
index e270a0d..a4e0e97 100644
--- a/apps/board/events.py
+++ b/apps/board/events.py
@@ -32,7 +32,7 @@ from flask import (Blueprint, Response, abort, flash, g, redirect,
from . import content, gitea, uploads
from .db import get_db
from .render import to_html
-from .security import admin_required, login_required
+from .security import admin_required, is_at_least, login_required
bp = Blueprint("events", __name__)
@@ -129,7 +129,7 @@ def month():
this_month=f"{today.year:04d}-{today.month:02d}",
today=today.day if (today.year, today.month) == (year, number) else 0,
public_missing=public_missing,
- may_edit=g.member["role"] in ("owner", "admin"),
+ may_edit=is_at_least(g.member["role"], "admin"),
)
@@ -140,7 +140,7 @@ def show(event_id: int):
return render_template("event.html", event=row,
body_html=to_html(row["body_md"] or ""),
when=_spoken_date(row["starts_on"]),
- may_edit=g.member["role"] in ("owner", "admin"))
+ may_edit=is_at_least(g.member["role"], "admin"))
@bp.route("/calendario/
{{ member.email }}
{% endif %} diff --git a/apps/board/templates/members.html b/apps/board/templates/members.html index 884cc84..4a90610 100644 --- a/apps/board/templates/members.html +++ b/apps/board/templates/members.html @@ -64,10 +64,11 @@ {% if is_admin %}- Hay un solo responsable. El responsable da de alta administradores; los - administradores dan de alta miembros y moderadores. Suspender, cambiar el rol, - reenviar la invitación y eliminar están en la ficha de cada persona, bajo - «Gestionar». + Hay un solo superadministrador y un solo responsable. El superadministrador + lleva la plataforma: las cuentas de administrador, el aspecto y la identidad + del sitio. El responsable lleva la asociación: los miembros, los moderadores + y las invitaciones. Suspender, cambiar el rol, reenviar la invitación y + eliminar están en la ficha de cada persona, bajo «Gestionar».
{% endif %} {% endblock %} diff --git a/apps/board/tests/conftest.py b/apps/board/tests/conftest.py index 523d893..e049071 100644 --- a/apps/board/tests/conftest.py +++ b/apps/board/tests/conftest.py @@ -65,9 +65,23 @@ def make_member(db): return _make +@pytest.fixture +def superadmin_id(db): + """The account BOARD_OWNER seeds: the superadministrator, who runs the + platform and passes every check below them.""" + return db.execute( + "SELECT id FROM members WHERE role = 'superadmin'").fetchone()["id"] + + @pytest.fixture def owner_id(db): - return db.execute("SELECT id FROM members WHERE role = 'owner'").fetchone()["id"] + """A responsable — the association's chair, which is empty on a fresh + install. Minted here because the two roles are deliberately different + people, and a test that means one should not reach for the other.""" + return db.execute( + """INSERT INTO members (gitea_login, display_name, email, role) + VALUES ('presidenta', 'Presidenta', 'presidenta@example.com', 'owner')""" + ).lastrowid @pytest.fixture diff --git a/apps/board/tests/test_brand.py b/apps/board/tests/test_brand.py index e401a88..127fe14 100644 --- a/apps/board/tests/test_brand.py +++ b/apps/board/tests/test_brand.py @@ -99,10 +99,12 @@ def test_an_unreadable_pair_warns_and_a_readable_one_does_not(): # --- the form ------------------------------------------------------------- @pytest.fixture -def admin(make_member, sign_in): - member_id = make_member("admina", role="admin") - sign_in(member_id) - return member_id +def admin(superadmin_id, sign_in): + """The superadministrator. Named `admin` because every test below reads + "signed in as the person who may change this", and that person is no longer + an administrator: the look and the identity are the platform's.""" + sign_in(superadmin_id) + return superadmin_id # Arguments for the test client rather than fields of the form. Separated by @@ -125,8 +127,11 @@ def save(post, **fields): return post("/comunidad/gestion/marca", data, **sent) -def test_only_admins_reach_it(client, post, make_member, sign_in): - for role in ("user", "moderator"): +def test_only_the_superadmin_reaches_it(client, post, make_member, sign_in): + """An administrator is refused too, which is the change: the colours and the + identity belong to whoever runs the platform, not to the association's + committee.""" + for role in ("user", "moderator", "admin", "owner"): sign_in(make_member(f"persona-{role}", role=role)) assert client.get("/comunidad/gestion/marca").status_code == 403 assert save(post, **{"token-brand": "#1b5e20"}).status_code == 403 @@ -370,17 +375,20 @@ def test_restoring_empties_the_row_and_the_disk(app, client, db, post, admin): # --- erasure -------------------------------------------------------------- -def test_erasing_the_admin_leaves_the_brand_standing(client, db, post, owner_id, - make_member, sign_in): +def test_erasing_whoever_set_the_brand_leaves_it_standing(client, db, post, admin, + make_member): """The colours belong to the association, like an event in the calendar. - An admin leaving is not a reason for the site to look like a default - install again.""" - admin_id = make_member("admina", role="admin") - sign_in(admin_id) - save(post, **{"token-brand": "#1b5e20"}) + Whoever set them leaving is not a reason for the site to look like a default + install again. - sign_in(owner_id) - post(f"/comunidad/miembros/{admin_id}/eliminar") + The row erased is a former superadministrator who has since handed the + platform on and is an admin again — which is the only way a row that set the + brand can become erasable at all, since neither chair can be erased.""" + former = make_member("anterior", role="admin") + save(post, **{"token-brand": "#1b5e20"}) + db.execute("UPDATE brand SET updated_by = ? WHERE id = 1", (former,)) + + post(f"/comunidad/miembros/{former}/eliminar") row = db.execute("SELECT tokens_json, updated_by FROM brand").fetchone() assert json.loads(row["tokens_json"]) == {"brand": "#1b5e20"} diff --git a/apps/board/tests/test_events.py b/apps/board/tests/test_events.py index 686158e..b253b69 100644 --- a/apps/board/tests/test_events.py +++ b/apps/board/tests/test_events.py @@ -24,9 +24,9 @@ def quiet_gitea(monkeypatch): @pytest.fixture -def an_event(post, owner_id, sign_in, quiet_gitea): +def an_event(post, superadmin_id, sign_in, quiet_gitea): def _add(title="Asamblea", starts_on="2026-10-24", **extra): - sign_in(owner_id) + sign_in(superadmin_id) data = {"title": title, "starts_on": starts_on} data.update(extra) post("/comunidad/calendario/nuevo", data) @@ -72,19 +72,19 @@ def test_the_calendar_itself_is_behind_the_login(client): # --- the month ----------------------------------------------------------- def test_the_month_shows_its_own_events_and_not_the_neighbours( - client, an_event, owner_id, sign_in): + client, an_event, superadmin_id, sign_in): an_event("Asamblea", "2026-10-24") an_event("Ensayo", "2026-11-03") - sign_in(owner_id) + sign_in(superadmin_id) october = client.get("/comunidad/calendario?mes=2026-10").get_data(as_text=True) assert "Asamblea" in october assert "Ensayo" not in october -def test_the_arrows_cross_the_year(client, an_event, owner_id, sign_in): - sign_in(owner_id) +def test_the_arrows_cross_the_year(client, an_event, superadmin_id, sign_in): + sign_in(superadmin_id) page = client.get("/comunidad/calendario?mes=2026-12").get_data(as_text=True) assert "mes=2027-01" in page @@ -98,10 +98,10 @@ def test_shifting_months_wraps_properly(): def test_a_mistyped_month_shows_today_rather_than_an_error( - client, owner_id, sign_in, quiet_gitea): + client, superadmin_id, sign_in, quiet_gitea): """A calendar that refuses to draw because a query string was mistyped is worse than one that shows now.""" - sign_in(owner_id) + sign_in(superadmin_id) today = date.today() page = client.get("/comunidad/calendario?mes=pumpkin") @@ -110,8 +110,8 @@ def test_a_mistyped_month_shows_today_rather_than_an_error( assert events.month_label(today.year, today.month) in page.get_data(as_text=True) -def test_february_in_a_leap_year_has_twenty_nine_days(client, owner_id, sign_in, quiet_gitea): - sign_in(owner_id) +def test_february_in_a_leap_year_has_twenty_nine_days(client, superadmin_id, sign_in, quiet_gitea): + sign_in(superadmin_id) page = client.get("/comunidad/calendario?mes=2028-02").get_data(as_text=True) assert ">29<" in page assert ">30<" not in page @@ -120,13 +120,13 @@ def test_february_in_a_leap_year_has_twenty_nine_days(client, owner_id, sign_in, # --- what the git server does to this ------------------------------------ def test_the_private_events_survive_a_git_server_that_is_down( - client, post, owner_id, sign_in, monkeypatch): + client, post, superadmin_id, sign_in, monkeypatch): """The half that only exists here must not be taken down by the half that does not. A refused connection reaches this module as a GiteaError because gitea.py translates it — before that it was a bare OSError and this page would have 500ed.""" import requests - sign_in(owner_id) + sign_in(superadmin_id) post("/comunidad/calendario/nuevo", {"title": "Asamblea", "starts_on": "2026-10-24"}) def refuse(*args, **kwargs): @@ -143,10 +143,10 @@ def test_the_private_events_survive_a_git_server_that_is_down( # --- the .ics ------------------------------------------------------------- -def test_the_ics_is_a_calendar_a_phone_understands(client, an_event, owner_id, sign_in): +def test_the_ics_is_a_calendar_a_phone_understands(client, an_event, superadmin_id, sign_in): an_event("Asamblea", "2026-10-24", starts_at="19:00", location="Local de la asociación") - sign_in(owner_id) + sign_in(superadmin_id) response = client.get("/comunidad/calendario/1.ics") @@ -159,22 +159,22 @@ def test_the_ics_is_a_calendar_a_phone_understands(client, an_event, owner_id, s assert "UID:evento-1@vienalatina.com" in body # stable, so re-adding updates -def test_an_event_with_no_time_lasts_the_whole_day(client, an_event, owner_id, sign_in): +def test_an_event_with_no_time_lasts_the_whole_day(client, an_event, superadmin_id, sign_in): """VALUE=DATE rather than inventing midnight, which is how a calendar shows it as a band across the top of the day.""" an_event("Jornada", "2026-10-24") - sign_in(owner_id) + sign_in(superadmin_id) body = client.get("/comunidad/calendario/1.ics").get_data(as_text=True) assert "DTSTART;VALUE=DATE:20261024" in body -def test_a_comma_in_the_place_is_escaped(client, an_event, owner_id, sign_in): +def test_a_comma_in_the_place_is_escaped(client, an_event, superadmin_id, sign_in): """An unescaped comma in LOCATION makes the rest of the line a second value, and the address arrives truncated.""" an_event("Asamblea", "2026-10-24", location="Plaza de Ottakring, junto al mercado") - sign_in(owner_id) + sign_in(superadmin_id) body = client.get("/comunidad/calendario/1.ics").get_data(as_text=True) @@ -196,8 +196,8 @@ def test_the_ics_needs_a_session(client, an_event): # --- refusals ------------------------------------------------------------- -def test_an_event_without_a_date_is_refused(client, db, post, owner_id, sign_in, quiet_gitea): - sign_in(owner_id) +def test_an_event_without_a_date_is_refused(client, db, post, superadmin_id, sign_in, quiet_gitea): + sign_in(superadmin_id) response = post("/comunidad/calendario/nuevo", {"title": "Algún día"}) @@ -205,8 +205,8 @@ def test_an_event_without_a_date_is_refused(client, db, post, owner_id, sign_in, assert db.execute("SELECT COUNT(*) AS n FROM events").fetchone()["n"] == 0 -def test_a_nonsense_time_is_refused(client, db, post, owner_id, sign_in, quiet_gitea): - sign_in(owner_id) +def test_a_nonsense_time_is_refused(client, db, post, superadmin_id, sign_in, quiet_gitea): + sign_in(superadmin_id) post("/comunidad/calendario/nuevo", {"title": "Asamblea", "starts_on": "2026-10-24", "starts_at": "25:99"}) @@ -217,14 +217,14 @@ def test_a_nonsense_time_is_refused(client, db, post, owner_id, sign_in, quiet_g # --- erasure -------------------------------------------------------------- def test_erasing_the_admin_leaves_the_event_standing( - db, post, an_event, owner_id, make_member, sign_in, quiet_gitea): + db, post, an_event, superadmin_id, make_member, sign_in, quiet_gitea): """The meeting still happens after they leave: the event belongs to the association, so the row stays and the name goes.""" admin = make_member("admina", role="admin") sign_in(admin) post("/comunidad/calendario/nuevo", {"title": "Asamblea", "starts_on": "2026-10-24"}) - sign_in(owner_id) + sign_in(superadmin_id) post(f"/comunidad/miembros/{admin}/eliminar") row = db.execute("SELECT title, created_by FROM events").fetchone() diff --git a/apps/board/tests/test_invites.py b/apps/board/tests/test_invites.py index fd888b8..4ba2fdf 100644 --- a/apps/board/tests/test_invites.py +++ b/apps/board/tests/test_invites.py @@ -222,10 +222,10 @@ def test_a_suspended_member_gets_no_reset(client, post, make_member, outbox): # --- inviting from the members screen ------------------------------------- def test_creating_a_member_emails_them_instead_of_showing_a_password( - app, client, post, owner_id, sign_in, outbox, monkeypatch): + app, client, post, superadmin_id, sign_in, outbox, monkeypatch): monkeypatch.setattr(gitea, "admin_create_user", lambda login, email, name, password: None) - sign_in(owner_id) + sign_in(superadmin_id) response = post("/comunidad/miembros/nuevo", { "login": "maria", "display_name": "María", "email": "m@example.com", @@ -241,7 +241,7 @@ def test_creating_a_member_emails_them_instead_of_showing_a_password( def test_when_mail_fails_the_admin_is_given_the_link( - app, client, post, owner_id, sign_in, monkeypatch): + app, client, post, superadmin_id, sign_in, monkeypatch): """Otherwise the account exists and the member simply never gets in.""" monkeypatch.setattr(gitea, "admin_create_user", lambda login, email, name, password: None) @@ -249,7 +249,7 @@ def test_when_mail_fails_the_admin_is_given_the_link( def explode(to, subject, body): raise mail.MailFailed("connection refused") monkeypatch.setattr(mail, "send", explode) - sign_in(owner_id) + sign_in(superadmin_id) response = post("/comunidad/miembros/nuevo", { "login": "maria", "display_name": "María", "email": "m@example.com", @@ -265,13 +265,13 @@ def test_when_mail_fails_the_admin_is_given_the_link( # --- when the server cannot send at all ----------------------------------- def test_an_unconfigured_server_does_not_blame_the_mail_server( - app, client, post, owner_id, sign_in, monkeypatch): + app, client, post, superadmin_id, sign_in, monkeypatch): """No MAIL_HOST is not a failure, and saying "no se pudo enviar" sends the admin hunting for an SMTP error that was never produced.""" monkeypatch.setattr(gitea, "admin_create_user", lambda login, email, name, password: None) app.config["MAIL_HOST"] = "" - sign_in(owner_id) + sign_in(superadmin_id) page = post("/comunidad/miembros/nuevo", { "login": "maria", "display_name": "María", "email": "m@example.com", @@ -283,9 +283,9 @@ def test_an_unconfigured_server_does_not_blame_the_mail_server( assert "/comunidad/invitacion/" in page -def test_the_form_warns_before_it_is_filled_in(app, client, owner_id, sign_in): +def test_the_form_warns_before_it_is_filled_in(app, client, superadmin_id, sign_in): app.config["MAIL_HOST"] = "" - sign_in(owner_id) + sign_in(superadmin_id) assert "no envía correo" in client.get( "/comunidad/miembros/nuevo").get_data(as_text=True) @@ -323,13 +323,13 @@ def test_recovery_is_always_offered_now(app, client): # member added any other way had no route in at all: no invitation was ever # issued for them and nothing could issue one later. -def test_an_existing_member_can_be_invited(app, client, post, owner_id, make_member, +def test_an_existing_member_can_be_invited(app, client, post, superadmin_id, make_member, sign_in, outbox): """The case that prompted this: the admin made the account by hand, added the member with the box unticked, and nobody could reach the account — including the admin, who never knew the password.""" member_id = make_member("salvador") - sign_in(owner_id) + sign_in(superadmin_id) post(f"/comunidad/miembros/{member_id}/invitar") @@ -339,12 +339,12 @@ def test_an_existing_member_can_be_invited(app, client, post, owner_id, make_mem assert invites.lookup(token_in(outbox[0]["body"])) is not None -def test_re_inviting_kills_the_previous_link(app, client, post, owner_id, make_member, +def test_re_inviting_kills_the_previous_link(app, client, post, superadmin_id, make_member, sign_in, outbox): """A link that was forwarded, or is sitting in a mailbox somebody else can read, must stop working the moment a replacement is sent.""" member_id = make_member("salvador") - sign_in(owner_id) + sign_in(superadmin_id) post(f"/comunidad/miembros/{member_id}/invitar") post(f"/comunidad/miembros/{member_id}/invitar") @@ -370,13 +370,13 @@ def test_a_plain_user_cannot_invite(client, post, make_member, sign_in, outbox): def test_a_member_with_no_address_is_refused_before_a_token_is_made( - app, client, db, post, owner_id, sign_in, outbox): + app, client, db, post, superadmin_id, sign_in, outbox): """Issuing the token first would invalidate a previous, working invitation in exchange for one that cannot be delivered.""" member_id = db.execute( "INSERT INTO members (gitea_login, display_name, role) VALUES ('sincorreo', 'Sin', 'user')" ).lastrowid - sign_in(owner_id) + sign_in(superadmin_id) post(f"/comunidad/miembros/{member_id}/invitar", follow_redirects=True) @@ -384,9 +384,9 @@ def test_a_member_with_no_address_is_refused_before_a_token_is_made( assert db.execute("SELECT 1 FROM invites").fetchone() is None -def test_a_suspended_member_cannot_be_invited(client, post, owner_id, make_member, +def test_a_suspended_member_cannot_be_invited(client, post, superadmin_id, make_member, sign_in, outbox): - sign_in(owner_id) + sign_in(superadmin_id) response = post(f"/comunidad/miembros/{make_member('fuera', active=0)}/invitar") assert response.status_code == 403 @@ -394,11 +394,11 @@ def test_a_suspended_member_cannot_be_invited(client, post, owner_id, make_membe def test_when_the_mail_fails_the_admin_is_handed_the_link( - app, client, post, owner_id, make_member, sign_in, monkeypatch): + app, client, post, superadmin_id, make_member, sign_in, monkeypatch): def explode(to, subject, body): raise mail.MailFailed("connection refused") monkeypatch.setattr(mail, "send", explode) - sign_in(owner_id) + sign_in(superadmin_id) page = post(f"/comunidad/miembros/{make_member('salvador')}/invitar", follow_redirects=True).get_data(as_text=True) diff --git a/apps/board/tests/test_members.py b/apps/board/tests/test_members.py index 1bb4c2f..8f635d6 100644 --- a/apps/board/tests/test_members.py +++ b/apps/board/tests/test_members.py @@ -11,31 +11,53 @@ from apps.board.members import may_create, may_manage # --- the rules as plain functions --------------------------------------- -def test_only_the_owner_makes_admins(): - assert may_create("owner", "admin") +def test_only_the_superadmin_makes_admins(): + """The line this phase draws. An admin account is the platform's, not the + association's — which is what makes it safe to hand the responsable chair to + a customer organisation's president.""" + assert may_create("superadmin", "admin") + assert not may_create("owner", "admin") assert not may_create("admin", "admin") assert not may_create("user", "admin") -def test_admins_and_the_owner_make_users(): +def test_everyone_above_a_moderator_makes_users(): + assert may_create("superadmin", "user") assert may_create("owner", "user") assert may_create("admin", "user") assert not may_create("user", "user") -def test_the_owner_is_beyond_everyone_including_themselves(): - assert not may_manage("owner", "owner") - assert not may_manage("admin", "owner") +def test_neither_chair_can_be_touched_by_anybody(): + """Both single chairs, both unreachable, for different reasons. The + superadministrator because there is nothing above them; the responsable + because the chair belongs to the association, and a platform administrator + quietly removing the president of the organisation they host is the move the + separation exists to prevent.""" + for actor in ("superadmin", "owner", "admin", "moderator", "user"): + assert not may_manage(actor, "superadmin"), actor + assert not may_manage(actor, "owner"), actor -def test_only_the_owner_manages_admins(): - assert may_manage("owner", "admin") +def test_only_the_superadmin_manages_admins(): + assert may_manage("superadmin", "admin") + assert not may_manage("owner", "admin") assert not may_manage("admin", "admin") +def test_the_role_picker_offers_exactly_what_the_handler_allows(): + """They used to be one constant and one predicate, which could only agree + for one actor once there were two levels above admin.""" + from apps.board.members import assignable_roles + for actor in ("superadmin", "owner", "admin", "moderator", "user"): + for role in ("admin", "moderator", "user"): + assert (role in assignable_roles(actor)) == may_create(actor, role), (actor, role) + + # --- the moderator, who curates content and not people ------------------- -def test_admins_and_the_owner_make_moderators(): +def test_admins_and_the_chairs_make_moderators(): + assert may_create("superadmin", "moderator") assert may_create("owner", "moderator") assert may_create("admin", "moderator") assert not may_create("moderator", "moderator") @@ -46,7 +68,7 @@ def test_a_moderator_has_no_power_over_anybody(): """The line the whole role rests on. Being trusted to judge what the public reads is not being trusted to suspend the person who wrote it, and a moderator who could do both would be a second kind of admin.""" - for target in ("owner", "admin", "moderator", "user"): + for target in ("superadmin", "owner", "admin", "moderator", "user"): assert not may_manage("moderator", target), target assert not may_create("moderator", target), target @@ -64,9 +86,8 @@ def test_an_admin_may_promote_a_member_to_moderator(client, db, post, make_membe def test_an_admin_still_cannot_mint_an_admin_through_the_role_form( client, db, post, make_member, sign_in): - """`set_role` moved from owner-only to admin-level so moderators can be - appointed routinely. That must not quietly hand admins the one power the - owner keeps.""" + """`set_role` is admin-level so moderators can be appointed routinely. That + must not quietly hand admins the one power the superadministrator keeps.""" admin = make_member("admina", role="admin") maria = make_member("maria") sign_in(admin) @@ -84,10 +105,10 @@ def test_a_moderator_cannot_change_a_role_at_all(client, db, post, make_member, def test_the_role_form_refuses_a_role_that_is_not_offered( - client, db, post, owner_id, make_member, sign_in): + client, db, post, superadmin_id, make_member, sign_in): """`tombstone` is a real value in the CHECK constraint and would make the member vanish from every listing while keeping their row.""" - sign_in(owner_id) + sign_in(superadmin_id) maria = make_member("maria") assert post(f"/comunidad/miembros/{maria}/rol", {"role": "tombstone"}).status_code == 403 @@ -96,24 +117,44 @@ def test_the_role_form_refuses_a_role_that_is_not_offered( # --- the database holds the line ---------------------------------------- -def test_a_second_owner_is_impossible(db): +def test_a_second_superadmin_is_impossible(db, superadmin_id): """Not a route check — a direct insert, because the point of the partial unique index is to survive a bug in the code above it.""" with pytest.raises(sqlite3.IntegrityError): db.execute( - "INSERT INTO members (gitea_login, role) VALUES ('usurpador', 'owner')" + "INSERT INTO members (gitea_login, role) VALUES ('usurpador', 'superadmin')" ) -def test_transfer_leaves_exactly_one_owner(app, db, owner_id, make_member): - from apps.board.members import transfer_ownership - admin_id = make_member("segunda", role="admin") - transfer_ownership(db, owner_id, admin_id) +def test_a_second_owner_is_impossible(db, owner_id): + with pytest.raises(sqlite3.IntegrityError): + db.execute( + "INSERT INTO members (gitea_login, role) VALUES ('usurpadora', 'owner')" + ) - owners = db.execute("SELECT id FROM members WHERE role = 'owner'").fetchall() - assert [row["id"] for row in owners] == [admin_id] + +@pytest.mark.parametrize("chair", ["superadmin", "owner"]) +def test_transfer_leaves_exactly_one_holder(app, db, superadmin_id, make_member, chair): + """Both chairs hand on the same way. The demotion comes first, or the unique + index refuses the promotion halfway through.""" + from apps.board.members import transfer_ownership + holder = superadmin_id if chair == "superadmin" else make_member("presi", role="owner") + admin_id = make_member("segunda", role="admin") + + transfer_ownership(db, holder, admin_id, chair) + + holders = db.execute("SELECT id FROM members WHERE role = ?", (chair,)).fetchall() + assert [row["id"] for row in holders] == [admin_id] assert db.execute("SELECT role FROM members WHERE id = ?", - (owner_id,)).fetchone()["role"] == "admin" + (holder,)).fetchone()["role"] == "admin" + + +def test_a_transfer_to_something_that_is_not_a_chair_is_refused(db, superadmin_id, make_member): + """`chair` comes from the route and never from a request, and this is what + keeps that true if somebody ever wires it to one.""" + from apps.board.members import transfer_ownership + with pytest.raises(ValueError): + transfer_ownership(db, superadmin_id, make_member("otra"), "admin") # --- the routes ---------------------------------------------------------- @@ -127,8 +168,8 @@ def test_admin_cannot_create_an_admin(client, post, make_member, sign_in): assert response.status_code == 403 -def test_owner_can_create_an_admin(client, db, post, owner_id, sign_in): - sign_in(owner_id) +def test_the_superadmin_can_create_an_admin(client, db, post, superadmin_id, sign_in): + sign_in(superadmin_id) post("/comunidad/miembros/nuevo", { "login": "nueva", "display_name": "Nueva", "email": "n@example.com", "role": "admin", @@ -142,15 +183,15 @@ def test_a_plain_user_cannot_reach_the_admin_screens(client, make_member, sign_i assert client.get("/comunidad/miembros/nuevo").status_code == 403 -def test_the_owner_cannot_be_suspended(client, post, owner_id, make_member, sign_in): +def test_the_superadmin_cannot_be_suspended(client, post, superadmin_id, make_member, sign_in): sign_in(make_member("admina", role="admin")) - response = post(f"/comunidad/miembros/{owner_id}/estado", {"active": "0"}) + response = post(f"/comunidad/miembros/{superadmin_id}/estado", {"active": "0"}) assert response.status_code == 403 -def test_the_owner_cannot_suspend_themselves(client, post, owner_id, sign_in): - sign_in(owner_id) - response = post(f"/comunidad/miembros/{owner_id}/estado", {"active": "0"}) +def test_the_superadmin_cannot_suspend_themselves(client, post, superadmin_id, sign_in): + sign_in(superadmin_id) + response = post(f"/comunidad/miembros/{superadmin_id}/estado", {"active": "0"}) assert response.status_code == 403 @@ -165,11 +206,11 @@ def test_an_admin_cannot_demote_another_admin(client, post, make_member, sign_in -def test_erasing_a_member_keeps_their_threads_readable(app, db, post, owner_id, make_member, sign_in): +def test_erasing_a_member_keeps_their_threads_readable(app, db, post, superadmin_id, make_member, sign_in): author = make_member("saliente") db.execute("INSERT INTO threads (author_id, title, body_md) VALUES (?, 'Hola', 'Texto')", (author,)) - sign_in(owner_id) + sign_in(superadmin_id) post(f"/comunidad/miembros/{author}/eliminar") assert db.execute("SELECT 1 FROM members WHERE id = ?", (author,)).fetchone() is None @@ -180,36 +221,52 @@ def test_erasing_a_member_keeps_their_threads_readable(app, db, post, owner_id, assert row["display_name"] == "Miembro eliminado" -def test_the_member_page_renders_for_each_role(client, db, owner_id, make_member, sign_in): - """Every role takes a different branch through member.html — the owner sees - transfer and erase, an admin sees suspend, a plain member sees neither — so - each one is rendered here rather than trusted. +def test_the_member_page_renders_for_each_role(client, db, superadmin_id, owner_id, + make_member, sign_in): + """Every role takes a different branch through member.html — the + superadministrator alone sees «Entregar la plataforma», both chairs see + «Eliminar», an admin sees «Suspender» and a plain member sees none of it — + so each one is rendered here rather than trusted. - These controls used to be on the cards in the directory and are on the - person's page now, which is what this looks at. The owner's branch needs an - admin to transfer to, so the page opened is the admin's. + The page opened is always somebody else's: nobody manages themselves, the + block is not drawn on your own page, and a test looking at it would pass for + the wrong reason. """ admin_id = make_member("admina", role="admin") + cases = [ + (superadmin_id, "admina", ["Entregar la plataforma", "Eliminar", "Suspender"]), + (owner_id, "admina", ["Eliminar", "Suspender"]), + (admin_id, "usuaria", ["Suspender"]), + (make_member("usuaria"), "admina", []), + ] + forbidden = {"Entregar la plataforma", "Eliminar", "Suspender"} - for member_id, expected in ((owner_id, "Transferir titularidad"), - (admin_id, "Suspender"), - (make_member("usuaria"), None)): + for member_id, who, expected in cases: sign_in(member_id) - # Never your own page: nobody manages themselves, so the block is not - # drawn there and the test would pass for the wrong reason. - who = "usuaria" if member_id == admin_id else "admina" body = client.get(f"/comunidad/miembro/{who}").get_data(as_text=True) assert who.title() in body - if expected: - assert expected in body - else: - assert "Transferir titularidad" not in body - assert "Suspender" not in body + for phrase in expected: + assert phrase in body, (member_id, phrase) + for phrase in forbidden - set(expected): + assert phrase not in body, (member_id, phrase) + + +def test_the_responsable_cannot_reach_an_admin_from_their_page( + client, owner_id, make_member, sign_in): + """The association's chair runs the association. An admin account is the + platform's, so the whole management block is absent from their page.""" + make_member("admina", role="admin") + sign_in(owner_id) + + body = client.get("/comunidad/miembro/admina").get_data(as_text=True) + + assert "Gestionar" in body # it is drawn — an admin is manageable… + assert "Administrador" not in body.split("Gestionar")[1] # …but not into or out of admin def test_the_new_member_form_hides_the_role_choice_from_admins( - client, owner_id, make_member, sign_in): - sign_in(owner_id) + client, superadmin_id, make_member, sign_in): + sign_in(superadmin_id) assert "Administrador" in client.get("/comunidad/miembros/nuevo").get_data(as_text=True) sign_in(make_member("admina", role="admin")) @@ -236,7 +293,7 @@ def test_the_export_is_only_your_own_writing(client, db, make_member, sign_in): # --- erasing somebody who has left traces -------------------------------- -def test_erasing_a_member_who_posted_a_picture(app, db, post, owner_id, make_member, sign_in): +def test_erasing_a_member_who_posted_a_picture(app, db, post, superadmin_id, make_member, sign_in): """This failed in production with a 500 the first time it was tried. `attachments.uploaded_by` is NOT NULL and does not cascade, so with a @@ -251,7 +308,7 @@ def test_erasing_a_member_who_posted_a_picture(app, db, post, owner_id, make_mem VALUES (1, 'foto-abc123abc123.jpg', 'foto.jpg', 'image/jpeg', 10, ?)""", (author,), ) - sign_in(owner_id) + sign_in(superadmin_id) response = post(f"/comunidad/miembros/{author}/eliminar") @@ -297,11 +354,11 @@ def test_every_table_pointing_at_members_is_accounted_for(db): # --- onboarding, now that there is only one account to make -------------- def test_a_new_member_has_no_password_until_they_choose_one( - client, db, post, owner_id, sign_in, monkeypatch): + client, db, post, superadmin_id, sign_in, monkeypatch): """No password is generated and none is shown. Until the invitation is used, password_hash is NULL — and a NULL hash cannot be signed in with.""" monkeypatch.setattr("apps.board.mail.send", lambda to, subject, body: None) - sign_in(owner_id) + sign_in(superadmin_id) post("/comunidad/miembros/nuevo", { "login": "maria", "display_name": "María", "email": "m@example.com", @@ -314,10 +371,10 @@ def test_a_new_member_has_no_password_until_they_choose_one( assert row["password_hash"] is None -def test_an_address_is_required(client, db, post, owner_id, sign_in): +def test_an_address_is_required(client, db, post, superadmin_id, sign_in): """It is the only way the invitation reaches anybody, so a member without one is a row that can never be used.""" - sign_in(owner_id) + sign_in(superadmin_id) post("/comunidad/miembros/nuevo", { "login": "maria", "display_name": "María", "email": "", "role": "user", }) @@ -325,12 +382,12 @@ def test_an_address_is_required(client, db, post, owner_id, sign_in): def test_a_duplicate_is_refused_before_anything_is_written( - client, db, post, owner_id, make_member, sign_in, monkeypatch): + client, db, post, superadmin_id, make_member, sign_in, monkeypatch): """The error that started this: "ya están en uso" for somebody who was not on the list. There is one list now, so the message and the screen agree.""" monkeypatch.setattr("apps.board.mail.send", lambda to, subject, body: None) make_member("maria") - sign_in(owner_id) + sign_in(superadmin_id) response = post("/comunidad/miembros/nuevo", { "login": "maria", "display_name": "Otra", "email": "otra@example.com", @@ -344,11 +401,11 @@ def test_a_duplicate_is_refused_before_anything_is_written( def test_erasing_a_member_lets_the_name_be_used_again( - client, db, post, owner_id, make_member, sign_in, monkeypatch): + client, db, post, superadmin_id, make_member, sign_in, monkeypatch): """Deleting used to leave an account behind on the other server, so the name stayed taken somewhere invisible. With one store, gone means gone.""" monkeypatch.setattr("apps.board.mail.send", lambda to, subject, body: None) - sign_in(owner_id) + sign_in(superadmin_id) post(f"/comunidad/miembros/{make_member('salvador')}/eliminar") post("/comunidad/miembros/nuevo", { @@ -477,3 +534,105 @@ def test_a_moderator_gets_no_controls_either(client, make_member, sign_in): assert client.post(f"/comunidad/miembros/{maria}/estado", data={"csrf_token": "token-for-tests", "active": "0"} ).status_code == 403 + + +# --- the two chairs, from the routes -------------------------------------- + +def test_an_admin_cannot_make_promote_or_erase_another_admin( + client, db, post, make_member, sign_in): + """Four doors into the same power, checked at each one. A hidden button is a + courtesy; these are the rules.""" + other = make_member("otra", role="admin") + sign_in(make_member("admina", role="admin")) + + assert post("/comunidad/miembros/nuevo", { + "login": "tercera", "display_name": "Tercera", + "email": "t@example.com", "role": "admin"}).status_code == 403 + assert post(f"/comunidad/miembros/{other}/rol", {"role": "user"}).status_code == 403 + assert post(f"/comunidad/miembros/{other}/estado", {"active": "0"}).status_code == 403 + assert post(f"/comunidad/miembros/{other}/eliminar").status_code == 403 + assert db.execute("SELECT role, active FROM members WHERE id = ?", + (other,)).fetchone()["role"] == "admin" + + +def test_the_responsable_cannot_touch_an_admin_either( + client, db, post, owner_id, make_member, sign_in): + """The chair this phase exists to make safe to hand over. A customer + organisation's president runs their association and does not administer the + platform that hosts it.""" + admin_id = make_member("admina", role="admin") + sign_in(owner_id) + + assert post("/comunidad/miembros/nuevo", { + "login": "nueva", "display_name": "Nueva", + "email": "n@example.com", "role": "admin"}).status_code == 403 + assert post(f"/comunidad/miembros/{admin_id}/rol", {"role": "user"}).status_code == 403 + assert post(f"/comunidad/miembros/{admin_id}/estado", {"active": "0"}).status_code == 403 + + +def test_nobody_reaches_the_superadmin_through_a_route( + client, post, superadmin_id, owner_id, make_member, sign_in): + for actor in (owner_id, make_member("admina", role="admin"), superadmin_id): + sign_in(actor) + assert post(f"/comunidad/miembros/{superadmin_id}/estado", + {"active": "0"}).status_code == 403, actor + assert post(f"/comunidad/miembros/{superadmin_id}/rol", + {"role": "user"}).status_code == 403, actor + assert post(f"/comunidad/miembros/{superadmin_id}/eliminar").status_code == 403, actor + + +def test_the_superadmin_cannot_erase_the_responsable(client, post, superadmin_id, + owner_id, sign_in): + """Deliberate, and the less obvious half of the separation: a platform + administrator quietly removing the president of the organisation they host + is exactly what two chairs are for.""" + sign_in(superadmin_id) + assert post(f"/comunidad/miembros/{owner_id}/eliminar").status_code == 403 + + +def test_handing_the_platform_on_is_the_superadmins_alone( + client, db, post, superadmin_id, owner_id, make_member, sign_in): + admin_id = make_member("admina", role="admin") + + for actor in (owner_id, admin_id): + sign_in(actor) + assert post(f"/comunidad/miembros/{admin_id}/transferir-plataforma" + ).status_code == 403 + + sign_in(superadmin_id) + post(f"/comunidad/miembros/{admin_id}/transferir-plataforma") + + assert db.execute("SELECT role FROM members WHERE id = ?", + (admin_id,)).fetchone()["role"] == "superadmin" + assert db.execute("SELECT role FROM members WHERE id = ?", + (superadmin_id,)).fetchone()["role"] == "admin" + + +def test_the_platform_only_goes_to_an_active_admin(client, db, post, superadmin_id, + make_member, sign_in): + sign_in(superadmin_id) + maria = make_member("maria") + suspended = make_member("dormida", role="admin", active=0) + + post(f"/comunidad/miembros/{maria}/transferir-plataforma") + post(f"/comunidad/miembros/{suspended}/transferir-plataforma") + + assert db.execute("SELECT role FROM members WHERE id = ?", + (superadmin_id,)).fetchone()["role"] == "superadmin" + + +def test_the_superadmin_can_fill_an_empty_responsable_chair( + client, db, post, superadmin_id, make_member, sign_in): + """A fresh install has nobody in it — migration 7 promotes the owner and + leaves the chair open — so somebody has to be able to seat the first one.""" + maria = make_member("maria") + sign_in(superadmin_id) + + post(f"/comunidad/miembros/{maria}/transferir") + + assert db.execute("SELECT role FROM members WHERE id = ?", + (maria,)).fetchone()["role"] == "owner" + # And the superadministrator is still the superadministrator: filling a + # chair you do not sit in costs you nothing. + assert db.execute("SELECT role FROM members WHERE id = ?", + (superadmin_id,)).fetchone()["role"] == "superadmin" diff --git a/apps/board/tests/test_messages.py b/apps/board/tests/test_messages.py index afd644b..a303398 100644 --- a/apps/board/tests/test_messages.py +++ b/apps/board/tests/test_messages.py @@ -301,7 +301,7 @@ def test_an_empty_message_with_no_picture_is_refused(client, db, post, make_memb # --- erasure -------------------------------------------------------------- def test_erasing_a_member_takes_their_private_messages( - app, client, db, post, owner_id, make_member, sign_in): + app, client, db, post, superadmin_id, make_member, sign_in): """Unlike a thread, which survives its author as "Miembro eliminado". A two-party exchange has no remainder to preserve, and keeping half of somebody's erased correspondence is what erasure exists to prevent.""" @@ -311,7 +311,7 @@ def test_erasing_a_member_takes_their_private_messages( content_type="multipart/form-data") name = db.execute("SELECT stored_name FROM attachments").fetchone()["stored_name"] - sign_in(owner_id) + sign_in(superadmin_id) post(f"/comunidad/miembros/{maria}/eliminar") for table in ("conversations", "conversation_members", "messages", "attachments"): @@ -320,14 +320,14 @@ def test_erasing_a_member_takes_their_private_messages( def test_erasing_a_member_removes_blocks_either_way( - client, db, post, owner_id, make_member, sign_in): + client, db, post, superadmin_id, make_member, sign_in): maria, jose = make_member("maria"), make_member("jose") sign_in(maria) post(f"/comunidad/privados/bloquear/{jose}") sign_in(jose) post(f"/comunidad/privados/bloquear/{maria}") - sign_in(owner_id) + sign_in(superadmin_id) post(f"/comunidad/miembros/{maria}/eliminar") assert db.execute("SELECT COUNT(*) AS n FROM blocks").fetchone()["n"] == 0 diff --git a/apps/board/tests/test_migrations.py b/apps/board/tests/test_migrations.py index 0bf5d20..6306dd8 100644 --- a/apps/board/tests/test_migrations.py +++ b/apps/board/tests/test_migrations.py @@ -181,28 +181,52 @@ def test_a_moderator_is_accepted_afterwards(old_db): def test_every_member_column_survives_the_rebuild(old_db): - """Thirteen columns copied by name. A typo in that list is a member losing - their email address, or their password, or their public page.""" - before = old_db.execute( - "SELECT id, gitea_login, display_name, email, role, active, created_by " - "FROM members ORDER BY id").fetchall() + """Thirteen columns copied by name, twice over now — steps 4 and 7 each + rebuild this table. A typo in either list is a member losing their email + address, or their password, or their public page. + + `role` is compared separately because step 7 deliberately changes exactly + one of them: see the test below.""" + columns = "id, gitea_login, display_name, email, active, created_by" + before = old_db.execute(f"SELECT {columns} FROM members ORDER BY id").fetchall() migrations.apply(old_db) - after = old_db.execute( - "SELECT id, gitea_login, display_name, email, role, active, created_by " - "FROM members ORDER BY id").fetchall() + after = old_db.execute(f"SELECT {columns} FROM members ORDER BY id").fetchall() assert [tuple(row) for row in after] == [tuple(row) for row in before] -def test_the_one_owner_rule_survives_the_rebuild(old_db): - """The partial unique index is not copied with the rows, so it has to be - recreated by hand. Without it the database silently stops being the thing - that guarantees one owner, and a bug in a handler becomes two owners.""" +def test_the_owner_becomes_the_superadmin(old_db): + """Step 7's one intended change to the data. The person who could already do + everything keeps being able to, nobody types anything, and the responsable + chair is left empty for the association to fill.""" + was_owner = old_db.execute( + "SELECT gitea_login FROM members WHERE role = 'owner'").fetchone()["gitea_login"] + migrations.apply(old_db) + + assert old_db.execute( + "SELECT role FROM members WHERE gitea_login = ?", (was_owner,) + ).fetchone()["role"] == "superadmin" + assert old_db.execute("SELECT COUNT(*) FROM members WHERE role = 'owner'" + ).fetchone()[0] == 0 + + +@pytest.mark.parametrize("chair", ["superadmin", "owner"]) +def test_both_single_chair_rules_survive_the_rebuild(old_db, chair): + """Neither partial unique index is copied with the rows, so both have to be + recreated by hand. Without them the database silently stops being the thing + that guarantees one of each, and a bug in a handler becomes two.""" + migrations.apply(old_db) + # The superadmin chair is already filled by the promotion; the responsable + # chair is empty, so it takes one insert to fill before the rule can bite. + if chair == "owner": + old_db.execute("INSERT INTO members (gitea_login, display_name, role) " + "VALUES ('primera', 'Primera', 'owner')") + with pytest.raises(sqlite3.IntegrityError): old_db.execute("INSERT INTO members (gitea_login, display_name, role) " - "VALUES ('otro', 'Otro', 'owner')") + f"VALUES ('otro', 'Otro', '{chair}')") def test_nothing_pointing_at_a_member_is_left_dangling(old_db): @@ -266,10 +290,13 @@ def test_the_app_starts_against_a_database_from_before_all_this(tmp_path): old_sql = old_sql.replace(" password_hash TEXT,\n", "") # …and predates the moderator role, so step 4 has a CHECK to widen here too. old_sql = old_sql.replace( - " role TEXT NOT NULL CHECK (role IN ('owner', 'admin', 'moderator',\n" + " role TEXT NOT NULL CHECK (role IN ('superadmin', 'owner', 'admin', 'moderator',\n" " 'user', 'tombstone')),", " role TEXT NOT NULL CHECK (role IN ('owner', 'admin', 'user', 'tombstone')),") assert "CHECK (role IN ('owner', 'admin', 'user', 'tombstone'))" in old_sql + old_sql = old_sql.replace( + "CREATE UNIQUE INDEX IF NOT EXISTS members_one_superadmin\n" + " ON members(role) WHERE role = 'superadmin';\n\n", "") old_sql += """ CREATE TABLE gitea_tokens ( member_id INTEGER PRIMARY KEY REFERENCES members(id) ON DELETE CASCADE, @@ -359,3 +386,57 @@ def test_step_six_drops_the_category_columns_and_keeps_the_rows(tmp_path): assert db.execute("PRAGMA user_version").fetchone()[0] == max( number for number, _, _ in migrations.STEPS) db.close() + + +def test_a_restart_does_not_demote_the_superadmin(tmp_path): + """The one that would have shipped silently. + + `_seed_superadmin` ends with `ON CONFLICT(gitea_login) DO UPDATE SET role = + …`. While owner was the top of the tree that line was right. Left as it was + after step 7, it would have matched BOARD_OWNER's login on every container + restart and set the role back to `owner` — a privilege *reduction* arriving + at no particular moment, caused by nothing anybody did, and leaving + `members_one_superadmin` free for somebody else to take the chair. + + Nothing about a single start-up catches that; it takes a second one. + """ + from apps.board.app import create_app + from apps.board.db import connect + + path = str(tmp_path / "board.db") + settings = {"SECRET_KEY": "x", "DB_PATH": path, "OWNER_LOGIN": "pablo", + "UPLOAD_DIR": str(tmp_path / "uploads"), "TESTING": True} + + create_app(settings) + create_app(settings) # the restart + create_app(settings) # and another, because containers do that + + db = connect(path) + rows = db.execute( + "SELECT gitea_login, role FROM members WHERE role IN ('superadmin', 'owner')" + ).fetchall() + assert [(r["gitea_login"], r["role"]) for r in rows] == [("pablo", "superadmin")] + db.close() + + +def test_a_second_superadmin_is_not_seeded_over_the_first(tmp_path): + """Changing BOARD_OWNER must not hand the platform to whoever can edit the + environment — a quieter escalation than it looks, since editing a compose + file draws far less attention than asking for access.""" + from apps.board.app import create_app + from apps.board.db import connect + + path = str(tmp_path / "board.db") + base = {"SECRET_KEY": "x", "DB_PATH": path, + "UPLOAD_DIR": str(tmp_path / "uploads"), "TESTING": True} + + create_app({**base, "OWNER_LOGIN": "pablo"}) + create_app({**base, "OWNER_LOGIN": "intruso"}) + + db = connect(path) + assert db.execute( + "SELECT gitea_login FROM members WHERE role = 'superadmin'" + ).fetchone()["gitea_login"] == "pablo" + assert db.execute( + "SELECT COUNT(*) FROM members WHERE gitea_login = 'intruso'").fetchone()[0] == 0 + db.close() diff --git a/apps/board/tests/test_profiles.py b/apps/board/tests/test_profiles.py index 76087fb..4614aa3 100644 --- a/apps/board/tests/test_profiles.py +++ b/apps/board/tests/test_profiles.py @@ -121,13 +121,13 @@ def test_the_bio_cannot_smuggle_html(client, published): @pytest.mark.parametrize("name", ["de", "pt-br", "categories", "admin", "comunidad", "robots", "DE"]) -def test_a_name_the_site_already_uses_is_refused(client, db, post, owner_id, +def test_a_name_the_site_already_uses_is_refused(client, db, post, superadmin_id, sign_in, name, monkeypatch): """Not because it would break the site — Caddy gives the static site every collision — but because their page would never load and nobody would know why.""" monkeypatch.setattr("apps.board.mail.send", lambda to, subject, body: None) - sign_in(owner_id) + sign_in(superadmin_id) post("/comunidad/miembros/nuevo", { "login": name, "display_name": "X", "email": "x@example.com", "role": "user", }) @@ -187,7 +187,7 @@ def test_a_board_picture_cannot_be_served_as_a_profile_photo( def test_erasing_a_member_takes_the_photo_off_disk( - app, client, db, post, owner_id, sign_in, published): + app, client, db, post, superadmin_id, sign_in, published): member_id = published() sign_in(member_id) post("/comunidad/mi-perfil", {"published": "on", "bio": "Hola", @@ -197,7 +197,7 @@ def test_erasing_a_member_takes_the_photo_off_disk( (member_id,)).fetchone()["photo_name"] assert (Path(app.config["UPLOAD_DIR"]) / name).exists() - sign_in(owner_id) + sign_in(superadmin_id) post(f"/comunidad/miembros/{member_id}/eliminar") assert not (Path(app.config["UPLOAD_DIR"]) / name).exists() @@ -264,7 +264,7 @@ def test_their_page_links_out_to_the_public_one_when_there_is_one( assert 'href="/maria"' in client.get("/comunidad/miembro/maria").get_data(as_text=True) -def test_an_erased_members_name_is_not_a_link(client, post, owner_id, +def test_an_erased_members_name_is_not_a_link(client, post, superadmin_id, make_member, sign_in): """The one name with no page behind it. An erased member's writing is reassigned to the tombstone, which is not a person and has nothing to @@ -274,7 +274,7 @@ def test_an_erased_members_name_is_not_a_link(client, post, owner_id, sign_in(maria) post("/comunidad/nuevo", {"title": "Hola", "body": "Qué tal"}) - sign_in(owner_id) + sign_in(superadmin_id) post(f"/comunidad/miembros/{maria}/eliminar") body = client.get("/comunidad/muro").get_data(as_text=True) diff --git a/apps/board/tests/test_reactions.py b/apps/board/tests/test_reactions.py index 81b5491..f1a49ba 100644 --- a/apps/board/tests/test_reactions.py +++ b/apps/board/tests/test_reactions.py @@ -101,8 +101,8 @@ def test_the_count_and_my_own_mark_show_on_the_page(client, post, thread, def test_reacting_to_something_that_is_gone_is_a_404(db, post, thread, - owner_id, make_member, sign_in): - sign_in(owner_id) + superadmin_id, make_member, sign_in): + sign_in(superadmin_id) post(f"/comunidad/tema/{thread}/eliminar") sign_in(make_member("maria")) @@ -138,13 +138,13 @@ def test_the_button_comes_back_to_the_comment_it_was_pressed_on( assert response.headers["Location"].endswith(f"/comunidad/tema/{thread}#c1") -def test_erasing_a_member_takes_their_reactions(db, post, thread, owner_id, +def test_erasing_a_member_takes_their_reactions(db, post, thread, superadmin_id, make_member, sign_in): maria = make_member("maria") sign_in(maria) react(post, "thread", thread) - sign_in(owner_id) + sign_in(superadmin_id) post(f"/comunidad/miembros/{maria}/eliminar") assert db.execute("SELECT COUNT(*) AS n FROM reactions").fetchone()["n"] == 0 diff --git a/apps/board/tests/test_submissions.py b/apps/board/tests/test_submissions.py index f24a8fb..5518258 100644 --- a/apps/board/tests/test_submissions.py +++ b/apps/board/tests/test_submissions.py @@ -364,7 +364,7 @@ def test_an_approved_one_cannot_be_edited_or_withdrawn( # --- erasure -------------------------------------------------------------- def test_erasing_the_author_takes_their_submissions_and_photos( - app, repo, db, post, owner_id, maria, sign_in): + app, repo, db, post, superadmin_id, maria, sign_in): """A submission is private writing, so it goes the way private messages do. What remains of an approved one is the post in the repository, which carries their name in a commit that is not ours to rewrite from here.""" @@ -372,14 +372,14 @@ def test_erasing_the_author_takes_their_submissions_and_photos( propose(post, picture=(io.BytesIO(PNG), "feria.png")) stored = only_submission(db)["photo_name"] - sign_in(owner_id) + sign_in(superadmin_id) post(f"/comunidad/miembros/{maria}/eliminar") assert db.execute("SELECT COUNT(*) AS n FROM submissions").fetchone()["n"] == 0 assert not (Path(app.config["UPLOAD_DIR"]) / stored).exists() -def test_erasing_a_reviewer_keeps_the_submission(db, post, owner_id, maria, +def test_erasing_a_reviewer_keeps_the_submission(db, post, superadmin_id, maria, make_member, sign_in): """Who reviewed something is a fact about the submission, not personal data of the reviewer, so the name goes and the row stays.""" @@ -390,7 +390,7 @@ def test_erasing_a_reviewer_keeps_the_submission(db, post, owner_id, maria, sign_in(reviewer) post(f"/comunidad/publicaciones/{submission_id}/rechazar", {"note": "Falta el dónde."}) - sign_in(owner_id) + sign_in(superadmin_id) post(f"/comunidad/miembros/{reviewer}/eliminar") row = only_submission(db) diff --git a/docs/server-setup.md b/docs/server-setup.md index e2ecba5..4e7cab7 100644 --- a/docs/server-setup.md +++ b/docs/server-setup.md @@ -521,43 +521,75 @@ has been archiving air" are otherwise the same empty line. ### 11.6 Who can do what -| | Responsable | Administrador | Moderador | Miembro | -|---|---|---|---|---| -| Wall: post, comment, edit own | ✓ | ✓ | ✓ | ✓ | -| Private messages, own profile | ✓ | ✓ | ✓ | ✓ | -| Propose a public post | ✓ | ✓ | ✓ | ✓ | -| Publish a public post directly | ✓ | ✓ | ✓ | — | -| Approve or return a proposal | ✓ | ✓ | ✓ | — | -| Edit and delete published posts | ✓ | ✓ | ✓ | — | -| Static pages of the site | ✓ | ✓ | — | — | -| Delete any wall post | ✓ | ✓ | — | — | -| Edit someone else's post | — | — | — | — | -| Pin and close threads | ✓ | ✓ | — | — | -| Create members and moderators | ✓ | ✓ | — | — | -| Change a role (below admin) | ✓ | ✓ | — | — | -| Create admins, promote to admin | ✓ | — | — | — | -| Suspend a member or moderator | ✓ | ✓ | — | — | -| Suspend an admin | ✓ | — | — | — | -| Transfer ownership, erase a member | ✓ | — | — | — | +Five roles, and **two of them are single chairs held by the database** rather +than by the application: a partial unique index each, so a bug in a handler +cannot produce a second of either. + +| | Superadministrador | Responsable | Administrador | Moderador | Miembro | +|---|---|---|---|---|---| +| Wall: post, comment, edit own | ✓ | ✓ | ✓ | ✓ | ✓ | +| Private messages, own profile | ✓ | ✓ | ✓ | ✓ | ✓ | +| Propose a public post | ✓ | ✓ | ✓ | ✓ | ✓ | +| Publish a public post directly | ✓ | ✓ | ✓ | ✓ | — | +| Approve or return a proposal | ✓ | ✓ | ✓ | ✓ | — | +| Edit and delete published posts | ✓ | ✓ | ✓ | ✓ | — | +| Static pages of the site | ✓ | ✓ | ✓ | — | — | +| Delete any wall post, pin and close | ✓ | ✓ | ✓ | — | — | +| Edit someone else's post | — | — | — | — | — | +| Create members and moderators | ✓ | ✓ | ✓ | — | — | +| Change a role below admin | ✓ | ✓ | ✓ | — | — | +| Suspend a member or moderator | ✓ | ✓ | ✓ | — | — | +| Erase a member | ✓ | ✓ | — | — | — | +| Name the responsable | ✓ | ✓ | — | — | — | +| **Create, promote, suspend an admin** | ✓ | — | — | — | — | +| **Marca: the look and the identity** | ✓ | — | — | — | — | +| **Estado del sistema, Registro** | ✓ | — | — | — | — | +| **Hand the platform on** | ✓ | — | — | — | — | + +**The two chairs do different jobs, and that is the point.** The +*superadministrador* runs the **platform**: admin accounts, the look, the +identity, the system tools. The *responsable* runs the **association**: members, +moderators, invitations, erasure. Installed for a second organisation, the first +is whoever maintains the box and the second is their president — which is what +makes the responsable chair safe to hand to a customer, and why an admin account +is not theirs to grant. + +**Neither chair can be touched by anybody, including themselves.** The +superadministrator because there is nothing above them; the responsable because +the chair belongs to the association, and a platform administrator quietly +removing the president of the organisation they host is exactly the move this +separation exists to prevent. Each steps down by handing their own chair on, and +whoever gives one up becomes an administrator — there is no role above the one +they just gave away. **A moderator has no power over people.** They decide what the public reads and nothing else: no creating, suspending, promoting or erasing anybody. That line is the whole point of having the role — a moderator who could also suspend the author of a post they had just returned would be a second kind of administrator. -Admins can appoint moderators; only the owner can appoint admins. That rule lives -in one place (`may_create` in `apps/board/members.py`) and the role form on -*Miembros* checks it twice: once for reaching the person, once for the role being -given. +Both rules live in one place each — `may_create` and `may_manage` in +`apps/board/members.py` — and the role picker on a member's page is built from +`assignable_roles(actor)`, the same predicate, so it can never offer a role the +handler will refuse. "This role or anything above it" is `is_at_least` in +`apps/board/security.py`, over one ordered `LADDER`: it replaced seven literal +tuples scattered through the app, each of which had silently excluded the +superadministrator the moment a tier appeared above owner. Nobody edits anyone else's words, administrators included. Taking a post down is visible to the person who wrote it; rewriting it is not, and an admin who could do that could leave a sentence attributed to a member who never wrote it. -There is exactly one owner, and the database enforces it with a unique index -rather than trusting the application to remember. The owner cannot be suspended -or demoted by anyone, themselves included — to step down, transfer ownership to -an admin. +**On upgrade**, migration 7 promotes the existing owner — Pablo — to +superadministrator and leaves the responsable chair empty. Nothing is erased and +nobody has to type anything: a superadministrator passes every check an owner +passed. The chair is filled from *Miembros* → somebody's page → **Nombrar +responsable** whenever there is somebody to put in it. + +`BOARD_OWNER` keeps its name and now seeds a superadministrator. It refuses to +change an existing one, so editing the environment cannot hand anybody the +platform — and the `ON CONFLICT` clause that writes the role is pinned to +`superadmin` for a reason worth knowing: left saying `owner`, it would have +demoted the superadministrator on every container restart. ### 11.7 Personal data