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 unguarded paths
Thiago Araujo da Silva2d216934ee4a
diff --git a/backend/e2e-test/routes/v1/privilege-boundary-removal.spec.ts b/backend/e2e-test/routes/v1/privilege-boundary-removal.spec.tsindex ddf609cab9..58be9d1f9d 100644--- a/backend/e2e-test/routes/v1/privilege-boundary-removal.spec.ts+++ b/backend/e2e-test/routes/v1/privilege-boundary-removal.spec.ts@@ -12,6 +12,10 @@* Prerequisites (handled by vitest-environment-knex.ts): testServer, jwtAuthToken, testDb.*/+import crypto from "node:crypto";++import { packRules } from "@casl/ability/extra";+import { AccessScope, OrgMembershipRole, ProjectMembershipRole, TableName } from "@app/db/schemas";import { seedData1 } from "@app/db/seed-data";@@ -236,3 +240,226 @@ describe("Privilege boundary on the deprecated v1 add-user-to-project route", ()expect(res.json().message).toContain("already part of project");});});++/**+ * A custom role holding only the removal action. This is the actor shape the boundary is about: a+ * principal that legitimately holds `member:delete` yet is weaker than the member it is removing.+ * The built-in org and project Member roles do not hold `member:delete` at all, so they would be+ * rejected by the plain permission check and never reach the boundary.+ *+ * The role is written straight to the table because the e2e license mock reports `rbac: false`, so+ * the custom-role routes refuse to create one. That gate is not what these tests are about, and the+ * boundary resolves roles out of these same columns however they were written.+ */+const insertMemberRemoverRole = async (slug: string, scope: { orgId: string } | { projectId: string }) => {+ const [role] = await testDb(TableName.Role)+ .insert({+ name: slug,+ slug,+ permissions: JSON.stringify(packRules([{ subject: "member", action: ["read", "delete"] }])),+ ...scope+ })+ .returning("id");++ return (role as { id: string }).id;+};++/** Repoint an existing membership at a custom role, replacing the built-in role it was created with. */+const useCustomRole = async (membershipId: string, customRoleId: string) => {+ await testDb(TableName.MembershipRole).where({ membershipId }).delete();+ await testDb(TableName.MembershipRole).insert({ membershipId, role: "custom", customRoleId });+};++const findIdentityMembershipId = async (identityId: string, projectId?: string) => {+ const row = await testDb(TableName.Membership)+ .where({+ actorIdentityId: identityId,+ scopeOrgId: seedData1.organization.id,+ scope: projectId ? AccessScope.Project : AccessScope.Organization,+ ...(projectId ? { scopeProjectId: projectId } : {})+ })+ .first();+ expect(row).toBeDefined();++ return (row as { id: string }).id;+};++/**+ * The seed carries exactly one user, and every removal path here targets a *user* membership. The+ * routes only need a non-ghost Users row joined to a Membership, never a login, so the target is+ * inserted directly rather than driven through the signup and SRP flow.+ */+const createTargetUser = async (label: string) => {+ const username = `${label}-${crypto.randomUUID()}@localhost.local`;+ const [user] = await testDb(TableName.Users)+ .insert({ username, email: username, firstName: label, isAccepted: true, isGhost: false })+ .returning("id");++ return { userId: (user as { id: string }).id, username };+};++const giveUserMembership = async ({+ userId,+ role,+ projectId+}: {+ userId: string;+ role: OrgMembershipRole | ProjectMembershipRole;+ projectId?: string;+}) => {+ const [membership] = await testDb(TableName.Membership)+ .insert({+ scope: projectId ? AccessScope.Project : AccessScope.Organization,+ scopeOrgId: seedData1.organization.id,+ scopeProjectId: projectId ?? null,+ actorUserId: userId+ })+ .returning("id");++ const membershipId = (membership as { id: string }).id;+ await testDb(TableName.MembershipRole).insert({ membershipId, role });+ return membershipId;+};++const dropUser = async (userId: string) => {+ await testDb(TableName.Membership).where({ actorUserId: userId }).delete();+ await testDb(TableName.Users).where({ id: userId }).delete();+};++describe("Privilege boundary on org membership removal", () => {+ // These are the v2 organization routes, which remove a member through org-service rather than+ // through the scoped membership factory. They carry the same reach as the scoped delete and so+ // need the same boundary; without it they are a way around it.+ let actor: { identityId: string; token: string };+ let adminTarget: { userId: string; membershipId: string };++ const deleteOrgMembership = (membershipId: string, headers: Record<string, string>) =>+ testServer.inject({+ method: "DELETE",+ url: `/api/v2/organizations/${seedData1.organization.id}/memberships/${membershipId}`,+ headers+ });++ const bulkDeleteOrgMemberships = (membershipIds: string[], headers: Record<string, string>) =>+ testServer.inject({+ method: "DELETE",+ url: `/api/v2/organizations/${seedData1.organization.id}/memberships`,+ headers,+ body: { membershipIds }+ });++ beforeAll(async () => {+ const roleId = await insertMemberRemoverRole("e2e-pb-org-member-remover", {+ orgId: seedData1.organization.id+ });+ actor = await createActorIdentity("e2e-pb-org-actor");+ await useCustomRole(await findIdentityMembershipId(actor.identityId), roleId);++ const target = await createTargetUser("e2e-pb-org-target");+ adminTarget = {+ userId: target.userId,+ membershipId: await giveUserMembership({ userId: target.userId, role: OrgMembershipRole.Admin })+ };+ });++ afterAll(async () => {+ await deleteIdentity(actor.identityId);+ await dropUser(adminTarget.userId);+ await testDb(TableName.Role).where({ slug: "e2e-pb-org-member-remover" }).delete();+ });++ describe("on the legacy privilege system", () => {+ beforeAll(() => setNewPrivilegeSystem(false));+ afterAll(() => setNewPrivilegeSystem(true));++ test("a member:delete-only role cannot remove an org Admin", async () => {+ const res = await deleteOrgMembership(adminTarget.membershipId, asIdentity(actor.token));+ expect(res.statusCode).toBe(403);+ expect(res.json().message).toContain("more privileged member");+ });++ test("the bulk route is bounded too, so it is not a way around the single-member route", async () => {+ const res = await bulkDeleteOrgMemberships([adminTarget.membershipId], asIdentity(actor.token));+ expect(res.statusCode).toBe(403);+ expect(res.json().message).toContain("more privileged member");+ });++ test("an admin can still remove an org Admin", async () => {+ const res = await deleteOrgMembership(adminTarget.membershipId, adminHeaders());+ expect(res.statusCode).toBe(200);++ adminTarget.membershipId = await giveUserMembership({+ userId: adminTarget.userId,+ role: OrgMembershipRole.Admin+ });+ });+ });+});++describe("Privilege boundary on the bulk project member removal route", () => {+ // DELETE /api/v1/projects/:projectId/memberships removes members by username through+ // project-membership-service, bypassing the scoped membership factory's delete guard.+ let project: { id: string };+ let actor: { identityId: string; token: string };+ let adminTarget: { userId: string; username: string };++ const removeMembers = (usernames: string[], headers: Record<string, string>) =>+ testServer.inject({+ method: "DELETE",+ url: `/api/v1/projects/${project.id}/memberships`,+ headers,+ body: { usernames }+ });++ beforeAll(async () => {+ const createProjectRes = await testServer.inject({+ method: "POST",+ url: "/api/v1/projects",+ headers: adminHeaders(),+ body: { projectName: "e2e-privilege-boundary-bulk-remove" }+ });+ expect(createProjectRes.statusCode).toBe(200);+ project = createProjectRes.json().project;++ const roleId = await insertMemberRemoverRole("e2e-pb-project-member-remover", { projectId: project.id });+ actor = await createActorIdentity("e2e-pb-bulk-actor");+ await addIdentityToProject(project.id, actor.identityId, ProjectMembershipRole.Member);+ await useCustomRole(await findIdentityMembershipId(actor.identityId, project.id), roleId);++ const target = await createTargetUser("e2e-pb-bulk-target");+ adminTarget = target;+ await giveUserMembership({ userId: target.userId, role: OrgMembershipRole.Member });+ await giveUserMembership({+ userId: target.userId,+ role: ProjectMembershipRole.Admin,+ projectId: project.id+ });+ });++ afterAll(async () => {+ await deleteIdentity(actor.identityId);+ await dropUser(adminTarget.userId);+ await testDb(TableName.Role).where({ slug: "e2e-pb-project-member-remover" }).delete();+ await testServer.inject({+ method: "DELETE",+ url: `/api/v1/projects/${project.id}`,+ headers: adminHeaders()+ });+ });++ describe("on the legacy privilege system", () => {+ beforeAll(() => setNewPrivilegeSystem(false));+ afterAll(() => setNewPrivilegeSystem(true));++ test("a member:delete-only role cannot remove a project Admin", async () => {+ const res = await removeMembers([adminTarget.username], asIdentity(actor.token));+ expect(res.statusCode).toBe(403);+ expect(res.json().message).toContain("more privileged member");+ });++ test("an admin can still remove a project Admin", async () => {+ const res = await removeMembers([adminTarget.username], adminHeaders());+ expect(res.statusCode).toBe(200);+ });+ });+});diff --git a/backend/src/services/membership/membership-fns.test.ts b/backend/src/services/membership/membership-fns.test.tsindex 7b30dbef79..361135584d 100644--- a/backend/src/services/membership/membership-fns.test.ts+++ b/backend/src/services/membership/membership-fns.test.ts@@ -31,6 +31,34 @@ describe("resolveMembershipRoleSlugs", () => {).toEqual(["admin"]);});+ test("deduplicates a slug repeated within one membership", () => {+ // The uniqueness key on membership roles spans isTemporary, so one membership can hold the same+ // custom role permanently and temporarily. Passing the slug twice makes getOrgPermissionByRoles+ // report it as missing, because it compares the requested count against the rows it finds.+ expect(+ resolveMembershipRoleSlugs([+ { role: "custom", customRoleSlug: "release-manager" },+ {+ role: "custom",+ customRoleSlug: "release-manager",+ isTemporary: true,+ temporaryAccessEndTime: new Date(Date.now() + 60_000)+ }+ ])+ ).toEqual(["release-manager"]);+ });++ test("deduplicates slugs shared across memberships in a bulk removal", () => {+ expect(+ resolveMembershipRoleSlugs([+ { role: "member" },+ { role: "member" },+ { role: "custom", customRoleSlug: "auditor" },+ { role: "custom", customRoleSlug: "auditor" }+ ])+ ).toEqual(["member", "auditor"]);+ });+test("returns an empty list when every role filters out", () => {expect(resolveMembershipRoleSlugs([diff --git a/backend/src/services/membership/membership-fns.ts b/backend/src/services/membership/membership-fns.tsindex fed77b0deb..33ca1ef72b 100644--- a/backend/src/services/membership/membership-fns.ts+++ b/backend/src/services/membership/membership-fns.ts@@ -53,9 +53,12 @@ type TMembershipRole = {temporaryAccessEndTime?: Date | null;};-// Resolves a membership's roles into the slug list that get{Org,Project}PermissionByRoles expects.-export const resolveMembershipRoleSlugs = (roles: TMembershipRole[]) =>- roles- .filter(isActiveRole)- .map((role) => role.customRoleSlug || role.role)- .filter((slug) => slug !== OrgMembershipRole.NoAccess && slug !== ProjectMembershipRole.NoAccess);+// Resolves membership roles into the slug list that get{Org,Project}PermissionByRoles expects.+export const resolveMembershipRoleSlugs = (roles: TMembershipRole[]) => [+ ...new Set(+ roles+ .filter(isActiveRole)+ .map((role) => role.customRoleSlug || role.role)+ .filter((slug) => slug !== OrgMembershipRole.NoAccess && slug !== ProjectMembershipRole.NoAccess)+ )+];diff --git a/backend/src/services/membership/membership-role-dal.ts b/backend/src/services/membership/membership-role-dal.tsindex bb70112215..a73a323aad 100644--- a/backend/src/services/membership/membership-role-dal.ts+++ b/backend/src/services/membership/membership-role-dal.ts@@ -1,10 +1,44 @@+import { Knex } from "knex";+import { TDbClient } from "@app/db";import { TableName } from "@app/db/schemas";+import { DatabaseError } from "@app/lib/errors";import { ormify } from "@app/lib/knex";export type TMembershipRoleDALFactory = ReturnType<typeof membershipRoleDALFactory>;+type TMembershipRoleSlug = {+ membershipId: string;+ role: string;+ isTemporary: boolean;+ temporaryAccessEndTime?: Date | null;+ customRoleSlug?: string | null;+};+export const membershipRoleDALFactory = (db: TDbClient) => {const orm = ormify(db, TableName.MembershipRole);- return orm;++ // Role rows for a set of memberships, carrying the custom-role slug rather than its id so the+ // result feeds resolveMembershipRoleSlugs directly. Batched so a bulk privilege-boundary check+ // costs one query no matter how many memberships the caller is removing.+ const findRolesByMembershipIds = async (membershipIds: string[], tx?: Knex): Promise<TMembershipRoleSlug[]> => {+ if (!membershipIds.length) return [];++ try {+ return await (tx || db.replicaNode())(TableName.MembershipRole)+ .whereIn(`${TableName.MembershipRole}.membershipId`, membershipIds)+ .leftJoin(TableName.Role, `${TableName.MembershipRole}.customRoleId`, `${TableName.Role}.id`)+ .select(+ db.ref("membershipId").withSchema(TableName.MembershipRole),+ db.ref("role").withSchema(TableName.MembershipRole),+ db.ref("isTemporary").withSchema(TableName.MembershipRole),+ db.ref("temporaryAccessEndTime").withSchema(TableName.MembershipRole),+ db.ref("slug").withSchema(TableName.Role).as("customRoleSlug")+ );+ } catch (error) {+ throw new DatabaseError({ error, name: "FindRolesByMembershipIds" });+ }+ };++ return { ...orm, findRolesByMembershipIds };};diff --git a/backend/src/services/org/org-service.ts b/backend/src/services/org/org-service.tsindex af180ba2ba..a4850fcb30 100644--- a/backend/src/services/org/org-service.ts+++ b/backend/src/services/org/org-service.ts@@ -1,4 +1,4 @@-import { ForbiddenError } from "@casl/ability";+import { ForbiddenError, MongoAbility } from "@casl/ability";import slugify from "@sindresorhus/slugify";import { Knex } from "knex";@@ -25,7 +25,7 @@ import {OrgPermissionSsoActions,OrgPermissionSubjects} from "@app/ee/services/permission/org-permission";-import { assertPermissionBoundary } from "@app/ee/services/permission/permission-fns";+import { assertPermissionBoundary, assertRoleSetBoundary } from "@app/ee/services/permission/permission-fns";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";import { TSamlConfigDALFactory } from "@app/ee/services/saml-config/saml-config-dal";import { getConfig } from "@app/lib/config/env";@@ -55,6 +55,7 @@ import { bootstrapCertManagerProject } from "../cert-manager-instance/cert-managimport { TCertificatePolicyDALFactory } from "../certificate-policy/certificate-policy-dal";import { TIdentityMetadataDALFactory } from "../identity/identity-metadata-dal";import { TMembershipDALFactory } from "../membership/membership-dal";+import { resolveMembershipRoleSlugs } from "../membership/membership-fns";import { TMembershipRoleDALFactory } from "../membership/membership-role-dal";import { TMembershipUserDALFactory } from "../membership-user/membership-user-dal";import { assertWillRetainOrgAdmin } from "../membership-user/membership-user-fns";@@ -1177,6 +1178,33 @@ export const orgServiceFactory = ({return membership;};+ const $assertMembershipRemovalBoundary = async ({+ membershipIds,+ orgId,+ permission+ }: {+ membershipIds: string[];+ orgId: string;+ permission: MongoAbility;+ }) => {+ const targetRoles = resolveMembershipRoleSlugs(await membershipRoleDAL.findRolesByMembershipIds(membershipIds));+ if (!targetRoles.length) return;++ const targetPermissions = await permissionService.getOrgPermissionByRoles(targetRoles, orgId);+ const { shouldUseNewPrivilegeSystem } = await requestMemoize(requestMemoKeys.orgFindById(orgId), () =>+ orgDAL.findById(orgId)+ );++ assertRoleSetBoundary({+ shouldUseNewPrivilegeSystem,+ opActions: OrgPermissionActions.Delete,+ opSubject: OrgPermissionSubjects.Member,+ actorPermission: permission,+ targetPermissions,+ baseMessage: "Failed to remove a more privileged member from the organization"+ });+ };+const deleteOrgMembership = async ({orgId,actor,@@ -1203,6 +1231,8 @@ export const orgServiceFactory = ({if (!membershipToDelete?.actorUserId)throw new NotFoundError({ message: `Organization membership with ID '${membershipId}' not found` });+ await $assertMembershipRemovalBoundary({ membershipIds: [membershipId], orgId, permission });+const [deletedMembership] = await deleteOrgMembershipsFn({orgMembershipIds: [membershipId],orgId,@@ -1256,6 +1286,8 @@ export const orgServiceFactory = ({message: `Organization membership with ID '${missingMembershipIds.join("', '")}' not found`});+ await $assertMembershipRemovalBoundary({ membershipIds, orgId, permission });+const deletedMemberships = await deleteOrgMembershipsFn({orgMembershipIds: membershipIds,orgId,diff --git a/backend/src/services/project-membership/project-membership-service.ts b/backend/src/services/project-membership/project-membership-service.tsindex 389ea13982..d57f737063 100644--- a/backend/src/services/project-membership/project-membership-service.ts+++ b/backend/src/services/project-membership/project-membership-service.ts@@ -25,6 +25,7 @@ import { TAlertChannelRecipientDALFactory } from "../alert/alert-channel-recipieimport { ActorType } from "../auth/auth-type";import { TGroupProjectDALFactory } from "../group-project/group-project-dal";import { TApplicationMembershipCleanupServiceFactory } from "../membership/application-membership-cleanup-service";+import { resolveMembershipRoleSlugs } from "../membership/membership-fns";import { TMembershipRoleDALFactory } from "../membership/membership-role-dal";import { TMembershipUserDALFactory } from "../membership-user/membership-user-dal";import { TNotificationServiceFactory } from "../notification/notification-service";@@ -52,7 +53,7 @@ type TProjectMembershipServiceFactoryDep = {smtpService: TSmtpService;projectMembershipDAL: TProjectMembershipDALFactory;membershipUserDAL: TMembershipUserDALFactory;- membershipRoleDAL: Pick<TMembershipRoleDALFactory, "insertMany" | "find" | "delete">;+ membershipRoleDAL: Pick<TMembershipRoleDALFactory, "insertMany" | "find" | "delete" | "findRolesByMembershipIds">;userDAL: Pick<TUserDALFactory, "find">;userAliasDAL: Pick<TUserAliasDALFactory, "findBySsoExternalIds">;orgDAL: Pick<TOrgDALFactory, "findById">;@@ -407,6 +408,25 @@ export const projectMembershipServiceFactory = ({});}+ const targetRoles = resolveMembershipRoleSlugs(+ await membershipRoleDAL.findRolesByMembershipIds(projectMembers.map(({ id }) => id))+ );+ if (targetRoles.length) {+ const targetPermissions = await permissionService.getProjectPermissionByRoles(targetRoles, projectId);+ const { shouldUseNewPrivilegeSystem } = await requestMemoize(requestMemoKeys.orgFindById(actorOrgId), () =>+ orgDAL.findById(actorOrgId)+ );++ assertRoleSetBoundary({+ shouldUseNewPrivilegeSystem,+ opActions: ProjectPermissionMemberActions.Delete,+ opSubject: ProjectPermissionSub.Member,+ actorPermission: permission,+ targetPermissions,+ baseMessage: "Failed to remove a more privileged member from the project"+ });+ }+await checkUserApproverPolicies(projectMembers.map((m) => m.user.id),projectId