Authorization Code with PKCE against any provider that publishes a discovery document, configured entirely from the UI — no environment variables, no restart to fix a typo in a client id, and a Test button that fetches the provider's metadata and says what it found. The best decision here was not writing any new session machinery. The callback sets the same httpOnly refresh cookie a password login sets and redirects to "/", and the SPA's existing boot-time restore() trades it for an access token. So an SSO session *is* a normal session — same revocation, same token_version checks, same everything — and no token is ever put in a URL fragment or query string where a proxy log or the browser history would keep it. The alternative everyone reaches for first, redirecting with #access_token=..., would have been a second code path and a worse one. What is actually verified, because "the provider said so" is worth nothing otherwise: the ID token's signature against the provider's published JWKS (re-fetched once if the kid is unknown, so key rotation heals itself), issuer, audience, expiry, and a nonce minted for that specific login. The state row is deleted when it is consumed, which is what makes a replayed callback fail, and it lives in the database rather than a dict so it survives the worker restart that can happen between the redirect out and the redirect back. Accounts match on sub, not username. It is the only identifier a provider promises is stable, so somebody renamed upstream stays the same account instead of silently acquiring a second one. An existing local account with that username is linked rather than duplicated, and keeps its role — linking must not quietly demote an admin. Claim-based admin mapping works in both directions: removed from the group upstream means read-only on the next sign-in. Two things this turned up that were already broken. verify_password raised passlib's UnknownHashError on a hash it could not parse, so a password attempt against an SSO account — which stores a deliberately unusable marker — would have been a 500 rather than a 401; it now returns false for any unparseable hash, which is the right answer for a corrupt row too. And the bundled nginx never forwarded X-Forwarded-Proto, so uvicorn saw plain HTTP behind TLS: the derived redirect URI came out as http:// and the refresh cookie lost its Secure flag. Both fixed. The password form stays on the login screen no matter what. A provider outage locking you out of the machine that runs your provider is a failure mode worth designing against. The authorization matrix made me write down why three routes are public, which is the right question to be asked: they are the path by which an unauthenticated person becomes an authenticated one. status deliberately returns only a boolean and a label — no issuer, no client id — so it tells a stranger nothing the button would not. 31 tests, with a throwaway RSA key standing in for a provider so verification is exercised for real rather than mocked: wrong key under the right kid, wrong audience, wrong issuer, expired, replayed nonce, reused state. Plus an end-to-end run of the whole flow — redirect, callback, cookie, session, group-mapped admin, replay refused, password login against the SSO account cleanly refused. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
169 lines
5.3 KiB
Python
169 lines
5.3 KiB
Python
"""StackPilot backend — FastAPI application entry point."""
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import logging
|
|
from contextlib import asynccontextmanager
|
|
|
|
from fastapi import FastAPI, Request
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
from fastapi.responses import JSONResponse
|
|
from sqlmodel import Session
|
|
|
|
from config import settings
|
|
from version import APP_VERSION
|
|
from database import engine, init_db
|
|
from docker_client import DockerError
|
|
from routers import (
|
|
audit,
|
|
auth,
|
|
backups,
|
|
containers,
|
|
dashboard,
|
|
destinations,
|
|
editor,
|
|
files,
|
|
git,
|
|
images,
|
|
networks,
|
|
oidc,
|
|
ports,
|
|
registries,
|
|
schedules,
|
|
secrets,
|
|
settings as settings_router,
|
|
stacks,
|
|
system,
|
|
templates,
|
|
tokens,
|
|
volumes,
|
|
ws,
|
|
)
|
|
from services import (
|
|
backup_destination_service,
|
|
git_service,
|
|
image_status_store,
|
|
logo_service,
|
|
registry_service,
|
|
schedule_service,
|
|
stack_lock_service,
|
|
template_service,
|
|
update_service,
|
|
)
|
|
|
|
logging.basicConfig(level=logging.INFO)
|
|
logger = logging.getLogger("stackpilot")
|
|
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app: FastAPI):
|
|
init_db()
|
|
# Register stacks that already exist on disk.
|
|
try:
|
|
with Session(engine) as session:
|
|
stacks.sync_discovered_stacks(session)
|
|
except Exception as exc: # noqa: BLE001
|
|
logger.warning("Stack discovery failed: %s", exc)
|
|
# One-off: encrypt backup-destination credentials written before they were
|
|
# stored encrypted (see services/crypto_service.py).
|
|
try:
|
|
with Session(engine) as session:
|
|
encrypted = backup_destination_service.migrate_plaintext_configs(session)
|
|
if encrypted:
|
|
logger.info("Encrypted %d backup destination config(s) at rest", encrypted)
|
|
except Exception as exc: # noqa: BLE001
|
|
logger.warning("Destination config encryption migration failed: %s", exc)
|
|
try:
|
|
moved = template_service.migrate_legacy_db_templates()
|
|
if moved:
|
|
logger.info("Migrated %d custom template(s) from the database to folders", moved)
|
|
except Exception as exc: # noqa: BLE001
|
|
logger.warning("Legacy template migration failed: %s", exc)
|
|
# Runtime state that used to live in module dicts and was lost on restart.
|
|
try:
|
|
with Session(engine) as session:
|
|
stale = stack_lock_service.prune_expired(session)
|
|
if stale:
|
|
logger.info("Cleared %d stale stack lock(s) from a previous run", stale)
|
|
except Exception as exc: # noqa: BLE001
|
|
logger.warning("Could not prune stack locks: %s", exc)
|
|
try:
|
|
restored = image_status_store.install()
|
|
logger.info("Restored %d cached image update status(es)", restored)
|
|
except Exception as exc: # noqa: BLE001
|
|
logger.warning("Could not restore the image update cache: %s", exc)
|
|
# Private registry credentials: into the in-memory cache the update checker
|
|
# reads, and into the config.json the Docker CLI reads.
|
|
try:
|
|
with Session(engine) as session:
|
|
known = registry_service.reload(session)
|
|
if known:
|
|
logger.info("Loaded credentials for %d registr%s", known, "y" if known == 1 else "ies")
|
|
except Exception as exc: # noqa: BLE001
|
|
logger.warning("Could not load registry credentials: %s", exc)
|
|
|
|
update_task = asyncio.create_task(update_service.background_loop())
|
|
schedule_task = asyncio.create_task(schedule_service.scheduler_loop())
|
|
# App logos. Deliberately a task and not awaited: the catalog is a network
|
|
# download, and a box with no outbound internet must still start instantly
|
|
# (it just keeps the built-in glyphs).
|
|
logo_task = asyncio.create_task(logo_service.catalog_loop())
|
|
git_service.ensure_cache_root()
|
|
git_task = asyncio.create_task(git_service.poll_loop())
|
|
logger.info("StackPilot backend ready on port %s", settings.PORT)
|
|
yield
|
|
update_task.cancel()
|
|
schedule_task.cancel()
|
|
logo_task.cancel()
|
|
git_task.cancel()
|
|
|
|
|
|
app = FastAPI(title="StackPilot", version=APP_VERSION, lifespan=lifespan)
|
|
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=settings.CORS_ORIGINS,
|
|
allow_credentials=True,
|
|
allow_methods=["*"],
|
|
allow_headers=["*"],
|
|
)
|
|
|
|
|
|
@app.exception_handler(DockerError)
|
|
async def docker_error_handler(_request: Request, exc: DockerError):
|
|
return JSONResponse(
|
|
status_code=502,
|
|
content={"error": exc.error, "detail": exc.detail},
|
|
)
|
|
|
|
|
|
app.include_router(auth.router)
|
|
app.include_router(stacks.router)
|
|
app.include_router(git.router)
|
|
app.include_router(git.hook_router)
|
|
app.include_router(oidc.router)
|
|
app.include_router(tokens.router)
|
|
app.include_router(registries.router)
|
|
app.include_router(secrets.router)
|
|
app.include_router(containers.router)
|
|
app.include_router(dashboard.router)
|
|
app.include_router(system.router)
|
|
app.include_router(volumes.router)
|
|
app.include_router(editor.router)
|
|
app.include_router(files.router)
|
|
app.include_router(images.router)
|
|
app.include_router(ports.router)
|
|
app.include_router(templates.router)
|
|
app.include_router(audit.router)
|
|
app.include_router(settings_router.router)
|
|
app.include_router(backups.router)
|
|
app.include_router(destinations.router)
|
|
app.include_router(schedules.router)
|
|
app.include_router(networks.router)
|
|
app.include_router(ws.router)
|
|
|
|
|
|
@app.get("/api/health")
|
|
def health() -> dict:
|
|
return {"status": "ok", "version": APP_VERSION}
|