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
63 changes: 63 additions & 0 deletions packages/api/migrations/0035_encrypted_generation_staging.sql
Original file line number Diff line number Diff line change
@@ -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;
96 changes: 96 additions & 0 deletions packages/api/src/postgres/encrypted-integration-repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"; }
}
Expand Down Expand Up @@ -126,4 +132,94 @@ export class EncryptedIntegrationRepository {
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) })));
}

/** 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<number> {
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<number> {
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;
});
}
}
Loading
Loading