Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions packages/api/migrations/0033_encrypted_integration_records.sql
Original file line number Diff line number Diff line change
@@ -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);
118 changes: 118 additions & 0 deletions packages/api/src/postgres/encrypted-integration-repository.ts
Original file line number Diff line number Diff line change
@@ -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<number> {
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<StoredChange>("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<Array<IntegrationMetadata & { revision: number; encryptedPayload: string }>> {
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<IntegrationChange[]> {
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<StoredChange>("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) })));
}
}
11 changes: 10 additions & 1 deletion packages/api/src/postgres/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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] })]);
Expand Down Expand Up @@ -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,
Expand Down
Loading
Loading