vienalatina/apps/board/tests/conftest.py
Claude b90cbd2a9f
One front door: the members area owns its own logins
Three complaints, one cause. Logging out could not finish because the
session belonged to another server, whose logout is POST-only and
unreachable from here. "Ese usuario ya está en uso" for somebody absent
from Miembros, because erase_member deleted our row and left the git
account standing — two stores of users, one of them showing. And the
hand-off to a differently-designed domain, with a Forgot password that
could never work. All three followed from delegating identity, so it is
no longer delegated.

Members now sign in at /comunidad/login against a scrypt hash in our own
database, via werkzeug.security, which arrives with Flask. They have no
account on the git server at all, which makes the collision impossible
rather than fixed. Logout is one click.

This removes more than it adds: the OAuth round trip, the client
registration, tokens.py with its refresh-before-expiry logic, the
gitea_tokens table, and the logged-out page that existed to apologise
for a logout that did not log you out.

The editor keeps per-writer attribution without per-writer tokens: one
CONTENT_TOKEN commits, and each commit names its author, which Gitea's
contents API supports and a test now asserts. CONTENT_TOKEN falls back
to GITEA_ADMIN_TOKEN so nothing breaks on deploy, but it only needs
write access to one repository, while the admin token can modify every
account on the instance — and now has no remaining job.

The refusals are the interesting part. Unknown name, wrong password,
suspended member and invited-but-never-arrived all answer identically,
asserted by comparing the rendered bytes. The hash check runs against a
decoy even when there is no such member, so an unknown name does not
answer faster. Attempts are rate limited, counted inside SQLite for the
reason invites.py documents. A NULL hash never matches anything.

Migration 2 adds password_hash and drops the dead OAuth tokens. Everyone
starts NULL, including the owner, so scripts/set-password.sh exists and
was tested before this could ship: it prompts without echo, never takes
the password as an argument where ps would show it, and refuses a short
one or an unknown member.

Rehearsed against a rebuilt copy of the server's database: starts, keeps
the photo, drops the tokens table, serves a login form with no redirect,
signs in, signs out, stays out.

223 tests.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NizVpJ2dwzCbjCrTLCjeHn
2026-09-29 08:25:25 +00:00

94 lines
2.8 KiB
Python

"""Shared fixtures.
Tests drive the app through Flask's test client rather than poking functions
directly, because most of what is worth checking here is a decision about who
may do what — and that decision is only real once it has survived routing,
the session and the CSRF hook.
Sign-in is faked by writing the session cookie: the OAuth round trip belongs to
Gitea, and the tests that care about it stub the two network calls instead.
"""
from __future__ import annotations
import sys
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
from apps.board.app import create_app # noqa: E402
from apps.board.db import connect # noqa: E402
@pytest.fixture
def app(tmp_path):
application = create_app({
"SECRET_KEY": "test-secret",
"DB_PATH": str(tmp_path / "board.db"),
"OWNER_LOGIN": "owner",
"SESSION_COOKIE_SECURE": False,
"COOLDOWN_SECONDS": 0,
"BASE_URL": "http://localhost",
"ADMIN_TOKEN": "admintoken",
"UPLOAD_DIR": str(tmp_path / "uploads"),
"TESTING": True,
})
yield application
@pytest.fixture
def db(app):
conn = connect(app.config["DB_PATH"])
yield conn
conn.close()
@pytest.fixture
def client(app):
return app.test_client()
@pytest.fixture
def make_member(db):
"""Insert a member and return its id. The owner already exists, seeded."""
def _make(login, role="user", active=1):
cursor = db.execute(
"""INSERT INTO members (gitea_login, display_name, email, role, active)
VALUES (?, ?, ?, ?, ?)""",
(login, login.title(), f"{login}@example.com", role, active),
)
return cursor.lastrowid
return _make
@pytest.fixture
def owner_id(db):
return db.execute("SELECT id FROM members WHERE role = 'owner'").fetchone()["id"]
@pytest.fixture
def sign_in(client):
def _sign_in(member_id):
with client.session_transaction() as session:
session["member_id"] = member_id
session["csrf"] = "token-for-tests"
return _sign_in
@pytest.fixture
def post(client):
"""POST with a valid CSRF token, so tests exercise authorisation rather
than repeatedly rediscovering that the CSRF hook works."""
def _post(url, data=None, **kwargs):
# A real anonymous visitor gets a CSRF token when the form renders, so
# signed-out pages (invitations, password recovery) need one here too —
# otherwise every such test fails on the hook rather than on its subject.
with client.session_transaction() as session:
session.setdefault("csrf", "token-for-tests")
payload = dict(data or {})
payload.setdefault("csrf_token", "token-for-tests")
return client.post(url, data=payload, **kwargs)
return _post