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
fix greptile review
adilsondfa4d2c9ef8a
diff --git a/backend/e2e-test/routes/v1/access-approval-policy.spec.ts b/backend/e2e-test/routes/v1/access-approval-policy.spec.tsindex ae41b15650..f38658cb8d 100644--- a/backend/e2e-test/routes/v1/access-approval-policy.spec.ts+++ b/backend/e2e-test/routes/v1/access-approval-policy.spec.ts@@ -1,10 +1,15 @@import crypto from "node:crypto";+import jwt from "jsonwebtoken";import { Knex } from "knex";-import { AccessScope, TableName } from "@app/db/schemas";+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;@@ -125,7 +130,98 @@ const cleanupGroup = async (db: Knex, groupId: string) => {await db(TableName.Groups).where({ id: groupId }).del();};+type TProjectMember = { userId: string; token: string };++const seedProjectMember = async (db: Knex): Promise<TProjectMember> => {+ const username = `aap-member-${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-policy",+ 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 cleanupProjectMember = async (db: Knex, userId: string) => {+ const memberships = await db(TableName.Membership).where({ actorUserId: userId }).select("id");+ if (memberships.length) {+ await db(TableName.MembershipRole)+ .whereIn(+ "membershipId",+ memberships.map((m) => m.id)+ )+ .del();+ await db(TableName.Membership).where({ actorUserId: userId }).del();+ }+ await db(TableName.AuthTokenSession).where({ userId }).del();+ await db(TableName.Users).where({ id: userId }).del();+};++// Secret access policies have no generic router of their own, so a caller can only reach+// the shared delete handler with one of their ids through another registered type's route.+const deletePolicyThroughGenericEndpoint = (policyId: string, token: string) =>+ testServer.inject({+ method: "DELETE",+ url: `/api/v1/approval-policies/pam-access/${policyId}`,+ headers: {+ authorization: `Bearer ${token}`+ }+ });+describe("Access approval policy router", async () => {+ beforeAll(async () => {+ initLogger();+ await initEnvConfig(testHsmService, testKmsRootConfigDAL, testSuperAdminDAL, logger);+ });+afterEach(async () => {const ids = createdPolicyIds.splice(0);await Promise.all(ids.map(deletePolicy));@@ -208,4 +304,31 @@ describe("Access approval policy router", async () => {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);++ try {+ const policy = await createPolicy({+ secretPath: "/generic-delete",+ approvals: 1,+ approvers: [{ id: seedData1.id, type: ApproverType.User }],+ name: "test-access-policy-generic-delete"+ });++ const asMember = await deletePolicyThroughGenericEndpoint(policy.id, member.token);+ expect(asMember.statusCode).toBe(403);+ expect(asMember.json().message).not.toContain("secret access policy");++ const asAdmin = await deletePolicyThroughGenericEndpoint(policy.id, jwtAuthToken);+ expect(asAdmin.statusCode).toBe(400);+ expect(asAdmin.json().message).toContain("secret access policy");++ const stillThere = await db(TableName.ApprovalPolicies).where({ id: policy.id }).first();+ expect(stillThere).toBeDefined();+ } finally {+ await cleanupProjectMember(db, member.userId);+ }+ });});diff --git a/backend/src/services/approval-policy/approval-policy-dal.ts b/backend/src/services/approval-policy/approval-policy-dal.tsindex e948888132..c521767622 100644--- a/backend/src/services/approval-policy/approval-policy-dal.ts+++ b/backend/src/services/approval-policy/approval-policy-dal.ts@@ -250,20 +250,20 @@ export const approvalPolicyDALFactory = (db: TDbClient) => {* on any step. The subject is identified by `userId` OR `groupId` (not both). Used to block* removing a member from an application while they're still wired up as a reviewer.*/- const findPoliciesWhereSubjectIsApprover = async (args: {- projectId: string;- type?: ApprovalPolicyType;- scopeType?: string;- scopeId?: string;- userId?: string;- userIds?: string[];- groupId?: string;- }) => {+ const findPoliciesWhereSubjectIsApprover = async (+ args: {+ type?: ApprovalPolicyType;+ scopeType?: string;+ scopeId?: string;+ userId?: string;+ userIds?: string[];+ groupId?: string;+ } & ({ projectId: string; organizationId?: undefined } | { projectId?: undefined; organizationId: string })+ ) => {try {const dbInstance = db.replicaNode();const baseQuery = dbInstance(TableName.ApprovalPolicies)- .where({ projectId: args.projectId }).innerJoin(TableName.ApprovalPolicySteps,`${TableName.ApprovalPolicySteps}.policyId`,@@ -275,6 +275,14 @@ export const approvalPolicyDALFactory = (db: TDbClient) => {`${TableName.ApprovalPolicySteps}.id`);+ if (args.projectId) {+ void baseQuery.where(`${TableName.ApprovalPolicies}.projectId`, args.projectId);+ } else if (args.organizationId) {+ void baseQuery.where(`${TableName.ApprovalPolicies}.organizationId`, args.organizationId);+ } else {+ return [];+ }+if (args.type) {void baseQuery.where(`${TableName.ApprovalPolicies}.type`, args.type);}diff --git a/backend/src/services/approval-policy/approval-policy-service.ts b/backend/src/services/approval-policy/approval-policy-service.tsindex 9261752ecd..4292681287 100644--- a/backend/src/services/approval-policy/approval-policy-service.ts+++ b/backend/src/services/approval-policy/approval-policy-service.ts@@ -934,12 +934,6 @@ export const approvalPolicyServiceFactory = ({throw new ForbiddenRequestError({ message: "Policy not found" });}- if (policy.type === ApprovalPolicyType.SecretAccess) {- throw new BadRequestError({- message: "This is a secret access policy. Delete it from the access approval policies instead."- });- }-await $assertCanManagePolicy(policy.projectId,policy.scopeType ?? null,@@ -949,6 +943,12 @@ export const approvalPolicyServiceFactory = ({policy.type as ApprovalPolicyType);+ if (policy.type === ApprovalPolicyType.SecretAccess) {+ throw new BadRequestError({+ message: "This is a secret access policy. Delete it from the access approval policies instead."+ });+ }+const cancelled = await approvalPolicyDAL.transaction(async (tx) => {const rows = await approvalRequestDAL.update({ policyId, status: ApprovalRequestStatus.Pending },diff --git a/backend/src/services/membership-group/membership-group-service.ts b/backend/src/services/membership-group/membership-group-service.tsindex 09ecc8282e..7d4b1f53e3 100644--- a/backend/src/services/membership-group/membership-group-service.ts+++ b/backend/src/services/membership-group/membership-group-service.ts@@ -415,18 +415,18 @@ export const membershipGroupServiceFactory = ({}}- if (existingMembership.scopeProjectId) {- const secretAccessPolicies = await approvalPolicyDAL.findPoliciesWhereSubjectIsApprover({- projectId: existingMembership.scopeProjectId,- type: ApprovalPolicyType.SecretAccess,- groupId: dto.selector.groupId+ const secretAccessPolicies = await approvalPolicyDAL.findPoliciesWhereSubjectIsApprover({+ ...(existingMembership.scopeProjectId+ ? { projectId: existingMembership.scopeProjectId }+ : { organizationId: existingMembership.scopeOrgId }),+ type: ApprovalPolicyType.SecretAccess,+ groupId: dto.selector.groupId+ });+ if (secretAccessPolicies.length > 0) {+ const policyNames = secretAccessPolicies.map((p) => p.name).join(", ");+ throw new BadRequestError({+ message: `Cannot remove group from ${existingMembership.scopeProjectId ? "project" : "organization"}: group is an approver in access approval ${secretAccessPolicies.length > 1 ? "policies" : "policy"}: ${policyNames}`});- if (secretAccessPolicies.length > 0) {- const policyNames = secretAccessPolicies.map((p) => p.name).join(", ");- throw new BadRequestError({- message: `Cannot remove group from project: group is an approver in access approval ${secretAccessPolicies.length > 1 ? "policies" : "policy"}: ${policyNames}`- });- }}// check if group is assigned to any secret approval policy