Skip to content

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

21.7 KB
Raw Blame
import { useEffect, useState } from "react";
import { subject } from "@casl/ability";
import {
  ActivityIcon,
  ChevronDownIcon,
  EditIcon,
  EyeIcon,
  HandshakeIcon,
  InfoIcon,
  LoaderCircleIcon,
  RefreshCwIcon,
  TrashIcon,
  XIcon
} from "lucide-react";
import { twMerge } from "tailwind-merge";

import { ProjectPermissionCan } from "@app/components/permissions";
import { SecretRotationV2StatusBadge } from "@app/components/secret-rotations-v2/SecretRotationV2StatusBadge";
import {
  Badge,
  Checkbox,
  IconButton,
  ProviderIcon,
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
  Tooltip,
  TooltipContent,
  TooltipTrigger
} from "@app/components/v3";
import {
  ProjectPermissionSecretRotationActions,
  ProjectPermissionSub
} from "@app/context/ProjectPermissionContext/types";
import { SECRET_ROTATION_MAP } from "@app/helpers/secretRotationsV2";
import { useToggle } from "@app/hooks";
import {
  SecretRotation,
  SecretRotationStatus,
  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 { 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_NAME_CELL_COLUMN_CLASS_NAME,
  TABLE_ROW_NAME_HEADER_COLUMN_CLASS_NAME
} from "../tableRowActionStyles";
import type { TableRowActivityChangeHandler, TableRowActivityId } from "../tableRowActivity";

type Props = {
  secretRotationName: string;
  environments: { name: string; slug: string }[];
  isSecretRotationInEnv: (name: string, env: string) => boolean;
  getSecretRotationByName: (slug: string, name: string) => TSecretRotationV2 | undefined;
  getSecretRotationStatusesByName: (name: string) => (SecretRotationStatus | null)[] | undefined;
  isSelected: boolean;
  onToggleRotationSelect: (name: string, isShiftKey: boolean) => void;
  onEdit: (secretRotation: TSecretRotationV2) => void;
  onRotate: (secretRotation: TSecretRotationV2) => void;
  onReconcile: (secretRotation: TSecretRotationV2) => void;
  onViewGeneratedCredentials: (secretRotation: TSecretRotationV2) => void;
  onDelete: (secretRotation: TSecretRotationV2) => void;
  onCheckActiveCredentials: (secretRotation: TSecretRotationV2) => Promise<void> | void;
  activityId: TableRowActivityId;
  onActivityChange: TableRowActivityChangeHandler;
};

const shouldShowReconciliationButton = (secretRotation: TSecretRotationV2) =>
  (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);

export const SecretRotationTableRow = ({
  secretRotationName,
  environments = [],
  isSecretRotationInEnv,
  getSecretRotationByName,
  getSecretRotationStatusesByName,
  isSelected,
  onToggleRotationSelect,
  onEdit,
  onRotate,
  onViewGeneratedCredentials,
  onDelete,
  onReconcile,
  onCheckActiveCredentials,
  activityId,
  onActivityChange
}: Props) => {
  const [isExpanded, setIsExpanded] = useToggle(false);
  const [checkingRotationId, setCheckingRotationId] = useState<string | null>(null);

  const handleCheckActiveCredentials = async (secretRotation: TSecretRotationV2) => {
    if (checkingRotationId) return;
    setCheckingRotationId(secretRotation.id);
    try {
      await onCheckActiveCredentials(secretRotation);
    } finally {
      setCheckingRotationId(null);
    }
  };

  const isSingleEnvView = environments.length === 1;
  const totalCols = environments.length + 2; // secret key row + icon

  const statuses = getSecretRotationStatusesByName(secretRotationName);

  // Pre-compute single env data
  const singleEnvSlug = isSingleEnvView ? environments[0].slug : "";
  const singleEnvRotation = isSingleEnvView
    ? getSecretRotationByName(singleEnvSlug, secretRotationName)
    : undefined;

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

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

  const renderActionButtons = (secretRotation: TSecretRotationV2) => {
    const { environment, folder } = secretRotation;

    const showReconcileButton = shouldShowReconciliationButton(secretRotation);
    const isCheckingRotation = checkingRotationId === secretRotation.id;

    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,
          isCheckingRotation && TABLE_ROW_ACTION_BAR_VISIBLE_CLASS_NAME
        )}
      >
        <ProjectPermissionCan
          I={ProjectPermissionSecretRotationActions.ReadGeneratedCredentials}
          a={subject(ProjectPermissionSub.SecretRotation, {
            environment: environment.slug,
            secretPath: folder.path,
            ...(secretRotation.connectionId && {
              connectionId: secretRotation.connectionId
            })
          })}
        >
          {(isAllowed) => (
            <Tooltip>
              <TooltipTrigger>
                <IconButton
                  aria-label="Validate rotation credentials"
                  variant="ghost"
                  size="xs"
                  className={twMerge(
                    TABLE_ROW_ACTION_BUTTON_CLASS_NAME,
                    isCheckingRotation && TABLE_ROW_ACTION_BUTTON_VISIBLE_CLASS_NAME
                  )}
                  isDisabled={!isAllowed || Boolean(checkingRotationId)}
                  onClick={() => handleCheckActiveCredentials(secretRotation)}
                >
                  {isCheckingRotation ? (
                    <LoaderCircleIcon className="animate-spin" />
                  ) : (
                    <ActivityIcon />
                  )}
                </IconButton>
              </TooltipTrigger>
              <TooltipContent>Validate Credentials</TooltipContent>
            </Tooltip>
          )}
        </ProjectPermissionCan>
        <ProjectPermissionCan
          I={ProjectPermissionSecretRotationActions.ReadGeneratedCredentials}
          a={subject(ProjectPermissionSub.SecretRotation, {
            environment: environment.slug,
            secretPath: folder.path,
            ...(secretRotation.connectionId && {
              connectionId: secretRotation.connectionId
            })
          })}
        >
          {(isAllowed) => (
            <Tooltip>
              <TooltipTrigger>
                <IconButton
                  aria-label="View generated rotation credentials"
                  variant="ghost"
                  size="xs"
                  className={TABLE_ROW_ACTION_BUTTON_CLASS_NAME}
                  isDisabled={!isAllowed}
                  onClick={() => onViewGeneratedCredentials(secretRotation)}
                >
                  <EyeIcon />
                </IconButton>
              </TooltipTrigger>
              <TooltipContent>View Generated Credentials</TooltipContent>
            </Tooltip>
          )}
        </ProjectPermissionCan>
        <ProjectPermissionCan
          I={ProjectPermissionSecretRotationActions.RotateSecrets}
          a={subject(ProjectPermissionSub.SecretRotation, {
            environment: environment.slug,
            secretPath: folder.path,
            ...(secretRotation.connectionId && {
              connectionId: secretRotation.connectionId
            })
          })}
        >
          {(isAllowed) => (
            <Tooltip>
              <TooltipTrigger>
                <IconButton
                  aria-label="Rotate secret"
                  variant="ghost"
                  size="xs"
                  className={TABLE_ROW_ACTION_BUTTON_CLASS_NAME}
                  isDisabled={!isAllowed}
                  onClick={() => onRotate(secretRotation)}
                >
                  <RefreshCwIcon />
                </IconButton>
              </TooltipTrigger>
              <TooltipContent>Rotate Secret</TooltipContent>
            </Tooltip>
          )}
        </ProjectPermissionCan>
        {showReconcileButton && (
          <ProjectPermissionCan
            I={ProjectPermissionSecretRotationActions.RotateSecrets}
            a={subject(ProjectPermissionSub.SecretRotation, {
              environment: environment.slug,
              secretPath: folder.path,
              ...(secretRotation.connectionId && {
                connectionId: secretRotation.connectionId
              })
            })}
          >
            {(isAllowed) => (
              <Tooltip>
                <TooltipTrigger>
                  <IconButton
                    aria-label="Reconcile secret rotation"
                    variant="ghost"
                    size="xs"
                    className={TABLE_ROW_ACTION_BUTTON_CLASS_NAME}
                    isDisabled={!isAllowed}
                    onClick={() => onReconcile(secretRotation)}
                  >
                    <HandshakeIcon />
                  </IconButton>
                </TooltipTrigger>
                <TooltipContent>Reconcile Secret</TooltipContent>
              </Tooltip>
            )}
          </ProjectPermissionCan>
        )}
        <ProjectPermissionCan
          I={ProjectPermissionSecretRotationActions.Edit}
          a={subject(ProjectPermissionSub.SecretRotation, {
            environment: environment.slug,
            secretPath: folder.path,
            ...(secretRotation.connectionId && {
              connectionId: secretRotation.connectionId
            })
          })}
          renderTooltip
          allowedLabel="Edit"
        >
          {(isAllowed) => (
            <Tooltip>
              <TooltipTrigger>
                <IconButton
                  aria-label="Edit secret rotation"
                  variant="ghost"
                  size="xs"
                  className={TABLE_ROW_ACTION_BUTTON_CLASS_NAME}
                  isDisabled={!isAllowed}
                  onClick={() => onEdit(secretRotation)}
                >
                  <EditIcon />
                </IconButton>
              </TooltipTrigger>
              <TooltipContent>Edit</TooltipContent>
            </Tooltip>
          )}
        </ProjectPermissionCan>
        <ProjectPermissionCan
          I={ProjectPermissionSecretRotationActions.Delete}
          a={subject(ProjectPermissionSub.SecretRotation, {
            environment: environment.slug,
            secretPath: folder.path,
            ...(secretRotation.connectionId && {
              connectionId: secretRotation.connectionId
            })
          })}
        >
          {(isAllowed) => (
            <Tooltip>
              <TooltipTrigger>
                <IconButton
                  aria-label="Delete secret rotation"
                  variant="ghost"
                  size="xs"
                  className={twMerge(TABLE_ROW_ACTION_BUTTON_CLASS_NAME, "hover:text-danger")}
                  onClick={() => onDelete(secretRotation)}
                  isDisabled={!isAllowed}
                >
                  <TrashIcon />
                </IconButton>
              </TooltipTrigger>
              <TooltipContent>Delete</TooltipContent>
            </Tooltip>
          )}
        </ProjectPermissionCan>
      </div>
    );
  };

  return (
    <>
      <TableRow
        onClick={isSingleEnvView ? undefined : setIsExpanded.toggle}
        className={twMerge(
          "group hover:z-10",
          (isExpanded || isSelected) && TABLE_ROW_ACTIVE_FILTER_CLASS_NAME
        )}
      >
        <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"
          )}
        >
          <div className="flex h-full items-center justify-center [&>svg]:size-4">
            {!isSingleEnvView && isExpanded ? (
              <ChevronDownIcon />
            ) : (
              <>
                <Checkbox
                  variant="project"
                  id={`checkbox-${secretRotationName}`}
                  isChecked={isSelected}
                  onClick={(e) => {
                    e.stopPropagation();
                    onToggleRotationSelect(secretRotationName, e.shiftKey);
                  }}
                  className={twMerge("hidden group-hover:flex", isSelected && "flex")}
                />
                <RefreshCwIcon
                  className={twMerge(
                    "block text-secret-rotation",
                    "group-hover:!hidden",
                    isSelected && "!hidden"
                  )}
                />
              </>
            )}
          </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}
        >
          {isSingleEnvView && singleEnvRotation ? (
            <div className="relative flex w-full items-center">
              <span className="truncate">{secretRotationName}</span>
              <Badge variant="neutral" className="mx-2.5">
                <ProviderIcon
                  icon={SECRET_ROTATION_MAP[singleEnvRotation.type].image}
                  style={{ width: "11px" }}
                  alt={`${SECRET_ROTATION_MAP[singleEnvRotation.type].name} logo`}
                />
                {SECRET_ROTATION_MAP[singleEnvRotation.type].name}
              </Badge>
              {singleEnvRotation.description && (
                <Tooltip>
                  <TooltipTrigger asChild>
                    <InfoIcon className="mr-2.5 !size-3 text-accent" />
                  </TooltipTrigger>
                  <TooltipContent>{singleEnvRotation.description}</TooltipContent>
                </Tooltip>
              )}
              {isSingleEnvView && singleEnvRotation && (
                <>
                  <div
                    className={twMerge(
                      "ml-auto flex items-center transition-[margin] duration-300 motion-reduce:transition-none",
                      shouldShowReconciliationButton(singleEnvRotation)
                        ? "mr-48 [@media(hover:hover)]:mr-0 [@media(hover:hover)]:group-focus-within:mr-48 [@media(hover:hover)]:group-hover:mr-48"
                        : "mr-40 [@media(hover:hover)]:mr-0 [@media(hover:hover)]:group-focus-within:mr-40 [@media(hover:hover)]:group-hover:mr-40",
                      checkingRotationId === singleEnvRotation.id &&
                        (shouldShowReconciliationButton(singleEnvRotation)
                          ? "[@media(hover:hover)]:mr-48"
                          : "[@media(hover:hover)]:mr-40")
                    )}
                  >
                    <SecretRotationV2StatusBadge secretRotation={singleEnvRotation} />
                  </div>
                  <div className="absolute top-1/2 -right-2.5 z-20 -translate-y-1/2">
                    {renderActionButtons(singleEnvRotation)}
                  </div>
                </>
              )}
            </div>
          ) : (
            <>
              {secretRotationName}
              {statuses?.some((status) => status === SecretRotationStatus.Failed) && (
                <Tooltip>
                  <TooltipTrigger asChild>
                    <Badge className="absolute top-1/2 right-2 -translate-y-1/2" variant="danger">
                      <XIcon />
                      Rotation Failed
                    </Badge>
                  </TooltipTrigger>
                  <TooltipContent>One or more secrets failed to rotate.</TooltipContent>
                </Tooltip>
              )}
            </>
          )}
        </TableCell>
        {environments.length > 1 &&
          environments.map(({ slug }, i) => {
            if (isExpanded) return <TableCell className="border-b-0 bg-container-hover" />;

            const isPresent = isSecretRotationInEnv(secretRotationName, slug);

            return (
              <ResourceEnvironmentStatusCell
                key={`sec-overview-${slug}-${i + 1}-folder`}
                status={isPresent ? "present" : "missing"}
              />
            );
          })}
      </TableRow>
      {!isSingleEnvView && isExpanded && (
        <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">
              <Table
                className="w-full min-w-[calc(var(--name-column-width,180px)+24rem)] 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}>
                      Environment
                    </TableHead>
                    <TableHead />
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {environments
                    .filter((env) => {
                      const secretRotation = getSecretRotationByName(env.slug, secretRotationName);

                      return Boolean(secretRotation);
                    })
                    .map(({ name: envName, slug }) => {
                      const secretRotation = getSecretRotationByName(slug, secretRotationName)!;
                      const { type, description } = secretRotation;

                      const { name: rotationType, image } = SECRET_ROTATION_MAP[type];

                      const showReconcileButton = shouldShowReconciliationButton(secretRotation);

                      return (
                        <TableRow key={slug} className="group relative hover:z-10">
                          <TableCell aria-hidden="true" className="w-10 max-w-10 min-w-10 p-0" />
                          <TableCell className={TABLE_ROW_NAME_CELL_COLUMN_CLASS_NAME}>
                            {envName}
                          </TableCell>
                          <TableCell>
                            <div className="relative flex w-full flex-wrap items-center">
                              <Badge variant="neutral">
                                <ProviderIcon
                                  icon={image}
                                  style={{
                                    width: "11px"
                                  }}
                                  alt={`${rotationType} logo`}
                                />
                                {rotationType}
                              </Badge>
                              {description && (
                                <Tooltip>
                                  <TooltipTrigger asChild>
                                    <InfoIcon className="size-3 text-accent" />
                                  </TooltipTrigger>
                                  <TooltipContent>{description}</TooltipContent>
                                </Tooltip>
                              )}
                              <div
                                className={twMerge(
                                  "ml-auto flex items-center transition-[margin] duration-300 motion-reduce:transition-none",
                                  showReconcileButton
                                    ? "mr-48 [@media(hover:hover)]:mr-0 [@media(hover:hover)]:group-focus-within:mr-48 [@media(hover:hover)]:group-hover:mr-48"
                                    : "mr-40 [@media(hover:hover)]:mr-0 [@media(hover:hover)]:group-focus-within:mr-40 [@media(hover:hover)]:group-hover:mr-40",
                                  checkingRotationId === secretRotation.id &&
                                    (showReconcileButton
                                      ? "[@media(hover:hover)]:mr-48"
                                      : "[@media(hover:hover)]:mr-40")
                                )}
                              >
                                <SecretRotationV2StatusBadge secretRotation={secretRotation} />
                              </div>
                              <div className="absolute top-1/2 -right-1.5 z-20 -translate-y-1/2">
                                {renderActionButtons(secretRotation)}
                              </div>
                            </div>
                          </TableCell>
                        </TableRow>
                      );
                    })}
                </TableBody>
              </Table>
            </div>
          </TableCell>
        </TableRow>
      )}
    </>
  );
};