Skip to content

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

feat(insights): fold unused access into the exposure card and judge no-reads on the tracked period

Dimitris Staratzisfe8d4179f74c
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.md
index 1318b9823e..9946065f7b 100644
--- a/backend/CLAUDE.md
+++ b/backend/CLAUDE.md
@@ -1155,12 +1155,17 @@ owns the two read endpoints and hands `recordRead` / `recordBulkRead` through to
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.
+ queries (syncs, rotation age, cross-project destinations) are deliberately left out. The unused-access term is
+ weighted by how much of the 30-day window the reads cover (`trackedDays`, from the project's `judgedFrom`), and
+ its label names that period, so a project tracked for three days neither claims "30 days" nor scores three
+ days of silence like thirty. `$loadSecretSummarizer` is the one place the counts and the score are derived,
+ used by the project computation and the per-secret endpoint, so the sheet and the card agree. The project
+ computation is cached per project (`insights-cache:<projectId>:secret-exposure`, under a per-project lock on a
+ cold cache) and keeps the 500 highest-scoring secrets plus a per-band tally, served by
+ `GET /insights/:projectId/secrets/exposure` with a per-caller DescribeSecret recheck of every listed secret. The
+ per-secret endpoint returns, for every reader who can read the value, whether they count as unused access and
+ why not (`isAdmin`, `accessChangedAt` after `judgedFrom`, or a secret newer than it), and 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 Settings
diff --git a/backend/src/ee/routes/v1/insights-router.ts b/backend/src/ee/routes/v1/insights-router.ts
index 62f6436d44..3afa8743ea 100644
--- a/backend/src/ee/routes/v1/insights-router.ts
+++ b/backend/src/ee/routes/v1/insights-router.ts
@@ -20,10 +20,9 @@ import {
SecretExposureListSchema,
SecretsProjectsSchema,
SecretsSummarySchema,
- StaticSecretsUsageSchema,
- UnusedSecretAccessSchema
+ StaticSecretsUsageSchema
} from "@app/ee/services/insights/insights-schemas";
-import { UnusedSecretAccessOrderBy } from "@app/ee/services/secret-read-activity/secret-read-activity-types";
+import { SecretExposureOrderBy } from "@app/ee/services/secret-read-activity/secret-read-activity-types";
import { INSIGHTS } from "@app/lib/api-docs";
import { OrderByDirection } from "@app/lib/types";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
@@ -483,75 +482,35 @@ export const registerInsightsRouter = async (server: FastifyZodProvider) => {
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",
- config: { rateLimit: readLimit },
- schema: {
- operationId: "getInsightsUnusedSecretAccess",
- description:
- "List the users and machine identities, other than project admins, that can read a secret's value but have not read it in the last 30 days",
- security: [{ bearerAuth: [] }],
- params: z.object({
- projectId: z.string().trim().max(36).describe(INSIGHTS.GET_UNUSED_SECRET_ACCESS.projectId)
- }),
- querystring: z.object({
- offset: z.coerce.number().int().min(0).max(10000).default(0).describe(INSIGHTS.GET_UNUSED_SECRET_ACCESS.offset),
- limit: z.coerce.number().int().min(1).max(100).default(20).describe(INSIGHTS.GET_UNUSED_SECRET_ACCESS.limit),
- orderBy: z.nativeEnum(UnusedSecretAccessOrderBy).optional().describe(INSIGHTS.GET_UNUSED_SECRET_ACCESS.orderBy),
+ offset: z.coerce.number().int().min(0).max(500).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),
+ orderBy: z.nativeEnum(SecretExposureOrderBy).optional().describe(INSIGHTS.GET_SECRET_EXPOSURE.orderBy),
orderDirection: z
.nativeEnum(OrderByDirection)
.default(OrderByDirection.ASC)
- .describe(INSIGHTS.GET_UNUSED_SECRET_ACCESS.orderDirection)
+ .describe(INSIGHTS.GET_SECRET_EXPOSURE.orderDirection)
}),
response: {
- 200: UnusedSecretAccessSchema
+ 200: SecretExposureListSchema
}
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),
handler: async (req, reply) => {
const { projectId } = req.params;
const {
- unusedAccess,
+ secrets,
totalCount,
unlistedCount,
+ bands,
trackingStartedAt,
preliminaryUntil,
remainingTTL,
projectName
- } = await server.services.secretReadActivity.listUnusedSecretAccess({ projectId, ...req.query }, req.permission);
+ } = await server.services.secretReadActivity.listSecretExposure({ projectId, ...req.query }, req.permission);
await server.services.auditLog.createAuditLog({
projectId,
event: {
- type: EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_UNUSED_ACCESS,
+ type: EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_SECRET_EXPOSURE,
metadata: { projectId, projectName }
},
...req.auditLogInfo
@@ -560,8 +519,7 @@ export const registerInsightsRouter = async (server: FastifyZodProvider) => {
if (remainingTTL && remainingTTL >= 0) {
void reply.header("X-Cache-TTL", remainingTTL);
}
-
- return { unusedAccess, totalCount, unlistedCount, trackingStartedAt, preliminaryUntil };
+ return { secrets, totalCount, unlistedCount, bands, trackingStartedAt, preliminaryUntil };
}
});
diff --git a/backend/src/ee/routes/v1/secret-router.ts b/backend/src/ee/routes/v1/secret-router.ts
index b3445b54f0..f9b55ca868 100644
--- a/backend/src/ee/routes/v1/secret-router.ts
+++ b/backend/src/ee/routes/v1/secret-router.ts
@@ -115,6 +115,7 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {
readActivity: z
.object({
trackedSince: z.date().describe(RAW_SECRETS.GET_READ_ACTIVITY.trackedSince),
+ judgedFrom: z.date().describe(RAW_SECRETS.GET_READ_ACTIVITY.judgedFrom),
reads: z
.object({
actorType: z
@@ -125,6 +126,18 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {
})
.array()
.describe(RAW_SECRETS.GET_READ_ACTIVITY.reads),
+ entitled: 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),
+ unread: z.boolean().describe(RAW_SECRETS.GET_READ_ACTIVITY.unread),
+ isAdmin: z.boolean().describe(RAW_SECRETS.GET_READ_ACTIVITY.isAdmin),
+ accessChangedAt: z.date().nullable().describe(RAW_SECRETS.GET_READ_ACTIVITY.accessChangedAt)
+ })
+ .array()
+ .describe(RAW_SECRETS.GET_READ_ACTIVITY.entitled),
exposure: SecretExposureSchema.describe(RAW_SECRETS.GET_READ_ACTIVITY.exposure),
ghostReaders: z
.object({
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.ts
index 7ee4e87b0c..6d156616d2 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
@@ -218,7 +218,6 @@ const DATA_ACCESS_EVENT_TYPES: readonly EventType[] = [
EventType.VIEW_INSIGHTS_AUTH_METHODS,
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,
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index a708453d41..ddc58f75c7 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -744,7 +744,6 @@ export enum EventType {
VIEW_INSIGHTS_AUTH_METHODS = "view-insights-auth-methods",
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",
@@ -5932,14 +5931,6 @@ interface ViewSecretManagementInsightsAccessVolumeEvent {
};
}
-interface ViewSecretManagementInsightsUnusedAccessEvent {
- type: EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_UNUSED_ACCESS;
- metadata: {
- projectId: string;
- projectName: string;
- };
-}
-
interface ViewSecretManagementInsightsSecretExposureEvent {
type: EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_SECRET_EXPOSURE;
metadata: {
@@ -8520,7 +8511,6 @@ export type Event =
| DashboardGetSecretVersionValueEvent
| ViewSecretManagementInsightsCalendarEvent
| ViewSecretManagementInsightsAccessVolumeEvent
- | ViewSecretManagementInsightsUnusedAccessEvent
| ViewSecretManagementInsightsSecretExposureEvent
| ViewSecretManagementInsightsOrgAuthMethodDistributionEvent
| ViewSecretManagementInsightsAccessLocationsEvent
diff --git a/backend/src/ee/services/insights/insights-schemas.ts b/backend/src/ee/services/insights/insights-schemas.ts
index 30cb773abf..9b97e6bbf5 100644
--- a/backend/src/ee/services/insights/insights-schemas.ts
+++ b/backend/src/ee/services/insights/insights-schemas.ts
@@ -7,7 +7,6 @@ import {
} 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";
export const SecretsSummarySchema = z.object({
activeLeases: z.number().int().describe(INSIGHTS.GET_SECRETS_SUMMARY.activeLeases),
@@ -72,35 +71,17 @@ export const SecretsProjectsSchema = z.object({
limit: z.number().int().describe(INSIGHTS.GET_SECRETS_PROJECTS.limit)
});
-export const UnusedSecretAccessSchema = z.object({
- totalCount: z.number().int().describe(INSIGHTS.GET_UNUSED_SECRET_ACCESS.totalCount),
- unlistedCount: z.number().int().describe(INSIGHTS.GET_UNUSED_SECRET_ACCESS.unlistedCount),
- trackingStartedAt: z.date().describe(INSIGHTS.GET_UNUSED_SECRET_ACCESS.trackingStartedAt),
- preliminaryUntil: z.date().describe(INSIGHTS.GET_UNUSED_SECRET_ACCESS.preliminaryUntil),
- unusedAccess: 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),
- 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)
- })
- .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),
+ unlistedCount: z.number().int().describe(INSIGHTS.GET_SECRET_EXPOSURE.unlistedCount),
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),
+ secretKey: z.string().describe(INSIGHTS.GET_SECRET_EXPOSURE.secretKey),
+ environment: z.string().describe(INSIGHTS.GET_SECRET_EXPOSURE.environment),
+ secretPath: z.string().describe(INSIGHTS.GET_SECRET_EXPOSURE.secretPath),
exposure: SecretExposureSchema
})
.merge(SecretExposureCountsSchema)
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.ts
index bdf60aaa96..9f20fb6fca 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
@@ -189,4 +189,33 @@ describe("calculateExposureScore", () => {
"1 ghost reader can no longer read it but still knows the value"
]);
});
+
+ test("weights unused access by how much of the window the reads cover, and says so", () => {
+ const counts = { entitledCount: 4, unreadCount: 4, ghostReaderCount: 0 };
+ const fullWindow = calculateExposureScore(counts);
+ const threeDays = calculateExposureScore(counts, 3);
+ const firstDay = calculateExposureScore(counts, 0.9);
+ const unusedPoints = (exposure: ReturnType<typeof calculateExposureScore>) =>
+ exposure.drivers.find((driver) => driver.kind === SecretExposureDriver.UnusedAccess)?.points ?? 0;
+
+ expect(unusedPoints(fullWindow)).toBe(25);
+ expect(unusedPoints(threeDays)).toBeLessThan(unusedPoints(fullWindow));
+ expect(unusedPoints(firstDay)).toBeLessThan(unusedPoints(threeDays));
+ expect(threeDays.drivers.map((driver) => driver.label)).toContain("4 of 4 have not read it in the 3 days tracked");
+ expect(calculateExposureScore(counts, 1).drivers.map((driver) => driver.label)).toContain(
+ "4 of 4 have not read it in the 1 day tracked"
+ );
+ expect(firstDay.drivers.map((driver) => driver.label)).toContain(
+ "4 of 4 have not read it since tracking began today"
+ );
+ expect(calculateExposureScore(counts, 45).drivers.map((driver) => driver.label)).toContain(
+ "4 of 4 have not read it in 30 days"
+ );
+ });
+
+ test("drops the unused-access driver when the tracked period is too short to give it a point", () => {
+ const exposure = calculateExposureScore({ entitledCount: 1, unreadCount: 1, ghostReaderCount: 0 }, 0.4);
+ expect(exposure.drivers.map((driver) => driver.kind)).toEqual([SecretExposureDriver.Readers]);
+ expect(pointsOf(exposure)).toBe(exposure.score);
+ });
});
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.ts
index cb0d3f1fd5..563282c54a 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
@@ -141,12 +141,23 @@ const pluralize = (count: number, singular: string, plural: string) => `${count}
// 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 => {
+// prototype's proportions for the same three terms, rescaled to add up to 100. `trackedDays` is how much of
+// the window the reads cover: the unused-access term is weighted by it, since three days without a read is
+// weak evidence next to thirty, and its label says which period it is judged on.
+export const calculateExposureScore = (
+ { entitledCount, unreadCount, ghostReaderCount }: TSecretExposureCounts,
+ trackedDays = SECRET_READ_ACTIVITY_WINDOW_DAYS
+): TSecretExposure => {
+ const coverage = clamp01(trackedDays / SECRET_READ_ACTIVITY_WINDOW_DAYS);
+ const trackedWholeDays = Math.floor(Math.min(trackedDays, SECRET_READ_ACTIVITY_WINDOW_DAYS));
+ let period = `in ${SECRET_READ_ACTIVITY_WINDOW_DAYS} days`;
+ if (coverage < 1) {
+ period =
+ trackedWholeDays < 1
+ ? "since tracking began today"
+ : `in the ${pluralize(trackedWholeDays, "day", "days")} tracked`;
+ }
+
const terms = [
{
kind: SecretExposureDriver.Readers,
@@ -162,8 +173,8 @@ export const calculateExposureScore = ({
},
{
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`
+ points: 25 * coverage * (entitledCount ? unreadCount / entitledCount : 0),
+ label: `${unreadCount} of ${entitledCount} ${unreadCount === 1 ? "has" : "have"} not read it ${period}`
}
];
const score = Math.round(terms.reduce((total, term) => total + term.points, 0));
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.ts
index 440ac3bb73..d6fec172a5 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
@@ -40,31 +40,28 @@ import {
import { TSecretReadActivityQueueServiceFactory } from "./secret-read-activity-queue";
import {
SecretExposureBand,
+ TEntitledReader,
TExposedSecret,
TGetSecretReadActivityDTO,
TListSecretExposureDTO,
- TListUnusedSecretAccessDTO,
TReachSecret,
TReadActivityScope,
TSecretExposureCounts,
TSecretLocation,
TSecretReach,
TSecretReachGraph,
- TSecretReaderType,
- TUnusedSecretAccess
+ TSecretReaderType
} from "./secret-read-activity-types";
-const UNUSED_SECRET_ACCESS_CACHE_TTL_SECONDS = 30;
+const SECRET_EXPOSURE_CACHE_TTL_SECONDS = 30;
const REACH_YIELD_INTERVAL = 100;
// Longer than a computation can take, so the lock is not lost mid-scan; waiters give up well before a request times out.
-const UNUSED_SECRET_ACCESS_COMPUTE_LOCK_TTL_MS = 5 * 60 * 1000;
-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 };
+const SECRET_EXPOSURE_COMPUTE_LOCK_TTL_MS = 5 * 60 * 1000;
+const SECRET_EXPOSURE_COMPUTE_WAIT_SECONDS = 60;
+// A large project can have hundreds of thousands of secrets, so only the highest-scoring ones are cached and
+// listed, about 250 KB per project; the per-band tally still covers them all.
+const SECRET_EXPOSURE_MAX_LISTED = 500;
+
type TCachedExposedSecret = TExposedSecret & { secretId: string };
type TSecretPermission = Parameters<typeof hasSecretReadValueOrDescribePermission>[0];
@@ -285,6 +282,8 @@ export const secretReadActivityServiceFactory = ({
$getProjectTrackingStartedAt(projectId)
]);
const judgedFrom = trackingStartedAt > windowStart ? trackingStartedAt : windowStart;
+ // How much of the window the reads cover, which weights the score's unused-access term and words it.
+ const trackedDays = (Date.now() - judgedFrom.getTime()) / DAY_IN_MS;
const actors = [
...userPermissions.map((actor) => ({ ...actor, actorType: ActorType.USER as const })),
...identityPermissions.map((actor) => ({ ...actor, actorType: ActorType.IDENTITY as const }))
@@ -316,14 +315,13 @@ export const secretReadActivityServiceFactory = ({
entitled,
unread,
ghostReaders,
- exposure: calculateExposureScore({
- entitledCount: entitled.length,
- unreadCount: unread.length,
- ghostReaderCount: ghostReaders.length
- })
+ exposure: calculateExposureScore(
+ { entitledCount: entitled.length, unreadCount: unread.length, ghostReaderCount: ghostReaders.length },
+ trackedDays
+ )
};
};
- return { summarize, actorNames };
+ return { summarize, actorNames, judgedFrom, trackedDays, accessChangedAtByActorId, adminActorIds };
};
const getSecretReadActivity = async (
@@ -355,16 +353,18 @@ export const secretReadActivityServiceFactory = ({
});
const windowStart = getReadActivityWindowStart();
- const [[activity], { summarize, actorNames }] = await Promise.all([
- $getReadActivity({ projectId, windowStart, secret: { environment, secretPath, secretName }, tree }),
- $loadSecretSummarizer(projectId, actor.orgId, windowStart)
- ]);
+ const [[activity], { summarize, actorNames, judgedFrom, accessChangedAtByActorId, adminActorIds }] =
+ 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}'`
});
}
const { entitled, unread, ghostReaders, exposure } = summarize(activity);
+ const unreadKeys = new Set(unread.map((reader) => `${reader.actorType}:${reader.id}`));
// 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.
@@ -381,7 +381,17 @@ export const secretReadActivityServiceFactory = ({
return {
trackedSince: activity.trackedSince,
+ judgedFrom,
reads: [...activity.reads.values()],
+ entitled: entitled.map(
+ (reader): TEntitledReader => ({
+ actorType: reader.actorType,
+ actorId: reader.id,
+ unread: unreadKeys.has(`${reader.actorType}:${reader.id}`),
+ isAdmin: adminActorIds.has(reader.id),
+ accessChangedAt: accessChangedAtByActorId.get(reader.id) ?? null
+ })
+ ),
entitledCount: entitled.length,
unreadCount: unread.length,
ghostReaderCount: ghostReaders.length,
@@ -393,17 +403,15 @@ export const secretReadActivityServiceFactory = ({
};
};
- // 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, and the secrets with the highest exposure score.
- const $computeUnusedSecretAccess = async (projectId: string, orgId: string) => {
+ // Every secret's exposure, keeping the highest-scoring ones and a tally of how many fall in each band.
+ const $computeProjectExposure = async (projectId: string, orgId: string) => {
const windowStart = getReadActivityWindowStart();
- const [activities, { summarize }] = await Promise.all([
+ const [activities, { summarize, trackedDays }] = await Promise.all([
$getReadActivity({ projectId, windowStart }),
$loadSecretSummarizer(projectId, orgId, windowStart)
]);
- // 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.
+ // Only counts and the score are kept for every secret; the listed ones are built from them afterwards.
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) {
@@ -423,29 +431,9 @@ export const secretReadActivityServiceFactory = ({
bands[exposure.band] += 1;
}
- const rows: TCachedUnusedSecretAccess[] = [];
- 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,
- environment: activity.environment,
- secretPath: activity.secretPath,
- actorType: actor.actorType,
- actorId: actor.id,
- actorName: actor.name,
- entitledCount: summary.entitledCount,
- unreadCount: summary.unreadCount,
- ghostReaderCount: summary.ghostReaderCount
- })
- );
- }
-
- const mostExposed = [...summaries]
- .filter((summary) => summary.score > 0)
- .sort((a, b) => b.score - a.score)
+ // A secret scoring 0 has nobody who can read it, so there is nothing to list.
+ const scored = summaries.filter((summary) => summary.score > 0).sort((a, b) => b.score - a.score);
+ const mostExposed = scored
.slice(0, SECRET_EXPOSURE_MAX_LISTED)
.map(({ activityIndex, score, ...counts }): TCachedExposedSecret => {
const activity = activities[activityIndex];
@@ -455,53 +443,47 @@ export const secretReadActivityServiceFactory = ({
environment: activity.environment,
secretPath: activity.secretPath,
...counts,
- exposure: calculateExposureScore(counts)
+ exposure: calculateExposureScore(counts, trackedDays)
};
});
- return {
- rows: rows.slice(0, UNUSED_SECRET_ACCESS_MAX_LISTED),
- totalCount: summaries.reduce((total, { unreadCount }) => total + unreadCount, 0),
- mostExposed,
- bands
- };
+ return { mostExposed, bands, scoredCount: scored.length };
};
// Requests on a cold cache, on any instance, wait for the one computing the project and read what it cached
// instead of each scanning the project. If the wait runs out, the request computes it itself.
- const $computeUnusedSecretAccessShared = async (projectId: string, orgId: string, cacheKey: string) => {
+ const $computeProjectExposureShared = async (projectId: string, orgId: string, cacheKey: string) => {
let lock: Awaited<ReturnType<typeof keyStore.acquireLock>> | undefined;
try {
lock = await keyStore.acquireLock(
- [KeyStorePrefixes.SecretReadActivityUnusedAccessLock(projectId)],
- UNUSED_SECRET_ACCESS_COMPUTE_LOCK_TTL_MS,
- { retryCount: UNUSED_SECRET_ACCESS_COMPUTE_WAIT_SECONDS, retryDelay: 1000 }
+ [KeyStorePrefixes.SecretReadActivityExposureLock(projectId)],
+ SECRET_EXPOSURE_COMPUTE_LOCK_TTL_MS,
+ { retryCount: SECRET_EXPOSURE_COMPUTE_WAIT_SECONDS, retryDelay: 1000 }
);
} catch {
lock = undefined;
}
try {
const cached = lock ? await keyStore.getItem(cacheKey) : null;
- if (cached) return JSON.parse(cached) as Awaited<ReturnType<typeof $computeUnusedSecretAccess>>;
+ if (cached) return JSON.parse(cached) as Awaited<ReturnType<typeof $computeProjectExposure>>;
- const result = await $computeUnusedSecretAccess(projectId, orgId);
+ const result = await $computeProjectExposure(projectId, orgId);
// Written before the lock is released, so the next request in line finds it.
- await keyStore.setItemWithExpiry(cacheKey, UNUSED_SECRET_ACCESS_CACHE_TTL_SECONDS, JSON.stringify(result));
+ await keyStore.setItemWithExpiry(cacheKey, SECRET_EXPOSURE_CACHE_TTL_SECONDS, JSON.stringify(result));
return result;
} finally {
await lock?.release();
}
};
- // 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");
+ // The whole project is computed once a day and cached, so paging through it is cheap.
+ const $getCachedProjectExposure = async (projectId: string, orgId: string) => {
+ const cacheKey = KeyStorePrefixes.InsightsCache(projectId, "secret-exposure");
const summary = await withCache({
keyStore,
key: cacheKey,
- ttlSeconds: UNUSED_SECRET_ACCESS_CACHE_TTL_SECONDS,
- fetcher: () => $computeUnusedSecretAccessShared(projectId, orgId, cacheKey)
+ ttlSeconds: SECRET_EXPOSURE_CACHE_TTL_SECONDS,
+ fetcher: () => $computeProjectExposureShared(projectId, orgId, cacheKey)
});
const [remainingTTL, { project, trackingStartedAt }] = await Promise.all([
getCacheTtl(keyStore, cacheKey),
@@ -545,57 +527,34 @@ export const secretReadActivityServiceFactory = ({
return visible;
};
- const listUnusedSecretAccess = async (
- { projectId, offset, limit, orderBy, orderDirection }: TListUnusedSecretAccessDTO,
+ const listSecretExposure = async (
+ { projectId, offset, limit, orderBy, orderDirection }: TListSecretExposureDTO,
actor: OrgServiceActor
) => {
const { permission } = await checkInsightsReadPermission(permissionService, projectId, actor);
- const { rows, totalCount, ...tracking } = await $getCachedProjectSummary(projectId, actor.orgId);
+ const { mostExposed, bands, scoredCount, ...tracking } = await $getCachedProjectExposure(projectId, actor.orgId);
const visibleSecrets = await $loadVisibleSecrets(
projectId,
permission,
- rows.map((row) => row.secretId)
+ mostExposed.map((secret) => secret.secretId)
);
- const visibleRows = rows.flatMap(({ secretId, ...row }): TUnusedSecretAccess[] => {
+ const visible = mostExposed.flatMap(({ secretId, ...row }): TExposedSecret[] => {
const secret = visibleSecrets.get(secretId);
return secret ? [{ ...row, ...secret }] : [];
});
// Unsorted, the list keeps its ranking. The sort is stable, so ties keep it too.
const sorted = orderBy
- ? [...visibleRows].sort((a, b) => {
+ ? [...visible].sort((a, b) => {
const [first, second] = orderDirection === OrderByDirection.DESC ? [b, a] : [a, b];
return first[orderBy].localeCompare(second[orderBy]);
})
- : visibleRows;
-
- return {
- unusedAccess: sorted.slice(offset, offset + limit),
- totalCount: visibleRows.length,
- unlistedCount: totalCount - rows.length,
- 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 }] : [];
- });
+ : visible;
return {
- secrets: visible.slice(offset, offset + limit),
+ secrets: sorted.slice(offset, offset + limit),
totalCount: visible.length,
+ unlistedCount: scoredCount - mostExposed.length,
bands,
projectName: tracking.projectName,
trackingStartedAt: tracking.trackingStartedAt,
@@ -608,7 +567,6 @@ export const secretReadActivityServiceFactory = ({
recordRead: secretReadActivityQueue.recordRead,
recordBulkRead: secretReadActivityQueue.recordBulkRead,
getSecretReadActivity,
- 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.ts
index 8450c6f3be..322326b630 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
@@ -127,15 +127,6 @@ export type TSecretExposure = {
drivers: TSecretExposureDriver[];
};
-export type TUnusedSecretAccess = TSecretExposureCounts & {
- secretKey: string;
- environment: string;
- secretPath: string;
- actorType: TSecretReaderType;
- actorId: string;
- actorName: string;
-};
-
export type TExposedSecret = TSecretExposureCounts & {
secretKey: string;
environment: string;
@@ -143,24 +134,27 @@ export type TExposedSecret = TSecretExposureCounts & {
exposure: TSecretExposure;
};
-export type TListSecretExposureDTO = {
- projectId: string;
- offset: number;
- limit: number;
+// A reader who can read the value today, and whether they count as unused access: no read, with the secret and
+// their access both older than the judged period. When they do not, the other fields say why.
+export type TEntitledReader = {
+ actorType: TSecretReaderType;
+ actorId: string;
+ unread: boolean;
+ isAdmin: boolean;
+ accessChangedAt: Date | null;
};
// Each value is the row field it sorts by.
-export enum UnusedSecretAccessOrderBy {
+export enum SecretExposureOrderBy {
SecretKey = "secretKey",
Environment = "environment",
- SecretPath = "secretPath",
- Actor = "actorName"
+ SecretPath = "secretPath"
}
-export type TListUnusedSecretAccessDTO = {
+export type TListSecretExposureDTO = {
projectId: string;
offset: number;
limit: number;
- orderBy?: UnusedSecretAccessOrderBy;
+ orderBy?: SecretExposureOrderBy;
orderDirection: OrderByDirection;
};
diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.ts
index 2c70efba1d..f3d9ed05b2 100644
--- a/backend/src/keystore/keystore.ts
+++ b/backend/src/keystore/keystore.ts
@@ -234,8 +234,7 @@ export const KeyStorePrefixes = {
`secret-read-activity:${day}:${actorId}:${scope}` as const,
SecretReadActivityStream: "secret-read-activity-stream" as const,
SecretReadActivityConsumerLock: "secret-read-activity:consumer-lock" as const,
- SecretReadActivityUnusedAccessLock: (projectId: string) =>
- `secret-read-activity:unused-access-lock:${projectId}` as const,
+ SecretReadActivityExposureLock: (projectId: string) => `secret-read-activity:exposure-lock:${projectId}` as const,
AuditLogIngestConsumerLock: "audit-log-ingest:consumer-lock" as const,
// period is a YYYY-MM stamp so the monthly notice can only go out once per org per month
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index c34e74f0e1..c31e09383f 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -947,42 +947,26 @@ export const INSIGHTS = {
totalProjects: "The total number of secret management projects in the organization.",
projectsWithIssues: "The number of secret management projects in the organization with at least one issue."
},
- GET_UNUSED_SECRET_ACCESS: {
- projectId: "The ID of the project to list unused secret access for.",
- offset: "The number of entries to skip before returning results.",
- limit: "The maximum number of entries to return per page.",
- orderBy: "The field to sort by. Without it, the secrets with the most unused access come first.",
- orderDirection: "The direction to sort in.",
- totalCount:
- "The number of entries the caller can page through: those of the top 1,000 in secrets the caller can see.",
- unlistedCount:
- "The number of further entries with less unused access that are not listed, counted across the whole project before the caller's permissions are applied. Zero unless the project has more than 1,000.",
- 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 results first cover the full 30 days. Until then they are preliminary: they cover only the reads since tracking started, and the access that existed when it started.",
- unusedAccess:
- "One entry for each secret and user or machine identity, other than project admins, that can read the secret's value but has not read it, or an import or reference of it, in the last 30 days. Secrets and access newer than 30 days are left out.",
- secretKey: "The key of the secret.",
- environment: "The slug of the environment the secret is in.",
- 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."
- },
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.",
+ orderBy: "The field to sort by. Without it, the most exposed secrets come first.",
+ orderDirection: "The direction to sort in.",
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.",
+ "The secrets with the highest exposure score: those of the top 500 in the project that the caller can see. Secrets scoring 0, which nobody can read, are not listed.",
+ secretKey: "The key of the secret.",
+ environment: "The slug of the environment the secret is in.",
+ secretPath: "The path of the folder the secret is in.",
totalCount: "The number of secrets the caller can page through.",
+ unlistedCount:
+ "The number of further scored secrets that are not listed, counted across the whole project before the caller's permissions are applied. Zero unless the project has more than 500.",
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."
+ "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 then, and weighs less in the score the shorter that period is."
},
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.",
@@ -1515,6 +1499,16 @@ export const RAW_SECRETS = {
secretPath: "The folder path where the secret is located.",
trackedSince:
"The start of the period reads are reported for: the later of 30 days ago, when read tracking began, and when the secret and its folder were created.",
+ judgedFrom:
+ "The start of the period unused access is judged on: the later of 30 days ago and when read tracking began for the project. A reader only counts as unused access once the secret and their access both predate it.",
+ entitled:
+ "One entry for each user or machine identity that can read the secret's value today, admins included, saying whether they count as unused access and, if not, why.",
+ unread:
+ "Whether the reader counts as unused access: no read since trackedSince, with the secret and their access both older than judgedFrom.",
+ isAdmin:
+ "Whether the reader is a project admin. Admins can read everything by design, so they never count as unused access.",
+ accessChangedAt:
+ "When the reader's access to the project last changed: the latest membership, role or privilege creation, edit or expiry. Null when it has never changed since the membership was created, or is unknown.",
reads:
"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.",
diff --git a/frontend/src/components/secrets/SecretAccessGraph/SecretAccessGraph.tsx b/frontend/src/components/secrets/SecretAccessGraph/SecretAccessGraph.tsx
index 390f9cf55d..c0847b685d 100644
--- a/frontend/src/components/secrets/SecretAccessGraph/SecretAccessGraph.tsx
+++ b/frontend/src/components/secrets/SecretAccessGraph/SecretAccessGraph.tsx
@@ -12,6 +12,7 @@ import {
useNodesState,
useReactFlow
} from "@xyflow/react";
+import { format } from "date-fns";
import { MaximizeIcon, MinusIcon, PlusIcon } from "lucide-react";
import { IconButton } from "@app/components/v3";
@@ -179,7 +180,7 @@ export const SecretAccessGraph = ({ input }: Props) => (
</div>
<p className="text-xs text-muted">
{input.hasReadActivity
- ? `Solid lines are reads in the last ${input.windowDays} days, dashed lines are access with no reads. Select a reader or group to follow its path.`
+ ? `Solid lines are reads since ${input.trackedSince ? format(new Date(input.trackedSince), "PP") : "tracking began"}, dashed lines are access with no reads yet. Select a reader or group to follow its path.`
: "Read activity is not visible for your role, so the lines only show who can read the value. Select a reader or group to follow its path."}
</p>
</ReactFlowProvider>
diff --git a/frontend/src/components/secrets/SecretAccessGraph/buildAccessGraph.test.ts b/frontend/src/components/secrets/SecretAccessGraph/buildAccessGraph.test.ts
index 31cf827271..eec51a4bcb 100644
--- a/frontend/src/components/secrets/SecretAccessGraph/buildAccessGraph.test.ts
+++ b/frontend/src/components/secrets/SecretAccessGraph/buildAccessGraph.test.ts
@@ -19,7 +19,15 @@ const input: TAccessGraphInput = {
groupIds: [],
lastReadAt: "2026-10-18T00:00:00.000Z"
},
- { id: "ci", name: "ci", type: "identity", isDirect: false, groupIds: ["devs"] },
+ {
+ id: "ci",
+ name: "ci",
+ type: "identity",
+ isDirect: false,
+ groupIds: ["devs"],
+ unreadSince: "2026-09-19T00:00:00.000Z"
+ },
+ { id: "newcomer", name: "newcomer", type: "identity", isDirect: true, groupIds: [] },
{
id: "bob",
@@ -32,7 +40,7 @@ const input: TAccessGraphInput = {
groups: [{ id: "devs", name: "devs", memberCount: 2 }],
ghosts: [{ id: "gone", name: null, type: "identity", lastReadAt: "2026-10-10T00:00:00.000Z" }],
hasReadActivity: true,
- windowDays: 30
+ trackedSince: "2026-09-19T00:00:00.000Z"
};
describe("buildAccessGraph", () => {
@@ -53,13 +61,13 @@ describe("buildAccessGraph", () => {
);
});
- test("puts the readers with no reads first", () => {
+ test("puts unused access first, then readers too new to judge, then the ones who have read", () => {
const readerYs = input.readers.map((entry) => [
entry.id,
nodeById.get(readerNodeId(entry))!.position.y
]);
const sorted = [...readerYs].sort((a, b) => Number(a[1]) - Number(b[1])).map(([id]) => id);
- expect(sorted).toEqual(["ci", "alice", "bob"]);
+ expect(sorted).toEqual(["ci", "newcomer", "alice", "bob"]);
});
test("connects direct readers to the secret and group-only readers through their group", () => {
diff --git a/frontend/src/components/secrets/SecretAccessGraph/buildAccessGraph.ts b/frontend/src/components/secrets/SecretAccessGraph/buildAccessGraph.ts
index e23842ea7c..bc8715e86d 100644
--- a/frontend/src/components/secrets/SecretAccessGraph/buildAccessGraph.ts
+++ b/frontend/src/components/secrets/SecretAccessGraph/buildAccessGraph.ts
@@ -12,6 +12,9 @@ export type TAccessGraphReader = {
isDirect: boolean;
groupIds: string[];
lastReadAt?: string;
+ // Set when the reader counts as unused access: no read since this date, with the secret and their access
+ // both older than the judged period. A reader with neither this nor a read is too new to judge.
+ unreadSince?: string;
};
export type TAccessGraphGroup = {
@@ -42,14 +45,14 @@ export type TAccessGraphInput = {
ghosts: TAccessGraphGhost[];
// False when the viewer cannot see read activity, so no edge claims a read or its absence.
hasReadActivity: boolean;
- windowDays: number;
+ trackedSince?: string;
};
export type TReaderNodeData = {
reader: TAccessGraphReader;
groupNames: string[];
hasReadActivity: boolean;
- windowDays: number;
+ trackedSince?: string;
};
export type TGroupNodeData = { group: TAccessGraphGroup };
@@ -117,18 +120,21 @@ export const buildAccessGraph = ({
groups,
ghosts,
hasReadActivity,
- windowDays
+ trackedSince
}: TAccessGraphInput) => {
const nodes: Node[] = [];
const edges: Edge[] = [];
- // The ones with no reads come first: they are what the viewer is here to find.
- const orderedReaders = [...readers].sort((a, b) => {
- if (hasReadActivity && Boolean(a.lastReadAt) !== Boolean(b.lastReadAt)) {
- return a.lastReadAt ? 1 : -1;
- }
- return a.name.localeCompare(b.name);
- });
+ // Unused access first, then readers too new to judge, then the ones who have read: the first group is what
+ // the viewer is here to find.
+ const rankOf = (reader: TAccessGraphReader) => {
+ if (!hasReadActivity) return 0;
+ if (reader.lastReadAt) return 2;
+ return reader.unreadSince ? 0 : 1;
+ };
+ const orderedReaders = [...readers].sort(
+ (a, b) => rankOf(a) - rankOf(b) || a.name.localeCompare(b.name)
+ );
const groupById = new Map(groups.map((group) => [group.id, group]));
const secretColumnX = MARGIN + (NODE_WIDTH + COLUMN_GAP) * (groups.length ? 2 : 1);
@@ -179,7 +185,7 @@ export const buildAccessGraph = ({
reader,
groupNames: viaGroups.map((group) => group.name),
hasReadActivity,
- windowDays
+ trackedSince
} satisfies TReaderNodeData
});
diff --git a/frontend/src/components/secrets/SecretAccessGraph/nodes.tsx b/frontend/src/components/secrets/SecretAccessGraph/nodes.tsx
index 2233464da3..606a149a0e 100644
--- a/frontend/src/components/secrets/SecretAccessGraph/nodes.tsx
+++ b/frontend/src/components/secrets/SecretAccessGraph/nodes.tsx
@@ -1,4 +1,5 @@
import { Handle, NodeProps, Position } from "@xyflow/react";
+import { format } from "date-fns";
import { SecretExposureBadge } from "@app/components/secrets/SecretExposureScore";
import { formatReadDay } from "@app/components/secrets/SecretReadStatusBadge";
@@ -21,14 +22,25 @@ const TYPE_LABEL: Record<TAccessGraphActorType, string> = {
const hiddenHandle = "!opacity-0";
export const ReaderNode = ({ data }: NodeProps & { data: TReaderNodeData }) => {
- const { reader, groupNames, hasReadActivity, windowDays } = data;
+ const { reader, groupNames, hasReadActivity } = data;
const hasReads = Boolean(reader.lastReadAt);
- let status: string | undefined;
+ // Three states once read activity is known: read, unused access, or too new to judge.
+ let status: { text: string; tone: string } | undefined;
if (hasReadActivity) {
- status = reader.lastReadAt
- ? `Read ${formatReadDay(reader.lastReadAt).toLowerCase()}`
- : `No reads in ${windowDays} days`;
+ if (reader.lastReadAt) {
+ status = {
+ text: `Read ${formatReadDay(reader.lastReadAt).toLowerCase()}`,
+ tone: "text-accent"
+ };
+ } else if (reader.unreadSince) {
+ status = {
+ text: `No reads since ${format(new Date(reader.unreadSince), "MMM d")}`,
+ tone: "text-warning"
+ };
+ } else {
+ status = { text: "No reads yet, too new to judge", tone: "text-muted" };
+ }
}
return (
@@ -51,11 +63,7 @@ export const ReaderNode = ({ data }: NodeProps & { data: TReaderNodeData }) => {
</p>
<span className="shrink-0 text-xs text-muted">{TYPE_LABEL[reader.type]}</span>
</div>
- {status && (
- <span className={cn("truncate text-xs", hasReads ? "text-accent" : "text-warning")}>
- {status}
- </span>
- )}
+ {status && <span className={cn("truncate text-xs", status.tone)}>{status.text}</span>}
<span className="mt-auto truncate text-xs text-muted">
{groupNames.length ? `Via ${groupNames.join(", ")}` : "Direct access"}
</span>
diff --git a/frontend/src/components/secrets/SecretExposureScore.tsx b/frontend/src/components/secrets/SecretExposureScore.tsx
index 153febe989..649555b5bf 100644
--- a/frontend/src/components/secrets/SecretExposureScore.tsx
+++ b/frontend/src/components/secrets/SecretExposureScore.tsx
@@ -135,7 +135,8 @@ export const SecretExposurePanel = ({ exposure, className }: PanelProps) => {
)}
<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.
+ and 25 for the share who have not read it in the tracked period, which counts in full once
+ that period is 30 days.
</p>
</div>
</div>
diff --git a/frontend/src/components/secrets/SecretReadStatusBadge.tsx b/frontend/src/components/secrets/SecretReadStatusBadge.tsx
index 38f2613f34..1ec4fdd209 100644
--- a/frontend/src/components/secrets/SecretReadStatusBadge.tsx
+++ b/frontend/src/components/secrets/SecretReadStatusBadge.tsx
@@ -1,9 +1,16 @@
-import { differenceInCalendarDays } from "date-fns";
+import { differenceInCalendarDays, format } from "date-fns";
-import { Badge } from "@app/components/v3";
+import { Badge, Tooltip, TooltipContent, TooltipTrigger } from "@app/components/v3";
+
+// What a reader's row says about their reads. A reader with no read is "unused access" only once the secret
+// and their access have both existed for the whole judged period; before that it is too early to say.
+export type TReaderReadStatus =
+ | { kind: "read"; lastReadAt: string }
+ | { kind: "unread"; since: string }
+ | { kind: "pending"; reason: string };
type Props = {
- lastReadAt?: string;
+ status: TReaderReadStatus;
};
// Only a reader's first read of the day is recorded, so the time of day would understate later reads.
@@ -14,9 +21,26 @@ export const formatReadDay = (lastReadAt: string) => {
return `${days} days ago`;
};
-export const SecretReadStatusBadge = ({ lastReadAt }: Props) => {
- if (lastReadAt) {
- return <span>{formatReadDay(lastReadAt)}</span>;
+export const SecretReadStatusBadge = ({ status }: Props) => {
+ if (status.kind === "read") {
+ return <span>{formatReadDay(status.lastReadAt)}</span>;
+ }
+ if (status.kind === "unread") {
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Badge variant="warning">No Reads</Badge>
+ </TooltipTrigger>
+ <TooltipContent>No reads since {format(new Date(status.since), "PP")}</TooltipContent>
+ </Tooltip>
+ );
}
- return <Badge variant="warning">No Reads</Badge>;
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Badge variant="neutral">No Reads Yet</Badge>
+ </TooltipTrigger>
+ <TooltipContent className="max-w-72">{status.reason}</TooltipContent>
+ </Tooltip>
+ );
};
diff --git a/frontend/src/hooks/api/auditLogs/constants.tsx b/frontend/src/hooks/api/auditLogs/constants.tsx
index 9d91b42858..7473a26112 100644
--- a/frontend/src/hooks/api/auditLogs/constants.tsx
+++ b/frontend/src/hooks/api/auditLogs/constants.tsx
@@ -301,8 +301,6 @@ export const eventToNameMap: { [K in EventType]: string } = {
"View Secrets Management Calendar Insights",
[EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_ACCESS_VOLUME]:
"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]:
diff --git a/frontend/src/hooks/api/auditLogs/enums.tsx b/frontend/src/hooks/api/auditLogs/enums.tsx
index 889d260f70..4278c5d176 100644
--- a/frontend/src/hooks/api/auditLogs/enums.tsx
+++ b/frontend/src/hooks/api/auditLogs/enums.tsx
@@ -294,7 +294,6 @@ 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",
diff --git a/frontend/src/hooks/api/secretInsights/index.ts b/frontend/src/hooks/api/secretInsights/index.ts
index 9c9999699d..fd2c92a691 100644
--- a/frontend/src/hooks/api/secretInsights/index.ts
+++ b/frontend/src/hooks/api/secretInsights/index.ts
@@ -15,8 +15,7 @@ export {
useGetSecretAccessVolume,
useGetSecretBlindIndexStatus,
useGetSecretExposure,
- useGetSecretsDuplication,
- useGetUnusedSecretAccess
+ useGetSecretsDuplication
} from "./queries";
export type {
TAccessLocation,
@@ -41,8 +40,6 @@ export type {
TGetSecretExposureResponse,
TGetSecretsDuplicationDTO,
TGetSecretsDuplicationResponse,
- TGetUnusedSecretAccessDTO,
- TGetUnusedSecretAccessResponse,
TOrgAuthMethodUsage,
TOrgDuplicatedSecretEntry,
TOrgDuplicatedSecretGroup,
@@ -57,7 +54,6 @@ export type {
TSecretAccessVolumeDay,
TSecretExposure,
TSecretExposureCounts,
- TSecretValueMatch,
- TUnusedSecretAccess
+ TSecretValueMatch
} from "./types";
-export { SecretExposureBand, SecretExposureDriver, UnusedSecretAccessOrderBy } from "./types";
+export { SecretExposureBand, SecretExposureDriver, SecretExposureOrderBy } from "./types";
diff --git a/frontend/src/hooks/api/secretInsights/queries.tsx b/frontend/src/hooks/api/secretInsights/queries.tsx
index 7ceae65fc6..682eb2722a 100644
--- a/frontend/src/hooks/api/secretInsights/queries.tsx
+++ b/frontend/src/hooks/api/secretInsights/queries.tsx
@@ -24,8 +24,6 @@ import {
TGetSecretExposureResponse,
TGetSecretsDuplicationDTO,
TGetSecretsDuplicationResponse,
- TGetUnusedSecretAccessDTO,
- TGetUnusedSecretAccessResponse,
TOrgAuthMethodUsage,
TOrgProjectsInsights,
TOrgSecretAccessVolume,
@@ -39,8 +37,6 @@ export const secretInsightsKeys = {
[...secretInsightsKeys.all(), "calendar-events", params] as const,
accessVolume: (params: TGetSecretAccessVolumeDTO) =>
[...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) =>
@@ -131,36 +127,6 @@ export const useGetSecretAccessVolume = (
});
};
-export const useGetUnusedSecretAccess = (
- params: TGetUnusedSecretAccessDTO,
- options?: Omit<
- UseQueryOptions<
- TGetUnusedSecretAccessResponse,
- unknown,
- TGetUnusedSecretAccessResponse,
- ReturnType<typeof secretInsightsKeys.unusedSecretAccess>
- >,
- "queryKey" | "queryFn"
- >
-) => {
- return useQuery({
- queryKey: secretInsightsKeys.unusedSecretAccess(params),
- queryFn: async () => {
- const { projectId, ...query } = params;
- const res = await apiRequest.get<Omit<TGetUnusedSecretAccessResponse, "remainingTtl">>(
- `/api/v1/insights/${projectId}/secrets/unused-access`,
- { 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
- });
-};
-
export const useGetSecretExposure = (
params: TGetSecretExposureDTO,
options?: Omit<
diff --git a/frontend/src/hooks/api/secretInsights/types.ts b/frontend/src/hooks/api/secretInsights/types.ts
index 642d5fdf6d..fca213b2c3 100644
--- a/frontend/src/hooks/api/secretInsights/types.ts
+++ b/frontend/src/hooks/api/secretInsights/types.ts
@@ -52,21 +52,6 @@ export type TGetSecretAccessVolumeDTO = {
projectId: string;
};
-export enum UnusedSecretAccessOrderBy {
- SecretKey = "secretKey",
- Environment = "environment",
- SecretPath = "secretPath",
- Actor = "actorName"
-}
-
-export type TGetUnusedSecretAccessDTO = {
- projectId: string;
- offset: number;
- limit: number;
- orderBy?: UnusedSecretAccessOrderBy;
- orderDirection?: OrderByDirection;
-};
-
// 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 = {
@@ -95,28 +80,18 @@ export type TSecretExposure = {
drivers: { kind: SecretExposureDriver; points: number; label: string }[];
};
-export type TUnusedSecretAccess = TSecretExposureCounts & {
- secretKey: string;
- environment: string;
- secretPath: string;
- actorType: "user" | "identity";
- actorId: string;
- actorName: string;
-};
-
-export type TGetUnusedSecretAccessResponse = {
- unusedAccess: TUnusedSecretAccess[];
- totalCount: number;
- unlistedCount: number;
- trackingStartedAt: string;
- preliminaryUntil: string;
- remainingTtl: number;
-};
+export enum SecretExposureOrderBy {
+ SecretKey = "secretKey",
+ Environment = "environment",
+ SecretPath = "secretPath"
+}
export type TGetSecretExposureDTO = {
projectId: string;
offset: number;
limit: number;
+ orderBy?: SecretExposureOrderBy;
+ orderDirection?: OrderByDirection;
};
export type TExposedSecret = TSecretExposureCounts & {
@@ -129,6 +104,7 @@ export type TExposedSecret = TSecretExposureCounts & {
export type TGetSecretExposureResponse = {
secrets: TExposedSecret[];
totalCount: number;
+ unlistedCount: number;
bands: Record<SecretExposureBand, number>;
trackingStartedAt: string;
preliminaryUntil: string;
diff --git a/frontend/src/hooks/api/secrets/types.ts b/frontend/src/hooks/api/secrets/types.ts
index b192d78153..d3b02f8000 100644
--- a/frontend/src/hooks/api/secrets/types.ts
+++ b/frontend/src/hooks/api/secrets/types.ts
@@ -165,11 +165,21 @@ export type TGetSecretReadActivityDTO = Omit<TGetSecretAccessListDTO, "includeAl
export type TSecretReadActivity = TSecretExposureCounts & {
trackedSince: string;
+ // The start of the period unused access is judged on; a reader counts only once the secret and their
+ // access both predate it.
+ judgedFrom: string;
reads: {
actorType: "user" | "identity";
actorId: string;
lastReadAt: string;
}[];
+ entitled: {
+ actorType: "user" | "identity";
+ actorId: string;
+ unread: boolean;
+ isAdmin: boolean;
+ accessChangedAt: string | null;
+ }[];
exposure: TSecretExposure;
ghostReaders: {
actorType: "user" | "identity";
diff --git a/frontend/src/pages/secret-manager/InsightsPage/InsightsPage.tsx b/frontend/src/pages/secret-manager/InsightsPage/InsightsPage.tsx
index 2db6262abe..5e8261deb8 100644
--- a/frontend/src/pages/secret-manager/InsightsPage/InsightsPage.tsx
+++ b/frontend/src/pages/secret-manager/InsightsPage/InsightsPage.tsx
@@ -34,8 +34,7 @@ import {
DuplicatedSecretsCard,
InsightsSummaryCards,
SecretAccessChart,
- SecretExposureCard,
- UnusedSecretAccessCard
+ SecretExposureCard
} from "./components";
export const InsightsPage = withProjectPermission(
@@ -140,9 +139,6 @@ export const InsightsPage = withProjectPermission(
<div className="mt-6">
<SecretExposureCard />
</div>
- <div className="mt-6">
- <UnusedSecretAccessCard />
- </div>
<div className="mt-6 grid items-start gap-6 xl:grid-cols-[1.3fr_1fr]">
<div className="flex flex-col gap-6">
<DuplicatedSecretsCard />
diff --git a/frontend/src/pages/secret-manager/InsightsPage/components/SecretExposureCard.tsx b/frontend/src/pages/secret-manager/InsightsPage/components/SecretExposureCard.tsx
index 11ea0148e4..67641394db 100644
--- a/frontend/src/pages/secret-manager/InsightsPage/components/SecretExposureCard.tsx
+++ b/frontend/src/pages/secret-manager/InsightsPage/components/SecretExposureCard.tsx
@@ -2,7 +2,7 @@ import { useState } from "react";
import { useParams } from "@tanstack/react-router";
import axios from "axios";
import { format } from "date-fns";
-import { FolderIcon, InfoIcon, KeyIcon } from "lucide-react";
+import { ChevronDownIcon, FolderIcon, InfoIcon, KeyIcon } from "lucide-react";
import { GoToSecretButton } from "@app/components/secrets/GoToSecretButton";
import {
@@ -12,6 +12,9 @@ import {
SecretExposureBadge
} from "@app/components/secrets/SecretExposureScore";
import {
+ Alert,
+ AlertDescription,
+ AlertTitle,
Badge,
Card,
CardContent,
@@ -36,6 +39,7 @@ import {
TableHead,
TableHeader,
TableRow,
+ type TableSortDirection,
Tooltip,
TooltipContent,
TooltipTrigger
@@ -43,27 +47,80 @@ import {
import { cn } from "@app/components/v3/utils";
import { useProject, useSubscription } from "@app/context";
import { usePagination, useResetPageHelper } from "@app/hooks";
-import { TExposedSecret, useGetSecretExposure } from "@app/hooks/api/secretInsights";
+import { OrderByDirection } from "@app/hooks/api/generic/types";
+import {
+ SecretExposureOrderBy,
+ TExposedSecret,
+ useGetSecretExposure
+} from "@app/hooks/api/secretInsights";
import { SecretAccessInsights } from "@app/pages/secret-manager/OverviewPage/components/SecretTableRow/SecretAccessInsights";
+const formatRemainingTtl = (seconds: number) => {
+ if (seconds < 60) {
+ const remainingSeconds = Math.max(1, seconds);
+ return `${remainingSeconds} ${remainingSeconds === 1 ? "second" : "seconds"}`;
+ }
+ if (seconds < 60 * 60) {
+ const minutes = Math.ceil(seconds / 60);
+ return `${minutes} ${minutes === 1 ? "minute" : "minutes"}`;
+ }
+ const hours = Math.ceil(seconds / (60 * 60));
+ return `${hours} ${hours === 1 ? "hour" : "hours"}`;
+};
+
+// The period the counts are judged on: the full window once tracking is that old, else since it began.
+const describeReadPeriod = (trackingStartedAt: string, isPreliminary: boolean) =>
+ isPreliminary ? `since ${format(new Date(trackingStartedAt), "PP")}` : "in the last 30 days";
+
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
- });
+ // An empty orderBy keeps the default ranking: the most exposed secrets first.
+ const {
+ page,
+ setPage,
+ perPage,
+ setPerPage,
+ offset,
+ limit,
+ orderBy,
+ setOrderBy,
+ orderDirection,
+ setOrderDirection
+ } = usePagination<SecretExposureOrderBy | "">("", { initPerPage: 10 });
const [selectedSecret, setSelectedSecret] = useState<TExposedSecret | null>(null);
const { data, isPending, error } = useGetSecretExposure(
- { projectId, offset, limit },
+ { projectId, offset, limit, orderBy: orderBy || undefined, orderDirection },
{ enabled: Boolean(subscription?.secretAccessInsights) }
);
const totalCount = data?.totalCount ?? 0;
useResetPageHelper({ totalCount, offset, setPage });
+ const updatesIn =
+ data?.remainingTtl != null && data.remainingTtl >= 0
+ ? formatRemainingTtl(data.remainingTtl)
+ : null;
const environmentNames = new Map(currentProject.environments.map((env) => [env.slug, env.name]));
+ const getSortDirection = (column: SecretExposureOrderBy): TableSortDirection => {
+ if (orderBy !== column) return "none";
+ return orderDirection === OrderByDirection.DESC ? "descending" : "ascending";
+ };
+
+ const handleSort = (column: SecretExposureOrderBy, direction: TableSortDirection) => {
+ setPage(1);
+ setOrderBy(direction === "none" ? "" : column);
+ setOrderDirection(direction === "descending" ? OrderByDirection.DESC : OrderByDirection.ASC);
+ };
+
+ const sortableColumns = [
+ { column: SecretExposureOrderBy.SecretKey, label: "Secret Key" },
+ { column: SecretExposureOrderBy.Environment, label: "Environment" },
+ { column: SecretExposureOrderBy.SecretPath, label: "Path" }
+ ];
+
const renderBody = () => {
if (isPending) return <Skeleton className="h-[200px] w-full" />;
@@ -83,6 +140,7 @@ export const SecretExposureCard = () => {
}
const isPreliminary = new Date(data.preliminaryUntil) > new Date();
+ const readPeriod = describeReadPeriod(data.trackingStartedAt, isPreliminary);
// Descending, so the band that needs attention first reads first.
const bandSummary = [...EXPOSURE_BANDS].reverse();
@@ -101,12 +159,16 @@ export const SecretExposureCard = () => {
))}
</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>
+ <Alert variant="info" className="mb-4">
+ <InfoIcon />
+ <AlertTitle>Preliminary Results</AlertTitle>
+ <AlertDescription>
+ Unused access is judged over 30 days of reads. Tracking for this project began on{" "}
+ {format(new Date(data.trackingStartedAt), "PP")}, so for now it covers only the reads
+ since then and weighs less in the score. Results are complete on{" "}
+ {format(new Date(data.preliminaryUntil), "PP")}.
+ </AlertDescription>
+ </Alert>
)}
{totalCount === 0 ? (
<Empty className="border">
@@ -120,9 +182,22 @@ export const SecretExposureCard = () => {
<Table>
<TableHeader>
<TableRow>
- <TableHead>Secret Key</TableHead>
- <TableHead>Environment</TableHead>
- <TableHead>Path</TableHead>
+ {sortableColumns.map(({ column, label }) => (
+ <TableHead
+ key={column}
+ sortDirection={getSortDirection(column)}
+ onSortChange={(direction) => handleSort(column, direction)}
+ >
+ {label}
+ <ChevronDownIcon
+ className={cn(
+ "transition-transform",
+ getSortDirection(column) === "descending" && "rotate-180",
+ getSortDirection(column) === "none" && "opacity-30"
+ )}
+ />
+ </TableHead>
+ ))}
<TableHead className="whitespace-nowrap">Exposure</TableHead>
<TableHead className="whitespace-nowrap">Readers</TableHead>
<TableHead className="whitespace-nowrap">No Reads</TableHead>
@@ -192,8 +267,8 @@ export const SecretExposureCard = () => {
</span>
</TooltipTrigger>
<TooltipContent>
- {row.unreadCount} of the {row.entitledCount} who can read this secret have
- not read it in the last 30 days
+ {row.unreadCount} of the {row.entitledCount} who can read this secret,
+ project admins aside, have not read it {readPeriod}
</TooltipContent>
</Tooltip>
</TableCell>
@@ -204,8 +279,8 @@ export const SecretExposureCard = () => {
<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.
+ {row.ghostReaderCount} read this secret {readPeriod} but can no longer
+ access it. They still know the value.
</TooltipContent>
</Tooltip>
) : (
@@ -233,6 +308,12 @@ export const SecretExposureCard = () => {
onChangePage={setPage}
onChangePerPage={setPerPage}
/>
+ {data.unlistedCount > 0 && (
+ <p className="mt-2 text-xs text-muted">
+ Showing the {totalCount.toLocaleString()} most exposed secrets.{" "}
+ {data.unlistedCount.toLocaleString()} more are not listed.
+ </p>
+ )}
</>
)}
</>
@@ -243,11 +324,18 @@ export const SecretExposureCard = () => {
<>
<Card>
<CardHeader>
- <CardTitle>Secret Exposure</CardTitle>
+ <CardTitle>
+ Secret Exposure
+ {updatesIn && (
+ <Badge variant="neutral" className="ml-2 font-normal">
+ Updates in {updatesIn}
+ </Badge>
+ )}
+ </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. Select a secret to see why
- it scores what it does.
+ Which secrets are most exposed, from how many can read the value, who can no longer read
+ it but still knows it, and who can read it but never does. Select a secret to see why it
+ scores what it does and who is behind each count.
</CardDescription>
</CardHeader>
<CardContent>{renderBody()}</CardContent>
diff --git a/frontend/src/pages/secret-manager/InsightsPage/components/UnusedSecretAccessCard.tsx b/frontend/src/pages/secret-manager/InsightsPage/components/UnusedSecretAccessCard.tsx
deleted file mode 100644
index 3e9c233824..0000000000
--- a/frontend/src/pages/secret-manager/InsightsPage/components/UnusedSecretAccessCard.tsx
+++ /dev/null
@@ -1,297 +0,0 @@
-import { useParams } from "@tanstack/react-router";
-import axios from "axios";
-import { format } from "date-fns";
-import {
- ChevronDownIcon,
- FolderIcon,
- HardDriveIcon,
- InfoIcon,
- KeyIcon,
- UserIcon
-} from "lucide-react";
-
-import { GoToSecretButton } from "@app/components/secrets/GoToSecretButton";
-import {
- Alert,
- AlertDescription,
- AlertTitle,
- Badge,
- Card,
- CardContent,
- CardDescription,
- CardHeader,
- CardTitle,
- Empty,
- EmptyDescription,
- EmptyHeader,
- EmptyTitle,
- Pagination,
- Skeleton,
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
- type TableSortDirection,
- 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 { OrderByDirection } from "@app/hooks/api/generic/types";
-import { UnusedSecretAccessOrderBy, useGetUnusedSecretAccess } from "@app/hooks/api/secretInsights";
-
-const formatRemainingTtl = (seconds: number) => {
- if (seconds < 60) {
- const remainingSeconds = Math.max(1, seconds);
- return `${remainingSeconds} ${remainingSeconds === 1 ? "second" : "seconds"}`;
- }
- if (seconds < 60 * 60) {
- const minutes = Math.ceil(seconds / 60);
- return `${minutes} ${minutes === 1 ? "minute" : "minutes"}`;
- }
- const hours = Math.ceil(seconds / (60 * 60));
- return `${hours} ${hours === 1 ? "hour" : "hours"}`;
-};
-
-export const UnusedSecretAccessCard = () => {
- const { currentProject, projectId } = useProject();
- const { orgId } = useParams({ strict: false });
- const { subscription } = useSubscription();
- // An empty orderBy keeps the default ranking: the secrets with the most unused access first.
- const {
- page,
- setPage,
- perPage,
- setPerPage,
- offset,
- limit,
- orderBy,
- setOrderBy,
- orderDirection,
- setOrderDirection
- } = usePagination<UnusedSecretAccessOrderBy | "">("", { initPerPage: 20 });
-
- const { data, isPending, error } = useGetUnusedSecretAccess(
- { projectId, offset, limit, orderBy: orderBy || undefined, orderDirection },
- { enabled: Boolean(subscription?.secretAccessInsights) }
- );
- const totalCount = data?.totalCount ?? 0;
- useResetPageHelper({ totalCount, offset, setPage });
-
- const updatesIn =
- data?.remainingTtl != null && data.remainingTtl >= 0
- ? formatRemainingTtl(data.remainingTtl)
- : null;
- const environmentNames = new Map(currentProject.environments.map((env) => [env.slug, env.name]));
-
- const getSortDirection = (column: UnusedSecretAccessOrderBy): TableSortDirection => {
- if (orderBy !== column) return "none";
- return orderDirection === OrderByDirection.DESC ? "descending" : "ascending";
- };
-
- const handleSort = (column: UnusedSecretAccessOrderBy, direction: TableSortDirection) => {
- setPage(1);
- setOrderBy(direction === "none" ? "" : column);
- setOrderDirection(direction === "descending" ? OrderByDirection.DESC : OrderByDirection.ASC);
- };
-
- const sortableColumns = [
- { column: UnusedSecretAccessOrderBy.SecretKey, label: "Secret Key" },
- { column: UnusedSecretAccessOrderBy.Environment, label: "Environment" },
- { column: UnusedSecretAccessOrderBy.SecretPath, label: "Path" },
- { column: UnusedSecretAccessOrderBy.Actor, label: "Name" }
- ];
-
- const renderBody = () => {
- if (isPending) return <Skeleton className="h-[200px] w-full" />;
-
- if (!data) {
- return (
- <Empty className="border">
- <EmptyHeader>
- <EmptyTitle>Could not load unused access</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();
- const preliminaryNotice = isPreliminary && (
- <Alert variant="info" className="mb-4">
- <InfoIcon />
- <AlertTitle>Preliminary Results</AlertTitle>
- <AlertDescription>
- Unused access is measured over 30 days of reads. Tracking for this project began on{" "}
- {format(new Date(data.trackingStartedAt), "PP")}, so these results cover a shorter period
- and will be complete on {format(new Date(data.preliminaryUntil), "PP")}.
- </AlertDescription>
- </Alert>
- );
-
- if (totalCount === 0) {
- return (
- <>
- {preliminaryNotice}
- <Empty className="border">
- <EmptyHeader>
- <EmptyTitle>
- {isPreliminary ? "No unused access so far" : "No unused access"}
- </EmptyTitle>
- <EmptyDescription>
- {isPreliminary
- ? "Everyone who could read these secrets when tracking began has read them since."
- : "Access shows here once someone has been able to read a secret for 30 days without reading it."}
- </EmptyDescription>
- </EmptyHeader>
- </Empty>
- </>
- );
- }
-
- return (
- <>
- {preliminaryNotice}
- <Table>
- <TableHeader>
- <TableRow>
- {sortableColumns.map(({ column, label }) => (
- <TableHead
- key={column}
- sortDirection={getSortDirection(column)}
- onSortChange={(direction) => handleSort(column, direction)}
- >
- {label}
- <ChevronDownIcon
- className={cn(
- "transition-transform",
- getSortDirection(column) === "descending" && "rotate-180",
- getSortDirection(column) === "none" && "opacity-30"
- )}
- />
- </TableHead>
- ))}
- <TableHead className="whitespace-nowrap">No Reads</TableHead>
- <TableHead className="whitespace-nowrap">Ghost Readers</TableHead>
- <TableHead variant="action" />
- </TableRow>
- </TableHeader>
- <TableBody>
- {data.unusedAccess.map((row) => {
- const ActorIcon = row.actorType === "user" ? UserIcon : HardDriveIcon;
- return (
- <TableRow
- key={`${row.environment}-${row.secretPath}-${row.secretKey}-${row.actorType}-${row.actorId}`}
- 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 isTruncatable className="max-w-60">
- <div className="flex items-center gap-2">
- <ActorIcon className="size-4 shrink-0 text-accent" />
- <span className="truncate">{row.actorName}</span>
- </div>
- </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}
- />
- {data.unlistedCount > 0 && (
- <p className="mt-2 text-xs text-muted">
- Showing the {totalCount.toLocaleString()} entries with the most unused access.{" "}
- {data.unlistedCount.toLocaleString()} more are not listed.
- </p>
- )}
- </>
- );
- };
-
- return (
- <Card>
- <CardHeader>
- <CardTitle>
- Unused Secret Access
- {updatesIn && (
- <Badge variant="neutral" className="ml-2 font-normal">
- Updates in {updatesIn}
- </Badge>
- )}
- </CardTitle>
- <CardDescription>
- Users and machine identities, other than project admins, that can read a secret but have
- not read it in the last 30 days
- </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.ts
index fc9c698bd3..96dba6d882 100644
--- a/frontend/src/pages/secret-manager/InsightsPage/components/index.ts
+++ b/frontend/src/pages/secret-manager/InsightsPage/components/index.ts
@@ -8,5 +8,4 @@ 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.tsx
index 8a75371428..01c5eeb5a3 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/SecretAccessInsights.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/SecretAccessInsights.tsx
@@ -24,7 +24,10 @@ import {
import { createNotification } from "@app/components/notifications";
import { SecretAccessGraph, TAccessGraphInput } from "@app/components/secrets/SecretAccessGraph";
import { SecretExposurePanel } from "@app/components/secrets/SecretExposureScore";
-import { SecretReadStatusBadge } from "@app/components/secrets/SecretReadStatusBadge";
+import {
+ SecretReadStatusBadge,
+ TReaderReadStatus
+} from "@app/components/secrets/SecretReadStatusBadge";
import {
Button,
ButtonGroup,
@@ -109,8 +112,6 @@ type Props = {
type AccessView = "graph" | "table";
-const READ_ACTIVITY_WINDOW_DAYS = 30;
-
const grantsReadValue = (actions: Iterable<string>) =>
[...actions].some(
(action) =>
@@ -507,6 +508,45 @@ export function SecretAccessInsights({
() => new Map(readActivity?.reads.map((read) => [`${read.actorType}:${read.actorId}`, read])),
[readActivity]
);
+ const entitledReaders = useMemo(
+ () =>
+ new Map(
+ readActivity?.entitled.map((reader) => [`${reader.actorType}:${reader.actorId}`, reader])
+ ),
+ [readActivity]
+ );
+
+ // What a reader's row and node say about their reads. "No reads" is only claimed once the secret and the
+ // reader's access have both existed for the whole judged period; before that the reason is spelled out.
+ const readStatusOf = (type: "user" | "identity", id: string): TReaderReadStatus | undefined => {
+ if (!readActivity) return undefined;
+ const key = `${type}:${id}`;
+ const lastReadAt = lastReads.get(key)?.lastReadAt;
+ if (lastReadAt) return { kind: "read", lastReadAt };
+ const reader = entitledReaders.get(key);
+ if (reader?.unread) return { kind: "unread", since: readActivity.trackedSince };
+ if (reader?.isAdmin) {
+ return {
+ kind: "pending",
+ reason:
+ "Project admins can read everything by design, so they are not counted as unused access."
+ };
+ }
+ const judgedFrom = new Date(readActivity.judgedFrom);
+ if (reader?.accessChangedAt && new Date(reader.accessChangedAt) > judgedFrom) {
+ return {
+ kind: "pending",
+ reason: `Their access changed on ${format(new Date(reader.accessChangedAt), "PP")}, so they have not had the whole tracked period to read it.`
+ };
+ }
+ if (new Date(readActivity.trackedSince) > judgedFrom) {
+ return {
+ kind: "pending",
+ reason: `The secret has only been tracked since ${format(new Date(readActivity.trackedSince), "PP")}, so nobody has had the whole period to read it.`
+ };
+ }
+ return { kind: "pending", reason: "Not counted as unused access." };
+ };
let readActivityDescription = "Loading read activity...";
if (readActivityError) {
@@ -533,6 +573,7 @@ export function SecretAccessInsights({
.filter((group) => group[memberField].includes(entry.id))
.map((group) => group.id);
if (!isDirect && !groupIds.length) return [];
+ const status = readStatusOf(type, entry.id);
return [
{
id: entry.id,
@@ -540,7 +581,8 @@ export function SecretAccessInsights({
type,
isDirect,
groupIds,
- lastReadAt: lastReads.get(`${type}:${entry.id}`)?.lastReadAt
+ lastReadAt: status?.kind === "read" ? status.lastReadAt : undefined,
+ unreadSince: status?.kind === "unread" ? status.since : undefined
}
];
};
@@ -570,11 +612,14 @@ export function SecretAccessInsights({
lastReadAt: ghost.lastReadAt
})),
hasReadActivity: Boolean(canReadInsights && readActivity),
- windowDays: READ_ACTIVITY_WINDOW_DAYS
+ trackedSince: readActivity?.trackedSince
};
+ // readStatusOf only reads readActivity, lastReads and entitledReaders, which are all listed.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
}, [
secretAccessList,
lastReads,
+ entitledReaders,
readActivity,
canReadInsights,
secretKey,
@@ -591,13 +636,10 @@ export function SecretAccessInsights({
]);
if (!canReadValue) return null;
if (isReadActivityLoading) return <Skeleton className="h-4 w-20 rounded" />;
- if (!readActivity) return null;
+ const status = readStatusOf(row.type, row.entry.id);
+ if (!status) return null;
- return (
- <SecretReadStatusBadge
- lastReadAt={lastReads.get(`${row.type}:${row.entry.id}`)?.lastReadAt}
- />
- );
+ return <SecretReadStatusBadge status={status} />;
};
const flatRows = useMemo<AccessRow[]>(() => {
@@ -1062,7 +1104,9 @@ export function SecretAccessInsights({
)}
</TableCell>
<TableCell className="w-40 whitespace-nowrap">
- <SecretReadStatusBadge lastReadAt={reader.lastReadAt} />
+ <SecretReadStatusBadge
+ status={{ kind: "read", lastReadAt: reader.lastReadAt }}
+ />
</TableCell>
</TableRow>
);