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: add project resource count to secret insights page
Scott Wilson99c66ad86638
diff --git a/backend/src/ee/routes/v1/insights-router.ts b/backend/src/ee/routes/v1/insights-router.tsindex 3093e48ed5..36df7d0dd0 100644--- a/backend/src/ee/routes/v1/insights-router.ts+++ b/backend/src/ee/routes/v1/insights-router.ts@@ -287,4 +287,32 @@ export const registerInsightsRouter = async (server: FastifyZodProvider) => {return result;}});++ server.route({+ method: "GET",+ url: "/secrets/counts",+ config: { rateLimit: readLimit },+ schema: {+ operationId: "getInsightsCounts",+ description: "Get project-wide entity counts for the insights dashboard header",+ security: [{ bearerAuth: [] }],+ querystring: z.object({+ projectId: z.string().trim()+ }),+ response: {+ 200: z.object({+ secretCount: z.number(),+ folderCount: z.number(),+ dynamicSecretCount: z.number(),+ secretRotationCount: z.number(),+ honeyTokenCount: z.number().nullable()+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) => {+ const { projectId } = req.query;+ return server.services.insights.getCounts({ projectId }, req.permission);+ }+ });};diff --git a/backend/src/ee/services/dynamic-secret/dynamic-secret-dal.ts b/backend/src/ee/services/dynamic-secret/dynamic-secret-dal.tsindex 34804815f8..c0bea06751 100644--- a/backend/src/ee/services/dynamic-secret/dynamic-secret-dal.ts+++ b/backend/src/ee/services/dynamic-secret/dynamic-secret-dal.ts@@ -63,6 +63,7 @@ export interface TDynamicSecretDALFactory extends Omit<TOrmify<TableName.Dynamic}>>;countByGatewayPoolId: (gatewayPoolId: string, tx?: Knex) => Promise<number>;+ countByProject: (projectId: string, tx?: Knex) => Promise<number>;}export const dynamicSecretDALFactory = (db: TDbClient): TDynamicSecretDALFactory => {@@ -273,6 +274,22 @@ export const dynamicSecretDALFactory = (db: TDbClient): TDynamicSecretDALFactoryreturn parseInt(String(result?.count || "0"), 10);};+ const countByProject = async (projectId: string, tx?: Knex) => {+ try {+ const result = await (tx || db.replicaNode())(TableName.DynamicSecret)+ .join(TableName.SecretFolder, `${TableName.DynamicSecret}.folderId`, `${TableName.SecretFolder}.id`)+ .join(TableName.Environment, `${TableName.SecretFolder}.envId`, `${TableName.Environment}.id`)+ .where(`${TableName.Environment}.projectId`, projectId)+ .whereNull(`${TableName.Environment}.deleteAfter`)+ .count("* as count")+ .first();++ return Number((result as { count?: string | number })?.count ?? 0);+ } catch (error) {+ throw new DatabaseError({ error, name: "Count by Project - Dynamic Secret" });+ }+ };+return {...orm,listDynamicSecretsByFolderIds,@@ -281,6 +298,7 @@ export const dynamicSecretDALFactory = (db: TDbClient): TDynamicSecretDALFactoryfindByGatewayId,countByGatewayId,findByGatewayPoolId,- countByGatewayPoolId+ countByGatewayPoolId,+ countByProject};};diff --git a/backend/src/ee/services/honey-token/honey-token-dal.ts b/backend/src/ee/services/honey-token/honey-token-dal.tsindex 54e78c774a..385242c052 100644--- a/backend/src/ee/services/honey-token/honey-token-dal.ts+++ b/backend/src/ee/services/honey-token/honey-token-dal.ts@@ -139,6 +139,17 @@ export const honeyTokenDALFactory = (db: TDbClient) => {await (tx || db)(TableName.HoneyTokenSecretMapping).where({ honeyTokenId }).delete();};+ const countByProjectId = async (projectId: string, tx?: Knex) => {+ const [result] = await (tx || db.replicaNode())(TableName.HoneyToken)+ .where(`${TableName.HoneyToken}.projectId`, projectId)+ .whereNot(`${TableName.HoneyToken}.status`, "revoked")+ .count<{ count: string | number }>({+ count: `${TableName.HoneyToken}.id`+ });++ return Number(result?.count ?? 0);+ };+return {...orm,findByFolderIds,@@ -146,6 +157,7 @@ export const honeyTokenDALFactory = (db: TDbClient) => {findOneByTokenIdentifierAndOrgId,findOneByTokenIdentifier,countByOrgId,+ countByProjectId,tryMarkTriggered,createSecretMappings,deleteSecretMappingsByHoneyTokenIddiff --git a/backend/src/ee/services/insights/insights-service.ts b/backend/src/ee/services/insights/insights-service.tsindex da04a16e4c..f41dfe10a2 100644--- a/backend/src/ee/services/insights/insights-service.ts+++ b/backend/src/ee/services/insights/insights-service.ts@@ -4,9 +4,15 @@ import { ForbiddenError } from "@casl/ability";import { ActionProjectType, IdentityAuthMethod } from "@app/db/schemas";import { TAuditLogDALFactory } from "@app/ee/services/audit-log/audit-log-dal";import { EventType } from "@app/ee/services/audit-log/audit-log-types";+import { TDynamicSecretDALFactory } from "@app/ee/services/dynamic-secret/dynamic-secret-dal";+import { THoneyTokenDALFactory } from "@app/ee/services/honey-token/honey-token-dal";import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";-import { ProjectPermissionInsightsActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";+import {+ ProjectPermissionHoneyTokenActions,+ ProjectPermissionInsightsActions,+ ProjectPermissionSub+} from "@app/ee/services/permission/project-permission";import { TSecretRotationV2DALFactory } from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-dal";import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";import { getCacheTtl, withCache } from "@app/lib/cache/with-cache";@@ -28,6 +34,7 @@ import {TGetAccessVolumeDTO,TGetAuthMethodDistributionDTO,TGetInsightsCalendarDTO,+ TGetInsightsCountsDTO,TGetInsightsSummaryDTO,TGetSecretsDuplicationDTO} from "./insights-types";@@ -36,13 +43,18 @@ type TInsightsServiceFactoryDep = {permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;licenseService: Pick<TLicenseServiceFactory, "getPlan">;auditLogDAL: Pick<TAuditLogDALFactory, "countByDateAndActor" | "countByIpAddress" | "countByAuthMethod">;- secretRotationV2DAL: Pick<TSecretRotationV2DALFactory, "findByProjectAndDateRange" | "findByProject">;+ secretRotationV2DAL: Pick<+ TSecretRotationV2DALFactory,+ "findByProjectAndDateRange" | "findByProject" | "countByProject"+ >;reminderDAL: Pick<TReminderDALFactory, "findByProjectAndDateRange">;- folderDAL: Pick<TSecretFolderDALFactory, "findSecretPathByFolderIds">;+ folderDAL: Pick<TSecretFolderDALFactory, "findSecretPathByFolderIds" | "countByProject">;secretV2BridgeDAL: Pick<TSecretV2BridgeDALFactory,- "findStaleByProject" | "countStaleByProject" | "findDuplicatedSecretValues"+ "findStaleByProject" | "countStaleByProject" | "findDuplicatedSecretValues" | "countByProject">;+ dynamicSecretDAL: Pick<TDynamicSecretDALFactory, "countByProject">;+ honeyTokenDAL: Pick<THoneyTokenDALFactory, "countByProjectId">;projectBotService: Pick<TProjectBotServiceFactory, "getBotKey">;projectDAL: Pick<TProjectDALFactory, "findById">;userDAL: Pick<TUserDALFactory, "find">;@@ -84,6 +96,8 @@ const checkInsightsPermission = async (});ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionInsightsActions.Read, ProjectPermissionSub.Insights);++ return { permission };};export const insightsServiceFactory = ({@@ -94,6 +108,8 @@ export const insightsServiceFactory = ({reminderDAL,folderDAL,secretV2BridgeDAL,+ dynamicSecretDAL,+ honeyTokenDAL,projectBotService,projectDAL,userDAL,@@ -565,12 +581,60 @@ export const insightsServiceFactory = ({return { result, remainingTTL };};+ const getCounts = async (dto: TGetInsightsCountsDTO, actorDto: OrgServiceActor) => {+ const { permission } = await checkInsightsPermission(permissionService, licenseService, dto.projectId, actorDto);++ const cacheKey = KeyStorePrefixes.InsightsCache(dto.projectId, "counts");+ const counts = await withCache({+ keyStore,+ key: cacheKey,+ ttlSeconds: KeyStoreTtls.InsightsCacheInSeconds,+ fetcher: async () => {+ const { shouldUseSecretV2Bridge } = await projectBotService.getBotKey(dto.projectId);+ if (!shouldUseSecretV2Bridge) throw new BadRequestError({ message: "Project version not supported" });++ // Honey tokens are a separately licensed feature; return null when unavailable so the UI hides the stat.+ const plan = await licenseService.getPlan(actorDto.orgId);++ const [secretCount, folderCount, dynamicSecretCount, secretRotationCount, honeyTokenCount] = await Promise.all([+ secretV2BridgeDAL.countByProject(dto.projectId),+ folderDAL.countByProject(dto.projectId),+ dynamicSecretDAL.countByProject(dto.projectId),+ secretRotationV2DAL.countByProject(dto.projectId),+ plan.honeyTokens ? honeyTokenDAL.countByProjectId(dto.projectId) : Promise.resolve(null)+ ]);++ return {+ secretCount,+ folderCount,+ dynamicSecretCount,+ secretRotationCount,+ honeyTokenCount+ };+ }+ });++ // Honey-token presence is sensitive (concealment is the feature) and is gated on HoneyTokens.Read+ // everywhere else, so strip the count for callers lacking that permission. Applied outside withCache+ // so the project-scoped cache key stays permission-independent.+ const canReadHoneyTokens = permission.can(+ ProjectPermissionHoneyTokenActions.Read,+ ProjectPermissionSub.HoneyTokens+ );++ return {+ ...counts,+ honeyTokenCount: canReadHoneyTokens ? counts.honeyTokenCount : null+ };+ };+return {getCalendar,getAccessVolume,// getAccessLocations,getAuthMethodDistribution,getSummary,- getSecretsDuplication+ getSecretsDuplication,+ getCounts};};diff --git a/backend/src/ee/services/insights/insights-types.ts b/backend/src/ee/services/insights/insights-types.tsindex 787e335372..d577952b03 100644--- a/backend/src/ee/services/insights/insights-types.ts+++ b/backend/src/ee/services/insights/insights-types.ts@@ -27,3 +27,7 @@ export type TGetInsightsSummaryDTO = {export type TGetSecretsDuplicationDTO = {projectId: string;};++export type TGetInsightsCountsDTO = {+ projectId: string;+};diff --git a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-dal.ts b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-dal.tsindex 7c14a97746..d23747e92e 100644--- a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-dal.ts+++ b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-dal.ts@@ -661,6 +661,25 @@ export const secretRotationV2DALFactory = (}};+ const countByProject = async (projectId: string, tx?: Knex) => {+ try {+ const result = await (tx || db.replicaNode())(TableName.SecretRotationV2)+ .join(TableName.SecretFolder, `${TableName.SecretRotationV2}.folderId`, `${TableName.SecretFolder}.id`)+ .join(TableName.Environment, function joinActiveEnvForSecretRotationV2Count() {+ this.on(`${TableName.SecretFolder}.envId`, `${TableName.Environment}.id`).andOnNull(+ `${TableName.Environment}.deleteAfter`+ );+ })+ .where(`${TableName.Environment}.projectId`, projectId)+ .countDistinct(`${TableName.SecretRotationV2}.id`)+ .first();++ return Number((result as { count?: string | number })?.count ?? 0);+ } catch (error) {+ throw new DatabaseError({ error, name: "Count by Project - Secret Rotation V2" });+ }+ };+return {...secretRotationV2Orm,find,@@ -675,6 +694,7 @@ export const secretRotationV2DALFactory = (findWithMappedSecretsCount,findByProjectAndDateRange,findByProject,+ countByProject,findSecretRotationsToQueue};};diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 8eec14bc63..2418d6d406 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -2753,6 +2753,8 @@ export const registerRoutes = async (reminderDAL,folderDAL,secretV2BridgeDAL,+ dynamicSecretDAL,+ honeyTokenDAL,projectBotService,projectDAL,userDAL,diff --git a/backend/src/services/secret-folder/secret-folder-dal.ts b/backend/src/services/secret-folder/secret-folder-dal.tsindex 031e39b157..f264477446 100644--- a/backend/src/services/secret-folder/secret-folder-dal.ts+++ b/backend/src/services/secret-folder/secret-folder-dal.ts@@ -541,6 +541,24 @@ export const secretFolderDALFactory = (db: TDbClient) => {}};+ const countByProject = async (projectId: string, tx?: Knex) => {+ try {+ const result = await (tx || db.replicaNode())(TableName.SecretFolder)+ .join(TableName.Environment, `${TableName.SecretFolder}.envId`, `${TableName.Environment}.id`)+ .where(`${TableName.Environment}.projectId`, projectId)+ .whereNull(`${TableName.Environment}.deleteAfter`)+ .where(`${TableName.SecretFolder}.isReserved`, false)+ // exclude per-environment root folders (parentId null) so a fresh project reports 0+ .whereNotNull(`${TableName.SecretFolder}.parentId`)+ .count("* as count")+ .first();++ return Number((result as { count?: string | number })?.count ?? 0);+ } catch (error) {+ throw new DatabaseError({ error, name: "countByProject" });+ }+ };+return {...secretFolderOrm,update,@@ -556,6 +574,7 @@ export const secretFolderDALFactory = (db: TDbClient) => {findByParentId,findByEnvId,findFoldersByRootAndIds,- lockFoldersForUpdate+ lockFoldersForUpdate,+ countByProject};};diff --git a/backend/src/services/secret-v2-bridge/secret-v2-bridge-dal.ts b/backend/src/services/secret-v2-bridge/secret-v2-bridge-dal.tsindex ef69056ee0..ee190bd3ca 100644--- a/backend/src/services/secret-v2-bridge/secret-v2-bridge-dal.ts+++ b/backend/src/services/secret-v2-bridge/secret-v2-bridge-dal.ts@@ -1350,6 +1350,25 @@ export const secretV2BridgeDALFactory = ({ db, keyStore }: TSecretV2DalArg) => {}};+ const countByProject = async (projectId: string, tx?: Knex) => {+ try {+ const result = await (tx || db.replicaNode())(TableName.SecretV2)+ .join(TableName.SecretFolder, `${TableName.SecretV2}.folderId`, `${TableName.SecretFolder}.id`)+ .join(TableName.Environment, `${TableName.SecretFolder}.envId`, `${TableName.Environment}.id`)+ .where(`${TableName.Environment}.projectId`, projectId)+ .whereNull(`${TableName.Environment}.deleteAfter`)+ // mirror the dashboard count (countByFolderIds): exclude personal/override secrets,+ // include honey-token + rotation backing secrets, count records (not distinct keys)+ .whereNull(`${TableName.SecretV2}.userId`)+ .count("* as count")+ .first();++ return Number((result as { count?: string | number })?.count ?? 0);+ } catch (error) {+ throw new DatabaseError({ error, name: "countByProject" });+ }+ };+return {...secretOrm,update,@@ -1370,6 +1389,7 @@ export const secretV2BridgeDALFactory = ({ db, keyStore }: TSecretV2DalArg) => {countByFolderIds,findStaleByProject,countStaleByProject,+ countByProject,findDuplicatedSecretValues,findOne,find,diff --git a/frontend/src/hooks/api/secretInsights/queries.tsx b/frontend/src/hooks/api/secretInsights/queries.tsxindex c6f3a4e6a4..f85e053dce 100644--- a/frontend/src/hooks/api/secretInsights/queries.tsx+++ b/frontend/src/hooks/api/secretInsights/queries.tsx@@ -7,6 +7,8 @@ import {TGetAuthMethodDistributionResponse,TGetCalendarInsightsDTO,TGetCalendarInsightsResponse,+ TGetInsightsCountsDTO,+ TGetInsightsCountsResponse,TGetInsightsSummaryDTO,TGetInsightsSummaryResponse,// TGetSecretAccessLocationsDTO,@@ -31,6 +33,8 @@ export const secretInsightsKeys = {[...secretInsightsKeys.all(), "auth-method-distribution", params] as const,summary: (params: TGetInsightsSummaryDTO) =>[...secretInsightsKeys.all(), "summary", params] as const,+ counts: (params: TGetInsightsCountsDTO) =>+ [...secretInsightsKeys.all(), "counts", params] as const,secretsDuplication: (params: TGetSecretsDuplicationDTO) =>[...secretInsightsKeys.all(), "secrets-duplication", params] as const,blindIndexStatus: (params: TGetSecretBlindIndexStatusDTO) =>@@ -169,6 +173,32 @@ export const useGetInsightsSummary = (});};+export const useGetInsightsCounts = (+ params: TGetInsightsCountsDTO,+ options?: Omit<+ UseQueryOptions<+ TGetInsightsCountsResponse,+ unknown,+ TGetInsightsCountsResponse,+ ReturnType<typeof secretInsightsKeys.counts>+ >,+ "queryKey" | "queryFn"+ >+) => {+ return useQuery({+ queryKey: secretInsightsKeys.counts(params),+ queryFn: async () => {+ const { data } = await apiRequest.get<TGetInsightsCountsResponse>(+ "/api/v1/insights/secrets/counts",+ { params }+ );+ return data;+ },+ staleTime: INSIGHTS_STALE_TIME,+ ...options+ });+};+export const useGetSecretsDuplication = (params: TGetSecretsDuplicationDTO,options?: Omit<diff --git a/frontend/src/hooks/api/secretInsights/types.ts b/frontend/src/hooks/api/secretInsights/types.tsindex 90a6371f37..65ca709b37 100644--- a/frontend/src/hooks/api/secretInsights/types.ts+++ b/frontend/src/hooks/api/secretInsights/types.ts@@ -152,3 +152,15 @@ export type TGetSecretBlindIndexStatusResponse = {status: "not-found" | "pending" | "completed" | "failed";message?: string;};++export type TGetInsightsCountsDTO = {+ projectId: string;+};++export type TGetInsightsCountsResponse = {+ secretCount: number;+ folderCount: number;+ dynamicSecretCount: number;+ secretRotationCount: number;+ honeyTokenCount: number | null;+};diff --git a/frontend/src/pages/secret-manager/InsightsPage/InsightsPage.tsx b/frontend/src/pages/secret-manager/InsightsPage/InsightsPage.tsxindex df04030b17..703c96ea89 100644--- a/frontend/src/pages/secret-manager/InsightsPage/InsightsPage.tsx+++ b/frontend/src/pages/secret-manager/InsightsPage/InsightsPage.tsx@@ -1,15 +1,27 @@-import { useEffect } from "react";+import { Fragment, ReactNode, useEffect } from "react";import { Helmet } from "react-helmet";+import {+ FingerprintIcon,+ FolderIcon,+ HexagonIcon,+ KeyIcon,+ LayersIcon,+ RefreshCwIcon+} from "lucide-react";import { UpgradePlanModal } from "@app/components/license/UpgradePlanModal";import { PageHeader } from "@app/components/v2";import {ProjectPermissionInsightsActions,ProjectPermissionSub,+ useProject,+ useProjectPermission,useSubscription} from "@app/context";+import { ProjectPermissionHoneyTokenActions } from "@app/context/ProjectPermissionContext/types";import { withProjectPermission } from "@app/hoc";import { ProjectType } from "@app/hooks/api/projects/types";+import { useGetInsightsCounts } from "@app/hooks/api/secretInsights/queries";import { usePopUp } from "@app/hooks/usePopUp";import {@@ -23,24 +35,96 @@ import {export const InsightsPage = withProjectPermission(() => {const { subscription } = useSubscription();+ const { currentProject, projectId } = useProject();+ const { permission } = useProjectPermission();const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp(["upgradePlan"] as const);+ const { data: counts } = useGetInsightsCounts(+ { projectId },+ { enabled: Boolean(subscription?.secretAccessInsights) }+ );+useEffect(() => {if (subscription && !subscription.secretAccessInsights) {handlePopUpOpen("upgradePlan");}}, [subscription]);+ const canReadHoneyTokens = permission.can(+ ProjectPermissionHoneyTokenActions.Read,+ ProjectPermissionSub.HoneyTokens+ );++ const headerStats: { label: string; value: number; icon: ReactNode }[] = counts+ ? [+ {+ label: "secrets",+ value: counts.secretCount,+ icon: <KeyIcon className="size-3.5 text-accent" />+ },+ {+ label: "environments",+ value: currentProject.environments.length,+ icon: <LayersIcon className="size-3.5 text-accent" />+ },+ {+ label: "folders",+ value: counts.folderCount,+ icon: <FolderIcon className="size-3.5 text-folder" />+ },+ {+ label: "rotations",+ value: counts.secretRotationCount,+ icon: <RefreshCwIcon className="size-3.5 text-secret-rotation" />+ },+ {+ label: "dynamic secrets",+ value: counts.dynamicSecretCount,+ icon: <FingerprintIcon className="size-3.5 text-dynamic-secret" />+ },+ ...(counts.honeyTokenCount !== null && canReadHoneyTokens+ ? [+ {+ label: "honey tokens",+ value: counts.honeyTokenCount,+ icon: <HexagonIcon className="size-3.5 text-yellow-700" />+ }+ ]+ : [])+ ]+ : [];++ const renderStatStrip = (className: string) => (+ <div className={`flex-wrap items-center gap-x-2 gap-y-1 text-xs text-accent ${className}`}>+ {headerStats.map((stat, idx) => (+ <Fragment key={stat.label}>+ {idx > 0 && <span className="text-border">|</span>}+ <span className="flex items-center gap-1 whitespace-nowrap">+ {stat.icon}+ <span className="ml-1">+ <span className="text-foreground/75">{stat.value.toLocaleString()}</span>{" "}+ {stat.label}+ </span>+ </span>+ </Fragment>+ ))}+ </div>+ );+return (<><Helmet><title>Insights</title></Helmet><PageHeader+ className="mb-4 dashboard:mb-10"scope={ProjectType.SecretManager}title="Secret Insights"description="Monitor upcoming secret rotations and reminders across your project."- />+ >+ {headerStats.length > 0 && renderStatStrip("hidden justify-end dashboard:flex")}+ </PageHeader>+ {headerStats.length > 0 && renderStatStrip("mb-6 flex justify-start dashboard:hidden")}<InsightsSummaryCards /><div className="mt-6 grid items-start gap-6 xl:grid-cols-[1.3fr_1fr]"><div className="flex flex-col gap-6">