Implement security hardening across frontend, backend, and infrastructure

- nginx: add X-Content-Type-Options, X-Frame-Options, X-XSS-Protection,
  and Referrer-Policy headers on all responses; rate limit /api/auth/login
  to 5 req/min per IP (burst 3) to prevent brute force
- frontend: add escHtml() utility to api.js; use it on all notes fields
  across dashboard, log, history, flock, and budget pages to prevent XSS
- log.js: fix broken loadRecent() call referencing removed #recent-body
  element; replaced with loadHistory() from history.js
- schemas.py: raise minimum password length from 6 to 10 characters
- admin.py: add audit logging for password reset, disable, delete, and
  impersonate actions; fix impersonate to use named admin param for logging
- main.py: add startup env validation — exits with clear error if any
  required env var is missing; configure structured logging to stdout
- docker-compose.yml: add log rotation (10 MB / 3 files) to all services

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-17 23:55:08 -07:00
parent b660263f30
commit 37f19a83ed
11 changed files with 100 additions and 42 deletions

View File

@@ -1,5 +1,6 @@
import os
import logging
import sys
from contextlib import asynccontextmanager
from fastapi import FastAPI
@@ -12,8 +13,21 @@ from auth import hash_password
from routers import eggs, flock, feed, stats, other
from routers import auth_router, admin
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
stream=sys.stdout,
)
logger = logging.getLogger("yolkbook")
_REQUIRED_ENV = ["ADMIN_USERNAME", "ADMIN_PASSWORD", "JWT_SECRET", "DATABASE_URL"]
def _validate_env():
missing = [k for k in _REQUIRED_ENV if not os.environ.get(k)]
if missing:
logger.critical("Missing required environment variables: %s", ", ".join(missing))
sys.exit(1)
def _seed_admin():
"""Create or update the admin user from environment variables.
@@ -68,6 +82,7 @@ def _run_migrations():
@asynccontextmanager
async def lifespan(app: FastAPI):
_validate_env()
Base.metadata.create_all(bind=engine)
_run_migrations()
_seed_admin()

View File

@@ -1,3 +1,5 @@
import logging
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy import select
from sqlalchemy.orm import Session
@@ -8,6 +10,7 @@ from schemas import UserCreate, UserOut, ResetPasswordRequest, TokenResponse
from auth import hash_password, create_access_token, get_current_admin, get_current_user
router = APIRouter(prefix="/api/admin", tags=["admin"])
logger = logging.getLogger("yolkbook")
@router.get("/users", response_model=list[UserOut])
@@ -50,6 +53,7 @@ def reset_password(
raise HTTPException(status_code=404, detail="User not found")
user.hashed_password = hash_password(body.new_password)
db.commit()
logger.warning("Admin '%s' reset password for user '%s' (id=%d).", current_admin.username, user.username, user.id)
return {"detail": f"Password reset for {user.username}"}
@@ -66,6 +70,7 @@ def disable_user(
raise HTTPException(status_code=400, detail="Cannot disable your own account")
user.is_disabled = True
db.commit()
logger.warning("Admin '%s' disabled user '%s' (id=%d).", current_admin.username, user.username, user.id)
return {"detail": f"User {user.username} disabled"}
@@ -94,6 +99,7 @@ def delete_user(
raise HTTPException(status_code=404, detail="User not found")
if user.id == current_admin.id:
raise HTTPException(status_code=400, detail="Cannot delete your own account")
logger.warning("Admin '%s' deleted user '%s' (id=%d).", current_admin.username, user.username, user.id)
db.delete(user)
db.commit()
@@ -101,11 +107,12 @@ def delete_user(
@router.post("/users/{user_id}/impersonate", response_model=TokenResponse)
def impersonate_user(
user_id: int,
_: User = Depends(get_current_admin),
current_admin: User = Depends(get_current_admin),
db: Session = Depends(get_db),
):
user = db.get(User, user_id)
if not user:
raise HTTPException(status_code=404, detail="User not found")
token = create_access_token(user.id, user.username, user.is_admin, user.timezone)
logger.warning("Admin '%s' (id=%d) is impersonating user '%s' (id=%d).", current_admin.username, current_admin.id, user.username, user.id)
return TokenResponse(access_token=token)

View File

@@ -16,10 +16,10 @@ class TokenResponse(BaseModel):
class ChangePasswordRequest(BaseModel):
current_password: str
new_password: str = Field(min_length=6)
new_password: str = Field(min_length=10)
class ResetPasswordRequest(BaseModel):
new_password: str = Field(min_length=6)
new_password: str = Field(min_length=10)
class TimezoneUpdate(BaseModel):
timezone: str = Field(min_length=1, max_length=64)
@@ -29,7 +29,7 @@ class TimezoneUpdate(BaseModel):
class UserCreate(BaseModel):
username: str = Field(min_length=2, max_length=64)
password: str = Field(min_length=6)
password: str = Field(min_length=10)
class UserOut(BaseModel):
id: int