Skip to content

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

feat(insights): org-wide duplicates card and search by secret value

Calvin2aa9f7b0664b
diff --git a/frontend/src/components/secrets/SecretValueSearchSheet.tsx b/frontend/src/components/secrets/SecretValueSearchSheet.tsx
new file mode 100644
index 0000000000..be83ff98fa
--- /dev/null
+++ b/frontend/src/components/secrets/SecretValueSearchSheet.tsx
@@ -0,0 +1,241 @@
+import { FormEvent, useState } from "react";
+import { useNavigate } from "@tanstack/react-router";
+import { ArrowRightIcon, EyeIcon, EyeOffIcon, FolderIcon, KeyIcon } from "lucide-react";
+
+import {
+ Badge,
+ Button,
+ Empty,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyTitle,
+ IconButton,
+ ProjectIcon,
+ SecretInput,
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetHeader,
+ SheetTitle,
+ Skeleton,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger
+} from "@app/components/v3";
+import { useSearchSecretsByValue } from "@app/hooks/api/secretInsights";
+
+import { SecretValueTrackingPrompt, useOrgSecretValueTracking } from "./SecretValueTrackingGate";
+
+// Mirrors SECRET_VALUE_SEARCH_LIMIT on the server, which truncates without saying so.
+const SEARCH_RESULT_LIMIT = 1000;
+
+const overviewRoute =
+ "/organizations/$orgId/projects/secret-management/$projectId/overview" as const;
+
+type Props = {
+ orgId: string;
+ isOpen: boolean;
+ onOpenChange: (isOpen: boolean) => void;
+};
+
+const SearchContent = ({ orgId, onClose }: { orgId: string; onClose: () => void }) => {
+ const navigate = useNavigate();
+ const [value, setValue] = useState("");
+ const [isRevealed, setIsRevealed] = useState(false);
+ const search = useSearchSecretsByValue();
+
+ const tracking = useOrgSecretValueTracking({ orgId, enabled: true });
+
+ if (!tracking.isTrackingOn) {
+ return (
+ <div className="p-4">
+ <SecretValueTrackingPrompt
+ tracking={tracking}
+ description="Searching by value needs every secret in the organization indexed once. Infisical then keeps the index current as secrets change, and secrets stay readable while it runs."
+ />
+ </div>
+ );
+ }
+
+ // Each search is an audited event, so it runs on submit rather than on every keystroke.
+ const handleSubmit = (event: FormEvent) => {
+ event.preventDefault();
+ if (!value) return;
+ search.mutate({ secretValue: value });
+ };
+
+ const matches = search.data?.secrets ?? [];
+
+ const renderResults = () => {
+ if (search.isPending) return <Skeleton className="h-[240px] w-full" />;
+
+ if (!search.data) {
+ return (
+ <Empty className="bg-transparent shadow-none">
+ <EmptyHeader>
+ <EmptyTitle>Enter a secret value to find where it is used</EmptyTitle>
+ <EmptyDescription>
+ Results cover every project in the organization, including ones you are not a member
+ of.
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ );
+ }
+
+ if (matches.length === 0) {
+ return (
+ <Empty className="bg-transparent shadow-none">
+ <EmptyHeader>
+ <EmptyTitle>No secret in the organization holds this value</EmptyTitle>
+ <EmptyDescription>Personal overrides are not searched.</EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ );
+ }
+
+ return (
+ <div className="flex min-h-0 flex-1 flex-col gap-2">
+ <p className="text-sm text-muted">
+ {matches.length >= SEARCH_RESULT_LIMIT
+ ? `Showing the first ${SEARCH_RESULT_LIMIT} matches`
+ : `${matches.length} ${matches.length === 1 ? "secret holds" : "secrets hold"} this value`}
+ </p>
+ <div className="min-h-0 flex-1 overflow-y-auto">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="w-[24%]">Project</TableHead>
+ <TableHead className="w-[28%]">Secret Key</TableHead>
+ <TableHead className="w-[18%]">Environment</TableHead>
+ <TableHead>Path</TableHead>
+ <TableHead variant="action" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {matches.map((match, idx) => (
+ <TableRow
+ key={`${match.projectId}-${match.key}-${match.environment.slug}-${match.secretPath}-${String(idx)}`}
+ className="group/row"
+ >
+ <TableCell isTruncatable className="max-w-48">
+ <div className="flex items-center gap-2">
+ <ProjectIcon className="size-3.5 shrink-0 text-muted" />
+ <span className="truncate">{match.projectName}</span>
+ </div>
+ </TableCell>
+ <TableCell isTruncatable className="max-w-60">
+ <div className="flex items-center gap-2">
+ <KeyIcon className="size-4 shrink-0 text-muted" />
+ <span className="truncate font-mono">{match.key}</span>
+ </div>
+ </TableCell>
+ <TableCell>
+ <Badge variant="info" isTruncatable className="max-w-full">
+ <span>{match.environment.name}</span>
+ </Badge>
+ </TableCell>
+ <TableCell>
+ <div className="flex items-center gap-2">
+ <FolderIcon className="size-3.5 shrink-0 text-folder" />
+ <span className="truncate">{match.secretPath}</span>
+ </div>
+ </TableCell>
+ <TableCell variant="action">
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <IconButton
+ variant="ghost"
+ size="sm"
+ aria-label="Go to secret folder"
+ className="opacity-0 transition-opacity group-hover/row:opacity-100 focus-visible:opacity-100"
+ onClick={() => {
+ onClose();
+ navigate({
+ to: overviewRoute,
+ params: { orgId, projectId: match.projectId },
+ search: {
+ secretPath: match.secretPath,
+ environments: [match.environment.slug]
+ }
+ });
+ }}
+ >
+ <ArrowRightIcon className="size-3.5" />
+ </IconButton>
+ </TooltipTrigger>
+ <TooltipContent>Go to secret folder</TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </div>
+ </div>
+ );
+ };
+
+ return (
+ <div className="flex min-h-0 flex-1 flex-col gap-4 p-4 pb-6">
+ <form className="flex gap-2" onSubmit={handleSubmit}>
+ <div className="flex flex-1 items-center gap-2">
+ {/* SecretInput rather than a password field: it is a masked textarea, so password
+ managers do not offer to save what is pasted into it. */}
+ <SecretInput
+ autoFocus
+ valueAlwaysHidden
+ isVisible={isRevealed}
+ containerClassName="flex-1"
+ placeholder="Paste a secret value..."
+ value={value}
+ onChange={(e) => setValue(e.target.value)}
+ onKeyDown={(e) => {
+ // A textarea would otherwise take Enter as a newline rather than a search.
+ if (e.key === "Enter" && !e.shiftKey) {
+ e.preventDefault();
+ e.currentTarget.form?.requestSubmit();
+ }
+ }}
+ />
+ <IconButton
+ type="button"
+ variant="outline"
+ aria-label={isRevealed ? "Hide value" : "Show value"}
+ onClick={() => setIsRevealed((prev) => !prev)}
+ >
+ {isRevealed ? <EyeOffIcon /> : <EyeIcon />}
+ </IconButton>
+ </div>
+ <Button type="submit" variant="org" isDisabled={!value} isPending={search.isPending}>
+ Search
+ </Button>
+ </form>
+ {renderResults()}
+ </div>
+ );
+};
+
+export const SecretValueSearchSheet = ({ orgId, isOpen, onOpenChange }: Props) => (
+ <Sheet open={isOpen} onOpenChange={onOpenChange}>
+ <SheetContent className="flex flex-col overflow-hidden sm:max-w-7xl">
+ <SheetHeader>
+ <SheetTitle>Search by Secret Value</SheetTitle>
+ <SheetDescription>
+ Find every project, environment and path where a secret value is used.
+ </SheetDescription>
+ </SheetHeader>
+ {/* Mounted only while open, so the value and results are dropped the moment it closes. */}
+ {isOpen && <SearchContent orgId={orgId} onClose={() => onOpenChange(false)} />}
+ </SheetContent>
+ </Sheet>
+);
diff --git a/frontend/src/components/secrets/SecretValueTrackingGate.tsx b/frontend/src/components/secrets/SecretValueTrackingGate.tsx
new file mode 100644
index 0000000000..0956f42b00
--- /dev/null
+++ b/frontend/src/components/secrets/SecretValueTrackingGate.tsx
@@ -0,0 +1,141 @@
+import { useEffect, useRef, useState } from "react";
+import { AlertTriangleIcon, Loader2Icon } from "lucide-react";
+
+import {
+ Button,
+ Empty,
+ EmptyContent,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyTitle,
+ Skeleton
+} from "@app/components/v3";
+import {
+ TGetOrgSecretValueTrackingStatusResponse,
+ useEnableOrgSecretValueTracking,
+ useGetOrgSecretValueTrackingStatus
+} from "@app/hooks/api/secretInsights";
+
+type TOrgSecretValueTracking = {
+ isLoading: boolean;
+ isTrackingOn: boolean;
+ status?: TGetOrgSecretValueTrackingStatusResponse;
+ isRunStarting: boolean;
+ isEnablePending: boolean;
+ enable: () => void;
+};
+
+// Everything that searches by value (org duplicates, search by secret value) needs the org index
+// finished first, so they share one way of asking for it and of showing the run.
+export const useOrgSecretValueTracking = ({
+ orgId,
+ enabled,
+ onTrackingOn
+}: {
+ orgId: string;
+ enabled: boolean;
+ onTrackingOn?: () => void;
+}): TOrgSecretValueTracking => {
+ const enableTracking = useEnableOrgSecretValueTracking();
+ const {
+ data: status,
+ isPending,
+ dataUpdatedAt
+ } = useGetOrgSecretValueTrackingStatus(orgId, { enabled });
+
+ // Only a run this view started or saw in flight should report completion: a completed status
+ // seen on first load is simply "already on". Keyed on the fetch time because a small org can go
+ // from enable to completed before the first poll, so the status value alone may never change.
+ const [awaitingRun, setAwaitingRun] = useState(false);
+ const onTrackingOnRef = useRef(onTrackingOn);
+ onTrackingOnRef.current = onTrackingOn;
+ useEffect(() => {
+ if (status?.status === "pending") setAwaitingRun(true);
+ if (status?.status === "failed") setAwaitingRun(false);
+ if (status?.status === "completed" && awaitingRun) {
+ setAwaitingRun(false);
+ onTrackingOnRef.current?.();
+ }
+ }, [status?.status, dataUpdatedAt, awaitingRun]);
+
+ const enable = () => {
+ enableTracking.reset();
+ enableTracking.mutate(
+ { orgId },
+ {
+ onSuccess: () => setAwaitingRun(true)
+ }
+ );
+ };
+
+ return {
+ isLoading: enabled && isPending,
+ // The status route reports completed whenever the org flag is set, so this is the durable answer.
+ isTrackingOn: status?.status === "completed" && !awaitingRun,
+ status,
+ isRunStarting: enableTracking.isPending || (enableTracking.isSuccess && awaitingRun),
+ isEnablePending: enableTracking.isPending,
+ enable
+ };
+};
+
+// Renders whatever stands between the caller and a finished index. Callers render their own
+// content once `tracking.isTrackingOn` is true.
+export const SecretValueTrackingPrompt = ({
+ tracking,
+ description
+}: {
+ tracking: TOrgSecretValueTracking;
+ description: string;
+}) => {
+ const { status, isLoading, isRunStarting, isEnablePending, enable } = tracking;
+
+ if (isLoading) return <Skeleton className="h-[200px] w-full" />;
+
+ if (status?.status === "failed" && !isEnablePending) {
+ return (
+ <div className="flex h-[200px] flex-col items-center justify-center gap-3">
+ <AlertTriangleIcon className="size-6 text-danger" />
+ <p className="text-sm text-danger">
+ Failed to index secrets: {status.message ?? "Unknown error"}
+ </p>
+ <Button variant="outline" onClick={enable}>
+ Retry
+ </Button>
+ </div>
+ );
+ }
+
+ if (status?.status === "pending" || isRunStarting) {
+ return (
+ <div className="flex h-[200px] flex-col items-center justify-center gap-3 text-center">
+ <Loader2Icon className="size-6 animate-spin text-org" />
+ <p className="text-sm text-foreground">
+ {status?.projectsTotal
+ ? `Indexed ${status.projectsDone} of ${status.projectsTotal} projects`
+ : "Starting to index secrets"}
+ </p>
+ <p className="max-w-md text-sm text-muted">
+ {status?.secretsProcessed
+ ? `${status.secretsProcessed.toLocaleString()} secrets checked so far. `
+ : ""}
+ You can leave this page. Indexing keeps going, and this is ready when it finishes.
+ </p>
+ </div>
+ );
+ }
+
+ return (
+ <Empty className="border">
+ <EmptyHeader>
+ <EmptyTitle>Secret value indexing is not turned on</EmptyTitle>
+ <EmptyDescription>{description}</EmptyDescription>
+ <EmptyContent>
+ <Button variant="org" size="xs" onClick={enable}>
+ Turn On Indexing
+ </Button>
+ </EmptyContent>
+ </EmptyHeader>
+ </Empty>
+ );
+};
diff --git a/frontend/src/context/OrgPermissionContext/types.ts b/frontend/src/context/OrgPermissionContext/types.ts
index de0b262d96..bef69e0381 100644
--- a/frontend/src/context/OrgPermissionContext/types.ts
+++ b/frontend/src/context/OrgPermissionContext/types.ts
@@ -119,7 +119,8 @@ export enum OrgPermissionHoneyTokenActions {
export enum OrgPermissionSecretsManagementInsightsActions {
Read = "read",
GenerateReport = "generate-report",
- DeleteReport = "delete-report"
+ DeleteReport = "delete-report",
+ SearchAllSecretValues = "search-all-secret-values"
}
export enum OrgPermissionProjectActions {
diff --git a/frontend/src/hooks/api/secretInsights/index.ts b/frontend/src/hooks/api/secretInsights/index.ts
index 507f35c9e5..f2e76e8450 100644
--- a/frontend/src/hooks/api/secretInsights/index.ts
+++ b/frontend/src/hooks/api/secretInsights/index.ts
@@ -1,3 +1,8 @@
+export {
+ useEnableOrgSecretValueTracking,
+ useRefreshOrgSecretsDuplication,
+ useSearchSecretsByValue
+} from "./mutations";
export {
secretInsightsKeys,
useGetAuthMethodDistribution,
@@ -5,8 +10,10 @@ export {
useGetInsightsSummary,
useGetOrgAuthMethodDistribution,
useGetOrgSecretsAccessVolume,
+ useGetOrgSecretsDuplication,
useGetOrgSecretsProjects,
useGetOrgSecretsSummary,
+ useGetOrgSecretValueTrackingStatus,
useGetOrgStaticSecretsUsage,
// useGetSecretAccessLocations,
useGetSecretAccessVolume,
@@ -24,7 +31,9 @@ export type {
TGetAuthMethodDistributionResponse,
TGetCalendarInsightsDTO,
TGetCalendarInsightsResponse,
+ TGetOrgSecretsDuplicationResponse,
TGetOrgSecretsProjectsDTO,
+ TGetOrgSecretValueTrackingStatusResponse,
TGetSecretAccessLocationsDTO,
TGetSecretAccessLocationsResponse,
TGetSecretAccessVolumeDTO,
@@ -32,12 +41,16 @@ export type {
TGetSecretsDuplicationDTO,
TGetSecretsDuplicationResponse,
TOrgAuthMethodUsage,
+ TOrgDuplicatedSecretEntry,
+ TOrgDuplicatedSecretGroup,
TOrgProjectInsight,
TOrgProjectInsightWarnings,
TOrgProjectsInsights,
TOrgSecretAccessVolume,
TOrgSecretsSummary,
TOrgStaticSecretUsage,
+ TSearchSecretsByValueResponse,
TSecretAccessVolumeActor,
- TSecretAccessVolumeDay
+ TSecretAccessVolumeDay,
+ TSecretValueMatch
} from "./types";
diff --git a/frontend/src/hooks/api/secretInsights/mutations.tsx b/frontend/src/hooks/api/secretInsights/mutations.tsx
new file mode 100644
index 0000000000..9a085c784f
--- /dev/null
+++ b/frontend/src/hooks/api/secretInsights/mutations.tsx
@@ -0,0 +1,48 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+
+import { apiRequest } from "@app/config/request";
+
+import { fetchOrgSecretsDuplication, secretInsightsKeys } from "./queries";
+import { TSearchSecretsByValueResponse } from "./types";
+
+export const useEnableOrgSecretValueTracking = () => {
+ const queryClient = useQueryClient();
+ return useMutation<{ message: string }, object, { orgId: string }>({
+ mutationFn: async () => {
+ const { data } = await apiRequest.post<{ message: string }>(
+ "/api/v1/organization/secret-value-tracking"
+ );
+ return data;
+ },
+ onSuccess: (_, { orgId }) => {
+ queryClient.invalidateQueries({
+ queryKey: secretInsightsKeys.orgSecretValueTrackingStatus(orgId)
+ });
+ }
+ });
+};
+
+// 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 useRefreshOrgSecretsDuplication = () => {
+ const queryClient = useQueryClient();
+ return useMutation<unknown, object, { orgId: string }>({
+ mutationFn: async ({ orgId }) => {
+ const data = await fetchOrgSecretsDuplication(true);
+ queryClient.setQueryData(secretInsightsKeys.orgSecretsDuplication(orgId), data);
+ return data;
+ }
+ });
+};
+
+// A mutation rather than a query so the value never becomes part of a cache key.
+export const useSearchSecretsByValue = () =>
+ useMutation<TSearchSecretsByValueResponse, object, { secretValue: string }>({
+ mutationFn: async ({ secretValue }) => {
+ const { data } = await apiRequest.post<TSearchSecretsByValueResponse>(
+ "/api/v4/secrets/search-by-value",
+ { secretValue, scope: "organization" }
+ );
+ return data;
+ }
+ });
diff --git a/frontend/src/hooks/api/secretInsights/queries.tsx b/frontend/src/hooks/api/secretInsights/queries.tsx
index 58b76afe07..5bd835d606 100644
--- a/frontend/src/hooks/api/secretInsights/queries.tsx
+++ b/frontend/src/hooks/api/secretInsights/queries.tsx
@@ -11,7 +11,9 @@ import {
TGetInsightsCountsResponse,
TGetInsightsSummaryDTO,
TGetInsightsSummaryResponse,
+ TGetOrgSecretsDuplicationResponse,
TGetOrgSecretsProjectsDTO,
+ TGetOrgSecretValueTrackingStatusResponse,
// TGetSecretAccessLocationsDTO,
// TGetSecretAccessLocationsResponse,
TGetSecretAccessVolumeDTO,
@@ -56,7 +58,11 @@ export const secretInsightsKeys = {
orgStaticSecretsUsage: (orgId: string) =>
[...secretInsightsKeys.all(), "org-static-secrets-usage", { orgId }] as const,
orgAccessVolume: (orgId: string) =>
- [...secretInsightsKeys.all(), "org-access-volume", { orgId }] as const
+ [...secretInsightsKeys.all(), "org-access-volume", { orgId }] as const,
+ orgSecretsDuplication: (orgId: string) =>
+ [...secretInsightsKeys.all(), "org-secrets-duplication", { orgId }] as const,
+ orgSecretValueTrackingStatus: (orgId: string) =>
+ [...secretInsightsKeys.all(), "org-secret-value-tracking-status", { orgId }] as const
};
const INSIGHTS_STALE_TIME = 5 * 60 * 1000; // 5 minutes
@@ -326,3 +332,38 @@ export const useGetOrgSecretsAccessVolume = (orgId: string, options?: { enabled?
staleTime: INSIGHTS_STALE_TIME
});
};
+
+export const fetchOrgSecretsDuplication = async (refresh = false) => {
+ const { data } = await apiRequest.get<TGetOrgSecretsDuplicationResponse>(
+ "/api/v1/insights/secrets/secrets-duplication",
+ { params: { refresh } }
+ );
+ return data;
+};
+
+export const useGetOrgSecretsDuplication = (orgId: string, options?: { enabled?: boolean }) => {
+ return useQuery({
+ queryKey: secretInsightsKeys.orgSecretsDuplication(orgId),
+ queryFn: () => fetchOrgSecretsDuplication(),
+ enabled: Boolean(orgId) && (options?.enabled ?? true),
+ staleTime: INSIGHTS_STALE_TIME
+ });
+};
+
+export const useGetOrgSecretValueTrackingStatus = (
+ orgId: string,
+ options?: { enabled?: boolean }
+) => {
+ return useQuery({
+ queryKey: secretInsightsKeys.orgSecretValueTrackingStatus(orgId),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<TGetOrgSecretValueTrackingStatusResponse>(
+ "/api/v1/organization/secret-value-tracking/status"
+ );
+ return data;
+ },
+ enabled: Boolean(orgId) && (options?.enabled ?? true),
+ staleTime: 0,
+ refetchInterval: (query) => (query.state.data?.status === "pending" ? 2000 : false)
+ });
+};
diff --git a/frontend/src/hooks/api/secretInsights/types.ts b/frontend/src/hooks/api/secretInsights/types.ts
index dda7a01097..ac97eae876 100644
--- a/frontend/src/hooks/api/secretInsights/types.ts
+++ b/frontend/src/hooks/api/secretInsights/types.ts
@@ -217,6 +217,37 @@ export type TOrgStaticSecretUsage = {
weeks: { weekStart: string; totalSecrets: number; isPartial: boolean }[];
};
+export type TOrgDuplicatedSecretEntry = TDuplicatedSecretEntry & {
+ projectId: string;
+ projectName: string;
+};
+
+export type TOrgDuplicatedSecretGroup = {
+ projectCount: number;
+ locationCount: number;
+ secrets: TOrgDuplicatedSecretEntry[];
+};
+
+export type TGetOrgSecretsDuplicationResponse = {
+ orgWideSecretValueTrackingEnabled: boolean;
+ groups: TOrgDuplicatedSecretGroup[];
+ computedAt: string | null;
+};
+
+export type TGetOrgSecretValueTrackingStatusResponse = {
+ status: "not-found" | "pending" | "completed" | "failed";
+ message?: string;
+ projectsTotal: number;
+ projectsDone: number;
+ secretsProcessed: number;
+};
+
+export type TSecretValueMatch = TOrgDuplicatedSecretEntry;
+
+export type TSearchSecretsByValueResponse = {
+ secrets: TSecretValueMatch[];
+};
+
export type TOrgSecretAccessVolume = {
days: { date: string; total: number }[];
};
diff --git a/frontend/src/pages/organization/ProjectsPage/ProjectTypePage/ProjectSearchInput.tsx b/frontend/src/pages/organization/ProjectsPage/ProjectTypePage/ProjectSearchInput.tsx
new file mode 100644
index 0000000000..cf153902f9
--- /dev/null
+++ b/frontend/src/pages/organization/ProjectsPage/ProjectTypePage/ProjectSearchInput.tsx
@@ -0,0 +1,128 @@
+import { FocusEvent, KeyboardEvent, useRef, useState } from "react";
+import { SearchIcon, ShieldAlertIcon } from "lucide-react";
+
+import { SecretValueSearchSheet } from "@app/components/secrets/SecretValueSearchSheet";
+import {
+ InputGroup,
+ InputGroupAddon,
+ InputGroupInput,
+ Popover,
+ PopoverContent,
+ PopoverTrigger
+} from "@app/components/v3";
+import { cn } from "@app/components/v3/utils";
+import { useSlashFocusSearch } from "@app/hooks";
+
+type Props = {
+ orgId: string;
+ value: string;
+ onChange: (value: string) => void;
+ canSearchByValue: boolean;
+};
+
+export const ProjectSearchInput = ({ orgId, value, onChange, canSearchByValue }: Props) => {
+ const inputRef = useRef<HTMLInputElement>(null);
+ const valueSearchBtnRef = useRef<HTMLButtonElement>(null);
+ const [isFocused, setIsFocused] = useState(false);
+ const [isOptionHighlighted, setIsOptionHighlighted] = useState(false);
+ const [isValueSearchOpen, setIsValueSearchOpen] = useState(false);
+ useSlashFocusSearch(inputRef);
+
+ const close = () => {
+ setIsFocused(false);
+ setIsOptionHighlighted(false);
+ };
+
+ const openValueSearch = () => {
+ close();
+ inputRef.current?.blur();
+ setIsValueSearchOpen(true);
+ };
+
+ const input = (
+ <InputGroup className="min-w-48 flex-1">
+ <InputGroupAddon align="inline-start">
+ <SearchIcon />
+ </InputGroupAddon>
+ <InputGroupInput
+ ref={inputRef}
+ placeholder="Search by project name..."
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ {...(canSearchByValue && {
+ onFocus: () => setIsFocused(true),
+ onBlur: (e: FocusEvent<HTMLInputElement>) => {
+ if (e.relatedTarget === valueSearchBtnRef.current) return;
+ close();
+ },
+ onKeyDown: (e: KeyboardEvent<HTMLInputElement>) => {
+ if (!isFocused) return;
+ if (e.key === "Tab" && !e.shiftKey) {
+ e.preventDefault();
+ valueSearchBtnRef.current?.focus();
+ } else if (e.key === "ArrowDown" || e.key === "ArrowUp") {
+ e.preventDefault();
+ setIsOptionHighlighted(true);
+ } else if (e.key === "Enter" && isOptionHighlighted) {
+ e.preventDefault();
+ openValueSearch();
+ } else if (e.key === "Escape") {
+ close();
+ inputRef.current?.blur();
+ }
+ }
+ })}
+ />
+ </InputGroup>
+ );
+
+ // The page is shared across products; only Secret Management with the permission gets the option.
+ if (!canSearchByValue) return input;
+
+ return (
+ <>
+ <Popover open={isFocused}>
+ <PopoverTrigger asChild>
+ <div className="flex min-w-48 flex-1">{input}</div>
+ </PopoverTrigger>
+ <PopoverContent
+ align="start"
+ className="w-[var(--radix-popover-trigger-width)] p-1"
+ onOpenAutoFocus={(e) => e.preventDefault()}
+ onCloseAutoFocus={(e) => e.preventDefault()}
+ onEscapeKeyDown={(e) => {
+ e.preventDefault();
+ inputRef.current?.focus();
+ close();
+ }}
+ >
+ <button
+ ref={valueSearchBtnRef}
+ type="button"
+ className={cn(
+ "flex w-full cursor-pointer items-center gap-2 rounded px-2 py-1.5 text-sm text-foreground hover:bg-foreground/5",
+ isOptionHighlighted && "bg-foreground/5"
+ )}
+ onFocus={() => setIsOptionHighlighted(true)}
+ onBlur={close}
+ onKeyDown={(e) => {
+ if (e.key === "Tab" && e.shiftKey) {
+ e.preventDefault();
+ inputRef.current?.focus();
+ }
+ }}
+ onClick={openValueSearch}
+ >
+ <ShieldAlertIcon className="size-4 shrink-0 text-muted" />
+ <span className="truncate">Search by secret value</span>
+ </button>
+ </PopoverContent>
+ </Popover>
+ <SecretValueSearchSheet
+ orgId={orgId}
+ isOpen={isValueSearchOpen}
+ onOpenChange={setIsValueSearchOpen}
+ />
+ </>
+ );
+};
diff --git a/frontend/src/pages/organization/ProjectsPage/ProjectTypePage/ProjectTypePage.tsx b/frontend/src/pages/organization/ProjectsPage/ProjectTypePage/ProjectTypePage.tsx
index c82a59429d..28b3148e79 100644
--- a/frontend/src/pages/organization/ProjectsPage/ProjectTypePage/ProjectTypePage.tsx
+++ b/frontend/src/pages/organization/ProjectsPage/ProjectTypePage/ProjectTypePage.tsx
@@ -1,5 +1,5 @@
/* eslint-disable @typescript-eslint/no-use-before-define */
-import { type ComponentProps, type ReactNode, useEffect, useMemo, useRef, useState } from "react";
+import { type ComponentProps, type ReactNode, useEffect, useMemo, useState } from "react";
import { Helmet } from "react-helmet";
import { Link, useNavigate, useParams } from "@tanstack/react-router";
import { format } from "date-fns";
@@ -38,9 +38,6 @@ import {
EmptyMedia,
EmptyTitle,
IconButton,
- InputGroup,
- InputGroupAddon,
- InputGroupInput,
PageHeader,
Pagination,
Skeleton,
@@ -63,7 +60,8 @@ import {
} from "@app/context";
import {
OrgPermissionAdminConsoleAction,
- OrgPermissionProjectActions
+ OrgPermissionProjectActions,
+ OrgPermissionSecretsManagementInsightsActions
} from "@app/context/OrgPermissionContext/types";
import {
getProjectHomePage,
@@ -77,13 +75,7 @@ import {
PreferenceKey,
setUserTablePreference
} from "@app/helpers/userTablePreferences";
-import {
- useDebounce,
- usePagination,
- usePopUp,
- useResetPageHelper,
- useSlashFocusSearch
-} from "@app/hooks";
+import { useDebounce, usePagination, usePopUp, useResetPageHelper } from "@app/hooks";
import {
useGetMyPendingProjectAccessRequests,
useGetUserProjects,
@@ -105,6 +97,8 @@ import {
ProjectListView
} from "@app/pages/organization/ProjectsPage/components/ProjectListToggle";
+import { ProjectSearchInput } from "./ProjectSearchInput";
+
enum ProjectsViewMode {
GRID = "grid",
LIST = "list"
@@ -722,6 +716,7 @@ const MyProjectsForType = ({
return (
<div className="@container flex flex-col gap-5">
<Toolbar
+ projectType={projectType}
searchFilter={searchFilter}
onSearchChange={setSearchFilter}
projectsViewMode={projectsViewMode}
@@ -1045,6 +1040,7 @@ const AllProjectsForType = ({
return (
<div className="flex flex-col gap-5">
<Toolbar
+ projectType={projectType}
searchFilter={searchFilter}
onSearchChange={setSearchFilter}
projectsViewMode={ProjectsViewMode.LIST}
@@ -1078,6 +1074,7 @@ const AllProjectsForType = ({
};
const Toolbar = ({
+ projectType,
searchFilter,
onSearchChange,
projectsViewMode,
@@ -1090,6 +1087,7 @@ const Toolbar = ({
isAddingProjectsAllowed,
isGridDisabled
}: {
+ projectType: ProjectType;
searchFilter: string;
onSearchChange: (value: string) => void;
projectsViewMode: ProjectsViewMode;
@@ -1102,23 +1100,22 @@ const Toolbar = ({
isAddingProjectsAllowed: boolean;
isGridDisabled?: boolean;
}) => {
- const searchInputRef = useRef<HTMLInputElement>(null);
- useSlashFocusSearch(searchInputRef);
+ const { currentOrg } = useOrganization();
+ const { permission } = useOrgPermission();
+ const canSearchAllSecretValues = permission.can(
+ OrgPermissionSecretsManagementInsightsActions.SearchAllSecretValues,
+ OrgPermissionSubjects.SecretsManagementInsights
+ );
return (
<div className="flex w-full flex-wrap items-center justify-between gap-2">
<div className="flex min-w-72 flex-1 items-center gap-2">
- <InputGroup className="min-w-48 flex-1">
- <InputGroupAddon align="inline-start">
- <SearchIcon />
- </InputGroupAddon>
- <InputGroupInput
- ref={searchInputRef}
- placeholder="Search by project name..."
- value={searchFilter}
- onChange={(e) => onSearchChange(e.target.value)}
- />
- </InputGroup>
+ <ProjectSearchInput
+ orgId={currentOrg.id}
+ value={searchFilter}
+ onChange={onSearchChange}
+ canSearchByValue={projectType === ProjectType.SecretManager && canSearchAllSecretValues}
+ />
{!hideProjectListToggle && (
<ProjectListToggle value={projectListView} onChange={onProjectListViewChange} />
)}
diff --git a/frontend/src/pages/organization/RoleByIDPage/components/OrgRoleModifySection.utils.ts b/frontend/src/pages/organization/RoleByIDPage/components/OrgRoleModifySection.utils.ts
index acc3375143..b0092a5058 100644
--- a/frontend/src/pages/organization/RoleByIDPage/components/OrgRoleModifySection.utils.ts
+++ b/frontend/src/pages/organization/RoleByIDPage/components/OrgRoleModifySection.utils.ts
@@ -213,7 +213,8 @@ const secretsManagementInsightsPermissionSchema = z
z.object({
[OrgPermissionSecretsManagementInsightsActions.Read]: z.boolean().optional(),
[OrgPermissionSecretsManagementInsightsActions.GenerateReport]: z.boolean().optional(),
- [OrgPermissionSecretsManagementInsightsActions.DeleteReport]: z.boolean().optional()
+ [OrgPermissionSecretsManagementInsightsActions.DeleteReport]: z.boolean().optional(),
+ [OrgPermissionSecretsManagementInsightsActions.SearchAllSecretValues]: z.boolean().optional()
})
)
.optional();
@@ -960,6 +961,12 @@ export const ORG_PERMISSION_OBJECT: Record<string, TOrgPermissionConfig> = {
value: OrgPermissionSecretsManagementInsightsActions.DeleteReport,
label: "Delete Report",
description: "Delete secrets management insight reports"
+ },
+ {
+ value: OrgPermissionSecretsManagementInsightsActions.SearchAllSecretValues,
+ label: "Search All Secret Values",
+ description:
+ "Find secrets that share a value in any project, including projects the user isn't a member of"
}
]
},
diff --git a/frontend/src/pages/organization/SecretInsightsPage/SecretInsightsPage.tsx b/frontend/src/pages/organization/SecretInsightsPage/SecretInsightsPage.tsx
index 6a32be66ce..9f04822d7c 100644
--- a/frontend/src/pages/organization/SecretInsightsPage/SecretInsightsPage.tsx
+++ b/frontend/src/pages/organization/SecretInsightsPage/SecretInsightsPage.tsx
@@ -45,6 +45,7 @@ import { ProjectType } from "@app/hooks/api/projects/types";
import {
AuthMethodsCard,
+ DuplicatedSecretsCard,
InsightsCard,
RequestOrgAuditReportModal,
SecretAccessVolumeCard,
@@ -252,6 +253,7 @@ export const SecretInsightsPage = withPermission(
isPlanRestricted={!hasInsightsPlan}
/>
)}
+ <DuplicatedSecretsCard isPlanRestricted={!hasInsightsPlan} />
<div
className={
showAuthMethodsSlot ? "grid gap-4 xl:grid-cols-[1fr_1.35fr]" : "grid gap-4"
diff --git a/frontend/src/pages/organization/SecretInsightsPage/components/DuplicateGroupList.tsx b/frontend/src/pages/organization/SecretInsightsPage/components/DuplicateGroupList.tsx
new file mode 100644
index 0000000000..ab87a5ed2a
--- /dev/null
+++ b/frontend/src/pages/organization/SecretInsightsPage/components/DuplicateGroupList.tsx
@@ -0,0 +1,150 @@
+import { useNavigate, useParams } from "@tanstack/react-router";
+import { ArrowRightIcon, FolderIcon, KeyIcon, LayersIcon, LockIcon } from "lucide-react";
+
+import {
+ Accordion,
+ AccordionContent,
+ AccordionItem,
+ AccordionTrigger,
+ Badge,
+ IconButton,
+ ProjectIcon,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger
+} from "@app/components/v3";
+import { cn } from "@app/components/v3/utils";
+import { TOrgDuplicatedSecretGroup } from "@app/hooks/api/secretInsights";
+
+const overviewRoute =
+ "/organizations/$orgId/projects/secret-management/$projectId/overview" as const;
+
+type Props = {
+ groups: TOrgDuplicatedSecretGroup[];
+};
+
+const pluralize = (count: number, word: string) => `${count} ${word}${count === 1 ? "" : "s"}`;
+
+export const DuplicateGroupList = ({ groups }: Props) => {
+ const { orgId } = useParams({ strict: false });
+ const navigate = useNavigate();
+
+ return (
+ <Accordion type="multiple">
+ {groups.map((group, groupIdx) => {
+ const isCrossProject = group.projectCount > 1;
+
+ return (
+ <AccordionItem
+ key={`group-${String(groupIdx)}`}
+ value={`group-${String(groupIdx)}`}
+ className={cn(isCrossProject && "border-l-2 border-l-org")}
+ >
+ <AccordionTrigger>
+ <div className="flex flex-1 items-center justify-between">
+ <div className="flex items-center gap-2">
+ <LockIcon className="size-3.5 text-muted" />
+ <span className="text-sm text-foreground">
+ <span className="font-medium">{group.secrets.length} secrets</span> share an
+ identical value
+ </span>
+ </div>
+ <Badge
+ variant={isCrossProject ? "org" : "neutral"}
+ className="flex items-center gap-1.5 font-normal"
+ >
+ <LayersIcon className="size-3" />
+ {isCrossProject
+ ? `${pluralize(group.projectCount, "project")} · ${pluralize(group.locationCount, "location")}`
+ : pluralize(group.locationCount, "location")}
+ </Badge>
+ </div>
+ </AccordionTrigger>
+ <AccordionContent className="group-data-[variant=default]/accordion:p-0">
+ <Table containerClassName="rounded-t-none overflow-x-hidden">
+ <TableHeader>
+ <TableRow>
+ <TableHead className="w-[22%]">Project</TableHead>
+ <TableHead className="w-[28%]">Secret Key</TableHead>
+ <TableHead className="w-[20%]">Environment</TableHead>
+ <TableHead>Path</TableHead>
+ <TableHead variant="action" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {group.secrets.map((entry, idx) => (
+ <TableRow
+ key={`${entry.projectId}-${entry.key}-${entry.environment.slug}-${entry.secretPath}-${String(idx)}`}
+ className="group/row"
+ >
+ <TableCell isTruncatable className="max-w-48">
+ <div className="flex items-center gap-2">
+ <ProjectIcon className="size-3.5 shrink-0 text-muted" />
+ <span className="truncate">{entry.projectName}</span>
+ </div>
+ </TableCell>
+ <TableCell isTruncatable className="max-w-60">
+ <div className="flex items-center gap-2">
+ <KeyIcon className="size-4 shrink-0 text-muted" />
+ <span className="truncate font-mono">{entry.key}</span>
+ </div>
+ </TableCell>
+ <TableCell>
+ <Badge variant="info" isTruncatable className="max-w-full">
+ <span>{entry.environment.name}</span>
+ </Badge>
+ </TableCell>
+ <TableCell>
+ <div className="flex items-center gap-2">
+ <FolderIcon className="size-3.5 shrink-0 text-folder" />
+ <span className="truncate">{entry.secretPath}</span>
+ </div>
+ </TableCell>
+ <TableCell variant="action">
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <IconButton
+ variant="ghost"
+ size="sm"
+ aria-label="Go to secret folder"
+ className="opacity-0 transition-opacity group-hover/row:opacity-100 focus-visible:opacity-100"
+ onClick={() =>
+ navigate({
+ to: overviewRoute,
+ params: {
+ orgId: orgId as string,
+ projectId: entry.projectId
+ },
+ search: {
+ secretPath: entry.secretPath,
+ environments: [entry.environment.slug]
+ }
+ })
+ }
+ >
+ <ArrowRightIcon className="size-3.5" />
+ </IconButton>
+ </TooltipTrigger>
+ <TooltipContent>Go to secret folder</TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </AccordionContent>
+ </AccordionItem>
+ );
+ })}
+ </Accordion>
+ );
+};
diff --git a/frontend/src/pages/organization/SecretInsightsPage/components/DuplicatedSecretsCard.tsx b/frontend/src/pages/organization/SecretInsightsPage/components/DuplicatedSecretsCard.tsx
new file mode 100644
index 0000000000..b7669e41ef
--- /dev/null
+++ b/frontend/src/pages/organization/SecretInsightsPage/components/DuplicatedSecretsCard.tsx
@@ -0,0 +1,196 @@
+import { useEffect, useState } from "react";
+import { useQueryClient } from "@tanstack/react-query";
+import { formatDistanceToNow } from "date-fns";
+import { AlertTriangleIcon, LockIcon, RefreshCwIcon } from "lucide-react";
+
+import {
+ SecretValueTrackingPrompt,
+ useOrgSecretValueTracking
+} from "@app/components/secrets/SecretValueTrackingGate";
+import {
+ Badge,
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+ Empty,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyMedia,
+ 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 {
+ secretInsightsKeys,
+ useGetOrgSecretsDuplication,
+ useRefreshOrgSecretsDuplication
+} from "@app/hooks/api/secretInsights";
+
+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;
+};
+
+export const DuplicatedSecretsCard = ({ isPlanRestricted }: Props) => {
+ const { currentOrg } = useOrganization();
+ const orgId = currentOrg.id;
+ const { permission } = useOrgPermission();
+ const queryClient = useQueryClient();
+
+ const canSearchAllValues = permission.can(
+ OrgPermissionSecretsManagementInsightsActions.SearchAllSecretValues,
+ OrgPermissionSubjects.SecretsManagementInsights
+ );
+ const canQuery = canSearchAllValues && !isPlanRestricted;
+
+ const tracking = useOrgSecretValueTracking({
+ orgId,
+ enabled: canQuery,
+ onTrackingOn: () =>
+ queryClient.invalidateQueries({ queryKey: secretInsightsKeys.orgSecretsDuplication(orgId) })
+ });
+
+ const { data, isPending, isError } = useGetOrgSecretsDuplication(orgId, {
+ enabled: canQuery && tracking.isTrackingOn
+ });
+ const refresh = useRefreshOrgSecretsDuplication();
+
+ const renderBody = () => {
+ if (isPlanRestricted) {
+ return (
+ <Empty className="border">
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <LockIcon />
+ </EmptyMedia>
+ <EmptyTitle>Duplicate detection is not on your current plan</EmptyTitle>
+ <EmptyDescription>
+ Upgrade to find secrets that share a value across every project in the organization.
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ );
+ }
+
+ if (!canSearchAllValues) {
+ return (
+ <Empty className="border">
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <LockIcon />
+ </EmptyMedia>
+ <EmptyTitle>You don&apos;t have access to organization-wide duplicates</EmptyTitle>
+ <EmptyDescription>
+ Ask an organization admin for the Search All Secret Values permission under Secrets
+ Management Insights.
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ );
+ }
+
+ if (!tracking.isTrackingOn) {
+ return (
+ <SecretValueTrackingPrompt
+ tracking={tracking}
+ description="Infisical indexes every secret in the organization once, then keeps the index current as secrets change. Secrets stay readable while it runs."
+ />
+ );
+ }
+
+ if (isPending) return <Skeleton className="h-[280px] w-full" />;
+
+ if (isError) {
+ return (
+ <div className="flex h-[200px] flex-col items-center justify-center gap-3">
+ <AlertTriangleIcon className="size-6 text-danger" />
+ <p className="text-sm text-danger">Could not load duplicated secrets.</p>
+ </div>
+ );
+ }
+
+ const groups = data?.groups ?? [];
+
+ if (groups.length === 0) {
+ return (
+ <Empty className="border">
+ <EmptyHeader>
+ <EmptyTitle>No duplicated secrets found</EmptyTitle>
+ <EmptyDescription>
+ No secret shares its value with another anywhere in the organization.
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ );
+ }
+
+ return <DuplicateGroupList groups={groups} />;
+ };
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>
+ Duplicated Secrets
+ {canQuery && data?.computedAt && (
+ <CheckedAtButton
+ computedAt={data.computedAt}
+ isRefreshing={refresh.isPending}
+ onRefresh={() => refresh.mutate({ orgId })}
+ />
+ )}
+ </CardTitle>
+ <CardDescription>
+ Secrets that share the same value, across every project in the organization
+ </CardDescription>
+ </CardHeader>
+ <CardContent>{renderBody()}</CardContent>
+ </Card>
+ );
+};
diff --git a/frontend/src/pages/organization/SecretInsightsPage/components/index.ts b/frontend/src/pages/organization/SecretInsightsPage/components/index.ts
index 2a8d46c106..4df415cd8a 100644
--- a/frontend/src/pages/organization/SecretInsightsPage/components/index.ts
+++ b/frontend/src/pages/organization/SecretInsightsPage/components/index.ts
@@ -1,4 +1,5 @@
export { AuthMethodsCard } from "./AuthMethodsCard";
+export { DuplicatedSecretsCard } from "./DuplicatedSecretsCard";
export { InsightsCard } from "./InsightsCard";
export { RequestOrgAuditReportModal } from "./RequestOrgAuditReportModal";
export { SecretAccessVolumeCard } from "./SecretAccessVolumeCard";