A superadministrator above the responsable

You asked for a super-admin, and most of it already existed as the `owner` role
— labelled «Responsable», seeded from BOARD_OWNER, already the only account that
could create an admin, demote one, erase anybody or hand the role on, with a
partial unique index making "exactly one" a database rule. You chose a genuine
fifth tier anyway, and there is a reading in which that is the better answer, so
this builds it with that reading made explicit:

  superadministrador — the platform: admin accounts, the look, the identity
  responsable        — the association: members, moderators, invitations

The split is worth more than a rename because of where this is going. Installed
for a second organisation, the superadministrator is whoever maintains the box
and the responsable is their president — so the responsable chair is safe to
hand to a customer, and an admin account is not theirs to grant.

Both chairs are unreachable, for different reasons. The superadministrator
because there is nothing above them. The responsable because the chair belongs
to the association: a platform administrator quietly removing the president of
the organisation they host is exactly the move two chairs exist 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.

Migration 7 is the rebuild migration 4 already did, for the same reason (SQLite
cannot alter a CHECK), and it promotes the existing owner — Pablo — to
superadministrator, leaving the responsable chair empty for the association to
fill. Nothing is erased; you offered and it was not needed.

Two things in here would have shipped silently without a test looking for them:

`_seed_superadmin` ends `ON CONFLICT(gitea_login) DO UPDATE SET role = …`. That
line was right while owner was the top of the tree. Left as it was, it would
have matched BOARD_OWNER's login and demoted the superadministrator back to
owner **on every container restart** — a privilege reduction caused by nothing
anybody did, freeing the chair for somebody else. It takes a second start-up to
catch, so the test starts the app three times.

And seven places outside the role modules asked "is this person at least an
admin" as a literal `("owner", "admin")` tuple — the wall's delete, the editor's
page collection, the calendar's edit flag, the dashboard, the moderation
predicate. Every one of them silently excluded the superadministrator the moment
a tier appeared above owner. They are now one ordered LADDER and one
`is_at_least`, so the next tier is a word in a list rather than an audit.

Marca moves from admin-only to superadmin-only, which is the distinction you
asked for: the look and the identity are the platform's.

564 tests pass, including the predicate table per actor and target, each of the
four doors into "make an admin" closed against an admin and against the
responsable, and both single-chair indexes surviving the rebuild.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NizVpJ2dwzCbjCrTLCjeHn
This commit is contained in:
admin 2026-10-06 11:55:41 +00:00
parent c2154b6f06
commit 1ff3522c56
No known key found for this signature in database
26 changed files with 801 additions and 276 deletions

View File

@ -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 # 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. # template would be the same string written twice, in two languages.
app.jinja_env.globals["tombstone_login"] = TOMBSTONE_LOGIN 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 @app.context_processor
def _year(): def _year():

View File

@ -21,7 +21,7 @@ from flask import (Blueprint, abort, current_app, flash, g, redirect,
from . import auth, uploads from . import auth, uploads
from .db import get_db from .db import get_db
from .render import excerpt, to_html 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__) bp = Blueprint("board", __name__)
@ -31,7 +31,7 @@ BODY_MAX = 20_000
def is_admin() -> bool: def is_admin() -> bool:
return g.member["role"] in ("owner", "admin") return is_at_least(g.member["role"], "admin")
def may_delete(row) -> bool: def may_delete(row) -> bool:

View File

@ -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 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. 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 ### The two destinations
One form, saved to two places, because the two halves cannot read the same 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 . import gitea, uploads
from .db import get_db from .db import get_db
from .security import admin_required from .security import superadmin_required
bp = Blueprint("brand", __name__) bp = Blueprint("brand", __name__)
@ -364,7 +372,7 @@ def _read_picture(field: str, allowed: tuple[str, ...], errors: list[str]):
# --- routes ---------------------------------------------------------------- # --- routes ----------------------------------------------------------------
@bp.route("/gestion/marca", methods=["GET", "POST"]) @bp.route("/gestion/marca", methods=["GET", "POST"])
@admin_required @superadmin_required
def edit(): def edit():
if request.method == "GET": if request.method == "GET":
state = current() state = current()
@ -439,7 +447,7 @@ def _store(stored: dict, css: str, logo, favicon, state: dict) -> None:
@bp.route("/gestion/marca/publicar", methods=["POST"]) @bp.route("/gestion/marca/publicar", methods=["POST"])
@admin_required @superadmin_required
def publish(): def publish():
"""Try the commits again after the git server was unreachable.""" """Try the commits again after the git server was unreachable."""
if _publish(): if _publish():
@ -448,7 +456,7 @@ def publish():
@bp.route("/gestion/marca/restaurar", methods=["POST"]) @bp.route("/gestion/marca/restaurar", methods=["POST"])
@admin_required @superadmin_required
def restore(): def restore():
"""Back to the colours the site was built with. """Back to the colours the site was built with.

View File

@ -33,7 +33,7 @@ from flask import (Blueprint, abort, current_app, flash, g, redirect,
from . import gitea from . import gitea
from .db import get_db from .db import get_db
from .render import to_html 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 # 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 # knows what each one looks like on the wire, so the editor and the board
# cannot drift apart about what a picture is. # cannot drift apart about what a picture is.
@ -233,7 +233,7 @@ def _collection_or_404(collection: str) -> dict:
if collection not in COLLECTIONS: if collection not in COLLECTIONS:
abort(404) abort(404)
meta = COLLECTIONS[collection] 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) abort(403)
return meta return meta
@ -242,7 +242,7 @@ def visible_collections() -> dict:
"""The collections this member may write to, for the tabs. A tab that only """The collections this member may write to, for the tabs. A tab that only
ever produces a 403 is worse than no tab.""" ever produces a 403 is worse than no tab."""
return {name: meta for name, meta in COLLECTIONS.items() 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: def _name_or_404(name: str) -> str:

View File

@ -65,7 +65,7 @@ def init_db(app) -> None:
for step in migrations.apply(db): for step in migrations.apply(db):
app.logger.info("Applied migration %s", step) app.logger.info("Applied migration %s", step)
_ensure_tombstone(db) _ensure_tombstone(db)
_seed_owner(db, app) _seed_superadmin(db, app)
finally: finally:
db.close() db.close()
@ -79,35 +79,49 @@ def _ensure_tombstone(db: sqlite3.Connection) -> None:
) )
def _seed_owner(db: sqlite3.Connection, app) -> None: def _seed_superadmin(db: sqlite3.Connection, app) -> None:
"""Create the first owner from BOARD_OWNER, once. """Create the first superadministrator from BOARD_OWNER, once.
Deliberately refuses to change an existing owner. Were this to overwrite, Still `BOARD_OWNER` rather than a new name: it is the variable the server's
anyone who could edit the environment could hand themselves ownership by `.env` already carries, and an install that has to edit its environment to
restarting the container — which is a quieter privilege escalation than it survive an upgrade is an install that breaks on upgrade.
looks, since editing a compose file draws far less attention than asking
the owner for access. 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() 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 existing:
if login and existing["gitea_login"].lower() != login.lower(): if login and existing["gitea_login"].lower() != login.lower():
app.logger.warning( app.logger.warning(
"BOARD_OWNER is %r but the owner is %r; leaving it alone. " "BOARD_OWNER is %r but the superadministrator is %r; leaving it "
"Transfer ownership from inside the app instead.", "alone. Hand the platform on from inside the app instead.",
login, existing["gitea_login"], login, existing["gitea_login"],
) )
return return
if not login: 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 return
db.execute( db.execute(
"""INSERT INTO members (gitea_login, display_name, role, active) """INSERT INTO members (gitea_login, display_name, role, active)
VALUES (?, ?, 'owner', 1) VALUES (?, ?, 'superadmin', 1)
ON CONFLICT(gitea_login) DO UPDATE SET role = 'owner', active = 1""", ON CONFLICT(gitea_login) DO UPDATE SET role = 'superadmin', active = 1""",
(login, login), (login, login),
) )
app.logger.info("Seeded %r as owner.", login) app.logger.info("Seeded %r as superadministrator.", login)

View File

