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
Merge tests/secrets-phase-1-core into tests/secrets-phase-2-governance
varonixe942067bc5ad
diff --cc backend/e2e-test/routes/v1/access-approval-global-policy-routing.spec.tsindex e31fa568cd,fababd4eb2..f458ca7c64--- a/backend/e2e-test/routes/v1/access-approval-global-policy-routing.spec.ts+++ b/backend/e2e-test/routes/v1/access-approval-global-policy-routing.spec.ts@@@ -166,8 -246,57 +167,29 @@@ describe("Access approval policy routinconst unchangedLegacy = await db(TableName.AccessApprovalPolicy).where({ id: legacyPolicy.id }).first();expect(unchangedLegacy?.secretPath).toBe("/policy-routing-conflict-legacy");-- const samePath = await patchPolicy(policy.id, { secretPath: "/policy-routing-conflict" });- expect(samePath.statusCode).toBe(200);});+ test("A migrated policy's legacy row does not block the scope it moved away from", async () => {+ const migrated = await createGlobalPolicy({+ name: "policy-routing-migrated",+ secretPath: "/policy-routing-migrated"+ });+ await createLegacyPolicy({+ id: migrated.id,+ name: "policy-routing-migrated",+ secretPath: "/policy-routing-migrated"+ });++ const moved = await patchPolicy(migrated.id, { secretPath: "/policy-routing-migrated-moved" });+ expect(moved.statusCode).toBe(200);++ const replacement = await createGlobalPolicy({+ name: "policy-routing-migrated-replacement",+ secretPath: "/policy-routing-migrated"+ });+ expect(replacement.secretPath).toBe("/policy-routing-migrated");+ });+- test("Getting a global policy by id carries approver and bypasser names", async () => {- const policy = await createGlobalPolicy({- name: "policy-routing-get",- secretPath: "/policy-routing-get",- bypassers: [{ type: BypasserType.User, id: seedData1.id }]- });-- const res = await getPolicy(policy.id);-- expect(res.statusCode).toBe(200);- const { approval } = res.json();- expect(approval.id).toBe(policy.id);- expect(approval.secretPath).toBe("/policy-routing-get");- expect(approval.approvers).toEqual([- {- id: seedData1.id,- type: ApproverType.User,- name: seedData1.username,- sequence: 1,- approvalsRequired: 1- }- ]);- expect(approval.bypassers).toEqual([{ id: seedData1.id, type: BypasserType.User, name: seedData1.username }]);- });-test("Listing and counting policies include both systems", async () => {const legacyPolicy = await createLegacyPolicy({name: "policy-routing-list-legacy",diff --cc backend/e2e-test/routes/v1/access-approval-global-request-lifecycle.spec.tsindex 040604e1b0,46cd2a1e1a..6429fcbee4--- 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@@@ -98,4 -473,813 +111,209 @@@ describe("Access approval request lifecexpect(rejectRes.statusCode).toBe(400);expect(rejectRes.json().message).toBe("The request has been closed");});+});+- const openPendingRequest = async (secretPath: string) => {- const policy = await createGlobalPolicy({ name: `scope-${secretPath.replace(/[/*]/g, "")}`, secretPath });- const createRes = await createAccessRequest(secretPath);- expect(createRes.statusCode).toBe(200);- return { policy, requestId: createRes.json().approval.id as string };- };-- test("Approval is refused when the policy path no longer contains the requested glob", async () => {- const secretPath = "/scope-mismatch/*";- const { policy, requestId } = await openPendingRequest(secretPath);-- await getDb()(TableName.ApprovalPolicySecretEnvironment)- .where({ policyId: policy.id })- .update({ secretPath: "/other" });-- const approveRes = await reviewAccessRequest(requestId, { status: "approved" });- expect(approveRes.statusCode).toBe(400);- expect(approveRes.json().message).toBe(`The policy no longer covers secret path '${secretPath}'.`);-- const request = await getDb()(TableName.ApprovalRequests).where({ id: requestId }).first();- expect(request?.status).toBe("pending");- });-- test("Approval stands when a broader policy path still contains the requested glob", async () => {- const secretPath = "/scope-broader/*";- const { policy, requestId } = await openPendingRequest(secretPath);-- await getDb()(TableName.ApprovalPolicySecretEnvironment)- .where({ policyId: policy.id })- .update({ secretPath: "/scope-broader/**" });-- const approveRes = await reviewAccessRequest(requestId, { status: "approved" });- expect(approveRes.statusCode).toBe(200);-- const request = await getDb()(TableName.ApprovalRequests).where({ id: requestId }).first();- expect(request?.status).toBe("approved");- });-- test("Approval is refused when the policy no longer includes the requested environment", async () => {- const { policy, requestId } = await openPendingRequest("/scope-env");- const otherEnv = await getDb()(TableName.Environment)- .where({ projectId: seedData1.project.id })- .whereNot({ slug: seedData1.environment.slug })- .first();- expect(otherEnv).toBeDefined();-- await getDb()(TableName.ApprovalPolicySecretEnvironment)- .where({ policyId: policy.id })- .update({ envId: otherEnv!.id });-- const approveRes = await reviewAccessRequest(requestId, { status: "approved" });- expect(approveRes.statusCode).toBe(400);- expect(approveRes.json().message).toBe(- `The policy is no longer attached to environment '${seedData1.environment.slug}'.`- );- });-- test("A request whose policy path no longer matches can still be rejected", async () => {- const { policy, requestId } = await openPendingRequest("/scope-reject/*");++const createApprovedTemporaryRequest = async (secretPath: string) => {++ const policy = await createGlobalPolicy({ name: `lifecycle-${secretPath.slice(1)}`, secretPath });+- await getDb()(TableName.ApprovalPolicySecretEnvironment)- .where({ policyId: policy.id })- .update({ secretPath: "/other" });++ const createRes = await createAccessRequest(secretPath, { isTemporary: true, temporaryRange: "1h" });++ expect(createRes.statusCode).toBe(200);++ const requestId = createRes.json().approval.id as string;+- const rejectRes = await reviewAccessRequest(requestId, { status: "rejected" });- expect(rejectRes.statusCode).toBe(200);- expect(rejectRes.json().review.status).toBe("rejected");++ const reviewRes = await reviewAccessRequest(requestId, { status: "approved" });++ expect(reviewRes.statusCode).toBe(200);+- const request = await getDb()(TableName.ApprovalRequests).where({ id: requestId }).first();- expect(request?.status).toBe("rejected");- const grants = await getDb()(TableName.ApprovalRequestGrants).where({ requestId });- expect(grants).toHaveLength(0);- });-});++ return { policy, requestId };++};++ type TApprover = { userId: string; token: string };++ const createApproverUser = async (): Promise<TApprover> => {+ const db = getDb();+ const username = `access-approver-${alphaNumericNanoId(8)}@example.com`.toLowerCase();+ const [user] = await db(TableName.Users)+ .insert({ username, email: username, isGhost: false, isAccepted: true, authMethods: [AuthMethod.EMAIL] })+ .returning("*");++ const [orgMembership] = await db(TableName.Membership)+ .insert({+ scope: AccessScope.Organization,+ scopeOrgId: seedData1.organization.id,+ actorUserId: user.id,+ status: OrgMembershipStatus.Accepted,+ isActive: true+ })+ .returning("*");+ await db(TableName.MembershipRole).insert({ membershipId: orgMembership.id, role: OrgMembershipRole.Member });++ const [projectMembership] = await db(TableName.Membership)+ .insert({+ scope: AccessScope.Project,+ scopeOrgId: seedData1.organization.id,+ scopeProjectId: seedData1.project.id,+ actorUserId: user.id+ })+ .returning("*");+ await db(TableName.MembershipRole).insert({+ membershipId: projectMembership.id,+ role: ProjectMembershipRole.Member+ });++ const [session] = await db(TableName.AuthTokenSession)+ .insert({+ userId: user.id,+ ip: "127.0.0.1",+ userAgent: "e2e-access-approval-required-approvals",+ accessVersion: 1,+ refreshVersion: 1,+ lastUsed: new Date()+ } as never)+ .returning("*");++ return {+ userId: user.id,+ token: jwt.sign(+ {+ authTokenType: AuthTokenType.ACCESS_TOKEN,+ userId: user.id,+ tokenVersionId: session.id,+ authMethod: AuthMethod.EMAIL,+ organizationId: seedData1.organization.id,+ accessVersion: 1+ },+ getConfig().AUTH_SECRET,+ { expiresIn: 3600 }+ )+ };+ };+-const reviewAs = (approver: TApprover, requestId: string) =>- testServer.inject({- method: "POST",- url: `/api/v1/access-approvals/requests/${requestId}/review`,- headers: { authorization: `Bearer ${approver.token}` },- body: { status: "approved" }- });--const createPolicyWithApprovers = async (body: {- secretPath: string;- approvers: { type: ApproverType; id: string; sequence?: number }[];- approvals: number;- approvalsRequired?: { stepNumber: number; numberOfApprovals: number }[];-}) => {- 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: `required-${body.secretPath.slice(1)}`,- allowedSelfApprovals: false,- ...body- }- });- expect(res.statusCode).toBe(200);- const { approval } = res.json();- globalPolicyIds.push(approval.id);- return approval as { id: string };-};--const getPolicySteps = (policyId: string) =>- getDb()(TableName.ApprovalPolicySteps).where({ policyId }).orderBy("stepNumber", "asc");-+ const getRequestState = async (requestId: string) => {+ const db = getDb();+ const request = await db(TableName.ApprovalRequests).where({ id: requestId }).first();+ const grant = await db(TableName.ApprovalRequestGrants).where({ requestId }).first();+ const privilege = grant ? await db(TableName.AdditionalPrivilege).where({ grantId: grant.id }).first() : undefined;+ return { status: request?.status, currentStep: request?.currentStep, grant, privilege };+ };+-const openRequest = async (secretPath: string) => {- const res = await createAccessRequest(secretPath);- expect(res.statusCode).toBe(200);- 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[] = [];- let a: TApprover;- let b: TApprover;- let c: TApprover;-- beforeAll(async () => {- initLogger();- await initEnvConfig(testHsmService, testKmsRootConfigDAL, testSuperAdminDAL, logger);- a = await createApproverUser();- b = await createApproverUser();- c = await createApproverUser();- approvers.push(a, b, c);- });-- 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((approver) => approver.userId);- await db(TableName.UserGroupMembership).whereIn("userId", userIds).del();- if (groupIds.length) {- await db(TableName.Membership).whereIn("actorGroupId", groupIds).del();- await db(TableName.Groups).whereIn("id", groupIds).del();- }- 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("Two of three approvers complete a step that needs two approvals", async () => {- const secretPath = "/required-two-of-three";- const policy = await createPolicyWithApprovers({- secretPath,- approvers: [a, b, c].map((approver) => ({ type: ApproverType.User, id: approver.userId })),- approvals: 1,- approvalsRequired: [{ stepNumber: 1, numberOfApprovals: 2 }]- });-- const steps = await getPolicySteps(policy.id);- expect(steps.map((step) => step.requiredApprovals)).toEqual([2]);-- const requestId = await openRequest(secretPath);-- expect((await reviewAs(a, requestId)).statusCode).toBe(200);- const afterFirst = await getRequestState(requestId);- expect(afterFirst.status).toBe("pending");- expect(afterFirst.grant).toBeUndefined();-- expect((await reviewAs(b, requestId)).statusCode).toBe(200);- const afterSecond = await getRequestState(requestId);- expect(afterSecond.status).toBe("approved");- expect(afterSecond.grant?.status).toBe("active");- expect(afterSecond.privilege?.actorUserId).toBe(seedData1.id);-- const lateReview = await reviewAs(c, requestId);- expect(lateReview.statusCode).toBe(400);- expect(lateReview.json().message).toBe("The request has been closed");- });-- test("With two approvers and one required approval, the first approval approves the request", async () => {- const secretPath = "/required-one-of-two";- const policy = await createPolicyWithApprovers({- secretPath,- approvers: [a, b].map((approver) => ({ type: ApproverType.User, id: approver.userId })),- approvals: 1,- approvalsRequired: [{ stepNumber: 1, numberOfApprovals: 1 }]- });-- const steps = await getPolicySteps(policy.id);- expect(steps.map((step) => step.requiredApprovals)).toEqual([1]);-- const requestId = await openRequest(secretPath);-- expect((await reviewAs(b, requestId)).statusCode).toBe(200);- const state = await getRequestState(requestId);- expect(state.status).toBe("approved");- expect(state.grant?.status).toBe("active");- expect(state.privilege?.actorUserId).toBe(seedData1.id);-- const secondReview = await reviewAs(a, requestId);- expect(secondReview.statusCode).toBe(400);- expect(secondReview.json().message).toBe("The request has been closed");- });-- test("A first step with no approvalsRequired entry needs the policy's approvals", async () => {- const secretPath = "/required-from-approvals";- const policy = await createPolicyWithApprovers({- secretPath,- approvers: [- { type: ApproverType.User, id: a.userId },- { type: ApproverType.User, id: b.userId }- ],- approvals: 2- });-- const steps = await getPolicySteps(policy.id);- expect(steps.map((step) => step.requiredApprovals)).toEqual([2]);-- const requestId = await openRequest(secretPath);- expect((await reviewAs(a, requestId)).statusCode).toBe(200);- expect((await getRequestState(requestId)).status).toBe("pending");-- expect((await reviewAs(b, requestId)).statusCode).toBe(200);- const state = await getRequestState(requestId);- expect(state.status).toBe("approved");- expect(state.privilege).toBeDefined();- });-- test("The second step starts only after the first and needs its own two approvals", async () => {- const secretPath = "/required-two-steps";- const policy = await createPolicyWithApprovers({- secretPath,- approvers: [- { type: ApproverType.User, id: a.userId, sequence: 1 },- { type: ApproverType.User, id: b.userId, sequence: 2 },- { type: ApproverType.User, id: c.userId, sequence: 2 }- ],- approvals: 1,- approvalsRequired: [- { stepNumber: 1, numberOfApprovals: 1 },- { stepNumber: 2, numberOfApprovals: 2 }- ]- });-- const steps = await getPolicySteps(policy.id);- expect(steps.map((step) => step.requiredApprovals)).toEqual([1, 2]);-- const requestId = await openRequest(secretPath);-- const early = await reviewAs(b, requestId);- expect(early.statusCode).toBe(400);- expect(early.json().message).toBe("You are not a reviewer in this step");-- expect((await reviewAs(a, requestId)).statusCode).toBe(200);- const afterStepOne = await getRequestState(requestId);- expect(afterStepOne.status).toBe("pending");- expect(afterStepOne.currentStep).toBe(2);-- expect((await reviewAs(b, requestId)).statusCode).toBe(200);- const afterOneOfTwo = await getRequestState(requestId);- expect(afterOneOfTwo.status).toBe("pending");- expect(afterOneOfTwo.grant).toBeUndefined();-- expect((await reviewAs(c, requestId)).statusCode).toBe(200);- const approved = await getRequestState(requestId);- expect(approved.status).toBe("approved");- expect(approved.privilege).toBeDefined();- });-- test("Each approving group member counts as one approval", async () => {- const db = getDb();- const secretPath = "/required-group";- const slug = `required-group-${alphaNumericNanoId(6).toLowerCase()}`;- const [group] = await db(TableName.Groups)- .insert({ orgId: seedData1.organization.id, name: slug, slug })- .returning("*");- groupIds.push(group.id);- await db(TableName.UserGroupMembership).insert([- { userId: a.userId, groupId: group.id, isPending: false },- { userId: b.userId, groupId: group.id, isPending: false }- ]);- const [groupOrgMembership, groupProjectMembership] = await db(TableName.Membership)- .insert([- {- actorGroupId: group.id,- scope: AccessScope.Organization,- scopeOrgId: seedData1.organization.id,- isActive: true- },- {- actorGroupId: group.id,- scope: AccessScope.Project,- scopeOrgId: seedData1.organization.id,- scopeProjectId: seedData1.project.id,- isActive: true- }- ])- .returning("*");- await db(TableName.MembershipRole).insert([- { membershipId: groupOrgMembership.id, role: OrgMembershipRole.Member },- { membershipId: groupProjectMembership.id, role: ProjectMembershipRole.Member }- ]);-- await createPolicyWithApprovers({- secretPath,- approvers: [{ type: ApproverType.Group, id: group.id }],- approvals: 1,- approvalsRequired: [{ stepNumber: 1, numberOfApprovals: 2 }]- });-- const requestId = await openRequest(secretPath);-- expect((await reviewAs(a, requestId)).statusCode).toBe(200);- expect((await getRequestState(requestId)).status).toBe("pending");-- expect((await reviewAs(b, requestId)).statusCode).toBe(200);- const state = await getRequestState(requestId);- 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", () => {- 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 refuses break-glass when self-approvals are off", 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(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("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");- });-});-+ describe("Additional privilege list on the global system", () => {+ const approvers: TApprover[] = [];+ const legacyRequestIds: string[] = [];+ let approver: TApprover;++ const listUserPrivileges = async () => {+ const membership = await getDb()(TableName.Membership)+ .where({ scope: AccessScope.Project, scopeProjectId: seedData1.project.id, actorUserId: seedData1.id })+ .first();+ const res = await testServer.inject({+ method: "GET",+ url: `/api/v1/user-project-additional-privilege?projectMembershipId=${membership?.id}`,+ headers: authHeaders()+ });+ expect(res.statusCode).toBe(200);+ return res.json().privileges as {+ id: string;+ isLinkedToAccessApproval: boolean;+ accessApprovalRequestId: string | null;+ policyApproverUserIds: 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);+ const legacyIds = legacyRequestIds.splice(0);++ if (legacyIds.length) {+ await db(TableName.AccessApprovalRequest).whereIn("id", legacyIds).del();+ }+ 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.AccessApprovalPolicyApprover).whereIn("policyId", globalIds).del();+ await db(TableName.AccessApprovalPolicy).whereIn("id", globalIds).del();+ 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 privilege granted on the global system is listed as managed by its request", async () => {+ const { requestId } = await createApprovedTemporaryRequest("/privilege-list-native");+ const { privilege } = await getRequestState(requestId);++ const listed = (await listUserPrivileges()).find((el) => el.id === privilege?.id);+ expect(listed?.isLinkedToAccessApproval).toBe(true);+ expect(listed?.accessApprovalRequestId).toBe(requestId);+ expect(listed?.policyApproverUserIds).toEqual([seedData1.id]);+ });++ test("A migrated privilege lists the global policy's approvers after they change", async () => {+ const db = getDb();+ const secretPath = "/privilege-list-migrated";+ const { policy, requestId } = await createApprovedTemporaryRequest(secretPath);+ const { privilege } = await getRequestState(requestId);++ const environment = await db(TableName.Environment)+ .where({ projectId: seedData1.project.id, slug: seedData1.environment.slug })+ .first();+ const legacyPolicy: TAccessApprovalPoliciesInsert & { id: string } = {+ id: policy.id,+ name: "privilege-list-migrated",+ secretPath,+ envId: environment?.id as string,+ deletedAt: new Date()+ };+ await db(TableName.AccessApprovalPolicy).insert(legacyPolicy);+ await db(TableName.AccessApprovalPolicyApprover).insert({ policyId: policy.id, approverUserId: seedData1.id });+ const legacyRequest: TAccessApprovalRequestsInsert & { id: string } = {+ id: requestId,+ policyId: policy.id,+ privilegeId: privilege?.id,+ requestedByUserId: seedData1.id,+ isTemporary: true,+ temporaryRange: "1h",+ permissions: JSON.stringify([]),+ status: "approved"+ };+ await db(TableName.AccessApprovalRequest).insert(legacyRequest);+ legacyRequestIds.push(requestId);++ const res = await patchPolicy(policy.id, {+ secretPath,+ approvers: [{ type: ApproverType.User, id: approver.userId }]+ });+ expect(res.statusCode).toBe(200);++ const listed = (await listUserPrivileges()).find((el) => el.id === privilege?.id);+ expect(listed?.isLinkedToAccessApproval).toBe(true);+ expect(listed?.accessApprovalRequestId).toBe(requestId);+ expect(listed?.policyApproverUserIds).toEqual([approver.userId]);+ });+ });diff --cc backend/e2e-test/routes/v1/access-approval-global-request-routing.spec.tsindex e9e205759b,4f3fd54ab2..57f8b89f3b--- a/backend/e2e-test/routes/v1/access-approval-global-request-routing.spec.ts+++ b/backend/e2e-test/routes/v1/access-approval-global-request-routing.spec.ts@@@ -247,4 -278,38 +248,31 @@@ describe("Access approval request routiawait fakeWebhookServer.stop();}}, 30_000);++ test("A migrated policy's legacy row does not take requests for the path it moved away from", async () => {+ const secretPath = "/routing-migrated";+ const created = await createGlobalPolicy({ name: "routing-migrated", secretPath });+ expect(created.statusCode).toBe(200);+ const policyId: string = created.json().approval.id;+ await createLegacyPolicy({ id: policyId, name: "routing-migrated", secretPath });++ const moved = await testServer.inject({+ method: "PATCH",+ url: `/api/v1/access-approvals/policies/${policyId}`,+ headers: {+ authorization: `Bearer ${jwtAuthToken}`+ },+ body: {+ secretPath: "/routing-migrated-moved",+ approvers: [{ type: ApproverType.User, id: seedData1.id }],+ approvals: 1+ }+ });+ expect(moved.statusCode).toBe(200);++ const res = await createAccessRequest(secretPath);++ expect(res.statusCode).toBe(404);+ expect(res.json().message).toContain("No policy in environment");+ });-- test("A request with no policy on either system is rejected", async () => {- const res = await createAccessRequest("/routing-none");-- expect(res.statusCode).toBe(404);- expect(res.json().message).toContain("No policy in environment");- });});diff --cc backend/e2e-test/routes/v1/secret-approval-global-guards.spec.tsindex afc490ed9f,d5d88fbfb7..bca968ab5b--- a/backend/e2e-test/routes/v1/secret-approval-global-guards.spec.ts+++ b/backend/e2e-test/routes/v1/secret-approval-global-guards.spec.ts@@@ -62,10 -216,247 +62,87 @@@ describe("Global approval system guardafterAll(async () => {const db = getDb();- await db(TableName.ApprovalRequests).whereIn("id", requestIds).del();- await db(TableName.ApprovalPolicies).whereIn("id", policyIds).del();await db(TableName.SecretApprovalRequest).whereIn("id", legacyRequestIds).del();await db(TableName.SecretApprovalPolicy).whereIn("id", legacyPolicyIds).del();- await db(TableName.Membership).whereIn("actorUserId", userIds).del();- await db(TableName.Membership).whereIn("actorGroupId", groupIds).del();- await db(TableName.Groups).whereIn("id", groupIds).del();- await db(TableName.Users).whereIn("id", userIds).del();- });-- test("a user who approves a global policy cannot be removed from the project until the policy is gone", async () => {- const { userId, username } = await createProjectUser("global-approver");- userIds.push(userId);- const policyId = await createGlobalPolicy("global-user-guard", "/global-user-guard", {- type: ApproverType.User,- id: userId- });- policyIds.push(policyId);-- const blocked = await removeProjectUser(username);- expect(blocked.statusCode).toBe(400);- expect(blocked.json().message).toBe(- "Cannot remove user from project: user is an approver in secret approval policy: global-user-guard"- );-- await deleteGlobalPolicy(policyId);-- const removed = await removeProjectUser(username);- expect(removed.statusCode).toBe(200);- });-- test("a group that approves a global policy cannot be removed from the project until the policy is gone", async () => {- const groupId = await createProjectGroup("global-approver-group");- groupIds.push(groupId);- const policyId = await createGlobalPolicy("global-group-guard", "/global-group-guard", {- type: ApproverType.Group,- id: groupId- });- policyIds.push(policyId);-- const blocked = await removeProjectGroup(groupId);- expect(blocked.statusCode).toBe(400);- expect(blocked.json().message).toBe(- "Cannot remove group from project: group is an approver in secret approval policy: global-group-guard"- );-- await deleteGlobalPolicy(policyId);-- const removed = await removeProjectGroup(groupId);- expect(removed.statusCode).toBe(200);- });-- test("a user saved on an open request cannot be removed after the policy approver changes", async () => {- const { userId, username } = await createProjectUser("open-request-approver");- userIds.push(userId);- const folderName = `open-request-user-${crypto.randomUUID().slice(0, 8)}`;- const folder = await createFolder({- workspaceId: projectId,- environmentSlug: envSlug,- secretPath: "/",- name: folderName,- authToken: jwtAuthToken- });- const policyId = await createGlobalPolicy("open-request-user-guard", `/${folderName}`, {- type: ApproverType.User,- id: userId- });- policyIds.push(policyId);- const { approvalRequestId, slug } = await seedOpenRequestWithApprover(folder.id, { userId });- requestIds.push(approvalRequestId);-- await replaceGlobalPolicyApprover(policyId, { type: ApproverType.User, id: seedData1.id });-- const blocked = await removeProjectUser(username);- expect(blocked.statusCode).toBe(400);- expect(blocked.json().message).toBe(- `Cannot remove user from project: user is an approver on open secret approval request: ${slug}`- );-- await getDb()(TableName.ApprovalRequests).where({ id: approvalRequestId }).update({ status: "close" });-- const removed = await removeProjectUser(username);- expect(removed.statusCode).toBe(200);-- await deleteFolder({- workspaceId: projectId,- environmentSlug: envSlug,- secretPath: "/",- id: folder.id,- authToken: jwtAuthToken- });- });-- test("a group saved on an open request cannot be removed after the policy approver changes", async () => {- const groupId = await createProjectGroup("open-request-approver-group");- groupIds.push(groupId);- const folderName = `open-request-group-${crypto.randomUUID().slice(0, 8)}`;- const folder = await createFolder({- workspaceId: projectId,- environmentSlug: envSlug,- secretPath: "/",- name: folderName,- authToken: jwtAuthToken- });- const policyId = await createGlobalPolicy("open-request-group-guard", `/${folderName}`, {- type: ApproverType.Group,- id: groupId- });- policyIds.push(policyId);- const { approvalRequestId, slug } = await seedOpenRequestWithApprover(folder.id, { groupId });- requestIds.push(approvalRequestId);-- await replaceGlobalPolicyApprover(policyId, { type: ApproverType.User, id: seedData1.id });-- const blocked = await removeProjectGroup(groupId);- expect(blocked.statusCode).toBe(400);- expect(blocked.json().message).toBe(- `Cannot remove group from project: group is an approver on open secret approval request: ${slug}`- );-- await getDb()(TableName.ApprovalRequests).where({ id: approvalRequestId }).update({ status: "close" });-- const removed = await removeProjectGroup(groupId);- expect(removed.statusCode).toBe(200);-- await deleteFolder({- workspaceId: projectId,- environmentSlug: envSlug,- secretPath: "/",- id: folder.id,- authToken: jwtAuthToken- });- });-- test("a folder with an open global change request cannot be deleted, directly or through its parent", async () => {- const { parentName, parent, child } = await createFolderTree();- const requestId = await seedOpenSecretChangeRequest(child.id);- requestIds.push(requestId);-- const expectedMessage = openRequestMessage(`/${parentName}/child`);-- const childBlocked = await deleteFolderRequest(child.id, `/${parentName}`);- expect(childBlocked.statusCode).toBe(400);- expect(childBlocked.json().message).toBe(expectedMessage);-- const parentBlocked = await deleteFolderRequest(parent.id, "/");- expect(parentBlocked.statusCode).toBe(400);- expect(parentBlocked.json().message).toBe(expectedMessage);-- expect(await getDb()(TableName.SecretFolder).where({ id: child.id }).first()).toBeDefined();-- await getDb()(TableName.ApprovalRequests).where({ id: requestId }).update({ status: "close" });-- await deleteFolder({- workspaceId: projectId,- environmentSlug: envSlug,- secretPath: "/",- id: parent.id,- authToken: jwtAuthToken,- forceDelete: true- });- expect(await getDb()(TableName.SecretFolder).where({ id: child.id }).first()).toBeUndefined();});+ test("a user who approves a migrated policy's legacy twin is removable once the global policy drops them", async () => {+ const { userId, username } = await createProjectUser("migrated-approver");+ userIds.push(userId);+ const policyId = await createGlobalPolicy("migrated-user-guard", "/migrated-user-guard", {+ type: ApproverType.User,+ id: userId+ });+ policyIds.push(policyId);+ await seedLegacySecretApprovalPolicy(getDb(), {+ id: policyId,+ projectId,+ environment: envSlug,+ secretPath: "/migrated-user-guard",+ name: "migrated-user-guard",+ approverUserId: userId+ });+ legacyPolicyIds.push(policyId);++ const blocked = await removeProjectUser(username);+ expect(blocked.statusCode).toBe(400);++ await replaceGlobalPolicyApprover(policyId, { type: ApproverType.User, id: seedData1.id });++ const removed = await removeProjectUser(username);+ expect(removed.statusCode).toBe(200);+ });++ test("a folder whose open legacy request was migrated is deletable once the global copy closes", async () => {+ const { parentName, parent, child } = await createFolderTree();+ const legacyPolicy = await seedLegacySecretApprovalPolicy(getDb(), {+ projectId,+ environment: envSlug,+ secretPath: `/${parentName}/child`,+ name: "migrated-folder-guard",+ approverUserId: seedData1.id+ });+ legacyPolicyIds.push(legacyPolicy.id);+ const requestId = await seedOpenLegacyRequest(child.id, legacyPolicy.id);+ legacyRequestIds.push(requestId);+ const globalTwin = {+ id: requestId,+ projectId,+ organizationId: orgId,+ policyId: null,+ requesterId: seedData1.id,+ requesterName: "test",+ requesterEmail: seedData1.email,+ type: ApprovalPolicyType.SecretChange,+ status: "open",+ currentStep: 1,+ requestData: JSON.stringify({})+ };+ await getDb()(TableName.ApprovalRequests).insert(globalTwin);+ await getDb()(TableName.SecretChangeRequests).insert({+ approvalRequestId: requestId,+ folderId: child.id,+ slug: `guard-${crypto.randomUUID().slice(0, 8)}`+ });+ requestIds.push(requestId);++ const blocked = await deleteFolderRequest(parent.id, "/");+ expect(blocked.statusCode).toBe(400);+ expect(blocked.json().message).toBe(openRequestMessage(`/${parentName}/child`));++ await getDb()(TableName.ApprovalRequests).where({ id: requestId }).update({ status: "close" });++ await deleteFolder({+ workspaceId: projectId,+ environmentSlug: envSlug,+ secretPath: "/",+ id: parent.id,+ authToken: jwtAuthToken,+ forceDelete: true+ });+ expect(await getDb()(TableName.SecretFolder).where({ id: child.id }).first()).toBeUndefined();+ });+test("a folder with an open legacy change request cannot be deleted until the request is closed", async () => {const { parentName, parent, child } = await createFolderTree();const legacyPolicy = await seedLegacySecretApprovalPolicy(getDb(), {