Skip to content

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

improvement(secrets): remove legacy environment dashboard (#7624)

Andrew Huange905755fefa4
diff --git a/frontend/src/components/navigation/NavHeader.tsx b/frontend/src/components/navigation/NavHeader.tsx
deleted file mode 100644
index 127b1066e5..0000000000
--- a/frontend/src/components/navigation/NavHeader.tsx
+++ /dev/null
@@ -1,217 +0,0 @@
-import { useState } from "react";
-import { faAngleRight, faCheck, faCopy, faLock } from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import { Link, useParams } from "@tanstack/react-router";
-import { twMerge } from "tailwind-merge";
-
-import { useOrganization, useProject } from "@app/context";
-import { useToggle } from "@app/hooks";
-
-import { createNotification } from "../notifications";
-import { IconButton, Select, SelectItem, Tooltip } from "../v2";
-
-type Props = {
- pageName: string;
- isProjectRelated?: boolean;
- isOrganizationRelated?: boolean;
- currentEnv?: string;
- userAvailableEnvs?: any[];
- onEnvChange?: (slug: string) => void;
- secretPath?: string;
- isFolderMode?: boolean;
- isProtectedBranch?: boolean;
- protectionPolicyName?: string;
-};
-
-// TODO: make links clickable and clean up
-
-/**
- * This is the component at the top of almost every page.
- * It shows how to navigate to a certain page.
- * It future these links should also be clickable and hoverable
- * @param {object} obj
- * @param {string} obj.pageName - Name of the page
- * @param {boolean} obj.isProjectRelated - whether or not this page is related to project (determine if it's 2 or 3 navigation steps)
- * @param {boolean} obj.isOrganizationRelated - whether or not this page is related to organization (determine if it's 2 or 3 navigation steps)
- * @param {string} obj.currentEnv - current environment inside a project
- * @param {string} obj.userAvailableEnvs - environments that are available to a user in this project (used for the dropdown)
- * @param {string} obj.onEnvChange - the action that happens when an env is changed
- * @returns
- */
-// TODO(akhilmhdh): simply this header and nav system later
-export default function NavHeader({
- pageName,
- isProjectRelated,
- isOrganizationRelated,
- currentEnv,
- userAvailableEnvs = [],
- onEnvChange,
- isFolderMode,
- secretPath = "/",
- isProtectedBranch = false,
- protectionPolicyName
-}: Props): JSX.Element {
- const { currentProject } = useProject();
- const { currentOrg } = useOrganization();
-
- const [isCopied, { timedToggle: toggleIsCopied }] = useToggle(false);
- const [isHoveringCopyButton, setIsHoveringCopyButton] = useState(false);
-
- const routerEnvSlug = useParams({
- strict: false,
- select: (el) => el.envSlug
- });
-
- const secretPathSegments = secretPath.split("/").filter(Boolean);
-
- return (
- <div className="flex flex-row items-center pt-6">
- <div className="mr-2 flex h-5 w-5 min-w-5 items-center justify-center rounded-md bg-primary text-sm text-black">
- {currentOrg?.name?.charAt(0)}
- </div>
- <Link
- to="/organizations/$orgId/projects"
- params={{ orgId: currentOrg.id }}
- className="truncate pl-0.5 text-sm font-medium text-primary/80 hover:text-primary"
- >
- {currentOrg?.name}
- </Link>
- {isProjectRelated && (
- <>
- <FontAwesomeIcon icon={faAngleRight} className="mr-3 ml-3 text-xs text-gray-400" />
- <div className="truncate text-sm font-medium text-bunker-300">{currentProject?.name}</div>
- </>
- )}
- {isOrganizationRelated && (
- <>
- <FontAwesomeIcon icon={faAngleRight} className="mr-3 ml-3 text-xs text-gray-400" />
- <div className="text-sm font-medium text-bunker-300">Organization Settings</div>
- </>
- )}
- <FontAwesomeIcon icon={faAngleRight} className="mr-3 ml-3 text-sm text-gray-400" />
- {pageName === "Secrets" ? (
- <Link
- to="/organizations/$orgId/projects/secret-management/$projectId/overview"
- params={{ orgId: currentOrg?.id || "", projectId: currentProject.id }}
- className="text-sm font-medium text-primary/80 hover:text-primary"
- >
- {pageName}
- </Link>
- ) : (
- <div className="text-sm text-gray-400">{pageName}</div>
- )}
- {currentEnv && secretPath === "/" && (
- <>
- <FontAwesomeIcon icon={faAngleRight} className="mr-1.5 ml-3 text-xs text-gray-400" />
- <div className="rounded-md pl-3 hover:bg-bunker-100/10">
- <Tooltip content="Select environment">
- <Select
- value={currentEnv}
- onValueChange={(value) => {
- if (value && onEnvChange) onEnvChange(value);
- }}
- className="border-none bg-transparent pl-0 text-sm font-medium text-primary/80 hover:text-primary"
- dropdownContainerClassName="text-bunker-200 bg-mineshaft-800 border border-mineshaft-600 drop-shadow-2xl"
- >
- {userAvailableEnvs?.map(({ name, slug }) => (
- <SelectItem value={slug} key={slug}>
- {name}
- </SelectItem>
- ))}
- </Select>
- </Tooltip>
- </div>
- </>
- )}
- {isFolderMode && routerEnvSlug && Boolean(secretPathSegments.length) && (
- <div className="flex items-center space-x-3">
- <FontAwesomeIcon icon={faAngleRight} className="mr-1.5 ml-3 text-xs text-gray-400" />
- <Link
- to="/organizations/$orgId/projects/secret-management/$projectId/secrets/$envSlug"
- params={{ orgId: currentOrg.id, projectId: currentProject.id, envSlug: routerEnvSlug }}
- className="text-sm font-medium text-primary/80 hover:text-primary"
- >
- {userAvailableEnvs?.find(({ slug }) => slug === currentEnv)?.name}
- </Link>
- </div>
- )}
- {isFolderMode &&
- secretPathSegments?.map((folderName, index) => {
- const newSecretPath = `/${secretPathSegments.slice(0, index + 1).join("/")}`;
-
- return (
- <div
- className="flex items-center space-x-3"
- key={`breadcrumb-secret-path-${folderName}`}
- >
- <FontAwesomeIcon icon={faAngleRight} className="mr-1.5 ml-3 text-xs text-gray-400" />
- {index + 1 === secretPathSegments?.length ? (
- <div className="flex items-center space-x-2">
- <span
- className={twMerge(
- "text-sm transition-all",
- isHoveringCopyButton ? "text-bunker-200" : "text-bunker-300"
- )}
- >
- {folderName}
- </span>
- <Tooltip
- className="relative right-2"
- position="bottom"
- content="Copy secret path"
- >
- <IconButton
- variant="plain"
- ariaLabel="copy"
- onMouseEnter={() => setIsHoveringCopyButton(true)}
- onMouseLeave={() => setIsHoveringCopyButton(false)}
- onClick={() => {
- if (isCopied) return;
-
- navigator.clipboard.writeText(newSecretPath);
-
- createNotification({
- text: "Copied secret path to clipboard",
- type: "info"
- });
-
- toggleIsCopied(2000);
- }}
- className="hover:bg-bunker-100/10"
- >
- <FontAwesomeIcon
- icon={!isCopied ? faCopy : faCheck}
- size="sm"
- className="cursor-pointer"
- />
- </IconButton>
- </Tooltip>
- </div>
- ) : (
- <Link
- to="/organizations/$orgId/projects/secret-management/$projectId/secrets/$envSlug"
- params={{
- orgId: currentOrg?.id || "",
- projectId: currentProject.id,
- envSlug: routerEnvSlug || ""
- }}
- search={(query) => ({ ...query, secretPath: newSecretPath })}
- className={twMerge(
- "text-sm transition-all hover:text-primary",
- isHoveringCopyButton ? "text-primary" : "text-primary/80"
- )}
- >
- {folderName}
- </Link>
- )}
- </div>
- );
- })}
- {isProtectedBranch && (
- <Tooltip content={`Protected by policy ${protectionPolicyName}`}>
- <FontAwesomeIcon icon={faLock} className="ml-2 text-primary" />
- </Tooltip>
- )}
- </div>
- );
-}
diff --git a/frontend/src/components/navigation/SecretDashboardPathBreadcrumb.tsx b/frontend/src/components/navigation/SecretDashboardPathBreadcrumb.tsx
index 62f219da91..d9effbac9a 100644
--- a/frontend/src/components/navigation/SecretDashboardPathBreadcrumb.tsx
+++ b/frontend/src/components/navigation/SecretDashboardPathBreadcrumb.tsx
@@ -71,13 +71,16 @@ export const SecretDashboardPathBreadcrumb = ({
</div>
) : (
<Link
- to="/organizations/$orgId/projects/secret-management/$projectId/secrets/$envSlug"
+ to="/organizations/$orgId/projects/secret-management/$projectId/overview"
params={{
orgId: currentOrg.id,
- projectId,
- envSlug: environmentSlug
+ projectId
}}
- search={(query) => ({ ...query, secretPath: newSecretPath })}
+ search={(query) => ({
+ ...query,
+ secretPath: newSecretPath,
+ environments: [environmentSlug]
+ })}
className={twMerge(
"text-sm transition-all hover:text-primary",
isCopying && "text-primary"
diff --git a/frontend/src/components/v2/InfisicalSecretInput/InfisicalSecretInput.tsx b/frontend/src/components/v2/InfisicalSecretInput/InfisicalSecretInput.tsx
index 771958345f..cda9eed25b 100644
--- a/frontend/src/components/v2/InfisicalSecretInput/InfisicalSecretInput.tsx
+++ b/frontend/src/components/v2/InfisicalSecretInput/InfisicalSecretInput.tsx
@@ -86,7 +86,7 @@ export const InfisicalSecretInput = forwardRef<HTMLTextAreaElement, Props>(
) => {
const { currentProject } = useProject();
const projectId = currentProject?.id || "";
- const navigate = useNavigate({ from: ROUTE_PATHS.SecretManager.SecretDashboardPage.path });
+ const navigate = useNavigate({ from: ROUTE_PATHS.SecretManager.OverviewPage.path });
const { permission } = useProjectPermission();
const [debouncedValue] = useDebounce(value, 100);
@@ -443,17 +443,14 @@ export const InfisicalSecretInput = forwardRef<HTMLTextAreaElement, Props>(
}
navigate({
- to: ROUTE_PATHS.SecretManager.SecretDashboardPage.path,
- params: {
- projectId,
- envSlug: environmentSlug
- },
+ to: ROUTE_PATHS.SecretManager.OverviewPage.path,
+ params: { projectId },
search: (prev) => ({
...prev,
secretPath: segment === environmentSlug ? "/" : folderPath,
search: segment === secretName ? secretName : prev.search,
filterBy: segment === secretName ? "secret" : prev.filterBy,
- tags: ""
+ environments: [environmentSlug]
})
});
},
diff --git a/frontend/src/components/v3/platform/SecretInput/InfisicalSecretInput.tsx b/frontend/src/components/v3/platform/SecretInput/InfisicalSecretInput.tsx
index 763caa73d0..4691749831 100644
--- a/frontend/src/components/v3/platform/SecretInput/InfisicalSecretInput.tsx
+++ b/frontend/src/components/v3/platform/SecretInput/InfisicalSecretInput.tsx
@@ -59,7 +59,7 @@ export const InfisicalSecretInput = forwardRef<HTMLTextAreaElement, Props>(
) => {
const { currentProject } = useProject();
const projectId = currentProject?.id || "";
- const navigate = useNavigate({ from: ROUTE_PATHS.SecretManager.SecretDashboardPage.path });
+ const navigate = useNavigate({ from: ROUTE_PATHS.SecretManager.OverviewPage.path });
const { permission } = useProjectPermission();
const [debouncedValue] = useDebounce(value, 100);
@@ -206,14 +206,14 @@ export const InfisicalSecretInput = forwardRef<HTMLTextAreaElement, Props>(
}
navigate({
- to: ROUTE_PATHS.SecretManager.SecretDashboardPage.path,
- params: { projectId, envSlug: environmentSlug },
+ to: ROUTE_PATHS.SecretManager.OverviewPage.path,
+ params: { projectId },
search: (prev) => ({
...prev,
secretPath: segment === environmentSlug ? "/" : folderPath,
search: segment === secretName ? secretName : prev.search,
filterBy: segment === secretName ? "secret" : prev.filterBy,
- tags: ""
+ environments: [environmentSlug]
})
});
},
diff --git a/frontend/src/const/routes.ts b/frontend/src/const/routes.ts
index 1997dacf01..6dd60bb1c2 100644
--- a/frontend/src/const/routes.ts
+++ b/frontend/src/const/routes.ts
@@ -107,10 +107,6 @@ export const ROUTE_PATHS = Object.freeze({
"/organizations/$orgId/projects/secret-management/$projectId/approval",
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/approval"
),
- SecretDashboardPage: setRoute(
- "/organizations/$orgId/projects/secret-management/$projectId/secrets/$envSlug",
- "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/secrets/$envSlug"
- ),
RollbackPreviewPage: setRoute(
"/organizations/$orgId/projects/secret-management/$projectId/commits/$environment/$folderId/$commitId/restore",
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/commits/$environment/$folderId/$commitId/restore"
diff --git a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayConnectedResourcesSection/GatewayConnectedResourcesSection.tsx b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayConnectedResourcesSection/GatewayConnectedResourcesSection.tsx
index 6fe9f85589..1edd310b92 100644
--- a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayConnectedResourcesSection/GatewayConnectedResourcesSection.tsx
+++ b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayConnectedResourcesSection/GatewayConnectedResourcesSection.tsx
@@ -43,15 +43,17 @@ const ResourceRow = ({
name,
subtitle,
to,
- params
+ params,
+ search
}: {
name: string;
subtitle: string;
to: string;
params: Record<string, string>;
+ search?: Record<string, unknown>;
}) => (
<Item asChild variant="outline" size="xs">
- <Link to={to as "/"} params={params}>
+ <Link to={to as "/"} params={params} search={search as never}>
<ItemContent>
<ItemTitle>{name}</ItemTitle>
<ItemDescription className="text-mineshaft-400">{subtitle}</ItemDescription>
@@ -132,12 +134,12 @@ export const GatewayConnectedResourcesSection = ({ gatewayId }: Props) => {
key={d.id}
name={d.name}
subtitle={`${d.environmentSlug} · ${d.projectName}`}
- to="/organizations/$orgId/projects/secret-management/$projectId/secrets/$envSlug"
+ to="/organizations/$orgId/projects/secret-management/$projectId/overview"
params={{
orgId: currentOrg.id,
- projectId: d.projectId,
- envSlug: d.environmentSlug
+ projectId: d.projectId
}}
+ search={{ environments: [d.environmentSlug] }}
/>
))}
</ItemGroup>
diff --git a/frontend/src/pages/secret-manager/CommitDetailsPage/components/RollbackPreviewTab/route.tsx b/frontend/src/pages/secret-manager/CommitDetailsPage/components/RollbackPreviewTab/route.tsx
index 8d518e624d..a9076243e1 100644
--- a/frontend/src/pages/secret-manager/CommitDetailsPage/components/RollbackPreviewTab/route.tsx
+++ b/frontend/src/pages/secret-manager/CommitDetailsPage/components/RollbackPreviewTab/route.tsx
@@ -33,11 +33,14 @@ export const Route = createFileRoute(
links: context.project.environments.map((el) => ({
label: el.name,
link: linkOptions({
- to: "/organizations/$orgId/projects/secret-management/$projectId/secrets/$envSlug",
+ to: "/organizations/$orgId/projects/secret-management/$projectId/overview",
params: {
orgId: params.orgId,
- projectId: params.projectId,
- envSlug: el.slug
+ projectId: params.projectId
+ },
+ search: {
+ secretPath: search.secretPath,
+ environments: [el.slug]
}
})
}))
diff --git a/frontend/src/pages/secret-manager/CommitDetailsPage/route.tsx b/frontend/src/pages/secret-manager/CommitDetailsPage/route.tsx
index 6d6c63f292..cab5129ba6 100644
--- a/frontend/src/pages/secret-manager/CommitDetailsPage/route.tsx
+++ b/frontend/src/pages/secret-manager/CommitDetailsPage/route.tsx
@@ -33,11 +33,14 @@ export const Route = createFileRoute(
links: context.project.environments.map((el) => ({
label: el.name,
link: linkOptions({
- to: "/organizations/$orgId/projects/secret-management/$projectId/secrets/$envSlug",
+ to: "/organizations/$orgId/projects/secret-management/$projectId/overview",
params: {
orgId: params.orgId,
- projectId: params.projectId,
- envSlug: el.slug
+ projectId: params.projectId
+ },
+ search: {
+ secretPath: search.secretPath,
+ environments: [el.slug]
}
})
}))
diff --git a/frontend/src/pages/secret-manager/CommitsPage/route.tsx b/frontend/src/pages/secret-manager/CommitsPage/route.tsx
index 463ba463e4..facff9fcdd 100644
--- a/frontend/src/pages/secret-manager/CommitsPage/route.tsx
+++ b/frontend/src/pages/secret-manager/CommitsPage/route.tsx
@@ -34,11 +34,14 @@ export const Route = createFileRoute(
links: context.project.environments.map((el) => ({
label: el.name,
link: linkOptions({
- to: "/organizations/$orgId/projects/secret-management/$projectId/secrets/$envSlug",
+ to: "/organizations/$orgId/projects/secret-management/$projectId/overview",
params: {
orgId: params.orgId,
- projectId: params.projectId,
- envSlug: el.slug
+ projectId: params.projectId
+ },
+ search: {
+ secretPath: search.secretPath,
+ environments: [el.slug]
}
})
}))
diff --git a/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsx b/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsx
index 19cd2ae306..35de9ac39e 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsx
@@ -305,6 +305,7 @@ const OverviewPageContent = () => {
environments: el.environments,
dynamicSecretId: el.dynamicSecretId,
honeyTokenId: el.honeyTokenId,
+ tags: el.tags,
filterBy: el.filterBy
})
});
@@ -456,18 +457,18 @@ const OverviewPageContent = () => {
);
// Apply one-shot deep-link inputs to local filters, then strip them from the URL in a SINGLE
- // navigate. These arrive either from a notification/email link (`search`, `filterBy`) or from
- // the secret reference tree (`environments` + `search`). Handling them in one effect/navigate
+ // navigate. These arrive from notifications, legacy dashboard bookmarks (`tags`, `filterBy`),
+ // or the secret reference tree (`environments` + `search`). Handling them in one effect/navigate
// (rather than two racing effects) guarantees every param is cleared after it's applied. That
// matters most for `environments`: re-selecting the same environment from the reference tree
// changes the param again and re-fires this effect instead of being a no-op. Runs reactively
// (not mount-only) because the tree is rendered inside this page, so navigating from a node
// updates the params without remounting.
useEffect(() => {
- const { search, filterBy, environments: envSlugs, ...query } = routerSearch;
+ const { search, tags, filterBy, environments: envSlugs, ...query } = routerSearch;
const hasEnvLink = Boolean(envSlugs?.length);
- if (!search && !filterBy && !hasEnvLink) return;
+ if (!search && !tags && !filterBy && !hasEnvLink) return;
// Env link present but envs not loaded yet → wait so we don't strip it before applying.
if (hasEnvLink && userAvailableEnvs.length === 0) return;
@@ -480,15 +481,31 @@ const OverviewPageContent = () => {
}
}
- if (search || filterBy) {
+ if (search || tags || filterBy) {
const initialFilter = { ...DEFAULT_FILTER_STATE };
if (filterBy) {
- const rowType = Object.values(RowType).find((rt) => rt === filterBy);
- if (rowType) {
- initialFilter[rowType] = true;
- }
+ filterBy
+ .split(",")
+ .map((value) => value.trim())
+ .filter((value): value is RowType => Object.values(RowType).includes(value as RowType))
+ .forEach((rowType) => {
+ initialFilter[rowType] = true;
+ });
}
+
+ const initialTagFilter = (tags ?? "")
+ .split(",")
+ .reduce<Record<string, boolean>>((acc, tag) => {
+ const tagSlug = tag.trim();
+ if (tagSlug) acc[tagSlug] = true;
+ return acc;
+ }, {});
+ if (Object.keys(initialTagFilter).length > 0) {
+ initialFilter[RowType.Secret] = true;
+ }
+
setFilter(initialFilter);
+ setTagFilter(initialTagFilter);
if (search) {
setSearchFilter(search as string);
@@ -498,6 +515,7 @@ const OverviewPageContent = () => {
navigate({ search: query, replace: true });
}, [
routerSearch.search,
+ routerSearch.tags,
routerSearch.filterBy,
routerSearch.environments?.join(","),
userAvailableEnvs.length
diff --git a/frontend/src/pages/secret-manager/OverviewPage/route.tsx b/frontend/src/pages/secret-manager/OverviewPage/route.tsx
index 26b1bc930b..16d5249a17 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/route.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/route.tsx
@@ -12,6 +12,7 @@ const SecretOverviewPageQuerySchema = z.object({
environments: z.array(z.string()).catch([]),
dynamicSecretId: z.string().optional(),
honeyTokenId: z.string().optional(),
+ tags: z.string().optional(),
filterBy: z.string().optional()
});
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/SecretDashboardPage.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/SecretDashboardPage.tsx
deleted file mode 100644
index 88a4d36233..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/SecretDashboardPage.tsx
+++ /dev/null
@@ -1,1149 +0,0 @@
-/* eslint-disable no-case-declarations */
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import { Helmet } from "react-helmet";
-import { useTranslation } from "react-i18next";
-import { subject } from "@casl/ability";
-import {
- faArrowDown,
- faArrowUp,
- faChevronLeft,
- faInfoCircle
-} from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import { Link, useNavigate, useParams, useSearch } from "@tanstack/react-router";
-import { twMerge } from "tailwind-merge";
-
-import { createNotification } from "@app/components/notifications";
-import { PermissionDeniedBanner } from "@app/components/permissions";
-import {
- Button,
- Checkbox,
- ContentLoader,
- Modal,
- ModalContent,
- PageHeader,
- Pagination,
- Tooltip
-} from "@app/components/v2";
-import { ROUTE_PATHS } from "@app/const/routes";
-import {
- ProjectPermissionActions,
- ProjectPermissionDynamicSecretActions,
- ProjectPermissionSub,
- useOrganization,
- useProject,
- useProjectPermission
-} from "@app/context";
-import {
- ProjectPermissionCommitsActions,
- ProjectPermissionSecretActions,
- ProjectPermissionSecretRotationActions
-} from "@app/context/ProjectPermissionContext/types";
-import {
- getUserTablePreference,
- PreferenceKey,
- setUserTablePreference
-} from "@app/helpers/userTablePreferences";
-import { useDebounce, usePagination, usePopUp, useResetPageHelper } from "@app/hooks";
-import {
- useGetImportedSecretsSingleEnv,
- useGetSecretApprovalPolicyOfABoard,
- useGetWsTags
-} from "@app/hooks/api";
-import { useGetProjectSecretsDetails } from "@app/hooks/api/dashboard";
-import { dashboardKeys } from "@app/hooks/api/dashboard/queries";
-import { DashboardSecretsOrderBy } from "@app/hooks/api/dashboard/types";
-import { useGetFolderCommitsCount } from "@app/hooks/api/folderCommits";
-import { OrderByDirection } from "@app/hooks/api/generic/types";
-import { ProjectType, ProjectVersion } from "@app/hooks/api/projects/types";
-import { queryClient } from "@app/hooks/api/reactQuery";
-import { PendingAction } from "@app/hooks/api/secretFolders/types";
-import { useCreateCommit } from "@app/hooks/api/secrets/mutations";
-import { SecretV3RawSanitized } from "@app/hooks/api/types";
-import { usePathAccessPolicies } from "@app/hooks/usePathAccessPolicies";
-import { useResizableColWidth } from "@app/hooks/useResizableColWidth";
-import { hasSecretReadValueOrDescribePermission } from "@app/lib/fn/permission";
-import { RequestAccessModal } from "@app/pages/secret-manager/SecretApprovalsPage/components/AccessApprovalRequest/components/RequestAccessModal";
-import { HoneyTokenListView } from "@app/pages/secret-manager/SecretDashboardPage/components/HoneyTokenListView";
-import { SecretRotationListView } from "@app/pages/secret-manager/SecretDashboardPage/components/SecretRotationListView";
-
-import { SecretTableResourceCount } from "../OverviewPage/components/SecretTableResourceCount";
-import { SecretV2MigrationSection } from "../OverviewPage/components/SecretV2MigrationSection";
-import { ActionBar } from "./components/ActionBar";
-import { CommitForm } from "./components/CommitForm";
-import { CreateSecretForm } from "./components/CreateSecretForm";
-import { DynamicSecretListView } from "./components/DynamicSecretListView";
-import { EnvironmentTabs } from "./components/EnvironmentTabs";
-import { FolderBreadCrumbs } from "./components/FolderBreadCrumbs";
-import { FolderListView } from "./components/FolderListView";
-import { SecretDropzone } from "./components/SecretDropzone";
-import { SecretImportListView } from "./components/SecretImportListView";
-import { SecretListView, SecretNoAccessListView } from "./components/SecretListView";
-import {
- PendingChanges,
- PopUpNames,
- StoreProvider,
- useBatchMode,
- useBatchModeActions,
- usePopUpAction,
- usePopUpState,
- useSelectedSecretActions,
- useSelectedSecrets
-} from "./SecretMainPage.store";
-import { Filter, RowType } from "./SecretMainPage.types";
-
-const LOADER_TEXT = [
- "Retrieving your encrypted secrets...",
- "Fetching folders...",
- "Getting secret import links..."
-];
-
-const Page = () => {
- const { currentOrg } = useOrganization();
- const { currentProject } = useProject();
- const navigate = useNavigate({
- from: ROUTE_PATHS.SecretManager.SecretDashboardPage.path
- });
- const routerQueryParams = useSearch({
- from: ROUTE_PATHS.SecretManager.SecretDashboardPage.id
- });
- const environment = useParams({
- from: ROUTE_PATHS.SecretManager.SecretDashboardPage.id,
- select: (el) => el.envSlug
- });
-
- const { permission } = useProjectPermission();
- const { mutateAsync: createCommit, isPending: isCommitPending } = useCreateCommit();
-
- const tableRef = useRef<HTMLTableElement>(null);
-
- const [isVisible, setIsVisible] = useState(false);
- const [selectedDynamicSecretId, setSelectedDynamicSecretId] = useState<string | null>(
- routerQueryParams.dynamicSecretId || ""
- );
- const { isBatchMode, pendingChanges } = useBatchMode();
- const { loadPendingChanges, setExistingKeys } = useBatchModeActions();
-
- const {
- offset,
- limit,
- orderDirection,
- setOrderDirection,
- setPage,
- perPage,
- page,
- setPerPage,
- orderBy
- } = usePagination<DashboardSecretsOrderBy>(DashboardSecretsOrderBy.Name, {
- initPerPage: getUserTablePreference("secretDashboardTable", PreferenceKey.PerPage, 100)
- });
-
- const handlePerPageChange = (newPerPage: number) => {
- setPerPage(newPerPage);
- setUserTablePreference("secretDashboardTable", PreferenceKey.PerPage, newPerPage);
- };
-
- const { popUp, handlePopUpClose, handlePopUpOpen } = usePopUp(["requestAccess"] as const);
-
- // env slug
- const projectId = currentProject?.id || "";
- const projectSlug = currentProject?.slug || "";
- const secretPath = (routerQueryParams.secretPath as string) || "/";
-
- useEffect(() => {
- if (isBatchMode && projectId && environment && secretPath) {
- loadPendingChanges({ projectId, environment, secretPath });
- }
- }, [isBatchMode, projectId, environment, secretPath, loadPendingChanges]);
-
- useEffect(() => {
- if (isVisible) setIsVisible(false);
- }, [environment]);
-
- useEffect(() => {
- if (routerQueryParams.dynamicSecretId !== null) {
- setSelectedDynamicSecretId(routerQueryParams.dynamicSecretId);
-
- navigate({
- search: (prev) => ({
- ...prev,
- dynamicSecretId: undefined
- })
- });
-
- // if any of the router query params are changed, we have to clear the selected dynamic secret id to avoid re-rendering the lease modal when it suddendly becomes available
- } else {
- setSelectedDynamicSecretId(null);
- }
- }, [
- routerQueryParams.filterBy,
- routerQueryParams.search,
- routerQueryParams.secretPath,
- routerQueryParams.tags
- ]);
-
- const canReadSecret = hasSecretReadValueOrDescribePermission(
- permission,
- ProjectPermissionSecretActions.DescribeSecret,
- {
- environment,
- secretPath,
- secretName: "*",
- secretTags: ["*"]
- }
- );
-
- const canEditSecrets = permission.can(
- ProjectPermissionSecretActions.Edit,
- subject(ProjectPermissionSub.Secrets, {
- environment,
- secretPath,
- secretName: "*",
- secretTags: ["*"]
- })
- );
-
- const canDeleteSecrets = permission.can(
- ProjectPermissionSecretActions.Delete,
- subject(ProjectPermissionSub.Secrets, {
- environment,
- secretPath,
- secretName: "*",
- secretTags: ["*"]
- })
- );
-
- const canReadSecretImports = permission.can(
- ProjectPermissionActions.Read,
- subject(ProjectPermissionSub.SecretImports, { environment, secretPath })
- );
-
- const canReadDynamicSecret = permission.can(
- ProjectPermissionDynamicSecretActions.ReadRootCredential,
- subject(ProjectPermissionSub.DynamicSecrets, { environment, secretPath, metadata: ["*"] })
- );
-
- const canReadSecretRotations = permission.can(
- ProjectPermissionSecretRotationActions.Read,
- subject(ProjectPermissionSub.SecretRotation, { environment, secretPath })
- );
-
- const canReadCommits = permission.can(
- ProjectPermissionCommitsActions.Read,
- ProjectPermissionSub.Commits
- );
-
- const getFilterStateFromQueryParams = useCallback(() => {
- const filterByArray = routerQueryParams.filterBy
- ? (routerQueryParams.filterBy as string).split(",").filter(Boolean)
- : [];
-
- const includeFilters = {
- [RowType.Folder]: filterByArray.includes("folder") || false,
- [RowType.Import]: filterByArray.includes("import") || false,
- [RowType.DynamicSecret]: filterByArray.includes("dynamic") || false,
- [RowType.Secret]: filterByArray.includes("secret") || false,
- [RowType.SecretRotation]: filterByArray.includes("rotation") || false
- };
-
- const tags = routerQueryParams.tags
- ? routerQueryParams.tags.split(",").reduce(
- (acc, tag) => {
- const trimmedTag = tag.trim();
- if (trimmedTag) {
- acc[trimmedTag] = true;
- }
- return acc;
- },
- {} as Record<string, boolean>
- )
- : {};
-
- return {
- tags,
- searchFilter: (routerQueryParams.search as string) || "",
- include: includeFilters
- };
- }, [routerQueryParams.search, routerQueryParams.tags, routerQueryParams.filterBy]);
-
- const defaultFilterState = getFilterStateFromQueryParams();
-
- const [filter, setFilter] = useState<Filter>(defaultFilterState);
- const [debouncedSearchFilter, setDebouncedSearchFilter] = useDebounce(filter.searchFilter);
-
- const createSecretPopUp = usePopUpState(PopUpNames.CreateSecretForm);
- const { togglePopUp } = usePopUpAction();
-
- useEffect(() => {
- if (!currentProject?.environments.find((env) => env.slug === environment)) {
- createNotification({
- text: "No environment found with given slug",
- type: "error"
- });
- navigate({
- to: "/organizations/$orgId/projects/secret-management/$projectId/overview",
- params: {
- orgId: currentOrg.id,
- projectId
- }
- });
- }
- }, [currentProject, environment]);
-
- const isResourceTypeFiltered = Object.values(filter.include).some(Boolean);
- const {
- data,
- isPending: isDetailsLoading,
- isFetching: isDetailsFetching,
- isFetched
- } = useGetProjectSecretsDetails({
- environment,
- projectId,
- secretPath,
- offset,
- limit,
- orderBy,
- search: debouncedSearchFilter,
- orderDirection,
- includeImports: canReadSecretImports && (isResourceTypeFiltered ? filter.include.import : true),
- includeFolders: isResourceTypeFiltered ? filter.include.folder : true,
- includeDynamicSecrets:
- canReadDynamicSecret && (isResourceTypeFiltered ? filter.include.dynamic : true),
- includeSecrets: canReadSecret && (isResourceTypeFiltered ? filter.include.secret : true),
- includeSecretRotations:
- canReadSecretRotations && (isResourceTypeFiltered ? filter.include.rotation : true),
- includeHoneyTokens: true,
- tags: filter.tags
- });
-
- useEffect(() => {
- // if switching tabs in a folder path that doesn't exist in a separate env we navigate to the root
- if (!data && isFetched) {
- navigate({
- search: (prev) => ({
- ...prev,
- secretPath: "/"
- })
- });
- }
- }, [data, isFetched]);
-
- const {
- imports,
- folders,
- dynamicSecrets,
- secretRotations,
- honeyTokens,
- secrets,
- totalImportCount = 0,
- totalFolderCount = 0,
- totalDynamicSecretCount = 0,
- totalSecretCount = 0,
- totalCount = 0,
- importedBy,
- usedBySecretSyncs,
- totalSecretRotationCount = 0
- } = data ?? {};
-
- useResetPageHelper({
- totalCount,
- offset,
- setPage
- });
-
- // fetch imported secrets to show user the overriden ones
- const { data: importedSecrets } = useGetImportedSecretsSingleEnv({
- projectId,
- environment,
- path: secretPath,
- options: {
- enabled: canReadSecret
- }
- });
-
- // fetch tags
- const { data: tags } = useGetWsTags(
- permission.can(ProjectPermissionActions.Read, ProjectPermissionSub.Tags) ? projectId : ""
- );
-
- const { pathPolicies, hasPathPolicies } = usePathAccessPolicies({ secretPath, environment });
-
- const { data: boardPolicy } = useGetSecretApprovalPolicyOfABoard({
- projectId,
- environment,
- secretPath
- });
- const isProtectedBranch = Boolean(boardPolicy);
-
- const handleCreateCommit = async (changes: PendingChanges, message: string) => {
- await createCommit({
- projectId,
- environment,
- secretPath,
- pendingChanges: changes,
- message
- });
-
- // Check if there are only folder changes (no secret changes)
- // Folder changes are not affected by approval policies, so they're saved directly
- const hasOnlyFolderChanges = changes.folders.length > 0 && changes.secrets.length === 0;
- const requiresApproval = isProtectedBranch && !hasOnlyFolderChanges;
-
- if (!requiresApproval) {
- changes.secrets.forEach((secret) => {
- if (secret.type === "update" && secret.secretValue !== undefined) {
- queryClient.setQueryData(
- dashboardKeys.getSecretValue({
- projectId,
- environment,
- secretPath,
- secretKey: secret.newSecretName ?? secret.secretKey,
- isOverride: false
- }),
- { value: secret.secretValue }
- );
- }
- });
- }
-
- createNotification({
- text: requiresApproval
- ? "Requested changes have been sent for review"
- : "Changes saved successfully",
- type: "success"
- });
- };
-
- const {
- data: { count: folderCommitsCount, folderId } = { count: 0, folderId: "" },
- isPending: isFolderCommitsCountLoading,
- isFetching: isFolderCommitsCountFetching
- } = useGetFolderCommitsCount({
- directory: secretPath,
- projectId,
- environment,
- isPaused: !canReadCommits
- });
-
- const handleOnClickRollbackMode = () => {
- navigate({
- to: "/organizations/$orgId/projects/secret-management/$projectId/commits/$environment/$folderId",
- params: {
- orgId: currentOrg.id,
- projectId,
- folderId,
- environment
- },
- search: (query) => ({
- ...query,
- secretPath
- })
- });
- };
-
- const noAccessSecretCount = Math.max(
- (page * perPage > totalCount ? totalCount % perPage : perPage) -
- (imports?.length || 0) -
- (folders?.length || 0) -
- (secrets?.length || 0) -
- (dynamicSecrets?.length || 0) -
- (secretRotations?.length || 0) -
- (honeyTokens?.length || 0),
- 0
- );
- const isNotEmpty = Boolean(
- secrets?.length ||
- folders?.length ||
- imports?.length ||
- dynamicSecrets?.length ||
- secretRotations?.length ||
- noAccessSecretCount ||
- pendingChanges.secrets.length ||
- pendingChanges.folders.length
- );
-
- useEffect(() => {
- if (data && isBatchMode) {
- const existingSecretKeys = [...(secrets?.map((s) => s.key) || [])];
-
- const existingFolderNames = folders?.map((f) => f.name) || [];
-
- setExistingKeys(existingSecretKeys, existingFolderNames);
- }
- }, [data, isBatchMode, setExistingKeys, secrets, importedSecrets, folders]);
-
- const handleSortToggle = () =>
- setOrderDirection((state) =>
- state === OrderByDirection.ASC ? OrderByDirection.DESC : OrderByDirection.ASC
- );
-
- const handleTagToggle = useCallback(
- (tagSlug: string) => {
- setFilter((state) => {
- const isTagPresent = Boolean(state.tags?.[tagSlug]);
- const newTagFilter = { ...state.tags };
- if (isTagPresent) delete newTagFilter[tagSlug];
- else newTagFilter[tagSlug] = true;
-
- // Update URL to match filter state
- const tagsList = Object.keys(newTagFilter).filter((tag) => newTagFilter[tag]);
- navigate({
- search: (prev) => ({
- ...prev,
- tags: tagsList.length > 0 ? tagsList.join(",") : ""
- })
- });
-
- return { ...state, tags: newTagFilter };
- });
- },
- [navigate]
- );
-
- const handleToggleRowType = useCallback(
- (rowType: RowType) => {
- setFilter((state) => {
- const newInclude = {
- ...state.include,
- [rowType]: !state.include[rowType]
- };
-
- // Update URL to match filter state
- const filterByList: string[] = [];
- if (newInclude[RowType.Folder]) filterByList.push("folder");
- if (newInclude[RowType.Import]) filterByList.push("import");
- if (newInclude[RowType.DynamicSecret]) filterByList.push("dynamic");
- if (newInclude[RowType.Secret]) filterByList.push("secret");
- if (newInclude[RowType.SecretRotation]) filterByList.push("rotation");
-
- navigate({
- search: (prev) => ({
- ...prev,
- filterBy: filterByList.length > 0 ? filterByList.join(",") : ""
- })
- });
-
- return {
- ...state,
- include: newInclude
- };
- });
- },
- [navigate]
- );
-
- const handleClearFilters = useCallback(() => {
- setFilter({
- searchFilter: "",
- tags: {},
- include: {
- [RowType.Folder]: false,
- [RowType.Import]: false,
- [RowType.DynamicSecret]: false,
- [RowType.Secret]: false,
- [RowType.SecretRotation]: false
- }
- });
- setDebouncedSearchFilter("");
- navigate({
- search: (prev) => ({
- ...prev,
- search: "",
- tags: "",
- filterBy: ""
- })
- });
- }, [navigate]);
-
- const handleSearchChange = useCallback(
- (searchFilter: string) => {
- setFilter((state) => ({ ...state, searchFilter }));
-
- // Update URL to match filter state
- navigate({
- search: (prev) => ({
- ...prev,
- search: searchFilter || ""
- })
- });
- },
- [navigate]
- );
-
- const handleToggleVisibility = useCallback(() => setIsVisible((state) => !state), []);
-
- const { handleMouseDown, isResizing, colWidth } = useResizableColWidth({
- initialWidth: 320,
- minWidth: 100,
- maxWidth: tableRef.current
- ? tableRef.current.clientWidth - 148 // ensure value column can't collapse completely
- : 800,
- ref: tableRef
- });
-
- useEffect(() => {
- const filterState = getFilterStateFromQueryParams();
- setFilter(filterState);
- setDebouncedSearchFilter(filterState.searchFilter);
- }, [getFilterStateFromQueryParams]);
-
- const selectedSecrets = useSelectedSecrets();
- const selectedSecretActions = useSelectedSecretActions();
-
- const allRowsSelectedOnPage = useMemo(() => {
- if (!secrets?.length) return { isChecked: false, isIndeterminate: false };
-
- if (secrets?.every((secret) => selectedSecrets[secret.id]))
- return { isChecked: true, isIndeterminate: false };
-
- if (secrets?.some((secret) => selectedSecrets[secret.id]))
- return { isChecked: true, isIndeterminate: true };
-
- return { isChecked: false, isIndeterminate: false };
- }, [selectedSecrets, secrets]);
-
- const toggleSelectAllRows = () => {
- const newChecks = { ...selectedSecrets };
-
- secrets?.forEach((secret) => {
- if (secret.isRotatedSecret || secret.isHoneyTokenSecret) return;
-
- if (allRowsSelectedOnPage.isChecked) {
- delete newChecks[secret.id];
- } else {
- newChecks[secret.id] = secret;
- }
- });
-
- selectedSecretActions.set(newChecks);
- };
-
- if (isDetailsLoading) {
- return <ContentLoader text={LOADER_TEXT} />;
- }
-
- const handleResetFilter = () => {
- setFilter(defaultFilterState);
- setDebouncedSearchFilter("");
- };
-
- const getMergedSecretsWithPending = (
- paramSecrets?: (SecretV3RawSanitized | null)[]
- ): SecretV3RawSanitized[] => {
- const sanitizedParamSecrets = paramSecrets?.filter(Boolean) as
- | SecretV3RawSanitized[]
- | undefined;
- if (!isBatchMode || pendingChanges.secrets.length === 0) {
- return sanitizedParamSecrets || secrets || [];
- }
-
- const mergedSecrets = [...(sanitizedParamSecrets || secrets || [])] as (SecretV3RawSanitized & {
- originalKey?: string;
- })[];
-
- pendingChanges.secrets.forEach((change) => {
- switch (change.type) {
- case PendingAction.Create:
- mergedSecrets.unshift({
- id: change.id,
- key: change.secretKey,
- value: change.secretValue,
- comment: change.secretComment || "",
- skipMultilineEncoding: change.skipMultilineEncoding || false,
- tags: change.tags || [],
- secretMetadata: change.secretMetadata || [],
- createdAt: new Date().toISOString(),
- updatedAt: new Date().toISOString(),
- version: 1,
- isPending: true,
- pendingAction: PendingAction.Create
- } as unknown as SecretV3RawSanitized);
- break;
-
- case PendingAction.Update:
- const updateIndex = mergedSecrets.findIndex((s) => s.key === change.secretKey);
- if (updateIndex >= 0) {
- mergedSecrets[updateIndex] = {
- ...mergedSecrets[updateIndex],
- key: change.newSecretName || change.secretKey,
- value:
- change.secretValue !== undefined
- ? change.secretValue
- : mergedSecrets[updateIndex].value,
- comment:
- change.secretComment !== undefined
- ? change.secretComment
- : mergedSecrets[updateIndex].comment,
- skipMultilineEncoding:
- change.skipMultilineEncoding !== undefined
- ? change.skipMultilineEncoding
- : mergedSecrets[updateIndex].skipMultilineEncoding,
- secretMetadata: change.secretMetadata || mergedSecrets[updateIndex].secretMetadata,
- isPending: true,
- pendingAction: PendingAction.Update,
- tags: change.tags
- ? change.tags?.map((tag) => ({
- id: tag.id,
- slug: tag.slug,
- projectId,
- createdAt: new Date().toISOString(),
- updatedAt: new Date().toISOString(),
- __v: 0
- })) || []
- : mergedSecrets[updateIndex].tags,
- originalKey: mergedSecrets[updateIndex].key
- };
- }
- break;
-
- case PendingAction.Delete:
- const deleteIndex = mergedSecrets.findIndex((s) => s.key === change.secretKey);
- if (deleteIndex >= 0) {
- mergedSecrets[deleteIndex] = {
- ...mergedSecrets[deleteIndex],
- isPending: true,
- pendingAction: PendingAction.Delete
- };
- }
- break;
-
- default:
- break;
- }
- });
-
- return mergedSecrets;
- };
-
- const getMergedFoldersWithPending = () => {
- if (!isBatchMode || pendingChanges.folders.length === 0) {
- return folders;
- }
-
- const mergedFolders = [...(folders || [])];
-
- pendingChanges.folders.forEach((change) => {
- switch (change.type) {
- case PendingAction.Create:
- mergedFolders.unshift({
- id: change.id,
- name: change.folderName,
- description: change.description,
- parentId: null,
- isPending: true,
- pendingAction: PendingAction.Create
- } as any);
- break;
-
- case PendingAction.Update:
- const updateIndex = mergedFolders.findIndex((f) => f.id === change.id);
- if (updateIndex >= 0) {
- mergedFolders[updateIndex] = {
- ...mergedFolders[updateIndex],
- name: change.folderName,
- description:
- change.description !== undefined
- ? change.description
- : mergedFolders[updateIndex].description,
- isPending: true,
- pendingAction: PendingAction.Update
- };
- }
- break;
-
- case PendingAction.Delete:
- const deleteIndex = mergedFolders.findIndex((f) => f.id === change.id);
- if (deleteIndex >= 0) {
- mergedFolders[deleteIndex] = {
- ...mergedFolders[deleteIndex],
- isPending: true,
- pendingAction: PendingAction.Delete
- };
- }
- break;
-
- default:
- break;
- }
- });
-
- return mergedFolders;
- };
-
- const mergedSecrets = getMergedSecretsWithPending();
- const mergedFolders = getMergedFoldersWithPending();
-
- if (!(currentProject?.version === ProjectVersion.V3))
- return (
- <div className="flex h-full w-full flex-col items-center justify-center px-6 text-mineshaft-50 dark:scheme-dark">
- <SecretV2MigrationSection />
- </div>
- );
-
- return (
- <div className="mx-auto flex max-w-8xl flex-col text-mineshaft-50 dark:scheme-dark">
- <Link
- to="/organizations/$orgId/projects/secret-management/$projectId/overview"
- params={{
- orgId: currentOrg.id,
- projectId
- }}
- className="mb-4 flex items-center gap-x-2 text-sm text-mineshaft-400"
- >
- <FontAwesomeIcon icon={faChevronLeft} />
- Secrets Overview
- </Link>
- <PageHeader
- scope={ProjectType.SecretManager}
- title="Secrets Management"
- description={
- <p className="text-md text-bunker-300">
- Inject your secrets using
- <a
- className="ml-1 text-mineshaft-300 underline decoration-primary-800 underline-offset-4 duration-200 hover:text-mineshaft-100 hover:decoration-primary-600"
- href="https://infisical.com/docs/cli/overview"
- target="_blank"
- rel="noopener noreferrer"
- >
- Infisical CLI
- </a>
- ,
- <a
- className="ml-1 text-mineshaft-300 underline decoration-primary-800 underline-offset-4 duration-200 hover:text-mineshaft-100 hover:decoration-primary-600"
- href="https://infisical.com/docs/api-reference/overview/introduction"
- target="_blank"
- rel="noopener noreferrer"
- >
- Infisical API
- </a>
- ,
- <a
- className="ml-1 text-mineshaft-300 underline decoration-primary-800 underline-offset-4 duration-200 hover:text-mineshaft-100 hover:decoration-primary-600"
- href="https://infisical.com/docs/sdks/overview"
- target="_blank"
- rel="noopener noreferrer"
- >
- Infisical SDKs
- </a>
- , and
- <a
- className="ml-1 text-mineshaft-300 underline decoration-primary-800 underline-offset-4 duration-200 hover:text-mineshaft-100 hover:decoration-primary-600"
- href="https://infisical.com/docs/documentation/getting-started/introduction"
- target="_blank"
- rel="noopener noreferrer"
- >
- more
- </a>
- .
- </p>
- }
- />
- <SecretV2MigrationSection />
- <FolderBreadCrumbs secretPath={secretPath} />
- <EnvironmentTabs secretPath={secretPath} />
- <ActionBar
- environment={environment}
- secretPath={secretPath}
- isVisible={isVisible}
- isBatchMode={isBatchMode}
- filter={filter}
- tags={tags}
- onVisibilityToggle={handleToggleVisibility}
- onSearchChange={handleSearchChange}
- onToggleTagFilter={handleTagToggle}
- commitCount={folderCommitsCount || 0}
- isCommitCountLoading={isFolderCommitsCountLoading && isFolderCommitsCountFetching}
- onToggleRowType={handleToggleRowType}
- onClickRollbackMode={handleOnClickRollbackMode}
- protectedBranchPolicyName={boardPolicy?.name}
- importedBy={importedBy}
- usedBySecretSyncs={usedBySecretSyncs}
- hasPathPolicies={hasPathPolicies}
- onRequestAccess={(params) => handlePopUpOpen("requestAccess", params)}
- onClearFilters={handleClearFilters}
- />
- <div
- ref={tableRef}
- className={twMerge(
- "mt-3 thin-scrollbar overflow-x-hidden overflow-y-auto rounded-md bg-mineshaft-800 text-left text-sm text-bunker-300",
- isNotEmpty && "rounded-b-none"
- )}
- >
- <div className="flex flex-col" id="dashboard">
- {isNotEmpty && (
- <div
- className={twMerge(
- "sticky top-0 flex border-b border-mineshaft-600 bg-mineshaft-800 font-medium"
- )}
- >
- <Tooltip
- className="max-w-[20rem] whitespace-nowrap"
- content={
- totalCount > 0
- ? `${
- !allRowsSelectedOnPage.isChecked ? "Select" : "Unselect"
- } all secrets on page`
- : ""
- }
- >
- <div className="mr-[0.055rem] flex w-11 items-center justify-center pl-2.5">
- <Checkbox
- isDisabled={totalCount === 0}
- id="checkbox-select-all-rows"
- onClick={(e) => e.stopPropagation()}
- isChecked={allRowsSelectedOnPage.isChecked}
- isIndeterminate={allRowsSelectedOnPage.isIndeterminate}
- onCheckedChange={toggleSelectAllRows}
- />
- </div>
- </Tooltip>
- <div className="relative">
- <div
- tabIndex={-1}
- role="button"
- className={`absolute -right-[0.05rem] z-40 h-full w-0.5 cursor-ew-resize hover:bg-blue-400/20 ${
- isResizing ? "bg-blue-400/75" : "bg-transparent"
- }`}
- onMouseDown={handleMouseDown}
- />
- <div className="pointer-events-none absolute top-2 -right-[0.04rem] z-30">
- <div className="h-5 w-0.5 rounded-[1.5px] bg-gray-400 opacity-50" />
- </div>
- <div
- className="flex shrink-0 items-center border-r border-mineshaft-600 py-2 pl-4"
- style={{ width: colWidth }}
- role="button"
- tabIndex={0}
- onClick={handleSortToggle}
- onKeyDown={(evt) => {
- if (evt.key === "Enter") handleSortToggle();
- }}
- >
- Key
- <FontAwesomeIcon
- icon={orderDirection === OrderByDirection.ASC ? faArrowDown : faArrowUp}
- className="ml-2"
- />
- </div>
- </div>
- <div className="grow px-4 py-2">Value</div>
- </div>
- )}
- {hasPathPolicies &&
- // eslint-disable-next-line no-nested-ternary
- (!canReadSecret ? (
- <div
- className={twMerge(
- "flex border-l-2 border-l-primary bg-mineshaft-700 px-4 py-2",
- isNotEmpty ? "border-b border-b-mineshaft-600" : ""
- )}
- >
- <div className="flex items-center text-sm">
- <FontAwesomeIcon
- icon={faInfoCircle}
- className="mr-[1.65rem] ml-[0.15rem] text-primary"
- />
- <span>You do not have permission to read secrets in this folder</span>
- </div>
- <Button
- variant="outline_bg"
- size="xs"
- className="ml-auto"
- onClick={() => handlePopUpOpen("requestAccess", [ProjectPermissionActions.Read])}
- >
- Request Access
- </Button>
- </div>
- ) : !canEditSecrets || !canDeleteSecrets ? (
- <div className="flex border-b border-l-2 border-b-mineshaft-600 border-l-primary bg-mineshaft-700 px-4 py-2">
- <div className="flex items-center text-sm">
- <FontAwesomeIcon
- icon={faInfoCircle}
- className="mr-[1.65rem] ml-[0.15rem] text-primary"
- />
- <span>
- You do not have permission to {!canEditSecrets ? "edit" : ""}
- {!canEditSecrets && !canDeleteSecrets ? " or " : ""}
- {!canDeleteSecrets ? "delete" : ""} secrets in this folder
- </span>
- </div>
- <Button
- variant="outline_bg"
- size="xs"
- className="ml-auto"
- onClick={() =>
- handlePopUpOpen("requestAccess", [
- ...(!canEditSecrets ? [ProjectPermissionActions.Edit] : []),
- ...(!canDeleteSecrets ? [ProjectPermissionActions.Delete] : [])
- ])
- }
- >
- Request Access
- </Button>
- </div>
- ) : null)}
-
- {canReadSecretImports && Boolean(imports?.length) && (
- <SecretImportListView
- searchTerm={debouncedSearchFilter}
- secretImports={imports}
- isFetching={isDetailsFetching}
- environment={environment}
- projectId={projectId}
- secretPath={secretPath}
- importedSecrets={importedSecrets}
- />
- )}
- {Boolean(mergedFolders?.length) && (
- <FolderListView
- folders={mergedFolders}
- environment={environment}
- projectId={projectId}
- secretPath={secretPath}
- onNavigateToFolder={handleResetFilter}
- canNavigate={isFetched}
- />
- )}
- {canReadDynamicSecret && Boolean(dynamicSecrets?.length) && (
- <DynamicSecretListView
- selectedDynamicSecretId={selectedDynamicSecretId}
- environment={environment}
- projectSlug={projectSlug}
- secretPath={secretPath}
- dynamicSecrets={dynamicSecrets}
- />
- )}
- {canReadSecretRotations && Boolean(secretRotations?.length) && (
- <SecretRotationListView
- secretRotations={secretRotations}
- colWidth={colWidth}
- tags={tags}
- projectId={projectId}
- secretPath={secretPath}
- isProtectedBranch={isProtectedBranch}
- importedBy={importedBy}
- usedBySecretSyncs={usedBySecretSyncs}
- getMergedSecretsWithPending={getMergedSecretsWithPending}
- />
- )}
- {Boolean(honeyTokens?.length) && <HoneyTokenListView honeyTokens={honeyTokens} />}
- {canReadSecret && Boolean(mergedSecrets?.length) && (
- <SecretListView
- colWidth={colWidth}
- secrets={mergedSecrets}
- tags={tags}
- isVisible={isVisible}
- environment={environment}
- projectId={projectId}
- secretPath={secretPath}
- isProtectedBranch={isProtectedBranch}
- importedBy={importedBy}
- usedBySecretSyncs={usedBySecretSyncs}
- />
- )}
- {(pendingChanges.secrets.length > 0 || pendingChanges.folders.length > 0) && (
- <CommitForm
- onCommit={handleCreateCommit}
- environment={environment}
- projectId={projectId}
- secretPath={secretPath}
- isCommitting={isCommitPending}
- />
- )}
- {noAccessSecretCount > 0 && <SecretNoAccessListView count={noAccessSecretCount} />}
- </div>
- </div>
- {!canReadSecret &&
- !canReadDynamicSecret &&
- !canReadSecretImports &&
- folders?.length === 0 && <PermissionDeniedBanner />}
- {!isDetailsLoading &&
- (totalCount > 0 ||
- pendingChanges.secrets.length > 0 ||
- pendingChanges.folders.length > 0) && (
- <Pagination
- startAdornment={
- <SecretTableResourceCount
- dynamicSecretCount={totalDynamicSecretCount}
- importCount={totalImportCount}
- secretCount={
- totalSecretCount +
- pendingChanges.secrets.filter((s) => s.type === PendingAction.Create).length
- }
- folderCount={
- totalFolderCount +
- pendingChanges.folders.filter((f) => f.type === PendingAction.Create).length
- }
- secretRotationCount={totalSecretRotationCount}
- />
- }
- className="rounded-b-md border-t border-solid border-t-mineshaft-600"
- count={totalCount + pendingChanges.secrets.length + pendingChanges.folders.length}
- page={page}
- perPage={perPage}
- onChangePage={(newPage) => setPage(newPage)}
- onChangePerPage={handlePerPageChange}
- />
- )}
- <Modal
- isOpen={createSecretPopUp.isOpen}
- onOpenChange={(state) => togglePopUp(PopUpNames.CreateSecretForm, state)}
- >
- <ModalContent
- title="Create Secret"
- subTitle="Add a secret to this particular environment and folder"
- bodyClassName="overflow-visible"
- >
- <CreateSecretForm
- environment={environment}
- projectId={projectId}
- secretPath={secretPath}
- autoCapitalize={currentProject?.autoCapitalization}
- isProtectedBranch={isProtectedBranch}
- isBatchMode={isBatchMode}
- />
- </ModalContent>
- </Modal>
- {!!pathPolicies && (
- <RequestAccessModal
- policies={pathPolicies}
- isOpen={popUp.requestAccess.isOpen}
- onOpenChange={() => {
- handlePopUpClose("requestAccess");
- }}
- selectedActions={popUp.requestAccess.data}
- secretPath={pathPolicies?.[0]?.secretPath}
- environment={environment}
- />
- )}
- <SecretDropzone
- environment={environment}
- projectId={projectId}
- secretPath={secretPath}
- isSmaller={isNotEmpty}
- environments={currentProject?.environments}
- />
- </div>
- );
-};
-
-export const SecretDashboardPage = () => {
- const { t } = useTranslation();
-
- return (
- <>
- <Helmet>
- <title>{t("common.head-title", { title: t("dashboard.title") })}</title>
- <link rel="icon" href="/infisical.ico" />
- <meta property="og:image" content="/images/message.png" />
- <meta property="og:title" content={String(t("dashboard.og-title"))} />
- <meta name="og:description" content={String(t("dashboard.og-description"))} />
- </Helmet>
- <div className="h-full">
- <StoreProvider>
- <Page />
- </StoreProvider>
- </div>
- </>
- );
-};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/ActionBar.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/ActionBar.tsx
deleted file mode 100644
index a5cadd9c57..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/ActionBar.tsx
+++ /dev/null
@@ -1,1383 +0,0 @@
-import { useMemo } from "react";
-import { subject } from "@casl/ability";
-import {
- faAngleDown,
- faAnglesRight,
- faCheckCircle,
- faChevronRight,
- faCodeCommit,
- faDownload,
- faEye,
- faEyeSlash,
- faFileImport,
- faFilter,
- faFingerprint,
- faFolder,
- faFolderPlus,
- faInfoCircle,
- faKey,
- faLock,
- faPaste,
- faPlus,
- faRotate,
- faTrash
-} from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import { useQueryClient } from "@tanstack/react-query";
-import { AxiosError } from "axios";
-import FileSaver from "file-saver";
-import { twMerge } from "tailwind-merge";
-
-import { UpgradePlanModal } from "@app/components/license/UpgradePlanModal";
-import { createNotification, type NotificationType } from "@app/components/notifications";
-import { ProjectPermissionCan } from "@app/components/permissions";
-import { CreateSecretRotationV2Modal } from "@app/components/secret-rotations-v2";
-import {
- Button,
- DeleteActionModal,
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuGroup,
- DropdownMenuItem,
- DropdownMenuLabel,
- DropdownMenuTrigger,
- DropdownSubMenu,
- DropdownSubMenuContent,
- DropdownSubMenuTrigger,
- IconButton,
- Modal,
- ModalClose,
- ModalContent,
- Tooltip
-} from "@app/components/v2";
-import {
- Badge,
- Dialog,
- DialogContent,
- DialogDescription,
- DialogHeader,
- DialogTitle,
- SelectedActionBar
-} from "@app/components/v3";
-import {
- ProjectPermissionActions,
- ProjectPermissionDynamicSecretActions,
- ProjectPermissionSub,
- useProject,
- useProjectPermission,
- useSubscription
-} from "@app/context";
-import {
- ProjectPermissionCommitsActions,
- ProjectPermissionSecretActions,
- ProjectPermissionSecretRotationActions
-} from "@app/context/ProjectPermissionContext/types";
-import { useCanUseProjectAppConnectionImport, usePopUp } from "@app/hooks";
-import {
- useCreateFolder,
- useCreateSecretBatch,
- useDeleteSecretBatch,
- useMoveSecrets,
- useUpdateSecretBatch
-} from "@app/hooks/api";
-import { useListAvailableAppConnections } from "@app/hooks/api/appConnections";
-import { AppConnection } from "@app/hooks/api/appConnections/enums";
-import {
- dashboardKeys,
- fetchDashboardProjectSecretsByKeys
-} from "@app/hooks/api/dashboard/queries";
-import { UsedBySecretSyncs } from "@app/hooks/api/dashboard/types";
-import { useImportVaultSecrets } from "@app/hooks/api/migration";
-import { ExternalMigrationImportStatus } from "@app/hooks/api/migration/types";
-import { secretApprovalRequestKeys } from "@app/hooks/api/secretApprovalRequest/queries";
-import { PendingAction } from "@app/hooks/api/secretFolders/types";
-import { fetchProjectSecrets, secretKeys } from "@app/hooks/api/secrets/queries";
-import { ApiErrorTypes, SecretType, TApiErrors, WsTag } from "@app/hooks/api/types";
-import { SecretSearchInput } from "@app/pages/secret-manager/OverviewPage/components/SecretSearchInput";
-
-import {
- PendingFolderCreate,
- PopUpNames,
- useBatchModeActions,
- usePopUpAction,
- useSelectedSecretActions,
- useSelectedSecrets
-} from "../../SecretMainPage.store";
-import { Filter, RowType } from "../../SecretMainPage.types";
-import { CollapsibleSecretImports } from "../SecretListView/CollapsibleSecretImports";
-import { ReplicateFolderFromBoard } from "./ReplicateFolderFromBoard/ReplicateFolderFromBoard";
-import { CreateDynamicSecretForm } from "./CreateDynamicSecretForm";
-import { CreateSecretImportForm } from "./CreateSecretImportForm";
-import { FolderForm } from "./FolderForm";
-import { MoveSecretsModal } from "./MoveSecretsModal";
-import { VaultSecretImportModal } from "./VaultSecretImportModal";
-
-type TParsedEnv = { value: string; comments: string[]; secretPath?: string; secretKey: string }[];
-type TParsedFolderEnv = Record<
- string,
- Record<string, { value: string; comments: string[]; secretPath?: string }>
->;
-type TSecOverwriteOpt = { update: TParsedEnv; create: TParsedEnv };
-
-type Props = {
- // switch the secrets type as it gets decrypted after api call
- environment: string;
- secretPath?: string;
- filter: Filter;
- tags?: WsTag[];
- isVisible?: boolean;
- isBatchMode?: boolean;
- commitCount: number;
- isCommitCountLoading?: boolean;
- protectedBranchPolicyName?: string;
- onSearchChange: (term: string) => void;
- onToggleTagFilter: (tagId: string) => void;
- onVisibilityToggle: () => void;
- onToggleRowType: (rowType: RowType) => void;
- onClickRollbackMode: () => void;
- usedBySecretSyncs?: UsedBySecretSyncs[];
- importedBy?: {
- environment: { name: string; slug: string };
- folders: {
- name: string;
- secrets?: { secretId: string; referencedSecretKey: string; referencedSecretEnv: string }[];
- isImported: boolean;
- }[];
- }[];
- onRequestAccess: (actions: ProjectPermissionActions[]) => void;
- hasPathPolicies: boolean;
- onClearFilters: () => void;
-};
-
-export const ActionBar = ({
- environment,
- secretPath = "/",
- filter,
- tags = [],
- isVisible,
- isBatchMode,
- commitCount,
- isCommitCountLoading,
- onSearchChange,
- onToggleTagFilter,
- onVisibilityToggle,
- onClickRollbackMode,
- onToggleRowType,
- protectedBranchPolicyName,
- importedBy,
- usedBySecretSyncs,
- onRequestAccess,
- hasPathPolicies,
- onClearFilters
-}: Props) => {
- const { projectId, currentProject } = useProject();
- const { handlePopUpOpen, handlePopUpToggle, handlePopUpClose, popUp } = usePopUp([
- "addFolder",
- "addDynamicSecret",
- "addSecretImport",
- "bulkDeleteSecrets",
- "addSecretRotation",
- "moveSecrets",
- "misc",
- "upgradePlan",
- "replicateFolder",
- "confirmUpload",
- "requestAccess",
- "importFromVault"
- ] as const);
- const isProtectedBranch = Boolean(protectedBranchPolicyName);
- const { subscription } = useSubscription();
- const { openPopUp } = usePopUpAction();
- const { mutateAsync: createFolder } = useCreateFolder();
- const { mutateAsync: deleteBatchSecretV3 } = useDeleteSecretBatch();
- const { mutateAsync: moveSecrets } = useMoveSecrets();
- const { mutateAsync: updateSecretBatch, isPending: isUpdatingSecrets } = useUpdateSecretBatch({
- options: { onSuccess: undefined }
- });
- const { mutateAsync: createSecretBatch, isPending: isCreatingSecrets } = useCreateSecretBatch({
- options: { onSuccess: undefined }
- });
- const { mutateAsync: importVaultSecrets } = useImportVaultSecrets();
- const queryClient = useQueryClient();
- const { addPendingChange } = useBatchModeActions();
-
- const selectedSecrets = useSelectedSecrets();
- const { reset: resetSelectedSecret } = useSelectedSecretActions();
- const isManagedSecretSelected = Object.values(selectedSecrets).some(
- (secret) => secret.isRotatedSecret || secret.isHoneyTokenSecret
- );
- const isHoneyTokenSelected = Object.values(selectedSecrets).some(
- (secret) => secret.isHoneyTokenSecret
- );
-
- const { permission } = useProjectPermission();
- const vaultSecretSubject = useMemo(
- () =>
- subject(ProjectPermissionSub.Secrets, {
- environment,
- secretPath,
- secretName: "*",
- secretTags: ["*"]
- }),
- [environment, secretPath]
- );
- const canUseAppConnectionImport = useCanUseProjectAppConnectionImport(vaultSecretSubject);
- const { data: vaultAppConnections = [] } = useListAvailableAppConnections(
- AppConnection.HCVault,
- projectId,
- { enabled: canUseAppConnectionImport }
- );
- const hasVaultConnection = vaultAppConnections.length > 0;
-
- const handleFolderCreate = async (folderName: string, description: string | null) => {
- if (isBatchMode) {
- const folderId = `${folderName}`;
- const pendingFolderCreate: PendingFolderCreate = {
- id: folderId,
- resourceType: "folder",
- type: PendingAction.Create,
- folderName,
- description: description || undefined,
- parentPath: secretPath,
- timestamp: Date.now()
- };
-
- addPendingChange(pendingFolderCreate, {
- projectId,
- environment,
- secretPath
- });
-
- handlePopUpClose("addFolder");
- return;
- }
-
- await createFolder({
- name: folderName,
- path: secretPath,
- environment,
- projectId,
- description
- });
- handlePopUpClose("addFolder");
- createNotification({
- type: "success",
- text: "Successfully created folder"
- });
- };
-
- const handleSecretDownload = async () => {
- try {
- const { secrets: localSecrets, imports: localImportedSecrets } = await fetchProjectSecrets({
- projectId,
- expandSecretReferences: true,
- includeImports: true,
- environment,
- secretPath
- });
- const secretsPicked = new Set<string>();
- const secretsToDownload: { key: string; value?: string; comment?: string }[] = [];
- localSecrets.forEach((el) => {
- secretsPicked.add(el.secretKey);
- secretsToDownload.push({
- key: el.secretKey,
- value: el.secretValue,
- comment: el.secretComment
- });
- });
-
- for (let i = localImportedSecrets.length - 1; i >= 0; i -= 1) {
- for (let j = localImportedSecrets[i].secrets.length - 1; j >= 0; j -= 1) {
- const secret = localImportedSecrets[i].secrets[j];
- if (!secretsPicked.has(secret.secretKey)) {
- secretsToDownload.push({
- key: secret.secretKey,
- value: secret.secretValue,
- comment: secret.secretComment
- });
- }
- secretsPicked.add(secret.secretKey);
- }
- }
-
- const file = secretsToDownload
- .sort((a, b) => a.key.toLowerCase().localeCompare(b.key.toLowerCase()))
- .reduce(
- (prev, { key, comment, value }, index) =>
- prev +
- (comment
- ? `${index === 0 ? "#" : "\n#"} ${comment}\n${key}=${value}\n`
- : `${key}=${value}\n`),
- ""
- );
-
- const blob = new Blob([file], { type: "text/plain;charset=utf-8" });
- FileSaver.saveAs(blob, `${environment}.env`);
- } catch (err) {
- if (err instanceof AxiosError) {
- const error = err?.response?.data as TApiErrors;
-
- if (error?.error === ApiErrorTypes.ForbiddenError && error.message.includes("readValue")) {
- createNotification({
- title: "You don't have permission to download secrets",
- text: "You don't have permission to view one or more of the secrets in the current folder. Please contact your administrator.",
- type: "error"
- });
- return;
- }
- }
- createNotification({
- title: "Failed to download secrets",
- text: "Please try again later.",
- type: "error"
- });
- }
- };
-
- const handleSecretBulkDelete = async () => {
- const bulkDeletedSecrets = Object.values(selectedSecrets);
- await deleteBatchSecretV3({
- secretPath,
- projectId,
- environment,
- secrets: bulkDeletedSecrets.map(({ key }) => ({ secretKey: key, type: SecretType.Shared }))
- });
- resetSelectedSecret();
- handlePopUpClose("bulkDeleteSecrets");
- createNotification({
- type: "success",
- text: "Successfully deleted secrets"
- });
- };
-
- const handleSecretsMove = async ({
- destinationEnvironment,
- destinationSecretPath,
- shouldOverwrite
- }: {
- destinationEnvironment: string;
- destinationSecretPath: string;
- shouldOverwrite: boolean;
- }) => {
- try {
- const secretsToMove = Object.values(selectedSecrets);
- const { isDestinationUpdated, isSourceUpdated } = await moveSecrets({
- shouldOverwrite,
- sourceEnvironment: environment,
- sourceSecretPath: secretPath,
- destinationEnvironment,
- destinationSecretPath,
- projectId,
- projectSlug: currentProject.slug,
- secretIds: secretsToMove.map((sec) => sec.id)
- });
-
- let notificationMessage = "";
- let notificationType: NotificationType = "info";
-
- if (isDestinationUpdated && isSourceUpdated) {
- notificationMessage = "Successfully moved selected secrets";
- notificationType = "success";
- } else if (isDestinationUpdated) {
- notificationMessage =
- "Successfully created secrets in destination. A secret approval request has been generated for the source.";
- } else if (isSourceUpdated) {
- notificationMessage = "A secret approval request has been generated in the destination";
- } else {
- notificationMessage =
- "A secret approval request has been generated in both the source and the destination.";
- }
-
- createNotification({
- type: notificationType,
- text: notificationMessage
- });
-
- resetSelectedSecret();
- } catch (error) {
- console.error(error);
- }
- };
-
- // Replicate Secrets Logic
- const createSecretCount = Object.keys(
- (popUp.confirmUpload?.data as TSecOverwriteOpt)?.create || {}
- ).length;
-
- const updateSecretCount = Object.keys(
- (popUp.confirmUpload?.data as TSecOverwriteOpt)?.update || {}
- ).length;
-
- const isNonConflictingUpload = !updateSecretCount;
- const isSubmitting = isCreatingSecrets || isUpdatingSecrets;
-
- const handleParsedEnvMultiFolder = async (envByPath: TParsedFolderEnv) => {
- if (Object.keys(envByPath).length === 0) {
- createNotification({
- type: "error",
- text: "Failed to find secrets"
- });
- return;
- }
-
- try {
- const allUpdateSecrets: TParsedEnv = [];
- const allCreateSecrets: TParsedEnv = [];
-
- await Promise.all(
- Object.entries(envByPath).map(async ([folderPath, secrets]) => {
- // Normalize the path
- let normalizedPath = folderPath;
-
- // If the path is "/", use the current secretPath
- if (normalizedPath === "/") {
- normalizedPath = secretPath;
- } else {
- // Otherwise, concatenate with the current secretPath, avoiding double slashes
- const baseSecretPath = secretPath.endsWith("/") ? secretPath.slice(0, -1) : secretPath;
- // Remove leading slash from folder path if present to avoid double slashes
- const cleanFolderPath = folderPath.startsWith("/")
- ? folderPath.substring(1)
- : folderPath;
- normalizedPath = `${baseSecretPath}/${cleanFolderPath}`;
- }
-
- const secretFolderKeys = Object.keys(secrets);
-
- if (secretFolderKeys.length === 0) return;
-
- // Check which secrets already exist in this path
- const batchSize = 50;
- const secretBatches = Array.from(
- { length: Math.ceil(secretFolderKeys.length / batchSize) },
- (_, i) => secretFolderKeys.slice(i * batchSize, (i + 1) * batchSize)
- );
-
- const existingSecretLookup = new Set<string>();
-
- const processBatches = async () => {
- await secretBatches.reduce(async (previous, batch) => {
- await previous;
- try {
- const { secrets: batchSecrets } = await fetchDashboardProjectSecretsByKeys({
- secretPath: normalizedPath,
- environment,
- projectId,
- keys: batch
- });
-
- batchSecrets.forEach((secret) => {
- existingSecretLookup.add(`${normalizedPath}-${secret.secretKey}`);
- });
- } catch (error) {
- if (!(error instanceof AxiosError && error.response?.status === 404)) {
- throw error;
- }
- }
- }, Promise.resolve());
- };
-
- await processBatches();
-
- // Categorize each secret as update or create
- secretFolderKeys.forEach((secretKey) => {
- const secretData = secrets[secretKey];
-
- // Store the path with the secret for later batch processing
- const secretWithPath = {
- ...secretData,
- secretPath: normalizedPath,
- secretKey
- };
-
- if (existingSecretLookup.has(`${normalizedPath}-${secretKey}`)) {
- allUpdateSecrets.push(secretWithPath);
- } else {
- allCreateSecrets.push(secretWithPath);
- }
- });
- })
- );
- handlePopUpOpen("confirmUpload", {
- update: allUpdateSecrets,
- create: allCreateSecrets
- });
- } catch (e) {
- console.error(e);
- createNotification({
- text: "Failed to check for secret conflicts",
- type: "error"
- });
- handlePopUpClose("confirmUpload");
- }
- };
-
- const handleSaveFolderImport = async () => {
- const { update, create } = popUp?.confirmUpload?.data as TSecOverwriteOpt;
- try {
- // Group secrets by their path for batch operations
- const groupedCreateSecrets: Record<
- string,
- Array<{
- type: SecretType;
- secretComment: string;
- secretValue: string;
- secretKey: string;
- }>
- > = {};
-
- const groupedUpdateSecrets: Record<
- string,
- Array<{
- type: SecretType;
- secretComment: string;
- secretValue: string;
- secretKey: string;
- }>
- > = {};
-
- // Collect all unique paths that need folders to be created
- const allPaths = new Set<string>();
-
- // Add paths from create secrets
- create.forEach((secData) => {
- if (secData.secretPath && secData.secretPath !== secretPath) {
- allPaths.add(secData.secretPath);
- }
- });
-
- // Create a map of folder paths to their folder name (last segment)
- const folderPaths = Array.from(allPaths).map((path) => {
- // Remove trailing slash if it exists
- const normalizedPath = path.endsWith("/") ? path.slice(0, -1) : path;
- // Split by '/' to get path segments
- const segments = normalizedPath.split("/");
- // Get the last segment as the folder name
- const folderName = segments[segments.length - 1];
- // Get the parent path (everything except the last segment)
- const parentPath = segments.slice(0, -1).join("/");
-
- return {
- folderName,
- fullPath: normalizedPath,
- parentPath: parentPath || "/"
- };
- });
-
- // Sort paths by depth (shortest first) to ensure parent folders are created before children
- folderPaths.sort(
- (a, b) => (a.fullPath.match(/\//g) || []).length - (b.fullPath.match(/\//g) || []).length
- );
-
- // Track created folders to avoid duplicates
- const createdFolders = new Set<string>();
-
- // Create all necessary folders in order using Promise.all and reduce
- await folderPaths.reduce(async (previousPromise, { folderName, fullPath, parentPath }) => {
- // Wait for the previous promise to complete
- await previousPromise;
-
- // Skip if we've already created this folder
- if (createdFolders.has(fullPath)) return Promise.resolve();
-
- try {
- await createFolder({
- name: folderName,
- path: parentPath,
- environment,
- projectId
- });
-
- createdFolders.add(fullPath);
- } catch (err) {
- console.log(`Folder ${folderName} may already exist:`, err);
- }
-
- return Promise.resolve();
- }, Promise.resolve());
-
- if (create.length > 0) {
- create.forEach((secData) => {
- // Use the stored secretPath or fall back to the current secretPath
- const path = secData.secretPath || secretPath;
-
- if (!groupedCreateSecrets[path]) {
- groupedCreateSecrets[path] = [];
- }
-
- groupedCreateSecrets[path].push({
- type: SecretType.Shared,
- secretComment: secData.comments.join("\n"),
- secretValue: secData.value,
- secretKey: secData.secretKey
- });
- });
-
- await Promise.all(
- Object.entries(groupedCreateSecrets).map(([path, secrets]) =>
- createSecretBatch({
- secretPath: path,
- projectId,
- environment,
- secrets
- })
- )
- );
- }
-
- if (update.length > 0) {
- update.forEach((secData) => {
- // Use the stored secretPath or fall back to the current secretPath
- const path = secData.secretPath || secretPath;
-
- if (!groupedUpdateSecrets[path]) {
- groupedUpdateSecrets[path] = [];
- }
-
- groupedUpdateSecrets[path].push({
- type: SecretType.Shared,
- secretComment: secData.comments.join("\n"),
- secretValue: secData.value,
- secretKey: secData.secretKey
- });
- });
-
- // Update secrets for each path in parallel
- await Promise.all(
- Object.entries(groupedUpdateSecrets).map(([path, secrets]) =>
- updateSecretBatch({
- secretPath: path,
- projectId,
- environment,
- secrets
- })
- )
- );
- }
-
- // Invalidate appropriate queries to refresh UI
- queryClient.invalidateQueries({
- queryKey: secretKeys.getProjectSecret({ projectId, environment, secretPath })
- });
- queryClient.invalidateQueries({});
- dashboardKeys.getDashboardSecrets({ projectId, secretPath });
- queryClient.invalidateQueries({
- queryKey: secretApprovalRequestKeys.count({ projectId })
- });
- queryClient.invalidateQueries({
- queryKey: secretApprovalRequestKeys.listAllForProject({ projectId })
- });
-
- handlePopUpClose("confirmUpload");
- createNotification({
- type: "success",
- text: isProtectedBranch
- ? "Uploaded changes have been sent for review"
- : "Successfully uploaded secrets"
- });
- } catch (err) {
- console.log(err);
- createNotification({
- type: "error",
- text: "Failed to upload secrets"
- });
- }
- };
-
- const handleVaultImport = async (
- vaultPaths: string[],
- namespace: string,
- connectionId: string
- ) => {
- const { status } = await importVaultSecrets({
- projectId,
- environment,
- secretPath,
- vaultNamespace: namespace,
- vaultSecretPaths: vaultPaths,
- connectionId
- });
-
- if (status === ExternalMigrationImportStatus.ApprovalRequired) {
- createNotification({
- type: "info",
- text:
- vaultPaths.length > 1
- ? `Secret change request created for ${vaultPaths.length} Vault paths. Awaiting approval.`
- : "Secret change request created successfully. Awaiting approval."
- });
- } else {
- createNotification({
- type: "success",
- text:
- vaultPaths.length > 1
- ? `Successfully imported secrets from ${vaultPaths.length} HashiCorp Vault paths`
- : "Successfully imported secrets from HashiCorp Vault"
- });
- }
- };
-
- const isTableFiltered =
- Object.values(filter.tags).some(Boolean) || Object.values(filter.include).some(Boolean);
-
- const filteredTags = Object.values(filter?.tags ?? {}).filter(Boolean).length;
-
- return (
- <>
- <div className="mt-4 flex flex-wrap items-center gap-2">
- <SecretSearchInput
- isSingleEnv
- className="w-2/5"
- value={filter.searchFilter}
- onChange={onSearchChange}
- environments={[currentProject.environments.find((env) => env.slug === environment)!]}
- projectId={projectId}
- tags={tags}
- />
- <div>
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button
- size="sm"
- variant="outline_bg"
- className={twMerge(
- "flex h-10",
- isTableFiltered && "border-primary/40 bg-primary/10"
- )}
- leftIcon={
- <FontAwesomeIcon
- icon={faFilter}
- className={isTableFiltered ? "text-primary/80" : undefined}
- />
- }
- >
- Filters
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end" sideOffset={2} className="p-0">
- <DropdownMenuGroup>Filter By</DropdownMenuGroup>
- <DropdownMenuItem
- onClick={(e) => {
- e.preventDefault();
- onToggleRowType(RowType.Import);
- }}
- icon={filter?.include[RowType.Import] && <FontAwesomeIcon icon={faCheckCircle} />}
- iconPos="right"
- >
- <div className="flex items-center gap-2">
- <FontAwesomeIcon icon={faFileImport} className="text-green-700" />
- <span>Imports</span>
- </div>
- </DropdownMenuItem>
- <DropdownMenuItem
- onClick={(e) => {
- e.preventDefault();
- onToggleRowType(RowType.Folder);
- }}
- icon={filter?.include[RowType.Folder] && <FontAwesomeIcon icon={faCheckCircle} />}
- iconPos="right"
- >
- <div className="flex items-center gap-2">
- <FontAwesomeIcon icon={faFolder} className="text-yellow-700" />
- <span>Folders</span>
- </div>
- </DropdownMenuItem>
- <DropdownMenuItem
- onClick={(e) => {
- e.preventDefault();
- onToggleRowType(RowType.DynamicSecret);
- }}
- icon={
- filter?.include[RowType.DynamicSecret] && <FontAwesomeIcon icon={faCheckCircle} />
- }
- iconPos="right"
- >
- <div className="flex items-center gap-2">
- <FontAwesomeIcon icon={faFingerprint} className="text-yellow-700" />
- <span>Dynamic Secrets</span>
- </div>
- </DropdownMenuItem>
- <DropdownMenuItem
- onClick={(e) => {
- e.preventDefault();
- onToggleRowType(RowType.SecretRotation);
- }}
- icon={
- filter?.include[RowType.SecretRotation] && (
- <FontAwesomeIcon icon={faCheckCircle} />
- )
- }
- iconPos="right"
- >
- <div className="flex items-center gap-2">
- <FontAwesomeIcon icon={faRotate} className="text-mineshaft-400" />
- <span>Secret Rotations</span>
- </div>
- </DropdownMenuItem>
- <DropdownMenuItem
- onClick={(e) => {
- e.preventDefault();
- onToggleRowType(RowType.Secret);
- }}
- icon={filter?.include[RowType.Secret] && <FontAwesomeIcon icon={faCheckCircle} />}
- iconPos="right"
- >
- <div className="flex items-center gap-2">
- <FontAwesomeIcon icon={faKey} className="text-bunker-300" />
- <span>Secrets</span>
- </div>
- </DropdownMenuItem>
- {Boolean(tags.length) && (
- <DropdownSubMenu>
- <DropdownSubMenuTrigger
- iconPos="right"
- icon={<FontAwesomeIcon icon={faChevronRight} size="sm" />}
- >
- <div className="flex w-full justify-between">
- <span>Tags</span>
- {Boolean(filteredTags) && (
- <Badge variant="info">{filteredTags} Applied</Badge>
- )}
- </div>
- </DropdownSubMenuTrigger>
- <DropdownSubMenuContent className="max-h-80 thin-scrollbar overflow-y-auto rounded-l-none">
- <DropdownMenuLabel className="sticky top-0 bg-mineshaft-900">
- <div className="flex w-full items-center justify-between">
- <span>Filter by Secret Tags</span>
- <Tooltip content="Matches secrets with one or more of the applied tags">
- <FontAwesomeIcon icon={faInfoCircle} />
- </Tooltip>
- </div>
- </DropdownMenuLabel>
- {tags.map(({ id, slug, color }) => (
- <DropdownMenuItem
- onClick={(evt) => {
- evt.preventDefault();
- onToggleTagFilter(slug);
- }}
- key={id}
- icon={filter?.tags[slug] && <FontAwesomeIcon icon={faCheckCircle} />}
- iconPos="right"
- >
- <div className="flex items-center">
- <div
- className="mr-2 h-2 w-2 rounded-full"
- style={{ background: color || "#bec2c8" }}
- />
- {slug}
- </div>
- </DropdownMenuItem>
- ))}
- </DropdownSubMenuContent>
- </DropdownSubMenu>
- )}
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- {isTableFiltered && (
- <Button variant="plain" colorSchema="secondary" onClick={onClearFilters}>
- Clear Filters
- </Button>
- )}
- <div className="grow" />
- <div>
- {isProtectedBranch && (
- <Tooltip content={`Protected by policy ${protectedBranchPolicyName}`}>
- <IconButton
- variant="outline_bg"
- className="border-primary/40 bg-primary/10"
- ariaLabel="protected"
- >
- <FontAwesomeIcon icon={faLock} className="text-primary" />
- </IconButton>
- </Tooltip>
- )}
- </div>
- <div>
- <IconButton variant="outline_bg" ariaLabel="Download" onClick={handleSecretDownload}>
- <FontAwesomeIcon icon={faDownload} />
- </IconButton>
- </div>
- <div>
- <IconButton variant="outline_bg" ariaLabel="Reveal" onClick={onVisibilityToggle}>
- <FontAwesomeIcon icon={isVisible ? faEyeSlash : faEye} />
- </IconButton>
- </div>
- <div>
- <ProjectPermissionCan
- I={ProjectPermissionCommitsActions.Read}
- a={ProjectPermissionSub.Commits}
- >
- {(isAllowed) => (
- <Button
- variant="outline_bg"
- onClick={() => {
- if (subscription && subscription.pitRecovery) {
- onClickRollbackMode();
- return;
- }
-
- handlePopUpOpen("upgradePlan", {
- featureName: "PIT Recovery"
- });
- }}
- leftIcon={<FontAwesomeIcon icon={faCodeCommit} />}
- isLoading={isCommitCountLoading}
- className="h-10"
- isDisabled={!isAllowed}
- >
- {`${commitCount} Commit${commitCount === 1 ? "" : "s"}`}
- </Button>
- )}
- </ProjectPermissionCan>
- </div>
- <div className="flex items-center">
- {hasPathPolicies ? (
- <Button
- variant="outline_bg"
- leftIcon={<FontAwesomeIcon icon={faPlus} />}
- onClick={() =>
- permission.can(
- ProjectPermissionSecretActions.Create,
- subject(ProjectPermissionSub.Secrets, {
- environment,
- secretPath,
- secretName: "*",
- secretTags: ["*"]
- })
- )
- ? openPopUp(PopUpNames.CreateSecretForm)
- : handlePopUpOpen("requestAccess", [ProjectPermissionActions.Create])
- }
- className="h-10 rounded-r-none"
- >
- Add Secret
- </Button>
- ) : (
- <ProjectPermissionCan
- I={ProjectPermissionActions.Create}
- a={subject(ProjectPermissionSub.Secrets, {
- environment,
- secretPath,
- secretName: "*",
- secretTags: ["*"]
- })}
- >
- {(isAllowed) => (
- <Button
- variant="outline_bg"
- leftIcon={<FontAwesomeIcon icon={faPlus} />}
- onClick={() => openPopUp(PopUpNames.CreateSecretForm)}
- className="h-10 rounded-r-none"
- isDisabled={!isAllowed}
- >
- Add Secret
- </Button>
- )}
- </ProjectPermissionCan>
- )}
- <DropdownMenu
- open={popUp.misc.isOpen}
- onOpenChange={(isOpen) => handlePopUpToggle("misc", isOpen)}
- >
- <DropdownMenuTrigger asChild>
- <IconButton
- ariaLabel="add-folder-or-import"
- variant="outline_bg"
- className="rounded-l-none bg-mineshaft-600 p-3"
- >
- <FontAwesomeIcon icon={faAngleDown} />
- </IconButton>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <div className="flex flex-col space-y-1 p-1.5">
- <ProjectPermissionCan
- I={ProjectPermissionActions.Create}
- a={subject(ProjectPermissionSub.SecretFolders, {
- environment,
- secretPath
- })}
- >
- {(isAllowed) => (
- <Button
- leftIcon={<FontAwesomeIcon icon={faFolderPlus} className="pr-2" />}
- onClick={() => {
- handlePopUpOpen("addFolder");
- handlePopUpClose("misc");
- }}
- isDisabled={!isAllowed}
- variant="outline_bg"
- className="h-10 text-left"
- isFullWidth
- >
- Add Folder
- </Button>
- )}
- </ProjectPermissionCan>
- <ProjectPermissionCan
- I={ProjectPermissionDynamicSecretActions.CreateRootCredential}
- a={subject(ProjectPermissionSub.DynamicSecrets, {
- environment,
- secretPath,
- secretName: "*",
- secretTags: ["*"],
- metadata: ["*"]
- })}
- >
- {(isAllowed) => (
- <Button
- leftIcon={<FontAwesomeIcon icon={faFingerprint} className="pr-2" />}
- onClick={() => {
- if (subscription && subscription.dynamicSecret) {
- handlePopUpOpen("addDynamicSecret");
- handlePopUpClose("misc");
- return;
- }
- handlePopUpOpen("upgradePlan", {
- featureName: "Dynamic Secrets",
- isEnterpriseFeature: true
- });
- }}
- isDisabled={!isAllowed}
- variant="outline_bg"
- className="h-10 text-left"
- isFullWidth
- >
- Add Dynamic Secret
- </Button>
- )}
- </ProjectPermissionCan>
- <ProjectPermissionCan
- I={ProjectPermissionSecretRotationActions.Create}
- a={subject(ProjectPermissionSub.SecretRotation, {
- environment,
- secretPath
- })}
- >
- {(isAllowed) => (
- <Button
- leftIcon={<FontAwesomeIcon icon={faRotate} className="pr-2" />}
- onClick={() => {
- if (subscription && subscription.secretRotation) {
- handlePopUpOpen("addSecretRotation");
- handlePopUpClose("misc");
- return;
- }
- handlePopUpOpen("upgradePlan", {
- featureName: "Secret Rotation"
- });
- }}
- variant="outline_bg"
- className="h-10 text-left"
- isFullWidth
- isDisabled={!isAllowed}
- >
- Add Secret Rotation
- </Button>
- )}
- </ProjectPermissionCan>
- <ProjectPermissionCan
- I={ProjectPermissionActions.Create}
- a={subject(ProjectPermissionSub.SecretImports, {
- environment,
- secretPath
- })}
- >
- {(isAllowed) => (
- <Button
- leftIcon={<FontAwesomeIcon icon={faFileImport} className="pr-2" />}
- onClick={() => {
- handlePopUpOpen("addSecretImport");
- handlePopUpClose("misc");
- }}
- variant="outline_bg"
- className="h-10 text-left"
- isFullWidth
- isDisabled={!isAllowed}
- >
- Add Import
- </Button>
- )}
- </ProjectPermissionCan>
- <ProjectPermissionCan
- I={ProjectPermissionActions.Create}
- a={subject(ProjectPermissionSub.SecretFolders, {
- environment,
- secretPath
- })}
- >
- {(isAllowed) => (
- <Button
- leftIcon={<FontAwesomeIcon icon={faPaste} className="pr-2" />}
- onClick={() => {
- handlePopUpOpen("replicateFolder");
- handlePopUpClose("misc");
- }}
- isDisabled={!isAllowed}
- variant="outline_bg"
- className="h-10 text-left"
- isFullWidth
- >
- Replicate Secrets
- </Button>
- )}
- </ProjectPermissionCan>
- {hasVaultConnection && (
- <ProjectPermissionCan
- I={ProjectPermissionActions.Create}
- a={subject(ProjectPermissionSub.Secrets, {
- environment,
- secretPath,
- secretName: "*",
- secretTags: ["*"]
- })}
- >
- {(isAllowed) => (
- <Button
- leftIcon={
- <img
- src="/images/integrations/Vault.png"
- alt="HashiCorp Vault"
- className="h-4 w-4"
- />
- }
- onClick={() => {
- handlePopUpOpen("importFromVault");
- handlePopUpClose("misc");
- }}
- isDisabled={!isAllowed}
- variant="outline_bg"
- className="h-10 text-left"
- isFullWidth
- >
- Add from HashiCorp Vault
- </Button>
- )}
- </ProjectPermissionCan>
- )}
- </div>
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- </div>
- <SelectedActionBar
- selectedCount={Object.keys(selectedSecrets).length}
- onClearSelection={resetSelectedSecret}
- >
- <ProjectPermissionCan
- I={ProjectPermissionActions.Delete}
- a={subject(ProjectPermissionSub.Secrets, {
- environment,
- secretPath,
- secretName: "*",
- secretTags: ["*"]
- })}
- renderTooltip
- allowedLabel="Move"
- >
- {(isAllowed) => (
- <Button
- variant="outline_bg"
- leftIcon={<FontAwesomeIcon icon={faAnglesRight} />}
- onClick={() => handlePopUpOpen("moveSecrets")}
- isDisabled={!isAllowed || isHoneyTokenSelected}
- size="xs"
- >
- Move
- </Button>
- )}
- </ProjectPermissionCan>
- <ProjectPermissionCan
- I={ProjectPermissionActions.Delete}
- a={subject(ProjectPermissionSub.Secrets, {
- environment,
- secretPath,
- secretName: "*",
- secretTags: ["*"]
- })}
- renderTooltip
- allowedLabel="Delete"
- >
- {(isAllowed) => (
- <Button
- variant="outline_bg"
- colorSchema="danger"
- leftIcon={<FontAwesomeIcon icon={faTrash} />}
- onClick={() => handlePopUpOpen("bulkDeleteSecrets")}
- isDisabled={!isAllowed || isManagedSecretSelected}
- size="xs"
- >
- Delete
- </Button>
- )}
- </ProjectPermissionCan>
- </SelectedActionBar>
- {/* all the side triggers from actions like modals etc */}
- <CreateSecretImportForm
- environment={environment}
- secretPath={secretPath}
- projectId={projectId}
- onUpgradePlan={() =>
- handlePopUpOpen("upgradePlan", {
- featureName: "Secret Imports"
- })
- }
- isOpen={popUp.addSecretImport.isOpen}
- onClose={() => handlePopUpClose("addSecretImport")}
- onTogglePopUp={(isOpen) => handlePopUpToggle("addSecretImport", isOpen)}
- />
- <CreateDynamicSecretForm
- isOpen={popUp.addDynamicSecret.isOpen}
- onToggle={(isOpen) => handlePopUpToggle("addDynamicSecret", isOpen)}
- projectSlug={currentProject.slug}
- environments={[{ slug: environment, name: environment, id: "not-used" }]}
- secretPath={secretPath}
- isSingleEnvironmentMode
- />
- <CreateSecretRotationV2Modal
- secretPath={secretPath}
- environment={environment}
- isOpen={popUp.addSecretRotation.isOpen}
- onOpenChange={(isOpen) => handlePopUpToggle("addSecretRotation", isOpen)}
- />
- <Dialog
- open={popUp.addFolder.isOpen}
- onOpenChange={(isOpen) => handlePopUpToggle("addFolder", isOpen)}
- >
- <DialogContent className="max-w-lg">
- <DialogHeader>
- <DialogTitle>Add Folder</DialogTitle>
- <DialogDescription>Add a new folder to organize your secrets.</DialogDescription>
- </DialogHeader>
- <FolderForm onCreateFolder={handleFolderCreate} />
- </DialogContent>
- </Dialog>
- <DeleteActionModal
- isOpen={popUp.bulkDeleteSecrets.isOpen}
- deleteKey="delete"
- title="Do you want to delete these secrets?"
- onChange={(isOpen) => handlePopUpToggle("bulkDeleteSecrets", isOpen)}
- onDeleteApproved={handleSecretBulkDelete}
- formContent={
- ((importedBy && importedBy.length > 0) ||
- (usedBySecretSyncs && usedBySecretSyncs?.length > 0)) && (
- <CollapsibleSecretImports
- importedBy={importedBy}
- secretsToDelete={Object.values(selectedSecrets).map((s) => s.key)}
- usedBySecretSyncs={usedBySecretSyncs}
- />
- )
- }
- />
- <MoveSecretsModal
- popUp={popUp}
- handlePopUpToggle={handlePopUpToggle}
- onMoveApproved={handleSecretsMove}
- secretsToMove={Object.values(selectedSecrets).map((s) => ({ id: s.id, key: s.key }))}
- environment={environment}
- secretPath={secretPath}
- projectId={projectId}
- />
- <ReplicateFolderFromBoard
- isOpen={popUp.replicateFolder.isOpen}
- onToggle={(isOpen) => handlePopUpToggle("replicateFolder", isOpen)}
- onParsedEnv={handleParsedEnvMultiFolder}
- environment={environment}
- environments={currentProject.environments}
- projectId={projectId}
- secretPath={secretPath}
- />
- {subscription && (
- <UpgradePlanModal
- isOpen={popUp.upgradePlan.isOpen}
- onOpenChange={(isOpen) => handlePopUpToggle("upgradePlan", isOpen)}
- isEnterpriseFeature={popUp.upgradePlan.data?.isEnterpriseFeature}
- text={`Your current plan does not include access to ${popUp.upgradePlan.data?.featureName}. To unlock this feature, please upgrade to Infisical ${popUp.upgradePlan.data?.isEnterpriseFeature ? "Enterprise" : "Pro"} plan.`}
- />
- )}
- <Modal
- isOpen={popUp?.confirmUpload?.isOpen}
- onOpenChange={(open) => handlePopUpToggle("confirmUpload", open)}
- >
- <ModalContent
- title="Confirm Secret Upload"
- footerContent={[
- <Button
- isLoading={isSubmitting}
- isDisabled={isSubmitting}
- colorSchema={isNonConflictingUpload ? "primary" : "danger"}
- key="overwrite-btn"
- onClick={handleSaveFolderImport}
- >
- {isNonConflictingUpload ? "Upload" : "Overwrite"}
- </Button>,
- <Button
- key="keep-old-btn"
- className="ml-4"
- onClick={() => handlePopUpClose("confirmUpload")}
- variant="outline_bg"
- isDisabled={isSubmitting}
- >
- Cancel
- </Button>
- ]}
- >
- {isNonConflictingUpload ? (
- <div>
- Are you sure you want to import {createSecretCount} secret
- {createSecretCount > 1 ? "s" : ""} to this environment?
- </div>
- ) : (
- <div className="flex flex-col text-gray-300">
- <div>Your project already contains the following {updateSecretCount} secrets:</div>
- <div className="mt-2 text-sm text-gray-400">
- {(popUp?.confirmUpload?.data as TSecOverwriteOpt)?.update
- ?.map((sec) => sec.secretKey)
- .join(", ")}
- </div>
- <div className="mt-6">
- Are you sure you want to overwrite these secrets
- {createSecretCount > 0
- ? ` and import ${createSecretCount} new
- one${createSecretCount > 1 ? "s" : ""}`
- : ""}
- ?
- </div>
- </div>
- )}
- </ModalContent>
- </Modal>
- <Modal
- isOpen={popUp?.requestAccess?.isOpen}
- onOpenChange={(open) => handlePopUpToggle("requestAccess", open)}
- >
- <ModalContent title="Access Restricted">
- <p className="mb-2 text-bunker-300">You do not have permission to perform this action.</p>
- <p className="text-bunker-300">Request access to perform this action in this folder.</p>
- <div className="mt-8 flex items-center gap-4">
- <ModalClose asChild>
- <Button onClick={() => onRequestAccess(popUp?.requestAccess.data)}>
- Request Access
- </Button>
- </ModalClose>
- <ModalClose asChild>
- <Button variant="plain" colorSchema="secondary">
- Cancel
- </Button>
- </ModalClose>
- </div>
- </ModalContent>
- </Modal>
- <VaultSecretImportModal
- isOpen={popUp.importFromVault.isOpen}
- onOpenChange={(isOpen) => handlePopUpToggle("importFromVault", isOpen)}
- environment={environment}
- secretPath={secretPath}
- appConnections={vaultAppConnections}
- onImport={handleVaultImport}
- />
- </>
- );
-};
-
-ActionBar.displayName = "ActionBar";
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/MoveSecretsModal.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/MoveSecretsModal.tsx
deleted file mode 100644
index 0d27c05b8d..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/MoveSecretsModal.tsx
+++ /dev/null
@@ -1,256 +0,0 @@
-import { Controller, useForm } from "react-hook-form";
-import { faKey, faWarning } from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import { zodResolver } from "@hookform/resolvers/zod";
-import { useQueries } from "@tanstack/react-query";
-import { z } from "zod";
-
-import {
- Button,
- Checkbox,
- FormControl,
- Modal,
- ModalContent,
- Select,
- SelectItem,
- Table,
- TBody,
- Td,
- Th,
- THead,
- Tr
-} from "@app/components/v2";
-import { SecretPathInput } from "@app/components/v2/SecretPathInput";
-import { useProject } from "@app/context";
-import { fetchSecretReferences, secretKeys } from "@app/hooks/api/secrets/queries";
-import { UsePopUpState } from "@app/hooks/usePopUp";
-
-type Props = {
- popUp: UsePopUpState<["moveSecrets"]>;
- handlePopUpToggle: (popUpName: keyof UsePopUpState<["moveSecrets"]>, state?: boolean) => void;
- onMoveApproved: (moveParams: {
- destinationEnvironment: string;
- destinationSecretPath: string;
- shouldOverwrite: boolean;
- }) => void;
- secretsToMove: { id: string; key: string }[];
- environment: string;
- secretPath: string;
- projectId: string;
-};
-
-const formSchema = z.object({
- environment: z.string().trim(),
- secretPath: z
- .string()
- .trim()
- .transform((val) =>
- typeof val === "string" && val.at(-1) === "/" && val.length > 1 ? val.slice(0, -1) : val
- ),
- shouldOverwrite: z.boolean().default(false)
-});
-
-type TFormSchema = z.infer<typeof formSchema>;
-
-export const MoveSecretsModal = ({
- popUp,
- handlePopUpToggle,
- onMoveApproved,
- secretsToMove,
- environment,
- secretPath,
- projectId
-}: Props) => {
- const {
- handleSubmit,
- control,
- reset,
- watch,
- formState: { isSubmitting }
- } = useForm<TFormSchema>({ resolver: zodResolver(formSchema) });
-
- const { currentProject } = useProject();
- const environments = currentProject?.environments || [];
- const selectedEnvironment = watch("environment");
-
- const referenceQueries = useQueries({
- queries: secretsToMove.map((secret) => ({
- queryKey: secretKeys.getSecretReferences({
- secretKey: secret.key,
- secretPath,
- environment,
- projectId
- }),
- queryFn: () =>
- fetchSecretReferences({
- secretKey: secret.key,
- secretPath,
- environment,
- projectId
- }),
- enabled: popUp.moveSecrets.isOpen && secretsToMove.length > 0
- }))
- });
-
- // aggregate all references and so we can calculate total count including hidden ones
- const allReferences = referenceQueries
- .filter((refQueries) => refQueries.data?.tree)
- .flatMap((q, idx) =>
- (q.data?.tree.children || []).map((child) => ({
- secretKey: child.key,
- environment: child.environment,
- secretPath: child.secretPath,
- movedSecretKey: secretsToMove[idx].key
- }))
- )
- .filter(
- (ref, index, self) =>
- index ===
- self.findIndex(
- (r) =>
- r.secretKey === ref.secretKey &&
- r.environment === ref.environment &&
- r.secretPath === ref.secretPath &&
- r.movedSecretKey === ref.movedSecretKey
- )
- );
-
- const hasReferences = allReferences.length > 0;
- const isLoadingReferences = referenceQueries.some((refQueries) => refQueries.isLoading);
-
- const handleFormSubmit = (data: TFormSchema) => {
- onMoveApproved({
- destinationEnvironment: data.environment,
- destinationSecretPath: data.secretPath,
- shouldOverwrite: data.shouldOverwrite
- });
-
- handlePopUpToggle("moveSecrets", false);
- };
-
- return (
- <Modal
- isOpen={popUp.moveSecrets.isOpen}
- onOpenChange={(isOpen) => {
- reset();
- handlePopUpToggle("moveSecrets", isOpen);
- }}
- >
- <ModalContent
- title="Move Secrets"
- subTitle="Move secrets from the current path to the selected destination"
- >
- <form onSubmit={handleSubmit(handleFormSubmit)}>
- <Controller
- control={control}
- name="environment"
- defaultValue={environments?.[0]?.slug}
- render={({ field: { onChange, ...field }, fieldState: { error } }) => (
- <FormControl label="Environment" errorText={error?.message} isError={Boolean(error)}>
- <Select
- defaultValue={field.value}
- {...field}
- onValueChange={(e) => onChange(e)}
- className="w-full"
- >
- {environments.map(({ name, slug }) => (
- <SelectItem value={slug} key={slug}>
- {name}
- </SelectItem>
- ))}
- </Select>
- </FormControl>
- )}
- />
- <Controller
- control={control}
- name="secretPath"
- defaultValue="/"
- render={({ field, fieldState: { error } }) => (
- <FormControl label="Secret Path" isError={Boolean(error)} errorText={error?.message}>
- <SecretPathInput {...field} environment={selectedEnvironment} />
- </FormControl>
- )}
- />
- <Controller
- control={control}
- name="shouldOverwrite"
- defaultValue={false}
- render={({ field: { onBlur, value, onChange } }) => (
- <Checkbox
- id="overwrite-checkbox"
- className="ml-2"
- isChecked={value}
- onCheckedChange={onChange}
- onBlur={onBlur}
- >
- Overwrite existing secrets
- </Checkbox>
- )}
- />
- {hasReferences && !isLoadingReferences && (
- <div className="mt-4">
- <div className="mb-4 rounded-md border border-yellow-700/30 bg-yellow-900/20">
- <div className="flex items-start gap-3 p-4">
- <div className="mt-0.5 shrink-0 text-yellow-500">
- <FontAwesomeIcon icon={faWarning} className="h-5 w-5" />
- </div>
- <p className="text-sm text-yellow-500">
- {allReferences.length} secret{allReferences.length !== 1 ? "s" : ""} will have
- their references updated to match the path after the secret has been moved.
- </p>
- </div>
- </div>
-
- {allReferences.length > 0 && (
- <div className="max-h-40 overflow-y-auto rounded-md border border-mineshaft-700">
- <Table>
- <THead className="sticky -top-1 bg-bunker-800">
- <Th className="px-4">Type</Th>
- <Th className="px-4">Environment</Th>
- <Th className="truncate px-4">Path</Th>
- <Th className="px-4">Secret Key</Th>
- </THead>
- <TBody>
- {allReferences.map((ref) => (
- <Tr
- key={`${ref.secretKey}-${ref.environment}-${ref.secretPath}-${ref.movedSecretKey}`}
- >
- <Td>
- <FontAwesomeIcon icon={faKey} className="h-4 w-4 text-gray-400" />
- </Td>
- <Td className="px-4">{ref.environment}</Td>
- <Td className="truncate px-4">{ref.secretPath}</Td>
- <Td className="px-4">{ref.secretKey}</Td>
- </Tr>
- ))}
- </TBody>
- </Table>
- </div>
- )}
- </div>
- )}
- <div className="mt-7 flex items-center">
- <Button
- isDisabled={isSubmitting}
- isLoading={isSubmitting}
- key="move-secrets-submit"
- className="mr-4"
- type="submit"
- >
- Move
- </Button>
- <Button
- key="move-secrets-cancel"
- onClick={() => handlePopUpToggle("moveSecrets", false)}
- variant="plain"
- colorSchema="secondary"
- >
- Cancel
- </Button>
- </div>
- </form>
- </ModalContent>
- </Modal>
- );
-};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/index.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/index.tsx
deleted file mode 100644
index 507d4f0e4f..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/index.tsx
+++ /dev/null
@@ -1 +0,0 @@
-export { ActionBar } from "./ActionBar";
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/CompareEnvironments.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/CompareEnvironments.tsx
deleted file mode 100644
index c95fae63dc..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/CompareEnvironments.tsx
+++ /dev/null
@@ -1,592 +0,0 @@
-import { useCallback, useEffect, useRef, useState } from "react";
-import { MultiValue } from "react-select";
-import {
- faArrowDown,
- faArrowUp,
- faCheckCircle,
- faFilter,
- faFingerprint,
- faFolder,
- faKey,
- faRotate,
- faSearch
-} from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import { AlertTriangleIcon } from "lucide-react";
-import { twMerge } from "tailwind-merge";
-
-import {
- Button,
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuLabel,
- DropdownMenuTrigger,
- EmptyState,
- FilterableSelect,
- FormLabel,
- IconButton,
- Input,
- Lottie,
- Pagination,
- Table,
- TableContainer,
- TBody,
- Th,
- THead,
- Tooltip,
- Tr
-} from "@app/components/v2";
-import { Badge } from "@app/components/v3";
-import { useProject } from "@app/context";
-import {
- getUserTablePreference,
- PreferenceKey,
- setUserTablePreference
-} from "@app/helpers/userTablePreferences";
-import { useDebounce, usePagination, useResetPageHelper } from "@app/hooks";
-import { useGetImportedSecretsAllEnvs } from "@app/hooks/api";
-import { useGetProjectSecretsOverview } from "@app/hooks/api/dashboard";
-import { DashboardSecretsOrderBy } from "@app/hooks/api/dashboard/types";
-import { OrderByDirection } from "@app/hooks/api/generic/types";
-import { ProjectEnv } from "@app/hooks/api/projects/types";
-import { useResizableColWidth } from "@app/hooks/useResizableColWidth";
-import {
- useDynamicSecretOverview,
- useFolderOverview,
- useSecretOverview,
- useSecretRotationOverview
-} from "@app/hooks/utils";
-import { SecretTableResourceCount } from "@app/pages/secret-manager/OverviewPage/components/SecretTableResourceCount";
-
-import { DynamicSecretRow } from "./components/DynamicSecretRow";
-import { FolderRow } from "./components/FolderRow";
-import { SecretRotationRow } from "./components/SecretRotationRow";
-import { SecretNoAccessRow, SecretRow } from "./components/SecretRow";
-
-type Props = {
- secretPath: string;
-};
-
-enum RowType {
- Folder = "folder",
- DynamicSecret = "dynamic",
- Secret = "secret",
- SecretRotation = "rotation"
-}
-
-type Filter = {
- [key in RowType]: boolean;
-};
-
-const DEFAULT_FILTER_STATE = {
- [RowType.Folder]: false,
- [RowType.DynamicSecret]: false,
- [RowType.Secret]: false,
- [RowType.SecretRotation]: false
-};
-
-const COL_WIDTH_OFFSET = 220;
-
-export const CompareEnvironments = ({ secretPath }: Props) => {
- const { currentProject } = useProject();
- const compareEnvironmentsKey = `compare-environments-${currentProject.id}`;
-
- const [selectedEnvironments, setSelectedEnvironments] = useState<ProjectEnv[]>(() => {
- try {
- const storedEnvironments = JSON.parse(localStorage.getItem(compareEnvironmentsKey) ?? "[]");
-
- if (Array.isArray(storedEnvironments) && storedEnvironments.length > 0) {
- const potentialEnvs: string[] = [];
- storedEnvironments.forEach((env) => {
- if (typeof env === "string") {
- potentialEnvs.push(env);
- }
- });
-
- return currentProject.environments.filter((env) => potentialEnvs.includes(env.id));
- }
- } catch {
- // do nothing and proceed
- }
- return currentProject.environments.slice(0, 2);
- });
-
- const [filter, setFilter] = useState<Filter>(DEFAULT_FILTER_STATE);
-
- const {
- offset,
- limit,
- orderDirection,
- setOrderDirection,
- setPage,
- perPage,
- page,
- setPerPage,
- orderBy
- } = usePagination<DashboardSecretsOrderBy>(DashboardSecretsOrderBy.Name, {
- initPerPage: getUserTablePreference("secretCompareTable", PreferenceKey.PerPage, 50)
- });
-
- const handlePerPageChange = (newPerPage: number) => {
- setPerPage(newPerPage);
- setUserTablePreference("secretCompareTable", PreferenceKey.PerPage, newPerPage);
- };
-
- const projectId = currentProject.id;
- const [searchFilter, setSearchFilter] = useState("");
- const [debouncedSearchFilter] = useDebounce(searchFilter);
- const [debouncedSelectedEnvironments] = useDebounce(selectedEnvironments);
-
- useEffect(() => {
- localStorage.setItem(
- compareEnvironmentsKey,
- JSON.stringify(selectedEnvironments.map((env) => env.id))
- );
- }, [debouncedSelectedEnvironments]);
-
- const {
- secretImports,
- isImportedSecretPresentInEnv,
- getImportedSecretByKey,
- getEnvImportedSecretKeyCount
- } = useGetImportedSecretsAllEnvs({
- projectId,
- path: secretPath,
- environments: (currentProject.environments || []).map(({ slug }) => slug)
- });
-
- const compareEnvironments = selectedEnvironments.length
- ? selectedEnvironments
- : currentProject.environments;
-
- const isFilteredByResources = Object.values(filter).some(Boolean);
- const { isPending: isOverviewLoading, data: overview } = useGetProjectSecretsOverview(
- {
- projectId,
- environments: compareEnvironments.map((env) => env.slug),
- secretPath,
- orderDirection,
- orderBy,
- includeFolders: isFilteredByResources ? filter.folder : true,
- includeDynamicSecrets: isFilteredByResources ? filter.dynamic : true,
- includeSecrets: isFilteredByResources ? filter.secret : true,
- includeImports: true,
- includeSecretRotations: isFilteredByResources ? filter.rotation : true,
- search: debouncedSearchFilter,
- limit,
- offset
- },
- { enabled: Boolean(compareEnvironments.length) }
- );
-
- const {
- secrets,
- folders,
- dynamicSecrets,
- secretRotations,
- totalFolderCount,
- totalSecretCount,
- totalDynamicSecretCount,
- totalSecretRotationCount,
- totalCount = 0,
- totalUniqueFoldersInPage,
- totalUniqueSecretsInPage,
- totalUniqueSecretImportsInPage,
- totalUniqueDynamicSecretsInPage,
- totalUniqueSecretRotationsInPage
- } = overview ?? {};
-
- const secretImportsShaped = secretImports
- ?.flatMap(({ data }) => data)
- .filter(Boolean)
- .flatMap((item) => item?.secrets || []);
-
- const handleIsImportedSecretPresentInEnv = (envSlug: string, secretName: string) => {
- if (secrets?.some((s) => s.key === secretName && s.env === envSlug)) {
- return false;
- }
- if (secretImportsShaped.some((s) => s.key === secretName && s.sourceEnv === envSlug)) {
- return true;
- }
- return isImportedSecretPresentInEnv(envSlug, secretName);
- };
-
- useResetPageHelper({
- totalCount,
- offset,
- setPage
- });
-
- const { folderNamesAndDescriptions, isFolderPresentInEnv } = useFolderOverview(folders);
-
- const { dynamicSecretNames, isDynamicSecretPresentInEnv } =
- useDynamicSecretOverview(dynamicSecrets);
-
- const { secretRotationNames, isSecretRotationPresentInEnv, getSecretRotationByName } =
- useSecretRotationOverview(secretRotations);
-
- const { secKeys, getEnvSecretKeyCount } = useSecretOverview(
- secrets?.concat(secretImportsShaped) || []
- );
-
- const getSecretByKey = useCallback(
- (env: string, key: string) => {
- const sec = secrets?.find((s) => s.env === env && s.key === key);
- return sec;
- },
- [secrets]
- );
-
- const [tableWidth, setTableWidth] = useState(0);
- const tableRef = useRef<HTMLTableElement>(null);
-
- const { handleMouseDown, isResizing, colWidth } = useResizableColWidth({
- initialWidth: 320,
- minWidth: 160,
- maxWidth: tableRef.current
- ? tableRef.current.clientWidth - COL_WIDTH_OFFSET // ensure value column can't collapse completely
- : 800,
- ref: tableRef
- });
-
- const handleToggleRowType = useCallback(
- (rowType: RowType) =>
- setFilter((state) => {
- return {
- ...state,
- [rowType]: !state[rowType]
- };
- }),
- []
- );
-
- const isTableEmpty = totalCount === 0;
-
- const isTableFiltered = isFilteredByResources;
-
- useEffect(() => {
- const element = tableRef.current;
- if (!element) return;
-
- const handleResize = () => {
- setTableWidth(element.clientWidth - 1);
- };
-
- const resizeObserver = new ResizeObserver(handleResize);
- resizeObserver.observe(element);
-
- // eslint-disable-next-line consistent-return
- return () => {
- resizeObserver.disconnect();
- };
- }, [tableRef]);
-
- return (
- // scott: this is reverse to fix z-indexing bug of dropdown with sticky table cols; couldn't resolve with flex-col
- <div className="flex flex-1 flex-col-reverse overflow-hidden">
- {!isOverviewLoading && totalCount > 0 && (
- <Pagination
- startAdornment={
- <SecretTableResourceCount
- dynamicSecretCount={totalDynamicSecretCount}
- secretCount={totalSecretCount}
- folderCount={totalFolderCount}
- secretRotationCount={totalSecretRotationCount}
- />
- }
- className="rounded-b-lg border border-solid border-mineshaft-500 bg-mineshaft-700"
- count={totalCount}
- page={page}
- perPage={perPage}
- onChangePage={(newPage) => setPage(newPage)}
- onChangePerPage={handlePerPageChange}
- />
- )}
- <div className="flex thin-scrollbar flex-1 flex-col overflow-y-auto">
- <TableContainer
- ref={tableRef}
- className={twMerge(
- "mt-4 flex flex-1 flex-col border-mineshaft-500 bg-mineshaft-700",
- !isTableEmpty && "rounded-b-none"
- )}
- >
- {/* eslint-disable-next-line no-nested-ternary */}
- {isOverviewLoading ? (
- <div className="flex h-full flex-col items-center justify-center">
- <Lottie
- isAutoPlay
- icon="infisical_loading"
- className="h-10 place-self-center self-center"
- />
- </div>
- ) : isTableEmpty ? (
- <EmptyState
- titleClassName="text-base"
- className="m-auto bg-mineshaft-700 text-lg"
- title={
- isTableFiltered
- ? "No secrets to compare with current filters"
- : "No secrets to compare"
- }
- />
- ) : (
- <Table className="border-collapse bg-mineshaft-700">
- <THead className="sticky top-0 z-20">
- <Tr className="sticky top-0 z-20">
- <Th className="sticky left-0 z-10 border-none p-0" style={{ width: colWidth }}>
- <div className="relative">
- <div
- tabIndex={-1}
- role="button"
- className={`absolute -right-[0.02rem] z-40 h-full w-0.5 cursor-ew-resize hover:bg-blue-400/20 ${
- isResizing ? "bg-blue-400/75" : "bg-transparent"
- }`}
- onMouseDown={handleMouseDown}
- />
- <div className="pointer-events-none absolute top-[0.67rem] -right-[0.02rem] z-30">
- <div className="h-5 w-0.5 rounded-[1.5px] bg-gray-400 opacity-50" />
- </div>
- <div className="flex h-full items-center border-r border-b-2 border-mineshaft-500 bg-mineshaft-700 bg-clip-padding p-0 px-4 py-2.5 text-sm normal-case">
- Name
- <IconButton
- variant="plain"
- className="mt-[0.1rem] ml-1"
- ariaLabel="sort"
- onClick={() =>
- setOrderDirection((prev) =>
- prev === OrderByDirection.ASC
- ? OrderByDirection.DESC
- : OrderByDirection.ASC
- )
- }
- >
- <FontAwesomeIcon
- className="h-3"
- icon={orderDirection === "asc" ? faArrowDown : faArrowUp}
- />
- </IconButton>
- </div>
- </div>
- </Th>
- {compareEnvironments?.map(({ name, slug }, index) => {
- const envSecKeyCount = getEnvSecretKeyCount(slug);
- const importedSecKeyCount = getEnvImportedSecretKeyCount(slug);
- const missingKeyCount = secKeys.length - envSecKeyCount - importedSecKeyCount;
-
- return (
- <Th
- className="border-none p-0 text-center whitespace-nowrap"
- key={`environment-${slug}`}
- >
- <div
- className={twMerge(
- "flex h-full w-full items-center justify-center gap-x-2 border-b-2 border-mineshaft-500 bg-mineshaft-700 p-0 px-4 py-2.5 text-center text-sm normal-case",
- index < compareEnvironments.length - 1 && "border-r"
- )}
- >
- {name}
- {missingKeyCount > 0 && (
- <Tooltip
- className="max-w-none lowercase"
- content={
- <>
- {missingKeyCount} secret{missingKeyCount > 1 ? "s" : ""} missing
- compared to other environments on this page
- </>
- }
- >
- <Badge variant="warning">
- <AlertTriangleIcon />
- {missingKeyCount}
- </Badge>
- </Tooltip>
- )}
- </div>
- </Th>
- );
- })}
- </Tr>
- </THead>
- <TBody>
- {folderNamesAndDescriptions.map(({ name: folderName }, index) => (
- <FolderRow
- folderName={folderName}
- isFolderPresentInEnv={isFolderPresentInEnv}
- environments={compareEnvironments}
- key={`overview-${folderName}-${index + 1}`}
- colWidth={colWidth}
- />
- ))}
- {dynamicSecretNames.map((dynamicSecretName, index) => (
- <DynamicSecretRow
- dynamicSecretName={dynamicSecretName}
- isDynamicSecretInEnv={isDynamicSecretPresentInEnv}
- environments={compareEnvironments}
- key={`overview-${dynamicSecretName}-${index + 1}`}
- colWidth={colWidth}
- />
- ))}
- {secretRotationNames.map((secretRotationName, index) => (
- <SecretRotationRow
- secretRotationName={secretRotationName}
- isSecretRotationInEnv={isSecretRotationPresentInEnv}
- environments={compareEnvironments}
- getSecretRotationByName={getSecretRotationByName}
- key={`overview-${secretRotationName}-${index + 1}`}
- colWidth={colWidth}
- tableWidth={tableWidth}
- />
- ))}
- {secKeys.map((key, index) => (
- <SecretRow
- colWidth={colWidth}
- secretPath={secretPath}
- getImportedSecretByKey={getImportedSecretByKey}
- isImportedSecretPresentInEnv={handleIsImportedSecretPresentInEnv}
- key={`overview-${key}-${index + 1}`}
- environments={compareEnvironments}
- secretKey={key}
- getSecretByKey={getSecretByKey}
- tableWidth={tableWidth}
- />
- ))}
- <SecretNoAccessRow
- colWidth={colWidth}
- environments={compareEnvironments}
- count={Math.max(
- (page * perPage > totalCount ? totalCount % perPage : perPage) -
- (totalUniqueFoldersInPage || 0) -
- (totalUniqueDynamicSecretsInPage || 0) -
- (totalUniqueSecretsInPage || 0) -
- (totalUniqueSecretImportsInPage || 0) -
- (totalUniqueSecretRotationsInPage || 0),
- 0
- )}
- />
- </TBody>
- </Table>
- )}
- </TableContainer>
- </div>
- <div className="mt-3 flex flex-row items-center justify-center space-x-2">
- <Input
- value={searchFilter}
- onChange={(e) => setSearchFilter(e.target.value)}
- className="h-full flex-1"
- placeholder="Search by resource name..."
- leftIcon={<FontAwesomeIcon icon={faSearch} />}
- containerClassName="h-10"
- />
- {isTableFiltered && (
- <Button
- variant="plain"
- colorSchema="secondary"
- onClick={() => {
- setFilter(DEFAULT_FILTER_STATE);
- }}
- >
- Clear Filters
- </Button>
- )}
- {compareEnvironments.length > 0 && (
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button
- size="sm"
- variant="outline_bg"
- className={twMerge(
- "flex h-10",
- isTableFiltered && "border-primary/40 bg-primary/10"
- )}
- leftIcon={
- <FontAwesomeIcon
- icon={faFilter}
- className={isTableFiltered ? "text-primary/80" : undefined}
- />
- }
- >
- Filters
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent
- className="max-h-[70vh] thin-scrollbar overflow-y-auto"
- align="end"
- sideOffset={2}
- >
- <DropdownMenuLabel>Filter by Resource</DropdownMenuLabel>
- <DropdownMenuItem
- onClick={(e) => {
- e.preventDefault();
- handleToggleRowType(RowType.Folder);
- }}
- icon={filter[RowType.Folder] && <FontAwesomeIcon icon={faCheckCircle} />}
- iconPos="right"
- >
- <div className="flex items-center gap-2">
- <FontAwesomeIcon icon={faFolder} className="text-yellow-700" />
- <span>Folders</span>
- </div>
- </DropdownMenuItem>
- <DropdownMenuItem
- onClick={(e) => {
- e.preventDefault();
- handleToggleRowType(RowType.DynamicSecret);
- }}
- icon={filter[RowType.DynamicSecret] && <FontAwesomeIcon icon={faCheckCircle} />}
- iconPos="right"
- >
- <div className="flex items-center gap-2">
- <FontAwesomeIcon icon={faFingerprint} className="text-yellow-700" />
- <span>Dynamic Secrets</span>
- </div>
- </DropdownMenuItem>
- <DropdownMenuItem
- onClick={(e) => {
- e.preventDefault();
- handleToggleRowType(RowType.SecretRotation);
- }}
- icon={filter[RowType.SecretRotation] && <FontAwesomeIcon icon={faCheckCircle} />}
- iconPos="right"
- >
- <div className="flex items-center gap-2">
- <FontAwesomeIcon icon={faRotate} className="text-mineshaft-400" />
- <span>Secret Rotations</span>
- </div>
- </DropdownMenuItem>
- <DropdownMenuItem
- onClick={(e) => {
- e.preventDefault();
- handleToggleRowType(RowType.Secret);
- }}
- icon={filter[RowType.Secret] && <FontAwesomeIcon icon={faCheckCircle} />}
- iconPos="right"
- >
- <div className="flex items-center gap-2">
- <FontAwesomeIcon icon={faKey} className="text-bunker-300" />
- <span>Secrets</span>
- </div>
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- )}
- </div>
- <div className="z-99999999!">
- <FormLabel label="Select Environments to Compare" />
- <FilterableSelect
- value={selectedEnvironments}
- onChange={(value) => {
- const selected = value as MultiValue<ProjectEnv>;
-
- setSelectedEnvironments((selected as ProjectEnv[]) ?? []);
- }}
- placeholder="Leave blank to compare all environments"
- options={currentProject.environments}
- getOptionValue={(option) => option.slug}
- getOptionLabel={(option) => option.name}
- isMulti
- />
- </div>
- </div>
- );
-};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/components/DynamicSecretRow/DynamicSecretRow.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/components/DynamicSecretRow/DynamicSecretRow.tsx
deleted file mode 100644
index 16de6533b8..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/components/DynamicSecretRow/DynamicSecretRow.tsx
+++ /dev/null
@@ -1,41 +0,0 @@
-import { faFingerprint } from "@fortawesome/free-solid-svg-icons";
-
-import { Tr } from "@app/components/v2";
-
-import { EnvironmentStatusCell, ResourceNameCell } from "../shared";
-
-type Props = {
- dynamicSecretName: string;
- environments: { name: string; slug: string }[];
- isDynamicSecretInEnv: (name: string, env: string) => boolean;
- colWidth: number;
-};
-
-export const DynamicSecretRow = ({
- dynamicSecretName,
- environments = [],
- isDynamicSecretInEnv,
- colWidth
-}: Props) => {
- return (
- <Tr isHoverable className="group border-mineshaft-500">
- <ResourceNameCell
- label={dynamicSecretName}
- icon={faFingerprint}
- colWidth={colWidth}
- iconClassName="text-yellow-700"
- />
- {environments.map(({ slug }, i) => {
- const isPresent = isDynamicSecretInEnv(dynamicSecretName, slug);
-
- return (
- <EnvironmentStatusCell
- isLast={i === environments.length - 1}
- status={isPresent ? "present" : "missing"}
- key={`dynamic-secret-${dynamicSecretName}-${i + 1}-value`}
- />
- );
- })}
- </Tr>
- );
-};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/components/DynamicSecretRow/index.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/components/DynamicSecretRow/index.tsx
deleted file mode 100644
index 5c7bf445a4..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/components/DynamicSecretRow/index.tsx
+++ /dev/null
@@ -1 +0,0 @@
-export { DynamicSecretRow } from "./DynamicSecretRow";
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/components/FolderRow/FolderRow.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/components/FolderRow/FolderRow.tsx
deleted file mode 100644
index a3d672e13b..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/components/FolderRow/FolderRow.tsx
+++ /dev/null
@@ -1,41 +0,0 @@
-import { faFolder } from "@fortawesome/free-solid-svg-icons";
-
-import { Tr } from "@app/components/v2";
-
-import { EnvironmentStatusCell, ResourceNameCell } from "../shared";
-
-type Props = {
- folderName: string;
- environments: { name: string; slug: string }[];
- isFolderPresentInEnv: (name: string, env: string) => boolean;
- colWidth: number;
-};
-
-export const FolderRow = ({
- folderName,
- environments = [],
- isFolderPresentInEnv,
- colWidth
-}: Props) => {
- return (
- <Tr isHoverable className="group border-mineshaft-500">
- <ResourceNameCell
- label={folderName}
- icon={faFolder}
- iconClassName="text-yellow-700"
- colWidth={colWidth}
- />
- {environments.map(({ slug }, i) => {
- const isPresent = isFolderPresentInEnv(folderName, slug);
-
- return (
- <EnvironmentStatusCell
- isLast={i === environments.length - 1}
- status={isPresent ? "present" : "missing"}
- key={`folder-${slug}-${i + 1}-value`}
- />
- );
- })}
- </Tr>
- );
-};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/components/FolderRow/index.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/components/FolderRow/index.tsx
deleted file mode 100644
index 171b2e5963..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/components/FolderRow/index.tsx
+++ /dev/null
@@ -1 +0,0 @@
-export { FolderRow } from "./FolderRow";
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/components/SecretRotationRow/SecretRotationRow.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/components/SecretRotationRow/SecretRotationRow.tsx
deleted file mode 100644
index fe2295fa73..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/components/SecretRotationRow/SecretRotationRow.tsx
+++ /dev/null
@@ -1,179 +0,0 @@
-import { faEye, faEyeSlash, faInfoCircle, faRotate } from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import { twMerge } from "tailwind-merge";
-
-import { IconButton, TableContainer, Tag, Td, Tooltip, Tr } from "@app/components/v2";
-import { Blur } from "@app/components/v2/Blur";
-import { InfisicalSecretInput } from "@app/components/v2/InfisicalSecretInput";
-import { SECRET_ROTATION_MAP } from "@app/helpers/secretRotationsV2";
-import { useToggle } from "@app/hooks";
-import { TSecretRotationV2 } from "@app/hooks/api/secretRotationsV2";
-
-import { EnvironmentStatusCell, ResourceNameCell } from "../shared";
-
-type Props = {
- secretRotationName: string;
- environments: { name: string; slug: string }[];
- isSecretRotationInEnv: (name: string, env: string) => boolean;
- getSecretRotationByName: (slug: string, name: string) => TSecretRotationV2 | undefined;
- colWidth: number;
- tableWidth: number;
-};
-
-export const SecretRotationRow = ({
- secretRotationName,
- environments = [],
- isSecretRotationInEnv,
- colWidth,
- getSecretRotationByName,
- tableWidth
-}: Props) => {
- const [isExpanded, setIsExpanded] = useToggle(false);
- const [isSecretVisible, setIsSecretVisible] = useToggle();
-
- const totalCols = environments.length + 1; // secret key row
-
- return (
- <>
- <Tr isHoverable isSelectable onClick={setIsExpanded.toggle} className="group">
- <ResourceNameCell
- label={secretRotationName}
- icon={faRotate}
- colWidth={colWidth}
- iconClassName="text-mineshaft-400"
- isRowExpanded={isExpanded}
- />
- {environments.map(({ slug }, i) => {
- const isPresent = isSecretRotationInEnv(secretRotationName, slug);
-
- return (
- <EnvironmentStatusCell
- isLast={i === environments.length - 1}
- status={isPresent ? "present" : "missing"}
- key={`secret-rotation-${slug}-${i + 1}-value`}
- />
- );
- })}
- </Tr>
- {isExpanded &&
- environments.map(({ name: envName, slug }) => {
- const secretRotation = getSecretRotationByName(slug, secretRotationName);
-
- if (!secretRotation) return null;
-
- const { type, secrets, description } = secretRotation;
-
- const { name: rotationType, image } = SECRET_ROTATION_MAP[type];
-
- return (
- <Tr key={`secret-rotation-${slug}-${secretRotationName}`} className="border-b-0">
- <Td
- colSpan={totalCols}
- style={{ minWidth: tableWidth, maxWidth: tableWidth }}
- className="sticky left-0 bg-clip-padding px-0 py-0"
- >
- <div
- style={{ minWidth: tableWidth, maxWidth: tableWidth }}
- className="sticky left-0 bg-clip-padding px-0 py-0"
- >
- <div className="flex h-[40px]! items-center justify-between gap-x-2 bg-mineshaft-800 px-4">
- <div className="w-full">
- <div className="flex w-full flex-wrap items-center gap-x-2.5">
- <span>{envName}</span>
- <Tag className="flex items-center gap-1 px-1.5 py-0 text-xs normal-case">
- <img
- src={`/images/integrations/${image}`}
- className="w-[11px]"
- alt={`${rotationType} logo`}
- />
- {rotationType}
- </Tag>
- {description && (
- <Tooltip content={description}>
- <FontAwesomeIcon icon={faInfoCircle} className="text-mineshaft-400" />
- </Tooltip>
- )}
- </div>
- </div>
- <Tooltip
- side="left"
- content={isSecretVisible ? "Hide Values" : "Reveal Values"}
- >
- <IconButton
- variant="plain"
- colorSchema="secondary"
- ariaLabel={isSecretVisible ? "Hide Values" : "Reveal Values"}
- onClick={() => setIsSecretVisible.toggle()}
- >
- <FontAwesomeIcon icon={isSecretVisible ? faEyeSlash : faEye} />
- </IconButton>
- </Tooltip>
- </div>
- <TableContainer className="rounded-none border-0">
- <table className="secret-table w-full border-b-0 bg-mineshaft-900!">
- <tbody className="!last:border-b-0 w-full border-t-2 border-mineshaft-600">
- {secrets.map((secret, index) => {
- return (
- <Tooltip
- className="max-w-sm"
- content={
- secret
- ? undefined
- : "You do not have permission to view this secret."
- }
- // eslint-disable-next-line react/no-array-index-key
- key={`rotation-secret-${secretRotation.id}-${index}`}
- >
- <tr className="hover:bg-mineshaft-800/50">
- <td
- style={{
- width: colWidth
- }}
- className="h-px! border-none p-0!"
- >
- <div
- className="flex h-full flex-1 items-center border-r border-mineshaft-500 px-4 py-1"
- style={{
- width: colWidth
- }}
- >
- <span className={twMerge(!secret && "blur-sm", "truncate")}>
- {secret?.key ?? "********"}
- </span>
- </div>
- </td>
- <td className="h-[40px]! px-4!">
- {/* eslint-disable-next-line no-nested-ternary */}
- {!secret ? (
- <div className="h-full pl-4 blur-sm">********</div>
- ) : secret.secretValueHidden ? (
- <Blur
- className="py-0"
- tooltipText="You do not have permission to read the value of this secret."
- />
- ) : (
- <InfisicalSecretInput
- isReadOnly
- value={secret.value}
- isVisible={isSecretVisible}
- secretPath={secretRotation.folder.path}
- environment={secretRotation.environment.slug}
- onChange={() => {}}
- />
- )}
- </td>
- </tr>
- </Tooltip>
- );
- })}
- </tbody>
- </table>
- </TableContainer>
- </div>
- </Td>
- </Tr>
- );
- })}
- </>
- );
-};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/components/SecretRotationRow/index.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/components/SecretRotationRow/index.tsx
deleted file mode 100644
index a0b2fcfa72..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/components/SecretRotationRow/index.tsx
+++ /dev/null
@@ -1 +0,0 @@
-export { SecretRotationRow } from "./SecretRotationRow";
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/components/SecretRow/EnvironmentSecretRow.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/components/SecretRow/EnvironmentSecretRow.tsx
deleted file mode 100644
index 073dfd7258..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/components/SecretRow/EnvironmentSecretRow.tsx
+++ /dev/null
@@ -1,49 +0,0 @@
-import { faEyeSlash } from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-
-import { Tooltip } from "@app/components/v2";
-import { InfisicalSecretInput } from "@app/components/v2/InfisicalSecretInput";
-
-type Props = {
- defaultValue?: string | null;
- isOverride?: boolean;
- isVisible?: boolean;
- isImportedSecret: boolean;
- environment: string;
- secretValueHidden: boolean;
- secretPath: string;
-};
-
-export const EnvironmentSecretRow = ({
- defaultValue,
- isOverride,
- isImportedSecret,
- secretValueHidden,
- environment,
- secretPath,
- isVisible
-}: Props) => {
- return (
- <div className="group flex w-full cursor-text items-center space-x-2">
- {secretValueHidden && !isOverride && (
- <Tooltip content="You do not have access to view the current value">
- <FontAwesomeIcon className="pl-2" size="sm" icon={faEyeSlash} />
- </Tooltip>
- )}
- <div className="flex-1 pr-2 pl-3">
- <InfisicalSecretInput
- onChange={() => {}}
- isReadOnly
- value={defaultValue as string}
- key="secret-input"
- isVisible={isVisible && !secretValueHidden}
- secretPath={secretPath}
- environment={environment}
- isImport={isImportedSecret}
- defaultValue={secretValueHidden ? "" : undefined}
- canEditButNotView={secretValueHidden && !isOverride}
- />
- </div>
- </div>
- );
-};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/components/SecretRow/SecretNoAccessRow.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/components/SecretRow/SecretNoAccessRow.tsx
deleted file mode 100644
index 075726d1bb..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/components/SecretRow/SecretNoAccessRow.tsx
+++ /dev/null
@@ -1,44 +0,0 @@
-import { faLock } from "@fortawesome/free-solid-svg-icons";
-
-import { Tr } from "@app/components/v2";
-import { Blur } from "@app/components/v2/Blur";
-
-import { EnvironmentStatusCell, ResourceNameCell } from "../shared";
-
-type Props = {
- environments: { name: string; slug: string }[];
- count: number;
- colWidth: number;
-};
-
-export const SecretNoAccessRow = ({ environments = [], count, colWidth }: Props) => {
- return (
- <>
- {Array.from(Array(count)).map((_, j) => (
- <Tr
- key={`no-access-secret-${j + 1}`}
- isHoverable
- isSelectable
- className="group border-mineshaft-500"
- >
- <ResourceNameCell
- label={<Blur />}
- iconClassName="text-bunker-400"
- icon={faLock}
- colWidth={colWidth}
- tooltipContent="You do not have permission to view this secret"
- />
- {environments.map(({ slug }, i) => {
- return (
- <EnvironmentStatusCell
- isLast={i === environments.length - 1}
- status="no-access"
- key={`no-access-sec--${slug}-${i + 1}-value`}
- />
- );
- })}
- </Tr>
- ))}
- </>
- );
-};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/components/SecretRow/SecretRow.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/components/SecretRow/SecretRow.tsx
deleted file mode 100644
index 3eeaa993e0..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/components/SecretRow/SecretRow.tsx
+++ /dev/null
@@ -1,237 +0,0 @@
-import { subject } from "@casl/ability";
-import {
- faCodeBranch,
- faEye,
- faEyeSlash,
- faFileImport,
- faKey,
- faRotate,
- faShieldHalved
-} from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-
-import { IconButton, TableContainer, Td, Tooltip, Tr } from "@app/components/v2";
-import { useProjectPermission } from "@app/context";
-import {
- ProjectPermissionSecretActions,
- ProjectPermissionSub
-} from "@app/context/ProjectPermissionContext/types";
-import { useToggle } from "@app/hooks";
-import { SecretV3RawSanitized } from "@app/hooks/api/secrets/types";
-import { ProjectEnv } from "@app/hooks/api/types";
-import { HIDDEN_SECRET_VALUE } from "@app/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretItem";
-
-import { EnvironmentStatus, EnvironmentStatusCell, ResourceNameCell } from "../shared";
-import { EnvironmentSecretRow } from "./EnvironmentSecretRow";
-
-type Props = {
- secretKey: string;
- secretPath: string;
- environments: { name: string; slug: string }[];
- getSecretByKey: (slug: string, key: string) => SecretV3RawSanitized | undefined;
- isImportedSecretPresentInEnv: (env: string, secretName: string) => boolean;
- getImportedSecretByKey: (
- env: string,
- secretName: string
- ) => { secret?: SecretV3RawSanitized; environmentInfo?: ProjectEnv } | undefined;
- colWidth: number;
- tableWidth: number;
-};
-
-export const SecretRow = ({
- secretKey,
- environments = [],
- secretPath,
- getSecretByKey,
- isImportedSecretPresentInEnv,
- getImportedSecretByKey,
- colWidth,
- tableWidth
-}: Props) => {
- const [isFormExpanded, setIsFormExpanded] = useToggle();
- const totalCols = environments.length + 1; // secret key row
- const [isSecretVisible, setIsSecretVisible] = useToggle();
-
- const { permission } = useProjectPermission();
-
- const getDefaultValue = (
- secret: SecretV3RawSanitized | undefined,
- importedSecret: { secret?: SecretV3RawSanitized } | undefined
- ) => {
- const canEditSecretValue = permission.can(
- ProjectPermissionSecretActions.Edit,
- subject(ProjectPermissionSub.Secrets, {
- environment: secret?.env || "",
- secretPath: secret?.path || "",
- secretName: secret?.key || "",
- secretTags: ["*"]
- })
- );
-
- if (secret?.secretValueHidden && !secret?.valueOverride) {
- return canEditSecretValue ? HIDDEN_SECRET_VALUE : "";
- }
- return secret?.valueOverride || secret?.value || importedSecret?.secret?.value || "";
- };
-
- return (
- <>
- <Tr
- isHoverable
- isSelectable
- onClick={() => setIsFormExpanded.toggle()}
- className="group border-mineshaft-500"
- >
- <ResourceNameCell
- colWidth={colWidth}
- label={secretKey}
- icon={faKey}
- iconClassName="text-bunker-300"
- isRowExpanded={isFormExpanded}
- />
- {environments.map(({ slug }, i) => {
- const secret = getSecretByKey(slug, secretKey);
-
- const isSecretImported = isImportedSecretPresentInEnv(slug, secretKey);
-
- const isSecretPresent = Boolean(secret);
- const isSecretEmpty = secret?.value === "";
-
- let status: EnvironmentStatus;
-
- if (isSecretEmpty) {
- status = "empty";
- } else if (isSecretPresent) {
- status = "present";
- } else if (isSecretImported) {
- status = "imported";
- } else {
- status = "missing";
- }
-
- return (
- <EnvironmentStatusCell
- isLast={i === environments.length - 1}
- key={`sec-overview-${slug}-${i + 1}-value`}
- status={status}
- />
- );
- })}
- </Tr>
- {isFormExpanded && (
- <Tr className="border-b-0">
- <Td
- colSpan={totalCols}
- style={{ minWidth: tableWidth, maxWidth: tableWidth }}
- className="sticky left-0 bg-clip-padding px-0 py-0"
- >
- <div
- style={{ minWidth: tableWidth, maxWidth: tableWidth }}
- className="sticky left-0 bg-clip-padding px-0 py-0"
- >
- <TableContainer className="rounded-none border-0">
- <table className="secret-table bg-mineshaft-900">
- <thead>
- <tr className="h-10 border-b-2 border-mineshaft-600 bg-mineshaft-800">
- <th
- style={{
- width: colWidth
- }}
- className="min-table-row"
- >
- <span className="truncate">Environment</span>
- </th>
- <th style={{ padding: "0.5rem 1rem" }} className="border-none">
- Value
- </th>
- <div className="absolute top-[4px] right-3 mt-1 mr-1 ml-auto w-min">
- <Tooltip
- side="left"
- content={isSecretVisible ? "Hide Values" : "Reveal Values"}
- >
- <IconButton
- variant="plain"
- colorSchema="secondary"
- ariaLabel={isSecretVisible ? "Hide Values" : "Reveal Values"}
- onClick={() => setIsSecretVisible.toggle()}
- >
- <FontAwesomeIcon icon={isSecretVisible ? faEyeSlash : faEye} />
- </IconButton>
- </Tooltip>
- </div>
- </tr>
- </thead>
- <tbody className="border-t-2 border-mineshaft-600">
- {environments.map(({ name, slug }) => {
- const secret = getSecretByKey(slug, secretKey);
-
- const isImportedSecret = isImportedSecretPresentInEnv(slug, secretKey);
- const importedSecret = getImportedSecretByKey(slug, secretKey);
-
- return (
- <tr
- key={`secret-expanded-${slug}-${secretKey}`}
- className="h-full hover:bg-mineshaft-700/70"
- >
- <td
- className="h-px border-none p-0!"
- style={{
- width: colWidth
- }}
- >
- <div
- title={name}
- style={{
- width: colWidth
- }}
- className="flex h-full min-h-[40px] w-32 items-center space-x-2 border-r border-mineshaft-500 px-4"
- >
- <span className="truncate">{name}</span>
- {isImportedSecret && (
- <Tooltip
- content={`Imported secret from the '${importedSecret?.environmentInfo?.name}' environment`}
- >
- <FontAwesomeIcon icon={faFileImport} />
- </Tooltip>
- )}
- {secret?.isRotatedSecret && (
- <Tooltip content="Rotated Secret">
- <FontAwesomeIcon icon={faRotate} />
- </Tooltip>
- )}
- {secret?.isHoneyTokenSecret && (
- <Tooltip content="Honey Token Secret">
- <FontAwesomeIcon icon={faShieldHalved} className="text-yellow" />
- </Tooltip>
- )}
- {secret?.valueOverride && (
- <Tooltip content="Personal Override">
- <FontAwesomeIcon icon={faCodeBranch} />
- </Tooltip>
- )}
- </div>
- </td>
- <td className="col-span-2 h-8 w-full">
- <EnvironmentSecretRow
- secretPath={secretPath}
- isVisible={isSecretVisible}
- secretValueHidden={secret?.secretValueHidden || false}
- defaultValue={getDefaultValue(secret, importedSecret)}
- isOverride={Boolean(secret?.valueOverride)}
- isImportedSecret={isImportedSecret}
- environment={slug}
- />
- </td>
- </tr>
- );
- })}
- </tbody>
- </table>
- </TableContainer>
- </div>
- </Td>
- </Tr>
- )}
- </>
- );
-};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/components/SecretRow/index.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/components/SecretRow/index.tsx
deleted file mode 100644
index a1e4a3d518..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/components/SecretRow/index.tsx
+++ /dev/null
@@ -1,2 +0,0 @@
-export { SecretNoAccessRow } from "./SecretNoAccessRow";
-export { SecretRow } from "./SecretRow";
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/components/shared/EnvironmentStatusCell.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/components/shared/EnvironmentStatusCell.tsx
deleted file mode 100644
index fa5d2f8bbd..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/components/shared/EnvironmentStatusCell.tsx
+++ /dev/null
@@ -1,75 +0,0 @@
-import { IconDefinition } from "@fortawesome/free-brands-svg-icons";
-import { faCircle } from "@fortawesome/free-regular-svg-icons";
-import { faBan, faCheck, faFileImport, faXmark } from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import { twMerge } from "tailwind-merge";
-
-import { Td, Tooltip } from "@app/components/v2";
-
-export type EnvironmentStatus = "present" | "missing" | "empty" | "imported" | "no-access";
-
-type Props = {
- isLast: boolean;
- status: EnvironmentStatus;
-};
-
-export const EnvironmentStatusCell = ({ isLast, status }: Props) => {
- let tooltipContent: string;
- let icon: IconDefinition;
- let iconClassName: string;
-
- switch (status) {
- case "present":
- tooltipContent = "Present in environment";
- icon = faCheck;
- iconClassName = "h-3 w-3";
- break;
- case "missing":
- tooltipContent = "Missing from environment";
- icon = faXmark;
- iconClassName = "h-3.5 w-3.5";
- break;
- case "empty":
- tooltipContent = "Empty value in environment";
- icon = faCircle;
- iconClassName = "h-3 w-3";
- break;
- case "imported":
- tooltipContent = "Imported into environment";
- icon = faFileImport;
- iconClassName = "h-3 w-3";
- break;
- case "no-access":
- tooltipContent = "You do not have permission to view this secret";
- icon = faBan;
- iconClassName = "h-3 w-3";
- break;
- default:
- throw new Error(`Unhandled environment status: ${status as string}`);
- }
-
- return (
- <Td
- className={twMerge(
- "border-b border-mineshaft-500 bg-clip-padding p-0 group-hover:bg-mineshaft-600",
- (status === "present" || status === "imported") && "text-green-600",
- status === "empty" && "text-yellow",
- status === "missing" && "text-red-600",
- status === "no-access" && "text-bunker-400"
- )}
- >
- <div
- className={twMerge(
- "flex h-10 items-center justify-center border-mineshaft-500 px-0 py-3",
- !isLast && "border-r"
- )}
- >
- <div className="flex justify-center">
- <Tooltip center content={tooltipContent}>
- <FontAwesomeIcon className={iconClassName} icon={icon} />
- </Tooltip>
- </div>
- </div>
- </Td>
- );
-};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/components/shared/ResourceNameCell.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/components/shared/ResourceNameCell.tsx
deleted file mode 100644
index 079b563d50..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/components/shared/ResourceNameCell.tsx
+++ /dev/null
@@ -1,47 +0,0 @@
-import { ReactElement } from "react";
-import { IconDefinition } from "@fortawesome/free-brands-svg-icons";
-import { faAngleDown } from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-
-import { Td, Tooltip } from "@app/components/v2";
-
-type Props = {
- isRowExpanded?: boolean;
- label: ReactElement | string;
- icon: IconDefinition;
- iconClassName?: string;
- colWidth: number;
- tooltipContent?: string;
-};
-
-export const ResourceNameCell = ({
- isRowExpanded,
- label,
- icon,
- iconClassName,
- colWidth,
- tooltipContent
-}: Props) => {
- return (
- <Td
- className="sticky left-0 z-10 border-b border-mineshaft-500 bg-mineshaft-700 bg-clip-padding p-0 group-hover:bg-mineshaft-600"
- style={{
- width: colWidth
- }}
- >
- <Tooltip content={tooltipContent} className="max-w-sm">
- <div
- style={{
- width: colWidth
- }}
- className="flex h-10 items-center space-x-5 border-r border-mineshaft-600 px-4 py-2.5"
- >
- <div className="w-5 min-w-5">
- <FontAwesomeIcon className={iconClassName} icon={isRowExpanded ? faAngleDown : icon} />
- </div>
- {typeof label === "string" ? <span className="truncate">{label}</span> : label}
- </div>
- </Tooltip>
- </Td>
- );
-};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/components/shared/index.ts b/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/components/shared/index.ts
deleted file mode 100644
index c8bd53cbef..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/components/shared/index.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-export * from "./EnvironmentStatusCell";
-export * from "./ResourceNameCell";
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/index.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/index.tsx
deleted file mode 100644
index f5c9979726..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/index.tsx
+++ /dev/null
@@ -1 +0,0 @@
-export * from "./CompareEnvironments";
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CreateSecretForm/CreateSecretForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/CreateSecretForm/CreateSecretForm.tsx
deleted file mode 100644
index 61dcc24493..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CreateSecretForm/CreateSecretForm.tsx
+++ /dev/null
@@ -1,299 +0,0 @@
-import { ClipboardEvent, useRef } from "react";
-import { Controller, useForm } from "react-hook-form";
-import { faTriangleExclamation, faWarning } from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import { zodResolver } from "@hookform/resolvers/zod";
-import { z } from "zod";
-
-import { createNotification } from "@app/components/notifications";
-import { Button, FormControl, Input, Tooltip } from "@app/components/v2";
-import { CreatableSelect } from "@app/components/v2/CreatableSelect";
-import { InfisicalSecretInput } from "@app/components/v2/InfisicalSecretInput";
-import { PasswordGenerator } from "@app/components/v3";
-import {
- ProjectPermissionActions,
- ProjectPermissionSub,
- useProject,
- useProjectPermission
-} from "@app/context";
-import { getKeyValue } from "@app/helpers/parseEnvVar";
-import { useCreateSecretV3, useCreateWsTag, useGetWsTags } from "@app/hooks/api";
-import { PendingAction } from "@app/hooks/api/secretFolders/types";
-import { SecretType } from "@app/hooks/api/types";
-
-import {
- PendingSecretCreate,
- PopUpNames,
- useBatchModeActions,
- usePopUpAction
-} from "../../SecretMainPage.store";
-
-const typeSchema = z.object({
- key: z.string().trim().min(1, { message: "Secret key is required" }),
- value: z.string().optional(),
- tags: z.array(z.object({ label: z.string().trim(), value: z.string().trim() })).optional()
-});
-
-type TFormSchema = z.infer<typeof typeSchema>;
-
-type Props = {
- environment: string;
- projectId: string;
- secretPath?: string;
- // modal props
- autoCapitalize?: boolean;
- isProtectedBranch?: boolean;
- isBatchMode?: boolean;
-};
-
-export const CreateSecretForm = ({
- environment,
- projectId,
- secretPath = "/",
- autoCapitalize = true,
- isProtectedBranch = false,
- isBatchMode = false
-}: Props) => {
- const {
- register,
- handleSubmit,
- control,
- reset,
- setValue,
- watch,
- formState: { errors, isSubmitting }
- } = useForm<TFormSchema>({ resolver: zodResolver(typeSchema) });
- const { closePopUp } = usePopUpAction();
-
- const { mutateAsync: createSecretV3 } = useCreateSecretV3();
- const createWsTag = useCreateWsTag();
- const { addPendingChange } = useBatchModeActions();
-
- const { currentProject } = useProject();
- const { permission } = useProjectPermission();
- const canReadTags = permission.can(ProjectPermissionActions.Read, ProjectPermissionSub.Tags);
- const { data: projectTags, isPending: isTagsLoading } = useGetWsTags(
- canReadTags ? projectId : ""
- );
-
- const secretKeyInputRef = useRef<HTMLInputElement>(null);
- const { ref: setSecretKeyHookRef, ...secretKeyRegisterRest } = register("key");
-
- const secretKey = watch("key");
-
- const slugSchema = z.string().trim().toLowerCase().min(1);
- const createNewTag = async (slug: string) => {
- // TODO: Replace with slugSchema generic
- const parsedSlug = slugSchema.parse(slug);
- await createWsTag.mutateAsync({
- projectId,
- tagSlug: parsedSlug,
- tagColor: ""
- });
- };
-
- const handleFormSubmit = async ({ key, value, tags }: TFormSchema) => {
- if (isBatchMode) {
- const pendingSecretCreate: PendingSecretCreate = {
- id: key,
- type: PendingAction.Create,
- secretKey: key,
- secretValue: value || "",
- secretComment: "",
- tags: tags?.map((el) => ({ id: el.value, slug: el.label })),
- timestamp: Date.now(),
- resourceType: "secret"
- };
- addPendingChange(pendingSecretCreate, {
- projectId,
-
- environment,
- secretPath
- });
- closePopUp(PopUpNames.CreateSecretForm);
- reset();
- return;
- }
- await createSecretV3({
- environment,
- projectId,
- secretPath,
- secretKey: key,
- secretValue: value || "",
- secretComment: "",
- type: SecretType.Shared,
- tagIds: tags?.map((el) => el.value)
- });
- closePopUp(PopUpNames.CreateSecretForm);
- reset();
-
- createNotification({
- type: isProtectedBranch ? "info" : "success",
- text: isProtectedBranch
- ? "Requested changes have been sent for review"
- : "Successfully created secret"
- });
- };
-
- const handlePaste = (e: ClipboardEvent<HTMLInputElement>) => {
- const delimitters = [":", "="];
- const pastedContent = e.clipboardData.getData("text");
- const { key, value } = getKeyValue(pastedContent, delimitters);
-
- const isWholeKeyHighlighted =
- secretKeyInputRef.current &&
- secretKeyInputRef.current.selectionStart === 0 &&
- secretKeyInputRef.current.selectionEnd === secretKeyInputRef.current.value.length;
-
- if (!secretKey || isWholeKeyHighlighted) {
- e.preventDefault();
- const keyStr = autoCapitalize ? key.toUpperCase() : key;
- setValue("key", keyStr);
- if (value) {
- setValue("value", value);
- }
- }
- };
-
- return (
- <form onSubmit={handleSubmit(handleFormSubmit)} noValidate>
- <FormControl
- label="Key"
- isRequired
- isError={Boolean(errors?.key)}
- errorText={errors?.key?.message}
- >
- <Input
- {...secretKeyRegisterRest}
- ref={(e) => {
- setSecretKeyHookRef(e);
- // @ts-expect-error this is for multiple ref single component
- secretKeyInputRef.current = e;
- }}
- warning={
- secretKey?.includes(" ") ? (
- <Tooltip
- className="w-full max-w-72"
- content={
- <div>
- Secret key contains whitespaces.
- <br />
- <br /> If this is the desired format, you need to provide it as{" "}
- <code className="rounded-md bg-mineshaft-500 px-1 py-0.5">
- {encodeURIComponent(secretKey.trim())}
- </code>{" "}
- when making API requests.
- </div>
- }
- >
- <FontAwesomeIcon
- icon={faWarning}
- className="absolute right-0 mr-3 text-yellow-600"
- />
- </Tooltip>
- ) : undefined
- }
- placeholder="Type your secret name"
- onPaste={handlePaste}
- autoCapitalization={autoCapitalize}
- />
- </FormControl>
- <Controller
- control={control}
- name="value"
- render={({ field }) => (
- <FormControl
- label="Value"
- tooltipText={
- <div>
- You can add references to other secrets using the format{" "}
- <code className="rounded-sm bg-mineshaft-600 px-1 py-0.5">
- &#36;{"{"}secret_name{"}"}
- </code>
- <br />
- <br />
- You can go to the referenced secret by holding the{" "}
- <code className="rounded-sm bg-mineshaft-600 px-1 py-0.5">Cmd</code> (Mac) or{" "}
- <code className="rounded-sm bg-mineshaft-600 px-1 py-0.5">Ctrl</code>{" "}
- (Windows/Linux) key and clicking on the secret name.
- </div>
- }
- tooltipClassName="max-w-md"
- isError={Boolean(errors?.value)}
- errorText={errors?.value?.message}
- >
- <div className="flex items-center gap-2">
- <InfisicalSecretInput
- {...field}
- environment={environment}
- secretPath={secretPath}
- containerClassName="text-bunker-300 hover:border-primary-400/50 border border-mineshaft-600 bg-mineshaft-900 px-2 py-1.5"
- />
- <PasswordGenerator
- onUsePassword={field.onChange}
- projectId={projectId}
- selectedEnvironments={[{ slug: environment }]}
- secretPath={secretPath}
- environments={currentProject?.environments}
- />
- </div>
- </FormControl>
- )}
- />
- <Controller
- control={control}
- name="tags"
- render={({ field }) => (
- <FormControl
- label="Tags"
- isError={Boolean(errors?.value)}
- errorText={errors?.value?.message}
- helperText={
- !canReadTags ? (
- <div className="flex items-center space-x-2">
- <FontAwesomeIcon icon={faTriangleExclamation} className="text-yellow-400" />
- <span>You do not have permission to read tags.</span>
- </div>
- ) : (
- ""
- )
- }
- >
- <CreatableSelect
- isMulti
- className="w-full"
- placeholder="Select tags to assign to secret..."
- isValidNewOption={(v) => slugSchema.safeParse(v).success}
- name="tagIds"
- isDisabled={!canReadTags}
- isLoading={isTagsLoading && canReadTags}
- options={projectTags?.map((el) => ({ label: el.slug, value: el.id }))}
- value={field.value}
- onChange={field.onChange}
- onCreateOption={createNewTag}
- />
- </FormControl>
- )}
- />
- <div className="mt-7 flex items-center">
- <Button
- isDisabled={isSubmitting}
- isLoading={isSubmitting}
- key="layout-create-project-submit"
- className="mr-4"
- type="submit"
- >
- Create Secret
- </Button>
- <Button
- key="layout-cancel-create-project"
- onClick={() => closePopUp(PopUpNames.CreateSecretForm)}
- variant="plain"
- colorSchema="secondary"
- >
- Cancel
- </Button>
- </div>
- </form>
- );
-};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CreateSecretForm/index.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/CreateSecretForm/index.tsx
deleted file mode 100644
index a7851ed770..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CreateSecretForm/index.tsx
+++ /dev/null
@@ -1 +0,0 @@
-export { CreateSecretForm } from "./CreateSecretForm";
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/DynamicSecretListView.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/DynamicSecretListView.tsx
deleted file mode 100644
index a317a89c80..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/DynamicSecretListView.tsx
+++ /dev/null
@@ -1,314 +0,0 @@
-import { useEffect } from "react";
-import { subject } from "@casl/ability";
-import { faEdit, faFingerprint, faTrash, faWarning } from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-
-import { createNotification } from "@app/components/notifications";
-import { ProjectPermissionCan } from "@app/components/permissions";
-import {
- Button,
- DeleteActionModal,
- IconButton,
- Modal,
- ModalContent,
- Tag,
- Tooltip
-} from "@app/components/v2";
-import { Badge } from "@app/components/v3";
-import { ProjectPermissionDynamicSecretActions, ProjectPermissionSub } from "@app/context";
-import { usePopUp } from "@app/hooks";
-import { useDeleteDynamicSecret } from "@app/hooks/api";
-import {
- DynamicSecretProviders,
- DynamicSecretStatus,
- TDynamicSecret
-} from "@app/hooks/api/dynamicSecret/types";
-
-import { CreateDynamicSecretLease } from "./CreateDynamicSecretLease";
-import { DynamicSecretLease } from "./DynamicSecretLease";
-import { EditDynamicSecretForm } from "./EditDynamicSecretForm";
-
-const formatProviderName = (type: DynamicSecretProviders) => {
- if (type === DynamicSecretProviders.SqlDatabase) return "SQL Database";
- return "";
-};
-
-type Props = {
- dynamicSecrets?: TDynamicSecret[];
- environment: string;
- projectSlug: string;
- secretPath?: string;
- selectedDynamicSecretId: string | null;
-};
-
-export const DynamicSecretListView = ({
- selectedDynamicSecretId,
- dynamicSecrets = [],
- environment,
- projectSlug,
- secretPath = "/"
-}: Props) => {
- const { popUp, handlePopUpToggle, handlePopUpOpen, handlePopUpClose } = usePopUp([
- "dynamicSecretLeases",
- "createDynamicSecretLease",
- "updateDynamicSecret",
- "deleteDynamicSecret"
- ] as const);
-
- const deleteDynamicSecret = useDeleteDynamicSecret();
-
- const handleDynamicSecretDelete = async () => {
- const { name, isForced } = popUp.deleteDynamicSecret.data as TDynamicSecret & {
- isForced?: boolean;
- };
- await deleteDynamicSecret.mutateAsync({
- environmentSlug: environment,
- projectSlug,
- path: secretPath,
- name,
- isForced
- });
- handlePopUpClose("deleteDynamicSecret");
- createNotification({
- type: "success",
- text: "Successfully deleted dynamic secret"
- });
- };
-
- useEffect(() => {
- if (
- selectedDynamicSecretId &&
- dynamicSecrets.find((secret) => secret.id === selectedDynamicSecretId)
- ) {
- handlePopUpOpen("dynamicSecretLeases", selectedDynamicSecretId);
- }
- }, [selectedDynamicSecretId]);
-
- return (
- <>
- {dynamicSecrets.map((secret) => {
- const isRevoking = secret.status === DynamicSecretStatus.Deleting;
- return (
- <Modal
- key={secret.id}
- isOpen={
- popUp.dynamicSecretLeases.isOpen && popUp.dynamicSecretLeases.data === secret.id
- }
- onOpenChange={(state) => handlePopUpToggle("dynamicSecretLeases", state)}
- >
- <div
- className="group flex cursor-pointer border-b border-mineshaft-600 hover:bg-mineshaft-700"
- role="button"
- tabIndex={0}
- onKeyDown={(evt) => {
- // no lease view for TOTP because it's irrelevant
- if (secret.type === DynamicSecretProviders.Totp) {
- return;
- }
-
- if (evt.key === "Enter" && !isRevoking)
- handlePopUpOpen("dynamicSecretLeases", secret.id);
- }}
- onClick={() => {
- // no lease view for TOTP because it's irrelevant
- if (secret.type === DynamicSecretProviders.Totp) {
- return;
- }
-
- if (!isRevoking) {
- handlePopUpOpen("dynamicSecretLeases", secret.id);
- }
- }}
- >
- <div className="flex w-11 items-center px-5 py-3 text-yellow-700">
- <FontAwesomeIcon icon={faFingerprint} />
- </div>
- <div className="flex grow items-center px-4 py-3" role="button" tabIndex={0}>
- {secret.name}
- <Tag className="ml-4 px-2 py-0 text-xs normal-case">
- {formatProviderName(secret.type)}
- </Tag>
- {Boolean(secret.status) && (
- <Tooltip content={secret?.statusDetails || secret.status || ""}>
- <FontAwesomeIcon
- className={
- secret.status === DynamicSecretStatus.Deleting
- ? "text-yellow-600"
- : "text-red-600"
- }
- icon={faWarning}
- />
- </Tooltip>
- )}
- </div>
- <div className="flex items-center space-x-2 px-4 py-2">
- <ProjectPermissionCan
- I={ProjectPermissionDynamicSecretActions.Lease}
- a={subject(ProjectPermissionSub.DynamicSecrets, {
- environment,
- secretPath,
- metadata: secret.metadata
- })}
- renderTooltip
- allowedLabel="Generate Lease"
- >
- {(isAllowed) => (
- <Button
- size="xs"
- className="m-0 px-2 py-0.5 opacity-0 group-hover:opacity-100"
- isDisabled={isRevoking || !isAllowed}
- onClick={(evt) => {
- evt.stopPropagation();
- handlePopUpOpen("createDynamicSecretLease", secret);
- }}
- >
- Generate
- </Button>
- )}
- </ProjectPermissionCan>
-
- {secret.status === DynamicSecretStatus.FailedDeletion && (
- <Tooltip content="This action will remove the secret from internal storage, but it will remain in external systems. Use this option only after you've confirmed that your external leases are handled.">
- <Button
- size="xs"
- className="m-0 px-2 py-0.5"
- colorSchema="danger"
- isDisabled={isRevoking}
- onClick={(evt) => {
- evt.stopPropagation();
- handlePopUpOpen("deleteDynamicSecret", {
- ...secret,
- isForced: true
- });
- }}
- >
- Force Delete
- </Button>
- </Tooltip>
- )}
- </div>
- <div className="flex w-16 items-center justify-between border-l border-mineshaft-600 px-3 py-3">
- <ProjectPermissionCan
- I={ProjectPermissionDynamicSecretActions.EditRootCredential}
- a={subject(ProjectPermissionSub.DynamicSecrets, {
- environment,
- secretPath,
- metadata: secret.metadata
- })}
- renderTooltip
- allowedLabel="Edit"
- >
- {(isAllowed) => (
- <IconButton
- ariaLabel="edit-dynamic-secret"
- variant="plain"
- size="sm"
- className="p-0 opacity-0 group-hover:opacity-100"
- onClick={(evt) => {
- evt.stopPropagation();
- handlePopUpOpen("updateDynamicSecret", secret);
- }}
- isDisabled={!isAllowed || isRevoking}
- >
- <FontAwesomeIcon icon={faEdit} />
- </IconButton>
- )}
- </ProjectPermissionCan>
- <ProjectPermissionCan
- I={ProjectPermissionDynamicSecretActions.DeleteRootCredential}
- a={subject(ProjectPermissionSub.DynamicSecrets, {
- environment,
- secretPath,
- metadata: secret.metadata
- })}
- renderTooltip
- allowedLabel="Delete"
- >
- {(isAllowed) => (
- <IconButton
- ariaLabel="delete-dynamic-secret"
- variant="plain"
- colorSchema="danger"
- size="md"
- className="p-0 opacity-0 group-hover:opacity-100"
- onClick={(evt) => {
- evt.stopPropagation();
- handlePopUpOpen("deleteDynamicSecret", secret);
- }}
- isDisabled={!isAllowed || isRevoking}
- >
- <FontAwesomeIcon icon={faTrash} />
- </IconButton>
- )}
- </ProjectPermissionCan>
- </div>
- </div>
- <ModalContent
- title={
- <div className="flex items-center space-x-2">
- <p>Dynamic secret leases</p>
- <Badge variant="neutral">{secret.name}</Badge>
- </div>
- }
- subTitle="Revoke or renew your secret leases"
- className="max-w-3xl"
- >
- <DynamicSecretLease
- dynamicSecret={secret}
- onClickNewLease={() => handlePopUpOpen("createDynamicSecretLease", secret)}
- onClose={() => handlePopUpClose("dynamicSecretLeases")}
- projectSlug={projectSlug}
- key={secret.id}
- dynamicSecretName={secret.name}
- secretPath={secretPath}
- environment={environment}
- />
- </ModalContent>
- </Modal>
- );
- })}
- <Modal
- isOpen={popUp.createDynamicSecretLease.isOpen}
- onOpenChange={(state) => handlePopUpToggle("createDynamicSecretLease", state)}
- >
- <ModalContent title="Provision lease">
- <CreateDynamicSecretLease
- provider={
- (popUp.createDynamicSecretLease?.data as { type: DynamicSecretProviders })?.type
- }
- onClose={() => handlePopUpClose("createDynamicSecretLease")}
- projectSlug={projectSlug}
- dynamicSecretName={(popUp.createDynamicSecretLease?.data as { name: string })?.name}
- secretPath={secretPath}
- environment={environment}
- />
- </ModalContent>
- </Modal>
- <Modal
- isOpen={popUp.updateDynamicSecret.isOpen}
- onOpenChange={(state) => handlePopUpToggle("updateDynamicSecret", state)}
- >
- <ModalContent title="Edit dynamic secret" className="max-w-3xl">
- <EditDynamicSecretForm
- onClose={() => handlePopUpClose("updateDynamicSecret")}
- projectSlug={projectSlug}
- dynamicSecretName={(popUp.updateDynamicSecret?.data as TDynamicSecret)?.name}
- secretPath={secretPath}
- environment={environment}
- />
- </ModalContent>
- </Modal>
- <DeleteActionModal
- isOpen={popUp.deleteDynamicSecret.isOpen}
- deleteKey={(popUp.deleteDynamicSecret?.data as TDynamicSecret)?.name}
- title={
- (popUp.deleteDynamicSecret?.data as { isForced?: boolean })?.isForced
- ? "Do you want to force delete this dynamic secret?"
- : "Do you want to delete this dynamic secret?"
- }
- onChange={(isOpen) => handlePopUpToggle("deleteDynamicSecret", isOpen)}
- onDeleteApproved={handleDynamicSecretDelete}
- />
- </>
- );
-};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/index.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/index.tsx
deleted file mode 100644
index 752d8a9290..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/index.tsx
+++ /dev/null
@@ -1 +0,0 @@
-export { DynamicSecretListView } from "./DynamicSecretListView";
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/EnvironmentTabs/EnvironmentTabs.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/EnvironmentTabs/EnvironmentTabs.tsx
deleted file mode 100644
index ed8a5ae881..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/EnvironmentTabs/EnvironmentTabs.tsx
+++ /dev/null
@@ -1,246 +0,0 @@
-import { useState } from "react";
-import { faEllipsisH, faPlus } from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import { useQueryClient } from "@tanstack/react-query";
-import { useNavigate, useParams } from "@tanstack/react-router";
-
-import { UpgradePlanModal } from "@app/components/license/UpgradePlanModal";
-import { ProjectPermissionCan } from "@app/components/permissions";
-import {
- Button,
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuLabel,
- DropdownMenuTrigger,
- Modal,
- ModalContent,
- Tab,
- TabList,
- Tabs,
- Tooltip
-} from "@app/components/v2";
-import { ROUTE_PATHS } from "@app/const/routes";
-import {
- ProjectPermissionActions,
- ProjectPermissionSub,
- useOrganization,
- useProject,
- useSubscription
-} from "@app/context";
-import { usePopUp } from "@app/hooks";
-import { projectKeys } from "@app/hooks/api";
-import { ProjectEnv } from "@app/hooks/api/projects/types";
-import { AddEnvironmentModal } from "@app/pages/secret-manager/SettingsPage/components/EnvironmentSection/AddEnvironmentModal";
-
-import { CompareEnvironments } from "../CompareEnvironments";
-
-const COMPARE_ENVIRONMENT_TAB = "__COMPARE_ENVIRONMENT_TAB__";
-const ADD_ENVIRONMENT_TAB = "__ADD_ENVIRONMENT_TAB__";
-const VIEW_MORE_ENVIRONMENT_TAB = "__VIEW_MORE_ENVIRONMENT_TAB__";
-
-type Props = {
- secretPath: string;
-};
-
-const TABS_TO_SHOW = 5;
-
-export const EnvironmentTabs = ({ secretPath }: Props) => {
- const { currentOrg } = useOrganization();
- const { currentProject } = useProject();
- const currentEnv = useParams({
- from: ROUTE_PATHS.SecretManager.SecretDashboardPage.id,
- select: (el) => el.envSlug
- });
-
- const { subscription } = useSubscription();
-
- const isMoreEnvironmentsAllowed =
- subscription?.environmentLimit && currentProject?.environments
- ? currentProject.environments.length < subscription.environmentLimit
- : true;
-
- const [isNavigating, setIsNavigating] = useState(false);
-
- const navigate = useNavigate();
-
- const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp([
- "compareEnvironments",
- "createEnvironment",
- "upgradePlan"
- ] as const);
-
- const selectedIndex = currentProject.environments.findIndex((env) => env.slug === currentEnv);
-
- let tabEnvironments: ProjectEnv[];
- let dropdownEnvironments: ProjectEnv[];
-
- if (selectedIndex < TABS_TO_SHOW) {
- tabEnvironments = currentProject.environments.slice(0, TABS_TO_SHOW);
- dropdownEnvironments = currentProject.environments.slice(TABS_TO_SHOW);
- } else {
- tabEnvironments = [
- ...currentProject.environments.slice(0, TABS_TO_SHOW - 1),
- currentProject.environments[selectedIndex]
- ];
- dropdownEnvironments = currentProject.environments
- .slice(TABS_TO_SHOW - 1)
- .filter((env) => env.slug !== currentEnv);
- }
-
- const queryClient = useQueryClient();
-
- const handleSelect = async (envSlug: string) => {
- if (isNavigating) return;
-
- setIsNavigating(true);
- await navigate({
- to: ROUTE_PATHS.SecretManager.SecretDashboardPage.path,
- params: {
- envSlug,
- projectId: currentProject.id,
- orgId: currentOrg.id
- },
- search: (prev) => prev
- });
- setIsNavigating(false);
- };
-
- const handleAddEnvironment = () => {
- if (isMoreEnvironmentsAllowed) {
- handlePopUpOpen("createEnvironment");
- } else {
- handlePopUpOpen("upgradePlan");
- }
- };
-
- return (
- <>
- <Tabs
- value={currentEnv}
- onValueChange={(value) => {
- if (value === COMPARE_ENVIRONMENT_TAB) {
- handlePopUpOpen("compareEnvironments");
- return;
- }
-
- if (value === ADD_ENVIRONMENT_TAB) {
- handleAddEnvironment();
- return;
- }
-
- handleSelect(value);
- }}
- defaultValue="environment-tabs"
- >
- <TabList>
- {tabEnvironments.map((environment) => (
- <Tab key={environment.slug} className="max-w-[12vw] truncate" value={environment.slug}>
- <p className="truncate">{environment.name}</p>
- </Tab>
- ))}
- {dropdownEnvironments.length ? (
- <DropdownMenu>
- <DropdownMenuTrigger>
- <Tab value={VIEW_MORE_ENVIRONMENT_TAB} className="p-0">
- <Tooltip content="More Environments">
- <div className="px-3">
- <FontAwesomeIcon icon={faEllipsisH} />
- </div>
- </Tooltip>
- </Tab>
- </DropdownMenuTrigger>
- <DropdownMenuContent
- className="max-h-[70vh] thin-scrollbar overflow-y-auto"
- sideOffset={2}
- align="center"
- >
- <DropdownMenuLabel>Environments</DropdownMenuLabel>
- <div className="max-h-[40vh] thin-scrollbar overflow-auto">
- {dropdownEnvironments.map((environment) => (
- <DropdownMenuItem
- key={environment.id}
- onClick={(e) => {
- e.stopPropagation();
- handleSelect(environment.slug);
- }}
- >
- {environment.name}
- </DropdownMenuItem>
- ))}
- </div>
- <div className="h-1 border-t border-mineshaft-600" />
- <ProjectPermissionCan
- I={ProjectPermissionActions.Create}
- a={ProjectPermissionSub.Environments}
- >
- {(isAllowed) => (
- <DropdownMenuItem
- isDisabled={!isAllowed}
- onClick={handleAddEnvironment}
- className="data-highlighted:bg-mineshaft-900"
- >
- <Button
- size="xs"
- variant="outline_bg"
- leftIcon={<FontAwesomeIcon icon={faPlus} />}
- className="w-full"
- >
- Add Environment
- </Button>
- </DropdownMenuItem>
- )}
- </ProjectPermissionCan>
- </DropdownMenuContent>
- </DropdownMenu>
- ) : (
- <Tab value={ADD_ENVIRONMENT_TAB} className="p-0">
- <Tooltip content="Add environment">
- <div className="px-3">
- <FontAwesomeIcon icon={faPlus} />
- </div>
- </Tooltip>
- </Tab>
- )}
- {/* scott: removing until we have time to update for fetching secret value */}
- {/* {currentProject.environments.length > 1 && (
- <Tab className="ml-auto" value={COMPARE_ENVIRONMENT_TAB}>
- <div className="flex items-center gap-x-2 whitespace-nowrap">
- <FontAwesomeIcon icon={faArrowRightArrowLeft} />
- Compare Environments
- </div>
- </Tab>
- )} */}
- </TabList>
- </Tabs>
- <Modal
- isOpen={popUp.compareEnvironments.isOpen}
- onOpenChange={(isOpen) => handlePopUpToggle("compareEnvironments", isOpen)}
- >
- <ModalContent
- title="Compare Environments"
- subTitle="Compare secrets across multiple environments"
- className="flex h-full w-[95vw]! max-w-none flex-col"
- bodyClassName="flex-1 flex flex-col overflow-hidden"
- >
- <CompareEnvironments secretPath={secretPath} />
- </ModalContent>
- </Modal>
- <UpgradePlanModal
- isOpen={popUp.upgradePlan.isOpen}
- onOpenChange={(isOpen) => handlePopUpToggle("upgradePlan", isOpen)}
- text="Your current plan does not include access to adding custom environments. To unlock this feature, please upgrade to Infisical Pro plan."
- />
- <AddEnvironmentModal
- isOpen={popUp.createEnvironment.isOpen}
- onOpenChange={(isOpen) => handlePopUpToggle("createEnvironment", isOpen)}
- onComplete={async (env) => {
- await queryClient.refetchQueries({
- queryKey: projectKeys.getProjectById(currentProject.id)
- });
- handleSelect(env.slug);
- }}
- />
- </>
- );
-};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/EnvironmentTabs/index.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/EnvironmentTabs/index.tsx
deleted file mode 100644
index 76be6609bf..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/EnvironmentTabs/index.tsx
+++ /dev/null
@@ -1 +0,0 @@
-export * from "./EnvironmentTabs";
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/FolderBreadCrumbs/FolderBreadCrumbs.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/FolderBreadCrumbs/FolderBreadCrumbs.tsx
deleted file mode 100644
index bb4488a67e..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/FolderBreadCrumbs/FolderBreadCrumbs.tsx
+++ /dev/null
@@ -1,52 +0,0 @@
-import { faFolderOpen } from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import { useNavigate } from "@tanstack/react-router";
-
-type Props = {
- secretPath: string;
-};
-
-export const FolderBreadCrumbs = ({ secretPath = "/" }: Props) => {
- const navigate = useNavigate({
- from: "/organizations/$orgId/projects/secret-management/$projectId/secrets/$envSlug"
- });
-
- const onFolderCrumbClick = (index: number) => {
- const newSecPath = `/${secretPath.split("/").filter(Boolean).slice(0, index).join("/")}`;
- if (secretPath === newSecPath) return;
- navigate({
- search: (prev) => ({ ...prev, secretPath: newSecPath })
- });
- };
-
- return (
- <div className="mb-3 flex flex-wrap items-center gap-x-2 gap-y-3">
- <div
- className="breadcrumb relative z-20 border-solid border-mineshaft-600 bg-mineshaft-800 py-1 pr-2 pl-5 text-sm hover:bg-mineshaft-600"
- onClick={() => onFolderCrumbClick(0)}
- onKeyDown={() => null}
- role="button"
- tabIndex={0}
- >
- <FontAwesomeIcon icon={faFolderOpen} className="text-primary-700" />
- </div>
- {(secretPath || "")
- .split("/")
- .filter(Boolean)
- .map((path, index, arr) => (
- <div
- key={`secret-path-${index + 1}`}
- className={`breadcrumb relative z-20 ${
- index + 1 === arr.length ? "cursor-default" : "cursor-pointer"
- } border-solid border-mineshaft-600 py-1 pr-2 pl-5 text-sm text-mineshaft-200`}
- onClick={() => onFolderCrumbClick(index + 1)}
- onKeyDown={() => null}
- role="button"
- tabIndex={0}
- >
- {path}
- </div>
- ))}
- </div>
- );
-};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/FolderBreadCrumbs/index.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/FolderBreadCrumbs/index.tsx
deleted file mode 100644
index 8224cdb25c..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/FolderBreadCrumbs/index.tsx
+++ /dev/null
@@ -1 +0,0 @@
-export { FolderBreadCrumbs } from "./FolderBreadCrumbs";
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/FolderListView/FolderListView.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/FolderListView/FolderListView.tsx
deleted file mode 100644
index 942e792e60..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/FolderListView/FolderListView.tsx
+++ /dev/null
@@ -1,330 +0,0 @@
-import { subject } from "@casl/ability";
-import {
- faClose,
- faEdit,
- faFolder,
- faInfoCircle,
- faPencilSquare,
- faTrash
-} from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import { useNavigate, useSearch } from "@tanstack/react-router";
-import { twMerge } from "tailwind-merge";
-
-import { createNotification } from "@app/components/notifications";
-import { ProjectPermissionCan } from "@app/components/permissions";
-import { DeleteActionModal, IconButton } from "@app/components/v2";
-import { Tooltip } from "@app/components/v2/Tooltip/Tooltip";
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogHeader,
- DialogTitle
-} from "@app/components/v3";
-import { ROUTE_PATHS } from "@app/const/routes";
-import { ProjectPermissionActions, ProjectPermissionSub, useSubscription } from "@app/context";
-import { usePopUp } from "@app/hooks";
-import { useDeleteFolder, useUpdateFolder } from "@app/hooks/api";
-import { PendingAction, TSecretFolder } from "@app/hooks/api/secretFolders/types";
-
-import {
- PendingFolderCreate,
- PendingFolderDelete,
- PendingFolderUpdate,
- useBatchMode,
- useBatchModeActions
-} from "../../SecretMainPage.store";
-import { FolderForm } from "../ActionBar/FolderForm";
-
-type Props = {
- folders?: TSecretFolder[];
- environment: string;
- projectId: string;
- secretPath?: string;
- onNavigateToFolder: (path: string) => void;
- canNavigate: boolean;
-};
-
-export const FolderListView = ({
- folders = [],
- environment,
- projectId,
- secretPath = "/",
- onNavigateToFolder,
- canNavigate
-}: Props) => {
- const { popUp, handlePopUpToggle, handlePopUpOpen, handlePopUpClose } = usePopUp([
- "updateFolder",
- "deleteFolder"
- ] as const);
- const navigate = useNavigate({ from: ROUTE_PATHS.SecretManager.SecretDashboardPage.path });
- const secretPathQueryparam = useSearch({
- from: ROUTE_PATHS.SecretManager.SecretDashboardPage.id,
- select: (el) => el.secretPath
- });
- const { subscription } = useSubscription();
-
- const { mutateAsync: updateFolder } = useUpdateFolder();
- const { mutateAsync: deleteFolder } = useDeleteFolder();
- const { isBatchMode } = useBatchMode();
- const { addPendingChange, removePendingChange } = useBatchModeActions();
-
- const handleFolderUpdate = async (
- newFolderName: string,
- newFolderDescription: string | null,
- oldFolderName?: string,
- oldFolderDescription?: string
- ) => {
- const updateFolderData = popUp.updateFolder.data;
- if (!updateFolderData) throw new Error("Update folder data is required");
- const { id: folderId, pendingAction, isPending } = updateFolderData as TSecretFolder;
-
- if (isBatchMode) {
- const isEditingPendingCreation = isPending && pendingAction === PendingAction.Create;
-
- if (isEditingPendingCreation) {
- const updatedCreate: PendingFolderCreate = {
- id: folderId,
- type: PendingAction.Create,
- folderName: newFolderName,
- description: newFolderDescription || undefined,
- parentPath: secretPath,
- timestamp: Date.now(),
- resourceType: "folder"
- };
-
- addPendingChange(updatedCreate, {
- projectId,
- environment,
- secretPath
- });
- } else {
- const updateChange: PendingFolderUpdate = {
- id: folderId,
- type: PendingAction.Update,
- originalFolderName: oldFolderName || "",
- folderName: newFolderName,
- originalDescription: oldFolderDescription,
- description: newFolderDescription || undefined,
- timestamp: Date.now(),
- resourceType: "folder"
- };
-
- addPendingChange(updateChange, {
- projectId,
- environment,
- secretPath
- });
- }
-
- handlePopUpClose("updateFolder");
- return;
- }
-
- await updateFolder({
- folderId,
- name: newFolderName,
- path: secretPath,
- environment,
- projectId,
- description: newFolderDescription
- });
- handlePopUpClose("updateFolder");
- createNotification({
- type: "success",
- text: "Successfully saved folder"
- });
- };
-
- const handleDeletePending = (id: string) => {
- removePendingChange(id, "folder", {
- projectId,
- environment,
- secretPath
- });
- };
-
- const handleFolderDelete = async () => {
- const folderData = popUp.deleteFolder?.data as TSecretFolder;
-
- if (isBatchMode) {
- const pendingFolderDelete: PendingFolderDelete = {
- id: folderData.id,
- folderName: folderData.name,
- folderPath: secretPath,
- resourceType: "folder",
- type: PendingAction.Delete,
- timestamp: Date.now()
- };
-
- addPendingChange(pendingFolderDelete, {
- projectId,
- environment,
- secretPath
- });
-
- handlePopUpClose("deleteFolder");
- return;
- }
-
- await deleteFolder({
- folderId: folderData.id,
- path: secretPath,
- environment,
- projectId
- });
-
- handlePopUpClose("deleteFolder");
- createNotification({
- type: "success",
- text: "Successfully deleted folder"
- });
- };
-
- const handleFolderClick = (name: string, isPending?: boolean) => {
- if (isPending || !canNavigate) {
- return;
- }
- const path = `${secretPathQueryparam === "/" ? "" : secretPathQueryparam}/${name}`;
- navigate({
- search: (el) => ({ ...el, secretPath: path })
- }).then(() => onNavigateToFolder(path));
- };
-
- return (
- <>
- {folders.map(({ name, id, description, pendingAction, isPending }) => (
- <div
- key={id}
- className={twMerge(
- "group flex cursor-pointer border-b border-mineshaft-600 hover:bg-mineshaft-700",
- isPending && "bg-mineshaft-700/60",
- pendingAction === PendingAction.Delete && "border-l-2 border-l-red-600/75",
- pendingAction === PendingAction.Update && "border-l-2 border-l-yellow-600/75",
- pendingAction === PendingAction.Create && "border-l-2 border-l-green-600/75"
- )}
- >
- <div className="flex w-11 items-center px-5 py-3 text-yellow-700">
- <FontAwesomeIcon icon={faFolder} />
- </div>
- <div
- className="flex grow items-center px-4 py-3"
- role="button"
- tabIndex={0}
- onKeyDown={(evt) => {
- if (evt.key === "Enter") handleFolderClick(name, isPending);
- }}
- onClick={() => handleFolderClick(name, isPending)}
- >
- {name}
- {description && (
- <Tooltip
- position="right"
- className="flex max-w-lg items-center space-x-4 py-4 whitespace-pre-wrap"
- content={description}
- >
- <FontAwesomeIcon icon={faInfoCircle} className="ml-1 text-mineshaft-400" />
- </Tooltip>
- )}
- </div>
- {isPending ? (
- <div className="flex w-16 items-center justify-between border-l border-mineshaft-600 px-3 py-3">
- <IconButton
- ariaLabel="edit-folder"
- variant="plain"
- size="sm"
- className="p-0 opacity-0 group-hover:opacity-100"
- isDisabled
- onClick={() => {}}
- >
- <FontAwesomeIcon icon={faPencilSquare} size="lg" />
- </IconButton>
-
- <IconButton
- ariaLabel="delete-folder"
- variant="plain"
- size="md"
- className="p-0 opacity-0 group-hover:opacity-100"
- onClick={() => handleDeletePending(id)}
- >
- <FontAwesomeIcon icon={faClose} size="lg" />
- </IconButton>
- </div>
- ) : (
- <div className="flex w-16 items-center justify-between border-l border-mineshaft-600 px-3 py-3">
- <ProjectPermissionCan
- I={ProjectPermissionActions.Edit}
- a={subject(ProjectPermissionSub.SecretFolders, { environment, secretPath })}
- renderTooltip
- allowedLabel="Edit"
- >
- {(isAllowed) => (
- <IconButton
- ariaLabel="edit-folder"
- variant="plain"
- size="sm"
- className="p-0 opacity-0 group-hover:opacity-100"
- onClick={() => handlePopUpOpen("updateFolder", { id, name, description })}
- isDisabled={!isAllowed}
- >
- <FontAwesomeIcon icon={faEdit} />
- </IconButton>
- )}
- </ProjectPermissionCan>
- <ProjectPermissionCan
- I={ProjectPermissionActions.Delete}
- a={subject(ProjectPermissionSub.SecretFolders, { environment, secretPath })}
- renderTooltip
- allowedLabel="Delete"
- >
- {(isAllowed) => (
- <IconButton
- ariaLabel="delete-folder"
- variant="plain"
- colorSchema="danger"
- size="md"
- className="p-0 opacity-0 group-hover:opacity-100"
- onClick={() => handlePopUpOpen("deleteFolder", { id, name })}
- isDisabled={!isAllowed}
- >
- <FontAwesomeIcon icon={faTrash} />
- </IconButton>
- )}
- </ProjectPermissionCan>
- </div>
- )}
- </div>
- ))}
- <Dialog
- open={popUp.updateFolder.isOpen}
- onOpenChange={(isOpen) => handlePopUpToggle("updateFolder", isOpen)}
- >
- <DialogContent className="max-w-lg">
- <DialogHeader>
- <DialogTitle>Edit Folder</DialogTitle>
- <DialogDescription>Update the folder name and description.</DialogDescription>
- </DialogHeader>
- <FolderForm
- isEdit
- defaultFolderName={(popUp.updateFolder?.data as TSecretFolder)?.name}
- defaultDescription={(popUp.updateFolder?.data as TSecretFolder)?.description}
- onUpdateFolder={handleFolderUpdate}
- />
- </DialogContent>
- </Dialog>
- <DeleteActionModal
- isOpen={popUp.deleteFolder.isOpen}
- deleteKey={(popUp.deleteFolder?.data as TSecretFolder)?.name}
- title="Do you want to delete this folder?"
- subTitle={`This folder and all its contents will be removed. ${
- subscription?.pitRecovery
- ? "You can reverse this action by rolling back to a previous commit."
- : "Rolling back to a previous commit isn't available on your current plan. Upgrade to enable this feature."
- }`}
- onChange={(isOpen) => handlePopUpToggle("deleteFolder", isOpen)}
- onDeleteApproved={handleFolderDelete}
- />
- </>
- );
-};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/FolderListView/index.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/FolderListView/index.tsx
deleted file mode 100644
index 32326edd84..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/FolderListView/index.tsx
+++ /dev/null
@@ -1 +0,0 @@
-export { FolderListView } from "./FolderListView";
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/HoneyTokenListView/HoneyTokenItem.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/HoneyTokenListView/HoneyTokenItem.tsx
deleted file mode 100644
index dc88d8daa5..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/HoneyTokenListView/HoneyTokenItem.tsx
+++ /dev/null
@@ -1,245 +0,0 @@
-import { useState } from "react";
-import { subject } from "@casl/ability";
-import { AnimatePresence, motion } from "framer-motion";
-import {
- AsteriskIcon,
- BanIcon,
- ExternalLinkIcon,
- HexagonIcon,
- InfoIcon,
- PencilIcon
-} from "lucide-react";
-import { twMerge } from "tailwind-merge";
-
-import { ProjectPermissionCan } from "@app/components/permissions";
-import { Checkbox } from "@app/components/v2";
-import { Badge, IconButton, Tooltip, TooltipContent, TooltipTrigger } from "@app/components/v3";
-import { ProjectPermissionSub } from "@app/context";
-import { ProjectPermissionHoneyTokenActions } from "@app/context/ProjectPermissionContext/types";
-import { HONEY_TOKEN_MAP } from "@app/helpers/honeyTokens";
-import { HoneyTokenStatus, HoneyTokenType } from "@app/hooks/api/honeyTokens/enums";
-import { TDashboardHoneyToken } from "@app/hooks/api/honeyTokens/types";
-
-type Props = {
- honeyToken: TDashboardHoneyToken;
- isSelected: boolean;
- onToggleSelect: () => void;
- onEdit: () => void;
- onRevoke: () => void;
- onViewCredentials: () => void;
- onViewDetails: () => void;
-};
-
-export const HoneyTokenItem = ({
- honeyToken,
- isSelected,
- onToggleSelect,
- onEdit,
- onRevoke,
- onViewCredentials,
- onViewDetails
-}: Props) => {
- const { name, type, status, secretsMapping } = honeyToken;
- const isRevoked = status === HoneyTokenStatus.Revoked;
- const [isExpanded, setIsExpanded] = useState(true);
-
- const honeyTokenInfo = HONEY_TOKEN_MAP[type as HoneyTokenType];
- const mappedSecretKeys = Object.values(secretsMapping || {});
-
- const statusVariantMap: Record<string, "success" | "danger" | "neutral"> = {
- [HoneyTokenStatus.Active]: "success",
- [HoneyTokenStatus.Triggered]: "danger",
- [HoneyTokenStatus.Revoked]: "neutral"
- };
-
- return (
- <>
- <div
- className={twMerge(
- "group flex cursor-pointer border-b border-mineshaft-600 hover:bg-mineshaft-700"
- )}
- onClick={() => setIsExpanded(!isExpanded)}
- onKeyDown={(e) => {
- if (e.key === "Enter" || e.key === " ") {
- e.preventDefault();
- setIsExpanded(!isExpanded);
- }
- }}
- role="button"
- tabIndex={0}
- aria-expanded={isExpanded}
- aria-label={`${isExpanded ? "Collapse" : "Expand"} honey token secrets for ${name}`}
- >
- <div
- className={twMerge(
- "flex w-11 items-center py-2 pl-5",
- status === HoneyTokenStatus.Triggered && "text-red",
- status === HoneyTokenStatus.Active && "text-yellow",
- status === HoneyTokenStatus.Revoked && "text-mineshaft-400"
- )}
- >
- <div className={twMerge("ml-[-1px] hidden group-hover:flex", isSelected && "flex")}>
- <Checkbox
- id={`checkbox-honey-token-${honeyToken.id}`}
- isChecked={isSelected}
- onCheckedChange={onToggleSelect}
- onClick={(e) => e.stopPropagation()}
- className={twMerge("hidden group-hover:flex", isSelected && "flex")}
- />
- </div>
- <HexagonIcon className={twMerge("size-4 group-hover:hidden", isSelected && "hidden")} />
- </div>
- <div className="flex grow items-center py-2 pr-2 pl-4">
- <div className="flex w-full flex-wrap items-center">
- <span>{name}</span>
- {honeyTokenInfo && (
- <Badge variant="neutral" className="mx-2.5">
- <img
- src={`/images/integrations/${honeyTokenInfo.image}`}
- style={{ width: "11px" }}
- alt={`${honeyTokenInfo.name} logo`}
- />
- {honeyTokenInfo.name} Honey Token
- </Badge>
- )}
- <Badge variant={statusVariantMap[status] ?? "neutral"}>
- {status === HoneyTokenStatus.Active && "Active"}
- {status === HoneyTokenStatus.Triggered && "Triggered"}
- {status === HoneyTokenStatus.Revoked && "Revoked"}
- </Badge>
- </div>
- <div
- key="actions"
- className="ml-2 flex h-full shrink-0 self-start transition-all group-hover:gap-x-2"
- >
- <Tooltip>
- <TooltipTrigger asChild>
- <InfoIcon className="size-4 text-mineshaft-400" />
- </TooltipTrigger>
- <TooltipContent>{mappedSecretKeys.length} mapped secret(s)</TooltipContent>
- </Tooltip>
- </div>
- </div>
- <AnimatePresence mode="wait">
- <motion.div
- key="options"
- className="flex w-32 items-center justify-between border-l border-mineshaft-600 px-2 py-3"
- initial={{ x: 0, opacity: 0 }}
- animate={{ x: 0, opacity: 1 }}
- exit={{ x: 10, opacity: 0 }}
- >
- <Tooltip>
- <TooltipTrigger asChild>
- <IconButton
- aria-label="View details"
- variant="ghost"
- size="xs"
- className="opacity-0 group-hover:opacity-100"
- onClick={(e) => {
- e.stopPropagation();
- onViewDetails();
- }}
- >
- <ExternalLinkIcon className="size-4" />
- </IconButton>
- </TooltipTrigger>
- <TooltipContent>View details</TooltipContent>
- </Tooltip>
- <ProjectPermissionCan
- I={ProjectPermissionHoneyTokenActions.ReadCredentials}
- a={subject(ProjectPermissionSub.HoneyTokens, {
- environment: honeyToken.environment.slug,
- secretPath: honeyToken.folder.path
- })}
- renderTooltip
- allowedLabel="View credentials"
- >
- {(isAllowed) => (
- <IconButton
- aria-label="View credentials"
- variant="ghost"
- size="xs"
- isDisabled={!isAllowed || isRevoked}
- className="opacity-0 group-hover:opacity-100"
- onClick={(e) => {
- e.stopPropagation();
- onViewCredentials();
- }}
- >
- <AsteriskIcon className="size-4" />
- </IconButton>
- )}
- </ProjectPermissionCan>
- <ProjectPermissionCan
- I={ProjectPermissionHoneyTokenActions.Edit}
- a={subject(ProjectPermissionSub.HoneyTokens, {
- environment: honeyToken.environment.slug,
- secretPath: honeyToken.folder.path
- })}
- renderTooltip
- allowedLabel="Edit"
- >
- {(isAllowed) => (
- <IconButton
- aria-label="Edit honey token"
- variant="ghost"
- size="xs"
- isDisabled={!isAllowed || isRevoked}
- className="opacity-0 group-hover:opacity-100"
- onClick={(e) => {
- e.stopPropagation();
- onEdit();
- }}
- >
- <PencilIcon className="size-4" />
- </IconButton>
- )}
- </ProjectPermissionCan>
- {status !== HoneyTokenStatus.Revoked && (
- <ProjectPermissionCan
- I={ProjectPermissionHoneyTokenActions.Revoke}
- a={subject(ProjectPermissionSub.HoneyTokens, {
- environment: honeyToken.environment.slug,
- secretPath: honeyToken.folder.path
- })}
- renderTooltip
- allowedLabel="Revoke"
- >
- {(isAllowed) => (
- <IconButton
- aria-label="Revoke honey token"
- variant="danger"
- size="xs"
- className="opacity-0 group-hover:opacity-100"
- onClick={(e) => {
- e.stopPropagation();
- onRevoke();
- }}
- isDisabled={!isAllowed}
- >
- <BanIcon className="size-4" />
- </IconButton>
- )}
- </ProjectPermissionCan>
- )}
- </motion.div>
- </AnimatePresence>
- </div>
- {isExpanded && (
- <div className="border-b border-mineshaft-600 bg-bunker-800">
- {mappedSecretKeys.map((secretKey) => (
- <div
- key={secretKey}
- className="flex items-center border-b border-mineshaft-700 px-5 py-2 pl-16 last:border-b-0"
- >
- <span className="font-mono text-sm text-bunker-200">{secretKey}</span>
- <Badge variant="warning" className="ml-2">
- Decoy
- </Badge>
- </div>
- ))}
- </div>
- )}
- </>
- );
-};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/HoneyTokenListView/HoneyTokenListView.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/HoneyTokenListView/HoneyTokenListView.tsx
deleted file mode 100644
index bee9bc08f4..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/HoneyTokenListView/HoneyTokenListView.tsx
+++ /dev/null
@@ -1,77 +0,0 @@
-import { useState } from "react";
-
-import {
- EditHoneyTokenModal,
- HoneyTokenDetailsDrawer,
- RevokeHoneyTokenModal,
- ViewHoneyTokenCredentialsModal
-} from "@app/components/honey-tokens";
-import { useProject } from "@app/context";
-import { TDashboardHoneyToken } from "@app/hooks/api/honeyTokens/types";
-
-import { HoneyTokenItem } from "./HoneyTokenItem";
-
-type Props = {
- honeyTokens?: TDashboardHoneyToken[];
-};
-
-export const HoneyTokenListView = ({ honeyTokens }: Props) => {
- const { projectId } = useProject();
-
- const [revokeTarget, setRevokeTarget] = useState<TDashboardHoneyToken>();
- const [editTarget, setEditTarget] = useState<TDashboardHoneyToken>();
- const [credentialsTarget, setCredentialsTarget] = useState<TDashboardHoneyToken>();
- const [detailsHoneyTokenId, setDetailsHoneyTokenId] = useState<string | null>(null);
- const [selectedHoneyTokenIds, setSelectedHoneyTokenIds] = useState<Record<string, boolean>>({});
-
- const toggleHoneyTokenSelect = (honeyTokenId: string) => {
- setSelectedHoneyTokenIds((prev) => ({
- ...prev,
- [honeyTokenId]: !prev[honeyTokenId]
- }));
- };
-
- return (
- <>
- {honeyTokens?.map((honeyToken) => (
- <HoneyTokenItem
- key={honeyToken.id}
- honeyToken={honeyToken}
- isSelected={Boolean(selectedHoneyTokenIds[honeyToken.id])}
- onToggleSelect={() => toggleHoneyTokenSelect(honeyToken.id)}
- onEdit={() => setEditTarget(honeyToken)}
- onRevoke={() => setRevokeTarget(honeyToken)}
- onViewCredentials={() => setCredentialsTarget(honeyToken)}
- onViewDetails={() => setDetailsHoneyTokenId(honeyToken.id)}
- />
- ))}
- <EditHoneyTokenModal
- isOpen={Boolean(editTarget)}
- onOpenChange={(isOpen) => {
- if (!isOpen) setEditTarget(undefined);
- }}
- honeyToken={editTarget}
- />
- <RevokeHoneyTokenModal
- isOpen={Boolean(revokeTarget)}
- onOpenChange={(isOpen) => {
- if (!isOpen) setRevokeTarget(undefined);
- }}
- honeyToken={revokeTarget}
- />
- <ViewHoneyTokenCredentialsModal
- isOpen={Boolean(credentialsTarget)}
- onOpenChange={(isOpen) => {
- if (!isOpen) setCredentialsTarget(undefined);
- }}
- honeyToken={credentialsTarget}
- projectId={projectId}
- />
- <HoneyTokenDetailsDrawer
- projectId={projectId}
- honeyTokenId={detailsHoneyTokenId}
- onClose={() => setDetailsHoneyTokenId(null)}
- />
- </>
- );
-};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/HoneyTokenListView/index.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/HoneyTokenListView/index.tsx
deleted file mode 100644
index 3aa71fd2e5..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/HoneyTokenListView/index.tsx
+++ /dev/null
@@ -1 +0,0 @@
-export { HoneyTokenListView } from "./HoneyTokenListView";
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretDropzone/CopySecretsFromBoard.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretDropzone/CopySecretsFromBoard.tsx
deleted file mode 100644
index ef56c2e3b4..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretDropzone/CopySecretsFromBoard.tsx
+++ /dev/null
@@ -1,268 +0,0 @@
-import { useEffect, useState } from "react";
-import { Controller, useForm } from "react-hook-form";
-import { subject } from "@casl/ability";
-import { faClone, faFileImport, faSquareCheck } from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import { zodResolver } from "@hookform/resolvers/zod";
-import { z } from "zod";
-
-import { ProjectPermissionCan } from "@app/components/permissions";
-import {
- Button,
- FilterableSelect,
- FormControl,
- IconButton,
- Modal,
- ModalContent,
- ModalTrigger,
- Switch,
- Tooltip
-} from "@app/components/v2";
-import { SecretPathInput } from "@app/components/v2/SecretPathInput";
-import { ProjectPermissionActions, ProjectPermissionSub } from "@app/context";
-import { ProjectPermissionSecretActions } from "@app/context/ProjectPermissionContext/types";
-import { useDebounce } from "@app/hooks";
-import { useGetAccessibleSecrets } from "@app/hooks/api/dashboard";
-
-const formSchema = z.object({
- environment: z.object({ name: z.string(), slug: z.string() }),
- secretPath: z
- .string()
- .trim()
- .transform((val) =>
- typeof val === "string" && val.at(-1) === "/" && val.length > 1 ? val.slice(0, -1) : val
- ),
- secrets: z
- .object({ secretKey: z.string(), secretValue: z.string().optional() })
- .array()
- .min(1, "Select one or more secrets to copy")
-});
-
-type TFormSchema = z.infer<typeof formSchema>;
-
-type Props = {
- isOpen?: boolean;
- isSmaller?: boolean;
- onToggle: (isOpen: boolean) => void;
- onParsedEnv: (env: Record<string, { value: string; comments: string[] }>) => void;
- environments?: { name: string; slug: string }[];
- projectId: string;
- environment: string;
- secretPath: string;
-};
-
-export const CopySecretsFromBoard = ({
- environments = [],
- projectId,
- environment,
- secretPath,
- isOpen,
- isSmaller,
- onToggle,
- onParsedEnv
-}: Props) => {
- const [shouldIncludeValues, setShouldIncludeValues] = useState(true);
-
- const {
- handleSubmit,
- control,
- watch,
- reset,
- setValue,
- formState: { isDirty }
- } = useForm<TFormSchema>({
- resolver: zodResolver(formSchema),
- defaultValues: { secretPath: "/", environment: environments?.[0] }
- });
-
- const envCopySecPath = watch("secretPath");
- const selectedEnvSlug = watch("environment");
- const [debouncedEnvCopySecretPath] = useDebounce(envCopySecPath);
-
- const { data: accessibleSecrets, isPending: isAccessibleSecretsLoading } =
- useGetAccessibleSecrets({
- projectId,
- secretPath: debouncedEnvCopySecretPath,
- environment: selectedEnvSlug.slug,
- filterByAction: shouldIncludeValues
- ? ProjectPermissionSecretActions.ReadValue
- : ProjectPermissionSecretActions.DescribeSecret,
- options: {
- enabled:
- Boolean(projectId) &&
- Boolean(selectedEnvSlug) &&
- Boolean(debouncedEnvCopySecretPath) &&
- isOpen
- }
- });
-
- useEffect(() => {
- setValue("secrets", []);
- }, [debouncedEnvCopySecretPath, selectedEnvSlug]);
-
- const handleSecSelectAll = () => {
- if (accessibleSecrets) {
- setValue("secrets", accessibleSecrets, { shouldDirty: true });
- }
- };
-
- const handleFormSubmit = async (data: TFormSchema) => {
- const secretsToBePulled: Record<string, { value: string; comments: string[] }> = {};
- data.secrets.forEach(({ secretKey, secretValue }) => {
- secretsToBePulled[secretKey] = {
- value: (shouldIncludeValues && secretValue) || "",
- comments: [""]
- };
- });
- onParsedEnv(secretsToBePulled);
- onToggle(false);
- reset();
- };
-
- return (
- <Modal
- isOpen={isOpen}
- onOpenChange={(state) => {
- onToggle(state);
- reset();
- }}
- >
- <ModalTrigger asChild>
- <div>
- <ProjectPermissionCan
- I={ProjectPermissionActions.Create}
- a={subject(ProjectPermissionSub.Secrets, {
- environment,
- secretPath,
- secretName: "*",
- secretTags: ["*"]
- })}
- >
- {(isAllowed) => (
- <Button
- leftIcon={<FontAwesomeIcon icon={faFileImport} />}
- onClick={() => onToggle(true)}
- isDisabled={!isAllowed}
- variant="star"
- size={isSmaller ? "xs" : "sm"}
- >
- Copy Secrets From An Environment
- </Button>
- )}
- </ProjectPermissionCan>
- </div>
- </ModalTrigger>
- <ModalContent
- bodyClassName="overflow-visible"
- className="max-w-2xl"
- title="Copy Secret From An Environment"
- subTitle="Copy/paste secrets from other environments into this context"
- >
- <form onSubmit={handleSubmit(handleFormSubmit)}>
- <div className="flex items-center space-x-2">
- <Controller
- control={control}
- name="environment"
- render={({ field: { value, onChange } }) => (
- <FormControl label="Environment" isRequired className="w-1/3">
- <FilterableSelect
- value={value}
- onChange={onChange}
- options={environments}
- placeholder="Select environment..."
- getOptionLabel={(option) => option.name}
- getOptionValue={(option) => option.slug}
- />
- </FormControl>
- )}
- />
- <Controller
- control={control}
- name="secretPath"
- render={({ field }) => (
- <FormControl label="Secret Path" className="grow" isRequired>
- <SecretPathInput
- {...field}
- placeholder="Provide a path, default is /"
- environment={selectedEnvSlug?.slug}
- />
- </FormControl>
- )}
- />
- </div>
- <div className="border-t border-mineshaft-600 pt-4">
- <div className="mb-4 flex items-center justify-between">
- <div>Secrets</div>
- </div>
- <div className="flex w-full items-start gap-3">
- <Controller
- control={control}
- name="secrets"
- render={({ field: { value, onChange }, fieldState: { error } }) => (
- <FormControl
- className="flex-1"
- isError={Boolean(error)}
- errorText={error?.message}
- >
- <FilterableSelect
- placeholder={
- // eslint-disable-next-line no-nested-ternary
- isAccessibleSecretsLoading
- ? "Loading secrets..."
- : accessibleSecrets?.length
- ? "Select secrets..."
- : "No secrets found..."
- }
- isLoading={isAccessibleSecretsLoading}
- options={accessibleSecrets}
- value={value}
- onChange={onChange}
- isMulti
- getOptionValue={(option) => option.secretKey}
- getOptionLabel={(option) => option.secretKey}
- />
- </FormControl>
- )}
- />
- <Tooltip content="Select All">
- <IconButton
- className="mt-1 h-9 w-9"
- ariaLabel="Select all"
- variant="outline_bg"
- size="xs"
- onClick={handleSecSelectAll}
- >
- <FontAwesomeIcon icon={faSquareCheck} size="lg" />
- </IconButton>
- </Tooltip>
- </div>
- <div className="my-6 ml-2">
- <Switch
- id="populate-include-value"
- isChecked={shouldIncludeValues}
- onCheckedChange={(isChecked) => {
- setValue("secrets", []);
- setShouldIncludeValues(isChecked as boolean);
- }}
- >
- Include secret values
- </Switch>
- </div>
- <div className="flex items-center space-x-4">
- <Button
- leftIcon={<FontAwesomeIcon icon={faClone} />}
- type="submit"
- isDisabled={!isDirty}
- >
- Copy Secrets
- </Button>
- <Button variant="plain" colorSchema="secondary" onClick={() => onToggle(false)}>
- Cancel
- </Button>
- </div>
- </div>
- </form>
- </ModalContent>
- </Modal>
- );
-};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretDropzone/PasteSecretEnvModal.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretDropzone/PasteSecretEnvModal.tsx
deleted file mode 100644
index c31afc9833..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretDropzone/PasteSecretEnvModal.tsx
+++ /dev/null
@@ -1,165 +0,0 @@
-import { useForm } from "react-hook-form";
-import { subject } from "@casl/ability";
-import { faInfoCircle, faPaste } from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import { zodResolver } from "@hookform/resolvers/zod";
-import { z } from "zod";
-
-import { ProjectPermissionCan } from "@app/components/permissions";
-import { parseDotEnv, parseJson } from "@app/components/utilities/parseSecrets";
-import {
- Button,
- FormControl,
- Modal,
- ModalContent,
- ModalTrigger,
- TextArea
-} from "@app/components/v2";
-import { ProjectPermissionActions, ProjectPermissionSub } from "@app/context";
-
-type Props = {
- isOpen?: boolean;
- isSmaller?: boolean;
- onToggle: (isOpen: boolean) => void;
- onParsedEnv: (env: Record<string, { value: string; comments: string[] }>) => void;
- environment: string;
- secretPath: string;
-};
-
-const formSchema = z.object({
- value: z.string().trim()
-});
-
-type TForm = z.infer<typeof formSchema>;
-
-const PasteEnvForm = ({ onParsedEnv }: Pick<Props, "onParsedEnv">) => {
- const {
- handleSubmit,
- register,
- formState: { isDirty, errors },
- setError,
- setFocus
- } = useForm<TForm>({ defaultValues: { value: "" }, resolver: zodResolver(formSchema) });
-
- const onSubmit = ({ value }: TForm) => {
- let env: Record<string, { value: string; comments: string[] }>;
- try {
- env = parseJson(value);
- } catch {
- // not json, parse as env
- env = parseDotEnv(value);
- }
-
- if (!Object.keys(env).length) {
- setError("value", {
- message: "No secrets found. Please make sure the provided format is valid."
- });
- setFocus("value");
- return;
- }
-
- onParsedEnv(env);
- };
-
- return (
- <form onSubmit={handleSubmit(onSubmit)}>
- <FormControl
- label="Secret Values"
- isError={Boolean(errors.value)}
- errorText={errors.value?.message}
- icon={<FontAwesomeIcon size="sm" className="text-mineshaft-400" icon={faInfoCircle} />}
- tooltipClassName="max-w-lg px-2 whitespace-pre-line"
- tooltipText={
- <div className="flex flex-col gap-2">
- <p>Example Formats:</p>
- <pre className="rounded-md bg-mineshaft-900 p-3 text-xs">
- {/* eslint-disable-next-line react/jsx-no-comment-textnodes */}
- <p className="text-mineshaft-400">// .json</p>
- {JSON.stringify(
- {
- APP_NAME: "example-service",
- APP_VERSION: "1.2.3",
- NODE_ENV: "production"
- },
- null,
- 2
- )}
- </pre>
- <pre className="rounded-md bg-mineshaft-900 p-3 text-xs">
- <p className="text-mineshaft-400"># .env</p>
- <p>APP_NAME=&quot;example-service&quot;</p>
- <p>APP_VERSION=&quot;1.2.3&quot;</p>
- <p>NODE_ENV=&quot;production&quot;</p>
- </pre>
- <pre className="rounded-md bg-mineshaft-900 p-3 text-xs">
- <p className="text-mineshaft-400"># .yml</p>
- <p>APP_NAME: example-service</p>
- <p>APP_VERSION: 1.2.3</p>
- <p>NODE_ENV: production</p>
- </pre>
- </div>
- }
- >
- <TextArea
- {...register("value")}
- placeholder="Paste secrets in .json, .yml or .env format..."
- className="h-[60vh] resize-none!"
- />
- </FormControl>
- <Button isDisabled={!isDirty} type="submit">
- Import Secrets
- </Button>
- </form>
- );
-};
-
-export const PasteSecretEnvModal = ({
- isSmaller,
- isOpen,
- onParsedEnv,
- onToggle,
- environment,
- secretPath
-}: Props) => {
- return (
- <Modal isOpen={isOpen} onOpenChange={onToggle}>
- <ModalTrigger asChild>
- <div>
- <ProjectPermissionCan
- I={ProjectPermissionActions.Create}
- a={subject(ProjectPermissionSub.Secrets, {
- environment,
- secretPath,
- secretName: "*",
- secretTags: ["*"]
- })}
- >
- {(isAllowed) => (
- <Button
- leftIcon={<FontAwesomeIcon icon={faPaste} />}
- onClick={() => onToggle(true)}
- isDisabled={!isAllowed}
- variant="star"
- size={isSmaller ? "xs" : "sm"}
- >
- Paste Secrets
- </Button>
- )}
- </ProjectPermissionCan>
- </div>
- </ModalTrigger>
- <ModalContent
- className="max-w-2xl"
- title="Past Secret Values"
- subTitle="Paste values in .env, .json or .yml format"
- >
- <PasteEnvForm
- onParsedEnv={(value) => {
- onToggle(false);
- onParsedEnv(value);
- }}
- />
- </ModalContent>
- </Modal>
- );
-};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretDropzone/SecretDropzone.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretDropzone/SecretDropzone.tsx
deleted file mode 100644
index 87f95a1cbb..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretDropzone/SecretDropzone.tsx
+++ /dev/null
@@ -1,578 +0,0 @@
-import { ChangeEvent, Dispatch, DragEvent, SetStateAction, useState } from "react";
-import { useTranslation } from "react-i18next";
-import { subject } from "@casl/ability";
-import { faArrowRight, faPlus, faUpload } from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import { AsteriskIcon, KeyIcon, MessageSquareIcon } from "lucide-react";
-import { twMerge } from "tailwind-merge";
-
-import { createNotification } from "@app/components/notifications";
-import { ProjectPermissionCan } from "@app/components/permissions";
-// TODO:(akhilmhdh) convert all the util functions like this into a lib folder grouped by functionality
-import {
- parseCsvToMatrix,
- parseDotEnv,
- parseJson,
- parseYaml
-} from "@app/components/utilities/parseSecrets";
-import {
- Button,
- FormLabel,
- Lottie,
- Modal,
- ModalContent,
- Select,
- SelectItem
-} from "@app/components/v2";
-import { Badge } from "@app/components/v3";
-import { ProjectPermissionActions, ProjectPermissionSub } from "@app/context";
-import { usePopUp, useToggle } from "@app/hooks";
-import { PendingAction } from "@app/hooks/api/secretFolders/types";
-import { fetchProjectSecrets, mergePersonalSecrets } from "@app/hooks/api/secrets/queries";
-import { SecretV3RawSanitized } from "@app/hooks/api/secrets/types";
-
-import {
- BatchContext,
- PendingSecretCreate,
- PendingSecretUpdate,
- PopUpNames,
- useBatchModeActions,
- usePopUpAction
-} from "../../SecretMainPage.store";
-import { CopySecretsFromBoard } from "./CopySecretsFromBoard";
-import { PasteSecretEnvModal } from "./PasteSecretEnvModal";
-
-type TParsedEnv = Record<string, { value: string; comments: string[] }>;
-type TSecOverwriteOpt = {
- update: TParsedEnv;
- create: TParsedEnv;
- existingSecrets: SecretV3RawSanitized[];
-};
-
-type Props = {
- isSmaller: boolean;
- environments?: { name: string; slug: string }[];
- projectId: string;
- environment: string;
- secretPath: string;
-};
-
-type SecretMatrixMap = {
- key: number;
- value: number | null;
- comment: number | null;
-};
-
-const popupKeys = ["importSecEnv", "pasteSecEnv", "importMatrixMap"] as const;
-
-const MatrixImportModalTableRow = ({
- importSecretMatrixMap,
- setImportSecretMatrixMap,
- headers,
- mapKey
-}: {
- importSecretMatrixMap: SecretMatrixMap;
- setImportSecretMatrixMap: Dispatch<SetStateAction<SecretMatrixMap>>;
- headers: string[];
- mapKey: keyof SecretMatrixMap;
-}) => {
- return (
- <tr>
- <td className="w-full">
- <Select
- value={importSecretMatrixMap[mapKey]?.toString() || (null as unknown as string)}
- onValueChange={(v) =>
- setImportSecretMatrixMap((ism) => ({
- ...ism,
- [mapKey]: v ? parseInt(v, 10) : null
- }))
- }
- className="w-full border border-mineshaft-500"
- position="popper"
- placeholder="Select an option..."
- dropdownContainerClassName="max-w-none"
- >
- {mapKey !== "key" && <SelectItem value={null as unknown as string}>None</SelectItem>}
- {headers.map((header, col) => {
- return (
- <SelectItem value={col.toString()} key={`${mapKey}-${header}`}>
- {header}
- </SelectItem>
- );
- })}
- </Select>
- </td>
- <td className="pr-5 pl-5 whitespace-nowrap">
- <div className="flex items-center justify-center">
- <FontAwesomeIcon className="text-mineshaft-400" icon={faArrowRight} />
- </div>
- </td>
- <td className="whitespace-nowrap">
- <div className="flex h-full items-start justify-center">
- <Badge isFullWidth variant="neutral">
- {mapKey === "key" && (
- <>
- <KeyIcon />
- Secret Key
- </>
- )}
- {mapKey === "value" && (
- <>
- <AsteriskIcon />
- Secret Value
- </>
- )}
- {mapKey === "comment" && (
- <>
- <MessageSquareIcon />
- Comment
- </>
- )}
- </Badge>
- </div>
- </td>
- </tr>
- );
-};
-
-export const SecretDropzone = ({
- isSmaller,
- environments = [],
- projectId,
- environment,
- secretPath
-}: Props): JSX.Element => {
- const { t } = useTranslation();
- const [isDragActive, setDragActive] = useToggle();
- const [isLoading, setIsLoading] = useToggle();
-
- // Maps matrix columns to parts of a secret
- const [importSecretMatrixMap, setImportSecretMatrixMap] = useState<SecretMatrixMap>({
- key: 0,
- value: null,
- comment: null
- });
-
- const { popUp, handlePopUpToggle, handlePopUpOpen, handlePopUpClose } = usePopUp(popupKeys);
- const { openPopUp } = usePopUpAction();
- const { addPendingChange } = useBatchModeActions();
-
- // hide copy secrets from board due to import folders feature
- const shouldRenderCopySecrets = false;
-
- const handleDrag = (e: DragEvent) => {
- e.preventDefault();
- e.stopPropagation();
- if (e.type === "dragenter" || e.type === "dragover") {
- setDragActive.on();
- } else if (e.type === "dragleave") {
- setDragActive.off();
- }
- };
-
- const handleSaveSecrets = async (data: TSecOverwriteOpt) => {
- const { update, create, existingSecrets } = data;
-
- try {
- const context: BatchContext = {
- projectId,
- environment,
- secretPath
- };
-
- const existingSecretsMap = existingSecrets.reduce<Record<string, SecretV3RawSanitized>>(
- (prev, curr) => ({ ...prev, [curr.key]: curr }),
- {}
- );
-
- const totalCount = Object.keys(create || {}).length + Object.keys(update || {}).length;
-
- if (Object.keys(create || {}).length) {
- Object.entries(create).forEach(([secretKey, secData]) => {
- const createChange: PendingSecretCreate = {
- id: secretKey,
- timestamp: Date.now(),
- resourceType: "secret",
- type: PendingAction.Create,
- secretKey,
- secretValue: secData.value,
- secretComment: secData.comments.join("\n") || undefined,
- tags: [],
- secretMetadata: []
- };
- addPendingChange(createChange, context);
- });
- }
-
- if (Object.keys(update || {}).length) {
- Object.entries(update).forEach(([secretKey, secData]) => {
- const existingSecret = existingSecretsMap[secretKey];
-
- if (!existingSecret) {
- console.warn(`Existing secret not found for key: ${secretKey}`);
- return;
- }
-
- const updateChange: PendingSecretUpdate = {
- id: existingSecret.id,
- timestamp: Date.now(),
- resourceType: "secret",
- type: PendingAction.Update,
- secretKey,
- secretValue: secData.value,
- secretComment: secData.comments.join("\n") || undefined,
- existingSecret,
- originalValue: existingSecret.value || "",
- originalComment: existingSecret.comment || "",
- originalSkipMultilineEncoding: existingSecret.skipMultilineEncoding || false,
- originalTags: existingSecret.tags || [],
- originalSecretMetadata: existingSecret.secretMetadata || []
- };
- addPendingChange(updateChange, context);
- });
- }
-
- createNotification({
- type: "success",
- text: `Successfully imported ${totalCount} secret${totalCount > 1 ? "s" : ""}.`
- });
- } catch (err) {
- console.log(err);
- createNotification({
- type: "error",
- text: "Failed to import secrets"
- });
- }
- };
-
- const handleParsedEnv = async (env: TParsedEnv) => {
- const envSecretKeys = Object.keys(env);
-
- if (!envSecretKeys.length) {
- createNotification({
- type: "error",
- text: "Failed to find secrets"
- });
- return;
- }
-
- try {
- setIsLoading.on();
- const { secrets: rawExistingSecrets } = await fetchProjectSecrets({
- projectId,
- environment,
- secretPath,
- viewSecretValue: true
- });
-
- const allExistingSecrets = mergePersonalSecrets(rawExistingSecrets);
-
- const existingSecretsMap = allExistingSecrets.reduce<Record<string, SecretV3RawSanitized>>(
- (prev, curr) => ({ ...prev, [curr.key]: curr }),
- {}
- );
-
- const updateSecrets: TParsedEnv = {};
- const createSecrets: TParsedEnv = {};
- const relevantExistingSecrets: SecretV3RawSanitized[] = [];
-
- Object.entries(env).forEach(([secretKey, secretData]) => {
- const existingSecret = existingSecretsMap[secretKey];
- if (existingSecret) {
- updateSecrets[secretKey] = secretData;
- relevantExistingSecrets.push(existingSecret);
- } else {
- createSecrets[secretKey] = secretData;
- }
- });
-
- await handleSaveSecrets({
- update: updateSecrets,
- create: createSecrets,
- existingSecrets: relevantExistingSecrets
- });
- } catch (e) {
- console.error(e);
- createNotification({
- text: "Failed to check for secret conflicts",
- type: "error"
- });
- } finally {
- setIsLoading.off();
- }
- };
-
- const parseFile = (file?: File) => {
- const reader = new FileReader();
- if (!file) {
- createNotification({
- text: "You can't inject files from VS Code. Click 'Reveal in finder', and drag your file directly from the directory where it's located.",
- type: "error"
- });
- return;
- }
-
- setIsLoading.on();
- reader.onload = (event) => {
- if (!event?.target?.result) {
- createNotification({
- type: "error",
- text: "Invalid file contents."
- });
- setIsLoading.off();
- return;
- }
-
- let env: TParsedEnv;
-
- const src = event.target.result as ArrayBuffer;
-
- switch (file.type) {
- case "application/json":
- env = parseJson(src);
- break;
- case "text/yaml":
- case "application/x-yaml":
- case "application/yaml":
- env = parseYaml(src);
- break;
- case "text/csv": {
- const { matrix: fullMatrix } = parseCsvToMatrix(src);
- if (!fullMatrix.length) {
- createNotification({
- type: "error",
- text: "Failed to find secrets in CSV file. File might be empty."
- });
- setIsLoading.off();
- return;
- }
- const headers = fullMatrix[0];
- const matrix = fullMatrix.slice(1);
- handlePopUpOpen("importMatrixMap", { headers, matrix });
- setIsLoading.off();
- return;
- }
- default:
- env = parseDotEnv(src);
- break;
- }
- setIsLoading.off();
- handleParsedEnv(env);
- };
-
- // If something is wrong show an error
- try {
- reader.readAsText(file);
- } catch (error) {
- console.log(error);
- }
- };
-
- const finishMappedMatrixImport = (matrix: string[][]) => {
- const env: TParsedEnv = {};
- matrix.forEach((row) => {
- const key = row[importSecretMatrixMap.key];
- if (key) {
- env[key] = {
- value: importSecretMatrixMap.value ? row[importSecretMatrixMap.value] : "",
- comments: importSecretMatrixMap.comment ? [row[importSecretMatrixMap.comment]] : []
- };
- }
- });
- handlePopUpClose("importMatrixMap");
- setImportSecretMatrixMap({ key: 0, value: null, comment: null });
- handleParsedEnv(env);
- };
-
- const handleDrop = (e: DragEvent) => {
- e.preventDefault();
- e.stopPropagation();
- if (!e.dataTransfer) {
- return;
- }
-
- e.dataTransfer.dropEffect = "copy";
- setDragActive.off();
- parseFile(e.dataTransfer.files[0]);
- };
-
- const handleFileUpload = (e: ChangeEvent<HTMLInputElement>) => {
- e.preventDefault();
- parseFile(e.target?.files?.[0]);
- };
-
- return (
- <div>
- <div
- onDragEnter={handleDrag}
- onDragLeave={handleDrag}
- onDragOver={handleDrag}
- onDrop={handleDrop}
- className={twMerge(
- "relative mx-0.5 mt-4 mb-4 flex cursor-pointer items-center justify-center rounded-md bg-mineshaft-900 px-2 py-4 text-sm text-mineshaft-200 opacity-60 outline-2 outline-chicago-600 duration-200 outline-dashed hover:opacity-100",
- isDragActive && "opacity-100",
- !isSmaller && "mx-auto mt-40 w-full max-w-3xl flex-col space-y-4 py-20",
- isLoading && "bg-bunker-800"
- )}
- >
- {isLoading ? (
- <div className="mb-16 flex items-center justify-center pt-16">
- <Lottie isAutoPlay icon="infisical_loading" className="h-32 w-32" />
- </div>
- ) : (
- <div className="flex flex-col items-center justify-center space-y-2">
- <div>
- <FontAwesomeIcon icon={faUpload} size={isSmaller ? "2x" : "5x"} />
- </div>
- <div>
- <p className="">{t(isSmaller ? "common.drop-zone-keys" : "common.drop-zone")}</p>
- </div>
- <ProjectPermissionCan
- I={ProjectPermissionActions.Create}
- a={subject(ProjectPermissionSub.Secrets, {
- environment,
- secretPath,
- secretName: "*",
- secretTags: ["*"]
- })}
- >
- {(isAllowed) => (
- <input
- id="fileSelect"
- disabled={!isAllowed}
- type="file"
- className="absolute h-full w-full cursor-pointer opacity-0"
- accept=".txt,.env,.yml,.yaml,.json,.csv"
- onChange={handleFileUpload}
- />
- )}
- </ProjectPermissionCan>
- <div
- className={twMerge(
- "flex w-full flex-row items-center justify-center py-4",
- isSmaller && "py-1"
- )}
- >
- <div className="w-1/5 border-t border-mineshaft-700" />
- <p className="mx-4 text-xs text-mineshaft-400">OR</p>
- <div className="w-1/5 border-t border-mineshaft-700" />
- </div>
- <div className="flex flex-col items-center justify-center gap-4 lg:flex-row">
- <PasteSecretEnvModal
- isOpen={popUp.pasteSecEnv.isOpen}
- onToggle={(isOpen) => handlePopUpToggle("pasteSecEnv", isOpen)}
- onParsedEnv={handleParsedEnv}
- environment={environment}
- secretPath={secretPath}
- isSmaller={isSmaller}
- />
- {shouldRenderCopySecrets && (
- <CopySecretsFromBoard
- isOpen={popUp.importSecEnv.isOpen}
- onToggle={(isOpen) => handlePopUpToggle("importSecEnv", isOpen)}
- onParsedEnv={handleParsedEnv}
- environment={environment}
- environments={environments}
- projectId={projectId}
- secretPath={secretPath}
- isSmaller={isSmaller}
- />
- )}
- {!isSmaller && (
- <ProjectPermissionCan
- I={ProjectPermissionActions.Create}
- a={subject(ProjectPermissionSub.Secrets, {
- environment,
- secretPath,
- secretName: "*",
- secretTags: ["*"]
- })}
- >
- {(isAllowed) => (
- <Button
- leftIcon={<FontAwesomeIcon icon={faPlus} />}
- onClick={() => openPopUp(PopUpNames.CreateSecretForm)}
- variant="star"
- isDisabled={!isAllowed}
- >
- Add a New Secret
- </Button>
- )}
- </ProjectPermissionCan>
- )}
- </div>
- </div>
- )}
- </div>
-
- {/* Matrix Import Modal */}
- <Modal
- isOpen={popUp?.importMatrixMap?.isOpen}
- onOpenChange={(open) => handlePopUpToggle("importMatrixMap", open)}
- >
- <ModalContent
- title="Import Column Mapping"
- subTitle="Map your data columns to different parts of the secret"
- >
- <div className="w-full overflow-hidden">
- <table className="w-full table-auto">
- <thead>
- <tr className="text-left">
- <th>
- <FormLabel tooltipClassName="max-w-sm" label="Import Column" />
- </th>
- <th />
- <th className="whitespace-nowrap">
- <FormLabel label="Resulting Import" />
- </th>
- </tr>
- </thead>
- <tbody>
- {/* Key */}
- <MatrixImportModalTableRow
- importSecretMatrixMap={importSecretMatrixMap}
- setImportSecretMatrixMap={setImportSecretMatrixMap}
- headers={popUp?.importMatrixMap.data?.headers || []}
- mapKey="key"
- />
-
- {/* Value */}
- <MatrixImportModalTableRow
- importSecretMatrixMap={importSecretMatrixMap}
- setImportSecretMatrixMap={setImportSecretMatrixMap}
- headers={popUp?.importMatrixMap.data?.headers || []}
- mapKey="value"
- />
-
- {/* Comment */}
- <MatrixImportModalTableRow
- importSecretMatrixMap={importSecretMatrixMap}
- setImportSecretMatrixMap={setImportSecretMatrixMap}
- headers={popUp?.importMatrixMap.data?.headers || []}
- mapKey="comment"
- />
- </tbody>
- </table>
- </div>
-
- <div className="flex w-full flex-row-reverse justify-between gap-4 pt-4">
- <Button
- onClick={() =>
- popUp.importMatrixMap.data?.matrix
- ? finishMappedMatrixImport(popUp.importMatrixMap.data?.matrix)
- : createNotification({
- text: "Invalid secret matrix.",
- type: "error"
- })
- }
- isFullWidth
- variant="outline_bg"
- >
- Import Secrets
- </Button>
- </div>
- </ModalContent>
- </Modal>
- </div>
- );
-};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretDropzone/index.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretDropzone/index.tsx
deleted file mode 100644
index e0fb737b6d..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretDropzone/index.tsx
+++ /dev/null
@@ -1 +0,0 @@
-export { SecretDropzone } from "./SecretDropzone";
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretImportListView/SecretImportItem.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretImportListView/SecretImportItem.tsx
deleted file mode 100644
index 52ba47a69c..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretImportListView/SecretImportItem.tsx
+++ /dev/null
@@ -1,369 +0,0 @@
-import { useEffect } from "react";
-import { subject } from "@casl/ability";
-import { useSortable } from "@dnd-kit/sortable";
-import {
- faCalendarCheck,
- faFileImport,
- faFolder,
- faInfoCircle,
- faKey,
- faRotate,
- faSearch,
- faTrash,
- faUpDown,
- faWarning,
- faXmark
-} from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import { format } from "date-fns";
-import { twMerge } from "tailwind-merge";
-
-import { createNotification } from "@app/components/notifications";
-import { ProjectPermissionCan } from "@app/components/permissions";
-import { EmptyState, IconButton, TableContainer, Tooltip } from "@app/components/v2";
-import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "@app/components/v3";
-import { ProjectPermissionActions, ProjectPermissionSub, useProject } from "@app/context";
-import { useToggle } from "@app/hooks";
-import { useResyncSecretReplication } from "@app/hooks/api";
-import { TSecretImport } from "@app/hooks/api/types";
-
-import { SecretImportSecretRow } from "./SecretImportSecretRow";
-
-type Props = {
- onDelete: () => void;
- environment: string;
- secretPath?: string;
- secretImport?: TSecretImport;
- isReplicationExpand?: boolean;
- importedSecrets: {
- key: string;
- value?: string;
- overridden: { env: string; secretPath: string };
- environment: string;
- secretPath?: string;
- isEmpty?: boolean;
- }[];
- searchTerm: string;
- onExpandReplicateSecrets: (id: string) => void;
-};
-
-// to show the environment and folder icon
-export const EnvFolderIcon = ({
- env,
- secretPath
-}: // isReplication
-{
- env: string;
- secretPath: string;
- // isReplication?: boolean;
-}) => (
- <div className="inline-flex items-center space-x-2">
- <div style={{ minWidth: "96px" }}>{env || "-"}</div>
- {secretPath && (
- <div className="inline-flex items-center space-x-2 border-l border-mineshaft-600 pl-2">
- {/* {isReplication && <Tag size="xs">Replication Mode</Tag>} */}
- <FontAwesomeIcon icon={faFolder} className="text-md text-green-700" />
- <span>{secretPath}</span>
- </div>
- )}
- </div>
-);
-
-export const SecretImportItem = ({
- onDelete,
- isReplicationExpand,
- importedSecrets = [],
- searchTerm = "",
- secretPath = "/",
- environment,
- secretImport,
- onExpandReplicateSecrets: onExpandReplicate
-}: Props) => {
- const {
- isReserved,
- id,
- isReplication,
- isReplicationSuccess,
- isAccessRevoked,
- replicationStatus,
- lastReplicated,
- importEnv
- } = secretImport as TSecretImport;
- const { currentProject } = useProject();
- const [isExpanded, setIsExpanded] = useToggle();
- const { attributes, listeners, transform, transition, setNodeRef, isDragging } = useSortable({
- id
- });
- const resyncSecretReplication = useResyncSecretReplication();
- useEffect(() => {
- const filteredSecrets = importedSecrets.filter((secret) =>
- secret.key.toUpperCase().includes(searchTerm.toUpperCase())
- );
-
- if (filteredSecrets.length > 0 && searchTerm) {
- setIsExpanded.on();
- } else {
- setIsExpanded.off();
- }
- }, [searchTerm]);
-
- useEffect(() => {
- if (isDragging) {
- setIsExpanded.off();
- }
- }, [isDragging]);
-
- const style = {
- transform: transform ? `translateY(${transform.y ? Math.round(transform.y) : 0}px)` : "",
- transition
- };
-
- const handleResyncSecretReplication = async () => {
- if (resyncSecretReplication.isPending) return;
- await resyncSecretReplication.mutateAsync({
- id,
- environment,
- path: secretPath,
- projectId: currentProject?.id || ""
- });
- createNotification({
- text: "Please refresh the dashboard to view changes",
- type: "success"
- });
- };
-
- const handleRowClick = () => {
- if (isReplication) {
- onExpandReplicate(id);
- } else {
- setIsExpanded.toggle();
- }
- };
-
- const filteredImportedSecrets = importedSecrets.filter((secret) =>
- secret.key.toUpperCase().includes(searchTerm.toUpperCase())
- );
-
- return (
- <>
- <div
- className={twMerge(
- "group flex cursor-pointer border-b border-mineshaft-600 hover:bg-mineshaft-700",
- isReserved && "hidden"
- )}
- role="button"
- ref={setNodeRef}
- tabIndex={0}
- style={style}
- onClick={handleRowClick}
- onKeyDown={(e) => {
- if (e.key === "Enter") {
- handleRowClick();
- }
- }}
- >
- <div className="flex w-11 items-center py-2 pl-5 text-green-700">
- <FontAwesomeIcon icon={faFileImport} />
- </div>
- <div className="flex grow items-center py-2 pr-2 pl-4">
- <EnvFolderIcon
- env={importEnv.slug || ""}
- secretPath={secretImport?.importPath || ""}
- // isReplication={isReplication}
- />
- {secretImport?.sourceProjectName &&
- importEnv.projectId &&
- importEnv.projectId !== currentProject?.id && (
- <span className="ml-2 rounded border border-yellow-700/40 bg-yellow-900/20 px-1.5 py-0.5 text-xs text-yellow-400">
- {secretImport.sourceProjectName}
- </span>
- )}
- </div>
- <div className="flex items-center space-x-4 py-2 pr-4">
- {isAccessRevoked && (
- <span className="rounded border border-red-700/40 bg-red-900/20 px-1.5 py-0.5 text-xs text-red-400">
- Secret share revoked
- </span>
- )}
- {lastReplicated && (
- <Tooltip
- position="left"
- className="max-w-md break-words whitespace-normal"
- content={
- <div className="flex max-h-40 flex-col overflow-auto">
- <div className="flex self-start">
- <FontAwesomeIcon icon={faCalendarCheck} className="pt-0.5 pr-2 text-sm" />
- <div className="text-sm">Last Replication</div>
- </div>
- <div className="pl-5 text-left text-xs">
- {lastReplicated
- ? format(new Date(lastReplicated), "yyyy-MM-dd, hh:mm aaa")
- : "-"}
- </div>
- {!isReplicationSuccess && (
- <>
- <div className="mt-2 flex self-start">
- <FontAwesomeIcon icon={faXmark} className="pt-1 pr-2 text-sm" />
- <div className="text-sm">Fail reason</div>
- </div>
- <div className="pl-5 text-left text-xs">{replicationStatus}</div>
- </>
- )}
- </div>
- }
- >
- <div
- className={twMerge(
- "opacity-0 group-hover:opacity-100",
- !isReplicationSuccess && "text-red-600"
- )}
- >
- <FontAwesomeIcon icon={isReplicationSuccess ? faInfoCircle : faWarning} />
- </div>
- </Tooltip>
- )}
- {isReplication && (
- <ProjectPermissionCan
- I={ProjectPermissionActions.Edit}
- a={subject(ProjectPermissionSub.SecretImports, { environment, secretPath })}
- renderTooltip
- allowedLabel="Resync replicated secrets"
- >
- {(isAllowed) => (
- <IconButton
- size="md"
- colorSchema="primary"
- variant="plain"
- ariaLabel="expand"
- className={twMerge(
- "p-0 opacity-0 group-hover:opacity-100",
- resyncSecretReplication.isPending && "animate-spin opacity-100"
- )}
- isDisabled={!isAllowed}
- onClick={handleResyncSecretReplication}
- >
- <FontAwesomeIcon icon={faRotate} />
- </IconButton>
- )}
- </ProjectPermissionCan>
- )}
- </div>
- <div className="flex w-16 items-center justify-between border-l border-mineshaft-600 py-3.5 pr-3 pl-4">
- <ProjectPermissionCan
- I={ProjectPermissionActions.Edit}
- a={subject(ProjectPermissionSub.SecretImports, {
- environment,
- secretPath: secretPath || "/"
- })}
- renderTooltip
- allowedLabel="Change order"
- >
- {(isAllowed) => (
- <IconButton
- size="md"
- colorSchema="primary"
- variant="plain"
- ariaLabel="expand"
- className="p-0 opacity-0 group-hover:opacity-100"
- {...attributes}
- {...listeners}
- isDisabled={!isAllowed}
- >
- <FontAwesomeIcon icon={faUpDown} />
- </IconButton>
- )}
- </ProjectPermissionCan>
- <ProjectPermissionCan
- I={ProjectPermissionActions.Delete}
- a={subject(ProjectPermissionSub.SecretImports, { environment, secretPath })}
- renderTooltip
- allowedLabel="Delete"
- >
- {(isAllowed) => (
- <IconButton
- size="md"
- variant="plain"
- colorSchema="danger"
- ariaLabel="delete"
- className="p-0 opacity-0 group-hover:opacity-100"
- onClick={(evt) => {
- evt.stopPropagation();
- onDelete();
- }}
- isDisabled={!isAllowed}
- >
- <FontAwesomeIcon icon={faTrash} />
- </IconButton>
- )}
- </ProjectPermissionCan>
- </div>
- </div>
- {!isReplication && (isReplicationExpand || isExpanded) && !isDragging && (
- <td
- colSpan={3}
- className={`bg-bunker-800 ${isExpanded && "border-b-2 border-mineshaft-500"}`}
- >
- {isAccessRevoked ? (
- <div className="p-4">
- <Empty className="gap-3 border-danger/30 bg-danger/5 p-4 text-danger md:p-4">
- <EmptyHeader className="gap-1.5">
- <div className="flex items-center gap-2">
- <FontAwesomeIcon icon={faWarning} className="size-4 shrink-0" />
- <EmptyTitle>
- {secretImport?.sourceProjectName
- ? `${secretImport.sourceProjectName} revoked access to these secrets.`
- : "Access to these secrets has been revoked."}
- </EmptyTitle>
- </div>
- <EmptyDescription className="text-danger/70">
- Import can no longer be resolved. Re-request access from the source project or
- remove this import.
- </EmptyDescription>
- </EmptyHeader>
- </Empty>
- </div>
- ) : (
- <div className="rounded-md bg-bunker-700 p-1">
- <TableContainer>
- <table className="secret-table">
- <thead>
- <tr>
- <td style={{ padding: "0.25rem 1rem" }}>Key</td>
- <td style={{ padding: "0.25rem 1rem" }}>Value</td>
- </tr>
- </thead>
- <tbody>
- {importedSecrets?.length === 0 && (
- <tr>
- <td colSpan={3}>
- <EmptyState title="No secrets found" icon={faKey} />
- </td>
- </tr>
- )}
- {filteredImportedSecrets.length === 0 && importedSecrets?.length !== 0 && (
- <tr>
- <td colSpan={3}>
- <EmptyState title="No secrets match search" icon={faSearch} />
- </td>
- </tr>
- )}
- {filteredImportedSecrets.map((secret, index) => (
- <SecretImportSecretRow
- secret={
- importEnv.projectId !== currentProject?.id
- ? { ...secret, environment, secretPath }
- : secret
- }
- key={`${id}-${secret.key}-${index + 1}`}
- />
- ))}
- </tbody>
- </table>
- </TableContainer>
- </div>
- )}
- </td>
- )}
- </>
- );
-};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretImportListView/SecretImportListView.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretImportListView/SecretImportListView.tsx
deleted file mode 100644
index 794fce88f5..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretImportListView/SecretImportListView.tsx
+++ /dev/null
@@ -1,247 +0,0 @@
-import { useEffect, useState } from "react";
-import {
- closestCenter,
- DndContext,
- DragEndEvent,
- KeyboardSensor,
- MouseSensor,
- TouchSensor,
- useSensor,
- useSensors
-} from "@dnd-kit/core";
-import { restrictToVerticalAxis } from "@dnd-kit/modifiers";
-import { arrayMove, SortableContext, verticalListSortingStrategy } from "@dnd-kit/sortable";
-
-import { createNotification } from "@app/components/notifications";
-import { DeleteActionModal } from "@app/components/v2";
-import { usePopUp } from "@app/hooks";
-import { useDeleteSecretImport, useUpdateSecretImport } from "@app/hooks/api";
-import { ReservedFolders } from "@app/hooks/api/secretFolders/types";
-import { TSecretImport } from "@app/hooks/api/secretImports/types";
-import { ProjectEnv, SecretV3RawSanitized } from "@app/hooks/api/types";
-import { formatReservedPaths } from "@app/lib/fn/string";
-
-import { SecretImportItem } from "./SecretImportItem";
-
-const SECRET_IN_DASHBOARD = "Present In Dashboard";
-
-type TImportedSecrets = Array<{
- environmentInfo: ProjectEnv;
- secretPath: string;
- folderId: string;
- secrets: SecretV3RawSanitized[];
-}>;
-
-export const computeImportedSecretRows = (
- secretImport: TSecretImport,
- importSecrets: TImportedSecrets = [],
- secrets: SecretV3RawSanitized[] = [],
- replicatedFolder?: TSecretImport
-) => {
- const importedSecEnv = replicatedFolder?.importEnv.slug ?? secretImport.importEnv.slug;
- const importedSecPath = replicatedFolder?.importPath ?? secretImport.importPath;
- const overrideEnv = secretImport.isReserved ? secretImport.importEnv.slug : undefined;
- const overridePath = secretImport.isReserved ? secretImport.importPath : undefined;
- const importedSecIndex = importSecrets.findIndex(
- ({ secretPath, environmentInfo }) =>
- secretPath === importedSecPath && importedSecEnv === environmentInfo.slug
- );
- if (importedSecIndex === -1) return [];
-
- const importedSec = importSecrets[importedSecIndex];
- const overridenSec: Record<string, { env: string; secretPath: string }> = {};
-
- for (let i = importedSecIndex + 1; i < importSecrets.length; i += 1) {
- importSecrets[i].secrets.forEach((el) => {
- overridenSec[el.key] = {
- env: importSecrets[i].environmentInfo.name,
- secretPath: formatReservedPaths(importSecrets[i].secretPath)
- };
- });
- }
-
- secrets.forEach((el) => {
- overridenSec[el.key] = { env: SECRET_IN_DASHBOARD, secretPath: "" };
- });
-
- const importedEntry: Record<string, boolean> = {};
- const importedSecretEntries: {
- key: string;
- value?: string;
- environment: string;
- secretPath?: string;
- overridden: {
- env: string;
- secretPath: string;
- };
- isEmpty?: boolean;
- }[] = [];
-
- importedSec.secrets.forEach(({ key, value, isEmpty }) => {
- if (!importedEntry[key]) {
- importedSecretEntries.push({
- key,
- value,
- environment: overrideEnv ?? importedSec.environmentInfo.slug,
- secretPath: overridePath ?? importedSec.secretPath,
- overridden: overridenSec?.[key],
- isEmpty
- });
- importedEntry[key] = true;
- }
- });
-
- return importedSecretEntries;
-};
-
-type Props = {
- environment: string;
- projectId: string;
- secretPath?: string;
- secretImports?: TSecretImport[];
- isFetching?: boolean;
- // secrets?: SecretV3RawSanitized[];
- importedSecrets?: TImportedSecrets;
- searchTerm: string;
-};
-
-export const SecretImportListView = ({
- secretImports,
- environment,
- projectId,
- secretPath,
- importedSecrets,
- // secrets = [],
- isFetching,
- searchTerm
-}: Props) => {
- const { popUp, handlePopUpOpen, handlePopUpClose, handlePopUpToggle } = usePopUp([
- "deleteSecretImport"
- ] as const);
-
- const [replicationSecrets, setReplicationSecrets] = useState<Record<string, boolean>>({});
-
- const sensors = useSensors(
- useSensor(MouseSensor, {}),
- useSensor(TouchSensor, {}),
- useSensor(KeyboardSensor, {})
- );
-
- const [items, setItems] = useState(secretImports ?? []);
-
- const getImportReplicatedFolder = (importPath: string) => {
- if (!importPath.includes("/__reserve_replication_")) return undefined;
- const cleanImportPath = importPath.split("/__reserve_replication_")[1];
- const replicatedFolder = items?.find(({ id }) => id === cleanImportPath);
- return replicatedFolder;
- };
-
- useEffect(() => {
- if (!isFetching) {
- setItems(secretImports ?? []);
- }
- }, [isFetching, secretImports]);
-
- const { mutateAsync: deleteSecretImport } = useDeleteSecretImport();
- const { mutate: updateSecretImport } = useUpdateSecretImport();
-
- const handleSecretImportDelete = async () => {
- const { id: secretImportId } = popUp.deleteSecretImport?.data as { id: string };
- await deleteSecretImport({
- projectId,
- environment,
- path: secretPath,
- id: secretImportId
- });
- handlePopUpClose("deleteSecretImport");
- createNotification({
- type: "success",
- text: "Successfully removed secret link"
- });
- };
-
- const handleSecretImportReorder = ({ over, active }: DragEndEvent) => {
- if (active.id !== over?.id) {
- const oldIndex = items.findIndex(({ id }) => id === active.id);
- const newIndex = items.findIndex(({ id }) => id === over?.id);
- const newImportOrder = arrayMove(items, oldIndex, newIndex);
- setItems(newImportOrder);
- updateSecretImport({
- projectId,
- environment,
- path: secretPath,
- id: active.id as string,
- import: {
- position: newIndex + 1
- }
- });
- }
- };
-
- const handleOpenReplicationSecrets = (replicationImportId: string) => {
- const reservedImport = secretImports?.find(
- ({ isReserved, importPath, importEnv }) =>
- importEnv.slug === environment &&
- isReserved &&
- importPath ===
- `${secretPath === "/" ? "" : secretPath}/${
- ReservedFolders.SecretReplication
- }${replicationImportId}`
- );
- if (reservedImport) {
- setReplicationSecrets((state) => ({
- ...state,
- [reservedImport.id]: !state?.[reservedImport.id]
- }));
- }
- };
-
- return (
- <>
- <DndContext
- onDragEnd={handleSecretImportReorder}
- sensors={sensors}
- collisionDetection={closestCenter}
- modifiers={[restrictToVerticalAxis]}
- >
- <SortableContext items={items} strategy={verticalListSortingStrategy}>
- {items?.map((item) => {
- // TODO(akhilmhdh): change this and pass this whole object instead of one by one
- const replicatedFolder = item.isReserved
- ? getImportReplicatedFolder(item.importPath)
- : undefined;
- return (
- <SecretImportItem
- searchTerm={searchTerm}
- key={`imported-env-${item.id}`}
- isReplicationExpand={replicationSecrets?.[item.id]}
- onExpandReplicateSecrets={handleOpenReplicationSecrets}
- secretImport={item}
- importedSecrets={computeImportedSecretRows(
- item,
- importedSecrets,
- [],
- // secrets scott - now that secrets are paginated we are not showing if they are overridden (yet?)
- replicatedFolder
- )}
- secretPath={secretPath}
- environment={environment}
- onDelete={() => handlePopUpOpen("deleteSecretImport", item)}
- />
- );
- })}
- </SortableContext>
- </DndContext>
- <DeleteActionModal
- isOpen={popUp.deleteSecretImport.isOpen}
- deleteKey="unlink"
- title="Do you want to remove this secret import?"
- subTitle={`This will unlink secrets from environment ${
- (popUp.deleteSecretImport?.data as TSecretImport)?.importEnv
- } of path ${(popUp.deleteSecretImport?.data as TSecretImport)?.importPath}?`}
- onChange={(isOpen) => handlePopUpToggle("deleteSecretImport", isOpen)}
- onDeleteApproved={handleSecretImportDelete}
- />
- </>
- );
-};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretImportListView/SecretImportSecretRow.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretImportListView/SecretImportSecretRow.tsx
deleted file mode 100644
index fd8c8a4403..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretImportListView/SecretImportSecretRow.tsx
+++ /dev/null
@@ -1,68 +0,0 @@
-import { SecretInput } from "@app/components/v2";
-import { useProject } from "@app/context";
-import { useToggle } from "@app/hooks";
-import { useGetSecretValue } from "@app/hooks/api/dashboard/queries";
-import { HIDDEN_SECRET_VALUE } from "@app/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretItem";
-
-type SecretImportSecretRowProps = {
- secret: {
- key: string;
- value?: string;
- environment: string;
- secretPath?: string;
- isEmpty?: boolean;
- overridden: { env: string; secretPath: string };
- };
-};
-
-export const SecretImportSecretRow = ({
- secret: { key, environment, secretPath = "/", isEmpty }
-}: SecretImportSecretRowProps) => {
- const [isFieldFocused, setIsFieldFocused] = useToggle();
-
- const { currentProject } = useProject();
-
- const canFetchSecretValue = !isEmpty;
-
- const {
- data: secretValue,
- isPending: isPendingSecretValue,
- isError: isErrorFetchingSecretValue
- } = useGetSecretValue(
- {
- environment,
- secretPath,
- secretKey: key,
- projectId: currentProject.id
- },
- {
- enabled: isFieldFocused && canFetchSecretValue
- }
- );
-
- const isLoadingSecretValue = canFetchSecretValue && isPendingSecretValue;
-
- const getValue = () => {
- if (isLoadingSecretValue) return HIDDEN_SECRET_VALUE;
-
- if (isErrorFetchingSecretValue) return "Error loading secret value";
-
- return secretValue?.value || "";
- };
-
- return (
- <tr>
- <td className="h-10 w-1/2" style={{ padding: "0.25rem 1rem" }}>
- {key}
- </td>
- <td className="h-10 w-1/2" style={{ padding: "0.25rem 1rem" }}>
- <SecretInput
- value={getValue()}
- onFocus={() => setIsFieldFocused.on()}
- onBlur={() => setIsFieldFocused.off()}
- isReadOnly
- />
- </td>
- </tr>
- );
-};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretImportListView/index.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretImportListView/index.tsx
deleted file mode 100644
index c7d90c94da..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretImportListView/index.tsx
+++ /dev/null
@@ -1 +0,0 @@
-export { SecretImportListView } from "./SecretImportListView";
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretDetailSidebar.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretDetailSidebar.tsx
deleted file mode 100644
index b62b630dd7..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretDetailSidebar.tsx
+++ /dev/null
@@ -1,977 +0,0 @@
-import { useEffect } from "react";
-import { Controller, useFieldArray, useForm } from "react-hook-form";
-import { subject } from "@casl/ability";
-import { faCircleQuestion } from "@fortawesome/free-regular-svg-icons";
-import {
- faCheckCircle,
- faCopy,
- faPlus,
- faProjectDiagram,
- faSearch,
- faShare,
- faTag,
- faTrash,
- faTriangleExclamation
-} from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import { zodResolver } from "@hookform/resolvers/zod";
-import { useQueryClient } from "@tanstack/react-query";
-import { Link } from "@tanstack/react-router";
-
-import { UpgradePlanModal } from "@app/components/license/UpgradePlanModal";
-import { createNotification } from "@app/components/notifications";
-import { ProjectPermissionCan } from "@app/components/permissions";
-import { SecretReferenceTree } from "@app/components/secrets/SecretReferenceDetails";
-import {
- Button,
- Drawer,
- DrawerContent,
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuLabel,
- DropdownMenuTrigger,
- FormControl,
- FormLabel,
- IconButton,
- Input,
- Modal,
- ModalContent,
- Switch,
- Tag,
- TextArea,
- Tooltip
-} from "@app/components/v2";
-import { InfisicalSecretInput } from "@app/components/v2/InfisicalSecretInput";
-import {
- ProjectPermissionActions,
- ProjectPermissionSub,
- useOrganization,
- useProject,
- useProjectPermission,
- useSubscription
-} from "@app/context";
-import { ProjectPermissionSecretActions } from "@app/context/ProjectPermissionContext/types";
-import { getProjectBaseURL } from "@app/helpers/project";
-import { usePopUp, useToggle } from "@app/hooks";
-import { useGetSecretVersion, useRedactSecretValue } from "@app/hooks/api";
-import {
- dashboardKeys,
- fetchSecretValue,
- useGetSecretValue
-} from "@app/hooks/api/dashboard/queries";
-import { useGetSecretAccessList } from "@app/hooks/api/secrets/queries";
-import { SecretV3RawSanitized, WsTag } from "@app/hooks/api/types";
-import { hasSecretReadValueOrDescribePermission } from "@app/lib/fn/permission";
-import { camelCaseToSpaces } from "@app/lib/fn/string";
-
-import { HIDDEN_SECRET_VALUE } from "./SecretItem";
-import { formSchema, SecretActionType, TFormSchema } from "./SecretListView.utils";
-import { SecretVersionItem } from "./SecretVersionItem";
-
-type Props = {
- isOpen?: boolean;
- environment: string;
- secretPath: string;
- onToggle: (isOpen: boolean) => void;
- onClose: () => void;
- secret: SecretV3RawSanitized & { originalKey?: string };
- onDeleteSecret: () => void;
- onSaveSecret: (
- orgSec: SecretV3RawSanitized,
- modSec: Omit<SecretV3RawSanitized, "tags"> & { tags?: { id: string }[] },
- cb?: () => void
- ) => Promise<void>;
- tags: WsTag[];
- onCreateTag: () => void;
- handleSecretShare: (value: string) => void;
-};
-
-export const SecretDetailSidebar = ({
- isOpen,
- onToggle,
- onClose,
- secret: originalSecret,
- onDeleteSecret,
- onSaveSecret,
- tags,
- onCreateTag,
- environment,
- secretPath,
- handleSecretShare
-}: Props) => {
- const { currentOrg } = useOrganization();
- const { currentProject } = useProject();
- const [isFieldFocused, setIsFieldFocused] = useToggle();
- const queryClient = useQueryClient();
-
- const { mutateAsync: redactSecretValue } = useRedactSecretValue();
-
- // A personal override is always readable by its owner, so its fetch must not depend on the shared
- // value's `secretValueHidden` (true when the user lacks read access to the shared secret).
- const canFetchSecretValue =
- Boolean(originalSecret) &&
- (originalSecret?.idOverride
- ? !originalSecret.isOverrideEmpty
- : !originalSecret.secretValueHidden && !originalSecret.isEmpty);
-
- const fetchSecretValueParams = {
- environment,
- secretPath,
- secretKey: originalSecret?.originalKey || originalSecret?.key,
- projectId: currentProject.id,
- isOverride: Boolean(originalSecret?.idOverride)
- };
-
- const {
- data: secretValueData,
- isPending: isPendingSecretValue,
- isError: isErrorFetchingSecretValue
- } = useGetSecretValue(fetchSecretValueParams, {
- enabled: canFetchSecretValue && isFieldFocused
- });
-
- const isLoadingSecretValue = canFetchSecretValue && isPendingSecretValue;
- const hasFetchedSecretValue = !canFetchSecretValue || Boolean(secretValueData);
-
- const secret = {
- ...originalSecret,
- value: originalSecret?.value ?? secretValueData?.value,
- valueOverride: originalSecret?.valueOverride ?? secretValueData?.valueOverride
- };
-
- const { permission } = useProjectPermission();
-
- const canEditSecretValue = permission.can(
- ProjectPermissionSecretActions.Edit,
- subject(ProjectPermissionSub.Secrets, {
- environment,
- secretPath,
- secretName: secret.key,
- secretTags: ["*"]
- })
- );
-
- const getDefaultValue = () => {
- if (isLoadingSecretValue) return HIDDEN_SECRET_VALUE;
-
- if (secret.secretValueHidden) {
- return canEditSecretValue ? HIDDEN_SECRET_VALUE : "";
- }
-
- if (isErrorFetchingSecretValue) return "Error loading secret value...";
-
- return secret.value || "";
- };
-
- const getOverrideDefaultValue = () => {
- if (isLoadingSecretValue) return HIDDEN_SECRET_VALUE;
-
- // The personal override is always readable by its owner; it is not gated on the shared value's
- // `secretValueHidden`.
- if (isErrorFetchingSecretValue) return "Error loading secret value...";
-
- return secret.valueOverride || "";
- };
-
- const {
- control,
- watch,
- handleSubmit,
- setValue,
- reset,
- getValues,
- getFieldState,
- formState: { isDirty }
- } = useForm<TFormSchema>({
- resolver: zodResolver(formSchema),
- defaultValues: {
- ...secret,
- tags: secret?.tags?.map((tag) => ({ id: tag.id, slug: tag.slug, tagColor: tag.color })),
- valueOverride: getOverrideDefaultValue(),
- value: getDefaultValue()
- },
- disabled: !secret
- });
-
- // Update value fields when secret value is fetched, but only if user hasn't modified them
- useEffect(() => {
- if (secretValueData) {
- // Only update if the field hasn't been touched/modified by the user
- if (!getFieldState("value").isDirty && secretValueData.value !== undefined) {
- setValue("value", secretValueData.value, { shouldDirty: false });
- }
- if (!getFieldState("valueOverride").isDirty && secretValueData.valueOverride !== undefined) {
- setValue("valueOverride", secretValueData.valueOverride, { shouldDirty: false });
- }
- }
- }, [secretValueData, setValue, getFieldState]);
-
- // Reset form when a different secret is opened
- useEffect(() => {
- if (originalSecret?.id) {
- reset({
- ...secret,
- tags: secret?.tags?.map((tag) => ({ id: tag.id, slug: tag.slug, tagColor: tag.color })),
- valueOverride: getOverrideDefaultValue(),
- value: getDefaultValue()
- });
- }
- }, [originalSecret?.id]);
-
- const { handlePopUpToggle, popUp, handlePopUpOpen } = usePopUp([
- "secretAccessUpgradePlan",
- "secretReferenceTree",
- "redactSecretValue"
- ] as const);
-
- const tagFields = useFieldArray({
- control,
- name: "tags"
- });
-
- const metadataFormFields = useFieldArray({
- control,
- name: "secretMetadata"
- });
-
- const secretKey = secret?.key || "";
- const selectedTags = watch("tags", []) || [];
- const selectedTagsGroupById = selectedTags.reduce<Record<string, boolean>>(
- (prev, curr) => ({ ...prev, [curr.id]: true }),
- {}
- );
- const selectTagSlugs = selectedTags.map((i) => i.slug);
-
- const cannotEditSecret = permission.cannot(
- ProjectPermissionSecretActions.Edit,
- subject(ProjectPermissionSub.Secrets, {
- environment,
- secretPath,
- secretName: secretKey,
- secretTags: selectTagSlugs
- })
- );
-
- const cannotReadSecretValue = !hasSecretReadValueOrDescribePermission(
- permission,
- ProjectPermissionSecretActions.ReadValue,
- {
- environment,
- secretPath,
- secretName: secretKey,
- secretTags: selectTagSlugs
- }
- );
-
- const isReadOnly =
- hasSecretReadValueOrDescribePermission(
- permission,
- ProjectPermissionSecretActions.DescribeSecret,
- {
- environment,
- secretPath,
- secretName: secretKey,
- secretTags: selectTagSlugs
- }
- ) &&
- cannotEditSecret &&
- cannotReadSecretValue;
-
- const overrideAction = watch("overrideAction");
- const isOverridden =
- overrideAction === SecretActionType.Created || overrideAction === SecretActionType.Modified;
-
- const { data: secretVersion } = useGetSecretVersion({
- limit: 10,
- offset: 0,
- secretId: secret?.id
- });
-
- const { subscription } = useSubscription();
- const { data: secretAccessList, isPending } = useGetSecretAccessList({
- projectId: currentProject.id,
- environment,
- secretPath,
- secretKey: subscription?.secretAccessInsights ? secretKey : ""
- });
-
- const handleTagSelect = (tag: WsTag) => {
- if (selectedTagsGroupById?.[tag.id]) {
- const tagPos = selectedTags.findIndex(({ id }) => id === tag.id);
- if (tagPos !== -1) {
- tagFields.remove(tagPos);
- }
- } else {
- tagFields.append({ id: tag.id, slug: tag.slug, tagColor: tag.color });
- }
- };
-
- const handleFormSubmit = async (data: TFormSchema) => {
- await onSaveSecret(
- secret,
- {
- ...secret,
- ...data,
- value: getFieldState("value").isDirty ? data.value : undefined,
- valueOverride: getFieldState("valueOverride").isDirty ? data.valueOverride : undefined
- },
- () => reset()
- );
- };
-
- useEffect(() => {
- setValue(
- "reminderRecipients",
- secret?.secretReminderRecipients?.map((el) => el.user.id),
- {
- shouldDirty: false
- }
- );
- }, [secret?.secretReminderRecipients]);
-
- const fetchValue = async () => {
- if (secretValueData) return secretValueData.valueOverride ?? secretValueData.value;
-
- try {
- const data = await fetchSecretValue(fetchSecretValueParams);
-
- queryClient.setQueryData(dashboardKeys.getSecretValue(fetchSecretValueParams), data);
-
- return data?.valueOverride ?? data.value;
- } catch (error) {
- console.error(error);
- createNotification({
- type: "error",
- text: "Error fetching secret value"
- });
- throw error;
- }
- };
-
- return (
- <>
- <UpgradePlanModal
- isOpen={popUp.secretAccessUpgradePlan.isOpen}
- onOpenChange={(isUpgradeModalOpen) =>
- handlePopUpToggle("secretAccessUpgradePlan", isUpgradeModalOpen)
- }
- text="Secret access analysis feature can be unlocked if you upgrade to Infisical Pro plan."
- />
- <Modal
- isOpen={popUp.secretReferenceTree.isOpen}
- onOpenChange={(isSecretRefOpen) =>
- handlePopUpToggle("secretReferenceTree", isSecretRefOpen)
- }
- >
- <ModalContent
- className="max-w-3xl"
- title="Secret Reference Details"
- subTitle="Visual breakdown of secrets referenced by this secret."
- onOpenAutoFocus={(e) => e.preventDefault()}
- >
- <SecretReferenceTree
- secretPath={secretPath}
- environment={environment}
- secretKey={popUp.secretReferenceTree.data}
- onClose={() => {
- handlePopUpToggle("secretReferenceTree", false);
- onClose();
- }}
- />
- </ModalContent>
- </Modal>
-
- <Drawer
- onOpenChange={async (state) => {
- if (isOpen && isDirty) {
- await handleSubmit(handleFormSubmit)();
- }
- onToggle(state);
- }}
- isOpen={isOpen}
- >
- <DrawerContent
- title={`Secret – ${secret?.key}`}
- className="h-full thin-scrollbar w-md"
- cardBodyClassName="pb-0"
- onOpenAutoFocus={(e) => e.preventDefault()}
- >
- <form
- onSubmit={handleSubmit(handleFormSubmit)}
- className="flex h-full flex-1 flex-col gap-y-4"
- >
- <span className="text-sm text-bunker-300">
- Changes will automatically be applied for commit
- </span>
- <ProjectPermissionCan
- I={ProjectPermissionActions.Edit}
- a={subject(ProjectPermissionSub.Secrets, {
- environment,
- secretPath,
- secretName: secretKey,
- secretTags: selectTagSlugs
- })}
- >
- {(isAllowed) => (
- <Controller
- name="value"
- key="secret-value"
- control={control}
- render={({ field }) => (
- <FormControl
- className="mb-0"
- helperText={
- cannotReadSecretValue ? (
- <div className="flex space-x-2">
- <FontAwesomeIcon
- icon={faTriangleExclamation}
- className="mt-0.5 text-yellow-400"
- />
- <span>
- The value of this secret is hidden because you do not have the read
- secret value permission.
- </span>
- </div>
- ) : undefined
- }
- label="Value"
- >
- <div className="flex items-start gap-x-2">
- <InfisicalSecretInput
- isReadOnly={
- isReadOnly ||
- !isAllowed ||
- secret?.isRotatedSecret ||
- secret?.isHoneyTokenSecret ||
- isLoadingSecretValue ||
- isErrorFetchingSecretValue
- }
- canEditButNotView={secret.secretValueHidden && canEditSecretValue}
- environment={environment}
- secretPath={secretPath}
- key="secret-value"
- isDisabled={isOverridden}
- containerClassName="text-bunker-300 w-full hover:border-primary-400/50 border border-mineshaft-600 bg-mineshaft-900 px-2 py-1.5"
- {...field}
- autoFocus={false}
- onFocus={() => setIsFieldFocused.on()}
- onBlur={() => {
- setIsFieldFocused.off();
- field.onBlur();
- }}
- />
- <Tooltip
- content={
- !currentProject.secretSharing
- ? "This project does not allow secret sharing."
- : "You don't have permission to view the secret value."
- }
- isDisabled={!secret?.secretValueHidden && currentProject.secretSharing}
- >
- <Button
- isDisabled={secret?.secretValueHidden || !currentProject.secretSharing}
- className="px-2 py-[0.43rem] font-normal"
- variant="outline_bg"
- leftIcon={<FontAwesomeIcon icon={faShare} />}
- onClick={async () => {
- let value: string | undefined;
-
- if (hasFetchedSecretValue) {
- const values = getValues(["value", "valueOverride"]);
- value = secret.idOverride ? values[1] : values[0];
- } else {
- value = await fetchValue();
- }
-
- handleSecretShare(value ?? "");
- }}
- >
- Share
- </Button>
- </Tooltip>
- </div>
- </FormControl>
- )}
- />
- )}
- </ProjectPermissionCan>
- <div className="rounded-md border border-mineshaft-600 bg-mineshaft-900 p-4">
- <Controller
- control={control}
- name="skipMultilineEncoding"
- render={({ field: { value, onChange, onBlur } }) => (
- <ProjectPermissionCan
- I={ProjectPermissionActions.Edit}
- a={subject(ProjectPermissionSub.Secrets, {
- environment,
- secretPath,
- secretName: secretKey,
- secretTags: selectTagSlugs
- })}
- >
- {(isAllowed) => (
- <div className="flex items-center justify-between">
- <span className="w-max text-sm text-mineshaft-300">
- Multi-line encoding
- <Tooltip
- content="When enabled, multiline secrets will be handled by escaping newlines and enclosing the entire value in double quotes."
- className="z-100"
- >
- <FontAwesomeIcon icon={faCircleQuestion} className="ml-2" />
- </Tooltip>
- </span>
- <Switch
- id="skipmultiencoding-option"
- onCheckedChange={(isChecked) => onChange(isChecked)}
- isChecked={value ?? false}
- onBlur={onBlur}
- isDisabled={!isAllowed}
- className="items-center justify-between"
- />
- </div>
- )}
- </ProjectPermissionCan>
- )}
- />
- </div>
- <div className="flex flex-col rounded-md border border-mineshaft-600 bg-mineshaft-900 p-4 px-0 pb-0">
- <div
- className={`flex justify-between px-4 text-mineshaft-100 ${tagFields.fields.length > 0 ? "flex-col" : "flex-row"}`}
- >
- <div
- className={`text-sm text-mineshaft-300 ${tagFields.fields.length > 0 ? "mb-2" : "mt-0.5"}`}
- >
- Tags
- </div>
- <div>
- <FormControl>
- <div
- className={`flex flex-wrap gap-2 overflow-hidden ${tagFields.fields.length > 0 ? "pt-2" : ""}`}
- >
- {tagFields.fields.map(({ tagColor, id: formId, slug }) => (
- <Tag
- className="flex w-min items-center space-x-2"
- key={formId}
- onClose={() => {
- if (cannotEditSecret) {
- createNotification({ type: "error", text: "Access denied" });
- return;
- }
-
- const tag = tags?.find(({ slug: tagSlug }) => slug === tagSlug);
- if (tag) handleTagSelect(tag);
- }}
- >
- <div
- className="h-3 w-3 rounded-full"
- style={{ backgroundColor: tagColor || "#bec2c8" }}
- />
- <div className="text-sm">{slug}</div>
- </Tag>
- ))}
- <DropdownMenu>
- <ProjectPermissionCan
- I={ProjectPermissionActions.Edit}
- a={subject(ProjectPermissionSub.Secrets, {
- environment,
- secretPath,
- secretName: secretKey,
- secretTags: selectTagSlugs
- })}
- >
- {(isAllowed) => (
- <DropdownMenuTrigger asChild>
- <IconButton
- ariaLabel="add"
- variant="outline_bg"
- size="xs"
- className="rounded-md"
- isDisabled={!isAllowed}
- >
- <FontAwesomeIcon icon={faPlus} />
- </IconButton>
- </DropdownMenuTrigger>
- )}
- </ProjectPermissionCan>
- <DropdownMenuContent align="start" side="right" className="z-100">
- <DropdownMenuLabel className="pl-2">
- Add tags to this secret
- </DropdownMenuLabel>
- {tags.map((tag) => {
- const { id: tagId, slug, color } = tag;
-
- const isSelected = selectedTagsGroupById?.[tagId];
- return (
- <DropdownMenuItem
- onClick={() => handleTagSelect(tag)}
- key={tagId}
- icon={isSelected && <FontAwesomeIcon icon={faCheckCircle} />}
- iconPos="right"
- >
- <div className="flex items-center">
- <div
- className="mr-2 h-2 w-2 rounded-full"
- style={{ background: color || "#bec2c8" }}
- />
- {slug}
- </div>
- </DropdownMenuItem>
- );
- })}
- <ProjectPermissionCan
- I={ProjectPermissionActions.Create}
- a={ProjectPermissionSub.Tags}
- >
- {(isAllowed) => (
- <div className="p-2">
- <Button
- size="xs"
- className="w-full"
- colorSchema="primary"
- variant="outline_bg"
- leftIcon={<FontAwesomeIcon icon={faTag} />}
- onClick={onCreateTag}
- isDisabled={!isAllowed}
- >
- Create a tag
- </Button>
- </div>
- )}
- </ProjectPermissionCan>
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- </FormControl>
- </div>
- </div>
- <div
- className={`mb-4 w-full border-t border-mineshaft-600 ${tagFields.fields.length > 0 || metadataFormFields.fields.length > 0 ? "block" : "hidden"}`}
- />
- <div
- className={`flex justify-between px-4 text-mineshaft-100 ${metadataFormFields.fields.length > 0 ? "flex-col" : "flex-row"}`}
- >
- <div
- className={`text-sm text-mineshaft-300 ${metadataFormFields.fields.length > 0 ? "mb-2" : "mt-0.5"}`}
- >
- Metadata
- </div>
- <FormControl>
- <div className="flex flex-col space-y-2">
- {metadataFormFields.fields.map(({ id: metadataFieldId }, i) => (
- <div key={metadataFieldId} className="flex items-end space-x-2">
- <div className="grow">
- {i === 0 && <span className="text-xs text-mineshaft-400">Key</span>}
- <Controller
- control={control}
- name={`secretMetadata.${i}.key`}
- render={({ field, fieldState: { error } }) => (
- <FormControl
- isError={Boolean(error?.message)}
- errorText={error?.message}
- className="mb-0"
- >
- <Input {...field} className="max-h-8" />
- </FormControl>
- )}
- />
- </div>
- <div className="grow">
- {i === 0 && (
- <FormLabel
- label="Value"
- className="text-xs text-mineshaft-400"
- isOptional
- />
- )}
- <Controller
- control={control}
- name={`secretMetadata.${i}.value`}
- render={({ field, fieldState: { error } }) => (
- <FormControl
- isError={Boolean(error?.message)}
- errorText={error?.message}
- className="mb-0"
- >
- <Input {...field} className="max-h-8" />
- </FormControl>
- )}
- />
- </div>
- <div>
- {i === 0 && (
- <FormLabel label="Encrypt" className="text-xs text-mineshaft-400" />
- )}
- <Controller
- control={control}
- defaultValue={
- currentProject.enforceEncryptedSecretManagerSecretMetadata
- }
- name={`secretMetadata.${i}.isEncrypted`}
- render={({ field, fieldState: { error } }) => (
- <FormControl
- isError={Boolean(error?.message)}
- errorText={error?.message}
- className="mb-0 w-12"
- >
- <Switch
- id="metadata-is-encrypted-checkbox"
- isChecked={field.value}
- defaultChecked={field.value}
- onCheckedChange={field.onChange}
- className="mt-1.5 mb-2 ml-1"
- />
- </FormControl>
- )}
- />
- </div>
- <IconButton
- ariaLabel="delete key"
- className="bottom-0.5 max-h-8"
- variant="outline_bg"
- onClick={() => metadataFormFields.remove(i)}
- >
- <FontAwesomeIcon icon={faTrash} />
- </IconButton>
- </div>
- ))}
- <div className={`${metadataFormFields.fields.length > 0 ? "pt-2" : ""}`}>
- <IconButton
- ariaLabel="Add Key"
- variant="outline_bg"
- size="xs"
- className="rounded-md"
- onClick={() =>
- metadataFormFields.append({ key: "", value: "", isEncrypted: false })
- }
- >
- <FontAwesomeIcon icon={faPlus} />
- </IconButton>
- </div>
- </div>
- </FormControl>
- </div>
- </div>
- <Controller
- control={control}
- name="comment"
- render={({ field, fieldState: { error } }) => (
- <FormControl
- label="Comments & Notes"
- isError={Boolean(error?.message)}
- errorText={error?.message}
- className="mb-0 h-[125px] pb-0"
- >
- <TextArea
- className="mb-0 resize-none! border border-mineshaft-600 bg-mineshaft-900 text-sm"
- readOnly={isReadOnly}
- placeholder="add a comment or note to this secret..."
- rows={4}
- {...field}
- />
- </FormControl>
- )}
- />
- <div className="dark flex max-h-96 flex-1 cursor-default flex-col text-sm text-bunker-300">
- <div className="mb-0.5 text-mineshaft-400">Version History</div>
- <div className="flex thin-scrollbar flex-1 flex-col space-y-2 overflow-x-hidden overflow-y-auto rounded-md border border-mineshaft-600 bg-mineshaft-900 p-4 dark:scheme-dark">
- {secretVersion?.map((version) => (
- <SecretVersionItem
- canReadValue={!cannotReadSecretValue}
- secretVersion={version}
- secret={secret}
- currentVersion={secretVersion.length}
- onRedactSecretValue={async (versionId) => {
- await redactSecretValue({ versionId, secretId: secret.id });
-
- createNotification({
- title: "Secret value redacted",
- text: "The secret value has been redacted successfully and is no longer persisted or viewable.",
- type: "success"
- });
- }}
- canEditSecret={!cannotEditSecret}
- onRevert={async (versionValue) => {
- await fetchValue();
-
- setTimeout(() => {
- setValue("value", versionValue, { shouldDirty: true });
- }, 5);
- }}
- />
- ))}
- </div>
- </div>
- <div className="dark flex flex-col text-sm text-bunker-300">
- <div className="mb-0.5 text-mineshaft-400">
- Access List
- <Tooltip
- content="Lists all users, machine identities, and groups that have been granted any permission level (read, create, edit, or delete) for this secret."
- className="z-100"
- >
- <FontAwesomeIcon icon={faCircleQuestion} className="ml-2" />
- </Tooltip>
- </div>
- {secretAccessList ? (
- <div className="flex flex-col space-y-2 overflow-x-hidden overflow-y-auto rounded-md border border-mineshaft-600 bg-mineshaft-900 p-4 dark:scheme-dark">
- {secretAccessList.users.length > 0 && (
- <div className="pb-3">
- <div className="mb-2 font-bold">Users</div>
- <div className="flex flex-wrap gap-2">
- {secretAccessList.users.map((user) => (
- <div className="rounded-md bg-bunker-500">
- <Tooltip
- side="left"
- content={user.allowedActions
- .map((action) => camelCaseToSpaces(action))
- .join(", ")}
- className="z-100 capitalize"
- >
- <div className="text-secondary/80 rounded-md border border-mineshaft-600 bg-mineshaft-700 px-1 py-0.5 text-sm hover:text-mineshaft-100">
- {user.name}
- </div>
- </Tooltip>
- </div>
- ))}
- </div>
- </div>
- )}
- {secretAccessList.identities.length > 0 && (
- <div className="pb-3">
- <div className="mb-2 font-bold">Identities</div>
- <div className="flex flex-wrap gap-2">
- {secretAccessList.identities.map((identity) => (
- <div className="rounded-md bg-bunker-500">
- <Tooltip
- side="left"
- content={identity.allowedActions
- .map(
- (action) =>
- action.charAt(0).toUpperCase() + action.slice(1).toLowerCase()
- )
- .join(", ")}
- className="z-100"
- >
- <Link
- to={
- `${getProjectBaseURL(currentProject.type)}/identities/$identityId` as const
- }
- params={{
- orgId: currentOrg.id,
- projectId: currentProject.id,
- identityId: identity.id
- }}
- className="text-secondary/80 rounded-md border border-mineshaft-600 bg-mineshaft-700 px-1 py-0.5 text-sm hover:text-mineshaft-100"
- >
- {identity.name}
- </Link>
- </Tooltip>
- </div>
- ))}
- </div>
- </div>
- )}
- {secretAccessList.groups.length > 0 && (
- <div className="pb-3">
- <div className="mb-2 font-bold">Groups</div>
- <div className="flex flex-wrap gap-2">
- {secretAccessList.groups.map((group) => (
- <div className="rounded-md bg-bunker-500">
- <Tooltip
- side="left"
- content={group.allowedActions
- .map(
- (action) =>
- action.charAt(0).toUpperCase() + action.slice(1).toLowerCase()
- )
- .join(", ")}
- className="z-100"
- >
- <Link
- to={"/organizations/$orgId/groups/$groupId" as const}
- params={{
- orgId: currentOrg.id,
- groupId: group.id
- }}
- className="text-secondary/80 rounded-md border border-mineshaft-600 bg-mineshaft-700 px-1 py-0.5 text-sm hover:text-mineshaft-100"
- >
- {group.name}
- </Link>
- </Tooltip>
- </div>
- ))}
- </div>
- </div>
- )}
- </div>
- ) : (
- <Button
- className="w-full"
- leftIcon={<FontAwesomeIcon icon={faSearch} />}
- variant="outline_bg"
- isDisabled={isPending}
- isLoading={isPending}
- onClick={() => handlePopUpOpen("secretAccessUpgradePlan")}
- >
- Analyze Access
- </Button>
- )}
- </div>
- <div className="mt-auto flex items-center space-x-2 pb-4">
- <Button
- className="flex-1"
- variant="outline_bg"
- isDisabled={cannotReadSecretValue || secret.isEmpty}
- leftIcon={<FontAwesomeIcon icon={faProjectDiagram} />}
- onClick={() => handlePopUpOpen("secretReferenceTree", secretKey)}
- >
- Secret References
- </Button>
- <Tooltip content="Copy Secret ID" className="z-100">
- <IconButton
- variant="outline_bg"
- ariaLabel="Copy Secret ID"
- onClick={async () => {
- await navigator.clipboard.writeText(secret.id);
-
- createNotification({
- title: "Secret ID Copied",
- text: "The secret ID has been copied to your clipboard.",
- type: "success"
- });
- }}
- >
- <FontAwesomeIcon icon={faCopy} />
- </IconButton>
- </Tooltip>
- <ProjectPermissionCan
- I={ProjectPermissionActions.Delete}
- a={subject(ProjectPermissionSub.Secrets, {
- environment,
- secretPath,
- secretName: secretKey,
- secretTags: selectTagSlugs
- })}
- >
- {(isAllowed) => (
- <Tooltip content="Delete Secret" align="end" className="z-100">
- <IconButton
- colorSchema="danger"
- variant="outline_bg"
- ariaLabel="Delete Secret"
- className="h-min border border-mineshaft-600 bg-mineshaft-700 hover:border-red-500/70 hover:bg-red-600/20"
- isDisabled={!isAllowed}
- onClick={onDeleteSecret}
- >
- <FontAwesomeIcon icon={faTrash} />
- </IconButton>
- </Tooltip>
- )}
- </ProjectPermissionCan>
- </div>
- </form>
- </DrawerContent>
- </Drawer>
- </>
- );
-};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretListView.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretListView.tsx
deleted file mode 100644
index 4de5d11ded..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretListView.tsx
+++ /dev/null
@@ -1,652 +0,0 @@
-import { useCallback, useEffect, useRef } from "react";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import { useQueryClient } from "@tanstack/react-query";
-
-import { createNotification } from "@app/components/notifications";
-import { CreateTagModal } from "@app/components/tags/CreateTagModal";
-import { DeleteActionModal } from "@app/components/v2";
-import { usePopUp } from "@app/hooks";
-import { useCreateSecretV3, useDeleteSecretV3, useUpdateSecretV3 } from "@app/hooks/api";
-import { dashboardKeys } from "@app/hooks/api/dashboard/queries";
-import { UsedBySecretSyncs } from "@app/hooks/api/dashboard/types";
-import { commitKeys } from "@app/hooks/api/folderCommits/queries";
-import { secretApprovalRequestKeys } from "@app/hooks/api/secretApprovalRequest/queries";
-import { PendingAction } from "@app/hooks/api/secretFolders/types";
-import { secretKeys } from "@app/hooks/api/secrets/queries";
-import { SecretType, SecretV3RawSanitized } from "@app/hooks/api/secrets/types";
-import { WsTag } from "@app/hooks/api/types";
-import { useNavigationBlocker } from "@app/hooks/useNavigationBlocker";
-import { AddShareSecretModal } from "@app/pages/organization/SecretSharingPage/components/ShareSecret/AddShareSecretModal";
-
-import {
- PendingSecretChange,
- PendingSecretCreate,
- PendingSecretDelete,
- PendingSecretUpdate,
- useBatchMode,
- useBatchModeActions,
- useSelectedSecretActions,
- useSelectedSecrets
-} from "../../SecretMainPage.store";
-import { CollapsibleSecretImports } from "./CollapsibleSecretImports";
-import { SecretDetailSidebar } from "./SecretDetailSidebar";
-import { HIDDEN_SECRET_VALUE, HIDDEN_SECRET_VALUE_API_MASK, SecretItem } from "./SecretItem";
-import { FontAwesomeSpriteSymbols } from "./SecretListView.utils";
-
-type Props = {
- secrets?: SecretV3RawSanitized[];
- environment: string;
- projectId: string;
- secretPath?: string;
- tags?: WsTag[];
- isVisible?: boolean;
- isProtectedBranch?: boolean;
- usedBySecretSyncs?: UsedBySecretSyncs[];
- importedBy?: {
- environment: { name: string; slug: string };
- folders: {
- name: string;
- secrets?: { secretId: string; referencedSecretKey: string; referencedSecretEnv: string }[];
- isImported: boolean;
- }[];
- }[];
- colWidth: number;
- excludePendingCreates?: boolean;
-};
-
-export const SecretListView = ({
- secrets = [],
- environment,
- projectId,
- secretPath = "/",
- tags: wsTags = [],
- isVisible,
- isProtectedBranch = false,
- usedBySecretSyncs,
- importedBy,
- colWidth,
- excludePendingCreates = false
-}: Props) => {
- const queryClient = useQueryClient();
- const { popUp, handlePopUpToggle, handlePopUpOpen, handlePopUpClose } = usePopUp([
- "deleteSecret",
- "secretDetail",
- "createTag",
- "createSharedSecret"
- ] as const);
-
- // strip of side effect queries
- const { mutateAsync: createSecretV3 } = useCreateSecretV3({
- options: { onSuccess: undefined }
- });
- const { mutateAsync: updateSecretV3 } = useUpdateSecretV3({
- options: { onSuccess: undefined }
- });
- const { mutateAsync: deleteSecretV3 } = useDeleteSecretV3({
- options: { onSuccess: undefined }
- });
-
- const selectedSecrets = useSelectedSecrets();
- const { toggle: toggleSelectedSecret } = useSelectedSecretActions();
- const { isBatchMode, pendingChanges } = useBatchMode();
- useNavigationBlocker({
- shouldBlock: pendingChanges.secrets.length > 0 || pendingChanges.folders.length > 0,
- message:
- "You have unsaved changes. If you leave now, your work will be lost. Do you want to continue?",
- context: {
- projectId,
- environment,
- secretPath
- }
- });
- const { addPendingChange } = useBatchModeActions();
-
- const pendingChangesRef = useRef(pendingChanges);
- useEffect(() => {
- pendingChangesRef.current = pendingChanges;
- }, [pendingChanges]);
-
- const handleSecretOperation = async (
- operation: "create" | "update" | "delete",
- type: SecretType,
- key: string,
- {
- secretValueHidden,
- value,
- comment,
- reminderRepeatDays,
- reminderNote,
- reminderRecipients,
- tags,
- skipMultilineEncoding,
- newKey,
- secretId,
- secretMetadata,
- isRotatedSecret,
- isHoneyTokenSecret
- }: Partial<{
- secretValueHidden: boolean;
- value: string;
- comment: string;
- reminderRepeatDays: number | null;
- reminderNote: string | null;
- reminderRecipients?: string[] | null;
- tags: string[];
- skipMultilineEncoding: boolean | null;
- newKey: string;
- secretId: string;
- secretMetadata?: { key: string; value: string }[];
- isRotatedSecret?: boolean;
- isHoneyTokenSecret?: boolean;
- }> = {}
- ) => {
- if (operation === "delete") {
- await deleteSecretV3({
- environment,
- projectId,
- secretPath,
- secretKey: key,
- type,
- secretId
- });
- return;
- }
-
- if (operation === "update") {
- let secretValue = value;
-
- if (
- secretValueHidden &&
- (value === HIDDEN_SECRET_VALUE_API_MASK || value === HIDDEN_SECRET_VALUE)
- ) {
- secretValue = undefined;
- }
-
- await updateSecretV3({
- environment,
- projectId,
- secretPath,
- secretKey: key,
- ...(!(isRotatedSecret || isHoneyTokenSecret) && {
- newSecretName: newKey,
- secretValue: secretValueHidden ? secretValue : secretValue || ""
- }),
- type,
- tagIds: tags,
- secretComment: comment,
- secretReminderRepeatDays: reminderRepeatDays,
- secretReminderNote: reminderNote,
- secretReminderRecipients: reminderRecipients,
- skipMultilineEncoding,
- secretMetadata
- });
- return;
- }
-
- await createSecretV3(
- {
- environment,
- projectId,
- secretPath,
- secretKey: key,
- secretValue: value || "",
- secretComment: "",
- skipMultilineEncoding,
- type
- },
- {}
- );
- };
-
- function getTrueOriginalSecret(
- currentSecret: SecretV3RawSanitized,
- pendingSecrets: PendingSecretChange[]
- ): Omit<SecretV3RawSanitized, "tags"> & {
- tags?: { id: string; slug: string }[];
- } {
- // Find if there's already a pending change for this secret
- const existingChange = pendingSecrets.find((change) => change.id === currentSecret.id);
-
- if (!existingChange || existingChange.type === "create") {
- // If no existing change or it's a creation, current secret is the original
- return {
- ...currentSecret,
- tags: currentSecret.tags?.map((tag) => ({
- id: tag.id,
- slug: tag.slug
- }))
- };
- }
-
- if (existingChange.type === "update") {
- // If there's an existing update, reconstruct the original from the stored original values
- return {
- ...currentSecret,
- key: existingChange.secretKey, // Original key
- value: existingChange.originalValue || currentSecret.value,
- comment: existingChange.originalComment || currentSecret.comment,
- skipMultilineEncoding:
- existingChange.originalSkipMultilineEncoding ?? currentSecret.skipMultilineEncoding,
- tags:
- existingChange.originalTags?.map((tag) => ({
- id: tag.id,
- slug: tag.slug
- })) || currentSecret.tags,
- secretMetadata: existingChange.originalSecretMetadata || currentSecret.secretMetadata
- };
- }
-
- return {
- ...currentSecret,
- tags: currentSecret.tags?.map((tag) => ({ id: tag.id, slug: tag.slug }))
- };
- }
-
- // Improved handleSaveSecret function
- const handleSaveSecret = useCallback(
- async (
- orgSecret: SecretV3RawSanitized,
- modSecret: Omit<SecretV3RawSanitized, "tags"> & {
- tags?: { id: string; name?: string; slug?: string }[];
- secretMetadata?: { key: string; value: string }[];
- },
- cb?: () => void
- ) => {
- const { key: oldKey, secretValueHidden } = orgSecret;
- const {
- key,
- value,
- overrideAction,
- idOverride,
- valueOverride,
- tags,
- comment,
- reminderRepeatDays,
- reminderNote,
- reminderRecipients,
- secretMetadata,
- isReminderEvent,
- isPending,
- pendingAction
- } = modSecret;
- const hasKeyChanged = oldKey !== key && key;
-
- const tagIds = tags?.map(({ id }) => id);
- const oldTagIds = (orgSecret?.tags || []).map(({ id }) => id);
- const isSameTags = JSON.stringify(tagIds) === JSON.stringify(oldTagIds);
-
- const isSameRecipients =
- !reminderRecipients?.some(
- (newId) => !orgSecret.secretReminderRecipients?.find((oldId) => newId === oldId.user.id)
- ) && reminderRecipients?.length === orgSecret.secretReminderRecipients?.length;
-
- const isSharedSecUnchanged =
- (
- [
- "key",
- "value",
- "comment",
- "skipMultilineEncoding",
- "reminderRepeatDays",
- "reminderNote",
- "reminderRecipients",
- "secretMetadata"
- ] as const
- ).every((el) => orgSecret[el] === modSecret[el]) &&
- isSameTags &&
- isSameRecipients;
-
- // personal secret change
- let personalAction = false;
- if (overrideAction === "deleted") {
- await handleSecretOperation("delete", SecretType.Personal, oldKey, {
- secretId: orgSecret.idOverride
- });
- personalAction = true;
- } else if (overrideAction && idOverride) {
- await handleSecretOperation("update", SecretType.Personal, oldKey, {
- value: valueOverride,
- newKey: hasKeyChanged ? key : undefined,
- secretId: orgSecret.idOverride,
- skipMultilineEncoding: modSecret.skipMultilineEncoding
- });
- personalAction = true;
- } else if (overrideAction) {
- await handleSecretOperation("create", SecretType.Personal, oldKey, {
- value: valueOverride
- });
- personalAction = true;
- }
-
- // shared secret change
- if (!isSharedSecUnchanged && !personalAction) {
- if (isBatchMode) {
- const isEditingPendingCreation = isPending && pendingAction === PendingAction.Create;
-
- if (isEditingPendingCreation) {
- const updatedCreate: PendingSecretCreate = {
- id: orgSecret.id,
- type: PendingAction.Create,
- secretKey: key,
- secretValue: value || "",
- secretComment: comment || "",
- skipMultilineEncoding: modSecret.skipMultilineEncoding || false,
- tags: tags?.map((tag) => ({ id: tag.id, slug: tag.name || tag.slug || "" })) || [],
- secretMetadata: secretMetadata || [],
- timestamp: Date.now(),
- resourceType: "secret",
- originalKey: oldKey
- };
-
- addPendingChange(updatedCreate, {
- projectId,
- environment,
- secretPath
- });
- } else {
- const trueOriginalSecret = getTrueOriginalSecret(
- orgSecret,
- pendingChangesRef.current.secrets
- );
-
- const updateChange: PendingSecretUpdate = {
- id: orgSecret.id,
- type: PendingAction.Update,
- secretKey: trueOriginalSecret.key,
- newSecretName: key,
- originalValue: trueOriginalSecret.value,
- secretValue: value,
- originalComment: trueOriginalSecret.comment,
- secretComment: comment,
- originalSkipMultilineEncoding: trueOriginalSecret.skipMultilineEncoding,
- skipMultilineEncoding: modSecret.skipMultilineEncoding,
- originalTags:
- trueOriginalSecret.tags?.map((tag) => ({ id: tag.id, slug: tag.slug })) || [],
- tags: tags?.map((tag) => ({ id: tag.id, slug: tag.name || tag.slug || "" })) || [],
- originalSecretMetadata: trueOriginalSecret.secretMetadata || [],
- secretMetadata: secretMetadata || [],
- timestamp: Date.now(),
- resourceType: "secret",
- existingSecret: orgSecret
- };
-
- addPendingChange(updateChange, {
- projectId,
- environment,
- secretPath
- });
- }
-
- if (!isReminderEvent) {
- handlePopUpClose("secretDetail");
- }
- if (cb) cb();
- return;
- }
-
- await handleSecretOperation("update", SecretType.Shared, oldKey, {
- value,
- tags: tagIds,
- comment,
- reminderRepeatDays,
- reminderNote,
- reminderRecipients,
- secretId: orgSecret.id,
- newKey: hasKeyChanged ? key : undefined,
- skipMultilineEncoding: modSecret.skipMultilineEncoding,
- secretMetadata,
- isRotatedSecret: orgSecret.isRotatedSecret,
- isHoneyTokenSecret: orgSecret.isHoneyTokenSecret,
- secretValueHidden
- });
- if (cb) cb();
- }
- queryClient.invalidateQueries({
- queryKey: dashboardKeys.getDashboardSecrets({
- projectId,
- secretPath
- })
- });
- queryClient.invalidateQueries({
- queryKey: secretKeys.getProjectSecret({ projectId, environment, secretPath })
- });
- queryClient.invalidateQueries({
- queryKey: commitKeys.count({ projectId, environment, directory: secretPath })
- });
- queryClient.invalidateQueries({
- queryKey: commitKeys.history({
- projectId,
- environment,
- directory: secretPath
- })
- });
- queryClient.invalidateQueries({
- queryKey: secretApprovalRequestKeys.count({ projectId })
- });
- queryClient.invalidateQueries({
- queryKey: secretApprovalRequestKeys.listAllForProject({ projectId })
- });
- if (!isReminderEvent) {
- handlePopUpClose("secretDetail");
- }
-
- let successMessage;
- if (isReminderEvent) {
- successMessage = reminderRepeatDays
- ? "Successfully saved secret reminder"
- : "Successfully deleted secret reminder";
- } else {
- successMessage = "Successfully saved secrets";
- }
-
- createNotification({
- type: isProtectedBranch && !personalAction ? "info" : "success",
- text:
- isProtectedBranch && !personalAction
- ? "Requested changes have been sent for review"
- : successMessage
- });
- },
- [environment, secretPath, isProtectedBranch, isBatchMode, projectId, addPendingChange]
- );
-
- // Function to append newly created tag to the current secret
- const append = useCallback(
- (newTag: WsTag) => {
- const currentSecret = popUp.createTag.data as SecretV3RawSanitized;
- if (!currentSecret) return;
-
- const updatedTags = [...(currentSecret.tags || []), { id: newTag.id, slug: newTag.slug }];
-
- handleSaveSecret(currentSecret, {
- ...currentSecret,
- tags: updatedTags
- });
- },
- [popUp.createTag.data, handleSaveSecret]
- );
-
- const handleSecretDelete = useCallback(async () => {
- const {
- key,
- id: secretId,
- value,
- secretValueHidden,
- tags,
- secretMetadata,
- skipMultilineEncoding,
- comment
- } = popUp.deleteSecret?.data as SecretV3RawSanitized;
- if (isBatchMode) {
- const secretValueForDelete = value !== undefined ? value : HIDDEN_SECRET_VALUE_API_MASK;
-
- const deleteChange: PendingSecretDelete = {
- id: `${secretId}`,
- type: PendingAction.Delete,
- secretKey: key,
- secretValue: secretValueForDelete,
- timestamp: Date.now(),
- resourceType: "secret",
- secretValueHidden,
- tags: tags || [],
- secretMetadata: secretMetadata || [],
- skipMultilineEncoding: skipMultilineEncoding || false,
- comment: comment || ""
- };
-
- addPendingChange(deleteChange, {
- projectId,
- environment,
- secretPath
- });
-
- handlePopUpClose("deleteSecret");
- handlePopUpClose("secretDetail");
- return;
- }
-
- await handleSecretOperation("delete", SecretType.Shared, key, { secretId });
- // wrap this in another function and then reuse
- queryClient.invalidateQueries({
- queryKey: dashboardKeys.getDashboardSecrets({ projectId, secretPath })
- });
- queryClient.invalidateQueries({
- queryKey: secretKeys.getProjectSecret({ projectId, environment, secretPath })
- });
- queryClient.invalidateQueries({
- queryKey: commitKeys.count({ projectId, environment, directory: secretPath })
- });
- queryClient.invalidateQueries({
- queryKey: commitKeys.history({ projectId, environment, directory: secretPath })
- });
- queryClient.invalidateQueries({
- queryKey: secretApprovalRequestKeys.count({ projectId })
- });
- queryClient.invalidateQueries({
- queryKey: secretApprovalRequestKeys.listAllForProject({ projectId })
- });
- handlePopUpClose("deleteSecret");
- handlePopUpClose("secretDetail");
- createNotification({
- type: isProtectedBranch ? "info" : "success",
- text: isProtectedBranch
- ? "Requested changes have been sent for review"
- : "Successfully deleted secret"
- });
- }, [
- (popUp.deleteSecret?.data as SecretV3RawSanitized)?.key,
- environment,
- secretPath,
- isProtectedBranch,
- isBatchMode,
- projectId,
- addPendingChange
- ]);
-
- // for optimization on minimise re-rendering of secret items
- const onCreateTag = useCallback((secret?: SecretV3RawSanitized) => {
- if (secret) {
- handlePopUpOpen("createTag", secret);
- } else {
- handlePopUpOpen("createTag");
- }
- }, []);
- const onDeleteSecret = useCallback(
- (sec: SecretV3RawSanitized) => handlePopUpOpen("deleteSecret", sec),
- []
- );
- const onDetailViewSecret = useCallback(
- (sec: SecretV3RawSanitized) => handlePopUpOpen("secretDetail", sec),
- []
- );
- const onShareSecret = useCallback(
- (sec: SecretV3RawSanitized) =>
- handlePopUpOpen("createSharedSecret", {
- value: sec.valueOverride ?? sec.value
- }),
- []
- );
-
- return (
- <>
- {FontAwesomeSpriteSymbols.map(({ icon, symbol }) => (
- <FontAwesomeIcon icon={icon} symbol={symbol} key={`font-awesome-svg-spritie-${symbol}`} />
- ))}
- {secrets
- .filter((secret) => {
- if (!excludePendingCreates) return true;
- return !secret.isPending || secret.pendingAction !== PendingAction.Create;
- })
- .map((secret) => (
- <SecretItem
- colWidth={colWidth}
- environment={environment}
- secretPath={secretPath}
- tags={wsTags}
- isSelected={Boolean(selectedSecrets?.[secret.id])}
- onToggleSecretSelect={toggleSelectedSecret}
- isVisible={isVisible}
- secret={secret}
- key={secret.id}
- onSaveSecret={handleSaveSecret}
- onDeleteSecret={onDeleteSecret}
- onDetailViewSecret={onDetailViewSecret}
- importedBy={importedBy}
- onCreateTag={onCreateTag}
- onShareSecret={onShareSecret}
- isPending={secret.isPending}
- pendingAction={secret.pendingAction}
- />
- ))}
- <DeleteActionModal
- isOpen={popUp.deleteSecret.isOpen}
- deleteKey={(popUp.deleteSecret?.data as SecretV3RawSanitized)?.key}
- title="Do you want to delete this secret?"
- onChange={(isOpen) => handlePopUpToggle("deleteSecret", isOpen)}
- onDeleteApproved={handleSecretDelete}
- buttonText="Delete Secret"
- formContent={
- ((importedBy && importedBy.length > 0) ||
- (usedBySecretSyncs && usedBySecretSyncs?.length > 0)) && (
- <CollapsibleSecretImports
- importedBy={importedBy}
- usedBySecretSyncs={usedBySecretSyncs}
- secretsToDelete={[(popUp.deleteSecret?.data as SecretV3RawSanitized)?.key || ""]}
- />
- )
- }
- deletionMessage={
- <>
- Type the secret key{" "}
- <span className="font-bold">
- &quot;{(popUp.deleteSecret?.data as SecretV3RawSanitized)?.key}&quot;
- </span>{" "}
- to perform this action
- </>
- }
- />
- {popUp.secretDetail.data && (
- <SecretDetailSidebar
- environment={environment}
- secretPath={secretPath}
- isOpen={popUp.secretDetail.isOpen}
- onToggle={(isOpen) => handlePopUpToggle("secretDetail", isOpen)}
- secret={popUp.secretDetail.data as SecretV3RawSanitized}
- onDeleteSecret={() => handlePopUpOpen("deleteSecret", popUp.secretDetail.data)}
- onClose={() => handlePopUpClose("secretDetail")}
- onSaveSecret={handleSaveSecret}
- tags={wsTags}
- onCreateTag={() => handlePopUpOpen("createTag")}
- handleSecretShare={(value: string) => handlePopUpOpen("createSharedSecret", { value })}
- />
- )}
- <CreateTagModal
- isOpen={popUp.createTag.isOpen}
- onToggle={(isOpen) => handlePopUpToggle("createTag", isOpen)}
- append={append}
- currentSecret={popUp.createTag.data}
- />
- <AddShareSecretModal popUp={popUp} handlePopUpToggle={handlePopUpToggle} />
- </>
- );
-};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretNoAccessListView.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretNoAccessListView.tsx
deleted file mode 100644
index fa75168f53..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretNoAccessListView.tsx
+++ /dev/null
@@ -1,68 +0,0 @@
-import { faLock, faRotate } from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import { twMerge } from "tailwind-merge";
-
-import { FontAwesomeSymbol, Input, Tooltip } from "@app/components/v2";
-import { Blur } from "@app/components/v2/Blur";
-
-import { FontAwesomeSpriteName } from "./SecretListView.utils";
-
-type Props = {
- count: number;
- isRotationView?: boolean;
-};
-
-export const SecretNoAccessListView = ({ count, isRotationView }: Props) => {
- return (
- <>
- {Array.from(Array(count)).map((_, i) => (
- <Tooltip
- className="max-w-sm"
- asChild
- content="You do not have permission to view this secret"
- key={`no-access-secret-${i + 1}`}
- >
- <div
- className={twMerge(
- "flex border-b border-mineshaft-600 shadow-none hover:bg-mineshaft-700",
- isRotationView ? "bg-mineshaft-700/60" : "bg-mineshaft-800"
- )}
- >
- <div className="flex h-11 w-11 items-center justify-center px-4 py-3">
- {isRotationView ? (
- <div className="relative">
- <FontAwesomeIcon
- icon={faLock}
- size="xs"
- className={twMerge("ml-3 h-3.5 w-3.5")}
- />
- <FontAwesomeIcon
- icon={faRotate}
- size="xs"
- className="absolute -right-[0.2rem] -bottom-[0.05rem] text-mineshaft-400"
- />
- </div>
- ) : (
- <FontAwesomeSymbol
- className="ml-3 block h-3.5 w-3.5"
- symbolName={FontAwesomeSpriteName.KeyLock}
- />
- )}
- </div>
- <div className="ml-[0.05rem] flex h-11 w-80 shrink-0 items-center border-r border-mineshaft-600 px-4 py-2">
- <Input
- autoComplete="off"
- isReadOnly
- variant="plain"
- value="NO ACCESS"
- isDisabled
- className="w-full px-0 blur-xs placeholder:text-red-500 focus:text-bunker-100 focus:ring-transparent"
- />
- </div>
- <Blur className="pl-8" />
- </div>
- </Tooltip>
- ))}
- </>
- );
-};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretVersionItem.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretVersionItem.tsx
deleted file mode 100644
index e931e08d18..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretVersionItem.tsx
+++ /dev/null
@@ -1,423 +0,0 @@
-import { useState } from "react";
-import { faEye } from "@fortawesome/free-regular-svg-icons";
-import {
- faArrowRotateRight,
- faBan,
- faDesktop,
- faEyeSlash,
- faLock,
- faServer,
- faTrash,
- faUser
-} from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import { useNavigate } from "@tanstack/react-router";
-import { format } from "date-fns";
-import { twMerge } from "tailwind-merge";
-
-import { createNotification } from "@app/components/notifications";
-import { DeleteActionModal, IconButton, Tooltip } from "@app/components/v2";
-import { useProject } from "@app/context";
-import { usePopUp } from "@app/hooks";
-import { ActorType } from "@app/hooks/api/auditLogs/enums";
-import { fetchSecretVersionValue } from "@app/hooks/api/secrets/queries";
-import { SecretV3RawSanitized, SecretVersions } from "@app/hooks/api/secrets/types";
-
-interface SecretVersionItemProps {
- secretVersion: SecretVersions;
- secret: SecretV3RawSanitized;
- currentVersion: number;
- onRevert: (secretValue: string) => void;
- onRedactSecretValue: (versionId: string) => Promise<void>;
- canReadValue: boolean;
- canEditSecret: boolean;
-}
-
-export const SecretVersionItem = ({
- secretVersion: {
- createdAt,
- version,
- actor,
- secretValueHidden,
- id: versionId,
- isRedacted,
- redactedAt,
- redactedByActor
- },
- secret,
- currentVersion,
- onRevert,
- onRedactSecretValue,
- canReadValue,
- canEditSecret
-}: SecretVersionItemProps) => {
- const { currentProject } = useProject();
-
- const { handlePopUpToggle, popUp, handlePopUpOpen } = usePopUp(["redactSecretValue"] as const);
-
- const navigate = useNavigate();
-
- const getModifiedByIcon = (userType: string | undefined | null) => {
- switch (userType) {
- case ActorType.USER:
- return faUser;
- case ActorType.IDENTITY:
- return faDesktop;
- default:
- return faServer;
- }
- };
-
- const getModifiedByName = (
- userType: string | undefined | null,
- userName: string | null | undefined
- ) => {
- switch (userType) {
- case ActorType.PLATFORM:
- return "System-generated";
- case ActorType.IDENTITY:
- return userName || "Deleted Identity";
- case ActorType.USER:
- return userName || "Deleted User";
- default:
- return "Unknown";
- }
- };
-
- const getLinkToModifyHistoryEntity = (
- actorId: string,
- actorType: string,
- membershipId: string | null = "",
- groupId: string | null = "",
- actorName: string | null = ""
- ) => {
- switch (actorType) {
- case ActorType.USER:
- if (groupId)
- return `/projects/secret-management/${currentProject.id}/groups/${groupId}?username=${actorName}`;
- return `/projects/secret-management/${currentProject.id}/members/${membershipId}`;
- case ActorType.IDENTITY:
- return `/projects/secret-management/${currentProject.id}/identities/${actorId}`;
- default:
- return null;
- }
- };
-
- const onModifyHistoryClick = (
- actorId: string | undefined | null,
- actorType: string | undefined | null,
- membershipId: string | undefined | null,
- groupId: string | undefined | null,
- actorName: string | undefined | null
- ) => {
- if (!membershipId) {
- createNotification({
- type: "info",
- text: `This ${actorType === ActorType.USER ? "user" : "identity"} is no longer a member of this project.`
- });
- return;
- }
-
- if (actorType && actorId && actorType !== ActorType.PLATFORM) {
- const redirectLink = getLinkToModifyHistoryEntity(
- actorId,
- actorType,
- membershipId,
- groupId,
- actorName
- );
- if (redirectLink) {
- navigate({ to: redirectLink });
- }
- }
- };
-
- const [secretValue, setSecretValue] = useState<string | null>(null);
- const [isFetchingValue, setIsFetchingValue] = useState(false);
- const handleGetSecretValue = async () => {
- if (secretValue) return secretValue;
- try {
- setIsFetchingValue(true);
- const value = await fetchSecretVersionValue(secret.id, version);
- setSecretValue(value);
- return value;
- } catch (e) {
- console.error(e);
- createNotification({
- type: "error",
- text: "Failed to fetch secret version value"
- });
- throw e;
- } finally {
- setIsFetchingValue(false);
- }
- };
-
- const handleCopyValue = async (
- e: React.MouseEvent<HTMLButtonElement> | React.KeyboardEvent<HTMLButtonElement>
- ) => {
- const value = await handleGetSecretValue();
- navigator.clipboard.writeText(value || "");
- const target = e.currentTarget;
- target.style.borderBottom = "1px dashed";
- target.style.paddingBottom = "-1px";
-
- // Create and insert popup
- const popup = document.createElement("div");
- popup.className =
- "w-16 flex justify-center absolute top-6 left-0 text-xs text-primary-100 bg-mineshaft-800 px-1 py-0.5 rounded-md border border-primary-500/50";
- popup.textContent = "Copied!";
- target.parentElement?.appendChild(popup);
-
- // Remove popup and border after delay
- setTimeout(() => {
- popup.remove();
- target.style.borderBottom = "none";
- }, 3000);
- };
-
- return (
- <>
- <DeleteActionModal
- isOpen={popUp.redactSecretValue.isOpen}
- onChange={(isOpen) => handlePopUpToggle("redactSecretValue", isOpen)}
- onDeleteApproved={async () => {
- await onRedactSecretValue(versionId);
-
- handlePopUpToggle("redactSecretValue", false);
- }}
- deleteKey="confirm"
- title={`Are you sure you want to redact the secret value on version ${version}? This action is irreversible.`}
- />
- <div className={twMerge("flex flex-row", isRedacted && "opacity-100")}>
- <div className="flex w-full flex-col space-y-1">
- <div className="flex items-center">
- <div className="w-10">
- <div
- className={twMerge(
- "w-fit rounded-md border border-mineshaft-600 px-1 text-sm text-mineshaft-300",
- isRedacted ? "bg-red-500/30" : "bg-mineshaft-700"
- )}
- >
- v{version}
- </div>
- </div>
- <div>{format(new Date(createdAt), "Pp")}</div>
- </div>
- <div className="flex w-full cursor-default">
- <div className="relative w-10">
- <div className="absolute top-0 bottom-0 left-3 mt-0.5 border-l border-mineshaft-400/60" />
- </div>
- <div className="flex w-full cursor-default flex-col">
- {actor && (
- <div className="flex flex-row">
- <div className="flex w-fit flex-row text-sm">
- Modified by:
- <Tooltip
- className="z-[100] max-w-sm"
- content={
- getModifiedByName(actor.actorType, actor.name) +
- (!actor.membershipId && actor.actorId ? " (Removed from project)" : "")
- }
- >
- {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions */}
- <div
- onClick={
- actor.membershipId
- ? () =>
- onModifyHistoryClick(
- actor.actorId,
- actor.actorType,
- actor.membershipId,
- actor.groupId,
- actor.name
- )
- : undefined
- }
- className={actor.membershipId ? "cursor-pointer" : undefined}
- >
- <FontAwesomeIcon
- icon={getModifiedByIcon(actor.actorType)}
- className="ml-2"
- />
- {!actor.membershipId &&
- actor.actorType &&
- [ActorType.USER, ActorType.IDENTITY].includes(
- actor.actorType as ActorType
- ) && <FontAwesomeIcon className="ml-1 text-mineshaft-400" icon={faBan} />}
- </div>
- </Tooltip>
- </div>
- </div>
- )}
- <div className="flex flex-row">
- <div className="h-min w-fit rounded-xs bg-primary-500/10 px-1 text-primary-300/70">
- Value:
- </div>
- {!isRedacted ? (
- <div className="group pl-1 font-mono break-all">
- <div className="relative hidden cursor-pointer transition-all duration-200 group-[.show-value]:inline">
- <button
- type="button"
- className="text-left select-none"
- onClick={async (e) => {
- if (secretValueHidden) return;
-
- await handleCopyValue(e);
- }}
- onKeyDown={async (e) => {
- if (secretValueHidden) return;
-
- if (e.key === "Enter" || e.key === " ") {
- await handleCopyValue(e);
- }
- }}
- >
- <span
- className={twMerge(
- secretValueHidden && "text-xs text-bunker-300 opacity-40"
- )}
- >
- {/* eslint-disable-next-line no-nested-ternary */}
- {secretValueHidden
- ? "Hidden"
- : isFetchingValue
- ? "****"
- : ((secretValue || (
- <span className="text-mineshaft-400">EMPTY</span>
- )) ??
- "Error fetching secret value...")}
- </span>
- </button>
- <button
- type="button"
- className="ml-1 cursor-pointer"
- onClick={(e) => {
- e.stopPropagation();
- e.currentTarget.closest(".group")?.classList.remove("show-value");
- }}
- onKeyDown={(e) => {
- if (e.key === "Enter" || e.key === " ") {
- e.stopPropagation();
- e.currentTarget.closest(".group")?.classList.remove("show-value");
- }
- }}
- >
- <FontAwesomeIcon icon={faEyeSlash} />
- </button>
- </div>
- <span className="group-[.show-value]:hidden">
- ****
- <button
- type="button"
- className="ml-1 cursor-pointer"
- onClick={async (e) => {
- e.currentTarget.closest(".group")?.classList.add("show-value");
- await handleGetSecretValue();
- }}
- onKeyDown={async (e) => {
- if (e.key === "Enter" || e.key === " ") {
- e.currentTarget.closest(".group")?.classList.add("show-value");
- await handleGetSecretValue();
- }
- }}
- >
- <FontAwesomeIcon icon={faEye} />
- </button>
- </span>
- </div>
- ) : (
- <div className="flex items-center justify-center pl-1 font-mono break-all">
- <div className="relative transition-all duration-200">
- <Tooltip
- className="z-[100] max-w-sm"
- content={
- <div>
- <div className="flex items-center gap-2 text-red-500/70">
- <span className="text-xs">Redacted</span>
- <FontAwesomeIcon icon={faLock} />
- </div>
-
- <div className="text-xs text-bunker-300">
- Redacted by{" "}
- <b>
- {!redactedByActor?.projectMembershipId
- ? `${redactedByActor?.username} (Removed from project)`
- : redactedByActor.username ||
- redactedByActor.email ||
- "Unknown User"}
- </b>{" "}
- {redactedAt && (
- <span className="text-xs">
- on {format(new Date(redactedAt || ""), "Pp")}
- </span>
- )}
- </div>
- </div>
- }
- >
- <div className="flex gap-2">
- <span className="text-xs text-red-500/70">Redacted</span>
- <FontAwesomeIcon icon={faLock} />
- </div>
- </Tooltip>
- </div>
- </div>
- )}
- </div>
- </div>
- </div>
- </div>
- <div className="flex items-center gap-2">
- {!secret?.isRotatedSecret && !secret?.isHoneyTokenSecret && canReadValue && (
- <div
- className={`flex items-center justify-center ${version === currentVersion ? "hidden" : ""}`}
- >
- <Tooltip content="Restore Secret Value">
- <IconButton
- ariaLabel="Restore"
- variant="outline_bg"
- size="sm"
- className="h-8 w-8 rounded-md"
- onClick={async () => {
- if (secretValue) {
- onRevert(secretValue);
- return;
- }
-
- const value = await handleGetSecretValue();
-
- onRevert(value);
- }}
- >
- <FontAwesomeIcon icon={faArrowRotateRight} />
- </IconButton>
- </Tooltip>
- </div>
- )}
-
- {!secret?.isRotatedSecret &&
- !secret?.isHoneyTokenSecret &&
- canEditSecret &&
- !isRedacted && (
- <div
- className={`flex items-center justify-center ${version === currentVersion ? "hidden" : ""}`}
- >
- <Tooltip content="Redact Secret Value">
- <IconButton
- ariaLabel="Redact"
- variant="outline_bg"
- size="sm"
- className="h-8 w-8 rounded-md"
- onClick={() => handlePopUpOpen("redactSecretValue")}
- >
- <FontAwesomeIcon icon={faTrash} />
- </IconButton>
- </Tooltip>
- </div>
- )}
- </div>
- </div>
- </>
- );
-};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/index.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/index.tsx
deleted file mode 100644
index e9e1f1fddc..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/index.tsx
+++ /dev/null
@@ -1,2 +0,0 @@
-export { SecretListView } from "./SecretListView";
-export { SecretNoAccessListView } from "./SecretNoAccessListView";
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretRotationListView/SecretRotationItem.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretRotationListView/SecretRotationItem.tsx
deleted file mode 100644
index 2a5ede3861..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretRotationListView/SecretRotationItem.tsx
+++ /dev/null
@@ -1,334 +0,0 @@
-import { useState } from "react";
-import { subject } from "@casl/ability";
-import {
- faAsterisk,
- faEdit,
- faHandshake,
- faInfoCircle,
- faKey,
- faRotate,
- faTrash
-} from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import { AnimatePresence, motion } from "framer-motion";
-import { twMerge } from "tailwind-merge";
-
-import { ProjectPermissionCan } from "@app/components/permissions";
-import { SecretRotationV2StatusBadge } from "@app/components/secret-rotations-v2/SecretRotationV2StatusBadge";
-import { IconButton, Modal, ModalContent, TableContainer, Tag, Tooltip } from "@app/components/v2";
-import { ProjectPermissionSub } from "@app/context";
-import { ProjectPermissionSecretRotationActions } from "@app/context/ProjectPermissionContext/types";
-import { SECRET_ROTATION_MAP } from "@app/helpers/secretRotationsV2";
-import { UsedBySecretSyncs } from "@app/hooks/api/dashboard/types";
-import { SecretRotation, TSecretRotationV2 } from "@app/hooks/api/secretRotationsV2";
-import { HpIloRotationMethod } from "@app/hooks/api/secretRotationsV2/types/hp-ilo-rotation";
-import { UnixLinuxLocalAccountRotationMethod } from "@app/hooks/api/secretRotationsV2/types/unix-linux-local-account-rotation";
-import { WindowsLocalAccountRotationMethod } from "@app/hooks/api/secretRotationsV2/types/windows-local-account-rotation";
-import { SecretV3RawSanitized, WsTag } from "@app/hooks/api/types";
-
-import { SecretListView } from "../SecretListView";
-import { SecretRotationSecretRow } from "./SecretRotationSecretRow";
-
-type Props = {
- secretRotation: TSecretRotationV2;
- onEdit: () => void;
- onRotate: () => void;
- onReconcile: () => void;
- onViewGeneratedCredentials: () => void;
- onDelete: () => void;
- projectId: string;
- secretPath?: string;
- tags?: WsTag[];
- isProtectedBranch?: boolean;
- usedBySecretSyncs?: UsedBySecretSyncs[];
- importedBy?: {
- environment: { name: string; slug: string };
- folders: {
- name: string;
- secrets?: { secretId: string; referencedSecretKey: string; referencedSecretEnv: string }[];
- isImported: boolean;
- }[];
- }[];
- colWidth: number;
- getMergedSecretsWithPending: (
- paramSecrets?: (SecretV3RawSanitized | null)[]
- ) => SecretV3RawSanitized[];
-};
-
-export const SecretRotationItem = ({
- secretRotation,
- onEdit,
- onRotate,
- onReconcile,
- onViewGeneratedCredentials,
- onDelete,
- projectId,
- secretPath = "/",
- tags = [],
- isProtectedBranch = false,
- usedBySecretSyncs,
- importedBy,
- colWidth,
- getMergedSecretsWithPending
-}: Props) => {
- const { name, type, environment, folder, secrets, description } = secretRotation;
-
- const { name: rotationType, image } = SECRET_ROTATION_MAP[type];
- const [showSecrets, setShowSecrets] = useState(false);
- const [isExpanded, setIsExpanded] = useState(true);
-
- const showReconcileButton =
- (secretRotation.type === SecretRotation.UnixLinuxLocalAccount &&
- secretRotation.parameters.rotationMethod ===
- UnixLinuxLocalAccountRotationMethod.LoginAsTarget) ||
- (secretRotation.type === SecretRotation.WindowsLocalAccount &&
- secretRotation.parameters.rotationMethod ===
- WindowsLocalAccountRotationMethod.LoginAsTarget) ||
- (secretRotation.type === SecretRotation.HpIloLocalAccount &&
- secretRotation.parameters.rotationMethod === HpIloRotationMethod.LoginAsTarget);
-
- return (
- <>
- <div
- className={twMerge(
- "group flex cursor-pointer border-b border-mineshaft-600 hover:bg-mineshaft-700"
- )}
- onClick={() => setIsExpanded(!isExpanded)}
- onKeyDown={(e) => {
- if (e.key === "Enter" || e.key === " ") {
- e.preventDefault();
- setIsExpanded(!isExpanded);
- }
- }}
- role="button"
- tabIndex={0}
- aria-expanded={isExpanded}
- aria-label={`${isExpanded ? "Collapse" : "Expand"} rotation secrets for ${name}`}
- >
- <div className="text- flex w-11 items-center py-2 pl-5 text-mineshaft-400">
- <FontAwesomeIcon icon={faRotate} />
- </div>
- <div className="flex grow items-center py-2 pr-2 pl-4">
- <div className="flex w-full flex-wrap items-center">
- <span>{name}</span>
- <Tag className="mx-2.5 flex items-center gap-1 px-1.5 py-0 text-xs normal-case">
- <img
- src={`/images/integrations/${image}`}
- style={{
- width: "11px"
- }}
- alt={`${rotationType} logo`}
- />
- {rotationType}
- </Tag>
- {description && (
- <Tooltip content={description}>
- <FontAwesomeIcon icon={faInfoCircle} className="text-mineshaft-400" />
- </Tooltip>
- )}
- </div>
- <SecretRotationV2StatusBadge secretRotation={secretRotation} />
- <div
- key="actions"
- className="ml-2 flex h-full shrink-0 self-start transition-all group-hover:gap-x-2"
- >
- <Tooltip content="View Rotation Secrets">
- <IconButton
- ariaLabel="View rotation secrets"
- variant="plain"
- size="sm"
- className="w-0 overflow-hidden p-0 group-hover:w-5"
- onClick={(e) => {
- e.stopPropagation();
- setShowSecrets(true);
- }}
- >
- <FontAwesomeIcon icon={faKey} />
- </IconButton>
- </Tooltip>
- <ProjectPermissionCan
- I={ProjectPermissionSecretRotationActions.ReadGeneratedCredentials}
- a={subject(ProjectPermissionSub.SecretRotation, {
- environment: environment.slug,
- secretPath: folder.path,
- ...(secretRotation.connectionId && { connectionId: secretRotation.connectionId })
- })}
- renderTooltip
- allowedLabel="View Generated Credentials"
- >
- {(isAllowed) => (
- <IconButton
- ariaLabel="View generated credentials"
- variant="plain"
- size="sm"
- isDisabled={!isAllowed}
- className="w-0 overflow-hidden p-0 group-hover:w-5"
- onClick={(e) => {
- e.stopPropagation();
- onViewGeneratedCredentials();
- }}
- >
- <FontAwesomeIcon icon={faAsterisk} />
- </IconButton>
- )}
- </ProjectPermissionCan>
- <ProjectPermissionCan
- I={ProjectPermissionSecretRotationActions.RotateSecrets}
- a={subject(ProjectPermissionSub.SecretRotation, {
- environment: environment.slug,
- secretPath: folder.path,
- ...(secretRotation.connectionId && { connectionId: secretRotation.connectionId })
- })}
- renderTooltip
- allowedLabel="Rotate Secrets"
- >
- {(isAllowed) => (
- <IconButton
- ariaLabel="Rotate secrets"
- variant="plain"
- size="sm"
- isDisabled={!isAllowed}
- className="w-0 overflow-hidden p-0 group-hover:w-5"
- onClick={(e) => {
- e.stopPropagation();
- onRotate();
- }}
- >
- <FontAwesomeIcon icon={faRotate} />
- </IconButton>
- )}
- </ProjectPermissionCan>
- {showReconcileButton && (
- <ProjectPermissionCan
- I={ProjectPermissionSecretRotationActions.RotateSecrets}
- a={subject(ProjectPermissionSub.SecretRotation, {
- environment: environment.slug,
- secretPath: folder.path,
- ...(secretRotation.connectionId && { connectionId: secretRotation.connectionId })
- })}
- renderTooltip
- allowedLabel="Reconcile Secret"
- >
- {(isAllowed) => (
- <IconButton
- ariaLabel="Reconcile secret"
- variant="plain"
- size="sm"
- isDisabled={!isAllowed}
- className="w-0 overflow-hidden p-0 group-hover:w-5"
- onClick={(e) => {
- e.stopPropagation();
- onReconcile();
- }}
- >
- <FontAwesomeIcon icon={faHandshake} />
- </IconButton>
- )}
- </ProjectPermissionCan>
- )}
- </div>
- </div>
- <AnimatePresence mode="wait">
- <motion.div
- key="options"
- className="flex w-16 items-center justify-between border-l border-mineshaft-600 px-2 py-3"
- initial={{ x: 0, opacity: 0 }}
- animate={{ x: 0, opacity: 1 }}
- exit={{ x: 10, opacity: 0 }}
- >
- <ProjectPermissionCan
- I={ProjectPermissionSecretRotationActions.Edit}
- a={subject(ProjectPermissionSub.SecretRotation, {
- environment: environment.slug,
- secretPath: folder.path,
- ...(secretRotation.connectionId && { connectionId: secretRotation.connectionId })
- })}
- renderTooltip
- allowedLabel="Edit"
- >
- {(isAllowed) => (
- <IconButton
- ariaLabel="Edit rotation"
- variant="plain"
- isDisabled={!isAllowed}
- className="opacity-0 group-hover:opacity-100"
- onClick={(e) => {
- e.stopPropagation();
- onEdit();
- }}
- >
- <FontAwesomeIcon icon={faEdit} />
- </IconButton>
- )}
- </ProjectPermissionCan>
- <ProjectPermissionCan
- I={ProjectPermissionSecretRotationActions.Delete}
- a={subject(ProjectPermissionSub.SecretRotation, {
- environment: environment.slug,
- secretPath: folder.path,
- ...(secretRotation.connectionId && { connectionId: secretRotation.connectionId })
- })}
- renderTooltip
- allowedLabel="Delete"
- >
- {(isAllowed) => (
- <IconButton
- ariaLabel="Delete rotation"
- variant="plain"
- colorSchema="danger"
- className="opacity-0 group-hover:opacity-100"
- onClick={(e) => {
- e.stopPropagation();
- onDelete();
- }}
- isDisabled={!isAllowed}
- >
- <FontAwesomeIcon icon={faTrash} />
- </IconButton>
- )}
- </ProjectPermissionCan>
- </motion.div>
- </AnimatePresence>
- </div>
- {isExpanded && (
- <SecretListView
- colWidth={colWidth}
- secrets={getMergedSecretsWithPending(secretRotation.secrets) || []}
- tags={tags}
- environment={environment.slug}
- projectId={projectId}
- secretPath={secretPath}
- isProtectedBranch={isProtectedBranch}
- importedBy={importedBy}
- usedBySecretSyncs={usedBySecretSyncs}
- excludePendingCreates
- />
- )}
- <Modal onOpenChange={setShowSecrets} isOpen={showSecrets}>
- <ModalContent
- onOpenAutoFocus={(e) => e.preventDefault()}
- className="max-w-3xl"
- title="Rotation Secrets"
- >
- <TableContainer>
- <table className="secret-table">
- <tbody>
- {secrets.map((secret, index) => {
- return (
- <SecretRotationSecretRow
- // eslint-disable-next-line react/no-array-index-key
- key={`rotation-secret-${secretRotation.id}-${index}`}
- secret={secret}
- environment={secretRotation.environment.slug}
- secretPath={secretRotation.folder.path}
- />
- );
- })}
- </tbody>
- </table>
- </TableContainer>
- </ModalContent>
- </Modal>
- </>
- );
-};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretRotationListView/SecretRotationListView.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretRotationListView/SecretRotationListView.tsx
deleted file mode 100644
index beae124eaf..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretRotationListView/SecretRotationListView.tsx
+++ /dev/null
@@ -1,111 +0,0 @@
-import { DeleteSecretRotationV2Modal } from "@app/components/secret-rotations-v2/DeleteSecretRotationV2Modal";
-import { EditSecretRotationV2Modal } from "@app/components/secret-rotations-v2/EditSecretRotationV2Modal";
-import { ReconcileLocalAccountRotationModal } from "@app/components/secret-rotations-v2/ReconcileLocalAccountRotationModal";
-import { RotateSecretRotationV2Modal } from "@app/components/secret-rotations-v2/RotateSecretRotationV2Modal";
-import { ViewSecretRotationV2GeneratedCredentialsModal } from "@app/components/secret-rotations-v2/ViewSecretRotationV2GeneratedCredentials";
-import { usePopUp } from "@app/hooks";
-import { UsedBySecretSyncs } from "@app/hooks/api/dashboard/types";
-import { SecretRotation, TSecretRotationV2 } from "@app/hooks/api/secretRotationsV2";
-import { SecretV3RawSanitized, WsTag } from "@app/hooks/api/types";
-
-import { SecretRotationItem } from "./SecretRotationItem";
-
-type Props = {
- secretRotations?: TSecretRotationV2[];
- projectId: string;
- secretPath?: string;
- tags?: WsTag[];
- isProtectedBranch?: boolean;
- usedBySecretSyncs?: UsedBySecretSyncs[];
- importedBy?: {
- environment: { name: string; slug: string };
- folders: {
- name: string;
- secrets?: { secretId: string; referencedSecretKey: string; referencedSecretEnv: string }[];
- isImported: boolean;
- }[];
- }[];
- colWidth: number;
- getMergedSecretsWithPending: (
- secretParams?: (SecretV3RawSanitized | null)[]
- ) => SecretV3RawSanitized[];
-};
-
-export const SecretRotationListView = ({
- secretRotations,
- projectId,
- secretPath = "/",
- tags = [],
- isProtectedBranch = false,
- usedBySecretSyncs,
- importedBy,
- colWidth,
- getMergedSecretsWithPending
-}: Props) => {
- const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp([
- "editSecretRotation",
- "rotateSecretRotation",
- "viewSecretRotationGeneratedCredentials",
- "deleteSecretRotation",
- "reconcileSecretRotation"
- ] as const);
-
- return (
- <>
- {secretRotations?.map((secretRotation) => (
- <SecretRotationItem
- key={secretRotation.id}
- secretRotation={secretRotation}
- onEdit={() => handlePopUpOpen("editSecretRotation", secretRotation)}
- onRotate={() => handlePopUpOpen("rotateSecretRotation", secretRotation)}
- onReconcile={() => handlePopUpOpen("reconcileSecretRotation", secretRotation)}
- onViewGeneratedCredentials={() =>
- handlePopUpOpen("viewSecretRotationGeneratedCredentials", secretRotation)
- }
- onDelete={() => handlePopUpOpen("deleteSecretRotation", secretRotation)}
- colWidth={colWidth}
- tags={tags}
- projectId={projectId}
- secretPath={secretPath}
- isProtectedBranch={isProtectedBranch}
- importedBy={importedBy}
- usedBySecretSyncs={usedBySecretSyncs}
- getMergedSecretsWithPending={getMergedSecretsWithPending}
- />
- ))}
- <EditSecretRotationV2Modal
- isOpen={popUp.editSecretRotation.isOpen}
- secretRotation={popUp.editSecretRotation.data as TSecretRotationV2}
- onOpenChange={(isOpen) => handlePopUpToggle("editSecretRotation", isOpen)}
- />
- <RotateSecretRotationV2Modal
- isOpen={popUp.rotateSecretRotation.isOpen}
- secretRotation={popUp.rotateSecretRotation.data as TSecretRotationV2}
- onOpenChange={(isOpen) => handlePopUpToggle("rotateSecretRotation", isOpen)}
- />
- <ReconcileLocalAccountRotationModal
- isOpen={
- popUp.reconcileSecretRotation.isOpen &&
- (popUp.reconcileSecretRotation.data?.type === SecretRotation.UnixLinuxLocalAccount ||
- popUp.reconcileSecretRotation.data?.type === SecretRotation.WindowsLocalAccount ||
- popUp.reconcileSecretRotation.data?.type === SecretRotation.HpIloLocalAccount)
- }
- secretRotation={popUp.reconcileSecretRotation.data as TSecretRotationV2}
- onOpenChange={(isOpen) => handlePopUpToggle("reconcileSecretRotation", isOpen)}
- />
-
- <ViewSecretRotationV2GeneratedCredentialsModal
- isOpen={popUp.viewSecretRotationGeneratedCredentials.isOpen}
- secretRotation={popUp.viewSecretRotationGeneratedCredentials.data as TSecretRotationV2}
- onOpenChange={(isOpen) =>
- handlePopUpToggle("viewSecretRotationGeneratedCredentials", isOpen)
- }
- />
- <DeleteSecretRotationV2Modal
- isOpen={popUp.deleteSecretRotation.isOpen}
- secretRotation={popUp.deleteSecretRotation.data as TSecretRotationV2}
- onOpenChange={(isOpen) => handlePopUpToggle("deleteSecretRotation", isOpen)}
- />
- </>
- );
-};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretRotationListView/SecretRotationSecretRow.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretRotationListView/SecretRotationSecretRow.tsx
deleted file mode 100644
index 7bc5b87051..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretRotationListView/SecretRotationSecretRow.tsx
+++ /dev/null
@@ -1,76 +0,0 @@
-import { twMerge } from "tailwind-merge";
-
-import { SecretInput, Tooltip } from "@app/components/v2";
-import { Blur } from "@app/components/v2/Blur";
-import { useProject } from "@app/context";
-import { useToggle } from "@app/hooks";
-import { useGetSecretValue } from "@app/hooks/api/dashboard/queries";
-import { TSecretRotationV2 } from "@app/hooks/api/secretRotationsV2";
-import { HIDDEN_SECRET_VALUE } from "@app/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretItem";
-
-interface SecretRotationSecretRowProps {
- secret: TSecretRotationV2["secrets"][number];
- secretPath: string;
- environment: string;
-}
-
-export const SecretRotationSecretRow = ({
- secret,
- environment,
- secretPath
-}: SecretRotationSecretRowProps) => {
- const [isFieldFocused, setIsFieldFocused] = useToggle();
-
- const { currentProject } = useProject();
-
- const { data: secretValue, isPending: isLoadingSecretValue } = useGetSecretValue(
- {
- environment,
- secretPath,
- secretKey: secret?.key ?? "",
- projectId: currentProject.id
- },
- {
- enabled: isFieldFocused && Boolean(secret)
- }
- );
-
- const getValue = () => {
- if (isLoadingSecretValue) return HIDDEN_SECRET_VALUE;
-
- if (!secretValue) return "Error loading secret value";
-
- return secretValue.value || "";
- };
-
- return (
- <Tooltip
- className="max-w-sm"
- content={secret ? undefined : "You do not have permission to view this secret."}
- >
- <tr className="h-full last:border-b-0! hover:bg-mineshaft-700">
- <td className="flex h-full items-center" style={{ padding: "0.5rem 1rem" }}>
- <span className={twMerge(!secret && "blur-sm")}>{secret?.key ?? "********"}</span>
- </td>
- <td className="col-span-2 h-full w-full" style={{ padding: "0.5rem 1rem" }}>
- {/* eslint-disable-next-line no-nested-ternary */}
- {!secret ? (
- <div className="h-full pl-4 blur-sm">********</div>
- ) : secret.secretValueHidden ? (
- <Blur
- className="py-0"
- tooltipText="You do not have permission to read the value of this secret."
- />
- ) : (
- <SecretInput
- isReadOnly
- value={getValue()}
- onFocus={() => setIsFieldFocused.on()}
- onBlur={() => setIsFieldFocused.off()}
- />
- )}
- </td>
- </tr>
- </Tooltip>
- );
-};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretRotationListView/index.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretRotationListView/index.tsx
deleted file mode 100644
index 1421bf4a75..0000000000
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretRotationListView/index.tsx
+++ /dev/null
@@ -1 +0,0 @@
-export { SecretRotationListView } from "./SecretRotationListView";
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/route.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/route.tsx
index df054b6e2f..dfddc33cb5 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/route.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/route.tsx
@@ -1,12 +1,7 @@
-import { createFileRoute, linkOptions, stripSearchParams } from "@tanstack/react-router";
+import { createFileRoute, redirect, stripSearchParams } from "@tanstack/react-router";
import { zodValidator } from "@tanstack/zod-adapter";
import { z } from "zod";
-import { SecretDashboardPathBreadcrumb } from "@app/components/navigation/SecretDashboardPathBreadcrumb";
-import { BreadcrumbTypes } from "@app/components/v2";
-
-import { SecretDashboardPage } from "./SecretDashboardPage";
-
const SecretDashboardPageQueryParamsSchema = z.object({
secretPath: z.string().catch("/"),
search: z.string().catch(""),
@@ -16,10 +11,11 @@ const SecretDashboardPageQueryParamsSchema = z.object({
connectionId: z.string().optional(),
connectionName: z.string().optional()
});
+
+// Preserve legacy bookmarks while routing all secret management back through Overview.
export const Route = createFileRoute(
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/secrets/$envSlug"
)({
- component: SecretDashboardPage,
validateSearch: zodValidator(SecretDashboardPageQueryParamsSchema),
search: {
middlewares: [
@@ -32,46 +28,24 @@ export const Route = createFileRoute(
})
]
},
- beforeLoad: ({ context, params, search }) => {
- const secretPathSegments = search.secretPath.split("/").filter(Boolean);
- return {
- breadcrumbs: [
- ...context.breadcrumbs,
- {
- label: "Secrets",
- link: linkOptions({
- to: "/organizations/$orgId/projects/secret-management/$projectId/overview",
- params
- })
- },
- {
- type: BreadcrumbTypes.Dropdown,
- label: context.project.environments.find((el) => el.slug === params.envSlug)?.name || "",
- dropdownTitle: "Environments",
- links: context.project.environments.map((el) => ({
- label: el.name,
- link: linkOptions({
- to: "/organizations/$orgId/projects/secret-management/$projectId/secrets/$envSlug",
- params: {
- orgId: params.orgId,
- projectId: params.projectId,
- envSlug: el.slug
- }
- })
- }))
- },
- ...secretPathSegments.map((_, index) => ({
- type: BreadcrumbTypes.Component,
- component: () => (
- <SecretDashboardPathBreadcrumb
- secretPathSegments={secretPathSegments}
- selectedPathSegmentIndex={index}
- environmentSlug={params.envSlug}
- projectId={params.projectId}
- />
- )
- }))
- ]
- };
+ beforeLoad: ({ params, search }) => {
+ throw redirect({
+ to: "/organizations/$orgId/projects/secret-management/$projectId/overview",
+ params: {
+ orgId: params.orgId,
+ projectId: params.projectId
+ },
+ search: {
+ secretPath: search.secretPath,
+ search: search.search,
+ tags: search.tags || undefined,
+ filterBy: search.filterBy || undefined,
+ connectionId: search.connectionId,
+ connectionName: search.connectionName,
+ dynamicSecretId: search.dynamicSecretId || undefined,
+ environments: [params.envSlug]
+ },
+ replace: true
+ });
}
});