Skip to content

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

34.0 KB
Raw Blame
import React, { useEffect, useMemo, useState } from "react";
import { subject } from "@casl/ability";
import { useDragOperation } from "@dnd-kit/react";
import { useSortable } from "@dnd-kit/react/sortable";
import {
  BanIcon,
  ChevronRightIcon,
  FolderIcon,
  GripVerticalIcon,
  ImportIcon,
  InfoIcon,
  LayersIcon,
  RefreshCwIcon,
  SearchIcon,
  TrashIcon,
  TriangleAlertIcon
} from "lucide-react";
import { twMerge } from "tailwind-merge";

import { createNotification } from "@app/components/notifications";
import { ProjectPermissionCan } from "@app/components/permissions";
import {
  Badge,
  Empty,
  EmptyDescription,
  EmptyHeader,
  EmptyMedia,
  EmptyTitle,
  IconButton,
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
  Tooltip,
  TooltipContent,
  TooltipTrigger
} from "@app/components/v3";
import { ProjectPermissionActions, ProjectPermissionSub, useProject } from "@app/context";
import { useToggle } from "@app/hooks";
import { useResyncSecretReplication } from "@app/hooks/api";
import { ReservedFolders } from "@app/hooks/api/secretFolders/types";
import { TSecretImport } from "@app/hooks/api/secretImports/types";
import { SecretV3RawSanitized } from "@app/hooks/api/types";

import { ResourceEnvironmentStatusCell } from "../ResourceEnvironmentStatusCell";
import {
  TABLE_ROW_ACTION_BAR_CLASS_NAME,
  TABLE_ROW_ACTION_BAR_VISIBLE_CLASS_NAME,
  TABLE_ROW_ACTION_BUTTON_CLASS_NAME,
  TABLE_ROW_ACTION_BUTTON_VISIBLE_CLASS_NAME,
  TABLE_ROW_ACTIVE_FILTER_CLASS_NAME,
  TABLE_ROW_EXPAND_ICON_CLASS_NAME,
  TABLE_ROW_EXPAND_ICON_TRANSITION_CLASS_NAME,
  TABLE_ROW_EXPANDED_ICON_CLASS_NAME,
  TABLE_ROW_NAME_HEADER_COLUMN_CLASS_NAME,
  TABLE_ROW_RESOURCE_ICON_CLASS_NAME
} from "../tableRowActionStyles";
import type { TableRowActivityChangeHandler, TableRowActivityId } from "../tableRowActivity";
import { SecretImportSecretRow } from "./SecretImportSecretRow";

type ImportedSecretData = {
  environment: string;
  secretPath: string;
  sourceEnv: string;
  secrets: Pick<SecretV3RawSanitized, "id" | "key" | "env" | "isEmpty" | "version">[];
};

type Props = {
  importEnvSlug: string;
  importEnvName: string;
  importPath: string;
  environments: { name: string; slug: string }[];
  isSecretImportInEnv: (importEnvSlug: string, importPath: string, env: string) => boolean;
  getSecretImportByEnv: (
    importEnvSlug: string,
    importPath: string,
    env: string
  ) => TSecretImport | undefined;
  secretPath: string;
  searchFilter: string;
  onDelete: (secretImport: TSecretImport) => void;
  importedSecrets: ImportedSecretData[];
  index: number;
  secretImport?: TSecretImport;
  isVisible?: boolean;
  activityId: TableRowActivityId;
  onActivityChange: TableRowActivityChangeHandler;
};

