Skip to content

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

9.8 KB
Raw Blame
import { useQuery } from "@tanstack/react-query";
import { Link } from "@tanstack/react-router";
import { GlobeIcon, Layers3Icon, type LucideIcon, ServerIcon } from "lucide-react";

import { useOrganization, useOrgPermission, useSubscription } from "@app/context";
import {
  OrgGatewayPermissionActions,
  OrgGatewayPoolPermissionActions,
  OrgPermissionSubjects
} from "@app/context/OrgPermissionContext/types";
import { gatewayPoolsQueryKeys } from "@app/hooks/api/gateway-pools/queries";
import { TGatewayV2 } from "@app/hooks/api/gateways-v2/types";
import { isGatewayHealthy } from "@app/hooks/api/gateways-v2/utils";
import { gatewaysQueryKeys } from "@app/hooks/api/gateways/queries";
import { PoolHealthBadge } from "@app/pages/organization/NetworkingPage/components/GatewayTab/components/PoolHealthBadge";

import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from "../../generic/Select";
import { Tooltip, TooltipContent, TooltipTrigger } from "../../generic/Tooltip";

type GatewayPickerValue = {
  gatewayId: string | null;
  gatewayPoolId: string | null;
};

type Props = {
  value: GatewayPickerValue;
  onChange: (value: GatewayPickerValue) => void;
  isDisabled?: boolean;
  className?: string;
  isRequired?: boolean;
  placeholder?: string;
  isError?: boolean;
  noGatewayLabel?: string;
  noGatewayIcon?: LucideIcon;
  // Hides one gateway from the list, for callers where selecting it would be self-referential.
  excludeGatewayId?: string;
  // For callers where the backend exempts an individual gateway from the org's pool requirement.
  allowIndividualGateways?: boolean;
  // Limits the individual gateways to those that can serve the caller, such as HSM-capable ones.
  // The currently selected gateway is always kept so an existing value stays visible.
  filterGateway?: (gateway: TGatewayV2) => boolean;
};

const SectionLabel = ({ children }: { children: React.ReactNode }) => (
  <div className="px-2 pt-2 pb-1 text-xs text-muted">{children}</div>
);

const SectionDivider = () => <div className="my-1 h-px bg-border" />;

