Skip to content

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

feat(insights): list folder access as an access path and date access per secret

Dimitris Staratzisa49043b86dd1
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.md
index 150a502424..7e56fff04a 100644
--- a/backend/CLAUDE.md
+++ b/backend/CLAUDE.md
@@ -1146,16 +1146,20 @@ owns the two read endpoints and hands `recordRead` / `recordBulkRead` through to
cached computation, so the UI words the period "since <date>" while it is under 30 days old. The card leaves out project admins (users
and identities with the Admin role, directly or through a group, from `findAdminActorIds`): they can read
everything by design. Their reads are still recorded, so the access sheet's Last Read stays true for them. A
- pair is listed once the secret (`trackedSince`) and the actor's access (`findAccessChangedAt`: the latest
- membership creation, role or privilege creation, edit or expiry) both predate `judgedFrom`. Which secrets a
- change opened up is not recorded, so any access change restarts the window, including an edit to the rules of
- a custom role the reader holds. The per-secret sheet shows the plain fact
+ pair is listed once the secret (`trackedSince`) and the actor's access to that secret both predate `judgedFrom`.
+ Access is dated per secret (`createAccessDating`): each actor's sources (every role assignment and project-wide
+ privilege, from `getProjectPermissions`' `accessSources`; each group they are in; each folder grant) carry the date
+ `findAccessSourceDates` gives them, and a secret's access dates from the oldest source that grants it on its own,
+ so a change only restarts the window for the secrets it opened. An edit to a custom role's rules dates that role
+ for every secret it gives, since which secrets an edit opened is not recorded. Expired access is not a source,
+ except an expired folder grant, which can give back access it held back in its folder. Only an actor with a
+ source newer than `judgedFrom` is checked per secret, and each source once per secret across actors. The per-secret sheet shows the plain fact
instead: a read, "No reads", or "No reads yet" with the reason.
- **The access sheet.** The graph lives only in the secret's access sheet, served by
`GET /insights/:projectId/secrets/read-activity/:secretName` (the fixed segment comes first so a secret named
`reports` or `summary` cannot hit those routes). It returns `actors`: everyone who can read the value, admins
- included, each with `lastReadAt`, `isProjectAdmin`, `accessChangedAt`, and a `readStatus` (`read`, `unused`,
- `not-judged`) with a `notJudgedReason` (`project-admin`, `access-changed`, `secret-too-new`) from
+ included, each with `lastReadAt`, `isProjectAdmin`, `accessSince`, and a `readStatus` (`read`, `unused`,
+ `not-judged`) with a `notJudgedReason` (`project-admin`, `access-too-new`, `secret-too-new`) from
`getReadStatus`. The API returns codes and dates only; the UI writes the wording. Readers who lost access
("ghost readers") are not computed or returned.
- **The Insights card is per actor** (a user or machine identity; a group is never a row, only an access path).
@@ -1165,7 +1169,10 @@ owns the two read endpoints and hands `recordRead` / `recordBulkRead` through to
secrets it can read, how many it has not read and the environments involved; `$computeUnusedAccess`
ranks the tallies into rows (`accessibleSecretCount`, `unusedSecretCount`). Each row carries `accessPaths` as data: `roles` it holds directly (`id`/`slug`/`name`,
where a custom role has the slug `custom` and its own id), `groups` it belongs to with the roles each one gives,
- and `additionalPrivileges` as `id`/`name`; the UI decides how to label them. Custom role ids and names come from
+ `additionalPrivileges` as `id`/`name` (project-wide only), and `folderAccess`: the actor's own active folder grants
+ (`id`/`folderId`/`environment`/`secretPath`/`role`). A folder grant is stored as an additional privilege with a
+ `folderId`, which the member listings filter out, so `getProjectPermissions` returns them as
+ `folderAccessByActorId` from the grants it already loads. The UI decides how to label all of them. Custom role ids and names come from
`getProjectPermissions`, so the scan makes no role lookup of its own. Group members are checked with the group's
permission (`getProjectPermissions` lists only direct members) and count once however many ways they qualify. It
is cached per project for a day (`insights-cache:<projectId>:unused-access`, under a per-project lock on a cold
diff --git a/backend/src/ee/services/insights/insights-schemas.ts b/backend/src/ee/services/insights/insights-schemas.ts
index b6d970bc7b..1d48da0460 100644
--- a/backend/src/ee/services/insights/insights-schemas.ts
+++ b/backend/src/ee/services/insights/insights-schemas.ts
@@ -1,6 +1,6 @@
import { z } from "zod";
-import { IdentityAuthMethod } from "@app/db/schemas";
+import { IdentityAuthMethod, SecretFolderRole } from "@app/db/schemas";
import {
SecretReadNotJudgedReason,
SecretReadStatus
@@ -101,7 +101,17 @@ const UnusedAccessActorRowSchema = z.object({
name: z.string().describe(INSIGHTS.GET_UNUSED_ACCESS.additionalPrivilegeName)
})
.array()
- .describe(INSIGHTS.GET_UNUSED_ACCESS.additionalPrivileges)
+ .describe(INSIGHTS.GET_UNUSED_ACCESS.additionalPrivileges),
+ folderAccess: z
+ .object({
+ id: z.string().describe(INSIGHTS.GET_UNUSED_ACCESS.folderAccessId),
+ folderId: z.string().describe(INSIGHTS.GET_UNUSED_ACCESS.folderId),
+ environment: z.string().describe(INSIGHTS.GET_UNUSED_ACCESS.folderEnvironment),
+ secretPath: z.string().describe(INSIGHTS.GET_UNUSED_ACCESS.folderSecretPath),
+ role: z.nativeEnum(SecretFolderRole).describe(INSIGHTS.GET_UNUSED_ACCESS.folderRole)
+ })
+ .array()
+ .describe(INSIGHTS.GET_UNUSED_ACCESS.folderAccess)
})
.describe(INSIGHTS.GET_UNUSED_ACCESS.accessPaths)
});
@@ -135,7 +145,7 @@ export const SecretReadActivitySchema = z.object({
name: z.string().describe(INSIGHTS.GET_SECRET_READ_ACTIVITY.name),
isProjectAdmin: z.boolean().describe(INSIGHTS.GET_SECRET_READ_ACTIVITY.isProjectAdmin),
lastReadAt: z.date().nullable().describe(INSIGHTS.GET_SECRET_READ_ACTIVITY.lastReadAt),
- accessChangedAt: z.date().nullable().describe(INSIGHTS.GET_SECRET_READ_ACTIVITY.accessChangedAt),
+ accessSince: z.date().describe(INSIGHTS.GET_SECRET_READ_ACTIVITY.accessSince),
readStatus: z.nativeEnum(SecretReadStatus).describe(INSIGHTS.GET_SECRET_READ_ACTIVITY.readStatus),
notJudgedReason: z
.nativeEnum(SecretReadNotJudgedReason)
diff --git a/backend/src/ee/services/permission/permission-service-types.ts b/backend/src/ee/services/permission/permission-service-types.ts
index 6e8f26c351..6fc98ac9d7 100644
--- a/backend/src/ee/services/permission/permission-service-types.ts
+++ b/backend/src/ee/services/permission/permission-service-types.ts
@@ -163,12 +163,17 @@ export type TPermissionServiceFactory = {
name: string;
membershipId: string;
roles: {
+ // The role assignment's id.
+ id: string;
role: string;
customRoleSlug?: string | null;
customRoleId?: string | null;
customRoleName?: string | null;
}[];
additionalPrivileges: { id: string; name: string }[];
+ // Each role ("role:<assignment id>") and project-wide privilege ("privilege:<id>") as a permission of its own,
+ // without folder grants.
+ accessSources: () => { key: string; permission: MongoAbility<ProjectPermissionSet, MongoQuery> }[];
}[];
identityPermissions: {
permission: MongoAbility<ProjectPermissionSet, MongoQuery>;
@@ -176,12 +181,17 @@ export type TPermissionServiceFactory = {
name: string;
membershipId: string;
roles: {
+ // The role assignment's id.
+ id: string;
role: string;
customRoleSlug?: string | null;
customRoleId?: string | null;
customRoleName?: string | null;
}[];
additionalPrivileges: { id: string; name: string }[];
+ // Each role ("role:<assignment id>") and project-wide privilege ("privilege:<id>") as a permission of its own,
+ // without folder grants.
+ accessSources: () => { key: string; permission: MongoAbility<ProjectPermissionSet, MongoQuery> }[];
}[];
groupPermissions: {
permission: MongoAbility<ProjectPermissionSet, MongoQuery>;
@@ -197,6 +207,9 @@ export type TPermissionServiceFactory = {
customRoleName?: string | null;
}[];
}[];
+ // Each user's and identity's active folder grants, keyed by actor id, whether they are a direct member or
+ // reach the project through a group. Admins are listed too, though their grants are never applied.
+ folderAccessByActorId: Map<string, TProjectFolderScopedPrivilege[]>;
}>;
getOrgPermissionByRoles: (
roles: string[],
diff --git a/backend/src/ee/services/permission/permission-service.ts b/backend/src/ee/services/permission/permission-service.ts
index faf8f1823f..2d5b2c1798 100644
--- a/backend/src/ee/services/permission/permission-service.ts
+++ b/backend/src/ee/services/permission/permission-service.ts
@@ -957,6 +957,39 @@ export const permissionServiceFactory = ({
? undefined
: folderScopedPrivilegesByActorId.get(actorId)?.filter(isActiveRole);
+ // Each of a member's roles and project-wide privileges as a permission of its own, for a caller that needs to
+ // know which of them grants something. Built on first use, and members whose source has the same rules share one.
+ const sourceAbilities = new Map<string, MongoAbility<ProjectPermissionSet>>();
+ const accessSourcesOf = (
+ roles: { id: string; role: string; permissions?: unknown }[],
+ privileges: { id: string; permissions?: unknown }[],
+ identityContext: Record<string, unknown>
+ ) => {
+ let sources: { key: string; permission: MongoAbility<ProjectPermissionSet> }[] | undefined;
+ return () => {
+ sources ??= [
+ ...roles.map(({ id, role, permissions }) => ({
+ key: `role:${id}`,
+ rules: buildProjectPermissionRules([{ role, permissions }])
+ })),
+ ...privileges.map(({ id, permissions }) => ({
+ key: `privilege:${id}`,
+ rules: buildProjectPermissionRules([{ role: ProjectMembershipRole.Custom, permissions }])
+ }))
+ ].map(({ key, rules }) => {
+ const interpolated = interpolatePermissionRules(rules, identityContext);
+ const rulesKey = JSON.stringify(interpolated);
+ let permission = sourceAbilities.get(rulesKey);
+ if (!permission) {
+ permission = createMongoAbility<ProjectPermissionSet>(interpolated, { conditionsMatcher });
+ sourceAbilities.set(rulesKey, permission);
+ }
+ return { key, permission };
+ });
+ return sources;
+ };
+ };
+
// fetch user permissions
const rawUserProjectPermissions = await permissionDAL.getProjectUserPermissions(projectId, orgId);
const userPermissions = rawUserProjectPermissions.map((userProjectPermission) => {
@@ -981,13 +1014,14 @@ export const permissionServiceFactory = ({
),
"identity.metadata"
);
- const interpolatedRules = interpolatePermissionRules(rules, {
+ const identityContext = {
identity: {
id: userProjectPermission.userId,
username: userProjectPermission.username,
metadata: metadataKeyValuePair
}
- });
+ };
+ const interpolatedRules = interpolatePermissionRules(rules, identityContext);
const permission = createMongoAbility<ProjectPermissionSet>(interpolatedRules, {
conditionsMatcher
});
@@ -997,13 +1031,21 @@ export const permissionServiceFactory = ({
id: userProjectPermission.userId,
membershipId: userProjectPermission.id,
name: userProjectPermission.username,
- roles: (userProjectPermission.roles ?? []).map(({ role, customRoleSlug, customRoleId, customRoleName }) => ({
- role,
- customRoleSlug,
- customRoleId,
- customRoleName
- })),
- additionalPrivileges: (userProjectPermission.additionalPrivileges ?? []).map(({ id, name }) => ({ id, name }))
+ roles: (userProjectPermission.roles ?? []).map(
+ ({ id, role, customRoleSlug, customRoleId, customRoleName }) => ({
+ id,
+ role,
+ customRoleSlug,
+ customRoleId,
+ customRoleName
+ })
+ ),
+ additionalPrivileges: (userProjectPermission.additionalPrivileges ?? []).map(({ id, name }) => ({ id, name })),
+ accessSources: accessSourcesOf(
+ userProjectPermission.roles ?? [],
+ userProjectPermission.additionalPrivileges ?? [],
+ identityContext
+ )
};
});
@@ -1031,13 +1073,14 @@ export const permissionServiceFactory = ({
),
"identity.metadata"
);
- const interpolatedRules = interpolatePermissionRules(rules, {
+ const identityContext = {
identity: {
id: identityProjectPermission.identityId,
username: identityProjectPermission.username,
metadata: metadataKeyValuePair
}
- });
+ };
+ const interpolatedRules = interpolatePermissionRules(rules, identityContext);
const permission = createMongoAbility<ProjectPermissionSet>(interpolatedRules, {
conditionsMatcher
});
@@ -1048,7 +1091,8 @@ export const permissionServiceFactory = ({
membershipId: identityProjectPermission.id,
name: identityProjectPermission.username,
roles: (identityProjectPermission.roles ?? []).map(
- ({ role, customRoleSlug, customRoleId, customRoleName }) => ({
+ ({ id, role, customRoleSlug, customRoleId, customRoleName }) => ({
+ id,
role,
customRoleSlug,
customRoleId,
@@ -1058,7 +1102,12 @@ export const permissionServiceFactory = ({
additionalPrivileges: (identityProjectPermission.additionalPrivileges ?? []).map(({ id, name }) => ({
id,
name
- }))
+ })),
+ accessSources: accessSourcesOf(
+ identityProjectPermission.roles ?? [],
+ identityProjectPermission.additionalPrivileges ?? [],
+ identityContext
+ )
};
});
@@ -1104,10 +1153,24 @@ export const permissionServiceFactory = ({
};
});
+ const folderAccessByActorId = new Map(
+ [...folderScopedPrivilegesByActorId].map(([actorId, privileges]) => [
+ actorId,
+ privileges.filter(isActiveRole).map(({ id, folderId, role, environmentSlug, secretPath }) => ({
+ id,
+ folderId,
+ role,
+ environmentSlug,
+ secretPath
+ }))
+ ])
+ );
+
return {
userPermissions,
identityPermissions,
- groupPermissions
+ groupPermissions,
+ folderAccessByActorId
};
};
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 2162290c22..a608749fbe 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
@@ -135,87 +135,101 @@ export const secretReadActivityDALFactory = (db: TDbClient) => {
}
};
- type TAccessChange = {
- actorUserId?: string | null;
- actorIdentityId?: string | null;
- actorGroupId?: string | null;
- groupMemberId?: string | null;
- membershipCreatedAt?: Date | null;
+ type TRoleSourceRow = {
+ membershipRoleId: string;
+ actorGroupId: string | null;
+ membershipCreatedAt: Date;
createdAt: Date;
updatedAt: Date;
- temporaryAccessEndTime?: Date | null;
- customRoleUpdatedAt?: Date | null;
+ isTemporary: boolean;
+ temporaryAccessEndTime: Date | null;
+ customRoleUpdatedAt: Date | null;
};
- // The last time each user or identity joined the project or a group that is in it, or had a role, privilege or
- // folder grant created, changed or expired, or had the rules of a custom role they hold edited. Which secrets a
- // change opened up is not recorded, so any of them restarts the window; an expired restrictive folder grant can
- // restore access. Membership updatedAt is left out because logins bump it.
- const findAccessChangedAt = async (projectId: string, tx?: Knex) => {
+ type TPrivilegeSourceRow = {
+ id: string;
+ actorUserId: string | null;
+ actorIdentityId: string | null;
+ folderId: string | null;
+ createdAt: Date;
+ updatedAt: Date;
+ isTemporary: boolean;
+ temporaryAccessEndTime: Date | null;
+ };
+
+ // When each source of project access last changed, so a secret's access can be dated from the oldest source that
+ // grants it: every role assignment (of users, identities and groups, with the last edit to a custom role's rules,
+ // since which secrets an edit opened is not recorded), and every privilege and folder grant. Membership updatedAt
+ // is left out because logins bump it. Expired access only takes access away, so it is not a source, except an
+ // expired folder grant: a restrictive one can give back the access it held back in its folder.
+ const findAccessSourceDates = async (projectId: string, tx?: Knex) => {
try {
- const roleChanges = (qb: Knex.QueryBuilder) =>
- qb
+ const [roleRows, privilegeRows] = (await Promise.all([
+ (tx || db.replicaNode())(TableName.Membership)
.join(TableName.MembershipRole, `${TableName.Membership}.id`, `${TableName.MembershipRole}.membershipId`)
.leftJoin(TableName.Role, `${TableName.MembershipRole}.customRoleId`, `${TableName.Role}.id`)
.where(`${TableName.Membership}.scope`, AccessScope.Project)
- .where(`${TableName.Membership}.scopeProjectId`, projectId);
- const roleColumns = [
- db.ref("createdAt").withSchema(TableName.MembershipRole),
- db.ref("updatedAt").withSchema(TableName.MembershipRole),
- db.ref("temporaryAccessEndTime").withSchema(TableName.MembershipRole),
- db.ref("updatedAt").withSchema(TableName.Role).as("customRoleUpdatedAt")
- ];
- // A group's roles reach each of its members, from the day the member joined the group.
- const groupRoleChanges = (
- memberTable: TableName.UserGroupMembership | TableName.IdentityGroupMembership,
- memberColumn: "userId" | "identityId"
- ) =>
- roleChanges(
- (tx || db.replicaNode())(TableName.Membership).join(
- memberTable,
- `${TableName.Membership}.actorGroupId`,
- `${memberTable}.groupId`
- )
- ).select(
- db.ref(memberColumn).withSchema(memberTable).as("groupMemberId"),
- db.ref("createdAt").withSchema(memberTable).as("membershipCreatedAt"),
- ...roleColumns
- );
-
- const [directChanges, userGroupChanges, identityGroupChanges, privilegeChanges] = (await Promise.all([
- 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
- ),
- groupRoleChanges(TableName.UserGroupMembership, "userId"),
- groupRoleChanges(TableName.IdentityGroupMembership, "identityId"),
+ .where(`${TableName.Membership}.scopeProjectId`, projectId)
+ .select(
+ db.ref("id").withSchema(TableName.MembershipRole).as("membershipRoleId"),
+ db.ref("actorGroupId").withSchema(TableName.Membership),
+ db.ref("createdAt").withSchema(TableName.Membership).as("membershipCreatedAt"),
+ db.ref("createdAt").withSchema(TableName.MembershipRole),
+ db.ref("updatedAt").withSchema(TableName.MembershipRole),
+ db.ref("isTemporary").withSchema(TableName.MembershipRole),
+ db.ref("temporaryAccessEndTime").withSchema(TableName.MembershipRole),
+ db.ref("updatedAt").withSchema(TableName.Role).as("customRoleUpdatedAt")
+ ),
(tx || db.replicaNode())(TableName.AdditionalPrivilege)
.where({ projectId })
- .select("actorUserId", "actorIdentityId", "createdAt", "updatedAt", "temporaryAccessEndTime")
- ])) as TAccessChange[][];
+ .select(
+ "id",
+ "actorUserId",
+ "actorIdentityId",
+ "folderId",
+ "createdAt",
+ "updatedAt",
+ "isTemporary",
+ "temporaryAccessEndTime"
+ )
+ ])) as [TRoleSourceRow[], TPrivilegeSourceRow[]];
const now = new Date();
- const changedAtByActorId = new Map<string, Date>();
- [...directChanges, ...userGroupChanges, ...identityGroupChanges, ...privilegeChanges].forEach((change) => {
- // 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);
- if (change.customRoleUpdatedAt) dates.push(change.customRoleUpdatedAt);
- if (change.temporaryAccessEndTime && new Date(change.temporaryAccessEndTime) <= now) {
- dates.push(change.temporaryAccessEndTime);
+ const isExpired = (row: { isTemporary: boolean; temporaryAccessEndTime: Date | null }) =>
+ row.isTemporary && (!row.temporaryAccessEndTime || new Date(row.temporaryAccessEndTime) <= now);
+ const latestOf = (dates: (Date | null)[]) =>
+ new Date(Math.max(...dates.flatMap((date) => (date ? [new Date(date).getTime()] : []))));
+
+ const roleDates = new Map<string, Date>();
+ const groupDates = new Map<string, Date>();
+ roleRows.forEach((row) => {
+ if (isExpired(row)) return;
+ const date = latestOf([row.membershipCreatedAt, row.createdAt, row.updatedAt, row.customRoleUpdatedAt]);
+ roleDates.set(row.membershipRoleId, date);
+ if (!row.actorGroupId) return;
+ const groupDate = groupDates.get(row.actorGroupId);
+ if (!groupDate || date > groupDate) groupDates.set(row.actorGroupId, date);
+ });
+
+ const privilegeDates = new Map<string, Date>();
+ // Keyed "<actorId>:<folderId>": when an expired folder grant last gave access back in that folder.
+ const folderReopenedAt = new Map<string, Date>();
+ privilegeRows.forEach((row) => {
+ if (!isExpired(row)) {
+ privilegeDates.set(row.id, latestOf([row.createdAt, row.updatedAt]));
+ return;
}
- const latest = new Date(Math.max(...dates.map((date) => new Date(date).getTime())));
- const current = changedAtByActorId.get(actorId);
- if (!current || latest > current) changedAtByActorId.set(actorId, latest);
+ const actorId = row.actorUserId ?? row.actorIdentityId;
+ if (!row.folderId || !actorId || !row.temporaryAccessEndTime) return;
+ const key = `${actorId}:${row.folderId}`;
+ const endedAt = new Date(row.temporaryAccessEndTime);
+ const current = folderReopenedAt.get(key);
+ if (!current || endedAt > current) folderReopenedAt.set(key, endedAt);
});
- return changedAtByActorId;
+
+ return { roleDates, groupDates, privilegeDates, folderReopenedAt };
} catch (error) {
- throw new DatabaseError({ error, name: "Find project access changes" });
+ throw new DatabaseError({ error, name: "Find project access source dates" });
}
};
@@ -280,6 +294,6 @@ export const secretReadActivityDALFactory = (db: TDbClient) => {
createMonthlyPartitions,
dropPartitionsEndingBefore,
findTrackingStartedAt,
- findAccessChangedAt
+ findAccessSourceDates
};
};
diff --git a/backend/src/ee/services/secret-read-activity/secret-read-activity-fns.test.ts b/backend/src/ee/services/secret-read-activity/secret-read-activity-fns.test.ts
index ab5c5bb58e..7ba45e8edc 100644
--- a/backend/src/ee/services/secret-read-activity/secret-read-activity-fns.test.ts
+++ b/backend/src/ee/services/secret-read-activity/secret-read-activity-fns.test.ts
@@ -13,6 +13,7 @@ import {
classifySecretReads,
computeSecretReach,
coversWholeWindow,
+ createAccessDating,
getReadStatus,
getUtcMonthStart,
indexSecretReads,
@@ -24,6 +25,7 @@ import {
SecretReadNotJudgedReason,
SecretReadObjectType,
SecretReadStatus,
+ TAccessSource,
TProjectAccess,
TReachSecret,
TSecretActivity,
@@ -159,11 +161,15 @@ describe("summarizeSecretAccess", () => {
reads: new Map(),
...overrides
});
+ const datedAccess = (accessSince: Record<string, Date>) => ({
+ accessSinceOf: ({ actorId }: { actorId: string }) => accessSince[actorId],
+ latestAccessChangeOf: ({ actorId }: { actorId: string }) => accessSince[actorId]
+ });
const access = (overrides: Partial<TProjectAccess> = {}): TProjectAccess => ({
readersByRules: [[reader("direct"), reader("via-group")], [reader("no-access", cannotRead)]],
adminActorIds: new Set(),
- accessChangedAtByActorId: new Map(),
judgedFrom,
+ ...datedAccess({}),
...overrides
});
const ids = (readers: { actorId: string }[]) => readers.map((entry) => entry.actorId).sort();
@@ -193,14 +199,22 @@ describe("summarizeSecretAccess", () => {
expect(ids(summary.unread)).toEqual(["direct"]);
});
- test("does not count a reader who read it, or whose access changed inside the judged period", () => {
+ test("does not count a reader who read it, or who got access to it 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")]]) })
+ access(datedAccess({ "via-group": new Date("2026-10-01T00:00:00.000Z") }))
);
expect(summary.unread).toEqual([]);
});
+ test("still counts a reader whose sources all predate the judged period", () => {
+ const summary = summarizeSecretAccess(
+ activity(),
+ access(datedAccess({ direct: new Date("2026-09-01T00:00:00.000Z") }))
+ );
+ expect(ids(summary.unread)).toEqual(["direct", "via-group"]);
+ });
+
test("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([]);
@@ -214,7 +228,7 @@ describe("getReadStatus", () => {
lastReadAt: null,
isUnused: false,
isProjectAdmin: false,
- accessChangedAt: null,
+ accessSince: new Date("2026-09-01T00:00:00.000Z"),
judgedFrom,
...overrides
});
@@ -234,15 +248,96 @@ describe("getReadStatus", () => {
readStatus: SecretReadStatus.NotJudged,
notJudgedReason
});
- expect(status({ isProjectAdmin: true, accessChangedAt: new Date("2026-10-01T00:00:00.000Z") })).toEqual(
+ expect(status({ isProjectAdmin: true, accessSince: new Date("2026-10-01T00:00:00.000Z") })).toEqual(
notJudged(SecretReadNotJudgedReason.ProjectAdmin)
);
- expect(status({ accessChangedAt: new Date("2026-10-01T00:00:00.000Z") })).toEqual(
- notJudged(SecretReadNotJudgedReason.AccessChanged)
+ expect(status({ accessSince: new Date("2026-10-01T00:00:00.000Z") })).toEqual(
+ notJudged(SecretReadNotJudgedReason.AccessTooNew)
+ );
+ expect(status()).toEqual(notJudged(SecretReadNotJudgedReason.SecretTooNew));
+ });
+});
+
+describe("createAccessDating", () => {
+ const sept = new Date("2026-09-01T00:00:00.000Z");
+ const oct = new Date("2026-10-20T00:00:00.000Z");
+ const ability = (rules: Parameters<typeof createMongoAbility>[0]) =>
+ createMongoAbility<MongoAbility<ProjectPermissionSet>>(rules as never);
+ const readsProd = ability([
+ {
+ action: ProjectPermissionSecretActions.ReadValue,
+ subject: ProjectPermissionSub.Secrets,
+ conditions: { environment: "prod" }
+ }
+ ]);
+ const readsAll = ability([
+ { action: ProjectPermissionSecretActions.ReadValue, subject: ProjectPermissionSub.Secrets }
+ ]);
+ const secretIn = (environment: string, folderId: string): TSecretActivity => ({
+ secret: { key: "DB_PASS", tags: [], folderId } as unknown as TSecretActivity["secret"],
+ environment,
+ secretPath: "/",
+ trackedSince: sept,
+ reads: new Map()
+ });
+ const dating = (sources: TAccessSource[], folderReopenedAt = new Map<string, Date>()) =>
+ createAccessDating(new Map([["actor", sources]]), folderReopenedAt);
+ const actor = { actorId: "actor" };
+
+ test("dates a secret from the oldest source that grants it, so a new source elsewhere changes nothing", () => {
+ const { accessSinceOf, latestAccessChangeOf } = dating([
+ { date: sept, permission: () => readsProd },
+ { date: oct, permission: () => readsAll }
+ ]);
+ expect(accessSinceOf(actor, secretIn("prod", "f1"))).toEqual(sept);
+ expect(accessSinceOf(actor, secretIn("dev", "f1"))).toEqual(oct);
+ expect(latestAccessChangeOf(actor)).toEqual(oct);
+ });
+
+ test("only lets a folder grant reach secrets in its own folder", () => {
+ const { accessSinceOf } = dating([
+ { date: sept, permission: () => readsProd },
+ { date: oct, folderId: "granted", permission: () => readsAll }
+ ]);
+ expect(accessSinceOf(actor, secretIn("prod", "other"))).toEqual(sept);
+ expect(accessSinceOf(actor, secretIn("dev", "granted"))).toEqual(oct);
+ });
+
+ test("falls back to the newest source when no single source grants it", () => {
+ const { accessSinceOf } = dating([
+ { date: sept, permission: () => ability([]) },
+ { date: oct, permission: () => ability([]) }
+ ]);
+ expect(accessSinceOf(actor, secretIn("prod", "f1"))).toEqual(oct);
+ });
+
+ test("dates access in a folder no earlier than an expired folder grant there", () => {
+ const { accessSinceOf, latestAccessChangeOf } = dating(
+ [{ date: sept, permission: () => readsAll }],
+ new Map([["actor:held-back", oct]])
);
- expect(status({ accessChangedAt: new Date("2026-09-01T00:00:00.000Z") })).toEqual(
- notJudged(SecretReadNotJudgedReason.SecretTooNew)
+ expect(accessSinceOf(actor, secretIn("prod", "held-back"))).toEqual(oct);
+ expect(accessSinceOf(actor, secretIn("prod", "f1"))).toEqual(sept);
+ expect(latestAccessChangeOf(actor)).toEqual(oct);
+ });
+
+ test("checks a source shared by many actors once per secret", () => {
+ let builds = 0;
+ const shared = () => {
+ builds += 1;
+ return readsAll;
+ };
+ const { accessSinceOf } = createAccessDating(
+ new Map([
+ ["a", [{ date: sept, permission: shared }]],
+ ["b", [{ date: sept, permission: shared }]]
+ ]),
+ new Map()
);
+ const secret = secretIn("prod", "f1");
+ expect(accessSinceOf({ actorId: "a" }, secret)).toEqual(sept);
+ expect(accessSinceOf({ actorId: "b" }, secret)).toEqual(sept);
+ expect(builds).toBe(2);
});
});
diff --git a/backend/src/ee/services/secret-read-activity/secret-read-activity-fns.ts b/backend/src/ee/services/secret-read-activity/secret-read-activity-fns.ts
index 39620c5ac8..d5b19dcfaf 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
@@ -12,9 +12,11 @@ import {
SecretReadNotJudgedReason,
SecretReadObjectType,
SecretReadStatus,
+ TAccessSource,
TMemberRole,
TProjectAccess,
TProjectFolderTree,
+ TProjectReader,
TReachSecret,
TSecretAccessSummary,
TSecretActivity,
@@ -107,10 +109,69 @@ export const computeSecretReach = (secret: TReachSecret, graph: TSecretReachGrap
export const indexSecretReads = (reads: TSecretLastRead[]) => groupBy(reads, (read) => read.objectId);
-// An unread secret only counts as unused once both it and the reader's current access have existed for the
-// whole window. Before that, the reader has not had the whole window to read it.
-export const coversWholeWindow = (trackedSince: Date, accessChangedAt: Date | undefined, windowStart: Date) =>
- trackedSince <= windowStart && (!accessChangedAt || accessChangedAt <= windowStart);
+// An unread secret only counts as unused once both it and the reader's access to it have existed for the whole
+// window. Before that, the reader has not had the whole window to read it.
+export const coversWholeWindow = (trackedSince: Date, accessSince: Date | undefined, windowStart: Date) =>
+ trackedSince <= windowStart && (!accessSince || accessSince <= windowStart);
+
+const subjectOf = ({ secret, environment, secretPath }: TSecretActivity) => ({
+ environment,
+ secretPath,
+ secretName: secret.key,
+ secretTags: secret.tags?.map((tag) => tag.slug)
+});
+
+// Dates an actor's access to each secret from the oldest of their sources that still grants it on its own, so a
+// change only restarts the window for the secrets it opened. With no single source granting it (rules that only
+// add up together), the newest source date is used. An expired restrictive folder grant can have given back access
+// in its folder, so access there dates no earlier than that. Each source is checked once per secret, and sources
+// shared by many actors (a role, a group) are checked once for all of them.
+export const createAccessDating = (
+ sourcesByActorId: Map<string, TAccessSource[]>,
+ folderReopenedAt: Map<string, Date>
+): Pick<TProjectAccess, "accessSinceOf" | "latestAccessChangeOf"> => {
+ const latestByActorId = new Map<string, Date>();
+ const raise = (actorId: string, date?: Date) => {
+ const current = latestByActorId.get(actorId);
+ if (date && (!current || date > current)) latestByActorId.set(actorId, date);
+ };
+ sourcesByActorId.forEach((sources, actorId) => sources.forEach((source) => raise(actorId, source.date)));
+ folderReopenedAt.forEach((date, key) => raise(key.slice(0, key.indexOf(":")), date));
+
+ const latestAccessChangeOf = ({ actorId }: { actorId: string }) => latestByActorId.get(actorId);
+ const checksBySecret = new WeakMap<TSecretActivity, Map<unknown, boolean>>();
+
+ const accessSinceOf = ({ actorId }: { actorId: string }, activity: TSecretActivity) => {
+ let checks = checksBySecret.get(activity);
+ if (!checks) {
+ checks = new Map();
+ checksBySecret.set(activity, checks);
+ }
+ const knownChecks = checks;
+ const subject = subjectOf(activity);
+ const grants = (source: TAccessSource) => {
+ if (source.folderId && source.folderId !== activity.secret.folderId) return false;
+ const permission = source.permission();
+ let granted = knownChecks.get(permission);
+ if (granted === undefined) {
+ granted = hasSecretReadValueOrDescribePermission(permission, ProjectPermissionSecretActions.ReadValue, subject);
+ knownChecks.set(permission, granted);
+ }
+ return granted;
+ };
+ const grantingDates = (sourcesByActorId.get(actorId) ?? []).flatMap((source) =>
+ source.date && grants(source) ? [source.date] : []
+ );
+ let since = grantingDates.length
+ ? new Date(Math.min(...grantingDates.map((date) => date.getTime())))
+ : latestByActorId.get(actorId);
+ const reopenedAt = folderReopenedAt.get(`${actorId}:${activity.secret.folderId}`);
+ if (reopenedAt && (!since || reopenedAt > since)) since = reopenedAt;
+ return since;
+ };
+
+ return { accessSinceOf, latestAccessChangeOf };
+};
// Reads before trackedSince are ignored: the secret or its folder did not exist yet.
export const classifySecretReads = (
@@ -143,10 +204,11 @@ export const classifySecretReads = (
// Who can read the secret's value today, and which of them have left it unread. Unused access is judged on the
// non-admins, since admins can read everything by design.
export const summarizeSecretAccess = (
- { secret, environment, secretPath, trackedSince, reads }: TSecretActivity,
- { readersByRules, adminActorIds, accessChangedAtByActorId, judgedFrom }: TProjectAccess
+ activity: TSecretActivity,
+ { readersByRules, adminActorIds, judgedFrom, accessSinceOf, latestAccessChangeOf }: TProjectAccess
): TSecretAccessSummary => {
- const subject = { environment, secretPath, secretName: secret.key, secretTags: secret.tags?.map((tag) => tag.slug) };
+ const { trackedSince, reads } = activity;
+ const subject = subjectOf(activity);
const entitled = unique(
readersByRules
.filter(([{ permission }]) =>
@@ -156,10 +218,15 @@ export const summarizeSecretAccess = (
(reader) => toActorKey(reader.actorType, reader.actorId)
);
const nonAdmins = entitled.filter((reader) => !adminActorIds.has(reader.actorId));
+ // Only a reader with a source newer than the judged period needs the per-secret date.
+ const accessSince = (reader: TProjectReader) => {
+ const latest = latestAccessChangeOf(reader);
+ return latest && latest > judgedFrom ? accessSinceOf(reader, activity) : latest;
+ };
const unread = nonAdmins.filter(
(reader) =>
!reads.has(toActorKey(reader.actorType, reader.actorId)) &&
- coversWholeWindow(trackedSince, accessChangedAtByActorId.get(reader.actorId), judgedFrom)
+ coversWholeWindow(trackedSince, accessSince(reader), judgedFrom)
);
return { entitled, nonAdmins, unread };
};
@@ -171,20 +238,20 @@ export const getReadStatus = ({
lastReadAt,
isUnused,
isProjectAdmin,
- accessChangedAt,
+ accessSince,
judgedFrom
}: {
lastReadAt: Date | null;
isUnused: boolean;
isProjectAdmin: boolean;
- accessChangedAt: Date | null;
+ accessSince: Date;
judgedFrom: Date;
}) => {
if (lastReadAt) return { readStatus: SecretReadStatus.Read, notJudgedReason: null };
if (isUnused) return { readStatus: SecretReadStatus.Unused, notJudgedReason: null };
let notJudgedReason = SecretReadNotJudgedReason.SecretTooNew;
if (isProjectAdmin) notJudgedReason = SecretReadNotJudgedReason.ProjectAdmin;
- else if (accessChangedAt && accessChangedAt > judgedFrom) notJudgedReason = SecretReadNotJudgedReason.AccessChanged;
+ else if (accessSince > judgedFrom) notJudgedReason = SecretReadNotJudgedReason.AccessTooNew;
return { readStatus: SecretReadStatus.NotJudged, notJudgedReason };
};
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 ea78ae7d5d..553da84db2 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,17 +1,21 @@
import { setImmediate } from "node:timers/promises";
-import { SecretType, TableName } from "@app/db/schemas";
+import { createMongoAbility, MongoAbility } from "@casl/ability";
+
+import { SecretFolderRole, SecretType, TableName } from "@app/db/schemas";
import { TIdentityGroupMembershipDALFactory } from "@app/ee/services/group/identity-group-membership-dal";
import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";
import { checkInsightsReadPermission } from "@app/ee/services/insights/insights-fns";
import {
+ buildFolderScopedPrivilegeRules,
hasSecretReadValueOrDescribePermission,
throwIfMissingSecretReadValueOrDescribePermission
} from "@app/ee/services/permission/permission-fns";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
-import { ProjectPermissionSecretActions } from "@app/ee/services/permission/project-permission";
+import { ProjectPermissionSecretActions, ProjectPermissionSet } from "@app/ee/services/permission/project-permission";
import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";
import { getCacheTtl, withCache } from "@app/lib/cache/with-cache";
+import { conditionsMatcher } from "@app/lib/casl";
import { NotFoundError } from "@app/lib/errors";
import { groupBy } from "@app/lib/fn";
import { logger } from "@app/lib/logger";
@@ -32,6 +36,7 @@ import { TSecretReadActivityDALFactory } from "./secret-read-activity-dal";
import {
classifySecretReads,
computeSecretReach,
+ createAccessDating,
getReadActivityWindowStart,
getReadStatus,
indexSecretReads,
@@ -43,6 +48,7 @@ import {
} from "./secret-read-activity-fns";
import { TSecretReadActivityQueueServiceFactory } from "./secret-read-activity-queue";
import {
+ TAccessSource,
TGetSecretReadActivityDTO,
TGetUnusedAccessActorDTO,
TListUnusedAccessDTO,
@@ -74,7 +80,7 @@ type TSecretReadActivityServiceFactoryDep = {
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getProjectPermissions">;
secretReadActivityDAL: Pick<
TSecretReadActivityDALFactory,
- "findLastReads" | "findTrackingStartedAt" | "findAccessChangedAt" | "findAdminActorIds"
+ "findLastReads" | "findTrackingStartedAt" | "findAccessSourceDates" | "findAdminActorIds"
>;
secretReadActivityQueue: Pick<TSecretReadActivityQueueServiceFactory, "recordRead" | "recordBulkRead">;
folderDAL: Pick<TSecretFolderDALFactory, "findByProjectId">;
@@ -279,13 +285,13 @@ export const secretReadActivityServiceFactory = ({
// tracking began.
const $loadProjectAccess = async (projectId: string, orgId: string, windowStart: Date) => {
const [
- { userPermissions, identityPermissions, groupPermissions },
- accessChangedAtByActorId,
+ { userPermissions, identityPermissions, groupPermissions, folderAccessByActorId },
+ sourceDates,
adminActorIds,
{ trackingStartedAt }
] = await Promise.all([
permissionService.getProjectPermissions(projectId, orgId),
- secretReadActivityDAL.findAccessChangedAt(projectId),
+ secretReadActivityDAL.findAccessSourceDates(projectId),
secretReadActivityDAL.findAdminActorIds(projectId),
$getProjectTrackingStartedAt(projectId)
]);
@@ -297,15 +303,21 @@ export const secretReadActivityServiceFactory = ({
const groupById = new Map(groupPermissions.map((group) => [group.id, group]));
const groupMembers = [
- ...userGroupMemberships.map(({ groupId, userId }) => ({ groupId, actorType: ActorType.USER, actorId: userId })),
- ...identityGroupMemberships.map(({ groupId, identityId }) => ({
+ ...userGroupMemberships.map(({ groupId, userId, createdAt }) => ({
+ groupId,
+ actorType: ActorType.USER,
+ actorId: userId,
+ joinedAt: createdAt
+ })),
+ ...identityGroupMemberships.map(({ groupId, identityId, createdAt }) => ({
groupId,
actorType: ActorType.IDENTITY,
- actorId: identityId
+ actorId: identityId,
+ joinedAt: createdAt
}))
- ].flatMap(({ groupId, actorType, actorId }) => {
+ ].flatMap(({ groupId, actorType, actorId, joinedAt }) => {
const group = groupById.get(groupId);
- return group ? [{ group, actorType: actorType as TSecretReaderType, actorId }] : [];
+ return group ? [{ group, actorType: actorType as TSecretReaderType, actorId, joinedAt }] : [];
});
const readers: TProjectReader[] = [
...userPermissions.map(({ id, permission }) => ({ actorType: ActorType.USER as const, actorId: id, permission })),
@@ -321,16 +333,65 @@ export const secretReadActivityServiceFactory = ({
}))
];
+ // Every source of each actor's access with its date: their own roles and project-wide privileges, each group
+ // they are in (dated from joining it or from the group's own role change, whichever is later), and their folder
+ // grants. The permissions are built only for an actor whose access needs dating per secret.
+ const sourcesByActorId = new Map<string, TAccessSource[]>();
+ const addSources = (actorId: string, sources: TAccessSource[]) =>
+ sourcesByActorId.set(actorId, [...(sourcesByActorId.get(actorId) ?? []), ...sources]);
+ [...userPermissions, ...identityPermissions].forEach((member) => {
+ const permissionOf = (key: string) => () =>
+ (member.accessSources().find((source) => source.key === key) ?? { permission: member.permission }).permission;
+ addSources(member.id, [
+ ...member.roles.map((role) => ({
+ date: sourceDates.roleDates.get(role.id),
+ permission: permissionOf(`role:${role.id}`)
+ })),
+ ...member.additionalPrivileges.map((privilege) => ({
+ date: sourceDates.privilegeDates.get(privilege.id),
+ permission: permissionOf(`privilege:${privilege.id}`)
+ }))
+ ]);
+ });
+ groupMembers.forEach(({ group, actorId, joinedAt }) => {
+ const groupChangedAt = sourceDates.groupDates.get(group.id);
+ addSources(actorId, [
+ {
+ date: groupChangedAt && groupChangedAt > joinedAt ? groupChangedAt : joinedAt,
+ permission: () => group.permission
+ }
+ ]);
+ });
+ folderAccessByActorId.forEach((grants, actorId) => {
+ addSources(
+ actorId,
+ grants.map((grant) => {
+ let permission: MongoAbility<ProjectPermissionSet> | undefined;
+ return {
+ date: sourceDates.privilegeDates.get(grant.id),
+ folderId: grant.folderId,
+ permission: () => {
+ permission ??= createMongoAbility<ProjectPermissionSet>(buildFolderScopedPrivilegeRules([grant]), {
+ conditionsMatcher
+ });
+ return permission;
+ }
+ };
+ })
+ );
+ });
+
return {
readersByRules: Object.values(groupBy(readers, (reader) => JSON.stringify(reader.permission.rules))),
adminActorIds,
- accessChangedAtByActorId,
+ ...createAccessDating(sourcesByActorId, sourceDates.folderReopenedAt),
judgedFrom: trackingStartedAt > windowStart ? trackingStartedAt : windowStart,
directMembers: new Map([
...userPermissions.map((member) => [toActorKey(ActorType.USER, member.id), member] as const),
...identityPermissions.map((member) => [toActorKey(ActorType.IDENTITY, member.id), member] as const)
]),
- groupMembershipsByActorKey: groupBy(groupMembers, (member) => toActorKey(member.actorType, member.actorId))
+ groupMembershipsByActorKey: groupBy(groupMembers, (member) => toActorKey(member.actorType, member.actorId)),
+ folderAccessByActorId
};
};
@@ -399,19 +460,20 @@ export const secretReadActivityServiceFactory = ({
const key = toActorKey(reader.actorType, reader.actorId);
const lastReadAt = activity.reads.get(key)?.lastReadAt ?? null;
const isProjectAdmin = access.adminActorIds.has(reader.actorId);
- const accessChangedAt = access.accessChangedAtByActorId.get(reader.actorId) ?? null;
+ // Every reader has at least one dated source; without one, access is as old as the secret's tracked period.
+ const accessSince = access.accessSinceOf(reader, activity) ?? activity.trackedSince;
return {
actorType: reader.actorType,
actorId: reader.actorId,
name: names.get(key) ?? reader.actorId,
isProjectAdmin,
lastReadAt,
- accessChangedAt,
+ accessSince,
...getReadStatus({
lastReadAt,
isUnused: unusedKeys.has(key),
isProjectAdmin,
- accessChangedAt,
+ accessSince,
judgedFrom: access.judgedFrom
})
};
@@ -490,7 +552,16 @@ export const secretReadActivityServiceFactory = ({
name: group.name,
roles: toUnusedAccessRoles(group.roles)
})),
- additionalPrivileges: member?.additionalPrivileges ?? []
+ additionalPrivileges: member?.additionalPrivileges ?? [],
+ folderAccess: (access.folderAccessByActorId.get(tally.actorId) ?? []).map(
+ ({ id, folderId, role, environmentSlug, secretPath }) => ({
+ id,
+ folderId,
+ environment: environmentSlug,
+ secretPath,
+ role: role as SecretFolderRole
+ })
+ )
}
};
});
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 b2224a0c37..535877000c 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,6 +1,6 @@
import { MongoAbility, MongoQuery } from "@casl/ability";
-import { TProjectEnvironments, TSecretFolders, TSecretReadActivity } from "@app/db/schemas";
+import { SecretFolderRole, 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";
@@ -120,11 +120,21 @@ export type TProjectReader = {
permission: MongoAbility<ProjectPermissionSet, MongoQuery>;
};
+// One way an actor has access, and when it last changed. A folder grant only reaches secrets in its own folder.
+export type TAccessSource = {
+ date?: Date;
+ folderId?: string;
+ permission: () => MongoAbility<ProjectPermissionSet, MongoQuery>;
+};
+
export type TProjectAccess = {
readersByRules: TProjectReader[][];
adminActorIds: Set<string>;
- accessChangedAtByActorId: Map<string, Date>;
judgedFrom: Date;
+ // When the actor got access to the secret: the oldest of their sources that grants it on its own.
+ accessSinceOf: (actor: { actorId: string }, activity: TSecretActivity) => Date | undefined;
+ // The newest of the actor's source dates. When it is older than the judged period, so is every secret's access.
+ latestAccessChangeOf: (actor: { actorId: string }) => Date | undefined;
};
export type TSecretAccessSummary = {
@@ -142,7 +152,7 @@ export enum SecretReadStatus {
export enum SecretReadNotJudgedReason {
ProjectAdmin = "project-admin",
- AccessChanged = "access-changed",
+ AccessTooNew = "access-too-new",
SecretTooNew = "secret-too-new"
}
@@ -152,21 +162,25 @@ export type TSecretReadActivityActor = {
name: string;
isProjectAdmin: boolean;
lastReadAt: Date | null;
- accessChangedAt: Date | null;
+ accessSince: Date;
readStatus: SecretReadStatus;
notJudgedReason: SecretReadNotJudgedReason | null;
};
-export type TMemberRole = Awaited<
- ReturnType<TPermissionServiceFactory["getProjectPermissions"]>
->["userPermissions"][number]["roles"][number];
+// A group's roles carry no assignment id, and naming a role does not need one.
+export type TMemberRole = Omit<
+ Awaited<ReturnType<TPermissionServiceFactory["getProjectPermissions"]>>["userPermissions"][number]["roles"][number],
+ "id"
+>;
export type TUnusedAccessRole = { id: string | null; slug: string; name: string };
export type TUnusedAccessPaths = {
roles: TUnusedAccessRole[];
groups: { id: string; name: string; roles: TUnusedAccessRole[] }[];
+ // Project-wide only; a privilege tied to a folder is a folder grant, listed under folderAccess.
additionalPrivileges: { id: string; name: string }[];
+ folderAccess: { id: string; folderId: string; environment: string; secretPath: string; role: SecretFolderRole }[];
};
export type TUnusedAccessActor = {
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index 5639dd936e..6b04a0215c 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -970,9 +970,17 @@ export const INSIGHTS = {
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.",
+ additionalPrivileges:
+ "The project-wide additional privileges the actor holds. Access granted on a folder is listed under folderAccess instead.",
additionalPrivilegeId: "The ID of the additional privilege.",
additionalPrivilegeName: "The name of the additional privilege.",
+ folderAccess:
+ "The folder access the actor has been granted directly on folders, active grants only. It applies whether the actor is a direct member or reaches the project through a group.",
+ folderAccessId: "The ID of the folder access grant.",
+ folderId: "The ID of the folder.",
+ folderEnvironment: "The slug of the environment the folder is in.",
+ folderSecretPath: "The path of the folder.",
+ folderRole: "The access level granted on the folder: list, read, edit, manage or full-access.",
totalCount: "The number of actors the caller can page through.",
periodStart:
"Unused means no read since this date: 30 days before the results were computed, or when reads started being tracked for the project if that is later. Results are recomputed once a day."
@@ -1005,12 +1013,12 @@ export const INSIGHTS = {
"Whether the actor is a project admin, directly or through a group. Admins can read everything by design, so they never count as unused access.",
lastReadAt:
"When the actor last read the secret, or an import or reference of it, since readsTrackedSince, as the first read of that day. Null when they have not.",
- accessChangedAt:
- "When the actor's access to the project last changed: the latest membership, role or privilege creation, edit or expiry. Null when it has not changed since the membership was created.",
+ accessSince:
+ "When the actor got access to this secret: the oldest of their roles, groups, privileges and folder grants that gives it on its own, from when it was last created or changed. An edit to a custom role's rules counts for every secret the role gives, since which secrets an edit opened is not recorded.",
readStatus:
"read: the actor read the secret since readsTrackedSince. unused: no read, and the secret and their access both predate unusedAccessJudgedFrom, so it counts as unused access. not-judged: no read, but it does not count yet; notJudgedReason says why.",
notJudgedReason:
- "Why an actor without a read is not counted as unused access. project-admin: admins are never counted. access-changed: their access changed after unusedAccessJudgedFrom. secret-too-new: the secret is newer than unusedAccessJudgedFrom. Null unless readStatus is not-judged."
+ "Why an actor without a read is not counted as unused access. project-admin: admins are never counted. access-too-new: they got access to the secret after unusedAccessJudgedFrom. secret-too-new: the secret is newer than unusedAccessJudgedFrom. Null unless readStatus is not-judged."
},
GET_SECRETS_ACCESS_VOLUME: {
days: "One entry for each of the last seven days, oldest first. Days with no secret access are included with a total of zero.",
diff --git a/frontend/src/hooks/api/secretInsights/types.ts b/frontend/src/hooks/api/secretInsights/types.ts
index 844b87e82e..a4fadc1188 100644
--- a/frontend/src/hooks/api/secretInsights/types.ts
+++ b/frontend/src/hooks/api/secretInsights/types.ts
@@ -1,3 +1,4 @@
+import { SecretFolderRole } from "../folderAccess/types";
import { IdentityAuthMethod } from "../identities/enums";
export type TCalendarRotation = {
@@ -67,6 +68,13 @@ export type TUnusedAccessPaths = {
roles: TUnusedAccessRole[];
groups: { id: string; name: string; roles: TUnusedAccessRole[] }[];
additionalPrivileges: { id: string; name: string }[];
+ folderAccess: {
+ id: string;
+ folderId: string;
+ environment: string;
+ secretPath: string;
+ role: SecretFolderRole;
+ }[];
};
// A user or machine identity that can read secrets it has not read in the tracked period.
@@ -122,7 +130,7 @@ export enum SecretReadStatus {
export enum SecretReadNotJudgedReason {
ProjectAdmin = "project-admin",
- AccessChanged = "access-changed",
+ AccessTooNew = "access-too-new",
SecretTooNew = "secret-too-new"
}
@@ -139,7 +147,8 @@ export type TSecretReadActivityActor = {
name: string;
isProjectAdmin: boolean;
lastReadAt: string | null;
- accessChangedAt: string | null;
+ // When they got access to this secret.
+ accessSince: string;
readStatus: SecretReadStatus;
notJudgedReason: SecretReadNotJudgedReason | null;
};
diff --git a/frontend/src/pages/secret-manager/InsightsPage/components/UnusedAccessCard.tsx b/frontend/src/pages/secret-manager/InsightsPage/components/UnusedAccessCard.tsx
index 2b84ef040c..271898feae 100644
--- a/frontend/src/pages/secret-manager/InsightsPage/components/UnusedAccessCard.tsx
+++ b/frontend/src/pages/secret-manager/InsightsPage/components/UnusedAccessCard.tsx
@@ -176,7 +176,10 @@ export const UnusedAccessCard = () => {
</TableCell>
<TableCell className="max-w-64">
<OverflowBadgeList
- items={accessPathBadges(row.accessPaths)}
+ items={accessPathBadges(
+ row.accessPaths,
+ (slug) => environmentNames.get(slug) ?? slug
+ )}
getKey={(item) => item.key}
getLabel={(item) => item.label}
getVariant={() => "neutral"}
diff --git a/frontend/src/pages/secret-manager/InsightsPage/components/unusedAccessHelpers.ts b/frontend/src/pages/secret-manager/InsightsPage/components/unusedAccessHelpers.ts
index 23178c039f..42391de0bd 100644
--- a/frontend/src/pages/secret-manager/InsightsPage/components/unusedAccessHelpers.ts
+++ b/frontend/src/pages/secret-manager/InsightsPage/components/unusedAccessHelpers.ts
@@ -2,6 +2,7 @@ import { format } from "date-fns";
import { HardDriveIcon, UserIcon } from "lucide-react";
import { TUnusedAccessPaths, UnusedAccessActorType } from "@app/hooks/api/secretInsights";
+import { FOLDER_ROLE_TIER_LABELS } from "@app/pages/secret-manager/OverviewPage/components/FolderAccessSheet/folder-access.const";
export const ACTOR_TYPE_CONFIG: Record<
UnusedAccessActorType,
@@ -11,7 +12,10 @@ export const ACTOR_TYPE_CONFIG: Record<
[UnusedAccessActorType.Identity]: { icon: HardDriveIcon, label: "Machine Identity" }
};
-export const accessPathBadges = ({ roles, additionalPrivileges, groups }: TUnusedAccessPaths) => [
+export const accessPathBadges = (
+ { roles, additionalPrivileges, groups, folderAccess }: TUnusedAccessPaths,
+ environmentName: (slug: string) => string
+) => [
...roles.map((role) => ({
key: `role:${role.slug}:${role.id ?? ""}`,
label: `Role: ${role.name}`
@@ -25,6 +29,10 @@ export const accessPathBadges = ({ roles, additionalPrivileges, groups }: TUnuse
label: group.roles.length
? `Group: ${group.name} (${group.roles.map((role) => role.name).join(", ")})`
: `Group: ${group.name}`
+ })),
+ ...folderAccess.map((access) => ({
+ key: `folder:${access.id}`,
+ label: `Folder: ${environmentName(access.environment)} ${access.secretPath} (${FOLDER_ROLE_TIER_LABELS[access.role] ?? access.role})`
}))
];
diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/SecretAccessInsights.tsx b/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/SecretAccessInsights.tsx
index 2d33f897d6..f2d7566a09 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/SecretAccessInsights.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/SecretAccessInsights.tsx
@@ -533,13 +533,10 @@ export function SecretAccessInsights({
"Project admins can read everything by design, so they are not counted as unused access."
};
}
- if (
- actor?.notJudgedReason === SecretReadNotJudgedReason.AccessChanged &&
- actor.accessChangedAt
- ) {
+ if (actor?.notJudgedReason === SecretReadNotJudgedReason.AccessTooNew) {
return {
kind: "pending",
- reason: `Their access changed on ${format(new Date(actor.accessChangedAt), "PP")}, after reads started being counted on ${judgedFrom}, so they have not had the whole period to read it.`
+ reason: `They got access to this secret on ${format(new Date(actor.accessSince), "PP")}, after reads started being counted on ${judgedFrom}, so they have not had the whole period to read it.`
};
}
if (actor?.notJudgedReason === SecretReadNotJudgedReason.SecretTooNew) {