Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat(pam): slack notifications for access approvals
bernie-g6b68641eea32
diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.tsindex 7191f67750..5ed61fda3f 100644--- a/backend/src/@types/knex.d.ts+++ b/backend/src/@types/knex.d.ts@@ -775,6 +775,11 @@ import {TPamDiscoverySourcesUpdate} from "@app/db/schemas/pam-discovery-sources";import { TPamDomains, TPamDomainsInsert, TPamDomainsUpdate } from "@app/db/schemas/pam-domains";+import {+ TPamFolderNotificationConfigs,+ TPamFolderNotificationConfigsInsert,+ TPamFolderNotificationConfigsUpdate+} from "@app/db/schemas/pam-folder-notification-configs";import { TPamFolders, TPamFoldersInsert, TPamFoldersUpdate } from "@app/db/schemas/pam-folders";import {TPamProjectRecordingConfigs,@@ -1750,6 +1755,11 @@ declare module "knex/types/tables" {TPamAccountTemplatesUpdate>;[TableName.PamFolder]: KnexOriginal.CompositeTableType<TPamFolders, TPamFoldersInsert, TPamFoldersUpdate>;+ [TableName.PamFolderNotificationConfig]: KnexOriginal.CompositeTableType<+ TPamFolderNotificationConfigs,+ TPamFolderNotificationConfigsInsert,+ TPamFolderNotificationConfigsUpdate+ >;[TableName.PamResource]: KnexOriginal.CompositeTableType<TPamResources, TPamResourcesInsert, TPamResourcesUpdate>;[TableName.PamResourceFavorite]: KnexOriginal.CompositeTableType<TPamResourceFavorites,diff --git a/backend/src/db/migrations/20260708143943_pam-folder-notification-configs.ts b/backend/src/db/migrations/20260708143943_pam-folder-notification-configs.tsnew file mode 100644index 0000000000..ae28f4c2a0--- /dev/null+++ b/backend/src/db/migrations/20260708143943_pam-folder-notification-configs.ts@@ -0,0 +1,31 @@+import { Knex } from "knex";++import { TableName } from "../schemas";+import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";++export async function up(knex: Knex): Promise<void> {+ if (await knex.schema.hasTable(TableName.PamFolderNotificationConfig)) return;++ await knex.schema.createTable(TableName.PamFolderNotificationConfig, (t) => {+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());+ t.uuid("folderId").notNullable();+ t.foreign("folderId").references("id").inTable(TableName.PamFolder).onDelete("CASCADE");+ t.index(["folderId"]);+ t.uuid("workflowIntegrationId").notNullable();+ t.foreign("workflowIntegrationId").references("id").inTable(TableName.WorkflowIntegrations).onDelete("CASCADE");+ t.index(["workflowIntegrationId"]);+ // [{ id, name }] channel objects; names are stored so the UI can render chips for viewers+ // who lack org Settings read (the Slack channel-list API), and so Teams can extend the+ // object shape (e.g. teamId) without a schema change.+ t.jsonb("channels").notNullable();+ t.jsonb("events").notNullable();+ t.timestamps(true, true, true);+ });++ await createOnUpdateTrigger(knex, TableName.PamFolderNotificationConfig);+}++export async function down(knex: Knex): Promise<void> {+ await dropOnUpdateTrigger(knex, TableName.PamFolderNotificationConfig);+ await knex.schema.dropTableIfExists(TableName.PamFolderNotificationConfig);+}diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.tsindex f076e3555d..dd35a8a83b 100644--- a/backend/src/db/schemas/index.ts+++ b/backend/src/db/schemas/index.ts@@ -137,6 +137,7 @@ export * from "./pam-discovery-source-resources";export * from "./pam-discovery-source-runs";export * from "./pam-discovery-sources";export * from "./pam-domains";+export * from "./pam-folder-notification-configs";export * from "./pam-folders";export * from "./pam-project-recording-configs";export * from "./pam-resource-favorites";diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.tsindex 2ec045125c..99eefff1da 100644--- a/backend/src/db/schemas/models.ts+++ b/backend/src/db/schemas/models.ts@@ -238,6 +238,7 @@ export enum TableName {// PAMPamAccountTemplate = "pam_account_templates",PamFolder = "pam_folders",+ PamFolderNotificationConfig = "pam_folder_notification_configs",PamResource = "pam_resources",PamAccount = "pam_accounts",PamSession = "pam_sessions",diff --git a/backend/src/db/schemas/pam-folder-notification-configs.ts b/backend/src/db/schemas/pam-folder-notification-configs.tsnew file mode 100644index 0000000000..4dfa3bd6f0--- /dev/null+++ b/backend/src/db/schemas/pam-folder-notification-configs.ts@@ -0,0 +1,27 @@+// Code generated by automation script, DO NOT EDIT.+// Automated by pulling database and generating zod schema+// To update. Just run npm run generate:schema+// Written by akhilmhdh.++import { z } from "zod";++import { TImmutableDBKeys } from "./models";++export const PamFolderNotificationConfigsSchema = z.object({+ id: z.string().uuid(),+ folderId: z.string().uuid(),+ workflowIntegrationId: z.string().uuid(),+ channels: z.unknown(),+ events: z.unknown(),+ createdAt: z.date(),+ updatedAt: z.date()+});++export type TPamFolderNotificationConfigs = z.infer<typeof PamFolderNotificationConfigsSchema>;+export type TPamFolderNotificationConfigsInsert = Omit<+ z.input<typeof PamFolderNotificationConfigsSchema>,+ TImmutableDBKeys+>;+export type TPamFolderNotificationConfigsUpdate = Partial<+ Omit<z.input<typeof PamFolderNotificationConfigsSchema>, TImmutableDBKeys>+>;diff --git a/backend/src/ee/routes/v1/pam-routers/pam-approval-configuration-router.ts b/backend/src/ee/routes/v1/pam-routers/pam-approval-configuration-router.tsindex c71f8d5e89..00d67e017e 100644--- a/backend/src/ee/routes/v1/pam-routers/pam-approval-configuration-router.ts+++ b/backend/src/ee/routes/v1/pam-routers/pam-approval-configuration-router.ts@@ -1,6 +1,7 @@import z from "zod";import { EventType } from "@app/ee/services/audit-log/audit-log-types";+import { PamNotificationEvent } from "@app/ee/services/pam/pam-enums";import { readLimit, writeLimit } from "@app/server/config/rateLimiter";import { verifyAuth } from "@app/server/plugins/auth/verify-auth";import { ApproverType } from "@app/services/approval-policy/approval-policy-enums";@@ -15,6 +16,17 @@ const StepSchema = z.object({approvers: z.array(ApproverSchema)});+const NotificationChannelSchema = z.object({+ id: z.string().min(1).max(64),+ name: z.string().min(1).max(256)+});++const NotificationConfigSchema = z.object({+ workflowIntegrationId: z.string().uuid(),+ channels: z.array(NotificationChannelSchema).min(1).max(20),+ events: z.array(z.nativeEnum(PamNotificationEvent)).min(1)+});+export const registerPamApprovalConfigurationRouter = async (server: FastifyZodProvider) => {server.route({method: "GET",@@ -30,6 +42,13 @@ export const registerPamApprovalConfigurationRouter = async (server: FastifyZodPz.object({approvers: z.array(ApproverSchema)})+ ),+ notificationConfigs: z.array(+ NotificationConfigSchema.extend({+ id: z.string().uuid(),+ integration: z.string(),+ integrationSlug: z.string()+ }))})}@@ -57,7 +76,8 @@ export const registerPamApprovalConfigurationRouter = async (server: FastifyZodPfolderId: z.string().uuid()}),body: z.object({- steps: z.array(StepSchema).max(1)+ steps: z.array(StepSchema).max(1),+ notificationConfigs: z.array(NotificationConfigSchema).max(10).optional()}),response: {200: z.object({@@ -71,6 +91,7 @@ export const registerPamApprovalConfigurationRouter = async (server: FastifyZodPfolderId: req.params.folderId,projectId: req.internalPamProjectId,steps: req.body.steps,+ notificationConfigs: req.body.notificationConfigs,actorId: req.permission.id,actor: req.permission.type,actorOrgId: req.permission.orgId,@@ -86,7 +107,8 @@ export const registerPamApprovalConfigurationRouter = async (server: FastifyZodPmetadata: {folderId: req.params.folderId,policyId: result.policyId,- stepCount: result.stepCount+ stepCount: result.stepCount,+ notificationConfigCount: result.notificationConfigCount}}});diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 896c9d03e7..88e105f2ee 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -6200,6 +6200,7 @@ interface PamApprovalConfigUpdateEvent {folderId: string;policyId: string | null;stepCount: number;+ notificationConfigCount?: number;};}diff --git a/backend/src/ee/services/pam-access-request/pam-access-request-fns.test.ts b/backend/src/ee/services/pam-access-request/pam-access-request-fns.test.tsnew file mode 100644index 0000000000..03bece775b--- /dev/null+++ b/backend/src/ee/services/pam-access-request/pam-access-request-fns.test.ts@@ -0,0 +1,70 @@+import { PamNotificationEvent } from "../pam/pam-enums";+import { getSlackSendTargets, TFolderNotificationConfigRow } from "./pam-access-request-fns";++const baseConfig = (overrides: Partial<TFolderNotificationConfigRow> = {}): TFolderNotificationConfigRow => ({+ workflowIntegrationId: "integration-1",+ integration: "slack",+ status: "installed",+ channels: [{ id: "C123", name: "access-requests" }],+ events: [PamNotificationEvent.AccessRequested],+ ...overrides+});++describe("getSlackSendTargets", () => {+ test("returns channel ids for a subscribed slack config", () => {+ const targets = getSlackSendTargets([baseConfig()], PamNotificationEvent.AccessRequested);+ expect(targets).toEqual([{ workflowIntegrationId: "integration-1", channelIds: ["C123"] }]);+ });++ test("skips configs not subscribed to the event", () => {+ const targets = getSlackSendTargets([baseConfig()], PamNotificationEvent.AccessRequestApproved);+ expect(targets).toEqual([]);+ });++ test("skips non-slack integrations", () => {+ const targets = getSlackSendTargets(+ [baseConfig({ integration: "microsoft-teams" })],+ PamNotificationEvent.AccessRequested+ );+ expect(targets).toEqual([]);+ });++ test("skips integrations that are not installed", () => {+ const targets = getSlackSendTargets([baseConfig({ status: "pending" })], PamNotificationEvent.AccessRequested);+ expect(targets).toEqual([]);+ });++ test("skips configs with no channels", () => {+ const targets = getSlackSendTargets([baseConfig({ channels: [] })], PamNotificationEvent.AccessRequested);+ expect(targets).toEqual([]);+ });++ test("tolerates malformed jsonb values", () => {+ const targets = getSlackSendTargets(+ [baseConfig({ channels: "not-an-array", events: { bogus: true } })],+ PamNotificationEvent.AccessRequested+ );+ expect(targets).toEqual([]);+ });++ test("fans out across multiple matching configs", () => {+ const targets = getSlackSendTargets(+ [+ baseConfig(),+ baseConfig({+ workflowIntegrationId: "integration-2",+ channels: [+ { id: "C456", name: "sre-oncall" },+ { id: "C789", name: "security" }+ ],+ events: [PamNotificationEvent.AccessRequested, PamNotificationEvent.AccessRequestDenied]+ })+ ],+ PamNotificationEvent.AccessRequested+ );+ expect(targets).toEqual([+ { workflowIntegrationId: "integration-1", channelIds: ["C123"] },+ { workflowIntegrationId: "integration-2", channelIds: ["C456", "C789"] }+ ]);+ });+});diff --git a/backend/src/ee/services/pam-access-request/pam-access-request-fns.ts b/backend/src/ee/services/pam-access-request/pam-access-request-fns.tsnew file mode 100644index 0000000000..9b9db3d54e--- /dev/null+++ b/backend/src/ee/services/pam-access-request/pam-access-request-fns.ts@@ -0,0 +1,45 @@+import { z } from "zod";++import {+ WorkflowIntegration,+ WorkflowIntegrationStatus+} from "@app/services/workflow-integration/workflow-integration-types";++import { PamNotificationEvent } from "../pam/pam-enums";++const NotificationChannelsSchema = z.array(z.object({ id: z.string(), name: z.string() }));+const NotificationEventsSchema = z.array(z.nativeEnum(PamNotificationEvent));++export const parseNotificationChannels = (value: unknown) => {+ const result = NotificationChannelsSchema.safeParse(value);+ return result.success ? result.data : [];+};++export const parseNotificationEvents = (value: unknown) => {+ const result = NotificationEventsSchema.safeParse(value);+ return result.success ? result.data : [];+};++export type TFolderNotificationConfigRow = {+ workflowIntegrationId: string;+ integration: string;+ status: string;+ channels: unknown;+ events: unknown;+};++// Resolves which Slack sends a folder's configs call for on a given event. Pure so the+// subscription/platform/status filtering is unit-testable without a DB.+export const getSlackSendTargets = (configs: TFolderNotificationConfigRow[], event: PamNotificationEvent) =>+ configs+ .filter(+ (config) =>+ config.integration === WorkflowIntegration.SLACK &&+ config.status === WorkflowIntegrationStatus.INSTALLED &&+ parseNotificationEvents(config.events).includes(event)+ )+ .map((config) => ({+ workflowIntegrationId: config.workflowIntegrationId,+ channelIds: parseNotificationChannels(config.channels).map((channel) => channel.id)+ }))+ .filter((target) => target.channelIds.length > 0);diff --git a/backend/src/ee/services/pam-access-request/pam-access-request-service.ts b/backend/src/ee/services/pam-access-request/pam-access-request-service.tsindex 6fb6e17d12..778c45c97c 100644--- a/backend/src/ee/services/pam-access-request/pam-access-request-service.ts+++ b/backend/src/ee/services/pam-access-request/pam-access-request-service.ts@@ -14,6 +14,7 @@ import { getConfig } from "@app/lib/config/env";import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";import { logger } from "@app/lib/logger";import { formatDuration, ms } from "@app/lib/ms";+import { TNotification, TriggerFeature } from "@app/lib/workflow-integrations/types";import {TApprovalPolicyDALFactory,TApprovalPolicyStepApproversDALFactory,@@ -40,14 +41,19 @@ import {createApprovalRequestWithSteps,notifyApproversForStep} from "@app/services/approval-policy/approval-request-fns";+import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { TMembershipDALFactory } from "@app/services/membership/membership-dal";import { TMembershipRoleDALFactory } from "@app/services/membership/membership-role-dal";import { TNotificationServiceFactory } from "@app/services/notification/notification-service";import { NotificationType } from "@app/services/notification/notification-types";+import { sendSlackNotification } from "@app/services/slack/slack-fns";+import { TSlackIntegrationDALFactory } from "@app/services/slack/slack-integration-dal";import { SmtpTemplates, TSmtpService } from "@app/services/smtp/smtp-service";import { TUserDALFactory } from "@app/services/user/user-dal";+import { TWorkflowIntegrationDALFactory } from "@app/services/workflow-integration/workflow-integration-dal";+import { WorkflowIntegration } from "@app/services/workflow-integration/workflow-integration-types";-import { PamAccessStatus, PamProductRole, PamSessionStatus } from "../pam/pam-enums";+import { PamAccessStatus, PamNotificationEvent, PamProductRole, PamSessionStatus } from "../pam/pam-enums";import { resolveAccountByPath } from "../pam/pam-fns";import {checkAccountAccess,@@ -61,6 +67,7 @@ import { TPamAccountTemplateDALFactory } from "../pam-account-template/pam-accouimport { TPamFolderDALFactory } from "../pam-folder/pam-folder-dal";import { TPamSessionDALFactory } from "../pam-session/pam-session-dal";import { sendPamSessionCancellationSignal } from "../pam-session/pam-session-fns";+import { getSlackSendTargets, parseNotificationChannels, parseNotificationEvents } from "./pam-access-request-fns";import {TCheckGrantDTO,TCreateAccessRequestDTO,@@ -74,6 +81,7 @@ import {TRevokeAccessRequestDTO,TSetApprovalConfigurationDTO} from "./pam-access-request-types";+import { TPamFolderNotificationConfigDALFactory } from "./pam-folder-notification-config-dal";type TPamAccessRequestServiceFactoryDep = {approvalPolicyDAL: Pick<@@ -120,6 +128,13 @@ type TPamAccessRequestServiceFactoryDep = {groupDAL: Pick<TGroupDALFactory, "find">;userGroupMembershipDAL: Pick<TUserGroupMembershipDALFactory, "find" | "findGroupMembershipsByUserIdInOrg">;userDAL: Pick<TUserDALFactory, "findById" | "find">;+ pamFolderNotificationConfigDAL: Pick<+ TPamFolderNotificationConfigDALFactory,+ "findByFolderIdWithIntegration" | "delete" | "insertMany" | "transaction"+ >;+ workflowIntegrationDAL: Pick<TWorkflowIntegrationDALFactory, "find">;+ slackIntegrationDAL: Pick<TSlackIntegrationDALFactory, "findByIdWithWorkflowIntegrationDetails">;+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;};export type TPamAccessRequestServiceFactory = ReturnType<typeof pamAccessRequestServiceFactory>;@@ -145,7 +160,11 @@ export const pamAccessRequestServiceFactory = ({smtpService,groupDAL,userGroupMembershipDAL,- userDAL+ userDAL,+ pamFolderNotificationConfigDAL,+ workflowIntegrationDAL,+ slackIntegrationDAL,+ kmsService}: TPamAccessRequestServiceFactoryDep) => {const findFolderPolicy = async (folderId: string) => {const policy = await approvalPolicyDAL.findOne({@@ -156,6 +175,90 @@ export const pamAccessRequestServiceFactory = ({return policy ?? null;};+ const getNotificationConfigs = async (folderId: string) => {+ const configs = await pamFolderNotificationConfigDAL.findByFolderIdWithIntegration(folderId);+ return configs.map((config) => ({+ id: config.id,+ workflowIntegrationId: config.workflowIntegrationId,+ integration: config.integration,+ integrationSlug: config.slug,+ channels: parseNotificationChannels(config.channels),+ events: parseNotificationEvents(config.events)+ }));+ };++ // Chat notifications are best-effort: they must never fail or delay the request flow itself.+ const triggerFolderSlackNotifications = async ({+ folderId,+ event,+ orgId,+ notification+ }: {+ folderId: string;+ event: PamNotificationEvent;+ orgId: string;+ notification: TNotification;+ }) => {+ try {+ const configs = await pamFolderNotificationConfigDAL.findByFolderIdWithIntegration(folderId);+ const targets = getSlackSendTargets(configs, event);++ for (const target of targets) {+ // eslint-disable-next-line no-await-in-loop+ const slackIntegration = await slackIntegrationDAL.findByIdWithWorkflowIntegrationDetails(+ target.workflowIntegrationId+ );+ if (slackIntegration) {+ // eslint-disable-next-line no-await-in-loop+ await sendSlackNotification({+ orgId,+ notification,+ kmsService,+ targetChannelIds: target.channelIds,+ slackIntegration+ });+ }+ }+ } catch (err) {+ logger.error(err, `Failed to send PAM Slack notifications [folderId=${folderId}] [event=${event}]`);+ }+ };++ const notifyFolderChannelsOfDecision = async (params: {+ folderId: string;+ decision: ApprovalRequestApprovalDecision;+ requesterName?: string | null;+ requesterEmail?: string | null;+ accountName?: string;+ comment?: string;+ orgId: string;+ requestId: string;+ }) => {+ const approved = params.decision === ApprovalRequestApprovalDecision.Approved;+ try {+ const folder = await pamFolderDAL.findById(params.folderId);+ const cfg = getConfig();+ await triggerFolderSlackNotifications({+ folderId: params.folderId,+ event: approved ? PamNotificationEvent.AccessRequestApproved : PamNotificationEvent.AccessRequestDenied,+ orgId: params.orgId,+ notification: {+ type: approved ? TriggerFeature.PAM_ACCESS_REQUEST_APPROVED : TriggerFeature.PAM_ACCESS_REQUEST_DENIED,+ payload: {+ requesterFullName: params.requesterName || "Unknown",+ requesterEmail: params.requesterEmail || "",+ accountName: params.accountName ?? "a PAM account",+ folderName: folder?.name ?? "",+ comment: params.comment,+ approvalUrl: `${cfg.SITE_URL}/organizations/${params.orgId}/pam/approval-requests?requestId=${params.requestId}`+ }+ }+ });+ } catch (err) {+ logger.error(err, `Failed to send PAM review Slack notifications [requestId=${params.requestId}]`);+ }+ };+// npm ms returns undefined (not an error) for strings it can't parse, e.g. Go-style "2h30m"const parseDurationMs = (duration: string): number => {const durationMs: number | undefined = ms(duration);@@ -298,17 +401,25 @@ export const pamAccessRequestServiceFactory = ({});}+ const notificationConfigs = await getNotificationConfigs(folderId);+const policy = await findFolderPolicy(folderId);if (!policy) {- return { steps: [] };+ return { steps: [], notificationConfigs };}// The policy row and step tuning fields are internal; the UI only needs the approver lists.const steps = await approvalPolicyDAL.findStepsByPolicyId(policy.id);- return { steps: steps.map((s) => ({ approvers: s.approvers })) };+ return { steps: steps.map((s) => ({ approvers: s.approvers })), notificationConfigs };};- const setApprovalConfiguration = async ({ folderId, projectId, steps, ...ctx }: TSetApprovalConfigurationDTO) => {+ const setApprovalConfiguration = async ({+ folderId,+ projectId,+ steps,+ notificationConfigs,+ ...ctx+ }: TSetApprovalConfigurationDTO) => {await verifyProductMembership(permissionService, projectId, ctx);const folder = await assertFolderPolicyManagement(folderId, projectId, ctx);@@ -334,6 +445,45 @@ export const pamAccessRequestServiceFactory = ({}}+ // Notification configs live independent of the policy row, so they are persisted before the+ // policy branches below; several of those branches return early.+ if (notificationConfigs !== undefined) {+ if (notificationConfigs.length > 0) {+ const integrationIds = [...new Set(notificationConfigs.map((c) => c.workflowIntegrationId))];+ const integrations = await workflowIntegrationDAL.find({ $in: { id: integrationIds } });+ const integrationById = new Map(integrations.map((i) => [i.id, i]));++ for (const config of notificationConfigs) {+ const integration = integrationById.get(config.workflowIntegrationId);+ if (!integration || integration.orgId !== ctx.actorOrgId) {+ throw new BadRequestError({ message: "Workflow integration not found in your organization" });+ }+ if (integration.integration !== WorkflowIntegration.SLACK) {+ throw new BadRequestError({+ message: "Only Slack workflow integrations are supported for PAM notifications"+ });+ }+ }+ }++ await pamFolderNotificationConfigDAL.transaction(async (tx) => {+ await pamFolderNotificationConfigDAL.delete({ folderId }, tx);+ if (notificationConfigs.length > 0) {+ await pamFolderNotificationConfigDAL.insertMany(+ notificationConfigs.map((config) => ({+ folderId,+ workflowIntegrationId: config.workflowIntegrationId,+ // arrays must be pre-serialized or knex binds them as PG arrays instead of jsonb+ channels: JSON.stringify(config.channels),+ events: JSON.stringify(config.events)+ })),+ tx+ );+ }+ });+ }+ const notificationConfigCount = notificationConfigs?.length;+const existingPolicy = await findFolderPolicy(folderId);const hasApprovers = steps.length === 1 && steps[0].approvers.length > 0;@@ -342,11 +492,11 @@ export const pamAccessRequestServiceFactory = ({await approvalPolicyStepsDAL.delete({ policyId: existingPolicy.id }, tx);await approvalPolicyDAL.deleteById(existingPolicy.id, tx);});- return { policyId: existingPolicy.id, folderId, stepCount: steps.length };+ return { policyId: existingPolicy.id, folderId, stepCount: steps.length, notificationConfigCount };}if (!hasApprovers) {- return { policyId: null, folderId, stepCount: 0 };+ return { policyId: null, folderId, stepCount: 0, notificationConfigCount };}if (existingPolicy) {@@ -379,7 +529,7 @@ export const pamAccessRequestServiceFactory = ({}});- return { policyId: existingPolicy.id, folderId, stepCount: steps.length };+ return { policyId: existingPolicy.id, folderId, stepCount: steps.length, notificationConfigCount };}const newPolicy = await approvalPolicyDAL.transaction(async (tx) => {@@ -426,7 +576,7 @@ export const pamAccessRequestServiceFactory = ({return policy;});- return { policyId: newPolicy.id, folderId, stepCount: steps.length };+ return { policyId: newPolicy.id, folderId, stepCount: steps.length, notificationConfigCount };};const createRequest = async ({ accountId, path, projectId, reason, duration, ...ctx }: TCreateAccessRequestDTO) => {@@ -556,6 +706,8 @@ export const pamAccessRequestServiceFactory = ({});+ const approvalUrl = `${getConfig().SITE_URL}/organizations/${ctx.actorOrgId}/pam/approval-requests?requestId=${request.id}`;+const firstStep = stepsForRequest[0];if (firstStep) {try {@@ -582,9 +734,6 @@ export const pamAccessRequestServiceFactory = ({const recipients = approverUsers.filter((u) => u.email).map((u) => u.email as string);if (recipients.length > 0) {- const cfg = getConfig();- const approvalUrl = `${cfg.SITE_URL}/organizations/${ctx.actorOrgId}/pam/approval-requests?requestId=${request.id}`;-await smtpService.sendMail({recipients,subjectLine: "PAM Access Request",@@ -603,6 +752,24 @@ export const pamAccessRequestServiceFactory = ({} catch (err) {logger.error(err, `Failed to send approval emails for PAM access request [requestId=${request.id}]`);}++ await triggerFolderSlackNotifications({+ folderId: account.folderId,+ event: PamNotificationEvent.AccessRequested,+ orgId: ctx.actorOrgId,+ notification: {+ type: TriggerFeature.PAM_ACCESS_REQUESTED,+ payload: {+ requesterFullName: requesterName || "Unknown",+ requesterEmail: user.email ?? "",+ accountName: account.name,+ folderName: account.folderName ?? "",+ accessDuration: formatDuration(duration),+ reason: trimmedReason,+ approvalUrl+ }+ }+ });}return { request, accountId: account.id, folderId: account.folderId };@@ -905,6 +1072,19 @@ export const pamAccessRequestServiceFactory = ({comment);+ if (folderId) {+ await notifyFolderChannelsOfDecision({+ folderId,+ decision: ApprovalRequestApprovalDecision.Rejected,+ requesterName: request.requesterName,+ requesterEmail: request.requesterEmail,+ accountName: rejectedAccount?.name,+ comment,+ orgId: request.organizationId,+ requestId: request.id+ });+ }+return { request: updatedRequest, accountId: requestData?.requestData?.accountId, folderId };}@@ -1012,6 +1192,19 @@ export const pamAccessRequestServiceFactory = ({approvedAccount?.name,comment);++ if (folderId) {+ await notifyFolderChannelsOfDecision({+ folderId,+ decision: ApprovalRequestApprovalDecision.Approved,+ requesterName: request.requesterName,+ requesterEmail: request.requesterEmail,+ accountName: approvedAccount?.name,+ comment,+ orgId: request.organizationId,+ requestId: request.id+ });+ }}return { request: updatedRequest, accountId: requestData?.requestData?.accountId, folderId };diff --git a/backend/src/ee/services/pam-access-request/pam-access-request-types.ts b/backend/src/ee/services/pam-access-request/pam-access-request-types.tsindex 22e1ac1c6c..5a4b8ffc3e 100644--- a/backend/src/ee/services/pam-access-request/pam-access-request-types.ts+++ b/backend/src/ee/services/pam-access-request/pam-access-request-types.ts@@ -1,5 +1,6 @@import { ApprovalRequestApprovalDecision, ApproverType } from "@app/services/approval-policy/approval-policy-enums";+import { PamNotificationEvent } from "../pam/pam-enums";import { TActorContext } from "../pam/pam-permission";export type TGetApprovalConfigurationDTO = {@@ -7,12 +8,20 @@ export type TGetApprovalConfigurationDTO = {projectId: string;} & TActorContext;+export type TPamNotificationConfigInput = {+ workflowIntegrationId: string;+ channels: { id: string; name: string }[];+ events: PamNotificationEvent[];+};+export type TSetApprovalConfigurationDTO = {folderId: string;projectId: string;steps: {approvers: { type: ApproverType; id: string }[];}[];+ // undefined leaves existing configs unchanged so older clients that only manage steps can't wipe them+ notificationConfigs?: TPamNotificationConfigInput[];} & TActorContext;export type TCreateAccessRequestDTO = {diff --git a/backend/src/ee/services/pam-access-request/pam-folder-notification-config-dal.ts b/backend/src/ee/services/pam-access-request/pam-folder-notification-config-dal.tsnew file mode 100644index 0000000000..21d5c890be--- /dev/null+++ b/backend/src/ee/services/pam-access-request/pam-folder-notification-config-dal.ts@@ -0,0 +1,34 @@+import { Knex } from "knex";++import { TDbClient } from "@app/db";+import { TableName } from "@app/db/schemas";+import { DatabaseError } from "@app/lib/errors";+import { ormify, selectAllTableCols } from "@app/lib/knex";++export type TPamFolderNotificationConfigDALFactory = ReturnType<typeof pamFolderNotificationConfigDALFactory>;++export const pamFolderNotificationConfigDALFactory = (db: TDbClient) => {+ const orm = ormify(db, TableName.PamFolderNotificationConfig);++ const findByFolderIdWithIntegration = async (folderId: string, tx?: Knex) => {+ try {+ return await (tx || db.replicaNode())(TableName.PamFolderNotificationConfig)+ .join(+ TableName.WorkflowIntegrations,+ `${TableName.PamFolderNotificationConfig}.workflowIntegrationId`,+ `${TableName.WorkflowIntegrations}.id`+ )+ .select(selectAllTableCols(TableName.PamFolderNotificationConfig))+ .select(db.ref("integration").withSchema(TableName.WorkflowIntegrations))+ .select(db.ref("slug").withSchema(TableName.WorkflowIntegrations))+ .select(db.ref("status").withSchema(TableName.WorkflowIntegrations))+ .select(db.ref("orgId").withSchema(TableName.WorkflowIntegrations))+ .where(`${TableName.PamFolderNotificationConfig}.folderId`, folderId)+ .orderBy(`${TableName.PamFolderNotificationConfig}.createdAt`, "asc");+ } catch (error) {+ throw new DatabaseError({ error, name: "Find PAM folder notification configs by folder ID" });+ }+ };++ return { ...orm, findByFolderIdWithIntegration };+};diff --git a/backend/src/ee/services/pam/CLAUDE.md b/backend/src/ee/services/pam/CLAUDE.mdindex 7f9c8f2276..a90b54e975 100644--- a/backend/src/ee/services/pam/CLAUDE.md+++ b/backend/src/ee/services/pam/CLAUDE.md@@ -16,6 +16,7 @@ All PAM services live under `backend/src/ee/services/pam-*/`:| `pam-session-recording/` | Recording chunk storage, retrieval, secrets, and storage providers (`aws-s3/`, `postgres/`) || `pam-membership/` | Product + resource membership management || `pam-project/` | PAM project bootstrap and resolver (formerly `pam-instance/`) |+| `pam-access-request/` | Folder approval configuration and access request lifecycle (built on the generic `approval-policy` engine), plus folder-level chat notification configs (`pam-folder-notification-config-dal.ts`, pure filtering helpers in `pam-access-request-fns.ts`) || `pam-web-access/` | WebSocket session handlers (Postgres, SSH, RDP), ticket-based auth |Routes live in `backend/src/ee/routes/v1/pam-routers/`.@@ -166,6 +167,12 @@ Session log masking (`sessionLogMaskingPatterns`) is a **setting**, not a policyNo migration, no router or response-schema change (beyond `policyRules` for gateway-enforced policies), and no DB default.+## Approval Chat Notifications (Slack)++Folder-level, not project-level: each folder's Approvals tab can attach org `workflow_integrations` (Slack only for now) with channels and subscribed events, stored in `pam_folder_notification_configs` (`channels` and `events` are jsonb; channel objects are `{ id, name }` so the UI renders names without needing the org-gated Slack channel-list API). This intentionally does NOT use `project_slack_configs` or `triggerWorkflowIntegrationNotification`, which resolve config by projectId (the single PAM project would make the config org-wide).++Flow: `createRequest` and `reviewRequest` in `pam-access-request-service.ts` call `triggerFolderSlackNotifications`, which filters configs via the pure `getSlackSendTargets` (`pam-access-request-fns.ts`, unit-tested) and sends through the shared `sendSlackNotification` (`services/slack/slack-fns.ts`). Events are `PamNotificationEvent` in `pam/pam-enums.ts` (mirrored in the frontend enums file). New `TriggerFeature.PAM_*` variants carry the payloads; their Slack templates live in `buildSlackPayload`. All sends are fire-and-forget (never fail the request flow). Config writes ride the existing PUT approval-configuration endpoint (undefined `notificationConfigs` leaves configs unchanged; empty array deletes all). Microsoft Teams can be added later by branching on `integration` in the trigger helper, the table needs no change.+## Credential RotationScheduled + on-demand rotation of a SQL account's password. Scoped to Postgres, MySQL, MSSQL. Lives in `pam-account-rotation/`.diff --git a/backend/src/ee/services/pam/pam-enums.ts b/backend/src/ee/services/pam/pam-enums.tsindex 32b25a4026..00eecb7e73 100644--- a/backend/src/ee/services/pam/pam-enums.ts+++ b/backend/src/ee/services/pam/pam-enums.ts@@ -53,3 +53,10 @@ export enum PamMemberKind {Group = "group",Identity = "identity"}++// Events a folder's chat notification config (Slack, later Teams) can subscribe to+export enum PamNotificationEvent {+ AccessRequested = "access-requested",+ AccessRequestApproved = "access-request-approved",+ AccessRequestDenied = "access-request-denied"+}diff --git a/backend/src/lib/workflow-integrations/types.ts b/backend/src/lib/workflow-integrations/types.tsindex 7b68687a41..e155f5c0b2 100644--- a/backend/src/lib/workflow-integrations/types.ts+++ b/backend/src/lib/workflow-integrations/types.ts@@ -8,7 +8,10 @@ export enum TriggerFeature {SECRET_APPROVAL = "secret-approval",ACCESS_REQUEST = "access-request",ACCESS_REQUEST_UPDATED = "access-request-updated",- SECRET_SYNC_ERROR = "secret-sync-error"+ SECRET_SYNC_ERROR = "secret-sync-error",+ PAM_ACCESS_REQUESTED = "pam-access-requested",+ PAM_ACCESS_REQUEST_APPROVED = "pam-access-request-approved",+ PAM_ACCESS_REQUEST_DENIED = "pam-access-request-denied"}export type TNotification =@@ -70,6 +73,29 @@ export type TNotification =projectName: string;projectPath: string;};+ }+ | {+ type: TriggerFeature.PAM_ACCESS_REQUESTED;+ payload: {+ requesterFullName: string;+ requesterEmail: string;+ accountName: string;+ folderName: string;+ accessDuration: string;+ reason?: string;+ approvalUrl: string;+ };+ }+ | {+ type: TriggerFeature.PAM_ACCESS_REQUEST_APPROVED | TriggerFeature.PAM_ACCESS_REQUEST_DENIED;+ payload: {+ requesterFullName: string;+ requesterEmail: string;+ accountName: string;+ folderName: string;+ comment?: string;+ approvalUrl: string;+ };};export type TTriggerWorkflowNotificationDTO = {diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 218550ae98..ba9bbdccba 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -106,6 +106,7 @@ import { oidcConfigDALFactory } from "@app/ee/services/oidc/oidc-config-dal";import { oidcConfigServiceFactory } from "@app/ee/services/oidc/oidc-config-service";import { pamAuditLogScopeResolverFactory } from "@app/ee/services/pam/pam-audit-log-fns";import { pamAccessRequestServiceFactory } from "@app/ee/services/pam-access-request/pam-access-request-service";+import { pamFolderNotificationConfigDALFactory } from "@app/ee/services/pam-access-request/pam-folder-notification-config-dal";import { pamAccountDALFactory } from "@app/ee/services/pam-account/pam-account-dal";import { pamAccountServiceFactory } from "@app/ee/services/pam-account/pam-account-service";import { pamAccountRotationQueueServiceFactory } from "@app/ee/services/pam-account-rotation/pam-account-rotation-queue";@@ -1660,6 +1661,7 @@ export const registerRoutes = async (const pamAccountTemplateDAL = pamAccountTemplateDALFactory(db);const pamFolderDAL = pamFolderDALFactory(db);+ const pamFolderNotificationConfigDAL = pamFolderNotificationConfigDALFactory(db);const pamMembershipService = pamMembershipServiceFactory({membershipDAL,@@ -1837,7 +1839,11 @@ export const registerRoutes = async (smtpService,groupDAL,userGroupMembershipDAL,- userDAL+ userDAL,+ pamFolderNotificationConfigDAL,+ workflowIntegrationDAL,+ slackIntegrationDAL,+ kmsService});const pamFolderService = pamFolderServiceFactory({diff --git a/backend/src/services/slack/slack-fns.ts b/backend/src/services/slack/slack-fns.tsindex eae9f36976..77f2e6c5d0 100644--- a/backend/src/services/slack/slack-fns.ts+++ b/backend/src/services/slack/slack-fns.ts@@ -255,6 +255,113 @@ const buildSlackPayload = (notification: TNotification) => {color: ERROR_COLOR};}+ case TriggerFeature.PAM_ACCESS_REQUESTED: {+ const { payload } = notification;++ const messageBody = `${payload.requesterFullName} (${payload.requesterEmail}) has requested access to ${payload.accountName} in the ${payload.folderName} folder.\n\nDuration: ${payload.accessDuration}${+ payload.reason ? `\n\nReason: ${payload.reason}` : ""+ }`;++ const headerBlocks = [+ {+ type: "header",+ text: {+ type: "plain_text",+ text: "New PAM access request pending review",+ emoji: true+ }+ }+ ];++ const payloadBlocks = [+ {+ type: "section",+ text: {+ type: "mrkdwn",+ text: `*${payload.requesterFullName}* (${payload.requesterEmail}) has requested access to *${payload.accountName}* in the *${payload.folderName}* folder.\n\n*Duration:* ${payload.accessDuration}${+ payload.reason ? `\n\n*Reason:* ${payload.reason}` : ""+ }`+ }+ },+ {+ type: "actions",+ elements: [+ {+ type: "button",+ text: {+ type: "plain_text",+ text: "View request",+ emoji: true+ },+ style: "primary",+ url: payload.approvalUrl+ }+ ]+ }+ ];++ return {+ headerBlocks,+ payloadMessage: messageBody,+ payloadBlocks,+ color: COMPANY_BRAND_COLOR+ };+ }+ case TriggerFeature.PAM_ACCESS_REQUEST_APPROVED:+ case TriggerFeature.PAM_ACCESS_REQUEST_DENIED: {+ const { payload } = notification;+ const isApproved = notification.type === TriggerFeature.PAM_ACCESS_REQUEST_APPROVED;+ const decision = isApproved ? "approved" : "denied";++ const messageBody = `The access request from ${payload.requesterFullName} (${payload.requesterEmail}) for ${payload.accountName} in the ${payload.folderName} folder has been ${decision}.${+ payload.comment ? `\n\nReviewer comment: ${payload.comment}` : ""+ }`;++ const headerBlocks = [+ {+ type: "header",+ text: {+ type: "plain_text",+ text: `PAM access request ${decision}`,+ emoji: true+ }+ }+ ];++ const payloadBlocks = [+ {+ type: "section",+ text: {+ type: "mrkdwn",+ text: `The access request from *${payload.requesterFullName}* (${payload.requesterEmail}) for *${payload.accountName}* in the *${payload.folderName}* folder has been *${decision}*.${+ payload.comment ? `\n\n*Reviewer comment:* ${payload.comment}` : ""+ }`+ }+ },+ {+ type: "actions",+ elements: [+ {+ type: "button",+ text: {+ type: "plain_text",+ text: "View request",+ emoji: true+ },+ style: "primary",+ url: payload.approvalUrl+ }+ ]+ }+ ];++ return {+ headerBlocks,+ payloadMessage: messageBody,+ payloadBlocks,+ color: isApproved ? COMPANY_BRAND_COLOR : ERROR_COLOR+ };+ }default: {throw new BadRequestError({message: "Slack notification type not supported."diff --git a/frontend/src/hooks/api/pam/enums.ts b/frontend/src/hooks/api/pam/enums.tsindex a6dffc002e..3f0444c014 100644--- a/frontend/src/hooks/api/pam/enums.ts+++ b/frontend/src/hooks/api/pam/enums.ts@@ -127,3 +127,10 @@ export enum PamApproverType {User = "user",Group = "group"}++// Mirrors PamNotificationEvent in backend/src/ee/services/pam/pam-enums.ts+export enum PamNotificationEvent {+ AccessRequested = "access-requested",+ AccessRequestApproved = "access-request-approved",+ AccessRequestDenied = "access-request-denied"+}diff --git a/frontend/src/hooks/api/pam/mutations.tsx b/frontend/src/hooks/api/pam/mutations.tsxindex 9bd1cf65c1..6a1b38efa9 100644--- a/frontend/src/hooks/api/pam/mutations.tsx+++ b/frontend/src/hooks/api/pam/mutations.tsx@@ -679,10 +679,10 @@ export const useRevokePamAccessRequest = () => {export const useSetPamApprovalConfig = () => {const queryClient = useQueryClient();return useMutation({- mutationFn: async ({ folderId, steps }: TSetPamApprovalConfigDTO) => {+ mutationFn: async ({ folderId, steps, notificationConfigs }: TSetPamApprovalConfigDTO) => {const { data } = await apiRequest.put(`/api/v1/pam/folders/${folderId}/approval-configuration`,- { steps }+ { steps, notificationConfigs });return data;},diff --git a/frontend/src/hooks/api/pam/types/index.ts b/frontend/src/hooks/api/pam/types/index.tsindex 29ce7c7edb..16cd1c6748 100644--- a/frontend/src/hooks/api/pam/types/index.ts+++ b/frontend/src/hooks/api/pam/types/index.ts@@ -6,6 +6,7 @@ import {PamAccountType,PamAccountView,PamApproverType,+ PamNotificationEvent,PamPolicyType,PamResourcePermissionActions,PamResourcePermissionSub,@@ -540,10 +541,21 @@ export type TPamAccessRequest = {grantStatus?: string | null;};+export type TPamNotificationConfig = {+ workflowIntegrationId: string;+ channels: { id: string; name: string }[];+ events: PamNotificationEvent[];+};+export type TPamApprovalConfig = {steps: {approvers: { type: PamApproverType; id: string }[];}[];+ notificationConfigs: (TPamNotificationConfig & {+ id: string;+ integration: string;+ integrationSlug: string;+ })[];};export type TPamAccessGrant = {@@ -581,4 +593,5 @@ export type TSetPamApprovalConfigDTO = {steps: {approvers: { type: PamApproverType; id: string }[];}[];+ notificationConfigs?: TPamNotificationConfig[];};diff --git a/frontend/src/pages/pam/PamAccountsPage/components/FolderApprovalsTab.tsx b/frontend/src/pages/pam/PamAccountsPage/components/FolderApprovalsTab.tsxindex 09e1a9173d..61d8ed7ee2 100644--- a/frontend/src/pages/pam/PamAccountsPage/components/FolderApprovalsTab.tsx+++ b/frontend/src/pages/pam/PamAccountsPage/components/FolderApprovalsTab.tsx@@ -52,11 +52,12 @@ import {useRevokePamAccessRequest,useSetPamApprovalConfig} from "@app/hooks/api/pam";-import { TPamAccessRequest } from "@app/hooks/api/pam/types";+import { TPamAccessRequest, TPamNotificationConfig } from "@app/hooks/api/pam/types";import { useGetOrgUsers } from "@app/hooks/api/users/queries";import { getRequestStatusInfo, isGrantActive } from "../../components/approvalRequestStatus";import { AccountPlatformIcon } from "../../PamAccessPage/components/AccountPlatformIcon";+import { FolderNotificationsSection } from "./FolderNotificationsSection";type ApproverEntry = { type: PamApproverType; id: string };@@ -133,21 +134,42 @@ export const FolderApprovalsTab = ({ folderId, onDirtyChange }: Props) => {const [approvers, setApprovers] = useState<ApproverEntry[]>([]);const [isDirty, setIsDirty] = useState(false);+ const [notificationConfigs, setNotificationConfigs] = useState<TPamNotificationConfig[]>([]);const savedApprovers = useMemo(() => {if (!config?.steps?.[0]) return [];return config.steps[0].approvers.map((a) => ({ type: a.type, id: a.id }));}, [config]);+ const savedNotificationConfigs = useMemo<TPamNotificationConfig[]>(+ () =>+ (config?.notificationConfigs ?? []).map((c) => ({+ workflowIntegrationId: c.workflowIntegrationId,+ channels: c.channels,+ events: c.events+ })),+ [config]+ );+useEffect(() => {setApprovers(savedApprovers);setIsDirty(false);}, [savedApprovers]);useEffect(() => {- onDirtyChange?.(isDirty);+ setNotificationConfigs(savedNotificationConfigs);+ }, [savedNotificationConfigs]);++ const isNotifDirty = useMemo(+ () => JSON.stringify(notificationConfigs) !== JSON.stringify(savedNotificationConfigs),+ [notificationConfigs, savedNotificationConfigs]+ );+ const isAnyDirty = isDirty || isNotifDirty;++ useEffect(() => {+ onDirtyChange?.(isAnyDirty);return () => onDirtyChange?.(false);- }, [isDirty, onDirtyChange]);+ }, [isAnyDirty, onDirtyChange]);const selectedIds = useMemo(() => new Set(approvers.map((a) => `${a.type}:${a.id}`)),@@ -219,8 +241,19 @@ export const FolderApprovalsTab = ({ folderId, onDirtyChange }: Props) => {};const handleSave = () => {+ const hasIncompleteConfig = notificationConfigs.some(+ (c) => !c.workflowIntegrationId || c.channels.length === 0 || c.events.length === 0+ );+ if (hasIncompleteConfig) {+ createNotification({+ type: "error",+ text: "Each notification needs a Slack workspace, at least one channel, and at least one event"+ });+ return;+ }+setConfig.mutate(- { folderId, steps: [{ approvers }] },+ { folderId, steps: [{ approvers }], notificationConfigs },{onSuccess: () => {createNotification({ type: "success", text: "Approval configuration saved" });@@ -235,6 +268,7 @@ export const FolderApprovalsTab = ({ folderId, onDirtyChange }: Props) => {const handleDiscard = () => {setApprovers(savedApprovers);+ setNotificationConfigs(savedNotificationConfigs);setIsDirty(false);};@@ -335,6 +369,8 @@ export const FolderApprovalsTab = ({ folderId, onDirtyChange }: Props) => {</CardContent></Card>+ <FolderNotificationsSection configs={notificationConfigs} onChange={setNotificationConfigs} />+<Card><CardHeader className="border-b"><CardTitle className="text-base">@@ -477,7 +513,7 @@ export const FolderApprovalsTab = ({ folderId, onDirtyChange }: Props) => {/><div aria-hidden className="h-8 shrink-0" />- {isDirty && (+ {isAnyDirty && (<div className="sticky bottom-0 -mx-4 mt-auto -mb-4 flex items-center justify-end gap-2 border-t border-border bg-popover px-4 py-3"><Button type="button" variant="ghost" onClick={handleDiscard}>Discarddiff --git a/frontend/src/pages/pam/PamAccountsPage/components/FolderNotificationsSection.tsx b/frontend/src/pages/pam/PamAccountsPage/components/FolderNotificationsSection.tsxnew file mode 100644index 0000000000..12ef3fe77d--- /dev/null+++ b/frontend/src/pages/pam/PamAccountsPage/components/FolderNotificationsSection.tsx@@ -0,0 +1,229 @@+import { useMemo } from "react";+import { Plus, Slack, Trash2 } from "lucide-react";++import {+ Badge,+ Button,+ Card,+ CardAction,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+ FilterableSelect,+ IconButton,+ Tooltip,+ TooltipContent,+ TooltipTrigger+} from "@app/components/v3";+import { useOrganization } from "@app/context";+import { useGetSlackIntegrationChannels, useGetWorkflowIntegrations } from "@app/hooks/api";+import { PamNotificationEvent } from "@app/hooks/api/pam";+import { TPamNotificationConfig } from "@app/hooks/api/pam/types";+import {+ WorkflowIntegration,+ WorkflowIntegrationPlatform+} from "@app/hooks/api/workflowIntegrations/types";++const EVENT_OPTIONS: { value: PamNotificationEvent; label: string }[] = [+ { value: PamNotificationEvent.AccessRequested, label: "Access requested" },+ { value: PamNotificationEvent.AccessRequestApproved, label: "Request approved" },+ { value: PamNotificationEvent.AccessRequestDenied, label: "Request denied" }+];++type IntegrationOption = { value: string; label: string };+type ChannelOption = { id: string; name: string };+type EventOption = (typeof EVENT_OPTIONS)[number];++type ConfigCardProps = {+ config: TPamNotificationConfig;+ integrationOptions: IntegrationOption[];+ onChange: (config: TPamNotificationConfig) => void;+ onRemove: () => void;+};++const NotificationConfigCard = ({+ config,+ integrationOptions,+ onChange,+ onRemove+}: ConfigCardProps) => {+ const { data: slackChannels, isError: isChannelListError } = useGetSlackIntegrationChannels(+ config.workflowIntegrationId || undefined+ );++ const channelOptions = useMemo<ChannelOption[]>(+ () =>+ (slackChannels ?? [])+ .slice()+ .sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase())),+ [slackChannels]+ );++ const selectedIntegration =+ integrationOptions.find((opt) => opt.value === config.workflowIntegrationId) ?? null;++ return (+ <div className="flex flex-col gap-4 rounded-md border border-border p-4">+ <div className="flex items-start gap-2">+ <div className="flex-1">+ <FilterableSelect+ value={selectedIntegration}+ options={integrationOptions}+ onChange={(opt) => {+ const next = opt as IntegrationOption | null;+ if (!next || next.value === config.workflowIntegrationId) return;+ // channels belong to the previous workspace, so a workspace change clears them+ onChange({ ...config, workflowIntegrationId: next.value, channels: [] });+ }}+ getOptionValue={(opt) => opt.value}+ getOptionLabel={(opt) => opt.label}+ placeholder="Select a Slack workspace..."+ />+ </div>+ <Tooltip>+ <TooltipTrigger asChild>+ <IconButton+ variant="ghost"+ aria-label="Remove notification config"+ className="text-muted hover:text-danger"+ onClick={onRemove}+ >+ <Trash2 className="size-4" />+ </IconButton>+ </TooltipTrigger>+ <TooltipContent>Remove</TooltipContent>+ </Tooltip>+ </div>++ {config.workflowIntegrationId && (+ <>+ <div className="flex flex-col gap-1.5">+ <span className="text-sm font-medium">Slack channels</span>+ <FilterableSelect+ isMulti+ value={config.channels}+ options={channelOptions}+ onChange={(selected) => {+ const channels = (selected as ChannelOption[] | null) ?? [];+ onChange({ ...config, channels: channels.map(({ id, name }) => ({ id, name })) });+ }}+ getOptionValue={(opt) => opt.id}+ getOptionLabel={(opt) => `#${opt.name}`}+ placeholder="Add Slack channel..."+ noOptionsMessage={() =>+ "No channels found. Invite the Infisical Slack app to private channels to list them here."+ }+ />+ {isChannelListError && (+ <p className="text-xs text-muted">+ Saved channels are shown, but listing Slack channels requires permission to read+ organization settings.+ </p>+ )}+ </div>++ <div className="flex flex-col gap-1.5">+ <span className="text-sm font-medium">Notify on</span>+ <FilterableSelect+ isMulti+ value={EVENT_OPTIONS.filter((opt) => config.events.includes(opt.value))}+ options={EVENT_OPTIONS}+ onChange={(selected) => {+ const events = ((selected as EventOption[] | null) ?? []).map((opt) => opt.value);+ onChange({ ...config, events });+ }}+ getOptionValue={(opt) => opt.value}+ getOptionLabel={(opt) => opt.label}+ placeholder="Add event..."+ />+ </div>+ </>+ )}+ </div>+ );+};++type Props = {+ configs: TPamNotificationConfig[];+ onChange: (configs: TPamNotificationConfig[]) => void;+};++export const FolderNotificationsSection = ({ configs, onChange }: Props) => {+ const { currentOrg } = useOrganization();+ const { data: workflowIntegrations } = useGetWorkflowIntegrations(currentOrg.id);++ const integrationOptions = useMemo<IntegrationOption[]>(+ () =>+ (workflowIntegrations ?? [])+ .filter(+ (integration: WorkflowIntegration) =>+ integration.integration === WorkflowIntegrationPlatform.SLACK+ )+ .map((integration) => ({ value: integration.id, label: integration.slug })),+ [workflowIntegrations]+ );++ const addConfig = () => {+ onChange([...configs, { workflowIntegrationId: "", channels: [], events: [] }]);+ };++ return (+ <Card>+ <CardHeader className="border-b">+ <CardTitle className="text-base">+ Notifications+ <Badge variant="pam">{configs.length}</Badge>+ </CardTitle>+ <CardDescription>+ Approvers always get in-app and email notifications. Add Slack to also post to a channel.+ </CardDescription>+ <CardAction>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button variant="outline" size="sm">+ <Plus className="size-4" />+ Add+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" sideOffset={2}>+ <DropdownMenuItem onSelect={addConfig}>+ <Slack className="size-4" />+ Slack+ </DropdownMenuItem>+ <DropdownMenuItem disabled>Microsoft Teams (coming soon)</DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </CardAction>+ </CardHeader>+ <CardContent className="flex flex-col gap-4">+ {configs.length === 0 ? (+ <div className="rounded-md border border-border p-8 text-center text-sm text-muted">+ No chat notifications configured.+ </div>+ ) : (+ configs.map((config, idx) => (+ <NotificationConfigCard+ // eslint-disable-next-line react/no-array-index-key+ key={idx}+ config={config}+ integrationOptions={integrationOptions}+ onChange={(next) => onChange(configs.map((c, i) => (i === idx ? next : c)))}+ onRemove={() => onChange(configs.filter((_, i) => i !== idx))}+ />+ ))+ )}+ {integrationOptions.length === 0 && (+ <p className="text-xs text-muted">+ No Slack workflow integrations are connected to this organization yet. Add one under+ Organization Settings, Workflow Integrations.+ </p>+ )}+ </CardContent>+ </Card>+ );+};