From 01605939b2d8c8beb5971eda88f72b7671d20bf4 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Wed, 11 Nov 2026 03:42:22 +0000 Subject: [PATCH] feat: persist encrypted integration records --- .../0033_encrypted_integration_records.sql | 45 +++++++ .../encrypted-integration-repository.ts | 118 ++++++++++++++++++ packages/api/src/postgres/schema.ts | 11 +- ...ed-integration-repository.postgres.test.ts | 97 ++++++++++++++ 4 files changed, 270 insertions(+), 1 deletion(-) create mode 100644 packages/api/migrations/0033_encrypted_integration_records.sql create mode 100644 packages/api/src/postgres/encrypted-integration-repository.ts create mode 100644 packages/api/test/encrypted-integration-repository.postgres.test.ts diff --git a/packages/api/migrations/0033_encrypted_integration_records.sql b/packages/api/migrations/0033_encrypted_integration_records.sql new file mode 100644 index 00000000..ed23c7a3 --- /dev/null +++ b/packages/api/migrations/0033_encrypted_integration_records.sql @@ -0,0 +1,45 @@ +CREATE TABLE app.integration_collections ( + tenant_id uuid PRIMARY KEY REFERENCES app.tenants(id) ON DELETE CASCADE, + revision bigint NOT NULL DEFAULT 0 CHECK (revision >= 0), + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now() +); + +CREATE TABLE app.integration_records ( + tenant_id uuid NOT NULL REFERENCES app.integration_collections(tenant_id) ON DELETE CASCADE, + 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, + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (tenant_id,id), + 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 UNIQUE INDEX integration_records_active_name ON app.integration_records(tenant_id,kind,lower(name)) WHERE deleted_at IS NULL; +CREATE INDEX integration_records_collection_order ON app.integration_records(tenant_id,revision,id); + +CREATE TABLE app.integration_changes ( + tenant_id uuid NOT NULL REFERENCES app.integration_collections(tenant_id) ON DELETE CASCADE, + 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, + created_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (tenant_id,revision), + UNIQUE (tenant_id,idempotency_key), + 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 INDEX integration_changes_page ON app.integration_changes(tenant_id,revision); diff --git a/packages/api/src/postgres/encrypted-integration-repository.ts b/packages/api/src/postgres/encrypted-integration-repository.ts new file mode 100644 index 00000000..aa864fa0 --- /dev/null +++ b/packages/api/src/postgres/encrypted-integration-repository.ts @@ -0,0 +1,118 @@ +import { decrypt, encrypt } from "../crypto"; +import type { Database } from "./database"; + +export type EncryptedIntegrationKind = "bearer" | "model"; +export type IntegrationMetadata = { id: string; kind: EncryptedIntegrationKind; name: string; origin: string | null; description: string | null }; +export type IntegrationWrite = IntegrationMetadata & { + expectedRevision: number; + idempotencyKey: string; + operation: "upsert" | "delete"; + /** Ciphertext produced with the user's unlock key. This repository never interprets it. */ + encryptedPayload?: string; +}; +export type IntegrationChange = IntegrationMetadata & { + revision: number; + 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 IntegrationValidationError extends Error { + constructor(message: string) { super(message); this.name = "IntegrationValidationError"; } +} + +type StoredChange = { + revision: string | number; operation: "upsert" | "delete"; record_id: string; kind: EncryptedIntegrationKind; + name: string; origin: string | null; description: string | null; encrypted_payload: string | null; +}; + +function safeRevision(value: string | number): number { + const number = Number(value); + if (!Number.isSafeInteger(number) || number < 0) throw new Error("Stored integration revision exceeds supported range"); + return number; +} + +function validate(change: IntegrationWrite): void { + if (!Number.isSafeInteger(change.expectedRevision) || change.expectedRevision < 0) throw new IntegrationValidationError("expectedRevision must be a non-negative safe integer"); + 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(change.id) || !uuid.test(change.idempotencyKey)) throw new IntegrationValidationError("id and idempotencyKey must be UUIDs"); + if (change.kind !== "bearer" && change.kind !== "model") throw new IntegrationValidationError("Unsupported integration kind"); + if (!change.name.trim() || change.name.length > 120) throw new IntegrationValidationError("name must contain 1 to 120 characters"); + if (change.description !== null && change.description.length > 500) throw new IntegrationValidationError("description must be at most 500 characters"); + if (change.kind === "bearer" && (!change.origin || change.origin.length > 2048)) throw new IntegrationValidationError("bearer integrations require an origin of at most 2048 characters"); + if (change.kind === "model" && change.origin !== null) throw new IntegrationValidationError("model accounts do not have an origin"); + if (change.operation === "upsert" && (typeof change.encryptedPayload !== "string" || !change.encryptedPayload.length)) throw new IntegrationValidationError("upserts require user-encrypted ciphertext"); + if (change.operation === "delete" && change.encryptedPayload !== undefined) throw new IntegrationValidationError("deletions cannot contain ciphertext"); +} + +export class EncryptedIntegrationRepository { + constructor(private database: Database, private tenantId: string, private serverEncryptionKey: string) { + if (!tenantId) throw new Error("tenantId is required"); + } + + async revision(): Promise { + const { rows } = await this.database.pool.query<{ revision: string | number }>("SELECT revision FROM app.integration_collections WHERE tenant_id=$1", [this.tenantId]); + return rows.length ? safeRevision(rows[0]!.revision) : 0; + } + + async write(input: IntegrationWrite): Promise<{ revision: number; duplicate: boolean }> { + validate(input); + const encryptedPayload = input.operation === "upsert" ? await encrypt(input.encryptedPayload!, this.serverEncryptionKey) : null; + const metadata = [input.id, input.kind, input.name, input.origin, input.description, input.operation, encryptedPayload]; + return this.database.transaction(async client => { + const existing = async () => (await client.query("SELECT revision,operation,record_id,kind,name,origin,description,encrypted_payload FROM app.integration_changes WHERE tenant_id=$1 AND idempotency_key=$2", [this.tenantId, input.idempotencyKey])).rows[0]; + const isSame = async (row: StoredChange) => row.record_id === metadata[0] && row.kind === metadata[1] && row.name === metadata[2] && row.origin === metadata[3] && row.description === metadata[4] && row.operation === metadata[5] && (row.encrypted_payload === null ? encryptedPayload === null : encryptedPayload !== null && await decrypt(row.encrypted_payload, this.serverEncryptionKey) === input.encryptedPayload); + const duplicate = await existing(); + if (duplicate) { + if (!await isSame(duplicate)) throw new IntegrationIdempotencyConflictError(); + return { revision: safeRevision(duplicate.revision), duplicate: true }; + } + + await client.query("INSERT INTO app.integration_collections(tenant_id) VALUES ($1) ON CONFLICT DO NOTHING", [this.tenantId]); + const bumped = await client.query<{ revision: string | number }>("UPDATE app.integration_collections SET revision=revision+1,updated_at=now() WHERE tenant_id=$1 AND revision=$2 RETURNING revision", [this.tenantId, input.expectedRevision]); + if (!bumped.rows.length) { + const racedDuplicate = await existing(); + if (racedDuplicate) { + if (!await isSame(racedDuplicate)) throw new IntegrationIdempotencyConflictError(); + return { revision: safeRevision(racedDuplicate.revision), duplicate: true }; + } + const current = await client.query<{ revision: string | number }>("SELECT revision FROM app.integration_collections WHERE tenant_id=$1", [this.tenantId]); + throw new StaleIntegrationRevisionError(safeRevision(current.rows[0]!.revision)); + } + const revision = safeRevision(bumped.rows[0]!.revision); + + if (input.operation === "upsert") { + 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,NULL) + ON CONFLICT (tenant_id,id) DO UPDATE SET kind=excluded.kind,name=excluded.name,origin=excluded.origin,description=excluded.description,revision=excluded.revision,encrypted_payload=excluded.encrypted_payload,deleted_at=NULL,updated_at=now()`, + [this.tenantId, input.id, input.kind, input.name, input.origin, input.description, revision, encryptedPayload]); + } else { + 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,NULL,now()) + ON CONFLICT (tenant_id,id) DO UPDATE SET kind=excluded.kind,name=excluded.name,origin=excluded.origin,description=excluded.description,revision=excluded.revision,encrypted_payload=NULL,deleted_at=now(),updated_at=now()`, + [this.tenantId, input.id, input.kind, input.name, input.origin, input.description, revision]); + } + 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, revision, crypto.randomUUID(), input.idempotencyKey, input.operation, input.id, input.kind, input.name, input.origin, input.description, encryptedPayload]); + return { revision, duplicate: false }; + }); + } + + async records(): Promise> { + const { rows } = await this.database.pool.query<{ id: string; kind: EncryptedIntegrationKind; name: string; origin: string | null; description: string | null; revision: string | number; encrypted_payload: string }>( + "SELECT id,kind,name,origin,description,revision,encrypted_payload FROM app.integration_records WHERE tenant_id=$1 AND deleted_at IS NULL ORDER BY revision,id", [this.tenantId]); + return Promise.all(rows.map(async row => ({ id: row.id, kind: row.kind, name: row.name, origin: row.origin, description: row.description, revision: safeRevision(row.revision), encryptedPayload: await decrypt(row.encrypted_payload, this.serverEncryptionKey) }))); + } + + async changesSince(revision: number, limit = 100): Promise { + if (!Number.isSafeInteger(revision) || revision < 0) throw new IntegrationValidationError("revision must be a non-negative safe integer"); + if (!Number.isSafeInteger(limit) || limit < 1 || limit > 500) throw new IntegrationValidationError("limit must be between 1 and 500"); + 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) }))); + } +} diff --git a/packages/api/src/postgres/schema.ts b/packages/api/src/postgres/schema.ts index bf7fdf6f..f478ad50 100644 --- a/packages/api/src/postgres/schema.ts +++ b/packages/api/src/postgres/schema.ts @@ -41,6 +41,15 @@ export const accessTokens = app.table("access_tokens", { }, t => [primaryKey({ columns: [t.tenantId, t.id] }), foreignKey({ columns: [t.tenantId, t.userId], foreignColumns: [members.tenantId, members.userId] }).onDelete("cascade")]); export const connections = app.table("connections", { tenantId: uuid("tenant_id").notNull().references(() => tenants.id, { onDelete: "cascade" }), kind: text("kind").notNull(), encryptedValue: text("encrypted_value").notNull(), updatedAt: updatedAt() }, t => [primaryKey({ columns: [t.tenantId, t.kind] })]); +export const integrationCollections = app.table("integration_collections", { + tenantId: uuid("tenant_id").primaryKey().references(() => tenants.id, { onDelete: "cascade" }), revision: bigint("revision", { mode: "number" }).notNull().default(0), createdAt: createdAt(), updatedAt: updatedAt(), +}); +export const integrationRecords = app.table("integration_records", { + tenantId: uuid("tenant_id").notNull().references(() => integrationCollections.tenantId, { onDelete: "cascade" }), id: uuid("id").notNull(), kind: text("kind").$type<"bearer" | "model">().notNull(), name: text("name").notNull(), origin: text("origin"), description: text("description"), revision: bigint("revision", { mode: "number" }).notNull(), encryptedPayload: text("encrypted_payload"), deletedAt: timestamp("deleted_at", { withTimezone: true, mode: "date" }), createdAt: createdAt(), updatedAt: updatedAt(), +}, t => [primaryKey({ columns: [t.tenantId, t.id] }), uniqueIndex("integration_records_active_name").on(t.tenantId, t.kind, sql`lower(${t.name})`).where(sql`${t.deletedAt} is null`), index("integration_records_collection_order").on(t.tenantId, t.revision, t.id), check("integration_records_kind_check", sql`${t.kind} IN ('bearer','model')`), check("integration_records_origin_check", sql`(${t.kind} = 'bearer' AND ${t.origin} IS NOT NULL) OR (${t.kind} = 'model' AND ${t.origin} IS NULL)`), check("integration_records_payload_check", sql`(${t.deletedAt} IS NULL AND ${t.encryptedPayload} IS NOT NULL) OR (${t.deletedAt} IS NOT NULL AND ${t.encryptedPayload} IS NULL)`)]); +export const integrationChanges = app.table("integration_changes", { + tenantId: uuid("tenant_id").notNull().references(() => integrationCollections.tenantId, { onDelete: "cascade" }), revision: bigint("revision", { mode: "number" }).notNull(), id: uuid("id").notNull(), idempotencyKey: uuid("idempotency_key").notNull(), operation: text("operation").$type<"upsert" | "delete">().notNull(), recordId: uuid("record_id").notNull(), kind: text("kind").$type<"bearer" | "model">().notNull(), name: text("name").notNull(), origin: text("origin"), description: text("description"), encryptedPayload: text("encrypted_payload"), createdAt: createdAt(), +}, t => [primaryKey({ columns: [t.tenantId, t.revision] }), unique().on(t.tenantId, t.idempotencyKey), index("integration_changes_page").on(t.tenantId, t.revision), check("integration_changes_operation_check", sql`${t.operation} IN ('upsert','delete')`), check("integration_changes_kind_check", sql`${t.kind} IN ('bearer','model')`), check("integration_changes_origin_check", sql`(${t.kind} = 'bearer' AND ${t.origin} IS NOT NULL) OR (${t.kind} = 'model' AND ${t.origin} IS NULL)`), check("integration_changes_payload_check", sql`(${t.operation} = 'upsert' AND ${t.encryptedPayload} IS NOT NULL) OR (${t.operation} = 'delete' AND ${t.encryptedPayload} IS NULL)`)]); export const linearWorkspaces = app.table("linear_workspaces", { organizationId: uuid("organization_id").primaryKey(), tenantId: uuid("tenant_id").notNull().unique().references(() => tenants.id, { onDelete: "cascade" }) }); export const githubInstallations = app.table("github_installations", { installationId: bigint("installation_id", { mode: "number" }).primaryKey(), tenantId: uuid("tenant_id").notNull().references(() => tenants.id, { onDelete: "cascade" }), accountLogin: text("account_login").notNull(), accountType: text("account_type").notNull(), state: text("state").$type<"active" | "suspended">().notNull(), updatedAt: updatedAt() }, t => [unique().on(t.tenantId, t.installationId), check("github_installations_state_check", sql`${t.state} in ('active','suspended')`)]); export const githubSetupStates = app.table("github_setup_states", { tenantId: uuid("tenant_id").notNull().references(() => tenants.id, { onDelete: "cascade" }), nonce: text("nonce").notNull(), expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), usedAt: timestamp("used_at", { withTimezone: true }) }, t => [primaryKey({ columns: [t.tenantId, t.nonce] })]); @@ -137,7 +146,7 @@ export const runRelations = relations(runs, ({ one, many }) => ({ export const databaseSchema = { schemaMigrations, tenants, oauthConnections, oauthConsentPreviews, authUsers, authAccounts, authResetTokens, authSessions, oauthDeviceAuthorizations, members, accessTokens, - connections, linearWorkspaces, githubInstallations, githubSetupStates, projects, jobs, vmImageVerifications, skills, jobSkills, triggers, webhookConditionsCutover, invocations, manualInvocationPermissions, jobRuns, runCredentials, runs, runArtifacts, + connections, integrationCollections, integrationRecords, integrationChanges, linearWorkspaces, githubInstallations, githubSetupStates, projects, jobs, vmImageVerifications, skills, jobSkills, triggers, webhookConditionsCutover, invocations, manualInvocationPermissions, jobRuns, runCredentials, runs, runArtifacts, runTraceEvents, runActivity, activeClaims, scheduleState, automaticWakes, lifecycleDeliveries, lifecycleEvents, jobEditDeliveries, jobEvents, webhookDeliveries, webhookDeliveryEvents, pendingVerifications, tailFingerprints, wakeHints, runTraceCursors, runTraceChunks, runTraceProjections, traceReplayLimits, traceReplayOperations, diff --git a/packages/api/test/encrypted-integration-repository.postgres.test.ts b/packages/api/test/encrypted-integration-repository.postgres.test.ts new file mode 100644 index 00000000..63045715 --- /dev/null +++ b/packages/api/test/encrypted-integration-repository.postgres.test.ts @@ -0,0 +1,97 @@ +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +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"; + +const url = process.env.AUTH_TEST_DATABASE_URL; +const serverKey = btoa("s".repeat(32)); +const userKey = btoa("u".repeat(32)); + +async function userEncrypt(plaintext: string): Promise { + const iv = crypto.getRandomValues(new Uint8Array(12)); + const key = await crypto.subtle.importKey("raw", Uint8Array.from(atob(userKey), c => c.charCodeAt(0)), "AES-GCM", false, ["encrypt"]); + const body = await crypto.subtle.encrypt({ name: "AES-GCM", iv }, key, new TextEncoder().encode(plaintext)); + const encode = (bytes: Uint8Array) => btoa(Array.from(bytes, byte => String.fromCharCode(byte)).join("")); + return `${encode(iv)}.${encode(new Uint8Array(body))}`; +} + +describe.skipIf(!url)("encrypted integration persistence (PostgreSQL)", () => { + let db: Database; + let admin: pg.Client; + let databaseName: string; + beforeAll(async () => { + admin = new pg.Client({ connectionString: url }); + await admin.connect(); + databaseName = `encrypted_integration_${crypto.randomUUID().replaceAll("-", "")}`; + await admin.query(`CREATE DATABASE ${databaseName}`); + const databaseUrl = new URL(url!); databaseUrl.pathname = `/${databaseName}`; + db = new Database({ connectionString: databaseUrl.toString() }); + const migrations = new URL("../migrations/", import.meta.url); + for (const file of (await readdir(migrations)).filter(file => /^\d+.*\.sql$/.test(file)).sort()) await db.pool.query(await readFile(new URL(file, migrations), "utf8")); + const migration = await db.pool.query("SELECT to_regclass('app.integration_collections') AS collection, to_regclass('app.integration_changes') AS changes"); + expect(migration.rows[0]).toEqual({ collection: "app.integration_collections", changes: "app.integration_changes" }); + }, 30_000); + afterAll(async () => { await db?.close(); await admin?.query(`DROP DATABASE IF EXISTS ${databaseName} WITH (FORCE)`); await admin?.end(); }); + + async function freshRepository() { + const tenantId = crypto.randomUUID(); + await db.pool.query("INSERT INTO app.tenants(id) VALUES ($1)", [tenantId]); + return { tenantId, repository: new EncryptedIntegrationRepository(db, tenantId, serverKey) }; + } + + it("encrypts user ciphertext again and server-key access cannot recover synthetic plaintext", async () => { + const plaintext = "synthetic bearer secret that must remain user-encrypted"; + const innerCiphertext = await userEncrypt(plaintext); + const id = crypto.randomUUID(), idempotencyKey = crypto.randomUUID(); + const { tenantId, repository } = await freshRepository(); + await repository.write({ id, idempotencyKey, expectedRevision: 0, operation: "upsert", kind: "bearer", name: "Source", origin: "https://api.example.test", description: "fixture", encryptedPayload: innerCiphertext }); + const stored = (await db.pool.query("SELECT encrypted_payload FROM app.integration_records WHERE tenant_id=$1 AND id=$2", [tenantId, id])).rows[0].encrypted_payload as string; + expect(stored).not.toBe(innerCiphertext); + expect(stored).not.toContain(plaintext); + const returned = (await repository.records())[0]!; + expect(returned.encryptedPayload).toBe(innerCiphertext); + await expect(decrypt(returned.encryptedPayload, serverKey)).rejects.toThrow(); + expect(returned.encryptedPayload).not.toContain(plaintext); + }); + + it("isolates tenants, rejects stale writes, and serializes concurrent conditional edits", async () => { + const { tenantId, repository } = await freshRepository(); + const otherTenant = crypto.randomUUID(); + await db.pool.query("INSERT INTO app.tenants(id) VALUES ($1)", [otherTenant]); + const other = new EncryptedIntegrationRepository(db, otherTenant, serverKey); + const first = { id: crypto.randomUUID(), idempotencyKey: crypto.randomUUID(), expectedRevision: 0, operation: "upsert" as const, kind: "model" as const, name: "Primary", origin: null, description: null, encryptedPayload: await userEncrypt("first") }; + await repository.write(first); + expect(await other.revision()).toBe(0); + expect(await other.records()).toEqual([]); + await expect(repository.write({ ...first, id: crypto.randomUUID(), idempotencyKey: crypto.randomUUID() })).rejects.toMatchObject({ name: "StaleIntegrationRevisionError", currentRevision: 1 }); + const base = await userEncrypt("parallel"); + const results = await Promise.allSettled([0, 1].map(() => repository.write({ id: crypto.randomUUID(), idempotencyKey: crypto.randomUUID(), expectedRevision: 1, operation: "upsert", kind: "model", name: `Concurrent-${crypto.randomUUID()}`, origin: null, description: null, encryptedPayload: base }))); + expect(results.filter(result => result.status === "fulfilled")).toHaveLength(1); + expect(results.filter(result => result.status === "rejected" && result.reason instanceof StaleIntegrationRevisionError)).toHaveLength(1); + }); + + it("returns edits and deletion tombstones in revision order and deduplicates retries", async () => { + const { repository, tenantId } = await freshRepository(); + const id = crypto.randomUUID(), idempotencyKey = crypto.randomUUID(); + const one = await userEncrypt("account version one"); + const first = { id, idempotencyKey, expectedRevision: await repository.revision(), operation: "upsert" as const, kind: "bearer" as const, name: "Ordered", origin: "https://one.example.test", description: null, encryptedPayload: one }; + const firstResult = await repository.write(first); + expect(firstResult.duplicate).toBe(false); + expect(await repository.write(first)).toEqual({ ...firstResult, duplicate: true }); + const two = await userEncrypt("account version two"); + const edit = { ...first, idempotencyKey: crypto.randomUUID(), expectedRevision: firstResult.revision, origin: "https://two.example.test", encryptedPayload: two }; + const editResult = await repository.write(edit); + const deletion = { id, idempotencyKey: crypto.randomUUID(), expectedRevision: editResult.revision, operation: "delete" as const, kind: "bearer" as const, name: "Ordered", origin: "https://two.example.test", description: null }; + const deleteResult = await repository.write(deletion); + const changes = await repository.changesSince(firstResult.revision - 1); + expect(changes.map(({ revision, operation }) => [revision, operation])).toEqual([[firstResult.revision, "upsert"], [editResult.revision, "upsert"], [deleteResult.revision, "delete"]]); + expect(changes.map(change => change.encryptedPayload)).toEqual([one, two, null]); + expect(await repository.records()).not.toContainEqual(expect.objectContaining({ id })); + const tombstone = await db.pool.query("SELECT deleted_at,encrypted_payload,revision FROM app.integration_records WHERE tenant_id=$1 AND id=$2", [tenantId, id]); + expect(tombstone.rows[0]).toMatchObject({ encrypted_payload: null, revision: String(deleteResult.revision) }); + expect(tombstone.rows[0].deleted_at).toBeInstanceOf(Date); + await expect(repository.write({ ...first, name: "Different operation with same key" })).rejects.toBeInstanceOf(IntegrationIdempotencyConflictError); + }); +});