From 77646c5ea1b087806721417c676ac4bffb1d20b5 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Wed, 11 Nov 2026 06:15:29 +0000 Subject: [PATCH] GEN-2871 stage encrypted rotation generations --- .../0035_encrypted_generation_staging.sql | 63 ++++++++++++ .../encrypted-integration-repository.ts | 96 ++++++++++++++++++ ...ed-integration-repository.postgres.test.ts | 97 ++++++++++++++++++- 3 files changed, 255 insertions(+), 1 deletion(-) create mode 100644 packages/api/migrations/0035_encrypted_generation_staging.sql diff --git a/packages/api/migrations/0035_encrypted_generation_staging.sql b/packages/api/migrations/0035_encrypted_generation_staging.sql new file mode 100644 index 00000000..f78674da --- /dev/null +++ b/packages/api/migrations/0035_encrypted_generation_staging.sql @@ -0,0 +1,63 @@ +CREATE TABLE app.integration_generation_journal ( + tenant_id uuid NOT NULL REFERENCES app.integration_collections(tenant_id) ON DELETE CASCADE, + generation_id uuid NOT NULL, + expected_revision bigint NOT NULL CHECK (expected_revision >= 0), + content_hash text NOT NULL CHECK (length(content_hash) = 64), + state text NOT NULL CHECK (state IN ('staged','committed','rolled_back','expired')), + committed_revision bigint, + created_at timestamptz NOT NULL DEFAULT now(), + committed_at timestamptz, + PRIMARY KEY (tenant_id,generation_id), + CHECK ((state = 'committed' AND committed_revision IS NOT NULL AND committed_at IS NOT NULL) + OR state <> 'committed') +); +CREATE INDEX integration_generation_cleanup ON app.integration_generation_journal(created_at,tenant_id) + WHERE state IN ('staged','committed','rolled_back','expired'); + +-- These tables contain metadata and user ciphertext only. The archive tables +-- retain one prior generation so a just-committed rotation can be rolled back. +CREATE TABLE app.integration_generation_records ( + tenant_id uuid NOT NULL, + generation_id uuid NOT NULL, + id uuid NOT NULL, + kind text NOT NULL CHECK (kind IN ('bearer','model')), + name text NOT NULL, + origin text, + description text, + revision bigint NOT NULL CHECK (revision > 0), + encrypted_payload text, + deleted_at timestamptz, + PRIMARY KEY (tenant_id,generation_id,id), + FOREIGN KEY (tenant_id,generation_id) REFERENCES app.integration_generation_journal(tenant_id,generation_id) ON DELETE CASCADE, + CHECK ((kind = 'bearer' AND origin IS NOT NULL) OR (kind = 'model' AND origin IS NULL)), + CHECK ((deleted_at IS NULL AND encrypted_payload IS NOT NULL) OR (deleted_at IS NOT NULL AND encrypted_payload IS NULL)) +); +CREATE TABLE app.integration_generation_changes ( + tenant_id uuid NOT NULL, + generation_id uuid NOT NULL, + revision bigint NOT NULL CHECK (revision > 0), + id uuid NOT NULL, + idempotency_key uuid NOT NULL, + operation text NOT NULL CHECK (operation IN ('upsert','delete')), + record_id uuid NOT NULL, + kind text NOT NULL CHECK (kind IN ('bearer','model')), + name text NOT NULL, + origin text, + description text, + encrypted_payload text, + PRIMARY KEY (tenant_id,generation_id,revision), + UNIQUE (tenant_id,generation_id,idempotency_key), + FOREIGN KEY (tenant_id,generation_id) REFERENCES app.integration_generation_journal(tenant_id,generation_id) ON DELETE CASCADE, + CHECK ((kind = 'bearer' AND origin IS NOT NULL) OR (kind = 'model' AND origin IS NULL)), + CHECK ((operation = 'upsert' AND encrypted_payload IS NOT NULL) OR (operation = 'delete' AND encrypted_payload IS NULL)) +); +CREATE TABLE app.integration_generation_previous_records (LIKE app.integration_records INCLUDING DEFAULTS); +ALTER TABLE app.integration_generation_previous_records ADD COLUMN generation_id uuid NOT NULL; +ALTER TABLE app.integration_generation_previous_records ADD PRIMARY KEY (tenant_id,generation_id,id); +ALTER TABLE app.integration_generation_previous_records ADD FOREIGN KEY (tenant_id) REFERENCES app.integration_collections(tenant_id) ON DELETE CASCADE; +ALTER TABLE app.integration_generation_previous_records ADD FOREIGN KEY (tenant_id,generation_id) REFERENCES app.integration_generation_journal(tenant_id,generation_id) ON DELETE CASCADE; +CREATE TABLE app.integration_generation_previous_changes (LIKE app.integration_changes INCLUDING DEFAULTS); +ALTER TABLE app.integration_generation_previous_changes ADD COLUMN generation_id uuid NOT NULL; +ALTER TABLE app.integration_generation_previous_changes ADD PRIMARY KEY (tenant_id,generation_id,revision); +ALTER TABLE app.integration_generation_previous_changes ADD FOREIGN KEY (tenant_id) REFERENCES app.integration_collections(tenant_id) ON DELETE CASCADE; +ALTER TABLE app.integration_generation_previous_changes ADD FOREIGN KEY (tenant_id,generation_id) REFERENCES app.integration_generation_journal(tenant_id,generation_id) ON DELETE CASCADE; diff --git a/packages/api/src/postgres/encrypted-integration-repository.ts b/packages/api/src/postgres/encrypted-integration-repository.ts index 4edea45d..095f6d03 100644 --- a/packages/api/src/postgres/encrypted-integration-repository.ts +++ b/packages/api/src/postgres/encrypted-integration-repository.ts @@ -16,12 +16,18 @@ export type IntegrationChange = IntegrationMetadata & { encryptedPayload: string | null; }; +export type GenerationRecord = IntegrationMetadata & { revision: number; encryptedPayload: string | null; deletedAt: Date | null }; +export type GenerationChange = IntegrationMetadata & { revision: number; idempotencyKey: string; operation: "upsert" | "delete"; encryptedPayload: string | null }; + export class StaleIntegrationRevisionError extends Error { constructor(readonly currentRevision: number) { super("Integration collection revision is stale"); this.name = "StaleIntegrationRevisionError"; } } export class IntegrationIdempotencyConflictError extends Error { constructor() { super("Integration idempotency key was already used for a different change"); this.name = "IntegrationIdempotencyConflictError"; } } +export class StaleIntegrationGenerationError extends Error { + constructor(readonly currentRevision: number) { super("Integration generation changed while rotation was staged"); this.name = "StaleIntegrationGenerationError"; } +} export class IntegrationValidationError extends Error { constructor(message: string) { super(message); this.name = "IntegrationValidationError"; } } @@ -126,4 +132,94 @@ export class EncryptedIntegrationRepository { const { rows } = await this.database.pool.query("SELECT revision,operation,record_id,kind,name,origin,description,encrypted_payload FROM app.integration_changes WHERE tenant_id=$1 AND revision>$2 ORDER BY revision LIMIT $3", [this.tenantId, revision, limit]); return Promise.all(rows.map(async row => ({ id: row.record_id, kind: row.kind, name: row.name, origin: row.origin, description: row.description, revision: safeRevision(row.revision), operation: row.operation, encryptedPayload: row.encrypted_payload === null ? null : await decrypt(row.encrypted_payload, this.serverEncryptionKey) }))); } + + /** Store one complete replacement generation. Payloads must already be user-encrypted. */ + async stageGeneration(input: { generationId: string; expectedRevision: number; records: GenerationRecord[]; changes: GenerationChange[] }): Promise<{ duplicate: boolean }> { + const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + if (!uuid.test(input.generationId) || !Number.isSafeInteger(input.expectedRevision) || input.expectedRevision < 0) throw new IntegrationValidationError("generationId and expectedRevision are invalid"); + if (input.records.length > 5000 || input.changes.length > 10000) throw new IntegrationValidationError("generation exceeds staging limits"); + for (const record of input.records) { + if (!uuid.test(record.id) || (record.encryptedPayload !== null && !isUserCiphertext(record.encryptedPayload)) || (record.deletedAt === null) !== (record.encryptedPayload !== null)) throw new IntegrationValidationError("generation records must contain ciphertext or a tombstone"); + } + for (const change of input.changes) { + if (!uuid.test(change.id) || !uuid.test(change.idempotencyKey) || !Number.isSafeInteger(change.revision) || change.revision < 1 || (change.encryptedPayload !== null && !isUserCiphertext(change.encryptedPayload)) || (change.operation === "upsert") !== (change.encryptedPayload !== null)) throw new IntegrationValidationError("generation changes must contain ordered ciphertext or tombstones"); + } + const canonical = JSON.stringify({ + records: [...input.records].sort((a,b) => a.id.localeCompare(b.id)).map(row => ({ ...row, deletedAt: row.deletedAt?.toISOString() ?? null })), + changes: [...input.changes].sort((a,b) => a.revision - b.revision).map(row => ({ ...row })), + }); + const hashBytes = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(canonical))); + const contentHash = Array.from(hashBytes, byte => byte.toString(16).padStart(2,"0")).join(""); + return this.database.transaction(async client => { + const prior = (await client.query<{ expected_revision: string | number; state: string; content_hash: string }>("SELECT expected_revision,state,content_hash FROM app.integration_generation_journal WHERE tenant_id=$1 AND generation_id=$2 FOR UPDATE", [this.tenantId, input.generationId])).rows[0]; + if (prior) { + if (safeRevision(prior.expected_revision) !== input.expectedRevision || prior.content_hash !== contentHash || prior.state === "expired" || prior.state === "rolled_back") throw new IntegrationIdempotencyConflictError(); + return { duplicate: true }; + } + await client.query("INSERT INTO app.integration_generation_journal(tenant_id,generation_id,expected_revision,content_hash,state) VALUES($1,$2,$3,$4,'staged')", [this.tenantId, input.generationId, input.expectedRevision,contentHash]); + for (const row of input.records) await client.query(`INSERT INTO app.integration_generation_records(tenant_id,generation_id,id,kind,name,origin,description,revision,encrypted_payload,deleted_at) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`, [this.tenantId,input.generationId,row.id,row.kind,row.name,row.origin,row.description,row.revision,row.encryptedPayload,row.deletedAt]); + for (const row of input.changes) await client.query(`INSERT INTO app.integration_generation_changes(tenant_id,generation_id,revision,id,idempotency_key,operation,record_id,kind,name,origin,description,encrypted_payload) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)`, [this.tenantId,input.generationId,row.revision,row.id,row.idempotencyKey,row.operation,row.id,row.kind,row.name,row.origin,row.description,row.encryptedPayload]); + return { duplicate: false }; + }); + } + + /** Atomically archive and replace records, tombstones, changes and the collection revision. */ + async commitGeneration(generationId: string, expectedRevision: number): Promise<{ revision: number; duplicate: boolean }> { + return this.database.transaction(async client => { + await client.query("INSERT INTO app.integration_collections(tenant_id) VALUES($1) ON CONFLICT DO NOTHING", [this.tenantId]); + const collection = (await client.query<{ revision: string | number }>("SELECT revision FROM app.integration_collections WHERE tenant_id=$1 FOR UPDATE", [this.tenantId])).rows[0]!; + const current = safeRevision(collection.revision); + const journal = (await client.query<{ expected_revision: string | number; state: string; committed_revision: string | number | null }>("SELECT expected_revision,state,committed_revision FROM app.integration_generation_journal WHERE tenant_id=$1 AND generation_id=$2 FOR UPDATE", [this.tenantId,generationId])).rows[0]; + if (!journal || safeRevision(journal.expected_revision) !== expectedRevision) throw new IntegrationValidationError("staged generation was not found for this revision"); + if (journal.state === "committed") return { revision: safeRevision(journal.committed_revision!), duplicate: true }; + if (journal.state !== "staged") throw new IntegrationValidationError("staged generation is no longer available"); + if (current !== expectedRevision) throw new StaleIntegrationGenerationError(current); + await client.query("DELETE FROM app.integration_generation_previous_records WHERE tenant_id=$1", [this.tenantId]); + await client.query("DELETE FROM app.integration_generation_previous_changes WHERE tenant_id=$1", [this.tenantId]); + await client.query(`INSERT INTO app.integration_generation_previous_records(tenant_id,id,kind,name,origin,description,revision,encrypted_payload,deleted_at,created_at,updated_at,generation_id) SELECT tenant_id,id,kind,name,origin,description,revision,encrypted_payload,deleted_at,created_at,updated_at,$2 FROM app.integration_records WHERE tenant_id=$1`, [this.tenantId,generationId]); + await client.query(`INSERT INTO app.integration_generation_previous_changes(tenant_id,revision,id,idempotency_key,operation,record_id,kind,name,origin,description,encrypted_payload,created_at,generation_id) SELECT tenant_id,revision,id,idempotency_key,operation,record_id,kind,name,origin,description,encrypted_payload,created_at,$2 FROM app.integration_changes WHERE tenant_id=$1`, [this.tenantId,generationId]); + await client.query("DELETE FROM app.integration_records WHERE tenant_id=$1", [this.tenantId]); + const records = (await client.query<{ id: string; kind: EncryptedIntegrationKind; name: string; origin: string | null; description: string | null; revision: string | number; encrypted_payload: string | null; deleted_at: Date | null }>("SELECT id,kind,name,origin,description,revision,encrypted_payload,deleted_at FROM app.integration_generation_records WHERE tenant_id=$1 AND generation_id=$2", [this.tenantId,generationId])).rows; + for (const row of records) await client.query(`INSERT INTO app.integration_records(tenant_id,id,kind,name,origin,description,revision,encrypted_payload,deleted_at) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9)`, [this.tenantId,row.id,row.kind,row.name,row.origin,row.description,row.revision,row.encrypted_payload === null ? null : await encrypt(row.encrypted_payload,this.serverEncryptionKey),row.deleted_at]); + await client.query("DELETE FROM app.integration_changes WHERE tenant_id=$1", [this.tenantId]); + const changes = (await client.query<{ revision: string | number; id: string; idempotency_key: string; operation: "upsert" | "delete"; record_id: string; kind: EncryptedIntegrationKind; name: string; origin: string | null; description: string | null; encrypted_payload: string | null }>("SELECT revision,id,idempotency_key,operation,record_id,kind,name,origin,description,encrypted_payload FROM app.integration_generation_changes WHERE tenant_id=$1 AND generation_id=$2 ORDER BY revision", [this.tenantId,generationId])).rows; + for (const row of changes) await client.query(`INSERT INTO app.integration_changes(tenant_id,revision,id,idempotency_key,operation,record_id,kind,name,origin,description,encrypted_payload) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)`, [this.tenantId,row.revision,row.id,row.idempotency_key,row.operation,row.record_id,row.kind,row.name,row.origin,row.description,row.encrypted_payload === null ? null : await encrypt(row.encrypted_payload,this.serverEncryptionKey)]); + const revision = current + 1; + await client.query("UPDATE app.integration_collections SET revision=$2,updated_at=now() WHERE tenant_id=$1", [this.tenantId,revision]); + await client.query("UPDATE app.integration_generation_journal SET state='committed',committed_revision=$3,committed_at=now() WHERE tenant_id=$1 AND generation_id=$2", [this.tenantId,generationId,revision]); + return { revision, duplicate: false }; + }); + } + + /** Restore the previous generation only while this commit is still the active revision. */ + async rollbackGeneration(generationId: string): Promise { + return this.database.transaction(async client => { + const collection = (await client.query<{ revision: string | number }>("SELECT revision FROM app.integration_collections WHERE tenant_id=$1 FOR UPDATE", [this.tenantId])).rows[0]; + const journal = (await client.query<{ state: string; committed_revision: string | number | null }>("SELECT state,committed_revision FROM app.integration_generation_journal WHERE tenant_id=$1 AND generation_id=$2 FOR UPDATE", [this.tenantId,generationId])).rows[0]; + if (!collection || !journal || journal.state !== "committed") throw new IntegrationValidationError("committed generation is not available for rollback"); + const current = safeRevision(collection.revision); + if (current !== safeRevision(journal.committed_revision!)) throw new StaleIntegrationGenerationError(current); + await client.query("DELETE FROM app.integration_records WHERE tenant_id=$1", [this.tenantId]); + await client.query(`INSERT INTO app.integration_records(tenant_id,id,kind,name,origin,description,revision,encrypted_payload,deleted_at,created_at,updated_at) SELECT tenant_id,id,kind,name,origin,description,revision,encrypted_payload,deleted_at,created_at,updated_at FROM app.integration_generation_previous_records WHERE tenant_id=$1 AND generation_id=$2`, [this.tenantId,generationId]); + await client.query("DELETE FROM app.integration_changes WHERE tenant_id=$1", [this.tenantId]); + await client.query(`INSERT INTO app.integration_changes(tenant_id,revision,id,idempotency_key,operation,record_id,kind,name,origin,description,encrypted_payload,created_at) SELECT tenant_id,revision,id,idempotency_key,operation,record_id,kind,name,origin,description,encrypted_payload,created_at FROM app.integration_generation_previous_changes WHERE tenant_id=$1 AND generation_id=$2`, [this.tenantId,generationId]); + const revision = current + 1; + await client.query("UPDATE app.integration_collections SET revision=$2,updated_at=now() WHERE tenant_id=$1", [this.tenantId,revision]); + await client.query("UPDATE app.integration_generation_journal SET state='rolled_back' WHERE tenant_id=$1 AND generation_id=$2", [this.tenantId,generationId]); + return revision; + }); + } + + /** Delete at most `limit` expired journals; committed archives are retained for at most maxAgeMs. */ + async cleanupGenerations(maxAgeMs: number, limit = 100): Promise { + if (!Number.isSafeInteger(maxAgeMs) || maxAgeMs < 0 || !Number.isSafeInteger(limit) || limit < 1 || limit > 500) throw new IntegrationValidationError("cleanup bounds are invalid"); + return this.database.transaction(async client => { + const expired = (await client.query<{ generation_id: string }>(`SELECT generation_id FROM app.integration_generation_journal WHERE tenant_id=$1 AND created_at < now() - ($2::bigint * interval '1 millisecond') ORDER BY created_at LIMIT $3 FOR UPDATE`, [this.tenantId,maxAgeMs,limit])).rows.map(row => row.generation_id); + if (!expired.length) return 0; + await client.query("DELETE FROM app.integration_generation_previous_records WHERE tenant_id=$1 AND generation_id=ANY($2::uuid[])", [this.tenantId,expired]); + await client.query("DELETE FROM app.integration_generation_previous_changes WHERE tenant_id=$1 AND generation_id=ANY($2::uuid[])", [this.tenantId,expired]); + await client.query("DELETE FROM app.integration_generation_journal WHERE tenant_id=$1 AND generation_id=ANY($2::uuid[])", [this.tenantId,expired]); + return expired.length; + }); + } } diff --git a/packages/api/test/encrypted-integration-repository.postgres.test.ts b/packages/api/test/encrypted-integration-repository.postgres.test.ts index 63045715..1d8c8331 100644 --- a/packages/api/test/encrypted-integration-repository.postgres.test.ts +++ b/packages/api/test/encrypted-integration-repository.postgres.test.ts @@ -3,7 +3,7 @@ import { readdir, readFile } from "node:fs/promises"; import pg from "pg"; import { decrypt } from "../src/crypto"; import { Database } from "../src/postgres/database"; -import { EncryptedIntegrationRepository, IntegrationIdempotencyConflictError, StaleIntegrationRevisionError } from "../src/postgres/encrypted-integration-repository"; +import { EncryptedIntegrationRepository, IntegrationIdempotencyConflictError, StaleIntegrationGenerationError, StaleIntegrationRevisionError } from "../src/postgres/encrypted-integration-repository"; const url = process.env.AUTH_TEST_DATABASE_URL; const serverKey = btoa("s".repeat(32)); @@ -94,4 +94,99 @@ describe.skipIf(!url)("encrypted integration persistence (PostgreSQL)", () => { expect(tombstone.rows[0].deleted_at).toBeInstanceOf(Date); await expect(repository.write({ ...first, name: "Different operation with same key" })).rejects.toBeInstanceOf(IntegrationIdempotencyConflictError); }); + + it("stages ciphertext only, atomically replaces the whole generation, and makes a lost commit reply retryable", async () => { + const { repository, tenantId } = await freshRepository(); + const id = crypto.randomUUID(), original = await userEncrypt("old credential fixture"), rotated = await userEncrypt("rotated credential fixture"); + const tombstoneId = crypto.randomUUID(), tombstoneCipher = await userEncrypt("deleted credential fixture"); + const write = { id, idempotencyKey: crypto.randomUUID(), expectedRevision: 0, operation: "upsert" as const, kind: "bearer" as const, name: "Rotation", origin: "https://rotation.example.test", description: null, encryptedPayload: original }; + await repository.write(write); + const tombstoneWrite = { id: tombstoneId, idempotencyKey: crypto.randomUUID(), expectedRevision: 1, operation: "upsert" as const, kind: "model" as const, name: "Retired", origin: null, description: null, encryptedPayload: tombstoneCipher }; + await repository.write(tombstoneWrite); + const tombstoneRevision = (await repository.write({ ...tombstoneWrite, expectedRevision: 2, idempotencyKey: crypto.randomUUID(), operation: "delete", encryptedPayload: undefined })).revision; + const baseRevision = tombstoneRevision; + const generationId = crypto.randomUUID(); + const snapshot = { records: [ + { id, kind: "bearer" as const, name: "Rotation", origin: write.origin, description: null, revision: 1, encryptedPayload: rotated, deletedAt: null }, + { id: tombstoneId, kind: "model" as const, name: "Retired", origin: null, description: null, revision: tombstoneRevision, encryptedPayload: null, deletedAt: new Date() }, + ], changes: [ + { id, idempotencyKey: crypto.randomUUID(), kind: "bearer" as const, name: "Rotation", origin: write.origin, description: null, revision: 1, operation: "upsert" as const, encryptedPayload: rotated }, + { id: tombstoneId, idempotencyKey: crypto.randomUUID(), kind: "model" as const, name: "Retired", origin: null, description: null, revision: 2, operation: "upsert" as const, encryptedPayload: tombstoneCipher }, + { id: tombstoneId, idempotencyKey: crypto.randomUUID(), kind: "model" as const, name: "Retired", origin: null, description: null, revision: tombstoneRevision, operation: "delete" as const, encryptedPayload: null }, + ] }; + expect(await repository.stageGeneration({ generationId, expectedRevision: baseRevision, ...snapshot })).toEqual({ duplicate: false }); + expect(await repository.stageGeneration({ generationId, expectedRevision: baseRevision, ...snapshot })).toEqual({ duplicate: true }); + await expect(repository.stageGeneration({ generationId, expectedRevision: baseRevision, ...snapshot, records: snapshot.records.map(record => record.id === id ? { ...record, encryptedPayload: original } : record) })).rejects.toBeInstanceOf(IntegrationIdempotencyConflictError); + const staged = await db.pool.query("SELECT encrypted_payload FROM app.integration_generation_records WHERE tenant_id=$1 AND generation_id=$2 AND encrypted_payload IS NOT NULL", [tenantId,generationId]); + expect(staged.rows[0].encrypted_payload).toBe(rotated); + expect(JSON.stringify(staged.rows)).not.toContain("rotated credential fixture"); + + await db.pool.query(`CREATE FUNCTION app.reject_rotation_delete() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected pre-commit failure'; END $$`); + await db.pool.query("CREATE TRIGGER reject_rotation_delete BEFORE DELETE ON app.integration_records FOR EACH ROW EXECUTE FUNCTION app.reject_rotation_delete()"); + await expect(repository.commitGeneration(generationId, baseRevision)).rejects.toThrow("injected pre-commit failure"); + expect((await repository.records()).find(record => record.id === id)!.encryptedPayload).toBe(original); + await db.pool.query("DROP TRIGGER reject_rotation_delete ON app.integration_records"); + await db.pool.query("DROP FUNCTION app.reject_rotation_delete()"); + + const lockA = 17391, lockB = 2871; + const gate = await db.pool.connect(); + await db.pool.query(`CREATE FUNCTION app.hold_rotation_insert() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN PERFORM pg_advisory_xact_lock(${lockA},${lockB}); RETURN NEW; END $$`); + await db.pool.query("CREATE TRIGGER hold_rotation_insert BEFORE INSERT ON app.integration_records FOR EACH ROW EXECUTE FUNCTION app.hold_rotation_insert()"); + await gate.query("SELECT pg_advisory_lock($1,$2)", [lockA,lockB]); + try { + const pendingCommit = repository.commitGeneration(generationId, baseRevision); + const deadline = Date.now() + 5_000; + let reachedInsert = false; + while (Date.now() < deadline) { + const waiting = await gate.query("SELECT 1 FROM pg_stat_activity WHERE wait_event_type='Lock' AND datname=current_database() AND pid<>pg_backend_pid() LIMIT 1"); + if (waiting.rowCount) { reachedInsert = true; break; } + await new Promise(resolve => setImmediate(resolve)); + } + expect(reachedInsert, JSON.stringify((await gate.query("SELECT pid,state,wait_event_type,wait_event,query FROM pg_stat_activity WHERE datname=current_database() AND pid<>pg_backend_pid()")).rows)).toBe(true); + expect((await repository.records()).find(record => record.id === id)!.encryptedPayload).toBe(original); + await gate.query("SELECT pg_advisory_unlock($1,$2)", [lockA,lockB]); + await pendingCommit; + } finally { + await gate.query("SELECT pg_advisory_unlock($1,$2)", [lockA,lockB]); + await db.pool.query("DROP TRIGGER hold_rotation_insert ON app.integration_records"); + await db.pool.query("DROP FUNCTION app.hold_rotation_insert()"); + gate.release(); + } + const committed = await repository.commitGeneration(generationId, baseRevision); + expect(committed).toEqual({ revision: baseRevision + 1, duplicate: true }); + // Simulate the caller losing the response after the transaction committed. + expect(await repository.commitGeneration(generationId, baseRevision)).toEqual({ ...committed, duplicate: true }); + await expect(repository.write({ id: crypto.randomUUID(), idempotencyKey: crypto.randomUUID(), expectedRevision: baseRevision, operation: "upsert", kind: "model", name: "Stale generation write", origin: null, description: null, encryptedPayload: await userEncrypt("stale write") })).rejects.toMatchObject({ name: "StaleIntegrationRevisionError", currentRevision: committed.revision }); + expect((await repository.records()).find(record => record.id === id)!.encryptedPayload).toBe(rotated); + const activeTombstone = await db.pool.query("SELECT deleted_at,encrypted_payload FROM app.integration_records WHERE tenant_id=$1 AND id=$2", [tenantId,tombstoneId]); + expect(activeTombstone.rows[0].encrypted_payload).toBeNull(); + expect(activeTombstone.rows[0].deleted_at).toBeInstanceOf(Date); + expect((await repository.changesSince(0)).map(change => change.encryptedPayload)).toEqual([rotated, tombstoneCipher, null]); + }); + + it("rejects a staged generation after concurrent writes and bounds rollback to the active commit", async () => { + const { repository, tenantId } = await freshRepository(); + const originalId = crypto.randomUUID(), original = await userEncrypt("preserved credential"); + const first = await repository.write({ id: originalId, idempotencyKey: crypto.randomUUID(), expectedRevision: 0, operation: "upsert", kind: "model", name: "Preserved", origin: null, description: null, encryptedPayload: original }); + const replacementId = crypto.randomUUID(), replacement = await userEncrypt("replacement credential"); + const staged = { generationId: crypto.randomUUID(), expectedRevision: first.revision, records: [{ id: replacementId, kind: "model" as const, name: "Replacement", origin: null, description: null, revision: first.revision, encryptedPayload: replacement, deletedAt: null }], changes: [{ id: replacementId, idempotencyKey: crypto.randomUUID(), kind: "model" as const, name: "Replacement", origin: null, description: null, revision: first.revision, operation: "upsert" as const, encryptedPayload: replacement }] }; + await repository.stageGeneration(staged); + await repository.write({ id: crypto.randomUUID(), idempotencyKey: crypto.randomUUID(), expectedRevision: first.revision, operation: "upsert", kind: "model", name: "Concurrent", origin: null, description: null, encryptedPayload: await userEncrypt("concurrent edit") }); + await expect(repository.commitGeneration(staged.generationId, first.revision)).rejects.toMatchObject({ name: "StaleIntegrationGenerationError", currentRevision: first.revision + 1 }); + expect((await repository.records()).map(record => record.name)).toEqual(["Preserved", "Concurrent"]); + + const baseRevision = await repository.revision(), rotated = await userEncrypt("rotated preserved credential"), generationId = crypto.randomUUID(); + const activeRecords = await repository.records(); + const currentChanges = await repository.changesSince(0, 500); + await repository.stageGeneration({ generationId, expectedRevision: baseRevision, + records: activeRecords.map(record => ({ ...record, encryptedPayload: record.id === originalId ? rotated : record.encryptedPayload, deletedAt: null })), + changes: currentChanges.map(change => ({ ...change, idempotencyKey: crypto.randomUUID(), encryptedPayload: change.operation === "upsert" && change.id === originalId ? rotated : change.encryptedPayload })) }); + const committed = await repository.commitGeneration(generationId, baseRevision); + expect((await repository.records()).find(record => record.id === originalId)!.encryptedPayload).toBe(rotated); + expect(await repository.rollbackGeneration(generationId)).toBe(committed.revision + 1); + expect((await repository.records()).find(record => record.id === originalId)!.encryptedPayload).toBe(original); + await expect(repository.rollbackGeneration(generationId)).rejects.toThrow("not available for rollback"); + expect(await repository.cleanupGenerations(0, 500)).toBeGreaterThanOrEqual(1); + expect((await db.pool.query("SELECT 1 FROM app.integration_generation_journal WHERE tenant_id=$1 AND generation_id=$2", [tenantId,generationId])).rowCount).toBe(0); + }); });