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
add reset steps in case the environment or the path changes
adilson1961e4cbcd5d
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 c107a3f06c..34870299fb 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@@ -504,6 +504,31 @@ const openRequest = async (secretPath: string) => {return res.json().approval.id as string;};+const patchPolicy = (policyId: string, body: Record<string, unknown>) =>+ testServer.inject({+ method: "PATCH",+ url: `/api/v1/access-approvals/policies/${policyId}`,+ headers: authHeaders(),+ body: { approvals: 1, allowedSelfApprovals: false, ...body }+ });++const getRequestSteps = async (requestId: string) => {+ const db = getDb();+ const steps = await db(TableName.ApprovalRequestSteps).where({ requestId }).orderBy("stepNumber", "asc");+ return Promise.all(+ steps.map(async (step) => {+ const eligible = await db(TableName.ApprovalRequestStepEligibleApprovers).where({ stepId: step.id });+ const approvals = await db(TableName.ApprovalRequestApprovals).where({ stepId: step.id });+ return {+ id: step.id,+ status: step.status,+ approverUserIds: eligible.map((row) => row.userId).sort(),+ approvalCount: approvals.length+ };+ })+ );+};+describe("Per-step required approvals on the global system", () => {const approvers: TApprover[] = [];const groupIds: string[] = [];@@ -716,6 +741,95 @@ describe("Per-step required approvals on the global system", () => {expect(state.status).toBe("approved");expect(state.privilege).toBeDefined();});++ const twoStepApprovers = () => [+ { type: ApproverType.User, id: a.userId, sequence: 1 },+ { type: ApproverType.User, id: b.userId, sequence: 2 }+ ];++ const openRequestPastStepOne = async (secretPath: string) => {+ const policy = await createPolicyWithApprovers({ secretPath, approvers: twoStepApprovers(), approvals: 1 });+ const requestId = await openRequest(secretPath);+ expect((await reviewAs(a, requestId)).statusCode).toBe(200);++ const before = await getRequestSteps(requestId);+ expect((await getRequestState(requestId)).currentStep).toBe(2);+ expect(before.map((step) => step.approvalCount)).toEqual([1, 0]);+ return { policy, requestId, before };+ };++ const expectStepsReset = async (requestId: string, before: Awaited<ReturnType<typeof getRequestSteps>>) => {+ const after = await getRequestSteps(requestId);+ expect((await getRequestState(requestId)).currentStep).toBe(1);+ expect(after.map((step) => step.status)).toEqual(["in-progress", "pending"]);+ expect(after.map((step) => step.approvalCount)).toEqual([0, 0]);+ expect(after.map((step) => step.id)).not.toEqual(before.map((step) => step.id));+ return after;+ };++ const expectStepsUntouched = async (requestId: string, before: Awaited<ReturnType<typeof getRequestSteps>>) => {+ expect((await getRequestState(requestId)).currentStep).toBe(2);+ expect(await getRequestSteps(requestId)).toEqual(before);+ };++ test("Changing the secret path rebuilds the steps of pending requests", async () => {+ const { policy, requestId, before } = await openRequestPastStepOne("/reset-path");++ const res = await patchPolicy(policy.id, { secretPath: "/reset-path-moved", approvers: twoStepApprovers() });+ expect(res.statusCode).toBe(200);++ const after = await expectStepsReset(requestId, before);+ expect(after.map((step) => step.approverUserIds)).toEqual([[a.userId], [b.userId]]);+ });++ test("Changing the environments rebuilds the steps of pending requests with the updated approvers", async () => {+ const { policy, requestId, before } = await openRequestPastStepOne("/reset-env");+ const otherEnv = await getDb()(TableName.Environment)+ .where({ projectId: seedData1.project.id })+ .whereNot({ slug: seedData1.environment.slug })+ .first();+ expect(otherEnv).toBeDefined();++ const res = await patchPolicy(policy.id, {+ secretPath: "/reset-env",+ environments: [otherEnv!.slug],+ approvers: [...twoStepApprovers(), { type: ApproverType.User, id: c.userId, sequence: 1 }]+ });+ expect(res.statusCode).toBe(200);++ const after = await expectStepsReset(requestId, before);+ expect(after.map((step) => step.approverUserIds)).toEqual([[a.userId, c.userId].sort(), [b.userId]]);+ });++ test("Changing only the approvers leaves the steps of pending requests alone", async () => {+ const { policy, requestId, before } = await openRequestPastStepOne("/reset-approvers-only");++ const res = await patchPolicy(policy.id, {+ secretPath: "/reset-approvers-only",+ environments: [seedData1.environment.slug],+ approvers: [...twoStepApprovers(), { type: ApproverType.User, id: c.userId, sequence: 1 }],+ approvalsRequired: [{ stepNumber: 1, numberOfApprovals: 2 }]+ });+ expect(res.statusCode).toBe(200);++ const policySteps = await getPolicySteps(policy.id);+ expect(policySteps.map((step) => step.requiredApprovals)).toEqual([2, 1]);+ await expectStepsUntouched(requestId, before);+ });++ test("Re-sending the same path and environments does not reset pending requests", async () => {+ const { policy, requestId, before } = await openRequestPastStepOne("/reset-unchanged");++ const res = await patchPolicy(policy.id, {+ name: "reset-unchanged-renamed",+ secretPath: "/reset-unchanged",+ environments: [seedData1.environment.slug],+ approvers: twoStepApprovers()+ });+ expect(res.statusCode).toBe(200);++ await expectStepsUntouched(requestId, before);+ });});describe("Break-glass approvals on the global system", () => {diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 330beff99f..3ccad503dc 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -2491,6 +2491,8 @@ export const registerRoutes = async (approvalPolicySecretEnvironmentDAL,secretAccessApprovalPolicyBridgeDAL,approvalRequestDAL,+ approvalRequestStepsDAL,+ approvalRequestStepEligibleApproversDAL,approvalRequestGrantsDAL,additionalPrivilegeDAL});diff --git a/backend/src/services/approval-policy/approval-request-fns.ts b/backend/src/services/approval-policy/approval-request-fns.tsindex ec67f81721..9d24944c58 100644--- a/backend/src/services/approval-policy/approval-request-fns.ts+++ b/backend/src/services/approval-policy/approval-request-fns.ts@@ -53,6 +53,53 @@ export type TApprovalRequestWithSteps = TApprovalRequests & {}>;};+type TInsertApprovalRequestStepsDeps = {+ approvalRequestStepsDAL: Pick<TApprovalRequestStepsDALFactory, "create">;+ approvalRequestStepEligibleApproversDAL: Pick<TApprovalRequestStepEligibleApproversDALFactory, "create">;+};++export const insertApprovalRequestSteps = async (+ { requestId, policySteps }: { requestId: string; policySteps: ApprovalPolicyStep[] },+ { approvalRequestStepsDAL, approvalRequestStepEligibleApproversDAL }: TInsertApprovalRequestStepsDeps,+ tx: Knex+) =>+ Promise.all(+ policySteps.map(async (step, i) => {+ const stepNum = i + 1;+ const newStep = await approvalRequestStepsDAL.create(+ {+ requestId,+ stepNumber: stepNum,+ name: step.name ?? null,+ status: stepNum === 1 ? ApprovalRequestStepStatus.InProgress : ApprovalRequestStepStatus.Pending,+ requiredApprovals: step.requiredApprovals,+ notifyApprovers: step.notifyApprovers ?? false,+ startedAt: stepNum === 1 ? new Date() : null+ },+ tx+ );++ await Promise.all(+ step.approvers.map((approver) =>+ approvalRequestStepEligibleApproversDAL.create(+ {+ stepId: newStep.id,+ userId: approver.type === ApproverType.User ? approver.id : null,+ groupId: approver.type === ApproverType.Group ? approver.id : null+ },+ tx+ )+ )+ );++ return {+ ...newStep,+ approvers: step.approvers,+ approvals: []+ };+ })+ );+export const createApprovalRequestWithSteps = async ({projectId,@@ -72,9 +119,7 @@ export const createApprovalRequestWithSteps = async (}: TCreateApprovalRequestWithStepsParams,dependencies: {approvalRequestDAL: Pick<TApprovalRequestDALFactory, "create" | "transaction">;- approvalRequestStepsDAL: Pick<TApprovalRequestStepsDALFactory, "create">;- approvalRequestStepEligibleApproversDAL: Pick<TApprovalRequestStepEligibleApproversDALFactory, "create">;- },+ } & TInsertApprovalRequestStepsDeps,externalTx?: Knex): Promise<TApprovalRequestWithSteps> => {const { approvalRequestDAL, approvalRequestStepsDAL, approvalRequestStepEligibleApproversDAL } = dependencies;@@ -101,41 +146,10 @@ export const createApprovalRequestWithSteps = async (tx);- const newSteps = await Promise.all(- policySteps.map(async (step, i) => {- const stepNum = i + 1;- const newStep = await approvalRequestStepsDAL.create(- {- requestId: newRequest.id,- stepNumber: stepNum,- name: step.name ?? null,- status: stepNum === 1 ? ApprovalRequestStepStatus.InProgress : ApprovalRequestStepStatus.Pending,- requiredApprovals: step.requiredApprovals,- notifyApprovers: step.notifyApprovers ?? false,- startedAt: stepNum === 1 ? new Date() : null- },- tx- );-- await Promise.all(- step.approvers.map((approver) =>- approvalRequestStepEligibleApproversDAL.create(- {- stepId: newStep.id,- userId: approver.type === ApproverType.User ? approver.id : null,- groupId: approver.type === ApproverType.Group ? approver.id : null- },- tx- )- )- );-- return {- ...newStep,- approvers: step.approvers,- approvals: []- };- })+ const newSteps = await insertApprovalRequestSteps(+ { requestId: newRequest.id, policySteps },+ { approvalRequestStepsDAL, approvalRequestStepEligibleApproversDAL },+ tx);return { request: newRequest, steps: newSteps };diff --git a/backend/src/services/secret-access-approval-policy-bridge/secret-access-approval-policy-bridge-service.ts b/backend/src/services/secret-access-approval-policy-bridge/secret-access-approval-policy-bridge-service.tsindex 46735d603a..ab97e3d0b9 100644--- a/backend/src/services/secret-access-approval-policy-bridge/secret-access-approval-policy-bridge-service.ts+++ b/backend/src/services/secret-access-approval-policy-bridge/secret-access-approval-policy-bridge-service.ts@@ -16,6 +16,7 @@ import {ApprovalRequestGrantStatus,ApprovalRequestStatus} from "@app/services/approval-policy/approval-policy-enums";+import { insertApprovalRequestSteps } from "@app/services/approval-policy/approval-request-fns";import { ActorType } from "@app/services/auth/auth-type";import {@@ -58,6 +59,8 @@ export const secretAccessApprovalPolicyBridgeServiceFactory = ({approvalPolicySecretEnvironmentDAL,secretAccessApprovalPolicyBridgeDAL,approvalRequestDAL,+ approvalRequestStepsDAL,+ approvalRequestStepEligibleApproversDAL,approvalRequestGrantsDAL,additionalPrivilegeDAL}: TSecretAccessApprovalPolicyBridgeServiceFactoryDep) => {@@ -267,6 +270,27 @@ export const secretAccessApprovalPolicyBridgeServiceFactory = ({return permission;};+ const $resetPendingRequestSteps = async (+ { policyId, steps }: { policyId: string; steps: TPolicyStep[] },+ tx: Knex+ ) => {+ const pendingRequests = await approvalRequestDAL.find({ policyId, status: ApprovalRequestStatus.Pending }, { tx });+ if (!pendingRequests.length) return;++ const requestIds = pendingRequests.map((request) => request.id);+ await approvalRequestStepsDAL.delete({ $in: { requestId: requestIds } }, tx);+ await Promise.all(+ requestIds.map((requestId) =>+ insertApprovalRequestSteps(+ { requestId, policySteps: steps },+ { approvalRequestStepsDAL, approvalRequestStepEligibleApproversDAL },+ tx+ )+ )+ );+ await approvalRequestDAL.update({ $in: { id: requestIds } }, { currentStep: 1 }, tx);+ };+const $findPolicyById = async (policyId: string, organizationId: string, message: string) => {const [policy] = await secretAccessApprovalPolicyBridgeDAL.findSecretAccessPolicies({ policyId, organizationId });if (!policy) throw new NotFoundError({ message });@@ -432,6 +456,12 @@ export const secretAccessApprovalPolicyBridgeServiceFactory = ({}const nextSecretPath = secretPath || policy.secretPath;+ const currentEnvSlugs = new Set(policy.environments.map((env) => env.slug));+ const environmentsChanged =+ environments !== undefined &&+ (envs.length !== currentEnvSlugs.size || envs.some((env) => !currentEnvSlugs.has(env.slug)));+ const scopeChanged = nextSecretPath !== policy.secretPath || environmentsChanged;+for (const env of envs) {if (// eslint-disable-next-line no-await-in-loop@@ -474,12 +504,13 @@ export const secretAccessApprovalPolicyBridgeServiceFactory = ({await approvalPolicyBypassersDAL.delete({ policyId: policy.id }, tx);await $insertStepsAndBypassers({ policyId: policy.id, steps, bypasserUserIds, groupBypassers }, tx);- if (environments || secretPath) {+ if (scopeChanged) {await approvalPolicySecretEnvironmentDAL.delete({ policyId: policy.id }, tx);await approvalPolicySecretEnvironmentDAL.insertMany(envs.map((env) => ({ policyId: policy.id, envId: env.id, secretPath: nextSecretPath })),tx);+ await $resetPendingRequestSteps({ policyId: policy.id, steps }, tx);}const [updatedPolicy] = await secretAccessApprovalPolicyBridgeDAL.findSecretAccessPolicies(diff --git a/backend/src/services/secret-access-approval-policy-bridge/secret-access-approval-policy-bridge-types.ts b/backend/src/services/secret-access-approval-policy-bridge/secret-access-approval-policy-bridge-types.tsindex 5ac055be9f..7d850f0991 100644--- a/backend/src/services/secret-access-approval-policy-bridge/secret-access-approval-policy-bridge-types.ts+++ b/backend/src/services/secret-access-approval-policy-bridge/secret-access-approval-policy-bridge-types.ts@@ -17,7 +17,9 @@ import {} from "@app/services/approval-policy/approval-policy-dal";import {TApprovalRequestDALFactory,- TApprovalRequestGrantsDALFactory+ TApprovalRequestGrantsDALFactory,+ TApprovalRequestStepEligibleApproversDALFactory,+ TApprovalRequestStepsDALFactory} from "@app/services/approval-policy/approval-request-dal";import { TProjectDALFactory } from "@app/services/project/project-dal";import { TProjectEnvDALFactory } from "@app/services/project-env/project-env-dal";@@ -41,6 +43,8 @@ export type TSecretAccessApprovalPolicyBridgeServiceFactoryDep = {"insertMany" | "delete" | "findPolicyByEnvIdsAndSecretPath">;approvalRequestDAL: Pick<TApprovalRequestDALFactory, "find" | "update">;+ approvalRequestStepsDAL: Pick<TApprovalRequestStepsDALFactory, "create" | "delete">;+ approvalRequestStepEligibleApproversDAL: Pick<TApprovalRequestStepEligibleApproversDALFactory, "create">;approvalRequestGrantsDAL: Pick<TApprovalRequestGrantsDALFactory, "update">;additionalPrivilegeDAL: Pick<TAdditionalPrivilegeDALFactory, "delete">;secretAccessApprovalPolicyBridgeDAL: Pick<TSecretAccessApprovalPolicyBridgeDALFactory, "findSecretAccessPolicies">;