dredd-core

The shared foundation for the Dredd family (Galena, Sygna, Counsel Scorecard, Galena Connect): one identity / session / auth / audit core, one org tree, one permission model, one SQLAlchemy Base. Apps import it; it never imports an app. Apache-2.0.

What's in it

Module Contents
dredd_core Base, NAMING_CONVENTION, UUIDPkMixin, TimestampMixin, SafeInet, pg_enum, and the models below
.identity AppUser, Session, ModulePermission, AppSetting, AuditLog; SHARED_IDENTITY_TABLES, MODULE_ROLES and the column lists three separate things have to agree on
.node Node, PermissionGrant, Favorite — the org tree
.authz effective-role resolution (ancestor-or-self inheritance) + grant CRUD; bind_moderation()
.auth AuthPolicy + AuthService — login, lockout, sessions, app tokens
.moderation ModerationPolicy + ModerationService — what a person may do in one module: platform-wide administrator, per-module moderator, per-module user, or no access at all
.security Argon2id password hashing, opaque tokens, passphrase KDF
.audit record() — the append-only audit writer
.db make_engine / make_session_factory with hardened defaults; libpq-style sslmode / sslrootcert URL parameters become a pg8000 TLS context (ssl_context_for, strip_tls_params); the family's TLS rule (is_local_host, require_verified_tls)
.schema migration_preflight_sql() — the first statement of an app's first revision: refuse the wrong migrating role before anything is created; enum_types() / create_enum_types() — the DDL prerequisite for create_all; own_tables() — which tables are this app's own; runtime_grants_sql() — the runtime role's least-privilege grants as one idempotent DO block; shared_identity_grants_sql(), account_delete_guard_sql() and session_update_guard_sql() for a shared identity schema
.identity_schema assert_identity_schema() (a boot assertion), create_identity_tables(), and the merge helpers repoint_identity_fks_sql() / orphan_rows_sql()
.provisioning provision() / provision_sql() — one app's schema and roles in the shared managed database, run live or rendered as SQL
.managed python -m dredd_core.managed provision (that routine as a command), check (read-only managed-Postgres preflight: cross-schema isolation, and the shared identity allowlist) and emulate (TEST-ONLY managed-Postgres lookalike)
.custom_fields (opt-in) CustomField, CustomFieldKind (text/number/date/choice/boolean); EntitySpec + register_entity / entity / registered_entities; create / update / all_fields / by_key / get; values_after; sort_expression / filter_expression / active_field; key_of, diff_of, MESSAGES
.table_views (opt-in) TableView, TableSpec + register_table; current / checked / readable; save_own / delete_own / save_firm_default / delete_firm_default; MESSAGES
.model_providers (opt-in) ModelProvider, ModelProviderPolicy, ModelProviderKey; offering / offering_to_an_administrator / usable_providers / visible / for_reading; policy / eu_only / set_policy; create / update / disable; api_key; check_base_url / check_models; create_model_provider_tables, model_provider_grants_sql, model_provider_import_sql; MESSAGES
.json_charset (opt-in) needs_json_charset / ensure_json_charset / ensure_json_charset_headers / ensure_json_charset_message; JsonCharset (pure-ASGI middleware) — charset=utf-8 on every JSON response
.module_client (opt-in, stdlib) ModuleClient(base_url, service=, timeout=, max_body=) · .request(method, path, *, token, params=, json=, body=, content_type=, headers=, accept=) → ModuleResponse (ok, json(), problem_detail(), raise_for_status()); ModuleCallError (502); check_base_url; multipart
.plain_files (opt-in) PlainFiles(data_dir) · save(data, name) → FileRef · open(file_id) · read(ref) · delete(file_id); response_headers(name, media_type=None, *, download=False); INLINE_MEDIA, SANDBOX_CSP
.document_ref (opt-in) DocumentRef, FileRef, to_dict / from_dict; SubjectRefMixin (columns + CHECK: exactly one); read_document / pin_document / read / move_to_documents
.events (opt-in) ModuleEvent, EventCursor, EventReceipt; emit (in the caller's transaction) / receive (cursor + receipts, at least once, idempotent on event.id); check_payload (identifiers and numbers only); create_event_tables, event_policies_sql (RLS: insert only as yourself), event_grants_sql; FIRST_EVENTS
.routes (opt-in) iter_routes(app.routes) — (original, effective) pairs over every route, included routers descended (FastAPI 0.15x keeps each as one _IncludedRouter)
.enums, .errors shared enums; the AppError Problem-Details hierarchy (no web framework)

Importing dredd_core registers the identity + org-tree tables on Base.metadata — and not the two opt-in modules' (see Custom fields and saved table views).

Install

It is a private repo, so pin it by tag (the newest release; the /dredd scaffold needs ≥ v0.9.0) and give CI a read-only token:

dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.25.0
# in the consuming app's CI, before `pip install`
- run: |
    git config --global url."https://x-access-token:${TOKEN}@github.com/Alpaq92/dredd-core".insteadOf "https://github.com/Alpaq92/dredd-core"
    pip install -r requirements.txt
  env: { TOKEN: "${{ secrets.DREDD_CORE_TOKEN }}" }

For local co-development, pip install -e ../dredd-core shadows the pin.

Starting a new app on it

dredd-core ships models, not migrations — each app owns its own migration history. Because the enum columns use create_type=False, the native enum types must exist before create_all:

from dredd_core import Base
from dredd_core.identity import SHARED_IDENTITY_TABLES
from dredd_core.schema import create_enum_types, migration_preflight_sql, own_tables

def upgrade() -> None:
    conn = op.get_bind()
    # FIRST, before anything exists: refuse a superuser, the platform admin or the runtime role.
    op.execute(migration_preflight_sql(settings.db_app_role))
    create_enum_types(conn)        # core's enum types — and yours, once your models are imported
    # Everything, standalone. In a deployment that shares one account per person, the identity
    # tables belong to the platform and this app must not create its own — see below.
    shared = SHARED_IDENTITY_TABLES if settings.identity_schema else ()
    Base.metadata.create_all(conn, tables=own_tables(Base.metadata, shared=shared))

That first line is not a belt-and-braces duplicate of the grants below, which make the same two role checks: the order is the whole point. A check inside a later revision is only reached if every revision before it succeeded, and the wrong role fails those for reasons that never mention the role — a module's 0001 migrated as the platform admin died on relation "app_user" does not exist, because that role's search_path does not carry the shared identity schema. Refused, but by accident, and with a message that sent the reader to the wrong place. migration_preflight_sql needs no table, role or grant of its own, so it can go first, which is where it belongs.

Grant the runtime role its privileges in the same revision (or a later one — the block is idempotent). Migrations run as the migrator role: the block refuses to run as a superuser or as postgres, and raises if the runtime role is missing or a grant silently did not take. The role's name is configuration (DB_APP_ROLE: app locally and in CI, <app>_app in the shared managed database):

from dredd_core.schema import runtime_grants_sql

def upgrade() -> None:
    op.execute(runtime_grants_sql(settings.db_app_role, append_only=("audit_log",), no_delete=()))

Apply the family's TLS rule to every database URL at start-up, so a database reached over a network is always verified and encrypted (a host counts as local when it is "", localhost, 127.0.0.1, ::1, postgres or listed in the app's DB_LOCAL_HOSTS; every other host must carry sslmode=verify-full, or the app refuses to start):

from dredd_core.db import require_verified_tls

require_verified_tls(settings.database_url, local_hosts=settings.db_local_hosts)   # ValueError = refuse
require_verified_tls(settings.migration_database_url, local_hosts=settings.db_local_hosts)

Build every engine through make_engine — the app's, Alembic's, a restore or seed script's — and never create_engine directly, so TLS URL parameters work everywhere:

# alembic/env.py — use the URL directly: never config.set_main_option(), whose configparser
# %-interpolation breaks URL-encoded passwords
from sqlalchemy import pool
from dredd_core.db import make_engine, strip_tls_params

url = settings.migration_database_url

def run_migrations_offline() -> None:
    context.configure(url=strip_tls_params(url), literal_binds=True, ...)   # --sql never connects

def run_migrations_online() -> None:
    connectable = make_engine(url, poolclass=pool.NullPool)

Wire the engine and auth from your own config:

from dredd_core.db import make_engine, make_session_factory
from dredd_core.auth import AuthPolicy, AuthService

engine = make_engine(settings.database_url)          # hide_parameters=True, pool_pre_ping, …
SessionLocal = make_session_factory(engine)

auth = AuthService(AuthPolicy(
    session_ttl_hours=settings.session_ttl_hours,
    app_token_prefix="sygna_pat_",                   # your product's greppable token prefix
))

Guard every read/write through the one authority:

from dredd_core import authz
from dredd_core.enums import NodeRole

authz.assert_role(db, user, node, NodeRole.editor)   # 404 if no access, 403 if insufficient

Managed PostgreSQL: one shared database

