Skip to content

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

refactor: cache unused secret access for 24 hours, capped at 1,000 entries

Dimitris Staratzis9bad1dc011fc
diff --git a/backend/src/ee/routes/v1/insights-router.ts b/backend/src/ee/routes/v1/insights-router.ts
index 5b13a2c971..4891e85b20 100644
--- a/backend/src/ee/routes/v1/insights-router.ts
+++ b/backend/src/ee/routes/v1/insights-router.ts
@@ -497,7 +497,7 @@ export const registerInsightsRouter = async (server: FastifyZodProvider) => {
onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),
handler: async (req, reply) => {
const { projectId } = req.params;
- const { unusedAccess, totalCount, trackingStartedAt, unusedAccessFrom, remainingTTL } =
+ const { unusedAccess, totalCount, unlistedCount, trackingStartedAt, unusedAccessFrom, remainingTTL } =
await server.services.secretReadActivity.listUnusedSecretAccess({ projectId, ...req.query }, req.permission);
await server.services.auditLog.createAuditLog({
projectId,
@@ -509,7 +509,7 @@ export const registerInsightsRouter = async (server: FastifyZodProvider) => {
void reply.header("X-Cache-TTL", remainingTTL);
}
- return { unusedAccess, totalCount, trackingStartedAt, unusedAccessFrom };
+ return { unusedAccess, totalCount, unlistedCount, trackingStartedAt, unusedAccessFrom };
}
});
diff --git a/backend/src/ee/services/insights/insights-schemas.ts b/backend/src/ee/services/insights/insights-schemas.ts
index ae5dffa411..5bae6957bc 100644
--- a/backend/src/ee/services/insights/insights-schemas.ts
+++ b/backend/src/ee/services/insights/insights-schemas.ts
@@ -69,6 +69,7 @@ export const SecretsProjectsSchema = z.object({
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),
unusedAccess: z
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 cb0550a507..38529783b6 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
@@ -44,7 +44,10 @@ import {
TUnusedSecretAccess
} from "./secret-read-activity-types";
-const UNUSED_SECRET_ACCESS_CACHE_TTL_SECONDS = 30;
+const UNUSED_SECRET_ACCESS_CACHE_TTL_SECONDS = 24 * 60 * 60;
+// A large project can have millions of unread secret and actor pairs, so only the highest-ranked entries are
+// cached and listed, about 200 KB per project.
+const UNUSED_SECRET_ACCESS_MAX_LISTED = 1000;
type TSecretReadActivityServiceFactoryDep = {
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getProjectPermissions">;
@@ -317,10 +320,11 @@ export const secretReadActivityServiceFactory = ({
})
);
}
- return rowsBySecret.sort((a, b) => b.length - a.length).flat();
+ const ranked = rowsBySecret.sort((a, b) => b.length - a.length).flat();
+ return { rows: ranked.slice(0, UNUSED_SECRET_ACCESS_MAX_LISTED), totalCount: ranked.length };
};
- // The whole project is computed once and cached, so paging through it is cheap.
+ // The whole project is computed once a day and cached, so paging through it is cheap.
const listUnusedSecretAccess = async (
{ projectId, offset, limit, orderBy, orderDirection }: TListUnusedSecretAccessDTO,
actor: OrgServiceActor
@@ -328,7 +332,7 @@ export const secretReadActivityServiceFactory = ({
await checkInsightsPermission(permissionService, licenseService, projectId, actor);
const cacheKey = KeyStorePrefixes.InsightsCache(projectId, "unused-secret-access");
- const unusedAccess = await withCache({
+ const { rows, totalCount } = await withCache({
keyStore,
key: cacheKey,
ttlSeconds: UNUSED_SECRET_ACCESS_CACHE_TTL_SECONDS,
@@ -347,15 +351,16 @@ export const secretReadActivityServiceFactory = ({
// Unsorted, the list keeps its ranking. The sort is stable, so ties keep it too.
const sorted = orderBy
- ? [...unusedAccess].sort((a, b) => {
+ ? [...rows].sort((a, b) => {
const [first, second] = orderDirection === OrderByDirection.DESC ? [b, a] : [a, b];
return first[orderBy].localeCompare(second[orderBy]);
})
- : unusedAccess;
+ : rows;
return {
unusedAccess: sorted.slice(offset, offset + limit),
- totalCount: sorted.length,
+ totalCount: rows.length,
+ unlistedCount: totalCount - rows.length,
trackingStartedAt: projectTrackingStartedAt,
unusedAccessFrom: new Date(projectTrackingStartedAt.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.ts
index 0301029a55..f3b71155c3 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -952,7 +952,9 @@ export const INSIGHTS = {
limit: "The maximum number of entries to return per page.",
orderBy: "The field to sort by. Without it, the secrets with the most unused access come first.",
orderDirection: "The direction to sort in.",
- totalCount: "The total number of entries across all pages.",
+ totalCount: "The number of entries that can be paged through, at most 1,000.",
+ unlistedCount:
+ "The number of further entries with less unused access that are not listed. 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:
diff --git a/frontend/src/hooks/api/secretInsights/queries.tsx b/frontend/src/hooks/api/secretInsights/queries.tsx
index ca5ee41c99..13c51939cb 100644
--- a/frontend/src/hooks/api/secretInsights/queries.tsx
+++ b/frontend/src/hooks/api/secretInsights/queries.tsx
@@ -70,7 +70,8 @@ export const secretInsightsKeys = {
};
const INSIGHTS_STALE_TIME = 5 * 60 * 1000; // 5 minutes
-const UNUSED_SECRET_ACCESS_POLL_INTERVAL_MS = 30 * 1000; // 30 seconds
+// The server recomputes unused access once a day, so a fresher fetch would return the same data.
+const UNUSED_SECRET_ACCESS_STALE_TIME = 24 * 60 * 60 * 1000; // 24 hours
export const useGetCalendarInsights = (
params: TGetCalendarInsightsDTO,
@@ -147,8 +148,7 @@ export const useGetUnusedSecretAccess = (
const remainingTtl = Number(res.headers["x-cache-ttl"] ?? -1);
return { ...res.data, remainingTtl };
},
- staleTime: UNUSED_SECRET_ACCESS_POLL_INTERVAL_MS,
- refetchInterval: UNUSED_SECRET_ACCESS_POLL_INTERVAL_MS,
+ staleTime: UNUSED_SECRET_ACCESS_STALE_TIME,
placeholderData: (previousData) => previousData,
...options
});
diff --git a/frontend/src/hooks/api/secretInsights/types.ts b/frontend/src/hooks/api/secretInsights/types.ts
index 7e2d679a75..99bbc9a916 100644
--- a/frontend/src/hooks/api/secretInsights/types.ts
+++ b/frontend/src/hooks/api/secretInsights/types.ts
@@ -79,6 +79,7 @@ export type TUnusedSecretAccess = {
export type TGetUnusedSecretAccessResponse = {
unusedAccess: TUnusedSecretAccess[];
totalCount: number;
+ unlistedCount: number;
trackingStartedAt: string;
unusedAccessFrom: string;
remainingTtl: number;
diff --git a/frontend/src/pages/secret-manager/InsightsPage/components/UnusedSecretAccessCard.tsx b/frontend/src/pages/secret-manager/InsightsPage/components/UnusedSecretAccessCard.tsx
index fa8b88a8fe..ccb1eeff12 100644
--- a/frontend/src/pages/secret-manager/InsightsPage/components/UnusedSecretAccessCard.tsx
+++ b/frontend/src/pages/secret-manager/InsightsPage/components/UnusedSecretAccessCard.tsx
@@ -36,8 +36,12 @@ const formatRemainingTtl = (seconds: number) => {
const remainingSeconds = Math.max(1, seconds);
return `${remainingSeconds} ${remainingSeconds === 1 ? "second" : "seconds"}`;
}
- const minutes = Math.ceil(seconds / 60);
- return `${minutes} ${minutes === 1 ? "minute" : "minutes"}`;
+ if (seconds < 60 * 60) {
+ const minutes = Math.ceil(seconds / 60);
+ return `${minutes} ${minutes === 1 ? "minute" : "minutes"}`;
+ }
+ const hours = Math.ceil(seconds / (60 * 60));
+ return `${hours} ${hours === 1 ? "hour" : "hours"}`;
};
export const UnusedSecretAccessCard = () => {
@@ -213,6 +217,12 @@ export const UnusedSecretAccessCard = () => {
onChangePage={setPage}
onChangePerPage={setPerPage}
/>
+ {data.unlistedCount > 0 && (
+ <p className="mt-2 text-xs text-muted">
+ Showing the {totalCount.toLocaleString()} entries with the most unused access.{" "}
+ {data.unlistedCount.toLocaleString()} more are not listed.
+ </p>
+ )}
</>
);
};