Skip to content

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

refac: move everything to insights service

adilsond41592dc9ed8
diff --git a/backend/e2e-test/product-insights-project-warnings.spec.ts b/backend/e2e-test/insights-project-warnings.spec.ts
similarity index 93%
rename from backend/e2e-test/product-insights-project-warnings.spec.ts
rename to backend/e2e-test/insights-project-warnings.spec.ts
index 9f63403ef9..a1d0bc3978 100644
--- a/backend/e2e-test/product-insights-project-warnings.spec.ts
+++ b/backend/e2e-test/insights-project-warnings.spec.ts
@@ -28,13 +28,19 @@ import {
OrgPermissionSubjects
} from "@app/ee/services/permission/org-permission";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
-import { productInsightsDALFactory } from "@app/ee/services/product-insights/product-insights-dal";
-import { productInsightsServiceFactory } from "@app/ee/services/product-insights/product-insights-service";
-import { TGetSecretsProjectWarningsDTO } from "@app/ee/services/product-insights/product-insights-types";
+import { insightsDALFactory } from "@app/ee/services/insights/insights-dal";
+import { insightsServiceFactory } from "@app/ee/services/insights/insights-service";
+import { TGetSecretsProjectWarningsDTO } from "@app/ee/services/insights/insights-types";
import { SecretRotationStatus } from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-enums";
import { ActorType, AuthMethod } from "@app/services/auth/auth-type";
import { SecretSyncStatus } from "@app/services/secret-sync/secret-sync-types";
+import {
+ passThroughKeyStore,
+ projectScopedInsightsDepStubs,
+ unreachableGetProjectPermission
+} from "./testUtils/insights";
+
declare const testDb: Knex;
const ORG_ID = randomUUID();
@@ -87,7 +93,8 @@ const buildPermission = (canRead: boolean): MongoAbility<OrgPermissionSet> =>
let canReadInsights = true;
let planHasInsights = true;
-const permissionService: Pick<TPermissionServiceFactory, "getOrgPermission"> = {
+const permissionService: Pick<TPermissionServiceFactory, "getOrgPermission" | "getProjectPermission"> = {
+ ...unreachableGetProjectPermission,
getOrgPermission: async () => ({
permission: buildPermission(canReadInsights),
memberships: [],
@@ -99,15 +106,15 @@ const licenseService = {
getPlan: async () => ({ secretAccessInsights: planHasInsights }) as unknown as TFeatureSet
};
-const productInsightsService = productInsightsServiceFactory({
+const insightsService = insightsServiceFactory({
+ ...projectScopedInsightsDepStubs,
permissionService,
licenseService,
orgDAL: { countAllOrgMembers: async () => 0 },
identityOrgMembershipDAL: { countAllOrgIdentities: async () => 0 },
dynamicSecretLeaseDAL: { countLeasesForOrg: async () => 0 },
- productInsightsDAL: productInsightsDALFactory(testDb),
- // Pass-through stub: every read misses so each call hits the database directly.
- keyStore: { getItem: async () => null, setItemWithExpiry: async () => "OK" }
+ insightsDAL: insightsDALFactory(testDb),
+ keyStore: passThroughKeyStore
});
const actor = (orgId: string, page?: { offset: number; limit: number }): TGetSecretsProjectWarningsDTO => ({
@@ -127,7 +134,7 @@ const secret = (folderId: string, overrides: Partial<TSecretsV2Insert> = {}): TS
...overrides
});
-describe("product-insights secrets project warnings", () => {
+describe("insights secrets project warnings", () => {
beforeAll(async () => {
const orgRows: (TOrganizationsInsert & { id: string })[] = [
{ id: ORG_ID, name: `warnings-${suffix}`, slug: `warnings-${suffix}` },
@@ -310,7 +317,7 @@ describe("product-insights secrets project warnings", () => {
});
test("returns all secret-manager projects ordered by severity with correct counts", async () => {
- const result = await productInsightsService.getSecretsProjectWarnings(actor(ORG_ID));
+ const result = await insightsService.getSecretsProjectWarnings(actor(ORG_ID));
// warn, clean, noBlindIndex, deletedEnv. The PAM project, the soft-deleted
// project, the v1 project and the other org's project are excluded from the listing.
@@ -369,7 +376,7 @@ describe("product-insights secrets project warnings", () => {
});
test("pagination slices rows while window totals stay constant", async () => {
- const page = await productInsightsService.getSecretsProjectWarnings(actor(ORG_ID, { offset: 1, limit: 2 }));
+ const page = await insightsService.getSecretsProjectWarnings(actor(ORG_ID, { offset: 1, limit: 2 }));
expect(page.totalProjects).toBe(4);
expect(page.projectsWithIssues).toBe(1);
@@ -379,7 +386,7 @@ describe("product-insights secrets project warnings", () => {
});
test("an organization with no projects reports empty results", async () => {
- const result = await productInsightsService.getSecretsProjectWarnings(actor(randomUUID()));
+ const result = await insightsService.getSecretsProjectWarnings(actor(randomUUID()));
expect(result.projects).toEqual([]);
expect(result.totalProjects).toBe(0);
expect(result.projectsWithIssues).toBe(0);
@@ -388,7 +395,7 @@ describe("product-insights secrets project warnings", () => {
test("throws when the actor cannot read secrets management insights", async () => {
canReadInsights = false;
try {
- await expect(productInsightsService.getSecretsProjectWarnings(actor(ORG_ID))).rejects.toBeInstanceOf(
+ await expect(insightsService.getSecretsProjectWarnings(actor(ORG_ID))).rejects.toBeInstanceOf(
ForbiddenError
);
} finally {
@@ -399,7 +406,7 @@ describe("product-insights secrets project warnings", () => {
test("throws when the plan does not include secret access insights", async () => {
planHasInsights = false;
try {
- await expect(productInsightsService.getSecretsProjectWarnings(actor(ORG_ID))).rejects.toThrow(
+ await expect(insightsService.getSecretsProjectWarnings(actor(ORG_ID))).rejects.toThrow(
/Upgrade your plan/
);
} finally {
diff --git a/backend/e2e-test/product-insights-service.spec.ts b/backend/e2e-test/insights-usage.spec.ts
similarity index 90%
rename from backend/e2e-test/product-insights-service.spec.ts
rename to backend/e2e-test/insights-usage.spec.ts
index 016393715d..23709688b9 100644
--- a/backend/e2e-test/product-insights-service.spec.ts
+++ b/backend/e2e-test/insights-usage.spec.ts
@@ -27,13 +27,19 @@ import {
OrgPermissionSubjects
} from "@app/ee/services/permission/org-permission";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
-import { productInsightsDALFactory } from "@app/ee/services/product-insights/product-insights-dal";
-import { productInsightsServiceFactory } from "@app/ee/services/product-insights/product-insights-service";
-import { TProductInsightsDTO } from "@app/ee/services/product-insights/product-insights-types";
+import { insightsDALFactory } from "@app/ee/services/insights/insights-dal";
+import { insightsServiceFactory } from "@app/ee/services/insights/insights-service";
+import { TOrgInsightsDTO } from "@app/ee/services/insights/insights-types";
import { ActorType, AuthMethod } from "@app/services/auth/auth-type";
import { identityOrgDALFactory } from "@app/services/identity/identity-org-dal";
import { orgDALFactory } from "@app/services/org/org-dal";
+import {
+ passThroughKeyStore,
+ projectScopedInsightsDepStubs,
+ unreachableGetProjectPermission
+} from "./testUtils/insights";
+
declare const testDb: Knex;
const ORG_ID = randomUUID();
@@ -94,7 +100,8 @@ const buildPermission = (canRead: boolean): MongoAbility<OrgPermissionSet> =>
let canReadInsights = true;
let planHasInsights = true;
-const permissionService: Pick<TPermissionServiceFactory, "getOrgPermission"> = {
+const permissionService: Pick<TPermissionServiceFactory, "getOrgPermission" | "getProjectPermission"> = {
+ ...unreachableGetProjectPermission,
getOrgPermission: async () => ({
permission: buildPermission(canReadInsights),
memberships: [],
@@ -106,18 +113,18 @@ const licenseService = {
getPlan: async () => ({ secretAccessInsights: planHasInsights }) as unknown as TFeatureSet
};
-const productInsightsService = productInsightsServiceFactory({
+const insightsService = insightsServiceFactory({
+ ...projectScopedInsightsDepStubs,
permissionService,
licenseService,
orgDAL: orgDALFactory(testDb),
identityOrgMembershipDAL: identityOrgDALFactory(testDb),
dynamicSecretLeaseDAL: dynamicSecretLeaseDALFactory(testDb),
- productInsightsDAL: productInsightsDALFactory(testDb),
- // Pass-through stub: every read misses so each call hits the database directly.
- keyStore: { getItem: async () => null, setItemWithExpiry: async () => "OK" }
+ insightsDAL: insightsDALFactory(testDb),
+ keyStore: passThroughKeyStore
});
-const actor = (orgId: string): TProductInsightsDTO => ({
+const actor = (orgId: string): TOrgInsightsDTO => ({
actor: ActorType.USER,
actorId: ids.uCounted,
actorAuthMethod: AuthMethod.EMAIL,
@@ -136,7 +143,7 @@ const lease = (dynamicSecretId: string): TDynamicSecretLeasesInsert & { id: stri
};
};
-describe("product-insights secrets usage insights", () => {
+describe("insights secrets usage insights", () => {
beforeAll(async () => {
// The generated *Insert types omit the immutable `id` key, and TS's excess-property check only
// fires on fresh object literals, so fixtures are held in typed consts to set explicit ids.
@@ -322,7 +329,7 @@ describe("product-insights secrets usage insights", () => {
});
test("returns the three usage counts for the organization", async () => {
- const insights = await productInsightsService.getSecretsUsageInsights(actor(ORG_ID));
+ const insights = await insightsService.getSecretsUsageInsights(actor(ORG_ID));
// uCounted only: the ghost, the invited and the deactivated membership are all excluded.
expect(insights.users).toBe(1);
@@ -343,22 +350,22 @@ describe("product-insights secrets usage insights", () => {
// every lease ever created.
await testDb(TableName.DynamicSecretLease).where({ id: revoked!.id }).delete();
- const insights = await productInsightsService.getSecretsUsageInsights(actor(ORG_ID));
+ const insights = await insightsService.getSecretsUsageInsights(actor(ORG_ID));
expect(insights.activeLeases).toBe(1);
await testDb(TableName.DynamicSecretLease).insert(lease(scopes.counted.dynamicSecretId));
- expect((await productInsightsService.getSecretsUsageInsights(actor(ORG_ID))).activeLeases).toBe(2);
+ expect((await insightsService.getSecretsUsageInsights(actor(ORG_ID))).activeLeases).toBe(2);
});
test("an organization with no resources reports zeroes", async () => {
- const insights = await productInsightsService.getSecretsUsageInsights(actor(randomUUID()));
+ const insights = await insightsService.getSecretsUsageInsights(actor(randomUUID()));
expect(insights).toEqual({ activeLeases: 0, users: 0, identities: 0 });
});
test("throws when the actor cannot read secrets management insights", async () => {
canReadInsights = false;
try {
- await expect(productInsightsService.getSecretsUsageInsights(actor(ORG_ID))).rejects.toBeInstanceOf(
+ await expect(insightsService.getSecretsUsageInsights(actor(ORG_ID))).rejects.toBeInstanceOf(
ForbiddenError
);
} finally {
@@ -369,7 +376,7 @@ describe("product-insights secrets usage insights", () => {
test("throws when the plan does not include secret access insights", async () => {
planHasInsights = false;
try {
- await expect(productInsightsService.getSecretsUsageInsights(actor(ORG_ID))).rejects.toThrow(/Upgrade your plan/);
+ await expect(insightsService.getSecretsUsageInsights(actor(ORG_ID))).rejects.toThrow(/Upgrade your plan/);
} finally {
planHasInsights = true;
}
diff --git a/backend/e2e-test/routes/v1/product-insights.spec.ts b/backend/e2e-test/routes/v1/insights.spec.ts
similarity index 86%
rename from backend/e2e-test/routes/v1/product-insights.spec.ts
rename to backend/e2e-test/routes/v1/insights.spec.ts
index d604e7707f..fd1b8b956e 100644
--- a/backend/e2e-test/routes/v1/product-insights.spec.ts
+++ b/backend/e2e-test/routes/v1/insights.spec.ts
@@ -1,11 +1,11 @@
import { describe, expect, test } from "vitest";
-const URL = "/api/v1/product-insights/secrets/usage-insights";
+const URL = "/api/v1/insights/secrets/usage-insights";
-// The counting itself is covered against a real database in e2e-test/product-insights-service.spec.ts.
+// The counting itself is covered against a real database in e2e-test/insights-usage.spec.ts.
// This file only asserts the route wiring, because the e2e instance runs unlicensed and the plan gate
// therefore rejects every request before any count is taken.
-describe("Product Insights V1 Router", async () => {
+describe("Insights V1 Router (org-scoped)", async () => {
test("GET usage insights is registered and refuses on plan restriction", async () => {
const res = await testServer.inject({
method: "GET",
@@ -19,7 +19,7 @@ describe("Product Insights V1 Router", async () => {
expect(res.json().message).toContain("Upgrade your plan");
});
- const WARNINGS_URL = "/api/v1/product-insights/secrets/project-warnings";
+ const WARNINGS_URL = "/api/v1/insights/secrets/project-warnings";
test("GET project warnings is registered and refuses on plan restriction", async () => {
const res = await testServer.inject({
diff --git a/backend/e2e-test/testUtils/insights.ts b/backend/e2e-test/testUtils/insights.ts
new file mode 100644
index 0000000000..b3446f56fa
--- /dev/null
+++ b/backend/e2e-test/testUtils/insights.ts
@@ -0,0 +1,89 @@
+import { TInsightsServiceFactoryDep } from "@app/ee/services/insights/insights-service";
+
+// The insights service covers both the per-project dashboard and the org-wide aggregates, so its factory
+// takes every dependency both halves need. Specs that only exercise the org-wide methods supply these
+// stubs for the project-scoped half.
+//
+// They throw rather than return empty values on purpose: a spec that accidentally reaches a project-scoped
+// code path should fail loudly instead of quietly asserting against a zero the stub invented.
+const unreachable =
+ (method: string) =>
+ (): never => {
+ throw new Error(
+ `insights test stub: ${method} was called, but this spec only exercises org-scoped insights. ` +
+ `Provide a real dependency if the assertion under test needs it.`
+ );
+ };
+
+// Specs supply their own getOrgPermission; this fills the other half of the permissionService contract.
+export const unreachableGetProjectPermission: Pick<
+ TInsightsServiceFactoryDep["permissionService"],
+ "getProjectPermission"
+> = {
+ getProjectPermission: unreachable("permissionService.getProjectPermission")
+};
+
+export const projectScopedInsightsDepStubs: Pick<
+ TInsightsServiceFactoryDep,
+ | "auditLogDAL"
+ | "secretRotationV2DAL"
+ | "reminderDAL"
+ | "folderDAL"
+ | "secretV2BridgeDAL"
+ | "dynamicSecretDAL"
+ | "honeyTokenDAL"
+ | "projectBotService"
+ | "projectDAL"
+ | "userDAL"
+ | "kmsService"
+> = {
+ auditLogDAL: {
+ countByDateAndActor: unreachable("auditLogDAL.countByDateAndActor"),
+ countByIpAddress: unreachable("auditLogDAL.countByIpAddress"),
+ countByAuthMethod: unreachable("auditLogDAL.countByAuthMethod")
+ },
+ secretRotationV2DAL: {
+ findByProjectAndDateRange: unreachable("secretRotationV2DAL.findByProjectAndDateRange"),
+ findByProject: unreachable("secretRotationV2DAL.findByProject"),
+ countByProject: unreachable("secretRotationV2DAL.countByProject")
+ },
+ reminderDAL: {
+ findByProjectAndDateRange: unreachable("reminderDAL.findByProjectAndDateRange")
+ },
+ folderDAL: {
+ findSecretPathByFolderIds: unreachable("folderDAL.findSecretPathByFolderIds"),
+ countByProject: unreachable("folderDAL.countByProject")
+ },
+ secretV2BridgeDAL: {
+ findStaleByProject: unreachable("secretV2BridgeDAL.findStaleByProject"),
+ countStaleByProject: unreachable("secretV2BridgeDAL.countStaleByProject"),
+ findDuplicatedSecretValues: unreachable("secretV2BridgeDAL.findDuplicatedSecretValues"),
+ countByProject: unreachable("secretV2BridgeDAL.countByProject")
+ },
+ dynamicSecretDAL: {
+ countByProject: unreachable("dynamicSecretDAL.countByProject")
+ },
+ honeyTokenDAL: {
+ countByProjectId: unreachable("honeyTokenDAL.countByProjectId")
+ },
+ projectBotService: {
+ getBotKey: unreachable("projectBotService.getBotKey")
+ },
+ projectDAL: {
+ findById: unreachable("projectDAL.findById")
+ },
+ userDAL: {
+ find: unreachable("userDAL.find")
+ },
+ kmsService: {
+ createCipherPairWithDataKey: unreachable("kmsService.createCipherPairWithDataKey")
+ }
+};
+
+// getSecretsUsageInsights does not cache; getSecretsProjectWarnings does. A pass-through keyStore makes every
+// read miss so each call hits the database directly.
+export const passThroughKeyStore: TInsightsServiceFactoryDep["keyStore"] = {
+ getItem: async () => null,
+ setItemWithExpiry: async () => "OK",
+ ttl: async () => -2
+};
diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.ts
index 4b12df9123..3cfaee5827 100644
--- a/backend/src/@types/fastify.d.ts
+++ b/backend/src/@types/fastify.d.ts
@@ -51,7 +51,6 @@ import { TPkiAcmeServiceFactory } from "@app/ee/services/pki-acme/pki-acme-types
import { TPkiDiscoveryServiceFactory } from "@app/ee/services/pki-discovery/pki-discovery-service";
import { TPkiInstallationServiceFactory } from "@app/ee/services/pki-discovery/pki-installation-service";
import { TPkiScepServiceFactory } from "@app/ee/services/pki-scep/pki-scep-service";
-import { TProductInsightsServiceFactory } from "@app/ee/services/product-insights/product-insights-service";
import { TProjectEventsService } from "@app/ee/services/project-events/project-events-service";
import { TProjectEventsSSEService } from "@app/ee/services/project-events/project-events-sse-service";
import { TProjectTemplateServiceFactory } from "@app/ee/services/project-template/project-template-types";
@@ -382,7 +381,6 @@ declare module "fastify" {
dynamicSecret: TDynamicSecretServiceFactory;
dynamicSecretLease: TDynamicSecretLeaseServiceFactory;
emailDomain: TEmailDomainServiceFactory;
- productInsights: TProductInsightsServiceFactory;
secretSharing: TSecretSharingServiceFactory;
rateLimit: TRateLimitServiceFactory;
userActivation: TUserActivationServiceFactory;
diff --git a/backend/src/ee/routes/v1/index.ts b/backend/src/ee/routes/v1/index.ts
index c03d8fe4b7..1a621cf7bf 100644
--- a/backend/src/ee/routes/v1/index.ts
+++ b/backend/src/ee/routes/v1/index.ts
@@ -38,7 +38,6 @@ import { registerPITRouter } from "./pit-router";
import { registerPkiAcmeRouter } from "./pki-acme-router";
import { registerPkiDiscoveryRouter } from "./pki-discovery-router";
import { registerPkiInstallationRouter } from "./pki-installation-router";
-import { registerProductInsightsRouter } from "./product-insights-router";
import { registerProjectRoleRouter } from "./project-role-router";
import { registerProjectRouter } from "./project-router";
import { registerProxiedServiceRouter } from "./proxied-service-router";
@@ -111,7 +110,6 @@ export const registerV1EERoutes = async (server: FastifyZodProvider) => {
await server.register(registerAgentProxyCaRouter, { prefix: "/organization/agent-proxy-ca" });
await server.register(registerInsightsRouter, { prefix: "/insights" });
- await server.register(registerProductInsightsRouter, { prefix: "/product-insights" });
await server.register(
async (pkiRouter) => {
diff --git a/backend/src/ee/routes/v1/insights-router.ts b/backend/src/ee/routes/v1/insights-router.ts
index 10ff53fd9a..7b09e6cc2c 100644
--- a/backend/src/ee/routes/v1/insights-router.ts
+++ b/backend/src/ee/routes/v1/insights-router.ts
@@ -12,6 +12,8 @@ import {
AuditReportStatus,
AuditReportType
} from "@app/ee/services/audit-report/audit-report-types";
+import { SecretsProjectWarningsSchema, SecretsUsageInsightsSchema } from "@app/ee/services/insights/insights-schemas";
+import { INSIGHTS } from "@app/lib/api-docs";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AuthMode } from "@app/services/auth/auth-type";
@@ -47,6 +49,106 @@ const AuditReportSchema = z.object({
});
export const registerInsightsRouter = async (server: FastifyZodProvider) => {
+ // Org-scoped insights. These aggregate across every secret management project in the organization,
+ // so they carry no :projectId and are gated on the org-level Secrets Management Insights subject.
+ // Everything below this block is project-scoped and lives under /:projectId.
+
+ server.route({
+ method: "GET",
+ url: "/secrets/usage-insights",
+ config: {
+ rateLimit: readLimit
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ schema: {
+ operationId: "getSecretsUsageInsights",
+ description: "Get secrets management usage counts for the requesting organization.",
+ security: [{ bearerAuth: [] }],
+ response: {
+ 200: z.object({
+ usageInsights: SecretsUsageInsightsSchema
+ })
+ }
+ },
+ handler: async (req) => {
+ const usageInsights = await server.services.insights.getSecretsUsageInsights({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ orgId: req.permission.orgId
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ event: {
+ type: EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_USAGE,
+ metadata: usageInsights
+ }
+ });
+
+ return { usageInsights };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/secrets/project-warnings",
+ config: {
+ rateLimit: readLimit
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ schema: {
+ operationId: "getSecretsProjectWarnings",
+ description:
+ "List the organization's secret management projects with outstanding issue counts, ordered by severity.",
+ security: [{ bearerAuth: [] }],
+ querystring: z.object({
+ offset: z.coerce
+ .number()
+ .int()
+ .min(0)
+ .max(10000)
+ .default(0)
+ .describe(INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.offset),
+ limit: z.coerce.number().int().min(1).max(100).default(20).describe(INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.limit)
+ }),
+ response: {
+ 200: z.object({
+ projectWarnings: SecretsProjectWarningsSchema
+ })
+ }
+ },
+ handler: async (req) => {
+ const projectWarnings = await server.services.insights.getSecretsProjectWarnings({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ orgId: req.permission.orgId,
+ offset: req.query.offset,
+ limit: req.query.limit
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ event: {
+ type: EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_PROJECT_WARNINGS,
+ metadata: {
+ totalProjects: projectWarnings.totalProjects,
+ projectsWithIssues: projectWarnings.projectsWithIssues,
+ offset: req.query.offset,
+ limit: req.query.limit
+ }
+ }
+ });
+
+ return { projectWarnings };
+ }
+ });
+
server.route({
method: "GET",
url: "/:projectId/secrets/calendar",
diff --git a/backend/src/ee/routes/v1/product-insights-router.ts b/backend/src/ee/routes/v1/product-insights-router.ts
deleted file mode 100644
index fe3e61bf81..0000000000
--- a/backend/src/ee/routes/v1/product-insights-router.ts
+++ /dev/null
@@ -1,113 +0,0 @@
-import { z } from "zod";
-
-import { EventType } from "@app/ee/services/audit-log/audit-log-types";
-import {
- SecretsProjectWarningsSchema,
- SecretsUsageInsightsSchema
-} from "@app/ee/services/product-insights/product-insights-schemas";
-import { PRODUCT_INSIGHTS } from "@app/lib/api-docs";
-import { readLimit } from "@app/server/config/rateLimiter";
-import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
-import { AuthMode } from "@app/services/auth/auth-type";
-
-export const registerProductInsightsRouter = async (server: FastifyZodProvider) => {
- server.route({
- method: "GET",
- url: "/secrets/usage-insights",
- config: {
- rateLimit: readLimit
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- schema: {
- operationId: "getSecretsUsageInsights",
- description: "Get secrets management usage counts for the requesting organization.",
- response: {
- 200: z.object({
- usageInsights: SecretsUsageInsightsSchema
- })
- }
- },
- handler: async (req) => {
- const usageInsights = await server.services.productInsights.getSecretsUsageInsights({
- actor: req.permission.type,
- actorId: req.permission.id,
- actorAuthMethod: req.permission.authMethod,
- actorOrgId: req.permission.orgId,
- orgId: req.permission.orgId
- });
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- event: {
- type: EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_USAGE,
- metadata: usageInsights
- }
- });
-
- return { usageInsights };
- }
- });
-
- server.route({
- method: "GET",
- url: "/secrets/project-warnings",
- config: {
- rateLimit: readLimit
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- schema: {
- operationId: "getSecretsProjectWarnings",
- description:
- "List the organization's secret management projects with outstanding issue counts, ordered by severity.",
- querystring: z.object({
- offset: z.coerce
- .number()
- .int()
- .min(0)
- .max(10000)
- .default(0)
- .describe(PRODUCT_INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.offset),
- limit: z.coerce
- .number()
- .int()
- .min(1)
- .max(100)
- .default(20)
- .describe(PRODUCT_INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.limit)
- }),
- response: {
- 200: z.object({
- projectWarnings: SecretsProjectWarningsSchema
- })
- }
- },
- handler: async (req) => {
- const projectWarnings = await server.services.productInsights.getSecretsProjectWarnings({
- actor: req.permission.type,
- actorId: req.permission.id,
- actorAuthMethod: req.permission.authMethod,
- actorOrgId: req.permission.orgId,
- orgId: req.permission.orgId,
- offset: req.query.offset,
- limit: req.query.limit
- });
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- event: {
- type: EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_PROJECT_WARNINGS,
- metadata: {
- totalProjects: projectWarnings.totalProjects,
- projectsWithIssues: projectWarnings.projectsWithIssues,
- offset: req.query.offset,
- limit: req.query.limit
- }
- }
- });
-
- return { projectWarnings };
- }
- });
-};
diff --git a/backend/src/ee/services/product-insights/product-insights-dal.ts b/backend/src/ee/services/insights/insights-dal.ts
similarity index 98%
rename from backend/src/ee/services/product-insights/product-insights-dal.ts
rename to backend/src/ee/services/insights/insights-dal.ts
index 112de82cc2..67befcb5a5 100644
--- a/backend/src/ee/services/product-insights/product-insights-dal.ts
+++ b/backend/src/ee/services/insights/insights-dal.ts
@@ -7,7 +7,7 @@ import { SecretRotationStatus } from "@app/ee/services/secret-rotation-v2/secret
import { DatabaseError } from "@app/lib/errors";
import { SecretSyncStatus } from "@app/services/secret-sync/secret-sync-types";
-import { TSecretsProjectWarning } from "./product-insights-types";
+import { TSecretsProjectWarning } from "./insights-types";
// Relative severity weights for ranking projects by outstanding issues. Failed
// rotations are the most urgent signal (a credential that should have changed
@@ -36,9 +36,9 @@ type TProjectWarningRow = {
projectsWithIssues: string | number;
};
-export type TProductInsightsDALFactory = ReturnType<typeof productInsightsDALFactory>;
+export type TInsightsDALFactory = ReturnType<typeof insightsDALFactory>;
-export const productInsightsDALFactory = (db: TDbClient) => {
+export const insightsDALFactory = (db: TDbClient) => {
const findProjectWarningsForOrg = async (
orgId: string,
{ offset, limit, staleBefore }: { offset: number; limit: number; staleBefore: Date },
diff --git a/backend/src/ee/services/insights/insights-schemas.ts b/backend/src/ee/services/insights/insights-schemas.ts
new file mode 100644
index 0000000000..5efc0d1f66
--- /dev/null
+++ b/backend/src/ee/services/insights/insights-schemas.ts
@@ -0,0 +1,34 @@
+import { z } from "zod";
+
+import { INSIGHTS } from "@app/lib/api-docs";
+
+export const SecretsUsageInsightsSchema = z.object({
+ activeLeases: z.number().int().describe(INSIGHTS.GET_SECRETS_USAGE_INSIGHTS.activeLeases),
+ users: z.number().int().describe(INSIGHTS.GET_SECRETS_USAGE_INSIGHTS.users),
+ identities: z.number().int().describe(INSIGHTS.GET_SECRETS_USAGE_INSIGHTS.identities)
+});
+
+export const SecretsProjectWarningSchema = z.object({
+ projectId: z.string().uuid().describe(INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.projectId),
+ projectName: z.string().describe(INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.projectName),
+ projectSlug: z.string().describe(INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.projectSlug),
+ totalSecrets: z.number().int().describe(INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.totalSecrets),
+ severityScore: z.number().int().describe(INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.severityScore),
+ warnings: z
+ .object({
+ duplicatedSecrets: z.number().int().nullable().describe(INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.duplicatedSecrets),
+ staleSecrets: z.number().int().describe(INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.staleSecrets),
+ failedRotations: z.number().int().describe(INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.failedRotations),
+ failedSyncs: z.number().int().describe(INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.failedSyncs),
+ orphanedLeases: z.number().int().describe(INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.orphanedLeases)
+ })
+ .describe(INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.warnings)
+});
+
+export const SecretsProjectWarningsSchema = z.object({
+ projects: SecretsProjectWarningSchema.array(),
+ totalProjects: z.number().int().describe(INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.totalProjects),
+ projectsWithIssues: z.number().int().describe(INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.projectsWithIssues),
+ offset: z.number().int().describe(INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.offset),
+ limit: z.number().int().describe(INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.limit)
+});
diff --git a/backend/src/ee/services/insights/insights-service.ts b/backend/src/ee/services/insights/insights-service.ts
index f41dfe10a2..fab9273d21 100644
--- a/backend/src/ee/services/insights/insights-service.ts
+++ b/backend/src/ee/services/insights/insights-service.ts
@@ -1,12 +1,17 @@
import { ForbiddenError } from "@casl/ability";
// import geoip from "geoip-lite";
-import { ActionProjectType, IdentityAuthMethod } from "@app/db/schemas";
+import { ActionProjectType, IdentityAuthMethod, OrganizationActionScope, TableName } 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 { TDynamicSecretLeaseDALFactory } from "@app/ee/services/dynamic-secret-lease/dynamic-secret-lease-dal";
import { THoneyTokenDALFactory } from "@app/ee/services/honey-token/honey-token-dal";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
+import {
+ OrgPermissionSecretsManagementInsightsActions,
+ OrgPermissionSubjects
+} from "@app/ee/services/permission/org-permission";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import {
ProjectPermissionHoneyTokenActions,
@@ -19,8 +24,10 @@ import { getCacheTtl, withCache } from "@app/lib/cache/with-cache";
import { BadRequestError } from "@app/lib/errors";
import { OrgServiceActor } from "@app/lib/types";
import { ActorType } from "@app/services/auth/auth-type";
+import { TIdentityOrgDALFactory } from "@app/services/identity/identity-org-dal";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { KmsDataKey } from "@app/services/kms/kms-types";
+import { TOrgDALFactory } from "@app/services/org/org-dal";
import { TProjectDALFactory } from "@app/services/project/project-dal";
import { TProjectBotServiceFactory } from "@app/services/project-bot/project-bot-service";
import { TReminderDALFactory } from "@app/services/reminder/reminder-dal";
@@ -29,6 +36,7 @@ import { containsSecretReference } from "@app/services/secret-v2-bridge/secret-r
import { TSecretV2BridgeDALFactory } from "@app/services/secret-v2-bridge/secret-v2-bridge-dal";
import { TUserDALFactory } from "@app/services/user/user-dal";
+import { TInsightsDALFactory } from "./insights-dal";
import {
// TGetAccessLocationsDTO,
TGetAccessVolumeDTO,
@@ -36,11 +44,16 @@ import {
TGetInsightsCalendarDTO,
TGetInsightsCountsDTO,
TGetInsightsSummaryDTO,
- TGetSecretsDuplicationDTO
+ TGetSecretsDuplicationDTO,
+ TGetSecretsProjectWarningsDTO,
+ TGetSecretsUsageInsightsDTO,
+ TOrgInsightsDTO,
+ TSecretsProjectWarnings,
+ TSecretsUsageInsights
} from "./insights-types";
-type TInsightsServiceFactoryDep = {
- permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
+export type TInsightsServiceFactoryDep = {
+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getOrgPermission">;
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
auditLogDAL: Pick<TAuditLogDALFactory, "countByDateAndActor" | "countByIpAddress" | "countByAuthMethod">;
secretRotationV2DAL: Pick<
@@ -60,10 +73,18 @@ type TInsightsServiceFactoryDep = {
userDAL: Pick<TUserDALFactory, "find">;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
keyStore: Pick<TKeyStoreFactory, "setItemWithExpiry" | "getItem" | "ttl">;
+ orgDAL: Pick<TOrgDALFactory, "countAllOrgMembers">;
+ identityOrgMembershipDAL: Pick<TIdentityOrgDALFactory, "countAllOrgIdentities">;
+ dynamicSecretLeaseDAL: Pick<TDynamicSecretLeaseDALFactory, "countLeasesForOrg">;
+ insightsDAL: Pick<TInsightsDALFactory, "findProjectWarningsForOrg">;
};
export type TInsightsServiceFactory = ReturnType<typeof insightsServiceFactory>;
+// Secrets untouched for longer than this count as stale in the org-wide project warnings.
+// getSummary derives the same 90 days inline, where it doubles as the rotation/reminder lookback window.
+const STALE_SECRET_THRESHOLD_DAYS = 90;
+
const VALUE_EVENT_TYPES = [
EventType.GET_SECRETS,
EventType.GET_SECRET,
@@ -100,6 +121,27 @@ const checkInsightsPermission = async (
return { permission };
};
+// Org-wide insights are gated on a separate org-level subject, so they get their own check rather than
+// reusing the project one above.
+const checkSecretsManagementInsightsPermission = async (
+ permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">,
+ action: OrgPermissionSecretsManagementInsightsActions,
+ { actor, actorId, orgId, actorAuthMethod, actorOrgId }: TOrgInsightsDTO
+) => {
+ const { permission } = await permissionService.getOrgPermission({
+ scope: OrganizationActionScope.Any,
+ actor,
+ actorId,
+ orgId,
+ actorAuthMethod,
+ actorOrgId
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(action, OrgPermissionSubjects.SecretsManagementInsights);
+
+ return { permission };
+};
+
export const insightsServiceFactory = ({
permissionService,
licenseService,
@@ -114,7 +156,11 @@ export const insightsServiceFactory = ({
projectDAL,
userDAL,
kmsService,
- keyStore
+ keyStore,
+ orgDAL,
+ identityOrgMembershipDAL,
+ dynamicSecretLeaseDAL,
+ insightsDAL
}: TInsightsServiceFactoryDep) => {
const fetchReminders = async (projectId: string, startDate: Date, endDate: Date) => {
const rawReminders = await reminderDAL.findByProjectAndDateRange({ projectId, startDate, endDate });
@@ -628,6 +674,67 @@ export const insightsServiceFactory = ({
};
};
+ const getSecretsUsageInsights = async (dto: TGetSecretsUsageInsightsDTO): Promise<TSecretsUsageInsights> => {
+ await checkSecretsManagementInsightsPermission(
+ permissionService,
+ OrgPermissionSecretsManagementInsightsActions.Read,
+ dto
+ );
+
+ const plan = await licenseService.getPlan(dto.orgId);
+ if (!plan.secretAccessInsights) {
+ throw new BadRequestError({
+ message: "Secrets management insights are not available on your plan. Upgrade your plan to access insights."
+ });
+ }
+
+ const [activeLeases, users, identities] = await Promise.all([
+ dynamicSecretLeaseDAL.countLeasesForOrg(dto.orgId),
+ orgDAL.countAllOrgMembers(dto.orgId),
+ identityOrgMembershipDAL.countAllOrgIdentities({
+ [`${TableName.Membership}.scopeOrgId` as "scopeOrgId"]: dto.orgId
+ })
+ ]);
+
+ return { activeLeases, users, identities };
+ };
+
+ const getSecretsProjectWarnings = async (dto: TGetSecretsProjectWarningsDTO): Promise<TSecretsProjectWarnings> => {
+ // Permission and plan checks run before the cache lookup so cached data is
+ // never served to an unauthorized actor.
+ await checkSecretsManagementInsightsPermission(
+ permissionService,
+ OrgPermissionSecretsManagementInsightsActions.Read,
+ dto
+ );
+
+ const plan = await licenseService.getPlan(dto.orgId);
+ if (!plan.secretAccessInsights) {
+ throw new BadRequestError({
+ message: "Secrets management insights are not available on your plan. Upgrade your plan to access insights."
+ });
+ }
+
+ const cacheKey = KeyStorePrefixes.InsightsCache(dto.orgId, `project-warnings:${dto.offset}:${dto.limit}`);
+ return withCache({
+ keyStore,
+ key: cacheKey,
+ ttlSeconds: KeyStoreTtls.InsightsCacheInSeconds,
+ fetcher: async () => {
+ const staleBefore = new Date();
+ staleBefore.setDate(staleBefore.getDate() - STALE_SECRET_THRESHOLD_DAYS);
+
+ const { projects, totalProjects, projectsWithIssues } = await insightsDAL.findProjectWarningsForOrg(dto.orgId, {
+ offset: dto.offset,
+ limit: dto.limit,
+ staleBefore
+ });
+
+ return { projects, totalProjects, projectsWithIssues, offset: dto.offset, limit: dto.limit };
+ }
+ });
+ };
+
return {
getCalendar,
getAccessVolume,
@@ -635,6 +742,8 @@ export const insightsServiceFactory = ({
getAuthMethodDistribution,
getSummary,
getSecretsDuplication,
- getCounts
+ getCounts,
+ getSecretsUsageInsights,
+ getSecretsProjectWarnings
};
};
diff --git a/backend/src/ee/services/insights/insights-types.ts b/backend/src/ee/services/insights/insights-types.ts
index d577952b03..6332807186 100644
--- a/backend/src/ee/services/insights/insights-types.ts
+++ b/backend/src/ee/services/insights/insights-types.ts
@@ -1,3 +1,7 @@
+import { TOrgPermission } from "@app/lib/types";
+
+// Project-scoped insights: the dashboard for a single secret management project.
+
export type TGetInsightsCalendarDTO = {
projectId: string;
month: number;
@@ -31,3 +35,46 @@ export type TGetSecretsDuplicationDTO = {
export type TGetInsightsCountsDTO = {
projectId: string;
};
+
+// Org-scoped insights: aggregates spanning every secret management project in the organization.
+
+export type TOrgInsightsDTO = TOrgPermission;
+
+export type TGetSecretsUsageInsightsDTO = TOrgInsightsDTO;
+
+export type TSecretsUsageInsights = {
+ activeLeases: number;
+ users: number;
+ identities: number;
+};
+
+export type TGetSecretsProjectWarningsDTO = TOrgInsightsDTO & {
+ offset: number;
+ limit: number;
+};
+
+export type TProjectWarningCounts = {
+ // null when the project does not have secret blind indexing enabled (the metric is unknowable, not zero)
+ duplicatedSecrets: number | null;
+ staleSecrets: number;
+ failedRotations: number;
+ failedSyncs: number;
+ orphanedLeases: number;
+};
+
+export type TSecretsProjectWarning = {
+ projectId: string;
+ projectName: string;
+ projectSlug: string;
+ totalSecrets: number;
+ severityScore: number;
+ warnings: TProjectWarningCounts;
+};
+
+export type TSecretsProjectWarnings = {
+ projects: TSecretsProjectWarning[];
+ totalProjects: number;
+ projectsWithIssues: number;
+ offset: number;
+ limit: number;
+};
diff --git a/backend/src/ee/services/product-insights/product-insights-fns.ts b/backend/src/ee/services/product-insights/product-insights-fns.ts
deleted file mode 100644
index 5dcfffa618..0000000000
--- a/backend/src/ee/services/product-insights/product-insights-fns.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import { ForbiddenError } from "@casl/ability";
-
-import { OrganizationActionScope } from "@app/db/schemas";
-import {
- OrgPermissionSecretsManagementInsightsActions,
- OrgPermissionSubjects
-} from "@app/ee/services/permission/org-permission";
-import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
-
-import { TProductInsightsDTO } from "./product-insights-types";
-
-export const checkSecretsManagementInsightsPermission = async (
- permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">,
- action: OrgPermissionSecretsManagementInsightsActions,
- { actor, actorId, orgId, actorAuthMethod, actorOrgId }: TProductInsightsDTO
-) => {
- const { permission } = await permissionService.getOrgPermission({
- scope: OrganizationActionScope.Any,
- actor,
- actorId,
- orgId,
- actorAuthMethod,
- actorOrgId
- });
-
- ForbiddenError.from(permission).throwUnlessCan(action, OrgPermissionSubjects.SecretsManagementInsights);
-
- return { permission };
-};
diff --git a/backend/src/ee/services/product-insights/product-insights-schemas.ts b/backend/src/ee/services/product-insights/product-insights-schemas.ts
deleted file mode 100644
index 7836fcb0e5..0000000000
--- a/backend/src/ee/services/product-insights/product-insights-schemas.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-import { z } from "zod";
-
-import { PRODUCT_INSIGHTS } from "@app/lib/api-docs";
-
-export const SecretsUsageInsightsSchema = z.object({
- activeLeases: z.number().int().describe(PRODUCT_INSIGHTS.GET_SECRETS_USAGE_INSIGHTS.activeLeases),
- users: z.number().int().describe(PRODUCT_INSIGHTS.GET_SECRETS_USAGE_INSIGHTS.users),
- identities: z.number().int().describe(PRODUCT_INSIGHTS.GET_SECRETS_USAGE_INSIGHTS.identities)
-});
-
-export const SecretsProjectWarningSchema = z.object({
- projectId: z.string().uuid().describe(PRODUCT_INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.projectId),
- projectName: z.string().describe(PRODUCT_INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.projectName),
- projectSlug: z.string().describe(PRODUCT_INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.projectSlug),
- totalSecrets: z.number().int().describe(PRODUCT_INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.totalSecrets),
- severityScore: z.number().int().describe(PRODUCT_INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.severityScore),
- warnings: z
- .object({
- duplicatedSecrets: z
- .number()
- .int()
- .nullable()
- .describe(PRODUCT_INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.duplicatedSecrets),
- staleSecrets: z.number().int().describe(PRODUCT_INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.staleSecrets),
- failedRotations: z.number().int().describe(PRODUCT_INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.failedRotations),
- failedSyncs: z.number().int().describe(PRODUCT_INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.failedSyncs),
- orphanedLeases: z.number().int().describe(PRODUCT_INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.orphanedLeases)
- })
- .describe(PRODUCT_INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.warnings)
-});
-
-export const SecretsProjectWarningsSchema = z.object({
- projects: SecretsProjectWarningSchema.array(),
- totalProjects: z.number().int().describe(PRODUCT_INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.totalProjects),
- projectsWithIssues: z.number().int().describe(PRODUCT_INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.projectsWithIssues),
- offset: z.number().int().describe(PRODUCT_INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.offset),
- limit: z.number().int().describe(PRODUCT_INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.limit)
-});
diff --git a/backend/src/ee/services/product-insights/product-insights-service.ts b/backend/src/ee/services/product-insights/product-insights-service.ts
deleted file mode 100644
index ed96fe0728..0000000000
--- a/backend/src/ee/services/product-insights/product-insights-service.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-import { TableName } from "@app/db/schemas";
-import { TDynamicSecretLeaseDALFactory } from "@app/ee/services/dynamic-secret-lease/dynamic-secret-lease-dal";
-import { OrgPermissionSecretsManagementInsightsActions } from "@app/ee/services/permission/org-permission";
-import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
-import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";
-import { withCache } from "@app/lib/cache/with-cache";
-import { BadRequestError } from "@app/lib/errors";
-import { TIdentityOrgDALFactory } from "@app/services/identity/identity-org-dal";
-import { TOrgDALFactory } from "@app/services/org/org-dal";
-
-import { TLicenseServiceFactory } from "../license/license-service";
-import { TProductInsightsDALFactory } from "./product-insights-dal";
-import { checkSecretsManagementInsightsPermission } from "./product-insights-fns";
-import {
- TGetSecretsProjectWarningsDTO,
- TGetSecretsUsageInsightsDTO,
- TSecretsProjectWarnings,
- TSecretsUsageInsights
-} from "./product-insights-types";
-
-type TProductInsightsServiceFactoryDep = {
- permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">;
- licenseService: Pick<TLicenseServiceFactory, "getPlan">;
- orgDAL: Pick<TOrgDALFactory, "countAllOrgMembers">;
- identityOrgMembershipDAL: Pick<TIdentityOrgDALFactory, "countAllOrgIdentities">;
- dynamicSecretLeaseDAL: Pick<TDynamicSecretLeaseDALFactory, "countLeasesForOrg">;
- productInsightsDAL: Pick<TProductInsightsDALFactory, "findProjectWarningsForOrg">;
- keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry">;
-};
-
-// Same threshold the per-project insights summary uses (insights-service.ts)
-const STALE_SECRET_THRESHOLD_DAYS = 90;
-
-export type TProductInsightsServiceFactory = ReturnType<typeof productInsightsServiceFactory>;
-
-export const productInsightsServiceFactory = ({
- permissionService,
- licenseService,
- orgDAL,
- identityOrgMembershipDAL,
- dynamicSecretLeaseDAL,
- productInsightsDAL,
- keyStore
-}: TProductInsightsServiceFactoryDep) => {
- const getSecretsUsageInsights = async (dto: TGetSecretsUsageInsightsDTO): Promise<TSecretsUsageInsights> => {
- await checkSecretsManagementInsightsPermission(
- permissionService,
- OrgPermissionSecretsManagementInsightsActions.Read,
- dto
- );
-
- const plan = await licenseService.getPlan(dto.orgId);
- if (!plan.secretAccessInsights) {
- throw new BadRequestError({
- message: "Secrets management insights are not available on your plan. Upgrade your plan to access insights."
- });
- }
-
- const [activeLeases, users, identities] = await Promise.all([
- dynamicSecretLeaseDAL.countLeasesForOrg(dto.orgId),
- orgDAL.countAllOrgMembers(dto.orgId),
- identityOrgMembershipDAL.countAllOrgIdentities({
- [`${TableName.Membership}.scopeOrgId` as "scopeOrgId"]: dto.orgId
- })
- ]);
-
- return { activeLeases, users, identities };
- };
-
- const getSecretsProjectWarnings = async (dto: TGetSecretsProjectWarningsDTO): Promise<TSecretsProjectWarnings> => {
- // Permission and plan checks run before the cache lookup so cached data is
- // never served to an unauthorized actor.
- await checkSecretsManagementInsightsPermission(
- permissionService,
- OrgPermissionSecretsManagementInsightsActions.Read,
- dto
- );
-
- const plan = await licenseService.getPlan(dto.orgId);
- if (!plan.secretAccessInsights) {
- throw new BadRequestError({
- message: "Secrets management insights are not available on your plan. Upgrade your plan to access insights."
- });
- }
-
- const cacheKey = KeyStorePrefixes.ProductInsightsCache(dto.orgId, `project-warnings:${dto.offset}:${dto.limit}`);
- return withCache({
- keyStore,
- key: cacheKey,
- ttlSeconds: KeyStoreTtls.InsightsCacheInSeconds,
- fetcher: async () => {
- const staleBefore = new Date();
- staleBefore.setDate(staleBefore.getDate() - STALE_SECRET_THRESHOLD_DAYS);
-
- const { projects, totalProjects, projectsWithIssues } = await productInsightsDAL.findProjectWarningsForOrg(
- dto.orgId,
- { offset: dto.offset, limit: dto.limit, staleBefore }
- );
-
- return { projects, totalProjects, projectsWithIssues, offset: dto.offset, limit: dto.limit };
- }
- });
- };
-
- return { getSecretsUsageInsights, getSecretsProjectWarnings };
-};
diff --git a/backend/src/ee/services/product-insights/product-insights-types.ts b/backend/src/ee/services/product-insights/product-insights-types.ts
deleted file mode 100644
index 59043eb148..0000000000
--- a/backend/src/ee/services/product-insights/product-insights-types.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-import { TOrgPermission } from "@app/lib/types";
-
-export type TProductInsightsDTO = TOrgPermission;
-
-export type TGetSecretsUsageInsightsDTO = TProductInsightsDTO;
-
-export type TSecretsUsageInsights = {
- activeLeases: number;
- users: number;
- identities: number;
-};
-
-export type TGetSecretsProjectWarningsDTO = TProductInsightsDTO & {
- offset: number;
- limit: number;
-};
-
-export type TProjectWarningCounts = {
- // null when the project does not have secret blind indexing enabled (the metric is unknowable, not zero)
- duplicatedSecrets: number | null;
- staleSecrets: number;
- failedRotations: number;
- failedSyncs: number;
- orphanedLeases: number;
-};
-
-export type TSecretsProjectWarning = {
- projectId: string;
- projectName: string;
- projectSlug: string;
- totalSecrets: number;
- severityScore: number;
- warnings: TProjectWarningCounts;
-};
-
-export type TSecretsProjectWarnings = {
- projects: TSecretsProjectWarning[];
- totalProjects: number;
- projectsWithIssues: number;
- offset: number;
- limit: number;
-};
diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.ts
index 2c3be5afff..f16b52a78b 100644
--- a/backend/src/keystore/keystore.ts
+++ b/backend/src/keystore/keystore.ts
@@ -142,8 +142,9 @@ export const KeyStorePrefixes = {
EmailSignupOtpHash: (hash: string) => `email-signup-otp:${hash}:hash` as const,
EmailSignupOtpLock: (hash: string) => `email-signup-otp:${hash}:lock` as const,
EmailSignupResendCooldown: (hash: string) => `email-signup-otp:${hash}:cd` as const,
- InsightsCache: (projectId: string, endpoint: string) => `insights-cache:${projectId}:${endpoint}` as const,
- ProductInsightsCache: (orgId: string, endpoint: string) => `product-insights-cache:${orgId}:${endpoint}` as const,
+ // scopeId is a projectId for the per-project dashboard and an orgId for the org-wide aggregates. Both are
+ // UUIDs and the endpoint segments do not overlap, so one prefix serves both without collision.
+ InsightsCache: (scopeId: string, endpoint: string) => `insights-cache:${scopeId}:${endpoint}` as const,
AdminConfig: "infisical-admin-cfg",
UpdateCheckLatestVersion: "update-check-latest-version",
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index 271b839d9c..f0ed300cfc 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -892,7 +892,7 @@ export const ORGANIZATIONS = {
}
} as const;
-export const PRODUCT_INSIGHTS = {
+export const INSIGHTS = {
GET_SECRETS_USAGE_INSIGHTS: {
activeLeases:
"The number of dynamic secret leases currently active across the organization's secret management projects. Revoked and expired leases are not counted.",
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index d3fbcfe0d3..6be97cfb6c 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -74,6 +74,7 @@ import { isHsmActiveAndEnabled } from "@app/ee/services/hsm/hsm-fns";
import { THsmServiceFactory } from "@app/ee/services/hsm/hsm-service";
import { identityAuthTemplateDALFactory } from "@app/ee/services/identity-auth-template/identity-auth-template-dal";
import { identityAuthTemplateServiceFactory } from "@app/ee/services/identity-auth-template/identity-auth-template-service";
+import { insightsDALFactory } from "@app/ee/services/insights/insights-dal";
import { insightsServiceFactory } from "@app/ee/services/insights/insights-service";
import { kmipClientCertificateDALFactory } from "@app/ee/services/kmip/kmip-client-certificate-dal";
import { kmipClientDALFactory } from "@app/ee/services/kmip/kmip-client-dal";
@@ -139,8 +140,6 @@ import { pkiInstallationServiceFactory } from "@app/ee/services/pki-discovery/pk
import { scepDynamicChallengeDALFactory } from "@app/ee/services/pki-scep/pki-scep-dynamic-challenge-dal";
import { pkiScepServiceFactory } from "@app/ee/services/pki-scep/pki-scep-service";
import { scepTransactionDALFactory } from "@app/ee/services/pki-scep/pki-scep-transaction-dal";
-import { productInsightsDALFactory } from "@app/ee/services/product-insights/product-insights-dal";
-import { productInsightsServiceFactory } from "@app/ee/services/product-insights/product-insights-service";
import { projectEventsServiceFactory } from "@app/ee/services/project-events/project-events-service";
import { projectEventsSSEServiceFactory } from "@app/ee/services/project-events/project-events-sse-service";
import { projectTemplateDALFactory } from "@app/ee/services/project-template/project-template-dal";
@@ -619,7 +618,7 @@ export const registerRoutes = async (
const integrationDAL = integrationDALFactory(db);
const offlineUsageReportDAL = offlineUsageReportDALFactory(db);
const orgProductStatsDAL = orgProductStatsDALFactory(db);
- const productInsightsDAL = productInsightsDALFactory(db);
+ const insightsDAL = insightsDALFactory(db);
const integrationAuthDAL = integrationAuthDALFactory(db);
const webhookDAL = webhookDALFactory(db);
const serviceTokenDAL = serviceTokenDALFactory(db);
@@ -2750,16 +2749,6 @@ export const registerRoutes = async (
licenseService
});
- const productInsightsService = productInsightsServiceFactory({
- permissionService,
- licenseService,
- orgDAL,
- identityOrgMembershipDAL,
- dynamicSecretLeaseDAL,
- productInsightsDAL,
- keyStore
- });
-
// DAILY
const dailyResourceCleanUp = dailyResourceCleanUpQueueServiceFactory({
scimService,
@@ -3097,7 +3086,11 @@ export const registerRoutes = async (
projectDAL,
userDAL,
kmsService,
- keyStore
+ keyStore,
+ orgDAL,
+ identityOrgMembershipDAL,
+ dynamicSecretLeaseDAL,
+ insightsDAL
});
const auditReportDAL = auditReportDALFactory(db);
@@ -3913,7 +3906,6 @@ export const registerRoutes = async (
dynamicSecret: dynamicSecretService,
dynamicSecretLease: dynamicSecretLeaseService,
emailDomain: emailDomainService,
- productInsights: productInsightsService,
saml: samlService,
ldap: ldapService,
auditLog: auditLogService,