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: update unused secret access logic to exclude project admins and clarify preliminary results
Dimitris Staratzisb627a47c152e
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex 5f40c9c99c..917e402005 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -1138,14 +1138,16 @@ owns the two read endpoints and hands `recordRead` / `recordBulkRead` through to(`UNUSED_SECRET_ACCESS_CACHE_TTL_SECONDS`), grouping actors by identical rules so each rule set is checked onceper secret. The per-secret endpoint checks the caller's access to the secret before building its reach, whichdecrypts every secret that could reference it.-- **The card only judges a full window.** It lists a principal who has not read a secret only once both the- secret (`trackedSince`) and their access have existed for the whole window, and leaves them out before that;- there is no separate status for it. Access age is `findAccessChangedAt`: the latest membership creation, role- or privilege (folder grants included) creation or edit. Which secrets a change opened up is not recorded, so- any change restarts the window, and a custom role's rules being edited is not seen at all. The per-secret- sheet shows the plain fact instead: a read, or "No reads". The card response carries `trackingStartedAt` (the- later of the migration that created the table and the project's creation) and `unusedAccessFrom` (a window- after it), so the UI can say tracking is in progress instead of showing an empty list as "no unused access".+- **The card judges a full window, or everything since tracking began.** It 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 the later of the window start and the project's tracking+ start (the later of the migration that created the table and the project's creation). So in a project tracked for+ less than 30 days the card already lists access unread since tracking began, and the response's+ `preliminaryUntil` tells the UI to label it preliminary. Which secrets a change opened up is not recorded, so any+ access change restarts the window, and a custom role's rules being edited is not seen at all. The per-secret sheet+ shows the plain fact instead: a read, or "No reads".### Audit Log Event Classes and Settingsdiff --git a/backend/src/ee/routes/v1/insights-router.ts b/backend/src/ee/routes/v1/insights-router.tsindex cbfda9db6b..0badbf7f92 100644--- a/backend/src/ee/routes/v1/insights-router.ts+++ b/backend/src/ee/routes/v1/insights-router.ts@@ -476,7 +476,7 @@ export const registerInsightsRouter = async (server: FastifyZodProvider) => {schema: {operationId: "getInsightsUnusedSecretAccess",description:- "List the users and machine identities that can read a secret's value but have not read it in the last 30 days",+ "List the users and machine identities, other than project admins, that can read a secret's value but have not read it in the last 30 days",security: [{ bearerAuth: [] }],params: z.object({projectId: z.string().trim().max(36).describe(INSIGHTS.GET_UNUSED_SECRET_ACCESS.projectId)@@ -502,7 +502,7 @@ export const registerInsightsRouter = async (server: FastifyZodProvider) => {totalCount,unlistedCount,trackingStartedAt,- unusedAccessFrom,+ preliminaryUntil,remainingTTL,projectName} = await server.services.secretReadActivity.listUnusedSecretAccess({ projectId, ...req.query }, req.permission);@@ -519,7 +519,7 @@ export const registerInsightsRouter = async (server: FastifyZodProvider) => {void reply.header("X-Cache-TTL", remainingTTL);}- return { unusedAccess, totalCount, unlistedCount, trackingStartedAt, unusedAccessFrom };+ return { unusedAccess, totalCount, unlistedCount, trackingStartedAt, preliminaryUntil };}});diff --git a/backend/src/ee/services/insights/insights-schemas.ts b/backend/src/ee/services/insights/insights-schemas.tsindex 5bae6957bc..2c1e380dac 100644--- a/backend/src/ee/services/insights/insights-schemas.ts+++ b/backend/src/ee/services/insights/insights-schemas.ts@@ -71,7 +71,7 @@ export const UnusedSecretAccessSchema = z.object({totalCount: z.number().int().describe(INSIGHTS.GET_UNUSED_SECRET_ACCESS.totalCount),unlistedCount: z.number().int().describe(INSIGHTS.GET_UNUSED_SECRET_ACCESS.unlistedCount),trackingStartedAt: z.date().describe(INSIGHTS.GET_UNUSED_SECRET_ACCESS.trackingStartedAt),- unusedAccessFrom: z.date().describe(INSIGHTS.GET_UNUSED_SECRET_ACCESS.unusedAccessFrom),+ preliminaryUntil: z.date().describe(INSIGHTS.GET_UNUSED_SECRET_ACCESS.preliminaryUntil),unusedAccess: z.object({secretKey: z.string().describe(INSIGHTS.GET_UNUSED_SECRET_ACCESS.secretKey),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.tsindex 1bc3d83220..81358897a6 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@@ -2,7 +2,7 @@ import { Knex } from "knex";import RE2 from "re2";import { TDbClient } from "@app/db";-import { AccessScope, TableName } from "@app/db/schemas";+import { AccessScope, ProjectMembershipRole, TableName } from "@app/db/schemas";import { DatabaseError } from "@app/lib/errors";import { chunkArray } from "@app/lib/fn";@@ -178,7 +178,50 @@ export const secretReadActivityDALFactory = (db: TDbClient) => {}};+ // Users and identities that hold the project Admin role now, directly or through a group. A temporary role counts+ // until it expires.+ const findAdminActorIds = async (projectId: string, tx?: Knex) => {+ try {+ const adminMemberships = (qb: Knex.QueryBuilder) =>+ qb+ .join(TableName.MembershipRole, `${TableName.Membership}.id`, `${TableName.MembershipRole}.membershipId`)+ .where(`${TableName.Membership}.scope`, AccessScope.Project)+ .where(`${TableName.Membership}.scopeProjectId`, projectId)+ .where(`${TableName.MembershipRole}.role`, ProjectMembershipRole.Admin)+ .where((roleQb) => {+ void roleQb+ .where(`${TableName.MembershipRole}.isTemporary`, false)+ .orWhere(`${TableName.MembershipRole}.temporaryAccessEndTime`, ">", new Date());+ });++ const [directAdmins, groupAdmins] = (await Promise.all([+ adminMemberships((tx || db.replicaNode())(TableName.Membership)).select(+ db.ref("actorUserId").withSchema(TableName.Membership),+ db.ref("actorIdentityId").withSchema(TableName.Membership)+ ),+ adminMemberships(+ (tx || db.replicaNode())(TableName.Membership).join(+ TableName.UserGroupMembership,+ `${TableName.Membership}.actorGroupId`,+ `${TableName.UserGroupMembership}.groupId`+ )+ ).select(db.ref("userId").withSchema(TableName.UserGroupMembership))+ ])) as [{ actorUserId: string | null; actorIdentityId: string | null }[], { userId: string }[]];++ return new Set([+ ...directAdmins.flatMap(({ actorUserId, actorIdentityId }) => {+ const actorId = actorUserId ?? actorIdentityId;+ return actorId ? [actorId] : [];+ }),+ ...groupAdmins.map(({ userId }) => userId)+ ]);+ } catch (error) {+ throw new DatabaseError({ error, name: "Find project admins" });+ }+ };+return {+ findAdminActorIds,upsertLastReads,findLastReads,createMonthlyPartitions,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 3f3ab5cabb..4e2abbb614 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@@ -60,7 +60,7 @@ type TSecretReadActivityServiceFactoryDep = {permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getProjectPermissions">;secretReadActivityDAL: Pick<TSecretReadActivityDALFactory,- "findLastReads" | "findTrackingStartedAt" | "findAccessChangedAt"+ "findLastReads" | "findTrackingStartedAt" | "findAccessChangedAt" | "findAdminActorIds">;secretReadActivityQueue: Pick<TSecretReadActivityQueueServiceFactory, "recordRead" | "recordBulkRead">;folderDAL: Pick<TSecretFolderDALFactory, "findByProjectId">;@@ -86,13 +86,13 @@ export const secretReadActivityServiceFactory = ({kmsService,keyStore}: TSecretReadActivityServiceFactoryDep) => {- let trackingStartedAt: Promise<Date | undefined> | undefined;+ let instanceTrackingStartedAt: Promise<Date | undefined> | undefined;const $getTrackingStartedAt = () => {- trackingStartedAt ??= secretReadActivityDAL.findTrackingStartedAt().catch((error) => {- trackingStartedAt = undefined;+ instanceTrackingStartedAt ??= secretReadActivityDAL.findTrackingStartedAt().catch((error) => {+ instanceTrackingStartedAt = undefined;throw error;});- return trackingStartedAt;+ return instanceTrackingStartedAt;};const $getReadActivity = async ({@@ -287,22 +287,41 @@ export const secretReadActivityServiceFactory = ({return { trackedSince: activity.trackedSince, reads: [...activity.reads.values()] };};- // Everyone who can read a secret's value but has not read it in the whole window, ranked by the secrets with the- // most of them.+ // Reads are known from the later of when tracking began on the instance and when the project was created.+ const $getProjectTrackingStartedAt = async (projectId: string) => {+ const [instanceStartedAt, project] = await Promise.all([$getTrackingStartedAt(), projectDAL.findById(projectId)]);+ return {+ project,+ trackingStartedAt: new Date(Math.max(instanceStartedAt?.getTime() ?? 0, project?.createdAt.getTime() ?? 0))+ };+ };++ // Everyone except admins who can read a secret's value but has not read it in the window, ranked by the secrets+ // with the most of them. Admins can read everything by design, so listing them would only add noise. In a project+ // tracked for less than the window, the window starts when tracking did, so the results are preliminary.const $computeUnusedSecretAccess = async (projectId: string, orgId: string) => {const windowStart = getReadActivityWindowStart();- const [activities, { userPermissions, identityPermissions }, accessChangedAtByActorId] = await Promise.all([+ const [+ activities,+ { userPermissions, identityPermissions },+ accessChangedAtByActorId,+ adminActorIds,+ { trackingStartedAt }+ ] = await Promise.all([$getReadActivity({ projectId, windowStart }),permissionService.getProjectPermissions(projectId, orgId),- secretReadActivityDAL.findAccessChangedAt(projectId)+ secretReadActivityDAL.findAccessChangedAt(projectId),+ secretReadActivityDAL.findAdminActorIds(projectId),+ $getProjectTrackingStartedAt(projectId)]);+ const judgedFrom = trackingStartedAt > windowStart ? trackingStartedAt : windowStart;// Actors with identical rules always get the same answer, so each distinct rule set is checked once.const actorGroups = Object.values(groupBy([...userPermissions.map((actor) => ({ ...actor, actorType: ActorType.USER as const })),...identityPermissions.map((actor) => ({ ...actor, actorType: ActorType.IDENTITY as const }))- ],+ ].filter((actor) => !adminActorIds.has(actor.id)),(actor) => JSON.stringify(actor.permission.rules)));@@ -321,7 +340,7 @@ export const secretReadActivityServiceFactory = ({.filter((actor) =>!reads.has(`${actor.actorType}:${actor.id}`) &&- coversWholeWindow(trackedSince, accessChangedAtByActorId.get(actor.id), windowStart)+ coversWholeWindow(trackedSince, accessChangedAtByActorId.get(actor.id), judgedFrom));// Only counts are kept for every secret: a large project can have millions of unread pairs, and only the@@ -399,10 +418,9 @@ export const secretReadActivityServiceFactory = ({ttlSeconds: UNUSED_SECRET_ACCESS_CACHE_TTL_SECONDS,fetcher: () => $computeUnusedSecretAccessShared(projectId, actor.orgId, cacheKey)});- const [remainingTTL, instanceTrackingStartedAt, project, tree, currentSecrets] = await Promise.all([+ const [remainingTTL, { project, trackingStartedAt }, tree, currentSecrets] = await Promise.all([getCacheTtl(keyStore, cacheKey),- $getTrackingStartedAt(),- projectDAL.findById(projectId),+ $getProjectTrackingStartedAt(projectId),loadProjectFolderTree({ folderDAL, projectEnvDAL }, projectId),rows.length? secretV2BridgeDAL.find({@@ -410,12 +428,6 @@ export const secretReadActivityServiceFactory = ({}): []]);- // Reads are known from the later of when tracking began and when the project was created, and nothing can be- // called unused until a whole window has passed since then.- const projectTrackingStartedAt = new Date(- Math.max(instanceTrackingStartedAt?.getTime() ?? 0, project?.createdAt.getTime() ?? 0)- );-// The cache is shared by everyone in the project and can be a day old, so each row is checked against the// secret as it is now: deleted secrets drop out, and a caller only gets the secrets they could see anyway.const currentSecretById = new Map(currentSecrets.map((secret) => [secret.id, secret]));@@ -449,8 +461,8 @@ export const secretReadActivityServiceFactory = ({totalCount: visibleRows.length,unlistedCount: totalCount - rows.length,projectName: project?.name ?? "",- trackingStartedAt: projectTrackingStartedAt,- unusedAccessFrom: new Date(projectTrackingStartedAt.getTime() + SECRET_READ_ACTIVITY_WINDOW_DAYS * DAY_IN_MS),+ trackingStartedAt,+ preliminaryUntil: new Date(trackingStartedAt.getTime() + SECRET_READ_ACTIVITY_WINDOW_DAYS * DAY_IN_MS),remainingTTL};};diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex 096847a829..eebfe7594a 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -959,10 +959,10 @@ export const INSIGHTS = {"The number of further entries with less unused access that are not listed, counted across the whole project before the caller's permissions are applied. Zero unless the project has more than 1,000.",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.",- unusedAccessFrom:- "When access can first be listed as unused: 30 days after tracking started. Until then the list is empty.",+ 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.",unusedAccess:- "One entry for each secret and user or machine identity that can read the secret's value but has not read it, or an import or reference of it, in the last 30 days. Secrets and access newer than 30 days are left out.",+ "One entry for each secret and user or machine identity, other than project admins, that can read the secret's value but has not read it, or an import or reference of it, in the last 30 days. Secrets and access newer than 30 days are left out.",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.",diff --git a/frontend/src/hooks/api/secretInsights/types.ts b/frontend/src/hooks/api/secretInsights/types.tsindex 99bbc9a916..4f3740b467 100644--- a/frontend/src/hooks/api/secretInsights/types.ts+++ b/frontend/src/hooks/api/secretInsights/types.ts@@ -81,7 +81,7 @@ export type TGetUnusedSecretAccessResponse = {totalCount: number;unlistedCount: number;trackingStartedAt: string;- unusedAccessFrom: string;+ preliminaryUntil: string;remainingTtl: number;};diff --git a/frontend/src/pages/secret-manager/InsightsPage/components/UnusedSecretAccessCard.tsx b/frontend/src/pages/secret-manager/InsightsPage/components/UnusedSecretAccessCard.tsxindex ccb1eeff12..cbde1d6531 100644--- a/frontend/src/pages/secret-manager/InsightsPage/components/UnusedSecretAccessCard.tsx+++ b/frontend/src/pages/secret-manager/InsightsPage/components/UnusedSecretAccessCard.tsx@@ -1,10 +1,20 @@import { useParams } from "@tanstack/react-router";import axios from "axios";import { format } from "date-fns";-import { ChevronDownIcon, FolderIcon, HardDriveIcon, KeyIcon, UserIcon } from "lucide-react";+import {+ ChevronDownIcon,+ FolderIcon,+ HardDriveIcon,+ InfoIcon,+ KeyIcon,+ UserIcon+} from "lucide-react";import { GoToSecretButton } from "@app/components/secrets/GoToSecretButton";import {+ Alert,+ AlertDescription,+ AlertTitle,Badge,Card,CardContent,@@ -111,37 +121,42 @@ export const UnusedSecretAccessCard = () => {);}- if (new Date(data.unusedAccessFrom) > new Date()) {- return (- <Empty className="border">- <EmptyHeader>- <EmptyTitle>Tracking reads</EmptyTitle>- <EmptyDescription>- Reads have been tracked since {format(new Date(data.trackingStartedAt), "PP")}. Access- that goes unread for 30 days shows here from{" "}- {format(new Date(data.unusedAccessFrom), "PP")}.- </EmptyDescription>- </EmptyHeader>- </Empty>- );- }+ const isPreliminary = new Date(data.preliminaryUntil) > new Date();+ const preliminaryNotice = isPreliminary && (+ <Alert variant="info" className="mb-4">+ <InfoIcon />+ <AlertTitle>Preliminary Results</AlertTitle>+ <AlertDescription>+ Unused access is measured over 30 days of reads. Tracking for this project began on{" "}+ {format(new Date(data.trackingStartedAt), "PP")}, so these results cover a shorter period+ and will be complete on {format(new Date(data.preliminaryUntil), "PP")}.+ </AlertDescription>+ </Alert>+ );if (totalCount === 0) {return (- <Empty className="border">- <EmptyHeader>- <EmptyTitle>No unused access</EmptyTitle>- <EmptyDescription>- Access shows here once someone has been able to read a secret for 30 days without- reading it.- </EmptyDescription>- </EmptyHeader>- </Empty>+ <>+ {preliminaryNotice}+ <Empty className="border">+ <EmptyHeader>+ <EmptyTitle>+ {isPreliminary ? "No unused access so far" : "No unused access"}+ </EmptyTitle>+ <EmptyDescription>+ {isPreliminary+ ? "Everyone who could read these secrets when tracking began has read them since."+ : "Access shows here once someone has been able to read a secret for 30 days without reading it."}+ </EmptyDescription>+ </EmptyHeader>+ </Empty>+ </>);}return (<>+ {preliminaryNotice}<Table><TableHeader><TableRow>@@ -239,8 +254,8 @@ export const UnusedSecretAccessCard = () => {)}</CardTitle><CardDescription>- Users and machine identities that can read a secret but have not read it in the last 30- days+ Users and machine identities, other than project admins, that can read a secret but have+ not read it in the last 30 days</CardDescription></CardHeader><CardContent>{renderBody()}</CardContent>