Skip to content

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

feat: implemented addIdentitiesToGroup service and endpoint

Piyush Gupta6a8316dc0249
diff --git a/backend/src/ee/routes/v1/group-router.ts b/backend/src/ee/routes/v1/group-router.ts
index a84e7a0327..0f6b49cabe 100644
--- a/backend/src/ee/routes/v1/group-router.ts
+++ b/backend/src/ee/routes/v1/group-router.ts
@@ -325,6 +325,41 @@ export const registerGroupRouter = async (server: FastifyZodProvider) => {
}
});
+ server.route({
+ method: "POST",
+ 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.ADD_IDENTITY.id),
+ identityId: z.string().trim().describe(GROUPS.ADD_IDENTITY.identityId)
+ }),
+ response: {
+ 200: IdentitiesSchema.pick({
+ id: true,
+ name: true
+ })
+ }
+ },
+ handler: async (req) => {
+ const identity = await server.services.group.addIdentityToGroup({
+ 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;
+ }
+ });
+
server.route({
method: "DELETE",
url: "/:id/users/:username",
diff --git a/backend/src/ee/services/group/group-fns.ts b/backend/src/ee/services/group/group-fns.ts
index 739553dbb1..15f76ac093 100644
--- a/backend/src/ee/services/group/group-fns.ts
+++ b/backend/src/ee/services/group/group-fns.ts
@@ -5,10 +5,11 @@ import { crypto } from "@app/lib/crypto/cryptography";
import { BadRequestError, ForbiddenRequestError, NotFoundError, ScimRequestError } from "@app/lib/errors";
import {
+ TAddIdentitiesToGroup,
TAddUsersToGroup,
TAddUsersToGroupByUserIds,
TConvertPendingGroupAdditionsToGroupMemberships,
- TRemoveIdentitiesFromGroupByIdentityIds,
+ TRemoveIdentitiesFromGroup,
TRemoveUsersFromGroupByUserIds
} from "./group-types";
@@ -286,6 +287,67 @@ export const addUsersToGroupByUserIds = async ({
});
};
+/**
+ * Add identities with identity ids [identityIds] to group [group].
+ * @param {group} group - group to add identity(s) to
+ * @param {string[]} identityIds - id(s) of organization scoped identity(s) to add to group
+ */
+export const addIdentitiesToGroup = async ({
+ group,
+ identityIds,
+ identityDAL,
+ identityOrgMembershipDAL,
+ identityGroupMembershipDAL
+}: TAddIdentitiesToGroup) => {
+ const processAddition = async (tx: Knex) => {
+ const identityIdsSet = new Set(identityIds);
+ const identityIdsArray = Array.from(identityIdsSet);
+
+ const foundIdentities = await identityOrgMembershipDAL.findByIds(identityIdsArray, tx);
+
+ const existingIdentityOrgMembershipsIdentityIdsSet = new Set(foundIdentities.map((u) => u.id));
+
+ identityIdsArray.forEach((identityId) => {
+ if (!existingIdentityOrgMembershipsIdentityIdsSet.has(identityId)) {
+ throw new ForbiddenRequestError({
+ message: `Identity with id ${identityId} is not part of the organization`
+ });
+ }
+ });
+
+ // check if identity group membership already exists
+ const existingIdentityGroupMemberships = await identityGroupMembershipDAL.find(
+ {
+ groupId: group.id,
+ $in: {
+ identityId: identityIdsArray
+ }
+ },
+ { tx }
+ );
+
+ if (existingIdentityGroupMemberships.length) {
+ throw new BadRequestError({
+ message: `${identityIdsArray.length > 1 ? `Identities are` : `Identity is`} already part of the group ${group.slug}`
+ });
+ }
+
+ await identityGroupMembershipDAL.insertMany(
+ foundIdentities.map((identity) => ({
+ identityId: identity.id,
+ groupId: group.id
+ })),
+ tx
+ );
+
+ return foundIdentities;
+ };
+
+ return identityDAL.transaction(async (tx) => {
+ return processAddition(tx);
+ });
+};
+
/**
* Remove users with user ids [userIds] from group [group].
* - Users may be part of the group (non-pending + pending);
@@ -422,13 +484,18 @@ export const removeUsersFromGroupByUserIds = async ({
});
};
-export const removeIdentitiesFromGroupByIdentityIds = async ({
+/**
+ * Remove identities with identity ids [identityIds] from group [group].
+ * @param {group} group - group to remove identity(s) from
+ * @param {string[]} identityIds - id(s) of identity(s) to remove from group
+ */
+export const removeIdentitiesFromGroup = async ({
group,
identityIds,
identityDAL,
identityOrgMembershipDAL,
identityGroupMembershipDAL
-}: TRemoveIdentitiesFromGroupByIdentityIds) => {
+}: TRemoveIdentitiesFromGroup) => {
const processRemoval = async (tx: Knex) => {
const identityIdsSet = new Set(identityIds);
const identityIdsArray = Array.from(identityIdsSet);
diff --git a/backend/src/ee/services/group/group-service.ts b/backend/src/ee/services/group/group-service.ts
index 03304d39f5..dac1796cb2 100644
--- a/backend/src/ee/services/group/group-service.ts
+++ b/backend/src/ee/services/group/group-service.ts
@@ -21,11 +21,13 @@ import { constructPermissionErrorMessage, validatePrivilegeChangeOperation } fro
import { TPermissionServiceFactory } from "../permission/permission-service-types";
import { TGroupDALFactory } from "./group-dal";
import {
+ addIdentitiesToGroup,
addUsersToGroupByUserIds,
- removeIdentitiesFromGroupByIdentityIds,
+ removeIdentitiesFromGroup,
removeUsersFromGroupByUserIds
} from "./group-fns";
import {
+ TAddIdentityToGroupDTO,
TAddUserToGroupDTO,
TCreateGroupDTO,
TDeleteGroupDTO,
@@ -43,7 +45,7 @@ type TGroupServiceFactoryDep = {
userDAL: Pick<TUserDALFactory, "find" | "findUserEncKeyByUserIdsBatch" | "transaction" | "findUserByUsername">;
identityDAL: Pick<TIdentityDALFactory, "findOne" | "find" | "transaction">;
identityOrgMembershipDAL: Pick<TIdentityOrgDALFactory, "findByIds">;
- identityGroupMembershipDAL: Pick<TIdentityGroupMembershipDALFactory, "find" | "delete">;
+ identityGroupMembershipDAL: Pick<TIdentityGroupMembershipDALFactory, "find" | "delete" | "insertMany">;
groupDAL: Pick<
TGroupDALFactory,
| "create"
@@ -518,6 +520,80 @@ export const groupServiceFactory = ({
return users[0];
};
+ const addIdentityToGroup = async ({
+ id,
+ identityId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: TAddIdentityToGroupDTO) => {
+ 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);
+
+ // check if group with slug exists
+ 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.AddIdentities,
+ OrgPermissionSubjects.Groups,
+ permission,
+ rolePermissionDetails.permission
+ );
+
+ if (!permissionBoundary.isValid)
+ throw new PermissionBoundaryError({
+ message: constructPermissionErrorMessage(
+ "Failed to add identity to more privileged group",
+ shouldUseNewPrivilegeSystem,
+ OrgPermissionGroupActions.AddIdentities,
+ 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 addIdentitiesToGroup({
+ group,
+ identityIds: [identity.id],
+ identityDAL,
+ identityOrgMembershipDAL,
+ identityGroupMembershipDAL
+ });
+
+ return identities[0];
+ };
+
const removeUserFromGroup = async ({
id,
username,
@@ -663,7 +739,7 @@ export const groupServiceFactory = ({
message: `Failed to find identity with ID ${identityId}`
});
- const identities = await removeIdentitiesFromGroupByIdentityIds({
+ const identities = await removeIdentitiesFromGroup({
group,
identityIds: [identity.id],
identityDAL,
@@ -681,6 +757,7 @@ export const groupServiceFactory = ({
listGroupUsers,
listGroupProjects,
addUserToGroup,
+ addIdentityToGroup,
removeUserFromGroup,
removeIdentityFromGroup,
getGroupById
diff --git a/backend/src/ee/services/group/group-types.ts b/backend/src/ee/services/group/group-types.ts
index 10f673d202..6f483979ee 100644
--- a/backend/src/ee/services/group/group-types.ts
+++ b/backend/src/ee/services/group/group-types.ts
@@ -65,6 +65,11 @@ export type TAddUserToGroupDTO = {
username: string;
} & TGenericPermission;
+export type TAddIdentityToGroupDTO = {
+ id: string;
+ identityId: string;
+} & TGenericPermission;
+
export type TRemoveUserFromGroupDTO = {
id: string;
username: string;
@@ -102,6 +107,14 @@ export type TAddUsersToGroupByUserIds = {
tx?: Knex;
};
+export type TAddIdentitiesToGroup = {
+ group: TGroups;
+ identityIds: string[];
+ identityDAL: Pick<TIdentityDALFactory, "transaction">;
+ identityOrgMembershipDAL: Pick<TIdentityOrgDALFactory, "findByIds">;
+ identityGroupMembershipDAL: Pick<TIdentityGroupMembershipDALFactory, "find" | "insertMany">;
+};
+
export type TRemoveUsersFromGroupByUserIds = {
group: TGroups;
userIds: string[];
@@ -112,7 +125,7 @@ export type TRemoveUsersFromGroupByUserIds = {
tx?: Knex;
};
-export type TRemoveIdentitiesFromGroupByIdentityIds = {
+export type TRemoveIdentitiesFromGroup = {
group: TGroups;
identityIds: string[];
identityDAL: Pick<TIdentityDALFactory, "find" | "transaction">;
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index 0f81fe1b28..e5601dee18 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -120,6 +120,10 @@ export const GROUPS = {
id: "The ID of the group to add the user to.",
username: "The username of the user to add to the group."
},
+ ADD_IDENTITY: {
+ id: "The ID of the group to add the identity to.",
+ identityId: "The ID of the identity to add to the group."
+ },
GET_BY_ID: {
id: "The ID of the group to fetch."
},