Skip to content

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

address greptile comments

adilson79dc5aea808f
diff --git a/backend/src/ee/services/secret-change-request-bridge/secret-change-request-bridge-service.test.ts b/backend/src/ee/services/secret-change-request-bridge/secret-change-request-bridge-service.test.ts
index 996dfda720..f821b6a99a 100644
--- a/backend/src/ee/services/secret-change-request-bridge/secret-change-request-bridge-service.test.ts
+++ b/backend/src/ee/services/secret-change-request-bridge/secret-change-request-bridge-service.test.ts
@@ -795,11 +795,11 @@ describe("secretChangeRequestBridge mergeSecretChangeRequest", () => {
test("lets a soft policy without bypassers merge unapproved and records the bypass", async () => {
const { service, deps } = buildService({ policy: { ...POLICY, enforcementLevel: "soft" } });
- const result = await merge(service, { actorId: "user-1", bypassReason: "incident" });
+ const result = await merge(service, { actorId: "user-1", bypassReason: " incident response " });
expect(deps.secretChangeRequestDAL.updateById).toHaveBeenCalledWith(
"change-1",
- expect.objectContaining({ hasMerged: true, bypassReason: "incident" }),
+ expect.objectContaining({ hasMerged: true, bypassReason: "incident response" }),
OWN_TX
);
expect(queueChangeRequestWebhook).toHaveBeenCalledWith(expect.objectContaining({ isBypassed: true }));
@@ -809,22 +809,62 @@ describe("secretChangeRequestBridge mergeSecretChangeRequest", () => {
secretPath: "/app",
actorId: "user-1",
approverUserIds: ["approver-1"],
- bypassReason: "incident"
+ bypassReason: "incident response"
});
- expect(result).toMatchObject({ isMergedViaBypass: true, approval: { bypassReason: "incident" } });
+ expect(result).toMatchObject({ isMergedViaBypass: true, approval: { bypassReason: "incident response" } });
});
test("only a listed bypasser, directly or through a group, can bypass a soft policy", async () => {
const policy = { ...POLICY, enforcementLevel: "soft", bypassers: [{ type: "group", id: "group-9" }] };
+ const bypass = { actorId: "user-1", bypassReason: "incident response" };
const refused = buildService({ policy });
- await expect(merge(refused.service, { actorId: "user-1" })).rejects.toBeInstanceOf(BadRequestError);
+ await expect(merge(refused.service, bypass)).rejects.toBeInstanceOf(BadRequestError);
const allowed = buildService({ policy });
allowed.deps.userGroupMembershipDAL.findGroupMembershipsByUserIdInOrg.mockResolvedValue([{ groupId: "group-9" }]);
- await expect(merge(allowed.service, { actorId: "user-1" })).resolves.toMatchObject({ isMergedViaBypass: true });
+ await expect(merge(allowed.service, bypass)).resolves.toMatchObject({ isMergedViaBypass: true });
const direct = buildService({ policy: { ...policy, bypassers: [{ type: "user", id: "user-1" }] } });
- await expect(merge(direct.service, { actorId: "user-1" })).resolves.toMatchObject({ isMergedViaBypass: true });
+ await expect(merge(direct.service, bypass)).resolves.toMatchObject({ isMergedViaBypass: true });
+ });
+
+ test("refuses a bypass merge without a reason of at least 10 characters", async () => {
+ const { service, deps } = buildService({ policy: { ...POLICY, enforcementLevel: "soft" } });
+ const refusal = new BadRequestError({
+ message: "A bypass reason of at least 10 characters is required to bypass approvals"
+ });
+
+ await expect(merge(service, { actorId: "user-1" })).rejects.toThrow(refusal);
+ await expect(merge(service, { actorId: "user-1", bypassReason: " " })).rejects.toThrow(refusal);
+ await expect(merge(service, { actorId: "user-1", bypassReason: "too short" })).rejects.toThrow(refusal);
+ expect(applySecretApprovalCommitsV2Bridge).not.toHaveBeenCalled();
+ expect(deps.secretChangeRequestDAL.updateById).not.toHaveBeenCalled();
+ });
+
+ test("refuses when an approval is withdrawn between the checks and the lock", async () => {
+ const { service, deps } = buildService({ requestSteps: [stepWith({ approvals: approvedBy("approver-1") })] });
+ deps.approvalRequestDAL.findStepsByRequestId
+ .mockResolvedValueOnce([stepWith({ approvals: approvedBy("approver-1") })])
+ .mockResolvedValueOnce([
+ stepWith({
+ approvals: [
+ {
+ id: "approval-0",
+ stepId: "step-1",
+ approverUserId: "approver-1",
+ decision: ApprovalRequestApprovalDecision.Rejected
+ }
+ ]
+ })
+ ]);
+
+ await expect(merge(service)).rejects.toThrow(
+ new BadRequestError({ message: "Secret approval request 'slug-1' needs 1 approval(s) on step 1 and has 0." })
+ );
+ expect(deps.approvalRequestDAL.findStepsByRequestId).toHaveBeenNthCalledWith(2, "request-1", OWN_TX);
+ expect(applySecretApprovalCommitsV2Bridge).not.toHaveBeenCalled();
+ expect(deps.secretChangeRequestDAL.updateById).not.toHaveBeenCalled();
+ expect(deps.approvalRequestDAL.updateById).not.toHaveBeenCalled();
});
test("does not persist a bypass reason on a fully approved merge", async () => {
@@ -984,11 +1024,40 @@ describe("secretChangeRequestBridge updateSecretChangeRequestStatus", () => {
await expect(setStatus(service, { status: RequestState.Open })).resolves.toMatchObject({
status: ApprovalRequestStatus.Open
});
+ expect(deps.approvalPolicyDAL.findByIdForShare).toHaveBeenCalledWith("policy-1", OWN_TX);
+ expect(deps.approvalPolicyDAL.findByIdForShare.mock.invocationCallOrder[0]).toBeLessThan(
+ deps.approvalRequestDAL.findByIdForUpdate.mock.invocationCallOrder[0]
+ );
expect(queueChangeRequestWebhook).toHaveBeenCalledWith(
expect.objectContaining({ action: ChangeRequestWebhookAction.Reopened })
);
});
+ test("refuses when the policy is deleted while the reopen waits on its lock", async () => {
+ const { service, deps } = buildService();
+ const closed = { ...APPROVAL_REQUEST, status: ApprovalRequestStatus.Closed };
+ deps.approvalRequestDAL.findById.mockResolvedValue(closed);
+ deps.approvalPolicyDAL.findByIdForShare.mockResolvedValueOnce(undefined);
+
+ await expect(setStatus(service, { status: RequestState.Open })).rejects.toThrow("has been deleted");
+ expect(deps.approvalRequestDAL.findByIdForUpdate).not.toHaveBeenCalled();
+ expect(deps.approvalRequestDAL.updateById).not.toHaveBeenCalled();
+ expect(deps.secretChangeRequestDAL.updateById).not.toHaveBeenCalled();
+ expect(queueChangeRequestWebhook).not.toHaveBeenCalled();
+ });
+
+ test("refuses when the locked request no longer belongs to the policy", async () => {
+ const { service, deps } = buildService();
+ const closed = { ...APPROVAL_REQUEST, status: ApprovalRequestStatus.Closed };
+ deps.approvalRequestDAL.findById.mockResolvedValue(closed);
+ deps.approvalRequestDAL.findByIdForUpdate.mockResolvedValueOnce({ ...closed, policyId: null });
+
+ await expect(setStatus(service, { status: RequestState.Open })).rejects.toThrow("has been deleted");
+ expect(deps.approvalRequestDAL.updateById).not.toHaveBeenCalled();
+ expect(deps.secretChangeRequestDAL.updateById).not.toHaveBeenCalled();
+ expect(queueChangeRequestWebhook).not.toHaveBeenCalled();
+ });
+
test("refuses when the plan lacks secret approvals", async () => {
const { service, deps } = buildService();
deps.licenseService.getPlan.mockResolvedValue({ secretApproval: false });
diff --git a/backend/src/ee/services/secret-change-request-bridge/secret-change-request-bridge-service.ts b/backend/src/ee/services/secret-change-request-bridge/secret-change-request-bridge-service.ts
index f04e8370e3..c2e4f4d7f3 100644
--- a/backend/src/ee/services/secret-change-request-bridge/secret-change-request-bridge-service.ts
+++ b/backend/src/ee/services/secret-change-request-bridge/secret-change-request-bridge-service.ts
@@ -166,6 +166,10 @@ type TSecretChangeRequestBridgeServiceFactoryDep = {
telemetryService: Pick<TTelemetryServiceFactory, "sendPostHogEvents">;
};
+type TRequestSteps = Awaited<ReturnType<TApprovalRequestDALFactory["findStepsByRequestId"]>>;
+
+const POLICY_DELETED_MESSAGE = "The policy associated with this secret approval request has been deleted.";
+
export type TSecretChangeRequestBridgeServiceFactory = ReturnType<typeof secretChangeRequestBridgeServiceFactory>;
export const secretChangeRequestBridgeServiceFactory = ({
@@ -288,9 +292,7 @@ export const secretChangeRequestBridgeServiceFactory = ({
? await secretChangePolicyBridgeService.findSecretChangePolicyById(policyId, tx)
: undefined;
if (!policy) {
- throw new BadRequestError({
- message: "The policy associated with this secret approval request has been deleted."
- });
+ throw new BadRequestError({ message: POLICY_DELETED_MESSAGE });
}
return policy;
};
@@ -338,6 +340,51 @@ export const secretChangeRequestBridgeServiceFactory = ({
return { hasRole, permission, steps, currentStep, userGroupIds };
};
+ const $findUnmetStep = (steps: TRequestSteps, eligibleByStepId: Map<string, Set<string>>) =>
+ steps
+ .map((step) => {
+ const eligibleUserIds = eligibleByStepId.get(step.id) ?? new Set<string>();
+ const approvedCount = new Set(
+ step.approvals
+ .filter(
+ (approval) =>
+ approval.decision === ApprovalRequestApprovalDecision.Approved &&
+ eligibleUserIds.has(approval.approverUserId)
+ )
+ .map((approval) => approval.approverUserId)
+ ).size;
+ return { step, approvedCount };
+ })
+ .find(({ step, approvedCount }) => approvedCount < step.requiredApprovals);
+
+ const $resolveMergeBypass = ({
+ unmetStep,
+ slug,
+ isSoftEnforcement,
+ canBypass,
+ bypassReason
+ }: {
+ unmetStep: ReturnType<typeof $findUnmetStep>;
+ slug: string;
+ isSoftEnforcement: boolean;
+ canBypass: boolean;
+ bypassReason?: string;
+ }): { isMergedViaBypass: true; bypassReason: string } | { isMergedViaBypass: false; bypassReason: null } => {
+ if (!unmetStep) return { isMergedViaBypass: false, bypassReason: null };
+ if (!(isSoftEnforcement && canBypass)) {
+ throw new BadRequestError({
+ message: `Secret approval request '${slug}' needs ${unmetStep.step.requiredApprovals} approval(s) on step ${unmetStep.step.stepNumber} and has ${unmetStep.approvedCount}.`
+ });
+ }
+ const trimmed = bypassReason?.trim() ?? "";
+ if (trimmed.length < 10) {
+ throw new BadRequestError({
+ message: "A bypass reason of at least 10 characters is required to bypass approvals"
+ });
+ }
+ return { isMergedViaBypass: true, bypassReason: trimmed };
+ };
+
const $writeSecretChangeRequest = async (
{
policyId,
@@ -576,22 +623,11 @@ export const secretChangeRequestBridgeServiceFactory = ({
action: "merge"
});
- const stepApprovals = await Promise.all(
- steps.map(async (step) => {
- const eligibleUserIds = await resolveStepApproverUserIds(step, userGroupMembershipDAL);
- const approvedCount = new Set(
- step.approvals
- .filter(
- (approval) =>
- approval.decision === ApprovalRequestApprovalDecision.Approved &&
- eligibleUserIds.has(approval.approverUserId)
- )
- .map((approval) => approval.approverUserId)
- ).size;
- return { step, approvedCount };
- })
+ const eligibleByStepId = new Map(
+ await Promise.all(
+ steps.map(async (step) => [step.id, await resolveStepApproverUserIds(step, userGroupMembershipDAL)] as const)
+ )
);
- const unmetStep = stepApprovals.find(({ step, approvedCount }) => approvedCount < step.requiredApprovals);
const isSoftEnforcement = policy.enforcementLevel === EnforcementLevel.Soft;
const canBypass =
!policy.bypassers.length ||
@@ -600,13 +636,15 @@ export const secretChangeRequestBridgeServiceFactory = ({
(bypasser.type === BypasserType.User && bypasser.id === actorId) ||
(bypasser.type === BypasserType.Group && userGroupIds.has(bypasser.id))
);
-
- if (unmetStep && !(isSoftEnforcement && canBypass)) {
- throw new BadRequestError({
- message: `Secret approval request '${secretChangeRequest.slug}' needs ${unmetStep.step.requiredApprovals} approval(s) on step ${unmetStep.step.stepNumber} and has ${unmetStep.approvedCount}.`
+ const resolveBypass = (requestSteps: TRequestSteps) =>
+ $resolveMergeBypass({
+ unmetStep: $findUnmetStep(requestSteps, eligibleByStepId),
+ slug: secretChangeRequest.slug,
+ isSoftEnforcement,
+ canBypass,
+ bypassReason
});
- }
- const isMergedViaBypass = isSoftEnforcement && Boolean(unmetStep);
+ resolveBypass(steps);
const project = await projectDAL.findById(projectId);
if (!project) throw new NotFoundError({ message: `Project with ID '${projectId}' not found` });
@@ -624,6 +662,8 @@ export const secretChangeRequestBridgeServiceFactory = ({
if (!locked || locked.status !== ApprovalRequestStatus.Open) {
throw new BadRequestError({ message: "You can only merge open approval requests" });
}
+ const lockedSteps = await approvalRequestDAL.findStepsByRequestId(approvalRequest.id, tx);
+ const bypass = resolveBypass(lockedSteps);
const secrets = await applySecretApprovalCommitsV2Bridge({
projectId,
@@ -649,7 +689,7 @@ export const secretChangeRequestBridgeServiceFactory = ({
conflicts: JSON.stringify(conflicts),
hasMerged: true,
statusChangedByUserId: actorId,
- bypassReason: isMergedViaBypass ? (bypassReason ?? null) : null
+ bypassReason: bypass.bypassReason
},
tx
);
@@ -660,7 +700,7 @@ export const secretChangeRequestBridgeServiceFactory = ({
);
await secretV2BridgeDAL.invalidateSecretCacheByProjectId(projectId, tx);
- return { secrets, approvalRequest: mergedApprovalRequest, secretChangeRequest: mergedChangeRequest };
+ return { secrets, approvalRequest: mergedApprovalRequest, secretChangeRequest: mergedChangeRequest, bypass };
});
await syncMergedSecrets({ projectId, actorOrgId, actor, actorId, folder, secrets: merged.secrets });
@@ -675,7 +715,7 @@ export const secretChangeRequestBridgeServiceFactory = ({
environment: folder.environmentSlug,
environmentName: folder.environmentName,
secretPath: folder.path,
- isBypassed: isMergedViaBypass
+ isBypassed: merged.bypass.isMergedViaBypass
});
} catch (error) {
logger.error(
@@ -684,14 +724,14 @@ export const secretChangeRequestBridgeServiceFactory = ({
);
}
- if (isMergedViaBypass) {
+ if (merged.bypass.isMergedViaBypass) {
await notifySecretApprovalBypass({
project,
environmentName: folder.environmentName,
secretPath: folder.path,
actorId,
approverUserIds: unique(policy.userApprovers.map((approver) => approver.userId)),
- bypassReason
+ bypassReason: merged.bypass.bypassReason
});
}
@@ -709,7 +749,7 @@ export const secretChangeRequestBridgeServiceFactory = ({
secretPath: folder.path,
secrets: merged.secrets
}),
- isMergedViaBypass,
+ isMergedViaBypass: merged.bypass.isMergedViaBypass,
requestedByActor: buildRequestedByActor({
committerUserId: approvalRequest.requesterId,
committerUser: { email: approvalRequest.requesterEmail, username: approvalRequest.requesterEmail },
@@ -835,10 +875,14 @@ export const secretChangeRequestBridgeServiceFactory = ({
if (approvalRequest.status === status) throw new BadRequestError({ message: alreadyInStatusMessage });
const updated = await approvalRequestDAL.transaction(async (tx) => {
+ const lockedPolicy = await approvalPolicyDAL.findByIdForShare(policy.id, tx);
+ if (!lockedPolicy) throw new BadRequestError({ message: POLICY_DELETED_MESSAGE });
+
const locked = await approvalRequestDAL.findByIdForUpdate(approvalRequest.id, tx);
if (!locked || locked.status !== approvalRequest.status) {
throw new BadRequestError({ message: alreadyInStatusMessage });
}
+ if (locked.policyId !== policy.id) throw new BadRequestError({ message: POLICY_DELETED_MESSAGE });
const lockedChangeRequest = await secretChangeRequestDAL.findOne({ approvalRequestId: approvalRequest.id }, tx);
if (!lockedChangeRequest || lockedChangeRequest.hasMerged) {
throw new BadRequestError({ message: "Approval request has been merged" });