Skip to content

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

remove recipient in case of hard delete

Thiago Araujo da Silvaef09c6eb3238
diff --git a/backend/src/db/migrations/20260714120000_add-alerts.ts b/backend/src/db/migrations/20260714120000_add-alerts.ts
index 0690b0cc12..ee3cbe8a23 100644
--- a/backend/src/db/migrations/20260714120000_add-alerts.ts
+++ b/backend/src/db/migrations/20260714120000_add-alerts.ts
@@ -23,7 +23,8 @@ export async function up(knex: Knex): Promise<void> {
t.foreign("orgId").references("id").inTable(TableName.Organization).onDelete("CASCADE");
t.foreign("projectId").references("id").inTable(TableName.Project).onDelete("CASCADE");
- t.index("orgId");
+ // No standalone orgId index: alert_unique_scope_resource_event below has orgId as its leftmost
+ // column, so it already serves the orgId FK and every org-scoped lookup.
t.index("projectId");
t.index(["resourceType", "triggerType", "enabled"]);
});
@@ -72,8 +73,11 @@ export async function up(knex: Knex): Promise<void> {
t.timestamps(true, true, true);
t.foreign("channelId").references("id").inTable(TableName.AlertChannel).onDelete("CASCADE");
- t.index("channelId");
+ // The unique index below is leftmost on channelId, so it already covers the channelId FK.
t.unique(["channelId", "principalType", "principalId"]);
+ // Serves principal-side cleanup: pruning a user's rows when they leave, and a group's rows when
+ // the group is deleted. Neither can use the channelId-leading index.
+ t.index(["principalType", "principalId"]);
});
await createOnUpdateTrigger(knex, TableName.AlertChannelRecipient);
@@ -91,7 +95,8 @@ export async function up(knex: Knex): Promise<void> {
t.foreign("alertId").references("id").inTable(TableName.Alert).onDelete("CASCADE");
t.foreign("channelId").references("id").inTable(TableName.AlertChannel).onDelete("CASCADE");
- t.index("alertId");
+ // The unique index below is leftmost on alertId, so it already covers the alertId FK. channelId
+ // needs its own index for the other FK.
t.index("channelId");
t.unique(["alertId", "channelId"]);
});
diff --git a/backend/src/ee/services/group/group-service.ts b/backend/src/ee/services/group/group-service.ts
index 9746b2e8db..c92b2e0b16 100644
--- a/backend/src/ee/services/group/group-service.ts
+++ b/backend/src/ee/services/group/group-service.ts
@@ -23,6 +23,8 @@ import { alphaNumericNanoId } from "@app/lib/nanoid";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
import { TGenericPermission } from "@app/lib/types";
+import { TAlertChannelRecipientDALFactory } from "@app/services/alert/alert-channel-recipient-dal";
+import { AlertPrincipalType } from "@app/services/alert/alert-types";
import { TIdentityDALFactory } from "@app/services/identity/identity-dal";
import { TIdentityAccessTokenServiceFactory } from "@app/services/identity-access-token/identity-access-token-service";
import { PamIdentities, SecretIdentities } from "@app/services/license-client";
@@ -102,6 +104,7 @@ type TGroupServiceFactoryDep = {
oidcConfigDAL: Pick<TOidcConfigDALFactory, "findOne">;
usageMeteringService: Pick<TUsageMeteringServiceFactory, "emit">;
identityAccessTokenService: Pick<TIdentityAccessTokenServiceFactory, "bumpIdentityRevocationVersion">;
+ alertChannelRecipientDAL: Pick<TAlertChannelRecipientDALFactory, "deleteByPrincipals">;
};
export type TGroupServiceFactory = ReturnType<typeof groupServiceFactory>;
@@ -123,7 +126,8 @@ export const groupServiceFactory = ({
membershipGroupDAL,
membershipRoleDAL,
usageMeteringService,
- identityAccessTokenService
+ identityAccessTokenService,
+ alertChannelRecipientDAL
}: TGroupServiceFactoryDep) => {
const createGroup = async ({ name, slug, role, actor, actorId, actorAuthMethod, actorOrgId }: TCreateGroupDTO) => {
if (!actorOrgId) throw new UnauthorizedError({ message: "No organization ID provided in request" });
@@ -577,6 +581,11 @@ export const groupServiceFactory = ({
orgId: actorOrgId
});
+ await alertChannelRecipientDAL.deleteByPrincipals({
+ principalType: AlertPrincipalType.GROUP,
+ principalIds: [groupId]
+ });
+
return deletedGroup;
};
diff --git a/backend/src/lib/config/request.ts b/backend/src/lib/config/request.ts
index 8947af176e..83c7e1ff90 100644
--- a/backend/src/lib/config/request.ts
+++ b/backend/src/lib/config/request.ts
@@ -28,7 +28,7 @@ export function axiosResponseInterceptor(response: AxiosResponse, customLogger:
export const isRetryableRequestError = (error: AxiosError): boolean =>
error.response?.status === 429 || axiosRetry.isNetworkError(error) || axiosRetry.isRetryableError(error);
-export const REQUEST_RETRY_CONFIG = {
+const REQUEST_RETRY_CONFIG = {
retries: 3,
// eslint-disable-next-line
retryDelay: axiosRetry.exponentialDelay
diff --git a/backend/src/lib/telemetry/metrics.ts b/backend/src/lib/telemetry/metrics.ts
index bebfcff396..e22f097b04 100644
--- a/backend/src/lib/telemetry/metrics.ts
+++ b/backend/src/lib/telemetry/metrics.ts
@@ -613,7 +613,7 @@ export enum AlertDispatchOutcome {
NoProvider = "no_provider",
// Nothing matched the alert condition in this run.
NoDueTargets = "no_due_targets",
- // Targets matched, but the alert has no enabled channels to notify.
+ // The alert has no enabled channels, so the run is skipped before scanning for targets.
NoChannels = "no_channels",
// Targets matched, but every one had already been alerted inside the dedup window.
AllDeduped = "all_deduped"
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 1977c52e4f..091034ad41 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -1163,7 +1163,8 @@ export const registerRoutes = async (
membershipGroupDAL,
membershipRoleDAL,
usageMeteringService,
- identityAccessTokenService
+ identityAccessTokenService,
+ alertChannelRecipientDAL
});
const groupProjectService = groupProjectServiceFactory({
groupDAL,
@@ -1288,7 +1289,8 @@ export const registerRoutes = async (
totpConfigDAL,
webAuthnCredentialDAL,
mfaRecoveryCodeService,
- usageMeteringService
+ usageMeteringService,
+ alertChannelRecipientDAL
});
const totpService = totpServiceFactory({
diff --git a/backend/src/services/alert/alert-channel-recipient-dal.test.ts b/backend/src/services/alert/alert-channel-recipient-dal.test.ts
index 370d466535..e9a2ca8d8a 100644
--- a/backend/src/services/alert/alert-channel-recipient-dal.test.ts
+++ b/backend/src/services/alert/alert-channel-recipient-dal.test.ts
@@ -1,6 +1,7 @@
import { TableName } from "@app/db/schemas";
import { alertChannelRecipientDALFactory } from "./alert-channel-recipient-dal";
+import { AlertPrincipalType } from "./alert-types";
// Records query-builder calls so we can assert the scope cleanup filters correctly without a DB.
const buildDAL = () => {
@@ -60,3 +61,27 @@ describe("alert channel recipient dal — scope cleanup", () => {
expect(calls.channelWhere).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 } = buildDAL();
+
+ const deleted = await dal.deleteByPrincipals({
+ principalType: AlertPrincipalType.GROUP,
+ principalIds: ["g1"]
+ });
+
+ 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(calls.channelWhere).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);
+ });
+});
diff --git a/backend/src/services/alert/alert-channel-recipient-dal.ts b/backend/src/services/alert/alert-channel-recipient-dal.ts
index 6101b18722..448ef08334 100644
--- a/backend/src/services/alert/alert-channel-recipient-dal.ts
+++ b/backend/src/services/alert/alert-channel-recipient-dal.ts
@@ -35,6 +35,24 @@ export const alertChannelRecipientDALFactory = (db: TDbClient) => {
}
};
+ // Prunes recipient rows for principals that no longer exist anywhere (a hard-deleted user or group).
+ // principalId carries no FK, so nothing cascades these away on its own.
+ const deleteByPrincipals = async (
+ { principalType, principalIds }: { principalType: AlertPrincipalType; principalIds: string[] },
+ tx?: Knex
+ ): Promise<number> => {
+ try {
+ if (!principalIds.length) return 0;
+
+ return await (tx || db)(TableName.AlertChannelRecipient)
+ .where(`${TableName.AlertChannelRecipient}.principalType`, principalType)
+ .whereIn(`${TableName.AlertChannelRecipient}.principalId`, principalIds)
+ .del();
+ } catch (error) {
+ throw new DatabaseError({ error, name: "DeleteByPrincipals" });
+ }
+ };
+
const deleteUsersRecipientsByScope = async (
{ userIds, orgId, projectId }: { userIds: string[]; orgId?: string; projectId?: string },
tx?: Knex
@@ -60,6 +78,7 @@ export const alertChannelRecipientDALFactory = (db: TDbClient) => {
...alertChannelRecipientOrm,
findByChannelIds,
deleteByChannelId,
+ deleteByPrincipals,
deleteUsersRecipientsByScope
};
};
diff --git a/backend/src/services/alert/alert-engine.test.ts b/backend/src/services/alert/alert-engine.test.ts
index f662940c39..00adfff308 100644
--- a/backend/src/services/alert/alert-engine.test.ts
+++ b/backend/src/services/alert/alert-engine.test.ts
@@ -53,11 +53,14 @@ const makeAlert = () => ({
updatedAt: new Date()
});
-const makeProvider = (targets: TTarget[]): IResourceAlertProvider<TTarget> => ({
+const makeProvider = (targets: TTarget[], onFindDueTargets?: () => void): IResourceAlertProvider<TTarget> => ({
resourceType: RESOURCE_TYPE,
eventTypes: ["test.resource.expiration"],
conditionSchema: z.any(),
- findDueTargets: async () => targets,
+ findDueTargets: async () => {
+ onFindDueTargets?.();
+ return targets;
+ },
assertPermission: async () => undefined,
assertResourceInScope: async () => undefined,
targetId: (target) => target.id,
@@ -101,7 +104,12 @@ const buildEngine = (opts: {
failEmailFor?: string;
}) => {
const registry = alertProviderRegistryFactory();
- registry.register(makeProvider(opts.targets) as IResourceAlertProvider);
+ let findDueTargetsCalls = 0;
+ registry.register(
+ makeProvider(opts.targets, () => {
+ findDueTargetsCalls += 1;
+ }) as IResourceAlertProvider
+ );
const sentMail: Array<{ recipients: string[] }> = [];
const historyWrites: Array<{ deliveries: TDelivery[]; status: string }> = [];
@@ -161,7 +169,13 @@ const buildEngine = (opts: {
}
} as unknown as TAlertEngineDep);
- return { engine, sentMail, historyWrites, getPeakConcurrentSends: () => peakConcurrentSends };
+ return {
+ engine,
+ sentMail,
+ historyWrites,
+ getPeakConcurrentSends: () => peakConcurrentSends,
+ getFindDueTargetsCalls: () => findDueTargetsCalls
+ };
};
describe("alert engine", () => {
@@ -386,8 +400,8 @@ describe("alert engine", () => {
expect(getPeakConcurrentSends()).toBeGreaterThan(1);
});
- test("writes no history when there are no enabled channels", async () => {
- const { engine, historyWrites } = buildEngine({
+ test("writes no history and skips the resource scan when there are no enabled channels", async () => {
+ const { engine, historyWrites, getFindDueTargetsCalls } = buildEngine({
targets: [{ id: "t1" }],
channels: [{ id: "c-email", channelType: "email", encryptedConfig: encConfig({}), enabled: false }]
});
@@ -396,6 +410,8 @@ describe("alert engine", () => {
expect(outcome).toBe(AlertDispatchOutcome.NoChannels);
expect(historyWrites).toHaveLength(0);
+ // The scan is the expensive part of a run; a channel-less alert must not pay for it daily.
+ expect(getFindDueTargetsCalls()).toBe(0);
});
test("reports no due targets when nothing matches the condition", async () => {
diff --git a/backend/src/services/alert/alert-engine.ts b/backend/src/services/alert/alert-engine.ts
index c46d8d1cc5..db54b11281 100644
--- a/backend/src/services/alert/alert-engine.ts
+++ b/backend/src/services/alert/alert-engine.ts
@@ -55,7 +55,10 @@ export const alertEngineFactory = ({
return AlertDispatchOutcome.NoProvider;
}
- const targets = await provider.findDueTargets({
+ const channels = await alertChannelDAL.findByAlertId(alert.id, { enabled: true });
+ if (channels.length === 0) return AlertDispatchOutcome.NoChannels;
+
+ const dueTargets = await provider.findDueTargets({
orgId: alert.orgId,
projectId: alert.projectId,
resourceId: alert.resourceId,
@@ -63,30 +66,32 @@ export const alertEngineFactory = ({
condition: alert.condition,
asOf: opts?.asOf ?? new Date()
});
- if (targets.length === 0) return AlertDispatchOutcome.NoDueTargets;
+ if (dueTargets.length === 0) return AlertDispatchOutcome.NoDueTargets;
- const channels = await alertChannelDAL.findByAlertId(alert.id, { enabled: true });
- if (channels.length === 0) return AlertDispatchOutcome.NoChannels;
+ const targets = dueTargets.map((target) => ({ target, id: provider.targetId(target) }));
const window = provider.dedupWindowHours?.(alert.condition) ?? DEFAULT_DEDUP_WINDOW_HOURS;
- const candidateIds = targets.map((target) => provider.targetId(target));
- const recentlyAlerted = await alertHistoryDAL.findRecentlyAlertedTargets(alert.id, candidateIds, window);
+ const recentlyAlerted = await alertHistoryDAL.findRecentlyAlertedTargets(
+ alert.id,
+ targets.map((target) => target.id),
+ window
+ );
const alertedSet = new Set(recentlyAlerted.map((row) => `${row.channelId}:${row.targetId}`));
const channelWork = channels
.map((channel) => {
const definition = ALERT_CHANNEL_REGISTRY[channel.channelType as AlertChannelType];
- const dueTargets = targets.filter((target) => !alertedSet.has(`${channel.id}:${provider.targetId(target)}`));
+ const due = targets.filter((target) => !alertedSet.has(`${channel.id}:${target.id}`));
const cap = definition?.maxTargetsPerRun;
- if (cap && dueTargets.length > cap) {
+ if (cap && due.length > cap) {
logger.info(
- `Alert ${channel.channelType} channel capped at ${cap} targets this run; ${dueTargets.length - cap} deferred to the next run [alertId=${alert.id}] [channelId=${channel.id}]`
+ `Alert ${channel.channelType} channel capped at ${cap} targets this run; ${due.length - cap} deferred to the next run [alertId=${alert.id}] [channelId=${channel.id}]`
);
- return { channel, dueTargets: dueTargets.slice(0, cap) };
+ return { channel, due: due.slice(0, cap) };
}
- return { channel, dueTargets };
+ return { channel, due };
})
- .filter((work) => work.dueTargets.length > 0);
+ .filter((work) => work.due.length > 0);
if (channelWork.length === 0) return AlertDispatchOutcome.AllDeduped;
const alertContext: TAlertContext = {
@@ -129,8 +134,8 @@ export const alertEngineFactory = ({
const sendLimit = pLimit(ALERT_DELIVERY_CONCURRENCY);
const channelResults = await Promise.all(
- channelWork.map(async ({ channel, dueTargets }): Promise<TChannelDispatchResult> => {
- const targetIds = dueTargets.map((target) => provider.targetId(target));
+ channelWork.map(async ({ channel, due }): Promise<TChannelDispatchResult> => {
+ const targetIds = due.map((target) => target.id);
const base = { channelId: channel.id, channelType: channel.channelType, targetIds };
const definition = ALERT_CHANNEL_REGISTRY[channel.channelType as AlertChannelType];
if (!definition) return { ...base, success: false, error: "Unknown channel type" };
@@ -143,7 +148,11 @@ export const alertEngineFactory = ({
return { ...base, success: false, error: "Failed to decrypt channel config" };
}
- const payload = provider.buildPayload(alertContext, dueTargets, viewUrl);
+ const payload = provider.buildPayload(
+ alertContext,
+ due.map((target) => target.target),
+ viewUrl
+ );
try {
if (definition.directed) {
diff --git a/backend/src/services/alert/channels/alert-channel-email-fns.ts b/backend/src/services/alert/channels/alert-channel-email-fns.ts
index d58e663d67..95b7bfd993 100644
--- a/backend/src/services/alert/channels/alert-channel-email-fns.ts
+++ b/backend/src/services/alert/channels/alert-channel-email-fns.ts
@@ -1,4 +1,4 @@
-import { RETRYABLE_NETWORK_ERRORS } from "@app/lib/retry/network-errors";
+import { logger } from "@app/lib/logger";
import { SmtpTemplates } from "@app/services/smtp/smtp-service";
import {
@@ -7,15 +7,6 @@ import {
TAlertPayload,
TChannelResult
} from "../alert-channel-types";
-import { deliverWithRetry } from "./alert-channel-retry-fns";
-
-const isEmailErrorRetryable = (err: unknown): boolean => {
- const msg = (err instanceof Error ? err.message : String(err)).toLowerCase();
- if (RETRYABLE_NETWORK_ERRORS.some((code) => msg.includes(code.toLowerCase()))) return true;
- if (msg.includes("timeout") || msg.includes("connection")) return true;
- if (["421", "450", "451", "452"].some((code) => msg.includes(code))) return true;
- return false;
-};
const buildSubstitutions = (payload: TAlertPayload) => ({
alertName: payload.alert.name,
@@ -33,11 +24,11 @@ const buildSubstitutions = (payload: TAlertPayload) => ({
const sendEmail = async (
smtpService: TAlertChannelSendContext["deps"]["smtpService"],
- recipients: string[],
+ recipient: string,
payload: TAlertPayload
): Promise<void> => {
await smtpService.sendMail({
- recipients,
+ recipients: [recipient],
subjectLine: `Infisical ${payload.resourceKind} ${payload.eventLabel} Alert`,
substitutions: buildSubstitutions(payload),
template: SmtpTemplates.AlertNotification
@@ -47,13 +38,17 @@ const sendEmail = async (
export const sendEmailNotification = async (ctx: TAlertChannelSendContext): Promise<TChannelResult> => {
EmailChannelConfigSchema.parse(ctx.config);
- if (!ctx.recipient?.email) {
+ const recipient = ctx.recipient?.email;
+ if (!recipient) {
return { success: false, error: "No recipient for email channel" };
}
- const recipients = [ctx.recipient.email];
- return deliverWithRetry(() => sendEmail(ctx.deps.smtpService, recipients, ctx.payload), isEmailErrorRetryable, {
- channelId: ctx.channelId,
- channelLabel: "email"
- });
+ try {
+ await sendEmail(ctx.deps.smtpService, recipient, ctx.payload);
+ return { success: true };
+ } catch (err) {
+ const error = err instanceof Error ? err.message : String(err);
+ logger.info({ channelId: ctx.channelId, error }, `Alert email delivery failed [channelId=${ctx.channelId}]`);
+ return { success: false, error };
+ }
};
diff --git a/backend/src/services/alert/channels/alert-channel-retry-fns.ts b/backend/src/services/alert/channels/alert-channel-retry-fns.ts
deleted file mode 100644
index 9a963be417..0000000000
--- a/backend/src/services/alert/channels/alert-channel-retry-fns.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-import { AxiosError } from "axios";
-
-import { REQUEST_RETRY_CONFIG } from "@app/lib/config/request";
-import { delay } from "@app/lib/delay";
-import { logger } from "@app/lib/logger";
-
-import { TChannelResult } from "../alert-channel-types";
-
-export const deliverWithRetry = async (
- fn: () => Promise<void>,
- isRetryable: (err: unknown) => boolean,
- ctx: { channelId: string; channelLabel: string }
-): Promise<TChannelResult> => {
- const { retries, retryDelay } = REQUEST_RETRY_CONFIG;
- let lastError: Error | undefined;
-
- for (let attempt = 0; attempt <= retries; attempt += 1) {
- try {
- // eslint-disable-next-line no-await-in-loop
- await fn();
- return { success: true };
- } catch (err) {
- lastError = err instanceof Error ? err : new Error(String(err));
- const statusCode = (lastError as AxiosError).response?.status;
-
- if (!isRetryable(lastError)) {
- logger.info(
- { channelId: ctx.channelId, statusCode, error: lastError.message },
- `Alert ${ctx.channelLabel} delivery error is not retryable [channelId=${ctx.channelId}]`
- );
- return { success: false, error: lastError.message };
- }
-
- const delayMs = attempt < retries ? retryDelay(attempt + 1) : 0;
- logger.info(
- { channelId: ctx.channelId, attempt: attempt + 1, retries, statusCode, error: lastError.message },
- `Alert ${ctx.channelLabel} delivery failed, ${attempt < retries ? `retrying in ${Math.round(delayMs)}ms` : "no more retries"} [channelId=${ctx.channelId}]`
- );
-
- if (attempt < retries) {
- // eslint-disable-next-line no-await-in-loop
- await delay(delayMs);
- }
- }
- }
-
- return { success: false, error: lastError?.message };
-};
diff --git a/backend/src/services/alert/channels/alert-channels.test.ts b/backend/src/services/alert/channels/alert-channels.test.ts
index 16fcb8ae23..6791b32fb9 100644
--- a/backend/src/services/alert/channels/alert-channels.test.ts
+++ b/backend/src/services/alert/channels/alert-channels.test.ts
@@ -1,5 +1,3 @@
-import { REQUEST_RETRY_CONFIG } from "@app/lib/config/request";
-
import { AlertChannelType, SlackChannelConfigSchema, TAlertPayload } from "../alert-channel-types";
import { sendEmailNotification } from "./alert-channel-email-fns";
import { buildPagerDutyEvent } from "./alert-channel-pagerduty-fns";
@@ -218,10 +216,10 @@ describe("sendEmailNotification (directed)", () => {
expect(result.success).toBe(false);
});
- // SMTP has no client-level retry, so the channel retries on the same terms as the shared axios
- // client the HTTP channels dispatch through: one initial attempt plus REQUEST_RETRY_CONFIG.retries.
- test("retries a transient SMTP failure as many times as an outbound request would", async () => {
- vi.useFakeTimers();
+ // SMTP submission has no idempotency key, so a retry across an ambiguous failure would deliver the
+ // same alert twice. The send is attempted once and the failure is surfaced instead, matching every
+ // other email path on the platform; the engine records it so the next run retries the target.
+ test("attempts a failing send once and reports the error rather than retrying", async () => {
let attempts = 0;
const ctx = {
...baseCtx(),
@@ -238,12 +236,10 @@ describe("sendEmailNotification (directed)", () => {
}
};
- const pending = sendEmailNotification(ctx);
- await vi.runAllTimersAsync();
- const result = await pending;
- vi.useRealTimers();
+ const result = await sendEmailNotification(ctx);
- expect(attempts).toBe(1 + REQUEST_RETRY_CONFIG.retries);
+ expect(attempts).toBe(1);
expect(result.success).toBe(false);
+ expect(result.error).toBe("connection timeout");
});
});
diff --git a/backend/src/services/alert/providers/identity-credential-alert-provider.ts b/backend/src/services/alert/providers/identity-credential-alert-provider.ts
index 8b5a4bc80e..f13699f098 100644
--- a/backend/src/services/alert/providers/identity-credential-alert-provider.ts
+++ b/backend/src/services/alert/providers/identity-credential-alert-provider.ts
@@ -26,8 +26,8 @@ export const IDENTITY_AUTHENTICATION_RESOURCE_TYPE = "identity.authentication";
export const IDENTITY_AUTHENTICATION_EXPIRY_EVENT = "identity.authentication.expiry";
const alertBeforeRegex = new RE2("^\\d+d$");
-export const MIN_ALERT_BEFORE_DAYS = 1;
-export const MAX_ALERT_BEFORE_DAYS = 90;
+const MIN_ALERT_BEFORE_DAYS = 1;
+const MAX_ALERT_BEFORE_DAYS = 90;
const alertBeforeDays = (alertBefore: string): number => parseInt(alertBefore.slice(0, -1), 10);
diff --git a/backend/src/services/user/user-service.ts b/backend/src/services/user/user-service.ts
index 94a858c737..c2194bb5f2 100644
--- a/backend/src/services/user/user-service.ts
+++ b/backend/src/services/user/user-service.ts
@@ -9,6 +9,8 @@ import { crypto } from "@app/lib/crypto";
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { sanitizeEmail, validateEmail } from "@app/lib/validator";
+import { TAlertChannelRecipientDALFactory } from "@app/services/alert/alert-channel-recipient-dal";
+import { AlertPrincipalType } from "@app/services/alert/alert-types";
import { TAuthTokenServiceFactory } from "@app/services/auth-token/auth-token-service";
import { TokenType } from "@app/services/auth-token/auth-token-types";
import { IdentitiesMeter, PamIdentities, SecretIdentities, UserIdentities } from "@app/services/license-client";
@@ -72,6 +74,7 @@ type TUserServiceFactoryDep = {
webAuthnCredentialDAL: Pick<TWebAuthnCredentialDALFactory, "find">;
mfaRecoveryCodeService: Pick<TMfaRecoveryCodeServiceFactory, "rotateRecoveryCodes" | "deleteRecoveryCodes">;
usageMeteringService: Pick<TUsageMeteringServiceFactory, "emit">;
+ alertChannelRecipientDAL: Pick<TAlertChannelRecipientDALFactory, "deleteByPrincipals">;
};
export type TUserServiceFactory = ReturnType<typeof userServiceFactory>;
@@ -88,7 +91,8 @@ export const userServiceFactory = ({
totpConfigDAL,
webAuthnCredentialDAL,
mfaRecoveryCodeService,
- usageMeteringService
+ usageMeteringService,
+ alertChannelRecipientDAL
}: TUserServiceFactoryDep) => {
const sendEmailVerificationCode = async (token: string) => {
const config = getConfig();
@@ -566,6 +570,11 @@ export const userServiceFactory = ({
const user = await userDAL.deleteById(userId);
+ await alertChannelRecipientDAL.deleteByPrincipals({
+ principalType: AlertPrincipalType.USER,
+ principalIds: [userId]
+ });
+
// Deleting the user cascades its org, project, and group memberships, so every identity meter changes.
const orgIds = [...new Set(orgMemberships.map((m) => m.scopeOrgId).filter((id): id is string => Boolean(id)))];
orgIds.forEach((orgId) => {
diff --git a/frontend/src/pages/organization/IdentityDetailsByIDPage/components/IdentityAlertDetail.tsx b/frontend/src/pages/organization/IdentityDetailsByIDPage/components/IdentityAlertDetail.tsx
index 5bf6be7633..bab4f8947f 100644
--- a/frontend/src/pages/organization/IdentityDetailsByIDPage/components/IdentityAlertDetail.tsx
+++ b/frontend/src/pages/organization/IdentityDetailsByIDPage/components/IdentityAlertDetail.tsx
@@ -12,10 +12,7 @@ export const IdentityAlertDetail = ({ identityId, identityName }: Props) => (
identityId={identityId}
identityName={identityName}
renderPermissionGate={(render) => (
- <OrgPermissionCan
- I={OrgPermissionIdentityActions.Edit}
- a={OrgPermissionSubjects.Identity}
- >
+ <OrgPermissionCan I={OrgPermissionIdentityActions.Edit} a={OrgPermissionSubjects.Identity}>
{render}
</OrgPermissionCan>
)}