Skip to content

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

19.6 KB
Raw Blame
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { subject } from "@casl/ability";
import { useQuery } from "@tanstack/react-query";
import { Link, useNavigate, useParams } from "@tanstack/react-router";
import {
  ChevronLeftIcon,
  CopyIcon,
  EllipsisIcon,
  InfoIcon,
  ShieldIcon,
  TrashIcon,
  UserRoundXIcon,
  VenetianMaskIcon
} from "lucide-react";

import { IdentityDelegationSection } from "@app/components/agent-vault/IdentityDelegationSection";
import { AssumePrivilegesDialog } from "@app/components/assume-privileges";
import { createNotification } from "@app/components/notifications";
import { PageTitle } from "@app/components/PageTitle";
import { OrgPermissionCan, ProjectPermissionCan } from "@app/components/permissions";
import {
  Alert,
  AlertDescription,
  AlertTitle,
  Button,
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
  Empty,
  EmptyDescription,
  EmptyHeader,
  EmptyTitle,
  OrgIcon,
  PageHeader,
  PageLoader,
  SubOrgIcon,
  Tooltip,
  TooltipContent,
  TooltipTrigger
} from "@app/components/v3";
import {
  OrgPermissionIdentityActions,
  OrgPermissionSubjects,
  ProjectPermissionActions,
  ProjectPermissionIdentityActions,
  ProjectPermissionSub,
  useOrganization,
  useProject,
  useSubscription
} from "@app/context";
import {
  getProjectBaseURL,
  getProjectLabel,
  hidesProjects,
  supportsAssumePrivileges
} from "@app/helpers/project";
import { usePopUp } from "@app/hooks";
import {
  useDeleteProjectIdentityMembership,
  useGetProjectIdentityMembershipV2
} from "@app/hooks/api";
import { useRevokeAgentVaultMembers } from "@app/hooks/api/agentVault";
import { ActorType } from "@app/hooks/api/auditLogs/enums";
import { useRemovePamProductIdentityMember } from "@app/hooks/api/pam";
import { projectIdentityQuery, useDeleteProjectIdentity } from "@app/hooks/api/projectIdentity";
import { ProjectType } from "@app/hooks/api/projects/types";
import { AdditionalPrivilegesRemovedSection } from "@app/pages/project/components/AdditionalPrivilegesRemovedSection";
import { FolderAccessSection } from "@app/pages/project/components/FolderAccessSection";
import { ProjectIdentityAuthenticationSection } from "@app/pages/project/IdentityDetailsByIDPage/components/ProjectIdentityAuthSection";
import { ProjectIdentityDetailsSection } from "@app/pages/project/IdentityDetailsByIDPage/components/ProjectIdentityDetailsSection";
import { ProjectAccessControlTabs } from "@app/types/project";

import { IdentityActionConfirmationDialog } from "./components/IdentityActionConfirmationDialog";
import { IdentityPermissionAuditSheet } from "./components/IdentityPermissionAuditSheet";
import { IdentityProjectAdditionalPrivilegeSection } from "./components/IdentityProjectAdditionalPrivilegeSection";
import { IdentityRoleDetailsSection } from "./components/IdentityRoleDetailsSection";
import { ProjectIdentityAlertAction } from "./components/ProjectIdentityAlertAction";

