Skip to content

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

chore: update to shared with cache util

Scott Wilson5ea6e3dfbfd7
diff --git a/backend/src/ee/services/insights/insights-service.ts b/backend/src/ee/services/insights/insights-service.ts
index 4b819407b7..a1071ea148 100644
--- a/backend/src/ee/services/insights/insights-service.ts
+++ b/backend/src/ee/services/insights/insights-service.ts
@@ -9,6 +9,7 @@ import { TPermissionServiceFactory } from "@app/ee/services/permission/permissio
import { ProjectPermissionInsightsActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
import { TSecretRotationV2DALFactory } from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-dal";
import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";
+import { withCache } from "@app/lib/cache/with-cache";
import { BadRequestError } from "@app/lib/errors";
import { OrgServiceActor } from "@app/lib/types";
import { ActorType } from "@app/services/auth/auth-type";
@@ -87,15 +88,6 @@ export const insightsServiceFactory = ({
userDAL,
keyStore
}: TInsightsServiceFactoryDep) => {
- const withCache = async <T>(cacheKey: string, fn: () => Promise<T>): Promise<T> => {
- const cached = await keyStore.getItem(cacheKey);
- if (cached) return JSON.parse(cached) as T;
-
- const result = await fn();
- await keyStore.setItemWithExpiry(cacheKey, KeyStoreTtls.InsightsCacheInSeconds, JSON.stringify(result));
- return result;
- };
-
const fetchReminders = async (projectId: string, startDate: Date, endDate: Date) => {
const rawReminders = await reminderDAL.findByProjectAndDateRange({ projectId, startDate, endDate });
if (!rawReminders.length) return [];
@@ -123,35 +115,40 @@ export const insightsServiceFactory = ({
await checkInsightsPermission(permissionService, licenseService, dto.projectId, actorDto);
const cacheKey = KeyStorePrefixes.InsightsCache(dto.projectId, `calendar:${dto.year}-${dto.month}`);
- return withCache(cacheKey, async () => {
- const { shouldUseSecretV2Bridge } = await projectBotService.getBotKey(dto.projectId);
- if (!shouldUseSecretV2Bridge) throw new BadRequestError({ message: "Project version not supported" });
-
- // Pad by 1 day on each side so events near month boundaries are captured
- // regardless of the caller's timezone offset from UTC.
- const startDate = new Date(Date.UTC(dto.year, dto.month - 1, 0));
- const endDate = new Date(Date.UTC(dto.year, dto.month, 1, 23, 59, 59, 999));
-
- const [rotations, reminders] = await Promise.all([
- secretRotationV2DAL.findByProjectAndDateRange({ projectId: dto.projectId, startDate, endDate }),
- fetchReminders(dto.projectId, startDate, endDate)
- ]);
-
- return {
- rotations: rotations.map((r) => ({
- id: r.id,
- name: r.name,
- type: r.type,
- nextRotationAt: r.nextRotationAt ?? null,
- environment: r.environment.slug,
- secretPath: r.folder.path,
- secretKeys: r.secretKeys,
- rotationInterval: r.rotationInterval,
- rotationStatus: r.rotationStatus,
- isAutoRotationEnabled: r.isAutoRotationEnabled
- })),
- reminders
- };
+ return withCache({
+ keyStore,
+ key: cacheKey,
+ ttlSeconds: KeyStoreTtls.InsightsCacheInSeconds,
+ fetcher: async () => {
+ const { shouldUseSecretV2Bridge } = await projectBotService.getBotKey(dto.projectId);
+ if (!shouldUseSecretV2Bridge) throw new BadRequestError({ message: "Project version not supported" });
+
+ // Pad by 1 day on each side so events near month boundaries are captured
+ // regardless of the caller's timezone offset from UTC.
+ const startDate = new Date(Date.UTC(dto.year, dto.month - 1, 0));
+ const endDate = new Date(Date.UTC(dto.year, dto.month, 1, 23, 59, 59, 999));
+
+ const [rotations, reminders] = await Promise.all([
+ secretRotationV2DAL.findByProjectAndDateRange({ projectId: dto.projectId, startDate, endDate }),
+ fetchReminders(dto.projectId, startDate, endDate)
+ ]);
+
+ return {
+ rotations: rotations.map((r) => ({
+ id: r.id,
+ name: r.name,
+ type: r.type,
+ nextRotationAt: r.nextRotationAt ?? null,
+ environment: r.environment.slug,
+ secretPath: r.folder.path,
+ secretKeys: r.secretKeys,
+ rotationInterval: r.rotationInterval,
+ rotationStatus: r.rotationStatus,
+ isAutoRotationEnabled: r.isAutoRotationEnabled
+ })),
+ reminders
+ };
+ }
});
};
@@ -159,78 +156,83 @@ export const insightsServiceFactory = ({
await checkInsightsPermission(permissionService, licenseService, dto.projectId, actorDto);
const cacheKey = KeyStorePrefixes.InsightsCache(dto.projectId, "access-volume");
- return withCache(cacheKey, async () => {
- const now = new Date();
- const todayStr = now.toISOString().slice(0, 10);
- const endDate = new Date(`${todayStr}T23:59:59.999Z`);
- const startDate = new Date(`${todayStr}T00:00:00.000Z`);
- startDate.setUTCDate(startDate.getUTCDate() - 6);
-
- const rows = await auditLogDAL.countByDateAndActor({
- orgId: actorDto.orgId,
- projectId: dto.projectId,
- eventTypes: VALUE_EVENT_TYPES,
- startDate: startDate.toISOString(),
- endDate: endDate.toISOString()
- });
-
- // Resolve user display names from userIds in audit log metadata
- const userIds = [
- ...new Set(
- rows
- .filter((r) => r.actor === ActorType.USER)
- .map((r) => (r.actorMetadata as Record<string, string> | null)?.userId)
- .filter(Boolean) as string[]
- )
- ];
- const userNameMap = new Map<string, string>();
- if (userIds.length > 0) {
- const users = await userDAL.find({ $in: { id: userIds } });
- users.forEach((u) => {
- const displayName = [u.firstName, u.lastName].filter(Boolean).join(" ");
- if (displayName) userNameMap.set(u.id, displayName);
+ return withCache({
+ keyStore,
+ key: cacheKey,
+ ttlSeconds: KeyStoreTtls.InsightsCacheInSeconds,
+ fetcher: async () => {
+ const now = new Date();
+ const todayStr = now.toISOString().slice(0, 10);
+ const endDate = new Date(`${todayStr}T23:59:59.999Z`);
+ const startDate = new Date(`${todayStr}T00:00:00.000Z`);
+ startDate.setUTCDate(startDate.getUTCDate() - 6);
+
+ const rows = await auditLogDAL.countByDateAndActor({
+ orgId: actorDto.orgId,
+ projectId: dto.projectId,
+ eventTypes: VALUE_EVENT_TYPES,
+ startDate: startDate.toISOString(),
+ endDate: endDate.toISOString()
});
- }
-
- // Pre-populate the last 7 days
- const dayMap = new Map<string, Map<string, { name: string; type: string; count: number }>>();
- for (let i = 6; i >= 0; i -= 1) {
- const d = new Date(`${todayStr}T00:00:00.000Z`);
- d.setUTCDate(d.getUTCDate() - i);
- dayMap.set(d.toISOString().slice(0, 10), new Map());
- }
- rows.forEach((row) => {
- const dateKey = typeof row.date === "string" ? row.date : new Date(row.date).toISOString().slice(0, 10);
- const actorMap = dayMap.get(dateKey);
- if (!actorMap) return;
-
- const actorMeta = row.actorMetadata as Record<string, string> | null;
- let actorName: string;
- if (row.actor === ActorType.USER && actorMeta?.userId) {
- actorName = userNameMap.get(actorMeta.userId) || actorMeta.email || actorMeta.username || "Unknown";
- } else if (row.actor === ActorType.USER) {
- actorName = actorMeta?.email || actorMeta?.username || "Unknown";
- } else {
- actorName = actorMeta?.name || actorMeta?.identityId || "Unknown";
+ // Resolve user display names from userIds in audit log metadata
+ const userIds = [
+ ...new Set(
+ rows
+ .filter((r) => r.actor === ActorType.USER)
+ .map((r) => (r.actorMetadata as Record<string, string> | null)?.userId)
+ .filter(Boolean) as string[]
+ )
+ ];
+ const userNameMap = new Map<string, string>();
+ if (userIds.length > 0) {
+ const users = await userDAL.find({ $in: { id: userIds } });
+ users.forEach((u) => {
+ const displayName = [u.firstName, u.lastName].filter(Boolean).join(" ");
+ if (displayName) userNameMap.set(u.id, displayName);
+ });
}
- const actorKey = `${row.actor}:${actorName}`;
- const existing = actorMap.get(actorKey);
- if (existing) {
- existing.count += row.count;
- } else {
- actorMap.set(actorKey, { name: actorName, type: row.actor, count: row.count });
+ // Pre-populate the last 7 days
+ const dayMap = new Map<string, Map<string, { name: string; type: string; count: number }>>();
+ for (let i = 6; i >= 0; i -= 1) {
+ const d = new Date(`${todayStr}T00:00:00.000Z`);
+ d.setUTCDate(d.getUTCDate() - i);
+ dayMap.set(d.toISOString().slice(0, 10), new Map());
}
- });
- const days = Array.from(dayMap.entries()).map(([date, actorMap]) => {
- const actors = Array.from(actorMap.values()).sort((a, b) => b.count - a.count);
- const total = actors.reduce((sum, a) => sum + a.count, 0);
- return { date, total, actors };
- });
+ rows.forEach((row) => {
+ const dateKey = typeof row.date === "string" ? row.date : new Date(row.date).toISOString().slice(0, 10);
+ const actorMap = dayMap.get(dateKey);
+ if (!actorMap) return;
+
+ const actorMeta = row.actorMetadata as Record<string, string> | null;
+ let actorName: string;
+ if (row.actor === ActorType.USER && actorMeta?.userId) {
+ actorName = userNameMap.get(actorMeta.userId) || actorMeta.email || actorMeta.username || "Unknown";
+ } else if (row.actor === ActorType.USER) {
+ actorName = actorMeta?.email || actorMeta?.username || "Unknown";
+ } else {
+ actorName = actorMeta?.name || actorMeta?.identityId || "Unknown";
+ }
+ const actorKey = `${row.actor}:${actorName}`;
+
+ const existing = actorMap.get(actorKey);
+ if (existing) {
+ existing.count += row.count;
+ } else {
+ actorMap.set(actorKey, { name: actorName, type: row.actor, count: row.count });
+ }
+ });
+
+ const days = Array.from(dayMap.entries()).map(([date, actorMap]) => {
+ const actors = Array.from(actorMap.values()).sort((a, b) => b.count - a.count);
+ const total = actors.reduce((sum, a) => sum + a.count, 0);
+ return { date, total, actors };
+ });
- return { days };
+ return { days };
+ }
});
};
@@ -317,75 +319,80 @@ export const insightsServiceFactory = ({
await checkInsightsPermission(permissionService, licenseService, dto.projectId, actorDto);
const cacheKey = KeyStorePrefixes.InsightsCache(dto.projectId, `auth-methods:${dto.days}`);
- return withCache(cacheKey, async () => {
- const endDate = new Date();
- const startDate = new Date();
- startDate.setUTCDate(startDate.getUTCDate() - dto.days);
-
- const authRows = await auditLogDAL.countByAuthMethod({
- orgId: actorDto.orgId,
- projectId: dto.projectId,
- eventTypes: VALUE_EVENT_TYPES,
- startDate: startDate.toISOString(),
- endDate: endDate.toISOString()
- });
-
- const methodCounts = new Map<string, number>();
-
- const authMethodLabels: Record<string, string> = {
- email: "Email",
- google: "Google",
- github: "GitHub",
- gitlab: "GitLab",
- "okta-saml": "Okta SAML",
- "azure-saml": "Azure SAML",
- "jumpcloud-saml": "JumpCloud SAML",
- "google-saml": "Google SAML",
- "keycloak-saml": "Keycloak SAML",
- ldap: "LDAP",
- oidc: "OIDC"
- };
-
- const identityAuthMethodLabels: Record<IdentityAuthMethod, string> = {
- [IdentityAuthMethod.UNIVERSAL_AUTH]: "Universal Auth",
- [IdentityAuthMethod.TOKEN_AUTH]: "Token Auth",
- [IdentityAuthMethod.KUBERNETES_AUTH]: "Kubernetes",
- [IdentityAuthMethod.GCP_AUTH]: "GCP Auth",
- [IdentityAuthMethod.AWS_AUTH]: "AWS Auth",
- [IdentityAuthMethod.AZURE_AUTH]: "Azure Auth",
- [IdentityAuthMethod.OIDC_AUTH]: "OIDC",
- [IdentityAuthMethod.JWT_AUTH]: "JWT Auth",
- [IdentityAuthMethod.LDAP_AUTH]: "LDAP Auth",
- [IdentityAuthMethod.ALICLOUD_AUTH]: "AliCloud Auth",
- [IdentityAuthMethod.TLS_CERT_AUTH]: "TLS Certificate",
- [IdentityAuthMethod.OCI_AUTH]: "OCI Auth",
- [IdentityAuthMethod.SPIFFE_AUTH]: "SPIFFE Auth"
- };
-
- authRows.forEach((row) => {
- const actorMeta = row.actorMetadata as Record<string, unknown> | null;
- let method = "Unknown";
-
- if (row.actor === "user") {
- const raw = (actorMeta?.authMethod as string) || "Unknown";
- method = authMethodLabels[raw] || raw;
- } else if (row.actor === "identity") {
- const identityAuth = actorMeta?.authMethod as IdentityAuthMethod | undefined;
- method = identityAuth ? identityAuthMethodLabels[identityAuth] || identityAuth : "Unknown";
- } else if (row.actor === "service") {
- method = "Service Token";
- } else {
- method = row.actor;
- }
+ return withCache({
+ keyStore,
+ key: cacheKey,
+ ttlSeconds: KeyStoreTtls.InsightsCacheInSeconds,
+ fetcher: async () => {
+ const endDate = new Date();
+ const startDate = new Date();
+ startDate.setUTCDate(startDate.getUTCDate() - dto.days);
+
+ const authRows = await auditLogDAL.countByAuthMethod({
+ orgId: actorDto.orgId,
+ projectId: dto.projectId,
+ eventTypes: VALUE_EVENT_TYPES,
+ startDate: startDate.toISOString(),
+ endDate: endDate.toISOString()
+ });
- methodCounts.set(method, (methodCounts.get(method) || 0) + (row.count || 0));
- });
+ const methodCounts = new Map<string, number>();
+
+ const authMethodLabels: Record<string, string> = {
+ email: "Email",
+ google: "Google",
+ github: "GitHub",
+ gitlab: "GitLab",
+ "okta-saml": "Okta SAML",
+ "azure-saml": "Azure SAML",
+ "jumpcloud-saml": "JumpCloud SAML",
+ "google-saml": "Google SAML",
+ "keycloak-saml": "Keycloak SAML",
+ ldap: "LDAP",
+ oidc: "OIDC"
+ };
+
+ const identityAuthMethodLabels: Record<IdentityAuthMethod, string> = {
+ [IdentityAuthMethod.UNIVERSAL_AUTH]: "Universal Auth",
+ [IdentityAuthMethod.TOKEN_AUTH]: "Token Auth",
+ [IdentityAuthMethod.KUBERNETES_AUTH]: "Kubernetes",
+ [IdentityAuthMethod.GCP_AUTH]: "GCP Auth",
+ [IdentityAuthMethod.AWS_AUTH]: "AWS Auth",
+ [IdentityAuthMethod.AZURE_AUTH]: "Azure Auth",
+ [IdentityAuthMethod.OIDC_AUTH]: "OIDC",
+ [IdentityAuthMethod.JWT_AUTH]: "JWT Auth",
+ [IdentityAuthMethod.LDAP_AUTH]: "LDAP Auth",
+ [IdentityAuthMethod.ALICLOUD_AUTH]: "AliCloud Auth",
+ [IdentityAuthMethod.TLS_CERT_AUTH]: "TLS Certificate",
+ [IdentityAuthMethod.OCI_AUTH]: "OCI Auth",
+ [IdentityAuthMethod.SPIFFE_AUTH]: "SPIFFE Auth"
+ };
+
+ authRows.forEach((row) => {
+ const actorMeta = row.actorMetadata as Record<string, unknown> | null;
+ let method = "Unknown";
+
+ if (row.actor === "user") {
+ const raw = (actorMeta?.authMethod as string) || "Unknown";
+ method = authMethodLabels[raw] || raw;
+ } else if (row.actor === "identity") {
+ const identityAuth = actorMeta?.authMethod as IdentityAuthMethod | undefined;
+ method = identityAuth ? identityAuthMethodLabels[identityAuth] || identityAuth : "Unknown";
+ } else if (row.actor === "service") {
+ method = "Service Token";
+ } else {
+ method = row.actor;
+ }
+
+ methodCounts.set(method, (methodCounts.get(method) || 0) + (row.count || 0));
+ });
- const methods = Array.from(methodCounts.entries())
- .map(([method, count]) => ({ method, count }))
- .sort((a, b) => b.count - a.count);
+ const methods = Array.from(methodCounts.entries())
+ .map(([method, count]) => ({ method, count }))
+ .sort((a, b) => b.count - a.count);
- return { methods };
+ return { methods };
+ }
});
};
@@ -396,83 +403,88 @@ export const insightsServiceFactory = ({
dto.projectId,
`summary:${dto.staleSecretsOffset ?? 0}:${dto.staleSecretsLimit ?? 50}`
);
- return withCache(cacheKey, async () => {
- const { shouldUseSecretV2Bridge } = await projectBotService.getBotKey(dto.projectId);
- if (!shouldUseSecretV2Bridge) throw new BadRequestError({ message: "Project version not supported" });
-
- const now = new Date();
- const in7Days = new Date(now);
- in7Days.setDate(now.getDate() + 7);
- const lookback90Days = new Date(now);
- lookback90Days.setDate(now.getDate() - 90);
- const staleThreshold = lookback90Days;
-
- // Fetch upcoming rotations (by date range) and all failed rotations (no date filter) in parallel
- // Use 90-day lookback to capture overdue items without unbounded historical queries
- const [upcomingRotationsRaw, allProjectRotations, reminders] = await Promise.all([
- secretRotationV2DAL.findByProjectAndDateRange({
- projectId: dto.projectId,
- startDate: lookback90Days,
- endDate: in7Days
- }),
- secretRotationV2DAL.findByProject(dto.projectId),
- fetchReminders(dto.projectId, lookback90Days, in7Days)
- ]);
-
- const mapRotation = (r: (typeof allProjectRotations)[number]) => ({
- name: r.name,
- environment: r.environment.slug,
- secretPath: r.folder.path,
- nextRotationAt: r.nextRotationAt ?? null,
- rotationStatus: r.rotationStatus
- });
-
- const mapReminder = (r: (typeof reminders)[number]) => ({
- secretKey: r.secretKey,
- environment: r.environment,
- secretPath: r.secretPath,
- nextReminderDate: r.nextReminderDate
- });
-
- const upcomingRotations = upcomingRotationsRaw.map(mapRotation);
-
- const failedRotations = allProjectRotations.filter((r) => r.rotationStatus === "failed").map(mapRotation);
- const upcomingReminders = reminders.filter((r) => new Date(r.nextReminderDate) >= now).map(mapReminder);
- const overdueReminders = reminders.filter((r) => new Date(r.nextReminderDate) < now).map(mapReminder);
-
- const [rawStaleSecrets, totalStaleCount] = await Promise.all([
- secretV2BridgeDAL.findStaleByProject(dto.projectId, staleThreshold, {
- offset: dto.staleSecretsOffset ?? 0,
- limit: dto.staleSecretsLimit ?? 50
- }),
- secretV2BridgeDAL.countStaleByProject(dto.projectId, staleThreshold)
- ]);
-
- // Resolve folder paths for stale secrets
- const staleFolderIds = [...new Set(rawStaleSecrets.map((s) => s.folderId))];
- const staleFolders = staleFolderIds.length
- ? await folderDAL.findSecretPathByFolderIds(dto.projectId, staleFolderIds)
- : [];
- const staleFolderMap: Record<string, string> = {};
- staleFolders.forEach((f) => {
- if (f) staleFolderMap[f.id] = f.path;
- });
-
- const staleSecrets = rawStaleSecrets.map((s) => ({
- key: s.key,
- environment: s.environment,
- secretPath: staleFolderMap[s.folderId] ?? "/",
- updatedAt: s.updatedAt
- }));
-
- return {
- upcomingRotations,
- failedRotations,
- upcomingReminders,
- overdueReminders,
- staleSecrets,
- totalStaleCount
- };
+ return withCache({
+ keyStore,
+ key: cacheKey,
+ ttlSeconds: KeyStoreTtls.InsightsCacheInSeconds,
+ fetcher: async () => {
+ const { shouldUseSecretV2Bridge } = await projectBotService.getBotKey(dto.projectId);
+ if (!shouldUseSecretV2Bridge) throw new BadRequestError({ message: "Project version not supported" });
+
+ const now = new Date();
+ const in7Days = new Date(now);
+ in7Days.setDate(now.getDate() + 7);
+ const lookback90Days = new Date(now);
+ lookback90Days.setDate(now.getDate() - 90);
+ const staleThreshold = lookback90Days;
+
+ // Fetch upcoming rotations (by date range) and all failed rotations (no date filter) in parallel
+ // Use 90-day lookback to capture overdue items without unbounded historical queries
+ const [upcomingRotationsRaw, allProjectRotations, reminders] = await Promise.all([
+ secretRotationV2DAL.findByProjectAndDateRange({
+ projectId: dto.projectId,
+ startDate: lookback90Days,
+ endDate: in7Days
+ }),
+ secretRotationV2DAL.findByProject(dto.projectId),
+ fetchReminders(dto.projectId, lookback90Days, in7Days)
+ ]);
+
+ const mapRotation = (r: (typeof allProjectRotations)[number]) => ({
+ name: r.name,
+ environment: r.environment.slug,
+ secretPath: r.folder.path,
+ nextRotationAt: r.nextRotationAt ?? null,
+ rotationStatus: r.rotationStatus
+ });
+
+ const mapReminder = (r: (typeof reminders)[number]) => ({
+ secretKey: r.secretKey,
+ environment: r.environment,
+ secretPath: r.secretPath,
+ nextReminderDate: r.nextReminderDate
+ });
+
+ const upcomingRotations = upcomingRotationsRaw.map(mapRotation);
+
+ const failedRotations = allProjectRotations.filter((r) => r.rotationStatus === "failed").map(mapRotation);
+ const upcomingReminders = reminders.filter((r) => new Date(r.nextReminderDate) >= now).map(mapReminder);
+ const overdueReminders = reminders.filter((r) => new Date(r.nextReminderDate) < now).map(mapReminder);
+
+ const [rawStaleSecrets, totalStaleCount] = await Promise.all([
+ secretV2BridgeDAL.findStaleByProject(dto.projectId, staleThreshold, {
+ offset: dto.staleSecretsOffset ?? 0,
+ limit: dto.staleSecretsLimit ?? 50
+ }),
+ secretV2BridgeDAL.countStaleByProject(dto.projectId, staleThreshold)
+ ]);
+
+ // Resolve folder paths for stale secrets
+ const staleFolderIds = [...new Set(rawStaleSecrets.map((s) => s.folderId))];
+ const staleFolders = staleFolderIds.length
+ ? await folderDAL.findSecretPathByFolderIds(dto.projectId, staleFolderIds)
+ : [];
+ const staleFolderMap: Record<string, string> = {};
+ staleFolders.forEach((f) => {
+ if (f) staleFolderMap[f.id] = f.path;
+ });
+
+ const staleSecrets = rawStaleSecrets.map((s) => ({
+ key: s.key,
+ environment: s.environment,
+ secretPath: staleFolderMap[s.folderId] ?? "/",
+ updatedAt: s.updatedAt
+ }));
+
+ return {
+ upcomingRotations,
+ failedRotations,
+ upcomingReminders,
+ overdueReminders,
+ staleSecrets,
+ totalStaleCount
+ };
+ }
});
};