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
refac: change the endpoint path
adilsona1629b773cf0
diff --git a/backend/e2e-test/insights-project-warnings.spec.ts b/backend/e2e-test/insights-project-warnings.spec.tsindex a1d0bc3978..25a33c1ff3 100644--- a/backend/e2e-test/insights-project-warnings.spec.ts+++ b/backend/e2e-test/insights-project-warnings.spec.ts@@ -1,6 +1,6 @@import { randomUUID } from "node:crypto";-import { createMongoAbility, ForbiddenError, MongoAbility } from "@casl/ability";+import { ForbiddenError } from "@casl/ability";import { Knex } from "knex";import { afterAll, beforeAll, describe, expect, test } from "vitest";@@ -21,13 +21,6 @@ import {TUsersInsert} from "@app/db/schemas";import { DynamicSecretLeaseStatus } from "@app/ee/services/dynamic-secret-lease/dynamic-secret-lease-types";-import { TFeatureSet } from "@app/ee/services/license/license-types";-import {- OrgPermissionSecretsManagementInsightsActions,- OrgPermissionSet,- OrgPermissionSubjects-} from "@app/ee/services/permission/org-permission";-import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-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";@@ -35,11 +28,7 @@ import { SecretRotationStatus } from "@app/ee/services/secret-rotation-v2/secretimport { 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";+import { buildOrgInsightsGateStubs, passThroughKeyStore, projectScopedInsightsDepStubs } from "./testUtils/insights";declare const testDb: Knex;@@ -78,33 +67,7 @@ const projectList = Object.values(projects);const DYNAMIC_SECRET_ID = randomUUID();-const buildPermission = (canRead: boolean): MongoAbility<OrgPermissionSet> =>- createMongoAbility<OrgPermissionSet>(- canRead- ? [- {- action: OrgPermissionSecretsManagementInsightsActions.Read,- subject: OrgPermissionSubjects.SecretsManagementInsights- }- ]- : []- );--let canReadInsights = true;-let planHasInsights = true;--const permissionService: Pick<TPermissionServiceFactory, "getOrgPermission" | "getProjectPermission"> = {- ...unreachableGetProjectPermission,- getOrgPermission: async () => ({- permission: buildPermission(canReadInsights),- memberships: [],- hasRole: () => false- })-};--const licenseService = {- getPlan: async () => ({ secretAccessInsights: planHasInsights }) as unknown as TFeatureSet-};+const { permissionService, licenseService, setCanReadInsights, setPlanHasInsights } = buildOrgInsightsGateStubs();const insightsService = insightsServiceFactory({...projectScopedInsightsDepStubs,@@ -393,24 +356,20 @@ describe("insights secrets project warnings", () => {});test("throws when the actor cannot read secrets management insights", async () => {- canReadInsights = false;+ setCanReadInsights(false);try {- await expect(insightsService.getSecretsProjectWarnings(actor(ORG_ID))).rejects.toBeInstanceOf(- ForbiddenError- );+ await expect(insightsService.getSecretsProjectWarnings(actor(ORG_ID))).rejects.toBeInstanceOf(ForbiddenError);} finally {- canReadInsights = true;+ setCanReadInsights(true);}});test("throws when the plan does not include secret access insights", async () => {- planHasInsights = false;+ setPlanHasInsights(false);try {- await expect(insightsService.getSecretsProjectWarnings(actor(ORG_ID))).rejects.toThrow(- /Upgrade your plan/- );+ await expect(insightsService.getSecretsProjectWarnings(actor(ORG_ID))).rejects.toThrow(/Upgrade your plan/);} finally {- planHasInsights = true;+ setPlanHasInsights(true);}});});diff --git a/backend/e2e-test/insights-usage.spec.ts b/backend/e2e-test/insights-usage.spec.tsindex 23709688b9..4bb449a911 100644--- a/backend/e2e-test/insights-usage.spec.ts+++ b/backend/e2e-test/insights-usage.spec.ts@@ -1,6 +1,6 @@import { randomUUID } from "node:crypto";-import { createMongoAbility, ForbiddenError, MongoAbility } from "@casl/ability";+import { ForbiddenError } from "@casl/ability";import { Knex } from "knex";import { afterAll, beforeAll, describe, expect, test } from "vitest";@@ -20,13 +20,6 @@ import {TUsersInsert} from "@app/db/schemas";import { dynamicSecretLeaseDALFactory } from "@app/ee/services/dynamic-secret-lease/dynamic-secret-lease-dal";-import { TFeatureSet } from "@app/ee/services/license/license-types";-import {- OrgPermissionSecretsManagementInsightsActions,- OrgPermissionSet,- OrgPermissionSubjects-} from "@app/ee/services/permission/org-permission";-import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-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";@@ -34,11 +27,7 @@ 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";+import { buildOrgInsightsGateStubs, passThroughKeyStore, projectScopedInsightsDepStubs } from "./testUtils/insights";declare const testDb: Knex;@@ -85,33 +74,7 @@ const scopes = {const scopeList = Object.values(scopes);-const buildPermission = (canRead: boolean): MongoAbility<OrgPermissionSet> =>- createMongoAbility<OrgPermissionSet>(- canRead- ? [- {- action: OrgPermissionSecretsManagementInsightsActions.Read,- subject: OrgPermissionSubjects.SecretsManagementInsights- }- ]- : []- );--let canReadInsights = true;-let planHasInsights = true;--const permissionService: Pick<TPermissionServiceFactory, "getOrgPermission" | "getProjectPermission"> = {- ...unreachableGetProjectPermission,- getOrgPermission: async () => ({- permission: buildPermission(canReadInsights),- memberships: [],- hasRole: () => false- })-};--const licenseService = {- getPlan: async () => ({ secretAccessInsights: planHasInsights }) as unknown as TFeatureSet-};+const { permissionService, licenseService, setCanReadInsights, setPlanHasInsights } = buildOrgInsightsGateStubs();const insightsService = insightsServiceFactory({...projectScopedInsightsDepStubs,@@ -363,22 +326,20 @@ describe("insights secrets usage insights", () => {});test("throws when the actor cannot read secrets management insights", async () => {- canReadInsights = false;+ setCanReadInsights(false);try {- await expect(insightsService.getSecretsUsageInsights(actor(ORG_ID))).rejects.toBeInstanceOf(- ForbiddenError- );+ await expect(insightsService.getSecretsUsageInsights(actor(ORG_ID))).rejects.toBeInstanceOf(ForbiddenError);} finally {- canReadInsights = true;+ setCanReadInsights(true);}});test("throws when the plan does not include secret access insights", async () => {- planHasInsights = false;+ setPlanHasInsights(false);try {await expect(insightsService.getSecretsUsageInsights(actor(ORG_ID))).rejects.toThrow(/Upgrade your plan/);} finally {- planHasInsights = true;+ setPlanHasInsights(true);}});});diff --git a/backend/e2e-test/routes/v1/insights.spec.ts b/backend/e2e-test/routes/v1/insights.spec.tsindex fd1b8b956e..7fb4d65a6c 100644--- a/backend/e2e-test/routes/v1/insights.spec.ts+++ b/backend/e2e-test/routes/v1/insights.spec.ts@@ -1,12 +1,12 @@import { describe, expect, test } from "vitest";-const URL = "/api/v1/insights/secrets/usage-insights";+const URL = "/api/v1/insights/secrets/summary";// 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("Insights V1 Router (org-scoped)", async () => {- test("GET usage insights is registered and refuses on plan restriction", async () => {+ test("GET secrets summary is registered and refuses on plan restriction", async () => {const res = await testServer.inject({method: "GET",url: URL,@@ -19,12 +19,12 @@ describe("Insights V1 Router (org-scoped)", async () => {expect(res.json().message).toContain("Upgrade your plan");});- const WARNINGS_URL = "/api/v1/insights/secrets/project-warnings";+ const PROJECTS_URL = "/api/v1/insights/secrets/projects";- test("GET project warnings is registered and refuses on plan restriction", async () => {+ test("GET secrets projects is registered and refuses on plan restriction", async () => {const res = await testServer.inject({method: "GET",- url: WARNINGS_URL,+ url: PROJECTS_URL,headers: { authorization: `Bearer ${jwtAuthToken}` }});@@ -32,10 +32,10 @@ describe("Insights V1 Router (org-scoped)", async () => {expect(res.json().message).toContain("Upgrade your plan");});- test("GET project warnings rejects an out-of-bounds limit", async () => {+ test("GET secrets projects rejects an out-of-bounds limit", async () => {const res = await testServer.inject({method: "GET",- url: `${WARNINGS_URL}?limit=500`,+ url: `${PROJECTS_URL}?limit=500`,headers: { authorization: `Bearer ${jwtAuthToken}` }});diff --git a/backend/e2e-test/testUtils/insights.ts b/backend/e2e-test/testUtils/insights.tsindex b3446f56fa..ce62f122ae 100644--- a/backend/e2e-test/testUtils/insights.ts+++ b/backend/e2e-test/testUtils/insights.ts@@ -1,4 +1,12 @@+import { createMongoAbility, MongoAbility } from "@casl/ability";+import { TInsightsServiceFactoryDep } from "@app/ee/services/insights/insights-service";+import { TFeatureSet } from "@app/ee/services/license/license-types";+import {+ OrgPermissionSecretsManagementInsightsActions,+ OrgPermissionSet,+ OrgPermissionSubjects+} from "@app/ee/services/permission/org-permission";// 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@@ -6,14 +14,12 @@ import { TInsightsServiceFactoryDep } from "@app/ee/services/insights/insights-s//// 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.`- );- };+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<@@ -39,7 +45,6 @@ export const projectScopedInsightsDepStubs: Pick<> = {auditLogDAL: {countByDateAndActor: unreachable("auditLogDAL.countByDateAndActor"),- countByIpAddress: unreachable("auditLogDAL.countByIpAddress"),countByAuthMethod: unreachable("auditLogDAL.countByAuthMethod")},secretRotationV2DAL: {@@ -80,6 +85,45 @@ export const projectScopedInsightsDepStubs: Pick<}};+// Every org-wide insight is gated on the same org read permission plus the same plan entitlement, so specs+// share one set of stubs for that gate and flip the two toggles to exercise the two rejection paths.+export const buildOrgInsightsGateStubs = () => {+ let canReadInsights = true;+ let planHasInsights = true;++ const buildPermission = (canRead: boolean): MongoAbility<OrgPermissionSet> =>+ createMongoAbility<OrgPermissionSet>(+ canRead+ ? [+ {+ action: OrgPermissionSecretsManagementInsightsActions.Read,+ subject: OrgPermissionSubjects.SecretsManagementInsights+ }+ ]+ : []+ );++ return {+ permissionService: {+ ...unreachableGetProjectPermission,+ getOrgPermission: async () => ({+ permission: buildPermission(canReadInsights),+ memberships: [],+ hasRole: () => false+ })+ } as TInsightsServiceFactoryDep["permissionService"],+ licenseService: {+ getPlan: async () => ({ secretAccessInsights: planHasInsights }) as unknown as TFeatureSet+ } as TInsightsServiceFactoryDep["licenseService"],+ setCanReadInsights: (canRead: boolean) => {+ canReadInsights = canRead;+ },+ setPlanHasInsights: (hasPlan: boolean) => {+ planHasInsights = hasPlan;+ }+ };+};+// 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"] = {diff --git a/backend/src/ee/routes/v1/insights-router.ts b/backend/src/ee/routes/v1/insights-router.tsindex 65ca5b752a..40016d3db2 100644--- a/backend/src/ee/routes/v1/insights-router.ts+++ b/backend/src/ee/routes/v1/insights-router.ts@@ -15,8 +15,8 @@ import {import {OrgAuthMethodDistributionSchema,OrgSecretsAccessVolumeSchema,- SecretsProjectWarningsSchema,- SecretsUsageInsightsSchema,+ SecretsProjectsSchema,+ SecretsSummarySchema,StaticSecretsUsageSchema} from "@app/ee/services/insights/insights-schemas";import { INSIGHTS } from "@app/lib/api-docs";@@ -57,22 +57,23 @@ 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.+ // Everything below this block is project-scoped, lives under /:projectId, and is gated on the+ // project-level Insights subject instead.server.route({method: "GET",- url: "/secrets/usage-insights",+ url: "/secrets/summary",config: {rateLimit: readLimit},onRequest: verifyAuth([AuthMode.JWT]),schema: {- operationId: "getSecretsUsageInsights",+ operationId: "getSecretsSummary",description: "Get secrets management usage counts for the requesting organization.",security: [{ bearerAuth: [] }],response: {200: z.object({- usageInsights: SecretsUsageInsightsSchema+ usageInsights: SecretsSummarySchema})}},@@ -100,29 +101,22 @@ export const registerInsightsRouter = async (server: FastifyZodProvider) => {server.route({method: "GET",- url: "/secrets/project-warnings",+ url: "/secrets/projects",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.",+ operationId: "getSecretsProjects",+ description: "List the organization's secret management projects, 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)+ offset: z.coerce.number().int().min(0).max(10000).default(0).describe(INSIGHTS.GET_SECRETS_PROJECTS.offset),+ limit: z.coerce.number().int().min(1).max(100).default(20).describe(INSIGHTS.GET_SECRETS_PROJECTS.limit)}),response: {200: z.object({- projectWarnings: SecretsProjectWarningsSchema+ projectWarnings: SecretsProjectsSchema})}},@@ -200,13 +194,13 @@ export const registerInsightsRouter = async (server: FastifyZodProvider) => {server.route({method: "GET",- url: "/secrets/auth-method-distribution",+ url: "/secrets/usage/auth-methods",config: {rateLimit: readLimit},onRequest: verifyAuth([AuthMode.JWT]),schema: {- operationId: "getSecretsAuthMethodDistribution",+ operationId: "getSecretsUsageAuthMethods",description:"Get the number of times each machine identity authentication method was used to access a secret value in the requesting organization over the past week.",security: [{ bearerAuth: [] }],@@ -251,7 +245,7 @@ export const registerInsightsRouter = async (server: FastifyZodProvider) => {schema: {operationId: "getStaticSecretsUsage",description:- "Get how many static secrets the requesting organization stored at the end of each of the last twelve UTC calendar weeks.",+ "Get how many static secrets the requesting organization created in each of the last twelve UTC calendar weeks.",security: [{ bearerAuth: [] }],response: {200: z.object({@@ -274,7 +268,7 @@ export const registerInsightsRouter = async (server: FastifyZodProvider) => {event: {type: EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_STATIC_SECRET_USAGE,metadata: {- totalSecrets: staticSecretUsage.weeks.at(-1)?.totalSecrets ?? 0+ totalSecretsCreated: staticSecretUsage.weeks.reduce((sum, week) => sum + week.totalSecrets, 0)}}});@@ -379,45 +373,9 @@ export const registerInsightsRouter = async (server: FastifyZodProvider) => {}});- // server.route({- // method: "GET",- // url: "/:projectId/secrets/access-locations",- // config: { rateLimit: readLimit },- // schema: {- // operationId: "getInsightsAccessLocations",- // description: "Get geographic locations of secret access based on audit log IP addresses",- // security: [{ bearerAuth: [] }],- // params: z.object({- // projectId: z.string().trim()- // }),- // querystring: z.object({- // days: z.coerce.number().min(1).max(90).default(30)- // }),- // response: {- // 200: z.object({- // locations: z.array(- // z.object({ lat: z.number(), lng: z.number(), city: z.string(), country: z.string(), count: z.number() })- // )- // })- // }- // },- // onRequest: verifyAuth([AuthMode.JWT]),- // handler: async (req) => {- // const { projectId } = req.params;- // const { days } = req.query;- // const result = await server.services.insights.getAccessLocations({ projectId, days }, req.permission);- // await server.services.auditLog.createAuditLog({- // projectId,- // event: { type: EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_ACCESS_LOCATIONS, metadata: { projectId, days } },- // ...req.auditLogInfo- // });- // return result;- // }- // });-server.route({method: "GET",- url: "/:projectId/auth/method-distribution",+ url: "/:projectId/usage/auth-methods",config: { rateLimit: readLimit },schema: {operationId: "getInsightsAuthMethodDistribution",diff --git a/backend/src/ee/services/insights/insights-fns.ts b/backend/src/ee/services/insights/insights-fns.tsindex 9afd11e7ec..b2b3222346 100644--- a/backend/src/ee/services/insights/insights-fns.ts+++ b/backend/src/ee/services/insights/insights-fns.ts@@ -5,33 +5,38 @@ import { TAccessVolumeActor, TAccessVolumeDay } from "./insights-types";const ACCESS_VOLUME_DAYS = 7;const STATIC_SECRET_USAGE_WEEKS = 12;-export const buildAccessVolumeWindow = () => {- const todayStr = new Date().toISOString().slice(0, 10);- const endDate = new Date(`${todayStr}T23:59:59.999Z`);- const startDate = new Date(`${todayStr}T00:00:00.000Z`);- startDate.setUTCDate(startDate.getUTCDate() - (ACCESS_VOLUME_DAYS - 1));+export const toUtcDateString = (date: Date) => date.toISOString().slice(0, 10);++const startOfUtcDay = (date: Date) => new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()));- return { todayStr, startDate, endDate };+const startOfUtcWeek = (date: Date) => {+ const monday = startOfUtcDay(date);+ monday.setUTCDate(monday.getUTCDate() - ((monday.getUTCDay() + 6) % 7));++ return monday;};-// Every date in the window, oldest first, so days with no access still appear in the response-// rather than being skipped.-export const listAccessVolumeDates = (todayStr: string) => {- const dates: string[] = [];- for (let i = ACCESS_VOLUME_DAYS - 1; i >= 0; i -= 1) {- const d = new Date(`${todayStr}T00:00:00.000Z`);- d.setUTCDate(d.getUTCDate() - i);- dates.push(d.toISOString().slice(0, 10));+const listBucketStarts = (lastBucketStart: Date, count: number, stepDays: number) => {+ const bucketStarts: string[] = [];+ for (let i = count - 1; i >= 0; i -= 1) {+ const bucketStart = new Date(lastBucketStart);+ bucketStart.setUTCDate(bucketStart.getUTCDate() - i * stepDays);+ bucketStarts.push(toUtcDateString(bucketStart));}- return dates;+ return bucketStarts;};-const startOfUtcWeek = (date: Date) => {- const monday = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()));- monday.setUTCDate(monday.getUTCDate() - ((monday.getUTCDay() + 6) % 7));+export const buildAccessVolumeWindow = () => {+ const startOfToday = startOfUtcDay(new Date());- return monday;+ const startDate = new Date(startOfToday);+ startDate.setUTCDate(startDate.getUTCDate() - (ACCESS_VOLUME_DAYS - 1));++ const endDate = new Date(startOfToday);+ endDate.setUTCHours(23, 59, 59, 999);++ return { dates: listBucketStarts(startOfToday, ACCESS_VOLUME_DAYS, 1), startDate, endDate };};export const buildStaticSecretUsageWindow = () => {@@ -40,22 +45,15 @@ export const buildStaticSecretUsageWindow = () => {const windowStart = new Date(currentWeekStart);windowStart.setUTCDate(windowStart.getUTCDate() - (STATIC_SECRET_USAGE_WEEKS - 1) * 7);- return { windowStart, currentWeekStart };-};--export const listStaticSecretUsageWeekStarts = (currentWeekStart: Date) => {- const weekStarts: string[] = [];- for (let i = STATIC_SECRET_USAGE_WEEKS - 1; i >= 0; i -= 1) {- const weekStart = new Date(currentWeekStart);- weekStart.setUTCDate(weekStart.getUTCDate() - i * 7);- weekStarts.push(weekStart.toISOString().slice(0, 10));- }-- return weekStarts;+ return {+ windowStart,+ currentWeekStart,+ weekStarts: listBucketStarts(currentWeekStart, STATIC_SECRET_USAGE_WEEKS, 7)+ };};-export const buildAccessVolumeDayBuckets = (todayStr: string) =>- new Map(listAccessVolumeDates(todayStr).map((date) => [date, new Map<string, TAccessVolumeActor>()]));+export const buildAccessVolumeDayBuckets = (dates: string[]) =>+ new Map(dates.map((date) => [date, new Map<string, TAccessVolumeActor>()]));// Rows outside the window are dropped. The same actor can arrive as several rows when the// underlying aggregate groups on fields we do not surface, so counts are summed per actor.diff --git a/backend/src/ee/services/insights/insights-schemas.ts b/backend/src/ee/services/insights/insights-schemas.tsindex 8d86036fa6..b3b7f981c1 100644--- a/backend/src/ee/services/insights/insights-schemas.ts+++ b/backend/src/ee/services/insights/insights-schemas.ts@@ -10,20 +10,20 @@ export const SecretsSummarySchema = z.object({});export const SecretsProjectWarningSchema = z.object({- projectId: z.string().uuid().describe(INSIGHTS.GET_SECRETS_PROJECT.projectId),- projectName: z.string().describe(INSIGHTS.GET_SECRETS_PROJECT.projectName),- projectSlug: z.string().describe(INSIGHTS.GET_SECRETS_PROJECT.projectSlug),- totalSecrets: z.number().int().describe(INSIGHTS.GET_SECRETS_PROJECT.totalSecrets),- severityScore: z.number().int().describe(INSIGHTS.GET_SECRETS_PROJECT.severityScore),+ projectId: z.string().uuid().describe(INSIGHTS.GET_SECRETS_PROJECTS.projectId),+ projectName: z.string().describe(INSIGHTS.GET_SECRETS_PROJECTS.projectName),+ projectSlug: z.string().describe(INSIGHTS.GET_SECRETS_PROJECTS.projectSlug),+ totalSecrets: z.number().int().describe(INSIGHTS.GET_SECRETS_PROJECTS.totalSecrets),+ severityScore: z.number().int().describe(INSIGHTS.GET_SECRETS_PROJECTS.severityScore),warnings: z.object({- duplicatedSecrets: z.number().int().nullable().describe(INSIGHTS.GET_SECRETS_PROJECT.duplicatedSecrets),- staleSecrets: z.number().int().describe(INSIGHTS.GET_SECRETS_PROJECT.staleSecrets),- failedRotations: z.number().int().describe(INSIGHTS.GET_SECRETS_PROJECT.failedRotations),- failedSyncs: z.number().int().describe(INSIGHTS.GET_SECRETS_PROJECT.failedSyncs),- orphanedLeases: z.number().int().describe(INSIGHTS.GET_SECRETS_PROJECT.orphanedLeases)+ duplicatedSecrets: z.number().int().nullable().describe(INSIGHTS.GET_SECRETS_PROJECTS.duplicatedSecrets),+ staleSecrets: z.number().int().describe(INSIGHTS.GET_SECRETS_PROJECTS.staleSecrets),+ failedRotations: z.number().int().describe(INSIGHTS.GET_SECRETS_PROJECTS.failedRotations),+ failedSyncs: z.number().int().describe(INSIGHTS.GET_SECRETS_PROJECTS.failedSyncs),+ orphanedLeases: z.number().int().describe(INSIGHTS.GET_SECRETS_PROJECTS.orphanedLeases)})- .describe(INSIGHTS.GET_SECRETS_PROJECT.warnings)+ .describe(INSIGHTS.GET_SECRETS_PROJECTS.warnings)});export const OrgSecretsAccessVolumeSchema = z.object({diff --git a/backend/src/ee/services/insights/insights-service.ts b/backend/src/ee/services/insights/insights-service.tsindex 88453c575a..e96104e962 100644--- a/backend/src/ee/services/insights/insights-service.ts+++ b/backend/src/ee/services/insights/insights-service.ts@@ -45,9 +45,8 @@ import {buildAccessVolumeWindow,buildStaticSecretUsageWindow,collapseAccessVolumeDays,- listAccessVolumeDates,- listStaticSecretUsageWeekStarts,- resolveUserDisplayNames+ resolveUserDisplayNames,+ toUtcDateString} from "./insights-fns";import {TGetAccessVolumeDTO,@@ -55,12 +54,8 @@ import {TGetInsightsCalendarDTO,TGetInsightsCountsDTO,TGetInsightsSummaryDTO,- TGetOrgAccessVolumeDTO,- TGetOrgAuthMethodDistributionDTO,TGetSecretsDuplicationDTO,TGetSecretsProjectWarningsDTO,- TGetSecretsUsageInsightsDTO,- TGetStaticSecretsUsageDTO,TOrgAccessVolume,TOrgAuthMethodDistribution,TOrgInsightsDTO,@@ -72,7 +67,7 @@ import {export type TInsightsServiceFactoryDep = {permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getOrgPermission">;licenseService: Pick<TLicenseServiceFactory, "getPlan">;- auditLogDAL: Pick<TAuditLogDALFactory, "countByDateAndActor" | "countByIpAddress" | "countByAuthMethod">;+ auditLogDAL: Pick<TAuditLogDALFactory, "countByDateAndActor" | "countByAuthMethod">;// Undefined when the instance has no ClickHouse configured. Only the org-wide aggregates use it,// and each degrades to an unsupported no-op response in that case.clickhouseAuditLogDAL?: Pick<TClickHouseAuditLogDALFactory, "countByDateForOrg" | "countByIdentityAuthMethodForOrg">;@@ -104,8 +99,6 @@ export type TInsightsServiceFactoryDep = {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 = [@@ -117,18 +110,27 @@ const VALUE_EVENT_TYPES = [EventType.CREATE_DYNAMIC_SECRET_LEASE];-const checkInsightsPermission = async (- permissionService: TInsightsServiceFactoryDep["permissionService"],+// Both halves of the product (the per-project dashboard and the org-wide aggregates) are gated on the+// same entitlement, so the check and its message live in one place.+const assertInsightsPlanEnabled = async (licenseService: TInsightsServiceFactoryDep["licenseService"],- projectId: string,- actor: OrgServiceActor+ orgId: string) => {- const plan = await licenseService.getPlan(actor.orgId);+ const plan = await licenseService.getPlan(orgId);if (!plan.secretAccessInsights) {throw new BadRequestError({message: "Failed to access insights due to plan restriction. Upgrade your plan to access insights."});}+};++const checkInsightsPermission = async (+ permissionService: TInsightsServiceFactoryDep["permissionService"],+ licenseService: TInsightsServiceFactoryDep["licenseService"],+ projectId: string,+ actor: OrgServiceActor+) => {+ await assertInsightsPlanEnabled(licenseService, actor.orgId);const { permission } = await permissionService.getProjectPermission({actor: actor.type,@@ -144,34 +146,6 @@ const checkInsightsPermission = async (return { permission };};-// used for the secret product insights-const checkSecretsProductInsightsPermission = async (- permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">,- licenseService: Pick<TLicenseServiceFactory, "getPlan">,- 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);-- const plan = await licenseService.getPlan(orgId);- if (!plan.secretAccessInsights) {- throw new BadRequestError({- message: "Secrets management insights are not available on your plan. Upgrade your plan to access insights."- });- }-- return { permission };-};-export const insightsServiceFactory = ({permissionService,licenseService,@@ -193,6 +167,25 @@ export const insightsServiceFactory = ({dynamicSecretLeaseDAL,insightsDAL}: TInsightsServiceFactoryDep) => {+ // Gate for every org-wide aggregate: the org-level read permission plus the insights entitlement.+ const assertOrgInsightsRead = async ({ actor, actorId, orgId, actorAuthMethod, actorOrgId }: TOrgInsightsDTO) => {+ const { permission } = await permissionService.getOrgPermission({+ scope: OrganizationActionScope.Any,+ actor,+ actorId,+ orgId,+ actorAuthMethod,+ actorOrgId+ });++ ForbiddenError.from(permission).throwUnlessCan(+ OrgPermissionSecretsManagementInsightsActions.Read,+ OrgPermissionSubjects.SecretsManagementInsights+ );++ await assertInsightsPlanEnabled(licenseService, orgId);+ };+const fetchReminders = async (projectId: string, startDate: Date, endDate: Date) => {const rawReminders = await reminderDAL.findByProjectAndDateRange({ projectId, startDate, endDate });if (!rawReminders.length) return [];@@ -266,7 +259,7 @@ export const insightsServiceFactory = ({key: cacheKey,ttlSeconds: KeyStoreTtls.InsightsCacheInSeconds,fetcher: async () => {- const { todayStr, startDate, endDate } = buildAccessVolumeWindow();+ const { dates, startDate, endDate } = buildAccessVolumeWindow();const rows = await auditLogDAL.countByDateAndActor({orgId: actorDto.orgId,@@ -285,7 +278,7 @@ export const insightsServiceFactory = ({)]);- const dayMap = buildAccessVolumeDayBuckets(todayStr);+ const dayMap = buildAccessVolumeDayBuckets(dates);rows.forEach((row) => {const actorMeta = row.actorMetadata as Record<string, string> | null;@@ -411,7 +404,7 @@ export const insightsServiceFactory = ({const in7Days = new Date(now);in7Days.setDate(now.getDate() + 7);const lookback90Days = new Date(now);- lookback90Days.setDate(now.getDate() - 90);+ lookback90Days.setDate(now.getDate() - STALE_SECRET_THRESHOLD_DAYS);const staleThreshold = lookback90Days;// Fetch upcoming rotations (by date range) and all failed rotations (no date filter) in parallel@@ -596,13 +589,8 @@ export const insightsServiceFactory = ({};};- const getSecretsUsageInsights = async (dto: TGetSecretsUsageInsightsDTO): Promise<TSecretsUsageInsights> => {- await checkSecretsProductInsightsPermission(- permissionService,- licenseService,- OrgPermissionSecretsManagementInsightsActions.Read,- dto- );+ const getSecretsUsageInsights = async (dto: TOrgInsightsDTO): Promise<TSecretsUsageInsights> => {+ await assertOrgInsightsRead(dto);const [activeLeases, users, identities] = await Promise.all([dynamicSecretLeaseDAL.countLeasesForOrg(dto.orgId),@@ -616,12 +604,8 @@ export const insightsServiceFactory = ({};const getSecretsProjectWarnings = async (dto: TGetSecretsProjectWarningsDTO): Promise<TSecretsProjectWarnings> => {- await checkSecretsProductInsightsPermission(- permissionService,- licenseService,- OrgPermissionSecretsManagementInsightsActions.Read,- dto- );+ await assertOrgInsightsRead(dto);+const cacheKey = KeyStorePrefixes.InsightsCache(dto.orgId, `project-warnings:${dto.offset}:${dto.limit}`);return withCache({keyStore,@@ -642,13 +626,8 @@ export const insightsServiceFactory = ({});};- const getOrgAccessVolume = async (dto: TGetOrgAccessVolumeDTO): Promise<TOrgAccessVolume> => {- await checkSecretsProductInsightsPermission(- permissionService,- licenseService,- OrgPermissionSecretsManagementInsightsActions.Read,- dto- );+ const getOrgAccessVolume = async (dto: TOrgInsightsDTO): Promise<TOrgAccessVolume> => {+ await assertOrgInsightsRead(dto);const appCfg = getConfig();if (!appCfg.CLICKHOUSE_AUDIT_LOG_ENABLED || !clickhouseAuditLogDAL) {@@ -661,7 +640,7 @@ export const insightsServiceFactory = ({key: cacheKey,ttlSeconds: KeyStoreTtls.InsightsCacheInSeconds,fetcher: async () => {- const { todayStr, startDate, endDate } = buildAccessVolumeWindow();+ const { dates, startDate, endDate } = buildAccessVolumeWindow();const rows = await clickhouseAuditLogDAL.countByDateForOrg({orgId: dto.orgId,@@ -673,22 +652,15 @@ export const insightsServiceFactory = ({const countsByDate = new Map(rows.map((row) => [row.date, row.count]));return {- days: listAccessVolumeDates(todayStr).map((date) => ({ date, total: countsByDate.get(date) ?? 0 })),+ days: dates.map((date) => ({ date, total: countsByDate.get(date) ?? 0 })),isSupported: true};}});};- const getOrgAuthMethodDistribution = async (- dto: TGetOrgAuthMethodDistributionDTO- ): Promise<TOrgAuthMethodDistribution> => {- await checkSecretsProductInsightsPermission(- permissionService,- licenseService,- OrgPermissionSecretsManagementInsightsActions.Read,- dto- );+ const getOrgAuthMethodDistribution = async (dto: TOrgInsightsDTO): Promise<TOrgAuthMethodDistribution> => {+ await assertOrgInsightsRead(dto);const appCfg = getConfig();if (!appCfg.CLICKHOUSE_AUDIT_LOG_ENABLED || !clickhouseAuditLogDAL) {@@ -743,17 +715,11 @@ export const insightsServiceFactory = ({// Deleting a secret is a hard delete with no tombstone, so a week can only be counted from the// createdAt of secrets that still exist. Past weeks therefore understate what was created then// and drift lower as those secrets are deleted.- const getStaticSecretsUsage = async (dto: TGetStaticSecretsUsageDTO): Promise<TStaticSecretsUsage> => {- await checkSecretsProductInsightsPermission(- permissionService,- licenseService,- OrgPermissionSecretsManagementInsightsActions.Read,- dto- );+ const getStaticSecretsUsage = async (dto: TOrgInsightsDTO): Promise<TStaticSecretsUsage> => {+ await assertOrgInsightsRead(dto);- const { windowStart, currentWeekStart } = buildStaticSecretUsageWindow();- const currentWeekStartStr = currentWeekStart.toISOString().slice(0, 10);- const weekStarts = listStaticSecretUsageWeekStarts(currentWeekStart);+ const { windowStart, currentWeekStart, weekStarts } = buildStaticSecretUsageWindow();+ const currentWeekStartStr = toUtcDateString(currentWeekStart);// using two different cache keys because the current week is still in progress, so the count is not yet complete.// The prior weeks can have a longer TTLdiff --git a/backend/src/ee/services/insights/insights-types.ts b/backend/src/ee/services/insights/insights-types.tsindex 8f06be3539..7af2b9d9a1 100644--- a/backend/src/ee/services/insights/insights-types.ts+++ b/backend/src/ee/services/insights/insights-types.ts@@ -1,6 +1,16 @@-import { IdentityAuthMethod } from "@app/db/schemas";+import { z } from "zod";+import { TOrgPermission } from "@app/lib/types";+import {+ OrgAuthMethodDistributionSchema,+ OrgSecretsAccessVolumeSchema,+ SecretsProjectsSchema,+ SecretsProjectWarningSchema,+ SecretsSummarySchema,+ StaticSecretsUsageSchema+} from "./insights-schemas";+// Project-scoped insights: the dashboard for a single secret management project.export type TGetInsightsCalendarDTO = {@@ -13,11 +23,6 @@ export type TGetAccessVolumeDTO = {projectId: string;};-export type TGetAccessLocationsDTO = {- projectId: string;- days: number;-};-export type TGetAuthMethodDistributionDTO = {projectId: string;days: number;@@ -41,46 +46,19 @@ export type TGetInsightsCountsDTO = {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;-};--export type TGetOrgAccessVolumeDTO = TOrgInsightsDTO;+// The org-wide responses are derived from the route schemas rather than restated, so the shape and its+// field documentation live in one place. Every field is documented there via .describe().+export type TSecretsUsageInsights = z.infer<typeof SecretsSummarySchema>;+export type TSecretsProjectWarning = z.infer<typeof SecretsProjectWarningSchema>;+export type TSecretsProjectWarnings = z.infer<typeof SecretsProjectsSchema>;+export type TOrgAccessVolume = z.infer<typeof OrgSecretsAccessVolumeSchema>;+export type TOrgAuthMethodDistribution = z.infer<typeof OrgAuthMethodDistributionSchema>;+export type TStaticSecretsUsage = z.infer<typeof StaticSecretsUsageSchema>;export type TAccessVolumeActor = {name: string;@@ -93,48 +71,3 @@ export type TAccessVolumeDay = {total: number;actors: TAccessVolumeActor[];};--export type TOrgAccessVolumeDay = {- date: string;- total: number;-};--export type TOrgAccessVolume = {- days: TOrgAccessVolumeDay[];- // false when audit logs are served from Postgres rather than ClickHouse, in which case- // the aggregate is not computed and `days` is empty.- isSupported: boolean;-};--export type TGetOrgAuthMethodDistributionDTO = TOrgInsightsDTO;--export type TOrgAuthMethodCount = {- authMethod: IdentityAuthMethod;- count: number;-};--export type TOrgAuthMethodDistribution = {- methods: TOrgAuthMethodCount[];- totalFetches: number;- // Fetches by a machine identity whose auth method the audit log did not record, or that this- // version does not recognise.- unknownCount: number;- // false when audit logs are served from Postgres rather than ClickHouse, in which case- // the aggregate is not computed and `methods` is empty.- isSupported: boolean;-};--export type TGetStaticSecretsUsageDTO = TOrgInsightsDTO;--export type TStaticSecretsUsageWeek = {- // The Monday the week starts on, in UTC, as YYYY-MM-DD- weekStart: string;- // the total amount of static secrets created in the week- totalSecrets: number;- // true for the trailing bucket only, which is measured as of now rather than at a week's end.- isPartial: boolean;-};--export type TStaticSecretsUsage = {- weeks: TStaticSecretsUsageWeek[];-};diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex 63d7f41fc0..de9e80cab2 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -893,13 +893,13 @@ export const ORGANIZATIONS = {} as const;export const INSIGHTS = {- GET_SECRETS_USAGE_INSIGHTS: {+ GET_SECRETS_SUMMARY: {activeLeases:"The number of dynamic secret leases currently active across the organization's secret management projects. Revoked and expired leases are not counted.",users: "The number of users who have accepted an active membership in the organization.",identities: "The number of machine identities that belong to the organization."},- GET_SECRETS_PROJECT_WARNINGS: {+ GET_SECRETS_PROJECTS: {offset: "The number of projects to skip before returning results.",limit: "The maximum number of projects to return per page.",projectId: "The ID of the project.",@@ -942,13 +942,13 @@ export const INSIGHTS = {},GET_STATIC_SECRETS_USAGE: {weeks:- "One entry for each of the last twelve weeks, oldest first. Weeks in which no secret was created are included, repeating the previous week's total.",+ "One entry for each of the last twelve weeks, oldest first. Weeks in which no secret was created are included with a count of zero.",weekStart:"The Monday the week starts on, in UTC, as YYYY-MM-DD. Weeks are UTC calendar weeks, not a rolling window anchored on today.",totalSecrets:- "The total number of static secrets stored across every secret management project in the organization at the end of this week. This is a cumulative total, not the number of secrets added during the week. Personal secret overrides are not counted, and neither are secrets in projects or environments that have been deleted. Because deleted secrets leave no record, past weeks count only the secrets that still exist today: totals for earlier weeks understate what was stored at the time, and the series never decreases even across a week in which more secrets were deleted than created. The last entry is exact.",+ "The number of static secrets created across every secret management project in the organization during this week. Each week is counted on its own, so this is not a running total. Personal secret overrides are not counted, and neither are secrets in projects or environments that have been deleted. Because deleted secrets leave no record, a week counts only the secrets created then that still exist today, so earlier weeks understate what was created at the time and drift lower as those secrets are deleted.",isPartial:- "Whether the week is still in progress. True for the last entry only, which is the total as of now rather than at the end of a completed week."+ "Whether the week is still in progress. True for the last entry only, which covers Monday through now rather than a full week, so its count is not comparable to the weeks before it."}} as const;diff --git a/backend/src/services/secret-folder/secret-folder-service.ts b/backend/src/services/secret-folder/secret-folder-service.tsindex 4117f56502..f5582320c7 100644--- a/backend/src/services/secret-folder/secret-folder-service.ts+++ b/backend/src/services/secret-folder/secret-folder-service.ts@@ -16,7 +16,6 @@ import { TSecretApprovalRequestSecretDALFactory } from "@app/ee/services/secret-import { TSecretRotationV2DALFactory } from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-dal";import { PgSqlLock } from "@app/keystore/keystore";import { BadRequestError, NotFoundError } from "@app/lib/errors";-import { logger } from "@app/lib/logger";import { OrderByDirection, OrgServiceActor } from "@app/lib/types";import { ActorType } from "@app/services/auth/auth-type";import { TKmsServiceFactory } from "@app/services/kms/kms-service";@@ -1640,7 +1639,6 @@ export const secretFolderServiceFactory = ({canActorReadBlock(permission, destinationEnvironment, "secret_approval_policy", destinationBlock.blockingAbsPath)? destinationBlock: undefined;- logger.info({ readableDestinationBlock }, "readableDestinationBlock");return {canMove: !sourceBlock,diff --git a/frontend/src/hooks/api/auditReports/mutations.tsx b/frontend/src/hooks/api/auditReports/mutations.tsxindex 4e0d1d0088..c54fd3fa5e 100644--- a/frontend/src/hooks/api/auditReports/mutations.tsx+++ b/frontend/src/hooks/api/auditReports/mutations.tsx@@ -22,7 +22,7 @@ export const useRequestAuditReport = () => {export const useDeleteAuditReport = () => {const queryClient = useQueryClient();return useMutation({- mutationFn: async (auditReportId: string) => {+ mutationFn: async ({ projectId, auditReportId }: TDeleteAuditReportDTO) => {const { data } = await apiRequest.delete<TAuditReport>(`/api/v1/insights/${projectId}/secrets/reports/${auditReportId}`);diff --git a/frontend/src/hooks/api/secretInsights/queries.tsx b/frontend/src/hooks/api/secretInsights/queries.tsxindex 37aafa9457..5eeaec33c2 100644--- a/frontend/src/hooks/api/secretInsights/queries.tsx+++ b/frontend/src/hooks/api/secretInsights/queries.tsx@@ -139,7 +139,7 @@ export const useGetAuthMethodDistribution = (queryFn: async () => {const { projectId, ...query } = params;const { data } = await apiRequest.get<TGetAuthMethodDistributionResponse>(- `/api/v1/insights/${projectId}/auth/method-distribution`,+ `/api/v1/insights/${projectId}/usage/auth-methods`,{ params: query });return data;