@ -32,7 +32,7 @@ from flask import (Blueprint, Response, abort, flash, g, redirect,
from . import content, gitea, uploads from . import content, gitea, uploads
from .db import get_db from .db import get_db
from .render import to_html 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__) bp = Blueprint("events", __name__)
@ -129,7 +129,7 @@ def month():
this_month=f"{today.year:04d}-{today.month:02d}", this_month=f"{today.year:04d}-{today.month:02d}",
today=today.day if (today.year, today.month) == (year, number) else 0, today=today.day if (today.year, today.month) == (year, number) else 0,
public_missing=public_missing, 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, return render_template("event.html", event=row,
body_html=to_html(row["body_md"] or ""), body_html=to_html(row["body_md"] or ""),
when=_spoken_date(row["starts_on"]), 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/<int:event_id>.ics") @bp.route("/calendario/<int:event_id>.ics")

View File

@ -18,7 +18,7 @@ from flask import Blueprint, g, jsonify, render_template, request, url_for
from . import submissions from . import submissions
from .db import TOMBSTONE_LOGIN, get_db from .db import TOMBSTONE_LOGIN, get_db
from .render import excerpt, to_html from .render import excerpt, to_html
from .security import admin_required, csrf_token, login_required from .security import admin_required, csrf_token, is_at_least, login_required
bp = Blueprint("home", __name__) bp = Blueprint("home", __name__)
@ -126,7 +126,7 @@ def session_state():
{"label": "Publicaciones", "url": url_for("submissions.index")}, {"label": "Publicaciones", "url": url_for("submissions.index")},
{"label": "Calendario", "url": url_for("events.month")}, {"label": "Calendario", "url": url_for("events.month")},
] ]
if g.member["role"] in ("owner", "admin"): if is_at_least(g.member["role"], "admin"):
sections.append({"label": "Gestión", "url": url_for("home.gestion")}) sections.append({"label": "Gestión", "url": url_for("home.gestion")})
return _no_store(jsonify({ return _no_store(jsonify({

View File

@ -1,11 +1,14 @@
"""Members and roles. """Members and roles.
Four roles, and the rules between them are short enough to state in full: Five roles, and the rules between them are short enough to state in full:
* exactly one **owner**, who creates and removes admins and can hand ownership * exactly one **superadministrador**, who runs the platform: admin accounts,
on; nobody can deactivate or demote them, including themselves the look, the identity and the system tools. Nobody can deactivate, demote or
* **admins** create, deactivate and promote members, moderate the board, and erase them, including themselves
publish and edit the static pages of the public site * exactly one **responsable**, who runs the association: members, moderators
and invitations. They cannot touch an admin, the look or the identity
* **admins** create, deactivate and promote members and moderators, moderate
the board, and publish and edit the static pages of the public site
* **moderators** approve or reject what members propose for the public site, * **moderators** approve or reject what members propose for the public site,
and publish their own posts without waiting for anybody. They have no power and publish their own posts without waiting for anybody. They have no power
over people: moderating content is not the same authority, and giving one the over people: moderating content is not the same authority, and giving one the
@ -30,7 +33,8 @@ from flask import (Blueprint, Response, abort, current_app, flash, g, redirect,
from . import auth, invites, mail, messages, profiles, uploads from . import auth, invites, mail, messages, profiles, uploads
from .db import TOMBSTONE_LOGIN, get_db from .db import TOMBSTONE_LOGIN, get_db
from .render import to_html from .render import to_html
from .security import admin_required, login_required, owner_required from .security import (admin_required, login_required, owner_required,
superadmin_required)
bp = Blueprint("members", __name__) bp = Blueprint("members", __name__)
@ -41,20 +45,35 @@ LOGIN_RE = re.compile(r"^[A-Za-z0-9]([A-Za-z0-9._-]{0,38}[A-Za-z0-9])?$")
# "Miembro" rather than "Usuario" on the screens, while the stored value stays # "Miembro" rather than "Usuario" on the screens, while the stored value stays
# `user`: renaming the value would mean a migration and rewriting every role # `user`: renaming the value would mean a migration and rewriting every role
# check for a word nobody types. # check for a word nobody types.
ROLE_LABELS = {"owner": "Responsable", "admin": "Administrador", ROLE_LABELS = {"superadmin": "Superadministrador", "owner": "Responsable",
"moderator": "Moderador", "user": "Miembro"} "admin": "Administrador", "moderator": "Moderador",
"user": "Miembro"}
# Who may be given which role on the Miembros screen, most trusted first, so # Who may be given which role, by whom. A function rather than the constant it
# the form and the predicates below cannot disagree about the list. # used to be, because the answer now depends on who is asking: the role picker
ASSIGNABLE_ROLES = ("admin", "moderator", "user") # must never offer what the handler will refuse, and with two levels above admin
# a single list can only be right for one of them.
def assignable_roles(actor_role: str) -> tuple[str, ...]:
return tuple(role for role in ("admin", "moderator", "user")
if may_create(actor_role, role))
def may_create(actor_role: str, target_role: str) -> bool: def may_create(actor_role: str, target_role: str) -> bool:
"""Who may bring whom in. Admins cannot mint more admins.""" """Who may bring whom in.
**An admin account is the superadministrator's alone** — that is the line
this phase exists to draw. The responsable runs the association and can fill
it with members and moderators; who administers the platform is not theirs
to decide, which is what makes it safe to hand the responsable chair to a
customer organisation's president.
Nobody creates a superadministrator or a responsable here. Both are single
chairs held by a unique index, and both change hands by transfer, below.
"""
if target_role == "admin": if target_role == "admin":
return actor_role == "owner" return actor_role == "superadmin"
if target_role in ("moderator", "user"): if target_role in ("moderator", "user"):
return actor_role in ("owner", "admin") return actor_role in ("superadmin", "owner", "admin")
return False return False
@ -64,12 +83,20 @@ def may_manage(actor_role: str, target_role: str) -> bool:
A moderator appears nowhere in this function, deliberately: they approve A moderator appears nowhere in this function, deliberately: they approve
posts and nothing else. Being trusted to judge what the public reads is not posts and nothing else. Being trusted to judge what the public reads is not
the same as being trusted to suspend the person who wrote it. the same as being trusted to suspend the person who wrote it.
The two chairs are out of reach by the same rule that put them there. A
superadministrator cannot be suspended or demoted by anybody, themselves
included — the way out is to hand the platform on. The responsable is out of
reach of everyone below, and of the superadministrator too: the chair is the
association's, and a platform administrator quietly removing the president
of the organisation they host is exactly the move this separation exists to
make impossible. Transferring it is the association's own act.
""" """
if target_role == "owner": if target_role in ("superadmin", "owner"):
return False # the owner is out of reach of everyone, themselves included return False
if target_role == "admin": if target_role == "admin":
return actor_role == "owner" return actor_role == "superadmin"
return actor_role in ("owner", "admin") return actor_role in ("superadmin", "owner", "admin")
def tombstone_id(db: sqlite3.Connection) -> int: def tombstone_id(db: sqlite3.Connection) -> int:
@ -77,17 +104,28 @@ def tombstone_id(db: sqlite3.Connection) -> int:
return row["id"] return row["id"]
def transfer_ownership(db: sqlite3.Connection, owner_id: int, target_id: int) -> None: def transfer_ownership(db: sqlite3.Connection, holder_id: int, target_id: int,
"""Hand ownership to an admin, atomically. chair: str) -> None:
"""Hand one of the two chairs on, atomically.
The demotion has to come first. With the partial unique index in place, a The demotion has to come first. With the partial unique index in place, a
promote-then-demote order would momentarily ask for two owners and the promote-then-demote order would momentarily ask for two holders of the chair
database would refuse — correctly, but confusingly. and the database would refuse — correctly, but confusingly.
`chair` is 'superadmin' or 'owner' and comes from the route, never from a
request. The person giving it up becomes an admin, which is the most they
can be left with: there is no role above the one they just gave away.
Filling an empty chair is the same call with nobody to demote — the first
UPDATE matches no row and the transaction is one statement shorter.
""" """
if chair not in ("superadmin", "owner"):
raise ValueError(f"not a chair: {chair!r}")
db.execute("BEGIN IMMEDIATE") db.execute("BEGIN IMMEDIATE")
try: try:
db.execute("UPDATE members SET role = 'admin' WHERE id = ?", (owner_id,)) db.execute("UPDATE members SET role = 'admin' WHERE id = ? AND role = ?",
db.execute("UPDATE members SET role = 'owner' WHERE id = ?", (target_id,)) (holder_id, chair))
db.execute("UPDATE members SET role = ? WHERE id = ?", (chair, target_id))
db.execute("COMMIT") db.execute("COMMIT")
except Exception: except Exception:
db.execute("ROLLBACK") db.execute("ROLLBACK")
@ -319,7 +357,7 @@ def new():
if request.method == "GET": if request.method == "GET":
return render_template( return render_template(
"member_new.html", "member_new.html",
can_make_admin=g.member["role"] == "owner", can_make_admin=may_create(g.member["role"], "admin"),
# Without mail the invitation cannot leave the building, so the # Without mail the invitation cannot leave the building, so the
# admin has to pass the link on by hand. Worth knowing before # admin has to pass the link on by hand. Worth knowing before
# filling the form rather than after. # filling the form rather than after.
@ -454,7 +492,7 @@ def set_role(member_id: int):
""" """
target = _load(member_id) target = _load(member_id)
role = request.form.get("role", "") role = request.form.get("role", "")
if role not in ASSIGNABLE_ROLES: if role not in assignable_roles(g.member["role"]):
abort(403) abort(403)
if not may_manage(g.member["role"], target["role"]): if not may_manage(g.member["role"], target["role"]):
abort(403) abort(403)
@ -468,12 +506,34 @@ def set_role(member_id: int):
@bp.route("/miembros/<int:member_id>/transferir", methods=["POST"]) @bp.route("/miembros/<int:member_id>/transferir", methods=["POST"])
@owner_required @owner_required
def transfer(member_id: int): def transfer(member_id: int):
"""Hand the association on. The responsable's own act, or the
superadministrator filling an empty chair."""
target = _load(member_id)
if target["role"] not in ("admin", "moderator", "user") or not target["active"]:
flash("Solo puedes nombrar responsable a un miembro activo.", "error")
return redirect(_page(target))
transfer_ownership(get_db(), g.member["id"], target["id"], "owner")
flash(f"{target['display_name']} es ahora el responsable.", "ok")
return redirect(_page(target))
@bp.route("/miembros/<int:member_id>/transferir-plataforma", methods=["POST"])
@superadmin_required
def transfer_platform(member_id: int):
"""Hand the platform on.
Separate from the route above because they are different jobs, and because
conflating them is how somebody hands away more than they meant to: this one
is irreversible from the giver's side — the moment it commits, the person
running it is an admin and cannot take it back.
"""
target = _load(member_id) target = _load(member_id)
if target["role"] != "admin" or not target["active"]: if target["role"] != "admin" or not target["active"]:
flash("Solo puedes transferir la titularidad a un administrador activo.", "error") flash("Solo puedes entregar la plataforma a un administrador activo.", "error")
return redirect(_page(target)) return redirect(_page(target))
transfer_ownership(get_db(), g.member["id"], target["id"]) transfer_ownership(get_db(), g.member["id"], target["id"], "superadmin")
flash(f"{target['display_name']} es ahora el responsable. Tú eres administrador.", "ok") flash(f"{target['display_name']} es ahora el superadministrador. "
"Tú eres administrador.", "ok")
return redirect(_page(target)) return redirect(_page(target))
@ -481,7 +541,10 @@ def transfer(member_id: int):
@owner_required @owner_required
def erase(member_id: int): def erase(member_id: int):
target = _load(member_id) target = _load(member_id)
if target["role"] == "owner": # Through the predicate rather than a bare role test: the two chairs are
# unreachable by exactly the rule that protects them everywhere else, and a
# second spelling of it here is a second place to get it wrong.
if not may_manage(g.member["role"], target["role"]):
abort(403) abort(403)
# Files only after the transaction has committed: a rollback can put the # Files only after the transaction has committed: a rollback can put the
# rows back, and nothing can put the pictures back. # rows back, and nothing can put the pictures back.

View File

@ -249,6 +249,70 @@ def _no_more_categories(db: sqlite3.Connection) -> None:
db.execute(f"ALTER TABLE {table} DROP COLUMN categories") db.execute(f"ALTER TABLE {table} DROP COLUMN categories")
def _a_superadmin_above_the_owner(db: sqlite3.Connection) -> None:
"""Add the `superadmin` role, and give it to whoever is the owner today.
The same rebuild as step 4, for the same reason — `role` carries a CHECK and
SQLite has no DROP CONSTRAINT — so the notes there about the eight tables
that reference `members`, about the rename, and about foreign keys being off
outside the transaction all apply here unchanged. Two things are particular
to this step:
* **Both partial unique indexes have to be created afterwards.** The copy
carries neither. Losing `members_one_owner` would quietly allow a second
responsable, and never creating `members_one_superadmin` would allow two
superadministrators — which is the one rule this whole phase rests on.
* **The existing owner is promoted.** Nobody has to type anything, nothing
is erased, and the person who could already do everything keeps being able
to. It leaves the responsable chair empty, which breaks nothing: a
superadministrator passes every check an owner passes, and the chair is
filled from inside the app whenever there is somebody to put in it.
"""
if "superadmin" in _role_check(db):
return
db.execute("""
CREATE TABLE members_new (
id INTEGER PRIMARY KEY,
gitea_login TEXT NOT NULL UNIQUE COLLATE NOCASE,
display_name TEXT NOT NULL DEFAULT '',
email TEXT NOT NULL DEFAULT '',
password_hash TEXT,
profile_published INTEGER NOT NULL DEFAULT 0 CHECK (profile_published IN (0, 1)),
bio TEXT,
links TEXT,
photo_name TEXT,
role TEXT NOT NULL CHECK (role IN ('superadmin', 'owner', 'admin',
'moderator', 'user', 'tombstone')),
active INTEGER NOT NULL DEFAULT 1 CHECK (active IN (0, 1)),
created_at TEXT NOT NULL DEFAULT (datetime('now')),
created_by INTEGER REFERENCES members(id),
last_seen_at TEXT
)""")
db.execute("""
INSERT INTO members_new
(id, gitea_login, display_name, email, password_hash,
profile_published, bio, links, photo_name,
role, active, created_at, created_by, last_seen_at)
SELECT id, gitea_login, display_name, email, password_hash,
profile_published, bio, links, photo_name,
role, active, created_at, created_by, last_seen_at
FROM members""")
db.execute("DROP TABLE members")
db.execute("ALTER TABLE members_new RENAME TO members")
# Promoted before the indexes exist, so the row is never momentarily both
# the only owner and the only superadmin under two rules at once.
db.execute("UPDATE members SET role = 'superadmin' WHERE role = 'owner'")
db.execute("""CREATE UNIQUE INDEX IF NOT EXISTS members_one_superadmin
ON members(role) WHERE role = 'superadmin'""")
db.execute("""CREATE UNIQUE INDEX IF NOT EXISTS members_one_owner
ON members(role) WHERE role = 'owner'""")
broken = db.execute("PRAGMA foreign_key_check").fetchall()
if broken:
raise RuntimeError(f"migration left dangling references: {broken}")
# (number, description, function). The number is the value written to # (number, description, function). The number is the value written to
# user_version once the step succeeds. # user_version once the step succeeds.
STEPS = [ STEPS = [
@ -258,6 +322,7 @@ STEPS = [
(4, "members can be moderators", _members_can_moderate), (4, "members can be moderators", _members_can_moderate),
(5, "events carry a date of their own", _rooms_for_a_date_of_its_own), (5, "events carry a date of their own", _rooms_for_a_date_of_its_own),
(6, "there are no categories any more", _no_more_categories), (6, "there are no categories any more", _no_more_categories),
(7, "a superadministrator above the responsable", _a_superadmin_above_the_owner),
] ]

View File

@ -20,9 +20,10 @@ CREATE TABLE IF NOT EXISTS members (
bio TEXT, bio TEXT,
links TEXT, -- JSON array of {label, url} links TEXT, -- JSON array of {label, url}
photo_name TEXT, photo_name TEXT,
-- 'moderator' arrived with migration 4, which had to rebuild this table: -- 'moderator' arrived with migration 4 and 'superadmin' with migration 7,
-- SQLite has no DROP CONSTRAINT, so widening a CHECK is never an ALTER. -- each of which had to rebuild this table: SQLite has no DROP CONSTRAINT, so
role TEXT NOT NULL CHECK (role IN ('owner', 'admin', 'moderator', -- widening a CHECK is never an ALTER.
role TEXT NOT NULL CHECK (role IN ('superadmin', 'owner', 'admin', 'moderator',
'user', 'tombstone')), 'user', 'tombstone')),
active INTEGER NOT NULL DEFAULT 1 CHECK (active IN (0, 1)), active INTEGER NOT NULL DEFAULT 1 CHECK (active IN (0, 1)),
created_at TEXT NOT NULL DEFAULT (datetime('now')), created_at TEXT NOT NULL DEFAULT (datetime('now')),
@ -30,9 +31,17 @@ CREATE TABLE IF NOT EXISTS members (
last_seen_at TEXT last_seen_at TEXT
); );
-- The one-owner rule, held by the database rather than by the application, so -- Two chairs, one person each, held by the database rather than by the
-- a mistake in a handler cannot produce a second owner. SQLite enforces a -- application, so a mistake in a handler cannot produce a second of either.
-- partial unique index exactly like a full one. -- SQLite enforces a partial unique index exactly like a full one.
-- The superadministrator runs the platform — admin accounts, the look
-- and the identity — and the responsable runs the association — the members,
-- the moderators and the invitations. Installed for a second organisation, the
-- first is whoever maintains the box and the second is their president, which
-- is the whole reason the two are separate rows rather than one.
CREATE UNIQUE INDEX IF NOT EXISTS members_one_superadmin
ON members(role) WHERE role = 'superadmin';
CREATE UNIQUE INDEX IF NOT EXISTS members_one_owner CREATE UNIQUE INDEX IF NOT EXISTS members_one_owner
ON members(role) WHERE role = 'owner'; ON members(role) WHERE role = 'owner';

View File

@ -43,12 +43,38 @@ def login_required(view):
return wrapped return wrapped
# Most trusted first. Every decorator below is "this role or anything above it",
# which is the one rule worth keeping in a list rather than in four functions:
# adding a tier then means adding a word here, not auditing every check.
LADDER = ("superadmin", "owner", "admin", "moderator", "user")
def _at_least(rank: str):
"""The roles that pass a check for `rank` — it and everything above it."""
return LADDER[:LADDER.index(rank) + 1]
def is_at_least(role: str, rank: str) -> bool:
"""`role` is `rank` or anything above it.
Exported because seven places outside this module had the same question
written as a literal tuple — `g.member["role"] in ("owner", "admin")` — and
every one of them silently excluded the superadministrator the moment a tier
was added above owner. A tuple is a copy of a rule; this is the rule.
"""
return role in _at_least(rank)
def admin_required(view): def admin_required(view):
"""Owner counts as an admin. Admin does not count as owner.""" """The superadministrator and the responsable both count as admins.
Not the other way round: an admin is not a responsable, and neither is a
responsable the superadministrator.
"""
@wraps(view) @wraps(view)
@login_required @login_required
def wrapped(*args, **kwargs): def wrapped(*args, **kwargs):
if g.member["role"] not in ("owner", "admin"): if g.member["role"] not in _at_least("admin"):
abort(403) abort(403)
return view(*args, **kwargs) return view(*args, **kwargs)
return wrapped return wrapped
@ -65,17 +91,39 @@ def moderator_required(view):
@wraps(view) @wraps(view)
@login_required @login_required
def wrapped(*args, **kwargs): def wrapped(*args, **kwargs):
if g.member["role"] not in ("owner", "admin", "moderator"): if g.member["role"] not in _at_least("moderator"):
abort(403) abort(403)
return view(*args, **kwargs) return view(*args, **kwargs)
return wrapped return wrapped
def owner_required(view): def owner_required(view):
"""The association's chair. The superadministrator passes it too.
Everything the responsable may do, the superadministrator may do; the
reverse is the whole point of there being two roles, and is
`superadmin_required` below.
"""
@wraps(view) @wraps(view)
@login_required @login_required
def wrapped(*args, **kwargs): def wrapped(*args, **kwargs):
if g.member["role"] != "owner": if g.member["role"] not in _at_least("owner"):
abort(403)
return view(*args, **kwargs)
return wrapped
def superadmin_required(view):
"""The platform: admin accounts, the look, the identity, the system tools.
The only check with nothing above it. A responsable who wants one of these
screens is a responsable who should be asking the person who installed this,
which is exactly the line the two roles are drawn along.
"""
@wraps(view)
@login_required
def wrapped(*args, **kwargs):
if g.member["role"] != "superadmin":
abort(403) abort(403)
return view(*args, **kwargs) return view(*args, **kwargs)
return wrapped return wrapped

View File

@ -33,7 +33,7 @@ from flask import (Blueprint, abort, current_app, flash, g, redirect,
from . import content, gitea, uploads from . import content, gitea, uploads
from .db import get_db from .db import get_db
from .render import excerpt, to_html from .render import excerpt, to_html
from .security import login_required, moderator_required from .security import is_at_least, login_required, moderator_required
bp = Blueprint("submissions", __name__) bp = Blueprint("submissions", __name__)
@ -54,7 +54,7 @@ STATE_LABELS = {
def may_moderate(member=None) -> bool: def may_moderate(member=None) -> bool:
member = member or g.member member = member or g.member
return member is not None and member["role"] in ("owner", "admin", "moderator") return member is not None and is_at_least(member["role"], "moderator")
def pending_count() -> int: def pending_count() -> int:

View File

@ -53,6 +53,7 @@
</p> </p>
</section> </section>
{% if g.member.role == 'superadmin' %}
<section class="panel"> <section class="panel">
<div class="panel__head"> <div class="panel__head">
<h2>Marca</h2> <h2>Marca</h2>
@ -67,6 +68,7 @@
volver a lo de fábrica. volver a lo de fábrica.
</p> </p>
</section> </section>
{% endif %}
{% if counts.pending %} {% if counts.pending %}
<section class="panel panel--attention"> <section class="panel panel--attention">

View File

@ -14,8 +14,13 @@
{% block title %}{{ member.display_name }}{% endblock %} {% block title %}{{ member.display_name }}{% endblock %}
{% set me = g.member %} {% set me = g.member %}
{% set is_owner = me.role == 'owner' %} {# The template mirrors the predicates in members.py rather than restating
{% set is_admin = me.role in ('owner', 'admin') %} them: `can_assign` is the same list the handler will accept, so the picker
cannot offer a role that comes back 403. #}
{% set is_super = me.role == 'superadmin' %}
{% set is_chair = me.role in ('superadmin', 'owner') %}
{% set is_admin = me.role in ('superadmin', 'owner', 'admin') %}
{% set can_assign = assignable_roles(me.role) %}
{% block main %} {% block main %}
<div class="feed-head"> <div class="feed-head">
@ -139,7 +144,7 @@
{% endif %} {% endif %}
{% endif %} {% endif %}
{% if is_admin and member.role != 'owner' and not is_me %} {% if is_admin and member.role not in ('superadmin', 'owner') and not is_me %}
{# Moved here from the directory cards. A <details>, not a script: the CSP has {# Moved here from the directory cards. A <details>, not a script: the CSP has
no 'unsafe-inline'. Every button is still checked in its handler — this block no 'unsafe-inline'. Every button is still checked in its handler — this block
being hidden from a moderator is a courtesy, not the rule. #} being hidden from a moderator is a courtesy, not the rule. #}
@ -164,36 +169,48 @@
</form> </form>
{% endif %} {% endif %}
{% if is_owner or member.role != 'admin' %} {% if member.role in can_assign or member.role not in ('admin',) %}
<form class="inline-form" method="post" <form class="inline-form" method="post"
action="{{ url_for('members.set_role', member_id=member.id) }}"> action="{{ url_for('members.set_role', member_id=member.id) }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"> <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<label class="sr-only" for="role">Rol de {{ member.display_name }}</label> <label class="sr-only" for="role">Rol de {{ member.display_name }}</label>
<select id="role" name="role"> <select id="role" name="role">
<option value="user" {{ 'selected' if member.role == 'user' }}>Miembro</option> {% for role in can_assign %}
<option value="moderator" {{ 'selected' if member.role == 'moderator' }}>Moderador</option> <option value="{{ role }}" {{ 'selected' if member.role == role }}>{{ labels[role] }}</option>
{% if is_owner %} {% endfor %}
<option value="admin" {{ 'selected' if member.role == 'admin' }}>Administrador</option>
{% endif %}
</select> </select>
<button class="linkish" type="submit">Cambiar rol</button> <button class="linkish" type="submit">Cambiar rol</button>
</form> </form>
{% endif %} {% endif %}
{% if is_owner %} {% if is_chair and member.active %}
{% if member.role == 'admin' and member.active %} {# Naming the responsable: the association's chair. The superadministrator
<form method="post" action="{{ url_for('members.transfer', member_id=member.id) }}" can fill it when it is empty — a fresh install has nobody in it — and
data-confirm="Vas a dejar de ser el responsable y {{ member.display_name }} pasará a serlo. ¿Seguro?"> the responsable can hand it on. #}
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"> <form method="post" action="{{ url_for('members.transfer', member_id=member.id) }}"
<button class="linkish" type="submit">Transferir titularidad</button> data-confirm="{{ member.display_name }} pasará a ser el responsable de la asociación. ¿Seguro?">
</form> <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
{% endif %} <button class="linkish" type="submit">Nombrar responsable</button>
</form>
{% endif %}
<form method="post" action="{{ url_for('members.erase', member_id=member.id) }}" {% if is_super and member.role == 'admin' and member.active %}
data-confirm="Se borrarán sus datos personales. Sus mensajes quedarán como «Miembro eliminado». ¿Seguro?"> {# Handing the platform on. Its own button, and its own sentence, because
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"> it is irreversible from this side: the moment it commits you are an
<button class="linkish linkish--danger" type="submit">Eliminar</button> administrator and cannot take it back. #}
</form> <form method="post" action="{{ url_for('members.transfer_platform', member_id=member.id) }}"
data-confirm="{{ member.display_name }} pasará a ser el superadministrador y tú pasarás a ser administrador. No podrás deshacerlo tú mismo. ¿Seguro?">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<button class="linkish linkish--danger" type="submit">Entregar la plataforma</button>
</form>
{% endif %}
{% if is_chair %}
<form method="post" action="{{ url_for('members.erase', member_id=member.id) }}"
data-confirm="Se borrarán sus datos personales. Sus mensajes quedarán como «Miembro eliminado». ¿Seguro?">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<button class="linkish linkish--danger" type="submit">Eliminar</button>
</form>
{% endif %} {% endif %}
{% if member.email %}<p class="muted small">{{ member.email }}</p>{% endif %} {% if member.email %}<p class="muted small">{{ member.email }}</p>{% endif %}

View File

@ -64,10 +64,11 @@
{% if is_admin %} {% if is_admin %}
<p class="muted small"> <p class="muted small">
Hay un solo responsable. El responsable da de alta administradores; los Hay un solo superadministrador y un solo responsable. El superadministrador
administradores dan de alta miembros y moderadores. Suspender, cambiar el rol, lleva la plataforma: las cuentas de administrador, el aspecto y la identidad
reenviar la invitación y eliminar están en la ficha de cada persona, bajo del sitio. El responsable lleva la asociación: los miembros, los moderadores
«Gestionar». y las invitaciones. Suspender, cambiar el rol, reenviar la invitación y
eliminar están en la ficha de cada persona, bajo «Gestionar».
</p> </p>
{% endif %} {% endif %}
{% endblock %} {% endblock %}

View File

@ -65,9 +65,23 @@ def make_member(db):
return _make 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 @pytest.fixture
def owner_id(db): 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 @pytest.fixture

View File

@ -99,10 +99,12 @@ def test_an_unreadable_pair_warns_and_a_readable_one_does_not():
# --- the form ------------------------------------------------------------- # --- the form -------------------------------------------------------------
@pytest.fixture @pytest.fixture
def admin(make_member, sign_in): def admin(superadmin_id, sign_in):
member_id = make_member("admina", role="admin") """The superadministrator. Named `admin` because every test below reads
sign_in(member_id) "signed in as the person who may change this", and that person is no longer
return member_id 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 # 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) return post("/comunidad/gestion/marca", data, **sent)
def test_only_admins_reach_it(client, post, make_member, sign_in): def test_only_the_superadmin_reaches_it(client, post, make_member, sign_in):
for role in ("user", "moderator"): """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)) sign_in(make_member(f"persona-{role}", role=role))
assert client.get("/comunidad/gestion/marca").status_code == 403 assert client.get("/comunidad/gestion/marca").status_code == 403
assert save(post, **{"token-brand": "#1b5e20"}).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 -------------------------------------------------------------- # --- erasure --------------------------------------------------------------
def test_erasing_the_admin_leaves_the_brand_standing(client, db, post, owner_id, def test_erasing_whoever_set_the_brand_leaves_it_standing(client, db, post, admin,
make_member, sign_in): make_member):
"""The colours belong to the association, like an event in the calendar. """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 Whoever set them leaving is not a reason for the site to look like a default
install again.""" install again.
admin_id = make_member("admina", role="admin")
sign_in(admin_id)
save(post, **{"token-brand": "#1b5e20"})
sign_in(owner_id) The row erased is a former superadministrator who has since handed the
post(f"/comunidad/miembros/{admin_id}/eliminar") 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() row = db.execute("SELECT tokens_json, updated_by FROM brand").fetchone()
assert json.loads(row["tokens_json"]) == {"brand": "#1b5e20"} assert json.loads(row["tokens_json"]) == {"brand": "#1b5e20"}

View File

@ -24,9 +24,9 @@ def quiet_gitea(monkeypatch):
@pytest.fixture @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): 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 = {"title": title, "starts_on": starts_on}
data.update(extra) data.update(extra)
post("/comunidad/calendario/nuevo", data) post("/comunidad/calendario/nuevo", data)
@ -72,19 +72,19 @@ def test_the_calendar_itself_is_behind_the_login(client):
# --- the month ----------------------------------------------------------- # --- the month -----------------------------------------------------------
def test_the_month_shows_its_own_events_and_not_the_neighbours( 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("Asamblea", "2026-10-24")
an_event("Ensayo", "2026-11-03") 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) october = client.get("/comunidad/calendario?mes=2026-10").get_data(as_text=True)
assert "Asamblea" in october assert "Asamblea" in october
assert "Ensayo" not in october assert "Ensayo" not in october
def test_the_arrows_cross_the_year(client, an_event, owner_id, sign_in): def test_the_arrows_cross_the_year(client, an_event, superadmin_id, sign_in):
sign_in(owner_id) sign_in(superadmin_id)
page = client.get("/comunidad/calendario?mes=2026-12").get_data(as_text=True) page = client.get("/comunidad/calendario?mes=2026-12").get_data(as_text=True)
assert "mes=2027-01" in page 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( 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 """A calendar that refuses to draw because a query string was mistyped is
worse than one that shows now.""" worse than one that shows now."""
sign_in(owner_id) sign_in(superadmin_id)
today = date.today() today = date.today()
page = client.get("/comunidad/calendario?mes=pumpkin") 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) 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): def test_february_in_a_leap_year_has_twenty_nine_days(client, superadmin_id, sign_in, quiet_gitea):
sign_in(owner_id) sign_in(superadmin_id)
page = client.get("/comunidad/calendario?mes=2028-02").get_data(as_text=True) page = client.get("/comunidad/calendario?mes=2028-02").get_data(as_text=True)
assert ">29<" in page assert ">29<" in page
assert ">30<" not 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 ------------------------------------ # --- what the git server does to this ------------------------------------
def test_the_private_events_survive_a_git_server_that_is_down( 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 """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 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 gitea.py translates it — before that it was a bare OSError and this page
would have 500ed.""" would have 500ed."""
import requests import requests
sign_in(owner_id) sign_in(superadmin_id)
post("/comunidad/calendario/nuevo", {"title": "Asamblea", "starts_on": "2026-10-24"}) post("/comunidad/calendario/nuevo", {"title": "Asamblea", "starts_on": "2026-10-24"})
def refuse(*args, **kwargs): def refuse(*args, **kwargs):
@ -143,10 +143,10 @@ def test_the_private_events_survive_a_git_server_that_is_down(
# --- the .ics ------------------------------------------------------------- # --- 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", an_event("Asamblea", "2026-10-24", starts_at="19:00",
location="Local de la asociación") location="Local de la asociación")
sign_in(owner_id) sign_in(superadmin_id)
response = client.get("/comunidad/calendario/1.ics") 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 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 """VALUE=DATE rather than inventing midnight, which is how a calendar shows
it as a band across the top of the day.""" it as a band across the top of the day."""
an_event("Jornada", "2026-10-24") 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) body = client.get("/comunidad/calendario/1.ics").get_data(as_text=True)
assert "DTSTART;VALUE=DATE:20261024" in body 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 """An unescaped comma in LOCATION makes the rest of the line a second
value, and the address arrives truncated.""" value, and the address arrives truncated."""
an_event("Asamblea", "2026-10-24", location="Plaza de Ottakring, junto al mercado") 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) 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 ------------------------------------------------------------- # --- refusals -------------------------------------------------------------
def test_an_event_without_a_date_is_refused(client, db, post, owner_id, sign_in, quiet_gitea): def test_an_event_without_a_date_is_refused(client, db, post, superadmin_id, sign_in, quiet_gitea):
sign_in(owner_id) sign_in(superadmin_id)
response = post("/comunidad/calendario/nuevo", {"title": "Algún día"}) 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 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): def test_a_nonsense_time_is_refused(client, db, post, superadmin_id, sign_in, quiet_gitea):
sign_in(owner_id) sign_in(superadmin_id)
post("/comunidad/calendario/nuevo", post("/comunidad/calendario/nuevo",
{"title": "Asamblea", "starts_on": "2026-10-24", "starts_at": "25:99"}) {"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 -------------------------------------------------------------- # --- erasure --------------------------------------------------------------
def test_erasing_the_admin_leaves_the_event_standing( 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 """The meeting still happens after they leave: the event belongs to the
association, so the row stays and the name goes.""" association, so the row stays and the name goes."""
admin = make_member("admina", role="admin") admin = make_member("admina", role="admin")
sign_in(admin) sign_in(admin)
post("/comunidad/calendario/nuevo", {"title": "Asamblea", "starts_on": "2026-10-24"}) 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") post(f"/comunidad/miembros/{admin}/eliminar")
row = db.execute("SELECT title, created_by FROM events").fetchone() row = db.execute("SELECT title, created_by FROM events").fetchone()

View File

@ -222,10 +222,10 @@ def test_a_suspended_member_gets_no_reset(client, post, make_member, outbox):
# --- inviting from the members screen ------------------------------------- # --- inviting from the members screen -------------------------------------
def test_creating_a_member_emails_them_instead_of_showing_a_password( 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", monkeypatch.setattr(gitea, "admin_create_user",
lambda login, email, name, password: None) lambda login, email, name, password: None)
sign_in(owner_id) sign_in(superadmin_id)
response = post("/comunidad/miembros/nuevo", { response = post("/comunidad/miembros/nuevo", {
"login": "maria", "display_name": "María", "email": "m@example.com", "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( 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.""" """Otherwise the account exists and the member simply never gets in."""
monkeypatch.setattr(gitea, "admin_create_user", monkeypatch.setattr(gitea, "admin_create_user",
lambda login, email, name, password: None) 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): def explode(to, subject, body):
raise mail.MailFailed("connection refused") raise mail.MailFailed("connection refused")
monkeypatch.setattr(mail, "send", explode) monkeypatch.setattr(mail, "send", explode)
sign_in(owner_id) sign_in(superadmin_id)
response = post("/comunidad/miembros/nuevo", { response = post("/comunidad/miembros/nuevo", {
"login": "maria", "display_name": "María", "email": "m@example.com", "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 ----------------------------------- # --- when the server cannot send at all -----------------------------------
def test_an_unconfigured_server_does_not_blame_the_mail_server( 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 """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.""" admin hunting for an SMTP error that was never produced."""
monkeypatch.setattr(gitea, "admin_create_user", monkeypatch.setattr(gitea, "admin_create_user",
lambda login, email, name, password: None) lambda login, email, name, password: None)
app.config["MAIL_HOST"] = "" app.config["MAIL_HOST"] = ""
sign_in(owner_id) sign_in(superadmin_id)
page = post("/comunidad/miembros/nuevo", { page = post("/comunidad/miembros/nuevo", {
"login": "maria", "display_name": "María", "email": "m@example.com", "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 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"] = "" app.config["MAIL_HOST"] = ""
sign_in(owner_id) sign_in(superadmin_id)
assert "no envía correo" in client.get( assert "no envía correo" in client.get(
"/comunidad/miembros/nuevo").get_data(as_text=True) "/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 # member added any other way had no route in at all: no invitation was ever
# issued for them and nothing could issue one later. # 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): sign_in, outbox):
"""The case that prompted this: the admin made the account by hand, added """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 — the member with the box unticked, and nobody could reach the account —
including the admin, who never knew the password.""" including the admin, who never knew the password."""
member_id = make_member("salvador") 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")
@ -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 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): sign_in, outbox):
"""A link that was forwarded, or is sitting in a mailbox somebody else can """A link that was forwarded, or is sitting in a mailbox somebody else can
read, must stop working the moment a replacement is sent.""" read, must stop working the moment a replacement is sent."""
member_id = make_member("salvador") 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")
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( 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 """Issuing the token first would invalidate a previous, working invitation
in exchange for one that cannot be delivered.""" in exchange for one that cannot be delivered."""
member_id = db.execute( member_id = db.execute(
"INSERT INTO members (gitea_login, display_name, role) VALUES ('sincorreo', 'Sin', 'user')" "INSERT INTO members (gitea_login, display_name, role) VALUES ('sincorreo', 'Sin', 'user')"
).lastrowid ).lastrowid
sign_in(owner_id) sign_in(superadmin_id)
post(f"/comunidad/miembros/{member_id}/invitar", follow_redirects=True) 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 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, outbox):
sign_in(owner_id) sign_in(superadmin_id)
response = post(f"/comunidad/miembros/{make_member('fuera', active=0)}/invitar") response = post(f"/comunidad/miembros/{make_member('fuera', active=0)}/invitar")
assert response.status_code == 403 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( 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): def explode(to, subject, body):
raise mail.MailFailed("connection refused") raise mail.MailFailed("connection refused")
monkeypatch.setattr(mail, "send", explode) monkeypatch.setattr(mail, "send", explode)
sign_in(owner_id) sign_in(superadmin_id)
page = post(f"/comunidad/miembros/{make_member('salvador')}/invitar", page = post(f"/comunidad/miembros/{make_member('salvador')}/invitar",
follow_redirects=True).get_data(as_text=True) follow_redirects=True).get_data(as_text=True)

View File

@ -11,31 +11,53 @@ from apps.board.members import may_create, may_manage
# --- the rules as plain functions --------------------------------------- # --- the rules as plain functions ---------------------------------------
def test_only_the_owner_makes_admins(): def test_only_the_superadmin_makes_admins():
assert may_create("owner", "admin") """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("admin", "admin")
assert not may_create("user", "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("owner", "user")
assert may_create("admin", "user") assert may_create("admin", "user")
assert not may_create("user", "user") assert not may_create("user", "user")
def test_the_owner_is_beyond_everyone_including_themselves(): def test_neither_chair_can_be_touched_by_anybody():
assert not may_manage("owner", "owner") """Both single chairs, both unreachable, for different reasons. The
assert not may_manage("admin", "owner") 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(): def test_only_the_superadmin_manages_admins():
assert may_manage("owner", "admin") assert may_manage("superadmin", "admin")
assert not may_manage("owner", "admin")
assert not may_manage("admin", "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 ------------------- # --- 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("owner", "moderator")
assert may_create("admin", "moderator") assert may_create("admin", "moderator")
assert not may_create("moderator", "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 """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 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.""" 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_manage("moderator", target), target
assert not may_create("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( def test_an_admin_still_cannot_mint_an_admin_through_the_role_form(
client, db, post, make_member, sign_in): client, db, post, make_member, sign_in):
"""`set_role` moved from owner-only to admin-level so moderators can be """`set_role` is admin-level so moderators can be appointed routinely. That
appointed routinely. That must not quietly hand admins the one power the must not quietly hand admins the one power the superadministrator keeps."""
owner keeps."""
admin = make_member("admina", role="admin") admin = make_member("admina", role="admin")
maria = make_member("maria") maria = make_member("maria")
sign_in(admin) 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( 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 """`tombstone` is a real value in the CHECK constraint and would make the
member vanish from every listing while keeping their row.""" member vanish from every listing while keeping their row."""
sign_in(owner_id) sign_in(superadmin_id)
maria = make_member("maria") maria = make_member("maria")
assert post(f"/comunidad/miembros/{maria}/rol", {"role": "tombstone"}).status_code == 403 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 ---------------------------------------- # --- 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 """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.""" unique index is to survive a bug in the code above it."""
with pytest.raises(sqlite3.IntegrityError): with pytest.raises(sqlite3.IntegrityError):
db.execute( 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): def test_a_second_owner_is_impossible(db, owner_id):
from apps.board.members import transfer_ownership with pytest.raises(sqlite3.IntegrityError):
admin_id = make_member("segunda", role="admin") db.execute(
transfer_ownership(db, owner_id, admin_id) "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 = ?", 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 ---------------------------------------------------------- # --- the routes ----------------------------------------------------------
@ -127,8 +168,8 @@ def test_admin_cannot_create_an_admin(client, post, make_member, sign_in):
assert response.status_code == 403 assert response.status_code == 403
def test_owner_can_create_an_admin(client, db, post, owner_id, sign_in): def test_the_superadmin_can_create_an_admin(client, db, post, superadmin_id, sign_in):
sign_in(owner_id) sign_in(superadmin_id)
post("/comunidad/miembros/nuevo", { post("/comunidad/miembros/nuevo", {
"login": "nueva", "display_name": "Nueva", "email": "n@example.com", "login": "nueva", "display_name": "Nueva", "email": "n@example.com",
"role": "admin", "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 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")) 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 assert response.status_code == 403
def test_the_owner_cannot_suspend_themselves(client, post, owner_id, sign_in): def test_the_superadmin_cannot_suspend_themselves(client, post, superadmin_id, sign_in):
sign_in(owner_id) sign_in(superadmin_id)
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 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") author = make_member("saliente")
db.execute("INSERT INTO threads (author_id, title, body_md) VALUES (?, 'Hola', 'Texto')", db.execute("INSERT INTO threads (author_id, title, body_md) VALUES (?, 'Hola', 'Texto')",
(author,)) (author,))
sign_in(owner_id) sign_in(superadmin_id)
post(f"/comunidad/miembros/{author}/eliminar") post(f"/comunidad/miembros/{author}/eliminar")
assert db.execute("SELECT 1 FROM members WHERE id = ?", (author,)).fetchone() is None 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" assert row["display_name"] == "Miembro eliminado"
def test_the_member_page_renders_for_each_role(client, db, owner_id, make_member, sign_in): def test_the_member_page_renders_for_each_role(client, db, superadmin_id, owner_id,
"""Every role takes a different branch through member.html — the owner sees make_member, sign_in):
transfer and erase, an admin sees suspend, a plain member sees neither — so """Every role takes a different branch through member.html — the
each one is rendered here rather than trusted. 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 The page opened is always somebody else's: nobody manages themselves, the
person's page now, which is what this looks at. The owner's branch needs an block is not drawn on your own page, and a test looking at it would pass for
admin to transfer to, so the page opened is the admin's. the wrong reason.
""" """
admin_id = make_member("admina", role="admin") 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"), for member_id, who, expected in cases:
(admin_id, "Suspender"),
(make_member("usuaria"), None)):
sign_in(member_id) 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) body = client.get(f"/comunidad/miembro/{who}").get_data(as_text=True)
assert who.title() in body assert who.title() in body
if expected: for phrase in expected:
assert expected in body assert phrase in body, (member_id, phrase)
else: for phrase in forbidden - set(expected):
assert "Transferir titularidad" not in body assert phrase not in body, (member_id, phrase)
assert "Suspender" not in body
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( def test_the_new_member_form_hides_the_role_choice_from_admins(
client, owner_id, make_member, sign_in): client, superadmin_id, make_member, sign_in):
sign_in(owner_id) sign_in(superadmin_id)
assert "Administrador" in client.get("/comunidad/miembros/nuevo").get_data(as_text=True) assert "Administrador" in client.get("/comunidad/miembros/nuevo").get_data(as_text=True)
sign_in(make_member("admina", role="admin")) 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 -------------------------------- # --- 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. """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 `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, ?)""", VALUES (1, 'foto-abc123abc123.jpg', 'foto.jpg', 'image/jpeg', 10, ?)""",
(author,), (author,),
) )
sign_in(owner_id) sign_in(superadmin_id)
response = post(f"/comunidad/miembros/{author}/eliminar") 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 -------------- # --- onboarding, now that there is only one account to make --------------
def test_a_new_member_has_no_password_until_they_choose_one( 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 """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.""" 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) monkeypatch.setattr("apps.board.mail.send", lambda to, subject, body: None)
sign_in(owner_id) sign_in(superadmin_id)
post("/comunidad/miembros/nuevo", { post("/comunidad/miembros/nuevo", {
"login": "maria", "display_name": "María", "email": "m@example.com", "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 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 """It is the only way the invitation reaches anybody, so a member without
one is a row that can never be used.""" one is a row that can never be used."""
sign_in(owner_id) sign_in(superadmin_id)
post("/comunidad/miembros/nuevo", { post("/comunidad/miembros/nuevo", {
"login": "maria", "display_name": "María", "email": "", "role": "user", "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( 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 """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.""" 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) monkeypatch.setattr("apps.board.mail.send", lambda to, subject, body: None)
make_member("maria") make_member("maria")
sign_in(owner_id) sign_in(superadmin_id)
response = post("/comunidad/miembros/nuevo", { response = post("/comunidad/miembros/nuevo", {
"login": "maria", "display_name": "Otra", "email": "otra@example.com", "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( 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 """Deleting used to leave an account behind on the other server, so the
name stayed taken somewhere invisible. With one store, gone means gone.""" name stayed taken somewhere invisible. With one store, gone means gone."""
monkeypatch.setattr("apps.board.mail.send", lambda to, subject, body: None) 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(f"/comunidad/miembros/{make_member('salvador')}/eliminar")
post("/comunidad/miembros/nuevo", { 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", assert client.post(f"/comunidad/miembros/{maria}/estado",
data={"csrf_token": "token-for-tests", "active": "0"} data={"csrf_token": "token-for-tests", "active": "0"}
).status_code == 403 ).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"

View File

@ -301,7 +301,7 @@ def test_an_empty_message_with_no_picture_is_refused(client, db, post, make_memb
# --- erasure -------------------------------------------------------------- # --- erasure --------------------------------------------------------------
def test_erasing_a_member_takes_their_private_messages( 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 """Unlike a thread, which survives its author as "Miembro eliminado". A
two-party exchange has no remainder to preserve, and keeping half of two-party exchange has no remainder to preserve, and keeping half of
somebody's erased correspondence is what erasure exists to prevent.""" 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") content_type="multipart/form-data")
name = db.execute("SELECT stored_name FROM attachments").fetchone()["stored_name"] 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") post(f"/comunidad/miembros/{maria}/eliminar")
for table in ("conversations", "conversation_members", "messages", "attachments"): 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( 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") maria, jose = make_member("maria"), make_member("jose")
sign_in(maria) sign_in(maria)
post(f"/comunidad/privados/bloquear/{jose}") post(f"/comunidad/privados/bloquear/{jose}")
sign_in(jose) sign_in(jose)
post(f"/comunidad/privados/bloquear/{maria}") post(f"/comunidad/privados/bloquear/{maria}")
sign_in(owner_id) sign_in(superadmin_id)
post(f"/comunidad/miembros/{maria}/eliminar") post(f"/comunidad/miembros/{maria}/eliminar")
assert db.execute("SELECT COUNT(*) AS n FROM blocks").fetchone()["n"] == 0 assert db.execute("SELECT COUNT(*) AS n FROM blocks").fetchone()["n"] == 0

View File

@ -181,28 +181,52 @@ def test_a_moderator_is_accepted_afterwards(old_db):
def test_every_member_column_survives_the_rebuild(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 """Thirteen columns copied by name, twice over now — steps 4 and 7 each
their email address, or their password, or their public page.""" rebuild this table. A typo in either list is a member losing their email
before = old_db.execute( address, or their password, or their public page.
"SELECT id, gitea_login, display_name, email, role, active, created_by "
"FROM members ORDER BY id").fetchall() `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) migrations.apply(old_db)
after = old_db.execute( after = old_db.execute(f"SELECT {columns} FROM members ORDER BY id").fetchall()
"SELECT id, gitea_login, display_name, email, role, active, created_by "
"FROM members ORDER BY id").fetchall()
assert [tuple(row) for row in after] == [tuple(row) for row in before] assert [tuple(row) for row in after] == [tuple(row) for row in before]
def test_the_one_owner_rule_survives_the_rebuild(old_db): def test_the_owner_becomes_the_superadmin(old_db):
"""The partial unique index is not copied with the rows, so it has to be """Step 7's one intended change to the data. The person who could already do
recreated by hand. Without it the database silently stops being the thing everything keeps being able to, nobody types anything, and the responsable
that guarantees one owner, and a bug in a handler becomes two owners.""" 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) 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): with pytest.raises(sqlite3.IntegrityError):
old_db.execute("INSERT INTO members (gitea_login, display_name, role) " 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): 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", "") old_sql = old_sql.replace(" password_hash TEXT,\n", "")
# …and predates the moderator role, so step 4 has a CHECK to widen here too. # …and predates the moderator role, so step 4 has a CHECK to widen here too.
old_sql = old_sql.replace( 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')),", " 'user', 'tombstone')),",
" role TEXT NOT NULL CHECK (role IN ('owner', 'admin', 'user', 'tombstone')),") " role TEXT NOT NULL CHECK (role IN ('owner', 'admin', 'user', 'tombstone')),")
assert "CHECK (role IN ('owner', 'admin', 'user', 'tombstone'))" in old_sql 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 += """ old_sql += """
CREATE TABLE gitea_tokens ( CREATE TABLE gitea_tokens (
member_id INTEGER PRIMARY KEY REFERENCES members(id) ON DELETE CASCADE, 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( assert db.execute("PRAGMA user_version").fetchone()[0] == max(
number for number, _, _ in migrations.STEPS) number for number, _, _ in migrations.STEPS)
db.close() 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()

View File

@ -121,13 +121,13 @@ def test_the_bio_cannot_smuggle_html(client, published):
@pytest.mark.parametrize("name", ["de", "pt-br", "categories", "admin", @pytest.mark.parametrize("name", ["de", "pt-br", "categories", "admin",
"comunidad", "robots", "DE"]) "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): sign_in, name, monkeypatch):
"""Not because it would break the site — Caddy gives the static site every """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 collision — but because their page would never load and nobody would know
why.""" why."""
monkeypatch.setattr("apps.board.mail.send", lambda to, subject, body: None) monkeypatch.setattr("apps.board.mail.send", lambda to, subject, body: None)
sign_in(owner_id) sign_in(superadmin_id)
post("/comunidad/miembros/nuevo", { post("/comunidad/miembros/nuevo", {
"login": name, "display_name": "X", "email": "x@example.com", "role": "user", "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( 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() member_id = published()
sign_in(member_id) sign_in(member_id)
post("/comunidad/mi-perfil", {"published": "on", "bio": "Hola", 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"] (member_id,)).fetchone()["photo_name"]
assert (Path(app.config["UPLOAD_DIR"]) / name).exists() assert (Path(app.config["UPLOAD_DIR"]) / name).exists()
sign_in(owner_id) sign_in(superadmin_id)
post(f"/comunidad/miembros/{member_id}/eliminar") post(f"/comunidad/miembros/{member_id}/eliminar")
assert not (Path(app.config["UPLOAD_DIR"]) / name).exists() 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) 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): make_member, sign_in):
"""The one name with no page behind it. An erased member's writing is """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 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) sign_in(maria)
post("/comunidad/nuevo", {"title": "Hola", "body": "Qué tal"}) post("/comunidad/nuevo", {"title": "Hola", "body": "Qué tal"})
sign_in(owner_id) sign_in(superadmin_id)
post(f"/comunidad/miembros/{maria}/eliminar") post(f"/comunidad/miembros/{maria}/eliminar")
body = client.get("/comunidad/muro").get_data(as_text=True) body = client.get("/comunidad/muro").get_data(as_text=True)

View File

@ -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, def test_reacting_to_something_that_is_gone_is_a_404(db, post, thread,
owner_id, make_member, sign_in): superadmin_id, make_member, sign_in):
sign_in(owner_id) sign_in(superadmin_id)
post(f"/comunidad/tema/{thread}/eliminar") post(f"/comunidad/tema/{thread}/eliminar")
sign_in(make_member("maria")) 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") 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): make_member, sign_in):
maria = make_member("maria") maria = make_member("maria")
sign_in(maria) sign_in(maria)
react(post, "thread", thread) react(post, "thread", thread)
sign_in(owner_id) sign_in(superadmin_id)
post(f"/comunidad/miembros/{maria}/eliminar") post(f"/comunidad/miembros/{maria}/eliminar")
assert db.execute("SELECT COUNT(*) AS n FROM reactions").fetchone()["n"] == 0 assert db.execute("SELECT COUNT(*) AS n FROM reactions").fetchone()["n"] == 0

View File

@ -364,7 +364,7 @@ def test_an_approved_one_cannot_be_edited_or_withdrawn(
# --- erasure -------------------------------------------------------------- # --- erasure --------------------------------------------------------------
def test_erasing_the_author_takes_their_submissions_and_photos( 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. """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 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.""" 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")) propose(post, picture=(io.BytesIO(PNG), "feria.png"))
stored = only_submission(db)["photo_name"] stored = only_submission(db)["photo_name"]
sign_in(owner_id) sign_in(superadmin_id)
post(f"/comunidad/miembros/{maria}/eliminar") post(f"/comunidad/miembros/{maria}/eliminar")
assert db.execute("SELECT COUNT(*) AS n FROM submissions").fetchone()["n"] == 0 assert db.execute("SELECT COUNT(*) AS n FROM submissions").fetchone()["n"] == 0
assert not (Path(app.config["UPLOAD_DIR"]) / stored).exists() 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): make_member, sign_in):
"""Who reviewed something is a fact about the submission, not personal data """Who reviewed something is a fact about the submission, not personal data
of the reviewer, so the name goes and the row stays.""" 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) sign_in(reviewer)
post(f"/comunidad/publicaciones/{submission_id}/rechazar", {"note": "Falta el dónde."}) 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") post(f"/comunidad/miembros/{reviewer}/eliminar")
row = only_submission(db) row = only_submission(db)

View File

@ -521,43 +521,75 @@ has been archiving air" are otherwise the same empty line.
### 11.6 Who can do what ### 11.6 Who can do what
| | Responsable | Administrador | Moderador | Miembro | 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
| Wall: post, comment, edit own | ✓ | ✓ | ✓ | ✓ | cannot produce a second of either.
| Private messages, own profile | ✓ | ✓ | ✓ | ✓ |
| Propose a public post | ✓ | ✓ | ✓ | ✓ | | | Superadministrador | Responsable | Administrador | Moderador | Miembro |
| Publish a public post directly | ✓ | ✓ | ✓ | — | |---|---|---|---|---|---|
| Approve or return a proposal | ✓ | ✓ | ✓ | — | | Wall: post, comment, edit own | ✓ | ✓ | ✓ | ✓ | ✓ |
| Edit and delete published posts | ✓ | ✓ | ✓ | — | | Private messages, own profile | ✓ | ✓ | ✓ | ✓ | ✓ |
| Static pages of the site | ✓ | ✓ | — | — | | Propose a public post | ✓ | ✓ | ✓ | ✓ | ✓ |
| Delete any wall post | ✓ | ✓ | — | — | | Publish a public post directly | ✓ | ✓ | ✓ | ✓ | — |
| Edit someone else's post | — | — | — | — | | Approve or return a proposal | ✓ | ✓ | ✓ | ✓ | — |
| Pin and close threads | ✓ | ✓ | — | — | | Edit and delete published posts | ✓ | ✓ | ✓ | ✓ | — |
| Create members and moderators | ✓ | ✓ | — | — | | Static pages of the site | ✓ | ✓ | ✓ | — | — |
| Change a role (below admin) | ✓ | ✓ | — | — | | Delete any wall post, pin and close | ✓ | ✓ | ✓ | — | — |
| Create admins, promote to admin | ✓ | — | — | — | | Edit someone else's post | — | — | — | — | — |
| Suspend a member or moderator | ✓ | ✓ | — | — | | Create members and moderators | ✓ | ✓ | ✓ | — | — |
| Suspend an admin | ✓ | — | — | — | | Change a role below admin | ✓ | ✓ | ✓ | — | — |
| Transfer ownership, erase a member | ✓ | — | — | — | | 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 **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 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 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. 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 Both rules live in one place each — `may_create` and `may_manage` in
in one place (`may_create` in `apps/board/members.py`) and the role form on `apps/board/members.py` — and the role picker on a member's page is built from
*Miembros* checks it twice: once for reaching the person, once for the role being `assignable_roles(actor)`, the same predicate, so it can never offer a role the
given. 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 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 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. 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 **On upgrade**, migration 7 promotes the existing owner — Pablo — to
rather than trusting the application to remember. The owner cannot be suspended superadministrator and leaves the responsable chair empty. Nothing is erased and
or demoted by anyone, themselves included — to step down, transfer ownership to nobody has to type anything: a superadministrator passes every check an owner
an admin. 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 ### 11.7 Personal data