Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
fix(insights): date restored access from when the restriction ended, and bound scan memory
Dimitris Staratzis2b61d5431080
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex 2b74030b7f..8e98cadbdd 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -1161,8 +1161,11 @@ owns the two read endpoints and hands `recordRead` / `recordBulkRead` through to`groupsOnly` so placeholders hold the member's details; 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+ for every secret it gives, since which secrets an edit opened is not recorded. Expired access is not a source, but+ an ended restriction may have given access back, so access dates no earlier than an expired folder grant in its+ folder, a folder grant edited since its creation in its folder, or an expired temporary role or privilege across+ all of its holder's access (what it held back is not worked out). Only the current secret's source checks are+ kept, so the scan's memory does not grow with the project. Only an actor with asource newer than `judgedFrom` is checked per secret, and each source once per secret across actors. A read frombefore the reader had access to a secret is dropped for that secret (`readsByActorKey`): reads are credited byfolder, and a folder read then could not have returned it. A read recorded against the secret itselfdiff --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.tsindex a608749fbe..994f3f9550 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@@ -137,6 +137,8 @@ export const secretReadActivityDALFactory = (db: TDbClient) => {type TRoleSourceRow = {membershipRoleId: string;+ actorUserId: string | null;+ actorIdentityId: string | null;actorGroupId: string | null;membershipCreatedAt: Date;createdAt: Date;@@ -160,8 +162,9 @@ export const secretReadActivityDALFactory = (db: TDbClient) => {// 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.+ // is left out because logins bump it. Expired access is not a source, but a restriction ending can give access+ // back, so its end is kept as the earliest that access can date from: an expired folder grant's in its folder, and+ // an expired temporary role's or privilege's for the whole of its holder's access.const findAccessSourceDates = async (projectId: string, tx?: Knex) => {try {const [roleRows, privilegeRows] = (await Promise.all([@@ -172,6 +175,8 @@ export const secretReadActivityDALFactory = (db: TDbClient) => {.where(`${TableName.Membership}.scopeProjectId`, projectId).select(db.ref("id").withSchema(TableName.MembershipRole).as("membershipRoleId"),+ 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"),db.ref("createdAt").withSchema(TableName.MembershipRole),@@ -200,34 +205,46 @@ export const secretReadActivityDALFactory = (db: TDbClient) => {const latestOf = (dates: (Date | null)[]) =>new Date(Math.max(...dates.flatMap((date) => (date ? [new Date(date).getTime()] : []))));+ // Keyed by the user, identity or group that held it: when its latest temporary role or privilege expired.+ const accessReopenedAt = new Map<string, Date>();+ const raise = (dates: Map<string, Date>, key: string, date: Date) => {+ const current = dates.get(key);+ if (!current || date > current) dates.set(key, date);+ };+ const recordExpiry = (holderId: string | null, endedAt: Date | null) => {+ if (holderId && endedAt) raise(accessReopenedAt, holderId, new Date(endedAt));+ };+const roleDates = new Map<string, Date>();const groupDates = new Map<string, Date>();roleRows.forEach((row) => {- if (isExpired(row)) return;+ if (isExpired(row)) {+ recordExpiry(row.actorUserId ?? row.actorIdentityId ?? row.actorGroupId, row.temporaryAccessEndTime);+ 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);+ if (row.actorGroupId) raise(groupDates, row.actorGroupId, date);});const privilegeDates = new Map<string, Date>();+ const editedPrivilegeIds = new Set<string>();// Keyed "<actorId>:<folderId>": when an expired folder grant last gave access back in that folder.const folderReopenedAt = new Map<string, Date>();privilegeRows.forEach((row) => {+ const actorId = row.actorUserId ?? row.actorIdentityId;if (!isExpired(row)) {privilegeDates.set(row.id, latestOf([row.createdAt, row.updatedAt]));+ if (new Date(row.updatedAt) > new Date(row.createdAt)) editedPrivilegeIds.add(row.id);return;}- 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);+ if (!row.folderId) recordExpiry(actorId, row.temporaryAccessEndTime);+ else if (actorId && row.temporaryAccessEndTime) {+ raise(folderReopenedAt, `${actorId}:${row.folderId}`, new Date(row.temporaryAccessEndTime));+ }});- return { roleDates, groupDates, privilegeDates, folderReopenedAt };+ return { roleDates, groupDates, privilegeDates, editedPrivilegeIds, folderReopenedAt, accessReopenedAt };} catch (error) {throw new DatabaseError({ error, name: "Find project access source dates" });}diff --git a/backend/src/ee/services/secret-read-activity/secret-read-activity-fns.test.ts b/backend/src/ee/services/secret-read-activity/secret-read-activity-fns.test.tsindex 8ff6e3a22e..80a5bdfb18 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@@ -378,6 +378,25 @@ describe("createAccessDating", () => {expect(latestAccessChangeOf(actor)).toEqual(oct);});+ test("dates access in an edited folder grant's folder from the edit, since it may have held access back", () => {+ const { accessSinceOf } = dating([+ { date: sept, permission: () => readsAll },+ { date: oct, folderId: "granted", restartsFolder: true, permission: () => readsAll }+ ]);+ expect(accessSinceOf(actor, secretIn("prod", "granted"))).toEqual(oct);+ expect(accessSinceOf(actor, secretIn("prod", "f1"))).toEqual(sept);+ });++ test("dates all access no earlier than an expired temporary role or privilege", () => {+ const { accessSinceOf, latestAccessChangeOf } = createAccessDating(+ new Map([["actor", [{ date: sept, permission: () => readsAll }]]]),+ new Map(),+ new Map([["actor", oct]])+ );+ expect(accessSinceOf(actor, secretIn("prod", "f1"))).toEqual(oct);+ expect(latestAccessChangeOf(actor)).toEqual(oct);+ });+test("checks a source shared by many actors once per secret", () => {let builds = 0;const shared = () => {diff --git a/backend/src/ee/services/secret-read-activity/secret-read-activity-fns.ts b/backend/src/ee/services/secret-read-activity/secret-read-activity-fns.tsindex 7d07a5b991..c8ff3dbea8 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@@ -123,12 +123,15 @@ const subjectOf = ({ secret, environment, secretPath }: TSecretActivity) => ({// 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.+// add up together), the newest source date is used. Restrictions that ended can have given access back, so access+// dates no earlier than an expired folder grant in its folder (folderReopenedAt, by "<actorId>:<folderId>"), an+// edited folder grant in its folder, or an expired temporary role or privilege anywhere (accessReopenedAt, by actor,+// since what it held back is not worked out). Sources are checked once per secret, shared ones (a role, a group)+// once for every actor holding them, and only the current secret's checks are kept.export const createAccessDating = (sourcesByActorId: Map<string, TAccessSource[]>,- folderReopenedAt: Map<string, Date>+ folderReopenedAt: Map<string, Date>,+ accessReopenedAt = new Map<string, Date>()): Pick<TProjectAccess, "accessSinceOf" | "latestAccessChangeOf"> => {const latestByActorId = new Map<string, Date>();const raise = (actorId: string, date?: Date) => {@@ -137,36 +140,42 @@ export const createAccessDating = (};sourcesByActorId.forEach((sources, actorId) => sources.forEach((source) => raise(actorId, source.date)));folderReopenedAt.forEach((date, key) => raise(key.slice(0, key.indexOf(":")), date));+ accessReopenedAt.forEach((date, actorId) => raise(actorId, date));const latestAccessChangeOf = ({ actorId }: { actorId: string }) => latestByActorId.get(actorId);- const checksBySecret = new WeakMap<TSecretActivity, Map<unknown, boolean>>();+ let checkedSecret: TSecretActivity | undefined;+ let checks = new Map<unknown, boolean>();const accessSinceOf = ({ actorId }: { actorId: string }, activity: TSecretActivity) => {- let checks = checksBySecret.get(activity);- if (!checks) {+ if (activity !== checkedSecret) {+ checkedSecret = activity;checks = new Map();- checksBySecret.set(activity, checks);}- const knownChecks = checks;const subject = subjectOf(activity);+ const inFolder = (source: TAccessSource) => source.folderId === activity.secret.folderId;const grants = (source: TAccessSource) => {- if (source.folderId && source.folderId !== activity.secret.folderId) return false;+ if (source.folderId && !inFolder(source)) return false;const permission = source.permission();- let granted = knownChecks.get(permission);+ let granted = checks.get(permission);if (granted === undefined) {granted = hasSecretReadValueOrDescribePermission(permission, ProjectPermissionSecretActions.ReadValue, subject);- knownChecks.set(permission, granted);+ checks.set(permission, granted);}return granted;};- const grantingDates = (sourcesByActorId.get(actorId) ?? []).flatMap((source) =>- source.date && grants(source) ? [source.date] : []- );+ const sources = sourcesByActorId.get(actorId) ?? [];+ const grantingDates = sources.flatMap((source) => (source.date && grants(source) ? [source.date] : []));+ const floors = [+ folderReopenedAt.get(`${actorId}:${activity.secret.folderId}`),+ accessReopenedAt.get(actorId),+ ...sources.map((source) => (source.restartsFolder && inFolder(source) ? source.date : undefined))+ ];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;+ floors.forEach((floor) => {+ if (floor && (!since || floor > since)) since = floor;+ });return since;};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.tsindex 05c5cde43f..f24673ac89 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@@ -421,6 +421,7 @@ export const secretReadActivityServiceFactory = ({return {date: sourceDates.privilegeDates.get(grant.id),folderId: grant.folderId,+ restartsFolder: sourceDates.editedPrivilegeIds.has(grant.id),permission: () => {permission ??= createMongoAbility<ProjectPermissionSet>(buildFolderScopedPrivilegeRules([grant]), {conditionsMatcher@@ -432,10 +433,20 @@ export const secretReadActivityServiceFactory = ({);});+ // A group's expired temporary role reached each of its members.+ const accessReopenedAt = new Map<string, Date>();+ const membersByGroupId = groupBy(groupMembers, (member) => member.group.id);+ sourceDates.accessReopenedAt.forEach((date, holderId) => {+ (membersByGroupId[holderId]?.map((member) => member.actorId) ?? [holderId]).forEach((actorId) => {+ const current = accessReopenedAt.get(actorId);+ if (!current || date > current) accessReopenedAt.set(actorId, date);+ });+ });+return {readersByRules: Object.values(groupBy(readers, (reader) => JSON.stringify(reader.permission.rules))),adminActorIds,- ...createAccessDating(sourcesByActorId, sourceDates.folderReopenedAt),+ ...createAccessDating(sourcesByActorId, sourceDates.folderReopenedAt, accessReopenedAt),judgedFrom: trackingStartedAt > windowStart ? trackingStartedAt : windowStart,directMembers: new Map([...userPermissions.map((member) => [toActorKey(ActorType.USER, member.id), member] as const),diff --git a/backend/src/ee/services/secret-read-activity/secret-read-activity-types.ts b/backend/src/ee/services/secret-read-activity/secret-read-activity-types.tsindex 357fb7f005..f6ac169778 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@@ -131,6 +131,9 @@ export type TProjectReader = {export type TAccessSource = {date?: Date;folderId?: string;+ // A folder grant edited since it was created may have held access back before, so access in its folder dates from+ // the edit.+ restartsFolder?: boolean;permission: () => MongoAbility<ProjectPermissionSet, MongoQuery>;};