Skip to content

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

feat: added statistics

Sheen Capadngan1e157af9919d
diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.ts
index 419c1ca270..c1cb13478a 100644
--- a/backend/src/@types/fastify.d.ts
+++ b/backend/src/@types/fastify.d.ts
@@ -135,6 +135,7 @@ import { TNotificationServiceFactory } from "@app/services/notification/notifica
import { TOfflineUsageReportServiceFactory } from "@app/services/offline-usage-report/offline-usage-report-service";
import { TOrgServiceFactory } from "@app/services/org/org-service";
import { TOrgAdminServiceFactory } from "@app/services/org-admin/org-admin-service";
+import { TOrgProductStatsServiceFactory } from "@app/services/org-product-stats/org-product-stats-service";
import { TPkiAlertServiceFactory } from "@app/services/pki-alert/pki-alert-service";
import { TPkiAlertV2ServiceFactory } from "@app/services/pki-alert-v2/pki-alert-v2-service";
import { TPkiApplicationEnrollmentServiceFactory } from "@app/services/pki-application/pki-application-enrollment-service";
@@ -404,6 +405,7 @@ declare module "fastify" {
notification: TNotificationServiceFactory;
announcement: TAnnouncementServiceFactory;
offlineUsageReport: TOfflineUsageReportServiceFactory;
+ orgProductStats: TOrgProductStatsServiceFactory;
pamFolder: TPamFolderServiceFactory;
pamResource: TPamResourceServiceFactory;
pamDomain: TPamDomainServiceFactory;
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 92ba09a0fb..6b4476f555 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -389,6 +389,8 @@ import { orgServiceFactory } from "@app/services/org/org-service";
import { orgAdminServiceFactory } from "@app/services/org-admin/org-admin-service";
import { orgAssetDALFactory } from "@app/services/org-asset/org-asset-dal";
import { orgMembershipDALFactory } from "@app/services/org-membership/org-membership-dal";
+import { orgProductStatsDALFactory } from "@app/services/org-product-stats/org-product-stats-dal";
+import { orgProductStatsServiceFactory } from "@app/services/org-product-stats/org-product-stats-service";
import { pamAccountRotationServiceFactory } from "@app/services/pam-account-rotation/pam-account-rotation-queue";
import { pamSessionExpirationServiceFactory } from "@app/services/pam-session-expiration/pam-session-expiration-queue";
import { dailyExpiringPkiItemAlertQueueServiceFactory } from "@app/services/pki-alert/expiring-pki-item-alert-queue";
@@ -577,6 +579,7 @@ export const registerRoutes = async (
const integrationDAL = integrationDALFactory(db);
const offlineUsageReportDAL = offlineUsageReportDALFactory(db);
+ const orgProductStatsDAL = orgProductStatsDALFactory(db);
const integrationAuthDAL = integrationAuthDALFactory(db);
const webhookDAL = webhookDALFactory(db);
const serviceTokenDAL = serviceTokenDALFactory(db);
@@ -1210,6 +1213,10 @@ export const registerRoutes = async (
licenseService
});
+ const orgProductStatsService = orgProductStatsServiceFactory({
+ orgProductStatsDAL
+ });
+
const orgAdminService = orgAdminServiceFactory({
smtpService,
projectDAL,
@@ -3368,6 +3375,7 @@ export const registerRoutes = async (
authToken: tokenService,
superAdmin: superAdminService,
offlineUsageReport: offlineUsageReportService,
+ orgProductStats: orgProductStatsService,
project: projectService,
projectMembership: projectMembershipService,
projectKey: projectKeyService,
diff --git a/backend/src/server/routes/v1/organization-router.ts b/backend/src/server/routes/v1/organization-router.ts
index fb52971613..6d247c25c7 100644
--- a/backend/src/server/routes/v1/organization-router.ts
+++ b/backend/src/server/routes/v1/organization-router.ts
@@ -643,4 +643,48 @@ export const registerOrgRouter = async (server: FastifyZodProvider) => {
return { identities };
}
});
+
+ server.route({
+ method: "GET",
+ url: "/product-stats",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ hide: true,
+ operationId: "getOrganizationProductStats",
+ description: "Get aggregated product statistics for the organization",
+ response: {
+ 200: z.object({
+ secretManager: z.object({
+ secretsCount: z.number(),
+ projectsCount: z.number()
+ }),
+ certificateManager: z.object({
+ certificatesCount: z.number(),
+ certificateAuthoritiesCount: z.number()
+ }),
+ kms: z.object({
+ keysCount: z.number(),
+ projectsCount: z.number()
+ }),
+ secretScanning: z.object({
+ dataSourcesCount: z.number(),
+ projectsCount: z.number()
+ }),
+ pam: z.object({
+ accountsCount: z.number(),
+ projectsCount: z.number()
+ })
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const stats = await server.services.orgProductStats.getOrgProductStats({
+ actorOrgId: req.permission.orgId
+ });
+ return stats;
+ }
+ });
};
diff --git a/backend/src/services/org-product-stats/index.ts b/backend/src/services/org-product-stats/index.ts
new file mode 100644
index 0000000000..9c6465c98f
--- /dev/null
+++ b/backend/src/services/org-product-stats/index.ts
@@ -0,0 +1,3 @@
+export { orgProductStatsDALFactory, type TOrgProductStatsDALFactory } from "./org-product-stats-dal";
+export { orgProductStatsServiceFactory, type TOrgProductStatsServiceFactory } from "./org-product-stats-service";
+export type { TOrgProductStats, TOrgProductStatsDTO } from "./org-product-stats-types";
diff --git a/backend/src/services/org-product-stats/org-product-stats-dal.ts b/backend/src/services/org-product-stats/org-product-stats-dal.ts
new file mode 100644
index 0000000000..3f86155807
--- /dev/null
+++ b/backend/src/services/org-product-stats/org-product-stats-dal.ts
@@ -0,0 +1,131 @@
+import { Knex } from "knex";
+
+import { TDbClient } from "@app/db";
+import { ProjectType, TableName } from "@app/db/schemas";
+import { DatabaseError } from "@app/lib/errors";
+
+export type TOrgProductStatsDALFactory = ReturnType<typeof orgProductStatsDALFactory>;
+
+export const orgProductStatsDALFactory = (db: TDbClient) => {
+ const countSecretsForOrg = async (orgId: 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`)
+ .join(TableName.Project, `${TableName.Environment}.projectId`, `${TableName.Project}.id`)
+ .where(`${TableName.Project}.orgId`, orgId)
+ .where(`${TableName.Project}.type`, ProjectType.SecretManager)
+ .count(`${TableName.SecretV2}.id as count`)
+ .first()) as { count: string } | undefined;
+
+ return parseInt(result?.count || "0", 10);
+ } catch (error) {
+ throw new DatabaseError({ error, name: "CountSecretsForOrg" });
+ }
+ };
+
+ const countCertificatesForOrg = async (orgId: string, tx?: Knex) => {
+ try {
+ const result = (await (tx || db.replicaNode())(TableName.Certificate)
+ .join(TableName.Project, `${TableName.Certificate}.projectId`, `${TableName.Project}.id`)
+ .where(`${TableName.Project}.orgId`, orgId)
+ .where(`${TableName.Project}.type`, ProjectType.CertificateManager)
+ .count(`${TableName.Certificate}.id as count`)
+ .first()) as { count: string } | undefined;
+
+ return parseInt(result?.count || "0", 10);
+ } catch (error) {
+ throw new DatabaseError({ error, name: "CountCertificatesForOrg" });
+ }
+ };
+
+ const countCertificateAuthoritiesForOrg = async (orgId: string, tx?: Knex) => {
+ try {
+ const result = (await (tx || db.replicaNode())(TableName.CertificateAuthority)
+ .join(TableName.Project, `${TableName.CertificateAuthority}.projectId`, `${TableName.Project}.id`)
+ .where(`${TableName.Project}.orgId`, orgId)
+ .where(`${TableName.Project}.type`, ProjectType.CertificateManager)
+ .count(`${TableName.CertificateAuthority}.id as count`)
+ .first()) as { count: string } | undefined;
+
+ return parseInt(result?.count || "0", 10);
+ } catch (error) {
+ throw new DatabaseError({ error, name: "CountCertificateAuthoritiesForOrg" });
+ }
+ };
+
+ const countKmsKeysForOrg = async (orgId: string, tx?: Knex) => {
+ try {
+ const result = (await (tx || db.replicaNode())(TableName.KmsKey)
+ .join(TableName.Project, `${TableName.KmsKey}.projectId`, `${TableName.Project}.id`)
+ .where(`${TableName.Project}.orgId`, orgId)
+ .where(`${TableName.Project}.type`, ProjectType.KMS)
+ .count(`${TableName.KmsKey}.id as count`)
+ .first()) as { count: string } | undefined;
+
+ return parseInt(result?.count || "0", 10);
+ } catch (error) {
+ throw new DatabaseError({ error, name: "CountKmsKeysForOrg" });
+ }
+ };
+
+ const countDataSourcesForOrg = async (orgId: string, tx?: Knex) => {
+ try {
+ const result = (await (tx || db.replicaNode())(TableName.SecretScanningDataSource)
+ .join(TableName.Project, `${TableName.SecretScanningDataSource}.projectId`, `${TableName.Project}.id`)
+ .where(`${TableName.Project}.orgId`, orgId)
+ .where(`${TableName.Project}.type`, ProjectType.SecretScanning)
+ .count(`${TableName.SecretScanningDataSource}.id as count`)
+ .first()) as { count: string } | undefined;
+
+ return parseInt(result?.count || "0", 10);
+ } catch (error) {
+ throw new DatabaseError({ error, name: "CountDataSourcesForOrg" });
+ }
+ };
+
+ const countPamAccountsForOrg = async (orgId: string, tx?: Knex) => {
+ try {
+ const result = (await (tx || db.replicaNode())(TableName.PamAccount)
+ .join(TableName.Project, `${TableName.PamAccount}.projectId`, `${TableName.Project}.id`)
+ .where(`${TableName.Project}.orgId`, orgId)
+ .where(`${TableName.Project}.type`, ProjectType.PAM)
+ .count(`${TableName.PamAccount}.id as count`)
+ .first()) as { count: string } | undefined;
+
+ return parseInt(result?.count || "0", 10);
+ } catch (error) {
+ throw new DatabaseError({ error, name: "CountPamAccountsForOrg" });
+ }
+ };
+
+ const countProjectsByTypeForOrg = async (orgId: string, tx?: Knex) => {
+ try {
+ const results = (await (tx || db.replicaNode())(TableName.Project)
+ .where("orgId", orgId)
+ .groupBy("type")
+ .select("type")
+ .count("id as count")) as Array<{ type: string; count: string }>;
+
+ return results.reduce(
+ (acc, row) => {
+ acc[row.type as ProjectType] = parseInt(row.count, 10);
+ return acc;
+ },
+ {} as Record<ProjectType, number>
+ );
+ } catch (error) {
+ throw new DatabaseError({ error, name: "CountProjectsByTypeForOrg" });
+ }
+ };
+
+ return {
+ countSecretsForOrg,
+ countCertificatesForOrg,
+ countCertificateAuthoritiesForOrg,
+ countKmsKeysForOrg,
+ countDataSourcesForOrg,
+ countPamAccountsForOrg,
+ countProjectsByTypeForOrg
+ };
+};
diff --git a/backend/src/services/org-product-stats/org-product-stats-service.ts b/backend/src/services/org-product-stats/org-product-stats-service.ts
new file mode 100644
index 0000000000..79421d48c9
--- /dev/null
+++ b/backend/src/services/org-product-stats/org-product-stats-service.ts
@@ -0,0 +1,59 @@
+import { ProjectType } from "@app/db/schemas";
+
+import { TOrgProductStatsDALFactory } from "./org-product-stats-dal";
+import { TOrgProductStats, TOrgProductStatsDTO } from "./org-product-stats-types";
+
+type TOrgProductStatsServiceFactoryDep = {
+ orgProductStatsDAL: TOrgProductStatsDALFactory;
+};
+
+export type TOrgProductStatsServiceFactory = ReturnType<typeof orgProductStatsServiceFactory>;
+
+export const orgProductStatsServiceFactory = ({ orgProductStatsDAL }: TOrgProductStatsServiceFactoryDep) => {
+ const getOrgProductStats = async ({ actorOrgId }: TOrgProductStatsDTO): Promise<TOrgProductStats> => {
+ const [
+ secretsCount,
+ certificatesCount,
+ certificateAuthoritiesCount,
+ keysCount,
+ dataSourcesCount,
+ accountsCount,
+ projectCounts
+ ] = await Promise.all([
+ orgProductStatsDAL.countSecretsForOrg(actorOrgId),
+ orgProductStatsDAL.countCertificatesForOrg(actorOrgId),
+ orgProductStatsDAL.countCertificateAuthoritiesForOrg(actorOrgId),
+ orgProductStatsDAL.countKmsKeysForOrg(actorOrgId),
+ orgProductStatsDAL.countDataSourcesForOrg(actorOrgId),
+ orgProductStatsDAL.countPamAccountsForOrg(actorOrgId),
+ orgProductStatsDAL.countProjectsByTypeForOrg(actorOrgId)
+ ]);
+
+ return {
+ secretManager: {
+ secretsCount,
+ projectsCount: projectCounts[ProjectType.SecretManager] || 0
+ },
+ certificateManager: {
+ certificatesCount,
+ certificateAuthoritiesCount
+ },
+ kms: {
+ keysCount,
+ projectsCount: projectCounts[ProjectType.KMS] || 0
+ },
+ secretScanning: {
+ dataSourcesCount,
+ projectsCount: projectCounts[ProjectType.SecretScanning] || 0
+ },
+ pam: {
+ accountsCount,
+ projectsCount: projectCounts[ProjectType.PAM] || 0
+ }
+ };
+ };
+
+ return {
+ getOrgProductStats
+ };
+};
diff --git a/backend/src/services/org-product-stats/org-product-stats-types.ts b/backend/src/services/org-product-stats/org-product-stats-types.ts
new file mode 100644
index 0000000000..037b804551
--- /dev/null
+++ b/backend/src/services/org-product-stats/org-product-stats-types.ts
@@ -0,0 +1,26 @@
+export type TOrgProductStatsDTO = {
+ actorOrgId: string;
+};
+
+export type TOrgProductStats = {
+ secretManager: {
+ secretsCount: number;
+ projectsCount: number;
+ };
+ certificateManager: {
+ certificatesCount: number;
+ certificateAuthoritiesCount: number;
+ };
+ kms: {
+ keysCount: number;
+ projectsCount: number;
+ };
+ secretScanning: {
+ dataSourcesCount: number;
+ projectsCount: number;
+ };
+ pam: {
+ accountsCount: number;
+ projectsCount: number;
+ };
+};
diff --git a/frontend/src/hooks/api/organization/index.ts b/frontend/src/hooks/api/organization/index.ts
index bd6c6a3cf8..ecf6576353 100644
--- a/frontend/src/hooks/api/organization/index.ts
+++ b/frontend/src/hooks/api/organization/index.ts
@@ -21,6 +21,7 @@ export {
useGetOrgPlansTable,
useGetOrgPlanTable,
useGetOrgPmtMethods,
+ useGetOrgProductStats,
useGetOrgTaxIds,
useGetOrgTrialUrl,
useSearchOrganizationGroups,
@@ -28,3 +29,4 @@ export {
useUpdateOrgBillingDetails,
useUpgradePrivilegeSystem
} from "./queries";
+export type { TOrgProductStats } from "./types";
diff --git a/frontend/src/hooks/api/organization/queries.tsx b/frontend/src/hooks/api/organization/queries.tsx
index 1905348a6b..67e0007c3b 100644
--- a/frontend/src/hooks/api/organization/queries.tsx
+++ b/frontend/src/hooks/api/organization/queries.tsx
@@ -20,6 +20,7 @@ import {
TaxID,
TListOrgIdentitiesDTO,
TOrgIdentitiesList,
+ TOrgProductStats,
UpdateOrgDTO
} from "./types";
@@ -63,7 +64,8 @@ export const organizationKeys = {
getOrgIntegrationAuths: (orgId: string) => [{ orgId }, "integration-auths"] as const,
getOrgById: (orgId: string) => ["organization", { orgId }],
getAvailableIdentities: () => ["available-identities"],
- getAvailableUsers: () => ["available-users"]
+ getAvailableUsers: () => ["available-users"],
+ getOrgProductStats: (orgId: string) => [{ orgId }, "organization-product-stats"] as const
};
export const fetchOrganizations = async () => {
@@ -739,3 +741,13 @@ export const useGetAvailableOrgUsers = (enabled = true) =>
},
enabled
});
+
+export const useGetOrgProductStats = (orgId: string) =>
+ useQuery({
+ queryKey: organizationKeys.getOrgProductStats(orgId),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<TOrgProductStats>("/api/v1/organization/product-stats");
+ return data;
+ },
+ enabled: Boolean(orgId)
+ });
diff --git a/frontend/src/hooks/api/organization/types.ts b/frontend/src/hooks/api/organization/types.ts
index 9c819710dc..df7616b24a 100644
--- a/frontend/src/hooks/api/organization/types.ts
+++ b/frontend/src/hooks/api/organization/types.ts
@@ -178,3 +178,26 @@ export enum OrgMembershipStatus {
Invited = "invited",
Accepted = "accepted"
}
+
+export type TOrgProductStats = {
+ secretManager: {
+ secretsCount: number;
+ projectsCount: number;
+ };
+ certificateManager: {
+ certificatesCount: number;
+ certificateAuthoritiesCount: number;
+ };
+ kms: {
+ keysCount: number;
+ projectsCount: number;
+ };
+ secretScanning: {
+ dataSourcesCount: number;
+ projectsCount: number;
+ };
+ pam: {
+ accountsCount: number;
+ projectsCount: number;
+ };
+};
diff --git a/frontend/src/pages/organization/ProjectsPage/components/ProjectCategoryOverview.tsx b/frontend/src/pages/organization/ProjectsPage/components/ProjectCategoryOverview.tsx
index 925ffe0fe3..9dcdd1d51f 100644
--- a/frontend/src/pages/organization/ProjectsPage/components/ProjectCategoryOverview.tsx
+++ b/frontend/src/pages/organization/ProjectsPage/components/ProjectCategoryOverview.tsx
@@ -24,7 +24,7 @@ import {
getProjectTitle,
projectTypeToUrlSlug
} from "@app/helpers/project";
-import { useGetUserProjects } from "@app/hooks/api";
+import { useGetOrgProductStats, useGetUserProjects } from "@app/hooks/api";
import { useCertManagerInstanceState } from "@app/hooks/api/certManagerInstance";
import { useOrgAdminAccessProject } from "@app/hooks/api/orgAdmin/mutation";
import { Project, ProjectType } from "@app/hooks/api/projects/types";
@@ -37,25 +37,27 @@ const PRODUCT_TYPES: ProjectType[] = [
ProjectType.PAM
];
+const formatNumber = (num: number): string => {
+ return num.toLocaleString();
+};
+
+type ProductStat = {
+ label: string;
+ value: number;
+};
+
export const ProjectCategoryOverview = () => {
const navigate = useNavigate();
const { currentOrg } = useOrganization();
const { permission } = useOrgPermission();
const { data: projects = [], isPending: isProjectsLoading } = useGetUserProjects();
const { data: certManagerInstance } = useCertManagerInstanceState();
+ const { data: productStats } = useGetOrgProductStats(currentOrg?.id ?? "");
const orgAdminAccessProject = useOrgAdminAccessProject();
const [isRequestAccessOpen, setIsRequestAccessOpen] = useState(false);
const [isCertManagerSetupOpen, setIsCertManagerSetupOpen] = useState(false);
- const projectCountsByType = useMemo(
- () =>
- projects.reduce<Partial<Record<ProjectType, number>>>((counts, project) => {
- return { ...counts, [project.type]: (counts[project.type] || 0) + 1 };
- }, {}),
- [projects]
- );
-
const certManagerActiveProjectId = certManagerInstance?.activeProjectId ?? null;
const certManagerActiveProject = useMemo(
() =>
@@ -72,6 +74,40 @@ export const ProjectCategoryOverview = () => {
[projects, certManagerActiveProjectId]
);
+ const getStatsForType = (type: ProjectType): ProductStat[] => {
+ if (!productStats) return [];
+
+ switch (type) {
+ case ProjectType.SecretManager:
+ return [
+ { label: "secrets", value: productStats.secretManager.secretsCount },
+ { label: "projects", value: productStats.secretManager.projectsCount }
+ ];
+ case ProjectType.CertificateManager:
+ return [
+ { label: "certificates", value: productStats.certificateManager.certificatesCount },
+ { label: "CAs", value: productStats.certificateManager.certificateAuthoritiesCount }
+ ];
+ case ProjectType.KMS:
+ return [
+ { label: "keys", value: productStats.kms.keysCount },
+ { label: "projects", value: productStats.kms.projectsCount }
+ ];
+ case ProjectType.SecretScanning:
+ return [
+ { label: "data sources", value: productStats.secretScanning.dataSourcesCount },
+ { label: "projects", value: productStats.secretScanning.projectsCount }
+ ];
+ case ProjectType.PAM:
+ return [
+ { label: "accounts", value: productStats.pam.accountsCount },
+ { label: "projects", value: productStats.pam.projectsCount }
+ ];
+ default:
+ return [];
+ }
+ };
+
const navigateToCertManager = (projectId: string) => {
navigate({
to: "/organizations/$orgId/projects/cert-manager/$projectId/overview",
@@ -148,8 +184,7 @@ export const ProjectCategoryOverview = () => {
<>
<div className="grid grid-cols-1 gap-5 lg:grid-cols-2">
{PRODUCT_TYPES.map((type) => {
- const isCertManager = type === ProjectType.CertificateManager;
- const count = projectCountsByType[type] || 0;
+ const stats = getStatsForType(type);
return (
<Card
@@ -160,25 +195,34 @@ export const ProjectCategoryOverview = () => {
onKeyDown={(e) => {
if (e.key === "Enter") handleTileClick(type);
}}
- className="group relative h-auto cursor-pointer overflow-hidden px-7 transition-all duration-100 before:absolute before:inset-y-0 before:left-0 before:w-1.5 before:bg-mineshaft-400 before:transition-colors before:content-[''] hover:bg-card/80 hover:before:bg-primary"
+ className="h-auto cursor-pointer transition-all duration-100 hover:bg-card/80"
>
<CardHeader>
<CardTitle className="flex items-start justify-between">
<div className="rounded-sm border border-mineshaft-500 bg-mineshaft-600 p-1.5 shadow-inner">
<Lottie className="h-7 w-7 shrink-0" icon={getProjectLottieIcon(type)} />
</div>
- {!isCertManager && count > 1 && (
- <span className="text-xs font-normal text-accent">{count} projects</span>
- )}
</CardTitle>
<CardDescription className="mt-3 text-lg font-semibold text-foreground">
{getProjectTitle(type)}
</CardDescription>
</CardHeader>
- <CardContent>
- <p className="line-clamp-3 text-sm leading-relaxed text-accent">
+ <CardContent className="flex flex-col gap-3">
+ <p className="line-clamp-2 text-sm leading-relaxed text-accent">
{getProjectDescription(type)}
</p>
+ {stats.length > 0 && (
+ <div className="flex items-center gap-4 border-t border-mineshaft-600 pt-3 text-sm">
+ {stats.map((stat) => (
+ <span key={stat.label} className="text-mineshaft-300">
+ <span className="font-semibold text-foreground">
+ {formatNumber(stat.value)}
+ </span>{" "}
+ {stat.label}
+ </span>
+ ))}
+ </div>
+ )}
</CardContent>
</Card>
);