Skip to content

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

30.2 KB
Raw Blame
import { useCallback, useState } from "react";
import { subject } from "@casl/ability";
import {
  ChevronDownIcon,
  FilterIcon,
  InfoIcon,
  LockIcon,
  MoreHorizontalIcon,
  PlusIcon,
  SearchIcon,
  TrashIcon
} from "lucide-react";
import { twMerge } from "tailwind-merge";

import { AssumePrivilegesDialog } from "@app/components/assume-privileges";
import { createNotification } from "@app/components/notifications";
import { ProjectPermissionCan } from "@app/components/permissions";
import {
  Badge,
  Blur,
  Button,
  Card,
  CardAction,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
  DocumentationLinkBadge,
  DropdownMenu,
  DropdownMenuCheckboxItem,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSub,
  DropdownMenuSubContent,
  DropdownMenuSubTrigger,
  DropdownMenuTrigger,
  Empty,
  EmptyDescription,
  EmptyHeader,
  EmptyTitle,
  IconButton,
  IdentityRoleBadges,
  InputGroup,
  InputGroupAddon,
  InputGroupInput,
  OrgIcon,
  Pagination,
  ProjectIcon,
  RowLink,
  Skeleton,
  Spinner,
  SubOrgIcon,
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
  Tooltip,
  TooltipContent,
  TooltipTrigger
} from "@app/components/v3";
import {
  ProjectPermissionActions,
  ProjectPermissionIdentityActions,
  ProjectPermissionSub,
  useOrganization,
  useProject
} from "@app/context";
import {
  getInstancePinningLink,
  getProjectBaseURL,
  getProjectLabel,
  hidesProjects
} from "@app/helpers/project";
import {
  getUserTablePreference,
  PreferenceKey,
  setUserTablePreference
} from "@app/helpers/userTablePreferences";
import { withProjectPermission } from "@app/hoc";
import { usePagination, useResetPageHelper, useScopeVariant } from "@app/hooks";
import {
  IdentityAuthMethod,
  identityAuthToNameMap,
  useDeleteProjectIdentity,
  useDeleteProjectIdentityMembership,
  useGetProjectRoles,
  useListProjectIdentityMemberships
} from "@app/hooks/api";
import { ActorType } from "@app/hooks/api/auditLogs/enums";
import { OrderByDirection } from "@app/hooks/api/generic/types";
import { ProjectIdentityOrderBy } from "@app/hooks/api/projects/types";
import { usePopUp } from "@app/hooks/usePopUp";
import { IdentityAuthMethodModal } from "@app/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAuthMethodModal";
import { IdentityActionConfirmationDialog } from "@app/pages/project/IdentityDetailsByIDPage/components/IdentityActionConfirmationDialog";
import { IdentityAuthMethodSheet } from "@app/views/IdentityAuthMethods";

import { CreateProjectIdentitySheet } from "./components/CreateProjectIdentity/CreateProjectIdentitySheet";

