fix(integrations): partial unique index so user-link doesn't clobber workspace row

This commit is contained in:
Philipinho
2026-05-23 13:06:47 +01:00
parent b4c917ac07
commit 6a870adec9
2 changed files with 73 additions and 14 deletions
@@ -1,5 +1,6 @@
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { InjectKysely } from 'nestjs-kysely'; import { InjectKysely } from 'nestjs-kysely';
import { sql } from 'kysely';
import { KyselyDB, KyselyTransaction } from '@docmost/db/types/kysely.types'; import { KyselyDB, KyselyTransaction } from '@docmost/db/types/kysely.types';
import { import {
IntegrationConnection, IntegrationConnection,
@@ -124,14 +125,9 @@ export class IntegrationConnectionRepo {
); );
} }
// Clear any stale non-workspace row for the same (integration, user) to // No need to clear other rows: the migration 20260524T020000 made the
// avoid the uq(integration_id, user_id) constraint blocking the insert. // (integration_id, user_id) constraint partial-on-kind='user', so a
await db // workspace insert never conflicts with the installer's user-link row.
.deleteFrom('integrationConnections')
.where('integrationId', '=', input.integrationId)
.where('userId', '=', input.userId)
.where('kind', '!=', 'workspace')
.execute();
return db return db
.insertInto('integrationConnections') .insertInto('integrationConnections')
@@ -286,6 +282,11 @@ export class IntegrationConnectionRepo {
trx?: KyselyTransaction, trx?: KyselyTransaction,
): Promise<IntegrationConnection> { ): Promise<IntegrationConnection> {
const db = dbOrTx(this.db, trx); const db = dbOrTx(this.db, trx);
// Target the partial unique index uq_integration_connections_user_per_integration
// (integration_id, user_id) WHERE kind = 'user'. Without the .where() hint,
// ON CONFLICT can't match a partial index. The kind discriminator means a
// workspace bot row sharing (integration_id, user_id) with this user-link
// is no longer a conflict, so we cannot flip its kind.
return await db return await db
.insertInto('integrationConnections') .insertInto('integrationConnections')
.values({ .values({
@@ -298,12 +299,14 @@ export class IntegrationConnectionRepo {
accessToken: null, accessToken: null,
}) })
.onConflict((oc) => .onConflict((oc) =>
oc.columns(['integrationId', 'userId']).doUpdateSet({ oc
providerUserId: input.providerUserId, .columns(['integrationId', 'userId'])
metadata: input.metadata as any, .where(sql.ref('kind'), '=', 'user')
kind: 'user', .doUpdateSet({
updatedAt: new Date(), providerUserId: input.providerUserId,
}), metadata: input.metadata as any,
updatedAt: new Date(),
}),
) )
.returningAll() .returningAll()
.executeTakeFirstOrThrow(); .executeTakeFirstOrThrow();
@@ -0,0 +1,56 @@
import { type Kysely, sql } from 'kysely';
export async function up(db: Kysely<any>): Promise<void> {
// The original (integration_id, user_id) unique constraint predates the
// `kind` discriminator. For workspace-scoped integrations (Slack), the
// installer's user_id appears on BOTH the workspace bot row and their
// personal user-link row. The constraint blocks that, and the resulting
// upsert-conflict in user-link flow flipped the existing workspace row
// to kind='user' (clobbering the bot connection).
//
// Replace with a partial unique index that only constrains kind='user'
// rows. Workspace rows already have their own partial unique index on
// (integration_id) WHERE kind = 'workspace'.
await sql`ALTER TABLE integration_connections DROP CONSTRAINT uq_integration_connections_integration_user`.execute(
db,
);
await db.schema
.createIndex('uq_integration_connections_user_per_integration')
.on('integration_connections')
.columns(['integration_id', 'user_id'])
.where(sql.ref('kind'), '=', 'user')
.unique()
.execute();
// Repair Slack workspace rows that got flipped to kind='user' by the
// earlier upsertUserLink bug. User-link rows have NULL access_token by
// design; any kind='user' row that still has access_token AND scopes
// populated for a Slack integration is the corrupted bot row.
await sql`
UPDATE integration_connections ic
SET kind = 'workspace'
FROM integrations i
WHERE ic.integration_id = i.id
AND i.type = 'slack'
AND ic.kind = 'user'
AND ic.access_token IS NOT NULL
AND ic.scopes IS NOT NULL
`.execute(db);
}
export async function down(db: Kysely<any>): Promise<void> {
await db.schema
.dropIndex('uq_integration_connections_user_per_integration')
.ifExists()
.execute();
// Re-adding the full constraint will fail on any DB that now legitimately
// has both a kind='workspace' and kind='user' row for the same
// (integration_id, user_id). Operators rolling back should clean those
// up first. We don't try to be clever; the constraint name is preserved.
await sql`ALTER TABLE integration_connections ADD CONSTRAINT uq_integration_connections_integration_user UNIQUE (integration_id, user_id)`.execute(
db,
);
}