Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat(insights): score secret exposure and list ghost readers per secret
Dimitris Staratzise83317c629bc
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex 86e073f650..1318b9823e 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -1151,6 +1151,16 @@ owns the two read endpoints and hands `recordRead` / `recordBulkRead` through toderived from sets the computation already holds: `entitledCount` (everyone who can read the value today,admins included), `unreadCount` (the non-admins among them with no read in the window) and`ghostReaderCount` (readers in the window who can no longer read it, so they still know the value).+- **Exposure score.** `calculateExposureScore` (`secret-read-activity-fns.ts`) turns those three counts into a 0+ to 100 score with Low, Elevated, High and Critical bands and whole-point drivers that add up to it (readers up+ to 45 on a log scale saturating at 40, ghost readers up to 30 saturating at 4, unused access up to 25 by+ share). It is the blast radius prototype's three read-activity terms rescaled; the terms that would need new+ queries (syncs, rotation age, cross-project destinations) are deliberately left out. `$loadSecretSummarizer`+ is the one place the counts and the score are derived, used by the card computation and the per-secret+ endpoint, so the sheet and the cards agree. The cached project computation also keeps the 100 highest-scoring+ secrets and a per-band tally, served by `GET /insights/:projectId/secrets/exposure` through the same cache+ and the same per-caller DescribeSecret recheck as the unused access card. The per-secret endpoint names each+ ghost reader from the project's members, else from the user or identity row, else null for a deleted reader.### Audit Log Event Classes and Settingsdiff --git a/backend/src/ee/routes/v1/insights-router.ts b/backend/src/ee/routes/v1/insights-router.tsindex 0badbf7f92..62f6436d44 100644--- a/backend/src/ee/routes/v1/insights-router.ts+++ b/backend/src/ee/routes/v1/insights-router.ts@@ -17,6 +17,7 @@ import {import {OrgAuthMethodDistributionSchema,OrgSecretsAccessVolumeSchema,+ SecretExposureListSchema,SecretsProjectsSchema,SecretsSummarySchema,StaticSecretsUsageSchema,@@ -469,6 +470,47 @@ export const registerInsightsRouter = async (server: FastifyZodProvider) => {}});+ server.route({+ method: "GET",+ url: "/:projectId/secrets/exposure",+ config: { rateLimit: readLimit },+ schema: {+ operationId: "getInsightsSecretExposure",+ description:+ "List the secrets with the highest exposure score in a project, with how many of the project's secrets fall in each band",+ security: [{ bearerAuth: [] }],+ params: z.object({+ projectId: z.string().trim().max(36).describe(INSIGHTS.GET_SECRET_EXPOSURE.projectId)+ }),+ querystring: z.object({+ offset: z.coerce.number().int().min(0).max(100).default(0).describe(INSIGHTS.GET_SECRET_EXPOSURE.offset),+ limit: z.coerce.number().int().min(1).max(100).default(10).describe(INSIGHTS.GET_SECRET_EXPOSURE.limit)+ }),+ response: {+ 200: SecretExposureListSchema+ }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),+ handler: async (req, reply) => {+ const { projectId } = req.params;+ const { secrets, totalCount, bands, trackingStartedAt, preliminaryUntil, remainingTTL, projectName } =+ await server.services.secretReadActivity.listSecretExposure({ projectId, ...req.query }, req.permission);+ await server.services.auditLog.createAuditLog({+ projectId,+ event: {+ type: EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_SECRET_EXPOSURE,+ metadata: { projectId, projectName }+ },+ ...req.auditLogInfo+ });++ if (remainingTTL && remainingTTL >= 0) {+ void reply.header("X-Cache-TTL", remainingTTL);+ }+ return { secrets, totalCount, bands, trackingStartedAt, preliminaryUntil };+ }+ });+server.route({method: "GET",url: "/:projectId/secrets/unused-access",diff --git a/backend/src/ee/routes/v1/secret-router.ts b/backend/src/ee/routes/v1/secret-router.tsindex a18b5ba6eb..b3445b54f0 100644--- a/backend/src/ee/routes/v1/secret-router.ts+++ b/backend/src/ee/routes/v1/secret-router.ts@@ -1,6 +1,10 @@import z from "zod";import { ProjectPermissionSecretActions } from "@app/ee/services/permission/project-permission";+import {+ SecretExposureCountsSchema,+ SecretExposureSchema+} from "@app/ee/services/secret-read-activity/secret-read-activity-schemas";import { RAW_SECRETS } from "@app/lib/api-docs";import { prefixWithSlash, removeTrailingSlash } from "@app/lib/fn";import { readLimit } from "@app/server/config/rateLimiter";@@ -108,19 +112,33 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {}),response: {200: z.object({- readActivity: z.object({- trackedSince: z.date().describe(RAW_SECRETS.GET_READ_ACTIVITY.trackedSince),- reads: z- .object({- actorType: z- .enum([ActorType.USER, ActorType.IDENTITY])- .describe(RAW_SECRETS.GET_READ_ACTIVITY.actorType),- actorId: z.string().describe(RAW_SECRETS.GET_READ_ACTIVITY.actorId),- lastReadAt: z.date().describe(RAW_SECRETS.GET_READ_ACTIVITY.lastReadAt)- })- .array()- .describe(RAW_SECRETS.GET_READ_ACTIVITY.reads)- })+ readActivity: z+ .object({+ trackedSince: z.date().describe(RAW_SECRETS.GET_READ_ACTIVITY.trackedSince),+ reads: z+ .object({+ actorType: z+ .enum([ActorType.USER, ActorType.IDENTITY])+ .describe(RAW_SECRETS.GET_READ_ACTIVITY.actorType),+ actorId: z.string().describe(RAW_SECRETS.GET_READ_ACTIVITY.actorId),+ lastReadAt: z.date().describe(RAW_SECRETS.GET_READ_ACTIVITY.lastReadAt)+ })+ .array()+ .describe(RAW_SECRETS.GET_READ_ACTIVITY.reads),+ exposure: SecretExposureSchema.describe(RAW_SECRETS.GET_READ_ACTIVITY.exposure),+ ghostReaders: z+ .object({+ actorType: z+ .enum([ActorType.USER, ActorType.IDENTITY])+ .describe(RAW_SECRETS.GET_READ_ACTIVITY.actorType),+ actorId: z.string().describe(RAW_SECRETS.GET_READ_ACTIVITY.actorId),+ actorName: z.string().nullable().describe(RAW_SECRETS.GET_READ_ACTIVITY.ghostReaderName),+ lastReadAt: z.date().describe(RAW_SECRETS.GET_READ_ACTIVITY.lastReadAt)+ })+ .array()+ .describe(RAW_SECRETS.GET_READ_ACTIVITY.ghostReaders)+ })+ .merge(SecretExposureCountsSchema)})}},diff --git a/backend/src/ee/services/audit-log/audit-log-event-classes.ts b/backend/src/ee/services/audit-log/audit-log-event-classes.tsindex 0df31a673d..7ee4e87b0c 100644--- a/backend/src/ee/services/audit-log/audit-log-event-classes.ts+++ b/backend/src/ee/services/audit-log/audit-log-event-classes.ts@@ -219,6 +219,7 @@ const DATA_ACCESS_EVENT_TYPES: readonly EventType[] = [EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_CALENDAR,EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_ACCESS_VOLUME,EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_UNUSED_ACCESS,+ EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_SECRET_EXPOSURE,EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_ORG_AUTH_METHOD_DISTRIBUTION,EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_ACCESS_LOCATIONS,EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_SUMMARY,diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 5dacf934bc..a708453d41 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -745,6 +745,7 @@ export enum EventType {VIEW_INSIGHTS_SECRETS_MANAGEMENT_CALENDAR = "view-insights-secrets-management-calendar",VIEW_INSIGHTS_SECRETS_MANAGEMENT_ACCESS_VOLUME = "view-insights-secrets-management-access-volume",VIEW_INSIGHTS_SECRETS_MANAGEMENT_UNUSED_ACCESS = "view-insights-secrets-management-unused-access",+ VIEW_INSIGHTS_SECRETS_MANAGEMENT_SECRET_EXPOSURE = "view-insights-secrets-management-secret-exposure",VIEW_INSIGHTS_SECRETS_MANAGEMENT_ORG_AUTH_METHOD_DISTRIBUTION = "view-insights-secrets-management-org-auth-method-distribution",VIEW_INSIGHTS_SECRETS_MANAGEMENT_ACCESS_LOCATIONS = "view-insights-secrets-management-access-locations",VIEW_INSIGHTS_SECRETS_MANAGEMENT_SUMMARY = "view-insights-secrets-management-summary",@@ -5939,6 +5940,14 @@ interface ViewSecretManagementInsightsUnusedAccessEvent {};}+interface ViewSecretManagementInsightsSecretExposureEvent {+ type: EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_SECRET_EXPOSURE;+ metadata: {+ projectId: string;+ projectName: string;+ };+}+interface ViewSecretManagementInsightsOrgAuthMethodDistributionEvent {type: EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_ORG_AUTH_METHOD_DISTRIBUTION;metadata: {@@ -8512,6 +8521,7 @@ export type Event =| ViewSecretManagementInsightsCalendarEvent| ViewSecretManagementInsightsAccessVolumeEvent| ViewSecretManagementInsightsUnusedAccessEvent+ | ViewSecretManagementInsightsSecretExposureEvent| ViewSecretManagementInsightsOrgAuthMethodDistributionEvent| ViewSecretManagementInsightsAccessLocationsEvent| ViewInsightsAuthMethodsEventdiff --git a/backend/src/ee/services/insights/insights-schemas.ts b/backend/src/ee/services/insights/insights-schemas.tsindex f1b7ac419f..30cb773abf 100644--- a/backend/src/ee/services/insights/insights-schemas.ts+++ b/backend/src/ee/services/insights/insights-schemas.ts@@ -1,6 +1,11 @@import { z } from "zod";import { IdentityAuthMethod } from "@app/db/schemas";+import {+ SecretExposureCountsSchema,+ SecretExposureSchema+} from "@app/ee/services/secret-read-activity/secret-read-activity-schemas";+import { SecretExposureBand } from "@app/ee/services/secret-read-activity/secret-read-activity-types";import { INSIGHTS } from "@app/lib/api-docs";import { ActorType } from "@app/services/auth/auth-type";@@ -79,11 +84,26 @@ export const UnusedSecretAccessSchema = z.object({secretPath: z.string().describe(INSIGHTS.GET_UNUSED_SECRET_ACCESS.secretPath),actorType: z.enum([ActorType.USER, ActorType.IDENTITY]).describe(INSIGHTS.GET_UNUSED_SECRET_ACCESS.actorType),actorId: z.string().describe(INSIGHTS.GET_UNUSED_SECRET_ACCESS.actorId),- actorName: z.string().describe(INSIGHTS.GET_UNUSED_SECRET_ACCESS.actorName),- entitledCount: z.number().int().describe(INSIGHTS.GET_UNUSED_SECRET_ACCESS.entitledCount),- unreadCount: z.number().int().describe(INSIGHTS.GET_UNUSED_SECRET_ACCESS.unreadCount),- ghostReaderCount: z.number().int().describe(INSIGHTS.GET_UNUSED_SECRET_ACCESS.ghostReaderCount)+ actorName: z.string().describe(INSIGHTS.GET_UNUSED_SECRET_ACCESS.actorName)})+ .merge(SecretExposureCountsSchema).array().describe(INSIGHTS.GET_UNUSED_SECRET_ACCESS.unusedAccess)});++export const SecretExposureListSchema = z.object({+ totalCount: z.number().int().describe(INSIGHTS.GET_SECRET_EXPOSURE.totalCount),+ bands: z.record(z.nativeEnum(SecretExposureBand), z.number().int()).describe(INSIGHTS.GET_SECRET_EXPOSURE.bands),+ trackingStartedAt: z.date().describe(INSIGHTS.GET_SECRET_EXPOSURE.trackingStartedAt),+ preliminaryUntil: z.date().describe(INSIGHTS.GET_SECRET_EXPOSURE.preliminaryUntil),+ secrets: z+ .object({+ secretKey: z.string().describe(INSIGHTS.GET_UNUSED_SECRET_ACCESS.secretKey),+ environment: z.string().describe(INSIGHTS.GET_UNUSED_SECRET_ACCESS.environment),+ secretPath: z.string().describe(INSIGHTS.GET_UNUSED_SECRET_ACCESS.secretPath),+ exposure: SecretExposureSchema+ })+ .merge(SecretExposureCountsSchema)+ .array()+ .describe(INSIGHTS.GET_SECRET_EXPOSURE.secrets)+});diff --git a/backend/src/ee/services/secret-read-activity/secret-read-activity-fns.test.ts b/backend/src/ee/services/secret-read-activity/secret-read-activity-fns.test.tsindex dff9a6ad02..bdf60aaa96 100644--- a/backend/src/ee/services/secret-read-activity/secret-read-activity-fns.test.ts+++ b/backend/src/ee/services/secret-read-activity/secret-read-activity-fns.test.ts@@ -3,13 +3,21 @@ import { describe, expect, test } from "vitest";import { ActorType } from "@app/services/auth/auth-type";import {+ calculateExposureScore,classifySecretReads,computeSecretReach,coversWholeWindow,getUtcMonthStart,indexSecretReads} from "./secret-read-activity-fns";-import { SecretReadObjectType, TReachSecret, TSecretLastRead, TSecretReachGraph } from "./secret-read-activity-types";+import {+ SecretExposureBand,+ SecretExposureDriver,+ SecretReadObjectType,+ TReachSecret,+ TSecretLastRead,+ TSecretReachGraph+} from "./secret-read-activity-types";const dbPass: TReachSecret = { id: "db-pass", folderId: "shared", key: "DB_PASS" };const dbUrl: TReachSecret = { id: "db-url", folderId: "shared", key: "DB_URL" };@@ -119,3 +127,66 @@ describe("coversWholeWindow", () => {expect(coversWholeWindow(windowStart, new Date("2026-10-10T00:00:00.000Z"), windowStart)).toBe(false);});});++describe("calculateExposureScore", () => {+ const pointsOf = (score: ReturnType<typeof calculateExposureScore>) =>+ score.drivers.reduce((total, driver) => total + driver.points, 0);++ test("is zero with nothing to drive it", () => {+ const exposure = calculateExposureScore({ entitledCount: 0, unreadCount: 0, ghostReaderCount: 0 });+ expect(exposure).toEqual({ score: 0, band: SecretExposureBand.Low, drivers: [] });+ });++ test("saturates each term at its weight", () => {+ const exposure = calculateExposureScore({ entitledCount: 40, unreadCount: 40, ghostReaderCount: 4 });+ expect(exposure.score).toBe(100);+ expect(exposure.band).toBe(SecretExposureBand.Critical);+ expect(exposure.drivers.map(({ kind, points }) => [kind, points])).toEqual([+ [SecretExposureDriver.Readers, 45],+ [SecretExposureDriver.GhostReaders, 30],+ [SecretExposureDriver.UnusedAccess, 25]+ ]);+ });++ test("weighs a few readers far more than a few more", () => {+ const two = calculateExposureScore({ entitledCount: 2, unreadCount: 0, ghostReaderCount: 0 }).score;+ const twelve = calculateExposureScore({ entitledCount: 12, unreadCount: 0, ghostReaderCount: 0 }).score;+ const fortyTwo = calculateExposureScore({ entitledCount: 42, unreadCount: 0, ghostReaderCount: 0 }).score;+ expect(twelve - two).toBeGreaterThan(fortyTwo - twelve);+ expect(fortyTwo).toBe(45);+ });++ test("lists the drivers largest first, with whole points adding up to the score", () => {+ const exposure = calculateExposureScore({ entitledCount: 3, unreadCount: 1, ghostReaderCount: 1 });+ expect(exposure.score).toBe(Math.round(45 * (Math.log2(4) / Math.log2(41)) + 30 * 0.25 + 25 * (1 / 3)));+ expect(exposure.band).toBe(SecretExposureBand.Elevated);+ expect(pointsOf(exposure)).toBe(exposure.score);+ expect(exposure.drivers.map((driver) => driver.points)).toEqual(+ [...exposure.drivers.map((driver) => driver.points)].sort((a, b) => b - a)+ );+ expect(exposure.drivers.every((driver) => Number.isInteger(driver.points) && driver.points > 0)).toBe(true);+ });++ test("leaves out a term worth nothing", () => {+ const exposure = calculateExposureScore({ entitledCount: 5, unreadCount: 0, ghostReaderCount: 0 });+ expect(exposure.drivers.map((driver) => driver.kind)).toEqual([SecretExposureDriver.Readers]);+ expect(pointsOf(exposure)).toBe(exposure.score);+ });++ test("puts the score in its band", () => {+ const bandOf = (counts: Parameters<typeof calculateExposureScore>[0]) => calculateExposureScore(counts).band;+ expect(bandOf({ entitledCount: 1, unreadCount: 0, ghostReaderCount: 0 })).toBe(SecretExposureBand.Low);+ expect(bandOf({ entitledCount: 1, unreadCount: 1, ghostReaderCount: 0 })).toBe(SecretExposureBand.Elevated);+ expect(bandOf({ entitledCount: 10, unreadCount: 8, ghostReaderCount: 2 })).toBe(SecretExposureBand.High);+ expect(bandOf({ entitledCount: 30, unreadCount: 30, ghostReaderCount: 3 })).toBe(SecretExposureBand.Critical);+ });++ test("words each driver with its counts", () => {+ const { drivers } = calculateExposureScore({ entitledCount: 1, unreadCount: 1, ghostReaderCount: 1 });+ expect(drivers.map((driver) => driver.label)).toEqual([+ "1 of 1 has not read it in 30 days",+ "1 user or machine identity can read the value",+ "1 ghost reader can no longer read it but still knows the value"+ ]);+ });+});diff --git a/backend/src/ee/services/secret-read-activity/secret-read-activity-fns.ts b/backend/src/ee/services/secret-read-activity/secret-read-activity-fns.tsindex 30ff99afe1..cb0d3f1fd5 100644--- a/backend/src/ee/services/secret-read-activity/secret-read-activity-fns.ts+++ b/backend/src/ee/services/secret-read-activity/secret-read-activity-fns.ts@@ -5,8 +5,12 @@ import { TSecretFolderDALFactory } from "@app/services/secret-folder/secret-foldimport { buildFolderIdMap, buildFolderPath } from "@app/services/secret-folder/secret-folder-fns";import {+ SecretExposureBand,+ SecretExposureDriver,SecretReadObjectType,TReachSecret,+ TSecretExposure,+ TSecretExposureCounts,TSecretLastRead,TSecretLocation,TSecretReach,@@ -127,3 +131,64 @@ export const classifySecretReads = (reach.folderIds.forEach((folderId) => record(SecretReadObjectType.Folder, folderId));return activity;};++const clamp01 = (value: number) => Math.max(0, Math.min(1, value));++// Counts grow long-tailed: going from 2 to 12 readers matters far more than going from 40 to 50.+const logScale = (value: number, saturateAt: number) => clamp01(Math.log2(value + 1) / Math.log2(saturateAt + 1));++const pluralize = (count: number, singular: string, plural: string) => `${count} ${count === 1 ? singular : plural}`;++// A score from 0 to 100 built from the three facts read activity gives: how many can read the value, how many+// who no longer can still know it, and how many of those who can never do. The weights follow the blast radius+// prototype's proportions for the same three terms, rescaled to add up to 100.+export const calculateExposureScore = ({+ entitledCount,+ unreadCount,+ ghostReaderCount+}: TSecretExposureCounts): TSecretExposure => {+ const terms = [+ {+ kind: SecretExposureDriver.Readers,+ points: 45 * logScale(entitledCount, 40),+ label: `${pluralize(entitledCount, "user or machine identity", "users and machine identities")} can read the value`+ },+ {+ kind: SecretExposureDriver.GhostReaders,+ points: 30 * clamp01(ghostReaderCount / 4),+ label: `${pluralize(ghostReaderCount, "ghost reader", "ghost readers")} can no longer read it but still ${+ ghostReaderCount === 1 ? "knows" : "know"+ } the value`+ },+ {+ kind: SecretExposureDriver.UnusedAccess,+ points: 25 * (entitledCount ? unreadCount / entitledCount : 0),+ label: `${unreadCount} of ${entitledCount} ${unreadCount === 1 ? "has" : "have"} not read it in ${SECRET_READ_ACTIVITY_WINDOW_DAYS} days`+ }+ ];+ const score = Math.round(terms.reduce((total, term) => total + term.points, 0));++ // Whole numbers that add up to exactly the score, by largest remainder: rounding each term on its own comes+ // out a point off the total often enough to look like a bug.+ const contributing = terms.filter((term) => term.points > 0).sort((a, b) => b.points - a.points);+ const points = contributing.map((term) => Math.floor(term.points));+ let remainder = score - points.reduce((total, value) => total + value, 0);+ contributing+ .map((term, index) => ({ index, fraction: term.points - points[index] }))+ .sort((a, b) => b.fraction - a.fraction)+ .forEach(({ index }) => {+ if (remainder <= 0) return;+ points[index] += 1;+ remainder -= 1;+ });+ const drivers = contributing+ .map((term, index) => ({ kind: term.kind, points: points[index], label: term.label }))+ .filter((driver) => driver.points > 0);++ let band = SecretExposureBand.Low;+ if (score >= 85) band = SecretExposureBand.Critical;+ else if (score >= 60) band = SecretExposureBand.High;+ else if (score >= 30) band = SecretExposureBand.Elevated;++ return { score, band, drivers };+};diff --git a/backend/src/ee/services/secret-read-activity/secret-read-activity-schemas.ts b/backend/src/ee/services/secret-read-activity/secret-read-activity-schemas.tsnew file mode 100644index 0000000000..91a92406bd--- /dev/null+++ b/backend/src/ee/services/secret-read-activity/secret-read-activity-schemas.ts@@ -0,0 +1,24 @@+import { z } from "zod";++import { SECRET_EXPOSURE } from "@app/lib/api-docs";++import { SecretExposureBand, SecretExposureDriver } from "./secret-read-activity-types";++export const SecretExposureSchema = z.object({+ score: z.number().int().min(0).max(100).describe(SECRET_EXPOSURE.score),+ band: z.nativeEnum(SecretExposureBand).describe(SECRET_EXPOSURE.band),+ drivers: z+ .object({+ kind: z.nativeEnum(SecretExposureDriver).describe(SECRET_EXPOSURE.driverKind),+ points: z.number().int().describe(SECRET_EXPOSURE.driverPoints),+ label: z.string().describe(SECRET_EXPOSURE.driverLabel)+ })+ .array()+ .describe(SECRET_EXPOSURE.drivers)+});++export const SecretExposureCountsSchema = z.object({+ entitledCount: z.number().int().describe(SECRET_EXPOSURE.entitledCount),+ unreadCount: z.number().int().describe(SECRET_EXPOSURE.unreadCount),+ ghostReaderCount: z.number().int().describe(SECRET_EXPOSURE.ghostReaderCount)+});diff --git a/backend/src/ee/services/secret-read-activity/secret-read-activity-service.ts b/backend/src/ee/services/secret-read-activity/secret-read-activity-service.tsindex ac491a44ff..440ac3bb73 100644--- a/backend/src/ee/services/secret-read-activity/secret-read-activity-service.ts+++ b/backend/src/ee/services/secret-read-activity/secret-read-activity-service.ts@@ -13,6 +13,7 @@ import { NotFoundError } from "@app/lib/errors";import { groupBy } from "@app/lib/fn";import { OrderByDirection, OrgServiceActor } from "@app/lib/types";import { ActorType } from "@app/services/auth/auth-type";+import { TIdentityDALFactory } from "@app/services/identity/identity-dal";import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { KmsDataKey } from "@app/services/kms/kms-types";import { TProjectDALFactory } from "@app/services/project/project-dal";@@ -21,9 +22,11 @@ import { TSecretFolderDALFactory } from "@app/services/secret-folder/secret-foldimport { TSecretImportDALFactory } from "@app/services/secret-import/secret-import-dal";import { getAllSecretReferences } from "@app/services/secret-v2-bridge/secret-reference-fns";import { TSecretV2BridgeDALFactory } from "@app/services/secret-v2-bridge/secret-v2-bridge-dal";+import { TUserDALFactory } from "@app/services/user/user-dal";import { TSecretReadActivityDALFactory } from "./secret-read-activity-dal";import {+ calculateExposureScore,classifySecretReads,computeSecretReach,coversWholeWindow,@@ -36,12 +39,18 @@ import {} from "./secret-read-activity-fns";import { TSecretReadActivityQueueServiceFactory } from "./secret-read-activity-queue";import {+ SecretExposureBand,+ TExposedSecret,TGetSecretReadActivityDTO,+ TListSecretExposureDTO,TListUnusedSecretAccessDTO,TReachSecret,TReadActivityScope,+ TSecretExposureCounts,+ TSecretLocation,TSecretReach,TSecretReachGraph,+ TSecretReaderType,TUnusedSecretAccess} from "./secret-read-activity-types";@@ -53,8 +62,11 @@ const UNUSED_SECRET_ACCESS_COMPUTE_WAIT_SECONDS = 60;// A large project can have millions of unread secret and actor pairs, so only the highest-ranked entries are// cached and listed, about 200 KB per project.const UNUSED_SECRET_ACCESS_MAX_LISTED = 1000;+const SECRET_EXPOSURE_MAX_LISTED = 100;type TCachedUnusedSecretAccess = TUnusedSecretAccess & { secretId: string };+type TCachedExposedSecret = TExposedSecret & { secretId: string };+type TSecretPermission = Parameters<typeof hasSecretReadValueOrDescribePermission>[0];type TSecretReadActivityServiceFactoryDep = {permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getProjectPermissions">;@@ -68,6 +80,8 @@ type TSecretReadActivityServiceFactoryDep = {projectEnvDAL: Pick<TProjectEnvDALFactory, "find">;secretImportDAL: Pick<TSecretImportDALFactory, "find">;secretV2BridgeDAL: Pick<TSecretV2BridgeDALFactory, "find" | "findSecretReferencesByProjectId">;+ userDAL: Pick<TUserDALFactory, "find">;+ identityDAL: Pick<TIdentityDALFactory, "find">;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;keyStore: Pick<TKeyStoreFactory, "setItemWithExpiry" | "getItem" | "ttl" | "acquireLock">;};@@ -83,6 +97,8 @@ export const secretReadActivityServiceFactory = ({projectEnvDAL,secretImportDAL,secretV2BridgeDAL,+ userDAL,+ identityDAL,kmsService,keyStore}: TSecretReadActivityServiceFactoryDep) => {@@ -244,6 +260,71 @@ export const secretReadActivityServiceFactory = ({};});};+ type TSecretActivity = Awaited<ReturnType<typeof $getReadActivity>>[number];++ // Reads are known from the later of when tracking began on the instance and when the project was created.+ const $getProjectTrackingStartedAt = async (projectId: string) => {+ const [instanceStartedAt, project] = await Promise.all([$getTrackingStartedAt(), projectDAL.findById(projectId)]);+ return {+ project,+ trackingStartedAt: new Date(Math.max(instanceStartedAt?.getTime() ?? 0, project?.createdAt.getTime() ?? 0))+ };+ };++ // How each secret stands, from everyone who can read its value today, admins included: unused access is+ // judged on the non-admins among them, since admins can read everything by design; ghost readers are readers+ // in the window who are not among them at all, so their access was since removed; and the exposure score is+ // computed from those counts. In a project tracked for less than the window, the window starts when tracking+ // did, so the results are preliminary.+ const $loadSecretSummarizer = async (projectId: string, orgId: string, windowStart: Date) => {+ const [{ userPermissions, identityPermissions }, accessChangedAtByActorId, adminActorIds, { trackingStartedAt }] =+ await Promise.all([+ permissionService.getProjectPermissions(projectId, orgId),+ secretReadActivityDAL.findAccessChangedAt(projectId),+ secretReadActivityDAL.findAdminActorIds(projectId),+ $getProjectTrackingStartedAt(projectId)+ ]);+ const judgedFrom = trackingStartedAt > windowStart ? trackingStartedAt : windowStart;+ const actors = [+ ...userPermissions.map((actor) => ({ ...actor, actorType: ActorType.USER as const })),+ ...identityPermissions.map((actor) => ({ ...actor, actorType: ActorType.IDENTITY as const }))+ ];+ // Actors with identical rules always get the same answer, so each distinct rule set is checked once.+ const actorGroups = Object.values(groupBy(actors, (actor) => JSON.stringify(actor.permission.rules)));+ const actorNames = new Map(actors.map((actor) => [`${actor.actorType}:${actor.id}`, actor.name]));++ const summarize = ({ secret, environment, secretPath, trackedSince, reads }: TSecretActivity) => {+ const entitled = actorGroups+ .filter(([{ permission }]) =>+ hasSecretReadValueOrDescribePermission(permission, ProjectPermissionSecretActions.ReadValue, {+ environment,+ secretPath,+ secretName: secret.key,+ secretTags: secret.tags?.map((tag) => tag.slug)+ })+ )+ .flat();+ const entitledKeys = new Set(entitled.map((actor) => `${actor.actorType}:${actor.id}`));+ const unread = entitled.filter(+ (actor) =>+ !adminActorIds.has(actor.id) &&+ !reads.has(`${actor.actorType}:${actor.id}`) &&+ coversWholeWindow(trackedSince, accessChangedAtByActorId.get(actor.id), judgedFrom)+ );+ const ghostReaders = [...reads.values()].filter((read) => !entitledKeys.has(`${read.actorType}:${read.actorId}`));+ return {+ entitled,+ unread,+ ghostReaders,+ exposure: calculateExposureScore({+ entitledCount: entitled.length,+ unreadCount: unread.length,+ ghostReaderCount: ghostReaders.length+ })+ };+ };+ return { summarize, actorNames };+ };const getSecretReadActivity = async ({ projectId, environment, secretPath, secretName }: TGetSecretReadActivityDTO,@@ -273,109 +354,80 @@ export const secretReadActivityServiceFactory = ({secretTags: secret.tags?.map((tag) => tag.slug)});- const [activity] = await $getReadActivity({- projectId,- windowStart: getReadActivityWindowStart(),- secret: { environment, secretPath, secretName },- tree- });+ const windowStart = getReadActivityWindowStart();+ const [[activity], { summarize, actorNames }] = await Promise.all([+ $getReadActivity({ projectId, windowStart, secret: { environment, secretPath, secretName }, tree }),+ $loadSecretSummarizer(projectId, actor.orgId, windowStart)+ ]);if (!activity) {throw new NotFoundError({message: `Secret with name '${secretName}' not found at path '${secretPath}' in environment '${environment}'`});}- return { trackedSince: activity.trackedSince, reads: [...activity.reads.values()] };- };+ const { entitled, unread, ghostReaders, exposure } = summarize(activity);++ // A ghost reader may have left the project or been deleted since, so names the project's members do not+ // give are looked up directly; a reader deleted outright has none.+ const unnamed = ghostReaders.filter((read) => !actorNames.has(`${read.actorType}:${read.actorId}`));+ const idsOf = (actorType: TSecretReaderType) =>+ unnamed.filter((read) => read.actorType === actorType).map((read) => read.actorId);+ const [userIds, identityIds] = [idsOf(ActorType.USER), idsOf(ActorType.IDENTITY)];+ const [users, identities] = await Promise.all([+ userIds.length ? userDAL.find({ $in: { id: userIds } }) : [],+ identityIds.length ? identityDAL.find({ $in: { id: identityIds } }) : []+ ]);+ users.forEach((user) => actorNames.set(`${ActorType.USER}:${user.id}`, user.username));+ identities.forEach((identity) => actorNames.set(`${ActorType.IDENTITY}:${identity.id}`, identity.name));- // Reads are known from the later of when tracking began on the instance and when the project was created.- const $getProjectTrackingStartedAt = async (projectId: string) => {- const [instanceStartedAt, project] = await Promise.all([$getTrackingStartedAt(), projectDAL.findById(projectId)]);return {- project,- trackingStartedAt: new Date(Math.max(instanceStartedAt?.getTime() ?? 0, project?.createdAt.getTime() ?? 0))+ trackedSince: activity.trackedSince,+ reads: [...activity.reads.values()],+ entitledCount: entitled.length,+ unreadCount: unread.length,+ ghostReaderCount: ghostReaders.length,+ exposure,+ ghostReaders: ghostReaders.map((read) => ({+ ...read,+ actorName: actorNames.get(`${read.actorType}:${read.actorId}`) ?? null+ }))};};// Everyone except admins who can read a secret's value but has not read it in the window, ranked by the secrets- // with the most of them. Admins can read everything by design, so listing them would only add noise. In a project- // tracked for less than the window, the window starts when tracking did, so the results are preliminary.+ // with the most of them, and the secrets with the highest exposure score.const $computeUnusedSecretAccess = async (projectId: string, orgId: string) => {const windowStart = getReadActivityWindowStart();- const [- activities,- { userPermissions, identityPermissions },- accessChangedAtByActorId,- adminActorIds,- { trackingStartedAt }- ] = await Promise.all([+ const [activities, { summarize }] = await Promise.all([$getReadActivity({ projectId, windowStart }),- permissionService.getProjectPermissions(projectId, orgId),- secretReadActivityDAL.findAccessChangedAt(projectId),- secretReadActivityDAL.findAdminActorIds(projectId),- $getProjectTrackingStartedAt(projectId)+ $loadSecretSummarizer(projectId, orgId, windowStart)]);- const judgedFrom = trackingStartedAt > windowStart ? trackingStartedAt : windowStart;- // Actors with identical rules always get the same answer, so each distinct rule set is checked once.- const allActorGroups = Object.values(- groupBy(- [- ...userPermissions.map((actor) => ({ ...actor, actorType: ActorType.USER as const })),- ...identityPermissions.map((actor) => ({ ...actor, actorType: ActorType.IDENTITY as const }))- ],- (actor) => JSON.stringify(actor.permission.rules)- )- );-- // Everyone who can read the value today, admins included. Unused access is judged on the non-admins among them;- // ghost readers are readers in the window who are not among them at all, so their access was since removed.- const entitledActorsOf = ({ secret, environment, secretPath }: (typeof activities)[number]) =>- allActorGroups- .filter(([{ permission }]) =>- hasSecretReadValueOrDescribePermission(permission, ProjectPermissionSecretActions.ReadValue, {- environment,- secretPath,- secretName: secret.key,- secretTags: secret.tags?.map((tag) => tag.slug)- })- )- .flat();- const summarizeSecret = (activity: (typeof activities)[number]) => {- const { trackedSince, reads } = activity;- const entitled = entitledActorsOf(activity);- const entitledKeys = new Set(entitled.map((actor) => `${actor.actorType}:${actor.id}`));- const unread = entitled.filter(- (actor) =>- !adminActorIds.has(actor.id) &&- !reads.has(`${actor.actorType}:${actor.id}`) &&- coversWholeWindow(trackedSince, accessChangedAtByActorId.get(actor.id), judgedFrom)- );- let ghostReaderCount = 0;- reads.forEach((_, key) => {- if (!entitledKeys.has(key)) ghostReaderCount += 1;- });- return { entitledCount: entitled.length, unread, ghostReaderCount };- };-- // Only counts are kept for every secret: a large project can have millions of unread pairs, and only the- // highest-ranked ones are listed, so their rows are built in a second pass.- const unreadCounts: { activityIndex: number; count: number }[] = [];+ // Only counts and the score are kept for every secret: a large project can have millions of unread pairs, and+ // only the highest-ranked secrets are listed, so their rows are built in a second pass.+ const summaries: (TSecretExposureCounts & { activityIndex: number; score: number })[] = [];+ const bands: Record<SecretExposureBand, number> = { low: 0, elevated: 0, high: 0, critical: 0 };for (let activityIndex = 0; activityIndex < activities.length; activityIndex += 1) {// Permission checks are synchronous, so yield between secrets to keep a large project from blocking other requests.// eslint-disable-next-line no-await-in-loopawait new Promise<void>((resolve) => {setImmediate(resolve);});- unreadCounts.push({ activityIndex, count: summarizeSecret(activities[activityIndex]).unread.length });+ const { entitled, unread, ghostReaders, exposure } = summarize(activities[activityIndex]);+ summaries.push({+ activityIndex,+ entitledCount: entitled.length,+ unreadCount: unread.length,+ ghostReaderCount: ghostReaders.length,+ score: exposure.score+ });+ bands[exposure.band] += 1;}- unreadCounts.sort((a, b) => b.count - a.count);const rows: TCachedUnusedSecretAccess[] = [];- for (const { activityIndex, count } of unreadCounts) {- if (rows.length >= UNUSED_SECRET_ACCESS_MAX_LISTED || count === 0) break;- const activity = activities[activityIndex];- const { entitledCount, unread, ghostReaderCount } = summarizeSecret(activity);- unread.forEach((actor) =>+ for (const summary of [...summaries].sort((a, b) => b.unreadCount - a.unreadCount)) {+ if (rows.length >= UNUSED_SECRET_ACCESS_MAX_LISTED || summary.unreadCount === 0) break;+ const activity = activities[summary.activityIndex];+ summarize(activity).unread.forEach((actor) =>rows.push({secretId: activity.secret.id,secretKey: activity.secret.key,@@ -384,15 +436,34 @@ export const secretReadActivityServiceFactory = ({actorType: actor.actorType,actorId: actor.id,actorName: actor.name,- entitledCount,- unreadCount: unread.length,- ghostReaderCount+ entitledCount: summary.entitledCount,+ unreadCount: summary.unreadCount,+ ghostReaderCount: summary.ghostReaderCount}));}++ const mostExposed = [...summaries]+ .filter((summary) => summary.score > 0)+ .sort((a, b) => b.score - a.score)+ .slice(0, SECRET_EXPOSURE_MAX_LISTED)+ .map(({ activityIndex, score, ...counts }): TCachedExposedSecret => {+ const activity = activities[activityIndex];+ return {+ secretId: activity.secret.id,+ secretKey: activity.secret.key,+ environment: activity.environment,+ secretPath: activity.secretPath,+ ...counts,+ exposure: calculateExposureScore(counts)+ };+ });+return {rows: rows.slice(0, UNUSED_SECRET_ACCESS_MAX_LISTED),- totalCount: unreadCounts.reduce((total, { count }) => total + count, 0)+ totalCount: summaries.reduce((total, { unreadCount }) => total + unreadCount, 0),+ mostExposed,+ bands};};@@ -422,37 +493,43 @@ export const secretReadActivityServiceFactory = ({}};- // The whole project is computed once a day and cached, so paging through it is cheap.- const listUnusedSecretAccess = async (- { projectId, offset, limit, orderBy, orderDirection }: TListUnusedSecretAccessDTO,- actor: OrgServiceActor- ) => {- const { permission } = await checkInsightsReadPermission(permissionService, projectId, actor);-+ // The whole project is computed once a day and cached, so paging through it is cheap. Both cards read the+ // same cached computation, so they agree.+ const $getCachedProjectSummary = async (projectId: string, orgId: string) => {const cacheKey = KeyStorePrefixes.InsightsCache(projectId, "unused-secret-access");- const { rows, totalCount } = await withCache({+ const summary = await withCache({keyStore,key: cacheKey,ttlSeconds: UNUSED_SECRET_ACCESS_CACHE_TTL_SECONDS,- fetcher: () => $computeUnusedSecretAccessShared(projectId, actor.orgId, cacheKey)+ fetcher: () => $computeUnusedSecretAccessShared(projectId, orgId, cacheKey)});- const [remainingTTL, { project, trackingStartedAt }, tree, currentSecrets] = await Promise.all([+ const [remainingTTL, { project, trackingStartedAt }] = await Promise.all([getCacheTtl(keyStore, cacheKey),- $getProjectTrackingStartedAt(projectId),+ $getProjectTrackingStartedAt(projectId)+ ]);+ return {+ ...summary,+ remainingTTL,+ projectName: project?.name ?? "",+ trackingStartedAt,+ preliminaryUntil: new Date(trackingStartedAt.getTime() + SECRET_READ_ACTIVITY_WINDOW_DAYS * DAY_IN_MS)+ };+ };++ // The cache is shared by everyone in the project and can be a day old, so each listed secret is checked against+ // the secret as it is now: deleted secrets drop out, keys and paths are current, and a caller only gets the+ // secrets they could see anyway.+ const $loadVisibleSecrets = async (projectId: string, permission: TSecretPermission, secretIds: string[]) => {+ const [tree, currentSecrets] = await Promise.all([loadProjectFolderTree({ folderDAL, projectEnvDAL }, projectId),- rows.length- ? secretV2BridgeDAL.find({- $in: { [`${TableName.SecretV2}.id` as "id"]: [...new Set(rows.map((row) => row.secretId))] }- })+ secretIds.length+ ? secretV2BridgeDAL.find({ $in: { [`${TableName.SecretV2}.id` as "id"]: [...new Set(secretIds)] } }): []]);- // The cache is shared by everyone in the project and can be a day old, so each row is checked against the- // secret as it is now: deleted secrets drop out, and a caller only gets the secrets they could see anyway.- const currentSecretById = new Map(currentSecrets.map((secret) => [secret.id, secret]));- const visibleRows = rows.flatMap(({ secretId, ...row }): TUnusedSecretAccess[] => {- const secret = currentSecretById.get(secretId);- const location = secret && tree.locationOf(secret.folderId);- if (!secret || !location) return [];+ const visible = new Map<string, TSecretLocation & { secretKey: string }>();+ currentSecrets.forEach((secret) => {+ const location = tree.locationOf(secret.folderId);+ if (!location) return;const canDescribe = hasSecretReadValueOrDescribePermission(permission,ProjectPermissionSecretActions.DescribeSecret,@@ -463,7 +540,25 @@ export const secretReadActivityServiceFactory = ({secretTags: secret.tags?.map((tag) => tag.slug)});- return canDescribe ? [{ ...row, secretKey: secret.key, ...location }] : [];+ if (canDescribe) visible.set(secret.id, { secretKey: secret.key, ...location });+ });+ return visible;+ };++ const listUnusedSecretAccess = async (+ { projectId, offset, limit, orderBy, orderDirection }: TListUnusedSecretAccessDTO,+ actor: OrgServiceActor+ ) => {+ const { permission } = await checkInsightsReadPermission(permissionService, projectId, actor);+ const { rows, totalCount, ...tracking } = await $getCachedProjectSummary(projectId, actor.orgId);+ const visibleSecrets = await $loadVisibleSecrets(+ projectId,+ permission,+ rows.map((row) => row.secretId)+ );+ const visibleRows = rows.flatMap(({ secretId, ...row }): TUnusedSecretAccess[] => {+ const secret = visibleSecrets.get(secretId);+ return secret ? [{ ...row, ...secret }] : [];});// Unsorted, the list keeps its ranking. The sort is stable, so ties keep it too.@@ -478,10 +573,34 @@ export const secretReadActivityServiceFactory = ({unusedAccess: sorted.slice(offset, offset + limit),totalCount: visibleRows.length,unlistedCount: totalCount - rows.length,- projectName: project?.name ?? "",- trackingStartedAt,- preliminaryUntil: new Date(trackingStartedAt.getTime() + SECRET_READ_ACTIVITY_WINDOW_DAYS * DAY_IN_MS),- remainingTTL+ projectName: tracking.projectName,+ trackingStartedAt: tracking.trackingStartedAt,+ preliminaryUntil: tracking.preliminaryUntil,+ remainingTTL: tracking.remainingTTL+ };+ };++ const listSecretExposure = async ({ projectId, offset, limit }: TListSecretExposureDTO, actor: OrgServiceActor) => {+ const { permission } = await checkInsightsReadPermission(permissionService, projectId, actor);+ const { mostExposed, bands, ...tracking } = await $getCachedProjectSummary(projectId, actor.orgId);+ const visibleSecrets = await $loadVisibleSecrets(+ projectId,+ permission,+ mostExposed.map((secret) => secret.secretId)+ );+ const visible = mostExposed.flatMap(({ secretId, ...row }): TExposedSecret[] => {+ const secret = visibleSecrets.get(secretId);+ return secret ? [{ ...row, ...secret }] : [];+ });++ return {+ secrets: visible.slice(offset, offset + limit),+ totalCount: visible.length,+ bands,+ projectName: tracking.projectName,+ trackingStartedAt: tracking.trackingStartedAt,+ preliminaryUntil: tracking.preliminaryUntil,+ remainingTTL: tracking.remainingTTL};};@@ -489,6 +608,7 @@ export const secretReadActivityServiceFactory = ({recordRead: secretReadActivityQueue.recordRead,recordBulkRead: secretReadActivityQueue.recordBulkRead,getSecretReadActivity,- listUnusedSecretAccess+ listUnusedSecretAccess,+ listSecretExposure};};diff --git a/backend/src/ee/services/secret-read-activity/secret-read-activity-types.ts b/backend/src/ee/services/secret-read-activity/secret-read-activity-types.tsindex 12292526cf..8450c6f3be 100644--- a/backend/src/ee/services/secret-read-activity/secret-read-activity-types.ts+++ b/backend/src/ee/services/secret-read-activity/secret-read-activity-types.ts@@ -93,17 +93,60 @@ export type TReadActivityScope = {secret?: Omit<TGetSecretReadActivityDTO, "projectId">;};-export type TUnusedSecretAccess = {+// How a secret stands: everyone who can read its value today, admins included; the non-admins among them with+// no read in the window; and the readers in the window who can no longer read it, so they still know the value.+export type TSecretExposureCounts = {+ entitledCount: number;+ unreadCount: number;+ ghostReaderCount: number;+};++export enum SecretExposureBand {+ Low = "low",+ Elevated = "elevated",+ High = "high",+ Critical = "critical"+}++export enum SecretExposureDriver {+ Readers = "readers",+ GhostReaders = "ghost-readers",+ UnusedAccess = "unused-access"+}++export type TSecretExposureDriver = {+ kind: SecretExposureDriver;+ // Whole points, adding up to the score, so the arithmetic shown beside the number is exact.+ points: number;+ label: string;+};++export type TSecretExposure = {+ score: number;+ band: SecretExposureBand;+ drivers: TSecretExposureDriver[];+};++export type TUnusedSecretAccess = TSecretExposureCounts & {secretKey: string;environment: string;secretPath: string;actorType: TSecretReaderType;actorId: string;actorName: string;- // How the secret as a whole stands, repeated on each of its rows so a row can be read on its own.- entitledCount: number;- unreadCount: number;- ghostReaderCount: number;+};++export type TExposedSecret = TSecretExposureCounts & {+ secretKey: string;+ environment: string;+ secretPath: string;+ exposure: TSecretExposure;+};++export type TListSecretExposureDTO = {+ projectId: string;+ offset: number;+ limit: number;};// Each value is the row field it sorts by.diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex 20ccd70219..c34e74f0e1 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -968,11 +968,21 @@ export const INSIGHTS = {secretPath: "The path of the folder the secret is in.",actorType: "Whether the entry is a user or a machine identity.",actorId: "The ID of the user or machine identity.",- actorName: "The username of the user, or the name of the machine identity.",- entitledCount: "How many users and machine identities, admins included, can read this secret's value today.",- unreadCount: "How many of those, admins excluded, have not read it in the window. This row is one of them.",- ghostReaderCount:- "How many users and machine identities read this secret in the window but can no longer read it today, for example after leaving the project. They still know the value."+ actorName: "The username of the user, or the name of the machine identity."+ },+ GET_SECRET_EXPOSURE: {+ projectId: "The ID of the project to list secret exposure for.",+ offset: "The number of secrets to skip before returning results.",+ limit: "The maximum number of secrets to return per page.",+ secrets:+ "The secrets with the highest exposure score, highest first: those of the top 100 in the project that the caller can see. Secrets scoring 0 are not listed.",+ totalCount: "The number of secrets the caller can page through.",+ bands:+ "How many of the project's secrets fall in each band, counted across the whole project before the caller's permissions are applied.",+ trackingStartedAt:+ "When reads started being tracked for this project: the later of when read tracking was enabled on the instance and when the project was created.",+ preliminaryUntil:+ "When the scores first cover the full 30 days. Until then they are preliminary: unused access covers only the reads since tracking started, and the access that existed when it started."},GET_SECRETS_ACCESS_VOLUME: {days: "One entry for each of the last seven days, oldest first. Days with no secret access are included with a total of zero.",@@ -1399,6 +1409,21 @@ export const SECRETS = {}} as const;+export const SECRET_EXPOSURE = {+ score:+ "The exposure score, from 0 to 100, built from how many can read the value, how many who can no longer read it still know it, and how many who can read it never do.",+ band: "The band the score falls in: low (0 to 29), elevated (30 to 59), high (60 to 84) or critical (85 to 100).",+ drivers: "What makes up the score, largest first. The points add up to the score.",+ driverKind:+ "Which term the driver is: readers (up to 45 points), ghost-readers (up to 30 points) or unused-access (up to 25 points).",+ driverPoints: "The whole points this term contributed to the score.",+ driverLabel: "The term in words, with its counts.",+ entitledCount: "How many users and machine identities, admins included, can read this secret's value today.",+ unreadCount: "How many of those, admins excluded, have not read it in the last 30 days.",+ ghostReaderCount:+ "How many users and machine identities read this secret in the last 30 days but can no longer read it today, for example after leaving the project. They still know the value."+};+export const RAW_SECRETS = {LIST: {expand: "Whether or not to expand secret references.",@@ -1494,7 +1519,12 @@ export const RAW_SECRETS = {"One entry for each user or machine identity that read the secret, or an import or reference of it, since trackedSince. Only the first read of each day is recorded.",actorType: "Whether the reader is a user or a machine identity.",actorId: "The ID of the user or machine identity.",- lastReadAt: "When the reader last read the secret, as the first read of that day."+ lastReadAt: "When the reader last read the secret, as the first read of that day.",+ exposure: "The secret's exposure score, computed from the counts in this response.",+ ghostReaders:+ "The users and machine identities that read the secret since trackedSince but can no longer read it today, for example after leaving the project. They still know the value.",+ ghostReaderName:+ "The username of the user, or the name of the machine identity. Null when the reader has since been deleted."},DUPLICATE_SECRET: {projectId: "The ID of the project containing the secret.",diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex b481067f8e..62f79851cd 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -3534,6 +3534,8 @@ export const registerRoutes = async (projectEnvDAL,secretImportDAL,secretV2BridgeDAL,+ userDAL,+ identityDAL,kmsService,keyStore});diff --git a/frontend/src/components/secrets/SecretExposureScore.tsx b/frontend/src/components/secrets/SecretExposureScore.tsxnew file mode 100644index 0000000000..153febe989--- /dev/null+++ b/frontend/src/components/secrets/SecretExposureScore.tsx@@ -0,0 +1,143 @@+import { Badge, Skeleton } from "@app/components/v3";+import { cn } from "@app/components/v3/utils";+import {+ SecretExposureBand,+ SecretExposureDriver,+ TSecretExposure+} from "@app/hooks/api/secretInsights/types";++export const EXPOSURE_BAND_LABEL: Record<SecretExposureBand, string> = {+ [SecretExposureBand.Low]: "Low",+ [SecretExposureBand.Elevated]: "Elevated",+ [SecretExposureBand.High]: "High",+ [SecretExposureBand.Critical]: "Critical"+};++export const EXPOSURE_BAND_VARIANT: Record<+ SecretExposureBand,+ "success" | "info" | "warning" | "danger"+> = {+ [SecretExposureBand.Low]: "success",+ [SecretExposureBand.Elevated]: "info",+ [SecretExposureBand.High]: "warning",+ [SecretExposureBand.Critical]: "danger"+};++export const EXPOSURE_BAND_TEXT: Record<SecretExposureBand, string> = {+ [SecretExposureBand.Low]: "text-success",+ [SecretExposureBand.Elevated]: "text-info",+ [SecretExposureBand.High]: "text-warning",+ [SecretExposureBand.Critical]: "text-danger"+};++const EXPOSURE_BAND_FILL: Record<SecretExposureBand, string> = {+ [SecretExposureBand.Low]: "bg-success",+ [SecretExposureBand.Elevated]: "bg-info",+ [SecretExposureBand.High]: "bg-warning",+ [SecretExposureBand.Critical]: "bg-danger"+};++const DRIVER_TONE: Record<SecretExposureDriver, string> = {+ [SecretExposureDriver.Readers]: "text-accent",+ [SecretExposureDriver.GhostReaders]: "text-warning",+ [SecretExposureDriver.UnusedAccess]: "text-warning"+};++// Ascending, so the meter, the caption and the card's summary come from one list.+export const EXPOSURE_BANDS = [+ { band: SecretExposureBand.Low, range: "0-29" },+ { band: SecretExposureBand.Elevated, range: "30-59" },+ { band: SecretExposureBand.High, range: "60-84" },+ { band: SecretExposureBand.Critical, range: "85-100" }+];++export const SecretExposureBadge = ({ exposure }: { exposure: TSecretExposure }) => (+ <Badge variant={EXPOSURE_BAND_VARIANT[exposure.band]} className="gap-1.5">+ <span className="font-mono">{exposure.score}</span>+ <span>{EXPOSURE_BAND_LABEL[exposure.band]}</span>+ </Badge>+);++type PanelProps = {+ exposure?: TSecretExposure;+ className?: string;+};++// The score with its arithmetic beside it: each driver carries the whole points it contributed, and they+// add up to the number shown.+export const SecretExposurePanel = ({ exposure, className }: PanelProps) => {+ if (!exposure) {+ return (+ <div className={cn("flex gap-6 rounded-md border border-border bg-container p-4", className)}>+ <Skeleton className="h-20 w-44" />+ <Skeleton className="h-20 flex-1" />+ </div>+ );+ }++ return (+ <div+ className={cn(+ "flex flex-wrap gap-x-6 gap-y-3 rounded-md border border-border bg-container p-4",+ className+ )}+ >+ <div className="flex w-44 shrink-0 flex-col gap-1.5">+ <span className="text-xs tracking-wide text-muted uppercase">Exposure</span>+ <div className="flex items-baseline gap-2">+ <span+ className={cn("text-4xl leading-none font-semibold", EXPOSURE_BAND_TEXT[exposure.band])}+ >+ {exposure.score}+ </span>+ <span className={cn("text-sm", EXPOSURE_BAND_TEXT[exposure.band])}>+ {EXPOSURE_BAND_LABEL[exposure.band]}+ </span>+ </div>+ {/* Four segments rather than a continuous bar: the band is what decides whether anyone acts. */}+ <div className="flex gap-1" aria-hidden>+ {EXPOSURE_BANDS.map((entry) => (+ <span+ key={entry.band}+ className={cn(+ "h-1 flex-1 rounded-full",+ entry.band === exposure.band ? EXPOSURE_BAND_FILL[exposure.band] : "bg-border"+ )}+ />+ ))}+ </div>+ <p className="text-xs leading-relaxed text-muted">+ {EXPOSURE_BANDS.map((entry) => `${EXPOSURE_BAND_LABEL[entry.band]} ${entry.range}`).join(+ " · "+ )}+ </p>+ </div>++ <div className="flex min-w-0 flex-1 flex-col gap-2 border-border sm:border-l sm:pl-6">+ {exposure.drivers.length ? (+ <div className="flex flex-col gap-1.5">+ {exposure.drivers.map((driver) => (+ <div key={driver.kind} className="flex gap-2.5">+ <span+ className={cn(+ "w-7 shrink-0 font-mono text-xs leading-relaxed",+ DRIVER_TONE[driver.kind]+ )}+ >+ +{driver.points}+ </span>+ <p className="text-xs leading-relaxed text-foreground">{driver.label}</p>+ </div>+ ))}+ </div>+ ) : (+ <p className="text-xs text-accent">Nobody can read this secret's value.</p>+ )}+ <p className="text-xs text-muted">+ Up to 45 points for how many can read the value, 30 for ghost readers who still know it,+ and 25 for the share who have not read it in 30 days.+ </p>+ </div>+ </div>+ );+};diff --git a/frontend/src/hooks/api/auditLogs/constants.tsx b/frontend/src/hooks/api/auditLogs/constants.tsxindex 710d240f5e..9d91b42858 100644--- a/frontend/src/hooks/api/auditLogs/constants.tsx+++ b/frontend/src/hooks/api/auditLogs/constants.tsx@@ -303,6 +303,8 @@ export const eventToNameMap: { [K in EventType]: string } = {"View Secrets Management Access Volume Insights",[EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_UNUSED_ACCESS]:"View Secrets Management Unused Access Insights",+ [EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_SECRET_EXPOSURE]:+ "View Secrets Management Secret Exposure Insights",[EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_ORG_AUTH_METHOD_DISTRIBUTION]:"View Organization Secrets Management Auth Method Distribution Insights",[EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_ACCESS_LOCATIONS]:diff --git a/frontend/src/hooks/api/auditLogs/enums.tsx b/frontend/src/hooks/api/auditLogs/enums.tsxindex baea88275c..889d260f70 100644--- a/frontend/src/hooks/api/auditLogs/enums.tsx+++ b/frontend/src/hooks/api/auditLogs/enums.tsx@@ -295,6 +295,7 @@ export enum EventType {VIEW_INSIGHTS_SECRETS_MANAGEMENT_CALENDAR = "view-insights-secrets-management-calendar",VIEW_INSIGHTS_SECRETS_MANAGEMENT_ACCESS_VOLUME = "view-insights-secrets-management-access-volume",VIEW_INSIGHTS_SECRETS_MANAGEMENT_UNUSED_ACCESS = "view-insights-secrets-management-unused-access",+ VIEW_INSIGHTS_SECRETS_MANAGEMENT_SECRET_EXPOSURE = "view-insights-secrets-management-secret-exposure",VIEW_INSIGHTS_SECRETS_MANAGEMENT_ORG_AUTH_METHOD_DISTRIBUTION = "view-insights-secrets-management-org-auth-method-distribution",VIEW_INSIGHTS_SECRETS_MANAGEMENT_ACCESS_LOCATIONS = "view-insights-secrets-management-access-locations",VIEW_INSIGHTS_SECRETS_MANAGEMENT_SUMMARY = "view-insights-secrets-management-summary",diff --git a/frontend/src/hooks/api/secretInsights/index.ts b/frontend/src/hooks/api/secretInsights/index.tsindex f8fc37d351..9c9999699d 100644--- a/frontend/src/hooks/api/secretInsights/index.ts+++ b/frontend/src/hooks/api/secretInsights/index.ts@@ -14,6 +14,7 @@ export {// useGetSecretAccessLocations,useGetSecretAccessVolume,useGetSecretBlindIndexStatus,+ useGetSecretExposure,useGetSecretsDuplication,useGetUnusedSecretAccess} from "./queries";@@ -24,6 +25,7 @@ export type {TCalendarRotation,TDuplicatedSecretEntry,TDuplicatedSecretGroup,+ TExposedSecret,TGetAuthMethodDistributionDTO,TGetAuthMethodDistributionResponse,TGetCalendarInsightsDTO,@@ -35,6 +37,8 @@ export type {TGetSecretAccessLocationsResponse,TGetSecretAccessVolumeDTO,TGetSecretAccessVolumeResponse,+ TGetSecretExposureDTO,+ TGetSecretExposureResponse,TGetSecretsDuplicationDTO,TGetSecretsDuplicationResponse,TGetUnusedSecretAccessDTO,@@ -51,7 +55,9 @@ export type {TSearchSecretsByValueResponse,TSecretAccessVolumeActor,TSecretAccessVolumeDay,+ TSecretExposure,+ TSecretExposureCounts,TSecretValueMatch,TUnusedSecretAccess} from "./types";-export { UnusedSecretAccessOrderBy } from "./types";+export { SecretExposureBand, SecretExposureDriver, UnusedSecretAccessOrderBy } from "./types";diff --git a/frontend/src/hooks/api/secretInsights/queries.tsx b/frontend/src/hooks/api/secretInsights/queries.tsxindex fe3b2abbf6..7ceae65fc6 100644--- a/frontend/src/hooks/api/secretInsights/queries.tsx+++ b/frontend/src/hooks/api/secretInsights/queries.tsx@@ -20,6 +20,8 @@ import {TGetSecretAccessVolumeResponse,TGetSecretBlindIndexStatusDTO,TGetSecretBlindIndexStatusResponse,+ TGetSecretExposureDTO,+ TGetSecretExposureResponse,TGetSecretsDuplicationDTO,TGetSecretsDuplicationResponse,TGetUnusedSecretAccessDTO,@@ -39,6 +41,8 @@ export const secretInsightsKeys = {[...secretInsightsKeys.all(), "access-volume", params] as const,unusedSecretAccess: (params: TGetUnusedSecretAccessDTO) =>[...secretInsightsKeys.all(), "unused-secret-access", params] as const,+ secretExposure: (params: TGetSecretExposureDTO) =>+ [...secretInsightsKeys.all(), "secret-exposure", params] as const,// accessLocations: (params: TGetSecretAccessLocationsDTO) =>// [...secretInsightsKeys.all(), "access-locations", params] as const,authMethodDistribution: (params: TGetAuthMethodDistributionDTO) =>@@ -71,6 +75,10 @@ export const secretInsightsKeys = {const INSIGHTS_STALE_TIME = 5 * 60 * 1000; // 5 minutes+// Fresh until the server's cached copy expires, then refetched, so an open card picks up the recomputed list.+const cachedInsightsRefreshMs = (data?: { remainingTtl: number }) =>+ data && data.remainingTtl > 0 ? data.remainingTtl * 1000 : INSIGHTS_STALE_TIME;+export const useGetCalendarInsights = (params: TGetCalendarInsightsDTO,options?: Omit<@@ -146,11 +154,38 @@ export const useGetUnusedSecretAccess = (const remainingTtl = Number(res.headers["x-cache-ttl"] ?? -1);return { ...res.data, remainingTtl };},- // Fresh until the server's cached copy expires, so the next fetch returns the recomputed list.- staleTime: (query) => {- const remainingTtl = query.state.data?.remainingTtl ?? -1;- return remainingTtl > 0 ? remainingTtl * 1000 : INSIGHTS_STALE_TIME;+ staleTime: (query) => cachedInsightsRefreshMs(query.state.data),+ refetchInterval: (query) => cachedInsightsRefreshMs(query.state.data),+ placeholderData: (previousData) => previousData,+ ...options+ });+};++export const useGetSecretExposure = (+ params: TGetSecretExposureDTO,+ options?: Omit<+ UseQueryOptions<+ TGetSecretExposureResponse,+ unknown,+ TGetSecretExposureResponse,+ ReturnType<typeof secretInsightsKeys.secretExposure>+ >,+ "queryKey" | "queryFn"+ >+) => {+ return useQuery({+ queryKey: secretInsightsKeys.secretExposure(params),+ queryFn: async () => {+ const { projectId, ...query } = params;+ const res = await apiRequest.get<Omit<TGetSecretExposureResponse, "remainingTtl">>(+ `/api/v1/insights/${projectId}/secrets/exposure`,+ { params: query }+ );+ const remainingTtl = Number(res.headers["x-cache-ttl"] ?? -1);+ return { ...res.data, remainingTtl };},+ staleTime: (query) => cachedInsightsRefreshMs(query.state.data),+ refetchInterval: (query) => cachedInsightsRefreshMs(query.state.data),placeholderData: (previousData) => previousData,...options});diff --git a/frontend/src/hooks/api/secretInsights/types.ts b/frontend/src/hooks/api/secretInsights/types.tsindex 44058c87e8..642d5fdf6d 100644--- a/frontend/src/hooks/api/secretInsights/types.ts+++ b/frontend/src/hooks/api/secretInsights/types.ts@@ -67,16 +67,41 @@ export type TGetUnusedSecretAccessDTO = {orderDirection?: OrderByDirection;};-export type TUnusedSecretAccess = {+// How a secret stands: everyone who can read its value today, admins included; the non-admins among them with+// no read in the last 30 days; and the readers who can no longer read it, so they still know the value.+export type TSecretExposureCounts = {+ entitledCount: number;+ unreadCount: number;+ ghostReaderCount: number;+};++export enum SecretExposureBand {+ Low = "low",+ Elevated = "elevated",+ High = "high",+ Critical = "critical"+}++export enum SecretExposureDriver {+ Readers = "readers",+ GhostReaders = "ghost-readers",+ UnusedAccess = "unused-access"+}++export type TSecretExposure = {+ score: number;+ band: SecretExposureBand;+ // Whole points that add up to the score, largest first.+ drivers: { kind: SecretExposureDriver; points: number; label: string }[];+};++export type TUnusedSecretAccess = TSecretExposureCounts & {secretKey: string;environment: string;secretPath: string;actorType: "user" | "identity";actorId: string;actorName: string;- entitledCount: number;- unreadCount: number;- ghostReaderCount: number;};export type TGetUnusedSecretAccessResponse = {@@ -88,6 +113,28 @@ export type TGetUnusedSecretAccessResponse = {remainingTtl: number;};+export type TGetSecretExposureDTO = {+ projectId: string;+ offset: number;+ limit: number;+};++export type TExposedSecret = TSecretExposureCounts & {+ secretKey: string;+ environment: string;+ secretPath: string;+ exposure: TSecretExposure;+};++export type TGetSecretExposureResponse = {+ secrets: TExposedSecret[];+ totalCount: number;+ bands: Record<SecretExposureBand, number>;+ trackingStartedAt: string;+ preliminaryUntil: string;+ remainingTtl: number;+};+export type TGetInsightsSummaryDTO = {projectId: string;staleSecretsOffset?: number;diff --git a/frontend/src/hooks/api/secrets/types.ts b/frontend/src/hooks/api/secrets/types.tsindex 60f4cf4e67..b192d78153 100644--- a/frontend/src/hooks/api/secrets/types.ts+++ b/frontend/src/hooks/api/secrets/types.ts@@ -2,6 +2,7 @@ import { ProjectPermissionSecretActions } from "@app/context/ProjectPermissionCoimport { Reminder } from "@app/hooks/api/reminders/types";import { PendingAction } from "../secretFolders/types";+import { TSecretExposure, TSecretExposureCounts } from "../secretInsights/types";import type { WsTag } from "../tags/types";export enum SecretType {@@ -162,13 +163,21 @@ export type TGetSecretAccessListDTO = {export type TGetSecretReadActivityDTO = Omit<TGetSecretAccessListDTO, "includeAllEntities">;-export type TSecretReadActivity = {+export type TSecretReadActivity = TSecretExposureCounts & {trackedSince: string;reads: {actorType: "user" | "identity";actorId: string;lastReadAt: string;}[];+ exposure: TSecretExposure;+ ghostReaders: {+ actorType: "user" | "identity";+ actorId: string;+ // Null when the reader has since been deleted.+ actorName: string | null;+ lastReadAt: string;+ }[];};export type TCreateSecretsV3DTO = {diff --git a/frontend/src/pages/secret-manager/InsightsPage/InsightsPage.tsx b/frontend/src/pages/secret-manager/InsightsPage/InsightsPage.tsxindex d952b030df..2db6262abe 100644--- a/frontend/src/pages/secret-manager/InsightsPage/InsightsPage.tsx+++ b/frontend/src/pages/secret-manager/InsightsPage/InsightsPage.tsx@@ -34,6 +34,7 @@ import {DuplicatedSecretsCard,InsightsSummaryCards,SecretAccessChart,+ SecretExposureCard,UnusedSecretAccessCard} from "./components";@@ -136,6 +137,9 @@ export const InsightsPage = withProjectPermission(<div className="mt-6"><AuditReportsCard /></div>+ <div className="mt-6">+ <SecretExposureCard />+ </div><div className="mt-6"><UnusedSecretAccessCard /></div>diff --git a/frontend/src/pages/secret-manager/InsightsPage/components/SecretExposureCard.tsx b/frontend/src/pages/secret-manager/InsightsPage/components/SecretExposureCard.tsxnew file mode 100644index 0000000000..f8c7cc6273--- /dev/null+++ b/frontend/src/pages/secret-manager/InsightsPage/components/SecretExposureCard.tsx@@ -0,0 +1,244 @@+import { useParams } from "@tanstack/react-router";+import axios from "axios";+import { format } from "date-fns";+import { FolderIcon, InfoIcon, KeyIcon } from "lucide-react";++import { GoToSecretButton } from "@app/components/secrets/GoToSecretButton";+import {+ EXPOSURE_BAND_LABEL,+ EXPOSURE_BAND_TEXT,+ EXPOSURE_BANDS,+ SecretExposureBadge+} from "@app/components/secrets/SecretExposureScore";+import {+ Badge,+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+ Empty,+ EmptyDescription,+ EmptyHeader,+ EmptyTitle,+ Pagination,+ Skeleton,+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+ Tooltip,+ TooltipContent,+ TooltipTrigger+} from "@app/components/v3";+import { cn } from "@app/components/v3/utils";+import { useProject, useSubscription } from "@app/context";+import { usePagination, useResetPageHelper } from "@app/hooks";+import { useGetSecretExposure } from "@app/hooks/api/secretInsights";++export const SecretExposureCard = () => {+ const { currentProject, projectId } = useProject();+ const { orgId } = useParams({ strict: false });+ const { subscription } = useSubscription();+ const { page, setPage, perPage, setPerPage, offset, limit } = usePagination("", {+ initPerPage: 10+ });++ const { data, isPending, error } = useGetSecretExposure(+ { projectId, offset, limit },+ { enabled: Boolean(subscription?.secretAccessInsights) }+ );+ const totalCount = data?.totalCount ?? 0;+ useResetPageHelper({ totalCount, offset, setPage });++ const environmentNames = new Map(currentProject.environments.map((env) => [env.slug, env.name]));++ const renderBody = () => {+ if (isPending) return <Skeleton className="h-[200px] w-full" />;++ if (!data) {+ return (+ <Empty className="border">+ <EmptyHeader>+ <EmptyTitle>Could not load secret exposure</EmptyTitle>+ <EmptyDescription>+ {(axios.isAxiosError(error) &&+ (error.response?.data as { message?: string })?.message) ||+ "Try again in a moment."}+ </EmptyDescription>+ </EmptyHeader>+ </Empty>+ );+ }++ const isPreliminary = new Date(data.preliminaryUntil) > new Date();+ // Descending, so the band that needs attention first reads first.+ const bandSummary = [...EXPOSURE_BANDS].reverse();++ return (+ <>+ <div className="mb-4 grid grid-cols-2 gap-3 sm:grid-cols-4">+ {bandSummary.map(({ band, range }) => (+ <div key={band} className="rounded-md border border-border bg-container px-3 py-2">+ <div className={cn("text-2xl leading-none font-semibold", EXPOSURE_BAND_TEXT[band])}>+ {data.bands[band].toLocaleString()}+ </div>+ <div className="mt-1 text-xs text-muted">+ {EXPOSURE_BAND_LABEL[band]} · {range}+ </div>+ </div>+ ))}+ </div>+ {isPreliminary && (+ <p className="mb-4 flex items-center gap-1.5 text-xs text-muted">+ <InfoIcon className="size-3.5 shrink-0" />+ Preliminary: unused access only covers reads since{" "}+ {format(new Date(data.trackingStartedAt), "PP")}. Scores are complete on{" "}+ {format(new Date(data.preliminaryUntil), "PP")}.+ </p>+ )}+ {totalCount === 0 ? (+ <Empty className="border">+ <EmptyHeader>+ <EmptyTitle>No exposed secrets</EmptyTitle>+ <EmptyDescription>A secret scores once someone can read its value.</EmptyDescription>+ </EmptyHeader>+ </Empty>+ ) : (+ <>+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead>Secret Key</TableHead>+ <TableHead>Environment</TableHead>+ <TableHead>Path</TableHead>+ <TableHead className="whitespace-nowrap">Exposure</TableHead>+ <TableHead className="whitespace-nowrap">Readers</TableHead>+ <TableHead className="whitespace-nowrap">No Reads</TableHead>+ <TableHead className="whitespace-nowrap">Ghost Readers</TableHead>+ <TableHead variant="action" />+ </TableRow>+ </TableHeader>+ <TableBody>+ {data.secrets.map((row) => (+ <TableRow+ key={`${row.environment}-${row.secretPath}-${row.secretKey}`}+ className="group/row"+ >+ <TableCell isTruncatable className="max-w-60">+ <div className="flex items-center gap-2">+ <KeyIcon className="size-4 shrink-0 text-muted" />+ <span className="truncate font-mono">{row.secretKey}</span>+ </div>+ </TableCell>+ <TableCell>+ <Badge variant="info" isTruncatable className="max-w-full">+ <span>{environmentNames.get(row.environment) ?? row.environment}</span>+ </Badge>+ </TableCell>+ <TableCell isTruncatable className="max-w-48">+ <div className="flex items-center gap-2">+ <FolderIcon className="size-3.5 shrink-0 text-folder" />+ <span className="truncate">{row.secretPath}</span>+ </div>+ </TableCell>+ <TableCell className="whitespace-nowrap">+ <Tooltip>+ <TooltipTrigger asChild>+ <span>+ <SecretExposureBadge exposure={row.exposure} />+ </span>+ </TooltipTrigger>+ <TooltipContent className="max-w-72">+ <ul className="flex flex-col gap-1">+ {row.exposure.drivers.map((driver) => (+ <li key={driver.kind} className="flex gap-2">+ <span className="w-7 shrink-0 font-mono">+{driver.points}</span>+ <span>{driver.label}</span>+ </li>+ ))}+ </ul>+ </TooltipContent>+ </Tooltip>+ </TableCell>+ <TableCell className="whitespace-nowrap">+ <Tooltip>+ <TooltipTrigger asChild>+ <span>{row.entitledCount}</span>+ </TooltipTrigger>+ <TooltipContent>+ {row.entitledCount} users and machine identities, admins included, can+ read this secret's value+ </TooltipContent>+ </Tooltip>+ </TableCell>+ <TableCell className="whitespace-nowrap">+ <Tooltip>+ <TooltipTrigger asChild>+ <span>+ {row.unreadCount} of {row.entitledCount}+ </span>+ </TooltipTrigger>+ <TooltipContent>+ {row.unreadCount} of the {row.entitledCount} who can read this secret have+ not read it in the last 30 days+ </TooltipContent>+ </Tooltip>+ </TableCell>+ <TableCell className="whitespace-nowrap">+ {row.ghostReaderCount > 0 ? (+ <Tooltip>+ <TooltipTrigger asChild>+ <Badge variant="warning">{row.ghostReaderCount}</Badge>+ </TooltipTrigger>+ <TooltipContent>+ {row.ghostReaderCount} read this secret in the last 30 days but can no+ longer access it. They still know the value.+ </TooltipContent>+ </Tooltip>+ ) : (+ <span className="text-muted">0</span>+ )}+ </TableCell>+ <TableCell variant="action">+ <GoToSecretButton+ orgId={orgId as string}+ projectId={projectId}+ secretKey={row.secretKey}+ secretPath={row.secretPath}+ environmentSlug={row.environment}+ isProjectMember+ />+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ <Pagination+ count={totalCount}+ page={page}+ perPage={perPage}+ onChangePage={setPage}+ onChangePerPage={setPerPage}+ />+ </>+ )}+ </>+ );+ };++ return (+ <Card>+ <CardHeader>+ <CardTitle>Secret Exposure</CardTitle>+ <CardDescription>+ The secrets with the highest exposure score, from how many can read the value, who can no+ longer read it but still knows it, and who never reads it+ </CardDescription>+ </CardHeader>+ <CardContent>{renderBody()}</CardContent>+ </Card>+ );+};diff --git a/frontend/src/pages/secret-manager/InsightsPage/components/index.ts b/frontend/src/pages/secret-manager/InsightsPage/components/index.tsindex 1073b2a662..fc9c698bd3 100644--- a/frontend/src/pages/secret-manager/InsightsPage/components/index.ts+++ b/frontend/src/pages/secret-manager/InsightsPage/components/index.ts@@ -6,6 +6,7 @@ export { CalendarLegend } from "./CalendarLegend";export { DuplicatedSecretsCard } from "./DuplicatedSecretsCard";export { InsightsSummaryCards } from "./InsightsSummaryCards";export { SecretAccessChart } from "./SecretAccessChart";+export { SecretExposureCard } from "./SecretExposureCard";export type { CalendarEvent } from "./types";export { UnusedSecretAccessCard } from "./UnusedSecretAccessCard";// export { WorldMap } from "./WorldMap";diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/SecretAccessInsights.tsx b/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/SecretAccessInsights.tsxindex e799f03bf8..48a6989294 100644--- a/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/SecretAccessInsights.tsx+++ b/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/SecretAccessInsights.tsx@@ -20,6 +20,7 @@ import {} from "lucide-react";import { createNotification } from "@app/components/notifications";+import { SecretExposurePanel } from "@app/components/secrets/SecretExposureScore";import { SecretReadStatusBadge } from "@app/components/secrets/SecretReadStatusBadge";import {Button,@@ -640,6 +641,9 @@ export function SecretAccessInsights({ secretKey, environment, secretPath }: Proreturn (<><div className="flex thin-scrollbar flex-col gap-4 overflow-y-auto p-4">+ {canReadInsights && !readActivityError && (+ <SecretExposurePanel exposure={readActivity?.exposure} />+ )}<div className="flex items-center gap-2"><Label className="cursor-pointer gap-1.5 text-xs whitespace-nowrap text-muted"><Toggle@@ -900,6 +904,51 @@ export function SecretAccessInsights({ secretKey, environment, secretPath }: Pro</TableBody></Table>)}+ {canReadInsights && readActivity && readActivity.ghostReaders.length > 0 && (+ <div className="flex flex-col gap-3">+ <div>+ <h3 className="text-sm font-medium">Ghost Readers</h3>+ <p className="text-xs text-muted">+ Read this secret since {format(new Date(readActivity.trackedSince), "PP")} but can+ no longer access it. They still know the value.+ </p>+ </div>+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead className="w-48">Type</TableHead>+ <TableHead>Name</TableHead>+ <TableHead className="w-40">Last Read</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {readActivity.ghostReaders.map((reader) => {+ const { icon: TypeIcon, label: typeLabel } = TYPE_CONFIG[reader.actorType];+ return (+ <TableRow key={`${reader.actorType}-${reader.actorId}`}>+ <TableCell>+ <span className="flex items-center gap-2">+ <TypeIcon className="size-4 text-accent" />+ {typeLabel}+ </span>+ </TableCell>+ <TableCell isTruncatable className="max-w-[180px] font-medium">+ {reader.actorName ?? (+ <span className="text-muted italic">+ Deleted {reader.actorType === "user" ? "user" : "machine identity"}+ </span>+ )}+ </TableCell>+ <TableCell className="w-40 whitespace-nowrap">+ <SecretReadStatusBadge lastReadAt={reader.lastReadAt} />+ </TableCell>+ </TableRow>+ );+ })}+ </TableBody>+ </Table>+ </div>+ )}</div><Sheet