Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

add index on group, the group has FK but no index

Thiago Araujo da Silva6c7b9773596e
diff --git a/backend/src/db/migrations/20260728120000_add-user-group-membership-indexes.ts b/backend/src/db/migrations/20260728120000_add-user-group-membership-indexes.ts
new file mode 100644
index 0000000000..aaee1bc825
--- /dev/null
+++ b/backend/src/db/migrations/20260728120000_add-user-group-membership-indexes.ts
@@ -0,0 +1,53 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+
+// user_group_membership carried nothing but its primary key, leaving both of its foreign keys
+// unindexed on a table that sits in the middle of every group-expanded access check:
+// - groupId: expanding a group to its members (alert recipient resolution on every send,
+// removing a group from a scope) and joining the table to a group's project membership.
+// - userId: resolving which groups a user belongs to, and the group-inherited half of the
+// effective-project-membership check.
+// Both were seq scans of the whole table. groupId is paired with userId so the composite also
+// serves the groupId-only lookups as a leftmost prefix.
+const GROUP_ID_USER_ID_INDEX = "idx_user_group_membership_group_id_user_id";
+const USER_ID_INDEX = "idx_user_group_membership_user_id";
+const MIGRATION_TIMEOUT = 60 * 60 * 1000; // 60 minutes
+const MIGRATION_LOCK_TIMEOUT = 30 * 1000; // 30 seconds
+
+export async function up(knex: Knex): Promise<void> {
+ const stmtResult = await knex.raw("SHOW statement_timeout");
+ const originalStatementTimeout = stmtResult.rows[0].statement_timeout;
+ const lockResult = await knex.raw("SHOW lock_timeout");
+ const originalLockTimeout = lockResult.rows[0].lock_timeout;
+
+ try {
+ await knex.raw(`SET statement_timeout = ${MIGRATION_TIMEOUT}`);
+ await knex.raw(`SET lock_timeout = ${MIGRATION_LOCK_TIMEOUT}`);
+
+ if (await knex.schema.hasColumn(TableName.UserGroupMembership, "groupId")) {
+ await knex.raw(`
+ CREATE INDEX CONCURRENTLY IF NOT EXISTS "${GROUP_ID_USER_ID_INDEX}"
+ ON ${TableName.UserGroupMembership} ("groupId", "userId")
+ `);
+ }
+
+ if (await knex.schema.hasColumn(TableName.UserGroupMembership, "userId")) {
+ await knex.raw(`
+ CREATE INDEX CONCURRENTLY IF NOT EXISTS "${USER_ID_INDEX}"
+ ON ${TableName.UserGroupMembership} ("userId")
+ `);
+ }
+ } finally {
+ await knex.raw(`SET statement_timeout = '${originalStatementTimeout}'`);
+ await knex.raw(`SET lock_timeout = '${originalLockTimeout}'`);
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ await knex.raw(`DROP INDEX CONCURRENTLY IF EXISTS "${GROUP_ID_USER_ID_INDEX}"`);
+ await knex.raw(`DROP INDEX CONCURRENTLY IF EXISTS "${USER_ID_INDEX}"`);
+}
+
+const config = { transaction: false };
+export { config };
diff --git a/backend/src/services/alert/alert-channel-recipient-dal.ts b/backend/src/services/alert/alert-channel-recipient-dal.ts
index 710e622350..92773e5036 100644
--- a/backend/src/services/alert/alert-channel-recipient-dal.ts
+++ b/backend/src/services/alert/alert-channel-recipient-dal.ts
@@ -91,17 +91,29 @@ export const alertChannelRecipientDALFactory = (db: TDbClient) => {
.whereRaw(`"om"."actorUserId" = ${principalIdAsUuid}`);
})
.where((scopeQb) => {
- void scopeQb.whereNull("ch.projectId").orWhereExists((projectQb) => {
- void projectQb
- .select(db.raw("1"))
- .from({ pm: TableName.Membership })
- .leftJoin({ ugm: TableName.UserGroupMembership }, (join) => {
- void join.on("ugm.groupId", "pm.actorGroupId").andOn("ugm.isPending", "=", db.raw("?", [false]));
- })
- .where("pm.scope", AccessScope.Project)
- .whereRaw(`"pm"."scopeProjectId" = "ch"."projectId"`)
- .whereRaw(`("pm"."actorUserId" = ${principalIdAsUuid} OR "ugm"."userId" = ${principalIdAsUuid})`);
- });
+ void scopeQb
+ .whereNull("ch.projectId")
+ .orWhereExists((directQb) => {
+ void directQb
+ .select(db.raw("1"))
+ .from({ pm: TableName.Membership })
+ .where("pm.scope", AccessScope.Project)
+ .whereRaw(`"pm"."scopeProjectId" = "ch"."projectId"`)
+ .whereRaw(`"pm"."actorUserId" = ${principalIdAsUuid}`);
+ })
+ .orWhereExists((viaGroupQb) => {
+ void viaGroupQb
+ .select(db.raw("1"))
+ .from({ ugm: TableName.UserGroupMembership })
+ .join({ gm: TableName.Membership }, (join) => {
+ void join
+ .on("gm.actorGroupId", "ugm.groupId")
+ .andOn("gm.scope", "=", db.raw("?", [AccessScope.Project]));
+ })
+ .whereRaw(`"gm"."scopeProjectId" = "ch"."projectId"`)
+ .whereRaw(`"ugm"."userId" = ${principalIdAsUuid}`)
+ .where("ugm.isPending", false);
+ });
});
};
@@ -154,39 +166,34 @@ export const alertChannelRecipientDALFactory = (db: TDbClient) => {
tx?: Knex
): Promise<number> => {
try {
- const uniqueUserIds = [...new Set(userIds)];
+ const uniqueUserIds = new Set(userIds);
const uniqueGroupIds = [...new Set(groupIds)];
- if (!uniqueUserIds.length && !uniqueGroupIds.length) return 0;
-
- const deletedUserRows = (await (tx || db)(TableName.AlertChannelRecipient)
- .where(`${TableName.AlertChannelRecipient}.principalType`, AlertPrincipalType.USER)
- .where((principalQb) => {
- if (uniqueUserIds.length) {
- void principalQb.whereIn(`${TableName.AlertChannelRecipient}.principalId`, uniqueUserIds);
- }
- if (uniqueGroupIds.length) {
- void principalQb.orWhereIn(
- `${TableName.AlertChannelRecipient}.principalId`,
- (tx || db)(TableName.UserGroupMembership)
- .select(db.raw(`"${TableName.UserGroupMembership}"."userId"::text`))
- .whereIn(`${TableName.UserGroupMembership}.groupId`, uniqueGroupIds)
- );
- }
- })
- .whereNotExists($whereUserStillInChannelScope)
- .del()
- .returning("channelId")) as { channelId: string }[];
-
- const deletedGroupRows = uniqueGroupIds.length
- ? ((await (tx || db)(TableName.AlertChannelRecipient)
- .where(`${TableName.AlertChannelRecipient}.principalType`, AlertPrincipalType.GROUP)
- .whereIn(`${TableName.AlertChannelRecipient}.principalId`, uniqueGroupIds)
- .whereNotExists($whereGroupStillInChannelScope)
- .del()
- .returning("channelId")) as { channelId: string }[])
- : [];
-
- const deleted = [...deletedUserRows, ...deletedGroupRows];
+ if (!uniqueUserIds.size && !uniqueGroupIds.length) return 0;
+
+ if (uniqueGroupIds.length) {
+ const members = (await (tx || db)(TableName.UserGroupMembership)
+ .whereIn(`${TableName.UserGroupMembership}.groupId`, uniqueGroupIds)
+ .select(`${TableName.UserGroupMembership}.userId`)) as { userId: string }[];
+ members.forEach((member) => uniqueUserIds.add(member.userId));
+ }
+
+ const deleteForPrincipals = async (principalType: AlertPrincipalType, principalIds: string[]) => {
+ if (!principalIds.length) return [] as { channelId: string }[];
+
+ return (await (tx || db)(TableName.AlertChannelRecipient)
+ .where(`${TableName.AlertChannelRecipient}.principalType`, principalType)
+ .whereIn(`${TableName.AlertChannelRecipient}.principalId`, principalIds)
+ .whereNotExists(
+ principalType === AlertPrincipalType.USER ? $whereUserStillInChannelScope : $whereGroupStillInChannelScope
+ )
+ .del()
+ .returning("channelId")) as { channelId: string }[];
+ };
+
+ const deleted = [
+ ...(await deleteForPrincipals(AlertPrincipalType.USER, [...uniqueUserIds])),
+ ...(await deleteForPrincipals(AlertPrincipalType.GROUP, uniqueGroupIds))
+ ];
await $disableChannelsWithoutRecipients([...new Set(deleted.map((row) => row.channelId))], tx);
diff --git a/frontend/src/views/Alerts/ChannelCard.tsx b/frontend/src/views/Alerts/ChannelCard.tsx
index b41ed7672d..fa561566a3 100644
--- a/frontend/src/views/Alerts/ChannelCard.tsx
+++ b/frontend/src/views/Alerts/ChannelCard.tsx
@@ -4,7 +4,6 @@ import { TrashIcon } from "lucide-react";
import {
Field,
FieldContent,
- FieldDescription,
FieldError,
FieldLabel,
IconButton,
@@ -41,14 +40,6 @@ export const ChannelCard = ({ index, projectId, onRemove, canRemove }: Props) =>
const Icon = getChannelIcon(channelType);
- // A saved email channel can only reach zero recipients by having them pruned when they left the
- // org or project, which also disables the channel. Say so, since the empty field is otherwise
- // indistinguishable from one the user just cleared.
- const hasLostRecipients =
- isExisting &&
- channelType === AlertChannelType.Email &&
- (channel?.recipients?.length ?? 0) === 0;
-
return (
<div className="flex flex-col gap-4 rounded-md border border-border p-4">
<div className="flex items-center justify-between">
@@ -115,12 +106,6 @@ export const ChannelCard = ({ index, projectId, onRemove, canRemove }: Props) =>
)}
/>
<FieldError errors={[channelErrors?.recipients as { message?: string } | undefined]} />
- {hasLostRecipients && (
- <FieldDescription className="text-warning">
- Every recipient of this channel lost access, so the channel was disabled. Add a
- recipient and enable it to resume notifications.
- </FieldDescription>
- )}
</FieldContent>
</Field>
)}