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: implemented removeIdentityFromGroup service and endpoint
Piyush Gupta22cea0052c23
diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.tsindex 603df5f6ca..b11eac32b7 100644--- a/backend/src/@types/knex.d.ts+++ b/backend/src/@types/knex.d.ts@@ -146,6 +146,9 @@ import {TIdentityGcpAuths,TIdentityGcpAuthsInsert,TIdentityGcpAuthsUpdate,+ TIdentityGroupMembership,+ TIdentityGroupMembershipInsert,+ TIdentityGroupMembershipUpdate,TIdentityJwtAuths,TIdentityJwtAuthsInsert,TIdentityJwtAuthsUpdate,@@ -823,6 +826,11 @@ declare module "knex/types/tables" {TUserGroupMembershipInsert,TUserGroupMembershipUpdate>;+ [TableName.IdentityGroupMembership]: KnexOriginal.CompositeTableType<+ TIdentityGroupMembership,+ TIdentityGroupMembershipInsert,+ TIdentityGroupMembershipUpdate+ >;[TableName.GroupProjectMembership]: KnexOriginal.CompositeTableType<TGroupProjectMemberships,TGroupProjectMembershipsInsert,diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.tsindex 78dcb1980c..aae5496720 100644--- a/backend/src/db/schemas/index.ts+++ b/backend/src/db/schemas/index.ts@@ -46,6 +46,7 @@ export * from "./identity-alicloud-auths";export * from "./identity-aws-auths";export * from "./identity-azure-auths";export * from "./identity-gcp-auths";+export * from "./identity-group-membership";export * from "./identity-jwt-auths";export * from "./identity-kubernetes-auths";export * from "./identity-metadata";diff --git a/backend/src/ee/routes/v1/group-router.ts b/backend/src/ee/routes/v1/group-router.tsindex 4696bef26d..a84e7a0327 100644--- a/backend/src/ee/routes/v1/group-router.ts+++ b/backend/src/ee/routes/v1/group-router.ts@@ -1,6 +1,6 @@import { z } from "zod";-import { GroupsSchema, OrgMembershipRole, ProjectsSchema, UsersSchema } from "@app/db/schemas";+import { GroupsSchema, IdentitiesSchema, OrgMembershipRole, ProjectsSchema, UsersSchema } from "@app/db/schemas";import {EFilterReturnedProjects,EFilterReturnedUsers,@@ -362,4 +362,39 @@ export const registerGroupRouter = async (server: FastifyZodProvider) => {return user;}});++ server.route({+ method: "DELETE",+ url: "/:id/identities/:identityId",+ config: {+ rateLimit: writeLimit+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ schema: {+ hide: false,+ tags: [ApiDocsTags.Groups],+ params: z.object({+ id: z.string().trim().describe(GROUPS.DELETE_IDENTITY.id),+ identityId: z.string().trim().describe(GROUPS.DELETE_IDENTITY.identityId)+ }),+ response: {+ 200: IdentitiesSchema.pick({+ id: true,+ name: true+ })+ }+ },+ handler: async (req) => {+ const identity = await server.services.group.removeIdentityFromGroup({+ id: req.params.id,+ identityId: req.params.identityId,+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId+ });++ return identity;+ }+ });};diff --git a/backend/src/ee/services/group/group-fns.ts b/backend/src/ee/services/group/group-fns.tsindex c4384cc4e2..739553dbb1 100644--- a/backend/src/ee/services/group/group-fns.ts+++ b/backend/src/ee/services/group/group-fns.ts@@ -8,6 +8,7 @@ import {TAddUsersToGroup,TAddUsersToGroupByUserIds,TConvertPendingGroupAdditionsToGroupMemberships,+ TRemoveIdentitiesFromGroupByIdentityIds,TRemoveUsersFromGroupByUserIds} from "./group-types";@@ -421,6 +422,65 @@ export const removeUsersFromGroupByUserIds = async ({});};+export const removeIdentitiesFromGroupByIdentityIds = async ({+ group,+ identityIds,+ identityDAL,+ identityOrgMembershipDAL,+ identityGroupMembershipDAL+}: TRemoveIdentitiesFromGroupByIdentityIds) => {+ const processRemoval = async (tx: Knex) => {+ const identityIdsSet = new Set(identityIds);+ const identityIdsArray = Array.from(identityIdsSet);++ const foundIdentities = await identityOrgMembershipDAL.findByIds(identityIdsArray, tx);++ if (foundIdentities.length !== identityIdsArray.length) {+ throw new NotFoundError({+ message: `Identities not found`+ });+ }++ const existingIdentityGroupMemberships = await identityGroupMembershipDAL.find(+ {+ groupId: group.id,+ $in: {+ identityId: identityIdsArray+ }+ },+ { tx }+ );++ const existingIdentityGroupMembershipsIdentityIdsSet = new Set(+ existingIdentityGroupMemberships.map((u) => u.identityId)+ );++ identityIdsArray.forEach((identityId) => {+ if (!existingIdentityGroupMembershipsIdentityIdsSet.has(identityId)) {+ throw new ForbiddenRequestError({+ message: `Identities are not part of the group ${group.slug}`+ });+ }+ });++ await identityGroupMembershipDAL.delete(+ {+ groupId: group.id,+ $in: {+ identityId: identityIdsArray+ }+ },+ tx+ );++ return foundIdentities;+ };++ return identityDAL.transaction(async (tx) => {+ return processRemoval(tx);+ });+};+/*** Convert pending group additions for users with ids [userIds] to group memberships.* @param {string[]} userIds - id(s) of user(s) to try to convert pending group additions to group membershipsdiff --git a/backend/src/ee/services/group/group-service.ts b/backend/src/ee/services/group/group-service.tsindex 1a6a046a6b..03304d39f5 100644--- a/backend/src/ee/services/group/group-service.ts+++ b/backend/src/ee/services/group/group-service.ts@@ -5,6 +5,8 @@ import { AccessScope, OrganizationActionScope, OrgMembershipRole, TRoles } fromimport { TOidcConfigDALFactory } from "@app/ee/services/oidc/oidc-config-dal";import { BadRequestError, NotFoundError, PermissionBoundaryError, UnauthorizedError } from "@app/lib/errors";import { alphaNumericNanoId } from "@app/lib/nanoid";+import { TIdentityDALFactory } from "@app/services/identity/identity-dal";+import { TIdentityOrgDALFactory } from "@app/services/identity/identity-org-dal";import { TMembershipRoleDALFactory } from "@app/services/membership/membership-role-dal";import { TMembershipGroupDALFactory } from "@app/services/membership-group/membership-group-dal";import { TOrgDALFactory } from "@app/services/org/org-dal";@@ -18,7 +20,11 @@ import { OrgPermissionGroupActions, OrgPermissionSubjects } from "../permission/import { constructPermissionErrorMessage, validatePrivilegeChangeOperation } from "../permission/permission-fns";import { TPermissionServiceFactory } from "../permission/permission-service-types";import { TGroupDALFactory } from "./group-dal";-import { addUsersToGroupByUserIds, removeUsersFromGroupByUserIds } from "./group-fns";+import {+ addUsersToGroupByUserIds,+ removeIdentitiesFromGroupByIdentityIds,+ removeUsersFromGroupByUserIds+} from "./group-fns";import {TAddUserToGroupDTO,TCreateGroupDTO,@@ -26,13 +32,18 @@ import {TGetGroupByIdDTO,TListGroupProjectsDTO,TListGroupUsersDTO,+ TRemoveIdentityFromGroupDTO,TRemoveUserFromGroupDTO,TUpdateGroupDTO} from "./group-types";+import { TIdentityGroupMembershipDALFactory } from "./identity-group-membership-dal";import { TUserGroupMembershipDALFactory } from "./user-group-membership-dal";type TGroupServiceFactoryDep = {userDAL: Pick<TUserDALFactory, "find" | "findUserEncKeyByUserIdsBatch" | "transaction" | "findUserByUsername">;+ identityDAL: Pick<TIdentityDALFactory, "findOne" | "find" | "transaction">;+ identityOrgMembershipDAL: Pick<TIdentityOrgDALFactory, "findByIds">;+ identityGroupMembershipDAL: Pick<TIdentityGroupMembershipDALFactory, "find" | "delete">;groupDAL: Pick<TGroupDALFactory,| "create"@@ -65,6 +76,9 @@ type TGroupServiceFactoryDep = {export type TGroupServiceFactory = ReturnType<typeof groupServiceFactory>;export const groupServiceFactory = ({+ identityDAL,+ identityOrgMembershipDAL,+ identityGroupMembershipDAL,userDAL,groupDAL,orgDAL,@@ -587,6 +601,79 @@ export const groupServiceFactory = ({return users[0];};+ const removeIdentityFromGroup = async ({+ id,+ identityId,+ actor,+ actorId,+ actorAuthMethod,+ actorOrgId+ }: TRemoveIdentityFromGroupDTO) => {+ if (!actorOrgId) throw new UnauthorizedError({ message: "No organization ID provided in request" });++ const { permission } = await permissionService.getOrgPermission({+ scope: OrganizationActionScope.Any,+ actor,+ actorId,+ orgId: actorOrgId,+ actorAuthMethod,+ actorOrgId+ });+ ForbiddenError.from(permission).throwUnlessCan(OrgPermissionGroupActions.Edit, OrgPermissionSubjects.Groups);++ const group = await groupDAL.findOne({+ orgId: actorOrgId,+ id+ });++ if (!group)+ throw new NotFoundError({+ message: `Failed to find group with ID ${id}`+ });++ const [rolePermissionDetails] = await permissionService.getOrgPermissionByRoles([group.role], actorOrgId);+ const { shouldUseNewPrivilegeSystem } = await orgDAL.findById(actorOrgId);++ // check if user has broader or equal to privileges than group+ const permissionBoundary = validatePrivilegeChangeOperation(+ shouldUseNewPrivilegeSystem,+ OrgPermissionGroupActions.RemoveIdentities,+ OrgPermissionSubjects.Groups,+ permission,+ rolePermissionDetails.permission+ );+ if (!permissionBoundary.isValid)+ throw new PermissionBoundaryError({+ message: constructPermissionErrorMessage(+ "Failed to remove identity from more privileged group",+ shouldUseNewPrivilegeSystem,+ OrgPermissionGroupActions.RemoveIdentities,+ OrgPermissionSubjects.Groups+ ),+ details: { missingPermissions: permissionBoundary.missingPermissions }+ });++ const identity = await identityDAL.findOne({+ orgId: actorOrgId,+ id: identityId+ });++ if (!identity)+ throw new NotFoundError({+ message: `Failed to find identity with ID ${identityId}`+ });++ const identities = await removeIdentitiesFromGroupByIdentityIds({+ group,+ identityIds: [identity.id],+ identityDAL,+ identityOrgMembershipDAL,+ identityGroupMembershipDAL+ });++ return identities[0];+ };+return {createGroup,updateGroup,@@ -595,6 +682,7 @@ export const groupServiceFactory = ({listGroupProjects,addUserToGroup,removeUserFromGroup,+ removeIdentityFromGroup,getGroupById};};diff --git a/backend/src/ee/services/group/group-types.ts b/backend/src/ee/services/group/group-types.tsindex 335b6d72bb..10f673d202 100644--- a/backend/src/ee/services/group/group-types.ts+++ b/backend/src/ee/services/group/group-types.ts@@ -3,6 +3,8 @@ import { Knex } from "knex";import { TGroups } from "@app/db/schemas";import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";import { OrderByDirection, TGenericPermission } from "@app/lib/types";+import { TIdentityDALFactory } from "@app/services/identity/identity-dal";+import { TIdentityOrgDALFactory } from "@app/services/identity/identity-org-dal";import { TMembershipGroupDALFactory } from "@app/services/membership-group/membership-group-dal";import { TOrgDALFactory } from "@app/services/org/org-dal";import { TProjectDALFactory } from "@app/services/project/project-dal";@@ -10,6 +12,8 @@ import { TProjectBotDALFactory } from "@app/services/project-bot/project-bot-dalimport { TProjectKeyDALFactory } from "@app/services/project-key/project-key-dal";import { TUserDALFactory } from "@app/services/user/user-dal";+import { TIdentityGroupMembershipDALFactory } from "./identity-group-membership-dal";+export type TCreateGroupDTO = {name: string;slug?: string;@@ -66,6 +70,11 @@ export type TRemoveUserFromGroupDTO = {username: string;} & TGenericPermission;+export type TRemoveIdentityFromGroupDTO = {+ id: string;+ identityId: string;+} & TGenericPermission;+// group fns typesexport type TAddUsersToGroup = {@@ -103,6 +112,14 @@ export type TRemoveUsersFromGroupByUserIds = {tx?: Knex;};+export type TRemoveIdentitiesFromGroupByIdentityIds = {+ group: TGroups;+ identityIds: string[];+ identityDAL: Pick<TIdentityDALFactory, "find" | "transaction">;+ identityOrgMembershipDAL: Pick<TIdentityOrgDALFactory, "findByIds">;+ identityGroupMembershipDAL: Pick<TIdentityGroupMembershipDALFactory, "find" | "delete">;+};+export type TConvertPendingGroupAdditionsToGroupMemberships = {userIds: string[];userDAL: Pick<TUserDALFactory, "findUserEncKeyByUserIdsBatch" | "transaction" | "find" | "findById">;diff --git a/backend/src/ee/services/group/identity-group-membership-dal.ts b/backend/src/ee/services/group/identity-group-membership-dal.tsnew file mode 100644index 0000000000..7b6d67244d--- /dev/null+++ b/backend/src/ee/services/group/identity-group-membership-dal.ts@@ -0,0 +1,13 @@+import { TDbClient } from "@app/db";+import { TableName } from "@app/db/schemas";+import { ormify } from "@app/lib/knex";++export type TIdentityGroupMembershipDALFactory = ReturnType<typeof identityGroupMembershipDALFactory>;++export const identityGroupMembershipDALFactory = (db: TDbClient) => {+ const identityGroupMembershipOrm = ormify(db, TableName.IdentityGroupMembership);++ return {+ ...identityGroupMembershipOrm+ };+};diff --git a/backend/src/ee/services/permission/org-permission.ts b/backend/src/ee/services/permission/org-permission.tsindex 743dcd63fb..0c00c8b408 100644--- a/backend/src/ee/services/permission/org-permission.ts+++ b/backend/src/ee/services/permission/org-permission.ts@@ -88,8 +88,10 @@ export enum OrgPermissionGroupActions {Edit = "edit",Delete = "delete",GrantPrivileges = "grant-privileges",+ AddIdentities = "add-identities",AddMembers = "add-members",- RemoveMembers = "remove-members"+ RemoveMembers = "remove-members",+ RemoveIdentities = "remove-identities"}export enum OrgPermissionBillingActions {@@ -381,8 +383,10 @@ const buildAdminPermission = () => {can(OrgPermissionGroupActions.Edit, OrgPermissionSubjects.Groups);can(OrgPermissionGroupActions.Delete, OrgPermissionSubjects.Groups);can(OrgPermissionGroupActions.GrantPrivileges, OrgPermissionSubjects.Groups);+ can(OrgPermissionGroupActions.AddIdentities, OrgPermissionSubjects.Groups);can(OrgPermissionGroupActions.AddMembers, OrgPermissionSubjects.Groups);can(OrgPermissionGroupActions.RemoveMembers, OrgPermissionSubjects.Groups);+ can(OrgPermissionGroupActions.RemoveIdentities, OrgPermissionSubjects.Groups);can(OrgPermissionBillingActions.Read, OrgPermissionSubjects.Billing);can(OrgPermissionBillingActions.ManageBilling, OrgPermissionSubjects.Billing);diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex 3c89722484..0f81fe1b28 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -126,6 +126,10 @@ export const GROUPS = {DELETE_USER: {id: "The ID of the group to remove the user from.",username: "The username of the user to remove from the group."+ },+ DELETE_IDENTITY: {+ id: "The ID of the group to remove the identity from.",+ identityId: "The ID of the identity to remove from the group."}} as const;diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex ec9e56880a..182ee0ddc1 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -46,6 +46,7 @@ import { githubOrgSyncDALFactory } from "@app/ee/services/github-org-sync/githubimport { githubOrgSyncServiceFactory } from "@app/ee/services/github-org-sync/github-org-sync-service";import { groupDALFactory } from "@app/ee/services/group/group-dal";import { groupServiceFactory } from "@app/ee/services/group/group-service";+import { identityGroupMembershipDALFactory } from "@app/ee/services/group/identity-group-membership-dal";import { userGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";import { isHsmActiveAndEnabled } from "@app/ee/services/hsm/hsm-fns";import { THsmServiceFactory } from "@app/ee/services/hsm/hsm-service";@@ -452,6 +453,7 @@ export const registerRoutes = async (const identityMetadataDAL = identityMetadataDALFactory(db);const identityAccessTokenDAL = identityAccessTokenDALFactory(db);const identityOrgMembershipDAL = identityOrgDALFactory(db);+ const identityGroupMembershipDAL = identityGroupMembershipDALFactory(db);const identityProjectDAL = identityProjectDALFactory(db);const identityAuthTemplateDAL = identityAuthTemplateDALFactory(db);@@ -736,6 +738,9 @@ export const registerRoutes = async (membershipGroupDAL});const groupService = groupServiceFactory({+ identityDAL,+ identityOrgMembershipDAL,+ identityGroupMembershipDAL,userDAL,groupDAL,orgDAL,diff --git a/backend/src/services/identity/identity-org-dal.ts b/backend/src/services/identity/identity-org-dal.tsindex 117195ca71..17de47ad6b 100644--- a/backend/src/services/identity/identity-org-dal.ts+++ b/backend/src/services/identity/identity-org-dal.ts@@ -674,5 +674,21 @@ export const identityOrgDALFactory = (db: TDbClient) => {}};- return { find, findOne, countAllOrgIdentities, searchIdentities };+ const findByIds = async (identityIds: string[], tx?: Knex) => {+ try {+ const identities = await (tx || db.replicaNode())(TableName.Identity)+ .join(TableName.Membership, `${TableName.Membership}.actorIdentityId`, `${TableName.Identity}.id`)+ .where(`${TableName.Membership}.scope`, AccessScope.Organization)+ .whereNotNull(`${TableName.Membership}.actorIdentityId`)+ .whereNull(`${TableName.Identity}.projectId`)+ .whereIn(`${TableName.Identity}.id`, identityIds)+ .select(selectAllTableCols(TableName.Identity));++ return identities;+ } catch (error) {+ throw new DatabaseError({ error, name: "findByIds" });+ }+ };++ return { find, findOne, countAllOrgIdentities, searchIdentities, findByIds };};