Skip to content

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

24.9 KB
Raw Blame
import { useState } from "react";
import { Link, linkOptions } from "@tanstack/react-router";
import { format } from "date-fns";
import {
  BanIcon,
  CircleAlertIcon,
  FilterIcon,
  GlobeIcon,
  IdCardIcon,
  LogsIcon,
  MoreHorizontalIcon,
  PackageIcon,
  PencilIcon,
  PlusIcon,
  SearchIcon,
  TriangleAlertIcon
} from "lucide-react";

import { AgentVaultSessionLogUpgradeModal } from "@app/components/agent-vault/AgentVaultSessionLogUpgradeModal";
import {
  useAgentVaultSetupProgress,
  useOpenAgentVaultSetupStep
} from "@app/components/agent-vault/SetupChecklist";
import { PageTitle } from "@app/components/PageTitle";
import {
  Alert,
  AlertAction,
  AlertDescription,
  Button,
  Card,
  CardAction,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
  DocumentationLinkBadge,
  DropdownMenu,
  DropdownMenuCheckboxItem,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuTrigger,
  Empty,
  EmptyDescription,
  EmptyHeader,
  EmptyTitle,
  IconButton,
  InputGroup,
  InputGroupAddon,
  InputGroupInput,
  OverflowBadgeList,
  PageHeader,
  Pagination,
  Skeleton,
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
  Tabs,
  TabsList,
  TabsTrigger,
  Tooltip,
  TooltipContent,
  TooltipTrigger
} from "@app/components/v3";
import { useOrganization, useProjectPermission, useSubscription } from "@app/context";
import { isAgentVaultSessionLogBlockedByPlan } from "@app/helpers/agentVaultSessionLogs";
import {
  getUserTablePreference,
  PreferenceKey,
  setUserTablePreference
} from "@app/helpers/userTablePreferences";
import { useDebounce, useResetPageHelper } from "@app/hooks";
import {
  AgentVaultSessionScope,
  AgentVaultSessionStatus,
  useGetAgentVaultSession,
  useGetAgentVaultSessionLogHealth,
  useGetAgentVaultSessionLogSettings,
  useListAgentVaultAccessBundles,
  useListAgentVaultSessions
} from "@app/hooks/api/agentVault";
import { AgentVaultSessionLogStorageType } from "@app/hooks/api/agentVault/enums";
import { TAgentVaultMintedSession, TAgentVaultSession } from "@app/hooks/api/agentVault/types";
import { ProjectType } from "@app/hooks/api/projects/types";
import { ProjectMembershipRole } from "@app/hooks/api/roles/types";
import { useAgentVaultCreateIntent } from "@app/hooks/useAgentVaultCreateIntent";
import { useAgentVaultSheetState } from "@app/hooks/useAgentVaultSheetState";
import { SessionLogReadAccessAlert } from "@app/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogReadAccessAlert";

import { AgentVaultDocsUrls } from "../agent-vault-docs-urls";
import { CreateSessionDialog } from "./components/CreateSessionDialog";
import { EditSessionLabelDialog } from "./components/EditSessionLabelDialog";
import { InlineServicesList } from "./components/InlineServicesHoverCard";
import { RevokeSessionDialog } from "./components/RevokeSessionDialog";
import { SampleSessionSheet, SampleSessionTable } from "./components/SampleSessionSheet";
import { SessionCreatedDialog } from "./components/SessionCreatedDialog";
import { SessionDetailSheet } from "./components/SessionDetailSheet";
import { SessionExpiry } from "./components/SessionExpiry";
import { SessionIdentity } from "./components/SessionIdentity";
import {
  inlineServicesLabel,
  toAccessItems,
  TSessionAccessItem
} from "./components/sessionInlineServices";
import { SessionLabel } from "./components/SessionLabel";
import { SESSION_STATUS_PRESENTATION, SessionStatusBadge } from "./components/SessionStatusBadge";

const STATUS_OPTIONS = [
  AgentVaultSessionStatus.Active,
  AgentVaultSessionStatus.Revoked,
  AgentVaultSessionStatus.Expired
];

const accessItemIcon = (item: TSessionAccessItem) =>
  item.kind === "bundle" ? <PackageIcon /> : <GlobeIcon />;

const accessItemHoverCard = (item: TSessionAccessItem) =>
  item.kind === "inline" ? <InlineServicesList services={item.services} /> : undefined;