const Page = () => {
  const navigate = useNavigate();
  const identityId = useParams({
    strict: false,
    select: (el) => el.identityId as string
  });
  const { currentProject, projectId } = useProject();
  const { currentOrg, isSubOrganization } = useOrganization();
  const { subscription } = useSubscription();

  const { data: identityMembershipDetails, isPending: isMembershipDetailsLoading } =
    useGetProjectIdentityMembershipV2(projectId, identityId, currentProject?.type);

  const { mutateAsync: removeIdentityMutateAsync } = useDeleteProjectIdentityMembership();
  const { mutateAsync: removePamIdentityMutateAsync } = useRemovePamProductIdentityMember();
  const { mutateAsync: revokeAgentVaultMembers } = useRevokeAgentVaultMembers();

  const isProjectIdentity = Boolean(identityMembershipDetails?.identity.projectId);
  const isCertManager = currentProject?.type === ProjectType.CertificateManager;
  const isPam = currentProject?.type === ProjectType.PAM;
  const isAgentVault = currentProject?.type === ProjectType.AgentVault;
  // Products where the underlying project is an internal detail the user never sees
  const isSecretManager = currentProject?.type === ProjectType.SecretManager;
  const hasFolderRbacPlan = Boolean(subscription?.secretsFolderRbac);
  const isStandaloneProduct = isCertManager || isPam || isAgentVault;
  const canAssumePrivileges = supportsAssumePrivileges(currentProject.type);

  let removeMenuItemLabel = "Remove From Project";
  if (isProjectIdentity) {
    removeMenuItemLabel = "Delete Machine Identity";
  } else if (isCertManager) {
    removeMenuItemLabel = "Remove From Certificate Manager";
  } else if (isPam) {
    removeMenuItemLabel = "Remove From PAM";
  } else if (isAgentVault) {
    removeMenuItemLabel = "Remove From Agent Vault";
  }

  const projectsHidden = hidesProjects(currentProject?.type);
  const namesProduct = isStandaloneProduct || projectsHidden;

  let accessControlLabel = "project";
  if (projectsHidden) {
    accessControlLabel = getProjectLabel(currentProject?.type).toLowerCase();
  } else if (isPam) {
    accessControlLabel = "PAM";
  } else if (isAgentVault) {
    accessControlLabel = "Agent Vault";
  }
  const pageDescription = `Configure and manage${
    isProjectIdentity ? " machine identity and " : " "
  }${accessControlLabel} access control`;

  const {
    data: identity,
    isPending: isProjectIdentityPending,
    refetch: refetchIdentity
  } = useQuery({
    ...projectIdentityQuery.getById({
      identityId: identityMembershipDetails?.identity.id as string,
      projectId: identityMembershipDetails?.identity.projectId as string
    }),
    enabled: isProjectIdentity
  });

  const { mutateAsync: deleteIdentity } = useDeleteProjectIdentity();

  const { popUp, handlePopUpOpen, handlePopUpClose, handlePopUpToggle } = usePopUp([
    "removeIdentity",
    "deleteIdentity",
    "assumePrivileges"
  ] as const);
  const [isPermissionAuditOpen, setIsPermissionAuditOpen] = useState(false);

  const onRemoveIdentitySubmit = async () => {
    if (isPam) {
      // PAM removal goes through the PAM endpoint so PAM audit events fire and
      // folder/account resource memberships are cleaned up (the generic route skips that)
      await removePamIdentityMutateAsync({
        identityId,
        projectId
      });
    } else if (isAgentVault) {
      // Same reason as PAM: the product route keeps the last-admin guard, emits the Agent Vault event
      // and reaps the identity's bundle grants, none of which the generic route does.
      await revokeAgentVaultMembers({ machineIdentityIds: [identityId] });
    } else {
      await removeIdentityMutateAsync({
        identityId,
        projectId
      });
    }
    createNotification({
      text: `Successfully removed machine identity from ${namesProduct ? accessControlLabel : "project"}`,
      type: "success"
    });
    handlePopUpClose("removeIdentity");
    navigate({
      to: `${getProjectBaseURL(currentProject.type)}/access-management` as const,
      params: {
        projectId,
        orgId: currentOrg.id
      },
      search: {
        selectedTab: "identities"
      }
    });
  };

  const handleDeleteIdentity = async () => {
    if (!identity) return;

    try {
      await deleteIdentity({
        identityId: identity.id,
        projectId: identity.projectId!
      });

      navigate({
        to: `${getProjectBaseURL(currentProject.type)}/access-management`,
        search: {
          selectedTab: "identities"
        }
      });
    } catch {
      createNotification({
        type: "error",
        text: isCertManager
          ? "Failed to delete Certificate Manager machine identity"
          : "Failed to delete project machine identity"
      });
    }
  };

  if (isMembershipDetailsLoading || (isProjectIdentity && isProjectIdentityPending)) {
    return <PageLoader />;
  }

  const isOrgIdentity = !isProjectIdentity;
  const isSubOrgIdentity =
    isOrgIdentity &&
    isSubOrganization &&
    currentOrg.rootOrgId !== identityMembershipDetails?.identity.orgId;

  return (
    <div className="@container mx-auto flex max-w-8xl flex-col">
      {identityMembershipDetails ? (
        <>
          <PageHeader
            scope={currentProject.type}
            description={pageDescription}
            title={identityMembershipDetails.identity.name}
            backLink={
              <Link
                to={`${getProjectBaseURL(currentProject.type)}/access-management`}
                params={{
                  projectId,
                  orgId: currentOrg.id
                }}
                search={{
                  selectedTab: ProjectAccessControlTabs.Identities
                }}
              >
                <ChevronLeftIcon aria-hidden className="size-4" />
                {namesProduct ? "Machine Identities" : "Project Machine Identities"}
              </Link>
            }
          >
            <div className="flex items-center gap-2">
              {isProjectIdentity ? (
                <ProjectIdentityAlertAction
                  identityId={identityMembershipDetails.identity.id}
                  projectId={currentProject.id}
                />
              ) : (
                <ProjectIdentityAlertAction
                  identityId={identityMembershipDetails.identity.id}
                  readOnly
                />
              )}
              {!isStandaloneProduct && (
                <Button variant="outline" onClick={() => setIsPermissionAuditOpen(true)}>
                  <ShieldIcon />
                  Permission Audit
                </Button>
              )}
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button variant="outline">
                    Options
                    <EllipsisIcon />
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end">
                  <DropdownMenuItem
                    onClick={() => {
                      navigator.clipboard.writeText(identityMembershipDetails.identity.id);
                      createNotification({
                        text: "Machine identity ID copied to clipboard",
                        type: "info"
                      });
                    }}
                  >
                    <CopyIcon />
                    Copy Machine Identity ID
                  </DropdownMenuItem>
                  {canAssumePrivileges && (
                    <ProjectPermissionCan
                      I={ProjectPermissionIdentityActions.AssumePrivileges}
                      a={subject(ProjectPermissionSub.Identity, {
                        identityId: identityMembershipDetails?.identity.id
                      })}
                    >
                      {(isAllowed) => (
                        <Tooltip>
                          <TooltipTrigger className="block w-full">
                            <DropdownMenuItem
                              isDisabled={!isAllowed}
                              onClick={() => handlePopUpOpen("assumePrivileges")}
                            >
                              <VenetianMaskIcon />
                              Assume Privileges
                              {isAllowed && <InfoIcon className="text-muted" />}
                            </DropdownMenuItem>
                          </TooltipTrigger>
                          {isAllowed && (
                            <TooltipContent className="max-w-80" side="left">
                              Assume the privileges of this machine identity, allowing you to
                              replicate their access behavior.
                            </TooltipContent>
                          )}
                        </Tooltip>
                      )}
                    </ProjectPermissionCan>
                  )}
                  <ProjectPermissionCan
                    I={ProjectPermissionActions.Delete}
                    a={subject(ProjectPermissionSub.Identity, {
                      identityId: identityMembershipDetails?.identity?.id
                    })}
                  >
                    {(isAllowed) => (
                      <DropdownMenuItem
                        variant="danger"
                        isDisabled={!isAllowed}
                        onClick={() =>
                          isProjectIdentity
                            ? handlePopUpOpen("deleteIdentity")
                            : handlePopUpOpen("removeIdentity")
                        }
                      >
                        {isProjectIdentity ? <TrashIcon /> : <UserRoundXIcon />}
                        {removeMenuItemLabel}
                      </DropdownMenuItem>
                    )}
                  </ProjectPermissionCan>
                </DropdownMenuContent>
              </DropdownMenu>
            </div>
          </PageHeader>
          <div className="flex flex-col gap-5 @4xl:flex-row">
            <ProjectIdentityDetailsSection
              identity={identity || { ...identityMembershipDetails?.identity, projectId: "" }}
              isOrgIdentity={isOrgIdentity}
              isSubOrgIdentity={isSubOrgIdentity}
              membership={identityMembershipDetails!}
            />

            <div className="flex min-w-0 flex-1 flex-col gap-y-5">
              {identity ? (
                <ProjectIdentityAuthenticationSection
                  identity={identity}
                  refetchIdentity={() => refetchIdentity()}
                />
              ) : (
                <Card>
                  <CardHeader>
                    <CardTitle>Authentication</CardTitle>
                    <CardDescription>Configure authentication methods</CardDescription>
                  </CardHeader>
                  <CardContent>
                    <Alert variant={isSubOrgIdentity ? "sub-org" : "org"}>
                      {isSubOrgIdentity ? <SubOrgIcon /> : <OrgIcon />}
                      <AlertTitle>
                        Machine identity managed by {isSubOrgIdentity ? "sub-" : ""}organization
                      </AlertTitle>
                      <AlertDescription>
                        <p>
                          This machine identity&apos;s authentication methods are managed by your{" "}
                          {isSubOrgIdentity ? "sub-" : ""}organization
                          <OrgPermissionCan
                            I={OrgPermissionIdentityActions.Read}
                            an={OrgPermissionSubjects.Identity}
                          >
                            {(isAllowed) =>
                              isAllowed ? (
                                <>
                                  <span>
                                    <br /> To make changes,{" "}
                                  </span>
                                  <Link
                                    to="/organizations/$orgId/identities/$identityId"
                                    className="inline-block cursor-pointer text-foreground underline underline-offset-2"
                                    params={{
                                      identityId,
                                      orgId: identityMembershipDetails.identity.orgId
                                    }}
                                  >
                                    go to {isSubOrgIdentity ? "sub-" : ""}organization access
                                    control
                                  </Link>
                                </>
                              ) : null
                            }
                          </OrgPermissionCan>
                          .
                        </p>
                      </AlertDescription>
                    </Alert>
                  </CardContent>
                </Card>
              )}
              {isAgentVault && (
                <IdentityDelegationSection
                  machineIdentityId={identityId}
                  machineIdentityName={identityMembershipDetails.identity.name}
                />
              )}
              {!isAgentVault && (
                <IdentityRoleDetailsSection
                  identityMembershipDetails={identityMembershipDetails}
                  isMembershipDetailsLoading={isMembershipDetailsLoading}
                />
              )}
              {!isStandaloneProduct && currentProject.isLegacyAdditionalPrivilegesEnabled && (
                <IdentityProjectAdditionalPrivilegeSection
                  identityMembershipDetails={identityMembershipDetails}
                />
              )}
              {isSecretManager &&
                !hasFolderRbacPlan &&
                !currentProject.isLegacyAdditionalPrivilegesEnabled && (
                  <AdditionalPrivilegesRemovedSection />
                )}
              {isSecretManager && hasFolderRbacPlan && (
                <FolderAccessSection
                  actor={{
                    type: "identity",
                    id: identityMembershipDetails.identity.id,
                    name: identityMembershipDetails.identity.name
                  }}
                />
              )}
            </div>
          </div>
          <IdentityActionConfirmationDialog
            open={popUp.removeIdentity.isOpen}
            title={`Remove ${identityMembershipDetails.identity.name} from ${
              namesProduct ? accessControlLabel : "the project"
            }?`}
            description={`The machine identity will lose access to ${
              namesProduct ? accessControlLabel : "this project"
            } but remain available in its organization.`}
            descriptionAsAlert
            confirmationText="remove"
            actionLabel="Remove"
            onOpenChange={(isOpen) => handlePopUpToggle("removeIdentity", isOpen)}
            onConfirm={onRemoveIdentitySubmit}
          />
          <AssumePrivilegesDialog
            isOpen={popUp.assumePrivileges.isOpen}
            onOpenChange={(isOpen) => handlePopUpToggle("assumePrivileges", isOpen)}
            actorType={ActorType.IDENTITY}
            actorId={identityId}
          />
          <IdentityActionConfirmationDialog
            open={popUp.deleteIdentity.isOpen}
            title={`Delete ${identity?.name || "machine identity"}?`}
            description={`This permanently deletes the ${
              isCertManager ? "Certificate Manager" : "project"
            } machine identity and revokes its access. This cannot be undone.`}
            descriptionAsAlert
            descriptionAlertVariant="danger"
            confirmationText="confirm"
            actionLabel="Delete"
            onOpenChange={(isOpen) => handlePopUpToggle("deleteIdentity", isOpen)}
            onConfirm={handleDeleteIdentity}
          />
          {isPermissionAuditOpen && (
            <IdentityPermissionAuditSheet
              open={isPermissionAuditOpen}
              onOpenChange={setIsPermissionAuditOpen}
              identityId={identityId}
              targetName={identityMembershipDetails.identity.name}
            />
          )}
        </>
      ) : (
        <Empty>
          <EmptyHeader>
            <EmptyTitle>Machine identity not found</EmptyTitle>
            <EmptyDescription>
              The machine identity may have been removed or you may not have access to it.
            </EmptyDescription>
          </EmptyHeader>
        </Empty>
      )}
    </div>
  );
};

export const IdentityDetailsByIDPage = () => {
  const { t } = useTranslation();

  return (
    <>
      <PageTitle title={t("page-titles.machine-identity")} />
      <link rel="icon" href="/infisical.ico" />
      <ProjectPermissionCan
        I={ProjectPermissionActions.Read}
        a={ProjectPermissionSub.Identity}
        passThrough={false}
        renderGuardBanner
      >
        <Page />
      </ProjectPermissionCan>
    </>
  );
};