ADR-022: Unauthenticated database management (/database/management)¶
Status: Accepted Date: 2026-09-24
Problem¶
Operating this app needs an Odoo-style database manager: list/create/switch/delete the Postgres databases behind a deployment, and extract/restore a database (SQL + optionally its S3 content) as a portable archive — reachable even when nobody can log in yet (a fresh deployment, a locked-out admin), so it cannot ride the normal JWT session model.
Decision¶
- Auth model: every action on
/api/v1/database-management/*(core/internal/dbmanage) is gated by comparing anX-Master-Keyheader againstConfig.MasterPassword— the SAME secret that signs every JWT (internal/auth.TokenService), not a separate one. One secret to provision/rotate, but this page is now an alternate full-compromise path if it leaks — accepted trade-off, not an oversight. NojwtMw/permMwon the route group; every handler callsRequireMasterKeyitself, including plain listing (revealing live database names to an anonymous caller is real information). Rate-limited with the sameAuthRateLimiterthe/api/v1/authgroup uses, as defense-in-depth against brute-forcing the key. - Switching is a true live hot-swap, not a restart.
core-backpreviously opened onepgxpool.Poolat boot and never again — everyRepository[T]/handler/background ticker captured that same*orm.DBpointer, never a copy of the pool.db.DB.SwapPool(core/orm/ pool/db/db.go) turnedpoolinto anatomic.Pointer[pgxpool.Pool]so a switch repoints the SAME*orm.DBat a different database in place — every existing repo/handler picks up the new pool with nothing to rebuild. - Prepare/Activate split (blue/green toggling) supersedes the original one-call
SwitchTo. The original design didSwapPool(instant, live cutover) thenmodule.Registry.Boot(schema provisioning) — meaning real traffic was already hitting the new database while it was still being provisioned, for as long asBoot()took (measured: up to ~2 minutes on production spinning disk — see the pitfall bullet below).internal/dbmanage/prepare.godecouples the two: Prepare(ctx, name)provisions a database without touching the live pool at all —Provisioner.Provision(provision.go) builds its own throwawaymodule.Registryper call, completely independent of the process's one live registry singleton (safe because that registry's active/table-ownership bookkeeping is derived purely frommodule_root's filesystem scan, never from which database happens to be live — it never needed recomputing on a switch to begin with). On success the resulting pool is kept warm, not closed, and recorded inManager.prepared[name]as a ready standby.Handler.Prepare(POST .../:name/prepare) runs this in a background goroutine and returns202immediately;Handler.Listsurfacesunprepared/preparing/ready/failedper database so the UI can poll.Activate(ctx, name)is the actual cutover — near-instant, since all it does isPingthe already-warm standby pool once (cheap insurance against a connection that died while idle;SwapPoolitself does zero validation),SwapPoolit in, force-disconnect every presence websocket, best-effort persistdb_name(temp-file-then-rename, same patternmodule.json's own PUT uses — failure to persist logs loudly but doesn't fail the request, since the live switch already happened), andsetActiveName. Crucially, the just-deactivated pool becomes the new standby for its own name instead of being closed — this is what makes toggling back to it later free (no re-provisioning, no new connections, just anotherPing+SwapPool), directly answering "toggle between a first and a second database, don't re-deploy on every switch."SwitchTo(switch.go) is now a thin backward-compatible wrapper —Prepare(blocking, if not alreadyready) thenActivate— kept for scripts/callers that still want the old one-call blocking behavior; the UI itself moved to the two-step flow.Discard(name)releases a prepared standby without activating it (closes its pool, drops the map entry) — both an explicit "never mind" UI action and somethingDeletenow calls first, since Postgres refusesDROP DATABASEwhile a standby's connections are still open.Preparereports real progress, not a spinner.module.Registry.BootWithProgress(new, alongside the unchangedBoot) fires a(done, total int)callback after each Go module's ownensureTable/ensureColumns/Migratepass — Go modules are effectively the entire workload (every module shipped in this repo today is type"go"), so this covers the real cost without separate plumbing through the WASM loader or the trailing index pass.Provisioner.ProvisionWithProgressforwards it;Manager.provisionAndKeepWarmthreads it into the target's ownpreparedTarget, mutating that SAME struct in place across every outcome (progress, failure, success) rather than replacing it, so a failed attempt still shows how far it got instead of resetting to 0/0.Manager.lastPrepareDuration— the most recent successfulPrepare's own wall-clock time in this process — is what a still-runningPrepare'sestimated_secondsis forecast from (zero/absent the first time anything is prepared in a fresh process, since there's nothing yet to estimate from).Handler.List's response carriesprogress_done/progress_total/elapsed_seconds/estimated_secondsalongsidestatus; the frontend renders aLinearProgressbar (determinate once a real done/total pair has arrived, indeterminate before that) under apreparingrow, tickingelapsed_secondsup locally between the 3s polls so the number moves every second instead of jumping.- Boot-time
EnsureDatabaseExists: a config pointed at a not-yet-provisioneddb_namenow creates it instead of refusing to start.core-backpreviously connected to whateverdb_namewas configured with no fallback — Postgres refuses a connection to a database that doesn't exist at all, so a fresh deployment, or an existing one simply repointed at a differentdb_name, failed to boot outright.core/cmd/app/main.gonow callsdbmanage.EnsureDatabaseExists(ctx, configContent)(a thinSELECT EXISTS ... FROM pg_databasecheck,CreateDatabaseonly on a miss) immediately before opening its real connection pool. An already-existing database is left completely untouched; schema provisioning is still main.go's own unconditionalmodule.Registry.Boot+auth.SeedDevAdmincall right after, exactly as for any other empty database — this function's only job is making sure that step has something to connect to. - A real prerequisite bug this exposed:
module.Registry.Boot's Go-module schema provisioning (internal/module/go_module.go'sloadGoModule) decided whether to runensureTable/ensureColumnsby diffing a process-global, in-memory table registry, not real database state — correct on a process's first boot, silently a no-op on any later Boot call in the same process (exactly what create/switch need). Fixed by running the already-fully- idempotent (IF NOT EXISTS)ensureTable/ensureColumnsunconditionally every call, keeping the in-memory diff only for table-ownership bookkeeping. This is what makes "switch into an empty database" and "create + immediately provision a new one" both actually work. - That "unconditionally every call" fix was itself O(n²) until a second pass:
loadGoModule's per-table loop walks the ENTIRE global table registry (every table any module has EVER registered, not just the current module's own), so module k of n redundantly re-issuedensureTable/ensureColumnsfor all k-1 tables earlier modules in the SAMEBoot()call had already handled — on an otherwise-empty target (this feature's whole point), that's pure redundant round trips, not a no-op skipped byIF NOT EXISTS(the statement still has to be sent and answered). Fixed by scoping a per-Boot()-callensuredThisBootset through every module'sloadGoModuleinvocation: a table is ensured exactly once perBoot()call — still unconditional across separateBoot()calls (the actual invariant a switch depends on), just no longer redundant within one. - A NOT-NULL column with no natural default could wedge
Boot()outright on a populated table.ensureColumnsderiveszeroSQLDefaultfor backfilling a new required column (''/false/0/'{}'::jsonb) but has no sane default forUUID—model.BaseModel's ownTenantIDis exactly this type.ADD COLUMN ... NOT NULLwith noDEFAULTfails outright (Postgres 23502) the moment the table already has rows, which is precisely the case a switch into a real, pre-existing database hits. A module can hand-write the correct two-step fix in its ownMigrate()hook (add nullable, backfill per-row,ALTER COLUMN ... SET NOT NULL—auth.module.go'suser_roles.tenant_idandpropertymanagement's own analogous case) butMigrate()runs afterensureColumnsin the same module's load, so the column's OWN required nullable-first step never happened before that hand-written fix could even reach it — the generic pass errored out first and aborted the wholeBoot()beforeMigrate()ran. Fixed by havingensureColumnsretry a 23502 on a no-default NOT NULL column as a plain nullableADD COLUMN, leaving the owning module'sMigrate()to backfill and tighten it — exactly the gapzeroSQLDefault's own doc comment already named ("would otherwise permanently wedge auto-migration") but that wasn't actually wired up until now. - Also surfaced:
auth.SeedDevAdminhad a standing, silent bug — it seeded aPermissionsrow under a hardcoded id AND unconditionally calledSeedDefaultRoles, which seeded a different id for the samecode = "*:*:*", violatingidx_permissions_codeon every single boot (silently swallowed as non-fatal inmain.go, so nobody noticed — the original admin/role pair seeded fine regardless, only the newer Admin/Viewer/Deny bundle silently failed). This package'sProvisionertreats that error as fatal (a fresh database MUST be immediately loggable-into), which is what surfaced it. Fixed by reusing the SAME deterministic id (seedUUID(DevTenantID, "permission:*:*:*")) for both seed paths instead of two rows sharing a code. - S3 extraction is manifest-driven, not a bucket dump.
BuildManifestqueries the database being extracted (not necessarily the active one) for theobject_keyof every row inmanifestSources:picture,attachment, and the Teams app'schat_attachmentand liveteam_filerows (deleting a Teams file removes its object, so deleted rows are left out; a table the database doesn't have is skipped). A module that stores objects under a table of its own must be added to that list, or its files silently miss from extractions — this is what scopes an extraction to exactly that database's own objects out of a bucket potentially shared by several EERP databases on the same instance. Generated report PDFs (internal/reports) are deliberately never included: that package persists no DB row for its own S3 key at all, and a report is always regeneratable on demand from the underlying invoice/quote/receipt data, which the SQL dump already carries. - Dump/restore shells out to
pg_dump/pg_restore(PGDG apt repo incore/Dockerfile's runtime stage, pinned to the server's own Postgres 18 major version) rather than reimplementing the dump format.extract.gostreams a zip directly into the HTTP response viaarchive/zip(no temp file, no full in-memory buffering);restore.gowrites the upload to a temp dir,pg_restores the dump, then re-uploads each manifest object to the current instance's bucket at the same key — no key rewriting, since keys are tenant/table/record/field-scoped, never environment-scoped. The restore reads the dump's table of contents first and leaves out any extension the target server doesn't ship, with the schemas it owns: a database first created by an older PostGIS image carriespostgis_tiger_geocoder, which PostGIS 3.7 images dropped and EERP never used, and a strict restore would fail on it. A failed restore drops the database it created, so the next attempt can reuse the name. - Frontend:
core-front/apps/shell/app/database/management/page.tsxis a plain client component, deliberately outsiderequireAuth()and the descriptor-driven view engine — this route must render for a fully anonymous visitor. No BFF/Server Actions: the browser calls/api/v1/database-management/*directly with the typed master key as a header, the same "browser calls Go directly for a good reason" precedent Presence established (ADR-020), here because of large binary transfer with no session involved at all. Per row, the action shown followsstatus:unprepared/failed→ Prepare,preparing→ a disabled spinner chip plus a full-widthPrepareProgressRowunderneath — aLinearProgressbar with its own numeric%label (determinate onceprogress_totalhas arrived, indeterminate only for the brief window before that first callback), and a bareelapsed / estimatedcaption underneath (e.g.12s / 45s— no sentence, just the two numbers),ready→ Activate + Discard,active→ none. AuseEffectpollsGET .../databaseson a 500ms interval whilepreparing(silently — no busy flag, so it never fights an in-flight foreground action; short enough that the bar visibly fills step by step instead of jumping in a few big increments) — the only way this page learns anything, sincePrepareruns off-request with no push/webhook path back to the browser. - Infra:
infra/nginx/nginx.confgets its ownlocation /api/v1/database-management/block (client_max_body_size 2g,proxy_read_timeout 3600s) — the default/api/v1/block's 50m/120s is far too small for a full dump+S3 bundle.
Sequence: prepare (background) then activate (instant)¶
Two separate request paths now, deliberately never sharing a request: Prepare does every bit of slow, DB-touching work off the live pool entirely; Activate does none of it.
flowchart TD
PReq["POST .../:name/prepare"] --> PAuth{"RequireMasterKey"}
PAuth -- "missing/invalid" --> P401["401"]
PAuth -- ok --> PValid{"validateName(name)"}
PValid -- invalid --> P400["400"]
PValid -- ok --> Kick["go func(){ Manager.Prepare(context.Background(), name) }()"]
Kick --> P202["202 Accepted — caller polls GET .../databases for status"]
Kick -. "background goroutine, never on the request" .-> Guard{"already preparing\nor already ready?"}
Guard -- yes --> NoOp["no-op — repeat Prepare of an\nunchanged target costs nothing"]
Guard -- no --> Open["orm.New: open a pool to name\nWITH the deployment's real MaxConns/MinConns\n(not pgx bare defaults)"]
Open --> Boot
subgraph Boot["Provisioner.Provision(ctx, tmp.DB) — its OWN throwaway module.Registry,\nnever the live moduleRuntime singleton"]
direction TB
Bootstrap["bootstrap module_migrations + module_operation_log tables"]
Detect["detector: scan module_root for module.json (WASM + Go, active or not)"]
Bootstrap --> Detect
Detect --> Wasm["WASM modules: priority-tiered groups, loaded in PARALLEL"]
Detect --> GoLoop
subgraph GoLoop["Go modules — SEQUENTIAL, registration order"]
direction TB
Fresh["ensuredThisBoot := {} — fresh set for THIS Boot() call only"]
Reg["module.Register(): declare its own tables in-memory"]
Fresh --> Reg
Reg --> Seen{"table already in\nensuredThisBoot this call?"}
Seen -- yes --> SkipCols["skip ensureTable/ensureColumns\n(handled by an earlier module this call)"]
Seen -- no --> EnsureTable["ensureTable: CREATE TABLE IF NOT EXISTS"]
EnsureTable --> AddCol["ensureColumns: ALTER TABLE ADD COLUMN IF NOT EXISTS"]
AddCol -- ok --> MarkSeen["ensuredThisBoot[table] = true"]
AddCol -- "23502 + NOT NULL + no default" --> Retry["retry: ADD COLUMN nullable instead"]
AddCol -- "other error" --> ModErr["abort THIS module: addErr(err), Boot continues with the rest"]
Retry --> MarkSeen
MarkSeen --> SkipCols
SkipCols --> Migrate["module's own Migrate() hook:\nhand-written DDL, per-row backfills,\nunique indexes, ALTER COLUMN SET NOT NULL"]
Migrate --> Progress["onProgress(i+1, len(goMods))\n-> preparedTarget.progressDone/progressTotal"]
end
Wasm --> Idx
GoLoop --> Idx["AFTER every module: ensureIndexes\nfor every db-tagged 'col,index' field, every registered table"]
Idx --> SeedAdmin["auth.SeedDevAdmin"]
end
Boot -- error --> Fail["tmp.Close() — don't leak the failed attempt's\nconnections; prepared[name] = {err} -> status 'failed'"]
Boot -- ok --> Warm["keep tmp.DB.Pool() OPEN — do NOT close it;\nprepared[name] = {pool, ready: true} -> status 'ready'"] flowchart TD
AReq["POST .../:name/activate"] --> AAuth{"RequireMasterKey"}
AAuth -- "missing/invalid" --> A401["401"]
AAuth -- ok --> Ready{"prepared[name] ready?"}
Ready -- no --> A409["409 NOT_READY — prepare it first"]
Ready -- yes --> Ping{"Ping the warm standby pool"}
Ping -- "fails (died while idle)" --> Evict["evict + close the stale entry,\nreturn an error asking for re-prepare"]
Ping -- ok --> Swap["db.DB.SwapPool(standby pool):\natomically repoint the live *orm.DB\n— the actual cutover, one pointer swap"]
Swap --> Presence["presence.Hub.CloseAll: force-disconnect every open websocket"]
Presence --> Persist["persistDBName: atomic temp-file+rename write into the on-disk config"]
Persist -- write fails --> PersistWarn["log loudly — live switch already succeeded, don't fail the request"]
Persist -- ok --> SetActive["setActiveName(name)"]
PersistWarn --> SetActive
SetActive --> Repurpose["prepared[oldName] = {pool: OLD live pool, ready: true}\n— NOT closed: it's the new standby, free to toggle back to"]
Repurpose --> Forget["delete(prepared, name) — live now, not a standby"]
Forget --> A200["200 — new pool already serving live traffic"] Every ALTER/CREATE in Prepare's Go-module loop and trailing index pass is its own DB round trip, Boot()-unconditional by design (see the bullets above) — so on an otherwise-empty target this cost is almost entirely schema size × round-trip latency, not row count, and it never touches the request path at all now. A real production database being prepared for the first time additionally pays for whatever a module's own Migrate() hook has to backfill (UPDATE ... FROM ... scans, index builds) — that part does scale with the target's existing row counts, unlike the schema-provisioning loop above it, but it's still happening off to the side, not blocking live traffic. Activate itself does none of this — it's bounded by one Ping round trip plus a handful of fast, non-DDL bookkeeping steps, regardless of schema size or row count on either side.
Consequences / pitfalls¶
- A switch invalidates every current session implicitly, not by design revocation — an old JWT's claims simply stop resolving against whatever database is now live. The existing 401-then-redirect-to-
/loginhandling (ApiClient.ts) covers this with no new frontend code; presence sockets are force-closed explicitly since nothing else would notice they're stale. - The old grace-period-then-
Close()dance is gone, on purpose. The original design always destroyed the outgoing pool (defer time.AfterFunc(5*time.Second, oldPool.Close)) because it had nowhere else to put it. SinceActivatenow repurposes the just-deactivated pool as the new standby for its own name instead, there's nothing to leak-guard against on the happy path — the pool that used to need a deferredClosenow just keeps living inManager.prepared. A pool only actually gets closed on an explicitDiscard, a failedPrepareattempt (leaked otherwise), or a stale standby caught byActivate's pre-swapPing. Manager.preparedis in-memory only, never persisted — deliberately. Acore-backrestart wipes it; anything not currently active needs a freshPrepareafter one. This isn't a gap: a restart is also exactly when new module code/migrations could exist, so forcing re-preparation is correct, not just convenient — there's no staleness/fingerprinting problem to solve because nothing survives long enough to go stale across a code change.Prepare's pool now carries the deployment's realMaxConns/MinConns(cfg.MaxConns/cfg.MinConns, threaded throughManager) — the originalCreateAndProvisionandSwitchToboth silently built their pool withpgxpool.New's bare defaults instead, harmless when the pool was immediately closed again (CreateAndProvision) or short-lived, but a real gap once a pool built this way can end up serving all production traffic indefinitely viaActivate'sSwapPool.Manager.DeletecallsDiscardbeforeDropDatabase— a database sitting as a prepared-but- never-activated standby holds open idle connections, and Postgres refusesDROP DATABASEwhile any exist ("database is being accessed by other users"). Without this, deleting an abandoned prepare candidate would fail with that raw error instead of just working.DROP DATABASE/CREATE DATABASEidentifiers can't be parameterized — safety is a strict^[a-z][a-z0-9_]{0,62}$allowlist (dbmanage.validateName) pluspgx.Identifier{}.Sanitize(), not string interpolation of arbitrary request input.- The database LIST is filtered to "EERP-shaped" databases (
to_regclass('public.users')and('public.app_settings')both non-null) —postgres/template0/template1/an unrelated database sharing the same Postgres server never appear, so there is no path to switching into or dropping something that isn't an EERP database via this UI. Preparetime is dominated by fsync-per-statement, not row count — this used to be switch time before the Prepare/Activate split, and the underlying cost hasn't changed, just where it lands. EveryensureTable/ensureColumns/ensureIndexescall outside an explicit transaction is Postgres's own autocommit — one WAL fsync per statement, not perBoot()call. On fast local storage (SSD/NVMe, sub-millisecond fsync) this is unnoticeable even for a few hundred statements; on spinning disk (a real fsync can cost 5-20ms+) the SAME schema-size-bound statement count that takes under a second in dev can stretch to a minute or more in production — the original "switch takes 2 minutes on a hard drive for a brand-new (empty) database" report, not data volume (an empty target has no row-scanning step at all). It no longer blocks live traffic —Prepareruns off the request path — but an operator waiting on the "preparing → ready" status still feels it. The lever this doesn't yet use: batching aBoot()call's DDL into one (or a few) transactions would collapse many fsyncs into one commit — not implemented, since it needsMigrator.Migrate(ctx, db *orm.DB)'s signature to acceptorm.Executorinstead (13 modules implement it today); add it ifPreparetime on slow storage becomes a real operational problem.