Be our own edge: headers and the console from the backend, no Caddy

The platform is dropping Caddy (Atrium's backend becomes the front door and
forwards /sygna/* with the prefix stripped), and the standalone stack drops
it too, so the backend now answers for everything Caddy added.

- app/edge.py: SecurityHeaders, pure ASGI and outermost, sets the full
  set on every response, errors included: nosniff, Referrer-Policy
  same-origin (the family's value), COOP same-origin, X-Frame-Options DENY
  or SAMEORIGIN, and on the console Caddy's CSP (frame-ancestors from
  FRAME_ANCESTORS) plus no-cache. The CSP stays console-only, as Caddy had
  it: on the API it would break the Swagger UI at /api/v1/docs.
- FRAME_ANCESTORS is 'none' (default) or 'self'; anything else refuses to
  start.
- SpaStaticFiles is try_files {path} /index.html; ConsoleUnlessApi keeps
  everything under /api and /healthz off the console (404 or 405 with
  Allow), comparing route paths.
- BodySizeLimit caps a request at 100 MB; GZipMiddleware; /healthz answers
  HEAD too.
- Dockerfile: frontend as a named build context; uvicorn with
  --proxy-headers, --forwarded-allow-ips and --no-server-header.
- Standalone compose publishes the backend on :80; Caddyfile deleted;
  deploy_check and compose-smoke check the new shape.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-16 16:07:14 +02:00
co-authored by Claude Opus 5.5
parent a157223358
commit aac6b1e11a
15 changed files with 639 additions and 195 deletions
+14 -5
View File
@@ -11,8 +11,8 @@ APP_ENV=production
APP_BASE_URL=http://localhost
# Where this module is mounted on the platform: /sygna. Empty = standalone, at the root of its
# own host. Whatever is set here reaches uvicorn as --root-path too, and the reverse proxy in
# front must strip the same prefix — the two are one decision (see Caddyfile).
# own host. Whatever is set here reaches uvicorn as --root-path too, and the front door must
# strip the same prefix (Atrium forwards /sygna/* without it) — the two are one decision.
ROOT_PATH=
# ── Database ─────────────────────────────────────────────────────────────────
@@ -184,9 +184,18 @@ GALENA_EMBED=false
# Point a container restart policy at the first and a load balancer at the second. Using the
# first for both is how a dead instance keeps its share of the traffic.
# ── Reverse proxy ────────────────────────────────────────────────────────────
# Plain HTTP on :80 by default. Set to your domain for automatic TLS.
CADDY_SITE_ADDRESS=:80
# ── The edge (no reverse proxy) ──────────────────────────────────────────────
# The backend serves the console and sets its own security headers; docker-compose.yml publishes it
# on :80, plain HTTP. For TLS put your own terminator in front, or run Sygna on the platform.
#
# Which upstream IPs uvicorn trusts for X-Forwarded-For / X-Forwarded-Proto, so the real client IP
# lands in the audit log. Empty = loopback only (the image's default), right for this stack, where
# nothing sits in front of the backend. Behind your own TLS terminator, set its address or subnet;
# never `*`. docker-compose.yml sets it empty, overriding this line.
FORWARDED_ALLOW_IPS=
# Who may frame Sygna: 'none' (default; X-Frame-Options DENY) or 'self' (SAMEORIGIN). Anything else
# refuses start-up.
FRAME_ANCESTORS='none'
# ── OpenTelemetry (opt-in) ───────────────────────────────────────────────────
OTEL_ENABLED=false
+18 -8
View File
@@ -99,7 +99,7 @@ jobs:
- name: Deploy pre-flight
working-directory: backend
# Catches the failures the test suite cannot: a setting the code reads that .env.example
# never mentions, a healthcheck aimed at a route that moved, a Caddy matcher that misses
# never mentions, a healthcheck aimed at a route that moved, a console mount that swallows
# the API prefix.
run: python scripts/deploy_check.py
- name: Shared-file drift vs Galena
@@ -308,9 +308,9 @@ jobs:
# ── the deployment itself ─────────────────────────────────────────────────────
# Everything above runs Sygna from source against a Postgres service container. None of it
# executes docker-compose.yml, the Dockerfile, the Caddyfile or db/init — they were verified only
# executes docker-compose.yml, the Dockerfile or db/init — they were verified only
# by deploy_check.py READING them, and the machine this project is developed on cannot run
# containers at all (a VM without nested virtualization). This job is the first place those four
# containers at all (a VM without nested virtualization). This job is the first place those three
# files run. It found on its first attempt that the image could not be built by anyone, since the
# private dredd-core dependency needs git and a credential and the slim image had neither.
compose-smoke:
@@ -338,10 +338,10 @@ jobs:
DREDD_CORE_TOKEN: ${{ secrets.DREDD_CORE_TOKEN }}
run: docker compose up -d --build
- name: Wait for readiness through Caddy
# Caddy starts only once the backend's deep healthcheck passes, and the backend only once the
# migration has completed — so one successful response here proves the whole ordering:
# postgres healthy → migrate + seed → backend ready → proxy up.
- name: Wait for readiness on the published port
# The backend starts only once the migration has completed, and it is published on :80
# itself (no proxy) — so one successful deep response here proves the whole ordering:
# postgres healthy → migrate + seed → backend ready.
run: |
for i in $(seq 1 60); do
if curl -fsS "http://localhost/healthz?deep=1" >/dev/null 2>&1; then
@@ -353,7 +353,7 @@ jobs:
docker compose ps
exit 1
- name: Drive it through the proxy
- name: Drive it through the published port
run: |
set -euo pipefail
echo "--- liveness and readiness"
@@ -364,6 +364,16 @@ jobs:
headers=$(curl -fsSI http://localhost/)
echo "$headers" | grep -qi "content-security-policy" || { echo "::error::no CSP on the console"; exit 1; }
echo "$headers" | grep -qi "x-frame-options: DENY" || { echo "::error::console is frameable"; exit 1; }
echo "$headers" | grep -qi "referrer-policy: same-origin" || { echo "::error::no Referrer-Policy"; exit 1; }
echo "$headers" | grep -qi "cross-origin-opener-policy: same-origin" || { echo "::error::no COOP"; exit 1; }
echo "$headers" | grep -qi "cache-control: no-cache" || { echo "::error::console not revalidated"; exit 1; }
if echo "$headers" | grep -qi "^server:"; then echo "::error::Server header leaked"; exit 1; fi
echo "--- a deep link survives a reload (SPA fallback), the API never falls to the console"
curl -fsS http://localhost/matters/1 | grep -q "<title>Sygna" || { echo "::error::no SPA fallback"; exit 1; }
code=$(curl -s -o /dev/null -w '%{http_code}' http://localhost/api/v1/nope)
[ "$code" = "404" ] || { echo "::error::unknown API path answered $code"; exit 1; }
curl -s http://localhost/api/v1/nope | jq -e '.status == 404' >/dev/null || { echo "::error::unknown API path is not a problem response"; exit 1; }
curl -fsS http://localhost/ | grep -q "<title>Sygna" || { echo "::error::console did not render"; exit 1; }
echo "--- log in as the seeded administrator"
+24 -5
View File
@@ -7,7 +7,7 @@ Guidance for Claude Code when working in this repository.
**Sygna** — practice management (CRM + matters + time) for **Polish law firms**. It is a **module
of the Dredd platform**, served under the path **`/sygna`** alongside Atrium, Galena and Counsel.
Stack: **FastAPI + SQLAlchemy 2 + Alembic + PostgreSQL 16 / 17**, Argon2id auth + server-side
cookie sessions, a **no-build static console** (vanilla JS), Docker Compose + Caddy. License
cookie sessions, a **no-build static console** (vanilla JS), Docker Compose (no reverse proxy — the backend is its own edge). License
**Apache-2.0**; every dependency is permissive (no copyleft).
**One platform, one account, one admin pane.** The family runs at one origin, one module per path
@@ -96,7 +96,7 @@ frontend/ index.html · app.css · app.js (no build step, PL-firs
db/init/ 01-roles.sh (creates the app + migrator roles)
db/managed/ provision.sql (dredd-core's rendering, CI-checked) · README.md (Sygna's runbook
in the family's shared managed database, plus the database-wide checklist)
docker-compose.yml · docker-compose.managed-db.yml · Caddyfile · .env.example · .github/workflows/ci.yml
docker-compose.yml · docker-compose.managed-db.yml · .env.example · .github/workflows/ci.yml
docs/CRMecenas-Discovery-Report.md (research; §4 superseded by PLAN.md)
```
@@ -107,7 +107,7 @@ DREDD_CORE_TOKEN=… docker compose up -d --build # full stack; the token is a
cd backend && pytest # DB-free unit tests; integration auto-skips
SYGNA_RUN_INTEGRATION=1 pytest # full API loop (needs a migrated+seeded Postgres)
python scripts/license_gate.py # CI license gate locally
python scripts/deploy_check.py # compose/Dockerfile/Caddyfile/.env coherence
python scripts/deploy_check.py # compose/Dockerfile/edge/.env coherence
python scripts/deploy_check.py --env ../.env # + the managed-database URLs (TLS, pooler, roles)
python -m app.restore [NAME --yes] # list backups / restore one, one-shot (needs the migrator URL)
python -m dredd_core.managed check --url DATABASE_URL --expect-schema sygna --require-tls \
@@ -570,6 +570,24 @@ BOOTSTRAP_ADMIN_PASSWORD=… python scripts/walkthrough.py # drive the whole p
- **Console security:** `esc()` every dynamic value; bearer token in memory only, cookie session
primary; nothing loads from a CDN (the CSP has no third-party origins). `frame-src` names
Galena's origin only when `GALENA_EMBED` is on.
- **No Caddy, anywhere.** On the platform Atrium's backend is the front door and forwards
`/sygna/*` here with the prefix stripped (uvicorn's `--root-path "$ROOT_PATH"` puts it back);
standalone, `docker-compose.yml` publishes the backend on :80 with nothing in front. The backend
is its own edge (`app/edge.py`, wired in `main.py`): it serves the console (`frontend/`,
`/frontend` in the image via the `frontend` build context) at `/` LAST, behind
`ConsoleUnlessApi`, so `/api/*` and `/healthz` never fall to it (unknown → 404 problem, wrong
method → 405 + `Allow`); any other GET for a missing file gets `index.html` (Caddy's
`try_files {path} /index.html`). `SecurityHeaders` (pure ASGI, outermost) stamps every response,
errors included, with Caddy's set (except Referrer-Policy, the family's `same-origin`):
nosniff, X-Frame-Options, `Referrer-Policy: same-origin`, `Cross-Origin-Opener-Policy: same-origin`; the console (not
the API — `/api/v1/docs` is Swagger from a CDN) also gets the CSP and `Cache-Control: no-cache`.
`FRAME_ANCESTORS` is `'none'` (default, XFO DENY) or `'self'` (SAMEORIGIN); anything else
refuses start-up. No HSTS (Caddy never sent one here). Also gzip (min 1000 B), a 100 MB
request-body cap (`BodySizeLimit`, 413), and uvicorn `--proxy-headers --forwarded-allow-ips
"${FORWARDED_ALLOW_IPS:-127.0.0.1}" --no-server-header` — those flags live ONLY in
`backend/Dockerfile`'s CMD, never a compose `command:`. `FORWARDED_ALLOW_IPS` is never `*`
(the port is published). Every path comparison reads `get_route_path(scope)`, never
`request.url.path` (ROOT_PATH).
- **Icons are Tabler (MIT), path data vendored into the `ICN` map** — the same family Galena
uses, so the two consoles match in a shared launcher. Never load them from a CDN; see
CREDITS.md for the list.
@@ -669,8 +687,9 @@ has to be **provisioned** with `--identity-schema` before the hub grants any tie
schema, and `USAGE` comes from provisioning. db/managed/README.md §4a has the sequence.
**The container stack runs in CI** (`compose-smoke`, 2026-09-12): the image builds, compose brings
postgres → migrate+seed → backend → Caddy up in order, and the job logs in through the proxy,
reads the seeded matters, checks the console's CSP and frame headers, and confirms from inside
postgres → migrate+seed → backend (published on :80) up in order, and the job logs in through
that port, reads the seeded matters, checks the console's security headers, the SPA fallback and
that an unknown API path is a 404 problem rather than the console, and confirms from inside
the database container that the `app` role is refused on `audit_log` and `conflict_check`. It is
the only place those files execute — the development machine is a VM without nested
virtualization and cannot run containers. **Building the image needs `DREDD_CORE_TOKEN`** as a
-1
View File
@@ -34,7 +34,6 @@ same palette. Only the hex values are used, not the stylesheet.
| httpx | BSD-3-Clause |
| OpenTelemetry SDK + instrumentation | Apache-2.0 |
| PostgreSQL | PostgreSQL Licence |
| Caddy | Apache-2.0 |
## Data sources
-64
View File
@@ -1,64 +0,0 @@
# Caddy serves the static console and reverse-proxies the API to the backend.
# Default: plain HTTP on :80. For TLS, set CADDY_SITE_ADDRESS to your domain in .env
# (Caddy then provisions a certificate automatically).
#
# ── This is the STANDALONE shell. The platform's shell lives in Atrium ───────
# The family runs at ONE ORIGIN, one module per path — /atrium, /galena, /sygna, /counsel — and
# that site block is in Atrium's deploy tree, not here. This file stays for running Sygna on its
# own: one app at `/`, with ROOT_PATH empty. Same image, same console, both ways; what differs is
# the .env and which Caddyfile is in front.
#
# ── If you do mount this under a path, it is ONE decision, never two ─────────
#
# handle_path /sygna/* (Caddy strips) ⟺ --root-path /sygna (uvicorn prepends)
#
# uvicorn prepends `root_path` to the request path, on the assumption that the proxy already
# stripped it. So plain `handle` plus `--root-path` doubles the prefix and 404s everything, and
# stripping without `--root-path` makes every server-generated URL escape the prefix. There is no
# X-Forwarded-Prefix support anywhere in the chain; the prefix has to be an explicit flag.
#
# ── The rejection of path mounting that used to be written here was wrong ────
# It said path mounting was "considered and rejected — both consoles assume root-relative asset
# and API paths, so it is a rewrite of two frontends to save one DNS record". Both halves were
# false. Every asset reference in every console is already document-relative (`href="app.css"`,
# `src="app.js"`), every route is a hash fragment the server never sees, and every API call
# funnels through one constant — so the real cost was one line per console (`const API = new
# URL('api/v1', document.baseURI).pathname`) and one flag per backend. Do not re-derive the old
# conclusion from the old premise.
#
# ── The embedded case file, at one origin ────────────────────────────────────
# The session-cookie half of the old plan dissolves: Galena's cookie is this origin's cookie, so
# there is no parent-domain scoping to arrange and no SameSite dance. The CSP half does not —
# Galena still defaults to `frame-ancestors 'none'` and `GALENA_FRAME_ANCESTORS` takes an origin
# list, so enabling the embed is still a deliberate change in the GALENA repository. Until it is
# made, leave GALENA_EMBED=false: Sygna links to the case file instead, and says so.
{$CADDY_SITE_ADDRESS::80} {
encode gzip
# API + health → backend
@api path /api/v1/* /healthz
handle @api {
reverse_proxy backend:8000
}
# Everything else → the static console (SPA fallback to index.html)
handle {
root * /srv
try_files {path} /index.html
# Revalidate the console assets (ETag) so a rebuilt app.js/app.css is picked up
# without a manual hard refresh.
header Cache-Control "no-cache"
# Content-Security-Policy for the console. 'unsafe-inline' covers the theme
# pre-paint inline script + inline style attributes. No third-party origins:
# Sygna's console loads nothing from a CDN.
header Content-Security-Policy "default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; 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'"
file_server
}
header {
X-Content-Type-Options nosniff
X-Frame-Options DENY
Referrer-Policy strict-origin-when-cross-origin
Cross-Origin-Opener-Policy same-origin
}
}
+8 -5
View File
@@ -55,8 +55,11 @@ cp .env.example .env # then edit the passwords
docker compose up -d --build
```
Postgres → migrate (+seed) → backend → Caddy on `:80`. Only Caddy is published; the backend and
database are expose-only. Sign in with `BOOTSTRAP_ADMIN_EMAIL` / `BOOTSTRAP_ADMIN_PASSWORD`.
Postgres → migrate (+seed) → backend on `:80`. There is no reverse proxy: the backend serves the
API, the console and its own security headers, and is the only published service; the database is
expose-only. For HTTPS put your own TLS terminator in front (and set `FORWARDED_ALLOW_IPS` to its
address), or run Sygna as a module of the platform, where Atrium is the front door. `FRAME_ANCESTORS`
(`'none'` by default, or `'self'`) decides who may frame the console. Sign in with `BOOTSTRAP_ADMIN_EMAIL` / `BOOTSTRAP_ADMIN_PASSWORD`.
### Deploying on a managed PostgreSQL provider
@@ -101,7 +104,7 @@ entirely in the browser against an invented Warsaw firm — three matters, a wal
deadline, an unpaid invoice — with the data in `localStorage` and nothing leaving the page. That
is what makes the URL something you can send to somebody. `SYGNA_DEMO=0` opts out.
A real firm keeps the console on the **same origin** as its API, served by Caddy: everything here
A real firm keeps the console on the **same origin** as its API, served by its own backend: everything here
is privileged material, and a proxy in front of it is one more place that sees it.
### Local development
@@ -128,8 +131,8 @@ cd backend && alembic upgrade head && python -m app.seed
cd backend && .venv/bin/python -m uvicorn app.main:app --port 8032 --app-dir .
```
The console is served by the backend at `http://localhost:8032` (Caddy serves it directly in
production). On Windows write `.env` **without a BOM** — see the gotchas in
The console is served by the backend at `http://localhost:8032` (in production too: the backend
is its own edge, with the SPA fallback and the security headers). On Windows write `.env` **without a BOM** — see the gotchas in
[`CLAUDE.md`](CLAUDE.md).
`SEED_DEMO=true` creates a small firm whose demo data is chosen to exercise the conflict engine:
+18 -8
View File
@@ -33,6 +33,13 @@ COPY --from=build /install /usr/local
WORKDIR /app
COPY . .
# The static console, which this backend now serves itself (app/main.py mounts it at "/"; there is
# no Caddy in front any more). It lives in the repo's frontend/, outside this build context, so it
# arrives as a NAMED build context: compose passes `additional_contexts: { frontend: ./frontend }`,
# and a bare build from backend/ needs `docker build --build-context frontend=../frontend .`.
# /frontend is exactly where main.py's default (two levels above app/main.py) looks.
COPY --from=frontend . /frontend
RUN useradd -m app && mkdir -p /data && chown -R app /data /app
ENV DATA_DIR=/data
USER app
@@ -40,16 +47,19 @@ USER app
EXPOSE 8000
HEALTHCHECK --interval=15s --timeout=5s --retries=10 \
CMD python -c "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://localhost:8000/api/v1/health').status==200 else 1)"
# Trust X-Forwarded-For only from the reverse proxy. The default '*' is safe ONLY because the
# backend is expose-only in docker-compose (never host-published) — Caddy is the sole ingress.
# If you publish this port directly, set FORWARDED_ALLOW_IPS to the proxy's address so client IPs
# in the audit log can't be spoofed.
ENV FORWARDED_ALLOW_IPS=*
# Which proxy may set X-Forwarded-For / -Proto. On the platform that is Atrium's front door, pinned to
# Sygna's network in Atrium's compose.yaml; standalone the backend is published directly and nothing
# sits in front, so the default trusts loopback only (empty means the same — `:-` below treats empty
# as unset). Never `*`: with the port published, anyone could then forge the audit log's client IP.
ENV FORWARDED_ALLOW_IPS=
# Where this module is mounted on the platform. Empty by default, which is the standalone stack:
# Sygna at the root of its own host. Set ROOT_PATH=/sygna and the reverse proxy in front MUST
# strip that prefix (`handle_path /sygna/*`) — uvicorn PREPENDS root_path to the request path, so
# Sygna at the root of its own host. Set ROOT_PATH=/sygna and the front door MUST
# strip that prefix (Atrium forwards `/sygna/*` without it) — uvicorn PREPENDS root_path to the request path, so
# a proxy that does not strip gives `/sygna/sygna/...` and 404s everything, and a proxy that
# strips without this flag makes every server-generated URL escape the prefix. One decision, two
# places, one variable. The HEALTHCHECK above needs no change: uvicorn prepends, Starlette strips.
ENV ROOT_PATH=
CMD ["sh", "-c", "exec uvicorn app.main:app --host 0.0.0.0 --port 8000 --forwarded-allow-ips \"$FORWARDED_ALLOW_IPS\" --root-path \"$ROOT_PATH\""]
# `sh -c` so the variables expand at start-up; `exec` so uvicorn keeps PID 1 and gets SIGTERM.
# --no-server-header: nothing in front strips `Server` any more. These flags live ONLY here — no
# compose `command:` override, here or in Atrium's compose.yaml.
CMD ["sh", "-c", "exec uvicorn app.main:app --host 0.0.0.0 --port 8000 --root-path \"$ROOT_PATH\" --proxy-headers --forwarded-allow-ips \"${FORWARDED_ALLOW_IPS:-127.0.0.1}\" --no-server-header"]
+18 -2
View File
@@ -31,8 +31,8 @@ class Settings(BaseSettings):
# Where this module is mounted on the platform — `/sygna` — or empty when Sygna runs
# standalone at the root of its own host. The SAME value is handed to uvicorn as
# `--root-path` (backend/Dockerfile), because the two halves are one decision: Caddy strips
# the prefix with `handle_path /sygna/*` and uvicorn puts it back. They read one environment
# `--root-path` (backend/Dockerfile), because the two halves are one decision: the front door
# strips the prefix (Atrium forwards `/sygna/*` without it) and uvicorn puts it back. They read one environment
# variable so they cannot be set apart; FastAPI is told as well, so /docs and the OpenAPI
# `servers` entry point at the prefixed address rather than the origin root.
root_path: str = ""
@@ -240,6 +240,22 @@ class Settings(BaseSettings):
# separately-served console in dev.
cors_allow_origins: str = ""
# CSP `frame-ancestors` on the console, and the matching X-Frame-Options on every response this
# backend sends (app/edge.py). `'none'` (the default) = nobody may frame Sygna (X-Frame-Options:
# DENY), what Caddy sent before this backend served its own console. `'self'` = only this
# origin may (SAMEORIGIN), for a platform page that embeds Sygna. Nothing else: an origin list
# cannot be expressed in X-Frame-Options, and a typo here must not quietly widen framing, so
# anything else refuses start-up. The quotes are optional (an .env loader may strip them).
frame_ancestors: str = "'none'"
@field_validator("frame_ancestors")
@classmethod
def _known_frame_ancestors(cls, v: str) -> str:
bare = v.strip().strip("'")
if bare not in ("none", "self"):
raise ValueError("FRAME_ANCESTORS must be 'none' or 'self'")
return f"'{bare}'"
# Bootstrap admin (seed)
bootstrap_admin_email: str = "admin@example.com"
bootstrap_admin_password: str = "admin12345"
+223
View File
@@ -0,0 +1,223 @@
"""What Caddy used to do in front of this backend: security headers, the body cap, the console.
The platform no longer runs Caddy. Atrium's backend is the front door and forwards `/sygna/*` here
with the prefix stripped (exactly as `handle_path /sygna/*` did), and a standalone install runs
uvicorn on :80 with nothing in front. Either way this process now answers for everything a browser
gets, so the rules Sygna's Caddyfile applied live here, unchanged in substance. Same shape as
Counsel Scorecard's `app/edge.py`.
**Every path comparison reads the ROUTE path** (`starlette._utils.get_route_path`), never
`request.url.path` / `scope["path"]`: with ROOT_PATH=/sygna uvicorn re-prepends the prefix, so the
raw path reads `/sygna/api/v1/...` and an `/api` match would silently miss, handing the API the
console's CSP and Cache-Control, and handing unknown API paths to the console.
"""
from __future__ import annotations
from collections.abc import Sequence
from fastapi import HTTPException as FastAPIHTTPException
from starlette._utils import get_route_path
from starlette.datastructures import MutableHeaders
from starlette.exceptions import HTTPException
from starlette.responses import JSONResponse, Response
from starlette.routing import BaseRoute, Match
from starlette.staticfiles import StaticFiles
from starlette.types import ASGIApp, Message, Receive, Scope, Send
# Paths the backend owns. Caddy's split was `@api path /api/v1/* /healthz` → backend, everything
# else → the static console; nothing under these is ever answered by the console. `/api` as a
# whole rather than `/api/v1` only: an `/api/v2/x` that renders the console's HTML with a 200 is a
# misleading answer to a client, not a deep link.
API_PATHS = ("/api", "/healthz")
# The owner's ceiling for one request body. Caddy set none. It bounds memory; it does not shape the
# API (document and template uploads keep their own, smaller limits).
MAX_BODY_BYTES = 100 * 1024 * 1024
def owns_path(path: str) -> bool:
return any(path == p or path.startswith(f"{p}/") for p in API_PATHS)
def content_security_policy(frame_ancestors: str, frame_src: str = "'self'") -> str:
"""The console's policy: Sygna's Caddyfile CSP, plus `frame-src`, with frame-ancestors from the
setting. 'unsafe-inline' is required by the theme pre-paint inline <script> and the inline
style="" attributes in index.html. Nothing loads from a CDN — Sygna's console is entirely
same-origin, which is the point when the data is privileged. `frame-src` names Galena's origin
only when the case-file embed is switched on (main.py), so by default the console frames nothing
but itself."""
return ("default-src 'self'; "
"base-uri 'self'; "
"object-src 'none'; "
f"frame-ancestors {frame_ancestors}; "
f"frame-src {frame_src}; "
"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'")
def _problem(scope: Scope, status: int, title: str, detail: str,
headers: dict[str, str] | None = None) -> JSONResponse:
# The same RFC 9457 body app/errors.py builds for every other refusal.
return JSONResponse(
{"type": "about:blank", "title": title, "status": status, "detail": detail,
"instance": scope.get("root_path", "") + get_route_path(scope)},
status_code=status, media_type="application/problem+json", headers=headers)
class SecurityHeaders:
"""Caddy's `header { ... }` block, on every response — console, API, 404, 405, 413 and 500.
Pure ASGI (not `@app.middleware("http")`) so it wraps the responses the other middlewares
produce and a streamed body is not buffered. Added LAST in main.py, i.e. outermost. Headers are
SET, as Caddy's `header` directive set them, not defaulted.
Everywhere: nosniff, X-Frame-Options (DENY for `'none'`, SAMEORIGIN for `'self'`),
`Referrer-Policy: same-origin`, `Cross-Origin-Opener-Policy: same-origin`.
On the console only (anything outside /api and /healthz), as Caddy's `handle` block had them:
the CSP and `Cache-Control: no-cache` (revalidate by ETag, so a rebuilt app.js/app.css is picked
up without a hard refresh). Not on the API: /api/v1/docs is Swagger UI from a CDN, which the
console's policy would blank. No HSTS — Sygna's Caddyfile never sent one. The `Server` header is
not removed here; uvicorn runs with --no-server-header.
"""
def __init__(self, app: ASGIApp, *, frame_ancestors: str, frame_src: str = "'self'") -> None:
self.app = app
self.csp = content_security_policy(frame_ancestors, frame_src)
self.xfo = "SAMEORIGIN" if frame_ancestors == "'self'" else "DENY"
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
await self.app(scope, receive, send)
return
console = not owns_path(get_route_path(scope))
async def _send(message: Message) -> None:
if message["type"] == "http.response.start":
headers = MutableHeaders(scope=message)
headers["X-Content-Type-Options"] = "nosniff"
headers["X-Frame-Options"] = self.xfo
headers["Referrer-Policy"] = "same-origin"
headers["Cross-Origin-Opener-Policy"] = "same-origin"
if console:
headers["Content-Security-Policy"] = self.csp
headers["Cache-Control"] = "no-cache"
await send(message)
await self.app(scope, receive, _send)
class _BodyTooLarge(FastAPIHTTPException):
"""FastAPI's own HTTPException, because FastAPI turns any OTHER exception raised while it reads
the body into a 400 "error parsing the body"; this one it re-raises, and its handler answers."""
def __init__(self, max_bytes: int) -> None:
super().__init__(413, f"The request body exceeds {max_bytes} bytes.")
class BodySizeLimit:
"""Refuse a request body over `max_bytes` with a 413 problem response.
A declared Content-Length over the cap is refused before the app runs. A chunked body is
counted as it is read; once it passes the cap the app's next `receive()` raises, and the 413 is
sent if the app has not started its response yet.
"""
def __init__(self, app: ASGIApp, *, max_bytes: int = MAX_BODY_BYTES) -> None:
self.app = app
self.max_bytes = max_bytes
def _refusal(self, scope: Scope) -> JSONResponse:
return _problem(scope, 413, "Payload Too Large",
f"The request body exceeds {self.max_bytes} bytes.")
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
await self.app(scope, receive, send)
return
for name, value in scope.get("headers", ()):
if name == b"content-length":
try:
declared = int(value)
except ValueError:
declared = 0
if declared > self.max_bytes:
await self._refusal(scope)(scope, receive, send)
return
seen = 0
started = False
async def _receive() -> Message:
nonlocal seen
message = await receive()
if message["type"] == "http.request":
seen += len(message.get("body", b""))
if seen > self.max_bytes:
raise _BodyTooLarge(self.max_bytes)
return message
async def _send(message: Message) -> None:
nonlocal started
if message["type"] == "http.response.start":
started = True
await send(message)
try:
await self.app(scope, _receive, _send)
except _BodyTooLarge:
if started:
raise
await self._refusal(scope)(scope, receive, send)
class SpaStaticFiles(StaticFiles):
"""Caddy's `try_files {path} /index.html` + `file_server`: a GET/HEAD for a file that does not
exist gets the console's index.html (200), so a deep link survives a reload. Other methods keep
StaticFiles' 405, as file_server answered."""
async def get_response(self, path: str, scope: Scope) -> Response:
try:
return await super().get_response(path, scope)
except HTTPException as exc:
if exc.status_code != 404:
raise
return await super().get_response("index.html", scope)
class ConsoleUnlessApi:
"""Serve the static console, except under the API's own paths — those are answered here.
The console is mounted at "/" last, so every bound path+method wins. But a `Mount` FULL-matches
every path beneath it, which beats a route's PARTIAL match (path right, method wrong — the
signal Starlette turns into 405). Without this shim `GET` on a POST-only API path would get the
console's index.html (the SPA fallback), and `POST /api/v1/nope` a static-file 405. So under
`/api` and `/healthz` this answers itself: 405 + `Allow` when some route claims the path under
another method (asked via Starlette's own `route.matches`, no second copy of the path regexes),
and a 404 problem response when none does. Same design as Galena's `_ConsoleUnlessApi` and
Counsel's `ConsoleUnlessApi`.
"""
def __init__(self, console: ASGIApp, routes: Sequence[BaseRoute]) -> None:
self._console = console
# The LIVE app.routes list, read per request: this is built while the app still is.
self._routes = routes
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http" or not owns_path(get_route_path(scope)):
await self._console(scope, receive, send)
return
allowed: set[str] = set()
for route in self._routes:
methods = getattr(route, "methods", None)
if methods and route.matches(scope)[0] is Match.PARTIAL:
allowed |= set(methods)
if allowed:
response = _problem(scope, 405, "Method Not Allowed",
"That method is not allowed on this path.",
headers={"Allow": ", ".join(sorted(allowed))})
else:
response = _problem(scope, 404, "Not Found", "No API route matches this path.")
await response(scope, receive, send)
+24 -49
View File
@@ -11,15 +11,15 @@ from pathlib import Path
from dredd_core.identity_schema import assert_identity_schema
from fastapi import Depends, FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles
from sqlalchemy import text
from starlette._utils import get_route_path
from . import __version__
from .config import get_settings
from .db import engine
from .deps import refuse_cross_site_write
from .edge import BodySizeLimit, ConsoleUnlessApi, SecurityHeaders, SpaStaticFiles
from .errors import ProblemDetailErrorMiddleware, install_error_handlers
from .logging_config import configure_logging
from .observability import setup_observability
@@ -121,8 +121,8 @@ app = FastAPI(
docs_url=f"{API_PREFIX}/docs",
redoc_url=None,
openapi_url=f"{API_PREFIX}/openapi.json",
# The path this module is mounted at on the platform (`/sygna`), empty standalone. Caddy
# strips it and uvicorn re-adds it; this is the third party to that one decision, and it is
# The path this module is mounted at on the platform (`/sygna`), empty standalone. The front
# door (Atrium) strips it and uvicorn re-adds it; this is the third party to that one decision, and it is
# what makes /docs and the OpenAPI `servers` entry address the module rather than the origin.
root_path=settings.root_path,
lifespan=lifespan,
@@ -133,6 +133,10 @@ app = FastAPI(
install_error_handlers(app)
setup_observability(app, engine)
# The request-body cap (100 MB). Innermost of the middlewares added here, so a chunked body that
# overruns it is refused before ProblemDetailErrorMiddleware could mistake that for a 500.
app.add_middleware(BodySizeLimit)
# Added BEFORE CORS so 500s flow back out through CORS and carry the headers a browser needs.
app.add_middleware(ProblemDetailErrorMiddleware)
@@ -144,52 +148,13 @@ if settings.cors_origins_list:
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 —
# Sygna's console is entirely same-origin, which is the point when the data is privileged.
#
# `frame-src` names Galena's origin ONLY when embedding is switched on, so the default build
# still frames nothing at all. Stage C (PLAN.md §3.4) needs the matching change on Galena's
# side; until that lands the console falls back to a link.
# side; until that lands the console falls back to a link. The policy itself is app/edge.py's.
_FRAME_SRC = "'self'"
if settings.galena_embed and settings.galena_origin:
_FRAME_SRC = f"'self' {settings.galena_origin}"
_CONSOLE_CSP = (
"default-src 'self'; "
"base-uri 'self'; "
"object-src 'none'; "
"frame-ancestors 'none'; "
f"frame-src {_FRAME_SRC}; "
"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")
# The ROUTE path, not the URL path. Mounted at `/sygna`, the URL path still carries the
# prefix, so `/sygna/api/v1/...` would fail the test below and every API response would pick
# up the console's Cache-Control and CSP. `get_route_path` is the helper Starlette's own
# router uses to strip `root_path`; it has no public alias, and re-deriving the strip by hand
# in each of the family's four backends is how four copies drift.
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, aml.router, nodes.router, permissions.router,
@@ -204,7 +169,7 @@ for router in (
app.include_router(router, prefix=API_PREFIX)
@app.get("/healthz")
@app.api_route("/healthz", methods=["GET", "HEAD"])
def healthz(deep: bool = False) -> dict:
"""Liveness by default; readiness with `?deep=1`.
@@ -231,9 +196,19 @@ def healthz(deep: bool = False) -> dict:
return {"status": "ok", "database": True}
# Serve the static console (so the app runs without a separate web server in dev). In production
# Caddy can serve it directly. Mount LAST so /api/v1/* and /healthz win.
# Caddy's `encode gzip`. Inside SecurityHeaders, so compressed responses carry the headers too.
app.add_middleware(GZipMiddleware, minimum_size=1000)
# Caddy's `header { ... }` block. Added LAST, so it is the outermost middleware and also stamps the
# responses every other layer produces — 404, 405, 413 and the 500 problem response included.
app.add_middleware(SecurityHeaders, frame_ancestors=settings.frame_ancestors, frame_src=_FRAME_SRC)
# The static console (frontend/), which Caddy used to serve from /srv. Mounted at "/" LAST so every
# API route wins, behind ConsoleUnlessApi so /api/* and /healthz never fall through to it (see its
# docstring), with Caddy's `try_files {path} /index.html` SPA fallback. SYGNA_FRONTEND_DIR overrides
# the location; the default is the repo's ../frontend, which is also where backend/Dockerfile copies
# it (/frontend in the image). Absent (a bare API checkout), the backend simply serves no console.
_FRONTEND = Path(os.environ.get("SYGNA_FRONTEND_DIR")
or Path(__file__).resolve().parents[2] / "frontend")
if _FRONTEND.exists():
app.mount("/", StaticFiles(directory=str(_FRONTEND), html=True), name="frontend")
if _FRONTEND.is_dir():
app.mount("/", ConsoleUnlessApi(SpaStaticFiles(directory=str(_FRONTEND), html=True),
app.routes), name="frontend")
+29 -18
View File
@@ -2,7 +2,7 @@
The failures this catches are the boring ones that cost an evening — a setting the code reads
but `.env.example` never mentions, a healthcheck pointing at a route that no longer exists, a
Caddy matcher that misses the API prefix. None of them show up in the test suite, because the
console mount that would swallow the API. None of them show up in the test suite, because the
test suite never reads docker-compose.yml.
Run it before shipping: python scripts/deploy_check.py
@@ -50,7 +50,7 @@ def read(rel: str) -> str:
compose = read("docker-compose.yml")
dockerfile = read("backend/Dockerfile")
caddy = read("Caddyfile")
edge_py = read("backend/app/edge.py")
env_example = read(".env.example")
config_py = read("backend/app/config.py")
main_py = read("backend/app/main.py")
@@ -85,9 +85,19 @@ check("condition: service_completed_successfully" in compose,
check("condition: service_healthy" in compose,
"nothing waits on the postgres healthcheck",
"migrate waits for a healthy postgres")
check('"80:80"' in compose and "expose:" in compose,
"expected only Caddy published and backend expose-only",
"only Caddy is published; postgres and backend are expose-only")
check('ports: ["80:8000"]' in compose and compose.count("ports:") == 1,
"expected only the backend published (80:8000) and postgres expose-only",
"only the backend is published; postgres is expose-only")
check("caddy" not in compose.lower() and not (ROOT / "Caddyfile").exists(),
"a Caddy service or Caddyfile is back — the backend is its own edge (app/edge.py)",
"no reverse proxy in the stack; the backend is its own edge")
check(compose.count("frontend: ./frontend") >= 2 and "COPY --from=frontend" in dockerfile,
"the console is not built into the image (additional_contexts + COPY --from=frontend)",
"the console is baked into the image from the frontend build context")
check("exec uvicorn" not in compose and "--no-server-header" in dockerfile
and "--proxy-headers" in dockerfile,
"uvicorn's edge flags (--proxy-headers, --no-server-header) are missing from the Dockerfile CMD",
"uvicorn runs with --proxy-headers and --no-server-header (Dockerfile CMD only)")
check("/docker-entrypoint-initdb.d" in compose,
"db/init is not mounted, so the least-privilege roles are never created",
"db/init mounted — app + migrator roles created on first start")
@@ -118,22 +128,23 @@ check("ARG DREDD_CORE_TOKEN" not in dockerfile and "ENV DREDD_CORE_TOKEN" not in
check("dredd_core_token" in compose and "environment: DREDD_CORE_TOKEN" in compose,
"compose does not pass DREDD_CORE_TOKEN to the build as a secret")
# ── Caddy matches the API the app actually serves ─────────────────────────────
# ── the backend's own edge matches what Caddy did ─────────────────────────────
prefix = re.search(r'API_PREFIX = "([^"]+)"', main_py)
check(bool(prefix), "cannot find API_PREFIX in main.py")
if prefix:
check(f"{prefix.group(1)}/*" in caddy,
f"Caddy does not route {prefix.group(1)}/* to the backend",
f"Caddy routes {prefix.group(1)}/* to the backend")
check("reverse_proxy backend:8000" in caddy,
"Caddy does not proxy to the backend service name/port",
"Caddy proxies to backend:8000")
check("try_files {path} /index.html" in caddy,
"no SPA fallback — deep links will 404 on reload",
"SPA fallback present (deep links survive a reload)")
for header in ("X-Content-Type-Options", "X-Frame-Options", "Content-Security-Policy"):
check(header in caddy, f"Caddy does not set {header}")
notes.append("Caddy sets nosniff / frame / CSP headers on the static console")
check(prefix.group(1).startswith("/api"),
f"API_PREFIX {prefix.group(1)} is outside /api, so ConsoleUnlessApi would not guard it",
f"{prefix.group(1)} is guarded from the console by ConsoleUnlessApi")
check("ConsoleUnlessApi(SpaStaticFiles(" in main_py,
"the console is not mounted behind ConsoleUnlessApi with the SPA fallback",
"SPA fallback present (deep links survive a reload); the API never falls to the console")
check("app.add_middleware(SecurityHeaders" in main_py and "GZipMiddleware" in main_py
and "app.add_middleware(BodySizeLimit)" in main_py,
"main.py does not install SecurityHeaders / GZip / BodySizeLimit")
for header in ("X-Content-Type-Options", "X-Frame-Options", "Content-Security-Policy",
"Referrer-Policy", "Cross-Origin-Opener-Policy", "Cache-Control"):
check(header in edge_py, f"app/edge.py does not set {header}")
notes.append("the backend sets nosniff / frame / CSP / referrer / COOP headers itself")
# ── secrets and least privilege ───────────────────────────────────────────────
check("app" in roles_sh and "migrator" in roles_sh,
+237
View File
@@ -0,0 +1,237 @@
"""DB-free tests for what Caddy used to do in front of the backend (`app/edge.py`, `main.py`).
The backend now serves its own console, sets its own security headers and answers /healthz, both as
a platform module (Atrium forwards /sygna/* with the prefix stripped, uvicorn re-adds it via
--root-path) and standalone (uvicorn on :80, nothing in front).
"""
from __future__ import annotations
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import ValidationError
from app.config import Settings
from app.edge import MAX_BODY_BYTES, BodySizeLimit, SecurityHeaders, content_security_policy
from app.errors import ProblemDetailErrorMiddleware
from app.main import _FRONTEND, app
# Sygna's Caddyfile CSP, character for character, with the `frame-src 'self'` the backend has
# always added (Caddy's policy had none, so default-src 'self' applied: the same thing, spelled out).
CADDY_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'")
client = TestClient(app)
INDEX = (_FRONTEND / "index.html").read_bytes()
def _assert_caddy_headers(resp, *, console: bool) -> None:
"""Caddy's `header { }` block on everything; its console `handle` added CSP + Cache-Control."""
h = resp.headers
assert h["x-content-type-options"] == "nosniff"
assert h["x-frame-options"] == "DENY"
assert h["referrer-policy"] == "same-origin"
assert h["cross-origin-opener-policy"] == "same-origin"
if console:
assert h["content-security-policy"] == CADDY_CSP
assert h["cache-control"] == "no-cache"
else:
assert "content-security-policy" not in h
assert h.get("cache-control") != "no-cache"
assert "strict-transport-security" not in h
assert "server" not in h
# ── headers on every kind of response ─────────────────────────────────────────
def test_default_csp_is_caddys_policy():
assert content_security_policy("'none'") == CADDY_CSP
@pytest.mark.parametrize("method,path,status,console", [
("GET", "/", 200, True), # the console
("GET", "/index.html", 200, True),
("GET", "/app.js", 200, True),
("GET", "/matters/123", 200, True), # SPA fallback
("POST", "/matters", 405, True), # wrong method on the console
("GET", "/api/v1/health", 200, False), # an API route
("GET", "/healthz", 200, False),
("HEAD", "/healthz", 200, False),
("GET", "/api/v1/nope", 404, False), # unknown API path
("POST", "/api/v1/health", 405, False), # wrong method on an API path
("GET", "/api/v1/auth/login", 405, False), # POST-only API route
("GET", "/api/v1/auth/me", 401, False), # refused
])
def test_every_response_carries_the_headers(method, path, status, console):
resp = client.request(method, path)
assert resp.status_code == status
_assert_caddy_headers(resp, console=console)
def test_headers_on_a_500():
inner = FastAPI()
@inner.get("/api/boom")
def boom():
raise RuntimeError("kaboom")
inner.add_middleware(ProblemDetailErrorMiddleware)
inner.add_middleware(SecurityHeaders, frame_ancestors="'none'")
resp = TestClient(inner, raise_server_exceptions=False).get("/api/boom")
assert resp.status_code == 500
assert resp.headers["content-type"] == "application/problem+json"
_assert_caddy_headers(resp, console=False)
def test_headers_on_a_413():
resp = client.post("/api/v1/auth/login", content=b"",
headers={"content-length": str(MAX_BODY_BYTES + 1)})
assert resp.status_code == 413
_assert_caddy_headers(resp, console=False)
def test_galena_embed_widens_frame_src_only():
csp = content_security_policy("'none'", "'self' https://galena.example")
assert "frame-src 'self' https://galena.example;" in csp
assert "frame-ancestors 'none';" in csp
# ── FRAME_ANCESTORS ───────────────────────────────────────────────────────────
def _framed(value: str):
inner = FastAPI()
inner.get("/")(lambda: {})
inner.add_middleware(SecurityHeaders, frame_ancestors=Settings(
_env_file=None, frame_ancestors=value).frame_ancestors)
return TestClient(inner).get("/").headers
def test_frame_ancestors_default_is_none_and_deny(monkeypatch):
monkeypatch.delenv("FRAME_ANCESTORS", raising=False)
assert Settings(_env_file=None).frame_ancestors == "'none'"
h = _framed("'none'")
assert h["x-frame-options"] == "DENY"
assert "frame-ancestors 'none';" in h["content-security-policy"]
@pytest.mark.parametrize("value", ["'self'", "self", " 'self' "])
def test_frame_ancestors_self_is_sameorigin(value):
h = _framed(value)
assert h["x-frame-options"] == "SAMEORIGIN"
assert "frame-ancestors 'self';" in h["content-security-policy"]
@pytest.mark.parametrize("value", ["*", "https://evil.example", "'self' https://x.example", "",
"'unsafe-inline'", "none self"])
def test_frame_ancestors_anything_else_refuses_startup(value):
with pytest.raises(ValidationError):
Settings(_env_file=None, frame_ancestors=value)
# ── routing: /healthz, the console, the API never served by it ────────────────
def test_spa_fallback_serves_index_for_unknown_console_paths():
for path in ("/", "/matters/abc", "/some/deep/link", "/nope.js"):
resp = client.get(path)
assert resp.status_code == 200, path
assert resp.content == INDEX, path
def test_real_assets_are_served_as_themselves():
resp = client.get("/app.css")
assert resp.status_code == 200
assert resp.content == (_FRONTEND / "app.css").read_bytes()
def test_api_is_never_answered_by_the_console():
for path in ("/api", "/api/", "/api/v1/nope", "/api/v2/x", "/healthz/x"):
resp = client.get(path)
assert resp.status_code == 404, path
assert resp.headers["content-type"] == "application/problem+json", path
assert resp.content != INDEX
def test_wrong_method_on_an_api_path_is_405_with_allow():
resp = client.post("/api/v1/health")
assert resp.status_code == 405
assert resp.headers["allow"] == "GET"
assert resp.json()["status"] == 405
resp = client.get("/api/v1/auth/login")
assert resp.status_code == 405 and resp.headers["allow"] == "POST"
resp = client.post("/healthz")
assert resp.status_code == 405
assert set(resp.headers["allow"].split(", ")) == {"GET", "HEAD"}
def test_unknown_api_path_under_another_method_is_404_not_405():
resp = client.post("/api/v1/nope")
assert resp.status_code == 404
assert resp.headers["content-type"] == "application/problem+json"
def test_gzip_on_large_responses():
assert len(INDEX) > 1000
resp = client.get("/", headers={"accept-encoding": "gzip"})
assert resp.headers.get("content-encoding") == "gzip"
_assert_caddy_headers(resp, console=True)
# ── behind the platform: ROOT_PATH=/sygna ─────────────────────────────────────
def test_root_path_prefix_still_routes_console_and_api():
# As uvicorn --root-path /sygna delivers it: the prefix is in both root_path and path.
prefixed = TestClient(app, root_path="/sygna")
console = prefixed.get("/sygna/matters/1")
assert console.status_code == 200 and console.content == INDEX
_assert_caddy_headers(console, console=True)
assert prefixed.get("/sygna/").content == INDEX
api = prefixed.get("/sygna/api/v1/health")
assert api.status_code == 200 and api.json()["service"] == "sygna"
_assert_caddy_headers(api, console=False)
assert prefixed.get("/sygna/healthz").status_code == 200
miss = prefixed.get("/sygna/api/v1/nope")
assert miss.status_code == 404
assert miss.headers["content-type"] == "application/problem+json"
assert miss.json()["instance"] == "/sygna/api/v1/nope"
_assert_caddy_headers(miss, console=False)
wrong = prefixed.post("/sygna/api/v1/health")
assert wrong.status_code == 405 and wrong.headers["allow"] == "GET"
# ── the request body cap ──────────────────────────────────────────────────────
def _echo_app(limit: int) -> TestClient:
inner = FastAPI()
@inner.post("/echo")
async def echo(payload: dict):
return payload
inner.add_middleware(BodySizeLimit, max_bytes=limit)
return TestClient(inner)
def test_body_over_the_cap_is_413():
c = _echo_app(64)
assert c.post("/echo", json={"a": "b"}).status_code == 200
resp = c.post("/echo", json={"a": "x" * 100})
assert resp.status_code == 413
assert resp.headers["content-type"] == "application/problem+json"
def test_chunked_body_over_the_cap_is_413():
c = _echo_app(64)
def chunks():
yield b'{"a": "'
yield b"x" * 100
yield b'"}'
resp = c.post("/echo", content=chunks(), headers={"content-type": "application/json"})
assert resp.status_code == 413
def test_the_app_cap_is_100_mb():
assert MAX_BODY_BYTES == 100 * 1024 * 1024
+2 -2
View File
@@ -5,7 +5,7 @@
# docker compose -f docker-compose.yml -f docker-compose.managed-db.yml up -d --build
#
# The database lives elsewhere, so the local postgres service is switched off and nothing waits
# for it; migrate (+seed), backend and caddy otherwise run as in docker-compose.yml. Before the
# for it; migrate (+seed) and backend otherwise run as in docker-compose.yml. Before the
# first start, Sygna must be provisioned in the database (schema sygna, roles sygna_migrator /
# sygna_app) and .env must carry its URLs: the provider's host and port (through a pooler, its
# session mode, never transaction mode), <role>.<tenant> user names where the pooler wants them,
@@ -22,7 +22,7 @@ services:
migrate:
# docker-compose.yml makes migrate wait for the local postgres healthcheck; there is none here.
# (backend depends only on migrate, and caddy only on backend, so both keep their ordering.)
# (backend depends only on migrate, so it keeps its ordering.)
# It does not retry either: some providers ban the host's IP after a few failed logins in a
# row, so a wrong password must fail once and loudly.
depends_on: !reset null
+21 -25
View File
@@ -1,8 +1,11 @@
# Sygna stack: postgres → migrate (+seed) → backend → caddy.
# Only Caddy is published to the host; postgres + backend are expose-only.
# Sygna stack: postgres → migrate (+seed) → backend on :80.
# No reverse proxy: the backend serves the API, the console and its own security headers, and is
# the only service published to the host; postgres is expose-only. For TLS put your own terminator
# in front (and list its address in FORWARDED_ALLOW_IPS below), or run Sygna as a module of the
# platform, where Atrium is the front door.
#
# Runs alongside Galena's stack — different volumes, different database. This file is the
# STANDALONE stack; on the platform the four modules sit behind ONE Caddy at one origin (the hub's
# STANDALONE stack; on the platform the modules sit behind Atrium's backend at one origin (the hub's
# deploy tree), each still its own process with its own schema and its own least-privilege roles.
# What they share is the package (dredd-core) and, from the identity stage, exactly two tables —
# never each other's domain data (PLAN.md §3.4).
@@ -33,6 +36,8 @@ services:
migrate:
build:
context: ./backend
additional_contexts:
frontend: ./frontend
secrets: [dredd_core_token]
image: sygna-backend:local
env_file: .env
@@ -47,14 +52,24 @@ services:
backend:
build:
context: ./backend
# The console (../frontend) is copied into the image from this named context
# (backend/Dockerfile: COPY --from=frontend).
additional_contexts:
frontend: ./frontend
secrets: [dredd_core_token]
image: sygna-backend:local
env_file: .env
expose: ["8000"]
ports: ["80:8000"]
environment:
# Nothing sits in front of the backend here, so no hop may set X-Forwarded-For: empty = the
# image's default (loopback only), and the audit log records the real peer address. Behind
# your own TLS terminator, set its address or subnet instead (never `*`).
FORWARDED_ALLOW_IPS: ""
# No `command:` — backend/Dockerfile's CMD is the one place uvicorn's flags live.
# Readiness, not liveness: `?deep=1` runs SELECT 1, so a container that is up but cannot
# reach the database reports unhealthy instead of quietly accepting traffic it cannot serve.
# Caddy's `depends_on` then waits for a backend that actually works. Python rather than curl
# or wget — the slim image has neither, and a healthcheck that always fails is worse than none.
# Python rather than curl or wget — the slim image has neither, and a healthcheck that always
# fails is worse than none.
healthcheck:
test: ["CMD", "python", "-c",
"import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:8000/healthz?deep=1', timeout=4).status == 200 else 1)"]
@@ -68,28 +83,9 @@ services:
migrate:
condition: service_completed_successfully
caddy:
image: caddy:2
depends_on:
backend:
condition: service_healthy
environment:
CADDY_SITE_ADDRESS: ${CADDY_SITE_ADDRESS:-:80}
ports:
- "80:80"
- "443:443"
- "443:443/udp"
volumes:
- ./Caddyfile:/etc/caddy/Caddyfile:ro
- ./frontend:/srv:ro
- caddy_data:/data
- caddy_config:/config
volumes:
pgdata:
sygna-data:
caddy_data:
caddy_config:
secrets:
# Read from the environment of whoever runs `docker compose build`, and used only by the
+3 -3
View File
@@ -17,14 +17,14 @@
# Set SYGNA_DEMO=0 to get a bare console with neither backend nor mock.
#
# This is a front door, not a way to run Sygna's server on Netlify. In particular: a real firm's
# deployment keeps the console on the SAME origin as its API, served by Caddy, because everything
# deployment keeps the console on the SAME origin as its API, served by its own backend, because everything
# in Sygna is privileged material and a proxy in front of it is one more place that sees it.
[build]
publish = "frontend"
command = "bash netlify/prepare.sh"
# Roughly mirrors the Caddy deploy's hardening; the strict CSP lives in the backend (app/main.py).
# Roughly mirrors the backend's own hardening; the strict CSP lives in the backend (app/edge.py).
[[headers]]
for = "/*"
[headers.values]
@@ -34,7 +34,7 @@
# Sygna frames GALENA (the Akta tab, controlled by frame-src — who Sygna may embed); no page
# ever frames Sygna, and the demo has no case file to show anyway.
X-Frame-Options = "DENY"
Referrer-Policy = "strict-origin-when-cross-origin"
Referrer-Policy = "same-origin"
# The console loads nothing from a CDN — the same rule the real deployment enforces — so the
# demo cannot quietly acquire a third-party dependency that the Docker build would then lack.
Content-Security-Policy = "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'"