Heimdall/src/store/index.ts
Meta Vens b5d7b6b0cc A refused store closes its pool; pin the key's columns and uniqueness
The startup check's refusal left the store's pool open: the process exits
on it in production, but the connection outlived the refusal. createStore
now closes a store it refuses.

Two live cases the first run showed undefended (mutants D6 and D9): a
unique key replaced by a plain index on the same columns, and by a unique
index on other columns of the same count. The read-only-role case also
checks that no session of the role outlives the refusal. The fixture's
owner pool ignores the connection ends its own forced drop causes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 17:29:19 +02:00

41 lines
1.7 KiB
TypeScript

import { type HeimdallConfig } from "../config.js";
import { InMemoryStore } from "./in-memory.js";
import { createPostgresStore } from "./postgres.js";
import { type HeimdallStore } from "./types.js";
export * from "./types.js";
export { InMemoryStore } from "./in-memory.js";
export { PostgresStore, createPostgresStore } from "./postgres.js";
export async function createStore(config: HeimdallConfig): Promise<HeimdallStore> {
if (config.storage.backend !== "postgres") {
return new InMemoryStore();
}
const store = createPostgresStore(config.storage.databaseUrl ?? "postgres://127.0.0.1/heimdall");
try {
// Every start connects and proves the database can take its requests,
// whether or not it applied the schema first (CREATE ... IF NOT EXISTS
// leaves a damaged table as it is), so a misbound URL, an empty or
// damaged database, or a role that may not write fails here rather than
// in the first request.
if (config.storage.applySchemaOnStartup) {
await store.ensureSchema();
}
await 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
// wrongly. Startup prints this error, so it names only the input and a
// code, and carries no cause.
const code = (error as { code?: unknown }).code;
// A refused store is never handed out, so it is closed here: its pool
// would otherwise hold the connection open.
await store.close().catch(() => undefined);
throw new Error(
`Postgres storage could not be prepared (${typeof code === "string" ? code : "error"}); check GC_ACCESS_DATABASE_URL_FILE.`
);
}
return store;
}