Skip to content

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

7.1 KB
Raw Blame
import { useEffect, useRef } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { Link, useNavigate, useParams } from "@tanstack/react-router";
import { ChevronLeftIcon, EllipsisIcon } from "lucide-react";

import { PageTitle } from "@app/components/PageTitle";
import { ProjectPermissionCan } from "@app/components/permissions";
import {
  Badge,
  Button,
  ConfirmationAlertDialog,
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
  PageHeader,
  PageLoader
} from "@app/components/v3";
import {
  ProjectPermissionPkiDiscoveryActions,
  ProjectPermissionSub,
  useOrganization,
  useProject
} from "@app/context";
import {
  isPkiDiscoveryScanInFlight,
  pkiDiscoveryKeys,
  pkiInstallationKeys,
  TPkiDiscovery,
  useDeletePkiDiscovery,
  useGetPkiDiscovery,
  useTriggerPkiDiscoveryScan
} from "@app/hooks/api";
import { ProjectType } from "@app/hooks/api/projects/types";
import { usePopUp } from "@app/hooks/usePopUp";

import { DiscoveryJobSheet } from "../DiscoveryPage/components/DiscoveryJobSheet";
import {
  DiscoveryDetailsSection,
  DiscoveryInstallationsSection,
  DiscoveryScanLogsSection,
  DiscoveryTargetSection
} from "./components";

const Page = () => {
  const { currentProject } = useProject();
  const projectId = currentProject.id;
  const { currentOrg } = useOrganization();
  const navigate = useNavigate();
  const { discoveryId, orgId } = useParams({
    from: "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/cert-manager/_cert-manager-layout/discovery/$discoveryId"
  });

  const queryClient = useQueryClient();
  const { data: discovery, isLoading } = useGetPkiDiscovery({ discoveryId });
  const triggerScan = useTriggerPkiDiscoveryScan();
  const deleteDiscovery = useDeletePkiDiscovery();

  const isScanRunning = isPkiDiscoveryScanInFlight(discovery?.lastScanStatus);
  const wasScanRunningRef = useRef(isScanRunning);

  // Once a scan finishes, refresh scan runs and installations so the final state is not stale
  useEffect(() => {
    if (wasScanRunningRef.current && !isScanRunning) {
      queryClient.invalidateQueries({
        queryKey: pkiDiscoveryKeys.scanHistoryByDiscovery(discoveryId)
      });
      queryClient.invalidateQueries({ queryKey: pkiInstallationKeys.list(projectId) });
    }
    wasScanRunningRef.current = isScanRunning;
  }, [isScanRunning, discoveryId, projectId, queryClient]);

  const { popUp, handlePopUpOpen, handlePopUpClose, handlePopUpToggle } = usePopUp([
    "editJob",
    "deleteJob"
  ] as const);

  if (isLoading) {
    return <PageLoader />;
  }

  if (!discovery) {
    return null;
  }

  const handleTriggerScan = async () => {
    try {
      await triggerScan.mutateAsync({ discoveryId, projectId });
    } catch {
      // Error handled by mutation
    }
  };

  const handleDelete = async () => {
    try {
      await deleteDiscovery.mutateAsync({ discoveryId });
      handlePopUpClose("deleteJob");
      navigate({
        to: "/organizations/$orgId/cert-manager/discovery",
        params: { orgId }
      });
    } catch {
      // Error handled by mutation
    }
  };

  return (
    <div className="mx-auto flex flex-col justify-between text-foreground-inverse">
      <div className="mx-auto mb-6 flex w-full max-w-8xl flex-col">
        <PageHeader
          backLink={
            <Link
              to="/organizations/$orgId/cert-manager/discovery"
              params={{ orgId: currentOrg.id }}
            >
              <ChevronLeftIcon size={16} />
              Jobs
            </Link>
          }
          scope={ProjectType.CertificateManager}
          description="Certificate Discovery Job"
          title={
            <span className="inline-flex max-w-full items-center gap-x-3">
              <span className="truncate" title={discovery.name}>
                {discovery.name}
              </span>
              {discovery.isAutoScanEnabled && <Badge variant="info">Auto-Scan</Badge>}
            </span>
          }
        >
          <div className="flex items-center gap-2">
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="outline">
                  Options
                  <EllipsisIcon />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                <ProjectPermissionCan
                  I={ProjectPermissionPkiDiscoveryActions.Edit}
                  a={ProjectPermissionSub.PkiDiscovery}
                >
                  {(isAllowed) => (
                    <DropdownMenuItem
                      isDisabled={!isAllowed}
                      onClick={() => handlePopUpOpen("editJob", discovery)}
                    >
                      Edit
                    </DropdownMenuItem>
                  )}
                </ProjectPermissionCan>
                <ProjectPermissionCan
                  I={ProjectPermissionPkiDiscoveryActions.Delete}
                  a={ProjectPermissionSub.PkiDiscovery}
                >
                  {(isAllowed) => (
                    <DropdownMenuItem
                      variant="danger"
                      isDisabled={!isAllowed}
                      onClick={() => handlePopUpOpen("deleteJob")}
                    >
                      Delete
                    </DropdownMenuItem>
                  )}
                </ProjectPermissionCan>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        </PageHeader>

        <div className="flex flex-col gap-5 lg:flex-row">
          <div className="flex w-full flex-col gap-5 lg:max-w-[24rem]">
            <DiscoveryDetailsSection discovery={discovery} />
            <DiscoveryTargetSection discovery={discovery} />
          </div>
          <div className="flex min-w-0 flex-1 flex-col gap-y-5">
            <DiscoveryScanLogsSection
              discoveryId={discoveryId}
              onTriggerScan={handleTriggerScan}
              isTriggerDisabled={!discovery.isActive || isScanRunning}
              isTriggerPending={triggerScan.isPending}
              isScanRunning={isScanRunning}
            />
            <DiscoveryInstallationsSection
              discoveryId={discoveryId}
              projectId={projectId}
              isScanRunning={isScanRunning}
            />
          </div>
        </div>
      </div>

      <DiscoveryJobSheet
        isOpen={popUp.editJob.isOpen}
        onClose={() => handlePopUpClose("editJob")}
        projectId={projectId}
        discovery={popUp.editJob.data as TPkiDiscovery | undefined}
      />

      <ConfirmationAlertDialog
        isOpen={popUp.deleteJob.isOpen}
        title="Are you sure you want to delete this discovery job?"
        description="This action cannot be undone. The discovery configuration will be permanently deleted."
        onOpenChange={(isOpen) => handlePopUpToggle("deleteJob", isOpen)}
        confirmKey="confirm"
        onConfirm={handleDelete}
      />
    </div>
  );
};

export const DiscoveryDetailsByIDPage = () => {
  return (
    <>
      <PageTitle title="Discovery Job Details" />
      <link rel="icon" href="/infisical.ico" />
      <Page />
    </>
  );
};