vienalatina/apps/board/db.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

128 lines
4.9 KiB
Python

"""SQLite access for the members area.
One connection per request, closed when the request ends. SQLite is enough
here by a wide margin: a trusted group of tens of people generates a handful
of writes a day, and keeping the database a single file on disk means the
backup story is `cp`, which matters more than throughput nobody will use.
"""
from __future__ import annotations
import sqlite3
from pathlib import Path
from flask import current_app, g
from . import migrations
SCHEMA_PATH = Path(__file__).with_name("schema.sql")
# Authorship of a removed member is reassigned to this row rather than deleted,
# so their threads keep their shape and replies to them still make sense. It can
# never log in: the login gate requires an active member holding a real role.
TOMBSTONE_LOGIN = "__removed__"
TOMBSTONE_NAME = "Miembro eliminado"
def connect(path: str) -> sqlite3.Connection:
# isolation_level=None puts the driver in autocommit mode, so the only
# transactions are the ones written explicitly with BEGIN. Python's
# implicit-transaction behaviour is surprising often enough to be worth
# opting out of entirely.
conn = sqlite3.connect(path, isolation_level=None)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA foreign_keys = ON")
conn.execute("PRAGMA journal_mode = WAL")
conn.execute("PRAGMA busy_timeout = 5000")
return conn
def get_db() -> sqlite3.Connection:
if "db" not in g:
g.db = connect(current_app.config["DB_PATH"])
return g.db
def close_db(_exception=None) -> None:
db = g.pop("db", None)
if db is not None:
db.close()
def init_db(app) -> None:
"""Apply the schema, bring old databases up to date, seed the fixed rows.
The order is deliberate. `schema.sql` is all CREATE TABLE IF NOT EXISTS, so
on an empty database it builds everything in its current shape and the
migrations below find nothing to do; on a database that has run before it
adds only what is new and silently leaves existing tables alone — which is
precisely why migrations have to come second and clean up after it.
"""
Path(app.config["DB_PATH"]).parent.mkdir(parents=True, exist_ok=True)
db = connect(app.config["DB_PATH"])
try:
db.executescript(SCHEMA_PATH.read_text(encoding="utf-8"))
for step in migrations.apply(db):
app.logger.info("Applied migration %s", step)
_ensure_tombstone(db)
_seed_superadmin(db, app)
finally:
db.close()
def _ensure_tombstone(db: sqlite3.Connection) -> None:
db.execute(
"""INSERT INTO members (gitea_login, display_name, role, active)
VALUES (?, ?, 'tombstone', 0)
ON CONFLICT(gitea_login) DO NOTHING""",
(TOMBSTONE_LOGIN, TOMBSTONE_NAME),
)
def _seed_superadmin(db: sqlite3.Connection, app) -> None:
"""Create the first superadministrator from BOARD_OWNER, once.
Still `BOARD_OWNER` rather than a new name: it is the variable the server's
`.env` already carries, and an install that has to edit its environment to
survive an upgrade is an install that breaks on upgrade.
Deliberately refuses to change an existing superadministrator. Were this to
overwrite, anyone who could edit the environment could hand themselves the
platform by restarting the container — a quieter privilege escalation than
it looks, since editing a compose file draws far less attention than asking
for access.
**The `ON CONFLICT` below is the half worth reading twice.** It used to end
`SET role = 'owner'`, which was right while owner was the top of the tree.
Left that way after migration 7 it would have found the superadministrator's
login, matched the conflict, and demoted them back to owner on every
container restart — a privilege *reduction* arriving at the least convenient
moment and attributable to nothing anybody did. `members_one_superadmin`
would then have let somebody else take the chair.
"""
login = (app.config.get("OWNER_LOGIN") or "").strip()
existing = db.execute(
"SELECT gitea_login FROM members WHERE role = 'superadmin'").fetchone()
if existing:
if login and existing["gitea_login"].lower() != login.lower():
app.logger.warning(
"BOARD_OWNER is %r but the superadministrator is %r; leaving it "
"alone. Hand the platform on from inside the app instead.",
login, existing["gitea_login"],
)
return
if not login:
app.logger.warning("No superadministrator yet and BOARD_OWNER is unset — "
"nobody can sign in.")
return
db.execute(
"""INSERT INTO members (gitea_login, display_name, role, active)
VALUES (?, ?, 'superadmin', 1)
ON CONFLICT(gitea_login) DO UPDATE SET role = 'superadmin', active = 1""",
(login, login),
)
app.logger.info("Seeded %r as superadministrator.", login)