From 59155638f0e77fb4d98126d3d9e92ca04fce29c5 Mon Sep 17 00:00:00 2001 From: Artexis10 Date: Tue, 1 Dec 2026 05:47:27 +0000 Subject: [PATCH 01/29] Move schema releases to a protected migration job Add a schema_releases table that only the schema owner writes, a release workflow in a protected environment, and a production build step that waits for its commit's schema release instead of migrating. The runner records a release after migrations and grants succeed, and records overtaken commits as superseded. Remove the build-time migration script. --- .github/quality.yml | 6 +- .github/workflows/migrate-database.yml | 67 ++++++ ...omem_identity_lock_and_schema_releases.sql | 82 +++++++ .../tasks.md | 8 +- package.json | 2 +- scripts/exomem-cloud-grants.sql | 13 + scripts/migrate.ts | 112 ++++++++- scripts/schema-release-plan.sh | 32 +++ scripts/vercel-maybe-migrate.ts | 60 ----- scripts/wait-for-schema-release.ts | 159 +++++++++++++ ...chema-release-postgres.integration.test.ts | 222 ++++++++++++++++++ .../__tests__/schema-release.test.ts | 213 +++++++++++++++++ 12 files changed, 901 insertions(+), 75 deletions(-) create mode 100644 .github/workflows/migrate-database.yml create mode 100644 migrations/0100_exomem_identity_lock_and_schema_releases.sql create mode 100755 scripts/schema-release-plan.sh delete mode 100644 scripts/vercel-maybe-migrate.ts create mode 100644 scripts/wait-for-schema-release.ts create mode 100644 src/lib/exomem-hosted/__tests__/schema-release-postgres.integration.test.ts create mode 100644 src/lib/exomem-hosted/__tests__/schema-release.test.ts diff --git a/.github/quality.yml b/.github/quality.yml index 2549116c..0a817644 100644 --- a/.github/quality.yml +++ b/.github/quality.yml @@ -41,8 +41,9 @@ classes: - "content/*" - "public/*" - "ops/*" # the hosted scheduler's cron jobs - # Run by every production deploy (vercel-build) or by the gateway image build. - - "scripts/vercel-maybe-migrate.ts" + # Run by every production deploy (vercel-build), by the schema release job or by the gateway image build. + - "scripts/wait-for-schema-release.ts" + - "scripts/schema-release-plan.sh" - "scripts/migrate.ts" - "scripts/*.sql" # the database grants migrate.ts applies - "scripts/verify-exomem-gateway-bundle.mjs" @@ -54,6 +55,7 @@ classes: - "scripts/strict-generation-visibility-cutover.ts" - "scripts/generate-jwt-keypair.ts" # `--commit` inserts the public key into signing_keys - ".github/workflows/publish-exomem-gateway.yml" # builds and publishes the gateway image + - ".github/workflows/migrate-database.yml" # applies the schema release to production - "instrumentation.ts" - "next.config.ts" - "tailwind.config.ts" diff --git a/.github/workflows/migrate-database.yml b/.github/workflows/migrate-database.yml new file mode 100644 index 00000000..3eae19e5 --- /dev/null +++ b/.github/workflows/migrate-database.yml @@ -0,0 +1,67 @@ +# Applies the database migrations and the grants script for the tip of `main`, +# then records the commit's schema release. The production build waits for that +# row (scripts/wait-for-schema-release.ts) and runs no migration itself. +# +# This is the only workflow that names the protected environment, and it starts +# only on a push to `main` or by hand. The environment accepts only `main` and +# holds the schema-owner connection string. +name: migrate-database + +on: + push: + branches: [main] + workflow_dispatch: + inputs: + dry_run: + description: List the pending migrations and change nothing + type: boolean + default: true + +permissions: + contents: read + +# One run applies at a time, and a running job is never cancelled: a cancelled +# migration would leave a half-applied step for the next run to find. A dry run +# changes nothing, so it takes a group of its own and never displaces a waiting +# run. +concurrency: + group: ${{ inputs.dry_run && format('schema-dry-run-{0}', github.run_id) || 'schema-release' }} + cancel-in-progress: false + +jobs: + migrate: + runs-on: ubuntu-latest + timeout-minutes: 30 + environment: production-schema + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + with: + fetch-depth: 0 + persist-credentials: false + # Reads git only. A commit behind the tip applies nothing. + - id: plan + run: scripts/schema-release-plan.sh "$GITHUB_SHA" >> "$GITHUB_OUTPUT" + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version: 24 + # No package install script runs in a job that holds the schema owner's credential. + - run: npm ci --ignore-scripts + # The only step that receives the secret. + - name: Migrate + env: + DATABASE_MIGRATION_URL: ${{ secrets.DATABASE_MIGRATION_URL }} + DRY_RUN: ${{ inputs.dry_run }} + TIP: ${{ steps.plan.outputs.tip }} + SUPERSEDED: ${{ steps.plan.outputs.superseded }} + run: | + if [ "$DRY_RUN" = "true" ]; then + if [ "$TIP" = "true" ]; then + node_modules/.bin/tsx scripts/migrate.ts --dry + else + echo "Dry run: $GITHUB_SHA is behind the tip of main, nothing to list." + fi + elif [ "$TIP" = "true" ]; then + node_modules/.bin/tsx scripts/migrate.ts --commit "$GITHUB_SHA" --superseded "$SUPERSEDED" + else + node_modules/.bin/tsx scripts/migrate.ts --record-superseded --superseded "$SUPERSEDED" + fi diff --git a/migrations/0100_exomem_identity_lock_and_schema_releases.sql b/migrations/0100_exomem_identity_lock_and_schema_releases.sql new file mode 100644 index 00000000..b2b5d44c --- /dev/null +++ b/migrations/0100_exomem_identity_lock_and_schema_releases.sql @@ -0,0 +1,82 @@ +-- Schema releases and the guard function (lock-cloud-identity-rows-and-record-issuance, +-- D2, D5, D9). This migration changes only the catalog: it adds one table and +-- the function that every guard trigger calls. + +-- A write to any table below waits behind this transaction until it commits. +-- The timeout bounds each wait, not the migration: when a lock stays busy, +-- the migration fails, the job fails, and the operator starts the job again. +-- One statement takes every lock in the order that admission and revocation +-- already write these tables (users, tenants, then grants, token families, +-- tokens); cell deletion writes them in another order, so a deadlock can fail +-- the migration the same way. SHARE ROW EXCLUSIVE is the mode that CREATE +-- TRIGGER takes. +SET LOCAL lock_timeout = '5s'; + +LOCK TABLE + exomem_users, + exomem_tenants, + exomem_marketplace_reviewer_credentials, + exomem_oauth_clients, + exomem_oauth_grants, + exomem_oauth_token_families, + exomem_oauth_refresh_tokens, + exomem_oauth_access_tokens, + exomem_cloud_service_credentials + IN SHARE ROW EXCLUSIVE MODE; + +-- The guard. Every trigger of this lock calls it. It refuses the statement +-- unless the role that runs it owns the table. It is not SECURITY DEFINER, +-- because it must see who the caller is. The pinned path keeps a temporary +-- table from taking the place of pg_class, and the body names nothing else. +CREATE FUNCTION exomem_refuse_unless_schema_owner() RETURNS trigger +LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp +AS $body$ +BEGIN + IF current_user IS DISTINCT FROM ( + SELECT pg_catalog.pg_get_userbyid(relowner) FROM pg_catalog.pg_class WHERE oid = TG_RELID + ) THEN + RAISE EXCEPTION 'EXOMEM_ROW_LOCKED: % on % is refused', TG_OP, TG_TABLE_NAME + USING ERRCODE = '42501'; + END IF; + RETURN NULL; +END; +$body$; + +REVOKE ALL ON FUNCTION exomem_refuse_unless_schema_owner() FROM PUBLIC; + +-- One row for each commit whose schema the release job applied or overtook. +-- The job inserts a row once and never updates it. +CREATE TABLE schema_releases ( + commit_sha text PRIMARY KEY CHECK (commit_sha ~ '^[0-9a-f]{40}$'), + -- A closed set that the release pipeline fixes, not data. + status text NOT NULL CHECK (status IN ('released', 'superseded')), + -- When the row was written: the release time of a released commit. + recorded_at timestamptz NOT NULL DEFAULT now() +); + +CREATE TRIGGER schema_releases_owner_only + AFTER INSERT OR UPDATE OR DELETE ON schema_releases + FOR EACH ROW EXECUTE FUNCTION exomem_refuse_unless_schema_owner(); +CREATE TRIGGER schema_releases_owner_only_truncate + BEFORE TRUNCATE ON schema_releases + FOR EACH STATEMENT EXECUTE FUNCTION exomem_refuse_unless_schema_owner(); + +-- Default privileges would give the web app's role every right on the new +-- table. Take back each right that any other role holds on it, in the +-- transaction that creates it. The grants script then gives select back. +DO $migration$ +DECLARE + holder record; +BEGIN + FOR holder IN + SELECT DISTINCT acl.grantee + FROM pg_class AS relation, aclexplode(relation.relacl) AS acl + WHERE relation.oid = to_regclass('schema_releases') AND acl.grantee <> relation.relowner + LOOP + EXECUTE format( + 'REVOKE ALL ON schema_releases FROM %s', + CASE WHEN holder.grantee = 0 THEN 'PUBLIC' ELSE quote_ident(pg_get_userbyid(holder.grantee)) END + ); + END LOOP; +END; +$migration$; diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md index b0b5f8b1..8be51d13 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md @@ -7,7 +7,7 @@ names each decision as D1 to D12. ## 1. Schema release pipeline (D9, D10) -- [ ] 1.1 In the first migration, set a lock timeout of five seconds for the +- [x] 1.1 In the first migration, set a lock timeout of five seconds for the transaction, then take D5's locks in D5's order with one `LOCK TABLE` statement. Create `schema_releases` (commit, status, release time) with a guard that refuses every write unless the schema owner runs it. Revoke every @@ -15,7 +15,7 @@ names each decision as D1 to D12. give the web app's role select on it and nothing else. Verify: as the web app's role, a select succeeds. An insert, update, delete and truncate are refused, also when the role holds those rights on the table. -- [ ] 1.2 In `scripts/migrate.ts`, accept a commit and a list of superseded +- [x] 1.2 In `scripts/migrate.ts`, accept a commit and a list of superseded commits, each as a full 40-character hash. With a commit, record its schema release after the grants script succeeds, and record each listed commit as superseded. Record with an insert that leaves an existing row unchanged. Add @@ -24,7 +24,7 @@ names each decision as D1 to D12. migration, a failed grants script, a dry run and a run with no commit record none. A commit that already has a row keeps its status. A malformed commit fails before the runner connects. -- [ ] 1.3 Add the migration workflow under `.github/workflows/`. It starts on a +- [x] 1.3 Add the migration workflow under `.github/workflows/`. It starts on a push to `main` and by hand, in the protected environment, with a dry-run input. It has a concurrency group that never cancels a running job, and a dry run stays outside that group. It has the tip-of-`main` check. It lists @@ -37,7 +37,7 @@ names each decision as D1 to D12. of `scripts/migrate.ts` succeeds. The test fails when a second workflow names the environment. The reviewer reads the three hardening properties in the diff. -- [ ] 1.4 Replace `scripts/vercel-maybe-migrate.ts` with a script that reads +- [x] 1.4 Replace `scripts/vercel-maybe-migrate.ts` with a script that reads the build's schema release, and point `vercel-build` at it. Keep the control-plane key check. Verify: the script continues on `released`, fails at once on `superseded`, and fails after its bounded wait when no row diff --git a/package.json b/package.json index fe3baf48..dda63f28 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,7 @@ "dev": "rm -rf .next && next dev --port 3000", "dev:next": "next dev", "build": "npm run check:exomem-theme && next build", - "vercel-build": "npm run check:exomem-theme && tsx scripts/vercel-maybe-migrate.ts && next build", + "vercel-build": "npm run check:exomem-theme && tsx scripts/wait-for-schema-release.ts && next build", "start": "next start", "gateway:start": "node dist/exomem-gateway/index.cjs", "gateway:typecheck": "tsc --noEmit", diff --git a/scripts/exomem-cloud-grants.sql b/scripts/exomem-cloud-grants.sql index cbac6e75..522143be 100644 --- a/scripts/exomem-cloud-grants.sql +++ b/scripts/exomem-cloud-grants.sql @@ -89,6 +89,19 @@ BEGIN ); END IF; + -- 1b. Schema releases (lock-cloud-identity-rows-and-record-issuance). The + -- guard in the migration holds whatever this section gives; the rights are + -- the first control and the guard the second. + -- + -- schema_releases: the web app's build reads its schema release and nothing + -- else touches the table from the web deployment. The migration job writes + -- it as the schema owner. + IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'substrate_app') + AND to_regclass('schema_releases') IS NOT NULL THEN + REVOKE ALL ON schema_releases FROM substrate_app; + GRANT SELECT ON schema_releases TO substrate_app; + END IF; + -- 2. C1-C1d, C5 and C6 are the exceptions to the schema-wide grant above: revoke -- whatever it (and PUBLIC) just gave every role on these four tables, then -- apply the exact C1 privilege table below. A rerun of this whole script diff --git a/scripts/migrate.ts b/scripts/migrate.ts index b951055e..9a5836c3 100644 --- a/scripts/migrate.ts +++ b/scripts/migrate.ts @@ -12,9 +12,18 @@ * statement applied successfully and the row was inserted, or the run aborts * and the file is left to be retried. * + * A caller that names a commit (`--commit `) also records that commit's + * schema release once the migrations and the grants script have succeeded, and + * records each commit of `--superseded ` as superseded. A run that + * names no commit records nothing. `--record-superseded` records the listed + * commits and applies nothing; the release job uses it for a run whose commit + * is no longer the tip of the default branch. + * * Usage: * tsx scripts/migrate.ts # apply pending migrations * tsx scripts/migrate.ts --dry # list pending migrations without applying + * tsx scripts/migrate.ts --commit [--superseded ] + * tsx scripts/migrate.ts --record-superseded --superseded */ import { existsSync, readFileSync, readdirSync } from "node:fs"; @@ -30,6 +39,15 @@ const RELEASE_A_MIGRATION = "0040_backup_version_commit.sql"; type Sql = Pick; +// The format of a git commit hash is fixed by git, so a pattern checks it. +const FULL_COMMIT_HASH = /^[0-9a-f]{40}$/; + +export function assertCommitHash(value: string, label: string): void { + if (!FULL_COMMIT_HASH.test(value)) { + throw new Error(`${label} must be a full 40-character commit hash`); + } +} + /** * `DATABASE_MIGRATION_URL`, when set, names PgBouncer's session-mode alias * (design D7): the schema-owning connection this runner holds a session-level @@ -166,13 +184,62 @@ async function applyFile(sql: Sql, migrationsDir: string, filename: string): Pro } } +/** + * Writes the schema release of `commit` and each superseded commit, in one + * transaction. A commit that already has a row keeps it, so a restarted run + * of a released commit leaves it released. The table is the schema owner's + * to write (migration 0100's guard). + */ +async function recordSchemaReleases( + sql: Sql, + commit: string | undefined, + superseded: readonly string[] +): Promise { + if ((await sql.query("SELECT to_regclass('schema_releases') AS name")).rows[0]?.name === null) { + // A stale run can reach a database that migration 0100 has not reached yet. + // No release can exist there, so there is nothing to supersede. + console.log("[migrate] schema_releases does not exist yet; nothing to record"); + return; + } + await sql.query("BEGIN"); + try { + if (commit !== undefined) { + await sql.query( + "INSERT INTO schema_releases (commit_sha, status) VALUES ($1, 'released') ON CONFLICT (commit_sha) DO NOTHING", + [commit] + ); + } + if (superseded.length > 0) { + await sql.query( + "INSERT INTO schema_releases (commit_sha, status) SELECT sha, 'superseded' FROM unnest($1::text[]) AS sha ON CONFLICT (commit_sha) DO NOTHING", + [superseded] + ); + } + await sql.query("COMMIT"); + } catch (error) { + await sql.query("ROLLBACK"); + throw error; + } + console.log( + `[migrate] recorded ${commit === undefined ? "no release" : `release ${commit}`} and ${superseded.length} superseded commit${superseded.length === 1 ? "" : "s"}` + ); +} + +/** Reads `--name value` or `--name=value`; undefined when the flag is absent. */ +function flagValue(argv: readonly string[], name: string): string | undefined { + const index = argv.findIndex((argument) => argument === name || argument.startsWith(`${name}=`)); + if (index < 0) return undefined; + const argument = argv[index]!; + const value = argument.includes("=") ? argument.slice(name.length + 1) : argv[index + 1]; + if (!value) throw new Error(`${name} needs a value`); + return value; +} + /** * Apply all pending migrations (or list them, if `dry: true`). * - * Exported so `scripts/vercel-maybe-migrate.ts` can call the same code path - * during Vercel production builds without spawning a child process. Throws on - * any migration failure so callers can decide whether to abort the build / - * non-zero exit / etc. + * Exported so tests call the same code path as the release job. Throws on any + * migration failure so callers can decide on a non-zero exit. */ export async function applyMigrations( opts: { @@ -180,17 +247,34 @@ export async function applyMigrations( databaseUrl?: string; migrationsDir?: string; grantsFile?: string; + /** Records this commit's schema release after the grants script succeeds. */ + commit?: string; + /** Commits that a newer schema release overtook; recorded as superseded. */ + supersededCommits?: readonly string[]; + /** Records `supersededCommits` and applies nothing. */ + recordSupersededOnly?: boolean; } = {} ): Promise { const { dry = false, migrationsDir = DEFAULT_MIGRATIONS_DIR, grantsFile = DEFAULT_GRANTS_FILE, + supersededCommits = [], } = opts; + // A malformed commit fails before the runner connects. + if (opts.commit !== undefined) assertCommitHash(opts.commit, "commit"); + for (const commit of supersededCommits) assertCommitHash(commit, "superseded commit"); + if (opts.recordSupersededOnly && (opts.commit !== undefined || supersededCommits.length === 0)) { + throw new Error("recording superseded commits takes a list of them and no commit"); + } const client = getClient(opts.databaseUrl); await client.connect(); let locked = false; try { + if (opts.recordSupersededOnly) { + await recordSchemaReleases(client, undefined, supersededCommits); + return; + } // A session lock is held on this dedicated connection across the applied // version recheck and every per-file transaction. A crashed runner drops // the connection and releases it automatically. @@ -260,6 +344,10 @@ export async function applyMigrations( console.log("FAIL"); throw new Error(`grants failed: ${err instanceof Error ? err.message : String(err)}`); } + // Only a run whose migrations and grants both succeeded reaches this line. + if (opts.commit !== undefined) { + await recordSchemaReleases(client, opts.commit, supersededCommits); + } } } finally { if (locked) { @@ -271,11 +359,19 @@ export async function applyMigrations( } } -// CLI entry point. Only runs when invoked directly (`tsx scripts/migrate.ts`) -// — not when imported as a module by `vercel-maybe-migrate.ts`. Standard ESM -// idiom: compare process.argv[1] against the file path of this module. +// CLI entry point. Only runs when invoked directly (`tsx scripts/migrate.ts`), +// not when a test imports the module. Standard ESM idiom: compare +// process.argv[1] against the file path of this module. if (process.argv[1] === fileURLToPath(import.meta.url)) { - applyMigrations({ dry: process.argv.includes("--dry") }).catch((err) => { + const argv = process.argv.slice(2); + (async () => { + await applyMigrations({ + dry: argv.includes("--dry"), + commit: flagValue(argv, "--commit"), + supersededCommits: flagValue(argv, "--superseded")?.split(",").filter(Boolean), + recordSupersededOnly: argv.includes("--record-superseded"), + }); + })().catch((err) => { console.error("[migrate] runner error:", err); process.exit(1); }); diff --git a/scripts/schema-release-plan.sh b/scripts/schema-release-plan.sh new file mode 100755 index 00000000..f6a62029 --- /dev/null +++ b/scripts/schema-release-plan.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +# Decides what the schema release job does for one commit. Prints two lines for +# the job's step output: +# tip=true|false whether the commit is the tip of the default branch +# superseded= the commits that the job records as superseded +# +# At the tip, the list holds the commit's recent first-parent ancestors. The +# migration runner records each one that has no row, so every commit that the +# previous schema release left behind gets a row, including one whose own run +# the concurrency group replaced. A commit that already has a row keeps it. +# Behind the tip, the list holds only the commit itself: it applies nothing. +# +# Usage: scripts/schema-release-plan.sh [remote] [branch] +set -euo pipefail + +commit="${1:?usage: schema-release-plan.sh [remote] [branch]}" +remote="${2:-origin}" +branch="${3:-main}" +# A bound on the history, not data: a gap longer than this leaves its oldest +# commits without a row, and a build of one of them fails after its wait. +history_limit=100 + +git fetch --quiet --no-tags "$remote" "$branch" +tip="$(git rev-parse FETCH_HEAD)" + +if [ "$tip" = "$commit" ]; then + echo "tip=true" + echo "superseded=$(git rev-list --first-parent --max-count="$history_limit" "$commit^" 2>/dev/null | paste -sd, -)" +else + echo "tip=false" + echo "superseded=$commit" +fi diff --git a/scripts/vercel-maybe-migrate.ts b/scripts/vercel-maybe-migrate.ts deleted file mode 100644 index 31c9c5c2..00000000 --- a/scripts/vercel-maybe-migrate.ts +++ /dev/null @@ -1,60 +0,0 @@ -/** - * Conditional production migration step for Vercel builds. - * - * Vercel runs `npm run vercel-build` (when present in package.json) on every - * deploy. We chain this script in front of `next build` so production deploys - * apply any pending migrations against the production database, while preview - * and development deploys skip migration entirely — preview builds must never - * touch the production schema. - * - * Failure mode: a failing migration aborts the build with a non-zero exit - * code, which Vercel surfaces as a failed deploy. The previous deploy stays - * live. This is the desired behavior — better to fail loudly than ship code - * that 500s on the first request to touch a missing table (the gui-v2.8.0 / - * migration 0015 incident, 2026-05-27). - * - * Manual override: set `SKIP_VERCEL_MIGRATE=1` in Vercel project env to - * temporarily disable. Use sparingly — the whole point of this script is to - * keep the schema and the deployed code in lockstep. The override skips the - * migrations only: a production deploy still needs a valid control-plane key. - */ - -import { applyMigrations } from './migrate'; -import { controlPlaneKeyFromEnv } from '../src/lib/exomem-hosted/security'; - -const env = process.env.VERCEL_ENV ?? 'unset'; -const skip = process.env.SKIP_VERCEL_MIGRATE === '1'; - -/** - * The Paddle webhook seals the payment-failed email, and the start, sign-in - * and OAuth routes seal or key their state, with EXOMEM_CONTROL_PLANE_KEY. - * Without a valid key each of them fails on every request, and Paddle only - * retries its webhook. Refusing the production deploy costs one blocked - * deploy (the previous one stays live) until the operator sets the key. - */ -function assertControlPlaneKey(): void { - try { - controlPlaneKeyFromEnv(); - } catch { - throw new Error('EXOMEM_CONTROL_PLANE_KEY is missing or not 32 bytes of base64url'); - } -} - -async function main() { - if (env === 'production') assertControlPlaneKey(); - if (skip) { - console.log('[vercel-maybe-migrate] SKIP_VERCEL_MIGRATE=1 — skipping'); - return; - } - if (env !== 'production') { - console.log(`[vercel-maybe-migrate] VERCEL_ENV=${env} — skipping (production-only)`); - return; - } - console.log('[vercel-maybe-migrate] VERCEL_ENV=production — applying pending migrations'); - await applyMigrations({ dry: false }); -} - -main().catch((err) => { - console.error('[vercel-maybe-migrate] failed:', err); - process.exit(1); -}); diff --git a/scripts/wait-for-schema-release.ts b/scripts/wait-for-schema-release.ts new file mode 100644 index 00000000..04e9a5fb --- /dev/null +++ b/scripts/wait-for-schema-release.ts @@ -0,0 +1,159 @@ +/** + * Production build gate for Vercel (`vercel-build`). + * + * A production build runs no migration. The release job in the protected + * environment applies the migrations and the grants script for the tip of the + * default branch, then records a schema release for that commit in + * `schema_releases`. This script reads that row with the web app's own role and + * lets the build continue only once the row for the build's commit says + * `released`: + * + * - `released`: continue. When a newer release exists, the log says so. + * - `superseded`: fail at once. A newer commit carries the schema release. + * - no row, no table, or a select the role may not run yet: keep waiting up to + * 15 minutes, then fail. The merge commit's build starts before the job has + * created the table or given the select right. + * + * Preview and development builds neither migrate nor wait. The control-plane + * key check stays for production. `SKIP_SCHEMA_RELEASE_WAIT=1` lets the + * operator ship one build without the wait during an incident. The previous + * deployment keeps serving after a failed build. + */ + +import { fileURLToPath } from "node:url"; +import { Client } from "pg"; +import { controlPlaneKeyFromEnv } from "../src/lib/exomem-hosted/security"; +import { assertCommitHash } from "./migrate"; + +const WAIT_MS = 15 * 60 * 1000; +const POLL_MS = 10_000; +const TAG = "[wait-for-schema-release]"; + +type SchemaReleaseRead = { + /** The status of the build's own commit, or null when it has no row. */ + status: string | null; + /** The newest released commit, or null when none exists. */ + newestReleased: string | null; +}; + +type Dependencies = { + read: (commit: string) => Promise; + sleep: (ms: number) => Promise; + now: () => number; + log: (line: string) => void; + waitMs?: number; + pollMs?: number; +}; + +/** + * The web app's role may lack the select right, or the table may not exist, + * until the release job for this very commit has run. Both mean "not yet". + */ +const NOT_READABLE_YET = new Set(["42P01", "42501"]); + +async function waitForSchemaRelease(commit: string, deps: Dependencies): Promise { + const { read, sleep, now, log, waitMs = WAIT_MS, pollMs = POLL_MS } = deps; + const deadline = now() + waitMs; + let lastReason = "no schema release row yet"; + for (;;) { + let row: SchemaReleaseRead | null = null; + try { + row = await read(commit); + } catch (error) { + const code = String((error as { code?: unknown }).code ?? "no code"); + lastReason = NOT_READABLE_YET.has(code) + ? `schema_releases is not readable yet (${code})` + : `schema release read failed (${code})`; + } + if (row?.status === "released") { + if (row.newestReleased !== null && row.newestReleased !== commit) { + log( + `${TAG} a newer schema release exists (${row.newestReleased}); this commit's schema is older` + ); + } + log(`${TAG} schema release for ${commit} exists`); + return; + } + if (row?.status === "superseded") { + throw new Error(`commit ${commit} is superseded: a newer commit carries the schema release`); + } + if (row) lastReason = "no schema release row yet"; + if (now() + pollMs > deadline) { + throw new Error( + `no schema release for ${commit} within ${Math.round(waitMs / 60_000)} minutes: ${lastReason}` + ); + } + log(`${TAG} waiting for the schema release of ${commit}: ${lastReason}`); + await sleep(pollMs); + } +} + +async function readFromDatabase(commit: string): Promise { + const url = process.env.DATABASE_URL; + if (!url) throw new Error("DATABASE_URL is not set"); + const client = new Client({ + connectionString: url, + connectionTimeoutMillis: 10_000, + query_timeout: 10_000, + }); + await client.connect(); + try { + const { rows } = await client.query<{ status: string | null; newest_released: string | null }>( + `SELECT + (SELECT status FROM schema_releases WHERE commit_sha = $1) AS status, + (SELECT commit_sha FROM schema_releases WHERE status = 'released' + ORDER BY recorded_at DESC LIMIT 1) AS newest_released`, + [commit] + ); + return { status: rows[0]?.status ?? null, newestReleased: rows[0]?.newest_released ?? null }; + } finally { + await client.end().catch(() => undefined); + } +} + +/** + * The Paddle webhook seals the payment-failed email, and the start, sign-in + * and OAuth routes seal or key their state, with EXOMEM_CONTROL_PLANE_KEY. + * Without a valid key each of them fails on every request, and Paddle only + * retries its webhook. Refusing the production deploy costs one blocked + * deploy (the previous one stays live) until the operator sets the key. + */ +function assertControlPlaneKey(): void { + try { + controlPlaneKeyFromEnv(); + } catch { + throw new Error("EXOMEM_CONTROL_PLANE_KEY is missing or not 32 bytes of base64url"); + } +} + +export async function checkSchemaRelease( + env: Record, + deps: Dependencies +): Promise { + const environment = env.VERCEL_ENV ?? "unset"; + if (environment !== "production") { + deps.log(`${TAG} VERCEL_ENV=${environment}: skipping (production only)`); + return; + } + assertControlPlaneKey(); + if (env.SKIP_SCHEMA_RELEASE_WAIT === "1") { + deps.log(`${TAG} SKIP_SCHEMA_RELEASE_WAIT=1: skipping the schema release check`); + return; + } + const commit = env.VERCEL_GIT_COMMIT_SHA; + if (!commit) throw new Error("a production build carries no commit (VERCEL_GIT_COMMIT_SHA)"); + assertCommitHash(commit, "VERCEL_GIT_COMMIT_SHA"); + await waitForSchemaRelease(commit, deps); +} + +if (process.argv[1] === fileURLToPath(import.meta.url)) { + checkSchemaRelease(process.env, { + read: readFromDatabase, + sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)), + now: () => Date.now(), + log: (line) => console.log(line), + }).catch((err) => { + console.error(`${TAG} failed:`, err instanceof Error ? err.message : err); + process.exit(1); + }); +} diff --git a/src/lib/exomem-hosted/__tests__/schema-release-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/schema-release-postgres.integration.test.ts new file mode 100644 index 00000000..ae91655d --- /dev/null +++ b/src/lib/exomem-hosted/__tests__/schema-release-postgres.integration.test.ts @@ -0,0 +1,222 @@ +import assert from "node:assert/strict"; +import { randomUUID } from "node:crypto"; +import { cp, mkdtemp, readdir, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { after, before, describe, it } from "node:test"; +import { Pool } from "pg"; +import { applyMigrations } from "../../../../scripts/migrate"; +import { ensureExomemPostgresTestExtensions } from "./postgres-test-extensions"; + +// Schema releases (design D9): the table the release job writes and the +// production build reads, and how the migration runner records into it. + +const databaseUrl = process.env.EXOMEM_TEST_DATABASE_URL; +const TEST_PASSWORD = "exomem-cloud-grants-test"; +const FIRST = "1".repeat(40); +const SECOND = "2".repeat(40); +const THIRD = "3".repeat(40); + +let adminPool: Pool | undefined; +let ownerPool: Pool | undefined; +let appPool: Pool | undefined; +let schema: string | undefined; +let ownerUrl: string; + +function roleUrl(role: string): string { + const url = new URL(databaseUrl!); + url.username = role; + url.password = TEST_PASSWORD; + url.searchParams.set("options", `-c search_path=${schema},public`); + return url.toString(); +} + +async function ensureRole(name: string): Promise { + await adminPool!.query( + `DO $$ + BEGIN + IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '${name}') THEN + CREATE ROLE ${name} LOGIN PASSWORD '${TEST_PASSWORD}'; + ELSE + ALTER ROLE ${name} WITH LOGIN PASSWORD '${TEST_PASSWORD}'; + END IF; + END + $$;` + ); +} + +async function releases(): Promise> { + const { rows } = await ownerPool!.query( + "SELECT commit_sha, status FROM schema_releases ORDER BY commit_sha" + ); + return rows; +} + +async function clearReleases(): Promise { + await ownerPool!.query("DELETE FROM schema_releases"); +} + +describe("schema releases PostgreSQL integration", { skip: !databaseUrl }, () => { + before(async () => { + schema = `schema_release_it_${randomUUID().replaceAll("-", "")}`; + await ensureExomemPostgresTestExtensions(databaseUrl!); + adminPool = new Pool({ connectionString: databaseUrl }); + await ensureRole("substrate_owner"); + await ensureRole("substrate_app"); + await adminPool.query(`CREATE SCHEMA "${schema}" AUTHORIZATION substrate_owner`); + await adminPool.query(`GRANT USAGE ON SCHEMA "${schema}" TO substrate_app`); + ownerUrl = roleUrl("substrate_owner"); + await applyMigrations({ databaseUrl: ownerUrl }); + ownerPool = new Pool({ connectionString: ownerUrl }); + appPool = new Pool({ connectionString: roleUrl("substrate_app") }); + }); + + after(async () => { + await appPool?.end(); + await ownerPool?.end(); + if (schema) await adminPool!.query(`DROP SCHEMA IF EXISTS "${schema}" CASCADE`); + await adminPool?.end(); + }); + + it("lets the web app's role read schema releases and refuses every write, also when it holds the rights", async () => { + await ownerPool!.query( + "INSERT INTO schema_releases (commit_sha, status) VALUES ($1, 'released')", + [FIRST] + ); + try { + const read = await appPool!.query( + "SELECT status FROM schema_releases WHERE commit_sha = $1", + [FIRST] + ); + assert.deepEqual(read.rows, [{ status: "released" }]); + + const writes = [ + `INSERT INTO schema_releases (commit_sha, status) VALUES ('${SECOND}', 'released')`, + `UPDATE schema_releases SET status = 'superseded' WHERE commit_sha = '${FIRST}'`, + "DELETE FROM schema_releases", + "TRUNCATE schema_releases", + ]; + for (const write of writes) { + await assert.rejects(appPool!.query(write), /permission denied/, write); + } + + // The guard holds when a grants script gives the rights anyway. + await ownerPool!.query( + "GRANT INSERT, UPDATE, DELETE, TRUNCATE ON schema_releases TO substrate_app" + ); + for (const write of writes) { + await assert.rejects(appPool!.query(write), /EXOMEM_ROW_LOCKED/, write); + } + assert.deepEqual(await releases(), [{ commit_sha: FIRST, status: "released" }]); + } finally { + await ownerPool!.query( + "REVOKE INSERT, UPDATE, DELETE, TRUNCATE ON schema_releases FROM substrate_app" + ); + await clearReleases(); + } + }); + + it("records a release and its superseded commits only after migrations and grants succeed", async () => { + await applyMigrations({ + databaseUrl: ownerUrl, + commit: SECOND, + supersededCommits: [FIRST, SECOND], + }); + assert.deepEqual(await releases(), [ + { commit_sha: FIRST, status: "superseded" }, + { commit_sha: SECOND, status: "released" }, + ]); + }); + + it("records nothing for a dry run, a run with no commit, a failed migration or a failed grants script", async () => { + await clearReleases(); + await applyMigrations({ + databaseUrl: ownerUrl, + dry: true, + commit: FIRST, + supersededCommits: [SECOND], + }); + await applyMigrations({ databaseUrl: ownerUrl }); + + const migrations = await mkdtemp(join(tmpdir(), "schema-release-migrations-")); + const brokenGrants = join(migrations, "broken-grants.sql"); + try { + for (const name of await readdir("migrations")) + await cp(join("migrations", name), join(migrations, name)); + await writeFile(join(migrations, "9999_fails.sql"), "SELECT 1 / 0;\n"); + await assert.rejects( + applyMigrations({ + databaseUrl: ownerUrl, + migrationsDir: migrations, + commit: FIRST, + supersededCommits: [SECOND], + }), + /9999_fails/ + ); + await rm(join(migrations, "9999_fails.sql")); + + await writeFile(brokenGrants, "SELECT 1 / 0;\n"); + await assert.rejects( + applyMigrations({ + databaseUrl: ownerUrl, + grantsFile: brokenGrants, + commit: FIRST, + supersededCommits: [SECOND], + }), + /grants failed/ + ); + } finally { + await rm(migrations, { recursive: true, force: true }); + } + assert.deepEqual(await releases(), []); + }); + + it("keeps the status of a commit that already has a row", async () => { + await clearReleases(); + await applyMigrations({ databaseUrl: ownerUrl, commit: FIRST }); + await applyMigrations({ + databaseUrl: ownerUrl, + commit: SECOND, + supersededCommits: [FIRST, THIRD], + }); + await applyMigrations({ + databaseUrl: ownerUrl, + recordSupersededOnly: true, + supersededCommits: [SECOND, THIRD], + }); + assert.deepEqual(await releases(), [ + { commit_sha: FIRST, status: "released" }, + { commit_sha: SECOND, status: "released" }, + { commit_sha: THIRD, status: "superseded" }, + ]); + }); + + it("records superseded commits with no migration, and fails a malformed commit before it connects", async () => { + await clearReleases(); + await applyMigrations({ + databaseUrl: ownerUrl, + recordSupersededOnly: true, + supersededCommits: [FIRST], + }); + assert.deepEqual(await releases(), [{ commit_sha: FIRST, status: "superseded" }]); + + // Nothing listens on this address, so only the check before connecting can answer. + const unreachable = "postgresql://nobody:none@127.0.0.1:1/none"; + await assert.rejects( + applyMigrations({ databaseUrl: unreachable, commit: "abc123" }), + /40-character/ + ); + await assert.rejects( + applyMigrations({ + databaseUrl: unreachable, + commit: FIRST, + supersededCommits: [`${SECOND}x`], + }), + /40-character/ + ); + await assert.rejects( + applyMigrations({ databaseUrl: unreachable, commit: "A".repeat(40) }), + /40-character/ + ); + }); +}); diff --git a/src/lib/exomem-hosted/__tests__/schema-release.test.ts b/src/lib/exomem-hosted/__tests__/schema-release.test.ts new file mode 100644 index 00000000..2fc35c8c --- /dev/null +++ b/src/lib/exomem-hosted/__tests__/schema-release.test.ts @@ -0,0 +1,213 @@ +import assert from "node:assert/strict"; +import { randomBytes } from "node:crypto"; +import { execFileSync } from "node:child_process"; +import { mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { afterEach, beforeEach, describe, it } from "node:test"; +import { parse } from "yaml"; +import { checkSchemaRelease } from "../../../../scripts/wait-for-schema-release"; + +// The production build's gate (scripts/wait-for-schema-release.ts), the release +// job's workflow file and its tip check. The database side runs in +// schema-release-postgres.integration.test.ts. + +const COMMIT = "a".repeat(40); +const NEWER = "b".repeat(40); +type Row = { status: string | null; newestReleased: string | null }; + +function productionEnv(extra: Record = {}) { + return { VERCEL_ENV: "production", VERCEL_GIT_COMMIT_SHA: COMMIT, ...extra }; +} + +/** A fake clock and database: each read returns the next scripted outcome. */ +function harness(outcomes: Array) { + let clock = 0; + const log: string[] = []; + const reads: number[] = []; + return { + log, + reads, + deps: { + read: async (): Promise => { + reads.push(clock); + const outcome = outcomes[Math.min(reads.length - 1, outcomes.length - 1)]!; + if ("code" in outcome) throw Object.assign(new Error("database"), { code: outcome.code }); + return outcome; + }, + sleep: async (ms: number) => { + clock += ms; + }, + now: () => clock, + log: (line: string) => log.push(line), + }, + }; +} + +describe("production build schema release gate", () => { + beforeEach(() => { + process.env.EXOMEM_CONTROL_PLANE_KEY = randomBytes(32).toString("base64url"); + }); + + it("continues on a released commit and says when a newer release exists", async () => { + const run = harness([{ status: "released", newestReleased: NEWER }]); + await checkSchemaRelease(productionEnv(), run.deps); + assert.equal(run.reads.length, 1); + assert.ok(run.log.some((line) => line.includes(`newer schema release exists (${NEWER})`))); + }); + + it("fails at once, without waiting, when its commit is superseded", async () => { + const run = harness([{ status: "superseded", newestReleased: NEWER }]); + await assert.rejects(checkSchemaRelease(productionEnv(), run.deps), /superseded/); + assert.equal(run.reads.length, 1); + }); + + it("fails after its bounded wait when no row appears", async () => { + const run = harness([{ status: null, newestReleased: null }]); + await assert.rejects(checkSchemaRelease(productionEnv(), run.deps), /within 15 minutes/); + assert.ok(run.reads.length > 10); + assert.ok(run.reads.at(-1)! <= 15 * 60 * 1000); + }); + + it("keeps waiting while the table is missing or the select is refused, then continues", async () => { + const run = harness([ + { code: "42P01" }, + { code: "42501" }, + { status: null, newestReleased: null }, + { status: "released", newestReleased: COMMIT }, + ]); + await checkSchemaRelease(productionEnv(), run.deps); + assert.equal(run.reads.length, 4); + }); + + it("fails a production build that carries no commit or a malformed one", async () => { + const run = harness([{ status: "released", newestReleased: COMMIT }]); + await assert.rejects( + checkSchemaRelease(productionEnv({ VERCEL_GIT_COMMIT_SHA: "" }), run.deps), + /no commit/ + ); + await assert.rejects( + checkSchemaRelease(productionEnv({ VERCEL_GIT_COMMIT_SHA: "abc123" }), run.deps), + /40-character/ + ); + assert.equal(run.reads.length, 0); + }); + + it("does nothing outside production, and logs a skip under the override", async () => { + const preview = harness([]); + await checkSchemaRelease({ VERCEL_ENV: "preview" }, preview.deps); + assert.equal(preview.reads.length, 0); + + const skipped = harness([]); + await checkSchemaRelease(productionEnv({ SKIP_SCHEMA_RELEASE_WAIT: "1" }), skipped.deps); + assert.equal(skipped.reads.length, 0); + assert.ok(skipped.log.some((line) => line.includes("SKIP_SCHEMA_RELEASE_WAIT"))); + }); + + it("still refuses a production build without the control-plane key", async () => { + delete process.env.EXOMEM_CONTROL_PLANE_KEY; + const run = harness([{ status: "released", newestReleased: COMMIT }]); + await assert.rejects(checkSchemaRelease(productionEnv(), run.deps), /EXOMEM_CONTROL_PLANE_KEY/); + await assert.rejects( + checkSchemaRelease(productionEnv({ SKIP_SCHEMA_RELEASE_WAIT: "1" }), run.deps), + /EXOMEM_CONTROL_PLANE_KEY/ + ); + }); +}); + +const WORKFLOWS = resolve(process.cwd(), ".github/workflows"); +const RELEASE_WORKFLOW = "migrate-database.yml"; +const SHA_PINNED_ACTION = /^[\w.-]+\/[\w.-]+@[0-9a-f]{40}$/; + +type Step = { uses?: string; run?: string; env?: Record }; +type Workflow = { + on: Record; + jobs: Record; +}; + +function readWorkflow(name: string): Workflow { + return parse(readFileSync(join(WORKFLOWS, name), "utf8")) as Workflow; +} + +describe("schema release workflow", () => { + const release = readWorkflow(RELEASE_WORKFLOW); + const environmentOf = (job: Workflow["jobs"][string]) => + typeof job.environment === "string" ? job.environment : job.environment?.name; + const environment = environmentOf(Object.values(release.jobs)[0]!)!; + + it("names the protected environment in no other workflow, and starts on no other event", () => { + assert.ok(environment, "the release job names its environment"); + for (const name of readdirSync(WORKFLOWS).filter((file) => /\.ya?ml$/.test(file))) { + if (name === RELEASE_WORKFLOW) continue; + assert.ok( + !readFileSync(join(WORKFLOWS, name), "utf8").includes(environment), + `${name} names the protected environment ${environment}` + ); + } + assert.deepEqual(Object.keys(release.on).sort(), ["push", "workflow_dispatch"]); + assert.deepEqual((release.on.push as { branches: string[] }).branches, ["main"]); + }); + + it("keeps the credential to one step, installs without scripts and pins every action", () => { + const steps = Object.values(release.jobs).flatMap((job) => job.steps); + const withSecret = steps.filter((step) => JSON.stringify(step.env ?? {}).includes("secrets.")); + assert.equal(withSecret.length, 1); + assert.match(withSecret[0]!.run ?? "", /scripts\/migrate\.ts/); + assert.ok(steps.some((step) => step.run === "npm ci --ignore-scripts")); + assert.ok( + !steps.some( + (step) => + /\bnpm (ci|install)\b/.test(step.run ?? "") && + !(step.run ?? "").includes("--ignore-scripts") + ) + ); + for (const step of steps.filter((candidate) => candidate.uses)) { + assert.match(step.uses!, SHA_PINNED_ACTION); + } + }); +}); + +describe("schema release tip check", () => { + let directory: string; + const git = (cwd: string, ...args: string[]) => + execFileSync("git", args, { cwd, encoding: "utf8" }).trim(); + const plan = (cwd: string, commit: string) => + Object.fromEntries( + execFileSync(join(process.cwd(), "scripts/schema-release-plan.sh"), [commit], { + cwd, + encoding: "utf8", + }) + .trim() + .split("\n") + .map((line) => line.split("=") as [string, string]) + ); + + beforeEach(() => { + directory = mkdtempSync(join(tmpdir(), "schema-release-plan-")); + }); + afterEach(() => rmSync(directory, { recursive: true, force: true })); + + it("passes at the tip with the older commits, and stops one commit behind it", () => { + const origin = join(directory, "origin"); + const clone = join(directory, "clone"); + execFileSync("git", ["init", "--quiet", "--initial-branch=main", origin]); + git(origin, "config", "user.email", "test@example.test"); + git(origin, "config", "user.name", "test"); + const commits: string[] = []; + for (const name of ["one", "two", "three"]) { + writeFileSync(join(origin, name), name); + git(origin, "add", name); + git(origin, "commit", "--quiet", "-m", name); + commits.push(git(origin, "rev-parse", "HEAD")); + } + execFileSync("git", ["clone", "--quiet", origin, clone]); + + const atTip = plan(clone, commits[2]!); + assert.equal(atTip.tip, "true"); + assert.deepEqual(atTip.superseded!.split(","), [commits[1], commits[0]]); + + const behind = plan(clone, commits[1]!); + assert.equal(behind.tip, "false"); + assert.equal(behind.superseded, commits[1]); + }); +}); From 2d6248317f3c9a6a819e2095e9b6c23a8acffbbf Mon Sep 17 00:00:00 2001 From: Artexis10 Date: Tue, 1 Dec 2026 05:56:46 +0000 Subject: [PATCH 02/29] Lock Cloud identity rows against the web app's database role Add guard triggers that refuse a change to an identity column of a grant, token family, access token, refresh token, client, tenant or service credential, a change of a set revocation or consumption time, and a delete or truncate of a grant, client, tenant, user, service credential or reviewer credential. Every guard holds for every role except the schema owner. Pin the search path of the schema owner's trigger and definer functions in the same migration. The grants script takes delete and the fixed-column update rights from the web app's role and revokes the trigger right on every table from every role but its owner. Narrow the grants test's every-right assertion to the tables the lock leaves alone. --- ...omem_identity_lock_and_schema_releases.sql | 203 +++++++++++++++++- .../design.md | 4 +- .../specs/exomem-hosted-mcp-oauth/spec.md | 2 +- .../tasks.md | 9 +- scripts/exomem-cloud-grants.sql | 101 ++++++++- .../cloud-grants-postgres.integration.test.ts | 23 +- 6 files changed, 329 insertions(+), 13 deletions(-) diff --git a/migrations/0100_exomem_identity_lock_and_schema_releases.sql b/migrations/0100_exomem_identity_lock_and_schema_releases.sql index b2b5d44c..e82018ca 100644 --- a/migrations/0100_exomem_identity_lock_and_schema_releases.sql +++ b/migrations/0100_exomem_identity_lock_and_schema_releases.sql @@ -1,6 +1,7 @@ --- Schema releases and the guard function (lock-cloud-identity-rows-and-record-issuance, +-- Schema releases and the identity lock (lock-cloud-identity-rows-and-record-issuance, -- D2, D5, D9). This migration changes only the catalog: it adds one table and --- the function that every guard trigger calls. +-- the guard triggers, and pins the search path of the functions that run as the +-- schema owner for another role. -- A write to any table below waits behind this transaction until it commits. -- The timeout bounds each wait, not the migration: when a lock stays busy, @@ -24,6 +25,88 @@ LOCK TABLE exomem_cloud_service_credentials IN SHARE ROW EXCLUSIVE MODE; +-- Pin the search path of every function that the database can run as the +-- schema owner for another role (design D2, "The create right"). A role that +-- can create a schema defines an operator there and puts that schema first on +-- its own path, and a trigger function that names an operator without a schema +-- then runs the role's operator as the schema owner. The set is read from the +-- catalog: the schema owner's trigger functions and SECURITY DEFINER functions +-- in this schema, and each SQL or PL/pgSQL function that a constraint, a column +-- default or an index calls. A function that belongs to an extension, and a C or +-- internal function, is out of the set: the first is not the schema owner's to +-- alter, and the second looks up no names. A function that one of them calls +-- runs under its caller's path. +-- +-- The health proof qualifies every name with its schema, so it gets only +-- pg_catalog and pg_temp. Every other function names schema objects without a +-- schema, so it gets pg_catalog, then the schemas of this migration's own path +-- that the schema owner, the bootstrap superuser (always role 10) or +-- pg_database_owner owns, then pg_temp. A schema that another role created never +-- enters a pin. When that filter leaves out a schema that a function needs, the +-- function fails with "does not exist" on its next call, and the operator pays: +-- they read the notice below, then fix the schema's owner or add a migration +-- that pins the function again. +DO $migration$ +DECLARE + target_schema text := current_schema(); + schema_owner oid := (SELECT oid FROM pg_roles WHERE rolname = current_user); + trusted_owners oid[] := ARRAY[ + schema_owner, 10::oid, (SELECT oid FROM pg_roles WHERE rolname = 'pg_database_owner') + ]; + owned_path text; + skipped_path text; + routine record; +BEGIN + SELECT string_agg(quote_ident(path.name), ', ' ORDER BY path.position) + FILTER (WHERE namespace.nspowner = ANY (trusted_owners)), + string_agg(quote_ident(path.name), ', ' ORDER BY path.position) + FILTER (WHERE namespace.nspowner <> ALL (trusted_owners)) + INTO owned_path, skipped_path + FROM unnest(current_schemas(false)) WITH ORDINALITY AS path(name, position) + JOIN pg_namespace AS namespace ON namespace.nspname = path.name; + IF skipped_path IS NOT NULL THEN + RAISE NOTICE 'search_path pins leave out schemas that another role owns: %', skipped_path; + END IF; + + FOR routine IN + SELECT proc.proname, pg_get_function_identity_arguments(proc.oid) AS arguments + FROM pg_proc AS proc + JOIN pg_language AS language ON language.oid = proc.prolang + WHERE proc.pronamespace = target_schema::regnamespace + AND proc.proowner = schema_owner + AND language.lanname NOT IN ('c', 'internal') + AND NOT EXISTS ( + SELECT 1 FROM pg_depend AS membership + WHERE membership.classid = 'pg_proc'::regclass AND membership.objid = proc.oid + AND membership.deptype = 'e' + ) + AND ( + proc.prorettype = 'trigger'::regtype + OR proc.prosecdef + OR EXISTS ( + SELECT 1 FROM pg_depend AS caller + LEFT JOIN pg_class AS caller_index + ON caller.classid = 'pg_class'::regclass AND caller_index.oid = caller.objid + WHERE caller.refclassid = 'pg_proc'::regclass AND caller.refobjid = proc.oid + AND ( + caller.classid IN ('pg_constraint'::regclass, 'pg_attrdef'::regclass) + OR caller_index.relkind IN ('i', 'I') + ) + ) + ) + LOOP + EXECUTE format( + 'ALTER FUNCTION %I.%I(%s) SET search_path = %s', + target_schema, routine.proname, routine.arguments, + CASE + WHEN routine.proname = 'exomem_record_memory_health_proof' THEN 'pg_catalog, pg_temp' + ELSE 'pg_catalog, ' || coalesce(owned_path || ', ', '') || 'pg_temp' + END + ); + END LOOP; +END; +$migration$; + -- The guard. Every trigger of this lock calls it. It refuses the statement -- unless the role that runs it owns the table. It is not SECURITY DEFINER, -- because it must see who the caller is. The pinned path keeps a temporary @@ -80,3 +163,119 @@ BEGIN END LOOP; END; $migration$; + +-- The lock (design D2). Each guard is an AFTER row trigger, so it judges the +-- stored row and the role that ran the statement, whatever a BEFORE trigger did +-- and whichever role a foreign-key action ran as. A WHEN clause on an update +-- guard lists the columns that must not change; no function runs for an update +-- that leaves them alone, such as the Home mint's upsert that changes only +-- updated_at. The grants script gives the web app's role update on the +-- complement of each list. A test asserts that every column of a column-locked +-- table is in exactly one of the two lists, so a new column forces a decision. +-- A one-way column is refused once it holds a value: it changes only from empty. + +CREATE TRIGGER exomem_oauth_grants_identity_lock + AFTER UPDATE ON exomem_oauth_grants + FOR EACH ROW WHEN ( + OLD.id IS DISTINCT FROM NEW.id OR OLD.user_id IS DISTINCT FROM NEW.user_id + OR OLD.tenant_id IS DISTINCT FROM NEW.tenant_id OR OLD.client_id IS DISTINCT FROM NEW.client_id + OR OLD.resource IS DISTINCT FROM NEW.resource OR OLD.created_at IS DISTINCT FROM NEW.created_at + OR OLD.reviewer_credential_id IS DISTINCT FROM NEW.reviewer_credential_id + OR OLD.candidate_id IS DISTINCT FROM NEW.candidate_id + OR OLD.assignment_id IS DISTINCT FROM NEW.assignment_id + OR OLD.assignment_generation IS DISTINCT FROM NEW.assignment_generation + OR OLD.staged_client_release_id IS DISTINCT FROM NEW.staged_client_release_id + OR (OLD.revoked_at IS NOT NULL AND NEW.revoked_at IS DISTINCT FROM OLD.revoked_at) + ) EXECUTE FUNCTION exomem_refuse_unless_schema_owner(); + +CREATE TRIGGER exomem_oauth_token_families_identity_lock + AFTER UPDATE ON exomem_oauth_token_families + FOR EACH ROW WHEN ( + OLD.id IS DISTINCT FROM NEW.id OR OLD.grant_id IS DISTINCT FROM NEW.grant_id + OR OLD.client_id IS DISTINCT FROM NEW.client_id OR OLD.expires_at IS DISTINCT FROM NEW.expires_at + OR OLD.created_at IS DISTINCT FROM NEW.created_at + OR OLD.candidate_id IS DISTINCT FROM NEW.candidate_id + OR OLD.assignment_id IS DISTINCT FROM NEW.assignment_id + OR OLD.assignment_generation IS DISTINCT FROM NEW.assignment_generation + OR OLD.staged_client_release_id IS DISTINCT FROM NEW.staged_client_release_id + OR OLD.reviewer_credential_id IS DISTINCT FROM NEW.reviewer_credential_id + OR (OLD.revoked_at IS NOT NULL AND NEW.revoked_at IS DISTINCT FROM OLD.revoked_at) + ) EXECUTE FUNCTION exomem_refuse_unless_schema_owner(); + +CREATE TRIGGER exomem_oauth_access_tokens_identity_lock + AFTER UPDATE ON exomem_oauth_access_tokens + FOR EACH ROW WHEN ( + OLD.id IS DISTINCT FROM NEW.id OR OLD.access_digest IS DISTINCT FROM NEW.access_digest + OR OLD.grant_id IS DISTINCT FROM NEW.grant_id OR OLD.family_id IS DISTINCT FROM NEW.family_id + OR OLD.client_id IS DISTINCT FROM NEW.client_id OR OLD.resource IS DISTINCT FROM NEW.resource + OR OLD.scopes IS DISTINCT FROM NEW.scopes OR OLD.expires_at IS DISTINCT FROM NEW.expires_at + OR OLD.created_at IS DISTINCT FROM NEW.created_at + OR OLD.candidate_id IS DISTINCT FROM NEW.candidate_id + OR OLD.assignment_id IS DISTINCT FROM NEW.assignment_id + OR OLD.assignment_generation IS DISTINCT FROM NEW.assignment_generation + OR OLD.staged_client_release_id IS DISTINCT FROM NEW.staged_client_release_id + OR OLD.reviewer_credential_id IS DISTINCT FROM NEW.reviewer_credential_id + OR (OLD.revoked_at IS NOT NULL AND NEW.revoked_at IS DISTINCT FROM OLD.revoked_at) + ) EXECUTE FUNCTION exomem_refuse_unless_schema_owner(); + +CREATE TRIGGER exomem_oauth_refresh_tokens_identity_lock + AFTER UPDATE ON exomem_oauth_refresh_tokens + FOR EACH ROW WHEN ( + OLD.id IS DISTINCT FROM NEW.id OR OLD.refresh_digest IS DISTINCT FROM NEW.refresh_digest + OR OLD.family_id IS DISTINCT FROM NEW.family_id + OR OLD.parent_refresh_token_id IS DISTINCT FROM NEW.parent_refresh_token_id + OR OLD.expires_at IS DISTINCT FROM NEW.expires_at OR OLD.created_at IS DISTINCT FROM NEW.created_at + OR OLD.candidate_id IS DISTINCT FROM NEW.candidate_id + OR OLD.assignment_id IS DISTINCT FROM NEW.assignment_id + OR OLD.assignment_generation IS DISTINCT FROM NEW.assignment_generation + OR OLD.staged_client_release_id IS DISTINCT FROM NEW.staged_client_release_id + OR OLD.oauth_client_id IS DISTINCT FROM NEW.oauth_client_id + OR OLD.reviewer_credential_id IS DISTINCT FROM NEW.reviewer_credential_id + OR (OLD.consumed_at IS NOT NULL AND NEW.consumed_at IS DISTINCT FROM OLD.consumed_at) + ) EXECUTE FUNCTION exomem_refuse_unless_schema_owner(); + +CREATE TRIGGER exomem_cloud_service_credentials_identity_lock + AFTER UPDATE ON exomem_cloud_service_credentials + FOR EACH ROW WHEN ( + OLD.id IS DISTINCT FROM NEW.id OR OLD.tenant_id IS DISTINCT FROM NEW.tenant_id + OR OLD.principal IS DISTINCT FROM NEW.principal + OR OLD.secret_digest IS DISTINCT FROM NEW.secret_digest + OR OLD.created_by_principal_digest IS DISTINCT FROM NEW.created_by_principal_digest + OR OLD.created_at IS DISTINCT FROM NEW.created_at + OR (OLD.revoked_at IS NOT NULL AND NEW.revoked_at IS DISTINCT FROM OLD.revoked_at) + OR (OLD.revoked_by_principal_digest IS NOT NULL + AND NEW.revoked_by_principal_digest IS DISTINCT FROM OLD.revoked_by_principal_digest) + ) EXECUTE FUNCTION exomem_refuse_unless_schema_owner(); + +-- Clients and tenants stay updatable except for the one identity column or two. +CREATE TRIGGER exomem_oauth_clients_identity_lock + AFTER UPDATE ON exomem_oauth_clients + FOR EACH ROW WHEN (OLD.id IS DISTINCT FROM NEW.id OR OLD.client_id IS DISTINCT FROM NEW.client_id) + EXECUTE FUNCTION exomem_refuse_unless_schema_owner(); + +CREATE TRIGGER exomem_tenants_identity_lock + AFTER UPDATE ON exomem_tenants + FOR EACH ROW WHEN (OLD.owner_user_id IS DISTINCT FROM NEW.owner_user_id) + EXECUTE FUNCTION exomem_refuse_unless_schema_owner(); + +-- No code deletes a grant, client, tenant, user, service credential or reviewer +-- credential. A truncate that cascades from another table fires the same guard. +DO $migration$ +DECLARE + locked_table text; +BEGIN + FOREACH locked_table IN ARRAY ARRAY[ + 'exomem_oauth_grants', 'exomem_oauth_clients', 'exomem_tenants', 'exomem_users', + 'exomem_cloud_service_credentials', 'exomem_marketplace_reviewer_credentials' + ] LOOP + EXECUTE format( + 'CREATE TRIGGER %I AFTER DELETE ON %I FOR EACH ROW EXECUTE FUNCTION exomem_refuse_unless_schema_owner()', + locked_table || '_delete_lock', locked_table + ); + EXECUTE format( + 'CREATE TRIGGER %I BEFORE TRUNCATE ON %I FOR EACH STATEMENT EXECUTE FUNCTION exomem_refuse_unless_schema_owner()', + locked_table || '_truncate_lock', locked_table + ); + END LOOP; +END; +$migration$; diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md index 4e0ecc5e..a84ec1d6 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md @@ -121,7 +121,7 @@ An event trigger that refuses `CREATE TRIGGER` to other roles would hold without - The first migration pins `search_path` on every function that the database can run as the schema owner for another role. These are the schema owner's trigger functions and `SECURITY DEFINER` functions in the schema, and each SQL or PL/pgSQL function in the schema that a constraint, a column default or an index calls. The set holds only functions that the schema owner owns and that belong to no extension: a C or internal function looks up no names, and the schema owner cannot alter an extension's functions. A function that one of them calls runs under its caller's path. - A function that qualifies every name gets `pg_catalog, pg_temp`. That covers the health proof and every function of this change. - - Every other one gets `pg_catalog`, then those schemas of the migration's own path that the schema owner, the bootstrap superuser or `pg_database_owner` owns, then `pg_temp`. On PostgreSQL 15 and later `public` belongs to `pg_database_owner`, which stands for the database's owner. A schema that another role created therefore never enters a pin. Its body names schema objects without a schema, and one calls `pgcrypto` in `public`. Production's path is `public`; a test's is its own schema, then `public`. Each body therefore resolves as it does today, except that a temporary table can no longer shadow a table. + - Every other one gets `pg_catalog`, then those schemas of the migration's own path that the schema owner, the bootstrap superuser or `pg_database_owner` owns, then `pg_temp`. On PostgreSQL 15 and later `public` belongs to `pg_database_owner`, which stands for the database's owner. A schema that another role created therefore never enters a pin. Its body names schema objects without a schema, and one calls `pgcrypto` in `public`. Production's path is `public`; a test's is its own schema, then `public`. Each body therefore resolves as it does today, except that a temporary table can no longer shadow a table. When the owner filter fires wrongly, because it leaves out a schema that a function needs, that function fails with a missing-object error on its next call. The operator pays: the migration prints the left-out schemas as a notice, and the repair is a reviewed change of the schema's owner or one more migration that pins the function again. - A test reads the catalog: each of those functions pins a path that starts with `pg_catalog` and ends with `pg_temp`. When the test fires wrongly, a migration that adds such a function fails CI until its author adds one `SET` clause. The author pays, and nothing reaches production. - The pinned path never names a schema that the role created, so the pin alone closes that route. It cannot close the route through a schema that the path names. The create right on the database also lets a role create a schema named after the schema owner, which the default path `"$user", public` searches first in the owner's own sessions. The rollout and the runbook's checks therefore read that no role other than a superuser, the schema owner or `pg_database_owner` holds a create right on the database or on a schema outside `pg_catalog` and `information_schema`, directly or through a membership, and list each schema that another role owns. Superusers hold every right, and each schema's owner holds the create right on it, so the read leaves those out. @@ -208,7 +208,7 @@ A record is deleted once its credential expired more than 90 days ago. A record The expiry is safe to key on. It is set at insert and is a fixed column afterwards. A credential cannot be used after its expiry, so no usable credential loses its record early. -A prune function deletes the records. The schema owner owns it, and it is `SECURITY DEFINER` with the same `search_path` rule as the recording function. Only the web app's role holds its execute right. Each call deletes at most 10,000 records. The reconcile job calls it once a run, beside the OAuth maintenance. At one run a minute it can delete 14.4 million records a day. D7 estimates 1.5 million new records a day at the load target. A backlog from a week without the job clears in about a day. +A prune function deletes the records. The schema owner owns it, and it is `SECURITY DEFINER` with the same `search_path` rule as the recording function. Of the roles granted the right to execute it, only the web app's role is one. Each call deletes at most 10,000 records. The reconcile job calls it once a run, beside the OAuth maintenance. At one run a minute it can delete 14.4 million records a day. D7 estimates 1.5 million new records a day at the load target. A backlog from a week without the job clears in about a day. The web app's role may call the function at any time, and it still deletes only records past their retention. The 90 days is a constant inside the function, not a setting: changing it needs a migration, which is a public commit. diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md index afc52705..deafbe35 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md @@ -132,7 +132,7 @@ The web app's database role SHALL hold update rights only on the columns its flo ### Requirement: Only the schema owner can attach a trigger or call the recording routine -The grants script SHALL revoke the trigger right on every table in the schema from every role except the table's owner, on every run. Every non-extension SQL or PL/pgSQL function that runs as the schema owner for another role SHALL pin a search path naming only schemas owned by the schema owner, the bootstrap superuser or the database's owner. `PUBLIC` SHALL not execute the guard, recording or prune routine. Only the web app's role SHALL execute the prune routine. +The grants script SHALL revoke the trigger right on every table in the schema from every role except the table's owner, on every run. Every non-extension SQL or PL/pgSQL function that runs as the schema owner for another role SHALL pin a search path naming only schemas owned by the schema owner, the bootstrap superuser or the database's owner. `PUBLIC` SHALL not execute the guard, recording or prune routine. Only the web app's role SHALL be granted the prune routine. #### Scenario: A role was given the trigger right by hand diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md index 8be51d13..3683eafb 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md @@ -61,11 +61,11 @@ names each decision as D1 to D12. from `PUBLIC` and from every role that is not the table's owner. Update the script's header, which names the exceptions to the schema-wide grant. Verify: task 5.6. -- [ ] 2.3 In `cloud-grants-postgres.integration.test.ts`, change the assertion +- [x] 2.3 In `cloud-grants-postgres.integration.test.ts`, change the assertion that the web app's role holds every right on every non-Cloud table. It now names the tables this change takes out. Verify: the suite passes, and the assertion fails if the lock's section is removed from the grants script. -- [ ] 2.4 Move each fixture step that changes a fixed column or deletes an +- [x] 2.4 Move each fixture step that changes a fixed column or deletes an identity row as the web app's role to the role that owns the schema. Change no assertion. Verify: every existing PostgreSQL suite passes with the guards in place. @@ -191,8 +191,9 @@ without truncate. Neither state holds the trigger right. the trigger right on any table in the schema, also after a hand-typed grant and a second run. The schema's functions that run with their owner's rights are exactly the health proof, the recording function and the prune function. - `PUBLIC` holds execute on none of them, nor on the guard function. Only the - web app's role holds execute on the prune function. Each function in the set + `PUBLIC` holds execute on none of them, nor on the guard function. Of the + roles granted execute on the prune function, only the web app's role is one. + Each function in the set of task 2.5, read from the catalog, pins a `search_path` that starts with `pg_catalog` and ends with `pg_temp`, and names only schemas that the schema owner, the bootstrap superuser or `pg_database_owner` owns. diff --git a/scripts/exomem-cloud-grants.sql b/scripts/exomem-cloud-grants.sql index 522143be..dabf7c60 100644 --- a/scripts/exomem-cloud-grants.sql +++ b/scripts/exomem-cloud-grants.sql @@ -29,6 +29,15 @@ -- review finding 3) -- the gateway connects to Postgres directly with -- its own role and runs that lookup itself. -- +-- 4. The identity lock (section 1b below): the exceptions to the schema-wide +-- grant in 1. substrate_app loses delete on grants, clients, tenants, users, +-- service credentials and reviewer credentials, and update on every column +-- of token families, access tokens, refresh tokens, grants and service +-- credentials except the ones its flows change. It reads schema_releases +-- and writes nothing there. The script also revokes the trigger right on +-- every table in the schema from every role but the table's owner. The +-- guards in migration 0100 hold whatever this script grants. +-- -- Applied by the migration runner (scripts/migrate.ts) after every run -- -- including one against a migrationsDir that never creates the Cloud -- tables at all, as the runner's own generic-runner tests do -- and by the @@ -50,6 +59,10 @@ DECLARE target_schema text := current_schema(); cloud_role text; oauth_table text; + lock_table text; + lock_columns text[]; + lock_column_list text; + lock_holder record; BEGIN -- 1. Schema-wide substrate_app DML, plus default privileges for whatever a -- later migration creates. Guarded on substrate_app existing so a database @@ -89,9 +102,10 @@ BEGIN ); END IF; - -- 1b. Schema releases (lock-cloud-identity-rows-and-record-issuance). The - -- guard in the migration holds whatever this section gives; the rights are - -- the first control and the guard the second. + -- 1b. Schema releases and the identity lock (lock-cloud-identity-rows-and-record-issuance). + -- Each part takes rights back from the schema-wide grant above, so it + -- runs after it. Guards in the migrations hold whatever this section + -- gives; the rights are the first control and the guards the second. -- -- schema_releases: the web app's build reads its schema release and nothing -- else touches the table from the web deployment. The migration job writes @@ -102,6 +116,87 @@ BEGIN GRANT SELECT ON schema_releases TO substrate_app; END IF; + -- Identity lock (design D2). The web app's role loses delete on the tables + -- whose rows it never deletes, and update on every column of the five + -- column-locked tables that its flows do not change. Insert stays whole-table: + -- an insert is the recorded operation. Each right is granted only when its + -- table and column exist, because a partial upgrade runs this script too. The + -- migration's guards hold when these rights are wrong, and a test asserts that + -- each column of a column-locked table is either in a list here or in its + -- guard's list, never both and never neither. + IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'substrate_app') THEN + FOREACH lock_table IN ARRAY ARRAY[ + 'exomem_oauth_grants', 'exomem_oauth_clients', 'exomem_tenants', 'exomem_users', + 'exomem_cloud_service_credentials', 'exomem_marketplace_reviewer_credentials' + ] LOOP + IF to_regclass(lock_table) IS NOT NULL THEN + EXECUTE format('REVOKE DELETE ON %I FROM substrate_app', lock_table); + END IF; + END LOOP; + + -- Column-locked tables: the changeable columns only. + FOR lock_table, lock_columns IN + SELECT * FROM (VALUES + ('exomem_oauth_grants', ARRAY['scopes', 'refresh_allowed', 'authorization_transaction_id', + 'updated_at', 'revoked_at', 'client_context_override']), + ('exomem_oauth_token_families', ARRAY['revoked_at', 'revoked_reason']), + ('exomem_oauth_access_tokens', ARRAY['revoked_at']), + ('exomem_oauth_refresh_tokens', ARRAY['consumed_at']), + ('exomem_cloud_service_credentials', ARRAY['revoked_at', 'revoked_by_principal_digest']) + ) AS locked(table_name, column_names) + LOOP + IF to_regclass(lock_table) IS NOT NULL THEN + EXECUTE format('REVOKE UPDATE ON %I FROM substrate_app', lock_table); + SELECT string_agg(quote_ident(column_name), ', ') INTO lock_column_list + FROM information_schema.columns + WHERE table_schema = target_schema AND table_name = lock_table + AND column_name = ANY (lock_columns); + IF lock_column_list IS NOT NULL THEN + EXECUTE format('GRANT UPDATE (%s) ON %I TO substrate_app', lock_column_list, lock_table); + END IF; + END IF; + END LOOP; + + -- Clients and tenants: every column except the identity columns. + FOR lock_table, lock_columns IN + SELECT * FROM (VALUES + ('exomem_oauth_clients', ARRAY['id', 'client_id']), + ('exomem_tenants', ARRAY['owner_user_id']) + ) AS locked(table_name, column_names) + LOOP + IF to_regclass(lock_table) IS NOT NULL THEN + EXECUTE format('REVOKE UPDATE ON %I FROM substrate_app', lock_table); + SELECT string_agg(quote_ident(column_name), ', ') INTO lock_column_list + FROM information_schema.columns + WHERE table_schema = target_schema AND table_name = lock_table + AND column_name <> ALL (lock_columns); + IF lock_column_list IS NOT NULL THEN + EXECUTE format('GRANT UPDATE (%s) ON %I TO substrate_app', lock_column_list, lock_table); + END IF; + END IF; + END LOOP; + END IF; + + -- The trigger right stays with the table's owner. A role that holds it on one + -- table can run its own code as the schema owner, and no guard holds against + -- that. Take it from PUBLIC and from every other role, on every table of the + -- schema, on every run. No flow creates a trigger; a tool that needs the right + -- fails until a reviewed change names it. + FOR lock_holder IN + SELECT DISTINCT relation.oid::regclass::text AS table_name, acl.grantee + FROM pg_class AS relation, aclexplode(relation.relacl) AS acl + WHERE relation.relnamespace = target_schema::regnamespace + AND relation.relkind IN ('r', 'p') + AND acl.privilege_type = 'TRIGGER' + AND acl.grantee <> relation.relowner + LOOP + EXECUTE format( + 'REVOKE TRIGGER ON %s FROM %s', + lock_holder.table_name, + CASE WHEN lock_holder.grantee = 0 THEN 'PUBLIC' ELSE quote_ident(pg_get_userbyid(lock_holder.grantee)) END + ); + END LOOP; + -- 2. C1-C1d, C5 and C6 are the exceptions to the schema-wide grant above: revoke -- whatever it (and PUBLIC) just gave every role on these four tables, then -- apply the exact C1 privilege table below. A rerun of this whole script diff --git a/src/lib/exomem-hosted/__tests__/cloud-grants-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-grants-postgres.integration.test.ts index ee231fb0..c7d07405 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-grants-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-grants-postgres.integration.test.ts @@ -53,6 +53,21 @@ const ACCESS_AUTH_TABLES = [ "exomem_cloud_access_challenges", ] as const; const CLOUD_RESOURCE = "https://cloud.example.test/mcp/v1"; +// The identity lock takes rights from these tables; each entry is what substrate_app holds on +// the table itself. A column grant is not a table right, so a column-locked table shows no update. +const NO_RIGHTS = { select: false, insert: false, update: false, delete: false }; +const LOCKED_TABLE_RIGHTS = { + exomem_oauth_grants: { select: true, insert: true, update: false, delete: false }, + exomem_oauth_token_families: { select: true, insert: true, update: false, delete: true }, + exomem_oauth_access_tokens: { select: true, insert: true, update: false, delete: true }, + exomem_oauth_refresh_tokens: { select: true, insert: true, update: false, delete: true }, + exomem_cloud_service_credentials: { select: true, insert: true, update: false, delete: false }, + exomem_oauth_clients: { select: true, insert: true, update: false, delete: false }, + exomem_tenants: { select: true, insert: true, update: false, delete: false }, + exomem_users: { select: true, insert: true, update: true, delete: false }, + exomem_marketplace_reviewer_credentials: { select: true, insert: true, update: true, delete: false }, + schema_releases: { ...NO_RIGHTS, select: true }, +} as const; let adminPool: Pool | undefined; let ownerPool: Pool | undefined; @@ -236,7 +251,8 @@ describe("Exomem Cloud grants PostgreSQL integration", { skip: !databaseUrl }, ( name !== "schema_migrations" && name !== "exomem_cloud_image_history" && name !== "exomem_cloud_imports" && - name !== "exomem_cloud_exports" + name !== "exomem_cloud_exports" && + !(name in LOCKED_TABLE_RIGHTS) ); assert.ok(nonCloudTables.length > 10, "sanity: the schema of record has plenty of non-Cloud tables"); const privileges = await tablePrivileges("substrate_app", nonCloudTables); @@ -248,6 +264,11 @@ describe("Exomem Cloud grants PostgreSQL integration", { skip: !databaseUrl }, ( assert.ok(grant.delete, `substrate_app should DELETE on ${name}`); } + const lockedPrivileges = await tablePrivileges("substrate_app", Object.keys(LOCKED_TABLE_RIGHTS)); + for (const [name, expected] of Object.entries(LOCKED_TABLE_RIGHTS)) { + assert.deepEqual(lockedPrivileges[name], expected, `substrate_app's rights on ${name}`); + } + // One real INSERT/DELETE round trip, not just has_table_privilege: a // simple table with no NOT NULL foreign keys. const host = `grant-roundtrip-${randomUUID()}.example.test`; From d66e91c6192234f88fbf07e0fd00237688d19179 Mon Sep 17 00:00:00 2001 From: Artexis10 Date: Tue, 1 Dec 2026 05:58:54 +0000 Subject: [PATCH 03/29] Record every issued credential in a log the web app cannot write Add exomem_cloud_issuance_log with a recording trigger on token families, access tokens, refresh tokens and service credentials. The recording function runs as the schema owner, so a credential insert fails when its record cannot be written. The log refuses every writer except the schema owner, and the migration writes one backfilled record for each existing credential row. A prune function, which only the web app's role may call, deletes records 90 days after their credential expires, in batches of 10000, and the reconcile job calls it. The grants script takes every right on the log from the web app's, gateway's and controller's roles, revokes execute on the new functions from PUBLIC, and gives the audit role read access. Add the log to the deletion receipt that the deletion-finish suite expects. --- ...omem_issuance_log_and_download_tickets.sql | 240 ++++++++++++++++++ scripts/exomem-cloud-grants.sql | 70 ++++- .../exomem-reconcile/__tests__/route.test.ts | 4 + src/app/api/cron/exomem-reconcile/route.ts | 5 + ...letion-finish-postgres.integration.test.ts | 5 +- .../cloud-grants-postgres.integration.test.ts | 1 + src/lib/exomem-hosted/issuance-maintenance.ts | 23 ++ 7 files changed, 346 insertions(+), 2 deletions(-) create mode 100644 migrations/0101_exomem_issuance_log_and_download_tickets.sql create mode 100644 src/lib/exomem-hosted/issuance-maintenance.ts diff --git a/migrations/0101_exomem_issuance_log_and_download_tickets.sql b/migrations/0101_exomem_issuance_log_and_download_tickets.sql new file mode 100644 index 00000000..2d5c6860 --- /dev/null +++ b/migrations/0101_exomem_issuance_log_and_download_tickets.sql @@ -0,0 +1,240 @@ +-- The issuance log (lock-cloud-identity-rows-and-record-issuance, D5, D6). +-- Every credential insert writes one log record in its own transaction, and a +-- record that cannot be written fails the insert. + +-- A write to a table below waits behind this transaction until it commits, +-- which is after the records for the existing rows are written. The timeout +-- bounds each wait, not the migration: when a lock stays busy, the migration +-- fails, the job fails, and the operator starts the job again. One statement +-- takes the locks in the order that revocation and issuance already write these +-- tables (token families, then tokens). SHARE ROW EXCLUSIVE is the mode that +-- CREATE TRIGGER takes. +SET LOCAL lock_timeout = '5s'; + +LOCK TABLE + exomem_oauth_token_families, + exomem_oauth_refresh_tokens, + exomem_oauth_access_tokens, + exomem_cloud_service_credentials + IN SHARE ROW EXCLUSIVE MODE; + +-- One record for each credential insert. Identifiers only: no token, digest, +-- secret, principal, path or address. No foreign keys, so a record outlives its +-- credential row and the insert stays cheap. +CREATE TABLE exomem_cloud_issuance_log ( + id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + -- The database clock when the record was written. A backfilled record holds + -- the migration's time, not the issuance time. + recorded_at timestamptz NOT NULL DEFAULT now(), + -- One kind for each table that has a recording trigger: a closed set that this + -- schema fixes, not data. + credential_kind text NOT NULL CHECK (credential_kind IN ( + 'access_token', 'refresh_token', 'token_family', 'service_credential', 'download_ticket' + )), + credential_id uuid NOT NULL, + grant_id uuid, + family_id uuid, + client_id uuid, + tenant_id uuid NOT NULL, + user_id uuid NOT NULL, + -- Empty for a credential that has no expiry, which the prune never deletes. + expires_at timestamptz, + -- The role that connected (session_user), not the owner that the recording + -- function runs as. + database_role text NOT NULL, + backfilled boolean NOT NULL DEFAULT false +); + +-- The prune reads by expiry, and one tenant's records list newest first. +CREATE INDEX exomem_cloud_issuance_log_expires_idx ON exomem_cloud_issuance_log (expires_at); +CREATE INDEX exomem_cloud_issuance_log_tenant_idx ON exomem_cloud_issuance_log (tenant_id, id); + +-- The log refuses every writer that is not the schema owner, whatever rights +-- the writer holds. The recording and prune functions run as the schema owner. +CREATE TRIGGER exomem_cloud_issuance_log_owner_only + AFTER INSERT OR UPDATE OR DELETE ON exomem_cloud_issuance_log + FOR EACH ROW EXECUTE FUNCTION exomem_refuse_unless_schema_owner(); +CREATE TRIGGER exomem_cloud_issuance_log_owner_only_truncate + BEFORE TRUNCATE ON exomem_cloud_issuance_log + FOR EACH STATEMENT EXECUTE FUNCTION exomem_refuse_unless_schema_owner(); + +-- Default privileges would give the web app's role every right on the new +-- table. Take back each right that any other role holds on it, in the +-- transaction that creates it. The grants script then gives back what each +-- role needs. +DO $migration$ +DECLARE + new_table text; + holder record; +BEGIN + FOREACH new_table IN ARRAY ARRAY['exomem_cloud_issuance_log'] LOOP + FOR holder IN + SELECT DISTINCT acl.grantee + FROM pg_class AS relation, aclexplode(relation.relacl) AS acl + WHERE relation.oid = to_regclass(new_table) AND acl.grantee <> relation.relowner + LOOP + EXECUTE format( + 'REVOKE ALL ON %I FROM %s', + new_table, + CASE WHEN holder.grantee = 0 THEN 'PUBLIC' ELSE quote_ident(pg_get_userbyid(holder.grantee)) END + ); + END LOOP; + END LOOP; +END; +$migration$; + +-- The recording function and the prune function run as the schema owner, +-- because they write a table on which their callers hold nothing. Each pins +-- `search_path = pg_catalog, pg_temp` and names every object with its schema, +-- and the migration creates each through current_schema(), so a temporary +-- table cannot take the place of the grant table or the log. +DO $migration$ +DECLARE + target_schema text := current_schema(); +BEGIN + -- TG_ARGV[0] is the credential kind. The function reads only what the row does + -- not name: a refresh token's grant through its token family, a tenant and a + -- user through the grant, a service credential's owner through its tenant. + -- Any missing row raises, so the credential insert fails closed. + EXECUTE format($definition$ + CREATE FUNCTION %1$I.exomem_record_issuance() RETURNS trigger + LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp + AS $body$ + DECLARE + kind text := TG_ARGV[0]; + the_grant uuid; + the_family uuid; + the_client uuid; + the_tenant uuid; + the_user uuid; + the_expiry timestamptz; + BEGIN + IF kind = 'token_family' THEN + the_grant := NEW.grant_id; the_family := NEW.id; + the_client := NEW.client_id; the_expiry := NEW.expires_at; + ELSIF kind = 'access_token' THEN + the_grant := NEW.grant_id; the_family := NEW.family_id; + the_client := NEW.client_id; the_expiry := NEW.expires_at; + ELSIF kind = 'refresh_token' THEN + SELECT family.grant_id, family.client_id INTO the_grant, the_client + FROM %1$I.exomem_oauth_token_families AS family WHERE family.id = NEW.family_id; + the_family := NEW.family_id; the_expiry := NEW.expires_at; + ELSIF kind = 'download_ticket' THEN + the_grant := NEW.grant_id; the_family := NEW.family_id; the_expiry := NEW.expires_at; + ELSIF kind = 'service_credential' THEN + the_tenant := NEW.tenant_id; + END IF; + + IF kind = 'service_credential' THEN + SELECT tenant.owner_user_id INTO the_user + FROM %1$I.exomem_tenants AS tenant WHERE tenant.id = the_tenant; + ELSE + SELECT grant_row.tenant_id, grant_row.user_id, coalesce(the_client, grant_row.client_id) + INTO the_tenant, the_user, the_client + FROM %1$I.exomem_oauth_grants AS grant_row WHERE grant_row.id = the_grant; + END IF; + IF the_user IS NULL THEN + RAISE EXCEPTION 'EXOMEM_ISSUANCE_UNRECORDED: no account for this credential' + USING ERRCODE = '23503'; + END IF; + + INSERT INTO %1$I.exomem_cloud_issuance_log ( + credential_kind, credential_id, grant_id, family_id, client_id, + tenant_id, user_id, expires_at, database_role + ) VALUES ( + kind, NEW.id, the_grant, the_family, the_client, + the_tenant, the_user, the_expiry, session_user + ); + RETURN NULL; + END; + $body$; + $definition$, target_schema); + + -- A record is kept until 90 days after its credential expires. The 90 days + -- is a constant here, not a setting: changing it takes a migration. A record + -- whose credential has no expiry never matches. One call deletes at most + -- 10000 records, so the reconcile job's call stays short. + EXECUTE format($definition$ + CREATE FUNCTION %1$I.exomem_prune_issuance_log() RETURNS integer + LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp + AS $body$ + DECLARE + deleted integer; + BEGIN + DELETE FROM %1$I.exomem_cloud_issuance_log AS record + USING ( + SELECT stale.id FROM %1$I.exomem_cloud_issuance_log AS stale + WHERE stale.expires_at < pg_catalog.now() - interval '90 days' + ORDER BY stale.expires_at + LIMIT 10000 + ) AS doomed + WHERE record.id = doomed.id; + GET DIAGNOSTICS deleted = ROW_COUNT; + RETURN deleted; + END; + $body$; + $definition$, target_schema); + + -- PostgreSQL gives PUBLIC execute on every new function. With it, any role + -- could attach the recording function to a trigger on its own table and + -- append records for rows that never existed. The grants script gives the web + -- app's role execute on the prune function only. + EXECUTE format('REVOKE ALL ON FUNCTION %I.exomem_record_issuance() FROM PUBLIC', target_schema); + EXECUTE format('REVOKE ALL ON FUNCTION %I.exomem_prune_issuance_log() FROM PUBLIC', target_schema); +END; +$migration$; + +-- One AFTER INSERT row trigger on each credential table. PostgreSQL checks the +-- execute right when a trigger is created, not when it fires, so no role but +-- the schema owner can attach the function. +CREATE TRIGGER exomem_oauth_token_families_issuance_record + AFTER INSERT ON exomem_oauth_token_families + FOR EACH ROW EXECUTE FUNCTION exomem_record_issuance('token_family'); +CREATE TRIGGER exomem_oauth_access_tokens_issuance_record + AFTER INSERT ON exomem_oauth_access_tokens + FOR EACH ROW EXECUTE FUNCTION exomem_record_issuance('access_token'); +CREATE TRIGGER exomem_oauth_refresh_tokens_issuance_record + AFTER INSERT ON exomem_oauth_refresh_tokens + FOR EACH ROW EXECUTE FUNCTION exomem_record_issuance('refresh_token'); +CREATE TRIGGER exomem_cloud_service_credentials_issuance_record + AFTER INSERT ON exomem_cloud_service_credentials + FOR EACH ROW EXECUTE FUNCTION exomem_record_issuance('service_credential'); + + +-- One backfilled record for each credential row that exists. It runs after the +-- triggers exist and inside the transaction that holds the locks, so no row can +-- land between the two steps without a record. +INSERT INTO exomem_cloud_issuance_log ( + credential_kind, credential_id, grant_id, family_id, client_id, + tenant_id, user_id, expires_at, database_role, backfilled +) +SELECT 'token_family', family.id, family.grant_id, family.id, family.client_id, + grant_row.tenant_id, grant_row.user_id, family.expires_at, current_user, true +FROM exomem_oauth_token_families AS family +JOIN exomem_oauth_grants AS grant_row ON grant_row.id = family.grant_id; + +INSERT INTO exomem_cloud_issuance_log ( + credential_kind, credential_id, grant_id, family_id, client_id, + tenant_id, user_id, expires_at, database_role, backfilled +) +SELECT 'access_token', token.id, token.grant_id, token.family_id, token.client_id, + grant_row.tenant_id, grant_row.user_id, token.expires_at, current_user, true +FROM exomem_oauth_access_tokens AS token +JOIN exomem_oauth_grants AS grant_row ON grant_row.id = token.grant_id; + +INSERT INTO exomem_cloud_issuance_log ( + credential_kind, credential_id, grant_id, family_id, client_id, + tenant_id, user_id, expires_at, database_role, backfilled +) +SELECT 'refresh_token', token.id, family.grant_id, token.family_id, family.client_id, + grant_row.tenant_id, grant_row.user_id, token.expires_at, current_user, true +FROM exomem_oauth_refresh_tokens AS token +JOIN exomem_oauth_token_families AS family ON family.id = token.family_id +JOIN exomem_oauth_grants AS grant_row ON grant_row.id = family.grant_id; + +INSERT INTO exomem_cloud_issuance_log ( + credential_kind, credential_id, tenant_id, user_id, database_role, backfilled +) +SELECT 'service_credential', credential.id, credential.tenant_id, tenant.owner_user_id, current_user, true +FROM exomem_cloud_service_credentials AS credential +JOIN exomem_tenants AS tenant ON tenant.id = credential.tenant_id; diff --git a/scripts/exomem-cloud-grants.sql b/scripts/exomem-cloud-grants.sql index dabf7c60..ace2b9e2 100644 --- a/scripts/exomem-cloud-grants.sql +++ b/scripts/exomem-cloud-grants.sql @@ -63,6 +63,7 @@ DECLARE lock_columns text[]; lock_column_list text; lock_holder record; + lock_role text; BEGIN -- 1. Schema-wide substrate_app DML, plus default privileges for whatever a -- later migration creates. Guarded on substrate_app existing so a database @@ -102,7 +103,7 @@ BEGIN ); END IF; - -- 1b. Schema releases and the identity lock (lock-cloud-identity-rows-and-record-issuance). + -- 1b. Identity lock and issuance log (lock-cloud-identity-rows-and-record-issuance). -- Each part takes rights back from the schema-wide grant above, so it -- runs after it. Guards in the migrations hold whatever this section -- gives; the rights are the first control and the guards the second. @@ -177,6 +178,73 @@ BEGIN END LOOP; END IF; + -- Issuance log (design D5, D6, D12). The web app's, the gateway's and the + -- controller's roles hold nothing on the log or on the sequence that numbers + -- its records. The guard refuses their writes whatever they hold, and the + -- recording and prune functions write as the schema owner. The audit role + -- reads the log and the columns that its checks compare, and nothing else. + IF to_regclass('exomem_cloud_issuance_log') IS NOT NULL THEN + REVOKE ALL ON exomem_cloud_issuance_log FROM PUBLIC; + FOREACH lock_role IN ARRAY ARRAY['substrate_app', 'exomem_gateway', 'exomem_cellctl', 'substrate_audit'] LOOP + IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = lock_role) THEN + EXECUTE format('REVOKE ALL ON exomem_cloud_issuance_log FROM %I', lock_role); + EXECUTE format( + 'REVOKE ALL ON SEQUENCE %s FROM %I', + pg_get_serial_sequence('exomem_cloud_issuance_log', 'id'), lock_role + ); + END IF; + END LOOP; + IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'substrate_audit') THEN + GRANT SELECT ON exomem_cloud_issuance_log TO substrate_audit; + -- The columns that the runbook's checks compare with the log: each credential + -- table's identifier and creation time, and the tenant's owner. + FOREACH lock_table IN ARRAY ARRAY[ + 'exomem_oauth_token_families', 'exomem_oauth_access_tokens', 'exomem_oauth_refresh_tokens', + 'exomem_cloud_service_credentials' + ] LOOP + IF to_regclass(lock_table) IS NOT NULL THEN + EXECUTE format('REVOKE ALL ON %I FROM substrate_audit', lock_table); + EXECUTE format('GRANT SELECT (id, created_at) ON %I TO substrate_audit', lock_table); + END IF; + END LOOP; + IF to_regclass('exomem_tenants') IS NOT NULL THEN + REVOKE ALL ON exomem_tenants FROM substrate_audit; + GRANT SELECT (id, owner_user_id) ON exomem_tenants TO substrate_audit; + END IF; + END IF; + END IF; + + -- PostgreSQL gives PUBLIC execute on every new function. The guard and the + -- recording function need no grant: PostgreSQL checks the right when a + -- trigger is created, not when it fires, and only the schema owner creates + -- these triggers. Only the web app's role may call the prune function, and + -- the reconcile job does so. + IF to_regprocedure('exomem_refuse_unless_schema_owner()') IS NOT NULL THEN + REVOKE ALL ON FUNCTION exomem_refuse_unless_schema_owner() FROM PUBLIC; + END IF; + IF to_regprocedure('exomem_record_issuance()') IS NOT NULL THEN + REVOKE ALL ON FUNCTION exomem_record_issuance() FROM PUBLIC; + END IF; + IF to_regprocedure('exomem_prune_issuance_log()') IS NOT NULL THEN + REVOKE ALL ON FUNCTION exomem_prune_issuance_log() FROM PUBLIC; + IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'substrate_app') THEN + GRANT EXECUTE ON FUNCTION exomem_prune_issuance_log() TO substrate_app; + END IF; + END IF; + FOREACH lock_role IN ARRAY ARRAY['substrate_app', 'exomem_gateway', 'exomem_cellctl', 'substrate_audit'] LOOP + IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = lock_role) THEN + IF to_regprocedure('exomem_refuse_unless_schema_owner()') IS NOT NULL THEN + EXECUTE format('REVOKE ALL ON FUNCTION exomem_refuse_unless_schema_owner() FROM %I', lock_role); + END IF; + IF to_regprocedure('exomem_record_issuance()') IS NOT NULL THEN + EXECUTE format('REVOKE ALL ON FUNCTION exomem_record_issuance() FROM %I', lock_role); + END IF; + IF lock_role <> 'substrate_app' AND to_regprocedure('exomem_prune_issuance_log()') IS NOT NULL THEN + EXECUTE format('REVOKE ALL ON FUNCTION exomem_prune_issuance_log() FROM %I', lock_role); + END IF; + END IF; + END LOOP; + -- The trigger right stays with the table's owner. A role that holds it on one -- table can run its own code as the schema owner, and no guard holds against -- that. Take it from PUBLIC and from every other role, on every table of the diff --git a/src/app/api/cron/exomem-reconcile/__tests__/route.test.ts b/src/app/api/cron/exomem-reconcile/__tests__/route.test.ts index 9c5983f6..9ec8c4b3 100644 --- a/src/app/api/cron/exomem-reconcile/__tests__/route.test.ts +++ b/src/app/api/cron/exomem-reconcile/__tests__/route.test.ts @@ -98,6 +98,9 @@ before(() => { }, }, }); + mock.module("@/lib/exomem-hosted/issuance-maintenance", { + namedExports: { pruneIssuanceState: async () => ({ records: 5 }) }, + }); mock.module("@/lib/exomem-hosted/email-change", { namedExports: { pruneExpiredExomemEmailChanges: async () => 2 }, }); @@ -233,6 +236,7 @@ describe("GET /api/cron/exomem-reconcile", () => { }, emailChangesPruned: 2, accessLogAuthPruned: null, + issuancePruned: { records: 5 }, }); }); diff --git a/src/app/api/cron/exomem-reconcile/route.ts b/src/app/api/cron/exomem-reconcile/route.ts index 8147848f..eee4a12f 100644 --- a/src/app/api/cron/exomem-reconcile/route.ts +++ b/src/app/api/cron/exomem-reconcile/route.ts @@ -8,6 +8,7 @@ import { retryPendingCloudCancellationNotices } from "@/lib/exomem-hosted/cloud- import { runBoundedCloudDeletionFinish } from "@/lib/exomem-hosted/cloud-deletion-finish"; import { runBoundedPaddleReceiptContacts } from "@/lib/exomem-hosted/paddle-receipt-contact"; import { pruneExpiredExomemEmailChanges } from "@/lib/exomem-hosted/email-change"; +import { pruneIssuanceState } from "@/lib/exomem-hosted/issuance-maintenance"; import { pruneExpiredOAuthState } from "@/lib/exomem-hosted/oauth-store"; import { promoteWaitlistedPeople, @@ -156,6 +157,9 @@ export async function GET(request: NextRequest): Promise { ) { throw new Error("EXOMEM_RECONCILIATION_LANE_FAILED"); } + // Retention of the issuance log. It reports a failure as null, so it cannot fail the + // route and needs no place in the settled lanes above. + const issuancePruned = await pruneIssuanceState(); const paddle = paddleResult.value; return NextResponse.json( { @@ -174,6 +178,7 @@ export async function GET(request: NextRequest): Promise { receiptContacts: contactsResult.value, emailChangesPruned: changesResult.value, accessLogAuthPruned: accessLogResult.value, + issuancePruned, oauth: { disabledCimd: oauthResult.value.disabledCimd, retiredAutoRegistered: oauthResult.value.retired.autoRegistered, diff --git a/src/lib/exomem-hosted/__tests__/cloud-deletion-finish-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-deletion-finish-postgres.integration.test.ts index b7abe1c0..ec107292 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-deletion-finish-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-deletion-finish-postgres.integration.test.ts @@ -581,11 +581,14 @@ async function tenantFootprint(tenantId: string): Promise /** * D4's receipt, exactly: nothing else may remain for the tenant, except email - * 07's row, which keeps its address only until 30 days after it settles. + * 07's row, which keeps its address only until 30 days after it settles. The + * issuance log keeps one identifier-only record for each credential row the + * tenant held: a token family, an access token and each refresh token. */ function d4Receipt(input: { cells?: number; refreshTokens?: number } = {}): Record { return { exomem_cloud_cells: input.cells ?? 1, + exomem_cloud_issuance_log: 2 + (input.refreshTokens ?? 0), exomem_email_outbox: 1, exomem_entitlements: 1, exomem_oauth_access_tokens: 1, diff --git a/src/lib/exomem-hosted/__tests__/cloud-grants-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-grants-postgres.integration.test.ts index c7d07405..be9be5c5 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-grants-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-grants-postgres.integration.test.ts @@ -67,6 +67,7 @@ const LOCKED_TABLE_RIGHTS = { exomem_users: { select: true, insert: true, update: true, delete: false }, exomem_marketplace_reviewer_credentials: { select: true, insert: true, update: true, delete: false }, schema_releases: { ...NO_RIGHTS, select: true }, + exomem_cloud_issuance_log: NO_RIGHTS, } as const; let adminPool: Pool | undefined; diff --git a/src/lib/exomem-hosted/issuance-maintenance.ts b/src/lib/exomem-hosted/issuance-maintenance.ts new file mode 100644 index 00000000..0183d4f9 --- /dev/null +++ b/src/lib/exomem-hosted/issuance-maintenance.ts @@ -0,0 +1,23 @@ +import { executeExomemSql as sql } from "./db"; + +type IssuancePruneResult = { + /** Records the log's prune function deleted, or null when the call failed. */ + records: number | null; +}; + +/** + * Retention for the issuance log. The log's own prune function holds the 90-day + * rule and its batch size, and deletes as the schema owner, because the web + * app's role holds nothing on the log. A failed call is reported as null, never + * as zero. + */ +export async function pruneIssuanceState(): Promise { + let records: number | null = null; + try { + const { rows } = await sql`/* exomem:prune-issuance-log */ SELECT exomem_prune_issuance_log() AS deleted`; + records = Number(rows[0]?.deleted); + } catch { + console.error("exomem-issuance: log retention failed"); + } + return { records }; +} From e21b73b14f93dbcc4f5534246f623020b44a6911 Mon Sep 17 00:00:00 2001 From: Artexis10 Date: Tue, 1 Dec 2026 06:23:29 +0000 Subject: [PATCH 04/29] Store a row for each download ticket and require it at the gateway The download handler stores one row for each ticket before it redirects. The gateway's login lookup finds the ticket's row by token family, path digest and expiry inside the same statement, so a correctly signed ticket without its row finds no login. The web app's role can select, insert and delete ticket rows and cannot update them. The gateway role reads three columns. The reconcile job removes expired rows in bounded batches. --- ...omem_issuance_log_and_download_tickets.sql | 45 +++++++-- scripts/exomem-cloud-grants.sql | 22 ++++- .../exomem-reconcile/__tests__/route.test.ts | 4 +- src/app/api/cron/exomem-reconcile/route.ts | 4 +- .../__tests__/cloud-download.test.ts | 23 +++++ src/exomem-gateway/cloud-handler.ts | 10 +- .../__tests__/cloud-download-ticket.test.ts | 22 +++-- .../cloud-grants-postgres.integration.test.ts | 1 + ...edia-download-postgres.integration.test.ts | 94 ++++++++++++++++++- .../exomem-hosted/cloud-download-ticket.ts | 18 +++- src/lib/exomem-hosted/cloud-media-download.ts | 23 ++++- src/lib/exomem-hosted/cloud-oauth.ts | 24 ++++- src/lib/exomem-hosted/issuance-maintenance.ts | 29 +++++- 13 files changed, 280 insertions(+), 39 deletions(-) diff --git a/migrations/0101_exomem_issuance_log_and_download_tickets.sql b/migrations/0101_exomem_issuance_log_and_download_tickets.sql index 2d5c6860..a8f0ad96 100644 --- a/migrations/0101_exomem_issuance_log_and_download_tickets.sql +++ b/migrations/0101_exomem_issuance_log_and_download_tickets.sql @@ -1,6 +1,6 @@ --- The issuance log (lock-cloud-identity-rows-and-record-issuance, D5, D6). --- Every credential insert writes one log record in its own transaction, and a --- record that cannot be written fails the insert. +-- The issuance log and the download ticket rows (lock-cloud-identity-rows-and-record-issuance, +-- D5, D6, D8). Every credential insert writes one log record in its own +-- transaction, and a record that cannot be written fails the insert. -- A write to a table below waits behind this transaction until it commits, -- which is after the records for the existing rows are written. The timeout @@ -8,7 +8,8 @@ -- fails, the job fails, and the operator starts the job again. One statement -- takes the locks in the order that revocation and issuance already write these -- tables (token families, then tokens). SHARE ROW EXCLUSIVE is the mode that --- CREATE TRIGGER takes. +-- CREATE TRIGGER takes. The download ticket table is created below, so no other +-- session can see it before the commit and it needs no lock. SET LOCAL lock_timeout = '5s'; LOCK TABLE @@ -58,16 +59,38 @@ CREATE TRIGGER exomem_cloud_issuance_log_owner_only_truncate BEFORE TRUNCATE ON exomem_cloud_issuance_log FOR EACH STATEMENT EXECUTE FUNCTION exomem_refuse_unless_schema_owner(); --- Default privileges would give the web app's role every right on the new --- table. Take back each right that any other role holds on it, in the --- transaction that creates it. The grants script then gives back what each +-- A download ticket is a signed message, and no row backed it. The web app now +-- stores one row for each ticket, and the gateway requires it. A row lives at +-- most one day. No foreign key: the gateway joins the token family when it +-- uses the ticket, and the recording function reads the row's grant. +CREATE TABLE exomem_cloud_download_tickets ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + family_id uuid NOT NULL, + grant_id uuid NOT NULL, + -- The ticket's claim: a SHA-256 of the path, in lower-case hexadecimal. + path_sha256 text NOT NULL CHECK (path_sha256 ~ '^[0-9a-f]{64}$'), + expires_at timestamptz NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + -- Two tickets with these three values carry the same authority and share one row. + UNIQUE (family_id, path_sha256, expires_at) +); +CREATE INDEX exomem_cloud_download_tickets_expiry_idx ON exomem_cloud_download_tickets (expires_at); + +-- A ticket row never changes, so every update is refused unless the schema owner runs it. +CREATE TRIGGER exomem_cloud_download_tickets_update_lock + AFTER UPDATE ON exomem_cloud_download_tickets + FOR EACH ROW EXECUTE FUNCTION exomem_refuse_unless_schema_owner(); + +-- Default privileges would give the web app's role every right on the two new +-- tables. Take back each right that any other role holds on them, in the +-- transaction that creates them. The grants script then gives back what each -- role needs. DO $migration$ DECLARE new_table text; holder record; BEGIN - FOREACH new_table IN ARRAY ARRAY['exomem_cloud_issuance_log'] LOOP + FOREACH new_table IN ARRAY ARRAY['exomem_cloud_issuance_log', 'exomem_cloud_download_tickets'] LOOP FOR holder IN SELECT DISTINCT acl.grantee FROM pg_class AS relation, aclexplode(relation.relacl) AS acl @@ -199,11 +222,13 @@ CREATE TRIGGER exomem_oauth_refresh_tokens_issuance_record CREATE TRIGGER exomem_cloud_service_credentials_issuance_record AFTER INSERT ON exomem_cloud_service_credentials FOR EACH ROW EXECUTE FUNCTION exomem_record_issuance('service_credential'); - +CREATE TRIGGER exomem_cloud_download_tickets_issuance_record + AFTER INSERT ON exomem_cloud_download_tickets + FOR EACH ROW EXECUTE FUNCTION exomem_record_issuance('download_ticket'); -- One backfilled record for each credential row that exists. It runs after the -- triggers exist and inside the transaction that holds the locks, so no row can --- land between the two steps without a record. +-- land between the two steps without a record. The ticket table is new and empty. INSERT INTO exomem_cloud_issuance_log ( credential_kind, credential_id, grant_id, family_id, client_id, tenant_id, user_id, expires_at, database_role, backfilled diff --git a/scripts/exomem-cloud-grants.sql b/scripts/exomem-cloud-grants.sql index ace2b9e2..7498cbf8 100644 --- a/scripts/exomem-cloud-grants.sql +++ b/scripts/exomem-cloud-grants.sql @@ -103,7 +103,7 @@ BEGIN ); END IF; - -- 1b. Identity lock and issuance log (lock-cloud-identity-rows-and-record-issuance). + -- 1b. Identity lock, issuance log and download tickets (lock-cloud-identity-rows-and-record-issuance). -- Each part takes rights back from the schema-wide grant above, so it -- runs after it. Guards in the migrations hold whatever this section -- gives; the rights are the first control and the guards the second. @@ -200,7 +200,7 @@ BEGIN -- table's identifier and creation time, and the tenant's owner. FOREACH lock_table IN ARRAY ARRAY[ 'exomem_oauth_token_families', 'exomem_oauth_access_tokens', 'exomem_oauth_refresh_tokens', - 'exomem_cloud_service_credentials' + 'exomem_cloud_service_credentials', 'exomem_cloud_download_tickets' ] LOOP IF to_regclass(lock_table) IS NOT NULL THEN EXECUTE format('REVOKE ALL ON %I FROM substrate_audit', lock_table); @@ -214,6 +214,24 @@ BEGIN END IF; END IF; + -- Download ticket rows (design D8): the web app stores and prunes them, the + -- gateway reads the three columns that it matches a ticket by, and no update + -- is granted. The migration's guard refuses an update whatever is granted. + IF to_regclass('exomem_cloud_download_tickets') IS NOT NULL THEN + REVOKE ALL ON exomem_cloud_download_tickets FROM PUBLIC; + IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'substrate_app') THEN + REVOKE ALL ON exomem_cloud_download_tickets FROM substrate_app; + GRANT SELECT, INSERT, DELETE ON exomem_cloud_download_tickets TO substrate_app; + END IF; + IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'exomem_gateway') THEN + REVOKE ALL ON exomem_cloud_download_tickets FROM exomem_gateway; + GRANT SELECT (family_id, path_sha256, expires_at) ON exomem_cloud_download_tickets TO exomem_gateway; + END IF; + IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'exomem_cellctl') THEN + REVOKE ALL ON exomem_cloud_download_tickets FROM exomem_cellctl; + END IF; + END IF; + -- PostgreSQL gives PUBLIC execute on every new function. The guard and the -- recording function need no grant: PostgreSQL checks the right when a -- trigger is created, not when it fires, and only the schema owner creates diff --git a/src/app/api/cron/exomem-reconcile/__tests__/route.test.ts b/src/app/api/cron/exomem-reconcile/__tests__/route.test.ts index 9ec8c4b3..104668a7 100644 --- a/src/app/api/cron/exomem-reconcile/__tests__/route.test.ts +++ b/src/app/api/cron/exomem-reconcile/__tests__/route.test.ts @@ -99,7 +99,7 @@ before(() => { }, }); mock.module("@/lib/exomem-hosted/issuance-maintenance", { - namedExports: { pruneIssuanceState: async () => ({ records: 5 }) }, + namedExports: { pruneIssuanceState: async () => ({ records: 5, tickets: 2 }) }, }); mock.module("@/lib/exomem-hosted/email-change", { namedExports: { pruneExpiredExomemEmailChanges: async () => 2 }, @@ -236,7 +236,7 @@ describe("GET /api/cron/exomem-reconcile", () => { }, emailChangesPruned: 2, accessLogAuthPruned: null, - issuancePruned: { records: 5 }, + issuancePruned: { records: 5, tickets: 2 }, }); }); diff --git a/src/app/api/cron/exomem-reconcile/route.ts b/src/app/api/cron/exomem-reconcile/route.ts index eee4a12f..cb7d8c56 100644 --- a/src/app/api/cron/exomem-reconcile/route.ts +++ b/src/app/api/cron/exomem-reconcile/route.ts @@ -157,8 +157,8 @@ export async function GET(request: NextRequest): Promise { ) { throw new Error("EXOMEM_RECONCILIATION_LANE_FAILED"); } - // Retention of the issuance log. It reports a failure as null, so it cannot fail the - // route and needs no place in the settled lanes above. + // Retention of the issuance log and the ticket rows. It reports each part as null on failure, + // so it cannot fail the route and needs no place in the settled lanes above. const issuancePruned = await pruneIssuanceState(); const paddle = paddleResult.value; return NextResponse.json( diff --git a/src/exomem-gateway/__tests__/cloud-download.test.ts b/src/exomem-gateway/__tests__/cloud-download.test.ts index dc79ca9b..6864936b 100644 --- a/src/exomem-gateway/__tests__/cloud-download.test.ts +++ b/src/exomem-gateway/__tests__/cloud-download.test.ts @@ -392,6 +392,29 @@ describe("Cloud download ticket at the gateway", () => { ); }); + it("looks the login up by the ticket's own path digest and expiry, so a ticket without its stored row finds none", async () => { + const now = Math.floor(Date.now() / 1000); + let selector: unknown; + const response = await handleCloudDownloadRequest( + ticketRequest(ticket({ now })), + ticketDeps({ + findLogin: async (looked) => { + selector = looked; + return null; + }, + }) + ); + assert.equal(response.status, 401); + assert.deepEqual(selector, { + familyId: CLAIMS.familyId, + grantId: CLAIMS.grantId, + ticket: { + pathSha256: createHash("sha256").update(PATH, "utf8").digest("hex"), + expiresAt: now + downloadTicketLifetimeSeconds(), + }, + }); + }); + it("refuses a ticket that is expired, for another path, forged or the wrong shape before any lookup or cell contact", async () => { const issuedLongAgo = Math.floor(Date.now() / 1000) - downloadTicketLifetimeSeconds() - 5; const cases: Array<[string, Request]> = [ diff --git a/src/exomem-gateway/cloud-handler.ts b/src/exomem-gateway/cloud-handler.ts index 2083c40a..7d9be993 100644 --- a/src/exomem-gateway/cloud-handler.ts +++ b/src/exomem-gateway/cloud-handler.ts @@ -57,6 +57,7 @@ import { REQUIRED_CLOUD_SCOPES, type ActiveCloudOAuthAccessToken, type ActiveCloudOAuthLogin, + type CloudDownloadTicketRow, } from "../lib/exomem-hosted/cloud-oauth"; import { findCloudServiceCredential, @@ -1118,7 +1119,12 @@ async function serveTicketDownload( cellId: claims.cellId, // Its own identity, so a long download never spends the Home channel's MCP bucket or slots. identityKey: `${claims.tenantId}:media-download`, - selector: { familyId: claims.familyId, grantId: claims.grantId }, + selector: { + familyId: claims.familyId, + grantId: claims.grantId, + // The login lookup also requires the ticket's stored row. + ticket: { pathSha256: claims.pathSha256, expiresAt: claims.expiresAt }, + }, // Only the app mints a ticket, and only from the owner's first-party login // of this tenant and cell. Anything else is refused whatever its MAC says. accepts: (login) => @@ -1135,7 +1141,7 @@ async function serveTicketDownload( type DownloadCaller = { cellId: string; identityKey: string; - selector: { familyId: string; grantId: string }; + selector: { familyId: string; grantId: string; ticket?: CloudDownloadTicketRow }; /** Whether the login, as it is now, is the one this credential may use. */ accepts(login: ActiveCloudOAuthLogin): boolean; refuse(): Response; diff --git a/src/lib/exomem-hosted/__tests__/cloud-download-ticket.test.ts b/src/lib/exomem-hosted/__tests__/cloud-download-ticket.test.ts index 44f7ba86..4bea46db 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-download-ticket.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-download-ticket.test.ts @@ -1,4 +1,5 @@ import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; import { describe, it } from "node:test"; import { downloadTicketLifetimeSeconds, @@ -14,6 +15,7 @@ const LOGIN = { grantId: "33333333-3333-4333-8333-333333333333", }; const PATH = "Recordings/standup.mp4"; +const PATH_SHA256 = createHash("sha256").update(PATH, "utf8").digest("hex"); const NOW = 1_800_000_000; const FIFTEEN_MINUTES = 15 * 60; const ONE_HOUR = 60 * 60; @@ -23,15 +25,19 @@ function ticket(options: Parameters[2] = { now: NOW } } describe("download ticket", () => { - it("names the login it was minted for", () => { - assert.deepEqual(verifyDownloadTicket(ticket(), PATH, KEY, { now: NOW }), LOGIN); + it("names the login it was minted for, and the digest and expiry that its row is keyed by", () => { + assert.deepEqual(verifyDownloadTicket(ticket(), PATH, KEY, { now: NOW }), { + ...LOGIN, + pathSha256: PATH_SHA256, + expiresAt: NOW + FIFTEEN_MINUTES, + }); }); it("lives fifteen minutes unless configured, so a ticket in an address is a short bearer", () => { assert.equal(downloadTicketLifetimeSeconds({}), FIFTEEN_MINUTES); - assert.deepEqual( - verifyDownloadTicket(ticket(), PATH, KEY, { now: NOW + FIFTEEN_MINUTES - 1 }), - LOGIN + assert.equal( + verifyDownloadTicket(ticket(), PATH, KEY, { now: NOW + FIFTEEN_MINUTES - 1 })?.familyId, + LOGIN.familyId ); assert.equal(verifyDownloadTicket(ticket(), PATH, KEY, { now: NOW + FIFTEEN_MINUTES }), null); }); @@ -41,9 +47,9 @@ describe("download ticket", () => { assert.equal(downloadTicketLifetimeSeconds(env), ONE_HOUR); const longer = ticket({ now: NOW, lifetimeSeconds: ONE_HOUR }); const gateway = { lifetimeSeconds: ONE_HOUR }; - assert.deepEqual( - verifyDownloadTicket(longer, PATH, KEY, { now: NOW + ONE_HOUR - 1, ...gateway }), - LOGIN + assert.equal( + verifyDownloadTicket(longer, PATH, KEY, { now: NOW + ONE_HOUR - 1, ...gateway })?.familyId, + LOGIN.familyId ); assert.equal( verifyDownloadTicket(longer, PATH, KEY, { now: NOW + ONE_HOUR, ...gateway }), diff --git a/src/lib/exomem-hosted/__tests__/cloud-grants-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-grants-postgres.integration.test.ts index be9be5c5..95a26c5c 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-grants-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-grants-postgres.integration.test.ts @@ -68,6 +68,7 @@ const LOCKED_TABLE_RIGHTS = { exomem_marketplace_reviewer_credentials: { select: true, insert: true, update: true, delete: false }, schema_releases: { ...NO_RIGHTS, select: true }, exomem_cloud_issuance_log: NO_RIGHTS, + exomem_cloud_download_tickets: { select: true, insert: true, update: false, delete: true }, } as const; let adminPool: Pool | undefined; diff --git a/src/lib/exomem-hosted/__tests__/cloud-media-download-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-media-download-postgres.integration.test.ts index 6dc94e36..7b8c238f 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-media-download-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-media-download-postgres.integration.test.ts @@ -1,5 +1,5 @@ import assert from "node:assert/strict"; -import { generateKeyPairSync, randomBytes, randomUUID } from "node:crypto"; +import { createHash, generateKeyPairSync, randomBytes, randomUUID } from "node:crypto"; import { after, before, describe, it } from "node:test"; import { Pool, type PoolClient } from "pg"; import { applyMigrations } from "../../../../scripts/migrate"; @@ -315,6 +315,98 @@ describe("Signed-in media download PostgreSQL boundary", { skip: !databaseUrl }, assert.equal(reached.length, served, "neither refused ticket reached a cell"); }); + it("stores one row for each ticket, by its path digest and expiry, before the redirect", async () => { + const a = await owner(); + const expiries = new Set(); + for (let attempt = 0; attempt < 3; attempt += 1) { + const claims = claimsOf((await link(a)).headers.get("location")!); + expiries.add(claims.exp); + const stored = await pool.query( + "SELECT path_sha256, extract(epoch FROM expires_at)::bigint AS exp FROM exomem_cloud_download_tickets WHERE family_id = $1 AND expires_at = to_timestamp($2)", + [claims.family_id, claims.exp] + ); + assert.equal(stored.rowCount, 1, "the row that the gateway looks up exists"); + assert.equal(stored.rows[0].path_sha256, createHash("sha256").update(PATH).digest("hex")); + } + const all = await pool.query( + "SELECT count(*)::int AS count FROM exomem_cloud_download_tickets t JOIN exomem_oauth_grants g ON g.id = t.grant_id WHERE g.tenant_id = $1", + [a.tenantId] + ); + assert.equal(all.rows[0].count, expiries.size, "one row for each distinct expiry"); + }); + + it("serves a correctly signed ticket only with its stored row, and the check rides inside the login lookup", async () => { + const a = await owner(); + const b = await owner(); + const { reached, follow } = gateway([a, b]); + const location = (await link(a)).headers.get("location")!; + const claims = claimsOf(location); + const otherLocation = (await link(b)).headers.get("location")!; + const ticketRow = (family: string) => + pool.query( + "SELECT id, grant_id, path_sha256, expires_at FROM exomem_cloud_download_tickets WHERE family_id = $1", + [family] + ); + const [row] = (await ticketRow(claims.family_id)).rows; + const other = (await ticketRow(claimsOf(otherLocation).family_id)).rows[0]; + + // Count the statements that the gateway runs for one download. + const statements: string[] = []; + const counted: ExomemSql = async (strings, ...values) => { + statements.push(strings.join("?")); + return taggedSql(pool)(strings, ...values); + }; + __setExomemSqlForTests(counted); + try { + assert.equal((await follow(location, { range: "bytes=0-1" })).status, 206); + } finally { + __setExomemSqlForTests(taggedSql(pool)); + } + const lookups = statements.filter((text) => text.includes("exomem_cloud_download_tickets")); + assert.equal(lookups.length, 1, "no statement is added: the ticket row is checked in place"); + assert.ok(lookups[0].includes("exomem_oauth_access_tokens"), "inside the login lookup"); + + // Each key of the stored row decides: a row that differs in one is no row for this ticket. + const reset = () => + pool.query( + "UPDATE exomem_cloud_download_tickets SET family_id = $2, grant_id = $3, path_sha256 = $4, expires_at = $5 WHERE id = $1", + [row.id, claims.family_id, row.grant_id, row.path_sha256, row.expires_at] + ); + const variants: Array<[string, string, unknown[]]> = [ + ["no row", "DELETE FROM exomem_cloud_download_tickets WHERE id = $1", []], + [ + "another path", + "UPDATE exomem_cloud_download_tickets SET path_sha256 = $2 WHERE id = $1", + ["0".repeat(64)], + ], + [ + "another expiry", + "UPDATE exomem_cloud_download_tickets SET expires_at = expires_at + interval '1 second' WHERE id = $1", + [], + ], + [ + "another family", + "UPDATE exomem_cloud_download_tickets SET family_id = $2, grant_id = $3 WHERE id = $1", + [claimsOf(otherLocation).family_id, other.grant_id], + ], + ]; + // The other owner's row may carry this ticket's path and expiry; the move below needs its place. + await pool.query("DELETE FROM exomem_cloud_download_tickets WHERE id = $1", [other.id]); + const served = reached.length; + for (const [name, text, extra] of variants) { + await pool.query(text, [row.id, ...extra]); + assert.equal((await follow(location)).status, 401, `${name}: refused`); + if (name === "no row") { + await pool.query( + "INSERT INTO exomem_cloud_download_tickets (id, family_id, grant_id, path_sha256, expires_at) VALUES ($1, $2, $3, $4, $5)", + [row.id, claims.family_id, row.grant_id, row.path_sha256, row.expires_at] + ); + } else await reset(); + } + assert.equal(reached.length, served, "no refused ticket reached a cell"); + assert.equal((await follow(location)).status, 200, "the restored row serves again"); + }); + it("answers 503 and mints nothing for a stopped cell", async () => { const stopped = await owner("stopped"); const response = await link(stopped); diff --git a/src/lib/exomem-hosted/cloud-download-ticket.ts b/src/lib/exomem-hosted/cloud-download-ticket.ts index 68d79362..6226caab 100644 --- a/src/lib/exomem-hosted/cloud-download-ticket.ts +++ b/src/lib/exomem-hosted/cloud-download-ticket.ts @@ -75,6 +75,16 @@ export type DownloadTicketClaims = { grantId: string; }; +/** + * What a verified ticket names beyond its login: the path digest and the expiry + * (in epoch seconds) that its stored row is keyed by. The app stores the row from + * this and the gateway looks it up by this. + */ +export type VerifiedDownloadTicket = DownloadTicketClaims & { + pathSha256: string; + expiresAt: number; +}; + function pathDigest(path: string): string { return createHash("sha256").update(path, "utf8").digest("hex"); } @@ -117,15 +127,15 @@ export function signDownloadTicket( /** * The claims of a ticket that is genuine, unexpired and minted for exactly * `path`; otherwise null, with no hint of which check failed. A ticket is - * only ever a pointer to a login: the caller must still resolve that login and - * compare its tenant and cell with these claims. + * only ever a pointer to a login: the caller must still resolve that login, + * compare its tenant and cell with these claims, and find the ticket's stored row. */ export function verifyDownloadTicket( ticket: string, path: string, key: Buffer, options: { now?: number; lifetimeSeconds?: number } = {} -): DownloadTicketClaims | null { +): VerifiedDownloadTicket | null { const now = options.now ?? nowSeconds(); const cap = options.lifetimeSeconds ?? downloadTicketLifetimeSeconds(); if (ticket.length === 0 || ticket.length > MAX_TICKET_CHARS) return null; @@ -158,5 +168,7 @@ export function verifyDownloadTicket( cellId: claims.cell_id, familyId: claims.family_id, grantId: claims.grant_id, + pathSha256: claims.path_sha256, + expiresAt: claims.exp, }; } diff --git a/src/lib/exomem-hosted/cloud-media-download.ts b/src/lib/exomem-hosted/cloud-media-download.ts index 4dc6a305..af1ee512 100644 --- a/src/lib/exomem-hosted/cloud-media-download.ts +++ b/src/lib/exomem-hosted/cloud-media-download.ts @@ -10,7 +10,12 @@ import { CLOUD_DOWNLOAD_PATH } from "../../exomem-gateway/cloud-origin"; import { controlPlaneKeyFromEnv } from "./security"; import { loadExomemCloudResource, type EnvironmentSource } from "./cloud-config"; -import { downloadTicketLifetimeSeconds, signDownloadTicket } from "./cloud-download-ticket"; +import { + downloadTicketLifetimeSeconds, + signDownloadTicket, + verifyDownloadTicket, +} from "./cloud-download-ticket"; +import { executeExomemSql as sql } from "./db"; import { openHomeLoginForTicket, servingCell } from "./cloud-home-mcp"; import { ExomemHostedError, exomemErrors } from "./errors"; import { PRIVATE_NO_STORE_HEADERS } from "./http"; @@ -108,6 +113,7 @@ export async function handleCloudMediaDownloadRequest( : unavailableCell(login.refused); } + const key = controlPlaneKeyFromEnv(); const ticket = signDownloadTicket( { tenantId: session.tenantId, @@ -116,9 +122,22 @@ export async function handleCloudMediaDownloadRequest( grantId: login.grantId, path, }, - controlPlaneKeyFromEnv(), + key, { lifetimeSeconds } ); + // The gateway serves a ticket only with its stored row, so the row exists before the + // redirect. Its key is read back from the signed ticket, so it is what the gateway looks up. + const signed = verifyDownloadTicket(ticket, path, key, { lifetimeSeconds }); + if (!signed) throw exomemErrors.invalidRequest(); + await sql` + /* exomem:store-download-ticket */ + INSERT INTO exomem_cloud_download_tickets (family_id, grant_id, path_sha256, expires_at) + VALUES ( + ${signed.familyId}::uuid, ${signed.grantId}::uuid, ${signed.pathSha256}, + to_timestamp(${signed.expiresAt}::double precision) + ) + ON CONFLICT (family_id, path_sha256, expires_at) DO NOTHING + `; const location = new URL(CLOUD_DOWNLOAD_PATH, mcpUrl); location.search = new URLSearchParams({ path, ticket }).toString(); return new Response(null, { diff --git a/src/lib/exomem-hosted/cloud-oauth.ts b/src/lib/exomem-hosted/cloud-oauth.ts index a7288697..3e8c4dcf 100644 --- a/src/lib/exomem-hosted/cloud-oauth.ts +++ b/src/lib/exomem-hosted/cloud-oauth.ts @@ -120,7 +120,15 @@ export type ActiveCloudOAuthLogin = { export type ActiveCloudOAuthAccessToken = ActiveCloudOAuthLogin & { scopes: string[] }; -type CloudOAuthSelector = { accessDigest: Buffer } | { familyId: string; grantId: string }; +/** + * A download ticket's stored row, which the login lookup requires when the caller + * holds a ticket (D8). The key is the ticket's own path digest and expiry. + */ +export type CloudDownloadTicketRow = { pathSha256: string; expiresAt: number }; + +type CloudOAuthSelector = + | { accessDigest: Buffer } + | { familyId: string; grantId: string; ticket?: CloudDownloadTicketRow }; /** * Looks up a Cloud-resource access token for the gateway (D3 step 4). Joins @@ -160,7 +168,7 @@ export async function findCloudOAuthAccessToken( * token lookup above except the token row's own. */ export async function findCloudOAuthLogin( - login: { familyId: string; grantId: string }, + login: { familyId: string; grantId: string; ticket?: CloudDownloadTicketRow }, acceptedResources: readonly string[] ): Promise { const row = await findCloudOAuthAuthority(login, acceptedResources); @@ -198,6 +206,8 @@ async function findCloudOAuthAuthority( const accessDigest = "accessDigest" in selector ? selector.accessDigest : null; const familyId = "familyId" in selector ? selector.familyId : null; const grantId = "grantId" in selector ? selector.grantId : null; + const ticketPathSha256 = "ticket" in selector ? (selector.ticket?.pathSha256 ?? null) : null; + const ticketExpiresAt = "ticket" in selector ? (selector.ticket?.expiresAt ?? null) : null; const { rows } = await executeExomemSql` /* exomem-cloud:find-oauth-access-token */ WITH token AS ( @@ -268,6 +278,16 @@ async function findCloudOAuthAuthority( -- is the one definition of "tenant live, owner unblocked" that this -- lookup and the service credential lookup share. AND exomem_cloud_tenant_access_allowed(oauth_grant.tenant_id, oauth_grant.user_id) + -- A download ticket is served only with its stored row (D8). The row is + -- found by the family, path digest and expiry that the ticket carries, so + -- this adds one index probe and no round trip. No other caller passes a ticket. + AND (${ticketPathSha256}::text IS NULL OR EXISTS ( + SELECT 1 FROM exomem_cloud_download_tickets AS stored_ticket + WHERE stored_ticket.family_id = token.family_id + AND stored_ticket.path_sha256 = ${ticketPathSha256}::text + AND stored_ticket.expires_at = to_timestamp(${ticketExpiresAt}::double precision) + AND stored_ticket.expires_at > now() + )) LIMIT 1 `; return (rows[0] as CloudOAuthAuthorityRow | undefined) ?? null; diff --git a/src/lib/exomem-hosted/issuance-maintenance.ts b/src/lib/exomem-hosted/issuance-maintenance.ts index 0183d4f9..2c06a158 100644 --- a/src/lib/exomem-hosted/issuance-maintenance.ts +++ b/src/lib/exomem-hosted/issuance-maintenance.ts @@ -1,15 +1,21 @@ import { executeExomemSql as sql } from "./db"; +// One run deletes at most this many expired ticket rows. A ticket row lives a day at most, +// so a minute-by-minute run clears any backlog far faster than rows arrive. +const TICKET_BATCH = 1000; + type IssuancePruneResult = { /** Records the log's prune function deleted, or null when the call failed. */ records: number | null; + /** Expired download ticket rows deleted, or null when the delete failed. */ + tickets: number | null; }; /** - * Retention for the issuance log. The log's own prune function holds the 90-day - * rule and its batch size, and deletes as the schema owner, because the web - * app's role holds nothing on the log. A failed call is reported as null, never - * as zero. + * Retention for the issuance log and the download ticket rows. The log's own + * prune function holds the 90-day rule and its batch size, and deletes as the + * schema owner, because the web app's role holds nothing on the log. Each part + * is isolated: a failed part is reported as null, never as zero. */ export async function pruneIssuanceState(): Promise { let records: number | null = null; @@ -19,5 +25,18 @@ export async function pruneIssuanceState(): Promise { } catch { console.error("exomem-issuance: log retention failed"); } - return { records }; + let tickets: number | null = null; + try { + const deleted = await sql` + /* exomem:prune-download-tickets */ + DELETE FROM exomem_cloud_download_tickets + WHERE id IN ( + SELECT id FROM exomem_cloud_download_tickets + WHERE expires_at <= now() ORDER BY expires_at LIMIT ${TICKET_BATCH} + )`; + tickets = deleted.rowCount ?? 0; + } catch { + console.error("exomem-issuance: download ticket retention failed"); + } + return { records, tickets }; } From 1da34cb77641480d78b05671afb93c4471b03486 Mon Sep 17 00:00:00 2001 From: Artexis10 Date: Wed, 2 Dec 2026 09:27:57 +0000 Subject: [PATCH 05/29] Prove the identity lock and the issuance log as the real database roles Two new suites attack the lock and the log as the web app's, the gateway's, the controller's and the audit role, in the narrow rights state that the grants script gives and in the wide state of an earlier script. Each attack asserts a refusal and an unchanged row. They also cover the guards alone, the older guards, the recording of every insert path, a renamed log table and the backfill of the migration. The grants suite gains the exact-rights checks, read from the catalog. Nine existing flow suites now run their production code through a pool that connects as the web app's role on the grants script's rights, so a flow that needs a withheld right fails in the test as it would in production. The code exchange, refresh, Home mint, service credential and download suites assert their issuance records. CI lists the two new suites. Tasks 2.1 to 5.8 are ticked. --- .github/workflows/test.yml | 2 + .../tasks.md | 34 +- .../account-postgres.integration.test.ts | 14 +- .../app-signout-postgres.integration.test.ts | 9 +- ...oud-admission-postgres.integration.test.ts | 9 +- ...letion-finish-postgres.integration.test.ts | 9 +- .../cloud-grants-postgres.integration.test.ts | 324 ++++++++++ .../cloud-home-postgres.integration.test.ts | 42 +- ...identity-lock-postgres.integration.test.ts | 584 ++++++++++++++++++ ...-issuance-log-postgres.integration.test.ts | 373 +++++++++++ ...edia-download-postgres.integration.test.ts | 5 + ...loud-reviewer-postgres.integration.test.ts | 9 +- ...e-credentials-postgres.integration.test.ts | 24 +- .../consent-apps-postgres.integration.test.ts | 9 +- src/lib/exomem-hosted/__tests__/flow-pool.ts | 40 ++ .../__tests__/identity-lock-fixture.ts | 218 +++++++ .../oauth-postgres.integration.test.ts | 55 +- 17 files changed, 1717 insertions(+), 43 deletions(-) create mode 100644 src/lib/exomem-hosted/__tests__/cloud-identity-lock-postgres.integration.test.ts create mode 100644 src/lib/exomem-hosted/__tests__/cloud-issuance-log-postgres.integration.test.ts create mode 100644 src/lib/exomem-hosted/__tests__/flow-pool.ts create mode 100644 src/lib/exomem-hosted/__tests__/identity-lock-fixture.ts diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index db0081cc..a561f858 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -66,6 +66,8 @@ jobs: node --import tsx --experimental-test-module-mocks --test src/lib/exomem-hosted/__tests__/cloud-cells-postgres.integration.test.ts src/lib/exomem-hosted/__tests__/cloud-grants-postgres.integration.test.ts + src/lib/exomem-hosted/__tests__/cloud-identity-lock-postgres.integration.test.ts + src/lib/exomem-hosted/__tests__/cloud-issuance-log-postgres.integration.test.ts src/lib/exomem-hosted/__tests__/cloud-access-log-postgres.integration.test.ts src/lib/exomem-hosted/__tests__/cloud-imports-postgres.integration.test.ts src/lib/exomem-hosted/__tests__/cloud-home-postgres.integration.test.ts diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md index 3683eafb..d77a86de 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md @@ -48,13 +48,13 @@ names each decision as D1 to D12. ## 2. Identity lock (D2, D3, D4) -- [ ] 2.1 In the first migration, add the guard function and the triggers of +- [x] 2.1 In the first migration, add the guard function and the triggers of D2. Fixed and one-way columns get an `AFTER UPDATE` row trigger with a `WHEN` clause. Deletes get an `AFTER DELETE` row trigger and a `BEFORE TRUNCATE` trigger. Build the guard function by D2's rules and revoke its execute right from `PUBLIC`. Change no rule of the three guards that exist today. Verify: tasks 5.1 and 5.2. -- [ ] 2.2 In `scripts/exomem-cloud-grants.sql`, add the lock's section after the +- [x] 2.2 In `scripts/exomem-cloud-grants.sql`, add the lock's section after the schema-wide grant. It revokes update and delete on the D2 tables from the web app's role. It then grants the D2 rights, each guarded on its table and column existing. It revokes the trigger right on every table in the schema @@ -69,7 +69,7 @@ names each decision as D1 to D12. identity row as the web app's role to the role that owns the schema. Change no assertion. Verify: every existing PostgreSQL suite passes with the guards in place. -- [ ] 2.5 In the first migration, pin `search_path` on each function of D2's +- [x] 2.5 In the first migration, pin `search_path` on each function of D2's "The create right": the schema owner's trigger and `SECURITY DEFINER` functions in the schema, and each SQL or PL/pgSQL function in the schema that a constraint, a column default or an index calls; only functions that @@ -83,7 +83,7 @@ names each decision as D1 to D12. ## 3. Issuance log (D5, D6, D12) -- [ ] 3.1 In the second migration, set a lock timeout of five seconds for the +- [x] 3.1 In the second migration, set a lock timeout of five seconds for the transaction, then take D5's locks in D5's order with one `LOCK TABLE` statement. Create `exomem_cloud_issuance_log` with its kind constraint, its three indexes and its guard. Add the recording function and revoke its @@ -92,13 +92,13 @@ names each decision as D1 to D12. right on the log in the same transaction. After the triggers exist, in the same transaction, write one backfilled record for each credential row that already exists. Verify: tasks 5.3 and 5.4. -- [ ] 3.2 Add the prune function with its batch of 10,000 records and its +- [x] 3.2 Add the prune function with its batch of 10,000 records and its 90-day constant. Revoke its execute right from `PUBLIC` and give it to the web app's role. Call it from the reconcile job beside the OAuth maintenance, and report the deleted count. Verify: a record inside its retention survives any number of calls, a record past it is deleted, and a service credential's record is never deleted. -- [ ] 3.3 In `scripts/exomem-cloud-grants.sql`, revoke every right on the log +- [x] 3.3 In `scripts/exomem-cloud-grants.sql`, revoke every right on the log from the web app's, the gateway's and the controller's roles on every run. Revoke execute on the guard, recording and prune functions from `PUBLIC`, and grant execute on the prune function to the web app's role. When the @@ -107,18 +107,18 @@ names each decision as D1 to D12. ## 4. Download ticket rows (D8) -- [ ] 4.1 In the second migration, create `exomem_cloud_download_tickets` with +- [x] 4.1 In the second migration, create `exomem_cloud_download_tickets` with its unique key, its expiry index, its update guard and its recording trigger. In the grants script, give the web app's role select, insert and delete, and the gateway's role select. Verify: as the web app's role, an update of a ticket row is refused, also after a grant of update on the table. -- [ ] 4.2 In the download handler, store the ticket's row before the redirect +- [x] 4.2 In the download handler, store the ticket's row before the redirect answer, with `ON CONFLICT DO NOTHING`. In the scheduled maintenance, delete a bounded batch of expired ticket rows. Verify: a download request leaves one row and one issuance record, a second ticket with the same token family, path and expiry adds neither, and a maintenance run removes an expired row. -- [ ] 4.3 In the gateway, require the matching unexpired row inside the +- [x] 4.3 In the gateway, require the matching unexpired row inside the statement that resolves the ticket's login. Verify: task 5.7. ## 5. Proof on a disposable PostgreSQL, as the real roles @@ -131,7 +131,7 @@ The wide state is select, insert, update, delete and truncate on every table in the schema, the log included. An earlier grants script gives the wide state without truncate. Neither state holds the trigger right. -- [ ] 5.1 Attacks as the web app's role, in both states. Re-point a grant's +- [x] 5.1 Attacks as the web app's role, in both states. Re-point a grant's tenant and user, by update and by a conflict action. Overwrite an access token's digest and a refresh token's digest. Extend an expiry. Change a reviewer reference. Clear a revocation time and a consumption time. Re-point @@ -141,7 +141,7 @@ without truncate. Neither state holds the trigger right. table that one of them references, with `CASCADE`. Create a trigger on a guarded table. Then create temporary tables that carry the names of the guarded tables, the log and the grant table, and run the list again. -- [ ] 5.2 The guards alone, with help that only the schema owner can give. +- [x] 5.2 The guards alone, with help that only the schema owner can give. The schema owner adds a `BEFORE` trigger that changes a grant's tenant: an update by the web app's role that names only `updated_at` is refused. The schema owner disables the delete guard on reviewer credentials. In the wide @@ -153,14 +153,14 @@ without truncate. Neither state holds the trigger right. token family that has tokens. A statement that keeps a revocation time that is already set succeeds. `EXPLAIN ANALYZE` of the Home mint's grant upsert lists no trigger of this change. -- [ ] 5.3 Every insert path writes its records, through the real functions. A +- [x] 5.3 Every insert path writes its records, through the real functions. A code exchange writes three. A refresh rotation writes two. A Home sign-in writes one for a new token family, and each Home mint writes one. A service credential and a download ticket write one each. A rolled-back transaction leaves none. A deleted and re-inserted token row has two. With temporary tables that carry the names of the log and the grant table, a token insert still records in the real log. -- [ ] 5.4 The log resists the web app's, the gateway's and the controller's +- [x] 5.4 The log resists the web app's, the gateway's and the controller's roles, in both states of group 5. Insert, update, delete and truncate on the log are refused. Dropping or disabling a recording trigger, creating a trigger on the log, replacing the recording function and setting @@ -170,7 +170,7 @@ without truncate. Neither state holds the trigger right. schema owner renames the log table, a token insert fails and leaves no row. A migration run over existing credential rows writes one backfilled record for each. -- [ ] 5.5 Every legitimate flow runs as the web app's role, on the rights of the +- [x] 5.5 Every legitimate flow runs as the web app's role, on the rights of the new grants script: authorization and consent, invite admission, code exchange, refresh rotation, token revocation by the client, by the owner and by the operator, account revocation, reviewer credential issue and reviewer @@ -181,7 +181,7 @@ without truncate. Neither state holds the trigger right. download. The PR changes no existing statement of these flows. The same run therefore covers the release that serves during a deploy. The reviewer checks that against the diff. -- [ ] 5.6 Rights are exact. After the grants script, the web app's rights on +- [x] 5.6 Rights are exact. After the grants script, the web app's rights on the D2 tables equal the D2 table. Every column of a column-locked table is either changeable or in a guard's list, never both and never neither. A second run changes nothing. The gateway's and the controller's rights on @@ -197,11 +197,11 @@ without truncate. Neither state holds the trigger right. of task 2.5, read from the catalog, pins a `search_path` that starts with `pg_catalog` and ends with `pg_temp`, and names only schemas that the schema owner, the bootstrap superuser or `pg_database_owner` owns. -- [ ] 5.7 The gateway refuses a correctly signed ticket that has no row, and +- [x] 5.7 The gateway refuses a correctly signed ticket that has no row, and serves one that has its row. It refuses one whose path, token family or expiry differs from the stored row. A download request runs as many database statements as it did before this change. -- [ ] 5.8 Cost at the load target (D7). Generate data for 10,000 tenants and a +- [x] 5.8 Cost at the load target (D7). Generate data for 10,000 tenants and a log of 10 million records. With `pgbench`, run the Home mint transaction's statements with and without this change's triggers: five runs each, same machine, same data. Report the median and the 95th percentile of both arms, diff --git a/src/lib/exomem-hosted/__tests__/account-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/account-postgres.integration.test.ts index 5f71f0fb..1ab5c270 100644 --- a/src/lib/exomem-hosted/__tests__/account-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/account-postgres.integration.test.ts @@ -25,6 +25,7 @@ import { loadExomemPaddleConfig } from "../paddle-config"; import { createSqlExomemPaddleEventStore } from "../paddle-event-store"; import { reconcileExomemPaddleSubscription } from "../paddle-reconciliation"; import { dispatchVerifiedExomemPaddleEvent } from "../paddle-webhook"; +import { productionPool } from "./flow-pool"; import { ensureExomemPostgresTestExtensions } from "./postgres-test-extensions"; // The lifecycle emails this suite's facts enqueue carry an encrypted payload. @@ -44,6 +45,8 @@ const WEBHOOK_ENVIRONMENT = { PADDLE_WEBHOOK_SECRET: "pdl_ntfset_example", }; +// The pool that production code runs on: the suite's own, or the web app role's. +let flowPool: Pool; let pool: Pool; let schema: string; let migrationsBefore: string; @@ -63,7 +66,7 @@ function taggedSql(client: Pool | PoolClient): ExomemSql { } async function interactiveTransaction(work: (tx: ExomemSql) => Promise): Promise { - const client = await pool.connect(); + const client = await flowPool!.connect(); try { await client.query("BEGIN"); const result = await work(taggedSql(client)); @@ -195,7 +198,7 @@ function subscriptionEvent( async function dispatch(event: Record) { return dispatchVerifiedExomemPaddleEvent(event, { env: WEBHOOK_ENVIRONMENT, - store: createSqlExomemPaddleEventStore(taggedSql(pool)), + store: createSqlExomemPaddleEventStore(taggedSql(flowPool!)), // The Cloud cell hook is not under test; these tenants have no cell. cloudHook: async () => undefined, }); @@ -213,7 +216,7 @@ async function reconcile(tenant: PaddleTenant, event: Record) { PADDLE_API_KEY: "pdl_sdbx_apikey_example", EXOMEM_PADDLE_PRODUCT_ID: "pro_exomem_example", }), - store: createSqlExomemPaddleEventStore(taggedSql(pool)), + store: createSqlExomemPaddleEventStore(taggedSql(flowPool!)), transport: async () => Response.json({ data }), } ); @@ -274,13 +277,16 @@ describe("Exomem account facts on PostgreSQL", { skip: !databaseUrl }, () => { legacyPastDueWithoutReceipt = await insertPaddleTenant("past_due", "users"); await applyMigrations({ databaseUrl: scoped.toString() }); - __setExomemSqlForTests(taggedSql(pool)); + // After the upgrade under test: the flow pool applies every migration to give its role rights. + flowPool = await productionPool(scoped.toString(), schema!); + __setExomemSqlForTests(taggedSql(flowPool)); __setExomemTransactionForTests(interactiveTransaction); }); after(async () => { __setExomemSqlForTests(null); __setExomemTransactionForTests(null); + await flowPool?.end(); if (pool) await pool.end(); if (migrationsBefore) rmSync(migrationsBefore, { recursive: true, force: true }); if (schema) { diff --git a/src/lib/exomem-hosted/__tests__/app-signout-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/app-signout-postgres.integration.test.ts index 211b8d32..14c77f24 100644 --- a/src/lib/exomem-hosted/__tests__/app-signout-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/app-signout-postgres.integration.test.ts @@ -9,6 +9,7 @@ import { drainExomemEmailOutbox } from "../email-outbox"; import { setOperationalEventSinkForTests } from "../observability"; import { pruneExpiredOAuthState } from "../oauth-store"; import { disconnectOwnerApp, listOwnerApps } from "../owner-apps"; +import { productionPool } from "./flow-pool"; import { ensureExomemPostgresTestExtensions } from "./postgres-test-extensions"; // The app sign-out notice and Home's reachability state against real @@ -18,6 +19,8 @@ import { ensureExomemPostgresTestExtensions } from "./postgres-test-extensions"; const CLOUD_RESOURCE = "https://cloud.example.test/mcp/v1"; const databaseUrl = process.env.EXOMEM_TEST_DATABASE_URL; +// The pool that production code runs on: the suite's own, or the web app role's. +let flowPool: Pool | undefined; let pool: Pool | undefined; let schema: string | undefined; @@ -41,7 +44,7 @@ function taggedSql(client: Pool | PoolClient): ExomemSql { } async function interactiveTransaction(callback: (tx: ExomemSql) => Promise): Promise { - const client = await pool!.connect(); + const client = await flowPool!.connect(); try { await client.query("BEGIN ISOLATION LEVEL READ COMMITTED"); const result = await callback(taggedSql(client)); @@ -212,7 +215,8 @@ describe("Exomem app sign-out notice PostgreSQL integration", { skip: !databaseU await applyMigrations({ databaseUrl: scoped.toString() }); await admin.end(); pool = new Pool({ connectionString: scoped.toString() }); - __setExomemSqlForTests(taggedSql(pool)); + flowPool = await productionPool(scoped.toString(), schema!); + __setExomemSqlForTests(taggedSql(flowPool)); __setExomemTransactionForTests(interactiveTransaction); }); @@ -220,6 +224,7 @@ describe("Exomem app sign-out notice PostgreSQL integration", { skip: !databaseU __setExomemSqlForTests(null); __setExomemTransactionForTests(null); setOperationalEventSinkForTests(null); + await flowPool?.end(); if (pool) await pool.end(); if (schema) { const admin = new Pool({ connectionString: databaseUrl }); diff --git a/src/lib/exomem-hosted/__tests__/cloud-admission-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-admission-postgres.integration.test.ts index 95a33445..6d9c3b9d 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-admission-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-admission-postgres.integration.test.ts @@ -21,6 +21,7 @@ import { tokenDigest } from "../security"; import { setMonthlyUpdateEmail } from "../whats-new-digest/setting"; import type { PaddleTransport } from "../paddle-billing"; import type { ExomemPaddleConfig } from "../paddle-config"; +import { productionPool } from "./flow-pool"; import { ensureExomemPostgresTestExtensions } from "./postgres-test-extensions"; // Task 3.3/3.4: Cloud admission (design D1) against real PostgreSQL. @@ -46,6 +47,8 @@ const FAKE_PADDLE_CONFIG: ExomemPaddleConfig = { }; const databaseUrl = process.env.EXOMEM_TEST_DATABASE_URL; +// The pool that production code runs on: the suite's own, or the web app role's. +let flowPool: Pool | undefined; let pool: Pool | undefined; let schema: string | undefined; @@ -61,7 +64,7 @@ function taggedSql(client: Pool | PoolClient): ExomemSql { } async function interactiveTransaction(callback: (tx: ExomemSql) => Promise): Promise { - const client = await pool!.connect(); + const client = await flowPool!.connect(); try { await client.query("BEGIN ISOLATION LEVEL READ COMMITTED"); const result = await callback(taggedSql(client)); @@ -226,13 +229,15 @@ describe("Exomem Cloud admission PostgreSQL integration", { skip: !databaseUrl } await applyMigrations({ databaseUrl: scoped.toString() }); await admin.end(); pool = new Pool({ connectionString: scoped.toString() }); - __setExomemSqlForTests(taggedSql(pool)); + flowPool = await productionPool(scoped.toString(), schema!); + __setExomemSqlForTests(taggedSql(flowPool)); __setExomemTransactionForTests(interactiveTransaction); }); after(async () => { __setExomemSqlForTests(null); __setExomemTransactionForTests(null); + await flowPool?.end(); if (pool) await pool.end(); if (schema) { const admin = new Pool({ connectionString: databaseUrl }); diff --git a/src/lib/exomem-hosted/__tests__/cloud-deletion-finish-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-deletion-finish-postgres.integration.test.ts index ec107292..797fe60f 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-deletion-finish-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-deletion-finish-postgres.integration.test.ts @@ -31,6 +31,7 @@ import { issueOAuthTokensFromCodeAtomic } from "../oauth-store"; import type { PaddleTransport } from "../paddle-billing"; import type { ExomemPaddleConfig } from "../paddle-config"; import { generateExternalToken, tokenDigest } from "../security"; +import { productionPool } from "./flow-pool"; import { ensureExomemPostgresTestExtensions } from "./postgres-test-extensions"; // The lifecycle emails this suite's facts enqueue carry an encrypted payload. @@ -44,6 +45,8 @@ process.env.EXOMEM_CONTROL_PLANE_KEY ??= randomBytes(32).toString("base64url"); // D4's receipt fails the test. const databaseUrl = process.env.EXOMEM_TEST_DATABASE_URL; +// The pool that production code runs on: the suite's own, or the web app role's. +let flowPool: Pool | undefined; let pool: Pool | undefined; let schema: string | undefined; @@ -84,7 +87,7 @@ function taggedSql(client: Pool | PoolClient): ExomemSql { } async function interactiveTransaction(callback: (tx: ExomemSql) => Promise): Promise { - const client = await pool!.connect(); + const client = await flowPool!.connect(); try { await client.query("BEGIN ISOLATION LEVEL READ COMMITTED"); const result = await callback(taggedSql(client)); @@ -714,13 +717,15 @@ describe("Exomem Cloud deletion finish PostgreSQL integration", { skip: !databas await applyMigrations({ databaseUrl: scoped.toString() }); await admin.end(); pool = new Pool({ connectionString: scoped.toString() }); - __setExomemSqlForTests(taggedSql(pool)); + flowPool = await productionPool(scoped.toString(), schema!); + __setExomemSqlForTests(taggedSql(flowPool)); __setExomemTransactionForTests(interactiveTransaction); }); after(async () => { __setExomemSqlForTests(null); __setExomemTransactionForTests(null); + await flowPool?.end(); if (pool) await pool.end(); if (schema) { const admin = new Pool({ connectionString: databaseUrl }); diff --git a/src/lib/exomem-hosted/__tests__/cloud-grants-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-grants-postgres.integration.test.ts index 95a26c5c..1335da48 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-grants-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-grants-postgres.integration.test.ts @@ -16,6 +16,7 @@ import { __setExomemSqlForTests, __setExomemTransactionForTests, type ExomemSql import { digestSecret, generateExternalToken } from "../security"; import { loadOpenServiceNotices } from "../service-notice-header"; import { assertCellAcceptsGrant } from "./cell-grant-rules"; +import { seedWorld } from "./identity-lock-fixture"; import { ensureExomemPostgresTestExtensions } from "./postgres-test-extensions"; // D7 (reopened task 3.2): scripts/exomem-cloud-grants.sql is the single @@ -221,6 +222,8 @@ describe("Exomem Cloud grants PostgreSQL integration", { skip: !databaseUrl }, ( } await applyMigrations({ databaseUrl: ownerUrl, migrationsDir: migrationRoot }); for (const role of CLOUD_ROLES) await ensureRole(role); + // The audit role reads the issuance log; the grants script gives it its reads only when it exists. + await ensureRole("substrate_audit"); await adminPool.query(`GRANT USAGE ON SCHEMA "${schema}" TO ${CLOUD_ROLES.join(", ")}`); // Grants must also work before any of migration 0079's columns exist. await applyMigrations({ databaseUrl: ownerUrl, migrationsDir: migrationRoot }); @@ -1785,4 +1788,325 @@ describe("Exomem Cloud grants PostgreSQL integration", { skip: !databaseUrl }, ( __setExomemTransactionForTests(null); } }); + + // Task 5.6: rights are exact. Each assertion names the attacker that a wrong right or a missing pin lets in. + + /** What substrate_app may update on each column-locked table (design D2), typed here so that a wider grant fails. */ + const APP_UPDATABLE_COLUMNS: Record = { + exomem_oauth_grants: [ + "scopes", "refresh_allowed", "authorization_transaction_id", "updated_at", "revoked_at", + "client_context_override", + ], + exomem_oauth_token_families: ["revoked_at", "revoked_reason"], + exomem_oauth_access_tokens: ["revoked_at"], + exomem_oauth_refresh_tokens: ["consumed_at"], + exomem_cloud_service_credentials: ["revoked_at", "revoked_by_principal_digest"], + }; + // A one-way column is changeable and also in its guard's list: the guard refuses a change once it holds a value. + const ONE_WAY_COLUMNS: Record = { + exomem_oauth_grants: ["revoked_at"], + exomem_oauth_token_families: ["revoked_at"], + exomem_oauth_access_tokens: ["revoked_at"], + exomem_oauth_refresh_tokens: ["consumed_at"], + exomem_cloud_service_credentials: ["revoked_at", "revoked_by_principal_digest"], + }; + // Clients and tenants stay updatable except for these identity columns. + const IDENTITY_COLUMNS: Record = { + exomem_oauth_clients: ["id", "client_id"], + exomem_tenants: ["owner_user_id"], + }; + + async function columnsOf(table: string): Promise { + const { rows } = await ownerPool!.query<{ attname: string }>( + `SELECT attname FROM pg_attribute + WHERE attrelid = to_regclass($1) AND attnum > 0 AND NOT attisdropped ORDER BY attname`, + [table] + ); + return rows.map((row) => row.attname); + } + + /** The columns that a table's update guards read, from the dependencies PostgreSQL records for a WHEN clause. */ + async function guardedColumns(table: string): Promise { + const { rows } = await ownerPool!.query<{ attname: string }>( + `SELECT DISTINCT attribute.attname + FROM pg_trigger AS trigger + JOIN pg_depend AS dependency + ON dependency.classid = 'pg_trigger'::regclass AND dependency.objid = trigger.oid + AND dependency.refclassid = 'pg_class'::regclass AND dependency.refobjid = trigger.tgrelid + AND dependency.refobjsubid > 0 + JOIN pg_attribute AS attribute + ON attribute.attrelid = dependency.refobjid AND attribute.attnum = dependency.refobjsubid + WHERE trigger.tgrelid = to_regclass($1) AND NOT trigger.tgisinternal + AND trigger.tgfoid = to_regproc('exomem_refuse_unless_schema_owner') + AND trigger.tgtype & 16 = 16 + ORDER BY attribute.attname`, + [table] + ); + return rows.map((row) => row.attname); + } + + async function updatableByApp(table: string, columns: readonly string[]): Promise { + const { rows } = await ownerPool!.query<{ attname: string }>( + `SELECT column_name AS attname FROM unnest($2::text[]) AS column_name + WHERE has_column_privilege('substrate_app', $1, column_name, 'UPDATE') ORDER BY column_name`, + [table, columns] + ); + return rows.map((row) => row.attname); + } + + it("lets the web app's role update only the changeable columns of each locked table, and puts every column in a guard's list or the role's, never neither", async () => { + const tables = [...Object.keys(APP_UPDATABLE_COLUMNS), ...Object.keys(IDENTITY_COLUMNS)]; + for (const table of tables) { + const columns = await columnsOf(table); + const changeable = await updatableByApp(table, columns); + const guarded = await guardedColumns(table); + const expectedChangeable = + table in APP_UPDATABLE_COLUMNS + ? [...APP_UPDATABLE_COLUMNS[table]!].sort() + : columns.filter((column) => !IDENTITY_COLUMNS[table]!.includes(column)); + assert.deepEqual(changeable, expectedChangeable, `${table}: columns that substrate_app may update`); + assert.deepEqual( + columns.filter((column) => !changeable.includes(column) && !guarded.includes(column)), + [], + `${table}: a column in neither list` + ); + assert.deepEqual( + changeable.filter((column) => guarded.includes(column)), + [...(ONE_WAY_COLUMNS[table] ?? [])].sort(), + `${table}: a column in both lists is a one-way column` + ); + } + }); + + it("gives the gateway only column reads and the controller nothing on the locked tables, the log and the ticket rows", async () => { + const tables = Object.keys(LOCKED_TABLE_RIGHTS); + const holds = async (role: string) => + ( + await ownerPool!.query<{ relname: string; scope: string; privilege_type: string }>( + `SELECT c.relname, 'table' AS scope, acl.privilege_type + FROM pg_class AS c, aclexplode(c.relacl) AS acl + WHERE c.relnamespace = current_schema()::regnamespace AND c.relname = ANY($1) AND acl.grantee = $2::regrole + UNION ALL + SELECT c.relname, a.attname, acl.privilege_type + FROM pg_attribute AS a JOIN pg_class AS c ON c.oid = a.attrelid, aclexplode(a.attacl) AS acl + WHERE c.relnamespace = current_schema()::regnamespace AND c.relname = ANY($1) + AND a.attnum > 0 AND acl.grantee = $2::regrole + ORDER BY 1, 2, 3`, + [tables, role] + ) + ).rows; + assert.deepEqual(await holds("exomem_cellctl"), [], "the controller holds nothing on these tables"); + const gateway = await holds("exomem_gateway"); + assert.deepEqual( + gateway.filter((held) => held.scope === "table" || held.privilege_type !== "SELECT"), + [], + "the gateway holds column reads only" + ); + assert.deepEqual( + gateway.filter((held) => held.relname === "exomem_cloud_download_tickets").map((held) => held.scope), + ["expires_at", "family_id", "path_sha256"], + "the gateway matches a ticket by these three columns" + ); + assert.deepEqual( + gateway.filter((held) => ["exomem_cloud_issuance_log", "schema_releases"].includes(held.relname)), + [], + "the gateway reads neither the log nor the schema releases" + ); + }); + + it("gives the audit role select on the log and the compared columns, and nothing else", async () => { + const audit = await ownerPool!.query<{ relname: string; scope: string; privilege_type: string }>( + `SELECT c.relname, 'table' AS scope, acl.privilege_type + FROM pg_class AS c, aclexplode(c.relacl) AS acl + WHERE c.relnamespace = current_schema()::regnamespace AND acl.grantee = 'substrate_audit'::regrole + UNION ALL + SELECT c.relname, a.attname, acl.privilege_type + FROM pg_attribute AS a JOIN pg_class AS c ON c.oid = a.attrelid, aclexplode(a.attacl) AS acl + WHERE c.relnamespace = current_schema()::regnamespace AND a.attnum > 0 AND acl.grantee = 'substrate_audit'::regrole + ORDER BY 1, 2, 3` + ); + const compared = [ + "exomem_cloud_download_tickets", "exomem_cloud_service_credentials", "exomem_oauth_access_tokens", + "exomem_oauth_refresh_tokens", "exomem_oauth_token_families", + ].flatMap((relname) => ["created_at", "id"].map((scope) => ({ relname, scope, privilege_type: "SELECT" }))); + const expected = [ + { relname: "exomem_cloud_issuance_log", scope: "table", privilege_type: "SELECT" }, + ...compared, + { relname: "exomem_tenants", scope: "id", privilege_type: "SELECT" }, + { relname: "exomem_tenants", scope: "owner_user_id", privilege_type: "SELECT" }, + ].sort((a, b) => (a.relname + a.scope).localeCompare(b.relname + b.scope)); + assert.deepEqual( + audit.rows.sort((a, b) => (a.relname + a.scope).localeCompare(b.relname + b.scope)), + expected + ); + }); + + it("leaves a column added after the grants script unwritable for the web app's role, also after a second run", async () => { + const tables = Object.keys(APP_UPDATABLE_COLUMNS); + for (const table of tables) await ownerPool!.query(`ALTER TABLE ${table} ADD COLUMN grants_probe integer`); + try { + await applyMigrations({ databaseUrl: roleUrl(databaseUrl!, "substrate_owner") }); + for (const table of tables) { + await assert.rejects( + appPool!.query(`UPDATE ${table} SET grants_probe = 1 WHERE false`), + (error: Error & { code?: string }) => error.code === "42501", + table + ); + } + } finally { + for (const table of tables) await ownerPool!.query(`ALTER TABLE ${table} DROP COLUMN grants_probe`); + } + }); + + it("leaves the trigger right with each table's owner, also after a hand-typed grant and a second run", async () => { + const holders = async () => + ( + await ownerPool!.query<{ relname: string; grantee: string }>( + `SELECT c.relname, CASE acl.grantee WHEN 0 THEN 'PUBLIC' ELSE pg_get_userbyid(acl.grantee)::text END AS grantee + FROM pg_class AS c, aclexplode(c.relacl) AS acl + WHERE c.relnamespace = current_schema()::regnamespace AND c.relkind IN ('r', 'p') + AND acl.privilege_type = 'TRIGGER' AND acl.grantee <> c.relowner + ORDER BY 1, 2` + ) + ).rows; + assert.deepEqual(await holders(), [], "no role but the owner holds the trigger right"); + await adminPool!.query( + `GRANT TRIGGER ON "${schema}".exomem_tenants, "${schema}".exomem_cloud_issuance_log TO substrate_app, exomem_gateway, PUBLIC` + ); + assert.equal((await holders()).length > 0, true, "the hand-typed grant took effect"); + await applyMigrations({ databaseUrl: roleUrl(databaseUrl!, "substrate_owner") }); + assert.deepEqual(await holders(), [], "a grants run takes the right back"); + }); + + it("runs with owner rights in exactly three functions, and lets only the web app's role call the prune", async () => { + const definers = await ownerPool!.query<{ proname: string }>( + `SELECT proname FROM pg_proc WHERE pronamespace = current_schema()::regnamespace AND prosecdef ORDER BY proname` + ); + assert.deepEqual( + definers.rows.map((row) => row.proname), + ["exomem_prune_issuance_log", "exomem_record_issuance", "exomem_record_memory_health_proof"] + ); + const executors = await ownerPool!.query<{ proname: string; grantee: string }>( + `SELECT proc.proname, CASE acl.grantee WHEN 0 THEN 'PUBLIC' ELSE pg_get_userbyid(acl.grantee)::text END AS grantee + FROM pg_proc AS proc, aclexplode(coalesce(proc.proacl, acldefault('f', proc.proowner))) AS acl + WHERE proc.pronamespace = current_schema()::regnamespace AND acl.privilege_type = 'EXECUTE' + AND proc.proname = ANY($1) AND acl.grantee <> proc.proowner + ORDER BY 1, 2`, + [[ + "exomem_prune_issuance_log", "exomem_record_issuance", "exomem_record_memory_health_proof", + "exomem_refuse_unless_schema_owner", + ]] + ); + assert.equal( + executors.rows.some((row) => row.grantee === "PUBLIC"), + false, + "PUBLIC executes none of them, nor the guard function" + ); + assert.deepEqual( + executors.rows.filter((row) => row.proname === "exomem_prune_issuance_log"), + [{ proname: "exomem_prune_issuance_log", grantee: "substrate_app" }] + ); + assert.deepEqual( + executors.rows.filter((row) => ["exomem_record_issuance", "exomem_refuse_unless_schema_owner"].includes(row.proname)), + [], + "no role but the owner executes the recording function or the guard function" + ); + }); + + it("pins a search path on each function that runs as the schema owner for another role, naming only schemas that a trusted role owns", async () => { + // The set of task 2.5, read from the catalog the way the migration reads it. + const pinned = await ownerPool!.query<{ proname: string; pin: string | null; untrusted: string[] }>( + `SELECT proc.proname, + (SELECT substr(setting, length('search_path=') + 1) FROM unnest(proc.proconfig) AS setting + WHERE setting LIKE 'search_path=%') AS pin, + ARRAY( + SELECT namespace.nspname::text FROM unnest( + string_to_array(replace((SELECT substr(setting, length('search_path=') + 1) + FROM unnest(proc.proconfig) AS setting WHERE setting LIKE 'search_path=%'), '"', ''), ', ') + ) AS schema_name + JOIN pg_namespace AS namespace ON namespace.nspname = schema_name + WHERE namespace.nspowner NOT IN (proc.proowner, 10, 'pg_database_owner'::regrole) + ) AS untrusted + FROM pg_proc AS proc + JOIN pg_language AS language ON language.oid = proc.prolang + WHERE proc.pronamespace = current_schema()::regnamespace + AND proc.proowner = 'substrate_owner'::regrole + AND language.lanname NOT IN ('c', 'internal') + AND NOT EXISTS ( + SELECT 1 FROM pg_depend AS membership + WHERE membership.classid = 'pg_proc'::regclass AND membership.objid = proc.oid AND membership.deptype = 'e' + ) + AND ( + proc.prorettype = 'trigger'::regtype OR proc.prosecdef + OR EXISTS ( + SELECT 1 FROM pg_depend AS caller + LEFT JOIN pg_class AS caller_index + ON caller.classid = 'pg_class'::regclass AND caller_index.oid = caller.objid + WHERE caller.refclassid = 'pg_proc'::regclass AND caller.refobjid = proc.oid + AND (caller.classid IN ('pg_constraint'::regclass, 'pg_attrdef'::regclass) + OR caller_index.relkind IN ('i', 'I')) + ) + ) + ORDER BY proc.proname` + ); + assert.ok(pinned.rows.length >= 4, "sanity: the set holds the guard, the recording function, the prune and more"); + for (const row of pinned.rows) { + const path = (row.pin ?? "").replaceAll('"', "").split(", "); + assert.equal(path[0], "pg_catalog", `${row.proname} starts its search path with pg_catalog`); + assert.equal(path.at(-1), "pg_temp", `${row.proname} ends its search path with pg_temp`); + assert.deepEqual(row.untrusted, [], `${row.proname} names a schema that an untrusted role owns`); + } + for (const name of ["exomem_refuse_unless_schema_owner", "exomem_record_issuance", "exomem_prune_issuance_log"]) { + assert.ok(pinned.rows.some((row) => row.proname === name), `${name} is in the set`); + } + }); + + it("keeps an operator that a role defines in a schema it owns from changing what a pinned function does", async () => { + // The grants-suite owner cannot create a schema for another role, so the superuser does. Production + // gives the web app's role no create right; this is the state that a stray create right would give. + const attackSchema = `operator_attack_${randomUUID().replaceAll("-", "").slice(0, 12)}`; + await adminPool!.query(`CREATE SCHEMA "${attackSchema}" AUTHORIZATION substrate_app`); + await ownerPool!.query( + `CREATE FUNCTION exomem_operator_probe(a varchar, b varchar) RETURNS boolean + LANGUAGE sql AS 'SELECT a = b'` + ); + const attacker = await appPool!.connect(); + try { + await attacker.query( + `CREATE FUNCTION "${attackSchema}".hijacked(varchar, varchar) RETURNS boolean + LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'operator hijacked'; END $$` + ); + await attacker.query( + `CREATE OPERATOR "${attackSchema}".= (LEFTARG = varchar, RIGHTARG = varchar, FUNCTION = "${attackSchema}".hijacked)` + ); + await attacker.query(`SET search_path = "${attackSchema}", "${schema}", public`); + // The control: a function with no pin takes the caller's path, so the attack works on this server. + await assert.rejects( + attacker.query(`SELECT "${schema}".exomem_operator_probe('a', 'a')`), + /operator hijacked/ + ); + await ownerPool!.query("ALTER FUNCTION exomem_operator_probe(varchar, varchar) SET search_path = pg_catalog, pg_temp"); + const pinnedProbe = await attacker.query(`SELECT "${schema}".exomem_operator_probe('a', 'a') AS equal`); + assert.equal(pinnedProbe.rows[0].equal, true, "the same function with a pin ignores the operator"); + + // The real recording function runs in that session, and its record is written. + const world = await seedWorld(ownerPool!); + const inserted = await attacker.query<{ id: string }>( + `INSERT INTO "${schema}".exomem_oauth_access_tokens + (access_digest, grant_id, family_id, client_id, resource, scopes, expires_at) + VALUES ($1, $2, $3, $4, 'https://gateway.example.test/mcp', ARRAY['mcp:read'], now() + interval '1 hour') + RETURNING id`, + [randomBytes(32), world.grantId, world.familyId, world.clientId] + ); + const recorded = await ownerPool!.query( + "SELECT count(*)::int AS count FROM exomem_cloud_issuance_log WHERE credential_id = $1", + [inserted.rows[0]!.id] + ); + assert.equal(recorded.rows[0].count, 1); + } finally { + attacker.release(); + await adminPool!.query(`DROP SCHEMA "${attackSchema}" CASCADE`); + await ownerPool!.query("DROP FUNCTION exomem_operator_probe(varchar, varchar)"); + } + }); }); diff --git a/src/lib/exomem-hosted/__tests__/cloud-home-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-home-postgres.integration.test.ts index 809dc4ad..99243148 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-home-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-home-postgres.integration.test.ts @@ -21,6 +21,7 @@ import { getOwnerCloudHomeStatus } from "../cloud-status"; import { __setExomemSqlForTests, __setExomemTransactionForTests, type ExomemSql } from "../db"; import { revokeOAuthAccountForOwnerTenantAtomic } from "../oauth-store"; import { digestSecret, generateExternalToken } from "../security"; +import { productionPool } from "./flow-pool"; import { ensureExomemPostgresTestExtensions } from "./postgres-test-extensions"; import { handleCloudStorage } from "../cloud-storage"; import { loadExomemPaddleConfig } from "../paddle-config"; @@ -47,6 +48,8 @@ const LEVELS = { coding: { level: "balanced", source: "default" }, conversation: { level: "balanced", source: "default" }, }; +// The pool that production code runs on: the suite's own, or the web app role's. +let flowPool: Pool; let pool: Pool; let schema: string; @@ -458,9 +461,10 @@ describe("Cloud Home channel and exports PostgreSQL boundary", { skip: !database scoped.searchParams.set("options", `-c search_path=${schema},public`); await applyMigrations({ databaseUrl: scoped.toString() }); pool = new Pool({ connectionString: scoped.toString() }); - __setExomemSqlForTests(taggedSql(pool)); + flowPool = await productionPool(scoped.toString(), schema!); + __setExomemSqlForTests(taggedSql(flowPool)); __setExomemTransactionForTests(async (work) => { - const client = await pool.connect(); + const client = await flowPool!.connect(); try { await client.query("BEGIN"); const result = await work(taggedSql(client)); @@ -478,6 +482,7 @@ describe("Cloud Home channel and exports PostgreSQL boundary", { skip: !database after(async () => { __setExomemSqlForTests(null); __setExomemTransactionForTests(null); + await flowPool?.end(); await pool?.end(); if (schema) { const admin = new Pool({ connectionString: databaseUrl }); @@ -542,7 +547,7 @@ describe("Cloud Home channel and exports PostgreSQL boundary", { skip: !database }, { env: f.env, - store: createSqlExomemPaddleEventStore(taggedSql(pool)), + store: createSqlExomemPaddleEventStore(taggedSql(flowPool!)), cloudHook: async () => {}, } ); @@ -706,6 +711,29 @@ describe("Cloud Home channel and exports PostgreSQL boundary", { skip: !database assert.equal(rows[0].admission_mode, "first_party"); }); + it("records the Home family once and the access token of each mint", async () => { + const alice = await owner(); + const cell = fakeCell(() => ({ revision: "r1", levels: LEVELS })); + const recorded = async () => + ( + await pool.query( + `SELECT credential_kind, count(*)::int AS count FROM exomem_cloud_issuance_log + WHERE tenant_id = $1 AND user_id = $2 GROUP BY credential_kind ORDER BY credential_kind`, + [alice.tenantId, alice.userId] + ) + ).rows; + assert.equal((await getLevels(alice, cell.fetchCell)).status, 200); + assert.deepEqual(await recorded(), [ + { credential_kind: "access_token", count: 1 }, + { credential_kind: "token_family", count: 1 }, + ]); + assert.equal((await getLevels(alice, cell.fetchCell)).status, 200); + assert.deepEqual(await recorded(), [ + { credential_kind: "access_token", count: 2 }, + { credential_kind: "token_family", count: 1 }, + ]); + }); + it("lets the gateway refuse a Home token minted before an account block or a started deletion", async () => { const blocked = await owner(); const deleting = await owner(); @@ -873,7 +901,7 @@ describe("Cloud Home channel and exports PostgreSQL boundary", { skip: !database // The session lookup refuses a blocked account, so the block lands in // the window after the session and cell checks, before the mint. __setExomemSqlForTests(async (strings, ...values) => { - const result = await taggedSql(pool)(strings, ...values); + const result = await taggedSql(flowPool!)(strings, ...values); if (strings.join("").includes("exomem-cloud:home-serving-cell")) { await revokeOAuthAccountForOwnerTenantAtomic({ ownerUserId: alice.userId, @@ -891,7 +919,7 @@ describe("Cloud Home channel and exports PostgreSQL boundary", { skip: !database reason: "ACCOUNT_ACCESS_CLOSED", }); } finally { - __setExomemSqlForTests(taggedSql(pool)); + __setExomemSqlForTests(taggedSql(flowPool!)); } const minted = await pool.query( `SELECT count(*)::integer AS tokens FROM exomem_oauth_access_tokens AS token @@ -907,7 +935,7 @@ describe("Cloud Home channel and exports PostgreSQL boundary", { skip: !database // The deletion commits after the session and cell checks, before the // mint, as one transaction: the tenant and its cell change together. __setExomemSqlForTests(async (strings, ...values) => { - const result = await taggedSql(pool)(strings, ...values); + const result = await taggedSql(flowPool!)(strings, ...values); if (strings.join("").includes("exomem-cloud:home-serving-cell")) { const deletion = await pool.connect(); try { @@ -936,7 +964,7 @@ describe("Cloud Home channel and exports PostgreSQL boundary", { skip: !database reason: "ACCOUNT_ACCESS_CLOSED", }); } finally { - __setExomemSqlForTests(taggedSql(pool)); + __setExomemSqlForTests(taggedSql(flowPool!)); } assert.equal(cell.calls.length, 0); }); diff --git a/src/lib/exomem-hosted/__tests__/cloud-identity-lock-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-identity-lock-postgres.integration.test.ts new file mode 100644 index 00000000..78bca1ec --- /dev/null +++ b/src/lib/exomem-hosted/__tests__/cloud-identity-lock-postgres.integration.test.ts @@ -0,0 +1,584 @@ +import assert from "node:assert/strict"; +import { randomBytes, randomUUID } from "node:crypto"; +import { after, before, describe, it } from "node:test"; +import type { Pool, PoolClient } from "pg"; +import { + createLockFixture, + seedClient, + seedWorld, + tableSnapshot, + type LockFixture, + type LockState, + type World, +} from "./identity-lock-fixture"; + +// The identity lock (design D2) against the web app's own database role. Each attack runs twice: +// in the narrow state, which is what the grants script gives, and in the wide state, where the +// role also holds select, insert, update, delete and truncate on every table. In the wide state +// only the guards stand, so each refusal there names the guard. + +const databaseUrl = process.env.EXOMEM_TEST_DATABASE_URL; +const LOCKED = "EXOMEM_ROW_LOCKED"; + +type Attack = { + name: string; + /** The table whose rows must be unchanged afterwards. */ + table: string; + text: string; + params?: unknown[]; + /** A guard refuses it in the wide state; otherwise a missing right does, in both states. */ + guard?: boolean; +}; + +type Victims = { + grantId: string; + clientId: string; + tenantId: string; + userId: string; + serviceCredentialId: string; + reviewerCredentialId: string; + ticketId: string; +}; + +/** Rows that nothing references, so a refusal can only come from the lock and not from a foreign key. */ +async function seedVictims(fx: LockFixture, world: World): Promise { + const id = async (text: string, values: unknown[] = []) => + (await fx.owner.query<{ id: string }>(text, values)).rows[0]!.id; + const grantId = await id( + `INSERT INTO exomem_oauth_grants (user_id, tenant_id, client_id, resource, scopes) + VALUES ($1, $2, $3, $4, ARRAY['mcp:read']) RETURNING id`, + [world.userId, world.tenantId, world.clientId, `https://victim.example.test/${randomUUID()}`] + ); + const clientId = await seedClient(fx.owner); + const lonelyUserId = await id("INSERT INTO exomem_users (email) VALUES ($1) RETURNING id", [ + `victim-${randomUUID()}@example.test`, + ]); + const reviewerOwnerId = await id("INSERT INTO exomem_users (email) VALUES ($1) RETURNING id", [ + `victim-${randomUUID()}@example.test`, + ]); + const ownerOfVictimTenant = await id( + "INSERT INTO exomem_users (email) VALUES ($1) RETURNING id", + [`victim-${randomUUID()}@example.test`] + ); + const tenantId = await id("INSERT INTO exomem_tenants (owner_user_id) VALUES ($1) RETURNING id", [ + ownerOfVictimTenant, + ]); + const serviceCredentialId = await id( + `INSERT INTO exomem_cloud_service_credentials (tenant_id, principal, secret_digest, created_by_principal_digest) + VALUES ($1, $2, $3, $4) RETURNING id`, + [world.tenantId, `service:t${randomBytes(6).toString("hex")}`, randomBytes(32), randomBytes(32)] + ); + const reviewerTenant = await id( + "INSERT INTO exomem_tenants (owner_user_id, marketplace_reviewer_purpose) VALUES ($1, true) RETURNING id", + [reviewerOwnerId] + ); + const reviewerCredentialId = await id( + `INSERT INTO exomem_marketplace_reviewer_credentials ( + provider, username_digest, password_hash, owner_user_id, tenant_id, fixture_version, + fixture_payload_digest, created_by_principal_digest, expires_at + ) VALUES ('openai', $1, '$argon2id$test', $2, $3, 'sample-v1', $4, $5, now() + interval '1 day') + RETURNING id`, + [randomBytes(32), reviewerOwnerId, reviewerTenant, "a".repeat(64), randomBytes(32)] + ); + const ticketId = await id( + `INSERT INTO exomem_cloud_download_tickets (family_id, grant_id, path_sha256, expires_at) + VALUES ($1, $2, $3, now() + interval '15 minutes') RETURNING id`, + [world.familyId, world.grantId, "0".repeat(64)] + ); + return { + grantId, + clientId, + tenantId, + userId: lonelyUserId, + serviceCredentialId, + reviewerCredentialId, + ticketId, + }; +} + +function attackList(fx: LockFixture, a: World, b: World, v: Victims): Attack[] { + const q = fx.q; + const grants = q("exomem_oauth_grants"); + const families = q("exomem_oauth_token_families"); + const access = q("exomem_oauth_access_tokens"); + const refresh = q("exomem_oauth_refresh_tokens"); + const credentials = q("exomem_cloud_service_credentials"); + const clients = q("exomem_oauth_clients"); + const tenants = q("exomem_tenants"); + const users = q("exomem_users"); + const reviewers = q("exomem_marketplace_reviewer_credentials"); + const tickets = q("exomem_cloud_download_tickets"); + const attacks: Attack[] = [ + { + name: "re-point a grant's tenant and user by update", + table: grants, + text: `UPDATE ${grants} SET tenant_id = $2, user_id = $3 WHERE id = $1`, + params: [a.grantId, b.tenantId, b.userId], + guard: true, + }, + { + name: "re-point a grant's tenant and user by a conflict action", + table: grants, + text: `INSERT INTO ${grants} (id, user_id, tenant_id, client_id, resource, scopes) + VALUES ($1, $2, $3, $4, 'https://other.example.test/mcp', ARRAY['mcp:read']) + ON CONFLICT (id) DO UPDATE SET tenant_id = EXCLUDED.tenant_id, user_id = EXCLUDED.user_id`, + params: [a.grantId, b.userId, b.tenantId, a.clientId], + guard: true, + }, + { + name: "overwrite an access token's digest", + table: access, + text: `UPDATE ${access} SET access_digest = $2 WHERE id = $1`, + params: [a.accessTokenId, randomBytes(32)], + guard: true, + }, + { + name: "overwrite a refresh token's digest", + table: refresh, + text: `UPDATE ${refresh} SET refresh_digest = $2 WHERE id = $1`, + params: [a.refreshTokenId, randomBytes(32)], + guard: true, + }, + { + name: "extend an access token's expiry", + table: access, + text: `UPDATE ${access} SET expires_at = expires_at + interval '30 days' WHERE id = $1`, + params: [a.accessTokenId], + guard: true, + }, + { + name: "extend a token family's expiry", + table: families, + text: `UPDATE ${families} SET expires_at = expires_at + interval '30 days' WHERE id = $1`, + params: [a.familyId], + guard: true, + }, + { + name: "extend a refresh token's expiry", + table: refresh, + text: `UPDATE ${refresh} SET expires_at = expires_at + interval '30 days' WHERE id = $1`, + params: [a.refreshTokenId], + guard: true, + }, + { + name: "change a grant's reviewer reference", + table: grants, + text: `UPDATE ${grants} SET reviewer_credential_id = $2 WHERE id = $1`, + params: [a.grantId, v.reviewerCredentialId], + guard: true, + }, + { + name: "clear a grant's revocation time", + table: grants, + text: `UPDATE ${grants} SET revoked_at = NULL WHERE id = $1`, + params: [a.spent.grantId], + guard: true, + }, + { + name: "clear a token family's revocation time", + table: families, + text: `UPDATE ${families} SET revoked_at = NULL WHERE id = $1`, + params: [a.spent.familyId], + guard: true, + }, + { + name: "clear an access token's revocation time", + table: access, + text: `UPDATE ${access} SET revoked_at = NULL WHERE id = $1`, + params: [a.spent.accessTokenId], + guard: true, + }, + { + name: "clear a refresh token's consumption time", + table: refresh, + text: `UPDATE ${refresh} SET consumed_at = NULL WHERE id = $1`, + params: [a.spent.refreshTokenId], + guard: true, + }, + { + name: "clear a service credential's revocation time", + table: credentials, + text: `UPDATE ${credentials} SET revoked_at = NULL WHERE id = $1`, + params: [a.spent.serviceCredentialId], + guard: true, + }, + { + name: "re-point a service credential's tenant", + table: credentials, + text: `UPDATE ${credentials} SET tenant_id = $2 WHERE id = $1`, + params: [a.serviceCredentialId, b.tenantId], + guard: true, + }, + { + name: "overwrite a service credential's digest", + table: credentials, + text: `UPDATE ${credentials} SET secret_digest = $2 WHERE id = $1`, + params: [a.serviceCredentialId, randomBytes(32)], + guard: true, + }, + { + name: "change a tenant's owner", + table: tenants, + text: `UPDATE ${tenants} SET owner_user_id = $2 WHERE id = $1`, + // The owner column is unique, so the new owner must be a user that owns no tenant. + params: [a.tenantId, v.userId], + guard: true, + }, + { + name: "change a client's identifier", + table: clients, + text: `UPDATE ${clients} SET client_id = 'https://attacker.example.test/client.json' WHERE id = $1`, + params: [a.clientId], + guard: true, + }, + { + name: "update a download ticket row", + table: tickets, + text: `UPDATE ${tickets} SET expires_at = expires_at + interval '30 days' WHERE id = $1`, + params: [v.ticketId], + guard: true, + }, + ]; + const deletions: Array<[string, string, string]> = [ + ["grant", grants, v.grantId], + ["client", clients, v.clientId], + ["tenant", tenants, v.tenantId], + ["user", users, v.userId], + ["service credential", credentials, v.serviceCredentialId], + ["reviewer credential", reviewers, v.reviewerCredentialId], + ]; + for (const [label, table, id] of deletions) { + attacks.push({ + name: `delete a ${label}`, + table, + text: `DELETE FROM ${table} WHERE id = $1`, + params: [id], + guard: true, + }); + attacks.push({ + // PostgreSQL refuses a plain truncate of a referenced table, for every role, before any trigger runs. + name: `truncate the ${label} table with CASCADE`, + table, + text: `TRUNCATE ${table} CASCADE`, + guard: true, + }); + } + // A cascade from a table that a guarded table references reaches the guarded table's truncate guard. + for (const referenced of [ + "exomem_oauth_authorization_transactions", + "exomem_agent_contract_candidates", + ]) { + attacks.push({ + name: `truncate ${referenced} with CASCADE`, + table: grants, + text: `TRUNCATE ${q(referenced)} CASCADE`, + guard: true, + }); + } + attacks.push({ + name: "create a trigger on a guarded table", + table: grants, + text: `CREATE TRIGGER app_probe AFTER INSERT ON ${grants} + FOR EACH ROW EXECUTE FUNCTION ${q("exomem_refuse_unless_schema_owner")}()`, + }); + return attacks; +} + +async function refusal( + pool: Pool | PoolClient, + attack: Attack +): Promise<{ code?: string; message: string }> { + try { + await pool.query(attack.text, attack.params); + } catch (error) { + return { code: (error as { code?: string }).code, message: (error as Error).message }; + } + return assert.fail(`${attack.name}: the statement succeeded`); +} + +const TABLES_UNDER_ATTACK = [ + "exomem_oauth_grants", + "exomem_oauth_token_families", + "exomem_oauth_access_tokens", + "exomem_oauth_refresh_tokens", + "exomem_cloud_service_credentials", + "exomem_oauth_clients", + "exomem_tenants", + "exomem_users", + "exomem_marketplace_reviewer_credentials", + "exomem_cloud_download_tickets", +]; + +const STATES: LockState[] = ["narrow", "wide"]; + +for (const state of STATES) { + describe( + `The identity lock against the web app's role, ${state} rights`, + { skip: !databaseUrl }, + () => { + let fx: LockFixture; + let a: World; + let b: World; + let victims: Victims; + + before(async () => { + fx = await createLockFixture(state); + a = await seedWorld(fx.owner); + b = await seedWorld(fx.owner); + victims = await seedVictims(fx, a); + }); + + after(async () => { + await fx?.close(); + }); + + async function everyTable(): Promise { + return Promise.all( + TABLES_UNDER_ATTACK.map((table) => tableSnapshot(fx.owner, fx.q(table))) + ); + } + + async function runAttacks(session: Pool | PoolClient): Promise { + const before = await everyTable(); + for (const attack of attackList(fx, a, b, victims)) { + const result = await refusal(session, attack); + assert.equal(result.code, "42501", `${attack.name}: ${result.message}`); + // With every right in hand, only a guard stops the statement, and it says so. + if (state === "wide" && attack.guard) + assert.match(result.message, new RegExp(LOCKED), `${attack.name}: ${result.message}`); + } + assert.deepEqual(await everyTable(), before, "no refused statement changed a row"); + } + + it("refuses every change of an identity field, every delete and every truncate", async () => { + await runAttacks(fx.app); + }); + + it("refuses the same list in a session whose temporary tables carry the guarded names", async () => { + const client = await fx.app.connect(); + try { + // A temporary table found first in the search path stands in for the real one. The log + // and the grant table are what the recording function reads and writes; pg_class is what the + // guard reads to learn the table's owner. + // The role cannot read the log, so the stand-in names its columns itself. + await client.query( + "CREATE TEMP TABLE exomem_cloud_issuance_log (id bigint, credential_kind text, tenant_id uuid, user_id uuid)" + ); + await client.query( + `CREATE TEMP TABLE exomem_oauth_grants (LIKE ${fx.q("exomem_oauth_grants")})` + ); + await client.query("CREATE TEMP TABLE pg_class (oid oid, relowner oid)"); + await client.query( + `INSERT INTO pg_temp.pg_class + SELECT c.oid, (SELECT oid FROM pg_catalog.pg_roles WHERE rolname = current_user) + FROM pg_catalog.pg_class AS c` + ); + await runAttacks(client); + } finally { + client.release(); + } + }); + + it("lets the schema owner make each of the changes", async () => { + const client = await fx.owner.connect(); + try { + for (const attack of attackList(fx, a, b, victims)) { + if (attack.name === "create a trigger on a guarded table") continue; + await client.query("BEGIN"); + try { + await client.query(attack.text, attack.params); + } catch (error) { + assert.fail(`${attack.name}: the owner was refused: ${(error as Error).message}`); + } finally { + await client.query("ROLLBACK"); + } + } + } finally { + client.release(); + } + }); + + it("keeps the three older guards in force for the schema owner, whose own changes the new guards allow", async () => { + // Each older guard is a BEFORE trigger that binds every role. Each statement below changes a lineage or + // purpose column on a row that is no candidate's, which the new guards let the owner do. + const refusals: Array<[string, string, unknown[], RegExp]> = [ + [ + "candidate lineage", + `UPDATE ${fx.q("exomem_oauth_grants")} SET candidate_id = gen_random_uuid() WHERE id = $1`, + [a.grantId], + /candidate OAuth lineage is immutable/, + ], + [ + "reviewer purpose", + `UPDATE ${fx.q("exomem_tenants")} SET marketplace_reviewer_purpose = true WHERE id = $1`, + [a.tenantId], + /marketplace reviewer purpose is immutable/, + ], + [ + "reviewer credential lineage", + `UPDATE ${fx.q("exomem_marketplace_reviewer_credentials")} SET assignment_generation = 1 WHERE id = $1`, + [victims.reviewerCredentialId], + /reviewer credential lineage is immutable/, + ], + ]; + for (const [guard, text, params, message] of refusals) { + await assert.rejects(fx.owner.query(text, params), message, guard); + } + }); + + it("refuses a change that a trigger of the owner's slips in, because the guard reads the stored row", async () => { + // A BEFORE trigger runs as the invoking role and can rewrite the row after the statement's + // column rights were checked. The update below names only updated_at. + await fx.owner.query( + `CREATE FUNCTION ${fx.q("test_retarget_grant")}() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN NEW.tenant_id := '${b.tenantId}'::uuid; RETURN NEW; END $$` + ); + await fx.owner.query( + `GRANT EXECUTE ON FUNCTION ${fx.q("test_retarget_grant")}() TO substrate_app` + ); + await fx.owner.query( + `CREATE TRIGGER aaa_retarget BEFORE UPDATE ON ${fx.q("exomem_oauth_grants")} + FOR EACH ROW EXECUTE FUNCTION ${fx.q("test_retarget_grant")}()` + ); + try { + const before = await tableSnapshot(fx.owner, fx.q("exomem_oauth_grants")); + await assert.rejects( + fx.app.query( + `UPDATE ${fx.q("exomem_oauth_grants")} SET updated_at = now() WHERE id = $1`, + [a.grantId] + ), + (error: Error) => error.message.includes(LOCKED) + ); + assert.equal(await tableSnapshot(fx.owner, fx.q("exomem_oauth_grants")), before); + } finally { + await fx.owner.query(`DROP TRIGGER aaa_retarget ON ${fx.q("exomem_oauth_grants")}`); + await fx.owner.query(`DROP FUNCTION ${fx.q("test_retarget_grant")}()`); + } + }); + + // In the narrow state the role holds no delete right on reviewer credentials, so no action runs. + it( + "keeps the grant's guard in force when the foreign-key action runs, not only the table's own delete guard", + { skip: state === "narrow" }, + async () => { + // A foreign-key action runs as the table owner, but the grant's guard is queued and fires as + // the role that ran the statement. The reviewer credential's own delete guard is off, so the + // grant's guard alone must refuse. + const credential = victims.reviewerCredentialId; + await fx.owner.query( + `UPDATE ${fx.q("exomem_oauth_grants")} SET reviewer_credential_id = $2 WHERE id = $1`, + [victims.grantId, credential] + ); + await fx.owner.query( + `ALTER TABLE ${fx.q("exomem_marketplace_reviewer_credentials")} + DISABLE TRIGGER exomem_marketplace_reviewer_credentials_delete_lock` + ); + try { + await assert.rejects( + fx.app.query( + `DELETE FROM ${fx.q("exomem_marketplace_reviewer_credentials")} WHERE id = $1`, + [credential] + ), + (error: Error) => + error.message.includes(LOCKED) && error.message.includes("exomem_oauth_grants") + ); + const kept = await fx.owner.query( + `SELECT (SELECT count(*) FROM ${fx.q("exomem_marketplace_reviewer_credentials")} WHERE id = $1)::int AS credentials, + (SELECT reviewer_credential_id FROM ${fx.q("exomem_oauth_grants")} WHERE id = $2) AS reference`, + [credential, victims.grantId] + ); + assert.deepEqual(kept.rows[0], { credentials: 1, reference: credential }); + } finally { + await fx.owner.query( + `ALTER TABLE ${fx.q("exomem_marketplace_reviewer_credentials")} + ENABLE TRIGGER exomem_marketplace_reviewer_credentials_delete_lock` + ); + await fx.owner.query( + `UPDATE ${fx.q("exomem_oauth_grants")} SET reviewer_credential_id = NULL WHERE id = $1`, + [victims.grantId] + ); + } + } + ); + + it("still lets the legitimate foreign-key actions run: a deleted transaction that a grant names, and a family with tokens", async () => { + const world = await seedWorld(fx.owner); + const transaction = await fx.owner.query<{ id: string }>( + `INSERT INTO exomem_oauth_authorization_transactions ( + transaction_digest, client_id, redirect_uri, resource, requested_scopes, state_digest, + pkce_challenge, expires_at, state_envelope, form_nonce_digest, continuation_binding + ) VALUES ($1, $2, 'https://client.example.test/callback', 'https://gateway.example.test/mcp', + ARRAY['mcp:read'], $3, 'challenge', now() + interval '10 minutes', '{}'::jsonb, $4, $5) + RETURNING id`, + [randomBytes(32), world.clientId, randomBytes(32), randomBytes(32), randomBytes(32)] + ); + await fx.owner.query( + `UPDATE exomem_oauth_grants SET authorization_transaction_id = $2 WHERE id = $1`, + [world.grantId, transaction.rows[0]!.id] + ); + await fx.app.query(`DELETE FROM exomem_oauth_authorization_transactions WHERE id = $1`, [ + transaction.rows[0]!.id, + ]); + const grant = await fx.owner.query( + "SELECT authorization_transaction_id FROM exomem_oauth_grants WHERE id = $1", + [world.grantId] + ); + assert.equal(grant.rows[0]!.authorization_transaction_id, null); + + await fx.app.query(`DELETE FROM exomem_oauth_token_families WHERE id = $1`, [ + world.familyId, + ]); + const tokens = await fx.owner.query( + `SELECT (SELECT count(*) FROM exomem_oauth_access_tokens WHERE family_id = $1)::int AS access, + (SELECT count(*) FROM exomem_oauth_refresh_tokens WHERE family_id = $1)::int AS refresh`, + [world.familyId] + ); + assert.deepEqual(tokens.rows[0], { access: 0, refresh: 0 }); + }); + + it("lets an update keep a revocation time that is already set, and change what the flows change", async () => { + await fx.app.query(`UPDATE exomem_oauth_grants SET revoked_at = revoked_at WHERE id = $1`, [ + a.spent.grantId, + ]); + await fx.app.query( + `UPDATE exomem_oauth_grants SET revoked_at = now() WHERE id = $1 AND revoked_at IS NULL`, + [b.grantId] + ); + const revoked = await fx.owner.query( + "SELECT revoked_at IS NOT NULL AS revoked FROM exomem_oauth_grants WHERE id = $1", + [b.grantId] + ); + assert.equal(revoked.rows[0]!.revoked, true); + }); + + it("runs the Home mint's grant upsert without firing a trigger of this change", async () => { + const grant = await fx.owner.query<{ resource: string }>( + "SELECT resource FROM exomem_oauth_grants WHERE id = $1", + [a.grantId] + ); + const client = await fx.app.connect(); + try { + await client.query("BEGIN"); + const plan = await client.query<{ "QUERY PLAN": string }>( + `EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF) + INSERT INTO exomem_oauth_grants (user_id, tenant_id, client_id, resource, scopes, refresh_allowed) + VALUES ($1, $2, $3, $4, ARRAY['mcp:read'], false) + ON CONFLICT (user_id, tenant_id, client_id, resource) WHERE revoked_at IS NULL + DO UPDATE SET updated_at = now()`, + [a.userId, a.tenantId, a.clientId, grant.rows[0]!.resource] + ); + const text = plan.rows.map((row) => row["QUERY PLAN"]).join("\n"); + assert.match(text, /Conflict Resolution: UPDATE/, "the upsert took its update branch"); + assert.doesNotMatch( + text, + /Trigger \S*(identity_lock|delete_lock|truncate_lock|issuance_record|update_lock)/, + "no trigger of this change ran for the upsert" + ); + } finally { + await client.query("ROLLBACK"); + client.release(); + } + }); + } + ); +} diff --git a/src/lib/exomem-hosted/__tests__/cloud-issuance-log-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-issuance-log-postgres.integration.test.ts new file mode 100644 index 00000000..fd35be28 --- /dev/null +++ b/src/lib/exomem-hosted/__tests__/cloud-issuance-log-postgres.integration.test.ts @@ -0,0 +1,373 @@ +import assert from "node:assert/strict"; +import { randomBytes } from "node:crypto"; +import { cp, mkdtemp, readdir, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { after, before, describe, it } from "node:test"; +import type { Pool } from "pg"; +import { applyMigrations } from "../../../../scripts/migrate"; +import { __setExomemSqlForTests, type ExomemSql } from "../db"; +import { pruneIssuanceState } from "../issuance-maintenance"; +import { + createLockFixture, + seedWorld, + tableSnapshot, + type LockFixture, + type LockState, + type World, +} from "./identity-lock-fixture"; + +// The issuance log (design D3) as the real roles. Each state is the same as in the lock suite: +// narrow is what the grants script gives, wide adds every right on every table. + +const databaseUrl = process.env.EXOMEM_TEST_DATABASE_URL; +const LOCKED = "EXOMEM_ROW_LOCKED"; +const STATES: LockState[] = ["narrow", "wide"]; + +function tagged(pool: Pool): ExomemSql { + return async (strings, ...values) => { + let text = strings[0]!; + for (let index = 0; index < values.length; index += 1) { + text += `$${index + 1}${strings[index + 1]}`; + } + const result = await pool.query(text, values); + return { rows: result.rows as Array>, rowCount: result.rowCount ?? 0 }; + }; +} + +for (const state of STATES) { + describe( + `The issuance log against the service roles, ${state} rights`, + { skip: !databaseUrl }, + () => { + let fx: LockFixture; + let world: World; + + before(async () => { + fx = await createLockFixture(state); + world = await seedWorld(fx.owner); + }); + + after(async () => { + await fx?.close(); + }); + + const log = () => fx.q("exomem_cloud_issuance_log"); + const accessInsert = (digest: Buffer) => ({ + text: `INSERT INTO ${fx.q("exomem_oauth_access_tokens")} + (access_digest, grant_id, family_id, client_id, resource, scopes, expires_at) + VALUES ($1, $2, $3, $4, 'https://gateway.example.test/mcp', ARRAY['mcp:read'], + now() + interval '1 hour') RETURNING id`, + params: [digest, world.grantId, world.familyId, world.clientId], + }); + const recordsFor = async (credentialId: string) => + ( + await fx.owner.query( + `SELECT credential_kind, tenant_id, user_id, grant_id, family_id, client_id, database_role, backfilled + FROM ${log()} WHERE credential_id = $1`, + [credentialId] + ) + ).rows; + + it("writes one record for a credential that the web app's role inserts, naming the role that connected", async () => { + const digest = randomBytes(32); + const insert = accessInsert(digest); + const { rows } = await fx.app.query(insert.text, insert.params); + assert.deepEqual(await recordsFor(rows[0].id), [ + { + credential_kind: "access_token", + tenant_id: world.tenantId, + user_id: world.userId, + grant_id: world.grantId, + family_id: world.familyId, + client_id: world.clientId, + database_role: "substrate_app", + backfilled: false, + }, + ]); + }); + + it("writes no record for a transaction that rolls back, and two for a row that is deleted and inserted again", async () => { + const countRecords = async () => + Number((await fx.owner.query(`SELECT count(*) FROM ${log()}`)).rows[0].count); + const recordsBefore = await countRecords(); + const client = await fx.app.connect(); + try { + await client.query("BEGIN"); + const insert = accessInsert(randomBytes(32)); + await client.query(insert.text, insert.params); + await client.query("ROLLBACK"); + } finally { + client.release(); + } + assert.equal(await countRecords(), recordsBefore); + + const digest = randomBytes(32); + const first = accessInsert(digest); + const one = await fx.app.query(first.text, first.params); + await fx.app.query(`DELETE FROM ${fx.q("exomem_oauth_access_tokens")} WHERE id = $1`, [ + one.rows[0].id, + ]); + const two = await fx.app.query(first.text, first.params); + assert.notEqual(one.rows[0].id, two.rows[0].id); + assert.equal( + await countRecords(), + recordsBefore + 2, + "each insert is a record; the delete removes none" + ); + }); + + it("still records in the real log when temporary tables carry the names of the log and the grant table", async () => { + const client = await fx.app.connect(); + try { + // The role cannot read the log, so the stand-in names its columns itself. + await client.query( + `CREATE TEMP TABLE exomem_cloud_issuance_log ( + credential_kind text, credential_id uuid, grant_id uuid, family_id uuid, client_id uuid, + tenant_id uuid, user_id uuid, expires_at timestamptz, database_role text, + id bigint, recorded_at timestamptz, backfilled boolean)` + ); + await client.query( + `CREATE TEMP TABLE exomem_oauth_grants (LIKE ${fx.q("exomem_oauth_grants")})` + ); + await client.query(`CREATE TEMP TABLE exomem_tenants (LIKE ${fx.q("exomem_tenants")})`); + const insert = accessInsert(randomBytes(32)); + const { rows } = await client.query(insert.text, insert.params); + const real = await recordsFor(rows[0].id); + assert.equal(real.length, 1, "the record is in the real log"); + assert.equal(real[0].user_id, world.userId, "its account comes from the real grant"); + const shadow = await client.query( + "SELECT count(*)::int AS count FROM pg_temp.exomem_cloud_issuance_log" + ); + assert.equal(shadow.rows[0].count, 0, "the temporary table holds nothing"); + } finally { + client.release(); + } + }); + + it("refuses an insert, update, delete or truncate on the log from the web app, the gateway and the controller", async () => { + const before = await tableSnapshot(fx.owner, log()); + for (const [role, pool] of [ + ["substrate_app", fx.app], + ["exomem_gateway", fx.gateway], + ["exomem_cellctl", fx.cellctl], + ] as const) { + const statements = [ + `INSERT INTO ${log()} (credential_kind, credential_id, tenant_id, user_id, database_role) + VALUES ('access_token', gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), 'forged')`, + `UPDATE ${log()} SET tenant_id = gen_random_uuid()`, + `DELETE FROM ${log()}`, + `TRUNCATE ${log()}`, + ]; + for (const statement of statements) { + await assert.rejects(pool.query(statement), (error: Error & { code?: string }) => { + assert.equal(error.code, "42501", `${role}: ${statement}: ${error.message}`); + if (state === "wide" && role === "substrate_app") + assert.match(error.message, new RegExp(LOCKED), `${role}: ${error.message}`); + return true; + }); + } + } + assert.equal(await tableSnapshot(fx.owner, log()), before); + }); + + it("refuses to drop or disable a recording trigger, to add a trigger on the log, to replace the function and to switch off triggers", async () => { + const before = await tableSnapshot(fx.owner, log()); + for (const pool of [fx.app, fx.gateway, fx.cellctl]) { + for (const statement of [ + `DROP TRIGGER exomem_oauth_access_tokens_issuance_record ON ${fx.q("exomem_oauth_access_tokens")}`, + `ALTER TABLE ${fx.q("exomem_oauth_access_tokens")} DISABLE TRIGGER exomem_oauth_access_tokens_issuance_record`, + `ALTER TABLE ${fx.q("exomem_oauth_access_tokens")} DISABLE TRIGGER ALL`, + `CREATE TRIGGER probe AFTER INSERT ON ${log()} FOR EACH ROW EXECUTE FUNCTION ${fx.q("exomem_refuse_unless_schema_owner")}()`, + `CREATE OR REPLACE FUNCTION ${fx.q("exomem_record_issuance")}() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RETURN NULL; END $$`, + "SET session_replication_role = replica", + ]) { + await assert.rejects(pool.query(statement), (error: Error & { code?: string }) => { + assert.equal(error.code, "42501", `${statement}: ${error.message}`); + return true; + }); + } + } + assert.equal(await tableSnapshot(fx.owner, log()), before); + }); + + it("refuses every service role, and the audit role, a trigger on its own table that runs the recording function", async () => { + const before = await tableSnapshot(fx.owner, log()); + for (const pool of [fx.app, fx.gateway, fx.cellctl, fx.audit]) { + const client = await pool.connect(); + try { + await client.query( + "CREATE TEMP TABLE forged (id uuid, grant_id uuid, family_id uuid, client_id uuid, expires_at timestamptz)" + ); + await assert.rejects( + client.query( + `CREATE TRIGGER forge AFTER INSERT ON forged FOR EACH ROW + EXECUTE FUNCTION ${fx.q("exomem_record_issuance")}('access_token')` + ), + (error: Error & { code?: string }) => error.code === "42501" + ); + } finally { + client.release(); + } + } + assert.equal(await tableSnapshot(fx.owner, log()), before, "the log gained no record"); + }); + + it("fails a credential insert, and leaves no row, when the log cannot take its record", async () => { + await fx.owner.query(`ALTER TABLE ${log()} RENAME TO exomem_cloud_issuance_log_moved`); + try { + const insert = accessInsert(randomBytes(32)); + const digest = insert.params[0] as Buffer; + await assert.rejects(fx.app.query(insert.text, insert.params)); + const kept = await fx.owner.query( + `SELECT count(*)::int AS count FROM ${fx.q("exomem_oauth_access_tokens")} WHERE access_digest = $1`, + [digest] + ); + assert.equal(kept.rows[0].count, 0); + } finally { + await fx.owner.query( + `ALTER TABLE ${fx.q("exomem_cloud_issuance_log_moved")} RENAME TO exomem_cloud_issuance_log` + ); + } + }); + + it("lets only the web app's role run the prune, and the prune deletes only records that expired 90 days ago", async () => { + for (const pool of [fx.gateway, fx.cellctl, fx.audit]) { + await assert.rejects( + pool.query(`SELECT ${fx.q("exomem_prune_issuance_log")}()`), + (error: Error & { code?: string }) => error.code === "42501" + ); + } + const stale = async (expiresAt: string | null) => + ( + await fx.owner.query<{ id: string }>( + `INSERT INTO ${log()} (credential_kind, credential_id, tenant_id, user_id, expires_at, database_role) + VALUES ('access_token', gen_random_uuid(), $1, $2, ${expiresAt ?? "NULL"}, 'substrate_owner') RETURNING id`, + [world.tenantId, world.userId] + ) + ).rows[0]!.id; + const old = await stale("now() - interval '91 days'"); + const recent = await stale("now() - interval '89 days'"); + const none = await stale(null); + const deleted = await fx.app.query( + `SELECT ${fx.q("exomem_prune_issuance_log")}() AS deleted` + ); + assert.equal(deleted.rows[0].deleted >= 1, true); + const left = await fx.owner.query<{ id: string }>( + `SELECT id FROM ${log()} WHERE id = ANY($1::bigint[]) ORDER BY id`, + [[old, recent, none]] + ); + assert.deepEqual( + left.rows.map((row) => row.id), + [recent, none].sort((x, y) => Number(x) - Number(y)), + "the record that expired 91 days ago is gone; a recent one and one without an expiry stay" + ); + }); + + it("lets the maintenance run, as the web app's role, remove an expired download ticket row", async () => { + const ticket = async (expires: string) => + ( + await fx.owner.query<{ id: string }>( + `INSERT INTO ${fx.q("exomem_cloud_download_tickets")} (family_id, grant_id, path_sha256, expires_at, created_at) + VALUES ($1, $2, $3, now() + ${expires}, now() - interval '2 hours') RETURNING id`, + [world.familyId, world.grantId, randomBytes(32).toString("hex")] + ) + ).rows[0]!.id; + const expired = await ticket("interval '-1 hour'"); + const live = await ticket("interval '10 minutes'"); + __setExomemSqlForTests(tagged(fx.app)); + try { + const result = await pruneIssuanceState(); + assert.equal(typeof result.records, "number"); + assert.ok((result.tickets ?? 0) >= 1); + } finally { + __setExomemSqlForTests(null); + } + const rows = await fx.owner.query<{ id: string }>( + `SELECT id FROM ${fx.q("exomem_cloud_download_tickets")} WHERE id = ANY($1::uuid[])`, + [[expired, live]] + ); + assert.deepEqual( + rows.rows.map((row) => row.id), + [live] + ); + }); + } + ); +} + +describe("The migration that adds the log", { skip: !databaseUrl }, () => { + let fx: LockFixture; + let migrationRoot: string; + const NO_GRANTS = "/nonexistent/exomem-cloud-grants.sql"; + + before(async () => { + fx = await createLockFixture("narrow", { migrate: false }); + migrationRoot = await mkdtemp(join(tmpdir(), "issuance-log-upgrade-")); + for (const name of await readdir("migrations")) { + if (name.endsWith(".sql") && name < "0101") + await cp(join("migrations", name), join(migrationRoot, name)); + } + }); + + after(async () => { + await rm(migrationRoot, { recursive: true, force: true }); + await fx?.close(); + }); + + it("writes one backfilled record for each credential row that existed, and gives the web app's role no right on the new tables", async () => { + // Earlier releases left default privileges that give the web app's role every right on a + // table a migration creates; the new tables must not inherit them. + await fx.admin.query( + `ALTER DEFAULT PRIVILEGES FOR ROLE substrate_owner IN SCHEMA "${fx.schema}" + GRANT ALL ON TABLES TO substrate_app` + ); + await applyMigrations({ + databaseUrl: fx.roleUrl("substrate_owner"), + migrationsDir: migrationRoot, + grantsFile: NO_GRANTS, + }); + const world = await seedWorld(fx.owner); + await applyMigrations({ databaseUrl: fx.roleUrl("substrate_owner"), grantsFile: NO_GRANTS }); + + const counts = await fx.owner.query<{ + credential_kind: string; + count: number; + backfilled: boolean; + }>( + `SELECT credential_kind, count(*)::int AS count, bool_and(backfilled) AS backfilled + FROM exomem_cloud_issuance_log WHERE tenant_id = $1 GROUP BY credential_kind ORDER BY credential_kind`, + [world.tenantId] + ); + assert.deepEqual(counts.rows, [ + { credential_kind: "access_token", count: 2, backfilled: true }, + { credential_kind: "refresh_token", count: 2, backfilled: true }, + { credential_kind: "service_credential", count: 2, backfilled: true }, + { credential_kind: "token_family", count: 2, backfilled: true }, + ]); + const role = await fx.owner.query( + "SELECT DISTINCT database_role FROM exomem_cloud_issuance_log WHERE tenant_id = $1", + [world.tenantId] + ); + assert.deepEqual( + role.rows, + [{ database_role: "substrate_owner" }], + "a backfilled record names the migrating role" + ); + + // has_table_privilege with a list answers true when the role holds any one of the rights. + const held = await fx.owner.query<{ log: boolean; tickets: boolean; sequence: boolean }>( + `SELECT has_table_privilege('substrate_app', 'exomem_cloud_issuance_log', + 'SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER') AS log, + has_table_privilege('substrate_app', 'exomem_cloud_download_tickets', + 'SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER') AS tickets, + has_sequence_privilege('substrate_app', pg_get_serial_sequence('exomem_cloud_issuance_log', 'id'), + 'USAGE, SELECT, UPDATE') AS sequence` + ); + assert.deepEqual( + held.rows[0], + { log: false, tickets: false, sequence: false }, + "no right at all until the grants script runs" + ); + }); +}); diff --git a/src/lib/exomem-hosted/__tests__/cloud-media-download-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-media-download-postgres.integration.test.ts index 7b8c238f..e2acbe3d 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-media-download-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-media-download-postgres.integration.test.ts @@ -333,6 +333,11 @@ describe("Signed-in media download PostgreSQL boundary", { skip: !databaseUrl }, [a.tenantId] ); assert.equal(all.rows[0].count, expiries.size, "one row for each distinct expiry"); + const recorded = await pool.query( + "SELECT count(*)::int AS count FROM exomem_cloud_issuance_log WHERE tenant_id = $1 AND credential_kind = 'download_ticket'", + [a.tenantId] + ); + assert.equal(recorded.rows[0].count, expiries.size, "one issuance record for each stored row"); }); it("serves a correctly signed ticket only with its stored row, and the check rides inside the login lookup", async () => { diff --git a/src/lib/exomem-hosted/__tests__/cloud-reviewer-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-reviewer-postgres.integration.test.ts index 7af1cf77..8335e4e0 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-reviewer-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-reviewer-postgres.integration.test.ts @@ -4,6 +4,7 @@ import { after, before, describe, it } from "node:test"; import { Pool, type PoolClient } from "pg"; import { applyMigrations } from "../../../../scripts/migrate"; import { __setExomemSqlForTests, __setExomemTransactionForTests, type ExomemSql } from "../db"; +import { productionPool } from "./flow-pool"; import { ensureExomemPostgresTestExtensions } from "./postgres-test-extensions"; import { randomCloudCellId } from "../cloud-admission"; import { @@ -30,6 +31,8 @@ import { const databaseUrl = process.env.EXOMEM_TEST_DATABASE_URL; const CLOUD_RESOURCE = "https://cloud.example.test/mcp/v1"; +// The pool that production code runs on: the suite's own, or the web app role's. +let flowPool: Pool; let pool: Pool; let schema: string; let statementBarrier: ((text: string) => Promise) | null = null; @@ -52,7 +55,7 @@ function taggedSql(client: Pool | PoolClient): ExomemSql { } async function transaction(callback: (tx: ExomemSql) => Promise): Promise { - const client = await pool.connect(); + const client = await flowPool!.connect(); try { await client.query("BEGIN ISOLATION LEVEL READ COMMITTED"); const result = await callback(taggedSql(client)); @@ -225,7 +228,8 @@ describe("Cloud reviewer PostgreSQL authority", { skip: !databaseUrl }, () => { await applyMigrations({ databaseUrl: scoped.toString() }); await admin.end(); pool = new Pool({ connectionString: scoped.toString() }); - __setExomemSqlForTests(taggedSql(pool)); + flowPool = await productionPool(scoped.toString(), schema!); + __setExomemSqlForTests(taggedSql(flowPool)); __setExomemTransactionForTests(transaction); }); after(async () => { @@ -236,6 +240,7 @@ describe("Cloud reviewer PostgreSQL authority", { skip: !databaseUrl }, () => { } __setExomemSqlForTests(null); __setExomemTransactionForTests(null); + await flowPool?.end(); if (pool) await pool.end(); if (schema) { const admin = new Pool({ connectionString: databaseUrl }); diff --git a/src/lib/exomem-hosted/__tests__/cloud-service-credentials-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-service-credentials-postgres.integration.test.ts index 65e139b2..c79ff692 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-service-credentials-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-service-credentials-postgres.integration.test.ts @@ -19,6 +19,7 @@ import { } from "../db"; import { digestSecret } from "../security"; import { SERVICE_CREDENTIAL_PREFIX } from "../service-credential-format"; +import { productionPool } from "./flow-pool"; import { ensureExomemPostgresTestExtensions } from "./postgres-test-extensions"; // add-cloud-service-credentials (D1-D5): the service credential store and the @@ -29,6 +30,8 @@ import { ensureExomemPostgresTestExtensions } from "./postgres-test-extensions"; const CLOUD_RESOURCE = "https://cloud.example.test/mcp/v1"; const OPERATOR_DIGEST = digestSecret("operator-test-principal"); const databaseUrl = process.env.EXOMEM_TEST_DATABASE_URL; +// The pool that production code runs on: the suite's own, or the web app role's. +let flowPool: Pool | undefined; let pool: Pool | undefined; let schema: string | undefined; @@ -44,7 +47,7 @@ function taggedSql(client: Pool | PoolClient): ExomemSql { } async function transaction(callback: (tx: ExomemSql) => Promise): Promise { - const client = await pool!.connect(); + const client = await flowPool!.connect(); try { await client.query("BEGIN ISOLATION LEVEL READ COMMITTED"); const result = await callback(taggedSql(client)); @@ -98,13 +101,15 @@ describe("Exomem Cloud service credentials PostgreSQL integration", { skip: !dat await applyMigrations({ databaseUrl: scoped.toString() }); await admin.end(); pool = new Pool({ connectionString: scoped.toString() }); - __setExomemSqlForTests(taggedSql(pool)); + flowPool = await productionPool(scoped.toString(), schema!); + __setExomemSqlForTests(taggedSql(flowPool)); __setExomemTransactionForTests(transaction); }); after(async () => { __setExomemSqlForTests(null); __setExomemTransactionForTests(null); + await flowPool?.end(); if (pool) await pool.end(); if (schema) { const admin = new Pool({ connectionString: databaseUrl }); @@ -149,6 +154,21 @@ describe("Exomem Cloud service credentials PostgreSQL integration", { skip: !dat assert.equal(access.firstParty, false); }); + it("records the issue of a service credential against its tenant's owner, without the secret", async () => { + const { tenantId, ownerUserId } = await newTenantWithCell(); + const issued = await issue(tenantId); + const { rows } = await pool!.query( + "SELECT to_jsonb(log) AS record FROM exomem_cloud_issuance_log AS log WHERE tenant_id = $1", + [tenantId] + ); + assert.equal(rows.length, 1); + assert.equal(rows[0].record.credential_kind, "service_credential"); + assert.equal(rows[0].record.credential_id, issued.credentialId); + assert.equal(rows[0].record.user_id, ownerUserId); + assert.equal(rows[0].record.expires_at, null, "a service credential has no expiry"); + assert.equal(JSON.stringify(rows[0].record).includes(issued.secret), false); + }); + it("refuses a malformed principal before any row exists", async () => { const { tenantId } = await newTenantWithCell(); for (const principal of ["creator-platform", "service:", "service:Upper", "service:a_b"]) { diff --git a/src/lib/exomem-hosted/__tests__/consent-apps-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/consent-apps-postgres.integration.test.ts index bc6054b2..7c3dbe3c 100644 --- a/src/lib/exomem-hosted/__tests__/consent-apps-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/consent-apps-postgres.integration.test.ts @@ -23,6 +23,7 @@ import { } from "../oauth-store"; import { disconnectOwnerApp, listOwnerApps, setOwnerAppContext } from "../owner-apps"; import { digestSecret, generateExternalToken, tokenDigest } from "../security"; +import { productionPool } from "./flow-pool"; import { ensureExomemPostgresTestExtensions } from "./postgres-test-extensions"; // Consent outcomes and connected apps (launch-exomem-cloud-web, B and C) @@ -32,6 +33,8 @@ import { ensureExomemPostgresTestExtensions } from "./postgres-test-extensions"; const CLOUD_RESOURCE = "https://cloud.example.test/mcp/v1"; const ORIGIN = "https://exomem.example.test"; const databaseUrl = process.env.EXOMEM_TEST_DATABASE_URL; +// The pool that production code runs on: the suite's own, or the web app role's. +let flowPool: Pool | undefined; let pool: Pool | undefined; let schema: string | undefined; @@ -54,7 +57,7 @@ function taggedSql(client: Pool | PoolClient): ExomemSql { } async function interactiveTransaction(callback: (tx: ExomemSql) => Promise): Promise { - const client = await pool!.connect(); + const client = await flowPool!.connect(); try { await client.query("BEGIN ISOLATION LEVEL READ COMMITTED"); const result = await callback(taggedSql(client)); @@ -310,7 +313,8 @@ describe( await applyMigrations({ databaseUrl: scoped.toString() }); await admin.end(); pool = new Pool({ connectionString: scoped.toString() }); - __setExomemSqlForTests(taggedSql(pool)); + flowPool = await productionPool(scoped.toString(), schema!); + __setExomemSqlForTests(taggedSql(flowPool)); __setExomemTransactionForTests(interactiveTransaction); }); @@ -318,6 +322,7 @@ describe( __setExomemSqlForTests(null); __setExomemTransactionForTests(null); setOperationalEventSinkForTests(null); + await flowPool?.end(); if (pool) await pool.end(); if (schema) { const admin = new Pool({ connectionString: databaseUrl }); diff --git a/src/lib/exomem-hosted/__tests__/flow-pool.ts b/src/lib/exomem-hosted/__tests__/flow-pool.ts new file mode 100644 index 00000000..09104ee5 --- /dev/null +++ b/src/lib/exomem-hosted/__tests__/flow-pool.ts @@ -0,0 +1,40 @@ +import { Pool } from "pg"; +import { applyMigrations } from "../../../../scripts/migrate"; + +// Production runs the web app's flows as its own database role, on the rights of +// scripts/exomem-cloud-grants.sql. A suite's own pool is the schema owner, which holds every right, +// so a flow that needs a right the grants script withholds passes there and fails in production. +// A suite hands its production code this pool instead, and keeps seeding and asserting on its own pool. +const FLOW_ROLE = "substrate_app"; +const FLOW_PASSWORD = "exomem-flow-role-test"; + +/** The web app role's login on the suite's schema, with the grants script applied for it. */ +export async function productionPool(scopedUrl: string, schema: string): Promise { + const admin = new Pool({ connectionString: process.env.EXOMEM_TEST_DATABASE_URL }); + try { + await admin.query( + `DO $$ + BEGIN + IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '${FLOW_ROLE}') THEN + CREATE ROLE ${FLOW_ROLE} LOGIN PASSWORD '${FLOW_PASSWORD}'; + ELSE + ALTER ROLE ${FLOW_ROLE} WITH LOGIN PASSWORD '${FLOW_PASSWORD}'; + END IF; + END + $$;` + ); + await admin.query(`GRANT USAGE ON SCHEMA "${schema}" TO ${FLOW_ROLE}`); + } finally { + await admin.end(); + } + // The role exists now, so the grants script gives it its rights. + await applyMigrations({ databaseUrl: scopedUrl }); + const url = new URL(scopedUrl); + url.username = FLOW_ROLE; + url.password = FLOW_PASSWORD; + const pool = new Pool({ connectionString: url.toString() }); + // A pool that quietly ran as another role would turn this proof into a pass on every right. + const { rows } = await pool.query<{ role: string }>("SELECT current_user AS role"); + if (rows[0]?.role !== FLOW_ROLE) throw new Error(`flow pool runs as ${rows[0]?.role}`); + return pool; +} diff --git a/src/lib/exomem-hosted/__tests__/identity-lock-fixture.ts b/src/lib/exomem-hosted/__tests__/identity-lock-fixture.ts new file mode 100644 index 00000000..31921e9c --- /dev/null +++ b/src/lib/exomem-hosted/__tests__/identity-lock-fixture.ts @@ -0,0 +1,218 @@ +import { randomBytes, randomUUID } from "node:crypto"; +import { Pool } from "pg"; +import { applyMigrations } from "../../../../scripts/migrate"; +import { ensureExomemPostgresTestExtensions } from "./postgres-test-extensions"; + +// The identity lock and the issuance log are proven as the real roles, not as a superuser that +// holds every right. A schema owned by substrate_owner takes the migrations and the grants script, +// as production does; substrate_app, exomem_gateway, exomem_cellctl and substrate_audit are plain +// login roles with no other privilege. + +export const FIXTURE_ROLES = [ + "substrate_app", + "exomem_cellctl", + "exomem_gateway", + "substrate_audit", +] as const; +export type LockState = "narrow" | "wide"; + +const PASSWORD = "exomem-identity-lock-test"; + +export type LockFixture = { + schema: string; + /** The schema owner, which runs the migrations and holds every right. */ + owner: Pool; + app: Pool; + gateway: Pool; + cellctl: Pool; + audit: Pool; + admin: Pool; + /** `"".`, so a statement reaches the real table whatever a session's temporary tables hold. */ + q(name: string): string; + roleUrl(role: string): string; + close(): Promise; +}; + +async function ensureRole(admin: Pool, name: string): Promise { + await admin.query( + `DO $$ + BEGIN + IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '${name}') THEN + CREATE ROLE ${name} LOGIN PASSWORD '${PASSWORD}'; + ELSE + ALTER ROLE ${name} WITH LOGIN PASSWORD '${PASSWORD}'; + END IF; + END + $$;` + ); +} + +/** + * A migrated schema in one of two rights states. The narrow state is what the grants script gives. + * The wide state adds select, insert, update, delete and truncate on every table, the log included, + * for the three service roles: the rights an earlier grants script gave, and more. + */ +export async function createLockFixture( + state: LockState, + options: { migrate?: boolean } = {} +): Promise { + const databaseUrl = process.env.EXOMEM_TEST_DATABASE_URL!; + const schema = `lock_it_${state}_${randomUUID().replaceAll("-", "")}`; + await ensureExomemPostgresTestExtensions(databaseUrl); + const admin = new Pool({ connectionString: databaseUrl }); + for (const role of ["substrate_owner", ...FIXTURE_ROLES]) await ensureRole(admin, role); + await admin.query(`CREATE SCHEMA "${schema}" AUTHORIZATION substrate_owner`); + await admin.query(`GRANT USAGE ON SCHEMA "${schema}" TO ${FIXTURE_ROLES.join(", ")}`); + + const roleUrl = (role: string): string => { + const url = new URL(databaseUrl); + url.username = role; + url.password = PASSWORD; + url.searchParams.set("options", `-c search_path=${schema},public`); + return url.toString(); + }; + if (options.migrate !== false) { + await applyMigrations({ databaseUrl: roleUrl("substrate_owner") }); + if (state === "wide") { + await admin.query( + `GRANT SELECT, INSERT, UPDATE, DELETE, TRUNCATE ON ALL TABLES IN SCHEMA "${schema}" + TO substrate_app, exomem_gateway, exomem_cellctl` + ); + } + } + const pools: Pool[] = [admin]; + const pool = (role: string): Pool => { + const created = new Pool({ connectionString: roleUrl(role), max: 4 }); + pools.push(created); + return created; + }; + return { + schema, + owner: pool("substrate_owner"), + app: pool("substrate_app"), + gateway: pool("exomem_gateway"), + cellctl: pool("exomem_cellctl"), + audit: pool("substrate_audit"), + admin, + q: (name) => `"${schema}".${name}`, + roleUrl, + async close() { + // Drop first: an open pool of a role keeps no lock on the schema. + await admin.query(`DROP SCHEMA IF EXISTS "${schema}" CASCADE`); + for (const created of pools) await created.end(); + }, + }; +} + +export type World = { + userId: string; + tenantId: string; + clientId: string; + grantId: string; + familyId: string; + accessTokenId: string; + accessDigest: Buffer; + refreshTokenId: string; + refreshDigest: Buffer; + serviceCredentialId: string; + /** The same rows, spent: revoked, consumed. A guard keeps each of those times. */ + spent: { + grantId: string; + familyId: string; + accessTokenId: string; + refreshTokenId: string; + serviceCredentialId: string; + }; +}; + +const RESOURCE = "https://gateway.example.test/mcp"; + +/** A pinned client row; its redirect list and digest satisfy the table's checks. */ +export async function seedClient(owner: Pool): Promise { + const redirectUris = JSON.stringify(["https://client.example.test/callback"]); + const { rows } = await owner.query<{ id: string }>( + `INSERT INTO exomem_oauth_clients ( + client_id, admission_mode, enabled, redirect_uris, redirect_uris_digest, + client_platform, oauth_client_config_sha256 + ) VALUES ($1, 'pinned', true, $2::jsonb, digest(convert_to($2::jsonb::text, 'utf8'), 'sha256'), + 'claude', $3) RETURNING id`, + [`https://client.example.test/${randomUUID()}.json`, redirectUris, "f".repeat(64)] + ); + return rows[0]!.id; +} + +/** One tenant with a live chain of credentials and a spent chain, written as the schema owner. */ +export async function seedWorld(owner: Pool): Promise { + const id = async (text: string, values: unknown[] = []): Promise => + (await owner.query<{ id: string }>(text, values)).rows[0]!.id; + const userId = await id("INSERT INTO exomem_users (email) VALUES ($1) RETURNING id", [ + `lock-${randomUUID()}@example.test`, + ]); + const tenantId = await id("INSERT INTO exomem_tenants (owner_user_id) VALUES ($1) RETURNING id", [ + userId, + ]); + const clientId = await seedClient(owner); + const chain = async (spent: boolean) => { + const revokedAt = spent ? "now()" : "NULL"; + const grant = await id( + `INSERT INTO exomem_oauth_grants (user_id, tenant_id, client_id, resource, scopes, revoked_at) + VALUES ($1, $2, $3, $4, ARRAY['mcp:read'], ${revokedAt}) RETURNING id`, + [userId, tenantId, clientId, `${RESOURCE}/${randomUUID()}`] + ); + const family = await id( + `INSERT INTO exomem_oauth_token_families (grant_id, client_id, expires_at, revoked_at) + VALUES ($1, $2, now() + interval '1 day', ${revokedAt}) RETURNING id`, + [grant, clientId] + ); + const accessDigest = randomBytes(32); + const access = await id( + `INSERT INTO exomem_oauth_access_tokens + (access_digest, grant_id, family_id, client_id, resource, scopes, expires_at, revoked_at) + VALUES ($1, $2, $3, $4, $5, ARRAY['mcp:read'], now() + interval '1 hour', ${revokedAt}) + RETURNING id`, + [accessDigest, grant, family, clientId, RESOURCE] + ); + const refreshDigest = randomBytes(32); + const refresh = await id( + `INSERT INTO exomem_oauth_refresh_tokens (refresh_digest, family_id, expires_at, consumed_at) + VALUES ($1, $2, now() + interval '1 day', ${revokedAt}) RETURNING id`, + [refreshDigest, family] + ); + const credential = await id( + `INSERT INTO exomem_cloud_service_credentials + (tenant_id, principal, secret_digest, created_by_principal_digest, revoked_at, revoked_by_principal_digest) + VALUES ($1, $2, $3, $4, ${revokedAt}, ${spent ? "$4" : "NULL"}) RETURNING id`, + [tenantId, `service:t${randomBytes(6).toString("hex")}`, randomBytes(32), randomBytes(32)] + ); + return { grant, family, access, accessDigest, refresh, refreshDigest, credential }; + }; + const live = await chain(false); + const spent = await chain(true); + return { + userId, + tenantId, + clientId, + grantId: live.grant, + familyId: live.family, + accessTokenId: live.access, + accessDigest: live.accessDigest, + refreshTokenId: live.refresh, + refreshDigest: live.refreshDigest, + serviceCredentialId: live.credential, + spent: { + grantId: spent.grant, + familyId: spent.family, + accessTokenId: spent.access, + refreshTokenId: spent.refresh, + serviceCredentialId: spent.credential, + }, + }; +} + +/** Every row of a table as JSON, to compare before and after a refused statement. */ +export async function tableSnapshot(owner: Pool, table: string): Promise { + const { rows } = await owner.query<{ snapshot: string }>( + `SELECT coalesce(jsonb_agg(to_jsonb(t) ORDER BY to_jsonb(t)::text), '[]'::jsonb)::text AS snapshot FROM ${table} AS t` + ); + return rows[0]!.snapshot; +} diff --git a/src/lib/exomem-hosted/__tests__/oauth-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/oauth-postgres.integration.test.ts index 65af59c1..a10f576e 100644 --- a/src/lib/exomem-hosted/__tests__/oauth-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/oauth-postgres.integration.test.ts @@ -5,6 +5,7 @@ import { readFileSync } from "node:fs"; import { resolve } from "node:path"; import { Pool, type PoolClient } from "pg"; import { applyMigrations } from "../../../../scripts/migrate"; +import { productionPool } from "./flow-pool"; import { ensureExomemPostgresTestExtensions } from "./postgres-test-extensions"; import { admitFirstCloudOAuthInviteAtomic, randomCloudCellId } from "../cloud-admission"; import { findCloudOAuthAccessToken, resolveApprovedCloudOAuthClient } from "../cloud-oauth"; @@ -47,6 +48,8 @@ const databaseUrl = process.env.EXOMEM_TEST_DATABASE_URL; const clientId = "https://client.example.test/metadata.json"; const resource = "https://gateway.example.test/mcp"; let pool: Pool | undefined; +// The pool that production code runs on: the suite's own, or the web app role's. +let flowPool: Pool | undefined; let schema: string | undefined; function digest(value: number): Buffer { @@ -67,7 +70,7 @@ function taggedSql(client: Pool | PoolClient): ExomemSql { } async function interactiveTransaction(callback: (tx: ExomemSql) => Promise): Promise { - const client = await pool!.connect(); + const client = await flowPool!.connect(); try { await client.query("BEGIN ISOLATION LEVEL READ COMMITTED"); const result = await callback(taggedSql(client)); @@ -235,7 +238,8 @@ describe("OAuth admission PostgreSQL integration", { skip: !databaseUrl, concurr await applyMigrations({ databaseUrl: scoped.toString() }); await admin.end(); pool = new Pool({ connectionString: scoped.toString() }); - __setExomemSqlForTests(taggedSql(pool)); + flowPool = await productionPool(scoped.toString(), schema); + __setExomemSqlForTests(taggedSql(flowPool)); __setExomemTransactionForTests(interactiveTransaction); await seedLiveCohort(); }); @@ -245,6 +249,7 @@ describe("OAuth admission PostgreSQL integration", { skip: !databaseUrl, concurr delete process.env.EXOMEM_CLOUD_MCP_PATH; __setExomemSqlForTests(null); __setExomemTransactionForTests(null); + await flowPool?.end(); if (pool) await pool.end(); if (schema) { const admin = new Pool({ connectionString: databaseUrl }); @@ -857,6 +862,50 @@ describe("OAuth admission PostgreSQL integration", { skip: !databaseUrl, concurr ); }); + it("records each credential that a code exchange and a refresh rotation write", async () => { + const internal = await seedClient(); + const fixture = await seedAuthorizationCode(internal, 160, true); + const recorded = async () => + ( + await pool!.query<{ credential_kind: string; count: number }>( + `SELECT credential_kind, count(*)::int AS count FROM exomem_cloud_issuance_log + WHERE tenant_id = $1 AND user_id = $2 GROUP BY credential_kind ORDER BY credential_kind`, + [fixture.tenantId, fixture.userId] + ) + ).rows; + assert.deepEqual(await recorded(), []); + const issued = await issueOAuthTokensFromCodeAtomic({ + codeDigest: fixture.codeDigest, + clientId, + redirectUri: "https://client.example.test/callback", + resource, + pkceChallenge: "challenge", + refreshDigest: digest(161), + accessDigest: digest(162), + accessExpiresAt: new Date(Date.now() + 60_000), + }); + assert.ok(issued); + assert.deepEqual(await recorded(), [ + { credential_kind: "access_token", count: 1 }, + { credential_kind: "refresh_token", count: 1 }, + { credential_kind: "token_family", count: 1 }, + ]); + const rotated = await rotateOAuthRefreshTokenAtomic({ + refreshDigest: digest(161), + replacementRefreshDigest: digest(163), + accessDigest: digest(164), + accessExpiresAt: new Date(Date.now() + 60_000), + clientId, + resource, + }); + assert.equal(rotated?.kind, "issued"); + assert.deepEqual(await recorded(), [ + { credential_kind: "access_token", count: 2 }, + { credential_kind: "refresh_token", count: 2 }, + { credential_kind: "token_family", count: 1 }, + ]); + }); + it("persists refresh material only for offline access and retains rotation lineage during GC", async () => { const internal = await seedClient(); const online = await seedAuthorizationCode(internal, 120, false); @@ -1622,7 +1671,7 @@ describe("OAuth admission PostgreSQL integration", { skip: !databaseUrl, concurr let transactions = 0; __setExomemTransactionForTests(async (callback) => { const holdsOpen = transactions++ === 0; - const client = await pool!.connect(); + const client = await flowPool!.connect(); try { await client.query("BEGIN ISOLATION LEVEL READ COMMITTED"); const result = await callback(taggedSql(client)); From 2c3a0573deb8471ef96d10250b7ec95dcf7c2d13 Mon Sep 17 00:00:00 2001 From: Artexis10 Date: Wed, 2 Dec 2026 09:36:16 +0000 Subject: [PATCH 06/29] Document the migration job, the identity lock and the issuance log The keys runbook now describes the protected migration job, the 15-minute build wait, the manual run with the operator's own copy of the credential, and the one build switch that skips the wait. The old build-time migration procedure and its pull of production variables are gone. The deployments runbook and the README say that a production build reads its schema release and never migrates, and that promotion, rollback and uploaded deployments do not check it. The operations runbook gains a section on what the lock refuses, the three emergency statements with what each suspends, the audit-role checks of the issuance log with their hourly overlap, the catalog checks, the size and retention reads, and the download ticket rows with their deploy and rollback order. Tasks 6.1 to 6.3 are ticked. --- README.md | 5 +- docs/runbooks/exomem-cloud-operations.md | 315 ++++++++++++++++++ docs/runbooks/production-keys-and-storage.md | 54 ++- docs/runbooks/vercel-deployments.md | 20 ++ .../tasks.md | 6 +- 5 files changed, 384 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 9e8f2c5d..3a0df9fe 100644 --- a/README.md +++ b/README.md @@ -131,7 +131,10 @@ npm run migrate # apply pending migrations from migrations/*.sql npm run migrate:dry # list pending migrations without applying ``` -The runner auto-creates a `schema_migrations` tracking table on first invocation. +The runner auto-creates a `schema_migrations` tracking table on first invocation. These commands run against the database that `DATABASE_URL` names in your shell, so use them on a local or disposable database. + +In production, a protected GitHub job (`.github/workflows/migrate-database.yml`) applies the migrations and the grants script for each commit that lands on `main`. +It then records the commit's schema release. The production build reads its schema release and never migrates. [`docs/runbooks/production-keys-and-storage.md`](./docs/runbooks/production-keys-and-storage.md) describes the job and the manual run. **JWT signing key.** Generate the active EdDSA keypair (and optionally insert the public-key row into `signing_keys`): diff --git a/docs/runbooks/exomem-cloud-operations.md b/docs/runbooks/exomem-cloud-operations.md index 5c16f8b1..f4e7a884 100644 --- a/docs/runbooks/exomem-cloud-operations.md +++ b/docs/runbooks/exomem-cloud-operations.md @@ -770,6 +770,321 @@ ticket, screenshot, test fixture or log. To rotate it, replace the value and redeploy before the provider verifies it. To remove it, delete the variable, redeploy, and confirm that the route returns `404`. +## Identity lock and issuance log + +Migrations `0100` and `0101` lock the rows that decide which tenant a credential reaches. They also record each +credential that the web app issues. This section says what the lock refuses and which statement the schema owner runs in an emergency. +It also says how to read the log and how download tickets use the database. The design is the OpenSpec change +`lock-cloud-identity-rows-and-record-issuance`. Its section "What the claim does not cover" lists the limits of the +claim, and those limits belong beside every statement of it. + +Four database roles appear here. `substrate_owner` owns the schema and runs the migrations. `substrate_app` is the web +app's role. `exomem_gateway` and `exomem_cellctl` are the gateway's and the controller's roles. `substrate_audit` reads +the log and nothing else. + +### What the lock refuses + +The grants script and the guards work together. The grants script takes rights from `substrate_app` on every run. A guard is a trigger that refuses a statement unless the schema owner runs it. +It still holds when a grants script gives too much. A guard raises `EXOMEM_ROW_LOCKED: on is refused` with SQLSTATE `42501`. An error +that reads `permission denied` comes from the grants script, not from a guard. + +| Table | Refused to the web app's role | Update guard | Delete and truncate guards | +| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------ | -------------------------------------------------------------------------- | +| `exomem_oauth_grants` | A change to any column except `scopes`, `refresh_allowed`, `authorization_transaction_id`, `updated_at`, `revoked_at` and `client_context_override`; a delete | `exomem_oauth_grants_identity_lock` | `exomem_oauth_grants_delete_lock`, `exomem_oauth_grants_truncate_lock` | +| `exomem_oauth_token_families` | A change to any column except `revoked_at` and `revoked_reason` | `exomem_oauth_token_families_identity_lock` | none: deletes stay | +| `exomem_oauth_access_tokens` | A change to any column except `revoked_at` | `exomem_oauth_access_tokens_identity_lock` | none: deletes stay | +| `exomem_oauth_refresh_tokens` | A change to any column except `consumed_at` | `exomem_oauth_refresh_tokens_identity_lock` | none: deletes stay | +| `exomem_cloud_service_credentials` | A change to any column except `revoked_at` and `revoked_by_principal_digest`; a delete | `exomem_cloud_service_credentials_identity_lock` | `exomem_cloud_service_credentials_delete_lock`, `..._truncate_lock` | +| `exomem_oauth_clients` | A change to `id` or `client_id`; a delete | `exomem_oauth_clients_identity_lock` | `exomem_oauth_clients_delete_lock`, `exomem_oauth_clients_truncate_lock` | +| `exomem_tenants` | A change to `owner_user_id`; a delete | `exomem_tenants_identity_lock` | `exomem_tenants_delete_lock`, `exomem_tenants_truncate_lock` | +| `exomem_users` | A delete | none | `exomem_users_delete_lock`, `exomem_users_truncate_lock` | +| `exomem_marketplace_reviewer_credentials` | A delete | none | `exomem_marketplace_reviewer_credentials_delete_lock`, `..._truncate_lock` | + +Four more rules hold on the same terms: + +- A revocation or consumption time that is already set cannot change. A statement that keeps the value succeeds. +- `schema_releases` and `exomem_cloud_issuance_log` refuse every insert, update, delete and truncate. + Only the schema owner and the routines that run as the schema owner may write them. The guards are `schema_releases_owner_only`, + `exomem_cloud_issuance_log_owner_only` and the matching `..._owner_only_truncate` triggers. +- A row in `exomem_cloud_download_tickets` cannot change. The guard is `exomem_cloud_download_tickets_update_lock`. +- A truncate that cascades from another table meets the same guards. + +The schema owner is exempt, because it can drop any guard. The lock is stated against the select, insert, update, +delete and truncate rights. It does not hold against a role that holds the trigger right, or a create right on the +database or on a schema. The checks below read those rights. + +### Emergency statements + +Run each statement as the schema owner, in `psql`, and write down its time and text. Read the error first, to see which +statement fits. + +- `permission denied for table` or `for column`: the grants script withheld a right. Use statement 1. +- `EXOMEM_ROW_LOCKED`: a guard refused a flow. Use statement 2. +- A credential insert fails, and the error names `exomem_record_issuance` or the log: the recording failed. Use + statement 3. + +| No | Statement | What it suspends | Undo | +| --- | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------- | +| 1 | `GRANT UPDATE () ON
TO substrate_app;` | Only the missing right on that column. The guard still refuses a fixed column. The grant lasts until the next run of the grants script, which is the next merge. | `REVOKE UPDATE () ON
FROM substrate_app;` | +| 2 | `ALTER TABLE
DISABLE TRIGGER ;` | That guard, for every role, on that table. The table's protection then rests on rights alone, and the grants script does not re-enable the trigger. A migration does not either. | `ALTER TABLE
ENABLE TRIGGER ;` | +| 3 | `ALTER TABLE
DISABLE TRIGGER
_issuance_record;` | The claim that the database records each credential, for that credential kind. A credential that the web app creates while the trigger is off has no record. The check "credential rows without a record" lists each one afterwards. | `ALTER TABLE
ENABLE TRIGGER
_issuance_record;` | + +The recording triggers are `exomem_oauth_token_families_issuance_record`, `exomem_oauth_access_tokens_issuance_record`, +`exomem_oauth_refresh_tokens_issuance_record`, `exomem_cloud_service_credentials_issuance_record` and +`exomem_cloud_download_tickets_issuance_record`. Each one sits on the table that its name gives. + +A hand-typed grant or a disabled trigger is an emergency state, not a fix. After either statement: + +1. Open a commit that changes the grants script or the guard so that the flow works under the lock. +2. Merge it. The migration job applies the grants script. +3. Run the undo of the statement, if the grants script has not already done so. +4. Run the catalog check "triggers that are missing or disabled" below. The expected result is no rows. +5. For statement 3, run the check "credential rows without a record" over the period of the outage. + +### The issuance log + +`exomem_cloud_issuance_log` holds one record for each credential that the web app inserts. +The credential is a token family, an access token, a refresh token, a service credential or a download ticket. A record holds identifiers only. +These are the credential's `id` and kind, its grant, token family, client, tenant and user, and its expiry. +A record also holds its own time and the database role that wrote it. It holds no token, digest, secret, path or address. A record that the migration wrote for an older +row has `backfilled` set. Its `recorded_at` is the migration's time. + +The recording fails closed. A credential insert fails when its record cannot be written. The web app's role cannot read, +write or alter the log. The reconcile job calls `exomem_prune_issuance_log()` once a run. The function deletes at most +10,000 records whose credential expired more than 90 days ago. It never deletes a record that has no expiry, which is a +service credential's. The job's response reports the deleted counts as `issuancePruned.records` and +`issuancePruned.tickets`. A value of `null` means that part failed, and the log line `exomem-issuance: log retention +failed` names it. + +#### Read it as the audit role + +Connect as `substrate_audit` for every query in this section. The grants script gives that role select on the log. +It also gives select on the `id` and `created_at` columns of the five credential tables, and on `id` and `owner_user_id` of `exomem_tenants`. It gives no other right. Each query below reads a range of record identifiers through the primary key. +Its cost follows the range, not the size of the log. + +Run the range checks about once an hour, and after any emergency statement. Each run starts one hour of records before +the point where the previous run stopped. A record gets its identifier when it is inserted, not when it commits, so a +record can commit after a run has read past it. The overlap lets the next run read it. A record whose transaction stayed +open for longer than that hour is missed by the range checks. The read of one tenant's records still returns it. + +1. Write down the value of `hi` that the previous run printed. For the first run, use `0`. +2. Start `psql` as `substrate_audit` with the value: `psql -v prev=`. +3. Find the range of this run: + + ```sql + SELECT max(id) AS hi FROM exomem_cloud_issuance_log \gset + SELECT coalesce( + (SELECT id FROM exomem_cloud_issuance_log + WHERE id <= :prev + AND recorded_at < (SELECT recorded_at FROM exomem_cloud_issuance_log WHERE id = :prev) - interval '1 hour' + ORDER BY id DESC LIMIT 1), 0) AS lo \gset + SELECT coalesce((SELECT recorded_at FROM exomem_cloud_issuance_log WHERE id = :lo), '-infinity') AS lo_time \gset + \echo hi=:hi lo=:lo + ``` + +4. Run the three range checks. Each one is a finding when it returns a row. + + Credential rows without a record. One statement reads the credential rows and the log, so a credential and its + record are both visible or both absent. A row here has no record. It reads the log from `lo` to its end. + + ```sql + SELECT created.kind, created.id, created.created_at + FROM ( + SELECT 'token_family' AS kind, id, created_at FROM exomem_oauth_token_families + UNION ALL SELECT 'access_token', id, created_at FROM exomem_oauth_access_tokens + UNION ALL SELECT 'refresh_token', id, created_at FROM exomem_oauth_refresh_tokens + UNION ALL SELECT 'service_credential', id, created_at FROM exomem_cloud_service_credentials + UNION ALL SELECT 'download_ticket', id, created_at FROM exomem_cloud_download_tickets + ) AS created + WHERE created.created_at >= :'lo_time' + AND NOT EXISTS ( + SELECT 1 FROM exomem_cloud_issuance_log AS record + WHERE record.id >= :lo + AND record.credential_kind = created.kind AND record.credential_id = created.id); + ``` + + Records written by another database role. The web app's role writes every record, except those that the migration + backfilled. A row here means that the schema owner, or a role with the insert right, issued a credential outside the + web app. Match it to a change record. + + ```sql + SELECT id, credential_kind, credential_id, database_role, recorded_at + FROM exomem_cloud_issuance_log + WHERE id BETWEEN :lo AND :hi AND NOT backfilled AND database_role <> 'substrate_app'; + ``` + + Records whose user is not the tenant's owner. The recording function copies both values from the grant. A mismatch + means that someone changed an owner after the record, or that the record is false. + + ```sql + SELECT record.id, record.credential_kind, record.tenant_id, record.user_id + FROM exomem_cloud_issuance_log AS record + JOIN exomem_tenants AS tenant ON tenant.id = record.tenant_id + WHERE record.id BETWEEN :lo AND :hi AND record.user_id <> tenant.owner_user_id; + ``` + +5. Write down the value of `hi` as the stop of this run. The next run takes it as `prev`. + +Read one tenant's records, newest first, a page at a time. Use it for an incident, and for an owner who asks who held +access. For the first page, use the value of `hi` plus one as ``. For the next page, use the lowest `id` of the +page before. + +```sql +SELECT id, recorded_at, credential_kind, credential_id, grant_id, family_id, client_id, expires_at +FROM exomem_cloud_issuance_log +WHERE tenant_id = '' AND id < +ORDER BY id DESC LIMIT 50; +``` + +#### Catalog checks + +These four checks read the catalog and the grants. Run them with the range checks, and after every migration. Each one +is a finding when it returns a row. Run them as `substrate_audit`: they need no other right. + +Triggers of this change that are missing or disabled. A row with a `NULL` state is missing. A state other than `O` is +disabled. + +```sql +SELECT expected.table_name, expected.trigger_name, trigger.tgenabled AS state +FROM (VALUES + ('exomem_oauth_grants', 'exomem_oauth_grants_identity_lock'), + ('exomem_oauth_token_families', 'exomem_oauth_token_families_identity_lock'), + ('exomem_oauth_access_tokens', 'exomem_oauth_access_tokens_identity_lock'), + ('exomem_oauth_refresh_tokens', 'exomem_oauth_refresh_tokens_identity_lock'), + ('exomem_cloud_service_credentials', 'exomem_cloud_service_credentials_identity_lock'), + ('exomem_oauth_clients', 'exomem_oauth_clients_identity_lock'), + ('exomem_tenants', 'exomem_tenants_identity_lock'), + ('exomem_oauth_grants', 'exomem_oauth_grants_delete_lock'), + ('exomem_oauth_grants', 'exomem_oauth_grants_truncate_lock'), + ('exomem_oauth_clients', 'exomem_oauth_clients_delete_lock'), + ('exomem_oauth_clients', 'exomem_oauth_clients_truncate_lock'), + ('exomem_tenants', 'exomem_tenants_delete_lock'), + ('exomem_tenants', 'exomem_tenants_truncate_lock'), + ('exomem_users', 'exomem_users_delete_lock'), + ('exomem_users', 'exomem_users_truncate_lock'), + ('exomem_cloud_service_credentials', 'exomem_cloud_service_credentials_delete_lock'), + ('exomem_cloud_service_credentials', 'exomem_cloud_service_credentials_truncate_lock'), + ('exomem_marketplace_reviewer_credentials', 'exomem_marketplace_reviewer_credentials_delete_lock'), + ('exomem_marketplace_reviewer_credentials', 'exomem_marketplace_reviewer_credentials_truncate_lock'), + ('schema_releases', 'schema_releases_owner_only'), + ('schema_releases', 'schema_releases_owner_only_truncate'), + ('exomem_cloud_issuance_log', 'exomem_cloud_issuance_log_owner_only'), + ('exomem_cloud_issuance_log', 'exomem_cloud_issuance_log_owner_only_truncate'), + ('exomem_cloud_download_tickets', 'exomem_cloud_download_tickets_update_lock'), + ('exomem_oauth_token_families', 'exomem_oauth_token_families_issuance_record'), + ('exomem_oauth_access_tokens', 'exomem_oauth_access_tokens_issuance_record'), + ('exomem_oauth_refresh_tokens', 'exomem_oauth_refresh_tokens_issuance_record'), + ('exomem_cloud_service_credentials', 'exomem_cloud_service_credentials_issuance_record'), + ('exomem_cloud_download_tickets', 'exomem_cloud_download_tickets_issuance_record') +) AS expected(table_name, trigger_name) +LEFT JOIN pg_trigger AS trigger + ON trigger.tgname = expected.trigger_name AND trigger.tgrelid = to_regclass(expected.table_name) +WHERE trigger.tgenabled IS DISTINCT FROM 'O'; +``` + +Roles other than the table's owner that hold the trigger right on a table in the schema. A role with that right can run +its own code as the schema owner, and no guard holds against it. Revoke the right with `REVOKE TRIGGER ON
FROM +`. The grants script revokes it on every run. + +```sql +SELECT class.oid::regclass AS table_name, + CASE WHEN privilege.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(privilege.grantee) END AS holder +FROM pg_class AS class +JOIN pg_namespace AS namespace ON namespace.oid = class.relnamespace AND namespace.nspname = current_schema() +CROSS JOIN LATERAL aclexplode(class.relacl) AS privilege +WHERE class.relkind IN ('r', 'p') AND privilege.privilege_type = 'TRIGGER' AND privilege.grantee <> class.relowner; +``` + +Roles that the web app's role is a member of. A membership can carry any right. The expected result is no rows. + +```sql +SELECT pg_get_userbyid(roleid) AS member_of +FROM pg_auth_members WHERE member = 'substrate_app'::regrole; +``` + +Create rights and schemas. A role that can create a schema can run its code as the schema owner, with no trigger right. +The first query lists each role that holds a create right on the database, or on a schema outside `pg_catalog` and `information_schema`. +It counts a right held directly or through a membership. +It leaves out a superuser, the schema owner and `pg_database_owner`. +The second lists each schema that another role owns. Revoke each right, and drop each schema that a role created. + +```sql +SELECT 'database' AS target, role.rolname AS holder +FROM pg_roles AS role +WHERE has_database_privilege(role.oid, current_database(), 'CREATE') + AND NOT role.rolsuper AND role.rolname NOT IN ('substrate_owner', 'pg_database_owner') +UNION ALL +SELECT namespace.nspname, role.rolname +FROM pg_namespace AS namespace +CROSS JOIN pg_roles AS role +WHERE namespace.nspname NOT IN ('pg_catalog', 'information_schema') + AND namespace.nspname NOT LIKE 'pg\_toast%' AND namespace.nspname NOT LIKE 'pg\_temp\_%' + AND has_schema_privilege(role.oid, namespace.oid, 'CREATE') + AND NOT role.rolsuper AND role.oid <> namespace.nspowner + AND role.rolname NOT IN ('substrate_owner', 'pg_database_owner'); + +SELECT namespace.nspname, pg_get_userbyid(namespace.nspowner) AS owner +FROM pg_namespace AS namespace +WHERE namespace.nspname NOT LIKE 'pg\_temp\_%' AND namespace.nspname NOT LIKE 'pg\_toast\_temp\_%' + AND namespace.nspowner <> 10 + AND pg_get_userbyid(namespace.nspowner) NOT IN ('substrate_owner', 'pg_database_owner'); +``` + +#### Size and retention + +At the load target the design estimates about 142 million records and 35 GB, which is 250 bytes for a record and its +three indexes. Read the size with the estimated record count. The count is the planner's estimate, so it lags until +the next analyse. + +```sql +SELECT pg_size_pretty(pg_total_relation_size('exomem_cloud_issuance_log')) AS size, + (SELECT reltuples::bigint FROM pg_class WHERE oid = 'exomem_cloud_issuance_log'::regclass) AS estimated_records; +``` + +Read how far the prune is behind. The count stops at 100,001, so the read stays short when the prune has failed for +long. A result of 100,001 means at least ten runs of backlog. Check the reconcile job's `issuancePruned.records`, and +the log line `exomem-issuance: log retention failed`. + +```sql +SELECT count(*) AS past_retention +FROM (SELECT 1 FROM exomem_cloud_issuance_log + WHERE expires_at < now() - interval '90 days' LIMIT 100001) AS stale; +``` + +A log that holds twice the size that the count of live credentials predicts needs a look at the prune first. The +retention period is a constant inside the function, so a change needs a migration. + +### Download ticket rows + +A download ticket is a signed message that names a token family, a grant, a path digest and an expiry. The web app stores one row in `exomem_cloud_download_tickets` before it redirects to the ticket's address. +The insert uses `ON CONFLICT DO NOTHING` on the key `(family_id, path_sha256, expires_at)`. Two tickets with the same three values share one row and +one record. The gateway serves a ticket only when that row exists and has not expired. The gateway checks it inside the +statement that finds the ticket's login, so a download makes no extra database round trip. + +- A ticket that has no row, or whose path, token family or expiry differs from the row, gets `401 DOWNLOAD_TICKET_INVALID` + from the gateway. The owner asks for the download again. +- The web app's role may select, insert and delete ticket rows. The gateway's role reads `family_id`, `path_sha256` and + `expires_at`. No role can update a row. +- The reconcile job deletes up to 1000 expired rows a run, through the index on `expires_at`. A row lives one day at most. +- The row table has no foreign key. A ticket row whose insert names no real grant fails, because the recording trigger + reads the grant. + +#### Deploy and rollback order + +A ticket signed by a web release that stores no row is refused by a gateway that requires one. The two releases +therefore move in a fixed order. + +1. Merge the change. The migration job creates the ticket table. The web release then stores a row for each ticket. +2. Wait at least one day. That is the longest lifetime of a ticket, so every ticket in use has its row. +3. Roll the gateway release that requires ticket rows. The expected result is that downloads keep working. + +To roll back, reverse the order: + +1. Roll the gateway back to its previous image first. That image ignores ticket rows. +2. Roll the web app back past this change only after the gateway has rolled back. + +A gateway that requires rows and a web release from before this change refuse every download until one of them moves. + ## External scheduler Vercel Hobby rejects cron expressions that run more than once per day, so the diff --git a/docs/runbooks/production-keys-and-storage.md b/docs/runbooks/production-keys-and-storage.md index c3660344..f60fdbd2 100644 --- a/docs/runbooks/production-keys-and-storage.md +++ b/docs/runbooks/production-keys-and-storage.md @@ -172,23 +172,53 @@ Each of these has bitten us in production at least once during hosted-backup rol **4. Asymmetric handling between paired endpoints.** When two endpoints implement opposite halves of the same protocol contract (upload mints URL → download fetches URL; encrypt → decrypt; write → read), an invariant on one side has to be honored on the other. Drift is invisible in unit tests that exercise each half in isolation. The hosted-backup contract uses `chunkIndex = -1` as the sentinel for the manifest blob in **both** the upload-URL response (`POST /api/backups/:id/versions`) and the download-URL request (`POST /api/backups/:id/versions/:vid/download-urls`); the upload side was correct from PR #2, but the download side validated all requested indices against the chunks table — where `-1` is by definition absent — and threw `NOT_FOUND` before ever reaching the manifest case. **When you find a sentinel value or magic-number convention in code, grep the codebase for every other place that value could appear and verify the symmetry.** Add an end-to-end test that round-trips through both endpoints with the sentinel. *(First seen: PR #7, `POST .../download-urls` with `chunkIndices: [-1]` returned `NOT_FOUND`, blocking the engine smoke test's pull half on a real prod backup `9e6f8cc9-…`/`910f3c00-…`. Push had worked because that path mints the manifest URL itself; download couldn't fetch what push had written.)* -**5. Migrations auto-run on Vercel *production* deploys via `vercel-build`** (since 2026-05-27). `package.json`'s `vercel-build` script chains `scripts/vercel-maybe-migrate.ts` before `next build`. The migrate step checks `VERCEL_ENV` and only runs against the production database when `VERCEL_ENV === 'production'` — preview and development builds skip it. A failing migration aborts the build and the previous deploy stays live. +**5. A protected GitHub job applies the migrations. The Vercel build never does.** The workflow `.github/workflows/migrate-database.yml` runs the job `migrate`. It starts on every push to `main` and by hand. It runs in the protected environment `production-schema`, whose branch rule accepts only `main`. That environment holds the schema-owner connection string as the secret `DATABASE_MIGRATION_URL`. No Vercel environment holds it. -**Implications:** +For the commit at the tip of `main`, the job does three things in order: -- **Adding a migration: just merge.** When you add `migrations/00XX_*.sql` and a PR that depends on the schema in the same merge, the Vercel deploy of `main` applies the migration before serving traffic. No manual step needed for the happy path. -- **Manual override:** set `SKIP_VERCEL_MIGRATE=1` in Vercel project env to disable temporarily (e.g. during incident response where a migration is hot-failing and you need the previous code path back up faster than a revert). Unset it once recovered. -- **Manual application is still possible** for one-off backfills or pre-merge dry-runs: +1. It applies the pending migrations, then `scripts/exomem-cloud-grants.sql`. +2. It records a schema release for the commit in `schema_releases`, with status `released`. +3. It records each earlier commit that has no row as `superseded`. - ```bash - vercel env pull .env.production.local --environment=production - npx tsx --env-file=.env.production.local scripts/migrate.ts --dry # confirm pending - npx tsx --env-file=.env.production.local scripts/migrate.ts # apply - rm .env.production.local # wipe local credentials - ``` +A job for a commit that is not the tip applies nothing. The concurrency group lets one run proceed at a time and never cancels a running one. -- **Preview deploys** still skip migrations entirely. If you need to test a migration's effect on a preview env, point that preview's `DATABASE_URL` at a separate, disposable database and apply via the manual `tsx --env-file=...` form above. +**The build.** `package.json`'s `vercel-build` script runs `scripts/wait-for-schema-release.ts` before `next build`. A production build reads the row for its own commit through the web app's database role: + +- `released`: the build continues. When a newer release exists, the log says so. +- `superseded`: the build fails at once. A newer commit carries the schema release. +- No row, no table, or a refused select: the build polls every 10 seconds for up to 15 minutes, then fails. The merge commit's build starts before the job has created the table. + +A production build that carries no commit identifier fails. A failed build leaves the previous deployment serving. Preview and development builds neither migrate nor wait. + +**A job that fails.** Each migration runs in one transaction with a lock timeout of five seconds. A migration that meets its lock timeout, or a deadlock with a flow that writes in another order, fails the job and records no release. Nothing stays half applied, and the build fails after its wait. + +1. Open the failed run in the repository's "Actions" tab. +2. Select "Re-run failed jobs". The job tests the tip again, so it applies only the tip of `main`. +3. Wait for the job to end. The expected result is a green run and a `released` row for the commit. + +If the same step fails twice, read its log for the lock that timed out. +Find the long transaction that holds that lock before you start the job again. + +**A manual run.** Use it when the runner cannot reach the database or GitHub Actions is down. It needs your own copy of the schema-owner connection string from your secret store, and the full hash of the commit to apply. + +1. Check out the tip of `main` in a clean working tree: `git fetch origin main && git checkout --detach origin/main`. +2. Read the hash of that commit: `git rev-parse HEAD`. Use the full 40 characters below. +3. Install the dependencies without install scripts: `npm ci --ignore-scripts`. +4. Hold the connection string in this shell only: `read -rs DATABASE_MIGRATION_URL && export DATABASE_MIGRATION_URL`. Paste it, then press Enter. +5. List the pending migrations: `npx tsx scripts/migrate.ts --dry`. The expected result is the list, and `[migrate] --dry: not applying`. +6. Print the superseded commits: `scripts/schema-release-plan.sh `. The expected result is `tip=true` and a `superseded=` list. +7. Apply and record: `npx tsx scripts/migrate.ts --commit --superseded `. The expected result is `[migrate] applying grants ... ok`, then `[migrate] recorded release ` and the count of superseded commits. +8. Clear the credential: `unset DATABASE_MIGRATION_URL`. + +Never write the connection string to a file, a Vercel variable or a shell history line. The build of a waiting merge commit continues within 10 seconds of step 7. + +**An incident that needs a build now.** Set `SKIP_SCHEMA_RELEASE_WAIT=1` in the Vercel Production environment to ship one build without the wait. The log of that build says that it skipped the check. The build then runs against whatever schema exists, so use it only when you know that the schema is compatible. Unset the variable once the incident ends. + +**Promotion, rollback and uploaded deployments** run no build, so none of them checks the schema release. `vercel-deployments.md` says what to check by hand. + +**Preview deploys.** To test a migration on a preview, point that preview's `DATABASE_URL` at a separate, disposable database. Apply the migrations with `scripts/migrate.ts` and that database's own connection string. Never point a preview at a database that holds production data. *(First seen: v2.0.0 cutover, migration `0011_recovery_tokens_used.sql` was caught pre-merge by manual review during the substrate→engine handoff. Repeated 2026-05-27 with `0015_account_sessions.sql` — engine v2.4.0 and gui-v2.7.0 / v2.8.0 all shipped before the migration was applied, and the new `/account/start` route 500'd at production until the manual migration ran. That incident motivated wiring the auto-migration into `vercel-build`.)* +*(The protected migration job replaces that auto-migration. It still applies migrations on every merge, and it takes the schema-owner credential out of the build.)* ### Verify the bypass is wired (substrate-side, no engine needed) diff --git a/docs/runbooks/vercel-deployments.md b/docs/runbooks/vercel-deployments.md index 3c171640..2d78a0bd 100644 --- a/docs/runbooks/vercel-deployments.md +++ b/docs/runbooks/vercel-deployments.md @@ -15,4 +15,24 @@ delete existing deployments or reduce retained storage by itself. Inventory old deployments separately, preserve production/current aliases and rollback targets, and remove only confirmed unused previews. +## Production builds and the schema release + +A production build never migrates the database. The protected job `migrate` applies the migrations and the grants script for the tip of `main`, then records a schema release for that commit. The build script `scripts/wait-for-schema-release.ts` reads the row for the build's commit and continues only on `released`. `production-keys-and-storage.md` describes the job, the wait and the manual run. + +The check runs in every production build that the platform makes from source: a push, a redeploy and a deploy hook. It does not run in these cases, because none of them runs the build script: + +- **Promotion** of an existing deployment to production. +- **Instant rollback** to an earlier deployment. +- **A deployment that was built elsewhere and uploaded** with the Vercel CLI. + +Each of the three serves code without a check of the schema. The schema may be older or newer than that code. Each migration stays compatible with the release before it, so a rollback of one release is safe. Before you promote, roll back further, or upload a deployment, follow these steps: + +1. Read the commit of the deployment that you plan to serve. +2. As the schema owner, run `SELECT commit_sha, status FROM schema_releases WHERE commit_sha = ''`. A `released` row means the schema is at least as new as that commit. +3. If the row is missing or `superseded`, read the commits between that one and the newest `released` row. Serve the deployment only when none of them adds a migration that breaks the older code. + +The expected result is a decision that you can name: the schema fits the code, or you start the migration job first. + +To ship one production build while the job cannot run, set `SKIP_SCHEMA_RELEASE_WAIT=1` in the Production environment, and unset it afterwards. + Reference: [Vercel Git configuration](https://vercel.com/docs/project-configuration/git-configuration). diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md index d77a86de..0ea9e1f8 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md @@ -215,14 +215,14 @@ without truncate. Neither state holds the trigger right. ## 6. Documentation -- [ ] 6.1 `docs/runbooks/production-keys-and-storage.md`: replace the +- [x] 6.1 `docs/runbooks/production-keys-and-storage.md`: replace the build-time migration section. Describe the migration job, the manual run with the operator's own copy of the credential and a named commit, and `SKIP_SCHEMA_RELEASE_WAIT`. Say that a migration that meets its lock timeout or a deadlock fails the job, and that the operator starts the job again. Remove `SKIP_VERCEL_MIGRATE` and the procedure that pulls production variables to a local file. -- [ ] 6.2 `docs/runbooks/exomem-cloud-operations.md`: what the lock refuses, +- [x] 6.2 `docs/runbooks/exomem-cloud-operations.md`: what the lock refuses, and each emergency statement with what it suspends. The issuance log: the D12 checks as the audit role, with the hour that each run reads again, a size check, and the statement that disables recording. The three catalog @@ -230,7 +230,7 @@ without truncate. Neither state holds the trigger right. rights held by a role other than a superuser, the schema owner or `pg_database_owner`, and schemas that another role owns. Ticket rows. The deploy order and the rollback order of D8. -- [ ] 6.3 `docs/runbooks/vercel-deployments.md` and the README's migration +- [x] 6.3 `docs/runbooks/vercel-deployments.md` and the README's migration section: the production build reads its schema release and never migrates. Say beside promotion, rollback and uploaded deployments that none of them checks the schema release. From 784f73098acbefa5fd17eb13e559ae8081582595 Mon Sep 17 00:00:00 2001 From: Artexis10 Date: Wed, 2 Dec 2026 09:43:30 +0000 Subject: [PATCH 07/29] Format the issuance retention helper with prettier --- src/lib/exomem-hosted/issuance-maintenance.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/lib/exomem-hosted/issuance-maintenance.ts b/src/lib/exomem-hosted/issuance-maintenance.ts index 2c06a158..b3fbd3ef 100644 --- a/src/lib/exomem-hosted/issuance-maintenance.ts +++ b/src/lib/exomem-hosted/issuance-maintenance.ts @@ -20,7 +20,8 @@ type IssuancePruneResult = { export async function pruneIssuanceState(): Promise { let records: number | null = null; try { - const { rows } = await sql`/* exomem:prune-issuance-log */ SELECT exomem_prune_issuance_log() AS deleted`; + const { rows } = + await sql`/* exomem:prune-issuance-log */ SELECT exomem_prune_issuance_log() AS deleted`; records = Number(rows[0]?.deleted); } catch { console.error("exomem-issuance: log retention failed"); From 08c18f107046910b27f56d70a61b8988ca457daa Mon Sep 17 00:00:00 2001 From: Artexis10 Date: Wed, 2 Dec 2026 09:45:50 +0000 Subject: [PATCH 08/29] Renumber the identity lock and issuance log migrations after main's 0100 --- docs/runbooks/exomem-cloud-operations.md | 2 +- ....sql => 0101_exomem_identity_lock_and_schema_releases.sql} | 0 ....sql => 0102_exomem_issuance_log_and_download_tickets.sql} | 0 scripts/exomem-cloud-grants.sql | 2 +- scripts/migrate.ts | 4 ++-- .../__tests__/cloud-issuance-log-postgres.integration.test.ts | 2 +- 6 files changed, 5 insertions(+), 5 deletions(-) rename migrations/{0100_exomem_identity_lock_and_schema_releases.sql => 0101_exomem_identity_lock_and_schema_releases.sql} (100%) rename migrations/{0101_exomem_issuance_log_and_download_tickets.sql => 0102_exomem_issuance_log_and_download_tickets.sql} (100%) diff --git a/docs/runbooks/exomem-cloud-operations.md b/docs/runbooks/exomem-cloud-operations.md index f4e7a884..73d2f84f 100644 --- a/docs/runbooks/exomem-cloud-operations.md +++ b/docs/runbooks/exomem-cloud-operations.md @@ -772,7 +772,7 @@ redeploy, and confirm that the route returns `404`. ## Identity lock and issuance log -Migrations `0100` and `0101` lock the rows that decide which tenant a credential reaches. They also record each +Migrations `0101` and `0102` lock the rows that decide which tenant a credential reaches. They also record each credential that the web app issues. This section says what the lock refuses and which statement the schema owner runs in an emergency. It also says how to read the log and how download tickets use the database. The design is the OpenSpec change `lock-cloud-identity-rows-and-record-issuance`. Its section "What the claim does not cover" lists the limits of the diff --git a/migrations/0100_exomem_identity_lock_and_schema_releases.sql b/migrations/0101_exomem_identity_lock_and_schema_releases.sql similarity index 100% rename from migrations/0100_exomem_identity_lock_and_schema_releases.sql rename to migrations/0101_exomem_identity_lock_and_schema_releases.sql diff --git a/migrations/0101_exomem_issuance_log_and_download_tickets.sql b/migrations/0102_exomem_issuance_log_and_download_tickets.sql similarity index 100% rename from migrations/0101_exomem_issuance_log_and_download_tickets.sql rename to migrations/0102_exomem_issuance_log_and_download_tickets.sql diff --git a/scripts/exomem-cloud-grants.sql b/scripts/exomem-cloud-grants.sql index 7498cbf8..19fcf28e 100644 --- a/scripts/exomem-cloud-grants.sql +++ b/scripts/exomem-cloud-grants.sql @@ -36,7 +36,7 @@ -- credentials except the ones its flows change. It reads schema_releases -- and writes nothing there. The script also revokes the trigger right on -- every table in the schema from every role but the table's owner. The --- guards in migration 0100 hold whatever this script grants. +-- guards in migration 0101 hold whatever this script grants. -- -- Applied by the migration runner (scripts/migrate.ts) after every run -- -- including one against a migrationsDir that never creates the Cloud diff --git a/scripts/migrate.ts b/scripts/migrate.ts index 9a5836c3..e90e1985 100644 --- a/scripts/migrate.ts +++ b/scripts/migrate.ts @@ -188,7 +188,7 @@ async function applyFile(sql: Sql, migrationsDir: string, filename: string): Pro * Writes the schema release of `commit` and each superseded commit, in one * transaction. A commit that already has a row keeps it, so a restarted run * of a released commit leaves it released. The table is the schema owner's - * to write (migration 0100's guard). + * to write (migration 0101's guard). */ async function recordSchemaReleases( sql: Sql, @@ -196,7 +196,7 @@ async function recordSchemaReleases( superseded: readonly string[] ): Promise { if ((await sql.query("SELECT to_regclass('schema_releases') AS name")).rows[0]?.name === null) { - // A stale run can reach a database that migration 0100 has not reached yet. + // A stale run can reach a database that migration 0101 has not reached yet. // No release can exist there, so there is nothing to supersede. console.log("[migrate] schema_releases does not exist yet; nothing to record"); return; diff --git a/src/lib/exomem-hosted/__tests__/cloud-issuance-log-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-issuance-log-postgres.integration.test.ts index fd35be28..3db90e80 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-issuance-log-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-issuance-log-postgres.integration.test.ts @@ -305,7 +305,7 @@ describe("The migration that adds the log", { skip: !databaseUrl }, () => { fx = await createLockFixture("narrow", { migrate: false }); migrationRoot = await mkdtemp(join(tmpdir(), "issuance-log-upgrade-")); for (const name of await readdir("migrations")) { - if (name.endsWith(".sql") && name < "0101") + if (name.endsWith(".sql") && name < "0102") await cp(join("migrations", name), join(migrationRoot, name)); } }); From 845eaad1bb73f9e8ee64c013deb9f2a0125f18f1 Mon Sep 17 00:00:00 2001 From: Artexis10 Date: Wed, 2 Dec 2026 10:22:18 +0000 Subject: [PATCH 09/29] Guard ticket grants and cell identity, and fail the search-path pin on foreign schemas A web-role insert into the download ticket table could name another tenant's token family with a grant of its own. The gateway matches a ticket on the family, the path digest and the expiry, so it admitted the ticket, and the issuance record named the inserting role's tenant and user. - Refuse a ticket row whose grant is not its token family's grant, or whose family does not exist, for every role (new definer function with a pinned path). The recording function now reads the grant through the family for tickets, as it does for refresh tokens. - Raise, and so roll back the first migration, when a schema on the migration path belongs to a role other than the schema owner, the bootstrap superuser or pg_database_owner. The error names each schema and its owner. The earlier notice left such schemas out of the pin, and the pinned functions then failed at their next call. - Refuse a change to cell_id or tenant_id on exomem_cloud_cells, and a delete or truncate, for every role except the schema owner. No code changes those columns or deletes a cell row as another role. - Add the schema release suite to the CI PostgreSQL list. - Update the design, the gateway and OAuth specs, the task list and the runbook, and name the gateway use log as a later step for limit 9. --- .github/workflows/test.yml | 1 + docs/runbooks/exomem-cloud-operations.md | 12 +- ...omem_identity_lock_and_schema_releases.sql | 55 +++--- ...omem_issuance_log_and_download_tickets.sql | 48 ++++- .../design.md | 17 +- .../specs/exomem-hosted-gateway/spec.md | 9 +- .../specs/exomem-hosted-mcp-oauth/spec.md | 7 +- .../tasks.md | 33 ++-- scripts/exomem-cloud-grants.sql | 6 + .../cloud-grants-postgres.integration.test.ts | 24 ++- ...identity-lock-postgres.integration.test.ts | 171 ++++++++++++++++++ .../__tests__/identity-lock-fixture.ts | 17 ++ 12 files changed, 342 insertions(+), 58 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index a561f858..f0ee4dfc 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -47,6 +47,7 @@ jobs: src/lib/exomem-hosted/__tests__/capacity-postgres.integration.test.ts src/lib/exomem-hosted/__tests__/migration-upgrade.integration.test.ts src/lib/exomem-hosted/__tests__/migration-runner.integration.test.ts + src/lib/exomem-hosted/__tests__/schema-release-postgres.integration.test.ts src/lib/exomem-hosted/__tests__/postgres.integration.test.ts src/lib/exomem-hosted/__tests__/alert-receiver-postgres.integration.test.ts src/lib/exomem-hosted/__tests__/access-recovery.test.ts diff --git a/docs/runbooks/exomem-cloud-operations.md b/docs/runbooks/exomem-cloud-operations.md index 73d2f84f..ac100c5a 100644 --- a/docs/runbooks/exomem-cloud-operations.md +++ b/docs/runbooks/exomem-cloud-operations.md @@ -797,6 +797,7 @@ that reads `permission denied` comes from the grants script, not from a guard. | `exomem_cloud_service_credentials` | A change to any column except `revoked_at` and `revoked_by_principal_digest`; a delete | `exomem_cloud_service_credentials_identity_lock` | `exomem_cloud_service_credentials_delete_lock`, `..._truncate_lock` | | `exomem_oauth_clients` | A change to `id` or `client_id`; a delete | `exomem_oauth_clients_identity_lock` | `exomem_oauth_clients_delete_lock`, `exomem_oauth_clients_truncate_lock` | | `exomem_tenants` | A change to `owner_user_id`; a delete | `exomem_tenants_identity_lock` | `exomem_tenants_delete_lock`, `exomem_tenants_truncate_lock` | +| `exomem_cloud_cells` | A change to `cell_id` or `tenant_id`; a delete | `exomem_cloud_cells_identity_lock` | `exomem_cloud_cells_delete_lock`, `exomem_cloud_cells_truncate_lock` | | `exomem_users` | A delete | none | `exomem_users_delete_lock`, `exomem_users_truncate_lock` | | `exomem_marketplace_reviewer_credentials` | A delete | none | `exomem_marketplace_reviewer_credentials_delete_lock`, `..._truncate_lock` | @@ -807,6 +808,8 @@ Four more rules hold on the same terms: Only the schema owner and the routines that run as the schema owner may write them. The guards are `schema_releases_owner_only`, `exomem_cloud_issuance_log_owner_only` and the matching `..._owner_only_truncate` triggers. - A row in `exomem_cloud_download_tickets` cannot change. The guard is `exomem_cloud_download_tickets_update_lock`. +- An insert into `exomem_cloud_download_tickets` must name the grant of its token family. The guard `exomem_cloud_download_tickets_grant_match` + refuses any other row, and a row for a family that does not exist, for every role including the schema owner. - A truncate that cascades from another table meets the same guards. The schema owner is exempt, because it can drop any guard. The lock is stated against the select, insert, update, @@ -954,6 +957,7 @@ FROM (VALUES ('exomem_cloud_service_credentials', 'exomem_cloud_service_credentials_identity_lock'), ('exomem_oauth_clients', 'exomem_oauth_clients_identity_lock'), ('exomem_tenants', 'exomem_tenants_identity_lock'), + ('exomem_cloud_cells', 'exomem_cloud_cells_identity_lock'), ('exomem_oauth_grants', 'exomem_oauth_grants_delete_lock'), ('exomem_oauth_grants', 'exomem_oauth_grants_truncate_lock'), ('exomem_oauth_clients', 'exomem_oauth_clients_delete_lock'), @@ -966,11 +970,14 @@ FROM (VALUES ('exomem_cloud_service_credentials', 'exomem_cloud_service_credentials_truncate_lock'), ('exomem_marketplace_reviewer_credentials', 'exomem_marketplace_reviewer_credentials_delete_lock'), ('exomem_marketplace_reviewer_credentials', 'exomem_marketplace_reviewer_credentials_truncate_lock'), + ('exomem_cloud_cells', 'exomem_cloud_cells_delete_lock'), + ('exomem_cloud_cells', 'exomem_cloud_cells_truncate_lock'), ('schema_releases', 'schema_releases_owner_only'), ('schema_releases', 'schema_releases_owner_only_truncate'), ('exomem_cloud_issuance_log', 'exomem_cloud_issuance_log_owner_only'), ('exomem_cloud_issuance_log', 'exomem_cloud_issuance_log_owner_only_truncate'), ('exomem_cloud_download_tickets', 'exomem_cloud_download_tickets_update_lock'), + ('exomem_cloud_download_tickets', 'exomem_cloud_download_tickets_grant_match'), ('exomem_oauth_token_families', 'exomem_oauth_token_families_issuance_record'), ('exomem_oauth_access_tokens', 'exomem_oauth_access_tokens_issuance_record'), ('exomem_oauth_refresh_tokens', 'exomem_oauth_refresh_tokens_issuance_record'), @@ -1066,8 +1073,9 @@ statement that finds the ticket's login, so a download makes no extra database r - The web app's role may select, insert and delete ticket rows. The gateway's role reads `family_id`, `path_sha256` and `expires_at`. No role can update a row. - The reconcile job deletes up to 1000 expired rows a run, through the index on `expires_at`. A row lives one day at most. -- The row table has no foreign key. A ticket row whose insert names no real grant fails, because the recording trigger - reads the grant. +- The row table has no foreign key. A guard refuses a ticket row whose grant is not the grant of its token family, and a + row for a family that does not exist. The recording trigger reads the tenant and the user through the family's grant, + not through the row's. #### Deploy and rollback order diff --git a/migrations/0101_exomem_identity_lock_and_schema_releases.sql b/migrations/0101_exomem_identity_lock_and_schema_releases.sql index e82018ca..2003ecee 100644 --- a/migrations/0101_exomem_identity_lock_and_schema_releases.sql +++ b/migrations/0101_exomem_identity_lock_and_schema_releases.sql @@ -16,6 +16,7 @@ SET LOCAL lock_timeout = '5s'; LOCK TABLE exomem_users, exomem_tenants, + exomem_cloud_cells, exomem_marketplace_reviewer_credentials, exomem_oauth_clients, exomem_oauth_grants, @@ -39,13 +40,14 @@ LOCK TABLE -- -- The health proof qualifies every name with its schema, so it gets only -- pg_catalog and pg_temp. Every other function names schema objects without a --- schema, so it gets pg_catalog, then the schemas of this migration's own path --- that the schema owner, the bootstrap superuser (always role 10) or --- pg_database_owner owns, then pg_temp. A schema that another role created never --- enters a pin. When that filter leaves out a schema that a function needs, the --- function fails with "does not exist" on its next call, and the operator pays: --- they read the notice below, then fix the schema's owner or add a migration --- that pins the function again. +-- schema, so it gets pg_catalog, then every schema of this migration's own path, +-- then pg_temp. A schema that another role owns must never enter a pin: that role +-- could define an operator there. The schema owner, the bootstrap superuser +-- (always role 10) and pg_database_owner are the trusted owners. When the path +-- holds a schema that any other role owns, the migration raises an error that +-- names each such schema and its owner, and the transaction rolls back, so the +-- old schema keeps serving. The operator pays one failed migration job, until +-- the schema's owner is fixed or the schema leaves the migration role's path. DO $migration$ DECLARE target_schema text := current_schema(); @@ -53,19 +55,21 @@ DECLARE trusted_owners oid[] := ARRAY[ schema_owner, 10::oid, (SELECT oid FROM pg_roles WHERE rolname = 'pg_database_owner') ]; - owned_path text; - skipped_path text; + path_schemas text; + untrusted_schemas text; routine record; BEGIN - SELECT string_agg(quote_ident(path.name), ', ' ORDER BY path.position) - FILTER (WHERE namespace.nspowner = ANY (trusted_owners)), - string_agg(quote_ident(path.name), ', ' ORDER BY path.position) - FILTER (WHERE namespace.nspowner <> ALL (trusted_owners)) - INTO owned_path, skipped_path + SELECT string_agg(quote_ident(path.name), ', ' ORDER BY path.position), + string_agg( + quote_ident(path.name) || ' (owned by ' || quote_ident(pg_get_userbyid(namespace.nspowner)) || ')', + ', ' ORDER BY path.position + ) FILTER (WHERE namespace.nspowner <> ALL (trusted_owners)) + INTO path_schemas, untrusted_schemas FROM unnest(current_schemas(false)) WITH ORDINALITY AS path(name, position) JOIN pg_namespace AS namespace ON namespace.nspname = path.name; - IF skipped_path IS NOT NULL THEN - RAISE NOTICE 'search_path pins leave out schemas that another role owns: %', skipped_path; + IF untrusted_schemas IS NOT NULL THEN + RAISE EXCEPTION 'The migration path holds schemas that another role owns: %. Change the owner of each schema, or take it off the path of the migration role, and run the migration again.', + untrusted_schemas; END IF; FOR routine IN @@ -100,7 +104,7 @@ BEGIN target_schema, routine.proname, routine.arguments, CASE WHEN routine.proname = 'exomem_record_memory_health_proof' THEN 'pg_catalog, pg_temp' - ELSE 'pg_catalog, ' || coalesce(owned_path || ', ', '') || 'pg_temp' + ELSE 'pg_catalog, ' || coalesce(path_schemas || ', ', '') || 'pg_temp' END ); END LOOP; @@ -247,7 +251,7 @@ CREATE TRIGGER exomem_cloud_service_credentials_identity_lock AND NEW.revoked_by_principal_digest IS DISTINCT FROM OLD.revoked_by_principal_digest) ) EXECUTE FUNCTION exomem_refuse_unless_schema_owner(); --- Clients and tenants stay updatable except for the one identity column or two. +-- Clients, tenants and cells stay updatable except for the one identity column or two. CREATE TRIGGER exomem_oauth_clients_identity_lock AFTER UPDATE ON exomem_oauth_clients FOR EACH ROW WHEN (OLD.id IS DISTINCT FROM NEW.id OR OLD.client_id IS DISTINCT FROM NEW.client_id) @@ -258,15 +262,24 @@ CREATE TRIGGER exomem_tenants_identity_lock FOR EACH ROW WHEN (OLD.owner_user_id IS DISTINCT FROM NEW.owner_user_id) EXECUTE FUNCTION exomem_refuse_unless_schema_owner(); --- No code deletes a grant, client, tenant, user, service credential or reviewer --- credential. A truncate that cascades from another table fires the same guard. +-- The gateway reaches a cell through cell.tenant_id, so a cell row that moves to another +-- tenant sends that tenant's traffic to this cell. cell_id names the cell that cellctl runs. +CREATE TRIGGER exomem_cloud_cells_identity_lock + AFTER UPDATE ON exomem_cloud_cells + FOR EACH ROW WHEN (OLD.cell_id IS DISTINCT FROM NEW.cell_id OR OLD.tenant_id IS DISTINCT FROM NEW.tenant_id) + EXECUTE FUNCTION exomem_refuse_unless_schema_owner(); + +-- No code deletes a grant, client, tenant, user, service credential, reviewer +-- credential or cell row: a cell ends as desired_state 'deleted', and no role +-- holds delete on cells. A truncate that cascades from another table fires the same guard. DO $migration$ DECLARE locked_table text; BEGIN FOREACH locked_table IN ARRAY ARRAY[ 'exomem_oauth_grants', 'exomem_oauth_clients', 'exomem_tenants', 'exomem_users', - 'exomem_cloud_service_credentials', 'exomem_marketplace_reviewer_credentials' + 'exomem_cloud_service_credentials', 'exomem_marketplace_reviewer_credentials', + 'exomem_cloud_cells' ] LOOP EXECUTE format( 'CREATE TRIGGER %I AFTER DELETE ON %I FOR EACH ROW EXECUTE FUNCTION exomem_refuse_unless_schema_owner()', diff --git a/migrations/0102_exomem_issuance_log_and_download_tickets.sql b/migrations/0102_exomem_issuance_log_and_download_tickets.sql index a8f0ad96..984919c4 100644 --- a/migrations/0102_exomem_issuance_log_and_download_tickets.sql +++ b/migrations/0102_exomem_issuance_log_and_download_tickets.sql @@ -62,7 +62,9 @@ CREATE TRIGGER exomem_cloud_issuance_log_owner_only_truncate -- A download ticket is a signed message, and no row backed it. The web app now -- stores one row for each ticket, and the gateway requires it. A row lives at -- most one day. No foreign key: the gateway joins the token family when it --- uses the ticket, and the recording function reads the row's grant. +-- uses the ticket. The grant column is not read by the gateway. The guard below +-- ties it to the token family's grant, and the recording function reads the +-- tenant and the user through the family, so the row's own claim decides nothing. CREATE TABLE exomem_cloud_download_tickets ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), family_id uuid NOT NULL, @@ -116,9 +118,10 @@ DECLARE target_schema text := current_schema(); BEGIN -- TG_ARGV[0] is the credential kind. The function reads only what the row does - -- not name: a refresh token's grant through its token family, a tenant and a - -- user through the grant, a service credential's owner through its tenant. - -- Any missing row raises, so the credential insert fails closed. + -- not name: a refresh token's or a download ticket's grant through its token + -- family, a tenant and a user through the grant, a service credential's owner + -- through its tenant. A ticket row also names a grant, but the record takes + -- the family's. Any missing row raises, so the credential insert fails closed. EXECUTE format($definition$ CREATE FUNCTION %1$I.exomem_record_issuance() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp @@ -138,12 +141,10 @@ BEGIN ELSIF kind = 'access_token' THEN the_grant := NEW.grant_id; the_family := NEW.family_id; the_client := NEW.client_id; the_expiry := NEW.expires_at; - ELSIF kind = 'refresh_token' THEN + ELSIF kind IN ('refresh_token', 'download_ticket') THEN SELECT family.grant_id, family.client_id INTO the_grant, the_client FROM %1$I.exomem_oauth_token_families AS family WHERE family.id = NEW.family_id; the_family := NEW.family_id; the_expiry := NEW.expires_at; - ELSIF kind = 'download_ticket' THEN - the_grant := NEW.grant_id; the_family := NEW.family_id; the_expiry := NEW.expires_at; ELSIF kind = 'service_credential' THEN the_tenant := NEW.tenant_id; END IF; @@ -173,6 +174,32 @@ BEGIN $body$; $definition$, target_schema); + -- The ticket guard. A ticket row must name the grant that its token family + -- belongs to. The gateway admits a ticket on the family, the path digest and + -- the expiry, so without this a role that can insert a row names another + -- tenant's family with a grant of its own, and the gateway admits it. + -- It runs as the schema owner so that it reads the family whatever the + -- inserting role may select. A family that does not exist refuses the row too. + -- A web request inserts the grant that it read from the family, so a flow + -- never meets the refusal, except when the family has gone since the ticket was signed. + EXECUTE format($definition$ + CREATE FUNCTION %1$I.exomem_refuse_ticket_grant_mismatch() RETURNS trigger + LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp + AS $body$ + BEGIN + IF NOT EXISTS ( + SELECT 1 FROM %1$I.exomem_oauth_token_families AS family + WHERE family.id = NEW.family_id AND family.grant_id = NEW.grant_id + ) THEN + -- %%: the format() call around this body reads each single percent sign as a placeholder. + RAISE EXCEPTION 'EXOMEM_ROW_LOCKED: insert on %% names a grant that its token family does not have', + TG_TABLE_NAME USING ERRCODE = '42501'; + END IF; + RETURN NULL; + END; + $body$; + $definition$, target_schema); + -- A record is kept until 90 days after its credential expires. The 90 days -- is a constant here, not a setting: changing it takes a migration. A record -- whose credential has no expiry never matches. One call deletes at most @@ -204,6 +231,7 @@ BEGIN -- app's role execute on the prune function only. EXECUTE format('REVOKE ALL ON FUNCTION %I.exomem_record_issuance() FROM PUBLIC', target_schema); EXECUTE format('REVOKE ALL ON FUNCTION %I.exomem_prune_issuance_log() FROM PUBLIC', target_schema); + EXECUTE format('REVOKE ALL ON FUNCTION %I.exomem_refuse_ticket_grant_mismatch() FROM PUBLIC', target_schema); END; $migration$; @@ -226,6 +254,12 @@ CREATE TRIGGER exomem_cloud_download_tickets_issuance_record AFTER INSERT ON exomem_cloud_download_tickets FOR EACH ROW EXECUTE FUNCTION exomem_record_issuance('download_ticket'); +-- The ticket guard is an AFTER row trigger like the others, so it judges the stored row. +-- Both triggers fire on every insert, in the order of their names; either one fails the insert. +CREATE TRIGGER exomem_cloud_download_tickets_grant_match + AFTER INSERT ON exomem_cloud_download_tickets + FOR EACH ROW EXECUTE FUNCTION exomem_refuse_ticket_grant_mismatch(); + -- One backfilled record for each credential row that exists. It runs after the -- triggers exist and inside the transaction that holds the locks, so no row can -- land between the two steps without a record. The ticket table is new and empty. diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md index a84ec1d6..73dcaef0 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md @@ -66,6 +66,7 @@ The grants script gives the web app's role these rights on every run: | `exomem_cloud_service_credentials` | `revoked_at`, `revoked_by_principal_digest` | both | removed | | `exomem_oauth_clients` | every column except `id` and `client_id` | none | removed | | `exomem_tenants` | every column except `owner_user_id` | none | removed | +| `exomem_cloud_cells` | `desired_state`, `desired_image`, `storage_gib`, `cancellation_notice_sent_at`, `deletion_grant`; the grants script already gives exactly these | none | never held | | `exomem_users` | every column | none | removed | | `exomem_marketplace_reviewer_credentials` | every column | none | removed | @@ -77,9 +78,9 @@ Column rights are the first control, because the database enforces them before a **Guards.** A guard is a trigger that refuses a statement unless the schema owner runs it. Guards do not depend on the grants script. They do three jobs: -- **Fixed columns.** On a column-locked table, a guard refuses a change to any fixed column. On clients and tenants, it refuses a change to the columns that the table above excepts. +- **Fixed columns.** On a column-locked table, a guard refuses a change to any fixed column. On clients and tenants, it refuses a change to the columns that the table above excepts. On cells, it refuses a change to `cell_id` or `tenant_id`, because the gateway reaches a cell through its tenant. - **One-way columns.** A guard refuses a change to a revocation or consumption value that is already set. Every revocation statement today either keeps the old value or filters on an empty one. -- **Deletes.** On every table whose delete the table above removes, a guard refuses a delete and a truncate. A truncate that cascades from another table meets the same guard. +- **Deletes.** On every table whose delete the table above removes or never held, a guard refuses a delete and a truncate. No flow deletes a cell row: a cell ends as `desired_state = 'deleted'`, and no role holds delete on cells. A truncate that cascades from another table meets the same guard. Every guard calls one function, built this way: @@ -105,7 +106,7 @@ One generic guard that compares every column outside an allow-list was weighed. **The schema owner is exempt** for two reasons. Its repairs, its test fixtures and its cascades must work: deleting a user removes that user's grants. It can also drop any trigger, so a guard against it would prevent nothing. -The body of a `SECURITY DEFINER` function that the schema owner owns runs as the schema owner, so its statements pass every guard. Each such function is part of the lock. The schema has one today (Context), and it writes none of these tables. This change adds two, in D5 and D6. A test pins the full set. When the test fires wrongly, a migration that adds a legitimate definer function fails CI until its author adds the function to the set. The author pays one line, in review, and nothing reaches production. +The body of a `SECURITY DEFINER` function that the schema owner owns runs as the schema owner, so its statements pass every guard. Each such function is part of the lock. The schema has one today (Context), and it writes none of these tables. This change adds three: the recording function and the ticket guard function (D5, D8) and the prune function (D6). A test pins the full set. When the test fires wrongly, a migration that adds a legitimate definer function fails CI until its author adds the function to the set. The author pays one line, in review, and nothing reaches production. **The trigger right.** A trigger that a role attaches to a table runs inside every statement that touches the table. When that statement is a foreign-key action, or belongs to a definer function, a `BEFORE` trigger's code runs as the schema owner. So does every statement that the code runs. The trigger's function can live in the role's temporary schema. So a role that holds the trigger right on one table of the schema can run its own code as the schema owner. No guard holds against that. @@ -121,7 +122,7 @@ An event trigger that refuses `CREATE TRIGGER` to other roles would hold without - The first migration pins `search_path` on every function that the database can run as the schema owner for another role. These are the schema owner's trigger functions and `SECURITY DEFINER` functions in the schema, and each SQL or PL/pgSQL function in the schema that a constraint, a column default or an index calls. The set holds only functions that the schema owner owns and that belong to no extension: a C or internal function looks up no names, and the schema owner cannot alter an extension's functions. A function that one of them calls runs under its caller's path. - A function that qualifies every name gets `pg_catalog, pg_temp`. That covers the health proof and every function of this change. - - Every other one gets `pg_catalog`, then those schemas of the migration's own path that the schema owner, the bootstrap superuser or `pg_database_owner` owns, then `pg_temp`. On PostgreSQL 15 and later `public` belongs to `pg_database_owner`, which stands for the database's owner. A schema that another role created therefore never enters a pin. Its body names schema objects without a schema, and one calls `pgcrypto` in `public`. Production's path is `public`; a test's is its own schema, then `public`. Each body therefore resolves as it does today, except that a temporary table can no longer shadow a table. When the owner filter fires wrongly, because it leaves out a schema that a function needs, that function fails with a missing-object error on its next call. The operator pays: the migration prints the left-out schemas as a notice, and the repair is a reviewed change of the schema's owner or one more migration that pins the function again. + - Every other one gets `pg_catalog`, then every schema of the migration's own path, then `pg_temp`. Each of these bodies names schema objects without a schema, and one calls `pgcrypto` in `public`. Production's path is `public`; a test's is its own schema, then `public`. Each body therefore resolves as it does today, except that a temporary table can no longer shadow a table. A schema that another role owns would put that role's operators into a pin. The migration therefore checks each schema of its path first. The schema owner, the bootstrap superuser or `pg_database_owner` must own it. On PostgreSQL 15 and later `public` belongs to `pg_database_owner`, which stands for the database's owner. When the check fires wrongly, because the owner of a schema on the path is harmless, the migration raises an error that names each such schema and its owner, and it rolls back. The old schema keeps serving. The operator pays one failed migration job, until the schema's owner is changed or the schema leaves the migration role's path. - A test reads the catalog: each of those functions pins a path that starts with `pg_catalog` and ends with `pg_temp`. When the test fires wrongly, a migration that adds such a function fails CI until its author adds one `SET` clause. The author pays, and nothing reaches production. - The pinned path never names a schema that the role created, so the pin alone closes that route. It cannot close the route through a schema that the path names. The create right on the database also lets a role create a schema named after the schema owner, which the default path `"$user", public` searches first in the owner's own sessions. The rollout and the runbook's checks therefore read that no role other than a superuser, the schema owner or `pg_database_owner` holds a create right on the database or on a schema outside `pg_catalog` and `information_schema`, directly or through a membership, and list each schema that another role owns. Superusers hold every right, and each schema's owner holds the create right on it, so the read leaves those out. @@ -162,6 +163,8 @@ The existing test suites set up fixtures as the role that owns the schema, so th Two existing options were checked first. `exomem_audit_events` exists and has no writer. It describes operations, with an outcome and size buckets, and has no column for a credential, grant, token family or user. Its two indexes would also add work to every token insert. The `pgaudit` extension writes statements to the server's log file. That needs server-level installation, and a reader cannot query the file beside the rows it describes. A table with a trigger is the smaller mechanism. +A third option was weighed and rejected for this change: recording at the gateway on each admission, a use log. It puts a write and a de-duplication on the gateway's hot path for every request. The issuance log and the ticket-row requirement already close the paths that this change targets. A use log is a later step for limit 9, which says that the log does not record use. + One table, `exomem_cloud_issuance_log`, holds one record for each credential insert: | Column | Meaning | @@ -194,9 +197,9 @@ Other points: **What the migrations lock.** Creating a trigger locks its table against inserts, updates and deletes until the commit. Reads continue, the gateway's lookups included. The change ships two migrations, so that the longer one locks fewer tables: -- The first adds `schema_releases` and the guards, and pins the functions' paths. It locks users, tenants, reviewer credentials, clients, grants, token families, refresh tokens, access tokens and service credentials. It changes only the catalog, so it commits soon after it holds the last lock. +- The first adds `schema_releases` and the guards, and pins the functions' paths. It locks users, tenants, cells, reviewer credentials, clients, grants, token families, refresh tokens, access tokens and service credentials. It changes only the catalog, so it commits soon after it holds the last lock. - The second adds the log, the ticket table, the recording triggers and the records for existing rows. It locks token families, refresh tokens, access tokens and service credentials until it has written those records. Code exchange, refresh, the Home mint, token revocation, service credential requests and the maintenance wait for it. Its length grows with the count of live credential rows. -- Each migration takes all its locks first, with one `LOCK TABLE` statement in the mode that creating a trigger takes. PostgreSQL takes them one at a time, in the order listed above. Admission writes users before tenants, and every revocation and issuance writes grants, then token families, then tokens, in that order. Two flows write in another order: cell deletion writes the OAuth tables, then tenants, then users, and deletion finish writes tenants before users. Either can deadlock with the first migration, and PostgreSQL then fails one of the two transactions. The reconcile job runs both flows every minute (`ops/exomem-hosted-schedules.json`), so a failed deletion step runs again a minute later. A deadlock fails the migration's job like a lock timeout does, and the operator starts the job again. +- Each migration takes all its locks first, with one `LOCK TABLE` statement in the mode that creating a trigger takes. PostgreSQL takes them one at a time, in the order listed above. Admission writes users before tenants, and every revocation and issuance writes grants, then token families, then tokens, in that order. Three flows write in another order: cell deletion writes the OAuth tables, then tenants, then users, deletion finish writes tenants before users, and the lifecycle sweep writes a cell before its tenant. Any of them can deadlock with the first migration, and PostgreSQL then fails one of the two transactions. The reconcile job runs both flows every minute (`ops/exomem-hosted-schedules.json`), so a failed deletion step runs again a minute later. A deadlock fails the migration's job like a lock timeout does, and the operator starts the job again. - Each migration sets a lock timeout of five seconds. Without one, its lock request would wait behind any long transaction, and every later write would wait behind the request. The timeout bounds each wait, not the migration. While the migration waits for one lock, it holds every lock that it took before, and new writes to the table it waits for queue behind its request. In the worst case, a write to users waits through all nine waits of the first migration, about 45 seconds, before that migration commits or fails. When a wait times out, the migration fails, the job fails, and a later run tries again. - If the second migration fails, the guards are in force without the log. No flow depends on the log, and a later run adds it. @@ -257,7 +260,7 @@ The web app now stores one row for each ticket in `exomem_cloud_download_tickets - **Key.** A unique key covers the token family, the path digest and the expiry. The web app inserts with `ON CONFLICT DO NOTHING`. Two tickets with the same three values carry the same authority and share one row and one record. - **Rights.** The web app's role holds select, insert and delete. The gateway's role holds select. A guard refuses every update unless the schema owner runs it. -- **No foreign key.** A row lives at most one day, and the gateway joins the token family when the ticket is used. The recording function reads the row's grant, so an insert that names no real grant fails. +- **No foreign key.** A row lives at most one day, and the gateway joins the token family when the ticket is used. A guard on insert refuses a row whose grant is not the grant of its token family, and a row for a family that does not exist. The gateway matches a ticket on the family, the path digest and the expiry, so without that guard a role that can insert names another tenant's family with a grant of its own, and the gateway admits the ticket. The guard function is `SECURITY DEFINER`, so it reads the family whatever the inserting role may select, and it pins its path like the recording function. The recording function reads the tenant and the user through the family's grant, not through the row's. When the guard fires wrongly, an insert fails for a family that vanished since the ticket was signed, and the owner asks for the download again. - **Prune.** The scheduled maintenance deletes a bounded batch of expired rows, through an index on the expiry. The gateway checks the signature as today and then requires the matching unexpired row. The check is one more condition in the statement that already resolves the ticket's login. A media request therefore makes no extra round trip, and each byte-range request costs one more index probe. A test counts the statements of a download request before and after. diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-gateway/spec.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-gateway/spec.md index 745594b9..4269fe3a 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-gateway/spec.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-gateway/spec.md @@ -2,7 +2,7 @@ ### Requirement: The gateway admits a download ticket only with its stored row -The web app SHALL store one row for each download ticket that it signs. The row SHALL name the ticket's token family, grant, path digest and expiry. The gateway SHALL refuse a ticket that has no matching unexpired row, whatever its signature says. The database SHALL refuse every update of a ticket row that the schema owner does not run. Every ticket row insert SHALL write an issuance record. +The web app SHALL store one row for each download ticket that it signs. The row SHALL name the ticket's token family, grant, path digest and expiry. The gateway SHALL refuse a ticket that has no matching unexpired row, whatever its signature says. The database SHALL refuse every update of a ticket row that the schema owner does not run, and every insert of a row whose grant is not its token family's grant. Every ticket row insert SHALL write an issuance record. #### Scenario: A signed ticket has no row @@ -31,10 +31,15 @@ The web app SHALL store one row for each download ticket that it signs. The row - **WHEN** the web app signs a second ticket with the same token family, path digest and expiry - **THEN** the two tickets share one row and one issuance record +#### Scenario: A ticket row names another tenant's family with the inserting role's own grant + +- **WHEN** the web app's role inserts a ticket row with another tenant's token family and a grant of its own +- **THEN** the database refuses the insert and no row exists for the gateway to match + #### Scenario: A ticket row is inserted - **WHEN** the web app stores a ticket row -- **THEN** the issuance log gains one record that names the row, its grant, token family, tenant, user and expiry +- **THEN** the issuance log gains one record that names the row, its token family, the family's grant, and the tenant, user and expiry that follow from that grant - **AND** the record holds no path and no path digest #### Scenario: The row check adds no round trip diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md index deafbe35..8c2d352a 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md @@ -2,7 +2,12 @@ ### Requirement: OAuth identity fields are unchangeable once written -This requirement binds every role except the schema owner. The database SHALL refuse every change to an identity field of an OAuth grant, token family, access token, refresh token or client, and to a tenant's owner. It SHALL let a revocation time and a consumption time change only from empty to a time. It SHALL refuse a delete of a grant, client, tenant, user or reviewer credential. Each refusal SHALL hold whatever select, insert, update, delete and truncate rights the role holds. +This requirement binds every role except the schema owner. The database SHALL refuse every change to an identity field of an OAuth grant, token family, access token, refresh token or client, to a tenant's owner, and to a cell's identifier or tenant. It SHALL let a revocation time and a consumption time change only from empty to a time. It SHALL refuse a delete of a grant, client, tenant, user, reviewer credential or cell. Each refusal SHALL hold whatever table rights the role holds. + +#### Scenario: A cell is re-pointed + +- **WHEN** the web app's role changes a cell's tenant or identifier, or deletes a cell row +- **THEN** the database refuses the statement and the cell row is unchanged #### Scenario: A grant is re-pointed diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md index 0ea9e1f8..a4d2ca35 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md @@ -1,6 +1,6 @@ Groups 1 to 6 are one implementation PR. Group 7 is the live rollout, and every step in it is the operator's. The change ships two migrations, which take the -next free numbers: 0100 and 0101 at the time of writing. The first holds +next free numbers: 0101 and 0102 at the time of writing. The first holds `schema_releases` and the guards. The second holds the log, the ticket table, the recording triggers and the records for existing rows (D5). `design.md` names each decision as D1 to D12. @@ -51,8 +51,10 @@ names each decision as D1 to D12. - [x] 2.1 In the first migration, add the guard function and the triggers of D2. Fixed and one-way columns get an `AFTER UPDATE` row trigger with a `WHEN` clause. Deletes get an `AFTER DELETE` row trigger and a `BEFORE TRUNCATE` - trigger. Build the guard function by D2's rules and revoke its execute right - from `PUBLIC`. Change no rule of the three guards that exist today. Verify: + trigger. Guard `exomem_cloud_cells` as well: an `AFTER UPDATE` row trigger on + `cell_id` and `tenant_id`, and the delete and truncate triggers. Build the + guard function by D2's rules and revoke its execute right from `PUBLIC`. + Change no rule of the three guards that exist today. Verify: tasks 5.1 and 5.2. - [x] 2.2 In `scripts/exomem-cloud-grants.sql`, add the lock's section after the schema-wide grant. It revokes update and delete on the D2 tables from the @@ -76,10 +78,13 @@ names each decision as D1 to D12. the schema owner owns and that belong to no extension. Read the set from the catalog. Give a function that qualifies every name `pg_catalog, pg_temp`. Give every other one - `pg_catalog`, then those schemas of `current_schemas(false)` that the schema - owner, the bootstrap superuser or `pg_database_owner` owns, then `pg_temp`. - Every function of this change pins its path at creation. Verify: task 5.6, - and every existing PostgreSQL suite passes with the pins in place. + `pg_catalog`, then every schema of `current_schemas(false)`, then `pg_temp`. + Raise an error that names each schema of that path which the schema owner, + the bootstrap superuser and `pg_database_owner` do not own, so the migration + fails and the old schema keeps serving. Every function of this change pins + its path at creation. Verify: task 5.6, a migration that fails on a schema + of another owner and applies on the same database without it, and every + existing PostgreSQL suite passes with the pins in place. ## 3. Issuance log (D5, D6, D12) @@ -110,9 +115,12 @@ names each decision as D1 to D12. - [x] 4.1 In the second migration, create `exomem_cloud_download_tickets` with its unique key, its expiry index, its update guard and its recording trigger. In the grants script, give the web app's role select, insert and - delete, and the gateway's role select. Verify: as the web app's role, an - update of a ticket row is refused, also after a grant of update on the - table. + delete, and the gateway's role select. Add a guard on insert that refuses a + row whose grant is not its token family's grant, and have the recording + trigger read the tenant and the user through the family's grant. Verify: as + the web app's role, an update of a ticket row is refused, also after a grant + of update on the table, and so is a row that names another tenant's family + with the role's own grant. - [x] 4.2 In the download handler, store the ticket's row before the redirect answer, with `ON CONFLICT DO NOTHING`. In the scheduled maintenance, delete a bounded batch of expired ticket rows. Verify: a download request leaves @@ -136,8 +144,9 @@ without truncate. Neither state holds the trigger right. token's digest and a refresh token's digest. Extend an expiry. Change a reviewer reference. Clear a revocation time and a consumption time. Re-point a service credential's tenant and overwrite its digest. Change a tenant's - owner and a client's identifier. Delete and truncate grants, clients, - tenants, users, service credentials and reviewer credentials. Truncate a + owner and a client's identifier. Re-point a cell to another tenant and + rename a cell. Delete and truncate grants, clients, tenants, users, cells, + service credentials and reviewer credentials. Truncate a table that one of them references, with `CASCADE`. Create a trigger on a guarded table. Then create temporary tables that carry the names of the guarded tables, the log and the grant table, and run the list again. diff --git a/scripts/exomem-cloud-grants.sql b/scripts/exomem-cloud-grants.sql index 19fcf28e..46318679 100644 --- a/scripts/exomem-cloud-grants.sql +++ b/scripts/exomem-cloud-grants.sql @@ -243,6 +243,9 @@ BEGIN IF to_regprocedure('exomem_record_issuance()') IS NOT NULL THEN REVOKE ALL ON FUNCTION exomem_record_issuance() FROM PUBLIC; END IF; + IF to_regprocedure('exomem_refuse_ticket_grant_mismatch()') IS NOT NULL THEN + REVOKE ALL ON FUNCTION exomem_refuse_ticket_grant_mismatch() FROM PUBLIC; + END IF; IF to_regprocedure('exomem_prune_issuance_log()') IS NOT NULL THEN REVOKE ALL ON FUNCTION exomem_prune_issuance_log() FROM PUBLIC; IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'substrate_app') THEN @@ -257,6 +260,9 @@ BEGIN IF to_regprocedure('exomem_record_issuance()') IS NOT NULL THEN EXECUTE format('REVOKE ALL ON FUNCTION exomem_record_issuance() FROM %I', lock_role); END IF; + IF to_regprocedure('exomem_refuse_ticket_grant_mismatch()') IS NOT NULL THEN + EXECUTE format('REVOKE ALL ON FUNCTION exomem_refuse_ticket_grant_mismatch() FROM %I', lock_role); + END IF; IF lock_role <> 'substrate_app' AND to_regprocedure('exomem_prune_issuance_log()') IS NOT NULL THEN EXECUTE format('REVOKE ALL ON FUNCTION exomem_prune_issuance_log() FROM %I', lock_role); END IF; diff --git a/src/lib/exomem-hosted/__tests__/cloud-grants-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-grants-postgres.integration.test.ts index 1335da48..96b720ea 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-grants-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-grants-postgres.integration.test.ts @@ -1978,13 +1978,18 @@ describe("Exomem Cloud grants PostgreSQL integration", { skip: !databaseUrl }, ( assert.deepEqual(await holders(), [], "a grants run takes the right back"); }); - it("runs with owner rights in exactly three functions, and lets only the web app's role call the prune", async () => { + it("runs with owner rights in exactly four functions, and lets only the web app's role call the prune", async () => { const definers = await ownerPool!.query<{ proname: string }>( `SELECT proname FROM pg_proc WHERE pronamespace = current_schema()::regnamespace AND prosecdef ORDER BY proname` ); assert.deepEqual( definers.rows.map((row) => row.proname), - ["exomem_prune_issuance_log", "exomem_record_issuance", "exomem_record_memory_health_proof"] + [ + "exomem_prune_issuance_log", + "exomem_record_issuance", + "exomem_record_memory_health_proof", + "exomem_refuse_ticket_grant_mismatch", + ] ); const executors = await ownerPool!.query<{ proname: string; grantee: string }>( `SELECT proc.proname, CASE acl.grantee WHEN 0 THEN 'PUBLIC' ELSE pg_get_userbyid(acl.grantee)::text END AS grantee @@ -1994,7 +1999,7 @@ describe("Exomem Cloud grants PostgreSQL integration", { skip: !databaseUrl }, ( ORDER BY 1, 2`, [[ "exomem_prune_issuance_log", "exomem_record_issuance", "exomem_record_memory_health_proof", - "exomem_refuse_unless_schema_owner", + "exomem_refuse_ticket_grant_mismatch", "exomem_refuse_unless_schema_owner", ]] ); assert.equal( @@ -2007,9 +2012,11 @@ describe("Exomem Cloud grants PostgreSQL integration", { skip: !databaseUrl }, ( [{ proname: "exomem_prune_issuance_log", grantee: "substrate_app" }] ); assert.deepEqual( - executors.rows.filter((row) => ["exomem_record_issuance", "exomem_refuse_unless_schema_owner"].includes(row.proname)), + executors.rows.filter((row) => + ["exomem_record_issuance", "exomem_refuse_ticket_grant_mismatch", "exomem_refuse_unless_schema_owner"].includes(row.proname) + ), [], - "no role but the owner executes the recording function or the guard function" + "no role but the owner executes the recording function or a guard function" ); }); @@ -2056,7 +2063,12 @@ describe("Exomem Cloud grants PostgreSQL integration", { skip: !databaseUrl }, ( assert.equal(path.at(-1), "pg_temp", `${row.proname} ends its search path with pg_temp`); assert.deepEqual(row.untrusted, [], `${row.proname} names a schema that an untrusted role owns`); } - for (const name of ["exomem_refuse_unless_schema_owner", "exomem_record_issuance", "exomem_prune_issuance_log"]) { + for (const name of [ + "exomem_refuse_unless_schema_owner", + "exomem_refuse_ticket_grant_mismatch", + "exomem_record_issuance", + "exomem_prune_issuance_log", + ]) { assert.ok(pinned.rows.some((row) => row.proname === name), `${name} is in the set`); } }); diff --git a/src/lib/exomem-hosted/__tests__/cloud-identity-lock-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-identity-lock-postgres.integration.test.ts index 78bca1ec..df9d16f1 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-identity-lock-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-identity-lock-postgres.integration.test.ts @@ -2,8 +2,11 @@ import assert from "node:assert/strict"; import { randomBytes, randomUUID } from "node:crypto"; import { after, before, describe, it } from "node:test"; import type { Pool, PoolClient } from "pg"; +import { applyMigrations } from "../../../../scripts/migrate"; import { createLockFixture, + randomCellId, + seedCell, seedClient, seedWorld, tableSnapshot, @@ -38,6 +41,8 @@ type Victims = { serviceCredentialId: string; reviewerCredentialId: string; ticketId: string; + /** A cell row of the first world's tenant that nothing else references. */ + cellId: string; }; /** Rows that nothing references, so a refusal can only come from the lock and not from a foreign key. */ @@ -85,6 +90,7 @@ async function seedVictims(fx: LockFixture, world: World): Promise { VALUES ($1, $2, $3, now() + interval '15 minutes') RETURNING id`, [world.familyId, world.grantId, "0".repeat(64)] ); + const cellId = await seedCell(fx.owner, world.tenantId); return { grantId, clientId, @@ -93,6 +99,7 @@ async function seedVictims(fx: LockFixture, world: World): Promise { serviceCredentialId, reviewerCredentialId, ticketId, + cellId, }; } @@ -108,6 +115,7 @@ function attackList(fx: LockFixture, a: World, b: World, v: Victims): Attack[] { const users = q("exomem_users"); const reviewers = q("exomem_marketplace_reviewer_credentials"); const tickets = q("exomem_cloud_download_tickets"); + const cells = q("exomem_cloud_cells"); const attacks: Attack[] = [ { name: "re-point a grant's tenant and user by update", @@ -231,6 +239,21 @@ function attackList(fx: LockFixture, a: World, b: World, v: Victims): Attack[] { params: [a.clientId], guard: true, }, + { + // The gateway reaches a cell through its tenant. The victim tenant has no cell, so no unique index answers first. + name: "re-point a cell to another tenant", + table: cells, + text: `UPDATE ${cells} SET tenant_id = $2 WHERE cell_id = $1`, + params: [v.cellId, v.tenantId], + guard: true, + }, + { + name: "rename a cell", + table: cells, + text: `UPDATE ${cells} SET cell_id = $2 WHERE cell_id = $1`, + params: [v.cellId, randomCellId()], + guard: true, + }, { name: "update a download ticket row", table: tickets, @@ -263,6 +286,20 @@ function attackList(fx: LockFixture, a: World, b: World, v: Victims): Attack[] { guard: true, }); } + // A cell row ends as desired_state 'deleted'; no flow deletes the row. + attacks.push({ + name: "delete a cell", + table: cells, + text: `DELETE FROM ${cells} WHERE cell_id = $1`, + params: [v.cellId], + guard: true, + }); + attacks.push({ + name: "truncate the cell table with CASCADE", + table: cells, + text: `TRUNCATE ${cells} CASCADE`, + guard: true, + }); // A cascade from a table that a guarded table references reaches the guarded table's truncate guard. for (const referenced of [ "exomem_oauth_authorization_transactions", @@ -307,6 +344,7 @@ const TABLES_UNDER_ATTACK = [ "exomem_users", "exomem_marketplace_reviewer_credentials", "exomem_cloud_download_tickets", + "exomem_cloud_cells", ]; const STATES: LockState[] = ["narrow", "wide"]; @@ -501,6 +539,96 @@ for (const state of STATES) { } ); + it("refuses a ticket row that names another tenant's family with the web app's own grant; with the guard off the gateway admits it and the record names the victim", async () => { + const tickets = fx.q("exomem_cloud_download_tickets"); + const insert = `INSERT INTO ${tickets} (family_id, grant_id, path_sha256, expires_at) + VALUES ($1, $2, $3, now() + interval '15 minutes') RETURNING id`; + // The gateway looks a ticket up by its family, path digest and expiry; it never reads the grant. + const gatewayFinds = async (path: string) => + ( + await fx.gateway.query<{ count: number }>( + `SELECT count(*)::int AS count FROM ${tickets} WHERE family_id = $1 AND path_sha256 = $2`, + [b.familyId, path] + ) + ).rows[0]!.count; + + const refusedPath = randomBytes(32).toString("hex"); + await assert.rejects( + fx.app.query(insert, [b.familyId, a.grantId, refusedPath]), + (error: Error & { code?: string }) => + error.code === "42501" && error.message.includes(LOCKED) + ); + assert.equal(await gatewayFinds(refusedPath), 0, "no row for the gateway to find"); + + // Control: with the guard off, the same insert goes through and the gateway finds the row. + // The record takes the tenant and the user from the family's grant, not from the row's. + const controlPath = randomBytes(32).toString("hex"); + const guard = "exomem_cloud_download_tickets_grant_match"; + await fx.owner.query(`ALTER TABLE ${tickets} DISABLE TRIGGER ${guard}`); + try { + const inserted = await fx.app.query<{ id: string }>(insert, [ + b.familyId, + a.grantId, + controlPath, + ]); + assert.equal( + await gatewayFinds(controlPath), + 1, + "the control row is found by the gateway" + ); + const record = await fx.owner.query( + `SELECT tenant_id, user_id, grant_id, database_role FROM ${fx.q("exomem_cloud_issuance_log")} + WHERE credential_kind = 'download_ticket' AND credential_id = $1`, + [inserted.rows[0]!.id] + ); + assert.deepEqual(record.rows, [ + { + tenant_id: b.tenantId, + user_id: b.userId, + grant_id: b.grantId, + database_role: "substrate_app", + }, + ]); + } finally { + await fx.owner.query(`ALTER TABLE ${tickets} ENABLE TRIGGER ${guard}`); + await fx.owner.query(`DELETE FROM ${tickets} WHERE path_sha256 = $1`, [controlPath]); + } + }); + + // In the narrow state the role holds no update right on a cell's tenant, so the grants script refuses first. + it( + "moves a cell to another tenant only when its guard is off, and the gateway then finds it under that tenant", + { skip: state === "narrow" }, + async () => { + const cells = fx.q("exomem_cloud_cells"); + const move = `UPDATE ${cells} SET tenant_id = $2 WHERE cell_id = $1`; + await assert.rejects( + fx.app.query(move, [victims.cellId, victims.tenantId]), + (error: Error) => error.message.includes(LOCKED) + ); + const guard = "exomem_cloud_cells_identity_lock"; + await fx.owner.query(`ALTER TABLE ${cells} DISABLE TRIGGER ${guard}`); + try { + await fx.app.query(move, [victims.cellId, victims.tenantId]); + const found = await fx.gateway.query<{ cell_id: string }>( + `SELECT cell_id FROM ${cells} WHERE tenant_id = $1 AND desired_state <> 'deleted'`, + [victims.tenantId] + ); + assert.deepEqual( + found.rows, + [{ cell_id: victims.cellId }], + "the control move reached the gateway's lookup" + ); + } finally { + await fx.owner.query(`ALTER TABLE ${cells} ENABLE TRIGGER ${guard}`); + await fx.owner.query(`UPDATE ${cells} SET tenant_id = $2 WHERE cell_id = $1`, [ + victims.cellId, + a.tenantId, + ]); + } + } + ); + it("still lets the legitimate foreign-key actions run: a deleted transaction that a grant names, and a family with tokens", async () => { const world = await seedWorld(fx.owner); const transaction = await fx.owner.query<{ id: string }>( @@ -582,3 +710,46 @@ for (const state of STATES) { } ); } + +describe("The migration that pins search paths", { skip: !databaseUrl }, () => { + let fx: LockFixture; + const NO_GRANTS = "/nonexistent/exomem-cloud-grants.sql"; + + before(async () => { + fx = await createLockFixture("narrow", { migrate: false }); + }); + + after(async () => { + await fx?.close(); + }); + + it("fails and applies nothing when the path holds a schema that another role owns, and names it with its owner", async () => { + const rogue = `rogue_${randomUUID().replaceAll("-", "")}`; + await fx.admin.query(`CREATE SCHEMA "${rogue}" AUTHORIZATION substrate_app`); + // PostgreSQL leaves a schema off a role's effective path unless the role holds usage on it, + // so the owner of the schema grants it, as an attacker would to make the schema resolve. + await fx.admin.query(`GRANT USAGE ON SCHEMA "${rogue}" TO substrate_owner`); + try { + const url = new URL(fx.roleUrl("substrate_owner")); + url.searchParams.set("options", `-c search_path=${fx.schema},${rogue},public`); + await assert.rejects( + applyMigrations({ databaseUrl: url.toString(), grantsFile: NO_GRANTS }), + (error: Error) => + error.message.includes(rogue) && error.message.includes("owned by substrate_app") + ); + const tables = await fx.owner.query<{ releases: string | null }>( + "SELECT to_regclass('schema_releases') AS releases" + ); + assert.equal(tables.rows[0]!.releases, null, "the migration rolled back"); + + // Control: the same database migrates once the schema is off the path. + await applyMigrations({ databaseUrl: fx.roleUrl("substrate_owner"), grantsFile: NO_GRANTS }); + const applied = await fx.owner.query<{ releases: string | null }>( + "SELECT to_regclass('schema_releases') AS releases" + ); + assert.notEqual(applied.rows[0]!.releases, null); + } finally { + await fx.admin.query(`DROP SCHEMA IF EXISTS "${rogue}" CASCADE`); + } + }); +}); diff --git a/src/lib/exomem-hosted/__tests__/identity-lock-fixture.ts b/src/lib/exomem-hosted/__tests__/identity-lock-fixture.ts index 31921e9c..06168d0c 100644 --- a/src/lib/exomem-hosted/__tests__/identity-lock-fixture.ts +++ b/src/lib/exomem-hosted/__tests__/identity-lock-fixture.ts @@ -209,6 +209,23 @@ export async function seedWorld(owner: Pool): Promise { }; } +const CELL_ID_ALPHABET = "abcdefghijklmnopqrstuvwxyz234567"; + +/** A cell id as the table's check requires: sixteen characters of lower-case base32. */ +export function randomCellId(): string { + return Array.from(randomBytes(16), (byte) => CELL_ID_ALPHABET[byte % 32]).join(""); +} + +/** A running cell row for a tenant, written as the schema owner. Returns its cell id. */ +export async function seedCell(owner: Pool, tenantId: string): Promise { + const cellId = randomCellId(); + await owner.query( + "INSERT INTO exomem_cloud_cells (cell_id, tenant_id, desired_state) VALUES ($1, $2, 'running')", + [cellId, tenantId] + ); + return cellId; +} + /** Every row of a table as JSON, to compare before and after a refused statement. */ export async function tableSnapshot(owner: Pool, table: string): Promise { const { rows } = await owner.query<{ snapshot: string }>( From 1ffc868488ca57d8987d8e2de3b92144c8c43c74 Mon Sep 17 00:00:00 2001 From: Artexis10 Date: Wed, 2 Dec 2026 10:49:08 +0000 Subject: [PATCH 10/29] Drop the ticket grant guard, end service credential records, and run PostgreSQL suites serially - Remove the download ticket grant guard and the ticket row's grant column. The gateway already requires the token family to carry the grant that the signed ticket names, so a role that inserts a row can name only a family with its real grant. That is issuance, which the log records. The handler stops writing the grant, and the recording function reads the grant, tenant and user through the token family. - Give a service credential's record an end. A service credential has no expiry, so its record was never pruned. The recording function now sets the record's end to the database clock when the credential is revoked or its row is deleted, and the prune deletes it 90 days later. The clock is used, not revoked_at, which the web role writes and could set in the past to bring the prune forward. A partial index finds the record. - Share one login-role password between the suites that create the same cluster-wide roles, and run the PostgreSQL steps in test.yml with --test-concurrency=1, because roles and grants belong to the cluster. - State the retention plainly in the proposal and the design: 90 days after expiry or end, up to 365 plus 90 days for a token family, and past account deletion for that window. Add cells to the identity lock bullet, match the release plan's 100 first-parent ancestors, and mark the size estimate as a lower bound. --- .github/workflows/test.yml | 8 +- docs/runbooks/exomem-cloud-operations.md | 29 +++-- ...omem_issuance_log_and_download_tickets.sql | 85 +++++++------- .../design.md | 22 ++-- .../proposal.md | 6 +- .../specs/exomem-hosted-gateway/spec.md | 9 +- .../specs/exomem-hosted-mcp-oauth/spec.md | 12 +- .../specs/substrate-database-releases/spec.md | 2 +- .../tasks.md | 24 ++-- scripts/exomem-cloud-grants.sql | 6 - .../cloud-grants-postgres.integration.test.ts | 27 ++--- ...identity-lock-postgres.integration.test.ts | 62 +---------- ...-issuance-log-postgres.integration.test.ts | 104 +++++++++++++++++- ...edia-download-postgres.integration.test.ts | 16 +-- src/lib/exomem-hosted/__tests__/flow-pool.ts | 3 +- .../__tests__/identity-lock-fixture.ts | 3 +- ...chema-release-postgres.integration.test.ts | 3 +- .../__tests__/test-role-password.ts | 5 + src/lib/exomem-hosted/cloud-media-download.ts | 4 +- 19 files changed, 236 insertions(+), 194 deletions(-) create mode 100644 src/lib/exomem-hosted/__tests__/test-role-password.ts diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index f0ee4dfc..84f48ee2 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -37,12 +37,14 @@ jobs: - id: install run: npm ci - run: npm test + # The PostgreSQL steps run one file at a time: the suites create the same login roles, and + # roles, their passwords and their grants belong to the cluster, so two files cannot share it. - name: Exomem shared PostgreSQL authority (OAuth, capacity, billing, sessions, migrations) env: EXOMEM_TEST_DATABASE_URL: postgresql://postgres:postgres@127.0.0.1:5432/substrate_test CONFIRM_ENDSTATE_CLOUD_RELEASE_A: "yes" run: >- - node --import tsx --experimental-test-module-mocks --test + node --import tsx --experimental-test-module-mocks --test --test-concurrency=1 src/lib/exomem-hosted/__tests__/oauth-postgres.integration.test.ts src/lib/exomem-hosted/__tests__/capacity-postgres.integration.test.ts src/lib/exomem-hosted/__tests__/migration-upgrade.integration.test.ts @@ -56,7 +58,7 @@ jobs: EXOMEM_TEST_DATABASE_URL: postgresql://postgres:postgres@127.0.0.1:5432/substrate_test CONFIRM_ENDSTATE_CLOUD_RELEASE_A: "yes" run: >- - node --import tsx --experimental-test-module-mocks --test + node --import tsx --experimental-test-module-mocks --test --test-concurrency=1 src/lib/hosted-backup/__tests__/version-commit-postgres.integration.test.ts src/lib/db/__tests__/pg-sql-driver.integration.test.ts - name: Exomem Cloud control plane PostgreSQL authority (schema, grants, admission, OAuth, Home channel, exports, lifecycle, deletion, release) @@ -64,7 +66,7 @@ jobs: EXOMEM_TEST_DATABASE_URL: postgresql://postgres:postgres@127.0.0.1:5432/substrate_test CONFIRM_ENDSTATE_CLOUD_RELEASE_A: "yes" run: >- - node --import tsx --experimental-test-module-mocks --test + node --import tsx --experimental-test-module-mocks --test --test-concurrency=1 src/lib/exomem-hosted/__tests__/cloud-cells-postgres.integration.test.ts src/lib/exomem-hosted/__tests__/cloud-grants-postgres.integration.test.ts src/lib/exomem-hosted/__tests__/cloud-identity-lock-postgres.integration.test.ts diff --git a/docs/runbooks/exomem-cloud-operations.md b/docs/runbooks/exomem-cloud-operations.md index ac100c5a..5c207314 100644 --- a/docs/runbooks/exomem-cloud-operations.md +++ b/docs/runbooks/exomem-cloud-operations.md @@ -808,8 +808,6 @@ Four more rules hold on the same terms: Only the schema owner and the routines that run as the schema owner may write them. The guards are `schema_releases_owner_only`, `exomem_cloud_issuance_log_owner_only` and the matching `..._owner_only_truncate` triggers. - A row in `exomem_cloud_download_tickets` cannot change. The guard is `exomem_cloud_download_tickets_update_lock`. -- An insert into `exomem_cloud_download_tickets` must name the grant of its token family. The guard `exomem_cloud_download_tickets_grant_match` - refuses any other row, and a row for a family that does not exist, for every role including the schema owner. - A truncate that cascades from another table meets the same guards. The schema owner is exempt, because it can drop any guard. The lock is stated against the select, insert, update, @@ -836,6 +834,10 @@ The recording triggers are `exomem_oauth_token_families_issuance_record`, `exome `exomem_oauth_refresh_tokens_issuance_record`, `exomem_cloud_service_credentials_issuance_record` and `exomem_cloud_download_tickets_issuance_record`. Each one sits on the table that its name gives. +Two more triggers on `exomem_cloud_service_credentials`, `exomem_cloud_service_credentials_issuance_end_revoke` and +`exomem_cloud_service_credentials_issuance_end_delete`, end a record when its credential is revoked or its row is +deleted. While they are off, that record stays open and the prune never deletes it. + A hand-typed grant or a disabled trigger is an emergency state, not a fix. After either statement: 1. Open a commit that changes the grants script or the guard so that the flow works under the lock. @@ -854,8 +856,11 @@ row has `backfilled` set. Its `recorded_at` is the migration's time. The recording fails closed. A credential insert fails when its record cannot be written. The web app's role cannot read, write or alter the log. The reconcile job calls `exomem_prune_issuance_log()` once a run. The function deletes at most -10,000 records whose credential expired more than 90 days ago. It never deletes a record that has no expiry, which is a -service credential's. The job's response reports the deleted counts as `issuancePruned.records` and +10,000 records whose credential expired, or ended, more than 90 days ago. A service credential has no expiry. Its +record stays open while the credential is live, and the prune never deletes it. When the credential is revoked, or its +row is deleted, the record's end becomes the database clock's time, and the prune deletes it 90 days later. A token +family's record lasts up to its 365-day expiry plus 90 days. A record outlives its account for the same time, because +only the schema owner deletes a record. The job's response reports the deleted counts as `issuancePruned.records` and `issuancePruned.tickets`. A value of `null` means that part failed, and the log line `exomem-issuance: log retention failed` names it. @@ -977,11 +982,12 @@ FROM (VALUES ('exomem_cloud_issuance_log', 'exomem_cloud_issuance_log_owner_only'), ('exomem_cloud_issuance_log', 'exomem_cloud_issuance_log_owner_only_truncate'), ('exomem_cloud_download_tickets', 'exomem_cloud_download_tickets_update_lock'), - ('exomem_cloud_download_tickets', 'exomem_cloud_download_tickets_grant_match'), ('exomem_oauth_token_families', 'exomem_oauth_token_families_issuance_record'), ('exomem_oauth_access_tokens', 'exomem_oauth_access_tokens_issuance_record'), ('exomem_oauth_refresh_tokens', 'exomem_oauth_refresh_tokens_issuance_record'), ('exomem_cloud_service_credentials', 'exomem_cloud_service_credentials_issuance_record'), + ('exomem_cloud_service_credentials', 'exomem_cloud_service_credentials_issuance_end_revoke'), + ('exomem_cloud_service_credentials', 'exomem_cloud_service_credentials_issuance_end_delete'), ('exomem_cloud_download_tickets', 'exomem_cloud_download_tickets_issuance_record') ) AS expected(table_name, trigger_name) LEFT JOIN pg_trigger AS trigger @@ -1039,9 +1045,9 @@ WHERE namespace.nspname NOT LIKE 'pg\_temp\_%' AND namespace.nspname NOT LIKE 'p #### Size and retention -At the load target the design estimates about 142 million records and 35 GB, which is 250 bytes for a record and its -three indexes. Read the size with the estimated record count. The count is the planner's estimate, so it lags until -the next analyse. +At the load target the design estimates at least 142 million records and at least 35 GB. The 35 GB uses 250 bytes for a +record and its three indexes, which is a lower bound: measured records were larger. Read the size with the estimated +record count. The count is the planner's estimate, so it lags until the next analyse. ```sql SELECT pg_size_pretty(pg_total_relation_size('exomem_cloud_issuance_log')) AS size, @@ -1073,9 +1079,10 @@ statement that finds the ticket's login, so a download makes no extra database r - The web app's role may select, insert and delete ticket rows. The gateway's role reads `family_id`, `path_sha256` and `expires_at`. No role can update a row. - The reconcile job deletes up to 1000 expired rows a run, through the index on `expires_at`. A row lives one day at most. -- The row table has no foreign key. A guard refuses a ticket row whose grant is not the grant of its token family, and a - row for a family that does not exist. The recording trigger reads the tenant and the user through the family's grant, - not through the row's. +- The row table has no foreign key and holds no grant. The recording trigger reads the grant, the tenant and the user + through the token family. An insert for a family that does not exist fails, because the recording fails closed. A role + that can insert a row can name another tenant's family, and the gateway then admits the ticket. The issuance log + records that insert, like every credential. #### Deploy and rollback order diff --git a/migrations/0102_exomem_issuance_log_and_download_tickets.sql b/migrations/0102_exomem_issuance_log_and_download_tickets.sql index 984919c4..26ab9dcc 100644 --- a/migrations/0102_exomem_issuance_log_and_download_tickets.sql +++ b/migrations/0102_exomem_issuance_log_and_download_tickets.sql @@ -38,7 +38,10 @@ CREATE TABLE exomem_cloud_issuance_log ( client_id uuid, tenant_id uuid NOT NULL, user_id uuid NOT NULL, - -- Empty for a credential that has no expiry, which the prune never deletes. + -- When the credential expires, so the prune keeps the record until 90 days after. + -- A service credential has no expiry: its record takes the time the credential + -- ends, by the database clock, when it is revoked or its row is deleted. Empty + -- while that credential is live, and the prune never deletes an empty one. expires_at timestamptz, -- The role that connected (session_user), not the owner that the recording -- function runs as. @@ -49,6 +52,10 @@ CREATE TABLE exomem_cloud_issuance_log ( -- The prune reads by expiry, and one tenant's records list newest first. CREATE INDEX exomem_cloud_issuance_log_expires_idx ON exomem_cloud_issuance_log (expires_at); CREATE INDEX exomem_cloud_issuance_log_tenant_idx ON exomem_cloud_issuance_log (tenant_id, id); +-- Ending a service credential finds its record by the credential's identifier. +-- The index holds only those records, so a token insert does not pay for it. +CREATE INDEX exomem_cloud_issuance_log_service_credential_idx + ON exomem_cloud_issuance_log (credential_id) WHERE credential_kind = 'service_credential'; -- The log refuses every writer that is not the schema owner, whatever rights -- the writer holds. The recording and prune functions run as the schema owner. @@ -62,13 +69,11 @@ CREATE TRIGGER exomem_cloud_issuance_log_owner_only_truncate -- A download ticket is a signed message, and no row backed it. The web app now -- stores one row for each ticket, and the gateway requires it. A row lives at -- most one day. No foreign key: the gateway joins the token family when it --- uses the ticket. The grant column is not read by the gateway. The guard below --- ties it to the token family's grant, and the recording function reads the --- tenant and the user through the family, so the row's own claim decides nothing. +-- uses the ticket, and the recording function reads the grant, tenant and user +-- through the family. The row names no grant, because nothing would read it. CREATE TABLE exomem_cloud_download_tickets ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), family_id uuid NOT NULL, - grant_id uuid NOT NULL, -- The ticket's claim: a SHA-256 of the path, in lower-case hexadecimal. path_sha256 text NOT NULL CHECK (path_sha256 ~ '^[0-9a-f]{64}$'), expires_at timestamptz NOT NULL, @@ -120,8 +125,7 @@ BEGIN -- TG_ARGV[0] is the credential kind. The function reads only what the row does -- not name: a refresh token's or a download ticket's grant through its token -- family, a tenant and a user through the grant, a service credential's owner - -- through its tenant. A ticket row also names a grant, but the record takes - -- the family's. Any missing row raises, so the credential insert fails closed. + -- through its tenant. Any missing row raises, so the credential insert fails closed. EXECUTE format($definition$ CREATE FUNCTION %1$I.exomem_record_issuance() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp @@ -135,6 +139,18 @@ BEGIN the_user uuid; the_expiry timestamptz; BEGIN + -- The end of a service credential: its revocation or the delete of its row. + -- The record takes the database clock, not the row's revoked_at, which the + -- web app's role writes and could set in the past to bring the prune forward. + -- A record that already has a time keeps it. + IF TG_OP <> 'INSERT' THEN + UPDATE %1$I.exomem_cloud_issuance_log AS record + SET expires_at = pg_catalog.now() + WHERE record.credential_kind = 'service_credential' + AND record.credential_id = OLD.id AND record.expires_at IS NULL; + RETURN NULL; + END IF; + IF kind = 'token_family' THEN the_grant := NEW.grant_id; the_family := NEW.id; the_client := NEW.client_id; the_expiry := NEW.expires_at; @@ -174,35 +190,9 @@ BEGIN $body$; $definition$, target_schema); - -- The ticket guard. A ticket row must name the grant that its token family - -- belongs to. The gateway admits a ticket on the family, the path digest and - -- the expiry, so without this a role that can insert a row names another - -- tenant's family with a grant of its own, and the gateway admits it. - -- It runs as the schema owner so that it reads the family whatever the - -- inserting role may select. A family that does not exist refuses the row too. - -- A web request inserts the grant that it read from the family, so a flow - -- never meets the refusal, except when the family has gone since the ticket was signed. - EXECUTE format($definition$ - CREATE FUNCTION %1$I.exomem_refuse_ticket_grant_mismatch() RETURNS trigger - LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp - AS $body$ - BEGIN - IF NOT EXISTS ( - SELECT 1 FROM %1$I.exomem_oauth_token_families AS family - WHERE family.id = NEW.family_id AND family.grant_id = NEW.grant_id - ) THEN - -- %%: the format() call around this body reads each single percent sign as a placeholder. - RAISE EXCEPTION 'EXOMEM_ROW_LOCKED: insert on %% names a grant that its token family does not have', - TG_TABLE_NAME USING ERRCODE = '42501'; - END IF; - RETURN NULL; - END; - $body$; - $definition$, target_schema); - - -- A record is kept until 90 days after its credential expires. The 90 days - -- is a constant here, not a setting: changing it takes a migration. A record - -- whose credential has no expiry never matches. One call deletes at most + -- A record is kept until 90 days after its credential expires, or for a + -- service credential, ends. The 90 days is a constant here, not a setting: + -- changing it takes a migration. A record of a live service credential never matches. One call deletes at most -- 10000 records, so the reconcile job's call stays short. EXECUTE format($definition$ CREATE FUNCTION %1$I.exomem_prune_issuance_log() RETURNS integer @@ -231,7 +221,6 @@ BEGIN -- app's role execute on the prune function only. EXECUTE format('REVOKE ALL ON FUNCTION %I.exomem_record_issuance() FROM PUBLIC', target_schema); EXECUTE format('REVOKE ALL ON FUNCTION %I.exomem_prune_issuance_log() FROM PUBLIC', target_schema); - EXECUTE format('REVOKE ALL ON FUNCTION %I.exomem_refuse_ticket_grant_mismatch() FROM PUBLIC', target_schema); END; $migration$; @@ -250,16 +239,19 @@ CREATE TRIGGER exomem_oauth_refresh_tokens_issuance_record CREATE TRIGGER exomem_cloud_service_credentials_issuance_record AFTER INSERT ON exomem_cloud_service_credentials FOR EACH ROW EXECUTE FUNCTION exomem_record_issuance('service_credential'); +-- The same function ends the record when the credential ends. A WHEN clause +-- cannot read NEW in a delete trigger, so a revocation and a delete get one trigger each. +CREATE TRIGGER exomem_cloud_service_credentials_issuance_end_revoke + AFTER UPDATE ON exomem_cloud_service_credentials + FOR EACH ROW WHEN (OLD.revoked_at IS NULL AND NEW.revoked_at IS NOT NULL) + EXECUTE FUNCTION exomem_record_issuance('service_credential'); +CREATE TRIGGER exomem_cloud_service_credentials_issuance_end_delete + AFTER DELETE ON exomem_cloud_service_credentials + FOR EACH ROW EXECUTE FUNCTION exomem_record_issuance('service_credential'); CREATE TRIGGER exomem_cloud_download_tickets_issuance_record AFTER INSERT ON exomem_cloud_download_tickets FOR EACH ROW EXECUTE FUNCTION exomem_record_issuance('download_ticket'); --- The ticket guard is an AFTER row trigger like the others, so it judges the stored row. --- Both triggers fire on every insert, in the order of their names; either one fails the insert. -CREATE TRIGGER exomem_cloud_download_tickets_grant_match - AFTER INSERT ON exomem_cloud_download_tickets - FOR EACH ROW EXECUTE FUNCTION exomem_refuse_ticket_grant_mismatch(); - -- One backfilled record for each credential row that exists. It runs after the -- triggers exist and inside the transaction that holds the locks, so no row can -- land between the two steps without a record. The ticket table is new and empty. @@ -291,9 +283,12 @@ FROM exomem_oauth_refresh_tokens AS token JOIN exomem_oauth_token_families AS family ON family.id = token.family_id JOIN exomem_oauth_grants AS grant_row ON grant_row.id = family.grant_id; +-- A credential that is revoked already ends at the migration's time, like every +-- backfilled time, so the prune keeps its record 90 days from the migration. INSERT INTO exomem_cloud_issuance_log ( - credential_kind, credential_id, tenant_id, user_id, database_role, backfilled + credential_kind, credential_id, tenant_id, user_id, expires_at, database_role, backfilled ) -SELECT 'service_credential', credential.id, credential.tenant_id, tenant.owner_user_id, current_user, true +SELECT 'service_credential', credential.id, credential.tenant_id, tenant.owner_user_id, + CASE WHEN credential.revoked_at IS NOT NULL THEN pg_catalog.now() END, current_user, true FROM exomem_cloud_service_credentials AS credential JOIN exomem_tenants AS tenant ON tenant.id = credential.tenant_id; diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md index 73dcaef0..9ea11ebc 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md @@ -106,7 +106,7 @@ One generic guard that compares every column outside an allow-list was weighed. **The schema owner is exempt** for two reasons. Its repairs, its test fixtures and its cascades must work: deleting a user removes that user's grants. It can also drop any trigger, so a guard against it would prevent nothing. -The body of a `SECURITY DEFINER` function that the schema owner owns runs as the schema owner, so its statements pass every guard. Each such function is part of the lock. The schema has one today (Context), and it writes none of these tables. This change adds three: the recording function and the ticket guard function (D5, D8) and the prune function (D6). A test pins the full set. When the test fires wrongly, a migration that adds a legitimate definer function fails CI until its author adds the function to the set. The author pays one line, in review, and nothing reaches production. +The body of a `SECURITY DEFINER` function that the schema owner owns runs as the schema owner, so its statements pass every guard. Each such function is part of the lock. The schema has one today (Context), and it writes none of these tables. This change adds two, in D5 and D6. A test pins the full set. When the test fires wrongly, a migration that adds a legitimate definer function fails CI until its author adds the function to the set. The author pays one line, in review, and nothing reaches production. **The trigger right.** A trigger that a role attaches to a table runs inside every statement that touches the table. When that statement is a foreign-key action, or belongs to a definer function, a `BEFORE` trigger's code runs as the schema owner. So does every statement that the code runs. The trigger's function can live in the role's temporary schema. So a role that holds the trigger right on one table of the schema can run its own code as the schema owner. No guard holds against that. @@ -175,7 +175,7 @@ One table, `exomem_cloud_issuance_log`, holds one record for each credential ins | `credential_id` | the credential row's identifier | | `grant_id`, `family_id`, `client_id` | as the credential row names them, or read through its token family | | `tenant_id`, `user_id` | read from the grant, or from the service credential's own tenant | -| `expires_at` | the credential's expiry, or empty when it has none | +| `expires_at` | the credential's expiry. A service credential has none: its record stays empty while the credential is live, and takes the database clock's time when the credential ends (D6) | | `database_role` | the role that connected (`session_user`) | | `backfilled` | true only for a record that the migration wrote for an older row | @@ -205,9 +205,11 @@ Other points: The recording fails closed: when the record cannot be written, the credential insert fails. This prevents a credential that exists with no record, which is the claim itself. When it fires wrongly, sign-in and Home fail for every user until the schema owner disables the trigger with one statement. The proof in `tasks.md` runs every flow through the trigger before release, and the runbook names that statement. -### D6. Records are kept until 90 days after the credential expires +### D6. Records are kept until 90 days after the credential expires or ends -A record is deleted once its credential expired more than 90 days ago. A record with no expiry, which is a service credential's, is never deleted. A token family lives up to its session maximum, 365 days by default, so its record lives longer than that. +A record is deleted once its credential expired, or ended, more than 90 days ago. A token family lives up to its session maximum, 365 days by default, so its record lives up to that plus 90 days. + +A service credential has no expiry. Its record has no end while the credential is live, and the prune never deletes it. When the credential is revoked, or its row is deleted, the recording function sets the record's end to the database clock's time. It runs from an update trigger on the revocation time and a delete trigger, and it sets a record's end once. The prune then deletes the record 90 days later. The function reads the clock, not the row's `revoked_at`. The web app's role writes that column, and a past time would bring the prune forward and erase the record of a credential that the role issued. A partial index on the credential's identifier, which holds only service credential records, finds the record. A token insert pays nothing for it. For a revoked credential that exists when the migration runs, the record's end is the migration's time. The expiry is safe to key on. It is set at insert and is a fixed column afterwards. A credential cannot be used after its expiry, so no usable credential loses its record early. @@ -238,7 +240,7 @@ Volume, from constants in the code and one assumption: - A refresh token expires after its idle window, 30 days by default, so its record lives up to 120 days. - Assumption, not a recorded figure: each of 10,000 tenants keeps Home visible for one hour a day and runs two apps for eight hours. -That gives about 1.5 million records a day: 1.2 million from Home and 0.3 million from apps. About 142 million sit inside the retention. A record with its three index entries takes roughly 250 bytes, so the log holds about 35 GB at the load target. Home's two-minute tokens are about three quarters of it. The row size is an estimate from the column list. Nothing here is measured, and the proof reports the measured size of a record. +That gives about 1.5 million records a day: 1.2 million from Home and 0.3 million from apps. About 142 million sit inside the retention. A record with its three index entries takes at least 250 bytes, so the log holds at least about 35 GB at the load target. Home's two-minute tokens are about three quarters of it. The 250 bytes is a lower bound from the column list: records measured in the proof were larger. The proof reports the measured size of a record. The log also costs outside the request: @@ -256,11 +258,11 @@ Proof, on a disposable PostgreSQL: A download ticket is a signed message that names a token family, a grant and a path digest. The web app signs it with a key that the gateway shares. No row backs it. A compromised web app could sign a ticket against any tenant's live Home token family and leave no trace. -The web app now stores one row for each ticket in `exomem_cloud_download_tickets`: an identifier, the token family, the grant, the path digest and the expiry. A recording trigger writes the issuance record. +The web app now stores one row for each ticket in `exomem_cloud_download_tickets`: an identifier, the token family, the path digest and the expiry. A recording trigger writes the issuance record. - **Key.** A unique key covers the token family, the path digest and the expiry. The web app inserts with `ON CONFLICT DO NOTHING`. Two tickets with the same three values carry the same authority and share one row and one record. - **Rights.** The web app's role holds select, insert and delete. The gateway's role holds select. A guard refuses every update unless the schema owner runs it. -- **No foreign key.** A row lives at most one day, and the gateway joins the token family when the ticket is used. A guard on insert refuses a row whose grant is not the grant of its token family, and a row for a family that does not exist. The gateway matches a ticket on the family, the path digest and the expiry, so without that guard a role that can insert names another tenant's family with a grant of its own, and the gateway admits the ticket. The guard function is `SECURITY DEFINER`, so it reads the family whatever the inserting role may select, and it pins its path like the recording function. The recording function reads the tenant and the user through the family's grant, not through the row's. When the guard fires wrongly, an insert fails for a family that vanished since the ticket was signed, and the owner asks for the download again. +- **No foreign key, and no grant column.** A row lives at most one day, and the gateway joins the token family when the ticket is used. The row names no grant, because nothing reads one: the gateway's lookup requires the ticket's token family to carry the grant that the signed ticket names. The recording function reads the grant, the tenant and the user through the family. An insert for a family that does not exist fails, because the recording fails closed. A role that can insert can name another tenant's family with that family's real grant, and the gateway then admits the ticket. That is issuance, which the log records and this change does not prevent (limit 1). - **Prune.** The scheduled maintenance deletes a bounded batch of expired rows, through an index on the expiry. The gateway checks the signature as today and then requires the matching unexpired row. The check is one more condition in the statement that already resolves the ticket's login. A media request therefore makes no extra round trip, and each byte-range request costs one more index probe. A test counts the statements of a download request before and after. @@ -284,7 +286,7 @@ A new workflow runs on every push to `main` and by hand. It runs in a protected 1. Checks that its commit is the tip of `main`. If it is not, the job applies nothing. It records the commit as superseded, unless the commit already has a row. 2. Runs `scripts/migrate.ts`, which applies the pending migrations and then the grants script. -3. Records a schema release for its commit. It records as superseded each commit between the previous schema release and its own that has no row. +3. Records a schema release for its commit. It records as superseded the commit's first-parent ancestors, up to 100, that have no row. An ancestor that already has a row keeps it. A gap longer than 100 commits leaves its oldest commits without a row, and a build of one of them fails after its wait. `schema_releases` holds one row for each commit, with a status of `released` or `superseded`. A row is written once and never changes: the job inserts and never updates. A restarted run of a released commit therefore leaves it released. A guard refuses every write to the table unless the schema owner runs it, and the web app's role holds select only. @@ -377,7 +379,7 @@ The claim is: the database records every credential that the account service iss 5. **What a grant allows.** The account service can change a grant's scopes. It can change an app's stored attributes, such as its name, its redirect addresses and whether it is enabled. The grant's tenant, user and app stay fixed. 6. **Suspension and blocks.** The account service sets a tenant's status and can add or remove an account block. 7. **The schema owner, the trigger right and the create right.** Whoever holds the schema-owner credential, administers the database server, or lands a commit on `main` can change the lock and the log. So can a role that holds the trigger right on a table in the schema, or a create right on the database or on a schema (D2). So can an administrator of the repository: they can edit the protected environment or the ruleset and run code with the schema-owner credential without landing a commit. The rollout turns off the administrators' bypass of the environment's rules, which narrows that path but does not remove it. Each change through `main` is a public commit. -8. **Old records.** A record is deleted 90 days after its credential expires. +8. **Retention.** The log keeps a record until 90 days after its credential expires. For a service credential, which has no expiry, that is 90 days after it is revoked or its row is deleted. A token family lives up to 365 days, so its record can last up to 365 plus 90 days. Records also outlive account deletion for that window: no flow but the schema owner deletes a record, and deleting an account does not. 9. **Use, revocation and deletion.** The log records issuance only. It does not say when a credential was used, revoked or deleted. 10. **The gateway's own keys.** The gateway signs cell tokens and upload capsules with its own keys. In this repository only gateway code loads them. Other services may hold them, and this change does not record what they sign. The rollout checks that no web deployment environment holds those keys. 11. **Credentials that the web app admits itself.** The web app issues and checks its own browser sessions. It does the same for the possession grants and sessions of the access record (`exomem_cloud_access_grants`, `exomem_cloud_access_sessions`). The gateway admits none of them, and the log records none. @@ -420,5 +422,5 @@ Rollback: Each question has a default that this design already uses. -1. **Retention.** The design keeps a record until 90 days after its credential expires. A longer period keeps evidence for longer. It also keeps a finer record of when each account was active, and costs storage in proportion. Home's two-minute tokens are about three quarters of the log, so their retention decides its size. The period becomes part of the public claim. +1. **Retention.** The design keeps a record until 90 days after its credential expires or, for a service credential, ends. A longer period keeps evidence for longer. It also keeps a finer record of when each account was active, and costs storage in proportion. Home's two-minute tokens are about three quarters of the log, so their retention decides its size. The period becomes part of the public claim. 2. **The migration job's runner.** A hosted runner may not reach the migration address. The choice is then a runner inside the database's network, or opening the address to hosted runners. The first keeps the address closed. It adds a machine to maintain, and a runner group that only this workflow may use. diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/proposal.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/proposal.md index 368ef051..22bc3f6f 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/proposal.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/proposal.md @@ -5,10 +5,10 @@ Substrate's web app signs users in and issues the credentials that the Exomem Cl ## What Changes - **Schema releases leave the web build.** A continuous-integration job in a protected environment applies migrations and the grants script for the tip of `main`. It then records a schema release for that commit, and records each overtaken commit as superseded. The production build runs no migration. It waits for its commit's schema release and fails at once when its commit is superseded. The schema-owner credential leaves every web deployment environment, and the operator rotates it. **BREAKING** for the operator: `SKIP_VERCEL_MIGRATE` and the migration procedure that pulls production variables from the web deployment go away. -- **Identity lock.** Guard triggers refuse every change to an identity field of a grant, token family, access token, refresh token, client or service credential. They also refuse a change to a tenant's owner. A revocation time and a consumption time change only from empty to a time. Guards refuse a delete of a grant, client, tenant, user, service credential or reviewer credential. Each guard holds for every role except the schema owner, whatever select, insert, update, delete and truncate rights that role holds. A guard checks the stored row, so no trigger that runs before it can slip a change past. The web app's database role also keeps update rights only on the columns its flows change. +- **Identity lock.** Guard triggers refuse every change to an identity field of a grant, token family, access token, refresh token, client or service credential. They also refuse a change to a tenant's owner and to a cell's identifier or tenant. A revocation time and a consumption time change only from empty to a time. Guards refuse a delete of a grant, client, tenant, user, cell, service credential or reviewer credential. Each guard holds for every role except the schema owner, whatever select, insert, update, delete and truncate rights that role holds. A guard checks the stored row, so no trigger that runs before it can slip a change past. The web app's database role also keeps update rights only on the columns its flows change. - **The trigger right stays with the schema owner.** A role that holds the trigger right on a table can run its own code as the schema owner, and no guard holds against that. The grants script therefore revokes that right on every table in the schema from every other role, on every run. `PUBLIC` holds no execute right on the functions that this change adds. Every function that the database can run as the schema owner for another role pins its search path, so a role's own operator cannot run in place of the built-in one. - **No switch.** The lock and the log are in force once the migrations apply. Relaxing either one takes a migration or a grants change, which is a reviewed commit. -- **Issuance log.** An owner-owned trigger writes one record for every access token, refresh token, token family, service credential and download ticket row, in the inserting transaction. The log refuses every write that the schema owner does not run. A read-only audit role reads it in bounded ranges. A record is kept until 90 days after its credential expires. +- **Issuance log.** An owner-owned trigger writes one record for every access token, refresh token, token family, service credential and download ticket row, in the inserting transaction. The log refuses every write that the schema owner does not run. A read-only audit role reads it in bounded ranges. A record is kept until 90 days after its credential expires or, for a service credential, which has no expiry, until 90 days after it is revoked or its row is deleted. A token family's record can therefore last up to its 365-day expiry plus 90 days. Records also outlive account deletion for that window, because no flow but the schema owner deletes a record. - **Download tickets get a stored row.** A download ticket is a credential that the web app signs with a key it holds. Today no row backs it. The web app now stores one row for each ticket, and the gateway refuses a ticket without its row. - **Proof as the real roles.** Tests on a disposable PostgreSQL run every legitimate flow as the web app's role. They run each attack as that role twice: with the new rights, and with select, insert, update, delete and truncate on every table. @@ -36,4 +36,4 @@ The account service stays the sign-in provider, so it can still issue a credenti - **Tests:** `cloud-grants-postgres.integration.test.ts` changes its assertion that the web app's role holds every right on every non-Cloud table. A fixture step that the lock refuses moves to the role that owns the schema. - **Runbooks:** `docs/runbooks/production-keys-and-storage.md`, `docs/runbooks/exomem-cloud-operations.md`, `docs/runbooks/vercel-deployments.md` and the README's migration section. - **Operator steps:** the protected environment and its secret, the audit role, the settings and database checks, and the merge that applies the lock and the log. Then removing and rotating the schema-owner credential, and rolling the gateway. `tasks.md` lists each one. -- **Storage and privacy:** the issuance log is a new retained record, and each backup grows by its size. It shows when each account's apps and Home were active, by opaque identifier, for the retention period. The privacy page must say so when it states the claim. +- **Storage and privacy:** the issuance log is a new retained record, and each backup grows by its size. It shows when each account's apps and Home were active, by opaque identifier, for the retention period above. The privacy page must say so when it states the claim. diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-gateway/spec.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-gateway/spec.md index 4269fe3a..0f42e754 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-gateway/spec.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-gateway/spec.md @@ -2,7 +2,7 @@ ### Requirement: The gateway admits a download ticket only with its stored row -The web app SHALL store one row for each download ticket that it signs. The row SHALL name the ticket's token family, grant, path digest and expiry. The gateway SHALL refuse a ticket that has no matching unexpired row, whatever its signature says. The database SHALL refuse every update of a ticket row that the schema owner does not run, and every insert of a row whose grant is not its token family's grant. Every ticket row insert SHALL write an issuance record. +The web app SHALL store one row for each download ticket that it signs. The row SHALL name the ticket's token family, path digest and expiry. The gateway SHALL refuse a ticket that has no matching unexpired row, whatever its signature says. The database SHALL refuse every update of a ticket row that the schema owner does not run. Every ticket row insert SHALL write an issuance record. #### Scenario: A signed ticket has no row @@ -31,15 +31,10 @@ The web app SHALL store one row for each download ticket that it signs. The row - **WHEN** the web app signs a second ticket with the same token family, path digest and expiry - **THEN** the two tickets share one row and one issuance record -#### Scenario: A ticket row names another tenant's family with the inserting role's own grant - -- **WHEN** the web app's role inserts a ticket row with another tenant's token family and a grant of its own -- **THEN** the database refuses the insert and no row exists for the gateway to match - #### Scenario: A ticket row is inserted - **WHEN** the web app stores a ticket row -- **THEN** the issuance log gains one record that names the row, its token family, the family's grant, and the tenant, user and expiry that follow from that grant +- **THEN** the issuance log gains one record that names the row, its token family, and the grant, tenant, user and expiry that follow from that family - **AND** the record holds no path and no path digest #### Scenario: The row check adds no round trip diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md index 8c2d352a..d5393214 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md @@ -241,7 +241,7 @@ The issuance log SHALL refuse every insert, update, delete and truncate that the ### Requirement: Issuance records outlive their credentials and stay cheap to write -An issuance record SHALL be kept until at least 90 days after its credential expires, and a record whose credential has no expiry SHALL be kept. Only the prune routine SHALL delete records, in bounded batches from the scheduled maintenance. Recording SHALL add less than one millisecond to the median latency of the Home mint transaction at the 10,000-tenant load target. +An issuance record SHALL be kept until at least 90 days after its credential expires. A service credential has no expiry, so its record SHALL be kept until at least 90 days after the credential is revoked or its row is deleted. Only the prune routine SHALL delete records, in bounded batches from the scheduled maintenance. Recording SHALL add less than one millisecond to the median latency of the Home mint transaction at the 10,000-tenant load target. #### Scenario: The scheduled maintenance prunes the log @@ -254,11 +254,17 @@ An issuance record SHALL be kept until at least 90 days after its credential exp - **WHEN** the web app's role calls the prune routine any number of times - **THEN** no record inside its retention is deleted -#### Scenario: A credential without an expiry +#### Scenario: A live service credential -- **WHEN** a service credential has no expiry +- **WHEN** a service credential is live - **THEN** the prune routine never deletes its record +#### Scenario: A service credential ends + +- **WHEN** the web app's role revokes a service credential, with any revocation time, or the schema owner deletes its row +- **THEN** the record's end is the database clock's time at that statement +- **AND** the prune routine deletes the record only after 90 days from then + #### Scenario: The Home mint at the load target - **WHEN** the same Home mint transaction runs with and without the guards and the recording, on the same machine and on data generated for the load target diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/substrate-database-releases/spec.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/substrate-database-releases/spec.md index cf7f0664..0fc58bf6 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/substrate-database-releases/spec.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/substrate-database-releases/spec.md @@ -39,7 +39,7 @@ Production migrations and the grants script SHALL run from a continuous-integrat - **WHEN** a second commit lands while the job runs for the first - **THEN** the runs do not overlap, and the later commit's run applies last -- **AND** that run records as superseded each commit between the previous schema release and its own that has no row +- **AND** that run records as superseded the commit's first-parent ancestors, up to 100, that have no row #### Scenario: The operator runs the job by hand diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md index a4d2ca35..0027f2b6 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md @@ -91,9 +91,11 @@ names each decision as D1 to D12. - [x] 3.1 In the second migration, set a lock timeout of five seconds for the transaction, then take D5's locks in D5's order with one `LOCK TABLE` statement. Create `exomem_cloud_issuance_log` with its kind constraint, its - three indexes and its guard. Add the recording function and revoke its - execute right from `PUBLIC`. Add one - `AFTER INSERT` trigger on each of the five credential tables. Revoke every + three indexes, a partial index for service credential records, and its + guard. Add the recording function and revoke its execute right from + `PUBLIC`. Add one `AFTER INSERT` trigger on each of the five credential + tables, and on the service credential table an update trigger on the + revocation time and a delete trigger that end the record (D6). Revoke every right on the log in the same transaction. After the triggers exist, in the same transaction, write one backfilled record for each credential row that already exists. Verify: tasks 5.3 and 5.4. @@ -101,8 +103,10 @@ names each decision as D1 to D12. 90-day constant. Revoke its execute right from `PUBLIC` and give it to the web app's role. Call it from the reconcile job beside the OAuth maintenance, and report the deleted count. Verify: a record inside its retention survives - any number of calls, a record past it is deleted, and a service credential's - record is never deleted. + any number of calls, and a record past it is deleted. A live service + credential's record is never deleted. A revoked credential's record takes + the database clock's time, whatever revocation time the row names, and is + deleted 90 days after. - [x] 3.3 In `scripts/exomem-cloud-grants.sql`, revoke every right on the log from the web app's, the gateway's and the controller's roles on every run. Revoke execute on the guard, recording and prune functions from `PUBLIC`, @@ -115,12 +119,10 @@ names each decision as D1 to D12. - [x] 4.1 In the second migration, create `exomem_cloud_download_tickets` with its unique key, its expiry index, its update guard and its recording trigger. In the grants script, give the web app's role select, insert and - delete, and the gateway's role select. Add a guard on insert that refuses a - row whose grant is not its token family's grant, and have the recording - trigger read the tenant and the user through the family's grant. Verify: as - the web app's role, an update of a ticket row is refused, also after a grant - of update on the table, and so is a row that names another tenant's family - with the role's own grant. + delete, and the gateway's role select. The row names no grant: the recording + trigger reads the grant, the tenant and the user through the token family. + Verify: as the web app's role, an update of a ticket row is refused, also + after a grant of update on the table. - [x] 4.2 In the download handler, store the ticket's row before the redirect answer, with `ON CONFLICT DO NOTHING`. In the scheduled maintenance, delete a bounded batch of expired ticket rows. Verify: a download request leaves diff --git a/scripts/exomem-cloud-grants.sql b/scripts/exomem-cloud-grants.sql index 46318679..19fcf28e 100644 --- a/scripts/exomem-cloud-grants.sql +++ b/scripts/exomem-cloud-grants.sql @@ -243,9 +243,6 @@ BEGIN IF to_regprocedure('exomem_record_issuance()') IS NOT NULL THEN REVOKE ALL ON FUNCTION exomem_record_issuance() FROM PUBLIC; END IF; - IF to_regprocedure('exomem_refuse_ticket_grant_mismatch()') IS NOT NULL THEN - REVOKE ALL ON FUNCTION exomem_refuse_ticket_grant_mismatch() FROM PUBLIC; - END IF; IF to_regprocedure('exomem_prune_issuance_log()') IS NOT NULL THEN REVOKE ALL ON FUNCTION exomem_prune_issuance_log() FROM PUBLIC; IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'substrate_app') THEN @@ -260,9 +257,6 @@ BEGIN IF to_regprocedure('exomem_record_issuance()') IS NOT NULL THEN EXECUTE format('REVOKE ALL ON FUNCTION exomem_record_issuance() FROM %I', lock_role); END IF; - IF to_regprocedure('exomem_refuse_ticket_grant_mismatch()') IS NOT NULL THEN - EXECUTE format('REVOKE ALL ON FUNCTION exomem_refuse_ticket_grant_mismatch() FROM %I', lock_role); - END IF; IF lock_role <> 'substrate_app' AND to_regprocedure('exomem_prune_issuance_log()') IS NOT NULL THEN EXECUTE format('REVOKE ALL ON FUNCTION exomem_prune_issuance_log() FROM %I', lock_role); END IF; diff --git a/src/lib/exomem-hosted/__tests__/cloud-grants-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-grants-postgres.integration.test.ts index 96b720ea..3ac7e3a4 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-grants-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-grants-postgres.integration.test.ts @@ -18,6 +18,7 @@ import { loadOpenServiceNotices } from "../service-notice-header"; import { assertCellAcceptsGrant } from "./cell-grant-rules"; import { seedWorld } from "./identity-lock-fixture"; import { ensureExomemPostgresTestExtensions } from "./postgres-test-extensions"; +import { TEST_ROLE_PASSWORD } from "./test-role-password"; // D7 (reopened task 3.2): scripts/exomem-cloud-grants.sql is the single // implementation of both (1) schema-wide substrate_app DML plus default @@ -33,7 +34,7 @@ import { ensureExomemPostgresTestExtensions } from "./postgres-test-extensions"; process.env.EXOMEM_CONTROL_PLANE_KEY ??= randomBytes(32).toString("base64url"); const databaseUrl = process.env.EXOMEM_TEST_DATABASE_URL; -const TEST_PASSWORD = "exomem-cloud-grants-test"; +const TEST_PASSWORD = TEST_ROLE_PASSWORD; const CLOUD_ROLES = ["substrate_app", "exomem_cellctl", "exomem_gateway"] as const; const C1_TABLES = [ "exomem_cloud_cells", @@ -1978,18 +1979,13 @@ describe("Exomem Cloud grants PostgreSQL integration", { skip: !databaseUrl }, ( assert.deepEqual(await holders(), [], "a grants run takes the right back"); }); - it("runs with owner rights in exactly four functions, and lets only the web app's role call the prune", async () => { + it("runs with owner rights in exactly three functions, and lets only the web app's role call the prune", async () => { const definers = await ownerPool!.query<{ proname: string }>( `SELECT proname FROM pg_proc WHERE pronamespace = current_schema()::regnamespace AND prosecdef ORDER BY proname` ); assert.deepEqual( definers.rows.map((row) => row.proname), - [ - "exomem_prune_issuance_log", - "exomem_record_issuance", - "exomem_record_memory_health_proof", - "exomem_refuse_ticket_grant_mismatch", - ] + ["exomem_prune_issuance_log", "exomem_record_issuance", "exomem_record_memory_health_proof"] ); const executors = await ownerPool!.query<{ proname: string; grantee: string }>( `SELECT proc.proname, CASE acl.grantee WHEN 0 THEN 'PUBLIC' ELSE pg_get_userbyid(acl.grantee)::text END AS grantee @@ -1999,7 +1995,7 @@ describe("Exomem Cloud grants PostgreSQL integration", { skip: !databaseUrl }, ( ORDER BY 1, 2`, [[ "exomem_prune_issuance_log", "exomem_record_issuance", "exomem_record_memory_health_proof", - "exomem_refuse_ticket_grant_mismatch", "exomem_refuse_unless_schema_owner", + "exomem_refuse_unless_schema_owner", ]] ); assert.equal( @@ -2012,11 +2008,9 @@ describe("Exomem Cloud grants PostgreSQL integration", { skip: !databaseUrl }, ( [{ proname: "exomem_prune_issuance_log", grantee: "substrate_app" }] ); assert.deepEqual( - executors.rows.filter((row) => - ["exomem_record_issuance", "exomem_refuse_ticket_grant_mismatch", "exomem_refuse_unless_schema_owner"].includes(row.proname) - ), + executors.rows.filter((row) => ["exomem_record_issuance", "exomem_refuse_unless_schema_owner"].includes(row.proname)), [], - "no role but the owner executes the recording function or a guard function" + "no role but the owner executes the recording function or the guard function" ); }); @@ -2063,12 +2057,7 @@ describe("Exomem Cloud grants PostgreSQL integration", { skip: !databaseUrl }, ( assert.equal(path.at(-1), "pg_temp", `${row.proname} ends its search path with pg_temp`); assert.deepEqual(row.untrusted, [], `${row.proname} names a schema that an untrusted role owns`); } - for (const name of [ - "exomem_refuse_unless_schema_owner", - "exomem_refuse_ticket_grant_mismatch", - "exomem_record_issuance", - "exomem_prune_issuance_log", - ]) { + for (const name of ["exomem_refuse_unless_schema_owner", "exomem_record_issuance", "exomem_prune_issuance_log"]) { assert.ok(pinned.rows.some((row) => row.proname === name), `${name} is in the set`); } }); diff --git a/src/lib/exomem-hosted/__tests__/cloud-identity-lock-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-identity-lock-postgres.integration.test.ts index df9d16f1..bc2e425e 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-identity-lock-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-identity-lock-postgres.integration.test.ts @@ -86,9 +86,9 @@ async function seedVictims(fx: LockFixture, world: World): Promise { [randomBytes(32), reviewerOwnerId, reviewerTenant, "a".repeat(64), randomBytes(32)] ); const ticketId = await id( - `INSERT INTO exomem_cloud_download_tickets (family_id, grant_id, path_sha256, expires_at) - VALUES ($1, $2, $3, now() + interval '15 minutes') RETURNING id`, - [world.familyId, world.grantId, "0".repeat(64)] + `INSERT INTO exomem_cloud_download_tickets (family_id, path_sha256, expires_at) + VALUES ($1, $2, now() + interval '15 minutes') RETURNING id`, + [world.familyId, "0".repeat(64)] ); const cellId = await seedCell(fx.owner, world.tenantId); return { @@ -539,62 +539,6 @@ for (const state of STATES) { } ); - it("refuses a ticket row that names another tenant's family with the web app's own grant; with the guard off the gateway admits it and the record names the victim", async () => { - const tickets = fx.q("exomem_cloud_download_tickets"); - const insert = `INSERT INTO ${tickets} (family_id, grant_id, path_sha256, expires_at) - VALUES ($1, $2, $3, now() + interval '15 minutes') RETURNING id`; - // The gateway looks a ticket up by its family, path digest and expiry; it never reads the grant. - const gatewayFinds = async (path: string) => - ( - await fx.gateway.query<{ count: number }>( - `SELECT count(*)::int AS count FROM ${tickets} WHERE family_id = $1 AND path_sha256 = $2`, - [b.familyId, path] - ) - ).rows[0]!.count; - - const refusedPath = randomBytes(32).toString("hex"); - await assert.rejects( - fx.app.query(insert, [b.familyId, a.grantId, refusedPath]), - (error: Error & { code?: string }) => - error.code === "42501" && error.message.includes(LOCKED) - ); - assert.equal(await gatewayFinds(refusedPath), 0, "no row for the gateway to find"); - - // Control: with the guard off, the same insert goes through and the gateway finds the row. - // The record takes the tenant and the user from the family's grant, not from the row's. - const controlPath = randomBytes(32).toString("hex"); - const guard = "exomem_cloud_download_tickets_grant_match"; - await fx.owner.query(`ALTER TABLE ${tickets} DISABLE TRIGGER ${guard}`); - try { - const inserted = await fx.app.query<{ id: string }>(insert, [ - b.familyId, - a.grantId, - controlPath, - ]); - assert.equal( - await gatewayFinds(controlPath), - 1, - "the control row is found by the gateway" - ); - const record = await fx.owner.query( - `SELECT tenant_id, user_id, grant_id, database_role FROM ${fx.q("exomem_cloud_issuance_log")} - WHERE credential_kind = 'download_ticket' AND credential_id = $1`, - [inserted.rows[0]!.id] - ); - assert.deepEqual(record.rows, [ - { - tenant_id: b.tenantId, - user_id: b.userId, - grant_id: b.grantId, - database_role: "substrate_app", - }, - ]); - } finally { - await fx.owner.query(`ALTER TABLE ${tickets} ENABLE TRIGGER ${guard}`); - await fx.owner.query(`DELETE FROM ${tickets} WHERE path_sha256 = $1`, [controlPath]); - } - }); - // In the narrow state the role holds no update right on a cell's tenant, so the grants script refuses first. it( "moves a cell to another tenant only when its guard is off, and the gateway then finds it under that tenant", diff --git a/src/lib/exomem-hosted/__tests__/cloud-issuance-log-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-issuance-log-postgres.integration.test.ts index 3db90e80..237d031d 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-issuance-log-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-issuance-log-postgres.integration.test.ts @@ -264,13 +264,100 @@ for (const state of STATES) { ); }); + // A service credential has no expiry, so its record takes the time the credential ends. + const serviceCredentials = () => fx.q("exomem_cloud_service_credentials"); + const addServiceCredential = async () => + ( + await fx.owner.query<{ id: string }>( + `INSERT INTO ${serviceCredentials()} + (tenant_id, principal, secret_digest, created_by_principal_digest) + VALUES ($1, $2, $3, $4) RETURNING id`, + [ + world.tenantId, + `service:t${randomBytes(6).toString("hex")}`, + randomBytes(32), + randomBytes(32), + ] + ) + ).rows[0]!.id; + const recordEnd = async (credentialId: string) => + ( + await fx.owner.query<{ open: boolean; at_now: boolean }>( + `SELECT expires_at IS NULL AS open, + coalesce(expires_at > now() - interval '1 minute' AND expires_at <= now(), false) AS at_now + FROM ${log()} WHERE credential_kind = 'service_credential' AND credential_id = $1`, + [credentialId] + ) + ).rows[0]; + + it("ends a service credential's record at the database clock when the web app's role revokes it, whatever revoked_at says", async () => { + const live = await addServiceCredential(); + const revoked = await addServiceCredential(); + assert.deepEqual(await recordEnd(live), { open: true, at_now: false }); + await fx.app.query( + `UPDATE ${serviceCredentials()} + SET revoked_at = now() - interval '200 days', revoked_by_principal_digest = $2 WHERE id = $1`, + [revoked, randomBytes(32)] + ); + assert.deepEqual( + await recordEnd(revoked), + { open: false, at_now: true }, + "a backdated revoked_at does not bring the prune forward" + ); + assert.deepEqual( + await recordEnd(live), + { open: true, at_now: false }, + "a live one stays open" + ); + }); + + it("ends a service credential's record when the schema owner deletes its row", async () => { + const credential = await addServiceCredential(); + await fx.owner.query(`DELETE FROM ${serviceCredentials()} WHERE id = $1`, [credential]); + assert.deepEqual(await recordEnd(credential), { open: false, at_now: true }); + }); + + it("prunes a revoked service credential's record 90 days after the revocation, and keeps a live one's", async () => { + const live = await addServiceCredential(); + const revoked = await addServiceCredential(); + await fx.app.query( + `UPDATE ${serviceCredentials()} SET revoked_at = now(), revoked_by_principal_digest = $2 WHERE id = $1`, + [revoked, randomBytes(32)] + ); + const pruneAsApp = () => + fx.app.query(`SELECT ${fx.q("exomem_prune_issuance_log")}() AS deleted`); + const kept = async () => + ( + await fx.owner.query<{ credential_id: string }>( + `SELECT credential_id FROM ${log()} WHERE credential_id = ANY($1::uuid[])`, + [[live, revoked]] + ) + ).rows + .map((row) => row.credential_id) + .sort(); + await pruneAsApp(); + assert.deepEqual(await kept(), [live, revoked].sort(), "90 days have not passed"); + // The test cannot wait 90 days, so the owner moves the recorded end back. + await fx.owner.query( + `UPDATE ${log()} SET expires_at = now() - interval '91 days' + WHERE credential_kind = 'service_credential' AND credential_id = $1`, + [revoked] + ); + await pruneAsApp(); + assert.deepEqual( + await kept(), + [live], + "the revoked one's record is gone; the live one's stays" + ); + }); + it("lets the maintenance run, as the web app's role, remove an expired download ticket row", async () => { const ticket = async (expires: string) => ( await fx.owner.query<{ id: string }>( - `INSERT INTO ${fx.q("exomem_cloud_download_tickets")} (family_id, grant_id, path_sha256, expires_at, created_at) - VALUES ($1, $2, $3, now() + ${expires}, now() - interval '2 hours') RETURNING id`, - [world.familyId, world.grantId, randomBytes(32).toString("hex")] + `INSERT INTO ${fx.q("exomem_cloud_download_tickets")} (family_id, path_sha256, expires_at, created_at) + VALUES ($1, $2, now() + ${expires}, now() - interval '2 hours') RETURNING id`, + [world.familyId, randomBytes(32).toString("hex")] ) ).rows[0]!.id; const expired = await ticket("interval '-1 hour'"); @@ -345,6 +432,17 @@ describe("The migration that adds the log", { skip: !databaseUrl }, () => { { credential_kind: "service_credential", count: 2, backfilled: true }, { credential_kind: "token_family", count: 2, backfilled: true }, ]); + const ends = await fx.owner.query( + `SELECT count(*) FILTER (WHERE expires_at IS NULL)::int AS open, + count(*) FILTER (WHERE expires_at IS NOT NULL)::int AS ended + FROM exomem_cloud_issuance_log WHERE tenant_id = $1 AND credential_kind = 'service_credential'`, + [world.tenantId] + ); + assert.deepEqual( + ends.rows, + [{ open: 1, ended: 1 }], + "the revoked service credential's backfilled record has an end, the live one's has none" + ); const role = await fx.owner.query( "SELECT DISTINCT database_role FROM exomem_cloud_issuance_log WHERE tenant_id = $1", [world.tenantId] diff --git a/src/lib/exomem-hosted/__tests__/cloud-media-download-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-media-download-postgres.integration.test.ts index e2acbe3d..7b6aa230 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-media-download-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-media-download-postgres.integration.test.ts @@ -329,7 +329,7 @@ describe("Signed-in media download PostgreSQL boundary", { skip: !databaseUrl }, assert.equal(stored.rows[0].path_sha256, createHash("sha256").update(PATH).digest("hex")); } const all = await pool.query( - "SELECT count(*)::int AS count FROM exomem_cloud_download_tickets t JOIN exomem_oauth_grants g ON g.id = t.grant_id WHERE g.tenant_id = $1", + "SELECT count(*)::int AS count FROM exomem_cloud_download_tickets t JOIN exomem_oauth_token_families f ON f.id = t.family_id JOIN exomem_oauth_grants g ON g.id = f.grant_id WHERE g.tenant_id = $1", [a.tenantId] ); assert.equal(all.rows[0].count, expiries.size, "one row for each distinct expiry"); @@ -349,7 +349,7 @@ describe("Signed-in media download PostgreSQL boundary", { skip: !databaseUrl }, const otherLocation = (await link(b)).headers.get("location")!; const ticketRow = (family: string) => pool.query( - "SELECT id, grant_id, path_sha256, expires_at FROM exomem_cloud_download_tickets WHERE family_id = $1", + "SELECT id, path_sha256, expires_at FROM exomem_cloud_download_tickets WHERE family_id = $1", [family] ); const [row] = (await ticketRow(claims.family_id)).rows; @@ -374,8 +374,8 @@ describe("Signed-in media download PostgreSQL boundary", { skip: !databaseUrl }, // Each key of the stored row decides: a row that differs in one is no row for this ticket. const reset = () => pool.query( - "UPDATE exomem_cloud_download_tickets SET family_id = $2, grant_id = $3, path_sha256 = $4, expires_at = $5 WHERE id = $1", - [row.id, claims.family_id, row.grant_id, row.path_sha256, row.expires_at] + "UPDATE exomem_cloud_download_tickets SET family_id = $2, path_sha256 = $3, expires_at = $4 WHERE id = $1", + [row.id, claims.family_id, row.path_sha256, row.expires_at] ); const variants: Array<[string, string, unknown[]]> = [ ["no row", "DELETE FROM exomem_cloud_download_tickets WHERE id = $1", []], @@ -391,8 +391,8 @@ describe("Signed-in media download PostgreSQL boundary", { skip: !databaseUrl }, ], [ "another family", - "UPDATE exomem_cloud_download_tickets SET family_id = $2, grant_id = $3 WHERE id = $1", - [claimsOf(otherLocation).family_id, other.grant_id], + "UPDATE exomem_cloud_download_tickets SET family_id = $2 WHERE id = $1", + [claimsOf(otherLocation).family_id], ], ]; // The other owner's row may carry this ticket's path and expiry; the move below needs its place. @@ -403,8 +403,8 @@ describe("Signed-in media download PostgreSQL boundary", { skip: !databaseUrl }, assert.equal((await follow(location)).status, 401, `${name}: refused`); if (name === "no row") { await pool.query( - "INSERT INTO exomem_cloud_download_tickets (id, family_id, grant_id, path_sha256, expires_at) VALUES ($1, $2, $3, $4, $5)", - [row.id, claims.family_id, row.grant_id, row.path_sha256, row.expires_at] + "INSERT INTO exomem_cloud_download_tickets (id, family_id, path_sha256, expires_at) VALUES ($1, $2, $3, $4)", + [row.id, claims.family_id, row.path_sha256, row.expires_at] ); } else await reset(); } diff --git a/src/lib/exomem-hosted/__tests__/flow-pool.ts b/src/lib/exomem-hosted/__tests__/flow-pool.ts index 09104ee5..464b4008 100644 --- a/src/lib/exomem-hosted/__tests__/flow-pool.ts +++ b/src/lib/exomem-hosted/__tests__/flow-pool.ts @@ -1,12 +1,13 @@ import { Pool } from "pg"; import { applyMigrations } from "../../../../scripts/migrate"; +import { TEST_ROLE_PASSWORD } from "./test-role-password"; // Production runs the web app's flows as its own database role, on the rights of // scripts/exomem-cloud-grants.sql. A suite's own pool is the schema owner, which holds every right, // so a flow that needs a right the grants script withholds passes there and fails in production. // A suite hands its production code this pool instead, and keeps seeding and asserting on its own pool. const FLOW_ROLE = "substrate_app"; -const FLOW_PASSWORD = "exomem-flow-role-test"; +const FLOW_PASSWORD = TEST_ROLE_PASSWORD; /** The web app role's login on the suite's schema, with the grants script applied for it. */ export async function productionPool(scopedUrl: string, schema: string): Promise { diff --git a/src/lib/exomem-hosted/__tests__/identity-lock-fixture.ts b/src/lib/exomem-hosted/__tests__/identity-lock-fixture.ts index 06168d0c..100b8c26 100644 --- a/src/lib/exomem-hosted/__tests__/identity-lock-fixture.ts +++ b/src/lib/exomem-hosted/__tests__/identity-lock-fixture.ts @@ -2,6 +2,7 @@ import { randomBytes, randomUUID } from "node:crypto"; import { Pool } from "pg"; import { applyMigrations } from "../../../../scripts/migrate"; import { ensureExomemPostgresTestExtensions } from "./postgres-test-extensions"; +import { TEST_ROLE_PASSWORD } from "./test-role-password"; // The identity lock and the issuance log are proven as the real roles, not as a superuser that // holds every right. A schema owned by substrate_owner takes the migrations and the grants script, @@ -16,7 +17,7 @@ export const FIXTURE_ROLES = [ ] as const; export type LockState = "narrow" | "wide"; -const PASSWORD = "exomem-identity-lock-test"; +const PASSWORD = TEST_ROLE_PASSWORD; export type LockFixture = { schema: string; diff --git a/src/lib/exomem-hosted/__tests__/schema-release-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/schema-release-postgres.integration.test.ts index ae91655d..cd504eee 100644 --- a/src/lib/exomem-hosted/__tests__/schema-release-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/schema-release-postgres.integration.test.ts @@ -7,12 +7,13 @@ import { after, before, describe, it } from "node:test"; import { Pool } from "pg"; import { applyMigrations } from "../../../../scripts/migrate"; import { ensureExomemPostgresTestExtensions } from "./postgres-test-extensions"; +import { TEST_ROLE_PASSWORD } from "./test-role-password"; // Schema releases (design D9): the table the release job writes and the // production build reads, and how the migration runner records into it. const databaseUrl = process.env.EXOMEM_TEST_DATABASE_URL; -const TEST_PASSWORD = "exomem-cloud-grants-test"; +const TEST_PASSWORD = TEST_ROLE_PASSWORD; const FIRST = "1".repeat(40); const SECOND = "2".repeat(40); const THIRD = "3".repeat(40); diff --git a/src/lib/exomem-hosted/__tests__/test-role-password.ts b/src/lib/exomem-hosted/__tests__/test-role-password.ts new file mode 100644 index 00000000..cdade039 --- /dev/null +++ b/src/lib/exomem-hosted/__tests__/test-role-password.ts @@ -0,0 +1,5 @@ +// The login roles that the PostgreSQL suites create (`substrate_app`, `exomem_gateway`, ...) belong +// to the whole cluster, not to a suite's schema. Every suite sets their password before it +// connects, so two suites that set different ones lock each other out. One password, set by each +// suite, keeps the logins valid whichever suite ran last. +export const TEST_ROLE_PASSWORD = "exomem-suite-role-test"; diff --git a/src/lib/exomem-hosted/cloud-media-download.ts b/src/lib/exomem-hosted/cloud-media-download.ts index af1ee512..af153645 100644 --- a/src/lib/exomem-hosted/cloud-media-download.ts +++ b/src/lib/exomem-hosted/cloud-media-download.ts @@ -131,9 +131,9 @@ export async function handleCloudMediaDownloadRequest( if (!signed) throw exomemErrors.invalidRequest(); await sql` /* exomem:store-download-ticket */ - INSERT INTO exomem_cloud_download_tickets (family_id, grant_id, path_sha256, expires_at) + INSERT INTO exomem_cloud_download_tickets (family_id, path_sha256, expires_at) VALUES ( - ${signed.familyId}::uuid, ${signed.grantId}::uuid, ${signed.pathSha256}, + ${signed.familyId}::uuid, ${signed.pathSha256}, to_timestamp(${signed.expiresAt}::double precision) ) ON CONFLICT (family_id, path_sha256, expires_at) DO NOTHING From c8466103370f3f31b415d744cc4e77d7ce9c24c9 Mon Sep 17 00:00:00 2001 From: Artexis10 Date: Wed, 2 Dec 2026 11:12:21 +0000 Subject: [PATCH 11/29] Scope the issuance claim and column-rights requirement, and settle the rollout text The claim now names the credentials the gateway admits, and Limit 2 states what the web app's role can and cannot do with export, import and deletion grants. The column-rights requirement names the five column-locked tables. A failed migration job also needs a redeploy of a production build that already failed. Task 5.8 says where the run's outputs are kept, and task 7.4 gives the audit role's creation statement. --- docs/runbooks/production-keys-and-storage.md | 5 ++- .../design.md | 10 +++--- .../proposal.md | 4 +-- .../specs/exomem-hosted-mcp-oauth/spec.md | 2 +- .../tasks.md | 33 ++++++++++++++----- 5 files changed, 36 insertions(+), 18 deletions(-) diff --git a/docs/runbooks/production-keys-and-storage.md b/docs/runbooks/production-keys-and-storage.md index f60fdbd2..0087176a 100644 --- a/docs/runbooks/production-keys-and-storage.md +++ b/docs/runbooks/production-keys-and-storage.md @@ -195,8 +195,11 @@ A production build that carries no commit identifier fails. A failed build leave 1. Open the failed run in the repository's "Actions" tab. 2. Select "Re-run failed jobs". The job tests the tip again, so it applies only the tip of `main`. 3. Wait for the job to end. The expected result is a green run and a `released` row for the commit. +4. If the merge commit's production build already failed, open it in Vercel and select "Redeploy". The expected result is a build that reads the `released` row and deploys. -If the same step fails twice, read its log for the lock that timed out. +Step 4 is needed because nothing rebuilds a build that failed after its 15-minute wait. + +If the job fails twice at the same migration, read its log for the lock that timed out. Find the long transaction that holds that lock before you start the job again. **A manual run.** Use it when the runner cannot reach the database or GitHub Actions is down. It needs your own copy of the schema-owner connection string from your secret store, and the full hash of the commit to apply. diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md index 9ea11ebc..3ac9289b 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md @@ -22,7 +22,7 @@ Load target: `openspec/project.md` records 10,000 tenants. Neither `docs/runbook **Goals** -- The database records every credential that the web app issues for a cell, and the web app's role cannot alter the record. +- The database records every credential that the gateway admits from the web app (the five kinds in D1), and the web app's role cannot alter the record. - The web app's role cannot change an existing credential row's identity, cannot revive a revoked credential, and cannot delete an identity row. - These controls hold whatever select, insert, update, delete and truncate rights a grants script gives the web app's role. - No web deployment environment holds a credential that can remove those controls. @@ -51,7 +51,7 @@ The stated problem was OAuth tokens. The gateway admits five kinds of credential A lock on access tokens alone would leave three silent paths. The web app's role could insert a service credential for any tenant. It could rewrite a service credential's digest or tenant. It could sign a download ticket against any live Home token family, with no insert at all. The lock and the log therefore cover all five kinds, and D8 gives the download ticket a row. -A refresh token never reaches the gateway. It is recorded and locked anyway, because the claim says "every credential" and the cost is one record for each rotation. +A refresh token never reaches the gateway, but the web app exchanges it for an access token that the gateway admits. The claim lists it, and the cost is one record for each rotation. ### D2. Column rights deny the web app's role; guards hold when the rights fail @@ -370,10 +370,10 @@ The first check reads the credential tables' rows of the same period. Those tabl ## What the claim does not cover -The claim is: the database records every credential that the account service issues for a cell, in a log that the account service cannot alter. These limits belong beside it wherever it is published. +The claim is: the database records every credential that the gateway admits from the account service, in a log that the account service cannot alter. Those credentials are OAuth access and refresh tokens, token families, service credentials and download tickets. These limits belong beside it wherever it is published. 1. **Issuance itself, and moving an app.** The account service signs users in. It can sign in as any account and issue a credential. It can also hand a connected app a credential for another tenant: at the app's next refresh, or at once by replacing the app's token row (D3). The log records each such insert. It cannot tell one from the owner's own action, and the record does not name the app's owner. -2. **Operation grants.** The account service signs export, import and deletion grants. Each is stored in its own row, not in this log. An export's grant is written once and the web app's role cannot change it. An import's and a deletion's grant is a column that the web app's role can update. +2. **Operation grants.** The account service signs export, import and deletion grants. The log does not record them. The web app's role can insert an export row with its grant. It cannot delete that row, and it holds no update right on the grant column. It can update an import's grant column. It can write a cell's deletion grant once: the trigger of migration 0084 refuses to replace or clear a stored deletion grant. 3. **Content that passes through the web app.** Home's viewer reads memory through the web app. The web app sees what an owner views there. 4. **Cell images.** The account service's operator interface sets the image that a cell runs. 5. **What a grant allows.** The account service can change a grant's scopes. It can change an app's stored attributes, such as its name, its redirect addresses and whether it is enabled. The grant's tenant, user and app stay fixed. @@ -389,7 +389,7 @@ The claim is: the database records every credential that the account service iss - **A flow that the inventory missed changes a fixed column.** → It fails in production from the merge, because the lock has no switch. The proof runs every flow in the inventory as the web app's role. The schema owner's emergency statement restores the flow, and a commit makes the fix durable. - **The recording trigger fails in production.** → Every token insert fails. The proof runs each insert path through the trigger, and the runbook names the statement that disables it. Disabling it suspends the claim, and the runbook says so. - **The second migration blocks writes to four tables while it writes the older rows' records.** → Token issue, refresh, the Home mint and revocation wait for that transaction (D5). Its length grows with the count of live credential rows. The rollout reads that count before the merge. -- **A migration meets its lock timeout or a deadlock.** → The job fails and records no schema release, so the build does not deploy. The operator starts the job again. +- **A migration meets its lock timeout or a deadlock.** → The job fails and records no schema release, so the build does not deploy. The operator starts the job again. If the production build already failed after its 15-minute wait, the operator redeploys it once the job is green, because nothing rebuilds it. - **A hand-typed grant gives a role the trigger right.** → The lock does not hold against that role until the grants script runs again. The runbook's checks list the grant. - **A hand-typed grant gives a role other than the owner a create right.** → The role may then reach code that runs as the schema owner (D2). The grants script does not revoke the right. The runbook's checks list the right and any schema the role created, and the operator revokes the right and drops the schema. - **The migration job cannot reach the database, or the CI service is down.** → Builds fail after the wait and the previous deployment serves. The operator runs `scripts/migrate.ts` by hand with the credential from the operator's secret store, which also records the schema release. diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/proposal.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/proposal.md index 22bc3f6f..6446d2b9 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/proposal.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/proposal.md @@ -1,11 +1,11 @@ ## Why -Substrate's web app signs users in and issues the credentials that the Exomem Cloud gateway admits. The grants script (`scripts/exomem-cloud-grants.sql`) gives its database role update and delete rights on every table in the schema, OAuth rows included. With them it can re-point a grant to another tenant or overwrite a token's digest with no insert. Nothing records an issuance. The build script (`vercel-build` in `package.json`) runs migrations with the schema-owner connection string, so the build's environment must hold that credential, and a compromised build could also remove any database control. So the privacy page can claim nothing about the account service. This change makes one claim true. The database records every credential that the account service issues for a cell, in a log that the account service cannot alter. The account service also cannot change a credential row's identity or revive a revoked credential. Replacing a credential takes an insert, which the log records. +Substrate's web app signs users in and issues the credentials that the Exomem Cloud gateway admits. The grants script (`scripts/exomem-cloud-grants.sql`) gives its database role update and delete rights on every table in the schema, OAuth rows included. With them it can re-point a grant to another tenant or overwrite a token's digest with no insert. Nothing records an issuance. The build script (`vercel-build` in `package.json`) runs migrations with the schema-owner connection string, so the build's environment must hold that credential, and a compromised build could also remove any database control. So the privacy page can claim nothing about the account service. This change makes one claim true. The database records every credential that the gateway admits from the account service, in a log that the account service cannot alter. Those credentials are OAuth access and refresh tokens, token families, service credentials and download tickets. Export, import and deletion grants are outside the log. The account service also cannot change a credential row's identity or revive a revoked credential. Replacing a credential takes an insert, which the log records. ## What Changes - **Schema releases leave the web build.** A continuous-integration job in a protected environment applies migrations and the grants script for the tip of `main`. It then records a schema release for that commit, and records each overtaken commit as superseded. The production build runs no migration. It waits for its commit's schema release and fails at once when its commit is superseded. The schema-owner credential leaves every web deployment environment, and the operator rotates it. **BREAKING** for the operator: `SKIP_VERCEL_MIGRATE` and the migration procedure that pulls production variables from the web deployment go away. -- **Identity lock.** Guard triggers refuse every change to an identity field of a grant, token family, access token, refresh token, client or service credential. They also refuse a change to a tenant's owner and to a cell's identifier or tenant. A revocation time and a consumption time change only from empty to a time. Guards refuse a delete of a grant, client, tenant, user, cell, service credential or reviewer credential. Each guard holds for every role except the schema owner, whatever select, insert, update, delete and truncate rights that role holds. A guard checks the stored row, so no trigger that runs before it can slip a change past. The web app's database role also keeps update rights only on the columns its flows change. +- **Identity lock.** Guard triggers refuse every change to an identity field of a grant, token family, access token, refresh token, client or service credential. They also refuse a change to a tenant's owner and to a cell's identifier or tenant. A revocation time and a consumption time change only from empty to a time. Guards refuse a delete of a grant, client, tenant, user, cell, service credential or reviewer credential. Each guard holds for every role except the schema owner, whatever select, insert, update, delete and truncate rights that role holds. A guard checks the stored row, so no trigger that runs before it can slip a change past. On the five column-locked tables that the grants script narrows (grants, token families, access tokens, refresh tokens and service credentials), the web app's database role also keeps update rights only on the columns its flows change. - **The trigger right stays with the schema owner.** A role that holds the trigger right on a table can run its own code as the schema owner, and no guard holds against that. The grants script therefore revokes that right on every table in the schema from every other role, on every run. `PUBLIC` holds no execute right on the functions that this change adds. Every function that the database can run as the schema owner for another role pins its search path, so a role's own operator cannot run in place of the built-in one. - **No switch.** The lock and the log are in force once the migrations apply. Relaxing either one takes a migration or a grants change, which is a reviewed commit. - **Issuance log.** An owner-owned trigger writes one record for every access token, refresh token, token family, service credential and download ticket row, in the inserting transaction. The log refuses every write that the schema owner does not run. A read-only audit role reads it in bounded ranges. A record is kept until 90 days after its credential expires or, for a service credential, which has no expiry, until 90 days after it is revoked or its row is deleted. A token family's record can therefore last up to its 365-day expiry plus 90 days. Records also outlive account deletion for that window, because no flow but the schema owner deletes a record. diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md index d5393214..0b432119 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md @@ -101,7 +101,7 @@ This requirement binds every role except the schema owner. The database SHALL re ### Requirement: The web app's database role holds only the OAuth rights its flows need -The web app's database role SHALL hold update rights only on the columns its flows change. It SHALL hold no delete right on grants, clients, tenants, users or reviewer credentials. The grants script SHALL apply these rights on every run, and a second run SHALL change nothing. The gateway's and the controller's rights on these tables SHALL stay as they were. +On the grants, token families, access tokens, refresh tokens and service credentials tables, the web app's database role SHALL hold update rights only on the columns its flows change. It SHALL hold no delete right on grants, clients, tenants, users or reviewer credentials. The grants script SHALL apply these rights on every run, and a second run SHALL change nothing. The gateway's and the controller's rights on these tables SHALL stay as they were. #### Scenario: The rights are exact diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md index 0027f2b6..0fe83997 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md @@ -219,8 +219,11 @@ without truncate. Neither state holds the trigger right. the write-ahead-log bytes for each mint, and the measured size of a record. Report `EXPLAIN (ANALYZE, BUFFERS)` of one prune call and of each D12 read. Pass: the median rises by less than one millisecond, the prune reads only - what it deletes, and no D12 read scans the whole log. Put the outputs in the - PR. + what it deletes, and no D12 read scans the whole log. Evidence: the run's + outputs are kept as a private record outside this public repository. They + are the median and the 95th percentile of the mint latency with and without + the triggers, the write-ahead-log bytes for each mint, the size of a record, + and the `EXPLAIN` plans. The run met the latency part of the pass condition. - [ ] 5.9 Add the new suites to the PostgreSQL integration list in `.github/workflows/test.yml`. Verify: CI runs them. @@ -230,9 +233,9 @@ without truncate. Neither state holds the trigger right. build-time migration section. Describe the migration job, the manual run with the operator's own copy of the credential and a named commit, and `SKIP_SCHEMA_RELEASE_WAIT`. Say that a migration that meets its lock timeout - or a deadlock fails the job, and that the operator starts the job again. Remove - `SKIP_VERCEL_MIGRATE` and the procedure that pulls production variables to a - local file. + or a deadlock fails the job, and that the operator starts the job again and + redeploys a production build that already failed. Remove `SKIP_VERCEL_MIGRATE` + and the procedure that pulls production variables to a local file. - [x] 6.2 `docs/runbooks/exomem-cloud-operations.md`: what the lock refuses, and each emergency statement with what it suspends. The issuance log: the D12 checks as the audit role, with the hour that each run reads again, a @@ -287,13 +290,25 @@ and its date. PostgreSQL major version as CI, so the foreign-key test of D2 holds there. Read the count of live credential rows, which sets how long the second migration blocks writes to the token and service - credential tables. Create the audit role. Evidence: the catalog queries' - outcome. Fix any failure before step 7.5. + credential tables. Create the audit role as the schema owner or another role + that holds the role-creation right: `CREATE ROLE substrate_audit LOGIN + NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION;`, then set its password + with `\password substrate_audit` in `psql` and store it in the operator's + secret store. The role needs the connect right on the database, which + `PUBLIC` holds unless the operator revoked it. If the operator revoked it, + run `GRANT CONNECT ON DATABASE TO substrate_audit;`. The role + needs no other right and no membership in any role. The grants script gives + it the select on the log and on the columns that the D12 checks compare + when the merge's job runs. The catalog checks read `pg_catalog`, which + every role can read. Evidence: the catalog queries' outcome. Fix any + failure before step 7.5. - [ ] 7.5 Approve the merge of the implementation PR. The merge applies the migrations to production. The lock and the log are in force from that moment, and the web app starts to store ticket rows. If a migration meets - its lock timeout or a deadlock, start the job again. Evidence: the job is green, the merge - commit has a schema release, and the production build read it and deployed. + its lock timeout or a deadlock, start the job again. If the production build + already failed, redeploy it after the job is green. Evidence: the job is + green, the merge commit has a schema release, and the production build read + it and deployed. - [ ] 7.6 Read the log and run the flows once. Sign in, connect an app, wait for one token refresh, open Home, download a file, disconnect the app, and see one maintenance run succeed. Run the D12 checks as the audit role. From 2b27bcc4b7415c86add337da5d8753df02549743 Mon Sep 17 00:00:00 2001 From: Artexis10 Date: Wed, 2 Dec 2026 11:36:10 +0000 Subject: [PATCH 12/29] Scope the lock and recording requirements, state retention bounds and the unscheduled checks The two OAuth requirements now name the table rights they hold against and point to the limit that lists what can still change the lock. Retention states the session policy's expiry bounds and that the database bounds no expiry. The limits add reviewer credentials, which the web app's role can still revive, and the manual running of the log checks. The Home mint proof note keeps its outputs in a private record. --- docs/runbooks/exomem-cloud-operations.md | 6 ++++-- .../design.md | 11 +++++++---- .../proposal.md | 4 ++-- .../specs/exomem-hosted-mcp-oauth/spec.md | 4 ++-- .../tasks.md | 2 +- 5 files changed, 16 insertions(+), 11 deletions(-) diff --git a/docs/runbooks/exomem-cloud-operations.md b/docs/runbooks/exomem-cloud-operations.md index 5c207314..16bb3991 100644 --- a/docs/runbooks/exomem-cloud-operations.md +++ b/docs/runbooks/exomem-cloud-operations.md @@ -858,8 +858,10 @@ The recording fails closed. A credential insert fails when its record cannot be write or alter the log. The reconcile job calls `exomem_prune_issuance_log()` once a run. The function deletes at most 10,000 records whose credential expired, or ended, more than 90 days ago. A service credential has no expiry. Its record stays open while the credential is live, and the prune never deletes it. When the credential is revoked, or its -row is deleted, the record's end becomes the database clock's time, and the prune deletes it 90 days later. A token -family's record lasts up to its 365-day expiry plus 90 days. A record outlives its account for the same time, because +row is deleted, the record's end becomes the database clock's time, and the prune deletes it 90 days later. The +session policy sets a token family's expiry, `EXOMEM_OAUTH_SESSION_MAX_DAYS` after sign-in (365 days by default, at most 730), and a refresh +token's expiry, `EXOMEM_OAUTH_REFRESH_IDLE_DAYS` (30 days by default, at most 90). The database bounds no expiry, so a role that +writes a far expiry only lengthens retention. A record outlives its account for the same time, because only the schema owner deletes a record. The job's response reports the deleted counts as `issuancePruned.records` and `issuancePruned.tickets`. A value of `null` means that part failed, and the log line `exomem-issuance: log retention failed` names it. diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md index 3ac9289b..63614e6b 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md @@ -23,7 +23,7 @@ Load target: `openspec/project.md` records 10,000 tenants. Neither `docs/runbook **Goals** - The database records every credential that the gateway admits from the web app (the five kinds in D1), and the web app's role cannot alter the record. -- The web app's role cannot change an existing credential row's identity, cannot revive a revoked credential, and cannot delete an identity row. +- On the column-locked tables, the web app's role cannot change an existing credential row's identity or revive a revoked credential. It cannot delete an identity row. - These controls hold whatever select, insert, update, delete and truncate rights a grants script gives the web app's role. - No web deployment environment holds a credential that can remove those controls. - Every flow that exists today keeps working, on the release that serves during a deploy too. @@ -207,7 +207,7 @@ The recording fails closed: when the record cannot be written, the credential in ### D6. Records are kept until 90 days after the credential expires or ends -A record is deleted once its credential expired, or ended, more than 90 days ago. A token family lives up to its session maximum, 365 days by default, so its record lives up to that plus 90 days. +A record is deleted once its credential expired, or ended, more than 90 days ago. A record therefore lasts until 90 days after its credential's expiry. The session policy sets the expiry: a token family lasts `EXOMEM_OAUTH_SESSION_MAX_DAYS` from sign-in, 365 days by default and at most 730 (`src/lib/exomem-hosted/oauth-session-policy.ts`). A refresh token lasts `EXOMEM_OAUTH_REFRESH_IDLE_DAYS`, 30 days by default and at most 90, and never past its family's expiry. An access token lasts one hour, also never past its family's expiry. The database bounds no expiry, so a role that writes a far expiry only lengthens retention. A service credential has no expiry. Its record has no end while the credential is live, and the prune never deletes it. When the credential is revoked, or its row is deleted, the recording function sets the record's end to the database clock's time. It runs from an update trigger on the revocation time and a delete trigger, and it sets a record's end once. The prune then deletes the record 90 days later. The function reads the clock, not the row's `revoked_at`. The web app's role writes that column, and a past time would bring the prune forward and erase the record of a credential that the role issued. A partial index on the credential's identifier, which holds only service credential records, finds the record. A token insert pays nothing for it. For a revoked credential that exists when the migration runs, the record's end is the migration's time. @@ -251,7 +251,7 @@ Proof, on a disposable PostgreSQL: - **Instrument.** `pgbench` runs the Home mint transaction's statements as a custom script, over generated data for 10,000 tenants. The same script runs with and without this change's triggers, five runs each, on the same machine and data. - **Size.** The log holds 10 million generated records. That is enough, because every insert lands at the right edge of an index, or at the right edge of one tenant's range. The pages that an insert touches stay in memory at any log size. -- **Result.** The PR reports the median and the 95th percentile of the transaction's latency for both arms, and the write-ahead-log bytes for each mint. The median must rise by less than one millisecond. +- **Result.** The run's outputs are kept as a private record outside this repository, and task 5.8 states the outcome. The median must rise by less than one millisecond. - **Plans.** `EXPLAIN (ANALYZE, BUFFERS)` of one prune call shows that it reads only the records it deletes. The same output for each read of D12 shows an index range and no full scan. ### D8. A download ticket gets a stored row @@ -379,10 +379,12 @@ The claim is: the database records every credential that the gateway admits from 5. **What a grant allows.** The account service can change a grant's scopes. It can change an app's stored attributes, such as its name, its redirect addresses and whether it is enabled. The grant's tenant, user and app stay fixed. 6. **Suspension and blocks.** The account service sets a tenant's status and can add or remove an account block. 7. **The schema owner, the trigger right and the create right.** Whoever holds the schema-owner credential, administers the database server, or lands a commit on `main` can change the lock and the log. So can a role that holds the trigger right on a table in the schema, or a create right on the database or on a schema (D2). So can an administrator of the repository: they can edit the protected environment or the ruleset and run code with the schema-owner credential without landing a commit. The rollout turns off the administrators' bypass of the environment's rules, which narrows that path but does not remove it. Each change through `main` is a public commit. -8. **Retention.** The log keeps a record until 90 days after its credential expires. For a service credential, which has no expiry, that is 90 days after it is revoked or its row is deleted. A token family lives up to 365 days, so its record can last up to 365 plus 90 days. Records also outlive account deletion for that window: no flow but the schema owner deletes a record, and deleting an account does not. +8. **Retention.** The log keeps a record until 90 days after its credential expires. For a service credential, which has no expiry, that is 90 days after it is revoked or its row is deleted. The session policy sets a token family's expiry: 365 days from sign-in by default, at most 730. It sets a refresh token's expiry from its idle window, 30 days by default, at most 90, never past its family's expiry. The database bounds no expiry, so a role that writes a far expiry only lengthens retention. Records also outlive account deletion for that window: no flow but the schema owner deletes a record, and deleting an account does not. 9. **Use, revocation and deletion.** The log records issuance only. It does not say when a credential was used, revoked or deleted. 10. **The gateway's own keys.** The gateway signs cell tokens and upload capsules with its own keys. In this repository only gateway code loads them. Other services may hold them, and this change does not record what they sign. The rollout checks that no web deployment environment holds those keys. 11. **Credentials that the web app admits itself.** The web app issues and checks its own browser sessions. It does the same for the possession grants and sessions of the access record (`exomem_cloud_access_grants`, `exomem_cloud_access_sessions`). The gateway admits none of them, and the log records none. +12. **Reviewer credentials.** The web app's role keeps update rights on every column of `exomem_marketplace_reviewer_credentials`. An existing guard fixes only its lineage columns: kind, candidate, assignment, assignment generation, staged client release and OAuth client. The role can therefore clear a reviewer credential's revocation time and revive it. The gateway then admits that credential's unrevoked families and tokens again. Their records exist from their inserts. +13. **Detection is manual.** The operator runs the runbook's checks. Nothing schedules them yet. Detecting a disabled recording trigger or a grant mismatch is therefore best-effort until a scheduled job runs them, which is a later step. ## Risks / Trade-offs @@ -398,6 +400,7 @@ The claim is: the database records every credential that the gateway admits from - **The gateway release rolls too early.** → A ticket signed before the web release is refused for the rest of its life. The owner asks for the download again. The task states the wait. - **Each deploy waits for the migration job.** → A deploy takes longer by the job's run time. The job installs dependencies and connects once. - **The schema owner's exemption hides a broken flow in ordinary tests.** → Most suites run as the role that owns the schema, so a guard never refuses them. Only the suites that connect as the web app's role prove the flows. +- **Nothing runs the D12 checks.** → The operator runs the runbook's checks. Nothing schedules them yet, so detecting a disabled recording trigger or a grant mismatch is best-effort until a scheduled job runs them. That job is a later step. ## Migration Plan diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/proposal.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/proposal.md index 6446d2b9..d6514133 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/proposal.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/proposal.md @@ -1,6 +1,6 @@ ## Why -Substrate's web app signs users in and issues the credentials that the Exomem Cloud gateway admits. The grants script (`scripts/exomem-cloud-grants.sql`) gives its database role update and delete rights on every table in the schema, OAuth rows included. With them it can re-point a grant to another tenant or overwrite a token's digest with no insert. Nothing records an issuance. The build script (`vercel-build` in `package.json`) runs migrations with the schema-owner connection string, so the build's environment must hold that credential, and a compromised build could also remove any database control. So the privacy page can claim nothing about the account service. This change makes one claim true. The database records every credential that the gateway admits from the account service, in a log that the account service cannot alter. Those credentials are OAuth access and refresh tokens, token families, service credentials and download tickets. Export, import and deletion grants are outside the log. The account service also cannot change a credential row's identity or revive a revoked credential. Replacing a credential takes an insert, which the log records. +Substrate's web app signs users in and issues the credentials that the Exomem Cloud gateway admits. The grants script (`scripts/exomem-cloud-grants.sql`) gives its database role update and delete rights on every table in the schema, OAuth rows included. With them it can re-point a grant to another tenant or overwrite a token's digest with no insert. Nothing records an issuance. The build script (`vercel-build` in `package.json`) runs migrations with the schema-owner connection string, so the build's environment must hold that credential, and a compromised build could also remove any database control. So the privacy page can claim nothing about the account service. This change makes one claim true. The database records every credential that the gateway admits from the account service, in a log that the account service cannot alter. Those credentials are OAuth access and refresh tokens, token families, service credentials and download tickets. Export, import and deletion grants are outside the log. On the column-locked tables, the account service also cannot change a credential row's identity or revive a revoked credential. Reviewer credentials stay writable by the web app's role (design limit 12). Replacing a credential takes an insert, which the log records. ## What Changes @@ -8,7 +8,7 @@ Substrate's web app signs users in and issues the credentials that the Exomem Cl - **Identity lock.** Guard triggers refuse every change to an identity field of a grant, token family, access token, refresh token, client or service credential. They also refuse a change to a tenant's owner and to a cell's identifier or tenant. A revocation time and a consumption time change only from empty to a time. Guards refuse a delete of a grant, client, tenant, user, cell, service credential or reviewer credential. Each guard holds for every role except the schema owner, whatever select, insert, update, delete and truncate rights that role holds. A guard checks the stored row, so no trigger that runs before it can slip a change past. On the five column-locked tables that the grants script narrows (grants, token families, access tokens, refresh tokens and service credentials), the web app's database role also keeps update rights only on the columns its flows change. - **The trigger right stays with the schema owner.** A role that holds the trigger right on a table can run its own code as the schema owner, and no guard holds against that. The grants script therefore revokes that right on every table in the schema from every other role, on every run. `PUBLIC` holds no execute right on the functions that this change adds. Every function that the database can run as the schema owner for another role pins its search path, so a role's own operator cannot run in place of the built-in one. - **No switch.** The lock and the log are in force once the migrations apply. Relaxing either one takes a migration or a grants change, which is a reviewed commit. -- **Issuance log.** An owner-owned trigger writes one record for every access token, refresh token, token family, service credential and download ticket row, in the inserting transaction. The log refuses every write that the schema owner does not run. A read-only audit role reads it in bounded ranges. A record is kept until 90 days after its credential expires or, for a service credential, which has no expiry, until 90 days after it is revoked or its row is deleted. A token family's record can therefore last up to its 365-day expiry plus 90 days. Records also outlive account deletion for that window, because no flow but the schema owner deletes a record. +- **Issuance log.** An owner-owned trigger writes one record for every access token, refresh token, token family, service credential and download ticket row, in the inserting transaction. The log refuses every write that the schema owner does not run. A read-only audit role reads it in bounded ranges. A record is kept until 90 days after its credential expires or, for a service credential, which has no expiry, until 90 days after it is revoked or its row is deleted. The session policy sets a token family's expiry (365 days from sign-in by default, at most 730) and a refresh token's expiry (30 days idle by default, at most 90, never past its family's expiry). The database bounds no expiry, so a role that writes a far expiry only lengthens retention. Records also outlive account deletion for that window, because no flow but the schema owner deletes a record. - **Download tickets get a stored row.** A download ticket is a credential that the web app signs with a key it holds. Today no row backs it. The web app now stores one row for each ticket, and the gateway refuses a ticket without its row. - **Proof as the real roles.** Tests on a disposable PostgreSQL run every legitimate flow as the web app's role. They run each attack as that role twice: with the new rights, and with select, insert, update, delete and truncate on every table. diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md index 0b432119..1e409818 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md @@ -2,7 +2,7 @@ ### Requirement: OAuth identity fields are unchangeable once written -This requirement binds every role except the schema owner. The database SHALL refuse every change to an identity field of an OAuth grant, token family, access token, refresh token or client, to a tenant's owner, and to a cell's identifier or tenant. It SHALL let a revocation time and a consumption time change only from empty to a time. It SHALL refuse a delete of a grant, client, tenant, user, reviewer credential or cell. Each refusal SHALL hold whatever table rights the role holds. +The database SHALL refuse any change to an identity field of a grant, token family, access token, refresh token or client, a tenant's owner, and a cell's identifier or tenant. A revocation or consumption time SHALL change only from empty to a time. It SHALL refuse a delete of a grant, client, tenant, user, reviewer credential or cell. Each refusal SHALL bind all roles but the schema owner, whatever select, insert, update, delete and truncate rights they hold. Design limit 7 lists exceptions. #### Scenario: A cell is re-pointed @@ -169,7 +169,7 @@ The grants script SHALL revoke the trigger right on every table in the schema fr ### Requirement: Every issued credential is recorded -The database SHALL write one issuance record for every access token, refresh token, token family, service credential and download ticket row. It SHALL write the record in the transaction that inserts the row. A credential row SHALL NOT be inserted without its record. No role except the schema owner SHALL be able to stop the recording. +The database SHALL write one issuance record for every access token, refresh token, token family, service credential and download ticket row. It SHALL write the record in the transaction that inserts the row. A credential row SHALL NOT be inserted without its record. Whatever select, insert, update, delete and truncate rights a role holds, no role except the schema owner SHALL be able to stop the recording. Design limit 7 lists what else can. #### Scenario: Home mints an access token diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md index 0fe83997..d43b9ebb 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md @@ -223,7 +223,7 @@ without truncate. Neither state holds the trigger right. outputs are kept as a private record outside this public repository. They are the median and the 95th percentile of the mint latency with and without the triggers, the write-ahead-log bytes for each mint, the size of a record, - and the `EXPLAIN` plans. The run met the latency part of the pass condition. + and the `EXPLAIN` plans. The run met each part of the pass condition. - [ ] 5.9 Add the new suites to the PostgreSQL integration list in `.github/workflows/test.yml`. Verify: CI runs them. From 9a484790d7bf4db8f66a4489dd6b05f31327d9c0 Mon Sep 17 00:00:00 2001 From: Artexis10 Date: Wed, 2 Dec 2026 12:08:59 +0000 Subject: [PATCH 13/29] End token family records at revocation or deletion, and prune the issuance log whatever the other lanes do A token family's record now ends at the database clock when the family is revoked or its row is deleted, an account's deletion included, like a service credential's record. Both kinds keep their record 90 days from then. A partial index on the family records finds the record, and the backfill ends the record of a family that is already revoked. The reconcile route now runs the issuance prune as a lane beside the others, so a failure in another lane no longer skips it. A prune part that fails fails the response, and the response carries the counts or null for a failed part in both the success and the failure case. The proposal, design, spec, tasks and runbook state the retention bound after an account's deletion, from the session policy's refresh idle window. --- docs/runbooks/exomem-cloud-operations.md | 21 ++-- ...omem_issuance_log_and_download_tickets.sql | 67 ++++++++--- .../design.md | 10 +- .../proposal.md | 4 +- .../specs/exomem-hosted-mcp-oauth/spec.md | 19 ++- .../tasks.md | 18 +-- .../exomem-reconcile/__tests__/route.test.ts | 40 ++++++- src/app/api/cron/exomem-reconcile/route.ts | 64 ++++++---- ...-issuance-log-postgres.integration.test.ts | 112 ++++++++++++++++++ src/lib/exomem-hosted/issuance-maintenance.ts | 2 +- 10 files changed, 295 insertions(+), 62 deletions(-) diff --git a/docs/runbooks/exomem-cloud-operations.md b/docs/runbooks/exomem-cloud-operations.md index 16bb3991..e0be73e7 100644 --- a/docs/runbooks/exomem-cloud-operations.md +++ b/docs/runbooks/exomem-cloud-operations.md @@ -834,9 +834,11 @@ The recording triggers are `exomem_oauth_token_families_issuance_record`, `exome `exomem_oauth_refresh_tokens_issuance_record`, `exomem_cloud_service_credentials_issuance_record` and `exomem_cloud_download_tickets_issuance_record`. Each one sits on the table that its name gives. -Two more triggers on `exomem_cloud_service_credentials`, `exomem_cloud_service_credentials_issuance_end_revoke` and -`exomem_cloud_service_credentials_issuance_end_delete`, end a record when its credential is revoked or its row is -deleted. While they are off, that record stays open and the prune never deletes it. +Four more triggers end a record when its credential is revoked or its row is deleted: `exomem_cloud_service_credentials_issuance_end_revoke` +and `exomem_cloud_service_credentials_issuance_end_delete` on `exomem_cloud_service_credentials`, and +`exomem_oauth_token_families_issuance_end_revoke` and `exomem_oauth_token_families_issuance_end_delete` on +`exomem_oauth_token_families`. While they are off, a service credential's record stays open and the prune never deletes it. +A token family's record then keeps its expiry. A hand-typed grant or a disabled trigger is an emergency state, not a fix. After either statement: @@ -858,13 +860,16 @@ The recording fails closed. A credential insert fails when its record cannot be write or alter the log. The reconcile job calls `exomem_prune_issuance_log()` once a run. The function deletes at most 10,000 records whose credential expired, or ended, more than 90 days ago. A service credential has no expiry. Its record stays open while the credential is live, and the prune never deletes it. When the credential is revoked, or its -row is deleted, the record's end becomes the database clock's time, and the prune deletes it 90 days later. The +row is deleted, the record's end becomes the database clock's time, and the prune deletes it 90 days later. A token +family's record ends the same way when the family is revoked or deleted, if that is before its expiry. The session policy sets a token family's expiry, `EXOMEM_OAUTH_SESSION_MAX_DAYS` after sign-in (365 days by default, at most 730), and a refresh token's expiry, `EXOMEM_OAUTH_REFRESH_IDLE_DAYS` (30 days by default, at most 90). The database bounds no expiry, so a role that -writes a far expiry only lengthens retention. A record outlives its account for the same time, because -only the schema owner deletes a record. The job's response reports the deleted counts as `issuancePruned.records` and +writes a far expiry only lengthens retention. After an account's deletion, a token family's record and a service credential's +record last 90 days, and an access token's or a refresh token's record lasts until 90 days after its own expiry. The longest +window after deletion is the refresh idle bound plus 90 days: 120 days by default, 180 at most. Only the schema owner deletes a record. The job's response reports the deleted counts as `issuancePruned.records` and `issuancePruned.tickets`. A value of `null` means that part failed, and the log line `exomem-issuance: log retention -failed` names it. +failed` names it. A failed part makes the job answer `503`, and the answer still carries `issuancePruned`. The prune runs +whatever the other lanes do. #### Read it as the audit role @@ -985,6 +990,8 @@ FROM (VALUES ('exomem_cloud_issuance_log', 'exomem_cloud_issuance_log_owner_only_truncate'), ('exomem_cloud_download_tickets', 'exomem_cloud_download_tickets_update_lock'), ('exomem_oauth_token_families', 'exomem_oauth_token_families_issuance_record'), + ('exomem_oauth_token_families', 'exomem_oauth_token_families_issuance_end_revoke'), + ('exomem_oauth_token_families', 'exomem_oauth_token_families_issuance_end_delete'), ('exomem_oauth_access_tokens', 'exomem_oauth_access_tokens_issuance_record'), ('exomem_oauth_refresh_tokens', 'exomem_oauth_refresh_tokens_issuance_record'), ('exomem_cloud_service_credentials', 'exomem_cloud_service_credentials_issuance_record'), diff --git a/migrations/0102_exomem_issuance_log_and_download_tickets.sql b/migrations/0102_exomem_issuance_log_and_download_tickets.sql index 26ab9dcc..6be6fcb9 100644 --- a/migrations/0102_exomem_issuance_log_and_download_tickets.sql +++ b/migrations/0102_exomem_issuance_log_and_download_tickets.sql @@ -38,10 +38,13 @@ CREATE TABLE exomem_cloud_issuance_log ( client_id uuid, tenant_id uuid NOT NULL, user_id uuid NOT NULL, - -- When the credential expires, so the prune keeps the record until 90 days after. - -- A service credential has no expiry: its record takes the time the credential - -- ends, by the database clock, when it is revoked or its row is deleted. Empty - -- while that credential is live, and the prune never deletes an empty one. + -- When the credential stops being usable, so the prune keeps the record until + -- 90 days after. A token family, an access token, a refresh token and a download + -- ticket take their expiry. A token family that is revoked or deleted before it + -- expires moves to the database clock's time. A service credential has no + -- expiry: its record takes the time the credential ends, by the database clock, + -- when it is revoked or its row is deleted. Empty while that credential is + -- live, and the prune never deletes an empty one. expires_at timestamptz, -- The role that connected (session_user), not the owner that the recording -- function runs as. @@ -52,10 +55,13 @@ CREATE TABLE exomem_cloud_issuance_log ( -- The prune reads by expiry, and one tenant's records list newest first. CREATE INDEX exomem_cloud_issuance_log_expires_idx ON exomem_cloud_issuance_log (expires_at); CREATE INDEX exomem_cloud_issuance_log_tenant_idx ON exomem_cloud_issuance_log (tenant_id, id); --- Ending a service credential finds its record by the credential's identifier. --- The index holds only those records, so a token insert does not pay for it. +-- Ending a service credential or a token family finds its record by the credential's +-- identifier. Each index holds only one kind's records, so an access or refresh +-- token insert, which is most of the log, does not pay for either. CREATE INDEX exomem_cloud_issuance_log_service_credential_idx ON exomem_cloud_issuance_log (credential_id) WHERE credential_kind = 'service_credential'; +CREATE INDEX exomem_cloud_issuance_log_token_family_idx + ON exomem_cloud_issuance_log (credential_id) WHERE credential_kind = 'token_family'; -- The log refuses every writer that is not the schema owner, whatever rights -- the writer holds. The recording and prune functions run as the schema owner. @@ -139,15 +145,25 @@ BEGIN the_user uuid; the_expiry timestamptz; BEGIN - -- The end of a service credential: its revocation or the delete of its row. - -- The record takes the database clock, not the row's revoked_at, which the - -- web app's role writes and could set in the past to bring the prune forward. - -- A record that already has a time keeps it. + -- The end of a credential: the revocation or the delete of its row. The record + -- takes the database clock, not the row's revoked_at, which the web app's role + -- writes and could set in the past to bring the prune forward. A revocation + -- is one-way, so it cannot end a live credential's record early. A record keeps + -- an end that is already in the past. Each kind has its own statement, with + -- the kind as a literal, because only a literal lets the planner use that + -- kind's partial index in a plan that is reused across calls. IF TG_OP <> 'INSERT' THEN - UPDATE %1$I.exomem_cloud_issuance_log AS record - SET expires_at = pg_catalog.now() - WHERE record.credential_kind = 'service_credential' - AND record.credential_id = OLD.id AND record.expires_at IS NULL; + IF kind = 'service_credential' THEN + UPDATE %1$I.exomem_cloud_issuance_log AS record + SET expires_at = pg_catalog.now() + WHERE record.credential_kind = 'service_credential' + AND record.credential_id = OLD.id AND record.expires_at IS NULL; + ELSIF kind = 'token_family' THEN + UPDATE %1$I.exomem_cloud_issuance_log AS record + SET expires_at = pg_catalog.now() + WHERE record.credential_kind = 'token_family' + AND record.credential_id = OLD.id AND record.expires_at > pg_catalog.now(); + END IF; RETURN NULL; END IF; @@ -190,10 +206,11 @@ BEGIN $body$; $definition$, target_schema); - -- A record is kept until 90 days after its credential expires, or for a - -- service credential, ends. The 90 days is a constant here, not a setting: - -- changing it takes a migration. A record of a live service credential never matches. One call deletes at most - -- 10000 records, so the reconcile job's call stays short. + -- A record is kept until 90 days after its credential expires, or ends: a token + -- family that is revoked or deleted, and a service credential. The 90 days is a + -- constant here, not a setting: changing it takes a migration. A record of a live + -- service credential never matches. One call deletes at most 10000 records, so + -- the reconcile job's call stays short. EXECUTE format($definition$ CREATE FUNCTION %1$I.exomem_prune_issuance_log() RETURNS integer LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp @@ -241,6 +258,14 @@ CREATE TRIGGER exomem_cloud_service_credentials_issuance_record FOR EACH ROW EXECUTE FUNCTION exomem_record_issuance('service_credential'); -- The same function ends the record when the credential ends. A WHEN clause -- cannot read NEW in a delete trigger, so a revocation and a delete get one trigger each. +-- A delete that the account's deletion cascades to fires the delete trigger too. +CREATE TRIGGER exomem_oauth_token_families_issuance_end_revoke + AFTER UPDATE ON exomem_oauth_token_families + FOR EACH ROW WHEN (OLD.revoked_at IS NULL AND NEW.revoked_at IS NOT NULL) + EXECUTE FUNCTION exomem_record_issuance('token_family'); +CREATE TRIGGER exomem_oauth_token_families_issuance_end_delete + AFTER DELETE ON exomem_oauth_token_families + FOR EACH ROW EXECUTE FUNCTION exomem_record_issuance('token_family'); CREATE TRIGGER exomem_cloud_service_credentials_issuance_end_revoke AFTER UPDATE ON exomem_cloud_service_credentials FOR EACH ROW WHEN (OLD.revoked_at IS NULL AND NEW.revoked_at IS NOT NULL) @@ -259,8 +284,12 @@ INSERT INTO exomem_cloud_issuance_log ( credential_kind, credential_id, grant_id, family_id, client_id, tenant_id, user_id, expires_at, database_role, backfilled ) +-- A family that is revoked already ends at the migration's time, unless it expired earlier. SELECT 'token_family', family.id, family.grant_id, family.id, family.client_id, - grant_row.tenant_id, grant_row.user_id, family.expires_at, current_user, true + grant_row.tenant_id, grant_row.user_id, + CASE WHEN family.revoked_at IS NOT NULL + THEN least(family.expires_at, pg_catalog.now()) ELSE family.expires_at END, + current_user, true FROM exomem_oauth_token_families AS family JOIN exomem_oauth_grants AS grant_row ON grant_row.id = family.grant_id; diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md index 63614e6b..db90df14 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md @@ -207,13 +207,17 @@ The recording fails closed: when the record cannot be written, the credential in ### D6. Records are kept until 90 days after the credential expires or ends -A record is deleted once its credential expired, or ended, more than 90 days ago. A record therefore lasts until 90 days after its credential's expiry. The session policy sets the expiry: a token family lasts `EXOMEM_OAUTH_SESSION_MAX_DAYS` from sign-in, 365 days by default and at most 730 (`src/lib/exomem-hosted/oauth-session-policy.ts`). A refresh token lasts `EXOMEM_OAUTH_REFRESH_IDLE_DAYS`, 30 days by default and at most 90, and never past its family's expiry. An access token lasts one hour, also never past its family's expiry. The database bounds no expiry, so a role that writes a far expiry only lengthens retention. +A record is deleted once its credential expired, or ended, more than 90 days ago. A token family and a service credential end when they are revoked or their row is deleted. The session policy sets the expiry: a token family lasts `EXOMEM_OAUTH_SESSION_MAX_DAYS` from sign-in, 365 days by default and at most 730 (`src/lib/exomem-hosted/oauth-session-policy.ts`). A refresh token lasts `EXOMEM_OAUTH_REFRESH_IDLE_DAYS`, 30 days by default and at most 90, and never past its family's expiry. An access token lasts one hour, also never past its family's expiry. The database bounds no expiry, so a role that writes a far expiry only lengthens retention. A service credential has no expiry. Its record has no end while the credential is live, and the prune never deletes it. When the credential is revoked, or its row is deleted, the recording function sets the record's end to the database clock's time. It runs from an update trigger on the revocation time and a delete trigger, and it sets a record's end once. The prune then deletes the record 90 days later. The function reads the clock, not the row's `revoked_at`. The web app's role writes that column, and a past time would bring the prune forward and erase the record of a credential that the role issued. A partial index on the credential's identifier, which holds only service credential records, finds the record. A token insert pays nothing for it. For a revoked credential that exists when the migration runs, the record's end is the migration's time. +A token family's record holds the family's expiry from the insert. The same recording function moves it to the database clock's time when the family is revoked or its row is deleted, if that is earlier. An update trigger on the revocation time and a delete trigger run it, and a delete that an account's deletion cascades to runs it too. The function reads the clock, not the row's `revoked_at`, for the same reason as above. A revocation is one-way, and a revoked family cannot be used, so the web app's role cannot end a live family's record early. A partial index on the credential's identifier, which holds only token family records, finds the record. An access token or refresh token insert pays nothing for it, and a family insert pays one more index entry. For a family that is revoked when the migration runs, the record's end is the migration's time, unless the family expired earlier. An access token's and a refresh token's record do not end early. Each keeps its own expiry. + +After an account's deletion, a token family's record and a service credential's record last 90 days. An access token's record lasts until 90 days after its own expiry, which is an hour at most from its issue. A refresh token's record lasts until 90 days after its own expiry, which is the idle window at most from its issue: 30 days by default, at most 90. The longest window after deletion is therefore the refresh token's idle bound plus 90 days, which is 120 days by default and 180 at most. A download ticket's record lasts a day plus 90 days at most. + The expiry is safe to key on. It is set at insert and is a fixed column afterwards. A credential cannot be used after its expiry, so no usable credential loses its record early. -A prune function deletes the records. The schema owner owns it, and it is `SECURITY DEFINER` with the same `search_path` rule as the recording function. Of the roles granted the right to execute it, only the web app's role is one. Each call deletes at most 10,000 records. The reconcile job calls it once a run, beside the OAuth maintenance. At one run a minute it can delete 14.4 million records a day. D7 estimates 1.5 million new records a day at the load target. A backlog from a week without the job clears in about a day. +A prune function deletes the records. The schema owner owns it, and it is `SECURITY DEFINER` with the same `search_path` rule as the recording function. Of the roles granted the right to execute it, only the web app's role is one. Each call deletes at most 10,000 records. The reconcile job calls it once a run as a lane of its own, beside the OAuth maintenance. Another lane's failure does not stop it. A part of it that fails is reported as `null` and fails the job's response with `503`, which carries the counts. At one run a minute it can delete 14.4 million records a day. D7 estimates 1.5 million new records a day at the load target. A backlog from a week without the job clears in about a day. The web app's role may call the function at any time, and it still deletes only records past their retention. The 90 days is a constant inside the function, not a setting: changing it needs a migration, which is a public commit. @@ -379,7 +383,7 @@ The claim is: the database records every credential that the gateway admits from 5. **What a grant allows.** The account service can change a grant's scopes. It can change an app's stored attributes, such as its name, its redirect addresses and whether it is enabled. The grant's tenant, user and app stay fixed. 6. **Suspension and blocks.** The account service sets a tenant's status and can add or remove an account block. 7. **The schema owner, the trigger right and the create right.** Whoever holds the schema-owner credential, administers the database server, or lands a commit on `main` can change the lock and the log. So can a role that holds the trigger right on a table in the schema, or a create right on the database or on a schema (D2). So can an administrator of the repository: they can edit the protected environment or the ruleset and run code with the schema-owner credential without landing a commit. The rollout turns off the administrators' bypass of the environment's rules, which narrows that path but does not remove it. Each change through `main` is a public commit. -8. **Retention.** The log keeps a record until 90 days after its credential expires. For a service credential, which has no expiry, that is 90 days after it is revoked or its row is deleted. The session policy sets a token family's expiry: 365 days from sign-in by default, at most 730. It sets a refresh token's expiry from its idle window, 30 days by default, at most 90, never past its family's expiry. The database bounds no expiry, so a role that writes a far expiry only lengthens retention. Records also outlive account deletion for that window: no flow but the schema owner deletes a record, and deleting an account does not. +8. **Retention.** The log keeps a record until 90 days after its credential expires. A token family's record ends earlier when the family is revoked or its row is deleted. A service credential, which has no expiry, ends the same way. The session policy sets a token family's expiry: 365 days from sign-in by default, at most 730. It sets a refresh token's expiry from its idle window, 30 days by default, at most 90, never past its family's expiry. The database bounds no expiry, so a role that writes a far expiry only lengthens retention. After an account's deletion, a token family's record and a service credential's record last 90 days. An access token's record and a refresh token's record last until 90 days after its own expiry. The longest window after deletion is the refresh token's idle bound plus 90 days: 120 days by default, 180 at most. No flow but the schema owner deletes a record, and deleting an account does not. 9. **Use, revocation and deletion.** The log records issuance only. It does not say when a credential was used, revoked or deleted. 10. **The gateway's own keys.** The gateway signs cell tokens and upload capsules with its own keys. In this repository only gateway code loads them. Other services may hold them, and this change does not record what they sign. The rollout checks that no web deployment environment holds those keys. 11. **Credentials that the web app admits itself.** The web app issues and checks its own browser sessions. It does the same for the possession grants and sessions of the access record (`exomem_cloud_access_grants`, `exomem_cloud_access_sessions`). The gateway admits none of them, and the log records none. diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/proposal.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/proposal.md index d6514133..17273e8e 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/proposal.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/proposal.md @@ -8,7 +8,7 @@ Substrate's web app signs users in and issues the credentials that the Exomem Cl - **Identity lock.** Guard triggers refuse every change to an identity field of a grant, token family, access token, refresh token, client or service credential. They also refuse a change to a tenant's owner and to a cell's identifier or tenant. A revocation time and a consumption time change only from empty to a time. Guards refuse a delete of a grant, client, tenant, user, cell, service credential or reviewer credential. Each guard holds for every role except the schema owner, whatever select, insert, update, delete and truncate rights that role holds. A guard checks the stored row, so no trigger that runs before it can slip a change past. On the five column-locked tables that the grants script narrows (grants, token families, access tokens, refresh tokens and service credentials), the web app's database role also keeps update rights only on the columns its flows change. - **The trigger right stays with the schema owner.** A role that holds the trigger right on a table can run its own code as the schema owner, and no guard holds against that. The grants script therefore revokes that right on every table in the schema from every other role, on every run. `PUBLIC` holds no execute right on the functions that this change adds. Every function that the database can run as the schema owner for another role pins its search path, so a role's own operator cannot run in place of the built-in one. - **No switch.** The lock and the log are in force once the migrations apply. Relaxing either one takes a migration or a grants change, which is a reviewed commit. -- **Issuance log.** An owner-owned trigger writes one record for every access token, refresh token, token family, service credential and download ticket row, in the inserting transaction. The log refuses every write that the schema owner does not run. A read-only audit role reads it in bounded ranges. A record is kept until 90 days after its credential expires or, for a service credential, which has no expiry, until 90 days after it is revoked or its row is deleted. The session policy sets a token family's expiry (365 days from sign-in by default, at most 730) and a refresh token's expiry (30 days idle by default, at most 90, never past its family's expiry). The database bounds no expiry, so a role that writes a far expiry only lengthens retention. Records also outlive account deletion for that window, because no flow but the schema owner deletes a record. +- **Issuance log.** An owner-owned trigger writes one record for every access token, refresh token, token family, service credential and download ticket row, in the inserting transaction. The log refuses every write that the schema owner does not run. A read-only audit role reads it in bounded ranges. A record is kept until 90 days after its credential stops being usable. That is its expiry or, for a token family and a service credential, the time it is revoked or its row is deleted, if that comes first. A service credential has no expiry. The session policy sets a token family's expiry (365 days from sign-in by default, at most 730) and a refresh token's expiry (30 days idle by default, at most 90, never past its family's expiry). The database bounds no expiry, so a role that writes a far expiry only lengthens retention. After an account's deletion, a token family's record and a service credential's record last 90 days. An access token's record and a refresh token's record last until 90 days after its own expiry. The longest window after deletion is the refresh token's idle bound plus 90 days: 120 days by default, 180 at most. No flow but the schema owner deletes a record. - **Download tickets get a stored row.** A download ticket is a credential that the web app signs with a key it holds. Today no row backs it. The web app now stores one row for each ticket, and the gateway refuses a ticket without its row. - **Proof as the real roles.** Tests on a disposable PostgreSQL run every legitimate flow as the web app's role. They run each attack as that role twice: with the new rights, and with select, insert, update, delete and truncate on every table. @@ -30,7 +30,7 @@ The account service stays the sign-in provider, so it can still issue a credenti - **Database:** two migrations. The first adds the schema release table and the guards, and pins the search path of the functions that run as the schema owner. The second adds the issuance log, the recording triggers and the download ticket table. It blocks writes to the token and service credential tables while it records existing rows. Each sets a lock timeout. `scripts/exomem-cloud-grants.sql` gains the lock's rights, the trigger and execute revokes, and the audit role's rights. No new grants file. - **Deployment:** a new workflow under `.github/workflows/`, `scripts/migrate.ts`, the `vercel-build` script and the script it calls. Each deploy waits for the migration job before it builds. -- **Web app:** the download handler stores a ticket row, and the reconcile job prunes ticket rows and issuance records. No other flow changes its SQL. +- **Web app:** the download handler stores a ticket row, and the reconcile job prunes ticket rows and issuance records. The prune is a lane beside the job's other lanes, so another lane's failure does not stop it, and its own failure fails the job's response. No other flow changes its SQL. - **Gateway:** one release that requires the ticket row. It rolls at least one maximum ticket lifetime after the web release, and it rolls back before the web app does. - **Other changes:** the gateway requirement stands beside the download-ticket requirements of the active change `add-cloud-media-access`. Archive that change first; `tasks.md` holds the step. - **Tests:** `cloud-grants-postgres.integration.test.ts` changes its assertion that the web app's role holds every right on every non-Cloud table. A fixture step that the lock refuses moves to the role that owns the schema. diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md index 1e409818..67ec2eff 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md @@ -241,7 +241,7 @@ The issuance log SHALL refuse every insert, update, delete and truncate that the ### Requirement: Issuance records outlive their credentials and stay cheap to write -An issuance record SHALL be kept until at least 90 days after its credential expires. A service credential has no expiry, so its record SHALL be kept until at least 90 days after the credential is revoked or its row is deleted. Only the prune routine SHALL delete records, in bounded batches from the scheduled maintenance. Recording SHALL add less than one millisecond to the median latency of the Home mint transaction at the 10,000-tenant load target. +An issuance record SHALL be kept until at least 90 days after its credential expires. A token family's record SHALL end when the family is revoked or its row is deleted, if that is earlier. A service credential has no expiry, so its record SHALL end the same way. Only the prune routine SHALL delete records, in bounded batches from the scheduled maintenance. Recording SHALL add less than one millisecond to the median latency of the Home mint transaction at the 10,000-tenant load target. #### Scenario: The scheduled maintenance prunes the log @@ -249,6 +249,12 @@ An issuance record SHALL be kept until at least 90 days after its credential exp - **THEN** the prune routine deletes at most 10,000 records whose credential expired more than 90 days ago - **AND** the job reports how many records it deleted +#### Scenario: Another lane of the reconcile job fails + +- **WHEN** another lane of the reconcile job fails +- **THEN** the prune routine still runs +- **AND** the job's response reports its counts, or `null` for a part that failed, and a failed part fails the response + #### Scenario: The web app's role calls the prune routine early - **WHEN** the web app's role calls the prune routine any number of times @@ -265,6 +271,17 @@ An issuance record SHALL be kept until at least 90 days after its credential exp - **THEN** the record's end is the database clock's time at that statement - **AND** the prune routine deletes the record only after 90 days from then +#### Scenario: A token family ends before it expires + +- **WHEN** the web app's role revokes a token family, with any revocation time, or deletes its row, or an account's deletion cascades to it +- **THEN** the record's end is the database clock's time at that statement +- **AND** the prune routine deletes the record only after 90 days from then + +#### Scenario: A live token family + +- **WHEN** a token family is neither revoked nor deleted +- **THEN** its record's end stays the family's expiry + #### Scenario: The Home mint at the load target - **WHEN** the same Home mint transaction runs with and without the guards and the recording, on the same machine and on data generated for the load target diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md index d43b9ebb..ec048ec5 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md @@ -91,11 +91,12 @@ names each decision as D1 to D12. - [x] 3.1 In the second migration, set a lock timeout of five seconds for the transaction, then take D5's locks in D5's order with one `LOCK TABLE` statement. Create `exomem_cloud_issuance_log` with its kind constraint, its - three indexes, a partial index for service credential records, and its - guard. Add the recording function and revoke its execute right from - `PUBLIC`. Add one `AFTER INSERT` trigger on each of the five credential - tables, and on the service credential table an update trigger on the - revocation time and a delete trigger that end the record (D6). Revoke every + three indexes, a partial index each for service credential and token family + records, and its guard. Add the recording function and revoke its execute + right from `PUBLIC`. Add one `AFTER INSERT` trigger on each of the five + credential tables, and on the service credential and token family tables an + update trigger on the revocation time and a delete trigger that end the + record (D6). Revoke every right on the log in the same transaction. After the triggers exist, in the same transaction, write one backfilled record for each credential row that already exists. Verify: tasks 5.3 and 5.4. @@ -104,9 +105,10 @@ names each decision as D1 to D12. web app's role. Call it from the reconcile job beside the OAuth maintenance, and report the deleted count. Verify: a record inside its retention survives any number of calls, and a record past it is deleted. A live service - credential's record is never deleted. A revoked credential's record takes - the database clock's time, whatever revocation time the row names, and is - deleted 90 days after. + credential's record is never deleted. A revoked credential's record, and a revoked + or deleted token family's, takes the database clock's time, whatever + revocation time the row names, and is deleted 90 days after. A live + family's record keeps its expiry. - [x] 3.3 In `scripts/exomem-cloud-grants.sql`, revoke every right on the log from the web app's, the gateway's and the controller's roles on every run. Revoke execute on the guard, recording and prune functions from `PUBLIC`, diff --git a/src/app/api/cron/exomem-reconcile/__tests__/route.test.ts b/src/app/api/cron/exomem-reconcile/__tests__/route.test.ts index 104668a7..c85bffde 100644 --- a/src/app/api/cron/exomem-reconcile/__tests__/route.test.ts +++ b/src/app/api/cron/exomem-reconcile/__tests__/route.test.ts @@ -20,6 +20,11 @@ let contactCalls = 0; let contactShouldFail = false; let accessLogIsEnabled = false; let accessLogPruneCalls = 0; +let issuancePruneCalls = 0; +let issuancePruneResult: { records: number | null; tickets: number | null } = { + records: 5, + tickets: 2, +}; before(() => { mock.module("@/lib/exomem-hosted/cloud-admission", { @@ -99,7 +104,12 @@ before(() => { }, }); mock.module("@/lib/exomem-hosted/issuance-maintenance", { - namedExports: { pruneIssuanceState: async () => ({ records: 5, tickets: 2 }) }, + namedExports: { + pruneIssuanceState: async () => { + issuancePruneCalls += 1; + return issuancePruneResult; + }, + }, }); mock.module("@/lib/exomem-hosted/email-change", { namedExports: { pruneExpiredExomemEmailChanges: async () => 2 }, @@ -154,6 +164,8 @@ afterEach(() => { contactShouldFail = false; accessLogIsEnabled = false; accessLogPruneCalls = 0; + issuancePruneCalls = 0; + issuancePruneResult = { records: 5, tickets: 2 }; if (ORIGINAL_SCHEDULER_SECRET === undefined) delete process.env.EXOMEM_HOSTED_SCHEDULER_SECRET; else process.env.EXOMEM_HOSTED_SCHEDULER_SECRET = ORIGINAL_SCHEDULER_SECRET; }); @@ -305,9 +317,35 @@ describe("GET /api/cron/exomem-reconcile", () => { assert.deepEqual(JSON.parse(text), { success: false, error: { code: "CONTROL_PLANE_UNAVAILABLE", retryable: true }, + issuancePruned: { records: 5, tickets: 2 }, }); }); + // Retention of the issuance log must not wait on a provider outage in another lane, + // and the response must say what the prune did either way. + it("still prunes the issuance log when another lane fails, and reports the counts", async () => { + process.env.EXOMEM_HOSTED_SCHEDULER_SECRET = "cron-secret"; + paddleShouldFail = true; + const { GET } = await import("../route"); + const response = await GET(request("cron-secret")); + assert.equal(response.status, 503); + assert.equal(issuancePruneCalls, 1); + const body = (await response.json()) as { issuancePruned: unknown }; + assert.deepEqual(body.issuancePruned, { records: 5, tickets: 2 }); + }); + + it("reports a failed issuance prune as a failed lane, with null for the part that failed", async () => { + process.env.EXOMEM_HOSTED_SCHEDULER_SECRET = "cron-secret"; + issuancePruneResult = { records: null, tickets: 2 }; + const { GET } = await import("../route"); + const response = await GET(request("cron-secret")); + assert.equal(response.status, 503); + assert.equal(paddleRunCalls, 1, "the other lanes still ran"); + assert.equal(cloudReconcileCalls, 1); + const body = (await response.json()) as { issuancePruned: unknown }; + assert.deepEqual(body.issuancePruned, { records: null, tickets: 2 }); + }); + // A sweep that stops reclaiming client slots must not stay silent (the // partitions would fill again) or keep billing and Cloud work from running. it("still runs billing and Cloud work when the OAuth lane fails, then reports the failure", async () => { diff --git a/src/app/api/cron/exomem-reconcile/route.ts b/src/app/api/cron/exomem-reconcile/route.ts index cb7d8c56..abd7ee12 100644 --- a/src/app/api/cron/exomem-reconcile/route.ts +++ b/src/app/api/cron/exomem-reconcile/route.ts @@ -8,7 +8,10 @@ import { retryPendingCloudCancellationNotices } from "@/lib/exomem-hosted/cloud- import { runBoundedCloudDeletionFinish } from "@/lib/exomem-hosted/cloud-deletion-finish"; import { runBoundedPaddleReceiptContacts } from "@/lib/exomem-hosted/paddle-receipt-contact"; import { pruneExpiredExomemEmailChanges } from "@/lib/exomem-hosted/email-change"; -import { pruneIssuanceState } from "@/lib/exomem-hosted/issuance-maintenance"; +import { + pruneIssuanceState, + type IssuancePruneResult, +} from "@/lib/exomem-hosted/issuance-maintenance"; import { pruneExpiredOAuthState } from "@/lib/exomem-hosted/oauth-store"; import { promoteWaitlistedPeople, @@ -124,23 +127,43 @@ export async function GET(request: NextRequest): Promise { { status: 401, headers: { "cache-control": "no-store" } } ); } + // Set once the issuance lane has run, so the failure response can report it too. + let issuancePruned: IssuancePruneResult | null = null; try { // The OAuth lane deletes expired codes and tokens and gives back the slots - // of clients that can no longer be used (reclaim-oauth-client-slots). It is - // bounded per run and runs beside the other lanes, so a failure in any one - // still lets the others finish this tick before the route reports it. - const [paddleResult, cloudResult, oauthResult, contactsResult, changesResult, accessLogResult] = - await Promise.allSettled([ - runBoundedPaddleReconcile({ - maxSubscriptions: 5, - timeBudgetMs: 8_000, - }), - runCloudLane(), - pruneExpiredOAuthState(), - runBoundedPaddleReceiptContacts({ maxContacts: 5, timeBudgetMs: 8_000 }), - pruneExpiredExomemEmailChanges(), - accessLogEnabled() ? pruneAccessLogAuth() : Promise.resolve(null), - ]); + // of clients that can no longer be used (reclaim-oauth-client-slots). The + // issuance lane prunes the issuance log and the download ticket rows. Both + // are bounded per run and run beside the other lanes, so a failure in any + // one still lets the others finish this tick before the route reports it. + const [ + paddleResult, + cloudResult, + oauthResult, + contactsResult, + changesResult, + accessLogResult, + issuanceResult, + ] = await Promise.allSettled([ + runBoundedPaddleReconcile({ + maxSubscriptions: 5, + timeBudgetMs: 8_000, + }), + runCloudLane(), + pruneExpiredOAuthState(), + runBoundedPaddleReceiptContacts({ maxContacts: 5, timeBudgetMs: 8_000 }), + pruneExpiredExomemEmailChanges(), + accessLogEnabled() ? pruneAccessLogAuth() : Promise.resolve(null), + pruneIssuanceState(), + ]); + // The prune logs and reports a failed part as null. A failed part counts as a failed lane, + // so the log's retention never stops without the route saying so. + if (issuanceResult.status === "rejected") + console.error("exomem-issuance: retention lane failed"); + issuancePruned = + issuanceResult.status === "fulfilled" + ? issuanceResult.value + : { records: null, tickets: null }; + const issuanceFailed = issuancePruned.records === null || issuancePruned.tickets === null; if (oauthResult.status === "rejected") { console.error("exomem-oauth: expired state and client retirement lane failed"); } @@ -153,13 +176,11 @@ export async function GET(request: NextRequest): Promise { changesResult.status === "rejected" || paddleResult.status === "rejected" || cloudResult.status === "rejected" || - oauthResult.status === "rejected" + oauthResult.status === "rejected" || + issuanceFailed ) { throw new Error("EXOMEM_RECONCILIATION_LANE_FAILED"); } - // Retention of the issuance log and the ticket rows. It reports each part as null on failure, - // so it cannot fail the route and needs no place in the settled lanes above. - const issuancePruned = await pruneIssuanceState(); const paddle = paddleResult.value; return NextResponse.json( { @@ -197,6 +218,9 @@ export async function GET(request: NextRequest): Promise { { success: false, error: { code: "CONTROL_PLANE_UNAVAILABLE", retryable: true }, + // The counts, or null for a failed part, whichever lane failed. Absent only when the + // failure came before the issuance lane ran. + ...(issuancePruned ? { issuancePruned } : {}), }, { status: 503, headers: { "cache-control": "no-store" } } ); diff --git a/src/lib/exomem-hosted/__tests__/cloud-issuance-log-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-issuance-log-postgres.integration.test.ts index 237d031d..71797223 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-issuance-log-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-issuance-log-postgres.integration.test.ts @@ -351,6 +351,101 @@ for (const state of STATES) { ); }); + // A token family's record holds the family's expiry. A revocation or a delete before then + // moves it to the database clock's time, so the prune keeps it 90 days from the end. + const families = () => fx.q("exomem_oauth_token_families"); + const addFamily = async (grantId = world.grantId) => + ( + await fx.owner.query<{ id: string }>( + `INSERT INTO ${families()} (grant_id, client_id, expires_at) + VALUES ($1, $2, now() + interval '300 days') RETURNING id`, + [grantId, world.clientId] + ) + ).rows[0]!.id; + const familyEnd = async (familyId: string) => + ( + await fx.owner.query<{ at_expiry: boolean; at_now: boolean }>( + `SELECT expires_at > now() + interval '299 days' AS at_expiry, + coalesce(expires_at > now() - interval '1 minute' AND expires_at <= now(), false) AS at_now + FROM ${log()} WHERE credential_kind = 'token_family' AND credential_id = $1`, + [familyId] + ) + ).rows[0]; + + it("ends a token family's record at the database clock when the web app's role revokes it, whatever revoked_at says", async () => { + const live = await addFamily(); + const revoked = await addFamily(); + assert.deepEqual(await familyEnd(live), { at_expiry: true, at_now: false }); + await fx.app.query( + `UPDATE ${families()} SET revoked_at = now() - interval '200 days' WHERE id = $1`, + [revoked] + ); + assert.deepEqual( + await familyEnd(revoked), + { at_expiry: false, at_now: true }, + "a backdated revoked_at does not bring the prune forward" + ); + assert.deepEqual( + await familyEnd(live), + { at_expiry: true, at_now: false }, + "a live family's record keeps its expiry" + ); + }); + + it("ends a token family's record when the web app's role deletes the family, and when a deleted grant cascades to it", async () => { + const deleted = await addFamily(); + await fx.app.query(`DELETE FROM ${families()} WHERE id = $1`, [deleted]); + assert.deepEqual(await familyEnd(deleted), { at_expiry: false, at_now: true }); + + // Account deletion removes a grant, and the family goes with it. + const grant = ( + await fx.owner.query<{ id: string }>( + `INSERT INTO ${fx.q("exomem_oauth_grants")} (user_id, tenant_id, client_id, resource, scopes) + VALUES ($1, $2, $3, $4, ARRAY['mcp:read']) RETURNING id`, + [ + world.userId, + world.tenantId, + world.clientId, + `https://gateway.example.test/mcp/${randomBytes(6).toString("hex")}`, + ] + ) + ).rows[0]!.id; + const cascaded = await addFamily(grant); + await fx.owner.query(`DELETE FROM ${fx.q("exomem_oauth_grants")} WHERE id = $1`, [grant]); + assert.deepEqual(await familyEnd(cascaded), { at_expiry: false, at_now: true }); + }); + + it("prunes a revoked token family's record 90 days after the revocation, and keeps a live family's", async () => { + const live = await addFamily(); + const revoked = await addFamily(); + await fx.app.query(`UPDATE ${families()} SET revoked_at = now() WHERE id = $1`, [revoked]); + const pruneAsApp = () => + fx.app.query(`SELECT ${fx.q("exomem_prune_issuance_log")}() AS deleted`); + const kept = async () => + ( + await fx.owner.query<{ credential_id: string }>( + `SELECT credential_id FROM ${log()} WHERE credential_id = ANY($1::uuid[])`, + [[live, revoked]] + ) + ).rows + .map((row) => row.credential_id) + .sort(); + await pruneAsApp(); + assert.deepEqual(await kept(), [live, revoked].sort(), "90 days have not passed"); + // The test cannot wait 90 days, so the owner moves the recorded end back. + await fx.owner.query( + `UPDATE ${log()} SET expires_at = now() - interval '91 days' + WHERE credential_kind = 'token_family' AND credential_id = $1`, + [revoked] + ); + await pruneAsApp(); + assert.deepEqual( + await kept(), + [live], + "the revoked family's record is gone; the live one stays" + ); + }); + it("lets the maintenance run, as the web app's role, remove an expired download ticket row", async () => { const ticket = async (expires: string) => ( @@ -443,6 +538,23 @@ describe("The migration that adds the log", { skip: !databaseUrl }, () => { [{ open: 1, ended: 1 }], "the revoked service credential's backfilled record has an end, the live one's has none" ); + const familyEnds = await fx.owner.query( + `SELECT family.revoked_at IS NOT NULL AS revoked, + record.expires_at <= now() AS ended + FROM exomem_cloud_issuance_log AS record + JOIN exomem_oauth_token_families AS family ON family.id = record.credential_id + WHERE record.tenant_id = $1 AND record.credential_kind = 'token_family' + ORDER BY revoked`, + [world.tenantId] + ); + assert.deepEqual( + familyEnds.rows, + [ + { revoked: false, ended: false }, + { revoked: true, ended: true }, + ], + "the revoked family's backfilled record has an end, the live family's keeps its expiry" + ); const role = await fx.owner.query( "SELECT DISTINCT database_role FROM exomem_cloud_issuance_log WHERE tenant_id = $1", [world.tenantId] diff --git a/src/lib/exomem-hosted/issuance-maintenance.ts b/src/lib/exomem-hosted/issuance-maintenance.ts index b3fbd3ef..0ce663b5 100644 --- a/src/lib/exomem-hosted/issuance-maintenance.ts +++ b/src/lib/exomem-hosted/issuance-maintenance.ts @@ -4,7 +4,7 @@ import { executeExomemSql as sql } from "./db"; // so a minute-by-minute run clears any backlog far faster than rows arrive. const TICKET_BATCH = 1000; -type IssuancePruneResult = { +export type IssuancePruneResult = { /** Records the log's prune function deleted, or null when the call failed. */ records: number | null; /** Expired download ticket rows deleted, or null when the delete failed. */ From 2d048401f7c7260f8cb5909108f5ff7f421d1781 Mon Sep 17 00:00:00 2001 From: Artexis10 Date: Wed, 2 Dec 2026 12:36:49 +0000 Subject: [PATCH 14/29] Revoke a tenant's service credentials when its cell is deleted, and state what D12 check 1 reads A service credential belongs to the tenant, not to one cell. Nothing revoked it when the tenant's cell was deleted, so its issuance record kept no end and the prune never deleted it. A live credential would also have served the tenant's next cell after re-admission. The statement that revokes a deleted cell's consent now also revokes the tenant's unrevoked service credentials. It sets the revocation time from the database clock and leaves the revoking principal empty. The existing trigger ends each credential's record. The unpaid-invite expiry, the lifecycle reconcile and the account deletion all run the statement, and the deletion finish repeats it, so a second run changes nothing. The web app's role already holds update on that column, so no grant changes. A PostgreSQL test runs the account deletion as that role and checks that another tenant's credential and its record stay open. Text: the proposal, D6, limit 8, the service credentials spec and the runbook now give the post-deletion bound for service credentials. D12, limit 13, the OAuth spec and the runbook now say that check 1 reads the five credential tables in full, is run on demand, and needs an index on created_at or a different query before anything schedules it. D7 and task 5.8 now say that the pgbench script and the 10,000-tenant generator are kept with the private record of the run. --- docs/runbooks/exomem-cloud-operations.md | 17 ++-- .../design.md | 18 ++--- .../proposal.md | 2 +- .../exomem-cloud-service-credentials/spec.md | 16 ++++ .../specs/exomem-hosted-mcp-oauth/spec.md | 6 +- .../tasks.md | 9 ++- ...letion-finish-postgres.integration.test.ts | 81 +++++++++++++++++++ src/lib/exomem-hosted/cloud-consent.ts | 16 +++- 8 files changed, 143 insertions(+), 22 deletions(-) diff --git a/docs/runbooks/exomem-cloud-operations.md b/docs/runbooks/exomem-cloud-operations.md index e0be73e7..ba2f4657 100644 --- a/docs/runbooks/exomem-cloud-operations.md +++ b/docs/runbooks/exomem-cloud-operations.md @@ -864,8 +864,10 @@ row is deleted, the record's end becomes the database clock's time, and the prun family's record ends the same way when the family is revoked or deleted, if that is before its expiry. The session policy sets a token family's expiry, `EXOMEM_OAUTH_SESSION_MAX_DAYS` after sign-in (365 days by default, at most 730), and a refresh token's expiry, `EXOMEM_OAUTH_REFRESH_IDLE_DAYS` (30 days by default, at most 90). The database bounds no expiry, so a role that -writes a far expiry only lengthens retention. After an account's deletion, a token family's record and a service credential's -record last 90 days, and an access token's or a refresh token's record lasts until 90 days after its own expiry. The longest +writes a far expiry only lengthens retention. Deleting an account's cell revokes its service credentials, in the transaction that revokes its consent. After the deletion, a +token family's record and a service credential's record last 90 days, and an access token's or a refresh token's record lasts +until 90 days after its own expiry. A service credential of an account deleted before this release keeps an open record until +you revoke it through the operator API. The longest window after deletion is the refresh idle bound plus 90 days: 120 days by default, 180 at most. Only the schema owner deletes a record. The job's response reports the deleted counts as `issuancePruned.records` and `issuancePruned.tickets`. A value of `null` means that part failed, and the log line `exomem-issuance: log retention failed` names it. A failed part makes the job answer `503`, and the answer still carries `issuancePruned`. The prune runs @@ -875,9 +877,9 @@ whatever the other lanes do. Connect as `substrate_audit` for every query in this section. The grants script gives that role select on the log. It also gives select on the `id` and `created_at` columns of the five credential tables, and on `id` and `owner_user_id` of `exomem_tenants`. It gives no other right. Each query below reads a range of record identifiers through the primary key. -Its cost follows the range, not the size of the log. +Its cost on the log follows the range, not the size of the log. The first check also reads the credential tables in full. -Run the range checks about once an hour, and after any emergency statement. Each run starts one hour of records before +Nothing schedules these checks. Run them on demand, and after any emergency statement. Each run starts one hour of records before the point where the previous run stopped. A record gets its identifier when it is inserted, not when it commits, so a record can commit after a run has read past it. The overlap lets the next run read it. A record whose transaction stayed open for longer than that hour is missed by the range checks. The read of one tenant's records still returns it. @@ -897,10 +899,13 @@ open for longer than that hour is missed by the range checks. The read of one te \echo hi=:hi lo=:lo ``` -4. Run the three range checks. Each one is a finding when it returns a row. +4. Run the three checks. Each one is a finding when it returns a row. Credential rows without a record. One statement reads the credential rows and the log, so a credential and its - record are both visible or both absent. A row here has no record. It reads the log from `lo` to its end. + record are both visible or both absent. A row here has no record. It reads the log from `lo` to its end. It reads + the five credential tables in full, because none has an index on `created_at`, and a consumed refresh token of an + unexpired family stays in its table. Run it on demand, never from a schedule. A scheduled version needs an index on + `created_at` or a different query, which is a later step. ```sql SELECT created.kind, created.id, created.created_at diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md index db90df14..540d7ed7 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md @@ -213,7 +213,7 @@ A service credential has no expiry. Its record has no end while the credential i A token family's record holds the family's expiry from the insert. The same recording function moves it to the database clock's time when the family is revoked or its row is deleted, if that is earlier. An update trigger on the revocation time and a delete trigger run it, and a delete that an account's deletion cascades to runs it too. The function reads the clock, not the row's `revoked_at`, for the same reason as above. A revocation is one-way, and a revoked family cannot be used, so the web app's role cannot end a live family's record early. A partial index on the credential's identifier, which holds only token family records, finds the record. An access token or refresh token insert pays nothing for it, and a family insert pays one more index entry. For a family that is revoked when the migration runs, the record's end is the migration's time, unless the family expired earlier. An access token's and a refresh token's record do not end early. Each keeps its own expiry. -After an account's deletion, a token family's record and a service credential's record last 90 days. An access token's record lasts until 90 days after its own expiry, which is an hour at most from its issue. A refresh token's record lasts until 90 days after its own expiry, which is the idle window at most from its issue: 30 days by default, at most 90. The longest window after deletion is therefore the refresh token's idle bound plus 90 days, which is 120 days by default and 180 at most. A download ticket's record lasts a day plus 90 days at most. +Deleting an account's cell revokes the account's service credentials, in the same statement that revokes its grants, families and access tokens. The statement runs when the tenant stops being served: the unpaid-invite expiry, the lifecycle reconcile and the account deletion all call it, and the deletion finish repeats it. It sets `revoked_at` to the database clock and leaves the revoking principal empty, because no operator revoked the credential. A credential belongs to the tenant, so a live one would otherwise serve the tenant's next cell after re-admission, and its record would stay open and never be pruned. The web app's role already holds update on that column, so no grant changes. Afterwards, a token family's record and a service credential's record last 90 days. A service credential of an account deleted before this release keeps an open record until the operator revokes it. An access token's record lasts until 90 days after its own expiry, which is an hour at most from its issue. A refresh token's record lasts until 90 days after its own expiry, which is the idle window at most from its issue: 30 days by default, at most 90. The longest window after deletion is therefore the refresh token's idle bound plus 90 days, which is 120 days by default and 180 at most. A download ticket's record lasts a day plus 90 days at most. The expiry is safe to key on. It is set at insert and is a fixed column afterwards. A credential cannot be used after its expiry, so no usable credential loses its record early. @@ -253,10 +253,10 @@ The log also costs outside the request: Proof, on a disposable PostgreSQL: -- **Instrument.** `pgbench` runs the Home mint transaction's statements as a custom script, over generated data for 10,000 tenants. The same script runs with and without this change's triggers, five runs each, on the same machine and data. +- **Instrument.** `pgbench` runs the Home mint transaction's statements as a custom script, over generated data for 10,000 tenants. The same script runs with and without this change's triggers, five runs each, on the same machine and data. The script and the generator are not in this repository. They are kept with the private record of the run, so a later change to the triggers or the guards needs that record's instrument to rerun the proof. - **Size.** The log holds 10 million generated records. That is enough, because every insert lands at the right edge of an index, or at the right edge of one tenant's range. The pages that an insert touches stay in memory at any log size. - **Result.** The run's outputs are kept as a private record outside this repository, and task 5.8 states the outcome. The median must rise by less than one millisecond. -- **Plans.** `EXPLAIN (ANALYZE, BUFFERS)` of one prune call shows that it reads only the records it deletes. The same output for each read of D12 shows an index range and no full scan. +- **Plans.** `EXPLAIN (ANALYZE, BUFFERS)` of one prune call shows that it reads only the records it deletes. The same output for each read of the log in D12 shows an index range and no full scan. D12's first check also reads the credential tables in full, so its plan is reported and no bound is set on it. ### D8. A download ticket gets a stored row @@ -352,11 +352,11 @@ Preview and development environments must hold no credential for the production ### D12. Reading the log -A log that nobody can read cheaply proves nothing. Two readers exist, and each one reads a bounded range. +A log that nobody can read cheaply proves nothing. Two readers exist, and each one reads a bounded range of the log. **The audit role.** A new role, `substrate_audit`, reads the log without the schema-owner credential. It holds select on the log and on the columns that its checks compare, and no other right. The grants script grants this when the role exists, as it does for the gateway's role. The operator creates the role in the rollout. -**The runbook's checks.** Each check that reads records takes a range of record identifiers and reads only that range, through the primary key. The checks are: +**The runbook's checks.** Each check that reads the log takes a range of record identifiers and reads only that range, through the primary key. The checks are: - credential rows created in the period that have no record; - records in the range whose database role is not the web app's role and that are not backfilled; @@ -366,7 +366,7 @@ A log that nobody can read cheaply proves nothing. Two readers exist, and each o - roles that the web app's role is a member of; - create rights that a role other than a superuser, the schema owner or `pg_database_owner` holds on the database or on a schema outside `pg_catalog` and `information_schema`, and schemas that a role other than the schema owner, the bootstrap superuser or `pg_database_owner` owns. -The first check reads the credential tables' rows of the same period. Those tables hold live rows only, so that read is bounded by the count of live credentials. The last four read the catalog. +The first check also reads the credential tables in full. It filters their rows by `created_at`, and none of the five tables has an index on that column. A consumed refresh token of an unexpired family stays in its table, so the tables hold more than the live credentials. The read grows with those tables, not with the range of the log. The operator runs it on demand (limit 13), not on a schedule. A scheduled version needs an index on `created_at` or a different query, which is a later step. The last four read the catalog. **Late commits.** PostgreSQL assigns a record's identifier at insert, not at commit. A record can therefore commit after a check has read past its identifier. Each run starts one hour of records before the point where the previous run stopped, so the next run reads such a record. It finds that start by walking back through the primary key, so the read stays bounded. A record whose transaction stayed open for longer than that hour is missed by the range checks. The read of one tenant's records still returns it. @@ -383,12 +383,12 @@ The claim is: the database records every credential that the gateway admits from 5. **What a grant allows.** The account service can change a grant's scopes. It can change an app's stored attributes, such as its name, its redirect addresses and whether it is enabled. The grant's tenant, user and app stay fixed. 6. **Suspension and blocks.** The account service sets a tenant's status and can add or remove an account block. 7. **The schema owner, the trigger right and the create right.** Whoever holds the schema-owner credential, administers the database server, or lands a commit on `main` can change the lock and the log. So can a role that holds the trigger right on a table in the schema, or a create right on the database or on a schema (D2). So can an administrator of the repository: they can edit the protected environment or the ruleset and run code with the schema-owner credential without landing a commit. The rollout turns off the administrators' bypass of the environment's rules, which narrows that path but does not remove it. Each change through `main` is a public commit. -8. **Retention.** The log keeps a record until 90 days after its credential expires. A token family's record ends earlier when the family is revoked or its row is deleted. A service credential, which has no expiry, ends the same way. The session policy sets a token family's expiry: 365 days from sign-in by default, at most 730. It sets a refresh token's expiry from its idle window, 30 days by default, at most 90, never past its family's expiry. The database bounds no expiry, so a role that writes a far expiry only lengthens retention. After an account's deletion, a token family's record and a service credential's record last 90 days. An access token's record and a refresh token's record last until 90 days after its own expiry. The longest window after deletion is the refresh token's idle bound plus 90 days: 120 days by default, 180 at most. No flow but the schema owner deletes a record, and deleting an account does not. +8. **Retention.** The log keeps a record until 90 days after its credential expires. A token family's record ends earlier when the family is revoked or its row is deleted. A service credential, which has no expiry, ends the same way. The session policy sets a token family's expiry: 365 days from sign-in by default, at most 730. It sets a refresh token's expiry from its idle window, 30 days by default, at most 90, never past its family's expiry. The database bounds no expiry, so a role that writes a far expiry only lengthens retention. Deleting an account's cell revokes its service credentials, so after the deletion a token family's record and a service credential's record last 90 days. A service credential of an account deleted before this release keeps an open record until the operator revokes it. An access token's record and a refresh token's record last until 90 days after its own expiry. The longest window after deletion is the refresh token's idle bound plus 90 days: 120 days by default, 180 at most. No flow but the schema owner deletes a record, and deleting an account does not. 9. **Use, revocation and deletion.** The log records issuance only. It does not say when a credential was used, revoked or deleted. 10. **The gateway's own keys.** The gateway signs cell tokens and upload capsules with its own keys. In this repository only gateway code loads them. Other services may hold them, and this change does not record what they sign. The rollout checks that no web deployment environment holds those keys. 11. **Credentials that the web app admits itself.** The web app issues and checks its own browser sessions. It does the same for the possession grants and sessions of the access record (`exomem_cloud_access_grants`, `exomem_cloud_access_sessions`). The gateway admits none of them, and the log records none. 12. **Reviewer credentials.** The web app's role keeps update rights on every column of `exomem_marketplace_reviewer_credentials`. An existing guard fixes only its lineage columns: kind, candidate, assignment, assignment generation, staged client release and OAuth client. The role can therefore clear a reviewer credential's revocation time and revive it. The gateway then admits that credential's unrevoked families and tokens again. Their records exist from their inserts. -13. **Detection is manual.** The operator runs the runbook's checks. Nothing schedules them yet. Detecting a disabled recording trigger or a grant mismatch is therefore best-effort until a scheduled job runs them, which is a later step. +13. **Detection is manual.** The operator runs the runbook's checks on demand. Nothing schedules them yet. The first check reads the five credential tables in full, because none has an index on `created_at`. Detecting a disabled recording trigger, a grant mismatch or a credential without a record is therefore best-effort until a scheduled job runs the checks. That job needs an index on `created_at` or a different first query, which is a later step. ## Risks / Trade-offs @@ -404,7 +404,7 @@ The claim is: the database records every credential that the gateway admits from - **The gateway release rolls too early.** → A ticket signed before the web release is refused for the rest of its life. The owner asks for the download again. The task states the wait. - **Each deploy waits for the migration job.** → A deploy takes longer by the job's run time. The job installs dependencies and connects once. - **The schema owner's exemption hides a broken flow in ordinary tests.** → Most suites run as the role that owns the schema, so a guard never refuses them. Only the suites that connect as the web app's role prove the flows. -- **Nothing runs the D12 checks.** → The operator runs the runbook's checks. Nothing schedules them yet, so detecting a disabled recording trigger or a grant mismatch is best-effort until a scheduled job runs them. That job is a later step. +- **Nothing runs the D12 checks.** → The operator runs the runbook's checks on demand. Nothing schedules them yet, so detecting a disabled recording trigger, a grant mismatch or a credential without a record is best-effort until a scheduled job runs them. The first check reads the credential tables in full, so that job needs an index on `created_at` or a different first query. It is a later step. ## Migration Plan diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/proposal.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/proposal.md index 17273e8e..13acf9fd 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/proposal.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/proposal.md @@ -8,7 +8,7 @@ Substrate's web app signs users in and issues the credentials that the Exomem Cl - **Identity lock.** Guard triggers refuse every change to an identity field of a grant, token family, access token, refresh token, client or service credential. They also refuse a change to a tenant's owner and to a cell's identifier or tenant. A revocation time and a consumption time change only from empty to a time. Guards refuse a delete of a grant, client, tenant, user, cell, service credential or reviewer credential. Each guard holds for every role except the schema owner, whatever select, insert, update, delete and truncate rights that role holds. A guard checks the stored row, so no trigger that runs before it can slip a change past. On the five column-locked tables that the grants script narrows (grants, token families, access tokens, refresh tokens and service credentials), the web app's database role also keeps update rights only on the columns its flows change. - **The trigger right stays with the schema owner.** A role that holds the trigger right on a table can run its own code as the schema owner, and no guard holds against that. The grants script therefore revokes that right on every table in the schema from every other role, on every run. `PUBLIC` holds no execute right on the functions that this change adds. Every function that the database can run as the schema owner for another role pins its search path, so a role's own operator cannot run in place of the built-in one. - **No switch.** The lock and the log are in force once the migrations apply. Relaxing either one takes a migration or a grants change, which is a reviewed commit. -- **Issuance log.** An owner-owned trigger writes one record for every access token, refresh token, token family, service credential and download ticket row, in the inserting transaction. The log refuses every write that the schema owner does not run. A read-only audit role reads it in bounded ranges. A record is kept until 90 days after its credential stops being usable. That is its expiry or, for a token family and a service credential, the time it is revoked or its row is deleted, if that comes first. A service credential has no expiry. The session policy sets a token family's expiry (365 days from sign-in by default, at most 730) and a refresh token's expiry (30 days idle by default, at most 90, never past its family's expiry). The database bounds no expiry, so a role that writes a far expiry only lengthens retention. After an account's deletion, a token family's record and a service credential's record last 90 days. An access token's record and a refresh token's record last until 90 days after its own expiry. The longest window after deletion is the refresh token's idle bound plus 90 days: 120 days by default, 180 at most. No flow but the schema owner deletes a record. +- **Issuance log.** An owner-owned trigger writes one record for every access token, refresh token, token family, service credential and download ticket row, in the inserting transaction. The log refuses every write that the schema owner does not run. A read-only audit role reads it in bounded ranges. A record is kept until 90 days after its credential stops being usable. That is its expiry or, for a token family and a service credential, the time it is revoked or its row is deleted, if that comes first. A service credential has no expiry. The session policy sets a token family's expiry (365 days from sign-in by default, at most 730) and a refresh token's expiry (30 days idle by default, at most 90, never past its family's expiry). The database bounds no expiry, so a role that writes a far expiry only lengthens retention. Deleting an account's cell revokes the account's service credentials in the transaction that revokes its consent, so after the deletion a token family's record and a service credential's record last 90 days. A service credential of an account deleted before this release keeps an open record until the operator revokes it. An access token's record and a refresh token's record last until 90 days after its own expiry. The longest window after deletion is the refresh token's idle bound plus 90 days: 120 days by default, 180 at most. No flow but the schema owner deletes a record. - **Download tickets get a stored row.** A download ticket is a credential that the web app signs with a key it holds. Today no row backs it. The web app now stores one row for each ticket, and the gateway refuses a ticket without its row. - **Proof as the real roles.** Tests on a disposable PostgreSQL run every legitimate flow as the web app's role. They run each attack as that role twice: with the new rights, and with select, insert, update, delete and truncate on every table. diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-cloud-service-credentials/spec.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-cloud-service-credentials/spec.md index 9c04b3ff..ebd67347 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-cloud-service-credentials/spec.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-cloud-service-credentials/spec.md @@ -35,3 +35,19 @@ This requirement binds every role except the schema owner. The database SHALL re - **WHEN** any role inserts a service credential row - **THEN** the issuance log gains one record that names the row and its tenant - **AND** the record holds neither the principal nor the secret digest + +### Requirement: Deleting a tenant's cell revokes its service credentials + +The transaction that sets a tenant's Cloud cell to deleted SHALL revoke every service credential of that tenant that is not yet revoked. The revocation time SHALL come from the database clock, and the revoking principal SHALL stay empty. A second run SHALL change nothing, and no other tenant's credential SHALL change. The credential's issuance record SHALL then end, so the prune routine deletes it 90 days later. + +#### Scenario: An account's deletion finishes + +- **WHEN** an owner confirms the account's deletion and the finish scrubs the tenant +- **THEN** each of the tenant's service credentials is revoked, with the database clock's time and no revoking principal +- **AND** each credential's issuance record has an end +- **AND** another tenant's service credential stays live and its record stays open + +#### Scenario: The deletion runs again + +- **WHEN** the revocation runs again for a tenant whose credentials are already revoked +- **THEN** no revocation time changes diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md index 67ec2eff..848a79bd 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md @@ -267,7 +267,7 @@ An issuance record SHALL be kept until at least 90 days after its credential exp #### Scenario: A service credential ends -- **WHEN** the web app's role revokes a service credential, with any revocation time, or the schema owner deletes its row +- **WHEN** the web app's role revokes a service credential, with any revocation time, or the schema owner deletes its row, or a tenant's cell deletion revokes it - **THEN** the record's end is the database clock's time at that statement - **AND** the prune routine deletes the record only after 90 days from then @@ -295,7 +295,7 @@ An issuance record SHALL be kept until at least 90 days after its credential exp ### Requirement: The issuance log is read in bounded ranges, without the schema-owner credential -A read-only audit role SHALL hold select on the issuance log and on the columns that its checks compare, and no other right. Each documented check SHALL read a bounded range of records. A reader SHALL be able to list one tenant's records a page at a time through an index. +A read-only audit role SHALL hold select on the issuance log and on the columns that its checks compare, and no other right. Each documented read of the log SHALL cover a bounded range of records. The check for credential rows without a record SHALL also read the credential tables in full, and the operator SHALL run it on demand. A reader SHALL be able to list one tenant's records a page at a time through an index. #### Scenario: The audit role reads the log @@ -306,7 +306,7 @@ A read-only audit role SHALL hold select on the issuance log and on the columns #### Scenario: A check reads a range - **WHEN** the operator runs a documented check over a range of record identifiers -- **THEN** the check reads that range through the primary key and no other record +- **THEN** the check reads that range of the log through the primary key and no other record of the log #### Scenario: A record commits late diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md index ec048ec5..ecbd0256 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md @@ -221,11 +221,16 @@ without truncate. Neither state holds the trigger right. the write-ahead-log bytes for each mint, and the measured size of a record. Report `EXPLAIN (ANALYZE, BUFFERS)` of one prune call and of each D12 read. Pass: the median rises by less than one millisecond, the prune reads only - what it deletes, and no D12 read scans the whole log. Evidence: the run's + what it deletes, and no D12 read of the log scans the whole log. D12's first + check also reads the credential tables in full, so the run reports its plan + and sets no bound on it. Evidence: the run's outputs are kept as a private record outside this public repository. They are the median and the 95th percentile of the mint latency with and without the triggers, the write-ahead-log bytes for each mint, the size of a record, - and the `EXPLAIN` plans. The run met each part of the pass condition. + and the `EXPLAIN` plans. The run met each part of the pass condition. The + `pgbench` script and the 10,000-tenant generator are not in this repository. + They are kept with that private record, so a later change to the triggers or + the guards needs that record's instrument to rerun the proof. - [ ] 5.9 Add the new suites to the PostgreSQL integration list in `.github/workflows/test.yml`. Verify: CI runs them. diff --git a/src/lib/exomem-hosted/__tests__/cloud-deletion-finish-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-deletion-finish-postgres.integration.test.ts index 797fe60f..43d93f60 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-deletion-finish-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-deletion-finish-postgres.integration.test.ts @@ -16,6 +16,7 @@ import { type CloudDeletionFinishDependencies, type CloudDeletionFinishOutcome, } from "../cloud-deletion-finish"; +import { revokeCloudResourceConsent } from "../cloud-consent"; import { reconcileCloudCellDesiredState, runBoundedCloudReconcile } from "../cloud-lifecycle"; import { clearSettledEmailRecipients, drainExomemEmailOutbox } from "../email-outbox"; import { @@ -118,6 +119,7 @@ async function resetFleet(): Promise { "exomem_exports", "exomem_entitlements", "exomem_cloud_cells", + "exomem_cloud_service_credentials", "exomem_oauth_account_blocks", "exomem_tenants", "exomem_users", @@ -1530,6 +1532,85 @@ describe("Exomem Cloud deletion finish PostgreSQL integration", { skip: !databas await assertFinishedReceipt(tenant, { sourceState: "complimentary_active" }); }); + it("revokes a deleted account's service credentials, ends their issuance records, and leaves another tenant's credential live", async () => { + await resetFleet(); + const gone = await admitCloudTenant({ source: "complimentary" }); + const kept = await admitCloudTenant({ source: "complimentary" }); + const addCredential = async (tenantId: string, principal: string) => + ( + await pool!.query<{ id: string }>( + `INSERT INTO exomem_cloud_service_credentials + (tenant_id, principal, secret_digest, created_by_principal_digest) + VALUES ($1, $2, $3, $4) RETURNING id`, + [tenantId, principal, randomBytes(32), randomBytes(32)] + ) + ).rows[0]!.id; + const goneCredentials = [ + await addCredential(gone.tenantId, "service:creator-platform"), + await addCredential(gone.tenantId, "service:other-product"), + ]; + const keptCredential = await addCredential(kept.tenantId, "service:creator-platform"); + // The record ends at the database clock when the credential does, and stays open while it lives. + const state = async (ids: string[]) => + ( + await pool!.query( + `SELECT credential.revoked_at IS NOT NULL AS revoked, + credential.revoked_at <= now() AS revoked_at_clock, + credential.revoked_by_principal_digest IS NULL AS no_operator, + record.expires_at IS NULL AS record_open, + coalesce(record.expires_at > now() - interval '1 minute' AND record.expires_at <= now(), false) AS record_ended_now + FROM exomem_cloud_service_credentials AS credential + JOIN exomem_cloud_issuance_log AS record + ON record.credential_kind = 'service_credential' AND record.credential_id = credential.id + WHERE credential.id = ANY($1::uuid[]) ORDER BY credential.id`, + [ids] + ) + ).rows; + const live = { revoked: false, record_open: true, record_ended_now: false }; + const ended = { revoked: true, record_open: false, record_ended_now: true }; + const pick = (rows: Array>, shape: Record) => + rows.map((row) => Object.fromEntries(Object.keys(shape).map((key) => [key, row[key]]))); + assert.deepEqual(pick(await state([...goneCredentials, keptCredential]), live), [ + live, + live, + live, + ]); + + const fake = fakePaddle(); + let atFinish: Array> = []; + await confirmCloudDeletion(gone, async (tenantId) => { + // The confirmation's reconcile deleted the cell row, which is where the tenant stops being served. + atFinish = await state(goneCredentials); + return finishCloudAccountDeletion(tenantId, withPaddle(fake)); + }); + assert.equal(await tenantStatus(gone.tenantId), "deleted"); + assert.deepEqual(pick(atFinish, ended), [ended, ended], "revoked when the cell was deleted"); + const afterFinish = await state(goneCredentials); + assert.deepEqual(pick(afterFinish, ended), [ended, ended]); + assert.ok( + afterFinish.every((row) => row.revoked_at_clock && row.no_operator), + "revoked at the database clock, by no operator" + ); + assert.deepEqual( + pick(await state([keptCredential]), live), + [live], + "another tenant's credential stays live" + ); + assert.notEqual(await tenantStatus(kept.tenantId), "deleted"); + + // A second pass revokes nothing and moves nothing. + const revokedAt = async () => + ( + await pool!.query( + "SELECT id, revoked_at::text AS revoked_at FROM exomem_cloud_service_credentials WHERE tenant_id = $1 ORDER BY id", + [gone.tenantId] + ) + ).rows; + const first = await revokedAt(); + await interactiveTransaction((tx) => revokeCloudResourceConsent(tx, gone.tenantId)); + assert.deepEqual(await revokedAt(), first); + }); + it("finishes a never-paid awaiting_checkout tenant, with no references, without any Paddle call", async () => { await resetFleet(); const tenant = await admitCloudTenant({ source: "paddle" }); diff --git a/src/lib/exomem-hosted/cloud-consent.ts b/src/lib/exomem-hosted/cloud-consent.ts index 728d9b70..90f66eaf 100644 --- a/src/lib/exomem-hosted/cloud-consent.ts +++ b/src/lib/exomem-hosted/cloud-consent.ts @@ -11,6 +11,13 @@ * and keying on the tenant alone means a deletion never depends on Cloud * configuration being present. A missing setting must not leave a deleted * tenant's tokens live. + * + * The tenant's service credentials end here too. A credential belongs to the + * tenant, not to one cell, so a live one would serve the tenant's next cell + * after re-admission, and its issuance record would stay open for ever. The + * revocation time comes from the database clock and the revoking principal + * stays empty: no operator revoked it. The trigger on that table ends the + * credential's issuance record. */ import type { ExomemSql } from "./db"; @@ -46,10 +53,17 @@ export async function revokeCloudResourceConsent(tx: ExomemSql, tenantId: string FROM cloud_grants WHERE token.grant_id = cloud_grants.id AND token.revoked_at IS NULL RETURNING token.id + ), + revoked_service_credentials AS ( + UPDATE exomem_cloud_service_credentials AS credential + SET revoked_at = now() + WHERE credential.tenant_id = ${tenantId}::uuid AND credential.revoked_at IS NULL + RETURNING credential.id ) SELECT (SELECT count(*) FROM revoked_grants) AS grants, (SELECT count(*) FROM revoked_families) AS families, - (SELECT count(*) FROM revoked_tokens) AS tokens + (SELECT count(*) FROM revoked_tokens) AS tokens, + (SELECT count(*) FROM revoked_service_credentials) AS service_credentials `; } From 698da642c7706e8476c2bb766a6c7e461f082dc2 Mon Sep 17 00:00:00 2001 From: Artexis10 Date: Wed, 2 Dec 2026 13:14:23 +0000 Subject: [PATCH 15/29] Revoke a deleted cell's service credentials in the database, and backfill only records the prune keeps The previous commit revoked a tenant's service credentials from the statement that revokes a deleted cell's consent. That left the release that serves during a build, and an instant rollback, with no revocation. This commit reverts that statement, so the PR again changes no existing SQL of those flows, and moves the rule into migration 0102. An AFTER UPDATE row trigger on the cells table fires when a cell's desired state becomes deleted, and an AFTER DELETE trigger fires when a row that is not yet deleted goes. Both set the revocation time from the database clock on the tenant's unrevoked service credentials and leave the revoking principal empty. The existing trigger ends each credential's record. The function runs with its caller's rights and pins its search path: only the web app's role sets a cell's desired state, and it already holds update on that column, so no grant changes. No check for another live cell is needed, because one index allows a single cell that is not deleted for each tenant. The second migration now locks cells first, the order in which the flows write them. The migration also revokes once, at its own time, the unrevoked service credentials of every tenant that has no cell other than deleted ones, so the credentials of accounts that an earlier release deleted end too. No record stays open after that. The backfill now writes a record only for a row whose record the prune would keep: its end is empty or at most 90 days old. A token that expired earlier gets none, which shortens the lock on a large old table. Task 7.4 gives the operator the count query with the same predicate. The runbook's first range run starts at the log's first record, so check 1 does not list a skipped row. PostgreSQL tests, in both rights states: the web app's role sets a cell deleted and the tenant's credentials and records end at the database clock; another tenant's stay live; a stop changes nothing; a second update changes nothing; a delete by the schema owner of a live cell row ends them, and a delete of an old deleted row beside a live cell does not. The migration test ends a deleted tenant's live credential, keeps a live tenant's, and writes no record for a token that expired 100 days earlier. Text: the proposal, D5, D6, D12, limit 8, Risks, Open Question 1, tasks 3.1, 3.4, 5.4 and 7.4, both delta specs and the runbook. --- docs/runbooks/exomem-cloud-operations.md | 25 +- ...omem_issuance_log_and_download_tickets.sql | 88 ++++++- .../design.md | 16 +- .../proposal.md | 4 +- .../exomem-cloud-service-credentials/spec.md | 17 +- .../specs/exomem-hosted-mcp-oauth/spec.md | 9 +- .../tasks.md | 50 +++- scripts/exomem-cloud-grants.sql | 10 +- ...letion-finish-postgres.integration.test.ts | 15 +- ...-issuance-log-postgres.integration.test.ts | 247 +++++++++++++++++- src/lib/exomem-hosted/cloud-consent.ts | 16 +- 11 files changed, 418 insertions(+), 79 deletions(-) diff --git a/docs/runbooks/exomem-cloud-operations.md b/docs/runbooks/exomem-cloud-operations.md index ba2f4657..b5980486 100644 --- a/docs/runbooks/exomem-cloud-operations.md +++ b/docs/runbooks/exomem-cloud-operations.md @@ -840,6 +840,11 @@ and `exomem_cloud_service_credentials_issuance_end_delete` on `exomem_cloud_serv `exomem_oauth_token_families`. While they are off, a service credential's record stays open and the prune never deletes it. A token family's record then keeps its expiry. +Two triggers on `exomem_cloud_cells`, `exomem_cloud_cells_service_credentials_end_update` and +`exomem_cloud_cells_service_credentials_end_delete`, revoke a tenant's service credentials when its cell is deleted. While they are off, +a deleted account's service credentials stay live in the database, and the gateway still refuses them, because it serves only a tenant that has a cell +that is not deleted. Revoke each one through the operator API afterwards. + A hand-typed grant or a disabled trigger is an emergency state, not a fix. After either statement: 1. Open a commit that changes the grants script or the guard so that the flow works under the lock. @@ -854,7 +859,8 @@ A hand-typed grant or a disabled trigger is an emergency state, not a fix. After The credential is a token family, an access token, a refresh token, a service credential or a download ticket. A record holds identifiers only. These are the credential's `id` and kind, its grant, token family, client, tenant and user, and its expiry. A record also holds its own time and the database role that wrote it. It holds no token, digest, secret, path or address. A record that the migration wrote for an older -row has `backfilled` set. Its `recorded_at` is the migration's time. +row has `backfilled` set. Its `recorded_at` is the migration's time. The migration writes no record for a row whose end is more than 90 days old, because the prune +would delete the record at once. The recording fails closed. A credential insert fails when its record cannot be written. The web app's role cannot read, write or alter the log. The reconcile job calls `exomem_prune_issuance_log()` once a run. The function deletes at most @@ -864,10 +870,10 @@ row is deleted, the record's end becomes the database clock's time, and the prun family's record ends the same way when the family is revoked or deleted, if that is before its expiry. The session policy sets a token family's expiry, `EXOMEM_OAUTH_SESSION_MAX_DAYS` after sign-in (365 days by default, at most 730), and a refresh token's expiry, `EXOMEM_OAUTH_REFRESH_IDLE_DAYS` (30 days by default, at most 90). The database bounds no expiry, so a role that -writes a far expiry only lengthens retention. Deleting an account's cell revokes its service credentials, in the transaction that revokes its consent. After the deletion, a +writes a far expiry only lengthens retention. A database trigger revokes a tenant's service credentials when its cell is deleted, whichever release or job deletes it. The migration +also revoked once the credentials of every account that an earlier release had deleted. After the deletion, a token family's record and a service credential's record last 90 days, and an access token's or a refresh token's record lasts -until 90 days after its own expiry. A service credential of an account deleted before this release keeps an open record until -you revoke it through the operator API. The longest +until 90 days after its own expiry. The longest window after deletion is the refresh idle bound plus 90 days: 120 days by default, 180 at most. Only the schema owner deletes a record. The job's response reports the deleted counts as `issuancePruned.records` and `issuancePruned.tickets`. A value of `null` means that part failed, and the log line `exomem-issuance: log retention failed` names it. A failed part makes the job answer `503`, and the answer still carries `issuancePruned`. The prune runs @@ -895,10 +901,17 @@ open for longer than that hour is missed by the range checks. The read of one te WHERE id <= :prev AND recorded_at < (SELECT recorded_at FROM exomem_cloud_issuance_log WHERE id = :prev) - interval '1 hour' ORDER BY id DESC LIMIT 1), 0) AS lo \gset - SELECT coalesce((SELECT recorded_at FROM exomem_cloud_issuance_log WHERE id = :lo), '-infinity') AS lo_time \gset + SELECT greatest( + coalesce((SELECT recorded_at FROM exomem_cloud_issuance_log WHERE id = :lo), '-infinity'), + coalesce((SELECT recorded_at FROM exomem_cloud_issuance_log ORDER BY id LIMIT 1), '-infinity')) AS lo_time \gset \echo hi=:hi lo=:lo ``` + `lo_time` is never earlier than the log's first record. That record carries the migration's time when the backfill wrote + any record. The migration wrote no record for a row whose end was more than 90 days old, and the first run must not list + those rows. If the log is empty, `lo_time` is `-infinity`, and the first check lists every credential row that the + backfill skipped. + 4. Run the three checks. Each one is a finding when it returns a row. Credential rows without a record. One statement reads the credential rows and the log, so a credential and its @@ -989,6 +1002,8 @@ FROM (VALUES ('exomem_marketplace_reviewer_credentials', 'exomem_marketplace_reviewer_credentials_truncate_lock'), ('exomem_cloud_cells', 'exomem_cloud_cells_delete_lock'), ('exomem_cloud_cells', 'exomem_cloud_cells_truncate_lock'), + ('exomem_cloud_cells', 'exomem_cloud_cells_service_credentials_end_update'), + ('exomem_cloud_cells', 'exomem_cloud_cells_service_credentials_end_delete'), ('schema_releases', 'schema_releases_owner_only'), ('schema_releases', 'schema_releases_owner_only_truncate'), ('exomem_cloud_issuance_log', 'exomem_cloud_issuance_log_owner_only'), diff --git a/migrations/0102_exomem_issuance_log_and_download_tickets.sql b/migrations/0102_exomem_issuance_log_and_download_tickets.sql index 6be6fcb9..fdbc395f 100644 --- a/migrations/0102_exomem_issuance_log_and_download_tickets.sql +++ b/migrations/0102_exomem_issuance_log_and_download_tickets.sql @@ -6,13 +6,14 @@ -- which is after the records for the existing rows are written. The timeout -- bounds each wait, not the migration: when a lock stays busy, the migration -- fails, the job fails, and the operator starts the job again. One statement --- takes the locks in the order that revocation and issuance already write these --- tables (token families, then tokens). SHARE ROW EXCLUSIVE is the mode that +-- takes the locks in the order that the flows already write these tables: a +-- cell, then token families, then tokens. SHARE ROW EXCLUSIVE is the mode that -- CREATE TRIGGER takes. The download ticket table is created below, so no other -- session can see it before the commit and it needs no lock. SET LOCAL lock_timeout = '5s'; LOCK TABLE + exomem_cloud_cells, exomem_oauth_token_families, exomem_oauth_refresh_tokens, exomem_oauth_access_tokens, @@ -232,12 +233,40 @@ BEGIN $body$; $definition$, target_schema); + -- A tenant's service credentials end when its cell does. A credential belongs to + -- the tenant, not to one cell, so a live one would serve the tenant's next cell + -- after re-admission, and its record would stay open and never be pruned. This + -- function runs as the role that changes the cell, not as the schema owner. Only + -- the web app's role changes a cell's desired state, and it holds update on the + -- revocation column, so the function needs no owner rights. It sets the + -- revocation time from the database clock and leaves the revoking principal + -- empty, because no operator revoked the credential. The existing trigger on the + -- credential table then ends its record. It names the tenant only, because one + -- index allows a single non-deleted cell for each tenant, so no other live cell + -- remains when a cell becomes deleted. It pins its path for the same reason as + -- the functions above. + EXECUTE format($definition$ + CREATE FUNCTION %1$I.exomem_revoke_service_credentials_of_cell() RETURNS trigger + LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp + AS $body$ + BEGIN + UPDATE %1$I.exomem_cloud_service_credentials AS credential + SET revoked_at = pg_catalog.now() + WHERE credential.tenant_id = OLD.tenant_id AND credential.revoked_at IS NULL; + RETURN NULL; + END; + $body$; + $definition$, target_schema); + -- PostgreSQL gives PUBLIC execute on every new function. With it, any role -- could attach the recording function to a trigger on its own table and -- append records for rows that never existed. The grants script gives the web - -- app's role execute on the prune function only. + -- app's role execute on the prune function only. The cell trigger's function is + -- closed the same way, though it runs with its caller's rights and can write + -- nothing that its caller cannot. EXECUTE format('REVOKE ALL ON FUNCTION %I.exomem_record_issuance() FROM PUBLIC', target_schema); EXECUTE format('REVOKE ALL ON FUNCTION %I.exomem_prune_issuance_log() FROM PUBLIC', target_schema); + EXECUTE format('REVOKE ALL ON FUNCTION %I.exomem_revoke_service_credentials_of_cell() FROM PUBLIC', target_schema); END; $migration$; @@ -277,21 +306,52 @@ CREATE TRIGGER exomem_cloud_download_tickets_issuance_record AFTER INSERT ON exomem_cloud_download_tickets FOR EACH ROW EXECUTE FUNCTION exomem_record_issuance('download_ticket'); --- One backfilled record for each credential row that exists. It runs after the --- triggers exist and inside the transaction that holds the locks, so no row can --- land between the two steps without a record. The ticket table is new and empty. +-- A cell that becomes deleted, by update or by a delete of a live row, revokes the +-- tenant's service credentials in the same statement, whichever release runs it. +-- The delete trigger covers the schema owner, the only role that can delete a cell +-- row. Deleting a row that is already deleted changes nothing for the tenant. +CREATE TRIGGER exomem_cloud_cells_service_credentials_end_update + AFTER UPDATE ON exomem_cloud_cells + FOR EACH ROW WHEN (OLD.desired_state IS DISTINCT FROM 'deleted' AND NEW.desired_state = 'deleted') + EXECUTE FUNCTION exomem_revoke_service_credentials_of_cell(); +CREATE TRIGGER exomem_cloud_cells_service_credentials_end_delete + AFTER DELETE ON exomem_cloud_cells + FOR EACH ROW WHEN (OLD.desired_state IS DISTINCT FROM 'deleted') + EXECUTE FUNCTION exomem_revoke_service_credentials_of_cell(); + +-- One-time revoke. A service credential of a tenant with no cell other than deleted +-- ones is not served, so it ends now, whichever release deleted the cell. The +-- revocation time is the migration's time, and the revoking principal stays empty. +-- It runs before the backfill, which then writes each ended credential's record +-- with that time. +UPDATE exomem_cloud_service_credentials AS credential +SET revoked_at = pg_catalog.now() +WHERE credential.revoked_at IS NULL + AND NOT EXISTS ( + SELECT 1 FROM exomem_cloud_cells AS cell + WHERE cell.tenant_id = credential.tenant_id AND cell.desired_state <> 'deleted' + ); + +-- One backfilled record for each credential row that exists, except a row whose +-- record the prune would delete at once: its end is more than 90 days old, which is +-- the prune function's constant. Each record takes the end that the recording +-- function would write. It runs after the triggers exist and inside the transaction +-- that holds the locks, so no row can land between the two steps without a record. +-- The ticket table is new and empty. INSERT INTO exomem_cloud_issuance_log ( credential_kind, credential_id, grant_id, family_id, client_id, tenant_id, user_id, expires_at, database_role, backfilled ) -- A family that is revoked already ends at the migration's time, unless it expired earlier. SELECT 'token_family', family.id, family.grant_id, family.id, family.client_id, - grant_row.tenant_id, grant_row.user_id, - CASE WHEN family.revoked_at IS NOT NULL - THEN least(family.expires_at, pg_catalog.now()) ELSE family.expires_at END, - current_user, true + grant_row.tenant_id, grant_row.user_id, family_end.at, current_user, true FROM exomem_oauth_token_families AS family -JOIN exomem_oauth_grants AS grant_row ON grant_row.id = family.grant_id; +JOIN exomem_oauth_grants AS grant_row ON grant_row.id = family.grant_id +CROSS JOIN LATERAL ( + SELECT CASE WHEN family.revoked_at IS NOT NULL + THEN least(family.expires_at, pg_catalog.now()) ELSE family.expires_at END AS at +) AS family_end +WHERE family_end.at >= pg_catalog.now() - interval '90 days'; INSERT INTO exomem_cloud_issuance_log ( credential_kind, credential_id, grant_id, family_id, client_id, @@ -300,7 +360,8 @@ INSERT INTO exomem_cloud_issuance_log ( SELECT 'access_token', token.id, token.grant_id, token.family_id, token.client_id, grant_row.tenant_id, grant_row.user_id, token.expires_at, current_user, true FROM exomem_oauth_access_tokens AS token -JOIN exomem_oauth_grants AS grant_row ON grant_row.id = token.grant_id; +JOIN exomem_oauth_grants AS grant_row ON grant_row.id = token.grant_id +WHERE token.expires_at >= pg_catalog.now() - interval '90 days'; INSERT INTO exomem_cloud_issuance_log ( credential_kind, credential_id, grant_id, family_id, client_id, @@ -310,7 +371,8 @@ SELECT 'refresh_token', token.id, family.grant_id, token.family_id, family.clien grant_row.tenant_id, grant_row.user_id, token.expires_at, current_user, true FROM exomem_oauth_refresh_tokens AS token JOIN exomem_oauth_token_families AS family ON family.id = token.family_id -JOIN exomem_oauth_grants AS grant_row ON grant_row.id = family.grant_id; +JOIN exomem_oauth_grants AS grant_row ON grant_row.id = family.grant_id +WHERE token.expires_at >= pg_catalog.now() - interval '90 days'; -- A credential that is revoked already ends at the migration's time, like every -- backfilled time, so the prune keeps its record 90 days from the migration. diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md index 540d7ed7..bd341403 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md @@ -192,14 +192,14 @@ Other points: - **No foreign keys.** A record outlives its credential row, and the insert stays cheap. - **Identifiers only.** The log holds no token, digest, secret, principal, path or address. It fits the content-free telemetry requirement of the OAuth spec. - **Tenant and user are copied.** The copy costs one primary-key read of a row that the same transaction has just touched. D12 uses it to read one tenant's records. -- **Existing rows.** The migration writes one record for each credential row that already exists. Those records are marked `backfilled`. Their `recorded_at` is the migration's time, not the issuance time, and their database role is the schema owner. +- **Existing rows.** The migration writes a record for each credential row whose record the prune would keep: the end that the recording function would write is empty, or is at most 90 days before the migration. A token that expired longer ago gets no record, because the prune would delete it at once, and a large old table would only lengthen the lock. Those records are marked `backfilled`. Their `recorded_at` is the migration's time, not the issuance time, and their database role is the schema owner. - **Order inside the migration.** The migration creates each recording trigger first and writes the older rows' records afterwards, in the same transaction. Creating the trigger locks the table against writes until the commit. No row can then land between the two steps without a record. **What the migrations lock.** Creating a trigger locks its table against inserts, updates and deletes until the commit. Reads continue, the gateway's lookups included. The change ships two migrations, so that the longer one locks fewer tables: - The first adds `schema_releases` and the guards, and pins the functions' paths. It locks users, tenants, cells, reviewer credentials, clients, grants, token families, refresh tokens, access tokens and service credentials. It changes only the catalog, so it commits soon after it holds the last lock. -- The second adds the log, the ticket table, the recording triggers and the records for existing rows. It locks token families, refresh tokens, access tokens and service credentials until it has written those records. Code exchange, refresh, the Home mint, token revocation, service credential requests and the maintenance wait for it. Its length grows with the count of live credential rows. -- Each migration takes all its locks first, with one `LOCK TABLE` statement in the mode that creating a trigger takes. PostgreSQL takes them one at a time, in the order listed above. Admission writes users before tenants, and every revocation and issuance writes grants, then token families, then tokens, in that order. Three flows write in another order: cell deletion writes the OAuth tables, then tenants, then users, deletion finish writes tenants before users, and the lifecycle sweep writes a cell before its tenant. Any of them can deadlock with the first migration, and PostgreSQL then fails one of the two transactions. The reconcile job runs both flows every minute (`ops/exomem-hosted-schedules.json`), so a failed deletion step runs again a minute later. A deadlock fails the migration's job like a lock timeout does, and the operator starts the job again. +- The second adds the log, the ticket table, the recording triggers, the cell trigger of D6 and the records for existing rows. It locks cells, token families, refresh tokens, access tokens and service credentials until it has written those records. Code exchange, refresh, the Home mint, token revocation, service credential requests, cell changes and the maintenance wait for it. Its length grows with the rows that the backfill writes, not with the size of the tables: a row whose record the prune would delete is skipped. Task 7.4 gives the query that counts those rows, with the backfill's own predicate. +- Each migration takes all its locks first, with one `LOCK TABLE` statement in the mode that creating a trigger takes. PostgreSQL takes them one at a time, in the order listed above, and the second migration takes cells first: a cell's change writes the service credentials after it, through the trigger of D6. Admission writes users before tenants, and every revocation and issuance writes grants, then token families, then tokens, in that order. Three flows write in another order: cell deletion writes the OAuth tables, then tenants, then users, deletion finish writes tenants before users, and the lifecycle sweep writes a cell before its tenant. Any of them can deadlock with the first migration, and PostgreSQL then fails one of the two transactions. The reconcile job runs both flows every minute (`ops/exomem-hosted-schedules.json`), so a failed deletion step runs again a minute later. A deadlock fails the migration's job like a lock timeout does, and the operator starts the job again. - Each migration sets a lock timeout of five seconds. Without one, its lock request would wait behind any long transaction, and every later write would wait behind the request. The timeout bounds each wait, not the migration. While the migration waits for one lock, it holds every lock that it took before, and new writes to the table it waits for queue behind its request. In the worst case, a write to users waits through all nine waits of the first migration, about 45 seconds, before that migration commits or fails. When a wait times out, the migration fails, the job fails, and a later run tries again. - If the second migration fails, the guards are in force without the log. No flow depends on the log, and a later run adds it. @@ -213,7 +213,7 @@ A service credential has no expiry. Its record has no end while the credential i A token family's record holds the family's expiry from the insert. The same recording function moves it to the database clock's time when the family is revoked or its row is deleted, if that is earlier. An update trigger on the revocation time and a delete trigger run it, and a delete that an account's deletion cascades to runs it too. The function reads the clock, not the row's `revoked_at`, for the same reason as above. A revocation is one-way, and a revoked family cannot be used, so the web app's role cannot end a live family's record early. A partial index on the credential's identifier, which holds only token family records, finds the record. An access token or refresh token insert pays nothing for it, and a family insert pays one more index entry. For a family that is revoked when the migration runs, the record's end is the migration's time, unless the family expired earlier. An access token's and a refresh token's record do not end early. Each keeps its own expiry. -Deleting an account's cell revokes the account's service credentials, in the same statement that revokes its grants, families and access tokens. The statement runs when the tenant stops being served: the unpaid-invite expiry, the lifecycle reconcile and the account deletion all call it, and the deletion finish repeats it. It sets `revoked_at` to the database clock and leaves the revoking principal empty, because no operator revoked the credential. A credential belongs to the tenant, so a live one would otherwise serve the tenant's next cell after re-admission, and its record would stay open and never be pruned. The web app's role already holds update on that column, so no grant changes. Afterwards, a token family's record and a service credential's record last 90 days. A service credential of an account deleted before this release keeps an open record until the operator revokes it. An access token's record lasts until 90 days after its own expiry, which is an hour at most from its issue. A refresh token's record lasts until 90 days after its own expiry, which is the idle window at most from its issue: 30 days by default, at most 90. The longest window after deletion is therefore the refresh token's idle bound plus 90 days, which is 120 days by default and 180 at most. A download ticket's record lasts a day plus 90 days at most. +A cell's deletion revokes its tenant's service credentials, in the database. An `AFTER UPDATE` row trigger on the cells table fires when a cell's desired state becomes `deleted`, and an `AFTER DELETE` trigger fires when a row that is not yet deleted goes. Both set `revoked_at` to the database clock on the tenant's unrevoked service credentials and leave the revoking principal empty, because no operator revoked them. The recording function's trigger then ends each record. The database does this, not the web app's code, so the release that serves during a build, and an instant rollback to the release before this one, still end the credentials: no flow's SQL changes. A credential belongs to the tenant, so a live one would otherwise serve the tenant's next cell after re-admission, and its record would stay open and never be pruned. The trigger function runs with its caller's rights, not the schema owner's. Only the web app's role sets a cell's desired state, and it already holds update on the revocation column, so no grant changes. The gateway's role reads cells only, and the controller's role writes observed columns only, so neither fires it. The schema owner is the only role that can delete a cell row, so the delete trigger covers it. The trigger does not check for another live cell, because one index allows a single cell that is not deleted for each tenant. A second update, or a delete of a row that is already deleted, changes nothing. Afterwards, a token family's record and a service credential's record last 90 days. The migration also revokes once, at its own time, every unrevoked service credential of a tenant that has no cell other than deleted ones, so the credentials of accounts that a release before this one deleted end too. No record stays open after that. An access token's record lasts until 90 days after its own expiry, which is an hour at most from its issue. A refresh token's record lasts until 90 days after its own expiry, which is the idle window at most from its issue: 30 days by default, at most 90. The longest window after deletion is therefore the refresh token's idle bound plus 90 days, which is 120 days by default and 180 at most. A download ticket's record lasts a day plus 90 days at most. The expiry is safe to key on. It is set at insert and is a fixed column afterwards. A credential cannot be used after its expiry, so no usable credential loses its record early. @@ -366,7 +366,7 @@ A log that nobody can read cheaply proves nothing. Two readers exist, and each o - roles that the web app's role is a member of; - create rights that a role other than a superuser, the schema owner or `pg_database_owner` holds on the database or on a schema outside `pg_catalog` and `information_schema`, and schemas that a role other than the schema owner, the bootstrap superuser or `pg_database_owner` owns. -The first check also reads the credential tables in full. It filters their rows by `created_at`, and none of the five tables has an index on that column. A consumed refresh token of an unexpired family stays in its table, so the tables hold more than the live credentials. The read grows with those tables, not with the range of the log. The operator runs it on demand (limit 13), not on a schedule. A scheduled version needs an index on `created_at` or a different query, which is a later step. The last four read the catalog. +The first check also reads the credential tables in full. It filters their rows by `created_at`, and none of the five tables has an index on that column. A consumed refresh token of an unexpired family stays in its table, so the tables hold more than the live credentials. The read grows with those tables, not with the range of the log. The operator runs it on demand (limit 13), not on a schedule. A scheduled version needs an index on `created_at` or a different query, which is a later step. The migration writes no record for a row whose record the prune would delete (D5), so the check ignores rows from before the release. The first run starts at the release time, which is the `recorded_at` of the log's first record, and not at the start of time. That time is the migration's time when the backfill wrote any record. The check then flags no skipped row. The last four read the catalog. **Late commits.** PostgreSQL assigns a record's identifier at insert, not at commit. A record can therefore commit after a check has read past its identifier. Each run starts one hour of records before the point where the previous run stopped, so the next run reads such a record. It finds that start by walking back through the primary key, so the read stays bounded. A record whose transaction stayed open for longer than that hour is missed by the range checks. The read of one tenant's records still returns it. @@ -383,7 +383,7 @@ The claim is: the database records every credential that the gateway admits from 5. **What a grant allows.** The account service can change a grant's scopes. It can change an app's stored attributes, such as its name, its redirect addresses and whether it is enabled. The grant's tenant, user and app stay fixed. 6. **Suspension and blocks.** The account service sets a tenant's status and can add or remove an account block. 7. **The schema owner, the trigger right and the create right.** Whoever holds the schema-owner credential, administers the database server, or lands a commit on `main` can change the lock and the log. So can a role that holds the trigger right on a table in the schema, or a create right on the database or on a schema (D2). So can an administrator of the repository: they can edit the protected environment or the ruleset and run code with the schema-owner credential without landing a commit. The rollout turns off the administrators' bypass of the environment's rules, which narrows that path but does not remove it. Each change through `main` is a public commit. -8. **Retention.** The log keeps a record until 90 days after its credential expires. A token family's record ends earlier when the family is revoked or its row is deleted. A service credential, which has no expiry, ends the same way. The session policy sets a token family's expiry: 365 days from sign-in by default, at most 730. It sets a refresh token's expiry from its idle window, 30 days by default, at most 90, never past its family's expiry. The database bounds no expiry, so a role that writes a far expiry only lengthens retention. Deleting an account's cell revokes its service credentials, so after the deletion a token family's record and a service credential's record last 90 days. A service credential of an account deleted before this release keeps an open record until the operator revokes it. An access token's record and a refresh token's record last until 90 days after its own expiry. The longest window after deletion is the refresh token's idle bound plus 90 days: 120 days by default, 180 at most. No flow but the schema owner deletes a record, and deleting an account does not. +8. **Retention.** The log keeps a record until 90 days after its credential expires. A token family's record ends earlier when the family is revoked or its row is deleted. A service credential, which has no expiry, ends the same way. The session policy sets a token family's expiry: 365 days from sign-in by default, at most 730. It sets a refresh token's expiry from its idle window, 30 days by default, at most 90, never past its family's expiry. The database bounds no expiry, so a role that writes a far expiry only lengthens retention. Deleting an account's cell revokes its service credentials in the database, so after the deletion a token family's record and a service credential's record last 90 days. The migration revokes the credentials of accounts that were deleted before it, so no record stays open. An access token's record and a refresh token's record last until 90 days after its own expiry. The longest window after deletion is the refresh token's idle bound plus 90 days: 120 days by default, 180 at most. No flow but the schema owner deletes a record, and deleting an account does not. 9. **Use, revocation and deletion.** The log records issuance only. It does not say when a credential was used, revoked or deleted. 10. **The gateway's own keys.** The gateway signs cell tokens and upload capsules with its own keys. In this repository only gateway code loads them. Other services may hold them, and this change does not record what they sign. The rollout checks that no web deployment environment holds those keys. 11. **Credentials that the web app admits itself.** The web app issues and checks its own browser sessions. It does the same for the possession grants and sessions of the access record (`exomem_cloud_access_grants`, `exomem_cloud_access_sessions`). The gateway admits none of them, and the log records none. @@ -394,7 +394,7 @@ The claim is: the database records every credential that the gateway admits from - **A flow that the inventory missed changes a fixed column.** → It fails in production from the merge, because the lock has no switch. The proof runs every flow in the inventory as the web app's role. The schema owner's emergency statement restores the flow, and a commit makes the fix durable. - **The recording trigger fails in production.** → Every token insert fails. The proof runs each insert path through the trigger, and the runbook names the statement that disables it. Disabling it suspends the claim, and the runbook says so. -- **The second migration blocks writes to four tables while it writes the older rows' records.** → Token issue, refresh, the Home mint and revocation wait for that transaction (D5). Its length grows with the count of live credential rows. The rollout reads that count before the merge. +- **The second migration blocks writes to five tables while it writes the older rows' records.** → Token issue, refresh, the Home mint, revocation and cell changes wait for that transaction (D5). Its length grows with the rows that the backfill writes. The rollout reads that count before the merge, with the query of task 7.4. - **A migration meets its lock timeout or a deadlock.** → The job fails and records no schema release, so the build does not deploy. The operator starts the job again. If the production build already failed after its 15-minute wait, the operator redeploys it once the job is green, because nothing rebuilds it. - **A hand-typed grant gives a role the trigger right.** → The lock does not hold against that role until the grants script runs again. The runbook's checks list the grant. - **A hand-typed grant gives a role other than the owner a create right.** → The role may then reach code that runs as the schema owner (D2). The grants script does not revoke the right. The runbook's checks list the right and any schema the role created, and the operator revokes the right and drops the schema. @@ -429,5 +429,5 @@ Rollback: Each question has a default that this design already uses. -1. **Retention.** The design keeps a record until 90 days after its credential expires or, for a service credential, ends. A longer period keeps evidence for longer. It also keeps a finer record of when each account was active, and costs storage in proportion. Home's two-minute tokens are about three quarters of the log, so their retention decides its size. The period becomes part of the public claim. +1. **Retention.** The design keeps a record until 90 days after its credential expires or, for a service credential, ends. A longer period keeps evidence for longer. It also keeps a finer record of when each account was active, and costs storage in proportion. The period becomes part of the public claim. If size is the concern, the larger lever is the Home mint on every 30-second poll. The non-goals leave that mint out of this change, and a later change can take it. Cutting retention is not the cheaper fix: it removes evidence for every kind of credential, while changing the mint rate shrinks only Home's records. 2. **The migration job's runner.** A hosted runner may not reach the migration address. The choice is then a runner inside the database's network, or opening the address to hosted runners. The first keeps the address closed. It adds a machine to maintain, and a runner group that only this workflow may use. diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/proposal.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/proposal.md index 13acf9fd..6c4d87c2 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/proposal.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/proposal.md @@ -8,7 +8,7 @@ Substrate's web app signs users in and issues the credentials that the Exomem Cl - **Identity lock.** Guard triggers refuse every change to an identity field of a grant, token family, access token, refresh token, client or service credential. They also refuse a change to a tenant's owner and to a cell's identifier or tenant. A revocation time and a consumption time change only from empty to a time. Guards refuse a delete of a grant, client, tenant, user, cell, service credential or reviewer credential. Each guard holds for every role except the schema owner, whatever select, insert, update, delete and truncate rights that role holds. A guard checks the stored row, so no trigger that runs before it can slip a change past. On the five column-locked tables that the grants script narrows (grants, token families, access tokens, refresh tokens and service credentials), the web app's database role also keeps update rights only on the columns its flows change. - **The trigger right stays with the schema owner.** A role that holds the trigger right on a table can run its own code as the schema owner, and no guard holds against that. The grants script therefore revokes that right on every table in the schema from every other role, on every run. `PUBLIC` holds no execute right on the functions that this change adds. Every function that the database can run as the schema owner for another role pins its search path, so a role's own operator cannot run in place of the built-in one. - **No switch.** The lock and the log are in force once the migrations apply. Relaxing either one takes a migration or a grants change, which is a reviewed commit. -- **Issuance log.** An owner-owned trigger writes one record for every access token, refresh token, token family, service credential and download ticket row, in the inserting transaction. The log refuses every write that the schema owner does not run. A read-only audit role reads it in bounded ranges. A record is kept until 90 days after its credential stops being usable. That is its expiry or, for a token family and a service credential, the time it is revoked or its row is deleted, if that comes first. A service credential has no expiry. The session policy sets a token family's expiry (365 days from sign-in by default, at most 730) and a refresh token's expiry (30 days idle by default, at most 90, never past its family's expiry). The database bounds no expiry, so a role that writes a far expiry only lengthens retention. Deleting an account's cell revokes the account's service credentials in the transaction that revokes its consent, so after the deletion a token family's record and a service credential's record last 90 days. A service credential of an account deleted before this release keeps an open record until the operator revokes it. An access token's record and a refresh token's record last until 90 days after its own expiry. The longest window after deletion is the refresh token's idle bound plus 90 days: 120 days by default, 180 at most. No flow but the schema owner deletes a record. +- **Issuance log.** An owner-owned trigger writes one record for every access token, refresh token, token family, service credential and download ticket row, in the inserting transaction. The log refuses every write that the schema owner does not run. A read-only audit role reads it in bounded ranges. A record is kept until 90 days after its credential stops being usable. That is its expiry or, for a token family and a service credential, the time it is revoked or its row is deleted, if that comes first. A service credential has no expiry. The session policy sets a token family's expiry (365 days from sign-in by default, at most 730) and a refresh token's expiry (30 days idle by default, at most 90, never past its family's expiry). The database bounds no expiry, so a role that writes a far expiry only lengthens retention. A database trigger on the cells table revokes a tenant's service credentials when its cell is deleted, so after the deletion a token family's record and a service credential's record last 90 days. The migration revokes once the service credentials of accounts that a release before this one deleted, so no record stays open. It writes records only for rows that the prune would keep. An access token's record and a refresh token's record last until 90 days after its own expiry. The longest window after deletion is the refresh token's idle bound plus 90 days: 120 days by default, 180 at most. No flow but the schema owner deletes a record. - **Download tickets get a stored row.** A download ticket is a credential that the web app signs with a key it holds. Today no row backs it. The web app now stores one row for each ticket, and the gateway refuses a ticket without its row. - **Proof as the real roles.** Tests on a disposable PostgreSQL run every legitimate flow as the web app's role. They run each attack as that role twice: with the new rights, and with select, insert, update, delete and truncate on every table. @@ -28,7 +28,7 @@ The account service stays the sign-in provider, so it can still issue a credenti ## Impact -- **Database:** two migrations. The first adds the schema release table and the guards, and pins the search path of the functions that run as the schema owner. The second adds the issuance log, the recording triggers and the download ticket table. It blocks writes to the token and service credential tables while it records existing rows. Each sets a lock timeout. `scripts/exomem-cloud-grants.sql` gains the lock's rights, the trigger and execute revokes, and the audit role's rights. No new grants file. +- **Database:** two migrations. The first adds the schema release table and the guards, and pins the search path of the functions that run as the schema owner. The second adds the issuance log, the recording triggers, the download ticket table and a trigger on cells that revokes a deleted tenant's service credentials. It blocks writes to the cell, token and service credential tables while it records existing rows. Each sets a lock timeout. `scripts/exomem-cloud-grants.sql` gains the lock's rights, the trigger and execute revokes, and the audit role's rights. No new grants file. - **Deployment:** a new workflow under `.github/workflows/`, `scripts/migrate.ts`, the `vercel-build` script and the script it calls. Each deploy waits for the migration job before it builds. - **Web app:** the download handler stores a ticket row, and the reconcile job prunes ticket rows and issuance records. The prune is a lane beside the job's other lanes, so another lane's failure does not stop it, and its own failure fails the job's response. No other flow changes its SQL. - **Gateway:** one release that requires the ticket row. It rolls at least one maximum ticket lifetime after the web release, and it rolls back before the web app does. diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-cloud-service-credentials/spec.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-cloud-service-credentials/spec.md index ebd67347..cfbe84cd 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-cloud-service-credentials/spec.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-cloud-service-credentials/spec.md @@ -38,7 +38,7 @@ This requirement binds every role except the schema owner. The database SHALL re ### Requirement: Deleting a tenant's cell revokes its service credentials -The transaction that sets a tenant's Cloud cell to deleted SHALL revoke every service credential of that tenant that is not yet revoked. The revocation time SHALL come from the database clock, and the revoking principal SHALL stay empty. A second run SHALL change nothing, and no other tenant's credential SHALL change. The credential's issuance record SHALL then end, so the prune routine deletes it 90 days later. +A database trigger SHALL revoke every service credential of a tenant that is not yet revoked when the tenant's Cloud cell becomes deleted, or when a cell that is not yet deleted is deleted. The revocation time SHALL come from the database clock, and the revoking principal SHALL stay empty. The migration SHALL revoke the same credentials once for each tenant that has no cell other than deleted ones. No other tenant's credential SHALL change. The credential's issuance record SHALL then end. #### Scenario: An account's deletion finishes @@ -47,7 +47,18 @@ The transaction that sets a tenant's Cloud cell to deleted SHALL revoke every se - **AND** each credential's issuance record has an end - **AND** another tenant's service credential stays live and its record stays open -#### Scenario: The deletion runs again +#### Scenario: A release that does not revoke the credentials deletes the cell -- **WHEN** the revocation runs again for a tenant whose credentials are already revoked +- **WHEN** the web app's role sets a tenant's cell to deleted by any statement +- **THEN** each of the tenant's unrevoked service credentials is revoked, with the database clock's time and no revoking principal + +#### Scenario: The cell is deleted again + +- **WHEN** the web app's role sets a cell that is already deleted to deleted again - **THEN** no revocation time changes + +#### Scenario: A tenant that an earlier release deleted + +- **WHEN** the migration runs and a tenant has no cell other than deleted ones +- **THEN** each of its unrevoked service credentials is revoked, with the migration's time and no revoking principal +- **AND** the credentials of a tenant that has a live cell stay live diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md index 848a79bd..668da8b9 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md @@ -217,9 +217,14 @@ The database SHALL write one issuance record for every access token, refresh tok #### Scenario: Credentials that predate the log - **WHEN** the migration that creates the log runs -- **THEN** it writes one record for each credential row that already exists, after the recording triggers exist and in the same transaction +- **THEN** it writes one record for each credential row that already exists and whose record the prune routine would keep, after the recording triggers exist and in the same transaction - **AND** each of those records is marked as backfilled, carries the migration's time and names the schema owner as its database role +#### Scenario: Credentials that ended long before the log + +- **WHEN** the migration runs and a token row expired more than 90 days earlier +- **THEN** it writes no record for that row + ### Requirement: The issuance log accepts writes from the schema owner only The issuance log SHALL refuse every insert, update, delete and truncate that the schema owner does not run. That SHALL hold whatever select, insert, update, delete and truncate rights the acting role holds. Apart from the schema owner, only the recording routine and the prune routine SHALL write the log. The web app's, the gateway's and the controller's database roles SHALL hold no right on it. @@ -295,7 +300,7 @@ An issuance record SHALL be kept until at least 90 days after its credential exp ### Requirement: The issuance log is read in bounded ranges, without the schema-owner credential -A read-only audit role SHALL hold select on the issuance log and on the columns that its checks compare, and no other right. Each documented read of the log SHALL cover a bounded range of records. The check for credential rows without a record SHALL also read the credential tables in full, and the operator SHALL run it on demand. A reader SHALL be able to list one tenant's records a page at a time through an index. +A read-only audit role SHALL hold select on the issuance log and on the columns that its checks compare, and no other right. Each documented read of the log SHALL cover a bounded range of records. The check for credential rows without a record SHALL also read the credential tables in full, and the operator SHALL run it on demand, from the release time on its first run. A reader SHALL be able to list one tenant's records a page at a time through an index. #### Scenario: The audit role reads the log diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md index ecbd0256..87058b6e 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md @@ -98,8 +98,9 @@ names each decision as D1 to D12. update trigger on the revocation time and a delete trigger that end the record (D6). Revoke every right on the log in the same transaction. After the triggers exist, in the - same transaction, write one backfilled record for each credential row that - already exists. Verify: tasks 5.3 and 5.4. + same transaction, write one backfilled record for each credential row whose + record the prune would keep: its end is empty or at most 90 days old. Verify: + tasks 5.3 and 5.4. - [x] 3.2 Add the prune function with its batch of 10,000 records and its 90-day constant. Revoke its execute right from `PUBLIC` and give it to the web app's role. Call it from the reconcile job beside the OAuth maintenance, @@ -115,6 +116,25 @@ names each decision as D1 to D12. and grant execute on the prune function to the web app's role. When the audit role exists, grant it select on the log and on the columns that the D12 checks compare. Verify: task 5.6. +- [x] 3.4 In the second migration, add a trigger function that runs with its + caller's rights and pins its search path. Attach it to `exomem_cloud_cells` + with an `AFTER UPDATE` row trigger that fires when the desired state becomes + `deleted`, and an `AFTER DELETE` row trigger on a row that is not yet + deleted. It sets `revoked_at` to the database clock on the tenant's + unrevoked service credentials and leaves the revoking principal empty (D6). + Take the cells lock first in D5's `LOCK TABLE`. After the triggers exist, + revoke once, at the migration's time, every unrevoked service credential of + a tenant that has no cell other than deleted ones, before the backfill. + Revoke the function's execute right from `PUBLIC` in the migration and in + the grants script. Verify: task 5.4's migration test, and the trigger tests + of the issuance log suite in both states of group 5. As the web app's role, + setting a cell to `deleted` ends the tenant's credentials and their records + at the database clock, and another tenant's stay live. A cell that only + stops changes nothing, and a second update changes nothing. A delete of a + live cell row by the schema owner ends them, and a delete of an old deleted + row beside a live cell does not. The migration ends the live credential of a + tenant that has only deleted cells and keeps that of a tenant with a live + cell. ## 4. Download ticket rows (D8) @@ -182,7 +202,8 @@ without truncate. Neither state holds the trigger right. function. The trigger is refused and the log gains no record. After the schema owner renames the log table, a token insert fails and leaves no row. A migration run over existing credential rows writes one backfilled record - for each. + for each row whose record the prune would keep, and none for a token that + expired more than 90 days before. - [x] 5.5 Every legitimate flow runs as the web app's role, on the rights of the new grants script: authorization and consent, invite admission, code exchange, refresh rotation, token revocation by the client, by the owner and @@ -295,9 +316,26 @@ and its date. and no right to set `session_replication_role`. No role but the owner holds the trigger right on any table in the schema. Production runs the same PostgreSQL major version as CI, so the foreign-key test of D2 holds there. - Read the count of live credential rows, which sets - how long the second migration blocks writes to the token and service - credential tables. Create the audit role as the schema owner or another role + Read the count of rows that the second migration's backfill will write, + which sets how long it blocks writes to the cell, token and service + credential tables. The query repeats the backfill's own predicate: a row + counts when the end that its record would take is empty or at most 90 days + old. + + ```sql + SELECT + (SELECT count(*) FROM exomem_oauth_token_families AS family + WHERE CASE WHEN family.revoked_at IS NOT NULL + THEN least(family.expires_at, now()) ELSE family.expires_at END + >= now() - interval '90 days') AS token_families, + (SELECT count(*) FROM exomem_oauth_access_tokens + WHERE expires_at >= now() - interval '90 days') AS access_tokens, + (SELECT count(*) FROM exomem_oauth_refresh_tokens + WHERE expires_at >= now() - interval '90 days') AS refresh_tokens, + (SELECT count(*) FROM exomem_cloud_service_credentials) AS service_credentials; + ``` + + Create the audit role as the schema owner or another role that holds the role-creation right: `CREATE ROLE substrate_audit LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION;`, then set its password with `\password substrate_audit` in `psql` and store it in the operator's diff --git a/scripts/exomem-cloud-grants.sql b/scripts/exomem-cloud-grants.sql index 19fcf28e..41099db8 100644 --- a/scripts/exomem-cloud-grants.sql +++ b/scripts/exomem-cloud-grants.sql @@ -232,8 +232,8 @@ BEGIN END IF; END IF; - -- PostgreSQL gives PUBLIC execute on every new function. The guard and the - -- recording function need no grant: PostgreSQL checks the right when a + -- PostgreSQL gives PUBLIC execute on every new function. The guard, the + -- recording function and the cell trigger's function need no grant: PostgreSQL checks the right when a -- trigger is created, not when it fires, and only the schema owner creates -- these triggers. Only the web app's role may call the prune function, and -- the reconcile job does so. @@ -243,6 +243,9 @@ BEGIN IF to_regprocedure('exomem_record_issuance()') IS NOT NULL THEN REVOKE ALL ON FUNCTION exomem_record_issuance() FROM PUBLIC; END IF; + IF to_regprocedure('exomem_revoke_service_credentials_of_cell()') IS NOT NULL THEN + REVOKE ALL ON FUNCTION exomem_revoke_service_credentials_of_cell() FROM PUBLIC; + END IF; IF to_regprocedure('exomem_prune_issuance_log()') IS NOT NULL THEN REVOKE ALL ON FUNCTION exomem_prune_issuance_log() FROM PUBLIC; IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'substrate_app') THEN @@ -257,6 +260,9 @@ BEGIN IF to_regprocedure('exomem_record_issuance()') IS NOT NULL THEN EXECUTE format('REVOKE ALL ON FUNCTION exomem_record_issuance() FROM %I', lock_role); END IF; + IF to_regprocedure('exomem_revoke_service_credentials_of_cell()') IS NOT NULL THEN + EXECUTE format('REVOKE ALL ON FUNCTION exomem_revoke_service_credentials_of_cell() FROM %I', lock_role); + END IF; IF lock_role <> 'substrate_app' AND to_regprocedure('exomem_prune_issuance_log()') IS NOT NULL THEN EXECUTE format('REVOKE ALL ON FUNCTION exomem_prune_issuance_log() FROM %I', lock_role); END IF; diff --git a/src/lib/exomem-hosted/__tests__/cloud-deletion-finish-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-deletion-finish-postgres.integration.test.ts index 43d93f60..e1b53dbc 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-deletion-finish-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-deletion-finish-postgres.integration.test.ts @@ -16,7 +16,6 @@ import { type CloudDeletionFinishDependencies, type CloudDeletionFinishOutcome, } from "../cloud-deletion-finish"; -import { revokeCloudResourceConsent } from "../cloud-consent"; import { reconcileCloudCellDesiredState, runBoundedCloudReconcile } from "../cloud-lifecycle"; import { clearSettledEmailRecipients, drainExomemEmailOutbox } from "../email-outbox"; import { @@ -1579,7 +1578,7 @@ describe("Exomem Cloud deletion finish PostgreSQL integration", { skip: !databas const fake = fakePaddle(); let atFinish: Array> = []; await confirmCloudDeletion(gone, async (tenantId) => { - // The confirmation's reconcile deleted the cell row, which is where the tenant stops being served. + // The confirmation's reconcile set the cell to deleted, and the database ended the credentials with it. atFinish = await state(goneCredentials); return finishCloudAccountDeletion(tenantId, withPaddle(fake)); }); @@ -1597,18 +1596,6 @@ describe("Exomem Cloud deletion finish PostgreSQL integration", { skip: !databas "another tenant's credential stays live" ); assert.notEqual(await tenantStatus(kept.tenantId), "deleted"); - - // A second pass revokes nothing and moves nothing. - const revokedAt = async () => - ( - await pool!.query( - "SELECT id, revoked_at::text AS revoked_at FROM exomem_cloud_service_credentials WHERE tenant_id = $1 ORDER BY id", - [gone.tenantId] - ) - ).rows; - const first = await revokedAt(); - await interactiveTransaction((tx) => revokeCloudResourceConsent(tx, gone.tenantId)); - assert.deepEqual(await revokedAt(), first); }); it("finishes a never-paid awaiting_checkout tenant, with no references, without any Paddle call", async () => { diff --git a/src/lib/exomem-hosted/__tests__/cloud-issuance-log-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-issuance-log-postgres.integration.test.ts index 71797223..dd175669 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-issuance-log-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-issuance-log-postgres.integration.test.ts @@ -10,6 +10,8 @@ import { __setExomemSqlForTests, type ExomemSql } from "../db"; import { pruneIssuanceState } from "../issuance-maintenance"; import { createLockFixture, + randomCellId, + seedCell, seedWorld, tableSnapshot, type LockFixture, @@ -351,6 +353,88 @@ for (const state of STATES) { ); }); + // A cell that ends revokes the tenant's service credentials in the same statement, so a + // release that does not know the rule, or a rollback, still ends them. Only the web app's role + // sets a cell's desired state, so these run as it. + const cells = () => fx.q("exomem_cloud_cells"); + const credentialState = async (credentialId: string) => + ( + await fx.owner.query<{ + revoked: boolean; + at_clock: boolean; + no_operator: boolean; + at: string | null; + }>( + `SELECT revoked_at IS NOT NULL AS revoked, coalesce(revoked_at <= now(), false) AS at_clock, + revoked_by_principal_digest IS NULL AS no_operator, revoked_at::text AS at + FROM ${serviceCredentials()} WHERE id = $1`, + [credentialId] + ) + ).rows[0]!; + + it("revokes a tenant's live service credentials at the database clock, and ends their records, when the web app's role sets its cell to deleted", async () => { + const gone = await seedWorld(fx.owner); + const kept = await seedWorld(fx.owner); + const goneCell = await seedCell(fx.owner, gone.tenantId); + await seedCell(fx.owner, kept.tenantId); + const spentBefore = await credentialState(gone.spent.serviceCredentialId); + assert.deepEqual(await recordEnd(gone.serviceCredentialId), { open: true, at_now: false }); + + await fx.app.query(`UPDATE ${cells()} SET desired_state = 'stopped' WHERE cell_id = $1`, [ + goneCell, + ]); + assert.equal( + (await credentialState(gone.serviceCredentialId)).revoked, + false, + "a cell that only stops keeps its tenant's credentials" + ); + + await fx.app.query(`UPDATE ${cells()} SET desired_state = 'deleted' WHERE cell_id = $1`, [ + goneCell, + ]); + const revoked = await credentialState(gone.serviceCredentialId); + assert.deepEqual( + { + revoked: revoked.revoked, + at_clock: revoked.at_clock, + no_operator: revoked.no_operator, + }, + { revoked: true, at_clock: true, no_operator: true } + ); + assert.deepEqual(await recordEnd(gone.serviceCredentialId), { open: false, at_now: true }); + assert.deepEqual( + await credentialState(gone.spent.serviceCredentialId), + spentBefore, + "a credential that was already revoked keeps its time and its revoking principal" + ); + assert.equal((await credentialState(kept.serviceCredentialId)).revoked, false); + assert.deepEqual(await recordEnd(kept.serviceCredentialId), { open: true, at_now: false }); + + await fx.app.query(`UPDATE ${cells()} SET desired_state = 'deleted' WHERE cell_id = $1`, [ + goneCell, + ]); + assert.deepEqual( + await credentialState(gone.serviceCredentialId), + revoked, + "a second update changes nothing" + ); + }); + + it("leaves a re-admitted tenant's credentials alone when its old deleted cell row goes, and revokes them when the schema owner deletes its live cell row", async () => { + const world = await seedWorld(fx.owner); + const oldCell = randomCellId(); + await fx.owner.query( + `INSERT INTO ${cells()} (cell_id, tenant_id, desired_state) VALUES ($1, $2, 'deleted')`, + [oldCell, world.tenantId] + ); + const liveCell = await seedCell(fx.owner, world.tenantId); + await fx.owner.query(`DELETE FROM ${cells()} WHERE cell_id = $1`, [oldCell]); + assert.equal((await credentialState(world.serviceCredentialId)).revoked, false); + await fx.owner.query(`DELETE FROM ${cells()} WHERE cell_id = $1`, [liveCell]); + assert.equal((await credentialState(world.serviceCredentialId)).revoked, true); + assert.deepEqual(await recordEnd(world.serviceCredentialId), { open: false, at_now: true }); + }); + // A token family's record holds the family's expiry. A revocation or a delete before then // moves it to the database clock's time, so the prune keeps it 90 days from the end. const families = () => fx.q("exomem_oauth_token_families"); @@ -483,6 +567,43 @@ describe("The migration that adds the log", { skip: !databaseUrl }, () => { let migrationRoot: string; const NO_GRANTS = "/nonexistent/exomem-cloud-grants.sql"; + type Seeded = { + live: World; + deleted: World; + deletedSpentRevokedAt: string; + stale: World; + staleOld: { familyId: string; accessTokenId: string; refreshTokenId: string }; + staleRecent: { familyId: string; accessTokenId: string; refreshTokenId: string }; + }; + let seeded: Seeded; + + // A family with an access token and a refresh token, all of which expired the given number of days ago. + const seedExpiredChain = async (world: World, daysAgo: number) => { + const id = async (text: string, values: unknown[]): Promise => + (await fx.owner.query<{ id: string }>(text, values)).rows[0]!.id; + const familyId = await id( + `INSERT INTO exomem_oauth_token_families (grant_id, client_id, created_at, expires_at) + VALUES ($1, $2, now() - make_interval(days => $3 + 1), now() - make_interval(days => $3)) + RETURNING id`, + [world.grantId, world.clientId, daysAgo] + ); + const accessTokenId = await id( + `INSERT INTO exomem_oauth_access_tokens + (access_digest, grant_id, family_id, client_id, resource, scopes, created_at, expires_at) + VALUES ($1, $2, $3, $4, 'https://example.test/mcp', ARRAY['mcp:read'], + now() - make_interval(days => $5 + 1), now() - make_interval(days => $5)) + RETURNING id`, + [randomBytes(32), world.grantId, familyId, world.clientId, daysAgo] + ); + const refreshTokenId = await id( + `INSERT INTO exomem_oauth_refresh_tokens (refresh_digest, family_id, created_at, expires_at) + VALUES ($1, $2, now() - make_interval(days => $3 + 1), now() - make_interval(days => $3)) + RETURNING id`, + [randomBytes(32), familyId, daysAgo] + ); + return { familyId, accessTokenId, refreshTokenId }; + }; + before(async () => { fx = await createLockFixture("narrow", { migrate: false }); migrationRoot = await mkdtemp(join(tmpdir(), "issuance-log-upgrade-")); @@ -490,14 +611,6 @@ describe("The migration that adds the log", { skip: !databaseUrl }, () => { if (name.endsWith(".sql") && name < "0102") await cp(join("migrations", name), join(migrationRoot, name)); } - }); - - after(async () => { - await rm(migrationRoot, { recursive: true, force: true }); - await fx?.close(); - }); - - it("writes one backfilled record for each credential row that existed, and gives the web app's role no right on the new tables", async () => { // Earlier releases left default privileges that give the web app's role every right on a // table a migration creates; the new tables must not inherit them. await fx.admin.query( @@ -509,8 +622,42 @@ describe("The migration that adds the log", { skip: !databaseUrl }, () => { migrationsDir: migrationRoot, grantsFile: NO_GRANTS, }); - const world = await seedWorld(fx.owner); + // A tenant whose cell is live, with an older cell that was deleted and then re-admitted. + const live = await seedWorld(fx.owner); + await fx.owner.query( + "INSERT INTO exomem_cloud_cells (cell_id, tenant_id, desired_state) VALUES ($1, $2, 'deleted')", + [randomCellId(), live.tenantId] + ); + await seedCell(fx.owner, live.tenantId); + // A tenant that a release before this one deleted: only a deleted cell, and a credential left live. + const deleted = await seedWorld(fx.owner); + await fx.owner.query( + "INSERT INTO exomem_cloud_cells (cell_id, tenant_id, desired_state) VALUES ($1, $2, 'deleted')", + [randomCellId(), deleted.tenantId] + ); + const deletedSpentRevokedAt = ( + await fx.owner.query<{ at: string }>( + "SELECT revoked_at::text AS at FROM exomem_cloud_service_credentials WHERE id = $1", + [deleted.spent.serviceCredentialId] + ) + ).rows[0]!.at; + // A tenant with credentials that expired 100 days ago, which the prune would delete at once, and + // credentials that expired 10 days ago, which it keeps. + const stale = await seedWorld(fx.owner); + await seedCell(fx.owner, stale.tenantId); + const staleOld = await seedExpiredChain(stale, 100); + const staleRecent = await seedExpiredChain(stale, 10); + seeded = { live, deleted, deletedSpentRevokedAt, stale, staleOld, staleRecent }; await applyMigrations({ databaseUrl: fx.roleUrl("substrate_owner"), grantsFile: NO_GRANTS }); + }); + + after(async () => { + await rm(migrationRoot, { recursive: true, force: true }); + await fx?.close(); + }); + + it("writes one backfilled record for each credential row that existed, and gives the web app's role no right on the new tables", async () => { + const world = seeded.live; const counts = await fx.owner.query<{ credential_kind: string; @@ -580,4 +727,86 @@ describe("The migration that adds the log", { skip: !databaseUrl }, () => { "no right at all until the grants script runs" ); }); + + it("revokes, at the migration's time and with no revoking principal, the live service credentials of a tenant that has only deleted cells, and leaves a live tenant's alone", async () => { + const state = async (credentialId: string) => + ( + await fx.owner.query<{ + revoked: boolean; + no_operator: boolean; + at_migration: boolean; + record_end_matches: boolean; + }>( + `SELECT credential.revoked_at IS NOT NULL AS revoked, + credential.revoked_by_principal_digest IS NULL AS no_operator, + credential.revoked_at = record.recorded_at AS at_migration, + record.expires_at IS NOT DISTINCT FROM credential.revoked_at AS record_end_matches + FROM exomem_cloud_service_credentials AS credential + JOIN exomem_cloud_issuance_log AS record + ON record.credential_kind = 'service_credential' AND record.credential_id = credential.id + WHERE credential.id = $1`, + [credentialId] + ) + ).rows[0]!; + const ended = await state(seeded.deleted.serviceCredentialId); + assert.equal(ended.revoked, true, "the deleted tenant's credential ends"); + assert.equal(ended.no_operator, true, "no operator revoked it"); + assert.equal( + ended.at_migration, + true, + "it ends at the migration's time, which stamps the record" + ); + assert.equal(ended.record_end_matches, true, "its record ends at the same time"); + assert.equal( + (await state(seeded.live.serviceCredentialId)).revoked, + false, + "a tenant with a live cell keeps its credential, whatever deleted cell it had before" + ); + const spent = await fx.owner.query<{ at: string; operator: boolean }>( + `SELECT revoked_at::text AS at, revoked_by_principal_digest IS NOT NULL AS operator + FROM exomem_cloud_service_credentials WHERE id = $1`, + [seeded.deleted.spent.serviceCredentialId] + ); + assert.deepEqual( + spent.rows, + [{ at: seeded.deletedSpentRevokedAt, operator: true }], + "a credential that was revoked before keeps its time and its operator" + ); + }); + + it("writes no record for a credential whose record the prune would delete at once, and one for each that is live or ended within 90 days", async () => { + const recorded = async (kind: string, credentialId: string) => + ( + await fx.owner.query( + "SELECT 1 FROM exomem_cloud_issuance_log WHERE credential_kind = $1 AND credential_id = $2", + [kind, credentialId] + ) + ).rowCount; + for (const [label, rows, count] of [ + ["expired 100 days ago", seeded.staleOld, 0], + ["expired 10 days ago", seeded.staleRecent, 1], + ] as const) { + assert.equal(await recorded("token_family", rows.familyId), count, `family ${label}`); + assert.equal( + await recorded("access_token", rows.accessTokenId), + count, + `access token ${label}` + ); + assert.equal( + await recorded("refresh_token", rows.refreshTokenId), + count, + `refresh token ${label}` + ); + } + assert.equal( + await recorded("token_family", seeded.stale.familyId), + 1, + "a live family has a record" + ); + assert.equal( + await recorded("service_credential", seeded.stale.spent.serviceCredentialId), + 1, + "a service credential revoked before the migration ends at the migration's time, so its record is kept" + ); + }); }); diff --git a/src/lib/exomem-hosted/cloud-consent.ts b/src/lib/exomem-hosted/cloud-consent.ts index 90f66eaf..728d9b70 100644 --- a/src/lib/exomem-hosted/cloud-consent.ts +++ b/src/lib/exomem-hosted/cloud-consent.ts @@ -11,13 +11,6 @@ * and keying on the tenant alone means a deletion never depends on Cloud * configuration being present. A missing setting must not leave a deleted * tenant's tokens live. - * - * The tenant's service credentials end here too. A credential belongs to the - * tenant, not to one cell, so a live one would serve the tenant's next cell - * after re-admission, and its issuance record would stay open for ever. The - * revocation time comes from the database clock and the revoking principal - * stays empty: no operator revoked it. The trigger on that table ends the - * credential's issuance record. */ import type { ExomemSql } from "./db"; @@ -53,17 +46,10 @@ export async function revokeCloudResourceConsent(tx: ExomemSql, tenantId: string FROM cloud_grants WHERE token.grant_id = cloud_grants.id AND token.revoked_at IS NULL RETURNING token.id - ), - revoked_service_credentials AS ( - UPDATE exomem_cloud_service_credentials AS credential - SET revoked_at = now() - WHERE credential.tenant_id = ${tenantId}::uuid AND credential.revoked_at IS NULL - RETURNING credential.id ) SELECT (SELECT count(*) FROM revoked_grants) AS grants, (SELECT count(*) FROM revoked_families) AS families, - (SELECT count(*) FROM revoked_tokens) AS tokens, - (SELECT count(*) FROM revoked_service_credentials) AS service_credentials + (SELECT count(*) FROM revoked_tokens) AS tokens `; } From 41d2d33459bded25f59d91b11794e366e83327f6 Mon Sep 17 00:00:00 2001 From: Artexis10 Date: Wed, 2 Dec 2026 13:29:36 +0000 Subject: [PATCH 16/29] Refuse a service credential for a tenant with no live cell, and lock that cell A service credential that commits just after a cell's deletion trigger ran stays unrevoked and serves the tenant's next cell after re-admission. A BEFORE INSERT trigger on exomem_cloud_service_credentials now reads the tenant's cell that is not deleted with FOR SHARE and refuses the insert (SQLSTATE 23503, constraint exomem_cloud_service_credentials_live_cell) when none exists. A deletion that starts after the insert waits for the insert to commit, and its trigger then revokes the new credential. An insert that waits for a deletion is refused once the deletion commits. The trigger function runs with its caller's rights and pins its search path. The migration and the grants script revoke its execute right. The service credential request answers the refusal as SERVICE_CREDENTIAL_TENANT_INELIGIBLE (409). The lifecycle sweep locks a cell before its tenant and a request locks the tenant first, so the two can deadlock; D5 records that and PostgreSQL fails one of them. Tests run as the web app's role in both rights states, on two connections with a statement timeout: refusal for a deleted-only tenant, a deletion that waits for an open insert, and an insert that waits for an open deletion. The seed world now has a live cell, as a credential needs one. --- docs/runbooks/exomem-cloud-operations.md | 6 + ...omem_issuance_log_and_download_tickets.sql | 33 ++++++ .../design.md | 4 +- .../proposal.md | 2 +- .../exomem-cloud-service-credentials/spec.md | 19 ++- .../tasks.md | 15 +++ scripts/exomem-cloud-grants.sql | 14 ++- ...identity-lock-postgres.integration.test.ts | 3 +- ...-issuance-log-postgres.integration.test.ts | 112 ++++++++++++++++-- ...e-credentials-postgres.integration.test.ts | 26 ++++ .../__tests__/identity-lock-fixture.ts | 27 ++++- .../cloud-service-credentials.ts | 16 ++- 12 files changed, 257 insertions(+), 20 deletions(-) diff --git a/docs/runbooks/exomem-cloud-operations.md b/docs/runbooks/exomem-cloud-operations.md index b5980486..5f7c9607 100644 --- a/docs/runbooks/exomem-cloud-operations.md +++ b/docs/runbooks/exomem-cloud-operations.md @@ -845,6 +845,11 @@ Two triggers on `exomem_cloud_cells`, `exomem_cloud_cells_service_credentials_en a deleted account's service credentials stay live in the database, and the gateway still refuses them, because it serves only a tenant that has a cell that is not deleted. Revoke each one through the operator API afterwards. +One trigger on `exomem_cloud_service_credentials`, `exomem_cloud_service_credentials_live_cell`, refuses a new service credential for a tenant +that has no cell that is not deleted, and locks that cell's row while the credential is inserted. While it is off, a request that overlaps a cell's +deletion can commit after the deletion's trigger ran, and its credential stays live for the tenant's next cell. After it is on again, revoke through +the operator API each live service credential of a tenant that has no cell that is not deleted. + A hand-typed grant or a disabled trigger is an emergency state, not a fix. After either statement: 1. Open a commit that changes the grants script or the guard so that the flow works under the lock. @@ -1004,6 +1009,7 @@ FROM (VALUES ('exomem_cloud_cells', 'exomem_cloud_cells_truncate_lock'), ('exomem_cloud_cells', 'exomem_cloud_cells_service_credentials_end_update'), ('exomem_cloud_cells', 'exomem_cloud_cells_service_credentials_end_delete'), + ('exomem_cloud_service_credentials', 'exomem_cloud_service_credentials_live_cell'), ('schema_releases', 'schema_releases_owner_only'), ('schema_releases', 'schema_releases_owner_only_truncate'), ('exomem_cloud_issuance_log', 'exomem_cloud_issuance_log_owner_only'), diff --git a/migrations/0102_exomem_issuance_log_and_download_tickets.sql b/migrations/0102_exomem_issuance_log_and_download_tickets.sql index fdbc395f..9c838dcd 100644 --- a/migrations/0102_exomem_issuance_log_and_download_tickets.sql +++ b/migrations/0102_exomem_issuance_log_and_download_tickets.sql @@ -258,6 +258,32 @@ BEGIN $body$; $definition$, target_schema); + -- A service credential needs a live cell when it is inserted, and the check + -- locks that cell's row. Without the lock, a credential could commit just after + -- the trigger above ran for a deletion that the credential's transaction had not + -- seen, and it would stay live for the tenant's next cell. The share lock makes + -- a deletion wait for the insert, and the trigger above then revokes the + -- committed credential. An insert that waits for a deletion finds no live cell + -- when the deletion commits, and is refused. It runs with its caller's rights, + -- which are the web app's role's: select on the cell's columns and update on the + -- columns that the share lock needs. It pins its path like the functions above. + EXECUTE format($definition$ + CREATE FUNCTION %1$I.exomem_require_live_cell_for_service_credential() RETURNS trigger + LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp + AS $body$ + BEGIN + PERFORM 1 FROM %1$I.exomem_cloud_cells AS cell + WHERE cell.tenant_id = NEW.tenant_id AND cell.desired_state <> 'deleted' + FOR SHARE; + IF NOT FOUND THEN + RAISE EXCEPTION 'EXOMEM_SERVICE_CREDENTIAL_NO_LIVE_CELL: the tenant has no cell that is not deleted' + USING ERRCODE = '23503', CONSTRAINT = 'exomem_cloud_service_credentials_live_cell'; + END IF; + RETURN NEW; + END; + $body$; + $definition$, target_schema); + -- PostgreSQL gives PUBLIC execute on every new function. With it, any role -- could attach the recording function to a trigger on its own table and -- append records for rows that never existed. The grants script gives the web @@ -267,6 +293,7 @@ BEGIN EXECUTE format('REVOKE ALL ON FUNCTION %I.exomem_record_issuance() FROM PUBLIC', target_schema); EXECUTE format('REVOKE ALL ON FUNCTION %I.exomem_prune_issuance_log() FROM PUBLIC', target_schema); EXECUTE format('REVOKE ALL ON FUNCTION %I.exomem_revoke_service_credentials_of_cell() FROM PUBLIC', target_schema); + EXECUTE format('REVOKE ALL ON FUNCTION %I.exomem_require_live_cell_for_service_credential() FROM PUBLIC', target_schema); END; $migration$; @@ -319,6 +346,12 @@ CREATE TRIGGER exomem_cloud_cells_service_credentials_end_delete FOR EACH ROW WHEN (OLD.desired_state IS DISTINCT FROM 'deleted') EXECUTE FUNCTION exomem_revoke_service_credentials_of_cell(); +-- A service credential is inserted only for a tenant with a live cell, and the +-- insert locks that cell's row (the function's comment says why). +CREATE TRIGGER exomem_cloud_service_credentials_live_cell + BEFORE INSERT ON exomem_cloud_service_credentials + FOR EACH ROW EXECUTE FUNCTION exomem_require_live_cell_for_service_credential(); + -- One-time revoke. A service credential of a tenant with no cell other than deleted -- ones is not served, so it ends now, whichever release deleted the cell. The -- revocation time is the migration's time, and the revoking principal stays empty. diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md index bd341403..502223be 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md @@ -199,7 +199,7 @@ Other points: - The first adds `schema_releases` and the guards, and pins the functions' paths. It locks users, tenants, cells, reviewer credentials, clients, grants, token families, refresh tokens, access tokens and service credentials. It changes only the catalog, so it commits soon after it holds the last lock. - The second adds the log, the ticket table, the recording triggers, the cell trigger of D6 and the records for existing rows. It locks cells, token families, refresh tokens, access tokens and service credentials until it has written those records. Code exchange, refresh, the Home mint, token revocation, service credential requests, cell changes and the maintenance wait for it. Its length grows with the rows that the backfill writes, not with the size of the tables: a row whose record the prune would delete is skipped. Task 7.4 gives the query that counts those rows, with the backfill's own predicate. -- Each migration takes all its locks first, with one `LOCK TABLE` statement in the mode that creating a trigger takes. PostgreSQL takes them one at a time, in the order listed above, and the second migration takes cells first: a cell's change writes the service credentials after it, through the trigger of D6. Admission writes users before tenants, and every revocation and issuance writes grants, then token families, then tokens, in that order. Three flows write in another order: cell deletion writes the OAuth tables, then tenants, then users, deletion finish writes tenants before users, and the lifecycle sweep writes a cell before its tenant. Any of them can deadlock with the first migration, and PostgreSQL then fails one of the two transactions. The reconcile job runs both flows every minute (`ops/exomem-hosted-schedules.json`), so a failed deletion step runs again a minute later. A deadlock fails the migration's job like a lock timeout does, and the operator starts the job again. +- Each migration takes all its locks first, with one `LOCK TABLE` statement in the mode that creating a trigger takes. PostgreSQL takes them one at a time, in the order listed above, and the second migration takes cells first: a cell's change writes the service credentials after it, through the trigger of D6. Admission writes users before tenants, and every revocation and issuance writes grants, then token families, then tokens, in that order. Three flows write in another order: cell deletion writes the OAuth tables, then tenants, then users, deletion finish writes tenants before users, and the lifecycle sweep writes a cell before its tenant. Any of them can deadlock with the first migration, and PostgreSQL then fails one of the two transactions. A service credential request locks the tenant, then the cell through D6's trigger. That is the order of deletion finish, which waits for the request on the tenant, and the reverse of the lifecycle sweep. If the sweep and a request for the same tenant overlap, they can deadlock, and PostgreSQL fails one of them. The sweep runs again a minute later, and the operator sends a failed request again. The reconcile job runs both flows every minute (`ops/exomem-hosted-schedules.json`), so a failed deletion step runs again a minute later. A deadlock fails the migration's job like a lock timeout does, and the operator starts the job again. - Each migration sets a lock timeout of five seconds. Without one, its lock request would wait behind any long transaction, and every later write would wait behind the request. The timeout bounds each wait, not the migration. While the migration waits for one lock, it holds every lock that it took before, and new writes to the table it waits for queue behind its request. In the worst case, a write to users waits through all nine waits of the first migration, about 45 seconds, before that migration commits or fails. When a wait times out, the migration fails, the job fails, and a later run tries again. - If the second migration fails, the guards are in force without the log. No flow depends on the log, and a later run adds it. @@ -213,7 +213,7 @@ A service credential has no expiry. Its record has no end while the credential i A token family's record holds the family's expiry from the insert. The same recording function moves it to the database clock's time when the family is revoked or its row is deleted, if that is earlier. An update trigger on the revocation time and a delete trigger run it, and a delete that an account's deletion cascades to runs it too. The function reads the clock, not the row's `revoked_at`, for the same reason as above. A revocation is one-way, and a revoked family cannot be used, so the web app's role cannot end a live family's record early. A partial index on the credential's identifier, which holds only token family records, finds the record. An access token or refresh token insert pays nothing for it, and a family insert pays one more index entry. For a family that is revoked when the migration runs, the record's end is the migration's time, unless the family expired earlier. An access token's and a refresh token's record do not end early. Each keeps its own expiry. -A cell's deletion revokes its tenant's service credentials, in the database. An `AFTER UPDATE` row trigger on the cells table fires when a cell's desired state becomes `deleted`, and an `AFTER DELETE` trigger fires when a row that is not yet deleted goes. Both set `revoked_at` to the database clock on the tenant's unrevoked service credentials and leave the revoking principal empty, because no operator revoked them. The recording function's trigger then ends each record. The database does this, not the web app's code, so the release that serves during a build, and an instant rollback to the release before this one, still end the credentials: no flow's SQL changes. A credential belongs to the tenant, so a live one would otherwise serve the tenant's next cell after re-admission, and its record would stay open and never be pruned. The trigger function runs with its caller's rights, not the schema owner's. Only the web app's role sets a cell's desired state, and it already holds update on the revocation column, so no grant changes. The gateway's role reads cells only, and the controller's role writes observed columns only, so neither fires it. The schema owner is the only role that can delete a cell row, so the delete trigger covers it. The trigger does not check for another live cell, because one index allows a single cell that is not deleted for each tenant. A second update, or a delete of a row that is already deleted, changes nothing. Afterwards, a token family's record and a service credential's record last 90 days. The migration also revokes once, at its own time, every unrevoked service credential of a tenant that has no cell other than deleted ones, so the credentials of accounts that a release before this one deleted end too. No record stays open after that. An access token's record lasts until 90 days after its own expiry, which is an hour at most from its issue. A refresh token's record lasts until 90 days after its own expiry, which is the idle window at most from its issue: 30 days by default, at most 90. The longest window after deletion is therefore the refresh token's idle bound plus 90 days, which is 120 days by default and 180 at most. A download ticket's record lasts a day plus 90 days at most. +A cell's deletion revokes its tenant's service credentials, in the database. An `AFTER UPDATE` row trigger on the cells table fires when a cell's desired state becomes `deleted`, and an `AFTER DELETE` trigger fires when a row that is not yet deleted goes. Both set `revoked_at` to the database clock on the tenant's unrevoked service credentials and leave the revoking principal empty, because no operator revoked them. The recording function's trigger then ends each record. The database does this, not the web app's code, so the release that serves during a build, and an instant rollback to the release before this one, still end the credentials: no flow's SQL changes. A credential belongs to the tenant, so a live one would otherwise serve the tenant's next cell after re-admission, and its record would stay open and never be pruned. The trigger function runs with its caller's rights, not the schema owner's. Only the web app's role sets a cell's desired state, and it already holds update on the revocation column, so no grant changes. The gateway's role reads cells only, and the controller's role writes observed columns only, so neither fires it. The schema owner is the only role that can delete a cell row, so the delete trigger covers it. The trigger does not check for another live cell, because one index allows a single cell that is not deleted for each tenant. A second update, or a delete of a row that is already deleted, changes nothing. A `BEFORE INSERT` row trigger on the service credentials table closes the opposite order. Without it, a credential that commits just after the deletion's trigger ran would stay live and serve the tenant's next cell. The trigger reads the tenant's cell that is not deleted with `FOR SHARE`, and refuses the insert when none exists, with SQLSTATE `23503` and the constraint name `exomem_cloud_service_credentials_live_cell`. A deletion that starts after the insert waits for the inserting transaction to commit, and the deletion's own trigger then revokes the new credential. An insert that waits for a deletion finds the updated row, finds no live cell when the deletion commits, and is refused. The service credential request answers that refusal as `SERVICE_CREDENTIAL_TENANT_INELIGIBLE` (409), the answer for any tenant without a live cell. This trigger function also runs with its caller's rights. The web app's role is the only role that inserts credentials. It holds select on the cell and update on the columns that the share lock needs, so no grant changes. Both triggers take the cell's lock before the credential: the insert locks the cell's row before its own row exists, and the cell trigger writes the credentials after the cell row, as D5's order requires. Afterwards, a token family's record and a service credential's record last 90 days. The migration also revokes once, at its own time, every unrevoked service credential of a tenant that has no cell other than deleted ones, so the credentials of accounts that a release before this one deleted end too. No record stays open after that. An access token's record lasts until 90 days after its own expiry, which is an hour at most from its issue. A refresh token's record lasts until 90 days after its own expiry, which is the idle window at most from its issue: 30 days by default, at most 90. The longest window after deletion is therefore the refresh token's idle bound plus 90 days, which is 120 days by default and 180 at most. A download ticket's record lasts a day plus 90 days at most. The expiry is safe to key on. It is set at insert and is a fixed column afterwards. A credential cannot be used after its expiry, so no usable credential loses its record early. diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/proposal.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/proposal.md index 6c4d87c2..0623a9c6 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/proposal.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/proposal.md @@ -28,7 +28,7 @@ The account service stays the sign-in provider, so it can still issue a credenti ## Impact -- **Database:** two migrations. The first adds the schema release table and the guards, and pins the search path of the functions that run as the schema owner. The second adds the issuance log, the recording triggers, the download ticket table and a trigger on cells that revokes a deleted tenant's service credentials. It blocks writes to the cell, token and service credential tables while it records existing rows. Each sets a lock timeout. `scripts/exomem-cloud-grants.sql` gains the lock's rights, the trigger and execute revokes, and the audit role's rights. No new grants file. +- **Database:** two migrations. The first adds the schema release table and the guards, and pins the search path of the functions that run as the schema owner. The second adds the issuance log, the recording triggers, the download ticket table a trigger on cells that revokes a deleted tenant's service credentials, and a trigger on service credentials that refuses a new one for a tenant without a live cell. It blocks writes to the cell, token and service credential tables while it records existing rows. Each sets a lock timeout. `scripts/exomem-cloud-grants.sql` gains the lock's rights, the trigger and execute revokes, and the audit role's rights. No new grants file. - **Deployment:** a new workflow under `.github/workflows/`, `scripts/migrate.ts`, the `vercel-build` script and the script it calls. Each deploy waits for the migration job before it builds. - **Web app:** the download handler stores a ticket row, and the reconcile job prunes ticket rows and issuance records. The prune is a lane beside the job's other lanes, so another lane's failure does not stop it, and its own failure fails the job's response. No other flow changes its SQL. - **Gateway:** one release that requires the ticket row. It rolls at least one maximum ticket lifetime after the web release, and it rolls back before the web app does. diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-cloud-service-credentials/spec.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-cloud-service-credentials/spec.md index cfbe84cd..7ba256fe 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-cloud-service-credentials/spec.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-cloud-service-credentials/spec.md @@ -38,7 +38,7 @@ This requirement binds every role except the schema owner. The database SHALL re ### Requirement: Deleting a tenant's cell revokes its service credentials -A database trigger SHALL revoke every service credential of a tenant that is not yet revoked when the tenant's Cloud cell becomes deleted, or when a cell that is not yet deleted is deleted. The revocation time SHALL come from the database clock, and the revoking principal SHALL stay empty. The migration SHALL revoke the same credentials once for each tenant that has no cell other than deleted ones. No other tenant's credential SHALL change. The credential's issuance record SHALL then end. +A database trigger SHALL revoke every unrevoked service credential of a tenant when its cell becomes deleted or a cell not yet deleted is deleted, at the database clock's time with no revoking principal. The migration SHALL do the same for each tenant with only deleted cells. No other tenant's credential SHALL change. The credential's issuance record SHALL then end. A second trigger SHALL refuse a new credential for a tenant with no cell that is not deleted, and lock that cell's row. #### Scenario: An account's deletion finishes @@ -57,6 +57,23 @@ A database trigger SHALL revoke every service credential of a tenant that is not - **WHEN** the web app's role sets a cell that is already deleted to deleted again - **THEN** no revocation time changes +#### Scenario: A credential is inserted for a tenant whose only cell is deleted + +- **WHEN** a service credential is inserted for a tenant that has no cell other than deleted ones +- **THEN** the insert is refused and no credential row is stored +- **AND** the service credential request answers `SERVICE_CREDENTIAL_TENANT_INELIGIBLE` + +#### Scenario: A deletion starts while a credential insert is open + +- **WHEN** a transaction has inserted a service credential and another transaction sets the tenant's cell to deleted before the first commits +- **THEN** the deletion waits for the insert to commit +- **AND** the credential is then revoked with the database clock's time and its record has an end + +#### Scenario: A credential insert waits for a deletion + +- **WHEN** a service credential insert waits for a transaction that sets the tenant's cell to deleted, and that transaction commits +- **THEN** the insert is refused and no credential row is stored + #### Scenario: A tenant that an earlier release deleted - **WHEN** the migration runs and a tenant has no cell other than deleted ones diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md index 87058b6e..7c2b0697 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md @@ -136,6 +136,21 @@ names each decision as D1 to D12. tenant that has only deleted cells and keeps that of a tenant with a live cell. +- [x] 3.5 In the second migration, add a `BEFORE INSERT` row trigger on + `exomem_cloud_service_credentials`. Its function runs with its caller's + rights and pins its search path. It reads the tenant's cell that is not + deleted with `FOR SHARE`, and raises SQLSTATE `23503` with the constraint + name `exomem_cloud_service_credentials_live_cell` when there is none. Revoke + the function's execute right from `PUBLIC` in the migration and in the grants + script. In the service credential request, answer that refusal as + `SERVICE_CREDENTIAL_TENANT_INELIGIBLE`. Verify, in both states of group 5, + with a statement timeout on each connection: a credential for a tenant whose + only cell is deleted is refused. A deletion that starts while the insert is + open waits for the commit, and the credential then ends at the database + clock with its record. An insert that waits for an open deletion is refused + after the commit. The request's own test shows the 409 answer. Without + `FOR SHARE`, the two waiting tests fail. + ## 4. Download ticket rows (D8) - [x] 4.1 In the second migration, create `exomem_cloud_download_tickets` with diff --git a/scripts/exomem-cloud-grants.sql b/scripts/exomem-cloud-grants.sql index 41099db8..e44cd5e8 100644 --- a/scripts/exomem-cloud-grants.sql +++ b/scripts/exomem-cloud-grants.sql @@ -233,10 +233,10 @@ BEGIN END IF; -- PostgreSQL gives PUBLIC execute on every new function. The guard, the - -- recording function and the cell trigger's function need no grant: PostgreSQL checks the right when a - -- trigger is created, not when it fires, and only the schema owner creates - -- these triggers. Only the web app's role may call the prune function, and - -- the reconcile job does so. + -- recording function and the two cell-related trigger functions need no + -- grant: PostgreSQL checks the right when a trigger is created, not when it + -- fires, and only the schema owner creates these triggers. Only the web app's + -- role may call the prune function, and the reconcile job does so. IF to_regprocedure('exomem_refuse_unless_schema_owner()') IS NOT NULL THEN REVOKE ALL ON FUNCTION exomem_refuse_unless_schema_owner() FROM PUBLIC; END IF; @@ -246,6 +246,9 @@ BEGIN IF to_regprocedure('exomem_revoke_service_credentials_of_cell()') IS NOT NULL THEN REVOKE ALL ON FUNCTION exomem_revoke_service_credentials_of_cell() FROM PUBLIC; END IF; + IF to_regprocedure('exomem_require_live_cell_for_service_credential()') IS NOT NULL THEN + REVOKE ALL ON FUNCTION exomem_require_live_cell_for_service_credential() FROM PUBLIC; + END IF; IF to_regprocedure('exomem_prune_issuance_log()') IS NOT NULL THEN REVOKE ALL ON FUNCTION exomem_prune_issuance_log() FROM PUBLIC; IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'substrate_app') THEN @@ -263,6 +266,9 @@ BEGIN IF to_regprocedure('exomem_revoke_service_credentials_of_cell()') IS NOT NULL THEN EXECUTE format('REVOKE ALL ON FUNCTION exomem_revoke_service_credentials_of_cell() FROM %I', lock_role); END IF; + IF to_regprocedure('exomem_require_live_cell_for_service_credential()') IS NOT NULL THEN + EXECUTE format('REVOKE ALL ON FUNCTION exomem_require_live_cell_for_service_credential() FROM %I', lock_role); + END IF; IF lock_role <> 'substrate_app' AND to_regprocedure('exomem_prune_issuance_log()') IS NOT NULL THEN EXECUTE format('REVOKE ALL ON FUNCTION exomem_prune_issuance_log() FROM %I', lock_role); END IF; diff --git a/src/lib/exomem-hosted/__tests__/cloud-identity-lock-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-identity-lock-postgres.integration.test.ts index bc2e425e..bb77aa9d 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-identity-lock-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-identity-lock-postgres.integration.test.ts @@ -6,7 +6,6 @@ import { applyMigrations } from "../../../../scripts/migrate"; import { createLockFixture, randomCellId, - seedCell, seedClient, seedWorld, tableSnapshot, @@ -90,7 +89,7 @@ async function seedVictims(fx: LockFixture, world: World): Promise { VALUES ($1, $2, now() + interval '15 minutes') RETURNING id`, [world.familyId, "0".repeat(64)] ); - const cellId = await seedCell(fx.owner, world.tenantId); + const cellId = world.cellId; return { grantId, clientId, diff --git a/src/lib/exomem-hosted/__tests__/cloud-issuance-log-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-issuance-log-postgres.integration.test.ts index dd175669..94f49fd3 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-issuance-log-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-issuance-log-postgres.integration.test.ts @@ -11,9 +11,9 @@ import { pruneIssuanceState } from "../issuance-maintenance"; import { createLockFixture, randomCellId, - seedCell, seedWorld, tableSnapshot, + waitForWaiter, type LockFixture, type LockState, type World, @@ -375,8 +375,7 @@ for (const state of STATES) { it("revokes a tenant's live service credentials at the database clock, and ends their records, when the web app's role sets its cell to deleted", async () => { const gone = await seedWorld(fx.owner); const kept = await seedWorld(fx.owner); - const goneCell = await seedCell(fx.owner, gone.tenantId); - await seedCell(fx.owner, kept.tenantId); + const goneCell = gone.cellId; const spentBefore = await credentialState(gone.spent.serviceCredentialId); assert.deepEqual(await recordEnd(gone.serviceCredentialId), { open: true, at_now: false }); @@ -427,7 +426,7 @@ for (const state of STATES) { `INSERT INTO ${cells()} (cell_id, tenant_id, desired_state) VALUES ($1, $2, 'deleted')`, [oldCell, world.tenantId] ); - const liveCell = await seedCell(fx.owner, world.tenantId); + const liveCell = world.cellId; await fx.owner.query(`DELETE FROM ${cells()} WHERE cell_id = $1`, [oldCell]); assert.equal((await credentialState(world.serviceCredentialId)).revoked, false); await fx.owner.query(`DELETE FROM ${cells()} WHERE cell_id = $1`, [liveCell]); @@ -435,6 +434,105 @@ for (const state of STATES) { assert.deepEqual(await recordEnd(world.serviceCredentialId), { open: false, at_now: true }); }); + // A service credential is inserted only for a tenant with a live cell, and the insert locks + // that cell's row. These run as the web app's role, which mints credentials. Each connection + // has a statement timeout, so a lock that waits for the wrong thing fails the test. + const NO_LIVE_CELL = { + code: "23503", + constraint: "exomem_cloud_service_credentials_live_cell", + }; + const mintSql = () => `INSERT INTO ${serviceCredentials()} + (tenant_id, principal, secret_digest, created_by_principal_digest) + VALUES ($1, $2, $3, $4) RETURNING id`; + const mintValues = (tenantId: string) => [ + tenantId, + `service:t${randomBytes(6).toString("hex")}`, + randomBytes(32), + randomBytes(32), + ]; + const credentialCount = async (tenantId: string) => + ( + await fx.owner.query<{ count: number }>( + `SELECT count(*)::integer AS count FROM ${serviceCredentials()} WHERE tenant_id = $1`, + [tenantId] + ) + ).rows[0]!.count; + const sessions = async () => { + const [mint, deletion] = [await fx.app.connect(), await fx.app.connect()]; + for (const session of [mint, deletion]) + await session.query("SET statement_timeout = 10000"); + return { + mint, + deletion, + // The pool destroys a connection that carries a changed setting and maybe an open transaction. + close: () => { + mint.release(true); + deletion.release(true); + }, + }; + }; + // The caller keeps the promise to await it later, and a rejection that comes first is not "unhandled". + const pending = (promise: Promise): Promise => { + promise.catch(() => undefined); + return promise; + }; + + it("refuses a service credential for a tenant whose only cell is deleted", async () => { + const gone = await seedWorld(fx.owner); + await fx.app.query(`UPDATE ${cells()} SET desired_state = 'deleted' WHERE cell_id = $1`, [ + gone.cellId, + ]); + const before = await credentialCount(gone.tenantId); + await assert.rejects(fx.app.query(mintSql(), mintValues(gone.tenantId)), NO_LIVE_CELL); + assert.equal(await credentialCount(gone.tenantId), before); + }); + + it("revokes a credential that is inserted while a deletion of its tenant's cell waits for the insert", async () => { + const target = await seedWorld(fx.owner); + const { mint, deletion, close } = await sessions(); + try { + await mint.query("BEGIN"); + const minted = await mint.query<{ id: string }>(mintSql(), mintValues(target.tenantId)); + const deleting = pending( + deletion.query(`UPDATE ${cells()} SET desired_state = 'deleted' WHERE cell_id = $1`, [ + target.cellId, + ]) + ); + await waitForWaiter(fx.owner, mint); + await mint.query("COMMIT"); + await deleting; + const id = minted.rows[0]!.id; + const state = await credentialState(id); + assert.deepEqual( + { revoked: state.revoked, at_clock: state.at_clock, no_operator: state.no_operator }, + { revoked: true, at_clock: true, no_operator: true } + ); + assert.deepEqual(await recordEnd(id), { open: false, at_now: true }); + } finally { + close(); + } + }); + + it("refuses a credential that waits for a deletion of its tenant's cell, once the deletion commits", async () => { + const target = await seedWorld(fx.owner); + const { mint, deletion, close } = await sessions(); + try { + await deletion.query("BEGIN"); + await deletion.query( + `UPDATE ${cells()} SET desired_state = 'deleted' WHERE cell_id = $1`, + [target.cellId] + ); + const before = await credentialCount(target.tenantId); + const minting = pending(mint.query(mintSql(), mintValues(target.tenantId))); + await waitForWaiter(fx.owner, deletion); + await deletion.query("COMMIT"); + await assert.rejects(minting, NO_LIVE_CELL); + assert.equal(await credentialCount(target.tenantId), before); + } finally { + close(); + } + }); + // A token family's record holds the family's expiry. A revocation or a delete before then // moves it to the database clock's time, so the prune keeps it 90 days from the end. const families = () => fx.q("exomem_oauth_token_families"); @@ -628,12 +726,11 @@ describe("The migration that adds the log", { skip: !databaseUrl }, () => { "INSERT INTO exomem_cloud_cells (cell_id, tenant_id, desired_state) VALUES ($1, $2, 'deleted')", [randomCellId(), live.tenantId] ); - await seedCell(fx.owner, live.tenantId); // A tenant that a release before this one deleted: only a deleted cell, and a credential left live. const deleted = await seedWorld(fx.owner); await fx.owner.query( - "INSERT INTO exomem_cloud_cells (cell_id, tenant_id, desired_state) VALUES ($1, $2, 'deleted')", - [randomCellId(), deleted.tenantId] + "UPDATE exomem_cloud_cells SET desired_state = 'deleted' WHERE cell_id = $1", + [deleted.cellId] ); const deletedSpentRevokedAt = ( await fx.owner.query<{ at: string }>( @@ -644,7 +741,6 @@ describe("The migration that adds the log", { skip: !databaseUrl }, () => { // A tenant with credentials that expired 100 days ago, which the prune would delete at once, and // credentials that expired 10 days ago, which it keeps. const stale = await seedWorld(fx.owner); - await seedCell(fx.owner, stale.tenantId); const staleOld = await seedExpiredChain(stale, 100); const staleRecent = await seedExpiredChain(stale, 10); seeded = { live, deleted, deletedSpentRevokedAt, stale, staleOld, staleRecent }; diff --git a/src/lib/exomem-hosted/__tests__/cloud-service-credentials-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-service-credentials-postgres.integration.test.ts index c79ff692..a5d5d361 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-service-credentials-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-service-credentials-postgres.integration.test.ts @@ -20,6 +20,7 @@ import { import { digestSecret } from "../security"; import { SERVICE_CREDENTIAL_PREFIX } from "../service-credential-format"; import { productionPool } from "./flow-pool"; +import { waitForWaiter } from "./identity-lock-fixture"; import { ensureExomemPostgresTestExtensions } from "./postgres-test-extensions"; // add-cloud-service-credentials (D1-D5): the service credential store and the @@ -346,6 +347,31 @@ describe("Exomem Cloud service credentials PostgreSQL integration", { skip: !dat }); }); + it("answers a request whose tenant's cell is deleted while it waits as ineligible, and stores nothing", async () => { + const target = await newTenantWithCell(); + const deletion = await pool!.connect(); + try { + await deletion.query("BEGIN"); + await deletion.query( + "UPDATE exomem_cloud_cells SET desired_state = 'deleted' WHERE cell_id = $1", + [target.cellId] + ); + // The lookup still reads the cell as live, so the insert's lock on that cell is what waits. + const issuing = issue(target.tenantId); + issuing.catch(() => undefined); + await waitForWaiter(pool!, deletion); + await deletion.query("COMMIT"); + await assert.rejects(issuing, { code: "SERVICE_CREDENTIAL_TENANT_INELIGIBLE" }); + const { rows } = await pool!.query( + "SELECT count(*)::integer AS count FROM exomem_cloud_service_credentials WHERE tenant_id = $1", + [target.tenantId] + ); + assert.equal(rows[0]!.count, 0); + } finally { + deletion.release(true); + } + }); + it("refuses issuance for a marketplace-reviewer tenant (review R2)", async () => { // Reviewer credentials carry their own expiry contract; a long-lived // service credential would sidestep it, so issuance is refused outright. diff --git a/src/lib/exomem-hosted/__tests__/identity-lock-fixture.ts b/src/lib/exomem-hosted/__tests__/identity-lock-fixture.ts index 100b8c26..b00c7fdb 100644 --- a/src/lib/exomem-hosted/__tests__/identity-lock-fixture.ts +++ b/src/lib/exomem-hosted/__tests__/identity-lock-fixture.ts @@ -1,5 +1,5 @@ import { randomBytes, randomUUID } from "node:crypto"; -import { Pool } from "pg"; +import { Pool, type PoolClient } from "pg"; import { applyMigrations } from "../../../../scripts/migrate"; import { ensureExomemPostgresTestExtensions } from "./postgres-test-extensions"; import { TEST_ROLE_PASSWORD } from "./test-role-password"; @@ -108,6 +108,8 @@ export async function createLockFixture( export type World = { userId: string; tenantId: string; + /** The tenant's one live cell. A service credential can be inserted only for a tenant that has one. */ + cellId: string; clientId: string; grantId: string; familyId: string; @@ -152,6 +154,7 @@ export async function seedWorld(owner: Pool): Promise { const tenantId = await id("INSERT INTO exomem_tenants (owner_user_id) VALUES ($1) RETURNING id", [ userId, ]); + const cellId = await seedCell(owner, tenantId); const clientId = await seedClient(owner); const chain = async (spent: boolean) => { const revokedAt = spent ? "now()" : "NULL"; @@ -192,6 +195,7 @@ export async function seedWorld(owner: Pool): Promise { return { userId, tenantId, + cellId, clientId, grantId: live.grant, familyId: live.family, @@ -227,6 +231,27 @@ export async function seedCell(owner: Pool, tenantId: string): Promise { return cellId; } +/** + * Waits until another session waits for the open transaction on `holder`. The wait is the proof + * that a lock is held: a statement that never waits fails here, and a statement that is stuck + * fails on the caller's statement timeout, so a wrong lock never shows as a pass or a hang. + */ +export async function waitForWaiter(observer: Pool, holder: PoolClient): Promise { + const { rows } = await holder.query<{ xid: string }>( + "SELECT pg_current_xact_id()::xid::text AS xid" + ); + for (let attempt = 0; attempt < 100; attempt += 1) { + const waiting = await observer.query( + `SELECT 1 FROM pg_locks + WHERE locktype = 'transactionid' AND NOT granted AND transactionid = $1::xid`, + [rows[0]!.xid] + ); + if (waiting.rows.length > 0) return; + await new Promise((resolve) => setTimeout(resolve, 50)); + } + throw new Error("no statement waited for the open transaction"); +} + /** Every row of a table as JSON, to compare before and after a refused statement. */ export async function tableSnapshot(owner: Pool, table: string): Promise { const { rows } = await owner.query<{ snapshot: string }>( diff --git a/src/lib/exomem-hosted/cloud-service-credentials.ts b/src/lib/exomem-hosted/cloud-service-credentials.ts index 8ce0cfed..29e184ef 100644 --- a/src/lib/exomem-hosted/cloud-service-credentials.ts +++ b/src/lib/exomem-hosted/cloud-service-credentials.ts @@ -24,6 +24,12 @@ import { SERVICE_CREDENTIAL_PRINCIPAL_FORMAT, } from "./service-credential-format"; +/** + * The name that migration 0102's insert trigger gives its refusal: the tenant's + * cell was deleted between this request's lookup and its insert (design D6). + */ +const NO_LIVE_CELL_CONSTRAINT = "exomem_cloud_service_credentials_live_cell"; + /** Design D5: rotation without downtime is exactly two live credentials. */ const MAX_LIVE_CREDENTIALS_PER_PRINCIPAL = 2; @@ -134,6 +140,9 @@ export async function issueCloudServiceCredentialAtomic( if (Number(live.rows[0]?.count ?? 0) >= MAX_LIVE_CREDENTIALS_PER_PRINCIPAL) { throw exomemErrors.serviceCredentialLimit(); } + // The insert locks the cell's row, so a deletion that began after the lookup waits for + // this transaction; one that already ran makes the insert fail, and that failure + // gets the answer of a tenant with no live cell (design D6). const inserted = await tx` /* exomem-cloud:issue-service-credential */ INSERT INTO exomem_cloud_service_credentials ( @@ -142,7 +151,12 @@ export async function issueCloudServiceCredentialAtomic( ${row.id}::uuid, ${input.principal}, ${digestSecret(secret)}, ${input.operatorPrincipalDigest} ) RETURNING id - `; + `.catch((error: unknown) => { + if ((error as { constraint?: unknown } | null)?.constraint === NO_LIVE_CELL_CONSTRAINT) { + throw exomemErrors.serviceCredentialTenantIneligible(); + } + throw error; + }); return { credentialId: String(inserted.rows[0]!.id), tenantId: row.id, From 49b416ffb796a86982fbbcc63e3713180fbb486f Mon Sep 17 00:00:00 2001 From: Artexis10 Date: Wed, 2 Dec 2026 13:33:35 +0000 Subject: [PATCH 17/29] Answer a deadlock on a service credential request as a retryable 503 The lifecycle sweep locks a cell before its tenant, and a service credential request locks the tenant first, so the two can deadlock and PostgreSQL then fails one of them. The request now maps SQLSTATE 40P01 to 503 SERVICE_CREDENTIAL_RETRY, retryable, with a Retry-After of 3 seconds, instead of a bare 500. The transaction rolled back whole, so the operator sends the request again. The route does not retry. The operator error response now sends Retry-After whenever an error names a delay. A serialization failure (40001) cannot reach the request: its transactions run at READ COMMITTED. --- .../exomem-cloud-service-credentials.md | 5 ++- .../design.md | 2 +- .../tasks.md | 7 +++-- .../__tests__/route.test.ts | 20 ++++++++++++ .../cloud-service-credentials.test.ts | 31 +++++++++++++++++++ .../cloud-service-credentials.ts | 14 +++++++++ src/lib/exomem-hosted/errors.ts | 11 +++++++ .../exomem-hosted/operator-observability.ts | 7 ++++- 8 files changed, 92 insertions(+), 5 deletions(-) create mode 100644 src/lib/exomem-hosted/__tests__/cloud-service-credentials.test.ts diff --git a/docs/runbooks/exomem-cloud-service-credentials.md b/docs/runbooks/exomem-cloud-service-credentials.md index ea088dc8..fe7870de 100644 --- a/docs/runbooks/exomem-cloud-service-credentials.md +++ b/docs/runbooks/exomem-cloud-service-credentials.md @@ -44,7 +44,10 @@ tenant is `deletion_pending` or `deleted`, its owner has an account block, it has no non-deleted cell, or it is a marketplace-reviewer tenant — reviewer credentials carry their own expiry contract a long-lived secret would sidestep. A 409 `SERVICE_CREDENTIAL_LIMIT` means the tenant and principal -already hold two live credentials; revoke one before issuing another. +already hold two live credentials; revoke one before issuing another. A 503 +`SERVICE_CREDENTIAL_RETRY` with a `Retry-After` header means the database failed +the request to break a lock cycle with a lifecycle sweep of the same tenant. +Nothing was stored, so send the request again after the header's seconds. The 201 response is the only place the secret ever appears: `secret`, `credentialId`, `tenantId`, `principal`, `cellId`, `cloudMcpUrl`. It is sent diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md index 502223be..e6415617 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md @@ -199,7 +199,7 @@ Other points: - The first adds `schema_releases` and the guards, and pins the functions' paths. It locks users, tenants, cells, reviewer credentials, clients, grants, token families, refresh tokens, access tokens and service credentials. It changes only the catalog, so it commits soon after it holds the last lock. - The second adds the log, the ticket table, the recording triggers, the cell trigger of D6 and the records for existing rows. It locks cells, token families, refresh tokens, access tokens and service credentials until it has written those records. Code exchange, refresh, the Home mint, token revocation, service credential requests, cell changes and the maintenance wait for it. Its length grows with the rows that the backfill writes, not with the size of the tables: a row whose record the prune would delete is skipped. Task 7.4 gives the query that counts those rows, with the backfill's own predicate. -- Each migration takes all its locks first, with one `LOCK TABLE` statement in the mode that creating a trigger takes. PostgreSQL takes them one at a time, in the order listed above, and the second migration takes cells first: a cell's change writes the service credentials after it, through the trigger of D6. Admission writes users before tenants, and every revocation and issuance writes grants, then token families, then tokens, in that order. Three flows write in another order: cell deletion writes the OAuth tables, then tenants, then users, deletion finish writes tenants before users, and the lifecycle sweep writes a cell before its tenant. Any of them can deadlock with the first migration, and PostgreSQL then fails one of the two transactions. A service credential request locks the tenant, then the cell through D6's trigger. That is the order of deletion finish, which waits for the request on the tenant, and the reverse of the lifecycle sweep. If the sweep and a request for the same tenant overlap, they can deadlock, and PostgreSQL fails one of them. The sweep runs again a minute later, and the operator sends a failed request again. The reconcile job runs both flows every minute (`ops/exomem-hosted-schedules.json`), so a failed deletion step runs again a minute later. A deadlock fails the migration's job like a lock timeout does, and the operator starts the job again. +- Each migration takes all its locks first, with one `LOCK TABLE` statement in the mode that creating a trigger takes. PostgreSQL takes them one at a time, in the order listed above, and the second migration takes cells first: a cell's change writes the service credentials after it, through the trigger of D6. Admission writes users before tenants, and every revocation and issuance writes grants, then token families, then tokens, in that order. Three flows write in another order: cell deletion writes the OAuth tables, then tenants, then users, deletion finish writes tenants before users, and the lifecycle sweep writes a cell before its tenant. Any of them can deadlock with the first migration, and PostgreSQL then fails one of the two transactions. The reconcile job runs both flows every minute (`ops/exomem-hosted-schedules.json`), so a failed deletion step runs again a minute later. A deadlock fails the migration's job like a lock timeout does, and the operator starts the job again. A service credential request locks the tenant, then the cell through D6's trigger. That is the order of deletion finish, which waits for the request on the tenant, and the reverse of the lifecycle sweep. If the sweep and a request for the same tenant overlap, they can deadlock, and PostgreSQL fails one of them. The sweep runs again a minute later. A request that PostgreSQL fails answers 503 `SERVICE_CREDENTIAL_RETRY` with `Retry-After: 3`, and the operator sends it again. - Each migration sets a lock timeout of five seconds. Without one, its lock request would wait behind any long transaction, and every later write would wait behind the request. The timeout bounds each wait, not the migration. While the migration waits for one lock, it holds every lock that it took before, and new writes to the table it waits for queue behind its request. In the worst case, a write to users waits through all nine waits of the first migration, about 45 seconds, before that migration commits or fails. When a wait times out, the migration fails, the job fails, and a later run tries again. - If the second migration fails, the guards are in force without the log. No flow depends on the log, and a later run adds it. diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md index 7c2b0697..b8bebea2 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md @@ -143,12 +143,15 @@ names each decision as D1 to D12. name `exomem_cloud_service_credentials_live_cell` when there is none. Revoke the function's execute right from `PUBLIC` in the migration and in the grants script. In the service credential request, answer that refusal as - `SERVICE_CREDENTIAL_TENANT_INELIGIBLE`. Verify, in both states of group 5, + `SERVICE_CREDENTIAL_TENANT_INELIGIBLE`. Answer a deadlock (SQLSTATE 40P01) + that the sweep's lock order can cause as 503 `SERVICE_CREDENTIAL_RETRY` with + `Retry-After: 3`, and not as a bare 500. Verify, in both states of group 5, with a statement timeout on each connection: a credential for a tenant whose only cell is deleted is refused. A deletion that starts while the insert is open waits for the commit, and the credential then ends at the database clock with its record. An insert that waits for an open deletion is refused - after the commit. The request's own test shows the 409 answer. Without + after the commit. The request's own test shows the 409 answer, and a unit + test shows the 503 answer for a thrown 40P01. Without `FOR SHARE`, the two waiting tests fail. ## 4. Download ticket rows (D8) diff --git a/src/app/api/exomem/admin/service-credentials/__tests__/route.test.ts b/src/app/api/exomem/admin/service-credentials/__tests__/route.test.ts index 8b9274b9..5b88eaae 100644 --- a/src/app/api/exomem/admin/service-credentials/__tests__/route.test.ts +++ b/src/app/api/exomem/admin/service-credentials/__tests__/route.test.ts @@ -10,6 +10,7 @@ let issued: Record | null = null; let revokeCalls = 0; let nextRevokeResult = true; let nextList: unknown[] | null = []; +let nextIssueError: Error | null = null; before(() => { process.env.EXOMEM_ADMIN_TOKEN = ADMIN_TOKEN; @@ -17,6 +18,7 @@ before(() => { namedExports: { issueCloudServiceCredentialAtomic: async (input: Record) => { issued = input; + if (nextIssueError) throw nextIssueError; return { credentialId: CREDENTIAL_ID, tenantId: TENANT_ID, @@ -58,6 +60,7 @@ beforeEach(() => { revokeCalls = 0; nextRevokeResult = true; nextList = []; + nextIssueError = null; }); function request( @@ -110,6 +113,23 @@ describe("Exomem operator service credentials", () => { assert.equal(issued?.principal, "service:creator-platform"); }); + it("answers a retryable error with 503 and a Retry-After header, never a bare 500", async () => { + const { exomemErrors } = await import("@/lib/exomem-hosted/errors"); + nextIssueError = exomemErrors.serviceCredentialRetry(); + const { POST } = await import("../route"); + const response = await POST( + request("POST", { + authorization: `Bearer ${ADMIN_TOKEN}`, + body: { tenantId: TENANT_ID, principal: "service:creator-platform" }, + }) + ); + assert.equal(response.status, 503); + assert.equal(response.headers.get("retry-after"), "3"); + const body = (await response.json()) as { error: { code: string; retryable: boolean } }; + assert.equal(body.error.code, "SERVICE_CREDENTIAL_RETRY"); + assert.equal(body.error.retryable, true); + }); + it("enforces the service: principal format", async () => { const { POST } = await import("../route"); for (const principal of [ diff --git a/src/lib/exomem-hosted/__tests__/cloud-service-credentials.test.ts b/src/lib/exomem-hosted/__tests__/cloud-service-credentials.test.ts new file mode 100644 index 00000000..1eff50e6 --- /dev/null +++ b/src/lib/exomem-hosted/__tests__/cloud-service-credentials.test.ts @@ -0,0 +1,31 @@ +import assert from "node:assert/strict"; +import { after, before, describe, it } from "node:test"; +import { issueCloudServiceCredentialAtomic } from "../cloud-service-credentials"; +import { __setExomemTransactionForTests } from "../db"; +import { digestSecret } from "../security"; + +// A request whose transaction PostgreSQL fails to break a lock cycle gets a retryable answer, +// not an unnamed 500 (design D5). The cycle itself needs two transactions and is not reproduced. + +describe("Exomem Cloud service credential issuance, lock cycle", () => { + before(() => { + __setExomemTransactionForTests(async () => { + throw Object.assign(new Error("deadlock detected"), { code: "40P01" }); + }); + }); + + after(() => { + __setExomemTransactionForTests(null); + }); + + it("answers a deadlock that PostgreSQL detects as a retryable 503", async () => { + await assert.rejects( + issueCloudServiceCredentialAtomic({ + tenantId: "018f2d91-7c42-7000-8000-000000000012", + principal: "service:creator-platform", + operatorPrincipalDigest: digestSecret("operator-test-principal"), + }), + { code: "SERVICE_CREDENTIAL_RETRY", status: 503, retryable: true, retryAfterMs: 3000 } + ); + }); +}); diff --git a/src/lib/exomem-hosted/cloud-service-credentials.ts b/src/lib/exomem-hosted/cloud-service-credentials.ts index 29e184ef..f35c019a 100644 --- a/src/lib/exomem-hosted/cloud-service-credentials.ts +++ b/src/lib/exomem-hosted/cloud-service-credentials.ts @@ -30,6 +30,12 @@ import { */ const NO_LIVE_CELL_CONSTRAINT = "exomem_cloud_service_credentials_live_cell"; +/** + * PostgreSQL's code for a transaction that it failed to break a lock cycle (design D5). A + * serialization failure (40001) cannot reach this request: its transactions run at READ COMMITTED. + */ +const DEADLOCK_DETECTED = "40P01"; + /** Design D5: rotation without downtime is exactly two live credentials. */ const MAX_LIVE_CREDENTIALS_PER_PRINCIPAL = 2; @@ -164,6 +170,14 @@ export async function issueCloudServiceCredentialAtomic( cellId: row.cell_id, secret, }; + }).catch((error: unknown) => { + // The sweep locks a cell before its tenant and this request locks the tenant first (design D5). + // The transaction rolled back whole and the secret was never stored, so the operator can + // send the request again, and the answer says so. + if ((error as { code?: unknown } | null)?.code === DEADLOCK_DETECTED) { + throw exomemErrors.serviceCredentialRetry(); + } + throw error; }); } diff --git a/src/lib/exomem-hosted/errors.ts b/src/lib/exomem-hosted/errors.ts index 88e5f2bd..836aed10 100644 --- a/src/lib/exomem-hosted/errors.ts +++ b/src/lib/exomem-hosted/errors.ts @@ -178,6 +178,17 @@ export const exomemErrors = { status: 409, message: "no eligible tenant matches this selector", }), + // The database failed this request's transaction to break a lock cycle (design D5). The + // transaction rolled back whole, so sending the request again is safe. + serviceCredentialRetry: () => + new ExomemHostedError({ + code: "SERVICE_CREDENTIAL_RETRY", + status: 503, + message: "the request met a concurrent change; send it again", + retryable: true, + retryAfterMs: 3000, + remediation: "retry_later", + }), } as const; export function safeErrorEnvelope(error: unknown, requestId?: string): ExomemHostedErrorEnvelope { diff --git a/src/lib/exomem-hosted/operator-observability.ts b/src/lib/exomem-hosted/operator-observability.ts index 5fdc3a68..18b98960 100644 --- a/src/lib/exomem-hosted/operator-observability.ts +++ b/src/lib/exomem-hosted/operator-observability.ts @@ -35,5 +35,10 @@ export function operatorControlErrorResponse(error: unknown, requestId: string) errorCode: reported instanceof ExomemHostedError ? reported.code : "INTERNAL_ERROR", variables, }); - return safeErrorResponse(reported, requestId); + const response = safeErrorResponse(reported, requestId); + // The header counts whole seconds. An error that names a delay sends it as the header too. + if (reported instanceof ExomemHostedError && reported.retryAfterMs) { + response.headers.set("retry-after", String(Math.ceil(reported.retryAfterMs / 1000))); + } + return response; } From 9d249a4b58e19692f5d0d190ce22d21cd4fec6d6 Mon Sep 17 00:00:00 2001 From: Artexis10 Date: Wed, 2 Dec 2026 14:11:16 +0000 Subject: [PATCH 18/29] Anchor the audit read on a surviving record, and reopen the cost proof The runbook's range query named the record that the previous run stopped at. The prune can delete that record, and the read then started at the beginning of the log. It now anchors on the nearest record at or below that point, and starts at the oldest record when none survives, which is the unread range. An empty log gives an empty range. Check 3 now says what a hit means: the web app's role inserted a grant for someone other than the tenant's owner. Task 5.8 now names the commit that its run measured and stays open. The triggers that end token family records, the cell deletion triggers and the service credential insert trigger came after that run, so a rerun is owed. D7 no longer says that the run's script and generator are kept. --- docs/runbooks/exomem-cloud-operations.md | 16 ++++++++++++---- .../design.md | 6 +++--- .../tasks.md | 14 +++++++++----- 3 files changed, 24 insertions(+), 12 deletions(-) diff --git a/docs/runbooks/exomem-cloud-operations.md b/docs/runbooks/exomem-cloud-operations.md index 5f7c9607..e9db701a 100644 --- a/docs/runbooks/exomem-cloud-operations.md +++ b/docs/runbooks/exomem-cloud-operations.md @@ -900,11 +900,12 @@ open for longer than that hour is missed by the range checks. The read of one te 3. Find the range of this run: ```sql - SELECT max(id) AS hi FROM exomem_cloud_issuance_log \gset + SELECT coalesce(max(id), 0) AS hi FROM exomem_cloud_issuance_log \gset SELECT coalesce( (SELECT id FROM exomem_cloud_issuance_log WHERE id <= :prev - AND recorded_at < (SELECT recorded_at FROM exomem_cloud_issuance_log WHERE id = :prev) - interval '1 hour' + AND recorded_at < (SELECT recorded_at FROM exomem_cloud_issuance_log + WHERE id <= :prev ORDER BY id DESC LIMIT 1) - interval '1 hour' ORDER BY id DESC LIMIT 1), 0) AS lo \gset SELECT greatest( coalesce((SELECT recorded_at FROM exomem_cloud_issuance_log WHERE id = :lo), '-infinity'), @@ -912,6 +913,11 @@ open for longer than that hour is missed by the range checks. The read of one te \echo hi=:hi lo=:lo ``` + The prune can delete the record that `prev` names, so `lo` anchors on the nearest record at or below `prev` that still + exists, and walks back from there through the primary key for one hour of records. If no record at or below `prev` + exists, every record in the log is newer than `prev`, and `lo` is `0`: the range then holds exactly the records + that this run has not read. An empty log gives `hi=0`, and the checks that use the range return no row. + `lo_time` is never earlier than the log's first record. That record carries the migration's time when the backfill wrote any record. The migration wrote no record for a row whose end was more than 90 days old, and the first run must not list those rows. If the log is empty, `lo_time` is `-infinity`, and the first check lists every credential row that the @@ -951,8 +957,10 @@ open for longer than that hour is missed by the range checks. The read of one te WHERE id BETWEEN :lo AND :hi AND NOT backfilled AND database_role <> 'substrate_app'; ``` - Records whose user is not the tenant's owner. The recording function copies both values from the grant. A mismatch - means that someone changed an owner after the record, or that the record is false. + Records whose user is not the tenant's owner. The recording function copies both values from the grant, a guard + refuses a change to a tenant's owner, and only the database writes records. A row here means that the web app's + role inserted a grant for a user other than the tenant's owner, and the gateway admits that grant. Find the grant + by the record's `grant_id` and revoke it. ```sql SELECT record.id, record.credential_kind, record.tenant_id, record.user_id diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md index e6415617..b221239f 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md @@ -253,9 +253,9 @@ The log also costs outside the request: Proof, on a disposable PostgreSQL: -- **Instrument.** `pgbench` runs the Home mint transaction's statements as a custom script, over generated data for 10,000 tenants. The same script runs with and without this change's triggers, five runs each, on the same machine and data. The script and the generator are not in this repository. They are kept with the private record of the run, so a later change to the triggers or the guards needs that record's instrument to rerun the proof. +- **Instrument.** `pgbench` runs the Home mint transaction's statements as a custom script, over generated data for 10,000 tenants. The same script runs with and without this change's triggers, five runs each, on the same machine and data. The script and the generator are not in this repository, and the first run's copies were not kept. A rerun builds them again from this description. - **Size.** The log holds 10 million generated records. That is enough, because every insert lands at the right edge of an index, or at the right edge of one tenant's range. The pages that an insert touches stay in memory at any log size. -- **Result.** The run's outputs are kept as a private record outside this repository, and task 5.8 states the outcome. The median must rise by less than one millisecond. +- **Result.** The run's outputs are kept as a private record outside this repository, and task 5.8 states the outcome and the commit that the run measured. The median must rise by less than one millisecond. - **Plans.** `EXPLAIN (ANALYZE, BUFFERS)` of one prune call shows that it reads only the records it deletes. The same output for each read of the log in D12 shows an index range and no full scan. D12's first check also reads the credential tables in full, so its plan is reported and no bound is set on it. ### D8. A download ticket gets a stored row @@ -368,7 +368,7 @@ A log that nobody can read cheaply proves nothing. Two readers exist, and each o The first check also reads the credential tables in full. It filters their rows by `created_at`, and none of the five tables has an index on that column. A consumed refresh token of an unexpired family stays in its table, so the tables hold more than the live credentials. The read grows with those tables, not with the range of the log. The operator runs it on demand (limit 13), not on a schedule. A scheduled version needs an index on `created_at` or a different query, which is a later step. The migration writes no record for a row whose record the prune would delete (D5), so the check ignores rows from before the release. The first run starts at the release time, which is the `recorded_at` of the log's first record, and not at the start of time. That time is the migration's time when the backfill wrote any record. The check then flags no skipped row. The last four read the catalog. -**Late commits.** PostgreSQL assigns a record's identifier at insert, not at commit. A record can therefore commit after a check has read past its identifier. Each run starts one hour of records before the point where the previous run stopped, so the next run reads such a record. It finds that start by walking back through the primary key, so the read stays bounded. A record whose transaction stayed open for longer than that hour is missed by the range checks. The read of one tenant's records still returns it. +**Late commits.** PostgreSQL assigns a record's identifier at insert, not at commit. A record can therefore commit after a check has read past its identifier. Each run starts one hour of records before the point where the previous run stopped, so the next run reads such a record. It finds that start by walking back through the primary key from the nearest record at or below the previous stop that still exists, because the prune can delete the record that the stop names. If none exists, every record is newer than the previous stop, and the run starts at the oldest record. The read stays bounded. A record whose transaction stayed open for longer than that hour is missed by the range checks. The read of one tenant's records still returns it. **One tenant's records.** An index on `tenant_id` with `id` lists one tenant's issuances, newest first, a page at a time. That is the read for an incident and for an owner who asks who held access. Without the index, it would scan the whole log. diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md index b8bebea2..d45a2ba0 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md @@ -253,7 +253,7 @@ without truncate. Neither state holds the trigger right. serves one that has its row. It refuses one whose path, token family or expiry differs from the stored row. A download request runs as many database statements as it did before this change. -- [x] 5.8 Cost at the load target (D7). Generate data for 10,000 tenants and a +- [ ] 5.8 Cost at the load target (D7). Generate data for 10,000 tenants and a log of 10 million records. With `pgbench`, run the Home mint transaction's statements with and without this change's triggers: five runs each, same machine, same data. Report the median and the 95th percentile of both arms, @@ -266,10 +266,14 @@ without truncate. Neither state holds the trigger right. outputs are kept as a private record outside this public repository. They are the median and the 95th percentile of the mint latency with and without the triggers, the write-ahead-log bytes for each mint, the size of a record, - and the `EXPLAIN` plans. The run met each part of the pass condition. The - `pgbench` script and the 10,000-tenant generator are not in this repository. - They are kept with that private record, so a later change to the triggers or - the guards needs that record's instrument to rerun the proof. + and the `EXPLAIN` plans. One run measured commit `e21b73b1`, and it met each + part of the pass condition. That commit predates the triggers that end token + family records, the triggers on a cell's deletion and the trigger that + refuses a service credential for a tenant with no live cell. A rerun on the + final migration is owed, and this task stays open until it runs. The + `pgbench` script and the 10,000-tenant generator are not in this repository, + and the first run's copies were not kept. The rerun builds them again from + this description. - [ ] 5.9 Add the new suites to the PostgreSQL integration list in `.github/workflows/test.yml`. Verify: CI runs them. From e8a7c3db853a61b1ebe2b06831447e076ca445b5 Mon Sep 17 00:00:00 2001 From: Artexis10 Date: Wed, 2 Dec 2026 14:11:17 +0000 Subject: [PATCH 19/29] Run the download suite as the web app's role and the gateway's role The suite stored each ticket row and ran the gateway's lookup as a superuser, which holds every right. The link handler now runs as the web app's role and the gateway's lookup as its own narrower role, on the rights of the grants script. The superuser pool only seeds and asserts. A removed column right on the gateway or a removed insert right on the web app now fails the suite. --- ...edia-download-postgres.integration.test.ts | 48 +++++++++++++------ src/lib/exomem-hosted/__tests__/flow-pool.ts | 25 +++++++--- 2 files changed, 52 insertions(+), 21 deletions(-) diff --git a/src/lib/exomem-hosted/__tests__/cloud-media-download-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-media-download-postgres.integration.test.ts index 7b6aa230..063b90f0 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-media-download-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-media-download-postgres.integration.test.ts @@ -11,11 +11,14 @@ import type { ExomemCloudConfig } from "../cloud-config"; import { handleCloudMediaDownloadRequest } from "../cloud-media-download"; import { __setExomemSqlForTests, __setExomemTransactionForTests, type ExomemSql } from "../db"; import { digestSecret, generateExternalToken } from "../security"; +import { gatewayPool, productionPool } from "./flow-pool"; import { ensureExomemPostgresTestExtensions } from "./postgres-test-extensions"; // add-cloud-media-access: the signed-in download link against real PostgreSQL. The browser // session, the ticket and the gateway's login lookup all run for real; only the cell's -// bytes are substituted, at the gateway's `fetchCell` boundary. +// bytes are substituted, at the gateway's `fetchCell` boundary. Production runs the link as the +// web app's role and the gateway as its own narrower role, on the rights of the grants script, so +// each runs as that role here. The suite's own pool is a superuser that only seeds and asserts. process.env.EXOMEM_CONTROL_PLANE_KEY ??= randomBytes(32).toString("base64url"); @@ -27,6 +30,12 @@ const { privateKey } = generateKeyPairSync("ed25519"); const PATH = "Recordings/standup.mp4"; const BYTES = Buffer.from("0123456789"); let pool: Pool; +/** The web app's role: the link handler stores each ticket's row as this role. */ +let appPool: Pool; +/** The gateway's role: the login lookup that requires the row runs as this role. */ +let gatewayRolePool: Pool; +/** The statement handle that the gateway's lookup uses; a case swaps in a counting wrapper. */ +let gatewaySql: ExomemSql; let schema: string; type Owner = { userId: string; tenantId: string; cellId: string; cookie: string }; @@ -123,13 +132,19 @@ function gateway(cells: Owner[]) { }, }); }) as unknown as typeof fetch; - const follow = (location: string, headers: Record = {}) => - handleCloudDownloadRequest(new Request(location, { headers }), { - config, - fetchCell, - upstream: testUpstream(), - takeRateLimit: async () => true, - }); + const follow = async (location: string, headers: Record = {}) => { + __setExomemSqlForTests(gatewaySql); + try { + return await handleCloudDownloadRequest(new Request(location, { headers }), { + config, + fetchCell, + upstream: testUpstream(), + takeRateLimit: async () => true, + }); + } finally { + __setExomemSqlForTests(taggedSql(appPool)); + } + }; return { reached, follow }; } @@ -144,9 +159,12 @@ describe("Signed-in media download PostgreSQL boundary", { skip: !databaseUrl }, scoped.searchParams.set("options", `-c search_path=${schema},public`); await applyMigrations({ databaseUrl: scoped.toString() }); pool = new Pool({ connectionString: scoped.toString() }); - __setExomemSqlForTests(taggedSql(pool)); + appPool = await productionPool(scoped.toString(), schema); + gatewayRolePool = await gatewayPool(scoped.toString(), schema); + gatewaySql = taggedSql(gatewayRolePool); + __setExomemSqlForTests(taggedSql(appPool)); __setExomemTransactionForTests(async (work) => { - const client = await pool.connect(); + const client = await appPool.connect(); try { await client.query("BEGIN"); const result = await work(taggedSql(client)); @@ -165,6 +183,8 @@ describe("Signed-in media download PostgreSQL boundary", { skip: !databaseUrl }, __setExomemSqlForTests(null); __setExomemTransactionForTests(null); await pool?.end(); + await appPool?.end(); + await gatewayRolePool?.end(); if (schema) { const admin = new Pool({ connectionString: databaseUrl }); await admin.query(`DROP SCHEMA "${schema}" CASCADE`); @@ -357,15 +377,15 @@ describe("Signed-in media download PostgreSQL boundary", { skip: !databaseUrl }, // Count the statements that the gateway runs for one download. const statements: string[] = []; - const counted: ExomemSql = async (strings, ...values) => { + const asGateway = gatewaySql; + gatewaySql = async (strings, ...values) => { statements.push(strings.join("?")); - return taggedSql(pool)(strings, ...values); + return asGateway(strings, ...values); }; - __setExomemSqlForTests(counted); try { assert.equal((await follow(location, { range: "bytes=0-1" })).status, 206); } finally { - __setExomemSqlForTests(taggedSql(pool)); + gatewaySql = asGateway; } const lookups = statements.filter((text) => text.includes("exomem_cloud_download_tickets")); assert.equal(lookups.length, 1, "no statement is added: the ticket row is checked in place"); diff --git a/src/lib/exomem-hosted/__tests__/flow-pool.ts b/src/lib/exomem-hosted/__tests__/flow-pool.ts index 464b4008..ab064a55 100644 --- a/src/lib/exomem-hosted/__tests__/flow-pool.ts +++ b/src/lib/exomem-hosted/__tests__/flow-pool.ts @@ -6,36 +6,47 @@ import { TEST_ROLE_PASSWORD } from "./test-role-password"; // scripts/exomem-cloud-grants.sql. A suite's own pool is the schema owner, which holds every right, // so a flow that needs a right the grants script withholds passes there and fails in production. // A suite hands its production code this pool instead, and keeps seeding and asserting on its own pool. +// The gateway reads the same tables as its own narrower role, so it has a pool of its own. const FLOW_ROLE = "substrate_app"; +const GATEWAY_ROLE = "exomem_gateway"; const FLOW_PASSWORD = TEST_ROLE_PASSWORD; /** The web app role's login on the suite's schema, with the grants script applied for it. */ -export async function productionPool(scopedUrl: string, schema: string): Promise { +export function productionPool(scopedUrl: string, schema: string): Promise { + return rolePool(FLOW_ROLE, scopedUrl, schema); +} + +/** The gateway role's login on the suite's schema, with the grants script applied for it. */ +export function gatewayPool(scopedUrl: string, schema: string): Promise { + return rolePool(GATEWAY_ROLE, scopedUrl, schema); +} + +async function rolePool(role: string, scopedUrl: string, schema: string): Promise { const admin = new Pool({ connectionString: process.env.EXOMEM_TEST_DATABASE_URL }); try { await admin.query( `DO $$ BEGIN - IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '${FLOW_ROLE}') THEN - CREATE ROLE ${FLOW_ROLE} LOGIN PASSWORD '${FLOW_PASSWORD}'; + IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '${role}') THEN + CREATE ROLE ${role} LOGIN PASSWORD '${FLOW_PASSWORD}'; ELSE - ALTER ROLE ${FLOW_ROLE} WITH LOGIN PASSWORD '${FLOW_PASSWORD}'; + ALTER ROLE ${role} WITH LOGIN PASSWORD '${FLOW_PASSWORD}'; END IF; END $$;` ); - await admin.query(`GRANT USAGE ON SCHEMA "${schema}" TO ${FLOW_ROLE}`); + await admin.query(`GRANT USAGE ON SCHEMA "${schema}" TO ${role}`); } finally { await admin.end(); } // The role exists now, so the grants script gives it its rights. await applyMigrations({ databaseUrl: scopedUrl }); const url = new URL(scopedUrl); - url.username = FLOW_ROLE; + url.username = role; url.password = FLOW_PASSWORD; const pool = new Pool({ connectionString: url.toString() }); // A pool that quietly ran as another role would turn this proof into a pass on every right. const { rows } = await pool.query<{ role: string }>("SELECT current_user AS role"); - if (rows[0]?.role !== FLOW_ROLE) throw new Error(`flow pool runs as ${rows[0]?.role}`); + if (rows[0]?.role !== role) throw new Error(`${role} pool runs as ${rows[0]?.role}`); return pool; } From 16fd2f35ed4712ffe0ff3aa8abc92d932c3e9612 Mon Sep 17 00:00:00 2001 From: Artexis10 Date: Wed, 2 Dec 2026 14:46:25 +0000 Subject: [PATCH 20/29] Tick task 5.8 with the commit that the cost proof measured The cost proof ran again on commit e8a7c3db, which holds every trigger of the change, and met each part of its pass condition. Task 5.8 names that commit and is ticked. D7 and the task say that the proof's script, generator and outputs are kept with the private record, so a later change to the triggers or the guards reruns it with the same instrument. --- .../design.md | 2 +- .../tasks.md | 15 ++++++--------- 2 files changed, 7 insertions(+), 10 deletions(-) diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md index b221239f..21f42501 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md @@ -253,7 +253,7 @@ The log also costs outside the request: Proof, on a disposable PostgreSQL: -- **Instrument.** `pgbench` runs the Home mint transaction's statements as a custom script, over generated data for 10,000 tenants. The same script runs with and without this change's triggers, five runs each, on the same machine and data. The script and the generator are not in this repository, and the first run's copies were not kept. A rerun builds them again from this description. +- **Instrument.** `pgbench` runs the Home mint transaction's statements as a custom script, over generated data for 10,000 tenants. The same script runs with and without this change's triggers, five runs each, on the same machine and data. The script and the generator are not in this repository. They are kept with the private record of the run, together with its outputs, so a later change to the triggers or the guards reruns the proof with the same instrument. - **Size.** The log holds 10 million generated records. That is enough, because every insert lands at the right edge of an index, or at the right edge of one tenant's range. The pages that an insert touches stay in memory at any log size. - **Result.** The run's outputs are kept as a private record outside this repository, and task 5.8 states the outcome and the commit that the run measured. The median must rise by less than one millisecond. - **Plans.** `EXPLAIN (ANALYZE, BUFFERS)` of one prune call shows that it reads only the records it deletes. The same output for each read of the log in D12 shows an index range and no full scan. D12's first check also reads the credential tables in full, so its plan is reported and no bound is set on it. diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md index d45a2ba0..5b22e0dd 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md @@ -253,7 +253,7 @@ without truncate. Neither state holds the trigger right. serves one that has its row. It refuses one whose path, token family or expiry differs from the stored row. A download request runs as many database statements as it did before this change. -- [ ] 5.8 Cost at the load target (D7). Generate data for 10,000 tenants and a +- [x] 5.8 Cost at the load target (D7). Generate data for 10,000 tenants and a log of 10 million records. With `pgbench`, run the Home mint transaction's statements with and without this change's triggers: five runs each, same machine, same data. Report the median and the 95th percentile of both arms, @@ -266,14 +266,11 @@ without truncate. Neither state holds the trigger right. outputs are kept as a private record outside this public repository. They are the median and the 95th percentile of the mint latency with and without the triggers, the write-ahead-log bytes for each mint, the size of a record, - and the `EXPLAIN` plans. One run measured commit `e21b73b1`, and it met each - part of the pass condition. That commit predates the triggers that end token - family records, the triggers on a cell's deletion and the trigger that - refuses a service credential for a tenant with no live cell. A rerun on the - final migration is owed, and this task stays open until it runs. The - `pgbench` script and the 10,000-tenant generator are not in this repository, - and the first run's copies were not kept. The rerun builds them again from - this description. + and the `EXPLAIN` plans. The run measured commit `e8a7c3db`, which holds + every trigger of this change, and it met each part of the pass condition. + The `pgbench` script and the 10,000-tenant generator are not in this + repository. They are kept with that private record, so a later change to the + triggers or the guards reruns the proof with the same instrument. - [ ] 5.9 Add the new suites to the PostgreSQL integration list in `.github/workflows/test.yml`. Verify: CI runs them. From 8eb2dc071875df14e6db87108ab9458a53d02512 Mon Sep 17 00:00:00 2001 From: Artexis10 Date: Wed, 2 Dec 2026 15:15:13 +0000 Subject: [PATCH 21/29] Close the way an earlier grants script restores wide rights The production build of the commit before this change can still be in flight at the merge. It waits for the migration job's lock, then applies the earlier grants script, which gives the web app's role select, insert, update and delete on every table, the log included. A redeploy of an earlier commit does the same. A dry run applies no grants, so the rollout step that ended with a dry run did not undo it. Task 7.7 now ends with a run of the migration job that is not a dry run, and checks the role's rights. The runbook gains a catalog check that lists each right of the web app's role beyond what the grants script gives it: any right on the log or its sequence, a write on schema_releases, an update of a ticket row, a delete on a table whose rows the role never deletes, and an update of a column outside a locked table's changeable list. Task 7.6 runs it, the design names the in-flight build as a way the old grants return, and the spec's list of checks and the count of catalog checks follow. The identity requirement of the OAuth spec now limits the one-way revocation and consumption rule to grants, token families, access tokens and refresh tokens, and points to design limits 5 and 12 for clients and reviewer credentials. --- docs/runbooks/exomem-cloud-operations.md | 71 ++++++++++++++++++- .../design.md | 7 +- .../specs/exomem-hosted-mcp-oauth/spec.md | 3 +- .../tasks.md | 31 +++++--- 4 files changed, 96 insertions(+), 16 deletions(-) diff --git a/docs/runbooks/exomem-cloud-operations.md b/docs/runbooks/exomem-cloud-operations.md index e9db701a..51f15806 100644 --- a/docs/runbooks/exomem-cloud-operations.md +++ b/docs/runbooks/exomem-cloud-operations.md @@ -984,7 +984,7 @@ ORDER BY id DESC LIMIT 50; #### Catalog checks -These four checks read the catalog and the grants. Run them with the range checks, and after every migration. Each one +These five checks read the catalog and the grants. Run them with the range checks, and after every migration. Each one is a finding when it returns a row. Run them as `substrate_audit`: they need no other right. Triggers of this change that are missing or disabled. A row with a `NULL` state is missing. A state other than `O` is @@ -1058,6 +1058,75 @@ SELECT pg_get_userbyid(roleid) AS member_of FROM pg_auth_members WHERE member = 'substrate_app'::regrole; ``` +Rights of the web app's role beyond what the grants script gives it. The grants script of an earlier release gives the +role select, insert, update and delete on every table. It runs again when a build of an earlier commit applies it: the +production build that was in flight at the merge, or a redeploy of an earlier commit. A dry run of the migration job +applies no grants. Each row is a right that the role must not hold, whether it holds the right itself or through `PUBLIC` +or a membership: + +- any right on the log, or on the sequence that numbers its records; +- insert, update or delete on `schema_releases`, where the role keeps select; +- update of a ticket row, where the role keeps select, insert and delete; +- delete on a table whose rows the role never deletes; +- update of a column outside the table's changeable list (design D2). + +The expected result is no rows. The emergency statement 1 also shows a row here until the next run of the grants script. +The query repeats the changeable columns of `scripts/exomem-cloud-grants.sql`, so a change to one list needs a change to the other. + +```sql +SELECT forbidden.table_name, forbidden.privilege, NULL::name AS column_name +FROM (VALUES + ('exomem_cloud_issuance_log', 'SELECT'), ('exomem_cloud_issuance_log', 'INSERT'), + ('exomem_cloud_issuance_log', 'UPDATE'), ('exomem_cloud_issuance_log', 'DELETE'), + ('schema_releases', 'INSERT'), ('schema_releases', 'UPDATE'), ('schema_releases', 'DELETE'), + ('exomem_cloud_download_tickets', 'UPDATE'), + ('exomem_oauth_grants', 'DELETE'), ('exomem_oauth_clients', 'DELETE'), ('exomem_tenants', 'DELETE'), + ('exomem_users', 'DELETE'), ('exomem_cloud_service_credentials', 'DELETE'), + ('exomem_marketplace_reviewer_credentials', 'DELETE'), ('exomem_cloud_cells', 'DELETE') +) AS forbidden(table_name, privilege) +WHERE CASE forbidden.privilege + WHEN 'DELETE' THEN has_table_privilege('substrate_app', to_regclass(forbidden.table_name), 'DELETE') + ELSE has_any_column_privilege('substrate_app', to_regclass(forbidden.table_name), forbidden.privilege) +END +UNION ALL +SELECT 'exomem_cloud_issuance_log_id_seq', privilege.name, NULL +FROM (VALUES ('USAGE'), ('SELECT'), ('UPDATE')) AS privilege(name) +WHERE has_sequence_privilege('substrate_app', pg_get_serial_sequence('exomem_cloud_issuance_log', 'id'), privilege.name) +UNION ALL +SELECT locked.table_name, 'UPDATE', attribute.attname +FROM (VALUES + ('exomem_oauth_grants', ARRAY['scopes', 'refresh_allowed', 'authorization_transaction_id', + 'updated_at', 'revoked_at', 'client_context_override']), + ('exomem_oauth_token_families', ARRAY['revoked_at', 'revoked_reason']), + ('exomem_oauth_access_tokens', ARRAY['revoked_at']), + ('exomem_oauth_refresh_tokens', ARRAY['consumed_at']), + ('exomem_cloud_service_credentials', ARRAY['revoked_at', 'revoked_by_principal_digest']) +) AS locked(table_name, changeable) +JOIN pg_attribute AS attribute + ON attribute.attrelid = to_regclass(locked.table_name) AND attribute.attnum > 0 AND NOT attribute.attisdropped +WHERE attribute.attname <> ALL (locked.changeable) + AND has_column_privilege('substrate_app', attribute.attrelid, attribute.attnum, 'UPDATE') +UNION ALL +SELECT fixed.table_name, 'UPDATE', attribute.attname +FROM (VALUES + ('exomem_oauth_clients', ARRAY['id', 'client_id']), + ('exomem_tenants', ARRAY['owner_user_id']) +) AS fixed(table_name, identity_columns) +JOIN pg_attribute AS attribute + ON attribute.attrelid = to_regclass(fixed.table_name) AND attribute.attnum > 0 AND NOT attribute.attisdropped +WHERE attribute.attname = ANY (fixed.identity_columns) + AND has_column_privilege('substrate_app', attribute.attrelid, attribute.attnum, 'UPDATE') +ORDER BY 1, 2, 3; +``` + +If a row appears: + +1. Open the "Actions" tab of the repository and select the workflow `migrate-database`. +2. Select "Run workflow" for `main`, clear "List the pending migrations and change nothing", and run it. +3. Wait for the green run. Its grants script takes back each right that the role holds by its own grant. +4. Run the check again. The expected result is no rows. +5. If a row remains, the right comes through `PUBLIC` or a membership. Revoke it from that holder. + Create rights and schemas. A role that can create a schema can run its code as the schema owner, with no trigger right. The first query lists each role that holds a create right on the database, or on a schema outside `pg_catalog` and `information_schema`. It counts a right held directly or through a membership. diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md index 21f42501..7e2b9347 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md @@ -364,9 +364,10 @@ A log that nobody can read cheaply proves nothing. Two readers exist, and each o - triggers of this change that are missing or disabled; - roles other than the owner that hold the trigger right on a table in the schema; - roles that the web app's role is a member of; +- rights that the web app's role holds on the log, `schema_releases`, ticket rows and the locked tables beyond what the grants script gives it; - create rights that a role other than a superuser, the schema owner or `pg_database_owner` holds on the database or on a schema outside `pg_catalog` and `information_schema`, and schemas that a role other than the schema owner, the bootstrap superuser or `pg_database_owner` owns. -The first check also reads the credential tables in full. It filters their rows by `created_at`, and none of the five tables has an index on that column. A consumed refresh token of an unexpired family stays in its table, so the tables hold more than the live credentials. The read grows with those tables, not with the range of the log. The operator runs it on demand (limit 13), not on a schedule. A scheduled version needs an index on `created_at` or a different query, which is a later step. The migration writes no record for a row whose record the prune would delete (D5), so the check ignores rows from before the release. The first run starts at the release time, which is the `recorded_at` of the log's first record, and not at the start of time. That time is the migration's time when the backfill wrote any record. The check then flags no skipped row. The last four read the catalog. +The first check also reads the credential tables in full. It filters their rows by `created_at`, and none of the five tables has an index on that column. A consumed refresh token of an unexpired family stays in its table, so the tables hold more than the live credentials. The read grows with those tables, not with the range of the log. The operator runs it on demand (limit 13), not on a schedule. A scheduled version needs an index on `created_at` or a different query, which is a later step. The migration writes no record for a row whose record the prune would delete (D5), so the check ignores rows from before the release. The first run starts at the release time, which is the `recorded_at` of the log's first record, and not at the start of time. That time is the migration's time when the backfill wrote any record. The check then flags no skipped row. The last five read the catalog. **Late commits.** PostgreSQL assigns a record's identifier at insert, not at commit. A record can therefore commit after a check has read past its identifier. Each run starts one hour of records before the point where the previous run stopped, so the next run reads such a record. It finds that start by walking back through the primary key from the nearest record at or below the previous stop that still exists, because the prune can delete the record that the stop names. If none exists, every record is newer than the previous stop, and the run starts at the oldest record. The read stays bounded. A record whose transaction stayed open for longer than that hour is missed by the range checks. The read of one tenant's records still returns it. @@ -413,7 +414,7 @@ The claim is: the database records every credential that the gateway admits from 1. Before the merge, the operator creates the protected environment and its secret, and creates the audit role. The operator confirms that the job's runner can reach the migration address, and reads the repository settings and the database facts that the lock depends on. 2. The operator approves the merge. The job applies the migrations and the grants. The lock and the log are in force from that moment, and the web app starts to store ticket rows. 3. The operator reads the log and runs the flows once against production. -4. The operator removes the schema-owner credential from every web deployment environment, rotates it, and checks the preview and development variables. +4. The operator removes the schema-owner credential from every web deployment environment, rotates it, and checks the preview and development variables. The operator then starts the migration job once more, not as a dry run, and reads the rights of the web app's role. 5. The operator rolls the gateway release that requires ticket rows, at least one day after step 2. 6. The evidence goes to the owner of the privacy page text. @@ -421,7 +422,7 @@ Rollback: - **A flow fails under the lock.** The schema owner runs the emergency statement from the runbook. A commit then fixes the grants script or the guard. - **A revert before step 4.** The revert restores the build-time migration, and its build applies the earlier grants script. The web app's role regains update and delete on every table, the new ones included. It gains no trigger right, because that script grants none. The guards still refuse a change to a fixed or one-way column and a delete of an identity row. They also refuse every write to the log and to `schema_releases`, and every update of a ticket row. The migrations' tables and triggers stay. -- **A rebuild of an earlier commit between steps 2 and 4.** It applies the earlier grants script in the same way. The next run of the migration job restores the rights. Step 4 follows step 2 closely for that reason. +- **The earlier grants script returns between steps 2 and 4.** Two builds can apply it. The first is the in-flight production build of the commit before this change: it waits on the migration job's advisory lock, then applies the earlier grants script after the job's own. The second is a redeploy of an earlier commit. Each leaves the web app's role with the wide state, the log included. A dry run applies no grants. The non-dry run in step 4 (task 7.7) restores the narrow rights, and the runbook's check of the role's rights lists any that remain. Step 4 follows step 2 closely for that reason. - **After step 4.** The earlier build script cannot migrate. With no schema-owner connection string, it falls back to the web app's connection string, which holds no right on `schema_migrations`, and the build fails. A revert of this change is then a fix forward through the migration job. A promotion of an existing deployment still works, because it runs no build. - **The gateway.** Roll the gateway back to its previous image before the web app goes back past this change (D8). diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md index 668da8b9..84a35b43 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md @@ -2,7 +2,7 @@ ### Requirement: OAuth identity fields are unchangeable once written -The database SHALL refuse any change to an identity field of a grant, token family, access token, refresh token or client, a tenant's owner, and a cell's identifier or tenant. A revocation or consumption time SHALL change only from empty to a time. It SHALL refuse a delete of a grant, client, tenant, user, reviewer credential or cell. Each refusal SHALL bind all roles but the schema owner, whatever select, insert, update, delete and truncate rights they hold. Design limit 7 lists exceptions. +The database SHALL refuse a change to an identity field of a grant, token family, access token, refresh token or client, a tenant's owner, and a cell's identifier or tenant, and a delete of a grant, client, tenant, user, reviewer credential or cell. A grant, token family, access token or refresh token SHALL change its revocation or consumption time only from empty. Each refusal SHALL bind all roles but the schema owner, whatever rights they hold. Design limits 5, 7 and 12 list exceptions. #### Scenario: A cell is re-pointed @@ -325,6 +325,7 @@ A read-only audit role SHALL hold select on the issuance log and on the columns - **AND** they list records whose database role is not the web app's role, except backfilled records - **AND** they list each role other than the owner that holds the trigger right on a table in the schema - **AND** they list each role that the web app's role is a member of +- **AND** they list each right that the web app's role holds on the log, `schema_releases`, ticket rows and the locked tables beyond what the grants script gives it - **AND** they list each create right that a role other than a superuser, the schema owner or `pg_database_owner` holds on the database or on a schema outside `pg_catalog` and `information_schema`, and each schema that another role owns #### Scenario: One tenant's records are listed diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md index 5b22e0dd..dec873f5 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md @@ -286,11 +286,12 @@ without truncate. Neither state holds the trigger right. - [x] 6.2 `docs/runbooks/exomem-cloud-operations.md`: what the lock refuses, and each emergency statement with what it suspends. The issuance log: the D12 checks as the audit role, with the hour that each run reads again, a - size check, and the statement that disables recording. The three catalog - checks of D12: the trigger right, the web app's role memberships, create - rights held by a role other than a superuser, the schema owner or - `pg_database_owner`, and schemas that another role owns. Ticket - rows. The deploy order and the rollback order of D8. + size check, and the statement that disables recording. The four catalog + checks of D12: the trigger right, the web app's role memberships, the web + app's rights beyond what the grants script gives it (with the steps that + restore them), create rights held by a role other than a superuser, the + schema owner or `pg_database_owner`, and schemas that another role owns. + Ticket rows. The deploy order and the rollback order of D8. - [x] 6.3 `docs/runbooks/vercel-deployments.md` and the README's migration section: the production build reads its schema release and never migrates. Say beside promotion, rollback and uploaded deployments that none of them @@ -375,16 +376,24 @@ and its date. it and deployed. - [ ] 7.6 Read the log and run the flows once. Sign in, connect an app, wait for one token refresh, open Home, download a file, disconnect the app, and - see one maintenance run succeed. Run the D12 checks as the audit role. - Evidence: the flows add records for the test account, and the checks list - nothing. Run no attack against production; task 5.1 is that proof. + see one maintenance run succeed. Run the D12 checks as the audit role, the + check of the web app's rights included. Evidence: the flows add records for + the test account, and the checks list nothing. A row from the rights check + means that an earlier grants script ran after the job, and step 7.7 takes + the right back. Run no attack against production; task 5.1 is that proof. - [ ] 7.7 On the day of step 7.5, remove the schema-owner connection string and `SKIP_VERCEL_MIGRATE` from every web deployment environment. Then rotate the schema-owner credential and store the new value in the protected environment. Until this step, a rebuild of an earlier commit applies the - earlier grants script. Evidence: a listing of variable names shows no - schema-owner variable, a dry run of the job is green, and a connection with - the old credential is refused. + earlier grants script. So can the production build of the commit before this + change, if it was still in flight at step 7.5: it waits on the job's lock, + then applies that script after the job's own. When no build of an earlier + commit is still running, run the `migrate-database` workflow for `main` with + `dry_run` set to false. A dry run applies no grants. The job's grants script + restores the narrow rights. Then run the runbook's check of the web app's + rights as the audit role. Evidence: a listing of variable names shows no + schema-owner variable, the non-dry run is green, the rights check lists no + row, and a connection with the old credential is refused. - [ ] 7.8 Read the host and the database name of each preview and development database variable, without printing a secret. Replace and rotate any that names the production database. Check that no web deployment environment From b4d6a204b8ee123c1dfbec291689fbc6d0b184c2 Mon Sep 17 00:00:00 2001 From: Artexis10 Date: Wed, 2 Dec 2026 15:27:09 +0000 Subject: [PATCH 22/29] Keep the rights check free of the grants script's column lists The runbook's check of the web app's rights repeated the changeable column lists of the grants script. Nothing kept the two in step, so a later grants change would have made the check list a legitimate right and sent the operator after a grant that does not exist. For the five column-locked tables and for clients and tenants, the query now lists only a table-wide update, which the grants script never gives. It counts a right held through PUBLIC or a membership, and ignores a single column grant, which the guard refuses to honour for a locked column. The rows for the log and its sequence, schema_releases, ticket rows and the deletes stay as they were. The runbook says that a column grant is not listed, and its recovery steps name the causes of a surviving row in order: a build of an earlier commit that still runs, then a right through PUBLIC or a membership. D12 and the spec's scenario say "table-wide" for the locked tables. --- docs/runbooks/exomem-cloud-operations.md | 54 ++++++++----------- .../design.md | 2 +- .../specs/exomem-hosted-mcp-oauth/spec.md | 2 +- 3 files changed, 23 insertions(+), 35 deletions(-) diff --git a/docs/runbooks/exomem-cloud-operations.md b/docs/runbooks/exomem-cloud-operations.md index 51f15806..ae3afb7e 100644 --- a/docs/runbooks/exomem-cloud-operations.md +++ b/docs/runbooks/exomem-cloud-operations.md @@ -1068,55 +1068,41 @@ or a membership: - insert, update or delete on `schema_releases`, where the role keeps select; - update of a ticket row, where the role keeps select, insert and delete; - delete on a table whose rows the role never deletes; -- update of a column outside the table's changeable list (design D2). +- a table-wide update on a table that carries column rights only: grants, token families, access tokens, refresh + tokens, service credentials, clients and tenants (design D2). -The expected result is no rows. The emergency statement 1 also shows a row here until the next run of the grants script. -The query repeats the changeable columns of `scripts/exomem-cloud-grants.sql`, so a change to one list needs a change to the other. +The expected result is no rows. A single column grant on a locked column is not listed, because the guard refuses the +change anyway. That includes the emergency statement 1. ```sql -SELECT forbidden.table_name, forbidden.privilege, NULL::name AS column_name +SELECT forbidden.table_name, forbidden.privilege FROM (VALUES ('exomem_cloud_issuance_log', 'SELECT'), ('exomem_cloud_issuance_log', 'INSERT'), ('exomem_cloud_issuance_log', 'UPDATE'), ('exomem_cloud_issuance_log', 'DELETE'), ('schema_releases', 'INSERT'), ('schema_releases', 'UPDATE'), ('schema_releases', 'DELETE'), - ('exomem_cloud_download_tickets', 'UPDATE'), - ('exomem_oauth_grants', 'DELETE'), ('exomem_oauth_clients', 'DELETE'), ('exomem_tenants', 'DELETE'), - ('exomem_users', 'DELETE'), ('exomem_cloud_service_credentials', 'DELETE'), - ('exomem_marketplace_reviewer_credentials', 'DELETE'), ('exomem_cloud_cells', 'DELETE') + ('exomem_cloud_download_tickets', 'UPDATE') ) AS forbidden(table_name, privilege) WHERE CASE forbidden.privilege WHEN 'DELETE' THEN has_table_privilege('substrate_app', to_regclass(forbidden.table_name), 'DELETE') ELSE has_any_column_privilege('substrate_app', to_regclass(forbidden.table_name), forbidden.privilege) END UNION ALL -SELECT 'exomem_cloud_issuance_log_id_seq', privilege.name, NULL +SELECT 'exomem_cloud_issuance_log_id_seq', privilege.name FROM (VALUES ('USAGE'), ('SELECT'), ('UPDATE')) AS privilege(name) WHERE has_sequence_privilege('substrate_app', pg_get_serial_sequence('exomem_cloud_issuance_log', 'id'), privilege.name) UNION ALL -SELECT locked.table_name, 'UPDATE', attribute.attname -FROM (VALUES - ('exomem_oauth_grants', ARRAY['scopes', 'refresh_allowed', 'authorization_transaction_id', - 'updated_at', 'revoked_at', 'client_context_override']), - ('exomem_oauth_token_families', ARRAY['revoked_at', 'revoked_reason']), - ('exomem_oauth_access_tokens', ARRAY['revoked_at']), - ('exomem_oauth_refresh_tokens', ARRAY['consumed_at']), - ('exomem_cloud_service_credentials', ARRAY['revoked_at', 'revoked_by_principal_digest']) -) AS locked(table_name, changeable) -JOIN pg_attribute AS attribute - ON attribute.attrelid = to_regclass(locked.table_name) AND attribute.attnum > 0 AND NOT attribute.attisdropped -WHERE attribute.attname <> ALL (locked.changeable) - AND has_column_privilege('substrate_app', attribute.attrelid, attribute.attnum, 'UPDATE') -UNION ALL -SELECT fixed.table_name, 'UPDATE', attribute.attname +SELECT forbidden.table_name, forbidden.privilege FROM (VALUES - ('exomem_oauth_clients', ARRAY['id', 'client_id']), - ('exomem_tenants', ARRAY['owner_user_id']) -) AS fixed(table_name, identity_columns) -JOIN pg_attribute AS attribute - ON attribute.attrelid = to_regclass(fixed.table_name) AND attribute.attnum > 0 AND NOT attribute.attisdropped -WHERE attribute.attname = ANY (fixed.identity_columns) - AND has_column_privilege('substrate_app', attribute.attrelid, attribute.attnum, 'UPDATE') -ORDER BY 1, 2, 3; + ('exomem_oauth_grants', 'UPDATE'), ('exomem_oauth_token_families', 'UPDATE'), + ('exomem_oauth_access_tokens', 'UPDATE'), ('exomem_oauth_refresh_tokens', 'UPDATE'), + ('exomem_cloud_service_credentials', 'UPDATE'), ('exomem_oauth_clients', 'UPDATE'), + ('exomem_tenants', 'UPDATE'), + ('exomem_oauth_grants', 'DELETE'), ('exomem_oauth_clients', 'DELETE'), ('exomem_tenants', 'DELETE'), + ('exomem_users', 'DELETE'), ('exomem_cloud_service_credentials', 'DELETE'), + ('exomem_marketplace_reviewer_credentials', 'DELETE'), ('exomem_cloud_cells', 'DELETE') +) AS forbidden(table_name, privilege) +WHERE has_table_privilege('substrate_app', to_regclass(forbidden.table_name), forbidden.privilege) +ORDER BY 1, 2; ``` If a row appears: @@ -1125,7 +1111,9 @@ If a row appears: 2. Select "Run workflow" for `main`, clear "List the pending migrations and change nothing", and run it. 3. Wait for the green run. Its grants script takes back each right that the role holds by its own grant. 4. Run the check again. The expected result is no rows. -5. If a row remains, the right comes through `PUBLIC` or a membership. Revoke it from that holder. +5. If a row remains, wait for any running build of an earlier commit to end. Then run the job and the check again. +6. If a row still remains, the right comes through `PUBLIC` or a membership. Revoke it from that holder. +7. Run the check again. The expected result is no rows. Create rights and schemas. A role that can create a schema can run its code as the schema owner, with no trigger right. The first query lists each role that holds a create right on the database, or on a schema outside `pg_catalog` and `information_schema`. diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md index 7e2b9347..dd68f907 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md @@ -364,7 +364,7 @@ A log that nobody can read cheaply proves nothing. Two readers exist, and each o - triggers of this change that are missing or disabled; - roles other than the owner that hold the trigger right on a table in the schema; - roles that the web app's role is a member of; -- rights that the web app's role holds on the log, `schema_releases`, ticket rows and the locked tables beyond what the grants script gives it; +- rights that the web app's role holds on the log, `schema_releases`, ticket rows and, table-wide, the locked tables beyond what the grants script gives it; - create rights that a role other than a superuser, the schema owner or `pg_database_owner` holds on the database or on a schema outside `pg_catalog` and `information_schema`, and schemas that a role other than the schema owner, the bootstrap superuser or `pg_database_owner` owns. The first check also reads the credential tables in full. It filters their rows by `created_at`, and none of the five tables has an index on that column. A consumed refresh token of an unexpired family stays in its table, so the tables hold more than the live credentials. The read grows with those tables, not with the range of the log. The operator runs it on demand (limit 13), not on a schedule. A scheduled version needs an index on `created_at` or a different query, which is a later step. The migration writes no record for a row whose record the prune would delete (D5), so the check ignores rows from before the release. The first run starts at the release time, which is the `recorded_at` of the log's first record, and not at the start of time. That time is the migration's time when the backfill wrote any record. The check then flags no skipped row. The last five read the catalog. diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md index 84a35b43..85d19525 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md @@ -325,7 +325,7 @@ A read-only audit role SHALL hold select on the issuance log and on the columns - **AND** they list records whose database role is not the web app's role, except backfilled records - **AND** they list each role other than the owner that holds the trigger right on a table in the schema - **AND** they list each role that the web app's role is a member of -- **AND** they list each right that the web app's role holds on the log, `schema_releases`, ticket rows and the locked tables beyond what the grants script gives it +- **AND** they list each right that the web app's role holds on the log, `schema_releases`, ticket rows and, table-wide, the locked tables beyond what the grants script gives it - **AND** they list each create right that a role other than a superuser, the schema owner or `pg_database_owner` holds on the database or on a schema outside `pg_catalog` and `information_schema`, and each schema that another role owns #### Scenario: One tenant's records are listed From a2e262d6af80d4f21c5e9ef61cc97c93d97fdb5e Mon Sep 17 00:00:00 2001 From: Artexis10 Date: Wed, 2 Dec 2026 16:16:36 +0000 Subject: [PATCH 23/29] Release the tip of main, page the runbook reads and end records at the statement The schema release job could lose a newer push's release when two runs overlapped in the concurrency group. The runbook's log reads could list a credential whose record the prune had rightly deleted, and could read the whole log on a first run. The two end-time updates of the second migration used the transaction's start time. Schema release - Every run checks out main, installs, then reads the tip of origin/main again with scripts/schema-release-plan.sh. It applies that tip only when its checkout equals the tip, and records that commit. When main moved during the install, the run ends green with a notice: the push that moved main started its own run. The push trigger has no path filter, and a test holds that. - A dry run takes its own concurrency group, takes no advisory lock and creates no schema_migrations table: an absent table reads as an empty set. - --record-superseded and recordSupersededOnly are removed. Every run now releases the tip, so no run has superseded commits left to record. - schema_releases gets a partial index on released rows, newest first, so the wait script's poll reads one index entry and no longer sorts the table. - A test applies and records the tip of a disposable two-commit remote, and applies nothing once main has moved on. Record ends - A service credential's record and a token family's record end at statement_timestamp(), as does a cell's revoked_at, so a transaction that stays open after the revoking statement no longer lengthens the record. Runbook reads - Check 1 lists only credentials that must still have a record: created in the last 90 days and after the second migration was applied. The audit role cannot read expiry columns or schema_migrations, so the operator reads the install time once and passes it to every run. A live service credential older than 90 days is not checked. - Each run reads at most one page of identifiers, 100,000 by default and the operator's to change. The operator repeats the run from its stop until it reaches the newest identifier. Checks 2 and 3 and the log side of check 1 stay primary-key index ranges, including the first run. - The dry listing of the release steps takes no lock. Specification and design - The tasks, D5, D9, D12 and the two specs follow the above. Task 7.4 and D5 count the rows that each backfill read scans, which are the full source tables, and use that count for the lock window and the go/no-go. Two symbols of the lock fixture are no longer exported. --- .github/workflows/migrate-database.yml | 32 ++++++---- docs/runbooks/exomem-cloud-operations.md | 55 ++++++++++------ docs/runbooks/production-keys-and-storage.md | 14 ++-- ...omem_identity_lock_and_schema_releases.sql | 5 ++ ...omem_issuance_log_and_download_tickets.sql | 16 +++-- .../design.md | 19 +++--- .../specs/exomem-hosted-mcp-oauth/spec.md | 9 ++- .../specs/substrate-database-releases/spec.md | 22 ++++--- .../tasks.md | 61 ++++++++++-------- scripts/migrate.ts | 47 +++++++------- scripts/schema-release-plan.sh | 41 ++++++------ scripts/wait-for-schema-release.ts | 13 ++-- ...-issuance-log-postgres.integration.test.ts | 36 +++++++++++ .../__tests__/identity-lock-fixture.ts | 4 +- .../migration-runner.integration.test.ts | 53 ++++++++++++++- ...chema-release-postgres.integration.test.ts | 60 ++++++++++++++--- .../__tests__/schema-release.test.ts | 64 ++++++++++++++----- 17 files changed, 387 insertions(+), 164 deletions(-) diff --git a/.github/workflows/migrate-database.yml b/.github/workflows/migrate-database.yml index 3eae19e5..99d124e7 100644 --- a/.github/workflows/migrate-database.yml +++ b/.github/workflows/migrate-database.yml @@ -1,7 +1,15 @@ # Applies the database migrations and the grants script for the tip of `main`, -# then records the commit's schema release. The production build waits for that +# then records the tip's schema release. The production build waits for that # row (scripts/wait-for-schema-release.ts) and runs no migration itself. # +# Every run releases the tip of `main` as it stands when the run starts, whatever +# commit started it. The group below keeps one waiting run, so a restart of an +# old run can replace the waiting run of a newer push. That run then releases the +# newer tip and loses nothing. Only the step that applies reads the tip again, and +# it applies nothing when `main` moved during the install: the push that moved it +# started a run of its own. This rule needs a run for every push to `main`, so +# the `push` trigger has no path filter. +# # This is the only workflow that names the protected environment, and it starts # only on a push to `main` or by hand. The environment accepts only `main` and # holds the schema-owner connection string. @@ -34,34 +42,34 @@ jobs: timeout-minutes: 30 environment: production-schema steps: + # The tip, not the commit that started the run. - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 with: + ref: main fetch-depth: 0 persist-credentials: false - # Reads git only. A commit behind the tip applies nothing. - - id: plan - run: scripts/schema-release-plan.sh "$GITHUB_SHA" >> "$GITHUB_OUTPUT" - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 with: node-version: 24 # No package install script runs in a job that holds the schema owner's credential. - run: npm ci --ignore-scripts + # Reads git only. It runs after the install and just before the migration, so it + # sees the tip as late as it can. + - id: plan + run: scripts/schema-release-plan.sh >> "$GITHUB_OUTPUT" # The only step that receives the secret. - name: Migrate env: DATABASE_MIGRATION_URL: ${{ secrets.DATABASE_MIGRATION_URL }} DRY_RUN: ${{ inputs.dry_run }} + APPLY: ${{ steps.plan.outputs.apply }} TIP: ${{ steps.plan.outputs.tip }} SUPERSEDED: ${{ steps.plan.outputs.superseded }} run: | if [ "$DRY_RUN" = "true" ]; then - if [ "$TIP" = "true" ]; then - node_modules/.bin/tsx scripts/migrate.ts --dry - else - echo "Dry run: $GITHUB_SHA is behind the tip of main, nothing to list." - fi - elif [ "$TIP" = "true" ]; then - node_modules/.bin/tsx scripts/migrate.ts --commit "$GITHUB_SHA" --superseded "$SUPERSEDED" + node_modules/.bin/tsx scripts/migrate.ts --dry + elif [ "$APPLY" = "true" ]; then + node_modules/.bin/tsx scripts/migrate.ts --commit "$TIP" --superseded "$SUPERSEDED" else - node_modules/.bin/tsx scripts/migrate.ts --record-superseded --superseded "$SUPERSEDED" + echo "::notice::main moved to $TIP while this job installed. The run for that push applies it." fi diff --git a/docs/runbooks/exomem-cloud-operations.md b/docs/runbooks/exomem-cloud-operations.md index ae3afb7e..63f0e3f9 100644 --- a/docs/runbooks/exomem-cloud-operations.md +++ b/docs/runbooks/exomem-cloud-operations.md @@ -888,45 +888,59 @@ whatever the other lanes do. Connect as `substrate_audit` for every query in this section. The grants script gives that role select on the log. It also gives select on the `id` and `created_at` columns of the five credential tables, and on `id` and `owner_user_id` of `exomem_tenants`. It gives no other right. Each query below reads a range of record identifiers through the primary key. -Its cost on the log follows the range, not the size of the log. The first check also reads the credential tables in full. +Each run reads at most one page of record identifiers, so its cost on the log follows the page, not the size of the log. The first check also reads the credential tables in full. Nothing schedules these checks. Run them on demand, and after any emergency statement. Each run starts one hour of records before the point where the previous run stopped. A record gets its identifier when it is inserted, not when it commits, so a record can commit after a run has read past it. The overlap lets the next run read it. A record whose transaction stayed open for longer than that hour is missed by the range checks. The read of one tenant's records still returns it. -1. Write down the value of `hi` that the previous run printed. For the first run, use `0`. -2. Start `psql` as `substrate_audit` with the value: `psql -v prev=`. -3. Find the range of this run: +1. Read the time that migration 0102 was applied, once, as the schema owner: `SELECT applied_at FROM schema_migrations WHERE version = '0102_exomem_issuance_log_and_download_tickets.sql';`. Every run takes it as `install`. The audit role cannot read `schema_migrations`. +2. Write down the value of `hi` that the previous run printed. For the first run, use `0`. +3. Start `psql` as `substrate_audit`: `psql -v prev= -v install='' -v page=100000`. +4. Find the range of this run: ```sql - SELECT coalesce(max(id), 0) AS hi FROM exomem_cloud_issuance_log \gset + SELECT coalesce(max(id), 0) AS newest FROM exomem_cloud_issuance_log \gset SELECT coalesce( (SELECT id FROM exomem_cloud_issuance_log WHERE id <= :prev AND recorded_at < (SELECT recorded_at FROM exomem_cloud_issuance_log WHERE id <= :prev ORDER BY id DESC LIMIT 1) - interval '1 hour' ORDER BY id DESC LIMIT 1), 0) AS lo \gset + SELECT least(:newest, :lo + :page) AS hi \gset SELECT greatest( coalesce((SELECT recorded_at FROM exomem_cloud_issuance_log WHERE id = :lo), '-infinity'), - coalesce((SELECT recorded_at FROM exomem_cloud_issuance_log ORDER BY id LIMIT 1), '-infinity')) AS lo_time \gset - \echo hi=:hi lo=:lo + :'install'::timestamptz, + now() - interval '90 days') AS lo_time \gset + SELECT CASE WHEN :hi = :newest THEN 'infinity'::timestamptz + ELSE coalesce((SELECT recorded_at FROM exomem_cloud_issuance_log + WHERE id <= :hi ORDER BY id DESC LIMIT 1), '-infinity') - interval '1 hour' END AS hi_time \gset + \echo newest=:newest hi=:hi lo=:lo ``` + `page` is the most identifiers that one run reads. It is yours to change: raise it to read more in a run, or lower it to read + less. Keep it above the number of records that the web app writes in one hour. Otherwise `lo` moves back by more than the + page, and `hi` does not rise above `prev`. + The prune can delete the record that `prev` names, so `lo` anchors on the nearest record at or below `prev` that still exists, and walks back from there through the primary key for one hour of records. If no record at or below `prev` - exists, every record in the log is newer than `prev`, and `lo` is `0`: the range then holds exactly the records - that this run has not read. An empty log gives `hi=0`, and the checks that use the range return no row. + exists, every record in the log is newer than `prev`, and `lo` is `0`: the range then starts at the first record that + this run has not read. An empty log gives `hi=0`, and the checks that use the range return no row. - `lo_time` is never earlier than the log's first record. That record carries the migration's time when the backfill wrote - any record. The migration wrote no record for a row whose end was more than 90 days old, and the first run must not list - those rows. If the log is empty, `lo_time` is `-infinity`, and the first check lists every credential row that the - backfill skipped. + `lo_time` and `hi_time` bound the credential rows that the first check lists. `lo_time` is never earlier than `install`. No + record exists before the migration, except the backfill's, which carries the migration's time, and the backfill wrote + none for a row that ended more than 90 days before. `lo_time` is also never earlier than 90 days ago. The prune deletes a record + 90 days after its credential ends, and a credential ends after it is created, so the record of a credential that is less + than 90 days old exists. The record of an older credential may be gone. The first check does not list that credential, + and that includes a service credential that is still live. `hi_time` is one hour before the record that `hi` names, and + `infinity` for the last page. A credential that is newer than `hi_time` belongs to the next pass, which starts one + hour of records before `hi`. -4. Run the three checks. Each one is a finding when it returns a row. +5. Run the three checks. Each one is a finding when it returns a row. Credential rows without a record. One statement reads the credential rows and the log, so a credential and its - record are both visible or both absent. A row here has no record. It reads the log from `lo` to its end. It reads + record are both visible or both absent. A row here has no record. It reads the log from `lo` to `hi`. It reads the five credential tables in full, because none has an index on `created_at`, and a consumed refresh token of an unexpired family stays in its table. Run it on demand, never from a schedule. A scheduled version needs an index on `created_at` or a different query, which is a later step. @@ -940,10 +954,10 @@ open for longer than that hour is missed by the range checks. The read of one te UNION ALL SELECT 'service_credential', id, created_at FROM exomem_cloud_service_credentials UNION ALL SELECT 'download_ticket', id, created_at FROM exomem_cloud_download_tickets ) AS created - WHERE created.created_at >= :'lo_time' + WHERE created.created_at >= :'lo_time' AND created.created_at < :'hi_time' AND NOT EXISTS ( SELECT 1 FROM exomem_cloud_issuance_log AS record - WHERE record.id >= :lo + WHERE record.id BETWEEN :lo AND :hi AND record.credential_kind = created.kind AND record.credential_id = created.id); ``` @@ -969,10 +983,13 @@ open for longer than that hour is missed by the range checks. The read of one te WHERE record.id BETWEEN :lo AND :hi AND record.user_id <> tenant.owner_user_id; ``` -5. Write down the value of `hi` as the stop of this run. The next run takes it as `prev`. +6. Write down the value of `hi` as the stop of this run. The next run takes it as `prev`. +7. If `hi` is below `newest`, the log holds records that this run did not read. Run again with `prev` set to this `hi`, until + `hi` equals `newest`. The first run on a large log, and a run after a long gap, take several passes. The expected result + is a last pass that prints `hi` equal to `newest`. Read one tenant's records, newest first, a page at a time. Use it for an incident, and for an owner who asks who held -access. For the first page, use the value of `hi` plus one as ``. For the next page, use the lowest `id` of the +access. For the first page, use the value of `newest` plus one as ``. For the next page, use the lowest `id` of the page before. ```sql diff --git a/docs/runbooks/production-keys-and-storage.md b/docs/runbooks/production-keys-and-storage.md index 0087176a..ba03d7c8 100644 --- a/docs/runbooks/production-keys-and-storage.md +++ b/docs/runbooks/production-keys-and-storage.md @@ -174,13 +174,13 @@ Each of these has bitten us in production at least once during hosted-backup rol **5. A protected GitHub job applies the migrations. The Vercel build never does.** The workflow `.github/workflows/migrate-database.yml` runs the job `migrate`. It starts on every push to `main` and by hand. It runs in the protected environment `production-schema`, whose branch rule accepts only `main`. That environment holds the schema-owner connection string as the secret `DATABASE_MIGRATION_URL`. No Vercel environment holds it. -For the commit at the tip of `main`, the job does three things in order: +Whatever commit started a run, the job checks out the tip of `main` as it stands when the run starts, then does three things in order: 1. It applies the pending migrations, then `scripts/exomem-cloud-grants.sql`. -2. It records a schema release for the commit in `schema_releases`, with status `released`. -3. It records each earlier commit that has no row as `superseded`. +2. It records a schema release for the tip in `schema_releases`, with status `released`. +3. It records each earlier commit of the tip's history that has no row as `superseded`. -A job for a commit that is not the tip applies nothing. The concurrency group lets one run proceed at a time and never cancels a running one. +Just before step 1, the job reads the tip once more. When `main` moved during the install, it applies nothing, and the run that the new push started applies the new tip. The concurrency group lets one run proceed at a time and never cancels a running one. It keeps only the newest waiting run, so a restart of an old run can replace the waiting run of a newer push. That run releases the newer tip. **The build.** `package.json`'s `vercel-build` script runs `scripts/wait-for-schema-release.ts` before `next build`. A production build reads the row for its own commit through the web app's database role: @@ -193,8 +193,8 @@ A production build that carries no commit identifier fails. A failed build leave **A job that fails.** Each migration runs in one transaction with a lock timeout of five seconds. A migration that meets its lock timeout, or a deadlock with a flow that writes in another order, fails the job and records no release. Nothing stays half applied, and the build fails after its wait. 1. Open the failed run in the repository's "Actions" tab. -2. Select "Re-run failed jobs". The job tests the tip again, so it applies only the tip of `main`. -3. Wait for the job to end. The expected result is a green run and a `released` row for the commit. +2. Select "Re-run failed jobs". The job takes the tip of `main` again, whatever commit the failed run was for. +3. Wait for the job to end. The expected result is a green run and a `released` row for the tip of `main`. 4. If the merge commit's production build already failed, open it in Vercel and select "Redeploy". The expected result is a build that reads the `released` row and deploys. Step 4 is needed because nothing rebuilds a build that failed after its 15-minute wait. @@ -209,7 +209,7 @@ Find the long transaction that holds that lock before you start the job again. 3. Install the dependencies without install scripts: `npm ci --ignore-scripts`. 4. Hold the connection string in this shell only: `read -rs DATABASE_MIGRATION_URL && export DATABASE_MIGRATION_URL`. Paste it, then press Enter. 5. List the pending migrations: `npx tsx scripts/migrate.ts --dry`. The expected result is the list, and `[migrate] --dry: not applying`. -6. Print the superseded commits: `scripts/schema-release-plan.sh `. The expected result is `tip=true` and a `superseded=` list. +6. Print the superseded commits: `scripts/schema-release-plan.sh`. The expected result is `apply=true`, `tip=` with the hash from step 2, and a `superseded=` list. 7. Apply and record: `npx tsx scripts/migrate.ts --commit --superseded `. The expected result is `[migrate] applying grants ... ok`, then `[migrate] recorded release ` and the count of superseded commits. 8. Clear the credential: `unset DATABASE_MIGRATION_URL`. diff --git a/migrations/0101_exomem_identity_lock_and_schema_releases.sql b/migrations/0101_exomem_identity_lock_and_schema_releases.sql index 2003ecee..1be500ff 100644 --- a/migrations/0101_exomem_identity_lock_and_schema_releases.sql +++ b/migrations/0101_exomem_identity_lock_and_schema_releases.sql @@ -141,6 +141,11 @@ CREATE TABLE schema_releases ( recorded_at timestamptz NOT NULL DEFAULT now() ); +-- The build's wait script reads the newest released commit on every poll, so +-- the read walks this index and scans no rows. +CREATE INDEX schema_releases_newest_released_idx + ON schema_releases (recorded_at DESC) WHERE status = 'released'; + CREATE TRIGGER schema_releases_owner_only AFTER INSERT OR UPDATE OR DELETE ON schema_releases FOR EACH ROW EXECUTE FUNCTION exomem_refuse_unless_schema_owner(); diff --git a/migrations/0102_exomem_issuance_log_and_download_tickets.sql b/migrations/0102_exomem_issuance_log_and_download_tickets.sql index 9c838dcd..639c2e74 100644 --- a/migrations/0102_exomem_issuance_log_and_download_tickets.sql +++ b/migrations/0102_exomem_issuance_log_and_download_tickets.sql @@ -147,8 +147,10 @@ BEGIN the_expiry timestamptz; BEGIN -- The end of a credential: the revocation or the delete of its row. The record - -- takes the database clock, not the row's revoked_at, which the web app's role - -- writes and could set in the past to bring the prune forward. A revocation + -- takes the database clock's statement time, not the row's revoked_at, which the + -- web app's role writes and could set in the past to bring the prune forward. + -- The statement time, not now(), so that retention runs from the revoking or + -- deleting statement and not from the start of a long transaction. A revocation -- is one-way, so it cannot end a live credential's record early. A record keeps -- an end that is already in the past. Each kind has its own statement, with -- the kind as a literal, because only a literal lets the planner use that @@ -156,14 +158,14 @@ BEGIN IF TG_OP <> 'INSERT' THEN IF kind = 'service_credential' THEN UPDATE %1$I.exomem_cloud_issuance_log AS record - SET expires_at = pg_catalog.now() + SET expires_at = pg_catalog.statement_timestamp() WHERE record.credential_kind = 'service_credential' AND record.credential_id = OLD.id AND record.expires_at IS NULL; ELSIF kind = 'token_family' THEN UPDATE %1$I.exomem_cloud_issuance_log AS record - SET expires_at = pg_catalog.now() + SET expires_at = pg_catalog.statement_timestamp() WHERE record.credential_kind = 'token_family' - AND record.credential_id = OLD.id AND record.expires_at > pg_catalog.now(); + AND record.credential_id = OLD.id AND record.expires_at > pg_catalog.statement_timestamp(); END IF; RETURN NULL; END IF; @@ -239,7 +241,7 @@ BEGIN -- function runs as the role that changes the cell, not as the schema owner. Only -- the web app's role changes a cell's desired state, and it holds update on the -- revocation column, so the function needs no owner rights. It sets the - -- revocation time from the database clock and leaves the revoking principal + -- revocation time from the statement's clock and leaves the revoking principal -- empty, because no operator revoked the credential. The existing trigger on the -- credential table then ends its record. It names the tenant only, because one -- index allows a single non-deleted cell for each tenant, so no other live cell @@ -251,7 +253,7 @@ BEGIN AS $body$ BEGIN UPDATE %1$I.exomem_cloud_service_credentials AS credential - SET revoked_at = pg_catalog.now() + SET revoked_at = pg_catalog.statement_timestamp() WHERE credential.tenant_id = OLD.tenant_id AND credential.revoked_at IS NULL; RETURN NULL; END; diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md index dd68f907..8e572ab4 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md @@ -198,7 +198,7 @@ Other points: **What the migrations lock.** Creating a trigger locks its table against inserts, updates and deletes until the commit. Reads continue, the gateway's lookups included. The change ships two migrations, so that the longer one locks fewer tables: - The first adds `schema_releases` and the guards, and pins the functions' paths. It locks users, tenants, cells, reviewer credentials, clients, grants, token families, refresh tokens, access tokens and service credentials. It changes only the catalog, so it commits soon after it holds the last lock. -- The second adds the log, the ticket table, the recording triggers, the cell trigger of D6 and the records for existing rows. It locks cells, token families, refresh tokens, access tokens and service credentials until it has written those records. Code exchange, refresh, the Home mint, token revocation, service credential requests, cell changes and the maintenance wait for it. Its length grows with the rows that the backfill writes, not with the size of the tables: a row whose record the prune would delete is skipped. Task 7.4 gives the query that counts those rows, with the backfill's own predicate. +- The second adds the log, the ticket table, the recording triggers, the cell trigger of D6 and the records for existing rows. It locks cells, token families, refresh tokens, access tokens and service credentials until it has written those records. Code exchange, refresh, the Home mint, token revocation, service credential requests, cell changes and the maintenance wait for it. Its length grows with the rows that its backfill reads, which are the full token family, access token, refresh token and service credential tables, because no expiry index covers every retained row: the refresh token index covers only unconsumed rows. The rows that it writes add to that. The migration runs once, against today's data, so task 7.4's query counts the rows that each read scans, and the window and the go/no-go use that count. - Each migration takes all its locks first, with one `LOCK TABLE` statement in the mode that creating a trigger takes. PostgreSQL takes them one at a time, in the order listed above, and the second migration takes cells first: a cell's change writes the service credentials after it, through the trigger of D6. Admission writes users before tenants, and every revocation and issuance writes grants, then token families, then tokens, in that order. Three flows write in another order: cell deletion writes the OAuth tables, then tenants, then users, deletion finish writes tenants before users, and the lifecycle sweep writes a cell before its tenant. Any of them can deadlock with the first migration, and PostgreSQL then fails one of the two transactions. The reconcile job runs both flows every minute (`ops/exomem-hosted-schedules.json`), so a failed deletion step runs again a minute later. A deadlock fails the migration's job like a lock timeout does, and the operator starts the job again. A service credential request locks the tenant, then the cell through D6's trigger. That is the order of deletion finish, which waits for the request on the tenant, and the reverse of the lifecycle sweep. If the sweep and a request for the same tenant overlap, they can deadlock, and PostgreSQL fails one of them. The sweep runs again a minute later. A request that PostgreSQL fails answers 503 `SERVICE_CREDENTIAL_RETRY` with `Retry-After: 3`, and the operator sends it again. - Each migration sets a lock timeout of five seconds. Without one, its lock request would wait behind any long transaction, and every later write would wait behind the request. The timeout bounds each wait, not the migration. While the migration waits for one lock, it holds every lock that it took before, and new writes to the table it waits for queue behind its request. In the worst case, a write to users waits through all nine waits of the first migration, about 45 seconds, before that migration commits or fails. When a wait times out, the migration fails, the job fails, and a later run tries again. - If the second migration fails, the guards are in force without the log. No flow depends on the log, and a later run adds it. @@ -288,13 +288,14 @@ The download ticket's own requirements live in the active change `add-cloud-medi A new workflow runs on every push to `main` and by hand. It runs in a protected environment whose branch rule accepts only `main`. The schema-owner connection string is that environment's secret. The job: -1. Checks that its commit is the tip of `main`. If it is not, the job applies nothing. It records the commit as superseded, unless the commit already has a row. -2. Runs `scripts/migrate.ts`, which applies the pending migrations and then the grants script. -3. Records a schema release for its commit. It records as superseded the commit's first-parent ancestors, up to 100, that have no row. An ancestor that already has a row keeps it. A gap longer than 100 commits leaves its oldest commits without a row, and a build of one of them fails after its wait. +1. Checks out the tip of `main` as it stands when the run starts, whatever commit started the run, and installs its dependencies. +2. Reads the tip once more, after the install and just before it applies. If `main` moved in between, the job applies nothing: the push that moved it started a run of its own, which applies the new tip. +3. Runs `scripts/migrate.ts`, which applies the pending migrations and then the grants script. +4. Records a schema release for the tip. It records as superseded the tip's first-parent ancestors, up to 100, that have no row. An ancestor that already has a row keeps it. A gap longer than 100 commits leaves its oldest commits without a row, and a build of one of them fails after its wait. `schema_releases` holds one row for each commit, with a status of `released` or `superseded`. A row is written once and never changes: the job inserts and never updates. A restarted run of a released commit therefore leaves it released. A guard refuses every write to the table unless the schema owner runs it, and the web app's role holds select only. -A concurrency group lets one run proceed at a time and keeps only the newest waiting run. A dry run stays outside the group. It changes nothing, and inside the group it would displace the waiting run. The tip check stops a restarted old run from applying an older grants script. +A concurrency group lets one run proceed at a time and keeps only the newest waiting run. A restart of an old run can therefore replace the waiting run of a newer push. That is safe because every run releases the tip, not its own commit: the replacing run releases the newer commit, and a build of that commit finds its row. A dry run stays outside the group. It changes nothing, and inside the group it would displace the waiting run. Releasing the tip stops a restarted old run from applying an older grants script. The rule needs a run for every push to `main`, so the trigger has no path filter, and a test holds that. The group's `queue: max` setting would keep every waiting run in order, but a burst of pushes would then run one install after another before the newest tip, and a full queue cancels the newest run. The single waiting slot with a tip that each run resolves loses no push and runs fewer installs. `scripts/migrate.ts` records a schema release only when its caller names a commit, as a full 40-character hash. The workflow names its own. A local run, the test job and the end-to-end job name none and record nothing. An operator's run by hand names the commit it applies. @@ -305,7 +306,7 @@ A concurrency group lets one run proceed at a time and keeps only the newest wai - Every action is pinned to a commit, not to a tag. - The environment has no required reviewer. The operator already authorises each merge, and a second click would add a wait without a second person. -Who starts a run does not matter. A run can only apply the tip of `main`: the branch rule refuses other branches, and the tip check refuses older commits. What matters is which code a run executes, and who can change the rules. A test holds the first rule below, and the rollout reads the others: +Who starts a run does not matter. A run can only apply the tip of `main`: the branch rule refuses other branches, and the job checks out the tip whatever commit started it. What matters is which code a run executes, and who can change the rules. A test holds the first rule below, and the rollout reads the others: - **Only this workflow names the environment, and it starts only on a push to `main` or by hand.** A run that starts on `pull_request_target` or `workflow_run` carries `main` as its ref, so the branch rule accepts it. Such a run can check out a pull request's code. No workflow does so today, and a test that reads the workflow files keeps it so. When that test fires wrongly, a new workflow that needs the environment or another event fails CI until the test names it. Its author pays one reviewed edit. - **The ruleset on `main` names no bypass actor.** A bypass actor could push a commit that the merge queue never checked, and the job would run it with the credential. @@ -367,9 +368,9 @@ A log that nobody can read cheaply proves nothing. Two readers exist, and each o - rights that the web app's role holds on the log, `schema_releases`, ticket rows and, table-wide, the locked tables beyond what the grants script gives it; - create rights that a role other than a superuser, the schema owner or `pg_database_owner` holds on the database or on a schema outside `pg_catalog` and `information_schema`, and schemas that a role other than the schema owner, the bootstrap superuser or `pg_database_owner` owns. -The first check also reads the credential tables in full. It filters their rows by `created_at`, and none of the five tables has an index on that column. A consumed refresh token of an unexpired family stays in its table, so the tables hold more than the live credentials. The read grows with those tables, not with the range of the log. The operator runs it on demand (limit 13), not on a schedule. A scheduled version needs an index on `created_at` or a different query, which is a later step. The migration writes no record for a row whose record the prune would delete (D5), so the check ignores rows from before the release. The first run starts at the release time, which is the `recorded_at` of the log's first record, and not at the start of time. That time is the migration's time when the backfill wrote any record. The check then flags no skipped row. The last five read the catalog. +The first check also reads the credential tables in full. It filters their rows by `created_at`, and none of the five tables has an index on that column. A consumed refresh token of an unexpired family stays in its table, so the tables hold more than the live credentials. The read grows with those tables, not with the range of the log. The operator runs it on demand (limit 13), not on a schedule. A scheduled version needs an index on `created_at` or a different query, which is a later step. The record of a credential that is less than 90 days old exists, because the prune deletes a record 90 days after its credential ends and a credential ends after it is created. So the check lists only credentials created in the last 90 days, and never before the install time of the second migration. The audit role cannot read `schema_migrations`, so the operator reads that time once, as the schema owner, and passes it to every run. A credential older than 90 days is not checked, because its record may be gone. That includes a service credential that is still live. Widening the audit role's column grant to the credential's expiry and revocation time would bring such a credential back; this change does not. The last five read the catalog. -**Late commits.** PostgreSQL assigns a record's identifier at insert, not at commit. A record can therefore commit after a check has read past its identifier. Each run starts one hour of records before the point where the previous run stopped, so the next run reads such a record. It finds that start by walking back through the primary key from the nearest record at or below the previous stop that still exists, because the prune can delete the record that the stop names. If none exists, every record is newer than the previous stop, and the run starts at the oldest record. The read stays bounded. A record whose transaction stayed open for longer than that hour is missed by the range checks. The read of one tenant's records still returns it. +**Late commits.** PostgreSQL assigns a record's identifier at insert, not at commit. A record can therefore commit after a check has read past its identifier. Each run starts one hour of records before the point where the previous run stopped, so the next run reads such a record. It finds that start by walking back through the primary key from the nearest record at or below the previous stop that still exists, because the prune can delete the record that the stop names. If none exists, every record is newer than the previous stop, and the run starts at the oldest record. Each run reads at most one page of identifiers: its stop is the lesser of the newest identifier and its start plus the page. The page is 100,000 by default and the operator's to change. The operator runs again from that stop until it reaches the newest identifier, so the first run on a large log, and a run after a long gap, take several passes. Each pass stays an index range on the primary key. The read stays bounded. A record whose transaction stayed open for longer than that hour is missed by the range checks. The read of one tenant's records still returns it. **One tenant's records.** An index on `tenant_id` with `id` lists one tenant's issuances, newest first, a page at a time. That is the read for an incident and for an owner who asks who held access. Without the index, it would scan the whole log. @@ -395,7 +396,7 @@ The claim is: the database records every credential that the gateway admits from - **A flow that the inventory missed changes a fixed column.** → It fails in production from the merge, because the lock has no switch. The proof runs every flow in the inventory as the web app's role. The schema owner's emergency statement restores the flow, and a commit makes the fix durable. - **The recording trigger fails in production.** → Every token insert fails. The proof runs each insert path through the trigger, and the runbook names the statement that disables it. Disabling it suspends the claim, and the runbook says so. -- **The second migration blocks writes to five tables while it writes the older rows' records.** → Token issue, refresh, the Home mint, revocation and cell changes wait for that transaction (D5). Its length grows with the rows that the backfill writes. The rollout reads that count before the merge, with the query of task 7.4. +- **The second migration blocks writes to five tables while it writes the older rows' records.** → Token issue, refresh, the Home mint, revocation and cell changes wait for that transaction (D5). Its length grows with the rows that its backfill reads. The rollout reads that count before the merge, with the query of task 7.4. - **A migration meets its lock timeout or a deadlock.** → The job fails and records no schema release, so the build does not deploy. The operator starts the job again. If the production build already failed after its 15-minute wait, the operator redeploys it once the job is green, because nothing rebuilds it. - **A hand-typed grant gives a role the trigger right.** → The lock does not hold against that role until the grants script runs again. The runbook's checks list the grant. - **A hand-typed grant gives a role other than the owner a create right.** → The role may then reach code that runs as the schema owner (D2). The grants script does not revoke the right. The runbook's checks list the right and any schema the role created, and the operator revokes the right and drops the schema. diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md index 85d19525..e7095568 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md @@ -300,7 +300,7 @@ An issuance record SHALL be kept until at least 90 days after its credential exp ### Requirement: The issuance log is read in bounded ranges, without the schema-owner credential -A read-only audit role SHALL hold select on the issuance log and on the columns that its checks compare, and no other right. Each documented read of the log SHALL cover a bounded range of records. The check for credential rows without a record SHALL also read the credential tables in full, and the operator SHALL run it on demand, from the release time on its first run. A reader SHALL be able to list one tenant's records a page at a time through an index. +A read-only audit role SHALL hold select on the issuance log and on the columns that its checks compare, and no other right. Each documented read of the log SHALL cover a bounded range of records. The check for credential rows without a record SHALL also read the credential tables in full, and the operator SHALL run it on demand. A reader SHALL be able to list one tenant's records a page at a time through an index. #### Scenario: The audit role reads the log @@ -312,6 +312,13 @@ A read-only audit role SHALL hold select on the issuance log and on the columns - **WHEN** the operator runs a documented check over a range of record identifiers - **THEN** the check reads that range of the log through the primary key and no other record of the log +- **AND** the range holds at most one page of identifiers, and the operator repeats the run from its stop until the range reaches the newest identifier + +#### Scenario: The credential check lists only credentials that must have a record + +- **WHEN** the operator runs the check for credential rows without a record +- **THEN** it lists only credentials created in the last 90 days and after the second migration was applied +- **AND** a credential older than 90 days is not listed, because the prune may have deleted its record, and that includes a live service credential #### Scenario: A record commits late diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/substrate-database-releases/spec.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/substrate-database-releases/spec.md index 0fc58bf6..86ad5554 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/substrate-database-releases/spec.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/substrate-database-releases/spec.md @@ -2,7 +2,7 @@ ### Requirement: Production migrations run from a protected job outside the web deployment -Production migrations and the grants script SHALL run from a continuous-integration job in a protected environment that accepts only the default branch. That environment SHALL be the only automated holder of the schema-owner credential. The job SHALL apply only the tip of the default branch, one run at a time. It SHALL record a schema release for its commit only after the migrations and the grants script succeed. +Production migrations and the grants script SHALL run from a continuous-integration job in a protected environment that accepts only the default branch. That environment SHALL be the only automated holder of the schema-owner credential. The job SHALL apply only the tip of the default branch, one run at a time, whatever commit started the run. It SHALL record a schema release for that tip only after the migrations and the grants script succeed. #### Scenario: A commit lands on the default branch @@ -22,13 +22,19 @@ Production migrations and the grants script SHALL run from a continuous-integrat #### Scenario: A run starts for a commit that is no longer the tip - **WHEN** a run starts, or someone restarts one, and its commit is no longer the tip of the default branch -- **THEN** the job applies nothing -- **AND** it records that commit as superseded, unless the commit already has a row +- **THEN** the job applies the tip of the default branch as it stands when the run starts, and records that tip as released +- **AND** it records the tip's first-parent ancestors, up to 100, that have no row as superseded -#### Scenario: A released commit's run is restarted +#### Scenario: A restarted run replaces the waiting run of a newer push -- **WHEN** someone restarts the run of a commit that is recorded as released and is no longer the tip -- **THEN** the job applies nothing and the commit stays released +- **WHEN** someone restarts the run of an older commit while the run of a newer push waits, and the restarted run replaces the waiting one +- **THEN** the restarted run releases the newer tip, and no push stays without a release + +#### Scenario: The default branch moves while the job installs + +- **WHEN** a push lands after the job started and before it applies +- **THEN** the job reads the tip once more just before it applies, finds that it moved, and applies nothing +- **AND** the run that the push started applies the new tip #### Scenario: A recorded commit never changes @@ -39,12 +45,12 @@ Production migrations and the grants script SHALL run from a continuous-integrat - **WHEN** a second commit lands while the job runs for the first - **THEN** the runs do not overlap, and the later commit's run applies last -- **AND** that run records as superseded the commit's first-parent ancestors, up to 100, that have no row +- **AND** that run records as superseded the tip's first-parent ancestors, up to 100, that have no row #### Scenario: The operator runs the job by hand - **WHEN** the operator starts the job for the default branch as a dry run -- **THEN** the job lists the pending migrations and changes nothing +- **THEN** the job lists the pending migrations of the tip and changes nothing, and it takes no migration lock and creates no table, so an empty database stays empty - **AND** it neither cancels nor replaces a run that applies migrations #### Scenario: A migration cannot take its lock diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md index dec873f5..5ae4f95d 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md @@ -18,22 +18,28 @@ names each decision as D1 to D12. - [x] 1.2 In `scripts/migrate.ts`, accept a commit and a list of superseded commits, each as a full 40-character hash. With a commit, record its schema release after the grants script succeeds, and record each listed commit as - superseded. Record with an insert that leaves an existing row unchanged. Add - a mode that only records commits as superseded. Verify on a disposable - PostgreSQL: a successful run with a commit records the release. A failed - migration, a failed grants script, a dry run and a run with no commit record - none. A commit that already has a row keeps its status. A malformed commit - fails before the runner connects. + superseded. Record with an insert that leaves an existing row unchanged. A dry + run takes no migration lock and creates no table, and an absent tracking + table counts as an empty applied set. Verify on a disposable PostgreSQL: a + successful run with a commit records the release. A failed migration, a + failed grants script, a dry run and a run with no commit record none. A + commit that already has a row keeps its status. A malformed commit fails + before the runner connects. A dry run on an empty schema leaves it empty, + while another session holds the migration lock. - [x] 1.3 Add the migration workflow under `.github/workflows/`. It starts on a push to `main` and by hand, in the protected environment, with a dry-run input. It has a concurrency group that never cancels a running job, and a - dry run stays outside that group. It has the tip-of-`main` check. It lists - the superseded commits from the checkout's history. Only the migrate step + dry run stays outside that group. It checks out the tip of `main` whatever + commit started the run. After the install, and just before the migrate + step, it reads the tip again and applies nothing when `main` moved. It lists + the tip's superseded ancestors from the checkout's history. Only the migrate step receives the secret. Dependencies install with `npm ci --ignore-scripts`. Every action is pinned to a commit. Add a test that reads the workflow files: only this workflow names the protected environment, and it starts on - no other event. Verify: in a scratch clone, the tip check passes at the tip - and stops one commit behind it. After an install without scripts, a dry run + no other event, and with no path filter on the push. Verify: in a scratch + clone, the tip check applies at the tip and stops once `main` has moved on. + On a scratch remote, a run that an older commit started releases the newer + tip and records the older commit as superseded. After an install without scripts, a dry run of `scripts/migrate.ts` succeeds. The test fails when a second workflow names the environment. The reviewer reads the three hardening properties in the diff. @@ -336,23 +342,28 @@ and its date. and no right to set `session_replication_role`. No role but the owner holds the trigger right on any table in the schema. Production runs the same PostgreSQL major version as CI, so the foreign-key test of D2 holds there. - Read the count of rows that the second migration's backfill will write, - which sets how long it blocks writes to the cell, token and service - credential tables. The query repeats the backfill's own predicate: a row - counts when the end that its record would take is empty or at most 90 days - old. + Read the count of rows that each of the second migration's backfill reads + scans, which are the full source tables: this migration runs once, against + today's data. That count sets how long the migration blocks writes to the + cell, token and service credential tables, and the go/no-go uses it. The + query also counts the rows that each backfill writes, by the backfill's own + predicate: a row counts when the end that its record would take is empty or + at most 90 days old. ```sql - SELECT - (SELECT count(*) FROM exomem_oauth_token_families AS family - WHERE CASE WHEN family.revoked_at IS NOT NULL - THEN least(family.expires_at, now()) ELSE family.expires_at END - >= now() - interval '90 days') AS token_families, - (SELECT count(*) FROM exomem_oauth_access_tokens - WHERE expires_at >= now() - interval '90 days') AS access_tokens, - (SELECT count(*) FROM exomem_oauth_refresh_tokens - WHERE expires_at >= now() - interval '90 days') AS refresh_tokens, - (SELECT count(*) FROM exomem_cloud_service_credentials) AS service_credentials; + SELECT 'token_families' AS source, count(*) AS rows_read, + count(*) FILTER (WHERE CASE WHEN family.revoked_at IS NOT NULL + THEN least(family.expires_at, now()) ELSE family.expires_at END + >= now() - interval '90 days') AS rows_written + FROM exomem_oauth_token_families AS family + UNION ALL SELECT 'access_tokens', count(*), + count(*) FILTER (WHERE expires_at >= now() - interval '90 days') + FROM exomem_oauth_access_tokens + UNION ALL SELECT 'refresh_tokens', count(*), + count(*) FILTER (WHERE expires_at >= now() - interval '90 days') + FROM exomem_oauth_refresh_tokens + UNION ALL SELECT 'service_credentials', count(*), count(*) + FROM exomem_cloud_service_credentials; ``` Create the audit role as the schema owner or another role diff --git a/scripts/migrate.ts b/scripts/migrate.ts index e90e1985..bf8cba6a 100644 --- a/scripts/migrate.ts +++ b/scripts/migrate.ts @@ -15,15 +15,16 @@ * A caller that names a commit (`--commit `) also records that commit's * schema release once the migrations and the grants script have succeeded, and * records each commit of `--superseded ` as superseded. A run that - * names no commit records nothing. `--record-superseded` records the listed - * commits and applies nothing; the release job uses it for a run whose commit - * is no longer the tip of the default branch. + * names no commit records nothing. + * + * A dry run only reads. It takes no migration lock and creates no table, so it + * lists every migration as pending on a database that has none applied, and + * leaves that database empty. * * Usage: * tsx scripts/migrate.ts # apply pending migrations * tsx scripts/migrate.ts --dry # list pending migrations without applying * tsx scripts/migrate.ts --commit [--superseded ] - * tsx scripts/migrate.ts --record-superseded --superseded */ import { existsSync, readFileSync, readdirSync } from "node:fs"; @@ -33,8 +34,8 @@ import { Client, type ClientBase } from "pg"; const DEFAULT_MIGRATIONS_DIR = resolve(process.cwd(), "migrations"); const DEFAULT_GRANTS_FILE = resolve(process.cwd(), "scripts/exomem-cloud-grants.sql"); -const MIGRATION_LOCK_NAMESPACE = 0x45584f4d; // "EXOM" -const MIGRATION_LOCK_ID = 0x454d; // "EM" +export const MIGRATION_LOCK_NAMESPACE = 0x45584f4d; // "EXOM" +export const MIGRATION_LOCK_ID = 0x454d; // "EM" const RELEASE_A_MIGRATION = "0040_backup_version_commit.sql"; type Sql = Pick; @@ -93,6 +94,10 @@ async function ensureTrackingTable(sql: Sql): Promise { } async function getAppliedVersions(sql: Sql): Promise> { + // A dry run reaches here without the tracking table on a database that no + // migration has touched: nothing is applied there. + const present = await sql.query("SELECT to_regclass('schema_migrations') IS NOT NULL AS present"); + if (!(present.rows[0] as { present: boolean }).present) return new Set(); const { rows } = await sql.query<{ version: string }>("SELECT version FROM schema_migrations"); return new Set((rows as Array<{ version: string }>).map((r) => r.version)); } @@ -196,8 +201,7 @@ async function recordSchemaReleases( superseded: readonly string[] ): Promise { if ((await sql.query("SELECT to_regclass('schema_releases') AS name")).rows[0]?.name === null) { - // A stale run can reach a database that migration 0101 has not reached yet. - // No release can exist there, so there is nothing to supersede. + // A commit from before migration 0101 has no table to record in. console.log("[migrate] schema_releases does not exist yet; nothing to record"); return; } @@ -251,8 +255,6 @@ export async function applyMigrations( commit?: string; /** Commits that a newer schema release overtook; recorded as superseded. */ supersededCommits?: readonly string[]; - /** Records `supersededCommits` and applies nothing. */ - recordSupersededOnly?: boolean; } = {} ): Promise { const { @@ -264,26 +266,22 @@ export async function applyMigrations( // A malformed commit fails before the runner connects. if (opts.commit !== undefined) assertCommitHash(opts.commit, "commit"); for (const commit of supersededCommits) assertCommitHash(commit, "superseded commit"); - if (opts.recordSupersededOnly && (opts.commit !== undefined || supersededCommits.length === 0)) { - throw new Error("recording superseded commits takes a list of them and no commit"); - } const client = getClient(opts.databaseUrl); await client.connect(); let locked = false; try { - if (opts.recordSupersededOnly) { - await recordSchemaReleases(client, undefined, supersededCommits); - return; - } // A session lock is held on this dedicated connection across the applied // version recheck and every per-file transaction. A crashed runner drops - // the connection and releases it automatically. - await client.query("SELECT pg_advisory_lock($1, $2)", [ - MIGRATION_LOCK_NAMESPACE, - MIGRATION_LOCK_ID, - ]); - locked = true; - await ensureTrackingTable(client); + // the connection and releases it automatically. A dry run writes nothing, + // so it needs neither the lock nor the tracking table. + if (!dry) { + await client.query("SELECT pg_advisory_lock($1, $2)", [ + MIGRATION_LOCK_NAMESPACE, + MIGRATION_LOCK_ID, + ]); + locked = true; + await ensureTrackingTable(client); + } const applied = await getAppliedVersions(client); const all = listMigrationFiles(migrationsDir); const pending = all.filter((name) => !applied.has(name)); @@ -369,7 +367,6 @@ if (process.argv[1] === fileURLToPath(import.meta.url)) { dry: argv.includes("--dry"), commit: flagValue(argv, "--commit"), supersededCommits: flagValue(argv, "--superseded")?.split(",").filter(Boolean), - recordSupersededOnly: argv.includes("--record-superseded"), }); })().catch((err) => { console.error("[migrate] runner error:", err); diff --git a/scripts/schema-release-plan.sh b/scripts/schema-release-plan.sh index f6a62029..9522b00e 100755 --- a/scripts/schema-release-plan.sh +++ b/scripts/schema-release-plan.sh @@ -1,21 +1,26 @@ #!/usr/bin/env bash -# Decides what the schema release job does for one commit. Prints two lines for -# the job's step output: -# tip=true|false whether the commit is the tip of the default branch -# superseded= the commits that the job records as superseded +# Decides what the schema release job applies. The job checks out the tip of the +# default branch when it starts, whatever commit started the run, installs its +# dependencies, then runs this script just before it applies. Prints three lines +# for the job's step output: +# tip= the tip of the default branch now +# apply=true|false whether the checked-out commit is that tip +# superseded= the tip's recent first-parent ancestors # -# At the tip, the list holds the commit's recent first-parent ancestors. The -# migration runner records each one that has no row, so every commit that the -# previous schema release left behind gets a row, including one whose own run -# the concurrency group replaced. A commit that already has a row keeps it. -# Behind the tip, the list holds only the commit itself: it applies nothing. +# The migration runner records each listed commit that has no row as superseded, +# so every commit that the previous schema release left behind gets a row, +# including one whose own run the concurrency group replaced. A commit that +# already has a row keeps it. # -# Usage: scripts/schema-release-plan.sh [remote] [branch] +# apply=false means the default branch moved while the job installed: the job holds +# the old tip's code, and the push that moved it started a run of its own, which +# applies the new tip. +# +# Usage: scripts/schema-release-plan.sh [remote] [branch] set -euo pipefail -commit="${1:?usage: schema-release-plan.sh [remote] [branch]}" -remote="${2:-origin}" -branch="${3:-main}" +remote="${1:-origin}" +branch="${2:-main}" # A bound on the history, not data: a gap longer than this leaves its oldest # commits without a row, and a build of one of them fails after its wait. history_limit=100 @@ -23,10 +28,10 @@ history_limit=100 git fetch --quiet --no-tags "$remote" "$branch" tip="$(git rev-parse FETCH_HEAD)" -if [ "$tip" = "$commit" ]; then - echo "tip=true" - echo "superseded=$(git rev-list --first-parent --max-count="$history_limit" "$commit^" 2>/dev/null | paste -sd, -)" +echo "tip=$tip" +if [ "$tip" = "$(git rev-parse HEAD)" ]; then + echo "apply=true" else - echo "tip=false" - echo "superseded=$commit" + echo "apply=false" fi +echo "superseded=$(git rev-list --first-parent --max-count="$history_limit" "$tip^" 2>/dev/null | paste -sd, -)" diff --git a/scripts/wait-for-schema-release.ts b/scripts/wait-for-schema-release.ts index 04e9a5fb..679cb628 100644 --- a/scripts/wait-for-schema-release.ts +++ b/scripts/wait-for-schema-release.ts @@ -99,10 +99,15 @@ async function readFromDatabase(commit: string): Promise { await client.connect(); try { const { rows } = await client.query<{ status: string | null; newest_released: string | null }>( - `SELECT - (SELECT status FROM schema_releases WHERE commit_sha = $1) AS status, - (SELECT commit_sha FROM schema_releases WHERE status = 'released' - ORDER BY recorded_at DESC LIMIT 1) AS newest_released`, + // The newest released commit is read only once the build's own release exists: a poll + // that finds none pays one primary key lookup. The index on released rows serves the rest. + `SELECT own.status, + CASE WHEN own.status = 'released' THEN + (SELECT commit_sha FROM schema_releases WHERE status = 'released' + ORDER BY recorded_at DESC LIMIT 1) + END AS newest_released + FROM (SELECT $1::text AS commit_sha) AS wanted + LEFT JOIN schema_releases AS own ON own.commit_sha = wanted.commit_sha`, [commit] ); return { status: rows[0]?.status ?? null, newestReleased: rows[0]?.newest_released ?? null }; diff --git a/src/lib/exomem-hosted/__tests__/cloud-issuance-log-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-issuance-log-postgres.integration.test.ts index 94f49fd3..3c2c2cfc 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-issuance-log-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-issuance-log-postgres.integration.test.ts @@ -574,6 +574,42 @@ for (const state of STATES) { ); }); + it("ends a record at the revoking statement, not at the start of a transaction that stayed open", async () => { + const credential = await addServiceCredential(); + const family = await addFamily(); + const client = await fx.app.connect(); + let before: Date; + try { + await client.query("BEGIN"); + // The transaction clock stays at BEGIN while the statement clock moves on. + before = ( + await client.query<{ before: Date }>( + "SELECT pg_sleep(1.2), clock_timestamp() AS before" + ) + ).rows[0]!.before; + await client.query( + `UPDATE ${serviceCredentials()} SET revoked_at = now(), revoked_by_principal_digest = $2 WHERE id = $1`, + [credential, randomBytes(32)] + ); + await client.query(`UPDATE ${families()} SET revoked_at = now() WHERE id = $1`, [family]); + await client.query("COMMIT"); + } finally { + client.release(); + } + const { rows } = await fx.owner.query<{ credential_kind: string; expires_at: Date }>( + `SELECT credential_kind, expires_at FROM ${log()} + WHERE credential_id = ANY($1::uuid[]) AND credential_kind IN ('service_credential', 'token_family')`, + [[credential, family]] + ); + assert.equal(rows.length, 2); + for (const row of rows) { + assert.ok( + row.expires_at >= before!, + `the ${row.credential_kind} record ends at the revoking statement` + ); + } + }); + it("ends a token family's record when the web app's role deletes the family, and when a deleted grant cascades to it", async () => { const deleted = await addFamily(); await fx.app.query(`DELETE FROM ${families()} WHERE id = $1`, [deleted]); diff --git a/src/lib/exomem-hosted/__tests__/identity-lock-fixture.ts b/src/lib/exomem-hosted/__tests__/identity-lock-fixture.ts index b00c7fdb..d8e528ff 100644 --- a/src/lib/exomem-hosted/__tests__/identity-lock-fixture.ts +++ b/src/lib/exomem-hosted/__tests__/identity-lock-fixture.ts @@ -9,7 +9,7 @@ import { TEST_ROLE_PASSWORD } from "./test-role-password"; // as production does; substrate_app, exomem_gateway, exomem_cellctl and substrate_audit are plain // login roles with no other privilege. -export const FIXTURE_ROLES = [ +const FIXTURE_ROLES = [ "substrate_app", "exomem_cellctl", "exomem_gateway", @@ -222,7 +222,7 @@ export function randomCellId(): string { } /** A running cell row for a tenant, written as the schema owner. Returns its cell id. */ -export async function seedCell(owner: Pool, tenantId: string): Promise { +async function seedCell(owner: Pool, tenantId: string): Promise { const cellId = randomCellId(); await owner.query( "INSERT INTO exomem_cloud_cells (cell_id, tenant_id, desired_state) VALUES ($1, $2, 'running')", diff --git a/src/lib/exomem-hosted/__tests__/migration-runner.integration.test.ts b/src/lib/exomem-hosted/__tests__/migration-runner.integration.test.ts index ed50d80e..871c575c 100644 --- a/src/lib/exomem-hosted/__tests__/migration-runner.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/migration-runner.integration.test.ts @@ -4,7 +4,11 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { describe, it } from "node:test"; import { Client } from "pg"; -import { applyMigrations } from "../../../../scripts/migrate"; +import { + applyMigrations, + MIGRATION_LOCK_ID, + MIGRATION_LOCK_NAMESPACE, +} from "../../../../scripts/migrate"; const databaseUrl = process.env.EXOMEM_TEST_DATABASE_URL ?? process.env.DATABASE_URL; @@ -81,4 +85,51 @@ describe("migration runner PostgreSQL integration", { skip: !databaseUrl }, () = rmSync(directory, { recursive: true, force: true }); } }); + + it("lists pending migrations in a dry run without creating a table or waiting for the migration lock", async () => { + const schema = `migration_dry_${process.pid}_${Date.now()}`; + const admin = new Client({ connectionString: databaseUrl }); + const holder = new Client({ connectionString: databaseUrl }); + const directory = mkdtempSync(join(tmpdir(), "exomem-migrations-")); + await admin.connect(); + await holder.connect(); + try { + await admin.query(`CREATE SCHEMA "${schema}"`); + writeFileSync( + join(directory, "0001_dry_probe.sql"), + "CREATE TABLE dry_probe (id integer);\n", + "utf8" + ); + const scopedUrl = new URL(databaseUrl!); + scopedUrl.searchParams.set("options", `-c search_path=${schema}`); + // Another runner holds the migration lock for the whole dry run. + await holder.query("SELECT pg_advisory_lock($1, $2)", [ + MIGRATION_LOCK_NAMESPACE, + MIGRATION_LOCK_ID, + ]); + + const finished = applyMigrations({ + databaseUrl: scopedUrl.toString(), + migrationsDir: directory, + dry: true, + }).then(() => "done"); + const timeout = new Promise((resolve) => setTimeout(() => resolve("waiting"), 5_000)); + assert.equal(await Promise.race([finished, timeout]), "done"); + + const tables = await admin.query( + "SELECT table_name FROM information_schema.tables WHERE table_schema = $1", + [schema] + ); + assert.deepEqual(tables.rows, [], "the dry run left the empty schema empty"); + } finally { + await holder.query("SELECT pg_advisory_unlock($1, $2)", [ + MIGRATION_LOCK_NAMESPACE, + MIGRATION_LOCK_ID, + ]); + await holder.end(); + await admin.query(`DROP SCHEMA IF EXISTS "${schema}" CASCADE`); + await admin.end(); + rmSync(directory, { recursive: true, force: true }); + } + }); }); diff --git a/src/lib/exomem-hosted/__tests__/schema-release-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/schema-release-postgres.integration.test.ts index cd504eee..d99b1fc3 100644 --- a/src/lib/exomem-hosted/__tests__/schema-release-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/schema-release-postgres.integration.test.ts @@ -1,4 +1,5 @@ import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; import { randomUUID } from "node:crypto"; import { cp, mkdtemp, readdir, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; @@ -182,8 +183,8 @@ describe("schema releases PostgreSQL integration", { skip: !databaseUrl }, () => }); await applyMigrations({ databaseUrl: ownerUrl, - recordSupersededOnly: true, - supersededCommits: [SECOND, THIRD], + commit: THIRD, + supersededCommits: [SECOND], }); assert.deepEqual(await releases(), [ { commit_sha: FIRST, status: "released" }, @@ -192,15 +193,56 @@ describe("schema releases PostgreSQL integration", { skip: !databaseUrl }, () => ]); }); - it("records superseded commits with no migration, and fails a malformed commit before it connects", async () => { + it("releases the pushed tip, and marks the older commit superseded, when a run that an older commit started proceeds", async () => { await clearReleases(); - await applyMigrations({ - databaseUrl: ownerUrl, - recordSupersededOnly: true, - supersededCommits: [FIRST], - }); - assert.deepEqual(await releases(), [{ commit_sha: FIRST, status: "superseded" }]); + const root = await mkdtemp(join(tmpdir(), "schema-release-remote-")); + try { + const origin = join(root, "origin"); + const checkout = join(root, "checkout"); + const git = (cwd: string, ...args: string[]) => + execFileSync("git", args, { cwd, encoding: "utf8" }).trim(); + execFileSync("git", ["init", "--quiet", "--initial-branch=main", origin]); + git(origin, "config", "user.email", "test@example.test"); + git(origin, "config", "user.name", "test"); + const push = async (name: string) => { + await writeFile(join(origin, name), name); + git(origin, "add", name); + git(origin, "commit", "--quiet", "-m", name); + return git(origin, "rev-parse", "HEAD"); + }; + const older = await push("older"); + const newer = await push("newer"); + // The job's checkout takes the tip of main, not the commit that started the run. + execFileSync("git", ["clone", "--quiet", "--branch", "main", origin, checkout]); + const plan = Object.fromEntries( + execFileSync(join(process.cwd(), "scripts/schema-release-plan.sh"), [], { + cwd: checkout, + encoding: "utf8", + }) + .trim() + .split("\n") + .map((line) => line.split("=") as [string, string]) + ); + assert.equal(plan.apply, "true"); + + await applyMigrations({ + databaseUrl: ownerUrl, + commit: plan.tip, + supersededCommits: plan.superseded!.split(","), + }); + assert.deepEqual( + await releases(), + [ + { commit_sha: older, status: "superseded" }, + { commit_sha: newer, status: "released" }, + ].sort((a, b) => a.commit_sha.localeCompare(b.commit_sha)) + ); + } finally { + await rm(root, { recursive: true, force: true }); + } + }); + it("fails a malformed commit before it connects", async () => { // Nothing listens on this address, so only the check before connecting can answer. const unreachable = "postgresql://nobody:none@127.0.0.1:1/none"; await assert.rejects( diff --git a/src/lib/exomem-hosted/__tests__/schema-release.test.ts b/src/lib/exomem-hosted/__tests__/schema-release.test.ts index 2fc35c8c..3d0cad3c 100644 --- a/src/lib/exomem-hosted/__tests__/schema-release.test.ts +++ b/src/lib/exomem-hosted/__tests__/schema-release.test.ts @@ -119,7 +119,14 @@ const WORKFLOWS = resolve(process.cwd(), ".github/workflows"); const RELEASE_WORKFLOW = "migrate-database.yml"; const SHA_PINNED_ACTION = /^[\w.-]+\/[\w.-]+@[0-9a-f]{40}$/; -type Step = { uses?: string; run?: string; env?: Record }; +type Step = { + id?: string; + name?: string; + uses?: string; + run?: string; + with?: Record; + env?: Record; +}; type Workflow = { on: Record; jobs: Record; @@ -145,7 +152,27 @@ describe("schema release workflow", () => { ); } assert.deepEqual(Object.keys(release.on).sort(), ["push", "workflow_dispatch"]); - assert.deepEqual((release.on.push as { branches: string[] }).branches, ["main"]); + // No path filter: the job applies only the tip, so a push that started no run would never release. + assert.deepEqual(release.on.push, { branches: ["main"] }); + }); + + it("releases the tip of main whatever commit started the run, reading it again just before it applies", () => { + const steps = Object.values(release.jobs).flatMap((job) => job.steps); + const checkout = steps.find((step) => step.uses?.startsWith("actions/checkout@"))!; + assert.equal(checkout.with?.ref, "main"); + assert.ok( + !JSON.stringify(steps).includes("GITHUB_SHA") && + !JSON.stringify(steps).includes("github.sha"), + "no step names the commit that started the run" + ); + const order = (match: (step: Step) => boolean) => steps.findIndex(match); + const install = order((step) => step.run === "npm ci --ignore-scripts"); + const plan = order((step) => step.run?.includes("schema-release-plan.sh") ?? false); + const migrate = order((step) => step.run?.includes("scripts/migrate.ts") ?? false); + assert.ok( + install >= 0 && install < plan && plan < migrate, + "the tip is read after the install" + ); }); it("keeps the credential to one step, installs without scripts and pins every action", () => { @@ -171,9 +198,9 @@ describe("schema release tip check", () => { let directory: string; const git = (cwd: string, ...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8" }).trim(); - const plan = (cwd: string, commit: string) => + const plan = (cwd: string) => Object.fromEntries( - execFileSync(join(process.cwd(), "scripts/schema-release-plan.sh"), [commit], { + execFileSync(join(process.cwd(), "scripts/schema-release-plan.sh"), [], { cwd, encoding: "utf8", }) @@ -181,33 +208,36 @@ describe("schema release tip check", () => { .split("\n") .map((line) => line.split("=") as [string, string]) ); + const commitFile = (repository: string, name: string) => { + writeFileSync(join(repository, name), name); + git(repository, "add", name); + git(repository, "commit", "--quiet", "-m", name); + return git(repository, "rev-parse", "HEAD"); + }; beforeEach(() => { directory = mkdtempSync(join(tmpdir(), "schema-release-plan-")); }); afterEach(() => rmSync(directory, { recursive: true, force: true })); - it("passes at the tip with the older commits, and stops one commit behind it", () => { + it("applies the tip with its older commits, and applies nothing once main has moved on", () => { const origin = join(directory, "origin"); const clone = join(directory, "clone"); execFileSync("git", ["init", "--quiet", "--initial-branch=main", origin]); git(origin, "config", "user.email", "test@example.test"); git(origin, "config", "user.name", "test"); - const commits: string[] = []; - for (const name of ["one", "two", "three"]) { - writeFileSync(join(origin, name), name); - git(origin, "add", name); - git(origin, "commit", "--quiet", "-m", name); - commits.push(git(origin, "rev-parse", "HEAD")); - } + const commits = ["one", "two", "three"].map((name) => commitFile(origin, name)); execFileSync("git", ["clone", "--quiet", origin, clone]); - const atTip = plan(clone, commits[2]!); - assert.equal(atTip.tip, "true"); + const atTip = plan(clone); + assert.equal(atTip.tip, commits[2]); + assert.equal(atTip.apply, "true"); assert.deepEqual(atTip.superseded!.split(","), [commits[1], commits[0]]); - const behind = plan(clone, commits[1]!); - assert.equal(behind.tip, "false"); - assert.equal(behind.superseded, commits[1]); + // A push lands while the job installs: its code is no longer the tip's. + const pushed = commitFile(origin, "four"); + const moved = plan(clone); + assert.equal(moved.tip, pushed); + assert.equal(moved.apply, "false"); }); }); From 99353c58d9d9bd0c92470520d01df68f8275718a Mon Sep 17 00:00:00 2001 From: Artexis10 Date: Wed, 2 Dec 2026 16:29:45 +0000 Subject: [PATCH 24/29] Count each runbook pass from the previous stop, and cap its look-back at one page A run of the runbook's range checks set its stop to its start plus one page. The migration's backfill is one transaction, so all its records share one recorded_at and no record is an hour older. With a backfill of one page or more, the start went back to the first record, the stop equalled the previous stop, and the run never advanced. Each run now counts from the previous stop: - The look-back to a record one hour older goes back at most one page. - The stop is the lesser of the newest identifier and the previous stop plus one page, so it rises on every run while the previous stop is below the newest identifier. A run reads at most two pages. - The first check's lo_time is the time of the first record at or after the start, because the record at the start can be absent. Its window keeps the install clamp and hi_time. A pass's lo_time is at or before the previous pass's hi_time, or it is the install time, before which the check lists nothing. - The runbook says that the backfill holds no late commit, that a finding inside the overlap shows in two passes, and that the page must stay above one hour of writes, or the cap on the look-back can miss a late commit. D12, the spec scenario for a range check and task 7.6 follow. --- docs/runbooks/exomem-cloud-operations.md | 34 +++++++++++-------- .../design.md | 4 +-- .../specs/exomem-hosted-mcp-oauth/spec.md | 3 +- .../tasks.md | 3 +- 4 files changed, 26 insertions(+), 18 deletions(-) diff --git a/docs/runbooks/exomem-cloud-operations.md b/docs/runbooks/exomem-cloud-operations.md index 63f0e3f9..9096b40a 100644 --- a/docs/runbooks/exomem-cloud-operations.md +++ b/docs/runbooks/exomem-cloud-operations.md @@ -888,11 +888,11 @@ whatever the other lanes do. Connect as `substrate_audit` for every query in this section. The grants script gives that role select on the log. It also gives select on the `id` and `created_at` columns of the five credential tables, and on `id` and `owner_user_id` of `exomem_tenants`. It gives no other right. Each query below reads a range of record identifiers through the primary key. -Each run reads at most one page of record identifiers, so its cost on the log follows the page, not the size of the log. The first check also reads the credential tables in full. +Each run reads at most two pages of record identifiers, so its cost on the log follows the page, not the size of the log. The first check also reads the credential tables in full. Nothing schedules these checks. Run them on demand, and after any emergency statement. Each run starts one hour of records before -the point where the previous run stopped. A record gets its identifier when it is inserted, not when it commits, so a -record can commit after a run has read past it. The overlap lets the next run read it. A record whose transaction stayed +the point where the previous run stopped, and never more than one page before it. A record gets its identifier when it is inserted, not when it commits, so a +record can commit after a run has read past it. The overlap lets the next run read it, and lists a finding inside the overlap in both passes: it is one finding, matched by its `id`. A record whose transaction stayed open for longer than that hour is missed by the range checks. The read of one tenant's records still returns it. 1. Read the time that migration 0102 was applied, once, as the schema owner: `SELECT applied_at FROM schema_migrations WHERE version = '0102_exomem_issuance_log_and_download_tickets.sql';`. Every run takes it as `install`. The audit role cannot read `schema_migrations`. @@ -902,15 +902,18 @@ open for longer than that hour is missed by the range checks. The read of one te ```sql SELECT coalesce(max(id), 0) AS newest FROM exomem_cloud_issuance_log \gset + SELECT greatest(:prev - :page, 0) AS back \gset SELECT coalesce( (SELECT id FROM exomem_cloud_issuance_log - WHERE id <= :prev + WHERE id BETWEEN :back AND :prev AND recorded_at < (SELECT recorded_at FROM exomem_cloud_issuance_log WHERE id <= :prev ORDER BY id DESC LIMIT 1) - interval '1 hour' - ORDER BY id DESC LIMIT 1), 0) AS lo \gset - SELECT least(:newest, :lo + :page) AS hi \gset + ORDER BY id DESC LIMIT 1), :back) AS lo \gset + SELECT least(:newest, :prev + :page) AS hi \gset SELECT greatest( - coalesce((SELECT recorded_at FROM exomem_cloud_issuance_log WHERE id = :lo), '-infinity'), + CASE WHEN :lo = 0 THEN '-infinity'::timestamptz + ELSE coalesce((SELECT recorded_at FROM exomem_cloud_issuance_log + WHERE id >= :lo ORDER BY id LIMIT 1), 'infinity') END, :'install'::timestamptz, now() - interval '90 days') AS lo_time \gset SELECT CASE WHEN :hi = :newest THEN 'infinity'::timestamptz @@ -919,14 +922,16 @@ open for longer than that hour is missed by the range checks. The read of one te \echo newest=:newest hi=:hi lo=:lo ``` - `page` is the most identifiers that one run reads. It is yours to change: raise it to read more in a run, or lower it to read - less. Keep it above the number of records that the web app writes in one hour. Otherwise `lo` moves back by more than the - page, and `hi` does not rise above `prev`. + `page` is the most identifiers that one run reads past the previous stop, and the most that it reads before it. It is yours + to change: raise it to read more in a run, or lower it to read less. Keep it above the number of records that the web app + writes in one hour. Otherwise the look-back stops at one page, before the hour is covered, and a record that commits later + than that can be missed. `hi` rises above `prev` on every run while `prev` is below `newest`, so step 7 ends. The prune can delete the record that `prev` names, so `lo` anchors on the nearest record at or below `prev` that still - exists, and walks back from there through the primary key for one hour of records. If no record at or below `prev` - exists, every record in the log is newer than `prev`, and `lo` is `0`: the range then starts at the first record that - this run has not read. An empty log gives `hi=0`, and the checks that use the range return no row. + exists, and walks back from there through the primary key for one hour of records, to at most one page before `prev`. + If no record in that page is an hour older, `lo` is one page before `prev`, or `0`. The migration's backfill is one + transaction: its records carry one time and no record of the log is an hour older, so the look-back stops at the page + there, and that transaction holds no late commit. An empty log gives `hi=0`, and the checks that use the range return no row. `lo_time` and `hi_time` bound the credential rows that the first check lists. `lo_time` is never earlier than `install`. No record exists before the migration, except the backfill's, which carries the migration's time, and the backfill wrote @@ -935,7 +940,8 @@ open for longer than that hour is missed by the range checks. The read of one te than 90 days old exists. The record of an older credential may be gone. The first check does not list that credential, and that includes a service credential that is still live. `hi_time` is one hour before the record that `hi` names, and `infinity` for the last page. A credential that is newer than `hi_time` belongs to the next pass, which starts one - hour of records before `hi`. + hour of records before `hi`. `lo_time` is the time of the first record at or after `lo`. Consecutive passes leave no gap: + a pass's `lo_time` is at or before the previous pass's `hi_time`, or it is `install`, before which the check lists nothing. 5. Run the three checks. Each one is a finding when it returns a row. diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md index 8e572ab4..a740f95e 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md @@ -368,9 +368,9 @@ A log that nobody can read cheaply proves nothing. Two readers exist, and each o - rights that the web app's role holds on the log, `schema_releases`, ticket rows and, table-wide, the locked tables beyond what the grants script gives it; - create rights that a role other than a superuser, the schema owner or `pg_database_owner` holds on the database or on a schema outside `pg_catalog` and `information_schema`, and schemas that a role other than the schema owner, the bootstrap superuser or `pg_database_owner` owns. -The first check also reads the credential tables in full. It filters their rows by `created_at`, and none of the five tables has an index on that column. A consumed refresh token of an unexpired family stays in its table, so the tables hold more than the live credentials. The read grows with those tables, not with the range of the log. The operator runs it on demand (limit 13), not on a schedule. A scheduled version needs an index on `created_at` or a different query, which is a later step. The record of a credential that is less than 90 days old exists, because the prune deletes a record 90 days after its credential ends and a credential ends after it is created. So the check lists only credentials created in the last 90 days, and never before the install time of the second migration. The audit role cannot read `schema_migrations`, so the operator reads that time once, as the schema owner, and passes it to every run. A credential older than 90 days is not checked, because its record may be gone. That includes a service credential that is still live. Widening the audit role's column grant to the credential's expiry and revocation time would bring such a credential back; this change does not. The last five read the catalog. +The first check also reads the credential tables in full. It filters their rows by `created_at`, and none of the five tables has an index on that column. A consumed refresh token of an unexpired family stays in its table, so the tables hold more than the live credentials. The read grows with those tables, not with the range of the log. The operator runs it on demand (limit 13), not on a schedule. A scheduled version needs an index on `created_at` or a different query, which is a later step. The record of a credential that is less than 90 days old exists, because the prune deletes a record 90 days after its credential ends and a credential ends after it is created. So the check lists only credentials created in the last 90 days, and never before the install time of the second migration. The audit role cannot read `schema_migrations`, so the operator reads that time once, as the schema owner, and passes it to every run. A credential older than 90 days is not checked, because its record may be gone. That includes a service credential that is still live. Widening the audit role's column grant to the credential's expiry and revocation time would bring such a credential back; this change does not. Consecutive passes leave no gap: a pass's `lo_time` is at or before the previous pass's `hi_time`, or it is the install time, before which the check lists nothing. The last five read the catalog. -**Late commits.** PostgreSQL assigns a record's identifier at insert, not at commit. A record can therefore commit after a check has read past its identifier. Each run starts one hour of records before the point where the previous run stopped, so the next run reads such a record. It finds that start by walking back through the primary key from the nearest record at or below the previous stop that still exists, because the prune can delete the record that the stop names. If none exists, every record is newer than the previous stop, and the run starts at the oldest record. Each run reads at most one page of identifiers: its stop is the lesser of the newest identifier and its start plus the page. The page is 100,000 by default and the operator's to change. The operator runs again from that stop until it reaches the newest identifier, so the first run on a large log, and a run after a long gap, take several passes. Each pass stays an index range on the primary key. The read stays bounded. A record whose transaction stayed open for longer than that hour is missed by the range checks. The read of one tenant's records still returns it. +**Late commits.** PostgreSQL assigns a record's identifier at insert, not at commit. A record can therefore commit after a check has read past its identifier. Each run starts one hour of records before the point where the previous run stopped, so the next run reads such a record. It finds that start by walking back through the primary key from the nearest record at or below the previous stop that still exists, because the prune can delete the record that the stop names. The walk goes back at most one page. The backfill is one transaction, so its records share one time and none is an hour older: the walk stops at the page there, and that transaction holds no late commit. Each run counts its stop from the previous stop: the stop is the lesser of the newest identifier and the previous stop plus one page. So a run reads at most two pages of identifiers, and its stop rises above the previous stop on every run while the previous stop is below the newest identifier. The page is 100,000 by default and the operator's to change. It must stay above the records of one hour of writes, or the cap on the walk can miss a late commit. The operator runs again from each stop until it reaches the newest identifier, so the first run on a large log, and a run after a long gap, take several passes. Each pass stays an index range on the primary key. The read stays bounded. A record whose transaction stayed open for longer than that hour is missed by the range checks. The read of one tenant's records still returns it. **One tenant's records.** An index on `tenant_id` with `id` lists one tenant's issuances, newest first, a page at a time. That is the read for an incident and for an owner who asks who held access. Without the index, it would scan the whole log. diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md index e7095568..15164f8d 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md @@ -312,7 +312,8 @@ A read-only audit role SHALL hold select on the issuance log and on the columns - **WHEN** the operator runs a documented check over a range of record identifiers - **THEN** the check reads that range of the log through the primary key and no other record of the log -- **AND** the range holds at most one page of identifiers, and the operator repeats the run from its stop until the range reaches the newest identifier +- **AND** the range holds at most two pages of identifiers: the walk back from the previous stop is capped at one page, and the stop is at most one page past the previous stop +- **AND** the stop of each run is above the previous stop while that stop is below the newest identifier, so the operator reaches the newest identifier by repeating the run from each stop #### Scenario: The credential check lists only credentials that must have a record diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md index 5ae4f95d..c1249c4f 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md @@ -388,7 +388,8 @@ and its date. - [ ] 7.6 Read the log and run the flows once. Sign in, connect an app, wait for one token refresh, open Home, download a file, disconnect the app, and see one maintenance run succeed. Run the D12 checks as the audit role, the - check of the web app's rights included. Evidence: the flows add records for + check of the web app's rights included. Repeat the range checks from each + stop until the stop equals the newest identifier. Evidence: the flows add records for the test account, and the checks list nothing. A row from the rights check means that an earlier grants script ran after the job, and step 7.7 takes the right back. Run no attack against production; task 5.1 is that proof. From aa65dde0d05fdd846112cefa4171d738f51f38d7 Mon Sep 17 00:00:00 2001 From: Artexis10 Date: Wed, 2 Dec 2026 16:49:09 +0000 Subject: [PATCH 25/29] Close the recorder and range-read gaps of the issuance log The recorder gives a record its end at the insert when a service credential or a token family is inserted already revoked. Before, a service credential kept an open record that the prune never selects, and a family kept its future expiry. A PostgreSQL test covers each kind through the web app's role. The rights check now lists truncate and references on the log, at table level and on a column. The trigger right keeps its own check. The range reads change in two ways: - The credential window is exclusive at both ends. A token family and its first access token share one creation time, and the family's record can sit one identifier below the start of a pass. - The look-back has no cap in records. It walks to the nearest record that is an hour older and stops at the end of the backfill, which the operator reads once with the install time. A cap left a hole whenever an hour held more than a page of records. A pass now reads one hour of records and at most one page, so the page no longer affects what a pass finds. The no-build deploy procedure now requires a schema release for the candidate's commit or a newer one before it serves, and keeps the compatibility check for a candidate older than the newest release. D12, the range scenario of the OAuth spec and task 7.6 follow the runbook. --- docs/runbooks/exomem-cloud-operations.md | 65 ++++++++++++------- docs/runbooks/vercel-deployments.md | 22 +++++-- ...omem_issuance_log_and_download_tickets.sql | 12 ++++ .../design.md | 6 +- .../specs/exomem-hosted-mcp-oauth/spec.md | 4 +- .../tasks.md | 5 +- ...-issuance-log-postgres.integration.test.ts | 30 +++++++++ 7 files changed, 109 insertions(+), 35 deletions(-) diff --git a/docs/runbooks/exomem-cloud-operations.md b/docs/runbooks/exomem-cloud-operations.md index 9096b40a..6331e5ed 100644 --- a/docs/runbooks/exomem-cloud-operations.md +++ b/docs/runbooks/exomem-cloud-operations.md @@ -888,21 +888,29 @@ whatever the other lanes do. Connect as `substrate_audit` for every query in this section. The grants script gives that role select on the log. It also gives select on the `id` and `created_at` columns of the five credential tables, and on `id` and `owner_user_id` of `exomem_tenants`. It gives no other right. Each query below reads a range of record identifiers through the primary key. -Each run reads at most two pages of record identifiers, so its cost on the log follows the page, not the size of the log. The first check also reads the credential tables in full. +Each run reads one hour of records before the previous stop and at most one page after it, so its cost on the log follows the write rate of one hour and the page, not the size of the log. The first check also reads the credential tables in full. Nothing schedules these checks. Run them on demand, and after any emergency statement. Each run starts one hour of records before -the point where the previous run stopped, and never more than one page before it. A record gets its identifier when it is inserted, not when it commits, so a +the point where the previous run stopped, and never before the end of the backfill. A record gets its identifier when it is inserted, not when it commits, so a record can commit after a run has read past it. The overlap lets the next run read it, and lists a finding inside the overlap in both passes: it is one finding, matched by its `id`. A record whose transaction stayed open for longer than that hour is missed by the range checks. The read of one tenant's records still returns it. 1. Read the time that migration 0102 was applied, once, as the schema owner: `SELECT applied_at FROM schema_migrations WHERE version = '0102_exomem_issuance_log_and_download_tickets.sql';`. Every run takes it as `install`. The audit role cannot read `schema_migrations`. -2. Write down the value of `hi` that the previous run printed. For the first run, use `0`. -3. Start `psql` as `substrate_audit`: `psql -v prev= -v install='' -v page=100000`. -4. Find the range of this run: +2. Read the identifier of the last record that the migration backfilled, once, as the audit role. Every run takes it as `backfill_end`. The migration wrote those records before any other record could land, so they are the first records of the log. The query reads only up to the first other record, and an empty result is `0`. + + ```sql + SELECT coalesce( + (SELECT min(id) - 1 FROM exomem_cloud_issuance_log WHERE NOT backfilled), + (SELECT max(id) FROM exomem_cloud_issuance_log), 0) AS backfill_end; + ``` + +3. Write down the value of `hi` that the previous run printed. For the first run, use `0`. +4. Start `psql` as `substrate_audit`: `psql -v prev= -v install='' -v backfill_end= -v page=100000`. +5. Find the range of this run: ```sql SELECT coalesce(max(id), 0) AS newest FROM exomem_cloud_issuance_log \gset - SELECT greatest(:prev - :page, 0) AS back \gset + SELECT least(:backfill_end, :prev) AS back \gset SELECT coalesce( (SELECT id FROM exomem_cloud_issuance_log WHERE id BETWEEN :back AND :prev @@ -922,28 +930,30 @@ open for longer than that hour is missed by the range checks. The read of one te \echo newest=:newest hi=:hi lo=:lo ``` - `page` is the most identifiers that one run reads past the previous stop, and the most that it reads before it. It is yours - to change: raise it to read more in a run, or lower it to read less. Keep it above the number of records that the web app - writes in one hour. Otherwise the look-back stops at one page, before the hour is covered, and a record that commits later - than that can be missed. `hi` rises above `prev` on every run while `prev` is below `newest`, so step 7 ends. + `page` is the most identifiers that one run reads past the previous stop. It is yours to change: raise it to read more in + a run and take fewer passes, or lower it to read less. It does not affect what a run finds. `hi` rises above `prev` on every + run while `prev` is below `newest`, so step 8 ends. The prune can delete the record that `prev` names, so `lo` anchors on the nearest record at or below `prev` that still - exists, and walks back from there through the primary key for one hour of records, to at most one page before `prev`. - If no record in that page is an hour older, `lo` is one page before `prev`, or `0`. The migration's backfill is one - transaction: its records carry one time and no record of the log is an hour older, so the look-back stops at the page - there, and that transaction holds no late commit. An empty log gives `hi=0`, and the checks that use the range return no row. + exists, and walks back from there through the primary key until it finds a record that is an hour older. The walk stops + at `back`, which is `backfill_end`, or `prev` while `prev` is lower. The backfill is one transaction: its records carry one + time and none is an hour older, and that transaction holds no late commit. A run that starts past the backfill reads at most the + backfill's last record, and the walk reads one hour of records at most. An empty log gives `hi=0`, and the checks + that use the range return no row. - `lo_time` and `hi_time` bound the credential rows that the first check lists. `lo_time` is never earlier than `install`. No + `lo_time` and `hi_time` bound the credential rows that the first check lists, and both ends are exclusive. `lo_time` is never earlier than `install`. No record exists before the migration, except the backfill's, which carries the migration's time, and the backfill wrote none for a row that ended more than 90 days before. `lo_time` is also never earlier than 90 days ago. The prune deletes a record 90 days after its credential ends, and a credential ends after it is created, so the record of a credential that is less than 90 days old exists. The record of an older credential may be gone. The first check does not list that credential, and that includes a service credential that is still live. `hi_time` is one hour before the record that `hi` names, and `infinity` for the last page. A credential that is newer than `hi_time` belongs to the next pass, which starts one - hour of records before `hi`. `lo_time` is the time of the first record at or after `lo`. Consecutive passes leave no gap: - a pass's `lo_time` is at or before the previous pass's `hi_time`, or it is `install`, before which the check lists nothing. + hour of records before `hi`. `lo_time` is the time of the first record at or after `lo`. A credential created at + `lo_time` is not listed, because its record can sit just below `lo`: a token family and its first access token, minted + together, share that time. Consecutive passes leave no gap: a pass's `lo_time` is strictly before the previous pass's + `hi_time`, or it is `install` or the 90-day edge, before which the check lists nothing. -5. Run the three checks. Each one is a finding when it returns a row. +6. Run the three checks. Each one is a finding when it returns a row. Credential rows without a record. One statement reads the credential rows and the log, so a credential and its record are both visible or both absent. A row here has no record. It reads the log from `lo` to `hi`. It reads @@ -951,6 +961,10 @@ open for longer than that hour is missed by the range checks. The read of one te unexpired family stays in its table. Run it on demand, never from a schedule. A scheduled version needs an index on `created_at` or a different query, which is a later step. + A row has one exception. Suppose the transaction that wrote the record at `lo` stayed open while another credential was + created. Then that credential's record can sit just below `lo`. Before you act on a row, look its record up with + `SELECT id FROM exomem_cloud_issuance_log WHERE credential_id = ''`. + ```sql SELECT created.kind, created.id, created.created_at FROM ( @@ -960,7 +974,7 @@ open for longer than that hour is missed by the range checks. The read of one te UNION ALL SELECT 'service_credential', id, created_at FROM exomem_cloud_service_credentials UNION ALL SELECT 'download_ticket', id, created_at FROM exomem_cloud_download_tickets ) AS created - WHERE created.created_at >= :'lo_time' AND created.created_at < :'hi_time' + WHERE created.created_at > :'lo_time' AND created.created_at < :'hi_time' AND NOT EXISTS ( SELECT 1 FROM exomem_cloud_issuance_log AS record WHERE record.id BETWEEN :lo AND :hi @@ -989,8 +1003,8 @@ open for longer than that hour is missed by the range checks. The read of one te WHERE record.id BETWEEN :lo AND :hi AND record.user_id <> tenant.owner_user_id; ``` -6. Write down the value of `hi` as the stop of this run. The next run takes it as `prev`. -7. If `hi` is below `newest`, the log holds records that this run did not read. Run again with `prev` set to this `hi`, until +7. Write down the value of `hi` as the stop of this run. The next run takes it as `prev`. +8. If `hi` is below `newest`, the log holds records that this run did not read. Run again with `prev` set to this `hi`, until `hi` equals `newest`. The first run on a large log, and a run after a long gap, take several passes. The expected result is a last pass that prints `hi` equal to `newest`. @@ -1087,7 +1101,8 @@ production build that was in flight at the merge, or a redeploy of an earlier co applies no grants. Each row is a right that the role must not hold, whether it holds the right itself or through `PUBLIC` or a membership: -- any right on the log, or on the sequence that numbers its records; +- any right on the log, at table level or on a column: select, insert, update, delete, truncate or references. The trigger right has its own check above; +- any right on the sequence that numbers the log's records; - insert, update or delete on `schema_releases`, where the role keeps select; - update of a ticket row, where the role keeps select, insert and delete; - delete on a table whose rows the role never deletes; @@ -1102,11 +1117,13 @@ SELECT forbidden.table_name, forbidden.privilege FROM (VALUES ('exomem_cloud_issuance_log', 'SELECT'), ('exomem_cloud_issuance_log', 'INSERT'), ('exomem_cloud_issuance_log', 'UPDATE'), ('exomem_cloud_issuance_log', 'DELETE'), + ('exomem_cloud_issuance_log', 'TRUNCATE'), ('exomem_cloud_issuance_log', 'REFERENCES'), ('schema_releases', 'INSERT'), ('schema_releases', 'UPDATE'), ('schema_releases', 'DELETE'), ('exomem_cloud_download_tickets', 'UPDATE') ) AS forbidden(table_name, privilege) -WHERE CASE forbidden.privilege - WHEN 'DELETE' THEN has_table_privilege('substrate_app', to_regclass(forbidden.table_name), 'DELETE') +WHERE CASE + WHEN forbidden.privilege IN ('DELETE', 'TRUNCATE') + THEN has_table_privilege('substrate_app', to_regclass(forbidden.table_name), forbidden.privilege) ELSE has_any_column_privilege('substrate_app', to_regclass(forbidden.table_name), forbidden.privilege) END UNION ALL diff --git a/docs/runbooks/vercel-deployments.md b/docs/runbooks/vercel-deployments.md index 2d78a0bd..bf31024d 100644 --- a/docs/runbooks/vercel-deployments.md +++ b/docs/runbooks/vercel-deployments.md @@ -25,13 +25,25 @@ The check runs in every production build that the platform makes from source: a - **Instant rollback** to an earlier deployment. - **A deployment that was built elsewhere and uploaded** with the Vercel CLI. -Each of the three serves code without a check of the schema. The schema may be older or newer than that code. Each migration stays compatible with the release before it, so a rollback of one release is safe. Before you promote, roll back further, or upload a deployment, follow these steps: +Each of the three serves code without a check of the schema. The schema may be older or newer than that code. A deployment whose migrations have not run can fail on a table or column that does not exist. Each migration stays compatible with the release before it, so a rollback of one release is safe. Before you promote, roll back, or upload a deployment, follow these steps: -1. Read the commit of the deployment that you plan to serve. -2. As the schema owner, run `SELECT commit_sha, status FROM schema_releases WHERE commit_sha = ''`. A `released` row means the schema is at least as new as that commit. -3. If the row is missing or `superseded`, read the commits between that one and the newest `released` row. Serve the deployment only when none of them adds a migration that breaks the older code. +1. Read the commit hash of the deployment that you plan to serve. +2. As the schema owner, run the query below. It returns the row of that commit and the newest `released` row. -The expected result is a decision that you can name: the schema fits the code, or you start the migration job first. + ```sql + SELECT 'candidate' AS which, commit_sha, status FROM schema_releases WHERE commit_sha = '' + UNION ALL + (SELECT 'newest', commit_sha, status FROM schema_releases WHERE status = 'released' ORDER BY recorded_at DESC LIMIT 1); + ``` + +3. In a checkout of the repository, run `git merge-base --is-ancestor ` and note its exit status. +4. If the exit status is not 0 and the row of the commit is not `released`, do not serve the deployment. Its migrations may not have run. +5. In that case, run the `migrate-database` workflow for `main` and wait for the green run. Then repeat from step 2. +6. If the exit status is 0 and the commit is not the newest `released` commit, run `git log --oneline ..`. +7. Serve the deployment only when no listed commit adds a migration that breaks the older code. +8. In every other case, serve the deployment. + +The expected result is a decision that you can name: the schema is at least as new as the code and no later migration breaks it, or you run the migration job first. To ship one production build while the job cannot run, set `SKIP_SCHEMA_RELEASE_WAIT=1` in the Production environment, and unset it afterwards. diff --git a/migrations/0102_exomem_issuance_log_and_download_tickets.sql b/migrations/0102_exomem_issuance_log_and_download_tickets.sql index 639c2e74..630623ce 100644 --- a/migrations/0102_exomem_issuance_log_and_download_tickets.sql +++ b/migrations/0102_exomem_issuance_log_and_download_tickets.sql @@ -170,9 +170,18 @@ BEGIN RETURN NULL; END IF; + -- A row inserted already revoked ends at its insert, by the same rule as a + -- revocation: the schema accepts such a row, and the web app's role can insert it. + -- Without this, a service credential's record would stay open and the prune + -- would never select it, and a family's would keep its future expiry. An access + -- token also has a revocation column, but its record always takes its expiry, + -- on a revocation as well, so it needs no case here. IF kind = 'token_family' THEN the_grant := NEW.grant_id; the_family := NEW.id; the_client := NEW.client_id; the_expiry := NEW.expires_at; + IF NEW.revoked_at IS NOT NULL THEN + the_expiry := least(NEW.expires_at, pg_catalog.statement_timestamp()); + END IF; ELSIF kind = 'access_token' THEN the_grant := NEW.grant_id; the_family := NEW.family_id; the_client := NEW.client_id; the_expiry := NEW.expires_at; @@ -182,6 +191,9 @@ BEGIN the_family := NEW.family_id; the_expiry := NEW.expires_at; ELSIF kind = 'service_credential' THEN the_tenant := NEW.tenant_id; + IF NEW.revoked_at IS NOT NULL THEN + the_expiry := pg_catalog.statement_timestamp(); + END IF; END IF; IF kind = 'service_credential' THEN diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md index a740f95e..2f26e29b 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md @@ -326,7 +326,7 @@ The previous deployment keeps serving after a failed build, as it does today. A **What the check proves.** It proves that the schema is at least as new as the build. It does not prove that the schema is not newer. A rebuild of an older released commit passes, and its log says that a newer schema release exists. D10's rule covers one release back; an older rebuild is the operator's decision. -The check runs in every production build on the platform: a push, a redeploy and a deploy hook. It does not run for a deployment that was built elsewhere and uploaded, for a promotion, or for an instant rollback. None of those runs the build script. Each needs the platform's deploy credential or the operator's dashboard. +The check runs in every production build on the platform: a push, a redeploy and a deploy hook. It does not run for a deployment that was built elsewhere and uploaded, for a promotion, or for an instant rollback. None of those runs the build script. Each needs the platform's deploy credential or the operator's dashboard. The runbook therefore asks the operator, before such a deployment serves, for a schema release of its commit or of a newer one, and for the compatibility check when the commit is older than the newest release. Alternatives: @@ -368,9 +368,9 @@ A log that nobody can read cheaply proves nothing. Two readers exist, and each o - rights that the web app's role holds on the log, `schema_releases`, ticket rows and, table-wide, the locked tables beyond what the grants script gives it; - create rights that a role other than a superuser, the schema owner or `pg_database_owner` holds on the database or on a schema outside `pg_catalog` and `information_schema`, and schemas that a role other than the schema owner, the bootstrap superuser or `pg_database_owner` owns. -The first check also reads the credential tables in full. It filters their rows by `created_at`, and none of the five tables has an index on that column. A consumed refresh token of an unexpired family stays in its table, so the tables hold more than the live credentials. The read grows with those tables, not with the range of the log. The operator runs it on demand (limit 13), not on a schedule. A scheduled version needs an index on `created_at` or a different query, which is a later step. The record of a credential that is less than 90 days old exists, because the prune deletes a record 90 days after its credential ends and a credential ends after it is created. So the check lists only credentials created in the last 90 days, and never before the install time of the second migration. The audit role cannot read `schema_migrations`, so the operator reads that time once, as the schema owner, and passes it to every run. A credential older than 90 days is not checked, because its record may be gone. That includes a service credential that is still live. Widening the audit role's column grant to the credential's expiry and revocation time would bring such a credential back; this change does not. Consecutive passes leave no gap: a pass's `lo_time` is at or before the previous pass's `hi_time`, or it is the install time, before which the check lists nothing. The last five read the catalog. +The first check also reads the credential tables in full. It filters their rows by `created_at`, and none of the five tables has an index on that column. A consumed refresh token of an unexpired family stays in its table, so the tables hold more than the live credentials. The read grows with those tables, not with the range of the log. The operator runs it on demand (limit 13), not on a schedule. A scheduled version needs an index on `created_at` or a different query, which is a later step. The record of a credential that is less than 90 days old exists, because the prune deletes a record 90 days after its credential ends and a credential ends after it is created. So the check lists only credentials created in the last 90 days, and never before the install time of the second migration. The audit role cannot read `schema_migrations`, so the operator reads that time once, as the schema owner, and passes it to every run. A credential older than 90 days is not checked, because its record may be gone. That includes a service credential that is still live. Widening the audit role's column grant to the credential's expiry and revocation time would bring such a credential back; this change does not. The window is exclusive at both ends: a credential created at `lo_time` is not listed, because a token family and its first access token share one time and the family's record can sit one identifier below `lo`. Consecutive passes leave no gap: a pass's `lo_time` is strictly before the previous pass's `hi_time`, or it is the install time, before which the check lists nothing. The last five read the catalog. -**Late commits.** PostgreSQL assigns a record's identifier at insert, not at commit. A record can therefore commit after a check has read past its identifier. Each run starts one hour of records before the point where the previous run stopped, so the next run reads such a record. It finds that start by walking back through the primary key from the nearest record at or below the previous stop that still exists, because the prune can delete the record that the stop names. The walk goes back at most one page. The backfill is one transaction, so its records share one time and none is an hour older: the walk stops at the page there, and that transaction holds no late commit. Each run counts its stop from the previous stop: the stop is the lesser of the newest identifier and the previous stop plus one page. So a run reads at most two pages of identifiers, and its stop rises above the previous stop on every run while the previous stop is below the newest identifier. The page is 100,000 by default and the operator's to change. It must stay above the records of one hour of writes, or the cap on the walk can miss a late commit. The operator runs again from each stop until it reaches the newest identifier, so the first run on a large log, and a run after a long gap, take several passes. Each pass stays an index range on the primary key. The read stays bounded. A record whose transaction stayed open for longer than that hour is missed by the range checks. The read of one tenant's records still returns it. +**Late commits.** PostgreSQL assigns a record's identifier at insert, not at commit. A record can therefore commit after a check has read past its identifier. Each run starts one hour of records before the point where the previous run stopped, so the next run reads such a record. It finds that start by walking back through the primary key from the nearest record at or below the previous stop that still exists, because the prune can delete the record that the stop names. The walk looks for the nearest record that is at least one hour older than that record, and it does not go below the end of the backfill. The operator reads that end once, with the install time: it is the identifier before the first record that is not backfilled. The backfill is one transaction, so its records share one time, none is an hour older, and that transaction holds no late commit: the walk never reads it, and a run past it never returns to it. The walk has no cap in records, because a cap leaves a gap in the first check whenever an hour holds more than a page of records. So a run reads one hour of records before the previous stop and at most one page after it, and its read depends on the write rate of one hour, not on the page. A run counts its stop from the previous stop: the stop is the lesser of the newest identifier and the previous stop plus one page, so it rises above the previous stop on every run while the previous stop is below the newest identifier. The page is 100,000 by default and the operator's to change; it sets the number of passes, not what a pass finds. The operator runs again from each stop until it reaches the newest identifier, so the first run on a large log, and a run after a long gap, take several passes. Each pass stays an index range on the primary key. The read stays bounded. A record whose transaction stayed open for longer than that hour is missed by the range checks. The read of one tenant's records still returns it. **One tenant's records.** An index on `tenant_id` with `id` lists one tenant's issuances, newest first, a page at a time. That is the read for an incident and for an owner who asks who held access. Without the index, it would scan the whole log. diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md index 15164f8d..037cf76f 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md @@ -312,7 +312,7 @@ A read-only audit role SHALL hold select on the issuance log and on the columns - **WHEN** the operator runs a documented check over a range of record identifiers - **THEN** the check reads that range of the log through the primary key and no other record of the log -- **AND** the range holds at most two pages of identifiers: the walk back from the previous stop is capped at one page, and the stop is at most one page past the previous stop +- **AND** the range holds the records of one hour before the previous stop, and at most one page after it: the walk back from the previous stop ends at the nearest record that is an hour older, or at the end of the backfill, and the stop is at most one page past the previous stop - **AND** the stop of each run is above the previous stop while that stop is below the newest identifier, so the operator reaches the newest identifier by repeating the run from each stop #### Scenario: The credential check lists only credentials that must have a record @@ -320,6 +320,8 @@ A read-only audit role SHALL hold select on the issuance log and on the columns - **WHEN** the operator runs the check for credential rows without a record - **THEN** it lists only credentials created in the last 90 days and after the second migration was applied - **AND** a credential older than 90 days is not listed, because the prune may have deleted its record, and that includes a live service credential +- **AND** a credential created at the lower edge of a pass is left to the previous pass, so a token family and its first access token that were created together and sit across a page boundary are not listed +- **AND** every credential without a record is listed in some pass, whatever the number of records in an hour #### Scenario: A record commits late diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md index c1249c4f..9bf7be78 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md @@ -388,8 +388,9 @@ and its date. - [ ] 7.6 Read the log and run the flows once. Sign in, connect an app, wait for one token refresh, open Home, download a file, disconnect the app, and see one maintenance run succeed. Run the D12 checks as the audit role, the - check of the web app's rights included. Repeat the range checks from each - stop until the stop equals the newest identifier. Evidence: the flows add records for + check of the web app's rights included. Read the install + time and the end of the backfill once, as the runbook says, and repeat the + range checks from each stop until the stop equals the newest identifier. Evidence: the flows add records for the test account, and the checks list nothing. A row from the rights check means that an earlier grants script ran after the job, and step 7.7 takes the right back. Run no attack against production; task 5.1 is that proof. diff --git a/src/lib/exomem-hosted/__tests__/cloud-issuance-log-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-issuance-log-postgres.integration.test.ts index 3c2c2cfc..68cb6082 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-issuance-log-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-issuance-log-postgres.integration.test.ts @@ -610,6 +610,36 @@ for (const state of STATES) { } }); + it("ends a record at its insert when the web app's role inserts a service credential or a token family already revoked", async () => { + // The schema accepts such a row. Without an end, the credential's record would stay + // open for ever and the family's would keep its future expiry, and the prune would + // select neither. + const credential = ( + await fx.app.query<{ id: string }>( + `INSERT INTO ${serviceCredentials()} + (tenant_id, principal, secret_digest, created_by_principal_digest, revoked_at, revoked_by_principal_digest) + VALUES ($1, $2, $3, $4, now() - interval '200 days', $5) RETURNING id`, + [ + world.tenantId, + `service:t${randomBytes(6).toString("hex")}`, + randomBytes(32), + randomBytes(32), + randomBytes(32), + ] + ) + ).rows[0]!.id; + assert.deepEqual(await recordEnd(credential), { open: false, at_now: true }); + + const family = ( + await fx.app.query<{ id: string }>( + `INSERT INTO ${families()} (grant_id, client_id, expires_at, revoked_at) + VALUES ($1, $2, now() + interval '300 days', now() - interval '200 days') RETURNING id`, + [world.grantId, world.clientId] + ) + ).rows[0]!.id; + assert.deepEqual(await familyEnd(family), { at_expiry: false, at_now: true }); + }); + it("ends a token family's record when the web app's role deletes the family, and when a deleted grant cascades to it", async () => { const deleted = await addFamily(); await fx.app.query(`DELETE FROM ${families()} WHERE id = $1`, [deleted]); From e07c87ac76cf4900319b9c979105eb7d9566c547 Mon Sep 17 00:00:00 2001 From: Artexis10 Date: Wed, 2 Dec 2026 17:10:51 +0000 Subject: [PATCH 26/29] docs(openspec): record issuance suite CI evidence --- .../lock-cloud-identity-rows-and-record-issuance/tasks.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md index 9bf7be78..040defe3 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md @@ -277,7 +277,7 @@ without truncate. Neither state holds the trigger right. The `pgbench` script and the 10,000-tenant generator are not in this repository. They are kept with that private record, so a later change to the triggers or the guards reruns the proof with the same instrument. -- [ ] 5.9 Add the new suites to the PostgreSQL integration list in +- [x] 5.9 Add the new suites to the PostgreSQL integration list in `.github/workflows/test.yml`. Verify: CI runs them. ## 6. Documentation From 4343dc16b43f779b601fc1e9149d872a6f91fcd5 Mon Sep 17 00:00:00 2001 From: Artexis10 Date: Wed, 2 Dec 2026 17:39:43 +0000 Subject: [PATCH 27/29] fix(cloud): check issuance coverage across pruned records and late commits --- docs/runbooks/exomem-cloud-operations.md | 216 +++++++++--------- docs/runbooks/vercel-deployments.md | 4 +- ...omem_issuance_log_and_download_tickets.sql | 17 +- .../design.md | 27 ++- .../specs/exomem-hosted-mcp-oauth/spec.md | 18 +- .../specs/substrate-database-releases/spec.md | 3 +- .../tasks.md | 31 ++- 7 files changed, 155 insertions(+), 161 deletions(-) diff --git a/docs/runbooks/exomem-cloud-operations.md b/docs/runbooks/exomem-cloud-operations.md index 6331e5ed..2013bec1 100644 --- a/docs/runbooks/exomem-cloud-operations.md +++ b/docs/runbooks/exomem-cloud-operations.md @@ -886,136 +886,129 @@ whatever the other lanes do. #### Read it as the audit role -Connect as `substrate_audit` for every query in this section. The grants script gives that role select on the log. -It also gives select on the `id` and `created_at` columns of the five credential tables, and on `id` and `owner_user_id` of `exomem_tenants`. It gives no other right. Each query below reads a range of record identifiers through the primary key. -Each run reads one hour of records before the previous stop and at most one page after it, so its cost on the log follows the write rate of one hour and the page, not the size of the log. The first check also reads the credential tables in full. - -Nothing schedules these checks. Run them on demand, and after any emergency statement. Each run starts one hour of records before -the point where the previous run stopped, and never before the end of the backfill. A record gets its identifier when it is inserted, not when it commits, so a -record can commit after a run has read past it. The overlap lets the next run read it, and lists a finding inside the overlap in both passes: it is one finding, matched by its `id`. A record whose transaction stayed -open for longer than that hour is missed by the range checks. The read of one tenant's records still returns it. - -1. Read the time that migration 0102 was applied, once, as the schema owner: `SELECT applied_at FROM schema_migrations WHERE version = '0102_exomem_issuance_log_and_download_tickets.sql';`. Every run takes it as `install`. The audit role cannot read `schema_migrations`. -2. Read the identifier of the last record that the migration backfilled, once, as the audit role. Every run takes it as `backfill_end`. The migration wrote those records before any other record could land, so they are the first records of the log. The query reads only up to the first other record, and an empty result is `0`. - - ```sql - SELECT coalesce( - (SELECT min(id) - 1 FROM exomem_cloud_issuance_log WHERE NOT backfilled), - (SELECT max(id) FROM exomem_cloud_issuance_log), 0) AS backfill_end; - ``` - -3. Write down the value of `hi` that the previous run printed. For the first run, use `0`. -4. Start `psql` as `substrate_audit`: `psql -v prev= -v install='' -v backfill_end= -v page=100000`. -5. Find the range of this run: +Connect as `substrate_audit` for these checks. It can read the issuance log, +the identifier and creation time of each credential, and each tenant's +identifier and owner. Run the credential check on demand. It reads all five +credential tables. Save the two checkpoints separately and only after their +queries succeed. + +##### Credential rows without an issuance record + +1. Read the migration time as the schema owner: + `SELECT applied_at FROM schema_migrations WHERE version = '0102_exomem_issuance_log_and_download_tickets.sql';`. + Use it as `install`. For the first pass, also use it as `checked_through`. +2. Read the database time as the audit role: `SELECT clock_timestamp();`. Use it as the fixed `credential_target` for this sweep. +3. In psql as the audit role, set `install`, `checked_through`, and `credential_target` as timestamp variables. + Set `credential_page` to a positive interval such as `1 hour`. A wider page reads the credential tables fewer times during a catch-up. +4. Run this query. It checks one new time page and repeats the preceding hour to catch late commits. ```sql - SELECT coalesce(max(id), 0) AS newest FROM exomem_cloud_issuance_log \gset - SELECT least(:backfill_end, :prev) AS back \gset - SELECT coalesce( - (SELECT id FROM exomem_cloud_issuance_log - WHERE id BETWEEN :back AND :prev - AND recorded_at < (SELECT recorded_at FROM exomem_cloud_issuance_log - WHERE id <= :prev ORDER BY id DESC LIMIT 1) - interval '1 hour' - ORDER BY id DESC LIMIT 1), :back) AS lo \gset - SELECT least(:newest, :prev + :page) AS hi \gset - SELECT greatest( - CASE WHEN :lo = 0 THEN '-infinity'::timestamptz - ELSE coalesce((SELECT recorded_at FROM exomem_cloud_issuance_log - WHERE id >= :lo ORDER BY id LIMIT 1), 'infinity') END, - :'install'::timestamptz, - now() - interval '90 days') AS lo_time \gset - SELECT CASE WHEN :hi = :newest THEN 'infinity'::timestamptz - ELSE coalesce((SELECT recorded_at FROM exomem_cloud_issuance_log - WHERE id <= :hi ORDER BY id DESC LIMIT 1), '-infinity') - interval '1 hour' END AS hi_time \gset - \echo newest=:newest hi=:hi lo=:lo - ``` - - `page` is the most identifiers that one run reads past the previous stop. It is yours to change: raise it to read more in - a run and take fewer passes, or lower it to read less. It does not affect what a run finds. `hi` rises above `prev` on every - run while `prev` is below `newest`, so step 8 ends. - - The prune can delete the record that `prev` names, so `lo` anchors on the nearest record at or below `prev` that still - exists, and walks back from there through the primary key until it finds a record that is an hour older. The walk stops - at `back`, which is `backfill_end`, or `prev` while `prev` is lower. The backfill is one transaction: its records carry one - time and none is an hour older, and that transaction holds no late commit. A run that starts past the backfill reads at most the - backfill's last record, and the walk reads one hour of records at most. An empty log gives `hi=0`, and the checks - that use the range return no row. - - `lo_time` and `hi_time` bound the credential rows that the first check lists, and both ends are exclusive. `lo_time` is never earlier than `install`. No - record exists before the migration, except the backfill's, which carries the migration's time, and the backfill wrote - none for a row that ended more than 90 days before. `lo_time` is also never earlier than 90 days ago. The prune deletes a record - 90 days after its credential ends, and a credential ends after it is created, so the record of a credential that is less - than 90 days old exists. The record of an older credential may be gone. The first check does not list that credential, - and that includes a service credential that is still live. `hi_time` is one hour before the record that `hi` names, and - `infinity` for the last page. A credential that is newer than `hi_time` belongs to the next pass, which starts one - hour of records before `hi`. `lo_time` is the time of the first record at or after `lo`. A credential created at - `lo_time` is not listed, because its record can sit just below `lo`: a token family and its first access token, minted - together, share that time. Consecutive passes leave no gap: a pass's `lo_time` is strictly before the previous pass's - `hi_time`, or it is `install` or the 90-day edge, before which the check lists nothing. - -6. Run the three checks. Each one is a finding when it returns a row. - - Credential rows without a record. One statement reads the credential rows and the log, so a credential and its - record are both visible or both absent. A row here has no record. It reads the log from `lo` to `hi`. It reads - the five credential tables in full, because none has an index on `created_at`, and a consumed refresh token of an - unexpired family stays in its table. Run it on demand, never from a schedule. A scheduled version needs an index on - `created_at` or a different query, which is a later step. - - A row has one exception. Suppose the transaction that wrote the record at `lo` stayed open while another credential was - created. Then that credential's record can sit just below `lo`. Before you act on a row, look its record up with - `SELECT id FROM exomem_cloud_issuance_log WHERE credential_id = ''`. - - ```sql - SELECT created.kind, created.id, created.created_at - FROM ( + WITH floor AS ( + SELECT greatest(:'install'::timestamptz, now() - interval '90 days') AS start_at + ), bounds AS ( + SELECT greatest(start_at, :'checked_through'::timestamptz - interval '1 hour') AS lo, + least(:'credential_target'::timestamptz, + greatest(start_at, :'checked_through'::timestamptz) + :'credential_page'::interval) AS hi, + start_at + FROM floor + ), issued AS ( SELECT 'token_family' AS kind, id, created_at FROM exomem_oauth_token_families UNION ALL SELECT 'access_token', id, created_at FROM exomem_oauth_access_tokens UNION ALL SELECT 'refresh_token', id, created_at FROM exomem_oauth_refresh_tokens UNION ALL SELECT 'service_credential', id, created_at FROM exomem_cloud_service_credentials UNION ALL SELECT 'download_ticket', id, created_at FROM exomem_cloud_download_tickets - ) AS created - WHERE created.created_at > :'lo_time' AND created.created_at < :'hi_time' - AND NOT EXISTS ( - SELECT 1 FROM exomem_cloud_issuance_log AS record - WHERE record.id BETWEEN :lo AND :hi - AND record.credential_kind = created.kind AND record.credential_id = created.id); + ) + SELECT bounds.hi AS next_checked_through, + bounds.start_at > greatest(:'install'::timestamptz, :'checked_through'::timestamptz) AS retention_gap, + missing.kind, missing.id, missing.created_at + FROM bounds + LEFT JOIN LATERAL ( + SELECT issued.kind, issued.id, issued.created_at + FROM issued + LEFT JOIN LATERAL ( + SELECT true AS present + FROM exomem_cloud_issuance_log AS record + WHERE record.credential_kind = issued.kind AND record.credential_id = issued.id + AND record.recorded_at >= issued.created_at + LIMIT 1 + ) AS matching ON true + WHERE issued.created_at >= bounds.lo AND issued.created_at < bounds.hi AND matching.present IS NULL + ) AS missing ON true; ``` - Records written by another database role. The web app's role writes every record, except those that the migration - backfilled. A row here means that the schema owner, or a role with the insert right, issued a credential outside the - web app. Match it to a change record. +5. Investigate rows with a credential identifier. Without a finding, the query returns one row with empty credential fields. +6. If `retention_gap` is true, record the skipped period up to the retention floor as unverified. Older credentials can have pruned records. +7. Save `next_checked_through` as `checked_through`. Repeat until it equals `credential_target`. - ```sql - SELECT id, credential_kind, credential_id, database_role, recorded_at - FROM exomem_cloud_issuance_log - WHERE id BETWEEN :lo AND :hi AND NOT backfilled AND database_role <> 'substrate_app'; - ``` +The two edges are lower-inclusive and upper-exclusive. The next pass covers +the upper edge. Each lookup matches the credential kind and identifier and +requires a record from its creation time or later. An earlier issuance with +the same identifier cannot satisfy the check. If two rows reused both an +identifier and creation time, this check cannot distinguish them. The +credential and its log record use the +same database snapshot. Repeating the final page from its checkpoint reads +the last hour again. A transaction open for more than an hour can fall +outside the replay. To investigate an older period, list the records of the +affected tenant through the indexed read below. + +##### Recorded issuances - Records whose user is not the tenant's owner. The recording function copies both values from the grant, a guard - refuses a change to a tenant's owner, and only the database writes records. A row here means that the web app's - role inserted a grant for a user other than the tenant's owner, and the gateway admits that grant. Find the grant - by the record's `grant_id` and revoke it. +1. Start psql with `ON_ERROR_STOP` set. Set `prev_id`, `prior_before`, and `prior_after` from the last successful pass. For the first pass, use `0` and two `-infinity` timestamps. +2. Set `id_target` to `0` at the start of a sweep. Set `page` to `100000`, or a smaller positive number. +3. Run this block in one transaction. It reads one new page and replays recent records through the previous stop. ```sql - SELECT record.id, record.credential_kind, record.tenant_id, record.user_id - FROM exomem_cloud_issuance_log AS record + BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY; + SELECT statement_timestamp() AS sample_before, + clock_timestamp() AS sample_after, + coalesce((SELECT max(id) FROM exomem_cloud_issuance_log), 0) AS newest \gset + SELECT greatest(:'prev_id'::bigint, coalesce(nullif(:'id_target'::bigint, 0), :newest)) AS target \gset + SELECT least(:target, :'prev_id'::bigint + :'page'::bigint) AS hi \gset + + WITH records AS MATERIALIZED ( + SELECT id, credential_kind, tenant_id, user_id, database_role, backfilled + FROM exomem_cloud_issuance_log + WHERE id > :'prev_id'::bigint AND id <= :hi + UNION ALL + SELECT id, credential_kind, tenant_id, user_id, database_role, backfilled + FROM exomem_cloud_issuance_log + WHERE NOT backfilled AND id <= :'prev_id'::bigint + AND recorded_at >= :'prior_before'::timestamptz - interval '1 hour' + AND recorded_at <= :'prior_after'::timestamptz + ) + SELECT 'other database role' AS finding, id, credential_kind, tenant_id, user_id + FROM records WHERE NOT backfilled AND database_role <> 'substrate_app' + UNION ALL + SELECT 'user differs from tenant owner', record.id, record.credential_kind, + record.tenant_id, record.user_id + FROM records AS record JOIN exomem_tenants AS tenant ON tenant.id = record.tenant_id - WHERE record.id BETWEEN :lo AND :hi AND record.user_id <> tenant.owner_user_id; + WHERE record.user_id <> tenant.owner_user_id; + COMMIT; + \echo prev_id=:hi prior_before=:sample_before prior_after=:sample_after id_target=:target ``` -7. Write down the value of `hi` as the stop of this run. The next run takes it as `prev`. -8. If `hi` is below `newest`, the log holds records that this run did not read. Run again with `prev` set to this `hi`, until - `hi` equals `newest`. The first run on a large log, and a run after a long gap, take several passes. The expected result - is a last pass that prints `hi` equal to `newest`. +4. Investigate each returned finding. If a repeat shows the same identifier and finding, treat it as one finding. +5. Save all four values printed by the successful block. Keep `id_target` fixed until `prev_id` reaches it. + +A new sweep captures the current greatest identifier. Later writes do not +move that sweep's target. A pruned stop does not change the numeric cursor. +The recorded time comes from the transaction's start, so it can differ from +identifier order. The replay uses the prior snapshot's time window and the +index on recorded time. With transactions open for at most one hour, a +record that committed after the previous snapshot can appear in the replay +even if its identifier is already behind the stop. Backfilled records were +written in a single transaction. The new pages cover them. -Read one tenant's records, newest first, a page at a time. Use it for an incident, and for an owner who asks who held -access. For the first page, use the value of `newest` plus one as ``. For the next page, use the lowest `id` of the -page before. +Read one tenant's records, newest first, a page at a time. Use it for an +incident, and for an owner who asks who held access. For the first page, use +the current greatest log identifier plus one as `before`. For the next +page, use the lowest identifier from the previous page. ```sql SELECT id, recorded_at, credential_kind, credential_id, grant_id, family_id, client_id, expires_at FROM exomem_cloud_issuance_log -WHERE tenant_id = '' AND id < +WHERE tenant_id = :'tenant_id'::uuid AND id < :'before'::bigint ORDER BY id DESC LIMIT 50; ``` @@ -1185,9 +1178,8 @@ WHERE namespace.nspname NOT LIKE 'pg\_temp\_%' AND namespace.nspname NOT LIKE 'p #### Size and retention -At the load target the design estimates at least 142 million records and at least 35 GB. The 35 GB uses 250 bytes for a -record and its three indexes, which is a lower bound: measured records were larger. Read the size with the estimated -record count. The count is the planner's estimate, so it lags until the next analyse. +Compare the log's size with the estimated record count. The count comes from +the planner and lags until the next analyse. ```sql SELECT pg_size_pretty(pg_total_relation_size('exomem_cloud_issuance_log')) AS size, diff --git a/docs/runbooks/vercel-deployments.md b/docs/runbooks/vercel-deployments.md index bf31024d..889c1972 100644 --- a/docs/runbooks/vercel-deployments.md +++ b/docs/runbooks/vercel-deployments.md @@ -25,7 +25,7 @@ The check runs in every production build that the platform makes from source: a - **Instant rollback** to an earlier deployment. - **A deployment that was built elsewhere and uploaded** with the Vercel CLI. -Each of the three serves code without a check of the schema. The schema may be older or newer than that code. A deployment whose migrations have not run can fail on a table or column that does not exist. Each migration stays compatible with the release before it, so a rollback of one release is safe. Before you promote, roll back, or upload a deployment, follow these steps: +Each of the three serves code without a check of the schema. The schema may be older or newer than that code. A deployment whose migrations have not run can fail on a table or column that does not exist. Before you promote, roll back, or upload a deployment, follow these steps: 1. Read the commit hash of the deployment that you plan to serve. 2. As the schema owner, run the query below. It returns the row of that commit and the newest `released` row. @@ -45,6 +45,8 @@ Each of the three serves code without a check of the schema. The schema may be o The expected result is a decision that you can name: the schema is at least as new as the code and no later migration breaks it, or you run the migration job first. +When migration 0102 is in force and the previous web release is serving, pause service credential issuance. This applies during the first rollout and after an instant rollback. The previous release can return HTTP 500 when the new guard refuses a request. Resume issuance when the new release serves. + To ship one production build while the job cannot run, set `SKIP_SCHEMA_RELEASE_WAIT=1` in the Production environment, and unset it afterwards. Reference: [Vercel Git configuration](https://vercel.com/docs/project-configuration/git-configuration). diff --git a/migrations/0102_exomem_issuance_log_and_download_tickets.sql b/migrations/0102_exomem_issuance_log_and_download_tickets.sql index 630623ce..8f6c9068 100644 --- a/migrations/0102_exomem_issuance_log_and_download_tickets.sql +++ b/migrations/0102_exomem_issuance_log_and_download_tickets.sql @@ -56,13 +56,12 @@ CREATE TABLE exomem_cloud_issuance_log ( -- The prune reads by expiry, and one tenant's records list newest first. CREATE INDEX exomem_cloud_issuance_log_expires_idx ON exomem_cloud_issuance_log (expires_at); CREATE INDEX exomem_cloud_issuance_log_tenant_idx ON exomem_cloud_issuance_log (tenant_id, id); --- Ending a service credential or a token family finds its record by the credential's --- identifier. Each index holds only one kind's records, so an access or refresh --- token insert, which is most of the log, does not pay for either. -CREATE INDEX exomem_cloud_issuance_log_service_credential_idx - ON exomem_cloud_issuance_log (credential_id) WHERE credential_kind = 'service_credential'; -CREATE INDEX exomem_cloud_issuance_log_token_family_idx - ON exomem_cloud_issuance_log (credential_id) WHERE credential_kind = 'token_family'; +-- Credential checks and service credential or family end events use the same +-- lookup. The time index lets a later audit find recent commits below a saved ID. +CREATE INDEX exomem_cloud_issuance_log_credential_idx + ON exomem_cloud_issuance_log (credential_kind, credential_id, recorded_at); +CREATE INDEX exomem_cloud_issuance_log_replay_idx + ON exomem_cloud_issuance_log (recorded_at, id) WHERE NOT backfilled; -- The log refuses every writer that is not the schema owner, whatever rights -- the writer holds. The recording and prune functions run as the schema owner. @@ -152,9 +151,7 @@ BEGIN -- The statement time, not now(), so that retention runs from the revoking or -- deleting statement and not from the start of a long transaction. A revocation -- is one-way, so it cannot end a live credential's record early. A record keeps - -- an end that is already in the past. Each kind has its own statement, with - -- the kind as a literal, because only a literal lets the planner use that - -- kind's partial index in a plan that is reused across calls. + -- an end that is already in the past. IF TG_OP <> 'INSERT' THEN IF kind = 'service_credential' THEN UPDATE %1$I.exomem_cloud_issuance_log AS record diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md index 2f26e29b..d52c008e 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md @@ -170,7 +170,7 @@ One table, `exomem_cloud_issuance_log`, holds one record for each credential ins | Column | Meaning | |---|---| | `id` | identity column, in insert order | -| `recorded_at` | the database clock when the record was written | +| `recorded_at` | the time the transaction started | | `credential_kind` | `access_token`, `refresh_token`, `token_family`, `service_credential` or `download_ticket` | | `credential_id` | the credential row's identifier | | `grant_id`, `family_id`, `client_id` | as the credential row names them, or read through its token family | @@ -209,9 +209,9 @@ The recording fails closed: when the record cannot be written, the credential in A record is deleted once its credential expired, or ended, more than 90 days ago. A token family and a service credential end when they are revoked or their row is deleted. The session policy sets the expiry: a token family lasts `EXOMEM_OAUTH_SESSION_MAX_DAYS` from sign-in, 365 days by default and at most 730 (`src/lib/exomem-hosted/oauth-session-policy.ts`). A refresh token lasts `EXOMEM_OAUTH_REFRESH_IDLE_DAYS`, 30 days by default and at most 90, and never past its family's expiry. An access token lasts one hour, also never past its family's expiry. The database bounds no expiry, so a role that writes a far expiry only lengthens retention. -A service credential has no expiry. Its record has no end while the credential is live, and the prune never deletes it. When the credential is revoked, or its row is deleted, the recording function sets the record's end to the database clock's time. It runs from an update trigger on the revocation time and a delete trigger, and it sets a record's end once. The prune then deletes the record 90 days later. The function reads the clock, not the row's `revoked_at`. The web app's role writes that column, and a past time would bring the prune forward and erase the record of a credential that the role issued. A partial index on the credential's identifier, which holds only service credential records, finds the record. A token insert pays nothing for it. For a revoked credential that exists when the migration runs, the record's end is the migration's time. +A service credential has no expiry. Its record has no end while the credential is live, and the prune never deletes it. When the credential is revoked, or its row is deleted, the recording function sets the record's end to the database clock's time. It runs from an update trigger on the revocation time and a delete trigger, and it sets a record's end once. The prune then deletes the record 90 days later. The function reads the clock, not the row's `revoked_at`. The web app's role writes that column, and a past time would bring the prune forward and erase the record of a credential that the role issued. The audit's credential index finds the record by kind and identifier. For a revoked credential that exists when the migration runs, the record's end is the migration's time. -A token family's record holds the family's expiry from the insert. The same recording function moves it to the database clock's time when the family is revoked or its row is deleted, if that is earlier. An update trigger on the revocation time and a delete trigger run it, and a delete that an account's deletion cascades to runs it too. The function reads the clock, not the row's `revoked_at`, for the same reason as above. A revocation is one-way, and a revoked family cannot be used, so the web app's role cannot end a live family's record early. A partial index on the credential's identifier, which holds only token family records, finds the record. An access token or refresh token insert pays nothing for it, and a family insert pays one more index entry. For a family that is revoked when the migration runs, the record's end is the migration's time, unless the family expired earlier. An access token's and a refresh token's record do not end early. Each keeps its own expiry. +A token family's record holds the family's expiry from the insert. The same recording function moves it to the database clock's time when the family is revoked or its row is deleted, if that is earlier. An update trigger on the revocation time and a delete trigger run it, and a delete that an account's deletion cascades to runs it too. The function reads the clock, not the row's `revoked_at`, for the same reason as above. A revocation is one-way, and a revoked family cannot be used, so the web app's role cannot end a live family's record early. The same credential index finds the family's record. For a family that is revoked when the migration runs, the record's end is the migration's time, unless the family expired earlier. An access token's and a refresh token's record do not end early. Each keeps its own expiry. A cell's deletion revokes its tenant's service credentials, in the database. An `AFTER UPDATE` row trigger on the cells table fires when a cell's desired state becomes `deleted`, and an `AFTER DELETE` trigger fires when a row that is not yet deleted goes. Both set `revoked_at` to the database clock on the tenant's unrevoked service credentials and leave the revoking principal empty, because no operator revoked them. The recording function's trigger then ends each record. The database does this, not the web app's code, so the release that serves during a build, and an instant rollback to the release before this one, still end the credentials: no flow's SQL changes. A credential belongs to the tenant, so a live one would otherwise serve the tenant's next cell after re-admission, and its record would stay open and never be pruned. The trigger function runs with its caller's rights, not the schema owner's. Only the web app's role sets a cell's desired state, and it already holds update on the revocation column, so no grant changes. The gateway's role reads cells only, and the controller's role writes observed columns only, so neither fires it. The schema owner is the only role that can delete a cell row, so the delete trigger covers it. The trigger does not check for another live cell, because one index allows a single cell that is not deleted for each tenant. A second update, or a delete of a row that is already deleted, changes nothing. A `BEFORE INSERT` row trigger on the service credentials table closes the opposite order. Without it, a credential that commits just after the deletion's trigger ran would stay live and serve the tenant's next cell. The trigger reads the tenant's cell that is not deleted with `FOR SHARE`, and refuses the insert when none exists, with SQLSTATE `23503` and the constraint name `exomem_cloud_service_credentials_live_cell`. A deletion that starts after the insert waits for the inserting transaction to commit, and the deletion's own trigger then revokes the new credential. An insert that waits for a deletion finds the updated row, finds no live cell when the deletion commits, and is refused. The service credential request answers that refusal as `SERVICE_CREDENTIAL_TENANT_INELIGIBLE` (409), the answer for any tenant without a live cell. This trigger function also runs with its caller's rights. The web app's role is the only role that inserts credentials. It holds select on the cell and update on the columns that the share lock needs, so no grant changes. Both triggers take the cell's lock before the credential: the insert locks the cell's row before its own row exists, and the cell trigger writes the credentials after the cell row, as D5's order requires. Afterwards, a token family's record and a service credential's record last 90 days. The migration also revokes once, at its own time, every unrevoked service credential of a tenant that has no cell other than deleted ones, so the credentials of accounts that a release before this one deleted end too. No record stays open after that. An access token's record lasts until 90 days after its own expiry, which is an hour at most from its issue. A refresh token's record lasts until 90 days after its own expiry, which is the idle window at most from its issue: 30 days by default, at most 90. The longest window after deletion is therefore the refresh token's idle bound plus 90 days, which is 120 days by default and 180 at most. A download ticket's record lasts a day plus 90 days at most. @@ -230,7 +230,7 @@ A Home tool call runs about seven statements today. One checks the cell before t This change adds work in two places. The token insert gains: - one read of the grant by primary key; -- one log insert with three index entries (`id`, `expires_at`, and `tenant_id` with `id`); +- one log insert with five index entries. The identity lookup and late-commit replay share the live insert; - one call of the log's guard. Each update of a column-locked table gains the evaluation of its guard's `WHEN` clause, which calls no function. @@ -244,19 +244,20 @@ Volume, from constants in the code and one assumption: - A refresh token expires after its idle window, 30 days by default, so its record lives up to 120 days. - Assumption, not a recorded figure: each of 10,000 tenants keeps Home visible for one hour a day and runs two apps for eight hours. -That gives about 1.5 million records a day: 1.2 million from Home and 0.3 million from apps. About 142 million sit inside the retention. A record with its three index entries takes at least 250 bytes, so the log holds at least about 35 GB at the load target. Home's two-minute tokens are about three quarters of it. The 250 bytes is a lower bound from the column list: records measured in the proof were larger. The proof reports the measured size of a record. +Use that traffic mix and the retention periods to size the representative +dataset. Measure storage with the audit indexes before rollout. The log also costs outside the request: -- Each record is written once and deleted once. At the load target that is about three million row changes a day in the write-ahead log. +- Each record is written once and deleted once. Both writes contribute to the write-ahead log. - Each base backup grows by the log's size, and a restore takes longer in proportion. Proof, on a disposable PostgreSQL: - **Instrument.** `pgbench` runs the Home mint transaction's statements as a custom script, over generated data for 10,000 tenants. The same script runs with and without this change's triggers, five runs each, on the same machine and data. The script and the generator are not in this repository. They are kept with the private record of the run, together with its outputs, so a later change to the triggers or the guards reruns the proof with the same instrument. -- **Size.** The log holds 10 million generated records. That is enough, because every insert lands at the right edge of an index, or at the right edge of one tenant's range. The pages that an insert touches stay in memory at any log size. +- **Size.** The instrument holds 10 million generated records. Its results describe that sample and the tested client count. Latency at the projected log size and concurrency remains unverified. The expiry index also holds credentials with different lifetimes and records whose expiry can change. - **Result.** The run's outputs are kept as a private record outside this repository, and task 5.8 states the outcome and the commit that the run measured. The median must rise by less than one millisecond. -- **Plans.** `EXPLAIN (ANALYZE, BUFFERS)` of one prune call shows that it reads only the records it deletes. The same output for each read of the log in D12 shows an index range and no full scan. D12's first check also reads the credential tables in full, so its plan is reported and no bound is set on it. +- **Plans.** Run `EXPLAIN (ANALYZE, BUFFERS)` on one prune and on each current D12 query. The prune should read only the records it deletes. Each D12 read must use a bounded range or lookup on the log. D12's first check also reads the credential tables in full, so its plan is reported and no bound is set on those tables. ### D8. A download ticket gets a stored row @@ -343,7 +344,9 @@ The order for each commit is: migrations, grants, schema release, build, serve. The release that is already serving meets the new schema and the new grants during the build. It also meets them after an instant rollback. So each migration and each grants change stays compatible with the previous release. That is today's unwritten rule, and it is now a requirement. -This change obeys it. The lock changes no statement, so the previous release runs under the new rights and guards. The proof runs the flows as the web app's role for that reason. The recording triggers are invisible to callers. The ticket table exists before the web app writes to it, and the gateway requires it last. +The previous release runs under the new rights and guards. The proof runs the existing flows as the web app's role. The ticket table exists before the web app writes to it, and the gateway requires it last. + +Service credential issuance is an operator action. Migration 0102 can refuse an ineligible cell or detect the lock conflict described in D5. The previous release can report either as HTTP 500. The new release reports the ineligible cell as 409 and the lock conflict as a retryable 503. Keep issuance paused while the previous release serves against 0102, during both rollout and instant rollback. ### D11. The schema-owner credential is removed, then rotated @@ -357,7 +360,7 @@ A log that nobody can read cheaply proves nothing. Two readers exist, and each o **The audit role.** A new role, `substrate_audit`, reads the log without the schema-owner credential. It holds select on the log and on the columns that its checks compare, and no other right. The grants script grants this when the role exists, as it does for the gateway's role. The operator creates the role in the rollout. -**The runbook's checks.** Each check that reads the log takes a range of record identifiers and reads only that range, through the primary key. The checks are: +**The runbook's checks.** Each log read uses a bounded range or an indexed lookup. The checks are: - credential rows created in the period that have no record; - records in the range whose database role is not the web app's role and that are not backfilled; @@ -368,9 +371,9 @@ A log that nobody can read cheaply proves nothing. Two readers exist, and each o - rights that the web app's role holds on the log, `schema_releases`, ticket rows and, table-wide, the locked tables beyond what the grants script gives it; - create rights that a role other than a superuser, the schema owner or `pg_database_owner` holds on the database or on a schema outside `pg_catalog` and `information_schema`, and schemas that a role other than the schema owner, the bootstrap superuser or `pg_database_owner` owns. -The first check also reads the credential tables in full. It filters their rows by `created_at`, and none of the five tables has an index on that column. A consumed refresh token of an unexpired family stays in its table, so the tables hold more than the live credentials. The read grows with those tables, not with the range of the log. The operator runs it on demand (limit 13), not on a schedule. A scheduled version needs an index on `created_at` or a different query, which is a later step. The record of a credential that is less than 90 days old exists, because the prune deletes a record 90 days after its credential ends and a credential ends after it is created. So the check lists only credentials created in the last 90 days, and never before the install time of the second migration. The audit role cannot read `schema_migrations`, so the operator reads that time once, as the schema owner, and passes it to every run. A credential older than 90 days is not checked, because its record may be gone. That includes a service credential that is still live. Widening the audit role's column grant to the credential's expiry and revocation time would bring such a credential back; this change does not. The window is exclusive at both ends: a credential created at `lo_time` is not listed, because a token family and its first access token share one time and the family's record can sit one identifier below `lo`. Consecutive passes leave no gap: a pass's `lo_time` is strictly before the previous pass's `hi_time`, or it is the install time, before which the check lists nothing. The last five read the catalog. +**Credential coverage.** The first check scans the credential tables on demand. The operator chooses the time page. A wider page reads the tables fewer times during a catch-up but makes more log lookups. The sweep has a fixed target, and each pass repeats the preceding hour. Each credential and its indexed lookup use one snapshot. The lookup excludes records older than the credential. An identifier reused with the same creation time cannot be distinguished by this check. The audit role's grants stay narrow. The operator reads the migration time once as schema owner. The check clips its lower edge to that time and the 90-day retention floor. It reports a gap if retention has overtaken the checkpoint. -**Late commits.** PostgreSQL assigns a record's identifier at insert, not at commit. A record can therefore commit after a check has read past its identifier. Each run starts one hour of records before the point where the previous run stopped, so the next run reads such a record. It finds that start by walking back through the primary key from the nearest record at or below the previous stop that still exists, because the prune can delete the record that the stop names. The walk looks for the nearest record that is at least one hour older than that record, and it does not go below the end of the backfill. The operator reads that end once, with the install time: it is the identifier before the first record that is not backfilled. The backfill is one transaction, so its records share one time, none is an hour older, and that transaction holds no late commit: the walk never reads it, and a run past it never returns to it. The walk has no cap in records, because a cap leaves a gap in the first check whenever an hour holds more than a page of records. So a run reads one hour of records before the previous stop and at most one page after it, and its read depends on the write rate of one hour, not on the page. A run counts its stop from the previous stop: the stop is the lesser of the newest identifier and the previous stop plus one page, so it rises above the previous stop on every run while the previous stop is below the newest identifier. The page is 100,000 by default and the operator's to change; it sets the number of passes, not what a pass finds. The operator runs again from each stop until it reaches the newest identifier, so the first run on a large log, and a run after a long gap, take several passes. Each pass stays an index range on the primary key. The read stays bounded. A record whose transaction stayed open for longer than that hour is missed by the range checks. The read of one tenant's records still returns it. +**Recorded issuances.** The recorded-issuance checks use a separate numeric checkpoint and a fixed greatest identifier for the sweep. Each pass reads one new page through the primary key. It also checks identifiers at or below the checkpoint whose transaction-start time falls within the previous snapshot's replay window. The replay uses the partial time index and excludes the backfill. The backfill committed together and is covered by the new pages. Identifier order need not match transaction-start order. An uncommitted record therefore stays eligible for the next replay even if a later identifier has an earlier timestamp. The replay covers transactions open for up to one hour. Longer transactions can fall outside it. A checkpoint advances only after the queries succeed. **One tenant's records.** An index on `tenant_id` with `id` lists one tenant's issuances, newest first, a page at a time. That is the read for an incident and for an owner who asks who held access. Without the index, it would scan the whole log. diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md index 037cf76f..987591ec 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md @@ -300,7 +300,7 @@ An issuance record SHALL be kept until at least 90 days after its credential exp ### Requirement: The issuance log is read in bounded ranges, without the schema-owner credential -A read-only audit role SHALL hold select on the issuance log and on the columns that its checks compare, and no other right. Each documented read of the log SHALL cover a bounded range of records. The check for credential rows without a record SHALL also read the credential tables in full, and the operator SHALL run it on demand. A reader SHALL be able to list one tenant's records a page at a time through an index. +A read-only audit role SHALL hold select on the issuance log and on the columns that its checks compare, and no other right. Each documented read of the log SHALL use an indexed lookup or read a bounded range. The check for credential rows without a record SHALL also read the credential tables in full, and the operator SHALL run it on demand. A reader SHALL be able to list one tenant's records a page at a time through an index. #### Scenario: The audit role reads the log @@ -311,22 +311,22 @@ A read-only audit role SHALL hold select on the issuance log and on the columns #### Scenario: A check reads a range - **WHEN** the operator runs a documented check over a range of record identifiers -- **THEN** the check reads that range of the log through the primary key and no other record of the log -- **AND** the range holds the records of one hour before the previous stop, and at most one page after it: the walk back from the previous stop ends at the nearest record that is an hour older, or at the end of the backfill, and the stop is at most one page past the previous stop -- **AND** the stop of each run is above the previous stop while that stop is below the newest identifier, so the operator reaches the newest identifier by repeating the run from each stop +- **THEN** the check reads one new page through the primary key and replays recent records through the previous stop using the time index +- **AND** each successful page advances toward the sweep's fixed target even if new log rows arrive or the saved stop is pruned #### Scenario: The credential check lists only credentials that must have a record - **WHEN** the operator runs the check for credential rows without a record -- **THEN** it lists only credentials created in the last 90 days and after the second migration was applied +- **THEN** it looks up the credential kind and identifier for credentials created in the last 90 days and from the second migration onward +- **AND** a record from before a credential's creation cannot cover a later reuse of its identifier - **AND** a credential older than 90 days is not listed, because the prune may have deleted its record, and that includes a live service credential -- **AND** a credential created at the lower edge of a pass is left to the previous pass, so a token family and its first access token that were created together and sit across a page boundary are not listed -- **AND** every credential without a record is listed in some pass, whatever the number of records in an hour +- **AND** each pass covers its lower time edge and leaves its upper time edge to the next pass +- **AND** a missing credential is listed even if pruning removed the closest issuance records or the log is empty #### Scenario: A record commits late -- **WHEN** a record commits after a run of the checks has read past its identifier, less than one hour late -- **THEN** the next run reads that record, because each run starts one hour of records before the point where the previous run stopped +- **WHEN** a record in a transaction open for up to one hour commits after a check has read past its identifier +- **THEN** the next check reads that record using the previous snapshot's time window even when record time and identifier order differ #### Scenario: The checks name what they find diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/substrate-database-releases/spec.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/substrate-database-releases/spec.md index 86ad5554..b624fdfe 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/substrate-database-releases/spec.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/substrate-database-releases/spec.md @@ -102,7 +102,8 @@ A production build of the web app SHALL run no migration. It SHALL finish only a #### Scenario: The serving release meets the new schema - **WHEN** the job has applied a commit's migrations and grants, and that commit's build has not finished -- **THEN** every flow of the release that is still serving keeps working +- **THEN** existing user flows keep working under the new schema and grants +- **AND** during the migration that adds the service credential guard, the operator waits for the new web release before issuing service credentials #### Scenario: A preview or development build diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md index 040defe3..63c6903e 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md @@ -97,8 +97,8 @@ names each decision as D1 to D12. - [x] 3.1 In the second migration, set a lock timeout of five seconds for the transaction, then take D5's locks in D5's order with one `LOCK TABLE` statement. Create `exomem_cloud_issuance_log` with its kind constraint, its - three indexes, a partial index each for service credential and token family - records, and its guard. Add the recording function and revoke its execute + five indexes and its guard. The audit uses the credential lookup and the + partial index for late-commit replay. Add the recording function and revoke its execute right from `PUBLIC`. Add one `AFTER INSERT` trigger on each of the five credential tables, and on the service credential and token family tables an update trigger on the revocation time and a delete trigger that end the @@ -259,8 +259,8 @@ without truncate. Neither state holds the trigger right. serves one that has its row. It refuses one whose path, token family or expiry differs from the stored row. A download request runs as many database statements as it did before this change. -- [x] 5.8 Cost at the load target (D7). Generate data for 10,000 tenants and a - log of 10 million records. With `pgbench`, run the Home mint transaction's +- [ ] 5.8 Cost proof (D7). For comparison with the earlier sample, generate data + for 10,000 tenants and a log of 10 million records. With `pgbench`, run the Home mint transaction's statements with and without this change's triggers: five runs each, same machine, same data. Report the median and the 95th percentile of both arms, the write-ahead-log bytes for each mint, and the measured size of a record. @@ -268,15 +268,13 @@ without truncate. Neither state holds the trigger right. Pass: the median rises by less than one millisecond, the prune reads only what it deletes, and no D12 read of the log scans the whole log. D12's first check also reads the credential tables in full, so the run reports its plan - and sets no bound on it. Evidence: the run's - outputs are kept as a private record outside this public repository. They - are the median and the 95th percentile of the mint latency with and without - the triggers, the write-ahead-log bytes for each mint, the size of a record, - and the `EXPLAIN` plans. The run measured commit `e8a7c3db`, which holds - every trigger of this change, and it met each part of the pass condition. - The `pgbench` script and the 10,000-tenant generator are not in this - repository. They are kept with that private record, so a later change to the - triggers or the guards reruns the proof with the same instrument. + and sets no bound on it. Keep the results as private evidence. The run at + `e8a7c3db` used the predecessor indexes and audit queries. The current + indexes change insert cost. Repeat the write proof with the same instrument + and run the current D12 queries on the generated log. The 10-million-record + run gives a sample result. Verify the budget at the projected load and + retained volume, or show that the sample covers the same index working set + and write conditions. - [x] 5.9 Add the new suites to the PostgreSQL integration list in `.github/workflows/test.yml`. Verify: CI runs them. @@ -378,7 +376,8 @@ and its date. when the merge's job runs. The catalog checks read `pg_catalog`, which every role can read. Evidence: the catalog queries' outcome. Fix any failure before step 7.5. -- [ ] 7.5 Approve the merge of the implementation PR. The merge applies the +- [ ] 7.5 Pause operator service credential issuance until the new web release serves. + Approve the merge of the implementation PR. The merge applies the migrations to production. The lock and the log are in force from that moment, and the web app starts to store ticket rows. If a migration meets its lock timeout or a deadlock, start the job again. If the production build @@ -389,8 +388,8 @@ and its date. for one token refresh, open Home, download a file, disconnect the app, and see one maintenance run succeed. Run the D12 checks as the audit role, the check of the web app's rights included. Read the install - time and the end of the backfill once, as the runbook says, and repeat the - range checks from each stop until the stop equals the newest identifier. Evidence: the flows add records for + time once, as the runbook says, and run both audit sweeps to their fixed + targets. Evidence: the flows add records for the test account, and the checks list nothing. A row from the rights check means that an earlier grants script ran after the job, and step 7.7 takes the right back. Run no attack against production; task 5.1 is that proof. From d334125102158e2524c20f557d092634776b0284 Mon Sep 17 00:00:00 2001 From: Artexis10 Date: Wed, 2 Dec 2026 17:59:52 +0000 Subject: [PATCH 28/29] fix(cloud): harden credential deletion and bound audit work --- README.md | 8 +- docs/runbooks/exomem-cloud-operations.md | 81 +++++++++-------- ...omem_issuance_log_and_download_tickets.sql | 36 +++++++- .../design.md | 12 ++- .../exomem-cloud-service-credentials/spec.md | 5 ++ .../specs/exomem-hosted-mcp-oauth/spec.md | 5 +- .../tasks.md | 17 ++-- ...-issuance-log-postgres.integration.test.ts | 87 ++++++++++++++++++- src/lib/exomem-hosted/issuance-maintenance.ts | 3 +- 9 files changed, 192 insertions(+), 62 deletions(-) diff --git a/README.md b/README.md index 3a0df9fe..173c2bcf 100644 --- a/README.md +++ b/README.md @@ -124,14 +124,14 @@ For a new blog post, do nothing extra — drop a `.md` file in `content/blog/` w The substrate also serves as the auth issuer + metadata store + presigned-URL minter for **Endstate Hosted Backup v2**. Protocol locked in [`hosted-backup-contract.md`](./hosted-backup-contract.md) (OIDC discovery, EdDSA JWTs, Argon2id-derived `serverPassword + masterKey` split, R2 storage with 5-version retention). -**Migrations.** +**Local migrations.** Set `LOCAL_DATABASE_URL` to a disposable database before running these commands. ```bash -npm run migrate # apply pending migrations from migrations/*.sql -npm run migrate:dry # list pending migrations without applying +env -u DATABASE_MIGRATION_URL DATABASE_URL="${LOCAL_DATABASE_URL:?}" npm run migrate:dry +env -u DATABASE_MIGRATION_URL DATABASE_URL="${LOCAL_DATABASE_URL:?}" npm run migrate ``` -The runner auto-creates a `schema_migrations` tracking table on first invocation. These commands run against the database that `DATABASE_URL` names in your shell, so use them on a local or disposable database. +The runner prefers `DATABASE_MIGRATION_URL` when both variables are set. The local commands clear it for each invocation. Applying migrations creates the tracking table if needed. The dry run only lists pending migrations. In production, a protected GitHub job (`.github/workflows/migrate-database.yml`) applies the migrations and the grants script for each commit that lands on `main`. It then records the commit's schema release. The production build reads its schema release and never migrates. [`docs/runbooks/production-keys-and-storage.md`](./docs/runbooks/production-keys-and-storage.md) describes the job and the manual run. diff --git a/docs/runbooks/exomem-cloud-operations.md b/docs/runbooks/exomem-cloud-operations.md index 2013bec1..4e403a54 100644 --- a/docs/runbooks/exomem-cloud-operations.md +++ b/docs/runbooks/exomem-cloud-operations.md @@ -888,7 +888,7 @@ whatever the other lanes do. Connect as `substrate_audit` for these checks. It can read the issuance log, the identifier and creation time of each credential, and each tenant's -identifier and owner. Run the credential check on demand. It reads all five +identifier and owner. Run the credential check on demand. It reads pages from the five credential tables. Save the two checkpoints separately and only after their queries succeed. @@ -896,60 +896,67 @@ queries succeed. 1. Read the migration time as the schema owner: `SELECT applied_at FROM schema_migrations WHERE version = '0102_exomem_issuance_log_and_download_tickets.sql';`. - Use it as `install`. For the first pass, also use it as `checked_through`. -2. Read the database time as the audit role: `SELECT clock_timestamp();`. Use it as the fixed `credential_target` for this sweep. -3. In psql as the audit role, set `install`, `checked_through`, and `credential_target` as timestamp variables. - Set `credential_page` to a positive interval such as `1 hour`. A wider page reads the credential tables fewer times during a catch-up. -4. Run this query. It checks one new time page and repeats the preceding hour to catch late commits. + Use it as `install`. For the first sweep, use the same value as `checked_through`. +2. Read the settled time as the audit role: `SELECT clock_timestamp() - interval '1 hour';`. Use it as the fixed `credential_target`. +3. If the target is no later than `checked_through`, let the next check cover new time. For a live mint check, use the tenant's log page below. +4. For each row in the table, set `kind` and `credential_table` in psql. Start with `after_id` empty and `page` set to `10000` or a smaller positive number. + + | `kind` | `credential_table` | + | --- | --- | + | `token_family` | `exomem_oauth_token_families` | + | `access_token` | `exomem_oauth_access_tokens` | + | `refresh_token` | `exomem_oauth_refresh_tokens` | + | `service_credential` | `exomem_cloud_service_credentials` | + | `download_ticket` | `exomem_cloud_download_tickets` | + +5. Run this query. It reads a page by credential identifier before filtering by time, so each pass checks only that page. ```sql WITH floor AS ( - SELECT greatest(:'install'::timestamptz, now() - interval '90 days') AS start_at + SELECT greatest(:'install'::timestamptz, now() - interval '2160 hours') AS start_at + ), credentials AS MATERIALIZED ( + SELECT id, created_at FROM :"credential_table" + WHERE id >= coalesce(nullif(:'after_id', '')::uuid, '00000000-0000-0000-0000-000000000000'::uuid) + AND id IS DISTINCT FROM nullif(:'after_id', '')::uuid + ORDER BY id LIMIT :'page'::integer ), bounds AS ( SELECT greatest(start_at, :'checked_through'::timestamptz - interval '1 hour') AS lo, - least(:'credential_target'::timestamptz, - greatest(start_at, :'checked_through'::timestamptz) + :'credential_page'::interval) AS hi, + :'credential_target'::timestamptz AS hi, start_at FROM floor - ), issued AS ( - SELECT 'token_family' AS kind, id, created_at FROM exomem_oauth_token_families - UNION ALL SELECT 'access_token', id, created_at FROM exomem_oauth_access_tokens - UNION ALL SELECT 'refresh_token', id, created_at FROM exomem_oauth_refresh_tokens - UNION ALL SELECT 'service_credential', id, created_at FROM exomem_cloud_service_credentials - UNION ALL SELECT 'download_ticket', id, created_at FROM exomem_cloud_download_tickets ) - SELECT bounds.hi AS next_checked_through, + SELECT (SELECT id FROM credentials ORDER BY id DESC LIMIT 1) AS next_id, bounds.start_at > greatest(:'install'::timestamptz, :'checked_through'::timestamptz) AS retention_gap, - missing.kind, missing.id, missing.created_at + missing.id, missing.created_at FROM bounds LEFT JOIN LATERAL ( - SELECT issued.kind, issued.id, issued.created_at - FROM issued + SELECT credential.id, credential.created_at + FROM credentials AS credential LEFT JOIN LATERAL ( SELECT true AS present FROM exomem_cloud_issuance_log AS record - WHERE record.credential_kind = issued.kind AND record.credential_id = issued.id - AND record.recorded_at >= issued.created_at + WHERE record.credential_kind = :'kind' AND record.credential_id = credential.id + AND record.recorded_at >= credential.created_at LIMIT 1 ) AS matching ON true - WHERE issued.created_at >= bounds.lo AND issued.created_at < bounds.hi AND matching.present IS NULL + WHERE credential.created_at >= bounds.lo AND credential.created_at < bounds.hi + AND matching.present IS NULL ) AS missing ON true; ``` -5. Investigate rows with a credential identifier. Without a finding, the query returns one row with empty credential fields. -6. If `retention_gap` is true, record the skipped period up to the retention floor as unverified. Older credentials can have pruned records. -7. Save `next_checked_through` as `checked_through`. Repeat until it equals `credential_target`. - -The two edges are lower-inclusive and upper-exclusive. The next pass covers -the upper edge. Each lookup matches the credential kind and identifier and -requires a record from its creation time or later. An earlier issuance with -the same identifier cannot satisfy the check. If two rows reused both an -identifier and creation time, this check cannot distinguish them. The -credential and its log record use the -same database snapshot. Repeating the final page from its checkpoint reads -the last hour again. A transaction open for more than an hour can fall -outside the replay. To investigate an older period, list the records of the -affected tenant through the indexed read below. +6. Investigate rows with a credential identifier. Without a finding, the query returns one row with empty credential fields. +7. If `retention_gap` is true, record the skipped period as unverified. Older credentials can have pruned records. +8. Set `after_id` to `next_id` after a successful query. Repeat until `next_id` is empty, then move to the next credential kind. +9. After all five kinds finish, save `credential_target` as `checked_through`. + +The time window includes the lower edge and leaves the upper edge to the +next sweep. The one-hour delay lets a transaction with the database's +creation time finish before the sweep reads its identifier range. A longer +open transaction or an explicitly backdated credential can fall outside +that coverage. The next sweep repeats the last hour. The credential and its +log record use the same snapshot in every page. An earlier issuance with the +same identifier cannot satisfy the check. A reuse with the same creation +time can match the old record. For older work, use the tenant's log page. ##### Recorded issuances @@ -1193,7 +1200,7 @@ the log line `exomem-issuance: log retention failed`. ```sql SELECT count(*) AS past_retention FROM (SELECT 1 FROM exomem_cloud_issuance_log - WHERE expires_at < now() - interval '90 days' LIMIT 100001) AS stale; + WHERE expires_at < now() - interval '2160 hours' LIMIT 100001) AS stale; ``` A log that holds twice the size that the count of live credentials predicts needs a look at the prune first. The diff --git a/migrations/0102_exomem_issuance_log_and_download_tickets.sql b/migrations/0102_exomem_issuance_log_and_download_tickets.sql index 8f6c9068..a0c7048f 100644 --- a/migrations/0102_exomem_issuance_log_and_download_tickets.sql +++ b/migrations/0102_exomem_issuance_log_and_download_tickets.sql @@ -186,6 +186,27 @@ BEGIN SELECT family.grant_id, family.client_id INTO the_grant, the_client FROM %1$I.exomem_oauth_token_families AS family WHERE family.id = NEW.family_id; the_family := NEW.family_id; the_expiry := NEW.expires_at; + IF kind = 'download_ticket' THEN + -- The expiry index bounds each mint to 32 candidates before locking, + -- so a locked backlog cannot make a request walk the expired table. + WITH candidates AS MATERIALIZED ( + SELECT candidate.id, candidate.expires_at + FROM %1$I.exomem_cloud_download_tickets AS candidate + WHERE candidate.expires_at <= pg_catalog.statement_timestamp() + AND candidate.id <> NEW.id + ORDER BY candidate.expires_at + LIMIT 32 + ) + DELETE FROM %1$I.exomem_cloud_download_tickets AS expired + WHERE expired.id = ( + SELECT lock_target.id + FROM candidates + JOIN %1$I.exomem_cloud_download_tickets AS lock_target ON lock_target.id = candidates.id + ORDER BY candidates.expires_at + LIMIT 1 + FOR UPDATE OF lock_target SKIP LOCKED + ); + END IF; ELSIF kind = 'service_credential' THEN the_tenant := NEW.tenant_id; IF NEW.revoked_at IS NOT NULL THEN @@ -233,7 +254,7 @@ BEGIN DELETE FROM %1$I.exomem_cloud_issuance_log AS record USING ( SELECT stale.id FROM %1$I.exomem_cloud_issuance_log AS stale - WHERE stale.expires_at < pg_catalog.now() - interval '90 days' + WHERE stale.expires_at < pg_catalog.now() - interval '2160 hours' ORDER BY stale.expires_at LIMIT 10000 ) AS doomed @@ -261,6 +282,13 @@ BEGIN LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp AS $body$ BEGIN + -- The revocation must see credentials that committed while deletion + -- waited for the cell lock. The web transaction already uses read + -- committed. Refuse a stale snapshot before deleting or revoking. + IF pg_catalog.current_setting('transaction_isolation') <> 'read committed' THEN + RAISE EXCEPTION 'Cell deletion must use READ COMMITTED to revoke service credentials' + USING ERRCODE = '0A000'; + END IF; UPDATE %1$I.exomem_cloud_service_credentials AS credential SET revoked_at = pg_catalog.statement_timestamp() WHERE credential.tenant_id = OLD.tenant_id AND credential.revoked_at IS NULL; @@ -395,7 +423,7 @@ CROSS JOIN LATERAL ( SELECT CASE WHEN family.revoked_at IS NOT NULL THEN least(family.expires_at, pg_catalog.now()) ELSE family.expires_at END AS at ) AS family_end -WHERE family_end.at >= pg_catalog.now() - interval '90 days'; +WHERE family_end.at >= pg_catalog.now() - interval '2160 hours'; INSERT INTO exomem_cloud_issuance_log ( credential_kind, credential_id, grant_id, family_id, client_id, @@ -405,7 +433,7 @@ SELECT 'access_token', token.id, token.grant_id, token.family_id, token.client_i grant_row.tenant_id, grant_row.user_id, token.expires_at, current_user, true FROM exomem_oauth_access_tokens AS token JOIN exomem_oauth_grants AS grant_row ON grant_row.id = token.grant_id -WHERE token.expires_at >= pg_catalog.now() - interval '90 days'; +WHERE token.expires_at >= pg_catalog.now() - interval '2160 hours'; INSERT INTO exomem_cloud_issuance_log ( credential_kind, credential_id, grant_id, family_id, client_id, @@ -416,7 +444,7 @@ SELECT 'refresh_token', token.id, family.grant_id, token.family_id, family.clien FROM exomem_oauth_refresh_tokens AS token JOIN exomem_oauth_token_families AS family ON family.id = token.family_id JOIN exomem_oauth_grants AS grant_row ON grant_row.id = family.grant_id -WHERE token.expires_at >= pg_catalog.now() - interval '90 days'; +WHERE token.expires_at >= pg_catalog.now() - interval '2160 hours'; -- A credential that is revoked already ends at the migration's time, like every -- backfilled time, so the prune keeps its record 90 days from the migration. diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md index d52c008e..1c95da37 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md @@ -207,6 +207,8 @@ The recording fails closed: when the record cannot be written, the credential in ### D6. Records are kept until 90 days after the credential expires or ends +The cutoff uses 90 elapsed days. A session's time zone does not change it. + A record is deleted once its credential expired, or ended, more than 90 days ago. A token family and a service credential end when they are revoked or their row is deleted. The session policy sets the expiry: a token family lasts `EXOMEM_OAUTH_SESSION_MAX_DAYS` from sign-in, 365 days by default and at most 730 (`src/lib/exomem-hosted/oauth-session-policy.ts`). A refresh token lasts `EXOMEM_OAUTH_REFRESH_IDLE_DAYS`, 30 days by default and at most 90, and never past its family's expiry. An access token lasts one hour, also never past its family's expiry. The database bounds no expiry, so a role that writes a far expiry only lengthens retention. A service credential has no expiry. Its record has no end while the credential is live, and the prune never deletes it. When the credential is revoked, or its row is deleted, the recording function sets the record's end to the database clock's time. It runs from an update trigger on the revocation time and a delete trigger, and it sets a record's end once. The prune then deletes the record 90 days later. The function reads the clock, not the row's `revoked_at`. The web app's role writes that column, and a past time would bring the prune forward and erase the record of a credential that the role issued. The audit's credential index finds the record by kind and identifier. For a revoked credential that exists when the migration runs, the record's end is the migration's time. @@ -223,6 +225,8 @@ The web app's role may call the function at any time, and it still deletes only A btree index on `expires_at` serves the prune. The alternatives were worse. A partitioned log would make every token insert depend on partition upkeep. A block-range index would go stale as long-lived token family records pin old ranges. +Only a read-committed transaction may delete a live cell or set it to deleted. After waiting for issuance's cell lock, the revocation must see the newly committed credential. The web transaction already uses read committed. The database refuses a fixed-snapshot deletion rather than leave a credential live. + ### D7. Cost on the hot path, at the load target A Home tool call runs about seven statements today. One checks the cell before the transaction. Inside it come the client lookup, the retirement of a stale grant, the grant upsert, the token family lookup, the delete of expired tokens and the token insert. A new token family adds one insert. @@ -257,7 +261,7 @@ Proof, on a disposable PostgreSQL: - **Instrument.** `pgbench` runs the Home mint transaction's statements as a custom script, over generated data for 10,000 tenants. The same script runs with and without this change's triggers, five runs each, on the same machine and data. The script and the generator are not in this repository. They are kept with the private record of the run, together with its outputs, so a later change to the triggers or the guards reruns the proof with the same instrument. - **Size.** The instrument holds 10 million generated records. Its results describe that sample and the tested client count. Latency at the projected log size and concurrency remains unverified. The expiry index also holds credentials with different lifetimes and records whose expiry can change. - **Result.** The run's outputs are kept as a private record outside this repository, and task 5.8 states the outcome and the commit that the run measured. The median must rise by less than one millisecond. -- **Plans.** Run `EXPLAIN (ANALYZE, BUFFERS)` on one prune and on each current D12 query. The prune should read only the records it deletes. Each D12 read must use a bounded range or lookup on the log. D12's first check also reads the credential tables in full, so its plan is reported and no bound is set on those tables. +- **Plans.** Run `EXPLAIN (ANALYZE, BUFFERS)` on one prune and on each current D12 query. The prune should read only the records it deletes. Each D12 read must use a bounded range or lookup on the log. The credential check pages through the source tables by primary key, then probes the log's credential index for eligible rows. ### D8. A download ticket gets a stored row @@ -267,8 +271,8 @@ The web app now stores one row for each ticket in `exomem_cloud_download_tickets - **Key.** A unique key covers the token family, the path digest and the expiry. The web app inserts with `ON CONFLICT DO NOTHING`. Two tickets with the same three values carry the same authority and share one row and one record. - **Rights.** The web app's role holds select, insert and delete. The gateway's role holds select. A guard refuses every update unless the schema owner runs it. -- **No foreign key, and no grant column.** A row lives at most one day, and the gateway joins the token family when the ticket is used. The row names no grant, because nothing reads one: the gateway's lookup requires the ticket's token family to carry the grant that the signed ticket names. The recording function reads the grant, the tenant and the user through the family. An insert for a family that does not exist fails, because the recording fails closed. A role that can insert can name another tenant's family with that family's real grant, and the gateway then admits the ticket. That is issuance, which the log records and this change does not prevent (limit 1). -- **Prune.** The scheduled maintenance deletes a bounded batch of expired rows, through an index on the expiry. +- **No foreign key, and no grant column.** A signed ticket can authorize a download for at most one day, and the gateway joins the token family when the ticket is used. The row names no grant, because nothing reads one: the gateway's lookup requires the ticket's token family to carry the grant that the signed ticket names. The recording function reads the grant, the tenant and the user through the family. An insert for a family that does not exist fails, because the recording fails closed. A role that can insert can name another tenant's family with that family's real grant, and the gateway then admits the ticket. That is issuance, which the log records and this change does not prevent (limit 1). +- **Prune.** A new ticket looks up a bounded set of expired rows through the expiry index before trying any locks. It retires one available row and skips the cleanup if every candidate is locked. The scheduled job drains idle backlog and rows skipped during contention. If the recorder is disabled for emergency repairs, only the scheduled cleanup runs. An expired ticket cannot authorize a download while its row awaits deletion. The gateway checks the signature as today and then requires the matching unexpired row. The check is one more condition in the statement that already resolves the ticket's login. A media request therefore makes no extra round trip, and each byte-range request costs one more index probe. A test counts the statements of a download request before and after. @@ -371,7 +375,7 @@ A log that nobody can read cheaply proves nothing. Two readers exist, and each o - rights that the web app's role holds on the log, `schema_releases`, ticket rows and, table-wide, the locked tables beyond what the grants script gives it; - create rights that a role other than a superuser, the schema owner or `pg_database_owner` holds on the database or on a schema outside `pg_catalog` and `information_schema`, and schemas that a role other than the schema owner, the bootstrap superuser or `pg_database_owner` owns. -**Credential coverage.** The first check scans the credential tables on demand. The operator chooses the time page. A wider page reads the tables fewer times during a catch-up but makes more log lookups. The sweep has a fixed target, and each pass repeats the preceding hour. Each credential and its indexed lookup use one snapshot. The lookup excludes records older than the credential. An identifier reused with the same creation time cannot be distinguished by this check. The audit role's grants stay narrow. The operator reads the migration time once as schema owner. The check clips its lower edge to that time and the 90-day retention floor. It reports a gap if retention has overtaken the checkpoint. +**Credential coverage.** The on-demand check reads one primary-key page from one credential table at a time. It applies the time window after taking the page, so a quiet interval does not make PostgreSQL scan past the page. A sweep checks rows with creation times at least an hour old. That closed cohort lets the primary-key cursor advance without a long-lived database snapshot. A transaction open for more than an hour or an explicitly backdated credential can fall outside this check. The next sweep repeats the last hour. The log lookup excludes records older than the credential. Reuse with the same creation time cannot be distinguished. The audit role's grants stay narrow. The owner reads the migration time once; the check clips its lower edge to that time and the retention floor and reports an unverified gap if retention overtook the checkpoint. **Recorded issuances.** The recorded-issuance checks use a separate numeric checkpoint and a fixed greatest identifier for the sweep. Each pass reads one new page through the primary key. It also checks identifiers at or below the checkpoint whose transaction-start time falls within the previous snapshot's replay window. The replay uses the partial time index and excludes the backfill. The backfill committed together and is covered by the new pages. Identifier order need not match transaction-start order. An uncommitted record therefore stays eligible for the next replay even if a later identifier has an earlier timestamp. The replay covers transactions open for up to one hour. Longer transactions can fall outside it. A checkpoint advances only after the queries succeed. diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-cloud-service-credentials/spec.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-cloud-service-credentials/spec.md index 7ba256fe..274e6c20 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-cloud-service-credentials/spec.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-cloud-service-credentials/spec.md @@ -40,6 +40,11 @@ This requirement binds every role except the schema owner. The database SHALL re A database trigger SHALL revoke every unrevoked service credential of a tenant when its cell becomes deleted or a cell not yet deleted is deleted, at the database clock's time with no revoking principal. The migration SHALL do the same for each tenant with only deleted cells. No other tenant's credential SHALL change. The credential's issuance record SHALL then end. A second trigger SHALL refuse a new credential for a tenant with no cell that is not deleted, and lock that cell's row. +#### Scenario: A transaction with a fixed snapshot deletes a cell + +- **WHEN** a transaction running outside read committed tries to delete a live cell or set it to deleted +- **THEN** the database refuses the deletion and the cell and its credentials keep their state + #### Scenario: An account's deletion finishes - **WHEN** an owner confirms the account's deletion and the finish scrubs the tenant diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md index 987591ec..8481f39d 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md @@ -300,7 +300,7 @@ An issuance record SHALL be kept until at least 90 days after its credential exp ### Requirement: The issuance log is read in bounded ranges, without the schema-owner credential -A read-only audit role SHALL hold select on the issuance log and on the columns that its checks compare, and no other right. Each documented read of the log SHALL use an indexed lookup or read a bounded range. The check for credential rows without a record SHALL also read the credential tables in full, and the operator SHALL run it on demand. A reader SHALL be able to list one tenant's records a page at a time through an index. +A read-only audit role SHALL hold select on the issuance log and on the columns that its checks compare, and no other right. Each documented read of the log SHALL use an indexed lookup or read a bounded range. The on-demand credential check SHALL page through each source table by its primary key. A reader SHALL be able to list one tenant's records a page at a time through an index. #### Scenario: The audit role reads the log @@ -320,7 +320,8 @@ A read-only audit role SHALL hold select on the issuance log and on the columns - **THEN** it looks up the credential kind and identifier for credentials created in the last 90 days and from the second migration onward - **AND** a record from before a credential's creation cannot cover a later reuse of its identifier - **AND** a credential older than 90 days is not listed, because the prune may have deleted its record, and that includes a live service credential -- **AND** each pass covers its lower time edge and leaves its upper time edge to the next pass +- **AND** the fixed upper time edge is no later than one hour before the sweep starts +- **AND** the next sweep includes the upper time edge - **AND** a missing credential is listed even if pruning removed the closest issuance records or the log is empty #### Scenario: A record commits late diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md index 63c6903e..9d96aea8 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md @@ -136,7 +136,7 @@ names each decision as D1 to D12. of the issuance log suite in both states of group 5. As the web app's role, setting a cell to `deleted` ends the tenant's credentials and their records at the database clock, and another tenant's stay live. A cell that only - stops changes nothing, and a second update changes nothing. A delete of a + stops changes nothing, and a second update changes nothing. A deletion at a fixed transaction snapshot is refused. A delete of a live cell row by the schema owner ends them, and a delete of an old deleted row beside a live cell does not. The migration ends the live credential of a tenant that has only deleted cells and keeps that of a tenant with a live @@ -258,7 +258,9 @@ without truncate. Neither state holds the trigger right. - [x] 5.7 The gateway refuses a correctly signed ticket that has no row, and serves one that has its row. It refuses one whose path, token family or expiry differs from the stored row. A download request runs as many database - statements as it did before this change. + statements as it did before this change. One new ticket retires one expired row + and keeps both issuance records. Issuance succeeds without deleting a row + when the bounded set of expired candidates is locked. - [ ] 5.8 Cost proof (D7). For comparison with the earlier sample, generate data for 10,000 tenants and a log of 10 million records. With `pgbench`, run the Home mint transaction's statements with and without this change's triggers: five runs each, same @@ -266,9 +268,8 @@ without truncate. Neither state holds the trigger right. the write-ahead-log bytes for each mint, and the measured size of a record. Report `EXPLAIN (ANALYZE, BUFFERS)` of one prune call and of each D12 read. Pass: the median rises by less than one millisecond, the prune reads only - what it deletes, and no D12 read of the log scans the whole log. D12's first - check also reads the credential tables in full, so the run reports its plan - and sets no bound on it. Keep the results as private evidence. The run at + what it deletes, and no D12 read of the log scans the whole log. The credential check + reads a primary-key page from its source table before filtering by time. Keep the results as private evidence. The run at `e8a7c3db` used the predecessor indexes and audit queries. The current indexes change insert cost. Repeat the write proof with the same instrument and run the current D12 queries on the generated log. The 10-million-record @@ -352,13 +353,13 @@ and its date. SELECT 'token_families' AS source, count(*) AS rows_read, count(*) FILTER (WHERE CASE WHEN family.revoked_at IS NOT NULL THEN least(family.expires_at, now()) ELSE family.expires_at END - >= now() - interval '90 days') AS rows_written + >= now() - interval '2160 hours') AS rows_written FROM exomem_oauth_token_families AS family UNION ALL SELECT 'access_tokens', count(*), - count(*) FILTER (WHERE expires_at >= now() - interval '90 days') + count(*) FILTER (WHERE expires_at >= now() - interval '2160 hours') FROM exomem_oauth_access_tokens UNION ALL SELECT 'refresh_tokens', count(*), - count(*) FILTER (WHERE expires_at >= now() - interval '90 days') + count(*) FILTER (WHERE expires_at >= now() - interval '2160 hours') FROM exomem_oauth_refresh_tokens UNION ALL SELECT 'service_credentials', count(*), count(*) FROM exomem_cloud_service_credentials; diff --git a/src/lib/exomem-hosted/__tests__/cloud-issuance-log-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-issuance-log-postgres.integration.test.ts index 68cb6082..50113843 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-issuance-log-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-issuance-log-postgres.integration.test.ts @@ -434,6 +434,28 @@ for (const state of STATES) { assert.deepEqual(await recordEnd(world.serviceCredentialId), { open: false, at_now: true }); }); + it("refuses cell deletion in a transaction with a fixed snapshot", async () => { + const world = await seedWorld(fx.owner); + const transaction = await fx.app.connect(); + try { + await transaction.query("BEGIN ISOLATION LEVEL REPEATABLE READ"); + await assert.rejects( + transaction.query(`UPDATE ${cells()} SET desired_state = 'deleted' WHERE cell_id = $1`, [ + world.cellId, + ]), + { code: "0A000", message: /must use READ COMMITTED/ } + ); + } finally { + await transaction.query("ROLLBACK"); + transaction.release(); + } + assert.equal((await credentialState(world.serviceCredentialId)).revoked, false); + const state = await fx.owner.query(`SELECT desired_state FROM ${cells()} WHERE cell_id = $1`, [ + world.cellId, + ]); + assert.equal(state.rows[0]?.desired_state, "running"); + }); + // A service credential is inserted only for a tenant with a live cell, and the insert locks // that cell's row. These run as the web app's role, which mints credentials. Each connection // has a statement timeout, so a lock that waits for the wrong thing fails the test. @@ -703,8 +725,8 @@ for (const state of STATES) { [world.familyId, randomBytes(32).toString("hex")] ) ).rows[0]!.id; - const expired = await ticket("interval '-1 hour'"); const live = await ticket("interval '10 minutes'"); + const expired = await ticket("interval '-1 hour'"); __setExomemSqlForTests(tagged(fx.app)); try { const result = await pruneIssuanceState(); @@ -722,6 +744,69 @@ for (const state of STATES) { [live] ); }); + + it("removes one expired ticket on issuance and keeps both issuance records", async () => { + const tickets = fx.q("exomem_cloud_download_tickets"); + const expired = await fx.app.query<{ id: string }>( + `INSERT INTO ${tickets} (family_id, path_sha256, expires_at) + VALUES ($1, $2, now() - interval '1 minute') RETURNING id`, + [world.familyId, randomBytes(32).toString("hex")] + ); + const live = await fx.app.query<{ id: string }>( + `INSERT INTO ${tickets} (family_id, path_sha256, expires_at) + VALUES ($1, $2, now() + interval '10 minutes') RETURNING id`, + [world.familyId, randomBytes(32).toString("hex")] + ); + const ids = [expired.rows[0]!.id, live.rows[0]!.id]; + const retained = await fx.app.query<{ id: string }>( + `SELECT id FROM ${tickets} WHERE id = ANY($1::uuid[])`, + [ids] + ); + assert.deepEqual(retained.rows.map((row) => row.id), [live.rows[0]!.id]); + const recorded = await fx.owner.query<{ credential_id: string }>( + `SELECT credential_id FROM ${log()} WHERE credential_id = ANY($1::uuid[])`, + [ids] + ); + assert.deepEqual(recorded.rows.map((row) => row.credential_id).sort(), ids.sort()); + }); + + it("issues the ticket when all cleanup candidates are locked", async () => { + const tickets = fx.q("exomem_cloud_download_tickets"); + const seeded = await fx.owner.query<{ id: string }>( + `INSERT INTO ${tickets} (family_id, path_sha256, expires_at) + SELECT $1, encode(public.gen_random_bytes(32), 'hex'), now() + n * interval '1 minute' + FROM generate_series(1, 33) AS n RETURNING id`, + [world.familyId] + ); + const ids = seeded.rows.map((row) => row.id); + await fx.owner.query( + `UPDATE ${tickets} SET expires_at = expires_at - interval '1 hour' WHERE id = ANY($1::uuid[])`, + [ids] + ); + const locks = await fx.owner.connect(); + try { + await locks.query("BEGIN"); + await locks.query( + `SELECT id FROM ${tickets} WHERE id = ANY($1::uuid[]) + ORDER BY expires_at LIMIT 32 FOR UPDATE`, + [ids] + ); + const issued = await fx.app.query<{ id: string }>( + `INSERT INTO ${tickets} (family_id, path_sha256, expires_at) + VALUES ($1, $2, now() + interval '10 minutes') RETURNING id`, + [world.familyId, randomBytes(32).toString("hex")] + ); + assert.ok(issued.rows[0]?.id); + const remaining = await fx.app.query( + `SELECT id FROM ${tickets} WHERE id = ANY($1::uuid[])`, + [ids] + ); + assert.equal(remaining.rows.length, ids.length); + } finally { + await locks.query("ROLLBACK"); + locks.release(); + } + }); } ); } diff --git a/src/lib/exomem-hosted/issuance-maintenance.ts b/src/lib/exomem-hosted/issuance-maintenance.ts index 0ce663b5..5fd338b9 100644 --- a/src/lib/exomem-hosted/issuance-maintenance.ts +++ b/src/lib/exomem-hosted/issuance-maintenance.ts @@ -1,7 +1,6 @@ import { executeExomemSql as sql } from "./db"; -// One run deletes at most this many expired ticket rows. A ticket row lives a day at most, -// so a minute-by-minute run clears any backlog far faster than rows arrive. +// The job drains idle backlog and rows that issuance skipped because of locks. const TICKET_BATCH = 1000; export type IssuancePruneResult = { From 37f7098dd37f78c4d2c33129f0726ff288c5b7ff Mon Sep 17 00:00:00 2001 From: Artexis10 Date: Wed, 2 Dec 2026 18:12:29 +0000 Subject: [PATCH 29/29] docs: clarify download ticket expiry and cleanup --- docs/runbooks/exomem-cloud-operations.md | 3 ++- .../0102_exomem_issuance_log_and_download_tickets.sql | 8 ++++---- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/docs/runbooks/exomem-cloud-operations.md b/docs/runbooks/exomem-cloud-operations.md index 4e403a54..ebdfc40d 100644 --- a/docs/runbooks/exomem-cloud-operations.md +++ b/docs/runbooks/exomem-cloud-operations.md @@ -1217,7 +1217,8 @@ statement that finds the ticket's login, so a download makes no extra database r from the gateway. The owner asks for the download again. - The web app's role may select, insert and delete ticket rows. The gateway's role reads `family_id`, `path_sha256` and `expires_at`. No role can update a row. -- The reconcile job deletes up to 1000 expired rows a run, through the index on `expires_at`. A row lives one day at most. +- A ticket authorises a download for at most one day. Expired rows stay in the table until cleanup. +- The reconcile job deletes up to 1000 expired rows a run through the index on `expires_at`. - The row table has no foreign key and holds no grant. The recording trigger reads the grant, the tenant and the user through the token family. An insert for a family that does not exist fails, because the recording fails closed. A role that can insert a row can name another tenant's family, and the gateway then admits the ticket. The issuance log diff --git a/migrations/0102_exomem_issuance_log_and_download_tickets.sql b/migrations/0102_exomem_issuance_log_and_download_tickets.sql index a0c7048f..ee68f05a 100644 --- a/migrations/0102_exomem_issuance_log_and_download_tickets.sql +++ b/migrations/0102_exomem_issuance_log_and_download_tickets.sql @@ -73,10 +73,10 @@ CREATE TRIGGER exomem_cloud_issuance_log_owner_only_truncate FOR EACH STATEMENT EXECUTE FUNCTION exomem_refuse_unless_schema_owner(); -- A download ticket is a signed message, and no row backed it. The web app now --- stores one row for each ticket, and the gateway requires it. A row lives at --- most one day. No foreign key: the gateway joins the token family when it --- uses the ticket, and the recording function reads the grant, tenant and user --- through the family. The row names no grant, because nothing would read it. +-- stores one row for each ticket, and the gateway requires it. Cleanup deletes +-- expired rows. The gateway joins the token family when it uses the ticket. +-- The recording function reads the grant, tenant and user through the family. +-- Those lookups need only the family ID, so the row needs no foreign key or grant. CREATE TABLE exomem_cloud_download_tickets ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), family_id uuid NOT NULL,