export const GatewayPicker = ({
  value,
  onChange,
  isDisabled,
  className,
  isRequired,
  placeholder,
  isError,
  noGatewayLabel = "Internet Gateway",
  noGatewayIcon: NoGatewayIcon = GlobeIcon,
  excludeGatewayId,
  allowIndividualGateways,
  filterGateway
}: Props) => {
  const { subscription } = useSubscription();
  const { currentOrg } = useOrganization();
  const { permission } = useOrgPermission();
  const isPoolRequired = Boolean(currentOrg?.requireGatewayPools) && !allowIndividualGateways;
  // Pools stay listed when the policy is on even if the plan no longer includes them, or the
  // picker would have nothing selectable.
  const showPools = subscription?.gatewayPool || Boolean(currentOrg?.requireGatewayPools);

  const { data: gateways, isPending: isGatewaysLoading } = useQuery(gatewaysQueryKeys.list());
  // The list above drops gateways that never connected. A saved value can still point at one, so it
  // is looked up in the unfiltered list (same cached query) to keep the selection visible.
  const { data: allGateways } = useQuery({
    ...gatewaysQueryKeys.listAll(),
    enabled: Boolean(value.gatewayId)
  });
  const { data: pools, isPending: isPoolsLoading } = useQuery({
    ...gatewayPoolsQueryKeys.list(),
    enabled: Boolean(showPools)
  });

  const isLoading = isGatewaysLoading || (showPools && isPoolsLoading);

  let selectValue = isRequired ? "" : "internet";
  if (value.gatewayPoolId) {
    selectValue = `pool:${value.gatewayPoolId}`;
  } else if (value.gatewayId) {
    selectValue = `gateway:${value.gatewayId}`;
  }

  const handleChange = (v: string) => {
    if (v === "internet") {
      onChange({ gatewayId: null, gatewayPoolId: null });
    } else if (v.startsWith("pool:")) {
      onChange({ gatewayId: null, gatewayPoolId: v.replace("pool:", "") });
    } else if (v.startsWith("gateway:")) {
      onChange({ gatewayId: v.replace("gateway:", ""), gatewayPoolId: null });
    }
  };

  const listedGateways =
    gateways?.filter(
      (g) =>
        g.id !== excludeGatewayId &&
        (!filterGateway || filterGateway(g) || g.id === value.gatewayId)
    ) ?? [];
  const unlistedSelectedGateway =
    value.gatewayId && !listedGateways.some((g) => g.id === value.gatewayId)
      ? allGateways?.find((g) => g.id === value.gatewayId)
      : undefined;
  const v2Gateways = unlistedSelectedGateway
    ? [unlistedSelectedGateway, ...listedGateways]
    : listedGateways;

  const isOnline = (gw: (typeof v2Gateways)[number]) => isGatewayHealthy(gw);

  const poolCount = pools?.length ?? 0;
  const hasAnyGateways = v2Gateways.length > 0 || poolCount > 0;
  const isGatewayBlocked = (gatewayId: string) => isPoolRequired && gatewayId !== value.gatewayId;
  const canCreateGateway = permission.can(
    OrgGatewayPermissionActions.CreateGateways,
    OrgPermissionSubjects.Gateway
  );
  const canCreateGatewayPool = permission.can(
    OrgGatewayPoolPermissionActions.CreateGatewayPools,
    OrgPermissionSubjects.GatewayPool
  );

  return (
    <Select value={selectValue} onValueChange={handleChange} disabled={isDisabled || isLoading}>
      <SelectTrigger className={className ?? "w-full"} isError={isError}>
        <SelectValue placeholder={placeholder ?? "Select gateway..."} />
      </SelectTrigger>
      <SelectContent position="popper">
        {!isRequired && (
          <SelectItem value="internet">
            <span className="flex items-center gap-2">
              <NoGatewayIcon className="size-3.5 text-muted" />
              {noGatewayLabel}
            </span>
          </SelectItem>
        )}

        {showPools && pools && pools.length > 0 && (
          <>
            {!isRequired && <SectionDivider />}
            <SectionLabel>
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <Layers3Icon className="size-3" />
                  Gateway Pools
                </div>
                <Tooltip>
                  <TooltipTrigger asChild>
                    <span className="cursor-default rounded bg-info/10 px-1.5 py-0.5 text-[10px] font-semibold text-info">
                      HA
                    </span>
                  </TooltipTrigger>
                  <TooltipContent>High Availability</TooltipContent>
                </Tooltip>
              </div>
            </SectionLabel>
            {pools.map((pool) => (
              <SelectItem value={`pool:${pool.id}`} key={`pool-${pool.id}`}>
                <span className="flex min-w-0 items-center gap-2">
                  <Layers3Icon className="size-3.5 shrink-0 text-muted" />
                  <span className="truncate">{pool.name}</span>
                  <span className="shrink-0 text-xs">
                    <PoolHealthBadge pool={pool} />
                  </span>
                </span>
              </SelectItem>
            ))}
          </>
        )}

        {v2Gateways.length > 0 && (
          <>
            {(!isRequired || (showPools && pools && pools.length > 0)) && <SectionDivider />}
            <SectionLabel>
              <div className="flex items-center gap-2">
                <ServerIcon className="size-3" />
                Individual Gateways
              </div>
              {isPoolRequired && (
                <div className="mt-1 text-2xs">
                  Your organization requires a gateway pool, so individual gateways can&apos;t be
                  selected.
                </div>
              )}
            </SectionLabel>
            {v2Gateways.map((gw) => (
              <SelectItem
                value={`gateway:${gw.id}`}
                key={`gw-${gw.id}`}
                disabled={isGatewayBlocked(gw.id)}
              >
                <span className="flex min-w-0 items-center gap-2">
                  <ServerIcon className="size-3.5 shrink-0 text-muted" />
                  <span className="truncate">{gw.name}</span>
                  <span
                    className={`shrink-0 text-xs ${isOnline(gw) ? "text-success" : "text-danger"}`}
                  >
                    {isOnline(gw) ? "Online" : "Offline"}
                  </span>
                </span>
              </SelectItem>
            ))}
          </>
        )}

        {isPoolRequired && poolCount === 0 && (
          <div className="px-2 py-4 text-center text-sm text-muted">
            {canCreateGatewayPool ? (
              <>
                Your organization requires a gateway pool, but none exist yet.{" "}
                <Link
                  to="/organizations/$orgId/networking"
                  params={{ orgId: currentOrg.id }}
                  search={{ selectedTab: "gateways", gatewayView: "gateway-pools" }}
                  target="_blank"
                  className="text-foreground underline underline-offset-2 hover:text-info"
                >
                  Create one
                </Link>{" "}
                to continue.
              </>
            ) : (
              "Your organization requires a gateway pool, but none exist yet. Ask your organization admin to create one."
            )}
          </div>
        )}

        {!isPoolRequired && isRequired && !hasAnyGateways && (
          <div className="px-2 py-4 text-center text-sm text-muted">
            {canCreateGateway ? (
              <>
                No gateways configured.{" "}
                <Link
                  to="/organizations/$orgId/networking"
                  params={{ orgId: currentOrg.id }}
                  target="_blank"
                  className="text-foreground underline underline-offset-2 hover:text-info"
                >
                  Set one up
                </Link>{" "}
                to continue.
              </>
            ) : (
              "No gateways configured. Ask your organization admin to set one up."
            )}
          </div>
        )}
      </SelectContent>
    </Select>
  );
};