Buckets:

download
raw
14 kB
"""FastAPI application entry point for WineBox."""
import logging
import os
from contextlib import asynccontextmanager
from pathlib import Path
from typing import AsyncGenerator
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, JSONResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.errors import RateLimitExceeded
from slowapi.util import get_remote_address
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import Response
from winebox import __version__
from winebox.auth.regstack_setup import build_regstack
from winebox.config import settings
from winebox.database import close_db, init_db
from winebox.services.analytics import posthog_service
logger = logging.getLogger(__name__)
# Rate limiter configuration — disabled in test mode (CI runs many parallel
# logins from the same IP which would trigger the per-IP rate limit)
limiter = Limiter(
key_func=get_remote_address,
default_limits=["60/minute"],
enabled=os.environ.get("WINEBOX_RATE_LIMIT_DISABLED", "").lower() not in ("1", "true"),
)
class SecurityHeadersMiddleware(BaseHTTPMiddleware):
"""Middleware to add security headers to all responses."""
async def dispatch(self, request: Request, call_next) -> Response:
response = await call_next(request)
# Security headers
response.headers["X-Content-Type-Options"] = "nosniff"
response.headers["X-Frame-Options"] = "DENY"
response.headers["X-XSS-Protection"] = "1; mode=block"
response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
# Additional security headers
response.headers["X-Permitted-Cross-Domain-Policies"] = "none"
response.headers["Permissions-Policy"] = (
"accelerometer=(), camera=(self), geolocation=(self), gyroscope=(), "
"magnetometer=(), microphone=(), payment=(), usb=()"
)
# Content Security Policy
# Note: 'unsafe-inline' is kept for style-src only (for basic inline styles
# like style="display: none;"). Script-src does not need unsafe-inline as
# all JavaScript is loaded from external files.
# PostHog domains are allowed for analytics when enabled.
response.headers["Content-Security-Policy"] = (
"default-src 'self'; "
"script-src 'self' https://eu.posthog.com https://eu-assets.i.posthog.com; "
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; "
"img-src 'self' data: blob: https://eu.posthog.com; "
"font-src 'self' https://fonts.gstatic.com; "
"connect-src 'self' https://eu.posthog.com https://eu.i.posthog.com; "
"frame-ancestors 'none'; "
"form-action 'self'; "
"base-uri 'self'; "
"object-src 'none';"
)
# HTTPS enforcement header (browsers will upgrade to HTTPS)
if settings.enforce_https:
response.headers["Strict-Transport-Security"] = (
"max-age=31536000; includeSubDomains; preload"
)
return response
def _is_production() -> bool:
"""Check if we're running in production mode.
Returns:
True if running in production (not debug mode and not testing).
"""
return not settings.debug and not os.getenv("PYTEST_CURRENT_TEST")
def _validate_security_configuration() -> None:
"""Validate security configuration at startup.
Raises:
RuntimeError: If critical security issues are detected in production.
"""
issues = []
warnings = []
# Check for weak/missing secret key
secret_key = settings.secret_key
if not secret_key or len(secret_key) < 32:
issues.append(
"SECRET_KEY is missing or too short (minimum 32 characters). "
"Set WINEBOX_SECRET_KEY environment variable."
)
# Check for insecure defaults in production
if _is_production():
# Debug mode should be off in production
if settings.debug:
issues.append(
"Debug mode is enabled in production. "
"Set debug=false in config.toml or WINEBOX_DEBUG=false."
)
# Localhost MongoDB is suspicious in production
mongodb_url = settings.mongodb_url
if "localhost" in mongodb_url or "127.0.0.1" in mongodb_url:
warnings.append(
"MongoDB URL points to localhost in production. "
"This may indicate an insecure configuration."
)
# HTTPS should be enforced in production
if not settings.enforce_https:
warnings.append(
"HTTPS enforcement is disabled. "
"Consider enabling enforce_https=true for production."
)
# Log warnings
for warning in warnings:
logger.warning("SECURITY WARNING: %s", warning)
# Fail on critical issues in production
if issues and _is_production():
for issue in issues:
logger.error("SECURITY ERROR: %s", issue)
raise RuntimeError(
"Application startup blocked due to security configuration issues. "
"See logs for details."
)
elif issues:
# Log as warnings in development
for issue in issues:
logger.warning("SECURITY WARNING (development mode): %s", issue)
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
"""Application lifespan manager."""
# Startup
# Validate security configuration before proceeding
_validate_security_configuration()
# Ensure data directories exist
settings.image_storage_path.mkdir(parents=True, exist_ok=True)
Path("data").mkdir(parents=True, exist_ok=True)
# Initialize database
await init_db()
# Bring up regstack — owns the users, sessions, blacklist, and lockout
# collections and mounts the auth router on this app.
regstack = build_regstack()
await regstack.backend.install_schema()
app.include_router(regstack.router, prefix=regstack.config.api_prefix)
logger.info("Mounted regstack router at %s", regstack.config.api_prefix)
# Pre-warm the X-Wines filter cache so first page load is instant
try:
from winebox.routers.xwines import refresh_filter_cache
await refresh_filter_cache()
except Exception:
logger.warning("Failed to pre-warm X-Wines filter cache (data may not be loaded yet)")
yield
# Shutdown
try:
await regstack.aclose()
except Exception:
logger.exception("Error closing regstack backend")
# Shutdown PostHog analytics (flush pending events)
posthog_service.shutdown()
await close_db()
# Disable interactive API docs (/docs, /redoc, /openapi.json) outside of
# debug mode. Production and OAT serve real users — exposing the full
# OpenAPI schema lets attackers enumerate every endpoint without effort.
_docs_enabled = settings.debug
app = FastAPI(
title=settings.app_name,
description="Wine Cellar Management Application with OCR label scanning",
version=__version__,
lifespan=lifespan,
docs_url="/docs" if _docs_enabled else None,
redoc_url="/redoc" if _docs_enabled else None,
openapi_url="/openapi.json" if _docs_enabled else None,
)
# Add rate limiter
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
# Add CORS middleware with explicit configuration
# Only allow origins from the whitelist; empty list means same-origin only
if settings.cors_origins:
app.add_middleware(
CORSMiddleware,
allow_origins=settings.cors_origins,
allow_credentials=True,
allow_methods=["GET", "POST", "PUT", "DELETE", "PATCH"],
allow_headers=["Authorization", "Content-Type"],
expose_headers=["X-Request-ID"],
max_age=600, # Cache preflight for 10 minutes
)
# Add security headers middleware
app.add_middleware(SecurityHeadersMiddleware)
# Root serves web interface directly - no redirect to keep URL clean
@app.get("/", tags=["Root"])
async def root() -> FileResponse:
"""Root endpoint - serves the main web interface."""
static_path = Path(__file__).parent / "static" / "index.html"
return FileResponse(static_path, media_type="text/html")
# Serve favicon at /favicon.ico for browsers that request it automatically
@app.get("/favicon.ico", include_in_schema=False)
async def favicon() -> FileResponse:
"""Serve favicon for browser tab."""
favicon_path = Path(__file__).parent / "static" / "logos" / "favicon.svg"
return FileResponse(favicon_path, media_type="image/svg+xml")
# Wine Price Tracker — standalone mobile-first page
@app.get("/prices", tags=["Price Tracker"])
async def price_tracker_page() -> FileResponse:
"""Serve the wine price tracker mobile web app."""
static_path = Path(__file__).parent / "static" / "price-tracker.html"
return FileResponse(static_path, media_type="text/html")
# Design System — live component showcase paired with brand-kit/DESIGN-SYSTEM.md
@app.get("/design-system", tags=["Documentation"])
async def design_system_page() -> FileResponse:
"""Serve the design system reference page."""
static_path = Path(__file__).parent / "static" / "design-system.html"
return FileResponse(static_path, media_type="text/html")
# regstack emails embed canonical /verify?token=... and /reset-password?token=...
# URLs; the WineBox SPA uses hash-based routes. Redirect path → hash so a user
# landing on either URL ends up in the right SPA card.
@app.get("/verify", include_in_schema=False)
async def verify_redirect(request: Request) -> RedirectResponse:
return RedirectResponse(url=f"/#verify?{request.url.query}", status_code=302)
@app.get("/reset-password", include_in_schema=False)
async def reset_password_redirect(request: Request) -> RedirectResponse:
return RedirectResponse(url=f"/#reset-password?{request.url.query}", status_code=302)
# Health check endpoint
@app.get("/health", tags=["Health"])
async def health_check() -> JSONResponse:
"""Health check endpoint."""
return JSONResponse(
content={
"status": "healthy",
"version": __version__,
"app_name": settings.app_name,
}
)
# Override regstack's /api/auth/me so the response key is `id` (matching
# WineBox's existing SPA + admin contract) rather than regstack's `_id`.
# Must be registered BEFORE regstack's router is included in lifespan so
# this handler takes precedence on route match.
from winebox.services.auth import RequireAuth as _RequireAuth
from winebox.models.user import User as _WineboxUser
@app.get("/api/auth/me", tags=["Authentication"])
async def get_current_user_info(current_user: _RequireAuth) -> dict:
"""Authenticated user info — replaces regstack's /me to keep the
response key `id` (string) compatible with WineBox's SPA and admin."""
return {
"id": str(current_user.id),
"email": current_user.email,
"full_name": current_user.full_name,
"is_active": current_user.is_active,
"is_admin": current_user.is_admin,
"is_superuser": current_user.is_superuser,
"is_verified": current_user.is_verified,
"created_at": current_user.created_at,
"last_login": current_user.last_login,
}
# PostHog analytics configuration endpoint
@app.get("/api/config/analytics", tags=["Configuration"])
async def get_analytics_config() -> JSONResponse:
"""Get analytics configuration for frontend.
Returns PostHog settings (enabled, host, API key) for client-side analytics.
Only returns the public API key which is safe to expose.
"""
return JSONResponse(
content={
"enabled": settings.posthog_enabled,
"host": settings.posthog_host,
"api_key": settings.posthog_api_key or "",
}
)
# Import and include routers (auth is mounted from regstack inside lifespan).
from winebox.routers import (
bottles,
cases,
cellar,
demo,
export,
images,
import_router,
met,
price_tracker,
reference,
search,
transactions,
wines,
xwines,
)
app.include_router(wines.router, prefix="/api/wines", tags=["Wines"])
app.include_router(cellar.router, prefix="/api/cellar", tags=["Cellar"])
app.include_router(met.router, prefix="/api/met", tags=["Wines I've Met"])
app.include_router(transactions.router, prefix="/api/transactions", tags=["Transactions"])
app.include_router(search.router, prefix="/api/search", tags=["Search"])
app.include_router(reference.router, prefix="/api/reference", tags=["Reference Data"])
app.include_router(xwines.router, prefix="/api/xwines", tags=["X-Wines Dataset"])
app.include_router(export.router, prefix="/api/export", tags=["Export"])
app.include_router(import_router.router, prefix="/api/import", tags=["Import"])
app.include_router(demo.router, prefix="/api/demo", tags=["Demo Data"])
app.include_router(cases.router, prefix="/api/cases", tags=["Cases"])
app.include_router(bottles.router, prefix="/api/bottles", tags=["Bottles"])
app.include_router(price_tracker.router, prefix="/api/prices", tags=["Price Tracker"])
# Wine label images — auth-gated and ownership-checked. Was previously
# served via app.mount(StaticFiles), which let anyone with the UUID
# filename fetch the image; now every request requires the wine to belong
# to the authenticated user.
app.include_router(images.router, prefix="/api/images", tags=["Images"])
# Serve static files - mounted after routes to avoid conflicts
static_path = Path(__file__).parent / "static"
if static_path.exists():
app.mount("/static", StaticFiles(directory=str(static_path)), name="static")

Xet Storage Details

Size:
14 kB
·
Xet hash:
bf40c3065e29e3ce1683c80529264c8809cc06bebd45be56a4698386f0c12483

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.