export const SecretImportTableRow = ({
  importEnvSlug,
  importEnvName,
  importPath,
  environments = [],
  isSecretImportInEnv,
  getSecretImportByEnv,
  secretPath,
  searchFilter,
  onDelete,
  importedSecrets,
  index,
  secretImport,
  isVisible,
  activityId,
  onActivityChange
}: Props) => {
  const [isExpanded, setIsExpanded] = useToggle(false);
  const [selectedReplicationEnv, setSelectedReplicationEnv] = useState<string>("");
  const { currentProject } = useProject();
  const resyncSecretReplication = useResyncSecretReplication();

  const isSingleEnvView = environments.length === 1;
  const totalCols = environments.length + 2;

  const singleEnvSlug = isSingleEnvView ? environments[0].slug : "";
  const singleEnvImport = isSingleEnvView
    ? (secretImport ?? getSecretImportByEnv(importEnvSlug, importPath, singleEnvSlug))
    : undefined;

  const isAccessRevoked = isSingleEnvView
    ? (singleEnvImport?.isAccessRevoked ?? false)
    : (secretImport?.isAccessRevoked ?? false);

  const {
    ref: sortableRef,
    handleRef,
    isDragging
  } = useSortable({
    id: singleEnvImport?.id ?? "",
    index,
    disabled: !isSingleEnvView
  });

  const { source: dragSource } = useDragOperation();
  const isAnyDragging = dragSource != null;

  const allEnvImportedSecrets = useMemo(() => {
    if (isSingleEnvView) {
      const match = importedSecrets?.find(
        (imp) =>
          imp.environment === importEnvSlug &&
          imp.secretPath === importPath &&
          imp.sourceEnv === singleEnvSlug
      );
      return match ? [match] : [];
    }
    return (
      importedSecrets?.filter(
        (imp) => imp.environment === importEnvSlug && imp.secretPath === importPath
      ) ?? []
    );
  }, [importedSecrets, importEnvSlug, importPath, isSingleEnvView, singleEnvSlug]);

  // Union of unique secret keys across all environments (preserves search/expand behavior)
  const matchingImportedSecrets = useMemo(() => {
    if (allEnvImportedSecrets.length === 0) return [];
    if (isSingleEnvView) return allEnvImportedSecrets[0]?.secrets ?? [];
    const keySet = new Set<string>();
    return allEnvImportedSecrets.flatMap((envData) =>
      envData.secrets.filter((secret) => {
        if (keySet.has(secret.key)) return false;
        keySet.add(secret.key);
        return true;
      })
    );
  }, [allEnvImportedSecrets, isSingleEnvView]);

  // Per-environment secret key sets for multi-env discrepancy detection
  const secretKeysByEnv = useMemo(() => {
    if (isSingleEnvView) return new Map<string, Set<string>>();
    return new Map(
      allEnvImportedSecrets.map((envData) => [
        envData.sourceEnv,
        new Set(envData.secrets.map((s) => s.key))
      ])
    );
  }, [allEnvImportedSecrets, isSingleEnvView]);

  const filteredImportedSecrets = useMemo(() => {
    if (!searchFilter) return matchingImportedSecrets;
    return matchingImportedSecrets.filter((secret) =>
      secret.key.toUpperCase().includes(searchFilter.toUpperCase())
    );
  }, [matchingImportedSecrets, searchFilter]);

  const hasAnyReplicatedImport = useMemo(() => {
    if (isSingleEnvView) return false;
    return environments.some((env) => {
      if (!isSecretImportInEnv(importEnvSlug, importPath, env.slug)) return false;
      const imp = getSecretImportByEnv(importEnvSlug, importPath, env.slug);
      return imp?.isReplication === true;
    });
  }, [
    environments,
    isSingleEnvView,
    importEnvSlug,
    importPath,
    isSecretImportInEnv,
    getSecretImportByEnv
  ]);

  const envsWithImport = useMemo(() => {
    if (isSingleEnvView) return [];
    return environments.filter((env) => isSecretImportInEnv(importEnvSlug, importPath, env.slug));
  }, [environments, isSingleEnvView, importEnvSlug, importPath, isSecretImportInEnv]);

  const effectiveSelectedEnv = useMemo(() => {
    if (!hasAnyReplicatedImport || envsWithImport.length === 0) return "";
    if (selectedReplicationEnv && envsWithImport.some((e) => e.slug === selectedReplicationEnv)) {
      return selectedReplicationEnv;
    }
    return envsWithImport[0].slug;
  }, [hasAnyReplicatedImport, envsWithImport, selectedReplicationEnv]);

  const selectedEnvImportData = useMemo(() => {
    if (!hasAnyReplicatedImport || !effectiveSelectedEnv) return null;
    const envImportedSecrets = allEnvImportedSecrets.find(
      (imp) => imp.sourceEnv === effectiveSelectedEnv
    );
    const secretImportRecord = getSecretImportByEnv(
      importEnvSlug,
      importPath,
      effectiveSelectedEnv
    );
    return { envImportedSecrets, secretImportRecord };
  }, [
    hasAnyReplicatedImport,
    effectiveSelectedEnv,
    allEnvImportedSecrets,
    getSecretImportByEnv,
    importEnvSlug,
    importPath
  ]);

  const selectedEnvSecrets = useMemo(() => {
    if (!selectedEnvImportData?.envImportedSecrets) return [];
    const { secrets } = selectedEnvImportData.envImportedSecrets;
    if (!searchFilter) return secrets;
    return secrets.filter((secret) =>
      secret.key.toUpperCase().includes(searchFilter.toUpperCase())
    );
  }, [selectedEnvImportData, searchFilter]);

  useEffect(() => {
    if (searchFilter) {
      if (filteredImportedSecrets.length > 0) {
        setIsExpanded.on();
      } else {
        setIsExpanded.off();
      }
    }
  }, [searchFilter, filteredImportedSecrets.length]);

  useEffect(() => {
    onActivityChange(activityId, isExpanded);
  }, [activityId, isExpanded, onActivityChange]);

  useEffect(
    () => () => {
      onActivityChange(activityId, false);
    },
    [activityId, onActivityChange]
  );

  useEffect(() => {
    if (
      hasAnyReplicatedImport &&
      selectedReplicationEnv &&
      !envsWithImport.some((e) => e.slug === selectedReplicationEnv)
    ) {
      setSelectedReplicationEnv("");
    }
  }, [hasAnyReplicatedImport, envsWithImport, selectedReplicationEnv]);

  const handleResyncSecretReplication = async (importItem: TSecretImport, envSlug: string) => {
    if (resyncSecretReplication.isPending) return;
    await resyncSecretReplication.mutateAsync({
      id: importItem.id,
      environment: envSlug,
      path: secretPath,
      projectId: currentProject?.id || ""
    });
    createNotification({
      text: "Please refresh the dashboard to view changes",
      type: "success"
    });
  };

  const handleRowClick = () => {
    setIsExpanded.toggle();
  };

  const renderLeadingIcon = () => {
    if (isSingleEnvView) {
      return (
        <>
          <button
            type="button"
            ref={handleRef}
            aria-label={`${isExpanded ? "Collapse" : "Expand"} secret import ${importPath}`}
            aria-expanded={isExpanded}
            title="Drag to reorder; click to expand or collapse"
            className={twMerge(
              "absolute inset-0 flex cursor-grab items-center justify-center text-muted transition-opacity duration-75 active:cursor-grabbing motion-reduce:transition-none",
              isExpanded
                ? "opacity-100"
                : "opacity-100 [@media(hover:hover)]:pointer-events-none [@media(hover:hover)]:opacity-0 [@media(hover:hover)]:group-focus-within:pointer-events-auto [@media(hover:hover)]:group-focus-within:opacity-100 [@media(hover:hover)]:group-hover:pointer-events-auto [@media(hover:hover)]:group-hover:opacity-100"
            )}
            onClick={(event) => {
              event.stopPropagation();
              handleRowClick();
            }}
          >
            <ChevronRightIcon
              className={twMerge(
                "size-4 [@media(hover:hover)]:group-hover/import-handle:hidden",
                TABLE_ROW_EXPAND_ICON_TRANSITION_CLASS_NAME,
                isExpanded && TABLE_ROW_EXPANDED_ICON_CLASS_NAME
              )}
            />
            <GripVerticalIcon className="hidden size-4 [@media(hover:hover)]:group-hover/import-handle:block" />
          </button>
          {!isExpanded && (
            <ImportIcon className={twMerge("text-import", TABLE_ROW_RESOURCE_ICON_CLASS_NAME)} />
          )}
        </>
      );
    }

    return (
      <>
        <ImportIcon
          className={twMerge(
            "text-import",
            !isExpanded && TABLE_ROW_RESOURCE_ICON_CLASS_NAME,
            isExpanded && "hidden"
          )}
        />
        <ChevronRightIcon
          className={
            isExpanded ? TABLE_ROW_EXPANDED_ICON_CLASS_NAME : TABLE_ROW_EXPAND_ICON_CLASS_NAME
          }
        />
      </>
    );
  };

  const renderReplicationStatus = (importItem: TSecretImport, envSlug: string) => {
    return (
      <>
        {importItem.lastReplicated && (
          <Tooltip>
            <TooltipTrigger>
              {/* eslint-disable-next-line no-nested-ternary */}
              {!isSingleEnvView ? (
                importItem.isReplicationSuccess ? (
                  <InfoIcon className="text-accent" />
                ) : (
                  <TriangleAlertIcon className="text-danger" />
                )
              ) : (
                <div
                  className={twMerge(
                    "flex w-7 justify-center opacity-100",
                    !importItem.isReplicationSuccess && "text-danger"
                  )}
                >
                  {importItem.isReplicationSuccess ? (
                    <InfoIcon className="size-4 text-accent" />
                  ) : (
                    <TriangleAlertIcon className="size-4" />
                  )}
                </div>
              )}
            </TooltipTrigger>
            <TooltipContent className="max-w-xs">
              <div className="flex flex-col gap-1">
                <div className="flex items-center gap-1.5">
                  <InfoIcon className="size-3" />
                  <span className="text-sm">Last Replication</span>
                </div>
                <span className="pl-4 text-xs text-foreground/50">
                  {new Date(importItem.lastReplicated).toLocaleString()}
                </span>
                {!importItem.isReplicationSuccess && (
                  <>
                    <div className="mt-1 flex items-center gap-1.5">
                      <TriangleAlertIcon className="size-3" />
                      <span className="text-sm">Fail reason</span>
                    </div>
                    <span className="pl-4 text-xs text-muted">{importItem.replicationStatus}</span>
                  </>
                )}
              </div>
            </TooltipContent>
          </Tooltip>
        )}
        {isSingleEnvView && importItem.isReplication && (
          <ProjectPermissionCan
            I={ProjectPermissionActions.Edit}
            a={subject(ProjectPermissionSub.SecretImports, {
              environment: envSlug,
              secretPath: secretPath || "/"
            })}
            renderTooltip
            allowedLabel="Resync replicated secrets"
          >
            {(isAllowed) => (
              <Tooltip>
                <TooltipTrigger>
                  <IconButton
                    aria-label="Resync secret import"
                    variant="ghost"
                    size="xs"
                    className={twMerge(
                      TABLE_ROW_ACTION_BUTTON_CLASS_NAME,
                      resyncSecretReplication.isPending &&
                        `${TABLE_ROW_ACTION_BUTTON_VISIBLE_CLASS_NAME} animate-spin`
                    )}
                    isDisabled={!isAllowed}
                    onClick={(e) => {
                      e.stopPropagation();
                      handleResyncSecretReplication(importItem, envSlug);
                    }}
                  >
                    <RefreshCwIcon />
                  </IconButton>
                </TooltipTrigger>
                <TooltipContent>Resync</TooltipContent>
              </Tooltip>
            )}
          </ProjectPermissionCan>
        )}
      </>
    );
  };

  const renderSingleEnvActions = () => {
    if (!singleEnvImport) return null;

    return (
      <div
        className={twMerge(
          "flex items-center rounded-md border border-border bg-container-hover px-0.5 py-0.5 shadow-md",
          TABLE_ROW_ACTION_BAR_CLASS_NAME,
          resyncSecretReplication.isPending && TABLE_ROW_ACTION_BAR_VISIBLE_CLASS_NAME
        )}
      >
        {singleEnvImport.isReplication && (
          <ProjectPermissionCan
            I={ProjectPermissionActions.Edit}
            a={subject(ProjectPermissionSub.SecretImports, {
              environment: singleEnvSlug,
              secretPath: secretPath || "/"
            })}
            renderTooltip
            allowedLabel="Resync replicated secrets"
          >
            {(isAllowed) => (
              <Tooltip>
                <TooltipTrigger>
                  <IconButton
                    aria-label="Resync secret import"
                    variant="ghost"
                    size="xs"
                    className={twMerge(
                      TABLE_ROW_ACTION_BUTTON_CLASS_NAME,
                      resyncSecretReplication.isPending &&
                        `${TABLE_ROW_ACTION_BUTTON_VISIBLE_CLASS_NAME} animate-spin`
                    )}
                    isDisabled={!isAllowed}
                    onClick={(e) => {
                      e.stopPropagation();
                      handleResyncSecretReplication(singleEnvImport, singleEnvSlug);
                    }}
                  >
                    <RefreshCwIcon />
                  </IconButton>
                </TooltipTrigger>
                <TooltipContent>Resync</TooltipContent>
              </Tooltip>
            )}
          </ProjectPermissionCan>
        )}
        <ProjectPermissionCan
          I={ProjectPermissionActions.Delete}
          a={subject(ProjectPermissionSub.SecretImports, {
            environment: singleEnvSlug,
            secretPath: secretPath || "/"
          })}
          renderTooltip
          allowedLabel="Delete"
        >
          {(isAllowed) => (
            <Tooltip>
              <TooltipTrigger>
                <IconButton
                  aria-label="Delete secret import"
                  variant="ghost"
                  size="xs"
                  className={twMerge(TABLE_ROW_ACTION_BUTTON_CLASS_NAME, "hover:text-danger")}
                  isDisabled={!isAllowed}
                  onClick={(e) => {
                    e.stopPropagation();
                    onDelete(singleEnvImport);
                  }}
                >
                  <TrashIcon />
                </IconButton>
              </TooltipTrigger>
              <TooltipContent>Delete</TooltipContent>
            </Tooltip>
          )}
        </ProjectPermissionCan>
      </div>
    );
  };

  const renderReplicationEnvSelector = () => {
    if (envsWithImport.length <= 1) return null;

    return (
      <div className="flex flex-wrap items-center gap-2 border-b border-border px-3 py-3 pl-11">
        <span className="text-xs text-muted">Viewing secrets for:</span>
        <Select value={effectiveSelectedEnv} onValueChange={setSelectedReplicationEnv}>
          <SelectTrigger size="sm" onClick={(e) => e.stopPropagation()}>
            <SelectValue placeholder="Select environment..." />
          </SelectTrigger>
          <SelectContent position="popper">
            {envsWithImport.map((env) => (
              <SelectItem key={env.slug} value={env.slug}>
                {env.name}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>
    );
  };

  const getImportedSecretPath = (importItem?: TSecretImport | null) => {
    if (importItem?.isReplication) {
      return `${secretPath === "/" ? "" : secretPath}/${ReservedFolders.SecretReplication}${importItem.id}`;
    }

    if (importItem?.importEnv?.projectId !== currentProject?.id) {
      return secretPath;
    }

    return importPath;
  };

  const renderRevokedContent = () => (
    <Empty className="rounded-none bg-transparent shadow-none">
      <EmptyHeader className="gap-1.5">
        <div className="flex items-center gap-2">
          <TriangleAlertIcon className="size-4 shrink-0 text-danger" />
          <EmptyTitle>
            {secretImport?.sourceProjectName
              ? `"${secretImport.sourceProjectName}" revoked access to these secrets.`
              : "Access to these secrets has been revoked."}
          </EmptyTitle>
        </div>
        <EmptyDescription>
          Import can no longer be resolved. Re-request access from the source project or remove this
          import.
        </EmptyDescription>
      </EmptyHeader>
    </Empty>
  );

  const renderMultiEnvExpandedSecrets = () => {
    if (isAccessRevoked) return renderRevokedContent();

    if (hasAnyReplicatedImport) {
      const selectedImport = selectedEnvImportData?.secretImportRecord;

      if (selectedEnvSecrets.length === 0) {
        return (
          <>
            {renderReplicationEnvSelector()}
            <Empty className="rounded-none bg-transparent shadow-none">
              <EmptyHeader>
                <EmptyMedia variant="icon">
                  {searchFilter ? <SearchIcon /> : <ImportIcon />}
                </EmptyMedia>
                <EmptyTitle>
                  {searchFilter ? "No imported secrets match search" : "No imported secrets found"}
                </EmptyTitle>
              </EmptyHeader>
            </Empty>
          </>
        );
      }

      return (
        <>
          {renderReplicationEnvSelector()}
          <Table className="w-full table-fixed" containerClassName="rounded-none border-0">
            <colgroup>
              <col className="w-10" />
              <col className="w-[var(--name-column-width,180px)]" />
              <col />
            </colgroup>
            <TableHeader className="bg-container-hover">
              <TableRow>
                <TableHead aria-hidden="true" className="w-10 max-w-10 min-w-10 p-0" />
                <TableHead className={TABLE_ROW_NAME_HEADER_COLUMN_CLASS_NAME}>Name</TableHead>
                <TableHead>Value</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {selectedEnvSecrets.map((secret) => (
                <SecretImportSecretRow
                  key={`import-secret-multi-${effectiveSelectedEnv}-${secret.key}`}
                  secretKey={secret.key}
                  environment={
                    selectedImport?.isReplication ||
                    selectedImport?.importEnv?.projectId !== currentProject?.id
                      ? effectiveSelectedEnv
                      : importEnvSlug
                  }
                  secretPath={getImportedSecretPath(selectedImport)}
                  isEmpty={secret.isEmpty}
                  isVisible={isVisible}
                />
              ))}
            </TableBody>
          </Table>
        </>
      );
    }

    if (filteredImportedSecrets.length === 0) {
      return (
        <Empty className="rounded-none bg-transparent shadow-none">
          <EmptyHeader>
            <EmptyMedia variant="icon">
              {matchingImportedSecrets.length ? <SearchIcon /> : <ImportIcon />}
            </EmptyMedia>
            <EmptyTitle>
              {matchingImportedSecrets.length
                ? "No imported secrets match search"
                : "No imported secrets found"}
            </EmptyTitle>
          </EmptyHeader>
        </Empty>
      );
    }

    const hasAnyDiscrepancy = filteredImportedSecrets.some((secret) =>
      Array.from(secretKeysByEnv.values()).some((keys) => !keys.has(secret.key))
    );

    return (
      <>
        <Table className="w-full table-fixed" containerClassName="rounded-none border-0">
          <colgroup>
            <col className="w-10" />
            <col className="w-[var(--name-column-width,180px)]" />
            <col />
          </colgroup>
          <TableHeader className="bg-container-hover">
            <TableRow>
              <TableHead aria-hidden="true" className="w-10 max-w-10 min-w-10 p-0" />
              <TableHead className={TABLE_ROW_NAME_HEADER_COLUMN_CLASS_NAME}>Name</TableHead>
              <TableHead>Value</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {filteredImportedSecrets.map((secret) => {
              const missingEnvNames = environments
                .filter(
                  (env) =>
                    secretKeysByEnv.has(env.slug) && !secretKeysByEnv.get(env.slug)!.has(secret.key)
                )
                .map((env) => env.name);

              return (
                <SecretImportSecretRow
                  key={`import-secret-multi-${secret.key}`}
                  secretKey={secret.key}
                  environment={
                    secretImport?.importEnv?.projectId !== currentProject?.id
                      ? environments[0]?.slug || importEnvSlug
                      : importEnvSlug
                  }
                  secretPath={
                    secretImport?.importEnv?.projectId !== currentProject?.id
                      ? secretPath
                      : importPath
                  }
                  isEmpty={secret.isEmpty}
                  missingFromEnvs={missingEnvNames}
                  isVisible={isVisible}
                />
              );
            })}
          </TableBody>
        </Table>
        {hasAnyDiscrepancy && (
          <p className="max-w-full px-3 py-3 pl-11 text-xs text-wrap text-warning">
            <TriangleAlertIcon className="mr-1.5 mb-0.5 inline-block size-3 shrink-0" />
            One or more replicated imports may be out of sync. Secrets marked with a warning
            indicator are not present across all importing environments. Select a single environment
            to view exact import state.
          </p>
        )}
      </>
    );
  };

  const renderExpandedSecrets = (envSlug: string) => {
    if (isAccessRevoked) return renderRevokedContent();

    if (filteredImportedSecrets.length === 0) {
      return (
        <Empty className="rounded-none bg-transparent shadow-none">
          <EmptyHeader>
            <EmptyMedia variant="icon">
              {matchingImportedSecrets.length ? <SearchIcon /> : <ImportIcon />}
            </EmptyMedia>
            <EmptyTitle>
              {matchingImportedSecrets.length
                ? "No imported secrets match search"
                : "No imported secrets found"}
            </EmptyTitle>
          </EmptyHeader>
        </Empty>
      );
    }

    return (
      <Table className="w-full table-fixed" containerClassName="rounded-none border-0">
        <colgroup>
          <col className="w-10" />
          <col className="w-[var(--name-column-width,180px)]" />
          <col />
        </colgroup>
        <TableHeader className="bg-container-hover">
          <TableRow>
            <TableHead aria-hidden="true" className="w-10 max-w-10 min-w-10 p-0" />
            <TableHead className={TABLE_ROW_NAME_HEADER_COLUMN_CLASS_NAME}>Name</TableHead>
            <TableHead>Value</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {filteredImportedSecrets.map((secret) => (
            <SecretImportSecretRow
              key={`import-secret-${envSlug}-${secret.key}`}
              secretKey={secret.key}
              environment={
                singleEnvImport?.isReplication ||
                singleEnvImport?.importEnv?.projectId !== currentProject?.id
                  ? singleEnvSlug
                  : importEnvSlug
              }
              secretPath={getImportedSecretPath(singleEnvImport)}
              isEmpty={secret.isEmpty}
              isVisible={isVisible}
            />
          ))}
        </TableBody>
      </Table>
    );
  };

  return (
    <>
      <TableRow
        ref={isSingleEnvView ? (sortableRef as React.Ref<HTMLTableRowElement>) : undefined}
        onClick={handleRowClick}
        className={twMerge(
          "group hover:z-10",
          isExpanded && TABLE_ROW_ACTIVE_FILTER_CLASS_NAME,
          isDragging && "opacity-50"
        )}
      >
        <TableCell
          className={twMerge(
            "w-10 max-w-10 min-w-10 p-0",
            !isSingleEnvView && "sticky left-0 z-10",
            "bg-container transition-colors duration-75 group-hover:bg-container-hover",
            !isSingleEnvView && isExpanded && "border-b-0 bg-container-hover",
            isSingleEnvView && "group/import-handle relative"
          )}
        >
          <div className="flex h-full items-center justify-center [&>svg]:size-4">
            {renderLeadingIcon()}
          </div>
        </TableCell>
        <TableCell
          className={twMerge(
            !isSingleEnvView && "sticky left-10 z-10 border-r",
            "bg-container transition-colors duration-75 group-hover:bg-container-hover",
            !isSingleEnvView && isExpanded && "border-r-0 border-b-0 bg-container-hover"
          )}
          isTruncatable
          colSpan={isSingleEnvView ? 2 : undefined}
        >
          <div className="relative flex w-full items-center">
            <div className="flex items-center gap-2 overflow-hidden">
              {secretImport?.sourceProjectName &&
                secretImport.importEnv.projectId &&
                secretImport.importEnv.projectId !== currentProject?.id && (
                  <Badge variant="warning">{secretImport.sourceProjectName}</Badge>
                )}
              <Badge variant="neutral">
                <LayersIcon />
                {importEnvName}
              </Badge>
              <FolderIcon className="size-3.5 shrink-0 text-folder" />
              <span className="truncate">{importPath}</span>
            </div>
            {isAccessRevoked && (
              <div
                className={twMerge(
                  "ml-auto flex items-center",
                  isSingleEnvView &&
                    "mr-16 transition-[margin] duration-300 motion-reduce:transition-none [@media(hover:hover)]:mr-0 [@media(hover:hover)]:group-focus-within:mr-16 [@media(hover:hover)]:group-hover:mr-16"
                )}
              >
                <Badge variant="danger">
                  <BanIcon />
                  Secret share revoked
                </Badge>
              </div>
            )}
            {isSingleEnvView &&
              singleEnvImport?.isReplication &&
              singleEnvImport.lastReplicated && (
                <div className="mr-16 ml-auto flex items-center transition-[margin] duration-300 motion-reduce:transition-none [@media(hover:hover)]:mr-0 [@media(hover:hover)]:group-focus-within:mr-16 [@media(hover:hover)]:group-hover:mr-16">
                  <Tooltip>
                    <TooltipTrigger>
                      <div
                        className={twMerge(
                          "flex justify-center",
                          !singleEnvImport.isReplicationSuccess && "text-danger"
                        )}
                      >
                        {singleEnvImport.isReplicationSuccess ? (
                          <InfoIcon className="size-3.5 text-muted" />
                        ) : (
                          <TriangleAlertIcon className="size-3.5" />
                        )}
                      </div>
                    </TooltipTrigger>
                    <TooltipContent className="max-w-xs">
                      <div className="flex flex-col gap-1">
                        <div className="flex items-center gap-1.5">
                          <InfoIcon className="size-3" />
                          <span className="text-sm">Last Replication</span>
                        </div>
                        <span className="pl-4 text-xs text-foreground/50">
                          {new Date(singleEnvImport.lastReplicated).toLocaleString()}
                        </span>
                        {!singleEnvImport.isReplicationSuccess && (
                          <>
                            <div className="mt-1 flex items-center gap-1.5">
                              <TriangleAlertIcon className="size-3" />
                              <span className="text-sm">Fail reason</span>
                            </div>
                            <span className="pl-4 text-xs text-muted">
                              {singleEnvImport.replicationStatus}
                            </span>
                          </>
                        )}
                      </div>
                    </TooltipContent>
                  </Tooltip>
                </div>
              )}
            {isSingleEnvView && (
              <div className="absolute top-1/2 -right-2.5 z-20 -translate-y-1/2">
                {renderSingleEnvActions()}
              </div>
            )}
          </div>
        </TableCell>
        {environments.length > 1 &&
          environments.map(({ slug }, i) => {
            if (isExpanded)
              return (
                <TableCell
                  key={`import-env-expanded-${slug}`}
                  className="border-b-0 bg-container-hover"
                />
              );

            const isPresent = isSecretImportInEnv(importEnvSlug, importPath, slug);

            return (
              <ResourceEnvironmentStatusCell
                key={`import-overview-${slug}-${i + 1}`}
                status={isPresent ? "present" : "missing"}
              />
            );
          })}
      </TableRow>
      {isExpanded &&
        !isAnyDragging &&
        (isSingleEnvView ? (
          <TableRow
            key={`expanded-import-row-${index}`}
            className={twMerge("border-0 hover:bg-transparent", TABLE_ROW_ACTIVE_FILTER_CLASS_NAME)}
          >
            <TableCell colSpan={totalCols} className="border-0 p-0">
              <div className="sticky left-0 max-w-(--overview-table-width) min-w-(--overview-table-width) border-b border-border bg-container">
                {renderExpandedSecrets(singleEnvSlug)}
              </div>
            </TableCell>
          </TableRow>
        ) : (
          <TableRow
            className={twMerge("border-0 hover:bg-transparent", TABLE_ROW_ACTIVE_FILTER_CLASS_NAME)}
          >
            <TableCell colSpan={totalCols} className="border-0 p-0">
              <div className="sticky left-0 max-w-(--overview-table-width) min-w-(--overview-table-width) border-y border-border bg-container">
                <div className="flex min-h-10 flex-wrap items-center gap-2 border-b border-border px-3 py-1.5 pl-11">
                  <span className="text-xs text-muted">Imported in:</span>
                  {environments
                    .filter((env) => isSecretImportInEnv(importEnvSlug, importPath, env.slug))
                    .map(({ name: envName, slug }) => {
                      const secImp = getSecretImportByEnv(importEnvSlug, importPath, slug);

                      return (
                        <div
                          key={`import-env-badge-${slug}`}
                          className="group/badge flex items-center gap-1"
                        >
                          <Badge variant="neutral">
                            <LayersIcon />
                            {envName}
                            {secImp?.isReplication && renderReplicationStatus(secImp, slug)}
                          </Badge>
                        </div>
                      );
                    })}
                  <div className="ml-auto flex items-center gap-x-1.5 text-xs text-info">
                    <InfoIcon className="size-3" />
                    Select a single environment to manage imports
                  </div>
                </div>
                {renderMultiEnvExpandedSecrets()}
              </div>
            </TableCell>
          </TableRow>
        ))}
    </>
  );
};