Skip to content

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

allow break-glass without making a request first

Andreye1fca1b79f13
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.ts
index 302880a884..36a122b531 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
@@ -40,7 +40,13 @@ export const registerPamAccessRequestRouter = async (server: FastifyZodProvider)
accessType: z
.nativeEnum(PamAccessType)
.default(PamAccessType.Session)
- .describe("Whether the request unlocks launching sessions or viewing the account's credentials")
+ .describe("Whether the request unlocks launching sessions or viewing the account's credentials"),
+ breakGlass: z
+ .boolean()
+ .optional()
+ .describe(
+ "Self-approve the request immediately instead of waiting for an approver. Requires break-glass eligibility and a reason of at least 10 characters, which is reused as the bypass reason."
+ )
})
.refine((b) => Boolean(b.accountId) || Boolean(b.path), {
message: "Either 'accountId' or 'path' is required"
@@ -60,6 +66,7 @@ export const registerPamAccessRequestRouter = async (server: FastifyZodProvider)
reason: req.body.reason,
duration: req.body.duration,
accessType: req.body.accessType,
+ breakGlass: req.body.breakGlass,
actorId: req.permission.id,
actor: req.permission.type,
actorOrgId: req.permission.orgId,
@@ -83,6 +90,36 @@ export const registerPamAccessRequestRouter = async (server: FastifyZodProvider)
}
});
+ if (result.brokeGlass) {
+ const bypass = result.breakGlassMetadata;
+ 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: bypass.policyId,
+ policyName: bypass.policyName,
+ requestId: result.request.id,
+ grantId: bypass.grantId,
+ granteeUserId: req.permission.id,
+ granteeName: bypass.granteeName ?? undefined,
+ granteeEmail: bypass.granteeEmail ?? undefined,
+ accountId: bypass.accountId,
+ folderId: bypass.folderId,
+ folderName: bypass.folderName ?? undefined,
+ resourceName: bypass.folderName ?? undefined,
+ accountName: bypass.accountName,
+ accessDuration: bypass.accessDuration,
+ bypassReason: req.body.reason as string,
+ approverCount: bypass.approverCount
+ }
+ }
+ });
+ }
+
void server.services.telemetry
.sendPostHogEvents({
event: PostHogEventTypes.PamAccessRequestCreated,
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.ts
index e4110ee62d..13e838e671 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
@@ -737,803 +737,721 @@ export const pamAccessRequestServiceFactory = ({
};
};
- const createRequest = async ({
- accountId,
- path,
- projectId,
- reason,
+ const notifyOfBreakGlass = async ({
+ request,
+ steps,
+ account,
+ folderId,
duration,
- accessType = PamAccessType.Session,
- ...ctx
- }: TCreateAccessRequestDTO) => {
- const isCredentialRequest = accessType === PamAccessType.Credential;
- const trimmedReason = reason?.trim() || undefined;
- await verifyProductMembership(permissionService, projectId, ctx);
+ bypassReason,
+ actorId,
+ orgId
+ }: {
+ request: { id: string; requesterName?: string | null; requesterEmail?: string | null };
+ steps: { approvers: { type: string; id: string }[] }[];
+ account: { name: string; folderName: string | null };
+ folderId: string;
+ duration: string;
+ bypassReason: string;
+ actorId: string;
+ orgId: string;
+ }) => {
+ try {
+ const approverUserIds = new Set<string>();
+ const approverGroupIds = new Set<string>();
+ for (const step of steps) {
+ for (const approver of step.approvers) {
+ if (approver.type === ApproverType.User) approverUserIds.add(approver.id);
+ else approverGroupIds.add(approver.id);
+ }
+ }
- if (!accountId && !path) {
- throw new BadRequestError({ message: "Either 'accountId' or 'path' is required" });
- }
+ const groupMemberLists = await Promise.all(
+ [...approverGroupIds].map((groupId) => userGroupMembershipDAL.find({ groupId }))
+ );
+ groupMemberLists.forEach((members) => members.forEach((m) => approverUserIds.add(m.userId)));
+ approverUserIds.delete(actorId);
- // The CLI supplies a 'folderName/accountName' path; the dashboard supplies an accountId.
- const account = path
- ? await resolveAccountByPath({ pamFolderDAL, pamAccountDAL }, projectId, path)
- : await pamAccountDAL.findByIdWithDetails(accountId as string);
- if (!account || account.projectId !== projectId) {
- throw new NotFoundError({ message: "Account not found" });
- }
+ if (approverUserIds.size > 0) {
+ const approverUsers = await userDAL.find({ $in: { id: [...approverUserIds] } });
- // 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
- );
+ 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 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"
- });
+ 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}]`);
}
- 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) });
+ 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
+ }
}
- }
+ });
+ };
- if (accessControls.requireReason && !trimmedReason) {
+ const breakGlassRequest = async ({ requestId, projectId, bypassReason, ...ctx }: TBreakGlassAccessRequestDTO) => {
+ await verifyProductMembership(permissionService, projectId, ctx);
+
+ const trimmedReason = bypassReason.trim();
+ if (trimmedReason.length < 10) {
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"
+ message: "A break-glass reason of at least 10 characters is required. It is recorded in the audit log."
});
}
- if (!account.folderId) {
- throw new BadRequestError({ message: "Account must be in a folder to require approval" });
+ if (ctx.actor !== ActorType.USER) {
+ throw new ForbiddenRequestError({ message: "Only users can break glass on an access request" });
}
- const policy = await findFolderPolicy(account.folderId);
- if (!policy) {
- throw new BadRequestError({ message: "No approval configuration found for this folder" });
+ const request = await approvalRequestDAL.findById(requestId);
+ if (!request || request.projectId !== projectId || request.type !== ApprovalPolicyType.PamAccess) {
+ throw new NotFoundError({ message: "Request not found" });
}
- 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 (request.requesterId !== ctx.actorId) {
+ throw new ForbiddenRequestError({ message: "You can only break glass on your own access request" });
}
- if (maxMs && durationMs > maxMs) {
- throw new BadRequestError({ message: `Access duration must be at most ${accessDuration?.max}` });
+
+ if (request.status !== ApprovalRequestStatus.Pending) {
+ throw new BadRequestError({ message: "Request is not pending" });
}
- const existingPending = await approvalRequestDAL.find({
- ...actorRequestFilter(ctx),
- type: ApprovalPolicyType.PamAccess,
- status: ApprovalRequestStatus.Pending,
- projectId
- });
+ if (request.expiresAt && new Date(request.expiresAt) < new Date()) {
+ await approvalRequestDAL.updateById(requestId, { status: ApprovalRequestStatus.Expired });
+ throw new BadRequestError({ message: "Request has expired" });
+ }
- 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
- );
- });
+ const requestData = request.requestData as { version: number; requestData: TPamAccessRequestData } | null;
+ const folderId = requestData?.requestData?.folderId;
+ const accountId = requestData?.requestData?.accountId;
+ if (!folderId || !accountId) {
+ throw new BadRequestError({ message: "This request is missing the account it was raised for" });
+ }
- if (hasPendingForAccount) {
+ const account = await pamAccountDAL.findByIdWithDetails(accountId);
+ if (!account || account.projectId !== projectId || account.folderId !== folderId) {
throw new BadRequestError({
- message: isCredentialRequest
- ? "You already have a pending credential request for this account"
- : "You already have a pending request for this account"
+ message: "This request is no longer valid because the account has moved or been removed"
});
}
- 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 { 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.`
});
}
- const stepsForRequest = policySteps.map((s) => ({
- name: s.name ?? null,
- requiredApprovals: s.requiredApprovals,
- notifyApprovers: s.notifyApprovers ?? true,
- approvers: s.approvers
- }));
+ const policy = await findFolderPolicy(folderId);
+ if (!policy) {
+ throw new ForbiddenRequestError({ message: "Approval policy no longer exists for this folder" });
+ }
- const isIdentityActor = ctx.actor === ActorType.IDENTITY;
- const accessTypeLabel = isCredentialRequest ? "credential access" : "access";
- const { name: requesterName, email: requesterEmail } = await resolveRequesterDisplay(ctx);
+ const userGroupIds = await getUserGroupIds(ctx.actorId, ctx.actorOrgId);
+ if (!(await isFolderBreakGlassApprover(policy.id, ctx.actorId, userGroupIds))) {
+ throw new ForbiddenRequestError({
+ message: "You are not a break-glass approver for this folder"
+ });
+ }
- const requestData = {
- accountId: account.id,
- folderId: account.folderId,
- reason: trimmedReason,
- duration,
- accessType
- } as unknown as TApprovalRequestData;
+ 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 request = await createApprovalRequestWithSteps(
- {
- projectId,
- organizationId: ctx.actorOrgId,
- policyId: policy.id,
- policyType: ApprovalPolicyType.PamAccess,
- policySteps: stepsForRequest,
- requestData,
- 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
- },
- {
- approvalRequestDAL,
- approvalRequestStepsDAL,
- approvalRequestStepEligibleApproversDAL
- }
+ // Break-glass skips the approver, not the permission the request itself needed.
+ const accessType = requestData.requestData.accessType ?? PamAccessType.Session;
+ await checkAccountAccess(
+ permissionService,
+ account.id,
+ account.folderId,
+ projectId,
+ accessType === PamAccessType.Credential
+ ? ResourcePermissionPamResourceActions.ViewCredentials
+ : ResourcePermissionPamResourceActions.LaunchSessions,
+ ctx
);
- const approvalUrl = `${getConfig().SITE_URL}/organizations/${ctx.actorOrgId}/pam/approval-requests?requestId=${request.id}`;
+ 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);
- const firstStep = stepsForRequest[0];
- if (firstStep) {
- 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}]`);
+ 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" });
}
- try {
- const approverUserIds = new Set<string>();
- firstStep.approvers.filter((a) => a.type === ApproverType.User).forEach((a) => approverUserIds.add(a.id));
+ if (locked.expiresAt && new Date(locked.expiresAt) < new Date()) {
+ await approvalRequestDAL.updateById(requestId, { status: ApprovalRequestStatus.Expired }, tx);
+ throw new BadRequestError({ message: "Request has expired" });
+ }
- const groupMemberLists = await Promise.all(
- firstStep.approvers
- .filter((a) => a.type === ApproverType.Group)
- .map((a) => userGroupMembershipDAL.find({ groupId: a.id }))
+ await Promise.all(
+ steps.map((step) =>
+ approvalRequestStepsDAL.updateById(
+ step.id,
+ { status: ApprovalRequestStepStatus.Completed, completedAt: new Date() },
+ tx
+ )
+ )
+ );
+
+ 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
);
- 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);
+ await approvalRequestDAL.updateById(requestId, { status: ApprovalRequestStatus.Approved }, tx);
- 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}]`);
- }
- }
+ 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
+ );
- 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 { updatedRequest: await approvalRequestDAL.findById(requestId, tx), grant: createdGrant };
});
- return {
+ void notifyOfBreakGlass({
request,
- accountId: account.id,
- folderId: account.folderId,
+ steps,
+ account,
+ folderId,
+ duration: requestData.requestData.duration,
+ bypassReason: trimmedReason,
+ actorId: ctx.actorId,
+ orgId: ctx.actorOrgId
+ }).catch((err) => {
+ logger.error(err, `Failed to send PAM break-glass notifications [requestId=${requestId}]`);
+ });
+
+ return {
+ request: updatedRequest,
+ accountId,
+ folderId,
accountType: account.accountType,
- accessType
+ grantId: grant.id,
+ policyId: policy.id,
+ policyName: policy.name,
+ accountName: account.name,
+ folderName: account.folderName,
+ granteeName: request.requesterName,
+ granteeEmail: request.requesterEmail,
+ accessDuration: requestData.requestData.duration,
+ approverCount: bypassedApproverCount
};
};
- const listRequests = async ({ projectId, folderId, status, offset, limit, ...ctx }: TListAccessRequestsDTO) => {
+ const createRequest = async ({
+ accountId,
+ path,
+ projectId,
+ reason,
+ duration,
+ accessType = PamAccessType.Session,
+ breakGlass = false,
+ ...ctx
+ }: TCreateAccessRequestDTO) => {
+ const isCredentialRequest = accessType === PamAccessType.Credential;
+ const trimmedReason = reason?.trim() || undefined;
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" });
+ if (!accountId && !path) {
+ throw new BadRequestError({ message: "Either 'accountId' or 'path' 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);
+ if (breakGlass && (trimmedReason?.length ?? 0) < 10) {
+ throw new BadRequestError({
+ message: "A reason of at least 10 characters is required to break glass. It is recorded in the audit log."
+ });
+ }
- return {
- requests: await attachGrantExpiry(await enrichRequestsWithNames(requests)),
- totalCount
- };
- };
+ // The CLI supplies a 'folderName/accountName' path; the dashboard supplies an accountId.
+ const account = path
+ ? await resolveAccountByPath({ pamFolderDAL, pamAccountDAL }, projectId, path)
+ : await pamAccountDAL.findByIdWithDetails(accountId as string);
+ if (!account || account.projectId !== projectId) {
+ throw new NotFoundError({ message: "Account not found" });
+ }
- // 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))
+ // 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 listPendingMyApproval = async ({ projectId, folderId, ...ctx }: TListPendingMyApprovalDTO) => {
- await verifyProductMembership(permissionService, projectId, ctx);
-
- const userGroupIds = await getUserGroupIds(ctx.actorId, ctx.actorOrgId);
+ 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"
+ });
+ }
- // 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);
+ 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) });
}
}
- const result = candidates.filter((r) => {
- const fId = (r.requestData as { requestData?: TPamAccessRequestData } | null)?.requestData?.folderId;
- return Boolean(fId && liveApproverFolders.has(fId));
- });
+ 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"
+ });
+ }
- return { requests: await attachGrantExpiry(await enrichRequestsWithNames(result)) };
- };
+ if (!account.folderId) {
+ throw new BadRequestError({ message: "Account must be in a folder to require approval" });
+ }
- const getCount = async ({ projectId, ...ctx }: TGetAccessRequestCountDTO) => {
- await verifyProductMembership(permissionService, projectId, ctx);
+ const policy = await findFolderPolicy(account.folderId);
+ if (!policy) {
+ throw new BadRequestError({ message: "No approval configuration found for this folder" });
+ }
- const userGroupIds = await getUserGroupIds(ctx.actorId, ctx.actorOrgId);
+ 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 isApprover = await approvalPolicyDAL.isProjectApprover({
- projectId,
- userId: ctx.actorId,
- groupIds: [...userGroupIds],
+ const existingPending = await approvalRequestDAL.find({
+ ...actorRequestFilter(ctx),
type: ApprovalPolicyType.PamAccess,
- scopeType: ApprovalPolicyScope.PamFolder
+ status: ApprovalRequestStatus.Pending,
+ projectId
});
- // 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 };
- };
+ 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
+ );
+ });
- // 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");
+ 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 reviewRequest = async ({ requestId, projectId, status, comment, ...ctx }: TReviewAccessRequestDTO) => {
- await verifyProductMembership(permissionService, projectId, ctx);
+ const policySteps = await approvalPolicyDAL.findStepsByPolicyId(policy.id);
- const request = await approvalRequestDAL.findById(requestId);
- if (!request || request.projectId !== projectId || request.type !== ApprovalPolicyType.PamAccess) {
- throw new NotFoundError({ message: "Request not found" });
+ // 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."
+ });
}
- if (request.status !== ApprovalRequestStatus.Pending) {
- throw new BadRequestError({ message: "Request is not pending" });
- }
+ const stepsForRequest = policySteps.map((s) => ({
+ name: s.name ?? null,
+ requiredApprovals: s.requiredApprovals,
+ notifyApprovers: s.notifyApprovers ?? true,
+ approvers: s.approvers
+ }));
- if (request.expiresAt && new Date(request.expiresAt) < new Date()) {
- await approvalRequestDAL.updateById(requestId, { status: ApprovalRequestStatus.Expired });
- throw new BadRequestError({ message: "Request has expired" });
- }
+ const isIdentityActor = ctx.actor === ActorType.IDENTITY;
+ const accessTypeLabel = isCredentialRequest ? "credential access" : "access";
+ const { name: requesterName, email: requesterEmail } = await resolveRequesterDisplay(ctx);
- // 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 = {
+ accountId: account.id,
+ folderId: account.folderId,
+ reason: trimmedReason,
+ duration,
+ accessType
+ } as unknown as TApprovalRequestData;
- const requestData = request.requestData as { version: number; requestData: TPamAccessRequestData } | null;
- const folderId = requestData?.requestData?.folderId;
+ const request = await createApprovalRequestWithSteps(
+ {
+ projectId,
+ organizationId: ctx.actorOrgId,
+ policyId: policy.id,
+ policyType: ApprovalPolicyType.PamAccess,
+ policySteps: stepsForRequest,
+ requestData,
+ 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
+ },
+ {
+ approvalRequestDAL,
+ approvalRequestStepsDAL,
+ approvalRequestStepEligibleApproversDAL
+ }
+ );
- // 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 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}]`);
}
- }
- 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];
+ try {
+ const approverUserIds = new Set<string>();
+ firstStep.approvers.filter((a) => a.type === ApproverType.User).forEach((a) => approverUserIds.add(a.id));
- const userGroupIds = await getUserGroupIds(ctx.actorId, ctx.actorOrgId);
+ 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)));
- // 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" });
- }
+ const approverUsers = approverUserIds.size > 0 ? await userDAL.find({ $in: { id: [...approverUserIds] } }) : [];
+ const recipients = approverUsers.filter((u) => u.email).map((u) => u.email as string);
- // 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" });
+ 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}]`);
}
}
- 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 (breakGlass) {
+ const result = await breakGlassRequest({
+ requestId: request.id,
+ projectId,
+ bypassReason: trimmedReason as string,
+ ...ctx
+ });
+ return {
+ request: result.request,
+ accountId: account.id,
+ folderId: account.folderId,
+ accountType: account.accountType,
+ accessType,
+ brokeGlass: true as const,
+ breakGlassMetadata: result
+ };
}
- 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" });
+ 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
}
-
- 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;
+ return {
+ request,
+ accountId: account.id,
+ folderId: account.folderId,
+ accountType: account.accountType,
+ accessType,
+ brokeGlass: false as const,
+ breakGlassMetadata: undefined
+ };
+ };
- // 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 listRequests = async ({ projectId, folderId, status, offset, limit, ...ctx }: TListAccessRequestsDTO) => {
+ await verifyProductMembership(permissionService, projectId, ctx);
- 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" });
- }
+ // 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 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" });
- }
+ const filter: Record<string, unknown> = {
+ type: ApprovalPolicyType.PamAccess,
+ projectId
+ };
- await approvalRequestApprovalsDAL.create(
- {
- stepId: lockedStep.id,
- approverUserId: ctx.actorId,
- decision: ApprovalRequestApprovalDecision.Approved,
- comment
- },
- tx
- );
+ 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 newApprovalCount = stepApprovals.length + 1;
- if (newApprovalCount >= lockedStep.requiredApprovals) {
- await approvalRequestStepsDAL.updateById(
- lockedStep.id,
- { status: ApprovalRequestStepStatus.Completed, completedAt: new Date() },
- tx
- );
+ const requests = await approvalRequestDAL.find(filter, {
+ sort: [["createdAt", "desc"]],
+ offset,
+ limit,
+ count: true
+ });
+ const totalCount = Number(requests[0]?.count ?? 0);
- 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);
+ return {
+ requests: await attachGrantExpiry(await enrichRequestsWithNames(requests)),
+ totalCount
+ };
+ };
- 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
- );
- }
- }
- }
+ // 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 updated = await approvalRequestDAL.findById(requestId, tx);
- return { updatedRequest: updated, nextStepToNotify: nextStep };
- });
+ const listPendingMyApproval = async ({ projectId, folderId, ...ctx }: TListPendingMyApprovalDTO) => {
+ await verifyProductMembership(permissionService, projectId, ctx);
- if (nextStepToNotify) {
- await notifyApproversForStep(
- {
- name: nextStepToNotify.name ?? null,
- requiredApprovals: nextStepToNotify.requiredApprovals,
- notifyApprovers: true,
- approvers: nextStepToNotify.approvers
- },
- updatedRequest,
- { userGroupMembershipDAL, notificationService }
- );
- }
+ const userGroupIds = await getUserGroupIds(ctx.actorId, ctx.actorOrgId);
- 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
- );
+ // 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: [] };
- if (folderId) {
- void notifyFolderChannelsOfDecision({
- folderId,
- decision: ApprovalRequestApprovalDecision.Approved,
- requesterName: request.requesterName,
- requesterEmail: request.requesterEmail,
- accountName: approvedAccount?.name,
- comment,
- orgId: request.organizationId,
- requestId: request.id
- });
- }
- }
+ const requests = await approvalRequestDAL.findByProjectId(ApprovalPolicyType.PamAccess, projectId);
- return { request: updatedRequest, accountId: requestData?.requestData?.accountId, folderId };
- };
+ // 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;
- const notifyOfBreakGlass = async ({
- request,
- steps,
- account,
- folderId,
- duration,
- bypassReason,
- actorId,
- orgId
- }: {
- request: { id: string; requesterName?: string | null; requesterEmail?: string | null };
- steps: { approvers: { type: string; id: string }[] }[];
- account: { name: string; folderName: string | null };
- folderId: string;
- duration: string;
- bypassReason: string;
- actorId: string;
- orgId: string;
- }) => {
- try {
- const approverUserIds = new Set<string>();
- const approverGroupIds = new Set<string>();
- for (const step of steps) {
- for (const approver of step.approvers) {
- if (approver.type === ApproverType.User) approverUserIds.add(approver.id);
- else approverGroupIds.add(approver.id);
- }
+ if (folderId) {
+ const data = request.requestData as { version: number; requestData: TPamAccessRequestData } | null;
+ if (data?.requestData?.folderId !== folderId) return false;
}
- 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] } });
+ const currentStep = request.steps.find((s) => s.stepNumber === request.currentStep);
+ if (!currentStep) return false;
- 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)}"`
- }))
- );
+ return isUserEligibleApprover(currentStep.approvers, ctx.actorId, userGroupIds);
+ });
- 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
- }
- });
- }
+ // ...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);
}
- } 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 result = candidates.filter((r) => {
+ const fId = (r.requestData as { requestData?: TPamAccessRequestData } | null)?.requestData?.folderId;
+ return Boolean(fId && liveApproverFolders.has(fId));
});
+
+ return { requests: await attachGrantExpiry(await enrichRequestsWithNames(result)) };
};
- const breakGlassRequest = async ({ requestId, projectId, bypassReason, ...ctx }: TBreakGlassAccessRequestDTO) => {
+ const getCount = async ({ projectId, ...ctx }: TGetAccessRequestCountDTO) => {
await verifyProductMembership(permissionService, projectId, ctx);
- const trimmedReason = bypassReason.trim();
- if (trimmedReason.length < 10) {
- throw new BadRequestError({
- message: "A break-glass reason of at least 10 characters is required. It is recorded in the audit log."
- });
+ const userGroupIds = await getUserGroupIds(ctx.actorId, ctx.actorOrgId);
+
+ const isApprover = await approvalPolicyDAL.isProjectApprover({
+ 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 };
}
- if (ctx.actor !== ActorType.USER) {
- throw new ForbiddenRequestError({ message: "Only users can break glass on an access request" });
+ 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.requesterId !== ctx.actorId) {
- 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" });
}
@@ -1543,146 +1461,255 @@ export const pamAccessRequestServiceFactory = ({
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;
- const accountId = requestData?.requestData?.accountId;
- if (!folderId || !accountId) {
- throw new BadRequestError({ message: "This request is missing the account it was raised for" });
+
+ // 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 account = await pamAccountDAL.findByIdWithDetails(accountId);
- 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 { 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.`
- });
+ const hasAlreadyReviewed = currentStep.approvals.some(
+ (a: { approverUserId: string }) => a.approverUserId === ctx.actorId
+ );
+ if (hasAlreadyReviewed) {
+ throw new BadRequestError({ message: "You have already reviewed this request" });
}
- const policy = await findFolderPolicy(folderId);
- if (!policy) {
- throw new ForbiddenRequestError({ message: "Approval policy no longer exists for this folder" });
- }
+ 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" });
+ }
- const userGroupIds = await getUserGroupIds(ctx.actorId, ctx.actorOrgId);
- if (!(await isFolderBreakGlassApprover(policy.id, ctx.actorId, userGroupIds))) {
- throw new ForbiddenRequestError({
- message: "You are not a break-glass approver for this folder"
+ 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 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 rejectedAccountId = requestData?.requestData?.accountId;
+ const rejectedAccount = rejectedAccountId
+ ? await pamAccountDAL.findOne({ id: rejectedAccountId, projectId })
+ : undefined;
+ await notifyRequesterOfDecision(
+ updatedRequest,
+ ApprovalRequestApprovalDecision.Rejected,
+ rejectedAccount?.name,
+ comment
+ );
- // Break-glass skips the approver, not the permission the request itself needed.
- const accessType = requestData.requestData.accessType ?? PamAccessType.Session;
- await checkAccountAccess(
- permissionService,
- account.id,
- account.folderId,
- projectId,
- accessType === PamAccessType.Credential
- ? ResourcePermissionPamResourceActions.ViewCredentials
- : ResourcePermissionPamResourceActions.LaunchSessions,
- ctx
- );
+ if (folderId) {
+ void notifyFolderChannelsOfDecision({
+ folderId,
+ decision: ApprovalRequestApprovalDecision.Rejected,
+ requesterName: request.requesterName,
+ requesterEmail: request.requesterEmail,
+ accountName: rejectedAccount?.name,
+ comment,
+ orgId: request.organizationId,
+ requestId: request.id
+ });
+ }
- 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);
+ return { request: updatedRequest, accountId: requestData?.requestData?.accountId, folderId };
+ }
- const { updatedRequest, grant } = await approvalRequestDAL.transaction(async (tx) => {
+ 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" });
}
- if (locked.expiresAt && new Date(locked.expiresAt) < new Date()) {
- await approvalRequestDAL.updateById(requestId, { status: ApprovalRequestStatus.Expired }, tx);
- throw new BadRequestError({ message: "Request has expired" });
+ 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" });
}
- await Promise.all(
- steps.map((step) =>
- approvalRequestStepsDAL.updateById(
- step.id,
- { status: ApprovalRequestStepStatus.Completed, completedAt: new Date() },
- tx
- )
- )
+ 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 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}`
- },
+ 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
+ );
+ }
+ }
}
- await approvalRequestDAL.updateById(requestId, { status: ApprovalRequestStatus.Approved }, tx);
+ const updated = await approvalRequestDAL.findById(requestId, tx);
+ return { updatedRequest: updated, nextStepToNotify: nextStep };
+ });
- const createdGrant = await approvalRequestGrantsDAL.create(
+ if (nextStepToNotify) {
+ await notifyApproversForStep(
{
- 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
+ name: nextStepToNotify.name ?? null,
+ requiredApprovals: nextStepToNotify.requiredApprovals,
+ notifyApprovers: true,
+ approvers: nextStepToNotify.approvers
},
- tx
+ updatedRequest,
+ { userGroupMembershipDAL, notificationService }
);
+ }
- return { updatedRequest: await approvalRequestDAL.findById(requestId, tx), grant: createdGrant };
- });
+ 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
+ );
- void notifyOfBreakGlass({
- request,
- steps,
- account,
- folderId,
- duration: requestData.requestData.duration,
- bypassReason: trimmedReason,
- actorId: ctx.actorId,
- orgId: ctx.actorOrgId
- }).catch((err) => {
- logger.error(err, `Failed to send PAM break-glass notifications [requestId=${requestId}]`);
- });
+ 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,
- folderId,
- accountType: account.accountType,
- grantId: grant.id,
- policyId: policy.id,
- policyName: policy.name,
- accountName: account.name,
- folderName: account.folderName,
- granteeName: request.requesterName,
- granteeEmail: request.requesterEmail,
- accessDuration: requestData.requestData.duration,
- approverCount: bypassedApproverCount
- };
+ return { request: updatedRequest, accountId: requestData?.requestData?.accountId, folderId };
};
// Marks a grant Revoked and terminates the grantee's live sessions on the granted account.
diff --git a/backend/src/ee/services/pam-access-request/pam-access-request-types.ts b/backend/src/ee/services/pam-access-request/pam-access-request-types.ts
index 80c52de24b..5ae14196d0 100644
--- a/backend/src/ee/services/pam-access-request/pam-access-request-types.ts
+++ b/backend/src/ee/services/pam-access-request/pam-access-request-types.ts
@@ -33,6 +33,7 @@ export type TBreakGlassAccessRequestDTO = {
} & TActorContext;
export type TCreateAccessRequestDTO = {
+ breakGlass?: boolean;
accountId?: string;
path?: string;
projectId: string;
diff --git a/docs/documentation/platform/pam/access-requests/overview.mdx b/docs/documentation/platform/pam/access-requests/overview.mdx
index cec6f92ca3..09699adfd3 100644
--- a/docs/documentation/platform/pam/access-requests/overview.mdx
+++ b/docs/documentation/platform/pam/access-requests/overview.mdx
@@ -148,11 +148,13 @@ graph TD
### Breaking glass
-A break-glass approver files a request the usual way, with a reason and a duration. While it's pending, the request sheet offers **Break glass** below the approval workflow.
+There are two ways in, and both need a reason of at least 10 characters explaining why this can't wait for an approver. The reason is recorded in the audit log and sent to the approvers who were skipped.
-Breaking glass takes a second reason, at least 10 characters, for why this can't wait for an approver. Select **Break glass** and the grant opens straight away, for the duration the request asked for.
+If you already know nobody is available to approve, turn on **Break glass** in the request form before you submit. The request is raised and granted in one step, and the reason you gave doubles as the bypass reason.
-Nothing else about the grant changes. It expires on the same clock, a Folder Admin can revoke it the same way, and sessions on it are recorded like any other.
+If you filed a request and then decided not to wait, reopen the account from the **Accounts** page while the request is pending. The sheet offers **Break glass** below the approval workflow.
+
+Either way, the grant is the one the request asked for. It expires on the same clock, a Folder Admin can revoke it the same way, and sessions on it are recorded like any other. Breaking glass on a credential request grants a credential reveal, not a session.
### What happens next
diff --git a/frontend/src/hooks/api/pam/types/index.ts b/frontend/src/hooks/api/pam/types/index.ts
index 00ff180188..b3ebde9e4e 100644
--- a/frontend/src/hooks/api/pam/types/index.ts
+++ b/frontend/src/hooks/api/pam/types/index.ts
@@ -757,6 +757,7 @@ export type TPamAccessGrant = {
};
export type TCreatePamAccessRequestDTO = {
+ breakGlass?: boolean;
accountId: string;
reason?: string;
duration: string;
diff --git a/frontend/src/pages/pam/components/RequestAccessSheet.tsx b/frontend/src/pages/pam/components/RequestAccessSheet.tsx
index a2bcd0bfbf..15a15ac4a5 100644
--- a/frontend/src/pages/pam/components/RequestAccessSheet.tsx
+++ b/frontend/src/pages/pam/components/RequestAccessSheet.tsx
@@ -12,6 +12,7 @@ import {
User as UserIcon,
Users as UsersIcon
} from "lucide-react";
+import { twMerge } from "tailwind-merge";
import { z } from "zod";
import { createNotification } from "@app/components/notifications";
@@ -31,11 +32,13 @@ import {
FieldDescription,
FieldError,
FieldLabel,
+ FieldTitle,
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
+ Switch,
TextArea
} from "@app/components/v3";
import {
@@ -66,13 +69,19 @@ const DURATION_OPTIONS = [
];
// Reason requiredness follows the template's Require Reason policy, same as the API and CLI
-const makeSchema = (requireReason: boolean) =>
- z.object({
+const makeSchema = (requireReason: boolean, breakGlass: boolean) => {
+ const { minLength, message } = (() => {
+ if (breakGlass)
+ return { minLength: 10, message: "At least 10 characters for a break-glass request" };
+ if (requireReason) return { minLength: 1, message: "Required" };
+ return { minLength: 0, message: "Required" };
+ })();
+
+ return z.object({
duration: z.string().min(1, "Required"),
- reason: requireReason
- ? z.string().trim().min(1, "Required").max(500)
- : z.string().trim().max(500)
+ reason: z.string().trim().min(minLength, message).max(500)
});
+};
type FormData = z.infer<ReturnType<typeof makeSchema>>;
@@ -180,7 +189,13 @@ export const RequestAccessSheet = ({
: account?.pendingRequestId;
const canBreakGlass = Boolean(account?.canBreakGlass && pendingRequestId);
const requireReason = Boolean(account?.requireReason);
- const schema = useMemo(() => makeSchema(requireReason), [requireReason]);
+ const [breakGlassOnSubmit, setBreakGlassOnSubmit] = useState(false);
+ const requestLabel = isCredentialRequest ? "Request credentials" : "Request session access";
+ const submitLabel = breakGlassOnSubmit ? "Break glass" : requestLabel;
+ const schema = useMemo(
+ () => makeSchema(requireReason, breakGlassOnSubmit),
+ [requireReason, breakGlassOnSubmit]
+ );
const {
control,
@@ -196,6 +211,7 @@ export const RequestAccessSheet = ({
if (!open) {
reset();
setBypassReason("");
+ setBreakGlassOnSubmit(false);
}
onOpenChange(open);
};
@@ -224,14 +240,18 @@ export const RequestAccessSheet = ({
accountId: account.id,
duration: data.duration,
reason: data.reason || undefined,
- accessType
+ accessType,
+ breakGlass: breakGlassOnSubmit || undefined
},
{
onSuccess: () => {
+ const submittedText = isCredentialRequest
+ ? "Credential access request submitted"
+ : "Access request submitted";
createNotification({
- text: isCredentialRequest
- ? "Credential access request submitted"
- : "Access request submitted",
+ text: breakGlassOnSubmit
+ ? "Access granted. The approvers you skipped have been notified."
+ : submittedText,
type: "success"
});
reset();
@@ -336,7 +356,10 @@ export const RequestAccessSheet = ({
render={({ field, fieldState }) => (
<Field>
<FieldLabel>
- Reason {requireReason && <span className="text-danger">*</span>}
+ Reason{" "}
+ {(requireReason || breakGlassOnSubmit) && (
+ <span className="text-danger">*</span>
+ )}
</FieldLabel>
<FieldContent>
<TextArea
@@ -350,7 +373,9 @@ export const RequestAccessSheet = ({
isError={!!fieldState.error}
/>
<FieldDescription>
- Will be visible to approvers and recorded in audit logs.
+ {breakGlassOnSubmit
+ ? "Sent to the approvers you skip and recorded in audit logs."
+ : "Will be visible to approvers and recorded in audit logs."}
</FieldDescription>
<FieldError>{fieldState.error?.message}</FieldError>
</FieldContent>
@@ -388,14 +413,40 @@ export const RequestAccessSheet = ({
)}
/>
<ApprovalWorkflow accountId={account?.id} isPending={false} accessType={accessType} />
+ {account?.canBreakGlass && (
+ <Card
+ className={twMerge("p-4", breakGlassOnSubmit && "border-danger/40 bg-danger/5")}
+ >
+ <Field orientation="horizontal" className="items-center!">
+ <FieldContent>
+ <FieldTitle className="flex items-center gap-2">
+ <ShieldAlert className="size-4 shrink-0 text-danger" />
+ Break glass
+ </FieldTitle>
+ <FieldDescription>
+ Grant now, skipping the approvers. Every use is audited.
+ </FieldDescription>
+ </FieldContent>
+ <Switch
+ checked={breakGlassOnSubmit}
+ variant="danger"
+ onCheckedChange={setBreakGlassOnSubmit}
+ />
+ </Field>
+ </Card>
+ )}
</div>
<div className="flex items-center justify-end gap-2 border-t border-border pt-4">
<Button type="button" variant="ghost" onClick={() => handleOpenChange(false)}>
Cancel
</Button>
- <Button type="submit" variant="pam" isPending={createRequest.isPending}>
- <Send className="mr-1.5 size-4" />
- {isCredentialRequest ? "Request credentials" : "Request session access"}
+ <Button
+ type="submit"
+ variant={breakGlassOnSubmit ? "danger" : "pam"}
+ isPending={createRequest.isPending}
+ >
+ {!breakGlassOnSubmit && <Send className="mr-1.5 size-4" />}
+ {submitLabel}
</Button>
</div>
</form>