Skip to content

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

remove recipient on scope removal

Thiago Araujo da Silva7fdbfedd47aa
diff --git a/backend/src/db/migrations/20260714120000_add-alerts.ts b/backend/src/db/migrations/20260714120000_add-alerts.ts
index c091ea7d0a..a9794e050a 100644
--- a/backend/src/db/migrations/20260714120000_add-alerts.ts
+++ b/backend/src/db/migrations/20260714120000_add-alerts.ts
@@ -12,6 +12,7 @@ export async function up(knex: Knex): Promise<void> {
t.string("resourceType").notNullable();
t.string("resourceId").nullable();
t.string("eventType").notNullable();
+ t.string("triggerType").notNullable();
t.jsonb("condition").nullable();
t.jsonb("filters").nullable();
t.boolean("enabled").notNullable().defaultTo(true);
@@ -26,7 +27,7 @@ export async function up(knex: Knex): Promise<void> {
t.index("orgId");
t.index("projectId");
t.index("createdByUserId");
- t.index(["resourceType", "enabled"]);
+ t.index(["resourceType", "triggerType", "enabled"]);
});
await createOnUpdateTrigger(knex, TableName.Alert);
diff --git a/backend/src/db/schemas/alerts.ts b/backend/src/db/schemas/alerts.ts
index d4c17f761a..52da1fb081 100644
--- a/backend/src/db/schemas/alerts.ts
+++ b/backend/src/db/schemas/alerts.ts
@@ -14,6 +14,7 @@ export const AlertsSchema = z.object({
resourceType: z.string(),
resourceId: z.string().nullable().optional(),
eventType: z.string(),
+ triggerType: z.string(),
condition: z.unknown().nullable().optional(),
filters: z.unknown().nullable().optional(),
enabled: z.boolean().default(true),
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 3553f00094..dd35b66b29 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -898,9 +898,12 @@ export const registerRoutes = async (
userDAL
});
+ const alertChannelRecipientDAL = alertChannelRecipientDALFactory(db);
+
const membershipUserService = membershipUserServiceFactory({
licenseService,
membershipRoleDAL,
+ alertChannelRecipientDAL,
membershipUserDAL,
orgDAL,
permissionService,
@@ -1014,7 +1017,6 @@ export const registerRoutes = async (
const alertDAL = alertDALFactory(db);
const alertChannelDAL = alertChannelDALFactory(db);
- const alertChannelRecipientDAL = alertChannelRecipientDALFactory(db);
const alertChannelMembershipDAL = alertChannelMembershipDALFactory(db);
const alertHistoryDAL = alertHistoryDALFactory(db);
const alertProviderRegistry = alertProviderRegistryFactory();
@@ -1024,7 +1026,12 @@ export const registerRoutes = async (
permissionService
})
);
- const alertRecipientResolver = alertRecipientResolverFactory({ userDAL, userGroupMembershipDAL });
+ const alertRecipientResolver = alertRecipientResolverFactory({
+ userDAL,
+ userGroupMembershipDAL,
+ orgDAL,
+ projectDAL
+ });
const alertEngine = alertEngineFactory({
alertChannelDAL,
alertChannelRecipientDAL,
diff --git a/backend/src/services/alert/alert-channel-recipient-dal.test.ts b/backend/src/services/alert/alert-channel-recipient-dal.test.ts
new file mode 100644
index 0000000000..370d466535
--- /dev/null
+++ b/backend/src/services/alert/alert-channel-recipient-dal.test.ts
@@ -0,0 +1,62 @@
+import { TableName } from "@app/db/schemas";
+
+import { alertChannelRecipientDALFactory } from "./alert-channel-recipient-dal";
+
+// Records query-builder calls so we can assert the scope cleanup filters correctly without a DB.
+const buildDAL = () => {
+ const calls = {
+ channelWhere: [] as unknown[][],
+ recipientWhere: [] as unknown[][],
+ recipientWhereIn: [] as unknown[][]
+ };
+ const channelChain = {
+ select: () => channelChain,
+ where: (...args: unknown[]) => {
+ calls.channelWhere.push(args);
+ return channelChain;
+ }
+ };
+ const recipientChain = {
+ where: (...args: unknown[]) => {
+ calls.recipientWhere.push(args);
+ return recipientChain;
+ },
+ whereIn: (...args: unknown[]) => {
+ calls.recipientWhereIn.push(args);
+ return recipientChain;
+ },
+ del: async () => 2
+ };
+ const db = ((table: string) => (table === TableName.AlertChannel ? channelChain : recipientChain)) as never;
+
+ return { dal: alertChannelRecipientDALFactory(db), calls };
+};
+
+describe("alert channel recipient dal — scope cleanup", () => {
+ test("project removal scopes channels by projectId and prunes only USER principals", async () => {
+ const { dal, calls } = buildDAL();
+
+ const deleted = await dal.deleteUsersRecipientsByScope({ userIds: ["u1", "u2"], projectId: "proj-1" });
+
+ expect(deleted).toBe(2);
+ expect(calls.channelWhere).toContainEqual([`${TableName.AlertChannel}.projectId`, "proj-1"]);
+ expect(calls.recipientWhere).toContainEqual([`${TableName.AlertChannelRecipient}.principalType`, "user"]);
+ expect(calls.recipientWhereIn).toContainEqual([`${TableName.AlertChannelRecipient}.principalId`, ["u1", "u2"]]);
+ });
+
+ test("org removal scopes channels by orgId (covers org- and project-scoped channels)", async () => {
+ const { dal, calls } = buildDAL();
+
+ await dal.deleteUsersRecipientsByScope({ userIds: ["u1"], orgId: "org-1" });
+
+ expect(calls.channelWhere).toContainEqual([`${TableName.AlertChannel}.orgId`, "org-1"]);
+ });
+
+ test("no-op when no users or no scope", 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.channelWhere).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 993b48a84e..503b061cac 100644
--- a/backend/src/services/alert/alert-channel-recipient-dal.ts
+++ b/backend/src/services/alert/alert-channel-recipient-dal.ts
@@ -5,6 +5,8 @@ import { TableName, TAlertChannelRecipients } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors";
import { ormify, selectAllTableCols } from "@app/lib/knex";
+import { AlertPrincipalType } from "./alert-types";
+
export type TAlertChannelRecipientDALFactory = ReturnType<typeof alertChannelRecipientDALFactory>;
export const alertChannelRecipientDALFactory = (db: TDbClient) => {
@@ -45,10 +47,32 @@ export const alertChannelRecipientDALFactory = (db: TDbClient) => {
}
};
+ const deleteUsersRecipientsByScope = async (
+ { userIds, orgId, projectId }: { userIds: string[]; orgId?: string; projectId?: 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);
+
+ return await (tx || db)(TableName.AlertChannelRecipient)
+ .where(`${TableName.AlertChannelRecipient}.principalType`, AlertPrincipalType.USER)
+ .whereIn(`${TableName.AlertChannelRecipient}.principalId`, userIds)
+ .whereIn(`${TableName.AlertChannelRecipient}.channelId`, channelIds)
+ .del();
+ } catch (error) {
+ throw new DatabaseError({ error, name: "DeleteUsersRecipientsByScope" });
+ }
+ };
+
return {
...alertChannelRecipientOrm,
findByChannelId,
findByChannelIds,
- deleteByChannelId
+ deleteByChannelId,
+ deleteUsersRecipientsByScope
};
};
diff --git a/backend/src/services/alert/alert-dal.test.ts b/backend/src/services/alert/alert-dal.test.ts
index bf19b50a29..741ea568ac 100644
--- a/backend/src/services/alert/alert-dal.test.ts
+++ b/backend/src/services/alert/alert-dal.test.ts
@@ -39,5 +39,7 @@ describe("alert dal", () => {
expect(calls.whereNull).toContainEqual(`${TableName.Project}.deleteAfter`);
expect(calls.where).toContainEqual([`${TableName.Alert}.enabled`, true]);
expect(calls.where).toContainEqual([`${TableName.Alert}.resourceType`, "identity.credential"]);
+ // the cron sweep must only pick up scheduled alerts, never event-driven ones
+ expect(calls.where).toContainEqual([`${TableName.Alert}.triggerType`, "scheduled"]);
});
});
diff --git a/backend/src/services/alert/alert-dal.ts b/backend/src/services/alert/alert-dal.ts
index f990a2c863..9ae4a5b2cc 100644
--- a/backend/src/services/alert/alert-dal.ts
+++ b/backend/src/services/alert/alert-dal.ts
@@ -5,6 +5,8 @@ import { TableName, TAlerts } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors";
import { ormify, selectAllTableCols } from "@app/lib/knex";
+import { AlertTriggerType } from "./alert-types";
+
export type TAlertDALFactory = ReturnType<typeof alertDALFactory>;
export const alertDALFactory = (db: TDbClient) => {
@@ -15,6 +17,7 @@ export const alertDALFactory = (db: TDbClient) => {
const alerts = await (tx || db.replicaNode())(TableName.Alert)
.leftJoin(TableName.Project, `${TableName.Alert}.projectId`, `${TableName.Project}.id`)
.where(`${TableName.Alert}.resourceType`, resourceType)
+ .where(`${TableName.Alert}.triggerType`, AlertTriggerType.Scheduled)
.where(`${TableName.Alert}.enabled`, true)
.whereNull(`${TableName.Project}.deleteAfter`)
.select(selectAllTableCols(TableName.Alert))
diff --git a/backend/src/services/alert/alert-engine.test.ts b/backend/src/services/alert/alert-engine.test.ts
index db1798a7f8..7f51d74277 100644
--- a/backend/src/services/alert/alert-engine.test.ts
+++ b/backend/src/services/alert/alert-engine.test.ts
@@ -29,6 +29,7 @@ const makeAlert = () => ({
resourceType: RESOURCE_TYPE,
resourceId: null,
eventType: "test.resource.expiration",
+ triggerType: "scheduled",
condition: { alertBefore: "30d" },
filters: null,
enabled: true,
diff --git a/backend/src/services/alert/alert-engine.ts b/backend/src/services/alert/alert-engine.ts
index a03f657a96..063d15adfd 100644
--- a/backend/src/services/alert/alert-engine.ts
+++ b/backend/src/services/alert/alert-engine.ts
@@ -141,7 +141,10 @@ export const alertEngineFactory = ({
list.push(row);
rowsByChannel.set(row.channelId, list);
});
- recipientsByChannel = await alertRecipientResolver.resolveMany(rowsByChannel);
+ recipientsByChannel = await alertRecipientResolver.resolveMany(rowsByChannel, {
+ orgId: alert.orgId,
+ projectId: alert.projectId
+ });
}
const deps: TAlertChannelDeps = { smtpService };
diff --git a/backend/src/services/alert/alert-recipient-resolver.test.ts b/backend/src/services/alert/alert-recipient-resolver.test.ts
new file mode 100644
index 0000000000..22456b532c
--- /dev/null
+++ b/backend/src/services/alert/alert-recipient-resolver.test.ts
@@ -0,0 +1,84 @@
+import { alertRecipientResolverFactory } from "./alert-recipient-resolver";
+import { AlertPrincipalType } from "./alert-types";
+
+type TUser = { id: string; email: string | null; firstName: string | null };
+
+// Builds a resolver whose DALs reflect a chosen "current membership" so we can assert that a
+// user/group removed from the scope after channel config stops receiving alerts at send time.
+const buildResolver = (opts: {
+ users: TUser[];
+ groupMembers?: Record<string, string[]>; // groupId -> userIds (current group membership)
+ orgUserIds?: string[]; // users currently in the org
+ effectiveProjectUserIds?: string[]; // users currently effective in the project
+}) => {
+ const usersById = new Map(opts.users.map((u) => [u.id, u]));
+ return alertRecipientResolverFactory({
+ userDAL: {
+ find: async ({ $in }: { $in: { id: string[] } }) =>
+ $in.id.map((id) => usersById.get(id)).filter(Boolean) as TUser[]
+ } as never,
+ userGroupMembershipDAL: {
+ find: async ({ $in }: { $in: { groupId: string[] } }) =>
+ $in.groupId.flatMap((groupId) => (opts.groupMembers?.[groupId] ?? []).map((userId) => ({ groupId, userId })))
+ } as never,
+ orgDAL: {
+ findMembership: async ({ $in }: { $in: { actorUserId: string[] } }) =>
+ $in.actorUserId.filter((id) => (opts.orgUserIds ?? []).includes(id)).map((actorUserId) => ({ actorUserId }))
+ } as never,
+ projectDAL: {
+ findEffectiveProjectSubjectsMembership: async ({ userIds }: { userIds: string[] }) => ({
+ effectiveUserIds: userIds.filter((id) => (opts.effectiveProjectUserIds ?? []).includes(id)),
+ effectiveGroupIds: [] as string[]
+ })
+ } as never
+ });
+};
+
+const user = (id: string): TUser => ({ id, email: `${id}@example.com`, firstName: id.toUpperCase() });
+
+describe("alert recipient resolver — send-time scope re-check", () => {
+ test("org scope: drops a user no longer in the org, keeps members and raw emails", async () => {
+ const resolver = buildResolver({ users: [user("u1"), user("u2")], orgUserIds: ["u1"] });
+
+ const result = await resolver.resolveMany(
+ new Map([
+ [
+ "c1",
+ [
+ { principalType: AlertPrincipalType.USER, principalId: "u1" },
+ { principalType: AlertPrincipalType.USER, principalId: "u2" }, // removed from org
+ { principalType: AlertPrincipalType.EMAIL, principalId: "[email protected]" }
+ ]
+ ]
+ ]),
+ { orgId: "org-1", projectId: null }
+ );
+
+ const emails = (result.get("c1") ?? []).map((r) => r.email).sort();
+ expect(emails).toEqual(["[email protected]", "[email protected]"]);
+ });
+
+ test("project scope: drops group members no longer effective in the project", async () => {
+ const resolver = buildResolver({
+ users: [user("u1"), user("u2"), user("u3")],
+ groupMembers: { g1: ["u1", "u2"] }, // g1 still has u1 + u2 as members
+ effectiveProjectUserIds: ["u1"] // but only u1 is still an effective project member
+ });
+
+ const result = await resolver.resolveMany(
+ new Map([
+ [
+ "c1",
+ [
+ { principalType: AlertPrincipalType.GROUP, principalId: "g1" },
+ { principalType: AlertPrincipalType.USER, principalId: "u3" } // not an effective member
+ ]
+ ]
+ ]),
+ { orgId: "org-1", projectId: "proj-1" }
+ );
+
+ const emails = (result.get("c1") ?? []).map((r) => r.email);
+ expect(emails).toEqual(["[email protected]"]);
+ });
+});
diff --git a/backend/src/services/alert/alert-recipient-resolver.ts b/backend/src/services/alert/alert-recipient-resolver.ts
index 1a95b393b9..4599d364ad 100644
--- a/backend/src/services/alert/alert-recipient-resolver.ts
+++ b/backend/src/services/alert/alert-recipient-resolver.ts
@@ -1,5 +1,7 @@
import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";
import { logger } from "@app/lib/logger";
+import { TOrgDALFactory } from "@app/services/org/org-dal";
+import { TProjectDALFactory } from "@app/services/project/project-dal";
import { TUserDALFactory } from "@app/services/user/user-dal";
import { TAlertRecipient } from "./alert-channel-types";
@@ -8,15 +10,46 @@ import { AlertPrincipalType } from "./alert-types";
type TAlertRecipientResolverDep = {
userDAL: Pick<TUserDALFactory, "find">;
userGroupMembershipDAL: Pick<TUserGroupMembershipDALFactory, "find">;
+ orgDAL: Pick<TOrgDALFactory, "findMembership">;
+ projectDAL: Pick<TProjectDALFactory, "findEffectiveProjectSubjectsMembership">;
};
type TResolvableRecipient = { principalType: string; principalId: string };
+type TResolveScope = { orgId: string; projectId?: string | null };
+
export type TAlertRecipientResolver = ReturnType<typeof alertRecipientResolverFactory>;
-export const alertRecipientResolverFactory = ({ userDAL, userGroupMembershipDAL }: TAlertRecipientResolverDep) => {
+export const alertRecipientResolverFactory = ({
+ userDAL,
+ userGroupMembershipDAL,
+ orgDAL,
+ projectDAL
+}: TAlertRecipientResolverDep) => {
+ const resolveInScopeUserIds = async (
+ scope: TResolveScope,
+ userIds: string[],
+ groupIds: string[]
+ ): Promise<Set<string>> => {
+ if (userIds.length === 0) return new Set();
+
+ if (scope.projectId) {
+ const { effectiveUserIds } = await projectDAL.findEffectiveProjectSubjectsMembership({
+ orgId: scope.orgId,
+ projectId: scope.projectId,
+ userIds,
+ groupIds
+ });
+ return new Set(effectiveUserIds);
+ }
+
+ const memberships = await orgDAL.findMembership({ $in: { actorUserId: userIds }, scopeOrgId: scope.orgId });
+ return new Set(memberships.map((membership) => membership.actorUserId).filter((id): id is string => Boolean(id)));
+ };
+
const resolveMany = async (
- rowsByChannel: Map<string, TResolvableRecipient[]>
+ rowsByChannel: Map<string, TResolvableRecipient[]>,
+ scope: TResolveScope
): Promise<Map<string, TAlertRecipient[]>> => {
const allGroupIds = new Set<string>();
const allUserIds = new Set<string>();
@@ -38,9 +71,10 @@ export const alertRecipientResolverFactory = ({ userDAL, userGroupMembershipDAL
});
}
+ const inScopeUserIds = await resolveInScopeUserIds(scope, [...allUserIds], [...allGroupIds]);
const usersById = new Map<string, Awaited<ReturnType<typeof userDAL.find>>[number]>();
- if (allUserIds.size > 0) {
- const users = await userDAL.find({ $in: { id: [...allUserIds] } });
+ if (inScopeUserIds.size > 0) {
+ const users = await userDAL.find({ $in: { id: [...inScopeUserIds] } });
users.forEach((user) => usersById.set(user.id, user));
}
@@ -89,10 +123,5 @@ export const alertRecipientResolverFactory = ({ userDAL, userGroupMembershipDAL
return result;
};
- const resolve = async (recipients: TResolvableRecipient[]): Promise<TAlertRecipient[]> => {
- const resolved = await resolveMany(new Map([["", recipients]]));
- return resolved.get("") ?? [];
- };
-
- return { resolve, resolveMany };
+ return { resolveMany };
};
diff --git a/backend/src/services/alert/alert-service.ts b/backend/src/services/alert/alert-service.ts
index 0d2eba3a08..b72510b784 100644
--- a/backend/src/services/alert/alert-service.ts
+++ b/backend/src/services/alert/alert-service.ts
@@ -17,7 +17,7 @@ import {
TListAlertsDTO,
TUpdateAlertDTO
} from "./alert-service-types";
-import { AlertPermissionAction, IResourceAlertProvider } from "./alert-types";
+import { AlertPermissionAction, AlertTriggerType, IResourceAlertProvider } from "./alert-types";
import { ALERT_CHANNEL_REGISTRY } from "./channels/alert-channel-registry";
export type TAlertServiceFactoryDep = {
@@ -141,6 +141,7 @@ export const alertServiceFactory = ({
resourceType: dto.resourceType,
resourceId: dto.resourceId,
eventType: dto.eventType,
+ triggerType: AlertTriggerType.Scheduled,
condition: dto.condition != null ? JSON.stringify(dto.condition) : null,
filters: dto.filters != null ? JSON.stringify(dto.filters) : null,
enabled: dto.enabled ?? true,
diff --git a/backend/src/services/alert/alert-types.ts b/backend/src/services/alert/alert-types.ts
index fb32803a56..6dc9a6a9fb 100644
--- a/backend/src/services/alert/alert-types.ts
+++ b/backend/src/services/alert/alert-types.ts
@@ -10,6 +10,11 @@ export enum AlertPrincipalType {
EMAIL = "email"
}
+export enum AlertTriggerType {
+ Scheduled = "scheduled",
+ Event = "event"
+}
+
export enum AlertRunStatus {
SUCCESS = "success",
PARTIAL = "partial",
diff --git a/backend/src/services/membership-user/membership-user-service.ts b/backend/src/services/membership-user/membership-user-service.ts
index 1adf1aa103..3002e353f4 100644
--- a/backend/src/services/membership-user/membership-user-service.ts
+++ b/backend/src/services/membership-user/membership-user-service.ts
@@ -22,6 +22,7 @@ import { requestMemoize } from "@app/lib/request-context/request-memoizer";
import { SearchResourceOperators } from "@app/lib/search-resource/search";
import { isDisposableEmail, sanitizeEmail, validateEmail } from "@app/lib/validator";
import { PamIdentities, SecretIdentities } from "@app/services/license-client";
+import { TAlertChannelRecipientDALFactory } from "@app/services/alert/alert-channel-recipient-dal";
import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";
import { TAdditionalPrivilegeDALFactory } from "../additional-privilege/additional-privilege-dal";
@@ -88,6 +89,7 @@ type TMembershipUserServiceFactoryDep = {
oidcConfigDAL: Pick<TOidcConfigDALFactory, "findOne">;
samlConfigDAL: Pick<TSamlConfigDALFactory, "findOne">;
usageMeteringService: Pick<TUsageMeteringServiceFactory, "emit" | "emitForProject">;
+ alertChannelRecipientDAL: Pick<TAlertChannelRecipientDALFactory, "deleteUsersRecipientsByScope">;
};
export type TMembershipUserServiceFactory = ReturnType<typeof membershipUserServiceFactory>;
@@ -113,7 +115,8 @@ export const membershipUserServiceFactory = ({
emailDomainDAL,
oidcConfigDAL,
samlConfigDAL,
- usageMeteringService
+ usageMeteringService,
+ alertChannelRecipientDAL
}: TMembershipUserServiceFactoryDep) => {
const scopeFactory = {
[AccessScope.Organization]: newOrgMembershipUserFactory({
@@ -554,6 +557,12 @@ export const membershipUserServiceFactory = ({
additionalPrivilegeDAL,
approvalPolicyDAL
});
+ // 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;
}
@@ -574,6 +583,12 @@ 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);
diff --git a/frontend/src/views/AlertsPage/components/channels/ChannelForm.tsx b/frontend/src/views/AlertsPage/components/channels/ChannelForm.tsx
index a9fce88418..cd23750557 100644
--- a/frontend/src/views/AlertsPage/components/channels/ChannelForm.tsx
+++ b/frontend/src/views/AlertsPage/components/channels/ChannelForm.tsx
@@ -200,7 +200,9 @@ export const ChannelForm = ({ projectId, channel, onComplete, onCancel }: Props)
)}
/>
- {channelType === AlertChannelType.Email && <ChannelRecipientsField />}
+ {channelType === AlertChannelType.Email && (
+ <ChannelRecipientsField projectId={projectId} />
+ )}
{channelType === AlertChannelType.Slack && (
<Controller
diff --git a/frontend/src/views/AlertsPage/components/channels/ChannelRecipientsField.tsx b/frontend/src/views/AlertsPage/components/channels/ChannelRecipientsField.tsx
index dbc87b16b4..819273d49b 100644
--- a/frontend/src/views/AlertsPage/components/channels/ChannelRecipientsField.tsx
+++ b/frontend/src/views/AlertsPage/components/channels/ChannelRecipientsField.tsx
@@ -10,7 +10,12 @@ import {
FieldLabel
} from "@app/components/v3";
import { useOrganization } from "@app/context";
-import { useGetOrganizationGroups, useGetOrgUsers } from "@app/hooks/api";
+import {
+ useGetOrganizationGroups,
+ useGetOrgUsers,
+ useGetWorkspaceUsers,
+ useListWorkspaceGroups
+} from "@app/hooks/api";
import { TAlertChannelForm, TAlertChannelRecipientForm } from "@app/hooks/api/alertChannels";
import { ALERT_PRINCIPAL_TYPE_LABELS, AlertPrincipalType } from "@app/hooks/api/alerts";
@@ -22,38 +27,42 @@ type RecipientOption = {
label: string;
};
-export const ChannelRecipientsField = () => {
- const { control } = useFormContext<TAlertChannelForm>();
- const { currentOrg } = useOrganization();
- const orgId = currentOrg.id;
+type PrincipalSource = {
+ userOptions: RecipientOption[];
+ groupOptions: RecipientOption[];
+ labelLookup: Map<string, string>;
+};
- const [inputValue, setInputValue] = useState("");
+type MemberLike = {
+ user?: { id: string; username?: string; firstName?: string; lastName?: string; email?: string };
+};
- const { data: orgUsers = [] } = useGetOrgUsers(orgId);
- const { data: orgGroups = [] } = useGetOrganizationGroups(orgId);
-
- const { userOptions, groupOptions, labelLookup } = useMemo(() => {
- const lookup = new Map<string, string>();
-
- const users: RecipientOption[] = orgUsers
- .filter((member) => member.user?.id)
- .map((member) => {
- const label =
- member.user.username ||
- [member.user.firstName, member.user.lastName].filter(Boolean).join(" ") ||
- member.user.email ||
- member.user.id;
- lookup.set(`${AlertPrincipalType.User}:${member.user.id}`, label);
- return { principalType: AlertPrincipalType.User, principalId: member.user.id, label };
- });
-
- const groups: RecipientOption[] = orgGroups.map((group) => {
- lookup.set(`${AlertPrincipalType.Group}:${group.id}`, group.name);
- return { principalType: AlertPrincipalType.Group, principalId: group.id, label: group.name };
+const toUserOptions = (members: MemberLike[], lookup: Map<string, string>): RecipientOption[] =>
+ members
+ .filter((member) => member.user?.id)
+ .map((member) => {
+ const user = member.user!;
+ const label =
+ user.username ||
+ [user.firstName, user.lastName].filter(Boolean).join(" ") ||
+ user.email ||
+ user.id;
+ lookup.set(`${AlertPrincipalType.User}:${user.id}`, label);
+ return { principalType: AlertPrincipalType.User, principalId: user.id, label };
});
- return { userOptions: users, groupOptions: groups, labelLookup: lookup };
- }, [orgUsers, orgGroups]);
+const toGroupOptions = (
+ groups: { id: string; name: string }[],
+ lookup: Map<string, string>
+): RecipientOption[] =>
+ groups.map((group) => {
+ lookup.set(`${AlertPrincipalType.Group}:${group.id}`, group.name);
+ return { principalType: AlertPrincipalType.Group, principalId: group.id, label: group.name };
+ });
+
+const RecipientsSelect = ({ userOptions, groupOptions, labelLookup }: PrincipalSource) => {
+ const { control } = useFormContext<TAlertChannelForm>();
+ const [inputValue, setInputValue] = useState("");
const groupedOptions = useMemo(
() => [
@@ -132,7 +141,7 @@ export const ChannelRecipientsField = () => {
}}
/>
<FieldDescription>
- This channel delivers to these recipients. Add org users, groups, or raw email
+ This channel delivers to these recipients. Add users, groups, or raw email
addresses.
</FieldDescription>
<FieldError errors={[error]} />
@@ -143,3 +152,46 @@ export const ChannelRecipientsField = () => {
/>
);
};
+
+const OrgRecipients = () => {
+ const { currentOrg } = useOrganization();
+ const { data: orgUsers = [] } = useGetOrgUsers(currentOrg.id);
+ const { data: orgGroups = [] } = useGetOrganizationGroups(currentOrg.id);
+
+ const source = useMemo<PrincipalSource>(() => {
+ const labelLookup = new Map<string, string>();
+ return {
+ userOptions: toUserOptions(orgUsers, labelLookup),
+ groupOptions: toGroupOptions(orgGroups, labelLookup),
+ labelLookup
+ };
+ }, [orgUsers, orgGroups]);
+
+ return <RecipientsSelect {...source} />;
+};
+
+const ProjectRecipients = ({ projectId }: { projectId: string }) => {
+ const { data: projectUsers = [] } = useGetWorkspaceUsers(projectId, true);
+ const { data: projectGroups = [] } = useListWorkspaceGroups(projectId);
+
+ const source = useMemo<PrincipalSource>(() => {
+ const labelLookup = new Map<string, string>();
+ return {
+ userOptions: toUserOptions(projectUsers, labelLookup),
+ groupOptions: toGroupOptions(
+ projectGroups.map((membership) => ({
+ id: membership.group.id,
+ name: membership.group.name
+ })),
+ labelLookup
+ ),
+ labelLookup
+ };
+ }, [projectUsers, projectGroups]);
+
+ return <RecipientsSelect {...source} />;
+};
+
+export const ChannelRecipientsField = ({ projectId }: { projectId?: string }) => {
+ return projectId ? <ProjectRecipients projectId={projectId} /> : <OrgRecipients />;
+};