Skip to content

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

7.0 KB
Raw Blame
import { faCheck, faCopy, faDownload } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import FileSaver from "file-saver";

import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  IconButton,
  Spinner,
  Tooltip,
  TooltipContent,
  TooltipTrigger
} from "@app/components/v3";
import {
  ProjectPermissionCmekActions,
  ProjectPermissionSub,
  useProjectPermission
} from "@app/context";
import { useTimedReset } from "@app/hooks";
import { useGetCmekPrivateKey, useGetCmekPublicKey } from "@app/hooks/api/cmeks/queries";
import { AsymmetricKeyAlgorithm, TCmek } from "@app/hooks/api/cmeks/types";

type Props = {
  isOpen: boolean;
  onOpenChange: (isOpen: boolean) => void;
  cmek: TCmek;
};

type FormProps = Pick<Props, "cmek">;

const ExportKeyForm = ({ cmek }: FormProps) => {
  const { permission } = useProjectPermission();
  const isAsymmetricKey = Object.values(AsymmetricKeyAlgorithm).includes(
    cmek?.algorithm as AsymmetricKeyAlgorithm
  );

  const canReadPublicKey = permission.can(
    ProjectPermissionCmekActions.Read,
    ProjectPermissionSub.Cmek
  );

  const canExportPrivateKey = permission.can(
    ProjectPermissionCmekActions.ExportPrivateKey,
    ProjectPermissionSub.Cmek
  );

  const canExportKeyMaterial = canExportPrivateKey && cmek.isExportable;

  const { data: privateKeyData, isPending: isPrivateKeyPending } = useGetCmekPrivateKey(
    cmek?.id ?? "",
    {
      // Only fetch private key if user has ExportPrivateKey permission and the key allows export
      enabled: Boolean(cmek?.id) && canExportKeyMaterial
    }
  );

  const { data: publicKeyData, isPending: isPublicKeyPending } = useGetCmekPublicKey(
    cmek?.id ?? "",
    {
      // Only fetch public key if user has Read permission and it's an asymmetric key
      enabled: Boolean(cmek?.id) && isAsymmetricKey && canReadPublicKey
    }
  );

  const [copyPrivateKeyText, isCopyingPrivateKey, setCopyPrivateKeyText] = useTimedReset<string>({
    initialState: "Copy to clipboard"
  });

  const [copyPublicKeyText, isCopyingPublicKey, setCopyPublicKeyText] = useTimedReset<string>({
    initialState: "Copy to clipboard"
  });

  const downloadTxtFile = (filename: string, content: string) => {
    const blob = new Blob([content], { type: "text/plain;charset=utf-8" });
    FileSaver.saveAs(blob, filename);
  };

  const isLoading =
    (canExportKeyMaterial && isPrivateKeyPending) ||
    (isAsymmetricKey && canReadPublicKey && isPublicKeyPending);

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-8">
        <Spinner size="lg" label="Loading key material" />
      </div>
    );
  }

  return (
    <div>
      {canExportKeyMaterial && privateKeyData?.privateKey && (
        <>
          <div className="mb-4 flex items-center justify-between">
            <h2>{isAsymmetricKey ? "Private Key (Base64)" : "Key Material (Base64)"}</h2>
            <div className="flex gap-2">
              <Tooltip hoverable selectable={false} delayDuration={50}>
                <TooltipTrigger asChild>
                  <IconButton
                    aria-label={isAsymmetricKey ? "Copy Private Key" : "Copy Key Material"}
                    variant="outline"
                    size="sm"
                    onClick={() => {
                      navigator.clipboard.writeText(privateKeyData?.privateKey ?? "");
                      setCopyPrivateKeyText("Copied");
                    }}
                  >
                    <FontAwesomeIcon icon={isCopyingPrivateKey ? faCheck : faCopy} />
                  </IconButton>
                </TooltipTrigger>
                <TooltipContent sideOffset={5}>{copyPrivateKeyText}</TooltipContent>
              </Tooltip>
              <Tooltip hoverable selectable={false} delayDuration={50}>
                <TooltipTrigger asChild>
                  <IconButton
                    aria-label={isAsymmetricKey ? "Download Private Key" : "Download Key Material"}
                    variant="outline"
                    size="sm"
                    onClick={() => {
                      downloadTxtFile(
                        `${cmek.name}_${isAsymmetricKey ? "private_key" : "key_material"}`,
                        privateKeyData?.privateKey ?? ""
                      );
                    }}
                  >
                    <FontAwesomeIcon icon={faDownload} />
                  </IconButton>
                </TooltipTrigger>
                <TooltipContent sideOffset={5}>Download</TooltipContent>
              </Tooltip>
            </div>
          </div>
          <div className="mb-8 rounded-md border border-border bg-container p-2 text-sm text-foreground">
            <p className="font-mono break-all whitespace-pre-wrap">{privateKeyData?.privateKey}</p>
          </div>
        </>
      )}

      {isAsymmetricKey && canReadPublicKey && publicKeyData?.publicKey && (
        <>
          <div className="mb-4 flex items-center justify-between">
            <h2>Public Key (Base64)</h2>
            <div className="flex gap-2">
              <Tooltip hoverable selectable={false} delayDuration={50}>
                <TooltipTrigger asChild>
                  <IconButton
                    aria-label="Copy Public Key"
                    variant="outline"
                    size="sm"
                    onClick={() => {
                      navigator.clipboard.writeText(publicKeyData?.publicKey ?? "");
                      setCopyPublicKeyText("Copied");
                    }}
                  >
                    <FontAwesomeIcon icon={isCopyingPublicKey ? faCheck : faCopy} />
                  </IconButton>
                </TooltipTrigger>
                <TooltipContent sideOffset={5}>{copyPublicKeyText}</TooltipContent>
              </Tooltip>
              <Tooltip hoverable selectable={false} delayDuration={50}>
                <TooltipTrigger asChild>
                  <IconButton
                    aria-label="Download Public Key"
                    variant="outline"
                    size="sm"
                    onClick={() => {
                      downloadTxtFile(`${cmek.name}_public_key`, publicKeyData?.publicKey ?? "");
                    }}
                  >
                    <FontAwesomeIcon icon={faDownload} />
                  </IconButton>
                </TooltipTrigger>
                <TooltipContent sideOffset={5}>Download</TooltipContent>
              </Tooltip>
            </div>
          </div>
          <div className="mb-8 rounded-md border border-border bg-container p-2 text-sm text-foreground">
            <p className="font-mono break-all whitespace-pre-wrap">{publicKeyData?.publicKey}</p>
          </div>
        </>
      )}
    </div>
  );
};

export const CmekExportKeyModal = ({ isOpen, onOpenChange, cmek }: Props) => {
  return (
    <Dialog open={isOpen} onOpenChange={onOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Export Key</DialogTitle>
        </DialogHeader>
        {cmek && <ExportKeyForm cmek={cmek} />}
      </DialogContent>
    </Dialog>
  );
};