Skip to content

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

11.0 KB
Raw Blame
import { ReactNode, useEffect, useLayoutEffect, useRef, useState } from "react";
import { Control, Controller, useForm, useFormState } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { InfoIcon } from "lucide-react";
import { z } from "zod";

import { createNotification } from "@app/components/notifications";
import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
  Alert,
  AlertDescription,
  Button,
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  Field,
  FieldContent,
  FieldDescription,
  FieldError,
  FieldLabel,
  FieldTitle,
  Input,
  RadioGroup,
  RadioGroupItem,
  Tooltip,
  TooltipContent,
  TooltipTrigger
} from "@app/components/v3";
import { agentVaultDescriptionSchema } from "@app/helpers/agentVaultDescription";
import { addHostListIssues } from "@app/helpers/agentVaultHostPattern";
import {
  AgentVaultTrafficPolicy,
  isServiceHostsPolicy,
  useCreateAgentVaultProxy,
  useUpdateAgentVaultProxy
} from "@app/hooks/api/agentVault";
import { TAgentVaultProxy, TAgentVaultProxyToken } from "@app/hooks/api/agentVault/types";
import { slugSchema } from "@app/lib/schemas";

const TRAFFIC_POLICY_CHOICES = [
  {
    value: AgentVaultTrafficPolicy.AnyHost,
    title: "Any host",
    description: "Allow requests to reach any host."
  },
  {
    value: AgentVaultTrafficPolicy.ServiceHosts,
    title: "Service hosts only",
    description: "Only allow requests to reach hosts that the session's services cover."
  }
];

const schema = z
  .object({
    name: slugSchema({ max: 64, field: "Name" }),
    description: agentVaultDescriptionSchema.optional(),
    trafficPolicy: z.nativeEnum(AgentVaultTrafficPolicy),
    allowedHosts: z.string().trim().max(1024).optional(),
    // Guarded before coercion: z.coerce turns "" into 0, which would report the range error instead.
    pollInterval: z
      .string()
      .or(z.number())
      .refine((value) => String(value).trim() !== "", "Poll interval is required")
      .pipe(
        z.coerce
          .number({ invalid_type_error: "Poll interval is required" })
          .int("Poll interval must be a whole number of seconds")
          .min(10, "Poll interval must be at least 10 seconds")
          .max(300, "Poll interval must be at most 300 seconds")
      )
  })
  // Only under the service-hosts policy, where the field is on screen: an any-host proxy ignores the
  // list, and a stale value in a hidden field would block Save with an error nothing shows.
  .superRefine((data, ctx) => {
    if (data.trafficPolicy !== AgentVaultTrafficPolicy.ServiceHosts) return;
    addHostListIssues(data.allowedHosts, ctx, ["allowedHosts"]);
  });

type FormData = z.infer<typeof schema>;

const ADVANCED_ITEM = "advanced-options";

const AdvancedOptions = ({
  control,
  children
}: {
  control: Control<FormData>;
  children: ReactNode;
}) => {
  const [openItem, setOpenItem] = useState("");
  const { errors, submitCount } = useFormState({ control });
  const hasError = Boolean(errors.allowedHosts || errors.pollInterval);

  useEffect(() => {
    if (hasError) setOpenItem(ADVANCED_ITEM);
  }, [hasError, submitCount]);

  return (
    <Accordion
      type="single"
      collapsible
      variant="ghost"
      value={openItem}
      onValueChange={setOpenItem}
    >
      <AccordionItem value={ADVANCED_ITEM}>
        <AccordionTrigger>Advanced Options</AccordionTrigger>
        <AccordionContent>
          <div className="flex flex-col gap-4">{children}</div>
        </AccordionContent>
      </AccordionItem>
    </Accordion>
  );
};

type Props = {
  isOpen: boolean;
  onOpenChange: (isOpen: boolean) => void;
  proxy?: TAgentVaultProxy;
  onCreated?: (proxyToken: TAgentVaultProxyToken) => void;
};

