Panorama's trends live on Atrium's home (GET /home/trends) and 0018 hides its catalogue row. Now the kit drops it: front door MODULES, compose services/networks/volume, init.sh/push.sh/preflight cases, env templates, the submodule, and the seed (existing rows stay, hidden by 0018). The event READER tier stays, empty by default. Runbooks mark it retired. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
50 KiB
CLAUDE.md
Guidance for Claude Code when working in this repository.
What this is
Atrium — the Dredd family's front door: a launcher (the sidebar's Apps), a home page
(Strona główna: search over the modules, the figures,
your pending access requests and, for an administrator, the platform's state), a marketplace of modules (Galena, Sygna, Counsel Scorecard, Insider, Arbiter, …; Workflow/compass was retired 2026-11-14 — revision 0014 drops its catalogue row and module_permission rows; Panorama was taken off the platform in Atrium#53 — its trends are home's GET /home/trends, revision 0018 hides its row) and the
administration that decides who is offered what. 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**, Argon2id auth + server-side cookie sessions, a no-build static console (vanilla JS), Docker Compose (no reverse proxy; the backend is the edge). 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.21.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.
One platform, one account, one admin pane. The family runs at one origin, one module per path
(/atrium, /galena, /sygna, /counsel). A person has ONE identity: they sign in once, in
Atrium, and every module resolves the same session. Modules keep their own schema and their own
least-privilege roles — database isolation is unchanged — but identity is shared, not duplicated.
What a module still owns alone is its domain settings (Galena's storage and encryption, Sygna's
rates, Counsel's scoring). Because there is one origin there is no cross-origin handoff to design:
no signed assertion, no audience binding, no SameSite dance. A design that invents a token handoff
for this topology is over-engineering.
Four admin@example.com rows is a defect, not a design. Any text saying "no cross-app SSO",
"separate logins", or that Atrium "links but never signs you in" is stale — correct it. That model
was inferred by an assistant, never chosen.
Where the work stands. Done, and the default. The one origin, Atrium's 0004_shared_identity
and every module's own cutover revision have landed; the live box has run one account since
2026-10-01. The deploy kit installs one account by default: deploy/init.sh writes
PLATFORM_IDENTITY_SCHEMA=dredd (db.env), IDENTITY_SCHEMA=dredd + SESSION_COOKIE_NAME=dredd_session
in every env/<app>.env, and the shipped-on modules' roles in env/atrium.env's
IDENTITY_READER_ROLES/IDENTITY_MIGRATOR_ROLES; the first push.sh builds it from an empty database
(provision every app → Atrium's 0004 → each module's cutover, each with nothing to move) and refuses
the half-done shapes by name. init.sh --standalone is the explicit opt-out;
deploy/RUNBOOK-one-account.md only converts an existing standalone box. Insider
(deploy/modules/insider, slug/schema insider, subnet 172.30.15.0/24) ship switched off, each under
a Compose profile of its own name (PROFILED in init.sh/push.sh); init.sh --add <module> lists
its roles and turns its profile on (deploy/RUNBOOK-insider.md). Insider's optional OCR worker is a
second profile, ocr.
The one setting the whole thing turns on is IDENTITY_SCHEMA. Empty (the Settings default, and
this repo's own single-app compose stack that CI's compose-smoke runs; the family deploy kit sets it)
is the standalone deployment: Atrium owns its accounts in its own schema and everything below behaves
exactly as it did before. Set, this Atrium is the hub of a platform. Both are the same code, and
keeping them so is a hard rule — if they fork, local development forks from production, which is the
drift the package extraction ended. settings.shares_identity is the one predicate anything
switches on, and GET /config hands it (with hub_slug) to the console for the same reason.
The schema, its owner, the eight USAGE grants and the eight search_path changes are
PROVISIONING, not Alembic. A migrator is NOCREATEROLE and holds no CREATE on the database, and
ALTER ROLE <other> SET search_path needs superuser or CREATEROLE with ADMIN on that role. Only the
platform admin can, via db/managed/provision.sql (--identity-schema / --identity-owner). What
0004 does is the half only the schema's owner can: the tables inside it, the rows, and the
tiers. Neither half can move into the other, which is what makes a missed ordering a named error
rather than a race — and deploy/compose.yaml makes every module's migration wait for Atrium's.
The tiers are re-applied on every migrate, not only by revision: atrium-migrate runs
alembic upgrade head && python -m app.identity_grants && python -m app.seed, and
app/identity_grants.py runs shared_identity_grants_sql (authoritative: REVOKE ALL then grant,
verify, raise) for the roles in IDENTITY_READER_ROLES / IDENTITY_MIGRATOR_ROLES, as the
migrator (refuses an empty MIGRATION_DATABASE_URL or one logging in as DB_APP_ROLE; a missing
listed role refuses by name). So a module joining after Atrium is at head is an env edit plus a
deploy — never a new Atrium revision (0007_compass_joins was that workaround). Standalone it
is a no-op that does not connect. A separate step rather than an env.py hook because env.py
also runs for current/stamp/downgrade/--sql.
The shared model providers (dredd-core 0.15.0, revision 0009). model_provider,
model_provider_policy and model_provider_key live in the identity schema beside
module_permission, under the same rule: the hub writes, modules read. 0009 creates them there
(schema-qualified; standalone in Atrium's own schema), drops the empty local copies a fresh platform's
0001 built (refusing non-empty ones), and applies model_provider_grants_sql; app.identity_grants
re-applies that block on every migrate too. Readers = IDENTITY_READER_ROLES; the key opt-in
(MODEL_PROVIDER_KEY_READER_ROLES, arbiter_app,lexicon_app) and the REFERENCES tier
(MODEL_PROVIDER_MIGRATOR_ROLES, arbiter_migrator) take effect only for roles also in the identity
lists, so a box with Arbiter switched off migrates cleanly. The import door
(import_model_providers, Compass's 0021 moves its rows through it) is a STATE recomputed on every
migrate (import_door_wanted): open only while a joined importer exists, the shared model_provider
is empty and some module still holds a model_provider of its own; dropped otherwise. Never drop it
in a revision — Atrium migrates before Compass in one deploy, so a revision would close it before
Compass used it. MODEL_PROVIDER_SECRET is ONE value in env/atrium.env, env/arbiter.env and env/lexicon.env
(init.sh writes them; --add arbiter/--add lexicon reuse the hub's); the cipher is byte-compatible with Arbiter's
app/provider_keys.py (Argon2id derive_key, salt dredd.model_provider.v1, AES-256-GCM,
v1.<nonce>.<ct>). The administrator writes them on Dostawcy modeli (#/admin/providers, API routers/admin_providers.py). Home asks through these rows only (routers/models.py → services/providers.call_target → offering + api_key): the request names a model id, never an address, and there is no door for modules — a module that calls a model reads the provider (and, opted in, its key) itself.
Personal keys (dredd-core 0.18.0, revision 0010). model_provider.key_mode says whose key a call carries: firm (the administrator's, model_provider_key), user (the caller's own, model_provider_user_key — the hub's alone, no module tier, not even the key opt-in) or none. 0010 runs core's three idempotent steps in order (model_provider_key_mode_sql, create_model_provider_tables, the grant block via model_provider_statements, i.e. 0009's arguments). call_target takes the key from key_for only, never api_key; (None, "user") is a 409 model_provider_user_key_missing ("add your key"), and key_source in the model.ask audit row is the mode that paid. A person writes their own key on Moje klucze modeli (#/my-keys, API /me/model-keys, set_user_key / clear_user_key, shown only as user_key_prefix). A base_url change, or moving key_mode off user, deletes every personal key (core).
Module events (dredd-core 0.20.0, revision 0011; the Compass split's K1). The shared log module_event lives in the identity schema; the hub creates it there (create_event_tables, schema-qualified), drops empty local copies of the three event tables (refusing non-empty ones), then app.identity_grants.event_statements applies event_policies_sql(schema) (RLS: everybody reads, a role inserts only rows whose source_role is itself; any other policy dropped) and event_grants_sql (SELECT + INSERT for the emitters, nothing else for anybody: append-only). Emitters = the hub's own runtime role (always; managed check holds the writer tier to it) + MODULE_EVENT_EMITTER_ROLES filtered to joined identity readers (event_emitters; galena_app,compass_app in the deploy kit). Both blocks are authoritative and re-applied on every migrate, so a module listed later gets its tier on its next deploy, and a module NOT listed reaches nothing (its check without --events proves it). dredd_core.events is imported lazily (in 0011 and identity_grants): a module-level import would register its models before 0001's create_all and build local shadows on a fresh install. Standalone the log is Atrium's own in current_schema(), with the same policies, and module_event joins the runtime sweep's APPEND_ONLY — a later revision re-running the sweep must keep it there. The hub receives nothing (no cursor/receipt tables) and emits nothing yet; it holds the grant because the check requires it. Deploy order: Atrium's 0011 before Galena's 0011 / Compass's 0027 (push.sh migrates atrium first); push.sh checks galena and compass with --events and refuses a push whose env/atrium.env does not list their runtime role in MODULE_EVENT_EMITTER_ROLES. assert_identity_schema in the lifespan covers EVENT_TABLES too.
Counterparties (dredd-core 0.21.0, revision 0012; the Compass split's K2). The platform's one counterparty register (counterparty, counterparty_alias, counterparty_contact) lives in the identity schema; the hub creates it there (create_counterparty_tables, schema-qualified), drops empty local copies (refusing non-empty ones), then app.identity_grants.counterparty_statements applies counterparty_grants_sql and opens or drops the import door. The hub holds no tier and no counterparty logic (plan P3): writers = COUNTERPARTY_WRITER_ROLES (SELECT, INSERT, UPDATE; never DELETE a counterparty, TRUNCATE nowhere — sygna_app; without Sygna, the module that needs counterparties), readers = COUNTERPARTY_READER_ROLES (SELECT), migrators = COUNTERPARTY_MIGRATOR_ROLES (SELECT + REFERENCES), each filtered to joined roles (counterparty_tiers; a role in both runtime lists is a writer). Authoritative and re-applied on every migrate. The door import_counterparties(...) (SECURITY DEFINER, insert-only plus filling NULL numbers) is open while counterparty_door_wanted sees a module schema still holding a counterparty table (Compass before its 0028) or a party table without counterparty_id (Sygna before its 0006); it closes on the next migrate. Standalone 0012 is a no-op (the hub has no counterparties; a standalone module keeps its register in its own schema). dredd_core.counterparties is imported lazily, like events. push.sh checks each module with --counterparties <tier> from the hub env once its own pin is 0.21.0+, and refuses Sygna/Compass on 0.21.0+ unless both the runtime role (a tier) and the migrator are listed. assert_identity_schema covers COUNTERPARTY_TABLES.
Route walks go through dredd_core.routes.iter_routes (0.18.1): _ConsoleUnlessApi and every route-sweep test. A plain walk over app.routes sees no API route from FastAPI 0.15x on.
Only an administrator's ask may switch the model loaded on a local provider (integrations/model_server.py): anyone else asking for a different model gets a 409 model_busy naming the running model, the console shows it as is, and nothing is loaded or evicted; asking with the loaded model, or loading the first one, is open to everybody. ensure_loaded decides again under LOAD_LOCK, so a stale read at the door cannot evict (there the refusal arrives as the stream's error event). A switch unloads chat models only (CHAT_TYPES, type from /api/v0/models, instance ids from /api/v1/models); embedding models stay loaded.
Three words for what somebody may do, used verbatim everywhere — table, API, guard names, audit actions and console copy — because two words for one idea is how a permission model rots:
- administrator — platform-wide: every module, plus the hub itself.
app_user.is_admin, changed only throughservices/accounts.py. Needs no row anywhere. - moderator — administers exactly one module. A
module_permissionrow withrole = 'moderator', written only throughservices/moderation.py. - user — may USE exactly one module. The same row with
role = 'user'.
The fourth answer is no row at all, and it is the default for everybody: no access to that
module. That is what module_permission exists for — before it, anyone with an account could
type /galena and be let in, saw an empty drive, and nothing had refused them.
An administrator is a moderator of everything; a moderator is nothing outside their own module.
No tier can be granted from inside a module, and the thing that makes that true is the
grant, not a missing menu item: a module's runtime role holds SELECT on module_permission, a
seven-column SELECT on app_user and a three-column UPDATE on session, and nothing else. It
cannot admit anybody, promote anybody (least of all itself), create an account, elevate one, or
mint a credential. Atrium has administrators and no
moderators of its own — module_permission(user, 'atrium') is refused, and every account may
open the launcher anyway — which is why this app
defines require_administrator and deliberately no require_moderator, and why it never calls
authz.bind_moderation (that binding projects a moderator onto a module's node tree as manager;
Atrium's tree is the organisation chart, and a Galena moderator has no business managing it).
An assignment is a shortcut, not a second permission model. module_permission is the ONE
table that decides access: no row, no entry, and every module reads it and nothing else.
module_assignment survives only as this hub's convenience — a record of why somebody has a
module, and in particular the one way to say "everybody in Legal" without naming twelve people. It
is no longer consulted by anything making an access decision, and it is materialised into
per-user rows by services/marketplace.py.
That shortcut is re-materialised on every membership change, so it cannot go stale in either
direction: somebody who joins the department next week gets the module, and somebody who leaves
loses it. sync_module reconciles one module against its assignments; sync_members reconciles
one person against the whole catalogue; between them they are called from every hub write path that
can change the answer — assignment added or removed, availability changed, module created, access
request approved, unit grant given or taken away, unit deleted, account created, account
reactivated. There is no third table and no background job, because the hub is the only writer of
membership and of permissions, so every input is a request it served. Two rules keep the reconciliation safe and must not be
"simplified" away: it is a full set-difference, so every row it could delete has an assignment
behind it (naming somebody on a module's roster records a direct assignment for them, exactly as
approving an access request already did); and deactivated accounts take no part in it on either
side, or switching somebody off and on again would silently strip every module they moderated.
The other half of that freeze is reactivation re-materialises (routers/users.py ends in
sync_members): what was taken away while the account was off — removed from a unit, a module
switched off — must not come back with the switch.
Only an administrator or a module's own moderator lets someone INTO a module. Membership is a
unit MANAGER's to write — a node role, not a module tier — and membership materialises modules, so
without a rule the manager of Legal admitted anybody to every module assigned to Legal by adding
them to it. So a hub change that would give a person a module_permission row they do not already
have is allowed only if the actor is an administrator or a moderator of every module it would
give; otherwise it is a 403 naming the modules (Problem Details code: module_admission_refused +
modules, worded in PL/EN by the console's admissionRefusal), raised inside sync_members before
a single row is written, and the request's transaction — the grant and its audit row included —
rolls back with it. It is ONE computation, marketplace.newly_given, asked of the same per-person
answer (_entitled = assigned_ids) that the sweep then materialises, so the check and the rows
cannot disagree; sync_module asks it too. Every membership write in routers/nodes.py takes an
entitlements snapshot BEFORE it writes and passes before= — that is what makes "would give" mean
what this change gives, so taking someone out or deleting a unit (which can only take away) is
never refused, and changing a member's role gives nothing. Without a snapshot every row the sweep
would add counts: fail closed. Deactivated targets are measured too (their rows stay frozen), or an
administrator's later reactivation would carry out a manager's admission. everyone modules give
nothing new and off modules give nothing. Administrator-only paths (assignments, availability,
rosters, access requests, accounts) are unchanged. There is no unit-move route; one would be a
membership write for the whole moved sub-tree and must take the same snapshot.
The roster's HTTP path is still /admin/modules/{slug}/moderators, although the table is
module_permission. That is a deliberate exception to "one word per idea" and a cross-repo
contract: Counsel Scorecard's suite asserts the address character for character, and Galena and
Sygna quote it in their docs. Rename it in four repositories in one pass, or not at all.
The last administrator cannot be demoted or deactivated (services/accounts.py, counting only
active ones). Atrium had no such guard at all, and once the tier is platform-wide a mis-click
locked every module's administration out at once, with no second door back in.
Minting an app token for a module lives here and only here. No module holds INSERT on
session, and a role that can insert a session row can mint a valid credential for anyone — so
POST /api/v1/me/modules/{slug}/tokens is what replaces the Create token button the three module
consoles lose. The <slug>_pat_ prefix is provenance, not scope: one session row resolves in
every module, so it says where a leaked credential was issued and whose audit log to read first.
Only a sign-in session mints — POST /me/tokens and POST /me/modules/{slug}/tokens depend on
deps.require_session_credential, which reads the credential_kind get_current_user records: a
leaked app token that could mint would outlive its own revocation (a token row has no parent).
Listing and revoking stay open to any credential, because revoking is how a leak is contained.
That endpoint has a screen: Połączone aplikacje / Connected apps (viewTokens in
frontend/app.js), under Ustawienia / Settings — the section everybody has, not Administration —
because everybody holds their own credentials. It is the family's only one — a console that cannot mint leaves curl as the user's
route, which is exactly what the three modules now have — so keep its two promises: it says out loud
that a token authenticates in every module, and it shows the secret exactly once, in the reply to
the mint (mutate(..., { reopen }), never the default close-and-re-render).
assert_identity_schema runs in the lifespan, and is never optional. With
search_path = atrium, dredd, extensions, an unqualified app_user resolves to atrium.app_user
if one exists — and everything keeps working, silently back to two rows per human. A stray
create_all or a restored pg_dump --schema=atrium produces it, and nothing else in the system
ever mentions it. managed check --identity-schema catches it at deploy time; only a boot assertion
catches it after a restore.
Where things live
dredd-core (installed) Base · NAMING_CONVENTION · UUIDPkMixin · TimestampMixin · SafeInet · pg_enum
AppUser · Session · ModulePermission · AppSetting · AuditLog
Node · PermissionGrant · Favorite
SHARED_IDENTITY_TABLES (app_user, session, module_permission) — the three
that move to the shared schema; everything else stays per app
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.moderation ModerationPolicy · ModerationService
dredd_core.identity_schema assert_identity_schema (the boot guard)
create_identity_tables · repoint_identity_fks_sql
permission_grant_orphans_sql · orphan_rows_sql
dredd_core.db make_engine · make_session_factory · strip_tls_params
require_verified_tls · is_local_host · LOCAL_DATABASE_HOSTS
dredd_core.schema create_enum_types enum_types runtime_grants_sql
shared_identity_grants_sql · account_delete_guard_sql
own_tables
dredd_core.managed provision (--sql-only) · check · emulate (TEST-ONLY)
backend/app/
main.py config.py db.py deps.py errors.py security.py enums.py schemas.py seed.py
identity_grants.py (atrium-migrate step: re-applies the shared identity, model-provider and event tiers every run)
observability.py logging_config.py (db/errors/security/enums are shims)
models/ __init__ (re-exports core's AppUser/Session/ModulePermission/AppSetting/AuditLog/
Node/PermissionGrant/Favorite next to this app's own models)
marketplace Module · ModuleAssignment · AccessRequest (Text + CHECK vocabularies)
services/ auth · authz · audit (shims over dredd_core)
accounts the ADMINISTRATOR tier + the last-administrator guard, deactivate /
reactivate, and minting an app token FOR A MODULE (<slug>_pat_)
moderation module_permission: the roster, grant (an UPSERT, so it promotes and
demotes), revoke, revoke_module. The only writer on the platform.
marketplace (catalog, who may open what, requests, probe — and the reconciliation
that materialises a unit assignment into per-user permission rows) · settings
(closed, typed) · nodes (org units) · changes
integrations/ health (the outbound module probe — stdlib http.client on a socket it owns)
routers/ health auth users admin admin_modules marketplace nodes
backend/
tests/ unit (DB-free, always run) + integration (opt-in)
alembic/ env + 0001_initial (pgcrypto, create_enum_types, create_all, least-privilege grants)
+ 0002_marketplace (idempotent: checkfirst create, drops the demo entity, grants)
+ 0003_runtime_grants (dredd-core runtime_grants_sql for DB_APP_ROLE; fails loudly)
+ 0004_shared_identity (IDENTITY_SCHEMA only, else a no-op: builds the three shared
tables in the neutral schema, moves Atrium's rows in with their UUIDs, re-points
its 14 foreign keys, drops the local copies, grants all eight roles their tier,
forbids DELETE on an account. NOT downgradable on a platform — see the docstring,
and deploy/RUNBOOK-one-account.md for the operator sequence)
+ 0005_counsel_slug (the catalogue row the seed got wrong, and the permission rows
addressed to it; the survivor of a duplicate keeps the HIGHER role)
+ 0006_module_permission (dredd-core v0.11.0's rename, in THIS app's own schema —
`0001` is stamped and can never reach a database that already exists, which is
the `node_kind` mistake this family has made once. Decided by catalogue check:
already renamed → nothing; `module_moderator` → RENAME + its constraints +
`role` + every existing row set to moderator; in the shared schema or
IDENTITY_SCHEMA set → nothing, because a local copy would be the shadow table;
nowhere at all → built from the metadata)
scripts/ license_gate (CI copyleft gate) · deploy_check (compose/Dockerfile/front door/.env)
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)
db/managed/ provision.sql (rendered by dredd-core; CI checks it) · README.md (the managed-Postgres
runbook: project-wide steps for any provider, then Atrium's part)
docker-compose.yml · docker-compose.managed-db.yml (managed-database override)
.env.example · .github/workflows/ci.yml (backend on PG 16+17 · managed-db · compose-smoke)
Strict one-way layering — routers/ (HTTP, validation, authz; never touches SQL) →
services/ (domain logic) → models/ (ORM). Keep it.
Commands
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
ATRIUM_RUN_INTEGRATION=1 pytest # full API loop (needs a migrated+seeded Postgres)
alembic upgrade head --sql # inspect the DDL with no database
python scripts/license_gate.py # CI license gate locally
python scripts/deploy_check.py # compose/Dockerfile/front door/.env coherence (--env FILE)
node --check frontend/app.js # ALWAYS after editing the console
python -m dredd_core.managed provision --sql-only --schema atrium --app-role atrium_app \
--migrator-role atrium_migrator --output db/managed/provision.sql # from the repo root, after a core bump
Invariants — preserve these
-
NEVER add logic to a shim.
models/__init__.py(the core re-exports),services/auth.py,services/authz.py,services/audit.py,db.py,errors.py,security.pyandenums.pyexist so call sites keep their import paths. A shim may only: import fromdredd_core, bind names (authenticate = _service.authenticate), declare app-only constants (theatrium_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, repinrequirements.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 fromconfig.get_settings(), theatrium_sessioncookie name, FastAPI exception handlers that render core'sAppErroras Problem Details. -
Strict layering. No
select(...)/db.add/db.executein a router. A lonedb.get(Model, id)by primary key is acceptable. Services own every domain rule. -
dredd_core.authzis the only access authority (re-exported asservices/authz.py). Routers callassert_can_read/assert_rolebefore every read and write. No access → 404, never 403 — the existence of a record can itself be privileged. List screens filter through the readable-node set, not a per-row check. -
Append-only audit. Write through
dredd_core.audit.record. Theapprole holds no UPDATE/DELETE onaudit_log(enforced in the migration).migratorowns DDL;appis DML-only. This is a confidentiality control, not an ops convenience — never grant the app role DDL or audit mutation. -
dredd-core ships models, not migrations. Importing
dredd_coreregisters the identity and org-tree tables on the sharedBase.metadata; this app owns its0001. Because core's enum columns are declared withcreate_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)→ grants. Adding a model or a native enum needs no edit to0001:create_enum_typesandcreate_allboth derive from the metadata.tests/test_migration_parity.pyguards that the existing models are imported (an unimported model gets no table and no type). Add a new model's table name totest_the_apps_own_tables_are_registered, or a forgotten import goes unnoticed. Once this is deployed anywhere, a new table or enum type needs its own revision instead of an edit to0001, and so does a new label on an existing type (an ALTER TYPE revision, becausecreate_enum_typesskips types that already exist). -
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__.pyor it silently never gets a table. -
The org tree holds units only (workspace → group/folder) — no leaf kind, because modules are catalog rows, not nodes. Units have no owner and creating one grants nothing: dredd-core makes an owner a permanent, invisible manager, and an automatic grant would be membership (the creator keeps the parent's modules after losing the parent grant). A sub-unit's creator already manages it through the parent grant. Membership is a direct grant on a unit; the Members dialog shows grants on ancestors separately, as access, because they do not make someone a member. Migration 0002 turns legacy non-admin owners into explicit manager grants and clears every unit owner.
-
Cookie-authenticated writes must be same-origin —
deps.refuse_cross_site_write, registered once as an app-wide dependency inmain.py(the decision is core's,dredd_core.cross_site.cross_site_write_refusedsince v0.14.0; the dependency only raises this app's own error), checksSec-Fetch-Siteand, where browsers omit it (plain HTTP, older Safari),OriginagainstHost;CORS_ALLOW_ORIGINSentries are trusted. Its property changed when the family moved to one origin: a page at/galenais now same-origin with/atrium, so both signals pass and the guard no longer separates modules — it only still blocks genuinely foreign sites. Don't "restore" a guard that cannot work; the thing that keeps script from driving another module's API is each console's own CSP and the rule that untrusted bytes never execute in-origin. And never add an entry toCORS_ALLOW_ORIGINSnow that the family shares one origin:deps.pyreturns early for any listed origin, bypassing both signals. -
Sessions are server-side, so logout/deactivate is an instant kill-switch. Deactivating a user must also revoke their sessions. A session is a row in the platform's identity store — this app's schema today, the shared one after the identity cutover — and revoking it is honoured on the next request wherever the cookie is presented.
-
Token scope is enforced in
deps.get_current_userand nowhere else. Every authenticated route depends on it, so one check covers all of them and no future route can forget it. -
Nonemeans "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.errorstypes from services, render them in one handler — core'sextraincluded, as extension members (the admission refusal'scode+modulestravel that way). Stack traces hidden whenAPP_ENV=production. -
Console security:
esc()every dynamic value; the console holds no credential — the HttpOnly session cookie is the only one a sign-in issues, andPOST /auth/loginanswers with the user only (LoginOuthas notoken: a copy in the body was readable by any script on the platform's one origin). Non-browser clients keep the cookie (curl -c) or use an app token. Nothing loads from a CDN (the CSP has no third-party origins). -
Console writes go through
mutate(), and nothing refreshes shared state by hand.api()marks the settings, launcher and pending badge stale on every successful non-GET;router()re-reads them once (refreshShared), and so doesmutate()when a dialog stays open instead of navigating. A failed read keeps the old values and stays stale;showLogin()drops per-user data. A new action gets that for free, so don't addrefreshLauncher()calls after it. Inapp.css, base rules come before their variants and every breakpoint block sits at the end — sizes are classes (td.shrink,.app .mi), not inline styles, so overrides win by order, not by!importantor a doubled class. (!importantstays only on utilities that must always win:.hidden,.col-opt, reduced motion.) -
Brand = Open Color
grape#9c36b5— the family's own hue, which no sibling wears (Counsel Scorecard's mark is orange, so Atrium moved off it) — confined to identity: the app mark, the avatar, the focus ring. Module tiles wear the module's hue, not Atrium's;.mi.h-<hue>inapp.cssandGLYPHinapp.jsmust matchHUES/GLYPHSinservices/marketplace.py(tests/test_marketplace_unit.pyenforces it).galena/sygna/percentare the siblings' own marks — keep them identical to their apps' logos. 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.
-
Atrium is the platform's front door (
backend/app/frontdoor.py, the image's CMDuvicorn app.frontdoor:outer, started bypython -m app.serve). It is the only edge, with no reverse proxy in front:/→ 302/atrium/, exact/<slug>→ 308/<slug>/, Atrium itself via StarletteMount("/atrium")(which setsroot_pathin-process — no--root-path;ROOT_PATHmust be empty or/atrium), every other module streamed by onehttpx.AsyncClientper worker to the FIXEDFRONTDOOR_UPSTREAMSmap (never from the request), and the platform's plain 404 (NOT_FOUND) for the rest. Keep: the raw-path refusals (%2f %5c %2e %00,\, NUL,./..segments, non-origin-form targets → 400) checked onraw_pathBEFORE routing and the raw path forwarded byte-exact minus the prefix; Host unchanged (the modules' Origin-vs-Host guard), inboundX-Forwarded-*/Forwardeddropped and set anew; hop-by-hop +Serverstripped both ways; Content-Encoding passed through (aiter_raw); nothing buffered; 100 MB cap; aLocationnaming an internal upstream → 502; uvicorn--no-proxy-headers(this is the edge — the peer IS the client). Its own responses carry Atrium's headers (DENY); proxied ones carry only the module's. The standalonedocker-compose.ymlruns the SAME CMD with no proxy: backend on80:8000,FRONTDOOR_UPSTREAMSempty, Atrium at/atrium(CI's compose-smoke curls/atrium/...and the redirects). There is no reverse-proxy config file and no proxy service; never add one, and never add a composecommand:override. Tests:tests/test_frontdoor.py, ASGI-level so..and encodings reach the code unnormalised. TLS is optional, off by default (TlsConfig.from_env;deploy/compose.tls.yaml,deploy/RUNBOOK-tls.md). Off,app/serve.pyexecs exactly the one uvicorn above. On, it supervises two (plain:8000, HTTPS:8443with the certificate) and exits when the certbot sidecar's deploy hook touches/run/tls/reload, sorestart: unless-stoppedreloads the certificate — keep it that way: no Docker socket in any container. On plain HTTP, AFTERcheck_target, the front door serves/.well-known/acme-challenge/<token>from the webroot and, once the pair exists, 308s tohttps://<TLS_DOMAIN>(the configured name, never Host). It ownsStrict-Transport-Security: a module's is always stripped,HSTS_MAX_AGE(0 = none) is stamped on HTTPS responses only. -
Path-mounting is ONE decision, taken in two places. The family serves one module per path on one origin. For Atrium the front door's
Mount("/atrium")takes both halves at once (it routes on the full path and setsroot_path), so there is no--root-pathandROOT_PATHis empty or/atrium(mirrored intoFastAPI(root_path=...)for the OpenAPI servers). The MODULES still take it in two places: the front door strips/<slug>and their uvicorn--root-pathputs it back.uvicorn app.main:appwithROOT_PATHempty (dev) serves Atrium at the root.- Anything that branches on the request path must use the ROUTE path,
get_route_path(scope), notrequest.url.path— underroot_paththe URL carries the prefix and astartswith("/api")test silently stops matching (main.py's security-header middleware is the one that does this). - The console derives its API base from
document.baseURI(app.js'sAPI), never/api/v1: a root-absolute base would leave this module and hit a sibling's backend. Assets inindex.htmlare document-relative and routing is hash-based for the same reason — keep both, and never add a leading-slashhref/src/location.href. - Healthchecks need no prefix: uvicorn prepends
root_path, Starlette strips it again.
- Anything that branches on the request path must use the ROUTE path,
-
Availability is what Atrium offers, not access to the module. It decides whose launcher a module appears in, and nothing more. Under one origin a module's address is a guessable path (
/galena/), so withholding it withholds nothing: what keeps someone out is the module's ownpermission_grantrows. An unassigned person who types the path reaches the module and finds it empty. Say that plainly in the console copy rather than implying the tile is a lock. -
selected= direct user assignment ∪ membership of an assigned unit or any unit below it. Membership is the user's own permission grants (authz.grants_for_user) that core still honours (authz.readable_node_ids, so overlays apply) — resolved inmarketplace.accessible_ids, the one place. Administrators are not special in the launcher. Don't add a second resolver in a router. -
Settings are a closed set (
services/settings.SPECS). Add a key there with its type and bounds; never reintroduce a write-any-key endpoint. -
Module addresses are http(s) only, three times over:
marketplace.clean_url(also refuses credentials in the authority), theck_module_url_schemeCHECK, andsafeUrl()in the console. One origin per family does not relax this: a module's address is an ordinary absolute URL that happens to share our origin (http://<host>/galena), which all three gates already accept. Storing a path-only address (/galena) would mean changing a CHECK constraint, a validator and anhrefsanitiser together — a separate change with its own review, not a side effect of path-mounting. -
The probe is SSRF-shaped by nature: admin-only, audited (with its target), http(s), no redirects, ONE wall-clock deadline for the whole exchange: name resolution runs in a resolver thread joined only for the time left, each connect attempt is capped at the time left, and everything after connect is bounded by a watchdog on its own socket (socket timeouts restart per read), raw bytes read with
Accept-Encoding: identityand capped before they are kept (decoded reads are a decompression bomb), a few probes at once, the DB transaction ended before the call, and nothing of the body returned butversion. It always returns a verdict, never raises. Keep all of that. The stored health address is the module's public one (http://<host>/galena/api/v1/health), never a compose service name. In the deploy kitatrium-backendis the front door and does sit on every module's network, but the probe is meant to test what a browser gets (out through the public address and back in through the front door), and a service name means nothing outside that one compose file. -
The family catalog is seeded once per instance (
seed.CATALOG_SEEDEDmarker), never gated by a flag and never re-added after an administrator deletes modules. -
Slug is immutable — it names the module in URLs and every audit row.
-
Later revisions must be idempotent (
checkfirst,IF EXISTS):0001builds from the live metadata, so on a fresh database it already contains every current table. See0002. -
Managed Postgres = the family's ONE shared database on a managed PostgreSQL provider (PostgreSQL 17; runbook
db/managed/README.md— the project-wide steps for any provider, then Atrium's part). No provider is named anywhere (files, paths, variables, identifiers, comments, docs): provider know-how is written generically — "some poolers need<role>.<tenant>user names", "download the provider's root CA from its dashboard", "providers may expose tables through an auto-generated API: keep the schema out of it", "a restore may drop custom role passwords". The names aredb/managed/,docker-compose.managed-db.yml,MANAGED_DB_*env names, the CI jobmanaged-db. Keep all of this:- Own schema, never
public. Atrium lives in schemaatrium, owned byatrium_migrator. Nothing in code is schema-qualified: the roles'search_path = atrium, extensions(set by provisioning) puts tables, enum types andalembic_versionthere, andcreate_all's checkfirst /create_enum_typesonly see that schema. Don't add aschema=to models or migrations. - Per-app roles, named by config. Role names are cluster-wide, so in the shared database they are
atrium_migrator/atrium_app; locally and in CImigrator/app.DB_APP_ROLE(defaultapp) is the only place the runtime role's name lives —0003_runtime_grantsgrants to it. Never create genericapp/migratorroles in the shared database (0001still grants a role literally namedapponpublic;0002's unqualified grant runs only while the current schema ispublic— keep any such legacy block schema-guarded).deploy_check.pyrequires exactlyatrium_app/atrium_migratorin an external.env. Provisioning is dredd-core'spython -m dredd_core.managed provision;db/managed/provision.sqlis its rendering — re-render it, never hand-edit (CI--check-file). - Never migrate as
postgres(or any superuser / the platform admin), and0001's FIRST statement is what says so: dredd-core'smigration_preflight_sqlrefuses by name before anything is created — keep it first.runtime_grants_sqlrepeats the check in0003, but0003is reached only once0001and0002have succeeded, so as the platform admin the hub built the whole platform's accounts first, owned by that role, with only Alembic's one transaction taking them away again. Sygna is where that was noticed: its0001leaves the identity tables to the hub, so there the wrong role died onrelation "app_user" does not existinstead — refused by accident, naming neither the problem nor the fix. Migrations run as the migrator, the seed and the backend as the runtime role, and the long-running backend never gets migrator credentials (docker-compose.managed-db.ymlblanks them). - Grants fail loudly. A new table means a new revision that calls
runtime_grants_sqlagain; never go back to anIF EXISTS (role) THEN GRANTblock that skips silently. - One TLS rule,
dredd_core.db.require_verified_tls, applied bySettings(config.py, a model validator, so the backend,migrateand the seed all stop before anything connects). A database host counts as local when it is"",localhost,127.0.0.1,::1,postgresor listed inDB_LOCAL_HOSTS(comma-separated, optional); every other host must carrysslmode=verify-full(withsslrootcert, or the system trust store) or the app refuses to start. No provider host lists, and no other opt-out: a private host that genuinely needs no TLS goes intoDB_LOCAL_HOSTS.tests/test_settings_db_urls.pypins it; the error never carries the password. - TLS only through
make_engine. Every engine —db.py,alembic/env.py, the seed — is built bydredd_core.db.make_engine(one-shot ones withNullPool), nevercreate_engine: it turnssslmode=verify-full&sslrootcert=into a verifying context and refusesprefer/allow/disable.env.pyreads the URL from settings and never passes it throughconfig.set_main_option(configparser%interpolation breaks percent-encoded passwords); offline it usesstrip_tls_params. The provider's CA is mounted at/run/certs/db-ca.crtfromMANAGED_DB_CA_FILE. - Session-mode pooling, port 5432, never a transaction-mode pooler (commonly 6543). The user is
<role>.<tenant>where the provider's pooler needs the tenant in the user name (deploy_checkonly warns about a pooler host without it — only the provider knows). The runtime pool isDB_POOL_SIZE+DB_MAX_OVERFLOW: four apps share one connection limit. - PostgreSQL 16 and 17. CI runs the backend suite on both and a
managed-dbjob on 17 (emulate → provision → migrate → seed → tests asatrium_app→managed check→ downgrade/upgrade).deploy_check.pyvalidates an external-database.env(CI feeds it a managed-database-shaped one plus broken copies), andcompose-smokechecks the mergeddocker-compose.managed-db.ymlmodel.
- Own schema, never
Gotchas
- Installing needs credentials.
dredd-corelives in a private repo;pip install -r requirements.txtfails with an authentication error unless git can reach it (CI uses theDREDD_CORE_TOKENsecret; locally, your own GitHub credentials). favoriteis unused: importingdredd_coreregistersfavoritealong with the org tree (node,permission_grant, which Atrium does use for units and membership), so the table is created but stays empty — that is expected, not a bug. Don't try to suppress it.- On Windows, write
.envwithout a BOM (PowerShell'sOut-File -Encoding utf8adds 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 duplicateconstinside 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
visibilityover a duration or with a delay; the off-canvas drawer gets stuck when frames are throttled.transformtransitions;visibilityflips instantly. - Name model modules so they cannot shadow a stdlib module (
timelog.py, nottime.py).
Status
On dredd-core v0.9.0. Scaffolded with /dredd, then the demo entity was replaced by the marketplace
(September 2026): catalog, availability + unit/user assignments, access requests, health probe,
typed settings, organization and users screens, PL/EN console. Unit tests plus a real integration
suite (ATRIUM_RUN_INTEGRATION=1) run as the least-privilege app role.