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
refactor(insights): align the read activity endpoints and hooks with the other insights code
Dimitris Staratzis406029993c1b
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex c8111e6f17..669f39f573 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -1146,7 +1146,7 @@ owns the two read endpoints and hands `recordRead` / `recordBulkRead` through to- **Read path.** A read counts when it reaches the secret through its folder, an import of it, a secretreferencing it, or the source of a replication import (imports and references check the reader's own accessto the source, so revoking it would break them). The card computes the whole project once and caches it- (`UNUSED_SECRET_ACCESS_CACHE_TTL_SECONDS`), grouping actors by identical rules so each rule set is checked once+ (`KeyStoreTtls.InsightsUnusedAccessCacheInSeconds`), 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 judges a full window, or everything since tracking began.** Tracking starts at the later of thediff --git a/backend/src/ee/routes/v1/insights-router.ts b/backend/src/ee/routes/v1/insights-router.tsindex 1adeced44b..51d6e757f9 100644--- a/backend/src/ee/routes/v1/insights-router.ts+++ b/backend/src/ee/routes/v1/insights-router.ts@@ -495,21 +495,21 @@ export const registerInsightsRouter = async (server: FastifyZodProvider) => {onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),handler: async (req, reply) => {const { projectId } = req.params;- const { actors, totalCount, periodStart, remainingTTL, projectName } =- await server.services.secretReadActivity.listUnusedAccess({ projectId, ...req.query }, req.permission);+ const { result, remainingTTL } = await server.services.secretReadActivity.listUnusedAccess(+ { projectId, ...req.query },+ req.permission+ );await server.services.auditLog.createAuditLog({projectId,- event: {- type: EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_UNUSED_ACCESS,- metadata: { projectId, projectName }- },+ event: { type: EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_UNUSED_ACCESS, metadata: { projectId } },...req.auditLogInfo});if (remainingTTL && remainingTTL >= 0) {void reply.header("X-Cache-TTL", remainingTTL);}- return { actors, totalCount, periodStart };++ return result;}});@@ -533,22 +533,15 @@ export const registerInsightsRouter = async (server: FastifyZodProvider) => {onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),handler: async (req, reply) => {const { projectId, actorType, actorId } = req.params;- const { actor, secrets, periodStart, remainingTTL, projectName } =- await server.services.secretReadActivity.getUnusedAccessActor(- { projectId, actorType, actorId },- req.permission- );+ const { result, remainingTTL } = await server.services.secretReadActivity.getUnusedAccessActor(+ { projectId, actorType, actorId },+ req.permission+ );await server.services.auditLog.createAuditLog({projectId,event: {type: EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_UNUSED_ACCESS,- metadata: {- projectId,- projectName,- principalType: actorType,- principalId: actorId,- principalName: actor.name- }+ metadata: { projectId, principalType: actorType, principalId: actorId, principalName: result.actor.name }},...req.auditLogInfo});@@ -556,7 +549,8 @@ export const registerInsightsRouter = async (server: FastifyZodProvider) => {if (remainingTTL && remainingTTL >= 0) {void reply.header("X-Cache-TTL", remainingTTL);}- return { actor, secrets, periodStart };++ return result;}});diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 174aa10976..6d7aabbb40 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -5982,7 +5982,6 @@ 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;diff --git a/backend/src/ee/services/insights/insights-service.ts b/backend/src/ee/services/insights/insights-service.tsindex bcd84f17a3..ec2d92d62d 100644--- a/backend/src/ee/services/insights/insights-service.ts+++ b/backend/src/ee/services/insights/insights-service.ts@@ -127,8 +127,8 @@ const assertInsightsPlanEnabled = async (}};-const checkInsightsPermission = async (- permissionService: TInsightsServiceFactoryDep["permissionService"],+export const checkInsightsPermission = async (+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">,licenseService: TInsightsServiceFactoryDep["licenseService"],projectId: string,actor: OrgServiceActordiff --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 65349bfe24..1e6fdb8ef9 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,23 +1,20 @@import { setImmediate } from "node:timers/promises";-import { createMongoAbility, ForbiddenError } from "@casl/ability";+import { createMongoAbility } from "@casl/ability";-import { ActionProjectType, SecretFolderRole, SecretType, TableName } from "@app/db/schemas";+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 { checkInsightsPermission } from "@app/ee/services/insights/insights-service";+import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";import {buildFolderScopedPrivilegeRules,hasSecretReadValueOrDescribePermission,throwIfMissingSecretReadValueOrDescribePermission} from "@app/ee/services/permission/permission-fns";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";-import {- ProjectPermissionInsightsActions,- ProjectPermissionSecretActions,- ProjectPermissionSet,- ProjectPermissionSub-} from "@app/ee/services/permission/project-permission";-import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";+import { ProjectPermissionSecretActions, ProjectPermissionSet } from "@app/ee/services/permission/project-permission";+import { KeyStorePrefixes, KeyStoreTtls, 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";@@ -67,7 +64,6 @@ import {TUnusedSecret} from "./secret-read-activity-types";-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 UNUSED_ACCESS_COMPUTE_LOCK_TTL_MS = 5 * 60 * 1000;@@ -87,6 +83,7 @@ const once = <T>(build: () => T) => {type TSecretReadActivityServiceFactoryDep = {permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getProjectPermissions">;+ licenseService: Pick<TLicenseServiceFactory, "getPlan">;secretReadActivityDAL: Pick<TSecretReadActivityDALFactory,"findLastReads" | "findTrackingStartedAt" | "findAccessSourceDates" | "findAdminActorIds"@@ -110,6 +107,7 @@ export type TSecretReadActivityServiceFactory = ReturnType<typeof secretReadActiexport const secretReadActivityServiceFactory = ({permissionService,+ licenseService,secretReadActivityDAL,secretReadActivityQueue,folderDAL,@@ -125,23 +123,6 @@ export const secretReadActivityServiceFactory = ({kmsService,keyStore}: TSecretReadActivityServiceFactoryDep) => {- // The permission alone, not the plan: a downgrade must not hide reads already collected.- const $getInsightsPermission = async (projectId: string, actor: OrgServiceActor) => {- const { permission } = await permissionService.getProjectPermission({- actor: actor.type,- actorId: actor.id,- projectId,- actorAuthMethod: actor.authMethod,- actorOrgId: actor.orgId,- actionProjectType: ActionProjectType.SecretManager- });- ForbiddenError.from(permission).throwUnlessCan(- ProjectPermissionInsightsActions.Read,- ProjectPermissionSub.Insights- );- return permission;- };-let instanceTrackingStartedAt: Promise<Date | undefined> | undefined;const $getTrackingStartedAt = () => {instanceTrackingStartedAt ??= secretReadActivityDAL.findTrackingStartedAt().catch((error) => {@@ -492,7 +473,7 @@ export const secretReadActivityServiceFactory = ({{ projectId, environment, secretPath, secretName }: TGetSecretReadActivityDTO,actor: OrgServiceActor) => {- const permission = await $getInsightsPermission(projectId, actor);+ const { permission } = await checkInsightsPermission(permissionService, licenseService, projectId, actor);// The secret is checked before the reach is built, which decrypts every secret that could reference it.const tree = await loadProjectFolderTree({ folderDAL, projectEnvDAL }, projectId);@@ -648,7 +629,7 @@ export const secretReadActivityServiceFactory = ({const summary = await withCache({keyStore,key: cacheKey,- ttlSeconds: UNUSED_ACCESS_CACHE_TTL_SECONDS,+ ttlSeconds: KeyStoreTtls.InsightsUnusedAccessCacheInSeconds,// 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.fetcher: async () => {@@ -670,7 +651,7 @@ export const secretReadActivityServiceFactory = ({// 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, UNUSED_ACCESS_CACHE_TTL_SECONDS, JSON.stringify(result))+ .setItemWithExpiry(cacheKey, KeyStoreTtls.InsightsUnusedAccessCacheInSeconds, JSON.stringify(result)).catch((error) => {logger.warn(error, `unused-access: failed to cache the project computation [projectId=${projectId}]`);});@@ -680,33 +661,22 @@ export const secretReadActivityServiceFactory = ({}}});- const [remainingTTL, project] = await Promise.all([- getCacheTtl(keyStore, cacheKey),- projectDAL.findById(projectId)- ]);- return {- ...summary,- // Dates come back from the cache as strings.- periodStart: new Date(summary.periodStart),- remainingTTL,- projectName: project?.name ?? ""- };+ const remainingTTL = await getCacheTtl(keyStore, cacheKey);+ // Dates come back from the cache as strings.+ return { ...summary, periodStart: new Date(summary.periodStart), remainingTTL };};const listUnusedAccess = async ({ projectId, offset, limit, search }: TListUnusedAccessDTO,actor: OrgServiceActor) => {- await $getInsightsPermission(projectId, actor);- const { rows, ...tracking } = await $getCachedUnusedAccess(projectId, actor.orgId);+ await checkInsightsPermission(permissionService, licenseService, projectId, actor);+ const { rows, periodStart, remainingTTL } = await $getCachedUnusedAccess(projectId, actor.orgId);const needle = search?.trim().toLowerCase();const matching = needle ? rows.filter((row) => row.name.toLowerCase().includes(needle)) : rows;return {- actors: matching.slice(offset, offset + limit),- totalCount: matching.length,- projectName: tracking.projectName,- periodStart: tracking.periodStart,- remainingTTL: tracking.remainingTTL+ result: { actors: matching.slice(offset, offset + limit), totalCount: matching.length, periodStart },+ remainingTTL};};@@ -714,8 +684,8 @@ export const secretReadActivityServiceFactory = ({{ projectId, actorType, actorId }: TGetUnusedAccessActorDTO,actor: OrgServiceActor) => {- const permission = await $getInsightsPermission(projectId, actor);- const { rows, details, ...tracking } = await $getCachedUnusedAccess(projectId, actor.orgId);+ const { permission } = await checkInsightsPermission(permissionService, licenseService, projectId, actor);+ const { rows, details, periodStart, remainingTTL } = await $getCachedUnusedAccess(projectId, actor.orgId);const unusedAccessActor = rows.find((row) => row.actorType === actorType && row.actorId === actorId);if (!unusedAccessActor) {throw new NotFoundError({@@ -728,7 +698,7 @@ export const secretReadActivityServiceFactory = ({(await withCache({keyStore,key: KeyStorePrefixes.InsightsCache(projectId, `unused-access:${actorType}:${actorId}`),- ttlSeconds: UNUSED_ACCESS_CACHE_TTL_SECONDS,+ ttlSeconds: KeyStoreTtls.InsightsUnusedAccessCacheInSeconds,fetcher: async () =>(await $tallyUnusedAccess(projectId, actor.orgId)).tallies.get(actorId)?.unusedSecretIds ?? []}));@@ -758,13 +728,7 @@ export const secretReadActivityServiceFactory = ({a.secretPath.localeCompare(b.secretPath) ||a.secretKey.localeCompare(b.secretKey));- return {- actor: unusedAccessActor,- secrets,- projectName: tracking.projectName,- periodStart: tracking.periodStart,- remainingTTL: tracking.remainingTTL- };+ return { result: { actor: unusedAccessActor, secrets, periodStart }, remainingTTL };};return {diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.tsindex 45f3c2367d..9221882519 100644--- a/backend/src/keystore/keystore.ts+++ b/backend/src/keystore/keystore.ts@@ -282,6 +282,7 @@ export const KeyStoreTtls = {InsightsDuplicationCacheInSeconds: 300, // 5 minutesInsightsWeeklyHistoryCacheInSeconds: 86400, // 24 hoursInsightsOrgCacheInSeconds: 900, // 15 minutes+ InsightsUnusedAccessCacheInSeconds: 86400, // 24 hoursAdminConfigInSeconds: 60,UpdateCheckLatestVersionInSeconds: 1209600, // 14 days (survives one missed weekly check)InvalidatingCacheInSeconds: 1800, // 30 minutes max lock for cache invalidation jobdiff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 93c504d8d7..fed3e91166 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -3527,6 +3527,7 @@ export const registerRoutes = async (const secretReadActivityService = secretReadActivityServiceFactory({permissionService,+ licenseService,secretReadActivityDAL,secretReadActivityQueue,folderDAL,diff --git a/frontend/src/hooks/api/secretInsights/queries.tsx b/frontend/src/hooks/api/secretInsights/queries.tsxindex a6070c4bd2..44b085a28d 100644--- a/frontend/src/hooks/api/secretInsights/queries.tsx+++ b/frontend/src/hooks/api/secretInsights/queries.tsx@@ -80,10 +80,6 @@ export const secretInsightsKeys = {const INSIGHTS_STALE_TIME = 5 * 60 * 1000; // 5 minutes-// Fresh until the server's cached copy expires, then refetched, so an open card picks up the recomputed list.-const cachedInsightsRefreshMs = (data?: { remainingTtl: number }) =>- data && data.remainingTtl > 0 ? data.remainingTtl * 1000 : INSIGHTS_STALE_TIME;-export const useGetCalendarInsights = (params: TGetCalendarInsightsDTO,options?: Omit<@@ -159,8 +155,7 @@ export const useGetUnusedAccess = (const remainingTtl = Number(res.headers["x-cache-ttl"] ?? -1);return { ...res.data, remainingTtl };},- staleTime: (query) => cachedInsightsRefreshMs(query.state.data),- refetchInterval: (query) => cachedInsightsRefreshMs(query.state.data),+ staleTime: INSIGHTS_STALE_TIME,placeholderData: (previousData) => previousData,...options});@@ -187,7 +182,7 @@ export const useGetUnusedAccessActor = (const remainingTtl = Number(res.headers["x-cache-ttl"] ?? -1);return { ...res.data, remainingTtl };},- staleTime: (query) => cachedInsightsRefreshMs(query.state.data),+ staleTime: INSIGHTS_STALE_TIME,...options});};diff --git a/frontend/src/pages/secret-manager/InsightsPage/components/UnusedAccessCard.tsx b/frontend/src/pages/secret-manager/InsightsPage/components/UnusedAccessCard.tsxindex 0554c3bd9a..aac924fac7 100644--- a/frontend/src/pages/secret-manager/InsightsPage/components/UnusedAccessCard.tsx+++ b/frontend/src/pages/secret-manager/InsightsPage/components/UnusedAccessCard.tsx@@ -31,7 +31,7 @@ import {TooltipTrigger} from "@app/components/v3";import { cn } from "@app/components/v3/utils";-import { useProject, useSubscription } from "@app/context";+import { useProject } from "@app/context";import { usePagination, useResetPageHelper } from "@app/hooks";import { TUnusedAccessActor, useGetUnusedAccess } from "@app/hooks/api/secretInsights";@@ -47,14 +47,13 @@ import {export const UnusedAccessCard = () => {const { currentProject, projectId } = useProject();- const { subscription } = useSubscription();const { page, setPage, perPage, setPerPage, offset, limit, search, setSearch, debouncedSearch } =usePagination("", { initPerPage: 10 });const [selected, setSelected] = useState<TUnusedAccessActor | null>(null);const { data, isPending, error } = useGetUnusedAccess({ projectId, offset, limit, search: debouncedSearch || undefined },- { enabled: Boolean(subscription?.secretAccessInsights) }+ { enabled: !!projectId });const totalCount = data?.totalCount ?? 0;useResetPageHelper({ totalCount, offset, setPage });@@ -223,7 +222,7 @@ export const UnusedAccessCard = () => {</CardDescription><CardAction><InputGroup className="w-64">- <InputGroupAddon>+ <InputGroupAddon align="inline-start"><SearchIcon /></InputGroupAddon><InputGroupInput