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
improvement(pam): move to global approvals
Andreya07bb5c5e5c9
diff --git a/CLAUDE.md b/CLAUDE.mdindex ce44ac8c5c..31f070540d 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -122,6 +122,23 @@ All user-facing "notify me when X happens" features share one module: `backend/s**If you touch a code path that deletes or detaches an alertable resource, it must reap that resource's alerts.** `alerts.resourceId` has no foreign key, so nothing cascades and the alert is left dangling. Use `alertService.deleteAlertsForDeletedResource` when the row is gone (unscoped, reaps across every org) and `deleteAlertsForResource` when the resource only left a scope. See the alerting invariants in `backend/CLAUDE.md`.+### Approvals++All "someone has to approve this before it happens" features share one module:+`backend/src/services/approval-policy/`, which owns policies, requests, steps, grants, break-glass, and+the generic `/v1/<policy-type>/approval-policies` endpoints. Current types: PAM access, certificate+requests, code signing.++A policy type plugs in through **one** extension point, a `TApprovalResource` (see its doc comment),+constructed with its own dependencies and registered in the `approvalResources` map in+`server/routes/index.ts`; that also gives it the generic `/v1/approval-policies/<type>/...` endpoints,+which every type now uses for policy CRUD, requests, approve, reject and grant revocation. **Do not stand up a per-product approval service, request table, or review+endpoint**: `access-approval-*` and `secret-approval-*` predate this module and are what we are+converging away from. A product-facing service on top of it (PAM's `pam-access-request-service.ts`) is+for product vocabulary only: resolving the resource a request names, notifications, and read models.+Any rule about what is *allowed* belongs in the resource, or the product's own API and the shared API+stop agreeing.+### API Layer (Frontend)React Query + Axios with query key factories per domain. Each API domain in `frontend/src/hooks/api/` has `queries.tsx`, `mutations.tsx`, and `types.tsx` — see `frontend/CLAUDE.md` for conventions.diff --git a/backend/src/ee/routes/v1/pam-routers/pam-access-request-router.ts b/backend/src/ee/routes/v1/pam-routers/pam-access-request-router.tsindex 36a122b531..30a72fa05d 100644--- a/backend/src/ee/routes/v1/pam-routers/pam-access-request-router.ts+++ b/backend/src/ee/routes/v1/pam-routers/pam-access-request-router.ts@@ -6,11 +6,8 @@ import { PamAccessType } from "@app/ee/services/pam/pam-enums";import { readLimit, writeLimit } from "@app/server/config/rateLimiter";import { getTelemetryDistinctId } from "@app/server/lib/telemetry";import { verifyAuth } from "@app/server/plugins/auth/verify-auth";-import {- ApprovalPolicyType,- ApprovalRequestApprovalDecision,- ApproverType-} from "@app/services/approval-policy/approval-policy-enums";+import { ApprovalPolicyType, ApproverType } from "@app/services/approval-policy/approval-policy-enums";+import { parsePamAccessDuration } from "@app/services/approval-policy/pam-access/pam-access-policy-fns";import { AuthMode } from "@app/services/auth/auth-type";import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";@@ -19,6 +16,7 @@ const EnrichedRequestSchema = ApprovalRequestsSchema.extend({accountType: z.string().nullable(),folderName: z.string().nullable(),accessType: z.nativeEnum(PamAccessType),+ grantId: z.string().uuid().nullable(),grantExpiresAt: z.date().nullable(),grantStatus: z.string().nullable(),isBreakGlass: z.boolean(),@@ -36,7 +34,14 @@ export const registerPamAccessRequestRouter = async (server: FastifyZodProvider)accountId: z.string().uuid().optional(),path: z.string().min(3).optional().describe("Account path in the format 'folderName/accountName'"),reason: z.string().max(500).optional(),- duration: z.string().min(1),+ duration: z+ .string()+ .trim()+ .min(1)+ .max(32)+ .refine((val) => parsePamAccessDuration(val) !== null, {+ message: "Invalid access duration. Use a single unit like '30m', '2h', or '1d'"+ }),accessType: z.nativeEnum(PamAccessType).default(PamAccessType.Session)@@ -266,211 +271,4 @@ export const registerPamAccessRequestRouter = async (server: FastifyZodProvider)return result;}});-- server.route({- method: "POST",- url: "/:requestId/review",- config: { rateLimit: writeLimit },- schema: {- params: z.object({- requestId: z.string().uuid()- }),- body: z.object({- status: z.nativeEnum(ApprovalRequestApprovalDecision),- comment: z.string().max(500).optional()- }),- response: {- 200: z.object({- request: ApprovalRequestsSchema- })- }- },- onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),- handler: async (req) => {- const result = await server.services.pamAccessRequest.reviewRequest({- requestId: req.params.requestId,- projectId: req.internalPamProjectId,- status: req.body.status,- comment: req.body.comment,- actorId: req.permission.id,- actor: req.permission.type,- actorOrgId: req.permission.orgId,- actorAuthMethod: req.permission.authMethod- });-- await server.services.auditLog.createAuditLog({- ...req.auditLogInfo,- orgId: req.permission.orgId,- projectId: req.internalPamProjectId,- event: {- type: EventType.PAM_ACCESS_REQUEST_REVIEW,- metadata: {- requestId: req.params.requestId,- accountId: result.accountId,- folderId: result.folderId,- status: req.body.status,- comment: req.body.comment- }- }- });-- void server.services.telemetry- .sendPostHogEvents({- event: PostHogEventTypes.PamAccessRequestReviewed,- distinctId: getTelemetryDistinctId(req),- organizationId: req.permission.orgId,- properties: {- orgId: req.permission.orgId,- status: req.body.status- }- })- .catch(() => {});-- return { request: result.request };- }- });-- server.route({- method: "POST",- url: "/:requestId/break-glass",- config: { rateLimit: writeLimit },- schema: {- operationId: "breakGlassPamAccessRequest",- description: "Self-approve your own pending PAM access request in an emergency",- params: z.object({- requestId: z.string().uuid()- }),- body: z.object({- bypassReason: z- .string()- .trim()- .min(10)- .max(500)- .describe("Why the approvers are being skipped. Recorded in the audit log and sent to them.")- }),- response: {- 200: z.object({- request: ApprovalRequestsSchema- })- }- },- onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),- handler: async (req) => {- const result = await server.services.pamAccessRequest.breakGlassRequest({- requestId: req.params.requestId,- projectId: req.internalPamProjectId,- bypassReason: req.body.bypassReason,- actorId: req.permission.id,- actor: req.permission.type,- actorOrgId: req.permission.orgId,- actorAuthMethod: req.permission.authMethod- });-- await server.services.auditLog.createAuditLog({- ...req.auditLogInfo,- orgId: req.permission.orgId,- projectId: req.internalPamProjectId,- event: {- type: EventType.PAM_ACCESS_POLICY_BYPASSED,- metadata: {- policyType: ApprovalPolicyType.PamAccess,- policyId: result.policyId,- policyName: result.policyName,- requestId: req.params.requestId,- grantId: result.grantId,- granteeUserId: req.permission.id,- granteeName: result.granteeName ?? undefined,- granteeEmail: result.granteeEmail ?? undefined,- accountId: result.accountId,- folderId: result.folderId,- folderName: result.folderName ?? undefined,- resourceName: result.folderName ?? undefined,- accountName: result.accountName,- accessDuration: result.accessDuration,- bypassReason: req.body.bypassReason,- approverCount: result.approverCount- }- }- });-- void server.services.telemetry- .sendPostHogEvents({- event: PostHogEventTypes.PamAccessRequestBrokeGlass,- distinctId: getTelemetryDistinctId(req),- organizationId: req.permission.orgId,- properties: {- accountType: result.accountType,- orgId: req.permission.orgId- }- })- .catch(() => {});-- return { request: result.request };- }- });-- server.route({- method: "POST",- url: "/:requestId/revoke",- config: { rateLimit: writeLimit },- schema: {- params: z.object({- requestId: z.string().uuid()- }),- response: {- 200: z.object({- grant: z.object({- id: z.string().uuid(),- status: z.string(),- revokedAt: z.date().nullable()- })- })- }- },- onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),- handler: async (req) => {- const result = await server.services.pamAccessRequest.revokeGrant({- requestId: req.params.requestId,- projectId: req.internalPamProjectId,- actorId: req.permission.id,- actor: req.permission.type,- actorOrgId: req.permission.orgId,- actorAuthMethod: req.permission.authMethod- });-- await server.services.auditLog.createAuditLog({- ...req.auditLogInfo,- orgId: req.permission.orgId,- projectId: req.internalPamProjectId,- event: {- type: EventType.PAM_ACCESS_GRANT_REVOKE,- metadata: {- requestId: req.params.requestId,- grantId: result.grant.id,- accountId: result.accountId,- folderId: result.folderId- }- }- });-- void server.services.telemetry- .sendPostHogEvents({- event: PostHogEventTypes.PamAccessGrantRevoked,- distinctId: getTelemetryDistinctId(req),- organizationId: req.permission.orgId,- properties: {- orgId: req.permission.orgId- }- })- .catch(() => {});-- return {- grant: {- id: result.grant.id,- status: result.grant.status,- revokedAt: result.grant.revokedAt ?? null- }- };- }- });};diff --git a/backend/src/ee/routes/v1/pam-routers/pam-account-router.ts b/backend/src/ee/routes/v1/pam-routers/pam-account-router.tsindex 7d0a8995c5..8b6c034d38 100644--- a/backend/src/ee/routes/v1/pam-routers/pam-account-router.ts+++ b/backend/src/ee/routes/v1/pam-routers/pam-account-router.ts@@ -2,7 +2,7 @@ import z from "zod";import { PamAccountsSchema } from "@app/db/schemas";import { EventType } from "@app/ee/services/audit-log/audit-log-types";-import { PamAccessStatus, PamAccountType, PamHeartbeatStatus } from "@app/ee/services/pam/pam-enums";+import { PamAccountType, PamHeartbeatStatus } from "@app/ee/services/pam/pam-enums";import {ACCOUNT_TYPE_CONFIGS,buildPamAccountTypeMetadata,@@ -25,6 +25,7 @@ import { getTelemetryDistinctId } from "@app/server/lib/telemetry";import { withRoutePrefix } from "@app/server/lib/with-route-prefix";import { isUserSessionAuth } from "@app/server/plugins/auth/inject-identity";import { verifyAuth } from "@app/server/plugins/auth/verify-auth";+import { ApprovalAccessStatus } from "@app/services/approval-policy/approval-policy-types";import { AuthMode } from "@app/services/auth/auth-type";import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";@@ -68,12 +69,14 @@ const PamAccountListItemSchema = SanitizedAccountListItemSchema.extend({.describe("Whether the account's template has scheduled credential health checks turned on."),requiresApproval: z.boolean().describe("Whether this account requires approval before launching a session"),requireReason: z.boolean().describe("Whether the account's template requires a reason for access"),- accessStatus: z.nativeEnum(PamAccessStatus).describe("Current approval status for the caller"),+ accessStatus: z.nativeEnum(ApprovalAccessStatus).describe("Current approval status for the caller"),grantExpiresAt: z.date().nullable().describe("When the current grant expires, if granted"),pendingRequestId: z.string().nullable().describe("The caller's pending access request for this account, if any"),canBreakGlass: z.boolean().describe("Whether the caller may self-approve their own pending request for this account"),supportsCredentialReveal: z.boolean().describe("Whether this account type stores a credential that can be revealed"),- credentialAccessStatus: z.nativeEnum(PamAccessStatus).describe("Current credential-approval status for the caller"),+ credentialAccessStatus: z+ .nativeEnum(ApprovalAccessStatus)+ .describe("Current credential-approval status for the caller"),credentialPendingRequestId: z.string().nullable()@@ -451,7 +454,7 @@ export const registerPamAccountRouter = async (server: FastifyZodProvider) => {.describe("Whether launching a session for this account requires MFA verification. Machine identities cannot satisfy MFA, so launch is rejected for them when this is true."),- accessStatus: z.nativeEnum(PamAccessStatus).describe("Current approval status for the caller"),+ accessStatus: z.nativeEnum(ApprovalAccessStatus).describe("Current approval status for the caller"),grantExpiresAt: z.date().nullable().describe("When the current grant expires, if granted"),pendingRequestId: z.string()diff --git a/backend/src/ee/services/pam-access-request/pam-access-approval-resource.test.ts b/backend/src/ee/services/pam-access-request/pam-access-approval-resource.test.tsnew file mode 100644index 0000000000..42dc2b6952--- /dev/null+++ b/backend/src/ee/services/pam-access-request/pam-access-approval-resource.test.ts@@ -0,0 +1,60 @@+import { ApprovalPolicyType } from "@app/services/approval-policy/approval-policy-enums";+import { TPamAccessPolicy } from "@app/services/approval-policy/pam-access/pam-access-policy-types";++import { pamAccessApprovalResourceFactory } from "./pam-access-approval-resource";+import { TPamAccessRequestData } from "./pam-access-request-types";++const ACCOUNT_ID = "6cb4b2fa-1a9f-4b31-9f2d-6f3f5f9d4a11";+const FOLDER_ID = "9f8e7d6c-5b4a-4938-8271-6a5b4c3d2e33";++const buildResource = (approvalPolicyDAL: unknown) => pamAccessApprovalResourceFactory({ approvalPolicyDAL } as never);++describe("pam access resource: validateConstraints", () => {+ const { validateConstraints } = buildResource({});++ const policy = {+ constraints: { version: 1, constraints: { accessDuration: { min: "30m", max: "8h" } } }+ } as TPamAccessPolicy;++ const requestData = (duration: string) =>+ ({ accountId: ACCOUNT_ID, folderId: FOLDER_ID, duration }) as TPamAccessRequestData;++ test("accepts a duration inside the policy's window", () => {+ expect(validateConstraints(policy, requestData("2h"))).toEqual({ valid: true, errors: undefined });+ });++ test("names the bound a duration missed", () => {+ expect(validateConstraints(policy, requestData("5m")).errors).toEqual(["Access duration must be at least 30m"]);+ expect(validateConstraints(policy, requestData("2d")).errors).toEqual(["Access duration must be at most 8h"]);+ });++ test("reports an unparseable duration rather than comparing NaN", () => {+ const result = validateConstraints(policy, requestData("2h30m"));+ expect(result.valid).toBe(false);+ expect(result.errors?.[0]).toContain("Invalid access duration '2h30m'");+ });+});++describe("pam access resource: matchPolicy", () => {+ test("looks the policy up by the folder the account sits in", async () => {+ const policy = { id: "policy" };+ const findByProjectId = vi.fn().mockResolvedValue([policy]);++ const matched = await buildResource({ findByProjectId }).matchPolicy("project", {+ accountId: ACCOUNT_ID,+ folderId: FOLDER_ID+ });++ expect(matched).toBe(policy);+ expect(findByProjectId).toHaveBeenCalledWith(ApprovalPolicyType.PamAccess, "project", {+ scopeType: "pam-folder",+ scopeId: FOLDER_ID+ });+ });++ test("returns null for a folder with no policy", async () => {+ const resource = buildResource({ findByProjectId: vi.fn().mockResolvedValue([]) });++ await expect(resource.matchPolicy("project", { accountId: ACCOUNT_ID, folderId: FOLDER_ID })).resolves.toBeNull();+ });+});diff --git a/backend/src/ee/services/pam-access-request/pam-access-approval-resource.ts b/backend/src/ee/services/pam-access-request/pam-access-approval-resource.tsnew file mode 100644index 0000000000..ee4f49cd0c--- /dev/null+++ b/backend/src/ee/services/pam-access-request/pam-access-approval-resource.ts@@ -0,0 +1,964 @@+import { Knex } from "knex";++import { RESOURCE_SCOPE, ResourceType, TApprovalRequestGrants, TApprovalRequests } from "@app/db/schemas";+import { EventType } from "@app/ee/services/audit-log/audit-log-types";+import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";+import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";+import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";+import {+ ResourcePermissionApprovalPolicyActions,+ ResourcePermissionPamResourceActions,+ ResourcePermissionSub+} from "@app/ee/services/permission/resource-permission";+import { getConfig } from "@app/lib/config/env";+import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";+import { formatDuration, ms } from "@app/lib/ms";+import { TriggerFeature } from "@app/lib/workflow-integrations/types";+import { TApprovalPolicyDALFactory } from "@app/services/approval-policy/approval-policy-dal";+import {+ ApprovalAuditAction,+ ApprovalNotificationEvent,+ ApprovalPolicyScope,+ ApprovalPolicyType,+ ApprovalRequestApprovalDecision,+ ApprovalRequestGrantStatus,+ ApprovalRequestStatus,+ ApproverType+} from "@app/services/approval-policy/approval-policy-enums";+import { PolicyBypasser, TApprovalActor, TApprovalResource } from "@app/services/approval-policy/approval-policy-types";+import {+ TApprovalRequestDALFactory,+ TApprovalRequestGrantsDALFactory+} from "@app/services/approval-policy/approval-request-dal";+import {+ matchesPamAccessSubject,+ matchPamAccessGrants,+ PAM_DEFAULT_ACCESS_TYPE,+ parsePamAccessDuration+} from "@app/services/approval-policy/pam-access/pam-access-policy-fns";+import {+ TPamAccessPolicy,+ TPamAccessPolicyInputs+} from "@app/services/approval-policy/pam-access/pam-access-policy-types";+import { ActorType } from "@app/services/auth/auth-type";+import { TKmsServiceFactory } from "@app/services/kms/kms-service";+import { KmsDataKey } from "@app/services/kms/kms-types";+import { TMembershipDALFactory } from "@app/services/membership/membership-dal";+import { TMembershipRoleDALFactory } from "@app/services/membership/membership-role-dal";+import { NotificationType } from "@app/services/notification/notification-types";+import { SmtpTemplates } from "@app/services/smtp/smtp-service";+import { TUserDALFactory } from "@app/services/user/user-dal";++import {+ PamAccessType,+ PamAccountType,+ PamNotificationEvent,+ PamProductRole,+ PamSessionStatus+} from "../pam/pam-enums";+import {+ checkAccountAccess,+ checkFolderPermission,+ TActorContext,+ verifyProductMembership+} from "../pam/pam-permission";+import { resolveAccessControls } from "../pam/pam-policies";+import { TPamAccountDALFactory } from "../pam-account/pam-account-dal";+import {+ hasRevealableCredential,+ noRevealableCredentialMessage,+ normalizeCredentialAuthMethod+} from "../pam-account/pam-account-schemas";+import { TPamAccountTemplateDALFactory } from "../pam-account-template/pam-account-template-dal";+import { TPamFolderDALFactory } from "../pam-folder/pam-folder-dal";+import { TPamSessionDALFactory } from "../pam-session/pam-session-dal";+import { terminatePamSessions } from "../pam-session/pam-session-fns";+import { escapeMarkdown, getSlackSendTargets } from "./pam-access-request-fns";+import { TPamAccessRequestData } from "./pam-access-request-types";+import { TPamFolderNotificationConfigDALFactory } from "./pam-folder-notification-config-dal";++type TPamAccessApprovalResourceDep = {+ approvalPolicyDAL: Pick<+ TApprovalPolicyDALFactory,+ "findStepsByPolicyId" | "findByProjectId" | "findBypassersByPolicyId" | "findById"+ >;+ userGroupMembershipDAL: Pick<TUserGroupMembershipDALFactory, "findGroupMembershipsByUserIdInOrg">;+ approvalRequestDAL: Pick<TApprovalRequestDALFactory, "find">;+ approvalRequestGrantsDAL: Pick<TApprovalRequestGrantsDALFactory, "find" | "create" | "updateById">;+ pamAccountDAL: Pick<TPamAccountDALFactory, "findByIdWithDetails" | "find">;+ pamAccountTemplateDAL: Pick<TPamAccountTemplateDALFactory, "find">;+ pamFolderDAL: Pick<TPamFolderDALFactory, "findById" | "find">;+ pamSessionDAL: Pick<TPamSessionDALFactory, "find" | "update">;+ membershipDAL: Pick<TMembershipDALFactory, "find">;+ membershipRoleDAL: Pick<TMembershipRoleDALFactory, "find">;+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getResourcePermission">;+ userDAL: Pick<TUserDALFactory, "findById">;+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPAMConnectionDetails">;+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;+ licenseService: Pick<TLicenseServiceFactory, "getPlan">;+ pamFolderNotificationConfigDAL: Pick<TPamFolderNotificationConfigDALFactory, "findByFolderIdWithIntegration">;+};++type TPamRequestDecoration = {+ accountName: string | null;+ accountType: string | null;+ folderName: string | null;+ accessType: PamAccessType;+};++export type TPamAccessApprovalResource = TApprovalResource<+ TPamAccessPolicyInputs,+ TPamAccessPolicy,+ TPamAccessRequestData+> & {+ assertBreakGlassEligible: (args: { request: TApprovalRequests; actor: TApprovalActor }) => Promise<void>;+ decorateRequests: <T extends { requestData?: unknown }>(requests: T[]) => Promise<(T & TPamRequestDecoration)[]>;+ findActiveFolderMemberships: (+ projectId: string,+ folderId: string+ ) => Promise<Awaited<ReturnType<TMembershipDALFactory["find"]>>>;+ revokeGrantRow: (+ grant: TApprovalRequestGrants,+ actorId: string,+ reason: string,+ tx?: Knex+ ) => Promise<{ revoked: TApprovalRequestGrants; sendCancellationSignals: () => void }>;+};++const toActorContext = (actor: TApprovalActor): TActorContext => ({+ actorId: actor.id,+ actor: actor.type,+ actorOrgId: actor.orgId,+ actorAuthMethod: actor.authMethod+});++type TBreakGlassArgs = {+ request: TApprovalRequests;+ bypassers: PolicyBypasser[];+ actor: TApprovalActor;+ userGroupIds: Set<string>;+};++const requestDataOf = (request: { requestData?: unknown }) =>+ (request.requestData as { version: number; requestData: TPamAccessRequestData } | null)?.requestData ?? null;++// Everything PAM-specific about its approvals; the lifecycle itself lives in approval-policy-service+export const pamAccessApprovalResourceFactory = ({+ approvalPolicyDAL,+ userGroupMembershipDAL,+ approvalRequestDAL,+ approvalRequestGrantsDAL,+ pamAccountDAL,+ pamAccountTemplateDAL,+ pamFolderDAL,+ pamSessionDAL,+ membershipDAL,+ membershipRoleDAL,+ permissionService,+ userDAL,+ gatewayV2Service,+ kmsService,+ licenseService,+ pamFolderNotificationConfigDAL+}: TPamAccessApprovalResourceDep): TPamAccessApprovalResource => {+ const $assertFolderInProject = async (folderId: string, projectId: string) => {+ const folder = await pamFolderDAL.findById(folderId);+ if (!folder || folder.projectId !== projectId) {+ throw new NotFoundError({ message: "Folder not found" });+ }+ return folder;+ };++ // Temporary membership expiry is enforced lazily (rows are not deleted when access lapses), so+ // approver eligibility must filter to memberships that still carry an active role.+ const findActiveFolderMemberships = async (projectId: string, folderId: string) => {+ const memberships = await membershipDAL.find({+ scope: RESOURCE_SCOPE,+ scopeProjectId: projectId,+ scopeResourceType: ResourceType.PamFolder,+ scopeResourceId: folderId+ });+ if (!memberships.length) return [];++ const roles = await membershipRoleDAL.find({ $in: { membershipId: memberships.map((m) => m.id) } });+ const now = new Date();+ const isWithinTemporaryWindow = (r: (typeof roles)[number]) =>+ Boolean(r.temporaryAccessEndTime) &&+ now < new Date(r.temporaryAccessEndTime as Date) &&+ (!r.temporaryAccessStartTime || now >= new Date(r.temporaryAccessStartTime));+ const activeMembershipIds = new Set(+ roles.filter((r) => !r.isTemporary || isWithinTemporaryWindow(r)).map((r) => r.membershipId)+ );+ return memberships.filter((m) => m.isActive && activeMembershipIds.has(m.id));+ };++ const $holdsActiveFolderMembership = async (+ projectId: string,+ folderId: string,+ userId: string,+ userGroupIds: Set<string>+ ) => {+ const memberships = await findActiveFolderMemberships(projectId, folderId);+ return memberships.some((m) => m.actorUserId === userId || (m.actorGroupId && userGroupIds.has(m.actorGroupId)));+ };++ const $namesActor = (entries: { type: string; id: string }[], userId: string, userGroupIds: Set<string>) =>+ entries.some(+ (entry) =>+ (entry.type === ApproverType.User && entry.id === userId) ||+ (entry.type === ApproverType.Group && userGroupIds.has(entry.id))+ );++ const $findFolderPolicy = async (projectId: string, folderId: string) => {+ const policies = await approvalPolicyDAL.findByProjectId(ApprovalPolicyType.PamAccess, projectId, {+ scopeType: ApprovalPolicyScope.PamFolder,+ scopeId: folderId+ });+ return policies[0] ?? null;+ };++ const matchPolicy: TPamAccessApprovalResource["matchPolicy"] = async (projectId, inputs) => {+ if (!inputs.folderId) return null;+ return ((await $findFolderPolicy(projectId, inputs.folderId)) as TPamAccessPolicy) ?? null;+ };++ // An actor id is unique across both grantee columns, so querying each cannot cross-match.+ const canAccess: TPamAccessApprovalResource["canAccess"] = async (projectId, actorId, inputs) => {+ const [userGrants, identityGrants] = await Promise.all([+ approvalRequestGrantsDAL.find({+ granteeUserId: actorId,+ type: ApprovalPolicyType.PamAccess,+ status: ApprovalRequestGrantStatus.Active,+ projectId,+ revokedAt: null+ }),+ approvalRequestGrantsDAL.find({+ granteeMachineIdentityId: actorId,+ type: ApprovalPolicyType.PamAccess,+ status: ApprovalRequestGrantStatus.Active,+ projectId,+ revokedAt: null+ })+ ]);++ const now = new Date();+ return (+ matchPamAccessGrants([...userGrants, ...identityGrants], inputs).find(+ (grant) => !grant.expiresAt || new Date(grant.expiresAt) > now+ ) ?? null+ );+ };++ const matchesInputs: NonNullable<TPamAccessApprovalResource["matchesInputs"]> = (payload, inputs) =>+ matchesPamAccessSubject(payload, inputs as TPamAccessPolicyInputs);++ const validateConstraints: TPamAccessApprovalResource["validateConstraints"] = (policy, requestData) => {+ const requestedMs = parsePamAccessDuration(requestData.duration);+ if (requestedMs === null) {+ return {+ valid: false,+ errors: [`Invalid access duration '${requestData.duration}'. Use a single unit like '30m', '2h', or '1d'`]+ };+ }++ const { min, max } = policy.constraints.constraints.accessDuration;+ const errors: string[] = [];+ if (requestedMs < ms(min)) errors.push(`Access duration must be at least ${min}`);+ if (requestedMs > ms(max)) errors.push(`Access duration must be at most ${max}`);++ return { valid: errors.length === 0, errors: errors.length > 0 ? errors : undefined };+ };++ const postApprovalTxRoutine: NonNullable<TPamAccessApprovalResource["postApprovalTxRoutine"]> = async (+ request,+ tx,+ breakGlass+ ) => {+ const inputs = request.requestData.requestData as TPamAccessRequestData;+ const durationMs = parsePamAccessDuration(inputs.duration);++ const grant = await approvalRequestGrantsDAL.create(+ {+ projectId: request.projectId,+ requestId: request.id,+ // The request attributes its requester to exactly one column; mirror it onto the grant+ granteeUserId: request.requesterId,+ granteeMachineIdentityId: request.machineIdentityId,+ status: ApprovalRequestGrantStatus.Active,+ type: request.type,+ attributes: {+ accountId: inputs.accountId,+ folderId: inputs.folderId,+ accessType: inputs.accessType ?? PAM_DEFAULT_ACCESS_TYPE+ },+ expiresAt: durationMs === null ? null : new Date(Date.now() + durationMs),+ isBreakGlass: Boolean(breakGlass),+ bypassReason: breakGlass?.bypassReason ?? null+ },+ tx+ );++ return { grantId: grant.id };+ };++ const resolveScope = async (folderId: string) => {+ const folder = await pamFolderDAL.findById(folderId);+ if (!folder) {+ throw new NotFoundError({ message: "Folder not found" });+ }+ return { projectId: folder.projectId };+ };++ const assertCanManagePolicy: NonNullable<TPamAccessApprovalResource["assertCanManagePolicy"]> = async ({+ projectId,+ scopeId,+ actor,+ action+ }) => {+ if (!scopeId) {+ throw new BadRequestError({ message: "PAM approval policies must be scoped to a folder" });+ }++ const ctx = toActorContext(actor);+ await verifyProductMembership(permissionService, projectId, ctx);+ await $assertFolderInProject(scopeId, projectId);++ const { permission } = await checkFolderPermission(permissionService, scopeId, projectId, ctx);+ const canManage = permission.can(+ ResourcePermissionPamResourceActions.ManagePolicies,+ ResourcePermissionSub.PamResource+ );++ if (canManage) return;++ const isRead = action === ResourcePermissionApprovalPolicyActions.Read;+ const canAudit = permission.can(+ ResourcePermissionPamResourceActions.ViewAuditLogs,+ ResourcePermissionSub.PamResource+ );+ if (isRead && canAudit) return;++ throw new ForbiddenRequestError({+ message: isRead+ ? "You are not authorized to view this folder's approval configuration"+ : "You are not authorized to manage this folder's approval configuration"+ });+ };++ const verifyPolicyActors: NonNullable<TPamAccessApprovalResource["verifyPolicyActors"]> = async ({+ projectId,+ scopeId,+ approvers,+ bypassers+ }) => {+ if (!scopeId || (approvers.length === 0 && bypassers.length === 0)) return;++ const memberships = await findActiveFolderMemberships(projectId, scopeId);+ const memberUserIds = new Set(memberships.map((m) => m.actorUserId).filter(Boolean));+ const memberGroupIds = new Set(memberships.map((m) => m.actorGroupId).filter(Boolean));+ const isFolderMember = (entry: PolicyBypasser) =>+ entry.type === ApproverType.User ? memberUserIds.has(entry.id) : memberGroupIds.has(entry.id);++ if (approvers.some((approver) => !isFolderMember(approver))) {+ throw new BadRequestError({ message: "Approvers must be members of the folder" });+ }++ if (bypassers.some((bypasser) => !isFolderMember(bypasser))) {+ throw new BadRequestError({ message: "Break-glass users must be members of the folder" });+ }+ };++ const assertCanCreateRequest: NonNullable<TPamAccessApprovalResource["assertCanCreateRequest"]> = async ({+ projectId,+ policy,+ requestData,+ actor+ }) => {+ const inputs = requestData as TPamAccessRequestData;+ const ctx = toActorContext(actor);+ const isCredentialRequest = inputs.accessType === PamAccessType.Credential;++ await verifyProductMembership(permissionService, projectId, ctx);++ const account = await pamAccountDAL.findByIdWithDetails(inputs.accountId);+ if (!account || account.projectId !== projectId || account.folderId !== inputs.folderId) {+ throw new NotFoundError({ message: "Account not found" });+ }++ // Approval is a layer on top of standing access: only users who already hold the underlying+ // permission may request the temporary grant that unlocks it.+ await checkAccountAccess(+ permissionService,+ account.id,+ account.folderId,+ projectId,+ isCredentialRequest+ ? ResourcePermissionPamResourceActions.ViewCredentials+ : ResourcePermissionPamResourceActions.LaunchSessions,+ ctx+ );++ const accessControls = resolveAccessControls(account.templatePolicies);+ if (!accessControls.requiresApproval) {+ throw new BadRequestError({+ message: isCredentialRequest+ ? "This account does not require approval to view its credentials"+ : "This account does not require approval"+ });+ }++ if (isCredentialRequest) {+ const { decryptor } = await kmsService.createCipherPairWithDataKey({+ type: KmsDataKey.SecretManager,+ projectId+ });+ const credentials = normalizeCredentialAuthMethod(+ account.accountType as PamAccountType,+ JSON.parse(decryptor({ cipherTextBlob: account.encryptedCredentials }).toString("utf-8")) as Record<+ string,+ unknown+ >+ );+ if (!hasRevealableCredential(account.accountType as PamAccountType, credentials)) {+ throw new BadRequestError({ message: noRevealableCredentialMessage(account.name) });+ }+ }++ if (accessControls.requireReason && !inputs.reason) {+ throw new BadRequestError({+ name: "PAM_REASON_REQUIRED",+ message: isCredentialRequest+ ? "A reason is required to request credential access to this account"+ : "A reason is required to request access to this account"+ });+ }++ const policySteps = await approvalPolicyDAL.findStepsByPolicyId(policy.id);+ if (policySteps.length === 0 || policySteps.some((step) => step.approvers.length === 0)) {+ throw new BadRequestError({+ message:+ "This folder's approval policy has no approvers configured. Ask a folder admin to add approvers under the folder's Approvals tab, then submit your request again."+ });+ }++ // Dedupe per (account, access type), so a session request isn't blocked by a pending credential one.+ const pending = await approvalRequestDAL.find({+ ...(actor.type === ActorType.IDENTITY ? { machineIdentityId: actor.id } : { requesterId: actor.id }),+ type: ApprovalPolicyType.PamAccess,+ status: ApprovalRequestStatus.Pending,+ projectId+ });++ const hasPendingForAccount = pending.some((request) => {+ const data = requestDataOf(request);+ return (+ data?.accountId === inputs.accountId &&+ (data?.accessType ?? PamAccessType.Session) === (inputs.accessType ?? PamAccessType.Session)+ );+ });++ if (hasPendingForAccount) {+ throw new BadRequestError({+ message: isCredentialRequest+ ? "You already have a pending credential request for this account"+ : "You already have a pending request for this account"+ });+ }+ };++ const assertCanReview: NonNullable<TPamAccessApprovalResource["assertCanReview"]> = async ({+ request,+ decision,+ actor,+ userGroupIds+ }) => {+ // Self-approval is a conflict of interest and always blocked+ if (decision === ApprovalRequestApprovalDecision.Approved && request.requesterId === actor.id) {+ throw new ForbiddenRequestError({ message: "You cannot approve your own request" });+ }++ const inputs = requestDataOf(request);+ const folderId = inputs?.folderId;++ if (decision === ApprovalRequestApprovalDecision.Approved) {+ const account = inputs?.accountId ? await pamAccountDAL.findByIdWithDetails(inputs.accountId) : null;+ if (!account || account.projectId !== request.projectId || account.folderId !== folderId) {+ throw new BadRequestError({+ message: "This request is no longer valid because the account has moved or been removed"+ });+ }+ }++ if (!folderId) return;++ const currentPolicy = await $findFolderPolicy(request.projectId, folderId);+ if (!currentPolicy) {+ throw new ForbiddenRequestError({ message: "Approval policy no longer exists for this folder" });+ }++ const currentSteps = await approvalPolicyDAL.findStepsByPolicyId(currentPolicy.id);+ const isCurrentApprover = currentSteps.some((step) => $namesActor(step.approvers, actor.id, userGroupIds));+ if (!isCurrentApprover) {+ throw new ForbiddenRequestError({ message: "You are no longer an eligible approver for this folder" });+ }++ if (!(await $holdsActiveFolderMembership(request.projectId, folderId, actor.id, userGroupIds))) {+ throw new ForbiddenRequestError({ message: "You are no longer an eligible approver for this folder" });+ }+ };++ const $refuseBreakGlass = async ({+ request,+ bypassers,+ actor,+ userGroupIds+ }: TBreakGlassArgs): Promise<Error | null> => {+ if (actor.type !== ActorType.USER) {+ return new ForbiddenRequestError({ message: "Only users can break glass on an access request" });+ }++ const inputs = requestDataOf(request);+ if (!inputs?.accountId || !inputs.folderId) {+ return new BadRequestError({ message: "This request is missing the account it was raised for" });+ }++ const account = await pamAccountDAL.findByIdWithDetails(inputs.accountId);+ if (!account || account.projectId !== request.projectId || account.folderId !== inputs.folderId) {+ return new BadRequestError({+ message: "This request is no longer valid because the account has moved or been removed"+ });+ }++ if (!resolveAccessControls(account.templatePolicies).allowBreakGlass) {+ return new ForbiddenRequestError({+ message: `Break-glass is not enabled for '${account.name}'. Ask a PAM admin to turn on the Allow Break-Glass policy on its template.`+ });+ }++ if (!$namesActor(bypassers, actor.id, userGroupIds)) {+ return new ForbiddenRequestError({ message: "You are not a break-glass user for this folder" });+ }++ if (!(await $holdsActiveFolderMembership(request.projectId, inputs.folderId, actor.id, userGroupIds))) {+ return new ForbiddenRequestError({ message: "You are not a member of this folder" });+ }++ return null;+ };++ const assertBreakGlassEligible = async ({+ request,+ actor+ }: {+ request: TApprovalRequests;+ actor: TApprovalActor;+ }) => {+ const folderId = requestDataOf(request)?.folderId;+ const policy = folderId ? await $findFolderPolicy(request.projectId, folderId) : null;+ if (!policy) {+ throw new ForbiddenRequestError({ message: "Approval policy no longer exists for this folder" });+ }++ const [bypassers, userGroupMemberships] = await Promise.all([+ approvalPolicyDAL.findBypassersByPolicyId(policy.id),+ userGroupMembershipDAL.findGroupMembershipsByUserIdInOrg(actor.id, actor.orgId)+ ]);++ const refusal = await $refuseBreakGlass({+ request,+ actor,+ bypassers,+ userGroupIds: new Set(userGroupMemberships.map((g) => g.groupId))+ });+ if (refusal) throw refusal;+ };++ const isBreakGlassEligible: NonNullable<TPamAccessApprovalResource["isBreakGlassEligible"]> = async (args) =>+ !(await $refuseBreakGlass(args));++ const assertCanRevokeGrant: NonNullable<TPamAccessApprovalResource["assertCanRevokeGrant"]> = async ({+ grant,+ request,+ actor+ }) => {+ const ctx = toActorContext(actor);+ const { hasRole } = await verifyProductMembership(permissionService, grant.projectId, ctx);++ const accountId = request ? requestDataOf(request)?.accountId : undefined;+ const account = accountId ? await pamAccountDAL.findByIdWithDetails(accountId) : null;++ if (account && account.projectId === grant.projectId) {+ await checkAccountAccess(+ permissionService,+ account.id,+ account.folderId,+ grant.projectId,+ ResourcePermissionPamResourceActions.RevokeGrants,+ ctx+ );+ return;+ }++ if (!hasRole(PamProductRole.Admin)) {+ throw new ForbiddenRequestError({ message: "You are not authorized to revoke this approval" });+ }+ };++ // Terminates the grantee's live sessions on the granted account+ const onGrantRevoked = async ({+ grant,+ actorId,+ tx+ }: {+ grant: TApprovalRequestGrants;+ actorId: string;+ tx?: Knex;+ }): Promise<() => void> => {+ const noSignals = () => {};++ let granteeFilter: { userId: string } | { identityId: string } | null = null;+ if (grant.granteeMachineIdentityId) granteeFilter = { identityId: grant.granteeMachineIdentityId };+ else if (grant.granteeUserId) granteeFilter = { userId: grant.granteeUserId };++ const attrs = grant.attributes as { accountId?: string; accessType?: PamAccessType } | null;+ if (!attrs?.accountId || !granteeFilter) return noSignals;++ if ((attrs.accessType ?? PamAccessType.Session) === PamAccessType.Credential) return noSignals;++ const liveSessions = await pamSessionDAL.find(+ {+ accountId: attrs.accountId,+ ...granteeFilter,+ $in: { status: [PamSessionStatus.Active, PamSessionStatus.Starting] }+ },+ { tx }+ );+ if (liveSessions.length === 0) return noSignals;++ const actor = await userDAL.findById(actorId, tx);+ return terminatePamSessions({+ sessions: liveSessions,+ actorId,+ actorEmail: actor?.email ?? "",+ pamSessionDAL,+ gatewayV2Service,+ tx+ });+ };++ const $chatDeliveries = async (event: PamNotificationEvent, orgId: string, folderId: string) => {+ const plan = await licenseService.getPlan(orgId);+ if (!plan.pamSlackNotifications) return [];++ const configs = await pamFolderNotificationConfigDAL.findByFolderIdWithIntegration(folderId);+ return getSlackSendTargets(configs, event);+ };++ const buildNotification: NonNullable<TPamAccessApprovalResource["buildNotification"]> = async ({+ event,+ request,+ comment,+ bypassReason+ }) => {+ const inputs = requestDataOf(request);+ if (!inputs?.folderId) return null;++ const [account, folder] = await Promise.all([+ inputs.accountId ? pamAccountDAL.findByIdWithDetails(inputs.accountId) : null,+ pamFolderDAL.findById(inputs.folderId)+ ]);++ const accountName = account?.name ?? "a PAM account";+ const folderName = folder?.name ?? "";+ const orgId = request.organizationId;+ const cfg = getConfig();+ const accessTypeLabel = inputs.accessType === PamAccessType.Credential ? "credential access" : "access";+ const requesterName = request.requesterName || "A user";+ // Machine identities have no email; the label stands in so the template renders something.+ const requesterEmail = request.requesterEmail || "Machine Identity";+ const accountsUrl = `${cfg.SITE_URL}/organizations/${orgId}/pam/accounts`;++ if (event === ApprovalNotificationEvent.Requested) {+ const approvalUrl = `${cfg.SITE_URL}/organizations/${orgId}/pam/approval-requests?requestId=${request.id}`;+ return {+ inApp: {+ type: NotificationType.APPROVAL_REQUIRED,+ title: "Approval Required",+ body: `**${requesterName}** requested ${accessTypeLabel} to **${accountName}**.`,+ link: approvalUrl+ },+ email: {+ subjectLine:+ inputs.accessType === PamAccessType.Credential ? "PAM Credential Access Request" : "PAM Access Request",+ template: SmtpTemplates.AccessPamRequest,+ substitutions: {+ requesterFullName: requesterName,+ requesterEmail,+ accountName,+ folderName: folder?.name ?? undefined,+ accessDuration: formatDuration(inputs.duration),+ accessTypeLabel,+ reason: inputs.reason,+ approvalUrl+ }+ },+ chat: (await $chatDeliveries(PamNotificationEvent.AccessRequested, orgId, inputs.folderId)).map((target) => ({+ ...target,+ notification: {+ type: TriggerFeature.PAM_ACCESS_REQUESTED,+ payload: {+ requesterFullName: requesterName,+ requesterEmail,+ accountName,+ folderName,+ accessDuration: formatDuration(inputs.duration),+ accessTypeLabel,+ reason: inputs.reason,+ approvalUrl+ }+ }+ }))+ };+ }++ if (event === ApprovalNotificationEvent.Bypassed) {+ return {+ inApp: {+ type: NotificationType.ACCESS_APPROVAL_REQUEST_UPDATED,+ title: "Access approval bypassed",+ body: `**${escapeMarkdown(requesterName)}** used break-glass to self-approve access to **${escapeMarkdown(accountName)}**. Reason: "${escapeMarkdown(bypassReason ?? "")}"`,+ link: accountsUrl+ },+ email: {+ subjectLine: "PAM Access Approval Bypassed",+ template: SmtpTemplates.AccessPamRequestBypassed,+ substitutions: {+ requesterFullName: requesterName,+ requesterEmail: request.requesterEmail ?? "",+ resourceName: folder?.name ?? undefined,+ accountName,+ accessDuration: formatDuration(inputs.duration),+ bypassReason+ }+ },+ chat: (await $chatDeliveries(PamNotificationEvent.AccessRequestBypassed, orgId, inputs.folderId)).map(+ (target) => ({+ ...target,+ notification: {+ type: TriggerFeature.PAM_ACCESS_REQUEST_BYPASSED,+ payload: {+ requesterFullName: requesterName,+ requesterEmail: request.requesterEmail ?? "",+ accountName,+ folderName,+ accessDuration: formatDuration(inputs.duration),+ bypassReason: bypassReason ?? ""+ }+ }+ })+ )+ };+ }++ // A decided request leaves the approver inbox, so its messages link to the accounts page instead+ const approved = event === ApprovalNotificationEvent.Approved;+ return {+ inApp: {+ type: NotificationType.ACCESS_APPROVAL_REQUEST_UPDATED,+ title: approved ? "Access request approved" : "Access request denied",+ body: `Your access request for **${accountName}** was ${approved ? "approved" : "denied"}.${+ comment ? ` Reviewer comment: "${comment}"` : ""+ }`,+ link: accountsUrl+ },+ chat: (+ await $chatDeliveries(+ approved ? PamNotificationEvent.AccessRequestApproved : PamNotificationEvent.AccessRequestDenied,+ orgId,+ inputs.folderId+ )+ ).map((target) => ({+ ...target,+ notification: {+ type: approved ? TriggerFeature.PAM_ACCESS_REQUEST_APPROVED : TriggerFeature.PAM_ACCESS_REQUEST_DENIED,+ payload: {+ requesterFullName: requesterName,+ requesterEmail,+ accountName,+ folderName,+ comment,+ approvalUrl: accountsUrl+ }+ }+ }))+ };+ };++ const isLiveApprover: NonNullable<TPamAccessApprovalResource["isLiveApprover"]> = async ({+ projectId,+ scopeId,+ actor,+ userGroupIds+ }) => {+ const policy = await $findFolderPolicy(projectId, scopeId);+ if (!policy) return false;++ const steps = await approvalPolicyDAL.findStepsByPolicyId(policy.id);+ if (!steps.some((step) => $namesActor(step.approvers, actor.id, userGroupIds))) return false;++ return $holdsActiveFolderMembership(projectId, scopeId, actor.id, userGroupIds);+ };++ const decorateRequests: TPamAccessApprovalResource["decorateRequests"] = async (requests) => {+ const inputs = requests.map((request) => requestDataOf(request as { requestData?: unknown }));+ const accountIds = [...new Set(inputs.map((i) => i?.accountId).filter((id): id is string => Boolean(id)))];+ const folderIds = [...new Set(inputs.map((i) => i?.folderId).filter((id): id is string => Boolean(id)))];++ const accounts = accountIds.length > 0 ? await pamAccountDAL.find({ $in: { id: accountIds } }) : [];+ const folders = folderIds.length > 0 ? await pamFolderDAL.find({ $in: { id: folderIds } }) : [];+ const accountById = new Map(accounts.map((a) => [a.id, a]));+ const folderById = new Map(folders.map((f) => [f.id, f]));++ const templateIds = [...new Set(accounts.map((a) => a.templateId).filter(Boolean))];+ const templates = templateIds.length > 0 ? await pamAccountTemplateDAL.find({ $in: { id: templateIds } }) : [];+ const templateTypeById = new Map(templates.map((t) => [t.id, t.type]));++ return requests.map((request, i) => {+ const account = inputs[i]?.accountId ? accountById.get(inputs[i]!.accountId) : null;+ const folder = inputs[i]?.folderId ? folderById.get(inputs[i]!.folderId) : null;+ return {+ ...request,+ accountName: account?.name ?? null,+ accountType: account?.templateId ? (templateTypeById.get(account.templateId) ?? null) : null,+ folderName: folder?.name ?? null,+ accessType: inputs[i]?.accessType ?? PamAccessType.Session+ };+ });+ };++ const buildAuditEvent: NonNullable<TPamAccessApprovalResource["buildAuditEvent"]> = async ({+ action,+ request,+ grantId,+ actorId,+ comment,+ bypassReason+ }) => {+ const inputs = requestDataOf(request);+ const scope = { accountId: inputs?.accountId, folderId: inputs?.folderId };++ if (action === ApprovalAuditAction.RequestCreated) {+ if (!inputs?.accountId || !inputs.folderId) return null;+ return {+ type: EventType.PAM_ACCESS_REQUEST_CREATE,+ metadata: {+ requestId: request.id,+ accountId: inputs.accountId,+ folderId: inputs.folderId,+ duration: inputs.duration,+ accessType: inputs.accessType ?? PamAccessType.Session,+ reason: inputs.reason+ }+ };+ }++ if (action === ApprovalAuditAction.RequestReviewed) {+ return {+ type: EventType.PAM_ACCESS_REQUEST_REVIEW,+ metadata: { requestId: request.id, ...scope, status: request.status, comment }+ };+ }++ if (action === ApprovalAuditAction.GrantRevoked && grantId) {+ return {+ type: EventType.PAM_ACCESS_GRANT_REVOKE,+ metadata: { requestId: request.id, grantId, ...scope }+ };+ }++ if (action !== ApprovalAuditAction.RequestBypassed || !grantId) return null;++ const account = inputs?.accountId ? await pamAccountDAL.findByIdWithDetails(inputs.accountId) : null;+ const folder = inputs?.folderId ? await pamFolderDAL.findById(inputs.folderId) : null;+ const policy = request.policyId ? await approvalPolicyDAL.findById(request.policyId) : null;+ const steps = request.policyId ? await approvalPolicyDAL.findStepsByPolicyId(request.policyId) : [];++ return {+ type: EventType.PAM_ACCESS_POLICY_BYPASSED,+ metadata: {+ policyType: ApprovalPolicyType.PamAccess,+ policyId: policy?.id ?? null,+ policyName: policy?.name,+ requestId: request.id,+ grantId,+ granteeUserId: actorId,+ granteeName: request.requesterName ?? undefined,+ granteeEmail: request.requesterEmail ?? undefined,+ ...scope,+ folderName: folder?.name,+ resourceName: folder?.name,+ accountName: account?.name,+ accessDuration: inputs?.duration ?? "",+ bypassReason: bypassReason ?? "",+ approverCount: new Set(steps.flatMap((step) => step.approvers.map((a) => `${a.type}:${a.id}`))).size+ }+ };+ };++ const filterActiveApprovers: NonNullable<TPamAccessApprovalResource["filterActiveApprovers"]> = async (+ request,+ approvers+ ) => {+ const folderId = requestDataOf(request)?.folderId;+ if (!folderId || approvers.length === 0) return approvers;++ const memberships = await findActiveFolderMemberships(request.projectId, folderId);+ const activeKeys = new Set([+ ...memberships.filter((m) => m.actorUserId).map((m) => `${ApproverType.User}:${m.actorUserId}`),+ ...memberships.filter((m) => m.actorGroupId).map((m) => `${ApproverType.Group}:${m.actorGroupId}`)+ ]);++ return approvers.filter((approver) => activeKeys.has(`${approver.type}:${approver.id}`));+ };++ const revokeGrantRow = async (grant: TApprovalRequestGrants, actorId: string, reason: string, tx?: Knex) => {+ const revoked = await approvalRequestGrantsDAL.updateById(+ grant.id,+ {+ status: ApprovalRequestGrantStatus.Revoked,+ revokedByUserId: actorId,+ revokedAt: new Date(),+ revocationReason: reason+ },+ tx+ );++ return { revoked, sendCancellationSignals: await onGrantRevoked({ grant, actorId, tx }) };+ };++ return {+ matchPolicy,+ canAccess,+ matchesInputs,+ buildNotification,+ buildAuditEvent,+ decorateRequests,+ filterActiveApprovers,+ isLiveApprover,+ validateConstraints,+ postApprovalTxRoutine,+ resolveScope,+ noMatchingPolicyMessage: "No approval configuration found for this folder",+ assertCanManagePolicy,+ verifyPolicyActors,+ assertCanCreateRequest,+ assertCanReview,+ isBreakGlassEligible,+ assertBreakGlassEligible,+ assertCanRevokeGrant,+ onGrantRevoked,+ findActiveFolderMemberships,+ revokeGrantRow+ };+};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 f88ae788ae..05d8ceba44 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@@ -1,96 +1,32 @@-import { ForbiddenError } from "@casl/ability";import { Knex } from "knex";-import { RESOURCE_SCOPE, ResourceType, TApprovalRequestGrants } from "@app/db/schemas";-import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";-import { TGroupDALFactory } from "@app/ee/services/group/group-dal";-import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";+import { TApprovalRequestGrants } from "@app/db/schemas";import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";import {- ResourcePermissionPamResourceActions,- ResourcePermissionSub+ ResourcePermissionApprovalPolicyActions,+ ResourcePermissionPamResourceActions} from "@app/ee/services/permission/resource-permission";-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 {- TApprovalPolicyBypassersDALFactory,- TApprovalPolicyDALFactory,- TApprovalPolicyStepApproversDALFactory,- TApprovalPolicyStepsDALFactory-} from "@app/services/approval-policy/approval-policy-dal";-import {- ApprovalPolicyScope,- ApprovalPolicyType,- ApprovalRequestApprovalDecision,- ApprovalRequestGrantStatus,- ApprovalRequestStatus,- ApprovalRequestStepStatus,- ApproverType,- EnforcementLevel-} from "@app/services/approval-policy/approval-policy-enums";-import { TApprovalRequestData } from "@app/services/approval-policy/approval-policy-types";-import {- TApprovalRequestApprovalsDALFactory,- TApprovalRequestDALFactory,- TApprovalRequestGrantsDALFactory,- TApprovalRequestStepEligibleApproversDALFactory,- TApprovalRequestStepsDALFactory-} from "@app/services/approval-policy/approval-request-dal";-import {- createApprovalRequestWithSteps,- notifyApproversForStep-} from "@app/services/approval-policy/approval-request-fns";+import { TApprovalPolicyDALFactory } from "@app/services/approval-policy/approval-policy-dal";+import { ApprovalPolicyScope, ApprovalPolicyType } from "@app/services/approval-policy/approval-policy-enums";+import { TApprovalPolicyServiceFactory } from "@app/services/approval-policy/approval-policy-service";+import { TApprovalActor } from "@app/services/approval-policy/approval-policy-types";+import { TApprovalRequestDALFactory } from "@app/services/approval-policy/approval-request-dal";+import { TPamAccessPolicyInputs } from "@app/services/approval-policy/pam-access/pam-access-policy-types";import { ActorType } from "@app/services/auth/auth-type";import { TIdentityDALFactory } from "@app/services/identity/identity-dal";-import { TKmsServiceFactory } from "@app/services/kms/kms-service";-import { KmsDataKey } from "@app/services/kms/kms-types";-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,- PamAccessType,- PamAccountType,- PamNotificationEvent,- PamProductRole,- PamSessionStatus-} from "../pam/pam-enums";+import { PamAccessType } from "../pam/pam-enums";import { resolveAccountByPath } from "../pam/pam-fns";-import {- checkAccountAccess,- checkFolderPermission,- TActorContext,- verifyProductMembership-} from "../pam/pam-permission";-import { resolveAccessControls } from "../pam/pam-policies";+import { checkAccountAccess, TActorContext, verifyProductMembership } from "../pam/pam-permission";import { TPamAccountDALFactory } from "../pam-account/pam-account-dal";-import {- hasRevealableCredential,- noRevealableCredentialMessage,- normalizeCredentialAuthMethod-} from "../pam-account/pam-account-schemas";-import { TPamAccountTemplateDALFactory } from "../pam-account-template/pam-account-template-dal";import { TPamFolderDALFactory } from "../pam-folder/pam-folder-dal";-import { TPamSessionDALFactory } from "../pam-session/pam-session-dal";-import { terminatePamSessions } from "../pam-session/pam-session-fns";-import {- escapeMarkdown,- getSlackSendTargets,- parseNotificationChannels,- parseNotificationEvents-} from "./pam-access-request-fns";+import { TPamAccessApprovalResource } from "./pam-access-approval-resource";+import { parseNotificationChannels, parseNotificationEvents } from "./pam-access-request-fns";import {TAccessRequestActor,TBreakGlassAccessRequestDTO,@@ -102,29 +38,12 @@ import {TListAccessRequestsDTO,TListPendingMyApprovalDTO,TPamAccessRequestData,- TReviewAccessRequestDTO,- TRevokeAccessRequestDTO,TSetApprovalConfigurationDTO} from "./pam-access-request-types";import { TPamFolderNotificationConfigDALFactory } from "./pam-folder-notification-config-dal";type TPamAccessRequestServiceFactoryDep = {- approvalPolicyDAL: Pick<- TApprovalPolicyDALFactory,- | "find"- | "findOne"- | "create"- | "deleteById"- | "transaction"- | "findStepsByPolicyId"- | "isProjectApprover"- | "findScopeIdsWithApprovers"- | "findBypassersByPolicyId"- | "findBypassersByPolicyIds"- >;- approvalPolicyStepsDAL: Pick<TApprovalPolicyStepsDALFactory, "create" | "delete">;- approvalPolicyStepApproversDAL: Pick<TApprovalPolicyStepApproversDALFactory, "create" | "delete">;- approvalPolicyBypassersDAL: Pick<TApprovalPolicyBypassersDALFactory, "create" | "delete">;+ approvalPolicyDAL: Pick<TApprovalPolicyDALFactory, "findById">;approvalRequestDAL: Pick<TApprovalRequestDALFactory,| "find"@@ -138,22 +57,9 @@ type TPamAccessRequestServiceFactoryDep = {| "findStepsByRequestId"| "findByProjectId">;- approvalRequestStepsDAL: Pick<TApprovalRequestStepsDALFactory, "create" | "updateById">;- approvalRequestStepEligibleApproversDAL: Pick<TApprovalRequestStepEligibleApproversDALFactory, "create">;- approvalRequestApprovalsDAL: Pick<TApprovalRequestApprovalsDALFactory, "create" | "find">;- approvalRequestGrantsDAL: Pick<TApprovalRequestGrantsDALFactory, "find" | "findOne" | "create" | "updateById">;pamAccountDAL: Pick<TPamAccountDALFactory, "findByIdWithDetails" | "find" | "findOne">;- pamAccountTemplateDAL: Pick<TPamAccountTemplateDALFactory, "find">;pamFolderDAL: Pick<TPamFolderDALFactory, "findById" | "find" | "findOne">;- pamSessionDAL: Pick<TPamSessionDALFactory, "find" | "update">;- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPAMConnectionDetails">;- membershipDAL: Pick<TMembershipDALFactory, "find">;- membershipRoleDAL: Pick<TMembershipRoleDALFactory, "find">;permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getResourcePermission">;- notificationService: Pick<TNotificationServiceFactory, "createUserNotifications">;- smtpService: Pick<TSmtpService, "sendMail">;- groupDAL: Pick<TGroupDALFactory, "find">;- userGroupMembershipDAL: Pick<TUserGroupMembershipDALFactory, "find" | "findGroupMembershipsByUserIdInOrg">;userDAL: Pick<TUserDALFactory, "findById" | "find">;identityDAL: Pick<TIdentityDALFactory, "findById">;pamFolderNotificationConfigDAL: Pick<@@ -161,73 +67,60 @@ type TPamAccessRequestServiceFactoryDep = {"findByFolderIdWithIntegration" | "delete" | "insertMany" | "transaction">;workflowIntegrationDAL: Pick<TWorkflowIntegrationDALFactory, "find">;- slackIntegrationDAL: Pick<TSlackIntegrationDALFactory, "findByIdWithWorkflowIntegrationDetails">;- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;licenseService: Pick<TLicenseServiceFactory, "getPlan">;+ approvalPolicyService: Pick<+ TApprovalPolicyServiceFactory,+ | "create"+ | "updateById"+ | "deleteById"+ | "list"+ | "createRequest"+ | "approveRequest"+ | "rejectRequest"+ | "revokeGrant"+ | "getActiveGrant"+ | "getAccessStatuses"+ | "getScopeIdsWithApprovers"+ | "getBypassableScopeIds"+ | "reapScope"+ | "reapSubject"+ | "listScopeRequests"+ | "listPendingForApprover"+ | "countPendingForApprover"+ | "getApproverRoster"+ | "getScopeConfiguration"+ | "setScopeConfiguration"+ >;+ pamAccessApprovalResource: TPamAccessApprovalResource;};export type TPamAccessRequestServiceFactory = ReturnType<typeof pamAccessRequestServiceFactory>;export const pamAccessRequestServiceFactory = ({approvalPolicyDAL,- approvalPolicyStepsDAL,- approvalPolicyStepApproversDAL,- approvalPolicyBypassersDAL,approvalRequestDAL,- approvalRequestStepsDAL,- approvalRequestStepEligibleApproversDAL,- approvalRequestApprovalsDAL,- approvalRequestGrantsDAL,pamAccountDAL,- pamAccountTemplateDAL,pamFolderDAL,- pamSessionDAL,- gatewayV2Service,- membershipDAL,- membershipRoleDAL,permissionService,- notificationService,- smtpService,- groupDAL,- userGroupMembershipDAL,userDAL,identityDAL,pamFolderNotificationConfigDAL,workflowIntegrationDAL,- slackIntegrationDAL,- kmsService,- licenseService+ licenseService,+ approvalPolicyService,+ pamAccessApprovalResource}: TPamAccessRequestServiceFactoryDep) => {- const findFolderPolicy = async (folderId: string) => {- const policy = await approvalPolicyDAL.findOne({- type: ApprovalPolicyType.PamAccess,- scopeType: ApprovalPolicyScope.PamFolder,- scopeId: folderId- });- return policy ?? null;- };+ const toSubjectActor = ({ actorId, actor }: TAccessRequestActor) => ({ id: actorId, type: actor });- const isFolderBreakGlassUser = async (- policyId: string,- userId: string,- userGroupIds: Set<string>,- tx?: Knex- ): Promise<boolean> => {- const bypassers = await approvalPolicyDAL.findBypassersByPolicyId(policyId, tx);- return bypassers.some(- (b) =>- (b.type === ApproverType.User && b.id === userId) || (b.type === ApproverType.Group && userGroupIds.has(b.id))- );- };+ const toApprovalActor = (ctx: TActorContext): TApprovalActor => ({+ id: ctx.actorId,+ type: ctx.actor,+ authMethod: ctx.actorAuthMethod,+ orgId: ctx.actorOrgId+ });// Requests and grants attribute their actor to exactly one column: a user or a machine identity.// These build the matching filter so every lookup stays scoped to the calling actor's own rows.- const actorRequestFilter = ({ actorId, actor }: TAccessRequestActor) =>- actor === ActorType.IDENTITY ? { machineIdentityId: actorId } : { requesterId: actorId };-- const actorGrantFilter = ({ actorId, actor }: TAccessRequestActor) =>- actor === ActorType.IDENTITY ? { granteeMachineIdentityId: actorId } : { granteeUserId: actorId };-// Machine identities have no email; their name is the only human-readable attribution available.const resolveRequesterDisplay = async ({ actorId, actor }: TAccessRequestActor) => {if (actor === ActorType.IDENTITY) {@@ -252,222 +145,24 @@ export const pamAccessRequestServiceFactory = ({}));};- // 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 plan = await licenseService.getPlan(orgId);- if (!plan.pamSlackNotifications) return;-- 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 || "Machine Identity",- accountName: params.accountName ?? "a PAM account",- folderName: folder?.name ?? "",- comment: params.comment,- // Decided requests leave the approver inbox, so decision messages link to the- // unified PAM Accounts page (same destination as the in-app notification)- approvalUrl: `${cfg.SITE_URL}/organizations/${params.orgId}/pam/accounts`- }- }- });- } 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);- if (!durationMs || durationMs <= 0) {- throw new BadRequestError({- message: `Invalid access duration '${duration}'. Use a single unit like '30m', '2h', or '1d'`- });- }- return durationMs;- };-- // Confirms the folder belongs to the project (guards cross-project IDOR) and that the actor may- // manage its approval configuration. Used by every folder-scoped approval admin surface.+ // Guards cross-project IDOR and checks the actor may manage the configurationconst assertFolderPolicyManagement = async (folderId: string, projectId: string, ctx: TActorContext) => {+ await pamAccessApprovalResource.assertCanManagePolicy?.({+ projectId,+ scopeId: folderId,+ actor: toApprovalActor(ctx),+ action: ResourcePermissionApprovalPolicyActions.Edit+ });+const folder = await pamFolderDAL.findById(folderId);if (!folder || folder.projectId !== projectId) {throw new NotFoundError({ message: "Folder not found" });}- const { permission } = await checkFolderPermission(permissionService, folderId, projectId, ctx);- ForbiddenError.from(permission).throwUnlessCan(- ResourcePermissionPamResourceActions.ManagePolicies,- ResourcePermissionSub.PamResource- );return folder;};- const getUserGroupIds = async (userId: string, orgId: string): Promise<Set<string>> => {- const memberships = await userGroupMembershipDAL.findGroupMembershipsByUserIdInOrg(userId, orgId);- return new Set(memberships.map((m) => m.groupId));- };-- // Temporary membership expiry is enforced lazily (rows are not deleted when access lapses), so- // approver eligibility must filter to memberships that still carry an active role.- const findActiveFolderMemberships = async (projectId: string, folderId: string) => {- const memberships = await membershipDAL.find({- scope: RESOURCE_SCOPE,- scopeProjectId: projectId,- scopeResourceType: ResourceType.PamFolder,- scopeResourceId: folderId- });- if (!memberships.length) return [];-- const roles = await membershipRoleDAL.find({ $in: { membershipId: memberships.map((m) => m.id) } });- const now = new Date();- const isWithinTemporaryWindow = (r: (typeof roles)[number]) =>- Boolean(r.temporaryAccessEndTime) &&- now < new Date(r.temporaryAccessEndTime as Date) &&- (!r.temporaryAccessStartTime || now >= new Date(r.temporaryAccessStartTime));- const activeMembershipIds = new Set(- roles.filter((r) => !r.isTemporary || isWithinTemporaryWindow(r)).map((r) => r.membershipId)- );- return memberships.filter((m) => m.isActive && activeMembershipIds.has(m.id));- };-- const enrichRequestsWithNames = async <T extends { requestData?: unknown }>(requests: T[]) => {- const accountIds = new Set<string>();- const folderIds = new Set<string>();- for (const r of requests) {- const data = r.requestData as { version: number; requestData: TPamAccessRequestData } | null;- if (data?.requestData?.accountId) accountIds.add(data.requestData.accountId);- if (data?.requestData?.folderId) folderIds.add(data.requestData.folderId);- }-- const [accounts, folders] = await Promise.all([- accountIds.size > 0 ? pamAccountDAL.find({ $in: { id: [...accountIds] } }) : [],- folderIds.size > 0 ? pamFolderDAL.find({ $in: { id: [...folderIds] } }) : []- ]);- const accountMap = new Map(accounts.map((a) => [a.id, a]));- const folderMap = new Map(folders.map((f) => [f.id, f]));-- const templateIds = [...new Set(accounts.map((a) => a.templateId).filter(Boolean))];- const templates = templateIds.length > 0 ? await pamAccountTemplateDAL.find({ $in: { id: templateIds } }) : [];- const templateTypeMap = new Map(templates.map((t) => [t.id, t.type]));-- return requests.map((r) => {- const data = r.requestData as { version: number; requestData: TPamAccessRequestData } | null;- const account = data?.requestData?.accountId ? accountMap.get(data.requestData.accountId) : null;- const folder = data?.requestData?.folderId ? folderMap.get(data.requestData.folderId) : null;- return {- ...r,- accountName: account?.name ?? null,- accountType: account?.templateId ? (templateTypeMap.get(account.templateId) ?? null) : null,- folderName: folder?.name ?? null,- accessType: data?.requestData?.accessType ?? PamAccessType.Session- };- });- };-// Attach the access grant's expiry and status to each request. Requests themselves carry no expiry// or revocation state; the meaningful "expires"/"revoked" lives on the grant created on approval.- const attachGrantExpiry = async <T extends { id: string }>(requests: T[]) => {- if (requests.length === 0)- return requests.map((r) => ({- ...r,- grantExpiresAt: null as Date | null,- grantStatus: null as string | null,- isBreakGlass: false,- bypassReason: null as string | null- }));-- const grants = await approvalRequestGrantsDAL.find({ $in: { requestId: requests.map((r) => r.id) } });- const grantByRequestId = new Map<- string,- { expiresAt: Date | null; status: string; isBreakGlass: boolean; bypassReason: string | null }- >();- grants- .filter((g) => g.requestId)- .forEach((g) =>- grantByRequestId.set(g.requestId as string, {- expiresAt: g.expiresAt ?? null,- status: g.status,- isBreakGlass: Boolean(g.isBreakGlass),- bypassReason: g.bypassReason ?? null- })- );-- return requests.map((r) => {- const grant = grantByRequestId.get(r.id);- return {- ...r,- grantExpiresAt: grant?.expiresAt ?? null,- grantStatus: grant?.status ?? null,- isBreakGlass: grant?.isBreakGlass ?? false,- bypassReason: grant?.bypassReason ?? null- };- });- };-- const isUserEligibleApprover = (- approvers: { type: string; id: string }[],- userId: string,- userGroupIds: Set<string>- ): boolean => {- return approvers.some(- (a) =>- (a.type === ApproverType.User && a.id === userId) || (a.type === ApproverType.Group && userGroupIds.has(a.id))- );- };-const getApprovalConfiguration = async ({ folderId, projectId, ...ctx }: TGetApprovalConfigurationDTO) => {await verifyProductMembership(permissionService, projectId, ctx);@@ -476,34 +171,17 @@ export const pamAccessRequestServiceFactory = ({throw new NotFoundError({ message: "Folder not found" });}- // Viewing the configuration is read-only, so auditors (ViewAuditLogs) may see it alongside- // policy managers; editing still requires ManagePolicies via assertFolderPolicyManagement.- const { permission } = await checkFolderPermission(permissionService, folderId, projectId, ctx);- const canView =- permission.can(ResourcePermissionPamResourceActions.ManagePolicies, ResourcePermissionSub.PamResource) ||- permission.can(ResourcePermissionPamResourceActions.ViewAuditLogs, ResourcePermissionSub.PamResource);- if (!canView) {- throw new ForbiddenRequestError({- message: "You are not authorized to view this folder's approval configuration"- });- }-- const notificationConfigs = await getNotificationConfigs(folderId);-- const policy = await findFolderPolicy(folderId);- if (!policy) {- return { steps: [], notificationConfigs, breakGlassUsers: [] };- }+ const { steps, bypassers } = await approvalPolicyService.getScopeConfiguration(+ ApprovalPolicyType.PamAccess,+ ApprovalPolicyScope.PamFolder,+ folderId,+ toApprovalActor(ctx)+ );- // The policy row and step tuning fields are internal; the UI only needs the approver lists.- const [steps, breakGlassUsers] = await Promise.all([- approvalPolicyDAL.findStepsByPolicyId(policy.id),- approvalPolicyDAL.findBypassersByPolicyId(policy.id)- ]);return {- steps: steps.map((s) => ({ approvers: s.approvers })),- notificationConfigs,- breakGlassUsers: breakGlassUsers.map((b) => ({ type: b.type, id: b.id }))+ steps: steps.map((step) => ({ approvers: step.approvers })),+ notificationConfigs: await getNotificationConfigs(folderId),+ breakGlassUsers: bypassers};};@@ -522,33 +200,11 @@ export const pamAccessRequestServiceFactory = ({throw new BadRequestError({ message: "Phase 1 only supports a single approval step" });}- // Approvers and break-glass users must be active members of the folder. This keeps both lists in- // sync with membership so that removing someone from the folder (which strips their approver rows)- // can't be circumvented by designating a non-member or expired member.- const requestedApprovers = steps.flatMap((s) => s.approvers);+ const requestedApprovers = steps.flatMap((step) => step.approvers);const managesBreakGlass = breakGlassUsers !== undefined;- const requestedBreakGlassUsers = breakGlassUsers ?? [];- if (requestedApprovers.length > 0 || requestedBreakGlassUsers.length > 0) {- const memberships = await findActiveFolderMemberships(projectId, folderId);- const memberUserIds = new Set(memberships.map((m) => m.actorUserId).filter(Boolean));- const memberGroupIds = new Set(memberships.map((m) => m.actorGroupId).filter(Boolean));- const isFolderMember = (entry: { type: ApproverType; id: string }) =>- entry.type === ApproverType.User ? memberUserIds.has(entry.id) : memberGroupIds.has(entry.id);-- for (const approver of requestedApprovers) {- if (!isFolderMember(approver)) {- throw new BadRequestError({ message: "Approvers must be members of the folder" });- }- }-- for (const bypasser of requestedBreakGlassUsers) {- if (!isFolderMember(bypasser)) {- throw new BadRequestError({ message: "Break-glass users must be members of the folder" });- }- }- }-- const dedupedBreakGlassUsers = [...new Map(requestedBreakGlassUsers.map((b) => [`${b.type}:${b.id}`, b])).values()];+ const dedupedBreakGlassUsers = [+ ...new Map((breakGlassUsers ?? []).map((bypasser) => [`${bypasser.type}:${bypasser.id}`, bypasser])).values()+ ];if (dedupedBreakGlassUsers.length > 0 && requestedApprovers.length === 0) {throw new BadRequestError({@@ -556,24 +212,13 @@ export const pamAccessRequestServiceFactory = ({});}- const replaceBreakGlassUsers = async (policyId: string, tx: Knex) => {- if (!managesBreakGlass) return;- await approvalPolicyBypassersDAL.delete({ policyId }, tx);- for (const bypasser of dedupedBreakGlassUsers) {- // eslint-disable-next-line no-await-in-loop- await approvalPolicyBypassersDAL.create(- {- policyId,- userId: bypasser.type === ApproverType.User ? bypasser.id : null,- groupId: bypasser.type === ApproverType.Group ? bypasser.id : null- },- tx- );- }- };+ await pamAccessApprovalResource.verifyPolicyActors?.({+ projectId,+ scopeId: folderId,+ approvers: requestedApprovers,+ bypassers: dedupedBreakGlassUsers+ });- // 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 plan = await licenseService.getPlan(ctx.actorOrgId);@@ -617,264 +262,30 @@ export const pamAccessRequestServiceFactory = ({}});}- const notificationConfigCount = notificationConfigs?.length;-- const existingPolicy = await findFolderPolicy(folderId);-- const hasApprovers = steps.length === 1 && steps[0].approvers.length > 0;- if (!hasApprovers && existingPolicy) {- await approvalPolicyDAL.transaction(async (tx) => {- await approvalPolicyStepsDAL.delete({ policyId: existingPolicy.id }, tx);- await approvalPolicyDAL.deleteById(existingPolicy.id, tx);- });- return {- policyId: existingPolicy.id,- folderId,- stepCount: steps.length,- notificationConfigCount,- breakGlassUserCount: 0- };- }-- if (!hasApprovers) {- return { policyId: null, folderId, stepCount: 0, notificationConfigCount, breakGlassUserCount: 0 };- }-- if (existingPolicy) {- await approvalPolicyDAL.transaction(async (tx) => {- await approvalPolicyStepsDAL.delete({ policyId: existingPolicy.id }, tx);-- for (let i = 0; i < steps.length; i += 1) {- // eslint-disable-next-line no-await-in-loop- const newStep = await approvalPolicyStepsDAL.create(- {- policyId: existingPolicy.id,- stepNumber: i + 1,- requiredApprovals: 1,- notifyApprovers: true- },- tx- );-- for (const approver of steps[i].approvers) {- // eslint-disable-next-line no-await-in-loop- await approvalPolicyStepApproversDAL.create(- {- policyStepId: newStep.id,- userId: approver.type === ApproverType.User ? approver.id : null,- groupId: approver.type === ApproverType.Group ? approver.id : null- },- tx- );- }- }-- await replaceBreakGlassUsers(existingPolicy.id, tx);- });-- return {- policyId: existingPolicy.id,- folderId,- stepCount: steps.length,- notificationConfigCount,- breakGlassUserCount: managesBreakGlass ? dedupedBreakGlassUsers.length : undefined- };- }-- const newPolicy = await approvalPolicyDAL.transaction(async (tx) => {- const policy = await approvalPolicyDAL.create(- {- projectId,- organizationId: ctx.actorOrgId,- type: ApprovalPolicyType.PamAccess,- name: `PAM Folder Approval - ${folder.name}`,- scopeType: ApprovalPolicyScope.PamFolder,- scopeId: folderId,- enforcementLevel: EnforcementLevel.Hard,- conditions: { version: 1, conditions: [] },- constraints: { version: 1, constraints: { accessDuration: { min: "30s", max: "7d" } } }- },- tx- );-- for (let i = 0; i < steps.length; i += 1) {- // eslint-disable-next-line no-await-in-loop- const step = await approvalPolicyStepsDAL.create(- {- policyId: policy.id,- stepNumber: i + 1,- requiredApprovals: 1,- notifyApprovers: true- },- tx- );-- for (const approver of steps[i].approvers) {- // eslint-disable-next-line no-await-in-loop- await approvalPolicyStepApproversDAL.create(- {- policyStepId: step.id,- userId: approver.type === ApproverType.User ? approver.id : null,- groupId: approver.type === ApproverType.Group ? approver.id : null- },- tx- );- }- }-- await replaceBreakGlassUsers(policy.id, tx);- return policy;- });+ const { policyId } = await approvalPolicyService.setScopeConfiguration(+ ApprovalPolicyType.PamAccess,+ ApprovalPolicyScope.PamFolder,+ folderId,+ {+ steps: steps.map((step) => ({ requiredApprovals: 1, approvers: step.approvers })),+ ...(managesBreakGlass ? { bypassers: dedupedBreakGlassUsers } : {}),+ name: `PAM Folder Approval - ${folder.name}`,+ conditions: [],+ constraints: { accessDuration: { min: "30s", max: "7d" } }+ },+ toApprovalActor(ctx)+ );return {- policyId: newPolicy.id,+ policyId,folderId,stepCount: steps.length,- notificationConfigCount,+ notificationConfigCount: notificationConfigs?.length,breakGlassUserCount: managesBreakGlass ? dedupedBreakGlassUsers.length : undefined};};- const assertBreakGlassEligible = async ({- account,- folderId,- policyId,- projectId,- userGroupIds,- ctx- }: {- account: { name: string; templatePolicies: unknown };- folderId: string;- policyId: string;- projectId: string;- userGroupIds: Set<string>;- ctx: TActorContext;- }) => {- if (ctx.actor !== ActorType.USER) {- throw new ForbiddenRequestError({ message: "Only users can break glass on an access request" });- }-- const { allowBreakGlass } = resolveAccessControls(account.templatePolicies);- if (!allowBreakGlass) {- throw new ForbiddenRequestError({- message: `Break-glass is not enabled for '${account.name}'. Ask a PAM admin to turn on the Allow Break-Glass policy on its template.`- });- }-- if (!(await isFolderBreakGlassUser(policyId, ctx.actorId, userGroupIds))) {- throw new ForbiddenRequestError({ message: "You are not a break-glass user for this folder" });- }-- const activeMemberships = await findActiveFolderMemberships(projectId, folderId);- const hasActiveMembership = activeMemberships.some(- (m) => m.actorUserId === ctx.actorId || (m.actorGroupId && userGroupIds.has(m.actorGroupId))- );- if (!hasActiveMembership) {- throw new ForbiddenRequestError({ message: "You are not a member of this folder" });- }- };-- const notifyOfBreakGlass = async ({- request,- account,- folderId,- duration,- bypassReason,- actorId,- orgId,- projectId- }: {- request: { id: string; requesterName?: string | null; requesterEmail?: string | null };- account: { name: string; folderName: string | null };- folderId: string;- duration: string;- bypassReason: string;- actorId: string;- orgId: string;- projectId: string;- }) => {- try {- const livePolicy = await findFolderPolicy(folderId);- const [livePolicySteps, activeMemberships] = await Promise.all([- livePolicy ? approvalPolicyDAL.findStepsByPolicyId(livePolicy.id) : Promise.resolve([]),- findActiveFolderMemberships(projectId, folderId)- ]);- const activeMemberKeys = new Set([- ...activeMemberships.filter((m) => m.actorUserId).map((m) => `${ApproverType.User}:${m.actorUserId}`),- ...activeMemberships.filter((m) => m.actorGroupId).map((m) => `${ApproverType.Group}:${m.actorGroupId}`)- ]);-- const approverUserIds = new Set<string>();- const approverGroupIds = new Set<string>();- const holdsActiveMembership = (approver: { type: string; id: string }) =>- activeMemberKeys.has(`${approver.type}:${approver.id}`);-- for (const step of livePolicySteps) {- for (const approver of step.approvers.filter(holdsActiveMembership)) {- if (approver.type === ApproverType.User) approverUserIds.add(approver.id);- else approverGroupIds.add(approver.id);- }- }-- const groupMemberLists = await Promise.all(- [...approverGroupIds].map((groupId) => userGroupMembershipDAL.find({ groupId }))- );- groupMemberLists.forEach((members) => members.forEach((m) => approverUserIds.add(m.userId)));- approverUserIds.delete(actorId);-- if (approverUserIds.size > 0) {- const approverUsers = await userDAL.find({ $in: { id: [...approverUserIds] } });-- await notificationService.createUserNotifications(- [...approverUserIds].map((userId) => ({- userId,- orgId,- type: NotificationType.ACCESS_APPROVAL_REQUEST_UPDATED,- title: "Access approval bypassed",- body: `**${escapeMarkdown(request.requesterName ?? "A user")}** used break-glass to self-approve access to **${escapeMarkdown(account.name)}**. Reason: "${escapeMarkdown(bypassReason)}"`- }))- );-- const recipients = approverUsers.filter((u) => u.email).map((u) => u.email as string);- if (recipients.length > 0) {- await smtpService.sendMail({- recipients,- subjectLine: "PAM Access Approval Bypassed",- template: SmtpTemplates.AccessPamRequestBypassed,- substitutions: {- requesterFullName: request.requesterName ?? "A user",- requesterEmail: request.requesterEmail ?? "",- resourceName: account.folderName ?? undefined,- accountName: account.name,- accessDuration: formatDuration(duration),- bypassReason- }- });- }- }- } catch (err) {- logger.error(err, `Failed to send PAM break-glass notifications [requestId=${request.id}]`);- }-- void triggerFolderSlackNotifications({- folderId,- event: PamNotificationEvent.AccessRequestBypassed,- orgId,- notification: {- type: TriggerFeature.PAM_ACCESS_REQUEST_BYPASSED,- payload: {- requesterFullName: request.requesterName ?? "A user",- requesterEmail: request.requesterEmail ?? "",- accountName: account.name,- folderName: account.folderName ?? "",- accessDuration: formatDuration(duration),- bypassReason- }- }- });- };-const breakGlassRequest = async ({ requestId, projectId, bypassReason, ...ctx }: TBreakGlassAccessRequestDTO) => {await verifyProductMembership(permissionService, projectId, ctx);@@ -898,15 +309,6 @@ export const pamAccessRequestServiceFactory = ({throw new ForbiddenRequestError({ message: "You can only break glass on your own access request" });}- if (request.status !== ApprovalRequestStatus.Pending) {- throw new BadRequestError({ message: "Request is not pending" });- }-- if (request.expiresAt && new Date(request.expiresAt) < new Date()) {- await approvalRequestDAL.updateById(requestId, { status: ApprovalRequestStatus.Expired });- throw new BadRequestError({ message: "Request has expired" });- }-const requestData = request.requestData as { version: number; requestData: TPamAccessRequestData } | null;const folderId = requestData?.requestData?.folderId;const accountId = requestData?.requestData?.accountId;@@ -921,14 +323,6 @@ export const pamAccessRequestServiceFactory = ({});}- const policy = await findFolderPolicy(folderId);- if (!policy) {- throw new ForbiddenRequestError({ message: "Approval policy no longer exists for this folder" });- }-- const userGroupIds = await getUserGroupIds(ctx.actorId, ctx.actorOrgId);- await assertBreakGlassEligible({ account, folderId, policyId: policy.id, projectId, userGroupIds, ctx });-// Break-glass skips the approver, not the permission the request itself needed.const accessType = requestData.requestData.accessType ?? PamAccessType.Session;await checkAccountAccess(@@ -942,95 +336,37 @@ export const pamAccessRequestServiceFactory = ({ctx);- const steps = await approvalRequestDAL.findStepsByRequestId(requestId);- const bypassedApproverCount = new Set(steps.flatMap((s) => s.approvers.map((a) => `${a.type}:${a.id}`))).size;- const durationMs = parseDurationMs(requestData.requestData.duration);+ await pamAccessApprovalResource.assertBreakGlassEligible({ request, actor: toApprovalActor(ctx) });- const { updatedRequest, grant } = await approvalRequestDAL.transaction(async (tx) => {- const locked = await approvalRequestDAL.findByIdForUpdate(requestId, tx);- if (!locked || locked.status !== ApprovalRequestStatus.Pending) {- throw new BadRequestError({ message: "Request is not pending" });- }-- if (locked.expiresAt && new Date(locked.expiresAt) < new Date()) {- await approvalRequestDAL.updateById(requestId, { status: ApprovalRequestStatus.Expired }, tx);- throw new BadRequestError({ message: "Request has expired" });- }-- await Promise.all(- steps.map((step) =>- approvalRequestStepsDAL.updateById(- step.id,- { status: ApprovalRequestStepStatus.Completed, completedAt: new Date() },- tx- )- )- );-- if (!(await isFolderBreakGlassUser(policy.id, ctx.actorId, userGroupIds, tx))) {- throw new ForbiddenRequestError({ message: "You are not a break-glass user for this folder" });- }+ const policy = request.policyId ? await approvalPolicyDAL.findById(request.policyId) : null;- const currentStep = steps.find((s) => s.stepNumber === locked.currentStep);- if (currentStep) {- await approvalRequestApprovalsDAL.create(- {- stepId: currentStep.id,- approverUserId: ctx.actorId,- decision: ApprovalRequestApprovalDecision.Approved,- comment: `Break-glass: ${trimmedReason}`- },- tx- );- }-- await approvalRequestDAL.updateById(requestId, { status: ApprovalRequestStatus.Approved }, tx);-- const createdGrant = await approvalRequestGrantsDAL.create(- {- projectId: request.projectId,- requestId: request.id,- granteeUserId: request.requesterId,- status: ApprovalRequestGrantStatus.Active,- type: ApprovalPolicyType.PamAccess,- attributes: { accountId, folderId, accessType },- expiresAt: new Date(Date.now() + durationMs),- isBreakGlass: true,- bypassReason: trimmedReason- },- tx- );-- return { updatedRequest: await approvalRequestDAL.findById(requestId, tx), grant: createdGrant };- });+ const { request: updatedRequest, bypassMetadata } = await approvalPolicyService.approveRequest(+ requestId,+ { bypassReason: trimmedReason },+ toApprovalActor(ctx),+ ApprovalPolicyType.PamAccess+ );- void notifyOfBreakGlass({- request,- account,- folderId,- duration: requestData.requestData.duration,- bypassReason: trimmedReason,- actorId: ctx.actorId,- orgId: ctx.actorOrgId,- projectId- }).catch((err) => {- logger.error(err, `Failed to send PAM break-glass notifications [requestId=${requestId}]`);- });+ if (!bypassMetadata) {+ throw new BadRequestError({+ message: "Break-glass could not be applied because this folder's approval configuration changed. Try again."+ });+ }return {request: updatedRequest,accountId,folderId,accountType: account.accountType,- grantId: grant.id,- policyId: policy.id,- policyName: policy.name,+ grantId: bypassMetadata.grantId,+ policyId: policy?.id ?? null,+ policyName: policy?.name,accountName: account.name,folderName: account.folderName,granteeName: request.requesterName,granteeEmail: request.requesterEmail,accessDuration: requestData.requestData.duration,- approverCount: bypassedApproverCount+ approverCount: bypassMetadata.approverCount};};@@ -1044,9 +380,7 @@ export const pamAccessRequestServiceFactory = ({breakGlass = false,...ctx}: TCreateAccessRequestDTO) => {- const isCredentialRequest = accessType === PamAccessType.Credential;const trimmedReason = reason?.trim() || undefined;- await verifyProductMembership(permissionService, projectId, ctx);if (!accountId && !path) {throw new BadRequestError({ message: "Either 'accountId' or 'path' is required" });@@ -1066,213 +400,32 @@ export const pamAccessRequestServiceFactory = ({throw new NotFoundError({ message: "Account not found" });}- // Approval is a layer on top of standing access: only users who already hold the underlying- // permission may request the temporary grant that unlocks it.- await checkAccountAccess(- permissionService,- account.id,- account.folderId,- projectId,- isCredentialRequest- ? ResourcePermissionPamResourceActions.ViewCredentials- : ResourcePermissionPamResourceActions.LaunchSessions,- ctx- );-- const accessControls = resolveAccessControls(account.templatePolicies);- if (!accessControls.requiresApproval) {- throw new BadRequestError({- message: isCredentialRequest- ? "This account does not require approval to view its credentials"- : "This account does not require approval"- });- }-- if (isCredentialRequest) {- const { decryptor } = await kmsService.createCipherPairWithDataKey({- type: KmsDataKey.SecretManager,- projectId- });- const credentials = normalizeCredentialAuthMethod(- account.accountType as PamAccountType,- JSON.parse(decryptor({ cipherTextBlob: account.encryptedCredentials }).toString("utf-8")) as Record<- string,- unknown- >- );- if (!hasRevealableCredential(account.accountType as PamAccountType, credentials)) {- throw new BadRequestError({ message: noRevealableCredentialMessage(account.name) });- }- }-- if (accessControls.requireReason && !trimmedReason) {- throw new BadRequestError({- name: "PAM_REASON_REQUIRED",- message: isCredentialRequest- ? "A reason is required to request credential access to this account"- : "A reason is required to request access to this account"- });- }-if (!account.folderId) {throw new BadRequestError({ message: "Account must be in a folder to require approval" });}- const policy = await findFolderPolicy(account.folderId);- if (!policy) {- throw new BadRequestError({ message: "No approval configuration found for this folder" });- }-- if (breakGlass) {- await assertBreakGlassEligible({- account,- folderId: account.folderId,- policyId: policy.id,- projectId,- userGroupIds: await getUserGroupIds(ctx.actorId, ctx.actorOrgId),- ctx- });- }-- const durationMs = parseDurationMs(duration);- const accessDuration = (- policy.constraints as { constraints?: { accessDuration?: { min?: string; max?: string } } } | null- )?.constraints?.accessDuration;- const minMs = accessDuration?.min ? ms(accessDuration.min) : undefined;- const maxMs = accessDuration?.max ? ms(accessDuration.max) : undefined;- if (minMs && durationMs < minMs) {- throw new BadRequestError({ message: `Access duration must be at least ${accessDuration?.min}` });- }- if (maxMs && durationMs > maxMs) {- throw new BadRequestError({ message: `Access duration must be at most ${accessDuration?.max}` });- }-- const existingPending = await approvalRequestDAL.find({- ...actorRequestFilter(ctx),- type: ApprovalPolicyType.PamAccess,- status: ApprovalRequestStatus.Pending,- projectId- });-- const hasPendingForAccount = existingPending.some((r) => {- const data = r.requestData as { version: number; requestData: TPamAccessRequestData } | null;- return (- data?.requestData?.accountId === account.id &&- (data?.requestData?.accessType ?? PamAccessType.Session) === accessType- );- });-- if (hasPendingForAccount) {- throw new BadRequestError({- message: isCredentialRequest- ? "You already have a pending credential request for this account"- : "You already have a pending request for this account"- });- }-- const policySteps = await approvalPolicyDAL.findStepsByPolicyId(policy.id);-- // A step with no approvers can never be reviewed, wedging the request forever. The dashboard hides- // the request action in this case, but that guard must also hold for the CLI and direct API callers.- if (policySteps.length === 0 || policySteps.some((s) => s.approvers.length === 0)) {- throw new BadRequestError({- message:- "This folder's approval policy has no approvers configured. Ask a folder admin to add approvers under the folder's Approvals tab, then submit your request again."- });- }-- const stepsForRequest = policySteps.map((s) => ({- name: s.name ?? null,- requiredApprovals: s.requiredApprovals,- notifyApprovers: s.notifyApprovers ?? true,- approvers: s.approvers- }));-- const isIdentityActor = ctx.actor === ActorType.IDENTITY;- const accessTypeLabel = isCredentialRequest ? "credential access" : "access";- const { name: requesterName, email: requesterEmail } = await resolveRequesterDisplay(ctx);-- const requestData = {- accountId: account.id,- folderId: account.folderId,- reason: trimmedReason,- duration,- accessType- } as unknown as TApprovalRequestData;+ const requester = await resolveRequesterDisplay(ctx);- const request = await createApprovalRequestWithSteps(+ const { request } = await approvalPolicyService.createRequest(+ ApprovalPolicyType.PamAccess,{- projectId,- organizationId: ctx.actorOrgId,- policyId: policy.id,- policyType: ApprovalPolicyType.PamAccess,- policySteps: stepsForRequest,- requestData,+ scope: ApprovalPolicyScope.PamFolder,+ scopeId: account.folderId,+ requestData: {+ accountId: account.id,+ folderId: account.folderId,+ reason: trimmedReason,+ duration,+ accessType+ },justification: trimmedReason,- requesterUserId: ctx.actor === ActorType.USER ? ctx.actorId : null,- machineIdentityId: ctx.actor === ActorType.IDENTITY ? ctx.actorId : null,- requesterName,- requesterEmail,- scopeType: ApprovalPolicyScope.PamFolder,- scopeId: account.folderId+ machineIdentityId: ctx.actor === ActorType.IDENTITY ? ctx.actorId : undefined,+ requesterName: requester.name,+ requesterEmail: requester.email},- {- approvalRequestDAL,- approvalRequestStepsDAL,- approvalRequestStepEligibleApproversDAL- }+ toApprovalActor(ctx));- const approvalUrl = `${getConfig().SITE_URL}/organizations/${ctx.actorOrgId}/pam/approval-requests?requestId=${request.id}`;-- const firstStep = stepsForRequest[0];- if (firstStep && !breakGlass) {- try {- await notifyApproversForStep({ ...firstStep, notifyApprovers: true }, request, {- userGroupMembershipDAL,- notificationService- });- } catch (err) {- logger.error(err, `Failed to send in-app notifications for PAM access request [requestId=${request.id}]`);- }-- try {- const approverUserIds = new Set<string>();- firstStep.approvers.filter((a) => a.type === ApproverType.User).forEach((a) => approverUserIds.add(a.id));-- const groupMemberLists = await Promise.all(- firstStep.approvers- .filter((a) => a.type === ApproverType.Group)- .map((a) => userGroupMembershipDAL.find({ groupId: a.id }))- );- groupMemberLists.forEach((members) => members.forEach((m) => approverUserIds.add(m.userId)));-- const approverUsers = approverUserIds.size > 0 ? await userDAL.find({ $in: { id: [...approverUserIds] } }) : [];- const recipients = approverUsers.filter((u) => u.email).map((u) => u.email as string);-- if (recipients.length > 0) {- await smtpService.sendMail({- recipients,- subjectLine: isCredentialRequest ? "PAM Credential Access Request" : "PAM Access Request",- template: SmtpTemplates.AccessPamRequest,- substitutions: {- requesterFullName: requesterName,- // Machine identities have no email; the template renders the label alone- requesterEmail: isIdentityActor ? "Machine Identity" : requesterEmail,- accountName: account.name,- folderName: account.folderName ?? undefined,- accessDuration: formatDuration(duration),- accessTypeLabel,- reason: trimmedReason,- approvalUrl- }- });- }- } catch (err) {- logger.error(err, `Failed to send approval emails for PAM access request [requestId=${request.id}]`);- }- }-if (breakGlass) {const result = await breakGlassRequest({requestId: request.id,@@ -1291,25 +444,6 @@ export const pamAccessRequestServiceFactory = ({};}- void triggerFolderSlackNotifications({- folderId: account.folderId,- event: PamNotificationEvent.AccessRequested,- orgId: ctx.actorOrgId,- notification: {- type: TriggerFeature.PAM_ACCESS_REQUESTED,- payload: {- requesterFullName: requesterName,- requesterEmail: isIdentityActor ? "Machine Identity" : requesterEmail,- accountName: account.name,- folderName: account.folderName ?? "",- accessDuration: formatDuration(duration),- accessTypeLabel,- reason: trimmedReason,- approvalUrl- }- }- });-return {request,accountId: account.id,@@ -1324,626 +458,61 @@ export const pamAccessRequestServiceFactory = ({const listRequests = async ({ projectId, folderId, status, offset, limit, ...ctx }: TListAccessRequestsDTO) => {await verifyProductMembership(permissionService, projectId, ctx);- // This is the folder admin audit view (all requesters' requests), so it requires folder-level- // approval management. An approver's own queue is served by listPendingMyApproval instead.if (!folderId) {throw new BadRequestError({ message: "folderId is required" });}- await assertFolderPolicyManagement(folderId, projectId, ctx);-- const filter: Record<string, unknown> = {- type: ApprovalPolicyType.PamAccess,- projectId- };-- if (status) filter.status = status;- // PAM requests store their folder as scopeId, so pagination/filtering happens at the DB level.- filter.scopeType = ApprovalPolicyScope.PamFolder;- filter.scopeId = folderId;-- const requests = await approvalRequestDAL.find(filter, {- sort: [["createdAt", "desc"]],- offset,- limit,- count: true- });- const totalCount = Number(requests[0]?.count ?? 0);- return {- requests: await attachGrantExpiry(await enrichRequestsWithNames(requests)),- totalCount- };- };-- // Whether the actor is currently an approver on the folder's live policy AND still holds an active- // folder membership. This is the same authority reviewRequest enforces, so the approver queue and- // the review action agree; the creation-time snapshot alone would leak requests (and requester PII)- // to users removed as approvers after the request was created.- const isLiveFolderApprover = async (- projectId: string,- folderId: string,- actorId: string,- userGroupIds: Set<string>- ): Promise<boolean> => {- const policy = await findFolderPolicy(folderId);- if (!policy) return false;- const steps = await approvalPolicyDAL.findStepsByPolicyId(policy.id);- const onLivePolicy = steps.some((step) => isUserEligibleApprover(step.approvers, actorId, userGroupIds));- if (!onLivePolicy) return false;- const activeMemberships = await findActiveFolderMemberships(projectId, folderId);- return activeMemberships.some(- (m) => m.actorUserId === actorId || (m.actorGroupId && userGroupIds.has(m.actorGroupId))+ const { requests, totalCount } = await approvalPolicyService.listScopeRequests(+ ApprovalPolicyType.PamAccess,+ ApprovalPolicyScope.PamFolder,+ folderId,+ { status, offset, limit },+ toApprovalActor(ctx));++ return { requests: await pamAccessApprovalResource.decorateRequests(requests), totalCount };};const listPendingMyApproval = async ({ projectId, folderId, ...ctx }: TListPendingMyApprovalDTO) => {await verifyProductMembership(permissionService, projectId, ctx);- const userGroupIds = await getUserGroupIds(ctx.actorId, ctx.actorOrgId);-- // Fast reject for users who are not a live approver on any PAM policy in the project.- const isApprover = await approvalPolicyDAL.isProjectApprover({- projectId,- userId: ctx.actorId,- groupIds: [...userGroupIds],- type: ApprovalPolicyType.PamAccess,- scopeType: ApprovalPolicyScope.PamFolder- });- if (!isApprover) return { requests: [] };-- const requests = await approvalRequestDAL.findByProjectId(ApprovalPolicyType.PamAccess, projectId);-- // Only pending requests whose creation-time snapshot lists the actor belong in the queue...- const candidates = requests.filter((request) => {- if (request.status !== ApprovalRequestStatus.Pending) return false;-- if (folderId) {- const data = request.requestData as { version: number; requestData: TPamAccessRequestData } | null;- if (data?.requestData?.folderId !== folderId) return false;- }-- const currentStep = request.steps.find((s) => s.stepNumber === request.currentStep);- if (!currentStep) return false;-- return isUserEligibleApprover(currentStep.approvers, ctx.actorId, userGroupIds);- });-- // ...but the snapshot is re-validated against each folder's live policy so requests whose approver- // set changed after creation (e.g. the actor was removed) drop out rather than leaking.- const involvedFolderIds = [- ...new Set(- candidates- .map((r) => (r.requestData as { requestData?: TPamAccessRequestData } | null)?.requestData?.folderId)- .filter((id): id is string => Boolean(id))- )- ];- const liveApproverFolders = new Set<string>();- for (const fId of involvedFolderIds) {- // eslint-disable-next-line no-await-in-loop- if (await isLiveFolderApprover(projectId, fId, ctx.actorId, userGroupIds)) {- liveApproverFolders.add(fId);- }- }-- const result = candidates.filter((r) => {- const fId = (r.requestData as { requestData?: TPamAccessRequestData } | null)?.requestData?.folderId;- return Boolean(fId && liveApproverFolders.has(fId));- });+ const { requests } = await approvalPolicyService.listPendingForApprover(+ ApprovalPolicyType.PamAccess,+ ApprovalPolicyScope.PamFolder,+ { projectId, scopeId: folderId },+ toApprovalActor(ctx)+ );- return { requests: await attachGrantExpiry(await enrichRequestsWithNames(result)) };+ return { requests: await pamAccessApprovalResource.decorateRequests(requests) };};const getCount = async ({ projectId, ...ctx }: TGetAccessRequestCountDTO) => {await verifyProductMembership(permissionService, projectId, ctx);- const userGroupIds = await getUserGroupIds(ctx.actorId, ctx.actorOrgId);-- const isApprover = await approvalPolicyDAL.isProjectApprover({+ return approvalPolicyService.countPendingForApprover(+ ApprovalPolicyType.PamAccess,+ ApprovalPolicyScope.PamFolder,projectId,- userId: ctx.actorId,- groupIds: [...userGroupIds],- type: ApprovalPolicyType.PamAccess,- scopeType: ApprovalPolicyScope.PamFolder- });-- // A non-approver can never have requests awaiting their approval.- if (!isApprover) {- return { pendingCount: 0, isApprover: false };- }-- const requests = await approvalRequestDAL.findByProjectId(ApprovalPolicyType.PamAccess, projectId);-- // Phase 1 enforces a single approval step, so matching any step is equivalent to the current step.- const pendingCount = requests.filter(- (request) =>- request.status === ApprovalRequestStatus.Pending &&- request.steps.some((step) => isUserEligibleApprover(step.approvers, ctx.actorId, userGroupIds))- ).length;-- return { pendingCount, isApprover: true };- };-- // The review sheet promises the requester will see the reviewer's comment; the notification- // center is where that happens, since a decided request disappears from the requester's UI.- const notifyRequesterOfDecision = async (- request: { requesterId?: string | null; organizationId: string },- decision: ApprovalRequestApprovalDecision,- accountName: string | undefined,- comment: string | undefined- ) => {- if (!request.requesterId) return;- try {- const approved = decision === ApprovalRequestApprovalDecision.Approved;- await notificationService.createUserNotifications([- {- userId: request.requesterId,- orgId: request.organizationId,- type: NotificationType.ACCESS_APPROVAL_REQUEST_UPDATED,- title: approved ? "Access request approved" : "Access request denied",- body: `Your access request for **${accountName ?? "a PAM account"}** was ${- approved ? "approved" : "denied"- }.${comment ? ` Reviewer comment: "${comment}"` : ""}`,- link: `/organizations/${request.organizationId}/pam/accounts`- }- ]);- } catch (err) {- logger.error(err, "Failed to notify PAM access requester of review decision");- }- };-- const reviewRequest = async ({ requestId, projectId, status, comment, ...ctx }: TReviewAccessRequestDTO) => {- await verifyProductMembership(permissionService, projectId, ctx);-- const request = await approvalRequestDAL.findById(requestId);- if (!request || request.projectId !== projectId || request.type !== ApprovalPolicyType.PamAccess) {- throw new NotFoundError({ message: "Request not found" });- }-- if (request.status !== ApprovalRequestStatus.Pending) {- throw new BadRequestError({ message: "Request is not pending" });- }-- if (request.expiresAt && new Date(request.expiresAt) < new Date()) {- await approvalRequestDAL.updateById(requestId, { status: ApprovalRequestStatus.Expired });- throw new BadRequestError({ message: "Request has expired" });- }-- // Self-approval is a conflict of interest and always blocked. Denying your own request is harmless- // (it only withdraws your own pending access), so it is allowed.- if (status === ApprovalRequestApprovalDecision.Approved && request.requesterId === ctx.actorId) {- throw new ForbiddenRequestError({ message: "You cannot approve your own request" });- }-- const requestData = request.requestData as { version: number; requestData: TPamAccessRequestData } | null;- const folderId = requestData?.requestData?.folderId;-- // The request snapshots the account's folder at creation time, but the account may have since been- // moved or deleted. Approving would then grant access governed by the old folder's approvers,- // bypassing the account's current folder policy, so block approval of a stale request. Rejection- // stays allowed so the stale request can be cleared.- if (status === ApprovalRequestApprovalDecision.Approved) {- const requestedAccountId = requestData?.requestData?.accountId;- const account = requestedAccountId ? await pamAccountDAL.findOne({ id: requestedAccountId }) : undefined;- if (!account || account.projectId !== projectId || account.folderId !== folderId) {- throw new BadRequestError({- message: "This request is no longer valid because the account has moved or been removed"- });- }- }-- const steps = await approvalRequestDAL.findStepsByRequestId(requestId);- const currentStepIndex = steps.findIndex((s) => s.stepNumber === request.currentStep);- if (currentStepIndex === -1) {- throw new BadRequestError({ message: "Current step not found" });- }-- const currentStep = steps[currentStepIndex];-- const userGroupIds = await getUserGroupIds(ctx.actorId, ctx.actorOrgId);-- // The actor must have been an eligible approver on this request's current step (snapshot at creation).- if (!isUserEligibleApprover(currentStep.approvers, ctx.actorId, userGroupIds)) {- throw new ForbiddenRequestError({ message: "You are not an eligible approver for this request" });- }-- // And must still be an approver on the folder's live policy. A missing policy means no one is- // currently authorized to review, so this is a denial rather than a skip.- if (folderId) {- const currentPolicy = await findFolderPolicy(folderId);- if (!currentPolicy) {- throw new ForbiddenRequestError({ message: "Approval policy no longer exists for this folder" });- }- const currentSteps = await approvalPolicyDAL.findStepsByPolicyId(currentPolicy.id);- const isCurrentApprover = currentSteps.some((step) =>- isUserEligibleApprover(step.approvers, ctx.actorId, userGroupIds)- );- if (!isCurrentApprover) {- throw new ForbiddenRequestError({ message: "You are no longer an eligible approver for this folder" });- }-- // Approver rows are only stripped on explicit removal from the folder, not when a temporary- // membership lapses, so re-check that the actor still holds an active folder membership.- const activeMemberships = await findActiveFolderMemberships(projectId, folderId);- const hasActiveMembership = activeMemberships.some(- (m) => m.actorUserId === ctx.actorId || (m.actorGroupId && userGroupIds.has(m.actorGroupId))- );- if (!hasActiveMembership) {- throw new ForbiddenRequestError({ message: "You are no longer an eligible approver for this folder" });- }- }-- const hasAlreadyReviewed = currentStep.approvals.some(- (a: { approverUserId: string }) => a.approverUserId === ctx.actorId- );- if (hasAlreadyReviewed) {- throw new BadRequestError({ message: "You have already reviewed this request" });- }-- if (status === ApprovalRequestApprovalDecision.Rejected) {- const updatedRequest = await approvalRequestDAL.transaction(async (tx) => {- // Row lock serializes concurrent reviews; the pre-transaction checks may be stale by now- const locked = await approvalRequestDAL.findByIdForUpdate(requestId, tx);- if (!locked || locked.status !== ApprovalRequestStatus.Pending) {- throw new BadRequestError({ message: "Request is not pending" });- }- const lockedStep = steps.find((s) => s.stepNumber === locked.currentStep);- if (!lockedStep) {- throw new BadRequestError({ message: "Current step not found" });- }- if (!isUserEligibleApprover(lockedStep.approvers, ctx.actorId, userGroupIds)) {- throw new ForbiddenRequestError({ message: "You are not an eligible approver for this request" });- }-- await approvalRequestApprovalsDAL.create(- {- stepId: lockedStep.id,- approverUserId: ctx.actorId,- decision: ApprovalRequestApprovalDecision.Rejected,- comment- },- tx- );- await approvalRequestDAL.updateById(requestId, { status: ApprovalRequestStatus.Rejected }, tx);- return approvalRequestDAL.findById(requestId, tx);- });-- const rejectedAccountId = requestData?.requestData?.accountId;- const rejectedAccount = rejectedAccountId- ? await pamAccountDAL.findOne({ id: rejectedAccountId, projectId })- : undefined;- await notifyRequesterOfDecision(- updatedRequest,- ApprovalRequestApprovalDecision.Rejected,- rejectedAccount?.name,- comment- );-- if (folderId) {- void 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 };- }-- const { updatedRequest, nextStepToNotify } = await approvalRequestDAL.transaction(async (tx) => {- let nextStep = null;-- // Row lock serializes concurrent approvals; re-check state and re-read the approval count- // under the lock so two simultaneous approvers can't both complete the step or double-grant- const locked = await approvalRequestDAL.findByIdForUpdate(requestId, tx);- if (!locked || locked.status !== ApprovalRequestStatus.Pending) {- throw new BadRequestError({ message: "Request is not pending" });- }-- const lockedStepIndex = steps.findIndex((s) => s.stepNumber === locked.currentStep);- const lockedStep = steps[lockedStepIndex];- if (!lockedStep) {- throw new BadRequestError({ message: "Current step not found" });- }- if (!isUserEligibleApprover(lockedStep.approvers, ctx.actorId, userGroupIds)) {- throw new ForbiddenRequestError({ message: "You are not an eligible approver for this request" });- }-- const stepApprovals = await approvalRequestApprovalsDAL.find({ stepId: lockedStep.id }, { tx });- if (stepApprovals.some((a) => a.approverUserId === ctx.actorId)) {- throw new BadRequestError({ message: "You have already reviewed this request" });- }-- await approvalRequestApprovalsDAL.create(- {- stepId: lockedStep.id,- approverUserId: ctx.actorId,- decision: ApprovalRequestApprovalDecision.Approved,- comment- },- tx- );-- const newApprovalCount = stepApprovals.length + 1;- if (newApprovalCount >= lockedStep.requiredApprovals) {- await approvalRequestStepsDAL.updateById(- lockedStep.id,- { status: ApprovalRequestStepStatus.Completed, completedAt: new Date() },- tx- );-- const nextStepData = steps[lockedStepIndex + 1];- if (nextStepData) {- await approvalRequestDAL.updateById(requestId, { currentStep: locked.currentStep + 1 }, tx);- await approvalRequestStepsDAL.updateById(- nextStepData.id,- { status: ApprovalRequestStepStatus.InProgress, startedAt: new Date() },- tx- );- nextStep = nextStepData;- } else {- await approvalRequestDAL.updateById(requestId, { status: ApprovalRequestStatus.Approved }, tx);-- if (requestData?.requestData) {- const durationMs = parseDurationMs(requestData.requestData.duration);- const expiresAt = new Date(Date.now() + durationMs);- await approvalRequestGrantsDAL.create(- {- projectId: request.projectId,- requestId: request.id,- // The request carries exactly one actor column; mirror it onto the grant- granteeUserId: request.requesterId,- granteeMachineIdentityId: request.machineIdentityId,- status: ApprovalRequestGrantStatus.Active,- type: ApprovalPolicyType.PamAccess,- attributes: {- accountId: requestData.requestData.accountId,- folderId: requestData.requestData.folderId,- accessType: requestData.requestData.accessType ?? PamAccessType.Session- },- expiresAt- },- tx- );- }- }- }-- const updated = await approvalRequestDAL.findById(requestId, tx);- return { updatedRequest: updated, nextStepToNotify: nextStep };- });-- if (nextStepToNotify) {- await notifyApproversForStep(- {- name: nextStepToNotify.name ?? null,- requiredApprovals: nextStepToNotify.requiredApprovals,- notifyApprovers: true,- approvers: nextStepToNotify.approvers- },- updatedRequest,- { userGroupMembershipDAL, notificationService }- );- }-- if (updatedRequest.status === ApprovalRequestStatus.Approved) {- const approvedAccountId = requestData?.requestData?.accountId;- const approvedAccount = approvedAccountId- ? await pamAccountDAL.findOne({ id: approvedAccountId, projectId })- : undefined;- await notifyRequesterOfDecision(- updatedRequest,- ApprovalRequestApprovalDecision.Approved,- approvedAccount?.name,- comment- );-- if (folderId) {- void 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 };- };-- // Marks a grant Revoked and terminates the grantee's live sessions on the granted account.- //- // Returns the tunnel-cancellation callback rather than firing it, so a caller that revokes inside a- // transaction which can still roll back (account deletion) only cuts tunnels once the revocation is- // durable. Callers outside a transaction invoke it immediately.- const revokeGrantRow = async (- grant: TApprovalRequestGrants,- actorId: string,- reason: string,- tx?: Knex- ): Promise<{ revoked: TApprovalRequestGrants; sendCancellationSignals: () => void }> => {- const revoked = await approvalRequestGrantsDAL.updateById(- grant.id,- {- status: ApprovalRequestGrantStatus.Revoked,- revokedByUserId: actorId,- revokedAt: new Date(),- revocationReason: reason- },- tx+ toApprovalActor(ctx));-- const noSignals = { revoked, sendCancellationSignals: () => {} };-- // Sessions mirror the grant's actor column: a machine identity session carries identityId with a null- // userId, so scope the sweep to whichever column the grant was issued to. granteeUserId is SET NULL- // when the grantee user is deleted, leaving a grant with neither column — filtering on a null userId- // there would match every machine identity session on the account, so bail instead.- let granteeFilter: { userId: string } | { identityId: string } | null = null;- if (grant.granteeMachineIdentityId) granteeFilter = { identityId: grant.granteeMachineIdentityId };- else if (grant.granteeUserId) granteeFilter = { userId: grant.granteeUserId };-- const attrs = grant.attributes as { accountId?: string; accessType?: PamAccessType } | null;- if (!attrs?.accountId || !granteeFilter) return noSignals;-- if ((attrs.accessType ?? PamAccessType.Session) === PamAccessType.Credential) return noSignals;-- // Cover both active and starting sessions; a session mid-handshake would otherwise slip past- // revocation and go live. terminateSessionById flips the row, and the ALPN signal cuts the live- // tunnel, since neither the gateway nor the web-access loop watches the status column.- const liveSessions = await pamSessionDAL.find(- {- accountId: attrs.accountId,- ...granteeFilter,- $in: { status: [PamSessionStatus.Active, PamSessionStatus.Starting] }- },- { tx }- );- if (liveSessions.length === 0) return noSignals;-- const actor = await userDAL.findById(actorId, tx);- const sendCancellationSignals = await terminatePamSessions({- sessions: liveSessions,- actorId,- actorEmail: actor?.email ?? "",- pamSessionDAL,- gatewayV2Service,- tx- });-- return { revoked, sendCancellationSignals };- };-- const revokeGrant = async ({ requestId, projectId, ...ctx }: TRevokeAccessRequestDTO) => {- const { hasRole } = await verifyProductMembership(permissionService, projectId, ctx);-- const grant = await approvalRequestGrantsDAL.findOne({- requestId,- type: ApprovalPolicyType.PamAccess,- status: ApprovalRequestGrantStatus.Active- });-- if (!grant || grant.projectId !== projectId) {- throw new NotFoundError({ message: "No active approval found for this request" });- }-- const requestData = (await approvalRequestDAL.findById(requestId))?.requestData as {- version: number;- requestData: TPamAccessRequestData;- } | null;-- const accountId = requestData?.requestData?.accountId;- const account = accountId ? (await pamAccountDAL.find({ id: accountId, projectId }))[0] : undefined;-- if (account) {- await checkAccountAccess(- permissionService,- account.id,- account.folderId,- projectId,- ResourcePermissionPamResourceActions.RevokeGrants,- ctx- );- } else if (!hasRole(PamProductRole.Admin)) {- // The grant's account can't be resolved (missing from requestData or already deleted), so there- // is no resource to check RevokeGrants against. Fail closed to product admins.- throw new ForbiddenRequestError({ message: "You are not authorized to revoke this approval" });- }-- const { revoked: revokedGrant, sendCancellationSignals } = await revokeGrantRow(- grant,- ctx.actorId,- "Revoked by admin"- );- sendCancellationSignals();-- return { grant: revokedGrant, accountId, folderId: requestData?.requestData?.folderId, grantId: grant.id };};- // Approval policies, requests, and grants reference folders/accounts by scopeId or by a JSON id- // with no FK, so deleting a folder or account leaves them orphaned. These run inside the folder/- // account delete transaction to keep the approval state consistent.+ const cleanupFolderResources = (folderId: string, tx: Knex) =>+ approvalPolicyService.reapScope(ApprovalPolicyType.PamAccess, ApprovalPolicyScope.PamFolder, folderId, tx);- const cleanupFolderResources = async (folderId: string, tx: Knex) => {- // Deleting the policy cascades to its steps and approvers, which also stops the now-defunct- // folder from keeping its approvers "active" for approver-eligibility scans.- const policy = await approvalPolicyDAL.findOne(- { type: ApprovalPolicyType.PamAccess, scopeType: ApprovalPolicyScope.PamFolder, scopeId: folderId },- tx- );- if (policy) {- await approvalPolicyDAL.deleteById(policy.id, tx);- }-- await approvalRequestDAL.update(- {- type: ApprovalPolicyType.PamAccess,- scopeType: ApprovalPolicyScope.PamFolder,- scopeId: folderId,- status: ApprovalRequestStatus.Pending- },- { status: ApprovalRequestStatus.Cancelled },- tx- );- };-- // Returns the callback that cuts the tunnels of the sessions it terminated. It runs inside the caller's- // delete transaction, which can still fail, so the signals are the caller's to fire after COMMIT.- const cleanupAccountResources = async (+ const cleanupAccountResources = ({accountId,- folderId,projectId,actorId- }: { accountId: string; folderId: string | null | undefined; projectId: string; actorId: string },+ }: { accountId: string; folderId?: string | null; projectId: string; actorId: string },tx: Knex- ): Promise<() => void> => {- // Requests are folder-scoped with the account id in requestData JSON, so filter in memory.- if (folderId) {- const pending = await approvalRequestDAL.find(- {- type: ApprovalPolicyType.PamAccess,- scopeType: ApprovalPolicyScope.PamFolder,- scopeId: folderId,- status: ApprovalRequestStatus.Pending- },- { tx }- );- const staleIds = pending- .filter((r) => {- const data = r.requestData as { version: number; requestData: TPamAccessRequestData } | null;- return data?.requestData?.accountId === accountId;- })- .map((r) => r.id);- if (staleIds.length > 0) {- await approvalRequestDAL.update({ $in: { id: staleIds } }, { status: ApprovalRequestStatus.Cancelled }, tx);- }- }-- const activeGrants = await approvalRequestGrantsDAL.find(- { type: ApprovalPolicyType.PamAccess, status: ApprovalRequestGrantStatus.Active, projectId },- { tx }+ ) =>+ approvalPolicyService.reapSubject(+ ApprovalPolicyType.PamAccess,+ { projectId, inputs: { accountId } as TPamAccessPolicyInputs, actorId, reason: "Account deleted" },+ tx);- const pendingSignals: (() => void)[] = [];- for (const grant of activeGrants) {- const attrs = grant.attributes as { accountId?: string } | null;- if (attrs?.accountId === accountId) {- // eslint-disable-next-line no-await-in-loop- const { sendCancellationSignals } = await revokeGrantRow(grant, actorId, "Account deleted", tx);- pendingSignals.push(sendCancellationSignals);- }- }-- return () => pendingSignals.forEach((send) => send());- };const checkGrant = async ({accountId,@@ -1951,106 +520,39 @@ export const pamAccessRequestServiceFactory = ({projectId,accessType = PamAccessType.Session,...actorCtx- }: TCheckGrantDTO): Promise<TApprovalRequestGrants | null> => {- const grants = await approvalRequestGrantsDAL.find({- ...actorGrantFilter(actorCtx),- type: ApprovalPolicyType.PamAccess,- status: ApprovalRequestGrantStatus.Active,- projectId+ }: TCheckGrantDTO): Promise<TApprovalRequestGrants | null> =>+ approvalPolicyService.getActiveGrant(ApprovalPolicyType.PamAccess, projectId, toSubjectActor(actorCtx), {+ accountId,+ folderId: accountFolderId as string,+ accessType});- const now = new Date();- // Match the grant's snapshot folder against the account's CURRENT folder: a grant approved while- // the account lived in another folder must not authorize launch after the account is moved into a- // different (gated) folder whose approvers never reviewed it.- const forAccount = grants.filter((g) => {- const attrs = g.attributes as {- accountId?: string;- folderId?: string | null;- accessType?: PamAccessType;- } | null;- return (- attrs?.accountId === accountId &&- (attrs?.folderId ?? null) === (accountFolderId ?? null) &&- (attrs?.accessType ?? PamAccessType.Session) === accessType- );- });- // Prefer a still-valid grant; otherwise return an expired one (rather than null) so the caller can- // distinguish "grant expired" from "no grant" and signal PAM_GRANT_EXPIRED vs PAM_APPROVAL_REQUIRED.- const valid = forAccount.find((g) => !g.expiresAt || new Date(g.expiresAt) > now);- return valid ?? forAccount[0] ?? null;- };-const getAccessStatusBatch = async (actorCtx: TAccessRequestActor,accountIds: string[],projectId: string,accessType: PamAccessType = PamAccessType.Session- ): Promise<- Map<string, { accessStatus: PamAccessStatus; grantExpiresAt: Date | null; pendingRequestId: string | null }>- > => {- const result = new Map<- string,- { accessStatus: PamAccessStatus; grantExpiresAt: Date | null; pendingRequestId: string | null }- >();- if (accountIds.length === 0) return result;-- const now = new Date();-- const activeGrants = await approvalRequestGrantsDAL.find({- ...actorGrantFilter(actorCtx),- type: ApprovalPolicyType.PamAccess,- status: ApprovalRequestGrantStatus.Active,- projectId- });-- for (const grant of activeGrants) {- const isExpired = Boolean(grant.expiresAt && new Date(grant.expiresAt) <= now);- const attrs = grant.attributes as { accountId?: string; accessType?: PamAccessType } | null;- const grantAccessType = attrs?.accessType ?? PamAccessType.Session;- if (!isExpired && grantAccessType === accessType && attrs?.accountId && accountIds.includes(attrs.accountId)) {- result.set(attrs.accountId, {- accessStatus: PamAccessStatus.Granted,- grantExpiresAt: grant.expiresAt ? new Date(grant.expiresAt) : null,- pendingRequestId: null- });- }- }-- const pendingRequests = await approvalRequestDAL.find({- ...actorRequestFilter(actorCtx),- type: ApprovalPolicyType.PamAccess,- status: ApprovalRequestStatus.Pending,- projectId- });-- for (const request of pendingRequests) {- const data = request.requestData as { version: number; requestData: TPamAccessRequestData } | null;- const acctId = data?.requestData?.accountId;- const requestAccessType = data?.requestData?.accessType ?? PamAccessType.Session;- if (requestAccessType === accessType && acctId && accountIds.includes(acctId) && !result.has(acctId)) {- result.set(acctId, {- accessStatus: PamAccessStatus.Pending,- grantExpiresAt: null,- pendingRequestId: request.id- });- }- }+ ) => {+ const statuses = await approvalPolicyService.getAccessStatuses(+ ApprovalPolicyType.PamAccess,+ projectId,+ toSubjectActor(actorCtx),+ accountIds.map((accountId) => ({ accountId, accessType }))+ );- return result;+ return new Map(accountIds.map((accountId, i) => [accountId, statuses[i]]));};- // A folder counts as "configured" only when its policy has at least one approver, so an- // empty policy (e.g. after the last approver is removed) surfaces the unavailable flag.- const getFolderPolicyConfigured = async (folderIds: string[]): Promise<Set<string>> => {- if (folderIds.length === 0) return new Set();- const scopeIds = await approvalPolicyDAL.findScopeIdsWithApprovers({- type: ApprovalPolicyType.PamAccess,- scopeType: ApprovalPolicyScope.PamFolder,- scopeIds: folderIds- });- return new Set(scopeIds);- };+ // A folder counts as "configured" only when its policy has at least one approver, so an empty policy+ // surfaces the unavailable flag.+ const getFolderPolicyConfigured = async (folderIds: string[]): Promise<Set<string>> =>+ new Set(+ await approvalPolicyService.getScopeIdsWithApprovers(+ ApprovalPolicyType.PamAccess,+ ApprovalPolicyScope.PamFolder,+ folderIds+ )+ );// Of the given folders, the ones where this actor is a named break-glass user. Drives whether the// account list offers the break-glass action at all.@@ -2058,35 +560,16 @@ export const pamAccessRequestServiceFactory = ({folderIds: string[],actorCtx: TAccessRequestActor,orgId: string- ): Promise<Set<string>> => {- const result = new Set<string>();- if (folderIds.length === 0 || actorCtx.actor !== ActorType.USER) return result;-- const policies = await approvalPolicyDAL.find({- type: ApprovalPolicyType.PamAccess,- scopeType: ApprovalPolicyScope.PamFolder,- $in: { scopeId: folderIds }- });- if (policies.length === 0) return result;-- const [userGroupIds, bypassersByPolicyId] = await Promise.all([- getUserGroupIds(actorCtx.actorId, orgId),- approvalPolicyDAL.findBypassersByPolicyIds(policies.map((p) => p.id))- ]);-- for (const policy of policies) {- const isApprover = (bypassersByPolicyId[policy.id] ?? []).some(- (b) =>- (b.type === ApproverType.User && b.id === actorCtx.actorId) ||- (b.type === ApproverType.Group && userGroupIds.has(b.id))- );- if (isApprover && policy.scopeId) result.add(policy.scopeId);- }- return result;- };+ ): Promise<Set<string>> =>+ new Set(+ await approvalPolicyService.getBypassableScopeIds(+ ApprovalPolicyType.PamAccess,+ ApprovalPolicyScope.PamFolder,+ folderIds,+ { id: actorCtx.actorId, type: actorCtx.actor, orgId, authMethod: null }+ )+ );- // Requesters need to know who to ping for approval, so this is gated on the permission the- // request itself needs rather than the policy-management check used for the full config.const getAccountApprovers = async ({accountId,projectId,@@ -2112,80 +595,17 @@ export const pamAccessRequestServiceFactory = ({);if (!account.folderId) return { steps: [] };- const policy = await findFolderPolicy(account.folderId);- const livePolicySteps = policy ? await approvalPolicyDAL.findStepsByPolicyId(policy.id) : [];-- // A pending request is reviewed against its snapshotted approvers AND the live policy, so its- // workflow shows the intersection; the compose state shows the live policy a new request- // would snapshot.- let policySteps = livePolicySteps.map((step) => ({- requiredApprovals: step.requiredApprovals,- approvers: step.approvers- }));-- const pendingRequests = await approvalRequestDAL.find({- ...actorRequestFilter(ctx),- type: ApprovalPolicyType.PamAccess,- status: ApprovalRequestStatus.Pending,- projectId- });- const pendingForAccount = pendingRequests.find((r) => {- const data = r.requestData as { version: number; requestData: TPamAccessRequestData } | null;- return (- data?.requestData?.accountId === account.id &&- (data?.requestData?.accessType ?? PamAccessType.Session) === accessType- );- });-- if (pendingForAccount) {- const liveApproverKeys = new Set(- livePolicySteps.flatMap((step) => step.approvers.map((a) => `${a.type}:${a.id}`))- );- const requestSteps = await approvalRequestDAL.findStepsByRequestId(pendingForAccount.id);- policySteps = requestSteps.map((step) => ({- requiredApprovals: step.requiredApprovals,- approvers: step.approvers.filter((a) => liveApproverKeys.has(`${a.type}:${a.id}`))- }));- }-- if (policySteps.length === 0) return { steps: [] };-- const approverEntries = policySteps.flatMap((s) => s.approvers);- const userIds = approverEntries.filter((a) => a.type === ApproverType.User).map((a) => a.id);- const groupIds = approverEntries.filter((a) => a.type === ApproverType.Group).map((a) => a.id);-- const [users, groups, groupMemberships] = await Promise.all([- userIds.length > 0 ? userDAL.find({ $in: { id: userIds } }) : [],- groupIds.length > 0 ? groupDAL.find({ $in: { id: groupIds } }) : [],- groupIds.length > 0 ? userGroupMembershipDAL.find({ $in: { groupId: groupIds } }) : []- ]);- const userNameById = new Map(- users.map((u) => [- u.id,- [u.firstName, u.lastName].filter(Boolean).join(" ") || u.username || u.email || "Unknown user"- ])+ return approvalPolicyService.getApproverRoster(+ ApprovalPolicyType.PamAccess,+ ApprovalPolicyScope.PamFolder,+ {+ projectId,+ scopeId: account.folderId,+ inputs: { accountId: account.id, accessType } as TPamAccessPolicyInputs+ },+ toSubjectActor(ctx));- const groupNameById = new Map(groups.map((g) => [g.id, g.name]));- const groupMemberCounts = new Map<string, number>();- groupMemberships.forEach((m) => {- if (m.groupId) groupMemberCounts.set(m.groupId, (groupMemberCounts.get(m.groupId) ?? 0) + 1);- });-- return {- steps: policySteps.map((step) => ({- requiredApprovals: step.requiredApprovals,- approvers: step.approvers.map((a) =>- a.type === ApproverType.User- ? { type: ApproverType.User, name: userNameById.get(a.id) ?? "Unknown user" }- : {- type: ApproverType.Group,- name: groupNameById.get(a.id) ?? "Unknown group",- memberCount: groupMemberCounts.get(a.id) ?? 0- }- )- }))- };};return {@@ -2197,8 +617,6 @@ export const pamAccessRequestServiceFactory = ({listRequests,listPendingMyApproval,getCount,- reviewRequest,- revokeGrant,checkGrant,getAccessStatusBatch,getFolderPolicyConfigured,diff --git a/backend/src/ee/services/pam-account/pam-account-service.ts b/backend/src/ee/services/pam-account/pam-account-service.tsindex 711bdf30d1..34e94778a6 100644--- a/backend/src/ee/services/pam-account/pam-account-service.ts+++ b/backend/src/ee/services/pam-account/pam-account-service.ts@@ -19,6 +19,7 @@ import { hasPostgresErrorCode } from "@app/lib/errors/postgres";import { logger } from "@app/lib/logger";import { createSshKeyPair, SshCertKeyAlgorithm } from "@app/lib/ssh";import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";+import { ApprovalAccessStatus } from "@app/services/approval-policy/approval-policy-types";import { ActorType } from "@app/services/auth/auth-type";import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { KmsDataKey } from "@app/services/kms/kms-types";@@ -29,14 +30,7 @@ import { TOrgDALFactory } from "@app/services/org/org-dal";import { TUserDALFactory } from "@app/services/user/user-dal";import { testConnectionWithGateway } from "../gateway-v2/gateway-v2-fns";-import {- PamAccessStatus,- PamAccessType,- PamAccountType,- PamHeartbeatStatus,- PamProductRole,- PamSessionStatus-} from "../pam/pam-enums";+import { PamAccessType, PamAccountType, PamHeartbeatStatus, PamProductRole, PamSessionStatus } from "../pam/pam-enums";import { enforceMfa } from "../pam/pam-mfa";import {accountAccessAllows,@@ -353,13 +347,15 @@ export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) =>requiresApproval,supportsCredentialReveal: revealableById.get(a.id) ?? false,requireReason,- accessStatus: requiresApproval ? (statusEntry?.accessStatus ?? PamAccessStatus.None) : PamAccessStatus.None,+ accessStatus: requiresApproval+ ? (statusEntry?.accessStatus ?? ApprovalAccessStatus.None)+ : ApprovalAccessStatus.None,grantExpiresAt: statusEntry?.grantExpiresAt ?? null,pendingRequestId: statusEntry?.pendingRequestId ?? null,canBreakGlass: allowBreakGlass && !!a.folderId && breakGlassFolders.has(a.folderId),credentialAccessStatus: requiresApproval- ? (credentialStatusEntry?.accessStatus ?? PamAccessStatus.None)- : PamAccessStatus.None,+ ? (credentialStatusEntry?.accessStatus ?? ApprovalAccessStatus.None)+ : ApprovalAccessStatus.None,credentialPendingRequestId: credentialStatusEntry?.pendingRequestId ?? null,permissions: permissionsByAccountId.get(a.id) ?? [],createdAt: a.createdAt,@@ -1241,7 +1237,9 @@ export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) =>// Machine identities cannot satisfy MFA, so launch rejects them outright (see// pam-session-service). Callers acting as an identity should treat this as unusable.requireMfa,- accessStatus: requiresApproval ? (statusEntry?.accessStatus ?? PamAccessStatus.None) : PamAccessStatus.None,+ accessStatus: requiresApproval+ ? (statusEntry?.accessStatus ?? ApprovalAccessStatus.None)+ : ApprovalAccessStatus.None,grantExpiresAt: statusEntry?.grantExpiresAt ?? null,pendingRequestId: statusEntry?.pendingRequestId ?? null,canBreakGlass: allowBreakGlass && !!a.folderId && breakGlassFolders.has(a.folderId),diff --git a/backend/src/ee/services/pam-session/pam-session-service.ts b/backend/src/ee/services/pam-session/pam-session-service.tsindex 7f5ab12aa2..a476d5f1dd 100644--- a/backend/src/ee/services/pam-session/pam-session-service.ts+++ b/backend/src/ee/services/pam-session/pam-session-service.ts@@ -8,6 +8,7 @@ import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/import { ms } from "@app/lib/ms";import { alphaNumericNanoId } from "@app/lib/nanoid";import { createSshCert, createSshKeyPair, SshCertKeyAlgorithm, SshCertType } from "@app/lib/ssh";+import { ApprovalAccessStatus } from "@app/services/approval-policy/approval-policy-types";import { ActorType } from "@app/services/auth/auth-type";import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { KmsDataKey } from "@app/services/kms/kms-types";@@ -20,7 +21,6 @@ import { TUserDALFactory } from "@app/services/user/user-dal";import {PamAccessMethod,- PamAccessStatus,PamAccountType,PamPostgresAuthMethod,PamProductRole,@@ -554,7 +554,7 @@ export const pamSessionServiceFactory = ({message: "Access request required",details: {requireReason: policy.requireReason,- hasPendingRequest: statusMap.get(account.id)?.accessStatus === PamAccessStatus.Pending,+ hasPendingRequest: statusMap.get(account.id)?.accessStatus === ApprovalAccessStatus.Pending,hasApprovalPolicy: Boolean(account.folderId && foldersWithApprovalPolicy.has(account.folderId))}});diff --git a/backend/src/ee/services/pam/CLAUDE.md b/backend/src/ee/services/pam/CLAUDE.mdindex a56b03f0b7..d08845818a 100644--- a/backend/src/ee/services/pam/CLAUDE.md+++ b/backend/src/ee/services/pam/CLAUDE.md@@ -23,7 +23,7 @@ All PAM services live under `backend/src/ee/services/pam-*/`:| `pam-session-recording/` | Recording chunk storage/retrieval + storage providers || `pam-membership/` | Product + resource membership management || `pam-project/` | PAM project bootstrap + resolver |-| `pam-access-request/` | Folder approval config, access-request lifecycle, chat notifications |+| `pam-access-request/` | PAM's face on the shared approvals system: folder config, notifications, read models, approval resource || `pam-discovery/` | Discovery sources → staged accounts for import |Routes: `backend/src/ee/routes/v1/pam-routers/`. DI wiring: `backend/src/server/routes/index.ts` (narrow@@ -138,6 +138,24 @@ live in a process-wide map keyed by the driver's request id rather than on the ptest compares the login's `sessionInfo` against what was asked for, because Snowflake accepts a warehouseor role the credential can't use and silently leaves it unset.+## Approvals++**PAM approvals run on the shared approval system** (`backend/src/services/approval-policy/`), which+owns the whole lifecycle. PAM's contribution is one `TApprovalResource`+(`pam-access-request/pam-access-approval-resource.ts`), with its schemas under `approval-policy/pam-access/`.++`pam-access-request-service.ts` is the product-facing entry point, not a second implementation: it+resolves the account a CLI path names, delegates to `approvalPolicyService`, sends PAM's notifications,+and owns the access read models (`checkGrant`, `getAccessStatusBatch`, …). **A new PAM approval rule+belongs in the resource, never in that service**, or the CLI, the dashboard and the shared API stop+agreeing about what is allowed.++PAM is registered on the generic `/v1/approval-policies/pam-access/...` endpoints, which the dashboard+uses for approve, reject and grant revocation; the resource's `buildAuditEvent` is what keeps those+routes emitting PAM's own audit events, so folder and account auditors still see them. `/v1/pam/access-requests`+keeps only what the generic API cannot express: the CLI's `folderName/accountName` create, the paginated+folder list, the approver queue and count, the approver roster, and the folder notification configs.+## Policies & Settings**Policies** are governance controls on a template (MFA, reason, session duration, command-blocking),@@ -149,11 +167,14 @@ template's `settings` column, not `policies`. Both are edited on the template de**Break-glass** lets a requester self-approve their own pending request, and needs **both** gates open:the account's template carries `allow-break-glass`, *and* the folder's approval policy names the actor in`approval_policy_bypassers`. Neither alone is sufficient, and an empty bypasser list means **nobody** —-the shared `approval-policy-service` treats an empty list as everybody, which is the opposite rule, so do-not reuse its predicate. `allow-break-glass` resolves to false without `requires-approval`, since there is-then no approval to skip. Saving the folder config keeps the policy's `enforcementLevel` in step with the-list (`soft` when non-empty), and omitting `breakGlassUsers` entirely leaves the stored list alone so a-steps-only client can't switch break-glass off by accident. The grant records `isBreakGlass` ++the shared service's default reads an empty list as everybody, which is the opposite rule, so PAM+overrides it from the resource (`isBreakGlassEligible`) rather than anyone re-deriving the predicate. The+resource settles it once and exposes it two ways: a predicate for the `canBreakGlass` affordance, and an+assertion that names the failing gate. `allow-break-glass` resolves to false without `requires-approval`, since there is+then no approval to skip. `enforcementLevel` is **not** part of this: the shared default treats `soft` as+the opt-in to bypass, but PAM's two gates are the whole rule, so the folder config never writes that+column and the resource never reads it (a PAM policy stays `hard`). Omitting `breakGlassUsers` entirely+leaves the stored list alone so a steps-only client can't switch break-glass off by accident. The grant records `isBreakGlass` +`bypassReason`, and `PAM_ACCESS_POLICY_BYPASSED` must carry `accountId`/`folderId` or the event is hiddenfrom folder and account auditors (see the audit-log gotcha under Permissions).diff --git a/backend/src/ee/services/pam/pam-enums.ts b/backend/src/ee/services/pam/pam-enums.tsindex 336dce1f55..8c0de0ac8b 100644--- a/backend/src/ee/services/pam/pam-enums.ts+++ b/backend/src/ee/services/pam/pam-enums.ts@@ -78,13 +78,6 @@ export enum PamAccessType {Credential = "credential"}-// The caller's just-in-time approval state for an account gated behind an access request flow-export enum PamAccessStatus {- None = "none",- Pending = "pending",- Granted = "granted"-}-export enum PamMemberKind {User = "user",Group = "group",diff --git a/backend/src/ee/services/pki-acme/pki-acme-service.ts b/backend/src/ee/services/pki-acme/pki-acme-service.tsindex 2d848a09c0..83d818d9eb 100644--- a/backend/src/ee/services/pki-acme/pki-acme-service.ts+++ b/backend/src/ee/services/pki-acme/pki-acme-service.ts@@ -22,7 +22,6 @@ import { logger } from "@app/lib/logger";import { ms } from "@app/lib/ms";import { TApprovalPolicyDALFactory } from "@app/services/approval-policy/approval-policy-dal";import { ApprovalPolicyType } from "@app/services/approval-policy/approval-policy-enums";-import { APPROVAL_POLICY_FACTORY_MAP } from "@app/services/approval-policy/approval-policy-factory";import { TApprovalPolicyServiceFactory } from "@app/services/approval-policy/approval-policy-service";import {TCertRequestPolicy,@@ -188,7 +187,7 @@ type TPkiAcmeServiceFactoryDep = {pkiAcmeQueueService: Pick<TPkiAcmeQueueServiceFactory, "queueChallengeValidation">;auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;approvalPolicyDAL: Pick<TApprovalPolicyDALFactory, "findByProjectId" | "findStepsByPolicyId">;- approvalPolicyService: Pick<TApprovalPolicyServiceFactory, "createRequestFromPolicy">;+ approvalPolicyService: Pick<TApprovalPolicyServiceFactory, "createRequestFromPolicy" | "matchPolicy">;certificateRequestDAL: Pick<TCertificateRequestDALFactory, "create" | "updateById" | "transitionFromPending">;pkiApplicationProfileDAL: Pick<TPkiApplicationProfileDALFactory, "findOneByApplicationAndProfile">;acmeEnrollmentConfigDAL: Pick<TAcmeEnrollmentConfigDALFactory, "findById">;@@ -1278,11 +1277,8 @@ export const pkiAcmeServiceFactory = ({? await acmeAccountDAL.findApplicationIdByJunctionId(accountApplicationProfileId): null;- const approvalFactory = APPROVAL_POLICY_FACTORY_MAP[ApprovalPolicyType.CertRequest](- ApprovalPolicyType.CertRequest- );- const matchedApprovalPolicy = (await approvalFactory.matchPolicy(- approvalPolicyDAL as TApprovalPolicyDALFactory,+ const matchedApprovalPolicy = (await approvalPolicyService.matchPolicy(+ ApprovalPolicyType.CertRequest,profile.projectId,{profileName: profile.slug,diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 8cec726cd8..f7b03a5d76 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -108,6 +108,7 @@ import { licenseV2ServiceFactory } from "@app/ee/services/license-v2/license-v2-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 { pamAccessApprovalResourceFactory } from "@app/ee/services/pam-access-request/pam-access-approval-resource";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";@@ -254,7 +255,9 @@ import {approvalPolicyStepApproversDALFactory,approvalPolicyStepsDALFactory} from "@app/services/approval-policy/approval-policy-dal";+import { ApprovalPolicyType } from "@app/services/approval-policy/approval-policy-enums";import { approvalPolicyServiceFactory } from "@app/services/approval-policy/approval-policy-service";+import { TApprovalResourceRegistry } from "@app/services/approval-policy/approval-policy-types";import {approvalRequestApprovalsDALFactory,approvalRequestDALFactory,@@ -262,6 +265,8 @@ import {approvalRequestStepEligibleApproversDALFactory,approvalRequestStepsDALFactory} from "@app/services/approval-policy/approval-request-dal";+import { certRequestApprovalResourceFactory } from "@app/services/approval-policy/cert-request/cert-request-policy-factory";+import { codeSigningApprovalResourceFactory } from "@app/services/approval-policy/code-signing/code-signing-policy-factory";import { authDALFactory } from "@app/services/auth/auth-dal";import { authLoginServiceFactory } from "@app/services/auth/auth-login-service";import { authPaswordServiceFactory } from "@app/services/auth/auth-password-service";@@ -2055,157 +2060,6 @@ export const registerRoutes = async (gatewayV2Service});- const pamAccessRequestService = pamAccessRequestServiceFactory({- approvalPolicyDAL,- approvalPolicyStepsDAL,- approvalPolicyStepApproversDAL,- approvalPolicyBypassersDAL,- approvalRequestDAL,- approvalRequestStepsDAL,- approvalRequestStepEligibleApproversDAL,- approvalRequestApprovalsDAL,- approvalRequestGrantsDAL,- pamAccountDAL,- pamAccountTemplateDAL,- pamFolderDAL,- pamSessionDAL,- gatewayV2Service,- membershipDAL,- membershipRoleDAL,- permissionService,- notificationService,- smtpService,- groupDAL,- userGroupMembershipDAL,- userDAL,- identityDAL,- pamFolderNotificationConfigDAL,- workflowIntegrationDAL,- slackIntegrationDAL,- kmsService,- licenseService- });-- const pamFolderService = pamFolderServiceFactory({- pamFolderDAL,- membershipDAL,- membershipRoleDAL,- permissionService,- pamAccessRequestService- });-- const pamDiscoverySourceDAL = pamDiscoverySourceDALFactory(db);-- const pamAccountService = pamAccountServiceFactory({- pamAccountDAL,- pamFolderDAL,- pamAccountTemplateDAL,- membershipDAL,- membershipRoleDAL,- pamSessionDAL,- pamDiscoverySourceDAL,- userDAL,- orgDAL,- mfaSessionService,- permissionService,- kmsService,- gatewayV2DAL,- gatewayV2Service,- gatewayPoolService,- appConnectionDAL,- pamAccessRequestService,- licenseService- });-- const pamDiscoverySourceRunDAL = pamDiscoverySourceRunDALFactory(db);- const pamDiscoveredAccountDAL = pamDiscoveredAccountDALFactory(db);- const pamAccountDependencyDAL = pamAccountDependencyDALFactory(db);-- const pamDiscoveryService = pamDiscoverySourceServiceFactory({- pamDiscoverySourceDAL,- pamDiscoverySourceRunDAL,- pamDiscoveredAccountDAL,- pamAccountDependencyDAL,- pamAccountDAL,- pamAccountService,- permissionService,- kmsService,- gatewayV2DAL,- gatewayV2Service,- gatewayPoolService,- queueService,- cronJob,- auditLogService- });-- const pamAccountRotationService = pamAccountRotationServiceFactory({- pamAccountDAL,- permissionService,- membershipDAL,- membershipRoleDAL,- kmsService,- keyStore,- gatewayService,- gatewayV2Service,- gatewayPoolService,- pamAccountDependencyDAL,- pamDiscoverySourceDAL,- projectDAL- });-- const pamAccountHeartbeatService = pamAccountHeartbeatServiceFactory({- pamAccountDAL,- gatewayService,- gatewayV2Service,- gatewayPoolService,- kmsService,- permissionService,- projectDAL- });-- const pamSessionService = pamSessionServiceFactory({- pamSessionDAL,- pamAccountDAL,- pamFolderDAL,- membershipDAL,- membershipRoleDAL,- permissionService,- kmsService,- gatewayV2Service,- gatewayPoolService,- userDAL,- pamSessionExpirationService,- pamAccessRequestService,- mfaSessionService,- orgDAL,- telemetryService- });-- const pamSessionChunkService = pamSessionChunkServiceFactory({- pamSessionDAL,- pamSessionEventChunkDAL,- pamAccountDAL,- permissionService,- kmsService,- appConnectionDAL- });-- const pamWebAccessService = pamWebAccessServiceFactory({- pamAccountDAL,- pamAccessRequestService,- permissionService,- auditLogService,- tokenService,- pamSessionDAL,- gatewayV2Service,- gatewayPoolService,- kmsService,- userDAL,- mfaSessionService,- orgDAL,- telemetryService- });-const gitHubAppService = gitHubAppServiceFactory({gitHubAppDAL,permissionService,@@ -3171,26 +3025,6 @@ export const registerRoutes = async (pkiApplicationProfileDAL});- const pkiApplicationEnrollmentService = pkiApplicationEnrollmentServiceFactory({- pkiApplicationDAL,- pkiApplicationProfileDAL,- apiEnrollmentConfigDAL,- estEnrollmentConfigDAL,- acmeEnrollmentConfigDAL,- scepEnrollmentConfigDAL,- appConnectionService,- licenseService,- approvalPolicyDAL,- certificateProfileDAL,- certificateAuthorityDAL,- certificateAuthoritySecretDAL,- certificateAuthorityCertDAL,- hsmConnectorService,- kmsService,- projectDAL,- permissionService- });-const honeyTokenConfigService = honeyTokenConfigServiceFactory({honeyTokenConfigDAL,permissionService,@@ -3679,6 +3513,38 @@ export const registerRoutes = async (pkiSyncQueue});+ const pamAccessApprovalResource = pamAccessApprovalResourceFactory({+ licenseService,+ pamFolderNotificationConfigDAL,+ approvalPolicyDAL,+ userGroupMembershipDAL,+ approvalRequestDAL,+ approvalRequestGrantsDAL,+ pamAccountDAL,+ pamAccountTemplateDAL,+ pamFolderDAL,+ pamSessionDAL,+ membershipDAL,+ membershipRoleDAL,+ permissionService,+ userDAL,+ gatewayV2Service,+ kmsService+ });++ const approvalResources: TApprovalResourceRegistry = {+ [ApprovalPolicyType.PamAccess]: pamAccessApprovalResource as TApprovalResourceRegistry[ApprovalPolicyType],+ [ApprovalPolicyType.CertRequest]: certRequestApprovalResourceFactory({+ approvalPolicyDAL,+ certificateApprovalService,+ certificateRequestDAL+ }) as TApprovalResourceRegistry[ApprovalPolicyType],+ [ApprovalPolicyType.CertCodeSigning]: codeSigningApprovalResourceFactory({+ approvalPolicyDAL,+ approvalRequestGrantsDAL+ }) as TApprovalResourceRegistry[ApprovalPolicyType]+ };+const approvalPolicyService = approvalPolicyServiceFactory({approvalPolicyDAL,approvalPolicyStepsDAL,@@ -3696,13 +3562,169 @@ export const registerRoutes = async (userGroupMembershipDAL,notificationService,approvalRequestGrantsDAL,- certificateApprovalService,- certificateRequestDAL,smtpService,userDAL,+ groupDAL,+ slackIntegrationDAL,+ kmsService,+ resources: approvalResources+ });++ const pkiApplicationEnrollmentService = pkiApplicationEnrollmentServiceFactory({+ pkiApplicationDAL,+ pkiApplicationProfileDAL,+ apiEnrollmentConfigDAL,+ estEnrollmentConfigDAL,+ acmeEnrollmentConfigDAL,+ scepEnrollmentConfigDAL,+ appConnectionService,+ licenseService,+ approvalPolicyService,+ certificateProfileDAL,+ certificateAuthorityDAL,+ certificateAuthoritySecretDAL,+ certificateAuthorityCertDAL,+ hsmConnectorService,+ kmsService,+ projectDAL,+ permissionService+ });++ const pamAccessRequestService = pamAccessRequestServiceFactory({+ approvalPolicyDAL,+ approvalRequestDAL,+ pamAccountDAL,+ pamFolderDAL,+ permissionService,+ userDAL,+ identityDAL,+ pamFolderNotificationConfigDAL,+ workflowIntegrationDAL,+ licenseService,+ approvalPolicyService,+ pamAccessApprovalResource+ });++ const pamFolderService = pamFolderServiceFactory({+ pamFolderDAL,+ membershipDAL,+ membershipRoleDAL,+ permissionService,+ pamAccessRequestService+ });++ const pamDiscoverySourceDAL = pamDiscoverySourceDALFactory(db);++ const pamAccountService = pamAccountServiceFactory({+ pamAccountDAL,+ pamFolderDAL,+ pamAccountTemplateDAL,+ membershipDAL,+ membershipRoleDAL,+ pamSessionDAL,+ pamDiscoverySourceDAL,+ userDAL,+ orgDAL,+ mfaSessionService,+ permissionService,+ kmsService,+ gatewayV2DAL,+ gatewayV2Service,+ gatewayPoolService,+ appConnectionDAL,+ pamAccessRequestService,+ licenseService+ });++ const pamDiscoverySourceRunDAL = pamDiscoverySourceRunDALFactory(db);+ const pamDiscoveredAccountDAL = pamDiscoveredAccountDALFactory(db);+ const pamAccountDependencyDAL = pamAccountDependencyDALFactory(db);++ const pamDiscoveryService = pamDiscoverySourceServiceFactory({+ pamDiscoverySourceDAL,+ pamDiscoverySourceRunDAL,+ pamDiscoveredAccountDAL,+ pamAccountDependencyDAL,+ pamAccountDAL,+ pamAccountService,+ permissionService,+ kmsService,+ gatewayV2DAL,+ gatewayV2Service,+ gatewayPoolService,+ queueService,+ cronJob,+ auditLogService+ });++ const pamAccountRotationService = pamAccountRotationServiceFactory({+ pamAccountDAL,+ permissionService,+ membershipDAL,+ membershipRoleDAL,+ kmsService,+ keyStore,+ gatewayService,+ gatewayV2Service,+ gatewayPoolService,+ pamAccountDependencyDAL,+ pamDiscoverySourceDAL,+ projectDAL+ });++ const pamAccountHeartbeatService = pamAccountHeartbeatServiceFactory({+ pamAccountDAL,+ gatewayService,+ gatewayV2Service,+ gatewayPoolService,+ kmsService,+ permissionService,projectDAL});+ const pamSessionService = pamSessionServiceFactory({+ pamSessionDAL,+ pamAccountDAL,+ pamFolderDAL,+ membershipDAL,+ membershipRoleDAL,+ permissionService,+ kmsService,+ gatewayV2Service,+ gatewayPoolService,+ userDAL,+ pamSessionExpirationService,+ pamAccessRequestService,+ mfaSessionService,+ orgDAL,+ telemetryService+ });++ const pamSessionChunkService = pamSessionChunkServiceFactory({+ pamSessionDAL,+ pamSessionEventChunkDAL,+ pamAccountDAL,+ permissionService,+ kmsService,+ appConnectionDAL+ });++ const pamWebAccessService = pamWebAccessServiceFactory({+ pamAccountDAL,+ pamAccessRequestService,+ permissionService,+ auditLogService,+ tokenService,+ pamSessionDAL,+ gatewayV2Service,+ gatewayPoolService,+ kmsService,+ userDAL,+ mfaSessionService,+ orgDAL,+ telemetryService+ });+const certificateV3Service = certificateV3ServiceFactory({usageCounterDAL,pkiApplicationDAL,@@ -3991,7 +4013,10 @@ export const registerRoutes = async (identityDAL,permissionService,notificationService,- smtpService+ smtpService,+ slackIntegrationDAL,+ kmsService,+ approvalResources});const pkiTemplateService = pkiTemplatesServiceFactory({diff --git a/backend/src/server/routes/v1/approval-policy-routers/approval-policy-endpoints.ts b/backend/src/server/routes/v1/approval-policy-routers/approval-policy-endpoints.tsindex 6a92e4bb39..aea550eec3 100644--- a/backend/src/server/routes/v1/approval-policy-routers/approval-policy-endpoints.ts+++ b/backend/src/server/routes/v1/approval-policy-routers/approval-policy-endpoints.ts@@ -6,7 +6,11 @@ import { readLimit, writeLimit } from "@app/server/config/rateLimiter";import { getTelemetryDistinctId } from "@app/server/lib/telemetry";import { isUserSessionAuth } from "@app/server/plugins/auth/inject-identity";import { verifyAuth } from "@app/server/plugins/auth/verify-auth";-import { ApprovalPolicyScope, ApprovalPolicyType } from "@app/services/approval-policy/approval-policy-enums";+import {+ ApprovalAuditAction,+ ApprovalPolicyScope,+ ApprovalPolicyType+} from "@app/services/approval-policy/approval-policy-enums";import {TApprovalPolicyInputs,TCreatePolicyDTO,@@ -417,7 +421,11 @@ export const registerApprovalPolicyEndpoints = ({...req.auditLogInfo,orgId: req.permission.orgId,projectId: request.projectId,- event: {+ event: (await server.services.approvalPolicy.buildAuditEvent({+ action: ApprovalAuditAction.RequestCreated,+ request,+ actorId: req.permission.id+ })) ?? {type: EventType.APPROVAL_REQUEST_CREATE,metadata: {policyType: request.type,@@ -523,40 +531,29 @@ export const registerApprovalPolicyEndpoints = ({policyType);- if (request.isBreakGlass && bypassMetadata) {- await server.services.auditLog.createAuditLog({- ...req.auditLogInfo,- orgId: req.permission.orgId,- projectId: request.projectId,- event: {- type: EventType.PAM_ACCESS_POLICY_BYPASSED,- metadata: {- policyType,- policyId: request.policyId ?? null,- requestId: request.id,- granteeUserId: req.permission.id,- ...bypassMetadata- }- }- });- } else {- await server.services.auditLog.createAuditLog({- ...req.auditLogInfo,- orgId: req.permission.orgId,- projectId: request.projectId,- event: {- type: EventType.APPROVAL_REQUEST_APPROVE,- metadata: {- policyType: request.type,- approvalRequestId: request.id,- requesterName: request.requesterName,- requesterEmail: request.requesterEmail,- comment: req.body.comment,- ...getApprovalRequestSubjectMetadata(request)- }+ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ projectId: request.projectId,+ event: (await server.services.approvalPolicy.buildAuditEvent({+ action: bypassMetadata ? ApprovalAuditAction.RequestBypassed : ApprovalAuditAction.RequestReviewed,+ request,+ grantId: bypassMetadata?.grantId,+ actorId: req.permission.id,+ comment: req.body.comment,+ bypassReason: req.body.bypassReason+ })) ?? {+ type: EventType.APPROVAL_REQUEST_APPROVE,+ metadata: {+ policyType: request.type,+ approvalRequestId: request.id,+ requesterName: request.requesterName,+ requesterEmail: request.requesterEmail,+ comment: req.body.comment,+ ...getApprovalRequestSubjectMetadata(request)}- });- }+ }+ });if (policyType === ApprovalPolicyType.CertRequest || policyType === ApprovalPolicyType.CertCodeSigning) {await server.services.telemetry.sendPostHogEvents({@@ -608,7 +605,12 @@ export const registerApprovalPolicyEndpoints = ({...req.auditLogInfo,orgId: req.permission.orgId,projectId: request.projectId,- event: {+ event: (await server.services.approvalPolicy.buildAuditEvent({+ action: ApprovalAuditAction.RequestReviewed,+ request,+ actorId: req.permission.id,+ comment: req.body.comment+ })) ?? {type: EventType.APPROVAL_REQUEST_REJECT,metadata: {policyType: request.type,@@ -789,13 +791,23 @@ export const registerApprovalPolicyEndpoints = ({},onRequest: verifyAuth([AuthMode.JWT]),handler: async (req) => {- const { grant } = await server.services.approvalPolicy.revokeGrant(req.params.grantId, req.body, req.permission);+ const { grant, request } = await server.services.approvalPolicy.revokeGrant(+ req.params.grantId,+ req.body,+ req.permission+ );await server.services.auditLog.createAuditLog({...req.auditLogInfo,orgId: req.permission.orgId,projectId: grant.projectId,- event: {+ event: (request &&+ (await server.services.approvalPolicy.buildAuditEvent({+ action: ApprovalAuditAction.GrantRevoked,+ request,+ grantId: grant.id,+ actorId: req.permission.id+ }))) || {type: EventType.APPROVAL_REQUEST_GRANT_REVOKE,metadata: {policyType,diff --git a/backend/src/server/routes/v1/approval-policy-routers/index.ts b/backend/src/server/routes/v1/approval-policy-routers/index.tsindex 980a1e9fe0..a78c8418d3 100644--- a/backend/src/server/routes/v1/approval-policy-routers/index.ts+++ b/backend/src/server/routes/v1/approval-policy-routers/index.ts@@ -17,13 +17,36 @@ import {CreateCodeSigningRequestSchema,UpdateCodeSigningPolicySchema} from "@app/services/approval-policy/code-signing/code-signing-policy-schemas";+import {+ CreatePamAccessPolicySchema,+ CreatePamAccessRequestSchema,+ PamAccessCheckPolicyMatchResponseSchema,+ PamAccessPolicyInputsSchema,+ PamAccessPolicySchema,+ PamAccessRequestGrantSchema,+ PamAccessRequestSchema,+ UpdatePamAccessPolicySchema+} from "@app/services/approval-policy/pam-access/pam-access-policy-schemas";import { registerApprovalPolicyEndpoints } from "./approval-policy-endpoints";-// PamAccess is intentionally absent; PAM access requests are served only by /v1/pam/access-requestsexport const APPROVAL_POLICY_REGISTER_ROUTER_MAP: Partial<Record<ApprovalPolicyType, (server: FastifyZodProvider) => Promise<void>>> = {+ [ApprovalPolicyType.PamAccess]: async (server: FastifyZodProvider) => {+ registerApprovalPolicyEndpoints({+ server,+ policyType: ApprovalPolicyType.PamAccess,+ createPolicySchema: CreatePamAccessPolicySchema,+ updatePolicySchema: UpdatePamAccessPolicySchema,+ policyResponseSchema: PamAccessPolicySchema,+ createRequestSchema: CreatePamAccessRequestSchema,+ requestResponseSchema: PamAccessRequestSchema,+ grantResponseSchema: PamAccessRequestGrantSchema,+ inputsSchema: PamAccessPolicyInputsSchema,+ checkPolicyMatchResponseSchema: PamAccessCheckPolicyMatchResponseSchema+ });+ },[ApprovalPolicyType.CertRequest]: async (server: FastifyZodProvider) => {registerApprovalPolicyEndpoints({server,diff --git a/backend/src/services/approval-policy/approval-notification-fns.ts b/backend/src/services/approval-policy/approval-notification-fns.tsnew file mode 100644index 0000000000..7f8029260a--- /dev/null+++ b/backend/src/services/approval-policy/approval-notification-fns.ts@@ -0,0 +1,138 @@+import { TApprovalRequests } from "@app/db/schemas";+import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";+import { logger } from "@app/lib/logger";+import { TKmsServiceFactory } from "@app/services/kms/kms-service";+import { TNotificationServiceFactory } from "@app/services/notification/notification-service";+import { sendSlackNotification } from "@app/services/slack/slack-fns";+import { TSlackIntegrationDALFactory } from "@app/services/slack/slack-integration-dal";+import { TSmtpService } from "@app/services/smtp/smtp-service";+import { TUserDALFactory } from "@app/services/user/user-dal";++import { ApprovalNotificationEvent, ApproverType } from "./approval-policy-enums";+import { TApprovalNotification, TApprovalResource } from "./approval-policy-types";++export type TApprovalNotificationDeps = {+ userGroupMembershipDAL: Pick<TUserGroupMembershipDALFactory, "find">;+ userDAL: Pick<TUserDALFactory, "find">;+ notificationService: Pick<TNotificationServiceFactory, "createUserNotifications">;+ smtpService: Pick<TSmtpService, "sendMail">;+ slackIntegrationDAL: Pick<TSlackIntegrationDALFactory, "findByIdWithWorkflowIntegrationDetails">;+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;+};++export const expandApproversToUserIds = async (+ approvers: { type: ApproverType; id: string }[],+ userGroupMembershipDAL: Pick<TUserGroupMembershipDALFactory, "find">+) => {+ const userIds = new Set(approvers.filter((a) => a.type === ApproverType.User).map((a) => a.id));++ const groupMembers = await Promise.all(+ approvers.filter((a) => a.type === ApproverType.Group).map((a) => userGroupMembershipDAL.find({ groupId: a.id }))+ );+ groupMembers.forEach((members) => members.forEach((m) => userIds.add(m.userId)));++ return userIds;+};++const resolveRecipients = async (+ event: ApprovalNotificationEvent,+ request: TApprovalRequests,+ approvers: { type: ApproverType; id: string }[],+ actorId: string | undefined,+ { userGroupMembershipDAL }: Pick<TApprovalNotificationDeps, "userGroupMembershipDAL">+) => {+ if (event === ApprovalNotificationEvent.Approved || event === ApprovalNotificationEvent.Rejected) {+ return request.requesterId ? new Set([request.requesterId]) : new Set<string>();+ }++ const userIds = await expandApproversToUserIds(approvers, userGroupMembershipDAL);+ if (actorId) userIds.delete(actorId);+ return userIds;+};++const deliverToUsers = async (+ content: TApprovalNotification,+ recipientIds: Set<string>,+ request: TApprovalRequests,+ { userDAL, notificationService, smtpService }: TApprovalNotificationDeps+) => {+ if (recipientIds.size === 0) return;++ if (content.inApp) {+ await notificationService.createUserNotifications(+ [...recipientIds].map((userId) => ({ userId, orgId: request.organizationId, ...content.inApp! }))+ );+ }++ if (content.email) {+ const users = await userDAL.find({ $in: { id: [...recipientIds] } });+ const recipients = users.map((user) => user.email).filter((email): email is string => Boolean(email));+ if (recipients.length > 0) {+ await smtpService.sendMail({ recipients, ...content.email });+ }+ }+};++const deliverToChat = async (+ content: TApprovalNotification,+ request: TApprovalRequests,+ { slackIntegrationDAL, kmsService }: TApprovalNotificationDeps+) => {+ for (const delivery of content.chat ?? []) {+ // eslint-disable-next-line no-await-in-loop+ const slackIntegration = await slackIntegrationDAL.findByIdWithWorkflowIntegrationDetails(+ delivery.workflowIntegrationId+ );+ if (slackIntegration) {+ // eslint-disable-next-line no-await-in-loop+ await sendSlackNotification({+ orgId: request.organizationId,+ notification: delivery.notification,+ kmsService,+ targetChannelIds: delivery.channelIds,+ slackIntegration+ });+ }+ }+};++export const dispatchApprovalNotification = async (+ {+ event,+ request,+ resource,+ approvers,+ actorId,+ comment,+ bypassReason+ }: {+ event: ApprovalNotificationEvent;+ request: TApprovalRequests;+ resource: TApprovalResource;+ approvers: { type: ApproverType; id: string }[];+ actorId?: string;+ comment?: string;+ bypassReason?: string;+ },+ deps: TApprovalNotificationDeps+) => {+ if (!resource.buildNotification) return;++ try {+ const eligibleApprovers = resource.filterActiveApprovers+ ? await resource.filterActiveApprovers(request, approvers)+ : approvers;++ const content = await resource.buildNotification({ event, request, comment, bypassReason });+ if (!content) return;++ const recipientIds = await resolveRecipients(event, request, eligibleApprovers, actorId, deps);+ await deliverToUsers(content, recipientIds, request, deps);+ await deliverToChat(content, request, deps);+ } catch (err) {+ logger.error(+ { err, requestId: request.id, event },+ `Failed to deliver approval notifications [requestId=${request.id}] [event=${event}]`+ );+ }+};diff --git a/backend/src/services/approval-policy/approval-policy-enums.ts b/backend/src/services/approval-policy/approval-policy-enums.tsindex 63dc671522..45207d1fad 100644--- a/backend/src/services/approval-policy/approval-policy-enums.ts+++ b/backend/src/services/approval-policy/approval-policy-enums.ts@@ -1,3 +1,17 @@+export enum ApprovalNotificationEvent {+ Requested = "requested",+ Approved = "approved",+ Rejected = "rejected",+ Bypassed = "bypassed"+}++export enum ApprovalAuditAction {+ RequestCreated = "request-created",+ RequestReviewed = "request-reviewed",+ RequestBypassed = "request-bypassed",+ GrantRevoked = "grant-revoked"+}+export enum ApprovalPolicyType {PamAccess = "pam-access",CertRequest = "cert-request",diff --git a/backend/src/services/approval-policy/approval-policy-factory.ts b/backend/src/services/approval-policy/approval-policy-factory.tsdeleted file mode 100644index 0462101424..0000000000--- a/backend/src/services/approval-policy/approval-policy-factory.ts+++ /dev/null@@ -1,22 +0,0 @@-import { ApprovalPolicyType } from "./approval-policy-enums";-import {- TApprovalPolicy,- TApprovalPolicyInputs,- TApprovalRequestData,- TApprovalResourceFactory-} from "./approval-policy-types";-import { certRequestPolicyFactory } from "./cert-request/cert-request-policy-factory";-import { codeSigningPolicyFactory } from "./code-signing/code-signing-policy-factory";-import { pamAccessPolicyFactory } from "./pam-access/pam-access-policy-factory";--type TApprovalPolicyFactoryImplementation = TApprovalResourceFactory<- TApprovalPolicyInputs,- TApprovalPolicy,- TApprovalRequestData->;--export const APPROVAL_POLICY_FACTORY_MAP: Record<ApprovalPolicyType, TApprovalPolicyFactoryImplementation> = {- [ApprovalPolicyType.PamAccess]: pamAccessPolicyFactory as TApprovalPolicyFactoryImplementation,- [ApprovalPolicyType.CertRequest]: certRequestPolicyFactory as TApprovalPolicyFactoryImplementation,- [ApprovalPolicyType.CertCodeSigning]: codeSigningPolicyFactory as TApprovalPolicyFactoryImplementation-};diff --git a/backend/src/services/approval-policy/approval-policy-service.ts b/backend/src/services/approval-policy/approval-policy-service.tsindex ca87518da8..33ad6c39cf 100644--- a/backend/src/services/approval-policy/approval-policy-service.ts+++ b/backend/src/services/approval-policy/approval-policy-service.ts@@ -1,4 +1,5 @@import { ForbiddenError } from "@casl/ability";+import { Knex } from "knex";import {ActionProjectType,@@ -8,6 +9,7 @@ import {TApprovalPolicies,TApprovalRequests} from "@app/db/schemas";+import { TGroupDALFactory } from "@app/ee/services/group/group-dal";import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";@@ -21,23 +23,19 @@ import {ResourcePermissionApprovalPolicyActions,ResourcePermissionSub} from "@app/ee/services/permission/resource-permission";-import { getConfig } from "@app/lib/config/env";import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";-import { logger } from "@app/lib/logger";import { ms } from "@app/lib/ms";-import { OrgServiceActor } from "@app/lib/types";import { ActorType } from "@app/services/auth/auth-type";-import { TCertificateRequestDALFactory } from "@app/services/certificate-request/certificate-request-dal";-import { TCertificateApprovalService } from "@app/services/certificate-v3/certificate-approval-fns";+import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { TNotificationServiceFactory } from "@app/services/notification/notification-service";-import { NotificationType } from "@app/services/notification/notification-types";import { TPkiApplicationDALFactory } from "@app/services/pki-application/pki-application-dal";-import { SmtpTemplates, TSmtpService } from "@app/services/smtp/smtp-service";+import { TSlackIntegrationDALFactory } from "@app/services/slack/slack-integration-dal";+import { TSmtpService } from "@app/services/smtp/smtp-service";import { TUserDALFactory } from "@app/services/user/user-dal";import { TMembershipDALFactory } from "../membership/membership-dal";-import { TProjectDALFactory } from "../project/project-dal";import { TProjectMembershipDALFactory } from "../project-membership/project-membership-dal";+import { dispatchApprovalNotification } from "./approval-notification-fns";import {TApprovalPolicyBypassersDALFactory,TApprovalPolicyDALFactory,@@ -45,6 +43,8 @@ import {TApprovalPolicyStepsDALFactory} from "./approval-policy-dal";import {+ ApprovalAuditAction,+ ApprovalNotificationEvent,ApprovalPolicyScope,ApprovalPolicyType,ApprovalRequestApprovalDecision,@@ -54,20 +54,24 @@ import {ApproverType,EnforcementLevel} from "./approval-policy-enums";-import { APPROVAL_POLICY_FACTORY_MAP } from "./approval-policy-factory";import {- ApprovalPolicyStep,+ ApprovalAccessStatus,BreakGlassBypassMetadata,PolicyBypasser,+ TApprovalAccessStatus,+ TApprovalActor,TApprovalPolicy,TApprovalPolicyInputs,TApprovalRequest,+ TApprovalRequestData,+ TApprovalResourceRegistry,+ TApprovalScopeConfiguration,+ TApprovalSubjectActor,TBypassAffordances,TCreatePolicyDTO,TCreateRequestDTO,TCreateRequestFromPolicyDTO,TDecorationContext,- TPostApprovalContext,TUpdatePolicyDTO} from "./approval-policy-types";import {@@ -77,8 +81,7 @@ import {TApprovalRequestStepEligibleApproversDALFactory,TApprovalRequestStepsDALFactory} from "./approval-request-dal";-import { createApprovalRequestWithSteps, notifyStepApprovers } from "./approval-request-fns";-import { TPamAccessRequestData } from "./pam-access/pam-access-policy-types";+import { createApprovalRequestWithSteps } from "./approval-request-fns";type TApprovalPolicyServiceFactoryDep = {approvalPolicyDAL: TApprovalPolicyDALFactory;@@ -91,6 +94,8 @@ type TApprovalPolicyServiceFactoryDep = {approvalRequestStepEligibleApproversDAL: TApprovalRequestStepEligibleApproversDALFactory;approvalRequestGrantsDAL: TApprovalRequestGrantsDALFactory;userGroupMembershipDAL: TUserGroupMembershipDALFactory;+ slackIntegrationDAL: Pick<TSlackIntegrationDALFactory, "findByIdWithWorkflowIntegrationDetails">;+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;notificationService: TNotificationServiceFactory;permissionService: Pick<TPermissionServiceFactory,@@ -100,11 +105,10 @@ type TApprovalPolicyServiceFactoryDep = {projectMembershipDAL: Pick<TProjectMembershipDALFactory, "findProjectMembershipsByUserIds">;membershipDAL: Pick<TMembershipDALFactory, "find">;pkiApplicationDAL: Pick<TPkiApplicationDALFactory, "findById">;- certificateApprovalService: TCertificateApprovalService;- certificateRequestDAL: Pick<TCertificateRequestDALFactory, "updateById" | "findById">;smtpService: Pick<TSmtpService, "sendMail">;userDAL: Pick<TUserDALFactory, "findById" | "find">;- projectDAL: Pick<TProjectDALFactory, "findById">;+ groupDAL: Pick<TGroupDALFactory, "find">;+ resources: TApprovalResourceRegistry;};export type TApprovalPolicyServiceFactory = ReturnType<typeof approvalPolicyServiceFactory>;@@ -120,27 +124,50 @@ export const approvalPolicyServiceFactory = ({approvalRequestStepEligibleApproversDAL,approvalRequestGrantsDAL,userGroupMembershipDAL,+ slackIntegrationDAL,+ kmsService,notificationService,permissionService,licenseService,projectMembershipDAL,membershipDAL,pkiApplicationDAL,- certificateApprovalService,- certificateRequestDAL,smtpService,userDAL,- projectDAL+ groupDAL,+ resources}: TApprovalPolicyServiceFactoryDep) => {- const $notifyApprovers = (step: ApprovalPolicyStep, request: TApprovalRequests) =>- notifyStepApprovers(step, request, {- userGroupMembershipDAL,- notificationService,- userDAL,- smtpService- });+ const $resource = (policyType: ApprovalPolicyType) => {+ const resource = resources[policyType];+ if (!resource) {+ throw new BadRequestError({ message: `Approvals are not configured for ${policyType}` });+ }+ return resource;+ };- const $buildDecorationContext = (actor: OrgServiceActor): TDecorationContext => {+ const $notificationDeps = {+ userGroupMembershipDAL,+ userDAL,+ notificationService,+ smtpService,+ slackIntegrationDAL,+ kmsService+ };++ const $notify = (args: {+ event: ApprovalNotificationEvent;+ request: TApprovalRequests;+ approvers?: { type: ApproverType; id: string }[];+ actorId?: string;+ comment?: string;+ bypassReason?: string;+ }) =>+ dispatchApprovalNotification(+ { ...args, approvers: args.approvers ?? [], resource: $resource(args.request.type as ApprovalPolicyType) },+ $notificationDeps+ );++ const $buildDecorationContext = (actor: TApprovalActor): TDecorationContext => {let cached: Promise<Set<string>> | null = null;return {getUserGroupIds: () => {@@ -159,7 +186,7 @@ export const approvalPolicyServiceFactory = ({// match skips the permission check, so the token's org has to match too.const $isRequester = (request: { organizationId: string; requesterId?: string | null; machineIdentityId?: string | null },- actor: OrgServiceActor+ actor: TApprovalActor) => {if (request.organizationId !== actor.orgId) return false;@@ -168,6 +195,34 @@ export const approvalPolicyServiceFactory = ({: request.requesterId === actor.id;};+ const $isBreakGlassEligible = async ({+ request,+ policy,+ bypassers,+ actor,+ getUserGroupIds+ }: {+ request: TApprovalRequests;+ policy: TApprovalPolicies;+ bypassers: PolicyBypasser[];+ actor: TApprovalActor;+ getUserGroupIds: () => Promise<Set<string>>;+ }) => {+ const domainPredicate = resources[policy.type as ApprovalPolicyType]?.isBreakGlassEligible;+ if (domainPredicate) {+ return domainPredicate({ request, policy, bypassers, actor, userGroupIds: await getUserGroupIds() });+ }++ if (policy.enforcementLevel !== EnforcementLevel.Soft) return false;+ if (bypassers.length === 0) return true;++ const userGroupIds = await getUserGroupIds();+ return bypassers.some(+ (b) =>+ (b.type === ApproverType.User && b.id === actor.id) || (b.type === ApproverType.Group && userGroupIds.has(b.id))+ );+ };+const $decorateRequest = async <R extends {id: string;@@ -178,12 +233,10 @@ export const approvalPolicyServiceFactory = ({}>(request: R,- actor: OrgServiceActor,+ actor: TApprovalActor,ctx: TDecorationContext = $buildDecorationContext(actor)): Promise<R & TBypassAffordances> => {- // Bypass affordances are PAM-only — short-circuit other policy types so we don't fire- // a grant lookup for cert/codesigning request views.- if (request.type !== ApprovalPolicyType.PamAccess) {+ if (!resources[request.type as ApprovalPolicyType]?.isBreakGlassEligible) {return { ...request, canBreakGlass: false, isBreakGlass: false, bypassReason: null };}@@ -195,20 +248,17 @@ export const approvalPolicyServiceFactory = ({request.policyId) {const policy = ctx.policyById?.get(request.policyId) ?? (await approvalPolicyDAL.findById(request.policyId));- if (policy && policy.enforcementLevel === EnforcementLevel.Soft) {+ if (policy) {const bypassers =ctx.bypassersByPolicyId?.get(request.policyId) ??(await approvalPolicyDAL.findBypassersByPolicyId(request.policyId));- if (bypassers.length === 0) {- canBreakGlass = true;- } else {- const userGroupIds = await ctx.getUserGroupIds();- canBreakGlass = bypassers.some(- (b) =>- (b.type === ApproverType.User && b.id === actor.id) ||- (b.type === ApproverType.Group && userGroupIds.has(b.id))- );- }+ canBreakGlass = await $isBreakGlassEligible({+ request: request as unknown as TApprovalRequests,+ policy,+ bypassers,+ actor,+ getUserGroupIds: ctx.getUserGroupIds+ });}}@@ -239,7 +289,8 @@ export const approvalPolicyServiceFactory = ({const $resolveScope = async (scope: ApprovalPolicyScope,- scopeId: string+ scopeId: string,+ policyType: ApprovalPolicyType): Promise<{ projectId: string; scopeType: string | null; scopeId: string | null }> => {if (scope === ApprovalPolicyScope.Project) {return { projectId: scopeId, scopeType: null, scopeId: null };@@ -251,6 +302,13 @@ export const approvalPolicyServiceFactory = ({}return { projectId: app.projectId, scopeType: ApprovalPolicyScope.PkiApplication, scopeId };}++ const resolveDomainScope = resources[policyType]?.resolveScope;+ if (resolveDomainScope) {+ const { projectId } = await resolveDomainScope(scopeId);+ return { projectId, scopeType: scope, scopeId };+ }+throw new BadRequestError({ message: `Unsupported scope: ${String(scope)}` });};@@ -258,9 +316,16 @@ export const approvalPolicyServiceFactory = ({projectId: string,scopeType: string | null | undefined,scopeId: string | null | undefined,- actor: OrgServiceActor,- resourceAction: ResourcePermissionApprovalPolicyActions+ actor: TApprovalActor,+ resourceAction: ResourcePermissionApprovalPolicyActions,+ policyType: ApprovalPolicyType) => {+ const assertDomainCanManage = resources[policyType]?.assertCanManagePolicy;+ if (assertDomainCanManage) {+ await assertDomainCanManage({ projectId, scopeId: scopeId ?? null, actor, action: resourceAction });+ return;+ }+if (scopeType === ApprovalPolicyScope.PkiApplication && scopeId) {const { permission } = await permissionService.getResourcePermission({actor: actor.type,@@ -317,7 +382,7 @@ export const approvalPolicyServiceFactory = ({}: {requestId: string;request: TApprovalRequests;- actor: OrgServiceActor;+ actor: TApprovalActor;policy: TApprovalPolicies;policyType: ApprovalPolicyType;bypassReason: string;@@ -331,14 +396,15 @@ export const approvalPolicyServiceFactory = ({});}- // Re-check project membership in case the user was removed after creating the request.- await $verifyProjectUserMembership([actor.id], actor.orgId, request.projectId);+ if (!resources[policyType]) {+ await $verifyProjectUserMembership([actor.id], actor.orgId, request.projectId);+ }- const inputs = (request.requestData as { requestData: TPamAccessRequestData }).requestData;+ const inputs = (request.requestData as { requestData: TApprovalRequestData }).requestData;// Re-validate constraints in case the policy was tightened after the request was created.- const fac = APPROVAL_POLICY_FACTORY_MAP[policyType](policyType);- const constraintCheck = fac.validateConstraints(policy as unknown as TApprovalPolicy, inputs);+ const resource = $resource(policyType);+ const constraintCheck = resource.validateConstraints(policy as unknown as TApprovalPolicy, inputs);if (!constraintCheck.valid) {throw new BadRequestError({message: constraintCheck.errors@@ -349,25 +415,7 @@ export const approvalPolicyServiceFactory = ({const steps = await approvalRequestDAL.findStepsByRequestId(requestId);- const approverUserIdSet = new Set<string>();- const approverGroupIds: string[] = [];- for (const step of steps) {- for (const approver of step.approvers) {- if (approver.type === ApproverType.User) {- approverUserIdSet.add(approver.id);- } else {- approverGroupIds.push(approver.id);- }- }- }-- const expandedGroupMembers = (- await Promise.all([...new Set(approverGroupIds)].map((groupId) => userGroupMembershipDAL.find({ groupId })))- ).flat();- expandedGroupMembers.forEach((m) => approverUserIdSet.add(m.userId));- approverUserIdSet.delete(actor.id);-- const recipientUserIds = [...approverUserIdSet];+ const bypassedApproverCount = new Set(steps.flatMap((step) => step.approvers.map((a) => `${a.type}:${a.id}`))).size;const grant = await approvalRequestDAL.transaction(async (tx) => {const locked = await approvalRequestDAL.findByIdForUpdate(requestId, tx);@@ -408,25 +456,21 @@ export const approvalPolicyServiceFactory = ({);}- await approvalRequestDAL.updateById(requestId, { status: ApprovalRequestStatus.Approved }, tx);-- const durationMs = ms(inputs.accessDuration);- const expiresAt = new Date(Date.now() + durationMs);-- return approvalRequestGrantsDAL.create(- {- projectId: request.projectId,- requestId: request.id,- granteeUserId: actor.id,- status: ApprovalRequestGrantStatus.Active,- type: request.type,- attributes: inputs,- expiresAt,- isBreakGlass: true,- bypassReason: bypassReason.trim()- },+ const approvedRequest = await approvalRequestDAL.updateById(+ requestId,+ { status: ApprovalRequestStatus.Approved },tx);++ const result = await resource.postApprovalTxRoutine?.(approvedRequest as TApprovalRequest, tx, {+ bypassReason: bypassReason.trim()+ });++ if (!result?.grantId) {+ throw new BadRequestError({ message: `Bypassing approval is not supported for ${policyType} requests` });+ }++ return result;});const finalSteps = await approvalRequestDAL.findStepsByRequestId(requestId);@@ -434,78 +478,18 @@ export const approvalPolicyServiceFactory = ({const result = { ...finalRequest, steps: finalSteps } as TApprovalRequest & { steps: unknown[] };const bypassMetadata: BreakGlassBypassMetadata = {- grantId: grant.id,- resourceName: inputs.resourceName,- accountName: inputs.accountName,- accessDuration: inputs.accessDuration,+ grantId: grant.grantId,bypassReason: bypassReason.trim(),- approverCount: recipientUserIds.length+ approverCount: bypassedApproverCount};- if (recipientUserIds.length === 0) {- return { request: await $decorateRequest(result, actor), bypassMetadata };- }-- try {- const [recipients, project, actingUser] = await Promise.all([- userDAL.find({ $in: { id: recipientUserIds } }),- projectDAL.findById(request.projectId),- userDAL.findById(actor.id)- ]);- const cfg = getConfig();- const approvalPath = project- ? `/organizations/${project.orgId}/projects/pam/${request.projectId}/approvals/${requestId}`- : null;-- const requesterFullName = actingUser- ? `${actingUser.firstName ?? ""} ${actingUser.lastName ?? ""}`.trim() || (actingUser.email ?? "")- : "Unknown user";- const requesterEmail = actingUser?.email ?? "";-- await notificationService.createUserNotifications(- recipients.map((r) => ({- userId: r.id,- orgId: actor.orgId,- type: NotificationType.PAM_ACCESS_POLICY_BYPASSED,- title: "PAM Access Policy Bypassed",- body: `**${requesterFullName}** (${requesterEmail}) self-approved access to **${[- inputs.resourceName,- inputs.accountName- ]- .filter(Boolean)- .join(" / ")}** without obtaining the required approval.`,- link: approvalPath ?? undefined- }))- );-- const emailRecipients = recipients- .map((r) => r.email)- .filter((e): e is string => typeof e === "string" && e.length > 0);-- // Skip email when SITE_URL is unset — the link in the email would dead-link.- if (emailRecipients.length > 0 && cfg.SITE_URL && approvalPath) {- await smtpService.sendMail({- recipients: emailRecipients,- subjectLine: "Infisical PAM Access Policy Bypassed",- substitutions: {- requesterFullName,- requesterEmail,- resourceName: inputs.resourceName,- accountName: inputs.accountName,- accessDuration: inputs.accessDuration,- bypassReason: bypassReason.trim()- },- template: SmtpTemplates.AccessPamRequestBypassed- });- } else if (emailRecipients.length > 0 && !cfg.SITE_URL) {- logger.warn({ requestId }, `Skipping break-glass email: SITE_URL is not configured [requestId=${requestId}]`);- }- } catch (err) {- logger.error(- { err, requestId, granteeUserId: actor.id },- `Failed to deliver break-glass notifications [requestId=${requestId}] [granteeUserId=${actor.id}]`- );- }+ await $notify({+ event: ApprovalNotificationEvent.Bypassed,+ request: finalRequest,+ approvers: steps.flatMap((step) => step.approvers),+ actorId: actor.id,+ bypassReason: bypassReason.trim()+ });return { request: await $decorateRequest(result, actor), bypassMetadata };};@@ -542,6 +526,46 @@ export const approvalPolicyServiceFactory = ({}};+ const $verifyPolicyActors = async ({+ policyType,+ projectId,+ orgId,+ scopeType,+ scopeId,+ approvers,+ bypassers+ }: {+ policyType: ApprovalPolicyType;+ projectId: string;+ orgId: string;+ scopeType: string | null;+ scopeId: string | null;+ approvers: PolicyBypasser[];+ bypassers: PolicyBypasser[];+ }) => {+ const verifyDomainActors = resources[policyType]?.verifyPolicyActors;+ if (verifyDomainActors) {+ await verifyDomainActors({ projectId, scopeId, approvers, bypassers });+ return;+ }++ if (scopeType === ApprovalPolicyScope.PkiApplication && scopeId) {+ await $verifyApplicationApproverMembership(approvers, projectId, scopeId);+ } else {+ await $verifyProjectUserMembership(+ approvers.filter((approver) => approver.type === ApproverType.User).map((approver) => approver.id),+ orgId,+ projectId+ );+ }++ await $verifyProjectUserMembership(+ bypassers.filter((bypasser) => bypasser.type === ApproverType.User).map((bypasser) => bypasser.id),+ orgId,+ projectId+ );+ };+const create = async (policyType: ApprovalPolicyType,{@@ -556,9 +580,9 @@ export const approvalPolicyServiceFactory = ({enforcementLevel,bypassers}: TCreatePolicyDTO,- actor: OrgServiceActor+ actor: TApprovalActor) => {- const resolved = await $resolveScope(scope, inputScopeId);+ const resolved = await $resolveScope(scope, inputScopeId, policyType);const { projectId, scopeType: dbScopeType, scopeId: dbScopeId } = resolved;await $assertCanManagePolicy(@@ -566,7 +590,8 @@ export const approvalPolicyServiceFactory = ({dbScopeType,dbScopeId,actor,- ResourcePermissionApprovalPolicyActions.Create+ ResourcePermissionApprovalPolicyActions.Create,+ policyType);// CertRequest only: code signing follows pkiCodeSigning and PAM has its own product entitlement.@@ -580,32 +605,25 @@ export const approvalPolicyServiceFactory = ({}}- // Bypass-related fields are PAM-only at the moment. The schema accepts them on every policy- // type for forward-compat, but the service rejects non-PAM use so admins can't silently store- // configuration that the bypass branch will never honor.+ // The schema accepts bypass fields on every type, so reject them where nothing would honor them.if (- policyType !== ApprovalPolicyType.PamAccess &&+ !resources[policyType]?.isBreakGlassEligible &&(enforcementLevel === EnforcementLevel.Soft || (bypassers && bypassers.length > 0))) {throw new BadRequestError({- message: "Bypass approvals are only supported on PAM access policies"+ message: `Bypassing approval is not supported for ${policyType} policies`});}- const allApprovers = steps.flatMap((step) => step.approvers ?? []);- if (dbScopeType === ApprovalPolicyScope.PkiApplication && dbScopeId) {- await $verifyApplicationApproverMembership(allApprovers, projectId, dbScopeId);- } else {- const approverUserIds = allApprovers- .filter((approver) => approver.type === ApproverType.User)- .map((approver) => approver.id);- await $verifyProjectUserMembership(approverUserIds, actor.orgId, projectId);- }-- const bypasserUserIds = (bypassers ?? [])- .filter((bypasser) => bypasser.type === ApproverType.User)- .map((bypasser) => bypasser.id);- await $verifyProjectUserMembership(bypasserUserIds, actor.orgId, projectId);+ await $verifyPolicyActors({+ policyType,+ projectId,+ orgId: actor.orgId,+ scopeType: dbScopeType,+ scopeId: dbScopeId,+ approvers: steps.flatMap((step) => step.approvers ?? []),+ bypassers: bypassers ?? []+ });const policy = await approvalPolicyDAL.transaction(async (tx) => {const newPolicy = await approvalPolicyDAL.create(@@ -683,16 +701,21 @@ export const approvalPolicyServiceFactory = ({policyType: ApprovalPolicyType,scope: ApprovalPolicyScope,inputScopeId: string,- actor: OrgServiceActor+ actor: TApprovalActor) => {- const { projectId, scopeType: dbScopeType, scopeId: dbScopeId } = await $resolveScope(scope, inputScopeId);+ const {+ projectId,+ scopeType: dbScopeType,+ scopeId: dbScopeId+ } = await $resolveScope(scope, inputScopeId, policyType);await $assertCanManagePolicy(projectId,dbScopeType,dbScopeId,actor,- ResourcePermissionApprovalPolicyActions.Read+ ResourcePermissionApprovalPolicyActions.Read,+ policyType);const policies = await approvalPolicyDAL.findByProjectId(policyType, projectId, {@@ -703,7 +726,7 @@ export const approvalPolicyServiceFactory = ({return { policies, projectId };};- const getById = async (policyId: string, actor: OrgServiceActor) => {+ const getById = async (policyId: string, actor: TApprovalActor) => {const policy = await approvalPolicyDAL.findById(policyId);if (!policy) {throw new ForbiddenRequestError({ message: "Policy not found" });@@ -714,7 +737,8 @@ export const approvalPolicyServiceFactory = ({policy.scopeType ?? null,policy.scopeId ?? null,actor,- ResourcePermissionApprovalPolicyActions.Read+ ResourcePermissionApprovalPolicyActions.Read,+ policy.type as ApprovalPolicyType);const [steps, bypassers] = await Promise.all([@@ -737,7 +761,7 @@ export const approvalPolicyServiceFactory = ({enforcementLevel,bypassers}: TUpdatePolicyDTO,- actor: OrgServiceActor+ actor: TApprovalActor) => {const policy = await approvalPolicyDAL.findById(policyId);if (!policy) {@@ -752,36 +776,28 @@ export const approvalPolicyServiceFactory = ({policyScopeType,policyScopeId,actor,- ResourcePermissionApprovalPolicyActions.Edit+ ResourcePermissionApprovalPolicyActions.Edit,+ policy.type as ApprovalPolicyType);if (- policy.type !== ApprovalPolicyType.PamAccess &&+ !resources[policy.type as ApprovalPolicyType]?.isBreakGlassEligible &&(enforcementLevel === EnforcementLevel.Soft || (bypassers && bypassers.length > 0))) {throw new BadRequestError({- message: "Bypass approvals are only supported on PAM access policies"+ message: `Bypassing approval is not supported for ${policy.type} policies`});}- if (steps !== undefined) {- const allApprovers = steps.flatMap((step) => step.approvers ?? []);- if (policyScopeType === ApprovalPolicyScope.PkiApplication && policyScopeId) {- await $verifyApplicationApproverMembership(allApprovers, policy.projectId, policyScopeId);- } else {- const approverUserIds = allApprovers- .filter((approver) => approver.type === ApproverType.User)- .map((approver) => approver.id);- await $verifyProjectUserMembership(approverUserIds, actor.orgId, policy.projectId);- }- }-- if (bypassers !== undefined) {- const bypasserUserIds = bypassers- .filter((bypasser) => bypasser.type === ApproverType.User)- .map((bypasser) => bypasser.id);- await $verifyProjectUserMembership(bypasserUserIds, actor.orgId, policy.projectId);- }+ await $verifyPolicyActors({+ policyType: policy.type as ApprovalPolicyType,+ projectId: policy.projectId,+ orgId: actor.orgId,+ scopeType: policyScopeType,+ scopeId: policyScopeId,+ approvers: steps?.flatMap((step) => step.approvers ?? []) ?? [],+ bypassers: bypassers ?? []+ });const updatedPolicy = await approvalPolicyDAL.transaction(async (tx) => {const updateDoc: Partial<TApprovalPolicies> = {};@@ -810,7 +826,9 @@ export const approvalPolicyServiceFactory = ({updateDoc.enforcementLevel = enforcementLevel;}- const updated = await approvalPolicyDAL.updateById(policyId, updateDoc, tx);+ const updated = Object.keys(updateDoc).length+ ? await approvalPolicyDAL.updateById(policyId, updateDoc, tx)+ : await approvalPolicyDAL.findById(policyId, tx);if (steps !== undefined) {await approvalPolicyStepsDAL.delete({ policyId }, tx);@@ -878,7 +896,7 @@ export const approvalPolicyServiceFactory = ({};};- const deleteById = async (policyId: string, actor: OrgServiceActor) => {+ const deleteById = async (policyId: string, actor: TApprovalActor) => {const policy = await approvalPolicyDAL.findById(policyId);if (!policy) {throw new ForbiddenRequestError({ message: "Policy not found" });@@ -889,7 +907,8 @@ export const approvalPolicyServiceFactory = ({policy.scopeType ?? null,policy.scopeId ?? null,actor,- ResourcePermissionApprovalPolicyActions.Delete+ ResourcePermissionApprovalPolicyActions.Delete,+ policy.type as ApprovalPolicyType);await approvalPolicyDAL.deleteById(policyId);@@ -938,9 +957,11 @@ export const approvalPolicyServiceFactory = ({tx);- if (requestWithSteps.steps.length > 0) {- await $notifyApprovers(requestWithSteps.steps[0], requestWithSteps);- }+ await $notify({+ event: ApprovalNotificationEvent.Requested,+ request: requestWithSteps,+ approvers: requestWithSteps.steps[0]?.approvers ?? []+ });return {request: requestWithSteps@@ -963,42 +984,49 @@ export const approvalPolicyServiceFactory = ({requesterEmail: string;machineIdentityId?: string;},- actor: OrgServiceActor+ actor: TApprovalActor) => {- const { projectId } = await $resolveScope(scope, inputScopeId);+ const { projectId } = await $resolveScope(scope, inputScopeId, policyType);- const { permission } = await permissionService.getProjectPermission({- actor: actor.type,- actorAuthMethod: actor.authMethod,- actorId: actor.id,- actorOrgId: actor.orgId,- projectId,- actionProjectType: ActionProjectType.Any- });+ const assertDomainCanCreateRequest = resources[policyType]?.assertCanCreateRequest;- if (policyType === ApprovalPolicyType.CertCodeSigning) {- ForbiddenError.from(permission).throwUnlessCan(- ProjectPermissionCodeSigningActions.Sign,- ProjectPermissionSub.CodeSigners- );- } else {- ForbiddenError.from(permission).throwUnlessCan(- ProjectPermissionApprovalRequestActions.Create,- ProjectPermissionSub.ApprovalRequests- );+ // A type with its own authorization model owns this outright; its gate runs once the policy matched+ if (!assertDomainCanCreateRequest) {+ const { permission } = await permissionService.getProjectPermission({+ actor: actor.type,+ actorAuthMethod: actor.authMethod,+ actorId: actor.id,+ actorOrgId: actor.orgId,+ projectId,+ actionProjectType: ActionProjectType.Any+ });++ if (policyType === ApprovalPolicyType.CertCodeSigning) {+ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionCodeSigningActions.Sign,+ ProjectPermissionSub.CodeSigners+ );+ } else {+ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionApprovalRequestActions.Create,+ ProjectPermissionSub.ApprovalRequests+ );+ }}- const fac = APPROVAL_POLICY_FACTORY_MAP[policyType](policyType);+ const resource = $resource(policyType);- const policy = await fac.matchPolicy(approvalPolicyDAL, projectId, requestData);+ const policy = await resource.matchPolicy(projectId, requestData);if (!policy) {throw new ForbiddenRequestError({- message: "No policies match the requested resource, you can access it without a request"+ message:+ resources[policyType]?.noMatchingPolicyMessage ??+ "No policies match the requested resource, you can access it without a request"});}- const constraintValidation = fac.validateConstraints(policy, requestData);+ const constraintValidation = resource.validateConstraints(policy, requestData);if (!constraintValidation.valid) {const errorMessage = constraintValidation.errors? `Policy constraints not met: ${constraintValidation.errors.join("; ")}`@@ -1006,6 +1034,15 @@ export const approvalPolicyServiceFactory = ({throw new ForbiddenRequestError({ message: errorMessage });}+ if (assertDomainCanCreateRequest) {+ await assertDomainCanCreateRequest({+ projectId,+ policy,+ requestData: requestData as TApprovalRequestData,+ actor+ });+ }+let expiresAt: Date | undefined;if (requestDuration) {@@ -1040,7 +1077,7 @@ export const approvalPolicyServiceFactory = ({return { request: decorated };};- const getRequestById = async (requestId: string, actor: OrgServiceActor) => {+ const getRequestById = async (requestId: string, actor: TApprovalActor) => {const request = await approvalRequestDAL.findById(requestId);if (!request) {throw new ForbiddenRequestError({ message: "Request not found" });@@ -1102,7 +1139,7 @@ export const approvalPolicyServiceFactory = ({const approveRequest = async (requestId: string,{ comment, bypassReason }: { comment?: string; bypassReason?: string },- actor: OrgServiceActor,+ actor: TApprovalActor,policyType: ApprovalPolicyType): Promise<{request: TApprovalRequests & { steps: unknown[] } & TBypassAffordances;@@ -1119,9 +1156,10 @@ export const approvalPolicyServiceFactory = ({});}- if (bypassReason !== undefined && policyType !== ApprovalPolicyType.PamAccess) {+ const supportsBreakGlass = Boolean(resources[policyType]?.isBreakGlassEligible);+ if (bypassReason !== undefined && !supportsBreakGlass) {throw new BadRequestError({- message: "bypassReason is only supported for PAM access requests"+ message: `Bypassing approval is not supported for ${policyType} requests`});}@@ -1131,39 +1169,35 @@ export const approvalPolicyServiceFactory = ({}const policy =- bypassReason !== undefined && policyType === ApprovalPolicyType.PamAccess && request.policyId- ? await approvalPolicyDAL.findById(request.policyId)- : null;+ bypassReason !== undefined && request.policyId ? await approvalPolicyDAL.findById(request.policyId) : null;const bypassers: PolicyBypasser[] =- bypassReason !== undefined && policyType === ApprovalPolicyType.PamAccess && request.policyId+ bypassReason !== undefined && request.policyId? await approvalPolicyDAL.findBypassersByPolicyId(request.policyId): [];- if (bypassReason !== undefined && !policy) {- throw new BadRequestError({- message: "Policy no longer exists; cannot evaluate break-glass"- });- }-const userGroups = await userGroupMembershipDAL.findGroupMembershipsByUserIdInOrg(actor.id, actor.orgId);const userGroupIds = new Set(userGroups.map((g) => g.groupId));- // Opt-in: only triggers when the caller passes bypassReason.- const isBreakGlass =- bypassReason !== undefined &&- policyType === ApprovalPolicyType.PamAccess &&- actor.type === ActorType.USER &&- request.requesterId === actor.id &&- Boolean(policy) &&- policy?.enforcementLevel === EnforcementLevel.Soft &&- (bypassers.length === 0 ||- bypassers.some(- (b) =>- (b.type === ApproverType.User && b.id === actor.id) ||- (b.type === ApproverType.Group && userGroupIds.has(b.id))- ));+ if (bypassReason !== undefined) {+ if (!policy) {+ throw new BadRequestError({ message: "Policy no longer exists; cannot evaluate break-glass" });+ }++ const eligible =+ actor.type === ActorType.USER &&+ request.requesterId === actor.id &&+ (await $isBreakGlassEligible({+ request,+ policy,+ bypassers,+ actor,+ getUserGroupIds: () => Promise.resolve(userGroupIds)+ }));++ if (!eligible) {+ throw new ForbiddenRequestError({ message: "You are not permitted to bypass approval on this request" });+ }- if (isBreakGlass) {return $approveRequestBreakGlass({requestId,request,@@ -1200,18 +1234,55 @@ export const approvalPolicyServiceFactory = ({throw new ForbiddenRequestError({ message: "You cannot approve your own signing request" });}+ const assertDomainCanApprove = resources[policyType]?.assertCanReview;+ if (assertDomainCanApprove) {+ await assertDomainCanApprove({+ request,+ decision: ApprovalRequestApprovalDecision.Approved,+ actor,+ userGroupIds+ });+ }+const hasApproved = currentStep.approvals.some((a) => a.approverUserId === actor.id);if (hasApproved) {throw new BadRequestError({ message: "You have already approved this request" });}+ const resource = $resource(policyType);+const { updatedRequest, nextStepToNotify } = await approvalRequestDAL.transaction(async (tx) => {let nextStepToNotifyInner = null;- // Create approval+ const locked = await approvalRequestDAL.findByIdForUpdate(requestId, tx);+ if (!locked || locked.status !== ApprovalRequestStatus.Pending) {+ throw new BadRequestError({ message: "Request is not pending" });+ }++ const lockedStepIndex = steps.findIndex((s) => s.stepNumber === locked.currentStep);+ const lockedStep = steps[lockedStepIndex];+ if (!lockedStep) {+ throw new BadRequestError({ message: "Current step not found" });+ }++ // The step may have advanced since the pre-transaction check.+ const isEligibleForLockedStep = lockedStep.approvers.some(+ (approver) =>+ (approver.type === ApproverType.User && approver.id === actor.id) ||+ (approver.type === ApproverType.Group && userGroupIds.has(approver.id))+ );+ if (!isEligibleForLockedStep) {+ throw new ForbiddenRequestError({ message: "You are not an eligible approver for this step" });+ }++ const stepApprovals = await approvalRequestApprovalsDAL.find({ stepId: lockedStep.id }, { tx });+ if (stepApprovals.some((approval) => approval.approverUserId === actor.id)) {+ throw new BadRequestError({ message: "You have already approved this request" });+ }+await approvalRequestApprovalsDAL.create({- stepId: currentStep.id,+ stepId: lockedStep.id,approverUserId: actor.id,decision: ApprovalRequestApprovalDecision.Approved,comment@@ -1219,11 +1290,10 @@ export const approvalPolicyServiceFactory = ({tx);- const newApprovalCount = currentStep.approvals.length + 1;- if (newApprovalCount >= currentStep.requiredApprovals) {- // Step completed+ const newApprovalCount = stepApprovals.length + 1;+ if (newApprovalCount >= lockedStep.requiredApprovals) {await approvalRequestStepsDAL.updateById(- currentStep.id,+ lockedStep.id,{status: ApprovalRequestStepStatus.Completed,completedAt: new Date()@@ -1231,13 +1301,12 @@ export const approvalPolicyServiceFactory = ({tx);- const nextStep = steps[currentStepIndex + 1];+ const nextStep = steps[lockedStepIndex + 1];if (nextStep) {- // Move to next stepawait approvalRequestDAL.updateById(requestId,{- currentStep: request.currentStep + 1+ currentStep: locked.currentStep + 1},tx);@@ -1253,7 +1322,6 @@ export const approvalPolicyServiceFactory = ({nextStepToNotifyInner = nextStep;} else {- // All steps completedconst completedReq = await approvalRequestDAL.updateById(requestId,{@@ -1262,15 +1330,21 @@ export const approvalPolicyServiceFactory = ({tx);+ await resource.postApprovalTxRoutine?.(completedReq as TApprovalRequest, tx);+return { updatedRequest: completedReq, nextStepToNotify: null };}}- return { updatedRequest: request, nextStepToNotify: nextStepToNotifyInner };+ return { updatedRequest: locked, nextStepToNotify: nextStepToNotifyInner };});if (nextStepToNotify) {- await $notifyApprovers(nextStepToNotify, updatedRequest);+ await $notify({+ event: ApprovalNotificationEvent.Requested,+ request: updatedRequest,+ approvers: nextStepToNotify.approvers+ });}// Fetch fresh state@@ -1280,29 +1354,15 @@ export const approvalPolicyServiceFactory = ({const newRequest = { ...finalRequest, steps: finalSteps };if (finalRequest.status === ApprovalRequestStatus.Approved) {- const fac = APPROVAL_POLICY_FACTORY_MAP[updatedRequest.type as ApprovalPolicyType](- updatedRequest.type as ApprovalPolicyType- );-- const postApprovalContext: TPostApprovalContext = {- actor: {- type: actor.type,- id: actor.id,- authMethod: actor.authMethod,- orgId: actor.orgId- },- certificateApprovalService,- certificateRequestDAL- };-- await fac.postApprovalRoutine(approvalRequestGrantsDAL, newRequest as TApprovalRequest, postApprovalContext);+ await resource.postApprovalRoutine?.(newRequest as TApprovalRequest, actor);+ await $notify({ event: ApprovalNotificationEvent.Approved, request: finalRequest, comment });}const decorated = await $decorateRequest(newRequest, actor);return { request: decorated };};- const rejectRequest = async (requestId: string, { comment }: { comment?: string }, actor: OrgServiceActor) => {+ const rejectRequest = async (requestId: string, { comment }: { comment?: string }, actor: TApprovalActor) => {const request = await approvalRequestDAL.findById(requestId);if (!request) {throw new ForbiddenRequestError({ message: "Request not found" });@@ -1337,10 +1397,39 @@ export const approvalPolicyServiceFactory = ({throw new ForbiddenRequestError({ message: "You are not an eligible approver for this step" });}+ const assertDomainCanReject = resources[request.type as ApprovalPolicyType]?.assertCanReview;+ if (assertDomainCanReject) {+ await assertDomainCanReject({+ request,+ decision: ApprovalRequestApprovalDecision.Rejected,+ actor,+ userGroupIds+ });+ }+await approvalRequestDAL.transaction(async (tx) => {+ const locked = await approvalRequestDAL.findByIdForUpdate(requestId, tx);+ if (!locked || locked.status !== ApprovalRequestStatus.Pending) {+ throw new BadRequestError({ message: "Request is not pending" });+ }++ const lockedStep = steps.find((step) => step.stepNumber === locked.currentStep);+ if (!lockedStep) {+ throw new BadRequestError({ message: "Current step not found" });+ }++ const isEligibleForLockedStep = lockedStep.approvers.some(+ (approver) =>+ (approver.type === ApproverType.User && approver.id === actor.id) ||+ (approver.type === ApproverType.Group && userGroupIds.has(approver.id))+ );+ if (!isEligibleForLockedStep) {+ throw new ForbiddenRequestError({ message: "You are not an eligible approver for this step" });+ }+await approvalRequestApprovalsDAL.create({- stepId: currentStep.id,+ stepId: lockedStep.id,approverUserId: actor.id,decision: ApprovalRequestApprovalDecision.Rejected,comment@@ -1361,16 +1450,10 @@ export const approvalPolicyServiceFactory = ({const finalRequest = await approvalRequestDAL.findById(requestId);if (finalRequest) {- const fac = APPROVAL_POLICY_FACTORY_MAP[finalRequest.type as ApprovalPolicyType](- finalRequest.type as ApprovalPolicyType- );+ const resource = $resource(finalRequest.type as ApprovalPolicyType);- const postRejectionContext: TPostApprovalContext = {- certificateApprovalService,- certificateRequestDAL- };-- await fac.postRejectionRoutine(finalRequest as TApprovalRequest, postRejectionContext);+ await resource.postRejectionRoutine?.(finalRequest as TApprovalRequest);+ await $notify({ event: ApprovalNotificationEvent.Rejected, request: finalRequest, comment });}const decorated = await $decorateRequest({ ...finalRequest, steps: finalSteps }, actor);@@ -1381,9 +1464,13 @@ export const approvalPolicyServiceFactory = ({policyType: ApprovalPolicyType,scope: ApprovalPolicyScope,inputScopeId: string,- actor: OrgServiceActor+ actor: TApprovalActor) => {- const { projectId, scopeType: dbScopeType, scopeId: dbScopeId } = await $resolveScope(scope, inputScopeId);+ const {+ projectId,+ scopeType: dbScopeType,+ scopeId: dbScopeId+ } = await $resolveScope(scope, inputScopeId, policyType);let hasReadPermission: boolean;if (scope === ApprovalPolicyScope.PkiApplication && inputScopeId) {@@ -1473,7 +1560,7 @@ export const approvalPolicyServiceFactory = ({return { requests: decorated, projectId };};- const cancelRequest = async (requestId: string, actor: OrgServiceActor) => {+ const cancelRequest = async (requestId: string, actor: TApprovalActor) => {const request = await approvalRequestDAL.findById(requestId);if (!request) {throw new ForbiddenRequestError({ message: "Request not found" });@@ -1501,9 +1588,13 @@ export const approvalPolicyServiceFactory = ({policyType: ApprovalPolicyType,scope: ApprovalPolicyScope,inputScopeId: string,- actor: OrgServiceActor+ actor: TApprovalActor) => {- const { projectId, scopeType: dbScopeType, scopeId: dbScopeId } = await $resolveScope(scope, inputScopeId);+ const {+ projectId,+ scopeType: dbScopeType,+ scopeId: dbScopeId+ } = await $resolveScope(scope, inputScopeId, policyType);if (scope === ApprovalPolicyScope.PkiApplication && inputScopeId) {const { permission: resourcePermission } = await permissionService.getResourcePermission({@@ -1558,7 +1649,7 @@ export const approvalPolicyServiceFactory = ({return { grants: updatedGrants, projectId };};- const getGrantById = async (grantId: string, actor: OrgServiceActor) => {+ const getGrantById = async (grantId: string, actor: TApprovalActor) => {const grant = await approvalRequestGrantsDAL.findById(grantId);if (!grant) {throw new NotFoundError({ message: "Grant not found" });@@ -1592,50 +1683,57 @@ export const approvalPolicyServiceFactory = ({const revokeGrant = async (grantId: string,{ revocationReason }: { revocationReason?: string },- actor: OrgServiceActor+ actor: TApprovalActor) => {const grant = await approvalRequestGrantsDAL.findById(grantId);if (!grant) {throw new NotFoundError({ message: "Grant not found" });}- const { permission } = await permissionService.getProjectPermission({- actor: actor.type,- actorAuthMethod: actor.authMethod,- actorId: actor.id,- actorOrgId: actor.orgId,- projectId: grant.projectId,- actionProjectType: ActionProjectType.Any- });+ const grantPolicyType = grant.type as ApprovalPolicyType;+ const request = grant.requestId ? await approvalRequestDAL.findById(grant.requestId) : null;+ const assertDomainCanRevoke = resources[grantPolicyType]?.assertCanRevokeGrant;- const allowedAtProject = permission.can(- ProjectPermissionApprovalRequestGrantActions.Revoke,- ProjectPermissionSub.ApprovalRequestGrants- );+ if (assertDomainCanRevoke) {+ await assertDomainCanRevoke({ grant, request, actor });+ } else {+ const { permission } = await permissionService.getProjectPermission({+ actor: actor.type,+ actorAuthMethod: actor.authMethod,+ actorId: actor.id,+ actorOrgId: actor.orgId,+ projectId: grant.projectId,+ actionProjectType: ActionProjectType.Any+ });- if (!allowedAtProject) {- const request = grant.requestId ? await approvalRequestDAL.findById(grant.requestId) : null;- const requestScopeType = (request as { scopeType?: string | null } | null)?.scopeType ?? null;- const requestScopeId = (request as { scopeId?: string | null } | null)?.scopeId ?? null;- if (requestScopeType === ApprovalPolicyScope.PkiApplication && requestScopeId) {- const { permission: resourcePerm } = await permissionService.getResourcePermission({- actor: actor.type,- actorId: actor.id,- projectId: grant.projectId,- resourceType: ResourceType.CertificateApplication,- resourceId: requestScopeId,- actorAuthMethod: actor.authMethod,- actorOrgId: actor.orgId- });- ForbiddenError.from(resourcePerm).throwUnlessCan(- ProjectPermissionApprovalRequestGrantActions.Revoke,- ResourcePermissionSub.ApprovalRequestGrants- );- } else {- ForbiddenError.from(permission).throwUnlessCan(- ProjectPermissionApprovalRequestGrantActions.Revoke,- ProjectPermissionSub.ApprovalRequestGrants- );+ const allowedAtProject = permission.can(+ ProjectPermissionApprovalRequestGrantActions.Revoke,+ ProjectPermissionSub.ApprovalRequestGrants+ );++ if (!allowedAtProject) {+ const requestScopeType = (request as { scopeType?: string | null } | null)?.scopeType ?? null;+ const requestScopeId = (request as { scopeId?: string | null } | null)?.scopeId ?? null;+ if (requestScopeType === ApprovalPolicyScope.PkiApplication && requestScopeId) {+ const { permission: resourcePerm } = await permissionService.getResourcePermission({+ actor: actor.type,+ actorId: actor.id,+ projectId: grant.projectId,+ resourceType: ResourceType.CertificateApplication,+ resourceId: requestScopeId,+ actorAuthMethod: actor.authMethod,+ actorOrgId: actor.orgId+ });+ ForbiddenError.from(resourcePerm).throwUnlessCan(+ ProjectPermissionApprovalRequestGrantActions.Revoke,+ ResourcePermissionSub.ApprovalRequestGrants+ );+ } else {+ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionApprovalRequestGrantActions.Revoke,+ ProjectPermissionSub.ApprovalRequestGrants+ );+ }}}@@ -1650,13 +1748,19 @@ export const approvalPolicyServiceFactory = ({revocationReason});- return { grant: updatedGrant };+ const onDomainGrantRevoked = resources[grantPolicyType]?.onGrantRevoked;+ if (onDomainGrantRevoked) {+ const sendSideEffects = await onDomainGrantRevoked({ grant, actorId: actor.id });+ sendSideEffects();+ }++ return { grant: updatedGrant, request };};const checkPolicyMatch = async (policyType: ApprovalPolicyType,{ projectId, inputs }: { projectId: string; inputs: TApprovalPolicyInputs },- actor: OrgServiceActor+ actor: TApprovalActor) => {await permissionService.getProjectPermission({actor: actor.type,@@ -1667,15 +1771,15 @@ export const approvalPolicyServiceFactory = ({actionProjectType: ActionProjectType.Any});- const fac = APPROVAL_POLICY_FACTORY_MAP[policyType](policyType);+ const resource = $resource(policyType);- const policy = await fac.matchPolicy(approvalPolicyDAL, projectId, inputs);+ const policy = await resource.matchPolicy(projectId, inputs);if (!policy) {return { requiresApproval: false, hasActiveGrant: false };}- const activeGrant = await fac.canAccess(approvalRequestGrantsDAL, projectId, actor.id, inputs);+ const activeGrant = await resource.canAccess(projectId, actor.id, inputs);const innerConstraints = policy.constraints?.constraints;const constraints =@@ -1690,7 +1794,475 @@ export const approvalPolicyServiceFactory = ({};};+ const $actorGrantFilter = (actor: TApprovalSubjectActor) =>+ actor.type === ActorType.IDENTITY ? { granteeMachineIdentityId: actor.id } : { granteeUserId: actor.id };++ const $actorRequestFilter = (actor: TApprovalSubjectActor) =>+ actor.type === ActorType.IDENTITY ? { machineIdentityId: actor.id } : { requesterId: actor.id };++ const $matchingGrants = async (+ policyType: ApprovalPolicyType,+ projectId: string,+ actor: TApprovalSubjectActor,+ inputs: TApprovalPolicyInputs+ ) => {+ const resource = $resource(policyType);+ const grants = await approvalRequestGrantsDAL.find({+ ...$actorGrantFilter(actor),+ type: policyType,+ status: ApprovalRequestGrantStatus.Active,+ projectId+ });++ return grants.filter((grant) => resource.matchesInputs?.(grant.attributes, inputs));+ };++ const getActiveGrant = async (+ policyType: ApprovalPolicyType,+ projectId: string,+ actor: TApprovalSubjectActor,+ inputs: TApprovalPolicyInputs+ ) => {+ const matched = await $matchingGrants(policyType, projectId, actor, inputs);+ const now = new Date();++ return matched.find((grant) => !grant.expiresAt || new Date(grant.expiresAt) > now) ?? matched[0] ?? null;+ };++ const getAccessStatuses = async (+ policyType: ApprovalPolicyType,+ projectId: string,+ actor: TApprovalSubjectActor,+ inputsList: TApprovalPolicyInputs[]+ ): Promise<TApprovalAccessStatus[]> => {+ const empty = { accessStatus: ApprovalAccessStatus.None, grantExpiresAt: null, pendingRequestId: null };+ if (inputsList.length === 0) return [];++ const resource = $resource(policyType);+ const now = new Date();++ const [grants, pendingRequests] = await Promise.all([+ approvalRequestGrantsDAL.find({+ ...$actorGrantFilter(actor),+ type: policyType,+ status: ApprovalRequestGrantStatus.Active,+ projectId+ }),+ approvalRequestDAL.find({+ ...$actorRequestFilter(actor),+ type: policyType,+ status: ApprovalRequestStatus.Pending,+ projectId+ })+ ]);++ const liveGrants = grants.filter((grant) => !grant.expiresAt || new Date(grant.expiresAt) > now);++ return inputsList.map((inputs) => {+ const grant = liveGrants.find((g) => resource.matchesInputs?.(g.attributes, inputs));+ if (grant) {+ return {+ accessStatus: ApprovalAccessStatus.Granted,+ grantExpiresAt: grant.expiresAt ? new Date(grant.expiresAt) : null,+ pendingRequestId: null+ };+ }++ const pending = pendingRequests.find((request) =>+ resource.matchesInputs?.((request.requestData as { requestData?: unknown } | null)?.requestData, inputs)+ );++ return pending+ ? { accessStatus: ApprovalAccessStatus.Pending, grantExpiresAt: null, pendingRequestId: pending.id }+ : empty;+ });+ };++ const getScopeIdsWithApprovers = (+ policyType: ApprovalPolicyType,+ scopeType: ApprovalPolicyScope,+ scopeIds: string[]+ ) =>+ scopeIds.length === 0+ ? Promise.resolve([] as string[])+ : approvalPolicyDAL.findScopeIdsWithApprovers({ type: policyType, scopeType, scopeIds });++ const getBypassableScopeIds = async (+ policyType: ApprovalPolicyType,+ scopeType: ApprovalPolicyScope,+ scopeIds: string[],+ actor: TApprovalActor+ ) => {+ if (scopeIds.length === 0 || actor.type !== ActorType.USER) return [];++ const policies = await approvalPolicyDAL.find({ type: policyType, scopeType, $in: { scopeId: scopeIds } });+ if (policies.length === 0) return [];++ const [userGroupIds, bypassersByPolicyId] = await Promise.all([+ userGroupMembershipDAL+ .findGroupMembershipsByUserIdInOrg(actor.id, actor.orgId)+ .then((rows) => new Set(rows.map((g) => g.groupId))),+ approvalPolicyDAL.findBypassersByPolicyIds(policies.map((p) => p.id))+ ]);++ return policies+ .filter((policy) =>+ (bypassersByPolicyId[policy.id] ?? []).some(+ (b) =>+ (b.type === ApproverType.User && b.id === actor.id) ||+ (b.type === ApproverType.Group && userGroupIds.has(b.id))+ )+ )+ .map((policy) => policy.scopeId)+ .filter((scopeId): scopeId is string => Boolean(scopeId));+ };++ const reapScope = async (+ policyType: ApprovalPolicyType,+ scopeType: ApprovalPolicyScope,+ scopeId: string,+ tx: Knex+ ) => {+ const policy = await approvalPolicyDAL.findOne({ type: policyType, scopeType, scopeId }, tx);+ if (policy) await approvalPolicyDAL.deleteById(policy.id, tx);++ await approvalRequestDAL.update(+ { type: policyType, scopeType, scopeId, status: ApprovalRequestStatus.Pending },+ { status: ApprovalRequestStatus.Cancelled },+ tx+ );+ };++ const reapSubject = async (+ policyType: ApprovalPolicyType,+ {+ projectId,+ inputs,+ actorId,+ reason+ }: { projectId: string; inputs: TApprovalPolicyInputs; actorId: string; reason: string },+ tx: Knex+ ): Promise<() => void> => {+ const resource = $resource(policyType);+ const matches = (payload: unknown) => Boolean(resource.matchesInputs?.(payload, inputs));++ const pending = await approvalRequestDAL.find(+ { type: policyType, projectId, status: ApprovalRequestStatus.Pending },+ { tx }+ );+ const staleIds = pending+ .filter((request) => matches((request.requestData as { requestData?: unknown } | null)?.requestData))+ .map((request) => request.id);+ if (staleIds.length > 0) {+ await approvalRequestDAL.update({ $in: { id: staleIds } }, { status: ApprovalRequestStatus.Cancelled }, tx);+ }++ const activeGrants = await approvalRequestGrantsDAL.find(+ { type: policyType, status: ApprovalRequestGrantStatus.Active, projectId },+ { tx }+ );++ const pendingSignals: (() => void)[] = [];+ for (const grant of activeGrants.filter((g) => matches(g.attributes))) {+ // eslint-disable-next-line no-await-in-loop+ await approvalRequestGrantsDAL.updateById(+ grant.id,+ {+ status: ApprovalRequestGrantStatus.Revoked,+ revokedByUserId: actorId,+ revokedAt: new Date(),+ revocationReason: reason+ },+ tx+ );+ // eslint-disable-next-line no-await-in-loop+ pendingSignals.push((await resource.onGrantRevoked?.({ grant, actorId, tx })) ?? (() => {}));+ }++ return () => pendingSignals.forEach((send) => send());+ };++ const $attachGrantState = async <T extends { id: string }>(requests: T[]) => {+ const grants =+ requests.length > 0 ? await approvalRequestGrantsDAL.find({ $in: { requestId: requests.map((r) => r.id) } }) : [];++ const byRequestId = new Map(grants.filter((g) => g.requestId).map((g) => [g.requestId as string, g]));++ return requests.map((request) => {+ const grant = byRequestId.get(request.id);+ return {+ ...request,+ grantId: grant?.id ?? null,+ grantExpiresAt: grant?.expiresAt ?? null,+ grantStatus: grant?.status ?? null,+ isBreakGlass: Boolean(grant?.isBreakGlass),+ bypassReason: grant?.bypassReason ?? null+ };+ });+ };++ const $namesActor = (entries: { type: string; id: string }[], userId: string, userGroupIds: Set<string>) =>+ entries.some(+ (entry) =>+ (entry.type === ApproverType.User && entry.id === userId) ||+ (entry.type === ApproverType.Group && userGroupIds.has(entry.id))+ );++ const $userGroupIds = (actor: TApprovalActor) =>+ userGroupMembershipDAL+ .findGroupMembershipsByUserIdInOrg(actor.id, actor.orgId)+ .then((rows) => new Set(rows.map((g) => g.groupId)));++ const listScopeRequests = async (+ policyType: ApprovalPolicyType,+ scope: ApprovalPolicyScope,+ scopeId: string,+ { status, offset, limit }: { status?: string; offset?: number; limit?: number },+ actor: TApprovalActor+ ) => {+ const { projectId } = await $resolveScope(scope, scopeId, policyType);+ await $assertCanManagePolicy(+ projectId,+ scope,+ scopeId,+ actor,+ ResourcePermissionApprovalPolicyActions.Read,+ policyType+ );++ const requests = await approvalRequestDAL.find(+ { type: policyType, projectId, scopeType: scope, scopeId, ...(status ? { status } : {}) },+ { sort: [["createdAt", "desc"]], offset, limit, count: true }+ );++ return { requests: await $attachGrantState(requests), totalCount: Number(requests[0]?.count ?? 0) };+ };++ const $pendingForApprover = async (+ policyType: ApprovalPolicyType,+ scope: ApprovalPolicyScope,+ { projectId, scopeId }: { projectId: string; scopeId?: string },+ actor: TApprovalActor+ ) => {+ const userGroupIds = await $userGroupIds(actor);++ const isApprover = await approvalPolicyDAL.isProjectApprover({+ projectId,+ userId: actor.id,+ groupIds: [...userGroupIds],+ type: policyType,+ scopeType: scope+ });+ if (!isApprover) return null;++ const requests = await approvalRequestDAL.findByProjectId(policyType, projectId);+ const candidates = requests.filter((request) => {+ if (request.status !== ApprovalRequestStatus.Pending) return false;+ if (scopeId && request.scopeId !== scopeId) return false;++ const currentStep = request.steps.find((step) => step.stepNumber === request.currentStep);+ return Boolean(currentStep && $namesActor(currentStep.approvers, actor.id, userGroupIds));+ });++ const resource = $resource(policyType);+ if (!resource.isLiveApprover) return candidates;++ const liveScopeIds = new Set<string>();+ for (const candidateScopeId of new Set(+ candidates.map((r) => r.scopeId).filter((id): id is string => Boolean(id))+ )) {+ // eslint-disable-next-line no-await-in-loop+ if (await resource.isLiveApprover({ projectId, scopeId: candidateScopeId, actor, userGroupIds })) {+ liveScopeIds.add(candidateScopeId);+ }+ }++ return candidates.filter((request) => request.scopeId && liveScopeIds.has(request.scopeId));+ };++ const listPendingForApprover = async (+ policyType: ApprovalPolicyType,+ scope: ApprovalPolicyScope,+ args: { projectId: string; scopeId?: string },+ actor: TApprovalActor+ ) => {+ const pending = await $pendingForApprover(policyType, scope, args, actor);+ return { requests: await $attachGrantState(pending ?? []) };+ };++ const countPendingForApprover = async (+ policyType: ApprovalPolicyType,+ scope: ApprovalPolicyScope,+ projectId: string,+ actor: TApprovalActor+ ) => {+ const pending = await $pendingForApprover(policyType, scope, { projectId }, actor);+ return { pendingCount: pending?.length ?? 0, isApprover: pending !== null };+ };++ const getApproverRoster = async (+ policyType: ApprovalPolicyType,+ scope: ApprovalPolicyScope,+ { projectId, scopeId, inputs }: { projectId: string; scopeId: string; inputs: TApprovalPolicyInputs },+ actor: TApprovalSubjectActor+ ) => {+ const resource = $resource(policyType);+ const [policy] = await approvalPolicyDAL.findByProjectId(policyType, projectId, { scopeType: scope, scopeId });++ const livePolicySteps = policy ? await approvalPolicyDAL.findStepsByPolicyId(policy.id) : [];+ let steps = livePolicySteps.map((step) => ({+ requiredApprovals: step.requiredApprovals,+ approvers: step.approvers+ }));++ const pending = await approvalRequestDAL.find({+ ...$actorRequestFilter(actor),+ type: policyType,+ status: ApprovalRequestStatus.Pending,+ projectId+ });+ const pendingForSubject = pending.find((request) =>+ resource.matchesInputs?.((request.requestData as { requestData?: unknown } | null)?.requestData, inputs)+ );++ if (pendingForSubject) {+ const liveKeys = new Set(livePolicySteps.flatMap((step) => step.approvers.map((a) => `${a.type}:${a.id}`)));+ const requestSteps = await approvalRequestDAL.findStepsByRequestId(pendingForSubject.id);+ steps = requestSteps.map((step) => ({+ requiredApprovals: step.requiredApprovals,+ approvers: step.approvers.filter((a) => liveKeys.has(`${a.type}:${a.id}`))+ }));+ }++ if (steps.length === 0) return { steps: [] };++ const approvers = steps.flatMap((step) => step.approvers);+ const userIds = approvers.filter((a) => a.type === ApproverType.User).map((a) => a.id);+ const groupIds = approvers.filter((a) => a.type === ApproverType.Group).map((a) => a.id);++ const [users, groups, groupMemberships] = await Promise.all([+ userIds.length > 0 ? userDAL.find({ $in: { id: userIds } }) : [],+ groupIds.length > 0 ? groupDAL.find({ $in: { id: groupIds } }) : [],+ groupIds.length > 0 ? userGroupMembershipDAL.find({ $in: { groupId: groupIds } }) : []+ ]);++ const userNameById = new Map(+ users.map((u) => [u.id, [u.firstName, u.lastName].filter(Boolean).join(" ") || u.username || "Unknown user"])+ );+ const groupNameById = new Map(groups.map((g) => [g.id, g.name]));+ const memberCounts = new Map<string, number>();+ groupMemberships.forEach((m) => {+ if (m.groupId) memberCounts.set(m.groupId, (memberCounts.get(m.groupId) ?? 0) + 1);+ });++ return {+ steps: steps.map((step) => ({+ requiredApprovals: step.requiredApprovals,+ approvers: step.approvers.map((a) =>+ a.type === ApproverType.User+ ? { type: ApproverType.User, name: userNameById.get(a.id) ?? "Unknown user" }+ : {+ type: ApproverType.Group,+ name: groupNameById.get(a.id) ?? "Unknown group",+ memberCount: memberCounts.get(a.id) ?? 0+ }+ )+ }))+ };+ };++ const getScopeConfiguration = async (+ policyType: ApprovalPolicyType,+ scope: ApprovalPolicyScope,+ scopeId: string,+ actor: TApprovalActor+ ): Promise<TApprovalScopeConfiguration> => {+ const { policies } = await list(policyType, scope, scopeId, actor);+ const policy = policies[0];++ return policy+ ? {+ steps: policy.steps.map((step) => ({+ requiredApprovals: step.requiredApprovals,+ approvers: step.approvers+ })),+ bypassers: policy.bypassers.map((bypasser) => ({ type: bypasser.type, id: bypasser.id }))+ }+ : { steps: [], bypassers: [] };+ };++ const setScopeConfiguration = async (+ policyType: ApprovalPolicyType,+ scope: ApprovalPolicyScope,+ scopeId: string,+ {+ steps,+ bypassers,+ name,+ conditions,+ constraints+ }: {+ steps: TApprovalScopeConfiguration["steps"];+ bypassers?: PolicyBypasser[];+ name: string;+ conditions: TApprovalPolicy["conditions"]["conditions"];+ constraints: TApprovalPolicy["constraints"]["constraints"];+ },+ actor: TApprovalActor+ ) => {+ const { projectId } = await $resolveScope(scope, scopeId, policyType);+ const [existing] = await approvalPolicyDAL.findByProjectId(policyType, projectId, {+ scopeType: scope,+ scopeId+ });++ const hasApprovers = steps.some((step) => step.approvers.length > 0);+ if (!hasApprovers) {+ if (existing) await deleteById(existing.id, actor);+ return { policyId: existing?.id ?? null };+ }++ const policySteps = steps.map((step) => ({ ...step, notifyApprovers: true }));+ const bypassFields = bypassers ? { bypassers } : {};++ if (existing) {+ const { policy } = await updateById(existing.id, { steps: policySteps, ...bypassFields }, actor);+ return { policyId: policy.id };+ }++ const { policy } = await create(+ policyType,+ { scope, scopeId, name, conditions, constraints, steps: policySteps, ...bypassFields },+ actor+ );+ return { policyId: policy.id };+ };++ const buildAuditEvent = async (args: {+ action: ApprovalAuditAction;+ request: TApprovalRequests;+ grantId?: string;+ actorId: string;+ comment?: string;+ bypassReason?: string;+ }) => (await $resource(args.request.type as ApprovalPolicyType).buildAuditEvent?.(args)) ?? null;+return {+ buildAuditEvent,+ matchPolicy: (policyType: ApprovalPolicyType, projectId: string, inputs: TApprovalPolicyInputs) =>+ $resource(policyType).matchPolicy(projectId, inputs),+ getActiveGrant,+ getAccessStatuses,+ getScopeIdsWithApprovers,+ getBypassableScopeIds,+ reapScope,+ reapSubject,+ listScopeRequests,+ listPendingForApprover,+ countPendingForApprover,+ getApproverRoster,+ getScopeConfiguration,+ setScopeConfiguration,create,list,getById,diff --git a/backend/src/services/approval-policy/approval-policy-types.ts b/backend/src/services/approval-policy/approval-policy-types.tsindex b2e53cc3b8..0fd4b23382 100644--- a/backend/src/services/approval-policy/approval-policy-types.ts+++ b/backend/src/services/approval-policy/approval-policy-types.ts@@ -1,13 +1,22 @@import { Knex } from "knex";-import { TApprovalPolicies, TApprovalRequestGrants } from "@app/db/schemas";-import { TApprovalPolicyDALFactory } from "@app/services/approval-policy/approval-policy-dal";-import { TApprovalRequestGrantsDALFactory } from "@app/services/approval-policy/approval-request-dal";-import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";-import { TCertificateRequestDALFactory } from "@app/services/certificate-request/certificate-request-dal";-import { TCertificateApprovalService } from "@app/services/certificate-v3/certificate-approval-fns";--import { ApprovalPolicyScope, ApprovalPolicyType, ApproverType, EnforcementLevel } from "./approval-policy-enums";+import { TApprovalPolicies, TApprovalRequestGrants, TApprovalRequests } from "@app/db/schemas";+import { Event } from "@app/ee/services/audit-log/audit-log-types";+import { ResourcePermissionApprovalPolicyActions } from "@app/ee/services/permission/resource-permission";+import { OrgServiceActor } from "@app/lib/types";+import { TNotification } from "@app/lib/workflow-integrations/types";+import { NotificationType } from "@app/services/notification/notification-types";+import { SmtpTemplates } from "@app/services/smtp/smtp-service";++import {+ ApprovalAuditAction,+ ApprovalNotificationEvent,+ ApprovalPolicyScope,+ ApprovalPolicyType,+ ApprovalRequestApprovalDecision,+ ApproverType,+ EnforcementLevel+} from "./approval-policy-enums";import {TCertRequestPolicy,TCertRequestPolicyConditions,@@ -33,6 +42,10 @@ import {TPamAccessRequestData} from "./pam-access/pam-access-policy-types";+export type TApprovalActor = Pick<OrgServiceActor, "id" | "type" | "authMethod" | "orgId">;++export type TApprovalSubjectActor = Pick<TApprovalActor, "id" | "type">;+export type TApprovalPolicy = TPamAccessPolicy | TCertRequestPolicy | TCodeSigningPolicy;export type TApprovalPolicyInputs = TPamAccessPolicyInputs | TCertRequestPolicyInputs | TCodeSigningPolicyInputs;export type TApprovalPolicyConditions =@@ -56,9 +69,6 @@ export type TBypassAffordances = {export type BreakGlassBypassMetadata = {grantId: string;- resourceName?: string;- accountName?: string;- accessDuration: string;bypassReason: string;approverCount: number;};@@ -133,58 +143,139 @@ export interface TCreateRequestFromPolicyDTO {tx?: Knex;}-// Factory-export type TApprovalRequestFactoryMatchPolicy<I extends TApprovalPolicyInputs, P extends TApprovalPolicy> = (- approvalPolicyDAL: TApprovalPolicyDALFactory,- projectId: string,- inputs: I-) => Promise<P | null>;-export type TApprovalRequestFactoryCanAccess<I extends TApprovalPolicyInputs> = (- approvalRequestGrantsDAL: TApprovalRequestGrantsDALFactory,- projectId: string,- userId: string,- inputs: I-) => Promise<TApprovalRequestGrants | null>;-export type TApprovalRequestFactoryValidateConstraints<P extends TApprovalPolicy, R extends TApprovalRequestData> = (- policy: P,- inputs: R-) => { valid: boolean; errors?: string[] };--export type TPostApprovalContext = {- actor?: {- type: ActorType;- id: string;- authMethod: ActorAuthMethod;- orgId: string;- };- certificateApprovalService?: TCertificateApprovalService;- certificateRequestDAL?: Pick<TCertificateRequestDALFactory, "updateById" | "findById">;+export type TApprovalNotification = {+ inApp?: { type: NotificationType; title: string; body: string; link?: string };+ email?: { subjectLine: string; template: SmtpTemplates; substitutions: Record<string, unknown> };+ chat?: { workflowIntegrationId: string; channelIds: string[]; notification: TNotification }[];+};++// The one extension point: a policy type implements this and registers it at wiring time. Only the+// first three members are required; everything else falls back to shared behaviour.+export type TApprovalResource<+ I extends TApprovalPolicyInputs = TApprovalPolicyInputs,+ P extends TApprovalPolicy = TApprovalPolicy,+ R extends TApprovalRequestData = TApprovalRequestData+> = {+ matchPolicy: (projectId: string, inputs: I) => Promise<P | null>;+ canAccess: (projectId: string, actorId: string, inputs: I) => Promise<TApprovalRequestGrants | null>;+ validateConstraints: (policy: P, requestData: R) => { valid: boolean; errors?: string[] };++ // Whatever the approval entitles the requester to goes in the Tx variant, which commits with the+ // approval; anything reaching outside the database goes in postApprovalRoutine, after the commit.+ postApprovalTxRoutine?: (+ request: TApprovalRequest,+ tx: Knex,+ breakGlass?: { bypassReason: string }+ ) => Promise<{ grantId: string } | void>;+ postApprovalRoutine?: (request: TApprovalRequest, actor?: TApprovalActor) => Promise<void>;+ postRejectionRoutine?: (request: TApprovalRequest) => Promise<void>;++ // Whether a stored grant's attributes or a request's payload is for the thing these inputs name.+ // Without it the access-status and reaping helpers have nothing to match on.+ matchesInputs?: (payload: unknown, inputs: TApprovalPolicyInputs) => boolean;++ // Whether the actor is still an approver for the scope, for a type where the request's creation-time+ // approver snapshot can outlive the membership behind it.+ isLiveApprover?: (args: {+ projectId: string;+ scopeId: string;+ actor: TApprovalActor;+ userGroupIds: Set<string>;+ }) => Promise<boolean>;++ // The audit event a lifecycle action owes. A type whose auditors filter on resource ids contributes+ // its own event here; returning nothing leaves the generic approval event in place.+ buildAuditEvent?: (args: {+ action: ApprovalAuditAction;+ request: TApprovalRequests;+ grantId?: string;+ actorId: string;+ comment?: string;+ bypassReason?: string;+ }) => Promise<Event | null>;++ // Copy and chat routing for a lifecycle event. Returning nothing sends nothing.+ buildNotification?: (args: {+ event: ApprovalNotificationEvent;+ request: TApprovalRequests;+ comment?: string;+ bypassReason?: string;+ }) => Promise<TApprovalNotification | null>;+ // Narrows the notified approvers to those still eligible, for a type where an approver row can+ // outlive the membership behind it.+ filterActiveApprovers?: (+ request: TApprovalRequests,+ approvers: { type: ApproverType; id: string }[]+ ) => Promise<{ type: ApproverType; id: string }[]>;++ // Scope and authorization the service cannot work out on its own. Without these it resolves project+ // and application scopes itself, authorizes policy CRUD against project admin, and requires+ // approvers to be project members.+ resolveScope?: (scopeId: string) => Promise<{ projectId: string }>;+ // The default reads as an invitation to go ahead, which is wrong where an unconfigured scope is a+ // misconfiguration to report.+ noMatchingPolicyMessage?: string;+ assertCanManagePolicy?: (args: {+ projectId: string;+ scopeId: string | null;+ actor: TApprovalActor;+ action: ResourcePermissionApprovalPolicyActions;+ }) => Promise<void>;+ verifyPolicyActors?: (args: {+ projectId: string;+ scopeId: string | null;+ approvers: PolicyBypasser[];+ bypassers: PolicyBypasser[];+ }) => Promise<void>;+ assertCanCreateRequest?: (args: {+ projectId: string;+ policy: TApprovalPolicy;+ requestData: TApprovalRequestData;+ actor: TApprovalActor;+ }) => Promise<void>;+ assertCanReview?: (args: {+ request: TApprovalRequests;+ decision: ApprovalRequestApprovalDecision;+ actor: TApprovalActor;+ userGroupIds: Set<string>;+ }) => Promise<void>;+ // The default treats an empty bypasser list as everybody; a type reading it the other way says so here.+ isBreakGlassEligible?: (args: {+ request: TApprovalRequests;+ policy: TApprovalPolicies;+ bypassers: PolicyBypasser[];+ actor: TApprovalActor;+ userGroupIds: Set<string>;+ }) => Promise<boolean>;+ assertCanRevokeGrant?: (args: {+ grant: TApprovalRequestGrants;+ request: TApprovalRequests | null;+ actor: TApprovalActor;+ }) => Promise<void>;+ // Returns the side effects to fire once the revocation is durable, so a caller inside a transaction+ // that can still roll back cuts nothing early.+ onGrantRevoked?: (args: { grant: TApprovalRequestGrants; actorId: string; tx?: Knex }) => Promise<() => void>;};-export type TApprovalRequestFactoryPostApprovalRoutine<C extends TPostApprovalContext = TPostApprovalContext> = (- approvalRequestGrantsDAL: TApprovalRequestGrantsDALFactory,- request: TApprovalRequest,- context: C-) => Promise<void>;--export type TApprovalRequestFactoryPostRejectionRoutine<C extends TPostApprovalContext = TPostApprovalContext> = (- request: TApprovalRequest,- context: C-) => Promise<void>;--export type TApprovalResourceFactory<- I extends TApprovalPolicyInputs,- P extends TApprovalPolicy,- R extends TApprovalRequestData,- C extends TPostApprovalContext = TPostApprovalContext-> = (policyType: ApprovalPolicyType) => {- matchPolicy: TApprovalRequestFactoryMatchPolicy<I, P>;- canAccess: TApprovalRequestFactoryCanAccess<I>;- validateConstraints: TApprovalRequestFactoryValidateConstraints<P, R>;- postApprovalRoutine: TApprovalRequestFactoryPostApprovalRoutine<C>;- postRejectionRoutine: TApprovalRequestFactoryPostRejectionRoutine<C>;+export enum ApprovalAccessStatus {+ None = "none",+ Pending = "pending",+ Granted = "granted"+}++export type TApprovalAccessStatus = {+ accessStatus: ApprovalAccessStatus;+ grantExpiresAt: Date | null;+ pendingRequestId: string | null;+};++export type TApprovalScopeConfiguration = {+ steps: { requiredApprovals: number; approvers: PolicyBypasser[] }[];+ bypassers: PolicyBypasser[];};+export type TApprovalResourceRegistry = Partial<Record<ApprovalPolicyType, TApprovalResource>>;+export type TApprovalRequestSubjectMetadata = {certificateRequestId?: string;commonName?: string;diff --git a/backend/src/services/approval-policy/approval-request-fns.ts b/backend/src/services/approval-policy/approval-request-fns.tsindex 7b77b09768..ec67f81721 100644--- a/backend/src/services/approval-policy/approval-request-fns.ts+++ b/backend/src/services/approval-policy/approval-request-fns.ts@@ -2,12 +2,6 @@ import { Knex } from "knex";import { TApprovalRequests } from "@app/db/schemas";import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";-import { getConfig } from "@app/lib/config/env";-import { logger } from "@app/lib/logger";-import { TNotificationServiceFactory } from "@app/services/notification/notification-service";-import { NotificationType } from "@app/services/notification/notification-types";-import { SmtpTemplates, TSmtpService } from "@app/services/smtp/smtp-service";-import { TUserDALFactory } from "@app/services/user/user-dal";import {ApprovalPolicyType,@@ -172,118 +166,6 @@ export const resolveStepApproverUserIds = async (return userIds;};-export const notifyApproversForStep = async (- step: ApprovalPolicyStep,- request: TApprovalRequests,- dependencies: {- userGroupMembershipDAL: Pick<TUserGroupMembershipDALFactory, "find">;- notificationService: Pick<TNotificationServiceFactory, "createUserNotifications">;- },- preResolvedApproverUserIds?: Set<string>-): Promise<void> => {- const { userGroupMembershipDAL, notificationService } = dependencies;- const userIdsToNotify =- preResolvedApproverUserIds ?? (await resolveStepApproverUserIds(step, userGroupMembershipDAL));-- if (userIdsToNotify.size === 0) return;-- await notificationService.createUserNotifications(- Array.from(userIdsToNotify).map((userId) => ({- userId,- orgId: request.organizationId,- type: NotificationType.APPROVAL_REQUIRED,- title: "Approval Required",- body: `You have a new approval request for ${request.type} from ${request.requesterName}.`- }))- );-};--export const sendApprovalEmailsForStep = async (- step: ApprovalPolicyStep,- request: TApprovalRequests,- emailContext: {- subjectLine: string;- requestTypeLabel: string;- approvalUrl: string;- },- dependencies: {- userGroupMembershipDAL: Pick<TUserGroupMembershipDALFactory, "find">;- userDAL: Pick<TUserDALFactory, "find">;- smtpService: Pick<TSmtpService, "sendMail">;- },- preResolvedApproverUserIds?: Set<string>-): Promise<void> => {- const { userGroupMembershipDAL, userDAL, smtpService } = dependencies;- const approverUserIds =- preResolvedApproverUserIds ?? (await resolveStepApproverUserIds(step, userGroupMembershipDAL));-- if (approverUserIds.size === 0) return;-- const approverUsers = await userDAL.find({ $in: { id: Array.from(approverUserIds) } });- const recipients = approverUsers.filter((user) => user.email).map((user) => user.email as string);-- if (recipients.length === 0) return;-- await smtpService.sendMail({- recipients,- subjectLine: emailContext.subjectLine,- template: SmtpTemplates.PkiApprovalRequestNeedsReview,- substitutions: {- requesterName: request.requesterName,- requesterEmail: request.requesterEmail || undefined,- title: emailContext.subjectLine,- requestType: emailContext.requestTypeLabel,- justification: request.justification || undefined,- approvalUrl: emailContext.approvalUrl- }- });-};--export const notifyStepApprovers = async (- step: ApprovalPolicyStep,- request: TApprovalRequests,- dependencies: {- userGroupMembershipDAL: Pick<TUserGroupMembershipDALFactory, "find">;- notificationService: Pick<TNotificationServiceFactory, "createUserNotifications">;- userDAL: Pick<TUserDALFactory, "find">;- smtpService: Pick<TSmtpService, "sendMail">;- }-): Promise<void> => {- const { userGroupMembershipDAL, notificationService, userDAL, smtpService } = dependencies;-- const approverUserIds = await resolveStepApproverUserIds(step, userGroupMembershipDAL);-- await notifyApproversForStep(step, request, { userGroupMembershipDAL, notificationService }, approverUserIds);-- if (request.type !== ApprovalPolicyType.CertRequest && request.type !== ApprovalPolicyType.CertCodeSigning) {- return;- }-- const cfg = getConfig();- // skip email when SITE_URL is unset, the review link would dead-link- if (!cfg.SITE_URL) return;-- const isCodeSigning = request.type === ApprovalPolicyType.CertCodeSigning;-- try {- const approvalUrl = `${cfg.SITE_URL}/organizations/${request.organizationId}/projects/cert-manager/${request.projectId}/approvals/${request.id}?policyType=${encodeURIComponent(request.type)}&from=root-requests`;-- await sendApprovalEmailsForStep(- step,- request,- {- subjectLine: isCodeSigning ? "Code Signing Approval Request" : "Certificate Approval Request",- requestTypeLabel: isCodeSigning ? "code signing request" : "certificate request",- approvalUrl- },- { userGroupMembershipDAL, userDAL, smtpService },- approverUserIds- );- } catch (err) {- logger.error(err, `Failed to send approval request emails to approvers [requestId=${request.id}]`);- }-};-export const getApprovalRequestSubjectMetadata = (request: Pick<TApprovalRequests, "type" | "requestData">): TApprovalRequestSubjectMetadata => {diff --git a/backend/src/services/approval-policy/cert-request/cert-request-policy-factory.ts b/backend/src/services/approval-policy/cert-request/cert-request-policy-factory.tsindex fbfc0676ab..a188cd9c8e 100644--- a/backend/src/services/approval-policy/cert-request/cert-request-policy-factory.ts+++ b/backend/src/services/approval-policy/cert-request/cert-request-policy-factory.ts@@ -1,69 +1,83 @@+import { getConfig } from "@app/lib/config/env";import { logger } from "@app/lib/logger";+import { TCertificateRequestDALFactory } from "@app/services/certificate-request/certificate-request-dal";import { CertificateRequestStatus } from "@app/services/certificate-request/certificate-request-types";+import { TCertificateApprovalService } from "@app/services/certificate-v3/certificate-approval-fns";+import { NotificationType } from "@app/services/notification/notification-types";+import { SmtpTemplates } from "@app/services/smtp/smtp-service";-import { ApprovalPolicyScope } from "../approval-policy-enums";-import {- TApprovalRequestFactoryCanAccess,- TApprovalRequestFactoryMatchPolicy,- TApprovalRequestFactoryPostApprovalRoutine,- TApprovalRequestFactoryPostRejectionRoutine,- TApprovalRequestFactoryValidateConstraints,- TApprovalResourceFactory-} from "../approval-policy-types";-import {- TCertRequestApprovalContext,- TCertRequestPolicy,- TCertRequestPolicyInputs,- TCertRequestRequestData-} from "./cert-request-policy-types";+import { TApprovalPolicyDALFactory } from "../approval-policy-dal";+import { ApprovalNotificationEvent, ApprovalPolicyScope, ApprovalPolicyType } from "../approval-policy-enums";+import { TApprovalResource } from "../approval-policy-types";+import { TCertRequestPolicy, TCertRequestPolicyInputs, TCertRequestRequestData } from "./cert-request-policy-types";++type TCertRequestApprovalResourceDep = {+ approvalPolicyDAL: Pick<TApprovalPolicyDALFactory, "findByProjectId">;+ certificateApprovalService: TCertificateApprovalService;+ certificateRequestDAL: Pick<TCertificateRequestDALFactory, "updateById" | "findById">;+};-export const certRequestPolicyFactory: TApprovalResourceFactory<+export const certRequestApprovalResourceFactory = ({+ approvalPolicyDAL,+ certificateApprovalService,+ certificateRequestDAL+}: TCertRequestApprovalResourceDep): TApprovalResource<TCertRequestPolicyInputs,TCertRequestPolicy,- TCertRequestRequestData,- TCertRequestApprovalContext-> = (policyType) => {- const matchPolicy: TApprovalRequestFactoryMatchPolicy<TCertRequestPolicyInputs, TCertRequestPolicy> = async (- approvalPolicyDAL,- projectId,- inputs- ) => {- const policies = await approvalPolicyDAL.findByProjectId(policyType, projectId);+ TCertRequestRequestData+> => ({+ matchPolicy: async (projectId, inputs) => {+ const policies = await approvalPolicyDAL.findByProjectId(ApprovalPolicyType.CertRequest, projectId);const inputAppId = inputs.applicationId ?? null;const expectedScopeType = inputAppId ? ApprovalPolicyScope.PkiApplication : null;- const expectedScopeId = inputAppId ?? null;const candidates = (policies as TCertRequestPolicy[]).filter(- (p) => p.isActive && (p.scopeType ?? null) === expectedScopeType && (p.scopeId ?? null) === expectedScopeId+ (p) => p.isActive && (p.scopeType ?? null) === expectedScopeType && (p.scopeId ?? null) === inputAppId);- const matched = candidates.find((p) =>- p.conditions.conditions.some((c) => c.profileNames.includes(inputs.profileName))+ return (+ candidates.find((p) => p.conditions.conditions.some((c) => c.profileNames.includes(inputs.profileName))) ?? null);+ },++ // Certificate approvals issue a certificate rather than leaving a standing grant behind.+ canAccess: async () => null,- return matched ?? null;- };+ validateConstraints: () => ({ valid: true }),- const canAccess: TApprovalRequestFactoryCanAccess<TCertRequestPolicyInputs> = async () => {- return null;- };+ // Cert approvals notify approvers when raised; the decision shows up on the certificate itself.+ buildNotification: async ({ event, request }) => {+ if (event !== ApprovalNotificationEvent.Requested) return null;- const validateConstraints: TApprovalRequestFactoryValidateConstraints<- TCertRequestPolicy,- TCertRequestRequestData- > = () => {- return { valid: true };- };+ const cfg = getConfig();+ const approvalUrl = `${cfg.SITE_URL}/organizations/${request.organizationId}/projects/cert-manager/${request.projectId}/approvals/${request.id}?policyType=${encodeURIComponent(request.type)}&from=root-requests`;- const postApprovalRoutine: TApprovalRequestFactoryPostApprovalRoutine<TCertRequestApprovalContext> = async (- _approvalRequestGrantsDAL,- request,- context- ) => {- const { certificateApprovalService, certificateRequestDAL } = context;+ return {+ inApp: {+ type: NotificationType.APPROVAL_REQUIRED,+ title: "Approval Required",+ body: `You have a new approval request for ${request.type} from ${request.requesterName}.`,+ link: approvalUrl+ },+ email: cfg.SITE_URL+ ? {+ subjectLine: "Certificate Approval Request",+ template: SmtpTemplates.PkiApprovalRequestNeedsReview,+ substitutions: {+ requesterName: request.requesterName,+ requesterEmail: request.requesterEmail || undefined,+ title: "Certificate Approval Request",+ requestType: "certificate request",+ justification: request.justification || undefined,+ approvalUrl+ }+ }+ : undefined+ };+ },- const certRequestData = request.requestData.requestData as TCertRequestRequestData;- const certReqId = certRequestData.certificateRequestId;+ postApprovalRoutine: async (request) => {+ const certReqId = (request.requestData.requestData as TCertRequestRequestData).certificateRequestId;await certificateRequestDAL.updateById(certReqId, {status: CertificateRequestStatus.PENDING,@@ -74,7 +88,7 @@ export const certRequestPolicyFactory: TApprovalResourceFactory<await certificateApprovalService.issueCertificate(certReqId);logger.info({ certificateRequestId: certReqId, approvalRequestId: request.id },- "Certificate issued after approval"+ `Certificate issued after approval [certificateRequestId=${certReqId}]`);} catch (error) {const errorMessage = error instanceof Error ? error.message : String(error);@@ -83,34 +97,17 @@ export const certRequestPolicyFactory: TApprovalResourceFactory<errorMessage});logger.error(- {- error,- errorMessage,- errorStack: error instanceof Error ? error.stack : undefined,- certificateRequestId: certReqId,- approvalRequestId: request.id- },- "Failed to issue certificate after approval"+ { error, certificateRequestId: certReqId, approvalRequestId: request.id },+ `Failed to issue certificate after approval [certificateRequestId=${certReqId}]`);}- };+ },- const postRejectionRoutine: TApprovalRequestFactoryPostRejectionRoutine<TCertRequestApprovalContext> = async (- request,- context- ) => {- const certRequestData = request.requestData.requestData as TCertRequestRequestData;- await context.certificateRequestDAL.updateById(certRequestData.certificateRequestId, {+ postRejectionRoutine: async (request) => {+ const certReqId = (request.requestData.requestData as TCertRequestRequestData).certificateRequestId;+ await certificateRequestDAL.updateById(certReqId, {status: CertificateRequestStatus.REJECTED,approvalRequestId: request.id});- };-- return {- matchPolicy,- canAccess,- validateConstraints,- postApprovalRoutine,- postRejectionRoutine- };-};+ }+});diff --git a/backend/src/services/approval-policy/code-signing/code-signing-policy-factory.ts b/backend/src/services/approval-policy/code-signing/code-signing-policy-factory.tsindex ab3a5a7bed..f81485ec6e 100644--- a/backend/src/services/approval-policy/code-signing/code-signing-policy-factory.ts+++ b/backend/src/services/approval-policy/code-signing/code-signing-policy-factory.ts@@ -1,14 +1,12 @@+import { getConfig } from "@app/lib/config/env";import { ms } from "@app/lib/ms";+import { NotificationType } from "@app/services/notification/notification-types";+import { SmtpTemplates } from "@app/services/smtp/smtp-service";-import { ApprovalRequestGrantStatus } from "../approval-policy-enums";-import {- TApprovalRequestFactoryCanAccess,- TApprovalRequestFactoryMatchPolicy,- TApprovalRequestFactoryPostApprovalRoutine,- TApprovalRequestFactoryPostRejectionRoutine,- TApprovalRequestFactoryValidateConstraints,- TApprovalResourceFactory-} from "../approval-policy-types";+import { TApprovalPolicyDALFactory } from "../approval-policy-dal";+import { ApprovalNotificationEvent, ApprovalPolicyType, ApprovalRequestGrantStatus } from "../approval-policy-enums";+import { TApprovalResource } from "../approval-policy-types";+import { TApprovalRequestGrantsDALFactory } from "../approval-request-dal";import { normalizeCodeSigningScope } from "./code-signing-policy-fns";import {TCodeSigningGrantAttributes,@@ -17,56 +15,48 @@ import {TCodeSigningRequestData} from "./code-signing-policy-types";-export const codeSigningPolicyFactory: TApprovalResourceFactory<+type TCodeSigningApprovalResourceDep = {+ approvalPolicyDAL: Pick<TApprovalPolicyDALFactory, "findByProjectId">;+ approvalRequestGrantsDAL: Pick<TApprovalRequestGrantsDALFactory, "find" | "create">;+};++export const codeSigningApprovalResourceFactory = ({+ approvalPolicyDAL,+ approvalRequestGrantsDAL+}: TCodeSigningApprovalResourceDep): TApprovalResource<TCodeSigningPolicyInputs,TCodeSigningPolicy,TCodeSigningRequestData-> = (policyType) => {- const matchPolicy: TApprovalRequestFactoryMatchPolicy<TCodeSigningPolicyInputs, TCodeSigningPolicy> = async (- approvalPolicyDAL,- projectId,- inputs- ) => {- const policies = await approvalPolicyDAL.findByProjectId(policyType, projectId);- const policy = policies.find((p) => p.id === inputs.approvalPolicyId);-- if (!policy) return null;-- const p = policy as TCodeSigningPolicy;- if (!p.isActive) return null;-- return p;- };-- const canAccess: TApprovalRequestFactoryCanAccess<TCodeSigningPolicyInputs> = async (- approvalRequestGrantsDAL,- projectId,- userId,- inputs- ) => {+> => ({+ matchPolicy: async (projectId, inputs) => {+ const policies = await approvalPolicyDAL.findByProjectId(ApprovalPolicyType.CertCodeSigning, projectId);+ const policy = policies.find((p) => p.id === inputs.approvalPolicyId) as TCodeSigningPolicy | undefined;++ return policy?.isActive ? policy : null;+ },++ canAccess: async (projectId, actorId, inputs) => {const [userGrants, identityGrants] = await Promise.all([approvalRequestGrantsDAL.find({- granteeUserId: userId,- type: policyType,+ granteeUserId: actorId,+ type: ApprovalPolicyType.CertCodeSigning,status: ApprovalRequestGrantStatus.Active,projectId,revokedAt: null}),approvalRequestGrantsDAL.find({- granteeMachineIdentityId: userId,- type: policyType,+ granteeMachineIdentityId: actorId,+ type: ApprovalPolicyType.CertCodeSigning,status: ApprovalRequestGrantStatus.Active,projectId,revokedAt: null})]);- const grants = [...userGrants, ...identityGrants];-const now = new Date();return (- grants.find((grant) => {+ [...userGrants, ...identityGrants].find((grant) => {const attributes = grant.attributes as TCodeSigningGrantAttributes | null;if (!attributes || attributes.signerId !== inputs.signerId) return false;if (attributes.windowStart && new Date(attributes.windowStart) > now) return false;@@ -74,12 +64,39 @@ export const codeSigningPolicyFactory: TApprovalResourceFactory<return true;}) ?? null);- };+ },++ buildNotification: async ({ event, request }) => {+ if (event !== ApprovalNotificationEvent.Requested) return null;++ const cfg = getConfig();+ const approvalUrl = `${cfg.SITE_URL}/organizations/${request.organizationId}/projects/cert-manager/${request.projectId}/approvals/${request.id}?policyType=${encodeURIComponent(request.type)}&from=root-requests`;++ return {+ inApp: {+ type: NotificationType.APPROVAL_REQUIRED,+ title: "Approval Required",+ body: `You have a new approval request for ${request.type} from ${request.requesterName}.`,+ link: approvalUrl+ },+ email: cfg.SITE_URL+ ? {+ subjectLine: "Code Signing Approval Request",+ template: SmtpTemplates.PkiApprovalRequestNeedsReview,+ substitutions: {+ requesterName: request.requesterName,+ requesterEmail: request.requesterEmail || undefined,+ title: "Code Signing Approval Request",+ requestType: "code signing request",+ justification: request.justification || undefined,+ approvalUrl+ }+ }+ : undefined+ };+ },- const validateConstraints: TApprovalRequestFactoryValidateConstraints<TCodeSigningPolicy, TCodeSigningRequestData> = (- policy,- inputs- ) => {+ validateConstraints: (policy, inputs) => {const errors: string[] = [];const { maxWindowDuration, maxSignings } = policy.constraints.constraints;@@ -99,13 +116,10 @@ export const codeSigningPolicyFactory: TApprovalResourceFactory<errors.push(`Requested signings (${inputs.requestedSignings}) exceeds maximum of ${maxSignings}`);}- return {- valid: errors.length === 0,- errors: errors.length > 0 ? errors : undefined- };- };+ return { valid: errors.length === 0, errors: errors.length > 0 ? errors : undefined };+ },- const postApprovalRoutine: TApprovalRequestFactoryPostApprovalRoutine = async (approvalRequestGrantsDAL, request) => {+ postApprovalTxRoutine: async (request, tx) => {const requestData = request.requestData.requestData as TCodeSigningRequestData & {requestedWindowStart?: string;requestedWindowEnd?: string;@@ -130,30 +144,26 @@ export const codeSigningPolicyFactory: TApprovalResourceFactory<grantAttributes.windowStart = requestData.requestedWindowStart ?? new Date().toISOString();expiresAt = new Date(requestData.requestedWindowEnd);}+const scope = normalizeCodeSigningScope(requestData.scope);if (scope) {grantAttributes.scope = scope;}- await approvalRequestGrantsDAL.create({- projectId: request.projectId,- requestId: request.id,- granteeUserId: request.requesterId ?? null,- granteeMachineIdentityId: request.machineIdentityId ?? null,- status: ApprovalRequestGrantStatus.Active,- type: request.type,- attributes: grantAttributes,- expiresAt: expiresAt ?? null- });- };-- const postRejectionRoutine: TApprovalRequestFactoryPostRejectionRoutine = async () => {};-- return {- matchPolicy,- canAccess,- validateConstraints,- postApprovalRoutine,- postRejectionRoutine- };-};+ const grant = await approvalRequestGrantsDAL.create(+ {+ projectId: request.projectId,+ requestId: request.id,+ granteeUserId: request.requesterId ?? null,+ granteeMachineIdentityId: request.machineIdentityId ?? null,+ status: ApprovalRequestGrantStatus.Active,+ type: request.type,+ attributes: grantAttributes,+ expiresAt: expiresAt ?? null+ },+ tx+ );++ return { grantId: grant.id };+ }+});diff --git a/backend/src/services/approval-policy/pam-access/pam-access-policy-factory.ts b/backend/src/services/approval-policy/pam-access/pam-access-policy-factory.tsdeleted file mode 100644index 528e2c1753..0000000000--- a/backend/src/services/approval-policy/pam-access/pam-access-policy-factory.ts+++ /dev/null@@ -1,205 +0,0 @@-import picomatch from "picomatch";--import { ms } from "@app/lib/ms";--import { ApprovalRequestGrantStatus } from "../approval-policy-enums";-import {- TApprovalRequestFactoryCanAccess,- TApprovalRequestFactoryMatchPolicy,- TApprovalRequestFactoryPostApprovalRoutine,- TApprovalRequestFactoryPostRejectionRoutine,- TApprovalRequestFactoryValidateConstraints,- TApprovalResourceFactory-} from "../approval-policy-types";-import { TPamAccessPolicy, TPamAccessPolicyInputs, TPamAccessRequestData } from "./pam-access-policy-types";--// Helper function to check if a value matches any of the patterns in an array-const matchesAnyPattern = (value: string, patterns: string[]): boolean => {- return patterns.some((pattern) => picomatch(pattern)(value));-};--// Helper function to calculate specificity score for a pattern-const calculateSpecificity = (pattern: string): { wildcardCount: number; length: number } => {- const wildcardCount = (pattern.match(/\*/g) || []).length;- return { wildcardCount, length: pattern.length };-};--export const pamAccessPolicyFactory: TApprovalResourceFactory<- TPamAccessPolicyInputs,- TPamAccessPolicy,- TPamAccessRequestData-> = (policyType) => {- const matchPolicy: TApprovalRequestFactoryMatchPolicy<TPamAccessPolicyInputs, TPamAccessPolicy> = async (- approvalPolicyDAL,- projectId,- inputs- ) => {- const policies = await approvalPolicyDAL.findByProjectId(policyType, projectId);-- let bestMatch: { policy: TPamAccessPolicy; wildcardCount: number; patternLength: number } | null = null;-- for (const policy of policies) {- const p = policy as TPamAccessPolicy;- for (const c of p.conditions.conditions) {- let conditionMatches = false;- let totalWildcards = 0;- let totalPatternLength = 0;-- const hasResourceNames = c.resourceNames && c.resourceNames.length > 0;- const hasAccountNames = c.accountNames && c.accountNames.length > 0;-- if (hasResourceNames || hasAccountNames) {- let resourceMatches = true;- let accountMatches = true;-- if (hasResourceNames && inputs.resourceName) {- resourceMatches = matchesAnyPattern(inputs.resourceName, c.resourceNames!);- if (resourceMatches) {- for (const pattern of c.resourceNames!) {- if (picomatch(pattern)(inputs.resourceName)) {- const spec = calculateSpecificity(pattern);- totalWildcards += spec.wildcardCount;- totalPatternLength += spec.length;- break;- }- }- }- } else if (hasResourceNames && !inputs.resourceName) {- resourceMatches = false;- }-- if (hasAccountNames && inputs.accountName) {- accountMatches = matchesAnyPattern(inputs.accountName, c.accountNames!);- if (accountMatches) {- for (const pattern of c.accountNames!) {- if (picomatch(pattern)(inputs.accountName)) {- const spec = calculateSpecificity(pattern);- totalWildcards += spec.wildcardCount;- totalPatternLength += spec.length;- break;- }- }- }- } else if (hasAccountNames && !inputs.accountName) {- accountMatches = false;- }-- conditionMatches = resourceMatches && accountMatches;- }-- if (conditionMatches) {- if (- !bestMatch ||- totalWildcards < bestMatch.wildcardCount ||- (totalWildcards === bestMatch.wildcardCount && totalPatternLength > bestMatch.patternLength)- ) {- bestMatch = { policy: p, wildcardCount: totalWildcards, patternLength: totalPatternLength };- }- }- }- }-- return bestMatch?.policy || null;- };-- const canAccess: TApprovalRequestFactoryCanAccess<TPamAccessPolicyInputs> = async (- approvalRequestGrantsDAL,- projectId,- userId,- inputs- ) => {- const grants = await approvalRequestGrantsDAL.find({- granteeUserId: userId,- type: policyType,- status: ApprovalRequestGrantStatus.Active,- projectId,- revokedAt: null- });-- // TODO(andrey): Move some of this check to be part of SQL query- return (- grants.find((grant) => {- const grantAttributes = grant.attributes as TPamAccessPolicyInputs;-- if (inputs.resourceName || inputs.accountName) {- let resourceMatches = true;- let accountMatches = true;-- if (inputs.resourceName && grantAttributes.resourceName) {- resourceMatches = picomatch(grantAttributes.resourceName)(inputs.resourceName);- } else if (inputs.resourceName && !grantAttributes.resourceName) {- resourceMatches = false;- }-- if (inputs.accountName && grantAttributes.accountName) {- accountMatches = picomatch(grantAttributes.accountName)(inputs.accountName);- } else if (inputs.accountName && !grantAttributes.accountName) {- accountMatches = false;- }-- if (resourceMatches && accountMatches && (!grant.expiresAt || grant.expiresAt > new Date())) {- return true;- }- }-- return false;- }) ?? null- );- };-- const validateConstraints: TApprovalRequestFactoryValidateConstraints<TPamAccessPolicy, TPamAccessRequestData> = (- policy,- inputs- ) => {- const reqDuration = ms(inputs.accessDuration);- const durationConstraint = policy.constraints.constraints.accessDuration;- const minDuration = ms(durationConstraint.min);- const maxDuration = ms(durationConstraint.max);-- const errors: string[] = [];-- if (reqDuration < minDuration) {- errors.push(- `Access duration ${inputs.accessDuration} is below the minimum allowed duration of ${durationConstraint.min}`- );- }-- if (reqDuration > maxDuration) {- errors.push(- `Access duration ${inputs.accessDuration} exceeds the maximum allowed duration of ${durationConstraint.max}`- );- }-- return {- valid: errors.length === 0,- errors: errors.length > 0 ? errors : undefined- };- };-- const postApprovalRoutine: TApprovalRequestFactoryPostApprovalRoutine = async (approvalRequestGrantsDAL, request) => {- // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion- const inputs = request.requestData.requestData as TPamAccessRequestData;- const durationMs = ms(inputs.accessDuration);- const expiresAt = new Date(Date.now() + durationMs);-- await approvalRequestGrantsDAL.create({- projectId: request.projectId,- requestId: request.id,- granteeUserId: request.requesterId,- status: ApprovalRequestGrantStatus.Active,- type: request.type,- attributes: inputs,- expiresAt- });- };-- const postRejectionRoutine: TApprovalRequestFactoryPostRejectionRoutine = async () => {};-- return {- matchPolicy,- canAccess,- validateConstraints,- postApprovalRoutine,- postRejectionRoutine- };-};diff --git a/backend/src/services/approval-policy/pam-access/pam-access-policy-fns.test.ts b/backend/src/services/approval-policy/pam-access/pam-access-policy-fns.test.tsnew file mode 100644index 0000000000..649cf8b096--- /dev/null+++ b/backend/src/services/approval-policy/pam-access/pam-access-policy-fns.test.ts@@ -0,0 +1,68 @@+import { TApprovalRequestGrants } from "@app/db/schemas";++import { ApprovalPolicyType } from "../approval-policy-enums";+import { matchPamAccessGrants, parsePamAccessDuration } from "./pam-access-policy-fns";++const ACCOUNT_ID = "6cb4b2fa-1a9f-4b31-9f2d-6f3f5f9d4a11";+const OTHER_ACCOUNT_ID = "1d0e2c3b-4a59-4f68-9b77-2c8d5e6f7a22";+const FOLDER_ID = "9f8e7d6c-5b4a-4938-8271-6a5b4c3d2e33";+const OTHER_FOLDER_ID = "2a3b4c5d-6e7f-4809-91a2-b3c4d5e6f744";++const grant = (attributes: unknown) =>+ ({+ id: "grant",+ projectId: "project",+ status: "active",+ type: ApprovalPolicyType.PamAccess,+ isBreakGlass: false,+ attributes+ }) as TApprovalRequestGrants;++describe("parsePamAccessDuration", () => {+ test("parses a single-unit duration", () => {+ expect(parsePamAccessDuration("30m")).toBe(30 * 60 * 1000);+ expect(parsePamAccessDuration("2h")).toBe(2 * 60 * 60 * 1000);+ });++ // npm ms returns undefined rather than throwing, so an unparseable string has to be caught here+ test("rejects durations ms cannot parse, and non-positive ones", () => {+ expect(parsePamAccessDuration("2h30m")).toBeNull();+ expect(parsePamAccessDuration("soon")).toBeNull();+ expect(parsePamAccessDuration("0s")).toBeNull();+ expect(parsePamAccessDuration("-1h")).toBeNull();+ });+});++describe("matchPamAccessGrants", () => {+ const inputs = { accountId: ACCOUNT_ID, folderId: FOLDER_ID };++ test("matches a grant for the same account and folder", () => {+ expect(matchPamAccessGrants([grant({ accountId: ACCOUNT_ID, folderId: FOLDER_ID })], inputs)).toHaveLength(1);+ });++ test("ignores a grant for another account", () => {+ expect(matchPamAccessGrants([grant({ accountId: OTHER_ACCOUNT_ID, folderId: FOLDER_ID })], inputs)).toHaveLength(0);+ });++ // A grant approved while the account lived elsewhere must not follow it into a gated folder whose+ // approvers never reviewed it.+ test("ignores a grant whose folder no longer matches the account's", () => {+ expect(matchPamAccessGrants([grant({ accountId: ACCOUNT_ID, folderId: OTHER_FOLDER_ID })], inputs)).toHaveLength(0);+ });++ test("treats a missing access type as a session grant, never as a wildcard", () => {+ const legacy = [grant({ accountId: ACCOUNT_ID, folderId: FOLDER_ID })];++ expect(matchPamAccessGrants(legacy, { ...inputs, accessType: "session" })).toHaveLength(1);+ expect(matchPamAccessGrants(legacy, { ...inputs, accessType: "credential" })).toHaveLength(0);+ });++ test("keeps session and credential grants apart", () => {+ const grants = [+ grant({ accountId: ACCOUNT_ID, folderId: FOLDER_ID, accessType: "session" }),+ grant({ accountId: ACCOUNT_ID, folderId: FOLDER_ID, accessType: "credential" })+ ];++ expect(matchPamAccessGrants(grants, { ...inputs, accessType: "credential" })).toEqual([grants[1]]);+ });+});diff --git a/backend/src/services/approval-policy/pam-access/pam-access-policy-fns.ts b/backend/src/services/approval-policy/pam-access/pam-access-policy-fns.tsnew file mode 100644index 0000000000..e37a1b846b--- /dev/null+++ b/backend/src/services/approval-policy/pam-access/pam-access-policy-fns.ts@@ -0,0 +1,22 @@+import { TApprovalRequestGrants } from "@app/db/schemas";+import { ms } from "@app/lib/ms";++import { TPamAccessGrantAttributes, TPamAccessPolicyInputs } from "./pam-access-policy-types";++export const PAM_DEFAULT_ACCESS_TYPE = "session";++export const parsePamAccessDuration = (duration: string): number | null => {+ const parsed: number | undefined = ms(duration);+ return !parsed || parsed <= 0 ? null : parsed;+};++export const matchesPamAccessSubject = (payload: unknown, inputs: TPamAccessPolicyInputs) => {+ const attributes = payload as TPamAccessGrantAttributes | null;+ if (attributes?.accountId !== inputs.accountId) return false;+ if ("folderId" in inputs && (attributes?.folderId ?? null) !== (inputs.folderId ?? null)) return false;++ return (attributes?.accessType ?? PAM_DEFAULT_ACCESS_TYPE) === (inputs.accessType ?? PAM_DEFAULT_ACCESS_TYPE);+};++export const matchPamAccessGrants = (grants: TApprovalRequestGrants[], inputs: TPamAccessPolicyInputs) =>+ grants.filter((grant) => matchesPamAccessSubject(grant.attributes, inputs));diff --git a/backend/src/services/approval-policy/pam-access/pam-access-policy-schemas.ts b/backend/src/services/approval-policy/pam-access/pam-access-policy-schemas.tsindex 9284db35da..0d44d68559 100644--- a/backend/src/services/approval-policy/pam-access/pam-access-policy-schemas.ts+++ b/backend/src/services/approval-policy/pam-access/pam-access-policy-schemas.ts@@ -1,4 +1,3 @@-import picomatch from "picomatch";import { z } from "zod";import { ms } from "@app/lib/ms";@@ -13,61 +12,16 @@ import {BaseUpdateApprovalPolicySchema} from "../approval-policy-schemas";+export const PamAccessTypeSchema = z.enum(["session", "credential"]);+// Inputsexport const PamAccessPolicyInputsSchema = z.object({- resourceName: z.string().optional(),- accountName: z.string().optional()+ folderId: z.string().uuid().optional(),+ accountId: z.string().uuid(),+ accessType: PamAccessTypeSchema.optional()});-// Conditions-const resourceNameGlob = z.string().refine(- (el) => {- try {- picomatch.parse([el]);- return true;- } catch {- return false;- }- },- { message: "Invalid glob pattern for resource name" }-);--const accountNameGlob = z.string().refine(- (el) => {- try {- picomatch.parse([el]);- return true;- } catch {- return false;- }- },- { message: "Invalid glob pattern for account name" }-);--export const PamAccessPolicyConditionsSchema = z- .object({- resourceNames: resourceNameGlob.array().optional(),- accountNames: accountNameGlob.array().optional()- })- .array();--const MutatePamAccessPolicyConditionsSchema = z- .object({- resourceNames: resourceNameGlob.array().optional(),- accountNames: accountNameGlob.array().optional()- })- .refine(- (data) => {- // At least one condition type must be provided- const hasResourceNames = data.resourceNames && data.resourceNames.length > 0;- const hasAccountNames = data.accountNames && data.accountNames.length > 0;- return hasResourceNames || hasAccountNames;- },- {- message: "At least one condition type must be provided (resourceNames or accountNames)"- }- )- .array();+export const PamAccessPolicyConditionsSchema = z.object({}).array();const DurationSchema = z.string().refine((val) => {@@ -87,31 +41,20 @@ export const PamAccessPolicyConstraintsSchema = z.object({})});-// Request Data - Base schema for stored data (used by grants, etc.)+// Request Dataexport const PamAccessPolicyRequestDataSchema = z.object({- accessDuration: DurationSchema,- resourceName: resourceNameGlob.optional(),- accountName: accountNameGlob.optional()+ accountId: z.string().uuid(),+ folderId: z.string().uuid(),+ reason: z.string().trim().max(1024).optional(),+ duration: DurationSchema,+ accessType: PamAccessTypeSchema.optional()});-// Schema with validation for creating requests-const CreatePamAccessPolicyRequestDataSchema = z- .object({- accessDuration: DurationSchema,- resourceName: resourceNameGlob.optional(),- accountName: accountNameGlob.optional()- })- .refine(- (data) => {- // At least one identifier must be provided- const hasResourceName = Boolean(data.resourceName);- const hasAccountName = Boolean(data.accountName);- return hasResourceName || hasAccountName;- },- {- message: "At least one identifier must be provided (resourceName or accountName)"- }- );+export const PamAccessGrantAttributesSchema = z.object({+ accountId: z.string().uuid(),+ folderId: z.string().uuid().nullable().optional(),+ accessType: PamAccessTypeSchema.optional()+});// Policyexport const PamAccessPolicySchema = BaseApprovalPolicySchema.extend({@@ -126,12 +69,12 @@ export const PamAccessPolicySchema = BaseApprovalPolicySchema.extend({});export const CreatePamAccessPolicySchema = BaseCreateApprovalPolicySchema.extend({- conditions: MutatePamAccessPolicyConditionsSchema,+ conditions: PamAccessPolicyConditionsSchema,constraints: PamAccessPolicyConstraintsSchema});export const UpdatePamAccessPolicySchema = BaseUpdateApprovalPolicySchema.extend({- conditions: MutatePamAccessPolicyConditionsSchema.optional(),+ conditions: PamAccessPolicyConditionsSchema.optional(),constraints: PamAccessPolicyConstraintsSchema.optional()});@@ -144,12 +87,12 @@ export const PamAccessRequestSchema = BaseApprovalRequestSchema.extend({});export const CreatePamAccessRequestSchema = BaseCreateApprovalRequestSchema.extend({- requestData: CreatePamAccessPolicyRequestDataSchema+ requestData: PamAccessPolicyRequestDataSchema});// Grantsexport const PamAccessRequestGrantSchema = BaseApprovalRequestGrantSchema.extend({- attributes: PamAccessPolicyRequestDataSchema+ attributes: PamAccessGrantAttributesSchema});// Check Policy Match Responsediff --git a/backend/src/services/approval-policy/pam-access/pam-access-policy-types.ts b/backend/src/services/approval-policy/pam-access/pam-access-policy-types.tsindex 78118fcb0f..46796347c0 100644--- a/backend/src/services/approval-policy/pam-access/pam-access-policy-types.ts+++ b/backend/src/services/approval-policy/pam-access/pam-access-policy-types.ts@@ -1,6 +1,7 @@import { z } from "zod";import {+ PamAccessGrantAttributesSchema,PamAccessPolicyConditionsSchema,PamAccessPolicyConstraintsSchema,PamAccessPolicyInputsSchema,@@ -18,3 +19,5 @@ export type TPamAccessPolicyConstraints = z.infer<typeof PamAccessPolicyConstrai// Requestexport type TPamAccessRequest = z.infer<typeof PamAccessRequestSchema>;export type TPamAccessRequestData = z.infer<typeof PamAccessPolicyRequestDataSchema>;++export type TPamAccessGrantAttributes = z.infer<typeof PamAccessGrantAttributesSchema>;diff --git a/backend/src/services/certificate-v3/certificate-v3-service.test.ts b/backend/src/services/certificate-v3/certificate-v3-service.test.tsindex 4f168ce0c6..31bb563b6e 100644--- a/backend/src/services/certificate-v3/certificate-v3-service.test.ts+++ b/backend/src/services/certificate-v3/certificate-v3-service.test.ts@@ -225,7 +225,8 @@ describe("CertificateV3Service", () => {};const mockApprovalPolicyService = {- createRequestFromPolicy: vi.fn()+ createRequestFromPolicy: vi.fn(),+ matchPolicy: vi.fn()};const mockActor = {@@ -266,6 +267,7 @@ describe("CertificateV3Service", () => {mockCertificateRequestDAL.create.mockResolvedValue({ id: "cert-req-123", createdAt: new Date() });mockCertificateRequestDAL.transitionFromPending.mockResolvedValue({ id: "cert-req-123" });mockCertificateRequestDAL.attachCertificate.mockResolvedValue({ id: "cert-req-123" });+ mockApprovalPolicyService.matchPolicy.mockResolvedValue(null);mockApprovalPolicyService.createRequestFromPolicy.mockResolvedValue({request: { id: "approval-req-123", steps: [{ id: "step-1", stepNumber: 1, approvers: [] }] }});diff --git a/backend/src/services/certificate-v3/certificate-v3-service.ts b/backend/src/services/certificate-v3/certificate-v3-service.tsindex 0daa3b5411..bcd0ff5c67 100644--- a/backend/src/services/certificate-v3/certificate-v3-service.ts+++ b/backend/src/services/certificate-v3/certificate-v3-service.ts@@ -22,7 +22,6 @@ import { requestMemoKeys } from "@app/lib/request-context/memo-keys";import { requestMemoize } from "@app/lib/request-context/request-memoizer";import { TApprovalPolicyDALFactory } from "@app/services/approval-policy/approval-policy-dal";import { ApprovalPolicyType } from "@app/services/approval-policy/approval-policy-enums";-import { APPROVAL_POLICY_FACTORY_MAP } from "@app/services/approval-policy/approval-policy-factory";import { TApprovalPolicyServiceFactory } from "@app/services/approval-policy/approval-policy-service";import {TCertRequestPolicy,@@ -177,7 +176,7 @@ type TCertificateV3ServiceFactoryDep = {>;userDAL: Pick<TUserDALFactory, "findById">;identityDAL: Pick<TIdentityDALFactory, "findById">;- approvalPolicyService: Pick<TApprovalPolicyServiceFactory, "createRequestFromPolicy">;+ approvalPolicyService: Pick<TApprovalPolicyServiceFactory, "createRequestFromPolicy" | "matchPolicy">;resourceMetadataDAL: Pick<TResourceMetadataDALFactory, "insertMany" | "delete" | "find">;pkiAlertV2Queue?: Pick<TPkiAlertV2QueueServiceFactory, "queueCertificateEvent">;pkiApplicationProfileDAL: Pick<@@ -574,14 +573,10 @@ export const certificateV3ServiceFactory = ({);const applicationName = await $resolveApplicationName(applicationId);- const approvalFactory = APPROVAL_POLICY_FACTORY_MAP[ApprovalPolicyType.CertRequest](ApprovalPolicyType.CertRequest);- const matchedApprovalPolicy = (await approvalFactory.matchPolicy(- approvalPolicyDAL as TApprovalPolicyDALFactory,+ const matchedApprovalPolicy = (await approvalPolicyService.matchPolicy(+ ApprovalPolicyType.CertRequest,profile.projectId,- {- profileName: profile.slug,- applicationId- }+ { profileName: profile.slug, applicationId })) as TCertRequestPolicy | null;const certificateRequestWithDefaults = applyProfileDefaults(certificateRequest, profile.defaults);@@ -1398,16 +1393,10 @@ export const certificateV3ServiceFactory = ({});}- const csrApprovalFactory = APPROVAL_POLICY_FACTORY_MAP[ApprovalPolicyType.CertRequest](- ApprovalPolicyType.CertRequest- );- const csrMatchedApprovalPolicy = (await csrApprovalFactory.matchPolicy(- approvalPolicyDAL as TApprovalPolicyDALFactory,+ const csrMatchedApprovalPolicy = (await approvalPolicyService.matchPolicy(+ ApprovalPolicyType.CertRequest,profile.projectId,- {- profileName: profile.slug,- applicationId- }+ { profileName: profile.slug, applicationId })) as TCertRequestPolicy | null;if (csrMatchedApprovalPolicy && !shouldBypassApproval(actor, csrMatchedApprovalPolicy)) {@@ -1897,16 +1886,10 @@ export const certificateV3ServiceFactory = ({validateAwsPcaCaIssuanceInputs({ basicConstraints: certificateRequest.basicConstraints });}- const orderApprovalFactory = APPROVAL_POLICY_FACTORY_MAP[ApprovalPolicyType.CertRequest](- ApprovalPolicyType.CertRequest- );- const orderMatchedApprovalPolicy = (await orderApprovalFactory.matchPolicy(- approvalPolicyDAL as TApprovalPolicyDALFactory,+ const orderMatchedApprovalPolicy = (await approvalPolicyService.matchPolicy(+ ApprovalPolicyType.CertRequest,profile.projectId,- {- profileName: profile.slug,- applicationId- }+ { profileName: profile.slug, applicationId })) as TCertRequestPolicy | null;if (orderMatchedApprovalPolicy && !shouldBypassApproval(actor, orderMatchedApprovalPolicy)) {diff --git a/backend/src/services/pki-application/pki-application-enrollment-service.ts b/backend/src/services/pki-application/pki-application-enrollment-service.tsindex 5e259fd5f7..4b83418462 100644--- a/backend/src/services/pki-application/pki-application-enrollment-service.ts+++ b/backend/src/services/pki-application/pki-application-enrollment-service.ts@@ -20,9 +20,8 @@ import { BadRequestError, NotFoundError } from "@app/lib/errors";import { TProjectPermission } from "@app/lib/types";import { AppConnection } from "@app/services/app-connection/app-connection-enums";import { TAppConnectionServiceFactory } from "@app/services/app-connection/app-connection-service";-import { TApprovalPolicyDALFactory } from "@app/services/approval-policy/approval-policy-dal";import { ApprovalPolicyType } from "@app/services/approval-policy/approval-policy-enums";-import { APPROVAL_POLICY_FACTORY_MAP } from "@app/services/approval-policy/approval-policy-factory";+import { TApprovalPolicyServiceFactory } from "@app/services/approval-policy/approval-policy-service";import { TCertRequestPolicy } from "@app/services/approval-policy/cert-request/cert-request-policy-types";import { TCertificateAuthorityCertDALFactory } from "@app/services/certificate-authority/certificate-authority-cert-dal";import { TCertificateAuthorityDALFactory } from "@app/services/certificate-authority/certificate-authority-dal";@@ -113,7 +112,7 @@ type TPkiApplicationEnrollmentServiceFactoryDep = {scepEnrollmentConfigDAL: Pick<TScepEnrollmentConfigDALFactory, "create" | "updateById" | "deleteById" | "findById">;appConnectionService: Pick<TAppConnectionServiceFactory, "validateAppConnectionUsageById">;licenseService: Pick<TLicenseServiceFactory, "getPlan">;- approvalPolicyDAL: Pick<TApprovalPolicyDALFactory, "findByProjectId">;+ approvalPolicyService: Pick<TApprovalPolicyServiceFactory, "matchPolicy">;certificateProfileDAL: Pick<TCertificateProfileDALFactory, "findById">;certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findById" | "findByIdWithAssociatedCa">;certificateAuthoritySecretDAL: Pick<TCertificateAuthoritySecretDALFactory, "findOne">;@@ -138,7 +137,7 @@ export const pkiApplicationEnrollmentServiceFactory = ({scepEnrollmentConfigDAL,appConnectionService,licenseService,- approvalPolicyDAL,+ approvalPolicyService,certificateProfileDAL,certificateAuthorityDAL,certificateAuthoritySecretDAL,@@ -751,13 +750,13 @@ export const pkiApplicationEnrollmentServiceFactory = ({}if (isIntune && profile) {- const certRequestApprovalFactory = APPROVAL_POLICY_FACTORY_MAP[ApprovalPolicyType.CertRequest](- ApprovalPolicyType.CertRequest- );- const matchedApprovalPolicy = (await certRequestApprovalFactory.matchPolicy(- approvalPolicyDAL as TApprovalPolicyDALFactory,+ const matchedApprovalPolicy = (await approvalPolicyService.matchPolicy(+ ApprovalPolicyType.CertRequest,projectId,- { profileName: profile.slug, applicationId }+ {+ profileName: profile.slug,+ applicationId+ })) as TCertRequestPolicy | null;if (matchedApprovalPolicy) {diff --git a/backend/src/services/signer/signer-policy-service.ts b/backend/src/services/signer/signer-policy-service.tsindex 8f599ca6fa..310748173f 100644--- a/backend/src/services/signer/signer-policy-service.ts+++ b/backend/src/services/signer/signer-policy-service.ts@@ -11,24 +11,27 @@ import {import { BadRequestError, NotFoundError } from "@app/lib/errors";import { ms } from "@app/lib/ms";+import { dispatchApprovalNotification } from "../approval-policy/approval-notification-fns";import {TApprovalPolicyDALFactory,TApprovalPolicyStepApproversDALFactory,TApprovalPolicyStepsDALFactory} from "../approval-policy/approval-policy-dal";import {+ ApprovalNotificationEvent,ApprovalPolicyScope,ApprovalPolicyType,ApprovalRequestGrantStatus,ApprovalRequestStatus} from "../approval-policy/approval-policy-enums";+import { TApprovalResourceRegistry } from "../approval-policy/approval-policy-types";import {TApprovalRequestDALFactory,TApprovalRequestGrantsDALFactory,TApprovalRequestStepEligibleApproversDALFactory,TApprovalRequestStepsDALFactory} from "../approval-policy/approval-request-dal";-import { createApprovalRequestWithSteps, notifyStepApprovers } from "../approval-policy/approval-request-fns";+import { createApprovalRequestWithSteps } from "../approval-policy/approval-request-fns";import { CodeSigningScopeField } from "../approval-policy/code-signing/code-signing-policy-enums";import { normalizeCodeSigningScope } from "../approval-policy/code-signing/code-signing-policy-fns";import {@@ -38,9 +41,11 @@ import {} from "../approval-policy/code-signing/code-signing-policy-types";import { ActorType } from "../auth/auth-type";import { TIdentityDALFactory } from "../identity/identity-dal";+import { TKmsServiceFactory } from "../kms/kms-service";import { TMembershipDALFactory } from "../membership/membership-dal";import { TMembershipRoleDALFactory } from "../membership/membership-role-dal";import { TNotificationServiceFactory } from "../notification/notification-service";+import { TSlackIntegrationDALFactory } from "../slack/slack-integration-dal";import { TSmtpService } from "../smtp/smtp-service";import { TUserDALFactory } from "../user/user-dal";import { TSignerDALFactory } from "./signer-dal";@@ -71,6 +76,9 @@ type TSignerPolicyServiceFactoryDep = {membershipDAL: Pick<TMembershipDALFactory, "find" | "transaction">;membershipRoleDAL: Pick<TMembershipRoleDALFactory, "find">;userGroupMembershipDAL: Pick<TUserGroupMembershipDALFactory, "find">;+ slackIntegrationDAL: Pick<TSlackIntegrationDALFactory, "findByIdWithWorkflowIntegrationDetails">;+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;+ approvalResources: TApprovalResourceRegistry;identityGroupMembershipDAL: Pick<TIdentityGroupMembershipDALFactory, "find">;userDAL: Pick<TUserDALFactory, "findById" | "find">;identityDAL: Pick<TIdentityDALFactory, "findById">;@@ -139,6 +147,9 @@ export const signerPolicyServiceFactory = ({membershipDAL,membershipRoleDAL,userGroupMembershipDAL,+ slackIntegrationDAL,+ kmsService,+ approvalResources,identityGroupMembershipDAL,userDAL,identityDAL,@@ -668,14 +679,15 @@ export const signerPolicyServiceFactory = ({});- if (requestWithSteps.steps.length > 0) {- await notifyStepApprovers(requestWithSteps.steps[0], requestWithSteps, {- userGroupMembershipDAL,- notificationService,- userDAL,- smtpService- });- }+ await dispatchApprovalNotification(+ {+ event: ApprovalNotificationEvent.Requested,+ request: requestWithSteps,+ resource: approvalResources[ApprovalPolicyType.CertCodeSigning]!,+ approvers: requestWithSteps.steps[0]?.approvers ?? []+ },+ { userGroupMembershipDAL, userDAL, notificationService, smtpService, slackIntegrationDAL, kmsService }+ );return requestWithSteps;};diff --git a/frontend/src/hooks/api/pam/mutations.tsx b/frontend/src/hooks/api/pam/mutations.tsxindex da091b541e..9de151fef7 100644--- a/frontend/src/hooks/api/pam/mutations.tsx+++ b/frontend/src/hooks/api/pam/mutations.tsx@@ -831,10 +831,10 @@ export const useReviewPamAccessRequest = () => {const queryClient = useQueryClient();return useMutation({mutationFn: async ({ requestId, status, comment }: TReviewPamAccessRequestDTO) => {- const { data } = await apiRequest.post(`/api/v1/pam/access-requests/${requestId}/review`, {- status,- comment- });+ const { data } = await apiRequest.post(+ `/api/v1/approval-policies/pam-access/requests/${requestId}/${status === "approved" ? "approve" : "reject"}`,+ { comment }+ );return data;},onSuccess: () => {@@ -847,8 +847,11 @@ export const useReviewPamAccessRequest = () => {export const useRevokePamAccessRequest = () => {const queryClient = useQueryClient();return useMutation({- mutationFn: async ({ requestId }: TRevokePamAccessRequestDTO) => {- const { data } = await apiRequest.post(`/api/v1/pam/access-requests/${requestId}/revoke`);+ mutationFn: async ({ grantId }: TRevokePamAccessRequestDTO) => {+ const { data } = await apiRequest.post(+ `/api/v1/approval-policies/pam-access/grants/${grantId}/revoke`,+ { revocationReason: "Revoked by admin" }+ );return data;},onSuccess: () => {@@ -863,7 +866,7 @@ export const useBreakGlassPamAccessRequest = () => {return useMutation({mutationFn: async ({ requestId, bypassReason }: TBreakGlassPamAccessRequestDTO) => {const { data } = await apiRequest.post(- `/api/v1/pam/access-requests/${requestId}/break-glass`,+ `/api/v1/approval-policies/pam-access/requests/${requestId}/approve`,{ bypassReason });return data;diff --git a/frontend/src/hooks/api/pam/types/index.ts b/frontend/src/hooks/api/pam/types/index.tsindex c2a57ad33e..adab8f9eb1 100644--- a/frontend/src/hooks/api/pam/types/index.ts+++ b/frontend/src/hooks/api/pam/types/index.ts@@ -352,6 +352,7 @@ export type TAccessiblePamAccount = {requiresApproval?: boolean;requireReason?: boolean;accessStatus?: PamAccessStatus;+ grantId?: string | null;grantExpiresAt?: string | null;// Required, unlike the fields above: every endpoint returning this shape sets them, and a mapping// site that quietly omitted them is what stopped the break-glass action from ever rendering.@@ -731,6 +732,7 @@ export type TPamAccessRequest = {folderName?: string;host?: string;accessType?: PamAccessType;+ grantId?: string | null;grantExpiresAt?: string | null;grantStatus?: string | null;isBreakGlass?: boolean;@@ -784,7 +786,7 @@ export type TReviewPamAccessRequestDTO = {};export type TRevokePamAccessRequestDTO = {- requestId: string;+ grantId: string;};export type TBreakGlassPamAccessRequestDTO = {diff --git a/frontend/src/pages/pam/PamAccountsPage/components/FolderApprovalsTab.tsx b/frontend/src/pages/pam/PamAccountsPage/components/FolderApprovalsTab.tsxindex 9b0b859093..c5a7787442 100644--- a/frontend/src/pages/pam/PamAccountsPage/components/FolderApprovalsTab.tsx+++ b/frontend/src/pages/pam/PamAccountsPage/components/FolderApprovalsTab.tsx@@ -138,7 +138,7 @@ export const FolderApprovalsTab = ({ folderId, onDirtyChange }: Props) => {const confirmRevoke = async () => {if (!requestToRevoke) return;- await revokeMutation.mutateAsync({ requestId: requestToRevoke.id });+ await revokeMutation.mutateAsync({ grantId: requestToRevoke.grantId! });createNotification({ text: "Access revoked", type: "success" });setRequestToRevoke(null);};diff --git a/frontend/src/pages/pam/PamApprovalRequestsPage/components/ApprovalRequestDetailSheet.tsx b/frontend/src/pages/pam/PamApprovalRequestsPage/components/ApprovalRequestDetailSheet.tsxindex 10371ff041..e77b0a0d9a 100644--- a/frontend/src/pages/pam/PamApprovalRequestsPage/components/ApprovalRequestDetailSheet.tsx+++ b/frontend/src/pages/pam/PamApprovalRequestsPage/components/ApprovalRequestDetailSheet.tsx@@ -81,7 +81,7 @@ export const ApprovalRequestDetailSheet = ({ request, isOpen, onOpenChange }: Prconst handleRevoke = async () => {if (!request) return;- await revokeMutation.mutateAsync({ requestId: request.id });+ await revokeMutation.mutateAsync({ grantId: request.grantId! });createNotification({ text: "Access revoked", type: "success" });setIsRevokeConfirmOpen(false);onOpenChange(false);