Add auth foundation: sessions/tokens schema, Argon2 hashing, config

Two tables (sessions, user_tokens) + migration; only token *hashes* are stored, so a DB leak yields no usable credential. Argon2id password hashing and token primitives in app/core/security. Config and .env.example gain session/cookie/token TTLs, app base URL, and SMTP settings (twelve-factor). Migration verified reversible (drops the token_purpose enum) and matches the models.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Signed-off-by: Justin Paul <justin@jpaul.me>
This commit is contained in:
2026-06-06 10:51:51 -04:00
parent e5a8713293
commit 5123c85397
9 changed files with 278 additions and 0 deletions
+16
View File
@@ -27,6 +27,22 @@ class Settings(BaseSettings):
default="postgresql+asyncpg://provenance:provenance@localhost:5432/provenance",
)
# --- Auth / sessions ---
session_ttl_days: int = 30
token_ttl_hours: int = 24 # email-verify / password-reset token lifetime
cookie_name: str = "provenance_session"
cookie_secure: bool = True # set false for local http; true behind TLS
# Base URL used to build links in outbound email.
app_base_url: str = "http://localhost"
# --- Email (SMTP) ---
mailer: str = Field(default="console", description="console | smtp")
smtp_host: str | None = None
smtp_port: int = 587
smtp_username: str | None = None
smtp_password: str | None = None
smtp_from: str = "Provenance <no-reply@provenance.local>"
@lru_cache
def get_settings() -> Settings:
+35
View File
@@ -0,0 +1,35 @@
"""Password hashing and token primitives.
Passwords use Argon2id (argon2-cffi). Session and email tokens are random
high-entropy strings; only their SHA-256 hash is stored, so a database leak
never exposes a usable credential.
"""
import hashlib
import secrets
from argon2 import PasswordHasher
from argon2.exceptions import Argon2Error
_hasher = PasswordHasher()
def hash_password(password: str) -> str:
return _hasher.hash(password)
def verify_password(password_hash: str, password: str) -> bool:
try:
return _hasher.verify(password_hash, password)
except (Argon2Error, ValueError):
return False
def generate_token() -> str:
"""A URL-safe, high-entropy token (the raw secret handed to the client)."""
return secrets.token_urlsafe(32)
def hash_token(token: str) -> str:
"""SHA-256 of a token — what we store and look up by."""
return hashlib.sha256(token.encode("utf-8")).hexdigest()
+3
View File
@@ -2,6 +2,7 @@
and for ``create_all`` in tests."""
from app.models.audit import AuditEntry
from app.models.auth import Session, UserToken
from app.models.base import Base
from app.models.event import Event
from app.models.person import Name, Person
@@ -25,4 +26,6 @@ __all__ = [
"Source",
"Citation",
"AuditEntry",
"Session",
"UserToken",
]
+43
View File
@@ -0,0 +1,43 @@
"""Authentication state: opaque backend-issued sessions and single-use email
tokens. Only token *hashes* are stored (see app.core.security).
"""
import uuid
from datetime import datetime
from sqlalchemy import DateTime, ForeignKey, String, func
from sqlalchemy import Enum as SAEnum
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
from app.models.enums import TokenPurpose
from app.models.mixins import UUIDPrimaryKey
class Session(Base, UUIDPrimaryKey):
__tablename__ = "sessions"
user_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("users.id", ondelete="CASCADE"), index=True
)
token_hash: Mapped[str] = mapped_column(String(64), unique=True, index=True)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now(), nullable=False
)
expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
revoked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
class UserToken(Base, UUIDPrimaryKey):
__tablename__ = "user_tokens"
user_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("users.id", ondelete="CASCADE"), index=True
)
purpose: Mapped[TokenPurpose] = mapped_column(SAEnum(TokenPurpose, name="token_purpose"))
token_hash: Mapped[str] = mapped_column(String(64), unique=True, index=True)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now(), nullable=False
)
expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
used_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
+5
View File
@@ -55,3 +55,8 @@ class CitationConfidence(enum.StrEnum):
class AuditActorType(enum.StrEnum):
user = "user"
assistant = "assistant"
class TokenPurpose(enum.StrEnum):
email_verify = "email_verify"
password_reset = "password_reset"