Skip to content

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

feat(alerts): internal entry points and all-project-members recipients

Calvin508798f99171
diff --git a/backend/src/db/migrations/20260929120000_alerts-nullable-created-by-actor-id.ts b/backend/src/db/migrations/20260929120000_alerts-nullable-created-by-actor-id.ts
new file mode 100644
index 0000000000..cf2e289d82
--- /dev/null
+++ b/backend/src/db/migrations/20260929120000_alerts-nullable-created-by-actor-id.ts
@@ -0,0 +1,32 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+
+// Alerts created by the platform (data migrations, background jobs) have no actor id. The actor type
+// stays required so every row still says who or what created it.
+export async function up(knex: Knex): Promise<void> {
+ if (await knex.schema.hasColumn(TableName.Alert, "createdByActorId")) {
+ await knex.schema.alterTable(TableName.Alert, (t) => {
+ t.uuid("createdByActorId").nullable().alter();
+ });
+ }
+
+ if (await knex.schema.hasColumn(TableName.AlertChannel, "createdByActorId")) {
+ await knex.schema.alterTable(TableName.AlertChannel, (t) => {
+ t.uuid("createdByActorId").nullable().alter();
+ });
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ // Rows without an actor id cannot satisfy NOT NULL, and inventing an id would misattribute them.
+ await knex(TableName.Alert).whereNull("createdByActorId").delete();
+ await knex(TableName.AlertChannel).whereNull("createdByActorId").delete();
+
+ await knex.schema.alterTable(TableName.Alert, (t) => {
+ t.uuid("createdByActorId").notNullable().alter();
+ });
+ await knex.schema.alterTable(TableName.AlertChannel, (t) => {
+ t.uuid("createdByActorId").notNullable().alter();
+ });
+}
diff --git a/backend/src/db/schemas/alert-channels.ts b/backend/src/db/schemas/alert-channels.ts
index 3c43ad2058..da0a912b68 100644
--- a/backend/src/db/schemas/alert-channels.ts
+++ b/backend/src/db/schemas/alert-channels.ts
@@ -17,7 +17,7 @@ export const AlertChannelsSchema = z.object({
enabled: z.boolean().default(true),
orgId: z.string().uuid(),
projectId: z.string().nullable().optional(),
- createdByActorId: z.string().uuid(),
+ createdByActorId: z.string().uuid().nullable().optional(),
createdByActorType: z.string(),
createdAt: z.date(),
updatedAt: z.date()
diff --git a/backend/src/db/schemas/alerts.ts b/backend/src/db/schemas/alerts.ts
index 8a7867fb44..b41ad456a2 100644
--- a/backend/src/db/schemas/alerts.ts
+++ b/backend/src/db/schemas/alerts.ts
@@ -19,7 +19,7 @@ export const AlertsSchema = z.object({
enabled: z.boolean().default(true),
orgId: z.string().uuid(),
projectId: z.string().nullable().optional(),
- createdByActorId: z.string().uuid(),
+ createdByActorId: z.string().uuid().nullable().optional(),
createdByActorType: z.string(),
createdAt: z.date(),
updatedAt: z.date()
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 3526fefc23..1f4df71f61 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -1080,7 +1080,8 @@ export const registerRoutes = async (
userDAL,
userGroupMembershipDAL,
orgDAL,
- projectDAL
+ projectDAL,
+ projectMembershipDAL
});
const alertEngine = alertEngineFactory({
alertChannelDAL,
diff --git a/backend/src/services/alert/alert-channel-crypto-fns.ts b/backend/src/services/alert/alert-channel-crypto-fns.ts
index 9472bab0c9..735b83bd9f 100644
--- a/backend/src/services/alert/alert-channel-crypto-fns.ts
+++ b/backend/src/services/alert/alert-channel-crypto-fns.ts
@@ -1,3 +1,5 @@
+import { Knex } from "knex";
+
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { KmsDataKey } from "@app/services/kms/kms-types";
@@ -6,12 +8,14 @@ export type TAlertDecryptor = (data: { cipherTextBlob: Buffer }) => Buffer;
export const getAlertChannelCipher = (
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">,
- scope: { orgId: string; projectId?: string | null }
+ scope: { orgId: string; projectId?: string | null },
+ tx?: Knex
) =>
kmsService.createCipherPairWithDataKey(
scope.projectId
? { type: KmsDataKey.SecretManager, projectId: scope.projectId }
- : { type: KmsDataKey.Organization, orgId: scope.orgId }
+ : { type: KmsDataKey.Organization, orgId: scope.orgId },
+ tx
);
export const encryptChannelConfig = (config: unknown, encryptor: TAlertEncryptor): Buffer =>
diff --git a/backend/src/services/alert/alert-channel-service.test.ts b/backend/src/services/alert/alert-channel-service.test.ts
index e467f91e12..6631f66909 100644
--- a/backend/src/services/alert/alert-channel-service.test.ts
+++ b/backend/src/services/alert/alert-channel-service.test.ts
@@ -20,13 +20,14 @@ type TRow = {
enabled: boolean;
orgId: string;
projectId: string | null;
- createdByActorId: string;
+ createdByActorId: string | null;
createdByActorType: string;
createdAt: Date;
updatedAt: Date;
};
-const buildService = (opts?: { seed?: TRow[] }) => {
+const buildService = (opts?: { seed?: TRow[]; projectUserIds?: string[] }) => {
+ const scopeCheckTxs: unknown[] = [];
const store = new Map<string, TRow>();
(opts?.seed ?? []).forEach((r) => store.set(r.id, r));
const recipients = new Map<string, Array<{ channelId: string; principalType: string; principalId: string }>>();
@@ -75,19 +76,24 @@ const buildService = (opts?: { seed?: TRow[] }) => {
projectDAL: {
findEffectiveProjectSubjectsMembership: async ({
userIds,
- groupIds
+ groupIds,
+ tx: scopeTx
}: {
userIds: string[];
groupIds: string[];
- }) => ({
- effectiveUserIds: userIds,
- effectiveGroupIds: groupIds
- })
+ tx?: unknown;
+ }) => {
+ scopeCheckTxs.push(scopeTx);
+ return {
+ effectiveUserIds: opts?.projectUserIds ? userIds.filter((id) => opts.projectUserIds!.includes(id)) : userIds,
+ effectiveGroupIds: groupIds
+ };
+ }
},
groupDAL: { find: async (filter: { $in?: { id?: string[] } }) => (filter.$in?.id ?? []).map((id) => ({ id })) }
} as unknown as TAlertChannelServiceFactoryDep);
- return { service, store, recipients };
+ return { service, store, recipients, scopeCheckTxs };
};
const seedRow = (
@@ -262,4 +268,115 @@ describe("alert channel service", () => {
service.updateChannelInTx({ channelId: "ch-1", config: { webhookUrl: "" } }, channel as never, cipher, tx)
).rejects.toThrow(/Invalid slack channel config/);
});
+
+ test("accepts all project members on a channel in the same project", async () => {
+ const { service, recipients } = buildService();
+ const channel = await service.createChannelInTx(
+ {
+ name: "Email",
+ channelType: AlertChannelType.EMAIL,
+ config: {},
+ recipients: [{ principalType: AlertPrincipalType.PROJECT_MEMBERS, principalId: "proj-1" }],
+ orgId: "org-1",
+ projectId: "proj-1",
+ ...CREATOR
+ },
+ encryptor as never,
+ tx
+ );
+ expect(recipients.get(channel.id)).toEqual([
+ { channelId: channel.id, principalType: "project-members", principalId: "proj-1" }
+ ]);
+ });
+
+ test("rejects all project members on an org-scoped channel", async () => {
+ const { service } = buildService();
+ await expect(
+ service.createChannelInTx(
+ {
+ name: "Email",
+ channelType: AlertChannelType.EMAIL,
+ config: {},
+ recipients: [{ principalType: AlertPrincipalType.PROJECT_MEMBERS, principalId: "proj-1" }],
+ orgId: "org-1",
+ ...CREATOR
+ },
+ encryptor as never,
+ tx
+ )
+ ).rejects.toThrow("All project members can only be notified by a project alert");
+ });
+
+ test("rejects all project members that names another project", async () => {
+ const { service } = buildService();
+ await expect(
+ service.createChannelInTx(
+ {
+ name: "Email",
+ channelType: AlertChannelType.EMAIL,
+ config: {},
+ recipients: [{ principalType: AlertPrincipalType.PROJECT_MEMBERS, principalId: "other-project" }],
+ orgId: "org-1",
+ projectId: "proj-1",
+ ...CREATOR
+ },
+ encryptor as never,
+ tx
+ )
+ ).rejects.toThrow("All project members must refer to the alert's own project");
+ });
+
+ test("checks recipient scope inside the caller's transaction", async () => {
+ const { service, scopeCheckTxs } = buildService();
+ await service.createChannelInTx(
+ {
+ name: "Email",
+ channelType: AlertChannelType.EMAIL,
+ config: {},
+ recipients: [{ principalType: AlertPrincipalType.USER, principalId: "user-1" }],
+ orgId: "org-1",
+ projectId: "proj-1",
+ ...CREATOR
+ },
+ encryptor as never,
+ tx
+ );
+ expect(scopeCheckTxs).toEqual([tx]);
+ });
+
+ test("accepts a platform creator with no actor id", async () => {
+ const { service, store } = buildService();
+ const channel = await service.createChannelInTx(
+ {
+ name: "Email",
+ channelType: AlertChannelType.EMAIL,
+ config: {},
+ recipients: [{ principalType: AlertPrincipalType.USER, principalId: "user-1" }],
+ orgId: "org-1",
+ createdByActorId: null,
+ createdByActorType: "platform"
+ },
+ encryptor as never,
+ tx
+ );
+ expect(store.get(channel.id)).toMatchObject({ createdByActorId: null, createdByActorType: "platform" });
+ });
+
+ test("filterRecipientsInScope drops users who left the project and keeps the rest", async () => {
+ const { service } = buildService({ projectUserIds: ["user-1"] });
+ const kept = await service.filterRecipientsInScope(
+ { orgId: "org-1", projectId: "proj-1" },
+ [
+ { principalType: AlertPrincipalType.USER, principalId: "user-1" },
+ { principalType: AlertPrincipalType.USER, principalId: "user-gone" },
+ { principalType: AlertPrincipalType.PROJECT_MEMBERS, principalId: "proj-1" },
+ { principalType: AlertPrincipalType.PROJECT_MEMBERS, principalId: "other-project" }
+ ],
+ tx
+ );
+ expect(kept).toEqual([
+ { principalType: "user", principalId: "user-1" },
+ { principalType: "project-members", principalId: "proj-1" }
+ ]);
+ });
});
diff --git a/backend/src/services/alert/alert-channel-service.ts b/backend/src/services/alert/alert-channel-service.ts
index bd77b6d0de..6bcd09657d 100644
--- a/backend/src/services/alert/alert-channel-service.ts
+++ b/backend/src/services/alert/alert-channel-service.ts
@@ -46,7 +46,7 @@ export type TCreateChannelInTxInput = {
recipients?: TChannelRecipientInput[];
orgId: string;
projectId?: string | null;
- createdByActorId: string;
+ createdByActorId: string | null;
createdByActorType: string;
};
@@ -68,24 +68,44 @@ export const alertChannelServiceFactory = ({
projectDAL,
groupDAL
}: TAlertChannelServiceFactoryDep) => {
+ const $recipientIdsByType = (recipients: TChannelRecipientInput[]) => ({
+ userIds: [
+ ...new Set(recipients.filter((r) => r.principalType === AlertPrincipalType.USER).map((r) => r.principalId))
+ ],
+ groupIds: [
+ ...new Set(recipients.filter((r) => r.principalType === AlertPrincipalType.GROUP).map((r) => r.principalId))
+ ]
+ });
+
+ const $assertProjectMembersRecipients = (
+ projectId: string | null | undefined,
+ recipients: TChannelRecipientInput[]
+ ) => {
+ const projectMembers = recipients.filter((r) => r.principalType === AlertPrincipalType.PROJECT_MEMBERS);
+ if (projectMembers.length === 0) return;
+ if (!projectId) {
+ throw new BadRequestError({ message: "All project members can only be notified by a project alert" });
+ }
+ if (projectMembers.some((r) => r.principalId !== projectId)) {
+ throw new BadRequestError({ message: "All project members must refer to the alert's own project" });
+ }
+ };
+
// Confirms every recipient principal (user/group) actually belongs to the channel's scope so an
// alert can't be made to notify a foreign principal.
const $validateRecipients = async (
orgId: string,
projectId: string | null | undefined,
- recipients: TChannelRecipientInput[]
+ recipients: TChannelRecipientInput[],
+ tx?: Knex
) => {
- const userIds = [
- ...new Set(recipients.filter((r) => r.principalType === AlertPrincipalType.USER).map((r) => r.principalId))
- ];
- const groupIds = [
- ...new Set(recipients.filter((r) => r.principalType === AlertPrincipalType.GROUP).map((r) => r.principalId))
- ];
+ $assertProjectMembersRecipients(projectId, recipients);
+ const { userIds, groupIds } = $recipientIdsByType(recipients);
if (userIds.length === 0 && groupIds.length === 0) return;
const inScope = await resolvePrincipalsInScope(
{ orgDAL, projectDAL, groupDAL },
- { orgId, projectId, userIds, groupIds }
+ { orgId, projectId, userIds, groupIds, tx }
);
const scopeLabel = projectId ? "project" : "organization";
@@ -139,7 +159,7 @@ export const alertChannelServiceFactory = ({
const recipients = input.recipients ?? [];
$assertRecipientRules(definition, input.channelType, recipients);
assertChannelConfigValid(definition, input.channelType, input.config);
- await $validateRecipients(input.orgId, input.projectId, recipients);
+ await $validateRecipients(input.orgId, input.projectId, recipients, tx);
const created = await alertChannelDAL.create(
{
@@ -188,7 +208,7 @@ export const alertChannelServiceFactory = ({
if (input.recipients !== undefined) {
$assertRecipientRules(definition, channel.channelType, input.recipients);
- await $validateRecipients(channel.orgId, channel.projectId, input.recipients);
+ await $validateRecipients(channel.orgId, channel.projectId, input.recipients, tx);
}
await alertChannelDAL.updateById(
@@ -216,6 +236,33 @@ export const alertChannelServiceFactory = ({
}
};
+ // For callers that carry recipient lists from outside the alert module (eg reminder recipients that
+ // were never pruned when someone left the project), where an out-of-scope id should be dropped
+ // rather than fail the whole write.
+ const filterRecipientsInScope = async (
+ scope: { orgId: string; projectId?: string | null },
+ recipients: TChannelRecipientInput[],
+ tx?: Knex
+ ): Promise<TChannelRecipientInput[]> => {
+ const { userIds, groupIds } = $recipientIdsByType(recipients);
+ const inScope =
+ userIds.length || groupIds.length
+ ? await resolvePrincipalsInScope(
+ { orgDAL, projectDAL, groupDAL },
+ { orgId: scope.orgId, projectId: scope.projectId, userIds, groupIds, tx }
+ )
+ : { userIds: new Set<string>(), groupIds: new Set<string>() };
+
+ return recipients.filter((r) => {
+ if (r.principalType === AlertPrincipalType.USER) return inScope.userIds.has(r.principalId);
+ if (r.principalType === AlertPrincipalType.GROUP) return inScope.groupIds.has(r.principalId);
+ if (r.principalType === AlertPrincipalType.PROJECT_MEMBERS) {
+ return Boolean(scope.projectId) && r.principalId === scope.projectId;
+ }
+ return false;
+ });
+ };
+
const deleteChannelInTx = async (channelId: string, tx: Knex): Promise<void> => {
await alertChannelDAL.deleteById(channelId, tx);
};
@@ -255,6 +302,7 @@ export const alertChannelServiceFactory = ({
createChannelInTx,
updateChannelInTx,
deleteChannelInTx,
- getDetailsForChannels
+ getDetailsForChannels,
+ filterRecipientsInScope
};
};
diff --git a/backend/src/services/alert/alert-principal-scope-fns.ts b/backend/src/services/alert/alert-principal-scope-fns.ts
index 23bec67036..5453c30523 100644
--- a/backend/src/services/alert/alert-principal-scope-fns.ts
+++ b/backend/src/services/alert/alert-principal-scope-fns.ts
@@ -1,3 +1,5 @@
+import { Knex } from "knex";
+
import { OrgMembershipStatus } from "@app/db/schemas";
import { TGroupDALFactory } from "@app/ee/services/group/group-dal";
import { TOrgDALFactory } from "@app/services/org/org-dal";
@@ -30,18 +32,21 @@ export type TInScopePrincipals = { userIds: Set<string>; groupIds: Set<string> }
*/
export const resolvePrincipalsInScope = async (
{ orgDAL, projectDAL, groupDAL }: TPrincipalScopeDALs,
- { orgId, projectId, userIds, groupIds }: TPrincipalScope & { userIds: string[]; groupIds: string[] }
+ { orgId, projectId, userIds, groupIds, tx }: TPrincipalScope & { userIds: string[]; groupIds: string[]; tx?: Knex }
): Promise<TInScopePrincipals> => {
if (userIds.length === 0 && groupIds.length === 0) return { userIds: new Set(), groupIds: new Set() };
const activeOrgUserIds = new Set<string>();
if (userIds.length) {
- const memberships = await orgDAL.findMembership({
- $in: { actorUserId: userIds },
- scopeOrgId: orgId,
- isActive: true,
- status: OrgMembershipStatus.Accepted
- });
+ const memberships = await orgDAL.findMembership(
+ {
+ $in: { actorUserId: userIds },
+ scopeOrgId: orgId,
+ isActive: true,
+ status: OrgMembershipStatus.Accepted
+ },
+ { tx }
+ );
memberships.forEach((membership) => {
if (membership.actorUserId) activeOrgUserIds.add(membership.actorUserId);
});
@@ -52,7 +57,8 @@ export const resolvePrincipalsInScope = async (
orgId,
projectId,
userIds: [...activeOrgUserIds],
- groupIds
+ groupIds,
+ tx
});
return { userIds: new Set(effectiveUserIds), groupIds: new Set(effectiveGroupIds) };
}
@@ -61,6 +67,6 @@ export const resolvePrincipalsInScope = async (
if (!groupDAL || groupIds.length === 0) return { userIds: inScopeUserIds, groupIds: new Set(groupIds) };
- const orgGroups = await groupDAL.find({ $in: { id: groupIds }, orgId });
+ const orgGroups = await groupDAL.find({ $in: { id: groupIds }, orgId }, { tx });
return { userIds: inScopeUserIds, groupIds: new Set(orgGroups.map((group) => group.id)) };
};
diff --git a/backend/src/services/alert/alert-recipient-resolver.test.ts b/backend/src/services/alert/alert-recipient-resolver.test.ts
index 643169a334..9343a40b91 100644
--- a/backend/src/services/alert/alert-recipient-resolver.test.ts
+++ b/backend/src/services/alert/alert-recipient-resolver.test.ts
@@ -13,6 +13,7 @@ const buildResolver = (opts: {
invitedUserIds?: string[]; // users invited to the org who never accepted
effectiveProjectUserIds?: string[]; // users currently effective in the project
effectiveProjectGroupIds?: string[]; // groups currently holding a project membership
+ projectMemberUserIds?: string[]; // users a project member listing returns
}) => {
const usersById = new Map(opts.users.map((u) => [u.id, u]));
return alertRecipientResolverFactory({
@@ -55,6 +56,9 @@ const buildResolver = (opts: {
effectiveUserIds: userIds.filter((id) => (opts.effectiveProjectUserIds ?? []).includes(id)),
effectiveGroupIds: groupIds.filter((id) => (opts.effectiveProjectGroupIds ?? []).includes(id))
})
+ } as never,
+ projectMembershipDAL: {
+ findAllProjectMembers: async () => (opts.projectMemberUserIds ?? []).map((id) => ({ user: { id } }))
} as never
});
};
@@ -227,3 +231,80 @@ describe("alert recipient resolver — send-time scope re-check", () => {
expect(emails).toEqual(["[email protected]"]);
});
});
+
+describe("alert recipient resolver — all project members", () => {
+ test("expands to the project's current members", async () => {
+ const resolver = buildResolver({
+ users: [user("u1"), user("u2")],
+ projectMemberUserIds: ["u1", "u2"],
+ effectiveProjectUserIds: ["u1", "u2"]
+ });
+
+ const result = await resolver.resolveMany(
+ new Map([["c1", [{ principalType: AlertPrincipalType.PROJECT_MEMBERS, principalId: "proj-1" }]]]),
+ { orgId: "org-1", projectId: "proj-1" }
+ );
+
+ expect(
+ result
+ .get("c1")
+ ?.map((r) => r.email)
+ .sort()
+ });
+
+ test("still drops members whose org membership was deactivated", async () => {
+ const resolver = buildResolver({
+ users: [user("u1"), user("u2")],
+ orgUserIds: ["u1"],
+ deactivatedUserIds: ["u2"],
+ projectMemberUserIds: ["u1", "u2"],
+ effectiveProjectUserIds: ["u1", "u2"]
+ });
+
+ const result = await resolver.resolveMany(
+ new Map([["c1", [{ principalType: AlertPrincipalType.PROJECT_MEMBERS, principalId: "proj-1" }]]]),
+ { orgId: "org-1", projectId: "proj-1" }
+ );
+
+ expect(result.get("c1")?.map((r) => r.email)).toEqual(["[email protected]"]);
+ });
+
+ test("ignores a project members recipient that names another project", async () => {
+ const resolver = buildResolver({
+ users: [user("u1")],
+ projectMemberUserIds: ["u1"],
+ effectiveProjectUserIds: ["u1"]
+ });
+
+ const result = await resolver.resolveMany(
+ new Map([["c1", [{ principalType: AlertPrincipalType.PROJECT_MEMBERS, principalId: "other-project" }]]]),
+ { orgId: "org-1", projectId: "proj-1" }
+ );
+
+ expect(result.get("c1")).toEqual([]);
+ });
+
+ test("emails a user once when listed directly and through project members", async () => {
+ const resolver = buildResolver({
+ users: [user("u1")],
+ projectMemberUserIds: ["u1"],
+ effectiveProjectUserIds: ["u1"]
+ });
+
+ const result = await resolver.resolveMany(
+ new Map([
+ [
+ "c1",
+ [
+ { principalType: AlertPrincipalType.USER, principalId: "u1" },
+ { principalType: AlertPrincipalType.PROJECT_MEMBERS, principalId: "proj-1" }
+ ]
+ ]
+ ]),
+ { orgId: "org-1", projectId: "proj-1" }
+ );
+
+ expect(result.get("c1")).toHaveLength(1);
+ });
+});
diff --git a/backend/src/services/alert/alert-recipient-resolver.ts b/backend/src/services/alert/alert-recipient-resolver.ts
index 89b0031dff..fd1d00911b 100644
--- a/backend/src/services/alert/alert-recipient-resolver.ts
+++ b/backend/src/services/alert/alert-recipient-resolver.ts
@@ -2,6 +2,7 @@ import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-grou
import { logger } from "@app/lib/logger";
import { TOrgDALFactory } from "@app/services/org/org-dal";
import { TProjectDALFactory } from "@app/services/project/project-dal";
+import { TProjectMembershipDALFactory } from "@app/services/project-membership/project-membership-dal";
import { TUserDALFactory } from "@app/services/user/user-dal";
import { TAlertRecipient } from "./alert-channel-types";
@@ -13,6 +14,7 @@ type TAlertRecipientResolverDep = {
userGroupMembershipDAL: Pick<TUserGroupMembershipDALFactory, "find">;
orgDAL: Pick<TOrgDALFactory, "findMembership">;
projectDAL: Pick<TProjectDALFactory, "findEffectiveProjectSubjectsMembership">;
+ projectMembershipDAL: Pick<TProjectMembershipDALFactory, "findAllProjectMembers">;
};
type TResolvableRecipient = { principalType: string; principalId: string };
@@ -25,7 +27,8 @@ export const alertRecipientResolverFactory = ({
userDAL,
userGroupMembershipDAL,
orgDAL,
- projectDAL
+ projectDAL,
+ projectMembershipDAL
}: TAlertRecipientResolverDep) => {
const resolveMany = async (
rowsByChannel: Map<string, TResolvableRecipient[]>,
@@ -51,6 +54,23 @@ export const alertRecipientResolverFactory = ({
});
}
+ const wantsProjectMembers =
+ Boolean(scope.projectId) &&
+ [...rowsByChannel.values()].some((rows) =>
+ rows.some(
+ (recipient) =>
+ recipient.principalType === AlertPrincipalType.PROJECT_MEMBERS && recipient.principalId === scope.projectId
+ )
+ );
+ const projectMemberIds: string[] = [];
+ if (wantsProjectMembers && scope.projectId) {
+ const members = await projectMembershipDAL.findAllProjectMembers(scope.projectId);
+ members.forEach((member) => {
+ projectMemberIds.push(member.user.id);
+ allUserIds.add(member.user.id);
+ });
+ }
+
const { userIds: inScopeUserIds, groupIds: inScopeGroupIds } = await resolvePrincipalsInScope(
{ orgDAL, projectDAL },
{ orgId: scope.orgId, projectId: scope.projectId, userIds: [...allUserIds], groupIds: [...allGroupIds] }
@@ -75,6 +95,11 @@ export const alertRecipientResolverFactory = ({
(groupMembers.get(recipient.principalId) ?? []).forEach((userId) => userIds.add(userId));
}
break;
+ case AlertPrincipalType.PROJECT_MEMBERS:
+ if (scope.projectId && recipient.principalId === scope.projectId) {
+ projectMemberIds.forEach((userId) => userIds.add(userId));
+ }
+ break;
default:
logger.warn(`Unknown alert recipient principal type '${recipient.principalType}'`);
}
diff --git a/backend/src/services/alert/alert-service-types.ts b/backend/src/services/alert/alert-service-types.ts
index 154288c471..12d1e81493 100644
--- a/backend/src/services/alert/alert-service-types.ts
+++ b/backend/src/services/alert/alert-service-types.ts
@@ -24,6 +24,18 @@ export type TUpdateAlertDTO = TGenericPermission & {
channels?: TAlertChannelInput[];
};
+// For domain services that own their resource's authorization (eg reminders) and for background
+// work with no actor. They skip the provider's permission check, so callers must check first.
+export type TAlertCreator = { actorType: string; actorId: string | null };
+
+export type TCreateAlertInternalDTO = Omit<TCreateAlertDTO, keyof TGenericPermission | "projectId"> & {
+ orgId: string;
+ projectId: string | null;
+ createdBy: TAlertCreator;
+};
+
+export type TUpdateAlertInternalDTO = Omit<TUpdateAlertDTO, keyof TGenericPermission>;
+
export type TGetAlertDTO = TGenericPermission & { alertId: string };
export type TDeleteAlertDTO = TGenericPermission & { alertId: string };
diff --git a/backend/src/services/alert/alert-service.test.ts b/backend/src/services/alert/alert-service.test.ts
index e73d72a16c..7d01baaf0b 100644
--- a/backend/src/services/alert/alert-service.test.ts
+++ b/backend/src/services/alert/alert-service.test.ts
@@ -1,5 +1,8 @@
import { z } from "zod";
+import { DatabaseErrorCode } from "@app/lib/error-codes";
+import { DatabaseError } from "@app/lib/errors";
+
import { TAlertChannelInput } from "./alert-channel-service-types";
import { AlertChannelType, TAlertPayload } from "./alert-channel-types";
import { alertProviderRegistryFactory } from "./alert-provider-registry";
@@ -24,6 +27,7 @@ const buildService = (opts?: {
assertPermission?: (input: TAlertPermissionInput) => Promise<void>;
resourceScopeThrows?: boolean;
duplicateExists?: boolean;
+ createError?: Error;
// Runs right after a find() has taken its snapshot, to stand in for a concurrent transaction
// committing between two statements of ours.
afterFindAlerts?: (alerts: Map<string, Record<string, unknown>>) => void;
@@ -63,8 +67,16 @@ const buildService = (opts?: {
const channels = new Map<string, TChannelRow>(); // channelId -> row
const memberships = new Map<string, string[]>(); // alertId -> channelIds
const findFilters: Array<Record<string, unknown>> = [];
+ const createTxs: unknown[] = [];
+ let transactionsOpened = 0;
let channelSeq = 0;
+ const matches = (row: Record<string, unknown>, filter: Record<string, unknown>) => {
+ const { $in: inFilter, ...equality } = filter as { $in?: Record<string, unknown[]> };
+ const inMatch = Object.entries(inFilter ?? {}).every(([key, values]) => values.includes(row[key]));
+ return inMatch && Object.entries(equality).every(([key, value]) => value === undefined || row[key] === value);
+ };
+
const detach = (channelId: string) => {
memberships.forEach((ids, alertId) =>
memberships.set(
@@ -76,8 +88,13 @@ const buildService = (opts?: {
const service = alertServiceFactory({
alertDAL: {
- transaction: async (cb: (tx: unknown) => unknown) => cb({}),
- create: async (data: Record<string, unknown>) => {
+ transaction: async (cb: (tx: unknown) => unknown) => {
+ transactionsOpened += 1;
+ return cb({});
+ },
+ create: async (data: Record<string, unknown>, tx?: unknown) => {
+ createTxs.push(tx);
+ if (opts?.createError) throw opts.createError;
const row = {
id: "alert-1",
...data,
@@ -105,18 +122,17 @@ const buildService = (opts?: {
deleteById: async (id: string) => alerts.delete(id),
find: async (filter: Record<string, unknown>) => {
findFilters.push(filter);
- const rows = [...alerts.values()].filter((row) =>
- Object.entries(filter).every(([key, value]) => value === undefined || row[key] === value)
- );
+ const rows = [...alerts.values()].filter((row) => matches(row, filter));
opts?.afterFindAlerts?.(alerts);
return rows;
},
- delete: async (filter: Record<string, unknown> & { $in?: { id?: string[] } }) => {
- const { $in: inFilter, ...equality } = filter;
- const removed = [...alerts.values()].filter((row) => {
- if (inFilter?.id && !inFilter.id.includes(row.id as string)) return false;
- return Object.entries(equality).every(([key, value]) => value === undefined || row[key] === value);
- });
+ update: async (filter: Record<string, unknown>, data: Record<string, unknown>) => {
+ const updated = [...alerts.values()].filter((row) => matches(row, filter));
+ updated.forEach((row) => alerts.set(row.id as string, { ...row, ...data }));
+ return updated;
+ },
+ delete: async (filter: Record<string, unknown>) => {
+ const removed = [...alerts.values()].filter((row) => matches(row, filter));
removed.forEach((row) => alerts.delete(row.id as string));
return removed;
}
@@ -210,7 +226,16 @@ const buildService = (opts?: {
alertProviderRegistry: registry
} as unknown as TAlertServiceFactoryDep);
- return { service, permissionCalls, alerts, memberships, channels, findFilters };
+ return {
+ service,
+ permissionCalls,
+ alerts,
+ memberships,
+ channels,
+ findFilters,
+ createTxs,
+ transactionsOpened: () => transactionsOpened
+ };
};
const actor = {
@@ -663,3 +688,111 @@ describe("alert service", () => {
expect([...alerts.keys()]).toEqual(["other-resource", "other-type"]);
});
});
+
+describe("alert service internal entry points", () => {
+ const internalCreate = {
+ name: "Reminder for DB_PASSWORD",
+ resourceType: RESOURCE_TYPE,
+ resourceId: "resource-1",
+ eventType: "test.resource.opened",
+ condition: null,
+ orgId: "org-1",
+ projectId: "proj-1",
+ channels: [emailChannel],
+ createdBy: { actorType: "platform", actorId: null }
+ };
+
+ test("createAlertInternal skips the provider permission check and records the given creator", async () => {
+ const { service, permissionCalls, alerts } = buildService();
+ const alert = await service.createAlertInternal(internalCreate);
+
+ expect(permissionCalls).toHaveLength(0);
+ expect(alerts.get(alert.id)).toMatchObject({ createdByActorType: "platform", createdByActorId: null });
+ expect(alert.channels).toHaveLength(1);
+ });
+
+ test("createAlertInternal still validates the condition", async () => {
+ const { service } = buildService();
+ await expect(
+ service.createAlertInternal({
+ ...internalCreate,
+ eventType: "test.resource.expiration",
+ condition: { wrong: true }
+ })
+ ).rejects.toThrow("Invalid alert condition");
+ });
+
+ test("createAlertInternal writes inside the caller's transaction when given one", async () => {
+ const { service, createTxs, transactionsOpened } = buildService();
+ const callerTx = { caller: true } as never;
+ await service.createAlertInternal(internalCreate, callerTx);
+
+ expect(createTxs).toEqual([callerTx]);
+ expect(transactionsOpened()).toBe(0);
+ });
+
+ test("updateAlertInternal skips the provider permission check", async () => {
+ const { service, permissionCalls } = buildService();
+ const created = await service.createAlertInternal(internalCreate);
+ const updated = await service.updateAlertInternal({ alertId: created.id, enabled: false });
+
+ expect(permissionCalls).toHaveLength(0);
+ expect(updated.enabled).toBe(false);
+ });
+
+ test("findAlertsForResources returns each resource's alert with its channels", async () => {
+ const { service } = buildService();
+ await service.createAlertInternal(internalCreate);
+
+ const found = await service.findAlertsForResources({
+ resourceType: RESOURCE_TYPE,
+ resourceIds: ["resource-1", "resource-2"]
+ });
+
+ expect(found.map((a) => a.resourceId)).toEqual(["resource-1"]);
+ expect(found[0].channels).toHaveLength(1);
+ });
+
+ test("findAlertsForResources with no ids reads nothing", async () => {
+ const { service, findFilters } = buildService();
+ expect(await service.findAlertsForResources({ resourceType: RESOURCE_TYPE, resourceIds: [] })).toEqual([]);
+ expect(findFilters).toHaveLength(0);
+ });
+
+ test("deleteAlertsForDeletedResources reaps every listed resource and its channels", async () => {
+ const { service, alerts, channels } = buildService();
+ await service.createAlertInternal(internalCreate);
+ alerts.set("alert-2", { id: "alert-2", orgId: "org-1", resourceType: RESOURCE_TYPE, resourceId: "resource-2" });
+ alerts.set("alert-3", { id: "alert-3", orgId: "org-1", resourceType: RESOURCE_TYPE, resourceId: "resource-3" });
+
+ const deleted = await service.deleteAlertsForDeletedResources({
+ resourceType: RESOURCE_TYPE,
+ resourceIds: ["resource-1", "resource-2"]
+ });
+
+ expect(deleted).toBe(2);
+ expect([...alerts.keys()]).toEqual(["alert-3"]);
+ expect(channels.size).toBe(0);
+ });
+
+ test("a concurrent duplicate create surfaces as a readable error, not a 500", async () => {
+ const { service } = buildService({
+ createError: new DatabaseError({ error: { code: DatabaseErrorCode.UniqueViolation }, name: "Create" })
+ });
+ await expect(service.createAlertInternal(internalCreate)).rejects.toThrow(
+ "An alert for this resource and event already exists"
+ );
+ });
+
+ test("repointAlertsForResource moves a resource's alerts to its new id", async () => {
+ const { service, alerts } = buildService();
+ const created = await service.createAlertInternal(internalCreate);
+
+ await service.repointAlertsForResource(
+ { resourceType: RESOURCE_TYPE, fromResourceId: "resource-1", toResourceId: "resource-9" },
+ {} as never
+ );
+
+ expect(alerts.get(created.id)).toMatchObject({ resourceId: "resource-9" });
+ });
+});
diff --git a/backend/src/services/alert/alert-service.ts b/backend/src/services/alert/alert-service.ts
index 4a3225935f..982b1d7e5d 100644
--- a/backend/src/services/alert/alert-service.ts
+++ b/backend/src/services/alert/alert-service.ts
@@ -2,7 +2,8 @@ import { Knex } from "knex";
import { z } from "zod";
import { TAlertChannels, TAlerts } from "@app/db/schemas";
-import { BadRequestError, NotFoundError } from "@app/lib/errors";
+import { DatabaseErrorCode } from "@app/lib/error-codes";
+import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";
import { TGenericPermission } from "@app/lib/types";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
@@ -10,16 +11,18 @@ import { getAlertChannelCipher } from "./alert-channel-crypto-fns";
import { TAlertChannelDALFactory } from "./alert-channel-dal";
import { TAlertChannelMembershipDALFactory } from "./alert-channel-membership-dal";
import { TAlertChannelServiceFactory } from "./alert-channel-service";
-import { TAlertChannelEmbedded, TAlertChannelInput } from "./alert-channel-service-types";
+import { TAlertChannelEmbedded, TAlertChannelInput, TChannelRecipientInput } from "./alert-channel-service-types";
import { TAlertDALFactory } from "./alert-dal";
import { TAlertProviderRegistry } from "./alert-provider-registry";
import {
TAlertResponse,
TCreateAlertDTO,
+ TCreateAlertInternalDTO,
TDeleteAlertDTO,
TGetAlertDTO,
TListAlertsDTO,
- TUpdateAlertDTO
+ TUpdateAlertDTO,
+ TUpdateAlertInternalDTO
} from "./alert-service-types";
import { AlertPermissionAction, IResourceAlertProvider, TAlertEventDefinition, toAlertActor } from "./alert-types";
@@ -29,7 +32,11 @@ export type TAlertServiceFactoryDep = {
alertChannelMembershipDAL: Pick<TAlertChannelMembershipDALFactory, "insertMany">;
alertChannelService: Pick<
TAlertChannelServiceFactory,
- "createChannelInTx" | "updateChannelInTx" | "deleteChannelInTx" | "getDetailsForChannels"
+ | "createChannelInTx"
+ | "updateChannelInTx"
+ | "deleteChannelInTx"
+ | "getDetailsForChannels"
+ | "filterRecipientsInScope"
>;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
alertProviderRegistry: TAlertProviderRegistry;
@@ -103,6 +110,68 @@ export const alertServiceFactory = ({
updatedAt: alert.updatedAt
});
+ const $createAlertRows = async (
+ input: TCreateAlertInternalDTO,
+ event: TAlertEventDefinition,
+ cipher: Awaited<ReturnType<typeof getAlertChannelCipher>>,
+ tx: Knex
+ ): Promise<TAlertResponse> => {
+ let createdAlert: TAlerts;
+ try {
+ createdAlert = await alertDAL.create(
+ {
+ name: input.name,
+ description: input.description,
+ resourceType: input.resourceType,
+ resourceId: input.resourceId,
+ eventType: input.eventType,
+ triggerType: event.triggerType,
+ condition: input.condition != null ? JSON.stringify(input.condition) : null,
+ enabled: input.enabled ?? true,
+ orgId: input.orgId,
+ projectId: input.projectId,
+ createdByActorId: input.createdBy.actorId,
+ createdByActorType: input.createdBy.actorType
+ },
+ tx
+ );
+ } catch (err) {
+ // findScopedDuplicate reads the replica, so two concurrent creates can both pass it.
+ if (
+ err instanceof DatabaseError &&
+ (err.error as { code?: string })?.code === DatabaseErrorCode.UniqueViolation
+ ) {
+ throw new BadRequestError({ message: "An alert for this resource and event already exists" });
+ }
+ throw err;
+ }
+
+ for (const channelInput of input.channels) {
+ // eslint-disable-next-line no-await-in-loop -- one shared tx connection; writes must be serial
+ const channel = await alertChannelService.createChannelInTx(
+ {
+ name: channelInput.name,
+ channelType: channelInput.channelType,
+ config: channelInput.config ?? {},
+ enabled: channelInput.enabled,
+ recipients: channelInput.recipients,
+ orgId: input.orgId,
+ projectId: input.projectId,
+ createdByActorId: input.createdBy.actorId,
+ createdByActorType: input.createdBy.actorType
+ },
+ cipher.encryptor,
+ tx
+ );
+ // eslint-disable-next-line no-await-in-loop -- one shared tx connection; writes must be serial
+ await alertChannelMembershipDAL.insertMany([{ alertId: createdAlert.id, channelId: channel.id }], tx);
+ }
+
+ const attachedChannels = await alertChannelDAL.findByAlertId(createdAlert.id, {}, tx);
+ const details = await alertChannelService.getDetailsForChannels(attachedChannels, cipher, tx);
+ return $assembleResponse(createdAlert, details);
+ };
+
const createAlert = async (dto: TCreateAlertDTO): Promise<TAlertResponse> => {
if (!dto.resourceId) {
throw new BadRequestError({
@@ -147,55 +216,21 @@ export const alertServiceFactory = ({
throw new BadRequestError({ message: "At least one channel is required" });
}
- const scope = { orgId: dto.actorOrgId, projectId: dto.projectId ?? null };
- const cipher = await getAlertChannelCipher(kmsService, scope);
-
- const { created, channels } = await alertDAL.transaction(async (tx) => {
- const createdAlert = await alertDAL.create(
- {
- name: dto.name,
- description: dto.description,
- resourceType: dto.resourceType,
- resourceId: dto.resourceId,
- eventType: dto.eventType,
- triggerType: event.triggerType,
- condition: dto.condition != null ? JSON.stringify(dto.condition) : null,
- enabled: dto.enabled ?? true,
- orgId: dto.actorOrgId,
- projectId: dto.projectId,
- createdByActorId: dto.actorId,
- createdByActorType: dto.actor
- },
- tx
- );
-
- for (const channelInput of dto.channels) {
- // eslint-disable-next-line no-await-in-loop -- one shared tx connection; writes must be serial
- const channel = await alertChannelService.createChannelInTx(
- {
- name: channelInput.name,
- channelType: channelInput.channelType,
- config: channelInput.config ?? {},
- enabled: channelInput.enabled,
- recipients: channelInput.recipients,
- orgId: dto.actorOrgId,
- projectId: dto.projectId ?? null,
- createdByActorId: dto.actorId,
- createdByActorType: dto.actor
- },
- cipher.encryptor,
- tx
- );
- // eslint-disable-next-line no-await-in-loop -- one shared tx connection; writes must be serial
- await alertChannelMembershipDAL.insertMany([{ alertId: createdAlert.id, channelId: channel.id }], tx);
- }
-
- const attachedChannels = await alertChannelDAL.findByAlertId(createdAlert.id, {}, tx);
- const details = await alertChannelService.getDetailsForChannels(attachedChannels, cipher, tx);
- return { created: createdAlert, channels: details };
- });
-
- return $assembleResponse(created, channels);
+ const input: TCreateAlertInternalDTO = {
+ name: dto.name,
+ description: dto.description,
+ resourceType: dto.resourceType,
+ resourceId: dto.resourceId,
+ eventType: dto.eventType,
+ condition: dto.condition,
+ enabled: dto.enabled,
+ orgId: dto.actorOrgId,
+ projectId: dto.projectId ?? null,
+ channels: dto.channels,
+ createdBy: { actorType: dto.actor, actorId: dto.actorId }
+ };
+ const cipher = await getAlertChannelCipher(kmsService, input);
+ return alertDAL.transaction((tx) => $createAlertRows(input, event, cipher, tx));
};
const getAlertById = async (dto: TGetAlertDTO): Promise<TAlertResponse> => {
@@ -306,7 +341,7 @@ export const alertServiceFactory = ({
recipients: channelInput.recipients,
orgId: alert.orgId,
projectId: alert.projectId,
- createdByActorId: alert.createdByActorId,
+ createdByActorId: alert.createdByActorId ?? null,
createdByActorType: alert.createdByActorType
},
cipher.encryptor,
@@ -318,6 +353,32 @@ export const alertServiceFactory = ({
}
};
+ const $updateAlertRows = async (
+ alert: TAlerts,
+ input: TUpdateAlertInternalDTO,
+ cipher: Awaited<ReturnType<typeof getAlertChannelCipher>>,
+ tx: Knex
+ ): Promise<TAlertResponse> => {
+ const patch = {
+ ...(input.name !== undefined ? { name: input.name } : {}),
+ ...(input.description !== undefined ? { description: input.description } : {}),
+ ...(input.condition !== undefined
+ ? { condition: input.condition != null ? JSON.stringify(input.condition) : null }
+ : {}),
+ ...(input.enabled !== undefined ? { enabled: input.enabled } : {})
+ };
+
+ const updatedAlert = Object.keys(patch).length > 0 ? await alertDAL.updateById(alert.id, patch, tx) : alert;
+
+ if (input.channels !== undefined) {
+ await $reconcileChannels(alert, input.channels, cipher, tx);
+ }
+
+ const attachedChannels = await alertChannelDAL.findByAlertId(alert.id, {}, tx);
+ const details = await alertChannelService.getDetailsForChannels(attachedChannels, cipher, tx);
+ return $assembleResponse(updatedAlert, details);
+ };
+
const updateAlert = async (dto: TUpdateAlertDTO): Promise<TAlertResponse> => {
const alert = await alertDAL.findActiveById(dto.alertId);
if (!alert) throw new NotFoundError({ message: `Alert with ID '${dto.alertId}' not found` });
@@ -335,31 +396,8 @@ export const alertServiceFactory = ({
throw new BadRequestError({ message: "At least one channel is required" });
}
- const scope = { orgId: alert.orgId, projectId: alert.projectId };
- const cipher = await getAlertChannelCipher(kmsService, scope);
-
- const { updated, channels } = await alertDAL.transaction(async (tx) => {
- const patch = {
- ...(dto.name !== undefined ? { name: dto.name } : {}),
- ...(dto.description !== undefined ? { description: dto.description } : {}),
- ...(dto.condition !== undefined
- ? { condition: dto.condition != null ? JSON.stringify(dto.condition) : null }
- : {}),
- ...(dto.enabled !== undefined ? { enabled: dto.enabled } : {})
- };
-
- const updatedAlert = Object.keys(patch).length > 0 ? await alertDAL.updateById(alert.id, patch, tx) : alert;
-
- if (dto.channels !== undefined) {
- await $reconcileChannels(alert, dto.channels, cipher, tx);
- }
-
- const attachedChannels = await alertChannelDAL.findByAlertId(alert.id, {}, tx);
- const details = await alertChannelService.getDetailsForChannels(attachedChannels, cipher, tx);
- return { updated: updatedAlert, channels: details };
- });
-
- return $assembleResponse(updated, channels);
+ const cipher = await getAlertChannelCipher(kmsService, { orgId: alert.orgId, projectId: alert.projectId });
+ return alertDAL.transaction((tx) => $updateAlertRows(alert, dto, cipher, tx));
};
const $deleteAlertsByFilter = async (filter: Parameters<typeof alertDAL.delete>[0], tx: Knex): Promise<number> => {
@@ -433,6 +471,99 @@ export const alertServiceFactory = ({
tx?: Knex
): Promise<number> => $reapAlerts({ resourceType, resourceId }, tx);
+ const createAlertInternal = async (input: TCreateAlertInternalDTO, tx?: Knex): Promise<TAlertResponse> => {
+ const provider = $getProvider(input.resourceType);
+ const event = $getEvent(provider, input.eventType);
+ $validateCondition(event, input.condition);
+ if (input.channels.length === 0) {
+ throw new BadRequestError({ message: "At least one channel is required" });
+ }
+
+ const cipher = await getAlertChannelCipher(kmsService, input, tx);
+ return tx
+ ? $createAlertRows(input, event, cipher, tx)
+ : alertDAL.transaction((trx) => $createAlertRows(input, event, cipher, trx));
+ };
+
+ const updateAlertInternal = async (input: TUpdateAlertInternalDTO, tx?: Knex): Promise<TAlertResponse> => {
+ const alert = await alertDAL.findActiveById(input.alertId, tx);
+ if (!alert) throw new NotFoundError({ message: `Alert with ID '${input.alertId}' not found` });
+
+ const provider = $getProvider(alert.resourceType);
+ if (input.condition !== undefined) $validateCondition($getEvent(provider, alert.eventType), input.condition);
+ if (input.channels !== undefined && input.channels.length === 0) {
+ throw new BadRequestError({ message: "At least one channel is required" });
+ }
+
+ const cipher = await getAlertChannelCipher(kmsService, { orgId: alert.orgId, projectId: alert.projectId }, tx);
+ return tx
+ ? $updateAlertRows(alert, input, cipher, tx)
+ : alertDAL.transaction((trx) => $updateAlertRows(alert, input, cipher, trx));
+ };
+
+ const findAlertsForResources = async (
+ { resourceType, resourceIds }: { resourceType: string; resourceIds: string[] },
+ tx?: Knex
+ ): Promise<TAlertResponse[]> => {
+ if (resourceIds.length === 0) return [];
+
+ const alerts = await alertDAL.find({ resourceType, $in: { resourceId: resourceIds } }, { tx });
+ if (alerts.length === 0) return [];
+
+ const channels = await alertChannelDAL.findByAlertIds(
+ alerts.map((alert) => alert.id),
+ tx
+ );
+ const channelsByAlert = new Map<string, TAlertChannels[]>();
+ channels.forEach((channel) => {
+ channelsByAlert.set(channel.alertId, [...(channelsByAlert.get(channel.alertId) ?? []), channel]);
+ });
+
+ const cipherByScope = new Map<string, Awaited<ReturnType<typeof getAlertChannelCipher>>>();
+ const responses: TAlertResponse[] = [];
+ for (const alert of alerts) {
+ const scopeKey = `${alert.orgId}:${alert.projectId ?? ""}`;
+ let cipher = cipherByScope.get(scopeKey);
+ if (!cipher) {
+ // eslint-disable-next-line no-await-in-loop -- one cipher per scope, and resource ids usually share one
+ cipher = await getAlertChannelCipher(kmsService, { orgId: alert.orgId, projectId: alert.projectId }, tx);
+ cipherByScope.set(scopeKey, cipher);
+ }
+ // eslint-disable-next-line no-await-in-loop -- reuses tx when given, so reads must be serial
+ const details = await alertChannelService.getDetailsForChannels(channelsByAlert.get(alert.id) ?? [], cipher, tx);
+ responses.push($assembleResponse(alert, details));
+ }
+ return responses;
+ };
+
+ const deleteAlertsForDeletedResources = async (
+ { resourceType, resourceIds }: { resourceType: string; resourceIds: string[] },
+ tx?: Knex
+ ): Promise<number> => {
+ if (resourceIds.length === 0) return 0;
+ const run = (trx: Knex) => $deleteAlertsByFilter({ resourceType, $in: { resourceId: resourceIds } }, trx);
+ return tx ? run(tx) : alertDAL.transaction(run);
+ };
+
+ // For a resource that is recreated under a new id (eg a secret moved between folders), so its alerts
+ // and their history follow it instead of being rebuilt.
+ const repointAlertsForResource = async (
+ {
+ resourceType,
+ fromResourceId,
+ toResourceId
+ }: { resourceType: string; fromResourceId: string; toResourceId: string },
+ tx: Knex
+ ): Promise<void> => {
+ await alertDAL.update({ resourceType, resourceId: fromResourceId }, { resourceId: toResourceId }, tx);
+ };
+
+ const filterRecipientsInScope = (
+ scope: { orgId: string; projectId?: string | null },
+ recipients: TChannelRecipientInput[],
+ tx?: Knex
+ ) => alertChannelService.filterRecipientsInScope(scope, recipients, tx);
+
return {
createAlert,
getAlertById,
@@ -440,6 +571,12 @@ export const alertServiceFactory = ({
updateAlert,
deleteAlert,
deleteAlertsForResource,
- deleteAlertsForDeletedResource
+ deleteAlertsForDeletedResource,
+ createAlertInternal,
+ updateAlertInternal,
+ findAlertsForResources,
+ deleteAlertsForDeletedResources,
+ repointAlertsForResource,
+ filterRecipientsInScope
};
};
diff --git a/backend/src/services/alert/alert-types.ts b/backend/src/services/alert/alert-types.ts
index 3f66d795b1..4d49ee26e1 100644
--- a/backend/src/services/alert/alert-types.ts
+++ b/backend/src/services/alert/alert-types.ts
@@ -6,7 +6,9 @@ import { TAlertPayload } from "./alert-channel-types";
export enum AlertPrincipalType {
USER = "user",
- GROUP = "group"
+ GROUP = "group",
+ // Everyone in the channel's project at send time. principalId is the project id.
+ PROJECT_MEMBERS = "project-members"
}
export enum AlertTriggerType {