Skip to content

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

refactor(insights): move secret read activity under insights and make the APIs easier to read

Dimitris Staratzis75b153a12163
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.md
index a526ee308f..150a502424 100644
--- a/backend/CLAUDE.md
+++ b/backend/CLAUDE.md
@@ -1142,8 +1142,8 @@ owns the two read endpoints and hands `recordRead` / `recordBulkRead` through to
decrypts every secret that could reference it.
- **The card judges a full window, or everything since tracking began.** Tracking starts at the later of the
migration that created the table and the project's creation. In a project tracked for less than 30 days, the
- window starts when tracking did (`judgedFrom`), and the response's `fullWindowFrom` says when results first
- cover 30 days, so the UI words the period "since <date>" until then. The card leaves out project admins (users
+ window starts when tracking did (`judgedFrom`). The card's responses carry it as `periodStart`, stored with the
+ cached computation, so the UI words the period "since <date>" while it is under 30 days old. The card leaves out project admins (users
and identities with the Admin role, directly or through a group, from `findAdminActorIds`): they can read
everything by design. Their reads are still recorded, so the access sheet's Last Read stays true for them. A
pair is listed once the secret (`trackedSince`) and the actor's access (`findAccessChangedAt`: the latest
@@ -1151,18 +1151,19 @@ owns the two read endpoints and hands `recordRead` / `recordBulkRead` through to
change opened up is not recorded, so any access change restarts the window, including an edit to the rules of
a custom role the reader holds. The per-secret sheet shows the plain fact
instead: a read, "No reads", or "No reads yet" with the reason.
-- **The access sheet.** The graph lives only in the secret's access sheet (`GET /secrets/:name/read-activity`).
- That 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), plus three counts: `entitledCount`
- (non-admins who can read the value today), `unreadCount` (those among them counted as unused access) and
- `ghostReaderCount`. It also returns the ghost readers (readers in the window who can no longer read it, named
- from the project's members, else from the user or identity row, else null), which the UI does not show.
+- **The access sheet.** The graph lives only in the secret's access sheet, served by
+ `GET /insights/:projectId/secrets/read-activity/:secretName` (the fixed segment comes first so a secret named
+ `reports` or `summary` cannot hit those routes). It returns `actors`: everyone who can read the value, admins
+ included, each with `lastReadAt`, `isProjectAdmin`, `accessChangedAt`, and a `readStatus` (`read`, `unused`,
+ `not-judged`) with a `notJudgedReason` (`project-admin`, `access-changed`, `secret-too-new`) from
+ `getReadStatus`. The API returns codes and dates only; the UI writes the wording. Readers who lost access
+ ("ghost readers") are not computed or returned.
- **The Insights card is per actor** (a user or machine identity; a group is never a row, only an access path).
- `summarizeSecretAccess` (in `secret-read-activity-fns.ts`) is the one place a secret's readers, unread readers and
- ghost readers are derived, from the project's access loaded once by `$loadProjectAccess`; both the per-secret
+ `summarizeSecretAccess` (in `secret-read-activity-fns.ts`) is the one place a secret's readers and unread readers
+ are derived, from the project's access loaded once by `$loadProjectAccess`; both the per-secret
endpoint and the project scan use it. `$tallyUnusedAccess` scans every secret once and tallies, per actor, how many
- secrets it can read, how many it has not read, the environments involved and its latest read; `$computeUnusedAccess`
- ranks the tallies into rows. Each row carries `accessPaths` as data: `roles` it holds directly (`id`/`slug`/`name`,
+ secrets it can read, how many it has not read and the environments involved; `$computeUnusedAccess`
+ ranks the tallies into rows (`accessibleSecretCount`, `unusedSecretCount`). Each row carries `accessPaths` as data: `roles` it holds directly (`id`/`slug`/`name`,
where a custom role has the slug `custom` and its own id), `groups` it belongs to with the roles each one gives,
and `additionalPrivileges` as `id`/`name`; the UI decides how to label them. Custom role ids and names come from
`getProjectPermissions`, so the scan makes no role lookup of its own. Group members are checked with the group's
diff --git a/backend/src/ee/routes/v1/insights-router.ts b/backend/src/ee/routes/v1/insights-router.ts
index ecabf1ffc6..1adeced44b 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,
+ SecretReadActivitySchema,
SecretsProjectsSchema,
SecretsSummarySchema,
StaticSecretsUsageSchema,
@@ -24,7 +25,9 @@ import {
UnusedAccessSchema
} from "@app/ee/services/insights/insights-schemas";
import { INSIGHTS } from "@app/lib/api-docs";
+import { prefixWithSlash, removeTrailingSlash } from "@app/lib/fn";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
+import { BaseSecretNameSchema } from "@app/server/lib/schemas";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { ActorType, AuthMode } from "@app/services/auth/auth-type";
@@ -492,7 +495,7 @@ export const registerInsightsRouter = async (server: FastifyZodProvider) => {
onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),
handler: async (req, reply) => {
const { projectId } = req.params;
- const { actors, totalCount, trackingStartedAt, fullWindowFrom, remainingTTL, projectName } =
+ const { actors, totalCount, periodStart, remainingTTL, projectName } =
await server.services.secretReadActivity.listUnusedAccess({ projectId, ...req.query }, req.permission);
await server.services.auditLog.createAuditLog({
projectId,
@@ -506,7 +509,7 @@ export const registerInsightsRouter = async (server: FastifyZodProvider) => {
if (remainingTTL && remainingTTL >= 0) {
void reply.header("X-Cache-TTL", remainingTTL);
}
- return { actors, totalCount, trackingStartedAt, fullWindowFrom };
+ return { actors, totalCount, periodStart };
}
});
@@ -530,7 +533,7 @@ export const registerInsightsRouter = async (server: FastifyZodProvider) => {
onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),
handler: async (req, reply) => {
const { projectId, actorType, actorId } = req.params;
- const { actor, secrets, unlistedCount, trackingStartedAt, fullWindowFrom, remainingTTL, projectName } =
+ const { actor, secrets, periodStart, remainingTTL, projectName } =
await server.services.secretReadActivity.getUnusedAccessActor(
{ projectId, actorType, actorId },
req.permission
@@ -553,7 +556,47 @@ export const registerInsightsRouter = async (server: FastifyZodProvider) => {
if (remainingTTL && remainingTTL >= 0) {
void reply.header("X-Cache-TTL", remainingTTL);
}
- return { actor, secrets, unlistedCount, trackingStartedAt, fullWindowFrom };
+ return { actor, secrets, periodStart };
+ }
+ });
+
+ // The fixed segment comes before the secret name, so a secret named like another route here (reports, summary)
+ // cannot be routed to it.
+ server.route({
+ method: "GET",
+ url: "/:projectId/secrets/read-activity/:secretName",
+ config: { rateLimit: readLimit },
+ schema: {
+ operationId: "getInsightsSecretReadActivity",
+ description:
+ "List the users and machine identities that can read a secret's value, with each one's latest read and whether it counts as unused access",
+ security: [{ bearerAuth: [] }],
+ params: z.object({
+ projectId: z.string().trim().max(36).describe(INSIGHTS.GET_SECRET_READ_ACTIVITY.projectId),
+ secretName: BaseSecretNameSchema.max(500).describe(INSIGHTS.GET_SECRET_READ_ACTIVITY.secretName)
+ }),
+ querystring: z.object({
+ environment: z.string().trim().min(1).max(255).describe(INSIGHTS.GET_SECRET_READ_ACTIVITY.environment),
+ secretPath: z
+ .string()
+ .trim()
+ .max(1024)
+ .default("/")
+ .transform(prefixWithSlash)
+ .transform(removeTrailingSlash)
+ .describe(INSIGHTS.GET_SECRET_READ_ACTIVITY.secretPath)
+ }),
+ response: {
+ 200: z.object({ readActivity: SecretReadActivitySchema })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),
+ handler: async (req) => {
+ const readActivity = await server.services.secretReadActivity.getSecretReadActivity(
+ { projectId: req.params.projectId, secretName: req.params.secretName, ...req.query },
+ req.permission
+ );
+ return { readActivity };
}
});
diff --git a/backend/src/ee/routes/v1/secret-router.ts b/backend/src/ee/routes/v1/secret-router.ts
index 9d03955310..cb4059f01c 100644
--- a/backend/src/ee/routes/v1/secret-router.ts
+++ b/backend/src/ee/routes/v1/secret-router.ts
@@ -2,11 +2,10 @@ import z from "zod";
import { ProjectPermissionSecretActions } from "@app/ee/services/permission/project-permission";
import { RAW_SECRETS } from "@app/lib/api-docs";
-import { prefixWithSlash, removeTrailingSlash } from "@app/lib/fn";
+import { removeTrailingSlash } from "@app/lib/fn";
import { readLimit } from "@app/server/config/rateLimiter";
-import { BaseSecretNameSchema } from "@app/server/lib/schemas";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
-import { ActorType, AuthMode } from "@app/services/auth/auth-type";
+import { AuthMode } from "@app/services/auth/auth-type";
const AccessListEntrySchema = z.object({
allowedActions: z.nativeEnum(ProjectPermissionSecretActions).array(),
@@ -76,89 +75,4 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {
});
}
});
-
- server.route({
- method: "GET",
- url: "/:secretName/read-activity",
- config: {
- rateLimit: readLimit
- },
- schema: {
- operationId: "getSecretReadActivity",
- description: "Get which users and machine identities have recently read a secret",
- security: [
- {
- bearerAuth: []
- }
- ],
- params: z.object({
- secretName: BaseSecretNameSchema.max(500).describe(RAW_SECRETS.GET_READ_ACTIVITY.secretName)
- }),
- querystring: z.object({
- projectId: z.string().trim().max(36).describe(RAW_SECRETS.GET_READ_ACTIVITY.projectId),
- environment: z.string().trim().min(1).max(255).describe(RAW_SECRETS.GET_READ_ACTIVITY.environment),
- secretPath: z
- .string()
- .trim()
- .max(1024)
- .default("/")
- .transform(prefixWithSlash)
- .transform(removeTrailingSlash)
- .describe(RAW_SECRETS.GET_READ_ACTIVITY.secretPath)
- }),
- response: {
- 200: z.object({
- 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
- .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),
- 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),
- actorName: z.string().nullable().describe(RAW_SECRETS.GET_READ_ACTIVITY.readerName),
- 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),
- entitledCount: z.number().int().describe(RAW_SECRETS.GET_READ_ACTIVITY.entitledCount),
- unreadCount: z.number().int().describe(RAW_SECRETS.GET_READ_ACTIVITY.unreadCount),
- ghostReaderCount: z.number().int().describe(RAW_SECRETS.GET_READ_ACTIVITY.ghostReaderCount),
- 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)
- })
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),
- handler: async (req) => {
- const readActivity = await server.services.secretReadActivity.getSecretReadActivity(
- { ...req.query, secretName: req.params.secretName },
- req.permission
- );
- return { readActivity };
- }
- });
};
diff --git a/backend/src/ee/services/insights/insights-schemas.ts b/backend/src/ee/services/insights/insights-schemas.ts
index 5682bd40c4..b6d970bc7b 100644
--- a/backend/src/ee/services/insights/insights-schemas.ts
+++ b/backend/src/ee/services/insights/insights-schemas.ts
@@ -1,6 +1,10 @@
import { z } from "zod";
import { IdentityAuthMethod } from "@app/db/schemas";
+import {
+ SecretReadNotJudgedReason,
+ SecretReadStatus
+} 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";
@@ -77,10 +81,9 @@ const UnusedAccessActorRowSchema = z.object({
actorType: z.enum([ActorType.USER, ActorType.IDENTITY]).describe(INSIGHTS.GET_UNUSED_ACCESS.actorType),
actorId: z.string().describe(INSIGHTS.GET_UNUSED_ACCESS.actorId),
name: z.string().describe(INSIGHTS.GET_UNUSED_ACCESS.name),
- entitledCount: z.number().int().describe(INSIGHTS.GET_UNUSED_ACCESS.entitledCount),
- unreadCount: z.number().int().describe(INSIGHTS.GET_UNUSED_ACCESS.unreadCount),
+ accessibleSecretCount: z.number().int().describe(INSIGHTS.GET_UNUSED_ACCESS.accessibleSecretCount),
+ unusedSecretCount: z.number().int().describe(INSIGHTS.GET_UNUSED_ACCESS.unusedSecretCount),
environments: z.string().array().describe(INSIGHTS.GET_UNUSED_ACCESS.environments),
- lastReadAt: z.date().nullable().describe(INSIGHTS.GET_UNUSED_ACCESS.lastReadAt),
accessPaths: z
.object({
roles: UnusedAccessRoleSchema.array().describe(INSIGHTS.GET_UNUSED_ACCESS.roles),
@@ -105,16 +108,13 @@ const UnusedAccessActorRowSchema = z.object({
export const UnusedAccessSchema = z.object({
totalCount: z.number().int().describe(INSIGHTS.GET_UNUSED_ACCESS.totalCount),
- trackingStartedAt: z.date().describe(INSIGHTS.GET_UNUSED_ACCESS.trackingStartedAt),
- fullWindowFrom: z.date().describe(INSIGHTS.GET_UNUSED_ACCESS.fullWindowFrom),
+ periodStart: z.date().describe(INSIGHTS.GET_UNUSED_ACCESS.periodStart),
actors: UnusedAccessActorRowSchema.array().describe(INSIGHTS.GET_UNUSED_ACCESS.actors)
});
export const UnusedAccessActorSchema = z.object({
actor: UnusedAccessActorRowSchema,
- unlistedCount: z.number().int().describe(INSIGHTS.GET_UNUSED_ACCESS_ACTOR.unlistedCount),
- trackingStartedAt: z.date().describe(INSIGHTS.GET_UNUSED_ACCESS.trackingStartedAt),
- fullWindowFrom: z.date().describe(INSIGHTS.GET_UNUSED_ACCESS.fullWindowFrom),
+ periodStart: z.date().describe(INSIGHTS.GET_UNUSED_ACCESS.periodStart),
secrets: z
.object({
secretKey: z.string().describe(INSIGHTS.GET_UNUSED_ACCESS_ACTOR.secretKey),
@@ -124,3 +124,24 @@ export const UnusedAccessActorSchema = z.object({
.array()
.describe(INSIGHTS.GET_UNUSED_ACCESS_ACTOR.secrets)
});
+
+export const SecretReadActivitySchema = z.object({
+ readsTrackedSince: z.date().describe(INSIGHTS.GET_SECRET_READ_ACTIVITY.readsTrackedSince),
+ unusedAccessJudgedFrom: z.date().describe(INSIGHTS.GET_SECRET_READ_ACTIVITY.unusedAccessJudgedFrom),
+ actors: z
+ .object({
+ actorType: z.enum([ActorType.USER, ActorType.IDENTITY]).describe(INSIGHTS.GET_SECRET_READ_ACTIVITY.actorType),
+ actorId: z.string().describe(INSIGHTS.GET_SECRET_READ_ACTIVITY.actorId),
+ name: z.string().describe(INSIGHTS.GET_SECRET_READ_ACTIVITY.name),
+ isProjectAdmin: z.boolean().describe(INSIGHTS.GET_SECRET_READ_ACTIVITY.isProjectAdmin),
+ lastReadAt: z.date().nullable().describe(INSIGHTS.GET_SECRET_READ_ACTIVITY.lastReadAt),
+ accessChangedAt: z.date().nullable().describe(INSIGHTS.GET_SECRET_READ_ACTIVITY.accessChangedAt),
+ readStatus: z.nativeEnum(SecretReadStatus).describe(INSIGHTS.GET_SECRET_READ_ACTIVITY.readStatus),
+ notJudgedReason: z
+ .nativeEnum(SecretReadNotJudgedReason)
+ .nullable()
+ .describe(INSIGHTS.GET_SECRET_READ_ACTIVITY.notJudgedReason)
+ })
+ .array()
+ .describe(INSIGHTS.GET_SECRET_READ_ACTIVITY.actors)
+});
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 5734d7da22..ab5c5bb58e 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
@@ -13,6 +13,7 @@ import {
classifySecretReads,
computeSecretReach,
coversWholeWindow,
+ getReadStatus,
getUtcMonthStart,
indexSecretReads,
summarizeSecretAccess,
@@ -20,7 +21,9 @@ import {
toUnusedAccessRoles
} from "./secret-read-activity-fns";
import {
+ SecretReadNotJudgedReason,
SecretReadObjectType,
+ SecretReadStatus,
TProjectAccess,
TReachSecret,
TSecretActivity,
@@ -180,15 +183,14 @@ describe("summarizeSecretAccess", () => {
expect(ids(summary.entitled)).toEqual(["direct", "via-group"]);
});
- test("leaves admins out of unused access, and never counts their reads as a ghost's", () => {
+ test("leaves admins out of unused access", () => {
const summary = summarizeSecretAccess(
- activity({ reads: readBy("admin") }),
+ activity(),
access({ readersByRules: [[reader("admin"), reader("direct")]], adminActorIds: new Set(["admin"]) })
);
expect(ids(summary.entitled)).toEqual(["admin", "direct"]);
expect(ids(summary.nonAdmins)).toEqual(["direct"]);
expect(ids(summary.unread)).toEqual(["direct"]);
- expect(summary.ghostReaders).toEqual([]);
});
test("does not count a reader who read it, or whose access changed inside the judged period", () => {
@@ -203,10 +205,44 @@ describe("summarizeSecretAccess", () => {
const summary = summarizeSecretAccess(activity({ trackedSince: new Date("2026-10-01T00:00:00.000Z") }), access());
expect(summary.unread).toEqual([]);
});
+});
+
+describe("getReadStatus", () => {
+ const judgedFrom = new Date("2026-09-15T00:00:00.000Z");
+ const status = (overrides: Partial<Parameters<typeof getReadStatus>[0]> = {}) =>
+ getReadStatus({
+ lastReadAt: null,
+ isUnused: false,
+ isProjectAdmin: false,
+ accessChangedAt: null,
+ judgedFrom,
+ ...overrides
+ });
+
+ test("is read for anyone with a read, admins included", () => {
+ const hasRead = { readStatus: SecretReadStatus.Read, notJudgedReason: null };
+ expect(status({ lastReadAt: new Date("2026-10-01T00:00:00.000Z") })).toEqual(hasRead);
+ expect(status({ lastReadAt: new Date("2026-10-01T00:00:00.000Z"), isProjectAdmin: true })).toEqual(hasRead);
+ });
- test("counts a read by someone who can no longer read it as a ghost's", () => {
- const summary = summarizeSecretAccess(activity({ reads: readBy("no-access") }), access());
- expect(ids(summary.ghostReaders)).toEqual(["no-access"]);
+ test("is unused for a reader counted as unused access", () => {
+ expect(status({ isUnused: true })).toEqual({ readStatus: SecretReadStatus.Unused, notJudgedReason: null });
+ });
+
+ test("names why a reader without a read is not judged", () => {
+ const notJudged = (notJudgedReason: SecretReadNotJudgedReason) => ({
+ readStatus: SecretReadStatus.NotJudged,
+ notJudgedReason
+ });
+ expect(status({ isProjectAdmin: true, accessChangedAt: new Date("2026-10-01T00:00:00.000Z") })).toEqual(
+ notJudged(SecretReadNotJudgedReason.ProjectAdmin)
+ );
+ expect(status({ accessChangedAt: new Date("2026-10-01T00:00:00.000Z") })).toEqual(
+ notJudged(SecretReadNotJudgedReason.AccessChanged)
+ );
+ expect(status({ accessChangedAt: new Date("2026-09-01T00:00:00.000Z") })).toEqual(
+ notJudged(SecretReadNotJudgedReason.SecretTooNew)
+ );
});
});
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 5aa1cea34d..39620c5ac8 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
@@ -9,7 +9,9 @@ import { TSecretFolderDALFactory } from "@app/services/secret-folder/secret-fold
import { buildFolderIdMap, buildFolderPath } from "@app/services/secret-folder/secret-folder-fns";
import {
+ SecretReadNotJudgedReason,
SecretReadObjectType,
+ SecretReadStatus,
TMemberRole,
TProjectAccess,
TProjectFolderTree,
@@ -138,8 +140,8 @@ export const classifySecretReads = (
return activity;
};
-// Who can read the secret's value today, and which of them have left it unread.
-// Unused access is judged on the non-admins, since admins can read everything by design; ghost readers are readers in the window who can no longer read it
+// Who can read the secret's value today, and which of them have left it unread. Unused access is judged on the
+// non-admins, since admins can read everything by design.
export const summarizeSecretAccess = (
{ secret, environment, secretPath, trackedSince, reads }: TSecretActivity,
{ readersByRules, adminActorIds, accessChangedAtByActorId, judgedFrom }: TProjectAccess
@@ -153,18 +155,37 @@ export const summarizeSecretAccess = (
.flat(),
(reader) => toActorKey(reader.actorType, reader.actorId)
);
- const entitledKeys = new Set(entitled.map((reader) => toActorKey(reader.actorType, reader.actorId)));
- // Admins' reads still show, and a read of theirs is never a ghost's.
const nonAdmins = entitled.filter((reader) => !adminActorIds.has(reader.actorId));
const unread = nonAdmins.filter(
(reader) =>
!reads.has(toActorKey(reader.actorType, reader.actorId)) &&
coversWholeWindow(trackedSince, accessChangedAtByActorId.get(reader.actorId), judgedFrom)
);
- const ghostReaders = [...reads.values()].filter(
- (read) => !entitledKeys.has(toActorKey(read.actorType, read.actorId)) && !adminActorIds.has(read.actorId)
- );
- return { entitled, nonAdmins, unread, ghostReaders };
+ return { entitled, nonAdmins, unread };
+};
+
+// A reader without a read who is not unused access was left out for one of three reasons, checked in this order.
+// The last needs no check of its own: a non-admin whose access predates the judged period is only left out when
+// the secret does not.
+export const getReadStatus = ({
+ lastReadAt,
+ isUnused,
+ isProjectAdmin,
+ accessChangedAt,
+ judgedFrom
+}: {
+ lastReadAt: Date | null;
+ isUnused: boolean;
+ isProjectAdmin: boolean;
+ accessChangedAt: Date | null;
+ judgedFrom: Date;
+}) => {
+ if (lastReadAt) return { readStatus: SecretReadStatus.Read, notJudgedReason: null };
+ if (isUnused) return { readStatus: SecretReadStatus.Unused, notJudgedReason: null };
+ let notJudgedReason = SecretReadNotJudgedReason.SecretTooNew;
+ if (isProjectAdmin) notJudgedReason = SecretReadNotJudgedReason.ProjectAdmin;
+ else if (accessChangedAt && accessChangedAt > judgedFrom) notJudgedReason = SecretReadNotJudgedReason.AccessChanged;
+ return { readStatus: SecretReadStatus.NotJudged, notJudgedReason };
};
// Only the names of the predefined roles are read, so the project id they are built for does not matter.
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 e2a7dde32d..ea78ae7d5d 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
@@ -1,7 +1,6 @@
import { setImmediate } from "node:timers/promises";
import { SecretType, TableName } from "@app/db/schemas";
-import { DAY_IN_MS } from "@app/ee/services/audit-report/audit-report-fns";
import { TIdentityGroupMembershipDALFactory } from "@app/ee/services/group/identity-group-membership-dal";
import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";
import { checkInsightsReadPermission } from "@app/ee/services/insights/insights-fns";
@@ -34,9 +33,9 @@ import {
classifySecretReads,
computeSecretReach,
getReadActivityWindowStart,
+ getReadStatus,
indexSecretReads,
loadProjectFolderTree,
- SECRET_READ_ACTIVITY_WINDOW_DAYS,
summarizeSecretAccess,
toActorKey,
toLocationKey,
@@ -44,7 +43,6 @@ import {
} from "./secret-read-activity-fns";
import { TSecretReadActivityQueueServiceFactory } from "./secret-read-activity-queue";
import {
- TEntitledReader,
TGetSecretReadActivityDTO,
TGetUnusedAccessActorDTO,
TListUnusedAccessDTO,
@@ -54,6 +52,7 @@ import {
TSecretActivity,
TSecretReach,
TSecretReachGraph,
+ TSecretReadActivityActor,
TSecretReaderType,
TUnusedAccessActor,
TUnusedAccessSummary,
@@ -335,8 +334,7 @@ export const secretReadActivityServiceFactory = ({
};
};
- // Direct members come named. Everyone else (members only through a group, and readers since gone from the
- // project) is looked up; a user or identity deleted outright has no name.
+ // Direct members come named; members only through a group are looked up.
const $findActorNames = async (
actors: { actorType: string; actorId: string }[],
directMembers: Map<string, { name: string }>
@@ -393,32 +391,36 @@ export const secretReadActivityServiceFactory = ({
message: `Secret with name '${secretName}' not found at path '${secretPath}' in environment '${environment}'`
});
}
- const { entitled, nonAdmins, unread, ghostReaders } = summarizeSecretAccess(activity, access);
- const unreadKeys = new Set(unread.map((reader) => toActorKey(reader.actorType, reader.actorId)));
- const names = await $findActorNames([...entitled, ...ghostReaders], access.directMembers);
+ const { entitled, unread } = summarizeSecretAccess(activity, access);
+ const unusedKeys = new Set(unread.map((reader) => toActorKey(reader.actorType, reader.actorId)));
+ const names = await $findActorNames(entitled, access.directMembers);
+
+ const actors = entitled.map((reader): TSecretReadActivityActor => {
+ const key = toActorKey(reader.actorType, reader.actorId);
+ const lastReadAt = activity.reads.get(key)?.lastReadAt ?? null;
+ const isProjectAdmin = access.adminActorIds.has(reader.actorId);
+ const accessChangedAt = access.accessChangedAtByActorId.get(reader.actorId) ?? null;
+ return {
+ actorType: reader.actorType,
+ actorId: reader.actorId,
+ name: names.get(key) ?? reader.actorId,
+ isProjectAdmin,
+ lastReadAt,
+ accessChangedAt,
+ ...getReadStatus({
+ lastReadAt,
+ isUnused: unusedKeys.has(key),
+ isProjectAdmin,
+ accessChangedAt,
+ judgedFrom: access.judgedFrom
+ })
+ };
+ });
return {
- trackedSince: activity.trackedSince,
- judgedFrom: access.judgedFrom,
- reads: [...activity.reads.values()],
- entitled: entitled.map((reader): TEntitledReader => {
- const key = toActorKey(reader.actorType, reader.actorId);
- return {
- actorType: reader.actorType,
- actorId: reader.actorId,
- actorName: names.get(key) ?? null,
- unread: unreadKeys.has(key),
- isAdmin: access.adminActorIds.has(reader.actorId),
- accessChangedAt: access.accessChangedAtByActorId.get(reader.actorId) ?? null
- };
- }),
- entitledCount: nonAdmins.length,
- unreadCount: unread.length,
- ghostReaderCount: ghostReaders.length,
- ghostReaders: ghostReaders.map((read) => ({
- ...read,
- actorName: names.get(toActorKey(read.actorType, read.actorId)) ?? null
- }))
+ readsTrackedSince: activity.trackedSince,
+ unusedAccessJudgedFrom: access.judgedFrom,
+ actors: actors.sort((a, b) => a.name.localeCompare(b.name))
};
};
@@ -432,7 +434,6 @@ export const secretReadActivityServiceFactory = ({
$loadProjectAccess(projectId, orgId, windowStart)
]);
const tallies = new Map<string, TUnusedAccessTally>();
- const lastReadAtByKey = new Map<string, Date>();
for (const activity of activities) {
// eslint-disable-next-line no-await-in-loop
await setImmediate();
@@ -442,38 +443,34 @@ export const secretReadActivityServiceFactory = ({
const tally = tallies.get(key) ?? {
actorType,
actorId,
- entitledCount: 0,
- unreadCount: 0,
- unreadSecretIds: [],
+ accessibleSecretCount: 0,
+ unusedSecretCount: 0,
+ unusedSecretIds: [],
environments: new Set()
};
- tally.entitledCount += 1;
+ tally.accessibleSecretCount += 1;
tallies.set(key, tally);
});
// Every unread reader is also a non-admin, so its tally exists.
unread.forEach(({ actorType, actorId }) => {
const tally = tallies.get(toActorKey(actorType, actorId)) as TUnusedAccessTally;
- tally.unreadCount += 1;
+ tally.unusedSecretCount += 1;
tally.environments.add(activity.environment);
- if (tally.unreadSecretIds.length < UNUSED_ACCESS_MAX_SECRETS_PER_ACTOR) {
- tally.unreadSecretIds.push(activity.secret.id);
+ if (tally.unusedSecretIds.length < UNUSED_ACCESS_MAX_SECRETS_PER_ACTOR) {
+ tally.unusedSecretIds.push(activity.secret.id);
}
});
- activity.reads.forEach((read, key) => {
- const latest = lastReadAtByKey.get(key);
- if (!latest || read.lastReadAt > latest) lastReadAtByKey.set(key, read.lastReadAt);
- });
}
- return { tallies, lastReadAtByKey, access };
+ return { tallies, access };
};
// Every user and machine identity that can read secrets it has not read in the window, whether through a role, a
// privilege or a group. Ranked by how many such secrets it has.
const $computeUnusedAccess = async (projectId: string, orgId: string): Promise<TUnusedAccessSummary> => {
- const { tallies, lastReadAtByKey, access } = await $tallyUnusedAccess(projectId, orgId);
+ const { tallies, access } = await $tallyUnusedAccess(projectId, orgId);
const ranked = [...tallies.values()]
- .filter((tally) => tally.unreadCount > 0)
- .sort((a, b) => b.unreadCount - a.unreadCount || a.entitledCount - b.entitledCount);
+ .filter((tally) => tally.unusedSecretCount > 0)
+ .sort((a, b) => b.unusedSecretCount - a.unusedSecretCount || a.accessibleSecretCount - b.accessibleSecretCount);
const names = await $findActorNames(ranked, access.directMembers);
const rows = ranked.map((tally): TUnusedAccessActor => {
@@ -483,10 +480,9 @@ export const secretReadActivityServiceFactory = ({
actorType: tally.actorType,
actorId: tally.actorId,
name: names.get(key) ?? tally.actorId,
- entitledCount: tally.entitledCount,
- unreadCount: tally.unreadCount,
+ accessibleSecretCount: tally.accessibleSecretCount,
+ unusedSecretCount: tally.unusedSecretCount,
environments: [...tally.environments].sort(),
- lastReadAt: lastReadAtByKey.get(key) ?? null,
accessPaths: {
roles: toUnusedAccessRoles(member?.roles ?? []),
groups: (access.groupMembershipsByActorKey[key] ?? []).map(({ group }) => ({
@@ -503,9 +499,9 @@ export const secretReadActivityServiceFactory = ({
const details = Object.fromEntries(
ranked
.slice(0, UNUSED_ACCESS_DETAIL_MAX_ACTORS)
- .map((tally) => [toActorKey(tally.actorType, tally.actorId), tally.unreadSecretIds])
+ .map((tally) => [toActorKey(tally.actorType, tally.actorId), tally.unusedSecretIds])
);
- return { rows, details };
+ return { rows, details, periodStart: access.judgedFrom };
};
// The whole project is computed once a day and cached, so paging through it is cheap.
@@ -546,18 +542,16 @@ export const secretReadActivityServiceFactory = ({
}
}
});
- const [remainingTTL, { project, trackingStartedAt }] = await Promise.all([
+ const [remainingTTL, project] = await Promise.all([
getCacheTtl(keyStore, cacheKey),
- $getProjectTrackingStartedAt(projectId)
+ projectDAL.findById(projectId)
]);
return {
...summary,
// Dates come back from the cache as strings.
- rows: summary.rows.map((row) => ({ ...row, lastReadAt: row.lastReadAt ? new Date(row.lastReadAt) : null })),
+ periodStart: new Date(summary.periodStart),
remainingTTL,
- projectName: project?.name ?? "",
- trackingStartedAt,
- fullWindowFrom: new Date(trackingStartedAt.getTime() + SECRET_READ_ACTIVITY_WINDOW_DAYS * DAY_IN_MS)
+ projectName: project?.name ?? ""
};
};
@@ -573,8 +567,7 @@ export const secretReadActivityServiceFactory = ({
actors: matching.slice(offset, offset + limit),
totalCount: matching.length,
projectName: tracking.projectName,
- trackingStartedAt: tracking.trackingStartedAt,
- fullWindowFrom: tracking.fullWindowFrom,
+ periodStart: tracking.periodStart,
remainingTTL: tracking.remainingTTL
};
};
@@ -599,7 +592,7 @@ export const secretReadActivityServiceFactory = ({
keyStore,
key: KeyStorePrefixes.InsightsCache(projectId, `unused-access:${key}`),
ttlSeconds: UNUSED_ACCESS_CACHE_TTL_SECONDS,
- fetcher: async () => (await $tallyUnusedAccess(projectId, actor.orgId)).tallies.get(key)?.unreadSecretIds ?? []
+ fetcher: async () => (await $tallyUnusedAccess(projectId, actor.orgId)).tallies.get(key)?.unusedSecretIds ?? []
}));
// The cache is shared by everyone in the project and can be a day old, so each listed secret is checked against
@@ -630,11 +623,8 @@ export const secretReadActivityServiceFactory = ({
return {
actor: unusedAccessActor,
secrets,
- // Everything not in the list: past the cached cap, hidden from this viewer, or deleted since.
- unlistedCount: Math.max(0, unusedAccessActor.unreadCount - secrets.length),
projectName: tracking.projectName,
- trackingStartedAt: tracking.trackingStartedAt,
- fullWindowFrom: tracking.fullWindowFrom,
+ periodStart: tracking.periodStart,
remainingTTL: tracking.remainingTTL
};
};
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 7012227f2d..b2224a0c37 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
@@ -132,18 +132,29 @@ export type TSecretAccessSummary = {
entitled: TProjectReader[];
nonAdmins: TProjectReader[];
unread: TProjectReader[];
- ghostReaders: TSecretReadResult[];
};
-// 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 = {
+export enum SecretReadStatus {
+ Read = "read",
+ Unused = "unused",
+ NotJudged = "not-judged"
+}
+
+export enum SecretReadNotJudgedReason {
+ ProjectAdmin = "project-admin",
+ AccessChanged = "access-changed",
+ SecretTooNew = "secret-too-new"
+}
+
+export type TSecretReadActivityActor = {
actorType: TSecretReaderType;
actorId: string;
- actorName: string | null;
- unread: boolean;
- isAdmin: boolean;
+ name: string;
+ isProjectAdmin: boolean;
+ lastReadAt: Date | null;
accessChangedAt: Date | null;
+ readStatus: SecretReadStatus;
+ notJudgedReason: SecretReadNotJudgedReason | null;
};
export type TMemberRole = Awaited<
@@ -162,26 +173,27 @@ export type TUnusedAccessActor = {
actorType: TSecretReaderType;
actorId: string;
name: string;
- entitledCount: number;
- unreadCount: number;
+ accessibleSecretCount: number;
+ unusedSecretCount: number;
environments: string[];
- lastReadAt: Date | null;
accessPaths: TUnusedAccessPaths;
};
export type TUnusedAccessTally = {
actorType: TSecretReaderType;
actorId: string;
- entitledCount: number;
- unreadCount: number;
+ accessibleSecretCount: number;
+ unusedSecretCount: number;
// Capped at UNUSED_ACCESS_MAX_SECRETS_PER_ACTOR
- unreadSecretIds: string[];
+ unusedSecretIds: string[];
environments: Set<string>;
};
export type TUnusedAccessSummary = {
rows: TUnusedAccessActor[];
details: Record<string, string[]>;
+ // Unused means no read since this date: 30 days before the computation, or when tracking began if later.
+ periodStart: Date;
};
export type TUnusedSecret = TSecretLocation & { secretKey: string };
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index a4e917df39..5639dd936e 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -957,12 +957,10 @@ export const INSIGHTS = {
actorType: "Whether the actor is a user or a machine identity.",
actorId: "The ID of the user or machine identity.",
name: "The username of the user, or the name of the machine identity.",
- entitledCount: "How many secrets the actor can read the value of today.",
- unreadCount:
- "How many of those it has not read, or an import or reference of, in the last 30 days. Secrets and access newer than 30 days are not counted.",
+ accessibleSecretCount: "How many secrets the actor can read the value of today.",
+ unusedSecretCount:
+ "How many of those it has not read, or an import or reference of, since periodStart. A secret only counts once it and the actor's access both predate periodStart.",
environments: "The slugs of the environments holding the unread secrets.",
- lastReadAt:
- "When the actor last read any secret in the project in the last 30 days, as the first read of that day. Null when it read nothing.",
accessPaths: "How the actor has its access to the project's secrets.",
roles: "The project roles the actor holds directly, not through a group.",
roleId: "The ID of the custom role. Null for a built-in role.",
@@ -976,22 +974,43 @@ export const INSIGHTS = {
additionalPrivilegeId: "The ID of the additional privilege.",
additionalPrivilegeName: "The name of the additional privilege.",
totalCount: "The number of actors the caller can page through.",
- 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.",
- fullWindowFrom:
- "When the results first cover a full 30 days of reads: 30 days after reads started being tracked for the project. Before then they cover the reads since tracking began, and the access that existed then."
+ periodStart:
+ "Unused means no read since this date: 30 days before the results were computed, or when reads started being tracked for the project if that is later. Results are recomputed once a day."
},
GET_UNUSED_ACCESS_ACTOR: {
projectId: "The ID of the project.",
actorType: "Whether the actor is a user or a machine identity.",
actorId: "The ID of the user or machine identity.",
secrets:
- "The secrets the actor can read but has not read in the last 30 days, among those the caller can see, ordered by environment and path.",
+ "The secrets the actor can read but has not read since periodStart, ordered by environment and path. The list can be shorter than the actor's unusedSecretCount: it holds at most 200, only those the caller can see, and none deleted since the results were computed.",
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.",
- unlistedCount:
- "How many of the actor's unread secrets are not listed: past the first 200, in places the caller cannot see, or deleted since the results were computed."
+ secretPath: "The path of the folder the secret is in."
+ },
+ GET_SECRET_READ_ACTIVITY: {
+ projectId: "The ID of the project where the secret is located.",
+ secretName: "The name of the secret.",
+ environment: "The slug of the environment where the secret is located.",
+ secretPath: "The folder path where the secret is located.",
+ readsTrackedSince:
+ "Reads are reported from this date: the latest of 30 days ago, when reads started being tracked for the project, and when the secret and its folder were created.",
+ unusedAccessJudgedFrom:
+ "Unused access is judged from this date: the later of 30 days ago and when reads started being tracked for the project. An actor without a read only counts as unused access once the secret and their access both predate it.",
+ actors:
+ "One entry for each user or machine identity that can read the secret's value today, directly or through a group, ordered by name. Project admins are included so their reads show.",
+ actorType: "Whether the actor is a user or a machine identity.",
+ actorId: "The ID of the user or machine identity.",
+ name: "The username of the user, or the name of the machine identity.",
+ isProjectAdmin:
+ "Whether the actor is a project admin, directly or through a group. Admins can read everything by design, so they never count as unused access.",
+ lastReadAt:
+ "When the actor last read the secret, or an import or reference of it, since readsTrackedSince, as the first read of that day. Null when they have not.",
+ accessChangedAt:
+ "When the actor's access to the project last changed: the latest membership, role or privilege creation, edit or expiry. Null when it has not changed since the membership was created.",
+ readStatus:
+ "read: the actor read the secret since readsTrackedSince. unused: no read, and the secret and their access both predate unusedAccessJudgedFrom, so it counts as unused access. not-judged: no read, but it does not count yet; notJudgedReason says why.",
+ notJudgedReason:
+ "Why an actor without a read is not counted as unused access. project-admin: admins are never counted. access-changed: their access changed after unusedAccessJudgedFrom. secret-too-new: the secret is newer than unusedAccessJudgedFrom. Null unless readStatus is not-judged."
},
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.",
@@ -1502,38 +1521,6 @@ export const RAW_SECRETS = {
includeAllEntities:
"When true, includes all project users, identities, and groups in the response, even those without any access to the secret."
},
- GET_READ_ACTIVITY: {
- secretName: "The name of the secret to get read activity for.",
- projectId: "The ID of the project where the secret is located.",
- environment: "The slug of the environment where the secret is located.",
- 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, project admins included so their reads can be shown, saying whether they count as unused access and, if not, why.",
- readerName: "The username of the user, or the name of the machine identity. Null when it could not be resolved.",
- 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.",
- actorId: "The ID of the user or machine identity.",
- lastReadAt: "When the reader last read the secret, as the first read of that day.",
- entitledCount:
- "How many users and machine identities can read the secret's value today, project admins left out since they can read everything by design.",
- unreadCount: "How many of those count as unused access.",
- ghostReaderCount: "How many ghost readers the secret has.",
- 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.",
sourceEnvironment: "The slug of the source environment.",
diff --git a/frontend/src/hooks/api/secretInsights/index.ts b/frontend/src/hooks/api/secretInsights/index.ts
index 8764e6bc08..f5514d138f 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,
+ useGetSecretReadActivity,
useGetSecretsDuplication,
useGetUnusedAccess,
useGetUnusedAccessActor
@@ -36,6 +37,7 @@ export type {
TGetSecretAccessLocationsResponse,
TGetSecretAccessVolumeDTO,
TGetSecretAccessVolumeResponse,
+ TGetSecretReadActivityDTO,
TGetSecretsDuplicationDTO,
TGetSecretsDuplicationResponse,
TGetUnusedAccessActorDTO,
@@ -54,10 +56,12 @@ export type {
TSearchSecretsByValueResponse,
TSecretAccessVolumeActor,
TSecretAccessVolumeDay,
+ TSecretReadActivity,
+ TSecretReadActivityActor,
TSecretValueMatch,
TUnusedAccessActor,
TUnusedAccessPaths,
TUnusedAccessRole,
TUnusedSecret
} from "./types";
-export { UnusedAccessActorType } from "./types";
+export { SecretReadNotJudgedReason, SecretReadStatus, UnusedAccessActorType } from "./types";
diff --git a/frontend/src/hooks/api/secretInsights/queries.tsx b/frontend/src/hooks/api/secretInsights/queries.tsx
index dcf9847379..bc673c49cc 100644
--- a/frontend/src/hooks/api/secretInsights/queries.tsx
+++ b/frontend/src/hooks/api/secretInsights/queries.tsx
@@ -20,6 +20,7 @@ import {
TGetSecretAccessVolumeResponse,
TGetSecretBlindIndexStatusDTO,
TGetSecretBlindIndexStatusResponse,
+ TGetSecretReadActivityDTO,
TGetSecretsDuplicationDTO,
TGetSecretsDuplicationResponse,
TGetUnusedAccessActorDTO,
@@ -30,7 +31,8 @@ import {
TOrgProjectsInsights,
TOrgSecretAccessVolume,
TOrgSecretsSummary,
- TOrgStaticSecretUsage
+ TOrgStaticSecretUsage,
+ TSecretReadActivity
} from "./types";
export const secretInsightsKeys = {
@@ -43,6 +45,8 @@ export const secretInsightsKeys = {
[...secretInsightsKeys.all(), "unused-access", params] as const,
unusedAccessActor: (params: TGetUnusedAccessActorDTO) =>
[...secretInsightsKeys.all(), "unused-access-actor", params] as const,
+ secretReadActivity: (params: TGetSecretReadActivityDTO) =>
+ [...secretInsightsKeys.all(), "secret-read-activity", params] as const,
// accessLocations: (params: TGetSecretAccessLocationsDTO) =>
// [...secretInsightsKeys.all(), "access-locations", params] as const,
authMethodDistribution: (params: TGetAuthMethodDistributionDTO) =>
@@ -187,6 +191,22 @@ export const useGetUnusedAccessActor = (
});
};
+export const useGetSecretReadActivity = (
+ params: TGetSecretReadActivityDTO,
+ options?: { enabled?: boolean }
+) =>
+ useQuery({
+ queryKey: secretInsightsKeys.secretReadActivity(params),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<{ readActivity: TSecretReadActivity }>(
+ `/api/v1/insights/${params.projectId}/secrets/read-activity/${encodeURIComponent(params.secretKey)}`,
+ { params: { environment: params.environment, secretPath: params.secretPath } }
+ );
+ return data.readActivity;
+ },
+ enabled: Boolean(params.secretKey) && (options?.enabled ?? true)
+ });
+
export const useGetAuthMethodDistribution = (
params: TGetAuthMethodDistributionDTO,
options?: Omit<
diff --git a/frontend/src/hooks/api/secretInsights/types.ts b/frontend/src/hooks/api/secretInsights/types.ts
index 4474424209..844b87e82e 100644
--- a/frontend/src/hooks/api/secretInsights/types.ts
+++ b/frontend/src/hooks/api/secretInsights/types.ts
@@ -74,10 +74,9 @@ export type TUnusedAccessActor = {
actorType: UnusedAccessActorType;
actorId: string;
name: string;
- entitledCount: number;
- unreadCount: number;
+ accessibleSecretCount: number;
+ unusedSecretCount: number;
environments: string[];
- lastReadAt: string | null;
accessPaths: TUnusedAccessPaths;
};
@@ -91,8 +90,8 @@ export type TGetUnusedAccessDTO = {
export type TGetUnusedAccessResponse = {
actors: TUnusedAccessActor[];
totalCount: number;
- trackingStartedAt: string;
- fullWindowFrom: string;
+ // Unused means no read since this date: 30 days ago, or when tracking began if later.
+ periodStart: string;
remainingTtl: number;
};
@@ -111,12 +110,46 @@ export type TUnusedSecret = {
export type TGetUnusedAccessActorResponse = {
actor: TUnusedAccessActor;
secrets: TUnusedSecret[];
- unlistedCount: number;
- trackingStartedAt: string;
- fullWindowFrom: string;
+ periodStart: string;
remainingTtl: number;
};
+export enum SecretReadStatus {
+ Read = "read",
+ Unused = "unused",
+ NotJudged = "not-judged"
+}
+
+export enum SecretReadNotJudgedReason {
+ ProjectAdmin = "project-admin",
+ AccessChanged = "access-changed",
+ SecretTooNew = "secret-too-new"
+}
+
+export type TGetSecretReadActivityDTO = {
+ projectId: string;
+ environment: string;
+ secretPath: string;
+ secretKey: string;
+};
+
+export type TSecretReadActivityActor = {
+ actorType: UnusedAccessActorType;
+ actorId: string;
+ name: string;
+ isProjectAdmin: boolean;
+ lastReadAt: string | null;
+ accessChangedAt: string | null;
+ readStatus: SecretReadStatus;
+ notJudgedReason: SecretReadNotJudgedReason | null;
+};
+
+export type TSecretReadActivity = {
+ readsTrackedSince: string;
+ unusedAccessJudgedFrom: string;
+ actors: TSecretReadActivityActor[];
+};
+
export type TGetInsightsSummaryDTO = {
projectId: string;
staleSecretsOffset?: number;
diff --git a/frontend/src/hooks/api/secrets/queries.tsx b/frontend/src/hooks/api/secrets/queries.tsx
index a40e366ca5..51cb16aa98 100644
--- a/frontend/src/hooks/api/secrets/queries.tsx
+++ b/frontend/src/hooks/api/secrets/queries.tsx
@@ -22,12 +22,10 @@ import {
TGetProjectSecretsDTO,
TGetProjectSecretsKey,
TGetSecretAccessListDTO,
- TGetSecretReadActivityDTO,
TGetSecretReferencesDTO,
TGetSecretReferenceTreeDTO,
TGetSecretVersionValue,
TSecretDependencyTreeNode,
- TSecretReadActivity,
TSecretReferenceTraceNode,
TSecretVersionValue
} from "./types";
@@ -69,13 +67,6 @@ export const secretKeys = {
"secret-access-list",
{ projectId, environment, secretPath, secretKey, includeAllEntities }
] as const,
- getSecretReadActivity: ({
- projectId,
- environment,
- secretPath,
- secretKey
- }: TGetSecretReadActivityDTO) =>
- ["secret-read-activity", { projectId, environment, secretPath, secretKey }] as const,
getSecretReferenceTree: (dto: TGetSecretReferenceTreeDTO) => ["secret-reference-tree", dto],
getSecretReferences: (dto: TGetSecretReferencesDTO) => ["secret-references", dto]
};
@@ -371,29 +362,6 @@ export const useGetSecretAccessList = (dto: TGetSecretAccessListDTO) =>
}
});
-export const useGetSecretReadActivity = (
- dto: TGetSecretReadActivityDTO,
- options?: { enabled?: boolean }
-) =>
- useQuery({
- queryKey: secretKeys.getSecretReadActivity(dto),
- queryFn: async () => {
- const { data } = await apiRequest.get<{ readActivity: TSecretReadActivity }>(
- `/api/v1/secrets/${encodeURIComponent(dto.secretKey)}/read-activity`,
- {
- params: {
- projectId: dto.projectId,
- environment: dto.environment,
- secretPath: dto.secretPath
- }
- }
- );
-
- return data.readActivity;
- },
- enabled: Boolean(dto.secretKey) && (options?.enabled ?? true)
- });
-
const fetchSecretReferenceTree = async ({
secretPath,
projectId,
diff --git a/frontend/src/hooks/api/secrets/types.ts b/frontend/src/hooks/api/secrets/types.ts
index af34db7f28..d4822f8c1e 100644
--- a/frontend/src/hooks/api/secrets/types.ts
+++ b/frontend/src/hooks/api/secrets/types.ts
@@ -160,39 +160,6 @@ export type TGetSecretAccessListDTO = {
includeAllEntities?: boolean;
};
-export type TGetSecretReadActivityDTO = Omit<TGetSecretAccessListDTO, "includeAllEntities">;
-
-export type TSecretReadActivity = {
- 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;
- actorName: string | null;
- unread: boolean;
- isAdmin: boolean;
- accessChangedAt: string | null;
- }[];
- // Non-admins who can read the value, how many of them count as unused access, and the ghost readers.
- entitledCount: number;
- unreadCount: number;
- ghostReaderCount: number;
- ghostReaders: {
- actorType: "user" | "identity";
- actorId: string;
- // Null when the reader has since been deleted.
- actorName: string | null;
- lastReadAt: string;
- }[];
-};
-
export type TCreateSecretsV3DTO = {
secretKey: string;
secretValue: string;
diff --git a/frontend/src/pages/secret-manager/InsightsPage/components/UnusedAccessActorSheet.tsx b/frontend/src/pages/secret-manager/InsightsPage/components/UnusedAccessActorSheet.tsx
index c6c5204c07..5ab1ffcbad 100644
--- a/frontend/src/pages/secret-manager/InsightsPage/components/UnusedAccessActorSheet.tsx
+++ b/frontend/src/pages/secret-manager/InsightsPage/components/UnusedAccessActorSheet.tsx
@@ -44,6 +44,8 @@ const ActorSecrets = ({ data }: SecretsProps) => {
const [expanded, setExpanded] = useState<Set<string>>(() => new Set());
const environmentNames = new Map(currentProject.environments.map((env) => [env.slug, env.name]));
+ // The list stops at 200, leaves out what the viewer cannot see, and drops secrets deleted since the computation.
+ const unlistedCount = Math.max(0, data.actor.unusedSecretCount - data.secrets.length);
const byEnvironment = new Map<string, typeof data.secrets>();
data.secrets.forEach((secret) => {
byEnvironment.set(secret.environment, [
@@ -58,7 +60,7 @@ const ActorSecrets = ({ data }: SecretsProps) => {
<EmptyHeader>
<EmptyTitle>Nothing to show</EmptyTitle>
<EmptyDescription>
- {data.unlistedCount > 0
+ {unlistedCount > 0
? "Its unread secrets are in places you cannot see, or were deleted since the last update."
: "It has no unread secrets anymore."}
</EmptyDescription>
@@ -118,11 +120,10 @@ const ActorSecrets = ({ data }: SecretsProps) => {
</div>
);
})}
- {data.unlistedCount > 0 && (
+ {unlistedCount > 0 && (
<p className="text-xs text-muted">
- {data.unlistedCount} more unread {data.unlistedCount === 1 ? "secret is" : "secrets are"}{" "}
- not listed: past the first 200, in places you cannot see, or deleted since the last
- update.
+ {unlistedCount} more unread {unlistedCount === 1 ? "secret is" : "secrets are"} not
+ listed: past the first 200, in places you cannot see, or deleted since the last update.
</p>
)}
</div>
@@ -180,12 +181,9 @@ export const UnusedAccessActorSheet = ({ actor, onClose }: Props) => {
<Badge variant="neutral">{ACTOR_TYPE_CONFIG[actor.actorType].label}</Badge>
</SheetTitle>
<SheetDescription>
- Has not read {actor.unreadCount} of the {actor.entitledCount}{" "}
- {actor.entitledCount === 1 ? "secret" : "secrets"} it can access{" "}
- {data
- ? describeReadPeriod(data.trackingStartedAt, data.fullWindowFrom)
- : "in the last 30 days"}
- .
+ Has not read {actor.unusedSecretCount} of the {actor.accessibleSecretCount}{" "}
+ {actor.accessibleSecretCount === 1 ? "secret" : "secrets"} it can access{" "}
+ {data ? describeReadPeriod(data.periodStart) : "in the last 30 days"}.
</SheetDescription>
</SheetHeader>
)}
diff --git a/frontend/src/pages/secret-manager/InsightsPage/components/UnusedAccessCard.tsx b/frontend/src/pages/secret-manager/InsightsPage/components/UnusedAccessCard.tsx
index b835fcc0d1..2b84ef040c 100644
--- a/frontend/src/pages/secret-manager/InsightsPage/components/UnusedAccessCard.tsx
+++ b/frontend/src/pages/secret-manager/InsightsPage/components/UnusedAccessCard.tsx
@@ -63,9 +63,7 @@ export const UnusedAccessCard = () => {
? formatRemainingTtl(data.remainingTtl)
: null;
const environmentNames = new Map(currentProject.environments.map((env) => [env.slug, env.name]));
- const readPeriod = data
- ? describeReadPeriod(data.trackingStartedAt, data.fullWindowFrom)
- : "in the last 30 days";
+ const readPeriod = data ? describeReadPeriod(data.periodStart) : "in the last 30 days";
const renderBody = () => {
if (isPending) return <Skeleton className="h-[200px] w-full" />;
@@ -130,7 +128,7 @@ export const UnusedAccessCard = () => {
<TableBody>
{data.actors.map((row) => {
const { icon: TypeIcon, label } = ACTOR_TYPE_CONFIG[row.actorType];
- const percent = unusedSharePercent(row.unreadCount, row.entitledCount);
+ const percent = unusedSharePercent(row.unusedSecretCount, row.accessibleSecretCount);
const tone = unusedShareTone(percent);
return (
<TableRow
@@ -151,10 +149,10 @@ export const UnusedAccessCard = () => {
<div className="flex min-w-44 flex-col gap-1.5">
<div className="flex items-baseline justify-between gap-3 whitespace-nowrap">
<span>
- {row.unreadCount}{" "}
+ {row.unusedSecretCount}{" "}
<span className="text-muted">
- of {row.entitledCount}{" "}
- {row.entitledCount === 1 ? "secret unread" : "secrets unread"}
+ of {row.accessibleSecretCount}{" "}
+ {row.accessibleSecretCount === 1 ? "secret unread" : "secrets unread"}
</span>
</span>
<span className={cn("tabular-nums", tone.text)}>{percent}%</span>
diff --git a/frontend/src/pages/secret-manager/InsightsPage/components/unusedAccessHelpers.ts b/frontend/src/pages/secret-manager/InsightsPage/components/unusedAccessHelpers.ts
index 980f6af67b..23178c039f 100644
--- a/frontend/src/pages/secret-manager/InsightsPage/components/unusedAccessHelpers.ts
+++ b/frontend/src/pages/secret-manager/InsightsPage/components/unusedAccessHelpers.ts
@@ -28,17 +28,22 @@ export const accessPathBadges = ({ roles, additionalPrivileges, groups }: TUnuse
}))
];
+const WINDOW_MS = 30 * 24 * 60 * 60 * 1000;
+
// The period reads are judged on: the last 30 days once tracking has run that long, else since it began.
-export const describeReadPeriod = (trackingStartedAt: string, fullWindowFrom: string) =>
- new Date(fullWindowFrom) > new Date()
- ? `since ${format(new Date(trackingStartedAt), "PP")}`
+export const describeReadPeriod = (periodStart: string) =>
+ new Date(periodStart).getTime() > Date.now() - WINDOW_MS
+ ? `since ${format(new Date(periodStart), "PP")}`
: "in the last 30 days";
// The share of the secrets an actor can read that it has not read, as a whole percentage that only reads 0
// or 100 when it is exactly that.
-export const unusedSharePercent = (unreadCount: number, entitledCount: number) => {
- if (unreadCount >= entitledCount) return 100;
- return Math.min(99, Math.max(1, Math.round((unreadCount / Math.max(1, entitledCount)) * 100)));
+export const unusedSharePercent = (unusedSecretCount: number, accessibleSecretCount: number) => {
+ if (unusedSecretCount >= accessibleSecretCount) return 100;
+ return Math.min(
+ 99,
+ Math.max(1, Math.round((unusedSecretCount / Math.max(1, accessibleSecretCount)) * 100))
+ );
};
// Most of its access unread is the strongest sign an actor has access it does not need.
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 90e13cef1f..2d33f897d6 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/SecretAccessInsights.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/SecretAccessInsights.tsx
@@ -97,7 +97,12 @@ import {
} from "@app/hooks/api";
import { useGetAvailableOrgUsers } from "@app/hooks/api/organization/queries";
import { useCreateProjectUserAdditionalPrivilege } from "@app/hooks/api/projectUserAdditionalPrivilege";
-import { useGetSecretAccessList, useGetSecretReadActivity } from "@app/hooks/api/secrets/queries";
+import {
+ SecretReadNotJudgedReason,
+ SecretReadStatus,
+ useGetSecretReadActivity
+} from "@app/hooks/api/secretInsights";
+import { useGetSecretAccessList } from "@app/hooks/api/secrets/queries";
import { SecretAccessListEntry } from "@app/hooks/api/secrets/types";
import { IdentityProjectAdditionalPrivilegeModifySection } from "@app/pages/project/IdentityDetailsByIDPage/components/IdentityProjectAdditionalPrivilegeSection/IdentityProjectAdditionalPrivilegeModifySection";
import { MembershipProjectAdditionalPrivilegeModifySection } from "@app/pages/project/MemberDetailsByIDPage/components/MemberProjectAdditionalPrivilegeSection/MembershipProjectAdditionalPrivilegeModifySection";
@@ -504,46 +509,43 @@ export function SecretAccessInsights({
{ projectId: currentProject.id, environment, secretPath, secretKey },
{ enabled: canReadInsights }
);
- const lastReads = useMemo(
- () => new Map(readActivity?.reads.map((read) => [`${read.actorType}:${read.actorId}`, read])),
- [readActivity]
- );
- const entitledReaders = useMemo(
+ const readActors = useMemo(
() =>
- new Map(
- readActivity?.entitled.map((reader) => [`${reader.actorType}:${reader.actorId}`, reader])
- ),
+ new Map(readActivity?.actors.map((actor) => [`${actor.actorType}:${actor.actorId}`, actor])),
[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.
+ // What a reader's row and node say about their reads, worded from the status the API gives each reader.
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) {
+ const actor = readActors.get(`${type}:${id}`);
+ if (actor?.readStatus === SecretReadStatus.Read && actor.lastReadAt) {
+ return { kind: "read", lastReadAt: actor.lastReadAt };
+ }
+ if (actor?.readStatus === SecretReadStatus.Unused) {
+ return { kind: "unread", since: readActivity.readsTrackedSince };
+ }
+ const judgedFrom = format(new Date(readActivity.unusedAccessJudgedFrom), "PP");
+ if (actor?.notJudgedReason === SecretReadNotJudgedReason.ProjectAdmin) {
return {
kind: "pending",
reason:
"Project admins can read everything by design, so they are not counted as unused access."
};
}
- // judgedFrom is the start of the last 30 days, or when tracking began in a project tracked for less.
- const judgedFrom = new Date(readActivity.judgedFrom);
- if (reader?.accessChangedAt && new Date(reader.accessChangedAt) > judgedFrom) {
+ if (
+ actor?.notJudgedReason === SecretReadNotJudgedReason.AccessChanged &&
+ actor.accessChangedAt
+ ) {
return {
kind: "pending",
- reason: `Their access changed on ${format(new Date(reader.accessChangedAt), "PP")}, after reads started being counted on ${format(judgedFrom, "PP")}, so they have not had the whole period to read it.`
+ reason: `Their access changed on ${format(new Date(actor.accessChangedAt), "PP")}, after reads started being counted on ${judgedFrom}, so they have not had the whole period to read it.`
};
}
- if (new Date(readActivity.trackedSince) > judgedFrom) {
+ if (actor?.notJudgedReason === SecretReadNotJudgedReason.SecretTooNew) {
return {
kind: "pending",
- reason: `The secret is newer than ${format(judgedFrom, "PP")}, when reads started being counted, so nobody has had the whole period to read it.`
+ reason: `The secret is newer than ${judgedFrom}, when reads started being counted, so nobody has had the whole period to read it.`
};
}
return { kind: "pending", reason: "Not counted as unused access." };
@@ -556,7 +558,7 @@ export function SecretAccessInsights({
(readActivityError.response?.data as { message?: string })?.message) ||
"Read activity is unavailable.";
} else if (readActivity) {
- readActivityDescription = `Reads by users and machine identities since ${format(new Date(readActivity.trackedSince), "PP")}, including reads through imports and references.`;
+ readActivityDescription = `Reads by users and machine identities since ${format(new Date(readActivity.readsTrackedSince), "PP")}, including reads through imports and references.`;
}
// Every reader who can read the value, directly or through a group, with one line each to the secret.
@@ -581,7 +583,7 @@ export function SecretAccessInsights({
type,
isDirect,
groupIds,
- isAdmin: entitledReaders.get(`${type}:${entry.id}`)?.isAdmin ?? false,
+ isAdmin: readActors.get(`${type}:${entry.id}`)?.isProjectAdmin ?? false,
lastReadAt: status?.kind === "read" ? status.lastReadAt : undefined,
unreadSince: status?.kind === "unread" ? status.since : undefined
}
@@ -599,7 +601,7 @@ export function SecretAccessInsights({
...secretAccessList.users.map((user) => `user:${user.id}`),
...secretAccessList.identities.map((identity) => `identity:${identity.id}`)
]);
- const groupOnlyReaders = (readActivity?.entitled ?? []).flatMap((reader) => {
+ const groupOnlyReaders = (readActivity?.actors ?? []).flatMap((reader) => {
if (listed.has(`${reader.actorType}:${reader.actorId}`)) return [];
const memberField = reader.actorType === "user" ? "userIds" : "identityIds";
const groupIds = groups
@@ -609,11 +611,11 @@ export function SecretAccessInsights({
return [
{
id: reader.actorId,
- name: reader.actorName ?? reader.actorId,
+ name: reader.name,
type: reader.actorType,
isDirect: false,
groupIds,
- isAdmin: reader.isAdmin,
+ isAdmin: reader.isProjectAdmin,
lastReadAt: status?.kind === "read" ? status.lastReadAt : undefined,
unreadSince: status?.kind === "unread" ? status.since : undefined
}
@@ -630,14 +632,13 @@ export function SecretAccessInsights({
memberCount: group.userIds.length + group.identityIds.length
})),
hasReadActivity: Boolean(canReadInsights && readActivity),
- trackedSince: readActivity?.trackedSince
+ trackedSince: readActivity?.readsTrackedSince
};
- // readStatusOf only reads readActivity, lastReads and entitledReaders, which are all listed.
+ // readStatusOf only reads readActivity and readActors, which are both listed.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
secretAccessList,
- lastReads,
- entitledReaders,
+ readActors,
readActivity,
canReadInsights,
secretKey,