Files
Atrium/backend/app/main.py
T
tobayah 8378152fb2 Merge branch 'czat/zalaczniki' into pokazowka/2026-11-17
# Conflicts:
#	backend/app/main.py
#	frontend/app.css
#	frontend/app.js
2026-11-18 15:08:17 +01:00

243 lines
11 KiB
Python

"""FastAPI application entrypoint."""
from __future__ import annotations
import logging
import os
from collections.abc import Sequence
from contextlib import asynccontextmanager
from pathlib import Path
from dredd_core.identity import (
COUNTERPARTY_TABLES,
EVENT_TABLES,
MODEL_PROVIDER_TABLES,
SHARED_IDENTITY_TABLES,
)
from dredd_core.identity_schema import assert_identity_schema
from dredd_core.json_charset import ensure_json_charset
from dredd_core.routes import iter_routes
from fastapi import Depends, FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from sqlalchemy import text
# Starlette's own "what did the router match on" helper: scope["path"] minus scope["root_path"].
# Private module, but it is the single function Starlette itself routes with (routing.py calls it
# for every request), and starlette is pinned transitively through the fastapi pin.
from starlette._utils import get_route_path
from starlette.routing import BaseRoute, Match
from starlette.types import ASGIApp, Receive, Scope, Send
from . import __version__
from .config import get_settings
from .db import engine
from .deps import refuse_cross_site_write
from .errors import ProblemDetailErrorMiddleware, install_error_handlers, problem_response
from .logging_config import configure_logging
from .observability import setup_observability
from .routers import (
admin,
admin_modules,
admin_providers,
attachments,
auth,
health,
marketplace,
models,
nodes,
skills,
users,
)
API_PREFIX = "/api/v1"
settings = get_settings()
configure_logging()
log = logging.getLogger("atrium")
@asynccontextmanager
async def lifespan(_app: FastAPI):
"""Refuse to start if the shared identity tables are not where they must be.
This is the only guard against the one failure mode that has NO other symptom. Addressing in
this family is the `search_path`, never schema qualification, and this app's own schema has to
come first — otherwise `alembic_version`, the enum types and every new table would land
somewhere its migrator does not own. The whole cost of that correct choice is this: with
`search_path = atrium, dredd, extensions`, an unqualified `app_user` resolves to
**`atrium.app_user` if one exists** — and everything keeps working. You are simply back to two
rows per human, silently, which is the exact defect this entire change exists to end.
A stray `create_all`, a restored `pg_dump --schema=atrium`, or a fresh install whose cutover
revision has not run yet all produce it. `python -m dredd_core.managed check --identity-schema`
catches it when you deploy; only a boot assertion catches it after a restore. So it runs on
every start, it is not optional, and a failure here is meant to stop the container: a hub that
is quietly writing accounts nobody else can see is worse than a hub that is down.
Standalone (`IDENTITY_SCHEMA` empty) it does not even open a connection — there is no shared
schema to be wrong about, and a lifespan that needs the database to start would turn a slow
Postgres into a crash loop for no reason.
"""
if settings.shares_identity:
with engine.connect() as conn:
own = conn.scalar(text("SELECT current_schema()")) or ""
# The model providers too (revision 0009): a copy left in Atrium's own schema would be
# a private list the modules never see. The event log too (revision 0011): a local one
# would be a log no module writes to or reads. The counterparty register too
# (revision 0012): a local copy would be a register no module sees.
assert_identity_schema(conn, own_schema=own,
identity_schema=settings.identity_schema,
tables=SHARED_IDENTITY_TABLES | MODEL_PROVIDER_TABLES | EVENT_TABLES
| COUNTERPARTY_TABLES)
log.info("Shared identity schema %s: every identity table resolves there",
settings.identity_schema)
yield
app = FastAPI(
title="Atrium API",
version=__version__,
description="Atrium — the Dredd family's front door: a launcher and marketplace for every dredd-core module, with the administration that decides who is offered what.",
docs_url=f"{API_PREFIX}/docs",
redoc_url=None,
openapi_url=f"{API_PREFIX}/openapi.json",
# The path this app is mounted at, when the family serves one module per path on one origin
# (ROOT_PATH=/atrium behind the front door's `Mount("/atrium")`). Empty when it owns the root.
# uvicorn is told the same value on the command line and that is what does the real work — it
# puts the prefix back on scope["path"], so every URL Starlette generates (slash redirects,
# StaticFiles directory redirects) stays inside the prefix. Setting it here as well is what
# makes the OpenAPI schema and /docs point at the prefixed API. Both halves, always.
root_path=settings.root_path,
# Every route, once: an unsafe request riding on the ambient cookie must come from this site.
dependencies=[Depends(refuse_cross_site_write)],
lifespan=lifespan,
)
install_error_handlers(app)
setup_observability(app, engine)
# Added BEFORE CORS so 500s flow back out through CORS and carry the headers a browser needs.
app.add_middleware(ProblemDetailErrorMiddleware)
if settings.cors_origins_list:
if "*" in settings.cors_origins_list:
raise RuntimeError("CORS_ALLOW_ORIGINS='*' is unsafe with credentialed CORS.")
app.add_middleware(
CORSMiddleware, allow_origins=settings.cors_origins_list, allow_credentials=True,
allow_methods=["*"], allow_headers=["*"],
)
# Content-Security-Policy for the console. 'unsafe-inline' is required by the theme pre-paint
# inline <script> and the inline style="" attributes in index.html. Nothing loads from a CDN —
# the console is entirely same-origin, which is the point when the data is privileged.
_CONSOLE_CSP = (
"default-src 'self'; "
"base-uri 'self'; "
"object-src 'none'; "
"frame-ancestors 'none'; "
"frame-src 'self'; "
"form-action 'self'; "
"img-src 'self' data: blob:; "
"font-src 'self' data:; "
"style-src 'self' 'unsafe-inline'; "
"script-src 'self' 'unsafe-inline'; "
"connect-src 'self'"
)
@app.middleware("http")
async def _security_headers(request, call_next):
"""Revalidate the static console (no-cache → conditional GET, so a rebuilt app.js/app.css is
picked up without a hard refresh) and attach security headers."""
resp = await call_next(request)
resp.headers.setdefault("X-Content-Type-Options", "nosniff")
resp.headers.setdefault("Referrer-Policy", "same-origin")
resp.headers.setdefault("Cross-Origin-Opener-Policy", "same-origin")
resp.headers.setdefault("X-Frame-Options", "DENY")
if "content-type" in resp.headers: # JSON declares UTF-8 (PowerShell 5.1 reads Latin-1)
resp.headers["content-type"] = ensure_json_charset(resp.headers["content-type"])
# The ROUTE path, not the URL path: under ROOT_PATH the URL carries the mount prefix
# (/atrium/api/v1/...), so a startswith() test on it silently stops matching and every API
# response picks up the console's Cache-Control and CSP. get_route_path strips the prefix,
# which is exactly what the router matched on, so this reads the same at / and at /atrium.
path = get_route_path(request.scope)
if not path.startswith(("/api", "/healthz")):
resp.headers.setdefault("Cache-Control", "no-cache")
resp.headers.setdefault("Content-Security-Policy", _CONSOLE_CSP)
return resp
for router in (
health.router, auth.router, users.router, admin.router, admin_modules.router,
admin_providers.router, nodes.router, marketplace.router, models.router, skills.router, attachments.router,
skills.agents, skills.publish_requests,
):
app.include_router(router, prefix=API_PREFIX)
@app.get("/healthz")
def healthz() -> dict:
return {"status": "ok"}
# Every path Atrium's own API owns. Nothing under these may be answered by the static console — not
# even its 404 (see _ConsoleUnlessApi). The modules the front door proxies (/galena, /sygna, ...)
# never reach this app, so they are not this shim's concern.
_API_PATHS = (API_PREFIX, "/healthz")
class _ConsoleUnlessApi:
"""Serve the static console, except under the API's own paths — those are answered here.
Mounting the console at "/" last is not enough. An APIRoute whose path matches but whose
METHOD does not yields `Match.PARTIAL` (Starlette's 405 signal), and the router acts on it only
after every route came up empty — but a `Mount` at "/" FULL-matches every path, so StaticFiles
answered instead: `GET /api/v1/auth/logout` (POST-only) was a 404 indistinguishable from
`/api/v1/nope`, and `POST /api/v1/nope` was a 405 from StaticFiles, neither with `Allow`.
This shim answers API paths itself: 405 + `Allow` when some route claims the path under another
method (asked via Starlette's own `route.matches`, so there is no second copy of the path
regexes), 404 when none does. Ported from Galena's main._ConsoleUnlessApi.
The walk goes through `dredd_core.routes.iter_routes` (0.18.1): FastAPI 0.115.x keeps
`app.routes` flat, but from 0.15x each included router is one `_IncludedRouter` entry and a
plain walk would see no API route at all (every 405 back to a 404).
"""
def __init__(self, console: ASGIApp, routes: Sequence[BaseRoute]) -> None:
self._console = console
# The LIVE app.routes list, read per request: a copy taken now would miss later routes.
self._routes = routes
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
await self._console(scope, receive, send)
return
# The ROUTE path: under ROOT_PATH (/atrium) scope["path"] carries the prefix.
path = get_route_path(scope)
if not any(path == owned or path.startswith(f"{owned}/") for owned in _API_PATHS):
await self._console(scope, receive, send)
return
allowed: set[str] = set()
for _, route in iter_routes(self._routes):
methods = getattr(route, "methods", None)
if methods and route.matches(scope)[0] is Match.PARTIAL:
allowed |= set(methods)
if allowed:
response = problem_response(405, "Method Not Allowed",
"That method is not allowed on this path.",
headers={"Allow": ", ".join(sorted(allowed))})
else:
response = problem_response(404, "Not Found", "No API route matches this path.")
await response(scope, receive, send)
# Serve the static console. On the platform this IS production: the front door (app/frontdoor.py)
# mounts this whole app at /atrium and nothing else serves these files (the image ships them at
# /frontend, ATRIUM_FRONTEND_DIR). Mount LAST so /api/v1/* and /healthz win — with
# _ConsoleUnlessApi in front of it, because last place alone loses every 405.
_FRONTEND = Path(os.environ.get("ATRIUM_FRONTEND_DIR")
or Path(__file__).resolve().parents[2] / "frontend")
if _FRONTEND.exists():
app.mount("/", _ConsoleUnlessApi(StaticFiles(directory=str(_FRONTEND), html=True), app.routes),
name="frontend")