export const AgentVaultSessionsPage = () => {
  const { currentOrg } = useOrganization();
  const { hasProjectRole } = useProjectPermission();
  const isAdmin = hasProjectRole(ProjectMembershipRole.Admin);

  const [search, setSearch] = useState("");
  const [debouncedSearch] = useDebounce(search);
  const [statuses, setStatuses] = useState<AgentVaultSessionStatus[]>([]);
  const [scope, setScope] = useState(() => {
    const stored = getUserTablePreference(
      "agentVaultSessionsTable",
      PreferenceKey.SessionScope,
      AgentVaultSessionScope.All
    );
    return Object.values(AgentVaultSessionScope).includes(stored)
      ? stored
      : AgentVaultSessionScope.All;
  });
  const [page, setPage] = useState(1);
  const [perPage, setPerPage] = useState(() =>
    getUserTablePreference("agentVaultSessionsTable", PreferenceKey.PerPage, 20)
  );
  const [sessionToRevoke, setSessionToRevoke] = useState<TAgentVaultSession | null>(null);
  const [sessionToLabel, setSessionToLabel] = useState<TAgentVaultSession | null>(null);
  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
  const [mintedSession, setMintedSession] = useState<TAgentVaultMintedSession | null>(null);
  const [isSampleOpen, setIsSampleOpen] = useState(false);
  const { id: openSessionId, openSheet } = useAgentVaultSheetState();

  const { data, isPending } = useListAgentVaultSessions({
    scope: isAdmin ? scope : AgentVaultSessionScope.Mine,
    statuses,
    search: debouncedSearch.trim() || undefined,
    limit: perPage,
    offset: (page - 1) * perPage
  });
  const { data: accessBundles } = useListAgentVaultAccessBundles({ limit: 1 });
  const { data: sessionLogState } = useGetAgentVaultSessionLogSettings(isAdmin);
  const { data: sessionLogHealth } = useGetAgentVaultSessionLogHealth(isAdmin);
  const { subscription } = useSubscription();
  const [isUpgradeOpen, setIsUpgradeOpen] = useState(false);
  const sessionLogSettings = sessionLogState?.settings ?? null;
  // Covers a saved choice the plan dropped and the unsaved default the plan never included.
  const isSessionLogBlockedByPlan = isAgentVaultSessionLogBlockedByPlan(
    sessionLogSettings,
    subscription
  );

  const sessions = data?.sessions ?? [];
  const totalCount = data?.totalCount ?? 0;

  const loadedOpenSession = sessions.find((session) => session.id === openSessionId);
  const { data: fetchedOpenSession, isPending: isFetchingOpenSession } =
    useGetAgentVaultSession(openSessionId);
  const openSession = fetchedOpenSession ?? loadedOpenSession;
  const isOpenSessionPending = Boolean(openSessionId) && !openSession && isFetchingOpenSession;

  useResetPageHelper({ totalCount, offset: (page - 1) * perPage, setPage });

  // The debounced term, not the typed one: the rows on screen were fetched with this, so keying the copy
  // off the live input would caption a stale result set.
  const isFiltered = Boolean(debouncedSearch.trim()) || statuses.length > 0;
  const hasReachableBundles = (accessBundles?.totalCount ?? 0) > 0;
  useAgentVaultCreateIntent(() => setIsCreateDialogOpen(true), hasReachableBundles);

  const setupProgress = useAgentVaultSetupProgress();
  const openSetupStep = useOpenAgentVaultSetupStep(setupProgress);
  // An admin sees the sample only while the org has no session at all. A member can't list the org's
  // sessions, so they see it while they have none of their own.
  const isSampleShown =
    !isFiltered && (!isAdmin || (setupProgress.isSessionCountLoaded && !setupProgress.hasSession));
  // Offered only once the next step is known; until then there's nowhere to send the admin.
  const { nextStep } = setupProgress;
  const startSetup = nextStep
    ? () => {
        setupProgress.restore();
        setIsSampleOpen(false);
        openSetupStep(nextStep);
      }
    : undefined;

  let emptyTitle: string;
  let emptyDescription: string;
  if (isFiltered) {
    emptyTitle = "No sessions match these filters";
    emptyDescription = "Try a different search term or status.";
  } else if (!hasReachableBundles) {
    emptyTitle = isAdmin ? "No sessions yet" : "No access bundles granted to you";
    emptyDescription = isAdmin
      ? "Create an access bundle first, then create a session with it. Agents also need a proxy to route through."
      : "Ask an admin to grant you an access bundle.";
  } else {
    emptyTitle = "No sessions yet";
    emptyDescription = "Create a session to get a token an agent can run with.";
  }

  const emptyState = !isSampleShown ? (
    <CardContent>
      <Empty className="border">
        <EmptyHeader>
          <EmptyTitle>{emptyTitle}</EmptyTitle>
          <EmptyDescription>{emptyDescription}</EmptyDescription>
        </EmptyHeader>
        {!isFiltered && !hasReachableBundles && isAdmin && (
          <Button variant="av" asChild>
            <Link
              to="/organizations/$orgId/agent-vault/access-bundles"
              params={{ orgId: currentOrg.id }}
            >
              Go to Access Bundles
            </Link>
          </Button>
        )}
      </Empty>
    </CardContent>
  ) : (
    <>
      <SampleSessionTable onOpen={() => setIsSampleOpen(true)} />
      <CardContent className="flex items-center justify-between gap-4">
        <span className="text-sm text-muted">
          {emptyDescription} Open the sample to see what a session records.
        </span>
        {!hasReachableBundles && isAdmin && (
          <Button variant="av" size="sm" asChild>
            <Link
              to="/organizations/$orgId/agent-vault/access-bundles"
              params={{ orgId: currentOrg.id }}
            >
              Go to Access Bundles
            </Link>
          </Button>
        )}
      </CardContent>
    </>
  );

  return (
    <div className="mx-auto mb-6 flex w-full max-w-8xl flex-col">
      <PageTitle title="Sessions" />
      <PageHeader
        scope={ProjectType.AgentVault}
        icon={IdCardIcon}
        title="Sessions"
        description="Create sessions that let your agents reach the services they need."
      />

      <div className="flex flex-col gap-8">
        {sessionLogHealth?.connectionError &&
          sessionLogSettings?.enabled &&
          !isSessionLogBlockedByPlan && (
            <Alert variant="danger">
              <CircleAlertIcon />
              <AlertDescription>
                <p>{sessionLogHealth.connectionError}</p>
                <AlertAction>
                  <Button variant="outline" size="sm" asChild>
                    <Link
                      to="/organizations/$orgId/agent-vault/settings"
                      params={{ orgId: currentOrg.id }}
                    >
                      Go to Settings
                    </Link>
                  </Button>
                </AlertAction>
              </AlertDescription>
            </Alert>
          )}

        {isSessionLogBlockedByPlan && (
          <Alert variant="warning">
            <TriangleAlertIcon />
            <AlertDescription>
              <p>
                {sessionLogSettings?.storage.type === AgentVaultSessionLogStorageType.External
                  ? "Your plan no longer includes external storage. Upgrade to see recorded logs and keep recording. Recorded logs stay in your bucket."
                  : "Your plan doesn't include default storage, so session logs aren't being recorded. Upgrade to record and view them."}
              </p>
              <AlertAction>
                <Button variant="outline" size="sm" onClick={() => setIsUpgradeOpen(true)}>
                  Upgrade
                </Button>
              </AlertAction>
            </AlertDescription>
          </Alert>
        )}

        {sessionLogSettings && !sessionLogSettings.enabled && (
          <Alert variant="warning">
            <TriangleAlertIcon />
            <AlertDescription>
              <p>
                Sessions aren&apos;t being logged, so there is no record of what your agents
                reached.
              </p>
              <AlertAction>
                <Button variant="outline" size="sm" asChild>
                  <Link
                    to="/organizations/$orgId/agent-vault/settings"
                    params={{ orgId: currentOrg.id }}
                  >
                    Go to Settings
                  </Link>
                </Button>
              </AlertAction>
            </AlertDescription>
          </Alert>
        )}

        {isAdmin && !sessionLogHealth?.connectionError && <SessionLogReadAccessAlert />}

        <Card>
          <CardHeader>
            <CardTitle>
              Sessions
              <DocumentationLinkBadge href={AgentVaultDocsUrls.sessions} />
            </CardTitle>
            <CardDescription>
              A session names the actor who holds it, the services it can reach, and when it
              expires.
            </CardDescription>
            <CardAction>
              <Button
                variant="av"
                isDisabled={!hasReachableBundles}
                onClick={() => setIsCreateDialogOpen(true)}
              >
                <PlusIcon />
                Create Session
              </Button>
            </CardAction>
          </CardHeader>
          <CardContent className="flex items-center gap-2">
            <InputGroup className="flex-1">
              <InputGroupAddon>
                <SearchIcon />
              </InputGroupAddon>
              <InputGroupInput
                value={search}
                onChange={(e) => {
                  setSearch(e.target.value);
                  setPage(1);
                }}
                maxLength={255}
                placeholder="Search by label, identity, email, or access bundle..."
              />
            </InputGroup>
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <IconButton
                  aria-label="Filter sessions"
                  variant={statuses.length ? "av" : "outline"}
                >
                  <FilterIcon />
                </IconButton>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                <DropdownMenuLabel>Status</DropdownMenuLabel>
                {STATUS_OPTIONS.map((status) => {
                  const { label, icon: Icon, iconClassName } = SESSION_STATUS_PRESENTATION[status];
                  return (
                    <DropdownMenuCheckboxItem
                      key={status}
                      checked={statuses.includes(status)}
                      onClick={(e) => {
                        e.preventDefault();
                        setStatuses((prev) =>
                          prev.includes(status)
                            ? prev.filter((s) => s !== status)
                            : [...prev, status]
                        );
                        setPage(1);
                      }}
                    >
                      <Icon className={iconClassName} />
                      {label}
                    </DropdownMenuCheckboxItem>
                  );
                })}
              </DropdownMenuContent>
            </DropdownMenu>
            {isAdmin && (
              <Tabs
                value={scope}
                onValueChange={(value) => {
                  setScope(value as AgentVaultSessionScope);
                  setPage(1);
                  setUserTablePreference(
                    "agentVaultSessionsTable",
                    PreferenceKey.SessionScope,
                    value
                  );
                }}
              >
                <TabsList variant="filled">
                  <TabsTrigger value={AgentVaultSessionScope.All}>All Sessions</TabsTrigger>
                  <TabsTrigger value={AgentVaultSessionScope.Mine}>My Sessions</TabsTrigger>
                </TabsList>
              </Tabs>
            )}
          </CardContent>

          {!isPending && sessions.length === 0 ? (
            emptyState
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  {/* w-px holds the column to its capped content, so a long label truncates at the column's edge */}
                  <TableHead className="w-px">Label</TableHead>
                  <TableHead>Identity</TableHead>
                  <TableHead>Access</TableHead>
                  <TableHead>Created</TableHead>
                  <TableHead>Expires</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead variant="action" />
                </TableRow>
              </TableHeader>
              <TableBody>
                {isPending &&
                  Array.from({ length: 5 }).map((_, index) => (
                    // eslint-disable-next-line react/no-array-index-key
                    <TableRow key={`session-skeleton-${index}`}>
                      {Array.from({ length: 7 }).map((__, cell) => (
                        // eslint-disable-next-line react/no-array-index-key
                        <TableCell key={`session-skeleton-${index}-${cell}`}>
                          <Skeleton className="h-4 w-full" />
                        </TableCell>
                      ))}
                    </TableRow>
                  ))}
                {!isPending &&
                  sessions.map((session) => (
                    <TableRow
                      key={session.id}
                      onClick={() => openSheet(session.id)}
                      className="cursor-pointer"
                    >
                      <TableCell>
                        {session.label ? (
                          <SessionLabel label={session.label} className="max-w-60" />
                        ) : (
                          <span className="text-muted">—</span>
                        )}
                      </TableCell>
                      <TableCell>
                        <SessionIdentity session={session} />
                      </TableCell>
                      <TableCell>
                        <div className="max-w-72">
                          <OverflowBadgeList
                            items={toAccessItems(session)}
                            getKey={(item) =>
                              item.kind === "bundle"
                                ? `bundle:${item.bundle.id ?? item.bundle.name}`
                                : "inline"
                            }
                            getLabel={(item) =>
                              item.kind === "bundle"
                                ? item.bundle.name
                                : inlineServicesLabel(item.services.length)
                            }
                            getIcon={accessItemIcon}
                            getClassName={(item) =>
                              item.kind === "bundle" && !item.bundle.id ? "text-muted" : undefined
                            }
                            getHoverCard={accessItemHoverCard}
                            getTooltip={(item) =>
                              item.kind === "bundle" && !item.bundle.id
                                ? `${item.bundle.name} (deleted)`
                                : undefined
                            }
                            getLinkProps={(item) =>
                              item.kind === "bundle" && item.bundle.id
                                ? linkOptions({
                                    to: "/organizations/$orgId/agent-vault/access-bundles/$accessBundleId",
                                    params: { orgId: currentOrg.id, accessBundleId: item.bundle.id }
                                  })
                                : undefined
                            }
                          />
                        </div>
                      </TableCell>
                      <TableCell className="whitespace-nowrap">
                        {format(new Date(session.createdAt), "MMM dd, yyyy hh:mm a")}
                      </TableCell>
                      <TableCell>
                        {session.status === AgentVaultSessionStatus.Revoked ? (
                          <span className="text-muted">—</span>
                        ) : (
                          <SessionExpiry expiresAt={session.expiresAt} />
                        )}
                      </TableCell>
                      <TableCell>
                        <SessionStatusBadge status={session.status} />
                      </TableCell>
                      <TableCell variant="action">
                        <div className="flex items-center justify-end gap-1">
                          <Tooltip>
                            <TooltipTrigger asChild>
                              <IconButton
                                variant="ghost"
                                size="xs"
                                aria-label="View session logs"
                                onClick={(event) => {
                                  event.stopPropagation();
                                  openSheet(session.id);
                                }}
                              >
                                <LogsIcon />
                              </IconButton>
                            </TooltipTrigger>
                            <TooltipContent>View Session Logs</TooltipContent>
                          </Tooltip>
                          <DropdownMenu>
                            <DropdownMenuTrigger asChild>
                              <IconButton
                                variant="ghost"
                                size="xs"
                                aria-label="Open session actions"
                                onClick={(event) => event.stopPropagation()}
                              >
                                <MoreHorizontalIcon />
                              </IconButton>
                            </DropdownMenuTrigger>
                            <DropdownMenuContent
                              sideOffset={2}
                              align="end"
                              onClick={(event) => event.stopPropagation()}
                            >
                              <DropdownMenuItem onClick={() => openSheet(session.id)}>
                                <LogsIcon />
                                View Session Logs
                              </DropdownMenuItem>
                              {/* The API refuses label edits once the session's owner, or the user it acts on behalf of, is deleted */}
                              {session.actor.id !== null && session.onBehalfOf?.id !== null && (
                                <DropdownMenuItem onClick={() => setSessionToLabel(session)}>
                                  <PencilIcon />
                                  {session.label ? "Edit Label" : "Add Label"}
                                </DropdownMenuItem>
                              )}
                              <DropdownMenuItem
                                variant="danger"
                                isDisabled={session.status !== AgentVaultSessionStatus.Active}
                                onClick={() => setSessionToRevoke(session)}
                              >
                                <BanIcon />
                                Revoke Session
                              </DropdownMenuItem>
                            </DropdownMenuContent>
                          </DropdownMenu>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
              </TableBody>
            </Table>
          )}

          {totalCount > 0 && (
            <CardContent className="-mt-5 pt-0">
              <Pagination
                count={totalCount}
                page={page}
                perPage={perPage}
                onChangePage={setPage}
                onChangePerPage={(newPerPage) => {
                  setPerPage(newPerPage);
                  setPage(1);
                  setUserTablePreference(
                    "agentVaultSessionsTable",
                    PreferenceKey.PerPage,
                    newPerPage
                  );
                }}
              />
            </CardContent>
          )}
        </Card>
      </div>

      <CreateSessionDialog
        isOpen={isCreateDialogOpen}
        onOpenChange={setIsCreateDialogOpen}
        onCreated={setMintedSession}
      />

      <SessionCreatedDialog
        session={mintedSession}
        onOpenChange={(isOpen) => {
          if (!isOpen) setMintedSession(null);
        }}
      />

      <RevokeSessionDialog
        session={sessionToRevoke}
        onOpenChange={(isOpen) => {
          if (!isOpen) setSessionToRevoke(null);
        }}
      />

      <SampleSessionSheet
        isOpen={isSampleOpen}
        onOpenChange={setIsSampleOpen}
        onSetUp={isAdmin ? startSetup : undefined}
      />

      <SessionDetailSheet
        session={openSession}
        isPending={isOpenSessionPending}
        onRevoke={setSessionToRevoke}
        onEditLabel={setSessionToLabel}
      />

      <EditSessionLabelDialog
        session={sessionToLabel}
        onOpenChange={(isOpen) => {
          if (!isOpen) setSessionToLabel(null);
        }}
      />

      <AgentVaultSessionLogUpgradeModal
        isOpen={isUpgradeOpen}
        onOpenChange={setIsUpgradeOpen}
        storageType={sessionLogSettings?.storage.type}
      />
    </div>
  );
};