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
creat count endpoint
Thiago Araujo da Silva1abad125320c
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex 28a9b31f53..8fb39a937b 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -221,6 +221,15 @@ 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_COUNT_V2: {+ scope:+ "Array of scopes to count. Returns a count for each requested scope. Accepts 'organization' and/or 'project'.",+ search: {+ desc: "The filters to apply when counting.",+ name: "The name of the identity to filter by.",+ role: "The role of the identity to filter by."+ }}} as const;diff --git a/backend/src/server/routes/v2/identity-router.ts b/backend/src/server/routes/v2/identity-router.tsindex 72416dcb04..2eac138753 100644--- a/backend/src/server/routes/v2/identity-router.ts+++ b/backend/src/server/routes/v2/identity-router.ts@@ -163,4 +163,86 @@ export const registerIdentityRouter = async (server: FastifyZodProvider) => {return { identities: identityMemberships, totalCount };}});++ server.route({+ method: "POST",+ url: "/search/count",+ config: {+ rateLimit: readLimit+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ schema: {+ hide: false,+ operationId: "countMachineIdentitiesV2",+ tags: [ApiDocsTags.Identities],+ description:+ "Return per-scope counts of machine identities matching the given search filter. The response contains a count for every scope passed in the request body (zero when the caller has no access to that scope).",+ security: [+ {+ bearerAuth: []+ }+ ],+ body: z.object({+ scope: z+ .array(z.nativeEnum(SearchIdentitiesScope))+ .min(1)+ .default([SearchIdentitiesScope.Organization, SearchIdentitiesScope.Project])+ .describe(IDENTITIES.SEARCH_COUNT_V2.scope),+ 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_COUNT_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_COUNT_V2.search.role)+ })+ .describe(IDENTITIES.SEARCH_COUNT_V2.search.desc)+ .partial()+ )+ }),+ response: {+ 200: z.object({+ counts: z.object({+ organization: z.number().optional(),+ project: z.number().optional()+ })+ })+ }+ },+ handler: async (req) => {+ const counts = await server.services.identityV1.countOrgIdentitiesV2({+ 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+ });++ return { counts };+ }+ });};diff --git a/backend/src/services/identity/identity-org-dal.ts b/backend/src/services/identity/identity-org-dal.tsindex 0e4f946a9d..5c062a69e4 100644--- a/backend/src/services/identity/identity-org-dal.ts+++ b/backend/src/services/identity/identity-org-dal.ts@@ -28,6 +28,7 @@ import { OrderByDirection } from "@app/lib/types";import {OrgIdentityOrderBy,SearchIdentitiesScope,+ TCountIdentitiesV2DAL,TListOrgIdentitiesByOrgIdDTO,TSearchIdentitiesV2DAL,TSearchOrgIdentitiesByOrgIdDAL@@ -853,6 +854,11 @@ export const identityOrgDALFactory = (db: TDbClient) => {`${TableName.Membership}.actorIdentityId`,`${TableName.IdentityLdapAuth}.identityId`)+ .leftJoin(+ TableName.IdentityTlsCertAuth,+ `${TableName.Membership}.actorIdentityId`,+ `${TableName.IdentityTlsCertAuth}.identityId`+ ).leftJoin(TableName.IdentitySpiffeAuth,`${TableName.Membership}.actorIdentityId`,@@ -898,6 +904,7 @@ export const identityOrgDALFactory = (db: TDbClient) => {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("tlsCertId").withSchema(TableName.IdentityTlsCertAuth),db.ref("id").as("spiffeId").withSchema(TableName.IdentitySpiffeAuth)).select(db.ref("id").as("crId").withSchema(TableName.Role))@@ -947,6 +954,7 @@ export const identityOrgDALFactory = (db: TDbClient) => {azureId,tokenId,ldapId,+ tlsCertId,spiffeId,createdAt,updatedAt,@@ -988,6 +996,7 @@ export const identityOrgDALFactory = (db: TDbClient) => {tokenId,jwtId,ldapId,+ tlsCertId,spiffeId})}@@ -1052,5 +1061,92 @@ export const identityOrgDALFactory = (db: TDbClient) => {}};- return { find, findOne, countAllOrgIdentities, searchIdentities, searchIdentitiesV2 };+ const countIdentitiesV2 = async (+ { orgId, scope, accessibleProjectIds, searchFilter }: TCountIdentitiesV2DAL,+ tx?: Knex+ ) => {+ try {+ const includeOrgScope = scope.includes(SearchIdentitiesScope.Organization);+ const includeProjectScope = scope.includes(SearchIdentitiesScope.Project);++ const query = (tx || db.replicaNode())(TableName.Membership)+ .join(TableName.Identity, `${TableName.Identity}.id`, `${TableName.Membership}.actorIdentityId`)+ .whereNotNull(`${TableName.Membership}.actorIdentityId`);++ // Role filter requires joining MembershipRole + Role; the COUNT(DISTINCT) below+ // collapses the multi-row fan-out back to one row per membership.+ const hasRoleFilter = Boolean(searchFilter?.role);+ if (hasRoleFilter) {+ void query+ .leftJoin(TableName.MembershipRole, `${TableName.MembershipRole}.membershipId`, `${TableName.Membership}.id`)+ .leftJoin(TableName.Role, `${TableName.MembershipRole}.customRoleId`, `${TableName.Role}.id`);+ }++ 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 query.where((nested) => {+ void nested.where((sub) => orgScopeBranch(sub)).orWhere((sub) => projectScopeBranch(sub));+ });+ } else if (includeOrgScope) {+ void query.where((sub) => orgScopeBranch(sub));+ } else if (includeProjectScope) {+ void query.where((sub) => projectScopeBranch(sub));+ } else {+ return { organization: includeOrgScope ? 0 : undefined, project: includeProjectScope ? 0 : undefined };+ }++ if (searchFilter) {+ buildKnexFilterForSearchResource(query, 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` });+ }+ });+ }++ const rows = await query+ .groupBy(`${TableName.Membership}.scope`)+ .select(db.ref("scope").withSchema(TableName.Membership).as("scope"))+ .select<{ scope: string; count: string }[]>(+ db.raw(`COUNT(DISTINCT ??) as count`, [`${TableName.Membership}.id`])+ );++ const counts: { organization?: number; project?: number } = {};+ if (includeOrgScope) counts.organization = 0;+ if (includeProjectScope) counts.project = 0;+ for (const row of rows) {+ if (row.scope === AccessScope.Organization && includeOrgScope) {+ counts.organization = Number(row.count);+ } else if (row.scope === AccessScope.Project && includeProjectScope) {+ counts.project = Number(row.count);+ }+ }++ return counts;+ } catch (error) {+ throw new DatabaseError({ error, name: "CountIdentitiesV2" });+ }+ };++ return { find, findOne, countAllOrgIdentities, searchIdentities, searchIdentitiesV2, countIdentitiesV2 };};diff --git a/backend/src/services/identity/identity-service.ts b/backend/src/services/identity/identity-service.tsindex 069fba36d0..f9bacd459f 100644--- a/backend/src/services/identity/identity-service.ts+++ b/backend/src/services/identity/identity-service.ts@@ -40,6 +40,7 @@ import { TIdentityMetadataDALFactory } from "./identity-metadata-dal";import { TIdentityOrgDALFactory } from "./identity-org-dal";import {SearchIdentitiesScope,+ TCountIdentitiesV2DTO,TCreateIdentityDTO,TDeleteIdentityDTO,TGetIdentityByIdDTO,@@ -502,18 +503,19 @@ export const identityServiceFactory = ({return { identityMemberships: docs, totalCount };};- const searchOrgIdentitiesV2 = async ({+ const resolveIdentitySearchScope = async ({actor,actorId,actorAuthMethod,actorOrgId,- limit,- offset,- orderBy,- orderDirection,- scope,- searchFilter = {}- }: TSearchIdentitiesV2DTO) => {+ scope+ }: {+ actor: ActorType;+ actorId: string;+ actorAuthMethod: TSearchIdentitiesV2DTO["actorAuthMethod"];+ actorOrgId: string;+ scope: SearchIdentitiesScope[];+ }): Promise<{ uniqueScope: Set<SearchIdentitiesScope>; accessibleProjectIds: string[] }> => {const uniqueScope = new Set(scope);const { permission: orgPermission } = await permissionService.getOrgPermission({scope: OrganizationActionScope.Any,@@ -523,10 +525,7 @@ export const identityServiceFactory = ({actorAuthMethod,actorOrgId});- const canReadOrgIdentities = orgPermission.can(- OrgPermissionIdentityActions.Read,- OrgPermissionSubjects.Identity- );+ const canReadOrgIdentities = orgPermission.can(OrgPermissionIdentityActions.Read, OrgPermissionSubjects.Identity);if (uniqueScope.has(SearchIdentitiesScope.Organization) && !canReadOrgIdentities) {uniqueScope.delete(SearchIdentitiesScope.Organization);}@@ -574,6 +573,29 @@ export const identityServiceFactory = ({}}+ return { uniqueScope, accessibleProjectIds };+ };++ const searchOrgIdentitiesV2 = async ({+ actor,+ actorId,+ actorAuthMethod,+ actorOrgId,+ limit,+ offset,+ orderBy,+ orderDirection,+ scope,+ searchFilter = {}+ }: TSearchIdentitiesV2DTO) => {+ const { uniqueScope, accessibleProjectIds } = await resolveIdentitySearchScope({+ actor,+ actorId,+ actorAuthMethod,+ actorOrgId,+ scope+ });+if (!uniqueScope.size) {return { identityMemberships: [], totalCount: 0 };}@@ -585,13 +607,55 @@ export const identityServiceFactory = ({orderBy,orderDirection,searchFilter,- scope:Array.from(uniqueScope),+ scope: Array.from(uniqueScope),accessibleProjectIds});return { identityMemberships: docs, totalCount };};+ const countOrgIdentitiesV2 = async ({+ actor,+ actorId,+ actorAuthMethod,+ actorOrgId,+ scope,+ searchFilter = {}+ }: TCountIdentitiesV2DTO) => {+ const requestedOrg = scope.includes(SearchIdentitiesScope.Organization);+ const requestedProject = scope.includes(SearchIdentitiesScope.Project);++ const { uniqueScope, accessibleProjectIds } = await resolveIdentitySearchScope({+ actor,+ actorId,+ actorAuthMethod,+ actorOrgId,+ scope+ });++ // Build the response shape from the *requested* scopes so callers always get a number+ // for every scope they asked about (zero when permissions/projects filter the scope out).+ const counts: { organization?: number; project?: number } = {};+ if (requestedOrg) counts.organization = 0;+ if (requestedProject) counts.project = 0;++ if (!uniqueScope.size) {+ return counts;+ }++ const dalCounts = await identityOrgMembershipDAL.countIdentitiesV2({+ orgId: actorOrgId,+ scope: Array.from(uniqueScope),+ accessibleProjectIds,+ searchFilter+ });++ if (requestedOrg && dalCounts.organization !== undefined) counts.organization = dalCounts.organization;+ if (requestedProject && dalCounts.project !== undefined) counts.project = dalCounts.project;++ return counts;+ };+const listProjectIdentitiesByIdentityId = async ({identityId,actor,@@ -628,6 +692,7 @@ export const identityServiceFactory = ({getIdentityById,searchOrgIdentities,searchOrgIdentitiesV2,+ countOrgIdentitiesV2,listProjectIdentitiesByIdentityId};};diff --git a/backend/src/services/identity/identity-types.ts b/backend/src/services/identity/identity-types.tsindex 65b7b6e1b7..98c53cef32 100644--- a/backend/src/services/identity/identity-types.ts+++ b/backend/src/services/identity/identity-types.ts@@ -94,3 +94,21 @@ export type TSearchIdentitiesV2DTO = {role: Omit<TSearchResourceOperator, "number">;}>;} & TOrgPermission;++export type TCountIdentitiesV2DAL = {+ orgId: string;+ scope: SearchIdentitiesScope[];+ accessibleProjectIds: string[];+ searchFilter?: Partial<{+ name: Omit<TSearchResourceOperator, "number">;+ role: Omit<TSearchResourceOperator, "number">;+ }>;+};++export type TCountIdentitiesV2DTO = {+ 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 1ffe86dc44..70d4541384 100644--- a/frontend/src/hooks/api/identities/index.tsx+++ b/frontend/src/hooks/api/identities/index.tsx@@ -5,6 +5,8 @@ export * from "./queries";export type {IdentityMembershipSearchResult,IdentityMembershipSearchRole,+ TCountIdentitiesDTO,+ TIdentityMembershipCounts,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 f6ed50ff03..f1f6ab4318 100644--- a/frontend/src/hooks/api/identities/queries.tsx+++ b/frontend/src/hooks/api/identities/queries.tsx@@ -23,6 +23,8 @@ import {IdentityTokenAuth,IdentityUniversalAuth,SearchIdentitiesScope,+ TCountIdentitiesDTO,+ TIdentityMembershipCounts,TSearchIdentitiesDTO} from "./types";@@ -31,6 +33,9 @@ export const identitiesKeys = {searchIdentitiesRoot: ["identity", "search"] as const,searchIdentities: (dto: TSearchIdentitiesDTO) =>[...identitiesKeys.searchIdentitiesRoot, dto] as const,+ countIdentitiesRoot: ["identity", "search", "count"] as const,+ countIdentities: (dto: TCountIdentitiesDTO) =>+ [...identitiesKeys.countIdentitiesRoot, dto] as const,getIdentityUniversalAuth: (identityId: string) =>[{ identityId }, "identity-universal-auth"] as const,getIdentityUniversalAuthClientSecrets: (identityId: string) =>@@ -93,6 +98,21 @@ export const useSearchOrgIdentityMemberships = (dto: TSearchIdentitiesDTO) => {});};+export const useCountOrgIdentityMemberships = (dto: TCountIdentitiesDTO) => {+ const { scope, search } = dto;+ return useQuery({+ queryKey: identitiesKeys.countIdentities(dto),+ queryFn: async () => {+ const { data } = await apiRequest.post<{ counts: TIdentityMembershipCounts }>(+ "/api/v2/identities/search/count",+ { scope, search }+ );+ return data.counts;+ },+ placeholderData: (previousData) => previousData+ });+};+export const useGetIdentityProjectMemberships = (identityId: string) => {return useQuery({enabled: Boolean(identityId),diff --git a/frontend/src/hooks/api/identities/types.ts b/frontend/src/hooks/api/identities/types.tsindex 35084bc7de..55851bbada 100644--- a/frontend/src/hooks/api/identities/types.ts+++ b/frontend/src/hooks/api/identities/types.ts@@ -967,6 +967,19 @@ export type TSearchIdentitiesDTO = {};};+export type TCountIdentitiesDTO = {+ scope: SearchIdentitiesScope[];+ search: {+ name?: { $contains: string };+ role?: { $in: string[] };+ };+};++export type TIdentityMembershipCounts = {+ organization?: number;+ project?: number;+};+export type IdentityMembershipSearchRole = {id: string;role: "admin" | "member" | "viewer" | "no-access" | "custom" | string;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 855e239a50..a0b2e8b3f3 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@@ -74,6 +74,7 @@ import {import { usePagination, useResetPageHelper } from "@app/hooks";import {identityAuthToNameMap,+ useCountOrgIdentityMemberships,useGetOrgRoles,useSearchOrgIdentityMemberships,useUpdateOrgIdentity@@ -169,37 +170,17 @@ export const IdentityTable = ({ handlePopUpOpen }: Props) => {search: searchPayload});- // Lightweight per-scope queries powering the tab counts. Each query is keyed- // independently by scope so React Query caches them per tab. limit=1 keeps the- // result payload tiny while the totalCount window function gives us the chip total.- const allScopeQuery = useSearchOrgIdentityMemberships({- offset: 0,- limit: 1,- orderDirection,- orderBy,+ const { data: scopeCounts } = useCountOrgIdentityMemberships({scope: TAB_TO_SCOPE.all,search: searchPayload});- const orgScopeQuery = useSearchOrgIdentityMemberships({- offset: 0,- limit: 1,- orderDirection,- orderBy,- scope: TAB_TO_SCOPE.organization,- search: searchPayload- });- const projectScopeQuery = useSearchOrgIdentityMemberships({- offset: 0,- limit: 1,- orderDirection,- orderBy,- scope: TAB_TO_SCOPE.project,- search: searchPayload- });- const allScopeCount = allScopeQuery.data?.totalCount;- const orgScopeCount = orgScopeQuery.data?.totalCount;- const projectScopeCount = projectScopeQuery.data?.totalCount;+ const orgScopeCount = scopeCounts?.organization;+ const projectScopeCount = scopeCounts?.project;+ const allScopeCount =+ orgScopeCount === undefined && projectScopeCount === undefined+ ? undefined+ : (orgScopeCount ?? 0) + (projectScopeCount ?? 0);const { totalCount = 0 } = data ?? {};useResetPageHelper({@@ -347,10 +328,7 @@ export const IdentityTable = ({ handlePopUpOpen }: Props) => {<TableHeader><TableRow><TableHead- className={twMerge(- "cursor-pointer",- isSubOrganization ? "w-1/5" : "w-1/4"- )}+ className={twMerge("cursor-pointer", isSubOrganization ? "w-1/5" : "w-1/4")}onClick={() => handleSort(OrgIdentityOrderBy.Name)}>Name@@ -366,10 +344,7 @@ export const IdentityTable = ({ handlePopUpOpen }: Props) => {</TableHead><TableHead className={isSubOrganization ? "w-1/5" : "w-1/4"}>Scope</TableHead><TableHead- className={twMerge(- "cursor-pointer",- isSubOrganization ? "w-1/5" : "w-1/4"- )}+ className={twMerge("cursor-pointer", isSubOrganization ? "w-1/5" : "w-1/4")}onClick={() => handleSort(OrgIdentityOrderBy.Role)}>Role