export const IdentityTab = withProjectPermission(
  () => {
    const scopeVariant = useScopeVariant();
    const { currentProject, projectId } = useProject();
    const { isSubOrganization, currentOrg } = useOrganization();
    const productLabel = getProjectLabel(currentProject?.type);
    const projectsHidden = hidesProjects(currentProject?.type);

    const {
      offset,
      limit,
      orderBy,
      orderDirection,
      setOrderDirection,
      search,
      debouncedSearch,
      setPage,
      setSearch,
      perPage,
      page,
      setPerPage
    } = usePagination(ProjectIdentityOrderBy.Name, {
      initPerPage: getUserTablePreference("projectIdentityTable", PreferenceKey.PerPage, 20)
    });

    const handlePerPageChange = (newPerPage: number) => {
      setPerPage(newPerPage);
      setUserTablePreference("projectIdentityTable", PreferenceKey.PerPage, newPerPage);
    };

    const { data: projectRoles } = useGetProjectRoles(projectId, currentProject?.type);

    const [filterRoles, setFilterRoles] = useState<string[]>([]);
    const isTableFiltered = Boolean(filterRoles.length);

    const handleRoleToggle = useCallback(
      (roleSlug: string) =>
        setFilterRoles((prev) => {
          const next = prev.includes(roleSlug)
            ? prev.filter((r) => r !== roleSlug)
            : [...prev, roleSlug];
          setPage(1);
          return next;
        }),
      []
    );

    const { data, isPending, isFetching, refetch } = useListProjectIdentityMemberships(
      {
        projectId,
        projectType: currentProject?.type,
        offset,
        limit,
        orderDirection,
        orderBy,
        search: debouncedSearch,
        roles: filterRoles
      },
      { placeholderData: (prevData) => prevData }
    );

    const { totalCount = 0 } = data ?? {};

    useResetPageHelper({
      totalCount,
      offset,
      setPage
    });

    const { mutateAsync: deleteMembershipMutateAsync } = useDeleteProjectIdentityMembership();
    const { mutateAsync: deleteProjectIdentity } = useDeleteProjectIdentity();

    const { popUp, handlePopUpOpen, handlePopUpClose, handlePopUpToggle } = usePopUp([
      "createIdentity",
      "deleteIdentity",
      "upgradePlan",
      "addOptions",
      "identityAuthMethod",
      "assumePrivileges"
    ] as const);

    const [viewAuthMethodState, setViewAuthMethodState] = useState<{
      identityId: string;
      authMethod: IdentityAuthMethod;
    } | null>(null);

    const onRemoveIdentitySubmit = async (identityId: string, isProjectIdentity: boolean) => {
      if (isProjectIdentity) {
        await deleteProjectIdentity({
          identityId,
          projectId
        });

        createNotification({
          text: `Successfully deleted ${projectsHidden ? productLabel : "project"} machine identity`,
          type: "success"
        });
      } else {
        await deleteMembershipMutateAsync({
          identityId,
          projectId,
          projectType: currentProject?.type
        });

        createNotification({
          text: `Successfully removed machine identity from ${projectsHidden ? productLabel : "project"}`,
          type: "success"
        });
      }

      handlePopUpClose("deleteIdentity");
    };
    const noAccessIdentityCount = Math.max(
      (page * perPage > totalCount ? totalCount % perPage : perPage) -
        (data?.identityMemberships?.length || 0),
      0
    );

    return (
      <>
        <Card>
          <CardHeader>
            <CardTitle>
              {projectsHidden ? "Machine Identities" : `${productLabel} Machine Identities`}
              <DocumentationLinkBadge href="https://infisical.com/docs/documentation/platform/identities/machine-identities" />
            </CardTitle>
            <CardDescription>
              {`Create and manage ${productLabel.toLowerCase()} machine identities`}
            </CardDescription>
            <CardAction>
              <ProjectPermissionCan
                I={ProjectPermissionActions.Create}
                a={ProjectPermissionSub.Identity}
              >
                {(isAllowed) => (
                  <Button
                    variant={scopeVariant}
                    onClick={() => handlePopUpOpen("createIdentity")}
                    isDisabled={!isAllowed}
                  >
                    <PlusIcon />
                    {projectsHidden
                      ? "Add Machine Identity"
                      : `Add Machine Identity to ${productLabel}`}
                  </Button>
                )}
              </ProjectPermissionCan>
            </CardAction>
          </CardHeader>
          <CardContent>
            <div>
              <div className="mb-4 flex gap-2">
                <InputGroup className="flex-1">
                  <InputGroupAddon>
                    <SearchIcon />
                  </InputGroupAddon>
                  <InputGroupInput
                    value={search}
                    onChange={(e) => setSearch(e.target.value)}
                    placeholder={
                      projectsHidden
                        ? "Search machine identities by name..."
                        : "Search project machine identities by name..."
                    }
                  />
                </InputGroup>
                <DropdownMenu>
                  <DropdownMenuTrigger asChild>
                    <IconButton
                      aria-label="Filter machine identities"
                      variant={isTableFiltered ? scopeVariant : "outline"}
                    >
                      <FilterIcon />
                    </IconButton>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent align="end">
                    <DropdownMenuLabel>
                      {projectsHidden ? "Filter by Role" : `Filter by ${productLabel} Role`}
                    </DropdownMenuLabel>
                    {projectRoles?.map(({ id, slug, name }) => (
                      <DropdownMenuCheckboxItem
                        key={id}
                        checked={filterRoles.includes(slug)}
                        onClick={(e) => {
                          e.preventDefault();
                          handleRoleToggle(slug);
                        }}
                      >
                        {name}
                      </DropdownMenuCheckboxItem>
                    ))}
                  </DropdownMenuContent>
                </DropdownMenu>
              </div>
              {!isPending && data && data.totalCount === 0 ? (
                <Empty className="border">
                  <EmptyHeader>
                    <EmptyTitle>
                      {/* eslint-disable-next-line no-nested-ternary */}
                      {debouncedSearch.trim().length > 0 || isTableFiltered
                        ? "No machine identities match search"
                        : projectsHidden
                          ? "No machine identities have been added"
                          : "No machine identities have been added to this project"}
                    </EmptyTitle>
                    <EmptyDescription>
                      {debouncedSearch.trim().length > 0 || isTableFiltered
                        ? "Adjust your search or filter criteria."
                        : "Add a machine identity to get started."}
                    </EmptyDescription>
                  </EmptyHeader>
                </Empty>
              ) : (
                <>
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead
                          className="w-1/4"
                          sortDirection={
                            orderDirection === OrderByDirection.ASC ? "ascending" : "descending"
                          }
                          onSortChange={(direction) =>
                            setOrderDirection(
                              direction === "descending"
                                ? OrderByDirection.DESC
                                : OrderByDirection.ASC
                            )
                          }
                        >
                          Name
                          <ChevronDownIcon
                            className={twMerge(
                              "transition-transform",
                              orderDirection === OrderByDirection.DESC && "rotate-180"
                            )}
                          />
                        </TableHead>
                        <TableHead className="w-1/4">
                          {projectsHidden ? "Role" : `${productLabel} Role`}
                        </TableHead>
                        <TableHead>Managed by</TableHead>
                        <TableHead className="w-5">
                          {isFetching ? (
                            <Spinner size="xs" label="Refreshing machine identities" />
                          ) : null}
                        </TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {isPending &&
                        Array.from({ length: 10 }).map((_, i) => (
                          <TableRow key={`skeleton-${i + 1}`}>
                            <TableCell>
                              <Skeleton className="h-4 w-full" />
                            </TableCell>
                            <TableCell>
                              <Skeleton className="h-4 w-full" />
                            </TableCell>
                            <TableCell>
                              <Skeleton className="h-4 w-full" />
                            </TableCell>
                            <TableCell>
                              <Skeleton className="h-4 w-4" />
                            </TableCell>
                          </TableRow>
                        ))}
                      {!isPending &&
                        data &&
                        (data.identityMemberships ?? []).length > 0 &&
                        (data.identityMemberships ?? []).map((identityMember) => {
                          const {
                            identity: {
                              id,
                              name,
                              projectId: identityProjectId,
                              orgId: identityOrgId,
                              authMethods,
                              activeLockoutAuthMethods
                            },
                            roles
                          } = identityMember;
                          return (
                            <TableRow linked key={`st-v3-${id}`}>
                              <TableCell isTruncatable>
                                <RowLink
                                  {...(getInstancePinningLink(
                                    currentOrg.id,
                                    currentProject,
                                    `identities/${id}`
                                  ) ??
                                    ({
                                      to: `${getProjectBaseURL(currentProject.type)}/identities/$identityId`,
                                      params: {
                                        orgId: currentOrg.id,
                                        projectId: currentProject.id,
                                        identityId: id
                                      }
                                    } as const))}
                                >
                                  {name}
                                </RowLink>
                              </TableCell>
                              <TableCell>
                                <IdentityRoleBadges roles={roles} />
                              </TableCell>
                              <TableCell>
                                <Badge
                                  variant={
                                    // eslint-disable-next-line no-nested-ternary
                                    identityProjectId
                                      ? scopeVariant
                                      : isSubOrganization && currentOrg.id === identityOrgId
                                        ? "sub-org"
                                        : "org"
                                  }
                                >
                                  {/* eslint-disable-next-line no-nested-ternary */}
                                  {identityProjectId ? (
                                    <>
                                      <ProjectIcon />
                                      {productLabel}
                                    </>
                                  ) : isSubOrganization && currentOrg.id === identityOrgId ? (
                                    <>
                                      <SubOrgIcon />
                                      Sub-Organization
                                    </>
                                  ) : (
                                    <>
                                      <OrgIcon />
                                      Organization
                                    </>
                                  )}
                                </Badge>
                              </TableCell>
                              <TableCell data-row-interactive>
                                <div className="flex items-center justify-end gap-2">
                                  {(activeLockoutAuthMethods?.length ?? 0) > 0 && (
                                    <Tooltip>
                                      <TooltipTrigger asChild>
                                        <Badge isSquare variant="danger">
                                          <span className="sr-only">
                                            {`Locked out: ${(activeLockoutAuthMethods ?? [])
                                              .map((method) => identityAuthToNameMap[method])
                                              .join(", ")}`}
                                          </span>
                                          <LockIcon />
                                        </Badge>
                                      </TooltipTrigger>
                                      <TooltipContent>
                                        {`Locked out: ${(activeLockoutAuthMethods ?? [])
                                          .map((m) => identityAuthToNameMap[m])
                                          .join(", ")}`}
                                      </TooltipContent>
                                    </Tooltip>
                                  )}
                                  <DropdownMenu>
                                    <DropdownMenuTrigger asChild>
                                      <IconButton
                                        aria-label={`Open actions for ${name}`}
                                        variant="ghost"
                                        size="xs"
                                        onClick={(e) => e.stopPropagation()}
                                      >
                                        <MoreHorizontalIcon />
                                      </IconButton>
                                    </DropdownMenuTrigger>
                                    <DropdownMenuContent sideOffset={2} align="end">
                                      {identityProjectId && (
                                        <DropdownMenuSub>
                                          <DropdownMenuSubTrigger chevronOnLeft>
                                            Manage Auth Methods
                                          </DropdownMenuSubTrigger>
                                          <DropdownMenuSubContent>
                                            {(authMethods ?? []).map((method) => (
                                              <DropdownMenuItem
                                                key={method}
                                                onClick={(evt) => {
                                                  evt.stopPropagation();
                                                  evt.preventDefault();
                                                  setViewAuthMethodState({
                                                    identityId: id,
                                                    authMethod: method
                                                  });
                                                }}
                                              >
                                                {identityAuthToNameMap[method]}
                                                {activeLockoutAuthMethods?.includes(method) && (
                                                  <Badge
                                                    isSquare
                                                    variant="danger"
                                                    className="ml-auto"
                                                  >
                                                    <span className="sr-only">Locked out</span>
                                                    <LockIcon className="size-3!" />
                                                  </Badge>
                                                )}
                                              </DropdownMenuItem>
                                            ))}
                                            <ProjectPermissionCan
                                              I={ProjectPermissionIdentityActions.EditAuth}
                                              a={subject(ProjectPermissionSub.Identity, {
                                                identityId: id
                                              })}
                                            >
                                              {(isAllowed) => (
                                                <DropdownMenuItem
                                                  isDisabled={!isAllowed}
                                                  onClick={(evt) => {
                                                    evt.stopPropagation();
                                                    evt.preventDefault();
                                                    handlePopUpOpen("identityAuthMethod", {
                                                      identityId: id,
                                                      name,
                                                      allAuthMethods: authMethods ?? []
                                                    });
                                                  }}
                                                >
                                                  <PlusIcon />
                                                  Add Auth Method
                                                </DropdownMenuItem>
                                              )}
                                            </ProjectPermissionCan>
                                          </DropdownMenuSubContent>
                                        </DropdownMenuSub>
                                      )}
                                      <ProjectPermissionCan
                                        I={ProjectPermissionIdentityActions.AssumePrivileges}
                                        a={subject(ProjectPermissionSub.Identity, {
                                          identityId: id
                                        })}
                                      >
                                        {(isAllowed) => (
                                          <Tooltip>
                                            <TooltipTrigger className="block w-full">
                                              <DropdownMenuItem
                                                isDisabled={!isAllowed}
                                                onClick={(evt) => {
                                                  evt.stopPropagation();
                                                  evt.preventDefault();
                                                  handlePopUpOpen("assumePrivileges", {
                                                    identityId: id
                                                  });
                                                }}
                                              >
                                                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: id
                                        })}
                                      >
                                        {(isAllowed) => (
                                          <DropdownMenuItem
                                            variant="danger"
                                            isDisabled={!isAllowed}
                                            onClick={(evt) => {
                                              evt.stopPropagation();
                                              evt.preventDefault();
                                              handlePopUpOpen("deleteIdentity", {
                                                identityId: id,
                                                name,
                                                isProjectIdentity: Boolean(identityProjectId)
                                              });
                                            }}
                                          >
                                            {identityProjectId && <TrashIcon />}
                                            {identityProjectId
                                              ? "Delete Machine Identity"
                                              : `Remove From ${productLabel}`}
                                          </DropdownMenuItem>
                                        )}
                                      </ProjectPermissionCan>
                                    </DropdownMenuContent>
                                  </DropdownMenu>
                                </div>
                              </TableCell>
                            </TableRow>
                          );
                        })}
                      {!isPending &&
                        data &&
                        data?.totalCount !== 0 &&
                        Array.from(Array(noAccessIdentityCount)).map((_e, i) => (
                          <TableRow key={`hid-identity-${i + 1}`}>
                            <TableCell>
                              <div className="flex items-center gap-2">
                                <LockIcon className="size-4 text-muted" aria-hidden="true" />
                                <Blur
                                  className="w-min p-0"
                                  aria-label="Restricted machine identity"
                                  tooltipText="You do not have permission to view this machine identity."
                                />
                              </div>
                            </TableCell>
                            <TableCell className="text-muted">—</TableCell>
                            <TableCell className="text-muted">—</TableCell>
                            <TableCell />
                          </TableRow>
                        ))}
                    </TableBody>
                  </Table>
                  {!isPending && data && totalCount > 0 && (
                    <Pagination
                      count={totalCount}
                      page={page}
                      perPage={perPage}
                      onChangePage={(newPage) => setPage(newPage)}
                      onChangePerPage={handlePerPageChange}
                    />
                  )}
                </>
              )}
            </div>
          </CardContent>
        </Card>
        <CreateProjectIdentitySheet
          isOpen={popUp.createIdentity.isOpen}
          onOpenChange={(open) => handlePopUpToggle("createIdentity", open)}
        />
        <IdentityActionConfirmationDialog
          open={popUp.deleteIdentity.isOpen}
          title={
            popUp.deleteIdentity.data?.isProjectIdentity
              ? `Delete ${popUp.deleteIdentity.data?.name || "machine identity"}?`
              : `Remove ${popUp.deleteIdentity.data?.name || "machine identity"} from ${productLabel}?`
          }
          description={
            popUp.deleteIdentity.data?.isProjectIdentity
              ? `This permanently deletes the ${projectsHidden ? productLabel : "project"} machine identity and revokes its access. This cannot be undone.`
              : `The machine identity will lose access to this ${productLabel.toLowerCase()} but remain available in its organization.`
          }
          descriptionAsAlert
          descriptionAlertVariant={
            popUp.deleteIdentity.data?.isProjectIdentity ? "danger" : "warning"
          }
          confirmationText="confirm"
          actionLabel={popUp.deleteIdentity.data?.isProjectIdentity ? "Delete" : "Remove"}
          onOpenChange={(isOpen) => handlePopUpToggle("deleteIdentity", isOpen)}
          onConfirm={() =>
            onRemoveIdentitySubmit(
              popUp?.deleteIdentity?.data?.identityId,
              popUp?.deleteIdentity?.data?.isProjectIdentity
            )
          }
        />
        <IdentityAuthMethodModal
          popUp={popUp}
          handlePopUpOpen={handlePopUpOpen}
          handlePopUpToggle={handlePopUpToggle}
        />
        {viewAuthMethodState &&
          (() => {
            const viewedIdentity = data?.identityMemberships?.find(
              (m) => m.identity.id === viewAuthMethodState.identityId
            )?.identity;
            if (!viewedIdentity) return null;
            return (
              <IdentityAuthMethodSheet
                open
                onOpenChange={(open) => {
                  if (!open) setViewAuthMethodState(null);
                }}
                identityId={viewAuthMethodState.identityId}
                identityName={viewedIdentity.name}
                authMethod={viewAuthMethodState.authMethod}
                allAuthMethods={viewedIdentity.authMethods ?? []}
                isLockedOut={
                  viewedIdentity.activeLockoutAuthMethods?.includes(
                    viewAuthMethodState.authMethod
                  ) ?? false
                }
                onMutated={refetch}
              />
            );
          })()}
        <AssumePrivilegesDialog
          isOpen={popUp.assumePrivileges.isOpen}
          onOpenChange={(isOpen) => handlePopUpToggle("assumePrivileges", isOpen)}
          actorType={ActorType.IDENTITY}
          actorId={(popUp.assumePrivileges.data as { identityId: string })?.identityId}
        />
      </>
    );
  },
  {
    action: ProjectPermissionActions.Read,
    subject: ProjectPermissionSub.Identity,
    accessRestrictedMode: "dialog"
  }
);