27b66d6753
Introduce an always-on auth layer with auto-created admin on first boot, multi-tenant isolation for threads/stores, and a full setup/login flow. Backend - JWT access tokens with `ver` field for stale-token rejection; bump on password/email change - Password hashing, HttpOnly+Secure cookies (Secure derived from request scheme at runtime) - CSRF middleware covering both REST and LangGraph routes - IP-based login rate limiting (5 attempts / 5-min lockout) with bounded dict growth and X-Forwarded-For bypass fix - Multi-worker-safe admin auto-creation (single DB write, WAL once) - needs_setup + token_version on User model; SQLite schema migration - Thread/store isolation by owner; orphan thread migration on first admin registration - thread_id validated as UUID to prevent log injection - CLI tool to reset admin password - Decorator-based authz module extracted from auth core Frontend - Login and setup pages with SSR guard for needs_setup flow - Account settings page (change password / email) - AuthProvider + route guards; skips redirect when no users registered - i18n (en-US / zh-CN) for auth surfaces - Typed auth API client; parseAuthError unwraps FastAPI detail envelope Infra & tooling - Unified `serve.sh` with gateway mode + auto dep install - Public PyPI uv.toml pin for CI compatibility - Regenerated uv.lock with public index Tests - HTTP vs HTTPS cookie security tests - Auth middleware, rate limiter, CSRF, setup flow coverage
56 lines
1.6 KiB
Python
56 lines
1.6 KiB
Python
"""JWT token creation and verification."""
|
|
|
|
from datetime import UTC, datetime, timedelta
|
|
|
|
import jwt
|
|
from pydantic import BaseModel
|
|
|
|
from app.gateway.auth.config import get_auth_config
|
|
from app.gateway.auth.errors import TokenError
|
|
|
|
|
|
class TokenPayload(BaseModel):
|
|
"""JWT token payload."""
|
|
|
|
sub: str # user_id
|
|
exp: datetime
|
|
iat: datetime | None = None
|
|
ver: int = 0 # token_version — must match User.token_version
|
|
|
|
|
|
def create_access_token(user_id: str, expires_delta: timedelta | None = None, token_version: int = 0) -> str:
|
|
"""Create a JWT access token.
|
|
|
|
Args:
|
|
user_id: The user's UUID as string
|
|
expires_delta: Optional custom expiry, defaults to 7 days
|
|
token_version: User's current token_version for invalidation
|
|
|
|
Returns:
|
|
Encoded JWT string
|
|
"""
|
|
config = get_auth_config()
|
|
expiry = expires_delta or timedelta(days=config.token_expiry_days)
|
|
|
|
now = datetime.now(UTC)
|
|
payload = {"sub": user_id, "exp": now + expiry, "iat": now, "ver": token_version}
|
|
return jwt.encode(payload, config.jwt_secret, algorithm="HS256")
|
|
|
|
|
|
def decode_token(token: str) -> TokenPayload | TokenError:
|
|
"""Decode and validate a JWT token.
|
|
|
|
Returns:
|
|
TokenPayload if valid, or a specific TokenError variant.
|
|
"""
|
|
config = get_auth_config()
|
|
try:
|
|
payload = jwt.decode(token, config.jwt_secret, algorithms=["HS256"])
|
|
return TokenPayload(**payload)
|
|
except jwt.ExpiredSignatureError:
|
|
return TokenError.EXPIRED
|
|
except jwt.InvalidSignatureError:
|
|
return TokenError.INVALID_SIGNATURE
|
|
except jwt.PyJWTError:
|
|
return TokenError.MALFORMED
|