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

92 lines
3.7 KiB
Python

"""Storing and checking passwords, now that they are ours to keep.
Until this existed the members area had no passwords: it asked another server
whether somebody was who they said, which is why signing in meant leaving
vienalatina.com and why signing out could never finish. Taking the job back
means taking the responsibility with it, and the two things that go wrong are
both in here: how the hash is made, and how many guesses a stranger gets.
Hashing is `werkzeug.security`, which arrives with Flask — no new dependency,
and BSD-3, which matters for a platform meant to be resold. Its default is
scrypt with sensible parameters. Deliberately not a hand-rolled `hashlib`
call: the parameters, the salting and the constant-time comparison are exactly
the details worth not inventing.
"""
from __future__ import annotations
from datetime import timedelta
from werkzeug.security import check_password_hash, generate_password_hash
from .db import get_db
MINIMUM = 10
# Guessing budget. Generous enough that nobody typing their own password badly
# notices, small enough that a list of common passwords is not worth running.
ATTEMPT_WINDOW = timedelta(minutes=15)
ATTEMPT_LIMIT = 10
# Compared against when there is no such member, so that a wrong username and a
# wrong password take the same time to answer. Without it the reply comes back
# measurably faster for a name that does not exist, and the login form becomes
# a way to find out who is a member. The value is a real scrypt hash of a
# string nobody will guess; what it hashes is irrelevant.
_DECOY = generate_password_hash("no-such-member-" + "x" * 32)
def hash_password(password: str) -> str:
return generate_password_hash(password)
def verify(stored: str | None, password: str) -> bool:
"""Check a password, spending the same time when there is nothing to check.
A member with no password yet — invited but never arrived — has NULL here.
That must never be treated as "matches anything", and it must not answer
faster than a real failure either.
"""
if not stored:
check_password_hash(_DECOY, password)
return False
return check_password_hash(stored, password)
def record_attempt(identifier: str) -> None:
get_db().execute(
"INSERT INTO login_attempts (identifier) VALUES (?)", (identifier.lower(),)
)
def too_many_attempts(identifier: str) -> bool:
"""Counted inside SQLite, for the reason written up in invites.py.
`created_at` is written by SQLite's own `datetime('now')` and compared
against SQLite's own clock. Handing it a Python timestamp instead puts two
formats on either side of a string comparison, and the limit silently never
fires — which is how the reset limiter was broken before anybody noticed.
"""
minutes = int(ATTEMPT_WINDOW.total_seconds() // 60)
row = get_db().execute(
"""SELECT COUNT(*) AS n FROM login_attempts
WHERE identifier = ? AND created_at > datetime('now', ?)""",
(identifier.lower(), f"-{minutes} minutes"),
).fetchone()
return row["n"] >= ATTEMPT_LIMIT
def forget_attempts(identifier: str) -> None:
"""Called on a successful sign-in, so a member who mistyped four times and
then got it right does not carry those four into the next hour."""
get_db().execute("DELETE FROM login_attempts WHERE identifier = ?",
(identifier.lower(),))
def prune_attempts() -> None:
"""Old rows are of no interest to anyone and are a small record of who
tried to sign in and when. Dropped on each successful login rather than by
a scheduled job, because there is no scheduler here."""
get_db().execute(
"DELETE FROM login_attempts WHERE created_at < datetime('now', '-1 day')")