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
feat(insights): refresh control on the project duplicates card
Calvin8eb712a87949
diff --git a/backend/e2e-test/insights-secrets-duplication.spec.ts b/backend/e2e-test/insights-secrets-duplication.spec.tsindex eafa7279cd..e832873fc4 100644--- a/backend/e2e-test/insights-secrets-duplication.spec.ts+++ b/backend/e2e-test/insights-secrets-duplication.spec.ts@@ -21,9 +21,11 @@ import {OrgPermissionSet,OrgPermissionSubjects} from "@app/ee/services/permission/org-permission";+import { ProjectPermissionInsightsActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";import { ActorType, AuthMethod } from "@app/services/auth/auth-type";import { orgDALFactory } from "@app/services/org/org-dal";+import { projectDALFactory } from "@app/services/project/project-dal";import { secretFolderDALFactory } from "@app/services/secret-folder/secret-folder-dal";import { secretV2BridgeDALFactory } from "@app/services/secret-v2-bridge/secret-v2-bridge-dal";@@ -57,10 +59,26 @@ const insightsService = insightsServiceFactory({),memberships: [],hasRole: () => false+ }),+ getProjectPermission: async () => ({+ permission: createMongoAbility([+ { action: ProjectPermissionInsightsActions.Read, subject: ProjectPermissionSub.Insights }+ ])})- } as TInsightsServiceFactoryDep["permissionService"],+ } as unknown as TInsightsServiceFactoryDep["permissionService"],licenseService: gate.licenseService,orgDAL: { ...usageInsightsDepStubs.orgDAL, findById: orgDALFactory(testDb).findById },+ projectDAL: { findById: projectDALFactory(testDb).findById },+ // The project query builds its decryptor up front. No secret here carries an encrypted value, so+ // it is never invoked.+ kmsService: {+ createCipherPairWithDataKey: async () =>+ ({+ decryptor: () => {+ throw new Error("insights duplication spec: no secret carries an encrypted value to decrypt");+ }+ }) as never+ },folderDAL: {...projectScopedInsightsDepStubs.folderDAL,findSecretPathByFolderIds: secretFolderDALFactory(testDb).findSecretPathByFolderIds@@ -78,8 +96,7 @@ const orgActor = {orgId: ORG_ID};-// encryptedValue is left empty so the reference filter keeps every group without a KMS round trip,-// which is why the kmsService stub is never reached.+// encryptedValue is left empty so the reference filter keeps every group without a KMS round trip.const secret = (folderId: string, key: string, digest: string): TSecretsV2Insert & { id: string } => ({id: randomUUID(),key,@@ -88,8 +105,18 @@ const secret = (folderId: string, key: string, digest: string): TSecretsV2InsertsecretValueOrgBlindIndex: `org-${digest}`});+const projectActor = {+ type: ActorType.USER,+ id: USER_ID,+ authMethod: AuthMethod.EMAIL,+ orgId: ORG_ID,+ rootOrgId: ORG_ID,+ parentOrgId: ORG_ID+};+const clearCaches = async () => {await testKeyStore.deleteItem(KeyStorePrefixes.InsightsCache(ORG_ID, "org-secrets-duplication"));+ await testKeyStore.deleteItem(KeyStorePrefixes.InsightsCache(projects.here.projectId, "secrets-duplication"));};describe("insights secrets duplication", () => {@@ -225,4 +252,34 @@ describe("insights secrets duplication", () => {}});});++ describe("project scope", () => {+ const dto = { projectId: projects.here.projectId };++ test("reports when the answer was computed", async () => {+ const before = Date.now();+ const { result } = await insightsService.getSecretsDuplication({ ...dto, refresh: true }, projectActor);++ expect(result.computedAt).toEqual(expect.any(String));+ expect(new Date(result.computedAt as string).getTime()).toBeGreaterThanOrEqual(before - 1000);+ });++ test("answers from the cache until asked to refresh", async () => {+ await insightsService.getSecretsDuplication({ ...dto, refresh: true }, projectActor);++ const extra = secret(projects.here.folderId, "LATE_LOCAL", "local");+ await testDb(TableName.SecretV2).insert(extra);+ try {+ const localGroupSize = (r: Awaited<ReturnType<typeof insightsService.getSecretsDuplication>>) =>+ r.result.groups.find((g) => g.secrets.some((s) => s.key === "LOCAL_A"))?.secrets.length;++ expect(localGroupSize(await insightsService.getSecretsDuplication(dto, projectActor))).toBe(3);+ expect(+ localGroupSize(await insightsService.getSecretsDuplication({ ...dto, refresh: true }, projectActor))+ ).toBe(4);+ } finally {+ await testDb(TableName.SecretV2).where("id", extra.id).delete();+ }+ });+ });});diff --git a/backend/src/ee/routes/v1/insights-router.ts b/backend/src/ee/routes/v1/insights-router.tsindex d361f61878..50197ae195 100644--- a/backend/src/ee/routes/v1/insights-router.ts+++ b/backend/src/ee/routes/v1/insights-router.ts@@ -580,9 +580,21 @@ export const registerInsightsRouter = async (server: FastifyZodProvider) => {params: z.object({projectId: z.string().trim()}),+ querystring: z.object({+ refresh: z+ .enum(["true", "false"])+ .default("false")+ .transform((value) => value === "true")+ .describe("Recompute now instead of answering from the cached result.")+ }),response: {200: z.object({secretBlindIndexEnabled: z.boolean(),+ computedAt: z+ .string()+ .datetime()+ .nullable()+ .describe("When the groups were computed. Null when detection is not enabled."),groups: z.array(z.object({secrets: z.array(@@ -604,7 +616,7 @@ export const registerInsightsRouter = async (server: FastifyZodProvider) => {handler: async (req, reply) => {const { projectId } = req.params;const { result, remainingTTL } = await server.services.insights.getSecretsDuplication(- { projectId },+ { projectId, refresh: req.query.refresh },req.permission);await server.services.auditLog.createAuditLog({diff --git a/backend/src/ee/services/insights/insights-service.ts b/backend/src/ee/services/insights/insights-service.tsindex 8234cd76f8..1ac27374e9 100644--- a/backend/src/ee/services/insights/insights-service.ts+++ b/backend/src/ee/services/insights/insights-service.ts@@ -599,16 +599,20 @@ export const insightsServiceFactory = ({return {result: {secretBlindIndexEnabled: false,- groups: []+ groups: [],+ computedAt: null}};}+ if (dto.refresh) await keyStore.deleteItem(cacheKey);+const result = await withCache({keyStore,key: cacheKey,ttlSeconds: KeyStoreTtls.InsightsDuplicationCacheInSeconds,fetcher: async () => {+ const computedAt = new Date().toISOString();const rawGroups = await secretV2BridgeDAL.findDuplicatedSecretValues(dto.projectId);const { decryptor: secretManagerDecryptor } = await kmsService.createCipherPairWithDataKey({@@ -644,13 +648,14 @@ export const insightsServiceFactory = ({}))}));- return { secretBlindIndexEnabled: true as const, groups };+ return { secretBlindIndexEnabled: true as const, groups, computedAt };}});const remainingTTL = await getCacheTtl(keyStore, cacheKey);- return { result, remainingTTL };+ // An entry cached before computedAt existed lacks it until it expires.+ return { result: { ...result, computedAt: result.computedAt ?? null }, remainingTTL };};const getCounts = async (dto: TGetInsightsCountsDTO, actorDto: OrgServiceActor) => {diff --git a/backend/src/ee/services/insights/insights-types.ts b/backend/src/ee/services/insights/insights-types.tsindex 06ac2deddf..4ec162e9e3 100644--- a/backend/src/ee/services/insights/insights-types.ts+++ b/backend/src/ee/services/insights/insights-types.ts@@ -36,6 +36,7 @@ export type TGetInsightsSummaryDTO = {export type TGetSecretsDuplicationDTO = {projectId: string;+ refresh?: boolean;};export type TGetInsightsCountsDTO = {diff --git a/frontend/src/components/secrets/CheckedAtButton.tsx b/frontend/src/components/secrets/CheckedAtButton.tsxnew file mode 100644index 0000000000..08a4e28eae--- /dev/null+++ b/frontend/src/components/secrets/CheckedAtButton.tsx@@ -0,0 +1,49 @@+import { useEffect, useState } from "react";+import { formatDistanceToNow } from "date-fns";+import { RefreshCwIcon } from "lucide-react";++import { Badge } from "@app/components/v3";+import { cn } from "@app/components/v3/utils";++// Keeps "Checked N minutes ago" honest while the page sits open.+const useNow = (intervalMs: number) => {+ const [now, setNow] = useState(() => Date.now());+ useEffect(() => {+ const id = setInterval(() => setNow(Date.now()), intervalMs);+ return () => clearInterval(id);+ }, [intervalMs]);+ return now;+};++// Says how fresh a cached answer is and recomputes it on click, for cards whose result the server+// caches and nothing invalidates when the underlying data changes.+export const CheckedAtButton = ({+ computedAt,+ isRefreshing,+ onRefresh+}: {+ computedAt: string;+ isRefreshing: boolean;+ onRefresh: () => void;+}) => {+ const now = useNow(30_000);+ const computed = new Date(computedAt);+ const label =+ now - computed.getTime() < 60_000+ ? "Checked just now"+ : `Checked ${formatDistanceToNow(computed, { addSuffix: true })}`;++ return (+ <Badge variant="neutral" asChild className="ml-2 font-normal">+ <button+ type="button"+ onClick={onRefresh}+ disabled={isRefreshing}+ aria-label={`${label}. Check again`}+ >+ <RefreshCwIcon className={cn(isRefreshing && "animate-spin")} />+ {isRefreshing ? "Checking..." : label}+ </button>+ </Badge>+ );+};diff --git a/frontend/src/hooks/api/secretInsights/index.ts b/frontend/src/hooks/api/secretInsights/index.tsindex f2e76e8450..bd43561e88 100644--- a/frontend/src/hooks/api/secretInsights/index.ts+++ b/frontend/src/hooks/api/secretInsights/index.ts@@ -1,6 +1,7 @@export {useEnableOrgSecretValueTracking,useRefreshOrgSecretsDuplication,+ useRefreshSecretsDuplication,useSearchSecretsByValue} from "./mutations";export {diff --git a/frontend/src/hooks/api/secretInsights/mutations.tsx b/frontend/src/hooks/api/secretInsights/mutations.tsxindex 9a085c784f..cd44f6cc9f 100644--- a/frontend/src/hooks/api/secretInsights/mutations.tsx+++ b/frontend/src/hooks/api/secretInsights/mutations.tsx@@ -2,7 +2,7 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";import { apiRequest } from "@app/config/request";-import { fetchOrgSecretsDuplication, secretInsightsKeys } from "./queries";+import { fetchOrgSecretsDuplication, fetchSecretsDuplication, secretInsightsKeys } from "./queries";import { TSearchSecretsByValueResponse } from "./types";export const useEnableOrgSecretValueTracking = () => {@@ -24,6 +24,17 @@ export const useEnableOrgSecretValueTracking = () => {// Recomputes on the server rather than refetching, since a plain refetch answers from the// server's cache and would report the same stale result.+export const useRefreshSecretsDuplication = () => {+ const queryClient = useQueryClient();+ return useMutation<unknown, object, { projectId: string }>({+ mutationFn: async ({ projectId }) => {+ const data = await fetchSecretsDuplication(projectId, true);+ queryClient.setQueryData(secretInsightsKeys.secretsDuplication({ projectId }), data);+ return data;+ }+ });+};+export const useRefreshOrgSecretsDuplication = () => {const queryClient = useQueryClient();return useMutation<unknown, object, { orgId: string }>({diff --git a/frontend/src/hooks/api/secretInsights/queries.tsx b/frontend/src/hooks/api/secretInsights/queries.tsxindex 5bd835d606..9ffb26f4c7 100644--- a/frontend/src/hooks/api/secretInsights/queries.tsx+++ b/frontend/src/hooks/api/secretInsights/queries.tsx@@ -198,6 +198,14 @@ export const useGetInsightsCounts = (});};+export const fetchSecretsDuplication = async (projectId: string, refresh = false) => {+ const { data } = await apiRequest.get<TGetSecretsDuplicationResponse>(+ `/api/v1/insights/${projectId}/secrets/secrets-duplication`,+ { params: { refresh } }+ );+ return data;+};+export const useGetSecretsDuplication = (params: TGetSecretsDuplicationDTO,options?: Omit<@@ -212,13 +220,7 @@ export const useGetSecretsDuplication = () => {return useQuery({queryKey: secretInsightsKeys.secretsDuplication(params),- queryFn: async () => {- const res = await apiRequest.get<TGetSecretsDuplicationResponse>(- `/api/v1/insights/${params.projectId}/secrets/secrets-duplication`- );- const remainingTtl = Number(res.headers["x-cache-ttl"] ?? -1);- return { ...res.data, remainingTtl };- },+ queryFn: () => fetchSecretsDuplication(params.projectId),staleTime: INSIGHTS_STALE_TIME,...options});diff --git a/frontend/src/hooks/api/secretInsights/types.ts b/frontend/src/hooks/api/secretInsights/types.tsindex ac97eae876..06c563ad7f 100644--- a/frontend/src/hooks/api/secretInsights/types.ts+++ b/frontend/src/hooks/api/secretInsights/types.ts@@ -143,7 +143,8 @@ export type TDuplicatedSecretGroup = {export type TGetSecretsDuplicationResponse = {secretBlindIndexEnabled: boolean;groups: TDuplicatedSecretGroup[];- remainingTtl: number;+ // null when detection is not enabled, so nothing was computed+ computedAt: string | null;};export type TGetSecretBlindIndexStatusDTO = {diff --git a/frontend/src/pages/organization/SecretInsightsPage/components/DuplicatedSecretsCard.tsx b/frontend/src/pages/organization/SecretInsightsPage/components/DuplicatedSecretsCard.tsxindex b7669e41ef..cd1910d307 100644--- a/frontend/src/pages/organization/SecretInsightsPage/components/DuplicatedSecretsCard.tsx+++ b/frontend/src/pages/organization/SecretInsightsPage/components/DuplicatedSecretsCard.tsx@@ -1,14 +1,12 @@-import { useEffect, useState } from "react";import { useQueryClient } from "@tanstack/react-query";-import { formatDistanceToNow } from "date-fns";-import { AlertTriangleIcon, LockIcon, RefreshCwIcon } from "lucide-react";+import { AlertTriangleIcon, LockIcon } from "lucide-react";+import { CheckedAtButton } from "@app/components/secrets/CheckedAtButton";import {SecretValueTrackingPrompt,useOrgSecretValueTracking} from "@app/components/secrets/SecretValueTrackingGate";import {- Badge,Card,CardContent,CardDescription,@@ -21,7 +19,6 @@ import {EmptyTitle,Skeleton} from "@app/components/v3";-import { cn } from "@app/components/v3/utils";import { OrgPermissionSubjects, useOrganization, useOrgPermission } from "@app/context";import { OrgPermissionSecretsManagementInsightsActions } from "@app/context/OrgPermissionContext/types";import {@@ -32,47 +29,6 @@ import {import { DuplicateGroupList } from "./DuplicateGroupList";-// Keeps "Checked N minutes ago" honest while the page sits open.-const useNow = (intervalMs: number) => {- const [now, setNow] = useState(() => Date.now());- useEffect(() => {- const id = setInterval(() => setNow(Date.now()), intervalMs);- return () => clearInterval(id);- }, [intervalMs]);- return now;-};--const CheckedAtButton = ({- computedAt,- isRefreshing,- onRefresh-}: {- computedAt: string;- isRefreshing: boolean;- onRefresh: () => void;-}) => {- const now = useNow(30_000);- const computed = new Date(computedAt);- const label =- now - computed.getTime() < 60_000- ? "Checked just now"- : `Checked ${formatDistanceToNow(computed, { addSuffix: true })}`;-- return (- <Badge variant="neutral" asChild className="ml-2 font-normal">- <button- type="button"- onClick={onRefresh}- disabled={isRefreshing}- aria-label={`${label}. Check again`}- >- <RefreshCwIcon className={cn(isRefreshing && "animate-spin")} />- {isRefreshing ? "Checking..." : label}- </button>- </Badge>- );-};-type Props = {isPlanRestricted: boolean;};diff --git a/frontend/src/pages/secret-manager/InsightsPage/components/DuplicatedSecretsCard.tsx b/frontend/src/pages/secret-manager/InsightsPage/components/DuplicatedSecretsCard.tsxindex 50db7a499d..21d7504e2d 100644--- a/frontend/src/pages/secret-manager/InsightsPage/components/DuplicatedSecretsCard.tsx+++ b/frontend/src/pages/secret-manager/InsightsPage/components/DuplicatedSecretsCard.tsx@@ -11,6 +11,7 @@ import {LockIcon} from "lucide-react";+import { CheckedAtButton } from "@app/components/secrets/CheckedAtButton";import {Accordion,AccordionContent,@@ -46,7 +47,8 @@ import { useEnableSecretBlindIndex } from "@app/hooks/api/projects";import {secretInsightsKeys,useGetSecretBlindIndexStatus,- useGetSecretsDuplication+ useGetSecretsDuplication,+ useRefreshSecretsDuplication} from "@app/hooks/api/secretInsights";const overviewRoute =@@ -60,6 +62,7 @@ export const DuplicatedSecretsCard = () => {const [migrationTriggered, setMigrationTriggered] = useState(false);const enableBlindIndex = useEnableSecretBlindIndex();+ const refreshDuplicates = useRefreshSecretsDuplication();const { data, isPending } = useGetSecretsDuplication({ projectId }, { enabled: !!projectId });@@ -131,11 +134,6 @@ export const DuplicatedSecretsCard = () => {);};- const remainingMinutes =- data?.remainingTtl != null && data.remainingTtl >= 0- ? Math.max(1, Math.ceil(data.remainingTtl / 60))- : null;-const isMigrationRunning = migrationTriggered && migrationStatus !== "failed";const isMigrationFailed = migrationStatus === "failed" && !enableBlindIndex.isPending;const showEnableButton = !secretBlindIndexEnabled && !isMigrationRunning && !isMigrationFailed;@@ -145,10 +143,12 @@ export const DuplicatedSecretsCard = () => {<CardHeader><CardTitle>Duplicated Secrets- {remainingMinutes != null && (- <Badge variant="neutral" className="ml-2 font-normal">- Updates in {remainingMinutes} {remainingMinutes === 1 ? "minute" : "minutes"}- </Badge>+ {data?.computedAt && (+ <CheckedAtButton+ computedAt={data.computedAt}+ isRefreshing={refreshDuplicates.isPending}+ onRefresh={() => refreshDuplicates.mutate({ projectId })}+ />)}</CardTitle><CardDescription>