feat(admin): rebuild admin panel as out-of-band login with backups

- Separate admin login (ADMIN_USERNAME/ADMIN_PASSWORD) with its own JWT,
  no longer a seeded user account; lockout after 5 failed attempts
- Admin panel tabs: Users, Notifications, Backups, Reset
- Ntfy settings moved from .env/compose into admin_settings (token encrypted)
- Scheduled and on-demand mariadb-dump backups to NFS volume, with
  restore (entries only or all) and retention pruning
- Reset all entries, guarded by an automatic safety backup
- Remove user impersonation and the admin link in the user nav
- Login page falls back to admin login; nginx sends Cache-Control: no-cache

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
derekcandClaude Opus 5.5 committed 2026-11-23 00:24:19 -08:00
1 parent c54d2b251f
commit 6272322f31
28 files changed
+1523 -461

No files matched your search

+9 -1
View File
@@ -2,12 +2,20 @@ FROM python:3.12-slim
WORKDIR /app
# mariadb-client provides mariadb-dump / mariadb, used by app/services/backup.py
# for the admin panel's backups and restores (works against the MySQL 8 server).
RUN apt-get update && apt-get install -y --no-install-recommends mariadb-client \
&& rm -rf /var/lib/apt/lists/*
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app/ ./app/
RUN useradd -r -s /bin/false appuser
# uid 1000 so the NFS backup share (writable by uid 1000) mounted at /backups works.
RUN useradd -r -u 1000 -s /bin/false appuser \
&& mkdir -p /backups \
&& chown appuser:appuser /backups
USER appuser
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
+3 -5
View File
@@ -1,4 +1,3 @@
from typing import Optional
from pydantic_settings import BaseSettings
@@ -7,11 +6,10 @@ class Settings(BaseSettings):
secret_key: str
access_token_expire_minutes: int = 480
algorithm: str = "HS256"
admin_username: str
admin_password: str
# Out-of-band admin login (not a DB user). Both must be set to enable it.
admin_username: str = ""
admin_password: str = ""
allowed_origins: str = "http://localhost"
ntfy_url: Optional[str] = None
ntfy_token: Optional[str] = None
class Config:
env_file = ".env"
+1 -1
View File
@@ -14,7 +14,7 @@ class Base(DeclarativeBase):
async def init_db() -> None:
# Import models so their tables are registered on Base.metadata before create_all
from app.models import user, entry # noqa: F401
from app.models import user, entry, admin_settings # noqa: F401
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
+5 -5
View File
@@ -6,7 +6,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from app.database import AsyncSessionLocal
from app.utils.security import decode_token
from app.utils.security import decode_token, is_admin_token
bearer_scheme = HTTPBearer()
@@ -37,7 +37,7 @@ async def get_current_user(
return user
async def get_current_admin(current_user=Depends(get_current_user)):
if not current_user.is_admin:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Admin access required")
return current_user
async def get_current_admin(credentials: HTTPAuthorizationCredentials = Depends(bearer_scheme)) -> None:
# Out-of-band admin: authenticated by an admin-only JWT, not a DB user.
if not is_admin_token(credentials.credentials):
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Admin access required")
+6 -23
View File
@@ -3,14 +3,14 @@ from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy import select
from slowapi import _rate_limit_exceeded_handler
from slowapi.errors import RateLimitExceeded
from app.config import settings
from app.database import init_db, AsyncSessionLocal
from app import scheduler
from app.database import init_db
from app.limiter import limiter
from app.routers import auth, users, entries, public, admin
from app.routers import auth, users, entries, public, admin, backups
logging.basicConfig(
level=logging.INFO,
@@ -19,31 +19,13 @@ logging.basicConfig(
logger = logging.getLogger("bourbonacci")
async def _seed_admin() -> None:
from app.models.user import User
from app.utils.security import hash_password
async with AsyncSessionLocal() as db:
result = await db.execute(select(User).where(User.email == settings.admin_username))
user = result.scalar_one_or_none()
if user is None:
db.add(User(
email=settings.admin_username,
password_hash=hash_password(settings.admin_password),
display_name="Admin",
is_admin=True,
))
elif not user.is_admin:
user.is_admin = True
await db.commit()
@asynccontextmanager
async def lifespan(app: FastAPI):
await init_db()
await _seed_admin()
await scheduler.start()
logger.info("Bourbonacci started")
yield
scheduler.shutdown()
logger.info("Bourbonacci shutting down")
@@ -64,6 +46,7 @@ app.include_router(users.router)
app.include_router(entries.router)
app.include_router(public.router)
app.include_router(admin.router)
app.include_router(backups.router)
@app.get("/health")
+34
View File
@@ -0,0 +1,34 @@
from datetime import datetime
from typing import Optional
from sqlalchemy import Boolean, DateTime, Integer, String
from sqlalchemy.orm import Mapped, mapped_column
from app.database import Base
class AdminSettings(Base):
"""Single-row table (id=1) holding admin-only config that's edited live from the admin panel."""
__tablename__ = "admin_settings"
id: Mapped[int] = mapped_column(primary_key=True)
ntfy_server_url: Mapped[Optional[str]] = mapped_column(String(255))
ntfy_topic: Mapped[Optional[str]] = mapped_column(String(255))
ntfy_token: Mapped[Optional[str]] = mapped_column(String(500))
# Scheduled backups (see routers/backups.py, services/backup.py).
backup_enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
backup_frequency: Mapped[str] = mapped_column(String(10), nullable=False, default="daily")
backup_hour: Mapped[int] = mapped_column(Integer, nullable=False, default=3) # 0-23, UTC
backup_weekday: Mapped[int] = mapped_column(Integer, nullable=False, default=0) # 0=Mon, used if weekly
backup_retention: Mapped[int] = mapped_column(Integer, nullable=False, default=14)
# Optional subfolder under the mounted /backups directory.
backup_location: Mapped[Optional[str]] = mapped_column(String(255))
last_backup_at: Mapped[Optional[datetime]] = mapped_column(DateTime) # UTC
last_backup_status: Mapped[Optional[str]] = mapped_column(String(20)) # "success" | "error"
last_backup_error: Mapped[Optional[str]] = mapped_column(String(2000))
# Brute-force protection for the out-of-band admin login.
admin_failed_attempts: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
admin_locked_until: Mapped[Optional[datetime]] = mapped_column(DateTime) # UTC
+207 -115
View File
@@ -1,149 +1,241 @@
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
import secrets
from datetime import datetime, timedelta, timezone
from app.dependencies import get_db, get_current_admin, bearer_scheme
from fastapi import APIRouter, Depends, HTTPException, Request, status
from sqlalchemy import delete, func, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.config import settings
from app.dependencies import get_current_admin, get_db
from app.limiter import limiter
from app.models.admin_settings import AdminSettings
from app.models.entry import Entry
from app.models.user import User
from app.schemas.user import AdminUserCreate, AdminPasswordReset, AdminUserResponse, Token
from app.utils.security import hash_password, create_token
from app.schemas.admin import (
AdminLogin,
AdminNtfySettingsOut,
AdminNtfySettingsUpdate,
AdminTokenOut,
AdminUserOut,
ResetPasswordOut,
ResetResultOut,
)
from app.services.backup import BackupError, run_backup
from app.utils.crypto import encrypt
from app.utils.notify import notify
from app.utils.security import create_admin_token, hash_password
router = APIRouter(prefix="/api/admin", tags=["admin"])
@router.get("/users", response_model=list[AdminUserResponse])
async def list_users(
_: User = Depends(get_current_admin),
db: AsyncSession = Depends(get_db),
):
result = await db.execute(select(User).order_by(User.created_at))
return result.scalars().all()
MAX_FAILED_ADMIN_ATTEMPTS = 5
ADMIN_LOCKOUT_MINUTES = 15
@router.post("/users", response_model=AdminUserResponse, status_code=status.HTTP_201_CREATED)
async def create_user(
body: AdminUserCreate,
_: User = Depends(get_current_admin),
db: AsyncSession = Depends(get_db),
):
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")
def _utcnow() -> datetime:
# MySQL DATETIME columns are naive; store UTC.
return datetime.now(timezone.utc).replace(tzinfo=None)
user = User(
email=body.email,
password_hash=hash_password(body.password),
display_name=body.display_name or body.email.split("@")[0],
is_admin=False,
)
db.add(user)
async def _get_admin_settings(db: AsyncSession) -> AdminSettings:
row = (await db.execute(select(AdminSettings).where(AdminSettings.id == 1))).scalar_one_or_none()
if not row:
row = AdminSettings(id=1)
db.add(row)
await db.flush()
return row
@router.post("/login", response_model=AdminTokenOut)
@limiter.limit("5/minute")
async def admin_login(request: Request, body: AdminLogin, db: AsyncSession = Depends(get_db)):
if not settings.admin_username or not settings.admin_password:
raise HTTPException(status_code=503, detail="Admin login is not configured")
row = await _get_admin_settings(db)
if row.admin_locked_until and row.admin_locked_until > _utcnow():
raise HTTPException(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail="Admin login temporarily locked after repeated failed attempts. Try again later.",
)
ok_user = secrets.compare_digest(body.username.encode(), settings.admin_username.encode())
ok_pass = secrets.compare_digest(body.password.encode(), settings.admin_password.encode())
if not (ok_user and ok_pass):
row.admin_failed_attempts += 1
if row.admin_failed_attempts >= MAX_FAILED_ADMIN_ATTEMPTS:
row.admin_locked_until = _utcnow() + timedelta(minutes=ADMIN_LOCKOUT_MINUTES)
row.admin_failed_attempts = 0
await db.commit()
await notify(
"Admin login locked",
f"Admin login was locked out after {MAX_FAILED_ADMIN_ATTEMPTS} failed attempts.",
priority="high",
tags=["warning", "rotating_light"],
)
else:
await db.commit()
raise HTTPException(status_code=401, detail="Invalid admin credentials")
row.admin_failed_attempts = 0
row.admin_locked_until = None
await db.commit()
await db.refresh(user)
await notify("Admin login", "Successful admin login.", priority="high", tags=["closed_lock_with_key"])
return AdminTokenOut(access_token=create_admin_token())
# ── Users ────────────────────────────────────────────────────────────────────
@router.get("/users", response_model=list[AdminUserOut], dependencies=[Depends(get_current_admin)])
async def list_users(db: AsyncSession = Depends(get_db)):
rows = (
await db.execute(
select(User, func.count(Entry.id))
.outerjoin(Entry, Entry.user_id == User.id)
.group_by(User.id)
.order_by(func.lower(User.email))
)
).all()
return [
AdminUserOut(
id=u.id,
email=u.email,
display_name=u.display_name,
created_at=u.created_at,
is_disabled=u.is_disabled,
entry_count=count,
)
for u, count in rows
]
async def _get_user(user_id: int, db: AsyncSession) -> User:
user = (await db.execute(select(User).where(User.id == user_id))).scalar_one_or_none()
if not user:
raise HTTPException(status_code=404, detail="User not found")
return user
@router.post("/users/{user_id}/reset-password", status_code=status.HTTP_204_NO_CONTENT)
async def reset_password(
user_id: int,
body: AdminPasswordReset,
_: User = Depends(get_current_admin),
db: AsyncSession = Depends(get_db),
):
result = await db.execute(select(User).where(User.id == user_id))
user = result.scalar_one_or_none()
if not user:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
user.password_hash = hash_password(body.new_password)
@router.post(
"/users/{user_id}/reset-password",
response_model=ResetPasswordOut,
dependencies=[Depends(get_current_admin)],
)
async def reset_password(user_id: int, db: AsyncSession = Depends(get_db)):
user = await _get_user(user_id, db)
temp_password = secrets.token_urlsafe(9)
user.password_hash = hash_password(temp_password)
await db.commit()
await notify("Password reset issued", f"A temp password was issued for {user.email}.")
return ResetPasswordOut(temp_password=temp_password)
@router.post("/users/{user_id}/disable", status_code=status.HTTP_204_NO_CONTENT)
async def disable_user(
user_id: int,
current_admin: User = Depends(get_current_admin),
db: AsyncSession = Depends(get_db),
):
if user_id == current_admin.id:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Cannot disable your own account")
result = await db.execute(select(User).where(User.id == user_id))
user = result.scalar_one_or_none()
if not user:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
@router.post(
"/users/{user_id}/disable",
status_code=status.HTTP_204_NO_CONTENT,
dependencies=[Depends(get_current_admin)],
)
async def disable_user(user_id: int, db: AsyncSession = Depends(get_db)):
user = await _get_user(user_id, db)
user.is_disabled = True
await db.commit()
await notify("User Disabled", f"Account disabled: {user.email} (by admin {current_admin.email})", priority="default")
await notify("User disabled", f"Account disabled: {user.email}")
@router.post("/users/{user_id}/enable", status_code=status.HTTP_204_NO_CONTENT)
async def enable_user(
user_id: int,
_: User = Depends(get_current_admin),
db: AsyncSession = Depends(get_db),
):
result = await db.execute(select(User).where(User.id == user_id))
user = result.scalar_one_or_none()
if not user:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
@router.post(
"/users/{user_id}/enable",
status_code=status.HTTP_204_NO_CONTENT,
dependencies=[Depends(get_current_admin)],
)
async def enable_user(user_id: int, db: AsyncSession = Depends(get_db)):
user = await _get_user(user_id, db)
user.is_disabled = False
await db.commit()
@router.delete("/users/{user_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_user(
user_id: int,
current_admin: User = Depends(get_current_admin),
db: AsyncSession = Depends(get_db),
):
if user_id == current_admin.id:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Cannot delete your own account")
result = await db.execute(select(User).where(User.id == user_id))
user = result.scalar_one_or_none()
if not user:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
@router.delete(
"/users/{user_id}",
status_code=status.HTTP_204_NO_CONTENT,
dependencies=[Depends(get_current_admin)],
)
async def delete_user(user_id: int, db: AsyncSession = Depends(get_db)):
user = await _get_user(user_id, db)
email = user.email
await db.delete(user)
await db.commit()
await notify("User Deleted", f"Account deleted: {user.email} (by admin {current_admin.email})", priority="default")
await notify("Account deleted", f"{email} was deleted.", tags=["warning"])
@router.post("/users/{user_id}/impersonate", response_model=Token)
async def impersonate_user(
user_id: int,
current_admin: User = Depends(get_current_admin),
db: AsyncSession = Depends(get_db),
):
if user_id == current_admin.id:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Cannot impersonate yourself")
# ── Notifications ────────────────────────────────────────────────────────────
result = await db.execute(select(User).where(User.id == user_id))
user = result.scalar_one_or_none()
if not user:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
return Token(access_token=create_token(user.id, admin_id=current_admin.id))
def _ntfy_settings_out(row: AdminSettings) -> AdminNtfySettingsOut:
return AdminNtfySettingsOut(
ntfy_server_url=row.ntfy_server_url,
ntfy_topic=row.ntfy_topic,
has_token=bool(row.ntfy_token),
)
@router.post("/unimpersonate", response_model=Token)
async def unimpersonate(
credentials=Depends(bearer_scheme),
db: AsyncSession = Depends(get_db),
):
from app.utils.security import decode_token_full
@router.get("/ntfy-settings", response_model=AdminNtfySettingsOut, dependencies=[Depends(get_current_admin)])
async def get_ntfy_settings(db: AsyncSession = Depends(get_db)):
row = await _get_admin_settings(db)
await db.commit()
return _ntfy_settings_out(row)
token = credentials.credentials
payload = decode_token_full(token)
admin_id = payload.get("admin_id") if payload else None
if not admin_id:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Not an impersonation token")
result = await db.execute(select(User).where(User.id == admin_id))
admin = result.scalar_one_or_none()
if not admin or not admin.is_admin or admin.is_disabled:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Admin not found")
@router.put("/ntfy-settings", response_model=AdminNtfySettingsOut, dependencies=[Depends(get_current_admin)])
async def update_ntfy_settings(body: AdminNtfySettingsUpdate, db: AsyncSession = Depends(get_db)):
row = await _get_admin_settings(db)
if body.ntfy_server_url is not None:
row.ntfy_server_url = body.ntfy_server_url.strip() or None
if body.ntfy_topic is not None:
row.ntfy_topic = body.ntfy_topic.strip() or None
if body.ntfy_token is not None:
row.ntfy_token = encrypt(body.ntfy_token) if body.ntfy_token else None
await db.commit()
await db.refresh(row)
return _ntfy_settings_out(row)
return Token(access_token=create_token(admin.id))
@router.post(
"/ntfy-settings/test",
status_code=status.HTTP_204_NO_CONTENT,
dependencies=[Depends(get_current_admin)],
)
async def test_ntfy_settings():
ok = await notify(
"Test notification",
"This is a test notification from the Bourbonacci admin panel.",
tags=["white_check_mark"],
)
if not ok:
raise HTTPException(status_code=502, detail="Failed to send test notification. Check your ntfy settings.")
# ── Reset ────────────────────────────────────────────────────────────────────
async def _safety_backup(db: AsyncSession) -> str:
"""Run a fresh backup before a destructive reset. Refuses to proceed
(raises 502) if the backup itself fails, so a broken backup path can
never leave a reset with no safety net."""
try:
backup = await run_backup(db)
except BackupError as exc:
raise HTTPException(status_code=502, detail=f"Safety backup failed, reset aborted: {exc}")
return backup.filename
@router.post("/reset/entries", response_model=ResetResultOut, dependencies=[Depends(get_current_admin)])
async def reset_entries(db: AsyncSession = Depends(get_db)):
"""Delete every entry for every user. User accounts and settings are untouched."""
backup_filename = await _safety_backup(db)
result = await db.execute(delete(Entry))
await db.commit()
await notify(
"Entries reset",
f"All entries were deleted ({result.rowcount or 0} rows). Safety backup: {backup_filename}",
priority="high",
tags=["rotating_light"],
)
return ResetResultOut(entries_deleted=result.rowcount or 0, backup_filename=backup_filename)
+1 -3
View File
@@ -37,7 +37,7 @@ async def register(request: Request, body: UserCreate, db: AsyncSession = Depend
await db.refresh(user)
logger.info("New user registered: %s", body.email)
await notify("New Registration", f"User registered: {body.email}", priority="default")
await notify("New registration", f"User registered: {body.email}", tags=["bust_in_silhouette"])
return Token(access_token=create_token(user.id))
@@ -56,6 +56,4 @@ async def login(request: Request, body: LoginRequest, db: AsyncSession = Depends
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Account disabled")
logger.info("Login: %s (id=%s)", body.email, user.id)
if user.is_admin:
await notify("Admin Login", f"Admin login: {body.email}", priority="high")
return Token(access_token=create_token(user.id))
+104
View File
@@ -0,0 +1,104 @@
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app import scheduler
from app.dependencies import get_current_admin, get_db
from app.models.admin_settings import AdminSettings
from app.schemas.admin import (
BackupFileOut,
BackupSettingsOut,
BackupSettingsUpdate,
RestoreRequest,
RestoreResult,
)
from app.services.backup import (
BackupError,
delete_backup,
list_backups,
normalize_backup_location,
restore_backup,
run_backup,
)
from app.utils.notify import notify
router = APIRouter(
prefix="/api/admin/backups", tags=["backups"], dependencies=[Depends(get_current_admin)]
)
async def _get_settings_row(db: AsyncSession) -> AdminSettings:
row = (await db.execute(select(AdminSettings).where(AdminSettings.id == 1))).scalar_one_or_none()
if not row:
row = AdminSettings(id=1)
db.add(row)
await db.commit()
await db.refresh(row)
return row
@router.get("/settings", response_model=BackupSettingsOut)
async def get_backup_settings(db: AsyncSession = Depends(get_db)):
return await _get_settings_row(db)
@router.put("/settings", response_model=BackupSettingsOut)
async def update_backup_settings(body: BackupSettingsUpdate, db: AsyncSession = Depends(get_db)):
try:
location = normalize_backup_location(body.backup_location)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
row = await _get_settings_row(db)
row.backup_enabled = body.backup_enabled
row.backup_frequency = body.backup_frequency
row.backup_hour = body.backup_hour
row.backup_weekday = body.backup_weekday
row.backup_retention = body.backup_retention
row.backup_location = location
await db.commit()
await db.refresh(row)
scheduler.reschedule(row.backup_enabled, row.backup_frequency, row.backup_hour, row.backup_weekday)
return row
@router.get("", response_model=list[BackupFileOut])
async def list_backup_files(db: AsyncSession = Depends(get_db)):
row = await _get_settings_row(db)
return list_backups(row.backup_location)
@router.post("/run", response_model=BackupFileOut, status_code=status.HTTP_201_CREATED)
async def run_backup_now(db: AsyncSession = Depends(get_db)):
try:
return await run_backup(db)
except BackupError as exc:
raise HTTPException(status_code=502, detail=f"Backup failed: {exc}")
@router.post("/{filename}/restore", response_model=RestoreResult)
async def restore_backup_file(filename: str, body: RestoreRequest, db: AsyncSession = Depends(get_db)):
try:
await restore_backup(filename, body.scope, db)
except ValueError:
raise HTTPException(status_code=400, detail="Invalid backup filename")
except FileNotFoundError:
raise HTTPException(status_code=404, detail="Backup file not found")
except BackupError as exc:
raise HTTPException(status_code=502, detail=f"Restore failed: {exc}")
await notify(
"Backup restored",
f"Restored '{filename}' (scope: {body.scope}).",
priority="high",
tags=["rotating_light"],
)
return RestoreResult(scope=body.scope, filename=filename)
@router.delete("/{filename}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_backup_file(filename: str, db: AsyncSession = Depends(get_db)):
row = await _get_settings_row(db)
try:
delete_backup(filename, row.backup_location)
except ValueError:
raise HTTPException(status_code=400, detail="Invalid backup filename")
+48
View File
@@ -0,0 +1,48 @@
import logging
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.cron import CronTrigger
from sqlalchemy import select
from app.database import AsyncSessionLocal
from app.models.admin_settings import AdminSettings
from app.services.backup import run_backup
logger = logging.getLogger("bourbonacci.scheduler")
_JOB_ID = "scheduled_backup"
_scheduler = AsyncIOScheduler(timezone="UTC")
async def _run_scheduled_backup() -> None:
async with AsyncSessionLocal() as db:
try:
await run_backup(db)
except Exception:
logger.exception("Scheduled backup failed")
def reschedule(enabled: bool, frequency: str, hour: int, weekday: int) -> None:
if _scheduler.get_job(_JOB_ID):
_scheduler.remove_job(_JOB_ID)
if not enabled:
return
trigger = CronTrigger(
hour=hour,
minute=0,
day_of_week=weekday if frequency == "weekly" else "*",
timezone="UTC",
)
_scheduler.add_job(_run_scheduled_backup, trigger, id=_JOB_ID, replace_existing=True)
async def start() -> None:
async with AsyncSessionLocal() as db:
row = (await db.execute(select(AdminSettings).where(AdminSettings.id == 1))).scalar_one_or_none()
if row:
reschedule(row.backup_enabled, row.backup_frequency, row.backup_hour, row.backup_weekday)
_scheduler.start()
def shutdown() -> None:
_scheduler.shutdown(wait=False)
+96
View File
@@ -0,0 +1,96 @@
from datetime import datetime, timezone
from typing import Literal, Optional
from pydantic import BaseModel, Field, field_validator
def _as_utc(v: Optional[datetime]) -> Optional[datetime]:
# MySQL DATETIME columns come back naive; they're stored as UTC.
if v is not None and v.tzinfo is None:
return v.replace(tzinfo=timezone.utc)
return v
class AdminLogin(BaseModel):
username: str
password: str
class AdminTokenOut(BaseModel):
access_token: str
token_type: str = "bearer"
class AdminUserOut(BaseModel):
id: int
email: str
display_name: Optional[str]
created_at: datetime
is_disabled: bool
entry_count: int
class ResetPasswordOut(BaseModel):
temp_password: str
class ResetResultOut(BaseModel):
entries_deleted: int = 0
# Filename of the safety backup taken automatically right before the reset.
backup_filename: Optional[str] = None
class AdminNtfySettingsOut(BaseModel):
ntfy_server_url: Optional[str]
ntfy_topic: Optional[str]
has_token: bool
class AdminNtfySettingsUpdate(BaseModel):
ntfy_server_url: Optional[str] = None
ntfy_topic: Optional[str] = None
ntfy_token: Optional[str] = None
BackupScope = Literal["entries", "all"]
BackupFrequency = Literal["daily", "weekly"]
class BackupSettingsOut(BaseModel):
backup_enabled: bool
backup_frequency: BackupFrequency
backup_hour: int
backup_weekday: int
backup_retention: int
backup_location: Optional[str] = None
last_backup_at: Optional[datetime] = None
last_backup_status: Optional[str] = None
last_backup_error: Optional[str] = None
model_config = {"from_attributes": True}
_utc = field_validator("last_backup_at")(_as_utc)
class BackupSettingsUpdate(BaseModel):
backup_enabled: bool
backup_frequency: BackupFrequency = "daily"
backup_hour: int = Field(default=3, ge=0, le=23)
backup_weekday: int = Field(default=0, ge=0, le=6)
backup_retention: int = Field(default=14, ge=1, le=365)
backup_location: Optional[str] = Field(default=None, max_length=255)
class BackupFileOut(BaseModel):
filename: str
size_bytes: int
created_at: datetime
class RestoreRequest(BaseModel):
scope: BackupScope
class RestoreResult(BaseModel):
scope: BackupScope
filename: str
-23
View File
@@ -26,7 +26,6 @@ class UserResponse(BaseModel):
display_name: Optional[str]
timezone: str
bottle_size: Optional[float]
is_admin: bool
created_at: datetime
model_config = {"from_attributes": True}
@@ -40,25 +39,3 @@ class Token(BaseModel):
class LoginRequest(BaseModel):
email: EmailStr
password: str
class AdminUserCreate(BaseModel):
email: EmailStr
password: str
display_name: Optional[str] = None
class AdminPasswordReset(BaseModel):
new_password: str
class AdminUserResponse(BaseModel):
id: int
email: str
display_name: Optional[str]
timezone: str
is_admin: bool
is_disabled: bool
created_at: datetime
model_config = {"from_attributes": True}
View File
Whitespace-only changes.
+229
View File
@@ -0,0 +1,229 @@
import asyncio
import gzip
import logging
import os
import re
import secrets
from datetime import datetime, timezone
from pathlib import Path
from typing import Literal
from sqlalchemy import select
from sqlalchemy.engine import make_url
from sqlalchemy.ext.asyncio import AsyncSession
from app.config import settings
from app.database import engine
from app.models.admin_settings import AdminSettings
from app.schemas.admin import BackupFileOut
logger = logging.getLogger("bourbonacci.backup")
BACKUP_ROOT = Path("/backups")
_FILENAME_PREFIX = "bourbonacci_"
_FILENAME_SUFFIX = ".sql.gz"
_TABLE_MARKER = re.compile(rb"^-- Table structure for table `([^`]+)`", re.MULTILINE)
# First statement of the trailer mysqldump/mariadb-dump writes after the last table.
_TRAILER_MARKER = re.compile(rb"^/\*!40103 SET TIME_ZONE=@OLD_TIME_ZONE \*/;", re.MULTILINE)
class BackupError(Exception):
"""A mariadb-dump/mariadb subprocess exited non-zero."""
def _utcnow() -> datetime:
# MySQL DATETIME columns are naive; store UTC.
return datetime.now(timezone.utc).replace(tzinfo=None)
def _conn_args() -> tuple[list[str], dict[str, str]]:
"""Connection flags for the MariaDB CLI tools, derived from DATABASE_URL.
The password goes in MYSQL_PWD so it never shows up in the process list."""
url = make_url(settings.database_url)
args = [
"-h", url.host or "localhost",
"-P", str(url.port or 3306),
"-u", url.username or "",
# MySQL 8.4 serves TLS with an auto-generated self-signed cert.
"--skip-ssl-verify-server-cert",
]
env = {**os.environ, "MYSQL_PWD": url.password or ""}
return args, env
def _db_name() -> str:
return make_url(settings.database_url).database or ""
async def _get_settings(db: AsyncSession) -> AdminSettings:
row = (await db.execute(select(AdminSettings).where(AdminSettings.id == 1))).scalar_one_or_none()
if not row:
row = AdminSettings(id=1)
db.add(row)
await db.flush()
return row
_LOCATION_RE = re.compile(r"^[A-Za-z0-9_-]+(/[A-Za-z0-9_-]+)*$")
def normalize_backup_location(location: str | None) -> str | None:
"""Validate the admin's optional backup subfolder: plain folder names
(letters, digits, - and _) nested with "/", so it can't point outside
BACKUP_ROOT. Raises ValueError otherwise."""
location = (location or "").strip().strip("/")
if not location:
return None
if not _LOCATION_RE.match(location):
raise ValueError("Subfolder may only contain letters, numbers, - and _, separated by /.")
return location
def backup_dir(location: str | None = None) -> Path:
d = BACKUP_ROOT / location.strip("/") if location else BACKUP_ROOT
# Belt and braces alongside normalize_backup_location: never create or
# use a directory outside BACKUP_ROOT, whatever is stored in the row.
if not d.resolve().is_relative_to(BACKUP_ROOT.resolve()):
raise ValueError("Backup location must be inside the backup directory")
d.mkdir(parents=True, exist_ok=True)
return d
def _resolve_backup_file(filename: str, location: str | None) -> Path:
"""Resolve a filename against the backup directory, rejecting anything
that escapes it (path traversal via `..`, absolute paths, etc)."""
base = backup_dir(location).resolve()
candidate = (base / filename).resolve()
if not candidate.is_relative_to(base) or candidate.parent != base:
raise ValueError("Invalid backup filename")
return candidate
def list_backups(location: str | None = None) -> list[BackupFileOut]:
d = backup_dir(location)
files = [
BackupFileOut(
filename=f.name,
size_bytes=f.stat().st_size,
created_at=datetime.fromtimestamp(f.stat().st_mtime, tz=timezone.utc),
)
for f in d.iterdir()
if f.is_file() and f.name.startswith(_FILENAME_PREFIX) and f.name.endswith(_FILENAME_SUFFIX)
]
files.sort(key=lambda b: b.created_at, reverse=True)
return files
def prune_backups(retention: int, location: str | None = None) -> int:
files = list_backups(location)
to_delete = files[retention:]
for f in to_delete:
(backup_dir(location) / f.filename).unlink(missing_ok=True)
return len(to_delete)
async def _dump_to(path: Path) -> None:
conn, env = _conn_args()
proc = await asyncio.create_subprocess_exec(
"mariadb-dump", *conn,
"--single-transaction", "--no-tablespaces", "--skip-lock-tables",
_db_name(),
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, env=env,
)
stderr_task = asyncio.create_task(proc.stderr.read())
with gzip.open(path, "wb") as out:
while chunk := await proc.stdout.read(65536):
out.write(chunk)
stderr = await stderr_task
await proc.wait()
if proc.returncode != 0:
raise BackupError(stderr.decode(errors="replace").strip() or f"mariadb-dump exited {proc.returncode}")
async def _load_sql(sql: bytes) -> None:
conn, env = _conn_args()
proc = await asyncio.create_subprocess_exec(
"mariadb", *conn, _db_name(),
stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, env=env,
)
_, stderr = await proc.communicate(input=sql)
if proc.returncode != 0:
raise BackupError(stderr.decode(errors="replace").strip() or f"mariadb exited {proc.returncode}")
def _extract_table(sql: bytes, table: str) -> bytes:
"""Return the dump's header + the given table's DROP/CREATE/INSERT section + trailer,
so just that one table can be reloaded from a full-database dump."""
markers = list(_TABLE_MARKER.finditer(sql))
trailer = _TRAILER_MARKER.search(sql)
if not markers or not trailer:
raise BackupError("Backup file is not in the expected mysqldump format")
header = sql[: markers[0].start()]
for i, m in enumerate(markers):
if m.group(1).decode() == table:
end = markers[i + 1].start() if i + 1 < len(markers) else trailer.start()
return header + sql[m.start(): end] + sql[trailer.start():]
raise BackupError(f"Backup file has no `{table}` table")
async def run_backup(db: AsyncSession) -> BackupFileOut:
row = await _get_settings(db)
d = backup_dir(row.backup_location)
# A short random suffix guards against two backups landing in the same
# second (e.g. rapid "Backup now" clicks), which would otherwise silently
# overwrite one another.
stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
path = d / f"{_FILENAME_PREFIX}{stamp}_{secrets.token_hex(3)}{_FILENAME_SUFFIX}"
try:
await _dump_to(path)
except BackupError as exc:
path.unlink(missing_ok=True)
row.last_backup_at = _utcnow()
row.last_backup_status = "error"
row.last_backup_error = str(exc)[:2000]
await db.commit()
logger.error("Backup failed: %s", exc)
raise
# Full user data in plaintext -- keep it readable only by the app user.
path.chmod(0o600)
prune_backups(row.backup_retention, row.backup_location)
row.last_backup_at = _utcnow()
row.last_backup_status = "success"
row.last_backup_error = None
await db.commit()
stat = path.stat()
return BackupFileOut(
filename=path.name,
size_bytes=stat.st_size,
created_at=datetime.fromtimestamp(stat.st_mtime, tz=timezone.utc),
)
async def restore_backup(filename: str, scope: Literal["entries", "all"], db: AsyncSession) -> None:
row = await _get_settings(db)
path = _resolve_backup_file(filename, row.backup_location)
if not path.is_file():
raise FileNotFoundError(filename)
# Reading admin_settings above left this session in an open transaction
# holding a metadata lock on that table; a full restore DROPs and
# recreates it, which would block on that lock. Close the transaction first.
await db.commit()
sql = await asyncio.to_thread(lambda: gzip.decompress(path.read_bytes()))
if scope == "entries":
sql = _extract_table(sql, "entries")
await _load_sql(sql)
# Tables were dropped and recreated -- discard pooled connections so none
# carries state from before the restore.
await engine.dispose()
def delete_backup(filename: str, location: str | None) -> None:
path = _resolve_backup_file(filename, location)
path.unlink(missing_ok=True)
+21
View File
@@ -0,0 +1,21 @@
import base64
import hashlib
from cryptography.fernet import Fernet
from app.config import settings
def _fernet() -> Fernet:
# Derived from SECRET_KEY: rotating SECRET_KEY also invalidates any
# previously encrypted values (e.g. the stored ntfy token).
key = hashlib.sha256(settings.secret_key.encode()).digest()
return Fernet(base64.urlsafe_b64encode(key))
def encrypt(value: str) -> str:
return _fernet().encrypt(value.encode()).decode()
def decrypt(value: str) -> str:
return _fernet().decrypt(value.encode()).decode()
+62 -12
View File
@@ -1,19 +1,69 @@
import base64
import logging
import httpx
from typing import Optional
from app.config import settings
import httpx
from cryptography.fernet import InvalidToken
from sqlalchemy import select
from app.database import AsyncSessionLocal
from app.utils.crypto import decrypt
logger = logging.getLogger("bourbonacci.notify")
async def notify(title: str, message: str, priority: str = "default") -> None:
if not settings.ntfy_url:
return
headers = {"Title": f"Bourbonacci Admin - {title}", "Priority": priority}
if settings.ntfy_token:
headers["Authorization"] = f"Bearer {settings.ntfy_token}"
def _header_value(value: str) -> str:
# HTTP header values must be ASCII; ntfy decodes RFC 2047 encoded-words,
# so send non-ASCII titles/tags that way and leave plain ASCII untouched.
if value.isascii():
return value
return "=?UTF-8?B?" + base64.b64encode(value.encode("utf-8")).decode("ascii") + "?="
def _normalize_server_url(server_url: str) -> str:
server_url = server_url.strip()
if not server_url.startswith(("http://", "https://")):
server_url = "https://" + server_url
return server_url
async def notify(
title: str,
message: str,
priority: str = "default",
tags: Optional[list[str]] = None,
) -> bool:
"""Send an admin push notification using the ntfy settings saved in the
admin panel (Notifications tab). Returns False if not configured or the
send failed; never raises."""
from app.models.admin_settings import AdminSettings
async with AsyncSessionLocal() as db:
row = (await db.execute(select(AdminSettings).where(AdminSettings.id == 1))).scalar_one_or_none()
if not row or not row.ntfy_server_url or not row.ntfy_topic:
return False
try:
async with httpx.AsyncClient(timeout=5) as client:
await client.post(settings.ntfy_url, content=message, headers=headers)
except Exception as exc:
logger.warning("Ntfy notification failed: %s", exc)
token = decrypt(row.ntfy_token) if row.ntfy_token else None
except InvalidToken:
logger.error("Could not decrypt stored admin ntfy token")
return False
server_url = _normalize_server_url(row.ntfy_server_url)
url = server_url.rstrip("/") + "/" + row.ntfy_topic.strip("/")
headers = {"Title": _header_value(f"Bourbonacci Admin - {title}"), "Priority": priority}
if tags:
headers["Tags"] = _header_value(",".join(tags))
if token:
headers["Authorization"] = f"Bearer {token}"
try:
async with httpx.AsyncClient(timeout=10) as client:
resp = await client.post(url, content=message.encode("utf-8"), headers=headers)
if resp.status_code >= 300:
logger.warning("Ntfy send to %s failed with status %s", server_url, resp.status_code)
return False
return True
except httpx.HTTPError as exc:
logger.warning("Ntfy send to %s failed: %s", server_url, exc)
return False
+11 -6
View File
@@ -17,14 +17,18 @@ def verify_password(plain: str, hashed: str) -> bool:
return pwd_context.verify(plain, hashed)
def create_token(user_id: int, admin_id: Optional[int] = None) -> str:
def create_token(user_id: int) -> str:
expire = datetime.now(timezone.utc) + timedelta(minutes=settings.access_token_expire_minutes)
payload: dict = {"sub": str(user_id), "exp": expire}
if admin_id is not None:
payload["admin_id"] = admin_id
return jwt.encode(payload, settings.secret_key, algorithm=settings.algorithm)
def create_admin_token() -> str:
# No "sub" claim, so decode_token() rejects it as a user token.
expire = datetime.now(timezone.utc) + timedelta(minutes=settings.access_token_expire_minutes)
return jwt.encode({"admin": True, "exp": expire}, settings.secret_key, algorithm=settings.algorithm)
def decode_token(token: str) -> Optional[int]:
try:
payload = jwt.decode(token, settings.secret_key, algorithms=[settings.algorithm])
@@ -36,8 +40,9 @@ def decode_token(token: str) -> Optional[int]:
return None
def decode_token_full(token: str) -> Optional[dict]:
def is_admin_token(token: str) -> bool:
try:
return jwt.decode(token, settings.secret_key, algorithms=[settings.algorithm])
payload = jwt.decode(token, settings.secret_key, algorithms=[settings.algorithm])
except JWTError:
return None
return False
return payload.get("admin") is True
+2
View File
@@ -11,3 +11,5 @@ pytz==2026.6
email-validator==2.4.0
slowapi==0.1.10
httpx==0.28.1
cryptography==50.0.2
apscheduler==3.11.3