Skip to content

Architecture Crosscutting Concepts

Mohammad Rasoul Kazemi edited this page Nov 29, 2026 · 3 revisions

Architecture Crosscutting Concepts

This page is arc42 chapter 8: the concepts that apply to several building blocks. Security is summarised here and described in full on Security Model; the data side is on Data Security and Data Quality and Integrity. Settings are listed on Configuration.

Security

  • Accounts are PostgreSQL roles (ADR 0015). Cluster permissions are membership in kingres_admin > kingres_ops > kingres_readonly > kingres_stats. Every request re-derives the role's cluster roles from pg_roles and pg_auth_members, so a disabled or dropped role loses its sessions at once (finding CP-02). Memberships in dangerous predefined roles, or in roles with SUPERUSER, REPLICATION or BYPASSRLS, are refused (CP-05). LDAP and OIDC are not supported in the first release (LDAP, GSSAPI and PAM are designed by phase 16, not built).
  • One guard for every REST operation, in this order: node-state gating, cross-site check, rate limit for operations without a session, authentication (bearer token, session cookie or one-time setup token), CSRF check for cookie sessions, role check against x-required-role of the contract, validation of query parameters (unknown ones are 400), then the handler and the audit. The role table is generated from openapi.yaml, so there is no hand-kept copy.
  • Server to server: a cluster certificate authority (ECDSA P-256) and mutual TLS on an internal API with its own listener. It authenticates by client certificate only, checks the revocation list, authorises by a fixed table of calls per peer, and never runs a path, program name or SQL text taken from a request, with one exception (a statement-execution call only the leader may make, logged with length and hash). Sharding connections between nodes use the server certificate and no password. The trust model is stated: every server of a cluster is fully trusted.
  • Extension trust: the service role is a superuser and opens sessions in databases whose owners are not trusted, so before it reads or calls anything in the schema kingres of a user database, extguard checks that the extension and its schema belong to a superuser and that nothing foreign is in the schema; the extensions check their own schema in every install and upgrade script (details on Security Model).
  • Limits that remain: the key of the certificate authority is held by the manager leader; its escrow to the standbys of the map group is off until an administrator switches it on, and without it the new leader after a map group failover raises certificateAuthorityUnavailable until the operator restores pki/ca.key and pki/revoked.json from a backup; the publication listener of the ledger is public by design.
  • Reporting: vulnerabilities go to the private channel of SECURITY.md, not to a public issue.

Secrets

Secret Where it lives Protection
Role passwords PostgreSQL stored and synchronised as SCRAM-SHA-256 verifiers computed in kingresd, never plain
Service role password <data-dir>/service-credentials mode 0600; service connections use the instance's unix socket
Setup token <data-dir>/setup-token owner-only file; only its name is logged
Certificate authority key pki/ca.key on the manager leader; with the escrow switched on, a sealed copy on each server that hosts a ready standby of the map group file; clear text on the leader; a cold copy of the data directory must be treated as a secret, and a server that holds an escrow copy can become the authority
Master key of the transfers <data-dir>/transfer.key (setting transfer-key-file), outside the staging directory exported tables and databases are staged as files sealed in 64 KiB segments with AES-256-GCM
Cluster secret of kingres_shard held by each node of the cluster (check_cluster() reports secret_missing for a node without it) tags the names of prepared transactions with an HMAC; kingres.rotate_secret() refuses while tagged transactions are in doubt
Ledger signing keys ledger-keys-dir (default <data-dir>/ledger/keys) Ed25519 files, mode 0600 in a 0700 directory; sealed with PBKDF2-HMAC-SHA256 and AES-256-GCM when ledger-key-passphrase-file is set, otherwise in clear text and kingresd logs a warning; the passphrase is read from a file, never from the environment or the command line
Anchor target credentials <ledger-keys-dir>/anchor/<id>.json write-only through the API; never returned, logged, audited or stored in a task row

Logs, the audit file and alerts never carry statement text, passwords or tokens: the managed PostgreSQL configuration sets log_min_error_statement = panic, log_statement = none and log_min_duration_statement = -1, and local settings cannot override them (finding CP-03).

Configuration

  • kingresd: precedence, lowest to highest, is built-in default, JSON config file (-config), environment variable KINGRES_*, command-line flag. Unknown keys and invalid values stop the server at start.
  • Cluster settings (replica count, automatic failover, ledger publication and anchoring, clock tolerance and others) live in the system database and are changed through the REST API and the console.
  • PostgreSQL parameters (phase 13, built): set for the cluster, a server group, one server or a database; a narrower level beats a wider one; rendered into kingres-config.conf, never through ALTER SYSTEM; a parameter that needs a restart is shown as pending.
  • Extension settings are PostgreSQL GUCs (kingres_shard.*, kingres_ledger.*).

