diff --git a/README.md b/README.md index b0453af..20a89cc 100644 --- a/README.md +++ b/README.md @@ -145,37 +145,51 @@ runtime. ## Members area -`apps/board/` — a small Flask app at `/comunidad/`, behind Caddy, holding roles -and an internal message board. Signed-in members only. +`apps/board/` — a small Flask app at `/comunidad/`, behind Caddy. A member signs +in once and gets five sections: **Inicio** (a dashboard), **Muro** (the internal +board), **Privados** (messages between two members), **Publicaciones** (the +public site, through moderation) and, for admins, **Gestión**. ``` apps/board/ - app.py factory, config, the CSRF and noindex hooks - auth.py Gitea OAuth2 (confidential client) and the membership gate - members.py roles, provisioning, ownership transfer, GDPR erasure/export - board.py threads and comments - content.py the editor — writes posts to Gitea's contents API - gitea.py the only module that talks to Gitea - tokens.py per-member access tokens, refreshed before they expire - render.py markdown with raw HTML disabled - schema.sql the tables, including the one-owner index - tests/ pytest, 97 checks — `python3 -m pytest apps/board/tests` + app.py factory, config, the CSRF and noindex hooks + auth.py the login form, passwords, the membership gate + passwords.py scrypt hashing and the failed-attempt limiter + members.py roles, onboarding, ownership transfer, GDPR erasure/export + home.py Inicio, and Gestión + board.py the wall: threads and comments + messages.py private messages, unread marks, blocking + submissions.py what members propose for the public site, and its moderation + content.py the editor — commits posts and pages through Gitea's API + profiles.py public pages at vienalatina.com/ + uploads.py pictures: sniffed, renamed, served behind the login + invites.py one-time links for invitations and password resets + gitea.py the only module that talks to Gitea + migrations.py numbered schema steps, keyed on PRAGMA user_version + render.py markdown with raw HTML disabled + schema.sql the tables, including the one-owner index + tests/ pytest — `python3 -m pytest apps/board/tests` ``` -Three things about it are load-bearing and easy to undo by accident: +Four things about it are load-bearing and easy to undo by accident: -- **A Gitea account is not a membership.** Login succeeds only for an active row - in `members`. Drop that check and every account on the instance gets in, - starting with the translations bot. +- **The members area owns its own logins.** A password is a scrypt hash in + `members.password_hash`; a NULL hash cannot be signed in with, which is what + makes an invitation the only way in for a new member. - **One owner, enforced by a partial unique index**, not by application code. The owner cannot be suspended or demoted by anyone; stepping down means transferring ownership to an admin. +- **A moderator curates content and has no power over people.** No creating, + suspending, promoting or erasing anybody — `may_create` and `may_manage` in + `members.py` are the whole rule, and they are tested as plain functions. - **`html=False` in `render.py`** is the entire XSS defence, and it works because markdown-it then emits only its own tags. Turning it on means owning a sanitiser allowlist forever. Admins can delete anyone's post; **nobody can edit anyone else's**, admins included. Removing a post is visible to its author, quietly rewriting it is not. +The same line runs through moderation: a moderator approves or returns a +proposal, and never rewrites it to publish under somebody else's name. Its SQLite database is the only state on the server that git does not hold. `scripts/backup-board.sh` takes a consistent snapshot nightly — see @@ -183,10 +197,16 @@ Its SQLite database is the only state on the server that git does not hold. ### Writing posts -`/comunidad/contenido/` replaces Decap CMS for admins: a form that commits a -file through Gitea's contents API, so Woodpecker sees an ordinary push and -translate → build → deploy runs unchanged. Commits carry the author's own -account, not a bot's. +`/comunidad/contenido/` replaces Decap CMS: a form that commits a file through +Gitea's contents API, so Woodpecker sees an ordinary push and translate → build → +deploy runs unchanged. Commits name the person who wrote the post, not a bot — +`write_file` sends an author per commit. + +Moderators and admins write there directly. A member writes in +`/comunidad/publicaciones/` instead, and the proposal waits in SQLite until a +moderator approves it, which commits it through that same code under the +member's own name. Nothing a member writes reaches the repository before then, +because a commit to it *is* publication: the webhook starts the pipeline. It exists because Decap has no supported way to be themed — its maintainer's answer is override its CSS and accept that class names move, or fork it — so diff --git a/apps/board/app.py b/apps/board/app.py index bd3169e..45a312b 100644 --- a/apps/board/app.py +++ b/apps/board/app.py @@ -94,8 +94,11 @@ def create_app(overrides: dict | None = None) -> Flask: # restart, which is a confusing way to find out the variable is unset. raise RuntimeError("BOARD_SECRET_KEY is required (generate one with `openssl rand -hex 32`).") - from . import auth, board, content, members, messages, profiles, uploads + from . import (auth, board, content, home, members, messages, profiles, + submissions, uploads) app.register_blueprint(auth.bp, url_prefix=URL_PREFIX) + app.register_blueprint(home.bp, url_prefix=URL_PREFIX) + app.register_blueprint(submissions.bp, url_prefix=URL_PREFIX) app.register_blueprint(members.bp, url_prefix=URL_PREFIX) app.register_blueprint(content.bp, url_prefix=URL_PREFIX) app.register_blueprint(uploads.bp, url_prefix=URL_PREFIX) @@ -116,10 +119,13 @@ def create_app(overrides: dict | None = None) -> Flask: return {"current_year": datetime.now(timezone.utc).year} @app.context_processor - def _unread(): - # Lazily: base.html is rendered for signed-out pages and error pages - # too, and neither should run a query to draw a badge nobody sees. - return {"unread_private": messages.unread_count} + def _badges(): + # Lazily, as functions: base.html is rendered for signed-out pages and + # error pages too, and neither should run a query to draw a badge + # nobody sees. + return {"unread_private": messages.unread_count, + "pending_review": submissions.pending_count, + "may_moderate": submissions.may_moderate} @app.before_request def _before(): diff --git a/apps/board/auth.py b/apps/board/auth.py index ec1fcea..d2b654e 100644 --- a/apps/board/auth.py +++ b/apps/board/auth.py @@ -45,7 +45,7 @@ def load_member() -> None: return row = get_db().execute( """SELECT * FROM members - WHERE id = ? AND active = 1 AND role IN ('owner', 'admin', 'user')""", + WHERE id = ? AND active = 1 AND role != 'tombstone'""", (member_id,), ).fetchone() if row is None: @@ -63,13 +63,13 @@ def _safe_next(target: str) -> str: own community site. """ prefix = current_app.config["URL_PREFIX"] + "/" - return target if target.startswith(prefix) else url_for("board.threads") + return target if target.startswith(prefix) else url_for("home.index") @bp.route("/login", methods=["GET", "POST"]) def login(): if g.member is not None: - return redirect(url_for("board.threads")) + return redirect(url_for("home.index")) target = request.values.get("next", "") if request.method == "GET": @@ -98,7 +98,7 @@ def login(): member = get_db().execute( """SELECT * FROM members WHERE (gitea_login = ? COLLATE NOCASE OR email = ? COLLATE NOCASE) - AND role IN ('owner', 'admin', 'user')""", + AND role != 'tombstone'""", (identifier, identifier), ).fetchone() @@ -176,7 +176,7 @@ def recover(): member = get_db().execute( """SELECT * FROM members WHERE email = ? COLLATE NOCASE AND active = 1 - AND role IN ('owner', 'admin', 'user')""", + AND role != 'tombstone'""", (email,), ).fetchone() diff --git a/apps/board/board.py b/apps/board/board.py index 9e58a90..7873592 100644 --- a/apps/board/board.py +++ b/apps/board/board.py @@ -93,9 +93,14 @@ def _comment_or_404(comment_id: int): return row -@bp.route("/") +@bp.route("/muro") @login_required def threads(): + """The wall. It used to be the root of the members area, and `Inicio` is + there now: the first thing after signing in should say what has happened + everywhere, not drop somebody into one of the five places it could have + happened. Thread URLs are untouched, so nothing anyone has linked to moves. + """ page = max(1, request.args.get("page", 1, type=int)) rows = get_db().execute( """SELECT t.*, m.display_name AS author, diff --git a/apps/board/content.py b/apps/board/content.py index 3db2212..42f70d9 100644 --- a/apps/board/content.py +++ b/apps/board/content.py @@ -33,7 +33,7 @@ from flask import (Blueprint, abort, current_app, flash, g, redirect, from . import gitea from .db import get_db from .render import to_html -from .security import admin_required +from .security import moderator_required # One list of accepted formats for the whole app, kept in the module that # knows what each one looks like on the wire, so the editor and the board # cannot drift apart about what a picture is. @@ -41,14 +41,19 @@ from .uploads import IMAGE_EXTENSIONS bp = Blueprint("content", __name__) +# `role` is the floor for writing in this collection, checked by +# _collection_or_404 rather than by a decorator, because the two collections in +# one blueprint do not share an answer: a moderator curates what the public +# reads, and the static pages of the site are not that — they are the site's own +# structure, and changing "Acerca de" is an administrator's job. COLLECTIONS = { "post": { "label": "Artículos", "singular": "Artículo", - "folder": "content/post", "dated": True, + "folder": "content/post", "dated": True, "role": "moderator", }, "page": { "label": "Páginas", "singular": "Página", - "folder": "content/page", "dated": False, + "folder": "content/page", "dated": False, "role": "admin", }, } @@ -166,9 +171,22 @@ def listing(collection: str) -> list[dict]: # --- form handling ------------------------------------------------------- def _collection_or_404(collection: str) -> dict: + """404 for a collection that does not exist, 403 for one this member may not + write to. Every route here calls it before doing anything else, which is + what makes the per-collection rule real rather than a note in a template.""" if collection not in COLLECTIONS: abort(404) - return COLLECTIONS[collection] + meta = COLLECTIONS[collection] + if meta["role"] == "admin" and g.member["role"] not in ("owner", "admin"): + abort(403) + return meta + + +def visible_collections() -> dict: + """The collections this member may write to, for the tabs. A tab that only + ever produces a 403 is worse than no tab.""" + return {name: meta for name, meta in COLLECTIONS.items() + if meta["role"] != "admin" or g.member["role"] in ("owner", "admin")} def _name_or_404(name: str) -> str: @@ -212,46 +230,70 @@ def _read_form(collection: str) -> tuple[dict, str, list[str]]: return fields, body, errors -def _upload_image() -> str: - """Commit an uploaded picture and return the path the frontmatter uses. +def commit_picture(data: bytes, filename: str, author=None) -> str: + """Commit a picture into the site repository and return the path the + frontmatter uses. Deliberately a second commit rather than part of the post's. Gitea's contents API writes one file per request, and batching both into a single commit means the lower-level git trees API — noticeably more code to get wrong, for a benefit nobody sees beyond one fewer pipeline run. - """ - upload = request.files.get("picture") - if not upload or not upload.filename: - return "" - extension = upload.filename.rsplit(".", 1)[-1].lower() + Takes bytes rather than an upload so that approving a member's submission + can commit the picture it has had on disk since they proposed it, through + exactly this code. + """ + extension = filename.rsplit(".", 1)[-1].lower() if extension not in IMAGE_EXTENSIONS: raise gitea.GiteaError( f"Formato de imagen no admitido. Usa: {', '.join(sorted(IMAGE_EXTENSIONS))}." ) - - data = upload.read() maximum = current_app.config["UPLOAD_MAX_BYTES"] if len(data) > maximum: raise gitea.GiteaError( f"La imagen pesa {len(data) // 1024}KB y el máximo es {maximum // 1024}KB." ) - stem = slugify(upload.filename.rsplit(".", 1)[0])[:60] + stem = slugify(filename.rsplit(".", 1)[0])[:60] # A random suffix rather than a counter: two people uploading "foto.jpg" # in the same minute must not race for the same path. name = f"{stem}-{secrets.token_hex(3)}.{extension}" gitea.write_file(f"{UPLOAD_FOLDER}/{name}", data, f"content: subir {name}", gitea.content_token(), - member=g.member) + member=author or g.member) return f"/uploads/{name}" +def _upload_image() -> str: + upload = request.files.get("picture") + if not upload or not upload.filename: + return "" + return commit_picture(upload.read(), upload.filename) + + +def publish(collection: str, fields: dict, body: str, author) -> str: + """Write one post or page into the repository and return its path. + + The single place a commit is made from a finished form, shared by the editor + and by a moderator approving a submission, so both produce a byte-identical + file and the same commit shape. `author` is who wrote it, not who pressed + the button: `gitea.write_file` sends author and committer per commit, so an + approved submission keeps the member's name in git history. + """ + name = filename_for(collection, fields["title"], fields["date"]) + path = f"{COLLECTIONS[collection]['folder']}/{name}" + document = build_document(frontmatter_for(collection, fields), body) + gitea.write_file(path, document.encode("utf-8"), + f"content: publicar «{fields['title']}»", + gitea.content_token(), member=author) + return path + + # --- routes -------------------------------------------------------------- @bp.route("/contenido") @bp.route("/contenido/") -@admin_required +@moderator_required def index(collection: str = "post"): meta = _collection_or_404(collection) try: @@ -260,11 +302,11 @@ def index(collection: str = "post"): flash(str(exc), "error") items = [] return render_template("content_list.html", collection=collection, meta=meta, - collections=COLLECTIONS, items=items) + collections=visible_collections(), items=items) @bp.route("/contenido//nuevo", methods=["GET", "POST"]) -@admin_required +@moderator_required def new(collection: str): meta = _collection_or_404(collection) if request.method == "GET": @@ -280,12 +322,7 @@ def new(collection: str): picture = _upload_image() if picture: fields["image"] = picture - name = filename_for(collection, fields["title"], fields["date"]) - path = f"{meta['folder']}/{name}" - document = build_document(frontmatter_for(collection, fields), body) - gitea.write_file(path, document.encode("utf-8"), - f"content: publicar «{fields['title']}»", - gitea.content_token(), member=g.member) + publish(collection, fields, body, g.member) except gitea.GiteaError as exc: return _back_to_form(collection, meta, fields, body, [str(exc)], None) @@ -294,7 +331,7 @@ def new(collection: str): @bp.route("/contenido//editar/", methods=["GET", "POST"]) -@admin_required +@moderator_required def edit(collection: str, name: str): meta = _collection_or_404(collection) name = _name_or_404(name) @@ -348,7 +385,7 @@ def edit(collection: str, name: str): @bp.route("/contenido//eliminar/", methods=["POST"]) -@admin_required +@moderator_required def delete(collection: str, name: str): meta = _collection_or_404(collection) name = _name_or_404(name) @@ -368,7 +405,7 @@ def delete(collection: str, name: str): @bp.route("/contenido//vista-previa", methods=["POST"]) -@admin_required +@moderator_required def preview(collection: str): """Rendered on the server and returned as a whole page. diff --git a/apps/board/home.py b/apps/board/home.py new file mode 100644 index 0000000..1493b3f --- /dev/null +++ b/apps/board/home.py @@ -0,0 +1,111 @@ +"""Inicio — the one screen a member lands on. + +Every section of the members area was added in its own phase, and each one added +an entry to a flat navigation until signing in meant choosing between five words +with no idea which one held anything new. This page answers that first question: +what has happened since I was last here, and what is waiting for me. + +It owns no data. Every panel is a query the module responsible already runs for +its own page — the wall's newest threads, the unread count from `messages`, the +queue from `submissions` — gathered here and linked back there. Nothing on this +page is the only way to reach anything. +""" + +from __future__ import annotations + +from flask import Blueprint, g, render_template + +from . import submissions +from .db import TOMBSTONE_LOGIN, get_db +from .render import excerpt +from .security import admin_required, login_required + +bp = Blueprint("home", __name__) + +RECENT = 5 + + +@bp.route("/") +@login_required +def index(): + db = get_db() + threads = db.execute( + """SELECT t.id, t.title, t.body_md, t.created_at, m.display_name AS author, + (SELECT COUNT(*) FROM comments c + WHERE c.thread_id = t.id AND c.deleted_at IS NULL) AS replies + FROM threads t JOIN members m ON m.id = t.author_id + WHERE t.deleted_at IS NULL + ORDER BY t.created_at DESC LIMIT ?""", + (RECENT,), + ).fetchall() + + conversations = db.execute( + """SELECT other.id AS other_id, other.display_name AS other_name, + (SELECT COUNT(*) FROM messages msg + WHERE msg.conversation_id = c.id AND msg.author_id != mine.member_id + AND msg.deleted_at IS NULL + AND (mine.last_read_at IS NULL OR msg.created_at > mine.last_read_at) + ) AS unread, + (SELECT MAX(created_at) FROM messages + WHERE conversation_id = c.id AND deleted_at IS NULL) AS last_at + FROM conversations c + JOIN conversation_members mine + ON mine.conversation_id = c.id AND mine.member_id = :me + JOIN conversation_members theirs + ON theirs.conversation_id = c.id AND theirs.member_id != :me + JOIN members other ON other.id = theirs.member_id + ORDER BY last_at DESC NULLS LAST LIMIT :limit""", + {"me": g.member["id"], "limit": RECENT}, + ).fetchall() + + mine = db.execute( + """SELECT id, title, state, note FROM submissions + WHERE author_id = ? ORDER BY created_at DESC LIMIT ?""", + (g.member["id"], RECENT), + ).fetchall() + + # Only the people who can act on it get the queue; for everyone else the + # panel is not drawn, rather than drawn empty. + queue = [] + if submissions.may_moderate(): + queue = db.execute( + """SELECT s.id, s.title, s.created_at, m.display_name AS author + FROM submissions s JOIN members m ON m.id = s.author_id + WHERE s.state = 'pending' AND s.author_id != ? + ORDER BY s.created_at LIMIT ?""", + (g.member["id"], RECENT), + ).fetchall() + + people = db.execute( + """SELECT COUNT(*) AS n FROM members + WHERE active = 1 AND role != 'tombstone' AND gitea_login != ?""", + (TOMBSTONE_LOGIN,), + ).fetchone()["n"] + + return render_template("home.html", threads=threads, conversations=conversations, + mine=mine, queue=queue, people=people, excerpt=excerpt, + state_labels=submissions.STATE_LABELS) + + +@bp.route("/gestion") +@admin_required +def gestion(): + """Administration, which is two links and a count rather than a screen of + its own — Miembros and the static pages both already have their pages. It + exists so that neither of them has to sit in the navigation every member + sees, which is how *Contenido* ended up looking like a tab for everybody. + """ + db = get_db() + counts = { + "members": db.execute( + "SELECT COUNT(*) AS n FROM members WHERE role != 'tombstone'").fetchone()["n"], + "suspended": db.execute( + "SELECT COUNT(*) AS n FROM members WHERE active = 0 AND role != 'tombstone'" + ).fetchone()["n"], + "moderators": db.execute( + "SELECT COUNT(*) AS n FROM members WHERE role IN ('owner', 'admin', 'moderator')" + ).fetchone()["n"], + "pending": db.execute( + "SELECT COUNT(*) AS n FROM submissions WHERE state = 'pending'").fetchone()["n"], + } + return render_template("gestion.html", counts=counts) diff --git a/apps/board/members.py b/apps/board/members.py index 10a2228..c961224 100644 --- a/apps/board/members.py +++ b/apps/board/members.py @@ -1,11 +1,17 @@ """Members and roles. -Three roles, and the rules between them are short enough to state in full: +Four 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 on; nobody can deactivate or demote them, including themselves -* **admins** create and deactivate users, and moderate the board -* **users** post, comment, and edit or delete their own writing +* **admins** create, deactivate and promote members, 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, + 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 + other is how a curation role turns into a second admin by accident +* **members** post on the wall, write privately, keep a public profile, and + propose posts for the public site The predicates live as plain functions at the top of this module so they can be tested without a request, a session or a browser — and so that reading them @@ -31,20 +37,33 @@ bp = Blueprint("members", __name__) # edges. Checked here so a bad name fails before we create anything anywhere. LOGIN_RE = re.compile(r"^[A-Za-z0-9]([A-Za-z0-9._-]{0,38}[A-Za-z0-9])?$") -ROLE_LABELS = {"owner": "Responsable", "admin": "Administrador", "user": "Usuario"} +# "Miembro" rather than "Usuario" on the screens, while the stored value stays +# `user`: renaming the value would mean a migration and rewriting every role +# check for a word nobody types. +ROLE_LABELS = {"owner": "Responsable", "admin": "Administrador", + "moderator": "Moderador", "user": "Miembro"} + +# Who may be given which role on the Miembros screen, most trusted first, so +# the form and the predicates below cannot disagree about the list. +ASSIGNABLE_ROLES = ("admin", "moderator", "user") def may_create(actor_role: str, target_role: str) -> bool: """Who may bring whom in. Admins cannot mint more admins.""" if target_role == "admin": return actor_role == "owner" - if target_role == "user": + if target_role in ("moderator", "user"): return actor_role in ("owner", "admin") return False def may_manage(actor_role: str, target_role: str) -> bool: - """Deactivate, reactivate, or change the role of an existing member.""" + """Deactivate, reactivate, or change the role of an existing member. + + A moderator appears nowhere in this function, deliberately: they approve + 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. + """ if target_role == "owner": return False # the owner is out of reach of everyone, themselves included if target_role == "admin": @@ -102,8 +121,18 @@ REMOVED_ON_ERASE = { ("messages", "author_id"), ("blocks", "blocker_id"), ("blocks", "blocked_id"), + # A submission is private writing until a moderator approves it, so it goes + # with the rest of the private writing. The remainder of an approved one is + # the published post in the site repository, which already carries this + # person's name in the commit and is not ours to rewrite from here. + ("submissions", "author_id"), } +# Who reviewed somebody else's submission is a fact about that submission, not +# personal data of the reviewer, so it survives their erasure with the name +# removed rather than taking the submission down with it. +CLEARED_ON_ERASE_AFTER = {("submissions", "reviewed_by")} + def _conversations_of(member_id: int) -> str: return "SELECT conversation_id FROM conversation_members WHERE member_id = ?" @@ -150,6 +179,14 @@ def erase_member(db: sqlite3.Connection, member_id: int) -> list[str]: ) db.execute("DELETE FROM blocks WHERE blocker_id = ? OR blocked_id = ?", (member_id, member_id)) + orphaned += [row["photo_name"] for row in db.execute( + "SELECT photo_name FROM submissions WHERE author_id = ? AND photo_name IS NOT NULL", + (member_id,), + )] + db.execute("DELETE FROM submissions WHERE author_id = ?", (member_id,)) + for table, column in sorted(CLEARED_ON_ERASE_AFTER): + db.execute(f"UPDATE {table} SET {column} = NULL WHERE {column} = ?", + (member_id,)) # Table and column names come from the module constants above, never # from a request, so the interpolation is not a place user input can # reach. @@ -184,7 +221,8 @@ def index(): FROM members m LEFT JOIN members c ON c.id = m.created_by WHERE m.role != 'tombstone' - ORDER BY CASE m.role WHEN 'owner' THEN 0 WHEN 'admin' THEN 1 ELSE 2 END, + ORDER BY CASE m.role WHEN 'owner' THEN 0 WHEN 'admin' THEN 1 + WHEN 'moderator' THEN 2 ELSE 3 END, m.display_name COLLATE NOCASE""" ).fetchall() return render_template("members.html", members=rows, labels=ROLE_LABELS) @@ -319,11 +357,23 @@ def set_active(member_id: int): @bp.route("/miembros//rol", methods=["POST"]) -@owner_required +@admin_required def set_role(member_id: int): + """Admin-level rather than owner-level, now that there is a role between + the two worth handing out routinely. + + Two predicates, both of them: `may_manage` for reaching this person at all, + and `may_create` for the role being given — you may only grant a role you + could have created somebody with, which keeps "admins cannot mint admins" + true here as well without restating it. + """ target = _load(member_id) role = request.form.get("role", "") - if role not in ("admin", "user") or not may_manage(g.member["role"], target["role"]): + if role not in ASSIGNABLE_ROLES: + abort(403) + if not may_manage(g.member["role"], target["role"]): + abort(403) + if not may_create(g.member["role"], role): abort(403) get_db().execute("UPDATE members SET role = ? WHERE id = ?", (role, member_id)) flash(f"{target['display_name']} ahora es {ROLE_LABELS[role].lower()}.", "ok") diff --git a/apps/board/messages.py b/apps/board/messages.py index 05a4a05..4942ecb 100644 --- a/apps/board/messages.py +++ b/apps/board/messages.py @@ -122,7 +122,7 @@ def inbox(): people = get_db().execute( """SELECT m.id, m.display_name FROM members m WHERE m.id != :me AND m.active = 1 - AND m.role IN ('owner', 'admin', 'user') + AND m.role != 'tombstone' AND m.gitea_login != :ghost AND NOT EXISTS (SELECT 1 FROM blocks WHERE (blocker_id = :me AND blocked_id = m.id) @@ -165,7 +165,7 @@ def talk(member_id: int): abort(400) other = get_db().execute( """SELECT * FROM members - WHERE id = ? AND active = 1 AND role IN ('owner', 'admin', 'user')""", + WHERE id = ? AND active = 1 AND role != 'tombstone'""", (member_id,), ).fetchone() if other is None: diff --git a/apps/board/migrations.py b/apps/board/migrations.py index 1ffe317..986322b 100644 --- a/apps/board/migrations.py +++ b/apps/board/migrations.py @@ -24,6 +24,7 @@ again, so a correction is a new step. from __future__ import annotations +import re import sqlite3 @@ -31,6 +32,24 @@ def _columns(db: sqlite3.Connection, table: str) -> set[str]: return {row[1] for row in db.execute(f"PRAGMA table_info({table})")} +def _role_check(db: sqlite3.Connection) -> str: + """The CREATE TABLE text of `members` with its comments stripped. + + A CHECK constraint is the one piece of a table no pragma reports, so the + only way to ask what roles are allowed is to read the statement back — and + sqlite_master stores that statement *verbatim*, comments included. schema.sql + explains above the column why 'moderator' needed a rebuild, and searching the + raw text would find that sentence and conclude the work was already done. + Which is exactly what happened, and what the start-up test caught. + """ + row = db.execute( + "SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'members'" + ).fetchone() + if row is None: + return "" + return re.sub(r"--[^\n]*", "", row[0]) + + def _attachments_accept_messages(db: sqlite3.Connection) -> None: """Let an attachment hang off a private message. @@ -122,12 +141,78 @@ def _members_get_a_public_page(db: sqlite3.Connection) -> None: db.execute(f"ALTER TABLE members ADD COLUMN {column} {definition}") + +def _members_can_moderate(db: sqlite3.Connection) -> None: + """Add the `moderator` role, which means rebuilding this table. + + `role` carries `CHECK (role IN ('owner','admin','user','tombstone'))`, and + SQLite has no DROP CONSTRAINT, so widening the list is not an ALTER. This is + the same documented procedure as step 1 — new table, copy, drop, rename — + but on a table eight others point at, which is what makes it worth spelling + out: + + * `members` is referenced by threads, comments, conversation_members, + messages, blocks, attachments, invites, submissions and by itself + (`created_by`). Those clauses say `REFERENCES members`, resolved by name + at runtime rather than bound to the table's identity, so after the rename + they point at the new table with nothing to update. + * The rename only rewrites clauses that name `members_new`, and nothing + does, so no other table's schema is touched. + * `migrations.apply()` turns foreign keys off *outside* the transaction, + which is the only place it works — see the comment there. + * The partial unique index enforcing one owner is not carried over by the + copy and has to be recreated, or the database quietly loses the rule that + stops a second owner existing. + + Checked afterwards with `PRAGMA foreign_key_check`, and by the test that + builds a pre-migration database with a row in every referencing table. + """ + if "moderator" 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 ('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") + 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 # user_version once the step succeeds. STEPS = [ (1, "attachments can belong to a private message", _attachments_accept_messages), (2, "members keep their own password", _members_own_their_passwords), (3, "members can have a public page", _members_get_a_public_page), + (4, "members can be moderators", _members_can_moderate), ] diff --git a/apps/board/profiles.py b/apps/board/profiles.py index f16d1e2..9d74dda 100644 --- a/apps/board/profiles.py +++ b/apps/board/profiles.py @@ -85,7 +85,7 @@ def _published(login: str): """SELECT * FROM members WHERE gitea_login = ? COLLATE NOCASE AND profile_published = 1 AND active = 1 - AND role IN ('owner', 'admin', 'user')""", + AND role != 'tombstone'""", (login,), ).fetchone() diff --git a/apps/board/schema.sql b/apps/board/schema.sql index 71c0991..967cd8e 100644 --- a/apps/board/schema.sql +++ b/apps/board/schema.sql @@ -20,7 +20,10 @@ CREATE TABLE IF NOT EXISTS members ( bio TEXT, links TEXT, -- JSON array of {label, url} photo_name TEXT, - role TEXT NOT NULL CHECK (role IN ('owner', 'admin', 'user', 'tombstone')), + -- 'moderator' arrived with migration 4, which had to rebuild this table: + -- SQLite has no DROP CONSTRAINT, so widening a CHECK is never an ALTER. + role TEXT NOT NULL CHECK (role IN ('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), @@ -216,3 +219,49 @@ CREATE TABLE IF NOT EXISTS invites ( CREATE INDEX IF NOT EXISTS invites_open ON invites(member_id, purpose) WHERE used_at IS NULL; + +-- Public posts a member has proposed, waiting for a moderator. +-- +-- A draft in SQLite, deliberately not a commit. A commit to the site +-- repository *is* publication: Gitea's webhook fires Woodpecker, which +-- translates, builds and deploys within minutes. So nothing written here +-- reaches git until somebody with the moderator role approves it, and +-- approval is the only code path that calls gitea.write_file for a +-- submission. +-- +-- Moderators and admins do not use this table at all: they write through the +-- editor in content.py and their post is committed as they save it. The queue +-- exists for members, which is the whole of the curation policy — fewer posts, +-- each one read by somebody before the public sees it. +-- +-- The picture is a column here rather than a row in `attachments`, following +-- members.photo_name: a submission carries at most one, and giving +-- `attachments` a fourth possible parent would mean rebuilding that table +-- again for nothing. It lives in /data/uploads like every other private +-- picture, and is committed to the repository only on approval. +CREATE TABLE IF NOT EXISTS submissions ( + id INTEGER PRIMARY KEY, + author_id INTEGER NOT NULL REFERENCES members(id), + title TEXT NOT NULL, + body_md TEXT NOT NULL, + description TEXT NOT NULL DEFAULT '', + categories TEXT NOT NULL DEFAULT '', -- comma-separated, as content_cache + photo_name TEXT, + state TEXT NOT NULL DEFAULT 'pending' + CHECK (state IN ('pending', 'approved', 'rejected')), + -- Why it was rejected, in the moderator's words, shown to the author. A + -- queue that swallows work without saying why is a queue people stop using. + note TEXT, + reviewed_by INTEGER REFERENCES members(id), + reviewed_at TEXT, + -- Where it landed in the repository, so the author can be shown that it is + -- live rather than merely "approved". + published_path TEXT, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + updated_at TEXT +); + +CREATE INDEX IF NOT EXISTS submissions_queue + ON submissions(created_at) WHERE state = 'pending'; +CREATE INDEX IF NOT EXISTS submissions_author + ON submissions(author_id, created_at); diff --git a/apps/board/security.py b/apps/board/security.py index 87bab06..296cf0c 100644 --- a/apps/board/security.py +++ b/apps/board/security.py @@ -54,6 +54,23 @@ def admin_required(view): 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 ("owner", "admin", "moderator"): + abort(403) + return view(*args, **kwargs) + return wrapped + + def owner_required(view): @wraps(view) @login_required diff --git a/apps/board/static/board.css b/apps/board/static/board.css index 80cbdb4..a441922 100644 --- a/apps/board/static/board.css +++ b/apps/board/static/board.css @@ -324,3 +324,112 @@ input[type="file"] { border-radius: var(--radius-md); border: 1px solid var(--border-light); } + +/* One picture rather than a gallery: a proposal carries at most a single + image, and it is shown at reading size while it is being reviewed. */ +.attachment { + display: block; + margin: 0.75rem 0; + max-height: 320px; + max-width: 100%; + border-radius: var(--radius-md); + border: 1px solid var(--border-light); +} + +/* --- the corner account menu ----------------------------------------- */ +/* + * A
element, because the Content-Security-Policy has no + * 'unsafe-inline' and a menu that needs an onclick="" attribute is a menu the + * browser silently refuses to open. The summary is the whole control; the + * panel is positioned relative to it. + */ +.account { position: relative; } +.account__name { + cursor: pointer; + list-style: none; /* Firefox's default marker */ + color: var(--muted); + font-size: 0.9rem; + padding: 0.25rem 0; +} +.account__name::-webkit-details-marker { display: none; } +.account__name::after { content: " ▾"; color: var(--subtle); } +.account[open] .account__name { color: var(--brand); } +.account__menu { + position: absolute; + right: 0; + z-index: 20; + min-width: 13rem; + display: flex; + flex-direction: column; + gap: 0.15rem; + padding: 0.5rem; + background: var(--surface); + border: 1px solid var(--border-light); + border-radius: var(--radius-md); + box-shadow: var(--shadow); +} +.account__menu a, +.account__menu button { + text-align: left; + padding: 0.4rem 0.5rem; + border-radius: var(--radius-sm); + font-size: 0.92rem; + text-decoration: none; + color: var(--text); +} +.account__menu a:hover, +.account__menu button:hover { background: var(--surface-soft); } +.account__menu form { margin: 0; } + +/* --- Inicio's panels -------------------------------------------------- */ + +.panel { + background: var(--surface); + border: 1px solid var(--border-light); + border-radius: var(--radius-lg); + box-shadow: var(--shadow-sm); + padding: 1rem 1.25rem; + margin-bottom: 1.25rem; +} +/* Anything the member is expected to act on, rather than read. */ +.panel--attention { border-color: var(--brand); background: var(--brand-softer); } +.panel__head { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 1rem; + margin-bottom: 0.5rem; +} +.panel__head h2 { margin: 0; font-size: 1.05rem; } +.panel__row { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 0.5rem; + margin: 0.35rem 0; + padding-bottom: 0.35rem; + border-bottom: 1px solid var(--border-light); +} +.panel__row:last-child { border-bottom: none; padding-bottom: 0; } + +/* --- where a proposal has got to -------------------------------------- */ + +.tag--pending { background: var(--surface-soft); color: var(--muted); } +.tag--approved { background: var(--brand-soft); color: var(--brand-dark); } +.tag--rejected { background: #f7dcdc; color: var(--danger); } + +/* A role picker sitting in a table cell beside the other row actions. */ +.inline-form { display: flex; align-items: center; gap: 0.35rem; margin: 0; } +.inline-form select { padding: 0.2rem 0.35rem; font-size: 0.85rem; } + +/* Present for a screen reader, absent for everybody else — a - - - + {#
rather than a button with a handler: the CSP has no + 'unsafe-inline', so a menu that needs onclick="" is a menu that + silently never opens. This one works with the CSS and the HTML + alone. #} + {% endif %} {% if g.member %} {% endif %} @@ -58,7 +74,7 @@ diff --git a/apps/board/templates/error.html b/apps/board/templates/error.html index de8d0d6..45b33dc 100644 --- a/apps/board/templates/error.html +++ b/apps/board/templates/error.html @@ -5,6 +5,6 @@ {% endblock %} diff --git a/apps/board/templates/gestion.html b/apps/board/templates/gestion.html new file mode 100644 index 0000000..42c6088 --- /dev/null +++ b/apps/board/templates/gestion.html @@ -0,0 +1,51 @@ +{% extends "base.html" %} +{% block title %}Gestión{% endblock %} + +{% block main %} +
+

Gestión

+
+ +

+ Lo que sólo hace la administración. Todo lo demás — el muro, los privados, + las publicaciones — está en las otras secciones y funciona igual para ti que + para cualquier miembro. +

+ +
+
+

Miembros

+ Abrir +
+

+ {{ counts.members }} en total · {{ counts.moderators }} pueden moderar + {% if counts.suspended %} · {{ counts.suspended }} suspendido{{ '' if counts.suspended == 1 else 's' }}{% endif %} +

+

+ Dar de alta, invitar de nuevo, cambiar el rol, suspender y eliminar. +

+
+ +
+
+

Páginas del sitio

+ Abrir +
+

+ Acerca de, contacto y las demás páginas fijas de vienalatina.com. Las + publicaciones no están aquí: eso es + Publicaciones, que los + moderadores comparten contigo. +

+
+ +{% if counts.pending %} +
+
+

Pendiente de revisar

+ Ver +
+

{{ counts.pending }} propuesta{{ '' if counts.pending == 1 else 's' }} esperando a un moderador.

+
+{% endif %} +{% endblock %} diff --git a/apps/board/templates/home.html b/apps/board/templates/home.html new file mode 100644 index 0000000..597f362 --- /dev/null +++ b/apps/board/templates/home.html @@ -0,0 +1,82 @@ +{% extends "base.html" %} +{% block title %}Inicio{% endblock %} + +{% block main %} +
+

Hola, {{ g.member.display_name }}

+ {{ people }} miembro{{ '' if people == 1 else 's' }} activo{{ '' if people == 1 else 's' }} +
+ +{# Panels in the order things get acted on: what is waiting for me, then what + is waiting for everybody, then what I have sent somewhere. #} +{% if queue %} +
+
+

Para revisar

+ Ver la cola +
+ {% for item in queue %} +

+ {{ item.title }} + {{ item.author }} · {{ item.created_at }} +

+ {% endfor %} +
+{% endif %} + +
+
+

Privados

+ Todos +
+ {% if not conversations %} +

Todavía no tienes conversaciones. Escribe a alguien desde Privados.

+ {% endif %} + {% for c in conversations %} +

+ {{ c.other_name }} + {% if c.unread %}{{ c.unread }}{% endif %} + {% if c.last_at %}{{ c.last_at }}{% endif %} +

+ {% endfor %} +
+ +
+
+

Muro

+ Todo el muro +
+ {% if not threads %} +

El muro está vacío. Escribe el primero.

+ {% endif %} + {% for t in threads %} +

+ {{ t.title }} + {{ t.author }} · {{ t.replies }} respuesta{{ '' if t.replies == 1 else 's' }} +

+ {% endfor %} +
+ +
+
+

Mis publicaciones

+ Publicaciones +
+ {% if not mine %} +

+ {% if may_moderate() %} + Puedes publicar directamente en el sitio desde Publicaciones. + {% else %} + ¿Tienes algo que contarle al barrio? Propón una publicación + y un moderador la leerá antes de publicarla. + {% endif %} +

+ {% endif %} + {% for item in mine %} +

+ {{ item.title }} + {{ state_labels[item.state] }} +

+ {% endfor %} +
+{% endblock %} diff --git a/apps/board/templates/member_new.html b/apps/board/templates/member_new.html index 8986eaa..ff06703 100644 --- a/apps/board/templates/member_new.html +++ b/apps/board/templates/member_new.html @@ -29,15 +29,16 @@

{% endif %} - {% if can_make_admin %} - {% else %} - -

Los administradores sólo pueden dar de alta usuarios.

+ {% if not can_make_admin %} +

Sólo el responsable puede nombrar administradores.

{% endif %}
diff --git a/apps/board/templates/members.html b/apps/board/templates/members.html index c061cbf..d1535d7 100644 --- a/apps/board/templates/members.html +++ b/apps/board/templates/members.html @@ -48,13 +48,26 @@ {% endif %} - {% if is_owner %} -
+ {# A toggle worked while there were two roles. With three it has to + be a choice, and the options are the ones this person may + actually grant — the handler checks the same thing. #} + {% if is_owner or m.role != 'admin' %} + - - + + +
+ {% endif %} + {% if is_owner %} {% if m.role == 'admin' and m.active %}
diff --git a/apps/board/templates/submission.html b/apps/board/templates/submission.html new file mode 100644 index 0000000..f801d22 --- /dev/null +++ b/apps/board/templates/submission.html @@ -0,0 +1,73 @@ +{% extends "base.html" %} +{% block title %}{{ item.title }}{% endblock %} + +{% block main %} +
+

{{ item.title }}

+ Volver +
+ +
+
+ {{ labels[item.state] }} + {{ item.author }} · + {% if item.categories %} · {{ item.categories }}{% endif %} +
+ {% if item.description %}

{{ item.description }}

{% endif %} + {% if item.photo_name %} + Imagen de «{{ item.title }}» + {% endif %} +
{{ body_html }}
+
+ +{% if item.state == 'rejected' and item.note %} +
+

Motivo de la devolución

+

{{ item.note }}

+ {% if item.reviewer %}

— {{ item.reviewer }}, {{ item.reviewed_at }}

{% endif %} +
+{% endif %} + +{% if item.state == 'approved' %} +

+ Publicado{% if item.reviewer %} por {{ item.reviewer }}{% endif %}{% if item.published_path %} en {{ item.published_path }}{% endif %}. + La traducción al alemán y al portugués tarda un par de minutos. +

+{% endif %} + +{% if can_moderate and item.state != 'approved' %} +{# Approve and reject are two forms rather than one with a choice: they are not + variations of the same action, and the reason is required for only one. #} + + +

+ Al aprobar se publica tal cual está, firmado por {{ item.author }} — en el + sitio y en el historial del repositorio. +

+ +
+ +
+ + + + +
+{% endif %} + +{% if mine and item.state != 'approved' %} +
+ Editar +
+ + +
+
+{% endif %} +{% endblock %} diff --git a/apps/board/templates/submission_form.html b/apps/board/templates/submission_form.html new file mode 100644 index 0000000..bfe8074 --- /dev/null +++ b/apps/board/templates/submission_form.html @@ -0,0 +1,55 @@ +{% extends "base.html" %} +{% block title %}{{ 'Editar propuesta' if item else 'Proponer una publicación' }}{% endblock %} + +{% block main %} +
+

{{ 'Editar propuesta' if item else 'Proponer una publicación' }}

+
+ +

+ Esto no es el muro: va a vienalatina.com, en español, y se traduce solo al + alemán y al portugués. Un moderador lo lee antes de que salga. +

+ +
+ + + + + + + +

Una o dos líneas: es lo que se ve en los listados.

+ +
+ Categorías + {% for category in categories %} + + {% endfor %} +
+ + + + + + + {% if item and item.photo_name %} +

+ Ya tiene una imagen. Si eliges otra, la sustituye. +

+ {% endif %} + +
+ + Cancelar +
+
+{% endblock %} diff --git a/apps/board/templates/submissions.html b/apps/board/templates/submissions.html new file mode 100644 index 0000000..de5b068 --- /dev/null +++ b/apps/board/templates/submissions.html @@ -0,0 +1,86 @@ +{% extends "base.html" %} +{% block title %}Publicaciones{% endblock %} + +{% block main %} +
+

Publicaciones

+ {% if can_moderate %} + Publicar + {% else %} + Proponer + {% endif %} +
+ +

+ {% if can_moderate %} + Lo que publicas aquí sale al sitio en cuanto lo guardas. Lo que proponen los + miembros espera en esta cola hasta que tú u otro moderador lo apruebe. + Ver lo ya publicado. + {% else %} + Esto va a vienalatina.com, donde lo lee cualquiera. Un moderador lo lee + primero: si hace falta cambiar algo te lo devuelve con el motivo. + {% endif %} +

+ +{% if can_moderate %} +

Esperando revisión

+{% if not queue %} +

Nada pendiente. La cola está vacía.

+{% endif %} +{% for item in queue %} + +{% endfor %} +{% endif %} + +

Lo que he propuesto

+{% if not mine %} +
+

+ {% if can_moderate %} + Nada. Tus publicaciones no pasan por aquí: van directas al sitio. + {% else %} + Todavía no has propuesto nada. + {% endif %} +

+
+{% endif %} +{% for item in mine %} +
+
+ {{ labels[item.state] }} + +
+

+ {{ item.title }} +

+ {% if item.state == 'rejected' and item.note %} + {# The reason, on the list rather than one click away: it is the only thing + the author needs in order to know what to do next. #} +

Motivo: {{ item.note }}

+ {% endif %} +
+ {% if item.state != 'approved' %} + Editar +
+ + +
+ {% elif item.published_path %} + Publicado en {{ item.published_path }} + {% endif %} +
+
+{% endfor %} +{% endblock %} diff --git a/apps/board/templates/threads.html b/apps/board/templates/threads.html index 39035f8..6da0790 100644 --- a/apps/board/templates/threads.html +++ b/apps/board/templates/threads.html @@ -1,15 +1,15 @@ {% extends "base.html" %} -{% block title %}Mensajes{% endblock %} +{% block title %}Muro{% endblock %} {% block main %}
-

Mensajes

+

Muro

Escribir
{% if not threads %}
-

Todavía no hay mensajes. Escribe el primero.

+

Todavía no hay nada en el muro. Escribe el primero.

{% endif %} diff --git a/apps/board/tests/test_content.py b/apps/board/tests/test_content.py index c4ad68a..7639f87 100644 --- a/apps/board/tests/test_content.py +++ b/apps/board/tests/test_content.py @@ -308,3 +308,51 @@ def test_the_preview_renders_markdown_and_escapes_html(repo, editor, post): assert "fuerte" in page assert "" not in page assert not repo.files # a preview must not publish anything + + +# --- who may write which collection -------------------------------------- +# +# One blueprint, two answers. A moderator curates what the public reads, so +# posts are theirs. The static pages are the site's own structure — "Acerca de", +# contact — and changing those is an administrator's job. The check lives in +# _collection_or_404, which every route here calls before doing anything. + +def test_a_moderator_may_publish_a_post(repo, db, post, make_member, sign_in): + sign_in(make_member("luisa", role="moderator")) + + response = post("/comunidad/contenido/post/nuevo", + {"title": "Aviso", "body": "Texto.", "date": "2026-09-25"}) + + assert response.status_code == 302 + assert list(repo.files) == ["content/post/2026-09-25-aviso.es.md"] + + +def test_a_moderator_may_not_touch_the_static_pages(repo, client, post, + make_member, sign_in): + sign_in(make_member("luisa", role="moderator")) + + assert client.get("/comunidad/contenido/page").status_code == 403 + assert client.get("/comunidad/contenido/page/nuevo").status_code == 403 + assert post("/comunidad/contenido/page/nuevo", + {"title": "Acerca de", "body": "Texto."}).status_code == 403 + assert repo.files == {} + + +def test_a_member_may_not_use_the_editor_at_all(repo, client, post, + make_member, sign_in): + """Their route to the public site is a proposal, which waits for somebody.""" + sign_in(make_member("maria")) + + for path in ("/comunidad/contenido", "/comunidad/contenido/post/nuevo", + "/comunidad/contenido/page/nuevo"): + assert client.get(path).status_code == 403, path + assert repo.files == {} + + +def test_the_tabs_only_offer_what_this_member_may_open(repo, client, make_member, sign_in): + """A tab that always produces a 403 is worse than no tab.""" + sign_in(make_member("luisa", role="moderator")) + assert "Páginas" not in client.get("/comunidad/contenido").get_data(as_text=True) + + sign_in(make_member("admina", role="admin")) + assert "Páginas" in client.get("/comunidad/contenido").get_data(as_text=True) diff --git a/apps/board/tests/test_members.py b/apps/board/tests/test_members.py index 7ccb6f0..787e997 100644 --- a/apps/board/tests/test_members.py +++ b/apps/board/tests/test_members.py @@ -34,6 +34,67 @@ def test_only_the_owner_manages_admins(): assert not may_manage("admin", "admin") +# --- the moderator, who curates content and not people ------------------- + +def test_admins_and_the_owner_make_moderators(): + assert may_create("owner", "moderator") + assert may_create("admin", "moderator") + assert not may_create("moderator", "moderator") + assert not may_create("user", "moderator") + + +def test_a_moderator_has_no_power_over_anybody(): + """The line the whole role rests on. Being trusted to judge what the public + reads is not being trusted to suspend the person who wrote it, and a + moderator who could do both would be a second kind of admin.""" + for target in ("owner", "admin", "moderator", "user"): + assert not may_manage("moderator", target), target + assert not may_create("moderator", target), target + + +def test_an_admin_may_promote_a_member_to_moderator(client, db, post, make_member, sign_in): + admin = make_member("admina", role="admin") + maria = make_member("maria") + sign_in(admin) + + post(f"/comunidad/miembros/{maria}/rol", {"role": "moderator"}) + + assert db.execute("SELECT role FROM members WHERE id = ?", + (maria,)).fetchone()["role"] == "moderator" + + +def test_an_admin_still_cannot_mint_an_admin_through_the_role_form( + client, db, post, make_member, sign_in): + """`set_role` moved from owner-only to admin-level so moderators can be + appointed routinely. That must not quietly hand admins the one power the + owner keeps.""" + admin = make_member("admina", role="admin") + maria = make_member("maria") + sign_in(admin) + + assert post(f"/comunidad/miembros/{maria}/rol", {"role": "admin"}).status_code == 403 + assert db.execute("SELECT role FROM members WHERE id = ?", + (maria,)).fetchone()["role"] == "user" + + +def test_a_moderator_cannot_change_a_role_at_all(client, db, post, make_member, sign_in): + sign_in(make_member("luisa", role="moderator")) + maria = make_member("maria") + + assert post(f"/comunidad/miembros/{maria}/rol", {"role": "moderator"}).status_code == 403 + + +def test_the_role_form_refuses_a_role_that_is_not_offered( + client, db, post, owner_id, make_member, sign_in): + """`tombstone` is a real value in the CHECK constraint and would make the + member vanish from every listing while keeping their row.""" + sign_in(owner_id) + maria = make_member("maria") + + assert post(f"/comunidad/miembros/{maria}/rol", {"role": "tombstone"}).status_code == 403 + assert post(f"/comunidad/miembros/{maria}/rol", {"role": "owner"}).status_code == 403 + + # --- the database holds the line ---------------------------------------- def test_a_second_owner_is_impossible(db): @@ -206,9 +267,10 @@ def test_every_table_pointing_at_members_is_accounted_for(db): members.py's erase lists. Otherwise erasure breaks — and it breaks at the moment somebody exercises a right they are entitled to, which is the worst possible time to find out.""" - from apps.board.members import (CLEARED_ON_ERASE, REASSIGNED_ON_ERASE, - REMOVED_ON_ERASE) - handled = REASSIGNED_ON_ERASE | CLEARED_ON_ERASE | REMOVED_ON_ERASE + from apps.board.members import (CLEARED_ON_ERASE, CLEARED_ON_ERASE_AFTER, + REASSIGNED_ON_ERASE, REMOVED_ON_ERASE) + handled = (REASSIGNED_ON_ERASE | CLEARED_ON_ERASE | CLEARED_ON_ERASE_AFTER + | REMOVED_ON_ERASE) tables = [row["name"] for row in db.execute( "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'")] diff --git a/apps/board/tests/test_migrations.py b/apps/board/tests/test_migrations.py index c308c9f..19f7153 100644 --- a/apps/board/tests/test_migrations.py +++ b/apps/board/tests/test_migrations.py @@ -19,7 +19,37 @@ from apps.board import migrations # here as a literal rather than imported: the point is to reproduce what is on # the server, and schema.sql has moved on. OLD_SCHEMA = """ -CREATE TABLE members (id INTEGER PRIMARY KEY, gitea_login TEXT); +-- `members` as it shipped, because step 4 rebuilds it and a stub with two +-- columns would prove nothing about copying the other eleven. +CREATE TABLE members ( + id INTEGER PRIMARY KEY, + gitea_login TEXT NOT NULL UNIQUE COLLATE NOCASE, + display_name TEXT NOT NULL DEFAULT '', + email TEXT NOT NULL DEFAULT '', + role TEXT NOT NULL CHECK (role IN ('owner', 'admin', '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 +); +CREATE UNIQUE INDEX members_one_owner ON members(role) WHERE role = 'owner'; +-- Three of the eight tables that point at members(id), so the rebuild in step +-- 4 is checked with real references across it rather than on its own. +CREATE TABLE conversation_members ( + conversation_id INTEGER NOT NULL, + member_id INTEGER NOT NULL REFERENCES members(id), + PRIMARY KEY (conversation_id, member_id) +); +CREATE TABLE blocks ( + blocker_id INTEGER NOT NULL REFERENCES members(id), + blocked_id INTEGER NOT NULL REFERENCES members(id), + PRIMARY KEY (blocker_id, blocked_id) +); +CREATE TABLE invites ( + id INTEGER PRIMARY KEY, + member_id INTEGER NOT NULL REFERENCES members(id) ON DELETE CASCADE, + purpose TEXT NOT NULL +); CREATE TABLE threads (id INTEGER PRIMARY KEY, deleted_at TEXT); CREATE TABLE comments (id INTEGER PRIMARY KEY, deleted_at TEXT); CREATE TABLE messages (id INTEGER PRIMARY KEY, deleted_at TEXT); @@ -48,7 +78,13 @@ def old_db(tmp_path): # and fails on the server. db.execute("PRAGMA foreign_keys = ON") db.executescript(OLD_SCHEMA) - db.execute("INSERT INTO members (id, gitea_login) VALUES (1, 'salvador')") + db.execute("INSERT INTO members (id, gitea_login, display_name, email, role) " + "VALUES (1, 'salvador', 'Salvador', 's@example.com', 'user')") + db.execute("INSERT INTO members (id, gitea_login, display_name, role, created_by) " + "VALUES (2, 'pablo', 'Pablo', 'owner', 1)") + db.execute("INSERT INTO conversation_members VALUES (1, 1)") + db.execute("INSERT INTO blocks VALUES (1, 2)") + db.execute("INSERT INTO invites (member_id, purpose) VALUES (1, 'invite')") db.execute("INSERT INTO threads (id) VALUES (7)") db.execute("INSERT INTO comments (id) VALUES (9)") db.execute( @@ -126,6 +162,72 @@ def test_running_it_twice_changes_nothing(old_db): number for number, _, _ in migrations.STEPS) +# --- step 4: the moderator role ------------------------------------------ + +def test_the_role_check_refuses_a_moderator_beforehand(old_db): + """The premise, like the CHECK test above. SQLite has no DROP CONSTRAINT, + so if this ever stops raising, step 4 can shrink to an ALTER.""" + with pytest.raises(sqlite3.IntegrityError): + old_db.execute("INSERT INTO members (gitea_login, display_name, role) " + "VALUES ('luisa', 'Luisa', 'moderator')") + + +def test_a_moderator_is_accepted_afterwards(old_db): + migrations.apply(old_db) + old_db.execute("INSERT INTO members (gitea_login, display_name, role) " + "VALUES ('luisa', 'Luisa', 'moderator')") + assert old_db.execute( + "SELECT role FROM members WHERE gitea_login = 'luisa'").fetchone()["role"] == "moderator" + + +def test_every_member_column_survives_the_rebuild(old_db): + """Thirteen columns copied by name. A typo in that list is a member losing + their email address, or their password, or their public page.""" + before = old_db.execute( + "SELECT id, gitea_login, display_name, email, role, active, created_by " + "FROM members ORDER BY id").fetchall() + + migrations.apply(old_db) + + after = old_db.execute( + "SELECT id, gitea_login, display_name, email, role, active, created_by " + "FROM members ORDER BY id").fetchall() + assert [tuple(row) for row in after] == [tuple(row) for row in before] + + +def test_the_one_owner_rule_survives_the_rebuild(old_db): + """The partial unique index is not copied with the rows, so it has to be + recreated by hand. Without it the database silently stops being the thing + that guarantees one owner, and a bug in a handler becomes two owners.""" + migrations.apply(old_db) + with pytest.raises(sqlite3.IntegrityError): + old_db.execute("INSERT INTO members (gitea_login, display_name, role) " + "VALUES ('otro', 'Otro', 'owner')") + + +def test_nothing_pointing_at_a_member_is_left_dangling(old_db): + """Dropping and renaming `members` with foreign keys off is the only way to + do this, and it is also the way to quietly orphan every row in the eight + tables that reference it.""" + migrations.apply(old_db) + + assert old_db.execute("PRAGMA foreign_key_check").fetchall() == [] + assert old_db.execute("SELECT COUNT(*) FROM conversation_members").fetchone()[0] == 1 + assert old_db.execute("SELECT COUNT(*) FROM blocks").fetchone()[0] == 1 + assert old_db.execute("SELECT COUNT(*) FROM invites").fetchone()[0] == 1 + # And the references still bite: foreign keys are back on after apply(). + with pytest.raises(sqlite3.IntegrityError): + old_db.execute("INSERT INTO blocks VALUES (1, 999)") + + +def test_foreign_keys_are_back_on_afterwards(old_db): + """apply() switches them off outside the transaction and restores them in a + finally. A migration that leaves them off makes the whole process run + without enforcement until the container next restarts.""" + migrations.apply(old_db) + assert old_db.execute("PRAGMA foreign_keys").fetchone()[0] == 1 + + def test_a_fresh_database_skips_it(app, db): """schema.sql already builds the new shape, so the step must find its work done and return quietly rather than rebuilding a table it just created.""" @@ -162,6 +264,12 @@ def test_the_app_starts_against_a_database_from_before_all_this(tmp_path): " CHECK ((thread_id IS NULL) <> (comment_id IS NULL))") # …and predates members owning their own passwords. old_sql = old_sql.replace(" password_hash TEXT,\n", "") + # …and predates the moderator role, so step 4 has a CHECK to widen here too. + old_sql = old_sql.replace( + " role TEXT NOT NULL CHECK (role IN ('owner', 'admin', 'moderator',\n" + " 'user', 'tombstone')),", + " role TEXT NOT NULL CHECK (role IN ('owner', 'admin', 'user', 'tombstone')),") + assert "CHECK (role IN ('owner', 'admin', 'user', 'tombstone'))" in old_sql old_sql += """ CREATE TABLE gitea_tokens ( member_id INTEGER PRIMARY KEY REFERENCES members(id) ON DELETE CASCADE, @@ -194,6 +302,14 @@ def test_the_app_starts_against_a_database_from_before_all_this(tmp_path): assert (kept["stored_name"], kept["thread_id"], kept["bytes"]) == ( "foto-abc123abc123.jpg", 1, 2048) + # Step 4: the role list is wider, the one-owner rule survived the rebuild, + # and nothing that pointed at a member row lost its target. + db.execute("INSERT INTO members (gitea_login, display_name, role) " + "VALUES ('luisa', 'Luisa', 'moderator')") + assert db.execute("PRAGMA foreign_key_check").fetchall() == [] + assert db.execute( + "SELECT name FROM sqlite_master WHERE name = 'members_one_owner'").fetchone() + # And starting again changes nothing, because a container restarts. create_app({"SECRET_KEY": "x", "DB_PATH": path, "OWNER_LOGIN": "salvador", "UPLOAD_DIR": str(tmp_path / "uploads"), "TESTING": True}) diff --git a/apps/board/tests/test_navigation.py b/apps/board/tests/test_navigation.py new file mode 100644 index 0000000..eb60ad5 --- /dev/null +++ b/apps/board/tests/test_navigation.py @@ -0,0 +1,118 @@ +"""What each role can see and reach. + +This file exists because of a bug that no other test in this suite could have +caught: *Privados*, *Mi perfil* and *Contenido* were all inside one +`{% if g.member.role in ('owner', 'admin') %}` block in base.html, so an +ordinary member signed in to a wall and a member list and nothing else. Every +feature worked. Every test passed. Most of the members area was simply invisible +to the people it was built for. + +So the navigation is now asserted per role, from the rendered page, and every +section is asserted from its route as well — because a link nobody can see and a +link that 403s are the same thing to whoever needed it. +""" + +from __future__ import annotations + +import pytest + +# Label -> the path it leads to. Both halves matter: the label is what a member +# looks for, the path is what has to answer. +SECTIONS = { + "Inicio": "/comunidad/", + "Muro": "/comunidad/muro", + "Privados": "/comunidad/privados", + "Publicaciones": "/comunidad/publicaciones", +} +ADMIN_ONLY = {"Gestión": "/comunidad/gestion"} + + +@pytest.fixture +def nav(client, sign_in): + def _nav(member_id): + sign_in(member_id) + page = client.get("/comunidad/") + assert page.status_code == 200 + return page.get_data(as_text=True) + return _nav + + +@pytest.mark.parametrize("role", ["user", "moderator"]) +def test_a_member_sees_the_four_shared_sections(role, nav, make_member): + """The regression. Not one of these may depend on a role again.""" + body = nav(make_member("maria", role=role)) + for label in SECTIONS: + assert f">{label}" in body or f"{label}<" in body, label + + +@pytest.mark.parametrize("role", ["user", "moderator"]) +def test_a_member_does_not_see_gestion(role, nav, make_member): + assert "Gestión" not in nav(make_member("maria", role=role)) + + +def test_an_admin_sees_everything(nav, make_member): + body = nav(make_member("admina", role="admin")) + for label in list(SECTIONS) + list(ADMIN_ONLY): + assert label in body, label + + +@pytest.mark.parametrize("role", ["user", "moderator", "admin"]) +def test_the_account_items_are_in_the_corner_for_everybody(role, nav, make_member): + """They used to be navigation entries, and two of them admin-only. A member + with no way to reach their own profile or their own data export is the same + bug wearing a different hat.""" + body = nav(make_member("maria", role=role)) + assert "/comunidad/mi-perfil" in body + assert "/comunidad/mis-datos" in body + assert "Salir" in body + + +@pytest.mark.parametrize("role", ["user", "moderator", "admin"]) +@pytest.mark.parametrize("path", sorted(SECTIONS.values())) +def test_every_shared_section_answers_for_every_role(role, path, client, make_member, sign_in): + sign_in(make_member("maria", role=role)) + assert client.get(path).status_code == 200 + + +@pytest.mark.parametrize("role", ["user", "moderator"]) +def test_gestion_is_refused_below_admin(role, client, make_member, sign_in): + """Refused by the route, not hidden by the template. A moderator who types + the address meets the same answer as one who cannot see the link.""" + sign_in(make_member("maria", role=role)) + assert client.get("/comunidad/gestion").status_code == 403 + + +def test_gestion_opens_for_an_admin(client, make_member, sign_in): + sign_in(make_member("admina", role="admin")) + assert client.get("/comunidad/gestion").status_code == 200 + + +def test_signing_in_lands_on_inicio(client, db, post, make_member): + """It used to land on the wall, which is one of five places something may + have happened since the last visit.""" + from apps.board import passwords + member_id = make_member("maria") + db.execute("UPDATE members SET password_hash = ? WHERE id = ?", + (passwords.hash_password("una-contraseña-larga"), member_id)) + + response = post("/comunidad/login", + {"identifier": "maria", "password": "una-contraseña-larga"}) + + assert response.status_code == 302 + assert response.headers["Location"].rstrip("/").endswith("/comunidad") + + +def test_the_wall_keeps_its_thread_urls(client, post, make_member, sign_in): + """The wall moved from /comunidad/ to /comunidad/muro. Thread addresses did + not, because people have linked to them from private messages.""" + sign_in(make_member("maria")) + post("/comunidad/nuevo", {"title": "Hola", "body": "Qué tal"}) + + assert client.get("/comunidad/tema/1").status_code == 200 + assert client.get("/comunidad/muro").status_code == 200 + + +def test_signed_out_visitors_get_no_navigation(client): + body = client.get("/comunidad/login").get_data(as_text=True) + for label in list(SECTIONS) + list(ADMIN_ONLY): + assert f'>{label}<' not in body, label diff --git a/apps/board/tests/test_submissions.py b/apps/board/tests/test_submissions.py new file mode 100644 index 0000000..dc6c51d --- /dev/null +++ b/apps/board/tests/test_submissions.py @@ -0,0 +1,399 @@ +"""The moderation queue. + +The property every test here circles is the same one: **nothing a member writes +reaches the site repository until a moderator approves it.** A commit to that +repository is publication — Gitea's webhook starts the translate, build and +deploy pipeline — so "queued in git with a flag" would already be live in three +languages. The Gitea layer is therefore replaced by a dictionary, and several +tests assert it was *not* written to, which is the assertion that matters most. + +The second property is attribution. Approval commits under the author's name and +email, not the moderator's, because git history is where somebody looks months +later to ask who wrote a post. +""" + +from __future__ import annotations + +import hashlib +import io +from pathlib import Path + +import pytest + +from apps.board import gitea + +PNG = b"\x89PNG\r\n\x1a\n" + b"\x00" * 64 + + +class FakeRepo: + """Only what a submission needs: writes, with who made them.""" + + def __init__(self): + self.files: dict[str, bytes] = {} + self.commits: list[str] = [] + self.authors: list[dict] = [] + + def write_file(self, path, data, message, token=None, sha=None, member=None): + self.files[path] = data + self.commits.append(message) + self.authors.append(gitea._identity(member)) + return hashlib.sha1(data).hexdigest() + + +@pytest.fixture +def repo(monkeypatch): + fake = FakeRepo() + monkeypatch.setattr(gitea, "write_file", fake.write_file) + return fake + + +@pytest.fixture +def maria(make_member): + return make_member("maria", role="user") + + +@pytest.fixture +def luisa(make_member): + return make_member("luisa", role="moderator") + + +def propose(post, title="Feria en Ottakring", body="Habrá **empanadas**.", **extra): + data = {"title": title, "body": body} + data.update(extra) + return post("/comunidad/publicaciones/nueva", data) + + +def only_submission(db): + return db.execute("SELECT * FROM submissions").fetchone() + + +# --- a member proposes ---------------------------------------------------- + +def test_a_proposal_is_a_row_and_not_a_commit(repo, db, post, maria, sign_in): + """The whole point of the table. If this ever commits, the post is on + vienalatina.com before anybody has read it.""" + sign_in(maria) + propose(post, description="Una feria", categories=["Comunidad"]) + + row = only_submission(db) + assert (row["state"], row["title"], row["categories"]) == ( + "pending", "Feria en Ottakring", "Comunidad") + assert repo.files == {} + assert repo.commits == [] + + +def test_an_empty_proposal_is_refused(db, post, maria, sign_in): + sign_in(maria) + assert propose(post, title=" ", body=" ").status_code == 400 + assert db.execute("SELECT COUNT(*) AS n FROM submissions").fetchone()["n"] == 0 + + +def test_only_so_many_may_wait_at_once(db, post, maria, sign_in): + """A bound on how much unread work one person can put on the moderators + without talking to them.""" + from apps.board.submissions import PENDING_MAX + sign_in(maria) + for n in range(PENDING_MAX): + propose(post, title=f"Propuesta {n}") + + refused = propose(post, title="Una más") + + assert refused.status_code == 400 + assert db.execute("SELECT COUNT(*) AS n FROM submissions").fetchone()["n"] == PENDING_MAX + + +def test_a_moderator_is_sent_to_the_editor_instead(client, luisa, sign_in): + """Their posts do not queue, so a form that would wait for their own + approval is a detour with nothing at the end of it.""" + sign_in(luisa) + response = client.get("/comunidad/publicaciones/nueva") + + assert response.status_code == 302 + assert "/comunidad/contenido/post/nuevo" in response.headers["Location"] + + +def test_a_moderator_publishing_directly_does_commit(repo, db, post, luisa, sign_in): + """The other half of the policy: curation applies to members' posts, and a + moderator is the person doing the curating.""" + sign_in(luisa) + post("/comunidad/contenido/post/nuevo", + {"title": "Aviso", "body": "Texto.", "date": "2026-09-25"}) + + assert list(repo.files) == ["content/post/2026-09-25-aviso.es.md"] + assert db.execute("SELECT COUNT(*) AS n FROM submissions").fetchone()["n"] == 0 + + +# --- who may read an unapproved post ------------------------------------- + +def test_a_stranger_cannot_read_somebody_else_is_draft(client, db, post, maria, + make_member, sign_in): + sign_in(maria) + propose(post) + submission_id = only_submission(db)["id"] + + sign_in(make_member("curiosa")) + assert client.get(f"/comunidad/publicaciones/{submission_id}").status_code == 403 + + +def test_the_author_and_the_moderators_can(client, db, post, maria, luisa, sign_in): + sign_in(maria) + propose(post) + submission_id = only_submission(db)["id"] + + assert client.get(f"/comunidad/publicaciones/{submission_id}").status_code == 200 + sign_in(luisa) + assert client.get(f"/comunidad/publicaciones/{submission_id}").status_code == 200 + + +def test_the_queue_is_only_listed_for_moderators(client, db, post, maria, + luisa, make_member, sign_in): + sign_in(maria) + propose(post, title="Feria de Ottakring") + + sign_in(make_member("otro")) + assert "Feria de Ottakring" not in client.get( + "/comunidad/publicaciones").get_data(as_text=True) + + sign_in(luisa) + assert "Feria de Ottakring" in client.get( + "/comunidad/publicaciones").get_data(as_text=True) + + +def test_a_member_cannot_approve_their_own(repo, client, db, post, maria, sign_in): + """The one that would make the whole queue decorative.""" + sign_in(maria) + propose(post) + submission_id = only_submission(db)["id"] + + response = post(f"/comunidad/publicaciones/{submission_id}/aprobar") + + assert response.status_code == 403 + assert repo.files == {} + assert only_submission(db)["state"] == "pending" + + +def test_a_member_cannot_reject_either(client, db, post, maria, make_member, sign_in): + sign_in(maria) + propose(post) + submission_id = only_submission(db)["id"] + + sign_in(make_member("otro")) + assert post(f"/comunidad/publicaciones/{submission_id}/rechazar", + {"note": "No me gusta"}).status_code == 403 + + +# --- approval ------------------------------------------------------------- + +def test_approving_commits_once_under_the_author_is_name( + repo, db, post, maria, luisa, sign_in): + """Attribution is the reason `write_file` takes an author at all. A post + approved by Luisa but written by María has to say María in git.""" + sign_in(maria) + propose(post, categories=["Comunidad"]) + submission_id = only_submission(db)["id"] + + sign_in(luisa) + post(f"/comunidad/publicaciones/{submission_id}/aprobar") + + path, = repo.files + assert path.startswith("content/post/") and path.endswith("-feria-en-ottakring.es.md") + assert repo.authors == [{"name": "Maria", "email": "maria@example.com"}] + row = only_submission(db) + assert (row["state"], row["published_path"], row["reviewed_by"]) == ( + "approved", path, luisa) + + +def test_the_approved_file_is_what_the_pipeline_expects(repo, db, post, maria, + luisa, sign_in): + """The same contract the editor's own tests hold it to: Spanish source, no + `translated_from`, categories as a list.""" + import yaml + sign_in(maria) + propose(post, categories=["Comunidad", "Cultura"], description="Una feria") + submission_id = only_submission(db)["id"] + + sign_in(luisa) + post(f"/comunidad/publicaciones/{submission_id}/aprobar") + + path, = repo.files + text = repo.files[path].decode("utf-8") + front = yaml.safe_load(text.split("---")[1]) + assert front["lang"] == "es" + assert front["manual_translation"] is False + assert front["categories"] == ["Comunidad", "Cultura"] + assert front["description"] == "Una feria" + assert "translated_from" not in front + assert "empanadas" in text + + +def test_approving_twice_publishes_once(repo, db, post, maria, luisa, sign_in): + sign_in(maria) + propose(post) + submission_id = only_submission(db)["id"] + + sign_in(luisa) + post(f"/comunidad/publicaciones/{submission_id}/aprobar") + post(f"/comunidad/publicaciones/{submission_id}/aprobar") + + assert len(repo.commits) == 1 + + +def test_a_picture_is_private_until_approval_and_committed_after( + app, repo, client, db, post, maria, luisa, make_member, sign_in): + """Three things at once, because they are one story: the picture is readable + by the author and the moderators and nobody else, it is not in the + repository, and approving puts it there and takes the private copy away.""" + sign_in(maria) + propose(post, picture=(io.BytesIO(PNG), "feria.png")) + row = only_submission(db) + stored = row["photo_name"] + url = f"/comunidad/publicaciones/foto/{stored}" + + assert (Path(app.config["UPLOAD_DIR"]) / stored).exists() + assert client.get(url).status_code == 200 # the author + sign_in(make_member("curiosa")) + assert client.get(url).status_code == 404 # anybody else + sign_in(luisa) + assert client.get(url).status_code == 200 # a moderator + assert repo.files == {} # still nothing published + + post(f"/comunidad/publicaciones/{row['id']}/aprobar") + + assert any(path.startswith("static/uploads/") for path in repo.files) + assert only_submission(db)["photo_name"] is None + assert not (Path(app.config["UPLOAD_DIR"]) / stored).exists() + assert client.get(url).status_code == 404 + + +def test_a_file_that_is_not_an_image_is_refused(db, post, maria, sign_in): + sign_in(maria) + response = propose(post, picture=(io.BytesIO(b"nope"), "foto.png")) + + assert response.status_code == 400 + assert db.execute("SELECT COUNT(*) AS n FROM submissions").fetchone()["n"] == 0 + + +# --- rejection ------------------------------------------------------------ + +def test_rejecting_needs_a_reason_and_shows_it_to_the_author( + repo, client, db, post, maria, luisa, sign_in): + sign_in(maria) + propose(post) + submission_id = only_submission(db)["id"] + + sign_in(luisa) + post(f"/comunidad/publicaciones/{submission_id}/rechazar", {"note": " "}) + assert only_submission(db)["state"] == "pending" # no reason, no rejection + + post(f"/comunidad/publicaciones/{submission_id}/rechazar", + {"note": "Falta decir dónde es."}) + + assert only_submission(db)["state"] == "rejected" + assert repo.files == {} + sign_in(maria) + assert "Falta decir dónde es." in client.get( + "/comunidad/publicaciones").get_data(as_text=True) + + +def test_editing_a_rejected_one_puts_it_back_in_the_queue( + client, db, post, maria, luisa, sign_in): + """Otherwise a rewritten post stays marked "devuelto" and never reaches the + queue again — the author waits for a review that cannot happen.""" + sign_in(maria) + propose(post) + submission_id = only_submission(db)["id"] + sign_in(luisa) + post(f"/comunidad/publicaciones/{submission_id}/rechazar", {"note": "Falta el dónde."}) + + sign_in(maria) + post(f"/comunidad/publicaciones/{submission_id}/editar", + {"title": "Feria en Ottakring", "body": "En la plaza, el sábado."}) + + row = only_submission(db) + assert (row["state"], row["note"], row["reviewed_by"]) == ("pending", None, None) + sign_in(luisa) + assert "Feria en Ottakring" in client.get( + "/comunidad/publicaciones").get_data(as_text=True) + + +def test_nobody_else_may_edit_or_withdraw_it(client, db, post, maria, + luisa, make_member, sign_in): + """A moderator approves or returns a submission. Rewriting somebody's words + and publishing them under their name is not one of the two — the same line + the board draws between deleting a post and editing it.""" + sign_in(maria) + propose(post) + submission_id = only_submission(db)["id"] + + for other in (luisa, make_member("otro")): + sign_in(other) + assert post(f"/comunidad/publicaciones/{submission_id}/editar", + {"title": "Otra cosa", "body": "Otro texto"}).status_code == 403 + assert post(f"/comunidad/publicaciones/{submission_id}/retirar").status_code == 403 + + +def test_withdrawing_takes_the_picture_with_it(app, db, post, maria, sign_in): + sign_in(maria) + propose(post, picture=(io.BytesIO(PNG), "feria.png")) + row = only_submission(db) + + post(f"/comunidad/publicaciones/{row['id']}/retirar") + + assert db.execute("SELECT COUNT(*) AS n FROM submissions").fetchone()["n"] == 0 + assert not (Path(app.config["UPLOAD_DIR"]) / row["photo_name"]).exists() + + +def test_an_approved_one_cannot_be_edited_or_withdrawn( + repo, db, post, maria, luisa, sign_in): + """It is in the repository now. Changing it there is what the editor is + for, and withdrawing a row would not unpublish anything.""" + sign_in(maria) + propose(post) + submission_id = only_submission(db)["id"] + sign_in(luisa) + post(f"/comunidad/publicaciones/{submission_id}/aprobar") + + sign_in(maria) + post(f"/comunidad/publicaciones/{submission_id}/editar", + {"title": "Otra cosa", "body": "Otro texto"}) + post(f"/comunidad/publicaciones/{submission_id}/retirar") + + row = only_submission(db) + assert (row["state"], row["title"]) == ("approved", "Feria en Ottakring") + + +# --- erasure -------------------------------------------------------------- + +def test_erasing_the_author_takes_their_submissions_and_photos( + app, repo, db, post, owner_id, maria, sign_in): + """A submission is private writing, so it goes the way private messages do. + What remains of an approved one is the post in the repository, which carries + their name in a commit that is not ours to rewrite from here.""" + sign_in(maria) + propose(post, picture=(io.BytesIO(PNG), "feria.png")) + stored = only_submission(db)["photo_name"] + + sign_in(owner_id) + post(f"/comunidad/miembros/{maria}/eliminar") + + assert db.execute("SELECT COUNT(*) AS n FROM submissions").fetchone()["n"] == 0 + assert not (Path(app.config["UPLOAD_DIR"]) / stored).exists() + + +def test_erasing_a_reviewer_keeps_the_submission(db, post, owner_id, maria, + make_member, sign_in): + """Who reviewed something is a fact about the submission, not personal data + of the reviewer, so the name goes and the row stays.""" + reviewer = make_member("luisa", role="moderator") + sign_in(maria) + propose(post) + submission_id = only_submission(db)["id"] + sign_in(reviewer) + post(f"/comunidad/publicaciones/{submission_id}/rechazar", {"note": "Falta el dónde."}) + + sign_in(owner_id) + post(f"/comunidad/miembros/{reviewer}/eliminar") + + row = only_submission(db) + assert (row["state"], row["reviewed_by"], row["note"]) == ( + "rejected", None, "Falta el dónde.") diff --git a/apps/board/tests/test_templates.py b/apps/board/tests/test_templates.py index 2e1755f..581cdd1 100644 --- a/apps/board/tests/test_templates.py +++ b/apps/board/tests/test_templates.py @@ -21,8 +21,14 @@ def test_no_inline_event_handlers(template): """`default-src 'self'` with no 'unsafe-inline' means the browser ignores an onsubmit="" attribute without complaining. A delete button written that way loses its confirmation dialog and nobody finds out until something is - deleted by accident. Use data-confirm, handled in static/board.js.""" - found = INLINE_HANDLER.findall(template.read_text(encoding="utf-8")) + deleted by accident. Use data-confirm, handled in static/board.js. + + Comments stripped first, like the two guards below: base.html explains in a + Jinja comment why its account menu is a
rather than a button with + an onclick, and a guard that fails on its own reasoning gets deleted rather + than obeyed.""" + found = INLINE_HANDLER.findall( + JINJA_COMMENT.sub("", template.read_text(encoding="utf-8"))) assert not found, f"{template.name} has inline handler(s): {found}" diff --git a/docs/server-setup.md b/docs/server-setup.md index 567a19e..df525f8 100644 --- a/docs/server-setup.md +++ b/docs/server-setup.md @@ -426,15 +426,22 @@ If `github` is not a remote yet, add it once — see the end of step 8: git remote add github https://github.com/pablovolenski/vienalatina.git ``` -That rebuilds the image, copies the compose file across, restarts, and prints -the log. It never touches `/srv/board/.env` — that file holds the secrets and -lives only on the server — but it does compare it against `.env.example` and -name any setting that has appeared in the repository and is missing from yours. -New settings are always added by hand. +That takes a backup, rebuilds the image, copies the compose file across, +restarts, and prints the log. It never touches `/srv/board/.env` — that file +holds the secrets and lives only on the server — but it does compare it against +`.env.example` and name any setting that has appeared in the repository and is +missing from yours. New settings are always added by hand. + +**The backup is part of the deploy now, not a thing to remember.** The app +applies numbered migrations at start-up and two of them rebuild a table in +place — `attachments`, and `members`, which holds your own account. Neither can +be undone afterwards, and "back up first" works reliably until the one deploy +where it mattered. `BOARD_SKIP_BACKUP=1` skips it if you have just taken one. The database schema is applied at start-up with `CREATE TABLE IF NOT EXISTS`, so a release that adds a table needs no migration step: the table appears when -the new code does. +the new code does. Anything that *changes* an existing table is a numbered +migration instead — §11.11 — and the deploy's log tail names each one it ran. ### 11.4 Route it through Caddy @@ -481,17 +488,34 @@ has been archiving air" are otherwise the same empty line. ### 11.6 Who can do what -| | Owner | Admin | User | -|---|---|---|---| -| Post, comment, edit own | ✓ | ✓ | ✓ | -| Delete any post | ✓ | ✓ | — | -| Edit someone else's post | — | — | — | -| Pin and close threads | ✓ | ✓ | — | -| Create users | ✓ | ✓ | — | -| Create admins | ✓ | — | — | -| Suspend a user | ✓ | ✓ | — | -| Suspend an admin | ✓ | — | — | -| Transfer ownership | ✓ | — | — | +| | Responsable | Administrador | Moderador | Miembro | +|---|---|---|---|---| +| Wall: post, comment, edit own | ✓ | ✓ | ✓ | ✓ | +| Private messages, own profile | ✓ | ✓ | ✓ | ✓ | +| Propose a public post | ✓ | ✓ | ✓ | ✓ | +| Publish a public post directly | ✓ | ✓ | ✓ | — | +| Approve or return a proposal | ✓ | ✓ | ✓ | — | +| Edit and delete published posts | ✓ | ✓ | ✓ | — | +| Static pages of the site | ✓ | ✓ | — | — | +| Delete any wall post | ✓ | ✓ | — | — | +| Edit someone else's post | — | — | — | — | +| Pin and close threads | ✓ | ✓ | — | — | +| Create members and moderators | ✓ | ✓ | — | — | +| Change a role (below admin) | ✓ | ✓ | — | — | +| Create admins, promote to admin | ✓ | — | — | — | +| Suspend a member or moderator | ✓ | ✓ | — | — | +| Suspend an admin | ✓ | — | — | — | +| Transfer ownership, erase a member | ✓ | — | — | — | + +**A moderator has no power over people.** They decide what the public reads and +nothing else: no creating, suspending, promoting or erasing anybody. That line is +the whole point of having the role — a moderator who could also suspend the +author of a post they had just returned would be a second kind of administrator. + +Admins can appoint moderators; only the owner can appoint admins. That rule lives +in one place (`may_create` in `apps/board/members.py`) and the role form on +*Miembros* checks it twice: once for reaching the person, once for the role being +given. 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 @@ -508,7 +532,11 @@ Members' names, emails and writing are personal data under GDPR. - **Erasure:** the owner's *Eliminar* removes the member row entirely and reassigns their threads and comments to a tombstone shown as "Miembro - eliminado", so conversations other people took part in stay readable. + eliminado", so conversations other people took part in stay readable. Private + messages and unapproved proposals are deleted outright, pictures included. An + already-published post stays on the site: what remains of it is a commit in + the content repository carrying their name, and rewriting git history from the + members area is not something this app does. - **Access:** any member can download everything they have written from *Descargar mis datos*. - **Retention:** soft-deleted posts stay in the database until removed by hand. @@ -655,7 +683,27 @@ the one case it was never needed for. the proof the rebuild kept real rows. Back up first — `scripts/backup-board.sh` — as with any migration. -### 11.13 Public profiles at `vienalatina.com/su-nombre` +**Step 4 rebuilds `members` for the same reason**, to widen the role CHECK so +`moderator` is a legal value. It is the more delicate of the two: eight tables +point at `members(id)`, and the procedure drops and renames the table with +foreign keys off. The clauses in those tables say `REFERENCES members`, resolved +by name, so they find the new table by themselves — but the partial unique index +that guarantees one owner is *not* carried over by the copy and has to be +recreated, and `PRAGMA foreign_key_check` runs before the transaction commits. +Both are asserted by tests that build a database in the old shape with a row in +every referencing table. + +One trap worth recording, because it cost a debugging session: the allowed roles +can only be read back out of the `CREATE TABLE` text in `sqlite_master`, and +SQLite stores that text verbatim — comments included. The comment in `schema.sql` +that explains why `moderator` needed a rebuild contains the word, so the step's +"have I already run?" check found it and skipped itself. Comments are stripped +before the check now. + +**Back up before deploying this one in particular**: the table being rebuilt is +the one your own account is in, and it is irreversible in place. + +### 11.12 Public profiles at `vienalatina.com/su-nombre` A member fills in *Mi perfil* and ticks *Publicar mi página*. Until they do, there is no page: `profile_published` starts at 0 and an unpublished profile @@ -700,6 +748,57 @@ the same problem the Gitea theme has. If the colours change in `themes/vienalatina/assets/css/main.css`, change them in `apps/board/templates/profile.html` too. +### 11.13 The five sections, and the moderation queue + +Signing in lands on **Inicio**, a dashboard of what has happened since the last +visit. The navigation is the same for everybody except the last entry: + +| | Where | Who | +|---|---|---| +| **Inicio** | `/comunidad/` | everybody | +| **Muro** | `/comunidad/muro` | everybody | +| **Privados** | `/comunidad/privados` | everybody | +| **Publicaciones** | `/comunidad/publicaciones` | everybody, with two different pages behind it | +| **Gestión** | `/comunidad/gestion` | admins and the owner | + +*Mi perfil*, *Descargar mis datos* and *Salir* are in the menu under the member's +own name, top right. They are not sections of the site, and while they were in the +navigation three of the five entries were admin-only — which meant an ordinary +member signed in to a wall and a member list, with their own profile and their own +private messages hidden from them. `apps/board/tests/test_navigation.py` asserts +the navigation per role now, so that cannot come back quietly. + +The wall moved from `/comunidad/` to `/comunidad/muro`. Thread addresses did not +move, so anything linked from a private message still works. + +**Publicaciones is the queue.** A member writes a proposal; it lives in the +`submissions` table and goes nowhere near the site. A moderator or admin reads it +and either approves it — which commits it to the content repository under the +member's own name, so `git log` names the writer and not the approver — or returns +it with a reason the author reads on their own Publicaciones page. Moderators and +admins do not queue: they write in *Contenido* and their post is committed as they +save it. + +Three things worth knowing about that design: + +- **A pending post is not in git at all.** It could not be: a commit to that + repository *is* publication, because Gitea's webhook starts the translate → + build → deploy pipeline within seconds. There is no draft state on the site. +- **One publish path.** Approval calls `content.publish`, the same function the + editor uses, so an approved proposal is byte-identical to a post written by a + moderator and the pipeline cannot tell them apart. +- **Its picture is private until approval**, served from `/data/uploads` to the + author and the moderators only. Approving commits it to the repository and + deletes the private copy, so there is one file in one place. +- **There is no way to promote a wall thread into a proposal**, deliberately. + Writing for the public is a separate act from talking to the people you already + know, and the site is curated on purpose: fewer posts, each one read by somebody + first. + +Editing a returned proposal puts it back in the queue automatically. An approved +one can no longer be edited from there — the file is in the repository, and that +is what *Contenido* is for. + ## 12. Make Gitea look like the site Members sign in to `/comunidad/` through Gitea, so Gitea's sign-in form and its @@ -816,7 +915,7 @@ belonged to the git server, its logout is POST-only and unreachable from another domain, and one click on *Entrar* signed you straight back in. All of that followed from delegating identity, and none of it survived taking it back. -### 11.12 When nobody can sign in +### 11.14 When nobody can sign in Every path to a first password goes through email: the invitation when a member is added, and *¿olvidaste tu contraseña?* afterwards. If the mailbox is down diff --git a/scripts/deploy-board.sh b/scripts/deploy-board.sh index e46d75a..1226d97 100755 --- a/scripts/deploy-board.sh +++ b/scripts/deploy-board.sh @@ -11,7 +11,7 @@ # This script is the whole update, in the order that matters: # # git pull # done by you, first -# sudo bash scripts/deploy-board.sh +# sudo bash scripts/deploy-board.sh # backs up, builds, restarts # # It never touches /srv/board/.env. That file holds the secrets and exists only # on the server; the repository has .env.example instead, and the two drifting @@ -73,13 +73,27 @@ if [ -n "$blank" ]; then echo fi +# A backup before every restart, not only before the ones known to migrate. +# +# The app applies numbered migrations at start-up (apps/board/migrations.py), and +# two of them rebuild a table in place: `attachments`, and `members` — the table +# your own account is in. Neither can be undone once it has run. Remembering to +# back up by hand works right up until the deploy that mattered, so it happens +# here. Skipped with BOARD_SKIP_BACKUP=1 if there is no database yet. +if [ -z "${BOARD_SKIP_BACKUP:-}" ] && [ -f "${BOARD_DB:-$TARGET/data/board.db}" ]; then + echo "==> Backing up first (migrations are irreversible in place)" + bash "$REPO/scripts/backup-board.sh" +fi + echo "==> Restarting" cd "$TARGET" docker compose up -d --force-recreate -# The schema is applied at start-up with CREATE TABLE IF NOT EXISTS, so a new -# table arrives with the new code. If the container is not up a few seconds -# later it died during that, and the log says why. +# The schema is applied at start-up with CREATE TABLE IF NOT EXISTS and then the +# numbered migrations run, so a new table and a changed one both arrive with the +# new code. If the container is not up a few seconds later it died during that, +# and the log says why — the log line naming each migration applied is the one +# to read. sleep 3 docker compose ps echo