Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
fix prune membership
Thiago Araujo da Silva77b69e7c9aea
diff --git a/backend/src/ee/services/github-org-sync/github-org-sync-service.ts b/backend/src/ee/services/github-org-sync/github-org-sync-service.tsindex 0522352cd3..5865f66a50 100644--- a/backend/src/ee/services/github-org-sync/github-org-sync-service.ts+++ b/backend/src/ee/services/github-org-sync/github-org-sync-service.ts@@ -11,6 +11,7 @@ import { BadRequestError, NotFoundError } from "@app/lib/errors";import { groupBy } from "@app/lib/fn";import { logger } from "@app/lib/logger";import { retryWithBackoff } from "@app/lib/retry";+import { TAlertChannelRecipientDALFactory } from "@app/services/alert/alert-channel-recipient-dal";import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { KmsDataKey } from "@app/services/kms/kms-types";import { PamIdentities, SecretIdentities } from "@app/services/license-client";@@ -86,6 +87,7 @@ type TGithubOrgSyncServiceFactoryDep = {licenseService: Pick<TLicenseServiceFactory, "getPlan">;orgMembershipDAL: Pick<TOrgMembershipDALFactory, "findOrgMembershipById" | "findOrgMembershipsWithUsersByOrgId">;usageMeteringService: Pick<TUsageMeteringServiceFactory, "emit">;+ alertChannelRecipientDAL: Pick<TAlertChannelRecipientDALFactory, "pruneOutOfScopeRecipients">;};export type TGithubOrgSyncServiceFactory = ReturnType<typeof githubOrgSyncServiceFactory>;@@ -100,7 +102,8 @@ export const githubOrgSyncServiceFactory = ({orgMembershipDAL,membershipRoleDAL,membershipGroupDAL,- usageMeteringService+ usageMeteringService,+ alertChannelRecipientDAL}: TGithubOrgSyncServiceFactoryDep) => {const createGithubOrgSync = async ({githubOrgName,@@ -424,6 +427,8 @@ export const githubOrgSyncServiceFactory = ({{ userId, $in: { groupId: removeFromTeams.map((el) => el.groupId) } },tx);++ await alertChannelRecipientDAL.pruneOutOfScopeRecipients({ userIds: [userId] }, tx);});}@@ -841,6 +846,12 @@ export const githubOrgSyncServiceFactory = ({},tx);++ const removedUserIds = membershipsToRemove+ .map((membership) => activeMembers.find((am) => am.id === membership.orgMembershipId)?.user?.id)+ .filter(Boolean) as string[];+ await alertChannelRecipientDAL.pruneOutOfScopeRecipients({ userIds: removedUserIds }, tx);+updatedTeams.add(teamName);}}diff --git a/backend/src/ee/services/group/group-fns.ts b/backend/src/ee/services/group/group-fns.tsindex ca147a03b8..2f07dd294d 100644--- a/backend/src/ee/services/group/group-fns.ts+++ b/backend/src/ee/services/group/group-fns.ts@@ -398,7 +398,8 @@ export const removeUsersFromGroupByUserIds = async ({tx: outerTx,membershipGroupDAL,shouldFailOnMissingMembers = true,- usageMeteringService+ usageMeteringService,+ alertChannelRecipientDAL}: TRemoveUsersFromGroupByUserIds) => {const processRemoval = async (tx: Knex) => {if (userIds.length === 0) {@@ -529,6 +530,8 @@ export const removeUsersFromGroupByUserIds = async ({);}+ await alertChannelRecipientDAL.pruneOutOfScopeRecipients({ userIds: foundMembers.map((m) => m.id) }, tx);+// These users may have left a secret-manager or PAM project they only reached through this group.usageMeteringService?.emit(group.orgId, SecretIdentities.key);usageMeteringService?.emit(group.orgId, PamIdentities.key);diff --git a/backend/src/ee/services/group/group-service.ts b/backend/src/ee/services/group/group-service.tsindex 5c217b33d8..4913a39f7b 100644--- a/backend/src/ee/services/group/group-service.ts+++ b/backend/src/ee/services/group/group-service.ts@@ -104,7 +104,7 @@ type TGroupServiceFactoryDep = {oidcConfigDAL: Pick<TOidcConfigDALFactory, "findOne">;usageMeteringService: Pick<TUsageMeteringServiceFactory, "emit">;identityAccessTokenService: Pick<TIdentityAccessTokenServiceFactory, "bumpIdentityRevocationVersion">;- alertChannelRecipientDAL: Pick<TAlertChannelRecipientDALFactory, "deleteByPrincipals">;+ alertChannelRecipientDAL: Pick<TAlertChannelRecipientDALFactory, "deleteByPrincipals" | "pruneOutOfScopeRecipients">;};export type TGroupServiceFactory = ReturnType<typeof groupServiceFactory>;@@ -438,6 +438,8 @@ export const groupServiceFactory = ({const idsPerSubOrg = await Promise.all(referencingSubOrgs.map((subOrg) => collectIdsForSubOrg(subOrg.orgId)));await deleteMembershipsInBatch(idsPerSubOrg.flat(), tx);++ await alertChannelRecipientDAL.pruneOutOfScopeRecipients({ userIds }, tx);});};@@ -558,6 +560,8 @@ export const groupServiceFactory = ({membershipIdsToDelete.push(...userProjectIdsToDelete, ...identityProjectIdsToDelete);await deleteMembershipsInBatch(membershipIdsToDelete, tx);++ await alertChannelRecipientDAL.pruneOutOfScopeRecipients({ groupIds: [groupId] }, tx);});return group;@@ -577,6 +581,10 @@ export const groupServiceFactory = ({}return groupDAL.transaction(async (tx) => {+ // Read before the delete cascades the group memberships away — a member may have reached a+ // project only through this group, leaving them stale on that project's alert channels.+ const memberUserIds = (await userGroupMembershipDAL.find({ groupId }, { tx })).map((m) => m.userId);+const [deletedGroup] = await groupDAL.delete({id: groupId,@@ -593,6 +601,8 @@ export const groupServiceFactory = ({tx);+ await alertChannelRecipientDAL.pruneOutOfScopeRecipients({ userIds: memberUserIds }, tx);+return deletedGroup;});};@@ -1186,7 +1196,8 @@ export const groupServiceFactory = ({userDAL,userGroupMembershipDAL,membershipGroupDAL,- projectKeyDAL+ projectKeyDAL,+ alertChannelRecipientDAL});await cleanUpSubOrgProjectMemberships({diff --git a/backend/src/ee/services/group/group-types.ts b/backend/src/ee/services/group/group-types.tsindex 9673bb827b..7a1d63a138 100644--- a/backend/src/ee/services/group/group-types.ts+++ b/backend/src/ee/services/group/group-types.ts@@ -2,6 +2,7 @@ import { Knex } from "knex";import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";import { OrderByDirection, TGenericPermission } from "@app/lib/types";+import { TAlertChannelRecipientDALFactory } from "@app/services/alert/alert-channel-recipient-dal";import { TIdentityDALFactory } from "@app/services/identity/identity-dal";import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";import { TMembershipDALFactory } from "@app/services/membership/membership-dal";@@ -147,6 +148,7 @@ export type TRemoveUsersFromGroupByUserIds = {tx?: Knex;shouldFailOnMissingMembers?: boolean;usageMeteringService?: Pick<TUsageMeteringServiceFactory, "emit">;+ alertChannelRecipientDAL: Pick<TAlertChannelRecipientDALFactory, "pruneOutOfScopeRecipients">;};export type TRemoveIdentitiesFromGroup = {diff --git a/backend/src/ee/services/ldap-config/ldap-config-service.ts b/backend/src/ee/services/ldap-config/ldap-config-service.tsindex f718928476..5caaca7886 100644--- a/backend/src/ee/services/ldap-config/ldap-config-service.ts+++ b/backend/src/ee/services/ldap-config/ldap-config-service.ts@@ -28,6 +28,7 @@ import {} from "@app/lib/telemetry/metrics";import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";import { sanitizeEmail, validateEmail } from "@app/lib/validator/validate-email";+import { TAlertChannelRecipientDALFactory } from "@app/services/alert/alert-channel-recipient-dal";import { TAuthLoginFactory } from "@app/services/auth/auth-login-service";import { AuthMethod } from "@app/services/auth/auth-type";import { TAuthTokenServiceFactory } from "@app/services/auth-token/auth-token-service";@@ -82,6 +83,7 @@ type TLdapConfigServiceFactoryDep = {membershipGroupDAL: Pick<TMembershipGroupDALFactory, "find">;membershipRoleDAL: Pick<TMembershipRoleDALFactory, "create">;projectKeyDAL: Pick<TProjectKeyDALFactory, "find" | "findLatestProjectKey" | "insertMany" | "delete">;+ alertChannelRecipientDAL: Pick<TAlertChannelRecipientDALFactory, "pruneOutOfScopeRecipients">;projectDAL: Pick<TProjectDALFactory, "findProjectGhostUser" | "findById">;projectBotDAL: Pick<TProjectBotDALFactory, "findOne">;userGroupMembershipDAL: Pick<@@ -120,6 +122,7 @@ export const ldapConfigServiceFactory = ({membershipGroupDAL,membershipRoleDAL,projectKeyDAL,+ alertChannelRecipientDAL,projectDAL,projectBotDAL,userGroupMembershipDAL,@@ -715,6 +718,7 @@ export const ldapConfigServiceFactory = ({membershipGroupDAL,projectKeyDAL,usageMeteringService,+ alertChannelRecipientDAL,tx});}diff --git a/backend/src/ee/services/oidc/oidc-config-service.ts b/backend/src/ee/services/oidc/oidc-config-service.tsindex 5204bc3094..11e9486af6 100644--- a/backend/src/ee/services/oidc/oidc-config-service.ts+++ b/backend/src/ee/services/oidc/oidc-config-service.ts@@ -34,6 +34,7 @@ import {sanitizeEmail,validateEmail} from "@app/lib/validator";+import { TAlertChannelRecipientDALFactory } from "@app/services/alert/alert-channel-recipient-dal";import { TAuthLoginFactory } from "@app/services/auth/auth-login-service";import { ActorType, AuthMethod } from "@app/services/auth/auth-type";import { TAuthTokenServiceFactory } from "@app/services/auth-token/auth-token-service";@@ -105,6 +106,7 @@ type TOidcConfigServiceFactoryDep = {| "filterProjectsByUserMembership">;projectKeyDAL: Pick<TProjectKeyDALFactory, "find" | "findLatestProjectKey" | "insertMany" | "delete">;+ alertChannelRecipientDAL: Pick<TAlertChannelRecipientDALFactory, "pruneOutOfScopeRecipients">;projectDAL: Pick<TProjectDALFactory, "findProjectGhostUser" | "findById">;projectBotDAL: Pick<TProjectBotDALFactory, "findOne">;auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;@@ -131,6 +133,7 @@ export const oidcConfigServiceFactory = ({membershipGroupDAL,membershipRoleDAL,projectKeyDAL,+ alertChannelRecipientDAL,projectDAL,projectBotDAL,auditLogService,@@ -436,7 +439,8 @@ export const oidcConfigServiceFactory = ({userGroupMembershipDAL,membershipGroupDAL,projectKeyDAL,- usageMeteringService+ usageMeteringService,+ alertChannelRecipientDAL});}diff --git a/backend/src/ee/services/saml-config/saml-config-service.ts b/backend/src/ee/services/saml-config/saml-config-service.tsindex f912f1be7e..ae13097c69 100644--- a/backend/src/ee/services/saml-config/saml-config-service.ts+++ b/backend/src/ee/services/saml-config/saml-config-service.ts@@ -20,6 +20,7 @@ import { requestMemoKeys } from "@app/lib/request-context/memo-keys";import { requestMemoize } from "@app/lib/request-context/request-memoizer";import { recordSsoConfigChangeMetric, SsoConfigAction, SsoProvider } from "@app/lib/telemetry/metrics";import { sanitizeEmail, validateEmail } from "@app/lib/validator/validate-email";+import { TAlertChannelRecipientDALFactory } from "@app/services/alert/alert-channel-recipient-dal";import { TAuthLoginFactory } from "@app/services/auth/auth-login-service";import { AuthMethod } from "@app/services/auth/auth-type";import { TAuthTokenServiceFactory } from "@app/services/auth-token/auth-token-service";@@ -92,6 +93,7 @@ type TSamlConfigServiceFactoryDep = {projectDAL: Pick<TProjectDALFactory, "findById" | "findProjectGhostUser">;projectBotDAL: Pick<TProjectBotDALFactory, "findOne">;projectKeyDAL: Pick<TProjectKeyDALFactory, "find" | "delete" | "findLatestProjectKey" | "insertMany">;+ alertChannelRecipientDAL: Pick<TAlertChannelRecipientDALFactory, "pruneOutOfScopeRecipients">;membershipGroupDAL: Pick<TMembershipGroupDALFactory, "find" | "create">;loginService: Pick<TAuthLoginFactory, "processProviderCallback">;emailDomainDAL: Pick<TEmailDomainDALFactory, "findOne">;@@ -109,6 +111,7 @@ export const samlConfigServiceFactory = ({projectDAL,projectBotDAL,projectKeyDAL,+ alertChannelRecipientDAL,permissionService,licenseService,tokenService,@@ -254,6 +257,7 @@ export const samlConfigServiceFactory = ({membershipGroupDAL,projectKeyDAL,usageMeteringService,+ alertChannelRecipientDAL,tx: transaction});} catch (error) {diff --git a/backend/src/ee/services/scim/scim-service.ts b/backend/src/ee/services/scim/scim-service.tsindex d72e72f417..e8d79321ea 100644--- a/backend/src/ee/services/scim/scim-service.ts+++ b/backend/src/ee/services/scim/scim-service.ts@@ -29,6 +29,8 @@ import { requestMemoize } from "@app/lib/request-context/request-memoizer";import { recordScimOperationMetric, ScimOperation } from "@app/lib/telemetry/metrics";import { sanitizeEmail, validateEmail } from "@app/lib/validator/validate-email";import { TAdditionalPrivilegeDALFactory } from "@app/services/additional-privilege/additional-privilege-dal";+import { TAlertChannelRecipientDALFactory } from "@app/services/alert/alert-channel-recipient-dal";+import { AlertPrincipalType } from "@app/services/alert/alert-types";import { TApprovalPolicyDALFactory } from "@app/services/approval-policy/approval-policy-dal";import { AuthTokenType } from "@app/services/auth/auth-type";import { TExternalGroupOrgRoleMappingDALFactory } from "@app/services/external-group-org-role-mapping/external-group-org-role-mapping-dal";@@ -131,6 +133,7 @@ type TScimServiceFactoryDep = {externalGroupOrgRoleMappingDAL: TExternalGroupOrgRoleMappingDALFactory;additionalPrivilegeDAL: TAdditionalPrivilegeDALFactory;approvalPolicyDAL: Pick<TApprovalPolicyDALFactory, "deleteUserStepApproversInProjects">;+ alertChannelRecipientDAL: Pick<TAlertChannelRecipientDALFactory, "pruneOutOfScopeRecipients" | "deleteByPrincipals">;scimEventsDAL: Pick<TScimEventsDALFactory, "create" | "findEventsByOrgId">;emailDomainDAL: Pick<TEmailDomainDALFactory, "findOne">;telemetryService: Pick<TTelemetryServiceFactory, "sendPostHogEvents">;@@ -156,6 +159,7 @@ export const scimServiceFactory = ({membershipRoleDAL,additionalPrivilegeDAL,approvalPolicyDAL,+ alertChannelRecipientDAL,scimEventsDAL,emailDomainDAL,telemetryService,@@ -879,7 +883,8 @@ export const scimServiceFactory = ({membershipRoleDAL,userGroupMembershipDAL,additionalPrivilegeDAL,- approvalPolicyDAL+ approvalPolicyDAL,+ alertChannelRecipientDAL});// Deprovisioning cascades the user's project + group memberships, changing the identity meters.@@ -1350,6 +1355,7 @@ export const scimServiceFactory = ({userGroupMembershipDAL,membershipGroupDAL,projectKeyDAL,+ alertChannelRecipientDAL,tx,shouldFailOnMissingMembers});@@ -1534,9 +1540,21 @@ export const scimServiceFactory = ({status: 403});- const [group] = await groupDAL.delete({- id: groupId,- orgId+ const [group] = await groupDAL.transaction(async (tx) => {+ // Read the members before the delete cascades their group memberships away — one may have+ // reached a project only through this group, leaving them stale on its alert channels.+ const memberUserIds = (await userGroupMembershipDAL.find({ groupId }, { tx })).map((m) => m.userId);++ const deleted = await groupDAL.delete({ id: groupId, orgId }, tx);+ if (!deleted.length) return deleted;++ await alertChannelRecipientDAL.deleteByPrincipals(+ { principalType: AlertPrincipalType.GROUP, principalIds: [groupId] },+ tx+ );+ await alertChannelRecipientDAL.pruneOutOfScopeRecipients({ userIds: memberUserIds }, tx);++ return deleted;});// Return success even if group not found (idempotent delete per SCIM RFC 7644)diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 3806de6ffd..c6f7401fb3 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -956,7 +956,8 @@ export const registerRoutes = async (licenseService,applicationMembershipCleanupService,projectDAL,- usageMeteringService+ usageMeteringService,+ alertChannelRecipientDAL});const roleService = roleServiceFactory({@@ -1236,6 +1237,7 @@ export const registerRoutes = async (membershipUserDAL,additionalPrivilegeDAL,approvalPolicyDAL,+ alertChannelRecipientDAL,emailDomainDAL,telemetryService,usageMeteringService@@ -1251,7 +1253,8 @@ export const registerRoutes = async (orgMembershipDAL,membershipRoleDAL,membershipGroupDAL,- usageMeteringService+ usageMeteringService,+ alertChannelRecipientDAL});// gitHubAppService is created after gatewayPoolService (below) due to dependency on gateway services@@ -1351,7 +1354,8 @@ export const registerRoutes = async (loginService,emailDomainDAL,telemetryService,- usageMeteringService+ usageMeteringService,+ alertChannelRecipientDAL});const ldapService = ldapConfigServiceFactory({@@ -1375,7 +1379,8 @@ export const registerRoutes = async (loginService,emailDomainDAL,telemetryService,- usageMeteringService+ usageMeteringService,+ alertChannelRecipientDAL});const passwordService = authPaswordServiceFactory({tokenService,@@ -1439,7 +1444,8 @@ export const registerRoutes = async (additionalPrivilegeDAL,approvalPolicyDAL,certificatePolicyDAL,- usageMeteringService+ usageMeteringService,+ alertChannelRecipientDAL});const subOrgService = subOrgServiceFactory({@@ -1495,7 +1501,8 @@ export const registerRoutes = async (membershipIdentityDAL,membershipRoleDAL,membershipUserDAL,- usageMeteringService+ usageMeteringService,+ alertChannelRecipientDAL});const offlineUsageReportService = offlineUsageReportServiceFactory({@@ -1557,7 +1564,8 @@ export const registerRoutes = async (secretApprovalPolicyDAL,membershipRoleDAL,applicationMembershipCleanupService,- usageMeteringService+ usageMeteringService,+ alertChannelRecipientDAL});const projectKeyService = projectKeyServiceFactory({@@ -2905,7 +2913,8 @@ export const registerRoutes = async (loginService,emailDomainDAL,telemetryService,- usageMeteringService+ usageMeteringService,+ alertChannelRecipientDAL});const userActivationService = userActivationServiceFactory({diff --git a/backend/src/services/alert/alert-channel-recipient-dal.test.ts b/backend/src/services/alert/alert-channel-recipient-dal.test.tsindex 832cc2d1eb..ea25982a3c 100644--- a/backend/src/services/alert/alert-channel-recipient-dal.test.ts+++ b/backend/src/services/alert/alert-channel-recipient-dal.test.ts@@ -4,119 +4,101 @@ import { alertChannelRecipientDALFactory } from "./alert-channel-recipient-dal";import { AlertChannelType } from "./alert-channel-types";import { AlertPrincipalType } from "./alert-types";-type TChannelQueryLog = {- where: unknown[][];- whereIn: unknown[][];- notExistsSubqueries: number;- update?: Record<string, unknown>;-};+type TCall = { table: string; method: string; args: unknown[] };-// Records query-builder calls so we can assert the scope cleanup filters correctly without a DB.+// Records query-builder calls so we can assert what each prune targets without a database. Callbacks+// handed to where/whereExists/whereNotExists are invoked against a nested recorder, so the subquery+// builders still execute and their calls land in the same log.const buildDAL = (opts: { deletedChannelIds?: string[] } = {}) => {const deletedChannelIds = opts.deletedChannelIds ?? ["c1", "c2"];-- const calls = {- recipientWhere: [] as unknown[][],- recipientWhereIn: [] as unknown[][],- channelQueries: [] as TChannelQueryLog[]- };-- // The AlertChannel table is hit for two unrelated things — the channel-scoping subquery and the- // disable-empty-channels update — so each invocation gets its own log, classified by whether it- // ended in an update.- const channelChain = () => {- const log: TChannelQueryLog = { where: [], whereIn: [], notExistsSubqueries: 0 };- calls.channelQueries.push(log);-- const subquery = {- select: () => subquery,- from: () => subquery,- whereRaw: () => subquery- };- const chain = {- select: () => chain,- where: (...args: unknown[]) => {- log.where.push(args);- return chain;- },- whereIn: (...args: unknown[]) => {- log.whereIn.push(args);- return chain;- },- whereNotExists: (cb: (qb: typeof subquery) => void) => {- log.notExistsSubqueries += 1;- cb(subquery);- return chain;- },- update: async (patch: Record<string, unknown>) => {- log.update = patch;- return 1;+ const calls: TCall[] = [];++ const createChain = (table: string): Record<string, unknown> => {+ const chain: Record<string, unknown> = new Proxy(+ {},+ {+ get(_target, prop) {+ // Awaiting the chain (the disable-channels update) must not treat it as a promise.+ if (prop === "then") return undefined;+ if (prop === "del") {+ return () => {+ calls.push({ table, method: "del", args: [] });+ return { returning: async () => deletedChannelIds.map((channelId) => ({ channelId })) };+ };+ }+ return (...args: unknown[]) => {+ calls.push({ table, method: String(prop), args });+ args.forEach((arg) => {+ if (typeof arg === "function") (arg as (qb: unknown) => void)(chain);+ });+ return chain;+ };+ }}- };+ );return chain;};- const recipientChain = {- where: (...args: unknown[]) => {- calls.recipientWhere.push(args);- return recipientChain;- },- whereIn: (...args: unknown[]) => {- calls.recipientWhereIn.push(args);- return recipientChain;- },- del: () => ({- returning: async () => deletedChannelIds.map((channelId) => ({ channelId }))- })- };-- const db = ((table: string) =>- table === TableName.AlertChannel ? channelChain() : recipientChain) as unknown as Parameters<+ const db = ((table: string) => createChain(table)) as unknown as Parameters<typeof alertChannelRecipientDALFactory>[0];(db as unknown as { raw: (value: string) => string }).raw = (value: string) => value;- const scopeQueries = () => calls.channelQueries.filter((query) => !query.update);- const disableQueries = () => calls.channelQueries.filter((query) => query.update);+ const callsOn = (table: string, method: string) =>+ calls.filter((call) => call.table === table && call.method === method);+ const recipientArgs = (method: string) => callsOn(TableName.AlertChannelRecipient, method).flatMap((c) => c.args);- return { dal: alertChannelRecipientDALFactory(db), calls, scopeQueries, disableQueries };+ return { dal: alertChannelRecipientDALFactory(db), calls, callsOn, recipientArgs };};-describe("alert channel recipient dal — scope cleanup", () => {- test("project removal scopes channels by projectId and prunes only USER principals", async () => {- const { dal, calls, scopeQueries } = buildDAL();+describe("alert channel recipient dal — out-of-scope prune", () => {+ test("re-checks the given users against every channel they are a recipient of", async () => {+ const { dal, callsOn, recipientArgs } = buildDAL();- const deleted = await dal.deleteUsersRecipientsByScope({ userIds: ["u1", "u2"], projectId: "proj-1" });+ const deleted = await dal.pruneOutOfScopeRecipients({ userIds: ["u1", "u2"] });expect(deleted).toBe(2);- expect(scopeQueries().flatMap((query) => query.where)).toContainEqual([- `${TableName.AlertChannel}.projectId`,- "proj-1"- ]);- expect(calls.recipientWhere).toContainEqual([`${TableName.AlertChannelRecipient}.principalType`, "user"]);- expect(calls.recipientWhereIn).toContainEqual([`${TableName.AlertChannelRecipient}.principalId`, ["u1", "u2"]]);+ expect(recipientArgs("where")).toContainEqual(AlertPrincipalType.USER);+ expect(recipientArgs("whereIn")).toContainEqual(["u1", "u2"]);+ // The scope check is the correlated NOT EXISTS, not a pre-computed channel list, so a user who+ // kept access through another path (a group, another project) keeps their rows.+ expect(callsOn(TableName.AlertChannelRecipient, "whereNotExists")).toHaveLength(1);+ // Nothing about the group principals is touched.+ expect(recipientArgs("where")).not.toContainEqual(AlertPrincipalType.GROUP);+ });++ test("a group losing a scope re-checks its own rows and its members' rows", async () => {+ const { dal, callsOn, recipientArgs } = buildDAL();++ await dal.pruneOutOfScopeRecipients({ groupIds: ["g1"] });++ expect(recipientArgs("where")).toContainEqual(AlertPrincipalType.GROUP);+ expect(recipientArgs("where")).toContainEqual(AlertPrincipalType.USER);+ expect(recipientArgs("whereIn")).toContainEqual(["g1"]);+ // Members are reached through a subquery rather than a materialized id list.+ expect(callsOn(TableName.UserGroupMembership, "whereIn").flatMap((call) => call.args)).toContainEqual(["g1"]);});- test("org removal scopes channels by orgId (covers org- and project-scoped channels)", async () => {- const { dal, scopeQueries } = buildDAL();+ test("dedupes the principal ids it is handed", async () => {+ const { dal, recipientArgs } = buildDAL();- await dal.deleteUsersRecipientsByScope({ userIds: ["u1"], orgId: "org-1" });+ await dal.pruneOutOfScopeRecipients({ userIds: ["u1", "u1"] });- expect(scopeQueries().flatMap((query) => query.where)).toContainEqual([`${TableName.AlertChannel}.orgId`, "org-1"]);+ expect(recipientArgs("whereIn")).toContainEqual(["u1"]);});- test("no-op when no users or no scope", async () => {+ test("no-op when handed no principals", async () => {const { dal, calls } = buildDAL();- expect(await dal.deleteUsersRecipientsByScope({ userIds: [], orgId: "org-1" })).toBe(0);- expect(await dal.deleteUsersRecipientsByScope({ userIds: ["u1"] })).toBe(0);- expect(calls.channelQueries).toHaveLength(0);+ expect(await dal.pruneOutOfScopeRecipients({})).toBe(0);+ expect(await dal.pruneOutOfScopeRecipients({ userIds: [], groupIds: [] })).toBe(0);+ expect(calls).toHaveLength(0);});});describe("alert channel recipient dal — deleted principal cleanup", () => {- test("prunes a hard-deleted group's rows everywhere, with no channel scoping", async () => {- const { dal, calls, scopeQueries } = buildDAL();+ test("prunes a hard-deleted group's rows everywhere, with no scope check", async () => {+ const { dal, callsOn, recipientArgs } = buildDAL();const deleted = await dal.deleteByPrincipals({principalType: AlertPrincipalType.GROUP,@@ -124,18 +106,17 @@ describe("alert channel recipient dal — deleted principal cleanup", () => {});expect(deleted).toBe(2);- expect(calls.recipientWhere).toContainEqual([`${TableName.AlertChannelRecipient}.principalType`, "group"]);- expect(calls.recipientWhereIn).toContainEqual([`${TableName.AlertChannelRecipient}.principalId`, ["g1"]]);- // The principal no longer exists anywhere, so its rows are pruned across every org and project.- expect(scopeQueries()).toHaveLength(0);+ expect(recipientArgs("where")).toContainEqual(AlertPrincipalType.GROUP);+ expect(recipientArgs("whereIn")).toContainEqual(["g1"]);+ // The principal no longer exists anywhere, so its rows go regardless of org or project.+ expect(callsOn(TableName.AlertChannelRecipient, "whereNotExists")).toHaveLength(0);});test("no-op on an empty principal list", async () => {const { dal, calls } = buildDAL();expect(await dal.deleteByPrincipals({ principalType: AlertPrincipalType.USER, principalIds: [] })).toBe(0);- expect(calls.recipientWhere).toHaveLength(0);- expect(calls.channelQueries).toHaveLength(0);+ expect(calls).toHaveLength(0);});});@@ -145,8 +126,8 @@ describe("alert channel recipient dal — emptied channels", () => {// an alert that would notify nobody.test.each([[- "scope cleanup",- (dal: ReturnType<typeof buildDAL>["dal"]) => dal.deleteUsersRecipientsByScope({ userIds: ["u1"], orgId: "org-1" })+ "an out-of-scope prune",+ (dal: ReturnType<typeof buildDAL>["dal"]) => dal.pruneOutOfScopeRecipients({ userIds: ["u1"] })],["deleted principal cleanup",@@ -154,25 +135,25 @@ describe("alert channel recipient dal — emptied channels", () => {dal.deleteByPrincipals({ principalType: AlertPrincipalType.USER, principalIds: ["u1"] })]])("disables the directed channels left with no recipients after %s", async (_label, prune) => {- const { dal, disableQueries } = buildDAL({ deletedChannelIds: ["c1", "c1", "c2"] });+ const { dal, callsOn } = buildDAL({ deletedChannelIds: ["c1", "c1", "c2"] });await prune(dal);- const [disable] = disableQueries();- expect(disable.update).toEqual({ enabled: false });+ expect(callsOn(TableName.AlertChannel, "update").flatMap((call) => call.args)).toContainEqual({ enabled: false });+ const channelWhereIn = callsOn(TableName.AlertChannel, "whereIn").flatMap((call) => call.args);// Only the channels the prune actually touched, deduplicated.- expect(disable.whereIn).toContainEqual([`${TableName.AlertChannel}.id`, ["c1", "c2"]]);+ expect(channelWhereIn).toContainEqual(["c1", "c2"]);// Undirected channels (Slack, webhook, PagerDuty) deliver without recipients, so they are untouched.- expect(disable.whereIn).toContainEqual([`${TableName.AlertChannel}.channelType`, [AlertChannelType.EMAIL]]);+ expect(channelWhereIn).toContainEqual([AlertChannelType.EMAIL]);// Channels that still have other recipients keep running.- expect(disable.notExistsSubqueries).toBe(1);+ expect(callsOn(TableName.AlertChannel, "whereNotExists")).toHaveLength(1);});test("skips the disable pass when the prune deleted nothing", async () => {- const { dal, disableQueries } = buildDAL({ deletedChannelIds: [] });+ const { dal, callsOn } = buildDAL({ deletedChannelIds: [] });- await dal.deleteUsersRecipientsByScope({ userIds: ["u1"], orgId: "org-1" });+ await dal.pruneOutOfScopeRecipients({ userIds: ["u1"] });- expect(disableQueries()).toHaveLength(0);+ expect(callsOn(TableName.AlertChannel, "update")).toHaveLength(0);});});diff --git a/backend/src/services/alert/alert-channel-recipient-dal.ts b/backend/src/services/alert/alert-channel-recipient-dal.tsindex 4bfa4bc5f1..710e622350 100644--- a/backend/src/services/alert/alert-channel-recipient-dal.ts+++ b/backend/src/services/alert/alert-channel-recipient-dal.ts@@ -1,7 +1,7 @@import { Knex } from "knex";import { TDbClient } from "@app/db";-import { TableName, TAlertChannelRecipients } from "@app/db/schemas";+import { AccessScope, TableName, TAlertChannelRecipients } from "@app/db/schemas";import { DatabaseError } from "@app/lib/errors";import { ormify, selectAllTableCols } from "@app/lib/knex";@@ -75,29 +75,124 @@ export const alertChannelRecipientDALFactory = (db: TDbClient) => {}};- const deleteUsersRecipientsByScope = async (- { userIds, orgId, projectId }: { userIds: string[]; orgId?: string; projectId?: string },+ const $whereUserStillInChannelScope = (qb: Knex.QueryBuilder) => {+ const principalIdAsUuid = `"${TableName.AlertChannelRecipient}"."principalId"::uuid`;++ void qb+ .select(db.raw("1"))+ .from({ ch: TableName.AlertChannel })+ .whereRaw(`"ch"."id" = "${TableName.AlertChannelRecipient}"."channelId"`)+ .whereExists((orgQb) => {+ void orgQb+ .select(db.raw("1"))+ .from({ om: TableName.Membership })+ .where("om.scope", AccessScope.Organization)+ .whereRaw(`"om"."scopeOrgId" = "ch"."orgId"`)+ .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})`);+ });+ });+ };++ const $whereGroupStillInChannelScope = (qb: Knex.QueryBuilder) => {+ const principalIdAsUuid = `"${TableName.AlertChannelRecipient}"."principalId"::uuid`;++ void qb+ .select(db.raw("1"))+ .from({ ch: TableName.AlertChannel })+ .whereRaw(`"ch"."id" = "${TableName.AlertChannelRecipient}"."channelId"`)+ .where((scopeQb) => {+ void scopeQb+ .where((orgScopeQb) => {+ void orgScopeQb.whereNull("ch.projectId").whereExists((groupQb) => {+ void groupQb+ .select(db.raw("1"))+ .from({ g: TableName.Groups })+ .whereRaw(`"g"."id" = ${principalIdAsUuid}`)+ .whereRaw(`"g"."orgId" = "ch"."orgId"`);+ });+ })+ .orWhere((projectScopeQb) => {+ void projectScopeQb.whereNotNull("ch.projectId").whereExists((membershipQb) => {+ void membershipQb+ .select(db.raw("1"))+ .from({ pm: TableName.Membership })+ .where("pm.scope", AccessScope.Project)+ .whereRaw(`"pm"."scopeProjectId" = "ch"."projectId"`)+ .whereRaw(`"pm"."actorGroupId" = ${principalIdAsUuid}`);+ });+ });+ });+ };++ /**+ * Drops recipient rows whose principal can no longer reach the channel's scope, evaluated per+ * (principal, channel) pair. Call it after deleting a membership that can revoke access — losing an+ * org membership also prunes that org's project channels (and its sub-orgs'), losing a project+ * membership prunes only that project's channels.+ *+ * `groupIds` prunes the groups' own rows *and* their members' user rows: the recipient picker offers+ * anyone with access to the project, group-inherited included, so a user row can be backed solely by+ * a group and dies with it. Pass removed users in `userIds` when the group itself keeps its access.+ *+ * Safe to call unconditionally: a principal that still has access keeps its rows, so callers don't+ * have to work out which scopes a change actually touched.+ */+ const pruneOutOfScopeRecipients = async (+ { userIds = [], groupIds = [] }: { userIds?: string[]; groupIds?: string[] },tx?: Knex): Promise<number> => {try {- if (!userIds.length || (!orgId && !projectId)) return 0;-- const channelIds = (tx || db)(TableName.AlertChannel).select("id");- if (projectId) void channelIds.where(`${TableName.AlertChannel}.projectId`, projectId);- else void channelIds.where(`${TableName.AlertChannel}.orgId`, orgId as string);+ const uniqueUserIds = [...new Set(userIds)];+ const uniqueGroupIds = [...new Set(groupIds)];+ if (!uniqueUserIds.length && !uniqueGroupIds.length) return 0;- const deleted = (await (tx || db)(TableName.AlertChannelRecipient)+ const deletedUserRows = (await (tx || db)(TableName.AlertChannelRecipient).where(`${TableName.AlertChannelRecipient}.principalType`, AlertPrincipalType.USER)- .whereIn(`${TableName.AlertChannelRecipient}.principalId`, userIds)- .whereIn(`${TableName.AlertChannelRecipient}.channelId`, channelIds)+ .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];+await $disableChannelsWithoutRecipients([...new Set(deleted.map((row) => row.channelId))], tx);return deleted.length;} catch (error) {- throw new DatabaseError({ error, name: "DeleteUsersRecipientsByScope" });+ throw new DatabaseError({ error, name: "PruneOutOfScopeRecipients" });}};@@ -106,6 +201,6 @@ export const alertChannelRecipientDALFactory = (db: TDbClient) => {findByChannelIds,deleteByChannelId,deleteByPrincipals,- deleteUsersRecipientsByScope+ pruneOutOfScopeRecipients};};diff --git a/backend/src/services/membership-group/membership-group-service.ts b/backend/src/services/membership-group/membership-group-service.tsindex 76f6b131fc..899adf5037 100644--- a/backend/src/services/membership-group/membership-group-service.ts+++ b/backend/src/services/membership-group/membership-group-service.ts@@ -21,6 +21,7 @@ import { SearchResourceOperators } from "@app/lib/search-resource/search";import { PamIdentities, SecretIdentities } from "@app/services/license-client";import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";+import { TAlertChannelRecipientDALFactory } from "../alert/alert-channel-recipient-dal";import { TApplicationMembershipCleanupServiceFactory } from "../membership/application-membership-cleanup-service";import { assertSecretsTemporaryAccessAllowed } from "../membership/membership-fns";import { TMembershipRoleDALFactory } from "../membership/membership-role-dal";@@ -57,6 +58,7 @@ type TMembershipGroupServiceFactoryDep = {>;projectDAL: Pick<TProjectDALFactory, "findById">;usageMeteringService: Pick<TUsageMeteringServiceFactory, "emitForProject">;+ alertChannelRecipientDAL: Pick<TAlertChannelRecipientDALFactory, "pruneOutOfScopeRecipients">;};export type TMembershipGroupServiceFactory = ReturnType<typeof membershipGroupServiceFactory>;@@ -75,7 +77,8 @@ export const membershipGroupServiceFactory = ({licenseService,applicationMembershipCleanupService,projectDAL,- usageMeteringService+ usageMeteringService,+ alertChannelRecipientDAL}: TMembershipGroupServiceFactoryDep) => {const scopeFactory = {[AccessScope.Organization]: newOrgMembershipGroupFactory({@@ -421,6 +424,9 @@ export const membershipGroupServiceFactory = ({await membershipRoleDAL.delete({ membershipId: existingMembership.id }, tx);const doc = await membershipGroupDAL.deleteById(existingMembership.id, tx);++ await alertChannelRecipientDAL.pruneOutOfScopeRecipients({ groupIds: [dto.selector.groupId] }, tx);+return doc;};diff --git a/backend/src/services/membership-user/membership-user-service.ts b/backend/src/services/membership-user/membership-user-service.tsindex 2e7312bdad..5795afd00d 100644--- a/backend/src/services/membership-user/membership-user-service.ts+++ b/backend/src/services/membership-user/membership-user-service.ts@@ -89,7 +89,7 @@ type TMembershipUserServiceFactoryDep = {oidcConfigDAL: Pick<TOidcConfigDALFactory, "findOne">;samlConfigDAL: Pick<TSamlConfigDALFactory, "findOne">;usageMeteringService: Pick<TUsageMeteringServiceFactory, "emit" | "emitForProject">;- alertChannelRecipientDAL: Pick<TAlertChannelRecipientDALFactory, "deleteUsersRecipientsByScope">;+ alertChannelRecipientDAL: Pick<TAlertChannelRecipientDALFactory, "pruneOutOfScopeRecipients">;};export type TMembershipUserServiceFactory = ReturnType<typeof membershipUserServiceFactory>;@@ -555,14 +555,9 @@ export const membershipUserServiceFactory = ({userGroupMembershipDAL,membershipRoleDAL,additionalPrivilegeDAL,- approvalPolicyDAL+ approvalPolicyDAL,+ alertChannelRecipientDAL});- // Prune the user's alert-channel recipient rows across the whole org (org- and- // project-scoped channels) since leaving the org drops all their access.- await alertChannelRecipientDAL.deleteUsersRecipientsByScope(- { userIds: [dto.selector.userId], orgId: dto.permission.orgId },- tx- );return doc;}@@ -583,16 +578,15 @@ export const membershipUserServiceFactory = ({},tx);-- // Prune the user's alert-channel recipient rows for this project's channels only.- await alertChannelRecipientDAL.deleteUsersRecipientsByScope(- { userIds: [dto.selector.userId], projectId: dto.scopeData.projectId },- tx- );}await membershipRoleDAL.delete({ membershipId: existingMembership.id }, tx);const doc = await membershipUserDAL.deleteById(existingMembership.id, tx);++ if (dto.scopeData.scope === AccessScope.Project) {+ await alertChannelRecipientDAL.pruneOutOfScopeRecipients({ userIds: [dto.selector.userId] }, tx);+ }+return doc;};diff --git a/backend/src/services/org/org-fns.ts b/backend/src/services/org/org-fns.tsindex 25f67ec43f..abffe9b800 100644--- a/backend/src/services/org/org-fns.ts+++ b/backend/src/services/org/org-fns.ts@@ -7,6 +7,7 @@ import { TProjectKeyDALFactory } from "@app/services/project-key/project-key-dalimport { TUserAliasDALFactory } from "@app/services/user-alias/user-alias-dal";import { TAdditionalPrivilegeDALFactory } from "../additional-privilege/additional-privilege-dal";+import { TAlertChannelRecipientDALFactory } from "../alert/alert-channel-recipient-dal";import { TApprovalPolicyDALFactory } from "../approval-policy/approval-policy-dal";import { APPLICATION_APPROVAL_SCOPES } from "../membership/application-membership-cleanup-service";import { TMembershipRoleDALFactory } from "../membership/membership-role-dal";@@ -26,6 +27,7 @@ type TDeleteOrgMemberships = {userId?: string;additionalPrivilegeDAL: Pick<TAdditionalPrivilegeDALFactory, "delete">;approvalPolicyDAL: Pick<TApprovalPolicyDALFactory, "deleteUserStepApproversInProjects">;+ alertChannelRecipientDAL: Pick<TAlertChannelRecipientDALFactory, "pruneOutOfScopeRecipients">;};export const deleteOrgMembershipsFn = async ({@@ -39,7 +41,8 @@ export const deleteOrgMembershipsFn = async ({membershipUserDAL,userGroupMembershipDAL,additionalPrivilegeDAL,- approvalPolicyDAL+ approvalPolicyDAL,+ alertChannelRecipientDAL}: TDeleteOrgMemberships) => {const deletedMemberships = await orgDAL.transaction(async (tx) => {await assertWillRetainOrgAdmin({@@ -149,6 +152,8 @@ export const deleteOrgMembershipsFn = async ({tx);+ await alertChannelRecipientDAL.pruneOutOfScopeRecipients({ userIds: membershipUserIds }, tx);+await licenseService.updateSubscriptionOrgMemberCount(orgId);return orgMemberships;});diff --git a/backend/src/services/org/org-service.ts b/backend/src/services/org/org-service.tsindex 2d71eb3e06..61df87286c 100644--- a/backend/src/services/org/org-service.ts+++ b/backend/src/services/org/org-service.ts@@ -45,6 +45,7 @@ import { TOrgMembershipDALFactory } from "@app/services/org-membership/org-membeimport { TUserAliasDALFactory } from "@app/services/user-alias/user-alias-dal";import { TAdditionalPrivilegeDALFactory } from "../additional-privilege/additional-privilege-dal";+import { TAlertChannelRecipientDALFactory } from "../alert/alert-channel-recipient-dal";import { TApprovalPolicyDALFactory } from "../approval-policy/approval-policy-dal";import { TAuthLoginFactory } from "../auth/auth-login-service";import { ActorAuthMethod, ActorType, AuthMethod, AuthModeJwtTokenPayload, AuthTokenType } from "../auth/auth-type";@@ -129,6 +130,7 @@ type TOrgServiceFactoryDep = {userGroupMembershipDAL: TUserGroupMembershipDALFactory;additionalPrivilegeDAL: TAdditionalPrivilegeDALFactory;approvalPolicyDAL: Pick<TApprovalPolicyDALFactory, "deleteUserStepApproversInProjects">;+ alertChannelRecipientDAL: Pick<TAlertChannelRecipientDALFactory, "pruneOutOfScopeRecipients">;certificatePolicyDAL: Pick<TCertificatePolicyDALFactory, "create">;usageMeteringService: Pick<TUsageMeteringServiceFactory, "emit">;};@@ -166,6 +168,7 @@ export const orgServiceFactory = ({userGroupMembershipDAL,additionalPrivilegeDAL,approvalPolicyDAL,+ alertChannelRecipientDAL,certificatePolicyDAL,usageMeteringService}: TOrgServiceFactoryDep) => {@@ -1206,7 +1209,8 @@ export const orgServiceFactory = ({membershipRoleDAL,userGroupMembershipDAL,additionalPrivilegeDAL,- approvalPolicyDAL+ approvalPolicyDAL,+ alertChannelRecipientDAL});// Removing an org member cascades their project + group memberships, changing the identity meters.@@ -1248,7 +1252,8 @@ export const orgServiceFactory = ({membershipRoleDAL,userGroupMembershipDAL,additionalPrivilegeDAL,- approvalPolicyDAL+ approvalPolicyDAL,+ alertChannelRecipientDAL});// Removing org members cascades their project + group memberships, changing the identity meters.diff --git a/backend/src/services/project-membership/project-membership-service.ts b/backend/src/services/project-membership/project-membership-service.tsindex 2f0cf870a7..2cdcfa4c17 100644--- a/backend/src/services/project-membership/project-membership-service.ts+++ b/backend/src/services/project-membership/project-membership-service.ts@@ -20,6 +20,7 @@ import { TUserGroupMembershipDALFactory } from "../../ee/services/group/user-groimport { TSecretApprovalPolicyApproverDALFactory } from "../../ee/services/secret-approval-policy/secret-approval-policy-approver-dal";import { TSecretApprovalPolicyDALFactory } from "../../ee/services/secret-approval-policy/secret-approval-policy-dal";import { TAdditionalPrivilegeDALFactory } from "../additional-privilege/additional-privilege-dal";+import { TAlertChannelRecipientDALFactory } from "../alert/alert-channel-recipient-dal";import { ActorType } from "../auth/auth-type";import { TGroupProjectDALFactory } from "../group-project/group-project-dal";import { TApplicationMembershipCleanupServiceFactory } from "../membership/application-membership-cleanup-service";@@ -66,6 +67,7 @@ type TProjectMembershipServiceFactoryDep = {"cleanupActorApplicationMemberships" | "cleanupUsersApplicationMemberships">;usageMeteringService: Pick<TUsageMeteringServiceFactory, "emitForProject">;+ alertChannelRecipientDAL: Pick<TAlertChannelRecipientDALFactory, "pruneOutOfScopeRecipients">;};export type TProjectMembershipServiceFactory = ReturnType<typeof projectMembershipServiceFactory>;@@ -89,7 +91,8 @@ export const projectMembershipServiceFactory = ({userDAL,membershipRoleDAL,applicationMembershipCleanupService,- usageMeteringService+ usageMeteringService,+ alertChannelRecipientDAL}: TProjectMembershipServiceFactoryDep) => {const checkUserApproverPolicies = async (userIds: string[],@@ -403,6 +406,11 @@ export const projectMembershipServiceFactory = ({tx);+ await alertChannelRecipientDAL.pruneOutOfScopeRecipients(+ { userIds: projectMembers.map(({ user }) => user.id) },+ tx+ );+return deletedMemberships;};@@ -494,6 +502,8 @@ export const projectMembershipServiceFactory = ({tx);+ await alertChannelRecipientDAL.pruneOutOfScopeRecipients({ userIds: [actorId] }, tx);+return membership;});diff --git a/backend/src/services/super-admin/super-admin-service.ts b/backend/src/services/super-admin/super-admin-service.tsindex 95f1b1f669..359316a2c0 100644--- a/backend/src/services/super-admin/super-admin-service.ts+++ b/backend/src/services/super-admin/super-admin-service.ts@@ -35,6 +35,8 @@ import { IdentitiesMeter, PamIdentities, SecretIdentities, UserIdentities } fromimport { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";import { SmtpTemplates, TSmtpService } from "@app/services/smtp/smtp-service";+import { TAlertChannelRecipientDALFactory } from "../alert/alert-channel-recipient-dal";+import { AlertPrincipalType } from "../alert/alert-types";import { TAuthLoginFactory } from "../auth/auth-login-service";import { ActorType, AuthMethod, AuthTokenType } from "../auth/auth-type";import { TIdentityAccessTokenDALFactory } from "../identity-access-token/identity-access-token-dal";@@ -82,6 +84,7 @@ type TSuperAdminServiceFactoryDep = {membershipUserDAL: TMembershipUserDALFactory;membershipIdentityDAL: TMembershipIdentityDALFactory;membershipRoleDAL: TMembershipRoleDALFactory;+ alertChannelRecipientDAL: Pick<TAlertChannelRecipientDALFactory, "pruneOutOfScopeRecipients" | "deleteByPrincipals">;userAliasDAL: Pick<TUserAliasDALFactory, "findOne">;emailDomainDAL: TEmailDomainDALFactory;authService: Pick<TAuthLoginFactory, "generateUserTokens">;@@ -157,7 +160,8 @@ export const superAdminServiceFactory = ({membershipIdentityDAL,membershipUserDAL,membershipRoleDAL,- usageMeteringService+ usageMeteringService,+ alertChannelRecipientDAL}: TSuperAdminServiceFactoryDep) => {const initServerCfg = async () => {// TODO(akhilmhdh): bad pattern time less change this later to me itself@@ -735,7 +739,16 @@ export const superAdminServiceFactory = ({actorUserId: userId});- const user = await userDAL.deleteById(userId);+ const user = await userDAL.transaction(async (tx) => {+ const deletedUser = await userDAL.deleteById(userId, tx);+ // principalId carries no FK, so the user row going away leaves recipient rows behind.+ await alertChannelRecipientDAL.deleteByPrincipals(+ { principalType: AlertPrincipalType.USER, principalIds: [userId] },+ tx+ );+ return deletedUser;+ });+emitUserDeletionMeterEvents(orgMemberships);return user;};@@ -756,11 +769,22 @@ export const superAdminServiceFactory = ({$in: { actorUserId: userIds }});- const users = await userDAL.delete({- $in: {- id: userIds- }+ const users = await userDAL.transaction(async (tx) => {+ const deletedUsers = await userDAL.delete(+ {+ $in: {+ id: userIds+ }+ },+ tx+ );+ await alertChannelRecipientDAL.deleteByPrincipals(+ { principalType: AlertPrincipalType.USER, principalIds: userIds },+ tx+ );+ return deletedUsers;});+emitUserDeletionMeterEvents(orgMemberships);return users;};@@ -1016,6 +1040,11 @@ export const superAdminServiceFactory = ({scope: AccessScope.Organization,id: membershipId});++ if (organizationMembership?.actorUserId) {+ await alertChannelRecipientDAL.pruneOutOfScopeRecipients({ userIds: [organizationMembership.actorUserId] });+ }+return { ...organizationMembership, role: membershipRole.role, orgId: organizationId };};diff --git a/backend/src/services/user/user-service.ts b/backend/src/services/user/user-service.tsindex 859dd8b1de..fee62d8e50 100644--- a/backend/src/services/user/user-service.ts+++ b/backend/src/services/user/user-service.ts@@ -513,7 +513,15 @@ export const userServiceFactory = ({const myAccount = users?.find((el) => el.id === userId);if (duplicatedAccounts.length && myAccount) {await userDAL.transaction(async (tx) => {- await userDAL.delete({ $in: { id: duplicatedAccounts?.map((el) => el.id) } }, tx);+ const duplicatedAccountIds = duplicatedAccounts.map((el) => el.id);+ await userDAL.delete({ $in: { id: duplicatedAccountIds } }, tx);+ await alertChannelRecipientDAL.deleteByPrincipals(+ {+ principalType: AlertPrincipalType.USER,+ principalIds: duplicatedAccountIds+ },+ tx+ );await userDAL.updateById(userId, { username: (myAccount.email || myAccount.username).toLowerCase() }, tx);});}diff --git a/frontend/src/views/Alerts/AlertDetail.tsx b/frontend/src/views/Alerts/AlertDetail.tsxindex 305f39730c..2c90dd4e73 100644--- a/frontend/src/views/Alerts/AlertDetail.tsx+++ b/frontend/src/views/Alerts/AlertDetail.tsx@@ -1,5 +1,12 @@import { ReactNode } from "react";-import { BellPlusIcon, MoreHorizontalIcon, PencilIcon, TrashIcon } from "lucide-react";+import {+ BanIcon,+ BellPlusIcon,+ CheckIcon,+ MoreHorizontalIcon,+ PencilIcon,+ TrashIcon+} from "lucide-react";import { createNotification } from "@app/components/notifications";import { DeleteActionModal } from "@app/components/v2";@@ -86,6 +93,7 @@ export const AlertDetail = ({return (<div className="flex w-full items-center gap-2"><Badge variant={existingAlert.enabled ? "success" : "neutral"}>+ {existingAlert.enabled ? <CheckIcon /> : <BanIcon />}{existingAlert.enabled ? "Enabled" : "Disabled"}</Badge><span className="min-w-0 flex-1 truncate text-xs text-muted">{summary}</span>diff --git a/frontend/src/views/Alerts/ChannelRecipientsField.tsx b/frontend/src/views/Alerts/ChannelRecipientsField.tsxindex 8e25f7be01..5fae5bc9ee 100644--- a/frontend/src/views/Alerts/ChannelRecipientsField.tsx+++ b/frontend/src/views/Alerts/ChannelRecipientsField.tsx@@ -142,7 +142,7 @@ const ProjectRecipientSelect = ({orgId,...props}: SelectProps & { projectId: string; orgId: string }) => {- const { data: users = [] } = useGetWorkspaceUsers(projectId);+ const { data: users = [] } = useGetWorkspaceUsers(projectId, true);const { data: orgUsers = [] } = useGetOrgUsers(orgId);const { data: groups = [] } = useListWorkspaceGroups(projectId);