import logging import os from contextlib import asynccontextmanager from urllib.parse import urlparse from fastapi import FastAPI, Request from fastapi.responses import JSONResponse from fastapi.staticfiles import StaticFiles import ledger from cashbook_app import config from cashbook_app.db.models import Base from cashbook_app.db.session import get_engine, get_session_factory from cashbook_app.routers.attachments import router as attachments_router from cashbook_app.routers.auth_routes import router as auth_router from cashbook_app.routers.books import router as books_router from cashbook_app.routers.frontend import router as frontend_router from cashbook_app.routers.invoices import router as invoices_router from cashbook_app.routers.mileage import router as mileage_router from cashbook_app.routers.statements import router as statements_router from cashbook_app.routers.suppliers import router as suppliers_router from cashbook_app.routers.users_admin import router as users_router from cashbook_app.services import accounts, spreadsheets log = logging.getLogger("cashbook") class _SkipHealthChecks(logging.Filter): def filter(self, record: logging.LogRecord) -> bool: return "/healthz" not in record.getMessage() logging.getLogger("uvicorn.access").addFilter(_SkipHealthChecks()) SECURITY_HEADERS = { "X-Content-Type-Options": "nosniff", "X-Frame-Options": "DENY", "Referrer-Policy": "no-referrer", "Content-Security-Policy": "default-src 'self'; script-src 'self' 'unsafe-inline'; " "style-src 'self' 'unsafe-inline'; img-src 'self' data:; frame-ancestors 'none'", } def _bootstrap_admin() -> None: """First run: create an admin from BOOTSTRAP_ADMIN_USERNAME/PASSWORD if there are no users.""" username = os.environ.get("BOOTSTRAP_ADMIN_USERNAME", "").strip() password = os.environ.get("BOOTSTRAP_ADMIN_PASSWORD", "").strip() if not (accounts.auth_enabled() and username and password): return db = get_session_factory()() try: if accounts.count_users(db) == 0: accounts.create_user(db, username, password, is_superuser=True) log.warning("Created administrator %r from BOOTSTRAP_ADMIN_USERNAME", username) finally: db.close() def _migrate_spreadsheets() -> None: """Copy any .ods cashbooks left in the data folder into the database (once each).""" if not any(f.endswith(".ods") and f != "template.ods" for f in os.listdir(config.data_dir())): return from migrate import migrate_folder conn = ledger.connect(config.database_path()) try: for message in migrate_folder(conn, str(config.data_dir()), spreadsheets.office().open): log.warning(message) finally: conn.close() @asynccontextmanager async def lifespan(_app: FastAPI): Base.metadata.create_all(bind=get_engine()) ledger.connect(config.database_path()).close() # create / upgrade the books tables _bootstrap_admin() _migrate_spreadsheets() if not accounts.auth_enabled(): log.warning("AUTH_ENABLED=false: anyone who can reach this server can see and change the books") yield spreadsheets.stop() def _same_origin(request: Request) -> bool: """Refuse state-changing requests made from other websites. Compares the Origin's host name (ports differ behind Docker and proxies) with Host, X-Forwarded-Host and CASHBOOK_ALLOWED_HOSTS. """ origin = request.headers.get("origin") if not origin: return True host_of = lambda h: urlparse("//" + h.strip()).hostname allowed = {"localhost", "127.0.0.1", "::1"} | config.allowed_hosts() for h in [request.headers.get("host", "")] + request.headers.get("x-forwarded-host", "").split(","): if h.strip(): allowed.add(host_of(h)) if urlparse(origin).hostname in allowed: return True log.warning("Refused %s %s: Origin %s is not one of %s; add it to CASHBOOK_ALLOWED_HOSTS if it's yours", request.method, request.url.path, origin, sorted(allowed)) return False def create_app() -> FastAPI: app = FastAPI(title="Cashbook", lifespan=lifespan, docs_url=None, redoc_url=None) @app.middleware("http") async def security(request: Request, call_next): if request.method not in ("GET", "HEAD", "OPTIONS") and not _same_origin(request): return JSONResponse({"detail": "Refused: this page's address doesn't match the server's. " "See the server log, or set CASHBOOK_ALLOWED_HOSTS."}, status_code=403) response = await call_next(request) for k, v in SECURITY_HEADERS.items(): response.headers.setdefault(k, v) if request.url.path.startswith("/api/"): response.headers.setdefault("Cache-Control", "no-store") return response app.mount("/static", StaticFiles(directory=str(config.STATIC_DIR)), name="static") app.include_router(frontend_router) app.include_router(auth_router) app.include_router(users_router) app.include_router(books_router) app.include_router(statements_router) app.include_router(attachments_router) app.include_router(invoices_router) app.include_router(mileage_router) app.include_router(suppliers_router) return app app = create_app()