Files
homelable/backend/app/api/routes/auth.py
T
Pouzor 6ace796c8b security: fix C2, H5 and M1
C2 - JWT token was stored in localStorage (XSS-accessible):
  - Switch Zustand persist storage from localStorage to sessionStorage
  - Token is now scoped to the current tab and cleared on browser close

H5 - docker-compose had unsafe SECRET_KEY fallback:
  - Replace ${SECRET_KEY:-change_me_in_production} with :? syntax
  - Docker Compose now aborts with a clear error if SECRET_KEY is unset

M1 - Login endpoint had timing leak allowing username enumeration:
  - Always call verify_password() regardless of username match
  - Use hmac.compare_digest() for constant-time username comparison
  - Both checks run every time; attacker cannot distinguish wrong
    username from wrong password via response timing
2026-03-09 00:13:01 +01:00

41 lines
1.3 KiB
Python

import hmac
import yaml
from fastapi import APIRouter, HTTPException, status
from pydantic import BaseModel
from app.core.config import settings
from app.core.security import create_access_token, verify_password
router = APIRouter()
class LoginRequest(BaseModel):
username: str
password: str
class TokenResponse(BaseModel):
access_token: str
token_type: str = "bearer"
def _load_credentials() -> tuple[str, str]:
with open(settings.config_path) as f:
cfg = yaml.safe_load(f)
auth = cfg.get("auth", {})
return auth.get("username", "admin"), auth.get("password_hash", "")
@router.post("/login", response_model=TokenResponse)
async def login(body: LoginRequest) -> TokenResponse:
username, password_hash = _load_credentials()
# Always run both checks to prevent timing-based username enumeration.
# hmac.compare_digest is constant-time; verify_password (bcrypt) always runs.
username_ok = hmac.compare_digest(body.username, username)
password_ok = verify_password(body.password, password_hash)
if not username_ok or not password_ok:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials")
token = create_access_token(body.username)
return TokenResponse(access_token=token)