Skip to content

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

test(e2e): drop legacy access approval and change guard cases ported to the Go suite

varonixe430ce665da8
diff --git a/backend/e2e-test/routes/v1/access-approval-global-grant-revocation.spec.ts b/backend/e2e-test/routes/v1/access-approval-global-grant-revocation.spec.ts
deleted file mode 100644
index 1472c637c1..0000000000
--- a/backend/e2e-test/routes/v1/access-approval-global-grant-revocation.spec.ts
+++ /dev/null
@@ -1,196 +0,0 @@
-import jwt from "jsonwebtoken";
-import { Knex } from "knex";
-
-import { AccessScope, OrgMembershipRole, OrgMembershipStatus, ProjectMembershipRole, TableName } from "@app/db/schemas";
-import { seedData1 } from "@app/db/seed-data";
-import { ApproverType } from "@app/ee/services/access-approval-policy/access-approval-policy-types";
-import { getConfig, initEnvConfig } from "@app/lib/config/env";
-import { initLogger, logger } from "@app/lib/logger";
-import { alphaNumericNanoId } from "@app/lib/nanoid";
-import { AuthMethod, AuthTokenType } from "@app/services/auth/auth-type";
-
-const getDb = () => (globalThis as unknown as { testDb: Knex }).testDb;
-
-const SECRET_ACCESS_TYPE = "secret-access";
-
-type TMember = { userId: string; projectMembershipId: string; token: string };
-
-const adminHeaders = () => ({ authorization: `Bearer ${jwtAuthToken}` });
-
-const createProjectMember = async (): Promise<TMember> => {
- const db = getDb();
- const username = `grant-revocation-${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-grant-revocation",
- accessVersion: 1,
- refreshVersion: 1,
- lastUsed: new Date()
- } as never)
- .returning("*");
-
- return {
- userId: user.id,
- projectMembershipId: projectMembership.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 createGlobalPolicy = async (secretPath: string) => {
- const res = await testServer.inject({
- method: "POST",
- url: "/api/v1/access-approvals/policies",
- headers: adminHeaders(),
- body: {
- projectSlug: seedData1.project.slug,
- environment: seedData1.environment.slug,
- name: `grant-revocation-${secretPath.slice(1)}`,
- secretPath,
- approvers: [{ type: ApproverType.User, id: seedData1.id }],
- approvals: 1,
- allowedSelfApprovals: true
- }
- });
- expect(res.statusCode).toBe(200);
- const { approval }: { approval: { id: string } } = res.json();
- return approval;
-};
-
-const createApprovedRequest = async (secretPath: string, requesterHeaders: Record<string, string>) => {
- const createRes = await testServer.inject({
- method: "POST",
- url: `/api/v1/access-approvals/requests?projectSlug=${seedData1.project.slug}`,
- headers: requesterHeaders,
- body: {
- permissions: [
- ["read", "secrets", { environment: seedData1.environment.slug, secretPath: { $glob: secretPath } }]
- ],
- isTemporary: true,
- temporaryRange: "1h"
- }
- });
- expect(createRes.statusCode).toBe(200);
- const { approval }: { approval: { id: string } } = createRes.json();
-
- const reviewRes = await testServer.inject({
- method: "POST",
- url: `/api/v1/access-approvals/requests/${approval.id}/review`,
- headers: adminHeaders(),
- body: { status: "approved" }
- });
- expect(reviewRes.statusCode).toBe(200);
-
- const grant = await getDb()(TableName.ApprovalRequestGrants).where({ requestId: approval.id }).first();
- if (!grant) throw new Error(`Approved request '${approval.id}' has no grant`);
- expect(grant.status).toBe("active");
- return grant;
-};
-
-describe("Deleting an additional privilege revokes its approval grant", () => {
- const policyIds: string[] = [];
- const memberIds: string[] = [];
-
- beforeAll(async () => {
- initLogger();
- await initEnvConfig(testHsmService, testKmsRootConfigDAL, testSuperAdminDAL, logger);
- });
-
- afterEach(async () => {
- const db = getDb();
- const ids = policyIds.splice(0);
- const userIds = memberIds.splice(0);
-
- await db(TableName.AdditionalPrivilege)
- .whereIn("actorUserId", [seedData1.id, ...userIds])
- .whereLike("name", "requested-privilege-%")
- .del();
- await db(TableName.ApprovalRequestGrants)
- .where({ projectId: seedData1.project.id, type: SECRET_ACCESS_TYPE })
- .del();
- if (ids.length) {
- await db(TableName.ApprovalRequests).whereIn("policyId", ids).del();
- await db(TableName.ApprovalPolicies).whereIn("id", ids).del();
- }
- if (userIds.length) {
- 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("Removing a member from the project revokes only that member's grants", async () => {
- const db = getDb();
- const member = await createProjectMember();
- memberIds.push(member.userId);
-
- const memberPath = "/grant-revocation-member";
- policyIds.push((await createGlobalPolicy(memberPath)).id);
- const memberGrant = await createApprovedRequest(memberPath, { authorization: `Bearer ${member.token}` });
- const memberPrivilege = await db(TableName.AdditionalPrivilege).where({ grantId: memberGrant.id }).first();
- expect(memberPrivilege?.actorUserId).toBe(member.userId);
-
- const adminPath = "/grant-revocation-admin";
- policyIds.push((await createGlobalPolicy(adminPath)).id);
- const adminGrant = await createApprovedRequest(adminPath, adminHeaders());
-
- const removeRes = await testServer.inject({
- method: "DELETE",
- url: `/api/v1/projects/${seedData1.project.id}/memberships/${member.projectMembershipId}`,
- headers: adminHeaders()
- });
- expect(removeRes.statusCode).toBe(200);
-
- const privilegeAfter = await db(TableName.AdditionalPrivilege).where({ id: memberPrivilege?.id }).first();
- expect(privilegeAfter).toBeUndefined();
-
- const memberGrantAfter = await db(TableName.ApprovalRequestGrants).where({ id: memberGrant.id }).first();
- expect(memberGrantAfter?.status).toBe("revoked");
- expect(memberGrantAfter?.revokedAt).toBeTruthy();
- expect(memberGrantAfter?.revokedByUserId).toBeNull();
-
- const adminGrantAfter = await db(TableName.ApprovalRequestGrants).where({ id: adminGrant.id }).first();
- expect(adminGrantAfter?.status).toBe("active");
- expect(adminGrantAfter?.revokedAt).toBeNull();
- });
-});
diff --git 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
index 35f97b06e1..e31fa568cd 100644
--- 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
@@ -2,7 +2,7 @@ import { Knex } from "knex";
import { AccessScope, OrgMembershipRole, OrgMembershipStatus, ProjectMembershipRole, TableName } from "@app/db/schemas";
import { seedData1 } from "@app/db/seed-data";
-import { ApproverType, BypasserType } from "@app/ee/services/access-approval-policy/access-approval-policy-types";
+import { ApproverType } from "@app/ee/services/access-approval-policy/access-approval-policy-types";
import { alphaNumericNanoId } from "@app/lib/nanoid";
import { EnforcementLevel } from "@app/lib/types";
@@ -54,23 +54,17 @@ const createLegacyPolicy = async (dto: { name: string; secretPath: string }) =>
return policy;
};
-const createGlobalPolicy = async (dto: {
- name: string;
- secretPath: string;
- bypassers?: { type: BypasserType; id: string }[];
- environment?: string;
-}) => {
+const createGlobalPolicy = async (dto: { name: string; secretPath: string }) => {
const res = await testServer.inject({
method: "POST",
url: "/api/v1/access-approvals/policies",
headers: authHeaders(),
body: {
projectSlug: seedData1.project.slug,
- environment: dto.environment ?? seedData1.environment.slug,
+ environment: seedData1.environment.slug,
name: dto.name,
secretPath: dto.secretPath,
approvers: [{ type: ApproverType.User, id: seedData1.id }],
- bypassers: dto.bypassers,
approvals: 1
}
});
@@ -120,26 +114,6 @@ const countPolicies = () =>
headers: authHeaders()
});
-const environmentUrl = `/api/v1/workspace/${seedData1.project.id}/environments`;
-
-const createEnvironment = async (slug: string) => {
- const res = await testServer.inject({
- method: "POST",
- url: environmentUrl,
- headers: authHeaders(),
- body: { name: slug, slug }
- });
- expect(res.statusCode).toBe(200);
- return res.json().environment as { id: string; slug: string };
-};
-
-const deleteEnvironment = (envId: string) =>
- testServer.inject({
- method: "DELETE",
- url: `${environmentUrl}/${envId}?hardDelete=true`,
- headers: authHeaders()
- });
-
const expectNoLegacyRow = async (policyId: string) => {
const legacyRow = await getDb()(TableName.AccessApprovalPolicy).where({ id: policyId }).first();
expect(legacyRow).toBeUndefined();
@@ -167,56 +141,7 @@ describe("Access approval policy routing", () => {
}
});
- test("Updating a global policy writes the global tables and returns the legacy shape", async () => {
- const db = getDb();
- const env = await getSeedEnv();
- const policy = await createGlobalPolicy({ name: "policy-routing-update", secretPath: "/policy-routing-update" });
-
- const res = await patchPolicy(policy.id, {
- name: "policy-routing-update-renamed",
- secretPath: "/policy-routing-update-moved",
- approvers: [{ type: ApproverType.User, id: seedData1.id, sequence: 1 }],
- bypassers: [{ type: BypasserType.User, id: seedData1.id }],
- approvals: 1,
- allowedSelfApprovals: false
- });
-
- expect(res.statusCode).toBe(200);
- const { approval } = res.json();
- expect(approval.id).toBe(policy.id);
- expect(approval.name).toBe("policy-routing-update-renamed");
- expect(approval.secretPath).toBe("/policy-routing-update-moved");
- expect(approval.envId).toBe(env.id);
- expect(approval.environment.slug).toBe(seedData1.environment.slug);
- expect(approval.environments).toHaveLength(1);
- expect(approval.allowedSelfApprovals).toBe(false);
- expect(approval.approvals).toBe(1);
-
- const globalRow = await db(TableName.ApprovalPolicies).where({ id: policy.id }).first();
- expect(globalRow?.name).toBe("policy-routing-update-renamed");
- expect(globalRow?.type).toBe(SECRET_ACCESS_TYPE);
-
- const steps = await db(TableName.ApprovalPolicySteps).where({ policyId: policy.id });
- expect(steps).toHaveLength(1);
- expect(steps[0].requiredApprovals).toBe(1);
-
- const stepApprovers = await db(TableName.ApprovalPolicyStepApprovers).where({ policyStepId: steps[0].id });
- expect(stepApprovers).toHaveLength(1);
- expect(stepApprovers[0].userId).toBe(seedData1.id);
-
- const bypassers = await db(TableName.ApprovalPolicyBypassers).where({ policyId: policy.id });
- expect(bypassers).toHaveLength(1);
- expect(bypassers[0].userId).toBe(seedData1.id);
-
- const envRows = await db(TableName.ApprovalPolicySecretEnvironment).where({ policyId: policy.id });
- expect(envRows).toHaveLength(1);
- expect(envRows[0].secretPath).toBe("/policy-routing-update-moved");
- expect(envRows[0].envId).toBe(env.id);
-
- await expectNoLegacyRow(policy.id);
- });
-
- test("Updating a policy onto a path another policy covers is rejected on either system", async () => {
+ test("Updating a policy onto a path a policy on the other system covers is rejected", async () => {
const db = getDb();
const policy = await createGlobalPolicy({
name: "policy-routing-conflict",
@@ -235,44 +160,12 @@ describe("Access approval policy routing", () => {
expect(legacyConflict.statusCode).toBe(400);
expect(legacyConflict.json().message).toContain(`already exists in environment '${seedData1.environment.slug}'`);
- const globalConflict = await patchPolicy(policy.id, { secretPath: "/policy-routing-conflict-global" });
- expect(globalConflict.statusCode).toBe(400);
- expect(globalConflict.json().message).toContain(`already exists in environment '${seedData1.environment.slug}'`);
-
const legacyOntoGlobal = await patchPolicy(legacyPolicy.id, { secretPath: "/policy-routing-conflict-global" });
expect(legacyOntoGlobal.statusCode).toBe(400);
expect(legacyOntoGlobal.json().message).toContain(`already exists in environment '${seedData1.environment.slug}'`);
const 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("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 () => {
@@ -300,44 +193,6 @@ describe("Access approval policy routing", () => {
expect(countRes.json().count).toBe(approvals.length);
});
- test("Deleting a global policy removes it and its dependent rows", async () => {
- const db = getDb();
- const policy = await createGlobalPolicy({ name: "policy-routing-delete", secretPath: "/policy-routing-delete" });
-
- const res = await deletePolicy(policy.id);
-
- expect(res.statusCode).toBe(200);
- expect(res.json().approval.id).toBe(policy.id);
- expect(res.json().approval.secretPath).toBe("/policy-routing-delete");
-
- await expectNoGlobalRow(policy.id);
- expect(await db(TableName.ApprovalPolicySteps).where({ policyId: policy.id })).toHaveLength(0);
- expect(await db(TableName.ApprovalPolicyBypassers).where({ policyId: policy.id })).toHaveLength(0);
- expect(await db(TableName.ApprovalPolicySecretEnvironment).where({ policyId: policy.id })).toHaveLength(0);
- await expectNoLegacyRow(policy.id);
- });
-
- test("An environment a global policy covers cannot be deleted until the policy is removed", async () => {
- const db = getDb();
- const env = await createEnvironment("policy-routing-env-delete");
- const policy = await createGlobalPolicy({
- name: "policy-routing-env-delete",
- secretPath: "/policy-routing-env-delete",
- environment: env.slug
- });
-
- const blocked = await deleteEnvironment(env.id);
- expect(blocked.statusCode).toBe(400);
- expect(blocked.json().message).toBe("Environment is in use by an access approval policy");
- expect(await db(TableName.ApprovalPolicySecretEnvironment).where({ policyId: policy.id })).toHaveLength(1);
-
- expect((await deletePolicy(policy.id)).statusCode).toBe(200);
-
- const deleted = await deleteEnvironment(env.id);
- expect(deleted.statusCode).toBe(200);
- expect(await db(TableName.Environment).where({ id: env.id }).first()).toBeUndefined();
- });
-
test("A legacy policy keeps being served from the legacy tables", async () => {
const db = getDb();
const policy = await createLegacyPolicy({ name: "policy-routing-legacy", secretPath: "/policy-routing-legacy" });
@@ -457,159 +312,11 @@ describe("Access approval policy required approvals per step", () => {
(step) => step.requiredApprovals
);
- test("Updating without approvalsRequired takes approvals for the first step", async () => {
- const policy = await createGlobalPolicy({ name: "policy-routing-required-reset", secretPath: "/required-reset" });
- const approvers = [
- { type: ApproverType.User, id: seedData1.id, sequence: 1 },
- { type: ApproverType.User, id: otherApproverId, sequence: 1 }
- ];
-
- const withEntry = await patchPolicy(policy.id, {
- approvers,
- approvals: 2,
- approvalsRequired: [{ stepNumber: 1, numberOfApprovals: 2 }]
- });
- expect(withEntry.statusCode).toBe(200);
- expect(await getStepRequirements(policy.id)).toEqual([2]);
-
- const withoutEntry = await patchPolicy(policy.id, { approvers, approvals: 1 });
- expect(withoutEntry.statusCode).toBe(200);
- expect(await getStepRequirements(policy.id)).toEqual([1]);
-
- const getRes = await getPolicy(policy.id);
- expect(getRes.statusCode).toBe(200);
- expect(
- getRes.json().approval.approvers.map((approver: { approvalsRequired: number }) => approver.approvalsRequired)
- ).toEqual([1, 1]);
- });
-
- const createPolicyRaw = (body: Record<string, unknown>) =>
- testServer.inject({
- method: "POST",
- url: "/api/v1/access-approvals/policies",
- headers: authHeaders(),
- body: {
- projectSlug: seedData1.project.slug,
- environment: seedData1.environment.slug,
- approvals: 1,
- ...body
- }
- });
-
const approverViews = (approvers: { id: string; sequence: number; approvalsRequired: number }[]) =>
approvers
.map(({ id, sequence, approvalsRequired }) => ({ id, sequence, approvalsRequired }))
.sort((a, b) => a.sequence - b.sequence || a.id.localeCompare(b.id));
- test("A user who approves in two steps is returned once per step", async () => {
- const res = await createPolicyRaw({
- name: "policy-routing-user-in-two-steps",
- secretPath: "/user-in-two-steps",
- approvers: [
- { type: ApproverType.User, id: seedData1.id, sequence: 1 },
- { type: ApproverType.User, id: otherApproverId, sequence: 1 },
- { type: ApproverType.User, id: otherApproverId, sequence: 2 }
- ],
- approvalsRequired: [
- { stepNumber: 1, numberOfApprovals: 2 },
- { stepNumber: 2, numberOfApprovals: 1 }
- ]
- });
- expect(res.statusCode).toBe(200);
- const policyId = res.json().approval.id as string;
- globalPolicyIds.push(policyId);
-
- expect(await getStepRequirements(policyId)).toEqual([2, 1]);
-
- const getRes = await getPolicy(policyId);
- expect(getRes.statusCode).toBe(200);
- expect(approverViews(getRes.json().approval.approvers)).toEqual(
- approverViews([
- { id: seedData1.id, sequence: 1, approvalsRequired: 2 },
- { id: otherApproverId, sequence: 1, approvalsRequired: 2 },
- { id: otherApproverId, sequence: 2, approvalsRequired: 1 }
- ])
- );
- });
-
- test("Creating a step that requires more approvals than it has approvers is rejected", async () => {
- const name = "policy-routing-step-too-small";
- const res = await createPolicyRaw({
- name,
- secretPath: "/step-too-small",
- approvers: [
- { type: ApproverType.User, id: seedData1.id, sequence: 1 },
- { type: ApproverType.User, id: otherApproverId, sequence: 2 }
- ],
- approvalsRequired: [
- { stepNumber: 1, numberOfApprovals: 1 },
- { stepNumber: 2, numberOfApprovals: 2 }
- ]
- });
-
- expect(res.statusCode).toBe(400);
- expect(res.json().message).toContain("Step 2 requires 2 approvals but only has 1 approver");
- expect(await getDb()(TableName.ApprovalPolicies).where({ name }).first()).toBeUndefined();
- });
-
- test("approvals reads back as written when no approvalsRequired is sent", async () => {
- const approvers = [
- { type: ApproverType.User, id: seedData1.id, sequence: 1 },
- { type: ApproverType.User, id: otherApproverId, sequence: 1 }
- ];
- const createRes = await createPolicyRaw({
- name: "policy-routing-approvals-round-trip",
- secretPath: "/approvals-round-trip",
- approvers,
- approvals: 2
- });
- expect(createRes.statusCode).toBe(200);
- const policyId = createRes.json().approval.id as string;
- globalPolicyIds.push(policyId);
-
- expect(createRes.json().approval.approvals).toBe(2);
- expect(await getStepRequirements(policyId)).toEqual([2]);
- expect((await getPolicy(policyId)).json().approval.approvals).toBe(2);
-
- const withoutApprovals = await patchPolicy(policyId, { approvers, approvals: undefined });
- expect(withoutApprovals.statusCode).toBe(200);
- expect(withoutApprovals.json().approval.approvals).toBe(2);
- expect(await getStepRequirements(policyId)).toEqual([2]);
-
- const lowered = await patchPolicy(policyId, { approvers, approvals: 1 });
- expect(lowered.statusCode).toBe(200);
- expect((await getPolicy(policyId)).json().approval.approvals).toBe(1);
- expect(await getStepRequirements(policyId)).toEqual([1]);
- });
-
- test("Creating with more approvals than the first step's user approvers is rejected", async () => {
- const name = "policy-routing-approvals-too-many";
- const res = await createPolicyRaw({
- name,
- secretPath: "/approvals-too-many",
- approvers: [{ type: ApproverType.User, id: seedData1.id, sequence: 1 }],
- approvals: 2
- });
-
- expect(res.statusCode).toBe(400);
- expect(res.json().message).toContain("Step 1 requires 2 approvals but only has 1 approver");
- expect(await getDb()(TableName.ApprovalPolicies).where({ name }).first()).toBeUndefined();
- });
-
- test("Updating a policy into a step with too few approvers is rejected and leaves it untouched", async () => {
- const policy = await createGlobalPolicy({ name: "policy-routing-step-too-small-update", secretPath: "/too-small" });
-
- const res = await patchPolicy(policy.id, {
- approvers: [{ type: ApproverType.User, id: seedData1.id, sequence: 1 }],
- approvals: 2,
- approvalsRequired: [{ stepNumber: 1, numberOfApprovals: 2 }]
- });
-
- expect(res.statusCode).toBe(400);
- expect(res.json().message).toContain("Step 1 requires 2 approvals but only has 1 approver");
- expect(await getStepRequirements(policy.id)).toEqual([1]);
- });
-
test("A legacy policy also returns a user once per step", async () => {
const legacyPolicy = await createLegacyPolicy({
name: "policy-routing-legacy-user-in-two-steps",
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.ts
index 4f84b8441a..040604e1b0 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
@@ -1,20 +1,14 @@
-import jwt from "jsonwebtoken";
import { Knex } from "knex";
-import { AccessScope, OrgMembershipRole, OrgMembershipStatus, ProjectMembershipRole, TableName } from "@app/db/schemas";
+import { TableName } from "@app/db/schemas";
import { seedData1 } from "@app/db/seed-data";
import { ApproverType } from "@app/ee/services/access-approval-policy/access-approval-policy-types";
-import { getConfig, initEnvConfig } from "@app/lib/config/env";
-import { initLogger, logger } from "@app/lib/logger";
-import { alphaNumericNanoId } from "@app/lib/nanoid";
-import { AuthMethod, AuthTokenType } from "@app/services/auth/auth-type";
const getDb = () => (globalThis as unknown as { testDb: Knex }).testDb;
const SECRET_ACCESS_TYPE = "secret-access";
const globalPolicyIds: string[] = [];
-const policylessRequestIds: string[] = [];
const authHeaders = () => ({ authorization: `Bearer ${jwtAuthToken}` });
@@ -62,56 +56,11 @@ const reviewAccessRequest = (requestId: string, body: Record<string, unknown>) =
body
});
-const revokeAccessRequest = (requestId: string) =>
- testServer.inject({
- method: "POST",
- url: `/api/v1/access-approvals/requests/${requestId}/revoke`,
- headers: authHeaders()
- });
-
-const listAccessRequests = () =>
- testServer.inject({
- method: "GET",
- url: `/api/v1/access-approvals/requests?projectSlug=${seedData1.project.slug}`,
- headers: authHeaders()
- });
-
-const countAccessRequests = () =>
- testServer.inject({
- method: "GET",
- url: `/api/v1/access-approvals/requests/count?projectSlug=${seedData1.project.slug}`,
- headers: authHeaders()
- });
-
-const deletePolicy = (policyId: string) =>
- testServer.inject({
- method: "DELETE",
- url: `/api/v1/access-approvals/policies/${policyId}`,
- headers: authHeaders()
- });
-
-const createApprovedTemporaryRequest = async (secretPath: string) => {
- const policy = await createGlobalPolicy({ name: `lifecycle-${secretPath.slice(1)}`, secretPath });
-
- const createRes = await createAccessRequest(secretPath, { isTemporary: true, temporaryRange: "1h" });
- expect(createRes.statusCode).toBe(200);
- const requestId = createRes.json().approval.id as string;
-
- const reviewRes = await reviewAccessRequest(requestId, { status: "approved" });
- expect(reviewRes.statusCode).toBe(200);
-
- return { policy, requestId };
-};
-
describe("Access approval request lifecycle on the global system", () => {
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();
@@ -119,322 +68,6 @@ describe("Access approval request lifecycle on the global system", () => {
await db(TableName.ApprovalRequests).whereIn("policyId", globalIds).del();
await db(TableName.ApprovalPolicies).whereIn("id", globalIds).del();
}
- const requestIds = policylessRequestIds.splice(0);
- if (requestIds.length) {
- await db(TableName.ApprovalRequests).whereIn("id", requestIds).del();
- }
- });
-
- test("Approving a request creates a grant and a privilege that references it", async () => {
- const db = getDb();
- const { policy, requestId } = await createApprovedTemporaryRequest("/lifecycle-approve");
-
- const approvals = await db(TableName.ApprovalRequestApprovals)
- .join(
- TableName.ApprovalRequestSteps,
- `${TableName.ApprovalRequestApprovals}.stepId`,
- `${TableName.ApprovalRequestSteps}.id`
- )
- .where(`${TableName.ApprovalRequestSteps}.requestId`, requestId)
- .select(`${TableName.ApprovalRequestApprovals}.decision`);
- expect(approvals).toHaveLength(1);
- expect(approvals[0].decision).toBe("approved");
-
- const request = await db(TableName.ApprovalRequests).where({ id: requestId }).first();
- expect(request?.status).toBe("approved");
- expect(request?.policyId).toBe(policy.id);
-
- const grant = await db(TableName.ApprovalRequestGrants).where({ requestId }).first();
- expect(grant?.status).toBe("active");
- expect(grant?.type).toBe(SECRET_ACCESS_TYPE);
- expect(grant?.granteeUserId).toBe(seedData1.id);
- expect(grant?.expiresAt).toBeTruthy();
-
- const privilege = await db(TableName.AdditionalPrivilege).where({ grantId: grant?.id }).first();
- expect(privilege).toBeDefined();
- expect(privilege?.actorUserId).toBe(seedData1.id);
- expect(privilege?.projectId).toBe(seedData1.project.id);
- expect(privilege?.isTemporary).toBe(true);
- expect(privilege?.temporaryRange).toBe("1h");
-
- const legacyRows = await db(TableName.AccessApprovalRequest).where({ id: requestId });
- expect(legacyRows).toHaveLength(0);
- });
-
- test("A privilege granted through an approval request cannot be edited", async () => {
- const db = getDb();
- const { requestId } = await createApprovedTemporaryRequest("/lifecycle-edit-guard");
-
- const grant = await db(TableName.ApprovalRequestGrants).where({ requestId }).first();
- const privilege = await db(TableName.AdditionalPrivilege).where({ grantId: grant?.id }).first();
- expect(privilege).toBeDefined();
-
- const res = await testServer.inject({
- method: "PATCH",
- url: `/api/v1/user-project-additional-privilege/${privilege?.id}`,
- headers: authHeaders(),
- body: { isTemporary: false }
- });
- expect(res.statusCode).toBe(400);
- expect(res.json().message).toBe("Cannot update a privilege that was granted through an access approval request");
-
- const privilegeAfter = await db(TableName.AdditionalPrivilege).where({ id: privilege?.id }).first();
- expect(privilegeAfter?.isTemporary).toBe(true);
- });
-
- test("Revoking an approved request revokes the grant and deletes the privilege", async () => {
- const db = getDb();
- const { requestId } = await createApprovedTemporaryRequest("/lifecycle-revoke");
-
- const grantBefore = await db(TableName.ApprovalRequestGrants).where({ requestId }).first();
- expect(grantBefore?.status).toBe("active");
- const privilegeBefore = await db(TableName.AdditionalPrivilege).where({ grantId: grantBefore?.id }).first();
- expect(privilegeBefore).toBeDefined();
-
- const revokeRes = await revokeAccessRequest(requestId);
- expect(revokeRes.statusCode).toBe(200);
- const { request } = revokeRes.json();
- expect(request.id).toBe(requestId);
- expect(request.status).toBe("revoked");
- expect(request.revokedByUserId).toBe(seedData1.id);
- expect(request.revokedAt).toBeTruthy();
- expect(request.privilegeId).toBeNull();
-
- const grantAfter = await db(TableName.ApprovalRequestGrants).where({ id: grantBefore?.id }).first();
- expect(grantAfter?.status).toBe("revoked");
- expect(grantAfter?.revokedAt).toBeTruthy();
- expect(grantAfter?.revokedByUserId).toBe(seedData1.id);
-
- const privilegeAfter = await db(TableName.AdditionalPrivilege).where({ id: privilegeBefore?.id }).first();
- expect(privilegeAfter).toBeUndefined();
-
- const secondRevoke = await revokeAccessRequest(requestId);
- expect(secondRevoke.statusCode).toBe(400);
- expect(secondRevoke.json().message).toBe("Only approved requests can be revoked");
- });
-
- test("Deleting a policy keeps its requests listed and the count in step", async () => {
- const { policy, requestId: approvedId } = await createApprovedTemporaryRequest("/lifecycle-deleted-policy");
- const pendingRes = await createAccessRequest("/lifecycle-deleted-policy", { isTemporary: false });
- expect(pendingRes.statusCode).toBe(200);
- const pendingId = pendingRes.json().approval.id as string;
- policylessRequestIds.push(approvedId, pendingId);
-
- const countBefore = (await countAccessRequests()).json();
-
- expect((await deletePolicy(policy.id)).statusCode).toBe(200);
-
- const listRes = await listAccessRequests();
- expect(listRes.statusCode).toBe(200);
- const { requests } = listRes.json();
-
- const approved = requests.find((request: { id: string }) => request.id === approvedId);
- expect(approved).toBeDefined();
- expect(approved.policyId).toBeNull();
- expect(approved.policy.id).toBeNull();
- expect(approved.policy.deletedAt).toBeTruthy();
- expect(approved.policy.secretPath).toBe("/lifecycle-deleted-policy");
- expect(approved.environmentName).toBe(seedData1.environment.slug);
- expect(approved.status).toBe("revoked");
- expect(approved.privilege).toBeNull();
-
- const pending = requests.find((request: { id: string }) => request.id === pendingId);
- expect(pending).toBeDefined();
- expect(pending.policyId).toBeNull();
- expect(pending.policy.deletedAt).toBeTruthy();
- expect(pending.status).toBe("pending");
-
- const countAfter = (await countAccessRequests()).json();
- expect(countAfter.pendingCount).toBe(countBefore.pendingCount - 1);
- expect(countAfter.finalizedCount).toBe(countBefore.finalizedCount + 1);
-
- const reviewRes = await reviewAccessRequest(pendingId, { status: "approved" });
- expect(reviewRes.statusCode).toBe(400);
- expect(reviewRes.json().message).toBe("The policy associated with this access request has been deleted.");
- });
-
- test("Rejecting a request creates no grant and no privilege", async () => {
- const db = getDb();
- const secretPath = "/lifecycle-reject";
- await createGlobalPolicy({ name: "lifecycle-reject", secretPath });
-
- const createRes = await createAccessRequest(secretPath);
- expect(createRes.statusCode).toBe(200);
- const requestId = createRes.json().approval.id as string;
-
- const reviewRes = await reviewAccessRequest(requestId, { status: "rejected" });
- expect(reviewRes.statusCode).toBe(200);
- expect(reviewRes.json().review.status).toBe("rejected");
-
- const request = await db(TableName.ApprovalRequests).where({ id: requestId }).first();
- expect(request?.status).toBe("rejected");
-
- const grants = await db(TableName.ApprovalRequestGrants).where({ requestId });
- expect(grants).toHaveLength(0);
-
- const privileges = await db(TableName.AdditionalPrivilege)
- .where({ actorUserId: seedData1.id })
- .whereLike("name", "requested-privilege-%");
- expect(privileges).toHaveLength(0);
- });
-
- test("Global requests are served by the list and count endpoints", async () => {
- const { policy, requestId: approvedId } = await createApprovedTemporaryRequest("/lifecycle-list");
-
- const pendingPath = "/lifecycle-list-pending";
- await createGlobalPolicy({ name: "lifecycle-list-pending", secretPath: pendingPath });
- const pendingRes = await createAccessRequest(pendingPath);
- expect(pendingRes.statusCode).toBe(200);
- const pendingId = pendingRes.json().approval.id as string;
-
- const listRes = await listAccessRequests();
- expect(listRes.statusCode).toBe(200);
- const { requests } = listRes.json();
-
- const approved = requests.find((request: { id: string }) => request.id === approvedId);
- expect(approved).toBeDefined();
- expect(approved.policyId).toBe(policy.id);
- expect(approved.policy.id).toBe(policy.id);
- expect(approved.policy.secretPath).toBe("/lifecycle-list");
- expect(approved.environmentName).toBe(seedData1.environment.slug);
- expect(approved.isApproved).toBe(true);
- expect(approved.isTemporary).toBe(true);
- expect(approved.privilege).not.toBeNull();
- expect(approved.privilege.isTemporary).toBe(true);
- expect(approved.reviewers).toEqual([expect.objectContaining({ userId: seedData1.id, status: "approved" })]);
- expect(approved.policy.approvers).toEqual([expect.objectContaining({ userId: seedData1.id, sequence: 1 })]);
- expect(approved.requestedByUser.userId).toBe(seedData1.id);
- expect(approved.approvedByUser.userId).toBe(seedData1.id);
-
- const pending = requests.find((request: { id: string }) => request.id === pendingId);
- expect(pending).toBeDefined();
- expect(pending.status).toBe("pending");
- expect(pending.isApproved).toBe(false);
- expect(pending.privilege).toBeNull();
- expect(pending.reviewers).toEqual([]);
-
- const countRes = await countAccessRequests();
- expect(countRes.statusCode).toBe(200);
- expect(countRes.json().pendingCount).toBeGreaterThanOrEqual(1);
- expect(countRes.json().finalizedCount).toBeGreaterThanOrEqual(1);
-
- const revokeRes = await revokeAccessRequest(approvedId);
- expect(revokeRes.statusCode).toBe(200);
-
- const afterRevoke = (await listAccessRequests())
- .json()
- .requests.find((request: { id: string }) => request.id === approvedId);
- expect(afterRevoke.status).toBe("revoked");
- expect(afterRevoke.privilege).toBeNull();
- expect(afterRevoke.revokedByUser.userId).toBe(seedData1.id);
- });
-
- test("A duplicate pending request, an edit, and a bypass are rejected", async () => {
- const secretPath = "/lifecycle-guards";
- await createGlobalPolicy({ name: "lifecycle-guards", secretPath });
-
- const createRes = await createAccessRequest(secretPath);
- expect(createRes.statusCode).toBe(200);
- const requestId = createRes.json().approval.id as string;
-
- const duplicateRes = await createAccessRequest(secretPath);
- expect(duplicateRes.statusCode).toBe(400);
- expect(duplicateRes.json().message).toBe("You already have a pending access request with the same criteria");
-
- const patchRes = await testServer.inject({
- method: "PATCH",
- url: `/api/v1/access-approvals/requests/${requestId}`,
- headers: authHeaders(),
- body: { temporaryRange: "30m", editNote: "shorter" }
- });
- expect(patchRes.statusCode).toBe(400);
- 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(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 () => {
- const db = getDb();
- const secretPath = "/lifecycle-max-time";
- const policy = await createGlobalPolicy({ name: "lifecycle-max-time", secretPath }, { maxTimePeriod: "1h" });
-
- const storedPolicy = await db(TableName.ApprovalPolicies).where({ id: policy.id }).first();
- expect(storedPolicy?.maxRequestTtl).toBeNull();
- expect(storedPolicy?.constraints).toEqual(
- expect.objectContaining({ constraints: expect.objectContaining({ maxTimePeriod: "1h" }) })
- );
-
- const tooLongRes = await createAccessRequest(secretPath, { isTemporary: true, temporaryRange: "2h" });
- expect(tooLongRes.statusCode).toBe(400);
- expect(tooLongRes.json().message).toBe("Requested access time range is limited to 1h by policy");
-
- const permanentRes = await createAccessRequest(secretPath);
- expect(permanentRes.statusCode).toBe(400);
- expect(permanentRes.json().message).toBe("Requested access time range is limited to 1h by policy");
-
- const updateRes = await testServer.inject({
- method: "PATCH",
- url: `/api/v1/access-approvals/policies/${policy.id}`,
- headers: authHeaders(),
- body: { name: "lifecycle-max-time-renamed", approvers: [{ type: ApproverType.User, id: seedData1.id }] }
- });
- expect(updateRes.statusCode).toBe(200);
-
- const getRes = await testServer.inject({
- method: "GET",
- url: `/api/v1/access-approvals/policies/${policy.id}`,
- headers: authHeaders()
- });
- expect(getRes.statusCode).toBe(200);
- expect(getRes.json().approval.maxTimePeriod).toBe("1h");
-
- const withinRes = await createAccessRequest(secretPath, { isTemporary: true, temporaryRange: "30m" });
- expect(withinRes.statusCode).toBe(200);
- });
-
- test("Asking again for access the user already holds is rejected", async () => {
- const secretPath = "/lifecycle-active-grant";
- await createApprovedTemporaryRequest(secretPath);
-
- const repeatRes = await createAccessRequest(secretPath, { isTemporary: true, temporaryRange: "1h" });
- expect(repeatRes.statusCode).toBe(400);
- expect(repeatRes.json().message).toBe("You already have an active privilege with the same criteria");
- });
-
- test("A request with a range is granted temporary access even when isTemporary is false", async () => {
- const db = getDb();
- const secretPath = "/lifecycle-range-without-flag";
- await createGlobalPolicy({ name: "lifecycle-range-without-flag", secretPath });
-
- const createRes = await createAccessRequest(secretPath, { isTemporary: false, temporaryRange: "1h" });
- expect(createRes.statusCode).toBe(200);
- const requestId = createRes.json().approval.id as string;
-
- const reviewRes = await reviewAccessRequest(requestId, { status: "approved" });
- expect(reviewRes.statusCode).toBe(200);
-
- const grant = await db(TableName.ApprovalRequestGrants).where({ requestId }).first();
- expect(grant?.expiresAt).toBeTruthy();
-
- const privilege = await db(TableName.AdditionalPrivilege).where({ grantId: grant?.id }).first();
- expect(privilege?.isTemporary).toBe(true);
- expect(privilege?.temporaryRange).toBe("1h");
- expect(privilege?.temporaryAccessEndTime).toBeTruthy();
- });
-
- test("A temporary request without a range is rejected and saves nothing", async () => {
- const db = getDb();
- const secretPath = "/lifecycle-missing-range";
- const policy = await createGlobalPolicy({ name: "lifecycle-missing-range", secretPath });
-
- const createRes = await createAccessRequest(secretPath, { isTemporary: true });
- expect(createRes.statusCode).toBe(400);
- expect(createRes.json().message).toBe("A temporary range is required for temporary requests");
-
- const requests = await db(TableName.ApprovalRequests).where({ policyId: policy.id });
- expect(requests).toHaveLength(0);
});
test("An expired request cannot be approved or rejected and is marked expired", async () => {
@@ -465,698 +98,4 @@ describe("Access approval request lifecycle on the global system", () => {
expect(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/*");
-
- await getDb()(TableName.ApprovalPolicySecretEnvironment)
- .where({ policyId: policy.id })
- .update({ secretPath: "/other" });
-
- const rejectRes = await reviewAccessRequest(requestId, { status: "rejected" });
- expect(rejectRes.statusCode).toBe(200);
- expect(rejectRes.json().review.status).toBe("rejected");
-
- 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);
- });
-});
-
-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");
- });
});
diff --git 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
index 2c279ddc78..e9e205759b 100644
--- 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
@@ -162,36 +162,6 @@ describe("Access approval request routing", () => {
expect(rows[0].id).toBe(approval.id);
});
- test("A request against a global policy is routed to the global system", async () => {
- const db = getDb();
- const secretPath = "/routing-global";
- const createRes = await createGlobalPolicy({ name: "routing-global", secretPath });
- expect(createRes.statusCode).toBe(200);
-
- const globalPolicyRow = await db(TableName.ApprovalPolicies).where({ id: createRes.json().approval.id }).first();
- expect(globalPolicyRow?.type).toBe("secret-access");
-
- const res = await createAccessRequest(secretPath);
-
- expect(res.statusCode).toBe(200);
- const { approval } = res.json();
- expect(approval.policyId).toBe(globalPolicyRow?.id);
- expect(approval.status).toBe("pending");
-
- const globalRequest = await db(TableName.ApprovalRequests).where({ id: approval.id }).first();
- expect(globalRequest?.type).toBe(SECRET_ACCESS_TYPE);
- expect(globalRequest?.policyId).toBe(globalPolicyRow?.id);
- expect(globalRequest?.requesterId).toBe(seedData1.id);
-
- const steps = await db(TableName.ApprovalRequestSteps).where({ requestId: approval.id });
- expect(steps).toHaveLength(1);
-
- const legacyRows = await db(TableName.AccessApprovalRequest)
- .whereRaw(`"permissions"::text like ?`, [`%${secretPath}%`])
- .select("id");
- expect(legacyRows).toHaveLength(0);
- });
-
test("Review and revoke of a legacy request keep running on the legacy system", async () => {
const db = getDb();
const secretPath = "/routing-legacy-lifecycle";
@@ -277,11 +247,4 @@ describe("Access approval request routing", () => {
await fakeWebhookServer.stop();
}
}, 30_000);
-
- 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 --git a/backend/e2e-test/routes/v1/access-approval-policy.spec.ts b/backend/e2e-test/routes/v1/access-approval-policy.spec.ts
index 3b7b8e7a96..51753afaab 100644
--- a/backend/e2e-test/routes/v1/access-approval-policy.spec.ts
+++ b/backend/e2e-test/routes/v1/access-approval-policy.spec.ts
@@ -1,5 +1,3 @@
-import crypto from "node:crypto";
-
import jwt from "jsonwebtoken";
import { Knex } from "knex";
@@ -62,74 +60,6 @@ const createPolicy = async (dto: {
return approval;
};
-// Returns the raw response because callers assert on rejections too, so only
-// register a policy when one was actually created.
-const createPolicyWithGroupApprover = async (dto: { name: string; groupId: string; secretPath: string }) => {
- const res = await testServer.inject({
- method: "POST",
- url: `/api/v1/access-approvals/policies`,
- headers: {
- authorization: `Bearer ${jwtAuthToken}`
- },
- body: {
- projectSlug: seedData1.project.slug,
- environment: seedData1.environment.slug,
- name: dto.name,
- secretPath: dto.secretPath,
- approvers: [{ id: dto.groupId, type: ApproverType.Group }],
- approvals: 1
- }
- });
-
- if (res.statusCode === 200) {
- createdPolicyIds.push(res.json().approval.id);
- }
- return res;
-};
-
-const seedGroup = async (db: Knex, dto: { slug: string; addToProject: boolean }) => {
- const [group] = await db(TableName.Groups)
- .insert({
- orgId: seedData1.organization.id,
- name: dto.slug,
- slug: dto.slug
- })
- .returning("*");
-
- if (dto.addToProject) {
- const [membership] = await db(TableName.Membership)
- .insert({
- actorGroupId: group.id,
- scope: AccessScope.Project,
- scopeOrgId: seedData1.organization.id,
- scopeProjectId: seedData1.project.id,
- isActive: true
- })
- .returning("*");
-
- await db(TableName.MembershipRole).insert({
- membershipId: membership.id,
- role: "member"
- });
- }
-
- return group;
-};
-
-const cleanupGroup = async (db: Knex, groupId: string) => {
- const memberships = await db(TableName.Membership).where({ actorGroupId: groupId }).select("id");
- if (memberships.length) {
- await db(TableName.MembershipRole)
- .whereIn(
- "membershipId",
- memberships.map((m) => m.id)
- )
- .del();
- await db(TableName.Membership).where({ actorGroupId: groupId }).del();
- }
- await db(TableName.Groups).where({ id: groupId }).del();
-};
-
type TProjectMember = { userId: string; token: string };
const seedProjectMember = async (db: Knex): Promise<TProjectMember> => {
@@ -227,84 +157,6 @@ describe("Access approval policy router", async () => {
await Promise.all(ids.map(deletePolicy));
});
- test("Create policy", async () => {
- const policy = await createPolicy({
- secretPath: "/",
- approvals: 1,
- approvers: [{ id: seedData1.id, type: ApproverType.User }],
- name: "test-access-policy"
- });
-
- expect(policy.name).toBe("test-access-policy");
- });
-
- test("Create policy fails when group approver is not a member of the project", async () => {
- // A group id that has no membership row for the project must be rejected.
- const nonMemberGroupId = crypto.randomUUID();
-
- const res = await createPolicyWithGroupApprover({
- name: "test-access-policy-group-not-in-project",
- groupId: nonMemberGroupId,
- secretPath: "/group-not-member"
- });
-
- expect(res.statusCode).toBe(400);
- expect(res.json().message).toContain("Some groups are not members of the project");
- expect(res.json().message).toContain(nonMemberGroupId);
- });
-
- test("Create policy succeeds when group approver is a member of the project", async () => {
- const db = getDb();
- const group = await seedGroup(db, { slug: "aap-group-in-project", addToProject: true });
-
- try {
- const res = await createPolicyWithGroupApprover({
- name: "test-access-policy-group-in-project",
- groupId: group.id,
- secretPath: "/group-member"
- });
-
- expect(res.statusCode).toBe(200);
- expect(res.json().approval.name).toBe("test-access-policy-group-in-project");
- } finally {
- await cleanupGroup(db, group.id);
- }
- });
-
- test("Update policy fails when group approver is not a member of the project", async () => {
- const db = getDb();
- const group = await seedGroup(db, { slug: "aap-group-update", addToProject: true });
- const nonMemberGroupId = crypto.randomUUID();
-
- try {
- const createRes = await createPolicyWithGroupApprover({
- name: "test-access-policy-update",
- groupId: group.id,
- secretPath: "/group-update"
- });
- expect(createRes.statusCode).toBe(200);
- const policyId = createRes.json().approval.id;
-
- const updateRes = await testServer.inject({
- method: "PATCH",
- url: `/api/v1/access-approvals/policies/${policyId}`,
- headers: {
- authorization: `Bearer ${jwtAuthToken}`
- },
- body: {
- approvers: [{ id: nonMemberGroupId, type: ApproverType.Group }],
- approvals: 1
- }
- });
-
- expect(updateRes.statusCode).toBe(400);
- expect(updateRes.json().message).toContain("Some groups are not members of the project");
- expect(updateRes.json().message).toContain(nonMemberGroupId);
- } finally {
- await cleanupGroup(db, group.id);
- }
- });
-
test("Generic delete endpoint checks permission before revealing the policy type", async () => {
const db = getDb();
const member = await seedProjectMember(db);
diff --git a/backend/e2e-test/routes/v1/secret-approval-global-guards.spec.ts b/backend/e2e-test/routes/v1/secret-approval-global-guards.spec.ts
index d7ec96cb9f..afc490ed9f 100644
--- a/backend/e2e-test/routes/v1/secret-approval-global-guards.spec.ts
+++ b/backend/e2e-test/routes/v1/secret-approval-global-guards.spec.ts
@@ -4,103 +4,15 @@ import { createFolder, deleteFolder } from "e2e-test/testUtils/folders";
import { seedLegacySecretApprovalPolicy } from "e2e-test/testUtils/secret-approval-policies";
import { Knex } from "knex";
-import { AccessScope, OrgMembershipRole, ProjectMembershipRole, TableName } from "@app/db/schemas";
+import { TableName } from "@app/db/schemas";
import { seedData1 } from "@app/db/seed-data";
-import { ApproverType } from "@app/ee/services/access-approval-policy/access-approval-policy-types";
-import { ApprovalPolicyType } from "@app/services/approval-policy/approval-policy-enums";
const getDb = () => (globalThis as unknown as { testDb: Knex }).testDb;
const projectId = seedData1.projectV3.id;
-const orgId = seedData1.organization.id;
const envSlug = seedData1.environment.slug;
const authHeaders = () => ({ authorization: `Bearer ${jwtAuthToken}` });
-const insertMembership = async (
- membership: { scope: AccessScope; scopeProjectId?: string; actorUserId?: string; actorGroupId?: string },
- role: string
-) => {
- const [row] = await getDb()(TableName.Membership)
- .insert({ scopeOrgId: orgId, ...membership })
- .returning("id");
- const membershipId = (row as { id: string }).id;
- await getDb()(TableName.MembershipRole).insert({ membershipId, role });
- return membershipId;
-};
-
-const createProjectUser = async (label: string) => {
- const username = `${label}-${crypto.randomUUID()}@localhost.local`;
- const [user] = await getDb()(TableName.Users)
- .insert({ username, email: username, firstName: label, isAccepted: true, isGhost: false })
- .returning("id");
- const userId = (user as { id: string }).id;
- await insertMembership({ scope: AccessScope.Organization, actorUserId: userId }, OrgMembershipRole.Member);
- await insertMembership(
- { scope: AccessScope.Project, scopeProjectId: projectId, actorUserId: userId },
- ProjectMembershipRole.Member
- );
- return { userId, username };
-};
-
-const createProjectGroup = async (label: string) => {
- const slug = `${label}-${crypto.randomUUID().slice(0, 8)}`;
- const [group] = await getDb()(TableName.Groups).insert({ orgId, name: slug, slug }).returning("id");
- const groupId = (group as { id: string }).id;
- await insertMembership({ scope: AccessScope.Organization, actorGroupId: groupId }, OrgMembershipRole.NoAccess);
- await insertMembership(
- { scope: AccessScope.Project, scopeProjectId: projectId, actorGroupId: groupId },
- ProjectMembershipRole.Member
- );
- return groupId;
-};
-
-const createGlobalPolicy = async (name: string, secretPath: string, approver: { type: ApproverType; id: string }) => {
- const res = await testServer.inject({
- method: "POST",
- url: "/api/v2/secret-approvals",
- headers: authHeaders(),
- body: { projectId, environment: envSlug, secretPath, approvers: [approver], approvals: 1, name }
- });
- expect(res.statusCode).toBe(200);
- const policyId = (res.json() as { approval: { id: string } }).approval.id;
- expect(await getDb()(TableName.ApprovalPolicies).where({ id: policyId }).first()).toBeDefined();
- return policyId;
-};
-
-const replaceGlobalPolicyApprover = async (policyId: string, approver: { type: ApproverType; id: string }) => {
- const res = await testServer.inject({
- method: "PATCH",
- url: `/api/v2/secret-approvals/${policyId}`,
- headers: authHeaders(),
- body: { approvers: [approver], approvals: 1 }
- });
- expect(res.statusCode).toBe(200);
-};
-
-const deleteGlobalPolicy = async (policyId: string) => {
- const res = await testServer.inject({
- method: "DELETE",
- url: `/api/v2/secret-approvals/${policyId}`,
- headers: authHeaders()
- });
- expect(res.statusCode).toBe(200);
-};
-
-const removeProjectUser = (username: string) =>
- testServer.inject({
- method: "DELETE",
- url: `/api/v1/projects/${projectId}/memberships`,
- headers: authHeaders(),
- body: { usernames: [username] }
- });
-
-const removeProjectGroup = (groupId: string) =>
- testServer.inject({
- method: "DELETE",
- url: `/api/v1/projects/${projectId}/memberships/groups/${groupId}`,
- headers: authHeaders()
- });
-
const deleteFolderRequest = (folderId: string, secretPath: string) =>
testServer.inject({
method: "DELETE",
@@ -109,68 +21,6 @@ const deleteFolderRequest = (folderId: string, secretPath: string) =>
body: { workspaceId: projectId, environment: envSlug, path: secretPath, forceDelete: true }
});
-const seedOpenSecretChangeRequest = async (folderId: string) => {
- const [request] = await getDb()(TableName.ApprovalRequests)
- .insert({
- projectId,
- organizationId: orgId,
- policyId: null,
- requesterId: seedData1.id,
- requesterName: "test",
- requesterEmail: seedData1.email,
- type: ApprovalPolicyType.SecretChange,
- status: "open",
- currentStep: 0,
- requestData: JSON.stringify({})
- })
- .returning("id");
- const approvalRequestId = (request as { id: string }).id;
- await getDb()(TableName.SecretChangeRequests).insert({
- approvalRequestId,
- folderId,
- slug: `guard-${crypto.randomUUID().slice(0, 8)}`
- });
- return approvalRequestId;
-};
-
-const seedOpenRequestWithApprover = async (folderId: string, approver: { userId?: string; groupId?: string }) => {
- const slug = `guard-${crypto.randomUUID().slice(0, 8)}`;
- const [request] = await getDb()(TableName.ApprovalRequests)
- .insert({
- projectId,
- organizationId: orgId,
- policyId: null,
- requesterId: seedData1.id,
- requesterName: "test",
- requesterEmail: seedData1.email,
- type: ApprovalPolicyType.SecretChange,
- status: "open",
- currentStep: 1,
- requestData: JSON.stringify({})
- })
- .returning("id");
- const approvalRequestId = (request as { id: string }).id;
- const [step] = await getDb()(TableName.ApprovalRequestSteps)
- .insert({
- requestId: approvalRequestId,
- stepNumber: 1,
- status: "in-progress",
- requiredApprovals: 1
- })
- .returning("id");
- await getDb()(TableName.ApprovalRequestStepEligibleApprovers).insert({
- stepId: (step as { id: string }).id,
- userId: approver.userId ?? null,
- groupId: approver.groupId ?? null
- });
- await getDb()(TableName.SecretChangeRequests).insert({
- approvalRequestId,
- folderId,
- slug
- });
- return { approvalRequestId, slug };
-};
-
const seedOpenLegacyRequest = async (folderId: string, policyId: string) => {
const [request] = await getDb()(TableName.SecretApprovalRequest)
.insert({
@@ -207,177 +57,13 @@ const openRequestMessage = (folderPath: string) =>
`You cannot delete the selected folder because it has open change requests at folder path "${folderPath}". Merge or close the change requests and try again.`;
describe("Global approval system guards outside the approval routes", () => {
- const userIds: string[] = [];
- const groupIds: string[] = [];
- const policyIds: string[] = [];
- const requestIds: string[] = [];
const legacyPolicyIds: string[] = [];
const legacyRequestIds: string[] = [];
afterAll(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 folder with an open legacy change request cannot be deleted until the request is closed", async () => {