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
feat(external-group-org-role-mapping): enhance role mapping service and add tests
Victor Hugo dos Santos99b7e0aafee7
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 3526fefc23..006aafbc1f 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -3180,7 +3180,8 @@ export const registerRoutes = async (permissionService,licenseService,externalGroupOrgRoleMappingDAL,- roleDAL+ roleDAL,+ orgDAL});const appConnectionCredentialRotationService = appConnectionCredentialRotationServiceFactory({diff --git a/backend/src/server/routes/v1/external-group-org-role-mapping-router.ts b/backend/src/server/routes/v1/external-group-org-role-mapping-router.tsindex 127c32f6e1..6003ec8009 100644--- a/backend/src/server/routes/v1/external-group-org-role-mapping-router.ts+++ b/backend/src/server/routes/v1/external-group-org-role-mapping-router.ts@@ -26,7 +26,9 @@ export const registerExternalGroupOrgRoleMappingRouter = async (server: FastifyZ},onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),handler: async (req) => {- const mappings = server.services.externalGroupOrgRoleMapping.listExternalGroupOrgRoleMappings(req.permission);+ const mappings = await server.services.externalGroupOrgRoleMapping.listExternalGroupOrgRoleMappings(+ req.permission+ );await server.services.auditLog.createAuditLog({orgId: req.permission.orgId,@@ -67,7 +69,10 @@ export const registerExternalGroupOrgRoleMappingRouter = async (server: FastifyZhandler: async (req) => {const { body, permission } = req;- const mappings = server.services.externalGroupOrgRoleMapping.updateExternalGroupOrgRoleMappings(body, permission);+ const mappings = await server.services.externalGroupOrgRoleMapping.updateExternalGroupOrgRoleMappings(+ body,+ permission+ );await server.services.auditLog.createAuditLog({orgId: permission.orgId,diff --git a/backend/src/services/external-group-org-role-mapping/external-group-org-role-mapping-boundary.test.ts b/backend/src/services/external-group-org-role-mapping/external-group-org-role-mapping-boundary.test.tsnew file mode 100644index 0000000000..8f8f184281--- /dev/null+++ b/backend/src/services/external-group-org-role-mapping/external-group-org-role-mapping-boundary.test.ts@@ -0,0 +1,236 @@+import { createMongoAbility, MongoAbility } from "@casl/ability";+import { vi } from "vitest";++import { OrgMembershipRole } from "@app/db/schemas";+import {+ orgAdminPermissions,+ orgMemberPermissions,+ orgNoAccessPermissions,+ OrgPermissionActions,+ OrgPermissionMemberActions,+ OrgPermissionSubjects+} from "@app/ee/services/permission/org-permission";+import { BadRequestError, PermissionBoundaryError } from "@app/lib/errors";++import { externalGroupOrgRoleMappingServiceFactory } from "./external-group-org-role-mapping-service";++// SCIM applies a stored mapping to newly provisioned members with no user in the loop, so saving a+// mapping is the grant. `scim:edit` alone must not let an editor hand out roles beyond their reach.++const ORG_ID = "org-id";+const HIGH_ROLE = { id: "high-role-id", slug: "high" };++const admin = createMongoAbility<MongoAbility>(orgAdminPermissions);+const member = createMongoAbility<MongoAbility>(orgMemberPermissions);+const noAccess = createMongoAbility<MongoAbility>(orgNoAccessPermissions);+const high = createMongoAbility<MongoAbility>(orgAdminPermissions);++const scimEditor = createMongoAbility<MongoAbility>([+ { action: [OrgPermissionActions.Read, OrgPermissionActions.Edit], subject: OrgPermissionSubjects.Scim }+]);++const scimEditorWithGrant = createMongoAbility<MongoAbility>([+ { action: [OrgPermissionActions.Read, OrgPermissionActions.Edit], subject: OrgPermissionSubjects.Scim },+ { action: [OrgPermissionMemberActions.GrantPrivileges], subject: OrgPermissionSubjects.Member }+]);++type TStoredMapping = { groupName: string; role: string; roleId?: string | null };++const createService = ({+ actorPermission,+ shouldUseNewPrivilegeSystem,+ currentMappings = [],+ existingCustomRoles = [HIGH_ROLE]+}: {+ actorPermission: MongoAbility;+ shouldUseNewPrivilegeSystem: boolean;+ currentMappings?: TStoredMapping[];+ existingCustomRoles?: { id: string; slug: string }[];+}) => {+ const abilityByRole: Record<string, { permission: MongoAbility; role?: { slug: string } }> = {+ [OrgMembershipRole.Admin]: { permission: admin },+ [OrgMembershipRole.Member]: { permission: member },+ [OrgMembershipRole.NoAccess]: { permission: noAccess },+ [HIGH_ROLE.slug]: { permission: high, role: HIGH_ROLE }+ };++ const getOrgPermissionByRoles = vi+ .fn()+ .mockImplementation((roles: string[]) => roles.map((role) => abilityByRole[role]));++ const externalGroupOrgRoleMappingDAL = {+ find: vi.fn().mockResolvedValue(currentMappings.map((mapping) => ({ orgId: ORG_ID, roleId: null, ...mapping }))),+ updateExternalGroupOrgRoleMappingForOrg: vi.fn().mockResolvedValue([])+ };++ const service = externalGroupOrgRoleMappingServiceFactory({+ permissionService: {+ getOrgPermission: vi.fn().mockResolvedValue({ permission: actorPermission }),+ getOrgPermissionByRoles+ } as never,+ licenseService: { getPlan: vi.fn().mockResolvedValue({ rbac: true }) } as never,+ roleDAL: {+ find: vi+ .fn()+ .mockImplementation(({ $in }: { $in: { slug?: string[]; id?: string[] } }) =>+ existingCustomRoles.filter((role) => $in.slug?.includes(role.slug) || $in.id?.includes(role.id))+ )+ } as never,+ orgDAL: { findById: vi.fn().mockResolvedValue({ id: ORG_ID, shouldUseNewPrivilegeSystem }) } as never,+ externalGroupOrgRoleMappingDAL: externalGroupOrgRoleMappingDAL as never+ });++ const actor = { type: "user", id: "actor-id", authMethod: "email", orgId: ORG_ID } as never;+ const run = (mappings: { groupName: string; roleSlug: string }[]) =>+ service.updateExternalGroupOrgRoleMappings({ mappings }, actor);++ return {+ run,+ getOrgPermissionByRoles,+ persist: externalGroupOrgRoleMappingDAL.updateExternalGroupOrgRoleMappingForOrg+ };+};++const BOTH_SYSTEMS = [true, false];++describe("updateExternalGroupOrgRoleMappings privilege boundary", () => {+ test("the editor holds scim:edit, so the plain permission check is not what rejects it", () => {+ expect(scimEditor.can(OrgPermissionActions.Edit, OrgPermissionSubjects.Scim)).toBe(true);+ });++ test("a group mapped twice in one request is a 400, not a unique-index 500", async () => {+ const { run, persist } = createService({ actorPermission: admin, shouldUseNewPrivilegeSystem: true });++ await expect(+ run([+ { groupName: "g", roleSlug: OrgMembershipRole.NoAccess },+ { groupName: "g", roleSlug: OrgMembershipRole.NoAccess }+ ])+ ).rejects.toThrow(BadRequestError);+ expect(persist).not.toHaveBeenCalled();+ });++ test.each(BOTH_SYSTEMS)(+ "a limited editor can resubmit an admin mapping unchanged (new privilege system: %s)",+ async (shouldUseNewPrivilegeSystem) => {+ const { run, persist, getOrgPermissionByRoles } = createService({+ actorPermission: scimEditor,+ shouldUseNewPrivilegeSystem,+ currentMappings: [+ { groupName: "admins", role: OrgMembershipRole.Admin },+ { groupName: "highs", role: OrgMembershipRole.Custom, roleId: HIGH_ROLE.id }+ ]+ });++ await run([+ { groupName: "admins", roleSlug: OrgMembershipRole.Admin },+ { groupName: "highs", roleSlug: HIGH_ROLE.slug },+ { groupName: "nobody", roleSlug: OrgMembershipRole.NoAccess }+ ]);++ expect(getOrgPermissionByRoles).not.toHaveBeenCalled();+ expect(persist).toHaveBeenCalledOnce();+ }+ );++ test.each(BOTH_SYSTEMS)(+ "a limited editor cannot add an admin mapping (new privilege system: %s)",+ async (shouldUseNewPrivilegeSystem) => {+ const { run, persist } = createService({ actorPermission: scimEditor, shouldUseNewPrivilegeSystem });++ await expect(run([{ groupName: "admins", roleSlug: OrgMembershipRole.Admin }])).rejects.toThrow(+ PermissionBoundaryError+ );+ expect(persist).not.toHaveBeenCalled();+ }+ );++ test.each(BOTH_SYSTEMS)(+ "a limited editor cannot remove an admin mapping (new privilege system: %s)",+ async (shouldUseNewPrivilegeSystem) => {+ const { run, persist } = createService({+ actorPermission: scimEditor,+ shouldUseNewPrivilegeSystem,+ currentMappings: [{ groupName: "admins", role: OrgMembershipRole.Admin }]+ });++ await expect(run([])).rejects.toThrow(PermissionBoundaryError);+ expect(persist).not.toHaveBeenCalled();+ }+ );++ test.each(BOTH_SYSTEMS)(+ "a limited editor cannot downgrade an admin mapping to no-access (new privilege system: %s)",+ async (shouldUseNewPrivilegeSystem) => {+ const { run } = createService({+ actorPermission: scimEditor,+ shouldUseNewPrivilegeSystem,+ currentMappings: [{ groupName: "admins", role: OrgMembershipRole.Admin }]+ });++ await expect(run([{ groupName: "admins", roleSlug: OrgMembershipRole.NoAccess }])).rejects.toThrow(+ PermissionBoundaryError+ );+ }+ );++ test("a replaced custom-role mapping is bounded by the role its id resolves to", async () => {+ const { run, getOrgPermissionByRoles } = createService({+ actorPermission: scimEditor,+ shouldUseNewPrivilegeSystem: false,+ currentMappings: [{ groupName: "highs", role: OrgMembershipRole.Custom, roleId: HIGH_ROLE.id }]+ });++ await expect(run([])).rejects.toThrow(PermissionBoundaryError);+ expect(getOrgPermissionByRoles).toHaveBeenCalledWith([HIGH_ROLE.slug], ORG_ID);+ });++ test("a replaced mapping whose custom role no longer exists is skipped", async () => {+ const { run, persist, getOrgPermissionByRoles } = createService({+ actorPermission: scimEditor,+ shouldUseNewPrivilegeSystem: false,+ currentMappings: [{ groupName: "orphan", role: OrgMembershipRole.Custom, roleId: "deleted-role-id" }],+ existingCustomRoles: []+ });++ await run([]);++ expect(getOrgPermissionByRoles).not.toHaveBeenCalled();+ expect(persist).toHaveBeenCalledOnce();+ });++ test("on the new system, member:grant-privileges is the authority to map to admin", async () => {+ const { run, persist } = createService({+ actorPermission: scimEditorWithGrant,+ shouldUseNewPrivilegeSystem: true+ });++ await run([{ groupName: "admins", roleSlug: OrgMembershipRole.Admin }]);+ expect(persist).toHaveBeenCalledOnce();+ });++ test("on the legacy system, grant-privileges alone does not outrank admin", async () => {+ const { run } = createService({ actorPermission: scimEditorWithGrant, shouldUseNewPrivilegeSystem: false });++ await expect(run([{ groupName: "admins", roleSlug: OrgMembershipRole.Admin }])).rejects.toThrow(+ PermissionBoundaryError+ );+ });++ test.each(BOTH_SYSTEMS)(+ "an admin can add, change and remove admin mappings (new privilege system: %s)",+ async (shouldUseNewPrivilegeSystem) => {+ const { run, persist } = createService({+ actorPermission: admin,+ shouldUseNewPrivilegeSystem,+ currentMappings: [{ groupName: "admins", role: OrgMembershipRole.Admin }]+ });++ await run([+ { groupName: "admins", roleSlug: OrgMembershipRole.Member },+ { groupName: "highs", roleSlug: HIGH_ROLE.slug }+ ]);+ expect(persist).toHaveBeenCalledOnce();+ }+ );+});diff --git a/backend/src/services/external-group-org-role-mapping/external-group-org-role-mapping-service.ts b/backend/src/services/external-group-org-role-mapping/external-group-org-role-mapping-service.tsindex e51d25ce37..2c87ae5a44 100644--- a/backend/src/services/external-group-org-role-mapping/external-group-org-role-mapping-service.ts+++ b/backend/src/services/external-group-org-role-mapping/external-group-org-role-mapping-service.ts@@ -1,13 +1,23 @@import { ForbiddenError } from "@casl/ability";-import { OrganizationActionScope } from "@app/db/schemas";+import { OrganizationActionScope, OrgMembershipRole } from "@app/db/schemas";import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";-import { OrgPermissionActions, OrgPermissionSubjects } from "@app/ee/services/permission/org-permission";+import {+ OrgPermissionActions,+ OrgPermissionMemberActions,+ OrgPermissionSubjects+} from "@app/ee/services/permission/org-permission";+import { assertRoleSetBoundary } from "@app/ee/services/permission/permission-fns";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";+import { BadRequestError } from "@app/lib/errors";+import { requestMemoKeys } from "@app/lib/request-context/memo-keys";+import { requestMemoize } from "@app/lib/request-context/request-memoizer";import { OrgServiceActor } from "@app/lib/types";import { constructGroupOrgMembershipRoleMappings } from "@app/services/external-group-org-role-mapping/external-group-org-role-mapping-fns";import { TSyncExternalGroupOrgMembershipRoleMappingsDTO } from "@app/services/external-group-org-role-mapping/external-group-org-role-mapping-types";+import { roleNeedsPrivilegeBoundary } from "@app/services/membership/membership-fns";+import { TOrgDALFactory } from "../org/org-dal";import { TRoleDALFactory } from "../role/role-dal";import { TExternalGroupOrgRoleMappingDALFactory } from "./external-group-org-role-mapping-dal";@@ -16,6 +26,7 @@ type TExternalGroupOrgRoleMappingServiceFactoryDep = {permissionService: TPermissionServiceFactory;licenseService: TLicenseServiceFactory;roleDAL: TRoleDALFactory;+ orgDAL: Pick<TOrgDALFactory, "findById">;};export type TExternalGroupOrgRoleMappingServiceFactory = ReturnType<typeof externalGroupOrgRoleMappingServiceFactory>;@@ -24,7 +35,8 @@ export const externalGroupOrgRoleMappingServiceFactory = ({externalGroupOrgRoleMappingDAL,licenseService,permissionService,- roleDAL+ roleDAL,+ orgDAL}: TExternalGroupOrgRoleMappingServiceFactoryDep) => {const listExternalGroupOrgRoleMappings = async (actor: OrgServiceActor) => {const { permission } = await permissionService.getOrgPermission({@@ -62,6 +74,15 @@ export const externalGroupOrgRoleMappingServiceFactory = ({// TODO: will need to change if we add support for ldap, oidc, etc.ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Edit, OrgPermissionSubjects.Scim);+ const seenGroupNames = new Set<string>();+ for (const { groupName } of dto.mappings) {+ if (seenGroupNames.has(groupName))+ throw new BadRequestError({+ message: `Group '${groupName}' is mapped more than once. Map each group to a single organization role.`+ });+ seenGroupNames.add(groupName);+ }+const mappings = await constructGroupOrgMembershipRoleMappings({mappingsDTO: dto.mappings,roleDAL,@@ -69,6 +90,75 @@ export const externalGroupOrgRoleMappingServiceFactory = ({orgId: actor.orgId});+ const { shouldUseNewPrivilegeSystem } = await requestMemoize(requestMemoKeys.orgFindById(actor.orgId), () =>+ orgDAL.findById(actor.orgId)+ );++ const currentMappings = await externalGroupOrgRoleMappingDAL.find({ orgId: actor.orgId });+ const currentByGroupName = new Map(currentMappings.map((mapping) => [mapping.groupName, mapping]));+ const nextByGroupName = new Map(mappings.map((mapping) => [mapping.groupName, mapping]));++ const isSameRole = (a: { role: string; roleId?: string | null }, b: { role: string; roleId?: string | null }) =>+ a.role === b.role && (a.roleId ?? null) === (b.roleId ?? null);++ const grantedMappings = dto.mappings.filter(({ groupName, roleSlug }, index) => {+ const current = currentByGroupName.get(groupName);+ return roleNeedsPrivilegeBoundary(roleSlug) && (!current || !isSameRole(current, mappings[index]));+ });++ const replacedMappings = currentMappings.filter((current) => {+ const next = nextByGroupName.get(current.groupName);+ return current.role !== OrgMembershipRole.NoAccess && (!next || !isSameRole(current, next));+ });++ const replacedCustomRoleIds = replacedMappings.flatMap(({ roleId }) => (roleId ? [roleId] : []));+ const replacedCustomRoleSlugById = new Map(+ replacedCustomRoleIds.length+ ? (await roleDAL.find({ orgId: actor.orgId, $in: { id: replacedCustomRoleIds } })).map((role) => [+ role.id,+ role.slug+ ])+ : []+ );++ const boundaryChecks = [+ ...replacedMappings.flatMap((mapping) => {+ // a mapping whose custom role no longer resolves grants nothing, so there is no boundary to hold+ const roleSlug =+ mapping.role === OrgMembershipRole.Custom+ ? mapping.roleId && replacedCustomRoleSlugById.get(mapping.roleId)+ : mapping.role;+ return roleSlug+ ? [+ {+ roleSlug,+ baseMessage: `Failed to change the role mapping for group '${mapping.groupName}', which maps to role '${roleSlug}'`+ }+ ]+ : [];+ }),+ ...grantedMappings.map(({ groupName, roleSlug }) => ({+ roleSlug,+ baseMessage: `Failed to map group '${groupName}' to role '${roleSlug}'`+ }))+ ];++ if (boundaryChecks.length) {+ const roleSlugsToCheck = [...new Set(boundaryChecks.map(({ roleSlug }) => roleSlug))];+ const rolePermissions = await permissionService.getOrgPermissionByRoles(roleSlugsToCheck, actor.orgId);++ for (const { roleSlug, baseMessage } of boundaryChecks) {+ assertRoleSetBoundary({+ shouldUseNewPrivilegeSystem,+ opActions: OrgPermissionMemberActions.GrantPrivileges,+ opSubject: OrgPermissionSubjects.Member,+ actorPermission: permission,+ targetPermissions: [rolePermissions[roleSlugsToCheck.indexOf(roleSlug)]],+ baseMessage+ });+ }+ }+const data = await externalGroupOrgRoleMappingDAL.updateExternalGroupOrgRoleMappingForOrg(actor.orgId, mappings);return data;