Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat: add breakglass behavior
adilson6f3398fbc3bc
diff --git a/backend/e2e-test/routes/v1/access-approval-global-request-lifecycle.spec.ts b/backend/e2e-test/routes/v1/access-approval-global-request-lifecycle.spec.tsindex 119f9b68a3..331c6afbe6 100644--- a/backend/e2e-test/routes/v1/access-approval-global-request-lifecycle.spec.ts+++ b/backend/e2e-test/routes/v1/access-approval-global-request-lifecycle.spec.ts@@ -278,8 +278,8 @@ describe("Access approval request lifecycle on the global system", () => {expect(patchRes.json().message).toBe("Access requests on the global approval system cannot be edited");const bypassRes = await reviewAccessRequest(requestId, { status: "approved", bypassReason: "need it right now" });- expect(bypassRes.statusCode).toBe(400);- expect(bypassRes.json().message).toBe("Break-glass approvals are not supported for this request yet");+ expect(bypassRes.statusCode).toBe(403);+ expect(bypassRes.json().message).toBe("You are not permitted to bypass approval on this request");});test("A policy's max time period caps the requested range and survives an update that omits it", async () => {@@ -697,3 +697,181 @@ describe("Per-step required approvals on the global system", () => {expect(state.privilege).toBeDefined();});});++describe("Break-glass approvals on the global system", () => {+ const approvers: TApprover[] = [];+ let approver: TApprover;++ const bypassReason = "incident INC-1234 needs the production key now";++ const createSoftPolicy = async (body: { secretPath: string; bypassers?: { type: "user"; id: string }[] }) => {+ const res = await testServer.inject({+ method: "POST",+ url: "/api/v1/access-approvals/policies",+ headers: authHeaders(),+ body: {+ projectSlug: seedData1.project.slug,+ environment: seedData1.environment.slug,+ name: `break-glass-${body.secretPath.slice(1)}`,+ secretPath: body.secretPath,+ approvers: [{ type: ApproverType.User, id: approver.userId }],+ approvals: 1,+ allowedSelfApprovals: false,+ enforcementLevel: "soft",+ ...(body.bypassers && { bypassers: body.bypassers })+ }+ });+ expect(res.statusCode).toBe(200);+ const { approval } = res.json();+ globalPolicyIds.push(approval.id);+ return approval as { id: string };+ };++ beforeAll(async () => {+ initLogger();+ await initEnvConfig(testHsmService, testKmsRootConfigDAL, testSuperAdminDAL, logger);+ approver = await createApproverUser();+ approvers.push(approver);+ });++ afterEach(async () => {+ const db = getDb();+ const globalIds = globalPolicyIds.splice(0);++ await db(TableName.AdditionalPrivilege)+ .where({ actorUserId: seedData1.id })+ .whereLike("name", "requested-privilege-%")+ .del();+ await db(TableName.ApprovalRequestGrants)+ .where({ projectId: seedData1.project.id, type: SECRET_ACCESS_TYPE })+ .del();+ if (globalIds.length) {+ await db(TableName.ApprovalRequests).whereIn("policyId", globalIds).del();+ await db(TableName.ApprovalPolicies).whereIn("id", globalIds).del();+ }+ });++ afterAll(async () => {+ const db = getDb();+ const userIds = approvers.map((el) => el.userId);+ await db(TableName.AuthTokenSession).whereIn("userId", userIds).del();+ await db(TableName.Membership).whereIn("actorUserId", userIds).del();+ await db(TableName.Users).whereIn("id", userIds).del();+ });++ test("A listed bypasser approves their own request without the approver and gets a break-glass grant", async () => {+ const db = getDb();+ const secretPath = "/break-glass-listed";+ const policy = await createSoftPolicy({ secretPath, bypassers: [{ type: "user", id: seedData1.id }] });++ const createRes = await createAccessRequest(secretPath, { isTemporary: true, temporaryRange: "1h" });+ expect(createRes.statusCode).toBe(200);+ const requestId = createRes.json().approval.id as string;++ const selfApproveRes = await reviewAccessRequest(requestId, { status: "approved" });+ expect(selfApproveRes.statusCode).toBe(400);++ const bypassRes = await reviewAccessRequest(requestId, { status: "approved", bypassReason });+ expect(bypassRes.statusCode).toBe(200);+ expect(bypassRes.json().review.status).toBe("approved");+ expect(bypassRes.json().review.reviewerUserId).toBe(seedData1.id);++ const state = await getRequestState(requestId);+ expect(state.status).toBe("approved");+ expect(state.grant?.status).toBe("active");+ expect(state.grant?.isBreakGlass).toBe(true);+ expect(state.grant?.bypassReason).toBe(bypassReason);+ expect(state.grant?.granteeUserId).toBe(seedData1.id);+ expect(state.privilege?.actorUserId).toBe(seedData1.id);+ expect(state.privilege?.temporaryRange).toBe("1h");++ const steps = await db(TableName.ApprovalRequestSteps).where({ requestId });+ expect(steps.length).toBeGreaterThan(0);+ expect(steps.every((step) => step.status === "completed")).toBe(true);++ const listed = (await listAccessRequests()).json().requests.find((el: { id: string }) => el.id === requestId);+ expect(listed.policyId).toBe(policy.id);+ expect(listed.status).toBe("approved");+ expect(listed.bypassReason).toBe(bypassReason);+ expect(listed.policy.bypassers).toEqual([seedData1.id]);+ });++ test("A soft policy with no bypassers lets the requester break glass", async () => {+ const secretPath = "/break-glass-anyone";+ await createSoftPolicy({ secretPath });++ const createRes = await createAccessRequest(secretPath);+ expect(createRes.statusCode).toBe(200);+ const requestId = createRes.json().approval.id as string;++ const bypassRes = await reviewAccessRequest(requestId, { status: "approved", bypassReason });+ expect(bypassRes.statusCode).toBe(200);++ const state = await getRequestState(requestId);+ expect(state.status).toBe("approved");+ expect(state.grant?.isBreakGlass).toBe(true);+ expect(state.grant?.expiresAt).toBeNull();+ expect(state.privilege?.isTemporary).toBe(false);+ });++ test("A requester who is not on a non-empty bypasser list is refused", async () => {+ const secretPath = "/break-glass-not-listed";+ await createSoftPolicy({ secretPath, bypassers: [{ type: "user", id: approver.userId }] });++ const createRes = await createAccessRequest(secretPath);+ expect(createRes.statusCode).toBe(200);+ const requestId = createRes.json().approval.id as string;++ const bypassRes = await reviewAccessRequest(requestId, { status: "approved", bypassReason });+ expect(bypassRes.statusCode).toBe(403);+ expect(bypassRes.json().message).toBe("You are not permitted to bypass approval on this request");++ const state = await getRequestState(requestId);+ expect(state.status).toBe("pending");+ expect(state.grant).toBeUndefined();+ });++ test("Only the requester can break glass, even when the actor is an approver and a bypasser", async () => {+ const secretPath = "/break-glass-not-requester";+ await createSoftPolicy({ secretPath, bypassers: [{ type: "user", id: approver.userId }] });++ const createRes = await createAccessRequest(secretPath);+ expect(createRes.statusCode).toBe(200);+ const requestId = createRes.json().approval.id as string;++ const bypassRes = await testServer.inject({+ method: "POST",+ url: `/api/v1/access-approvals/requests/${requestId}/review`,+ headers: { authorization: `Bearer ${approver.token}` },+ body: { status: "approved", bypassReason }+ });+ expect(bypassRes.statusCode).toBe(403);+ expect(bypassRes.json().message).toBe("You are not permitted to bypass approval on this request");++ const normalRes = await reviewAs(approver, requestId);+ expect(normalRes.statusCode).toBe(200);+ const state = await getRequestState(requestId);+ expect(state.status).toBe("approved");+ expect(state.grant?.isBreakGlass).toBe(false);+ expect(state.grant?.bypassReason).toBeNull();+ });++ test("A bypass reason is rejected on a rejection and when it is too short", async () => {+ const secretPath = "/break-glass-bad-input";+ await createSoftPolicy({ secretPath });++ const createRes = await createAccessRequest(secretPath);+ expect(createRes.statusCode).toBe(200);+ const requestId = createRes.json().approval.id as string;++ const rejectRes = await reviewAccessRequest(requestId, { status: "rejected", bypassReason });+ expect(rejectRes.statusCode).toBe(400);+ expect(rejectRes.json().message).toBe("A bypass reason can only be provided when approving a request");++ const shortRes = await reviewAccessRequest(requestId, { status: "approved", bypassReason: "too short" });+ expect(shortRes.statusCode).toBe(422);++ const state = await getRequestState(requestId);+ expect(state.status).toBe("pending");+ });+});diff --git a/backend/src/ee/services/access-approval-policy/access-approval-policy-service.ts b/backend/src/ee/services/access-approval-policy/access-approval-policy-service.tsindex 74ed611359..6cc0abd072 100644--- a/backend/src/ee/services/access-approval-policy/access-approval-policy-service.ts+++ b/backend/src/ee/services/access-approval-policy/access-approval-policy-service.ts@@ -107,7 +107,7 @@ export const accessApprovalPolicyServiceFactory = ({}) => {const resolvedEnvIds = envId ? [envId] : envIds;if (!resolvedEnvIds?.length) {- throw new BadRequestError({ message: "Must provide either envId or envIds" }); // this message is not good for error+ throw new BadRequestError({ message: "Must provide either envId or envIds" });}for (const id of resolvedEnvIds) {diff --git a/backend/src/services/approval-policy/approval-policy-service.ts b/backend/src/services/approval-policy/approval-policy-service.tsindex cc336b4562..69e0e5ca68 100644--- a/backend/src/services/approval-policy/approval-policy-service.ts+++ b/backend/src/services/approval-policy/approval-policy-service.ts@@ -1832,6 +1832,13 @@ export const approvalPolicyServiceFactory = ({const request = grant.requestId ? await approvalRequestDAL.findById(grant.requestId) : null;const assertDomainCanRevoke = resources[grantPolicyType]?.assertCanRevokeGrant;+ // Secret access grants are managed on secret-access-approval-bridge service+ if (grantPolicyType === ApprovalPolicyType.SecretAccess) {+ throw new BadRequestError({+ message: "This grant is for a secret access request. Revoke it from the access request instead."+ });+ }+if (assertDomainCanRevoke) {await assertDomainCanRevoke({ grant, request, actor });} else {@@ -1875,12 +1882,6 @@ export const approvalPolicyServiceFactory = ({}}- if (grantPolicyType === ApprovalPolicyType.SecretAccess) {- throw new BadRequestError({- message: "This grant is for a secret access request. Revoke it from the access request instead."- });- }-if (grant.status !== ApprovalRequestGrantStatus.Active) {throw new BadRequestError({ message: "Grant is not active" });}diff --git a/backend/src/services/approval-policy/secret-access/secret-access-policy-factory.ts b/backend/src/services/approval-policy/secret-access/secret-access-policy-factory.tsindex 342730054d..f98731b9c7 100644--- a/backend/src/services/approval-policy/secret-access/secret-access-policy-factory.ts+++ b/backend/src/services/approval-policy/secret-access/secret-access-policy-factory.ts@@ -1,14 +1,16 @@+import { TApprovalPolicies } from "@app/db/schemas";import { NotFoundError } from "@app/lib/errors";import { TAdditionalPrivilegeDALFactory } from "@app/services/additional-privilege/additional-privilege-dal";import { TApprovalPolicyDALFactory } from "../approval-policy-dal";import { ApprovalPolicyType, ApprovalRequestGrantStatus } from "../approval-policy-enums";-import { TApprovalResource } from "../approval-policy-types";+import { TApprovalActor, TApprovalResource } from "../approval-policy-types";import { TApprovalRequestGrantsDALFactory } from "../approval-request-dal";import {createSecretAccessGrantWithPrivilege,getSecretAccessRequestData,hasSameAccessCriteria,+ isSecretAccessBreakGlassEligible,validateSecretAccessConstraints} from "./secret-access-policy-fns";import { SecretAccessPolicyRequestDataSchema } from "./secret-access-policy-schemas";@@ -61,7 +63,7 @@ export const secretAccessApprovalResourceFactory = ({validateConstraints: (policy, requestData) =>validateSecretAccessConstraints(policy.constraints.constraints, requestData),- postApprovalTxRoutine: async (request, tx) => {+ postApprovalTxRoutine: async (request, tx, breakGlass?: { bypassReason: string }) => {const { requesterId } = request;if (!requesterId) {throw new NotFoundError({ message: "The user who created this access request no longer exists" });@@ -72,12 +74,31 @@ export const secretAccessApprovalResourceFactory = ({projectId: request.projectId,requestId: request.id,granteeUserId: requesterId,- data: getSecretAccessRequestData(request)+ data: getSecretAccessRequestData(request),+ breakGlass},{ approvalRequestGrantsDAL, additionalPrivilegeDAL },tx);return { grantId: grant.id };- }+ },++ isBreakGlassEligible: async ({+ policy,+ bypassers,+ actor,+ userGroupIds+ }: {+ policy: Pick<TApprovalPolicies, "enforcementLevel">;+ bypassers: { type: string; id?: string | null }[];+ actor: Pick<TApprovalActor, "id">;+ userGroupIds: Set<string>;+ }) =>+ isSecretAccessBreakGlassEligible({+ enforcementLevel: policy.enforcementLevel,+ bypassers,+ actorUserId: actor.id,+ actorGroupIds: userGroupIds+ })}) satisfies TApprovalResource<TSecretAccessPolicyInputs, TSecretAccessPolicy, TSecretAccessRequestData>;diff --git a/backend/src/services/approval-policy/secret-access/secret-access-policy-fns.test.ts b/backend/src/services/approval-policy/secret-access/secret-access-policy-fns.test.tsindex 493af778c6..2d463ac1b5 100644--- a/backend/src/services/approval-policy/secret-access/secret-access-policy-fns.test.ts+++ b/backend/src/services/approval-policy/secret-access/secret-access-policy-fns.test.ts@@ -1,6 +1,7 @@import {getSecretAccessGrantWindow,hasSameAccessCriteria,+ isSecretAccessBreakGlassEligible,validateSecretAccessConstraints} from "./secret-access-policy-fns";import { TSecretAccessRequestData } from "./secret-access-policy-types";@@ -97,3 +98,57 @@ describe("hasSameAccessCriteria", () => {expect(hasSameAccessCriteria(null, { permissions: storedRequest.permissions, isTemporary: false })).toBe(false);});});++describe("isSecretAccessBreakGlassEligible", () => {+ const actorUserId = "a3c1f0e2-5b7d-4e8f-9a0b-1c2d3e4f5a6b";+ const groupId = "0f9e8d7c-6b5a-4e3d-8c2b-1a0f9e8d7c6b";+ const actorGroupIds = new Set([groupId]);++ test("a hard policy can never be bypassed", () => {+ expect(+ isSecretAccessBreakGlassEligible({ enforcementLevel: "hard", bypassers: [], actorUserId, actorGroupIds })+ ).toBe(false);+ });++ test("a soft policy with no bypassers lets anyone bypass", () => {+ expect(+ isSecretAccessBreakGlassEligible({ enforcementLevel: "soft", bypassers: [], actorUserId, actorGroupIds })+ ).toBe(true);+ });++ test("a soft policy lets a listed user bypass", () => {+ expect(+ isSecretAccessBreakGlassEligible({+ enforcementLevel: "soft",+ bypassers: [{ type: "user", id: actorUserId }],+ actorUserId,+ actorGroupIds+ })+ ).toBe(true);+ });++ test("a soft policy lets a member of a listed group bypass", () => {+ expect(+ isSecretAccessBreakGlassEligible({+ enforcementLevel: "soft",+ bypassers: [{ type: "group", id: groupId }],+ actorUserId,+ actorGroupIds+ })+ ).toBe(true);+ });++ test("a soft policy refuses a user who is on neither list", () => {+ expect(+ isSecretAccessBreakGlassEligible({+ enforcementLevel: "soft",+ bypassers: [+ { type: "user", id: "ffffffff-0000-4000-8000-000000000000" },+ { type: "group", id: "eeeeeeee-0000-4000-8000-000000000000" }+ ],+ actorUserId,+ actorGroupIds+ })+ ).toBe(false);+ });+});diff --git a/backend/src/services/approval-policy/secret-access/secret-access-policy-fns.ts b/backend/src/services/approval-policy/secret-access/secret-access-policy-fns.tsindex 02e0a355d8..869c2205f3 100644--- a/backend/src/services/approval-policy/secret-access/secret-access-policy-fns.ts+++ b/backend/src/services/approval-policy/secret-access/secret-access-policy-fns.ts@@ -8,7 +8,12 @@ import { ms } from "@app/lib/ms";import { alphaNumericNanoId } from "@app/lib/nanoid";import { TAdditionalPrivilegeDALFactory } from "@app/services/additional-privilege/additional-privilege-dal";-import { ApprovalPolicyType, ApprovalRequestGrantStatus } from "../approval-policy-enums";+import {+ ApprovalPolicyType,+ ApprovalRequestGrantStatus,+ ApproverType,+ EnforcementLevel+} from "../approval-policy-enums";import { TApprovalRequestGrantsDALFactory } from "../approval-request-dal";import { SecretAccessPolicyRequestDataSchema } from "./secret-access-policy-schemas";import { TSecretAccessPolicyConstraints, TSecretAccessRequestData } from "./secret-access-policy-types";@@ -69,6 +74,26 @@ export const validateSecretAccessConstraints = (};};+export const isSecretAccessBreakGlassEligible = ({+ enforcementLevel,+ bypassers,+ actorUserId,+ actorGroupIds+}: {+ enforcementLevel: string;+ bypassers: { type: string; id?: string | null }[];+ actorUserId: string;+ actorGroupIds: Set<string>;+}) => {+ if (enforcementLevel !== EnforcementLevel.Soft) return false;+ if (bypassers.length === 0) return true;++ return bypassers.some((bypasser) => {+ if (!bypasser.id) return false;+ return bypasser.type === ApproverType.Group ? actorGroupIds.has(bypasser.id) : bypasser.id === actorUserId;+ });+};+export const getSecretAccessGrantWindow = ({ isTemporary, temporaryRange }: Pick<TSecretAccessRequestData, "isTemporary" | "temporaryRange">,now: Date = new Date()@@ -95,12 +120,14 @@ export const createSecretAccessGrantWithPrivilege = async (projectId,requestId,granteeUserId,- data+ data,+ breakGlass}: {projectId: string;requestId: string;granteeUserId: string;data: TSecretAccessRequestData;+ breakGlass?: { bypassReason: string };},{ approvalRequestGrantsDAL, additionalPrivilegeDAL }: TCreateSecretAccessGrantWithPrivilegeDep,tx: Knex@@ -115,7 +142,9 @@ export const createSecretAccessGrantWithPrivilege = async (status: ApprovalRequestGrantStatus.Active,type: ApprovalPolicyType.SecretAccess,attributes: data,- expiresAt: grantWindow?.endTime ?? null+ expiresAt: grantWindow?.endTime ?? null,+ isBreakGlass: Boolean(breakGlass),+ bypassReason: breakGlass?.bypassReason ?? null},tx);diff --git a/backend/src/services/secret-access-approval-bridge/secret-access-approval-bridge-fns.ts b/backend/src/services/secret-access-approval-bridge/secret-access-approval-bridge-fns.tsindex 7d4bf029c9..06747e88ea 100644--- a/backend/src/services/secret-access-approval-bridge/secret-access-approval-bridge-fns.ts+++ b/backend/src/services/secret-access-approval-bridge/secret-access-approval-bridge-fns.ts@@ -106,7 +106,7 @@ export const toLegacyAccessApprovalRequest = (updatedAt: Date;editedByUserId: null;editNote: null;- bypassReason: null;+ bypassReason: string | null;privilegeDeletedAt: null;} => {if (!request.policyId) {@@ -143,7 +143,7 @@ export const toLegacyAccessApprovalRequest = (updatedAt: request.updatedAt,editedByUserId: null,editNote: null,- bypassReason: null,+ bypassReason: grant?.isBreakGlass ? (grant.bypassReason ?? null) : null,privilegeDeletedAt: null};};@@ -264,6 +264,80 @@ export const notifySecretAccessStepApprovers = async (}};+type TNotifySecretAccessBypassDep = Pick<+ TSecretAccessApprovalBridgeServiceFactoryDep,+ "userDAL" | "userGroupMembershipDAL" | "notificationService" | "smtpService"+>;++export const notifySecretAccessBypass = async (+ {+ request,+ project,+ policy,+ actingUser,+ environmentName,+ bypassReason+ }: {+ request: Pick<TSecretAccessRequestRow, "id" | "organizationId">;+ project: { id: string; name: string; orgId: string };+ policy: { secretPath: string; approvers: { type: ApproverType; id?: string | null }[] };+ actingUser: Pick<TUsers, "id" | "firstName" | "lastName" | "email">;+ environmentName: string;+ bypassReason: string;+ },+ { userDAL, userGroupMembershipDAL, notificationService, smtpService }: TNotifySecretAccessBypassDep+) => {+ try {+ const approverUserIds = await resolveStepApproverUserIds(+ {+ requiredApprovals: 1,+ approvers: policy.approvers.flatMap(({ type, id }) => (id ? [{ type, id }] : []))+ },+ userGroupMembershipDAL+ );+ if (!approverUserIds.size) return;++ const approverUsers = await userDAL.find({ $in: { id: [...approverUserIds] } });+ if (!approverUsers.length) return;++ const cfg = getConfig();+ const actingUserFullName = [actingUser.firstName, actingUser.lastName].filter(Boolean).join(" ");+ const approvalPath = `/organizations/${project.orgId}/projects/secret-management/${project.id}/approval?selectedTab=resource-requests&requestId=${encodeURIComponent(request.id)}`;++ await notificationService.createUserNotifications(+ approverUsers.map((approver) => ({+ userId: approver.id,+ orgId: request.organizationId,+ type: NotificationType.ACCESS_POLICY_BYPASSED,+ title: "Secret Access Policy Bypassed",+ body: `**${actingUserFullName}** (${actingUser.email}) has accessed a secret in **${policy.secretPath || "/"}** in the **${environmentName}** environment for project **${project.name}** without obtaining the required approval.`,+ link: approvalPath+ }))+ );++ const recipients = approverUsers.filter((approver) => approver.email).map((approver) => approver.email!);+ if (recipients.length) {+ await smtpService.sendMail({+ recipients,+ subjectLine: "Infisical Secret Access Policy Bypassed",+ substitutions: {+ projectName: project.name,+ requesterFullName: actingUserFullName,+ requesterEmail: actingUser.email,+ bypassReason,+ secretPath: policy.secretPath || "/",+ environment: environmentName,+ approvalUrl: `${cfg.SITE_URL}${approvalPath}`,+ requestType: "access"+ },+ template: SmtpTemplates.AccessSecretRequestBypassed+ });+ }+ } catch (error) {+ logger.error(error, `Failed to notify access request approvers of a bypass [requestId=${request.id}]`);+ }+};+type TSecretAccessPolicyRow = Awaited<ReturnType<TSecretAccessApprovalBridgeDALFactory["findSecretAccessPolicies"]>>[number];diff --git a/backend/src/services/secret-access-approval-bridge/secret-access-approval-bridge-service.ts b/backend/src/services/secret-access-approval-bridge/secret-access-approval-bridge-service.tsindex 3cb179d799..245d5067c2 100644--- a/backend/src/services/secret-access-approval-bridge/secret-access-approval-bridge-service.ts+++ b/backend/src/services/secret-access-approval-bridge/secret-access-approval-bridge-service.ts@@ -35,7 +35,8 @@ import { createApprovalRequestWithSteps } from "@app/services/approval-policy/apimport {getSecretAccessRequestData,hasSameAccessCriteria,- parseSecretAccessRequestData+ parseSecretAccessRequestData,+ validateSecretAccessConstraints} from "@app/services/approval-policy/secret-access/secret-access-policy-fns";import {TSecretAccessPolicy,@@ -50,6 +51,7 @@ import {collectSecretAccessRequestUserIds,composeSecretAccessRequestRows,isPolicySubjectMatch,+ notifySecretAccessBypass,notifySecretAccessStepApprovers,secretAccessApprovalPolicyExists,toLegacyAccessApprovalRequest@@ -929,10 +931,6 @@ export const secretAccessApprovalBridgeServiceFactory = ({actorOrgId,actorAuthMethod}: TReviewSecretAccessApprovalRequestDTO) => {- if (bypassReason !== undefined) {- throw new BadRequestError({ message: "Break-glass approvals are not supported for this request yet" });- }-const request = await $findRequestById(requestId);if (!request.policyId) {throw new BadRequestError({ message: "The policy associated with this access request has been deleted." });@@ -973,7 +971,11 @@ export const secretAccessApprovalBridgeServiceFactory = ({const isSelfReview = actorId === request.requesterId;const isApproving = status === ApprovalStatus.APPROVED;- if (isSelfReview && isApproving && !policy.allowedSelfApprovals) {+ const isBreakGlassAttempt = bypassReason !== undefined;+ if (isBreakGlassAttempt && !isApproving) {+ throw new BadRequestError({ message: "A bypass reason can only be provided when approving a request" });+ }+ if (isSelfReview && isApproving && !policy.allowedSelfApprovals && !isBreakGlassAttempt) {throw new BadRequestError({message: "Failed to review access approval request. Users are not authorized to review their own request."});@@ -986,6 +988,107 @@ export const secretAccessApprovalBridgeServiceFactory = ({throw new NotFoundError({ message: "The project associated with this access request was not found." });}+ if (isBreakGlassAttempt) {+ const trimmedBypassReason = bypassReason.trim();+ if (trimmedBypassReason.length < 10) {+ throw new BadRequestError({+ message: "A bypass reason of at least 10 characters is required to bypass approvals"+ });+ }++ const isEligible =+ actor === ActorType.USER &&+ isSelfReview &&+ (await secretAccessApprovalResource.isBreakGlassEligible({+ policy,+ bypassers: policy.bypassers,+ actor: { id: actorId },+ userGroupIds: actorGroupIds+ }));+ if (!isEligible) {+ throw new ForbiddenRequestError({ message: "You are not permitted to bypass approval on this request" });+ }++ const constraintValidation = validateSecretAccessConstraints({ maxTimePeriod: policy.maxTimePeriod }, data);+ if (!constraintValidation.valid) {+ throw new BadRequestError({+ message: `Policy constraints not met: ${constraintValidation.errors?.join("; ") ?? "unknown"}`+ });+ }++ const approval = await approvalRequestDAL.transaction(async (tx) => {+ const locked = await approvalRequestDAL.findByIdForUpdate(requestId, tx);+ if (!locked || locked.status !== ApprovalRequestStatus.Pending) {+ throw new BadRequestError({ message: "The request has been closed" });+ }+ if (locked.expiresAt && new Date(locked.expiresAt) < new Date()) {+ throw new BadRequestError({ message: "This access request has expired and can no longer be reviewed" });+ }++ const steps = await approvalRequestStepsDAL.find({ requestId }, { tx, sort: [["stepNumber", "asc"]] });+ const currentStep = steps.find((step) => step.stepNumber === locked.currentStep);+ if (!currentStep) throw new BadRequestError({ message: "Current step not found" });++ const completedAt = new Date();+ await Promise.all(+ steps.map((step) =>+ approvalRequestStepsDAL.updateById(+ step.id,+ { status: ApprovalRequestStepStatus.Completed, completedAt },+ tx+ )+ )+ );++ const stepApprovals = await approvalRequestApprovalsDAL.find({ stepId: currentStep.id }, { tx });+ const bypassApproval =+ stepApprovals.find((a) => a.approverUserId === actorId) ??+ (await approvalRequestApprovalsDAL.create(+ {+ stepId: currentStep.id,+ approverUserId: actorId,+ decision: ApprovalRequestApprovalDecision.Approved+ },+ tx+ ));++ const approved = await approvalRequestDAL.updateById(requestId, { status: ApprovalRequestStatus.Approved }, tx);+ await secretAccessApprovalResource.postApprovalTxRoutine(approved as TApprovalRequest, tx, {+ bypassReason: trimmedBypassReason+ });++ return bypassApproval;+ });++ const actingUser = await userDAL.findById(actorId);+ if (actingUser) {+ await notifySecretAccessBypass(+ {+ request,+ project,+ policy,+ actingUser,+ environmentName: policy.environment?.name ?? data.envSlug,+ bypassReason: trimmedBypassReason+ },+ { userDAL, userGroupMembershipDAL, notificationService, smtpService }+ );+ }++ const createdAt = approval.createdAt ?? new Date();+ return {+ id: approval.id,+ requestId,+ reviewerUserId: approval.approverUserId,+ status: approval.decision,+ createdAt,+ updatedAt: createdAt,+ projectId: request.projectId,+ policyId: policy.id,+ isBypass: true+ };+ }+const { approval, nextStep } = await approvalRequestDAL.transaction(async (tx) => {const locked = await approvalRequestDAL.findByIdForUpdate(requestId, tx);if (!locked || locked.status !== ApprovalRequestStatus.Pending) {diff --git a/backend/src/services/secret-access-approval-bridge/secret-access-approval-bridge-types.ts b/backend/src/services/secret-access-approval-bridge/secret-access-approval-bridge-types.tsindex 4535b2d2b8..5bd53825ea 100644--- a/backend/src/services/secret-access-approval-bridge/secret-access-approval-bridge-types.ts+++ b/backend/src/services/secret-access-approval-bridge/secret-access-approval-bridge-types.ts@@ -89,7 +89,7 @@ export type TSecretAccessApprovalBridgeServiceFactoryDep = {queueService: Pick<TQueueServiceFactory, "queue">;secretAccessApprovalResource: Pick<TSecretAccessApprovalResource,- "canAccess" | "validateConstraints" | "postApprovalTxRoutine"+ "canAccess" | "validateConstraints" | "postApprovalTxRoutine" | "isBreakGlassEligible">;};