export const ProxyFormDialog = ({ isOpen, onOpenChange, proxy, onCreated }: Props) => {
  const createProxy = useCreateAgentVaultProxy();
  const updateProxy = useUpdateAgentVaultProxy();

  const lastProxy = useRef(proxy);
  if (isOpen) lastProxy.current = proxy;
  const shownProxy = isOpen ? proxy : lastProxy.current;
  const isUpdate = Boolean(shownProxy);

  const {
    clearErrors,
    control,
    handleSubmit,
    reset,
    watch,
    formState: { isSubmitting }
  } = useForm<FormData>({ resolver: zodResolver(schema) });

  const isServiceHostsOnly = watch("trafficPolicy") === AgentVaultTrafficPolicy.ServiceHosts;

  const saveDelayNote = (() => {
    if (!shownProxy?.heartbeat) return null;
    return shownProxy.isHealthy
      ? "This proxy picks up the change on its next poll."
      : "This proxy is not connected right now. It picks up the change when it reconnects.";
  })();

  useLayoutEffect(() => {
    if (!isOpen) return undefined;

    reset({
      name: proxy?.name ?? "",
      description: proxy?.description ?? "",
      trafficPolicy:
        proxy && isServiceHostsPolicy(proxy.trafficPolicy)
          ? AgentVaultTrafficPolicy.ServiceHosts
          : AgentVaultTrafficPolicy.AnyHost,
      allowedHosts: proxy?.allowedHosts ?? "",
      pollInterval: proxy?.pollInterval ?? 60
    });

    return () => clearErrors();
  }, [isOpen, proxy, reset, clearErrors]);

  const onSubmit = async (data: FormData) => {
    try {
      const payload = {
        name: data.name,
        trafficPolicy: data.trafficPolicy,
        allowedHosts: data.allowedHosts ? data.allowedHosts : null,
        pollInterval: data.pollInterval
      };

      if (proxy) {
        await updateProxy.mutateAsync({
          proxyId: proxy.id,
          ...payload,
          description: data.description || null
        });
        createNotification({ text: `Proxy "${data.name}" updated`, type: "success" });
      } else {
        const result = await createProxy.mutateAsync({
          ...payload,
          description: data.description || undefined
        });
        createNotification({ text: `Proxy "${data.name}" created`, type: "success" });
        onCreated?.({ proxyToken: result.proxyToken });
      }

      onOpenChange(false);
    } catch {
      // A failed request returns a 4xx that the global request handler surfaces as a toast
    }
  };

  const settingsFields = (
    <>
      <Controller
        control={control}
        name="trafficPolicy"
        render={({ field }) => (
          <Field>
            <FieldLabel>Traffic Policy</FieldLabel>
            <FieldContent>
              <RadioGroup value={field.value} onValueChange={field.onChange}>
                {TRAFFIC_POLICY_CHOICES.map((choice) => {
                  const id = `traffic-policy-${choice.value}`;

                  return (
                    <FieldLabel key={choice.value} htmlFor={id} variant="av">
                      <Field orientation="horizontal">
                        <FieldContent>
                          <FieldTitle>{choice.title}</FieldTitle>
                          <FieldDescription>{choice.description}</FieldDescription>
                        </FieldContent>
                        <RadioGroupItem id={id} value={choice.value} />
                      </Field>
                    </FieldLabel>
                  );
                })}
              </RadioGroup>
            </FieldContent>
          </Field>
        )}
      />
      {isServiceHostsOnly && (
        <Controller
          control={control}
          name="allowedHosts"
          render={({ field, fieldState }) => (
            <Field>
              <FieldLabel>Exceptions</FieldLabel>
              <FieldContent>
                <Input
                  {...field}
                  placeholder="registry.npmjs.org, proxy.golang.org"
                  isError={Boolean(fieldState.error)}
                />
                <FieldError>{fieldState.error?.message}</FieldError>
              </FieldContent>
            </Field>
          )}
        />
      )}
      <Controller
        control={control}
        name="pollInterval"
        render={({ field, fieldState }) => (
          <Field>
            <FieldLabel>
              Poll Interval
              <Tooltip>
                <TooltipTrigger asChild>
                  <InfoIcon />
                </TooltipTrigger>
                <TooltipContent className="max-w-sm">
                  How often the proxy refreshes its configuration, in seconds. This determines how
                  long a change in these settings takes to reach a running agent.
                </TooltipContent>
              </Tooltip>
            </FieldLabel>
            <FieldContent>
              <Input {...field} type="number" isError={Boolean(fieldState.error)} />
              <FieldError>{fieldState.error?.message}</FieldError>
            </FieldContent>
          </Field>
        )}
      />
    </>
  );

  return (
    <Dialog open={isOpen} onOpenChange={onOpenChange}>
      <DialogContent>
        {/* DialogContent spaces its own children; the form is the only one, so it has to carry the layout. */}
        <form onSubmit={handleSubmit(onSubmit)} className="flex flex-col gap-6">
          <DialogHeader>
            <DialogTitle>{isUpdate ? "Edit Settings" : "Create Proxy"}</DialogTitle>
            <DialogDescription>
              Configure how this proxy handles your agents&apos; requests.
            </DialogDescription>
          </DialogHeader>

          <div className="flex flex-col gap-4">
            <Controller
              control={control}
              name="name"
              render={({ field, fieldState }) => (
                <Field>
                  <FieldLabel>Name</FieldLabel>
                  <FieldContent>
                    <Input {...field} placeholder="egress-1" isError={Boolean(fieldState.error)} />
                    <FieldError>{fieldState.error?.message}</FieldError>
                  </FieldContent>
                </Field>
              )}
            />
            <Controller
              control={control}
              name="description"
              render={({ field, fieldState }) => (
                <Field>
                  <FieldLabel>Description</FieldLabel>
                  <FieldContent>
                    <Input
                      {...field}
                      placeholder="Egress for the staging cluster"
                      isError={Boolean(fieldState.error)}
                    />
                    <FieldError>{fieldState.error?.message}</FieldError>
                  </FieldContent>
                </Field>
              )}
            />
            {shownProxy ? (
              settingsFields
            ) : (
              <AdvancedOptions control={control}>{settingsFields}</AdvancedOptions>
            )}
            {saveDelayNote && (
              <Alert variant="info">
                <InfoIcon />
                <AlertDescription>{saveDelayNote}</AlertDescription>
              </Alert>
            )}
          </div>

          <DialogFooter>
            <Button type="button" variant="ghost" onClick={() => onOpenChange(false)}>
              Cancel
            </Button>
            <Button type="submit" variant="av" isPending={isSubmitting}>
              {isUpdate ? "Save" : "Create"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
};