P0.1 — fail-closed secrets: - config.py: no default SECRET_KEY; refuses to boot when unset, a known placeholder, or <32 chars. Generate with: openssl rand -hex 32. - docker-compose.yml: literal secrets removed; runtime env now comes from a git-ignored .env via env_file. .env.example added as template. - .gitignore already covers .env (verified). P0.2 — locked CORS: - main.py: CORS_ORIGINS must be an explicit comma-separated allow-list. '*' or an empty value refuses to boot (was: silently ['*'] with allow_credentials=True). P0.3 — role-safe registration: - services/auth.py: client-supplied 'role' is IGNORED on POST /api/auth/register; self-registered users always get the least-privilege 'CS Rep' role. Unauthenticated callers can no longer mint Admin/Jerome, Admin/Wahab, or Director accounts. Tests: - conftest.py sets test SECRET_KEY/CORS_ORIGINS before app import. - New tests/test_p0_hardening.py (8 tests): role-escalation blocked for Admin/Jerome and Admin/Wahab, duplicate-email 409, and subprocess boot-validation for placeholder/short/missing secret + wildcard CORS. - Full suite: 44 passed. Redeploy note (per research): seed_units/seed_categories are insert-only, so the Aug-26 redeploy does NOT orphan historical tickets referencing units 103E/103W/105E/105W or the legacy 34-category tree. Pending Wahab: are 103E/103W/105E/105W real apartments dropped from the Excel regeneration? Optional follow-up: floor-number backfill for already- seeded units (mapping corrected floors; existing rows keep old values). Checks per HARDENING.md acceptance: - [x] starting without a real key fails loudly (subprocess-verified) - [x] compose carries no literal secret; secrets come from .env - [x] CORS_ORIGINS explicit allow-list, '*' rejected - [x] unauthenticated register cannot mint Admin/* or Director
82 lines
3.1 KiB
Python
82 lines
3.1 KiB
Python
"""Authentication service — register, login, refresh."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from fastapi import HTTPException, status
|
|
from sqlalchemy import select
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.core.security import (
|
|
create_access_token,
|
|
create_refresh_token,
|
|
decode_token,
|
|
hash_password,
|
|
verify_password,
|
|
)
|
|
from app.models.user import User
|
|
from app.schemas.auth import RegisterRequest
|
|
|
|
# HARDENING.md P0.3 — least-privilege default for self-registered users.
|
|
_SELF_REGISTER_ROLE = "CS Rep"
|
|
|
|
|
|
async def register(db: AsyncSession, body: RegisterRequest) -> User:
|
|
"""Create a new user. Raises 409 if email already exists.
|
|
|
|
HARDENING.md P0.3: unauthenticated self-registration must never mint a
|
|
privileged role. The client-supplied ``role`` field is IGNORED — new
|
|
self-registered users always land on the least-privilege role.
|
|
Admins assign elevated roles directly (DB seed / admin endpoint).
|
|
"""
|
|
result = await db.execute(select(User).where(User.email == body.email))
|
|
if result.scalar_one_or_none():
|
|
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="Email already registered")
|
|
|
|
user = User(
|
|
email=body.email,
|
|
password_hash=hash_password(body.password),
|
|
full_name=body.full_name,
|
|
phone=body.phone,
|
|
role=_SELF_REGISTER_ROLE,
|
|
)
|
|
db.add(user)
|
|
await db.flush()
|
|
await db.refresh(user)
|
|
return user
|
|
|
|
|
|
async def login(db: AsyncSession, email: str, password: str) -> tuple[str, str, User]:
|
|
"""Authenticate and return (access_token, refresh_token, user)."""
|
|
result = await db.execute(select(User).where(User.email == email))
|
|
user = result.scalar_one_or_none()
|
|
if user is None or not verify_password(password, user.password_hash):
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid email or password")
|
|
if not user.active:
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Account is inactive")
|
|
|
|
access_token = create_access_token({"sub": str(user.id)})
|
|
refresh_token = create_refresh_token({"sub": str(user.id)})
|
|
return access_token, refresh_token, user
|
|
|
|
|
|
async def refresh_access_token(db: AsyncSession, token: str) -> tuple[str, str]:
|
|
"""Validate a refresh token and issue a new token pair."""
|
|
try:
|
|
payload = decode_token(token)
|
|
if payload.get("type") != "refresh":
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token type")
|
|
except HTTPException:
|
|
raise
|
|
except Exception:
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid refresh token")
|
|
|
|
user_id: int = int(payload["sub"])
|
|
result = await db.execute(select(User).where(User.id == user_id))
|
|
user = result.scalar_one_or_none()
|
|
if user is None or not user.active:
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found or inactive")
|
|
|
|
new_access = create_access_token({"sub": str(user.id)})
|
|
new_refresh = create_refresh_token({"sub": str(user.id)})
|
|
return new_access, new_refresh
|