Reverses a shipped, tested, merged decision (D4/PR #2) rather than building on it — see docs/DECISIONS.md D15 for the full record: what was rejected (Postgres as a second container; Postgres+PostGIS bundled inside the single container via a supervisor), what this costs (no database-level RLS, no PostGIS, procrastinate needs replacing — all stated as a concern before this was decided, and reaffirmed anyway, which is the user's call to make about their own instance). The one invariant-critical consequence: isolation between users now rests entirely on the repository-layer scope (db.py's `Scope.select()`), not two layers. CLAUDE.md's invariant #4 is revised accordingly. This is not a downgrade-and-hope — `Scope` is built so an unfiltered query against a user-owned table is structurally harder to write than a scoped one (there is no method on `Scope` that returns one), and tests/test_auth.py::test_scoped_session_blocks_cross_user_reads replaces the old RLS proof with the same empirical standard: it doesn't trust the query builder filters correctly because the code reads correctly, it registers two real users and checks. test_unscoped_session_can_see_every_user_when_misused is the deliberately alarming companion — it demonstrates exactly what a reviewer must now catch, since nothing else will. Six real, non-obvious SQLite behaviours found and fixed by actually running this against a real file, not assumed from docs: - Foreign keys, ON DELETE CASCADE included, are OFF by default per connection — deleting a user silently left orphaned sessions/api_tokens, no error either way. Fixed with PRAGMA foreign_keys=ON on every connect. - Transactions default to DEFERRED, which only takes a write lock on the first actual write — a real check-then-act race for invite redemption (two concurrent redemptions could both read used_count < max_uses as true before either commits). Fixed by disabling the driver's implicit BEGIN and issuing BEGIN IMMEDIATE ourselves — SQLAlchemy's own documented recipe for this, not improvised. - DateTime(timezone=True) does NOT round-trip tzinfo on SQLite — a tz-aware datetime goes in, a naive one comes back out, and every `expires_at < datetime.now(UTC)` comparison in auth/service.py then raises TypeError. Fixed once at the Base level with a UTCDateTime TypeDecorator rather than per-column. - Uuid(as_uuid=True) stores as 32-char hex with NO hyphens on SQLite, not str(uuid)'s hyphenated form. A test fixture that raw-inserted the hyphenated form left rows the ORM's own later UPDATE (via invite.used_count += 1's autoflush) could never match by primary key, updating zero rows and raising StaleDataError. Fixed by using .hex to match exactly what the ORM itself writes. - BEGIN IMMEDIATE applies to every transaction, reads included — a long-lived test fixture that autobegins a transaction via a bare read and never explicitly closes it holds SQLite's exclusive write lock for the rest of the test, and a later scoped_session() call fails with "database is locked". Not an app-code bug (every real session block closes cleanly on exit), but real enough to document since the next person writing a test against the db_auth fixture will hit it too. - Python's sqlite3 module deprecates its own implicit datetime adapter as of 3.12 — silent today, warns on every raw-SQL datetime bind. Only ever hit test fixture code (the ORM path never uses it, confirmed by running the ORM-only health test with warnings promoted to errors and it stayed clean); fixed there with an explicit .isoformat() rather than left for a future Python version to turn into a real failure. Also, since with_for_update() silently no-ops on SQLite (confirmed — SQLAlchemy emits no SQL for it, no error either) rather than actually locking anything: removed it from register()'s invite-redemption query and corrected the comment to attribute the concurrency guarantee to BEGIN IMMEDIATE, where it now actually lives. One PR, not several, for the same reason PR #2 was: the migration, the models, db.py, and the docs recording why are five views of one decision — splitting them wouldn't make review easier, just disconnected. 552 insertions / 548 deletions across 17 files, most of it necessarily touching what PR #2 shipped rather than net-new code. Deliberately deferred, not solved here: PostGIS's replacement for spatial storage, procrastinate's replacement for background jobs, and the EXCLUDE USING gist constraint's replacement for component_installs — none of those tables exist yet (Phase 1-2), so none of it is broken, and docs/DECISIONS.md D15 records exactly what each future phase needs to decide before it can be built. .gitea/workflows/deploy pipeline (PR #4, built for the old 3-container Postgres compose stack) was closed as superseded rather than merged; the single-container image build is follow-up work, not part of this change. Verified: ruff check, ruff format --check, and mypy --strict all clean. 13/13 pytest passing against a real SQLite file, including with DeprecationWarning promoted to an error (confirms the sqlite3 adapter deprecation fix actually holds, not just that it's quiet by default). Full alembic upgrade -> downgrade -1 -> upgrade cycle run clean. alembic check clean with no include_object filter needed at all now (SQLite starts with nothing but what our own migrations create — no PostGIS/TIGER noise to filter out in the first place). CI's exact migration command sequence reproduced locally end to end before touching the workflow file. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
200 lines
7.5 KiB
Python
200 lines
7.5 KiB
Python
"""Auth bootstrap logic: register, login, session validation, logout.
|
|
|
|
Every function here runs against `db.auth_session()` (see its docstring for why these specific
|
|
pre-identity lookups need it) and every query is an exact match on a unique key — email,
|
|
token_hash, or code_hash — never an unfiltered scan.
|
|
|
|
Nothing outside this module should import `db.auth_session` — if a new feature needs it, that's
|
|
a sign the feature belongs here, not that the import should spread.
|
|
"""
|
|
|
|
from dataclasses import dataclass
|
|
from datetime import UTC, datetime, timedelta
|
|
from uuid import UUID
|
|
|
|
from sqlalchemy import select, update
|
|
|
|
from velodrome.auth.security import (
|
|
generate_token,
|
|
hash_invite_code,
|
|
hash_password,
|
|
hash_token,
|
|
verify_password,
|
|
)
|
|
from velodrome.config import get_settings
|
|
from velodrome.db import auth_session
|
|
from velodrome.models import Invite, Session, User
|
|
|
|
|
|
class AuthError(Exception):
|
|
"""Base class for auth failures the API layer turns into 4xx responses."""
|
|
|
|
|
|
class InvalidCredentials(AuthError):
|
|
pass
|
|
|
|
|
|
class InvalidInvite(AuthError):
|
|
pass
|
|
|
|
|
|
class EmailAlreadyRegistered(AuthError):
|
|
pass
|
|
|
|
|
|
class SessionInvalid(AuthError):
|
|
pass
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class AuthenticatedSession:
|
|
user_id: UUID
|
|
email: str
|
|
display_name: str
|
|
|
|
|
|
async def register(
|
|
*, email: str, password: str, display_name: str, invite_code: str
|
|
) -> AuthenticatedSession:
|
|
"""Validate an invite and create a user, atomically.
|
|
|
|
Open signup does not exist — see docs/PLAN.md "Auth". What stops a shared invite link being
|
|
redeemed twice concurrently is db.py's `BEGIN IMMEDIATE` setup, not a row lock on this
|
|
SELECT — SQLite has no `SELECT ... FOR UPDATE` (SQLAlchemy's SQLite dialect silently no-ops
|
|
`.with_for_update()`, confirmed empirically; it used to appear here when this ran against
|
|
Postgres — see git history). `BEGIN IMMEDIATE` takes SQLite's write lock for the whole
|
|
transaction up front, so two concurrent redemptions can't both read `used_count < max_uses`
|
|
as true before either commits — the second one simply waits for the first transaction to
|
|
finish, then sees the incremented count.
|
|
"""
|
|
code_hash = hash_invite_code(invite_code)
|
|
async with auth_session() as db:
|
|
async with db.begin():
|
|
invite = (
|
|
await db.execute(select(Invite).where(Invite.code_hash == code_hash))
|
|
).scalar_one_or_none()
|
|
|
|
if invite is None:
|
|
raise InvalidInvite("invite code not found")
|
|
if invite.revoked_at is not None:
|
|
raise InvalidInvite("invite has been revoked")
|
|
if invite.expires_at < datetime.now(UTC):
|
|
raise InvalidInvite("invite has expired")
|
|
if invite.used_count >= invite.max_uses:
|
|
raise InvalidInvite("invite has already been used")
|
|
if invite.email is not None and invite.email.lower() != email.lower():
|
|
raise InvalidInvite("invite is pinned to a different email address")
|
|
|
|
existing = (
|
|
await db.execute(select(User).where(User.email == email))
|
|
).scalar_one_or_none()
|
|
if existing is not None:
|
|
raise EmailAlreadyRegistered("an account with this email already exists")
|
|
|
|
user = User(
|
|
email=email,
|
|
display_name=display_name,
|
|
password_hash=hash_password(password),
|
|
role=invite.role,
|
|
)
|
|
db.add(user)
|
|
await db.flush() # populate user.id before we reference it below
|
|
|
|
invite.used_count += 1
|
|
|
|
return AuthenticatedSession(
|
|
user_id=user.id, email=user.email, display_name=user.display_name
|
|
)
|
|
|
|
|
|
async def login(
|
|
*, email: str, password: str, client: str, user_agent: str | None, ip: str | None
|
|
) -> tuple[str, AuthenticatedSession]:
|
|
"""Verify credentials and create a session. Returns (raw_token, session) — the raw token is
|
|
handed to the caller exactly once; only its hash is ever stored.
|
|
"""
|
|
async with auth_session() as db:
|
|
async with db.begin():
|
|
user = (await db.execute(select(User).where(User.email == email))).scalar_one_or_none()
|
|
|
|
# Deliberately identical error for "no such user" and "wrong password" — this is the
|
|
# one place a timing/response difference would leak which emails are registered.
|
|
if user is None or not user.is_active:
|
|
# Still run the hasher so this branch isn't measurably faster than a real
|
|
# mismatch (argon2's own duration masks a database-lookup-only shortcut).
|
|
verify_password(password, hash_password("decoy-password-never-matches"))
|
|
raise InvalidCredentials("invalid email or password")
|
|
if not verify_password(password, user.password_hash):
|
|
raise InvalidCredentials("invalid email or password")
|
|
|
|
settings = get_settings()
|
|
raw_token, token_hash = generate_token()
|
|
session_row = Session(
|
|
user_id=user.id,
|
|
token_hash=token_hash,
|
|
client=client,
|
|
user_agent=user_agent,
|
|
ip=ip,
|
|
expires_at=datetime.now(UTC) + timedelta(days=settings.session_ttl_days),
|
|
)
|
|
db.add(session_row)
|
|
|
|
return raw_token, AuthenticatedSession(
|
|
user_id=user.id, email=user.email, display_name=user.display_name
|
|
)
|
|
|
|
|
|
# Sessions are only touched this often to avoid a write on every single request; see
|
|
# docs/PLAN.md's auth section for the same throttling rule applied to last_seen_at.
|
|
_LAST_SEEN_THROTTLE = timedelta(minutes=5)
|
|
|
|
|
|
async def validate_session(raw_token: str) -> AuthenticatedSession:
|
|
"""Look a bearer token up and return the identity it belongs to, or raise SessionInvalid.
|
|
|
|
This is the auth entrypoint for every authenticated request — it's what runs *before*
|
|
db.scoped_session() can be used, because app.user_id isn't known until this returns.
|
|
"""
|
|
token_hash = hash_token(raw_token)
|
|
async with auth_session() as db:
|
|
async with db.begin():
|
|
row = (
|
|
await db.execute(
|
|
select(Session, User)
|
|
.join(User, User.id == Session.user_id)
|
|
.where(Session.token_hash == token_hash)
|
|
)
|
|
).one_or_none()
|
|
|
|
if row is None:
|
|
raise SessionInvalid("session not found")
|
|
session_row, user = row
|
|
|
|
if session_row.revoked_at is not None:
|
|
raise SessionInvalid("session has been revoked")
|
|
if session_row.expires_at < datetime.now(UTC):
|
|
raise SessionInvalid("session has expired")
|
|
if not user.is_active:
|
|
raise SessionInvalid("account is disabled")
|
|
|
|
now = datetime.now(UTC)
|
|
if now - session_row.last_seen_at > _LAST_SEEN_THROTTLE:
|
|
await db.execute(
|
|
update(Session).where(Session.id == session_row.id).values(last_seen_at=now)
|
|
)
|
|
|
|
return AuthenticatedSession(
|
|
user_id=user.id, email=user.email, display_name=user.display_name
|
|
)
|
|
|
|
|
|
async def logout(raw_token: str) -> None:
|
|
token_hash = hash_token(raw_token)
|
|
async with auth_session() as db:
|
|
async with db.begin():
|
|
await db.execute(
|
|
update(Session)
|
|
.where(Session.token_hash == token_hash, Session.revoked_at.is_(None))
|
|
.values(revoked_at=datetime.now(UTC))
|
|
)
|