Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
cleanup
varonix0da289253a53
diff --git a/backend/src/ee/routes/v1/insights-router.ts b/backend/src/ee/routes/v1/insights-router.tsindex ee81f6b87f..ecabf1ffc6 100644--- a/backend/src/ee/routes/v1/insights-router.ts+++ b/backend/src/ee/routes/v1/insights-router.ts@@ -20,14 +20,13 @@ import {SecretsProjectsSchema,SecretsSummarySchema,StaticSecretsUsageSchema,- UnusedAccessPrincipalSchema,+ UnusedAccessActorSchema,UnusedAccessSchema} from "@app/ee/services/insights/insights-schemas";-import { UnusedAccessPrincipalType } from "@app/ee/services/secret-read-activity/secret-read-activity-types";import { INSIGHTS } from "@app/lib/api-docs";import { readLimit, writeLimit } from "@app/server/config/rateLimiter";import { verifyAuth } from "@app/server/plugins/auth/verify-auth";-import { AuthMode } from "@app/services/auth/auth-type";+import { ActorType, AuthMode } from "@app/services/auth/auth-type";// Each report type declares exactly which inputs it accepts. The `inputs` schemas are the same consts// the generators use, so request validation and generation never drift.@@ -476,7 +475,7 @@ export const registerInsightsRouter = async (server: FastifyZodProvider) => {schema: {operationId: "getInsightsUnusedAccess",description:- "List the users, groups and machine identities that can read secrets they have not read in the last 30 days, those with the most such secrets first",+ "List the users and machine identities that can read secrets they have not read in the last 30 days, those with the most such secrets first",security: [{ bearerAuth: [] }],params: z.object({projectId: z.string().trim().max(36).describe(INSIGHTS.GET_UNUSED_ACCESS.projectId)@@ -493,7 +492,7 @@ export const registerInsightsRouter = async (server: FastifyZodProvider) => {onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),handler: async (req, reply) => {const { projectId } = req.params;- const { principals, totalCount, trackingStartedAt, fullWindowFrom, remainingTTL, projectName } =+ const { actors, totalCount, trackingStartedAt, fullWindowFrom, remainingTTL, projectName } =await server.services.secretReadActivity.listUnusedAccess({ projectId, ...req.query }, req.permission);await server.services.auditLog.createAuditLog({projectId,@@ -507,42 +506,46 @@ export const registerInsightsRouter = async (server: FastifyZodProvider) => {if (remainingTTL && remainingTTL >= 0) {void reply.header("X-Cache-TTL", remainingTTL);}- return { principals, totalCount, trackingStartedAt, fullWindowFrom };+ return { actors, totalCount, trackingStartedAt, fullWindowFrom };}});server.route({method: "GET",- url: "/:projectId/secrets/unused-access/:principalType/:principalId",+ url: "/:projectId/secrets/unused-access/:actorType/:actorId",config: { rateLimit: readLimit },schema: {- operationId: "getInsightsUnusedAccessPrincipal",- description: "List the secrets one user, group or machine identity can read but has not read in the last 30 days",+ operationId: "getInsightsUnusedAccessActor",+ description: "List the secrets one user or machine identity can read but has not read in the last 30 days",security: [{ bearerAuth: [] }],params: z.object({- projectId: z.string().trim().max(36).describe(INSIGHTS.GET_UNUSED_ACCESS_PRINCIPAL.projectId),- principalType: z- .nativeEnum(UnusedAccessPrincipalType)- .describe(INSIGHTS.GET_UNUSED_ACCESS_PRINCIPAL.principalType),- principalId: z.string().uuid().describe(INSIGHTS.GET_UNUSED_ACCESS_PRINCIPAL.principalId)+ projectId: z.string().trim().max(36).describe(INSIGHTS.GET_UNUSED_ACCESS_ACTOR.projectId),+ actorType: z.enum([ActorType.USER, ActorType.IDENTITY]).describe(INSIGHTS.GET_UNUSED_ACCESS_ACTOR.actorType),+ actorId: z.string().uuid().describe(INSIGHTS.GET_UNUSED_ACCESS_ACTOR.actorId)}),response: {- 200: UnusedAccessPrincipalSchema+ 200: UnusedAccessActorSchema}},onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),handler: async (req, reply) => {- const { projectId, principalType, principalId } = req.params;- const { principal, secrets, unlistedCount, trackingStartedAt, fullWindowFrom, remainingTTL, projectName } =- await server.services.secretReadActivity.getUnusedAccessPrincipal(- { projectId, principalType, principalId },+ const { projectId, actorType, actorId } = req.params;+ const { actor, secrets, unlistedCount, trackingStartedAt, fullWindowFrom, remainingTTL, projectName } =+ await server.services.secretReadActivity.getUnusedAccessActor(+ { projectId, actorType, actorId },req.permission);await server.services.auditLog.createAuditLog({projectId,event: {type: EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_UNUSED_ACCESS,- metadata: { projectId, projectName, principalType, principalId, principalName: principal.name }+ metadata: {+ projectId,+ projectName,+ principalType: actorType,+ principalId: actorId,+ principalName: actor.name+ }},...req.auditLogInfo});@@ -550,7 +553,7 @@ export const registerInsightsRouter = async (server: FastifyZodProvider) => {if (remainingTTL && remainingTTL >= 0) {void reply.header("X-Cache-TTL", remainingTTL);}- return { principal, secrets, unlistedCount, trackingStartedAt, fullWindowFrom };+ return { actor, secrets, unlistedCount, trackingStartedAt, fullWindowFrom };}});diff --git a/backend/src/ee/services/insights/insights-schemas.ts b/backend/src/ee/services/insights/insights-schemas.tsindex 08d8ae46c4..5682bd40c4 100644--- a/backend/src/ee/services/insights/insights-schemas.ts+++ b/backend/src/ee/services/insights/insights-schemas.ts@@ -1,8 +1,8 @@import { z } from "zod";import { IdentityAuthMethod } from "@app/db/schemas";-import { UnusedAccessPrincipalType } from "@app/ee/services/secret-read-activity/secret-read-activity-types";import { INSIGHTS } from "@app/lib/api-docs";+import { ActorType } from "@app/services/auth/auth-type";export const SecretsSummarySchema = z.object({activeLeases: z.number().int().describe(INSIGHTS.GET_SECRETS_SUMMARY.activeLeases),@@ -67,36 +67,60 @@ export const SecretsProjectsSchema = z.object({limit: z.number().int().describe(INSIGHTS.GET_SECRETS_PROJECTS.limit)});-const UnusedAccessPrincipalRowSchema = z.object({- principalType: z.nativeEnum(UnusedAccessPrincipalType).describe(INSIGHTS.GET_UNUSED_ACCESS.principalType),- principalId: z.string().describe(INSIGHTS.GET_UNUSED_ACCESS.principalId),+const UnusedAccessRoleSchema = z.object({+ id: z.string().nullable().describe(INSIGHTS.GET_UNUSED_ACCESS.roleId),+ slug: z.string().describe(INSIGHTS.GET_UNUSED_ACCESS.roleSlug),+ name: z.string().describe(INSIGHTS.GET_UNUSED_ACCESS.roleName)+});++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),- memberCount: z.number().int().nullable().describe(INSIGHTS.GET_UNUSED_ACCESS.memberCount),entitledCount: z.number().int().describe(INSIGHTS.GET_UNUSED_ACCESS.entitledCount),unreadCount: z.number().int().describe(INSIGHTS.GET_UNUSED_ACCESS.unreadCount),environments: z.string().array().describe(INSIGHTS.GET_UNUSED_ACCESS.environments),lastReadAt: z.date().nullable().describe(INSIGHTS.GET_UNUSED_ACCESS.lastReadAt),- accessVia: z.string().array().describe(INSIGHTS.GET_UNUSED_ACCESS.accessVia)+ accessPaths: z+ .object({+ roles: UnusedAccessRoleSchema.array().describe(INSIGHTS.GET_UNUSED_ACCESS.roles),+ groups: z+ .object({+ id: z.string().describe(INSIGHTS.GET_UNUSED_ACCESS.groupId),+ name: z.string().describe(INSIGHTS.GET_UNUSED_ACCESS.groupName),+ roles: UnusedAccessRoleSchema.array().describe(INSIGHTS.GET_UNUSED_ACCESS.groupRoles)+ })+ .array()+ .describe(INSIGHTS.GET_UNUSED_ACCESS.groups),+ additionalPrivileges: z+ .object({+ id: z.string().describe(INSIGHTS.GET_UNUSED_ACCESS.additionalPrivilegeId),+ name: z.string().describe(INSIGHTS.GET_UNUSED_ACCESS.additionalPrivilegeName)+ })+ .array()+ .describe(INSIGHTS.GET_UNUSED_ACCESS.additionalPrivileges)+ })+ .describe(INSIGHTS.GET_UNUSED_ACCESS.accessPaths)});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),- principals: UnusedAccessPrincipalRowSchema.array().describe(INSIGHTS.GET_UNUSED_ACCESS.principals)+ actors: UnusedAccessActorRowSchema.array().describe(INSIGHTS.GET_UNUSED_ACCESS.actors)});-export const UnusedAccessPrincipalSchema = z.object({- principal: UnusedAccessPrincipalRowSchema,- unlistedCount: z.number().int().describe(INSIGHTS.GET_UNUSED_ACCESS_PRINCIPAL.unlistedCount),+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),secrets: z.object({- secretKey: z.string().describe(INSIGHTS.GET_UNUSED_ACCESS_PRINCIPAL.secretKey),- environment: z.string().describe(INSIGHTS.GET_UNUSED_ACCESS_PRINCIPAL.environment),- secretPath: z.string().describe(INSIGHTS.GET_UNUSED_ACCESS_PRINCIPAL.secretPath)+ secretKey: z.string().describe(INSIGHTS.GET_UNUSED_ACCESS_ACTOR.secretKey),+ environment: z.string().describe(INSIGHTS.GET_UNUSED_ACCESS_ACTOR.environment),+ secretPath: z.string().describe(INSIGHTS.GET_UNUSED_ACCESS_ACTOR.secretPath)}).array()- .describe(INSIGHTS.GET_UNUSED_ACCESS_PRINCIPAL.secrets)+ .describe(INSIGHTS.GET_UNUSED_ACCESS_ACTOR.secrets)});diff --git a/backend/src/ee/services/permission/permission-dal.ts b/backend/src/ee/services/permission/permission-dal.tsindex 645bac5e18..17354aea9b 100644--- a/backend/src/ee/services/permission/permission-dal.ts+++ b/backend/src/ee/services/permission/permission-dal.ts@@ -64,6 +64,8 @@ export interface TPermissionDALFactory {id: string;role: string;customRoleSlug: string;+ customRoleId?: string | null;+ customRoleName?: string | null;permissions: unknown;temporaryRange: string | null | undefined;temporaryMode: string | null | undefined;@@ -73,6 +75,7 @@ export interface TPermissionDALFactory {}[];additionalPrivileges: {id: string;+ name: string;permissions: unknown;temporaryRange: string | null | undefined;temporaryMode: string | null | undefined;@@ -108,9 +111,11 @@ export interface TPermissionDALFactory {temporaryAccessStartTime?: Date | null | undefined;temporaryAccessEndTime?: Date | null | undefined;customRoleSlug?: string | null | undefined;+ customRoleName?: string | null | undefined;}[];additionalPrivileges: {id: string;+ name: string;permissions: unknown;temporaryRange: string | null | undefined;temporaryMode: string | null | undefined;@@ -141,6 +146,8 @@ export interface TPermissionDALFactory {id: string;role: string;customRoleSlug: string;+ customRoleId?: string | null;+ customRoleName?: string | null;permissions: unknown;temporaryRange: string | null | undefined;temporaryMode: string | null | undefined;@@ -155,6 +162,8 @@ export interface TPermissionDALFactory {id: string;role: string;customRoleSlug: string;+ customRoleId?: string | null;+ customRoleName?: string | null;permissions: unknown;temporaryRange: string | null | undefined;temporaryMode: string | null | undefined;@@ -540,6 +549,7 @@ export const permissionDALFactory = (db: TDbClient): TPermissionDALFactory => {db.ref("id").withSchema(TableName.Groups).as("groupId"),db.ref("name").withSchema(TableName.Groups).as("groupName"),db.ref("slug").withSchema("groupCustomRoles").as("groupProjectMembershipRoleCustomRoleSlug"),+ db.ref("name").withSchema("groupCustomRoles").as("groupProjectMembershipRoleCustomRoleName"),db.ref("permissions").withSchema("groupCustomRoles").as("groupProjectMembershipRolePermission"),db.ref("id").withSchema(TableName.MembershipRole).as("groupProjectMembershipRoleId"),db.ref("role").withSchema(TableName.MembershipRole).as("groupProjectMembershipRole"),@@ -574,6 +584,8 @@ export const permissionDALFactory = (db: TDbClient): TPermissionDALFactory => {groupProjectMembershipRole,groupProjectMembershipRolePermission,groupProjectMembershipRoleCustomRoleSlug,+ groupProjectMembershipRoleCustomRoleId,+ groupProjectMembershipRoleCustomRoleName,groupProjectMembershipRoleIsTemporary,groupProjectMembershipRoleTemporaryMode,groupProjectMembershipRoleTemporaryAccessEndTime,@@ -583,6 +595,8 @@ export const permissionDALFactory = (db: TDbClient): TPermissionDALFactory => {id: groupProjectMembershipRoleId,role: groupProjectMembershipRole,customRoleSlug: groupProjectMembershipRoleCustomRoleSlug,+ customRoleId: groupProjectMembershipRoleCustomRoleId as string | null,+ customRoleName: groupProjectMembershipRoleCustomRoleName as string | null,permissions: groupProjectMembershipRolePermission,temporaryRange: groupProjectMembershipRoleTemporaryRange,temporaryMode: groupProjectMembershipRoleTemporaryMode,@@ -660,6 +674,8 @@ export const permissionDALFactory = (db: TDbClient): TPermissionDALFactory => {db.ref("id").withSchema(TableName.Membership).as("membershipId"),db.ref("username").withSchema(TableName.Users).as("username"),db.ref("slug").withSchema(TableName.Role).as("roleSlug"),+ db.ref("name").withSchema(TableName.Role).as("roleName"),+ db.ref("customRoleId").withSchema(TableName.MembershipRole).as("membershipRoleCustomRoleId"),db.ref("permissions").withSchema(TableName.Role).as("customRolePermission"),db.ref("id").withSchema(TableName.MembershipRole).as("membershipRoleId"),db.ref("role").withSchema(TableName.MembershipRole).as("membershipRole"),@@ -714,6 +730,7 @@ export const permissionDALFactory = (db: TDbClient): TPermissionDALFactory => {label: "additionalPrivileges" as const,mapper: ({additionalPrivilegeId,+ additionalPrivilegeName,additionalPrivilegePermissions,additionalPrivilegeIsTemporary,additionalPrivilegeTemporaryMode,@@ -724,6 +741,7 @@ export const permissionDALFactory = (db: TDbClient): TPermissionDALFactory => {additionalPrivilegeUpdatedAt}) => ({id: additionalPrivilegeId,+ name: additionalPrivilegeName,permissions: additionalPrivilegePermissions,temporaryRange: additionalPrivilegeTemporaryRange,temporaryMode: additionalPrivilegeTemporaryMode,@@ -739,6 +757,8 @@ export const permissionDALFactory = (db: TDbClient): TPermissionDALFactory => {label: "roles" as const,mapper: ({roleSlug,+ roleName,+ membershipRoleCustomRoleId,customRolePermission,membershipRoleId,membershipRole,@@ -754,6 +774,8 @@ export const permissionDALFactory = (db: TDbClient): TPermissionDALFactory => {role: membershipRole,permissions: customRolePermission,customRoleSlug: roleSlug,+ customRoleId: membershipRoleCustomRoleId as string | null,+ customRoleName: roleName as string | null,temporaryRange: membershipRoleTemporaryRange,temporaryMode: membershipRoleTemporaryMode,temporaryAccessStartTime: membershipRoleTemporaryAccessStartTime,@@ -851,8 +873,10 @@ export const permissionDALFactory = (db: TDbClient): TPermissionDALFactory => {db.ref("createdAt").withSchema(TableName.Membership).as("membershipCreatedAt"),db.ref("updatedAt").withSchema(TableName.Membership).as("membershipUpdatedAt"),db.ref("slug").withSchema(TableName.Role).as("customRoleSlug"),+ db.ref("name").withSchema(TableName.Role).as("customRoleName"),db.ref("permissions").withSchema(TableName.Role),db.ref("id").withSchema(TableName.AdditionalPrivilege).as("identityApId"),+ db.ref("name").withSchema(TableName.AdditionalPrivilege).as("identityApName"),db.ref("permissions").withSchema(TableName.AdditionalPrivilege).as("identityApPermissions"),db.ref("temporaryMode").withSchema(TableName.AdditionalPrivilege).as("identityApTemporaryMode"),db.ref("isTemporary").withSchema(TableName.AdditionalPrivilege).as("identityApIsTemporary"),@@ -891,7 +915,8 @@ export const permissionDALFactory = (db: TDbClient): TPermissionDALFactory => {mapper: (data) =>MembershipRolesSchema.extend({permissions: z.unknown(),- customRoleSlug: z.string().optional().nullable()+ customRoleSlug: z.string().optional().nullable(),+ customRoleName: z.string().optional().nullable()}).parse(data)},{@@ -899,6 +924,7 @@ export const permissionDALFactory = (db: TDbClient): TPermissionDALFactory => {label: "additionalPrivileges" as const,mapper: ({identityApId,+ identityApName,identityApPermissions,identityApIsTemporary,identityApTemporaryMode,@@ -907,6 +933,7 @@ export const permissionDALFactory = (db: TDbClient): TPermissionDALFactory => {identityApTemporaryAccessStartTime}) => ({id: identityApId,+ name: identityApName,permissions: identityApPermissions,temporaryRange: identityApTemporaryRange,temporaryMode: identityApTemporaryMode,diff --git a/backend/src/ee/services/permission/permission-service-types.ts b/backend/src/ee/services/permission/permission-service-types.tsindex 233f897e79..6e8f26c351 100644--- a/backend/src/ee/services/permission/permission-service-types.ts+++ b/backend/src/ee/services/permission/permission-service-types.ts@@ -162,16 +162,26 @@ export type TPermissionServiceFactory = {id: string;name: string;membershipId: string;- roles: { role: string; customRoleSlug?: string | null }[];- hasAdditionalPrivileges: boolean;+ roles: {+ role: string;+ customRoleSlug?: string | null;+ customRoleId?: string | null;+ customRoleName?: string | null;+ }[];+ additionalPrivileges: { id: string; name: string }[];}[];identityPermissions: {permission: MongoAbility<ProjectPermissionSet, MongoQuery>;id: string;name: string;membershipId: string;- roles: { role: string; customRoleSlug?: string | null }[];- hasAdditionalPrivileges: boolean;+ roles: {+ role: string;+ customRoleSlug?: string | null;+ customRoleId?: string | null;+ customRoleName?: string | null;+ }[];+ additionalPrivileges: { id: string; name: string }[];}[];groupPermissions: {permission: MongoAbility<ProjectPermissionSet, MongoQuery>;@@ -180,7 +190,12 @@ export type TPermissionServiceFactory = {id: string;name: string;membershipId: string;- roles: { role: string; customRoleSlug?: string | null }[];+ roles: {+ role: string;+ customRoleSlug?: string | null;+ customRoleId?: string | null;+ customRoleName?: string | null;+ }[];}[];}>;getOrgPermissionByRoles: (diff --git a/backend/src/ee/services/permission/permission-service.ts b/backend/src/ee/services/permission/permission-service.tsindex 39749fbe45..faf8f1823f 100644--- a/backend/src/ee/services/permission/permission-service.ts+++ b/backend/src/ee/services/permission/permission-service.ts@@ -997,8 +997,13 @@ export const permissionServiceFactory = ({id: userProjectPermission.userId,membershipId: userProjectPermission.id,name: userProjectPermission.username,- roles: (userProjectPermission.roles ?? []).map(({ role, customRoleSlug }) => ({ role, customRoleSlug })),- hasAdditionalPrivileges: Boolean(userProjectPermission.additionalPrivileges?.length)+ roles: (userProjectPermission.roles ?? []).map(({ role, customRoleSlug, customRoleId, customRoleName }) => ({+ role,+ customRoleSlug,+ customRoleId,+ customRoleName+ })),+ additionalPrivileges: (userProjectPermission.additionalPrivileges ?? []).map(({ id, name }) => ({ id, name }))};});@@ -1042,8 +1047,18 @@ export const permissionServiceFactory = ({id: identityProjectPermission.identityId,membershipId: identityProjectPermission.id,name: identityProjectPermission.username,- roles: (identityProjectPermission.roles ?? []).map(({ role, customRoleSlug }) => ({ role, customRoleSlug })),- hasAdditionalPrivileges: Boolean(identityProjectPermission.additionalPrivileges?.length)+ roles: (identityProjectPermission.roles ?? []).map(+ ({ role, customRoleSlug, customRoleId, customRoleName }) => ({+ role,+ customRoleSlug,+ customRoleId,+ customRoleName+ })+ ),+ additionalPrivileges: (identityProjectPermission.additionalPrivileges ?? []).map(({ id, name }) => ({+ id,+ name+ }))};});@@ -1080,7 +1095,12 @@ export const permissionServiceFactory = ({id: groupProjectPermission.groupId,membershipId: groupProjectPermission.id,name: groupProjectPermission.username,- roles: (groupProjectPermission.roles ?? []).map(({ role, customRoleSlug }) => ({ role, customRoleSlug }))+ roles: (groupProjectPermission.roles ?? []).map(({ role, customRoleSlug, customRoleId, customRoleName }) => ({+ role,+ customRoleSlug,+ customRoleId,+ customRoleName+ }))};});diff --git a/backend/src/ee/services/secret-read-activity/secret-read-activity-fns.test.ts b/backend/src/ee/services/secret-read-activity/secret-read-activity-fns.test.tsindex dff9a6ad02..5734d7da22 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@@ -1,5 +1,12 @@+import { createMongoAbility, MongoAbility } from "@casl/ability";import { describe, expect, test } from "vitest";+import { ProjectMembershipRole } from "@app/db/schemas";+import {+ ProjectPermissionSecretActions,+ ProjectPermissionSet,+ ProjectPermissionSub+} from "@app/ee/services/permission/project-permission";import { ActorType } from "@app/services/auth/auth-type";import {@@ -7,9 +14,19 @@ import {computeSecretReach,coversWholeWindow,getUtcMonthStart,- indexSecretReads+ indexSecretReads,+ summarizeSecretAccess,+ toActorKey,+ toUnusedAccessRoles} from "./secret-read-activity-fns";-import { SecretReadObjectType, TReachSecret, TSecretLastRead, TSecretReachGraph } from "./secret-read-activity-types";+import {+ SecretReadObjectType,+ TProjectAccess,+ TReachSecret,+ TSecretActivity,+ TSecretLastRead,+ TSecretReachGraph+} from "./secret-read-activity-types";const dbPass: TReachSecret = { id: "db-pass", folderId: "shared", key: "DB_PASS" };const dbUrl: TReachSecret = { id: "db-url", folderId: "shared", key: "DB_URL" };@@ -119,3 +136,101 @@ describe("coversWholeWindow", () => {expect(coversWholeWindow(windowStart, new Date("2026-10-10T00:00:00.000Z"), windowStart)).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) => ({+ 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 access = (overrides: Partial<TProjectAccess> = {}): TProjectAccess => ({+ readersByRules: [[reader("direct"), reader("via-group")], [reader("no-access", cannotRead)]],+ adminActorIds: new Set(),+ accessChangedAtByActorId: new Map(),+ judgedFrom,+ ...overrides+ });+ const ids = (readers: { actorId: string }[]) => readers.map((entry) => entry.actorId).sort();+ const readBy = (actorId: string) =>+ new Map([+ [+ toActorKey(ActorType.USER, actorId),+ { actorType: ActorType.USER as const, actorId, lastReadAt: new Date("2026-10-01T00:00:00.000Z") }+ ]+ ]);++ test("lists each reader who can read the value once, however many memberships give it", () => {+ 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, and never counts their reads as a ghost's", () => {+ const summary = summarizeSecretAccess(+ activity({ reads: readBy("admin") }),+ 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", () => {+ const summary = summarizeSecretAccess(+ activity({ reads: readBy("direct") }),+ access({ accessChangedAtByActorId: new Map([["via-group", new Date("2026-10-01T00:00:00.000Z")]]) })+ );+ expect(summary.unread).toEqual([]);+ });++ 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([]);+ });++ 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"]);+ });+});++describe("toUnusedAccessRoles", () => {+ test("names built-in roles after their predefined role and keeps a custom role's id and name", () => {+ expect(+ toUnusedAccessRoles([+ { role: ProjectMembershipRole.Member },+ {+ role: ProjectMembershipRole.Custom,+ customRoleSlug: "deployer",+ customRoleId: "role-1",+ customRoleName: "Deployer"+ }+ ])+ ).toEqual([+ { id: null, slug: "member", name: "Member" },+ { 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.tsindex 30ff99afe1..5aa1cea34d 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@@ -1,18 +1,28 @@+import { ProjectMembershipRole, ProjectType } from "@app/db/schemas";import { DAY_IN_MS } from "@app/ee/services/audit-report/audit-report-fns";-import { groupBy, prefixWithSlash, removeTrailingSlash } from "@app/lib/fn";+import { hasSecretReadValueOrDescribePermission } from "@app/ee/services/permission/permission-fns";+import { ProjectPermissionSecretActions } from "@app/ee/services/permission/project-permission";+import { groupBy, prefixWithSlash, removeTrailingSlash, unique } from "@app/lib/fn";import { TProjectEnvDALFactory } from "@app/services/project-env/project-env-dal";+import { getPredefinedRoles } from "@app/services/project-role/project-role-fns";import { TSecretFolderDALFactory } from "@app/services/secret-folder/secret-folder-dal";import { buildFolderIdMap, buildFolderPath } from "@app/services/secret-folder/secret-folder-fns";import {SecretReadObjectType,+ TMemberRole,+ TProjectAccess,+ TProjectFolderTree,TReachSecret,+ TSecretAccessSummary,+ TSecretActivity,TSecretLastRead,TSecretLocation,TSecretReach,TSecretReachGraph,TSecretReaderType,- TSecretReadResult+ TSecretReadResult,+ TUnusedAccessRole} from "./secret-read-activity-types";export const getUtcMonthStart = (date: Date, monthOffset = 0) =>@@ -23,6 +33,8 @@ export const normalizeSecretPath = (secretPath: string) => removeTrailingSlash(pexport 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);@@ -36,7 +48,7 @@ export const loadProjectFolderTree = async (projectEnvDAL: Pick<TProjectEnvDALFactory, "find">;},projectId: string-) => {+): Promise<TProjectFolderTree> => {const [folders, environments] = await Promise.all([folderDAL.findByProjectId(projectId),projectEnvDAL.find({ projectId })@@ -61,8 +73,6 @@ export const loadProjectFolderTree = async (return { folders, folderById, envById, pathOf, locationOf, folderIdByLocation };};-export type TProjectFolderTree = Awaited<ReturnType<typeof loadProjectFolderTree>>;-// Imports and references check the reader's own access to the source secret, so a read through either// one uses that access and must count.export const computeSecretReach = (secret: TReachSecret, graph: TSecretReachGraph): TSecretReach => {@@ -110,7 +120,7 @@ export const classifySecretReads = (const record = (objectType: SecretReadObjectType, objectId: string) => {(readsByObjectId[objectId] ?? []).forEach((read) => {if (read.objectType !== objectType || read.lastReadAt < trackedSince) return;- const key = `${read.actorType}:${read.actorId}`;+ const key = toActorKey(read.actorType, read.actorId);const current = activity.get(key);if (!current || read.lastReadAt > current.lastReadAt) {activity.set(key, {@@ -127,3 +137,48 @@ export const classifySecretReads = (reach.folderIds.forEach((folderId) => record(SecretReadObjectType.Folder, folderId));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+export const summarizeSecretAccess = (+ { secret, environment, secretPath, trackedSince, reads }: TSecretActivity,+ { readersByRules, adminActorIds, accessChangedAtByActorId, judgedFrom }: TProjectAccess+): TSecretAccessSummary => {+ const subject = { environment, secretPath, secretName: secret.key, secretTags: secret.tags?.map((tag) => tag.slug) };+ const entitled = unique(+ readersByRules+ .filter(([{ permission }]) =>+ hasSecretReadValueOrDescribePermission(permission, ProjectPermissionSecretActions.ReadValue, subject)+ )+ .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 };+};++// Only the names of the predefined roles are read, so the project id they are built for does not matter.+const BUILT_IN_ROLE_NAMES = new Map<string, string>(+ getPredefinedRoles({ projectId: "", projectType: ProjectType.SecretManager }).map((role) => [role.slug, role.name])+);++// A built-in role has no id and is named after its predefined role; a custom role keeps its own id and name.+export const toUnusedAccessRoles = (roles: TMemberRole[]): TUnusedAccessRole[] =>+ unique(+ roles.map(({ role, customRoleId, customRoleName }) =>+ role === ProjectMembershipRole.Custom+ ? { id: customRoleId ?? null, slug: role, name: customRoleName ?? role }+ : { id: null, slug: role, name: BUILT_IN_ROLE_NAMES.get(role) ?? role }+ ),+ (role) => `${role.slug}:${role.id ?? role.name}`+ );diff --git a/backend/src/ee/services/secret-read-activity/secret-read-activity-queue.ts b/backend/src/ee/services/secret-read-activity/secret-read-activity-queue.tsindex 2946cfcd97..5e060711cf 100644--- a/backend/src/ee/services/secret-read-activity/secret-read-activity-queue.ts+++ b/backend/src/ee/services/secret-read-activity/secret-read-activity-queue.ts@@ -18,11 +18,11 @@ import {getUtcMonthStart,loadProjectFolderTree,normalizeSecretPath,- toLocationKey,- TProjectFolderTree+ toLocationKey} from "./secret-read-activity-fns";import {SecretReadObjectType,+ TProjectFolderTree,TRecordBulkSecretReadDTO,TRecordSecretReadDTO,TSecretLastRead,diff --git a/backend/src/ee/services/secret-read-activity/secret-read-activity-types.ts b/backend/src/ee/services/secret-read-activity/secret-read-activity-types.tsindex 676e7e31dd..7012227f2d 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@@ -1,5 +1,10 @@-import { TSecretReadActivity } from "@app/db/schemas";+import { MongoAbility, MongoQuery } from "@casl/ability";++import { TProjectEnvironments, TSecretFolders, TSecretReadActivity } from "@app/db/schemas";+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";+import { ProjectPermissionSet } from "@app/ee/services/permission/project-permission";import { ActorType } from "@app/services/auth/auth-type";+import { TSecretV2BridgeDALFactory } from "@app/services/secret-v2-bridge/secret-v2-bridge-dal";// A reader's last read of an object. The table also keys it by month (its partition key), which the DAL adds// on write and folds away on read.@@ -34,6 +39,16 @@ export type TReachSecret = { id: string; folderId: string; key?: string };export type TSecretLocation = { environment: string; secretPath: string };+// A project's folders, loaded once, with each folder's path and location worked out on demand.+export type TProjectFolderTree = {+ folders: TSecretFolders[];+ folderById: Record<string, TSecretFolders>;+ envById: Map<string, TProjectEnvironments>;+ pathOf: (folderId: string) => string;+ locationOf: (folderId: string) => TSecretLocation | undefined;+ folderIdByLocation: Map<string, string>;+};+export type TSecretReachGraph = {getReferencers: (secret: TReachSecret) => TReachSecret[];getImporterFolderIds: (folderId: string) => string[];@@ -85,11 +100,39 @@ export type TGetSecretReadActivityDTO = {secretName: string;};-// Without a secret, the whole project is in scope.+// Without a secret, the whole project is in scope. A caller that already loaded the folder tree passes it in.export type TReadActivityScope = {projectId: string;windowStart: Date;secret?: Omit<TGetSecretReadActivityDTO, "projectId">;+ tree?: TProjectFolderTree;+};++export type TSecretActivity = TSecretLocation & {+ secret: Awaited<ReturnType<TSecretV2BridgeDALFactory["find"]>>[number];+ trackedSince: Date;+ reads: Map<string, TSecretReadResult>;+};++export type TProjectReader = {+ actorType: TSecretReaderType;+ actorId: string;+ permission: MongoAbility<ProjectPermissionSet, MongoQuery>;+};++export type TProjectAccess = {+ readersByRules: TProjectReader[][];+ adminActorIds: Set<string>;+ accessChangedAtByActorId: Map<string, Date>;+ judgedFrom: Date;+};++export type TSecretAccessSummary = {+ // Everyone who can read the value today, each once.+ 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@@ -103,28 +146,42 @@ export type TEntitledReader = {accessChangedAt: Date | null;};-export enum UnusedAccessPrincipalType {- User = "user",- Identity = "identity",- Group = "group"-}+export type TMemberRole = Awaited<+ ReturnType<TPermissionServiceFactory["getProjectPermissions"]>+>["userPermissions"][number]["roles"][number];++export type TUnusedAccessRole = { id: string | null; slug: string; name: string };-// A user, group or machine identity that can read secrets it has not read in the window.-export type TUnusedAccessPrincipal = {- principalType: UnusedAccessPrincipalType;- principalId: string;+export type TUnusedAccessPaths = {+ roles: TUnusedAccessRole[];+ groups: { id: string; name: string; roles: TUnusedAccessRole[] }[];+ additionalPrivileges: { id: string; name: string }[];+};++export type TUnusedAccessActor = {+ actorType: TSecretReaderType;+ actorId: string;name: string;- // Groups only.- memberCount: number | null;- // The secrets it can read, and how many of those it has not read.entitledCount: number;unreadCount: number;- // The environments holding its unread secrets.environments: string[];- // Its latest read of any secret in the project within the window; a group's is its members' latest.lastReadAt: Date | null;- // How it has the access: roles, additional privileges and groups.- accessVia: string[];+ accessPaths: TUnusedAccessPaths;+};++export type TUnusedAccessTally = {+ actorType: TSecretReaderType;+ actorId: string;+ entitledCount: number;+ unreadCount: number;+ // Capped at UNUSED_ACCESS_MAX_SECRETS_PER_ACTOR+ unreadSecretIds: string[];+ environments: Set<string>;+};++export type TUnusedAccessSummary = {+ rows: TUnusedAccessActor[];+ details: Record<string, string[]>;};export type TUnusedSecret = TSecretLocation & { secretKey: string };@@ -136,8 +193,8 @@ export type TListUnusedAccessDTO = {search?: string;};-export type TGetUnusedAccessPrincipalDTO = {+export type TGetUnusedAccessActorDTO = {projectId: string;- principalType: UnusedAccessPrincipalType;- principalId: string;+ actorType: TSecretReaderType;+ actorId: string;};diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex 624da5cc1f..9d93c070e7 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -949,39 +949,49 @@ export const INSIGHTS = {},GET_UNUSED_ACCESS: {projectId: "The ID of the project to list unused access for.",- offset: "The number of principals to skip before returning results.",- limit: "The maximum number of principals to return per page.",- search: "Only principals whose name contains this text, ignoring case.",- principals:- "The users, groups and machine identities that can read secrets they have not read in the last 30 days (since tracking began, in a project tracked for less), those with the most such secrets first. Project admins and admin groups are left out: they can read everything by design.",- principalType: "Whether the principal is a user, a group or a machine identity.",- principalId: "The ID of the user, group or machine identity.",- name: "The username of the user, or the name of the group or machine identity.",- memberCount: "How many users and machine identities the group has. Null for a user or machine identity.",- entitledCount: "How many secrets the principal can read the value of today.",+ offset: "The number of actors to skip before returning results.",+ limit: "The maximum number of actors to return per page.",+ search: "Only actors whose name contains this text, ignoring case.",+ actors:+ "The users and machine identities that can read secrets they have not read in the last 30 days (since tracking began, in a project tracked for less), those with the most such secrets first. Project admins are left out: they can read everything by design.",+ 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. A group has not read a secret when none of its members have. Secrets and access newer than 30 days are not counted.",+ "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.",environments: "The slugs of the environments holding the unread secrets.",lastReadAt:- "When the principal last read any secret in the project in the last 30 days, as the first read of that day; a group's is its members' latest. Null when it read nothing.",- accessVia: "How the principal has the access: its roles, additional privileges, and the groups it belongs to.",- totalCount: "The number of principals the caller can page through.",+ "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.",+ roleSlug: "The slug of the built-in role, or 'custom' for a custom role.",+ roleName: "The name of the role.",+ groups: "The groups the actor belongs to that are members of the project.",+ groupId: "The ID of the group.",+ groupName: "The name of the group.",+ groupRoles: "The project roles the group gives its members.",+ additionalPrivileges: "The project-wide additional privileges the actor holds.",+ 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."},- GET_UNUSED_ACCESS_PRINCIPAL: {+ GET_UNUSED_ACCESS_ACTOR: {projectId: "The ID of the project.",- principalType: "Whether the principal is a user, a group or a machine identity.",- principalId: "The ID of the user, group or machine identity.",+ actorType: "Whether the actor is a user or a machine identity.",+ actorId: "The ID of the user or machine identity.",secrets:- "The secrets the principal 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 in the last 30 days, among those the caller can see, ordered by environment and path.",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 principal's unread secrets are not listed: past the first 200, in places the caller cannot see, or deleted since the results were computed."+ "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."},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.",diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 470356b87e..dc6ee05b34 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -3538,7 +3538,6 @@ export const registerRoutes = async (identityDAL,userGroupMembershipDAL,identityGroupMembershipDAL,- roleDAL,kmsService,keyStore});diff --git a/frontend/src/hooks/api/secretInsights/index.ts b/frontend/src/hooks/api/secretInsights/index.tsindex 2b3e92f12f..8764e6bc08 100644--- a/frontend/src/hooks/api/secretInsights/index.ts+++ b/frontend/src/hooks/api/secretInsights/index.ts@@ -16,7 +16,7 @@ export {useGetSecretBlindIndexStatus,useGetSecretsDuplication,useGetUnusedAccess,- useGetUnusedAccessPrincipal+ useGetUnusedAccessActor} from "./queries";export type {TAccessLocation,@@ -38,9 +38,9 @@ export type {TGetSecretAccessVolumeResponse,TGetSecretsDuplicationDTO,TGetSecretsDuplicationResponse,+ TGetUnusedAccessActorDTO,+ TGetUnusedAccessActorResponse,TGetUnusedAccessDTO,- TGetUnusedAccessPrincipalDTO,- TGetUnusedAccessPrincipalResponse,TGetUnusedAccessResponse,TOrgAuthMethodUsage,TOrgDuplicatedSecretEntry,@@ -55,7 +55,9 @@ export type {TSecretAccessVolumeActor,TSecretAccessVolumeDay,TSecretValueMatch,- TUnusedAccessPrincipal,+ TUnusedAccessActor,+ TUnusedAccessPaths,+ TUnusedAccessRole,TUnusedSecret} from "./types";-export { UnusedAccessPrincipalType } from "./types";+export { UnusedAccessActorType } from "./types";diff --git a/frontend/src/hooks/api/secretInsights/queries.tsx b/frontend/src/hooks/api/secretInsights/queries.tsxindex 14fa9cfe0c..dcf9847379 100644--- a/frontend/src/hooks/api/secretInsights/queries.tsx+++ b/frontend/src/hooks/api/secretInsights/queries.tsx@@ -22,9 +22,9 @@ import {TGetSecretBlindIndexStatusResponse,TGetSecretsDuplicationDTO,TGetSecretsDuplicationResponse,+ TGetUnusedAccessActorDTO,+ TGetUnusedAccessActorResponse,TGetUnusedAccessDTO,- TGetUnusedAccessPrincipalDTO,- TGetUnusedAccessPrincipalResponse,TGetUnusedAccessResponse,TOrgAuthMethodUsage,TOrgProjectsInsights,@@ -41,8 +41,8 @@ export const secretInsightsKeys = {[...secretInsightsKeys.all(), "access-volume", params] as const,unusedAccess: (params: TGetUnusedAccessDTO) =>[...secretInsightsKeys.all(), "unused-access", params] as const,- unusedAccessPrincipal: (params: TGetUnusedAccessPrincipalDTO) =>- [...secretInsightsKeys.all(), "unused-access-principal", params] as const,+ unusedAccessActor: (params: TGetUnusedAccessActorDTO) =>+ [...secretInsightsKeys.all(), "unused-access-actor", params] as const,// accessLocations: (params: TGetSecretAccessLocationsDTO) =>// [...secretInsightsKeys.all(), "access-locations", params] as const,authMethodDistribution: (params: TGetAuthMethodDistributionDTO) =>@@ -161,23 +161,23 @@ export const useGetUnusedAccess = (});};-export const useGetUnusedAccessPrincipal = (- params: TGetUnusedAccessPrincipalDTO,+export const useGetUnusedAccessActor = (+ params: TGetUnusedAccessActorDTO,options?: Omit<UseQueryOptions<- TGetUnusedAccessPrincipalResponse,+ TGetUnusedAccessActorResponse,unknown,- TGetUnusedAccessPrincipalResponse,- ReturnType<typeof secretInsightsKeys.unusedAccessPrincipal>+ TGetUnusedAccessActorResponse,+ ReturnType<typeof secretInsightsKeys.unusedAccessActor>>,"queryKey" | "queryFn">) => {return useQuery({- queryKey: secretInsightsKeys.unusedAccessPrincipal(params),+ queryKey: secretInsightsKeys.unusedAccessActor(params),queryFn: async () => {- const res = await apiRequest.get<Omit<TGetUnusedAccessPrincipalResponse, "remainingTtl">>(- `/api/v1/insights/${params.projectId}/secrets/unused-access/${params.principalType}/${params.principalId}`+ const res = await apiRequest.get<Omit<TGetUnusedAccessActorResponse, "remainingTtl">>(+ `/api/v1/insights/${params.projectId}/secrets/unused-access/${params.actorType}/${params.actorId}`);const remainingTtl = Number(res.headers["x-cache-ttl"] ?? -1);return { ...res.data, remainingTtl };diff --git a/frontend/src/hooks/api/secretInsights/types.ts b/frontend/src/hooks/api/secretInsights/types.tsindex db3e293a59..4474424209 100644--- a/frontend/src/hooks/api/secretInsights/types.ts+++ b/frontend/src/hooks/api/secretInsights/types.ts@@ -51,24 +51,34 @@ export type TGetSecretAccessVolumeDTO = {projectId: string;};-export enum UnusedAccessPrincipalType {+export enum UnusedAccessActorType {User = "user",- Identity = "identity",- Group = "group"+ Identity = "identity"}-// A user, group or machine identity that can read secrets it has not read in the tracked period.-export type TUnusedAccessPrincipal = {- principalType: UnusedAccessPrincipalType;- principalId: string;+// A built-in role has no id; a custom role has the slug "custom" and its own id.+export type TUnusedAccessRole = {+ id: string | null;+ slug: string;+ name: string;+};++export type TUnusedAccessPaths = {+ roles: TUnusedAccessRole[];+ groups: { id: string; name: string; roles: TUnusedAccessRole[] }[];+ additionalPrivileges: { id: string; name: string }[];+};++// A user or machine identity that can read secrets it has not read in the tracked period.+export type TUnusedAccessActor = {+ actorType: UnusedAccessActorType;+ actorId: string;name: string;- // Groups only.- memberCount: number | null;entitledCount: number;unreadCount: number;environments: string[];lastReadAt: string | null;- accessVia: string[];+ accessPaths: TUnusedAccessPaths;};export type TGetUnusedAccessDTO = {@@ -79,17 +89,17 @@ export type TGetUnusedAccessDTO = {};export type TGetUnusedAccessResponse = {- principals: TUnusedAccessPrincipal[];+ actors: TUnusedAccessActor[];totalCount: number;trackingStartedAt: string;fullWindowFrom: string;remainingTtl: number;};-export type TGetUnusedAccessPrincipalDTO = {+export type TGetUnusedAccessActorDTO = {projectId: string;- principalType: UnusedAccessPrincipalType;- principalId: string;+ actorType: UnusedAccessActorType;+ actorId: string;};export type TUnusedSecret = {@@ -98,8 +108,8 @@ export type TUnusedSecret = {secretPath: string;};-export type TGetUnusedAccessPrincipalResponse = {- principal: TUnusedAccessPrincipal;+export type TGetUnusedAccessActorResponse = {+ actor: TUnusedAccessActor;secrets: TUnusedSecret[];unlistedCount: number;trackingStartedAt: string;diff --git a/frontend/src/pages/secret-manager/InsightsPage/components/UnusedAccessPrincipalSheet.tsx b/frontend/src/pages/secret-manager/InsightsPage/components/UnusedAccessActorSheet.tsxsimilarity index 80%rename from frontend/src/pages/secret-manager/InsightsPage/components/UnusedAccessPrincipalSheet.tsxrename to frontend/src/pages/secret-manager/InsightsPage/components/UnusedAccessActorSheet.tsxindex d0ff2ce488..f9bf5c38c9 100644--- a/frontend/src/pages/secret-manager/InsightsPage/components/UnusedAccessPrincipalSheet.tsx+++ b/frontend/src/pages/secret-manager/InsightsPage/components/UnusedAccessActorSheet.tsx@@ -23,22 +23,22 @@ import {} from "@app/components/v3";import { useProject } from "@app/context";import {- TGetUnusedAccessPrincipalResponse,- TUnusedAccessPrincipal,- UnusedAccessPrincipalType,- useGetUnusedAccessPrincipal+ TGetUnusedAccessActorResponse,+ TUnusedAccessActor,+ UnusedAccessActorType,+ useGetUnusedAccessActor} from "@app/hooks/api/secretInsights";-import { describeReadPeriod, PRINCIPAL_TYPE_CONFIG } from "./unusedAccessHelpers";+import { ACTOR_TYPE_CONFIG, describeReadPeriod } from "./unusedAccessHelpers";// Rows shown per environment before "N more" opens the rest.const PREVIEW_ROWS = 5;type SecretsProps = {- data: TGetUnusedAccessPrincipalResponse;+ data: TGetUnusedAccessActorResponse;};-const PrincipalSecrets = ({ data }: SecretsProps) => {+const ActorSecrets = ({ data }: SecretsProps) => {const { currentProject, projectId } = useProject();const { orgId } = useParams({ strict: false });const [expanded, setExpanded] = useState<Set<string>>(() => new Set());@@ -60,7 +60,7 @@ const PrincipalSecrets = ({ data }: SecretsProps) => {<EmptyDescription>{data.unlistedCount > 0? "Its unread secrets are in places you cannot see, or were deleted since the last update."- : "This principal has no unread secrets anymore."}+ : "It has no unread secrets anymore."}</EmptyDescription></EmptyHeader></Empty>@@ -130,23 +130,23 @@ const PrincipalSecrets = ({ data }: SecretsProps) => {};type Props = {- principal: TUnusedAccessPrincipal | null;+ actor: TUnusedAccessActor | null;onClose: () => void;};-export const UnusedAccessPrincipalSheet = ({ principal, onClose }: Props) => {+export const UnusedAccessActorSheet = ({ actor, onClose }: Props) => {const { projectId } = useProject();- const { data, isPending, error } = useGetUnusedAccessPrincipal(+ const { data, isPending, error } = useGetUnusedAccessActor({projectId,- principalType: principal?.principalType ?? UnusedAccessPrincipalType.User,- principalId: principal?.principalId ?? ""+ actorType: actor?.actorType ?? UnusedAccessActorType.User,+ actorId: actor?.actorId ?? ""},- { enabled: Boolean(principal) }+ { enabled: Boolean(actor) });const renderBody = () => {- if (!principal) return null;+ if (!actor) return null;if (isPending) return <Skeleton className="h-48 w-full" />;if (!data) {return (@@ -162,30 +162,26 @@ export const UnusedAccessPrincipalSheet = ({ principal, onClose }: Props) => {</Empty>);}- return (- <PrincipalSecrets key={`${principal.principalType}-${principal.principalId}`} data={data} />- );+ return <ActorSecrets key={`${actor.actorType}-${actor.actorId}`} data={data} />;};return (<Sheet- open={principal !== null}+ open={actor !== null}onOpenChange={(isOpen) => {if (!isOpen) onClose();}}><SheetContent size="form" side="right" onOpenAutoFocus={(event) => event.preventDefault()}>- {principal && (+ {actor && (<SheetHeader><SheetTitle className="flex items-center gap-2">- <span className="truncate">{principal.name}</span>- <Badge variant="neutral">- {PRINCIPAL_TYPE_CONFIG[principal.principalType].label}- </Badge>+ <span className="truncate">{actor.name}</span>+ <Badge variant="neutral">{ACTOR_TYPE_CONFIG[actor.actorType].label}</Badge></SheetTitle><SheetDescription>- Has not read {principal.unreadCount} of the {principal.entitledCount}{" "}- {principal.entitledCount === 1 ? "secret" : "secrets"} it can access{" "}+ 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"}diff --git a/frontend/src/pages/secret-manager/InsightsPage/components/UnusedAccessCard.tsx b/frontend/src/pages/secret-manager/InsightsPage/components/UnusedAccessCard.tsxindex 3be1634137..b835fcc0d1 100644--- a/frontend/src/pages/secret-manager/InsightsPage/components/UnusedAccessCard.tsx+++ b/frontend/src/pages/secret-manager/InsightsPage/components/UnusedAccessCard.tsx@@ -32,23 +32,24 @@ import {import { cn } from "@app/components/v3/utils";import { useProject, useSubscription } from "@app/context";import { usePagination, useResetPageHelper } from "@app/hooks";-import { TUnusedAccessPrincipal, useGetUnusedAccess } from "@app/hooks/api/secretInsights";+import { TUnusedAccessActor, useGetUnusedAccess } from "@app/hooks/api/secretInsights";+import { UnusedAccessActorSheet } from "./UnusedAccessActorSheet";import {+ accessPathBadges,+ ACTOR_TYPE_CONFIG,describeReadPeriod,formatRemainingTtl,- PRINCIPAL_TYPE_CONFIG,unusedSharePercent,unusedShareTone} from "./unusedAccessHelpers";-import { UnusedAccessPrincipalSheet } from "./UnusedAccessPrincipalSheet";export const UnusedAccessCard = () => {const { currentProject, projectId } = useProject();const { subscription } = useSubscription();const { page, setPage, perPage, setPerPage, offset, limit, search, setSearch, debouncedSearch } =usePagination("", { initPerPage: 10 });- const [selected, setSelected] = useState<TUnusedAccessPrincipal | null>(null);+ const [selected, setSelected] = useState<TUnusedAccessActor | null>(null);const { data, isPending, error } = useGetUnusedAccess({ projectId, offset, limit, search: debouncedSearch || undefined },@@ -87,7 +88,7 @@ export const UnusedAccessCard = () => {if (totalCount === 0) {// Recent access and new secrets are not judged yet, so this cannot claim everything was read.const description = debouncedSearch- ? "No overprivileged user, group or machine identity matches your search."+ ? "No overprivileged user or machine identity matches your search.": `No identity has left a secret it can access unread ${readPeriod}.`;return (<Empty className="border">@@ -122,18 +123,18 @@ export const UnusedAccessCard = () => {</span></TableHead><TableHead>Environments</TableHead>- <TableHead className="whitespace-nowrap">Access Via</TableHead>+ <TableHead className="whitespace-nowrap">Access Paths</TableHead><TableHead variant="action" /></TableRow></TableHeader><TableBody>- {data.principals.map((row) => {- const { icon: TypeIcon, label } = PRINCIPAL_TYPE_CONFIG[row.principalType];+ {data.actors.map((row) => {+ const { icon: TypeIcon, label } = ACTOR_TYPE_CONFIG[row.actorType];const percent = unusedSharePercent(row.unreadCount, row.entitledCount);const tone = unusedShareTone(percent);return (<TableRow- key={`${row.principalType}-${row.principalId}`}+ key={`${row.actorType}-${row.actorId}`}className="group/row cursor-pointer"onClick={() => setSelected(row)}>@@ -144,11 +145,6 @@ export const UnusedAccessCard = () => {<span className="flex items-center gap-2"><TypeIcon className="size-4 shrink-0 text-accent" />{label}- {row.memberCount != null && (- <span className="text-muted">- · {row.memberCount} {row.memberCount === 1 ? "member" : "members"}- </span>- )}</span></TableCell><TableCell>@@ -157,7 +153,8 @@ export const UnusedAccessCard = () => {<span>{row.unreadCount}{" "}<span className="text-muted">- of {row.entitledCount} {row.entitledCount === 1 ? "secret" : "secrets"}+ of {row.entitledCount}{" "}+ {row.entitledCount === 1 ? "secret unread" : "secrets unread"}</span></span><span className={cn("tabular-nums", tone.text)}>{percent}%</span>@@ -181,9 +178,9 @@ export const UnusedAccessCard = () => {</TableCell><TableCell className="max-w-64"><OverflowBadgeList- items={row.accessVia}- getKey={(item) => item}- getLabel={(item) => item}+ items={accessPathBadges(row.accessPaths)}+ getKey={(item) => item.key}+ getLabel={(item) => item.label}getVariant={() => "neutral"}/></TableCell>@@ -219,8 +216,8 @@ export const UnusedAccessCard = () => {)}</CardTitle><CardDescription>- Users, groups, and machine identities with access to secrets they have not read{" "}- {readPeriod}. Select one to see those secrets.+ Users and machine identities with access to secrets they have not read {readPeriod}.+ Select one to see those secrets.</CardDescription></CardHeader><CardContent className="flex flex-col gap-4">@@ -241,7 +238,7 @@ export const UnusedAccessCard = () => {{renderBody()}</CardContent></Card>- <UnusedAccessPrincipalSheet principal={selected} onClose={() => setSelected(null)} />+ <UnusedAccessActorSheet actor={selected} onClose={() => setSelected(null)} /></>);};diff --git a/frontend/src/pages/secret-manager/InsightsPage/components/unusedAccessHelpers.ts b/frontend/src/pages/secret-manager/InsightsPage/components/unusedAccessHelpers.tsindex eeec844e89..980f6af67b 100644--- a/frontend/src/pages/secret-manager/InsightsPage/components/unusedAccessHelpers.ts+++ b/frontend/src/pages/secret-manager/InsightsPage/components/unusedAccessHelpers.ts@@ -1,31 +1,47 @@import { format } from "date-fns";-import { HardDriveIcon, UserIcon, UsersIcon } from "lucide-react";+import { HardDriveIcon, UserIcon } from "lucide-react";-import { UnusedAccessPrincipalType } from "@app/hooks/api/secretInsights";+import { TUnusedAccessPaths, UnusedAccessActorType } from "@app/hooks/api/secretInsights";-export const PRINCIPAL_TYPE_CONFIG: Record<- UnusedAccessPrincipalType,+export const ACTOR_TYPE_CONFIG: Record<+ UnusedAccessActorType,{ icon: typeof UserIcon; label: string }> = {- [UnusedAccessPrincipalType.User]: { icon: UserIcon, label: "User" },- [UnusedAccessPrincipalType.Identity]: { icon: HardDriveIcon, label: "Machine Identity" },- [UnusedAccessPrincipalType.Group]: { icon: UsersIcon, label: "Group" }+ [UnusedAccessActorType.User]: { icon: UserIcon, label: "User" },+ [UnusedAccessActorType.Identity]: { icon: HardDriveIcon, label: "Machine Identity" }};+export const accessPathBadges = ({ roles, additionalPrivileges, groups }: TUnusedAccessPaths) => [+ ...roles.map((role) => ({+ key: `role:${role.slug}:${role.id ?? ""}`,+ label: `Role: ${role.name}`+ })),+ ...additionalPrivileges.map((privilege) => ({+ key: `privilege:${privilege.id}`,+ label: `Privilege: ${privilege.name}`+ })),+ ...groups.map((group) => ({+ key: `group:${group.id}`,+ label: group.roles.length+ ? `Group: ${group.name} (${group.roles.map((role) => role.name).join(", ")})`+ : `Group: ${group.name}`+ }))+];+// 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")}`: "in the last 30 days";-// The share of the secrets a principal can read that it has not read, as a whole percentage that only reads 0+// 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)));};-// Most of its access unread is the strongest sign a principal has access it does not need.+// Most of its access unread is the strongest sign an actor has access it does not need.export const unusedShareTone = (percent: number) => {if (percent >= 75) return { text: "text-danger", bar: "bg-danger" };if (percent >= 25) return { text: "text-warning", bar: "bg-warning" };