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
use v2
Thiago Araujo da Silvab051604e05f5
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex 66b7f3ca9b..28a9b31f53 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -208,6 +208,19 @@ export const IDENTITIES = {limit: "The number of identities to return.",orderBy: "The column to order identities by.",orderDirection: "The direction to order identities in."+ },+ SEARCH_V2: {+ scope:+ "Array of scopes to search across. Accepts 'organization' to include organization-level identities and/or 'project' to include identities from projects the caller has access to. Defaults to ['organization'].",+ search: {+ desc: "The filters to apply to the search.",+ name: "The name of the identity to filter by.",+ role: "The role of the identity to filter by."+ },+ offset: "The offset to start from. If you enter 10, it will start from the 10th identity.",+ limit: "The number of identities to return.",+ orderBy: "The column to order identities by.",+ orderDirection: "The direction to order identities in."}} as const;diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex a86e0890bf..1594f70498 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -2000,7 +2000,8 @@ export const registerRoutes = async (keyStore,orgDAL,membershipIdentityDAL,- membershipRoleDAL+ membershipRoleDAL,+ projectDAL});const identityAccessTokenService = identityAccessTokenServiceFactory({diff --git a/backend/src/server/routes/v2/identity-router.ts b/backend/src/server/routes/v2/identity-router.tsnew file mode 100644index 0000000000..72416dcb04--- /dev/null+++ b/backend/src/server/routes/v2/identity-router.ts@@ -0,0 +1,166 @@+import { z } from "zod";++import { IdentitiesSchema, OrgRolesSchema } from "@app/db/schemas";+import { ApiDocsTags, IDENTITIES } from "@app/lib/api-docs";+import { buildSearchZodSchema, SearchResourceOperators } from "@app/lib/search-resource/search";+import { OrderByDirection } from "@app/lib/types";+import { CharacterType, zodValidateCharacters } from "@app/lib/validator/validate-string";+import { readLimit } from "@app/server/config/rateLimiter";+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";+import { AuthMode } from "@app/services/auth/auth-type";+import { OrgIdentityOrderBy, SearchIdentitiesScope } from "@app/services/identity/identity-types";++const searchResourceZodValidate = zodValidateCharacters([+ CharacterType.AlphaNumeric,+ CharacterType.Spaces,+ CharacterType.Underscore,+ CharacterType.Hyphen,+ CharacterType.ForwardSlash+]);++const roleSchema = z.object({+ id: z.string(),+ role: z.string(),+ customRoleId: z.string().nullable().optional(),+ customRoleName: z.string().nullable().optional(),+ customRoleSlug: z.string().nullable().optional(),+ customRoleDescription: z.string().nullable().optional(),+ customRolePermissions: z.unknown().nullable().optional(),+ isTemporary: z.boolean(),+ temporaryMode: z.string().nullable().optional(),+ temporaryRange: z.string().nullable().optional(),+ temporaryAccessStartTime: z.date().nullable().optional(),+ temporaryAccessEndTime: z.date().nullable().optional()+});++const identityMembershipResponseSchema = z.object({+ id: z.string(),+ identityId: z.string(),+ scope: z.nativeEnum(SearchIdentitiesScope),+ orgId: z.string(),+ projectId: z.string().nullable().optional(),+ project: z+ .object({+ id: z.string(),+ name: z.string(),+ slug: z.string(),+ type: z.string()+ })+ .nullable()+ .optional(),+ createdAt: z.date(),+ updatedAt: z.date(),+ lastLoginAuthMethod: z.string().nullable().optional(),+ lastLoginTime: z.date().nullable().optional(),+ roles: z.array(roleSchema),+ /** @deprecated use `roles` */+ customRole: OrgRolesSchema.pick({+ id: true,+ name: true,+ slug: true,+ permissions: true,+ description: true+ }).optional(),+ identity: IdentitiesSchema.pick({ name: true, id: true, hasDeleteProtection: true, orgId: true }).extend({+ authMethods: z.array(z.string())+ })+});++export const registerIdentityRouter = async (server: FastifyZodProvider) => {+ server.route({+ method: "POST",+ url: "/search",+ config: {+ rateLimit: readLimit+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ schema: {+ hide: false,+ operationId: "searchMachineIdentitiesV2",+ tags: [ApiDocsTags.Identities],+ description:+ "Search machine identities across organization and/or project scopes. Returns identities the caller has access to, each annotated with all roles assigned to that membership.",+ security: [+ {+ bearerAuth: []+ }+ ],+ body: z.object({+ scope: z+ .array(z.nativeEnum(SearchIdentitiesScope))+ .min(1)+ .default([SearchIdentitiesScope.Organization])+ .describe(IDENTITIES.SEARCH_V2.scope)+ .optional(),+ orderBy: z+ .nativeEnum(OrgIdentityOrderBy)+ .default(OrgIdentityOrderBy.Name)+ .describe(IDENTITIES.SEARCH_V2.orderBy)+ .optional(),+ orderDirection: z+ .nativeEnum(OrderByDirection)+ .default(OrderByDirection.ASC)+ .describe(IDENTITIES.SEARCH_V2.orderDirection)+ .optional(),+ limit: z.number().max(100).default(50).describe(IDENTITIES.SEARCH_V2.limit),+ offset: z.number().default(0).describe(IDENTITIES.SEARCH_V2.offset),+ search: buildSearchZodSchema(+ z+ .object({+ name: z+ .union([+ searchResourceZodValidate(z.string().max(255), "Name"),+ z+ .object({+ [SearchResourceOperators.$eq]: searchResourceZodValidate(z.string().max(255), "Name $eq"),+ [SearchResourceOperators.$contains]: searchResourceZodValidate(+ z.string().max(255),+ "Name $contains"+ ),+ [SearchResourceOperators.$in]: searchResourceZodValidate(z.string().max(255), "Name $in").array()+ })+ .partial()+ ])+ .describe(IDENTITIES.SEARCH_V2.search.name),+ role: z+ .union([+ searchResourceZodValidate(z.string().max(255), "Role"),+ z+ .object({+ [SearchResourceOperators.$eq]: searchResourceZodValidate(z.string().max(255), "Role $eq"),+ [SearchResourceOperators.$in]: searchResourceZodValidate(z.string().max(255), "Role $in").array()+ })+ .partial()+ ])+ .describe(IDENTITIES.SEARCH_V2.search.role)+ })+ .describe(IDENTITIES.SEARCH_V2.search.desc)+ .partial()+ )+ }),+ response: {+ 200: z.object({+ identities: identityMembershipResponseSchema.array(),+ totalCount: z.number()+ })+ }+ },+ handler: async (req) => {+ const { identityMemberships, totalCount } = await server.services.identityV1.searchOrgIdentitiesV2({+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId,+ orgId: req.permission.orgId,+ searchFilter: req.body.search,+ scope: req.body.scope ?? [SearchIdentitiesScope.Organization],+ limit: req.body.limit,+ offset: req.body.offset,+ orderBy: req.body.orderBy,+ orderDirection: req.body.orderDirection+ });++ return { identities: identityMemberships, totalCount };+ }+ });+};diff --git a/backend/src/server/routes/v2/index.ts b/backend/src/server/routes/v2/index.tsindex 24ca8c2b50..c0c9ac72e4 100644--- a/backend/src/server/routes/v2/index.ts+++ b/backend/src/server/routes/v2/index.ts@@ -6,6 +6,7 @@ import { registerDeprecatedIdentityProjectRouter } from "./deprecated-identity-pimport { registerDeprecatedProjectMembershipRouter } from "./deprecated-project-membership-router";import { registerDeprecatedProjectRouter } from "./deprecated-project-router";import { registerIdentityOrgRouter } from "./identity-org-router";+import { registerIdentityRouter } from "./identity-router";import { registerMfaRouter } from "./mfa-router";import { registerMfaSessionRouter } from "./mfa-session-router";import { registerOrgRouter } from "./organization-router";@@ -42,6 +43,8 @@ export const registerV2Routes = async (server: FastifyZodProvider) => {{ prefix: "/organizations" });+ await server.register(registerIdentityRouter, { prefix: "/identities" });+await server.register(registerSecretFolderRouter, { prefix: "/folders" });await server.register(registerSecretImportRouter, { prefix: "/secret-imports" });diff --git a/backend/src/services/identity/identity-org-dal.ts b/backend/src/services/identity/identity-org-dal.tsindex cc481cf89c..c373f02114 100644--- a/backend/src/services/identity/identity-org-dal.ts+++ b/backend/src/services/identity/identity-org-dal.ts@@ -27,7 +27,9 @@ import { buildKnexFilterForSearchResource } from "@app/lib/search-resource/db";import { OrderByDirection } from "@app/lib/types";import {OrgIdentityOrderBy,+ SearchIdentitiesScope,TListOrgIdentitiesByOrgIdDTO,+ TSearchIdentitiesV2DAL,TSearchOrgIdentitiesByOrgIdDAL} from "@app/services/identity/identity-types";@@ -698,5 +700,359 @@ export const identityOrgDALFactory = (db: TDbClient) => {}};- return { find, findOne, countAllOrgIdentities, searchIdentities };+ const searchIdentitiesV2 = async (+ {+ limit,+ offset = 0,+ orderBy = OrgIdentityOrderBy.Name,+ orderDirection = OrderByDirection.ASC,+ searchFilter,+ orgId,+ scope,+ accessibleProjectIds+ }: TSearchIdentitiesV2DAL,+ tx?: Knex+ ) => {+ try {+ const includeOrgScope = scope.includes(SearchIdentitiesScope.Organization);+ const includeProjectScope = scope.includes(SearchIdentitiesScope.Project);++ const applyScopeFilter = (qb: Knex.QueryBuilder) => {+ void qb.whereNotNull(`${TableName.Membership}.actorIdentityId`);++ const orgScopeBranch = (sub: Knex.QueryBuilder) => {+ void sub+ .where(`${TableName.Membership}.scope`, AccessScope.Organization)+ .where(`${TableName.Membership}.scopeOrgId`, orgId);+ };++ const projectScopeBranch = (sub: Knex.QueryBuilder) => {+ if (accessibleProjectIds.length === 0) {+ void sub.whereRaw("1 = 0");+ } else {+ void sub+ .where(`${TableName.Membership}.scope`, AccessScope.Project)+ .where(`${TableName.Membership}.scopeOrgId`, orgId)+ .whereIn(`${TableName.Membership}.scopeProjectId`, accessibleProjectIds);+ }+ };++ if (includeOrgScope && includeProjectScope) {+ void qb.where((nested) => {+ void nested.where((sub) => orgScopeBranch(sub)).orWhere((sub) => projectScopeBranch(sub));+ });+ } else if (includeOrgScope) {+ orgScopeBranch(qb);+ } else if (includeProjectScope) {+ projectScopeBranch(qb);+ } else {+ void qb.whereRaw("1 = 0");+ }+ };++ const searchedMemberships = (tx || db.replicaNode())(TableName.Membership)+ .join(TableName.Identity, `${TableName.Identity}.id`, `${TableName.Membership}.actorIdentityId`)+ .leftJoin(TableName.MembershipRole, `${TableName.MembershipRole}.membershipId`, `${TableName.Membership}.id`)+ .leftJoin(TableName.Role, `${TableName.MembershipRole}.customRoleId`, `${TableName.Role}.id`)+ .where(applyScopeFilter)+ .groupBy(`${TableName.Membership}.id`, `${TableName.Identity}.name`)+ .select(`${TableName.Membership}.id`)+ .select(db.ref("name").withSchema(TableName.Identity).as("identityName"))+ .select<{ id: string; identityName: string; roleSort: string; total_count: string }>(+ db.raw(`MIN(COALESCE(??, ??)) as "roleSort"`, [`${TableName.Role}.slug`, `${TableName.MembershipRole}.role`])+ )+ .select<{ id: string; identityName: string; roleSort: string; total_count: string }>(+ db.raw(`COUNT(*) OVER() as total_count`)+ );++ if (searchFilter) {+ buildKnexFilterForSearchResource(searchedMemberships, searchFilter, (attr) => {+ switch (attr) {+ case "role":+ return [`${TableName.Role}.slug`, `${TableName.MembershipRole}.role`];+ case "name":+ return `${TableName.Identity}.name`;+ default:+ throw new BadRequestError({ message: `Invalid ${String(attr)} provided` });+ }+ });+ }++ if (orderBy === OrgIdentityOrderBy.Role) {+ void searchedMemberships.orderBy("roleSort", orderDirection);+ } else {+ void searchedMemberships.orderBy("identityName", orderDirection);+ }++ if (limit) {+ void searchedMemberships.offset(offset).limit(limit);+ }++ const searchedMembershipsSubquery = searchedMemberships.as("searchedMemberships");+ type TSubquery = Awaited<typeof searchedMemberships>;++ const query = (tx || db.replicaNode())(TableName.Membership)+ .join<TSubquery>(searchedMembershipsSubquery, `${TableName.Membership}.id`, "searchedMemberships.id")+ .join(TableName.Identity, `${TableName.Identity}.id`, `${TableName.Membership}.actorIdentityId`)+ .join(TableName.MembershipRole, `${TableName.MembershipRole}.membershipId`, `${TableName.Membership}.id`)+ .leftJoin(TableName.Role, `${TableName.MembershipRole}.customRoleId`, `${TableName.Role}.id`)+ .leftJoin(TableName.Project, `${TableName.Project}.id`, `${TableName.Membership}.scopeProjectId`)+ .leftJoin(TableName.IdentityMetadata, (queryBuilder) => {+ void queryBuilder.on(`${TableName.Membership}.actorIdentityId`, `${TableName.IdentityMetadata}.identityId`);+ })+ .leftJoin(+ TableName.IdentityUniversalAuth,+ `${TableName.Membership}.actorIdentityId`,+ `${TableName.IdentityUniversalAuth}.identityId`+ )+ .leftJoin(+ TableName.IdentityGcpAuth,+ `${TableName.Membership}.actorIdentityId`,+ `${TableName.IdentityGcpAuth}.identityId`+ )+ .leftJoin(+ TableName.IdentityAliCloudAuth,+ `${TableName.Membership}.actorIdentityId`,+ `${TableName.IdentityAliCloudAuth}.identityId`+ )+ .leftJoin(+ TableName.IdentityAwsAuth,+ `${TableName.Membership}.actorIdentityId`,+ `${TableName.IdentityAwsAuth}.identityId`+ )+ .leftJoin(+ TableName.IdentityKubernetesAuth,+ `${TableName.Membership}.actorIdentityId`,+ `${TableName.IdentityKubernetesAuth}.identityId`+ )+ .leftJoin(+ TableName.IdentityOciAuth,+ `${TableName.Membership}.actorIdentityId`,+ `${TableName.IdentityOciAuth}.identityId`+ )+ .leftJoin(+ TableName.IdentityOidcAuth,+ `${TableName.Membership}.actorIdentityId`,+ `${TableName.IdentityOidcAuth}.identityId`+ )+ .leftJoin(+ TableName.IdentityAzureAuth,+ `${TableName.Membership}.actorIdentityId`,+ `${TableName.IdentityAzureAuth}.identityId`+ )+ .leftJoin(+ TableName.IdentityTokenAuth,+ `${TableName.Membership}.actorIdentityId`,+ `${TableName.IdentityTokenAuth}.identityId`+ )+ .leftJoin(+ TableName.IdentityJwtAuth,+ `${TableName.Membership}.actorIdentityId`,+ `${TableName.IdentityJwtAuth}.identityId`+ )+ .leftJoin(+ TableName.IdentityLdapAuth,+ `${TableName.Membership}.actorIdentityId`,+ `${TableName.IdentityLdapAuth}.identityId`+ )+ .leftJoin(+ TableName.IdentitySpiffeAuth,+ `${TableName.Membership}.actorIdentityId`,+ `${TableName.IdentitySpiffeAuth}.identityId`+ )+ .select(+ db.ref("id").withSchema(TableName.Membership),+ db.ref("scope").withSchema(TableName.Membership).as("membershipScope"),+ db.ref("scopeOrgId").withSchema(TableName.Membership).as("orgId"),+ db.ref("scopeProjectId").withSchema(TableName.Membership).as("scopeProjectId"),+ db.ref("total_count").withSchema("searchedMemberships"),+ db.ref("createdAt").withSchema(TableName.Membership),+ db.ref("updatedAt").withSchema(TableName.Membership),+ db.ref("lastLoginAuthMethod").withSchema(TableName.Membership),+ db.ref("lastLoginTime").withSchema(TableName.Membership),+ db.ref("actorIdentityId").withSchema(TableName.Membership).as("identityId"),+ db.ref("name").withSchema(TableName.Identity).as("identityName"),+ db.ref("hasDeleteProtection").withSchema(TableName.Identity),+ db.ref("orgId").withSchema(TableName.Identity).as("identityOrgId"),++ db.ref("id").withSchema(TableName.MembershipRole).as("membershipRoleId"),+ db.ref("role").withSchema(TableName.MembershipRole),+ db.ref("customRoleId").withSchema(TableName.MembershipRole).as("roleId"),+ db.ref("isTemporary").withSchema(TableName.MembershipRole),+ db.ref("temporaryMode").withSchema(TableName.MembershipRole),+ db.ref("temporaryRange").withSchema(TableName.MembershipRole),+ db.ref("temporaryAccessStartTime").withSchema(TableName.MembershipRole),+ db.ref("temporaryAccessEndTime").withSchema(TableName.MembershipRole),++ db.ref("id").as("projectIdRef").withSchema(TableName.Project),+ db.ref("name").as("projectName").withSchema(TableName.Project),+ db.ref("slug").as("projectSlug").withSchema(TableName.Project),+ db.ref("type").as("projectType").withSchema(TableName.Project),++ db.ref("id").as("uaId").withSchema(TableName.IdentityUniversalAuth),+ db.ref("id").as("gcpId").withSchema(TableName.IdentityGcpAuth),+ db.ref("id").as("alicloudId").withSchema(TableName.IdentityAliCloudAuth),+ db.ref("id").as("awsId").withSchema(TableName.IdentityAwsAuth),+ db.ref("id").as("kubernetesId").withSchema(TableName.IdentityKubernetesAuth),+ db.ref("id").as("ociId").withSchema(TableName.IdentityOciAuth),+ db.ref("id").as("oidcId").withSchema(TableName.IdentityOidcAuth),+ db.ref("id").as("azureId").withSchema(TableName.IdentityAzureAuth),+ db.ref("id").as("tokenId").withSchema(TableName.IdentityTokenAuth),+ db.ref("id").as("jwtId").withSchema(TableName.IdentityJwtAuth),+ db.ref("id").as("ldapId").withSchema(TableName.IdentityLdapAuth),+ db.ref("id").as("spiffeId").withSchema(TableName.IdentitySpiffeAuth)+ )+ .select(db.ref("id").as("crId").withSchema(TableName.Role))+ .select(db.ref("name").as("crName").withSchema(TableName.Role))+ .select(db.ref("slug").as("crSlug").withSchema(TableName.Role))+ .select(db.ref("description").as("crDescription").withSchema(TableName.Role))+ .select(db.ref("permissions").as("crPermission").withSchema(TableName.Role))+ .select(+ db.ref("id").withSchema(TableName.IdentityMetadata).as("metadataId"),+ db.ref("key").withSchema(TableName.IdentityMetadata).as("metadataKey"),+ db.ref("value").withSchema(TableName.IdentityMetadata).as("metadataValue")+ );++ if (orderBy === OrgIdentityOrderBy.Role) {+ void query.orderBy("searchedMemberships.roleSort", orderDirection);+ } else {+ void query.orderBy("searchedMemberships.identityName", orderDirection);+ }++ const docs = await query;++ const formattedDocs = sqlNestRelationships({+ data: docs,+ key: "id",+ parentMapper: ({+ identityId,+ identityOrgId,+ identityName,+ hasDeleteProtection,+ total_count,+ id,+ membershipScope,+ orgId: membershipOrgId,+ scopeProjectId,+ projectIdRef,+ projectName,+ projectSlug,+ projectType,+ uaId,+ alicloudId,+ awsId,+ gcpId,+ jwtId,+ kubernetesId,+ ociId,+ oidcId,+ azureId,+ tokenId,+ ldapId,+ spiffeId,+ createdAt,+ updatedAt,+ lastLoginTime,+ lastLoginAuthMethod+ }) => ({+ id,+ identityId: identityId as string,+ scope: membershipScope as SearchIdentitiesScope,+ orgId: membershipOrgId,+ projectId: scopeProjectId,+ total_count: total_count as string,+ createdAt,+ updatedAt,+ lastLoginTime,+ lastLoginAuthMethod,+ project: projectIdRef+ ? {+ id: projectIdRef,+ name: projectName,+ slug: projectSlug,+ type: projectType+ }+ : null,+ identity: {+ id: identityId as string,+ name: identityName,+ hasDeleteProtection,+ orgId: identityOrgId,+ authMethods: buildAuthMethods({+ uaId,+ alicloudId,+ awsId,+ gcpId,+ kubernetesId,+ ociId,+ oidcId,+ azureId,+ tokenId,+ jwtId,+ ldapId,+ spiffeId+ })+ }+ }),+ childrenMapper: [+ {+ key: "membershipRoleId",+ label: "roles" as const,+ mapper: ({+ membershipRoleId,+ role,+ roleId,+ crId,+ crName,+ crSlug,+ crDescription,+ crPermission,+ isTemporary,+ temporaryMode,+ temporaryRange,+ temporaryAccessStartTime,+ temporaryAccessEndTime+ }) => ({+ id: membershipRoleId,+ role,+ customRoleId: roleId,+ customRoleName: crName ?? null,+ customRoleSlug: crSlug ?? null,+ customRoleDescription: crDescription ?? null,+ customRolePermissions: crPermission ?? null,+ isTemporary,+ temporaryMode,+ temporaryRange,+ temporaryAccessStartTime,+ temporaryAccessEndTime,+ customRole: roleId+ ? {+ id: crId,+ name: crName,+ slug: crSlug,+ permissions: crPermission,+ description: crDescription+ }+ : undefined+ })+ },+ {+ key: "metadataId",+ label: "metadata" as const,+ mapper: ({ metadataKey, metadataValue, metadataId }) => ({+ id: metadataId,+ key: metadataKey,+ value: metadataValue+ })+ }+ ]+ });++ return { docs: formattedDocs, totalCount: Number(formattedDocs?.[0]?.total_count ?? 0) };+ } catch (error) {+ throw new DatabaseError({ error, name: "SearchIdentitiesV2" });+ }+ };++ return { find, findOne, countAllOrgIdentities, searchIdentities, searchIdentitiesV2 };};diff --git a/backend/src/services/identity/identity-service.ts b/backend/src/services/identity/identity-service.tsindex 00861d3ad7..c38455837f 100644--- a/backend/src/services/identity/identity-service.ts+++ b/backend/src/services/identity/identity-service.ts@@ -1,6 +1,13 @@import { ForbiddenError } from "@casl/ability";-import { AccessScope, OrganizationActionScope, OrgMembershipRole, TableName, TRoles } from "@app/db/schemas";+import {+ AccessScope,+ ActionProjectType,+ OrganizationActionScope,+ OrgMembershipRole,+ TableName,+ TRoles+} from "@app/db/schemas";import { TLicenseDALFactory } from "@app/ee/services/license/license-dal";import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";import { OrgPermissionIdentityActions, OrgPermissionSubjects } from "@app/ee/services/permission/org-permission";@@ -9,12 +16,14 @@ import {validatePrivilegeChangeOperation} from "@app/ee/services/permission/permission-fns";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";+import { ProjectPermissionIdentityActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";import { PgSqlLock, TKeyStoreFactory } from "@app/keystore/keystore";import { BadRequestError, NotFoundError, PermissionBoundaryError } from "@app/lib/errors";import { requestMemoKeys } from "@app/lib/request-context/memo-keys";import { requestMemoize } from "@app/lib/request-context/request-memoizer";import { TIdentityProjectDALFactory } from "@app/services/identity-project/identity-project-dal";import { getIdentityActiveLockoutAuthMethods } from "@app/services/identity-v2/identity-fns";+import { TProjectDALFactory } from "@app/services/project/project-dal";import { TAdditionalPrivilegeDALFactory } from "../additional-privilege/additional-privilege-dal";import { ActorType } from "../auth/auth-type";@@ -26,11 +35,13 @@ import { TIdentityDALFactory } from "./identity-dal";import { TIdentityMetadataDALFactory } from "./identity-metadata-dal";import { TIdentityOrgDALFactory } from "./identity-org-dal";import {+ SearchIdentitiesScope,TCreateIdentityDTO,TDeleteIdentityDTO,TGetIdentityByIdDTO,TListOrgIdentitiesByOrgIdDTO,TListProjectIdentitiesByIdentityIdDTO,+ TSearchIdentitiesV2DTO,TSearchOrgIdentitiesByOrgIdDTO,TUpdateIdentityDTO} from "./identity-types";@@ -42,12 +53,16 @@ type TIdentityServiceFactoryDep = {membershipIdentityDAL: TMembershipIdentityDALFactory;membershipRoleDAL: TMembershipRoleDALFactory;identityProjectDAL: Pick<TIdentityProjectDALFactory, "findByIdentityId">;- permissionService: Pick<TPermissionServiceFactory, "getOrgPermission" | "getOrgPermissionByRoles">;+ permissionService: Pick<+ TPermissionServiceFactory,+ "getOrgPermission" | "getOrgPermissionByRoles" | "getProjectPermission"+ >;licenseService: Pick<TLicenseServiceFactory, "getPlan" | "updateSubscriptionOrgMemberCount">;licenseDAL: Pick<TLicenseDALFactory, "countOrgUsersAndIdentities">;keyStore: Pick<TKeyStoreFactory, "getKeysByPattern" | "getItem">;orgDAL: Pick<TOrgDALFactory, "findById" | "findEffectiveOrgMembership">;additionalPrivilegeDAL: Pick<TAdditionalPrivilegeDALFactory, "delete">;+ projectDAL: Pick<TProjectDALFactory, "findUserProjects" | "findIdentityProjects">;};export type TIdentityServiceFactory = ReturnType<typeof identityServiceFactory>;@@ -64,7 +79,8 @@ export const identityServiceFactory = ({orgDAL,membershipIdentityDAL,membershipRoleDAL,- additionalPrivilegeDAL+ additionalPrivilegeDAL,+ projectDAL}: TIdentityServiceFactoryDep) => {const createIdentity = async ({name,@@ -482,6 +498,85 @@ export const identityServiceFactory = ({return { identityMemberships: docs, totalCount };};+ const searchOrgIdentitiesV2 = async ({+ actor,+ actorId,+ actorAuthMethod,+ actorOrgId,+ limit,+ offset,+ orderBy,+ orderDirection,+ scope,+ searchFilter = {}+ }: TSearchIdentitiesV2DTO) => {+ const uniqueScope = Array.from(new Set(scope));+ const { permission } = await permissionService.getOrgPermission({+ scope: OrganizationActionScope.Any,+ actor,+ actorId,+ orgId: actorOrgId,+ actorAuthMethod,+ actorOrgId+ });+ const canReadOrgIdentities = permission.can(OrgPermissionIdentityActions.Read, OrgPermissionSubjects.Identity);+ const wantsOrgScope = uniqueScope.includes(SearchIdentitiesScope.Organization);+ if (wantsOrgScope && !canReadOrgIdentities) {+ ForbiddenError.from(permission).throwUnlessCan(OrgPermissionIdentityActions.Read, OrgPermissionSubjects.Identity);+ }++ let accessibleProjectIds: string[] = [];+ const wantsProjectScope = uniqueScope.includes(SearchIdentitiesScope.Project);+ if (wantsProjectScope) {+ const actorProjects =+ actor === ActorType.USER+ ? await projectDAL.findUserProjects(actorId, actorOrgId)+ : await projectDAL.findIdentityProjects(actorId, actorOrgId);++ const uniqueProjectIds = Array.from(new Set(actorProjects.map((p) => p.id)));+ const projectAccessChecks = await Promise.all(+ uniqueProjectIds.map(async (projectId) => {+ try {+ const { permission: projectPermission } = await permissionService.getProjectPermission({+ actor,+ actorId,+ actionProjectType: ActionProjectType.Any,+ actorAuthMethod,+ projectId,+ actorOrgId+ });+ return projectPermission.can(ProjectPermissionIdentityActions.Read, ProjectPermissionSub.Identity)+ ? projectId+ : null;+ } catch {+ return null;+ }+ })+ );++ accessibleProjectIds = projectAccessChecks.filter((id): id is string => Boolean(id));+ }++ const effectiveScope = uniqueScope.filter((s) => s !== SearchIdentitiesScope.Organization || canReadOrgIdentities);++ if (!effectiveScope.length) {+ return { identityMemberships: [], totalCount: 0 };+ }++ const { totalCount, docs } = await identityOrgMembershipDAL.searchIdentitiesV2({+ orgId: actorOrgId,+ limit,+ offset,+ orderBy,+ orderDirection,+ searchFilter,+ scope: effectiveScope,+ accessibleProjectIds+ });++ return { identityMemberships: docs, totalCount };+ };+const listProjectIdentitiesByIdentityId = async ({identityId,actor,@@ -517,6 +612,7 @@ export const identityServiceFactory = ({listOrgIdentities,getIdentityById,searchOrgIdentities,+ searchOrgIdentitiesV2,listProjectIdentitiesByIdentityId};};diff --git a/backend/src/services/identity/identity-types.ts b/backend/src/services/identity/identity-types.tsindex 4380f6f416..65b7b6e1b7 100644--- a/backend/src/services/identity/identity-types.ts+++ b/backend/src/services/identity/identity-types.ts@@ -63,3 +63,34 @@ export type TSearchOrgIdentitiesByOrgIdDAL = {};export type TSearchOrgIdentitiesByOrgIdDTO = TSearchOrgIdentitiesByOrgIdDAL & TOrgPermission;++export enum SearchIdentitiesScope {+ Organization = "organization",+ Project = "project"+}++export type TSearchIdentitiesV2DAL = {+ limit?: number;+ offset?: number;+ orderBy?: OrgIdentityOrderBy;+ orderDirection?: OrderByDirection;+ orgId: string;+ scope: SearchIdentitiesScope[];+ accessibleProjectIds: string[];+ searchFilter?: Partial<{+ name: Omit<TSearchResourceOperator, "number">;+ role: Omit<TSearchResourceOperator, "number">;+ }>;+};++export type TSearchIdentitiesV2DTO = {+ limit?: number;+ offset?: number;+ orderBy?: OrgIdentityOrderBy;+ orderDirection?: OrderByDirection;+ scope: SearchIdentitiesScope[];+ searchFilter?: Partial<{+ name: Omit<TSearchResourceOperator, "number">;+ role: Omit<TSearchResourceOperator, "number">;+ }>;+} & TOrgPermission;diff --git a/frontend/src/hooks/api/identities/index.tsx b/frontend/src/hooks/api/identities/index.tsxindex bf49387acb..1ffe86dc44 100644--- a/frontend/src/hooks/api/identities/index.tsx+++ b/frontend/src/hooks/api/identities/index.tsx@@ -2,3 +2,9 @@ export { identityAuthToNameMap } from "./constants";export { IdentityAuthMethod } from "./enums";export * from "./mutations";export * from "./queries";+export type {+ IdentityMembershipSearchResult,+ IdentityMembershipSearchRole,+ TSearchIdentitiesDTO+} from "./types";+export { SearchIdentitiesScope } from "./types";diff --git a/frontend/src/hooks/api/identities/queries.tsx b/frontend/src/hooks/api/identities/queries.tsxindex 39e88b338c..f6ed50ff03 100644--- a/frontend/src/hooks/api/identities/queries.tsx+++ b/frontend/src/hooks/api/identities/queries.tsx@@ -14,6 +14,7 @@ import {IdentityKubernetesAuth,IdentityLdapAuth,IdentityMembershipOrg,+ IdentityMembershipSearchResult,IdentityOciAuth,IdentityOidcAuth,IdentityProjectMembershipV1,@@ -21,6 +22,7 @@ import {IdentityTlsCertAuth,IdentityTokenAuth,IdentityUniversalAuth,+ SearchIdentitiesScope,TSearchIdentitiesDTO} from "./types";@@ -70,18 +72,19 @@ export const useGetOrgIdentityMembershipById = (identityId: string) => {};export const useSearchOrgIdentityMemberships = (dto: TSearchIdentitiesDTO) => {- const { limit, search, offset, orderBy, orderDirection } = dto;+ const { limit, search, offset, orderBy, orderDirection, scope } = dto;return useQuery({queryKey: identitiesKeys.searchIdentities(dto),queryFn: async () => {const { data } = await apiRequest.post<{- identities: IdentityMembershipOrg[];+ identities: IdentityMembershipSearchResult[];totalCount: number;- }>("/api/v1/identities/search", {+ }>("/api/v2/identities/search", {limit,offset,orderBy,orderDirection,+ scope: scope ?? [SearchIdentitiesScope.Organization],search});return data;diff --git a/frontend/src/hooks/api/identities/types.ts b/frontend/src/hooks/api/identities/types.tsindex 6684541df8..bb3dc2af6d 100644--- a/frontend/src/hooks/api/identities/types.ts+++ b/frontend/src/hooks/api/identities/types.ts@@ -949,13 +949,59 @@ export type TProjectIdentityMembershipsListV2 = {totalCount: number;};+export enum SearchIdentitiesScope {+ Organization = "organization",+ // eslint-disable-next-line @typescript-eslint/no-shadow+ Project = "project"+}+export type TSearchIdentitiesDTO = {limit?: number;offset?: number;orderBy?: OrgIdentityOrderBy;orderDirection?: OrderByDirection;+ scope?: SearchIdentitiesScope[];search: {name?: { $contains: string };role?: { $in: string[] };};};++export type IdentityMembershipSearchRole = {+ id: string;+ role: "admin" | "member" | "viewer" | "no-access" | "custom" | string;+ customRoleId?: string | null;+ customRoleName?: string | null;+ customRoleSlug?: string | null;+ customRoleDescription?: string | null;+ customRolePermissions?: unknown;+ isTemporary: boolean;+ temporaryMode?: string | null;+ temporaryRange?: string | null;+ temporaryAccessStartTime?: string | null;+ temporaryAccessEndTime?: string | null;+};++export type IdentityMembershipSearchResult = {+ id: string;+ identityId: string;+ scope: SearchIdentitiesScope;+ orgId: string;+ projectId?: string | null;+ project?: {+ id: string;+ name: string;+ slug: string;+ type: string;+ } | null;+ createdAt: string;+ updatedAt: string;+ lastLoginAuthMethod?: IdentityAuthMethod | null;+ lastLoginTime?: string | null;+ roles: IdentityMembershipSearchRole[];+ /** @deprecated use `roles` */+ customRole?: TOrgRole;+ identity: Pick<Identity, "id" | "name" | "hasDeleteProtection" | "orgId"> & {+ authMethods: IdentityAuthMethod[];+ };+};diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityTable.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityTable.tsxindex 1d37e874c2..9a60e846ff 100644--- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityTable.tsx+++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityTable.tsx@@ -315,12 +315,14 @@ export const IdentityTable = ({ handlePopUpOpen }: Props) => {data?.identities?.map(({identity: { id, name, orgId },- role,- customRole,+ roles: membershipRoles,lastLoginAuthMethod,lastLoginTime}) => {const isSubOrgIdentity = currentOrg.id === orgId;+ const primaryRole = membershipRoles?.[0];+ const role = primaryRole?.role ?? "";+ const customRoleSlug = primaryRole?.customRoleSlug ?? null;return (<TableRow@@ -359,7 +361,7 @@ export const IdentityTable = ({ handlePopUpOpen }: Props) => {>{(isAllowed) => (<Select- value={role === "custom" ? (customRole?.slug as string) : role}+ value={role === "custom" ? (customRoleSlug as string) : role}disabled={!isAllowed}onValueChange={(selectedRole) =>handleChangeRole({