Files
admin 6f5a004cbe Merge pull request #5 from Alpaq92/fix/initiator-lock-and-round
fix(security): the initiator lock is the moderator's; a stale click fails in a new round
2026-11-28 10:39:53 +01:00

29 KiB

CLAUDE.md

Guidance for Claude Code when working in this repository.

What this is

Workflow — the platform's approval module: staged approval runs (obiegi akceptacji) on a Galena document, an uploaded file or a request (wniosek). 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.24.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 workflow 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])
                workflow  (approver_group(+_member) · workflow_template · request_type · request ·
                           workflow_run · run_stage_state · workflow_event · notification)
  services/     auth · audit · moderation     (shims over dredd_core)
                authz     (nodes tenancy: shim over dredd_core.authz · simple: local moderator/owner rules)
                changes · settings · audit_log   (this app's logic; audit_log: the read-only audit query)
                rules (pure: stages, settings, notes, keys) · engine (pure: act() for every action)
                galena (ModuleClient wrapper; tests/fake_galena) · subjects (upload / pin / read)
                requests (types + requests + snapshot) · groups · templates · assignees
                runs (start, act) · notify · lists (inbox / mine / archive + CSV, can_* flags)
                legacy_import (Galena's old runs + templates as history; `python -m
                               app.import_galena_runs runs.json [--commit]`, idempotent)
  routers/      health auth users admin dashboard (+ GET /stats)
                runs (runs, actions, stages, scan, /files upload, /options, inbox/mine/archive, notifications)
                templates · requests (fields, types, requests, GET /files/{id}) · groups
backend/tests/    unit (DB-free, always run) + integration (opt-in)
                  + e2e/test_console.py (Playwright, opt-in: test_expense_happy_path)
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)
                  + 0005_workflow (the workflow tables + custom_field + the event log; idempotent by
                    catalog; on the platform drops the local, empty module_event; refuses downgrade there)
backend/scripts/  license_gate · deploy_check
frontend/       index.html · app.css · app.js · InterVariable.woff2   (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

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
WORKFLOW_RUN_INTEGRATION=1 pytest # full API loop (needs a migrated+seeded Postgres)
WORKFLOW_E2E_BASE_URL=http://localhost:8141 pytest tests/e2e   # console e2e on a running stack
                                          # (needs `pip install playwright && playwright install chromium`)
alembic upgrade head --sql                # inspect the DDL with no database
python -m dredd_core.managed provision --sql-only --schema workflow --app-role workflow_app \
  --migrator-role workflow_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 workflow_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 the schema name: 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, workflow_app in the shared managed database, next to workflow_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 workflow 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 gray #495057 (gray7; dark-theme strokes gray4 #ced4da). Chosen because it is the only tile hue in Atrium's list no family module wears — every coloured hue is taken (grape Atrium, violet Galena, indigo Arbiter, blue Compass, cyan Sygna, teal Insider, green Lexicon, lime Scribe, yellow the signing module, orange Counsel, red Agora, pink Panorama), and gray needs no change in Atrium. 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).

The domain: approval runs (Compass split, work package „Workflow”)

Workflow is the platform's approval module: an obieg akceptacji (approval run) of 1-10 stages on one subject, with the rules of the product spec's §5.2a „Ustawienia obiegu”. Source documents: the implementation plan's Part B and the module spec (paths in .meduza/SPEC-workflow-module.md).

  • Subject. workflow_run carries dredd_core.document_ref.SubjectRefMixin or a request: a Galena DocumentRef (re-pinned at start by document id + path, read through module_client with the acting person's token, needs GALENA_BASE_URL; empty URL -> 409 galena_disabled), a FileRef in dredd_core.plain_files (an upload, always available) or a request (a wniosek of a moderator-defined request_type, fields from the dredd_core.custom_fields pool, frozen as a snapshot + sha256 when the run starts). A role stage (Galena role holders) only on a document.
  • States (RunStatus): w_toku -> zatwierdzony | podpisany | odrzucony | anulowany; podpisany is an approval that ends with the scan of a paper signature. One running run per subject (partial unique index).
  • Rules (§5.2a) live in two pure modules: services/rules.py validates templates, stages and settings (DEFAULT_SETTINGS + merge_settings, stable stage keys, notes ≤ 2000, required on reject / back / cancel / add_stage) and services/engine.py decides every action (act(): approve, reject, back, cancel, add_stage, refresh, paper_scan, edit_request) on a RunState. Refusal order is fixed: 404 -> 409 (stale stage_key_seen / round_seen / stages_seen, not running) -> 403 -> 422. Rejection follows §5.2a (back to the first or previous stage, a new round), not Galena's „rejection ends the run”. Keep new rules in these two files and test them DB-free. The initiator lock is the moderator's: initiator_may_approve is off by default, only a template can switch it on, and a run's settings_override may never lift it (merge_settings(..., for_run=True), 422 initiator_lock_fixed) - otherwise anybody could lay out stages naming only themselves and emit workflow.approved, which Galena moves a card on.
  • Who. Read access is services/authz.can_read_run (a Galena document: Galena's my_roles alone; file / request: initiator, this module's moderators, the stage's people). Owner = initiator or Galena manager / moderator. Approvers are fixed on entering a stage (run_stage_state, on_enter) or resolved live; services/assignees.py drops inactive people and those without module access.
  • Evidence. workflow_event is the timeline (append-only); runs, requests, templates, types and groups are archived, never deleted (NO_DELETE_TABLES). Every finishing action writes, in the same transaction: event + audit + a workflow.* event from dredd_core.workflow_contract (workflow.started, .approved, .rejected, .cancelled, .signed_on_paper; flat identifiers only — never a document path or a file name). A paper scan on a Galena document is written back through Galena (save_scan); when Galena refuses, the run keeps the scan as a FileRef.
  • GET /stats (dredd-core stats_contract): tiles inbox („Czeka na mnie”) and running („W toku”), counted with the very filter the lists apply.
  • Downloads are always attachments through plain_files.response_headers (octet-stream + sandbox CSP): nothing a person uploaded renders in this origin.
  • Standalone compose publishes :8141 (WORKFLOW_PORT).

Status

Stages 1-7 of .meduza/PLAN.md are built: skeleton from the family's signing module (CREDITS.md), renamed and stripped of signing, pinned to dredd-core v0.24.0; models + migration 0005; the pure rules and engine; the Galena client, subjects, requests, authz, groups, templates, assignees, runs (start, act, add stage, refresh, paper scan, request edit), notifications, lists and stats; the API; the console (lists, settings, start screens, run detail).

Verified locally: DB-free pytest, node --check frontend/app.js, Node smoke tests of the console with a stubbed DOM. Not run here (no Postgres, no Docker, no Playwright on this machine): every test_integration* (WORKFLOW_RUN_INTEGRATION=1), the e2e test (WORKFLOW_E2E_BASE_URL), the console in a real browser, and the managed-database path. dredd-core v0.24.0 was not tagged yet on 2026-11-18: the pin names a tag that must exist before CI can install it.