vienalatina/apps/board/security.py
Pablo Volenski 1ff3522c56
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
2026-10-06 11:55:41 +00:00

130 lines
4.2 KiB
Python

"""CSRF tokens and the decorators that gate routes by role.
The CSRF check is installed once as a before-request hook in app.py rather than
as a decorator on each handler. A decorator is something a future route can
forget; a hook covering every unsafe method is something it has to actively opt
out of.
"""
from __future__ import annotations
import hmac
import secrets
from functools import wraps
from flask import abort, g, redirect, request, session, url_for
SAFE_METHODS = {"GET", "HEAD", "OPTIONS"}
def csrf_token() -> str:
if "csrf" not in session:
session["csrf"] = secrets.token_urlsafe(32)
return session["csrf"]
def check_csrf() -> None:
if request.method in SAFE_METHODS:
return
sent = request.form.get("csrf_token", "")
expected = session.get("csrf", "")
# compare_digest rather than == so a wrong token cannot be guessed a
# character at a time by measuring how long the comparison takes.
if not expected or not hmac.compare_digest(sent, expected):
abort(400, "Formulario caducado. Vuelve a cargar la página e inténtalo de nuevo.")
def login_required(view):
@wraps(view)
def wrapped(*args, **kwargs):
if g.member is None:
return redirect(url_for("auth.login", next=request.path))
return view(*args, **kwargs)
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):
"""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)
@login_required
def wrapped(*args, **kwargs):
if g.member["role"] not in _at_least("admin"):
abort(403)
return view(*args, **kwargs)
return wrapped
def moderator_required(view):
"""Curating the public site. Admins and the owner count as moderators.
Deliberately separate from admin_required: a moderator decides what the
public sees and nothing else. They cannot reach Gestión, cannot create or
deactivate anybody, and cannot change a role — moderating content is not
power over people.
"""
@wraps(view)
@login_required
def wrapped(*args, **kwargs):
if g.member["role"] not in _at_least("moderator"):
abort(403)
return view(*args, **kwargs)
return wrapped
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)
@login_required
def wrapped(*args, **kwargs):
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)
return view(*args, **kwargs)
return wrapped