Observability

  • Logs. kingresd writes structured access logs without query strings, headers or bodies; log-format is text or json. listLogs answers for the whole cluster from any server and needs kingres_ops; each server caps a message at 8 KiB.
  • Metrics. No metrics store is bundled (ADR 0020): kingresd samples into an in-memory ring buffer for the console charts (empty after a restart) and serves the Prometheus text format at /metrics, which needs a stats-role token or metrics-token. queryMetrics merges the servers, with at most 2000 series.
  • Alerts. Kept per server in kingres_cp.alert, one open alert per kind and subject, severities info, warning, critical; cluster-wide reads name servers that did not answer (partial, missingServers). The kinds include server liveness (serverSuspect, serverDown), leases and replication (leaseLost, groupWithoutSynchronousStandby, groupUnderReplicated, replicationPending), failover (failoverNeedsDecision, failoverBlocked, failoverDataLoss, splitPromotion, autoFailoverTriggered, autoFailoverLimitReached), certificates, clocks, versions, extensions (extensionSchemaUntrusted, extensionSkipped) and the ledger (ledgerChainDiverged, ledgerSignerUnavailable, ledgerNotAnchored, ledgerAnchorFailed and others). The complete list with causes is on Monitoring and Alerts; the source is the AlertKind schema of the contract.
  • Audit. Every administrative operation is written to audit.jsonl (audit-file) with the request id and the actor, control characters replaced; listAuditEvents reads it. Failed sign-ins and rejected setup tokens are events of their own.
  • Request id. Every response carries X-Request-Id, copied into the problem body and the audit event.
  • In the extensions: kingres.check_cluster() (shard), kingres.ledger_status, ledger_verify, table_change_report, EXPLAIN annotations of the scan and pushdown paths.

Error handling

  • REST: errors are RFC 9457 problem documents (application/problem+json) with type, title, status, detail, instance and a stable machine-readable code from the ProblemCode enumeration. Clients branch on code and must tolerate unknown codes. Groups: 400 and 422 for bad input, 401 and 403 for identity, 409 for state conflicts (for example rebalance_in_progress, failover_in_progress, no_replica_available), 429 rate_limited and workbench_busy, 503 for what cannot be served now (node_uninitialized, map_group_unavailable, leader_unavailable, quorum_unavailable, system_database_stopped). Panics become 500 internal_error and are logged with the stack. See REST API Reference.
  • SQL: the extensions raise their own codes. KS001 means the bucket map or the extension version changed while the statement ran, and the statement may be repeated. KS006, KS007, KS009, KS012 and KS014 are answers of the control calls that the control plane reads by SQLSTATE; 0A000 is an unsupported or forged fragment; 40P01 is a distributed deadlock. A list is on Troubleshooting.
  • Tasks: long operations are tasks with steps, a lease and an epoch; every write of a run proves the lease, so a superseded holder records nothing; a time-out of a call is read as "did not finish" and the step asks the callee for its state. A step that touched the outside world is idempotent on repeat.
  • Never a wrong answer for a faster answer: the complete scan stays as the fallback and a faster path that cannot prove its conditions does not raise an error (ADR 0022).

Compatibility across PostgreSQL majors

One source of every extension builds and passes its regression and TAP suites on PostgreSQL 18 and 19. Differences live in one compatibility header per extension (src/pg_compat.h); code outside it does not test PG_VERSION_NUM. The same SQL scripts run on every major. The control plane, the console and the verifier do not depend on the major; where kingresd writes a setting or reads a catalog that differs, it asks the server for its version. A cluster runs one major, and adding a server of another major is refused (version_mismatch); moving a cluster between majors is not designed (ADR 0023).

Compatibility inside a major: the REST contract is versioned (0.34.0, 178 operations) and is checked against the server in both directions; the internal API is not versioned for new calls, an older server answers 404 not_found, which is read as "older version". Extension upgrades go by ALTER EXTENSION ... UPDATE; for example a database whose ledger SQL is older than the installed library must update before its ledger is written again. See Upgrades.

Other concepts

  • Licence headers: every new own file carries an SPDX header (AGPL-3.0-only); see Coding Standards.
  • Time: servers never exchange wall-clock times for decisions; liveness and leases use local monotonic clocks, and kingresd only measures and alerts on clock differences (clockDifference).
  • Idempotence and resumption: tasks, moves, failovers and key operations resume after a restart or a change of leader.

Sources

Clone this wiki locally