A start that does not apply the schema proves the schema is there

Self's ruling on the open apply=0 item: connecting proves the URL, not the
schema, so a good URL to an empty database started and then answered every
request with a 500 (42P01).

PostgresStore.checkSchema replaces checkConnection. One query finds every
table and index CREATE_SCHEMA_SQL creates and every column it adds, and
anything missing fails with SCHEMA_MISSING, which startup reports through
the same fixed message. The required names are read from CREATE_SCHEMA_SQL
itself, so a new table or migration is required as soon as it is written.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-09-30 15:49:23 +02:00
commit cad12165a9
4 changed files with 79 additions and 7 deletions

View file

@ -14,9 +14,10 @@ export async function createStore(config: HeimdallConfig): Promise<HeimdallStore
const store = createPostgresStore(config.storage.databaseUrl ?? "postgres://127.0.0.1/heimdall");
try {
// Connect on every start, whether or not it applies the schema, so a
// misbound URL fails here rather than in the first request.
await (config.storage.applySchemaOnStartup ? store.ensureSchema() : store.checkConnection());
// Every start connects, and one that does not apply the schema proves it
// is there, so a misbound URL or an empty database fails here rather than
// in the first request.
await (config.storage.applySchemaOnStartup ? store.ensureSchema() : store.checkSchema());
} catch (error) {
// pg's and Node's errors name the host, the database or the URL itself,
// and any of those can hold part of a secret that was bound or escaped

View file

@ -1,7 +1,7 @@
import { randomUUID } from "node:crypto";
import { Pool, type PoolClient, type QueryResultRow } from "pg";
import { type AppSlug, type HeimdallAuthAttemptStatus, type LinkedIdentityInput, type Provider } from "../contracts.js";
import { CREATE_SCHEMA_SQL } from "./schema.js";
import { CREATE_SCHEMA_SQL, REQUIRED_COLUMNS, REQUIRED_RELATIONS } from "./schema.js";
import {
type CreateAccountInput,
type CreateAuthAttemptInput,
@ -291,9 +291,34 @@ export class PostgresStore implements HeimdallStore {
await this.pool.query(CREATE_SCHEMA_SQL);
}
/** Opens a connection and runs a trivial query, so a start that does not apply the schema still proves the URL. */
async checkConnection(): Promise<void> {
await this.pool.query("SELECT 1");
/**
* Proves, for a start that does not apply the schema, that the URL connects
* and that the database holds every relation and column the schema makes.
* A missing one fails with code SCHEMA_MISSING.
*/
async checkSchema(): Promise<void> {
const result = await this.pool.query<{ missing: string }>(
`
SELECT name AS missing FROM unnest($1::text[]) AS name WHERE to_regclass(name) IS NULL
UNION ALL
SELECT required.table_name || '.' || required.column_name
FROM unnest($2::text[], $3::text[]) AS required(table_name, column_name)
WHERE NOT EXISTS (
SELECT 1 FROM information_schema.columns c
WHERE c.table_schema = current_schema()
AND c.table_name = required.table_name
AND c.column_name = required.column_name
)
`,
[
REQUIRED_RELATIONS,
REQUIRED_COLUMNS.map((required) => required.table),
REQUIRED_COLUMNS.map((required) => required.column),
]
);
if (result.rows.length > 0) {
throw Object.assign(new Error("The Heimdall schema is not applied."), { code: "SCHEMA_MISSING" });
}
}
async close(): Promise<void> {

View file

@ -162,3 +162,16 @@ CREATE TABLE IF NOT EXISTS audit_events (
CREATE INDEX IF NOT EXISTS audit_events_lookup_idx
ON audit_events(account_id, session_id, app_slug, created_at);
`;
/**
* What a start that does not apply the schema must find, read from the SQL
* above so the two cannot drift: every table and index it creates, and every
* column it adds to an existing table.
*/
export const REQUIRED_RELATIONS = [
...CREATE_SCHEMA_SQL.matchAll(/^CREATE (?:UNIQUE )?(?:TABLE|INDEX) IF NOT EXISTS (\w+)/gm),
].map((match) => match[1]!);
export const REQUIRED_COLUMNS = [
...CREATE_SCHEMA_SQL.matchAll(/^ALTER TABLE (\w+) ADD COLUMN IF NOT EXISTS (\w+)/gm),
].map((match) => ({ table: match[1]!, column: match[2]! }));

View file

@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import { newDb } from "pg-mem";
import { createPostgresStore, PostgresStore } from "../src/store/postgres.js";
import { REQUIRED_COLUMNS, REQUIRED_RELATIONS } from "../src/store/schema.js";
describe("PostgresStore", () => {
it("round-trips core auth records through postgres", async () => {
@ -209,3 +210,35 @@ describe("createPostgresStore", () => {
]);
});
});
describe("PostgresStore.checkSchema", () => {
it("requires every table and index the schema creates and every column it adds", () => {
expect(REQUIRED_RELATIONS).toEqual(
expect.arrayContaining(["accounts", "audit_events", "auth_completions_attempt_unconsumed_unique_idx", "audit_events_lookup_idx"])
);
expect(REQUIRED_RELATIONS).toHaveLength(17);
expect(REQUIRED_COLUMNS).toEqual([{ table: "auth_completions", column: "attempt_id" }]);
});
function storeAnswering(missing: string[]) {
const queries: unknown[][] = [];
const store = new PostgresStore({
query: (async (_text: string, values: unknown[]) => {
queries.push(values);
return { rows: missing.map((name) => ({ missing: name })) };
}) as never,
end: async () => undefined,
});
return { store, queries };
}
it("refuses with SCHEMA_MISSING when anything is missing", async () => {
const { store, queries } = storeAnswering(["auth_completions.attempt_id"]);
await expect(store.checkSchema()).rejects.toMatchObject({ code: "SCHEMA_MISSING" });
expect(queries).toEqual([[REQUIRED_RELATIONS, ["auth_completions"], ["attempt_id"]]]);
});
it("passes when nothing is missing", async () => {
await expect(storeAnswering([]).store.checkSchema()).resolves.toBeUndefined();
});
});