Skip to content

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

42.4 KB
Raw Blame
import { type JSX, useEffect, useMemo, useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import axios from "axios";
import { AlertTriangleIcon, Ban, InfoIcon } from "lucide-react";
import { z } from "zod";

import { createNotification } from "@app/components/notifications";
import {
  Alert,
  AlertDescription,
  AlertTitle,
  Badge,
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
  Field,
  FieldContent,
  FieldDescription,
  FieldError,
  FieldLabel,
  FieldTitle,
  GatewayPicker,
  Input,
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
  TextArea,
  Toggle
} from "@app/components/v3";
import { Skeleton } from "@app/components/v3/generic/Skeleton";
import { useProject } from "@app/context";
import { APP_CONNECTION_MAP, getAppConnectionProviderName } from "@app/helpers/appConnections";
import {
  AppConnection,
  useListAppConnections,
  useListAvailableAppConnectionsForApps
} from "@app/hooks/api/appConnections";
import {
  accountTypeRequiresRecording,
  getRotationIntervalOptions,
  isRotatablePamAccountType,
  maxGeneratedPasswordLength,
  PamAccountType,
  pamAccountTypeSupportsSessionLogMasking,
  PamPolicyType,
  useGetPamAccountTemplate,
  usePamAccountTypeMap,
  useUpdatePamAccountTemplate
} from "@app/hooks/api/pam";
import { PAM_RECORDING_CONNECTION_APPS } from "@app/hooks/api/pam/constants";
import { ApiErrorTypes, TApiErrors } from "@app/hooks/api/types";
import { PamSheetTab, usePamSheetState } from "@app/hooks/usePamSheetState";

import { AccountPlatformIcon } from "../../components/AccountPlatformIcon";
import { formatDetailDate, PamDetailSheet } from "../../components/PamDetailSheet";
import { PAM_TEMPLATE_TABS } from "../../components/pamResourceTabs";
import { POLICY_EDITORS } from "../../components/policyEditors";
import { SheetSaveBar } from "../../components/SheetSaveBar";

const configSchema = z.object({
  name: z.string().min(1, "Name is required").max(64),
  description: z.string().max(256).optional()
});

type ConfigForm = z.infer<typeof configSchema>;

const buildSettingsSchema = (maxPwLength: number) =>
  z
    .object({
      gatewayId: z.string().nullable(),
      gatewayPoolId: z.string().nullable(),
      recordingStorageBackend: z.enum(["postgres", "aws-s3"]),
      recordingConnectionId: z.string().nullable(),
      s3Bucket: z.string().optional(),
      s3Region: z.string().optional(),
      s3KeyPrefix: z.string().optional(),
      policies: z.record(z.unknown()),
      settings: z.object({
        sessionLogMaskingPatterns: z.string().optional(),
        sessionLogMaskingBuiltInDetection: z.boolean().optional(),
        rotationEnabled: z.boolean().optional(),
        heartbeatEnabled: z.boolean().optional(),
        heartbeatIntervalSeconds: z.number().optional(),
        rotationIntervalSeconds: z.number().nullable().optional(),
        pwLength: z.coerce.number().optional(),
        pwUppercase: z.coerce.number().optional(),
        pwLowercase: z.coerce.number().optional(),
        pwDigits: z.coerce.number().optional(),
        pwSymbols: z.coerce.number().optional(),
        pwAllowedSymbols: z.string().optional()
      })
    })
    .superRefine((data, ctx) => {
      if (data.recordingStorageBackend === "aws-s3") {
        if (!data.recordingConnectionId) {
          ctx.addIssue({
            code: z.ZodIssueCode.custom,
            path: ["recordingConnectionId"],
            message: "Select a connection"
          });
        }
        if (!data.s3Bucket?.trim()) {
          ctx.addIssue({
            code: z.ZodIssueCode.custom,
            path: ["s3Bucket"],
            message: "Bucket is required"
          });
        }
      }

      const length = data.settings.pwLength ?? Math.min(32, maxPwLength);
      const mins = {
        uppercase: data.settings.pwUppercase ?? 0,
        lowercase: data.settings.pwLowercase ?? 0,
        digits: data.settings.pwDigits ?? 0,
        symbols: data.settings.pwSymbols ?? 0
      };
      if (length < 1 || length > maxPwLength) {
        ctx.addIssue({
          code: z.ZodIssueCode.custom,
          path: ["settings", "pwLength"],
          message: `Length must be between 1 and ${maxPwLength}`
        });
      }
      (["pwUppercase", "pwLowercase", "pwDigits", "pwSymbols"] as const).forEach((key) => {
        const value = data.settings[key];
        if (value !== undefined && value < 0) {
          ctx.addIssue({
            code: z.ZodIssueCode.custom,
            path: ["settings", key],
            message: "Cannot be negative"
          });
        }
      });
      const totalRequired = mins.uppercase + mins.lowercase + mins.digits + mins.symbols;
      if (totalRequired === 0) {
        ctx.addIssue({
          code: z.ZodIssueCode.custom,
          path: ["settings", "pwLength"],
          message: "Require at least one character type"
        });
      } else if (totalRequired > length) {
        ctx.addIssue({
          code: z.ZodIssueCode.custom,
          path: ["settings", "pwLength"],
          message: "Length must be at least the sum of the minimums"
        });
      }
    });

type SettingsForm = z.infer<ReturnType<typeof buildSettingsSchema>>;

type Props = {
  isOpen: boolean;
  templateId?: string;
  onOpenChange: (open: boolean) => void;
};

const ConfigurationTab = ({
  templateId,
  onDirtyChange
}: {
  templateId: string;
  onDirtyChange?: (isDirty: boolean) => void;
}) => {
  const { data: template, isLoading } = useGetPamAccountTemplate(templateId);
  const updateTemplate = useUpdatePamAccountTemplate();

  const {
    control,
    handleSubmit,
    reset,
    formState: { isDirty }
  } = useForm<ConfigForm>({
    resolver: zodResolver(configSchema),
    defaultValues: {
      name: "",
      description: ""
    }
  });

  useEffect(() => {
    onDirtyChange?.(isDirty);
    return () => onDirtyChange?.(false);
  }, [isDirty, onDirtyChange]);

  useEffect(() => {
    if (template) {
      reset({
        name: template.name,
        description: template.description ?? ""
      });
    }
  }, [template, reset]);

  const onSubmit = (data: ConfigForm) => {
    updateTemplate.mutate(
      {
        templateId,
        name: data.name,
        description: data.description || null
      },
      {
        onSuccess: () => createNotification({ type: "success", text: "Template updated" })
      }
    );
  };

  if (isLoading) {
    return (
      <div className="flex flex-col gap-4 p-4">
        <Skeleton className="h-8 w-48" />
        <Skeleton className="h-16 w-full" />
      </div>
    );
  }

  return (
    <form onSubmit={handleSubmit(onSubmit)} className="flex flex-1 flex-col gap-4 p-4">
      <Card>
        <CardHeader className="border-b">
          <CardTitle className="text-base">Configuration</CardTitle>
          <CardDescription>Edit the template name and description.</CardDescription>
        </CardHeader>
        <CardContent className="flex flex-col gap-4">
          <Controller
            control={control}
            name="name"
            render={({ field, fieldState }) => (
              <Field>
                <FieldLabel>
                  Name<span className="text-product-pam">*</span>
                </FieldLabel>
                <FieldContent>
                  <Input
                    {...field}
                    isError={!!fieldState.error}
                    autoComplete="off"
                    name="pam-template-name"
                  />
                  <FieldError>{fieldState.error?.message}</FieldError>
                </FieldContent>
              </Field>
            )}
          />

          <Controller
            control={control}
            name="description"
            render={({ field, fieldState }) => (
              <Field>
                <FieldLabel>Description</FieldLabel>
                <FieldContent>
                  <TextArea {...field} rows={3} isError={!!fieldState.error} />
                  <FieldError>{fieldState.error?.message}</FieldError>
                </FieldContent>
              </Field>
            )}
          />
        </CardContent>
      </Card>

      <div aria-hidden className="h-8 shrink-0" />
      {isDirty && <SheetSaveBar isPending={updateTemplate.isPending} onDiscard={() => reset()} />}
    </form>
  );
};

const SettingsTab = ({
  templateId,
  onDirtyChange
}: {
  templateId: string;
  onDirtyChange?: (isDirty: boolean) => void;
}) => {
  const { data: template, isLoading } = useGetPamAccountTemplate(templateId);
  const updateTemplate = useUpdatePamAccountTemplate({ skipValidationToast: true });
  const { currentProject } = useProject();
  const { connections: recordingConnections } = useListAvailableAppConnectionsForApps(
    PAM_RECORDING_CONNECTION_APPS,
    currentProject.id
  );
  const { data: appConnections = [] } = useListAppConnections();
  const { map: accountTypeMap } = usePamAccountTypeMap();

  const maxPwLength = maxGeneratedPasswordLength(template?.type);
  const defaultPwLength = Math.min(32, maxPwLength);
  const settingsSchema = useMemo(() => buildSettingsSchema(maxPwLength), [maxPwLength]);

  const {
    control,
    handleSubmit,
    reset,
    setError,
    setValue,
    watch,
    formState: { isDirty }
  } = useForm<SettingsForm>({
    resolver: zodResolver(settingsSchema),
    defaultValues: {
      gatewayId: null,
      gatewayPoolId: null,
      recordingStorageBackend: "postgres",
      recordingConnectionId: null,
      s3Bucket: "",
      s3Region: "",
      s3KeyPrefix: "",
      policies: {},
      settings: {
        sessionLogMaskingPatterns: "",
        sessionLogMaskingBuiltInDetection: false,
        rotationEnabled: false,
        heartbeatEnabled: false,
        heartbeatIntervalSeconds: 86400,
        rotationIntervalSeconds: 86400,
        pwLength: defaultPwLength,
        pwUppercase: 1,
        pwLowercase: 1,
        pwDigits: 1,
        pwSymbols: 1,
        pwAllowedSymbols: "-_.~!*"
      }
    }
  });

  useEffect(() => {
    onDirtyChange?.(isDirty);
    return () => onDirtyChange?.(false);
  }, [isDirty, onDirtyChange]);

  useEffect(() => {
    if (template) {
      const settings = (template.settings ?? {}) as Record<string, unknown>;
      const s3Config = (settings.recordingS3Config ?? {}) as Record<string, string>;
      const savedBackend = settings.recordingStorageBackend as "postgres" | "aws-s3" | undefined;
      reset({
        gatewayId: template.gatewayId ?? null,
        gatewayPoolId: template.gatewayPoolId ?? null,
        recordingStorageBackend: savedBackend ?? "postgres",
        recordingConnectionId: template.recordingConnectionId ?? null,
        s3Bucket: s3Config.bucket ?? "",
        s3Region: s3Config.region ?? "",
        s3KeyPrefix: s3Config.keyPrefix ?? "",
        policies: (template.policies as Record<string, unknown>) ?? {},
        settings: {
          sessionLogMaskingPatterns: (settings.sessionLogMaskingPatterns as string) ?? "",
          sessionLogMaskingBuiltInDetection:
            (settings.sessionLogMaskingBuiltInDetection as boolean) ?? false,
          ...(() => {
            const rotation = (settings.rotation ?? {}) as {
              enabled?: boolean;
              intervalSeconds?: number | null;
            };
            const heartbeat = (settings.heartbeat ?? {}) as {
              enabled?: boolean;
              intervalSeconds?: number | null;
            };
            const pw = (settings.passwordRequirements ?? {}) as {
              length?: number;
              required?: {
                uppercase?: number;
                lowercase?: number;
                digits?: number;
                symbols?: number;
              };
              allowedSymbols?: string;
            };
            return {
              rotationEnabled: rotation.enabled ?? false,
              heartbeatEnabled: heartbeat.enabled ?? false,
              heartbeatIntervalSeconds: heartbeat.intervalSeconds ?? 86400,
              rotationIntervalSeconds:
                rotation.intervalSeconds !== undefined ? rotation.intervalSeconds : 86400,
              pwLength: pw.length ?? defaultPwLength,
              pwUppercase: pw.required?.uppercase ?? 1,
              pwLowercase: pw.required?.lowercase ?? 1,
              pwDigits: pw.required?.digits ?? 1,
              pwSymbols: pw.required?.symbols ?? 1,
              pwAllowedSymbols: pw.allowedSymbols ?? "-_.~!*"
            };
          })()
        }
      });
    }
  }, [template, reset]);

  if (isLoading) {
    return (
      <div className="flex flex-col gap-4 p-4">
        <Skeleton className="h-8 w-48" />
        <Skeleton className="h-16 w-full" />
        <Skeleton className="h-10 w-full" />
      </div>
    );
  }

  if (!template) return null;

  const gatewayId = watch("gatewayId");
  const gatewayPoolId = watch("gatewayPoolId");
  const policies = watch("policies");
  const storageBackend = watch("recordingStorageBackend");
  const recordingConnectionApp = recordingConnections.find(
    (conn) => conn.id === watch("recordingConnectionId")
  )?.app;
  const rotationEnabled = watch("settings.rotationEnabled");
  const heartbeatEnabled = watch("settings.heartbeatEnabled");
  const savedSettings = (template.settings ?? {}) as {
    rotation?: { intervalSeconds?: number | null };
    heartbeat?: { intervalSeconds?: number | null };
  };
  const requiresRecording = accountTypeRequiresRecording(template.type);
  const showGatewaySettings = accountTypeMap[template.type]?.requiresGateway !== false;
  const supportsSessionLogMasking = pamAccountTypeSupportsSessionLogMasking(template.type);

  const typeName = accountTypeMap[template.type]?.name ?? template.type;
  const isRotatableTemplateType = isRotatablePamAccountType(template.type);
  const requiresApproval = policies[PamPolicyType.RequiresApproval] === true;
  // These only change how an approval is reached, so they follow Require Approval
  const approvalDependentPolicies = [
    PamPolicyType.AllowAutoApproval,
    PamPolicyType.AllowBreakGlass
  ];
  const applicablePolicies = (accountTypeMap[template.type]?.applicablePolicies ?? []).filter(
    (p) => POLICY_EDITORS[p.key] && (!approvalDependentPolicies.includes(p.key) || requiresApproval)
  );

  const onSubmit = (data: SettingsForm) => {
    const settings: Record<string, unknown> = {
      ...((template.settings ?? {}) as Record<string, unknown>),
      recordingStorageBackend: data.recordingStorageBackend
    };

    if (data.recordingStorageBackend === "aws-s3" && data.s3Bucket) {
      settings.recordingS3Config = {
        bucket: data.s3Bucket,
        ...(recordingConnectionApp === AppConnection.S3Compatible
          ? {}
          : { region: data.s3Region || "us-east-1" }),
        ...(data.s3KeyPrefix ? { keyPrefix: data.s3KeyPrefix } : {})
      };
    } else {
      delete settings.recordingS3Config;
    }

    const maskingPatterns = data.settings.sessionLogMaskingPatterns?.trim();
    if (maskingPatterns) {
      settings.sessionLogMaskingPatterns = maskingPatterns;
    } else {
      delete settings.sessionLogMaskingPatterns;
    }

    // Never deleted when false: an absent key means "never configured", which is a different thing.
    settings.sessionLogMaskingBuiltInDetection = Boolean(
      data.settings.sessionLogMaskingBuiltInDetection
    );

    const isHeartbeatOn = Boolean(data.settings.heartbeatEnabled);
    settings.heartbeat = {
      enabled: isHeartbeatOn,
      intervalSeconds: isHeartbeatOn ? (data.settings.heartbeatIntervalSeconds ?? 86400) : null
    };

    if (isRotatableTemplateType) {
      const isRotationOn = Boolean(data.settings.rotationEnabled);
      settings.rotation = {
        enabled: isRotationOn,
        intervalSeconds: isRotationOn ? (data.settings.rotationIntervalSeconds ?? 86400) : null
      };
      settings.passwordRequirements = {
        length: data.settings.pwLength ?? defaultPwLength,
        required: {
          uppercase: data.settings.pwUppercase ?? 0,
          lowercase: data.settings.pwLowercase ?? 0,
          digits: data.settings.pwDigits ?? 0,
          symbols: data.settings.pwSymbols ?? 0
        },
        ...(data.settings.pwAllowedSymbols
          ? { allowedSymbols: data.settings.pwAllowedSymbols }
          : {})
      };
    } else {
      delete settings.rotation;
      delete settings.passwordRequirements;
    }

    updateTemplate.mutate(
      {
        templateId,
        policies: data.policies,
        gatewayId: data.gatewayId,
        gatewayPoolId: data.gatewayPoolId,
        settings,
        recordingConnectionId:
          data.recordingStorageBackend === "aws-s3" ? data.recordingConnectionId : null
      },
      {
        onError: (error) => {
          if (axios.isAxiosError(error)) {
            const responseData = error.response?.data as TApiErrors | undefined;
            if (responseData?.error === ApiErrorTypes.ValidationError) {
              const maskingIssue = responseData.message.find((issue) =>
                issue.path.join(".").includes("sessionLogMaskingPatterns")
              );
              if (maskingIssue) {
                setError("settings.sessionLogMaskingPatterns", {
                  type: "server",
                  message: maskingIssue.message
                });
                return;
              }
              // Surface the specific validation issue rather than the opaque generic toast.
              createNotification({
                type: "error",
                text: responseData.message[0]?.message ?? "Failed to update template"
              });
              return;
            }
            const msg = (error.response?.data as { message?: string })?.message;
            createNotification({
              type: "error",
              text: typeof msg === "string" ? msg : "Failed to update template"
            });
            return;
          }
          createNotification({ type: "error", text: "Failed to update template" });
        },
        // oxlint-disable-next-line react/no-unstable-nested-components -- a callback that builds a toast, not a component
        onSuccess: async (result) => {
          createNotification({ type: "success", text: "Template updated" });
          const { corsProbeUrl } = result as { corsProbeUrl?: string | null };
          if (corsProbeUrl) {
            try {
              await fetch(corsProbeUrl, { mode: "cors" });
            } catch {
              createNotification(
                {
                  title: "Bucket CORS not configured",
                  type: "warning",
                  text: "Session playback requires the bucket to allow GET requests from this origin.",
                  callToAction: (
                    <a
                      href="https://infisical.com/docs/documentation/platform/pam/recording-storage"
                      target="_blank"
                      rel="noopener noreferrer"
                      className="text-xs underline"
                    >
                      CORS setup docs
                    </a>
                  )
                },
                { autoClose: 10000 }
              );
            }
          }
        }
      }
    );
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)} className="flex flex-1 flex-col gap-4 p-4">
      <Card>
        <CardHeader className="border-b">
          <CardTitle className="text-base">Policies</CardTitle>
          <CardDescription>
            Policies available for {typeName} accounts using this template.
          </CardDescription>
        </CardHeader>
        <CardContent className="flex flex-col gap-6">
          {applicablePolicies.map((p) => {
            const Editor = POLICY_EDITORS[p.key]!;
            return (
              <Editor
                key={p.key}
                accountType={template.type as PamAccountType}
                label={p.label}
                description={p.description}
                value={policies[p.key]}
                onChange={(value) => {
                  const next = { ...policies };
                  if (value === null || value === undefined) delete next[p.key];
                  else next[p.key] = value;
                  if (p.key === PamPolicyType.RequiresApproval && value !== true) {
                    approvalDependentPolicies.forEach((key) => delete next[key]);
                  }
                  setValue("policies", next, { shouldDirty: true });
                }}
              />
            );
          })}
        </CardContent>
      </Card>

      {isRotatableTemplateType && (
        <Card>
          <CardHeader className="border-b">
            <CardTitle className="text-base">Credential settings</CardTitle>
            <CardDescription>
              How credentials for accounts using this template are rotated, and the format of the
              generated passwords.
            </CardDescription>
          </CardHeader>
          <CardContent className="flex flex-col gap-4">
            {/* Requirements are a policy independent of rotation: they apply to onboarded credentials and to the
                passwords generated during rotation, so they show whether or not automatic rotation is on. */}
            <div>
              <p className="text-sm font-medium text-foreground">Requirements</p>
              <p className="text-xs text-muted">
                Every credential must meet these rules, both when an account is onboarded and when a
                password is generated during rotation.
              </p>
            </div>
            <div className="grid grid-cols-2 gap-3">
              {(
                [
                  { name: "settings.pwLength", label: "Min length" },
                  { name: "settings.pwUppercase", label: "Min uppercase" },
                  { name: "settings.pwLowercase", label: "Min lowercase" },
                  { name: "settings.pwDigits", label: "Min numbers" },
                  { name: "settings.pwSymbols", label: "Min symbols" }
                ] as const
              ).map(({ name, label }) => (
                <Controller
                  key={name}
                  control={control}
                  name={name}
                  render={({ field, fieldState }) => (
                    <Field>
                      <FieldLabel>{label}</FieldLabel>
                      <Input
                        type="number"
                        max={name === "settings.pwLength" ? maxPwLength : undefined}
                        value={field.value ?? 0}
                        onChange={(e) => field.onChange(Number(e.target.value))}
                        onWheel={(e) => e.currentTarget.blur()}
                      />
                      {name === "settings.pwLength" && !fieldState.error && (
                        <FieldDescription>1 to {maxPwLength} characters</FieldDescription>
                      )}
                      {fieldState.error && <FieldError>{fieldState.error.message}</FieldError>}
                    </Field>
                  )}
                />
              ))}
            </div>
            <Controller
              control={control}
              name="settings.pwAllowedSymbols"
              render={({ field }) => (
                <Field>
                  <FieldLabel>Allowed symbols</FieldLabel>
                  <Input value={field.value ?? ""} onChange={field.onChange} placeholder="-_.~!*" />
                  <FieldDescription>
                    Symbols a credential may use. Quotes, backticks, backslashes, semicolons, and
                    question marks are not allowed.
                  </FieldDescription>
                </Field>
              )}
            />
            <div className="flex flex-col gap-4 border-t border-border pt-4">
              <Controller
                control={control}
                name="settings.rotationEnabled"
                render={({ field }) => (
                  <div className="flex items-center justify-between gap-3">
                    <div>
                      <p className="text-sm font-medium text-foreground">
                        Automatically rotate credentials
                      </p>
                      <p className="text-xs text-muted">
                        Infisical rotates credentials on a fixed schedule. When off, credentials
                        rotate only when triggered manually.
                      </p>
                    </div>
                    <Toggle
                      variant="pam"
                      checked={field.value ?? false}
                      onCheckedChange={field.onChange}
                    />
                  </div>
                )}
              />
              {rotationEnabled &&
                template.rotationImpact &&
                (template.rotationImpact.needsRotationAccount > 0 ? (
                  <Alert variant="warning">
                    <AlertTriangleIcon />
                    <AlertTitle>
                      {template.rotationImpact.needsRotationAccount}{" "}
                      {template.rotationImpact.needsRotationAccount === 1 ? "account" : "accounts"}{" "}
                      won&apos;t rotate yet
                    </AlertTitle>
                    <AlertDescription>
                      Set a rotation account on{" "}
                      {template.rotationImpact.needsRotationAccount === 1 ? "it" : "them"} to enable
                      rotation.
                      {template.rotationImpact.willRotate > 0 &&
                        ` ${template.rotationImpact.willRotate} ${
                          template.rotationImpact.willRotate === 1 ? "account is" : "accounts are"
                        } ready to rotate.`}
                    </AlertDescription>
                  </Alert>
                ) : (
                  // Nothing misconfigured: only surface while editing; the warning above always shows (actionable gap).
                  isDirty && (
                    <Alert variant="info">
                      <InfoIcon />
                      <AlertTitle>
                        {template.rotationImpact.willRotate === 0
                          ? "No accounts to rotate yet"
                          : `${template.rotationImpact.willRotate} ${
                              template.rotationImpact.willRotate === 1 ? "account" : "accounts"
                            } will rotate`}
                      </AlertTitle>
                      <AlertDescription>
                        {template.rotationImpact.willRotate === 0
                          ? "Accounts using this template will rotate once they have a rotation account."
                          : "Every account using this template has a rotation account."}
                      </AlertDescription>
                    </Alert>
                  )
                ))}
              {rotationEnabled && (
                <Controller
                  control={control}
                  name="settings.rotationIntervalSeconds"
                  render={({ field }) => (
                    <Field>
                      <FieldLabel>Rotate every</FieldLabel>
                      <Select
                        value={String(field.value ?? 86400)}
                        onValueChange={(value) => field.onChange(Number(value))}
                      >
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent position="popper">
                          {getRotationIntervalOptions(savedSettings.rotation?.intervalSeconds).map(
                            (option) => (
                              <SelectItem key={option.seconds} value={String(option.seconds)}>
                                {option.label}
                              </SelectItem>
                            )
                          )}
                        </SelectContent>
                      </Select>
                      <FieldDescription>
                        How often credentials are rotated automatically for accounts using this
                        template.
                      </FieldDescription>
                    </Field>
                  )}
                />
              )}
            </div>
          </CardContent>
        </Card>
      )}

      <Card>
        <CardHeader className="border-b">
          <CardTitle className="text-base">Credential Health</CardTitle>
          <CardDescription>
            Infisical checks that stored credentials still work, and shows the result on each
            account.
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex flex-col gap-4">
            <Controller
              control={control}
              name="settings.heartbeatEnabled"
              render={({ field }) => (
                <div className="flex items-center justify-between gap-3">
                  <p className="text-sm font-medium text-foreground">Check credentials</p>
                  <Toggle
                    variant="pam"
                    checked={field.value ?? false}
                    onCheckedChange={field.onChange}
                  />
                </div>
              )}
            />
            {heartbeatEnabled && (
              <Controller
                control={control}
                name="settings.heartbeatIntervalSeconds"
                render={({ field }) => (
                  <Field>
                    <FieldLabel>Check every</FieldLabel>
                    <Select
                      value={String(field.value ?? 86400)}
                      onValueChange={(value) => field.onChange(Number(value))}
                    >
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent position="popper">
                        {getRotationIntervalOptions(savedSettings.heartbeat?.intervalSeconds).map(
                          (option) => (
                            <SelectItem key={option.seconds} value={String(option.seconds)}>
                              {option.label}
                            </SelectItem>
                          )
                        )}
                      </SelectContent>
                    </Select>
                    <FieldDescription>
                      How often accounts using this template are checked.
                    </FieldDescription>
                  </Field>
                )}
              />
            )}
          </div>
        </CardContent>
      </Card>

      {showGatewaySettings && (
        <Card>
          <CardHeader className="border-b">
            <CardTitle className="text-base">System Settings</CardTitle>
            <CardDescription>
              System-level defaults for accounts using this template.
            </CardDescription>
          </CardHeader>
          <CardContent className="flex flex-col gap-6">
            <Field>
              <FieldLabel>Gateway</FieldLabel>
              <FieldContent>
                <GatewayPicker
                  value={{ gatewayId, gatewayPoolId }}
                  onChange={(value) => {
                    setValue("gatewayId", value.gatewayId, { shouldDirty: true });
                    setValue("gatewayPoolId", value.gatewayPoolId, { shouldDirty: true });
                  }}
                  noGatewayLabel="No Gateway"
                  noGatewayIcon={Ban}
                />
                <FieldDescription>
                  Used to reach accounts unless overridden on the account.
                </FieldDescription>
              </FieldContent>
            </Field>
          </CardContent>
        </Card>
      )}

      {showGatewaySettings && (
        <Card>
          <CardHeader className="border-b">
            <CardTitle className="text-base">Session Recording</CardTitle>
            <CardDescription>
              Where session recordings for accounts using this template are stored.
            </CardDescription>
          </CardHeader>
          <CardContent className="flex flex-col gap-6">
            <Controller
              name="recordingStorageBackend"
              control={control}
              render={({ field }) => (
                <Field>
                  <FieldLabel>Storage backend</FieldLabel>
                  <FieldContent>
                    <Select value={field.value} onValueChange={(v) => field.onChange(v)}>
                      <SelectTrigger className="w-full">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent position="popper">
                        <SelectItem value="postgres">Internal Database</SelectItem>
                        <SelectItem value="aws-s3">S3 Bucket</SelectItem>
                      </SelectContent>
                    </Select>
                  </FieldContent>
                </Field>
              )}
            />

            {requiresRecording && storageBackend === "postgres" && (
              <Alert variant="warning">
                <AlertTriangleIcon />
                <AlertTitle>Accounts cannot be launched</AlertTitle>
                <AlertDescription>
                  {typeName} accounts require an external recording storage backend. Accounts using
                  this template can still be created, but sessions can&apos;t be launched until
                  external storage is configured.
                </AlertDescription>
              </Alert>
            )}

            {storageBackend === "aws-s3" && (
              <>
                <Alert variant="warning">
                  <AlertTriangleIcon />
                  <AlertTitle>Changing bucket affects existing recordings</AlertTitle>
                  <AlertDescription>
                    Changing the bucket on a template with existing recordings makes those
                    recordings inaccessible unless you manually migrate each object. Keep the same
                    bucket and key prefix when rotating credentials.
                  </AlertDescription>
                </Alert>

                <Controller
                  name="recordingConnectionId"
                  control={control}
                  render={({ field, fieldState }) => (
                    <Field>
                      <FieldLabel>Connection</FieldLabel>
                      <FieldContent>
                        <Select
                          value={field.value ?? ""}
                          onValueChange={(v) => field.onChange(v || null)}
                        >
                          <SelectTrigger className="w-full" isError={!!fieldState.error}>
                            <SelectValue placeholder="Select a connection" />
                          </SelectTrigger>
                          <SelectContent position="popper">
                            {recordingConnections.length === 0 && (
                              <div className="px-2 py-3 text-center text-xs text-muted">
                                No AWS or S3-Compatible Storage connections found. Create one from
                                the App Connections page.
                              </div>
                            )}
                            {recordingConnections.map((conn) => {
                              const connection = appConnections.find(({ id }) => id === conn.id);
                              const providerName = connection
                                ? getAppConnectionProviderName(connection)
                                : APP_CONNECTION_MAP[conn.app].name;
                              return (
                                <SelectItem key={conn.id} value={conn.id}>
                                  {conn.name} <span className="text-muted">({providerName})</span>
                                </SelectItem>
                              );
                            })}
                          </SelectContent>
                        </Select>
                        {fieldState.error ? (
                          <FieldError>{fieldState.error.message}</FieldError>
                        ) : (
                          <FieldDescription>
                            The AWS or S3-Compatible Storage connection used to access the bucket.
                          </FieldDescription>
                        )}
                      </FieldContent>
                    </Field>
                  )}
                />

                <Controller
                  name="s3Bucket"
                  control={control}
                  render={({ field, fieldState }) => (
                    <Field>
                      <FieldLabel>S3 Bucket</FieldLabel>
                      <FieldContent>
                        <Input
                          {...field}
                          placeholder="my-recordings-bucket"
                          isError={!!fieldState.error}
                        />
                        <FieldError>{fieldState.error?.message}</FieldError>
                      </FieldContent>
                    </Field>
                  )}
                />

                {recordingConnectionApp !== AppConnection.S3Compatible && (
                  <Controller
                    name="s3Region"
                    control={control}
                    render={({ field }) => (
                      <Field>
                        <FieldLabel>Region</FieldLabel>
                        <FieldContent>
                          <Input {...field} placeholder="us-east-1" />
                        </FieldContent>
                      </Field>
                    )}
                  />
                )}

                <Controller
                  name="s3KeyPrefix"
                  control={control}
                  render={({ field }) => (
                    <Field>
                      <FieldLabel>Key prefix (optional)</FieldLabel>
                      <FieldContent>
                        <Input {...field} placeholder="pam-recordings/" />
                        <FieldDescription>Optional prefix for S3 object keys.</FieldDescription>
                      </FieldContent>
                    </Field>
                  )}
                />
              </>
            )}

            {supportsSessionLogMasking && (
              <div className="flex flex-col gap-4 border-t border-border pt-6">
                <div>
                  <p className="text-sm font-medium text-foreground">Session Log Masking</p>
                  <p className="text-xs text-muted">
                    What gets masked in recordings for accounts using this template.
                  </p>
                </div>

                <Controller
                  control={control}
                  name="settings.sessionLogMaskingBuiltInDetection"
                  render={({ field }) => (
                    <Field orientation="horizontal">
                      <FieldContent>
                        <FieldTitle>
                          Built-in Detection
                          <Badge variant="success">Recommended</Badge>
                        </FieldTitle>
                        <FieldDescription>
                          API keys and tokens from known providers, and the account&apos;s own
                          credentials, are masked automatically.
                        </FieldDescription>
                      </FieldContent>
                      <Toggle
                        variant="pam"
                        checked={field.value ?? false}
                        onCheckedChange={field.onChange}
                      />
                    </Field>
                  )}
                />

                <Controller
                  control={control}
                  name="settings.sessionLogMaskingPatterns"
                  render={({ field, fieldState }) => (
                    <Field>
                      <FieldLabel>Custom patterns</FieldLabel>
                      <FieldContent>
                        <TextArea
                          rows={5}
                          placeholder={"acme_[a-z0-9]{24}\ninternal-vault://\\S+"}
                          value={field.value ?? ""}
                          isError={!!fieldState.error}
                          onChange={(e) => {
                            const val = e.target.value;
                            field.onChange(val.trim() ? val : "");
                          }}
                        />
                        <FieldDescription>One regex per line.</FieldDescription>
                        <FieldError>{fieldState.error?.message}</FieldError>
                      </FieldContent>
                    </Field>
                  )}
                />
              </div>
            )}
          </CardContent>
        </Card>
      )}

      <div aria-hidden className="h-8 shrink-0" />
      {isDirty && <SheetSaveBar isPending={updateTemplate.isPending} onDiscard={() => reset()} />}
    </form>
  );
};

