Skip to content

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

refactor(insights): simplify the read activity module and shrink the diff

Dimitris Staratzis8ce6e0eeba28
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.md
index 8e98cadbdd..c8111e6f17 100644
--- a/backend/CLAUDE.md
+++ b/backend/CLAUDE.md
@@ -1167,7 +1167,7 @@ owns the two read endpoints and hands `recordRead` / `recordBulkRead` through to
all of its holder's access (what it held back is not worked out). Only the current secret's source checks are
kept, so the scan's memory does not grow with the project. Only an actor with a
source newer than `judgedFrom` is checked per secret, and each source once per secret across actors. A read from
- before the reader had access to a secret is dropped for that secret (`readsByActorKey`): reads are credited by
+ before the reader had access to a secret is dropped for that secret (`readsByActorId`): reads are credited by
folder, and a folder read then could not have returned it. A read recorded against the secret itself
(`lastSecretReadAt`) always counts, so a role change does not erase it. The per-secret sheet shows the plain fact
instead: a read, "No reads", or "No reads yet" with the reason.
diff --git a/backend/src/ee/services/insights/insights-fns.ts b/backend/src/ee/services/insights/insights-fns.ts
index 00af1fb358..bb1733ecf0 100644
--- a/backend/src/ee/services/insights/insights-fns.ts
+++ b/backend/src/ee/services/insights/insights-fns.ts
@@ -1,12 +1,4 @@
-import { ForbiddenError } from "@casl/ability";
-
-import { ActionProjectType } from "@app/db/schemas";
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
-import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
-import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
-import { ProjectPermissionInsightsActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
-import { BadRequestError } from "@app/lib/errors";
-import { OrgServiceActor } from "@app/lib/types";
import { TUserDALFactory } from "@app/services/user/user-dal";
import { TAccessVolumeActor, TAccessVolumeDay } from "./insights-types";
@@ -124,45 +116,3 @@ export const resolveUserDisplayNames = async (userDAL: Pick<TUserDALFactory, "fi
return userNameMap;
};
-
-export const assertInsightsPlanEnabled = async (
- licenseService: Pick<TLicenseServiceFactory, "getPlan">,
- orgId: string
-) => {
- const plan = await licenseService.getPlan(orgId);
- if (!plan.secretAccessInsights) {
- throw new BadRequestError({
- message: "Failed to access insights due to plan restriction. Upgrade your plan to access insights."
- });
- }
-};
-
-// Permission only, for reads of records the org already has, which a plan downgrade must not hide.
-export const checkInsightsReadPermission = async (
- permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">,
- projectId: string,
- actor: OrgServiceActor
-) => {
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorId: actor.id,
- projectId,
- actorAuthMethod: actor.authMethod,
- actorOrgId: actor.orgId,
- actionProjectType: ActionProjectType.SecretManager
- });
-
- ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionInsightsActions.Read, ProjectPermissionSub.Insights);
-
- return { permission };
-};
-
-export const checkInsightsPermission = async (
- permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">,
- licenseService: Pick<TLicenseServiceFactory, "getPlan">,
- projectId: string,
- actor: OrgServiceActor
-) => {
- await assertInsightsPlanEnabled(licenseService, actor.orgId);
- return checkInsightsReadPermission(permissionService, projectId, actor);
-};
diff --git a/backend/src/ee/services/insights/insights-service.ts b/backend/src/ee/services/insights/insights-service.ts
index 66374254d2..bcd84f17a3 100644
--- a/backend/src/ee/services/insights/insights-service.ts
+++ b/backend/src/ee/services/insights/insights-service.ts
@@ -1,7 +1,7 @@
import { ForbiddenError } from "@casl/ability";
// import geoip from "geoip-lite";
-import { IdentityAuthMethod, OrganizationActionScope } from "@app/db/schemas";
+import { ActionProjectType, IdentityAuthMethod, OrganizationActionScope } from "@app/db/schemas";
import { TClickHouseAuditLogDALFactory } from "@app/ee/services/audit-log/audit-log-clickhouse-dal";
import { TAuditLogDALFactory } from "@app/ee/services/audit-log/audit-log-dal";
import { TDynamicSecretDALFactory } from "@app/ee/services/dynamic-secret/dynamic-secret-dal";
@@ -15,6 +15,7 @@ import {
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import {
ProjectPermissionHoneyTokenActions,
+ ProjectPermissionInsightsActions,
ProjectPermissionSub
} from "@app/ee/services/permission/project-permission";
import { TSecretRotationV2DALFactory } from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-dal";
@@ -40,11 +41,9 @@ import { TUserDALFactory } from "@app/services/user/user-dal";
import { TInsightsDALFactory } from "./insights-dal";
import {
addAccessVolumeEntry,
- assertInsightsPlanEnabled,
buildAccessVolumeDayBuckets,
buildAccessVolumeWindow,
buildStaticSecretUsageWindow,
- checkInsightsPermission,
collapseAccessVolumeDays,
resolveUserDisplayNames,
reviveDates,
@@ -116,6 +115,40 @@ export type TInsightsServiceFactory = ReturnType<typeof insightsServiceFactory>;
// Both halves of the product (the per-project dashboard and the org-wide aggregates) are gated on the
// same entitlement, so the check and its message live in one place.
+const assertInsightsPlanEnabled = async (
+ licenseService: TInsightsServiceFactoryDep["licenseService"],
+ orgId: string
+) => {
+ const plan = await licenseService.getPlan(orgId);
+ if (!plan.secretAccessInsights) {
+ throw new BadRequestError({
+ message: "Failed to access insights due to plan restriction. Upgrade your plan to access insights."
+ });
+ }
+};
+
+const checkInsightsPermission = async (
+ permissionService: TInsightsServiceFactoryDep["permissionService"],
+ licenseService: TInsightsServiceFactoryDep["licenseService"],
+ projectId: string,
+ actor: OrgServiceActor
+) => {
+ await assertInsightsPlanEnabled(licenseService, actor.orgId);
+
+ const { permission } = await permissionService.getProjectPermission({
+ actor: actor.type,
+ actorId: actor.id,
+ projectId,
+ actorAuthMethod: actor.authMethod,
+ actorOrgId: actor.orgId,
+ actionProjectType: ActionProjectType.SecretManager
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionInsightsActions.Read, ProjectPermissionSub.Insights);
+
+ return { permission };
+};
+
export const PROJECT_WARNINGS_CHUNK_SIZE = 1000;
// One value genuinely can sit in thousands of places in a large org, and the caller is chasing a
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 80a5bdfb18..5231d35220 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
@@ -18,7 +18,6 @@ import {
getUtcMonthStart,
indexSecretReads,
summarizeSecretAccess,
- toActorKey,
toUnusedAccessRoles
} from "./secret-read-activity-fns";
import {
@@ -45,57 +44,66 @@ const graph: TSecretReachGraph = {
getImporterFolderIds: (folderId) => ({ nested: ["consumer"], consumer: ["edge"] })[folderId] ?? []
};
+const day = (date: string) => new Date(`${date}T00:00:00.000Z`);
+const sept = day("2026-09-01");
+const oct = day("2026-10-20");
+
const read = (overrides: Partial<TSecretLastRead>): TSecretLastRead => ({
objectId: "shared",
objectType: SecretReadObjectType.Folder,
actorId: "identity-1",
actorType: ActorType.IDENTITY,
- lastReadAt: new Date("2026-10-10T00:00:00.000Z"),
+ lastReadAt: day("2026-10-10"),
...overrides
});
-const trackedSince = new Date("2026-10-01T00:00:00.000Z");
+const ability = (rules: Parameters<typeof createMongoAbility>[0]) =>
+ createMongoAbility<MongoAbility<ProjectPermissionSet>>(rules as never);
+const readsAll = ability([{ action: ProjectPermissionSecretActions.ReadValue, subject: ProjectPermissionSub.Secrets }]);
+const readsProd = ability([
+ {
+ action: ProjectPermissionSecretActions.ReadValue,
+ subject: ProjectPermissionSub.Secrets,
+ conditions: { environment: "prod" }
+ }
+]);
+
+const activity = (overrides: Partial<TSecretActivity> = {}): TSecretActivity => ({
+ secret: { key: "DB_PASS", tags: [], folderId: "f1" } as unknown as TSecretActivity["secret"],
+ environment: "prod",
+ secretPath: "/",
+ trackedSince: sept,
+ reads: new Map(),
+ ...overrides
+});
describe("getUtcMonthStart", () => {
- test("uses the UTC month, not the local one", () => {
- expect(getUtcMonthStart(new Date("2026-10-31T23:59:59.999Z"))).toEqual(new Date("2026-10-01T00:00:00.000Z"));
- expect(getUtcMonthStart(new Date("2026-11-01T00:00:00.000Z"))).toEqual(new Date("2026-11-01T00:00:00.000Z"));
- });
-
- test("rolls over into the next and previous year", () => {
- expect(getUtcMonthStart(new Date("2026-12-15T00:00:00.000Z"), 1)).toEqual(new Date("2027-01-01T00:00:00.000Z"));
- expect(getUtcMonthStart(new Date("2026-01-15T00:00:00.000Z"), -1)).toEqual(new Date("2025-12-01T00:00:00.000Z"));
+ test("uses the UTC month and rolls over years", () => {
+ expect(getUtcMonthStart(new Date("2026-10-31T23:59:59.999Z"))).toEqual(day("2026-10-01"));
+ expect(getUtcMonthStart(day("2026-12-15"), 1)).toEqual(day("2027-01-01"));
+ expect(getUtcMonthStart(day("2026-01-15"), -1)).toEqual(day("2025-12-01"));
});
});
describe("computeSecretReach", () => {
- const reach = computeSecretReach(dbPass, graph);
-
- test("follows references transitively and stops at cycles", () => {
+ test("follows references transitively, stops at cycles, and includes every importing folder", () => {
+ const reach = computeSecretReach(dbPass, graph);
expect([...reach.secretIds].sort()).toEqual([connection.id, dbPass.id, dbUrl.id].sort());
- });
-
- test("includes the folders holding referencing secrets and every folder importing them, transitively", () => {
expect([...reach.folderIds].sort()).toEqual(["consumer", "edge", "nested", "shared"]);
});
});
describe("classifySecretReads", () => {
- const reach = computeSecretReach(dbPass, graph);
+ const trackedSince = day("2026-10-01");
const classify = (reads: TSecretLastRead[]) =>
- classifySecretReads(indexSecretReads(reads), reach, trackedSince).get(`${ActorType.IDENTITY}:identity-1`);
+ classifySecretReads(indexSecretReads(reads), computeSecretReach(dbPass, graph), trackedSince).get("identity-1");
- test("counts a read of a folder that imports the secret through a chain", () => {
+ test("counts reads of the secret, of secrets referencing it and of folders importing it, from trackedSince", () => {
expect(classify([read({ objectId: "edge" })])).toBeDefined();
- });
-
- test("counts a single read of a secret that references it", () => {
expect(classify([read({ objectId: connection.id, objectType: SecretReadObjectType.Secret })])).toBeDefined();
- });
-
- test("ignores a single read of an unrelated secret, and a folder read recorded under a secret's id", () => {
expect(classify([read({ objectId: "unrelated", objectType: SecretReadObjectType.Secret })])).toBeUndefined();
expect(classify([read({ objectId: dbPass.id, objectType: SecretReadObjectType.Folder })])).toBeUndefined();
+ expect(classify([read({ lastReadAt: day("2026-09-30") })])).toBeUndefined();
});
test("counts an unexpanded read only for the secret it returned, not the secrets it references", () => {
@@ -105,243 +113,133 @@ describe("classifySecretReads", () => {
).toBeUndefined();
});
- test("marks only a read recorded against the secret itself as known to have returned it", () => {
- const secretRead = new Date("2026-10-11T00:00:00.000Z");
+ test("keeps the latest read overall, and separately the latest read of the secret itself", () => {
expect(
classify([
- read({ lastReadAt: new Date("2026-10-12T00:00:00.000Z") }),
- read({ objectId: dbPass.id, objectType: SecretReadObjectType.Secret, lastReadAt: secretRead }),
- read({
- objectId: dbUrl.id,
- objectType: SecretReadObjectType.Secret,
- lastReadAt: new Date("2026-10-13T00:00:00.000Z")
- })
+ read({ lastReadAt: day("2026-10-05") }),
+ read({ objectId: dbPass.id, objectType: SecretReadObjectType.Secret, lastReadAt: day("2026-10-11") }),
+ read({ objectId: dbUrl.id, objectType: SecretReadObjectType.Secret, lastReadAt: day("2026-10-13") })
])
).toEqual({
actorType: ActorType.IDENTITY,
actorId: "identity-1",
- lastReadAt: new Date("2026-10-13T00:00:00.000Z"),
- lastSecretReadAt: secretRead
- });
- });
-
- test("ignores reads from before the secret was tracked", () => {
- expect(classify([read({ lastReadAt: new Date("2026-09-30T00:00:00.000Z") })])).toBeUndefined();
- });
-
- test("keeps the latest read across all the ways the secret was reached", () => {
- const latestRead = new Date("2026-10-12T00:00:00.000Z");
- expect(
- classify([
- read({ lastReadAt: new Date("2026-10-05T00:00:00.000Z") }),
- read({ objectId: "consumer", lastReadAt: latestRead }),
- read({ objectId: dbUrl.id, objectType: SecretReadObjectType.Secret })
- ])
- ).toEqual({
- actorType: ActorType.IDENTITY,
- actorId: "identity-1",
- lastReadAt: latestRead
+ lastReadAt: day("2026-10-13"),
+ lastSecretReadAt: day("2026-10-11")
});
});
});
describe("coversWholeWindow", () => {
- const windowStart = new Date("2026-09-15T00:00:00.000Z");
-
- test("is true once the secret and the access have both existed for the whole window", () => {
- expect(coversWholeWindow(windowStart, new Date("2026-08-01T00:00:00.000Z"), windowStart)).toBe(true);
- expect(coversWholeWindow(windowStart, undefined, windowStart)).toBe(true);
- });
-
- test("is false for a secret newer than the window", () => {
- expect(coversWholeWindow(new Date("2026-10-01T00:00:00.000Z"), undefined, windowStart)).toBe(false);
- });
-
- test("is false for a reader whose access changed inside the window", () => {
- expect(coversWholeWindow(windowStart, new Date("2026-10-10T00:00:00.000Z"), windowStart)).toBe(false);
+ test("needs both the secret and the access to predate the window", () => {
+ expect(coversWholeWindow(sept, day("2026-08-01"), sept)).toBe(true);
+ expect(coversWholeWindow(sept, undefined, sept)).toBe(true);
+ expect(coversWholeWindow(oct, undefined, sept)).toBe(false);
+ expect(coversWholeWindow(sept, oct, sept)).toBe(false);
});
});
describe("summarizeSecretAccess", () => {
- const judgedFrom = new Date("2026-09-15T00:00:00.000Z");
- const canRead = createMongoAbility<MongoAbility<ProjectPermissionSet>>([
- { action: ProjectPermissionSecretActions.ReadValue, subject: ProjectPermissionSub.Secrets }
- ]);
- const cannotRead = createMongoAbility<MongoAbility<ProjectPermissionSet>>([]);
- const reader = (actorId: string, permission = canRead) => ({
+ const judgedFrom = day("2026-09-15");
+ const reader = (actorId: string, permission = readsAll) => ({
actorType: ActorType.USER as const,
actorId,
permission
});
- const activity = (overrides: Partial<TSecretActivity> = {}): TSecretActivity => ({
- secret: { key: "DB_PASS", tags: [] } as unknown as TSecretActivity["secret"],
- environment: "prod",
- secretPath: "/",
- trackedSince: judgedFrom,
- reads: new Map(),
- ...overrides
- });
const datedAccess = (accessSince: Record<string, Date>) => ({
accessSinceOf: ({ actorId }: { actorId: string }) => accessSince[actorId],
latestAccessChangeOf: ({ actorId }: { actorId: string }) => accessSince[actorId]
});
const access = (overrides: Partial<TProjectAccess> = {}): TProjectAccess => ({
- readersByRules: [[reader("direct"), reader("via-group")], [reader("no-access", cannotRead)]],
+ readersByRules: [[reader("direct"), reader("via-group")], [reader("no-access", ability([]))]],
adminActorIds: new Set(),
judgedFrom,
...datedAccess({}),
...overrides
});
const ids = (readers: { actorId: string }[]) => readers.map((entry) => entry.actorId).sort();
- const readBy = (actorId: string) =>
+ const readBy = (actorId: string, lastSecretReadAt?: Date) =>
new Map([
- [
- toActorKey(ActorType.USER, actorId),
- { actorType: ActorType.USER as const, actorId, lastReadAt: new Date("2026-10-01T00:00:00.000Z") }
- ]
+ [actorId, { actorType: ActorType.USER as const, actorId, lastReadAt: day("2026-10-01"), lastSecretReadAt }]
]);
- test("lists each reader who can read the value once, however many memberships give it", () => {
+ test("lists each reader who can read the value once, and judges only the non-admins", () => {
const summary = summarizeSecretAccess(
- activity(),
- access({ readersByRules: [[reader("direct")], [reader("direct"), reader("via-group")]] })
- );
- expect(ids(summary.entitled)).toEqual(["direct", "via-group"]);
- });
-
- test("leaves admins out of unused access", () => {
- const summary = summarizeSecretAccess(
- activity(),
- access({ readersByRules: [[reader("admin"), reader("direct")]], adminActorIds: new Set(["admin"]) })
+ activity({ trackedSince: judgedFrom }),
+ access({
+ readersByRules: [[reader("admin"), reader("direct")], [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"]);
});
- test("does not count a reader who read it, or who got access to it inside the judged period", () => {
+ test("does not count a reader who read it, whose access is newer than the judged period, or a secret that is", () => {
const summary = summarizeSecretAccess(
- activity({ reads: readBy("direct") }),
- access(datedAccess({ "via-group": new Date("2026-10-01T00:00:00.000Z") }))
+ activity({ trackedSince: judgedFrom, reads: readBy("direct") }),
+ access(datedAccess({ "via-group": oct }))
);
expect(summary.unread).toEqual([]);
- });
-
- test("still counts a reader whose sources all predate the judged period", () => {
- const summary = summarizeSecretAccess(
- activity(),
- access(datedAccess({ direct: new Date("2026-09-01T00:00:00.000Z") }))
- );
- expect(ids(summary.unread)).toEqual(["direct", "via-group"]);
- });
-
- test("drops a read from before the reader had access to the secret, and keeps one after", () => {
- const readOnOct1 = readBy("direct");
- const before = summarizeSecretAccess(
- activity({ reads: readOnOct1 }),
- access(datedAccess({ direct: new Date("2026-10-05T00:00:00.000Z") }))
- );
- expect(before.readsByActorKey.has(toActorKey(ActorType.USER, "direct"))).toBe(false);
- const after = summarizeSecretAccess(
- activity({ reads: readOnOct1 }),
- access(datedAccess({ direct: new Date("2026-09-20T00:00:00.000Z") }))
- );
- expect(after.readsByActorKey.get(toActorKey(ActorType.USER, "direct"))?.lastReadAt).toEqual(
- new Date("2026-10-01T00:00:00.000Z")
- );
- });
-
- test("keeps a read of the secret itself from before the reader's current access, such as before a role change", () => {
- const folderReadThenSecretRead = new Map([
- [
- toActorKey(ActorType.USER, "direct"),
- {
- actorType: ActorType.USER as const,
- actorId: "direct",
- lastReadAt: new Date("2026-10-02T00:00:00.000Z"),
- lastSecretReadAt: new Date("2026-10-01T00:00:00.000Z")
- }
- ]
- ]);
- const summary = summarizeSecretAccess(
- activity({ reads: folderReadThenSecretRead }),
- access(datedAccess({ direct: new Date("2026-10-05T00:00:00.000Z") }))
- );
- expect(summary.readsByActorKey.get(toActorKey(ActorType.USER, "direct"))?.lastReadAt).toEqual(
- new Date("2026-10-01T00:00:00.000Z")
+ expect(summarizeSecretAccess(activity({ trackedSince: oct }), access()).unread).toEqual([]);
+ expect(
+ ids(summarizeSecretAccess(activity({ trackedSince: judgedFrom }), access(datedAccess({ direct: sept }))).unread)
+ ).toEqual(["direct", "via-group"]);
+ });
+
+ test("drops a folder read from before the reader had access, but keeps a read of the secret itself", () => {
+ const before = summarizeSecretAccess(activity({ reads: readBy("direct") }), access(datedAccess({ direct: oct })));
+ expect(before.readsByActorId.has("direct")).toBe(false);
+ const after = summarizeSecretAccess(activity({ reads: readBy("direct") }), access(datedAccess({ direct: sept })));
+ expect(after.readsByActorId.get("direct")?.lastReadAt).toEqual(day("2026-10-01"));
+ const ofTheSecret = summarizeSecretAccess(
+ activity({ reads: readBy("direct", day("2026-09-20")) }),
+ access(datedAccess({ direct: oct }))
);
- });
-
- test("does not count a secret newer than the judged period", () => {
- const summary = summarizeSecretAccess(activity({ trackedSince: new Date("2026-10-01T00:00:00.000Z") }), access());
- expect(summary.unread).toEqual([]);
+ expect(ofTheSecret.readsByActorId.get("direct")?.lastReadAt).toEqual(day("2026-09-20"));
});
});
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,
- accessSince: new Date("2026-09-01T00:00:00.000Z"),
- judgedFrom,
+ accessSince: sept,
+ judgedFrom: day("2026-09-15"),
...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("is unused for a reader counted as unused access", () => {
- expect(status({ isUnused: true })).toEqual({ readStatus: SecretReadStatus.Unused, notJudgedReason: null });
+ const notJudged = (notJudgedReason: SecretReadNotJudgedReason) => ({
+ readStatus: SecretReadStatus.NotJudged,
+ notJudgedReason
});
- test("names why a reader without a read is not judged", () => {
- const notJudged = (notJudgedReason: SecretReadNotJudgedReason) => ({
- readStatus: SecretReadStatus.NotJudged,
- notJudgedReason
+ test("is read, unused, or not judged for one of three reasons", () => {
+ expect(status({ lastReadAt: oct, isProjectAdmin: true })).toEqual({
+ readStatus: SecretReadStatus.Read,
+ notJudgedReason: null
});
- expect(status({ isProjectAdmin: true, accessSince: new Date("2026-10-01T00:00:00.000Z") })).toEqual(
+ expect(status({ isUnused: true })).toEqual({ readStatus: SecretReadStatus.Unused, notJudgedReason: null });
+ expect(status({ isProjectAdmin: true, accessSince: oct })).toEqual(
notJudged(SecretReadNotJudgedReason.ProjectAdmin)
);
- expect(status({ accessSince: new Date("2026-10-01T00:00:00.000Z") })).toEqual(
- notJudged(SecretReadNotJudgedReason.AccessTooNew)
- );
+ expect(status({ accessSince: oct })).toEqual(notJudged(SecretReadNotJudgedReason.AccessTooNew));
expect(status()).toEqual(notJudged(SecretReadNotJudgedReason.SecretTooNew));
});
});
describe("createAccessDating", () => {
- const sept = new Date("2026-09-01T00:00:00.000Z");
- const oct = new Date("2026-10-20T00:00:00.000Z");
- const ability = (rules: Parameters<typeof createMongoAbility>[0]) =>
- createMongoAbility<MongoAbility<ProjectPermissionSet>>(rules as never);
- const readsProd = ability([
- {
- action: ProjectPermissionSecretActions.ReadValue,
- subject: ProjectPermissionSub.Secrets,
- conditions: { environment: "prod" }
- }
- ]);
- const readsAll = ability([
- { action: ProjectPermissionSecretActions.ReadValue, subject: ProjectPermissionSub.Secrets }
- ]);
- const secretIn = (environment: string, folderId: string): TSecretActivity => ({
- secret: { key: "DB_PASS", tags: [], folderId } as unknown as TSecretActivity["secret"],
- environment,
- secretPath: "/",
- trackedSince: sept,
- reads: new Map()
- });
- const dating = (sources: TAccessSource[], folderReopenedAt = new Map<string, Date>()) =>
- createAccessDating(new Map([["actor", sources]]), folderReopenedAt);
const actor = { actorId: "actor" };
-
- test("dates a secret from the oldest source that grants it, so a new source elsewhere changes nothing", () => {
+ const secretIn = (environment: string, folderId: string) =>
+ activity({ secret: { key: "DB_PASS", tags: [], folderId } as unknown as TSecretActivity["secret"], environment });
+ const dating = (
+ sources: TAccessSource[],
+ folderReopenedAt = new Map<string, Date>(),
+ accessReopenedAt = new Map<string, Date>()
+ ) => createAccessDating({ actor: sources }, folderReopenedAt, accessReopenedAt);
+
+ test("dates a secret from the oldest source that grants it on its own, else from the newest source", () => {
const { accessSinceOf, latestAccessChangeOf } = dating([
{ date: sept, permission: () => readsProd },
{ date: oct, permission: () => readsAll }
@@ -349,6 +247,11 @@ describe("createAccessDating", () => {
expect(accessSinceOf(actor, secretIn("prod", "f1"))).toEqual(sept);
expect(accessSinceOf(actor, secretIn("dev", "f1"))).toEqual(oct);
expect(latestAccessChangeOf(actor)).toEqual(oct);
+ const { accessSinceOf: noneGrants } = dating([
+ { date: sept, permission: () => ability([]) },
+ { date: oct, permission: () => ability([]) }
+ ]);
+ expect(noneGrants(actor, secretIn("prod", "f1"))).toEqual(oct);
});
test("only lets a folder grant reach secrets in its own folder", () => {
@@ -360,41 +263,22 @@ describe("createAccessDating", () => {
expect(accessSinceOf(actor, secretIn("dev", "granted"))).toEqual(oct);
});
- test("falls back to the newest source when no single source grants it", () => {
- const { accessSinceOf } = dating([
- { date: sept, permission: () => ability([]) },
- { date: oct, permission: () => ability([]) }
- ]);
- expect(accessSinceOf(actor, secretIn("prod", "f1"))).toEqual(oct);
- });
+ test("dates access no earlier than an ended restriction: an expired or edited folder grant in its folder, an expired temporary role anywhere", () => {
+ const expired = dating([{ date: sept, permission: () => readsAll }], new Map([["actor:held-back", oct]]));
+ expect(expired.accessSinceOf(actor, secretIn("prod", "held-back"))).toEqual(oct);
+ expect(expired.accessSinceOf(actor, secretIn("prod", "f1"))).toEqual(sept);
+ expect(expired.latestAccessChangeOf(actor)).toEqual(oct);
- test("dates access in a folder no earlier than an expired folder grant there", () => {
- const { accessSinceOf, latestAccessChangeOf } = dating(
- [{ date: sept, permission: () => readsAll }],
- new Map([["actor:held-back", oct]])
- );
- expect(accessSinceOf(actor, secretIn("prod", "held-back"))).toEqual(oct);
- expect(accessSinceOf(actor, secretIn("prod", "f1"))).toEqual(sept);
- expect(latestAccessChangeOf(actor)).toEqual(oct);
- });
-
- test("dates access in an edited folder grant's folder from the edit, since it may have held access back", () => {
- const { accessSinceOf } = dating([
+ const edited = dating([
{ date: sept, permission: () => readsAll },
{ date: oct, folderId: "granted", restartsFolder: true, permission: () => readsAll }
]);
- expect(accessSinceOf(actor, secretIn("prod", "granted"))).toEqual(oct);
- expect(accessSinceOf(actor, secretIn("prod", "f1"))).toEqual(sept);
- });
+ expect(edited.accessSinceOf(actor, secretIn("prod", "granted"))).toEqual(oct);
+ expect(edited.accessSinceOf(actor, secretIn("prod", "f1"))).toEqual(sept);
- test("dates all access no earlier than an expired temporary role or privilege", () => {
- const { accessSinceOf, latestAccessChangeOf } = createAccessDating(
- new Map([["actor", [{ date: sept, permission: () => readsAll }]]]),
- new Map(),
- new Map([["actor", oct]])
- );
- expect(accessSinceOf(actor, secretIn("prod", "f1"))).toEqual(oct);
- expect(latestAccessChangeOf(actor)).toEqual(oct);
+ const expiredRole = dating([{ date: sept, permission: () => readsAll }], new Map(), new Map([["actor", oct]]));
+ expect(expiredRole.accessSinceOf(actor, secretIn("prod", "f1"))).toEqual(oct);
+ expect(expiredRole.latestAccessChangeOf(actor)).toEqual(oct);
});
test("checks a source shared by many actors once per secret", () => {
@@ -404,10 +288,8 @@ describe("createAccessDating", () => {
return readsAll;
};
const { accessSinceOf } = createAccessDating(
- new Map([
- ["a", [{ date: sept, permission: shared }]],
- ["b", [{ date: sept, permission: shared }]]
- ]),
+ { a: [{ date: sept, permission: shared }], b: [{ date: sept, permission: shared }] },
+ new Map(),
new Map()
);
const secret = secretIn("prod", "f1");
@@ -418,9 +300,10 @@ describe("createAccessDating", () => {
});
describe("toUnusedAccessRoles", () => {
- test("names built-in roles after their predefined role and keeps a custom role's id and name", () => {
+ test("names built-in roles after their predefined role, keeps a custom role's id and name, and lists each once", () => {
expect(
toUnusedAccessRoles([
+ { role: ProjectMembershipRole.Member },
{ role: ProjectMembershipRole.Member },
{
role: ProjectMembershipRole.Custom,
@@ -434,10 +317,4 @@ describe("toUnusedAccessRoles", () => {
{ id: "role-1", slug: "custom", name: "Deployer" }
]);
});
-
- test("lists a role held twice once", () => {
- expect(
- toUnusedAccessRoles([{ role: ProjectMembershipRole.Viewer }, { role: ProjectMembershipRole.Viewer }])
- ).toEqual([{ id: null, slug: "viewer", name: "Viewer" }]);
- });
});
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 c8ff3dbea8..07764bc1d5 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
@@ -37,8 +37,6 @@ export const normalizeSecretPath = (secretPath: string) => removeTrailingSlash(p
export const toLocationKey = ({ environment, secretPath }: TSecretLocation) =>
`${environment}:${normalizeSecretPath(secretPath)}`;
-export const toActorKey = (actorType: string, actorId: string) => `${actorType}:${actorId}`;
-
export const SECRET_READ_ACTIVITY_WINDOW_DAYS = 30;
export const getReadActivityWindowStart = () => new Date(Date.now() - SECRET_READ_ACTIVITY_WINDOW_DAYS * DAY_IN_MS);
@@ -129,20 +127,21 @@ const subjectOf = ({ secret, environment, secretPath }: TSecretActivity) => ({
// since what it held back is not worked out). Sources are checked once per secret, shared ones (a role, a group)
// once for every actor holding them, and only the current secret's checks are kept.
export const createAccessDating = (
- sourcesByActorId: Map<string, TAccessSource[]>,
+ sourcesByActorId: Record<string, TAccessSource[]>,
folderReopenedAt: Map<string, Date>,
- accessReopenedAt = new Map<string, Date>()
+ accessReopenedAt: Map<string, Date>
): Pick<TProjectAccess, "accessSinceOf" | "latestAccessChangeOf"> => {
const latestByActorId = new Map<string, Date>();
const raise = (actorId: string, date?: Date) => {
const current = latestByActorId.get(actorId);
if (date && (!current || date > current)) latestByActorId.set(actorId, date);
};
- sourcesByActorId.forEach((sources, actorId) => sources.forEach((source) => raise(actorId, source.date)));
+ Object.entries(sourcesByActorId).forEach(([actorId, sources]) =>
+ sources.forEach((source) => raise(actorId, source.date))
+ );
folderReopenedAt.forEach((date, key) => raise(key.slice(0, key.indexOf(":")), date));
accessReopenedAt.forEach((date, actorId) => raise(actorId, date));
- const latestAccessChangeOf = ({ actorId }: { actorId: string }) => latestByActorId.get(actorId);
let checkedSecret: TSecretActivity | undefined;
let checks = new Map<unknown, boolean>();
@@ -163,23 +162,20 @@ export const createAccessDating = (
}
return granted;
};
- const sources = sourcesByActorId.get(actorId) ?? [];
+ const sources = sourcesByActorId[actorId] ?? [];
const grantingDates = sources.flatMap((source) => (source.date && grants(source) ? [source.date] : []));
+ const since = grantingDates.length
+ ? new Date(Math.min(...grantingDates.map((date) => date.getTime())))
+ : latestByActorId.get(actorId);
const floors = [
folderReopenedAt.get(`${actorId}:${activity.secret.folderId}`),
accessReopenedAt.get(actorId),
- ...sources.map((source) => (source.restartsFolder && inFolder(source) ? source.date : undefined))
+ ...sources.filter((source) => source.restartsFolder && inFolder(source)).map((source) => source.date)
];
- let since = grantingDates.length
- ? new Date(Math.min(...grantingDates.map((date) => date.getTime())))
- : latestByActorId.get(actorId);
- floors.forEach((floor) => {
- if (floor && (!since || floor > since)) since = floor;
- });
- return since;
+ return floors.reduce((latest, floor) => (floor && (!latest || floor > latest) ? floor : latest), since);
};
- return { accessSinceOf, latestAccessChangeOf };
+ return { accessSinceOf, latestAccessChangeOf: ({ actorId }) => latestByActorId.get(actorId) };
};
// Reads before trackedSince are ignored: the secret or its folder did not exist yet.
@@ -192,8 +188,7 @@ export const classifySecretReads = (
const record = (objectType: SecretReadObjectType, objectId: string) => {
(readsByObjectId[objectId] ?? []).forEach((read) => {
if (read.objectType !== objectType || read.lastReadAt < trackedSince) return;
- const key = toActorKey(read.actorType, read.actorId);
- const current = activity.get(key) ?? {
+ const current = activity.get(read.actorId) ?? {
actorType: read.actorType as TSecretReaderType,
actorId: read.actorId,
lastReadAt: read.lastReadAt
@@ -203,7 +198,7 @@ export const classifySecretReads = (
if (isOfTheSecret && (!current.lastSecretReadAt || read.lastReadAt > current.lastSecretReadAt)) {
current.lastSecretReadAt = read.lastReadAt;
}
- activity.set(key, current);
+ activity.set(read.actorId, current);
});
};
@@ -227,7 +222,7 @@ export const summarizeSecretAccess = (
hasSecretReadValueOrDescribePermission(permission, ProjectPermissionSecretActions.ReadValue, subject)
)
.flat(),
- (reader) => toActorKey(reader.actorType, reader.actorId)
+ (reader) => reader.actorId
);
const nonAdmins = entitled.filter((reader) => !adminActorIds.has(reader.actorId));
// Only a reader with a source newer than the judged period needs the per-secret date.
@@ -238,22 +233,19 @@ export const summarizeSecretAccess = (
// A folder read credits every secret in the folder, so one from before the reader had access to this secret did
// not return it; a read recorded against the secret itself did, so it always counts. A read after the reader's
// newest source change is after their access to every secret, so only an earlier one is checked.
- const readsByActorKey = new Map<string, TSecretReadResult>();
+ const readsByActorId = new Map<string, TSecretReadResult>();
entitled.forEach((reader) => {
- const key = toActorKey(reader.actorType, reader.actorId);
- const read = reads.get(key);
+ const read = reads.get(reader.actorId);
if (!read) return;
const latest = latestAccessChangeOf(reader);
const since = latest && read.lastReadAt < latest ? accessSinceOf(reader, activity) : undefined;
- if (!since || read.lastReadAt >= since) readsByActorKey.set(key, read);
- else if (read.lastSecretReadAt) readsByActorKey.set(key, { ...read, lastReadAt: read.lastSecretReadAt });
+ if (!since || read.lastReadAt >= since) readsByActorId.set(reader.actorId, read);
+ else if (read.lastSecretReadAt) readsByActorId.set(reader.actorId, { ...read, lastReadAt: read.lastSecretReadAt });
});
const unread = nonAdmins.filter(
- (reader) =>
- !readsByActorKey.has(toActorKey(reader.actorType, reader.actorId)) &&
- coversWholeWindow(trackedSince, accessSince(reader), judgedFrom)
+ (reader) => !readsByActorId.has(reader.actorId) && coversWholeWindow(trackedSince, accessSince(reader), judgedFrom)
);
- return { entitled, nonAdmins, unread, readsByActorKey };
+ return { entitled, nonAdmins, unread, readsByActorId };
};
// A reader without a read who is not unused access was left out for one of three reasons, checked in this order.
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 b215f093df..65349bfe24 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,23 +1,27 @@
import { setImmediate } from "node:timers/promises";
-import { createMongoAbility, MongoAbility } from "@casl/ability";
+import { createMongoAbility, ForbiddenError } from "@casl/ability";
-import { SecretFolderRole, SecretType, TableName } from "@app/db/schemas";
+import { ActionProjectType, SecretFolderRole, SecretType, TableName } from "@app/db/schemas";
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";
import {
buildFolderScopedPrivilegeRules,
hasSecretReadValueOrDescribePermission,
throwIfMissingSecretReadValueOrDescribePermission
} from "@app/ee/services/permission/permission-fns";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
-import { ProjectPermissionSecretActions, ProjectPermissionSet } from "@app/ee/services/permission/project-permission";
+import {
+ ProjectPermissionInsightsActions,
+ ProjectPermissionSecretActions,
+ ProjectPermissionSet,
+ ProjectPermissionSub
+} from "@app/ee/services/permission/project-permission";
import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";
import { getCacheTtl, withCache } from "@app/lib/cache/with-cache";
import { conditionsMatcher } from "@app/lib/casl";
import { NotFoundError } from "@app/lib/errors";
-import { groupBy } from "@app/lib/fn";
+import { groupBy, unique } from "@app/lib/fn";
import { logger } from "@app/lib/logger";
import { OrgServiceActor } from "@app/lib/types";
import { ActorType } from "@app/services/auth/auth-type";
@@ -43,17 +47,14 @@ import {
indexSecretReads,
loadProjectFolderTree,
summarizeSecretAccess,
- toActorKey,
toLocationKey,
toUnusedAccessRoles
} from "./secret-read-activity-fns";
import { TSecretReadActivityQueueServiceFactory } from "./secret-read-activity-queue";
import {
- TAccessSource,
TGetSecretReadActivityDTO,
TGetUnusedAccessActorDTO,
TListUnusedAccessDTO,
- TProjectReader,
TReachSecret,
TReadActivityScope,
TSecretActivity,
@@ -76,6 +77,14 @@ const UNUSED_ACCESS_COMPUTE_WAIT_SECONDS = 60;
const UNUSED_ACCESS_DETAIL_MAX_ACTORS = 200;
const UNUSED_ACCESS_MAX_SECRETS_PER_ACTOR = 200;
+const once = <T>(build: () => T) => {
+ let value: T | undefined;
+ return () => {
+ value ??= build();
+ return value;
+ };
+};
+
type TSecretReadActivityServiceFactoryDep = {
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getProjectPermissions">;
secretReadActivityDAL: Pick<
@@ -116,6 +125,23 @@ export const secretReadActivityServiceFactory = ({
kmsService,
keyStore
}: TSecretReadActivityServiceFactoryDep) => {
+ // The permission alone, not the plan: a downgrade must not hide reads already collected.
+ const $getInsightsPermission = async (projectId: string, actor: OrgServiceActor) => {
+ const { permission } = await permissionService.getProjectPermission({
+ actor: actor.type,
+ actorId: actor.id,
+ projectId,
+ actorAuthMethod: actor.authMethod,
+ actorOrgId: actor.orgId,
+ actionProjectType: ActionProjectType.SecretManager
+ });
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionInsightsActions.Read,
+ ProjectPermissionSub.Insights
+ );
+ return permission;
+ };
+
let instanceTrackingStartedAt: Promise<Date | undefined> | undefined;
const $getTrackingStartedAt = () => {
instanceTrackingStartedAt ??= secretReadActivityDAL.findTrackingStartedAt().catch((error) => {
@@ -289,32 +315,29 @@ export const secretReadActivityServiceFactory = ({
};
};
- // The username and metadata of people the project permissions did not load, to fill placeholders in group roles.
- const $findActorDetails = async (
+ // The name, and when asked the metadata, of the users and identities the project permissions did not load.
+ const $findActors = async (
orgId: string,
- actors: { actorType: TSecretReaderType; actorId: string }[]
- ): Promise<Map<string, { username: string; metadata: { key: string; value: string }[] }>> => {
+ actors: { actorType: TSecretReaderType; actorId: string }[],
+ withMetadata: boolean
+ ) => {
const idsOf = (actorType: TSecretReaderType) =>
actors.filter((actor) => actor.actorType === actorType).map((actor) => actor.actorId);
const [userIds, identityIds] = [idsOf(ActorType.USER), idsOf(ActorType.IDENTITY)];
const [users, identities, userMetadata, identityMetadata] = await Promise.all([
userIds.length ? userDAL.find({ $in: { id: userIds } }) : [],
identityIds.length ? identityDAL.find({ $in: { id: identityIds } }) : [],
- userIds.length ? identityMetadataDAL.find({ orgId, $in: { userId: userIds } }) : [],
+ withMetadata && userIds.length ? identityMetadataDAL.find({ orgId, $in: { userId: userIds } }) : [],
// An identity's metadata lives under the org that owns it, which a linked group's child org is not, so it is
// loaded by identity alone, as getProjectPermission does.
- identityIds.length ? identityMetadataDAL.find({ $in: { identityId: identityIds } }) : []
+ withMetadata && identityIds.length ? identityMetadataDAL.find({ $in: { identityId: identityIds } }) : []
]);
const metadataByUserId = groupBy(userMetadata, (row) => row.userId ?? "");
const metadataByIdentityId = groupBy(identityMetadata, (row) => row.identityId ?? "");
- const toPairs = (rows: { key: string; value: string }[] = []) => rows.map(({ key, value }) => ({ key, value }));
return new Map([
- ...users.map(
- (user) => [user.id, { username: user.username, metadata: toPairs(metadataByUserId[user.id]) }] as const
- ),
+ ...users.map((user) => [user.id, { name: user.username, metadata: metadataByUserId[user.id] ?? [] }] as const),
...identities.map(
- (identity) =>
- [identity.id, { username: identity.name, metadata: toPairs(metadataByIdentityId[identity.id]) }] as const
+ (identity) => [identity.id, { name: identity.name, metadata: metadataByIdentityId[identity.id] ?? [] }] as const
)
]);
};
@@ -352,107 +375,96 @@ export const secretReadActivityServiceFactory = ({
const groupMembers = [
...userGroupMemberships.map(({ groupId, userId, createdAt }) => ({
groupId,
- actorType: ActorType.USER,
+ actorType: ActorType.USER as const,
actorId: userId,
joinedAt: createdAt
})),
...identityGroupMemberships.map(({ groupId, identityId, createdAt }) => ({
groupId,
- actorType: ActorType.IDENTITY,
+ actorType: ActorType.IDENTITY as const,
actorId: identityId,
joinedAt: createdAt
}))
- ].flatMap(({ groupId, actorType, actorId, joinedAt }) => {
+ ].flatMap(({ groupId, ...member }) => {
const group = groupById.get(groupId);
- return group ? [{ group, actorType: actorType as TSecretReaderType, actorId, joinedAt }] : [];
+ return group ? [{ ...member, group }] : [];
});
- const people = new Map<string, { actorType: TSecretReaderType; actorId: string; groupIds: string[] }>();
- const personOf = (actorType: TSecretReaderType, actorId: string) => {
- const key = toActorKey(actorType, actorId);
- const person = people.get(key) ?? { actorType, actorId, groupIds: [] };
- people.set(key, person);
- return person;
+ const groupMembershipsByActorId = groupBy(groupMembers, (member) => member.actorId);
+ const directMembers = new Map([...userPermissions, ...identityPermissions].map((member) => [member.id, member]));
+ const actors = unique(
+ [
+ ...userPermissions.map(({ id }) => ({ actorType: ActorType.USER as const, actorId: id })),
+ ...identityPermissions.map(({ id }) => ({ actorType: ActorType.IDENTITY as const, actorId: id })),
+ ...groupMembers.map(({ actorType, actorId }) => ({ actorType, actorId }))
+ ],
+ (actor) => actor.actorId
+ );
+
+ // Direct members come named, with the details that fill a placeholder such as {{identity.username}}. People only
+ // in through a group are looked up, their details only when a group role holds a placeholder.
+ const others = await $findActors(
+ orgId,
+ actors.filter((actor) => !directMembers.has(actor.actorId)),
+ groupRulesHavePlaceholders
+ );
+ const nameOf = (actorId: string) => directMembers.get(actorId)?.name ?? others.get(actorId)?.name ?? actorId;
+ const detailsOf = (actorId: string) => {
+ const other = others.get(actorId);
+ return other && { username: other.name, metadata: other.metadata };
};
- userPermissions.forEach(({ id }) => personOf(ActorType.USER, id));
- identityPermissions.forEach(({ id }) => personOf(ActorType.IDENTITY, id));
- groupMembers.forEach(({ group, actorType, actorId }) => personOf(actorType, actorId).groupIds.push(group.id));
-
- // A placeholder such as {{identity.username}} is filled from the person's own details. Direct members' details
- // come with the permissions; those of people only in through a group are looked up, and only when a group role
- // holds a placeholder.
- const directMemberIds = new Set([...userPermissions, ...identityPermissions].map(({ id }) => id));
- const groupOnly = [...people.values()].filter((person) => !directMemberIds.has(person.actorId));
- const detailsByActorId = groupRulesHavePlaceholders
- ? await $findActorDetails(orgId, groupOnly)
- : new Map<string, { username: string; metadata: { key: string; value: string }[] }>();
- const readers: TProjectReader[] = [...people.values()].map(({ actorType, actorId, groupIds: memberOf }) => ({
+ const groupIdsOf = (actorId: string) => (groupMembershipsByActorId[actorId] ?? []).map(({ group }) => group.id);
+ const readers = actors.map(({ actorType, actorId }) => ({
actorType,
actorId,
- permission: permissionForActor({ actorId, groupIds: memberOf, ...detailsByActorId.get(actorId) })
+ permission: permissionForActor({ actorId, groupIds: groupIdsOf(actorId), ...detailsOf(actorId) })
}));
// Every source of each actor's access with its date: their own roles and project-wide privileges, each group
- // they are in (dated from joining it or from the group's own role change, whichever is later), and their folder
- // grants. The permissions are built only for an actor whose access needs dating per secret.
- const sourcesByActorId = new Map<string, TAccessSource[]>();
- const addSources = (actorId: string, sources: TAccessSource[]) =>
- sourcesByActorId.set(actorId, [...(sourcesByActorId.get(actorId) ?? []), ...sources]);
- [...userPermissions, ...identityPermissions].forEach((member) => {
- const permissionOf = (key: string) => () =>
- (member.accessSources().find((source) => source.key === key) ?? { permission: member.permission }).permission;
- addSources(member.id, [
- ...member.roles.map((role) => ({
- date: sourceDates.roleDates.get(role.id),
- permission: permissionOf(`role:${role.id}`)
- })),
- ...member.additionalPrivileges.map((privilege) => ({
- date: sourceDates.privilegeDates.get(privilege.id),
- permission: permissionOf(`privilege:${privilege.id}`)
- }))
- ]);
- });
- // A group on its own, with the member's details filled into its placeholders. Built once, on first use.
- groupMembers.forEach(({ group, actorId, joinedAt }) => {
- const groupChangedAt = sourceDates.groupDates.get(group.id);
- let permission: MongoAbility<ProjectPermissionSet> | undefined;
- addSources(actorId, [
- {
+ // they are in (dated from joining it or from the group's own role change, whichever is later, with their details
+ // filled into its placeholders), and their folder grants. A permission is built on first use.
+ const sources = [
+ ...[...directMembers.values()].flatMap((member) => {
+ const sourceOf = (key: string) => () =>
+ member.accessSources().find((source) => source.key === key)?.permission ?? member.permission;
+ return [
+ ...member.roles.map((role) => ({
+ actorId: member.id,
+ date: sourceDates.roleDates.get(role.id),
+ permission: sourceOf(`role:${role.id}`)
+ })),
+ ...member.additionalPrivileges.map((privilege) => ({
+ actorId: member.id,
+ date: sourceDates.privilegeDates.get(privilege.id),
+ permission: sourceOf(`privilege:${privilege.id}`)
+ }))
+ ];
+ }),
+ ...groupMembers.map(({ group, actorId, joinedAt }) => {
+ const groupChangedAt = sourceDates.groupDates.get(group.id);
+ return {
+ actorId,
date: groupChangedAt && groupChangedAt > joinedAt ? groupChangedAt : joinedAt,
- permission: () => {
- permission ??= permissionForActor({
- actorId,
- groupIds: [group.id],
- groupsOnly: true,
- ...detailsByActorId.get(actorId)
- });
- return permission;
- }
- }
- ]);
- });
- folderAccessByActorId.forEach((grants, actorId) => {
- addSources(
- actorId,
- grants.map((grant) => {
- let permission: MongoAbility<ProjectPermissionSet> | undefined;
- return {
- date: sourceDates.privilegeDates.get(grant.id),
- folderId: grant.folderId,
- restartsFolder: sourceDates.editedPrivilegeIds.has(grant.id),
- permission: () => {
- permission ??= createMongoAbility<ProjectPermissionSet>(buildFolderScopedPrivilegeRules([grant]), {
- conditionsMatcher
- });
- return permission;
- }
- };
- })
- );
- });
+ permission: once(() =>
+ permissionForActor({ actorId, groupIds: [group.id], groupsOnly: true, ...detailsOf(actorId) })
+ )
+ };
+ }),
+ ...[...folderAccessByActorId].flatMap(([actorId, grants]) =>
+ grants.map((grant) => ({
+ actorId,
+ date: sourceDates.privilegeDates.get(grant.id),
+ folderId: grant.folderId,
+ restartsFolder: sourceDates.editedPrivilegeIds.has(grant.id),
+ permission: once(() =>
+ createMongoAbility<ProjectPermissionSet>(buildFolderScopedPrivilegeRules([grant]), { conditionsMatcher })
+ )
+ }))
+ )
+ ];
// A group's expired temporary role reached each of its members.
- const accessReopenedAt = new Map<string, Date>();
const membersByGroupId = groupBy(groupMembers, (member) => member.group.id);
+ const accessReopenedAt = new Map<string, Date>();
sourceDates.accessReopenedAt.forEach((date, holderId) => {
(membersByGroupId[holderId]?.map((member) => member.actorId) ?? [holderId]).forEach((actorId) => {
const current = accessReopenedAt.get(actorId);
@@ -463,41 +475,24 @@ export const secretReadActivityServiceFactory = ({
return {
readersByRules: Object.values(groupBy(readers, (reader) => JSON.stringify(reader.permission.rules))),
adminActorIds,
- ...createAccessDating(sourcesByActorId, sourceDates.folderReopenedAt, accessReopenedAt),
+ ...createAccessDating(
+ groupBy(sources, (source) => source.actorId),
+ sourceDates.folderReopenedAt,
+ accessReopenedAt
+ ),
judgedFrom: trackingStartedAt > windowStart ? trackingStartedAt : windowStart,
- directMembers: new Map([
- ...userPermissions.map((member) => [toActorKey(ActorType.USER, member.id), member] as const),
- ...identityPermissions.map((member) => [toActorKey(ActorType.IDENTITY, member.id), member] as const)
- ]),
- groupMembershipsByActorKey: groupBy(groupMembers, (member) => toActorKey(member.actorType, member.actorId)),
+ nameOf,
+ directMembers,
+ groupMembershipsByActorId,
folderAccessByActorId
};
};
- // 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 }>
- ) => {
- const others = actors.filter((actor) => !directMembers.has(toActorKey(actor.actorType, actor.actorId)));
- const userIds = [...new Set(others.filter((a) => a.actorType === ActorType.USER).map((a) => a.actorId))];
- const identityIds = [...new Set(others.filter((a) => a.actorType === ActorType.IDENTITY).map((a) => a.actorId))];
- const [users, identities] = await Promise.all([
- userIds.length ? userDAL.find({ $in: { id: userIds } }) : [],
- identityIds.length ? identityDAL.find({ $in: { id: identityIds } }) : []
- ]);
- return new Map([
- ...[...directMembers].map(([key, member]) => [key, member.name] as const),
- ...users.map((user) => [toActorKey(ActorType.USER, user.id), user.username] as const),
- ...identities.map((identity) => [toActorKey(ActorType.IDENTITY, identity.id), identity.name] as const)
- ]);
- };
-
const getSecretReadActivity = async (
{ projectId, environment, secretPath, secretName }: TGetSecretReadActivityDTO,
actor: OrgServiceActor
) => {
- const { permission } = await checkInsightsReadPermission(permissionService, projectId, actor);
+ const permission = await $getInsightsPermission(projectId, actor);
// The secret is checked before the reach is built, which decrypts every secret that could reference it.
const tree = await loadProjectFolderTree({ folderDAL, projectEnvDAL }, projectId);
@@ -531,26 +526,24 @@ export const secretReadActivityServiceFactory = ({
message: `Secret with name '${secretName}' not found at path '${secretPath}' in environment '${environment}'`
});
}
- const { entitled, unread, readsByActorKey } = summarizeSecretAccess(activity, access);
- const unusedKeys = new Set(unread.map((reader) => toActorKey(reader.actorType, reader.actorId)));
- const names = await $findActorNames(entitled, access.directMembers);
+ const { entitled, unread, readsByActorId } = summarizeSecretAccess(activity, access);
+ const unusedActorIds = new Set(unread.map((reader) => reader.actorId));
const actors = entitled.map((reader): TSecretReadActivityActor => {
- const key = toActorKey(reader.actorType, reader.actorId);
- const lastReadAt = readsByActorKey.get(key)?.lastReadAt ?? null;
+ const lastReadAt = readsByActorId.get(reader.actorId)?.lastReadAt ?? null;
const isProjectAdmin = access.adminActorIds.has(reader.actorId);
// Every reader has at least one dated source; without one, access is as old as the secret's tracked period.
const accessSince = access.accessSinceOf(reader, activity) ?? activity.trackedSince;
return {
actorType: reader.actorType,
actorId: reader.actorId,
- name: names.get(key) ?? reader.actorId,
+ name: access.nameOf(reader.actorId),
isProjectAdmin,
lastReadAt,
accessSince,
...getReadStatus({
lastReadAt,
- isUnused: unusedKeys.has(key),
+ isUnused: unusedActorIds.has(reader.actorId),
isProjectAdmin,
accessSince,
judgedFrom: access.judgedFrom
@@ -580,8 +573,7 @@ export const secretReadActivityServiceFactory = ({
await setImmediate();
const { nonAdmins, unread } = summarizeSecretAccess(activity, access);
nonAdmins.forEach(({ actorType, actorId }) => {
- const key = toActorKey(actorType, actorId);
- const tally = tallies.get(key) ?? {
+ const tally = tallies.get(actorId) ?? {
actorType,
actorId,
accessibleSecretCount: 0,
@@ -590,11 +582,11 @@ export const secretReadActivityServiceFactory = ({
environments: new Set()
};
tally.accessibleSecretCount += 1;
- tallies.set(key, tally);
+ tallies.set(actorId, 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;
+ unread.forEach(({ actorId }) => {
+ const tally = tallies.get(actorId) as TUnusedAccessTally;
tally.unusedSecretCount += 1;
tally.environments.add(activity.environment);
if (tally.unusedSecretIds.length < UNUSED_ACCESS_MAX_SECRETS_PER_ACTOR) {
@@ -612,21 +604,19 @@ export const secretReadActivityServiceFactory = ({
const ranked = [...tallies.values()]
.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 => {
- const key = toActorKey(tally.actorType, tally.actorId);
- const member = access.directMembers.get(key);
+ const member = access.directMembers.get(tally.actorId);
return {
actorType: tally.actorType,
actorId: tally.actorId,
- name: names.get(key) ?? tally.actorId,
+ name: access.nameOf(tally.actorId),
accessibleSecretCount: tally.accessibleSecretCount,
unusedSecretCount: tally.unusedSecretCount,
environments: [...tally.environments].sort(),
accessPaths: {
roles: toUnusedAccessRoles(member?.roles ?? []),
- groups: (access.groupMembershipsByActorKey[key] ?? []).map(({ group }) => ({
+ groups: (access.groupMembershipsByActorId[tally.actorId] ?? []).map(({ group }) => ({
id: group.id,
name: group.name,
roles: toUnusedAccessRoles(group.roles)
@@ -647,9 +637,7 @@ export const secretReadActivityServiceFactory = ({
// The unread secrets themselves are kept for the actors with the most of them, so the sheet lists them without
// another scan; anyone further down is scanned for on their own when opened.
const details = Object.fromEntries(
- ranked
- .slice(0, UNUSED_ACCESS_DETAIL_MAX_ACTORS)
- .map((tally) => [toActorKey(tally.actorType, tally.actorId), tally.unusedSecretIds])
+ ranked.slice(0, UNUSED_ACCESS_DETAIL_MAX_ACTORS).map((tally) => [tally.actorId, tally.unusedSecretIds])
);
return { rows, details, periodStart: access.judgedFrom };
};
@@ -709,7 +697,7 @@ export const secretReadActivityServiceFactory = ({
{ projectId, offset, limit, search }: TListUnusedAccessDTO,
actor: OrgServiceActor
) => {
- await checkInsightsReadPermission(permissionService, projectId, actor);
+ await $getInsightsPermission(projectId, actor);
const { rows, ...tracking } = await $getCachedUnusedAccess(projectId, actor.orgId);
const needle = search?.trim().toLowerCase();
const matching = needle ? rows.filter((row) => row.name.toLowerCase().includes(needle)) : rows;
@@ -726,7 +714,7 @@ export const secretReadActivityServiceFactory = ({
{ projectId, actorType, actorId }: TGetUnusedAccessActorDTO,
actor: OrgServiceActor
) => {
- const { permission } = await checkInsightsReadPermission(permissionService, projectId, actor);
+ const permission = await $getInsightsPermission(projectId, actor);
const { rows, details, ...tracking } = await $getCachedUnusedAccess(projectId, actor.orgId);
const unusedAccessActor = rows.find((row) => row.actorType === actorType && row.actorId === actorId);
if (!unusedAccessActor) {
@@ -734,15 +722,15 @@ export const secretReadActivityServiceFactory = ({
message: `No unused access found for ${actorType} '${actorId}' in this project`
});
}
- const key = toActorKey(actorType, actorId);
// An actor past those cached in full is scanned for on its own, and kept for the same day.
const secretIds =
- details[key] ??
+ details[actorId] ??
(await withCache({
keyStore,
- key: KeyStorePrefixes.InsightsCache(projectId, `unused-access:${key}`),
+ key: KeyStorePrefixes.InsightsCache(projectId, `unused-access:${actorType}:${actorId}`),
ttlSeconds: UNUSED_ACCESS_CACHE_TTL_SECONDS,
- fetcher: async () => (await $tallyUnusedAccess(projectId, actor.orgId)).tallies.get(key)?.unusedSecretIds ?? []
+ fetcher: async () =>
+ (await $tallyUnusedAccess(projectId, actor.orgId)).tallies.get(actorId)?.unusedSecretIds ?? []
}));
// The cache is shared by everyone in the project and can be a day old, so each listed secret is checked against
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 f6ac169778..d3aee19b6c 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
@@ -118,6 +118,7 @@ export type TReadActivityScope = {
export type TSecretActivity = TSecretLocation & {
secret: Awaited<ReturnType<TSecretV2BridgeDALFactory["find"]>>[number];
trackedSince: Date;
+ // Each reader's latest read of the secret, by actor id.
reads: Map<string, TSecretReadResult>;
};
@@ -152,9 +153,9 @@ export type TSecretAccessSummary = {
entitled: TProjectReader[];
nonAdmins: TProjectReader[];
unread: TProjectReader[];
- // The latest read of each entitled reader, keyed by actor, leaving out a read from before they had access to the
- // secret: a folder read then could not have returned it.
- readsByActorKey: Map<string, TSecretReadResult>;
+ // The latest read of each entitled reader, leaving out a read from before they had access to the secret: a
+ // folder read then could not have returned it.
+ readsByActorId: Map<string, TSecretReadResult>;
};
export enum SecretReadStatus {
@@ -218,6 +219,7 @@ export type TUnusedAccessTally = {
export type TUnusedAccessSummary = {
rows: TUnusedAccessActor[];
+ // The unused secret ids of the top actors, by actor id.
details: Record<string, string[]>;
// Unused means no read since this date: 30 days before the computation, or when tracking began if later.
periodStart: Date;
diff --git a/backend/src/services/secret-v2-bridge/secret-reference-fns.test.ts b/backend/src/services/secret-v2-bridge/secret-reference-fns.test.ts
index 8cffbc60f1..dedf25f4d4 100644
--- a/backend/src/services/secret-v2-bridge/secret-reference-fns.test.ts
+++ b/backend/src/services/secret-v2-bridge/secret-reference-fns.test.ts
@@ -256,18 +256,15 @@ describe("expandSecretReferencesFactory onSecretExpanded", () => {
return { expanded, reported };
};
- it("reports the reader's own override, not the shared secret it replaced", async () => {
+ it("reports the secret each reference resolved to, the reader's own override included", async () => {
const rows = [row("shared-db", "DB_PASSWORD", "shared"), row("alice-db", "DB_PASSWORD", "mine", "alice")];
- const result = await expand(rows, `postgres://\${DB_PASSWORD}@db`, { userId: "alice" });
- expect(result).toEqual({
+ const asAlice = await expand(rows, `postgres://\${DB_PASSWORD}@db`, { userId: "alice" });
+ expect(asAlice).toEqual({
expanded: "postgres://mine@db",
reported: [{ secretKey: "URL", referencedSecretIds: ["alice-db"] }]
});
- });
-
- it("reports the shared secret when no override is used", async () => {
- const result = await expand([row("shared-db", "DB_PASSWORD", "shared")], `postgres://\${DB_PASSWORD}@db`);
- expect(result.reported).toEqual([{ secretKey: "URL", referencedSecretIds: ["shared-db"] }]);
+ const shared = await expand(rows.slice(0, 1), `postgres://\${DB_PASSWORD}@db`);
+ expect(shared.reported).toEqual([{ secretKey: "URL", referencedSecretIds: ["shared-db"] }]);
});
it("reports nothing for an expansion that fails part way", async () => {
diff --git a/frontend/src/components/secrets/SecretAccessGraph/buildAccessGraph.test.ts b/frontend/src/components/secrets/SecretAccessGraph/buildAccessGraph.test.ts
index 92e46af0f1..2555e10a0f 100644
--- a/frontend/src/components/secrets/SecretAccessGraph/buildAccessGraph.test.ts
+++ b/frontend/src/components/secrets/SecretAccessGraph/buildAccessGraph.test.ts
@@ -58,16 +58,6 @@ describe("buildAccessGraph", () => {
const readerNode = (type: "user" | "identity", id: string) =>
nodeById.get(readerNodeId({ type, id }))!;
- test("lays readers and the secret out in two columns, with no other boxes", () => {
- const secret = nodeById.get(SECRET_NODE_ID)!;
- input.readers.forEach((entry) => {
- expect(readerNode(entry.type, entry.id).position.x).toBeLessThan(secret.position.x);
- });
- expect(nodes.every((node) => ["reader", "secret", "bandLabel"].includes(node.type ?? ""))).toBe(
- true
- );
- });
-
test("puts unused access first, then readers too new to judge, then readers, then admins", () => {
const order = [...input.readers]
.sort((a, b) => readerNode(a.type, a.id).position.y - readerNode(b.type, b.id).position.y)
@@ -76,7 +66,9 @@ describe("buildAccessGraph", () => {
});
test("gives every reader one line to the secret, and names every group on the node", () => {
+ const secret = nodeById.get(SECRET_NODE_ID)!;
input.readers.forEach((entry) => {
+ expect(readerNode(entry.type, entry.id).position.x).toBeLessThan(secret.position.x);
const lines = edges.filter((edge) => edge.source === readerNodeId(entry));
expect(lines.map((edge) => edge.target)).toEqual([SECRET_NODE_ID]);
});
diff --git a/frontend/src/hooks/api/secretInsights/queries.tsx b/frontend/src/hooks/api/secretInsights/queries.tsx
index d07034a58f..a6070c4bd2 100644
--- a/frontend/src/hooks/api/secretInsights/queries.tsx
+++ b/frontend/src/hooks/api/secretInsights/queries.tsx
@@ -194,9 +194,17 @@ export const useGetUnusedAccessActor = (
export const useGetSecretReadActivity = (
params: TGetSecretReadActivityDTO,
- options?: { enabled?: boolean }
-) =>
- useQuery({
+ options?: Omit<
+ UseQueryOptions<
+ TSecretReadActivity,
+ unknown,
+ TSecretReadActivity,
+ ReturnType<typeof secretInsightsKeys.secretReadActivity>
+ >,
+ "queryKey" | "queryFn"
+ >
+) => {
+ return useQuery({
queryKey: secretInsightsKeys.secretReadActivity(params),
queryFn: async () => {
const { data } = await apiRequest.get<{ readActivity: TSecretReadActivity }>(
@@ -205,8 +213,9 @@ export const useGetSecretReadActivity = (
);
return data.readActivity;
},
- enabled: Boolean(params.secretKey) && (options?.enabled ?? true)
+ ...options
});
+};
export const useGetAuthMethodDistribution = (
params: TGetAuthMethodDistributionDTO,
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 8a07f7f23c..e2061c2bef 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/SecretAccessInsights.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/SecretAccessInsights.tsx
@@ -111,7 +111,6 @@ type Props = {
secretKey: string;
environment: string;
secretPath: string;
- defaultView?: AccessView;
};
type AccessView = "graph" | "table";
@@ -433,12 +432,7 @@ function AddMemberPopover({
);
}
-export function SecretAccessInsights({
- secretKey,
- environment,
- secretPath,
- defaultView = "graph"
-}: Props) {
+export function SecretAccessInsights({ secretKey, environment, secretPath }: Props) {
const { currentOrg } = useOrganization();
const { currentProject } = useProject();
const { permission } = useProjectPermission();
@@ -448,7 +442,7 @@ export function SecretAccessInsights({
const [searchFilter, setSearchFilter] = useState("");
const [typeFilters, setTypeFilters] = useState<Set<AccessRowType>>(() => new Set());
const [showAllEntities, setShowAllEntities] = useState(true);
- const [view, setView] = useState<AccessView>(defaultView);
+ const [view, setView] = useState<AccessView>("graph");
const toggleTypeFilter = (type: AccessRowType) => {
setTypeFilters((prev) => {
@@ -510,15 +504,14 @@ export function SecretAccessInsights({
{ enabled: canReadInsights }
);
const readActors = useMemo(
- () =>
- new Map(readActivity?.actors.map((actor) => [`${actor.actorType}:${actor.actorId}`, actor])),
+ () => new Map(readActivity?.actors.map((actor) => [actor.actorId, actor])),
[readActivity]
);
// 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 => {
+ const readStatusOf = (actorId: string): TReaderReadStatus | undefined => {
if (!readActivity) return undefined;
- const actor = readActors.get(`${type}:${id}`);
+ const actor = readActors.get(actorId);
if (actor?.readStatus === SecretReadStatus.Read && actor.lastReadAt) {
return { kind: "read", lastReadAt: actor.lastReadAt };
}
@@ -558,70 +551,44 @@ export function SecretAccessInsights({
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.
+ // Every reader who can read the value, directly or through a group, with one line each to the secret. The read
+ // activity names them exactly, with each member's own folder grants applied to what a group gives them; without
+ // it, the access list decides, judging a group on its roles alone.
const graphInput = useMemo<TAccessGraphInput | undefined>(() => {
if (!secretAccessList) return undefined;
const groups = secretAccessList.groups.filter((group) => grantsReadValue(group.allowedActions));
- const toReader = (
- entry: SecretAccessListEntry,
- type: "user" | "identity",
- memberField: "userIds" | "identityIds"
- ) => {
- const isDirect = grantsReadValue(entry.allowedActions);
- const groupIds = groups
- .filter((group) => group[memberField].includes(entry.id))
- .map((group) => group.id);
- if (!isDirect && !groupIds.length) return [];
- // The access list judges a group on its roles alone, but a member's own folder grant also limits what the group
- // gives them. The read activity applies those grants, so once it has loaded it decides who is drawn.
- if (readActivity && !readActors.has(`${type}:${entry.id}`)) return [];
- const status = readStatusOf(type, entry.id);
- return [
- {
- id: entry.id,
- name: entry.name,
- type,
- isDirect,
- groupIds,
- isAdmin: readActors.get(`${type}:${entry.id}`)?.isProjectAdmin ?? false,
- lastReadAt: status?.kind === "read" ? status.lastReadAt : undefined,
- unreadSince: status?.kind === "unread" ? status.since : undefined
- }
- ];
- };
- const directReaders = [
- ...secretAccessList.users.flatMap((user) => toReader(user, "user", "userIds")),
- ...secretAccessList.identities.flatMap((identity) =>
- toReader(identity, "identity", "identityIds")
- )
+ const entries = [
+ ...secretAccessList.users.map((entry) => ({ type: "user" as const, entry })),
+ ...secretAccessList.identities.map((entry) => ({ type: "identity" as const, entry }))
];
- // Members who have the value only through a group are not in the access list's users or identities, but
- // the read activity names everyone who can read the value, so they are drawn from it.
- const listed = new Set([
- ...secretAccessList.users.map((user) => `user:${user.id}`),
- ...secretAccessList.identities.map((identity) => `identity:${identity.id}`)
- ]);
- const groupOnlyReaders = (readActivity?.actors ?? []).flatMap((reader) => {
- if (listed.has(`${reader.actorType}:${reader.actorId}`)) return [];
- const memberField = reader.actorType === "user" ? "userIds" : "identityIds";
- const groupIds = groups
- .filter((group) => group[memberField].includes(reader.actorId))
+ const entryById = new Map(entries.map(({ entry }) => [entry.id, entry]));
+ const isDirect = (id: string) => grantsReadValue(entryById.get(id)?.allowedActions ?? []);
+ const groupIdsOf = (type: "user" | "identity", id: string) =>
+ groups
+ .filter((group) => (type === "user" ? group.userIds : group.identityIds).includes(id))
.map((group) => group.id);
- const status = readStatusOf(reader.actorType, reader.actorId);
- return [
- {
- id: reader.actorId,
- name: reader.name,
- type: reader.actorType,
- isDirect: false,
- groupIds,
- isAdmin: reader.isProjectAdmin,
- lastReadAt: status?.kind === "read" ? status.lastReadAt : undefined,
- unreadSince: status?.kind === "unread" ? status.since : undefined
- }
- ];
- });
- const readers = [...directReaders, ...groupOnlyReaders];
+ const toReader = (type: "user" | "identity", id: string, name: string, isAdmin: boolean) => {
+ const status = readStatusOf(id);
+ return {
+ id,
+ name,
+ type,
+ isDirect: isDirect(id),
+ groupIds: groupIdsOf(type, id),
+ isAdmin,
+ lastReadAt: status?.kind === "read" ? status.lastReadAt : undefined,
+ unreadSince: status?.kind === "unread" ? status.since : undefined
+ };
+ };
+ const readers = readActivity
+ ? readActivity.actors.map((actor) =>
+ toReader(actor.actorType, actor.actorId, actor.name, actor.isProjectAdmin)
+ )
+ : entries.flatMap(({ type, entry }) =>
+ isDirect(entry.id) || groupIdsOf(type, entry.id).length
+ ? [toReader(type, entry.id, entry.name, false)]
+ : []
+ );
return {
secret: { key: secretKey, environment, secretPath },
readers,
@@ -655,7 +622,7 @@ export function SecretAccessInsights({
]);
if (!canReadValue) return null;
if (isReadActivityLoading) return <Skeleton className="h-4 w-20 rounded" />;
- const status = readStatusOf(row.type, row.entry.id);
+ const status = readStatusOf(row.entry.id);
if (!status) return null;
return <SecretReadStatusBadge status={status} />;
@@ -874,212 +841,205 @@ export function SecretAccessInsights({
/>
)}
</div>
- {view === "graph" &&
- (isLoading || !graphInput ? (
+ {/* eslint-disable no-nested-ternary */}
+ {view === "graph" ? (
+ isLoading || !graphInput ? (
<Skeleton className="h-[560px] w-full" />
) : (
<SecretAccessGraph input={graphInput} />
- ))}
- {view === "table" && (
- <>
- {/* eslint-disable-next-line no-nested-ternary */}
- {isLoading ? (
- <Table>
- <TableHeader>
- <TableRow>
- <TableHead>Type</TableHead>
- <TableHead>Name</TableHead>
- {canReadInsights && <TableHead className="w-40">Last Read</TableHead>}
- {PERMISSION_COLUMNS.filter((col) => !col.isLegacy).map((col) => (
- <TableHead key={col.action} className="w-[100px] text-center">
- {col.label}
- </TableHead>
- ))}
- <TableHead className="w-10" />
- </TableRow>
- </TableHeader>
- <TableBody>
- {Array.from({ length: 10 }).map((_, i) => (
- <TableRow key={`skeleton-row-${String(i)}`}>
- <TableCell>
- <Skeleton className="h-4 w-16 rounded" />
- </TableCell>
- <TableCell>
- <Skeleton className="h-4 w-24 rounded" />
- </TableCell>
- {canReadInsights && (
- <TableCell className="w-40">
- <Skeleton className="h-4 w-20 rounded" />
- </TableCell>
- )}
- {PERMISSION_COLUMNS.filter((col) => !col.isLegacy).map((col) => (
- <TableCell key={col.action} className="w-[100px] text-center">
- <Skeleton className="mx-auto h-4 w-4 rounded" />
- </TableCell>
- ))}
- <TableCell>
- <Skeleton className="h-4 w-6 rounded" />
- </TableCell>
- </TableRow>
+ )
+ ) : isLoading ? (
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Type</TableHead>
+ <TableHead>Name</TableHead>
+ {canReadInsights && <TableHead className="w-40">Last Read</TableHead>}
+ {PERMISSION_COLUMNS.filter((col) => !col.isLegacy).map((col) => (
+ <TableHead key={col.action} className="w-[100px] text-center">
+ {col.label}
+ </TableHead>
+ ))}
+ <TableHead className="w-10" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {Array.from({ length: 10 }).map((_, i) => (
+ <TableRow key={`skeleton-row-${String(i)}`}>
+ <TableCell>
+ <Skeleton className="h-4 w-16 rounded" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-4 w-24 rounded" />
+ </TableCell>
+ {canReadInsights && (
+ <TableCell className="w-40">
+ <Skeleton className="h-4 w-20 rounded" />
+ </TableCell>
+ )}
+ {PERMISSION_COLUMNS.filter((col) => !col.isLegacy).map((col) => (
+ <TableCell key={col.action} className="w-[100px] text-center">
+ <Skeleton className="mx-auto h-4 w-4 rounded" />
+ </TableCell>
))}
- </TableBody>
- </Table>
- ) : filteredRows.length === 0 ? (
- <Empty className="border">
- <EmptyHeader>
- <EmptyTitle>No Results Found</EmptyTitle>
- <EmptyDescription>
- No users, groups, or identities match your search.
- </EmptyDescription>
- </EmptyHeader>
- </Empty>
- ) : (
- <Table containerClassName="overflow-auto">
- <TableHeader sticky>
- <TableRow>
- <TableHead className="w-48">Type</TableHead>
- <TableHead>Name</TableHead>
- {canReadInsights && (
- <TableHead className="w-40">
- <Tooltip>
- <TooltipTrigger asChild>
- <span className="inline-flex items-center gap-1">
- Last Read
- <InfoIcon className="size-3.5 text-muted" />
- </span>
- </TooltipTrigger>
- <TooltipContent>{readActivityDescription}</TooltipContent>
- </Tooltip>
- </TableHead>
+ <TableCell>
+ <Skeleton className="h-4 w-6 rounded" />
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ ) : filteredRows.length === 0 ? (
+ <Empty className="border">
+ <EmptyHeader>
+ <EmptyTitle>No Results Found</EmptyTitle>
+ <EmptyDescription>
+ No users, groups, or identities match your search.
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ ) : (
+ <Table containerClassName="overflow-auto">
+ <TableHeader sticky>
+ <TableRow>
+ <TableHead className="w-48">Type</TableHead>
+ <TableHead>Name</TableHead>
+ {canReadInsights && (
+ <TableHead className="w-40">
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="inline-flex items-center gap-1">
+ Last Read
+ <InfoIcon className="size-3.5 text-muted" />
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>{readActivityDescription}</TooltipContent>
+ </Tooltip>
+ </TableHead>
+ )}
+ {visibleColumns.map((col) => (
+ <TableHead key={col.action} className="w-[100px] text-center">
+ {col.isLegacy ? (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="inline-flex items-center gap-1">
+ {col.label}
+ <TriangleAlertIcon className="size-3.5 text-warning" />
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>
+ This is a legacy permission. Migrate to Describe and Read Value for
+ finer-grained access control.
+ </TooltipContent>
+ </Tooltip>
+ ) : (
+ col.label
)}
- {visibleColumns.map((col) => (
- <TableHead key={col.action} className="w-[100px] text-center">
- {col.isLegacy ? (
+ </TableHead>
+ ))}
+ <TableHead className="w-10" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {filteredRows.map((row) => {
+ const { icon: TypeIcon, label: typeLabel } = TYPE_CONFIG[row.type];
+ return (
+ <TableRow key={`${row.type}-${row.entry.id}`}>
+ <TableCell>
+ <span className="flex items-center gap-2">
+ <TypeIcon className="size-4 text-accent" />
+ {typeLabel}
+ </span>
+ </TableCell>
+ <TableCell isTruncatable className="max-w-[180px] font-medium">
+ <div className="flex items-center gap-1.5">
+ <span className="truncate">{row.entry.name}</span>
+ {row.inheritedFromGroups && row.inheritedFromGroups.length > 0 && (
<Tooltip>
<TooltipTrigger asChild>
- <span className="inline-flex items-center gap-1">
- {col.label}
- <TriangleAlertIcon className="size-3.5 text-warning" />
+ <span className="inline-flex shrink-0 items-center gap-1 rounded bg-foreground/5 px-1.5 py-0.5 text-xs text-muted">
+ <UsersIcon className="size-3" />
+ {row.inheritedFromGroups.length}
</span>
</TooltipTrigger>
- <TooltipContent>
- This is a legacy permission. Migrate to Describe and Read Value for
- finer-grained access control.
+ <TooltipContent side="bottom">
+ Access through{" "}
+ {row.inheritedFromGroups.length === 1
+ ? `group: ${row.inheritedFromGroups[0]}`
+ : `groups: ${row.inheritedFromGroups.join(", ")}`}
</TooltipContent>
</Tooltip>
- ) : (
- col.label
)}
- </TableHead>
- ))}
- <TableHead className="w-10" />
- </TableRow>
- </TableHeader>
- <TableBody>
- {filteredRows.map((row) => {
- const { icon: TypeIcon, label: typeLabel } = TYPE_CONFIG[row.type];
- return (
- <TableRow key={`${row.type}-${row.entry.id}`}>
- <TableCell>
- <span className="flex items-center gap-2">
- <TypeIcon className="size-4 text-accent" />
- {typeLabel}
- </span>
- </TableCell>
- <TableCell isTruncatable className="max-w-[180px] font-medium">
- <div className="flex items-center gap-1.5">
- <span className="truncate">{row.entry.name}</span>
- {row.inheritedFromGroups && row.inheritedFromGroups.length > 0 && (
- <Tooltip>
- <TooltipTrigger asChild>
- <span className="inline-flex shrink-0 items-center gap-1 rounded bg-foreground/5 px-1.5 py-0.5 text-xs text-muted">
- <UsersIcon className="size-3" />
- {row.inheritedFromGroups.length}
- </span>
- </TooltipTrigger>
- <TooltipContent side="bottom">
- Access through{" "}
- {row.inheritedFromGroups.length === 1
- ? `group: ${row.inheritedFromGroups[0]}`
- : `groups: ${row.inheritedFromGroups.join(", ")}`}
- </TooltipContent>
- </Tooltip>
- )}
- </div>
+ </div>
+ </TableCell>
+ {canReadInsights && (
+ <TableCell className="w-40 whitespace-nowrap">
+ {renderLastRead(row)}
+ </TableCell>
+ )}
+ {visibleColumns.map((col) => {
+ const hasDirect = row.entry.allowedActions.includes(col.action);
+ const hasInherited = row.inheritedActions?.has(col.action);
+ return (
+ <TableCell key={col.action} className="w-[100px] text-center">
+ {/* eslint-disable-next-line no-nested-ternary */}
+ {hasDirect ? (
+ <CheckIcon className="mx-auto size-4 text-success" />
+ ) : hasInherited ? (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <UsersIcon className="mx-auto size-4 text-success" />
+ </TooltipTrigger>
+ <TooltipContent>Inherited from group</TooltipContent>
+ </Tooltip>
+ ) : (
+ <BanIcon className="mx-auto size-4 text-muted" />
+ )}
</TableCell>
- {canReadInsights && (
- <TableCell className="w-40 whitespace-nowrap">
- {renderLastRead(row)}
- </TableCell>
- )}
- {visibleColumns.map((col) => {
- const hasDirect = row.entry.allowedActions.includes(col.action);
- const hasInherited = row.inheritedActions?.has(col.action);
- return (
- <TableCell key={col.action} className="w-[100px] text-center">
- {/* eslint-disable-next-line no-nested-ternary */}
- {hasDirect ? (
- <CheckIcon className="mx-auto size-4 text-success" />
- ) : hasInherited ? (
- <Tooltip>
- <TooltipTrigger asChild>
- <UsersIcon className="mx-auto size-4 text-success" />
- </TooltipTrigger>
- <TooltipContent>Inherited from group</TooltipContent>
- </Tooltip>
- ) : (
- <BanIcon className="mx-auto size-4 text-muted" />
- )}
- </TableCell>
- );
- })}
- <TableCell className="text-right">
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <IconButton size="xs" variant="ghost">
- <MoreHorizontalIcon />
- </IconButton>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- {row.onEdit && (
- <Tooltip open={row.canEdit ? false : undefined}>
- <TooltipTrigger>
- <DropdownMenuItem
- isDisabled={!row.canEdit}
- onClick={() => row.onEdit?.()}
- >
- <PlusIcon />
- Add Additional Privilege
- </DropdownMenuItem>
- </TooltipTrigger>
- <TooltipContent side="left">
- {row.isSelf
- ? "You cannot modify your own privileges"
- : "You do not have permission to perform this action"}
- </TooltipContent>
- </Tooltip>
- )}
- <DropdownMenuItem asChild>
- <Link
- to={row.linkTo as "."}
- params={row.linkParams}
- target="_blank"
+ );
+ })}
+ <TableCell className="text-right">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton size="xs" variant="ghost">
+ <MoreHorizontalIcon />
+ </IconButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ {row.onEdit && (
+ <Tooltip open={row.canEdit ? false : undefined}>
+ <TooltipTrigger>
+ <DropdownMenuItem
+ isDisabled={!row.canEdit}
+ onClick={() => row.onEdit?.()}
>
- <ExternalLinkIcon />
- {row.isSelf ? "View" : "Manage"} Access
- </Link>
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </TableCell>
- </TableRow>
- );
- })}
- </TableBody>
- </Table>
- )}
- </>
+ <PlusIcon />
+ Add Additional Privilege
+ </DropdownMenuItem>
+ </TooltipTrigger>
+ <TooltipContent side="left">
+ {row.isSelf
+ ? "You cannot modify your own privileges"
+ : "You do not have permission to perform this action"}
+ </TooltipContent>
+ </Tooltip>
+ )}
+ <DropdownMenuItem asChild>
+ <Link to={row.linkTo as "."} params={row.linkParams} target="_blank">
+ <ExternalLinkIcon />
+ {row.isSelf ? "View" : "Manage"} Access
+ </Link>
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </TableCell>
+ </TableRow>
+ );
+ })}
+ </TableBody>
+ </Table>
)}
+ {/* eslint-enable no-nested-ternary */}
</div>
<Sheet