Scaffold Agora (dredd skill: simple tenancy, red, pl-first, dredd-core v0.22.0)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+158
@@ -0,0 +1,158 @@
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# Agora — copy to .env and edit. On Windows write it WITHOUT a BOM:
|
||||
# [System.IO.File]::WriteAllText("$PWD\.env", (Get-Content .env.example -Raw))
|
||||
# (PowerShell's Out-File -Encoding utf8 adds a BOM, which pydantic-settings then
|
||||
# folds into the first key name and you get a baffling "field required" error.)
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
# Core. Defaults fail closed: production hides error detail. The session cookie's
|
||||
# Secure flag is auto-detected from the request scheme (see SESSION_COOKIE_SECURE).
|
||||
APP_ENV=production
|
||||
APP_BASE_URL=http://localhost
|
||||
# Path prefix this deployment is mounted under. Empty = served at the origin root (this stack).
|
||||
# ROOT_PATH=/agora runs it as a module of a platform (one origin, one module per path). It is
|
||||
# HALF of one decision: the front door must STRIP the prefix (Atrium forwards `/agora/*` without it) and
|
||||
# this backend re-adds it via uvicorn --root-path. Set only one of the two and you get a doubled
|
||||
# prefix (404s everywhere) or server-generated URLs that escape it. The console needs nothing — it
|
||||
# derives its API base from the document.
|
||||
ROOT_PATH=
|
||||
|
||||
# ── Database ─────────────────────────────────────────────────────────────────
|
||||
# Runtime uses the least-privilege `app` role; Alembic uses `migrator`.
|
||||
POSTGRES_DB=agora
|
||||
POSTGRES_PASSWORD=change_me_super
|
||||
DB_APP_PASSWORD=change_me_app
|
||||
DB_MIGRATOR_PASSWORD=change_me_migrator
|
||||
|
||||
DATABASE_URL=postgresql+pg8000://app:change_me_app@postgres:5432/agora
|
||||
MIGRATION_DATABASE_URL=postgresql+pg8000://migrator:change_me_migrator@postgres:5432/agora
|
||||
# The runtime role's name (the user in DATABASE_URL); the runtime-grants migration grants to it.
|
||||
DB_APP_ROLE=app
|
||||
# The backend's connection pool: at most DB_POOL_SIZE + DB_MAX_OVERFLOW connections.
|
||||
DB_POOL_SIZE=5
|
||||
DB_MAX_OVERFLOW=10
|
||||
# TLS rule: a database host that is not local ("", localhost, 127.0.0.1, ::1 or `postgres`) must say
|
||||
# sslmode=verify-full in its URL, or the backend, migrate and the seed refuse to start. A private
|
||||
# database on a trusted network that truly needs no TLS is listed here instead (comma-separated).
|
||||
# No other opt-out.
|
||||
DB_LOCAL_HOSTS=
|
||||
|
||||
# ── Managed PostgreSQL (the family's shared database; replaces the local postgres) ──
|
||||
# Runbook: db/managed/README.md. Every app of the family shares ONE managed database; Agora
|
||||
# lives in schema agora, as roles agora_migrator and agora_app. Provision it
|
||||
# once, then replace the Database settings above with these, delete the POSTGRES_PASSWORD and
|
||||
# DB_*_PASSWORD lines (unused there), and start with BOTH compose files:
|
||||
# docker compose -f docker-compose.yml -f docker-compose.managed-db.yml up -d --build
|
||||
# - Host and port: from the provider's connection details. Through a pooler use its SESSION mode
|
||||
# (transaction mode breaks prepared statements; on the poolers the family knows that is port 5432,
|
||||
# never 6543), or the direct connection.
|
||||
# - User: <role>, or <role>.<tenant> where the pooler wants the tenant in the user name. Never the
|
||||
# platform admin (postgres).
|
||||
# - TLS: sslmode=verify-full against the provider's root CA (downloaded from its dashboard), which the
|
||||
# override mounts at /run/certs/db-ca.crt from MANAGED_DB_CA_FILE; leave sslrootcert out to verify
|
||||
# against the system trust store instead. sslmode=prefer/allow/disable are refused, and so is a
|
||||
# URL to any host that is not local without sslmode=verify-full (DB_LOCAL_HOSTS above).
|
||||
# - Passwords: percent-encode every character outside A-Z a-z 0-9 - . _ ~ (e.g. @ -> %40, % -> %25).
|
||||
# - DB_APP_ROLE: the role in DATABASE_URL without any .<tenant> suffix (migrate refuses otherwise).
|
||||
# - Pool: count DB_POOL_SIZE + DB_MAX_OVERFLOW + 1 (a seed or check beside the backend) per app, and
|
||||
# keep the total over every app in the database at or below 80% of its connection limit (the
|
||||
# provider's own services use the rest): 72 of 90, 48 of 60. Five apps at the defaults take
|
||||
# 5 x (15 + 1) = 80, which does NOT fit a 90-connection limit: set DB_POOL_SIZE=4 and
|
||||
# DB_MAX_OVERFLOW=8 in EVERY app (5 x 13 = 65), or size the instance for more. For a 60-connection
|
||||
# limit set DB_POOL_SIZE=3 and DB_MAX_OVERFLOW=2 in EVERY app (5 x 6 = 30). Through a pooler in
|
||||
# session mode, its own pool size must be at least DB_POOL_SIZE + DB_MAX_OVERFLOW + 1.
|
||||
# DB_POOL_SIZE >= 1 and DB_MAX_OVERFLOW >= 0 (0 / -1 would mean no limit, so they are refused).
|
||||
# MANAGED_DB_CA_FILE=./certs/db-ca.crt
|
||||
# DATABASE_URL=postgresql+pg8000://agora_app.<tenant>:<app-password>@<host>:5432/postgres?sslmode=verify-full&sslrootcert=/run/certs/db-ca.crt
|
||||
# MIGRATION_DATABASE_URL=postgresql+pg8000://agora_migrator.<tenant>:<migrator-password>@<host>:5432/postgres?sslmode=verify-full&sslrootcert=/run/certs/db-ca.crt
|
||||
# DB_APP_ROLE=agora_app
|
||||
# DB_POOL_SIZE=4
|
||||
# DB_MAX_OVERFLOW=8
|
||||
|
||||
# ── Storage ──────────────────────────────────────────────────────────────────
|
||||
DATA_DIR=/data
|
||||
|
||||
# ── One platform, one account ────────────────────────────────────────────────
|
||||
# The shared identity schema. Empty — this stack — is STANDALONE: Agora owns its own
|
||||
# accounts, has its own sign-in screen and its own Users administration, and the three settings
|
||||
# below do nothing. That is a supported deployment for ever, not a stage to grow out of.
|
||||
#
|
||||
# Set IDENTITY_SCHEMA=dredd and this app becomes a MODULE of the platform: `app_user`,
|
||||
# `session` and `module_permission` live in a neutral schema the hub owns and this app READS. A
|
||||
# person then has ONE account for everything, signs in once at the hub, and the cookie they got
|
||||
# there is the cookie this app accepts — one origin, one cookie, nothing to hand over. This app's
|
||||
# sign-in form disappears (there is no password here), account creation and password changes answer
|
||||
# 409 pointing at the hub, and app tokens stay listable and revocable but are minted there.
|
||||
#
|
||||
# It also starts REFUSING people, which standalone it never does. `module_permission` holds one row
|
||||
# per person per module, and no row is no access: somebody with a platform account who has not been
|
||||
# admitted to this one is turned away at the door rather than shown an empty screen. Admitting them,
|
||||
# and making somebody a moderator of this app, happens in the hub — this app holds SELECT on that
|
||||
# table and nothing else.
|
||||
#
|
||||
# Switching it on is NOT just this line. In order: the platform admin re-renders
|
||||
# db/managed/provision.sql with --identity-schema / --identity-owner and runs it (the schema, USAGE
|
||||
# and a search_path of `agora, dredd, extensions` — none of which a migrator may
|
||||
# do); the hub's own migration creates the tables and grants this app's two roles their tier; then
|
||||
# `alembic upgrade head` here runs 0003, which merges this schema's accounts into the shared ones by
|
||||
# e-mail address. Read backend/alembic/versions/0003_shared_identity.py before running it on
|
||||
# anything you care about — it drops this app's local identity tables, and every session and app
|
||||
# token with them. db/managed/README.md has the whole sequence.
|
||||
IDENTITY_SCHEMA=
|
||||
# This app's slug on the platform — the module a permission row admits somebody to. Only meaningful
|
||||
# with IDENTITY_SCHEMA set, and it must match the slug the hub uses for this app, or nobody's row
|
||||
# resolves and nobody but a platform administrator can open it. Note it is NOT always the same
|
||||
# string as the Postgres schema (`agora`): a module slug is a URL path segment, so the hub's
|
||||
# module_permission table allows hyphens and refuses underscores, while a schema name is the other
|
||||
# way round. The scaffolder derived this one from that one; change both or neither.
|
||||
MODULE_SLUG=agora
|
||||
# Where people sign in when accounts are shared: the hub's address as a browser sees it, e.g.
|
||||
# /atrium/. Empty is allowed — the console then says accounts live elsewhere without offering a
|
||||
# link that goes nowhere.
|
||||
IDENTITY_HUB_URL=
|
||||
# The session cookie's name. One account means one cookie: at a cutover every app in the family is
|
||||
# set to dredd_session. The old name is still read for a while, so renaming it does not sign
|
||||
# everybody out the moment the container restarts.
|
||||
SESSION_COOKIE_NAME=agora_session
|
||||
|
||||
# ── Auth / sessions ──────────────────────────────────────────────────────────
|
||||
SESSION_TTL_HOURS=12
|
||||
LOGIN_MAX_ATTEMPTS=5
|
||||
LOGIN_LOCKOUT_MINUTES=15
|
||||
# Empty = auto-detect from the request scheme (Secure over HTTPS only). Never key
|
||||
# this off APP_ENV — a Secure cookie over plain HTTP is dropped and login "doesn't stick".
|
||||
SESSION_COOKIE_SECURE=
|
||||
|
||||
# CORS — empty by default (same-origin design). Comma-separated origins for a
|
||||
# separately-served console in dev.
|
||||
CORS_ALLOW_ORIGINS=
|
||||
|
||||
# Who may frame Agora: 'none' (default; X-Frame-Options DENY) or 'self' (SAMEORIGIN, what the
|
||||
# platform's kit sets). Anything else refuses start-up.
|
||||
FRAME_ANCESTORS='none'
|
||||
|
||||
# ── Bootstrap admin (seed) ───────────────────────────────────────────────────
|
||||
BOOTSTRAP_ADMIN_EMAIL=admin@example.com
|
||||
BOOTSTRAP_ADMIN_PASSWORD=admin12345
|
||||
# Seed a small demo dataset so the app isn't empty on first run.
|
||||
SEED_DEMO=true
|
||||
|
||||
# ── App tokens ───────────────────────────────────────────────────────────────
|
||||
# Named, revocable credentials for desktop/CLI clients, so they never store a password.
|
||||
# The window is an IDLE timeout: every use slides it forward, so a token in regular use keeps
|
||||
# working while one that is exfiltrated and parked expires on its own.
|
||||
APP_TOKENS_ENABLED=true
|
||||
APP_TOKEN_IDLE_DAYS=30
|
||||
APP_TOKEN_MAX_IDLE_DAYS=365
|
||||
APP_TOKEN_RENEW_AFTER_HOURS=12
|
||||
|
||||
# ── The edge ─────────────────────────────────────────────────────────────────
|
||||
# No reverse proxy: the backend is published on :80 (plain HTTP) and is its own edge (app/edge.py).
|
||||
# uvicorn trusts X-Forwarded-For only from these addresses (default 127.0.0.1). On the platform, the
|
||||
# front door's address; never `*`.
|
||||
FORWARDED_ALLOW_IPS=127.0.0.1
|
||||
|
||||
# ── OpenTelemetry (opt-in) ───────────────────────────────────────────────────
|
||||
OTEL_ENABLED=false
|
||||
OTEL_SERVICE_NAME=agora-backend
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317
|
||||
@@ -0,0 +1,10 @@
|
||||
* text=auto eol=lf
|
||||
# Shell scripts run inside Linux containers: CRLF makes the shebang unparseable.
|
||||
*.sh text eol=lf
|
||||
*.py text eol=lf
|
||||
*.js text eol=lf
|
||||
*.css text eol=lf
|
||||
*.html text eol=lf
|
||||
*.md text eol=lf
|
||||
*.yml text eol=lf
|
||||
Dockerfile text eol=lf
|
||||
@@ -0,0 +1,306 @@
|
||||
name: CI
|
||||
on: [push, pull_request]
|
||||
|
||||
jobs:
|
||||
backend:
|
||||
runs-on: ubuntu-latest
|
||||
# 16 is the local stack's Postgres; 17 is what managed providers commonly run.
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
postgres: ["16", "17"]
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:${{ matrix.postgres }}
|
||||
env:
|
||||
POSTGRES_DB: agora
|
||||
POSTGRES_PASSWORD: superpw
|
||||
ports: ["5432:5432"]
|
||||
options: >-
|
||||
--health-cmd "pg_isready -U postgres" --health-interval 5s
|
||||
--health-timeout 5s --health-retries 20
|
||||
env:
|
||||
DATABASE_URL: postgresql+pg8000://app:apppw@localhost:5432/agora
|
||||
MIGRATION_DATABASE_URL: postgresql+pg8000://migrator:migpw@localhost:5432/agora
|
||||
DATA_DIR: ${{ github.workspace }}/agora-data
|
||||
BOOTSTRAP_ADMIN_EMAIL: admin@example.com
|
||||
BOOTSTRAP_ADMIN_PASSWORD: adminpass1
|
||||
SEED_DEMO: "true"
|
||||
AGORA_RUN_INTEGRATION: "1"
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/setup-python@v6
|
||||
with: { python-version: "3.12" }
|
||||
- name: Create least-privilege roles
|
||||
# The suite then runs as the DML-only `app` role, which is the only way the grants get
|
||||
# tested at all — a suite run as the superuser proves nothing about least privilege.
|
||||
run: |
|
||||
PGPASSWORD=superpw psql -h localhost -U postgres -d agora -v ON_ERROR_STOP=1 <<'SQL'
|
||||
CREATE ROLE migrator LOGIN PASSWORD 'migpw';
|
||||
CREATE ROLE app LOGIN PASSWORD 'apppw';
|
||||
GRANT CONNECT ON DATABASE agora TO migrator, app;
|
||||
ALTER SCHEMA public OWNER TO migrator;
|
||||
GRANT USAGE ON SCHEMA public TO app;
|
||||
-- Pre-create the extension as the superuser; the migration's CREATE EXTENSION IF NOT
|
||||
-- EXISTS then no-ops, so the least-privilege migrator never needs extension rights.
|
||||
CREATE EXTENSION IF NOT EXISTS "pgcrypto";
|
||||
SQL
|
||||
- name: Authenticate to dredd-core
|
||||
# dredd-core is a PRIVATE repo, so the `git+https://` requirement cannot be fetched
|
||||
# anonymously — without this step `pip install` fails with a git auth prompt/404.
|
||||
# The rewrite injects the token for that ONE repo URL; every other GitHub URL is untouched,
|
||||
# and the secret stays out of the requirements file and the pip log.
|
||||
# Add the secret under Settings → Secrets and variables → Actions → DREDD_CORE_TOKEN
|
||||
# (a fine-grained PAT with read-only Contents access on Alpaq92/dredd-core).
|
||||
env:
|
||||
TOKEN: ${{ secrets.DREDD_CORE_TOKEN }}
|
||||
run: |
|
||||
git config --global url."https://x-access-token:${TOKEN}@github.com/Alpaq92/dredd-core".insteadOf "https://github.com/Alpaq92/dredd-core"
|
||||
- name: Install deps
|
||||
working-directory: backend
|
||||
run: pip install -r requirements-dev.txt
|
||||
- name: Migrate + seed
|
||||
working-directory: backend
|
||||
run: alembic upgrade head && python -m app.seed
|
||||
- name: Tests
|
||||
working-directory: backend
|
||||
run: pytest -q --cov=app --cov-report=term-missing
|
||||
- name: Console syntax
|
||||
# A duplicate `const` inside one function silently stops the whole file parsing, so every
|
||||
# function after it disappears — and the symptom is a blank screen with no console error.
|
||||
run: node --check frontend/app.js
|
||||
- name: License gate (Python)
|
||||
working-directory: backend
|
||||
run: python scripts/license_gate.py
|
||||
- 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 reverse-proxy service
|
||||
# creeping back into compose.
|
||||
run: python scripts/deploy_check.py
|
||||
|
||||
# ── the family's shared managed database, emulated ──────────────────────────
|
||||
# The backend job runs on a superuser-made `app`/`migrator` pair in `public`. In the shared managed
|
||||
# database, Agora lives in schema `agora` as `agora_migrator` / `agora_app`,
|
||||
# provisioned by a platform admin that is NOT a superuser, next to the other apps' schemas.
|
||||
# `dredd_core.managed emulate` (TEST-ONLY) turns this plain Postgres 17 into a managed-Postgres
|
||||
# lookalike: a CREATEROLE admin `postgres_managed` standing in for a provider's `postgres`, the API
|
||||
# roles anon / authenticated / service_role (what an auto-generated table API connects as), and an
|
||||
# `extensions` schema. Then the real deployment path runs: provision as that admin (next to a sibling
|
||||
# app holding same-named tables), migrate as the migrator, seed + the integration suite as the runtime
|
||||
# role, and the managed check (schema, roles, isolation, API roles). No TLS here — the service has
|
||||
# none; verify-full is exercised against a TLS-only emulation when the template is verified
|
||||
# (db/managed/README.md). It installs the pinned dredd-core, so it needs a release that ships
|
||||
# `dredd_core.managed provision` (v0.9.0 or later, which the template requires anyway).
|
||||
managed-db:
|
||||
runs-on: ubuntu-latest
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:17
|
||||
env:
|
||||
POSTGRES_PASSWORD: superpw
|
||||
ports: ["5432:5432"]
|
||||
options: >-
|
||||
--health-cmd "pg_isready -U postgres" --health-interval 5s
|
||||
--health-timeout 5s --health-retries 20
|
||||
env:
|
||||
# Database `postgres`, as at most providers. Throwaway CI passwords (16+ characters: provisioning refuses less).
|
||||
SUPERUSER_URL: postgresql+pg8000://postgres:superpw@localhost:5432/postgres
|
||||
ADMIN_PASSWORD: ci-managed-admin-4f9c2e71
|
||||
ADMIN_URL: postgresql+pg8000://postgres_managed:ci-managed-admin-4f9c2e71@localhost:5432/postgres
|
||||
AGORA_MIGRATOR_PASSWORD: ci-app-migrator-8d3b5a06
|
||||
AGORA_APP_PASSWORD: ci-app-runtime-2e7f9c14
|
||||
SIBLING_MIGRATOR_PASSWORD: ci-sibling-migrator-61a0d9
|
||||
SIBLING_APP_PASSWORD: ci-sibling-runtime-c47e22
|
||||
DATABASE_URL: postgresql+pg8000://agora_app:ci-app-runtime-2e7f9c14@localhost:5432/postgres
|
||||
MIGRATION_DATABASE_URL: postgresql+pg8000://agora_migrator:ci-app-migrator-8d3b5a06@localhost:5432/postgres
|
||||
DB_APP_ROLE: agora_app
|
||||
DATA_DIR: ${{ github.workspace }}/agora-data
|
||||
BOOTSTRAP_ADMIN_EMAIL: admin@example.com
|
||||
BOOTSTRAP_ADMIN_PASSWORD: adminpass1
|
||||
SEED_DEMO: "true"
|
||||
AGORA_RUN_INTEGRATION: "1"
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/setup-python@v6
|
||||
with: { python-version: "3.12" }
|
||||
- name: Authenticate to dredd-core
|
||||
env:
|
||||
TOKEN: ${{ secrets.DREDD_CORE_TOKEN }}
|
||||
run: |
|
||||
git config --global url."https://x-access-token:${TOKEN}@github.com/Alpaq92/dredd-core".insteadOf "https://github.com/Alpaq92/dredd-core"
|
||||
- name: Install deps
|
||||
working-directory: backend
|
||||
run: pip install -r requirements-dev.txt
|
||||
- name: db/managed/provision.sql is what dredd-core renders
|
||||
# The SQL-editor path must never drift from the provisioning routine: exit 1 = stale; re-render it
|
||||
# with --output instead of --check-file (db/managed/README.md).
|
||||
run: |
|
||||
python -m dredd_core.managed provision --sql-only \
|
||||
--schema agora --app-role agora_app --migrator-role agora_migrator \
|
||||
--check-file db/managed/provision.sql
|
||||
- name: Emulate a managed Postgres (TEST-ONLY)
|
||||
# The service is on localhost, so no --allow-remote (emulate refuses a non-local host without it).
|
||||
run: python -m dredd_core.managed emulate --superuser-url SUPERUSER_URL --database postgres --password-env ADMIN_PASSWORD
|
||||
- name: A sibling app next door, with same-named tables and types
|
||||
# Role names are cluster-wide and every app's core tables share names: this app's migration must
|
||||
# neither skip its own audit_log / app_user / node_role because a sibling has them, nor reach them.
|
||||
run: |
|
||||
python -m dredd_core.managed provision --admin-url ADMIN_URL \
|
||||
--schema sibling --app-role sibling_app --migrator-role sibling_migrator \
|
||||
--migrator-password-env SIBLING_MIGRATOR_PASSWORD --app-password-env SIBLING_APP_PASSWORD
|
||||
PGPASSWORD=superpw psql -h localhost -U postgres -d postgres -v ON_ERROR_STOP=1 <<'SQL'
|
||||
SET ROLE sibling_migrator;
|
||||
CREATE TABLE sibling.audit_log (id bigint PRIMARY KEY);
|
||||
CREATE TABLE sibling.app_user (id bigint PRIMARY KEY);
|
||||
CREATE TYPE sibling.node_role AS ENUM ('sibling_only');
|
||||
SQL
|
||||
- name: Provision Agora as the platform admin
|
||||
run: |
|
||||
python -m dredd_core.managed provision --admin-url ADMIN_URL \
|
||||
--schema agora --app-role agora_app --migrator-role agora_migrator \
|
||||
--migrator-password-env AGORA_MIGRATOR_PASSWORD --app-password-env AGORA_APP_PASSWORD
|
||||
- name: Migrate (as agora_migrator) + seed (as agora_app)
|
||||
# As the compose migrate service does: alembic uses MIGRATION_DATABASE_URL, the seed DATABASE_URL.
|
||||
working-directory: backend
|
||||
run: alembic upgrade head && python -m app.seed
|
||||
- name: Tests (as agora_app, DB_APP_ROLE=agora_app)
|
||||
working-directory: backend
|
||||
run: pytest -q
|
||||
- name: Managed check, as the runtime role and as the migrator (isolation included)
|
||||
# The evidence tables come from app.models, the lists 0002 was given (the CLI's own default is
|
||||
# audit_log alone). Unquoted on purpose: one argument per table, none for an empty list.
|
||||
working-directory: backend
|
||||
run: |
|
||||
append_only=$(python -c "from app.models import APPEND_ONLY_TABLES as t; print(*t)")
|
||||
no_delete=$(python -c "from app.models import NO_DELETE_TABLES as t; print(*t)")
|
||||
for url in DATABASE_URL MIGRATION_DATABASE_URL; do
|
||||
python -m dredd_core.managed check --url "$url" --expect-schema agora \
|
||||
--app-role agora_app --migrator-role agora_migrator \
|
||||
--append-only $append_only --no-delete $no_delete
|
||||
done
|
||||
- name: Everything is in schema agora, nothing in public, nothing shared with the sibling
|
||||
run: |
|
||||
PGPASSWORD=superpw psql -h localhost -U postgres -d postgres -v ON_ERROR_STOP=1 <<'SQL'
|
||||
DO $$
|
||||
BEGIN
|
||||
IF EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
|
||||
WHERE n.nspname = 'public' AND c.relkind IN ('r', 'p', 'v', 'm', 'S')) THEN
|
||||
RAISE EXCEPTION 'a relation was created in schema public';
|
||||
END IF;
|
||||
IF (SELECT count(*) FROM pg_tables WHERE schemaname = 'agora'
|
||||
AND tablename IN ('alembic_version', 'audit_log', 'app_user')) <> 3
|
||||
OR NOT EXISTS (SELECT 1 FROM pg_type t JOIN pg_namespace n ON n.oid = t.typnamespace
|
||||
WHERE n.nspname = 'agora' AND t.typname = 'node_role') THEN
|
||||
RAISE EXCEPTION 'alembic_version / audit_log / app_user / node_role are not in schema agora';
|
||||
END IF;
|
||||
IF has_schema_privilege('agora_app', 'sibling', 'USAGE')
|
||||
OR has_schema_privilege('agora_migrator', 'sibling', 'USAGE')
|
||||
OR has_schema_privilege('sibling_app', 'agora', 'USAGE')
|
||||
OR has_schema_privilege('sibling_migrator', 'agora', 'USAGE') THEN
|
||||
RAISE EXCEPTION 'an app role can use the other app''s schema';
|
||||
END IF;
|
||||
END $$;
|
||||
SQL
|
||||
- name: The cutover revision did nothing, because this app is standalone
|
||||
# 0003_shared_identity is a NO-OP unless IDENTITY_SCHEMA is set, and this job never sets it.
|
||||
# That is the hard rule of the whole design — a scaffolded app must run ALONE — so it is
|
||||
# asserted against a real database rather than trusted: the three identity tables are still
|
||||
# in this app's own schema, there is no shared schema anywhere, and the bootstrap admin the
|
||||
# seed created is still here to sign in with.
|
||||
run: |
|
||||
PGPASSWORD=superpw psql -h localhost -U postgres -d postgres -v ON_ERROR_STOP=1 <<'SQL'
|
||||
DO $$
|
||||
BEGIN
|
||||
IF (SELECT count(*) FROM pg_tables WHERE schemaname = 'agora'
|
||||
AND tablename IN ('app_user', 'session', 'module_permission')) <> 3 THEN
|
||||
RAISE EXCEPTION 'a standalone app must keep its own identity tables in its own schema';
|
||||
END IF;
|
||||
-- And 0004 left nothing of the pre-v0.11.0 shape behind. Here rather than in a unit
|
||||
-- test because the whole point of that revision is what a real database already holds.
|
||||
IF EXISTS (SELECT 1 FROM pg_tables WHERE schemaname = 'agora'
|
||||
AND tablename = 'module_moderator') THEN
|
||||
RAISE EXCEPTION 'the pre-v0.11.0 permission table is still here';
|
||||
END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM agora.app_user) THEN
|
||||
RAISE EXCEPTION 'the seed created no bootstrap administrator';
|
||||
END IF;
|
||||
END $$;
|
||||
SQL
|
||||
- name: Downgrade to base and upgrade again (as agora_migrator)
|
||||
working-directory: backend
|
||||
run: alembic downgrade base && alembic upgrade head
|
||||
|
||||
# ── the deployment itself ─────────────────────────────────────────────────────
|
||||
# The backend job runs the app from source on the runner. Nothing there executes
|
||||
# docker-compose.yml, the Dockerfile, the console served from the image or db/init — and the private dredd-core install
|
||||
# inside the image is exactly what broke unnoticed before. This job runs the real stack, the way a
|
||||
# deployer does. (Modelled on Sygna's compose-smoke job, which proved the approach.)
|
||||
compose-smoke:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
|
||||
- name: Write a .env the way a deployer would
|
||||
run: |
|
||||
cp .env.example .env
|
||||
sed -i \
|
||||
-e 's/change_me_super/ci-super-0f3a/g' \
|
||||
-e 's/change_me_app/ci-app-7c21/g' \
|
||||
-e 's/change_me_migrator/ci-migrator-94be/g' \
|
||||
-e 's/^BOOTSTRAP_ADMIN_PASSWORD=.*/BOOTSTRAP_ADMIN_PASSWORD=ci-admin-password-1/' \
|
||||
.env
|
||||
# Settings only: a comment that mentions change_me_* is not a placeholder.
|
||||
if grep -v '^[[:space:]]*#' .env | grep -q change_me; then echo "::error::a placeholder survived into .env"; exit 1; fi
|
||||
|
||||
- name: Build and start the stack
|
||||
env:
|
||||
DREDD_CORE_TOKEN: ${{ secrets.DREDD_CORE_TOKEN }}
|
||||
run: docker compose up -d --build
|
||||
|
||||
- name: Wait for readiness on the published backend
|
||||
# The backend starts only once migrate + seed completed — so one successful response proves
|
||||
# the whole ordering.
|
||||
run: |
|
||||
for i in $(seq 1 60); do
|
||||
if curl -fsS http://localhost/healthz >/dev/null 2>&1; then
|
||||
echo "ready after ~$((i * 5))s"; exit 0
|
||||
fi
|
||||
sleep 5
|
||||
done
|
||||
echo "::error::the stack never became ready"
|
||||
docker compose ps
|
||||
exit 1
|
||||
|
||||
- name: Drive it through the published backend
|
||||
run: |
|
||||
set -euo pipefail
|
||||
curl -fsS http://localhost/healthz
|
||||
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" || { echo "::error::no frame policy on the console"; exit 1; }
|
||||
curl -fsS http://localhost/ | grep -q "<title>Agora" || { echo "::error::console did not render"; exit 1; }
|
||||
token=$(curl -fsS -X POST http://localhost/api/v1/auth/login \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{"email":"admin@example.com","password":"ci-admin-password-1"}' | jq -r .token)
|
||||
[ -n "$token" ] && [ "$token" != "null" ] || { echo "::error::login returned no token"; exit 1; }
|
||||
curl -fsS -H "Authorization: Bearer $token" http://localhost/api/v1/auth/me >/dev/null
|
||||
code=$(curl -s -o /dev/null -w '%{http_code}' http://localhost/api/v1/auth/me)
|
||||
[ "$code" = "401" ] || { echo "::error::expected 401 without a session, got $code"; exit 1; }
|
||||
|
||||
- name: The least-privilege roles hold inside the container
|
||||
# `|| true` is load-bearing: psql exits non-zero when the database refuses the statement, and
|
||||
# a refusal is the SUCCESS case — without it `bash -e` aborts on the correct answer.
|
||||
run: |
|
||||
set -uo pipefail
|
||||
out=$(docker compose exec -T postgres psql -U app -d agora -c "UPDATE audit_log SET action = 'tampered'" 2>&1 || true)
|
||||
echo "$out"
|
||||
echo "$out" | grep -q "permission denied" || { echo "::error::the app role can rewrite the audit log"; exit 1; }
|
||||
|
||||
- name: Show every service's log if anything failed
|
||||
if: failure()
|
||||
run: docker compose logs --no-color
|
||||
|
||||
- name: Tear down
|
||||
if: always()
|
||||
run: docker compose down -v
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
.env
|
||||
*.pyc
|
||||
__pycache__/
|
||||
.venv/
|
||||
venv/
|
||||
.pytest_cache/
|
||||
.ruff_cache/
|
||||
.coverage
|
||||
htmlcov/
|
||||
*.egg-info/
|
||||
dist/
|
||||
build/
|
||||
data/
|
||||
.DS_Store
|
||||
certs/
|
||||
@@ -0,0 +1,304 @@
|
||||
# CLAUDE.md
|
||||
|
||||
Guidance for Claude Code when working in this repository.
|
||||
|
||||
## What this is
|
||||
|
||||
**Agora** — A self-hosted management console. Built on **dredd-core**, the shared substrate of this app family:
|
||||
identity, sessions, auth, the access-control resolver, the org tree, audit and the security
|
||||
primitives are an installed dependency, not source in this repo. Stack: **FastAPI + SQLAlchemy 2
|
||||
+ Alembic + PostgreSQL 16 / 17**, Argon2id auth + server-side cookie sessions, a
|
||||
**no-build static console** (vanilla JS), Docker Compose, with the backend as its own edge (`app/edge.py`, no reverse proxy). License **Apache-2.0**; every dependency is
|
||||
permissive (no copyleft).
|
||||
|
||||
The core is pinned by tag in `backend/requirements.txt`:
|
||||
|
||||
```
|
||||
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.22.0
|
||||
```
|
||||
|
||||
It is a **private** repository, so installing it needs a token — see `README.md` for the
|
||||
`DREDD_CORE_TOKEN` secret CI uses. Upgrading core means moving that tag deliberately: read the
|
||||
core changelog, bump the pin, run the tests.
|
||||
|
||||
This app is **its own deployment with its own data**. It shares *code* with its siblings, not
|
||||
domain data — locally its own database, in the family's shared managed database its own schema
|
||||
`agora` and roles that no sibling's roles can reach. That isolation stays.
|
||||
|
||||
**Identity is the exception, and it is one setting.** The family's shape is **one platform, one
|
||||
account, one admin pane**: one origin, one module per path, where a person signs in once at the hub
|
||||
and every module resolves the same session — separate schemas, one roster. "Separate databases"
|
||||
never meant "separate logins"; don't write that it did, and don't design a cross-origin token
|
||||
handoff for a topology that has one origin.
|
||||
|
||||
`IDENTITY_SCHEMA` is the whole switch, and it is **empty here**, which is STANDALONE: this app owns
|
||||
`app_user` / `session` / `module_permission` in its own schema, has its own sign-in screen and its own
|
||||
Users administration. That must keep working for ever — an app with its own database and its own
|
||||
people is a supported deployment, not a stage to grow out of. Set it and this app becomes a MODULE:
|
||||
those three tables live in a neutral schema the hub owns and this app READS, the sign-in form becomes
|
||||
a link to the hub, account writes answer 409, and app tokens stay listable and revocable but are
|
||||
minted there. **Both shapes are one code path**, switched at runtime — never two, or the one nobody
|
||||
runs locally is the one that breaks. `alembic/versions/0003_shared_identity.py` is the cutover and
|
||||
`.env.example` has the order the steps go in; `ROOT_PATH` (also empty here) is the separate switch
|
||||
that mounts this app under a path prefix.
|
||||
|
||||
Terminology, exactly these three words: **"administrator"** = platform-wide, **"moderator"** = this
|
||||
module only, **"user"** = may open this module and nothing more. A module guards its own
|
||||
administration with `deps.require_moderator` and defines **no administrator-only guard at all** —
|
||||
every power left in a module is module-scoped, so a route here held to the platform-wide tier would
|
||||
only lock a moderator out of the job they were given. Whether somebody may be here at all is asked
|
||||
once, in `deps.get_current_user`.
|
||||
|
||||
## Where things live
|
||||
|
||||
```
|
||||
dredd-core (installed) Base · NAMING_CONVENTION · UUIDPkMixin · TimestampMixin · SafeInet · pg_enum
|
||||
AppUser · Session · AppSetting · AuditLog · Node · PermissionGrant · Favorite
|
||||
dredd_core.enums NodeRole PrincipalType ReviewPolicy EncryptionMode
|
||||
SessionKind TokenScope
|
||||
dredd_core.errors AppError AuthenticationError AuthorizationError
|
||||
NotFoundError ConflictError ValidationError
|
||||
dredd_core.security hash_password verify_password generate_session_token
|
||||
hash_token derive_key generate_app_token
|
||||
token_display_prefix
|
||||
dredd_core.audit record
|
||||
dredd_core.authz effective_role assert_can_read assert_role
|
||||
users_with_role_at_least find_user_grant
|
||||
upsert_user_grant remove_user_grant
|
||||
list_grants_for_display grants_for_user
|
||||
access_state ancestor_paths ancestor_or_self_nodes
|
||||
readable_node_ids register_overlay clear_overlays
|
||||
dredd_core.auth AuthPolicy · AuthService
|
||||
dredd_core.db make_engine (TLS URL params) · make_session_factory
|
||||
strip_tls_params
|
||||
dredd_core.schema create_enum_types · runtime_grants_sql
|
||||
dredd_core.managed provision · check · emulate (TEST-ONLY) (python -m)
|
||||
|
||||
backend/app/
|
||||
main.py config.py db.py deps.py errors.py security.py enums.py schemas.py seed.py
|
||||
observability.py logging_config.py (db/errors/security/enums are shims)
|
||||
models/ __init__ (shim: re-exports core's AppUser/Session/ModulePermission/AppSetting/AuditLog
|
||||
[+ Node/PermissionGrant/Favorite in nodes tenancy])
|
||||
example (the demo entity — this app's own model)
|
||||
services/ auth · audit · moderation (shims over dredd_core)
|
||||
authz (nodes tenancy: shim over dredd_core.authz · simple: local moderator/owner rules)
|
||||
changes · settings · nodes · audit_log · example (this app's logic)
|
||||
(nodes: nodes tenancy only · audit_log: the read-only audit query)
|
||||
routers/ health auth users admin nodes example dashboard (nodes: nodes tenancy only)
|
||||
backend/tests/ unit (DB-free, always run) + integration (opt-in)
|
||||
backend/alembic/ env + 0001_initial (pgcrypto, create_enum_types, create_all)
|
||||
+ 0002_runtime_grants (runtime_grants_sql for DB_APP_ROLE; evidence tables in models/__init__)
|
||||
+ 0003_shared_identity (the cutover: merge this schema's accounts into the
|
||||
platform's, re-point every foreign key, drop the local copies — a NO-OP unless
|
||||
IDENTITY_SCHEMA is set, and refused on downgrade when it is)
|
||||
+ 0004_module_permission (dredd-core v0.11.0 renamed `module_moderator`; a database
|
||||
whose 0001 ran before that still has the old table, and 0001 never runs again —
|
||||
rename it, add `role`, or build it from the metadata, decided by the catalog)
|
||||
backend/scripts/ license_gate · deploy_check
|
||||
frontend/ index.html · app.css · app.js (no build step)
|
||||
Tabler icon path data vendored into app.js's ICN map (CREDITS.md)
|
||||
db/init/ 01-roles.sh (creates the app + migrator roles — local stack only)
|
||||
db/managed/ provision.sql (rendered by dredd-core; CI checks it) · README.md (managed-database runbook)
|
||||
docker-compose.yml · docker-compose.managed-db.yml · .env.example · .github/workflows/ci.yml
|
||||
```
|
||||
|
||||
**Strict one-way layering** — `routers/` (HTTP, validation, authz; never touches SQL) →
|
||||
`services/` (domain logic) → `models/` (ORM). Keep it.
|
||||
|
||||
## Commands
|
||||
|
||||
```bash
|
||||
DREDD_CORE_TOKEN=... docker compose up -d --build # full stack; the token is a BuildKit build secret —
|
||||
# shell only, never .env (containers load .env)
|
||||
cd backend && pytest # DB-free unit tests; integration auto-skips
|
||||
AGORA_RUN_INTEGRATION=1 pytest # full API loop (needs a migrated+seeded Postgres)
|
||||
alembic upgrade head --sql # inspect the DDL with no database
|
||||
python -m dredd_core.managed provision --sql-only --schema agora --app-role agora_app \
|
||||
--migrator-role agora_migrator --check-file ../db/managed/provision.sql # rendering current?
|
||||
python scripts/license_gate.py # CI license gate locally
|
||||
python scripts/deploy_check.py # compose/Dockerfile/.env coherence
|
||||
node --check frontend/app.js # ALWAYS after editing the console
|
||||
```
|
||||
|
||||
## Invariants — preserve these
|
||||
|
||||
- **NEVER add logic to a shim.** `models/__init__.py` (its core re-exports), `services/auth.py`,
|
||||
`services/authz.py` (`nodes` tenancy only — in `simple` it is local logic), `services/audit.py`,
|
||||
`db.py`, `errors.py`, `security.py` and `enums.py` exist so call sites keep their import paths.
|
||||
A shim may only: import from `dredd_core`, bind
|
||||
names (`authenticate = _service.authenticate`), declare app-only constants (the
|
||||
`agora_pat_` token prefix), wire this app's settings into a core policy object, and list
|
||||
`__all__`. Behaviour belongs in core: **change dredd-core, tag it, repin `requirements.txt`** —
|
||||
and only then use it here. A rule written into a shim is a rule the siblings don't get and the
|
||||
next core upgrade silently overwrites.
|
||||
- **Core is configured, not subclassed.** App-specific bits stay app-side and are passed in — e.g.
|
||||
`AuthPolicy(session_ttl_hours=..., app_token_prefix=APP_TOKEN_PREFIX)` built from
|
||||
`config.get_settings()`, the session cookie's name (`SESSION_COOKIE_NAME`), FastAPI exception
|
||||
handlers that render core's `AppError` as Problem Details. The platform shape is configuration too,
|
||||
not a fork: `identity_writes_enabled` / `local_login_enabled` on that same policy, and
|
||||
`ModerationPolicy(module_slug=..., shared_permissions=...)` in `services/moderation.py`, all derived
|
||||
from `settings.shares_identity`.
|
||||
- **Strict layering.** No `select(...)` / `db.add` / `db.execute` in a router. A lone
|
||||
`db.get(Model, id)` by primary key is acceptable. Services own every domain rule.
|
||||
- **`services/authz.py` is the only access authority.** In `nodes` tenancy it re-exports
|
||||
`dredd_core.authz` (`assert_can_read` / `assert_role`; list screens filter through
|
||||
`readable_node_ids`, not a per-row check). In `simple` tenancy it is a local module
|
||||
(`can_read` / `assert_can_read` / `assert_can_write` / `assert_moderator`, each taking the
|
||||
`Session` first, because the top of the model is now a tier the database answers rather than a
|
||||
column on the person). Call it before every read and write. **No access → 404, never 403** — the
|
||||
existence of a record can itself be privileged.
|
||||
- **Three words for what a person may do, and only these three.** ADMINISTRATOR is platform-wide
|
||||
(`app_user.is_admin`); MODERATOR administers exactly one module; USER may use exactly one module.
|
||||
The last two are one `module_permission` row the hub writes, and the fourth answer is **no row**,
|
||||
which is the default for everybody and means no access to this app at all.
|
||||
**That last one is the behaviour, not a detail**: `deps.get_current_user` calls
|
||||
`moderation.assert_may_use` right after the token-scope check, so every authenticated route is
|
||||
covered by one call and no new route can forget it. Without it somebody with a platform account
|
||||
reaches every screen here, sees nothing, can write nothing — and has been refused by nothing, which
|
||||
is the absence of an access decision rather than one. Keep that call unconditional: standalone,
|
||||
core answers `"user"` for everybody and emits no SQL, which is exactly what lets one guard serve
|
||||
both shapes.
|
||||
This app READS those rows and never writes them — `permission_writes_enabled` stays False, and the
|
||||
enforcement is the missing grant, not the router. Guard every administration route with
|
||||
`deps.require_moderator`, never with `is_admin`: a grep for `is_admin` under `app/routers/` should
|
||||
come back empty except where a response serialises it for display. Standalone, ADMINISTRATOR and
|
||||
MODERATOR are the same thing, everybody is a USER, and `services/moderation.py` answers without
|
||||
emitting a single query.
|
||||
`MODULE_SLUG` is what keys a permission row, and it is **not** always the same string as
|
||||
`agora`: a module slug is a URL path segment, so the hub's `module_permission` table holds
|
||||
it to `^[a-z0-9][a-z0-9-]{0,39}$` — hyphens yes, underscores no — while a schema name is the
|
||||
reverse. `config.py` refuses a slug that table would reject, and it has to, because this app only
|
||||
ever SELECTs by it: an illegal one raises nothing here, it simply makes the query match no row for
|
||||
ever — and no row is no access, so nobody but a platform administrator could open the app.
|
||||
- **A module reads identity; the hub writes it.** On a platform this app's runtime role holds a
|
||||
column-restricted `SELECT` on `app_user` (no `password_hash`), `SELECT` plus a three-column
|
||||
`UPDATE` on `session`, `SELECT` and nothing else on `module_permission`, and no `INSERT` anywhere —
|
||||
a role that could insert a `session` row could mint a working credential for the administrator, and
|
||||
one that could write `module_permission` could admit anyone, promote anyone and promote itself. The
|
||||
`AuthPolicy` / `ModerationPolicy` flags are the sentence at the edge (a clean 409 instead of a
|
||||
Postgres permission error dressed up as a 500); the grant is the enforcement. Never add a write
|
||||
path to accounts, sessions or permissions here, and never "fix" a permission error by widening the
|
||||
grant — the hub already has the route you want.
|
||||
- **Append-only audit.** Write through `dredd_core.audit.record`. The runtime role holds no
|
||||
UPDATE/DELETE/TRUNCATE on `audit_log` (enforced by `0002_runtime_grants`). `migrator` owns DDL; the
|
||||
runtime role is DML-only. This is a confidentiality control, not an ops convenience — never grant
|
||||
the runtime role DDL or audit mutation. Evidence tables are named once, in `models/__init__.py`
|
||||
(`APPEND_ONLY_TABLES` / `NO_DELETE_TABLES`); a table missing there is fully writable.
|
||||
- **Grants go through `runtime_grants_sql` and fail loudly.** `op.execute(runtime_grants_sql(
|
||||
get_settings().db_app_role, append_only=APPEND_ONLY_TABLES, no_delete=NO_DELETE_TABLES))` — never a
|
||||
hand-written GRANT block, never one that skips silently when a role is missing. It refuses to run as
|
||||
a superuser or the platform admin, raises when the role is missing or a grant did not take, and
|
||||
strips the API roles (`anon` / `authenticated` / `service_role`, what a provider's auto-generated
|
||||
table API connects as). **Every revision that creates a table ends with that call**
|
||||
(`GRANT ... ON ALL TABLES` only covers the tables that exist when it runs).
|
||||
- **Role names are configuration, per app.** The runtime role is `DB_APP_ROLE` (`app` locally and in
|
||||
CI, `agora_app` in the shared managed database, next to `agora_migrator`) — role names
|
||||
are cluster-wide there, and generic names would let one app undo another's revokes. Nothing else in
|
||||
the app names a role.
|
||||
- **Own schema, never `public`, nothing schema-qualified.** In the shared database `agora` is
|
||||
owned by the migrator and first on both roles' `search_path` (set by `python -m dredd_core.managed
|
||||
provision`), so `alembic_version`, enum types and tables all land there. Don't qualify names in
|
||||
code or migrations; `create_all`'s checkfirst and `create_enum_types` then only see this app's schema.
|
||||
- **Never migrate as `postgres`** (or any superuser / platform admin): objects would be owned by it,
|
||||
and `0002` refuses. Migrations run as the migrator only; on a managed database the long-running
|
||||
backend gets no migrator credentials (`docker-compose.managed-db.yml` blanks them — an in-app restore
|
||||
would be an explicit, documented opt-in; prefer a one-shot container).
|
||||
- **One TLS rule, from core.** `config.py` applies `dredd_core.db.require_verified_tls` to both URLs:
|
||||
a database host counts as local when it is `""`, `localhost`, `127.0.0.1`, `::1`, `postgres` or
|
||||
listed in `DB_LOCAL_HOSTS` (comma-separated, optional); every other host must carry
|
||||
`sslmode=verify-full` (with `sslrootcert`, or the system trust store) or the app refuses to start.
|
||||
No provider host lists, no other opt-out — don't add one.
|
||||
- **TLS only through `make_engine`.** Every engine — runtime, Alembic (`make_engine(url,
|
||||
poolclass=NullPool)` online, `strip_tls_params(url)` offline), seed and any script — goes through
|
||||
`dredd_core.db.make_engine`, never `create_engine`: pg8000 ignores libpq's `sslmode` and silently
|
||||
falls back to plaintext. One-shot processes use `NullPool`; the backend's pool comes from
|
||||
`DB_POOL_SIZE` / `DB_MAX_OVERFLOW` (the shared database's connection limit is shared by every app).
|
||||
`alembic/env.py` never passes the URL through `config.set_main_option` (its `%`-interpolation breaks
|
||||
percent-encoded passwords).
|
||||
- **A pooler's session mode, never its transaction mode.** Through a provider's pooler use session
|
||||
mode (port 5432 on the poolers the family knows) or the direct host — never a transaction-mode port
|
||||
(6543 there). Some poolers want the tenant in the user name: `<role>.<tenant>`, and `DB_APP_ROLE` is
|
||||
the part before the dot. `deploy_check` fails on 6543, on a non-verify-full URL and on a `postgres`
|
||||
user.
|
||||
- **PostgreSQL 16 and 17.** The local stack runs 16, managed providers commonly run 17; CI runs the
|
||||
suite on both, and `managed-db` rehearses the shared-database path on 17.
|
||||
- **dredd-core ships models, not migrations.** Importing `dredd_core` registers the identity *and*
|
||||
org-tree tables on the shared `Base.metadata`; this app owns its `0001`. Because core's enum
|
||||
columns are declared with `create_type=False`, the native types must exist first:
|
||||
`create_enum_types(conn)` (core's enums plus this app's own, once its models are imported) →
|
||||
`Base.metadata.create_all(conn)`, then `0002`'s grants. **Adding a model or an enum needs no change to
|
||||
`0001`** — both are read off the metadata; `tests/test_migration_parity.py` guards that the model
|
||||
is imported. A database migrated *before* the model existed still needs a new revision for it.
|
||||
- **Every revision after `0001` must be idempotent** (`checkfirst=True`, `IF [NOT] EXISTS`, catalog
|
||||
checks): `0001` builds from the live metadata, so on a fresh database it already has the current
|
||||
shape and a plain `op.create_table` there fails. And **never change what `0001` creates without a
|
||||
follow-up revision** for databases migrated before — editing `0001` alone changes fresh installs
|
||||
and silently leaves every existing database behind. That is exactly how Galena's `node_kind`
|
||||
(native enum → text) broke existing databases. A table a later revision creates must also be
|
||||
granted there — end the revision with the same `runtime_grants_sql(...)` call as `0002` (and name
|
||||
the table in `APPEND_ONLY_TABLES` / `NO_DELETE_TABLES` first if it is evidence).
|
||||
- **A core upgrade can change the schema.** If a repin adds or alters a core table, write a new
|
||||
revision in this repo for it — core tags describe models, they do not migrate your database.
|
||||
- **Every model must be imported in `models/__init__.py`** or it silently never gets a table.
|
||||
- **(`nodes` tenancy) A leaf node and its domain row are created together**, in one transaction,
|
||||
by a domain service — never by the nodes router. A leaf without its row is an orphan the authz
|
||||
resolver can see but nothing can use.
|
||||
- **Sessions are server-side**, so logout/deactivate is an instant kill-switch. Deactivating a
|
||||
user must also revoke their sessions. Sessions live in *this* app's own tables only.
|
||||
- **Token scope is enforced in `deps.get_current_user` and nowhere else.** Every authenticated
|
||||
route depends on it, so one check covers all of them and no future route can forget it.
|
||||
- **Cookie-authenticated writes must be same-origin** — `deps.refuse_cross_site_write`, registered
|
||||
once as an app-wide dependency in `main.py`, so login, logout and every future route are covered.
|
||||
SameSite=Lax does not stop a same-site sibling app on another subdomain; the guard checks
|
||||
`Sec-Fetch-Site`, and `Origin` against `Host` where browsers omit the former (plain HTTP, older
|
||||
Safari). Bearer requests and `CORS_ALLOW_ORIGINS` entries are trusted. Deployed under a path prefix
|
||||
of a shared origin this guard separates the platform from foreign sites only, **never one module
|
||||
from another** — a page at `/sibling` is same-origin with this app, so both signals pass. That is
|
||||
what one account wants; don't "restore" a guard that cannot work there. The consequence is that an
|
||||
XSS in any console on that origin can drive every module's API with the user's cookie, which makes
|
||||
"untrusted bytes never execute in-origin" a platform-wide guarantee rather than a local one. And
|
||||
never add an entry to `CORS_ALLOW_ORIGINS` once the family shares an origin — `deps.py` returns
|
||||
early for any listed origin, bypassing both signals.
|
||||
- **Settings are a closed, typed set** (`services/settings.SPECS`). Add a key there with its type and
|
||||
bounds; never reintroduce an endpoint that writes any key it is given.
|
||||
- **Bad input is a 422, never a 500.** Type path ids as `uuid.UUID` and vocabularies as their enum in
|
||||
the schema, so FastAPI refuses them before a service builds a query or an enum from raw text.
|
||||
`tests/test_integration.py` holds this floor — extend it for the real domain, don't delete it.
|
||||
- **`None` means "not supplied", never "blank it"** in a partial update. Keep an explicit list of
|
||||
clearable fields if a user must be able to empty something.
|
||||
- **Errors are RFC 9457 Problem Details**; raise `dredd_core.errors` types from services, render
|
||||
them in one handler. Stack traces hidden when `APP_ENV=production`.
|
||||
- **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).
|
||||
- **Brand = Open Color `red` `#e03131`**, confined to identity — the app mark, icon
|
||||
tiles, the avatar, the focus ring. Buttons, nav and toolbar glyphs stay monochrome; brand
|
||||
everything and nothing stands out. Semantic ok/warn/err is a separate axis.
|
||||
- **Core stays permissive.** Apache-2.0; CI denies GPL/AGPL/SSPL. Copyleft or heavyweight
|
||||
components are optional sidecars, never core.
|
||||
- **No build step for the console.**
|
||||
|
||||
## Gotchas
|
||||
|
||||
- **Installing needs credentials.** `dredd-core` lives in a private repo; `pip install -r
|
||||
requirements.txt` fails with an authentication error unless git can reach it (CI uses the
|
||||
`DREDD_CORE_TOKEN` secret; locally, your own GitHub credentials).
|
||||
- **Tenancy `simple`:** importing `dredd_core` registers `node`, `permission_grant` and `favorite`
|
||||
regardless, so a flat single-tenant app still creates those three tables. They stay empty and
|
||||
unused — that is expected, not a bug. Don't try to suppress them.
|
||||
- **Some poolers want `<role>.<tenant>` logins**, and some providers ban the client IP for a while
|
||||
after a few wrong passwords in a row — nothing retries a failed migration on purpose. Percent-encode
|
||||
passwords in URLs. The managed-database runbook is `db/managed/README.md`.
|
||||
- On Windows, write `.env` **without a BOM** (PowerShell's `Out-File -Encoding utf8` adds one,
|
||||
and pydantic-settings folds it into the first key name) — use
|
||||
`[System.IO.File]::WriteAllText(...)`.
|
||||
- **Syntax-check the console after editing it**: `node --check frontend/app.js`. A duplicate
|
||||
`const` inside one function silently stops the whole file parsing, so every function defined
|
||||
after it disappears — and the symptom is a screen that renders nothing, with no console error.
|
||||
- Never transition `visibility` over a duration or with a delay; the off-canvas drawer gets stuck
|
||||
when frames are throttled. `transform` transitions; `visibility` flips instantly.
|
||||
- Name model modules so they cannot shadow a stdlib module (`timelog.py`, not `time.py`).
|
||||
|
||||
## Status
|
||||
|
||||
Scaffolded skeleton on dredd-core v0.22.0. The `example` entity (`Record`) is a worked seam —
|
||||
model → migration → service → router → console screen — to copy for the real domain, then delete.
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
# Credits
|
||||
|
||||
Agora is Apache-2.0. Every shipped dependency is permissively licensed — the CI license
|
||||
gate (`backend/scripts/license_gate.py`) fails the build on GPL, AGPL or SSPL.
|
||||
|
||||
## Runtime dependencies
|
||||
|
||||
| Project | License | Why |
|
||||
|---|---|---|
|
||||
| [FastAPI](https://fastapi.tiangolo.com) | MIT | the API framework |
|
||||
| [Starlette](https://www.starlette.io) | BSD-3-Clause | ASGI toolkit under FastAPI |
|
||||
| [Uvicorn](https://www.uvicorn.org) | BSD-3-Clause | ASGI server |
|
||||
| [python-multipart](https://github.com/Kludex/python-multipart) | Apache-2.0 | multipart/form-data parsing for FastAPI |
|
||||
| [Pydantic](https://docs.pydantic.dev) / pydantic-settings | MIT | validation + typed settings |
|
||||
| [SQLAlchemy](https://www.sqlalchemy.org) | MIT | ORM |
|
||||
| [Alembic](https://alembic.sqlalchemy.org) | MIT | migrations |
|
||||
| [pg8000](https://github.com/tlocke/pg8000) | BSD-3-Clause | pure-Python PostgreSQL driver — no libpq, no LGPL |
|
||||
| [argon2-cffi](https://github.com/hynek/argon2-cffi) | MIT | Argon2id password hashing |
|
||||
| [httpx](https://www.python-httpx.org) | BSD-3-Clause | the one outbound HTTP client |
|
||||
| [OpenTelemetry Python](https://opentelemetry.io) | Apache-2.0 | optional tracing, off by default |
|
||||
| [PostgreSQL](https://www.postgresql.org) | PostgreSQL License | the database |
|
||||
|
||||
## Console
|
||||
|
||||
| Project | License | Why |
|
||||
|---|---|---|
|
||||
| [Open Color](https://yeun.github.io/open-color/) | MIT | the colour palette, light and dark |
|
||||
| [Tabler Icons](https://tabler.io/icons) | MIT | outline icon set — path data is **vendored** into `frontend/app.js`'s `ICN` map, never loaded from a CDN, because the console's CSP allows no third-party origins |
|
||||
|
||||
No framework, no bundler, no CDN: the console is `index.html` + `app.css` + `app.js`.
|
||||
|
||||
## Design credit
|
||||
|
||||
The console's shape — grouped sidebar navigation, data tables with row actions, full-page create
|
||||
forms with edit modals, dashboard tiles, a command palette — is **inspired by
|
||||
[Open Mercato](https://github.com/open-mercato/open-mercato)**. It is an homage, not a copy or a
|
||||
fork: no Open Mercato code is included, and small deviations are intentional.
|
||||
|
||||
Identity, sessions, auth, authz, the org tree and the append-only audit log come from
|
||||
**dredd-core**, the family's shared package (Apache-2.0), pinned in `backend/requirements.txt`.
|
||||
The least-privilege database model (`app` DML / `migrator` DDL) follows it.
|
||||
@@ -0,0 +1,189 @@
|
||||
# Agora
|
||||
|
||||
A self-hosted management console.
|
||||
|
||||
Self-hosted and single-tenant, built on **dredd-core** — the shared substrate this app family
|
||||
installs as a dependency rather than copies.
|
||||
|
||||
## Stack
|
||||
|
||||
**FastAPI + SQLAlchemy 2 + Alembic + PostgreSQL 16 / 17**, Argon2id password hashing, server-side
|
||||
cookie sessions, an append-only audit log enforced by database grants, RFC 9457 Problem Details
|
||||
errors, opt-in OpenTelemetry, and a **no-build vanilla-JS console** (Open Color palette, Tabler
|
||||
icons, light/dark theme, two languages). Shipped with Docker Compose; the backend is its own edge (no reverse proxy). Apache-2.0, and CI
|
||||
refuses any GPL/AGPL/SSPL dependency.
|
||||
|
||||
## dredd-core
|
||||
|
||||
Identity and sessions, authentication, the access-control resolver, the org tree, the audit
|
||||
writer, the security primitives, the shared enums and error types, and the engine/session
|
||||
factories all come from one installed package. `backend/requirements.txt` pins it by tag:
|
||||
|
||||
```
|
||||
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.22.0
|
||||
```
|
||||
|
||||
The app-side files that used to hold that code (`services/auth.py`, `models/__init__.py`,
|
||||
`security.py`, `errors.py`, … and, in `nodes` tenancy, `services/authz.py`) are now **thin shims**:
|
||||
they re-export from `dredd_core` so every call site keeps its import path, and they hold only what
|
||||
is genuinely this app's — the `agora_pat_` token prefix, the `agora_session` cookie,
|
||||
the settings fed into core's auth policy. Fixing shared behaviour means changing dredd-core, tagging
|
||||
a release and moving the pin here — never patching a shim.
|
||||
|
||||
dredd-core ships **models, not migrations**: importing it registers its tables on the shared
|
||||
metadata, and this repo owns its own `0001` (native enum types are created first, then
|
||||
`create_all`). A core upgrade that changes the schema needs a new revision here.
|
||||
|
||||
**It is a private repository.** Local installs use your own GitHub credentials; CI authenticates
|
||||
with a `DREDD_CORE_TOKEN` repository secret (a fine-grained PAT with read access to
|
||||
`Alpaq92/dredd-core`), which the workflow injects before `pip install`. Without it, the install
|
||||
step fails with an authentication error.
|
||||
|
||||
This app is its own deployment with its own domain data. It shares code with its siblings, not that
|
||||
data: locally it has its own database; in the family's shared managed database it has its own schema
|
||||
and roles, which no sibling's roles can reach.
|
||||
|
||||
Identity is the exception, and it is shared on purpose: the family's shape is **one platform, one
|
||||
account, one admin pane** — one origin, one module per path, where you sign in once at the hub and
|
||||
every module resolves the same session. Separate schemas, one roster. As scaffolded this app is
|
||||
**standalone**: it serves at the root of its own host with its own accounts, its own sign-in and its
|
||||
own Users administration, and it keeps running that way whatever the family does. Mounting it under
|
||||
a path prefix of a shared origin is one setting (`ROOT_PATH`, empty by default) and no code change.
|
||||
|
||||
### Joining the platform
|
||||
|
||||
Sharing the roster is one more setting, `IDENTITY_SCHEMA`, plus three steps that are not this app's
|
||||
to take. Once it is set, `app_user`, `session` and `module_permission` live in a neutral schema the
|
||||
hub owns and this app **reads**: there is no password here, the sign-in screen becomes a link to the
|
||||
hub, creating or re-passwording an account answers 409 pointing there, and app tokens stay listable
|
||||
and revocable but are minted at the hub. And `module_permission` is what decides who may open this
|
||||
app at all — **no row for this module is no entry** — so the hub is where somebody is admitted to it
|
||||
and where somebody is made its moderator. Standalone that table is inert: there is one application,
|
||||
and having an account here is permission to use it. One origin means one cookie, so there is no handoff to
|
||||
build — no signed assertion, no audience binding, nothing to exchange. A design that adds one for
|
||||
this topology is over-engineering.
|
||||
|
||||
Both shapes are the same code, switched at runtime, and that is the property to defend: the moment
|
||||
they fork, the shape nobody runs locally is the shape that breaks.
|
||||
|
||||
The order matters, because only the last of the four steps happens in this repository:
|
||||
|
||||
1. **The platform admin provisions.** `db/managed/provision.sql`, re-rendered with
|
||||
`--identity-schema dredd --identity-owner atrium_migrator` (commit it, and add the same flags to
|
||||
CI's `--check-file` step — the platform's `push.sh` refuses a module whose committed file is not
|
||||
that rendering): the schema, `USAGE` for this app's two roles, and a `search_path` that reaches
|
||||
it. A migrator role may do none of those. The kit also sets `FRAME_ANCESTORS='self'`.
|
||||
2. **The hub migrates.** It owns the schema, so it creates the three tables and grants this app's
|
||||
roles their tier — a column-restricted `SELECT` on `app_user` that does not include
|
||||
`password_hash`, `SELECT` plus a narrow `UPDATE` on `session`, `SELECT` and nothing else on
|
||||
`module_permission`, and `INSERT` on none of them.
|
||||
3. **A person imports any account this app has and the hub does not.** Neither side can do it alone,
|
||||
by design, so it is a platform-admin step run from a census of every schema's `app_user`.
|
||||
4. **`alembic upgrade head` here** runs `0003_shared_identity`: it matches this schema's accounts to
|
||||
the shared ones by e-mail address, rewrites every id that names a person, re-points every foreign
|
||||
key, and drops the local copies. Read it before running it on anything you care about. Sessions
|
||||
and app tokens are deliberately not carried over — everybody signs in once more, at the hub.
|
||||
|
||||
Two administration tiers come with it, and these are the only two words for them: an
|
||||
**administrator** is platform-wide and is made in the hub; a **moderator** administers this module
|
||||
only, is also made in the hub, and is merely read here. Standalone they are the same thing and
|
||||
nothing queries anything.
|
||||
|
||||
## Quick start
|
||||
|
||||
```bash
|
||||
cp .env.example .env # then set the three DB passwords
|
||||
DREDD_CORE_TOKEN=github_pat_... docker compose up -d --build # postgres -> migrate(+seed) -> backend
|
||||
```
|
||||
|
||||
> **Building the image needs `DREDD_CORE_TOKEN`** (a read-only fine-grained PAT for
|
||||
> `Alpaq92/dredd-core`) in your **shell** — compose hands it to the build as a BuildKit secret, so it
|
||||
> never lands in an image layer. Don't put it in `.env`: every container loads that file at runtime.
|
||||
> CI's `compose-smoke` job runs exactly this stack on every push.
|
||||
|
||||
Open <http://localhost> and sign in with `BOOTSTRAP_ADMIN_EMAIL` / `BOOTSTRAP_ADMIN_PASSWORD`.
|
||||
|
||||
> **Windows:** write `.env` without a BOM —
|
||||
> `[System.IO.File]::WriteAllText("$PWD\.env", (Get-Content .env.example -Raw))`.
|
||||
> PowerShell's `Out-File -Encoding utf8` adds one, and pydantic-settings folds it into the first
|
||||
> key name, which produces a baffling "field required" error at startup.
|
||||
|
||||
## Development
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
python -m venv .venv && . .venv/Scripts/activate # or: source .venv/bin/activate
|
||||
pip install -r requirements-dev.txt # pulls dredd-core from GitHub — needs repo access
|
||||
|
||||
pytest # DB-free unit tests
|
||||
alembic upgrade head --sql # inspect the DDL without a database
|
||||
python scripts/license_gate.py # no GPL/AGPL/SSPL
|
||||
python scripts/deploy_check.py # stack-definition coherence
|
||||
node --check ../frontend/app.js # the console has no build step, so this is the check
|
||||
```
|
||||
|
||||
The API is served under `/api/v1`, with OpenAPI docs at `/api/v1/docs`.
|
||||
|
||||
## Deploying on a managed PostgreSQL
|
||||
|
||||
The Dredd family can run in **one shared managed database** (one PostgreSQL 16/17 database at a managed
|
||||
provider), with Atrium as the hub; Agora joins it as schema `agora` with its own roles
|
||||
`agora_migrator` and `agora_app`. The provider hosts only the database — the backend still
|
||||
runs on your server, with `docker compose -f docker-compose.yml -f docker-compose.managed-db.yml up -d
|
||||
--build`. The same path works against any PostgreSQL 16/17 whose admin may create roles and schemas.
|
||||
|
||||
- **Database-wide steps** (creating the database, the provider's root CA, keeping the schemas out of
|
||||
any auto-generated API, TLS enforcement, network restrictions, the connection budget, backups and
|
||||
point-in-time restore): step 0 of [`db/managed/README.md`](db/managed/README.md), and in more depth
|
||||
the family runbook in Atrium,
|
||||
[`deploy/README.md`](https://github.com/Alpaq92/Atrium/blob/main/deploy/README.md).
|
||||
- **Agora's steps** (provisioning with `python -m dredd_core.managed provision` or the rendered
|
||||
[`db/managed/provision.sql`](db/managed/provision.sql), `.env` with `DB_APP_ROLE` and the pool knobs,
|
||||
migrate + seed, `python -m dredd_core.managed check`, restore specifics):
|
||||
[`db/managed/README.md`](db/managed/README.md).
|
||||
- Connect through the provider's pooler in **session mode** (never a transaction-mode port such as
|
||||
6543) or directly, as `<role>` — or `<role>.<tenant>` where the pooler wants the tenant in the user
|
||||
name — with `?sslmode=verify-full&sslrootcert=/run/certs/db-ca.crt`. Never migrate as `postgres`.
|
||||
- **The TLS rule:** a database host that is not local (`""`, `localhost`, `127.0.0.1`, `::1`, `postgres`
|
||||
or a `DB_LOCAL_HOSTS` entry) must carry `sslmode=verify-full`, or the app refuses to start.
|
||||
|
||||
CI's `managed-db` job rehearses this path on PostgreSQL 17 without a superuser: it emulates a managed
|
||||
Postgres (`python -m dredd_core.managed emulate`), provisions the app next to a sibling, migrates, runs
|
||||
the integration suite as `agora_app` and runs the managed check.
|
||||
|
||||
## Security model
|
||||
|
||||
Two Postgres roles do the heavy lifting. `migrator` owns DDL and is used only by Alembic; `app`
|
||||
is the runtime role and holds DML only. The migration then revokes `UPDATE`/`DELETE` on
|
||||
`audit_log` from `app`, which is what makes the audit log evidence rather than a convenience: a
|
||||
compromised application cannot rewrite its own history, because the database will not let it.
|
||||
|
||||
The runtime role's name is configuration (`DB_APP_ROLE`, `app` by default): the grants migration
|
||||
(`0002_runtime_grants`) grants to it and **fails loudly** — rolling back — when that role is missing,
|
||||
when it runs as a superuser or the platform admin, or when a grant did not take. Migrations run as the
|
||||
migrator and nothing else.
|
||||
|
||||
Only the backend is published to the host (:80) — it serves the console and sets every security
|
||||
header itself (`backend/app/edge.py`); Postgres is `expose`-only. There is no reverse proxy.
|
||||
|
||||
Access control lives in exactly one module, `backend/app/services/authz.py` — a re-export of
|
||||
`dredd_core.authz` in `nodes` tenancy, a local admin/owner check in `simple` tenancy. No access
|
||||
returns **404, not 403**: a 403 confirms that the record the caller may not see exists.
|
||||
|
||||
## Project layout
|
||||
|
||||
| Path | What |
|
||||
|---|---|
|
||||
| `backend/app/models/` | this app's ORM entities; `__init__.py` re-exports dredd-core's |
|
||||
| `backend/app/services/` | every domain rule and all SQL; `auth`/`audit` are core shims (`authz` too, in `nodes` tenancy) |
|
||||
| `backend/app/routers/` | HTTP shape, validation, authz calls — no SQL |
|
||||
| `backend/alembic/` | `0001`: enum types → `create_all`; `0002`: runtime grants for `DB_APP_ROLE` |
|
||||
| `backend/scripts/` | license gate, deploy pre-flight |
|
||||
| `frontend/` | the console: `index.html` + `app.css` + `app.js`, no bundler |
|
||||
| `db/init/` | least-privilege role creation for the local stack, run once by Postgres |
|
||||
| `db/managed/` | the shared managed database: rendered `provision.sql` + this app's runbook |
|
||||
| `docker-compose.managed-db.yml` | override for a managed database: no local postgres, CA mounted, no migrator in the backend |
|
||||
|
||||
## License
|
||||
|
||||
Apache-2.0. See [`CREDITS.md`](CREDITS.md) for dependencies and design credits.
|
||||
@@ -0,0 +1,10 @@
|
||||
# Keep the build context small and Linux-clean (a local venv holds host binaries), and keep
|
||||
# credentials out of `COPY . .`.
|
||||
.venv/
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
.pytest_cache/
|
||||
*.egg-info/
|
||||
.coverage
|
||||
.env
|
||||
.env.*
|
||||
@@ -0,0 +1,69 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
|
||||
# ── build stage: resolve dependencies, including the private one ─────────────
|
||||
# `dredd-core` is a private GitHub repository pinned by tag in requirements.txt, so installing it
|
||||
# needs two things the runtime image should never have: `git`, and a credential.
|
||||
#
|
||||
# The credential arrives as a BuildKit SECRET, not a build argument. A build arg is baked into the
|
||||
# image history — `docker history` prints it — so a pushed image would publish the token to anyone
|
||||
# who can pull it. A secret mount exists only for the duration of the one RUN that uses it.
|
||||
# `GIT_CONFIG_*` scopes the rewrite to that same process, so nothing is written to a gitconfig
|
||||
# that could survive into a layer either.
|
||||
#
|
||||
# Build with: DREDD_CORE_TOKEN=... docker compose build (compose passes it as the secret)
|
||||
# (The same build as Sygna's, which its CI runs end to end.)
|
||||
FROM python:3.12-slim AS build
|
||||
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends git \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
WORKDIR /build
|
||||
COPY requirements.txt .
|
||||
# `required=true` only fails when the secret is ABSENT — compose passes an unset DREDD_CORE_TOKEN as
|
||||
# an EMPTY secret, which would otherwise surface much later as a confusing git auth error. Hence the
|
||||
# `test -s`. `tr -d` drops a stray CR/LF from a pasted token (git would echo a key containing one).
|
||||
RUN --mount=type=secret,id=dredd_core_token,required=true \
|
||||
test -s /run/secrets/dredd_core_token \
|
||||
|| { echo "build secret dredd_core_token is empty - export DREDD_CORE_TOKEN" >&2; exit 1; }; \
|
||||
GIT_CONFIG_COUNT=1 \
|
||||
GIT_CONFIG_KEY_0="url.https://x-access-token:$(tr -d '\r\n' < /run/secrets/dredd_core_token)@github.com/.insteadOf" \
|
||||
GIT_CONFIG_VALUE_0="https://github.com/" \
|
||||
pip install --no-cache-dir --prefix=/install -r requirements.txt
|
||||
|
||||
# ── runtime stage: no git, no credential, no compiler ────────────────────────
|
||||
FROM python:3.12-slim
|
||||
|
||||
COPY --from=build /install /usr/local
|
||||
|
||||
WORKDIR /app
|
||||
COPY . .
|
||||
|
||||
# The static console, which this backend serves itself (app/main.py mounts it at "/"; there is no
|
||||
# reverse proxy). 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 .`.
|
||||
COPY --from=frontend . /frontend
|
||||
ENV AGORA_FRONTEND_DIR=/frontend
|
||||
|
||||
RUN useradd -m app && mkdir -p /data && chown -R app /data /app
|
||||
ENV DATA_DIR=/data
|
||||
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)"
|
||||
# The backend is the edge: docker-compose.yml publishes it directly, with no reverse proxy. So
|
||||
# X-Forwarded-For is trusted only from 127.0.0.1 by default — anything else is a client's claim, and
|
||||
# the audit log records the peer address. On the Dredd platform set FORWARDED_ALLOW_IPS to the
|
||||
# front door's (Atrium backend's) address, never `*`.
|
||||
# The path prefix the platform's front door strips before the request reaches us. Empty (the
|
||||
# default) is the standalone stack, served at the origin root; ROOT_PATH=/agora mounts this app
|
||||
# under a path prefix of a shared origin. uvicorn PREPENDS it to the incoming path, so it pairs with
|
||||
# the front door forwarding `/agora/*` with the prefix stripped: set one without the other and you get either a doubled
|
||||
# prefix (404 everywhere) or server-generated URLs that escape the prefix. app/config.py reads the
|
||||
# same variable, so FastAPI's root_path agrees. The healthcheck below needs no prefix — uvicorn
|
||||
# prepends, Starlette strips, so the un-prefixed path still matches the route either way.
|
||||
ENV ROOT_PATH=
|
||||
# --no-server-header: nothing stands in front of uvicorn, so it must not announce itself.
|
||||
CMD ["sh", "-c", "exec uvicorn app.main:app --host 0.0.0.0 --port 8000 --proxy-headers --forwarded-allow-ips \"${FORWARDED_ALLOW_IPS:-127.0.0.1}\" --root-path \"$ROOT_PATH\" --no-server-header"]
|
||||
@@ -0,0 +1,40 @@
|
||||
[alembic]
|
||||
script_location = alembic
|
||||
prepend_sys_path = .
|
||||
# The URL is set in alembic/env.py from MIGRATION_DATABASE_URL (the DDL `migrator` role), so it
|
||||
# is deliberately absent here — a URL in this file would be a credential in version control and
|
||||
# would silently win over the environment.
|
||||
|
||||
[loggers]
|
||||
keys = root,sqlalchemy,alembic
|
||||
|
||||
[handlers]
|
||||
keys = console
|
||||
|
||||
[formatters]
|
||||
keys = generic
|
||||
|
||||
[logger_root]
|
||||
level = WARNING
|
||||
handlers = console
|
||||
qualname =
|
||||
|
||||
[logger_sqlalchemy]
|
||||
level = WARNING
|
||||
handlers =
|
||||
qualname = sqlalchemy.engine
|
||||
|
||||
[logger_alembic]
|
||||
level = INFO
|
||||
handlers =
|
||||
qualname = alembic
|
||||
|
||||
[handler_console]
|
||||
class = StreamHandler
|
||||
args = (sys.stderr,)
|
||||
level = NOTSET
|
||||
formatter = generic
|
||||
|
||||
[formatter_generic]
|
||||
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||
datefmt = %H:%M:%S
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Alembic environment — uses MIGRATION_DATABASE_URL (the DDL `migrator` role).
|
||||
|
||||
Online, the engine comes from `dredd_core.db.make_engine`, never `create_engine`: a managed Postgres
|
||||
(the family's shared managed database) URL carries libpq's `?sslmode=verify-full&sslrootcert=...`, and
|
||||
pg8000 has no sslmode of its own — handed to it directly the parameters fail the connection, and left
|
||||
out, pg8000 silently falls back to plaintext. `make_engine` turns them into a verifying TLS context.
|
||||
Offline (`alembic upgrade head --sql`) nothing connects, so the TLS parameters are stripped and the CA
|
||||
file they name does not have to exist on the machine rendering the SQL.
|
||||
|
||||
Where the tables land is the migrator's business, not this file's: nothing is schema-qualified, so
|
||||
`alembic_version`, the enum types and every table go to the first schema on the role's search_path —
|
||||
`public` locally, `agora` in the shared database, where provisioning sets that path.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from logging.config import fileConfig
|
||||
from pathlib import Path
|
||||
|
||||
from sqlalchemy import pool
|
||||
from sqlalchemy.engine import make_url
|
||||
from sqlalchemy.exc import ArgumentError
|
||||
|
||||
from alembic import context
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1])) # put backend/ on sys.path
|
||||
|
||||
from dredd_core.db import make_engine, strip_tls_params # noqa: E402
|
||||
|
||||
from app.config import get_settings # noqa: E402
|
||||
from app.models import Base # noqa: E402
|
||||
|
||||
config = context.config
|
||||
if config.config_file_name is not None:
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
# Read from the settings and used directly — never stored through config.set_main_option(): Alembic's
|
||||
# config is a ConfigParser, whose %-interpolation rejects a percent-encoded password.
|
||||
url = get_settings().migration_database_url
|
||||
target_metadata = Base.metadata
|
||||
|
||||
|
||||
def run_migrations_offline() -> None:
|
||||
context.configure(url=strip_tls_params(url),
|
||||
target_metadata=target_metadata, literal_binds=True,
|
||||
dialect_opts={"paramstyle": "named"})
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def _runtime_role_is_the_login() -> None:
|
||||
"""Refuse to migrate unless DB_APP_ROLE is the role DATABASE_URL logs in as.
|
||||
|
||||
0002 grants DML in this schema to DB_APP_ROLE and only checks that the role exists. A value copied
|
||||
from a sibling app's .env (galena_app) would get this schema's privileges and the real runtime
|
||||
role nothing, and fixing .env afterwards changes nothing: alembic is already at head. The migrate
|
||||
service has both URLs, so compare them before anything is granted.
|
||||
"""
|
||||
settings = get_settings()
|
||||
try:
|
||||
login = (make_url(settings.database_url).username or "").split(".", 1)[0]
|
||||
except (ArgumentError, ValueError):
|
||||
login = None # raised outside this block: the parser's message could hold the password
|
||||
if login is None:
|
||||
raise RuntimeError("DATABASE_URL is not a database URL (is the password percent-encoded?)")
|
||||
if login != settings.db_app_role:
|
||||
raise RuntimeError(
|
||||
f"refusing to migrate: DB_APP_ROLE is {settings.db_app_role!r}, but DATABASE_URL logs in as "
|
||||
f"{login!r}. 0002 grants the runtime privileges to DB_APP_ROLE, so both must name this app's "
|
||||
"runtime role (agora_app in the shared database, app locally).")
|
||||
|
||||
|
||||
def run_migrations_online() -> None:
|
||||
_runtime_role_is_the_login()
|
||||
connectable = make_engine(url, poolclass=pool.NullPool) # a one-shot process holds no pool
|
||||
try:
|
||||
with connectable.connect() as connection:
|
||||
context.configure(connection=connection, target_metadata=target_metadata)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
finally:
|
||||
connectable.dispose()
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
||||
@@ -0,0 +1,127 @@
|
||||
"""Initial schema: pgcrypto, the native enum types and every table (the grants are 0002).
|
||||
|
||||
Tables come from the ORM metadata. `from app.models import Base` imports this app's models *and*
|
||||
`dredd_core` — and importing `dredd_core` is what registers the shared identity tables (`app_user`,
|
||||
`session`, `app_setting`, `audit_log`) on that same metadata. So a single `create_all` builds both
|
||||
halves and the migration cannot drift from the models.
|
||||
|
||||
**dredd-core ships models, not migrations.** Every app in the family owns its own `0001` and its own
|
||||
schema — its own database locally, its own schema `agora` in the family's shared managed
|
||||
database: the core tables are created *here*, in this app's schema, from a shared model definition.
|
||||
No other app's roles can reach that schema, so a standalone install keeps its own accounts and its own
|
||||
`session` rows here. That is the starting point, not a ban on sharing: the family's shape is one
|
||||
platform at one origin where every module resolves the SAME session out of an identity store the hub
|
||||
owns, and moving this app onto one is `0003_shared_identity` plus a grant tier — never an edit to
|
||||
this file.
|
||||
|
||||
**This revision keeps building the identity tables locally even on a platform, deliberately.** It
|
||||
would be easy to filter them out of `create_all` with `own_tables(..., shared=...)`; that is the
|
||||
wrong call twice over. `create_all` still emits the foreign keys that point AT `app_user`, so the
|
||||
table has to exist first and a filtered fresh install fails outright. And it would give a fresh
|
||||
platform install a different code path from the live one, where `0001` ran long ago — whereas
|
||||
leaving it means `0003` moves the three tables in exactly the same way on both, with no rows to move
|
||||
on a fresh one. One path, exercised every time. Note that `create_all` is unqualified, so it builds
|
||||
them in whatever schema comes FIRST on the migrator's search_path, which is this app's own; the
|
||||
lifespan's `assert_identity_schema` is what proves `0003` then took them away again.
|
||||
|
||||
Nothing here is schema-qualified. Tables, enum types and `alembic_version` land in the first schema on
|
||||
the migrator's search_path (`public` locally; `agora, extensions` on the shared project, set by
|
||||
provisioning), and `create_all`'s checkfirst and `create_enum_types` only look there — so a sibling
|
||||
app's `audit_log` or `node_role` in *its* schema never makes a table or type here get skipped.
|
||||
|
||||
Bumping the dredd-core pin can change what `Base.metadata` holds. That is an ordinary schema change
|
||||
for this app and belongs in a **new** revision — never in an edit to this one.
|
||||
|
||||
Agora is flat (single-tenant) and never uses the org tree — but importing `dredd_core`
|
||||
registers those models too, so `node`, `permission_grant` and `favorite` are created here as well.
|
||||
They stay empty and unused. That is expected: three idle tables cost nothing, and trying to suppress
|
||||
them means fighting the metadata that the rest of core is built on. Leave them — a later move to
|
||||
tree tenancy just starts writing to them.
|
||||
|
||||
Why the enum types are created first
|
||||
------------------------------------
|
||||
Every native enum column is bound with `pg_enum(...)`, i.e. `postgresql.ENUM(..., create_type=False)`.
|
||||
That flag tells SQLAlchemy: this type already exists — do not emit `CREATE TYPE` while creating the
|
||||
table, and do not `DROP TYPE` while dropping it. It is what stops a type from being created by
|
||||
whichever table happens to be built first, and from being dropped out from under the second table
|
||||
that still uses it. The cost of that flag is that `create_all` on a fresh database fails with
|
||||
`type "node_role" does not exist` unless the types are already there. Hence the order in
|
||||
`upgrade()`:
|
||||
|
||||
create_enum_types(bind) # CREATE TYPE … — core's enums and Agora's own
|
||||
Base.metadata.create_all(bind) # then the tables that reference them
|
||||
|
||||
`create_enum_types` reads the types straight off `Base.metadata`, so **adding an enum needs no edit
|
||||
here**: declare it in `app/enums.py`, bind it on the column with `pg_enum(MyEnum, "my_enum")`, and
|
||||
import the model in `app/models/__init__.py`. Adding a table needs no edit either — `create_all`
|
||||
picks it up.
|
||||
|
||||
What *is* explicit DDL below is what the runtime `app` role must never be able to perform: the
|
||||
pgcrypto extension. The least-privilege grants — including the append-only `audit_log` — are the
|
||||
next revision, `0002_runtime_grants`, which every later table-creating revision repeats.
|
||||
|
||||
Once this app is deployed anywhere, stop editing this file and add a new revision instead: a
|
||||
database migrated before never re-runs `0001`, so an edit here reaches fresh installs only. And
|
||||
because this file builds from the *live* metadata, a fresh database already has the current shape
|
||||
— so **every later revision must be idempotent** (`checkfirst=True`, `IF [NOT] EXISTS`, catalog
|
||||
checks): a no-op on a fresh install, a real change on a database migrated before it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dredd_core.schema import create_enum_types
|
||||
from sqlalchemy.dialects.postgresql import ENUM as PGEnum
|
||||
|
||||
from alembic import op
|
||||
from app.models import Base
|
||||
|
||||
revision = "0001"
|
||||
down_revision = None
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def _enum_type_names() -> list[str]:
|
||||
"""Every native enum type the metadata references — core's and Agora's own.
|
||||
|
||||
`create_enum_types` creates them; nothing drops them, because `create_type=False` suppresses
|
||||
SQLAlchemy's `DROP TYPE` just as it suppresses the `CREATE`. So `downgrade()` needs this list to
|
||||
stay symmetric with `upgrade()`, and reading it from the same metadata is what keeps it so.
|
||||
"""
|
||||
names: set[str] = set()
|
||||
for table in Base.metadata.tables.values():
|
||||
for column in table.columns:
|
||||
if isinstance(column.type, PGEnum) and column.type.name:
|
||||
names.add(column.type.name)
|
||||
return sorted(names)
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
bind = op.get_bind()
|
||||
# A no-op wherever pgcrypto already exists: the local stack's db/init creates it as the superuser,
|
||||
# and a managed provider usually keeps it in schema `extensions`. (gen_random_uuid() is core PostgreSQL.)
|
||||
op.execute('CREATE EXTENSION IF NOT EXISTS "pgcrypto"')
|
||||
# Order matters — the enum columns are create_type=False (see the module docstring).
|
||||
create_enum_types(bind)
|
||||
Base.metadata.create_all(bind=bind)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
bind = op.get_bind()
|
||||
# Tables first: a type cannot be dropped while a column still depends on it. (0002's grants die
|
||||
# with the objects they were granted on.)
|
||||
Base.metadata.drop_all(bind=bind)
|
||||
for name in _enum_type_names():
|
||||
op.execute(f'DROP TYPE IF EXISTS "{name}"')
|
||||
# Only if this role owns it: CI and most installs pre-create pgcrypto as the superuser (so the
|
||||
# least-privilege migrator never needs extension rights), a managed provider installs it for the
|
||||
# whole shared database (where every app relies on it), and DROP EXTENSION by a non-owner fails the whole
|
||||
# downgrade — rolling back every table drop above with it.
|
||||
op.execute("""
|
||||
DO $$
|
||||
BEGIN
|
||||
IF EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'pgcrypto'
|
||||
AND extowner = (SELECT oid FROM pg_roles WHERE rolname = current_user)) THEN
|
||||
DROP EXTENSION pgcrypto;
|
||||
END IF;
|
||||
END $$;
|
||||
""")
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Runtime grants: what the least-privilege runtime role may do in Agora's schema.
|
||||
|
||||
One call to `dredd_core.schema.runtime_grants_sql`, which renders a single idempotent `DO` block that
|
||||
acts on `current_schema()` — `public` on the local stack (db/init/01-roles.sh makes `migrator` own it),
|
||||
`agora` in the family's shared managed database (provisioning puts it first on the migrator's
|
||||
search_path) — for the role DB_APP_ROLE names (`get_settings().db_app_role`: `app` locally and in CI,
|
||||
`agora_app` in the shared database, where role names are cluster-wide). Both setups end up with
|
||||
the same least-privilege shape:
|
||||
|
||||
- the runtime role may use the schema, SELECT / INSERT / UPDATE / DELETE every table and use its
|
||||
sequences;
|
||||
- it holds no UPDATE, DELETE or TRUNCATE on the append-only evidence tables, and no DELETE or TRUNCATE
|
||||
on the no-delete ones (`app.models.APPEND_ONLY_TABLES` / `NO_DELETE_TABLES`) — a compromised
|
||||
application still cannot rewrite its own history, because the database will not let it;
|
||||
- the API roles (`anon`, `authenticated`, `service_role` — what a provider's auto-generated table API
|
||||
connects as) hold nothing in the schema, including the migrator's default privileges for future
|
||||
objects (skipped where they don't exist).
|
||||
|
||||
It **fails loudly** instead of half-working, and the whole migration rolls back: when the runtime role
|
||||
was never provisioned (or DB_APP_ROLE names the wrong one), when it runs as a superuser or the platform
|
||||
admin (`postgres` at a provider, `postgres_managed` in the local emulation) or as the runtime role itself,
|
||||
and when the result does not hold afterwards (a table the migrator does not own, whose GRANT was a
|
||||
silent no-op; an evidence table the runtime role can still modify some other way). Migrations run as
|
||||
the migrator — MIGRATION_DATABASE_URL — and nothing else.
|
||||
|
||||
Being one statement, it also renders in `alembic upgrade head --sql` (for the role DB_APP_ROLE names
|
||||
when rendering). **Every later revision that creates a table ends with this same `op.execute(...)`**:
|
||||
`GRANT ... ON ALL TABLES` only covers the tables that exist when it runs, and there are no default
|
||||
privileges for the runtime role.
|
||||
|
||||
Downgrade is a no-op on purpose: the grants die with the tables `0001` drops, and putting a Data API
|
||||
role's privileges back would re-expose data.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dredd_core.schema import runtime_grants_sql
|
||||
|
||||
from alembic import op
|
||||
from app.config import get_settings
|
||||
from app.models import APPEND_ONLY_TABLES, NO_DELETE_TABLES
|
||||
|
||||
revision = "0002"
|
||||
down_revision = "0001"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.execute(runtime_grants_sql(get_settings().db_app_role,
|
||||
append_only=APPEND_ONLY_TABLES, no_delete=NO_DELETE_TABLES))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Nothing to undo — see the module docstring."""
|
||||
@@ -0,0 +1,484 @@
|
||||
"""Agora joins the platform: its accounts become THE platform's accounts.
|
||||
|
||||
Before this, Agora keeps its own `app_user`, and the `admin@example.com` in it is a different
|
||||
person from the `admin@example.com` in every sibling who happens to share an email address — four
|
||||
people, four passwords. After it, identity lives in a neutral schema the hub owns, this module reads
|
||||
it, and the cookie somebody got by signing in at the hub is the cookie this app accepts. One origin,
|
||||
one cookie, one `session` row: there is no handoff here and there must never be one.
|
||||
|
||||
**It does nothing at all unless IDENTITY_SCHEMA is set.** A standalone Agora — its own
|
||||
database, its own people, no hub — keeps every table exactly where `0001` put it and never runs a
|
||||
statement from this file. That is a hard rule, not a convenience: the two deployments must stay one
|
||||
codebase, or local development forks from production and the fork is discovered in production.
|
||||
|
||||
What runs where
|
||||
---------------
|
||||
The schema itself, its owner and this app's `USAGE` on it are PROVISIONING (`db/managed/provision.sql`,
|
||||
rendered with `--identity-schema` / `--identity-owner`, run by the platform admin) — Alembic here runs
|
||||
as this app's migrator, which is NOCREATEROLE, holds no CREATE on the database and cannot `ALTER ROLE`
|
||||
another role's search_path. The TABLES inside that schema, and the tier grants that let this app read
|
||||
them, are the HUB's migration, because only the schema's owner may create a table in it or grant a
|
||||
privilege on it. This revision does the only part that is this app's: move its own rows onto the
|
||||
shared accounts, follow them with its foreign keys, and drop the local copies.
|
||||
|
||||
`_PREFLIGHT` therefore refuses by name when either of those has not happened, rather than failing
|
||||
somewhere confusing afterwards. A platform's compose file should also order the two
|
||||
(`depends_on: <hub>-migrate: service_completed_successfully`) — the belt to these braces, because
|
||||
without it every module's migration one-shot starts in parallel and this one can lose the race
|
||||
nondeterministically, differently each time.
|
||||
|
||||
What this does to the live data, and to `admin@example.com`
|
||||
-----------------------------------------------------------
|
||||
Every local account is matched to the shared store **by lower(email)** and every id that names a
|
||||
person in this schema is rewritten to the shared one. On a deployment seeded the documented way that
|
||||
is one row: this app's `admin@example.com` is matched to the `admin@example.com` already in the
|
||||
shared store — the hub's row, which kept its own UUID and its own password when the hub migrated —
|
||||
and this app's UUID for that person is **replaced by the hub's** everywhere it appears. Nothing is
|
||||
deleted and no history changes hands: the audit rows still name the same human, under the id that
|
||||
human now has everywhere. The local row itself is then dropped with the table, and the person
|
||||
survives as one platform account with one password, which is the entire point.
|
||||
|
||||
An account this module has and the shared store does not **stops the migration**. It cannot be
|
||||
imported from here — this app's migrator holds `SELECT` and `REFERENCES` on the shared `app_user`
|
||||
and no `INSERT`, by design, and the hub's migrator holds nothing in this schema. Importing is a
|
||||
platform-admin step run between the two migrations, from a census of every schema's `app_user`.
|
||||
Orphaning the row instead would silently strip somebody of everything they own here.
|
||||
|
||||
**Sessions and app tokens are NOT carried over.** They are dropped with the local `session` table, so
|
||||
everyone signed in here signs in again — at the hub, once — and every app token is re-minted there.
|
||||
Two reasons, and the first is sufficient on its own:
|
||||
|
||||
1. This module cannot move them. No role of a module holds `INSERT` on the shared `session`, because
|
||||
a role that can insert a session row can mint a working credential for the administrator. There
|
||||
is no privilege here to carry a session across with.
|
||||
2. It would be wrong even if it could. A session row promoted into the shared store becomes a
|
||||
**platform** credential: issued against a password this app checked, for this app, and suddenly
|
||||
able to open the hub and every sibling. That is a real widening of an existing credential, and
|
||||
the honest place to pay for it is one sign-in on the day everybody is being told to sign in
|
||||
somewhere new anyway.
|
||||
|
||||
A fresh install behaves identically, by construction rather than by a second code path: `0001` still
|
||||
builds the three identity tables in this app's own schema, and this revision still moves them. There
|
||||
are simply no rows to move. The lifespan's `assert_identity_schema` then proves the local copies are
|
||||
really gone — with `search_path = agora, <identity>, extensions` an unqualified `app_user`
|
||||
resolves to a local one if it exists and everything keeps working, silently back to two rows per
|
||||
human, which is the failure mode with no other symptom.
|
||||
|
||||
Idempotent, like every revision after `0001`: re-running it moves what has not moved, repoints what
|
||||
is already pointed and drops what is already dropped.
|
||||
|
||||
One trap, because it is easy to walk into and looks like a bug
|
||||
--------------------------------------------------------------
|
||||
This revision is a **no-op when `IDENTITY_SCHEMA` is empty**, and Alembic records that it ran anyway.
|
||||
So a deployment that upgraded to head first and set `IDENTITY_SCHEMA` afterwards — a perfectly
|
||||
reasonable order, and what happens whenever the code ships before the platform is ready — sits at
|
||||
`0003` with its local identity tables intact, and the next `alembic upgrade head` says there is
|
||||
nothing to do. Nothing is broken and nothing is lost; the backend simply refuses to start, because
|
||||
the lifespan assertion can see the local copies. The way out is to put the version back and run it
|
||||
with the setting in place:
|
||||
|
||||
alembic stamp 0002 && alembic upgrade head
|
||||
|
||||
which is safe on a database that has already been converted, because of the paragraph above. The
|
||||
lifespan says this in its own error message, so nobody has to find this file to learn it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
|
||||
from dredd_core.identity import SHARED_IDENTITY_TABLES
|
||||
from dredd_core.identity_schema import permission_grant_orphans_sql, repoint_identity_fks_sql
|
||||
from sqlalchemy import text
|
||||
|
||||
from alembic import op
|
||||
from app.config import get_settings
|
||||
from app.models import Base
|
||||
|
||||
revision = "0003"
|
||||
down_revision = "0002"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
log = logging.getLogger("alembic.runtime.migration")
|
||||
|
||||
#: Local identity tables to drop once the rows are repointed, children before parents. Every drop is
|
||||
#: IF EXISTS rather than a list that has to know when each table was created: which of them a
|
||||
#: database has depends on which core was pinned the day `0001` ran — one from before dredd-core
|
||||
#: v0.10.0 has neither permission table, one migrated between v0.10.0 and v0.11.0 has
|
||||
#: `module_moderator`, and a fresh one has `module_permission`.
|
||||
#:
|
||||
#: **Both permission names are listed on purpose.** `0004` is the rename, and it runs AFTER this
|
||||
#: revision, so a single `alembic upgrade head` on a database migrated under v0.10.x still meets the
|
||||
#: old name here. Dropping only the new one would leave the old table behind, and the `CASCADE`
|
||||
#: below would not take it: cascading from `app_user` drops the dependent foreign KEY, not the table
|
||||
#: that holds it. A surviving `module_moderator` breaks nothing loudly — it is simply a local
|
||||
#: identity table nothing reads, in the one schema where that is the failure mode with no other
|
||||
#: symptom, and `0004` will not touch it either, because by then the schema has no local `app_user`
|
||||
#: to tell a standalone database from a module.
|
||||
#:
|
||||
#: Written out rather than derived from `SHARED_IDENTITY_TABLES`, which is a frozenset and so cannot
|
||||
#: carry the order the drops need. The assertion below is what keeps the two from drifting.
|
||||
_LOCAL_TABLES = ("module_permission", "module_moderator", "session", "app_user")
|
||||
|
||||
#: Every shared table must have a local drop; extra names (a table core has since renamed away from,
|
||||
#: like `module_moderator`) are fine and are why this is a coverage check rather than the equality it
|
||||
#: used to be. Equality caught exactly this class of drift once — a core release renaming a shared
|
||||
#: table while this list kept the old name — and then refused to import at all until the list was
|
||||
#: updated, which is the right failure for a missing drop and the wrong one for a surviving legacy
|
||||
#: name. So keep the check, in the one direction where a miss is unrecoverable: a local copy this
|
||||
#: never drops shadows the shared table through the search_path, silently, for ever.
|
||||
_UNDROPPED = set(SHARED_IDENTITY_TABLES) - set(_LOCAL_TABLES)
|
||||
if _UNDROPPED:
|
||||
raise RuntimeError(
|
||||
f"dredd-core's shared identity tables include {sorted(_UNDROPPED)}, which this revision "
|
||||
f"never drops locally (it drops {list(_LOCAL_TABLES)}). Add them here, in an order that "
|
||||
"drops children before parents, or the cutover leaves a local copy that shadows the shared "
|
||||
"table through the search_path."
|
||||
)
|
||||
|
||||
|
||||
def _person_columns() -> list[tuple[str, str, str]]:
|
||||
"""Every column in THIS schema that names a person, as `(table, column, extra WHERE)`.
|
||||
|
||||
Derived from `Base.metadata` rather than written out, which is the one place this template
|
||||
deliberately differs from the apps that already made this move. They could list their columns by
|
||||
hand because their domains were finished; a scaffolded app's is not, and a hand-written list
|
||||
would go stale the first time somebody adds `assigned_to` to a model. The derivation and
|
||||
`repoint_identity_fks_sql` then read the same metadata, so the rows this rewrites and the
|
||||
constraints it re-points can never disagree.
|
||||
|
||||
The shared identity tables are skipped: their own `user_id` / `created_by` columns live in the
|
||||
hub's schema, where this app holds no write privilege and where the ids were never local.
|
||||
|
||||
One column cannot be derived, and it is the dangerous one. `permission_grant.principal_id`
|
||||
carries no foreign key at all, because it is polymorphic on `principal_type` — so PostgreSQL
|
||||
would never mention a row this missed, and the only symptom would be somebody who cannot see a
|
||||
workspace they could see yesterday. It is appended by name, with the filter that makes it mean
|
||||
"a user", and `permission_grant_orphans_sql` checks the result in the same transaction.
|
||||
"""
|
||||
found: list[tuple[str, str, str]] = []
|
||||
for table in Base.metadata.sorted_tables:
|
||||
if table.name in SHARED_IDENTITY_TABLES:
|
||||
continue
|
||||
for column in table.columns:
|
||||
if any(fk.column.table.name == "app_user" for fk in column.foreign_keys):
|
||||
found.append((table.name, column.name, ""))
|
||||
if "permission_grant" in Base.metadata.tables:
|
||||
found.append(("permission_grant", "principal_id", " AND t.principal_type = 'user'"))
|
||||
return found
|
||||
|
||||
|
||||
def _constraint_phases(statements: list[str]) -> tuple[list[str], list[str]]:
|
||||
"""Split dredd-core's interleaved DROP/ADD pairs into the two phases this merge needs.
|
||||
|
||||
`repoint_identity_fks_sql` renders them in pairs because a hub, which keeps every UUID and only
|
||||
moves rows between schemas, can run them that way. A module cannot (see step 2 of `upgrade`), so
|
||||
they are separated here rather than in core, where the pairing is right for its own caller. The
|
||||
counts must match: if core ever renders something else, that is a change to notice loudly, not
|
||||
to silently mis-classify into a migration that drops constraints and never puts them back.
|
||||
"""
|
||||
drops = [s for s in statements if " DROP CONSTRAINT " in s]
|
||||
adds = [s for s in statements if " ADD CONSTRAINT " in s]
|
||||
if len(drops) != len(adds) or len(drops) + len(adds) != len(statements):
|
||||
raise RuntimeError(
|
||||
"repoint_identity_fks_sql no longer renders one DROP and one ADD per foreign key "
|
||||
f"({len(drops)} drops, {len(adds)} adds, {len(statements)} statements) - this "
|
||||
"revision separates the two phases and cannot do that safely any more"
|
||||
)
|
||||
return drops, adds
|
||||
|
||||
|
||||
def _ident(value: str, what: str) -> str:
|
||||
"""A plain SQL identifier, re-checked here even though `Settings` already validated it.
|
||||
|
||||
The name is rendered into DDL rather than bound, and one of the statements below drops tables. A
|
||||
second look costs nothing; the alternative is a config typo reaching `DROP TABLE`.
|
||||
|
||||
Deliberately the same shape `Settings` enforces and no laxer — in particular **no hyphen**.
|
||||
Every use below is UNQUOTED (`FROM <identity>.app_user`), so a hyphenated name would not be a
|
||||
permission problem or a wrong answer, it would be a PostgreSQL syntax error raised from the
|
||||
middle of the merge. dredd-core refuses it too, but only at step 2, after the preflight and the
|
||||
mapping have already run.
|
||||
"""
|
||||
if not re.fullmatch(r"[a-z][a-z0-9_]{0,62}", value or ""):
|
||||
raise RuntimeError(f"{what} is not a plain lower-case SQL identifier: {value!r}")
|
||||
return value
|
||||
|
||||
|
||||
# Three things must already be true, and each fails differently later if it is not. Refusing here
|
||||
# names the command that fixes it instead of leaving a half-migrated schema behind.
|
||||
#
|
||||
# Every SQL string in this file is dollar-quoted and free of percent signs and of a colon followed by
|
||||
# a word - SQLAlchemy scans the text it is handed for bind parameters, comments included, and a
|
||||
# stray one fails the migration with "a value is required for bind parameter".
|
||||
_PREFLIGHT = """
|
||||
DO $dredd_identity_preflight$
|
||||
DECLARE
|
||||
target text := {identity_literal};
|
||||
t text;
|
||||
BEGIN
|
||||
IF to_regnamespace(target) IS NULL THEN
|
||||
RAISE EXCEPTION USING
|
||||
MESSAGE = 'shared identity: schema ' || target || ' does not exist, or this role holds no '
|
||||
|| 'USAGE on it',
|
||||
HINT = 'It is provisioning, not a migration. Re-render db/managed/provision.sql with the '
|
||||
|| 'identity flags and run it as the platform admin, which is also what grants this app '
|
||||
|| 'USAGE and puts the schema on its search_path.';
|
||||
END IF;
|
||||
IF current_schema() = target THEN
|
||||
RAISE EXCEPTION USING
|
||||
MESSAGE = 'shared identity: this app''s own schema IS ' || target,
|
||||
HINT = 'The app''s own schema must come first on the search_path and must never BE the shared '
|
||||
|| 'one - the statements below drop this app''s local identity tables by name.';
|
||||
END IF;
|
||||
FOREACH t IN ARRAY ARRAY[{shared_tables}]::text[] LOOP
|
||||
IF to_regclass(quote_ident(target) || '.' || quote_ident(t)) IS NULL THEN
|
||||
RAISE EXCEPTION USING
|
||||
MESSAGE = 'shared identity: ' || target || '.' || t || ' does not exist yet',
|
||||
HINT = 'The hub owns those tables and creates them in its own migration. Run the hub''s '
|
||||
|| 'migration first (compose should declare the order; this is the loud version of it).';
|
||||
END IF;
|
||||
END LOOP;
|
||||
IF NOT has_table_privilege(quote_ident(target) || '.app_user', 'SELECT') THEN
|
||||
RAISE EXCEPTION USING
|
||||
MESSAGE = 'shared identity: this role cannot read ' || target || '.app_user',
|
||||
HINT = 'The hub''s revision grants each module''s roles their tier, from its own list of '
|
||||
|| 'reader and migrator role names. This app''s two roles are missing from those. Add '
|
||||
|| 'them and re-run the hub''s grant revision.';
|
||||
END IF;
|
||||
END
|
||||
$dredd_identity_preflight$
|
||||
"""
|
||||
|
||||
# The mapping, and the two things that must be true about it before a single id is rewritten. Built
|
||||
# as a TEMPORARY table rather than a CTE because every repoint statement reads it, and because it is
|
||||
# worth being able to look at when something goes wrong.
|
||||
#
|
||||
# Unqualified names resolve to this app's OWN schema, which is first on the search_path and has to
|
||||
# be; the shared store is always written schema-qualified. That asymmetry is the whole trick.
|
||||
_BUILD_MAP = """
|
||||
DO $dredd_identity_map$
|
||||
DECLARE
|
||||
own text := current_schema();
|
||||
missing text;
|
||||
collided text;
|
||||
BEGIN
|
||||
CREATE TEMPORARY TABLE dredd_identity_map (local uuid PRIMARY KEY, shared uuid NOT NULL)
|
||||
ON COMMIT DROP;
|
||||
IF to_regclass(quote_ident(own) || '.app_user') IS NULL THEN
|
||||
RAISE NOTICE USING MESSAGE = 'shared identity: no local app_user in ' || own
|
||||
|| ', nothing to map';
|
||||
RETURN;
|
||||
END IF;
|
||||
|
||||
-- An account here that the shared store has never heard of. It cannot be imported from this side
|
||||
-- (no INSERT) and the hub cannot see this schema to import it from that side, so this is the one
|
||||
-- step a person has to do, and it has to happen before this runs.
|
||||
SELECT string_agg(l.email, ', ' ORDER BY l.email) INTO missing
|
||||
FROM app_user l
|
||||
WHERE NOT EXISTS (SELECT 1 FROM {identity_schema}.app_user d
|
||||
WHERE lower(d.email) = lower(l.email));
|
||||
IF missing IS NOT NULL THEN
|
||||
RAISE EXCEPTION USING
|
||||
MESSAGE = 'shared identity: no account in {identity_schema} for ' || missing,
|
||||
HINT = 'Nothing is committed. Those people exist in this module and not on the platform yet; '
|
||||
|| 'orphaning them would strip them of everything they own here. Import them as the '
|
||||
|| 'platform admin first, from a census of every schema''s app_user, then run this again.';
|
||||
END IF;
|
||||
|
||||
INSERT INTO dredd_identity_map (local, shared)
|
||||
SELECT l.id, d.id FROM app_user l
|
||||
JOIN {identity_schema}.app_user d ON lower(d.email) = lower(l.email)
|
||||
WHERE d.id <> l.id;
|
||||
|
||||
-- Two local accounts resolving to one platform account would collide on any composite key that
|
||||
-- carries a person (favorite is keyed by user and node). It cannot happen while both tables carry
|
||||
-- a unique index on lower(email) - each side is then one row per address, so the mapping is
|
||||
-- one-to-one. This proves that rather than assuming it, and proving it is cheaper than the
|
||||
-- de-duplication pass the alternative would need, which would have to decide whose rows to throw
|
||||
-- away.
|
||||
SELECT string_agg(x.s::text, ', ') INTO collided
|
||||
FROM (SELECT shared AS s FROM dredd_identity_map GROUP BY shared HAVING count(*) > 1) AS x;
|
||||
IF collided IS NOT NULL THEN
|
||||
RAISE EXCEPTION USING
|
||||
MESSAGE = 'shared identity: two local accounts both resolve to platform account(s) '
|
||||
|| collided,
|
||||
HINT = 'That should be impossible while app_user has a unique index on lower(email). Look at '
|
||||
|| 'the duplicate rows before going further; merging them needs a decision about which '
|
||||
|| 'of their rows survive, and this migration will not make it for you.';
|
||||
END IF;
|
||||
|
||||
END
|
||||
$dredd_identity_map$
|
||||
"""
|
||||
|
||||
# What the operator is TOLD, as opposed to what the database refuses. Deliberately not a
|
||||
# `RAISE NOTICE` inside the block above: pg8000 collects server notices on the connection and nothing
|
||||
# ever prints them, so a notice raised there reaches the PostgreSQL log and no human running the
|
||||
# migration. Read back in Python and logged instead, which Alembic puts on stdout with everything
|
||||
# else. Online mode only - there is no connection to ask under `alembic upgrade --sql`.
|
||||
_SUMMARY = """
|
||||
SELECT l.email, (d.id IS DISTINCT FROM l.id) AS moved, (l.is_admin AND NOT d.is_admin) AS demoted
|
||||
FROM app_user l JOIN {identity_schema}.app_user d ON lower(d.email) = lower(l.email)
|
||||
ORDER BY l.email
|
||||
"""
|
||||
|
||||
# One statement per person-column. A single UPDATE joined against the map is computed from one
|
||||
# snapshot, so an id that is itself a key in the map cannot be rewritten twice - which a
|
||||
# row-at-a-time loop would get wrong, silently, and only on the databases where it matters.
|
||||
_REPOINT = """
|
||||
UPDATE {table} AS t SET {column} = m.shared
|
||||
FROM dredd_identity_map m
|
||||
WHERE t.{column} = m.local{extra}
|
||||
"""
|
||||
|
||||
# The last statement that can lose data, so it checks before it acts. Each drop is built with
|
||||
# quote_ident() against current_schema() rather than written unqualified - an unqualified
|
||||
# `DROP TABLE session` resolves through the search_path, and the moment the local table is gone that
|
||||
# is the SHARED one, belonging to every module at once.
|
||||
_DROP_LOCAL = """
|
||||
DO $dredd_identity_drop_local$
|
||||
DECLARE
|
||||
own text := current_schema();
|
||||
missing bigint;
|
||||
t text;
|
||||
BEGIN
|
||||
IF own = {identity_literal} THEN
|
||||
RAISE EXCEPTION 'shared identity: refusing to drop identity tables from the shared schema itself';
|
||||
END IF;
|
||||
IF to_regclass(quote_ident(own) || '.app_user') IS NOT NULL THEN
|
||||
SELECT count(*) INTO missing FROM app_user l
|
||||
WHERE NOT EXISTS (SELECT 1 FROM {identity_schema}.app_user d
|
||||
WHERE lower(d.email) = lower(l.email));
|
||||
IF missing > 0 THEN
|
||||
RAISE EXCEPTION USING
|
||||
MESSAGE = 'shared identity: ' || missing || ' account(s) of ' || own || ' are not in the '
|
||||
|| 'shared store',
|
||||
HINT = 'Dropping the local table now would delete them. Nothing is committed; find out why '
|
||||
|| 'the mapping above did not catch them before running this again.';
|
||||
END IF;
|
||||
END IF;
|
||||
FOREACH t IN ARRAY ARRAY[{local_tables}]::text[] LOOP
|
||||
EXECUTE 'DROP TABLE IF EXISTS ' || quote_ident(own) || '.' || quote_ident(t) || ' CASCADE';
|
||||
END LOOP;
|
||||
END
|
||||
$dredd_identity_drop_local$
|
||||
"""
|
||||
|
||||
|
||||
def _report(identity: str) -> None:
|
||||
"""Say who is about to be merged, and name anybody who is losing their administrator tier.
|
||||
|
||||
The demotion is not an error and must not stop the cutover: the platform tier is granted in the
|
||||
hub on purpose, and the account-import step sets `is_admin` false deliberately so that a module
|
||||
can never mint a platform administrator. But somebody who administered THIS module yesterday will
|
||||
be an ordinary user tomorrow unless an administrator names them a MODERATOR of it, and that is
|
||||
exactly the kind of thing nobody notices until the person complains.
|
||||
"""
|
||||
context = op.get_context()
|
||||
if context.as_sql:
|
||||
return # offline rendering: there is no connection to read back from
|
||||
bind = op.get_bind()
|
||||
# On a RE-RUN the local table is already gone, and an unqualified `app_user` in the query below
|
||||
# would then resolve through the search_path to the SHARED one — joining it to itself and
|
||||
# reporting every account on the platform as "matched". Nothing would break, but the log would
|
||||
# say something untrue at the one moment somebody is reading it carefully.
|
||||
if bind.scalar(text("SELECT to_regclass(quote_ident(current_schema()) || '.app_user')")) is None:
|
||||
log.info("shared identity: no local accounts left to merge (already converted)")
|
||||
return
|
||||
rows = bind.execute(text(_SUMMARY.format(identity_schema=identity))).mappings().all()
|
||||
if not rows:
|
||||
log.info("shared identity: no local accounts to merge")
|
||||
return
|
||||
moved = [r["email"] for r in rows if r["moved"]]
|
||||
demoted = [r["email"] for r in rows if r["demoted"]]
|
||||
log.info("shared identity: %d account(s) matched in %s, %d of them under a different id",
|
||||
len(rows), identity, len(moved))
|
||||
if demoted:
|
||||
log.warning(
|
||||
"shared identity: %s administered this module and is NOT a platform administrator. "
|
||||
"Nothing is wrong - the platform tier is granted in the hub, on purpose - but until an "
|
||||
"administrator names them a moderator of this module there, they are an ordinary user "
|
||||
"here.", ", ".join(demoted))
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
settings = get_settings()
|
||||
if not settings.shares_identity:
|
||||
# Standalone: this app owns its own accounts and always has. Not a skipped step — there is
|
||||
# no platform here for an account to be shared with.
|
||||
return
|
||||
|
||||
identity = _ident(settings.identity_schema, "IDENTITY_SCHEMA")
|
||||
literal = f"'{identity}'"
|
||||
shared = tuple(sorted(SHARED_IDENTITY_TABLES))
|
||||
|
||||
op.execute(_PREFLIGHT.format(
|
||||
identity_literal=literal,
|
||||
shared_tables=", ".join(f"'{name}'" for name in shared),
|
||||
))
|
||||
|
||||
# 1. Who is who. Refuses on an account the platform has never heard of, proves the mapping is
|
||||
# one-to-one, and warns about anybody losing an administrator flag. The temporary table it
|
||||
# leaves behind is ON COMMIT DROP, so it lives exactly as long as this transaction.
|
||||
op.execute(_BUILD_MAP.format(identity_schema=identity))
|
||||
_report(identity)
|
||||
|
||||
# 2. Drop every foreign key that names a person, BEFORE a single row moves — and this ordering is
|
||||
# the whole of it. Unlike a hub, which keeps its accounts' UUIDs and only moves them between
|
||||
# schemas, this merge CHANGES ids: a local account becomes the platform account it matched by
|
||||
# e-mail. So while the OLD constraints stand, the first `UPDATE node SET owner_id = <platform
|
||||
# id>` violates `fk_node_owner_id_app_user`, because that id is not in the local table; and
|
||||
# while the NEW ones stand it violates them just as immediately, because the rows still hold
|
||||
# local ids. Neither end can go first — the constraints have to be absent in between. (It also
|
||||
# saves PostgreSQL a foreign-key check per row through the mass updates below.)
|
||||
drops, adds = _constraint_phases(repoint_identity_fks_sql(identity, Base.metadata))
|
||||
for statement in drops:
|
||||
op.execute(statement)
|
||||
|
||||
# 3. Every id in this schema that names a person, derived from the same metadata.
|
||||
for table, column, extra in _person_columns():
|
||||
op.execute(_REPOINT.format(table=f'"{table}"', column=f'"{column}"', extra=extra))
|
||||
|
||||
# 4. The one column PostgreSQL will never complain about — see `_person_columns`. Checked here,
|
||||
# while the transaction can still roll everything back.
|
||||
if "permission_grant" in Base.metadata.tables:
|
||||
op.execute(permission_grant_orphans_sql(identity))
|
||||
|
||||
# 5. The constraints come back, pointing at the shared store. Adding a foreign key VALIDATES it
|
||||
# against every existing row, so this is not bookkeeping — it is the proof that step 3 reached
|
||||
# all of them. An id this migration failed to rewrite fails loudly right here, and the whole
|
||||
# transaction rolls back with the local tables still intact.
|
||||
for statement in adds:
|
||||
op.execute(statement)
|
||||
|
||||
# 6. The local copies, once every local account is provably present in the shared store. CASCADE
|
||||
# because `0001` also built the indexes and constraints that belong to these tables; nothing
|
||||
# outside them still depends on them by this point, which step 5 is what guarantees.
|
||||
op.execute(_DROP_LOCAL.format(
|
||||
identity_schema=identity,
|
||||
identity_literal=literal,
|
||||
local_tables=", ".join(f"'{name}'" for name in _LOCAL_TABLES),
|
||||
))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Refused in platform mode, and a no-op otherwise.
|
||||
|
||||
There is no honest downgrade. This app's accounts are now rows in a schema it does not own and
|
||||
may not write; the mapping from each platform id back to the local id it replaced was in a
|
||||
temporary table that died with the transaction that used it, deliberately, because keeping it
|
||||
would be keeping a second copy of the identity this change exists to unify. And `0001`'s
|
||||
`drop_all` on the way past would resolve `app_user` through the search_path to the SHARED table
|
||||
and take every module's accounts with it.
|
||||
|
||||
Restore the dump taken before the cutover instead. A cutover runbook that does not begin with
|
||||
one is not a runbook.
|
||||
"""
|
||||
if not get_settings().shares_identity:
|
||||
return
|
||||
raise NotImplementedError(
|
||||
"0003 cannot be downgraded while IDENTITY_SCHEMA is set: this module's accounts were merged "
|
||||
"into the platform's and the mapping back no longer exists. Restore the pre-cutover dump."
|
||||
)
|
||||
@@ -0,0 +1,198 @@
|
||||
"""`module_moderator` becomes `module_permission` on databases that already have the old shape.
|
||||
|
||||
dredd-core v0.11.0 replaced the moderator roster with a permission table: one row per person per
|
||||
module, carrying a `role` of `user` or `moderator`, and **no row meaning no access to that module at
|
||||
all**. Renaming the model reaches a *fresh* database, because `0001` builds from `Base.metadata`.
|
||||
It reaches nothing else: `0001` is stamped, so it never runs again, and a database migrated while
|
||||
dredd-core v0.10.x was pinned still holds `module_moderator` in this app's own schema.
|
||||
|
||||
That is the rule this family already paid for once and wrote down: **never change what `0001`
|
||||
creates without a follow-up revision for the databases migrated before.** Left undone, every symptom
|
||||
is late and names the wrong thing — a query for `module_permission` failing with *relation does not
|
||||
exist* on an ordinary screen, and `0003` looking for rows to move in a table that is not there.
|
||||
|
||||
Three states, decided by the catalog rather than by a setting, because a setting can be changed
|
||||
after the fact and the catalog cannot lie about what is in front of it:
|
||||
|
||||
* **`module_permission` is already there** — a fresh install, or a re-run. Nothing.
|
||||
* **`module_moderator` is there** — rename it, rename its constraints and its index onto the
|
||||
`pk_/uq_/ix_/fk_/ck_module_permission_*` names the naming convention would have given them, add
|
||||
`role`, add the CHECK the model renders from `MODULE_ROLES`, and set **every existing row to
|
||||
`moderator`**: the old table's rows were moderators, and a rename that quietly demoted them all to
|
||||
`user` would take this module's administration away from the people who have it, silently.
|
||||
* **neither, and this schema still has an `app_user` of its own** — a standalone database whose
|
||||
`0001` ran before the table existed at all. Create it, from the metadata, so it is byte-identical
|
||||
to what `0001` builds today.
|
||||
|
||||
And the fourth state, which is why the third is guarded on `app_user` rather than written as an
|
||||
`ELSE`: on the **platform**, `0003` has just dropped this schema's local identity tables, because
|
||||
identity belongs to the hub and this app only reads it. There is nothing here to rename and nothing
|
||||
to create — creating `module_permission` here would build the shadow table `assert_identity_schema`
|
||||
exists to catch, and the app would refuse to start on its next boot. The hub owns that table in the
|
||||
shared schema and creates it in its own revision; this app's migrator holds no privilege there.
|
||||
|
||||
A renamed table carries `role` as its last column while a freshly created one carries it third. That
|
||||
is cosmetic — nothing reads a column by position — and the alternative is rewriting the table to fix
|
||||
the look of `\\d module_permission`.
|
||||
|
||||
Downgrade is a no-op. Renaming the table back would re-break the code that is running, since the ORM
|
||||
maps `module_permission` and nothing else, and `0001`'s `drop_all` below this one already expects
|
||||
the new name.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dredd_core.schema import runtime_grants_sql
|
||||
from sqlalchemy.dialects import postgresql
|
||||
from sqlalchemy.schema import CreateIndex, CreateTable
|
||||
|
||||
from alembic import op
|
||||
from app.config import get_settings
|
||||
from app.models import APPEND_ONLY_TABLES, NO_DELETE_TABLES, ModulePermission
|
||||
|
||||
revision = "0004"
|
||||
down_revision = "0003"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
#: Old name → new name for everything PostgreSQL does **not** rename along with the table. `ALTER
|
||||
#: TABLE ... RENAME TO` moves the table and nothing else, so without this the new table keeps a
|
||||
#: primary key called `pk_module_moderator` — which works, and is a small lie that the next person to
|
||||
#: write a migration against these names would find the hard way. `RENAME CONSTRAINT` carries the
|
||||
#: backing index of a primary key or unique constraint with it; the plain index has to be renamed on
|
||||
#: its own. `ck_module_permission_role` is not here because it has no old counterpart: it arrives
|
||||
#: with the column.
|
||||
_CONSTRAINTS: tuple[tuple[str, str], ...] = (
|
||||
("pk_module_moderator", "pk_module_permission"),
|
||||
("uq_module_moderator_user_module", "uq_module_permission_user_module"),
|
||||
("ck_module_moderator_slug", "ck_module_permission_slug"),
|
||||
("fk_module_moderator_user_id_app_user", "fk_module_permission_user_id_app_user"),
|
||||
("fk_module_moderator_created_by_app_user", "fk_module_permission_created_by_app_user"),
|
||||
)
|
||||
_INDEXES: tuple[tuple[str, str], ...] = (
|
||||
("ix_module_moderator_module_slug", "ix_module_permission_module_slug"),
|
||||
)
|
||||
|
||||
|
||||
def _array(pairs: tuple[tuple[str, str], ...], which: int) -> str:
|
||||
"""One half of `pairs` as a SQL text array literal. The names are ours, written above."""
|
||||
return "ARRAY[" + ", ".join(f"'{pair[which]}'" for pair in pairs) + "]"
|
||||
|
||||
|
||||
def _ddl() -> str:
|
||||
"""`CREATE TABLE` + `CREATE INDEX` for `module_permission`, rendered from the live metadata.
|
||||
|
||||
From the model rather than written out, exactly as `0001` builds every table, so a database that
|
||||
arrives here by the create branch and one built by `0001` cannot end up with different shapes —
|
||||
server defaults, both CHECKs and both foreign keys included. Unqualified, so it lands in
|
||||
`current_schema()`, and its foreign keys resolve to the local `app_user`, which the branch that
|
||||
runs it has already established is there.
|
||||
"""
|
||||
dialect = postgresql.dialect()
|
||||
table = ModulePermission.__table__
|
||||
statements = [str(CreateTable(table).compile(dialect=dialect)).strip()]
|
||||
statements += [str(CreateIndex(index).compile(dialect=dialect)).strip()
|
||||
for index in sorted(table.indexes, key=lambda i: i.name)]
|
||||
# Dollar-quoted, and nested inside the guard block below. The rendered DDL contains a `$` (the
|
||||
# end anchor of the slug CHECK's regular expression) but never the tag itself, which is the only
|
||||
# thing that closes a dollar-quoted string.
|
||||
return "\n".join(f" EXECUTE $create${statement}$create$;" for statement in statements)
|
||||
|
||||
|
||||
# One statement, three branches, and the fourth outcome is every branch declining — so it renders
|
||||
# under `alembic upgrade --sql` as completely as it runs. An f-string rather than `str.format`: what
|
||||
# it interpolates carries `{0,39}` (the length bound in the slug CHECK's regular expression), which
|
||||
# `format` would read as a field name and raise on — so never run `format` over this, before or
|
||||
# after rendering.
|
||||
#
|
||||
# Every name is qualified with quote_ident(current_schema()). Unqualified, `module_moderator` and
|
||||
# `module_permission` resolve through the search_path, which on the platform ends at the shared
|
||||
# schema — renaming or altering the hub's table from inside a module.
|
||||
#
|
||||
# No percent sign and no colon-name sequence anywhere in here, comments included: `op.execute` wraps
|
||||
# the string in `text()`, which scans all of it, and a comment quoting that very rule has already
|
||||
# killed a migration on its first live run elsewhere in this family.
|
||||
_RENAME_OR_CREATE = f"""
|
||||
DO $dredd_module_permission$
|
||||
DECLARE
|
||||
own text := current_schema();
|
||||
rel oid;
|
||||
pair record;
|
||||
BEGIN
|
||||
IF to_regclass(quote_ident(own) || '.module_permission') IS NOT NULL THEN
|
||||
RETURN; -- built by 0001 from the current model, or renamed by an earlier run
|
||||
END IF;
|
||||
|
||||
IF to_regclass(quote_ident(own) || '.module_moderator') IS NOT NULL THEN
|
||||
EXECUTE 'ALTER TABLE ' || quote_ident(own)
|
||||
|| '.module_moderator RENAME TO module_permission';
|
||||
rel := to_regclass(quote_ident(own) || '.module_permission');
|
||||
|
||||
FOR pair IN SELECT * FROM
|
||||
unnest({_array(_CONSTRAINTS, 0)}, {_array(_CONSTRAINTS, 1)}) AS t(was, now_called)
|
||||
LOOP
|
||||
IF EXISTS (SELECT 1 FROM pg_constraint
|
||||
WHERE conrelid = rel AND conname = pair.was) THEN
|
||||
EXECUTE 'ALTER TABLE ' || quote_ident(own) || '.module_permission RENAME CONSTRAINT '
|
||||
|| quote_ident(pair.was) || ' TO ' || quote_ident(pair.now_called);
|
||||
END IF;
|
||||
END LOOP;
|
||||
|
||||
FOR pair IN SELECT * FROM
|
||||
unnest({_array(_INDEXES, 0)}, {_array(_INDEXES, 1)}) AS t(was, now_called)
|
||||
LOOP
|
||||
IF to_regclass(quote_ident(own) || '.' || quote_ident(pair.was)) IS NOT NULL THEN
|
||||
EXECUTE 'ALTER INDEX ' || quote_ident(own) || '.' || quote_ident(pair.was)
|
||||
|| ' RENAME TO ' || quote_ident(pair.now_called);
|
||||
END IF;
|
||||
END LOOP;
|
||||
|
||||
-- The lesser role is the default, here as in the model: an INSERT that forgets to name one
|
||||
-- admits a user, never a moderator.
|
||||
EXECUTE 'ALTER TABLE ' || quote_ident(own) || '.module_permission '
|
||||
|| 'ADD COLUMN IF NOT EXISTS role varchar(20) NOT NULL DEFAULT ' || quote_literal('user');
|
||||
-- Every row of the old table was a moderator: that was the only thing a row there could mean.
|
||||
-- Inside this branch and nowhere else, so a later demotion in the hub is never undone by a
|
||||
-- re-run -- once the table has the new name the first branch above has already returned.
|
||||
EXECUTE 'UPDATE ' || quote_ident(own) || '.module_permission SET role = '
|
||||
|| quote_literal('moderator');
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_constraint
|
||||
WHERE conrelid = rel AND conname = 'ck_module_permission_role') THEN
|
||||
EXECUTE 'ALTER TABLE ' || quote_ident(own) || '.module_permission '
|
||||
|| 'ADD CONSTRAINT ck_module_permission_role CHECK (role IN ('
|
||||
|| quote_literal('user') || ', ' || quote_literal('moderator') || '))';
|
||||
END IF;
|
||||
RETURN;
|
||||
END IF;
|
||||
|
||||
-- Neither name. Either this schema owns its accounts and simply predates the table, or identity
|
||||
-- is the hub's and 0003 has just dropped the local copies. The presence of a local app_user is
|
||||
-- what tells those two apart, and it is the only safe way to ask: creating this table on the
|
||||
-- platform would be the shadow copy that gives everyone a second identity, and the lifespan
|
||||
-- assertion would refuse to start the app on its next boot.
|
||||
IF to_regclass(quote_ident(own) || '.app_user') IS NOT NULL THEN
|
||||
{_ddl()}
|
||||
END IF;
|
||||
END
|
||||
$dredd_module_permission$
|
||||
"""
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.execute(_RENAME_OR_CREATE)
|
||||
# A renamed table keeps its own privileges, but a created one has none — and `0002`'s
|
||||
# `GRANT ... ON ALL TABLES` only covered the tables that existed when it ran. This is the rule
|
||||
# `0002` states for every later revision that can create a table, and it is cheap to keep:
|
||||
# the block is idempotent, so running it on a database where nothing was created costs one
|
||||
# statement and no decision about which branch was taken.
|
||||
op.execute(runtime_grants_sql(get_settings().db_app_role, append_only=APPEND_ONLY_TABLES,
|
||||
no_delete=NO_DELETE_TABLES))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Nothing, deliberately.
|
||||
|
||||
Renaming the table back would break the code that is running — the ORM maps `module_permission`
|
||||
and only that — and `0001`'s `drop_all`, the one revision below this that touches the table at
|
||||
all, already names it that way. No downgrade can conjure back the core release that wanted the
|
||||
other name either.
|
||||
"""
|
||||
@@ -0,0 +1 @@
|
||||
__version__ = "0.1.0"
|
||||
@@ -0,0 +1,325 @@
|
||||
"""Typed application settings, sourced from environment variables / .env.
|
||||
|
||||
The app owns its settings. The shared core never reads them: `services/auth.py` maps the
|
||||
relevant ones onto a `dredd_core.auth.AuthPolicy` and passes it in explicitly.
|
||||
|
||||
Defaults fail CLOSED: production hides error detail, so a deployment that forgets to set APP_ENV
|
||||
is the safe one rather than the leaky one. (The session cookie's Secure flag is auto-detected from
|
||||
the request scheme, not APP_ENV; SESSION_COOKIE_SECURE forces it.) An optional integration is
|
||||
switched off by an empty-string default and a `*_enabled` property, so "not configured" is a clean
|
||||
no-op instead of a crash.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
|
||||
from dredd_core.db import require_verified_tls
|
||||
from pydantic import Field, field_validator, model_validator
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
from sqlalchemy.engine import make_url
|
||||
from sqlalchemy.exc import ArgumentError
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
# hide_input_in_errors: a refused setting must not echo the input back, and the database URLs
|
||||
# carry passwords.
|
||||
model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8", extra="ignore",
|
||||
hide_input_in_errors=True)
|
||||
|
||||
# Core. Set APP_ENV=development locally for error detail and DEBUG logs.
|
||||
app_env: str = "production"
|
||||
app_base_url: str = "http://localhost"
|
||||
|
||||
# The path prefix this deployment is mounted under. Empty (the default) = served at the origin
|
||||
# root, which is the standalone stack this repo ships. ROOT_PATH=/agora runs it as a module
|
||||
# of a platform: one origin, one module per path.
|
||||
#
|
||||
# It is HALF of one decision, never set alone: the platform's front door must STRIP the
|
||||
# prefix (Atrium's backend forwards `/agora/*` without it) and this backend must re-add it. uvicorn PREPENDS root_path to
|
||||
# the incoming path, so forwarding without the strip doubles the prefix and 404s every route, while
|
||||
# stripping without ROOT_PATH makes every server-generated URL (redirects, StaticFiles' own
|
||||
# directory redirect, the OpenAPI `servers` entry) escape the prefix. The same value reaches
|
||||
# uvicorn as `--root-path "$ROOT_PATH"` (backend/Dockerfile) and FastAPI as `root_path=`
|
||||
# (main.py) — they must agree, which is why both read this one variable. The console needs
|
||||
# nothing: it derives its API base from the document.
|
||||
root_path: str = ""
|
||||
|
||||
@field_validator("root_path")
|
||||
@classmethod
|
||||
def _mounted_path(cls, v: str) -> str:
|
||||
# Refused rather than normalised, because uvicorn reads the RAW environment variable off
|
||||
# the command line while everything in-process reads this one. Silently fixing it here
|
||||
# would leave the two disagreeing: `--root-path /agora/` prepends `/agora/` and FastAPI
|
||||
# then overwrites scope["root_path"] with its own normalised `/agora`, so the two differ
|
||||
# by one character and every route 404s with nothing in the logs to say why.
|
||||
v = v.strip()
|
||||
if v and (not v.startswith("/") or v.endswith("/")):
|
||||
raise ValueError("ROOT_PATH must be empty or a path like /agora - leading slash, no "
|
||||
"trailing slash")
|
||||
return v
|
||||
|
||||
# Database (runtime = least-privilege "app" role; migrator = DDL). A managed database's URL
|
||||
# carries ?sslmode=verify-full&sslrootcert=..., which dredd_core.db.make_engine turns into TLS.
|
||||
database_url: str = "postgresql+pg8000://app:app@localhost:5432/agora"
|
||||
migration_database_url: str = (
|
||||
"postgresql+pg8000://migrator:migrator@localhost:5432/agora"
|
||||
)
|
||||
# The family's one TLS rule (dredd_core.db.require_verified_tls, applied below): a database host
|
||||
# that is not local must carry sslmode=verify-full, or the app refuses to start. Local is "",
|
||||
# localhost, 127.0.0.1, ::1, `postgres` (the compose service) — and, comma-separated here, any
|
||||
# further host that needs no TLS (a private database on a trusted network, say). Optional, and
|
||||
# the only exception to the rule.
|
||||
db_local_hosts: str = ""
|
||||
# The runtime role's NAME: the user DATABASE_URL logs in as, without a pooler's `.<tenant>`
|
||||
# suffix. The runtime-grants migration (0002) grants to it. `app` locally and in CI; in the
|
||||
# family's shared managed database role names are cluster-wide, so there it is
|
||||
# `agora_app` (db/managed/README.md). Nothing else in the app needs a role name.
|
||||
db_app_role: str = "app"
|
||||
# The backend's pool: at most db_pool_size + db_max_overflow connections. Every app of the family
|
||||
# draws on one shared database's connection limit, so size these there (db/managed/README.md).
|
||||
# Bounded below: SQLAlchemy reads pool_size=0 or max_overflow=-1 as "no limit".
|
||||
db_pool_size: int = Field(default=5, ge=1)
|
||||
db_max_overflow: int = Field(default=10, ge=0)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _external_database_verifies_tls(self) -> Settings:
|
||||
# Without sslmode, make_engine passes a URL through unchanged and pg8000 neither verifies the
|
||||
# server nor refuses plaintext. So a database anywhere but beside the app must say
|
||||
# sslmode=verify-full. Checked wherever settings load, so the backend, migrate and the seed
|
||||
# all refuse before a password crosses an unverified link. A blank URL is skipped (the
|
||||
# managed-database backend's MIGRATION_DATABASE_URL).
|
||||
for name in ("DATABASE_URL", "MIGRATION_DATABASE_URL"):
|
||||
_require_verified_tls(name, getattr(self, name.lower()), self.db_local_hosts)
|
||||
return self
|
||||
|
||||
# Working directory for anything written to disk (exports, generated documents).
|
||||
data_dir: str = "data"
|
||||
|
||||
# ── One platform, one account ────────────────────────────────────────────────
|
||||
# The shared identity schema. Empty — the default, and what this repo's own compose stack runs —
|
||||
# is the STANDALONE deployment: Agora owns `app_user` / `session` / `module_permission` in
|
||||
# its own schema, has its own sign-in screen and its own Users administration, and nothing that
|
||||
# follows changes. Set it (IDENTITY_SCHEMA=dredd) and this app becomes a MODULE of
|
||||
# the platform: those three tables live in a neutral schema the hub owns and every module READS,
|
||||
# a person has ONE account for the whole platform, they sign in once at the hub, and the cookie
|
||||
# they got there is the cookie this app accepts. One origin, one cookie — there is no handoff to
|
||||
# design here, and a design that invents a token exchange for this topology is over-engineering.
|
||||
#
|
||||
# It is a name rather than a boolean because several separate things need the name itself: the
|
||||
# cutover revision (alembic/versions/0003_shared_identity.py) moves this app's accounts into it
|
||||
# and re-points every foreign key there, and the lifespan asserts that the identity tables really
|
||||
# resolve there — the shadow-copy failure has no other symptom.
|
||||
#
|
||||
# The schema itself, its owner, this app's USAGE on it and the search_path that reaches it are
|
||||
# PROVISIONING, not migration: a migrator role holds no CREATE on the database and cannot
|
||||
# ALTER ROLE another role. See db/managed/README.md. This app never creates it — the hub's
|
||||
# migrator owns it, and the hub's own revision grants this app's two roles their tier.
|
||||
identity_schema: str = ""
|
||||
# This app's slug on the platform: the module a permission row is a permission FOR, and so the
|
||||
# the only thing this app tells dredd-core about the platform: core is handed data (a slug),
|
||||
# never a predicate, which is what keeps the rule and its enforcement inside core.
|
||||
#
|
||||
# It is a SEPARATE name from `agora`, this app's Postgres schema and role prefix, and the
|
||||
# two are allowed to differ because their judges differ. A schema name may hold underscores and
|
||||
# must not hold hyphens; a module slug is the platform's public vocabulary — it appears in a URL
|
||||
# path — and `dredd.module_permission` holds it to `^[a-z0-9][a-z0-9-]{0,39}$`: hyphens yes,
|
||||
# underscores no. A two-word app therefore has a schema `my_app` and a module slug `my-app`, and
|
||||
# the scaffolder derives the second from the first so the default is already legal.
|
||||
module_slug: str = "agora"
|
||||
# Where people sign in when identity is shared — the hub's address as a BROWSER sees it, e.g.
|
||||
# /atrium/ on the platform. Empty standalone (there is no hub), and empty is survivable on the
|
||||
# platform too: the console then says where accounts live without linking to them. It is
|
||||
# deployment topology, so it is a setting rather than something the console derives — deriving
|
||||
# the hub's address from this module's own path would hard-code the hub's slug into every module.
|
||||
identity_hub_url: str = ""
|
||||
|
||||
# Both of the names above reach SQL, so both are refused at startup rather than at the first
|
||||
# statement that uses them. They are validated SEPARATELY and to DIFFERENT shapes, because the
|
||||
# authority that will really judge each one is different — and a validator that is laxer than
|
||||
# the eventual judge is worse than none: it promises a refusal it does not deliver, and the
|
||||
# refusal then arrives from somewhere with no idea what the value was for.
|
||||
|
||||
@field_validator("identity_schema")
|
||||
@classmethod
|
||||
def _a_schema_name_that_needs_no_quoting(cls, v: str) -> str:
|
||||
# A plain SQL identifier, and deliberately NO hyphen: the name is rendered UNQUOTED into
|
||||
# 0003's DDL (`FROM <identity>.app_user`), one statement of which DROPs this app's local
|
||||
# identity tables. `dredd-core` holds it to the same shape wherever it renders it
|
||||
# (`schema._sql_name`, `provisioning._name`), so anything this accepted and core did not
|
||||
# would get through startup, run standalone perfectly well, and then fail the day somebody
|
||||
# sets it for real — as a PostgreSQL syntax error half-way through `alembic upgrade`, or as
|
||||
# a bare ValueError out of the lifespan assertion that the friendly handler does not catch.
|
||||
v = v.strip()
|
||||
if v and not re.fullmatch(r"[a-z][a-z0-9_]{0,62}", v):
|
||||
raise ValueError("IDENTITY_SCHEMA must be a plain lower-case SQL name — a letter, then "
|
||||
"letters, digits or _ (no hyphens: it is rendered unquoted into DDL) "
|
||||
"— or empty for a standalone app")
|
||||
return v
|
||||
|
||||
@field_validator("module_slug")
|
||||
@classmethod
|
||||
def _a_slug_the_shared_table_will_accept(cls, v: str) -> str:
|
||||
# Exactly the CHECK constraint on `dredd.module_permission.module_slug`, which lives in the
|
||||
# hub's schema and is the thing that would actually reject a row:
|
||||
# CHECK (module_slug ~ '^[a-z0-9][a-z0-9-]{0,39}$')
|
||||
# Hyphens yes, underscores no, 40 characters. Restating it here is worth the duplication
|
||||
# because of HOW it fails otherwise. This app never INSERTs a permission row — it only ever
|
||||
# SELECTs by slug — so an illegal slug raises nothing at all here. It makes
|
||||
# `WHERE module_slug = '...'` a query no row can ever match, while the hub's grant screen
|
||||
# refuses the INSERT at the other end of the platform. And since no row is no access, the
|
||||
# result is an app nobody but a platform administrator may open, with no error to say why.
|
||||
v = v.strip()
|
||||
if v and not re.fullmatch(r"[a-z0-9][a-z0-9-]{0,39}", v):
|
||||
raise ValueError("MODULE_SLUG must match the shape the platform's module_permission "
|
||||
"table accepts: a lower-case letter or digit, then letters, digits or "
|
||||
"- , at most 40 characters (no underscores — a module slug is a URL "
|
||||
"path segment, not a schema name)")
|
||||
return v
|
||||
|
||||
@field_validator("identity_hub_url")
|
||||
@classmethod
|
||||
def _hub_is_a_safe_address(cls, v: str) -> str:
|
||||
# Rendered into the console's sign-in card as an href, so it must be an address a browser
|
||||
# will navigate to and nothing else: a same-origin path (the platform: /atrium/) or an
|
||||
# absolute http(s) URL (a hub on another host, which one origin makes unnecessary but which a
|
||||
# two-host deployment could still want). Everything else — javascript:, data:, a
|
||||
# protocol-relative //host, a backslash a browser normalises to a slash — is refused here
|
||||
# rather than patched in the console, because an operator's typo should stop the process, not
|
||||
# produce a dead link on the one screen nobody is signed in to.
|
||||
v = v.strip()
|
||||
if not v:
|
||||
return v
|
||||
if v.startswith("//") or "\\" in v or "%5c" in v.lower():
|
||||
raise ValueError("IDENTITY_HUB_URL must not be protocol-relative or contain backslashes")
|
||||
if v.startswith(("/", "http://", "https://")):
|
||||
return v
|
||||
raise ValueError("IDENTITY_HUB_URL must be a path like /atrium/ or an http(s) URL")
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _a_module_knows_which_module_it_is(self) -> Settings:
|
||||
# A module of the platform with no slug is a half-configured one: `module_permission` rows
|
||||
# are keyed by slug, so nobody's row would ever resolve — and since no row is no access, this
|
||||
# app would refuse everyone but a platform administrator, who is the one person unable to
|
||||
# reproduce it. Standalone the slug is irrelevant and may be anything, empty included.
|
||||
if self.shares_identity and not self.module_slug:
|
||||
raise ValueError("MODULE_SLUG must name this app's module on the platform (e.g. "
|
||||
"agora) whenever IDENTITY_SCHEMA is set — permission "
|
||||
"rows are keyed by it")
|
||||
return self
|
||||
|
||||
# Auth / sessions (cookie-based, server-side rows in whichever identity store this app reads)
|
||||
# The cookie's NAME. One account means one cookie: at a cutover every app in the family is set to
|
||||
# SESSION_COOKIE_NAME=dredd_session, and because the family runs at ONE origin that is the
|
||||
# entire single-sign-on mechanism — no Domain attribute, no signed assertion, no audience
|
||||
# binding. The default keeps a standalone app on its own name; `deps.LEGACY_SESSION_COOKIES`
|
||||
# keeps reading the old one, so renaming it does not sign everybody out on the next restart.
|
||||
session_cookie_name: str = "agora_session"
|
||||
|
||||
@field_validator("session_cookie_name")
|
||||
@classmethod
|
||||
def _cookie_token(cls, v: str) -> str:
|
||||
# An RFC 6265 cookie-name token. A name carrying a space or a separator is dropped by the
|
||||
# browser without a word, and the symptom is a login that "doesn't stick" — the same
|
||||
# miserable bug SESSION_COOKIE_SECURE's comment is about, approached from the other side.
|
||||
v = v.strip()
|
||||
if not re.fullmatch(r"[A-Za-z0-9!#$%&'*+.^_`|~-]{1,64}", v):
|
||||
raise ValueError("SESSION_COOKIE_NAME must be a cookie name token, "
|
||||
"e.g. dredd_session")
|
||||
return v
|
||||
|
||||
session_ttl_hours: int = 12
|
||||
login_max_attempts: int = 5
|
||||
login_lockout_minutes: int = 15
|
||||
# None → auto-detect per request scheme (Secure over HTTPS only). Set true/false to force.
|
||||
# An empty env value (SESSION_COOKIE_SECURE=) is treated as None so it never crashes startup.
|
||||
# Never key this off APP_ENV — a Secure cookie over plain HTTP is dropped and login
|
||||
# "doesn't stick", which is a miserable thing to debug.
|
||||
session_cookie_secure: bool | None = None
|
||||
|
||||
@field_validator("session_cookie_secure", mode="before")
|
||||
@classmethod
|
||||
def _blank_secure_is_auto(cls, v):
|
||||
if isinstance(v, str) and v.strip() == "":
|
||||
return None
|
||||
return v
|
||||
|
||||
# App tokens — named, revocable credentials for desktop/CLI clients, so those clients never
|
||||
# store a password. The window is an IDLE timeout: every use slides expires_at forward, so a
|
||||
# token in regular use keeps working while one that is exfiltrated and parked expires on its
|
||||
# own. Set false to switch the feature off entirely.
|
||||
app_tokens_enabled: bool = True
|
||||
app_token_idle_days: int = 30
|
||||
app_token_max_idle_days: int = 365
|
||||
# Don't write to the database on every request just to slide the expiry.
|
||||
app_token_renew_after_hours: int = 12
|
||||
|
||||
# CORS — empty by default (same-origin design). Comma-separated origins to allow a
|
||||
# separately-served console in dev.
|
||||
cors_allow_origins: str = ""
|
||||
|
||||
# Who may frame the console: 'none' (default; X-Frame-Options DENY) or 'self' (SAMEORIGIN, what
|
||||
# the platform's kit sets so Atrium can frame its modules same-origin). Anything else refuses
|
||||
# start-up: a third-party origin here would let a foreign site frame privileged data.
|
||||
frame_ancestors: str = "'none'"
|
||||
|
||||
# Bootstrap admin (seed)
|
||||
bootstrap_admin_email: str = "admin@example.com"
|
||||
bootstrap_admin_password: str = "admin12345"
|
||||
seed_demo: bool = True
|
||||
|
||||
# OpenTelemetry (opt-in)
|
||||
otel_enabled: bool = False
|
||||
otel_service_name: str = "agora-backend"
|
||||
otel_exporter_otlp_endpoint: str = "http://otel-collector:4317"
|
||||
|
||||
@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}'"
|
||||
|
||||
@property
|
||||
def shares_identity(self) -> bool:
|
||||
"""True when this deployment is a MODULE of the platform rather than a standalone app.
|
||||
|
||||
The single predicate everything switches on — the auth policy, the seed, the lifespan
|
||||
assertion, the moderator tier, the cutover revision, the console's sign-in card — so "do we
|
||||
share accounts?" is asked in one vocabulary, and a future second signal changes one line.
|
||||
"""
|
||||
return bool(self.identity_schema)
|
||||
|
||||
@property
|
||||
def is_production(self) -> bool:
|
||||
return self.app_env.lower() == "production"
|
||||
|
||||
@property
|
||||
def cors_origins_list(self) -> list[str]:
|
||||
return [o.strip() for o in self.cors_allow_origins.split(",") if o.strip()]
|
||||
|
||||
@property
|
||||
def exports_dir(self) -> Path:
|
||||
return Path(self.data_dir) / "exports"
|
||||
|
||||
|
||||
def _require_verified_tls(name: str, url: str, local_hosts: str) -> None:
|
||||
"""Refuse `url` unless its host is local or it carries sslmode=verify-full (the family's one TLS
|
||||
rule, dredd_core.db.require_verified_tls). The message names the host, never the password."""
|
||||
if not url.strip():
|
||||
return
|
||||
try:
|
||||
parsed = make_url(url)
|
||||
except (ArgumentError, ValueError):
|
||||
return # malformed: make_engine refuses it before anything connects
|
||||
try:
|
||||
require_verified_tls(parsed, local_hosts=local_hosts)
|
||||
except ValueError as exc:
|
||||
raise ValueError(f"{name}: {exc} (db/managed/README.md)") from exc
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_settings() -> Settings:
|
||||
return Settings()
|
||||
@@ -0,0 +1,47 @@
|
||||
"""SQLAlchemy engine + session factory (runtime `app` role, DML only).
|
||||
|
||||
The engine and the session factory come from **dredd-core**: `make_engine()` carries the family's
|
||||
connection settings — a bounded pre-pinged pool, `hide_parameters=True` so bound values can never
|
||||
leak into an exception message or a log line, and TLS: a managed database's URL carries
|
||||
`?sslmode=verify-full&sslrootcert=...`, which pg8000 cannot read itself, so `make_engine` turns it
|
||||
into a verifying TLS context (and refuses the modes that allow plaintext). Build every engine through
|
||||
it, never `create_engine`. `make_session_factory()` supplies the session options (no autoflush, no
|
||||
autocommit, `expire_on_commit=False`).
|
||||
|
||||
What stays here is this app's own: the URL it connects to, its pool size, and `get_db()`, the FastAPI
|
||||
dependency every router depends on. Each scaffolded app is its own deployment with its own database
|
||||
(its own schema and roles in the family's shared managed database) — core supplies the plumbing, not a
|
||||
shared connection.
|
||||
|
||||
That stays true even when the app becomes a module of a platform and shares the family's identity
|
||||
rows: a shared table is reached through the role's `search_path` on this same connection, as an
|
||||
unqualified name, not through a second engine or a cross-database link. So there is exactly one
|
||||
engine here, always, and nothing in the app is ever schema-qualified.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterator
|
||||
|
||||
from dredd_core.db import make_engine, make_session_factory
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from .config import get_settings
|
||||
|
||||
settings = get_settings()
|
||||
|
||||
# The runtime URL is the least-privilege `app` role (DML only). DDL runs under
|
||||
# MIGRATION_DATABASE_URL, which only Alembic ever opens. The pool is sized from config, because in
|
||||
# the family's shared managed database every app draws on one connection limit.
|
||||
engine = make_engine(settings.database_url, pool_size=settings.db_pool_size,
|
||||
max_overflow=settings.db_max_overflow)
|
||||
|
||||
SessionLocal = make_session_factory(engine)
|
||||
|
||||
|
||||
def get_db() -> Iterator[Session]:
|
||||
"""FastAPI dependency yielding a request-scoped session."""
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
@@ -0,0 +1,175 @@
|
||||
"""FastAPI dependencies: DB session, token extraction, current user, the two access guards.
|
||||
|
||||
Session resolution itself lives in `dredd_core.auth`; what stays here is the HTTP edge — reading
|
||||
the session cookie or the bearer header, and turning a resolved row into the current user of a
|
||||
module they are allowed to be in.
|
||||
|
||||
Which `session` table that row comes out of is one setting, not two designs. STANDALONE
|
||||
(IDENTITY_SCHEMA empty, the default) this app owns its accounts and its own `session` rows, so its
|
||||
cookie means something only here. As a MODULE of the platform the identity tables live in a schema
|
||||
the hub owns and every module reads, so the cookie somebody got by signing in at the hub is the
|
||||
cookie this app accepts — one origin, one cookie, one `session` row, nothing to hand over.
|
||||
|
||||
Widening a cookie to a parent domain was never the way there and still isn't: a sibling holding its
|
||||
OWN `session` rows simply rejects a token hash it has never seen, and signs the person out with
|
||||
extra steps. What makes it work is one origin plus one shared table, which is a migration and a
|
||||
grant tier (`alembic/versions/0003_shared_identity.py`, `db/managed/README.md`).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from fastapi import Depends, Request
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from .config import get_settings
|
||||
from .db import get_db
|
||||
from .enums import TokenScope
|
||||
from .errors import AuthenticationError, AuthorizationError
|
||||
from .models import AppUser
|
||||
from .services import auth as auth_service
|
||||
from .services import moderation as moderation_service
|
||||
|
||||
SESSION_COOKIE = get_settings().session_cookie_name
|
||||
|
||||
#: Cookie names this app has issued before and still accepts. Renaming the cookie at a cutover
|
||||
#: (`agora_session` → `dredd_session`, one name for the whole platform) would otherwise
|
||||
#: sign everybody out the moment the new container starts — the row behind the token is the same row
|
||||
#: either way, only the label on the jar changed. `routers/auth.py` deletes every legacy name on the
|
||||
#: next login or logout, so this clears itself rather than accumulating.
|
||||
LEGACY_SESSION_COOKIES = tuple(n for n in ("agora_session",) if n != SESSION_COOKIE)
|
||||
|
||||
|
||||
def _bearer_token(request: Request) -> str | None:
|
||||
header = request.headers.get("authorization") or ""
|
||||
if header.lower().startswith("bearer "):
|
||||
return header[7:].strip() or None
|
||||
return None
|
||||
|
||||
|
||||
def extract_token(request: Request) -> str | None:
|
||||
"""Authorization: Bearer takes precedence over the session cookie (intentional > ambient)."""
|
||||
token = _bearer_token(request) or request.cookies.get(SESSION_COOKIE)
|
||||
if token:
|
||||
return token
|
||||
for legacy in LEGACY_SESSION_COOKIES:
|
||||
token = request.cookies.get(legacy)
|
||||
if token:
|
||||
return token
|
||||
return None
|
||||
|
||||
|
||||
def client_ip(request: Request) -> str | None:
|
||||
host = request.client.host if request.client else None
|
||||
if not host:
|
||||
return None
|
||||
try:
|
||||
ipaddress.ip_address(host)
|
||||
except ValueError:
|
||||
return None
|
||||
return host
|
||||
|
||||
|
||||
# Methods a read-scoped credential may use. Anything else mutates state.
|
||||
SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS"})
|
||||
|
||||
|
||||
def refuse_cross_site_write(request: Request) -> None:
|
||||
"""A state-changing request that rides on the ambient cookie must come from this site.
|
||||
|
||||
SameSite=Lax stops other *sites*, but not a same-site sibling — an app on one subdomain
|
||||
can POST to another with the admin's cookie attached. Registered once as an app-wide
|
||||
dependency (`main.py`), so every unsafe route is covered, login and logout included, and no new
|
||||
route can forget it. Two signals, in order:
|
||||
|
||||
* `Sec-Fetch-Site` — sent for potentially trustworthy (HTTPS or localhost) origins; older Safari
|
||||
never sends it. Anything but same-origin (or a user-typed `none`) is refused.
|
||||
* `Origin` — sent on every cross-origin POST, over plain HTTP too. Refused when it is the opaque
|
||||
`null`, or names a host other than this request's own, unless it is one of the configured
|
||||
`CORS_ALLOW_ORIGINS` (a separately served console is a deliberate, trusted origin).
|
||||
|
||||
A bearer token is intentional rather than ambient, so it is exempt. A client that sends neither
|
||||
header (curl, the test client) is not a browser being tricked.
|
||||
|
||||
Under a path prefix on a shared origin (ROOT_PATH set), a sibling module's console is
|
||||
*same-origin* with this one, so both signals pass and this guard no longer separates the modules
|
||||
— only the platform from genuinely foreign sites. That is deliberate: one origin is what one
|
||||
account buys. Write-level isolation between modules comes from authz on the shared identity, not
|
||||
from the origin; don't reintroduce an origin check that cannot distinguish them. And never add an
|
||||
entry to CORS_ALLOW_ORIGINS on such a deployment — the early return below trusts it outright.
|
||||
"""
|
||||
if request.method.upper() in SAFE_METHODS or _bearer_token(request):
|
||||
return
|
||||
raw_origin = request.headers.get("origin")
|
||||
origin = (raw_origin or "").strip()
|
||||
if origin and origin in get_settings().cors_origins_list:
|
||||
return
|
||||
site = request.headers.get("sec-fetch-site")
|
||||
if site is not None and site.lower() not in ("same-origin", "none"):
|
||||
raise AuthorizationError("Cross-site request refused.")
|
||||
if raw_origin is not None: # present but blank is malformed, not absent: it names no host
|
||||
try:
|
||||
theirs = urlsplit(raw_origin).netloc.lower()
|
||||
except ValueError:
|
||||
theirs = ""
|
||||
own = (request.headers.get("host") or "").lower()
|
||||
if origin.lower() == "null" or not own or theirs != own:
|
||||
raise AuthorizationError("Cross-site request refused.")
|
||||
|
||||
|
||||
def get_current_user(request: Request, db: Session = Depends(get_db)) -> AppUser:
|
||||
token = extract_token(request)
|
||||
if not token:
|
||||
raise AuthenticationError("Sign in to continue.")
|
||||
resolved = auth_service.resolve_session_full(db, token)
|
||||
if resolved is None:
|
||||
raise AuthenticationError("Your session has expired — please sign in again.")
|
||||
user, credential = resolved
|
||||
|
||||
# Scope is enforced HERE and nowhere else. Every authenticated route depends on this
|
||||
# function, so one check covers all of them and no future route can forget it. Scope narrows
|
||||
# what a credential may do; it never widens it — the caller's own roles are still checked by
|
||||
# services/authz.py afterwards.
|
||||
if credential.scope == TokenScope.read.value and request.method.upper() not in SAFE_METHODS:
|
||||
raise AuthorizationError("This app token is read-only. Create a read/write token instead.")
|
||||
|
||||
# And, for exactly the same reason, the other question every authenticated route has to ask:
|
||||
# may this person open this module AT ALL? On the platform a session is a PLATFORM session —
|
||||
# one account across every module — so holding one says nothing about being admitted to this
|
||||
# one. Admission is a `module_permission` row naming this app's slug, granted in the hub, and
|
||||
# NO ROW MEANS NO ENTRY. Without this a stranger with an account reaches every screen here:
|
||||
# they see nothing and can write nothing, but nothing has refused them, and "you can see
|
||||
# nothing" is not an access decision — it is the absence of one, one empty result at a time.
|
||||
#
|
||||
# Unconditional, and it has to stay that way. Standalone this costs nothing and refuses nobody:
|
||||
# with no shared identity store core answers `"user"` for everybody without emitting a query,
|
||||
# because there is one app here and nothing to be admitted to. That is what lets one guard sit
|
||||
# at the edge of both shapes with no second code path — so never make it depend on
|
||||
# `shares_identity`.
|
||||
moderation_service.assert_may_use(db, user)
|
||||
|
||||
request.state.credential_id = credential.id
|
||||
request.state.credential_kind = credential.kind
|
||||
return user
|
||||
|
||||
|
||||
def require_moderator(db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> AppUser:
|
||||
"""This app's administration: a platform ADMINISTRATOR, or a MODERATOR of this module.
|
||||
|
||||
The narrower of the two guards. `get_current_user` has already asked whether this person may be
|
||||
in this module at all; this asks whether they may administer it.
|
||||
|
||||
The successor to `require_admin`, and the same shape — only the predicate widened. STANDALONE it
|
||||
IS the old check: `services/moderation` short-circuits to `user.is_admin` and emits no SQL, so a
|
||||
single-tenant deployment is byte-for-byte unchanged and never queries a table it may not have.
|
||||
|
||||
**A module deliberately defines no `require_administrator`.** Once accounts live in the hub,
|
||||
every power left here is module-scoped — settings, this app's own data, access inside it — while
|
||||
the platform-wide ones (accounts, passwords, sessions, the module catalogue) moved to the hub. A
|
||||
route here guarded by the platform-wide tier would only mean "a moderator may not do the thing
|
||||
they were made a moderator to do". A grep for `is_admin` under `app/routers/` should come back
|
||||
empty: the only permitted readers of that column are dredd-core and the hub.
|
||||
"""
|
||||
return moderation_service.assert_moderator(db, user)
|
||||
@@ -0,0 +1,211 @@
|
||||
"""This backend's own edge: security headers, the body cap, the console.
|
||||
|
||||
There is no reverse proxy. Standalone, docker-compose.yml publishes uvicorn directly; on the Dredd
|
||||
platform Atrium's backend is the front door (its `app/frontdoor.py`) and forwards `/agora/*`
|
||||
here with the prefix stripped, and uvicorn's `--root-path "$ROOT_PATH"` puts it back. Either way this
|
||||
process answers for everything a browser gets. Same shape as the family modules' `app/edge.py`.
|
||||
|
||||
**Every path comparison reads the ROUTE path** (`starlette._utils.get_route_path`), never
|
||||
`request.url.path` / `scope["path"]`: with ROOT_PATH=/agora uvicorn re-prepends the prefix, so
|
||||
the raw path reads `/agora/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; everything else is the static console. Nothing under these is ever
|
||||
# answered by the console.
|
||||
API_PATHS = ("/api", "/healthz")
|
||||
|
||||
# The ceiling for one request body. It bounds memory; it does not shape the API.
|
||||
MAX_BODY_BYTES = 100 * 1024 * 1024
|
||||
|
||||
# Content-Security-Policy for the console. 'unsafe-inline' is required by the theme pre-paint inline
|
||||
# <script> in index.html, the inline onclick handlers app.js renders, and inline style=""
|
||||
# attributes. Nothing loads from a CDN — the console is entirely same-origin, which is the point
|
||||
# when the data is privileged. `frame-ancestors` comes from settings.frame_ancestors (FRAME_ANCESTORS):
|
||||
# 'none' by default, 'self' on the platform, where Atrium's front door frames its modules same-origin.
|
||||
def content_security_policy(frame_ancestors: str) -> str:
|
||||
return (
|
||||
f"default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors {frame_ancestors}; "
|
||||
"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'"
|
||||
)
|
||||
|
||||
|
||||
# The default ('none') policy, pinned by tests/test_edge.py.
|
||||
CONSOLE_CSP = content_security_policy("'none'")
|
||||
|
||||
|
||||
def owns_path(path: str) -> bool:
|
||||
return any(path == p or path.startswith(f"{p}/") for p in API_PATHS)
|
||||
|
||||
|
||||
def _problem(scope: Scope, status: int, error_type: str, title: str, detail: str,
|
||||
headers: dict[str, str] | None = None) -> JSONResponse:
|
||||
# The same RFC 9457 shape app/errors.py builds for every other refusal.
|
||||
return JSONResponse(
|
||||
{"type": error_type, "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:
|
||||
"""The security headers, on every response — console, API, 404, 405, 413 and 500 alike.
|
||||
|
||||
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.
|
||||
|
||||
Everywhere: nosniff, `X-Frame-Options` (DENY for FRAME_ANCESTORS='none', SAMEORIGIN for 'self'), `Referrer-Policy: same-origin`,
|
||||
`Cross-Origin-Opener-Policy: same-origin`. On the console only (anything outside /api and
|
||||
/healthz): the CSP and `Cache-Control: no-cache` (revalidate by ETag, so a rebuilt app.js/app.css
|
||||
is picked up without a hard refresh). Defaults only: a header a route already set wins. The
|
||||
`Server` header is not removed here; uvicorn runs with --no-server-header.
|
||||
"""
|
||||
|
||||
def __init__(self, app: ASGIApp, *, frame_ancestors: str = "'none'") -> None:
|
||||
self.app = app
|
||||
self.csp = content_security_policy(frame_ancestors)
|
||||
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.setdefault("X-Content-Type-Options", "nosniff")
|
||||
headers.setdefault("X-Frame-Options", self.xfo)
|
||||
headers.setdefault("Referrer-Policy", "same-origin")
|
||||
headers.setdefault("Cross-Origin-Opener-Policy", "same-origin")
|
||||
if console:
|
||||
headers.setdefault("Cache-Control", "no-cache")
|
||||
headers.setdefault("Content-Security-Policy", self.csp)
|
||||
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", "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):
|
||||
"""The SPA fallback: 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."""
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
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", "Method Not Allowed",
|
||||
"That method is not allowed on this path.",
|
||||
headers={"Allow": ", ".join(sorted(allowed))})
|
||||
else:
|
||||
response = _problem(scope, 404, "not_found", "Resource not found",
|
||||
"No API route matches this path.")
|
||||
await response(scope, receive, send)
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Enum labels: the shared ones re-exported from dredd-core, Agora's own below the divider.
|
||||
|
||||
`SessionKind` and `TokenScope` describe the credentials core's auth service issues; they are
|
||||
declared in **dredd-core** and re-exported here so every call site keeps importing
|
||||
`from ..enums import TokenScope`. (`dredd_core.enums` also carries `NodeRole`, `PrincipalType`,
|
||||
`ReviewPolicy` and `EncryptionMode`; this flat, single-tenant app has no use for them — the
|
||||
org-tree tables it inherits from core stay empty — but they are there if it ever grows one.)
|
||||
|
||||
The `.value` strings are the canonical DB enum labels. Native enum *types* are not created here:
|
||||
migration 0001 calls `create_enum_types(conn)` before `Base.metadata.create_all(...)`, which
|
||||
builds core's types and this app's own from the model metadata (the columns use
|
||||
`create_type=False`, so the types must exist first).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from enum import StrEnum
|
||||
|
||||
from dredd_core.enums import SessionKind, TokenScope
|
||||
|
||||
# NOTE: SessionKind and TokenScope back plain Text columns, NOT native PG enums — core's choice,
|
||||
# and a deliberate one: a credential vocabulary that grows (a new scope, a new kind) then needs no
|
||||
# type surgery on a live database.
|
||||
|
||||
|
||||
# ── Agora's own ────────────────────────────────────────────────────────
|
||||
# Demo enum for the `example` entity. Replace it with the real domain. A new enum needs no edit to
|
||||
# the migration: declare it here, bind it with `pg_enum(MyEnum, "my_enum")` on the model, and make
|
||||
# sure the model is imported in `app/models/__init__.py` — `create_enum_types` reads it from the
|
||||
# metadata, and the table itself is picked up by `create_all`.
|
||||
class RecordStatus(StrEnum):
|
||||
open = "open"
|
||||
done = "done"
|
||||
|
||||
|
||||
__all__ = [
|
||||
# from dredd-core, unchanged
|
||||
"SessionKind",
|
||||
"TokenScope",
|
||||
# this app's own
|
||||
"RecordStatus",
|
||||
]
|
||||
@@ -0,0 +1,102 @@
|
||||
"""RFC 9457 Problem Details errors + handlers/middleware.
|
||||
|
||||
The exception classes come from **dredd-core** (`dredd_core.errors`) so every app in the family
|
||||
raises — and every client parses — one error shape. They are re-exported here, so services and
|
||||
routers keep importing `from ..errors import NotFoundError` and nothing downstream changes.
|
||||
|
||||
The wiring below stays app-side on purpose: it needs this app's settings (stack traces are hidden
|
||||
when APP_ENV=production) and its logger name, and an app may add its own error class. DB DataError
|
||||
maps to 422 (not 500) — bad input is the client's problem, and returning 500 for it sends people
|
||||
debugging the wrong side.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from dredd_core.errors import (
|
||||
AppError,
|
||||
AuthenticationError,
|
||||
AuthorizationError,
|
||||
ConflictError,
|
||||
NotFoundError,
|
||||
ValidationError,
|
||||
)
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from sqlalchemy.exc import DataError, IntegrityError
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
|
||||
from .config import get_settings
|
||||
|
||||
log = logging.getLogger("agora.errors")
|
||||
settings = get_settings()
|
||||
_PROBLEM = "application/problem+json"
|
||||
|
||||
|
||||
class UpstreamError(AppError):
|
||||
"""A dependency (another service, an external API) failed. Distinct from our own 500 so the
|
||||
console can say which side broke and offer a retry.
|
||||
|
||||
An app-side subclass like this one is the normal way to extend the set: subclass `AppError`,
|
||||
give it a status and a title, and the handler below serves it without further wiring."""
|
||||
status_code = 502
|
||||
title = "Bad Gateway"
|
||||
|
||||
|
||||
def _problem(status: int, title: str, detail: str, extra: dict | None = None) -> JSONResponse:
|
||||
body = {"type": "about:blank", "title": title, "status": status, "detail": detail}
|
||||
if extra:
|
||||
body.update(extra)
|
||||
return JSONResponse(status_code=status, content=body, media_type=_PROBLEM)
|
||||
|
||||
|
||||
def install_error_handlers(app: FastAPI) -> None:
|
||||
@app.exception_handler(AppError)
|
||||
async def _app_error(_: Request, exc: AppError):
|
||||
return _problem(exc.status_code, exc.title, exc.detail, exc.extra)
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def _http_error(_: Request, exc: StarletteHTTPException):
|
||||
return _problem(exc.status_code, str(exc.detail) or "Error", str(exc.detail))
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def _validation_error(_: Request, exc: RequestValidationError):
|
||||
return _problem(422, "Unprocessable Entity", "Request validation failed.",
|
||||
{"errors": exc.errors()})
|
||||
|
||||
@app.exception_handler(DataError)
|
||||
async def _data_error(_: Request, __: DataError):
|
||||
return _problem(422, "Unprocessable Entity", "Invalid data for one or more fields.")
|
||||
|
||||
@app.exception_handler(IntegrityError)
|
||||
async def _integrity_error(_: Request, __: IntegrityError):
|
||||
return _problem(409, "Conflict", "That conflicts with an existing record.")
|
||||
|
||||
|
||||
class ProblemDetailErrorMiddleware(BaseHTTPMiddleware):
|
||||
"""Last-resort catch for unhandled exceptions → RFC 9457 500 (added INSIDE CORS)."""
|
||||
|
||||
async def dispatch(self, request: Request, call_next):
|
||||
try:
|
||||
return await call_next(request)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
log.exception("Unhandled error")
|
||||
detail = "An unexpected error occurred." if settings.is_production else str(exc)
|
||||
return _problem(500, "Internal Server Error", detail)
|
||||
|
||||
|
||||
__all__ = [
|
||||
# from dredd-core, unchanged
|
||||
"AppError",
|
||||
"AuthenticationError",
|
||||
"AuthorizationError",
|
||||
"NotFoundError",
|
||||
"ConflictError",
|
||||
"ValidationError",
|
||||
# this app's own
|
||||
"UpstreamError",
|
||||
"install_error_handlers",
|
||||
"ProblemDetailErrorMiddleware",
|
||||
]
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Structured-ish logging with no dependency.
|
||||
|
||||
Request bodies and bound SQL parameters are deliberately never logged — the engine is built with
|
||||
`hide_parameters=True` for the same reason. A log that quietly accumulates row data is a second
|
||||
copy of the database with none of its access controls.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import sys
|
||||
|
||||
from .config import get_settings
|
||||
|
||||
_FORMAT = "%(asctime)s %(levelname)-7s %(name)s: %(message)s"
|
||||
|
||||
|
||||
def configure_logging() -> None:
|
||||
settings = get_settings()
|
||||
level = logging.INFO if settings.is_production else logging.DEBUG
|
||||
root = logging.getLogger()
|
||||
if root.handlers: # uvicorn may have configured it already
|
||||
return
|
||||
handler = logging.StreamHandler(sys.stdout)
|
||||
handler.setFormatter(logging.Formatter(_FORMAT))
|
||||
root.addHandler(handler)
|
||||
root.setLevel(level)
|
||||
# SQL echo is off even in development: it prints values.
|
||||
logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
|
||||
@@ -0,0 +1,144 @@
|
||||
"""FastAPI application entrypoint."""
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import logging
|
||||
import os
|
||||
from collections.abc import AsyncIterator
|
||||
from pathlib import Path
|
||||
|
||||
from dredd_core.identity_schema import IdentitySchemaError, assert_identity_schema
|
||||
from fastapi import Depends, FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.middleware.gzip import GZipMiddleware
|
||||
from sqlalchemy import text
|
||||
|
||||
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
|
||||
from .routers import admin, auth, dashboard, example, health, users
|
||||
|
||||
API_PREFIX = "/api/v1"
|
||||
|
||||
settings = get_settings()
|
||||
configure_logging()
|
||||
log = logging.getLogger("agora")
|
||||
|
||||
|
||||
@contextlib.asynccontextmanager
|
||||
async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
|
||||
"""Prove the shared identity tables are where they must be, before serving one request.
|
||||
|
||||
The one guard against the failure mode with 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 in a schema its
|
||||
migrator does not own. The entire cost of that correct choice is this: with
|
||||
`search_path = agora, dredd, extensions`, an unqualified `app_user` resolves
|
||||
to **`agora.app_user` if one exists**, and everything keeps working. You are simply back
|
||||
to two rows per human, silently — which is the exact defect sharing identity exists to end.
|
||||
|
||||
A stray `create_all`, a restored single-schema dump, or a fresh install whose cutover revision
|
||||
has not run yet all produce it. `python -m dredd_core.managed check --identity-schema` catches it
|
||||
at deploy time; only a boot assertion catches it after a restore, which is the moment it is most
|
||||
likely and least expected. So it runs on every start, it is not optional, and failing it is meant
|
||||
to stop the container: a module quietly authenticating against its own private copy of everyone
|
||||
is worse than a module 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 nothing.
|
||||
"""
|
||||
if settings.shares_identity:
|
||||
with engine.connect() as conn:
|
||||
own = conn.scalar(text("SELECT current_schema()")) or ""
|
||||
try:
|
||||
assert_identity_schema(conn, own_schema=own,
|
||||
identity_schema=settings.identity_schema)
|
||||
except IdentitySchemaError as exc:
|
||||
# Core names the problem; this names the way out, because there is one specific way
|
||||
# to arrive here that looks like a bug and is not. Revision 0003 is a **no-op when
|
||||
# IDENTITY_SCHEMA is empty**, so a deployment that upgraded to head first and set
|
||||
# IDENTITY_SCHEMA afterwards is at 0003 with its local identity tables intact, and
|
||||
# `alembic upgrade head` will cheerfully say there is nothing to do. The fix is to
|
||||
# put the version back and run the revision with the setting in place.
|
||||
raise RuntimeError(
|
||||
f"{exc} If this app was upgraded to head BEFORE IDENTITY_SCHEMA was set, the "
|
||||
"cutover ran as a no-op and Alembic now thinks it is done: run "
|
||||
"`alembic stamp 0002 && alembic upgrade head` with IDENTITY_SCHEMA set, which "
|
||||
"re-runs it. (It is idempotent, so that is safe on a database that has already "
|
||||
"been converted.)"
|
||||
) from exc
|
||||
log.info("Shared identity schema %s: every identity table resolves there",
|
||||
settings.identity_schema)
|
||||
yield
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="Agora API",
|
||||
version=__version__,
|
||||
description="A self-hosted management console.",
|
||||
docs_url=f"{API_PREFIX}/docs",
|
||||
redoc_url=None,
|
||||
openapi_url=f"{API_PREFIX}/openapi.json",
|
||||
# The path prefix the platform's front door strips before the request reaches us. Empty (the
|
||||
# default) = served at the origin root; ROOT_PATH=/agora mounts this app under a path
|
||||
# prefix of a shared origin. Routes stay un-prefixed either way — FastAPI needs it only to emit correct
|
||||
# absolute URLs (the OpenAPI `servers` entry, the /docs asset links). uvicorn gets the same value
|
||||
# on its command line (backend/Dockerfile), so scope["root_path"] agrees however the app is run.
|
||||
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)
|
||||
|
||||
# The request-body cap (100 MB, app/edge.py). Innermost, 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)
|
||||
|
||||
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=["*"],
|
||||
)
|
||||
|
||||
for router in (
|
||||
health.router, auth.router, users.router, admin.router,
|
||||
example.router, dashboard.router,
|
||||
):
|
||||
app.include_router(router, prefix=API_PREFIX)
|
||||
|
||||
|
||||
@app.get("/healthz")
|
||||
def healthz() -> dict:
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
# Gzip (>= 1000 bytes). Inside SecurityHeaders, so compressed responses carry the headers too.
|
||||
app.add_middleware(GZipMiddleware, minimum_size=1000)
|
||||
# The security headers (app/edge.py). 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)
|
||||
|
||||
# The static console — this backend serves it itself; there is no reverse proxy. Mounted at "/"
|
||||
# LAST so every API route wins, behind ConsoleUnlessApi so /api/* and /healthz never fall through
|
||||
# to it (see its docstring), with the index.html SPA fallback. AGORA_FRONTEND_DIR
|
||||
# overrides the location; the default is the repo's ../frontend, which is also where
|
||||
# backend/Dockerfile copies it (/frontend in the image).
|
||||
_FRONTEND = Path(os.environ.get("AGORA_FRONTEND_DIR")
|
||||
or Path(__file__).resolve().parents[2] / "frontend")
|
||||
if _FRONTEND.is_dir():
|
||||
app.mount("/", ConsoleUnlessApi(SpaStaticFiles(directory=str(_FRONTEND), html=True),
|
||||
app.routes), name="console")
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Every model must be imported here.
|
||||
|
||||
The migration builds tables from `Base.metadata`, so a model that is never imported silently
|
||||
never gets a table — and the failure surfaces much later, as a missing relation at runtime.
|
||||
|
||||
The identity tables (`app_user`, `session`, `module_permission`, `app_setting`, `audit_log`) are not
|
||||
defined here: they live in **dredd-core**, and importing `dredd_core` is what registers them on
|
||||
`Base.metadata`. This module re-exports them under the names the rest of the app already uses,
|
||||
so every call site stays `from ..models import AppUser` regardless of where the class is
|
||||
declared.
|
||||
|
||||
Three of those names — `AppUser`, `Session` and `ModulePermission`, which is what
|
||||
`dredd_core.identity.SHARED_IDENTITY_TABLES` holds — belong to the PLATFORM once IDENTITY_SCHEMA is
|
||||
set: the hub owns them in a neutral schema and this app reads them. They stay on this metadata
|
||||
either way, because the ORM has to map a table to query it; what changes is which schema resolves
|
||||
them and which code paths may write them. `own_tables(Base.metadata, shared=SHARED_IDENTITY_TABLES)`
|
||||
is how a caller that must treat them differently — a backup sweep, say — draws that line.
|
||||
|
||||
This app is flat (single-tenant), so it does not import or use the org tree — but importing
|
||||
`dredd_core` registers those models too, which means `node`, `permission_grant` and `favorite`
|
||||
are still created by the migration. They stay empty and unused; that is expected, not a bug.
|
||||
Leave them alone rather than trying to drop them — a later move to tree tenancy just starts
|
||||
using them.
|
||||
|
||||
Add your own models next to `.example` and import them below.
|
||||
"""
|
||||
from dredd_core import (
|
||||
AppSetting,
|
||||
AppUser,
|
||||
AuditLog,
|
||||
Base,
|
||||
ModulePermission,
|
||||
SafeInet,
|
||||
Session,
|
||||
TimestampMixin,
|
||||
UUIDPkMixin,
|
||||
pg_enum,
|
||||
)
|
||||
|
||||
from .example import Record
|
||||
|
||||
# ── evidence tables: what the runtime role may never rewrite ──────────────────────────────────────
|
||||
# The runtime-grants migration (alembic/versions/0002_runtime_grants.py, and every later revision
|
||||
# that creates a table) passes these to dredd_core.schema.runtime_grants_sql, which first grants the
|
||||
# runtime role DML on ALL tables and then takes these privileges back — so a table missing here is
|
||||
# fully writable, and a misspelt name is skipped silently (tests/test_migration_parity.py checks each
|
||||
# one is a real table). `python -m dredd_core.managed check` must be given the same lists
|
||||
# (--append-only / --no-delete). Changing them on a deployed database needs a new revision that
|
||||
# re-applies the grants.
|
||||
#: The runtime role may INSERT and SELECT, never UPDATE, DELETE or TRUNCATE.
|
||||
APPEND_ONLY_TABLES: tuple[str, ...] = ("audit_log",)
|
||||
#: The runtime role may never DELETE or TRUNCATE (a decision that must survive; supersede it instead).
|
||||
NO_DELETE_TABLES: tuple[str, ...] = ()
|
||||
|
||||
__all__ = [
|
||||
"Base", "TimestampMixin", "UUIDPkMixin", "SafeInet", "pg_enum",
|
||||
# Who may use this module, and who administers it. This app only ever READS those rows
|
||||
# (`services/moderation.py`), and on the platform they do not even live in this schema —
|
||||
# but the table is on `Base.metadata`, so it has to be re-exported here or `own_tables(...,
|
||||
# shared=SHARED_IDENTITY_TABLES)` would be excluding a name this app never imported.
|
||||
"AppUser", "Session", "ModulePermission", "AppSetting", "AuditLog",
|
||||
"Record",
|
||||
"APPEND_ONLY_TABLES", "NO_DELETE_TABLES",
|
||||
]
|
||||
@@ -0,0 +1,27 @@
|
||||
"""The demo domain entity — a worked seam to copy, then delete."""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import ForeignKey, Index, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from dredd_core import Base, TimestampMixin, UUIDPkMixin, pg_enum
|
||||
|
||||
from ..enums import RecordStatus
|
||||
|
||||
|
||||
class Record(UUIDPkMixin, TimestampMixin, Base):
|
||||
__tablename__ = "record"
|
||||
|
||||
name: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
note: Mapped[str | None] = mapped_column(Text)
|
||||
status: Mapped[RecordStatus] = mapped_column(
|
||||
pg_enum(RecordStatus, "record_status"), nullable=False
|
||||
)
|
||||
# Who may act on the row, in the absence of a permission tree. Services check this; the
|
||||
# instance admin bypasses it.
|
||||
owner_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
|
||||
created_by: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
|
||||
|
||||
__table_args__ = (Index("ix_record_status", "status"),)
|
||||
@@ -0,0 +1,39 @@
|
||||
"""OpenTelemetry, opt-in and import-guarded.
|
||||
|
||||
Off by default and wrapped in a try/except on purpose: telemetry is an operator's choice, and a
|
||||
missing exporter must never be the reason the application refuses to start.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from .config import get_settings
|
||||
|
||||
log = logging.getLogger("agora.observability")
|
||||
|
||||
|
||||
def setup_observability(app, engine) -> None:
|
||||
settings = get_settings()
|
||||
if not settings.otel_enabled:
|
||||
return
|
||||
try:
|
||||
from opentelemetry import trace
|
||||
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
|
||||
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
|
||||
from opentelemetry.instrumentation.sqlalchemy import SQLAlchemyInstrumentor
|
||||
from opentelemetry.sdk.resources import Resource
|
||||
from opentelemetry.sdk.trace import TracerProvider
|
||||
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
||||
|
||||
provider = TracerProvider(
|
||||
resource=Resource.create({"service.name": settings.otel_service_name})
|
||||
)
|
||||
provider.add_span_processor(
|
||||
BatchSpanProcessor(OTLPSpanExporter(endpoint=settings.otel_exporter_otlp_endpoint))
|
||||
)
|
||||
trace.set_tracer_provider(provider)
|
||||
FastAPIInstrumentor.instrument_app(app)
|
||||
SQLAlchemyInstrumentor().instrument(engine=engine)
|
||||
log.info("OpenTelemetry enabled → %s", settings.otel_exporter_otlp_endpoint)
|
||||
except Exception: # noqa: BLE001
|
||||
log.warning("OTEL_ENABLED is set but OpenTelemetry could not start", exc_info=True)
|
||||
@@ -0,0 +1 @@
|
||||
"""HTTP routers. Validation, authz calls and response shaping only — no SQL."""
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Administration: instance settings and the audit log.
|
||||
|
||||
The audit log is readable here and nowhere else, and it is read-only everywhere — the runtime DB
|
||||
role has no UPDATE or DELETE on it, so this is not a matter of the router being polite.
|
||||
|
||||
Every endpoint here requires this module's administration tier — a platform ADMINISTRATOR, or a
|
||||
MODERATOR of this module (`deps.require_moderator`). None of it is platform-wide: these routes
|
||||
configure this app's own settings and read its own history, which is exactly the set a module keeps
|
||||
when accounts move to the hub. STANDALONE, "moderator" resolves to `is_admin` and this is the same
|
||||
guard it always was.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, Query, Request
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..db import get_db
|
||||
from ..deps import client_ip, get_current_user, require_moderator
|
||||
from ..models import AppUser
|
||||
from ..schemas import SettingsIn
|
||||
from ..services import audit, audit_log
|
||||
from ..services import settings as settings_service
|
||||
|
||||
router = APIRouter(tags=["admin"])
|
||||
|
||||
|
||||
@router.get("/config")
|
||||
def config(db: Session = Depends(get_db), _: AppUser = Depends(get_current_user)) -> dict:
|
||||
"""What the console needs to render itself. Never secrets — this is a signed-in user's view
|
||||
of the instance, not the operator's."""
|
||||
return {"settings": settings_service.public_config(db)}
|
||||
|
||||
|
||||
@router.get("/admin/settings")
|
||||
def read_settings(db: Session = Depends(get_db), _: AppUser = Depends(require_moderator)) -> list[dict]:
|
||||
return settings_service.describe(db)
|
||||
|
||||
|
||||
@router.put("/admin/settings")
|
||||
def update_settings(body: SettingsIn, request: Request, db: Session = Depends(get_db),
|
||||
admin: AppUser = Depends(require_moderator)) -> list[dict]:
|
||||
changed = settings_service.update(db, body.values, actor_id=admin.id)
|
||||
if changed:
|
||||
audit.record(db, action="setting.update", entity_type="app_setting", actor_id=admin.id,
|
||||
detail=", ".join(sorted(changed)), ip=client_ip(request), diff=changed)
|
||||
db.commit()
|
||||
return settings_service.describe(db)
|
||||
|
||||
|
||||
@router.get("/admin/audit")
|
||||
def read_audit(db: Session = Depends(get_db), _: AppUser = Depends(require_moderator),
|
||||
limit: int = Query(100, ge=1, le=500), offset: int = Query(0, ge=0),
|
||||
action: str | None = Query(None, max_length=64)) -> list[dict]:
|
||||
return audit_log.list_entries(db, limit=limit, offset=offset, action=action)
|
||||
@@ -0,0 +1,143 @@
|
||||
"""Login, logout, and "who am I".
|
||||
|
||||
The session cookie is the primary credential for the console; the same token is also returned in
|
||||
the body so a non-browser client can send it as a bearer. Both resolve through the one
|
||||
`session` table, so revocation covers both.
|
||||
|
||||
**Where people sign in depends on one setting, and only on that one.** STANDALONE (IDENTITY_SCHEMA
|
||||
empty, the default) it is here: this app owns its accounts and this file is the whole of it. As a
|
||||
MODULE of the platform it is at the hub — one origin means one cookie, so the session created at
|
||||
`/atrium/` arrives on every request to this module and `resolve_session_full` finds the same row.
|
||||
There is nothing to hand over, no assertion to sign and no audience to bind: the entire single
|
||||
sign-on mechanism is that both paths are the same site.
|
||||
|
||||
So `POST /auth/login` is switched OFF on the platform rather than left to fail. This module's
|
||||
database role cannot read `password_hash` — it is not in the column grant — `authenticate` returns
|
||||
None before it reads anything, and a login form that answers "incorrect email or password" to a
|
||||
*correct* password is the worst possible way to tell somebody their account moved. It answers 404
|
||||
with the address instead. `/logout` stays, and signing out here signs you out of the platform, which
|
||||
is what one account means and is said out loud on the screen the button is on.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, Request, Response
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..config import get_settings
|
||||
from ..db import get_db
|
||||
from ..deps import (
|
||||
LEGACY_SESSION_COOKIES,
|
||||
SESSION_COOKIE,
|
||||
client_ip,
|
||||
extract_token,
|
||||
get_current_user,
|
||||
)
|
||||
from ..errors import AuthenticationError, NotFoundError
|
||||
from ..models import AppUser
|
||||
from ..schemas import LoginIn, LoginOut, UserOut
|
||||
from ..services import audit
|
||||
from ..services import auth as auth_service
|
||||
from ..services import moderation as moderation_service
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||
settings = get_settings()
|
||||
|
||||
|
||||
def _secure_flag(request: Request) -> bool:
|
||||
"""Secure only over HTTPS unless forced. Keying this off APP_ENV instead is a classic
|
||||
own-goal: a Secure cookie sent over plain HTTP is dropped, and the symptom is a login that
|
||||
silently "doesn't stick" with nothing in the logs."""
|
||||
if settings.session_cookie_secure is not None:
|
||||
return settings.session_cookie_secure
|
||||
return request.url.scheme == "https"
|
||||
|
||||
|
||||
def _user_out(user: AppUser, *, is_moderator: bool | None = None) -> dict:
|
||||
"""The person, as the console sees them, in both administration tiers.
|
||||
|
||||
`is_admin` is the platform-wide ADMINISTRATOR — one boolean on the account, the hub's to grant.
|
||||
`is_moderator` is "may administer THIS module": an administrator, or somebody the hub named a
|
||||
moderator of this app. Resolving it costs a query, so a caller that already knows passes it; the
|
||||
default is the honest standalone answer, where the two tiers are the same thing.
|
||||
|
||||
Both keys are always present. The console draws its Administration nav from `is_moderator`, and
|
||||
a key that sometimes vanishes is how that quietly becomes "false" for everyone.
|
||||
"""
|
||||
return {"id": str(user.id), "email": user.email, "full_name": user.full_name,
|
||||
"is_admin": user.is_admin, "is_active": user.is_active,
|
||||
"is_moderator": user.is_admin if is_moderator is None else bool(is_moderator)}
|
||||
|
||||
|
||||
def _hub_address() -> str:
|
||||
"""Where to send somebody who tried to sign in here, phrased for a message, never a link."""
|
||||
return settings.identity_hub_url or "the hub"
|
||||
|
||||
|
||||
def _clear_legacy_cookies(response: Response, request: Request) -> None:
|
||||
"""Delete any session cookie this app used to issue under a different name.
|
||||
|
||||
One line of tidying that matters at exactly one moment: a cutover renames the cookie to the
|
||||
platform's, and a browser holding both would keep offering whichever the header listed first,
|
||||
for ever. `deps.extract_token` still READS the old name, so nobody is signed out by the rename;
|
||||
this is what makes that transitional read self-clearing rather than permanent.
|
||||
"""
|
||||
for legacy in LEGACY_SESSION_COOKIES:
|
||||
response.delete_cookie(legacy, path="/", samesite="lax",
|
||||
secure=_secure_flag(request), httponly=True)
|
||||
|
||||
|
||||
@router.post("/login", response_model=LoginOut)
|
||||
def login(body: LoginIn, request: Request, response: Response,
|
||||
db: Session = Depends(get_db)) -> dict:
|
||||
if settings.shares_identity:
|
||||
# 404 rather than 401 or 403: a client feature-detects a route that is not here by trying
|
||||
# it, and this one genuinely is not here. The message carries the address, because the
|
||||
# single most likely reader is a person whose password just stopped working.
|
||||
raise NotFoundError(
|
||||
f"Sign in at {_hub_address()} — one account covers every module, and the session you "
|
||||
"get there is the session this app accepts. There is no separate password here."
|
||||
)
|
||||
ip = client_ip(request)
|
||||
user = auth_service.authenticate(db, body.email, body.password)
|
||||
if user is None:
|
||||
# One message for every failure mode. Distinguishing "no such user" from "wrong password"
|
||||
# hands an attacker a free account-enumeration oracle.
|
||||
audit.record(db, actor_id=None, action="auth.login", entity_type="app_user",
|
||||
result="denied", detail=body.email, ip=ip)
|
||||
db.commit()
|
||||
raise AuthenticationError("Incorrect email or password.")
|
||||
|
||||
session, raw_token = auth_service.create_session(db, user, ip=ip)
|
||||
audit.record(db, action="auth.login", entity_type="app_user", entity_id=user.id,
|
||||
actor_id=user.id, result="ok", ip=ip)
|
||||
db.commit()
|
||||
|
||||
response.set_cookie(
|
||||
SESSION_COOKIE, raw_token,
|
||||
httponly=True, samesite="lax", secure=_secure_flag(request),
|
||||
max_age=settings.session_ttl_hours * 3600, path="/",
|
||||
)
|
||||
_clear_legacy_cookies(response, request)
|
||||
return {"token": raw_token, "user": _user_out(user)}
|
||||
|
||||
|
||||
@router.post("/logout")
|
||||
def logout(request: Request, response: Response, db: Session = Depends(get_db)) -> dict:
|
||||
token = extract_token(request)
|
||||
if token:
|
||||
auth_service.revoke_session(db, token)
|
||||
db.commit()
|
||||
# Delete with the same attributes it was set with, or the browser keeps it and the user stays
|
||||
# signed in after pressing sign out.
|
||||
response.delete_cookie(SESSION_COOKIE, path="/", samesite="lax",
|
||||
secure=_secure_flag(request), httponly=True)
|
||||
_clear_legacy_cookies(response, request)
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.get("/me", response_model=UserOut)
|
||||
def me(db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)) -> dict:
|
||||
# The console draws its Administration nav from `is_moderator`, so this is the one call that has
|
||||
# to resolve the tier properly rather than fall back to `is_admin`: a moderator of this module
|
||||
# who is not a platform administrator would otherwise never see the menu item they were given.
|
||||
return _user_out(user, is_moderator=moderation_service.is_moderator(db, user))
|
||||
@@ -0,0 +1,30 @@
|
||||
"""What the console's landing screen needs, in one round trip.
|
||||
|
||||
One endpoint rather than five: the dashboard is the first thing every user loads, and five
|
||||
parallel requests on a cold connection is the difference between "instant" and "sluggish". The
|
||||
counts come from the same permission-filtered service the list screens use, so a tile can never
|
||||
report a number that includes something the reader may not open.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..db import get_db
|
||||
from ..deps import get_current_user
|
||||
from ..models import AppUser
|
||||
from ..services import example as service
|
||||
|
||||
router = APIRouter(tags=["dashboard"])
|
||||
|
||||
|
||||
@router.get("/dashboard")
|
||||
def dashboard(db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
rows = service.list_records(db, user)
|
||||
counts = {
|
||||
"total": len(rows),
|
||||
"open": sum(1 for r in rows if r["status"] == "open"),
|
||||
"done": sum(1 for r in rows if r["status"] == "done"),
|
||||
}
|
||||
return {"cards": counts, "recent": rows[:8]}
|
||||
@@ -0,0 +1,59 @@
|
||||
"""The demo entity's HTTP surface — copy this shape, then delete the file.
|
||||
|
||||
Note what is NOT here: no `select(...)`, no `db.add`, no permission logic. The router validates,
|
||||
delegates, commits, and shapes the response. That separation is what lets one reviewer check
|
||||
every access rule by reading `services/authz.py` and the services, not twenty route handlers.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, Depends, Query, Request
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..db import get_db
|
||||
from ..deps import client_ip, get_current_user
|
||||
from ..enums import RecordStatus
|
||||
from ..models import AppUser
|
||||
from ..schemas import RecordCreateIn, RecordUpdateIn
|
||||
from ..services import example as service
|
||||
|
||||
router = APIRouter(prefix="/records", tags=["records"])
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_records(db: Session = Depends(get_db), user: AppUser = Depends(get_current_user),
|
||||
q: str = Query("", max_length=200), status: RecordStatus | None = Query(None)) -> list[dict]:
|
||||
return service.list_records(db, user, q=q, status=status)
|
||||
|
||||
|
||||
@router.get("/{record_id}")
|
||||
def get_record(record_id: uuid.UUID, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
return service.get_record(db, user, record_id)
|
||||
|
||||
|
||||
@router.post("", status_code=201)
|
||||
def create_record(body: RecordCreateIn, request: Request, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
out = service.create_record(db, user, name=body.name, note=body.note, ip=client_ip(request))
|
||||
db.commit()
|
||||
return out
|
||||
|
||||
|
||||
@router.patch("/{record_id}")
|
||||
def update_record(record_id: uuid.UUID, body: RecordUpdateIn, request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
out = service.update_record(db, user, record_id, name=body.name, note=body.note,
|
||||
status=body.status, ip=client_ip(request))
|
||||
db.commit()
|
||||
return out
|
||||
|
||||
|
||||
@router.delete("/{record_id}")
|
||||
def delete_record(record_id: uuid.UUID, request: Request, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
service.delete_record(db, user, record_id, ip=client_ip(request))
|
||||
db.commit()
|
||||
return {"status": "ok"}
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Liveness, and the shape of this deployment.
|
||||
|
||||
Both are deliberately unauthenticated and deliberately cheap — `/health` is what the container
|
||||
healthcheck and the load balancer call, and a probe that touches the database turns a slow query
|
||||
into a restart loop. `/meta` is what the console reads BEFORE anybody is signed in, which is the
|
||||
only moment the question it answers can be asked.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter
|
||||
|
||||
from .. import __version__
|
||||
from ..config import get_settings
|
||||
|
||||
router = APIRouter(tags=["health"])
|
||||
settings = get_settings()
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
def health() -> dict:
|
||||
return {"status": "ok", "version": __version__}
|
||||
|
||||
|
||||
@router.get("/meta")
|
||||
def meta() -> dict:
|
||||
"""What a client needs before it has a session — chiefly, whether it can sign in here at all.
|
||||
|
||||
`local_login` is false when this deployment is a MODULE of the platform: there is no password
|
||||
here because there is no account here, and the console draws a link to the hub instead of a
|
||||
form. `app_token_mint` is the same question for app tokens, kept separate from "does this server
|
||||
understand app tokens at all", because on the platform those two answers differ and a client
|
||||
that conflates them shows a Create-token button that always 409s.
|
||||
|
||||
Advertised rather than probed, so that one build of a client works against a standalone app and
|
||||
against a platform module without discovering the difference from an error.
|
||||
|
||||
The name of the shared schema is deliberately NOT here: an unauthenticated caller has no business
|
||||
learning the database's shape. `sign_in_url` is a configured address (IDENTITY_HUB_URL), never a
|
||||
derived one — deriving the hub's path from this module's own would bake its slug into every
|
||||
module — and empty is allowed: the console then says accounts live elsewhere rather than offering
|
||||
a link that goes nowhere.
|
||||
"""
|
||||
return {
|
||||
"product": "agora",
|
||||
"version": __version__,
|
||||
"local_login": not settings.shares_identity,
|
||||
"app_tokens": settings.app_tokens_enabled,
|
||||
"app_token_mint": settings.app_tokens_enabled and not settings.shares_identity,
|
||||
"sign_in_url": settings.identity_hub_url if settings.shares_identity else "",
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
"""Users and the current user's own credentials — or, on the platform, the read-only half of it.
|
||||
|
||||
**STANDALONE** (no IDENTITY_SCHEMA) this is unchanged: the app owns its accounts, and this module's
|
||||
administration creates them, changes passwords and deactivates them here. That path must keep
|
||||
working — an app with its own database and its own people is a supported deployment, not a leftover.
|
||||
|
||||
**On the platform** the hub owns every account, and this app's database role is a reader of the
|
||||
shared identity store: a column-restricted SELECT on `app_user`, and no INSERT or UPDATE at all. So
|
||||
the write routes below refuse before they touch anything. The refusal is politeness, not enforcement
|
||||
— the enforcement is the missing grant — but it is the difference between a 409 that says where to
|
||||
go and a Postgres permission error surfacing as a 500 on a screen somebody opened by accident.
|
||||
|
||||
The read route stays either way, and deliberately: granting somebody access to something in this
|
||||
module needs a list of people to grant it to, that list is a per-module screen, and it is one origin
|
||||
away from the hub that produced it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..config import get_settings
|
||||
from ..db import get_db
|
||||
from ..deps import client_ip, get_current_user, require_moderator
|
||||
from ..errors import AuthenticationError, ConflictError, NotFoundError
|
||||
from ..models import AppUser
|
||||
from ..schemas import AppTokenIn, AppTokenOut, PasswordChangeIn, UserCreateIn, UserOut
|
||||
from ..security import hash_password
|
||||
from ..services import audit
|
||||
from ..services import auth as auth_service
|
||||
from ..services import moderation as moderation_service
|
||||
|
||||
router = APIRouter(tags=["users"])
|
||||
settings = get_settings()
|
||||
|
||||
|
||||
def _user_out(u: AppUser, *, is_moderator: bool | None = None) -> dict:
|
||||
"""Both administration tiers, and always both keys — see `routers/auth._user_out` for why."""
|
||||
return {"id": str(u.id), "email": u.email, "full_name": u.full_name,
|
||||
"is_admin": u.is_admin, "is_active": u.is_active,
|
||||
"is_moderator": u.is_admin if is_moderator is None else bool(is_moderator)}
|
||||
|
||||
|
||||
def _identity_is_ours() -> None:
|
||||
"""Refuse an account write when the hub owns accounts.
|
||||
|
||||
Before the lookup and long before any flush, so nothing forbidden is ever attempted.
|
||||
`create_user` carries the same refusal inside dredd-core (`AuthPolicy.identity_writes_enabled`)
|
||||
and would raise on its own; the other routes assign to the ORM object directly and have no core
|
||||
call to carry it for them — hence one guard, used by all of them, so they answer identically.
|
||||
"""
|
||||
if settings.shares_identity:
|
||||
raise ConflictError(
|
||||
"Accounts are managed in the hub. Create people, change their names and passwords, and "
|
||||
"deactivate them there — one account reaches every module."
|
||||
)
|
||||
|
||||
|
||||
@router.get("/users", response_model=list[UserOut])
|
||||
def list_users(db: Session = Depends(get_db),
|
||||
_: AppUser = Depends(get_current_user)) -> list[dict]:
|
||||
"""Every signed-in user may list users: the console needs names to render "assigned to"
|
||||
pickers, and an email address inside the instance is not the secret worth hiding here."""
|
||||
# One query for the whole page's tier column, not one per row: `moderator_ids` returns this
|
||||
# module's roster as a set, and standalone it returns an empty set without touching the database.
|
||||
moderators = moderation_service.moderator_ids(db)
|
||||
return [_user_out(u, is_moderator=u.is_admin or u.id in moderators)
|
||||
for u in auth_service.list_users(db)]
|
||||
|
||||
|
||||
@router.post("/users", response_model=UserOut, status_code=201)
|
||||
def create_user(body: UserCreateIn, request: Request, db: Session = Depends(get_db),
|
||||
admin: AppUser = Depends(require_moderator)) -> dict:
|
||||
_identity_is_ours()
|
||||
user = auth_service.create_user(db, email=body.email, full_name=body.full_name,
|
||||
password=body.password, is_admin=body.is_admin)
|
||||
audit.record(db, action="user.create", entity_type="app_user", entity_id=user.id,
|
||||
actor_id=admin.id, detail=user.email, ip=client_ip(request))
|
||||
db.commit()
|
||||
return _user_out(user)
|
||||
|
||||
|
||||
@router.post("/users/{user_id}/deactivate", response_model=UserOut)
|
||||
def deactivate(user_id: uuid.UUID, request: Request, db: Session = Depends(get_db),
|
||||
admin: AppUser = Depends(require_moderator)) -> dict:
|
||||
_identity_is_ours()
|
||||
# A lone db.get by primary key is the one query a router may make (see the layering invariant).
|
||||
user = db.get(AppUser, user_id)
|
||||
if user is None:
|
||||
raise NotFoundError("User not found.")
|
||||
user.is_active = False
|
||||
# Kill the sessions too — an account that is "deactivated" but still holds a live cookie is
|
||||
# not deactivated.
|
||||
auth_service.revoke_user_sessions(db, user.id)
|
||||
audit.record(db, action="user.deactivate", entity_type="app_user", entity_id=user.id,
|
||||
actor_id=admin.id, ip=client_ip(request))
|
||||
db.commit()
|
||||
return _user_out(user)
|
||||
|
||||
|
||||
@router.post("/me/password")
|
||||
def change_password(body: PasswordChangeIn, request: Request, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
# First, and before `user.password_hash` is so much as read: on the platform that column is not
|
||||
# in this app's column grant, so touching it at all is a permission error rather than a wrong
|
||||
# answer. One password, changed in one place, is also the whole point of one account.
|
||||
_identity_is_ours()
|
||||
if not user.password_hash or not auth_service.verify_password(
|
||||
body.current_password, user.password_hash):
|
||||
raise AuthenticationError("Your current password is not correct.")
|
||||
# Revoke every session, including this one: a password change is usually a response to
|
||||
# suspecting someone else has it, so containment matters more than convenience.
|
||||
user.password_hash = hash_password(body.new_password)
|
||||
auth_service.revoke_user_sessions(db, user.id)
|
||||
audit.record(db, action="user.password_change", entity_type="app_user", entity_id=user.id,
|
||||
actor_id=user.id, ip=client_ip(request))
|
||||
db.commit()
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
# ── app tokens ────────────────────────────────────────────────────────────────
|
||||
# Listing and revoking stay here in both shapes; only MINTING moves to the hub. That split is a
|
||||
# grant, not a policy: a module holds no INSERT on `session`, and a role that can insert a session
|
||||
# row can mint a working credential for the administrator. It holds SELECT and UPDATE (revoked_at),
|
||||
# so a person can still see and kill the tokens they have — and a credential you cannot see is one
|
||||
# you cannot kill, which is why revocation must never follow minting to the hub.
|
||||
def _token_out(t) -> dict:
|
||||
return {"id": str(t.id), "name": t.name, "scope": t.scope, "token_prefix": t.token_prefix,
|
||||
"expires_at": t.expires_at.isoformat() if t.expires_at else None,
|
||||
"revoked_at": t.revoked_at.isoformat() if t.revoked_at else None}
|
||||
|
||||
|
||||
@router.get("/me/tokens", response_model=list[AppTokenOut])
|
||||
def list_tokens(db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> list[dict]:
|
||||
return [_token_out(t) for t in auth_service.list_app_tokens(db, user)]
|
||||
|
||||
|
||||
@router.post("/me/tokens", status_code=201)
|
||||
def create_token(body: AppTokenIn, request: Request, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
if settings.shares_identity:
|
||||
# The hub stamps the token `agora_pat_` on this module's behalf, so the prefix still
|
||||
# says where a leaked credential came from and whose audit log to read first.
|
||||
raise ConflictError(
|
||||
f"App tokens are created at {settings.identity_hub_url or 'the hub'}, once, for every "
|
||||
"module. You can still see and revoke the ones you have here."
|
||||
)
|
||||
row, raw = auth_service.create_app_token(
|
||||
db, user, name=body.name, scope=body.scope, idle_days=body.idle_days,
|
||||
ip=client_ip(request),
|
||||
)
|
||||
audit.record(db, action="token.create", entity_type="session", entity_id=row.id,
|
||||
actor_id=user.id, detail=body.name, ip=client_ip(request))
|
||||
db.commit()
|
||||
# The raw token is returned exactly once and never stored — only its hash is.
|
||||
return {"token": raw, **_token_out(row)}
|
||||
|
||||
|
||||
@router.delete("/me/tokens/{token_id}")
|
||||
def revoke_token(token_id: str, request: Request, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
row = auth_service.revoke_app_token(db, user, token_id)
|
||||
if row is None:
|
||||
raise NotFoundError("Token not found.")
|
||||
audit.record(db, action="token.revoke", entity_type="session", entity_id=row.id,
|
||||
actor_id=user.id, ip=client_ip(request))
|
||||
db.commit()
|
||||
return {"status": "ok"}
|
||||
@@ -0,0 +1,126 @@
|
||||
"""Request/response shapes.
|
||||
|
||||
Email is validated by an in-app regex rather than the `email-validator` package: one fewer
|
||||
dependency to license-audit and vendor, and the strictness difference does not matter for a
|
||||
field that is confirmed by sending mail to it anyway.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import uuid
|
||||
from typing import Annotated, Any
|
||||
|
||||
from dredd_core.enums import NodeRole
|
||||
from pydantic import AfterValidator, BaseModel, Field
|
||||
|
||||
from .enums import RecordStatus
|
||||
|
||||
_EMAIL = re.compile(r"^[^@\s]+@[^@\s.]+(\.[^@\s.]+)+$")
|
||||
|
||||
|
||||
def _valid_email(v: str) -> str:
|
||||
v = v.strip()
|
||||
if not _EMAIL.match(v) or len(v) > 254:
|
||||
raise ValueError("Not a valid email address.")
|
||||
return v
|
||||
|
||||
|
||||
Email = Annotated[str, AfterValidator(_valid_email)]
|
||||
|
||||
|
||||
# ── auth ──────────────────────────────────────────────────────────────────────
|
||||
class LoginIn(BaseModel):
|
||||
email: Email
|
||||
password: str = Field(min_length=1, max_length=200)
|
||||
|
||||
|
||||
class UserOut(BaseModel):
|
||||
"""The two administration tiers, side by side, and both keys always present.
|
||||
|
||||
`is_admin` is the platform-wide ADMINISTRATOR: one boolean on the account, and on a platform it
|
||||
is the hub's to grant. `is_moderator` is "may administer THIS module" — an administrator, or
|
||||
somebody the hub named a moderator of this app. The console draws its Administration nav from
|
||||
the second and never reads the first, because a moderator who saw no Administration menu would
|
||||
have been given a tier they cannot use. Standalone the two are the same thing.
|
||||
"""
|
||||
id: str
|
||||
email: str
|
||||
full_name: str
|
||||
is_admin: bool
|
||||
is_active: bool
|
||||
is_moderator: bool = False
|
||||
|
||||
|
||||
class LoginOut(BaseModel):
|
||||
token: str
|
||||
user: UserOut
|
||||
|
||||
|
||||
# ── users ─────────────────────────────────────────────────────────────────────
|
||||
class UserCreateIn(BaseModel):
|
||||
email: Email
|
||||
full_name: str = Field(min_length=1, max_length=200)
|
||||
password: str = Field(min_length=10, max_length=200)
|
||||
is_admin: bool = False
|
||||
|
||||
|
||||
class PasswordChangeIn(BaseModel):
|
||||
current_password: str = Field(min_length=1, max_length=200)
|
||||
new_password: str = Field(min_length=10, max_length=200)
|
||||
|
||||
|
||||
# ── app tokens ────────────────────────────────────────────────────────────────
|
||||
class AppTokenIn(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=120)
|
||||
scope: str = "read_write"
|
||||
idle_days: int | None = None
|
||||
|
||||
|
||||
class AppTokenOut(BaseModel):
|
||||
id: str
|
||||
name: str | None
|
||||
scope: str
|
||||
token_prefix: str | None
|
||||
expires_at: str | None
|
||||
revoked_at: str | None
|
||||
|
||||
|
||||
# ── nodes ─────────────────────────────────────────────────────────────────────
|
||||
class NodeCreateIn(BaseModel):
|
||||
kind: str = Field(min_length=1, max_length=32)
|
||||
name: str = Field(min_length=1, max_length=200)
|
||||
parent_id: uuid.UUID | None = None
|
||||
|
||||
|
||||
class NodeOut(BaseModel):
|
||||
id: str
|
||||
kind: str
|
||||
name: str
|
||||
path: str
|
||||
parent_id: str | None = None
|
||||
|
||||
|
||||
class GrantIn(BaseModel):
|
||||
user_id: uuid.UUID
|
||||
role: NodeRole
|
||||
|
||||
|
||||
# ── the demo entity ───────────────────────────────────────────────────────────
|
||||
class RecordCreateIn(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=200)
|
||||
note: str | None = Field(default=None, max_length=4000)
|
||||
# Required in node tenancy (which container it goes in); ignored in simple tenancy.
|
||||
parent_id: uuid.UUID | None = None
|
||||
|
||||
|
||||
class RecordUpdateIn(BaseModel):
|
||||
"""Every field optional: `None` means "not supplied", never "blank it"."""
|
||||
name: str | None = Field(default=None, min_length=1, max_length=200)
|
||||
note: str | None = Field(default=None, max_length=4000)
|
||||
status: RecordStatus | None = None
|
||||
|
||||
|
||||
# ── administration ────────────────────────────────────────────────────────────
|
||||
class SettingsIn(BaseModel):
|
||||
"""A partial set of settings to change, validated against `services/settings.SPECS`."""
|
||||
values: dict[str, Any] = Field(min_length=1, max_length=50)
|
||||
@@ -0,0 +1,57 @@
|
||||
"""Password hashing (Argon2id) and opaque tokens — thin app-side layer over dredd-core.
|
||||
|
||||
The primitives live in **dredd-core** (`dredd_core.security`) so every app in the family hashes
|
||||
and compares credentials exactly the same way; this module re-exports them under the names the
|
||||
rest of the app already imports, and adds the one genuinely app-specific thing: this app's token
|
||||
prefix.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dredd_core.security import (
|
||||
derive_key,
|
||||
generate_session_token,
|
||||
hash_password,
|
||||
hash_token,
|
||||
verify_password,
|
||||
)
|
||||
from dredd_core.security import generate_app_token as _generate_app_token
|
||||
from dredd_core.security import token_display_prefix as _token_display_prefix
|
||||
|
||||
# Recognisable prefix for app tokens. It costs nothing and buys two things: secret scanners
|
||||
# (GitHub/GitLab push protection, trufflehog) can match a leaked token by pattern, and the UI can
|
||||
# identify a credential by its head without ever showing the body.
|
||||
#
|
||||
# It is also what names the application in a leak report. A token resolves against whatever identity
|
||||
# store this app reads — its own rows while it runs standalone, the platform's shared store once it
|
||||
# is a module of one, where every module's tokens sit side by side. Either way the prefix is the only
|
||||
# thing saying which app minted the leaked credential, and so which audit log to read first. That
|
||||
# matters more under one platform, not less. Keep it distinct per app.
|
||||
APP_TOKEN_PREFIX = "agora_pat_"
|
||||
|
||||
|
||||
def generate_app_token() -> str:
|
||||
"""Opaque, high-entropy app token, prefixed so it is greppable. Only its hash is stored."""
|
||||
return _generate_app_token(APP_TOKEN_PREFIX)
|
||||
|
||||
|
||||
def token_display_prefix(token: str) -> str:
|
||||
"""The non-secret fragment safe to store and show, e.g. `agora_pat_a1b2c3`.
|
||||
|
||||
A few characters of a high-entropy token identify it among a user's handful of tokens while
|
||||
leaving it computationally useless — but it is still stored in the clear, so keep it short.
|
||||
"""
|
||||
return _token_display_prefix(token, APP_TOKEN_PREFIX)
|
||||
|
||||
|
||||
__all__ = [
|
||||
# from dredd-core, unchanged
|
||||
"hash_password",
|
||||
"verify_password",
|
||||
"generate_session_token",
|
||||
"hash_token",
|
||||
"derive_key",
|
||||
# this app's own
|
||||
"APP_TOKEN_PREFIX",
|
||||
"generate_app_token",
|
||||
"token_display_prefix",
|
||||
]
|
||||
@@ -0,0 +1,76 @@
|
||||
"""Idempotent bootstrap. Runs in the `migrate` compose service, right after `alembic upgrade head`.
|
||||
|
||||
It connects as the runtime role (DATABASE_URL), like the app itself — the migrator only ever runs
|
||||
Alembic.
|
||||
|
||||
Safe to run twice — it checks before it creates. A seed that fails on a second run turns every
|
||||
redeploy into a manual step, and manual steps are how production drifts from the documented setup.
|
||||
|
||||
On the platform, the account half of that is not this app's to do. The hub owns `app_user` and this
|
||||
module's role holds no INSERT on it, so the seed LOOKS the bootstrap administrator up in the shared
|
||||
store instead of creating one. If they are not there yet — the hub has not been seeded, or the
|
||||
account census has not run — it says why and does nothing, rather than failing: `docker compose up`
|
||||
runs the seed on every start, and a module that refuses to come up because the hub is one step behind
|
||||
turns an ordering detail into an outage. The demo data can wait; the accounts cannot be faked.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from dredd_core.db import make_engine, make_session_factory
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from sqlalchemy.pool import NullPool
|
||||
|
||||
from .config import get_settings
|
||||
from .db import SessionLocal
|
||||
from .enums import RecordStatus
|
||||
from .models import Record
|
||||
from .services import auth as auth_service
|
||||
|
||||
log = logging.getLogger("agora.seed")
|
||||
|
||||
|
||||
def run(session_factory: sessionmaker | None = None) -> None:
|
||||
settings = get_settings()
|
||||
db = (session_factory or SessionLocal)()
|
||||
try:
|
||||
admin = auth_service.find_user_by_email(db, settings.bootstrap_admin_email)
|
||||
if admin is None and settings.shares_identity:
|
||||
# The hub owns accounts, so there is nothing to create here and no privilege to do it
|
||||
# with. Everything below needs somebody to own the demo data, so stop cleanly.
|
||||
log.warning(
|
||||
"Shared identity (%s): %s has no account yet, so there is nobody to own the demo "
|
||||
"data. Accounts are created in the hub; re-run this seed afterwards.",
|
||||
settings.identity_schema, settings.bootstrap_admin_email,
|
||||
)
|
||||
return
|
||||
if admin is None:
|
||||
admin = auth_service.create_user(
|
||||
db,
|
||||
email=settings.bootstrap_admin_email,
|
||||
full_name="Administrator",
|
||||
password=settings.bootstrap_admin_password,
|
||||
is_admin=True,
|
||||
)
|
||||
log.info("Created bootstrap admin %s", admin.email)
|
||||
|
||||
if settings.seed_demo and db.scalar(select(Record.id)) is None:
|
||||
db.add(Record(name="Nowy rekord", note="Notatka",
|
||||
status=RecordStatus.open, owner_id=admin.id, created_by=admin.id))
|
||||
log.info("Seeded demo data")
|
||||
|
||||
db.commit()
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
# A one-shot process holds no pool: in the family's shared managed database every app draws on one
|
||||
# connection limit. Same URL, role and TLS settings (DATABASE_URL) as the app itself.
|
||||
seed_engine = make_engine(get_settings().database_url, poolclass=NullPool)
|
||||
try:
|
||||
run(make_session_factory(seed_engine))
|
||||
finally:
|
||||
seed_engine.dispose()
|
||||
@@ -0,0 +1 @@
|
||||
"""Domain services. Routers call these; nothing here talks HTTP."""
|
||||
@@ -0,0 +1,14 @@
|
||||
"""Append-only audit log writer — a thin shim. The logic lives in `dredd_core.audit`.
|
||||
|
||||
`record()` inserts one row into `audit_log`, which the `app` DB role may only INSERT and SELECT
|
||||
(the migration grants no UPDATE or DELETE). Re-exported here so `audit.record(...)` call sites
|
||||
across the routers stay unchanged.
|
||||
|
||||
**NO logic may be added here** — an audit writer that behaves differently per app is not an audit
|
||||
trail. Change `dredd_core.audit` and move the pin in `backend/requirements.txt` instead.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dredd_core.audit import record # noqa: F401 — re-exported for services.audit consumers
|
||||
|
||||
__all__ = ["record"]
|
||||
@@ -0,0 +1,31 @@
|
||||
"""Reading the audit log, for Administration.
|
||||
|
||||
Not `services/audit.py`: that file is a shim over `dredd_core.audit`, whose contract is "write one
|
||||
row", and a shim holds no logic. The query lives here so the router never builds SQL.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session as DbSession
|
||||
|
||||
from ..models import AppUser, AuditLog
|
||||
|
||||
|
||||
def list_entries(db: DbSession, *, limit: int = 100, offset: int = 0,
|
||||
action: str | None = None) -> list[dict]:
|
||||
stmt = (select(AuditLog, AppUser.email)
|
||||
.outerjoin(AppUser, AppUser.id == AuditLog.actor_id)
|
||||
.order_by(AuditLog.created_at.desc(), AuditLog.id))
|
||||
if action:
|
||||
# A prefix filter, not a pattern language: LIKE metacharacters are escaped.
|
||||
escaped = action.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
||||
stmt = stmt.where(AuditLog.action.like(escaped + "%", escape="\\"))
|
||||
rows = db.execute(stmt.limit(limit).offset(offset)).all()
|
||||
return [{
|
||||
"id": str(r.id), "action": r.action, "entity_type": r.entity_type,
|
||||
"entity_id": str(r.entity_id) if r.entity_id else None,
|
||||
"actor_id": str(r.actor_id) if r.actor_id else None, "actor_email": email,
|
||||
"result": r.result, "detail": r.detail, "diff": r.diff,
|
||||
"ip": str(r.ip) if r.ip is not None else None,
|
||||
"created_at": r.created_at.isoformat() if r.created_at else None,
|
||||
} for r, email in rows]
|
||||
@@ -0,0 +1,113 @@
|
||||
"""Authentication — a thin shim. The logic lives in `dredd_core.auth`.
|
||||
|
||||
`dredd_core.auth.AuthService` owns all of it: the credential check (with equalised timing on the
|
||||
user-missing / inactive / no-password path, plus failure counting and app-level lockout),
|
||||
server-side sessions backed by the `session` table (so revocation is an instant kill-switch), and
|
||||
named app tokens whose *idle* expiry slides forward on use — an exfiltrated token that is never
|
||||
used dies on its own, which a password never does.
|
||||
|
||||
This module binds Agora's settings and its own app-token prefix onto one `AuthService`
|
||||
and re-exports each operation as a module-level function, so every `auth_service.<fn>(db, ...)`
|
||||
call site (`deps.py`, `routers/auth.py`, `routers/users.py`, `seed.py`) reads exactly as before.
|
||||
|
||||
**NO logic may be added here.** If an operation has to change, change it in dredd-core and move
|
||||
the pin in `backend/requirements.txt` — a behaviour fork hiding in this file is how the family's
|
||||
apps drift apart, and auth is the worst place for that to happen quietly. What legitimately stays
|
||||
app-side is the *configuration* of the shared logic, and nothing else: the greppable token prefix
|
||||
(`..security.APP_TOKEN_PREFIX`), the policy knobs read from `..config`, and the whole HTTP edge —
|
||||
cookies, headers, status codes — which lives in `routers/auth.py`.
|
||||
|
||||
One consequence worth stating out loud: as scaffolded this app has its own database (its own schema,
|
||||
in the family's shared managed database) and therefore its own `session` table, so its cookie signs
|
||||
people in *here* and nowhere else. That is where it starts, not where the family ends — the target
|
||||
shape is one platform at one origin, one module per path, with a shared identity store every module
|
||||
resolves against: one account, one sign-in, separate schemas. Getting there is a migration plus a
|
||||
grant tier (the store is owned by the hub and read by the module), never a `Domain=` attribute on
|
||||
the cookie — a sibling holding its own `session` rows simply rejects a token hash it has never seen.
|
||||
Both modes run this same file: what differs is the `AuthPolicy` the settings map onto, below.
|
||||
|
||||
The last three knobs in that policy are the whole of "this app is a member of the platform, not its
|
||||
own island", and all three come from one setting. Standalone they are all True and this file behaves
|
||||
exactly as it always has. On the platform they are all False, because the hub owns identity and this
|
||||
app's database role is a READER of it: a column-restricted SELECT on `app_user` that does not
|
||||
include `password_hash`, SELECT plus a three-column UPDATE on `session`, and no INSERT on either.
|
||||
The flags are **not** the enforcement — the grant is — they are the sentence at the edge, so a
|
||||
forbidden operation comes back as a clean 409 instead of a Postgres permission error dressed up as a
|
||||
500 on an ordinary screen.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dredd_core.auth import AuthPolicy, AuthService
|
||||
|
||||
# Re-exported unchanged so `auth_service.verify_password(...)` keeps working for the
|
||||
# change-password route, which must check the *current* password before replacing it.
|
||||
from dredd_core.security import hash_password, verify_password # noqa: F401
|
||||
|
||||
from ..config import get_settings
|
||||
from ..security import APP_TOKEN_PREFIX
|
||||
|
||||
settings = get_settings()
|
||||
|
||||
# The per-install knobs. Core reads no app config of its own — an app maps its settings onto the
|
||||
# policy, which is why dredd-core imports nothing app-side.
|
||||
_POLICY = AuthPolicy(
|
||||
session_ttl_hours=settings.session_ttl_hours,
|
||||
login_max_attempts=settings.login_max_attempts,
|
||||
login_lockout_minutes=settings.login_lockout_minutes,
|
||||
# MINTING only. Listing and revoking app tokens are unaffected by this flag in core, which is
|
||||
# exactly right here: a module holds no INSERT on `session`, so it cannot create a credential —
|
||||
# a role that could insert a session row could mint a working cookie for the administrator — but
|
||||
# it holds SELECT and UPDATE (revoked_at), so a person can still see and kill the tokens they
|
||||
# have. Minting moves to the hub, which stamps them `agora_pat_` on this module's behalf.
|
||||
app_tokens_enabled=settings.app_tokens_enabled and not settings.shares_identity,
|
||||
app_token_idle_days=settings.app_token_idle_days,
|
||||
app_token_max_idle_days=settings.app_token_max_idle_days,
|
||||
app_token_renew_after_hours=settings.app_token_renew_after_hours,
|
||||
# Distinct per app on purpose: secret scanners can match a leaked credential by pattern, and
|
||||
# the console can name a token by its head without ever showing the body.
|
||||
app_token_prefix=APP_TOKEN_PREFIX,
|
||||
# Accounts are created, renamed, re-passworded and deactivated in ONE place. `create_user` then
|
||||
# refuses before it builds a row, so nothing forbidden is ever attempted.
|
||||
identity_writes_enabled=not settings.shares_identity,
|
||||
# Nobody signs in HERE: they sign in at the hub and this module resolves the same session row.
|
||||
# `authenticate` returns None before it reads anything, which also keeps this app from emitting
|
||||
# the two statements its grants would refuse — any read of `password_hash`, and the lockout's
|
||||
# `UPDATE ... RETURNING failed_login_count`.
|
||||
local_login_enabled=not settings.shares_identity,
|
||||
)
|
||||
_service = AuthService(_POLICY)
|
||||
|
||||
# ── users ────────────────────────────────────────────────────────────────────
|
||||
find_user_by_email = _service.find_user_by_email
|
||||
list_users = _service.list_users
|
||||
create_user = _service.create_user
|
||||
|
||||
# ── sessions ─────────────────────────────────────────────────────────────────
|
||||
authenticate = _service.authenticate
|
||||
create_session = _service.create_session
|
||||
resolve_session = _service.resolve_session
|
||||
resolve_session_full = _service.resolve_session_full
|
||||
revoke_session = _service.revoke_session
|
||||
revoke_user_sessions = _service.revoke_user_sessions
|
||||
|
||||
# ── app tokens ───────────────────────────────────────────────────────────────
|
||||
create_app_token = _service.create_app_token
|
||||
list_app_tokens = _service.list_app_tokens
|
||||
revoke_app_token = _service.revoke_app_token
|
||||
|
||||
__all__ = [
|
||||
"hash_password",
|
||||
"verify_password",
|
||||
"find_user_by_email",
|
||||
"list_users",
|
||||
"create_user",
|
||||
"authenticate",
|
||||
"create_session",
|
||||
"resolve_session",
|
||||
"resolve_session_full",
|
||||
"revoke_session",
|
||||
"revoke_user_sessions",
|
||||
"create_app_token",
|
||||
"list_app_tokens",
|
||||
"revoke_app_token",
|
||||
]
|
||||
@@ -0,0 +1,65 @@
|
||||
"""The single access authority for a single-tenant instance.
|
||||
|
||||
There is no permission tree here: authentication plus "this module's administration, or the owner"
|
||||
is the whole model. It still lives in one module, for the same reason the tree version does — when
|
||||
the rule is spelled out in one place, a reviewer can check every caller against it, and growing into
|
||||
a real tree later means changing this file rather than hunting checks across the routers.
|
||||
|
||||
Keep the **404-not-403** convention for anything whose existence is privileged: a 403 confirms
|
||||
that the record the caller may not see is real.
|
||||
|
||||
Every function takes the `Session` first, matching `dredd_core.authz`'s own shape in the tree
|
||||
tenancy, because the top of this model is no longer just a column on the person. It is a **tier**:
|
||||
|
||||
ADMINISTRATOR the whole platform `app_user.is_admin`
|
||||
MODERATOR exactly one module — here, this app a `module_permission` row the hub wrote
|
||||
|
||||
The other role such a row can carry, `user`, reaches nothing in this file and must not: it answers
|
||||
whether somebody may OPEN this app at all, which `deps.get_current_user` asks once at the edge.
|
||||
Inside, it is these questions and nothing else.
|
||||
|
||||
`services/moderation.py` answers both in one call, and answers them **without touching the database
|
||||
at all** when this app is standalone (no IDENTITY_SCHEMA), where the two tiers are the same thing
|
||||
and `is_admin` is the whole answer. So the `db` argument costs a single-tenant install nothing, and
|
||||
it is what lets a moderator of this module see what an administrator sees — the projection has to be
|
||||
TOTAL, or somebody the hub made a moderator would pass the administration screens and then find
|
||||
other people's records invisible.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy.orm import Session as DbSession
|
||||
|
||||
from ..errors import NotFoundError
|
||||
from ..models import AppUser
|
||||
from . import moderation
|
||||
|
||||
|
||||
def can_read(db: DbSession, user: AppUser, owner_id=None) -> bool:
|
||||
"""This module's administration sees everything; an owned row is visible to its owner. An
|
||||
unowned row is shared."""
|
||||
if owner_id is None or owner_id == user.id:
|
||||
return True
|
||||
return moderation.is_moderator(db, user)
|
||||
|
||||
|
||||
def assert_can_read(db: DbSession, user: AppUser, owner_id=None) -> None:
|
||||
if not can_read(db, user, owner_id):
|
||||
raise NotFoundError("Not found.")
|
||||
|
||||
|
||||
def assert_can_write(db: DbSession, user: AppUser, owner_id=None) -> None:
|
||||
"""Write needs the same visibility, stated separately so a future split (a read-only
|
||||
collaborator, say) has an obvious seam to change."""
|
||||
if not can_read(db, user, owner_id):
|
||||
raise NotFoundError("Not found.")
|
||||
|
||||
|
||||
def assert_moderator(db: DbSession, user: AppUser) -> AppUser:
|
||||
"""This module's administration: a platform ADMINISTRATOR, or a MODERATOR of this module.
|
||||
|
||||
The successor to `assert_admin`. **This app defines no administrator-only guard**, and that is
|
||||
the invariant rather than an oversight: once accounts live in the hub, every power left in a
|
||||
module is module-scoped, so a route guarded by the platform-wide tier would only lock a
|
||||
moderator out of the job they were given. `deps.require_moderator` is the HTTP edge of this one.
|
||||
"""
|
||||
return moderation.assert_moderator(db, user)
|
||||
@@ -0,0 +1,19 @@
|
||||
"""Field-level diffs for the audit log.
|
||||
|
||||
Deliberately NOT in `services/audit.py`: that file is a thin shim over `dredd_core.audit`, whose
|
||||
contract is "write one audit row" and nothing else. Logic never goes in a shim — it would either
|
||||
be lost on the next core bump or have to be pushed into core for every app to carry. This module
|
||||
is this app's own.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def diff_of(before: dict, after: dict) -> dict:
|
||||
"""{field: [old, new]} for changed fields only.
|
||||
|
||||
Only the changes: an audit entry that repeats every field of the row is one nobody reads, and
|
||||
the point of storing a diff is to make "what actually changed here?" answerable at a glance
|
||||
years later.
|
||||
"""
|
||||
keys = set(before) | set(after)
|
||||
return {k: [before.get(k), after.get(k)] for k in sorted(keys) if before.get(k) != after.get(k)}
|
||||
@@ -0,0 +1,105 @@
|
||||
"""The demo domain service — the seam to copy for real work, then delete.
|
||||
|
||||
What it demonstrates, and what your real services should keep doing:
|
||||
* every read and write goes through `authz`, including the list query;
|
||||
* `None` means "not supplied", never "blank it";
|
||||
* anything worth reconstructing later is written to the append-only audit log.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session as DbSession
|
||||
|
||||
from ..enums import RecordStatus
|
||||
from ..errors import NotFoundError, ValidationError
|
||||
from ..models import AppUser, Record
|
||||
from . import audit, authz, changes
|
||||
|
||||
|
||||
def _as_dict(r: Record) -> dict:
|
||||
return {
|
||||
"id": str(r.id), "name": r.name, "note": r.note, "status": r.status.value,
|
||||
"owner_id": str(r.owner_id) if r.owner_id else None,
|
||||
"created_at": r.created_at.isoformat() if r.created_at else None,
|
||||
}
|
||||
|
||||
|
||||
def list_records(db: DbSession, user: AppUser, *, q: str = "",
|
||||
status: str | None = None) -> list[dict]:
|
||||
stmt = select(Record)
|
||||
if q:
|
||||
stmt = stmt.where(Record.name.ilike(f"%{q}%"))
|
||||
if status:
|
||||
stmt = stmt.where(Record.status == RecordStatus(status))
|
||||
rows = list(db.scalars(stmt.order_by(Record.created_at.desc())).all())
|
||||
return [_as_dict(r) for r in rows if authz.can_read(db, user, r.owner_id)]
|
||||
|
||||
|
||||
def get_record(db: DbSession, user: AppUser, record_id: uuid.UUID) -> dict:
|
||||
row = db.get(Record, record_id)
|
||||
if row is None:
|
||||
raise NotFoundError("Not found.")
|
||||
authz.assert_can_read(db, user, row.owner_id)
|
||||
return _as_dict(row)
|
||||
|
||||
|
||||
def create_record(db: DbSession, user: AppUser, *, name: str, note: str | None = None,
|
||||
ip: str | None = None) -> dict:
|
||||
name = (name or "").strip()
|
||||
if not name:
|
||||
raise ValidationError("Give it a name.")
|
||||
row = Record(name=name, note=note, status=RecordStatus.open,
|
||||
owner_id=user.id, created_by=user.id)
|
||||
db.add(row)
|
||||
db.flush()
|
||||
audit.record(db, action="record.create", entity_type="record", entity_id=row.id,
|
||||
actor_id=user.id, detail=name, ip=ip)
|
||||
return _as_dict(row)
|
||||
|
||||
|
||||
def update_record(db: DbSession, user: AppUser, record_id: uuid.UUID, *,
|
||||
name: str | None = None, note: str | None = None,
|
||||
status: str | None = None, ip: str | None = None) -> dict:
|
||||
row = db.get(Record, record_id)
|
||||
if row is None:
|
||||
raise NotFoundError("Not found.")
|
||||
authz.assert_can_write(db, user, row.owner_id)
|
||||
|
||||
before = {"name": row.name, "note": row.note, "status": row.status.value}
|
||||
# `None` means "not supplied", never "blank it" — otherwise a partial update silently wipes
|
||||
# the fields it didn't mention.
|
||||
if name is not None:
|
||||
row.name = name.strip() or row.name
|
||||
if note is not None:
|
||||
row.note = note
|
||||
if status is not None:
|
||||
row.status = RecordStatus(status)
|
||||
after = {"name": row.name, "note": row.note, "status": row.status.value}
|
||||
|
||||
db.flush()
|
||||
audit.record(db, action="record.update", entity_type="record", entity_id=row.id,
|
||||
actor_id=user.id, ip=ip, diff=changes.diff_of(before, after))
|
||||
return _as_dict(row)
|
||||
|
||||
|
||||
def delete_record(db: DbSession, user: AppUser, record_id: uuid.UUID,
|
||||
ip: str | None = None) -> None:
|
||||
row = db.get(Record, record_id)
|
||||
if row is None:
|
||||
raise NotFoundError("Not found.")
|
||||
authz.assert_can_write(db, user, row.owner_id)
|
||||
audit.record(db, action="record.delete", entity_type="record", entity_id=row.id,
|
||||
actor_id=user.id, detail=row.name, ip=ip)
|
||||
db.delete(row)
|
||||
db.flush()
|
||||
|
||||
|
||||
def counts(db: DbSession, user: AppUser) -> dict:
|
||||
rows = list_records(db, user)
|
||||
return {
|
||||
"total": len(rows),
|
||||
"open": sum(1 for r in rows if r["status"] == RecordStatus.open.value),
|
||||
"done": sum(1 for r in rows if r["status"] == RecordStatus.done.value),
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
"""What a person may do in Agora, bound to Agora — a thin shim.
|
||||
|
||||
The model lives in `dredd_core.moderation` (shared across the family); this binds this app's slug and
|
||||
mode onto a `ModerationService` and re-exports its operations, exactly as `services/auth.py` does for
|
||||
`AuthPolicy`. Configuration, not logic — the rule and its implementation stay in core.
|
||||
|
||||
ADMINISTRATOR the whole platform: every module, and the hub `app_user.is_admin`
|
||||
MODERATOR administers exactly one module a `module_permission` row
|
||||
USER may use exactly one module a `module_permission` row
|
||||
|
||||
The module in question is always this one — `MODULE_SLUG` in the settings (`agora`).
|
||||
|
||||
The fourth answer is **no row**, and it is the default for everybody: no access to this module at
|
||||
all. That is what `assert_may_use` below is for, and `deps.get_current_user` is where it is asked.
|
||||
Without it a person with a platform account reaches every screen here — they see an empty app
|
||||
because they have no grants on anything, but nothing has refused them, and "you can see nothing" is
|
||||
not an access decision.
|
||||
|
||||
Three words, used verbatim in the guard names, the API fields and the console copy, because two words
|
||||
for one idea is how a permission model rots. An administrator is a moderator of everything by
|
||||
definition; a moderator is nothing outside their own module.
|
||||
|
||||
**This app reads these rows and never writes them.** `permission_writes_enabled` stays False, so
|
||||
`grant` and `revoke` raise a clean 409 rather than reaching a table this app's runtime role holds only
|
||||
SELECT on. That is the point of the design rather than an omission: a module that could write its own
|
||||
permission rows could admit anyone, promote anyone, and promote itself — permanent administration of
|
||||
itself, which the hub would neither see nor be able to take back. Who may use a module, and who
|
||||
administers it, is decided in the hub, by an administrator, with an audit row to show for it.
|
||||
|
||||
**Standalone it is inert.** With `shared_permissions=False` — which is every deployment that has no
|
||||
IDENTITY_SCHEMA — `module_role` answers `"user"` for everybody (and `"moderator"` for an
|
||||
administrator) and emits no SQL at all, so a single-tenant install behaves precisely as it always
|
||||
has and `assert_may_use` at the edge refuses nobody. That is what keeps "standalone with its own
|
||||
identity" and "module of a platform" the same code rather than two, and it is the property to defend
|
||||
the first time the two modes are tempted to fork.
|
||||
|
||||
**NO logic may be added here**, for the same reason as the other shims: an authorization model that
|
||||
differs per app is one nobody can audit. Change dredd-core, tag a release, repin.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dredd_core.moderation import ModerationPolicy, ModerationService
|
||||
|
||||
from ..config import get_settings
|
||||
|
||||
settings = get_settings()
|
||||
|
||||
POLICY = ModerationPolicy(
|
||||
module_slug=settings.module_slug,
|
||||
# Per-module permissions are a platform idea: without a shared identity store there is nowhere
|
||||
# for the row to live, nobody but this app to have written it, and only one app to be admitted
|
||||
# to.
|
||||
shared_permissions=settings.shares_identity,
|
||||
# Never, in a module. See the docstring — this is the model's whole safety property.
|
||||
permission_writes_enabled=False,
|
||||
)
|
||||
SERVICE = ModerationService(POLICY)
|
||||
|
||||
is_administrator = SERVICE.is_administrator
|
||||
# The one read every other question here is asked in terms of: None (no access), "user" or
|
||||
# "moderator". Bound alongside the guards because this file is what the routers import from, and a
|
||||
# caller reaching past it into `SERVICE` is how a shim stops being the one place the policy applies.
|
||||
module_role = SERVICE.module_role
|
||||
may_use = SERVICE.may_use
|
||||
assert_may_use = SERVICE.assert_may_use
|
||||
is_moderator = SERVICE.is_moderator
|
||||
assert_moderator = SERVICE.assert_moderator
|
||||
moderated_slugs = SERVICE.moderated_slugs
|
||||
moderator_ids = SERVICE.moderator_ids
|
||||
|
||||
__all__ = [
|
||||
"POLICY",
|
||||
"SERVICE",
|
||||
"is_administrator",
|
||||
"module_role",
|
||||
"may_use",
|
||||
"assert_may_use",
|
||||
"is_moderator",
|
||||
"assert_moderator",
|
||||
"moderated_slugs",
|
||||
"moderator_ids",
|
||||
]
|
||||
@@ -0,0 +1,116 @@
|
||||
"""Instance settings as auditable key/value rows — a closed, typed set.
|
||||
|
||||
Secrets never live here — they come from the environment. `app_setting` is for choices an
|
||||
administrator makes in the console and that must be visible in the audit log afterwards.
|
||||
|
||||
The set of keys is **closed**: `SPECS` is the whole vocabulary, and a write naming any other key is
|
||||
refused. An open key/value endpoint lets anything holding an admin session park arbitrary strings in
|
||||
a table the console trusts, and a typo silently creates a setting nothing reads. Rows for keys that
|
||||
are no longer specified are ignored rather than served. Add a setting by adding a `Spec`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session as DbSession
|
||||
|
||||
from ..errors import ValidationError
|
||||
from ..models import AppSetting
|
||||
|
||||
TEXT, BOOL, CHOICE = "text", "bool", "choice"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Spec:
|
||||
kind: str
|
||||
default: str
|
||||
max_length: int = 0
|
||||
required: bool = False
|
||||
choices: tuple[str, ...] = ()
|
||||
|
||||
|
||||
SPECS: dict[str, Spec] = {
|
||||
# What the console calls this instance. Plain text; the console escapes it.
|
||||
"instance_name": Spec(TEXT, "Agora", max_length=80, required=True),
|
||||
}
|
||||
|
||||
|
||||
def _typed(spec: Spec, raw: str) -> Any:
|
||||
return raw == "true" if spec.kind == BOOL else raw
|
||||
|
||||
|
||||
def _normalize(key: str, value: Any) -> str:
|
||||
"""The stored string for `value`, or ValidationError. Never trusts the caller's type."""
|
||||
spec = SPECS.get(key)
|
||||
if spec is None:
|
||||
raise ValidationError(f"Unknown setting: {key}.")
|
||||
if spec.kind == BOOL:
|
||||
if isinstance(value, bool):
|
||||
return "true" if value else "false"
|
||||
if isinstance(value, str) and value.lower() in ("true", "false"):
|
||||
return value.lower()
|
||||
raise ValidationError(f"{key} must be true or false.")
|
||||
if not isinstance(value, str):
|
||||
raise ValidationError(f"{key} must be text.")
|
||||
value = value.strip()
|
||||
if spec.kind == CHOICE:
|
||||
if value not in spec.choices:
|
||||
raise ValidationError(f"{key} must be one of: {', '.join(spec.choices)}.")
|
||||
return value
|
||||
if spec.required and not value:
|
||||
raise ValidationError(f"{key} cannot be empty.")
|
||||
if spec.max_length and len(value) > spec.max_length:
|
||||
raise ValidationError(f"{key} is longer than {spec.max_length} characters.")
|
||||
if any(ord(c) < 32 and c not in "\n\t" for c in value):
|
||||
raise ValidationError(f"{key} contains control characters.")
|
||||
return value
|
||||
|
||||
|
||||
def _stored(db: DbSession) -> dict[str, str]:
|
||||
return {r.key: r.value for r in db.scalars(select(AppSetting)).all() if r.key in SPECS}
|
||||
|
||||
|
||||
def get(db: DbSession, key: str) -> Any:
|
||||
spec = SPECS[key]
|
||||
row = db.get(AppSetting, key)
|
||||
return _typed(spec, row.value if row else spec.default)
|
||||
|
||||
|
||||
def public_config(db: DbSession) -> dict[str, Any]:
|
||||
"""Every setting, typed. None of them may be a secret: any signed-in user reads these."""
|
||||
stored = _stored(db)
|
||||
return {k: _typed(s, stored.get(k, s.default)) for k, s in SPECS.items()}
|
||||
|
||||
|
||||
def describe(db: DbSession) -> list[dict]:
|
||||
stored = _stored(db)
|
||||
return [{
|
||||
"key": k, "kind": s.kind,
|
||||
"value": _typed(s, stored.get(k, s.default)), "default": _typed(s, s.default),
|
||||
"max_length": s.max_length or None, "required": s.required, "choices": list(s.choices),
|
||||
} for k, s in SPECS.items()]
|
||||
|
||||
|
||||
def update(db: DbSession, values: dict[str, Any], *, actor_id=None) -> dict[str, list]:
|
||||
"""Validate every value first, then write the ones that changed. All or nothing.
|
||||
Returns `{key: [before, after]}` for the changed keys — the audit diff."""
|
||||
if not values:
|
||||
raise ValidationError("Nothing to change.")
|
||||
normalized = {k: _normalize(k, v) for k, v in values.items()}
|
||||
stored = _stored(db)
|
||||
changed: dict[str, list] = {}
|
||||
for key, value in normalized.items():
|
||||
before = stored.get(key, SPECS[key].default)
|
||||
if before == value:
|
||||
continue
|
||||
row = db.get(AppSetting, key)
|
||||
if row is None:
|
||||
db.add(AppSetting(key=key, value=value, updated_by=actor_id))
|
||||
else:
|
||||
row.value = value
|
||||
row.updated_by = actor_id
|
||||
changed[key] = [before, value]
|
||||
db.flush()
|
||||
return changed
|
||||
@@ -0,0 +1,23 @@
|
||||
[project]
|
||||
name = "agora-backend"
|
||||
version = "0.1.0"
|
||||
description = "A self-hosted management console."
|
||||
requires-python = ">=3.12"
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["tests"]
|
||||
addopts = "-q"
|
||||
pythonpath = ["."] # put backend/ (rootdir) on sys.path so `import app` works from `cd backend && pytest`
|
||||
filterwarnings = ["ignore::DeprecationWarning"]
|
||||
|
||||
[tool.ruff]
|
||||
line-length = 100
|
||||
target-version = "py312"
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = ["E", "F", "I", "B", "UP", "BLE"]
|
||||
ignore = ["E501"] # line length is handled by the formatter
|
||||
|
||||
[tool.coverage.run]
|
||||
source = ["app"]
|
||||
omit = ["app/observability.py"]
|
||||
@@ -0,0 +1,7 @@
|
||||
-r requirements.txt
|
||||
|
||||
pytest==8.3.4
|
||||
pytest-cov==6.0.0
|
||||
httpx==0.28.1 # also the TestClient transport
|
||||
pip-licenses==5.0.0 # the license gate reads this
|
||||
ruff==0.8.4
|
||||
@@ -0,0 +1,57 @@
|
||||
# Every entry is permissive — the CI license gate (scripts/license_gate.py) denies GPL/AGPL/SSPL.
|
||||
|
||||
# ── The shared core ───────────────────────────────────────────────────────────
|
||||
# dredd-core carries the family's identity + org-tree models, auth, authz, audit, errors, security
|
||||
# helpers and the enum-type creator. It is a real dependency, not copied source: `import dredd_core`
|
||||
# is what puts the shared tables on `Base.metadata`, and the app-side modules that keep the old
|
||||
# filenames are thin re-export shims over it.
|
||||
#
|
||||
# Pinned by TAG, never a branch — a moving ref would change this app's schema between two otherwise
|
||||
# identical `pip install` runs. To move to a newer core: bump the tag, run the tests, and add a NEW
|
||||
# alembic revision for whatever tables or columns the bump brings (never edit 0001).
|
||||
#
|
||||
# From v0.10.0 core also carries what lets this app be a MODULE of the platform rather than its own
|
||||
# island: the shared identity tables and `own_tables`, the column and table grant tiers a module is
|
||||
# held to, the boot assertion and merge helpers (`identity_schema`), the two `AuthPolicy` flags that
|
||||
# turn "this module may not write accounts" into a clean 409 instead of a Postgres permission error
|
||||
# dressed up as a 500, and the tiers (`moderation`, `authz.bind_moderation`). v0.11.0 then turned the
|
||||
# moderator roster into `module_permission` — one row per person per module, carrying a `role`, and
|
||||
# **no row meaning no access to that module at all** — which is what `deps.get_current_user` asks
|
||||
# with `assert_may_use`. Every one of those defaults to the previous behaviour, so a STANDALONE app —
|
||||
# its own database, its own people, no hub — is unchanged by them: core answers `"user"` for
|
||||
# everybody there and emits no SQL. The platform shape is switched on by IDENTITY_SCHEMA and by
|
||||
# nothing else.
|
||||
#
|
||||
# The repo is PRIVATE, so pip needs credentials to fetch it:
|
||||
# local — a GitHub PAT in your git credential helper (or an SSH `insteadOf` rewrite)
|
||||
# CI — the DREDD_CORE_TOKEN repo secret; see the auth step in .github/workflows/ci.yml
|
||||
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.22.0
|
||||
|
||||
# Web framework
|
||||
fastapi==0.115.6
|
||||
uvicorn[standard]==0.34.0
|
||||
python-multipart==0.0.20 # multipart/form-data uploads (Apache-2.0)
|
||||
|
||||
# Validation / settings
|
||||
pydantic==2.10.4
|
||||
pydantic-settings==2.7.1
|
||||
# email validation is done in-app via a regex validator (schemas.Email) — no email-validator dependency
|
||||
|
||||
# DB / ORM / migrations
|
||||
SQLAlchemy==2.0.50
|
||||
alembic==1.14.0
|
||||
pg8000==1.31.2 # pure-Python PostgreSQL driver, BSD-3-Clause (no LGPL, no libpq)
|
||||
|
||||
# Auth
|
||||
argon2-cffi==23.1.0 # Argon2id password hashing (MIT). dredd-core depends on it too, so
|
||||
# this is now a re-pin rather than the only source — kept explicit so
|
||||
# the version is visible here and the license gate sees it named.
|
||||
|
||||
# Outbound HTTP — the ONE client, used only from app/integrations/.
|
||||
httpx==0.28.1 # BSD-3-Clause
|
||||
|
||||
# OpenTelemetry (OTLP → OTel Collector) — optional, import-guarded in observability.py
|
||||
opentelemetry-sdk==1.42.1
|
||||
opentelemetry-exporter-otlp-proto-grpc==1.42.1
|
||||
opentelemetry-instrumentation-fastapi==0.63b1
|
||||
opentelemetry-instrumentation-sqlalchemy==0.63b1
|
||||
@@ -0,0 +1,334 @@
|
||||
"""Pre-flight for a deployment: does the stack definition actually hold together?
|
||||
|
||||
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
|
||||
reverse-proxy service creeping back in. 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 [--env PATH]
|
||||
|
||||
`--env` names the settings file to check (default: the repository's `.env`). When its DATABASE_URL
|
||||
points anywhere but the compose `postgres` service, this machine or a DB_LOCAL_HOSTS entry, the
|
||||
database is external — the family's shared managed database — and both URLs are checked for what that
|
||||
needs: verify-full TLS (against the mounted CA, or the system trust store), exactly this app's own
|
||||
roles (agora_app / agora_migrator: no platform-admin user, no sibling app's role), a
|
||||
pooler's session mode rather than its transaction-mode port 6543, distinct migrator and runtime roles,
|
||||
DB_APP_ROLE naming the runtime role, and a bounded pool.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
from urllib.parse import parse_qs, unquote
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||||
|
||||
_parser = argparse.ArgumentParser(description="Deployment pre-flight for the Agora stack.")
|
||||
_parser.add_argument("--env", type=pathlib.Path, default=ROOT / ".env",
|
||||
help="the settings file to check (default: .env at the repository root)")
|
||||
ENV_PATH: pathlib.Path = _parser.parse_args().env
|
||||
|
||||
problems: list[str] = []
|
||||
notes: list[str] = []
|
||||
|
||||
|
||||
def check(condition: bool, failure: str, ok: str | None = None) -> None:
|
||||
if condition:
|
||||
if ok:
|
||||
notes.append(ok)
|
||||
else:
|
||||
problems.append(failure)
|
||||
|
||||
|
||||
def read(rel: str) -> str:
|
||||
path = ROOT / rel
|
||||
if not path.exists():
|
||||
problems.append(f"missing file: {rel}")
|
||||
return ""
|
||||
return path.read_text(encoding="utf-8")
|
||||
|
||||
|
||||
compose = read("docker-compose.yml")
|
||||
dockerfile = read("backend/Dockerfile")
|
||||
env_example = read(".env.example")
|
||||
config_py = read("backend/app/config.py")
|
||||
main_py = read("backend/app/main.py")
|
||||
roles_sh = read("db/init/01-roles.sh")
|
||||
|
||||
# ── every Settings field is documented in .env.example ────────────────────────
|
||||
# A field the code reads but nobody knows to set is a deploy that comes up misconfigured and
|
||||
# silently wrong, which is worse than one that fails to start.
|
||||
fields = set(re.findall(r"^ ([a-z][a-z0-9_]*): ", config_py, re.M))
|
||||
documented = {line.split("=", 1)[0].strip().lower()
|
||||
for line in env_example.splitlines()
|
||||
if "=" in line and not line.strip().startswith("#")}
|
||||
# Fields with a sensible default that a deployment rarely overrides.
|
||||
OPTIONAL = {"app_base_url", "otel_service_name", "otel_exporter_otlp_endpoint",
|
||||
"seed_demo", "login_max_attempts", "login_lockout_minutes",
|
||||
"session_ttl_hours", "cors_allow_origins"}
|
||||
undocumented = sorted(fields - documented - OPTIONAL)
|
||||
check(not undocumented,
|
||||
f"settings read by config.py but absent from .env.example: {undocumented}",
|
||||
f"all {len(fields)} settings either documented or deliberately defaulted")
|
||||
|
||||
# ── compose wiring ────────────────────────────────────────────────────────────
|
||||
check("env_file: .env" in compose,
|
||||
"compose services do not load .env", "compose loads .env")
|
||||
check(compose.count("image: agora-backend:local") >= 2,
|
||||
"migrate and backend should share one built image",
|
||||
"migrate and backend share one image (no double build)")
|
||||
check("condition: service_completed_successfully" in compose,
|
||||
"backend does not wait for migrate to finish",
|
||||
"backend waits for migrations to complete")
|
||||
check("condition: service_healthy" in compose,
|
||||
"nothing waits on the postgres healthcheck",
|
||||
"migrate waits for a healthy postgres")
|
||||
check('"80:8000"' in compose and "expose:" in compose,
|
||||
"expected the backend published on :80 and postgres expose-only",
|
||||
"only the backend is published; postgres is expose-only")
|
||||
# No reverse proxy: the backend is its own edge (app/edge.py). A proxy service or config file coming
|
||||
# back would mean two places deciding headers and routing again.
|
||||
check("caddy" not in compose.lower() and not (ROOT / "Caddyfile").exists(),
|
||||
"a reverse-proxy service or Caddyfile is back — the backend is its own edge (app/edge.py)",
|
||||
"no reverse proxy: the backend is the edge")
|
||||
check(compose.count("frontend: ./frontend") >= 2,
|
||||
"compose does not pass the console to every build as the `frontend` build context",
|
||||
"every build gets the console as the `frontend` build context")
|
||||
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")
|
||||
|
||||
# ── the Dockerfile matches reality ────────────────────────────────────────────
|
||||
health_path = re.search(r"urlopen\('([^']+)'\)", dockerfile)
|
||||
check(bool(health_path), "Dockerfile healthcheck has no URL")
|
||||
if health_path:
|
||||
route = health_path.group(1).split("localhost:8000", 1)[-1]
|
||||
check("/health" in route,
|
||||
f"healthcheck hits {route} but no such route is registered",
|
||||
f"healthcheck target {route} matches a registered route")
|
||||
check("FORWARDED_ALLOW_IPS:-127.0.0.1" in dockerfile and "FORWARDED_ALLOW_IPS=*" not in env_example,
|
||||
"uvicorn must trust X-Forwarded-For only from 127.0.0.1 by default, never `*`",
|
||||
"forwarded-for handling pinned (audit-log IPs cannot be spoofed)")
|
||||
check("USER app" in dockerfile, "container runs as root",
|
||||
"container drops to a non-root user")
|
||||
|
||||
# ── the image can install the private core ────────────────────────────────────
|
||||
requirements = read("backend/requirements.txt")
|
||||
if "git+https://github.com/Alpaq92/dredd-core" in requirements:
|
||||
# Not `"git" in dockerfile` — the secret-mount RUN names github.com, so that could never fail.
|
||||
# Look for git as a package of an apt/apk install (comments dropped, `\` continuations joined as
|
||||
# BuildKit joins them: whitespace may follow the backslash, and blank lines inside are skipped).
|
||||
run_text = re.sub(r"\\[ \t]*\n(?:[ \t]*\n)*", " ", re.sub(r"(?m)^\s*#.*\n", "", dockerfile))
|
||||
installs_git = re.search(r"\b(?:apt-get|apt|apk)\b[^&;|\n]*?(?<![\w-])(?:install|add)(?![\w-])"
|
||||
r"[^&;|\n]*(?<![\w-])git(?![\w-])", run_text)
|
||||
check("--mount=type=secret,id=dredd_core_token" in dockerfile and bool(installs_git),
|
||||
"requirements pin private dredd-core, but the Dockerfile has no git + BuildKit token secret "
|
||||
"— `docker compose build` cannot fetch it",
|
||||
"Dockerfile installs private dredd-core via git + a BuildKit secret")
|
||||
check(compose.count("dredd_core_token") >= 3,
|
||||
"compose does not pass the dredd_core_token build secret to every service that builds",
|
||||
"compose passes the dredd_core_token build secret")
|
||||
if ENV_PATH.exists() and "DREDD_CORE_TOKEN" in ENV_PATH.read_text(encoding="utf-8"):
|
||||
problems.append("DREDD_CORE_TOKEN is in .env — every container loads .env at runtime; "
|
||||
"export it in the shell for `docker compose build` instead")
|
||||
|
||||
# ── the backend's own edge is wired as documented ─────────────────────────────
|
||||
edge_py = read("backend/app/edge.py")
|
||||
check(bool(re.search(r'API_PREFIX = "([^"]+)"', main_py)), "cannot find API_PREFIX in main.py")
|
||||
check("app.add_middleware(SecurityHeaders" in main_py,
|
||||
"main.py does not add the edge's SecurityHeaders middleware",
|
||||
"SecurityHeaders stamps every response")
|
||||
check("ConsoleUnlessApi(SpaStaticFiles(" in main_py,
|
||||
"the console is not mounted behind ConsoleUnlessApi with the SPA fallback",
|
||||
"console mounted behind ConsoleUnlessApi, with the SPA fallback (deep links survive a reload)")
|
||||
for header in ("X-Content-Type-Options", "X-Frame-Options", "Content-Security-Policy"):
|
||||
check(header in edge_py, f"app/edge.py does not set {header}")
|
||||
check("--no-server-header" in dockerfile, "uvicorn announces itself (no --no-server-header)",
|
||||
"uvicorn runs with --no-server-header")
|
||||
|
||||
# ── secrets and least privilege ───────────────────────────────────────────────
|
||||
check("app" in roles_sh and "migrator" in roles_sh,
|
||||
"db/init does not create both roles")
|
||||
grants_revision = read("backend/alembic/versions/0002_runtime_grants.py")
|
||||
models_init = read("backend/app/models/__init__.py")
|
||||
check("runtime_grants_sql(get_settings().db_app_role" in grants_revision
|
||||
and bool(re.search(r'^APPEND_ONLY_TABLES\b[^=\n]*=\s*\([^)]*"audit_log"', models_init, re.M)),
|
||||
"the runtime-grants migration no longer makes audit_log append-only for DB_APP_ROLE "
|
||||
"(0002_runtime_grants.py / APPEND_ONLY_TABLES in app/models/__init__.py)",
|
||||
"audit_log is append-only for the runtime role DB_APP_ROLE names (0002_runtime_grants)")
|
||||
check("change_me" in env_example,
|
||||
".env.example should ship obvious placeholder passwords")
|
||||
if ENV_PATH.exists():
|
||||
real = ENV_PATH.read_text(encoding="utf-8")
|
||||
if "change_me" in real:
|
||||
problems.append(".env still contains a change_me placeholder password")
|
||||
if real.startswith(""):
|
||||
problems.append(".env has a UTF-8 BOM — pydantic folds it into the first key name")
|
||||
else:
|
||||
notes.append(".env present, BOM-free")
|
||||
|
||||
# ── the shared managed database: provisioning and the compose override ────────
|
||||
provision_sql = read("db/managed/provision.sql")
|
||||
check("--schema agora --app-role agora_app --migrator-role agora_migrator"
|
||||
in provision_sql,
|
||||
"db/managed/provision.sql is not dredd-core's rendering for schema agora "
|
||||
"(re-render it: see db/managed/README.md)",
|
||||
"db/managed/provision.sql provisions schema agora (CI checks it is current)")
|
||||
override = read("docker-compose.managed-db.yml")
|
||||
CA_TARGET = "/run/certs/db-ca.crt"
|
||||
# The platform admin at a provider, and its stand-in in dredd-core's emulation.
|
||||
PLATFORM_ROLES = ("postgres", "postgres_managed")
|
||||
#: Agora's roles in the shared database (db/managed/README.md), the names provision.sql is rendered for.
|
||||
SHARED_ROLES = {"DATABASE_URL": "agora_app", "MIGRATION_DATABASE_URL": "agora_migrator"}
|
||||
|
||||
|
||||
def service_block(name: str) -> str:
|
||||
"""The indented body of one top-level service in the override ("" when absent)."""
|
||||
found = re.search(rf"(?ms)^ {name}:\n(.*?)(?=^ \S|^\S|\Z)", override)
|
||||
return found.group(1) if found else ""
|
||||
|
||||
|
||||
check("profiles:" in service_block("postgres"),
|
||||
"docker-compose.managed-db.yml does not switch the local postgres service off (profiles)",
|
||||
"the managed-db override switches the local postgres off")
|
||||
check("depends_on: !reset" in service_block("migrate"),
|
||||
"docker-compose.managed-db.yml still makes migrate wait for the local postgres",
|
||||
"the managed-db override stops migrate waiting for the local postgres")
|
||||
check(f"target: {CA_TARGET}" in override and "create_host_path: false" in override,
|
||||
f"docker-compose.managed-db.yml does not mount the provider's CA at {CA_TARGET}",
|
||||
f"the managed-db override mounts the provider's CA at {CA_TARGET}")
|
||||
check('MIGRATION_DATABASE_URL: ""' in service_block("backend"),
|
||||
"docker-compose.managed-db.yml leaves the migrator's URL in the long-running backend",
|
||||
"the managed-db override keeps migrator credentials out of the backend")
|
||||
|
||||
|
||||
def env_settings(text: str) -> dict[str, str]:
|
||||
"""KEY=VALUE lines of a compose env file (comments and blank lines skipped, outer quotes removed)."""
|
||||
values = {}
|
||||
for line in text.lstrip("\ufeff").splitlines():
|
||||
if "=" not in line or line.lstrip().startswith("#"):
|
||||
continue
|
||||
key, value = line.split("=", 1)
|
||||
value = value.strip()
|
||||
if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'":
|
||||
value = value[1:-1]
|
||||
values[key.strip().upper()] = value
|
||||
return values
|
||||
|
||||
|
||||
def db_url(name: str, value: str) -> dict | None:
|
||||
"""User, host, port and query of a database URL — or None, after recording why it is unusable."""
|
||||
match = re.match(r"^[A-Za-z][A-Za-z0-9+.-]*://(?P<authority>[^/?#]*)(?P<tail>.*)$", value)
|
||||
if not match:
|
||||
problems.append(f"{name} is not a database URL")
|
||||
return None
|
||||
authority, tail = match.group("authority"), match.group("tail")
|
||||
userinfo, _, hostport = authority.rpartition("@")
|
||||
user, _, password = userinfo.partition(":")
|
||||
# An unencoded @ : / ? # (or a stray %) in a password splits or decodes the URL wrongly.
|
||||
if ("@" in userinfo or ":" in password or re.search(r"%(?![0-9A-Fa-f]{2})", userinfo)
|
||||
or "@" in tail.split("?", 1)[0] or (tail[:1] in ("?", "#") and "@" in tail)):
|
||||
problems.append(f"{name}: percent-encode the password "
|
||||
"(@ as %40, : as %3A, / as %2F, ? as %3F, # as %23, % as %25)")
|
||||
return None
|
||||
host, _, port = hostport.rpartition(":") if re.search(r":[^\]]*$", hostport) else (hostport, "", "")
|
||||
if port and not port.isdigit():
|
||||
problems.append(f"{name}: the port is not a number (an unencoded character in the password?)")
|
||||
return None
|
||||
query = tail.split("?", 1)[1].split("#", 1)[0] if "?" in tail else ""
|
||||
return {"user": unquote(user), "host": host.lower(), "port": int(port) if port else 5432,
|
||||
"query": parse_qs(query), "raw": value}
|
||||
|
||||
|
||||
settings = env_settings(ENV_PATH.read_text(encoding="utf-8")) if ENV_PATH.exists() else {}
|
||||
runtime = db_url("DATABASE_URL", settings["DATABASE_URL"]) if settings.get("DATABASE_URL") else None
|
||||
# The family's TLS rule (dredd_core.db.require_verified_tls, applied by config.py): the compose
|
||||
# postgres service, this machine, or a DB_LOCAL_HOSTS entry is local; every other host is external.
|
||||
LOCAL_HOSTS = {"postgres", "localhost", "127.0.0.1", "[::1]", "::1", ""}
|
||||
LOCAL_HOSTS |= {h.strip().lower().strip("[]") for h in settings.get("DB_LOCAL_HOSTS", "").split(",")}
|
||||
if runtime and runtime["host"].strip("[]") not in LOCAL_HOSTS:
|
||||
notes.append(f"DATABASE_URL points at an external database ({runtime['host']}): "
|
||||
"managed-database checks (db/managed/README.md)")
|
||||
migration = None
|
||||
if settings.get("MIGRATION_DATABASE_URL"):
|
||||
migration = db_url("MIGRATION_DATABASE_URL", settings["MIGRATION_DATABASE_URL"])
|
||||
else:
|
||||
problems.append("MIGRATION_DATABASE_URL is not set: the migrate service runs alembic as the migrator")
|
||||
roles = {}
|
||||
names_ca = False
|
||||
for name, url in (("DATABASE_URL", runtime), ("MIGRATION_DATABASE_URL", migration)):
|
||||
if not url:
|
||||
continue
|
||||
role = url["user"].split(".", 1)[0]
|
||||
roles[name] = role
|
||||
check(not re.search(r"<[^>]*>", url["raw"]), f"{name} still contains a <placeholder>")
|
||||
modes = url["query"].get("sslmode", [])
|
||||
check(modes == ["verify-full"],
|
||||
f"{name} must set sslmode=verify-full (it has {', '.join(modes) or 'no sslmode'}): anything "
|
||||
"weaker does not check who answers, and without it pg8000 falls back to plaintext",
|
||||
f"{name} verifies TLS (sslmode=verify-full)")
|
||||
# verify-full without sslrootcert verifies against the system trust store (a server certificate
|
||||
# that chains to a public CA); with it, the file must be where the override mounts the CA.
|
||||
root_certs = url["query"].get("sslrootcert", [])
|
||||
names_ca = names_ca or bool(root_certs)
|
||||
check(not root_certs or root_certs == [CA_TARGET],
|
||||
f"{name} must set sslrootcert={CA_TARGET}, where docker-compose.managed-db.yml mounts the "
|
||||
"CA (or leave it out to verify against the system trust store)",
|
||||
f"{name} verifies the server against "
|
||||
f"{'the mounted provider CA' if root_certs else 'the system trust store'}")
|
||||
check(role not in PLATFORM_ROLES and role != "",
|
||||
f"{name} logs in as {role or 'no user'}: never the platform admin — use Agora's "
|
||||
"own roles (agora_app / agora_migrator)",
|
||||
f"{name} does not log in as the platform admin ({role})")
|
||||
check(role == SHARED_ROLES[name],
|
||||
f"{name} logs in as {role or 'no user'}, but Agora's role there is {SHARED_ROLES[name]}: "
|
||||
"role names are cluster-wide in the shared database, and the runtime-grants migration grants "
|
||||
"whichever role it is given, so another app's role would carry privileges between schemas",
|
||||
f"{name} logs in as Agora's own role ({role})")
|
||||
check(url["port"] != 6543,
|
||||
f"{name} uses port 6543, a pooler's transaction mode: use session mode (5432)",
|
||||
f"{name} avoids a transaction-mode pooler port (port {url['port']})")
|
||||
if "pooler" in url["host"] and "." not in url["user"]:
|
||||
notes.append(f"{name} logs in through a pooler as plain {role}: some poolers require the "
|
||||
"tenant in the user name (<role>.<tenant>) — check the provider's connection details")
|
||||
if len(roles) == 2:
|
||||
check(roles["DATABASE_URL"] != roles["MIGRATION_DATABASE_URL"],
|
||||
f"DATABASE_URL and MIGRATION_DATABASE_URL both log in as {roles['DATABASE_URL']}: "
|
||||
"the runtime role must not be the migrator",
|
||||
"the runtime and migrator roles differ")
|
||||
if names_ca:
|
||||
ca_file = settings.get("MANAGED_DB_CA_FILE") or "./certs/db-ca.crt"
|
||||
ca_path = pathlib.Path(ca_file) if pathlib.Path(ca_file).is_absolute() else ROOT / ca_file
|
||||
check(ca_path.is_file(),
|
||||
f"the provider's CA file {ca_file} (MANAGED_DB_CA_FILE) does not exist, and the override "
|
||||
"mounts it",
|
||||
"the provider's CA file exists")
|
||||
pool = {knob: settings.get(knob, default) for knob, default in
|
||||
(("DB_POOL_SIZE", "5"), ("DB_MAX_OVERFLOW", "10"))}
|
||||
bounded = (all(re.fullmatch(r"[0-9]+", value) for value in pool.values())
|
||||
and int(pool["DB_POOL_SIZE"]) >= 1)
|
||||
check(bounded,
|
||||
f"DB_POOL_SIZE must be a whole number of at least 1 and DB_MAX_OVERFLOW one of at least 0 "
|
||||
f"(got {pool}): SQLAlchemy reads DB_POOL_SIZE=0 or DB_MAX_OVERFLOW=-1 as no limit at all",
|
||||
f"the backend pool takes at most {sum(int(v) for v in pool.values()) if bounded else '?'} "
|
||||
"connections of the shared database's limit")
|
||||
if runtime:
|
||||
app_role = settings.get("DB_APP_ROLE") or "app"
|
||||
runtime_role = runtime["user"].split(".", 1)[0]
|
||||
check(app_role == runtime_role,
|
||||
f"DB_APP_ROLE is {app_role}, but DATABASE_URL logs in as {runtime_role}: the runtime-grants "
|
||||
"migration would grant the wrong role, or fail",
|
||||
f"DB_APP_ROLE matches the role DATABASE_URL logs in as ({app_role})")
|
||||
|
||||
# ── report ────────────────────────────────────────────────────────────────────
|
||||
for note in notes:
|
||||
print(f" ok {note}")
|
||||
if problems:
|
||||
print()
|
||||
for problem in problems:
|
||||
print(f" FAIL {problem}")
|
||||
print(f"\n{len(problems)} problem(s) — this deployment would not behave as documented.")
|
||||
sys.exit(1)
|
||||
print(f"\nDeploy check passed — {len(notes)} checks, no problems.")
|
||||
@@ -0,0 +1,114 @@
|
||||
"""CI license gate: fail the build if any *shipped* dependency is strong copyleft
|
||||
(GPL / AGPL / SSPL). LGPL is allowed by policy; MPL/Apache/MIT/BSD/HPND/PSF are fine.
|
||||
|
||||
It scans the dependency closure of `requirements.txt` — what actually goes into the image —
|
||||
rather than everything installed in the interpreter. In CI those are the same set; on a
|
||||
developer's machine they are not, and a gate that fails on an unrelated package someone
|
||||
installed years ago is a gate people learn to ignore.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import pathlib
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
DENY = ("AGPL", "SSPL") # always denied
|
||||
DENY_GPL_EXCEPT_LGPL = "GPL" # deny GPL but allow LGPL
|
||||
|
||||
REQUIREMENTS = pathlib.Path(__file__).resolve().parents[1] / "requirements.txt"
|
||||
_NAME = re.compile(r"^\s*([A-Za-z0-9_.\-]+)")
|
||||
|
||||
|
||||
def _norm(name: str) -> str:
|
||||
return re.sub(r"[-_.]+", "-", name).lower()
|
||||
|
||||
|
||||
def declared() -> set[str]:
|
||||
"""The names in requirements.txt, ignoring comments, extras and version pins."""
|
||||
out = set()
|
||||
for line in REQUIREMENTS.read_text(encoding="utf-8").splitlines():
|
||||
line = line.split("#", 1)[0].strip()
|
||||
if not line or line.startswith("-"):
|
||||
continue
|
||||
match = _NAME.match(line)
|
||||
if match:
|
||||
out.add(_norm(match.group(1)))
|
||||
return out
|
||||
|
||||
|
||||
def closure(roots: set[str]) -> set[str]:
|
||||
"""Roots plus everything they require, transitively. Extras and environment markers are
|
||||
ignored: an optional dependency that is installed is one that ships."""
|
||||
from importlib import metadata
|
||||
|
||||
seen: set[str] = set()
|
||||
queue = list(roots)
|
||||
while queue:
|
||||
name = queue.pop()
|
||||
if name in seen:
|
||||
continue
|
||||
seen.add(name)
|
||||
try:
|
||||
dist = metadata.distribution(name)
|
||||
except metadata.PackageNotFoundError:
|
||||
continue
|
||||
for req in dist.requires or []:
|
||||
match = _NAME.match(req)
|
||||
if match:
|
||||
queue.append(_norm(match.group(1)))
|
||||
return seen
|
||||
|
||||
|
||||
def main() -> int:
|
||||
out = subprocess.run(
|
||||
[sys.executable, "-m", "piplicenses", "--format=json"],
|
||||
capture_output=True, text=True,
|
||||
)
|
||||
if out.returncode != 0 or not out.stdout.strip():
|
||||
# Fall back to the console script name (the module form may be unavailable). A missing
|
||||
# executable raises rather than returning non-zero, and a traceback here reads like a
|
||||
# licence violation when it is a missing dev dependency — say which it is.
|
||||
try:
|
||||
out = subprocess.run(["pip-licenses", "--format=json"],
|
||||
capture_output=True, text=True)
|
||||
except FileNotFoundError:
|
||||
print("License gate could not run: pip-licenses is not installed.\n"
|
||||
" pip install -r requirements-dev.txt")
|
||||
return 2
|
||||
installed = json.loads(out.stdout or "[]")
|
||||
|
||||
shipped = closure(declared())
|
||||
missing = sorted(n for n in declared()
|
||||
if n not in {_norm(p["Name"]) for p in installed})
|
||||
scanned, violations = [], []
|
||||
for p in installed:
|
||||
if _norm(p["Name"]) not in shipped:
|
||||
continue
|
||||
scanned.append(p)
|
||||
lic = (p.get("License") or "").upper()
|
||||
if any(tok in lic for tok in DENY):
|
||||
violations.append((p["Name"], p["License"]))
|
||||
elif DENY_GPL_EXCEPT_LGPL in lic and "LGPL" not in lic:
|
||||
violations.append((p["Name"], p["License"]))
|
||||
|
||||
if violations:
|
||||
print("License gate FAILED — disallowed (strong copyleft) dependencies:")
|
||||
for name, lic in violations:
|
||||
print(f" - {name}: {lic}")
|
||||
return 1
|
||||
if missing:
|
||||
# Not a pass. A requirement that is not installed was not checked, and reporting OK
|
||||
# would mean the gate is silently narrower than it claims.
|
||||
print("License gate INCOMPLETE — declared but not installed, so not checked:")
|
||||
for name in missing:
|
||||
print(f" - {name}")
|
||||
print(" pip install -r requirements.txt")
|
||||
return 2
|
||||
print(f"License gate OK — {len(scanned)} shipped packages, no GPL/AGPL/SSPL.")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,83 @@
|
||||
"""Test fixtures.
|
||||
|
||||
Two tiers, on purpose. Unit tests are DB-free and always run, so `pytest` is green on a laptop
|
||||
with no Postgres. Integration tests need a migrated + seeded database and are opted into with
|
||||
AGORA_RUN_INTEGRATION=1 — a suite that fails by default because of missing
|
||||
infrastructure is one people stop running.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import os
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
|
||||
RUN_INTEGRATION = os.environ.get("AGORA_RUN_INTEGRATION") == "1"
|
||||
|
||||
integration = pytest.mark.skipif(
|
||||
not RUN_INTEGRATION,
|
||||
reason="set AGORA_RUN_INTEGRATION=1 with a migrated Postgres to run these",
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def client():
|
||||
"""A TestClient against the real app. Integration only — importing app.main builds the
|
||||
engine, which needs a reachable database."""
|
||||
if not RUN_INTEGRATION:
|
||||
pytest.skip("integration only")
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.main import app
|
||||
|
||||
with TestClient(app) as c:
|
||||
yield c
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def admin_client(client):
|
||||
"""A signed-in admin session, using the bootstrap credentials the seed created."""
|
||||
r = client.post("/api/v1/auth/login", json={"email": ADMIN_EMAIL, "password": ADMIN_PASSWORD})
|
||||
assert r.status_code == 200, r.text
|
||||
client.headers.update({"Authorization": "Bearer " + r.json()["token"]})
|
||||
return client
|
||||
|
||||
|
||||
# ── shared helpers ────────────────────────────────────────────────────────────
|
||||
ADMIN_EMAIL = os.environ.get("BOOTSTRAP_ADMIN_EMAIL", "admin@example.com")
|
||||
ADMIN_PASSWORD = os.environ.get("BOOTSTRAP_ADMIN_PASSWORD", "admin12345")
|
||||
USER_PASSWORD = "correct-horse-1"
|
||||
|
||||
|
||||
def bearer(token: str) -> dict:
|
||||
return {"Authorization": "Bearer " + token}
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def settings_set(admin_client, **values):
|
||||
"""Change instance settings for one block and put back exactly what was there — the suite
|
||||
runs against persistent databases, where a leftover setting is every user's problem."""
|
||||
before = {s["key"]: s["value"] for s in admin_client.get("/api/v1/admin/settings").json()}
|
||||
r = admin_client.put("/api/v1/admin/settings", json={"values": values})
|
||||
assert r.status_code == 200, r.text
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
admin_client.put("/api/v1/admin/settings", json={"values": {k: before[k] for k in values}})
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def make_user(admin_client):
|
||||
"""Create a user (names suffixed per run: users are never deleted) and sign them in."""
|
||||
run = uuid.uuid4().hex[:8]
|
||||
|
||||
def _make(label: str) -> dict:
|
||||
email = f"{label}-{run}@example.com"
|
||||
r = admin_client.post("/api/v1/users", json={
|
||||
"email": email, "full_name": label.title(), "password": USER_PASSWORD})
|
||||
assert r.status_code == 201, r.text
|
||||
login = admin_client.post("/api/v1/auth/login", json={"email": email, "password": USER_PASSWORD})
|
||||
assert login.status_code == 200, login.text
|
||||
return {**r.json(), "token": login.json()["token"]}
|
||||
return _make
|
||||
@@ -0,0 +1,64 @@
|
||||
"""The core shims must expose everything core does.
|
||||
|
||||
A shim that forgets a function fails only when that code path runs — importing the app still
|
||||
succeeds, and no unit test calls it — so the gap ships silently. (It did: list screens broke with
|
||||
"module 'app.services.authz' has no attribute 'readable_node_ids'".) This is the guard. When core
|
||||
gains a public function and the pin moves, these tests name exactly what the shim is missing.
|
||||
DB-free.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
|
||||
from dredd_core.auth import AuthService
|
||||
|
||||
from app.services import auth as auth_shim
|
||||
|
||||
|
||||
def _public_functions(module) -> set[str]:
|
||||
return {name for name, obj in vars(module).items()
|
||||
if not name.startswith("_") and inspect.isfunction(obj)
|
||||
and obj.__module__ == module.__name__}
|
||||
|
||||
|
||||
def test_auth_shim_binds_every_auth_service_operation():
|
||||
operations = {name for name, obj in vars(AuthService).items()
|
||||
if not name.startswith("_") and inspect.isfunction(obj)}
|
||||
missing = sorted(name for name in operations if not hasattr(auth_shim, name))
|
||||
assert not missing, f"services/auth.py does not bind: {missing}"
|
||||
|
||||
|
||||
# In `simple` tenancy services/authz.py is a genuinely local module (this module's administration,
|
||||
# or the owner - no tree), so there is no core authz shim to hold to parity. It still asks
|
||||
# services/moderation.py for the top of the model, which the test below covers.
|
||||
|
||||
|
||||
def test_moderation_shim_binds_every_moderation_service_operation():
|
||||
"""The MODERATOR tier, same rule as the auth shim.
|
||||
|
||||
`services/moderation.py` re-exports a `ModerationService`'s operations as module-level names, so
|
||||
`moderation.is_moderator(db, user)` reads the way `auth_service.authenticate(...)` does. A
|
||||
missing one only fails when that path runs — and the paths here are guards, so the failure is an
|
||||
exception on somebody's administration screen rather than anything a test would catch.
|
||||
"""
|
||||
from dredd_core.moderation import ModerationService
|
||||
|
||||
from app.services import moderation as moderation_shim
|
||||
|
||||
# Six operations are left unbound ON PURPOSE, and the list is here rather than absent so that
|
||||
# a genuinely new core function is still caught by the assertion below.
|
||||
# grant / revoke / revoke_module - a module never writes who may use it. It holds SELECT and
|
||||
# nothing else on `module_permission`, and a shim that exported the call would invite a
|
||||
# router to try it and get a Postgres permission error dressed up as a 500.
|
||||
# list_permissions / member_ids - the roster is answerable in the hub and only there. A module
|
||||
# knows whether YOU may be here and whether YOU may administer it; who else may is the hub's
|
||||
# screen, and exporting the read here is how a second, half-informed copy of it gets built.
|
||||
# module_roles - every module ONE person may open, which is the launcher's question. A module
|
||||
# has no launcher and no business enumerating its siblings' access.
|
||||
deliberately_unbound = {"grant", "revoke", "revoke_module", "list_permissions", "member_ids",
|
||||
"module_roles"}
|
||||
operations = {name for name, obj in vars(ModerationService).items()
|
||||
if not name.startswith("_") and inspect.isfunction(obj)
|
||||
and name not in deliberately_unbound}
|
||||
missing = sorted(name for name in operations if not hasattr(moderation_shim, name))
|
||||
assert not missing, f"services/moderation.py does not bind: {missing}"
|
||||
@@ -0,0 +1,115 @@
|
||||
"""DB-free tests for the backend's own edge (`app/edge.py`).
|
||||
|
||||
There is no reverse proxy: this process serves the console and sets every security header itself.
|
||||
`app.main` needs a database to import, so these build a small app from the same pieces, wired in the
|
||||
same order as main.py.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.edge import (
|
||||
CONSOLE_CSP,
|
||||
content_security_policy,
|
||||
BodySizeLimit,
|
||||
ConsoleUnlessApi,
|
||||
SecurityHeaders,
|
||||
SpaStaticFiles,
|
||||
)
|
||||
|
||||
|
||||
def _client(tmp_path) -> TestClient:
|
||||
(tmp_path / "index.html").write_text("<!doctype html><title>console</title>", encoding="utf-8")
|
||||
(tmp_path / "app.js").write_text("console.log(1)", encoding="utf-8")
|
||||
app = FastAPI()
|
||||
app.add_middleware(BodySizeLimit, max_bytes=1024)
|
||||
|
||||
@app.post("/api/v1/things")
|
||||
def make_thing() -> dict:
|
||||
return {"ok": True}
|
||||
|
||||
@app.get("/healthz")
|
||||
def healthz() -> dict:
|
||||
return {"status": "ok"}
|
||||
|
||||
app.add_middleware(SecurityHeaders)
|
||||
app.mount("/", ConsoleUnlessApi(SpaStaticFiles(directory=str(tmp_path), html=True),
|
||||
app.routes), name="console")
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
def test_console_gets_its_csp_and_no_cache(tmp_path):
|
||||
r = _client(tmp_path).get("/")
|
||||
assert r.status_code == 200
|
||||
assert r.headers["content-security-policy"] == CONSOLE_CSP
|
||||
assert r.headers["cache-control"] == "no-cache"
|
||||
assert r.headers["x-content-type-options"] == "nosniff"
|
||||
assert r.headers["x-frame-options"] == "DENY"
|
||||
assert r.headers["referrer-policy"] == "same-origin"
|
||||
|
||||
|
||||
def test_a_deep_link_falls_back_to_index(tmp_path):
|
||||
r = _client(tmp_path).get("/some/deep/link")
|
||||
assert r.status_code == 200 and "<title>console</title>" in r.text
|
||||
|
||||
|
||||
def test_the_api_gets_the_headers_but_not_the_console_policy(tmp_path):
|
||||
r = _client(tmp_path).get("/healthz")
|
||||
assert r.status_code == 200
|
||||
assert r.headers["x-content-type-options"] == "nosniff"
|
||||
assert "content-security-policy" not in r.headers
|
||||
|
||||
|
||||
def test_the_console_never_answers_for_the_api(tmp_path):
|
||||
client = _client(tmp_path)
|
||||
wrong_method = client.get("/api/v1/things")
|
||||
assert wrong_method.status_code == 405 and wrong_method.headers["allow"] == "POST"
|
||||
unknown = client.get("/api/v1/nope")
|
||||
assert unknown.status_code == 404
|
||||
assert unknown.headers["content-type"] == "application/problem+json"
|
||||
|
||||
|
||||
def test_an_oversized_body_is_refused(tmp_path):
|
||||
r = _client(tmp_path).post("/api/v1/things", content=b"x" * 2048)
|
||||
assert r.status_code == 413
|
||||
|
||||
|
||||
def _framed(tmp_path, value: str):
|
||||
from app.config import Settings
|
||||
(tmp_path / "index.html").write_text("<!doctype html>", encoding="utf-8")
|
||||
app = FastAPI()
|
||||
app.add_middleware(SecurityHeaders, frame_ancestors=Settings(
|
||||
_env_file=None, frame_ancestors=value).frame_ancestors)
|
||||
app.mount("/", ConsoleUnlessApi(SpaStaticFiles(directory=str(tmp_path), html=True),
|
||||
app.routes), name="console")
|
||||
return TestClient(app).get("/").headers
|
||||
|
||||
|
||||
def test_frame_ancestors_default_is_none_and_deny(tmp_path, monkeypatch):
|
||||
from app.config import Settings
|
||||
monkeypatch.delenv("FRAME_ANCESTORS", raising=False)
|
||||
assert Settings(_env_file=None).frame_ancestors == "'none'"
|
||||
h = _framed(tmp_path, "'none'")
|
||||
assert h["x-frame-options"] == "DENY"
|
||||
assert h["content-security-policy"] == CONSOLE_CSP
|
||||
assert "frame-ancestors 'none';" in CONSOLE_CSP
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", ["'self'", "self", " 'self' "])
|
||||
def test_frame_ancestors_self_is_sameorigin(tmp_path, value):
|
||||
h = _framed(tmp_path, value)
|
||||
assert h["x-frame-options"] == "SAMEORIGIN"
|
||||
assert h["content-security-policy"] == content_security_policy("'self'")
|
||||
assert "frame-ancestors 'self';" in h["content-security-policy"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", ["", "*", "https://evil.example", "'self' https://x.example",
|
||||
"'unsafe-inline'"])
|
||||
def test_frame_ancestors_anything_else_refuses_startup(value):
|
||||
from pydantic import ValidationError
|
||||
|
||||
from app.config import Settings
|
||||
with pytest.raises(ValidationError, match="FRAME_ANCESTORS must be 'none' or 'self'"):
|
||||
Settings(_env_file=None, frame_ancestors=value)
|
||||
@@ -0,0 +1,431 @@
|
||||
"""One platform, one account — the parts of it that can be proved without a database.
|
||||
|
||||
What these tests are for: **the default must be standalone, and the switch must be one setting.**
|
||||
A generated app ships with its own accounts, its own sign-in and its own Users administration, and
|
||||
it has to keep working that way for ever; joining a platform is `IDENTITY_SCHEMA` plus provisioning
|
||||
plus one migration. Everything below either pins that default or pins a refusal that would otherwise
|
||||
be discovered half-way through `alembic upgrade` on somebody's live database.
|
||||
|
||||
What they deliberately do NOT prove, because branches are not permissions: that the grants take,
|
||||
that this app's role really cannot read `password_hash`, that the merge loses no row. Those need a
|
||||
column-restricted role and real data — the managed-database CI job and a rehearsed cutover. These
|
||||
are the fast tripwire in front of that, never a substitute for it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import importlib
|
||||
import importlib.util
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
import uuid
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
VERSIONS = pathlib.Path(__file__).resolve().parents[1] / "alembic" / "versions"
|
||||
REVISION = VERSIONS / "0003_shared_identity.py"
|
||||
RENAME_REVISION = VERSIONS / "0004_module_permission.py"
|
||||
|
||||
#: The config-only shims: they read their settings once, at import, which is what makes them free at
|
||||
#: runtime and what makes a test have to reload them.
|
||||
_SHIMS = ("app.services.auth", "app.services.moderation")
|
||||
|
||||
|
||||
def _reload_shims() -> None:
|
||||
for name in _SHIMS:
|
||||
module = sys.modules.get(name)
|
||||
if module is not None:
|
||||
importlib.reload(module)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _no_ambient_platform(monkeypatch):
|
||||
"""Ignore whatever the shell says about the platform.
|
||||
|
||||
pydantic-settings reads `os.environ` even when no env file is loaded, and a CI job that
|
||||
exercises the platform shape exports exactly these names before running pytest. Without this,
|
||||
"the default is standalone" would quietly become "whatever the shell says": green on a laptop,
|
||||
and red in CI for the right reason after passing for the wrong one everywhere else.
|
||||
"""
|
||||
from app import config
|
||||
|
||||
for name in ("IDENTITY_SCHEMA", "MODULE_SLUG", "IDENTITY_HUB_URL", "SESSION_COOKIE_NAME"):
|
||||
monkeypatch.delenv(name, raising=False)
|
||||
config.get_settings.cache_clear()
|
||||
_reload_shims()
|
||||
yield
|
||||
config.get_settings.cache_clear()
|
||||
_reload_shims()
|
||||
|
||||
|
||||
def _settings(**overrides):
|
||||
from app.config import Settings
|
||||
|
||||
return Settings(_env_file=None, **overrides)
|
||||
|
||||
|
||||
def _load(path: pathlib.Path):
|
||||
"""A revision, loaded from its file — they are not importable as modules."""
|
||||
spec = importlib.util.spec_from_file_location(f"_rev_{path.stem}", path)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def _revision():
|
||||
"""The cutover revision."""
|
||||
return _load(REVISION)
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def _as_a_module(monkeypatch, schema: str = "dredd"):
|
||||
"""Run a block as if this deployment were a module of the platform.
|
||||
|
||||
The config-only shims read their settings at import, which is what makes them free at runtime;
|
||||
the price is that a test has to reload them. Both are reloaded back afterwards, so nothing
|
||||
leaks into the rest of the suite.
|
||||
"""
|
||||
from app import config
|
||||
from app.services import auth as auth_shim
|
||||
from app.services import moderation as moderation_shim
|
||||
|
||||
monkeypatch.setenv("IDENTITY_SCHEMA", schema)
|
||||
config.get_settings.cache_clear()
|
||||
_reload_shims()
|
||||
try:
|
||||
yield auth_shim, moderation_shim
|
||||
finally:
|
||||
monkeypatch.delenv("IDENTITY_SCHEMA", raising=False)
|
||||
config.get_settings.cache_clear()
|
||||
_reload_shims()
|
||||
|
||||
|
||||
# ── the default ───────────────────────────────────────────────────────────────
|
||||
def test_a_generated_app_is_standalone_until_somebody_says_otherwise():
|
||||
"""The hard rule. An app with its own database, its own people and no platform must run."""
|
||||
s = _settings()
|
||||
assert s.identity_schema == ""
|
||||
assert s.shares_identity is False
|
||||
assert s.identity_hub_url == ""
|
||||
assert s.session_cookie_name == "agora_session"
|
||||
|
||||
|
||||
def test_one_setting_is_the_whole_switch():
|
||||
assert _settings(identity_schema="dredd").shares_identity is True
|
||||
|
||||
|
||||
def test_standalone_keeps_every_local_capability():
|
||||
"""Nothing about the platform policy flags may change a standalone app's behaviour."""
|
||||
from app.services import auth as auth_shim
|
||||
|
||||
policy = auth_shim._POLICY
|
||||
assert policy.local_login_enabled is True
|
||||
assert policy.identity_writes_enabled is True
|
||||
assert policy.app_tokens_enabled is True
|
||||
|
||||
|
||||
def test_a_module_signs_nobody_in_and_writes_no_accounts(monkeypatch):
|
||||
with _as_a_module(monkeypatch) as (auth_shim, moderation_shim):
|
||||
policy = auth_shim._POLICY
|
||||
# Nobody signs in here: they sign in at the hub and this module resolves the same session.
|
||||
assert policy.local_login_enabled is False
|
||||
# Accounts are created, renamed and re-passworded in ONE place.
|
||||
assert policy.identity_writes_enabled is False
|
||||
# Minting moves to the hub — a role that could insert a `session` row could mint a working
|
||||
# credential for the administrator. Listing and revoking are untouched by this flag.
|
||||
assert policy.app_tokens_enabled is False
|
||||
# And the per-module permissions wake up, keyed by this module's own slug.
|
||||
assert moderation_shim.POLICY.shared_permissions is True
|
||||
assert moderation_shim.POLICY.module_slug == "agora"
|
||||
# A module never writes them. If it could, a compromised module could admit anyone, promote
|
||||
# anyone and promote itself, and the hub could neither see it nor take it back.
|
||||
assert moderation_shim.POLICY.permission_writes_enabled is False
|
||||
|
||||
|
||||
def test_the_permission_model_is_inert_standalone():
|
||||
from app.services import moderation as moderation_shim
|
||||
|
||||
assert moderation_shim.POLICY.shared_permissions is False
|
||||
assert moderation_shim.POLICY.permission_writes_enabled is False
|
||||
|
||||
|
||||
def test_the_guards_work_with_no_database_at_all():
|
||||
"""Standalone, the whole model resolves from `user.is_admin` and emits not one statement.
|
||||
|
||||
Proved by passing `None` where the `Session` goes: if anything reached the database it would
|
||||
raise `AttributeError` here rather than pass. That is the property that makes the two deployment
|
||||
shapes ONE code path — a standalone app pays nothing for machinery it does not use — and it is
|
||||
also why `services/authz.py` in `simple` tenancy can take a `Session` it will usually ignore.
|
||||
"""
|
||||
from dredd_core.errors import AuthorizationError
|
||||
|
||||
from app.services import moderation as moderation_shim
|
||||
|
||||
administrator = SimpleNamespace(id=uuid.uuid4(), is_admin=True)
|
||||
ordinary = SimpleNamespace(id=uuid.uuid4(), is_admin=False)
|
||||
|
||||
assert moderation_shim.is_moderator(None, administrator) is True
|
||||
assert moderation_shim.is_moderator(None, ordinary) is False
|
||||
assert moderation_shim.assert_moderator(None, administrator) is administrator
|
||||
with pytest.raises(AuthorizationError):
|
||||
moderation_shim.assert_moderator(None, ordinary)
|
||||
# The Users screen asks for the whole roster in one call; standalone there is nobody to name.
|
||||
assert moderation_shim.moderator_ids(None) == set()
|
||||
|
||||
|
||||
def test_a_standalone_app_admits_everybody_it_has_an_account_for():
|
||||
"""The hard rule, at the guard that could break it. `assert_may_use` sits at the edge of every
|
||||
authenticated route, so if it refused anybody standalone, a generated app with its own database
|
||||
and its own people would ship unusable.
|
||||
|
||||
`None` for the session is the assertion again: with no platform to be admitted to, core answers
|
||||
`"user"` for everyone without looking anything up. Having an account here IS permission to use
|
||||
the one application there is.
|
||||
"""
|
||||
from app.services import moderation as moderation_shim
|
||||
|
||||
for user in (SimpleNamespace(id=uuid.uuid4(), is_admin=True),
|
||||
SimpleNamespace(id=uuid.uuid4(), is_admin=False)):
|
||||
assert moderation_shim.may_use(None, user) is True
|
||||
assert moderation_shim.assert_may_use(None, user) is user
|
||||
|
||||
|
||||
def test_the_edge_asks_whether_this_person_may_be_here_at_all():
|
||||
"""The guard the permission table exists for, in the one place that covers every route.
|
||||
|
||||
`get_current_user` is what every authenticated route depends on, which is why token scope is
|
||||
checked there and nowhere else; the same argument makes it the only honest home for "may this
|
||||
person open this module". Read off the AST rather than by grep, so a call that is commented out
|
||||
— or moved inside a branch a standalone deployment skips — does not pass for the real thing.
|
||||
"""
|
||||
import ast
|
||||
import inspect
|
||||
|
||||
from app import deps
|
||||
|
||||
function = ast.parse(inspect.getsource(deps.get_current_user)).body[0]
|
||||
calls = [node for node in ast.walk(function)
|
||||
if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)
|
||||
and node.func.attr == "assert_may_use"]
|
||||
assert calls, "get_current_user does not ask whether this person may use this module"
|
||||
# At the top level of the function body, not inside an `if`: the answer must not depend on a
|
||||
# deployment shape. Standalone, core answers "user" for everybody and emits no SQL, which is
|
||||
# precisely what lets one guard serve both.
|
||||
top_level = [statement for statement in function.body
|
||||
if isinstance(statement, ast.Expr) and statement.value in calls]
|
||||
assert top_level, "the check is nested — it must apply to every deployment unconditionally"
|
||||
# And after the scope check, which is the cheaper of the two and the one that needs no row.
|
||||
scope = next(i for i, s in enumerate(function.body)
|
||||
if isinstance(s, ast.If) and "scope" in ast.dump(s.test))
|
||||
assert function.body.index(top_level[0]) > scope
|
||||
|
||||
|
||||
# ── refusals that would otherwise surface mid-migration ───────────────────────
|
||||
@pytest.mark.parametrize("bad", ["Dredd", "1dredd", "dredd schema", "dredd;drop", "dredd.public",
|
||||
"shared-identity"])
|
||||
def test_a_schema_name_that_reaches_ddl_is_refused_at_startup(bad):
|
||||
"""It is rendered into DDL, one statement of which DROPs this app's local identity tables.
|
||||
|
||||
The hyphen in the last case is the one that does not look wrong. It is a legal PostgreSQL schema
|
||||
name *when quoted*, and 0003 renders it UNQUOTED (`FROM <identity>.app_user`); dredd-core refuses
|
||||
it outright wherever it renders it. A validator laxer than either would let the app start, run
|
||||
standalone perfectly, and then fail on the day it matters — as a syntax error half-way through
|
||||
`alembic upgrade`, or as a bare ValueError out of the lifespan that the friendly handler in
|
||||
`main.py` catches nothing of, because it catches `IdentitySchemaError`.
|
||||
"""
|
||||
with pytest.raises(ValidationError):
|
||||
_settings(identity_schema=bad)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad", ["my_app", "My-App", "-app", "a" * 41, "app slug"])
|
||||
def test_a_module_slug_the_shared_table_would_reject_is_refused_at_startup(bad):
|
||||
"""The trap this app could never notice on its own, because nothing here would raise.
|
||||
|
||||
`dredd.module_permission` constrains the column to `^[a-z0-9][a-z0-9-]{0,39}$` — underscores are
|
||||
out, because a module slug is a URL path segment. This app only ever SELECTs by that slug; it
|
||||
holds no INSERT. So an illegal slug does not fail: it makes `WHERE module_slug = 'my_app'` a
|
||||
query no row can ever match, while the hub's CHECK refuses the INSERT at the other end of the
|
||||
platform. Nobody may use this app, for ever, and no error anywhere to explain it.
|
||||
|
||||
`my_app` leads the list on purpose: it is exactly what `slugify("My App")` produces for the
|
||||
Postgres schema, so it is the shape a scaffolded two-word app would have carried by default.
|
||||
"""
|
||||
with pytest.raises(ValidationError):
|
||||
_settings(module_slug=bad)
|
||||
|
||||
|
||||
def test_the_generated_module_slug_is_one_the_hub_would_accept():
|
||||
"""Whatever the scaffolder derived has to satisfy the constraint above, or every app whose name
|
||||
has two words in it ships with the tier quietly broken."""
|
||||
assert re.fullmatch(r"[a-z0-9][a-z0-9-]{0,39}", _settings().module_slug)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad", ["dredd session", "dredd;session", "dredd,session", ""])
|
||||
def test_a_cookie_name_a_browser_would_drop_is_refused(bad):
|
||||
"""A name carrying a separator is dropped silently and the symptom is a login that
|
||||
"doesn't stick" — the worst class of bug to debug from the outside."""
|
||||
with pytest.raises(ValidationError):
|
||||
_settings(session_cookie_name=bad)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad", ["javascript:alert(1)", "//evil.test", "/hub\\evil", "atrium"])
|
||||
def test_a_hub_address_that_is_not_an_address_is_refused(bad):
|
||||
"""It becomes an href on the one screen nobody is signed in to. An operator's typo should stop
|
||||
the process rather than produce a link that goes somewhere else."""
|
||||
with pytest.raises(ValidationError):
|
||||
_settings(identity_hub_url=bad)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("good", ["/atrium/", "/hub", "https://example.test/hub", ""])
|
||||
def test_the_addresses_a_hub_can_actually_have_are_accepted(good):
|
||||
assert _settings(identity_hub_url=good).identity_hub_url == good
|
||||
|
||||
|
||||
def test_a_module_must_know_which_module_it_is():
|
||||
"""`module_permission` rows are keyed by slug, so a module with none resolves nobody's row —
|
||||
and since no row is no access, it would refuse everyone but a platform administrator, who is
|
||||
the one person unable to reproduce it."""
|
||||
with pytest.raises(ValidationError):
|
||||
_settings(identity_schema="dredd", module_slug="")
|
||||
|
||||
|
||||
# ── the guard ─────────────────────────────────────────────────────────────────
|
||||
def test_this_app_has_no_platform_wide_guard():
|
||||
"""A module defines `require_moderator` and nothing else.
|
||||
|
||||
After a cutover every power left in a module is module-scoped; the platform-wide ones moved to
|
||||
the hub. A route here guarded by the platform-wide tier would only mean "a moderator may not do
|
||||
the thing they were made a moderator to do".
|
||||
"""
|
||||
from app import deps
|
||||
|
||||
assert hasattr(deps, "require_moderator")
|
||||
assert not hasattr(deps, "require_admin")
|
||||
assert not hasattr(deps, "require_administrator")
|
||||
|
||||
|
||||
def test_no_router_decides_access_from_the_platform_wide_flag():
|
||||
"""`is_admin` may be SERIALISED by a router (the console draws a chip from it); it may not be
|
||||
read to decide what somebody is allowed to do. The tier for that is `require_moderator`."""
|
||||
routers = (pathlib.Path(__file__).resolve().parents[1] / "app" / "routers")
|
||||
offenders = []
|
||||
for path in sorted(routers.glob("*.py")):
|
||||
for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1):
|
||||
stripped = line.strip()
|
||||
if stripped.startswith("#") or '"is_admin"' in stripped or "is_admin=" in stripped:
|
||||
continue
|
||||
if re.search(r"\bif\s+(not\s+)?\w+\.is_admin\b", stripped):
|
||||
offenders.append(f"{path.name}:{number}")
|
||||
assert not offenders, f"routers deciding access from is_admin: {offenders}"
|
||||
|
||||
|
||||
# ── the cutover revision ──────────────────────────────────────────────────────
|
||||
def test_the_cutover_does_nothing_at_all_when_there_is_no_platform():
|
||||
"""The hard rule again, at the one place that could break a standalone database. It must return
|
||||
before it touches `op`, which is why this can run with no alembic context at all."""
|
||||
rev = _revision()
|
||||
assert rev.upgrade() is None
|
||||
assert rev.downgrade() is None
|
||||
|
||||
|
||||
def test_the_cutover_refuses_to_be_undone_on_a_platform(monkeypatch):
|
||||
"""There is no honest un-merge: the mapping back died with the transaction that used it, and
|
||||
`0001`'s drop_all would resolve `app_user` through the search_path to the SHARED table."""
|
||||
from app import config
|
||||
|
||||
monkeypatch.setenv("IDENTITY_SCHEMA", "dredd")
|
||||
config.get_settings.cache_clear()
|
||||
try:
|
||||
with pytest.raises(NotImplementedError):
|
||||
_revision().downgrade()
|
||||
finally:
|
||||
monkeypatch.delenv("IDENTITY_SCHEMA", raising=False)
|
||||
config.get_settings.cache_clear()
|
||||
|
||||
|
||||
def test_every_column_that_names_a_person_is_found():
|
||||
"""Derived from the metadata rather than listed, so a domain table added next month is covered
|
||||
without anybody remembering to add it here."""
|
||||
rev = _revision()
|
||||
found = {(table, column) for table, column, _ in rev._person_columns()}
|
||||
assert ("audit_log", "actor_id") in found
|
||||
assert ("app_setting", "updated_by") in found
|
||||
assert ("record", "created_by") in found # the app's own demo table
|
||||
# The shared tables' own person-columns are the hub's, in the hub's schema, and were never local.
|
||||
assert not any(table in {"app_user", "session", "module_permission"} for table, _ in found)
|
||||
|
||||
|
||||
def test_the_column_postgres_would_never_complain_about_is_not_forgotten():
|
||||
"""`permission_grant.principal_id` carries no foreign key — it is polymorphic on
|
||||
`principal_type` — so a row the merge missed would grant nobody anything, for ever, and the only
|
||||
symptom would be a person who cannot see something they could see yesterday."""
|
||||
rev = _revision()
|
||||
polymorphic = [row for row in rev._person_columns()
|
||||
if row[0] == "permission_grant" and row[1] == "principal_id"]
|
||||
assert len(polymorphic) == 1
|
||||
assert "principal_type" in polymorphic[0][2]
|
||||
|
||||
|
||||
def test_the_constraint_phases_must_stay_paired():
|
||||
"""This revision separates core's interleaved DROP/ADD pairs because a merge that CHANGES ids
|
||||
cannot run them paired. If core ever renders something else, that must be loud — the quiet
|
||||
version is a migration that drops constraints and never puts them back."""
|
||||
rev = _revision()
|
||||
drops, adds = rev._constraint_phases(
|
||||
['ALTER TABLE "x" DROP CONSTRAINT "c"', 'ALTER TABLE "x" ADD CONSTRAINT "c" FOREIGN KEY'])
|
||||
assert len(drops) == len(adds) == 1
|
||||
with pytest.raises(RuntimeError):
|
||||
rev._constraint_phases(['ALTER TABLE "x" DROP CONSTRAINT "c"'])
|
||||
|
||||
|
||||
def test_no_statement_carries_a_sequence_the_driver_would_eat():
|
||||
"""SQLAlchemy scans the text it is handed for bind parameters — SQL COMMENTS INCLUDED — so a
|
||||
stray `:name` or `%` anywhere in these templates fails the migration on its first live run with
|
||||
"a value is required for bind parameter". That is a real bug this family has already had, in a
|
||||
comment that was *explaining* this very rule."""
|
||||
statements = {name: getattr(_revision(), name)
|
||||
for name in ("_PREFLIGHT", "_BUILD_MAP", "_SUMMARY", "_REPOINT", "_DROP_LOCAL")}
|
||||
# `_RENAME_OR_CREATE` carries table DDL rendered from the metadata, so it is the likeliest of
|
||||
# all of them to grow one of these by accident.
|
||||
statements["_RENAME_OR_CREATE"] = _load(RENAME_REVISION)._RENAME_OR_CREATE
|
||||
for name, sql in statements.items():
|
||||
assert "%" not in sql, f"{name} contains a percent sign"
|
||||
assert not re.search(r"(?<!:):\w", sql), f"{name} contains a colon-name sequence"
|
||||
|
||||
|
||||
# ── the rename revision ───────────────────────────────────────────────────────
|
||||
def test_the_rename_decides_from_the_catalog_and_never_from_a_setting():
|
||||
"""Which of the three shapes a database is in depends on which core was pinned the day `0001`
|
||||
ran, and nothing outside the database knows that. So every branch is a `to_regclass` test inside
|
||||
one statement — which also keeps `alembic upgrade --sql` honest, since an offline render has no
|
||||
connection to ask and must emit SQL that decides for itself."""
|
||||
sql = _load(RENAME_REVISION)._RENAME_OR_CREATE
|
||||
assert sql.count("to_regclass") >= 3
|
||||
assert "module_permission" in sql and "module_moderator" in sql
|
||||
# The create branch is guarded on a LOCAL app_user, not on an `ELSE`. On the platform `0003` has
|
||||
# just dropped the local identity tables, and creating one here would be the shadow copy the
|
||||
# lifespan assertion exists to catch — a second roster the search_path reaches first.
|
||||
assert "'.app_user'" in sql
|
||||
|
||||
|
||||
def test_a_renamed_row_keeps_the_only_meaning_it_ever_had():
|
||||
"""The old table had one meaning: a row in it was a moderator. Leaving those rows at the
|
||||
column's default would silently demote every moderator this platform has appointed, and nothing
|
||||
would report it — they would simply stop being able to administer their own module."""
|
||||
sql = " ".join(_load(RENAME_REVISION)._RENAME_OR_CREATE.split())
|
||||
assert "SET role = ' || quote_literal('moderator')" in sql
|
||||
|
||||
|
||||
def test_every_name_the_rename_has_to_carry_is_named():
|
||||
"""`ALTER TABLE ... RENAME TO` moves the table and nothing else: its constraints and its index
|
||||
keep names built from the old one. Harmless until the day a later revision drops one by the name
|
||||
the metadata gives it, and fails on exactly the oldest databases."""
|
||||
rev = _load(RENAME_REVISION)
|
||||
assert {new for _, new in rev._CONSTRAINTS} == {
|
||||
"pk_module_permission", "uq_module_permission_user_module", "ck_module_permission_slug",
|
||||
"fk_module_permission_user_id_app_user", "fk_module_permission_created_by_app_user",
|
||||
}
|
||||
assert rev._INDEXES == (("ix_module_moderator_module_slug", "ix_module_permission_module_slug"),)
|
||||
@@ -0,0 +1,228 @@
|
||||
"""The API against a real, migrated and seeded Postgres — run as the least-privilege `app` role.
|
||||
|
||||
Opt in with AGORA_RUN_INTEGRATION=1 (CI does). Names are suffixed per run and every
|
||||
setting a test changes is put back, so the suite can be re-run against the same database: users
|
||||
cannot be deleted, only deactivated, and nothing here depends on a clean slate.
|
||||
|
||||
This is the floor every app in the family inherits: authentication, the admin boundary, the closed
|
||||
settings set, access control on the demo entity, bad input as 422 (never 500), the cross-site write
|
||||
refusal, and the append-only audit log held by the database itself. Replace the demo-entity tests
|
||||
with the real domain's; keep the rest.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
from conftest import ADMIN_EMAIL, ADMIN_PASSWORD, USER_PASSWORD, bearer, integration, settings_set
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.exc import ProgrammingError
|
||||
|
||||
pytestmark = integration
|
||||
|
||||
RUN = uuid.uuid4().hex[:8]
|
||||
NODES = importlib.util.find_spec("app.services.nodes") is not None # tenancy `nodes`
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def root_id(admin_client):
|
||||
"""The root container's id; None in `simple` tenancy, which has no tree."""
|
||||
if not NODES:
|
||||
return None
|
||||
units = admin_client.get("/api/v1/tree/containers").json()
|
||||
return next(u["id"] for u in units if u["parent_id"] is None)
|
||||
|
||||
|
||||
def _create_record(client, headers, name: str, parent_id: str | None) -> dict:
|
||||
body = {"name": name, "note": "n"}
|
||||
if parent_id:
|
||||
body["parent_id"] = parent_id
|
||||
r = client.post("/api/v1/records", json=body, headers=headers)
|
||||
assert r.status_code == 201, r.text
|
||||
return r.json()
|
||||
|
||||
|
||||
# ── authentication ────────────────────────────────────────────────────────────
|
||||
def test_health_is_public(client):
|
||||
assert client.get("/api/v1/health").json()["status"] == "ok"
|
||||
|
||||
|
||||
def test_login_me_and_one_message_for_every_failure(admin_client, make_user):
|
||||
alice = make_user("alice")
|
||||
me = admin_client.get("/api/v1/auth/me", headers=bearer(alice["token"])).json()
|
||||
assert me["email"] == alice["email"]
|
||||
wrong = admin_client.post("/api/v1/auth/login", json={"email": alice["email"], "password": "nope"})
|
||||
missing = admin_client.post("/api/v1/auth/login",
|
||||
json={"email": f"ghost-{RUN}@example.com", "password": "nope"})
|
||||
assert wrong.status_code == missing.status_code == 401
|
||||
assert wrong.json()["detail"] == missing.json()["detail"] # no account-enumeration oracle
|
||||
|
||||
|
||||
def test_anonymous_requests_are_refused():
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.main import app
|
||||
|
||||
anon = TestClient(app)
|
||||
assert anon.get("/api/v1/auth/me").status_code == 401
|
||||
assert anon.get("/api/v1/records").status_code == 401
|
||||
|
||||
|
||||
def test_the_admin_boundary(admin_client, make_user):
|
||||
bob = make_user("bob")
|
||||
h = bearer(bob["token"])
|
||||
for method, path in [("GET", "/api/v1/admin/audit"), ("GET", "/api/v1/admin/settings"),
|
||||
("PUT", "/api/v1/admin/settings")]:
|
||||
r = admin_client.request(method, path, headers=h, json={"values": {"instance_name": "x"}})
|
||||
assert r.status_code == 403, (path, r.status_code)
|
||||
r = admin_client.post("/api/v1/users", headers=h, json={
|
||||
"email": f"sneaky-{RUN}@example.com", "full_name": "S", "password": USER_PASSWORD})
|
||||
assert r.status_code == 403
|
||||
|
||||
|
||||
def test_deactivation_ends_sessions_at_once(admin_client, make_user):
|
||||
carol = make_user("carol")
|
||||
assert admin_client.post(f"/api/v1/users/{carol['id']}/deactivate").status_code == 200
|
||||
assert admin_client.get("/api/v1/auth/me", headers=bearer(carol["token"])).status_code == 401
|
||||
|
||||
|
||||
# ── settings ──────────────────────────────────────────────────────────────────
|
||||
def test_settings_are_a_closed_typed_set(admin_client):
|
||||
assert admin_client.put("/api/v1/admin/settings",
|
||||
json={"values": {"shadow_key": "x"}}).status_code == 422
|
||||
assert admin_client.put("/api/v1/admin/settings",
|
||||
json={"values": {"instance_name": " "}}).status_code == 422
|
||||
name = f"Instance {RUN}"
|
||||
with settings_set(admin_client, instance_name=name):
|
||||
assert admin_client.get("/api/v1/config").json()["settings"]["instance_name"] == name
|
||||
rows = admin_client.get("/api/v1/admin/audit?action=setting.").json()
|
||||
assert any(e["diff"] and e["diff"].get("instance_name", [None, None])[1] == name for e in rows)
|
||||
assert admin_client.get("/api/v1/config").json()["settings"]["instance_name"] != name
|
||||
|
||||
|
||||
# ── the demo entity: access control and partial updates ───────────────────────
|
||||
def test_records_are_private_to_those_allowed(admin_client, make_user, root_id):
|
||||
owner, stranger = make_user("owner"), make_user("stranger")
|
||||
if NODES:
|
||||
# In the tree, a grant on the container is what lets someone write into it.
|
||||
r = admin_client.put(f"/api/v1/nodes/{root_id}/grants",
|
||||
json={"user_id": owner["id"], "role": "editor"})
|
||||
assert r.status_code == 200, r.text
|
||||
rec = _create_record(admin_client, bearer(owner["token"]), f"Private {RUN}", root_id)
|
||||
|
||||
h_other = bearer(stranger["token"])
|
||||
assert admin_client.get(f"/api/v1/records/{rec['id']}", headers=h_other).status_code == 404
|
||||
assert rec["id"] not in {x["id"] for x in admin_client.get("/api/v1/records", headers=h_other).json()}
|
||||
assert admin_client.patch(f"/api/v1/records/{rec['id']}", json={"note": "x"},
|
||||
headers=h_other).status_code == 404
|
||||
|
||||
# `None` means "not supplied": a status-only update keeps the note.
|
||||
r = admin_client.patch(f"/api/v1/records/{rec['id']}", json={"status": "done"},
|
||||
headers=bearer(owner["token"]))
|
||||
assert r.status_code == 200 and r.json()["note"] == "n" and r.json()["status"] == "done"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("method", "path", "body"), [
|
||||
("GET", "/api/v1/records/not-a-uuid", None),
|
||||
("PATCH", f"/api/v1/records/{uuid.uuid4()}", {"status": "archived-forever"}),
|
||||
("GET", "/api/v1/records?status=bogus", None),
|
||||
])
|
||||
def test_bad_input_is_422_never_500(admin_client, method, path, body):
|
||||
r = admin_client.request(method, path, json=body)
|
||||
assert r.status_code == 422, (path, r.status_code, r.text)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not NODES, reason="the org tree exists only in `nodes` tenancy")
|
||||
def test_bad_tree_input_is_422_never_500(admin_client, root_id):
|
||||
assert admin_client.post("/api/v1/nodes", json={
|
||||
"kind": "galaxy", "name": "X", "parent_id": root_id}).status_code == 422
|
||||
assert admin_client.put(f"/api/v1/nodes/{root_id}/grants", json={
|
||||
"user_id": str(uuid.uuid4()), "role": "emperor"}).status_code == 422
|
||||
|
||||
|
||||
# ── the HTTP edge ─────────────────────────────────────────────────────────────
|
||||
def test_cookie_writes_from_another_site_are_refused(client, monkeypatch):
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.config import get_settings
|
||||
from app.main import app
|
||||
|
||||
browser = TestClient(app) # its own cookie jar and no bearer header: a signed-in browser
|
||||
credentials = {"email": ADMIN_EMAIL, "password": ADMIN_PASSWORD}
|
||||
login = browser.post("/api/v1/auth/login", json=credentials)
|
||||
assert login.status_code == 200
|
||||
values = {"values": {"instance_name": f"Csrf {RUN}"}}
|
||||
assert browser.put("/api/v1/admin/settings", json=values,
|
||||
headers={"Sec-Fetch-Site": "same-site"}).status_code == 403
|
||||
assert browser.get("/api/v1/config", headers={"Sec-Fetch-Site": "cross-site"}).status_code == 200
|
||||
# Plain HTTP: no Sec-Fetch-Site, but the Origin of a sibling host still gives it away.
|
||||
assert browser.put("/api/v1/admin/settings", json=values,
|
||||
headers={"Origin": "http://sibling.example.com"}).status_code == 403
|
||||
# A blank Origin is malformed, not absent: it names no host, so it is refused too.
|
||||
assert browser.put("/api/v1/admin/settings", json=values, headers={"Origin": ""}).status_code == 403
|
||||
# App-wide, so the routes that run without a current user are covered too.
|
||||
assert browser.post("/api/v1/auth/login", json=credentials,
|
||||
headers={"Sec-Fetch-Site": "same-site"}).status_code == 403
|
||||
assert browser.post("/api/v1/auth/logout", headers={"Sec-Fetch-Site": "same-site"}).status_code == 403
|
||||
assert browser.get("/api/v1/auth/me").status_code == 200 # still signed in
|
||||
current = browser.get("/api/v1/config").json()["settings"]["instance_name"]
|
||||
assert current != f"Csrf {RUN}"
|
||||
# Same-origin passes, and so does a bearer token — it is not ambient. (Both rewrite the value
|
||||
# already there, so nothing is left changed.)
|
||||
unchanged = {"values": {"instance_name": current}}
|
||||
assert browser.put("/api/v1/admin/settings", json=unchanged,
|
||||
headers={"Sec-Fetch-Site": "same-origin"}).status_code == 200
|
||||
assert browser.put("/api/v1/admin/settings", json=unchanged, headers={
|
||||
"Sec-Fetch-Site": "cross-site", **bearer(login.json()["token"])}).status_code == 200
|
||||
# A separately served console listed in CORS_ALLOW_ORIGINS is a deliberate, trusted origin.
|
||||
monkeypatch.setattr(get_settings(), "cors_allow_origins", "http://console.example.test")
|
||||
r = browser.post("/api/v1/auth/login", json=credentials,
|
||||
headers={"Origin": "http://console.example.test", "Sec-Fetch-Site": "cross-site"})
|
||||
assert r.status_code == 200, r.text
|
||||
|
||||
|
||||
# ── the database backs the rules ──────────────────────────────────────────────
|
||||
def test_the_runtime_role_cannot_rewrite_the_audit_log(client):
|
||||
from app.db import engine
|
||||
|
||||
with engine.connect() as conn:
|
||||
with pytest.raises(ProgrammingError):
|
||||
conn.execute(text("UPDATE audit_log SET detail = 'rewritten'"))
|
||||
conn.rollback()
|
||||
|
||||
|
||||
def test_the_app_connects_as_the_role_the_grants_were_given_to(client):
|
||||
"""DB_APP_ROLE names the role the runtime-grants migration granted. If the app logs in as anyone
|
||||
else, the evidence protections above were applied to the wrong role."""
|
||||
from app.config import get_settings
|
||||
from app.db import engine
|
||||
|
||||
with engine.connect() as conn:
|
||||
assert conn.scalar(text("SELECT current_user")) == get_settings().db_app_role
|
||||
|
||||
|
||||
def test_evidence_tables_refuse_deletes_by_the_runtime_role(client):
|
||||
"""Every append-only and no-delete table, as named in app.models. `WHERE false`: the privilege is
|
||||
checked before any row is touched, so a broken grant still deletes nothing here."""
|
||||
from app.db import engine
|
||||
from app.models import APPEND_ONLY_TABLES, NO_DELETE_TABLES
|
||||
|
||||
for table in (*APPEND_ONLY_TABLES, *NO_DELETE_TABLES):
|
||||
with engine.connect() as conn:
|
||||
with pytest.raises(ProgrammingError, match="permission denied"):
|
||||
conn.execute(text(f'DELETE FROM "{table}" WHERE false'))
|
||||
conn.rollback()
|
||||
|
||||
|
||||
def test_append_only_tables_refuse_updates_by_the_runtime_role(client):
|
||||
"""UPDATE on every append-only table, as named in app.models, again `WHERE false`."""
|
||||
from app.db import engine
|
||||
from app.models import APPEND_ONLY_TABLES, Base
|
||||
|
||||
for table in APPEND_ONLY_TABLES:
|
||||
column = next(iter(Base.metadata.tables[table].columns)).name
|
||||
with engine.connect() as conn:
|
||||
with pytest.raises(ProgrammingError, match="permission denied"):
|
||||
conn.execute(text(f'UPDATE "{table}" SET "{column}" = "{column}" WHERE false'))
|
||||
conn.rollback()
|
||||
@@ -0,0 +1,60 @@
|
||||
"""The migration must stay in lockstep with the models.
|
||||
|
||||
Tables *and* enum types now both come from `Base.metadata`: the migration calls
|
||||
`create_enum_types(conn)` — which derives every native enum type from the metadata — and then
|
||||
`Base.metadata.create_all(conn)`. The old failure this file guarded (a hand-maintained `ENUMS` map
|
||||
drifting from the models) is therefore **gone by construction**, and there is no map left to check.
|
||||
|
||||
What can still break is a model that is never imported in `app/models/__init__.py`: it silently
|
||||
gets no table and no enum type, and the failure surfaces much later as a missing relation at
|
||||
runtime, usually on someone else's machine. That is what these tests guard.
|
||||
|
||||
Deliberately DB-free: they read the metadata as data, so they run everywhere.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dredd_core.schema import enum_types
|
||||
from sqlalchemy.dialects.postgresql import ENUM as PGEnum
|
||||
|
||||
|
||||
def _metadata():
|
||||
from app.models import Base
|
||||
|
||||
return Base.metadata
|
||||
|
||||
|
||||
def test_core_tables_are_registered():
|
||||
"""Importing `dredd_core` registers the shared identity tables on the one metadata."""
|
||||
assert {"app_user", "session", "app_setting", "audit_log"} <= set(_metadata().tables)
|
||||
|
||||
|
||||
def test_the_apps_own_tables_are_registered():
|
||||
"""A model missing from `app/models/__init__.py` silently gets no table."""
|
||||
assert "record" in _metadata().tables
|
||||
|
||||
|
||||
def test_every_model_enum_is_derived_for_the_migration():
|
||||
"""`create_enum_types()` emits exactly the types this derivation finds — so anything a column
|
||||
references must appear here, or the migration will not create it."""
|
||||
derived = enum_types(_metadata())
|
||||
for table in _metadata().tables.values():
|
||||
for column in table.columns:
|
||||
if isinstance(column.type, PGEnum) and column.type.name:
|
||||
assert column.type.name in derived, (
|
||||
f"enum {column.type.name} is used by a column but is not derived for the "
|
||||
"migration — is its model imported in app/models/__init__.py?"
|
||||
)
|
||||
|
||||
|
||||
def test_the_apps_own_enum_is_derived():
|
||||
assert "record_status" in enum_types(_metadata())
|
||||
|
||||
|
||||
def test_every_evidence_table_is_a_real_table():
|
||||
"""The runtime grants revoke only on tables that exist, so a misspelt evidence table would be
|
||||
skipped silently and stay fully writable for the runtime role."""
|
||||
from app.models import APPEND_ONLY_TABLES, NO_DELETE_TABLES
|
||||
|
||||
assert "audit_log" in APPEND_ONLY_TABLES
|
||||
missing = sorted((set(APPEND_ONLY_TABLES) | set(NO_DELETE_TABLES)) - set(_metadata().tables))
|
||||
assert not missing, f"evidence tables that are not tables: {missing}"
|
||||
@@ -0,0 +1,161 @@
|
||||
"""DB-free unit tests. These always run."""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from pydantic import ValidationError as PydanticValidationError
|
||||
|
||||
from app.config import Settings
|
||||
from app.enums import RecordStatus, SessionKind, TokenScope
|
||||
from app.schemas import LoginIn
|
||||
from app.security import (
|
||||
APP_TOKEN_PREFIX,
|
||||
generate_app_token,
|
||||
hash_password,
|
||||
hash_token,
|
||||
token_display_prefix,
|
||||
verify_password,
|
||||
)
|
||||
from app.services.changes import diff_of
|
||||
|
||||
|
||||
class TestPasswords:
|
||||
def test_roundtrip(self):
|
||||
h = hash_password("correct horse battery staple")
|
||||
assert verify_password("correct horse battery staple", h)
|
||||
assert not verify_password("wrong", h)
|
||||
|
||||
def test_hash_is_salted(self):
|
||||
# Two hashes of the same password must differ, or the store leaks which users share one.
|
||||
assert hash_password("same") != hash_password("same")
|
||||
|
||||
def test_malformed_hash_is_false_not_an_exception(self):
|
||||
assert verify_password("x", "not-a-hash") is False
|
||||
|
||||
|
||||
class TestTokens:
|
||||
def test_app_token_is_prefixed_and_long(self):
|
||||
t = generate_app_token()
|
||||
assert t.startswith(APP_TOKEN_PREFIX)
|
||||
assert len(t) > len(APP_TOKEN_PREFIX) + 30
|
||||
|
||||
def test_display_prefix_is_short_and_not_the_token(self):
|
||||
t = generate_app_token()
|
||||
p = token_display_prefix(t)
|
||||
assert t.startswith(p)
|
||||
assert len(p) == len(APP_TOKEN_PREFIX) + 6
|
||||
|
||||
def test_token_hash_is_stable_and_opaque(self):
|
||||
t = generate_app_token()
|
||||
assert hash_token(t) == hash_token(t)
|
||||
assert t not in hash_token(t)
|
||||
|
||||
|
||||
class TestEmailValidation:
|
||||
@pytest.mark.parametrize("good", ["a@b.co", "roman.chojnacki@example.com"])
|
||||
def test_accepts(self, good):
|
||||
assert LoginIn(email=good, password="x").email == good
|
||||
|
||||
@pytest.mark.parametrize("bad", ["", "no-at-sign", "a@b", "a b@c.com", "a@@b.com"])
|
||||
def test_rejects(self, bad):
|
||||
with pytest.raises(PydanticValidationError):
|
||||
LoginIn(email=bad, password="x")
|
||||
|
||||
|
||||
class TestAuditDiff:
|
||||
def test_only_changed_fields(self):
|
||||
assert diff_of({"a": 1, "b": 2}, {"a": 1, "b": 3}) == {"b": [2, 3]}
|
||||
|
||||
def test_added_and_removed(self):
|
||||
assert diff_of({"a": 1}, {"b": 2}) == {"a": [1, None], "b": [None, 2]}
|
||||
|
||||
def test_no_change_is_empty(self):
|
||||
assert diff_of({"a": 1}, {"a": 1}) == {}
|
||||
|
||||
|
||||
class TestSlugify:
|
||||
"""Node paths come from names; a name in Polish (or German, Danish…) cannot lose letters."""
|
||||
|
||||
@pytest.mark.parametrize(("name", "slug"), [
|
||||
("Dział procesowy", "dzial-procesowy"), ("Żółć gęślą jaźń", "zolc-gesla-jazn"),
|
||||
("Straße Øst", "strasse-ost"),
|
||||
])
|
||||
def test_letters_survive(self, name, slug):
|
||||
# services/nodes.py exists only in `nodes` tenancy.
|
||||
nodes = pytest.importorskip("app.services.nodes")
|
||||
assert nodes.slugify(name) == slug
|
||||
|
||||
|
||||
class TestEnums:
|
||||
def test_values_are_the_db_labels(self):
|
||||
assert RecordStatus.open.value == "open"
|
||||
assert SessionKind.app_token.value == "app_token"
|
||||
assert TokenScope.read.value == "read"
|
||||
|
||||
|
||||
PASSWORD = "s3cret-pw-9f1c"
|
||||
|
||||
|
||||
def _url(user: str, hostport: str, query: str = "") -> str:
|
||||
return f"postgresql+pg8000://{user}:{PASSWORD}@{hostport}/agora{query}"
|
||||
|
||||
|
||||
def _settings(**values) -> Settings:
|
||||
"""Settings from explicit values only: no .env, and every URL field given so a DATABASE_URL in
|
||||
the environment (the integration run's) cannot leak into a unit test."""
|
||||
values.setdefault("db_local_hosts", "")
|
||||
values.setdefault("database_url", _url("app", "localhost:5432"))
|
||||
values.setdefault("migration_database_url", _url("migrator", "localhost:5432"))
|
||||
return Settings(_env_file=None, **values)
|
||||
|
||||
|
||||
class TestDatabaseTlsRule:
|
||||
"""The family's one TLS rule (dredd_core.db.require_verified_tls), applied by config.py to both
|
||||
URLs: a database host that is not local must carry sslmode=verify-full, whatever the provider."""
|
||||
|
||||
@pytest.mark.parametrize("hostport", [
|
||||
"postgres:5432", # the compose service
|
||||
"localhost:5432",
|
||||
"LOCALHOST:5432",
|
||||
"127.0.0.1:5432",
|
||||
"[::1]:5432",
|
||||
"postgres", # no port
|
||||
])
|
||||
def test_local_hosts_need_no_tls(self, hostport):
|
||||
s = _settings(database_url=_url("app", hostport), migration_database_url=_url("migrator", hostport))
|
||||
assert s.db_local_hosts == ""
|
||||
|
||||
@pytest.mark.parametrize(("field", "url"), [
|
||||
("database_url", _url("x_app", "db.example-provider.com:5432")),
|
||||
("migration_database_url", _url("x_migrator", "db.example-provider.com:5432")),
|
||||
("database_url", _url("x_app", "db.example-provider.com:5432", "?sslmode=require")),
|
||||
("database_url", _url("x_app", "db.example-provider.com:5432",
|
||||
"?sslmode=verify-ca&sslrootcert=/run/certs/db-ca.crt")),
|
||||
("database_url", _url("x_app", "10.0.0.5:5432")), # private, still reached over a network
|
||||
("database_url", _url("x_app.tenant", "POOLER.DB.EXAMPLE-PROVIDER.COM.:5432")),
|
||||
])
|
||||
def test_remote_url_needs_verify_full(self, field, url):
|
||||
with pytest.raises(PydanticValidationError, match=f"{field.upper()}: database host .* is not local") as caught:
|
||||
_settings(**{field: url})
|
||||
message = str(caught.value)
|
||||
assert PASSWORD not in message # the refusal names the host, never the password
|
||||
assert "sslmode=verify-full" in message and "DB_LOCAL_HOSTS" in message
|
||||
|
||||
def test_verify_full_is_accepted_with_a_ca_file_or_the_system_store(self):
|
||||
remote = "pooler.db.example-provider.com:5432"
|
||||
_settings(database_url=_url("x_app.tenant", remote,
|
||||
"?sslmode=verify-full&sslrootcert=/run/certs/db-ca.crt"),
|
||||
migration_database_url="") # blank: the managed-db backend gets no migrator URL
|
||||
_settings(database_url=_url("x_app.tenant", remote, "?sslmode=verify-full"),
|
||||
migration_database_url=_url("x_migrator.tenant", remote, "?sslmode=verify-full"))
|
||||
|
||||
def test_db_local_hosts_is_the_only_exception(self):
|
||||
hostport = "db.internal.example:5432"
|
||||
with pytest.raises(PydanticValidationError, match="DATABASE_URL: database host 'db.internal.example'"):
|
||||
_settings(database_url=_url("app", hostport))
|
||||
# Comma-separated, blanks and case ignored, both URLs covered.
|
||||
s = _settings(db_local_hosts=" pg.lan , DB.Internal.Example",
|
||||
database_url=_url("app", hostport), migration_database_url=_url("migrator", hostport))
|
||||
assert s.db_local_hosts == " pg.lan , DB.Internal.Example"
|
||||
with pytest.raises(PydanticValidationError, match="MIGRATION_DATABASE_URL: database host"):
|
||||
_settings(db_local_hosts="pg.lan", database_url=_url("app", "pg.lan:5432"),
|
||||
migration_database_url=_url("migrator", hostport))
|
||||
@@ -0,0 +1,27 @@
|
||||
#!/bin/bash
|
||||
# Runs once on first Postgres start (as the superuser). Creates the least-privilege roles:
|
||||
# migrator — owns DDL (Alembic migrations)
|
||||
# app — runtime, DML only (+ append-only audit, enforced by the migration's grants)
|
||||
# Passwords come from the compose environment.
|
||||
set -e
|
||||
|
||||
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
|
||||
DO \$\$
|
||||
BEGIN
|
||||
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'migrator') THEN
|
||||
CREATE ROLE migrator LOGIN PASSWORD '${DB_MIGRATOR_PASSWORD}';
|
||||
END IF;
|
||||
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'app') THEN
|
||||
CREATE ROLE app LOGIN PASSWORD '${DB_APP_PASSWORD}';
|
||||
END IF;
|
||||
END
|
||||
\$\$;
|
||||
|
||||
GRANT CONNECT ON DATABASE ${POSTGRES_DB} TO migrator, app;
|
||||
-- migrator owns the schema (so create_all in the migration succeeds + objects are owned by it).
|
||||
ALTER SCHEMA public OWNER TO migrator;
|
||||
GRANT USAGE ON SCHEMA public TO app;
|
||||
-- Create pgcrypto here (as the superuser) so the migration's CREATE EXTENSION IF NOT EXISTS
|
||||
-- no-ops — the least-privilege migrator never needs extension-creation rights on the database.
|
||||
CREATE EXTENSION IF NOT EXISTS "pgcrypto";
|
||||
EOSQL
|
||||
@@ -0,0 +1,350 @@
|
||||
# Agora in the family's shared managed database
|
||||
|
||||
The Dredd family can run in **one managed PostgreSQL database** — one Postgres 16/17 database at a
|
||||
managed provider, one schema and two roles per app — with Atrium as the hub and every other app
|
||||
(Galena, Sygna, Counsel Scorecard, and now Agora) as its modules. The provider hosts only the
|
||||
database; Agora's backend still runs on your own server with Docker Compose. The same steps work
|
||||
against any PostgreSQL 16/17 whose admin may create roles and schemas.
|
||||
|
||||
Step 0 applies to the whole database, so do it once, whichever app you deploy first. The family runbook
|
||||
in the Atrium repository (`deploy/README.md`) covers it in more depth; the checklist below is the
|
||||
minimum and works on its own. Steps 1 to 5 cover only Agora's part.
|
||||
|
||||
## 0. The database itself (once, for every app)
|
||||
|
||||
- **Create the database** at the provider: Postgres 16 or 17, in a region close to your container hosts.
|
||||
Keep the platform admin's password (the provider's `postgres` role, usually not a superuser there) in
|
||||
your secret store. Agora uses it only for provisioning (step 1).
|
||||
- **Keep the schemas out of any auto-generated API.** Some providers expose tables through an
|
||||
auto-generated HTTP API that connects as `anon` / `authenticated` / `service_role` and exposes `public`
|
||||
by default. Switch such an API off, or never add an app schema to it. The backends connect to Postgres
|
||||
directly; `0002` and step 4's check also make sure those roles hold nothing in `agora`.
|
||||
- **Enforce TLS** on the server side if the provider offers a setting for it, so no client can connect in
|
||||
plaintext. Changing it may briefly restart the database.
|
||||
- **Download the provider's root CA** from its dashboard (skip this if the server's certificate chains to
|
||||
a public CA; `verify-full` then uses the system trust store and the URLs carry no `sslrootcert`). One
|
||||
file serves the whole database. Save it as `certs/db-ca.crt` next to `docker-compose.yml` on every
|
||||
container host, and compare its fingerprint and expiry on each host with what you recorded:
|
||||
`openssl x509 -in certs/db-ca.crt -noout -fingerprint -sha256 -enddate`.
|
||||
- **Restrict the network.** If the provider offers IP restrictions, allow only your container hosts'
|
||||
egress addresses, for direct and pooled connections alike.
|
||||
- **Size the connection budget** for every app (section 2 below has the arithmetic). The provider's own
|
||||
services may draw on the same total.
|
||||
- **Provider backups and point-in-time restores rewind the whole database, so they rewind every app
|
||||
together.** After any provider restore, reset every app's role passwords (step 1 with
|
||||
`--reset-passwords`, and each other app's equivalent), because a restore may drop custom role
|
||||
passwords, and run every app's check (step 4) before you start the backends.
|
||||
|
||||
## What Agora gets
|
||||
|
||||
| | Agora |
|
||||
|---|---|
|
||||
| Schema | `agora` (never `public`), owned by the migrator; `PUBLIC` holds nothing on it |
|
||||
| Migrator role | `agora_migrator`: owns every object; used only by `alembic upgrade head` in the one-shot `migrate` service. Its `statement_timeout` is `30min`, because a provider may cap statements at a couple of minutes, which is too short for a migration |
|
||||
| Runtime role | `agora_app`: DML only, no `UPDATE` / `DELETE` / `TRUNCATE` on `audit_log`; the backend's only login |
|
||||
| Extensions | none. `gen_random_uuid()` is core PostgreSQL, and `0001`'s `CREATE EXTENSION IF NOT EXISTS pgcrypto` is a no-op where the provider keeps a copy in `extensions` |
|
||||
| Shared identity | **only if this app joins a platform** (section 6): `USAGE` on a neutral schema the hub owns, plus a column-restricted read of the accounts in it. Never ownership, never `CREATE`, never an `INSERT` |
|
||||
|
||||
Role names are cluster-wide, so they carry the app's name: with a generic `app` / `migrator`, one app's
|
||||
migration could grant back what another app revoked, and one password would open every app. **Never
|
||||
create plain `app` or `migrator` roles in the shared database** — those names are for the local stack
|
||||
and CI only.
|
||||
|
||||
## 1. Provision Agora (once, as the platform admin)
|
||||
|
||||
dredd-core owns the provisioning routine; nothing here is hand-written SQL.
|
||||
|
||||
**From a shell (preferred)**, on any machine with the backend's requirements installed. Passwords come
|
||||
from environment variables, go to the server as SCRAM verifiers, and are never printed:
|
||||
|
||||
```bash
|
||||
python -c "import secrets; print(secrets.token_urlsafe(32))" # once per role: URL-safe, no encoding later
|
||||
read -rs AGORA_MIGRATOR_PASSWORD && export AGORA_MIGRATOR_PASSWORD
|
||||
read -rs AGORA_APP_PASSWORD && export AGORA_APP_PASSWORD
|
||||
read -rs ADMIN_DATABASE_URL && export ADMIN_DATABASE_URL
|
||||
# postgresql+pg8000://postgres.<tenant>:<admin-password>@<host>:5432/postgres?sslmode=verify-full&sslrootcert=./certs/db-ca.crt
|
||||
|
||||
python -m dredd_core.managed provision --admin-url ADMIN_DATABASE_URL \
|
||||
--schema agora --app-role agora_app --migrator-role agora_migrator \
|
||||
--migrator-password-env AGORA_MIGRATOR_PASSWORD --app-password-env AGORA_APP_PASSWORD
|
||||
```
|
||||
|
||||
In one transaction it creates both roles as plain `LOGIN` roles and schema `agora` owned by the
|
||||
migrator; gives `PUBLIC` nothing on the schema and the runtime role `USAGE`; grants both roles `USAGE`
|
||||
on `extensions` and sets `search_path = agora, extensions` (the migrator also gets
|
||||
`statement_timeout = 30min`); then revokes the admin's temporary membership in the migrator, which
|
||||
removes its standing `SET ROLE` path to the migrator, and verifies the result. That revoke is not a
|
||||
wall: the admin keeps `ADMIN OPTION` on the roles it created and can grant itself membership again, so
|
||||
anyone with the provider's SQL console can still rewrite `audit_log`. Treat that access as full trust and
|
||||
keep the database's members minimal. Exit 0 = done, 1 = refused or failed (rolled back, nothing
|
||||
changed), 2 = could not run. Re-running is safe: an existing role keeps its password unless you add
|
||||
`--reset-passwords`. Weak or placeholder passwords are refused (16 printable ASCII characters minimum).
|
||||
|
||||
**From the provider's SQL editor (no shell):** paste the whole of [`provision.sql`](provision.sql), replace
|
||||
the two `change_me` passwords in step 2 *there* (never in the committed file), and run it once as the
|
||||
platform admin. The editor's query history then holds the plaintext passwords, which the shell path
|
||||
avoids.
|
||||
|
||||
`provision.sql` is rendered by dredd-core — don't edit it. After a dredd-core upgrade, re-render it
|
||||
(CI's `managed-db` job runs the same command with `--check-file` and fails when the file is stale):
|
||||
|
||||
```bash
|
||||
python -m dredd_core.managed provision --sql-only --schema agora --app-role agora_app \
|
||||
--migrator-role agora_migrator --output db/managed/provision.sql
|
||||
```
|
||||
|
||||
The committed file is the **standalone** rendering, which is what a generated app needs on day one.
|
||||
Joining a platform adds two flags to that command, and therefore changes the file — which is exactly
|
||||
why CI compares it. See section 6.
|
||||
|
||||
**Joining Atrium (the platform) means re-rendering with the identity flags**, exactly as Galena,
|
||||
Sygna and Counsel ship theirs, and adding the same two flags to CI's `--check-file` step:
|
||||
|
||||
```bash
|
||||
python -m dredd_core.managed provision --sql-only --schema agora --app-role agora_app --migrator-role agora_migrator --identity-schema dredd --identity-owner atrium_migrator --output db/managed/provision.sql
|
||||
```
|
||||
|
||||
(plus every `--extension` this app's `0001` needs). The platform's `deploy/push.sh` checks it: before
|
||||
it provisions anything, it re-renders each module's `provision.sql` from that module's checkout with
|
||||
the canonical role names and the identity flags, and refuses the push when the committed file differs.
|
||||
A module still shipping the standalone rendering therefore cannot be deployed onto the platform.
|
||||
|
||||
## 2. Configure `.env`
|
||||
|
||||
Replace the Database settings with the commented "managed PostgreSQL" block in
|
||||
[`.env.example`](../../.env.example), and delete `POSTGRES_PASSWORD` / `DB_*_PASSWORD` (unused there):
|
||||
|
||||
```dotenv
|
||||
MANAGED_DB_CA_FILE=./certs/db-ca.crt
|
||||
DATABASE_URL=postgresql+pg8000://agora_app.<tenant>:<password>@<host>:5432/postgres?sslmode=verify-full&sslrootcert=/run/certs/db-ca.crt
|
||||
MIGRATION_DATABASE_URL=postgresql+pg8000://agora_migrator.<tenant>:<password>@<host>:5432/postgres?sslmode=verify-full&sslrootcert=/run/certs/db-ca.crt
|
||||
DB_APP_ROLE=agora_app
|
||||
# the connection budget below
|
||||
DB_POOL_SIZE=4
|
||||
DB_MAX_OVERFLOW=8
|
||||
```
|
||||
|
||||
- **Connection.** The host and port from the provider's connection details. Through a pooler, use its
|
||||
**session mode** (transaction mode breaks prepared statements; on the poolers the family knows that is
|
||||
port 5432 against 6543) — `deploy_check` refuses 6543. Some poolers require the tenant in the user
|
||||
name: then the user is `<role>.<tenant>`, and `DB_APP_ROLE` is the part before the dot. A direct
|
||||
connection may be IPv6-only, which Docker containers usually lack; the pooler is IPv4.
|
||||
- **TLS — the family's one rule.** A database host that is not local (`""`, `localhost`, `127.0.0.1`,
|
||||
`::1`, `postgres` — the compose service — or an entry of `DB_LOCAL_HOSTS`) must carry
|
||||
`sslmode=verify-full`, or the backend, migrate and the seed refuse to start when their settings load:
|
||||
pg8000 would otherwise skip verification and fall back to plaintext. With `sslrootcert` the server is
|
||||
verified against the provider's CA, which the override mounts at `/run/certs/db-ca.crt`; without it,
|
||||
against the system trust store. Every engine — the backend's, Alembic's, the seed's — is built by
|
||||
`dredd_core.db.make_engine`, which turns these parameters into a verifying TLS context;
|
||||
`sslmode=prefer` / `allow` / `disable` are refused before anything connects. `DB_LOCAL_HOSTS`
|
||||
(comma-separated) is for a private database on a trusted network that truly needs no TLS — the only
|
||||
exception, and one to write down.
|
||||
- **Passwords.** Percent-encode everything outside `A-Z a-z 0-9 - . _ ~` (`@` → `%40`, `%` → `%25`).
|
||||
Alembic reads the URL directly, never through its configparser, so an encoded `%` is fine.
|
||||
- **`DB_APP_ROLE`** is the role in `DATABASE_URL` (without a pooler's `.<tenant>`); the runtime-grants
|
||||
migration (`0002`) grants to it. `migrate` refuses to start when the two differ
|
||||
(`refusing to migrate: DB_APP_ROLE is …`), before anything is granted: a `DB_APP_ROLE` copied from a
|
||||
sibling's `.env` would otherwise hand that app's runtime role this schema. Naming a role that does not
|
||||
exist stops the migration with `runtime grants: role … does not exist`, and everything rolls back.
|
||||
- **Pool.** The backend holds up to `DB_POOL_SIZE + DB_MAX_OVERFLOW` connections. Migrate, the seed and
|
||||
the section 4 check use no pool, one connection each. `DB_POOL_SIZE` must be at least 1 and
|
||||
`DB_MAX_OVERFLOW` at least 0 (SQLAlchemy reads 0 / -1 as no limit, so the settings refuse them).
|
||||
- **The database's connection limit** (the server's `max_connections`, or the pooler's per-tenant
|
||||
pool) is shared by every app and by the provider's own services. Count `DB_POOL_SIZE +
|
||||
DB_MAX_OVERFLOW + 1` per app (the busy backend plus a seed, `migrate` or check beside it), and keep
|
||||
the apps' total at or below about 80% of the limit: 72 of 90, 48 of 60.
|
||||
- **Five apps do not fit a 90-connection limit at the defaults**: Atrium, Galena, Sygna, Counsel
|
||||
Scorecard and Agora at `5` / `10` take 5 × (15 + 1) = 80. Set `DB_POOL_SIZE=4` and
|
||||
`DB_MAX_OVERFLOW=8` in **every** app, 5 × (12 + 1) = 65, or size the instance for more.
|
||||
- With a **60-connection limit**, set `DB_POOL_SIZE=3` and `DB_MAX_OVERFLOW=2` in every app: 5 × (5 + 1)
|
||||
= 30.
|
||||
- Through a pooler in session mode, each client keeps its connection, so the pooler's own pool size
|
||||
(per user + database) must be at least `DB_POOL_SIZE + DB_MAX_OVERFLOW + 1`. With less, the extra
|
||||
client queues and then fails.
|
||||
- The family runbook's connection table counts four apps: add Agora's row there, and change the
|
||||
other apps' `.env` files to match.
|
||||
|
||||
Then run the pre-flight (`--env` checks another file): `python backend/scripts/deploy_check.py`. For an
|
||||
external `DATABASE_URL` it also checks both URLs — `sslmode=verify-full`, and `sslrootcert` at the
|
||||
mounted CA when given; the roles are exactly `agora_app` (`DATABASE_URL`) and
|
||||
`agora_migrator` (`MIGRATION_DATABASE_URL`), never `postgres` or another platform role, a sibling
|
||||
app's roles or a generic `app` / `migrator`; not port 6543; a percent-encoded password and no
|
||||
`<placeholder>`; different migrator and runtime roles; `DB_APP_ROLE` matching the runtime role; a bounded
|
||||
pool; and that the CA file exists when the URLs name one. Compose does not run it, so run it yourself.
|
||||
|
||||
## 3. Migrate, seed, run
|
||||
|
||||
```bash
|
||||
DREDD_CORE_TOKEN=github_pat_... \
|
||||
docker compose -f docker-compose.yml -f docker-compose.managed-db.yml up -d --build
|
||||
```
|
||||
|
||||
[`docker-compose.managed-db.yml`](../../docker-compose.managed-db.yml) switches the local `postgres` off,
|
||||
stops `migrate` waiting for it, and mounts the CA into `migrate` and `backend`.
|
||||
|
||||
- **`migrate`** runs `alembic upgrade head` as `agora_migrator`. Through the role's `search_path`,
|
||||
every table, enum type and `alembic_version` lands in `agora` with nothing schema-qualified in
|
||||
code; a sibling's same-named `audit_log`, `app_user` or `node_role` in its own schema does not make a
|
||||
table or type here get skipped. `0002` then grants `DB_APP_ROLE` its privileges, strips the API roles,
|
||||
and verifies the result. **The seed** then runs as `agora_app`.
|
||||
- **`backend`** gets a blank `MIGRATION_DATABASE_URL` (and blank local-postgres passwords), so the
|
||||
long-running process can only log in as `agora_app`. This skeleton never needs the migrator at
|
||||
runtime. If you add an in-app restore (as Galena and Sygna have), keeping the migrator's URL in the
|
||||
backend is an explicit opt-in; prefer a one-shot restore container
|
||||
(`docker compose -f … -f … run --rm -e MIGRATION_DATABASE_URL=… backend python -m <restore>`).
|
||||
- **Never migrate as the platform admin** (`postgres` at a provider; `postgres_managed` in the local
|
||||
emulation) or a superuser. `0002` refuses (`runtime grants: refusing to migrate as postgres …`) and the
|
||||
whole migration rolls back: anything created as the admin would be owned by it, and anything in
|
||||
`public` exposed to an auto-generated API.
|
||||
- **Nothing retries a failed migration**: some providers ban the client IP for a while after a few wrong
|
||||
passwords in a row. Fix `.env`, then run `docker compose -f … -f … run --rm migrate` once.
|
||||
|
||||
Pass **both** `-f` files on every compose command (`ps`, `logs`, `run`, `down`).
|
||||
|
||||
## 4. Verify
|
||||
|
||||
As the runtime role and as the migrator, inside the `migrate` container: it has both URLs from `.env`
|
||||
and the CA at the path they name, which a shell on the host has neither of.
|
||||
|
||||
```bash
|
||||
for url in DATABASE_URL MIGRATION_DATABASE_URL; do
|
||||
docker compose -f docker-compose.yml -f docker-compose.managed-db.yml run --rm --no-deps migrate \
|
||||
python -m dredd_core.managed check --url "$url" --expect-schema agora --require-tls \
|
||||
--app-role agora_app --migrator-role agora_migrator --append-only audit_log
|
||||
done
|
||||
```
|
||||
|
||||
It only reads, and fails (exit 1) unless: TLS is on from both ends; the connected role is neither a
|
||||
superuser nor the platform admin; the current schema is `agora` and `search_path` starts with it;
|
||||
the migrator owns the schema and no table belongs to a superuser or the platform admin;
|
||||
`agora_app` cannot modify `audit_log`; **isolation**
|
||||
— neither role holds `USAGE`, `CREATE`, ownership or an object privilege in any other app's schema;
|
||||
and `anon`, `authenticated` and `service_role` hold nothing in `agora`. Keep `--append-only` /
|
||||
`--no-delete` in step with `APPEND_ONLY_TABLES` / `NO_DELETE_TABLES` in `backend/app/models/__init__.py`.
|
||||
A provider whose platform keeps further schemas of its own in the database: name them with
|
||||
`--system-schema NAME ...` so the isolation check skips them.
|
||||
|
||||
**Through a pooler, `--require-tls` can fail a correct setup.** There, `pg_stat_ssl` describes the
|
||||
pooler's own connection to Postgres, which is encrypted only if the provider configures it that way. If
|
||||
the only failure is `TLS (server view)` while `TLS (client)` shows verify-full, your own link is
|
||||
verified: run the check again without `--require-tls`, where that row is a warning, and note it. Over
|
||||
the direct connection, keep `--require-tls`.
|
||||
|
||||
## 5. Restore
|
||||
|
||||
A point-in-time or backup restore at the provider rewinds **every app in the database together** —
|
||||
there is no per-app database restore (an app's own backup/export is the only per-app path). Follow the
|
||||
family runbook's restore procedure (stop every backend, restore, reset custom-role passwords, start).
|
||||
For Agora that means:
|
||||
|
||||
1. Reset both passwords — a provider's restore may drop custom role passwords — by re-running step 1
|
||||
with the passwords from your secret store and `--reset-passwords`. It changes nothing else.
|
||||
2. `docker compose -f docker-compose.yml -f docker-compose.managed-db.yml run --rm migrate` — a no-op
|
||||
when the restored schema is already at head; otherwise it brings it forward.
|
||||
3. Start the stack, then run step 4's `check` as both roles.
|
||||
|
||||
Not yet confirmed on a real managed database (the local verification used a TLS-only PostgreSQL
|
||||
emulation, `python -m dredd_core.managed emulate`): that a provider's `postgres` may grant the migrator to
|
||||
itself, create a schema for it and grant `USAGE` on `extensions` (provisioning stops with a clear error
|
||||
if the last does not take); that custom roles' `search_path` / `statement_timeout` survive the
|
||||
provider's own configuration; logins through a pooler and after a restore; certificate host-name checks
|
||||
against the direct and the pooler host; the pooler's default pool size; and whether the pooler's own
|
||||
connection to Postgres uses TLS (section 4's `--require-tls`).
|
||||
|
||||
## 6. Joining the platform (one account)
|
||||
|
||||
Everything above is true whether or not this app shares a roster. This section is the one change
|
||||
that makes it a **module** of a platform rather than an app that merely lives next door: `app_user`,
|
||||
`session` and `module_permission` move out of `agora` into a neutral schema the hub owns, and
|
||||
this app reads them. One person, one account, one password, one sign-in — and because the family
|
||||
runs at ONE origin, the cookie they got at the hub already arrives here. There is nothing to hand
|
||||
over and nothing to sign.
|
||||
|
||||
It also changes who may be here. `module_permission` holds one row per person per module, carrying a
|
||||
`role` of `user` or `moderator`, and **no row is no access**: an account the hub knows nothing about
|
||||
admitting to this app is refused at the door instead of shown an empty screen. Admitting somebody,
|
||||
and promoting them to moderator of this app, happens in the hub — this app holds `SELECT` on that
|
||||
table and nothing else, which is the whole reason it is safe for the modules to be separate
|
||||
deployments reading one table.
|
||||
|
||||
**Only the last of the four steps happens in this repository**, and that split is forced by
|
||||
privileges, not by taste. Read the whole section before starting; step 3 is the one nobody can
|
||||
automate.
|
||||
|
||||
### 6.1 Provision, as the platform admin
|
||||
|
||||
Two extra flags on step 1's command, and on the `--sql-only` re-render:
|
||||
|
||||
```bash
|
||||
python -m dredd_core.managed provision --admin-url ADMIN_DATABASE_URL \
|
||||
--schema agora --app-role agora_app --migrator-role agora_migrator \
|
||||
--identity-schema dredd --identity-owner atrium_migrator \
|
||||
--migrator-password-env AGORA_MIGRATOR_PASSWORD --app-password-env AGORA_APP_PASSWORD
|
||||
```
|
||||
|
||||
It grants this app's two roles `USAGE` on `dredd` — **only its own two**, so the
|
||||
grants accumulate one provisioning run per app and no script ever has to enumerate every role on the
|
||||
platform — and changes the `search_path` to `agora, dredd, extensions`. It does
|
||||
**not** create the schema: that happens on the owning app's own run, and a module provisioned before
|
||||
its owner is refused by name rather than left half-configured.
|
||||
|
||||
The app's own schema stays FIRST on that path, and it has to: `alembic_version`, the enum types and
|
||||
every new table land in the first schema, which must be one this app's migrator owns. The entire
|
||||
price of that correct choice is that an unqualified `app_user` resolves to a **local** copy if one
|
||||
exists — which is why the backend asserts at startup that it does not, and why that assertion is not
|
||||
optional. Never "fix" anything by putting the identity schema first.
|
||||
|
||||
Re-render `provision.sql` with the same two flags (section 1 has the command), add them to CI's
|
||||
`--check-file` step, and commit both — or CI fails, correctly, because the committed file would no
|
||||
longer describe this deployment, and the platform's `push.sh` refuses the module for the same reason.
|
||||
|
||||
### 6.2 The hub migrates
|
||||
|
||||
The schema's owner creates the three tables in it and grants this app's roles their tier. Nothing
|
||||
here can do that: only the owner may create a table in its schema or grant a privilege on it. Make
|
||||
sure the hub knows this app's two role names — it reads them from its own configuration — and that
|
||||
its migration runs **before** this one. Compose should say so
|
||||
(`depends_on: <hub>-migrate: {condition: service_completed_successfully}`); the migration below also
|
||||
refuses by name if it finds the tables missing, which is the loud version of the same thing.
|
||||
|
||||
What this app ends up holding, and nothing more:
|
||||
|
||||
| on | `agora_app` (runtime) | `agora_migrator` |
|
||||
|---|---|---|
|
||||
| `app_user` | `SELECT` on the ordinary columns only — **nothing at all** on `password_hash`, `failed_login_count`, `locked_until` | `SELECT`, `REFERENCES` (it re-points foreign keys) |
|
||||
| `session` | `SELECT`, and `UPDATE` on `last_seen_at` / `expires_at` / `revoked_at` | nothing |
|
||||
| `module_permission` | `SELECT` | nothing |
|
||||
| anything else there | nothing | nothing |
|
||||
|
||||
No `INSERT` anywhere, and that is the load-bearing line: a role that could insert a `session` row
|
||||
could mint a working credential for the administrator, one that could insert an `app_user` row could
|
||||
create or elevate anyone, and one that could write `module_permission` could admit anyone, promote
|
||||
anyone and promote itself. The console's 409s are politeness; this table is the enforcement.
|
||||
|
||||
### 6.3 Import the accounts this app has and the hub does not
|
||||
|
||||
Run a census first — one `SELECT id, email, is_admin, is_active` per schema's `app_user` — and
|
||||
compare by lower-cased e-mail. Anybody present here and absent there must be created in the hub
|
||||
**before** step 6.4, because neither side can do it: this app's migrator holds no `INSERT` on the
|
||||
shared `app_user`, and the hub's migrator holds nothing in `agora` to read from. It is a
|
||||
platform-admin step, run by eye, and on a freshly seeded pair of apps it is usually zero rows.
|
||||
|
||||
Anybody who administered *this* app and is not a platform administrator will come out an ordinary
|
||||
user. That is deliberate — a module must never be able to mint a platform administrator — so name
|
||||
them a **moderator** of this module in the hub afterwards. The migration warns about each such
|
||||
person by name as it runs.
|
||||
|
||||
### 6.4 Migrate this app
|
||||
|
||||
Set `IDENTITY_SCHEMA=dredd` (and, if the platform has settled on one cookie name,
|
||||
`SESSION_COOKIE_NAME`; the old name keeps being accepted, so nobody is signed out by the rename),
|
||||
then `alembic upgrade head`. That runs `0003_shared_identity`, in one transaction: match every local
|
||||
account to a shared one by e-mail, rewrite every id in this schema that names a person, re-point
|
||||
every foreign key at the shared table, prove no row was missed, and drop the local copies. It
|
||||
refuses rather than guessing if an account is unmatched, and it **cannot be downgraded** — restore
|
||||
the dump you took first.
|
||||
|
||||
Then run section 4's `check` again with `--identity-schema dredd`: it stops treating
|
||||
that schema as a leak and starts asserting the table above, column by column, with a closed
|
||||
allowlist. A passing report prints exactly what these two roles may touch there, which is the
|
||||
sentence to keep in the change record.
|
||||
@@ -0,0 +1,324 @@
|
||||
-- =================================================================================================
|
||||
-- Managed Postgres provisioning for one app of the family, in the shared database:
|
||||
-- schema agora, migrator agora_migrator, app agora_app, extensions: none, migrator statement_timeout 30min
|
||||
-- search_path agora, extensions; no shared identity schema (this app owns its own accounts)
|
||||
--
|
||||
-- Rendered by dredd-core. Do not edit: re-render, and let CI check it is current (exit 1 = stale):
|
||||
-- python -m dredd_core.managed provision --sql-only \
|
||||
-- --schema agora --app-role agora_app --migrator-role agora_migrator \
|
||||
-- --output db/managed/provision.sql (CI: --check-file db/managed/provision.sql)
|
||||
--
|
||||
-- Preferred path, from a shell (passwords come from environment variables and are never printed):
|
||||
-- python -m dredd_core.managed provision --admin-url ADMIN_DATABASE_URL \
|
||||
-- --schema agora --app-role agora_app --migrator-role agora_migrator \
|
||||
-- --migrator-password-env AGORA_MIGRATOR_PASSWORD --app-password-env AGORA_APP_PASSWORD
|
||||
--
|
||||
-- SQL editor path (no shell): paste this whole file into the provider's SQL editor, replace both
|
||||
-- change_me passwords in step 2 there (never in the committed file; at least 16 printable ASCII
|
||||
-- characters, different per role), and run it once as the platform admin (postgres). Re-running is
|
||||
-- safe: an existing role keeps its password unless reset_passwords is set to true (do that after a
|
||||
-- restore, which may drop custom role passwords). It never touches schema public and never drops
|
||||
-- anything.
|
||||
-- =================================================================================================
|
||||
BEGIN;
|
||||
|
||||
-- 1. preflight: refuse a connection, schema, role or extension this must not touch
|
||||
DO $dredd_provision_preflight$
|
||||
DECLARE
|
||||
target_schema text := 'agora';
|
||||
migrator_role text := 'agora_migrator';
|
||||
app_role text := 'agora_app';
|
||||
admin_roles text[] := ARRAY['postgres', 'postgres_managed']::text[];
|
||||
extension_names text[] := '{}'::text[];
|
||||
identity_schema text := '';
|
||||
identity_owner text := '';
|
||||
owns_identity boolean := false;
|
||||
seen text;
|
||||
r text;
|
||||
e text;
|
||||
BEGIN
|
||||
IF current_user::text IN (migrator_role, app_role) THEN
|
||||
RAISE EXCEPTION USING
|
||||
MESSAGE = 'provision: connected as ' || quote_ident(current_user::text)
|
||||
|| ', one of the roles being provisioned',
|
||||
HINT = 'Run it as the platform admin: postgres on a managed provider (postgres_managed in the local emulation).';
|
||||
END IF;
|
||||
IF (SELECT rolsuper FROM pg_roles WHERE rolname = current_user) THEN
|
||||
RAISE WARNING USING
|
||||
MESSAGE = 'provision: connected as the superuser ' || quote_ident(current_user::text),
|
||||
HINT = 'Fine on a local cluster or in CI; on a managed provider run it as postgres, which is not a superuser there.';
|
||||
ELSIF NOT (current_user::text = ANY (admin_roles)) THEN
|
||||
RAISE EXCEPTION USING
|
||||
MESSAGE = 'provision: connected as ' || quote_ident(current_user::text)
|
||||
|| ', which is neither the platform admin (' || array_to_string(admin_roles, ', ')
|
||||
|| ') nor a superuser',
|
||||
HINT = 'Run it as postgres on a managed provider (postgres_managed in the local emulation).';
|
||||
ELSIF NOT (SELECT rolcreaterole FROM pg_roles WHERE rolname = current_user)
|
||||
AND EXISTS (SELECT 1 FROM unnest(ARRAY[migrator_role, app_role]) AS n
|
||||
WHERE NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = n)) THEN
|
||||
RAISE EXCEPTION USING
|
||||
MESSAGE = 'provision: ' || quote_ident(current_user::text) || ' has no CREATEROLE, and a role is missing',
|
||||
HINT = 'Run it as the platform admin, which can create roles.';
|
||||
END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = 'extensions') THEN
|
||||
RAISE EXCEPTION USING
|
||||
MESSAGE = 'provision: schema extensions does not exist',
|
||||
HINT = 'A managed provider has it. On a plain PostgreSQL test cluster run '
|
||||
|| 'python -m dredd_core.managed emulate (TEST-ONLY) first.';
|
||||
END IF;
|
||||
SELECT pg_get_userbyid(nspowner)::text INTO seen FROM pg_namespace WHERE nspname = target_schema;
|
||||
IF seen IS NOT NULL AND seen <> migrator_role THEN
|
||||
RAISE EXCEPTION USING
|
||||
MESSAGE = 'provision: schema ' || quote_ident(target_schema) || ' already exists and is owned by '
|
||||
|| quote_ident(seen) || ', not ' || quote_ident(migrator_role),
|
||||
HINT = 'Another app, or an earlier setup, uses that schema; provisioning never takes a schema over. '
|
||||
|| 'Check the schema and role names.';
|
||||
END IF;
|
||||
IF identity_schema <> '' THEN
|
||||
SELECT pg_get_userbyid(nspowner)::text INTO seen FROM pg_namespace WHERE nspname = identity_schema;
|
||||
IF seen IS NOT NULL AND seen <> identity_owner THEN
|
||||
RAISE EXCEPTION USING
|
||||
MESSAGE = 'provision: the shared identity schema ' || quote_ident(identity_schema)
|
||||
|| ' already exists and is owned by ' || quote_ident(seen) || ', not '
|
||||
|| quote_ident(identity_owner),
|
||||
HINT = 'Another deployment, or an earlier setup, uses that name; provisioning never takes a '
|
||||
|| 'schema over. Check --identity-schema and --identity-owner.';
|
||||
END IF;
|
||||
IF seen IS NULL AND NOT owns_identity THEN
|
||||
RAISE EXCEPTION USING
|
||||
MESSAGE = 'provision: the shared identity schema ' || quote_ident(identity_schema)
|
||||
|| ' does not exist, and this app does not own it',
|
||||
HINT = 'Provision the app whose migrator is ' || quote_ident(identity_owner) || ' first: its '
|
||||
|| 'run creates the schema, and this one only asks for USAGE on it. (Ordering the other '
|
||||
|| 'way round is what a compose depends_on is for.)';
|
||||
END IF;
|
||||
END IF;
|
||||
FOREACH r IN ARRAY ARRAY[migrator_role, app_role] LOOP
|
||||
IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = r
|
||||
AND (rolsuper OR rolcreaterole OR rolcreatedb OR rolreplication OR rolbypassrls
|
||||
OR NOT rolcanlogin)) THEN
|
||||
RAISE EXCEPTION USING
|
||||
MESSAGE = 'provision: role ' || quote_ident(r) || ' already exists and is not a plain LOGIN role',
|
||||
HINT = 'An app role is LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS: '
|
||||
|| 'fix it with ALTER ROLE, or check the role names.';
|
||||
END IF;
|
||||
END LOOP;
|
||||
FOREACH e IN ARRAY extension_names LOOP
|
||||
SELECT n.nspname::text INTO seen
|
||||
FROM pg_extension x JOIN pg_namespace n ON n.oid = x.extnamespace WHERE x.extname = e;
|
||||
IF seen IS NOT NULL AND seen <> 'extensions' THEN
|
||||
RAISE EXCEPTION USING
|
||||
MESSAGE = 'provision: extension ' || quote_ident(e) || ' is installed in schema ' || quote_ident(seen)
|
||||
|| ', not extensions',
|
||||
HINT = 'The app roles'' search_path is their schema and extensions, so its functions and operator '
|
||||
|| 'classes would not resolve. Move it (ALTER EXTENSION ... SET SCHEMA extensions) once '
|
||||
|| 'nothing depends on where it is.';
|
||||
END IF;
|
||||
END LOOP;
|
||||
END
|
||||
$dredd_provision_preflight$;
|
||||
|
||||
-- 2. roles: create agora_migrator and agora_app (plain LOGIN roles) where missing
|
||||
DO $dredd_provision_roles$
|
||||
DECLARE
|
||||
migrator_role text := 'agora_migrator';
|
||||
app_role text := 'agora_app';
|
||||
migrator_password text := 'change_me'; -- replace change_me here (in the SQL editor, never in the committed file)
|
||||
app_password text := 'change_me'; -- replace change_me here (in the SQL editor, never in the committed file)
|
||||
reset_passwords boolean := false; -- true: also set the password of a role that already exists
|
||||
placeholders text[] := ARRAY['change_me', 'changeme', 'change-me', 'replace_me', 'replaceme', 'placeholder', 'password', 'your_password', 'yourpassword']::text[];
|
||||
names text[];
|
||||
passwords text[];
|
||||
pw text;
|
||||
i int;
|
||||
BEGIN
|
||||
names := ARRAY[migrator_role, app_role];
|
||||
passwords := ARRAY[migrator_password, app_password];
|
||||
FOR i IN 1..2 LOOP
|
||||
CONTINUE WHEN EXISTS (SELECT 1 FROM pg_roles WHERE rolname = names[i]) AND NOT reset_passwords;
|
||||
pw := passwords[i];
|
||||
IF pw IS NULL
|
||||
OR (NOT starts_with(pw, 'SCRAM-SHA-256$')
|
||||
AND (pw !~ '^[!-~]([ -~]*[!-~])?$'
|
||||
OR length(pw) < 16
|
||||
OR (SELECT count(DISTINCT c) FROM regexp_split_to_table(pw, '') AS c) < 6
|
||||
OR EXISTS (SELECT 1 FROM unnest(placeholders) AS w WHERE strpos(lower(pw), w) > 0)
|
||||
OR lower(pw) IN (migrator_role, app_role))) THEN
|
||||
RAISE EXCEPTION USING
|
||||
MESSAGE = 'provision: the password for ' || quote_ident(names[i]) || ' is empty or a placeholder',
|
||||
HINT = 'Use at least 16 printable ASCII characters, not change_me, and a different one per role.';
|
||||
END IF;
|
||||
IF passwords[3 - i] IS NOT NULL AND pw = passwords[3 - i] THEN
|
||||
RAISE EXCEPTION USING
|
||||
MESSAGE = 'provision: the passwords for ' || quote_ident(migrator_role) || ' and '
|
||||
|| quote_ident(app_role) || ' are identical',
|
||||
HINT = 'Each role needs its own password.';
|
||||
END IF;
|
||||
END LOOP;
|
||||
FOR i IN 1..2 LOOP
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = names[i]) THEN
|
||||
EXECUTE 'CREATE ROLE ' || quote_ident(names[i])
|
||||
|| ' LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS INHERIT PASSWORD '
|
||||
|| quote_literal(passwords[i]);
|
||||
ELSIF reset_passwords THEN
|
||||
EXECUTE 'ALTER ROLE ' || quote_ident(names[i]) || ' PASSWORD ' || quote_literal(passwords[i]);
|
||||
END IF;
|
||||
END LOOP;
|
||||
END
|
||||
$dredd_provision_roles$;
|
||||
|
||||
-- 3. temporary membership: PostgreSQL 16+ needs SET on agora_migrator to hand it a schema
|
||||
GRANT agora_migrator TO CURRENT_USER;
|
||||
|
||||
-- 4. schema agora, owned by agora_migrator
|
||||
CREATE SCHEMA IF NOT EXISTS agora AUTHORIZATION agora_migrator;
|
||||
|
||||
-- 5. schema agora: nothing for PUBLIC
|
||||
REVOKE ALL ON SCHEMA agora FROM PUBLIC;
|
||||
|
||||
-- 6. schema agora: USAGE for agora_app
|
||||
GRANT USAGE ON SCHEMA agora TO agora_app;
|
||||
|
||||
-- 7. schema extensions: USAGE for agora_migrator and agora_app
|
||||
GRANT USAGE ON SCHEMA extensions TO agora_migrator, agora_app;
|
||||
|
||||
-- 8. schema extensions: check that the USAGE grant took
|
||||
DO $dredd_provision_extensions_usage$
|
||||
DECLARE
|
||||
migrator_role text := 'agora_migrator';
|
||||
app_role text := 'agora_app';
|
||||
BEGIN
|
||||
IF NOT (has_schema_privilege(migrator_role, 'extensions', 'USAGE')
|
||||
AND has_schema_privilege(app_role, 'extensions', 'USAGE')) THEN
|
||||
RAISE EXCEPTION USING
|
||||
MESSAGE = 'provision: could not grant USAGE on schema extensions to ' || quote_ident(migrator_role)
|
||||
|| ' and ' || quote_ident(app_role),
|
||||
HINT = 'The connected role holds no grant option on schema extensions (PostgreSQL then only warns '
|
||||
|| '"no privileges were granted"). The apps need it for pg_trgm operator classes and extension '
|
||||
|| 'functions: have the platform owner GRANT USAGE ON SCHEMA extensions TO both roles.';
|
||||
END IF;
|
||||
END
|
||||
$dredd_provision_extensions_usage$;
|
||||
|
||||
-- 9. search_path of agora_migrator
|
||||
ALTER ROLE agora_migrator SET search_path = agora, extensions;
|
||||
|
||||
-- 10. search_path of agora_app
|
||||
ALTER ROLE agora_app SET search_path = agora, extensions;
|
||||
|
||||
-- 11. statement_timeout of agora_migrator
|
||||
ALTER ROLE agora_migrator SET statement_timeout = '30min';
|
||||
|
||||
-- 12. end the temporary membership: no standing SET ROLE agora_migrator for the admin
|
||||
REVOKE agora_migrator FROM CURRENT_USER;
|
||||
|
||||
-- 13. verify the end state
|
||||
DO $dredd_provision_verify$
|
||||
DECLARE
|
||||
target_schema text := 'agora';
|
||||
migrator_role text := 'agora_migrator';
|
||||
app_role text := 'agora_app';
|
||||
extension_names text[] := '{}'::text[];
|
||||
timeout_setting text := 'statement_timeout=30min';
|
||||
path_setting text := 'search_path=agora, extensions';
|
||||
identity_schema text := '';
|
||||
identity_owner text := '';
|
||||
admin_roles text[] := ARRAY['postgres', 'postgres_managed']::text[];
|
||||
admin_is_super boolean := (SELECT rolsuper FROM pg_roles WHERE rolname = current_user);
|
||||
problems text[] := '{}'::text[];
|
||||
held boolean;
|
||||
seen text;
|
||||
r text;
|
||||
e text;
|
||||
BEGIN
|
||||
FOREACH r IN ARRAY ARRAY[migrator_role, app_role] LOOP
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = r AND rolcanlogin
|
||||
AND NOT (rolsuper OR rolcreaterole OR rolcreatedb OR rolreplication OR rolbypassrls)) THEN
|
||||
problems := problems || ('role ' || quote_ident(r) || ' is missing or not a plain LOGIN role');
|
||||
CONTINUE;
|
||||
END IF;
|
||||
IF NOT has_schema_privilege(r, 'extensions', 'USAGE') THEN
|
||||
problems := problems || (quote_ident(r) || ' has no USAGE on schema extensions');
|
||||
END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_db_role_setting s
|
||||
WHERE s.setrole = (SELECT oid FROM pg_roles WHERE rolname = r) AND s.setdatabase = 0
|
||||
AND path_setting = ANY (s.setconfig)) THEN
|
||||
problems := problems || (quote_ident(r) || ' does not have ' || path_setting);
|
||||
END IF;
|
||||
IF NOT admin_is_super THEN
|
||||
IF current_setting('server_version_num')::int >= 160000 THEN
|
||||
held := pg_has_role(r::name, 'SET') OR pg_has_role(r::name, 'USAGE');
|
||||
ELSE
|
||||
held := pg_has_role(r::name, 'MEMBER');
|
||||
END IF;
|
||||
IF held THEN
|
||||
problems := problems || (quote_ident(current_user::text) || ' can still SET ROLE or use the privileges of '
|
||||
|| quote_ident(r) || ' (a membership granted by another role?)');
|
||||
END IF;
|
||||
END IF;
|
||||
END LOOP;
|
||||
IF (SELECT pg_get_userbyid(nspowner)::text FROM pg_namespace WHERE nspname = target_schema)
|
||||
IS DISTINCT FROM migrator_role THEN
|
||||
problems := problems || ('schema ' || quote_ident(target_schema) || ' is missing or not owned by '
|
||||
|| quote_ident(migrator_role));
|
||||
ELSE
|
||||
IF has_schema_privilege('public', target_schema, 'USAGE') OR has_schema_privilege('public', target_schema, 'CREATE') THEN
|
||||
problems := problems || ('PUBLIC still holds a privilege on schema ' || quote_ident(target_schema));
|
||||
END IF;
|
||||
IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = app_role) THEN
|
||||
IF NOT has_schema_privilege(app_role, target_schema, 'USAGE') THEN
|
||||
problems := problems || (quote_ident(app_role) || ' has no USAGE on schema ' || quote_ident(target_schema));
|
||||
END IF;
|
||||
IF has_schema_privilege(app_role, target_schema, 'CREATE') THEN
|
||||
problems := problems || (quote_ident(app_role) || ' can CREATE in schema ' || quote_ident(target_schema));
|
||||
END IF;
|
||||
END IF;
|
||||
END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_db_role_setting s
|
||||
WHERE s.setrole = (SELECT oid FROM pg_roles WHERE rolname = migrator_role) AND s.setdatabase = 0
|
||||
AND timeout_setting = ANY (s.setconfig)) THEN
|
||||
problems := problems || (quote_ident(migrator_role) || ' does not have ' || timeout_setting);
|
||||
END IF;
|
||||
IF identity_schema <> '' THEN
|
||||
SELECT pg_get_userbyid(nspowner)::text INTO seen FROM pg_namespace WHERE nspname = identity_schema;
|
||||
IF seen IS DISTINCT FROM identity_owner THEN
|
||||
problems := problems || ('the shared identity schema ' || quote_ident(identity_schema)
|
||||
|| ' is missing or not owned by ' || quote_ident(identity_owner));
|
||||
ELSE
|
||||
IF (SELECT rolsuper FROM pg_roles WHERE rolname = identity_owner)
|
||||
OR identity_owner = ANY (admin_roles) THEN
|
||||
problems := problems || ('the identity owner ' || quote_ident(identity_owner)
|
||||
|| ' is a superuser or the platform admin role');
|
||||
END IF;
|
||||
IF has_schema_privilege('public', identity_schema, 'USAGE')
|
||||
OR has_schema_privilege('public', identity_schema, 'CREATE') THEN
|
||||
problems := problems || ('PUBLIC still holds a privilege on schema ' || quote_ident(identity_schema));
|
||||
END IF;
|
||||
FOREACH r IN ARRAY ARRAY[migrator_role, app_role] LOOP
|
||||
CONTINUE WHEN NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = r);
|
||||
IF NOT has_schema_privilege(r, identity_schema, 'USAGE') THEN
|
||||
problems := problems || (quote_ident(r) || ' has no USAGE on schema ' || quote_ident(identity_schema));
|
||||
END IF;
|
||||
-- Only the owner creates in the shared schema: its tables are the owning app's migration,
|
||||
-- and a second app creating one there is how two apps end up with two account tables.
|
||||
IF r <> identity_owner AND has_schema_privilege(r, identity_schema, 'CREATE') THEN
|
||||
problems := problems || (quote_ident(r) || ' can CREATE in schema ' || quote_ident(identity_schema));
|
||||
END IF;
|
||||
END LOOP;
|
||||
END IF;
|
||||
END IF;
|
||||
FOREACH e IN ARRAY extension_names LOOP
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_extension x JOIN pg_namespace n ON n.oid = x.extnamespace
|
||||
WHERE x.extname = e AND n.nspname = 'extensions') THEN
|
||||
problems := problems || ('extension ' || quote_ident(e) || ' is not installed in schema extensions');
|
||||
END IF;
|
||||
END LOOP;
|
||||
IF cardinality(problems) > 0 THEN
|
||||
RAISE EXCEPTION USING
|
||||
MESSAGE = 'provision: the end state does not hold: ' || array_to_string(problems, '; '),
|
||||
HINT = 'Nothing was committed. Fix the cause and run the provisioning again.';
|
||||
END IF;
|
||||
END
|
||||
$dredd_provision_verify$;
|
||||
|
||||
COMMIT;
|
||||
@@ -0,0 +1,70 @@
|
||||
# Agora on a managed PostgreSQL database (the family's shared one, or any Postgres 16/17 reached
|
||||
# over a network): an override for docker-compose.yml.
|
||||
#
|
||||
# DREDD_CORE_TOKEN=github_pat_... \
|
||||
# docker compose -f docker-compose.yml -f docker-compose.managed-db.yml up -d --build
|
||||
#
|
||||
# The database lives elsewhere — the family shares ONE managed database, and Agora has schema
|
||||
# `agora` in it — so the local postgres service is switched off and nothing waits for it;
|
||||
# migrate (+seed) and backend are otherwise unchanged. Provision Agora first
|
||||
# (db/managed/README.md), and give .env the database's URLs — the provider's host and port (through a
|
||||
# pooler, its session mode, never transaction mode), user names agora_migrator /
|
||||
# agora_app (with the `.<tenant>` suffix where the pooler wants one),
|
||||
# ?sslmode=verify-full&sslrootcert=/run/certs/db-ca.crt — plus DB_APP_ROLE=agora_app.
|
||||
# `python backend/scripts/deploy_check.py` checks the .env side before you start.
|
||||
#
|
||||
# Uses the !reset merge tag (docs.docker.com/reference/compose-file/merge/, "Reset value"), so it needs a
|
||||
# Compose v2 release that supports it; `docker compose -f ... -f ... config` shows the merged result.
|
||||
# Pass -f with BOTH files on every command (ps, logs, run, down), or Compose falls back to the
|
||||
# local-postgres stack.
|
||||
#
|
||||
# Migrations are not retried on failure: some providers ban a client IP for a while after a few failed
|
||||
# password logins in a row, and a retry loop around a wrong password would trigger exactly that.
|
||||
services:
|
||||
postgres:
|
||||
# Off: a profile nobody activates keeps the service defined but never starts it.
|
||||
profiles: ["local-postgres"]
|
||||
# No data volume and no db/init mount — the schema and roles come from dredd-core's provisioning.
|
||||
volumes: !reset []
|
||||
|
||||
migrate:
|
||||
# docker-compose.yml makes migrate wait for the local postgres healthcheck; there is none here.
|
||||
# (backend depends only on migrate, so it stays as it is.)
|
||||
depends_on: !reset null
|
||||
environment:
|
||||
# The one-shot migrate service keeps the whole .env: alembic runs as MIGRATION_DATABASE_URL's
|
||||
# agora_migrator, the seed as DATABASE_URL's agora_app. 0002_runtime_grants grants
|
||||
# the role DB_APP_ROLE names, so an unset DB_APP_ROLE stops here rather than inside the migration.
|
||||
DB_APP_ROLE: ${DB_APP_ROLE:?set DB_APP_ROLE in .env to the runtime role, agora_app in the shared database}
|
||||
volumes: &managed_db_ca
|
||||
# The provider's root CA (downloaded from its dashboard; when the server's certificate chains to
|
||||
# a public CA, drop this mount and the URLs' sslrootcert — verify-full then uses the system trust
|
||||
# store), read-only, at the path the URLs' sslrootcert names. One file serves the whole shared
|
||||
# database. create_host_path: false makes a missing file an error at start-up instead of an
|
||||
# empty directory in its place.
|
||||
- type: bind
|
||||
source: ${MANAGED_DB_CA_FILE:-./certs/db-ca.crt}
|
||||
target: /run/certs/db-ca.crt
|
||||
read_only: true
|
||||
bind:
|
||||
create_host_path: false
|
||||
|
||||
backend:
|
||||
environment:
|
||||
# Least privilege: the long-running backend connects ONLY as agora_app (DATABASE_URL).
|
||||
# Blank the migrator's URL and the local-postgres passwords that `env_file: .env` would otherwise
|
||||
# inject (`environment:` wins over `env_file:`), so a compromised backend cannot log in as
|
||||
# agora_migrator and rewrite audit_log. This skeleton never needs the migrator at runtime.
|
||||
# An app that adds an in-app restore (Galena and Sygna have one) needs it there: keeping it is a
|
||||
# documented opt-in, and a one-shot restore container (`docker compose run --rm` with the
|
||||
# migrator's URL) is the recommended path.
|
||||
MIGRATION_DATABASE_URL: ""
|
||||
DB_MIGRATOR_PASSWORD: ""
|
||||
DB_APP_PASSWORD: ""
|
||||
POSTGRES_PASSWORD: ""
|
||||
# Passed through explicitly so the running configuration is visible here. The pool bounds the
|
||||
# connections this backend takes from the shared database's limit (db/managed/README.md).
|
||||
DB_APP_ROLE: ${DB_APP_ROLE:?set DB_APP_ROLE in .env to the runtime role, agora_app in the shared database}
|
||||
DB_POOL_SIZE: ${DB_POOL_SIZE:-5}
|
||||
DB_MAX_OVERFLOW: ${DB_MAX_OVERFLOW:-10}
|
||||
volumes: *managed_db_ca
|
||||
@@ -0,0 +1,64 @@
|
||||
# Agora stack: postgres → migrate (+seed) → backend. No reverse proxy: the backend is its own
|
||||
# edge (app/edge.py) and serves the console. Only the backend is published; postgres is expose-only.
|
||||
#
|
||||
# Runs alongside a sibling's stack — different volumes, different DB name. Each app in the family
|
||||
# keeps its OWN database; what they share is the `dredd-core` package, not a cluster.
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16
|
||||
environment:
|
||||
POSTGRES_DB: ${POSTGRES_DB:-agora}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-change_me_super}
|
||||
DB_APP_PASSWORD: ${DB_APP_PASSWORD:-change_me_app}
|
||||
DB_MIGRATOR_PASSWORD: ${DB_MIGRATOR_PASSWORD:-change_me_migrator}
|
||||
volumes:
|
||||
- pgdata:/var/lib/postgresql/data
|
||||
- ./db/init:/docker-entrypoint-initdb.d:ro
|
||||
expose: ["5432"]
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U postgres -d ${POSTGRES_DB:-agora}"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 20
|
||||
|
||||
migrate:
|
||||
build:
|
||||
context: ./backend
|
||||
additional_contexts: { frontend: ./frontend }
|
||||
secrets: [dredd_core_token]
|
||||
image: agora-backend:local
|
||||
env_file: .env
|
||||
command: sh -c "alembic upgrade head && python -m app.seed"
|
||||
restart: "no"
|
||||
volumes:
|
||||
- agora-data:/data
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
|
||||
backend:
|
||||
build:
|
||||
context: ./backend
|
||||
additional_contexts: { frontend: ./frontend }
|
||||
secrets: [dredd_core_token]
|
||||
image: agora-backend:local
|
||||
env_file: .env
|
||||
ports:
|
||||
- "80:8000"
|
||||
volumes:
|
||||
- agora-data:/data
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
agora-data:
|
||||
|
||||
secrets:
|
||||
# Used only by the build stage's one `pip install`; no running container gets it. Compose resolves
|
||||
# the variable from the shell OR the project .env (shell wins) — keep it in the shell, because every
|
||||
# service here also loads .env at runtime and would receive the token:
|
||||
# DREDD_CORE_TOKEN=github_pat_... docker compose up -d --build
|
||||
dredd_core_token:
|
||||
environment: DREDD_CORE_TOKEN
|
||||
@@ -0,0 +1,512 @@
|
||||
/* Agora console.
|
||||
UI chrome stays monochrome (near-black light / near-white dark) — buttons, emphasis, text.
|
||||
The brand is Open Color **red #e03131**, and it is confined to things that read as
|
||||
an identity rather than a control: the app mark, icon tiles, the avatar, the focus ring. Nav
|
||||
and toolbar glyphs stay monochrome, or the whole console turns into a colour field and nothing
|
||||
stands out.
|
||||
Semantic colour (overdue / warning / ok) is a separate axis from the brand and earns its
|
||||
place: something that needs attention has to read at a glance.
|
||||
Dark mode lightens the brand for text-weight use — a shade-8 on a near-black ground is legible
|
||||
as a filled background but too dim as a 2px stroke. */
|
||||
|
||||
:root {
|
||||
--bg: #f6f7f8;
|
||||
--surface: #ffffff;
|
||||
--surface-2: #f0f2f3;
|
||||
--surface-hover: #e9ecee;
|
||||
--border: #dfe3e6;
|
||||
--border-input: #c8ced3;
|
||||
--text: #14181b;
|
||||
--text-secondary: #4c565e;
|
||||
--text-muted: #6d7880;
|
||||
--text-faint: #98a2a9;
|
||||
--accent: #14181b;
|
||||
--accent-text: #ffffff;
|
||||
/* `--brand-bg` carries ICONS (3:1 against the glyph is the bar for graphics).
|
||||
`--brand-ink` is one step darker for the one filled shape that carries TEXT — the avatar's
|
||||
initials — where 4.5:1 applies. Same family, one step, rather than a second colour. */
|
||||
--brand: #e03131;
|
||||
--brand-bg: #e03131;
|
||||
--brand-ink: #c92a2a;
|
||||
--brand-fg: #fff5f5;
|
||||
|
||||
--ok: #1f7a4d;
|
||||
--ok-bg: #e7f5ee;
|
||||
--warn: #9a6200;
|
||||
--warn-bg: #fdf3e0;
|
||||
--err: #b02525;
|
||||
--err-bg: #fdeceb;
|
||||
|
||||
--radius: 8px;
|
||||
--radius-sm: 6px;
|
||||
--shadow: 0 1px 2px rgba(20, 24, 27, .06), 0 4px 12px rgba(20, 24, 27, .05);
|
||||
--mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;
|
||||
--sans: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root:not([data-theme="light"]) {
|
||||
--bg: #101315;
|
||||
--surface: #181c1f;
|
||||
--surface-2: #1f2427;
|
||||
--surface-hover: #272d31;
|
||||
--border: #2b3236;
|
||||
--border-input: #3a4247;
|
||||
--text: #eef1f2;
|
||||
--text-secondary: #b3bbc0;
|
||||
--text-muted: #8b959b;
|
||||
--text-faint: #69737a;
|
||||
--accent: #eef1f2;
|
||||
--accent-text: #101315;
|
||||
/* A lighter shade for stroke-weight use; the filled grounds stay put so a tile looks the
|
||||
same in both themes. */
|
||||
--brand: #ff8787;
|
||||
--brand-bg: #e03131;
|
||||
--brand-ink: #c92a2a;
|
||||
--brand-fg: #fff5f5;
|
||||
--ok: #5cc98f;
|
||||
--ok-bg: #16281f;
|
||||
--warn: #e8b45c;
|
||||
--warn-bg: #2a2115;
|
||||
--err: #f08a80;
|
||||
--err-bg: #2c1a18;
|
||||
--shadow: 0 1px 2px rgba(0, 0, 0, .4), 0 4px 14px rgba(0, 0, 0, .3);
|
||||
}
|
||||
}
|
||||
|
||||
:root[data-theme="dark"] {
|
||||
--bg: #101315;
|
||||
--surface: #181c1f;
|
||||
--surface-2: #1f2427;
|
||||
--surface-hover: #272d31;
|
||||
--border: #2b3236;
|
||||
--border-input: #3a4247;
|
||||
--text: #eef1f2;
|
||||
--text-secondary: #b3bbc0;
|
||||
--text-muted: #8b959b;
|
||||
--text-faint: #69737a;
|
||||
--accent: #eef1f2;
|
||||
--accent-text: #101315;
|
||||
--brand: #ff8787;
|
||||
--brand-bg: #e03131;
|
||||
--brand-ink: #c92a2a;
|
||||
--brand-fg: #fff5f5;
|
||||
--ok: #5cc98f;
|
||||
--ok-bg: #16281f;
|
||||
--warn: #e8b45c;
|
||||
--warn-bg: #2a2115;
|
||||
--err: #f08a80;
|
||||
--err-bg: #2c1a18;
|
||||
--shadow: 0 1px 2px rgba(0, 0, 0, .4), 0 4px 14px rgba(0, 0, 0, .3);
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: var(--sans);
|
||||
font-size: 14px;
|
||||
line-height: 1.5;
|
||||
color: var(--text);
|
||||
background: var(--bg);
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
.hidden { display: none !important; }
|
||||
a { color: inherit; cursor: pointer; text-decoration: none; }
|
||||
a:hover { text-decoration: underline; }
|
||||
:focus-visible { outline: 2px solid var(--brand); outline-offset: 2px; border-radius: 4px; }
|
||||
|
||||
/* ── login ─────────────────────────────────────────────────────────────── */
|
||||
#login {
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 24px;
|
||||
background: var(--bg);
|
||||
}
|
||||
.login-tools { position: fixed; top: 16px; right: 16px; display: flex; gap: 8px; z-index: 5; }
|
||||
.login-tools .iconbtn { background: var(--surface); border: 1px solid var(--border-input); }
|
||||
.login-card {
|
||||
width: 100%;
|
||||
max-width: 360px;
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
padding: 32px;
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
.login-card .logo { width: 40px; height: 40px; display: block; }
|
||||
.login-card h1 { font-size: 22px; margin: 16px 0 2px; letter-spacing: -.01em; }
|
||||
.lsub { color: var(--text-muted); font-size: 13px; margin-bottom: 22px; }
|
||||
.login-card .banner { margin: 14px 0 0; }
|
||||
.login-card .btn { margin-top: 18px; width: 100%; justify-content: center; }
|
||||
|
||||
/* ── shell ─────────────────────────────────────────────────────────────── */
|
||||
#app { display: flex; min-height: 100vh; }
|
||||
.sidebar {
|
||||
width: 232px;
|
||||
flex: none;
|
||||
background: var(--surface);
|
||||
border-right: 1px solid var(--border);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
position: sticky;
|
||||
top: 0;
|
||||
height: 100vh;
|
||||
}
|
||||
.brand { display: flex; align-items: center; gap: 10px; padding: 16px 18px; }
|
||||
.brand .logo { width: 26px; height: 26px; flex: none; }
|
||||
.brand .nm { font-weight: 650; letter-spacing: -.01em; font-size: 16px; }
|
||||
.nav { flex: 1; overflow-y: auto; padding: 6px 10px; display: flex; flex-direction: column; gap: 2px; }
|
||||
.sidebar-foot { flex: none; border-top: 1px solid var(--border); padding-bottom: 10px; }
|
||||
.nav-item {
|
||||
display: flex; align-items: center; gap: 10px;
|
||||
padding: 8px 10px; border-radius: var(--radius-sm);
|
||||
color: var(--text-secondary); cursor: pointer; font-size: 13.5px;
|
||||
}
|
||||
.nav-item:hover { background: var(--surface-hover); color: var(--text); text-decoration: none; }
|
||||
.nav-item.on { background: var(--surface-2); color: var(--text); font-weight: 550; }
|
||||
.nav-item svg { flex: none; color: var(--text-muted); }
|
||||
.nav-item.on svg { color: var(--text); }
|
||||
.nav-item .cnt {
|
||||
margin-left: auto; font-size: 11px; font-variant-numeric: tabular-nums;
|
||||
background: var(--surface-hover); color: var(--text-secondary);
|
||||
border-radius: 999px; padding: 1px 7px;
|
||||
}
|
||||
.nav-item .cnt.hot { background: var(--err-bg); color: var(--err); }
|
||||
.nav-sep { font-size: 11px; text-transform: uppercase; letter-spacing: .07em;
|
||||
color: var(--text-faint); padding: 14px 10px 4px; }
|
||||
|
||||
.main { flex: 1; min-width: 0; display: flex; flex-direction: column; }
|
||||
.topbar {
|
||||
display: flex; align-items: center; gap: 8px;
|
||||
padding: 10px 18px; border-bottom: 1px solid var(--border);
|
||||
background: var(--surface); position: sticky; top: 0; z-index: 4;
|
||||
}
|
||||
.spacer { flex: 1; }
|
||||
.vdiv { width: 1px; height: 20px; background: var(--border); margin: 0 4px; }
|
||||
.crumb { display: flex; align-items: center; gap: 6px; min-width: 0;
|
||||
overflow-x: auto; white-space: nowrap; scrollbar-width: none; color: var(--text-muted); }
|
||||
.crumb::-webkit-scrollbar { display: none; }
|
||||
.crumb b { color: var(--text); font-weight: 600; }
|
||||
.crumb .sep { color: var(--text-faint); }
|
||||
.content { padding: 22px; max-width: 1180px; width: 100%; }
|
||||
|
||||
#navToggle { display: none; }
|
||||
#navScrim { display: none; }
|
||||
.appcard.m-only { display: none; }
|
||||
/* ── global search ─────────────────────────────────────────────────────── */
|
||||
/* Looks like an input, is a button: the field itself is in the overlay, so there is one place
|
||||
the query lives rather than two that can disagree. */
|
||||
.searchbar {
|
||||
display: inline-flex; align-items: center; gap: 8px;
|
||||
min-width: 210px; padding: 5px 8px 5px 10px;
|
||||
border: 1px solid var(--border-input); border-radius: var(--radius-sm);
|
||||
background: var(--bg); color: var(--text-muted);
|
||||
font: inherit; font-size: 13px; cursor: text;
|
||||
}
|
||||
.searchbar:hover { background: var(--surface-hover); }
|
||||
.searchbar .sp { flex: 1; text-align: left; }
|
||||
.searchbar kbd {
|
||||
font: inherit; font-size: 10.5px; color: var(--text-faint);
|
||||
border: 1px solid var(--border); border-radius: 4px; padding: 1px 4px;
|
||||
}
|
||||
|
||||
/* ── controls ──────────────────────────────────────────────────────────── */
|
||||
.btn {
|
||||
display: inline-flex; align-items: center; gap: 7px;
|
||||
padding: 7px 13px; border-radius: var(--radius-sm);
|
||||
border: 1px solid var(--border-input); background: var(--surface);
|
||||
color: var(--text); font: inherit; font-size: 13.5px; cursor: pointer;
|
||||
}
|
||||
.btn:hover { background: var(--surface-hover); }
|
||||
/* A .btn that is an <a> because it navigates rather than acts — the sign-in link on a platform
|
||||
module's login card. Without this it picks up the global `a:hover` underline and is the one
|
||||
button in the console that behaves like a link. Same reset .nav-item and a.appcard already do. */
|
||||
a.btn:hover { text-decoration: none; }
|
||||
.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-text); }
|
||||
.btn.primary:hover { opacity: .88; }
|
||||
.btn.danger { color: var(--err); border-color: var(--border-input); }
|
||||
.btn.danger:hover { background: var(--err-bg); }
|
||||
.btn:disabled { opacity: .5; cursor: not-allowed; }
|
||||
.btn.sm { padding: 4px 9px; font-size: 12.5px; }
|
||||
|
||||
.iconbtn {
|
||||
display: inline-flex; align-items: center; justify-content: center;
|
||||
width: 32px; height: 32px; border-radius: var(--radius-sm);
|
||||
border: 1px solid transparent; background: transparent;
|
||||
color: var(--text-secondary); cursor: pointer; position: relative;
|
||||
}
|
||||
.iconbtn:hover { background: var(--surface-hover); color: var(--text); }
|
||||
.iconbtn.txt { font: 600 11.5px/1 var(--sans); letter-spacing: .04em; }
|
||||
/* Unread badge. Semantic red — it means "something needs you", which is separate from brand. */
|
||||
.iconbtn .cnt {
|
||||
position: absolute; top: 1px; right: 0;
|
||||
min-width: 15px; height: 15px; padding: 0 3px;
|
||||
border-radius: 999px; background: var(--err); color: #fff;
|
||||
font: 600 10px/15px var(--sans); text-align: center;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
/* Launcher — how sibling apps appear side by side once they share a shell. */
|
||||
.applist { display: grid; gap: 8px; }
|
||||
.appcard {
|
||||
display: flex; align-items: center; gap: 12px;
|
||||
padding: 12px 14px; border: 1px solid var(--border);
|
||||
border-radius: var(--radius); background: var(--surface); color: inherit;
|
||||
}
|
||||
a.appcard:hover, button.appcard:hover { background: var(--surface-hover); text-decoration: none; }
|
||||
button.appcard { width: 100%; font: inherit; text-align: left; cursor: pointer; }
|
||||
.appcard.on { background: var(--surface-2); }
|
||||
.appcard .ai {
|
||||
width: 36px; height: 36px; flex: none; border-radius: var(--radius-sm);
|
||||
background: var(--brand-bg); color: var(--brand-fg);
|
||||
display: inline-flex; align-items: center; justify-content: center;
|
||||
}
|
||||
.appcard .an { font-weight: 550; }
|
||||
.appcard > svg:last-child { margin-left: auto; color: var(--text-faint); flex: none; }
|
||||
|
||||
.avatar {
|
||||
padding: 0; font-family: inherit; line-height: 1;
|
||||
width: 30px; height: 30px; flex: none; border-radius: 50%;
|
||||
/* --brand-ink, not --brand-bg: these are initials, and text needs 4.5:1. */
|
||||
background: var(--brand-ink); border: 1px solid transparent;
|
||||
display: inline-flex; align-items: center; justify-content: center;
|
||||
font-size: 11.5px; font-weight: 650; color: var(--brand-fg); cursor: pointer;
|
||||
}
|
||||
|
||||
.field { display: block; font-size: 12.5px; color: var(--text-secondary); }
|
||||
.field > input, .field > select, .field > textarea, .pw-field > input {
|
||||
display: block; width: 100%; margin-top: 5px;
|
||||
padding: 8px 10px; border-radius: var(--radius-sm);
|
||||
border: 1px solid var(--border-input); background: var(--surface);
|
||||
color: var(--text); font: inherit; font-size: 13.5px;
|
||||
}
|
||||
.field > textarea { min-height: 78px; resize: vertical; }
|
||||
.pw-field { position: relative; display: block; }
|
||||
.pw-eye {
|
||||
position: absolute; right: 6px; top: 50%; transform: translateY(-50%);
|
||||
width: 26px; height: 26px; border: 0; background: transparent;
|
||||
color: var(--text-muted); cursor: pointer; display: inline-flex;
|
||||
align-items: center; justify-content: center;
|
||||
}
|
||||
.grid2 { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
|
||||
.grid3 { display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; }
|
||||
@media (max-width: 700px) { .grid2, .grid3 { grid-template-columns: 1fr; } }
|
||||
|
||||
/* ── page furniture ────────────────────────────────────────────────────── */
|
||||
.page-head { display: flex; align-items: flex-start; gap: 12px; margin-bottom: 18px; flex-wrap: wrap; }
|
||||
.page-head h2 { margin: 0; font-size: 19px; letter-spacing: -.01em; }
|
||||
.page-head .sub { color: var(--text-muted); font-size: 13px; margin-top: 2px; }
|
||||
/* `flex-wrap` on both, so a row of actions drops below the title instead of pushing the page
|
||||
sideways — a horizontally scrolling body is the one layout bug with no acceptable version. */
|
||||
.page-head .acts { margin-left: auto; display: flex; gap: 8px; flex-wrap: wrap; }
|
||||
|
||||
.card {
|
||||
background: var(--surface); border: 1px solid var(--border);
|
||||
border-radius: var(--radius); padding: 16px;
|
||||
}
|
||||
.card + .card { margin-top: 14px; }
|
||||
.card h3 { margin: 0 0 12px; font-size: 14px; font-weight: 650; }
|
||||
.card h3 .n { color: var(--text-faint); font-weight: 500; margin-left: 6px; }
|
||||
|
||||
.tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 12px; }
|
||||
.tile {
|
||||
background: var(--surface); border: 1px solid var(--border);
|
||||
border-radius: var(--radius); padding: 14px 16px;
|
||||
}
|
||||
.tile .k { font-size: 12px; color: var(--text-muted); }
|
||||
.tile .v { font-size: 24px; font-weight: 600; font-variant-numeric: tabular-nums;
|
||||
letter-spacing: -.02em; margin-top: 2px; }
|
||||
.tile.hot { border-color: var(--err); }
|
||||
.tile.hot .v { color: var(--err); }
|
||||
.tile.warn { border-color: var(--warn); }
|
||||
.tile.warn .v { color: var(--warn); }
|
||||
|
||||
.tablewrap { overflow-x: auto; }
|
||||
table { width: 100%; border-collapse: collapse; font-size: 13.5px; }
|
||||
th {
|
||||
text-align: left; font-size: 11px; text-transform: uppercase; letter-spacing: .06em;
|
||||
color: var(--text-faint); font-weight: 600; padding: 6px 10px;
|
||||
border-bottom: 1px solid var(--border); white-space: nowrap;
|
||||
}
|
||||
td { padding: 9px 10px; border-bottom: 1px solid var(--border); vertical-align: top; }
|
||||
tr:last-child td { border-bottom: 0; }
|
||||
tbody tr.click:hover { background: var(--surface-2); cursor: pointer; }
|
||||
td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; }
|
||||
td.mono { font-family: var(--mono); font-size: 12.5px; }
|
||||
|
||||
.chip {
|
||||
display: inline-flex; align-items: center; gap: 5px;
|
||||
padding: 1px 8px; border-radius: 999px; font-size: 11.5px;
|
||||
background: var(--surface-2); color: var(--text-secondary);
|
||||
border: 1px solid var(--border); white-space: nowrap;
|
||||
}
|
||||
.chip.ok { background: var(--ok-bg); color: var(--ok); border-color: transparent; }
|
||||
.chip.warn { background: var(--warn-bg); color: var(--warn); border-color: transparent; }
|
||||
.chip.err { background: var(--err-bg); color: var(--err); border-color: transparent; }
|
||||
|
||||
/* A severity stripe reads faster than a number when you are scanning a list for the one row
|
||||
that will ruin your week. */
|
||||
.stripe { border-left: 3px solid transparent; padding-left: 9px; }
|
||||
.stripe.s3 { border-left-color: var(--err); }
|
||||
.stripe.s2 { border-left-color: var(--warn); }
|
||||
.stripe.s1 { border-left-color: var(--border-input); }
|
||||
|
||||
.banner {
|
||||
padding: 9px 12px; border-radius: var(--radius-sm); font-size: 13px;
|
||||
border: 1px solid var(--border); background: var(--surface-2);
|
||||
}
|
||||
.banner.err { background: var(--err-bg); color: var(--err); border-color: transparent; }
|
||||
.banner.warn { background: var(--warn-bg); color: var(--warn); border-color: transparent; }
|
||||
.banner.ok { background: var(--ok-bg); color: var(--ok); border-color: transparent; }
|
||||
.banner + .banner, .card > .banner:first-child { margin-bottom: 12px; }
|
||||
|
||||
.empty {
|
||||
padding: 40px 20px; text-align: center; color: var(--text-muted);
|
||||
border: 1px dashed var(--border); border-radius: var(--radius); font-size: 13.5px;
|
||||
}
|
||||
.faint { color: var(--text-muted); }
|
||||
.tiny { font-size: 12px; }
|
||||
.wrap { overflow-wrap: anywhere; }
|
||||
.row { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
|
||||
.toolbar { display: flex; gap: 8px; align-items: center; margin-bottom: 12px; flex-wrap: wrap; }
|
||||
.toolbar input, .toolbar select {
|
||||
padding: 7px 10px; border-radius: var(--radius-sm);
|
||||
border: 1px solid var(--border-input); background: var(--surface);
|
||||
color: var(--text); font: inherit; font-size: 13.5px;
|
||||
}
|
||||
.toolbar input[type="search"] { min-width: 220px; }
|
||||
|
||||
/* ── modal ─────────────────────────────────────────────────────────────── */
|
||||
#modalRoot:empty { display: none; }
|
||||
.scrim {
|
||||
position: fixed; inset: 0; background: rgba(0, 0, 0, .4);
|
||||
display: flex; align-items: flex-start; justify-content: center;
|
||||
padding: 40px 16px; z-index: 40; overflow-y: auto;
|
||||
}
|
||||
.modal, .search-modal {
|
||||
background: var(--surface); border: 1px solid var(--border);
|
||||
border-radius: 10px; box-shadow: var(--shadow); width: 100%;
|
||||
}
|
||||
.modal { max-width: 560px; padding: 20px; }
|
||||
.modal.wide { max-width: 760px; }
|
||||
.modal h3 { margin: 0 0 4px; font-size: 16px; }
|
||||
.modal .msub { color: var(--text-muted); font-size: 12.5px; margin-bottom: 16px; }
|
||||
.modal .acts { display: flex; gap: 8px; justify-content: flex-end; margin-top: 18px; }
|
||||
.modal .field + .field, .modal .grid2 + .field, .modal .field + .grid2 { margin-top: 12px; }
|
||||
|
||||
/* ── command palette ───────────────────────────────────────────────────── */
|
||||
/* After the modal on purpose: it sits on the dialog's `.scrim` and overrides its padding at equal
|
||||
specificity by coming later. It shares the dialog's box (see `.modal, .search-modal`) but not its
|
||||
padding, so its dividers run edge to edge. It sits higher than a dialog — reached from anywhere,
|
||||
including from on top of one — and lands where the eye already is rather than centred. */
|
||||
.search-scrim { padding-top: 12vh; }
|
||||
.search-modal { max-width: 620px; overflow: hidden; }
|
||||
.search-modal .sin {
|
||||
display: flex; align-items: center; gap: 10px;
|
||||
padding: 12px 14px; border-bottom: 1px solid var(--border); color: var(--text-muted);
|
||||
}
|
||||
.search-modal .sin input {
|
||||
flex: 1; border: 0; background: none; color: var(--text);
|
||||
font: inherit; font-size: 15px; outline: none; padding: 0;
|
||||
}
|
||||
.search-results { max-height: 58vh; overflow-y: auto; overflow-x: hidden; }
|
||||
.search-results .sgroup {
|
||||
padding: 8px 14px 4px; font-size: 11px; font-weight: 600; letter-spacing: .04em;
|
||||
text-transform: uppercase; color: var(--text-faint);
|
||||
}
|
||||
.search-results .sitem {
|
||||
display: flex; align-items: center; gap: 10px; width: 100%;
|
||||
padding: 8px 14px; border: 0; background: none; color: var(--text);
|
||||
font: inherit; font-size: 13.5px; text-align: left; cursor: pointer;
|
||||
}
|
||||
.search-results .sitem:hover, .search-results .sitem.on { background: var(--surface-hover); }
|
||||
.search-results .sitem .ic { color: var(--text-muted); flex: none; display: flex; }
|
||||
.search-results .sitem .sb { min-width: 0; flex: 1; }
|
||||
/* Block, or the ellipsis never applies: overflow clipping needs a box, and these are spans. */
|
||||
.search-results .sitem .st, .search-results .sitem .ss { display: block; }
|
||||
.search-results .sitem .st { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.search-results .sitem .ss {
|
||||
font-size: 12px; color: var(--text-muted);
|
||||
white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
|
||||
}
|
||||
.search-modal .shint {
|
||||
padding: 8px 14px; border-top: 1px solid var(--border);
|
||||
font-size: 11.5px; color: var(--text-faint);
|
||||
}
|
||||
.search-empty { padding: 22px 14px; text-align: center; color: var(--text-muted); font-size: 13px; }
|
||||
|
||||
/* ── toast ─────────────────────────────────────────────────────────────── */
|
||||
#toast { position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%); z-index: 60; }
|
||||
.toast {
|
||||
background: var(--accent); color: var(--accent-text);
|
||||
padding: 9px 15px; border-radius: var(--radius-sm);
|
||||
font-size: 13px; box-shadow: var(--shadow);
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
* { transition: none !important; animation: none !important; }
|
||||
}
|
||||
|
||||
/* ── narrow screens ─────────────────────────────────────────────────────── */
|
||||
/* Breakpoints are last in the file on purpose, widest first: a media query adds no specificity, so
|
||||
an override only wins if it comes after the rule it overrides. */
|
||||
@media (max-width: 880px) {
|
||||
/* `visibility` as well as `transform`: a closed drawer must not be clickable or reachable by
|
||||
keyboard, and a translated-off panel still is. */
|
||||
.sidebar {
|
||||
position: fixed; z-index: 20;
|
||||
transform: translateX(-100%); visibility: hidden;
|
||||
/* Only `transform` transitions. `visibility` flips instantly in both directions, and is
|
||||
deliberately NOT delayed to animate the slide-out: any transition on visibility — even a
|
||||
0s one with a delay — needs the transition machinery to tick, and when frames are
|
||||
throttled (a background tab, a compositor that is not running) the drawer gets stuck in
|
||||
whichever state it was in. An instant close is worth more than 180ms of slide. */
|
||||
transition: transform .18s;
|
||||
}
|
||||
.sidebar.open { transform: none; visibility: visible; }
|
||||
#navToggle { display: inline-flex; }
|
||||
#navScrim.on { display: block; position: fixed; inset: 0; background: rgba(0,0,0,.35); z-index: 19; }
|
||||
.content { padding: 16px; }
|
||||
|
||||
/* Nine controls at 30px each leave the breadcrumb exactly 0 pixels. On a phone the top bar
|
||||
keeps only what you need constantly, and the rest moves into the account sheet. */
|
||||
.topbar .js-tool { display: none; }
|
||||
.appcard.m-only { display: flex; }
|
||||
.search-modal .shint { display: none; } /* no Esc key on a phone */
|
||||
.search-results { max-height: 62vh; }
|
||||
.topbar { padding: 10px 12px; gap: 6px; }
|
||||
.page-head { margin-bottom: 14px; }
|
||||
.page-head .acts { margin-left: 0; width: 100%; }
|
||||
.page-head .acts .btn { flex: 1; justify-content: center; }
|
||||
.toolbar input[type="search"] { min-width: 0; flex: 1; }
|
||||
.scrim { padding: 12px; }
|
||||
.search-scrim { padding-top: 8vh; }
|
||||
.modal { padding: 16px; }
|
||||
.modal .acts { flex-wrap: wrap; }
|
||||
.modal .acts .btn { flex: 1; justify-content: center; }
|
||||
.tile .v { font-size: 20px; }
|
||||
}
|
||||
|
||||
/* ── phones: data tables become stacked cards ──────────────────────────── */
|
||||
@media (max-width: 640px) {
|
||||
table.rt thead { display: none; }
|
||||
table.rt, table.rt tbody, table.rt tr { display: block; width: 100%; }
|
||||
table.rt tr { padding: 10px 0; border-bottom: 1px solid var(--border); }
|
||||
table.rt tr:last-child { border-bottom: 0; }
|
||||
table.rt td {
|
||||
display: flex; align-items: flex-start; justify-content: space-between; gap: 12px;
|
||||
padding: 3px 0; border: 0; text-align: right; width: auto;
|
||||
}
|
||||
table.rt td::before {
|
||||
content: attr(data-label); flex: none; text-align: left; padding-top: 2px;
|
||||
font-size: 10.5px; text-transform: uppercase; letter-spacing: .06em; color: var(--text-faint);
|
||||
}
|
||||
table.rt td:first-child { justify-content: flex-start; text-align: left; font-weight: 600; padding-bottom: 6px; }
|
||||
table.rt td:first-child::before, table.rt td.acts-cell::before { content: none; }
|
||||
table.rt td.acts-cell { justify-content: flex-end; padding-top: 8px; }
|
||||
table.rt td:not(:first-child) .row { justify-content: flex-end; }
|
||||
}
|
||||
+809
@@ -0,0 +1,809 @@
|
||||
/* Agora console — vanilla JS, no build step.
|
||||
Source strings are in the product's first language; I18N translates to the other. The
|
||||
mechanism (_tr / _trAttr / localize, matching on source text, with data-no-i18n opt-outs) is
|
||||
the same across the family — only the source language differs.
|
||||
|
||||
After editing this file, run `node --check frontend/app.js`. A duplicate `const` inside one
|
||||
function silently stops the whole file parsing, so every function defined after it disappears,
|
||||
and the symptom is a screen that renders nothing with no console error to find. */
|
||||
|
||||
'use strict';
|
||||
|
||||
/* The API base, derived from the document rather than hard-coded to the origin root. Served at the
|
||||
root (the standalone stack, ROOT_PATH empty) this is `/api/v1`; served under a path prefix as a
|
||||
module of a platform — one origin, one module per path — it is `/agora/api/v1`, and every
|
||||
`API + path` call site below is unchanged. This is the ONE line that makes the console portable
|
||||
across the prefix, and it only works because everything else here already is: every asset in
|
||||
index.html is document-relative and routing is hash-based. So: no leading-slash `src`, `href`,
|
||||
`fetch`, `location` or `window.open` anywhere in this console, ever.
|
||||
A fragment in the base is dropped by URL resolution, so a hash route resolves identically. It DOES
|
||||
depend on the trailing slash — bare `/agora` would resolve to `/api/v1` — which is why a
|
||||
platform proxy must redirect `/agora` to `/agora/`. */
|
||||
const API = new URL('api/v1', document.baseURI).pathname;
|
||||
/* 'nodes' = records live in a permission tree; 'simple' = flat, owner-based. */
|
||||
const TENANCY = 'simple';
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
/* A column label for a data cell. Tables with class "rt" become stacked cards on a phone, and each
|
||||
cell shows its label there (CSS `td[data-label]::before`); on a wide screen the header row does. */
|
||||
const lbl = (label) => ` data-label="${label}"`;
|
||||
const esc = (v) => String(v ?? '').replace(/[&<>"']/g, (c) =>
|
||||
({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||
|
||||
const state = {
|
||||
/* `meta` is the unauthenticated answer to "does this deployment have a sign-in of its own, or does
|
||||
the hub?" — see loadMeta(). Null until it has been asked for, which is deliberately not before
|
||||
it is needed. */
|
||||
token: '', user: null, meta: null, users: [], containers: [], config: {}, counts: {},
|
||||
};
|
||||
|
||||
/* The bearer token is kept in memory only — never localStorage — so an XSS bug cannot read it
|
||||
out of storage after the fact. The cookie is the primary credential and is HttpOnly. */
|
||||
async function api(method, path, body) {
|
||||
const opt = { method, headers: {}, credentials: 'same-origin' };
|
||||
if (state.token) opt.headers.Authorization = 'Bearer ' + state.token;
|
||||
if (body !== undefined) {
|
||||
opt.headers['Content-Type'] = 'application/json';
|
||||
opt.body = JSON.stringify(body);
|
||||
}
|
||||
const res = await fetch(API + path, opt);
|
||||
const text = await res.text();
|
||||
let data = null;
|
||||
if (text) { try { data = JSON.parse(text); } catch { data = { detail: text }; } }
|
||||
if (!res.ok) {
|
||||
const err = new Error((data && (data.detail || data.title)) || ('HTTP ' + res.status));
|
||||
err.status = res.status;
|
||||
err.problem = data;
|
||||
throw err;
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
function toast(msg) {
|
||||
const t = $('toast');
|
||||
t.innerHTML = `<div class="toast">${esc(msg)}</div>`;
|
||||
setTimeout(() => { t.innerHTML = ''; }, 3000);
|
||||
}
|
||||
|
||||
/* ── formatting ─────────────────────────────────────────────────────────── */
|
||||
const LOCALE = 'pl' === 'pl' ? 'pl-PL' : 'en-GB';
|
||||
|
||||
function fmtDate(iso) {
|
||||
if (!iso) return '—';
|
||||
const d = new Date(iso.length <= 10 ? iso + 'T00:00:00' : iso);
|
||||
return isNaN(d) ? '—' : d.toLocaleDateString(LOCALE, { day: '2-digit', month: '2-digit', year: 'numeric' });
|
||||
}
|
||||
function fmtDateTime(iso) {
|
||||
if (!iso) return '—';
|
||||
const d = new Date(iso);
|
||||
return isNaN(d) ? '—' : d.toLocaleString(LOCALE, {
|
||||
day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit',
|
||||
});
|
||||
}
|
||||
/* Money is integer minor units everywhere except this boundary — the API never sees a float. */
|
||||
function fmtMoney(minor, ccy) {
|
||||
if (minor == null) return '—';
|
||||
return (Number(minor) / 100).toLocaleString(LOCALE, {
|
||||
minimumFractionDigits: 2, maximumFractionDigits: 2,
|
||||
}) + ' ' + (ccy || 'PLN');
|
||||
}
|
||||
function toMinor(v) {
|
||||
const n = parseFloat(String(v == null ? '' : v).replace(/\s/g, '').replace(',', '.'));
|
||||
return Number.isFinite(n) ? Math.round(n * 100) : null;
|
||||
}
|
||||
function fromMinor(m) { return m == null ? '' : (m / 100).toFixed(2); }
|
||||
|
||||
function initials(s) {
|
||||
s = String(s || '?');
|
||||
return s.replace(/@.*/, '').split(/[.\s_-]+/).filter(Boolean).slice(0, 2)
|
||||
.map((x) => x[0].toUpperCase()).join('') || '?';
|
||||
}
|
||||
|
||||
/* ── icons (Tabler outline, MIT — path data vendored, never a CDN) ──────── */
|
||||
const ICN = {
|
||||
// tabler: layout-dashboard
|
||||
dashboard: '<path d="M5 4h4a1 1 0 0 1 1 1v6a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1v-6a1 1 0 0 1 1 -1"/><path d="M5 16h4a1 1 0 0 1 1 1v2a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1v-2a1 1 0 0 1 1 -1"/><path d="M15 12h4a1 1 0 0 1 1 1v6a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1v-6a1 1 0 0 1 1 -1"/><path d="M15 4h4a1 1 0 0 1 1 1v2a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1v-2a1 1 0 0 1 1 -1"/>',
|
||||
// tabler: file-text
|
||||
file: '<path d="M14 3v4a1 1 0 0 0 1 1h4"/><path d="M17 21h-10a2 2 0 0 1 -2 -2v-14a2 2 0 0 1 2 -2h7l5 5v11a2 2 0 0 1 -2 2"/><path d="M9 9l1 0"/><path d="M9 13l6 0"/><path d="M9 17l6 0"/>',
|
||||
// tabler: folder-open
|
||||
folder: '<path d="M5 19l2.757 -7.351a1 1 0 0 1 .936 -.649h12.307a1 1 0 0 1 .986 1.164l-.996 5.211a2 2 0 0 1 -1.964 1.625h-14.026a2 2 0 0 1 -2 -2v-11a2 2 0 0 1 2 -2h4l3 3h7a2 2 0 0 1 2 2v2"/>',
|
||||
// tabler: settings
|
||||
settings: '<path d="M10.325 4.317c.426 -1.756 2.924 -1.756 3.35 0a1.724 1.724 0 0 0 2.573 1.066c1.543 -.94 3.31 .826 2.37 2.37a1.724 1.724 0 0 0 1.065 2.572c1.756 .426 1.756 2.924 0 3.35a1.724 1.724 0 0 0 -1.066 2.573c.94 1.543 -.826 3.31 -2.37 2.37a1.724 1.724 0 0 0 -2.572 1.065c-.426 1.756 -2.924 1.756 -3.35 0a1.724 1.724 0 0 0 -2.573 -1.066c-1.543 .94 -3.31 -.826 -2.37 -2.37a1.724 1.724 0 0 0 -1.065 -2.572c-1.756 -.426 -1.756 -2.924 0 -3.35a1.724 1.724 0 0 0 1.066 -2.573c-.94 -1.543 .826 -3.31 2.37 -2.37c1 .608 2.296 .07 2.572 -1.065"/><path d="M9 12a3 3 0 1 0 6 0a3 3 0 0 0 -6 0"/>',
|
||||
// tabler: plus
|
||||
plus: '<path d="M12 5l0 14"/><path d="M5 12l14 0"/>',
|
||||
// tabler: check
|
||||
check: '<path d="M5 12l5 5l10 -10"/>',
|
||||
// tabler: x
|
||||
x: '<path d="M18 6l-12 12"/><path d="M6 6l12 12"/>',
|
||||
// tabler: sun
|
||||
sun: '<path d="M8 12a4 4 0 1 0 8 0a4 4 0 1 0 -8 0"/><path d="M3 12h1m8 -9v1m8 8h1m-9 8v1m-6.4 -15.4l.7 .7m12.1 -.7l-.7 .7m0 11.4l.7 .7m-12.1 -.7l-.7 .7"/>',
|
||||
// tabler: moon
|
||||
moon: '<path d="M12 3c.132 0 .263 0 .393 0a7.5 7.5 0 0 0 7.92 12.446a9 9 0 1 1 -8.313 -12.454l0 .008"/>',
|
||||
// tabler: device-desktop
|
||||
desktop: '<path d="M3 5a1 1 0 0 1 1 -1h16a1 1 0 0 1 1 1v10a1 1 0 0 1 -1 1h-16a1 1 0 0 1 -1 -1v-10"/><path d="M7 20h10"/><path d="M9 16v4"/><path d="M15 16v4"/>',
|
||||
// tabler: eye
|
||||
eye: '<path d="M10 12a2 2 0 1 0 4 0a2 2 0 0 0 -4 0"/><path d="M21 12c-2.4 4 -5.4 6 -9 6c-3.6 0 -6.6 -2 -9 -6c2.4 -4 5.4 -6 9 -6c3.6 0 6.6 2 9 6"/>',
|
||||
// tabler: eye-off
|
||||
eyeoff: '<path d="M10.585 10.587a2 2 0 0 0 2.829 2.828"/><path d="M16.681 16.673a8.717 8.717 0 0 1 -4.681 1.327c-3.6 0 -6.6 -2 -9 -6c1.272 -2.12 2.712 -3.678 4.32 -4.674m2.86 -1.146a9.055 9.055 0 0 1 1.82 -.18c3.6 0 6.6 2 9 6c-.666 1.11 -1.379 2.067 -2.138 2.87"/><path d="M3 3l18 18"/>',
|
||||
// tabler: trash
|
||||
trash: '<path d="M4 7l16 0"/><path d="M10 11l0 6"/><path d="M14 11l0 6"/><path d="M5 7l1 12a2 2 0 0 0 2 2h8a2 2 0 0 0 2 -2l1 -12"/><path d="M9 7v-3a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v3"/>',
|
||||
// tabler: menu-2
|
||||
menu: '<path d="M4 6h16"/><path d="M4 12h16"/><path d="M4 18h16"/>',
|
||||
// tabler: search
|
||||
search: '<path d="M3 10a7 7 0 1 0 14 0a7 7 0 1 0 -14 0"/><path d="M21 21l-6 -6"/>',
|
||||
// tabler: users
|
||||
users: '<path d="M5 7a4 4 0 1 0 8 0a4 4 0 1 0 -8 0"/><path d="M3 21v-2a4 4 0 0 1 4 -4h4a4 4 0 0 1 4 4v2"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/><path d="M21 21v-2a4 4 0 0 0 -3 -3.85"/>',
|
||||
// tabler: license
|
||||
license: '<path d="M15 21h-9a3 3 0 0 1 -3 -3v-1h10v2a2 2 0 0 0 4 0v-14a2 2 0 1 1 2 2h-2m2 -4h-11a3 3 0 0 0 -3 3v11"/><path d="M9 7l4 0"/><path d="M9 11l4 0"/>',
|
||||
// tabler: world
|
||||
globe: '<path d="M3 12a9 9 0 1 0 18 0a9 9 0 0 0 -18 0"/><path d="M3.6 9h16.8"/><path d="M3.6 15h16.8"/><path d="M11.5 3a17 17 0 0 0 0 18"/><path d="M12.5 3a17 17 0 0 1 0 18"/>',
|
||||
// tabler: logout
|
||||
logout: '<path d="M14 8v-2a2 2 0 0 0 -2 -2h-7a2 2 0 0 0 -2 2v12a2 2 0 0 0 2 2h7a2 2 0 0 0 2 -2v-2"/><path d="M9 12h12l-3 -3"/><path d="M18 15l3 -3"/>',
|
||||
};
|
||||
|
||||
function svg(p, w) {
|
||||
return `<svg viewBox="0 0 24 24" width="${w || 16}" height="${w || 16}" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${p}</svg>`;
|
||||
}
|
||||
|
||||
/* ── theme ──────────────────────────────────────────────────────────────── */
|
||||
const TH = { system: ICN.desktop, light: ICN.sun, dark: ICN.moon };
|
||||
|
||||
function themeMode() {
|
||||
try { return localStorage.getItem('agora_theme') || 'system'; } catch { return 'system'; }
|
||||
}
|
||||
function applyTheme(m) {
|
||||
const dark = m === 'dark' || (m === 'system' && matchMedia('(prefers-color-scheme:dark)').matches);
|
||||
document.documentElement.dataset.theme = dark ? 'dark' : 'light';
|
||||
document.querySelectorAll('.js-theme').forEach((b) => { b.innerHTML = svg(TH[m] || TH.system); });
|
||||
}
|
||||
function cycleTheme() {
|
||||
const next = { system: 'light', light: 'dark', dark: 'system' }[themeMode()] || 'system';
|
||||
try { localStorage.setItem('agora_theme', next); } catch { /* private mode */ }
|
||||
applyTheme(next);
|
||||
}
|
||||
/* "System" has to keep following the OS after load, not just at first paint: switching the OS to
|
||||
dark (or an automatic sunset switch) must repaint an open tab without a reload. */
|
||||
(function followOsTheme() {
|
||||
const mq = window.matchMedia && window.matchMedia('(prefers-color-scheme:dark)');
|
||||
const onChange = () => { if (themeMode() === 'system') applyTheme('system'); };
|
||||
// Guarded: at top level, a missing API would stop the whole file parsing past this point.
|
||||
if (mq && mq.addEventListener) mq.addEventListener('change', onChange);
|
||||
else if (mq && mq.addListener) mq.addListener(onChange); // Safari < 14
|
||||
})();
|
||||
|
||||
/* ── i18n ───────────────────────────────────────────────────────────────── */
|
||||
const SRC_LANG = 'pl';
|
||||
const ALT_LANG = 'en';
|
||||
|
||||
const I18N = {
|
||||
'System zarządzania': 'Management console',
|
||||
'Zaloguj się': 'Sign in',
|
||||
'Wyloguj się': 'Sign out',
|
||||
'Jedno konto obejmuje tu wszystko.': 'One account covers everything here.',
|
||||
'Zaloguj się raz, a to otworzy się bez drugiego hasła.': 'Sign in once, and this opens without a second password.',
|
||||
'Osobami i hasłami zarządza się w jednym miejscu dla całej platformy.': 'People and passwords are managed in one place for the whole platform.',
|
||||
'Dodanie kogoś, zmiana nazwy, reset hasła czy wyłączenie konta dzieją się tam — i obowiązują od razu wszędzie.': 'Add someone, rename them, reset a password or switch them off there — it applies everywhere at once.',
|
||||
'Tu ustawiasz tylko to, co dana osoba widzi w tym module.': 'What you set here is what they may see inside this module.',
|
||||
'Rola': 'Role',
|
||||
'E-mail': 'Email',
|
||||
'Hasło': 'Password',
|
||||
'Pokaż hasło': 'Show password',
|
||||
'Motyw': 'Theme',
|
||||
'Język': 'Language',
|
||||
'Konto': 'Account',
|
||||
'Szukaj…': 'Search…',
|
||||
'Motyw: systemowy': 'Theme: system',
|
||||
'Motyw: jasny': 'Theme: light',
|
||||
'Motyw: ciemny': 'Theme: dark',
|
||||
'Język: polski': 'Language: Polish',
|
||||
'Język: angielski': 'Language: English',
|
||||
'Pulpit': 'Dashboard',
|
||||
'Rekordy': 'Records',
|
||||
'Administracja': 'Administration',
|
||||
'Użytkownicy': 'Users',
|
||||
'Przestrzenie': 'Workspaces',
|
||||
'Nowy rekord': 'New record',
|
||||
'Nazwa': 'Name',
|
||||
'Notatka': 'Note',
|
||||
'Utworzono': 'Created',
|
||||
'Zapisz': 'Save',
|
||||
'Anuluj': 'Cancel',
|
||||
'Usuń': 'Delete',
|
||||
'Edytuj': 'Edit',
|
||||
'Wczytywanie…': 'Loading…',
|
||||
'Brak wyników': 'Nothing found',
|
||||
'Brak rekordów.': 'No records yet.',
|
||||
'Nie znaleziono strony.': 'Page not found.',
|
||||
'otwarty': 'open',
|
||||
'zamknięty': 'done',
|
||||
'Wszystkich': 'Total',
|
||||
'Zapisano.': 'Saved.',
|
||||
'Tej operacji nie da się cofnąć.': 'This cannot be undone.',
|
||||
};
|
||||
|
||||
let LANG = (function () {
|
||||
try {
|
||||
const s = localStorage.getItem('agora_lang');
|
||||
if (s === SRC_LANG || s === ALT_LANG) return s;
|
||||
} catch { /* private mode */ }
|
||||
return (navigator.language || SRC_LANG).toLowerCase().startsWith(SRC_LANG) ? SRC_LANG : ALT_LANG;
|
||||
})();
|
||||
|
||||
const _origAttr = new WeakMap();
|
||||
|
||||
function _tr(s) {
|
||||
if (LANG === SRC_LANG || s == null) return s;
|
||||
const k = String(s).trim();
|
||||
if (!k) return s;
|
||||
const v = I18N[k];
|
||||
return v ? String(s).replace(k, v) : s;
|
||||
}
|
||||
function _trAttr(el, attr) {
|
||||
const cur = el.getAttribute && el.getAttribute(attr);
|
||||
if (cur == null) return;
|
||||
let orig = _origAttr.get(el);
|
||||
if (!orig) { orig = {}; _origAttr.set(el, orig); }
|
||||
if (orig[attr] === undefined) orig[attr] = cur;
|
||||
el.setAttribute(attr, _tr(orig[attr]));
|
||||
}
|
||||
/* Translations set nodeValue / setAttribute, never innerHTML — so esc() still holds and a
|
||||
dictionary entry can never inject markup. */
|
||||
function localize(root) {
|
||||
if (LANG === SRC_LANG || !root) return;
|
||||
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
|
||||
const nodes = [];
|
||||
while (walker.nextNode()) nodes.push(walker.currentNode);
|
||||
nodes.forEach((n) => {
|
||||
if (n.parentElement && n.parentElement.closest('[data-no-i18n]')) return;
|
||||
const t = _tr(n.nodeValue);
|
||||
if (t !== n.nodeValue) n.nodeValue = t;
|
||||
});
|
||||
root.querySelectorAll('[title],[placeholder],[data-label],[aria-label]').forEach((el) => {
|
||||
if (el.closest('[data-no-i18n]')) return;
|
||||
_trAttr(el, 'title');
|
||||
_trAttr(el, 'placeholder');
|
||||
_trAttr(el, 'data-label');
|
||||
_trAttr(el, 'aria-label');
|
||||
});
|
||||
}
|
||||
function cycleLang() {
|
||||
LANG = LANG === SRC_LANG ? ALT_LANG : SRC_LANG;
|
||||
try { localStorage.setItem('agora_lang', LANG); } catch { /* private mode */ }
|
||||
location.reload();
|
||||
}
|
||||
|
||||
/* ── auth ─────────────────────────────────────────────────────────────────
|
||||
Two shapes, chosen by the server and never guessed. STANDALONE, this app owns its accounts and
|
||||
the form in index.html is the whole of signing in. As a MODULE of the platform, the hub owns
|
||||
every account: there is no password here, one origin means the hub's cookie already arrives on
|
||||
every request to this module, and "sign in" is therefore a link rather than a form. `/meta` says
|
||||
which — unauthenticated, which is the only way to ask before anybody is signed in. */
|
||||
async function loadMeta() {
|
||||
/* Fetched once per page load and cached: it is unauthenticated, it cannot change under a running
|
||||
console, and both the sign-in card and the Administration screen need the same answer. Never
|
||||
fatal — an older server has no `local_login` key, and a wholly unreachable one is about to
|
||||
produce a much louder error than a missing sign-in card. The default is the form, which is
|
||||
what every app of this family did before the platform existed. */
|
||||
if (state.meta) return state.meta;
|
||||
try { state.meta = await api('GET', '/meta'); } catch { state.meta = null; }
|
||||
return state.meta;
|
||||
}
|
||||
function hubMode() { return !!(state.meta && state.meta.local_login === false); }
|
||||
|
||||
function showLogin() {
|
||||
const hub = hubMode();
|
||||
$('loginForm').classList.toggle('hidden', hub);
|
||||
$('hubCard').classList.toggle('hidden', !hub);
|
||||
if (hub) {
|
||||
const url = (state.meta && state.meta.sign_in_url) || '';
|
||||
const a = $('btnHub');
|
||||
/* No address configured is a survivable state, not a broken one: say where accounts live
|
||||
without offering a link that goes nowhere. IDENTITY_HUB_URL is validated server-side as a
|
||||
path or an http(s) URL, so it can never be a javascript: or data: address by the time it
|
||||
reaches here. */
|
||||
if (url) { a.href = url; a.classList.remove('hidden'); }
|
||||
else { a.removeAttribute('href'); a.classList.add('hidden'); }
|
||||
}
|
||||
$('login').classList.remove('hidden'); $('app').classList.add('hidden');
|
||||
}
|
||||
function showApp() { $('login').classList.add('hidden'); $('app').classList.remove('hidden'); }
|
||||
|
||||
async function doLogin(e) {
|
||||
if (e) e.preventDefault();
|
||||
const err = $('loginErr');
|
||||
err.classList.add('hidden');
|
||||
try {
|
||||
const r = await api('POST', '/auth/login', {
|
||||
email: $('email').value, password: $('password').value,
|
||||
});
|
||||
state.token = r.token;
|
||||
state.user = r.user;
|
||||
await afterLogin();
|
||||
} catch (ex) {
|
||||
err.textContent = ex.message;
|
||||
err.classList.remove('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
async function doLogout() {
|
||||
try { await api('POST', '/auth/logout'); } catch { /* already gone */ }
|
||||
state.token = '';
|
||||
state.user = null;
|
||||
showLogin();
|
||||
}
|
||||
|
||||
async function restore() {
|
||||
try {
|
||||
state.user = await api('GET', '/auth/me');
|
||||
await afterLogin();
|
||||
} catch {
|
||||
/* Only now does it matter what kind of sign-in this server has, so only now is it asked for —
|
||||
a signed-in visitor never pays for the call. */
|
||||
await loadMeta();
|
||||
showLogin();
|
||||
}
|
||||
}
|
||||
|
||||
async function afterLogin() {
|
||||
await loadMeta();
|
||||
showApp();
|
||||
applyTheme(themeMode());
|
||||
document.querySelectorAll('#aLang,#btnLangLogin').forEach((b) => {
|
||||
b.textContent = LANG.toUpperCase();
|
||||
});
|
||||
$('aUser').textContent = initials(state.user.full_name || state.user.email);
|
||||
try { state.users = await api('GET', '/users'); } catch { state.users = []; }
|
||||
try { state.config = await api('GET', '/config'); } catch { state.config = {}; }
|
||||
if (TENANCY === 'nodes') {
|
||||
try { state.containers = await api('GET', '/tree/containers'); } catch { state.containers = []; }
|
||||
}
|
||||
if (!location.hash || location.hash === '#') location.hash = '#/';
|
||||
await router();
|
||||
}
|
||||
|
||||
/* May this person administer THIS module — a platform ADMINISTRATOR, or a MODERATOR of it. The
|
||||
server resolves both tiers into this one boolean (`/auth/me`), so no screen ever decides what it
|
||||
may do from `is_admin`: on a platform that flag is the hub's business, and a moderator who saw no
|
||||
Administration menu would have been given a tier they cannot use. Standalone the two are the same
|
||||
thing. (The Users table still *displays* `is_admin`, which is the one honest use of it — telling
|
||||
an Administrator chip from a Moderator one.) */
|
||||
const isModerator = () => !!(state.user && state.user.is_moderator);
|
||||
|
||||
/* ── navigation ─────────────────────────────────────────────────────────── */
|
||||
const NAV = [
|
||||
{ hash: '#/', icon: 'dashboard', label: 'Pulpit' },
|
||||
{ hash: '#/records', icon: 'file', label: 'Rekordy' },
|
||||
];
|
||||
|
||||
function renderNav(counts) {
|
||||
counts = counts || {};
|
||||
const cur = location.hash || '#/';
|
||||
$('nav').innerHTML = NAV.map((n) => {
|
||||
const on = cur === n.hash || (n.hash !== '#/' && cur.startsWith(n.hash));
|
||||
const c = counts[n.badge];
|
||||
const badge = c ? `<span class="cnt">${esc(String(c))}</span>` : '';
|
||||
return `<a class="nav-item ${on ? 'on' : ''}" href="${n.hash}">${svg(ICN[n.icon])}<span>${esc(n.label)}</span>${badge}</a>`;
|
||||
}).join('');
|
||||
$('navAdmin').innerHTML = isModerator()
|
||||
? `<a class="nav-item ${cur.startsWith('#/admin') ? 'on' : ''}" href="#/admin">${svg(ICN.settings)}<span>Administracja</span></a>`
|
||||
: '';
|
||||
localize($('sidebar'));
|
||||
}
|
||||
|
||||
function setCrumb(parts) {
|
||||
$('crumb').innerHTML = parts.map((p, i) => {
|
||||
const sep = i ? '<span class="sep">/</span>' : '';
|
||||
const last = i === parts.length - 1;
|
||||
return sep + (p.href && !last
|
||||
? `<a href="${esc(p.href)}">${esc(p.label)}</a>`
|
||||
: `<b>${esc(p.label)}</b>`);
|
||||
}).join(' ');
|
||||
}
|
||||
|
||||
function pageHead(title, sub, actions) {
|
||||
return `<div class="page-head"><div><h2>${esc(title)}</h2>${sub ? `<div class="sub">${esc(sub)}</div>` : ''}</div>${actions ? `<div class="acts">${actions}</div>` : ''}</div>`;
|
||||
}
|
||||
|
||||
function field(label, value) {
|
||||
return `<div><div class="tiny faint">${esc(label)}</div><div>${value == null || value === '' ? '—' : esc(String(value))}</div></div>`;
|
||||
}
|
||||
|
||||
function parseHash() {
|
||||
const h = (location.hash || '#/').replace(/^#\/?/, '');
|
||||
const [path, qs] = h.split('?');
|
||||
const q = {};
|
||||
(qs || '').split('&').forEach((kv) => {
|
||||
const [k, v] = kv.split('=');
|
||||
if (k) q[decodeURIComponent(k)] = decodeURIComponent(v || '');
|
||||
});
|
||||
return { seg: path.split('/').filter(Boolean), q };
|
||||
}
|
||||
|
||||
async function router() {
|
||||
if (!state.user) return;
|
||||
const C = $('content');
|
||||
const { seg, q } = parseHash();
|
||||
C.innerHTML = '<div class="faint">Wczytywanie…</div>';
|
||||
try {
|
||||
if (!seg.length) await viewDashboard(C);
|
||||
else if (seg[0] === 'records' && seg[1]) await viewRecord(C, seg[1]);
|
||||
else if (seg[0] === 'records') await viewRecords(C, q);
|
||||
else if (seg[0] === 'admin') await viewAdmin(C);
|
||||
else C.innerHTML = '<div class="empty">Nie znaleziono strony.</div>';
|
||||
} catch (ex) {
|
||||
if (ex.status === 401) { showLogin(); return; }
|
||||
C.innerHTML = `<div class="banner err">${esc(ex.message)}</div>`;
|
||||
}
|
||||
localize(C);
|
||||
renderNav(state.counts);
|
||||
closeDrawer();
|
||||
}
|
||||
|
||||
/* ── dashboard ──────────────────────────────────────────────────────────── */
|
||||
async function viewDashboard(C) {
|
||||
const d = await api('GET', '/dashboard');
|
||||
const c = d.cards || {};
|
||||
state.counts = { records: c.total };
|
||||
setCrumb([{ label: 'Pulpit' }]);
|
||||
|
||||
const tiles = [
|
||||
{ k: 'Wszystkich', v: c.total ?? 0, cls: '' },
|
||||
{ k: 'otwarty', v: c.open ?? 0, cls: '' },
|
||||
{ k: 'zamknięty', v: c.done ?? 0, cls: '' },
|
||||
];
|
||||
|
||||
C.innerHTML = pageHead('Pulpit', state.user.full_name || state.user.email,
|
||||
`<button class="btn primary" onclick="openRecordNew()">${svg(ICN.plus)}Nowy rekord</button>`)
|
||||
+ `<div class="tiles">${tiles.map((t) => `<div class="tile ${t.cls}"><div class="k">${esc(t.k)}</div><div class="v">${esc(String(t.v))}</div></div>`).join('')}</div>`
|
||||
+ `<div class="card" style="margin-top:14px"><h3>Rekordy<span class="n">${(d.recent || []).length}</span></h3>${recordTable(d.recent || [])}</div>`;
|
||||
}
|
||||
|
||||
function statusChip(s) {
|
||||
const cls = s === 'done' ? 'ok' : '';
|
||||
const label = s === 'done' ? 'zamknięty' : 'otwarty';
|
||||
return `<span class="chip ${cls}">${esc(label)}</span>`;
|
||||
}
|
||||
|
||||
function recordTable(rows) {
|
||||
if (!rows.length) return '<div class="empty">Brak rekordów.</div>';
|
||||
return `<div class="tablewrap"><table class="rt"><thead><tr>
|
||||
<th>Nazwa</th><th>Status</th><th>Utworzono</th>
|
||||
</tr></thead><tbody>${rows.map((r) => `<tr class="click" onclick="location.hash='#/records/${encodeURIComponent(r.id)}'">
|
||||
<td><div>${esc(r.name)}${r.note ? `<div class="faint tiny">${esc(r.note)}</div>` : ''}</div></td>
|
||||
<td${lbl('Status')}>${statusChip(r.status)}</td>
|
||||
<td class="faint tiny"${lbl('Utworzono')}>${fmtDate(r.created_at)}</td>
|
||||
</tr>`).join('')}</tbody></table></div>`;
|
||||
}
|
||||
|
||||
/* ── records ────────────────────────────────────────────────────────────── */
|
||||
async function viewRecords(C, q) {
|
||||
const params = new URLSearchParams();
|
||||
if (q.q) params.set('q', q.q);
|
||||
if (q.status) params.set('status', q.status);
|
||||
const rows = await api('GET', '/records' + (params.toString() ? '?' + params : ''));
|
||||
setCrumb([{ label: 'Rekordy' }]);
|
||||
|
||||
C.innerHTML = pageHead('Rekordy', rows.length + '',
|
||||
`<button class="btn primary" onclick="openRecordNew()">${svg(ICN.plus)}Nowy rekord</button>`)
|
||||
+ `<div class="toolbar">
|
||||
<input type="search" id="rq" placeholder="Szukaj…" value="${esc(q.q || '')}" />
|
||||
<select id="rstatus">
|
||||
${['', 'open', 'done'].map((s) => `<option value="${s}" ${q.status === s ? 'selected' : ''}>${s ? (s === 'done' ? 'zamknięty' : 'otwarty') : '—'}</option>`).join('')}
|
||||
</select>
|
||||
</div>`
|
||||
+ (rows.length ? `<div class="card">${recordTable(rows)}</div>` : '<div class="empty">Brak rekordów.</div>');
|
||||
|
||||
const go = () => {
|
||||
const p = new URLSearchParams();
|
||||
if ($('rq').value.trim()) p.set('q', $('rq').value.trim());
|
||||
if ($('rstatus').value) p.set('status', $('rstatus').value);
|
||||
location.hash = '#/records' + (p.toString() ? '?' + p : '');
|
||||
};
|
||||
$('rq').addEventListener('change', go);
|
||||
$('rstatus').addEventListener('change', go);
|
||||
}
|
||||
|
||||
async function viewRecord(C, id) {
|
||||
const r = await api('GET', '/records/' + encodeURIComponent(id));
|
||||
setCrumb([{ label: 'Rekordy', href: '#/records' }, { label: r.name }]);
|
||||
|
||||
const canDelete = TENANCY !== 'nodes' || r.role === 'manager';
|
||||
C.innerHTML = pageHead(r.name, r.path || '',
|
||||
`<button class="btn" onclick="openRecordEdit('${esc(r.id)}')">${svg(ICN.check)}Edytuj</button>`
|
||||
+ (canDelete ? `<button class="btn danger" onclick="deleteRecord('${esc(r.id)}')">${svg(ICN.trash)}Usuń</button>` : ''))
|
||||
+ `<div class="card"><div class="grid3">
|
||||
${field('Status', r.status === 'done' ? 'zamknięty' : 'otwarty')}
|
||||
${field('Utworzono', fmtDateTime(r.created_at))}
|
||||
</div>
|
||||
${r.note ? `<div style="margin-top:14px"><div class="tiny faint">Notatka</div><div>${esc(r.note)}</div></div>` : ''}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function containerOptions(selected) {
|
||||
return state.containers.map((n) =>
|
||||
`<option value="${esc(n.id)}" ${n.id === selected ? 'selected' : ''}>${esc(n.path)}</option>`).join('');
|
||||
}
|
||||
|
||||
function openRecordNew() {
|
||||
const where = TENANCY === 'nodes'
|
||||
? `<label class="field" style="margin-top:12px">Przestrzenie
|
||||
<select id="rcParent">${containerOptions()}</select></label>`
|
||||
: '';
|
||||
modal('Nowy rekord', '',
|
||||
`<label class="field">Nazwa<input id="rcName" /></label>
|
||||
<label class="field" style="margin-top:12px">Notatka<textarea id="rcNote"></textarea></label>
|
||||
${where}`,
|
||||
`<button class="btn" onclick="closeModal()">Anuluj</button>
|
||||
<button class="btn primary" onclick="saveRecordNew()">Zapisz</button>`);
|
||||
}
|
||||
|
||||
function saveRecordNew() {
|
||||
guard(async () => {
|
||||
const body = { name: $('rcName').value, note: $('rcNote').value || null };
|
||||
if (TENANCY === 'nodes') body.parent_id = $('rcParent') ? $('rcParent').value : null;
|
||||
const r = await api('POST', '/records', body);
|
||||
closeModal();
|
||||
toast('Zapisano.');
|
||||
location.hash = '#/records/' + encodeURIComponent(r.id);
|
||||
await router();
|
||||
});
|
||||
}
|
||||
|
||||
function openRecordEdit(id) {
|
||||
guard(async () => {
|
||||
const r = await api('GET', '/records/' + encodeURIComponent(id));
|
||||
modal('Edytuj', r.name,
|
||||
`<label class="field">Nazwa<input id="reName" value="${esc(r.name)}" /></label>
|
||||
<label class="field" style="margin-top:12px">Notatka<textarea id="reNote">${esc(r.note || '')}</textarea></label>
|
||||
<label class="field" style="margin-top:12px">Status
|
||||
<select id="reStatus">
|
||||
<option value="open" ${r.status === 'open' ? 'selected' : ''}>otwarty</option>
|
||||
<option value="done" ${r.status === 'done' ? 'selected' : ''}>zamknięty</option>
|
||||
</select></label>`,
|
||||
`<button class="btn" onclick="closeModal()">Anuluj</button>
|
||||
<button class="btn primary" onclick="saveRecordEdit('${esc(id)}')">Zapisz</button>`);
|
||||
});
|
||||
}
|
||||
|
||||
function saveRecordEdit(id) {
|
||||
guard(async () => {
|
||||
await api('PATCH', '/records/' + encodeURIComponent(id), {
|
||||
name: $('reName').value,
|
||||
note: $('reNote').value,
|
||||
status: $('reStatus').value,
|
||||
});
|
||||
closeModal();
|
||||
toast('Zapisano.');
|
||||
await router();
|
||||
});
|
||||
}
|
||||
|
||||
function deleteRecord(id) {
|
||||
modal('Usuń', '',
|
||||
'<div class="banner warn">Tej operacji nie da się cofnąć.</div>',
|
||||
`<button class="btn" onclick="closeModal()">Anuluj</button>
|
||||
<button class="btn danger" onclick="confirmDeleteRecord('${esc(id)}')">Usuń</button>`);
|
||||
}
|
||||
|
||||
function confirmDeleteRecord(id) {
|
||||
guard(async () => {
|
||||
await api('DELETE', '/records/' + encodeURIComponent(id));
|
||||
closeModal();
|
||||
toast('Zapisano.');
|
||||
location.hash = '#/records';
|
||||
await router();
|
||||
});
|
||||
}
|
||||
|
||||
/* ── administration ─────────────────────────────────────────────────────── */
|
||||
async function viewAdmin(C) {
|
||||
setCrumb([{ label: 'Administracja' }]);
|
||||
const audit = await api('GET', '/admin/audit?limit=50').catch(() => []);
|
||||
|
||||
/* Who owns accounts decides what this card offers. Standalone, everything: create, edit, set a
|
||||
password, deactivate. On the platform the hub owns them and this app's database role cannot
|
||||
write one, so the button goes rather than being left to produce a 409 — and the card says where
|
||||
it went, which is more use than a disabled control. */
|
||||
const hub = hubMode();
|
||||
/* Two tiers, two chips, the owner's own words. ADMINISTRATOR is platform-wide; MODERATOR is this
|
||||
module only. Standalone they coincide and only the first is ever shown. */
|
||||
const role = (u) => (u.is_admin ? '<span class="chip">Administrator</span>'
|
||||
: u.is_moderator ? '<span class="chip">Moderator</span>' : '');
|
||||
|
||||
C.innerHTML = pageHead('Administracja', '',
|
||||
hub ? '' : `<button class="btn primary" onclick="openUserNew()">${svg(ICN.plus)}Użytkownicy</button>`)
|
||||
+ `<div class="card"><h3>Użytkownicy<span class="n">${state.users.length}</span></h3>
|
||||
<div class="tablewrap"><table class="rt"><thead><tr>
|
||||
<th>Nazwa</th><th>E-mail</th><th>Rola</th><th>Status</th>
|
||||
</tr></thead><tbody>${state.users.map((u) => `<tr>
|
||||
<td>${esc(u.full_name)}</td>
|
||||
<td class="mono wrap"${lbl('E-mail')}>${esc(u.email)}</td>
|
||||
<td${lbl('Rola')}>${role(u)}</td>
|
||||
<td${lbl('Status')}><div class="row">${u.is_active ? '<span class="chip ok">active</span>' : '<span class="chip err">inactive</span>'}</div></td>
|
||||
</tr>`).join('')}</tbody></table></div>
|
||||
${hub ? `<div class="faint tiny" style="padding:10px 2px 2px">
|
||||
<span>Osobami i hasłami zarządza się w jednym miejscu dla całej platformy.</span>
|
||||
<span>Dodanie kogoś, zmiana nazwy, reset hasła czy wyłączenie konta dzieją się tam — i obowiązują od razu wszędzie.</span>
|
||||
<span>Tu ustawiasz tylko to, co dana osoba widzi w tym module.</span></div>` : ''}</div>`
|
||||
+ `<div class="card"><h3>Audit<span class="n">${audit.length}</span></h3>
|
||||
${audit.length ? `<div class="tablewrap"><table class="rt"><thead><tr>
|
||||
<th>Utworzono</th><th>Action</th><th>Entity</th><th>Result</th>
|
||||
</tr></thead><tbody>${audit.map((a) => `<tr>
|
||||
<td class="faint tiny">${fmtDateTime(a.created_at)}</td>
|
||||
<td class="mono wrap"${lbl('Action')}>${esc(a.action)}</td>
|
||||
<td class="tiny wrap"${lbl('Entity')}><div>${esc(a.entity_type)}${a.detail ? `<div class="faint">${esc(a.detail)}</div>` : ''}</div></td>
|
||||
<td${lbl('Result')}>${a.result === 'ok' ? '<span class="chip ok">ok</span>' : `<span class="chip err">${esc(a.result || '')}</span>`}</td>
|
||||
</tr>`).join('')}</tbody></table></div>` : '<div class="empty">—</div>'}</div>`;
|
||||
}
|
||||
|
||||
function openUserNew() {
|
||||
modal('Użytkownicy', '',
|
||||
`<label class="field">Nazwa<input id="unName" /></label>
|
||||
<label class="field" style="margin-top:12px">E-mail<input id="unEmail" type="email" /></label>
|
||||
<label class="field" style="margin-top:12px">Hasło<input id="unPass" type="password" /></label>`,
|
||||
`<button class="btn" onclick="closeModal()">Anuluj</button>
|
||||
<button class="btn primary" onclick="saveUserNew()">Zapisz</button>`);
|
||||
}
|
||||
|
||||
function saveUserNew() {
|
||||
guard(async () => {
|
||||
await api('POST', '/users', {
|
||||
full_name: $('unName').value,
|
||||
email: $('unEmail').value,
|
||||
password: $('unPass').value,
|
||||
});
|
||||
closeModal();
|
||||
state.users = await api('GET', '/users');
|
||||
toast('Zapisano.');
|
||||
await router();
|
||||
});
|
||||
}
|
||||
|
||||
/* ── modal ──────────────────────────────────────────────────────────────── */
|
||||
let _modalOpener = null;
|
||||
function closeModal() {
|
||||
const wasOpen = !!$('modalRoot').innerHTML;
|
||||
$('modalRoot').innerHTML = '';
|
||||
// Give focus back to whatever opened the dialog, rather than dropping it onto <body>.
|
||||
if (wasOpen && _modalOpener && document.contains(_modalOpener)) _modalOpener.focus();
|
||||
_modalOpener = null;
|
||||
}
|
||||
|
||||
function modal(title, sub, bodyHtml, actionsHtml, opts) {
|
||||
$('modalRoot').innerHTML = `<div class="scrim" onclick="if(event.target===this)closeModal()">
|
||||
<div class="modal ${opts && opts.wide ? 'wide' : ''}" role="dialog" aria-modal="true">
|
||||
<h3>${esc(title)}</h3>${sub ? `<div class="msub">${esc(sub)}</div>` : ''}
|
||||
<div id="modalBody">${bodyHtml}</div>
|
||||
<div class="acts">${actionsHtml}</div>
|
||||
</div></div>`;
|
||||
localize($('modalRoot'));
|
||||
if (!_modalOpener && document.activeElement && document.activeElement !== document.body
|
||||
&& !$('modalRoot').contains(document.activeElement)) _modalOpener = document.activeElement;
|
||||
// A field if there is one; otherwise the dialog's first control, so a keyboard user starts inside.
|
||||
const first = $('modalRoot').querySelector('input:not([type=hidden]),select,textarea')
|
||||
|| $('modalRoot').querySelector('.modal button, .modal a[href]');
|
||||
if (first) first.focus();
|
||||
}
|
||||
|
||||
function modalError(msg) {
|
||||
const b = $('modalBody');
|
||||
if (!b) { toast(msg); return; }
|
||||
let el = b.querySelector('.banner.err');
|
||||
if (!el) {
|
||||
el = document.createElement('div');
|
||||
el.className = 'banner err';
|
||||
el.style.marginBottom = '12px';
|
||||
b.prepend(el);
|
||||
}
|
||||
el.textContent = msg;
|
||||
}
|
||||
|
||||
/* Run an async handler and put its error where the user is looking — inside the dialog, not in
|
||||
a console they will never open. */
|
||||
function guard(fn) {
|
||||
return Promise.resolve().then(fn).catch((ex) => {
|
||||
if (ex && ex.status === 401) { showLogin(); return; }
|
||||
modalError(ex.message || String(ex));
|
||||
});
|
||||
}
|
||||
|
||||
/* ── command palette ────────────────────────────────────────────────────── */
|
||||
function openSearch() {
|
||||
modal('', '', '', '');
|
||||
$('modalRoot').innerHTML = `<div class="scrim search-scrim" onclick="if(event.target===this)closeModal()">
|
||||
<div class="search-modal" role="dialog" aria-modal="true">
|
||||
<div class="sin">${svg(ICN.search, 18)}<input id="sq" placeholder="Szukaj…" autocomplete="off" /></div>
|
||||
<div class="search-results" id="sres"></div>
|
||||
<div class="shint">Esc</div>
|
||||
</div></div>`;
|
||||
const input = $('sq');
|
||||
input.focus();
|
||||
let timer = null;
|
||||
const run = async () => {
|
||||
const q = input.value.trim();
|
||||
if (!q) { $('sres').innerHTML = ''; return; }
|
||||
try {
|
||||
const rows = await api('GET', '/records?q=' + encodeURIComponent(q));
|
||||
$('sres').innerHTML = rows.length
|
||||
? `<div class="sgroup">Rekordy</div>` + rows.slice(0, 12).map((r) =>
|
||||
`<button class="sitem" onclick="closeModal();location.hash='#/records/${encodeURIComponent(r.id)}'">
|
||||
<span class="ic">${svg(ICN.file)}</span>
|
||||
<span class="sb"><span class="st">${esc(r.name)}</span>
|
||||
<span class="ss">${esc(r.note || '')}</span></span></button>`).join('')
|
||||
: '<div class="search-empty">Brak wyników</div>';
|
||||
localize($('sres'));
|
||||
} catch { $('sres').innerHTML = ''; }
|
||||
};
|
||||
input.addEventListener('input', () => { clearTimeout(timer); timer = setTimeout(run, 180); });
|
||||
}
|
||||
|
||||
/* ── account sheet ──────────────────────────────────────────────────────── */
|
||||
/* On a phone the top bar drops search, theme and language (`.js-tool`) to leave room for the
|
||||
breadcrumb — so they live here too (`.m-only`), or a phone user could never reach them. */
|
||||
const THEME_LABEL = { system: 'Motyw: systemowy', light: 'Motyw: jasny', dark: 'Motyw: ciemny' };
|
||||
|
||||
function openAccount() {
|
||||
const mode = themeMode();
|
||||
const row = (icon, label, action, cls) =>
|
||||
`<button class="appcard ${cls || ''}" onclick="${action}"><span class="ai">${svg(icon)}</span><span class="an">${esc(label)}</span></button>`;
|
||||
modal(state.user ? (state.user.full_name || state.user.email) : '', state.user ? state.user.email : '',
|
||||
'<div class="applist">'
|
||||
+ row(ICN.search, 'Szukaj…', 'closeModal();openSearch()', 'm-only')
|
||||
+ row(TH[mode] || TH.system, THEME_LABEL[mode] || THEME_LABEL.system, 'cycleTheme();openAccount()', 'm-only')
|
||||
+ row(ICN.globe, LANG === 'pl' ? 'Język: polski' : 'Język: angielski', 'cycleLang()', 'm-only')
|
||||
+ row(ICN.logout, 'Wyloguj się', 'closeModal();doLogout()')
|
||||
+ '</div>',
|
||||
`<button class="btn" onclick="closeModal()">Anuluj</button>`);
|
||||
}
|
||||
|
||||
/* ── mobile drawer ──────────────────────────────────────────────────────── */
|
||||
function openDrawer() {
|
||||
$('sidebar').classList.add('open');
|
||||
$('navScrim').classList.add('on');
|
||||
}
|
||||
function closeDrawer() {
|
||||
$('sidebar').classList.remove('open');
|
||||
$('navScrim').classList.remove('on');
|
||||
}
|
||||
|
||||
/* ── boot ───────────────────────────────────────────────────────────────── */
|
||||
function togglePassword(inputId, btn) {
|
||||
const el = $(inputId);
|
||||
if (!el) return;
|
||||
const show = el.type === 'password';
|
||||
el.type = show ? 'text' : 'password';
|
||||
btn.innerHTML = svg(show ? ICN.eyeoff : ICN.eye);
|
||||
}
|
||||
|
||||
window.addEventListener('DOMContentLoaded', () => {
|
||||
applyTheme(themeMode());
|
||||
document.querySelectorAll('#aLang,#btnLangLogin').forEach((b) => {
|
||||
b.textContent = LANG.toUpperCase();
|
||||
b.addEventListener('click', cycleLang);
|
||||
});
|
||||
document.querySelectorAll('.js-theme').forEach((b) => b.addEventListener('click', cycleTheme));
|
||||
|
||||
$('loginForm').addEventListener('submit', doLogin);
|
||||
const pwBtn = $('pwToggleLogin');
|
||||
if (pwBtn) {
|
||||
pwBtn.innerHTML = svg(ICN.eye);
|
||||
pwBtn.addEventListener('click', () => togglePassword('password', pwBtn));
|
||||
}
|
||||
|
||||
$('navToggle').innerHTML = svg(ICN.menu, 18);
|
||||
$('navToggle').addEventListener('click', openDrawer);
|
||||
$('navScrim').addEventListener('click', closeDrawer);
|
||||
const searchBtn = $('aSearch');
|
||||
searchBtn.querySelector('.si').innerHTML = svg(ICN.search, 14);
|
||||
searchBtn.addEventListener('click', openSearch);
|
||||
$('aUser').addEventListener('click', openAccount);
|
||||
|
||||
window.addEventListener('hashchange', router);
|
||||
document.addEventListener('keydown', (e) => {
|
||||
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'k') { e.preventDefault(); openSearch(); }
|
||||
if (e.key === 'Escape') closeModal();
|
||||
});
|
||||
|
||||
localize(document.body);
|
||||
restore();
|
||||
});
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><rect x="2" y="2" width="20" height="20" rx="5" fill="#e03131"/><g stroke="#fff5f5" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" fill="none"><path d="M7 12.5l3.2 3.2L17 9"/></g></svg>
|
||||
|
After Width: | Height: | Size: 265 B |
@@ -0,0 +1,96 @@
|
||||
<!doctype html>
|
||||
<html lang="pl">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Agora — System zarządzania</title>
|
||||
<meta name="description" content="A self-hosted management console." />
|
||||
<meta name="robots" content="noindex" />
|
||||
<link rel="icon" type="image/svg+xml" href="favicon.svg" />
|
||||
<script>/* set theme before first paint to avoid a flash */
|
||||
(function(){try{var m=localStorage.getItem('agora_theme')||'system';
|
||||
var dark=m==='dark'||(m==='system'&&window.matchMedia&&matchMedia('(prefers-color-scheme:dark)').matches);
|
||||
document.documentElement.dataset.theme=dark?'dark':'light';}catch(e){}})();</script>
|
||||
<link rel="stylesheet" href="app.css" />
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<!-- Hidden until the console knows which screen this is: ONLY showLogin() reveals it. restore()
|
||||
resolves the session with an awaited GET /auth/me, so a pane that is visible by default paints
|
||||
the sign-in card for a frame on every single load — and on the platform the card it flashes is a
|
||||
password form this app does not even have any more (hubMode() reads state.meta, which loadMeta()
|
||||
only fills after that same await). Nothing is lost by waiting: without the script the form cannot
|
||||
submit anyway. -->
|
||||
<div id="login" class="hidden">
|
||||
<div class="login-tools">
|
||||
<button class="iconbtn txt" id="btnLangLogin" title="Język" data-no-i18n>PL</button>
|
||||
<button class="iconbtn js-theme" id="btnThemeLogin" title="Motyw"></button>
|
||||
</div>
|
||||
<form class="login-card" id="loginForm">
|
||||
<svg class="logo" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><rect x="2" y="2" width="20" height="20" rx="5" fill="#e03131"/><g stroke="#fff5f5" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" fill="none"><path d="M7 12.5l3.2 3.2L17 9"/></g></svg>
|
||||
<h1>Agora</h1>
|
||||
<div class="lsub">System zarządzania</div>
|
||||
<label class="field">E-mail <input id="email" type="email" autocomplete="username" /></label>
|
||||
<label class="field" style="margin-top:12px">Hasło
|
||||
<span class="pw-field">
|
||||
<input id="password" type="password" autocomplete="current-password" />
|
||||
<button type="button" class="pw-eye" id="pwToggleLogin" title="Pokaż hasło" aria-label="Pokaż hasło"></button>
|
||||
</span>
|
||||
</label>
|
||||
<div id="loginErr" class="banner err hidden"></div>
|
||||
<button class="btn primary" id="btnLogin" type="submit">Zaloguj się</button>
|
||||
</form>
|
||||
<!-- Shown INSTEAD of the form when this deployment is a module of the platform: there is no
|
||||
password here, because there is no account here. One origin means the session created at the
|
||||
hub already arrives on every request to this module, so "sign in" is a link, not a form. The
|
||||
href is filled in from /meta's sign_in_url — a configured address, deliberately absolute:
|
||||
every OTHER url in this console is document-relative so that it works at the origin root and
|
||||
under a path prefix alike, but the hub is a different module and deriving its address from
|
||||
ours would bake its slug in here. Hidden, and empty of controls, unless the server says so. -->
|
||||
<div class="login-card hidden" id="hubCard">
|
||||
<svg class="logo" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><rect x="2" y="2" width="20" height="20" rx="5" fill="#e03131"/><g stroke="#fff5f5" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" fill="none"><path d="M7 12.5l3.2 3.2L17 9"/></g></svg>
|
||||
<h1>Agora</h1>
|
||||
<div class="lsub">System zarządzania</div>
|
||||
<p id="hubCopy" style="margin:18px 0 0;font-size:13px;line-height:1.55;color:var(--text-secondary)">
|
||||
<span>Jedno konto obejmuje tu wszystko.</span>
|
||||
<span>Zaloguj się raz, a to otworzy się bez drugiego hasła.</span>
|
||||
</p>
|
||||
<!-- No inline styling: `.login-card .btn` already makes it full-width and centred, exactly as
|
||||
the form's own submit button. An anchor rather than a button because it navigates. -->
|
||||
<a class="btn primary hidden" id="btnHub">Zaloguj się</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="app" class="hidden">
|
||||
<aside class="sidebar" id="sidebar">
|
||||
<div class="brand">
|
||||
<svg class="logo" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><rect x="2" y="2" width="20" height="20" rx="5" fill="#e03131"/><g stroke="#fff5f5" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" fill="none"><path d="M7 12.5l3.2 3.2L17 9"/></g></svg>
|
||||
<span class="nm">Agora</span>
|
||||
</div>
|
||||
<nav class="nav" id="nav"></nav>
|
||||
<div class="nav sidebar-foot"><div class="nav-item" id="navAdmin"></div></div>
|
||||
</aside>
|
||||
<div id="navScrim"></div>
|
||||
<div class="main">
|
||||
<header class="topbar">
|
||||
<button class="iconbtn" id="navToggle" title="Menu"></button>
|
||||
<div class="crumb" id="crumb"></div>
|
||||
<div class="spacer"></div>
|
||||
<button class="searchbar js-tool" id="aSearch" title="Szukaj… (Ctrl+K)">
|
||||
<span class="si"></span><span class="sp">Szukaj…</span><kbd>Ctrl K</kbd>
|
||||
</button>
|
||||
<span class="vdiv js-tool"></span>
|
||||
<button class="iconbtn js-theme js-tool" id="aTheme" title="Motyw"></button>
|
||||
<button class="iconbtn txt js-tool" id="aLang" title="Język" data-no-i18n>PL</button>
|
||||
<button type="button" class="avatar" id="aUser" title="Konto" aria-label="Konto" aria-haspopup="dialog">?</button>
|
||||
</header>
|
||||
<main class="content" id="content"></main>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="modalRoot"></div>
|
||||
<div id="toast"></div>
|
||||
|
||||
<script src="app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user