export const TemplateDetailSheet = ({ isOpen, templateId, onOpenChange }: Props) => {
  const { data: template, isLoading } = useGetPamAccountTemplate(isOpen ? templateId : undefined);
  const { tab, setTab } = usePamSheetState("templateId");
  const [isFormDirty, setIsFormDirty] = useState(false);

  const { map: accountTypeMap } = usePamAccountTypeMap();
  const accountType = template?.type as PamAccountType | undefined;
  const typeInfo = accountType ? accountTypeMap[accountType] : undefined;

  const metadata = template
    ? [
        ...(template.description ? [{ label: "Description", value: template.description }] : []),
        {
          label: "Accounts",
          value: `${template.accountCount ?? 0} using this template`
        },
        { label: "Created", value: formatDetailDate(template.createdAt) }
      ]
    : [];

  const tabContent: Partial<Record<PamSheetTab, JSX.Element | null>> = {
    [PamSheetTab.General]: templateId ? (
      <SettingsTab templateId={templateId} onDirtyChange={setIsFormDirty} />
    ) : null,
    [PamSheetTab.Configuration]: templateId ? (
      <ConfigurationTab templateId={templateId} onDirtyChange={setIsFormDirty} />
    ) : null
  };

  return (
    <PamDetailSheet
      isOpen={isOpen}
      onOpenChange={onOpenChange}
      isLoading={isLoading}
      accountType={accountType}
      title={template?.name}
      typeBadge={typeInfo?.name}
      activeTab={tab}
      onTabChange={setTab}
      icon={
        accountType ? (
          <div className="mb-4 flex size-16 items-center justify-center rounded-lg border border-border bg-container">
            <AccountPlatformIcon accountType={accountType} size={40} />
          </div>
        ) : undefined
      }
      metadata={metadata}
      tabs={PAM_TEMPLATE_TABS.map((tabDef) => ({
        value: tabDef.value,
        label: tabDef.label,
        icon: <tabDef.icon className="mr-1.5 size-4" />,
        content: tabContent[tabDef.value] ?? null
      }))}
      isDirty={isFormDirty}
    />
  );
};