From 4ce6ab536e88f158fb81a66b25ae3d6f3d870461 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 21:08:14 +0100 Subject: [PATCH] Steward cut 2: replace SQL predicate compiler and TEMP TABLE ceremony with minimal table existence check --- src/store/index.ts | 8 +- src/store/postgres.ts | 286 ++------------------------------ src/store/schema.ts | 97 ++--------- tests/store.test.ts | 376 +++++------------------------------------- 4 files changed, 63 insertions(+), 704 deletions(-) diff --git a/src/store/index.ts b/src/store/index.ts index 69abbe6..18c52d5 100644 --- a/src/store/index.ts +++ b/src/store/index.ts @@ -32,13 +32,7 @@ export async function createStore(config: HeimdallConfig): Promise undefined); - // A role that may not create temporary tables is not a bad URL, so that - // refusal names the privilege instead. - const remedy = - code === "SCHEMA_TEMP_PRIVILEGE" - ? "grant the database role TEMPORARY on its database" - : "check GC_ACCESS_DATABASE_URL_FILE"; - throw new Error(`Postgres storage could not be prepared (${typeof code === "string" ? code : "error"}); ${remedy}.`); + throw new Error(`Postgres storage could not be prepared (${typeof code === "string" ? code : "error"}); check GC_ACCESS_DATABASE_URL_FILE.`); } return store; diff --git a/src/store/postgres.ts b/src/store/postgres.ts index f0da059..6469101 100644 --- a/src/store/postgres.ts +++ b/src/store/postgres.ts @@ -2,7 +2,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 { decideMove, movedRecord, type MoveFacts } from "./identity-move.js"; -import { CREATE_SCHEMA_SQL, REQUIRED_COLUMNS, REQUIRED_KEYS, REQUIRED_TABLES } from "./schema.js"; +import { CORE_TABLES, CREATE_SCHEMA_SQL } from "./schema.js"; import { type CreateAccountInput, type CreateAuthAttemptInput, @@ -411,279 +411,6 @@ function mapAuthAttemptRow(row: AuthAttemptRow): StoredAuthAttempt { return attempt; } -/** - * The AND-ed conditions of a predicate as Postgres prints it, each without a - * pair of parentheses that encloses all of it. Postgres flattens a chain of - * ANDs into one list, so `((a) AND (b) AND (c))` yields `a`, `b`, `c`. An OR, - * or an AND nested under one, stays whole: `((a OR b) AND c)` yields `a OR b` - * and `c`, and `(a OR (b AND c))` yields itself. Quoted text is never split. - */ -export function predicateConditions(printed: string): string[] { - const unwrap = (text: string): string => { - let current = text.trim(); - while (current.startsWith("(") && closingParenthesis(current, 0) === current.length - 1) { - current = current.slice(1, -1).trim(); - } - return current; - }; - const whole = unwrap(printed); - if (whole === "") return []; - const parts: string[] = []; - let depth = 0; - let quote: string | undefined; - let start = 0; - for (let position = 0; position < whole.length; position += 1) { - const character = whole[position]!; - if (quote) { - if (character === quote) quote = undefined; - } else if (character === "'" || character === '"') { - quote = character; - } else if (character === "(") { - depth += 1; - } else if (character === ")") { - depth -= 1; - } else if (depth === 0 && whole.startsWith(" AND ", position)) { - parts.push(whole.slice(start, position)); - start = position + " AND ".length; - position = start - 1; - } - } - parts.push(whole.slice(start)); - return parts.map(unwrap); -} - -/** The index of the parenthesis closing the one at `open`, outside quoted text, or -1. */ -function closingParenthesis(text: string, open: number): number { - let depth = 0; - let quote: string | undefined; - for (let position = open; position < text.length; position += 1) { - const character = text[position]!; - if (quote) { - if (character === quote) quote = undefined; - } else if (character === "'" || character === '"') { - quote = character; - } else if (character === "(") { - depth += 1; - } else if (character === ")") { - depth -= 1; - if (depth === 0) return position; - } - } - return -1; -} - -/** - * Whether an index predicate, as Postgres prints it, keeps exactly the rows - * the declared one (printed the same way) does: the same set of AND-ed - * conditions, ignoring `key_column IS NOT NULL` unless the index treats NULLs - * as equal, since otherwise rows with a NULL key never collide anyway. - */ -export function samePredicate(declared: string, actual: string, keyColumns: string[], nullsNotDistinct: boolean): boolean { - // A key without a predicate must have none: ON CONFLICT cannot infer a - // partial index as its arbiter. - if (predicateConditions(declared).length === 0) return actual.trim() === ""; - const redundant = new Set(nullsNotDistinct ? [] : keyColumns.map((column) => `${column} IS NOT NULL`)); - const conditions = (printed: string) => - [...new Set(predicateConditions(printed).filter((condition) => !redundant.has(condition)))].sort(); - const left = conditions(declared); - const right = conditions(actual); - return left.length === right.length && left.every((condition, index) => condition === right[index]); -} - -/** - * What the store's statements do to each table, and so the privileges its - * database role needs: it reads what it returns or looks up, inserts what it - * creates, updates what it changes or upserts, and deletes two things: - * expired oauth_state_uses rows (which needs SELECT for its WHERE), and the one - * linked_identities row an unlink names (unlinkLinkedIdentity, the only - * delete there; it needs SELECT for its WHERE and for the account's count). - * identity_moves is append-only. moveIdentities is the statement that updates - * linked_identities.account_id (its one writer), sessions, pending_links and - * auth_completions, all of which already hold UPDATE. - * audit_events is written and never read back. - */ -export const STORE_TABLE_PRIVILEGES: Readonly> = { - accounts: ["SELECT", "INSERT", "UPDATE"], - linked_identities: ["SELECT", "INSERT", "UPDATE", "DELETE"], - sessions: ["SELECT", "INSERT", "UPDATE"], - auth_attempts: ["SELECT", "INSERT", "UPDATE"], - private_command_receipts: ["SELECT", "INSERT"], - auth_completions: ["SELECT", "INSERT", "UPDATE"], - pending_links: ["SELECT", "INSERT", "UPDATE"], - oauth_state_uses: ["SELECT", "INSERT", "DELETE"], - capability_grants: ["SELECT", "INSERT"], - entitlement_snapshots: ["SELECT", "INSERT", "UPDATE"], - consent_receipts: ["SELECT", "INSERT"], - identity_moves: ["SELECT", "INSERT"], - audit_events: ["INSERT"], -}; - -/** What a database must hold for a store to serve it; see checkSchemaRequirements. */ -export interface SchemaRequirements { - tables: readonly string[]; - columns: readonly { table: string; column: string; type: string; nullable: boolean }[]; - keys: readonly { table: string; columns: string; predicate: string }[]; - privileges: Readonly>; -} - -/** What Heimdall's store needs, read from its schema and its statements. */ -export const HEIMDALL_SCHEMA_REQUIREMENTS: SchemaRequirements = { - tables: REQUIRED_TABLES, - columns: REQUIRED_COLUMNS, - keys: REQUIRED_KEYS, - privileges: STORE_TABLE_PRIVILEGES, -}; - -/** - * Each required key's predicate as Postgres prints it back (empty for none). - * One simple-protocol round trip on one connection: a transaction that builds - * a temporary copy of each keyed table's declared columns, indexes it with the - * declared predicate, reads the printed form and rolls back. The names and SQL - * come from the requirements, which are constants, never input. A role that - * may not create temporary tables fails with code SCHEMA_TEMP_PRIVILEGE. - */ -export async function printedDeclaredPredicates(pool: Pick, requirements: SchemaRequirements): Promise { - const partial = requirements.keys.flatMap((required, index) => (required.predicate ? [{ ...required, index }] : [])); - if (partial.length === 0) return requirements.keys.map(() => ""); - const statements = partial.flatMap(({ table, columns, predicate, index }) => { - const probe = `heimdall_key_probe_${index}`; - const declared = requirements.columns - .filter((column) => column.table === table) - .map((column) => `${column.column} ${column.type}`) - .join(", "); - return [ - `CREATE TEMP TABLE ${probe} (${declared}) ON COMMIT DROP`, - `CREATE UNIQUE INDEX ${probe}_idx ON ${probe} (${columns}) WHERE ${predicate}`, - ]; - }); - const select = partial - .map(({ index }) => `SELECT ${index} AS key, pg_get_expr(indpred, indrelid) AS predicate FROM pg_index WHERE indexrelid = 'pg_temp.heimdall_key_probe_${index}_idx'::regclass`) - .join(" UNION ALL "); - let results: Array<{ rows: Array<{ key: number; predicate: string }> }>; - try { - results = (await pool.query(["BEGIN", ...statements, select, "ROLLBACK"].join(";\n"))) as unknown as typeof results; - } catch (error) { - if ((error as { code?: unknown }).code === "42501") { - throw Object.assign(new Error("The Heimdall database role may not create temporary tables."), { code: "SCHEMA_TEMP_PRIVILEGE" }); - } - throw error; - } - const printed = results[results.length - 2]!.rows; - return requirements.keys.map((_, index) => printed.find((row) => row.key === index)?.predicate ?? ""); -} - -/** - * Proves that the database can take a store's requests: every required - * table; every column with its declared type, under a deterministic - * collation, and nullable where declared nullable; every unique key; and - * every privilege, held on the table or on each of its columns. A missing or - * altered piece fails with code SCHEMA_MISSING and a missing privilege with - * SCHEMA_PRIVILEGES; neither error names the piece. - * - * A key is met by a unique index on its table that is valid (a failed - * CREATE INDEX CONCURRENTLY or an interrupted DROP INDEX CONCURRENTLY leaves - * one that is not; Postgres never marks an index valid before it is ready), - * immediate (ON CONFLICT refuses a deferrable arbiter), has exactly the key's - * columns as its key columns (INCLUDE columns aside), compares them under - * deterministic collations (a case-insensitive one would merge two - * providers' user ids into one row), and has the key's predicate. A - * predicate matches when both, as Postgres prints them, are the same set of - * AND-ed conditions; a `key_column IS NOT NULL` condition may be absent on - * either side, because a unique index never makes NULL keys collide unless - * it is NULLS NOT DISTINCT. Postgres prints the declared predicates itself - * (printedDeclaredPredicates). - * - * What this does not prove is listed where the schema is: see schema.ts. - */ -export async function checkSchemaRequirements(pool: Pick, requirements: SchemaRequirements): Promise { - const declaredPredicates = await printedDeclaredPredicates(pool, requirements); - const privileges = Object.entries(requirements.privileges).flatMap(([table, wanted]) => - wanted.map((privilege) => ({ table, privilege })) - ); - const result = await pool.query<{ - kind: "missing" | "privilege" | "candidate"; - key: number | null; - predicate: string | null; - nulls_not_distinct: boolean | null; - }>( - ` - SELECT 'missing' AS kind, NULL::int AS key, NULL::text AS predicate, NULL::boolean AS nulls_not_distinct - FROM unnest($1::text[]) AS name WHERE to_regclass(name) IS NULL - UNION ALL - SELECT 'missing', NULL, NULL, NULL - FROM unnest($2::text[], $3::text[], $4::text[], $5::boolean[]) AS required(table_name, column_name, type_name, nullable) - WHERE NOT EXISTS ( - SELECT 1 FROM pg_attribute a - WHERE a.attrelid = to_regclass(required.table_name) - AND a.attname = required.column_name - AND a.attnum > 0 - AND NOT a.attisdropped - AND a.atttypid = to_regtype(required.type_name) - AND (NOT required.nullable OR NOT a.attnotnull) - AND NOT EXISTS (SELECT 1 FROM pg_collation c WHERE c.oid = a.attcollation AND NOT c.collisdeterministic) - ) - UNION ALL - SELECT 'candidate', required.key::int, pg_get_expr(i.indpred, i.indrelid), - coalesce((to_jsonb(i) ->> 'indnullsnotdistinct')::boolean, false) - FROM unnest($6::text[], $7::text[]) WITH ORDINALITY AS required(table_name, columns, key) - JOIN pg_index i ON i.indrelid = to_regclass(required.table_name) - WHERE i.indisunique - AND i.indisvalid - AND i.indimmediate - AND i.indnkeyatts = cardinality(string_to_array(required.columns, ',')) - AND ( - SELECT string_agg(a.attname, ',' ORDER BY a.attname) - FROM unnest(i.indkey::int2[]) WITH ORDINALITY AS key(attnum, position) - JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = key.attnum - WHERE key.position <= i.indnkeyatts - ) = required.columns - AND NOT EXISTS ( - SELECT 1 FROM unnest(i.indcollation::oid[]) WITH ORDINALITY AS key_collation(oid, position) - JOIN pg_collation c ON c.oid = key_collation.oid - WHERE key_collation.position <= i.indnkeyatts AND NOT c.collisdeterministic - ) - UNION ALL - SELECT 'privilege', NULL, NULL, NULL - FROM unnest($8::text[], $9::text[]) AS required(table_name, privilege) - WHERE EXISTS ( - SELECT 1 FROM unnest($2::text[], $3::text[]) AS used(table_name, column_name) - JOIN pg_attribute a ON a.attrelid = to_regclass(used.table_name) AND a.attname = used.column_name AND NOT a.attisdropped - WHERE used.table_name = required.table_name - AND NOT CASE WHEN required.privilege = 'DELETE' - THEN has_table_privilege(a.attrelid, 'DELETE') -- DELETE is a row privilege, never held per column - ELSE has_column_privilege(a.attrelid, a.attnum, required.privilege) END - ) - `, - [ - requirements.tables, - requirements.columns.map((required) => required.table), - requirements.columns.map((required) => required.column), - requirements.columns.map((required) => required.type), - requirements.columns.map((required) => required.nullable), - requirements.keys.map((required) => required.table), - requirements.keys.map((required) => required.columns), - privileges.map((required) => required.table), - privileges.map((required) => required.privilege), - ] - ); - const keyMet = requirements.keys.map((required, index) => - result.rows.some( - (row) => - row.kind === "candidate" && - row.key === index + 1 && - samePredicate(declaredPredicates[index]!, row.predicate ?? "", required.columns.split(","), row.nulls_not_distinct === true) - ) - ); - if (result.rows.some((row) => row.kind === "missing") || keyMet.includes(false)) { - throw Object.assign(new Error("The Heimdall schema is not applied."), { code: "SCHEMA_MISSING" }); - } - if (result.rows.some((row) => row.kind === "privilege")) { - throw Object.assign(new Error("The Heimdall database role lacks a privilege the store needs."), { - code: "SCHEMA_PRIVILEGES", - }); - } -} - export class PostgresStore implements HeimdallStore { constructor(private readonly pool: Pick) {} @@ -691,9 +418,16 @@ export class PostgresStore implements HeimdallStore { await this.pool.query(CREATE_SCHEMA_SQL); } - /** Proves, before Heimdall serves, that the database can take its requests (checkSchemaRequirements). */ + /** Verifies database connectivity and that the core schema tables exist. */ async checkSchema(): Promise { - await checkSchemaRequirements(this.pool, HEIMDALL_SCHEMA_REQUIREMENTS); + await this.pool.query("SELECT 1"); + const result = await this.pool.query<{ name: string }>( + "SELECT name FROM unnest($1::text[]) AS name WHERE to_regclass('public.' || name) IS NULL", + [CORE_TABLES] + ); + if (result.rows.length > 0) { + throw Object.assign(new Error("The Heimdall schema is not applied."), { code: "SCHEMA_MISSING" }); + } } async close(): Promise { diff --git a/src/store/schema.ts b/src/store/schema.ts index ff1fcf2..b91139f 100644 --- a/src/store/schema.ts +++ b/src/store/schema.ts @@ -253,85 +253,18 @@ CREATE INDEX IF NOT EXISTS audit_events_lookup_idx ON audit_events(account_id, session_id, app_slug, created_at); `; -const schemaText = CREATE_SCHEMA_SQL.replace(/\r\n/g, "\n"); -const createdTables = [...schemaText.matchAll(/^CREATE TABLE IF NOT EXISTS (\w+) \(\n([\s\S]*?)\n\);/gm)].map((match) => ({ - table: match[1]!, - lines: match[2]!.split("\n").map((line) => line.trim().replace(/,$/, "")), -})); - -/** Sorted and comma-separated, the form the schema check compares key columns in. */ -function columnList(text: string): string { - return text.split(",").map((column) => column.trim()).sort().join(","); -} - -/** The columns of a `PRIMARY KEY (a, b)` or `UNIQUE(a, b)` line, as a column list. */ -function keyColumns(line: string, keyword: "PRIMARY KEY" | "UNIQUE"): string | undefined { - const match = new RegExp(`^${keyword}\\s*\\(([^)]*)\\)`).exec(line); - return match ? columnList(match[1]!) : undefined; -} - -/* - * What every start must find before it serves, read from the SQL above so the - * two cannot drift. A start that applies the schema checks as well, because - * CREATE ... IF NOT EXISTS leaves a damaged table as it is. Indexes that only - * speed lookups are not required; the unique ones are, by shape, in - * REQUIRED_KEYS. - * - * Out of scope, each able to make a write fail on a database that passes the - * check: CHECK constraints; triggers; row-level security; unique indexes - * beyond the required keys, or stricter than them, including the leftovers of - * an interrupted concurrent index build (a valid extra one refuses rows the - * store expects to write, and even an invalid one that is ready is enforced - * on writes); NOT NULL columns the schema does not declare and that have no - * default, which the store's INSERTs leave out; and SELECT granted column by - * column when a statement reads `SELECT *` or `RETURNING *`, which needs - * SELECT on every column the table has, not only the declared ones. - */ - -/** Every table the schema creates. */ -export const REQUIRED_TABLES = createdTables.map(({ table }) => table); - -/** - * Every column a created table declares and every column the schema adds to - * an existing table, each with its declared type, and whether it is nullable: - * the store reads and writes values as that type, and leaves a nullable - * column null, so a column retyped or made NOT NULL under it fails its writes. - */ -export const REQUIRED_COLUMNS = [ - ...createdTables.flatMap(({ table, lines }) => - lines - .filter((line) => !/^(?:PRIMARY KEY|UNIQUE|FOREIGN KEY)\b/.test(line)) - .map((line) => { - const [, column, type] = /^(\w+) (\w+)/.exec(line)!; - return { table, column: column!, type: type!, nullable: !/\b(?:NOT NULL|PRIMARY KEY)\b/.test(line) }; - }) - ), - ...[...schemaText.matchAll(/^ALTER TABLE (\w+) ADD COLUMN IF NOT EXISTS (\w+) (\w+)([^;]*);/gm)].map((match) => ({ - table: match[1]!, - column: match[2]!, - type: match[3]!, - nullable: !/\b(?:NOT NULL|PRIMARY KEY)\b/.test(match[4]!), - })), -]; - -/** - * Every unique key the schema makes: the primary keys and unique constraints - * of the created tables, and each unique index it creates, with that index's - * predicate as the schema writes it (empty for none). Any index of the right - * shape serves, whatever its name; PostgresStore.checkSchema says what the - * right shape is. - */ -export const REQUIRED_KEYS = [ - ...createdTables.flatMap(({ table, lines }) => - lines.flatMap((line) => { - const columns = - /^(\w+) .*\bPRIMARY KEY\b/.exec(line)?.[1] ?? keyColumns(line, "PRIMARY KEY") ?? keyColumns(line, "UNIQUE"); - return columns ? [{ table, columns, predicate: "" }] : []; - }) - ), - ...[...schemaText.matchAll(/^CREATE UNIQUE INDEX IF NOT EXISTS \w+\s+ON (\w+)\(([^)]*)\)(?:\s+WHERE ([^;]+))?;/gm)].map((match) => ({ - table: match[1]!, - columns: columnList(match[2]!), - predicate: (match[3] ?? "").replace(/\s+/g, " ").trim(), - })), -]; +export const CORE_TABLES = [ + "accounts", + "linked_identities", + "sessions", + "auth_attempts", + "private_command_receipts", + "pending_links", + "auth_completions", + "oauth_state_uses", + "capability_grants", + "entitlement_snapshots", + "consent_receipts", + "identity_moves", + "audit_events", +] as const; diff --git a/tests/store.test.ts b/tests/store.test.ts index 03b869a..5a8e7e1 100644 --- a/tests/store.test.ts +++ b/tests/store.test.ts @@ -4,22 +4,13 @@ import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; import { newDb } from "pg-mem"; import { type HeimdallConfig } from "../src/config.js"; import { createStore, IdentityHeldElsewhereError, InMemoryStore, type HeimdallStore } from "../src/store/index.js"; -import { - createPostgresStore, - PostgresStore, - checkSchemaRequirements, - HEIMDALL_SCHEMA_REQUIREMENTS, - predicateConditions, - printedDeclaredPredicates, - samePredicate, - STORE_TABLE_PRIVILEGES, -} from "../src/store/postgres.js"; +import { createPostgresStore, PostgresStore } from "../src/store/postgres.js"; import { OAUTH_STATE_PRUNE_BATCH, OAUTH_STATE_PRUNE_MARGIN_MS, OAUTH_STATE_SKEW_MS, } from "../src/store/types.js"; -import { CREATE_SCHEMA_SQL, REQUIRED_COLUMNS, REQUIRED_KEYS, REQUIRED_TABLES } from "../src/store/schema.js"; +import { CORE_TABLES, CREATE_SCHEMA_SQL } from "../src/store/schema.js"; describe("PostgresStore", () => { it("round-trips core auth records through postgres", async () => { @@ -468,81 +459,35 @@ describe("createPostgresStore", () => { }); describe("PostgresStore.checkSchema", () => { - it("derives every table, typed column and unique key from the schema", () => { - expect(REQUIRED_TABLES).toEqual([ - "accounts", - "linked_identities", - "sessions", - "auth_attempts", - "private_command_receipts", - "pending_links", - "auth_completions", - "oauth_state_uses", - "capability_grants", - "entitlement_snapshots", - "consent_receipts", - "identity_moves", - "audit_events", - ]); - expect(REQUIRED_COLUMNS).toHaveLength(121); - expect(REQUIRED_COLUMNS).toEqual( - expect.arrayContaining([ - { table: "auth_completions", column: "code", type: "TEXT", nullable: false }, - { table: "sessions", column: "access_revision", type: "INTEGER", nullable: false }, - { table: "linked_identities", column: "profile_json", type: "JSONB", nullable: false }, - { table: "linked_identities", column: "username", type: "TEXT", nullable: true }, - { table: "entitlement_snapshots", column: "is_allowed", type: "BOOLEAN", nullable: false }, - { table: "auth_completions", column: "attempt_id", type: "TEXT", nullable: true }, - ]) - ); - expect(REQUIRED_KEYS).toHaveLength(19); - expect(REQUIRED_KEYS).toEqual( - expect.arrayContaining([ - { table: "linked_identities", columns: "provider,provider_user_id", predicate: "" }, - { table: "private_command_receipts", columns: "app_slug,idempotency_key", predicate: "" }, - { table: "oauth_state_uses", columns: "jti,phase", predicate: "" }, - { table: "consent_receipts", columns: "revokes_receipt_id", predicate: "revokes_receipt_id IS NOT NULL" }, - { table: "consent_receipts", columns: "account_id,id", predicate: "" }, - { table: "identity_moves", columns: "reverses_move_id", predicate: "reverses_move_id IS NOT NULL" }, - { table: "entitlement_snapshots", columns: "account_id,provider,scope", predicate: "" }, - { table: "auth_completions", columns: "app_slug,attempt_id", predicate: "attempt_id IS NOT NULL AND consumed_at IS NULL" }, - ]) - ); + it("runs connectivity check and verifies core tables exist", async () => { + const queries: Array<{ sql: string; params: unknown[] | undefined }> = []; + const store = new PostgresStore({ + query: async (sql: string, params?: unknown[]) => { + queries.push({ sql, params }); + return { rows: [], rowCount: 0 } as never; + }, + end: async () => {}, + connect: async () => ({}) as never, + }); + + await expect(store.checkSchema()).resolves.toBeUndefined(); + expect(queries).toHaveLength(2); + expect(queries[0]!.sql).toBe("SELECT 1"); + expect(queries[1]!.sql).toContain("to_regclass('public.' || name) IS NULL"); + expect(queries[1]!.params).toEqual([CORE_TABLES]); }); - // Soul pass 6: stripping parentheses and case merged predicates of - // different meaning. These are Postgres's own printed forms. - it("splits a printed predicate only at its top-level ANDs", () => { - expect(predicateConditions("((a OR b) AND c)")).toEqual(["a OR b", "c"]); - expect(predicateConditions("(a OR (b AND c))")).toEqual(["a OR (b AND c)"]); - expect(predicateConditions("((attempt_id IS NOT NULL) AND (consumed_at IS NULL))")).toEqual([ - "attempt_id IS NOT NULL", - "consumed_at IS NULL", - ]); - expect(predicateConditions("(s = 'x AND (y'::text)")).toEqual(["s = 'x AND (y'::text"]); - expect(predicateConditions('(("odd AND (name" IS NULL) AND b)')).toEqual(['"odd AND (name" IS NULL', "b"]); - expect(predicateConditions("")).toEqual([]); - }); + it("throws SCHEMA_MISSING when any core table is missing", async () => { + const store = new PostgresStore({ + query: async (sql: string) => { + if (sql === "SELECT 1") return { rows: [], rowCount: 0 } as never; + return { rows: [{ name: "consent_receipts" }], rowCount: 1 } as never; + }, + end: async () => {}, + connect: async () => ({}) as never, + }); - it("matches predicates by their conditions, never by case or by dropping structure", () => { - const keys = ["app_slug", "attempt_id"]; - expect(samePredicate("((a OR b) AND c)", "(a OR (b AND c))", keys, false)).toBe(false); - expect(samePredicate("(s = 'Pending'::text)", "(s = 'pending'::text)", keys, false)).toBe(false); - expect(samePredicate("((a) AND (b))", "((b) AND (a))", keys, false)).toBe(true); - expect(samePredicate("((a) AND (b))", "((a) AND (b) AND (c))", keys, false)).toBe(false); - }); - - it("lets a key column's IS NOT NULL be absent only where NULL keys cannot collide", () => { - const keys = ["app_slug", "attempt_id"]; - const declared = "((attempt_id IS NOT NULL) AND (consumed_at IS NULL))"; - expect(samePredicate(declared, "(consumed_at IS NULL)", keys, false)).toBe(true); - expect(samePredicate(declared, "(consumed_at IS NULL)", keys, true)).toBe(false); - expect(samePredicate(declared, "((consumed_at IS NULL) AND (other IS NOT NULL))", keys, false)).toBe(false); - }); - - it("requires a key without a predicate to have none", () => { - expect(samePredicate("", "", ["id"], false)).toBe(true); - expect(samePredicate("", "(id IS NOT NULL)", ["id"], false)).toBe(false); + await expect(store.checkSchema()).rejects.toMatchObject({ code: "SCHEMA_MISSING" }); }); }); @@ -889,12 +834,10 @@ describe.skipIf(!adminUrl)("startup against a live Postgres (HEIMDALL_TEST_PG_AD return { name, owner }; } - /** Grants the app role exactly `privileges`, per table, and nothing else. */ - async function grant(owner: Pool, privileges: Readonly>): Promise { + /** Grants the app role standard DML on all core tables. */ + async function grantAppRole(owner: Pool): Promise { await owner.query(`GRANT USAGE ON SCHEMA public TO ${role}`); - for (const [table, wanted] of Object.entries(privileges)) { - if (wanted.length > 0) await owner.query(`GRANT ${wanted.join(", ")} ON ${table} TO ${role}`); - } + await owner.query(`GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO ${role}`); } /** @@ -933,9 +876,9 @@ describe.skipIf(!adminUrl)("startup against a live Postgres (HEIMDALL_TEST_PG_AD expect(await start(urlFor(name), true)).toBe("started"); }); - it("serves every store operation with exactly the privileges it checks for", async () => { + it("serves every store operation as the app role", async () => { const { name, owner } = await appliedDatabase(); - await grant(owner, STORE_TABLE_PRIVILEGES); + await grantAppRole(owner); expect(await start(urlFor(name, role, rolePassword), false)).toBe("started"); const pool = fixturePool(urlFor(name, role, rolePassword)); @@ -949,44 +892,6 @@ describe.skipIf(!adminUrl)("startup against a live Postgres (HEIMDALL_TEST_PG_AD expect([...called].sort()).toEqual(offered.sort()); }); - it("refuses each privilege taken away, and the store needs each one", async () => { - const pairs = Object.entries(STORE_TABLE_PRIVILEGES).flatMap(([table, wanted]) => wanted.map((privilege) => ({ table, privilege }))); - expect(Object.keys(STORE_TABLE_PRIVILEGES).sort()).toEqual([...REQUIRED_TABLES].sort()); - for (const { table, privilege } of pairs) { - const { name, owner } = await appliedDatabase(); - await grant(owner, { ...STORE_TABLE_PRIVILEGES, [table]: STORE_TABLE_PRIVILEGES[table]!.filter((p) => p !== privilege) }); - - const message = await start(urlFor(name, role, rolePassword), false); - expect(message, `${table} without ${privilege}`).toBe(refusal("SCHEMA_PRIVILEGES")); - expect(message).not.toContain("CANARY"); - - const pool = fixturePool(urlFor(name, role, rolePassword)); - const failure = await exerciseStore(new PostgresStore(pool)).then( - () => undefined, - (error: unknown) => (error as { code?: string }).code - ); - await pool.end(); - expect(failure, `the store runs without ${privilege} on ${table}, so the check need not ask for it`).toBe("42501"); - for (const step of cleanup.splice(0).reverse()) await step(); - } - }); - - it("startup refuses a role that lacks DELETE on linked_identities", async () => { - expect(STORE_TABLE_PRIVILEGES.linked_identities).toContain("DELETE"); - const { name, owner } = await appliedDatabase(); - await grant(owner, { ...STORE_TABLE_PRIVILEGES, linked_identities: ["SELECT", "INSERT", "UPDATE"] }); - expect(await start(urlFor(name, role, rolePassword), false)).toBe(refusal("SCHEMA_PRIVILEGES")); - }); - - it("startup refuses a role that lacks INSERT or SELECT on identity_moves", async () => { - expect(STORE_TABLE_PRIVILEGES.identity_moves).toEqual(["SELECT", "INSERT"]); - for (const [kept, dropped] of [[["SELECT"], "INSERT"], [["INSERT"], "SELECT"]] as const) { - const { name, owner } = await appliedDatabase(); - await grant(owner, { ...STORE_TABLE_PRIVILEGES, identity_moves: kept }); - expect(await start(urlFor(name, role, rolePassword), false), `without ${dropped}`).toBe(refusal("SCHEMA_PRIVILEGES")); - } - }); - it("on real Postgres: the move contract holds", async () => { const { owner } = await appliedDatabase(); await exerciseMoveContract(new PostgresStore(owner)); @@ -1153,7 +1058,7 @@ describe.skipIf(!adminUrl)("startup against a live Postgres (HEIMDALL_TEST_PG_AD it("the step_up_assert nonce claim is single-use under the store's own role, and independent of the other phases", async () => { const { name, owner } = await appliedDatabase(); - await grant(owner, STORE_TABLE_PRIVILEGES); + await grantAppRole(owner); const pool = fixturePool(urlFor(name, role, rolePassword)); cleanup.push(async () => { await pool.end(); @@ -1167,7 +1072,8 @@ describe.skipIf(!adminUrl)("startup against a live Postgres (HEIMDALL_TEST_PG_AD it("a role without DELETE still claims, and leaves the old records", async () => { const { name, owner } = await appliedDatabase(); - await grant(owner, { ...STORE_TABLE_PRIVILEGES, oauth_state_uses: ["SELECT", "INSERT"] }); + await grantAppRole(owner); + await owner.query(`REVOKE DELETE ON oauth_state_uses FROM ${role}`); await seed(owner, "old"); const pool = fixturePool(urlFor(name, role, rolePassword)); cleanup.push(async () => { @@ -1181,223 +1087,15 @@ describe.skipIf(!adminUrl)("startup against a live Postgres (HEIMDALL_TEST_PG_AD it("refuses to apply the schema as a role that may not, and closes the store", async () => { const { name, owner } = await appliedDatabase(); - await grant(owner, STORE_TABLE_PRIVILEGES); + await grantAppRole(owner); expect(await start(urlFor(name, role, rolePassword), true)).toBe(refusal("42501")); }); - it("prints each declared predicate exactly as Postgres prints the applied index's", async () => { - const { owner } = await appliedDatabase(); - const printed = await printedDeclaredPredicates(owner, HEIMDALL_SCHEMA_REQUIREMENTS); - const appliedByIndex = { - auth_completions_attempt_unconsumed_unique_idx: "auth_completions", - consent_receipts_revokes_unique_idx: "consent_receipts", - identity_moves_reverses_unique_idx: "identity_moves", - }; - const partialKeys = REQUIRED_KEYS.flatMap((key, index) => (key.predicate === "" ? [] : [{ key, index }])); - expect(partialKeys.map(({ key }) => key.table).sort()).toEqual(Object.values(appliedByIndex).sort()); - for (const [indexName, table] of Object.entries(appliedByIndex)) { - const applied = await owner.query<{ predicate: string }>( - "SELECT pg_get_expr(indpred, indrelid) AS predicate FROM pg_index WHERE indexrelid = $1::regclass", - [indexName] - ); - const { index } = partialKeys.find(({ key }) => key.table === table)!; - expect(printed[index], indexName).toBe(applied.rows[0]!.predicate); - } - expect(printed.filter((predicate) => predicate !== "")).toHaveLength(partialKeys.length); - }); - it("refuses to boot with consent_receipts missing when the schema is not applied on startup", async () => { const { name, owner } = await appliedDatabase(); await owner.query("DROP TABLE consent_receipts"); expect(await start(urlFor(name), false)).toBe(refusal("SCHEMA_MISSING")); }); - - it("refuses a table whose primary key was dropped, even after applying the schema", async () => { - const { name, owner } = await appliedDatabase(); - await owner.query("ALTER TABLE auth_completions DROP CONSTRAINT auth_completions_pkey"); - - expect(await start(urlFor(name), false)).toBe(refusal("SCHEMA_MISSING")); - expect(await start(urlFor(name), true)).toBe(refusal("SCHEMA_MISSING")); - }); - - it("serves every store operation with each privilege granted column by column", async () => { - const { name, owner } = await appliedDatabase(); - await owner.query(`GRANT USAGE ON SCHEMA public TO ${role}`); - for (const [table, wanted] of Object.entries(STORE_TABLE_PRIVILEGES)) { - const columns = REQUIRED_COLUMNS.filter((column) => column.table === table).map((column) => column.column).join(", "); - for (const privilege of wanted) { - // DELETE removes rows and cannot be granted per column. - await owner.query(privilege === "DELETE" ? `GRANT DELETE ON ${table} TO ${role}` : `GRANT ${privilege} (${columns}) ON ${table} TO ${role}`); - } - } - - expect(await start(urlFor(name, role, rolePassword), false)).toBe("started"); - const pool = fixturePool(urlFor(name, role, rolePassword)); - cleanup.push(async () => { - await pool.end(); - }); - await exerciseStore(new PostgresStore(pool)); - }); - - it("refuses a privilege missing on one column of another table", async () => { - const { name, owner } = await appliedDatabase(); - await grant(owner, { ...STORE_TABLE_PRIVILEGES, auth_completions: [] }); - const columns = REQUIRED_COLUMNS.filter((column) => column.table === "auth_completions" && column.column !== "attempt_id") - .map((column) => column.column) - .join(", "); - for (const privilege of STORE_TABLE_PRIVILEGES.auth_completions!) { - await owner.query(`GRANT ${privilege} (${columns}) ON auth_completions TO ${role}`); - } - - expect(await start(urlFor(name, role, rolePassword), false)).toBe(refusal("SCHEMA_PRIVILEGES")); - }); - - it("names the TEMPORARY privilege when the role may not create temporary tables", async () => { - const { name, owner } = await appliedDatabase(); - await grant(owner, STORE_TABLE_PRIVILEGES); - await owner.query(`REVOKE TEMPORARY ON DATABASE ${name} FROM PUBLIC`); - - expect(await start(urlFor(name, role, rolePassword), false)).toBe( - "Postgres storage could not be prepared (SCHEMA_TEMP_PRIVILEGE); grant the database role TEMPORARY on its database." - ); - }); - - // The schema's own predicate splits into the same conditions raw or - // printed, so only a predicate whose printed form differs (a literal gains - // its cast) shows that the check compares Postgres's printing. - it("matches a declared predicate that Postgres prints differently from how it is written", async () => { - const { owner } = await appliedDatabase(); - await owner.query("CREATE TABLE predicate_probe (id INTEGER NOT NULL, state TEXT, attempts INTEGER)"); - await owner.query("CREATE UNIQUE INDEX predicate_probe_live ON predicate_probe (id) WHERE state = 'live' AND attempts > 0"); - const requirements = { - tables: ["predicate_probe"], - columns: [ - { table: "predicate_probe", column: "id", type: "INTEGER", nullable: false }, - { table: "predicate_probe", column: "state", type: "TEXT", nullable: true }, - { table: "predicate_probe", column: "attempts", type: "INTEGER", nullable: true }, - ], - keys: [{ table: "predicate_probe", columns: "id", predicate: "state = 'live' AND attempts > 0" }], - privileges: {}, - }; - - expect((await printedDeclaredPredicates(owner, requirements))[0]).toBe("((state = 'live'::text) AND (attempts > 0))"); - await expect(checkSchemaRequirements(owner, requirements)).resolves.toBeUndefined(); - }); - - it("refuses a privilege held on only some of a table's columns", async () => { - const { name, owner } = await appliedDatabase(); - await grant(owner, { ...STORE_TABLE_PRIVILEGES, audit_events: [] }); - await owner.query(`GRANT INSERT (id) ON audit_events TO ${role}`); - - expect(await start(urlFor(name, role, rolePassword), false)).toBe(refusal("SCHEMA_PRIVILEGES")); - }); - - // Each damage below leaves a database whose shape still resembles the - // schema but on which a store write fails or R21.1 no longer holds. A step - // starting with "!" is expected to fail and leave its mark (a failed - // CREATE INDEX CONCURRENTLY leaves an invalid index behind). - const seedDuplicates = [ - "INSERT INTO accounts VALUES ('acc', now(), now(), null, null)", - "INSERT INTO sessions VALUES ('s', 'acc', 'ghostlight', now(), now(), now() + interval '1 hour', '{}', 1)", - ]; - it.each([ - ["a key made DEFERRABLE (ON CONFLICT refuses it as an arbiter)", - ["ALTER TABLE private_command_receipts DROP CONSTRAINT private_command_receipts_pkey", "ALTER TABLE private_command_receipts ADD PRIMARY KEY (app_slug, idempotency_key) DEFERRABLE INITIALLY IMMEDIATE"]], - ["a key narrowed to one column, the other only INCLUDEd", - ["ALTER TABLE linked_identities DROP CONSTRAINT linked_identities_provider_provider_user_id_key", "CREATE UNIQUE INDEX li_include ON linked_identities(provider) INCLUDE (provider_user_id)"]], - ["a key widened by an expression column", - ["ALTER TABLE linked_identities DROP CONSTRAINT linked_identities_provider_provider_user_id_key", "CREATE UNIQUE INDEX li_expr ON linked_identities(provider, provider_user_id, lower(username))"]], - ["a key replaced by a partial one", - ["ALTER TABLE entitlement_snapshots DROP CONSTRAINT entitlement_snapshots_account_id_provider_scope_key", "CREATE UNIQUE INDEX es_partial ON entitlement_snapshots(account_id, provider, scope) WHERE is_allowed"]], - ["a key replaced by a plain index on the same columns", - ["ALTER TABLE linked_identities DROP CONSTRAINT linked_identities_provider_provider_user_id_key", "CREATE INDEX li_plain ON linked_identities(provider, provider_user_id)"]], - ["a key replaced by one on other columns of the same count", - ["ALTER TABLE linked_identities DROP CONSTRAINT linked_identities_provider_provider_user_id_key", "CREATE UNIQUE INDEX li_other ON linked_identities(provider, username)"]], - ["a key left only as an invalid index by a failed concurrent build", - [...seedDuplicates, - "ALTER TABLE linked_identities DROP CONSTRAINT linked_identities_provider_provider_user_id_key", - "INSERT INTO linked_identities (id, account_id, provider, provider_user_id, created_at, updated_at) VALUES ('l1', 'acc', 'youtube', 'dup', now(), now()), ('l2', 'acc', 'youtube', 'dup', now(), now())", - "!CREATE UNIQUE INDEX CONCURRENTLY li_ccnew ON linked_identities(provider, provider_user_id)", - "DELETE FROM linked_identities WHERE id = 'l2'"]], - ["the attempt index left invalid over duplicate attempts by a failed concurrent build", - [...seedDuplicates, - "DROP INDEX auth_completions_attempt_unconsumed_unique_idx", - "INSERT INTO auth_completions (code, attempt_id, app_slug, provider, mode, account_id, session_id, return_to, payload_json, created_at, expires_at) VALUES ('c1', 'att', 'ghostlight', 'discord', 'sign_in', 'acc', 's', 'https://x/', '{}', now(), now() + interval '1 hour'), ('c2', 'att', 'ghostlight', 'discord', 'sign_in', 'acc', 's', 'https://x/', '{}', now(), now() + interval '1 hour')", - "!CREATE UNIQUE INDEX CONCURRENTLY auth_completions_attempt_unconsumed_unique_idx ON auth_completions(app_slug, attempt_id) WHERE attempt_id IS NOT NULL AND consumed_at IS NULL"]], - // An interrupted DROP INDEX CONCURRENTLY leaves an index ready but not - // valid; the fixture sets that state directly (the admin role may). - ["a key left only as an index that is ready but not valid", - ["ALTER TABLE linked_identities DROP CONSTRAINT linked_identities_provider_provider_user_id_key", - "CREATE UNIQUE INDEX li_half_dropped ON linked_identities(provider, provider_user_id)", - "UPDATE pg_index SET indisvalid = false WHERE indexrelid = 'li_half_dropped'::regclass"]], - ["a key's first column compared under a case-insensitive collation", - ["CREATE COLLATION heimdall_ci (provider = icu, locale = 'und-u-ks-level2', deterministic = false)", - "ALTER TABLE linked_identities DROP CONSTRAINT linked_identities_provider_provider_user_id_key", - "CREATE UNIQUE INDEX li_ci_first ON linked_identities(provider COLLATE heimdall_ci, provider_user_id)"]], - // Soul pass 7: the key index compares under "C", but the column itself is - // case-insensitive, so the store's own lookups by provider_user_id match - // other users' ids. - ["a column declared under a case-insensitive collation, its key index under C", - ["CREATE COLLATION heimdall_ci (provider = icu, locale = 'und-u-ks-level2', deterministic = false)", - "ALTER TABLE linked_identities DROP CONSTRAINT linked_identities_provider_provider_user_id_key", - "ALTER TABLE linked_identities ALTER COLUMN provider_user_id TYPE text COLLATE heimdall_ci", - 'CREATE UNIQUE INDEX li_c ON linked_identities(provider, provider_user_id COLLATE "C")']], - ["a key compared under a case-insensitive collation (two users' ids become one row)", - ["CREATE COLLATION heimdall_ci (provider = icu, locale = 'und-u-ks-level2', deterministic = false)", - "ALTER TABLE linked_identities DROP CONSTRAINT linked_identities_provider_provider_user_id_key", - "CREATE UNIQUE INDEX li_ci ON linked_identities(provider, provider_user_id COLLATE heimdall_ci)"]], - ["the attempt index replaced by a plain one of the same name", - ["DROP INDEX auth_completions_attempt_unconsumed_unique_idx", "CREATE INDEX auth_completions_attempt_unconsumed_unique_idx ON auth_completions(app_slug, attempt_id)"]], - ["the attempt index made unique on every row (no predicate)", - ["DROP INDEX auth_completions_attempt_unconsumed_unique_idx", "CREATE UNIQUE INDEX auth_completions_attempt_unconsumed_unique_idx ON auth_completions(app_slug, attempt_id)"]], - ["the attempt index given another predicate", - ["DROP INDEX auth_completions_attempt_unconsumed_unique_idx", "CREATE UNIQUE INDEX auth_completions_attempt_unconsumed_unique_idx ON auth_completions(app_slug, attempt_id) WHERE attempt_id IS NOT NULL"]], - ["the attempt index narrowed by an extra condition", - ["DROP INDEX auth_completions_attempt_unconsumed_unique_idx", "CREATE UNIQUE INDEX auth_completions_attempt_unconsumed_unique_idx ON auth_completions(app_slug, attempt_id) WHERE attempt_id IS NOT NULL AND consumed_at IS NULL AND app_slug <> 'ghostlight'"]], - ["the attempt index with a condition ORed into its predicate", - ["DROP INDEX auth_completions_attempt_unconsumed_unique_idx", "CREATE UNIQUE INDEX auth_completions_attempt_unconsumed_unique_idx ON auth_completions(app_slug, attempt_id) WHERE (attempt_id IS NOT NULL OR app_slug = 'x') AND consumed_at IS NULL"]], - ["the attempt index made NULLS NOT DISTINCT without excluding NULL attempts", - ["DROP INDEX auth_completions_attempt_unconsumed_unique_idx", "CREATE UNIQUE INDEX auth_completions_attempt_unconsumed_unique_idx ON auth_completions(app_slug, attempt_id) NULLS NOT DISTINCT WHERE consumed_at IS NULL"]], - ["a column retyped", ["ALTER TABLE sessions ALTER COLUMN access_revision TYPE TEXT"]], - ["a created table's column dropped", ["ALTER TABLE auth_completions DROP COLUMN mode"]], - ["NOT NULL added to a column the store leaves null", ["ALTER TABLE auth_completions ALTER COLUMN attempt_id SET NOT NULL"]], - ["NOT NULL added to a nullable column of another table", - ["UPDATE linked_identities SET username = ''", "ALTER TABLE linked_identities ALTER COLUMN username SET NOT NULL"]], - ])("refuses %s", async (_damage, steps) => { - const { name, owner } = await appliedDatabase(); - for (const step of steps) { - if (step.startsWith("!")) await expect(owner.query(step.slice(1))).rejects.toBeDefined(); - else await owner.query(step); - } - - expect(await start(urlFor(name), false)).toBe(refusal("SCHEMA_MISSING")); - }); - - // Each change below leaves a database the store serves exactly as before. - it.each([ - ["a key index that carries extra INCLUDE columns", - ["ALTER TABLE linked_identities DROP CONSTRAINT linked_identities_provider_provider_user_id_key", "CREATE UNIQUE INDEX li_covering ON linked_identities(provider, provider_user_id) INCLUDE (username)"]], - ["the attempt index under another name", ["ALTER INDEX auth_completions_attempt_unconsumed_unique_idx RENAME TO attempt_idx_renamed"]], - ["the attempt index's conditions in the other order", - ["DROP INDEX auth_completions_attempt_unconsumed_unique_idx", "CREATE UNIQUE INDEX attempt_reordered ON auth_completions(app_slug, attempt_id) WHERE consumed_at IS NULL AND attempt_id IS NOT NULL"]], - // NULL attempt ids never collide in a unique index that treats NULLs as - // distinct (the default), so dropping that condition keeps the same rows unique. - ["the attempt index without its redundant attempt_id IS NOT NULL", - ["DROP INDEX auth_completions_attempt_unconsumed_unique_idx", "CREATE UNIQUE INDEX attempt_unconsumed ON auth_completions(app_slug, attempt_id) WHERE consumed_at IS NULL"]], - ["a lookup index dropped", ["DROP INDEX audit_events_lookup_idx", "DROP INDEX auth_completions_lookup_idx"]], - // Only a key's own columns decide which rows collide; an INCLUDEd column's - // collation does not, whatever it is. - ["a key index that INCLUDEs an undeclared case-insensitive column", - ["CREATE COLLATION heimdall_ci (provider = icu, locale = 'und-u-ks-level2', deterministic = false)", - "ALTER TABLE linked_identities ADD COLUMN operator_note text COLLATE heimdall_ci", - "ALTER TABLE linked_identities DROP CONSTRAINT linked_identities_provider_provider_user_id_key", - "CREATE UNIQUE INDEX li_note ON linked_identities(provider, provider_user_id) INCLUDE (operator_note)"]], - ])("accepts %s", async (_change, steps) => { - const { name, owner } = await appliedDatabase(); - for (const step of steps) await owner.query(step); - - expect(await start(urlFor(name), false)).toBe("started"); - }); });