Skip to content

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

feat: implemented listGroupIdentities endpoint and service

Piyush Gupta5fb0b590a1f8
diff --git a/backend/src/ee/routes/v1/group-router.ts b/backend/src/ee/routes/v1/group-router.ts
index 0f6b49cabe..56cc9b020e 100644
--- a/backend/src/ee/routes/v1/group-router.ts
+++ b/backend/src/ee/routes/v1/group-router.ts
@@ -2,6 +2,7 @@ import { z } from "zod";
import { GroupsSchema, IdentitiesSchema, OrgMembershipRole, ProjectsSchema, UsersSchema } from "@app/db/schemas";
import {
+ EFilterReturnedIdentities,
EFilterReturnedProjects,
EFilterReturnedUsers,
EGroupProjectsOrderBy
@@ -227,6 +228,56 @@ export const registerGroupRouter = async (server: FastifyZodProvider) => {
}
});
+ server.route({
+ method: "GET",
+ url: "/:id/identities",
+ config: {
+ rateLimit: readLimit
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.Groups],
+ params: z.object({
+ id: z.string().trim().describe(GROUPS.LIST_IDENTITIES.id)
+ }),
+ querystring: z.object({
+ offset: z.coerce.number().min(0).default(0).describe(GROUPS.LIST_IDENTITIES.offset),
+ limit: z.coerce.number().min(1).max(100).default(10).describe(GROUPS.LIST_IDENTITIES.limit),
+ search: z.string().trim().optional().describe(GROUPS.LIST_IDENTITIES.search),
+ filter: z.nativeEnum(EFilterReturnedIdentities).optional().describe(GROUPS.LIST_IDENTITIES.filterIdentities)
+ }),
+ response: {
+ 200: z.object({
+ identities: IdentitiesSchema.pick({
+ id: true,
+ name: true
+ })
+ .merge(
+ z.object({
+ isPartOfGroup: z.boolean(),
+ joinedGroupAt: z.date().nullable()
+ })
+ )
+ .array(),
+ totalCount: z.number()
+ })
+ }
+ },
+ handler: async (req) => {
+ const { identities, totalCount } = await server.services.group.listGroupIdentities({
+ id: req.params.id,
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ ...req.query
+ });
+
+ return { identities, totalCount };
+ }
+ });
+
server.route({
method: "GET",
url: "/:id/projects",
diff --git a/backend/src/ee/services/group/group-dal.ts b/backend/src/ee/services/group/group-dal.ts
index ced8410b76..e1f104f5df 100644
--- a/backend/src/ee/services/group/group-dal.ts
+++ b/backend/src/ee/services/group/group-dal.ts
@@ -6,7 +6,12 @@ import { DatabaseError } from "@app/lib/errors";
import { buildFindFilter, ormify, selectAllTableCols, TFindFilter, TFindOpt } from "@app/lib/knex";
import { OrderByDirection } from "@app/lib/types";
-import { EFilterReturnedProjects, EFilterReturnedUsers, EGroupProjectsOrderBy } from "./group-types";
+import {
+ EFilterReturnedIdentities,
+ EFilterReturnedProjects,
+ EFilterReturnedUsers,
+ EGroupProjectsOrderBy
+} from "./group-types";
export type TGroupDALFactory = ReturnType<typeof groupDALFactory>;
@@ -167,6 +172,82 @@ export const groupDALFactory = (db: TDbClient) => {
}
};
+ const findAllGroupPossibleIdentities = async ({
+ orgId,
+ groupId,
+ offset = 0,
+ limit,
+ search,
+ filter
+ }: {
+ orgId: string;
+ groupId: string;
+ offset?: number;
+ limit?: number;
+ search?: string;
+ filter?: EFilterReturnedIdentities;
+ }) => {
+ try {
+ const query = db
+ .replicaNode()(TableName.Membership)
+ .where(`${TableName.Membership}.scopeOrgId`, orgId)
+ .where(`${TableName.Membership}.scope`, AccessScope.Organization)
+ .whereNotNull(`${TableName.Membership}.actorIdentityId`)
+ .join(TableName.Identity, `${TableName.Membership}.actorIdentityId`, `${TableName.Identity}.id`)
+ .leftJoin(TableName.IdentityGroupMembership, (bd) => {
+ bd.on(`${TableName.IdentityGroupMembership}.identityId`, "=", `${TableName.Identity}.id`).andOn(
+ `${TableName.IdentityGroupMembership}.groupId`,
+ "=",
+ db.raw("?", [groupId])
+ );
+ })
+ .select(
+ db.ref("id").withSchema(TableName.Membership),
+ db.ref("groupId").withSchema(TableName.IdentityGroupMembership),
+ db.ref("createdAt").withSchema(TableName.IdentityGroupMembership).as("joinedGroupAt"),
+ db.ref("name").withSchema(TableName.Identity),
+ db.ref("id").withSchema(TableName.Identity).as("identityId"),
+ db.raw(`count(*) OVER() as total_count`)
+ )
+ .offset(offset)
+ .orderBy("name", "asc");
+
+ if (limit) {
+ void query.limit(limit);
+ }
+
+ if (search) {
+ void query.andWhereRaw(`LOWER("${TableName.Identity}"."name") ilike ?`, `%${search}%`);
+ }
+
+ switch (filter) {
+ case EFilterReturnedIdentities.ASSIGNED_IDENTITIES:
+ void query.andWhere(`${TableName.IdentityGroupMembership}.createdAt`, "is not", null);
+ break;
+ case EFilterReturnedIdentities.NON_ASSIGNED_IDENTITIES:
+ void query.andWhere(`${TableName.IdentityGroupMembership}.createdAt`, "is", null);
+ break;
+ default:
+ break;
+ }
+
+ const identities = await query;
+
+ return {
+ identities: identities.map(({ name, identityId, joinedGroupAt }) => ({
+ id: identityId,
+ name,
+ isPartOfGroup: !!groupId,
+ joinedGroupAt
+ })),
+ // @ts-expect-error col select is raw and not strongly typed
+ totalCount: Number(identities?.[0]?.total_count ?? 0)
+ };
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find all group identities" });
+ }
+ };
+
const findAllGroupProjects = async ({
orgId,
groupId,
@@ -314,6 +395,7 @@ export const groupDALFactory = (db: TDbClient) => {
findGroups,
findByOrgId,
findAllGroupPossibleMembers,
+ findAllGroupPossibleIdentities,
findAllGroupProjects,
findGroupsByProjectId,
findById,
diff --git a/backend/src/ee/services/group/group-service.ts b/backend/src/ee/services/group/group-service.ts
index 36ec57a637..687771296a 100644
--- a/backend/src/ee/services/group/group-service.ts
+++ b/backend/src/ee/services/group/group-service.ts
@@ -32,6 +32,7 @@ import {
TCreateGroupDTO,
TDeleteGroupDTO,
TGetGroupByIdDTO,
+ TListGroupIdentitiesDTO,
TListGroupProjectsDTO,
TListGroupUsersDTO,
TRemoveIdentityFromGroupDTO,
@@ -53,6 +54,7 @@ type TGroupServiceFactoryDep = {
| "update"
| "delete"
| "findAllGroupPossibleMembers"
+ | "findAllGroupPossibleIdentities"
| "findById"
| "transaction"
| "findAllGroupProjects"
@@ -391,6 +393,51 @@ export const groupServiceFactory = ({
return { users: members, totalCount };
};
+ const listGroupIdentities = async ({
+ id,
+ offset,
+ limit,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId,
+ search,
+ filter
+ }: TListGroupIdentitiesDTO) => {
+ 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.Read, OrgPermissionSubjects.Groups);
+
+ const group = await groupDAL.findOne({
+ orgId: actorOrgId,
+ id
+ });
+
+ if (!group)
+ throw new NotFoundError({
+ message: `Failed to find group with ID ${id}`
+ });
+
+ const { identities, totalCount } = await groupDAL.findAllGroupPossibleIdentities({
+ orgId: group.orgId,
+ groupId: group.id,
+ offset,
+ limit,
+ search,
+ filter
+ });
+
+ return { identities, totalCount };
+ };
+
const listGroupProjects = async ({
id,
offset,
@@ -747,6 +794,7 @@ export const groupServiceFactory = ({
updateGroup,
deleteGroup,
listGroupUsers,
+ listGroupIdentities,
listGroupProjects,
addUserToGroup,
addIdentityToGroup,
diff --git a/backend/src/ee/services/group/group-types.ts b/backend/src/ee/services/group/group-types.ts
index 6f483979ee..9203679e89 100644
--- a/backend/src/ee/services/group/group-types.ts
+++ b/backend/src/ee/services/group/group-types.ts
@@ -46,6 +46,14 @@ export type TListGroupUsersDTO = {
filter?: EFilterReturnedUsers;
} & TGenericPermission;
+export type TListGroupIdentitiesDTO = {
+ id: string;
+ offset: number;
+ limit: number;
+ search?: string;
+ filter?: EFilterReturnedIdentities;
+} & TGenericPermission;
+
export type TListGroupProjectsDTO = {
id: string;
offset: number;
@@ -152,6 +160,11 @@ export enum EFilterReturnedUsers {
NON_MEMBERS = "nonMembers"
}
+export enum EFilterReturnedIdentities {
+ ASSIGNED_IDENTITIES = "assignedIdentities",
+ NON_ASSIGNED_IDENTITIES = "nonAssignedIdentities"
+}
+
export enum EFilterReturnedProjects {
ASSIGNED_PROJECTS = "assignedProjects",
UNASSIGNED_PROJECTS = "unassignedProjects"
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index e5601dee18..b959158a67 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -106,6 +106,14 @@ export const GROUPS = {
filterUsers:
"Whether to filter the list of returned users. 'existingMembers' will only return existing users in the group, 'nonMembers' will only return users not in the group, undefined will return all users in the organization."
},
+ LIST_IDENTITIES: {
+ id: "The ID of the group to list identities for.",
+ offset: "The offset to start from. If you enter 10, it will start from the 10th identity.",
+ limit: "The number of identities to return.",
+ search: "The text string that identity name will be filtered by.",
+ filterIdentities:
+ "Whether to filter the list of returned identities. 'assignedIdentities' will only return identities assigned to the group, 'nonAssignedIdentities' will only return identities not assigned to the group, undefined will return all identities in the organization."
+ },
LIST_PROJECTS: {
id: "The ID of the group to list projects for.",
offset: "The offset to start from. If you enter 10, it will start from the 10th project.",