The whole family can run in one managed PostgreSQL database (the family's is on a managed provider: EU region, Postgres 17) — with Atrium as the hub and Galena, Sygna and Counsel Scorecard as its modules. A managed provider hosts only the database, so every backend still runs on a server of its own. The same tooling works against any PostgreSQL 16/17 whose admin may create roles and schemas — the deploy kit's own postgres:17 container included, which is its default.

App Schema Migrator role Runtime role Extensions
Atrium atrium atrium_migrator atrium_app
Galena galena galena_migrator galena_app
Sygna sygna sygna_migrator sygna_app
Counsel Scorecard counsel counsel_migrator counsel_app pg_trgm
  • One schema per app, never public, owned by that app's migrator. Role names carry the app: role names are cluster-wide, and with shared app / migrator roles one app's migration would grant back what another revoked (DELETE on Sygna's evidence tables, say) and one password would open every app. Local development and CI keep the plain app / migrator names; an app reads its runtime role's name from config (DB_APP_ROLE, default app) for its runtime-grants revision — nothing else in an app needs a role name. provision refuses app and migrator as role names, so the local shape can't reach a shared database.
  • search_path = <schema>[, <identity schema>], extensions for both roles (set by provisioning), so alembic_version, the enum types and every table land in the app's own schema with nothing schema-qualified in code. The app's own schema is first, always. create_enum_types and create_all's checkfirst only see the app's own schema, so one app's audit_log never makes another app's get skipped (tested with the core tables in two schemas of one database) — which is also what lets a standalone app keep its identity tables in its own schema.
  • Identity: one store per deployment, not one per app. Core declares app_user / session / module_permission on Base.metadata and an app creates them wherever its search_path puts them, so one body of code serves both shapes. A standalone app owns its identity outright — that stays supported and does not change. The Dredd family deployment is one platform: one origin, one module per path (/atrium, /galena, /sygna, /counsel), and a person has ONE account — they sign in once, in Atrium, and every module resolves the same session. Modules keep their own schema and their own least-privilege roles, so database isolation is unchanged; 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) — and its own audit_log and app_setting. One origin also means there is no cross-origin handoff to design — no signed assertion, no audience binding — so core needs no SSO protocol, it needs one shared set of tables. Today's four admin@example.com rows, one per app schema, are a defect being corrected, not the design: that model was inferred by an assistant, never chosen. Read any "separate logins", "no cross-app SSO" or "one app_user per app" claim as stale. See A shared identity schema.
  • Isolation: an app's roles hold no privilege in another app's schema — no USAGE, no tables, sequences or functions — and provisioning gives PUBLIC nothing on an app schema. python -m dredd_core.managed check proves it (below). A shared identity schema is the one deliberate exception, and it is earned the harder way: with --identity-schema that name leaves the negative sweep and an explicit, closed allowlist takes its place, one finding per role — a module may read accounts and write session rows, and never write accounts. Skipping a schema proves nothing, and the thing being skipped would be the one schema where every account on the platform lives.
  • Keep the schemas out of any auto-generated API. Providers may expose tables through an auto-generated HTTP API that connects as anon / authenticated / service_role (dredd_core.schema.API_ROLES) and exposes public by default. Switch such an API off, or never add an app schema to it; check also proves that those roles hold nothing in the app's schema.

Provisioning an app

One routine in core, never copy-pasted SQL. As the platform admin (the provider's postgres, which is not a superuser there), per app:

GALENA_MIGRATOR_PASSWORD=... GALENA_APP_PASSWORD=... \
python -m dredd_core.managed provision --admin-url ADMIN_DATABASE_URL \
    --schema galena --app-role galena_app --migrator-role galena_migrator \
    --migrator-password-env GALENA_MIGRATOR_PASSWORD --app-password-env GALENA_APP_PASSWORD
# Counsel adds: --extension pg_trgm        (--statement-timeout 30min is the default)

Before anything runs, names are validated: a schema or role that is not a plain lower-case SQL name, public or a system schema, a reserved or platform role (postgres, anon, pg_*, authenticator, …), and the local stack's generic app / migrator are refused.

--admin-url takes a URL or the name of an environment variable holding one. It runs, in one transaction, and reports each step:

  1. preflight — refuses to run as one of the app's own roles, or as a role that is neither the platform admin (postgres; postgres_managed in the emulation; or --admin-role NAME) nor a superuser. A superuser only warns — fine on a local cluster or in CI; a managed provider hands out none. Also refuses a schema that exists but belongs to another role (it never takes a schema over), an existing role that is not a plain LOGIN role, a database without schema extensions, and a requested extension installed outside extensions;
  2. roles — CREATE ROLE <migrator> / <app> LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS where missing. Passwords are refused when empty, a placeholder (change_me and the like), shorter than 16 characters, not printable ASCII, trivially guessable or identical; they are sent as SCRAM-SHA-256 verifiers computed client-side (so the plaintext is in no server log) and never printed. An existing role keeps its password unless --reset-passwords — use that after a restore, which may drop custom role passwords. Because an existing role keeps it, both --*-password-env flags are optional: a run whose roles all exist reads no password, so re-provisioning (a later deploy, or adding --identity-schema to a live deployment) needs none and should not be made to carry eight secrets it will not use. A role that must be created without one is refused by name, against pg_roles, with nothing committed; --reset-passwords needs both flags and is refused without them before anything connects;
  3. GRANT <migrator> TO CURRENT_USER — since PostgreSQL 16 a CREATEROLE role gets ADMIN but not SET on the roles it creates, and CREATE SCHEMA … AUTHORIZATION needs SET;
  4. CREATE SCHEMA IF NOT EXISTS <schema> AUTHORIZATION <migrator>;
  5. REVOKE ALL ON SCHEMA <schema> FROM PUBLIC; GRANT USAGE ON SCHEMA <schema> TO <app>;
  6. GRANT USAGE ON SCHEMA extensions TO <migrator>, <app> (pg_trgm operator classes and extension functions resolve through it), then verified — PostgreSQL only warns when the grantor lacks the grant option, so a grant that did not take is a clear error;
  7. with --identity-schema NAME --identity-owner ROLE (both or neither), the shared identity schema: the owning app's run — the one whose migrator is --identity-owner — creates it (AUTHORIZATION) and takes it away from PUBLIC; every app's run grants USAGE on it to its own two roles and verifies that the grant took. Each app grants only its own roles, so the grants accumulate one provisioning run at a time and no script ever enumerates every app's role names. A module's run refuses by name when the schema is not there yet, naming the app to provision first;
  8. ALTER ROLE <migrator>, <app> SET search_path = <schema>[, <identity schema>], extensions; ALTER ROLE <migrator> SET statement_timeout = '30min' (some providers cap statements at a couple of minutes; migrations and restores can take longer);
  9. CREATE EXTENSION IF NOT EXISTS <name> WITH SCHEMA extensions for each --extension;
  10. REVOKE <migrator> FROM CURRENT_USER (and the identity owner, where it is a different role), so nobody with dashboard SQL access can SET ROLE to the migrator and rewrite an audit log. (A CREATEROLE admin keeps ADMIN OPTION on the roles it created and could grant itself membership again: this removes the standing membership, it is not a wall.);
  11. verify the end state (role attributes, owner, ACLs, settings, extension placement, membership, and the identity schema's owner and grants) and roll everything back if any of it does not hold.

It is idempotent, never touches public and never drops anything. Exit 0 = done, 1 = refused or failed (rolled back, nothing changed), 2 = could not run.

Without a shell (the provider's SQL editor), --sql-only renders the same steps as one plain SQL script with change_me placeholders. Each app commits the rendering as db/managed/provision.sql; the operator pastes it into the editor, replaces the two passwords there (never in the committed file) and runs it once as the platform admin. The script refuses to create a role with a placeholder, and re-running it is safe. The file cannot drift, because each app's CI re-renders it:

python -m dredd_core.managed provision --sql-only --schema galena --app-role galena_app \
    --migrator-role galena_migrator --output db/managed/provision.sql           # write (UTF-8, LF)
python -m dredd_core.managed provision --sql-only --schema galena --app-role galena_app \
    --migrator-role galena_migrator --check-file db/managed/provision.sql       # CI: exit 1 = stale

The same two entry points in Python (dredd_core.provisioning, re-exported by dredd_core.managed):

provision_sql(*, schema: str, app_role: str, migrator_role: str, extensions: Iterable[str] = (),
              statement_timeout: str = "30min", admin_role: str | None = None,
              identity_schema: str | None = None, identity_owner: str | None = None) -> str

provision(connection, *, schema: str, app_role: str, migrator_role: str,
          app_password: str | None = None, migrator_password: str | None = None,
          extensions: Iterable[str] = (), statement_timeout: str = "30min",
          admin_role: str | None = None, identity_schema: str | None = None,
          identity_owner: str | None = None, reset_passwords: bool = False,
          on_step: Callable[[ProvisionStep], None] | None = None) -> list[ProvisionStep]

provision runs inside the caller's transaction (the caller commits; on ProvisionError, or a ProvisionRefused raised by the server-side preflight, it must roll back). A password is needed only to create a role or, with reset_passwords, to reset one. ProvisionStep is (status, title, detail) with status "ok" or "warn". check_passwords(app_role, app_password, migrator_role, migrator_password) is the password rule on its own.

To remove an app later, as the platform admin in one transaction (checked on the emulation): GRANT <migrator>, <app> TO CURRENT_USER; DROP SCHEMA <schema> CASCADE; REVOKE USAGE ON SCHEMA extensions FROM <migrator>, <app>; DROP OWNED BY <migrator>, <app>; DROP ROLE <app>, <migrator>; — the admin needs the membership back to drop what the migrator owns, and the USAGE on extensions was granted through the admin's own grant option, so it is revoked explicitly.

A shared identity schema

One account per person across a whole deployment. It is two phases, and neither can move to the other side:

phase who runs it what it does
A the platform admin, once per app the schema, its owner, REVOKE … FROM PUBLIC, GRANT USAGE to that app's two roles, and that app's search_path — provision --identity-schema/--identity-owner, above
B the identity owner's migrator, in its own Alembic revision CREATE TABLE, then the per-tier table and column grants for every app's roles

A cannot move into B: a migrator is created NOCREATEROLE and holds no CREATE on the database, so CREATE SCHEMA fails, and ALTER ROLE <other role> SET search_path needs privileges it does not have. B cannot move into A: you cannot GRANT SELECT (email, …) on a table that does not exist yet, and a grant that silently skips a missing table is exactly what this family banned.

Phase B, in the owning app's revision:

from dredd_core.identity_schema import create_identity_tables
from dredd_core.schema import (
    account_delete_guard_sql, session_update_guard_sql, shared_identity_grants_sql,
)

def upgrade() -> None:
    conn = op.get_bind()
    create_identity_tables(conn, "dredd")             # schema-qualified: see below
    op.execute(shared_identity_grants_sql(
        "dredd",
        owner_role="atrium_migrator",                 # must be the connected role
        writer_role="atrium_app",                     # the hub: the only writer of identity
        reader_roles=("galena_app", "sygna_app", "counsel_app"),
        migrator_roles=("galena_migrator", "sygna_migrator", "counsel_migrator"),
    ))
    op.execute(account_delete_guard_sql("dredd", owner_role="atrium_migrator"))
    op.execute(session_update_guard_sql("dredd", owner_role="atrium_migrator",
                                        writer_role="atrium_app"))
role app_user session module_permission
the identity owner OWNER OWNER OWNER
writer_role — the hub SELECT, INSERT, UPDATE SELECT, INSERT, UPDATE SELECT, INSERT, UPDATE, DELETE
reader_roles — the modules SELECT of READABLE_USER_COLUMNS only SELECT, UPDATE of SESSION_UPDATE_COLUMNS SELECT
migrator_roles — their migrators SELECT, REFERENCES — —
anon, authenticated, service_role, PUBLIC — — —
  • No write of any kind on module_permission for a module. A module that could write its own permission rows could admit anyone, promote anyone and promote itself — which is the entire reason the table is in the hub's keeping rather than in each module's schema.
  • No INSERT on session for a module. The row carries a user_id and a token hash, so a module that could insert one would mint a valid credential for the administrator. That is "become anyone".
  • No INSERT or UPDATE on app_user for a module — that is "create or elevate anyone".
  • No privilege of any kind on password_hash / failed_login_count / locked_until for a module, which is survivable only because those three columns are deferred on the model: without that, resolve_session_full's db.get(AppUser, …) names all ten columns and every authenticated request in every module fails on "permission denied for column password_hash". AuthService undefers them on the one path that needs them, so a standalone login is still one query.
  • No DELETE or TRUNCATE on app_user / session for anyone. Revocation is revoked_at, deactivation is is_active = false. account_delete_guard_sql closes the remaining hole — the identity owner, which holds DELETE by owning the table — with a BEFORE DELETE OR TRUNCATE trigger, because the cross-schema ON DELETE CASCADEs mean one DELETE would destroy rows in every other app's schema whatever privileges the deleting role holds there.
  • No module revives or prolongs a credential. The three-column UPDATE on session covers every row and every value, so on its own it would let any module set revoked_at = NULL on a session the hub revoked, or push the administrator's expires_at to infinity. session_update_guard_sql adds a row-level BEFORE UPDATE trigger that, for every role but the owner and the writer, refuses any change to revoked_at once it is set, any later expires_at except a live app token sliding to at most idle_days from now, and a change to any other column. Signing out, last_seen_at and the slide keep working unchanged.

The block revokes before it grants, so it is authoritative rather than additive: a column privilege somebody added by hand is gone after a re-run. It refuses to run as anyone but owner_role, refuses a missing table or a missing role rather than skipping it, and verifies the outcome — with three distinct messages, because a tier that did not take (the owner does not own the table), identity escalation (a reader that can write accounts or mint sessions) and permission escalation (a reader that can write who may use which module) are three different accidents.

The app's own schema stays first on the search_path, or alembic_version and every new domain table would land in a schema the app's migrator does not own. The cost of that correct choice is that a local app_user would silently win — and everything would keep working, with two rows per human. Two things guard it, and both are needed: create_identity_tables emits schema-qualified DDL so the owning app's own revision cannot build the shadow by accident, and assert_identity_schema runs in the application's lifespan, because a deploy-time check catches it when you deploy and only a boot assertion catches it after a restore.

own_tables(Base.metadata, shared=SHARED_IDENTITY_TABLES if settings.identity_schema else ())
assert_identity_schema(conn, own_schema=settings.db_schema, identity_schema=settings.identity_schema)

own_tables is the one place an app asks "which tables are mine?", and three callers need it: a fresh install's create_all (or it builds the shadow), a backup's sweep (or one module's archive carries every account on the platform), and a restore's DELETE pass (or it dies on a table the module holds only SELECT on, mid-incident).

For the one-off merge, dredd_core.identity_schema also renders repoint_identity_fks_sql (the ALTER TABLE pairs that move an app's foreign keys onto the shared app_user, derived from the metadata and the naming convention) and orphan_rows_sql / permission_grant_orphans_sql — count orphans, raise, in the same transaction. The second one exists because permission_grant.principal_id carries no foreign key (it is polymorphic on principal_type), so nothing else will ever say a word about a row the merge missed.

"Names no account" has two causes, and the check separates them, because only one of them is a merge's doing and only one of them a re-run can fix:

the id is verdict why
still an account of the app's own schema RAISE EXCEPTION, nothing committed the repoint was told to rewrite exactly those ids, and did not
in neither store RAISE WARNING, left alone no account, no e-mail, nothing to map it to — an account somebody DELETEd rather than deactivated leaves its grants behind, because the column carries no foreign key and PostgreSQL performs no referential action

Refusing over the second kind is what made a cutover un-retryable: the local app_user is gone by the time anybody re-runs it, so the check could no longer tell the two apart and blamed the merge for both — advising "map every old account id to its merged one (match on e-mail)" for an id that exists in neither schema. A merge cannot be the cause once the local table is gone, anyway: the run that dropped it passed this very check in the same transaction. permission_grant_orphans_query is the count behind that warning as a plain SELECT, for the revision to read back and log — a RAISE WARNING from inside a DO block reaches the PostgreSQL log and no human, because pg8000 collects server notices on the connection and nothing ever prints them.

Who may do what in a module

One account across the platform, and one table that says what it may do in each module — dredd.module_permission, one row per person per module:

answer source
no access to that module at all no row — the default for everybody
may use it role = 'user'
may use it and administer it (its /admin/* routes) role = 'moderator'
everything, everywhere, no row needed app_user.is_admin — the platform administrator

role is text with a CHECK, never a PostgreSQL enum, for the reason node.kind and session.kind are text: adding a value must not mean a migration in four schemas. It is rendered from MODULE_ROLES so Python and the constraint cannot drift.

The absence of a row is the point. Before this table a person with an account could type /galena and be let in — they saw an empty drive, but nothing had refused them, and "you can see nothing" is not an access decision. Nothing here can be granted or revoked from inside a module: the enforcement is the missing INSERT/UPDATE grant, not a missing menu item. Revoking is a hard DELETE, never a flag — a soft delete makes every reader responsible for WHERE revoked_at IS NULL, and a module that forgets keeps a revoked moderator, fail-open, in the one place that cannot afford it. role is the one mutable field: promoting a user to moderator is an UPDATE of a row that stays, so who admitted them and when survives it.

The hub's own slug is never in this table, for both roles: every account may open the launcher, so a 'user' row would say nothing, and the hub has administrators — its administration is not delegable a module at a time. The hub passes its own slug as hub_slug; core never knows which app is the hub.

from dredd_core import authz
from dredd_core.moderation import ModerationPolicy, ModerationService

_moderation = ModerationService(ModerationPolicy(
    module_slug=settings.module_slug,                    # "galena"; "" standalone
    shared_permissions=bool(settings.identity_schema),   # platform mode
))
authz.bind_moderation(_moderation)                       # once, at startup

The reads are module_role() (None / "user" / "moderator", memoized per Session), may_use() and is_moderator() on top of it, assert_may_use() / assert_moderator() at an app's edge, and module_roles() / moderated_slugs() / moderator_ids() / member_ids() / list_permissions() for a roster. The writes — grant() (which also promotes and demotes), revoke(), revoke_module() — are the hub's alone and answer ConflictError anywhere else.

A standalone app leaves shared_permissions at False: module_role then answers "moderator" for an administrator and "user" for everyone else, emitting no SQL at all. Everyone with an account may use the one app there is, is_moderator is user.is_admin, and putting assert_may_use at the edge is a no-op — so nothing about a standalone app's behaviour changes. In platform mode a moderator resolves as manager on every node, exactly where is_admin already sits, through three call sites — opening a node, listing nodes, and who is notified about a review. Miss the second and a moderator sees an empty drive whose items open fine when deep-linked; miss the third and moderators silently stop being told about anything. A plain 'user' row grants none of that: using a module is not a role in its tree.

bind_moderation is deliberately not an overlay. Overlays are restrict-only precisely so no registered callback can widen access, and a design that needed one to grant would invert that single safety property. Here the app supplies no predicate: it supplies a ModerationService, a core type whose only app-provided input is which module this is — a slug. The worst an app can get wrong is naming the wrong module.

Connections

  • Through the provider's pooler in session mode (port 5432 on the poolers the family knows) or the direct connection — never a transaction-mode pooler port (6543 on those poolers: no prepared statements, and open bugs such as a backend returned to the pool with a transaction open). Some poolers require the tenant in the user name: a role logs in as <role>.<tenant>.
  • ?sslmode=verify-full&sslrootcert=/run/certs/db-ca.crt on every URL. Download the provider's root CA from its dashboard (it is usually not in system trust stores); one CA file serves the whole database.
  • Connection budget. All four apps share the database's connection limit (a small managed instance allows something like 60–90). A make_engine engine holds up to pool_size + max_overflow connections (default 5 + 10 = 15), so four apps at the defaults can take all 60 before a migration, a restore or the dashboard gets one. Size the instance for it, or on a small one set DB_POOL_SIZE=3 and DB_MAX_OVERFLOW=2 for each app (4 × 5 = 20). Each app passes its pool knobs to make_engine from config; migrate, restore and seed engines use NullPool.
  • Coupling. A point-in-time or backup restore rewinds all four apps together. Per-app restore paths are the apps' own backups (Galena's and Sygna's). A provider's restore may drop custom role passwords — re-run provision with --reset-passwords afterwards.

What core supplies

  • The TLS rule. One rule for every app and the /dredd template, with no provider host lists: a database host counts as local when it is "", localhost, 127.0.0.1, ::1 or postgres (dredd_core.db.LOCAL_DATABASE_HOSTS) or listed in the app's 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. require_verified_tls(url, local_hosts=...) raises ValueError with a message that never carries the password; is_local_host(host, extra=...) is the predicate.

  • TLS. make_engine accepts ?sslmode=verify-full&sslrootcert=/run/certs/db-ca.crt. pg8000 has no sslmode: SQLAlchemy passes URL query parameters straight to pg8000.connect (a TypeError), and pg8000's default tries TLS without verification and silently falls back to plaintext. make_engine strips the parameters and builds connect_args["ssl_context"]: require (encrypted, unverified; pg8000 then refuses a server without TLS), verify-ca (chain verified against an explicit CA file), verify-full (chain and host name; sslrootcert absent or system = the system trust store). disable / allow / prefer raise ValueError — they permit plaintext. As in libpq, require with a CA file verifies the chain, and sslrootcert=system is accepted only with verify-full. URLs for libpq-based drivers (psycopg) pass through untouched.

  • Grants. runtime_grants_sql() (above) also strips the API roles (anon, authenticated, service_role) of every privilege in the schema, including the migrator's default privileges for them, and skips those roles where they do not exist (a plain local cluster).

  • Preflight. python -m dredd_core.managed check, connected as the app's runtime role (or its migrator):

    python -m dredd_core.managed check --url DATABASE_URL --expect-user galena_app --expect-schema galena \
        --require-tls --app-role galena_app --migrator-role galena_migrator [--append-only audit_log ...] \
        [--no-delete conflict_check ...] [--system-schema NAME ...] \
        [--identity-schema dredd --identity-tier reader]
    python -m dredd_core.managed check --url MIGRATION_DATABASE_URL --expect-user galena_migrator ...
    

    It only reads (inside a READ ONLY transaction it rolls back) and reports: TLS from both ends (sslmode in the URL; pg_stat_ssl on the server, which behind a pooler shows the pooler's own link), the server version, a connecting role that is neither a superuser nor the platform admin (with --expect-user ROLE, exactly that role: nothing else notices the migrator's credentials in the runtime URL, which pass every other finding), the current schema (public, or not the --expect-schema, fails), a search_path that starts with that schema (fails with --expect-schema, warns without; warns when extensions is missing from it), table owners (never a superuser or the platform admin; with --migrator-role, every table and view is owned by exactly that role), the runtime role's append-only / no-delete tables, the migrator owning the schema (with --migrator-role; a session as the migrator warns below a 30-minute statement_timeout), cross-schema isolation, and any privilege an API role holds in the schema. The transaction-pooler port 6543 fails. --url takes a URL or the name of an environment variable (default DATABASE_URL); passwords are never printed. Exit 0 = pass (warnings allowed), 1 = a check failed, 2 = it could not run.

    Isolation covers the runtime role, the --migrator-role and the connected role: each must hold no USAGE or CREATE on, and own nothing in, any other schema — whether granted directly, through a role membership or to PUBLIC — and no privilege on a table, view, sequence or function there. Two things are tolerated: a function's default EXECUTE for PUBLIC (unreachable without USAGE on its schema), and the default USAGE every role has on public through PUBLIC (CREATE on public, or any object privilege there, fails). Extension-owned objects and these schemas are skipped: every pg_* schema, pg_catalog, information_schema, extensions, and the schemas a managed platform's own services keep — auth, storage, realtime, _realtime, graphql, graphql_public, vault, pgsodium, pgsodium_masks, net, cron, pgbouncer, _analytics (dredd_core.provisioning.SYSTEM_SCHEMAS); --system-schema NAME ... adds a provider's further ones.

    The shared identity schema is the one exception, and --identity-schema NAME is how it is stated rather than skipped: the name leaves that negative sweep (the OK line says so, so a passing report shows the exception was deliberate) and a positive finding takes its place, one per role — identity <role> — naming exactly what it may reach and asserting it reaches nothing else in that schema. --identity-tier says what this app is to it: reader (a module: column-restricted SELECT on app_user, SELECT and a three-column UPDATE on session, SELECT on module_permission), writer (the hub) or owner (the hub, whose migrator owns the schema and its tables). A migrator that really owns the schema is measured as the owner whatever the flag says — ownership carries every privilege there and no REVOKE undoes it, so measuring it as a module's migrator would report the one role this design trusts most as an identity escalation, on a correct deployment, at the moment somebody is deciding whether to proceed with a cutover; the OK line then names the tier it used, so the command can be corrected. --identity-tier owner therefore asserts ownership — a role that claims it and does not own the schema still fails — rather than selecting the rules. A breach gets its own title — identity escalation <role> for a reader that can write accounts or mint sessions, permission escalation <role> for one that can write who may use which module — because those are different accidents and a title greps. identity shadow fails when the app's own schema holds a same-named table, which is the failure with no other symptom; identity tables fails when one of the three is missing; search_path fails when the identity schema is not on it (otherwise every shared table resolves nowhere, and the first sign is "relation app_user does not exist" inside a request); and the API-role sweep runs a second time against that schema, because an auto-generated API reaching the platform's accounts would be worse than it reaching any app table. A passing line reads, in full:

    [OK  ] identity galena_app: in dredd: USAGE, no CREATE, owns nothing; app_user: SELECT (id,
           created_at, updated_at, email, full_name, is_admin, is_active), nothing at all on
           password_hash/failed_login_count/locked_until; module_permission: SELECT; session: SELECT,
           UPDATE (last_seen_at, expires_at, revoked_at); nothing else in dredd
    

python -m dredd_core.managed emulate --superuser-url URL --database NAME --password-env VAR is TEST-ONLY. It turns a plain PostgreSQL database, connected to as a real superuser, into a managed-Postgres lookalike for CI and local tests: a non-superuser admin role with CREATEROLE / CREATEDB / BYPASSRLS, the API roles anon / authenticated / service_role with the default grants on public a provider's auto-generated API relies on, and an extensions schema with pgcrypto and uuid-ossp. The emulated admin role is called postgres_managed; on a managed provider the same role is postgres (a local cluster already has a superuser named postgres). Roles are cluster-wide while the grants are per database, so emulating a second database of the same cluster reuses the roles: an existing postgres_managed keeps its password unless --password is given, or --password-env together with --reset-password. It refuses to run without a superuser, against a host that is neither loopback nor on a private network (--allow-remote for a remote test server of your own — never a managed service), or on a server carrying a managed platform's own objects (its gateway, dashboard and pooler roles; its auth / storage / realtime / graphql_public / vault schemas).

What this rests on — provider know-how, kept generic; re-check it against your provider before relying on it:

  • Managed providers commonly offer Postgres 15 and 17, not 16, which the family targets locally; dredd-core's CI therefore runs on 16 and 17.
  • A provider's direct connection may be IPv6-only (Docker containers usually lack IPv6); its shared pooler is IPv4, with a session-mode port and a transaction-mode port — use session mode.
  • TLS is often optional on the server side by default. Verification needs the provider's root CA — downloaded from its dashboard, not in system trust stores — and verify-full.
  • The provider's postgres admin is not a superuser (CREATEROLE, CREATEDB, LOGIN, REPLICATION, BYPASSRLS) but may read every table: anyone with dashboard SQL access reads every app's data. Providers reserve role names for their platform (anon, authenticated, service_role, authenticator, dashboard_user, pgbouncer, their own prefixes). Only the admin has search_path = "$user", public, extensions; new roles get the default, which is why provisioning sets it.
  • An auto-generated API exposes schema public by default. A table the admin creates there may get SELECT / INSERT / UPDATE / DELETE for the API roles through default privileges; a table another role (the migrator) creates does not. Keep app schemas out of that API, or switch it off.
  • pgcrypto and uuid-ossp are usually pre-installed in schema extensions; pg_trgm is available. gen_random_uuid() is core since PostgreSQL 13.
  • Backups and point-in-time restores rewind the whole database, and a restore may not carry custom role passwords — re-run provision with --reset-passwords after one.

Not yet confirmed on a real managed project (the local emulation is PostgreSQL 16 with postgres_managed): that the hosted admin may GRANT <migrator> TO postgres, CREATE SCHEMA … AUTHORIZATION and GRANT USAGE ON SCHEMA extensions to custom roles (provisioning stops with a clear error if the last does not take); that custom roles' search_path / statement_timeout settings survive the provider's own configuration; custom-role logins through the pooler's session mode and after a restore; certificate host-name checks against the direct and the pooler host.

Custom fields and saved table views

Two opt-in modules (v0.13.0), ported from Compass's contract register (Tobiasz Badura, Apache-2.0): dredd_core.custom_fields lets a module's moderator add fields to a record type from the console (kinds text / number / date / choice / boolean, at most 30 active per entity, a key made from the first label and never changed, nothing ever deleted — archived), and dredd_core.table_views saves which columns a console table shows, their order, widths and sort — the user's own view, else the firm's default, else the one built into the code.

import dredd_core loads neither. An app opts in by importing them from its models package, which registers custom_field, table_view and the enum type custom_field_kind on Base.metadata (so create_enum_types, create_all and own_tables include them; table_view.user_id references app_user, so repoint_identity_fks_sql covers it on the platform). One table serves every record type: custom_field.entity ("contract", "matter", "lead" …) is chosen by the app's code, never by a user, and the key is unique per (entity, key).

entity is a record name in the singular (contract); table_key is a list or route in the plural (contracts).

Kind codes. CustomFieldKind (PG enum type custom_field_kind) holds codes, never labels:

code a value is the console's label (i18n, the app's)
text a string, 1..500 characters after trimming Tekst / Text
number a decimal string, at most 4 places, |x| < 10^14 Liczba / Number
date YYYY-MM-DD Data / Date
choice the key of one of the field's options (single choice; a multiple one would be multi_choice) Lista / Choice
boolean true / false (an empty field is no value, not a third kind) Tak/nie / Yes/no

choice and boolean are the filterable kinds (FILTERABLE). A refusal's extra.kind carries the code.

The entity registry. Every entity is declared once at startup, as a table is, and every custom-field operation looks it up first:

from dredd_core.custom_fields import EntitySpec, register_entity, registered_entities
from dredd_core.table_views import TableSpec, register_table

register_entity(EntitySpec("matter"))   # or register_entity("matter"); before its TableSpec
register_table(TableSpec(key="matters", entity="matter", ...))
[e.key for e in registered_entities()]  # ["matter"], sorted: what the module reports to Atrium
  • EntitySpec(key) checks the name against ENTITY_PATTERN (^[a-z0-9_]{1,40}\Z): a malformed one is a ValueError at import.
  • register_entity is idempotent for an identical spec (a module imported twice), a ValueError for a different spec under a taken key, a TypeError for anything but an EntitySpec or a name — the rules of register_table. Both registries are plain per-process dicts filled at import, before any request, so neither takes a lock.
  • entity(name) returns the spec or raises NotFoundError (404, code entity_unknown), as table_views.table(table_key) raises table_unknown. Every operation (all_fields, by_key, get, create, update, values_after) does that before any SQL, so a typo ("contrat") fails at its first call instead of quietly starting a second set of fields, and a route that takes the entity from its path (/fields/{entity}) answers 404, not 500 — the same reasoning as an unknown table_key.
  • register_table refuses (ValueError) a TableSpec whose entity is not registered yet, so a typo there is found at startup.
  • registered_entities() lists this process's entities. A registry is per process: the platform's list is the union of what each module reports.

What an app adds:

  1. An idempotent revision like Compass's 0011_register_config: the type in a DO $$ block that looks in current_schema() (not create_enum_types, which would make the revision change with future models), CREATE TABLE IF NOT EXISTS custom_field / table_view with their constraints spelled out (uq_custom_field_entity_key, the two ck_custom_field_* key CHECKs, uq_table_view_table_key_user_id NULLS NOT DISTINCT — PostgreSQL 15+ — and the user FK ON DELETE CASCADE), then the runtime grants again. Neither table is evidence: the runtime role keeps plain DML on both. A fresh database already has everything from 0001's create_all.
  2. A JSONB values column per entity: custom_fields JSONB NOT NULL DEFAULT '{}' on the record table, written only through custom_fields.values_after(db, entity, stored, sent) (assign the result: JSONB notices reassignment only), the record's own audit diff carrying custom.<key>.
  3. One TableSpec per console table, registered once at import: register_table(TableSpec(key="matters", entity="matter", columns={...}, builtin_columns=(...), required="name", sorts=frozenset({...}), default_sort="-created_at")).
  4. Thin routes: GET/POST/PATCH .../fields/{entity} → all_fields / create / update; GET/PUT/DELETE /views/{table_key} → current / save_own / delete_own; PUT/DELETE /views/{table_key}/default → save_firm_default / delete_firm_default; a list route sorts with sort_expression(Model.custom_fields, active_field(fields, key)).nulls_last() plus a tie-breaker, and filters with filter_expression. The moderator gate (require_moderator) on every definition write and on the firm's default is the app's: core takes the actor and audits it.
  5. A console panel (fields + the view picker) that shows detail as it is (Polish) and covers every code of custom_fields.MESSAGE_CODES / table_views.MESSAGE_CODES.

Rules to keep:

  • Keys never reach SQL text. Every key matches ^[a-z0-9_]{1,40}\Z (and a CHECK says so), yet sort and filter still pass it — and the option labels — as bound parameters only (->> with a parameter). In the console a key travels through data-*, a label is user data: escape it.
  • Strict on write, lenient on read. A save naming an unknown or archived column is a 422; a stored view that stopped holding is read without the parts that no longer hold, so a list always loads. An archived field's or option's value already stored stays saveable, and can always be cleared.
  • Serialized writes. Every definition write takes pg_advisory_xact_lock(0x44434346, hashtext(entity)) before any row lock (no 31st field, no duplicate key, no racing renumber); every write of a firm default takes pg_advisory_xact_lock(0x44435456, hashtext(table_key)), so its audit "before" is the default in force.
  • Audit with a diff, never on a no-op: custom_field.create / custom_field.update (detail = the entity; each field a move renumbers gets its own row), table_view.firm_default (detail = the table). A user's own view is a preference: not audited, keyed only by the signed-in user's id, and deleted with its user.
  • Refusals are core ValidationError (422) / NotFoundError (404): detail = the Polish sentence, extra = {"code", "en", ...params}. A malformed EntitySpec or TableSpec is a programming error (ValueError), not a 422; an unregistered entity or table is a 404.

Naming

Everything core defines — tables, columns, enum types and their values, message codes — uses English snake_case codes, as core always has (viewer, editor, review_required, app_token, read_write, and now text … boolean). A module's domain vocabulary stays in the module and is decided there: Compass's WorkflowState (w_toku) and its contract card's fact types (kwota, okres, klauzula) are Compass's and core does not touch them. Human text is never a code: the PL/EN labels live in the app's i18n layer, and the database stores the code. (The Polish detail of a refusal is a sentence for a human, not a code; its code is extra.code.)

0.13.0 notes

  • New, opt-in: dredd_core.custom_fields and dredd_core.table_views (above).
  • After Tobiasz Badura's review: CustomFieldKind uses English codes (tekst→text, liczba→number, data→date, lista→choice, tak_nie→boolean; the type is still custom_field_kind); entities are registered (EntitySpec, register_entity, entity, registered_entities, new code entity_unknown), and register_table requires its entity registered; the naming rule and the singular/plural rule above.
  • Adopting from Compass's register: in the revision that turns register_field into custom_field, rename the type's values in place (no row is rewritten — values on records never store the kind, and views store custom.<key>): ALTER TYPE <old type> RENAME VALUE 'tekst' TO 'text', likewise liczba→number, data→date, lista→choice, tak_nie→boolean, guarded by a catalog check so the revision stays idempotent.

The cross-site write guard and the audit-log reader

Two more opt-in modules (v0.14.0), promoted from code every app carried a copy of. import dredd_core loads neither, and neither imports a web framework.

  • dredd_core.cross_site.cross_site_write_refused(method, headers, allowed_origins) -> bool is the decision behind each app's app-wide deps.refuse_cross_site_write: unsafe methods without a bearer token must carry Sec-Fetch-Site: same-origin|none, and an Origin (when present) must name the request's own Host and be neither null nor blank, unless it is listed in CORS_ALLOW_ORIGINS. It returns a bool, so each app keeps its own dependency and raises its own error in its own language:

    from dredd_core.cross_site import cross_site_write_refused
    
    def refuse_cross_site_write(request: Request) -> None:
        if cross_site_write_refused(request.method, request.headers, get_settings().cors_origins_list):
            raise AuthorizationError("Cross-site request refused.")
    

    On the platform's one origin it separates the platform from foreign sites only, never one module from another; never list a family origin in CORS_ALLOW_ORIGINS (a listed origin skips both checks). SAFE_METHODS and bearer_token(headers) are exported too.

  • dredd_core.audit_log.list_entries(db, *, limit=100, offset=0, action=None) -> list[dict] is the read side for Administration → Audit: newest first (ties by id), action a literal prefix ("module."), each row with its actor's actor_email; limit clamped to 1..500.

0.14.0 notes

  • New, opt-in: dredd_core.cross_site and dredd_core.audit_log (above). No schema change, no migration, nothing an app must do on repin.
  • Surveyed and not promoted, because the copies behave differently: slugify (four copies: "Dział" gives dzial in Atrium and Sygna but dzia in Galena and Compass; Galena and Sygna fall back to item with no length cap, Atrium and Compass refuse an empty slug and cap it at 80 — and slugs are stored, so unifying changes new addresses) and typed settings (only Atrium's is closed and typed; Galena, Sygna and Compass accept open keys with per-app rules).

Model providers

An opt-in module (v0.15.0), ported from Compass's providers (Tobiasz Badura, Apache-2.0): which language models the platform may call, who may use them, and their API keys. import dredd_core does not load it; importing dredd_core.model_providers registers four tables (MODEL_PROVIDER_TABLES): model_provider (the card: name, kind, base_url, models, region, processor_name, dpa_url, trains_on_data, allowed_for, is_active, key_prefix, key_mode, enabled_by, timestamps), model_provider_policy (one row: level, eu_only), model_provider_key (provider_id, api_key_encrypted) and, since 0.18.0, model_provider_user_key (provider_id, user_id, api_key_encrypted, key_prefix).

On the platform they live in the shared identity schema, beside module_permission, and follow its rule: the hub writes, modules read. Standalone they sit in the app's own schema like any table.

role model_provider model_provider_policy model_provider_key model_provider_user_key
the identity owner OWNER OWNER OWNER OWNER
writer_role — the hub SELECT, INSERT, UPDATE SELECT, INSERT, UPDATE SELECT, INSERT, UPDATE, DELETE SELECT, INSERT, UPDATE, DELETE
reader_roles — the modules SELECT SELECT — —
key_reader_roles — opted-in modules (Compass) SELECT SELECT SELECT —
migrator_roles — those that reference a provider SELECT, REFERENCES — — —
PUBLIC, the API roles — — — —

The keys are a table of their own, not a column hidden from the reader grant (as app_user.password_hash is). A hidden column only works with deferred on the model — every ORM load in every module must leave it out, or the whole read fails with "permission denied for column" — and it makes the reader grant a column list that must grow with the card, where a forgotten column is unreadable and a wrong one is readable. A separate table makes the safe state the default: a module has no grant at all on it, and opting one in is a single table SELECT. A screen in any module still says whether a key is set: model_provider.key_prefix (six characters) is on the card.

The opt-in is key_reader_roles in the hub's grant block — for a module that calls a model itself (Compass's analyses). Home's "ask the model" runs in the hub, which reads keys as the writer, so atrium_app needs no opt-in and Galena, Sygna and Counsel get none. The block is authoritative: it strips every privilege any role but the owner holds on the three tables (table and column grants) before granting, so removing a module from key_reader_roles and re-running is what revokes its keys. managed check proves both directions — --model-provider-keys says the app is opted in:

without --model-provider-keys with it
the role cannot read the keys ok — model_provider_key: nothing at all fail — model_provider_key: no SELECT
the role can read the keys key exposure ok — SELECT (opted in to the keys)

A module that can write a provider or the policy fails as provider escalation; a module-schema copy of model_provider fails as model provider shadow. On a platform without the tables nothing changes.

The key at rest is the caller's ciphertext. api_key_encrypted is opaque: writes take an encrypt callable, api_key(db, provider, decrypt) — the one door out — a decrypt callable. Core holds no encryption key and adds no dependency. The hub and every opted-in module derive the same key from one deployment secret (e.g. MODEL_PROVIDER_SECRET, Argon2id via dredd_core.security.derive_key then AES-256-GCM, as Compass does today with SECRET_KEY); it is never in the database, so a dump is ciphertext and a restore without the secret leaves keys unreadable — the right failure.

The policy. Codes are English (README, "Naming"), narrowest first; allowed_for on a provider may only narrow the level. No policy row reads as admins_only with eu_only on: a fresh platform fails closed, and an unknown value never widens.

code Compass's code who may use a provider
nobody nikt nobody — the administrator included; the area is empty for everyone
admins_only tylko_admin an administrator (the default)
everyone kazdy everyone who may use the calling module

LEGACY_POLICY_CODES is that mapping, for the adopting revision. Who is an administrator is the caller's decision, passed as is_admin: the hub passes app_user.is_admin, a module its moderation.is_moderator(db, user) (which includes the administrator) — what Compass asks today. With eu_only, a provider is offered only if its region (ISO 3166 alpha-2) is in EU_EEA, or it is local; the EU "flag" a screen shows is stays_in_the_eu(provider), derived, never stored.

Reads: offering(db, model_id, *, is_admin) → (provider, model) or None; offering_to_an_administrator(db, model_id) (alias offered_to_an_administrator) tells "nobody here may" from "an administrator may, you may not"; usable_providers, visible (everything for an administrator, the usable ones for everyone else, nothing at nobody), for_reading (404, never 403), known_model_ids. Writes (the hub, or a standalone app): create, update (partial; clear= names what to empty; kind never changes), disable (the default way out — a run records its provider), delete_unused (a disabled provider no run points at; 409 provider_still_active / provider_in_use otherwise), set_policy. All refusals are coded ValidationError / NotFoundError (extra.code, Polish detail, English extra.en; MESSAGE_CODES). Every write is audited through dredd_core.audit: model_provider.create / .update / .disable / .delete / .policy, with a diff in which a key is only ever "set" / "replaced".

The call target comes only from this table (SSRF). A caller posts to provider.base_url as offering returned it, with the model from that row — never a URL, host or provider from the request; a request names a model id at most. That is also why writes are strict: check_base_url takes http(s) only, an IP literal or a well-formed DNS name, a valid port, no user name or password, no fragment, and for a local provider only LOCAL_HOSTS (localhost, 127.0.0.1, ::1, host.docker.internal) — an app whose local model runs in a sibling container passes local_hosts={"qwen"} explicitly. check_models wants at least one model, each with a non-empty, unique id; context_window a positive whole number when given; dialect openai (default), chatml or anthropic (the native Messages API — Anthropic documents its OpenAI-compatible endpoint as not production-ready).

Whose key a call carries: key_mode (0.18.0), one source per provider and never a fallback, so it is always clear who paid for a call:

key_mode the key written by
firm (default) the administrator's, model_provider_key the hub's admin screen (create / update)
user the calling person's own, model_provider_user_key that person, through the hub (set_user_key / clear_user_key)
none no key (a local model, a self-hosted server without authentication) —

A personal key never widens anything: the administrator still decides whether the provider exists, who may use it and whether it stays in the EU, and a person can neither add a provider nor name an address. model_provider_user_key is the hub's alone — no module may reach it, the key opt-in included — and managed check reports any grant on it to a module as key exposure.

  • set_user_key(db, *, actor, provider, api_key, encrypt, is_admin) → the six-character prefix. Refused as a 404 unless provider.key_mode == "user" and actor may use it now; audited as model_provider.user_key with only "set" / "replaced" in the diff.
  • clear_user_key(db, *, actor, provider) → whether there was one. Never refused by the policy: a person can always take their key back.
  • user_key_prefix(db, provider, user_id) → what the person's own screen shows.
  • key_for(db, provider, *, user_id, is_admin, decrypt) → (key | None, source), the one door out for every mode. It applies the policy on every call: once the administrator narrows the level, sets allowed_for, turns on eu_only or disables the provider, a stored personal key stops working (404), whatever is in the table. (None, "user") — no key stored — is the caller's refusal to make ("add your key"); (None, "none") is not a refusal.
  • A personal key never follows the provider to a new address. The administrator owns base_url, the person owns the key: an update that changes base_url, or moves key_mode away from user, deletes every personal key of that provider (audited as user_keys: [n, 0]), and each person enters theirs again for the new target.
  • Nor does the firm's. A stored key was entered for one address, and the next call sends it to whatever base_url says. So an update that changes base_url while a key is stored is refused (base_url_needs_key, 422) unless the same call sends api_key for the new target or clear={"api_key"}. Refused rather than cleared, so correcting an address never loses a key unannounced; whatever the key_mode, because a key left stored is sent again once the mode returns to firm.

0.15.0 notes

  • New, opt-in: dredd_core.model_providers (above); MODEL_PROVIDER_TABLES / MODEL_PROVIDER_KEY_TABLE in dredd_core.identity (names only); managed check --model-provider-keys. Nothing changes for an app that does not import the module, and check on a platform without the tables reports exactly what it did.

  • Atrium (the hub), one revision, as atrium_migrator, after the identity tables:

    from dredd_core import model_providers as mp
    
    def upgrade() -> None:
        conn = op.get_bind()
        mp.create_model_provider_tables(conn, "dredd")      # schema-qualified, idempotent
        op.execute(mp.model_provider_grants_sql(
            "dredd", owner_role="atrium_migrator", writer_role="atrium_app",
            reader_roles=("galena_app", "sygna_app", "counsel_app", "compass_app"),
            key_reader_roles=("compass_app",),              # the opt-in: Compass calls models itself
            migrator_roles=("compass_migrator",),           # analysis.model_provider_id references it
        ))
        for sql in mp.model_provider_import_sql(            # only while Compass moves in
                "dredd", owner_role="atrium_migrator", importer_role="compass_migrator"):
            op.execute(sql)
    

    Import the module from Atrium's models package; add MODEL_PROVIDER_TABLES to the shared= of its own_tables call only if Atrium's backup should leave them out (as the hub it owns them, so it keeps them in). Then the admin screens (providers + policy; the key goes in through encrypt, comes back only as key_prefix) and, later, the Home endpoint: streaming "ask the model", session and policy checked on the server (offering(db, model_id, is_admin=user.is_admin), refusing when it is None or usable_providers is empty), the target and key taken only from the row, a rate and response-size limit, and an audit row per call (who, which provider and model, when — never the question). In the next revision, op.execute(mp.drop_model_provider_import_sql("dredd")); check warns while the door is open. Prove it: managed check --identity-schema dredd --identity-tier owner.

  • Compass, one revision (as compass_migrator, after Atrium's):

    1. Read the local model_provider rows and its model_providers_policy / model_providers_eu_only settings; run every row through mp.check_base_url / mp.check_models (the door relies on CHECK constraints only); decrypt each key with its SECRET_KEY-derived key and re-encrypt it under the platform's MODEL_PROVIDER_SECRET; map the codes (LEGACY_POLICY_CODES, also for allowed_for) and set key_prefix from the plaintext.
    2. SELECT import_model_providers(CAST(:providers AS jsonb), CAST(:keys AS jsonb), CAST(:policy AS jsonb)) — ids are kept, so analysis.model_provider_id stays valid. It refuses if the platform already has providers (it seeds once, never edits).
    3. Drop fk_analysis_model_provider_id_model_provider, drop the local model_provider, and add the foreign key again, naming dredd.model_provider (DDL run once — the 0007 exception); delete the two settings. Guard every step with a catalog check so the revision is idempotent.
    4. Code: delete models/model_provider.py and import ModelProvider from dredd_core.model_providers (same table name, so mappings and FKs keep their names); services/providers.py becomes thin over core — usable_providers(db, actor) → mp.usable_providers(db, is_admin=moderation.is_moderator(db, actor)), offering(db, actor, m) → mp.offering(db, m, is_admin=...), api_key(provider) → mp.api_key(db, provider, decrypt), "provider.created" → model_provider.create; the routes' writes go to the hub (they become 409 on the platform, like account writes); ProviderKind → the kind text codes; the console's labels for nobody / admins_only / everyone. Backup and boot assertion: own_tables(shared=SHARED_IDENTITY_TABLES | MODEL_PROVIDER_TABLES) and assert_identity_schema(..., tables=SHARED_IDENTITY_TABLES | MODEL_PROVIDER_TABLES).
    5. Prove it: managed check ... --identity-schema dredd --identity-tier reader --model-provider-keys.
  • Galena, Sygna, Counsel: nothing until they show the list. Their roles are in reader_roles and check without the flag proves they cannot read a key; an app that imports the module adds MODEL_PROVIDER_TABLES to own_tables(shared=…) and assert_identity_schema(tables=…).

0.18.1 notes

  • dredd_core.routes.iter_routes. From FastAPI 0.15x include_router appends one _IncludedRouter per router to app.routes, so a plain walk sees no API route: a console wrapper asking matches answers 404 instead of 405 + Allow, and route-sweep tests find nothing and pass. Walk iter_routes(app.routes) instead; it uses FastAPI's iter_route_contexts where it exists and the flat list otherwise. No new dependency, no schema change.

0.18.0 notes

  • dredd_core.model_providers: key_mode on model_provider (KEY_MODES, check_key_mode, create(key_mode=) / update(key_mode=)), the table model_provider_user_key (MODEL_PROVIDER_USER_KEY_TABLE in dredd_core.identity), set_user_key, clear_user_key, user_key_prefix, key_for, model_provider_key_mode_sql, and the anthropic dialect. The grant block and managed check cover the new table; the import door carries key_mode.

  • Atrium (the hub), one revision, as atrium_migrator, in this order:

    def upgrade() -> None:
        conn = op.get_bind()
        op.execute(mp.model_provider_key_mode_sql("dredd"))   # the column; every provider stays "firm"
        mp.create_model_provider_tables(conn, "dredd")        # adds model_provider_user_key only
        op.execute(mp.model_provider_grants_sql("dredd", ...)) # the same arguments as in 0.15.0
    

    All three are idempotent. Then the code: the call path takes its key from key_for (not api_key), refuses "add your key" on (None, "user"), and audits the source; the admin card gets key_mode; a person's own screen writes through set_user_key / clear_user_key and shows user_key_prefix.

  • Order on a running platform: the hub first. A module on 0.18.0 whose managed check meets the 0.15.0 tables reports model provider tables as failed (model_provider_user_key is missing) until the hub's revision has run. Modules need no revision and no code change: they never touch personal keys, and key_mode is one more readable column on the card. A module that calls a model itself (Compass) cannot read personal keys, so for now it should use only firm and none providers: a user provider is Home's.

JSON responses declare UTF-8

An opt-in module (v0.16.0), promoted from Insider's edge. Starlette sends raw UTF-8 under a bare application/json / application/problem+json (it appends a charset to text/* only), and Windows PowerShell 5.1's Invoke-RestMethod decodes such a body as Latin-1: "Rozporządzenie" arrives as "RozporzÄ…dzenie". dredd_core.json_charset appends ; charset=utf-8 to any application/json or application/*+json content type that declares no charset, and touches nothing else (HTML, text/*, text/event-stream, NDJSON, binary). It never buffers a body. import dredd_core does not load it, and it imports no web framework.

  • In a pure-ASGI security-headers middleware (Galena, Sygna, Counsel, Compass, Insider), one line in the send wrapper: ensure_json_charset_message(message).
  • In an @app.middleware("http") edge (Atrium): resp.headers["content-type"] = ensure_json_charset(...); for raw header lists built by hand (Atrium's front door): ensure_json_charset_headers(headers).
  • With no such edge: app.add_middleware(JsonCharset), outermost.

0.16.0 notes

  • New, opt-in: dredd_core.json_charset (above). No schema change, no migration. Each app adopts it in its own edge and adds a test that sweeps its parameter-free routes and problem responses.

One search contract for every module

An opt-in, standard-library-only module (v0.17.0): dredd_core.search_contract. Atrium's Home (and later the command palette and the chat) makes ONE request per module, GET <module>/api/v1/search?q=&limit=, and reads ONE shape: {"version": 1, "q": str, "hits": [{kind, kind_label?, title, subtitle, link, id, score?, updated_at?}], "truncated": bool}.

  • Rule 1: authorisation stays in the module. A module returns only what the caller may see; the hub shows every hit it gets and re-checks nothing.
  • link is the module's own console route relative to its root (the hash route without #/; the hub opens <module root>#/<link>). A record without a valid route is dropped or falls back to a coarser route that exists.
  • normalize_query, is_searchable (2+ characters, else an empty 200), clamp_limit (default 10, max 50, garbage is the default), make_hit, make_response (pass limit + 1 candidates for an honest truncated), and validate_response for each module's conformance tests.
  • The hub always sends format=v1. A module whose legacy body has no hits answers the contract on every call, legacy keys alongside; one whose legacy body already uses hits (Galena, Counsel) switches on format=v1.

0.17.0 notes

  • New, opt-in: dredd_core.search_contract (above). No schema change, no migration.

Subjects of work: Galena documents or plain files (0.19.0)

Three opt-in modules for the Compass split (work package R2). None registers a table or a grant.

module_client — Sygna's Galena connector, generalised. A call carries the acting person's token (keyword-only, no default, never stored on the client; token=None only for a module's open endpoints such as Galena's /meta), goes to the callee's public base URL (<site>/galena, the platform's front door — no internal service names), and runs inside one time budget that covers connect, status and the whole body. http(s) only, no credentials in the address, no redirects (refused, not followed), no proxy from the environment, a bounded body, and no token, query or path in an error. No retries. Standard library only (urllib).

plain_files — DATA_DIR/files/<uuid>: one file = one id, written once (open(..., "xb")), no overwrite, folders, versions or listing. response_headers is Galena's /raw rule for every module: types outside INLINE_MEDIA become application/octet-stream + attachment, and every answer carries X-Content-Type-Options: nosniff and Content-Security-Policy: default-src 'none'; sandbox.

document_ref — a subject is exactly one of

DocumentRef(module="galena", document_id, path, commit_sha, sha256)   # with Galena
FileRef(file_id, sha256, size, name)                                  # without it: plain_files

sha256 is over the decrypted bytes, and every read verifies it. SubjectRefMixin puts the columns ref_module, ref_document_id, ref_path, ref_commit_sha, ref_file_id, ref_file_size, ref_file_name, ref_sha256 on the module's own table with ck_<table>_subject_ref_one_shape (exactly one shape, complete) and ck_<table>_subject_ref_sha256; no foreign key across modules. A model with its own __table_args__ adds *SubjectRefMixin.subject_ref_constraints(). A DocumentRef is read through Galena's GET /projects/{document_id}/raw?path=…&ref=<commit_sha>&download=true as the acting person; pin_document pins a path's last commit (/file-info) and hashes its bytes. D9: read() refuses a DocumentRef with no Galena client (409 galena_disabled); a FileRef always reads. D15: move_to_documents uploads a FileRef into a Galena folder, verifies the hash at the returned commit, then deletes the plain file; the caller stores the new DocumentRef with set_ref.

0.19.0 notes

  • New, opt-in: module_client, plain_files, document_ref. No schema change to core or the shared identity tables, no new grants: the mixin's columns live in the module's own table.
  • Adopting SubjectRefMixin is a migration in the module (new columns + the two CHECKs).

Module events (0.20.0)

Opt-in (dredd_core.events), for the Compass split (work package K1). One module says something happened; another acts on it later. Three tables register on import:

  • module_event — the log. id, txid (the writer's pg_current_xact_id()), source_role (default current_user), source_module (the sender's slug, a label), kind (<area>.<what>), payload (JSONB), created_at. Standalone it is in the module's own schema; on the platform in the shared identity schema, created by the hub (create_event_tables(conn, "dredd")), guarded by event_policies_sql("dredd") and granted by event_grants_sql("dredd", owner_role=…, emitter_roles=[hub_app, galena_app, compass_app, …]): SELECT, INSERT for each emitter and nothing else for anyone — no UPDATE, DELETE, TRUNCATE.
  • Row-level security: one policy lets a role insert only rows whose source_role is itself, one lets everybody read; any other policy on the table is dropped (permissive policies are OR-ed). So galena_app cannot write an event that claims to be compass_app's. Enabled, not forced: the owner (never a runtime role) bypasses it, which is what lets a restore put rows back as they were.
  • module_event_cursor, module_event_receipt — the receiver's own, in its own schema in both shapes. receive(db, consumer="galena", handlers={kind: fn}, sources={kind: roles}) locks the cursor row, reads only rows of transactions that have ended (txid below the snapshot's xmin, so no event can ever appear behind the cursor), writes one receipt per handled event (skipping one already received) and moves the cursor — all in the caller's transaction. At least once, idempotent on event.id. A handler answers applied or ignored; an event of a kind in sources from any other role is recorded refused and not handed on.
  • The payload is a flat object of identifiers and numbers (check_payload): snake-case keys, values null / bool / int / finite float / UUID / an identifier string (letters, digits, . _ : -, no space, no slash, ≤ 128). Never a file name, a title or a sentence: every taking part module reads every event.
  • managed check --events says this app takes part: its role must INSERT + SELECT the log and nothing more (event tampering), without the flag it must reach nothing (event exposure); the hub's runtime role always takes part; RLS and its two policies are proved wherever the table is (event forgery), and a local copy beside the shared one is an event shadow.

First events: document.version_added, workflow.approved, document.signed, negotiation.round_received, analysis.accepted (FIRST_EVENTS, documentation, not an allowlist).

0.20.0 notes

  • New, opt-in: dredd_core.events. EVENT_TABLES / EVENT_RECEIVER_TABLES in dredd_core.identity (names only). managed check gains events= / --events and the findings above; nothing changes for a deployment without module_event.
  • Hub (Atrium): one revision, as the identity owner — create_event_tables, then event_policies_sql(schema), then event_grants_sql naming its own runtime role and every taking part module's. Deploy it before any module that emits.
  • Module, standalone: its own revision creates the three tables, runs event_policies_sql() (the current schema) and re-runs runtime_grants_sql with module_event and module_event_receipt in append_only. On the platform: only the two receiver tables are local; a local module_event is a shadow, and the backup sweep and boot assertion name EVENT_TABLES with the identity tables.

Counterparties (0.21.0)

dredd_core.counterparties (opt-in) is the platform's one register of counterparties (the Compass split's K2, Tobiasz's D10): counterparty, counterparty_alias, counterparty_contact, in Compass's shape (spec 2026-10-09 kontrahenci, KH2: Sygna's column names, numbers as digits) with kind as text. Every module that opts in reads it; the link from a contract, matter or document to a counterparty stays in the module, as its own foreign key. Writers are opt-in roles: Sygna; without Sygna, the module that needs counterparties (Compass). The hub migrates and grants and holds no counterparty logic.

tier counterparty counterparty_alias, counterparty_contact
reader SELECT SELECT
writer SELECT, INSERT, UPDATE — archived, never deleted SELECT, INSERT, UPDATE, DELETE
a module's migrator SELECT, REFERENCES SELECT on aliases only
not listed, and the hub's runtime role nothing nothing
  • Keys: normalize (Sygna's, the search_key, search only) and match_key (legal forms kept, one spelling, every script kept; "" matches nothing). clean_nip/krs/regon with check digits. writable(db) asks the database whether the connected role may write what the search_path reaches, so a module answers a refused write with its own 409, never a 500.
  • Deduplication (resolve, plan_import): the same NIP, then the same KRS; else a non-empty match_key equal to exactly one counterparty of the same kind (name, then alias) whose numbers do not contradict — its empty numbers are filled; anything else is a new row (ambiguous or contradicting matches are never guessed). A merged row's name becomes an alias of the survivor; its aliases and contacts move over.
  • Moving rows in: a module's migrator plans with read_register(conn, identity) + plan_import, and writes with import_counterparties(conn, plan, schema=identity) through the hub's SECURITY DEFINER door import_counterparties(...) (counterparty_import_sql, executable by the listed migrators, insert-only plus filling NULL numbers, ON CONFLICT DO NOTHING, so a re-run is a no-op). Standalone the same plan is written straight into the module's own tables (schema=None). The module repoints its own foreign keys by plan.mapping.
  • Registries: dredd_core.registries (no tables) maps the KRS and Biała lista answers (normalize_krs, normalize_vat), moved from Compass; the HTTP and the per-firm switch stay in the module.
  • managed check --counterparties reader|writer proves the tier (counterparty tampering for a write the tier must not hold, counterparty exposure for a module not opted in that reaches the tables, counterparty shadow for a local copy, a WARN while the import door exists). Without the flag the app role must reach nothing there — so a module still on an older core, whose check does not know the tables, keeps passing as long as the hub does not list it.

0.21.0 notes

  • New, opt-in: dredd_core.counterparties, dredd_core.registries; COUNTERPARTY_TABLES / COUNTERPARTY_TIERS in dredd_core.identity (names only). Nothing changes for a deployment without the tables.
  • identity_schema.repoint_identity_fks_sql now also skips the three counterparty tables: a module whose metadata carries them (it imports the register) must not try to re-point the hub's counterparty.created_by during its identity cutover.
  • Hub (Atrium): one revision as the identity owner — create_counterparty_tables(conn, identity), then counterparty_grants_sql(identity, owner_role=…, writer_roles=…, reader_roles=…, migrator_roles=…), then the door while a module still has rows to bring (counterparty_import_sql / drop_counterparty_import_sql). Deploy it before the modules.
  • Module: own_tables(shared=SHARED_IDENTITY_TABLES | COUNTERPARTY_TABLES) on the platform (backup sweep, 0001, boot assertion); its revision moves its rows in and points its foreign keys at <identity>.counterparty. Standalone the three tables are its own.

Model access (0.22.0)

dredd_core.model_access (opt-in, no tables, needs pip install "dredd-core[models]") is the one model client of the family, moved out of Compass's app/agents/ byte for byte (Compass split, K3) so no module keeps its own:

  • schema: build_schema(rules, clauses) / validate — the grammar an answer is forced into (clause_ids an enum of the contract's own ids, four closed verdicts).
  • client: AskSpec, ask_with, ask, the DIALECTS table (openai, chatml) and the measured SAMPLING per model id. The body on the wire is pinned by tests/fixtures/zlote-cialo/.
  • loader: the one-model-at-a-time slot and loading/unloading on a local model server.
  • compute: a verdict checked against the figures of the paragraphs it points at; it only ever takes a verdict away.

Inputs are plain data and a provider's address: no session, no ORM, no settings. Which providers and keys a person may use stays in dredd_core.model_providers; a module that calls a model is opted in to --model-provider-keys by the hub. The station/hardware protocol comes with the first module that runs one (Arbiter, P4).

0.22.0 notes

  • New, opt-in: dredd_core.model_access and the models extra (httpx). Nothing else changes.
  • Module: keep the old import paths as aliases (sys.modules[__name__] = <core module>), not import * re-exports, so a test that monkeypatches app.agents.client.<name> still patches the module that runs.

Stats contract (0.23.0)

dredd_core.stats_contract (opt-in, standard library only, no tables) is the second read contract of the family, built like the search one (P10 of the Compass split, work package M4). Panorama, the platform's dashboard, asks every configured module GET <module>/api/v1/stats with the acting person's own session token and reads one shape:

{"version": 1, "module": "galena", "as_of": "2026-11-12T10:00:00+00:00",
 "tiles": [{"key": "contracts", "label": "Umowy", "count": 12, "link": "cards"}]}
  • Authorisation stays in the module, as in search: a tile counts only what the caller may see.
  • A tile equals its list: count is exactly the number of rows the caller sees on the screen link opens (the module's own hash route, without #/, the search contract's link rule). A number a module cannot promise that for is not a tile.
  • A tile is key (machine code, unique in the response), label (the module's wording), count (non-negative integer), link, and an optional as_of; at most 12 tiles. No content: no title, name or anything a person typed.
  • Module side: make_tile, make_response (both validate), validate_response for conformance tests.
  • Dashboard side: gather({slug: base_url}, token=…, timeout=3.0) asks every module in parallel through module_client (no redirects, no proxy, bounded body, one time budget) and never raises: each module is one line with status ok · absent (no base URL configured) · no_access (401/403, the person has no module_permission row there) · unavailable (timeout, unreachable, 5xx, 404, a body that is not the contract) and a machine reason. A disabled or absent module is a status, never an error page.

History and trends are not in this contract: they come from the event log (below), as aggregates.

The event log's reader tier (0.23.0)

event_grants_sql(..., reader_roles=[...]) grants SELECT alone on the shared module_event to a module that reports on the log and writes nothing (Panorama). The block verifies it (event tampering for a reader that can INSERT, UPDATE, DELETE or TRUNCATE), and a role is an emitter or a reader, never both. managed check --events-reader (check(..., events="reader")) proves the tier from the module's side. Every row is readable to every reader, as to every emitter: the payload is identifiers and numbers by construction, and a reader shows aggregates.

0.23.0 notes

  • New, opt-in: dredd_core.stats_contract. No schema change, no migration.
  • event_grants_sql gains reader_roles (default empty: the 0.20 block, unchanged in effect); managed check gains --events-reader. Hub (Atrium): to admit Panorama's trends, add panorama_app to reader_roles in its event-grant revision.
  • K4 (the chat), planned as 0.23.0 in the Compass split plan, was then moved to 0.24.0; 0.24.0 went to the Workflow contract instead (below), and K4 takes a later release.

0.23.1 notes

  • model_providers.update refuses to move base_url while a key is stored unless the same call sends api_key or clear={"api_key"} (base_url_needs_key, 422). No schema change. Only the hub writes providers, so Atrium is the one app whose behaviour changes; the rest repin to stay identical.

0.23.2 notes

  • New: model_providers.delete_unused(db, actor=, provider=) deletes a disabled provider that no run points at, its firm and personal keys with it, audited as model_provider.delete. Refused with 409 provider_still_active or provider_in_use. "In use" is the database's answer, not a list in core: every module's foreign key to model_provider is RESTRICT, so a module core does not know is covered too. Why: an API key that expires after a day used to leave a provider on the list for good, disabled.
  • Grants: the writer (the hub) gains DELETE on model_provider (still nothing on the policy); managed check now requires it of the writer. Hub (Atrium): no revision — atrium-migrate re-applies model_provider_grants_sql after every upgrade, so the repin grants it. No schema change; modules repin to stay identical.

Workflow contract (0.24.0)

dredd_core.workflow_contract (opt-in, no tables; it does not even import dredd_core.events) is what the platform's Workflow module (slug workflow) and the modules around it agree on. Workflow holds every approval run — on a Galena document, on a plain file, on a request such as an expense — and the others talk to it in two ways only: they read its events from the shared module_event log (Galena moves a contract card to "zatwierdzona") and they start a run with the acting person's token.

  • Kinds: workflow.started, workflow.approved, workflow.rejected, workflow.cancelled, workflow.signed_on_paper (KINDS; STARTED, APPROVED, …). SOURCE_MODULE = "workflow".
  • Who emits: only Workflow's runtime role workflow_app. source_module is a label anyone may write, so a receiver passes sources={kind: {"workflow_app"}} for each kind it handles to events.receive, and calls parse on every payload: a row in the log is untrusted input.
  • The payload — identifiers and numbers only, inside events.check_payload: run_id, actor_id, subject_kind (document · file · request, SUBJECT_KINDS), an optional stage, and the subject's ids: a document's module, document_id, commit_sha, sha256; a file's file_id, sha256; a request's request_type. No names, no content: a document's path and a file's name never enter the shared log (every taking part module reads every event). The receiver reads the document by document_id + commit_sha through Galena's API.
  • API:
    • payload(*, run_id, subject, request_type, actor_id, stage=None) → dict — subject is a DocumentRef or a FileRef, or None with a request_type; exactly one of the two, else ValidationError (subject_and_request_type / subject_missing).
    • parse(event_payload) → WorkflowEvent (frozen: run_id, subject_kind, document_module, document_id, commit_sha, file_id, sha256, request_type, actor_id, stage; the fields of the other subject kinds are None). Anything malformed is a ValidationError with a code, never a KeyError or TypeError.
    • WorkflowClient(client: ModuleClient).start(*, token, subject, template_id=None, note=None) → StartResult(run_id, link) — POST /runs with the acting person's token (keyword-only, no default; empty → ValidationError), so Workflow's own authorization decides. The body carries the whole document_ref.to_dict(subject), path included: it goes to one module's API, not into the log. An error answer raises as ModuleResponse.raise_for_status maps it; a 2xx without a valid run_id and a #/… link is a ModuleCallError. The link is a console route relative to Workflow's root (#/runs/<run_id>).
  • The engine is not in core. Templates, stages, who approves what: all of it lives in the Workflow module, the one home of every run (decided 2026-11-18). Core carries only what both sides must agree on, so a change to how approvals work is a release of one module, not of the family.

0.24.0 notes

  • New, opt-in: dredd_core.workflow_contract. No schema change, no migration.
  • request_type is [a-z0-9][a-z0-9_]{0,39}: a lower-case key of at most 40 characters that does not start with _ (an event identifier starts with a letter or digit).
  • events.FIRST_EVENTS: the comment on workflow.approved now names Workflow as its sender (it was "Compass (later Workflow)"). Comment only, no behaviour change.
  • Not here: the workflow_app grants in the event log — the hub adds it to emitter_roles in its event-grant revision before Workflow emits.

0.25.0 notes

  • model_access.client.build_prompt: a rule may carry step_id, step_name, step_instruction (a skill's step). Each new step_id gets a ## Krok: <name> header, and the instruction under it, inside the rules fence. Rules without step_id ask byte for byte as before (golden test unchanged); build_schema ignores the extra keys. No schema change, no migration.

Chat contract (0.26.0)

dredd_core.chat_contract (opt-in, standard library only, no tables) is K4 of the Compass split: what a module tells the platform's chat. The chat's rule is code finds, the model reads: the browser reads each module with the asker's own session, ranks one-sentence records against the question and gives the best ones to the model as numbered sources, with no tools. Instead of a hand-written reader per module in Atrium, a module may answer GET <module>/api/v1/chat/records?offset=&limit= with:

{"version": 1, "module": "galena", "as_of": "2026-11-25T10:00:00+00:00", "next_offset": null,
 "records": [{"key": "galena:umowa:1f0c", "kind": "umowa", "title": "UM-2026-0017 Najem biura",
              "text": "Umowa UM-2026-0017 „Najem biura”, kontrahent ACME, obowiązuje do 2027-01-31.",
              "link": "cards/1f0c", "labels": ["UM-2026-0017", "ACME"],
              "at": "2026-11-25T10:00:00+00:00"}]}
  • Authorisation stays in the module: a page holds only what the caller may read.
  • A record is one sentence about one thing: key (<module>:<kind>:<id>), kind (a lower-case word the chat may name), title, text, link (the search contract's link rule, so every cited source opens), optional labels, at, members. Bounded: 500 records a page, next_offset pages on (null on the last, and a page without the key is refused), title 300 and text 2000 (both cut at a word with … by make_record), 10 labels of 200, 200 members of 300.
  • Text is content and stays with the asker: it goes to the asker's browser and the model they chose, nowhere else. Actions (a contract check, an approval run) are not records; the chat routes them in code.
  • Module side: make_record, make_page(module, records, total=..., offset=...) (both validate; total is required, so a module cannot forget it and end pagination after one page), page_params (clamped offset and limit), validate_page for conformance tests. The consumer is Atrium's console (JavaScript).

0.26.0 notes

  • New, opt-in: dredd_core.chat_contract. No schema change, no migration.
  • search_contract.link_ok is public (the link rule every contract shares); _link_ok stays as an alias.

0.26.1 notes

  • New: schema.session_update_guard_sql(identity_schema, *, owner_role, writer_role), one DO block for the identity owner's revision, after shared_identity_grants_sql. It closes a gap the module tier's column grant left open: a module could un-revoke any session and extend any credential's expiry. Nothing changes for a module; the hub adds one revision. Standalone apps are not affected.

What deliberately stays app-side

The HTTP edge (cookies, error handlers, request wiring), node-tree CRUD (it depends on the app's own node-kind registry), and each app's domain tables. Core owns the schema and the permission algorithm; apps own tree manipulation and how requests reach it.

Development

pip install -e ".[test]"
DREDD_CORE_TEST_DATABASE_URL=postgresql+pg8000://postgres@localhost:5432/dredd_core_test pytest -q

DB-backed tests skip when that variable is unset. The connecting role must be able to DDL: the test conftest creates the enum types and tables itself (the URL may carry sslmode / sslrootcert). The grants, check, emulate and most provision tests create their roles, schemas and extensions inside the rolled-back test transaction, so the cluster keeps nothing. CI runs the suite against Postgres 16 and 17.

tests/test_shared_identity.py provisions a hub and a module into one emulated database and then proves the tiers the only way that proves anything: by running real statements as each role and watching PostgreSQL refuse them. A unit test that the rendered SQL mentions a column is not the same as a role that cannot read it.

tests/test_provision_live.py is the exception: it provisions five apps into the test database for real (committed roles and schemas, logins as each role, the CLI end to end) and drops everything again when the module ends, so it needs DREDD_CORE_TEST_DATABASE_URL to be a superuser. Every role and schema any test creates starts with DREDD_CORE_TEST_ROLE_PREFIX (default dct_) plus a random tag. The platform admin is DREDD_CORE_TEST_ADMIN_URL when set — e.g. postgres_managed on a database prepared with emulate — or a temporary NOSUPERUSER CREATEROLE role otherwise:

DREDD_CORE_TEST_DATABASE_URL=postgresql+pg8000://postgres@localhost:5432/dredd_core_test \
DREDD_CORE_TEST_ADMIN_URL=postgresql+pg8000://postgres_managed:pw@localhost:5432/dredd_core_test \
DREDD_CORE_TEST_ROLE_PREFIX=me_ pytest -q tests/test_provision.py tests/test_provision_live.py

The real-TLS tests need a server that requires TLS, and skip otherwise:

DREDD_CORE_TLS_TEST_URL=postgresql+pg8000://user:pw@127.0.0.1:54330/some_db \
DREDD_CORE_TLS_TEST_CA=/path/to/ca.crt pytest -q tests/test_tls_connection.py

DREDD_CORE_TLS_TEST_URL carries no sslmode (the tests add it); the server certificate must name the URL's host, and the CA file must be the one that signed it.

S
Description
No description provided
Readme Apache-2.0
614 KiB
Languages
Python 100%