Skip to content

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

feat(insights): list unused access per user, group and machine identity instead of per secret

Dimitris Staratzis3b3ffb44a0fb
diff --git a/backend/src/ee/routes/v1/insights-router.ts b/backend/src/ee/routes/v1/insights-router.ts
index 3afa8743ea..de0ce2171d 100644
--- a/backend/src/ee/routes/v1/insights-router.ts
+++ b/backend/src/ee/routes/v1/insights-router.ts
@@ -17,14 +17,14 @@ import {
import {
OrgAuthMethodDistributionSchema,
OrgSecretsAccessVolumeSchema,
- SecretExposureListSchema,
SecretsProjectsSchema,
SecretsSummarySchema,
- StaticSecretsUsageSchema
+ StaticSecretsUsageSchema,
+ UnusedAccessPrincipalSchema,
+ UnusedAccessSchema
} from "@app/ee/services/insights/insights-schemas";
-import { SecretExposureOrderBy } from "@app/ee/services/secret-read-activity/secret-read-activity-types";
+import { UnusedAccessPrincipalType } from "@app/ee/services/secret-read-activity/secret-read-activity-types";
import { INSIGHTS } from "@app/lib/api-docs";
-import { OrderByDirection } from "@app/lib/types";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AuthMode } from "@app/services/auth/auth-type";
@@ -471,46 +471,34 @@ export const registerInsightsRouter = async (server: FastifyZodProvider) => {
server.route({
method: "GET",
- url: "/:projectId/secrets/exposure",
+ url: "/:projectId/secrets/unused-access",
config: { rateLimit: readLimit },
schema: {
- operationId: "getInsightsSecretExposure",
+ operationId: "getInsightsUnusedAccess",
description:
- "List the secrets with the highest exposure score in a project, with how many of the project's secrets fall in each band",
+ "List the users, groups and machine identities that can read secrets they have not read in the tracked period, those with the most such secrets first",
security: [{ bearerAuth: [] }],
params: z.object({
- projectId: z.string().trim().max(36).describe(INSIGHTS.GET_SECRET_EXPOSURE.projectId)
+ projectId: z.string().trim().max(36).describe(INSIGHTS.GET_UNUSED_ACCESS.projectId)
}),
querystring: z.object({
- offset: z.coerce.number().int().min(0).max(500).default(0).describe(INSIGHTS.GET_SECRET_EXPOSURE.offset),
- limit: z.coerce.number().int().min(1).max(100).default(10).describe(INSIGHTS.GET_SECRET_EXPOSURE.limit),
- orderBy: z.nativeEnum(SecretExposureOrderBy).optional().describe(INSIGHTS.GET_SECRET_EXPOSURE.orderBy),
- orderDirection: z
- .nativeEnum(OrderByDirection)
- .default(OrderByDirection.ASC)
- .describe(INSIGHTS.GET_SECRET_EXPOSURE.orderDirection)
+ offset: z.coerce.number().int().min(0).max(10000).default(0).describe(INSIGHTS.GET_UNUSED_ACCESS.offset),
+ limit: z.coerce.number().int().min(1).max(100).default(20).describe(INSIGHTS.GET_UNUSED_ACCESS.limit),
+ search: z.string().trim().max(255).optional().describe(INSIGHTS.GET_UNUSED_ACCESS.search)
}),
response: {
- 200: SecretExposureListSchema
+ 200: UnusedAccessSchema
}
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),
handler: async (req, reply) => {
const { projectId } = req.params;
- const {
- secrets,
- totalCount,
- unlistedCount,
- bands,
- trackingStartedAt,
- preliminaryUntil,
- remainingTTL,
- projectName
- } = await server.services.secretReadActivity.listSecretExposure({ projectId, ...req.query }, req.permission);
+ const { principals, totalCount, trackingStartedAt, preliminaryUntil, remainingTTL, projectName } =
+ await server.services.secretReadActivity.listUnusedAccess({ projectId, ...req.query }, req.permission);
await server.services.auditLog.createAuditLog({
projectId,
event: {
- type: EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_SECRET_EXPOSURE,
+ type: EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_UNUSED_ACCESS,
metadata: { projectId, projectName }
},
...req.auditLogInfo
@@ -519,7 +507,51 @@ export const registerInsightsRouter = async (server: FastifyZodProvider) => {
if (remainingTTL && remainingTTL >= 0) {
void reply.header("X-Cache-TTL", remainingTTL);
}
- return { secrets, totalCount, unlistedCount, bands, trackingStartedAt, preliminaryUntil };
+ return { principals, totalCount, trackingStartedAt, preliminaryUntil };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:projectId/secrets/unused-access/:principalType/:principalId",
+ config: { rateLimit: readLimit },
+ schema: {
+ operationId: "getInsightsUnusedAccessPrincipal",
+ description:
+ "List the secrets one user, group or machine identity can read but has not read in the tracked period",
+ 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)
+ }),
+ response: {
+ 200: UnusedAccessPrincipalSchema
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),
+ handler: async (req, reply) => {
+ const { projectId, principalType, principalId } = req.params;
+ const { principal, secrets, unlistedCount, trackingStartedAt, preliminaryUntil, remainingTTL, projectName } =
+ await server.services.secretReadActivity.getUnusedAccessPrincipal(
+ { projectId, principalType, principalId },
+ 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 }
+ },
+ ...req.auditLogInfo
+ });
+
+ if (remainingTTL && remainingTTL >= 0) {
+ void reply.header("X-Cache-TTL", remainingTTL);
+ }
+ return { principal, secrets, unlistedCount, trackingStartedAt, preliminaryUntil };
}
});
diff --git a/backend/src/ee/services/audit-log/audit-log-event-classes.ts b/backend/src/ee/services/audit-log/audit-log-event-classes.ts
index 6d156616d2..0df31a673d 100644
--- a/backend/src/ee/services/audit-log/audit-log-event-classes.ts
+++ b/backend/src/ee/services/audit-log/audit-log-event-classes.ts
@@ -218,7 +218,7 @@ const DATA_ACCESS_EVENT_TYPES: readonly EventType[] = [
EventType.VIEW_INSIGHTS_AUTH_METHODS,
EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_CALENDAR,
EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_ACCESS_VOLUME,
- EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_SECRET_EXPOSURE,
+ EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_UNUSED_ACCESS,
EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_ORG_AUTH_METHOD_DISTRIBUTION,
EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_ACCESS_LOCATIONS,
EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_SUMMARY,
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index e9bbb0e435..ce7b5f2a5d 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -746,7 +746,7 @@ export enum EventType {
VIEW_INSIGHTS_AUTH_METHODS = "view-insights-auth-methods",
VIEW_INSIGHTS_SECRETS_MANAGEMENT_CALENDAR = "view-insights-secrets-management-calendar",
VIEW_INSIGHTS_SECRETS_MANAGEMENT_ACCESS_VOLUME = "view-insights-secrets-management-access-volume",
- VIEW_INSIGHTS_SECRETS_MANAGEMENT_SECRET_EXPOSURE = "view-insights-secrets-management-secret-exposure",
+ VIEW_INSIGHTS_SECRETS_MANAGEMENT_UNUSED_ACCESS = "view-insights-secrets-management-unused-access",
VIEW_INSIGHTS_SECRETS_MANAGEMENT_ORG_AUTH_METHOD_DISTRIBUTION = "view-insights-secrets-management-org-auth-method-distribution",
VIEW_INSIGHTS_SECRETS_MANAGEMENT_ACCESS_LOCATIONS = "view-insights-secrets-management-access-locations",
VIEW_INSIGHTS_SECRETS_MANAGEMENT_SUMMARY = "view-insights-secrets-management-summary",
@@ -5954,11 +5954,15 @@ interface ViewSecretManagementInsightsAccessVolumeEvent {
};
}
-interface ViewSecretManagementInsightsSecretExposureEvent {
- type: EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_SECRET_EXPOSURE;
+interface ViewSecretManagementInsightsUnusedAccessEvent {
+ type: EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_UNUSED_ACCESS;
metadata: {
projectId: string;
projectName: string;
+ // Set when one principal's unused secrets were viewed rather than the project list.
+ principalType?: string;
+ principalId?: string;
+ principalName?: string;
};
}
@@ -8536,7 +8540,7 @@ export type Event =
| DashboardGetSecretVersionValueEvent
| ViewSecretManagementInsightsCalendarEvent
| ViewSecretManagementInsightsAccessVolumeEvent
- | ViewSecretManagementInsightsSecretExposureEvent
+ | ViewSecretManagementInsightsUnusedAccessEvent
| ViewSecretManagementInsightsOrgAuthMethodDistributionEvent
| ViewSecretManagementInsightsAccessLocationsEvent
| ViewInsightsAuthMethodsEvent
diff --git a/backend/src/ee/services/insights/insights-schemas.ts b/backend/src/ee/services/insights/insights-schemas.ts
index 9b97e6bbf5..3891a08009 100644
--- a/backend/src/ee/services/insights/insights-schemas.ts
+++ b/backend/src/ee/services/insights/insights-schemas.ts
@@ -1,11 +1,7 @@
import { z } from "zod";
import { IdentityAuthMethod } from "@app/db/schemas";
-import {
- SecretExposureCountsSchema,
- SecretExposureSchema
-} from "@app/ee/services/secret-read-activity/secret-read-activity-schemas";
-import { SecretExposureBand } from "@app/ee/services/secret-read-activity/secret-read-activity-types";
+import { UnusedAccessPrincipalType } from "@app/ee/services/secret-read-activity/secret-read-activity-types";
import { INSIGHTS } from "@app/lib/api-docs";
export const SecretsSummarySchema = z.object({
@@ -71,20 +67,36 @@ export const SecretsProjectsSchema = z.object({
limit: z.number().int().describe(INSIGHTS.GET_SECRETS_PROJECTS.limit)
});
-export const SecretExposureListSchema = z.object({
- totalCount: z.number().int().describe(INSIGHTS.GET_SECRET_EXPOSURE.totalCount),
- unlistedCount: z.number().int().describe(INSIGHTS.GET_SECRET_EXPOSURE.unlistedCount),
- bands: z.record(z.nativeEnum(SecretExposureBand), z.number().int()).describe(INSIGHTS.GET_SECRET_EXPOSURE.bands),
- trackingStartedAt: z.date().describe(INSIGHTS.GET_SECRET_EXPOSURE.trackingStartedAt),
- preliminaryUntil: z.date().describe(INSIGHTS.GET_SECRET_EXPOSURE.preliminaryUntil),
+const UnusedAccessPrincipalRowSchema = z.object({
+ principalType: z.nativeEnum(UnusedAccessPrincipalType).describe(INSIGHTS.GET_UNUSED_ACCESS.principalType),
+ principalId: z.string().describe(INSIGHTS.GET_UNUSED_ACCESS.principalId),
+ 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)
+});
+
+export const UnusedAccessSchema = z.object({
+ totalCount: z.number().int().describe(INSIGHTS.GET_UNUSED_ACCESS.totalCount),
+ trackingStartedAt: z.date().describe(INSIGHTS.GET_UNUSED_ACCESS.trackingStartedAt),
+ preliminaryUntil: z.date().describe(INSIGHTS.GET_UNUSED_ACCESS.preliminaryUntil),
+ principals: UnusedAccessPrincipalRowSchema.array().describe(INSIGHTS.GET_UNUSED_ACCESS.principals)
+});
+
+export const UnusedAccessPrincipalSchema = z.object({
+ principal: UnusedAccessPrincipalRowSchema,
+ unlistedCount: z.number().int().describe(INSIGHTS.GET_UNUSED_ACCESS_PRINCIPAL.unlistedCount),
+ trackingStartedAt: z.date().describe(INSIGHTS.GET_UNUSED_ACCESS.trackingStartedAt),
+ preliminaryUntil: z.date().describe(INSIGHTS.GET_UNUSED_ACCESS.preliminaryUntil),
secrets: z
.object({
- secretKey: z.string().describe(INSIGHTS.GET_SECRET_EXPOSURE.secretKey),
- environment: z.string().describe(INSIGHTS.GET_SECRET_EXPOSURE.environment),
- secretPath: z.string().describe(INSIGHTS.GET_SECRET_EXPOSURE.secretPath),
- exposure: SecretExposureSchema
+ 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)
})
- .merge(SecretExposureCountsSchema)
.array()
- .describe(INSIGHTS.GET_SECRET_EXPOSURE.secrets)
+ .describe(INSIGHTS.GET_UNUSED_ACCESS_PRINCIPAL.secrets)
});
diff --git a/backend/src/ee/services/permission/permission-service-types.ts b/backend/src/ee/services/permission/permission-service-types.ts
index 4279346294..fac85f1162 100644
--- a/backend/src/ee/services/permission/permission-service-types.ts
+++ b/backend/src/ee/services/permission/permission-service-types.ts
@@ -162,18 +162,23 @@ export type TPermissionServiceFactory = {
id: string;
name: string;
membershipId: string;
+ roles: { role: string; customRoleSlug?: string | null }[];
+ hasAdditionalPrivileges: boolean;
}[];
identityPermissions: {
permission: MongoAbility<ProjectPermissionSet, MongoQuery>;
id: string;
name: string;
membershipId: string;
+ roles: { role: string; customRoleSlug?: string | null }[];
+ hasAdditionalPrivileges: boolean;
}[];
groupPermissions: {
permission: MongoAbility<ProjectPermissionSet, MongoQuery>;
id: string;
name: string;
membershipId: string;
+ roles: { role: string; customRoleSlug?: string | null }[];
}[];
}>;
getOrgPermissionByRoles: (
diff --git a/backend/src/ee/services/permission/permission-service.ts b/backend/src/ee/services/permission/permission-service.ts
index 6fbc958a82..aba3947879 100644
--- a/backend/src/ee/services/permission/permission-service.ts
+++ b/backend/src/ee/services/permission/permission-service.ts
@@ -996,7 +996,9 @@ export const permissionServiceFactory = ({
permission,
id: userProjectPermission.userId,
membershipId: userProjectPermission.id,
- name: userProjectPermission.username
+ name: userProjectPermission.username,
+ roles: (userProjectPermission.roles ?? []).map(({ role, customRoleSlug }) => ({ role, customRoleSlug })),
+ hasAdditionalPrivileges: Boolean(userProjectPermission.additionalPrivileges?.length)
};
});
@@ -1039,7 +1041,9 @@ export const permissionServiceFactory = ({
permission,
id: identityProjectPermission.identityId,
membershipId: identityProjectPermission.id,
- name: identityProjectPermission.username
+ name: identityProjectPermission.username,
+ roles: (identityProjectPermission.roles ?? []).map(({ role, customRoleSlug }) => ({ role, customRoleSlug })),
+ hasAdditionalPrivileges: Boolean(identityProjectPermission.additionalPrivileges?.length)
};
});
@@ -1057,7 +1061,8 @@ export const permissionServiceFactory = ({
permission,
id: groupProjectPermission.groupId,
membershipId: groupProjectPermission.id,
- name: groupProjectPermission.username
+ name: groupProjectPermission.username,
+ roles: (groupProjectPermission.roles ?? []).map(({ role, customRoleSlug }) => ({ role, customRoleSlug }))
};
});
diff --git a/backend/src/ee/services/secret-read-activity/secret-read-activity-dal.ts b/backend/src/ee/services/secret-read-activity/secret-read-activity-dal.ts
index cae7852146..2162290c22 100644
--- a/backend/src/ee/services/secret-read-activity/secret-read-activity-dal.ts
+++ b/backend/src/ee/services/secret-read-activity/secret-read-activity-dal.ts
@@ -138,6 +138,7 @@ export const secretReadActivityDALFactory = (db: TDbClient) => {
type TAccessChange = {
actorUserId?: string | null;
actorIdentityId?: string | null;
+ actorGroupId?: string | null;
groupMemberId?: string | null;
membershipCreatedAt?: Date | null;
createdAt: Date;
@@ -185,6 +186,7 @@ export const secretReadActivityDALFactory = (db: TDbClient) => {
roleChanges((tx || db.replicaNode())(TableName.Membership)).select(
db.ref("actorUserId").withSchema(TableName.Membership),
db.ref("actorIdentityId").withSchema(TableName.Membership),
+ db.ref("actorGroupId").withSchema(TableName.Membership),
db.ref("createdAt").withSchema(TableName.Membership).as("membershipCreatedAt"),
...roleColumns
),
@@ -198,7 +200,8 @@ export const secretReadActivityDALFactory = (db: TDbClient) => {
const now = new Date();
const changedAtByActorId = new Map<string, Date>();
[...directChanges, ...userGroupChanges, ...identityGroupChanges, ...privilegeChanges].forEach((change) => {
- const actorId = change.actorUserId ?? change.actorIdentityId ?? change.groupMemberId;
+ // A group's own date judges the group as a principal; its members' dates come from the group rows.
+ const actorId = change.actorUserId ?? change.actorIdentityId ?? change.groupMemberId ?? change.actorGroupId;
if (!actorId) return;
const dates = [change.createdAt, change.updatedAt];
if (change.membershipCreatedAt) dates.push(change.membershipCreatedAt);
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 9e8a94b82f..c7769f9951 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,4 +1,4 @@
-import { SecretType, TableName } from "@app/db/schemas";
+import { ProjectMembershipRole, SecretType, TableName } from "@app/db/schemas";
import { DAY_IN_MS } from "@app/ee/services/audit-report/audit-report-fns";
import { TIdentityGroupMembershipDALFactory } from "@app/ee/services/group/identity-group-membership-dal";
import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";
@@ -14,13 +14,14 @@ import { getCacheTtl, withCache } from "@app/lib/cache/with-cache";
import { NotFoundError } from "@app/lib/errors";
import { groupBy } from "@app/lib/fn";
import { logger } from "@app/lib/logger";
-import { OrderByDirection, OrgServiceActor } from "@app/lib/types";
+import { OrgServiceActor } from "@app/lib/types";
import { ActorType } from "@app/services/auth/auth-type";
import { TIdentityDALFactory } from "@app/services/identity/identity-dal";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { KmsDataKey } from "@app/services/kms/kms-types";
import { TProjectDALFactory } from "@app/services/project/project-dal";
import { TProjectEnvDALFactory } from "@app/services/project-env/project-env-dal";
+import { TRoleDALFactory } from "@app/services/role/role-dal";
import { TSecretFolderDALFactory } from "@app/services/secret-folder/secret-folder-dal";
import { TSecretImportDALFactory } from "@app/services/secret-import/secret-import-dal";
import { getAllSecretReferences } from "@app/services/secret-v2-bridge/secret-reference-fns";
@@ -42,30 +43,35 @@ import {
} from "./secret-read-activity-fns";
import { TSecretReadActivityQueueServiceFactory } from "./secret-read-activity-queue";
import {
- SecretExposureBand,
TEntitledReader,
- TExposedSecret,
TGetSecretReadActivityDTO,
- TListSecretExposureDTO,
+ TGetUnusedAccessPrincipalDTO,
+ TListUnusedAccessDTO,
TReachSecret,
TReadActivityScope,
- TSecretExposureCounts,
- TSecretLocation,
TSecretReach,
TSecretReachGraph,
- TSecretReaderType
+ TSecretReaderType,
+ TUnusedAccessPrincipal,
+ TUnusedSecret,
+ UnusedAccessPrincipalType
} from "./secret-read-activity-types";
-const SECRET_EXPOSURE_CACHE_TTL_SECONDS = 24 * 60 * 60;
+const UNUSED_ACCESS_CACHE_TTL_SECONDS = 24 * 60 * 60;
const REACH_YIELD_INTERVAL = 100;
// Longer than a computation can take, so the lock is not lost mid-scan; waiters give up well before a request times out.
-const SECRET_EXPOSURE_COMPUTE_LOCK_TTL_MS = 5 * 60 * 1000;
-const SECRET_EXPOSURE_COMPUTE_WAIT_SECONDS = 60;
-// A large project can have hundreds of thousands of secrets, so only the highest-scoring ones are cached and
-// listed, about 250 KB per project; the per-band tally still covers them all.
-const SECRET_EXPOSURE_MAX_LISTED = 500;
-
-type TCachedExposedSecret = TExposedSecret & { secretId: string };
+const UNUSED_ACCESS_COMPUTE_LOCK_TTL_MS = 5 * 60 * 1000;
+const UNUSED_ACCESS_COMPUTE_WAIT_SECONDS = 60;
+// Every principal's row is cached, but the unread secret ids behind the rows only for the principals with the most
+// of them, capped per principal, which keeps a project's entry under about 1.5 MB.
+const UNUSED_ACCESS_DETAIL_MAX_PRINCIPALS = 200;
+const UNUSED_ACCESS_MAX_SECRETS_PER_PRINCIPAL = 200;
+const ROLE_LABELS: Record<string, string> = {
+ admin: "Admin",
+ member: "Member",
+ viewer: "Viewer",
+ "no-access": "No Access"
+};
type TSecretPermission = Parameters<typeof hasSecretReadValueOrDescribePermission>[0];
type TSecretReadActivityServiceFactoryDep = {
@@ -84,6 +90,7 @@ type TSecretReadActivityServiceFactoryDep = {
identityDAL: Pick<TIdentityDALFactory, "find">;
userGroupMembershipDAL: Pick<TUserGroupMembershipDALFactory, "find">;
identityGroupMembershipDAL: Pick<TIdentityGroupMembershipDALFactory, "find">;
+ roleDAL: Pick<TRoleDALFactory, "find">;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
keyStore: Pick<TKeyStoreFactory, "setItemWithExpiry" | "getItem" | "ttl" | "acquireLock">;
};
@@ -103,6 +110,7 @@ export const secretReadActivityServiceFactory = ({
identityDAL,
userGroupMembershipDAL,
identityGroupMembershipDAL,
+ roleDAL,
kmsService,
keyStore
}: TSecretReadActivityServiceFactoryDep) => {
@@ -275,11 +283,12 @@ export const secretReadActivityServiceFactory = ({
};
};
- // How each secret stands, from everyone who can read its value today, admins included: unused access is
- // judged on the non-admins among them, since admins can read everything by design; ghost readers are readers
- // in the window who are not among them at all, so their access was since removed; and the exposure score is
- // computed from those counts. In a project tracked for less than the window, the window starts when tracking
- // did, so the results are preliminary.
+ // How each secret stands, from everyone who can read its value today: unused access is judged on the
+ // non-admins among them, since admins can read everything by design; ghost readers are readers in the window
+ // who are not among them at all, so their access was since removed; and the exposure score is computed from
+ // those counts. Groups are judged on their own too: a group's access to a secret is unused when none of its
+ // members read it. In a project tracked for less than the window, the window starts when tracking did, so the
+ // results are preliminary.
const $loadSecretSummarizer = async (projectId: string, orgId: string, windowStart: Date) => {
const [
{ userPermissions, identityPermissions, groupPermissions },
@@ -326,22 +335,37 @@ export const secretReadActivityServiceFactory = ({
];
// Actors with identical rules always get the same answer, so each distinct rule set is checked once.
const actorGroups = Object.values(groupBy(actors, (actor) => JSON.stringify(actor.permission.rules)));
- const actorNames = new Map(
+ const actorNames = new Map<string, string>(
actors.flatMap((actor) => (actor.name ? [[`${actor.actorType}:${actor.id}`, actor.name] as const] : []))
);
+ // Admin groups can read everything by design, so like admins they are left out.
+ const memberKeysByGroupId = new Map<string, string[]>();
+ const addMember = (groupId: string, key: string) =>
+ memberKeysByGroupId.set(groupId, [...(memberKeysByGroupId.get(groupId) ?? []), key]);
+ userGroupMemberships.forEach((membership) =>
+ addMember(membership.groupId, `${ActorType.USER}:${membership.userId}`)
+ );
+ identityGroupMemberships.forEach((membership) =>
+ addMember(membership.groupId, `${ActorType.IDENTITY}:${membership.identityId}`)
+ );
+ const groups = groupPermissions
+ .filter((group) => !group.roles.some((role) => role.role === ProjectMembershipRole.Admin))
+ .map((group) => ({ ...group, memberKeys: memberKeysByGroupId.get(group.id) ?? [] }));
+
const summarize = ({ secret, environment, secretPath, trackedSince, reads }: TSecretActivity) => {
+ const subject = {
+ environment,
+ secretPath,
+ secretName: secret.key,
+ secretTags: secret.tags?.map((tag) => tag.slug)
+ };
+ const canReadValue = (permission: TActor["permission"]) =>
+ hasSecretReadValueOrDescribePermission(permission, ProjectPermissionSecretActions.ReadValue, subject);
const entitled = [
...new Map(
actorGroups
- .filter(([{ permission }]) =>
- hasSecretReadValueOrDescribePermission(permission, ProjectPermissionSecretActions.ReadValue, {
- environment,
- secretPath,
- secretName: secret.key,
- secretTags: secret.tags?.map((tag) => tag.slug)
- })
- )
+ .filter(([{ permission }]) => canReadValue(permission))
.flat()
.map((actor) => [`${actor.actorType}:${actor.id}`, actor] as const)
).values()
@@ -358,19 +382,39 @@ export const secretReadActivityServiceFactory = ({
const ghostReaders = [...reads.values()].filter(
(read) => !entitledKeys.has(`${read.actorType}:${read.actorId}`) && !adminActorIds.has(read.actorId)
);
+ const entitledGroups = groups.filter((group) => canReadValue(group.permission));
+ const unreadGroups = entitledGroups.filter(
+ (group) =>
+ !group.memberKeys.some((key) => reads.has(key)) &&
+ coversWholeWindow(trackedSince, accessChangedAtByActorId.get(group.id), judgedFrom)
+ );
return {
entitled,
exposedTo,
unread,
ghostReaders,
+ entitledGroups,
+ unreadGroups,
exposure: calculateExposureScore(
{ entitledCount: exposedTo.length, unreadCount: unread.length, ghostReaderCount: ghostReaders.length },
trackedDays
)
};
};
- return { summarize, actorNames, judgedFrom, trackedDays, accessChangedAtByActorId, adminActorIds };
+ return {
+ summarize,
+ actorNames,
+ groups,
+ userPermissions,
+ identityPermissions,
+ judgedFrom,
+ trackedDays,
+ accessChangedAtByActorId,
+ adminActorIds
+ };
};
+ type TSummarizer = Awaited<ReturnType<typeof $loadSecretSummarizer>>;
+ type TSecretSummary = ReturnType<TSummarizer["summarize"]>;
const getSecretReadActivity = async (
{ projectId, environment, secretPath, secretName }: TGetSecretReadActivityDTO,
@@ -457,77 +501,204 @@ export const secretReadActivityServiceFactory = ({
};
};
- // Every secret's exposure, keeping the highest-scoring ones and a tally of how many fall in each band.
- const $computeProjectExposure = async (projectId: string, orgId: string) => {
+ // Walks every secret once and hands each one's summary to `visit`. The permission checks are synchronous, so it
+ // yields between secrets to keep a large project from blocking other requests.
+ const $walkSecrets = async (
+ projectId: string,
+ orgId: string,
+ visit: (activity: TSecretActivity, summary: TSecretSummary) => void
+ ) => {
const windowStart = getReadActivityWindowStart();
- const [activities, { summarize, trackedDays }] = await Promise.all([
+ const [activities, summarizer] = await Promise.all([
$getReadActivity({ projectId, windowStart }),
$loadSecretSummarizer(projectId, orgId, windowStart)
]);
-
- // Only counts and the score are kept for every secret; the listed ones are built from them afterwards.
- const summaries: (TSecretExposureCounts & { activityIndex: number; score: number })[] = [];
- const bands: Record<SecretExposureBand, number> = { low: 0, elevated: 0, high: 0, critical: 0 };
- for (let activityIndex = 0; activityIndex < activities.length; activityIndex += 1) {
- // Permission checks are synchronous, so yield between secrets to keep a large project from blocking other requests.
+ for (let index = 0; index < activities.length; index += 1) {
// eslint-disable-next-line no-await-in-loop
await new Promise<void>((resolve) => {
setImmediate(resolve);
});
- const { exposedTo, unread, ghostReaders, exposure } = summarize(activities[activityIndex]);
- summaries.push({
- activityIndex,
- entitledCount: exposedTo.length,
- unreadCount: unread.length,
- ghostReaderCount: ghostReaders.length,
- score: exposure.score
- });
- bands[exposure.band] += 1;
+ visit(activities[index], summarizer.summarize(activities[index]));
}
+ return summarizer;
+ };
- // A secret scoring 0 has nobody who can read it, so there is nothing to list.
- const scored = summaries.filter((summary) => summary.score > 0).sort((a, b) => b.score - a.score);
- const mostExposed = scored
- .slice(0, SECRET_EXPOSURE_MAX_LISTED)
- .map(({ activityIndex, score, ...counts }): TCachedExposedSecret => {
- const activity = activities[activityIndex];
- return {
- secretId: activity.secret.id,
- secretKey: activity.secret.key,
- environment: activity.environment,
- secretPath: activity.secretPath,
- ...counts,
- exposure: calculateExposureScore(counts, trackedDays)
+ const toPrincipalType = (actorType: TSecretReaderType) =>
+ actorType === ActorType.USER ? UnusedAccessPrincipalType.User : UnusedAccessPrincipalType.Identity;
+ const principalKey = (principalType: UnusedAccessPrincipalType, principalId: string) =>
+ `${principalType}:${principalId}`;
+
+ // Everyone who can read secrets they have not read in the window: users and machine identities, whether through
+ // a role, a privilege or a group, and the groups themselves. Ranked by how many such secrets they have.
+ const $computeUnusedAccess = async (projectId: string, orgId: string) => {
+ type TStat = {
+ principalType: UnusedAccessPrincipalType;
+ principalId: string;
+ entitledCount: number;
+ unreadCount: number;
+ unreadSecretIds: string[];
+ environments: Set<string>;
+ };
+ const stats = new Map<string, TStat>();
+ const statOf = (principalType: UnusedAccessPrincipalType, principalId: string) => {
+ const key = principalKey(principalType, principalId);
+ let stat = stats.get(key);
+ if (!stat) {
+ stat = {
+ principalType,
+ principalId,
+ entitledCount: 0,
+ unreadCount: 0,
+ unreadSecretIds: [],
+ environments: new Set()
};
- });
+ stats.set(key, stat);
+ }
+ return stat;
+ };
+ const markUnread = (principalType: UnusedAccessPrincipalType, principalId: string, activity: TSecretActivity) => {
+ const stat = statOf(principalType, principalId);
+ stat.unreadCount += 1;
+ stat.environments.add(activity.environment);
+ if (stat.unreadSecretIds.length < UNUSED_ACCESS_MAX_SECRETS_PER_PRINCIPAL) {
+ stat.unreadSecretIds.push(activity.secret.id);
+ }
+ };
+ const lastReadAtByKey = new Map<string, number>();
+
+ const { actorNames, groups, userPermissions, identityPermissions } = await $walkSecrets(
+ projectId,
+ orgId,
+ (activity, summary) => {
+ summary.exposedTo.forEach((actor) => {
+ statOf(toPrincipalType(actor.actorType), actor.id).entitledCount += 1;
+ });
+ summary.unread.forEach((actor) => markUnread(toPrincipalType(actor.actorType), actor.id, activity));
+ summary.entitledGroups.forEach((group) => {
+ statOf(UnusedAccessPrincipalType.Group, group.id).entitledCount += 1;
+ });
+ summary.unreadGroups.forEach((group) => markUnread(UnusedAccessPrincipalType.Group, group.id, activity));
+ activity.reads.forEach((read, key) => {
+ lastReadAtByKey.set(key, Math.max(lastReadAtByKey.get(key) ?? 0, read.lastReadAt.getTime()));
+ });
+ }
+ );
- return { mostExposed, bands, scoredCount: scored.length };
+ const ranked = [...stats.values()]
+ .filter((stat) => stat.unreadCount > 0)
+ .sort((a, b) => b.unreadCount - a.unreadCount || a.entitledCount - b.entitledCount);
+
+ // Direct members and groups come named; members who have the access only through a group are looked up.
+ groups.forEach((group) => actorNames.set(principalKey(UnusedAccessPrincipalType.Group, group.id), group.name));
+ const unnamed = ranked.filter((stat) => !actorNames.has(principalKey(stat.principalType, stat.principalId)));
+ const idsOf = (principalType: UnusedAccessPrincipalType) =>
+ unnamed.filter((stat) => stat.principalType === principalType).map((stat) => stat.principalId);
+ const [userIds, identityIds] = [idsOf(UnusedAccessPrincipalType.User), idsOf(UnusedAccessPrincipalType.Identity)];
+ const [users, identities] = await Promise.all([
+ userIds.length ? userDAL.find({ $in: { id: userIds } }) : [],
+ identityIds.length ? identityDAL.find({ $in: { id: identityIds } }) : []
+ ]);
+ users.forEach((user) => actorNames.set(principalKey(UnusedAccessPrincipalType.User, user.id), user.username));
+ identities.forEach((identity) =>
+ actorNames.set(principalKey(UnusedAccessPrincipalType.Identity, identity.id), identity.name)
+ );
+
+ // How each principal gets the access, from the roles its permission was built from. Custom roles are shown by
+ // name, which is the one lookup the computation makes beyond what the permissions already loaded.
+ const rolesByKey = new Map<string, { role: string; customRoleSlug?: string | null }[]>();
+ const privilegedKeys = new Set<string>();
+ userPermissions.forEach((entry) => {
+ rolesByKey.set(principalKey(UnusedAccessPrincipalType.User, entry.id), entry.roles);
+ if (entry.hasAdditionalPrivileges) privilegedKeys.add(principalKey(UnusedAccessPrincipalType.User, entry.id));
+ });
+ identityPermissions.forEach((entry) => {
+ rolesByKey.set(principalKey(UnusedAccessPrincipalType.Identity, entry.id), entry.roles);
+ if (entry.hasAdditionalPrivileges) privilegedKeys.add(principalKey(UnusedAccessPrincipalType.Identity, entry.id));
+ });
+ groups.forEach((group) => rolesByKey.set(principalKey(UnusedAccessPrincipalType.Group, group.id), group.roles));
+ const customRoleSlugs = [
+ ...new Set([...rolesByKey.values()].flat().flatMap((role) => (role.customRoleSlug ? [role.customRoleSlug] : [])))
+ ];
+ const customRoles = customRoleSlugs.length ? await roleDAL.find({ projectId, $in: { slug: customRoleSlugs } }) : [];
+ const customRoleNameBySlug = new Map(customRoles.map((role) => [role.slug, role.name]));
+ const groupNamesByMemberKey = new Map<string, string[]>();
+ groups.forEach((group) =>
+ group.memberKeys.forEach((key) =>
+ groupNamesByMemberKey.set(key, [...(groupNamesByMemberKey.get(key) ?? []), group.name])
+ )
+ );
+ const roleLabel = (role: { role: string; customRoleSlug?: string | null }) =>
+ role.role === ProjectMembershipRole.Custom && role.customRoleSlug
+ ? `Role: ${customRoleNameBySlug.get(role.customRoleSlug) ?? role.customRoleSlug}`
+ : `Role: ${ROLE_LABELS[role.role] ?? role.role}`;
+ const accessViaOf = (key: string) => [
+ ...new Set([
+ ...(rolesByKey.get(key) ?? []).map(roleLabel),
+ ...(privilegedKeys.has(key) ? ["Additional privilege"] : []),
+ ...(groupNamesByMemberKey.get(key) ?? []).map((name) => `Group: ${name}`)
+ ])
+ ];
+ // A group's last read is its members' latest.
+ const lastReadOf = (stat: TStat) => {
+ const keys =
+ stat.principalType === UnusedAccessPrincipalType.Group
+ ? (groups.find((group) => group.id === stat.principalId)?.memberKeys ?? [])
+ : [principalKey(stat.principalType, stat.principalId)];
+ const latest = Math.max(0, ...keys.map((key) => lastReadAtByKey.get(key) ?? 0));
+ return latest ? new Date(latest) : null;
+ };
+
+ const rows = ranked.map((stat): TUnusedAccessPrincipal => {
+ const key = principalKey(stat.principalType, stat.principalId);
+ return {
+ principalType: stat.principalType,
+ principalId: stat.principalId,
+ name: actorNames.get(key) ?? stat.principalId,
+ memberCount:
+ stat.principalType === UnusedAccessPrincipalType.Group
+ ? (groups.find((group) => group.id === stat.principalId)?.memberKeys.length ?? 0)
+ : null,
+ entitledCount: stat.entitledCount,
+ unreadCount: stat.unreadCount,
+ environments: [...stat.environments].sort(),
+ lastReadAt: lastReadOf(stat),
+ accessVia: accessViaOf(key)
+ };
+ });
+ // The unread secrets themselves are kept for the principals with the most of them, so the sheet lists them
+ // without another scan; anyone further down is computed on their own when opened.
+ const details = Object.fromEntries(
+ ranked
+ .slice(0, UNUSED_ACCESS_DETAIL_MAX_PRINCIPALS)
+ .map((stat) => [principalKey(stat.principalType, stat.principalId), stat.unreadSecretIds])
+ );
+ return { rows, details };
};
// Requests on a cold cache, on any instance, wait for the one computing the project and read what it cached
// instead of each scanning the project. If the wait runs out, the request computes it itself.
- const $computeProjectExposureShared = async (projectId: string, orgId: string, cacheKey: string) => {
+ const $computeUnusedAccessShared = async (projectId: string, orgId: string, cacheKey: string) => {
let lock: Awaited<ReturnType<typeof keyStore.acquireLock>> | undefined;
try {
lock = await keyStore.acquireLock(
- [KeyStorePrefixes.SecretReadActivityExposureLock(projectId)],
- SECRET_EXPOSURE_COMPUTE_LOCK_TTL_MS,
- { retryCount: SECRET_EXPOSURE_COMPUTE_WAIT_SECONDS, retryDelay: 1000 }
+ [KeyStorePrefixes.SecretReadActivityUnusedAccessLock(projectId)],
+ UNUSED_ACCESS_COMPUTE_LOCK_TTL_MS,
+ { retryCount: UNUSED_ACCESS_COMPUTE_WAIT_SECONDS, retryDelay: 1000 }
);
} catch {
lock = undefined;
}
try {
const cached = lock ? await keyStore.getItem(cacheKey) : null;
- if (cached) return JSON.parse(cached) as Awaited<ReturnType<typeof $computeProjectExposure>>;
+ if (cached) return JSON.parse(cached) as Awaited<ReturnType<typeof $computeUnusedAccess>>;
- const result = await $computeProjectExposure(projectId, orgId);
+ const result = await $computeUnusedAccess(projectId, orgId);
// Written before the lock is released, so the next request in line finds it. A failed write only costs
// the next request a recomputation, so it never fails this one.
await keyStore
- .setItemWithExpiry(cacheKey, SECRET_EXPOSURE_CACHE_TTL_SECONDS, JSON.stringify(result))
+ .setItemWithExpiry(cacheKey, UNUSED_ACCESS_CACHE_TTL_SECONDS, JSON.stringify(result))
.catch((error) => {
- logger.warn(error, `secret-exposure: failed to cache the project computation [projectId=${projectId}]`);
+ logger.warn(error, `unused-access: failed to cache the project computation [projectId=${projectId}]`);
});
return result;
} finally {
@@ -536,13 +707,13 @@ export const secretReadActivityServiceFactory = ({
};
// The whole project is computed once a day and cached, so paging through it is cheap.
- const $getCachedProjectExposure = async (projectId: string, orgId: string) => {
- const cacheKey = KeyStorePrefixes.InsightsCache(projectId, "secret-exposure");
+ const $getCachedUnusedAccess = async (projectId: string, orgId: string) => {
+ const cacheKey = KeyStorePrefixes.InsightsCache(projectId, "unused-access");
const summary = await withCache({
keyStore,
key: cacheKey,
- ttlSeconds: SECRET_EXPOSURE_CACHE_TTL_SECONDS,
- fetcher: () => $computeProjectExposureShared(projectId, orgId, cacheKey)
+ ttlSeconds: UNUSED_ACCESS_CACHE_TTL_SECONDS,
+ fetcher: () => $computeUnusedAccessShared(projectId, orgId, cacheKey)
});
const [remainingTTL, { project, trackingStartedAt }] = await Promise.all([
getCacheTtl(keyStore, cacheKey),
@@ -567,7 +738,7 @@ export const secretReadActivityServiceFactory = ({
? secretV2BridgeDAL.find({ $in: { [`${TableName.SecretV2}.id` as "id"]: [...new Set(secretIds)] } })
: []
]);
- const visible = new Map<string, TSecretLocation & { secretKey: string }>();
+ const visible = new Map<string, TUnusedSecret>();
currentSecrets.forEach((secret) => {
const location = tree.locationOf(secret.folderId);
if (!location) return;
@@ -586,35 +757,78 @@ export const secretReadActivityServiceFactory = ({
return visible;
};
- const listSecretExposure = async (
- { projectId, offset, limit, orderBy, orderDirection }: TListSecretExposureDTO,
+ const listUnusedAccess = async (
+ { projectId, offset, limit, search }: TListUnusedAccessDTO,
actor: OrgServiceActor
) => {
- const { permission } = await checkInsightsReadPermission(permissionService, projectId, actor);
- const { mostExposed, bands, scoredCount, ...tracking } = await $getCachedProjectExposure(projectId, actor.orgId);
- const visibleSecrets = await $loadVisibleSecrets(
- projectId,
- permission,
- mostExposed.map((secret) => secret.secretId)
- );
- const visible = mostExposed.flatMap(({ secretId, ...row }): TExposedSecret[] => {
- const secret = visibleSecrets.get(secretId);
- return secret ? [{ ...row, ...secret }] : [];
- });
+ await checkInsightsReadPermission(permissionService, 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;
+ return {
+ principals: matching.slice(offset, offset + limit),
+ totalCount: matching.length,
+ projectName: tracking.projectName,
+ trackingStartedAt: tracking.trackingStartedAt,
+ preliminaryUntil: tracking.preliminaryUntil,
+ remainingTTL: tracking.remainingTTL
+ };
+ };
- // Unsorted, the list keeps its ranking. The sort is stable, so ties keep it too.
- const sorted = orderBy
- ? [...visible].sort((a, b) => {
- const [first, second] = orderDirection === OrderByDirection.DESC ? [b, a] : [a, b];
- return first[orderBy].localeCompare(second[orderBy]);
- })
- : visible;
+ // The unread secrets of one principal who was not among those cached in full: one scan, kept for the same day.
+ const $computeUnusedSecretIdsFor = async (
+ projectId: string,
+ orgId: string,
+ principalType: UnusedAccessPrincipalType,
+ principalId: string
+ ) => {
+ const secretIds: string[] = [];
+ await $walkSecrets(projectId, orgId, (activity, summary) => {
+ const isUnread =
+ principalType === UnusedAccessPrincipalType.Group
+ ? summary.unreadGroups.some((group) => group.id === principalId)
+ : summary.unread.some(
+ (reader) => reader.id === principalId && toPrincipalType(reader.actorType) === principalType
+ );
+ if (isUnread && secretIds.length < UNUSED_ACCESS_MAX_SECRETS_PER_PRINCIPAL) secretIds.push(activity.secret.id);
+ });
+ return secretIds;
+ };
+ const getUnusedAccessPrincipal = async (
+ { projectId, principalType, principalId }: TGetUnusedAccessPrincipalDTO,
+ actor: OrgServiceActor
+ ) => {
+ const { permission } = await checkInsightsReadPermission(permissionService, projectId, actor);
+ const { rows, details, ...tracking } = await $getCachedUnusedAccess(projectId, actor.orgId);
+ const key = principalKey(principalType, principalId);
+ const principal = rows.find((row) => principalKey(row.principalType, row.principalId) === key);
+ if (!principal) {
+ throw new NotFoundError({
+ message: `No unused access found for ${principalType} '${principalId}' in this project`
+ });
+ }
+ const secretIds =
+ details[key] ??
+ (await withCache({
+ keyStore,
+ key: KeyStorePrefixes.InsightsCache(projectId, `unused-access:${key}`),
+ ttlSeconds: UNUSED_ACCESS_CACHE_TTL_SECONDS,
+ fetcher: () => $computeUnusedSecretIdsFor(projectId, actor.orgId, principalType, principalId)
+ }));
+ const visible = await $loadVisibleSecrets(projectId, permission, secretIds);
+ const secrets = secretIds
+ .flatMap((secretId) => visible.get(secretId) ?? [])
+ .sort(
+ (a, b) =>
+ a.environment.localeCompare(b.environment) ||
+ a.secretPath.localeCompare(b.secretPath) ||
+ a.secretKey.localeCompare(b.secretKey)
+ );
return {
- secrets: sorted.slice(offset, offset + limit),
- totalCount: visible.length,
- unlistedCount: scoredCount - mostExposed.length,
- bands,
+ principal,
+ secrets,
+ unlistedCount: Math.max(0, principal.unreadCount - secretIds.length),
projectName: tracking.projectName,
trackingStartedAt: tracking.trackingStartedAt,
preliminaryUntil: tracking.preliminaryUntil,
@@ -626,6 +840,7 @@ export const secretReadActivityServiceFactory = ({
recordRead: secretReadActivityQueue.recordRead,
recordBulkRead: secretReadActivityQueue.recordBulkRead,
getSecretReadActivity,
- listSecretExposure
+ listUnusedAccess,
+ getUnusedAccessPrincipal
};
};
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 df2ec3065f..aa30f7db48 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,4 @@
import { TSecretReadActivity } from "@app/db/schemas";
-import { OrderByDirection } from "@app/lib/types";
import { ActorType } from "@app/services/auth/auth-type";
// A reader's last read of an object. The table also keys it by month (its partition key), which the DAL adds
@@ -127,13 +126,6 @@ export type TSecretExposure = {
drivers: TSecretExposureDriver[];
};
-export type TExposedSecret = TSecretExposureCounts & {
- secretKey: string;
- environment: string;
- secretPath: string;
- exposure: TSecretExposure;
-};
-
// A reader who can read the value today, and whether they count as unused access: no read, with the secret and
// their access both older than the judged period. When they do not, the other fields say why.
export type TEntitledReader = {
@@ -145,17 +137,41 @@ export type TEntitledReader = {
accessChangedAt: Date | null;
};
-// Each value is the row field it sorts by.
-export enum SecretExposureOrderBy {
- SecretKey = "secretKey",
- Environment = "environment",
- SecretPath = "secretPath"
+export enum UnusedAccessPrincipalType {
+ User = "user",
+ Identity = "identity",
+ Group = "group"
}
-export type TListSecretExposureDTO = {
+// A user, group or machine identity that can read secrets it has not read in the window.
+export type TUnusedAccessPrincipal = {
+ principalType: UnusedAccessPrincipalType;
+ principalId: 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[];
+};
+
+export type TUnusedSecret = TSecretLocation & { secretKey: string };
+
+export type TListUnusedAccessDTO = {
projectId: string;
offset: number;
limit: number;
- orderBy?: SecretExposureOrderBy;
- orderDirection: OrderByDirection;
+ search?: string;
+};
+
+export type TGetUnusedAccessPrincipalDTO = {
+ projectId: string;
+ principalType: UnusedAccessPrincipalType;
+ principalId: string;
};
diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.ts
index b88575fa7a..45f3c2367d 100644
--- a/backend/src/keystore/keystore.ts
+++ b/backend/src/keystore/keystore.ts
@@ -236,7 +236,8 @@ export const KeyStorePrefixes = {
`secret-read-activity:${day}:${actorId}:${scope}` as const,
SecretReadActivityStream: "secret-read-activity-stream" as const,
SecretReadActivityConsumerLock: "secret-read-activity:consumer-lock" as const,
- SecretReadActivityExposureLock: (projectId: string) => `secret-read-activity:exposure-lock:${projectId}` as const,
+ SecretReadActivityUnusedAccessLock: (projectId: string) =>
+ `secret-read-activity:unused-access-lock:${projectId}` as const,
AuditLogIngestConsumerLock: "audit-log-ingest:consumer-lock" as const,
// period is a YYYY-MM stamp so the monthly notice can only go out once per org per month
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index 5445306749..84cf37078e 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -947,26 +947,40 @@ export const INSIGHTS = {
totalProjects: "The total number of secret management projects in the organization.",
projectsWithIssues: "The number of secret management projects in the organization with at least one issue."
},
- GET_SECRET_EXPOSURE: {
- projectId: "The ID of the project to list secret exposure for.",
- offset: "The number of secrets to skip before returning results.",
- limit: "The maximum number of secrets to return per page.",
- orderBy: "The field to sort by. Without it, the most exposed secrets come first.",
- orderDirection: "The direction to sort in.",
+ 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 tracked period, 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.",
+ unreadCount:
+ "How many of those it has not read, or an import or reference of, in the tracked period. A group has not read a secret when none of its members have. Secrets and access newer than the period are not counted.",
+ environments: "The slugs of the environments holding the unread secrets.",
+ lastReadAt:
+ "When the principal last read any secret in the project within the tracked period, 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.",
+ trackingStartedAt:
+ "When reads started being tracked for this project: the later of when read tracking was enabled on the instance and when the project was created.",
+ preliminaryUntil:
+ "When the results first cover the full 30 days. Until then they are preliminary: they cover only the reads since tracking started, and the access that existed when it started."
+ },
+ GET_UNUSED_ACCESS_PRINCIPAL: {
+ 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.",
secrets:
- "The secrets with the highest exposure score: those of the top 500 in the project that the caller can see. Secrets scoring 0, which nobody can read, are not listed.",
+ "The secrets the principal can read but has not read in the tracked period, 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.",
- totalCount: "The number of secrets the caller can page through.",
- unlistedCount:
- "The number of further scored secrets that are not listed, counted across the whole project before the caller's permissions are applied. Zero unless the project has more than 500.",
- bands:
- "How many of the project's secrets fall in each band, counted across the whole project before the caller's permissions are applied.",
- trackingStartedAt:
- "When reads started being tracked for this project: the later of when read tracking was enabled on the instance and when the project was created.",
- preliminaryUntil:
- "When the scores first cover the full 30 days. Until then they are preliminary: unused access covers only the reads since tracking started and the access that existed then, and weighs less in the score the shorter that period is."
+ unlistedCount: "How many more of the principal's unread secrets are not listed. Zero unless it has more than 200."
},
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.ts
index dc6ee05b34..470356b87e 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -3538,6 +3538,7 @@ export const registerRoutes = async (
identityDAL,
userGroupMembershipDAL,
identityGroupMembershipDAL,
+ roleDAL,
kmsService,
keyStore
});
diff --git a/frontend/src/pages/secret-manager/InsightsPage/components/SecretExposureCard.tsx b/frontend/src/pages/secret-manager/InsightsPage/components/SecretExposureCard.tsx
deleted file mode 100644
index 216d56b721..0000000000
--- a/frontend/src/pages/secret-manager/InsightsPage/components/SecretExposureCard.tsx
+++ /dev/null
@@ -1,384 +0,0 @@
-import { useState } from "react";
-import { useParams } from "@tanstack/react-router";
-import axios from "axios";
-import { format } from "date-fns";
-import { ChevronDownIcon, FolderIcon, InfoIcon, KeyIcon } from "lucide-react";
-
-import { GoToSecretButton } from "@app/components/secrets/GoToSecretButton";
-import {
- EXPOSURE_BAND_LABEL,
- EXPOSURE_BAND_TEXT,
- EXPOSURE_BANDS,
- SecretExposureBadge
-} from "@app/components/secrets/SecretExposureScore";
-import {
- Badge,
- Card,
- CardContent,
- CardDescription,
- CardHeader,
- CardTitle,
- Empty,
- EmptyDescription,
- EmptyHeader,
- EmptyTitle,
- Pagination,
- Separator,
- Sheet,
- SheetContent,
- SheetDescription,
- SheetHeader,
- SheetTitle,
- Skeleton,
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
- type TableSortDirection,
- Tooltip,
- TooltipContent,
- TooltipTrigger
-} from "@app/components/v3";
-import { cn } from "@app/components/v3/utils";
-import { useProject, useSubscription } from "@app/context";
-import { usePagination, useResetPageHelper } from "@app/hooks";
-import { OrderByDirection } from "@app/hooks/api/generic/types";
-import {
- SecretExposureOrderBy,
- TExposedSecret,
- useGetSecretExposure
-} from "@app/hooks/api/secretInsights";
-import { SecretAccessInsights } from "@app/pages/secret-manager/OverviewPage/components/SecretTableRow/SecretAccessInsights";
-
-const formatRemainingTtl = (seconds: number) => {
- if (seconds < 60) {
- const remainingSeconds = Math.max(1, seconds);
- return `${remainingSeconds} ${remainingSeconds === 1 ? "second" : "seconds"}`;
- }
- if (seconds < 60 * 60) {
- const minutes = Math.ceil(seconds / 60);
- return `${minutes} ${minutes === 1 ? "minute" : "minutes"}`;
- }
- const hours = Math.ceil(seconds / (60 * 60));
- return `${hours} ${hours === 1 ? "hour" : "hours"}`;
-};
-
-// The period the counts are judged on: the full window once tracking is that old, else since it began.
-const describeReadPeriod = (trackingStartedAt: string, isPreliminary: boolean) =>
- isPreliminary ? `since ${format(new Date(trackingStartedAt), "PP")}` : "in the last 30 days";
-
-export const SecretExposureCard = () => {
- const { currentProject, projectId } = useProject();
- const { orgId } = useParams({ strict: false });
- const { subscription } = useSubscription();
- // An empty orderBy keeps the default ranking: the most exposed secrets first.
- const {
- page,
- setPage,
- perPage,
- setPerPage,
- offset,
- limit,
- orderBy,
- setOrderBy,
- orderDirection,
- setOrderDirection
- } = usePagination<SecretExposureOrderBy | "">("", { initPerPage: 10 });
- const [selectedSecret, setSelectedSecret] = useState<TExposedSecret | null>(null);
-
- const { data, isPending, error } = useGetSecretExposure(
- { projectId, offset, limit, orderBy: orderBy || undefined, orderDirection },
- { enabled: Boolean(subscription?.secretAccessInsights) }
- );
- const totalCount = data?.totalCount ?? 0;
- useResetPageHelper({ totalCount, offset, setPage });
-
- const updatesIn =
- data?.remainingTtl != null && data.remainingTtl >= 0
- ? formatRemainingTtl(data.remainingTtl)
- : null;
- const environmentNames = new Map(currentProject.environments.map((env) => [env.slug, env.name]));
-
- const getSortDirection = (column: SecretExposureOrderBy): TableSortDirection => {
- if (orderBy !== column) return "none";
- return orderDirection === OrderByDirection.DESC ? "descending" : "ascending";
- };
-
- const handleSort = (column: SecretExposureOrderBy, direction: TableSortDirection) => {
- setPage(1);
- setOrderBy(direction === "none" ? "" : column);
- setOrderDirection(direction === "descending" ? OrderByDirection.DESC : OrderByDirection.ASC);
- };
-
- const sortableColumns = [
- { column: SecretExposureOrderBy.SecretKey, label: "Secret Key" },
- { column: SecretExposureOrderBy.Environment, label: "Environment" },
- { column: SecretExposureOrderBy.SecretPath, label: "Path" }
- ];
-
- const renderBody = () => {
- if (isPending) return <Skeleton className="h-[200px] w-full" />;
-
- if (!data) {
- return (
- <Empty className="border">
- <EmptyHeader>
- <EmptyTitle>Could not load secret exposure</EmptyTitle>
- <EmptyDescription>
- {(axios.isAxiosError(error) &&
- (error.response?.data as { message?: string })?.message) ||
- "Try again in a moment."}
- </EmptyDescription>
- </EmptyHeader>
- </Empty>
- );
- }
-
- const isPreliminary = new Date(data.preliminaryUntil) > new Date();
- const readPeriod = describeReadPeriod(data.trackingStartedAt, isPreliminary);
- // Descending, so the band that needs attention first reads first.
- const bandSummary = [...EXPOSURE_BANDS].reverse();
-
- return (
- <>
- <div className="mb-4 grid grid-cols-2 gap-3 sm:grid-cols-4">
- {bandSummary.map(({ band, range }) => (
- <div key={band} className="rounded-md border border-border bg-container px-3 py-2">
- <div className={cn("text-2xl leading-none font-semibold", EXPOSURE_BAND_TEXT[band])}>
- {data.bands[band].toLocaleString()}
- </div>
- <div className="mt-1 text-xs text-muted">
- {EXPOSURE_BAND_LABEL[band]} · {range}
- </div>
- </div>
- ))}
- </div>
- {isPreliminary && (
- <p className="mb-4 flex items-center gap-1.5 text-xs text-muted">
- <InfoIcon className="size-3.5 shrink-0" />
- Preliminary: reads are tracked since {format(new Date(data.trackingStartedAt), "PP")},
- so unused access covers that period and weighs less in the score until{" "}
- {format(new Date(data.preliminaryUntil), "PP")}.
- </p>
- )}
- {totalCount === 0 ? (
- <Empty className="border">
- <EmptyHeader>
- <EmptyTitle>No exposed secrets</EmptyTitle>
- <EmptyDescription>
- A secret scores once someone other than a project admin can read its value.
- </EmptyDescription>
- </EmptyHeader>
- </Empty>
- ) : (
- <>
- <Table>
- <TableHeader>
- <TableRow>
- {sortableColumns.map(({ column, label }) => (
- <TableHead
- key={column}
- sortDirection={getSortDirection(column)}
- onSortChange={(direction) => handleSort(column, direction)}
- >
- {label}
- <ChevronDownIcon
- className={cn(
- "transition-transform",
- getSortDirection(column) === "descending" && "rotate-180",
- getSortDirection(column) === "none" && "opacity-30"
- )}
- />
- </TableHead>
- ))}
- <TableHead className="whitespace-nowrap">Exposure</TableHead>
- <TableHead className="whitespace-nowrap">Readers</TableHead>
- <TableHead className="whitespace-nowrap">No Reads</TableHead>
- <TableHead className="whitespace-nowrap">Ghost Readers</TableHead>
- <TableHead variant="action" />
- </TableRow>
- </TableHeader>
- <TableBody>
- {data.secrets.map((row) => (
- <TableRow
- key={`${row.environment}-${row.secretPath}-${row.secretKey}`}
- className="group/row cursor-pointer"
- onClick={() => setSelectedSecret(row)}
- >
- <TableCell isTruncatable className="max-w-60">
- <div className="flex items-center gap-2">
- <KeyIcon className="size-4 shrink-0 text-muted" />
- <span className="truncate font-mono">{row.secretKey}</span>
- </div>
- </TableCell>
- <TableCell>
- <Badge variant="info" isTruncatable className="max-w-full">
- <span>{environmentNames.get(row.environment) ?? row.environment}</span>
- </Badge>
- </TableCell>
- <TableCell isTruncatable className="max-w-48">
- <div className="flex items-center gap-2">
- <FolderIcon className="size-3.5 shrink-0 text-folder" />
- <span className="truncate">{row.secretPath}</span>
- </div>
- </TableCell>
- <TableCell className="whitespace-nowrap">
- <Tooltip>
- <TooltipTrigger asChild>
- <span>
- <SecretExposureBadge exposure={row.exposure} />
- </span>
- </TooltipTrigger>
- <TooltipContent className="max-w-72">
- <ul className="flex flex-col gap-1">
- {row.exposure.drivers.map((driver) => (
- <li key={driver.kind} className="flex gap-2">
- <span className="w-7 shrink-0 font-mono">+{driver.points}</span>
- <span>{driver.label}</span>
- </li>
- ))}
- </ul>
- </TooltipContent>
- </Tooltip>
- </TableCell>
- <TableCell className="whitespace-nowrap">
- <Tooltip>
- <TooltipTrigger asChild>
- <span>{row.entitledCount}</span>
- </TooltipTrigger>
- <TooltipContent>
- {row.entitledCount} users and machine identities, project admins aside,
- can read this secret&apos;s value
- </TooltipContent>
- </Tooltip>
- </TableCell>
- <TableCell className="whitespace-nowrap">
- <Tooltip>
- <TooltipTrigger asChild>
- <span>
- {row.unreadCount} of {row.entitledCount}
- </span>
- </TooltipTrigger>
- <TooltipContent>
- {row.unreadCount} of the {row.entitledCount} who can read this secret,
- have not read it {readPeriod}
- </TooltipContent>
- </Tooltip>
- </TableCell>
- <TableCell className="whitespace-nowrap">
- {row.ghostReaderCount > 0 ? (
- <Tooltip>
- <TooltipTrigger asChild>
- <span>{row.ghostReaderCount}</span>
- </TooltipTrigger>
- <TooltipContent>
- {row.ghostReaderCount} read this secret {readPeriod} but can no longer
- access it. They still know the value.
- </TooltipContent>
- </Tooltip>
- ) : (
- <span className="text-muted">0</span>
- )}
- </TableCell>
- <TableCell variant="action" onClick={(event) => event.stopPropagation()}>
- <GoToSecretButton
- orgId={orgId as string}
- projectId={projectId}
- secretKey={row.secretKey}
- secretPath={row.secretPath}
- environmentSlug={row.environment}
- isProjectMember
- />
- </TableCell>
- </TableRow>
- ))}
- </TableBody>
- </Table>
- <Pagination
- count={totalCount}
- page={page}
- perPage={perPage}
- onChangePage={setPage}
- onChangePerPage={setPerPage}
- />
- {data.unlistedCount > 0 && (
- <p className="mt-2 text-xs text-muted">
- Showing the {totalCount.toLocaleString()} most exposed secrets.{" "}
- {data.unlistedCount.toLocaleString()} more are not listed.
- </p>
- )}
- </>
- )}
- </>
- );
- };
-
- return (
- <>
- <Card>
- <CardHeader>
- <CardTitle>
- Secret Exposure
- {updatesIn && (
- <Badge variant="neutral" className="ml-2 font-normal">
- Updates in {updatesIn}
- </Badge>
- )}
- </CardTitle>
- <CardDescription>
- Which secrets are most exposed, from how many can read the value, who can no longer read
- it but still knows it, and who can read it but never does. Select a secret to see why it
- scores what it does and who is behind each count.
- </CardDescription>
- </CardHeader>
- <CardContent>{renderBody()}</CardContent>
- </Card>
- <Sheet
- open={selectedSecret !== null}
- onOpenChange={(isOpen) => {
- if (!isOpen) setSelectedSecret(null);
- }}
- >
- <SheetContent
- onOpenAutoFocus={(event) => event.preventDefault()}
- size="wide"
- className="gap-y-0"
- side="right"
- >
- <SheetHeader>
- <SheetTitle>Secret Exposure</SheetTitle>
- <SheetDescription>
- Why this secret scores what it does, who can read it, and who still knows its value
- </SheetDescription>
- </SheetHeader>
- {selectedSecret && (
- <>
- <div className="bg-container p-4 text-foreground">
- <p className="truncate font-mono">{selectedSecret.secretKey}</p>
- <div className="mt-1 flex items-center gap-2">
- <Badge variant="neutral">
- {environmentNames.get(selectedSecret.environment) ?? selectedSecret.environment}
- </Badge>
- <span className="flex items-center gap-1 text-xs text-muted">
- <FolderIcon className="size-3.5 text-folder" />
- {selectedSecret.secretPath}
- </span>
- </div>
- </div>
- <Separator />
- <SecretAccessInsights
- key={`${selectedSecret.environment}-${selectedSecret.secretPath}-${selectedSecret.secretKey}`}
- secretKey={selectedSecret.secretKey}
- environment={selectedSecret.environment}
- secretPath={selectedSecret.secretPath}
- defaultView="graph"
- />
- </>
- )}
- </SheetContent>
- </Sheet>
- </>
- );
-};