Skip to content

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

59.7 KB
Raw Blame
/* eslint-disable no-underscore-dangle */
import dns from "dns";
import ConnectionString from "mongodb-connection-string-url";
import RE2 from "re2";
import { promisify } from "util";
import { z } from "zod";

import { BadRequestError } from "@app/lib/errors";
import { netbiosFromDomainFqdn } from "@app/lib/ldap/ldap-search-fns";

import {
  PamAccountSettingsOverridesSchema,
  PamTemplateSettingsSchema
} from "../pam-account-template/pam-account-template-schemas";
import { PamRecordingStorageBackend } from "../pam-session-recording/pam-recording-enums";
import {
  GcpServiceAccountAuthMethod,
  PamAccountType,
  PamPostgresAuthMethod,
  PamSnowflakeAuthMethod,
  PamSshAuthMethod
} from "../pam/pam-enums";
import { getApplicablePolicies, PamPolicyDescriptorSchema } from "../pam/pam-policies";

const resolveSrv = promisify(dns.resolveSrv);

enum PamFieldWidget {
  Text = "text",
  Number = "number",
  Boolean = "boolean",
  Select = "select",
  Textarea = "textarea",
  Password = "password"
}

const optionalTrimmedString = z
  .string()
  .trim()
  .transform((v) => v || undefined)
  .optional();

const boundedOptionalString = (max: number) =>
  z
    .string()
    .trim()
    .max(max)
    .transform((v) => v || undefined)
    .optional();

// Clearing a number input submits "" rather than undefined, which coercion would read as port 0.
const optionalPort = () =>
  z.preprocess(
    (v) => (v === null || (typeof v === "string" && v.trim() === "") ? undefined : v),
    z.coerce.number().int().min(1).max(65535).optional()
  );

const normalizeDelimitedStringList = (value: unknown): unknown => {
  if (Array.isArray(value)) return value;
  if (typeof value !== "string") return value;
  const items = value
    .split("\n")
    .flatMap((line) => line.split(","))
    .map((item) => item.trim())
    .filter((item) => item.length > 0);
  return items;
};

export const hostPattern = new RE2(/^[A-Za-z0-9.:_-]+$/);
const snowflakeAccountPattern = new RE2(/^[A-Za-z0-9][A-Za-z0-9._-]*$/);
const delimitedStringList = z.preprocess(
  normalizeDelimitedStringList,
  z.array(z.string().trim().min(1).max(255).regex(hostPattern, "Must be a valid hostname or IP address")).min(1)
);

// A type that gained its authMethod discriminator after launch has stored rows without one,
// which a discriminated union rejects outright. Defaulting it keeps them parsing
// everywhere they are re-read, including the rotation cron, which validates the stored blob every run.
const LEGACY_AUTH_METHODS = {
  [PamAccountType.Postgres]: PamPostgresAuthMethod.Password
} as const satisfies Partial<Record<PamAccountType, string>>;

type TLegacyAuthMethodType = keyof typeof LEGACY_AUTH_METHODS;

const withLegacyAuthMethod = <T extends z.ZodTypeAny>(accountType: TLegacyAuthMethodType, schema: T) =>
  z.preprocess(
    (value) =>
      typeof value === "object" && value !== null && !Array.isArray(value) && !("authMethod" in value)
        ? { ...value, authMethod: LEGACY_AUTH_METHODS[accountType] }
        : value,
    schema
  );

// Same defaulting, for credentials handed straight to the gateway without being re-parsed
export const normalizeCredentialAuthMethod = (
  accountType: PamAccountType,
  credentials: Record<string, unknown>
): Record<string, unknown> => {
  const fallback = LEGACY_AUTH_METHODS[accountType as TLegacyAuthMethodType];
  if (!fallback || credentials.authMethod !== undefined) return credentials;
  return { ...credentials, authMethod: fallback };
};

type TFieldConditionHint = { field: string; equals: string | boolean };
type TFieldForcedRuleHint = { when: TFieldConditionHint; value: string | number | boolean; reason: string };

// Source of truth for account types: per-type schemas + sparse UI hints
export const ORACLE_MAX_PASSWORD_LENGTH = 30;

export const ORACLE_MIN_GATEWAY_VERSION = "v0.43.133";

export const ACCOUNT_TYPE_CONFIGS = {
  [PamAccountType.Postgres]: {
    name: "PostgreSQL",
    icon: "Postgres.png",
    connectionStringSchemes: ["postgres", "postgresql"],
    connectionDetails: z.object({
      host: z.string().trim().min(1).max(255),
      port: z.coerce.number(),
      database: z.string().trim().min(1).max(255),
      sslEnabled: z.boolean(),
      sslRejectUnauthorized: z.boolean(),
      sslCertificate: optionalTrimmedString
    }),
    credentials: withLegacyAuthMethod(
      PamAccountType.Postgres,
      z.discriminatedUnion("authMethod", [
        z.object({
          authMethod: z.literal(PamPostgresAuthMethod.Password),
          username: z.string().trim().min(1).max(63),
          password: z
            .string()
            .trim()
            .max(256)
            .transform((v) => v || undefined)
            .optional()
        }),
        z.object({
          authMethod: z.literal(PamPostgresAuthMethod.AwsIam),
          username: z.string().trim().min(1).max(63),
          awsRegion: z
            .string()
            .trim()
            .min(1)
            .max(32)
            .regex(new RE2(/^[a-z0-9-]+$/), "Must be a valid AWS region"),
          roleArn: z.string().trim().min(1).max(2048)
        })
      ])
    ),
    sanitizedCredentials: z.object({
      authMethod: z.string().optional(),
      username: z.string(),
      awsRegion: z.string().optional(),
      roleArn: z.string().optional()
    }),
    ui: {
      port: { defaultValue: 5432 },
      authMethod: {
        label: "Auth Method",
        defaultValue: PamPostgresAuthMethod.Password,
        options: [
          { label: "Password", value: PamPostgresAuthMethod.Password },
          {
            label: "AWS IAM (RDS / Aurora)",
            value: PamPostgresAuthMethod.AwsIam,
            docsUrl: "https://infisical.com/docs/documentation/platform/pam/accounts/postgresql#aws-iam-authentication"
          }
        ]
      },
      awsRegion: {
        label: "AWS Region",
        tooltip: "The region of the RDS or Aurora instance (e.g. us-east-1)."
      },
      roleArn: {
        label: "Role ARN",
        tooltip:
          "The IAM role Infisical assumes to generate the authentication token. It needs rds-db:connect on this account's database user, and its trust policy must allow Infisical using your Infisical Organization ID as the External ID.\n\nOrganization ID: {{organizationId}}"
      },
      sslEnabled: {
        label: "SSL Enabled",
        forceWhen: [
          {
            when: { field: "credentials.authMethod", equals: PamPostgresAuthMethod.AwsIam },
            value: true,
            reason: "AWS IAM authentication requires an encrypted connection."
          }
        ]
      },
      sslRejectUnauthorized: {
        label: "Reject Unauthorized",
        showWhen: { field: "sslEnabled", equals: true }
      },
      sslCertificate: {
        label: "SSL Certificate",
        widget: PamFieldWidget.Textarea,
        showWhen: { field: "sslEnabled", equals: true },
        tooltip:
          "The CA certificate used to verify the server. Amazon RDS and Aurora publish one per region, e.g. https://truststore.pki.rds.amazonaws.com/us-east-1/us-east-1-bundle.pem"
      },
      password: { widget: PamFieldWidget.Password, secret: true }
    }
  },

  [PamAccountType.MySQL]: {
    name: "MySQL",
    icon: "MySql.png",
    connectionDetails: z.object({
      host: z.string().trim().min(1).max(255),
      port: z.coerce.number(),
      database: z.string().trim().min(1).max(64),
      sslEnabled: z.boolean(),
      sslRejectUnauthorized: z.boolean(),
      sslCertificate: optionalTrimmedString
    }),
    credentials: z.object({
      username: z.string().trim().min(1).max(32),
      password: z
        .string()
        .trim()
        .max(256)
        .transform((v) => v || undefined)
        .optional()
    }),
    sanitizedCredentials: z.object({ username: z.string() }),
    ui: {
      port: { defaultValue: 3306 },
      sslEnabled: { label: "SSL Enabled" },
      sslRejectUnauthorized: {
        label: "Reject Unauthorized",
        showWhen: { field: "sslEnabled", equals: true }
      },
      sslCertificate: {
        label: "SSL Certificate",
        widget: PamFieldWidget.Textarea,
        showWhen: { field: "sslEnabled", equals: true }
      },
      password: { widget: PamFieldWidget.Password, secret: true }
    }
  },

  [PamAccountType.MsSQL]: {
    name: "Microsoft SQL Server",
    icon: "MsSql.png",
    connectionDetails: z.object({
      host: z.string().trim().min(1).max(255),
      port: z.coerce.number(),
      database: z.string().trim().min(1).max(255),
      sslEnabled: z.boolean(),
      sslRejectUnauthorized: z.boolean(),
      sslCertificate: optionalTrimmedString
    }),
    credentials: z.discriminatedUnion("authMethod", [
      z.object({
        authMethod: z.literal("sql-login"),
        username: z.string().trim().min(1).max(63),
        password: z
          .string()
          .trim()
          .max(256)
          .transform((v) => v || undefined)
          .optional()
      }),
      z.object({
        authMethod: z.literal("ntlm"),
        username: z.string().trim().min(1).max(63),
        password: z
          .string()
          .trim()
          .max(256)
          .transform((v) => v || undefined)
          .optional(),
        domain: z.string().trim().min(1).max(255)
      }),
      z.object({
        authMethod: z.literal("kerberos"),
        username: z.string().trim().min(1).max(63),
        password: z
          .string()
          .trim()
          .max(256)
          .transform((v) => v || undefined)
          .optional(),
        realm: z
          .string()
          .trim()
          .min(1)
          .max(255)
          .regex(new RE2(/^[A-Za-z0-9._-]+$/))
          .transform((v) => v.toUpperCase()),
        kdcAddress: z
          .string()
          .trim()
          .max(255)
          .regex(new RE2(/^[A-Za-z0-9._:-]*$/))
          .transform((v) => v || undefined)
          .optional(),
        spn: z
          .string()
          .trim()
          .min(1)
          .max(500)
          .regex(new RE2(/^[A-Za-z0-9._:/-]+$/))
      })
    ]),
    sanitizedCredentials: z.object({
      authMethod: z.string().optional(),
      username: z.string().optional(),
      domain: z.string().optional(),
      realm: z.string().optional(),
      kdcAddress: z.string().optional(),
      spn: z.string().optional()
    }),
    ui: {
      port: { defaultValue: 1433 },
      database: { defaultValue: "master" },
      authMethod: {
        label: "Auth Method",
        defaultValue: "sql-login",
        options: [
          { label: "SQL Server Authentication", value: "sql-login" },
          { label: "Windows Authentication (NTLM)", value: "ntlm" },
          { label: "Windows Authentication (Kerberos)", value: "kerberos" }
        ]
      },
      domain: { label: "Domain" },
      realm: { label: "Realm" },
      kdcAddress: { label: "KDC Address" },
      spn: { label: "SPN" },
      sslEnabled: { label: "SSL Enabled" },
      sslRejectUnauthorized: {
        label: "Reject Unauthorized",
        showWhen: { field: "sslEnabled", equals: true }
      },
      sslCertificate: {
        label: "SSL Certificate",
        widget: PamFieldWidget.Textarea,
        showWhen: { field: "sslEnabled", equals: true }
      },
      password: { widget: PamFieldWidget.Password, secret: true }
    }
  },

  [PamAccountType.OracleDB]: {
    name: "Oracle Database",
    icon: "Oracle.png",
    connectionDetails: z.object({
      host: z.string().trim().min(1).max(255),
      port: z.coerce.number().int().min(1).max(65535),
      database: z
        .string()
        .trim()
        .min(1)
        .max(255)
        .regex(
          new RE2(/^[A-Za-z0-9][A-Za-z0-9_.\-#$]*$/),
          "Must start with a letter or digit and contain only letters, digits, underscores, dots, hyphens, # or $"
        ),
      sslEnabled: z.boolean(),
      sslRejectUnauthorized: z.boolean(),
      sslCertificate: optionalTrimmedString
    }),
    credentials: z.object({
      username: z.string().trim().min(1).max(128),
      password: z
        .string()
        .trim()
        .max(256)
        .transform((v) => v || undefined)
        .optional()
    }),
    sanitizedCredentials: z.object({ username: z.string() }),
    ui: {
      port: { defaultValue: 1521 },
      database: {
        label: "Service Name",
        tooltip: "The Oracle service name. For example FREEPDB1 or ORCL."
      },
      sslEnabled: { label: "SSL Enabled" },
      sslRejectUnauthorized: {
        label: "Reject Unauthorized",
        showWhen: { field: "sslEnabled", equals: true }
      },
      sslCertificate: {
        label: "SSL Certificate",
        widget: PamFieldWidget.Textarea,
        showWhen: { field: "sslEnabled", equals: true }
      },
      password: { widget: PamFieldWidget.Password, secret: true }
    }
  },

  [PamAccountType.MongoDB]: {
    name: "MongoDB",
    icon: "MongoDB.png",
    connectionDetails: z.object({
      connectionString: z
        .string()
        .trim()
        .min(1)
        .max(1024)
        .transform((val, ctx) => {
          let cs: ConnectionString;
          try {
            cs = new ConnectionString(val);
          } catch {
            ctx.addIssue({
              code: z.ZodIssueCode.custom,
              message: "Invalid MongoDB connection string. Must start with mongodb:// or mongodb+srv://"
            });
            return z.NEVER;
          }

          if (cs.username || cs.password) {
            ctx.addIssue({
              code: z.ZodIssueCode.custom,
              message:
                "Credentials should not be included in the connection string. Use the Username and Password fields instead"
            });
            return z.NEVER;
          }

          if (cs.pathname && cs.pathname !== "/") {
            ctx.addIssue({
              code: z.ZodIssueCode.custom,
              message: "Database should not be included in the connection string. Use the Database field instead"
            });
            return z.NEVER;
          }

          return cs.toString();
        }),
      database: z
        .string()
        .trim()
        .min(1)
        .max(64)
        .refine((val) => new RE2("^[a-zA-Z0-9_-]+$").test(val), {
          message: "Database name can only contain letters, numbers, underscores, and hyphens"
        }),
      sslEnabled: z.boolean(),
      sslRejectUnauthorized: z.boolean(),
      sslCertificate: optionalTrimmedString
    }),
    credentials: z.object({
      username: z.string().trim().min(1).max(255),
      password: z
        .string()
        .trim()
        .max(256)
        .transform((v) => v || undefined)
        .optional()
    }),
    sanitizedCredentials: z.object({ username: z.string().optional() }),
    ui: {
      connectionString: {
        label: "Connection String",
        widget: PamFieldWidget.Textarea,
        tooltip: "Supports mongodb:// and mongodb+srv:// URIs. Do not include credentials or database in the URI."
      },
      database: { defaultValue: "admin" },
      sslEnabled: { label: "SSL Enabled" },
      sslRejectUnauthorized: {
        label: "Reject Unauthorized",
        showWhen: { field: "sslEnabled", equals: true }
      },
      sslCertificate: {
        label: "SSL Certificate",
        widget: PamFieldWidget.Textarea,
        showWhen: { field: "sslEnabled", equals: true }
      },
      password: { widget: PamFieldWidget.Password, secret: true }
    }
  },

  [PamAccountType.Redis]: {
    name: "Redis",
    icon: "Redis.png",
    connectionDetails: z.object({
      host: z.string().trim().min(1).max(255),
      port: z.coerce.number().int().min(1).max(65535),
      sslEnabled: z.boolean(),
      sslRejectUnauthorized: z.boolean(),
      sslCertificate: optionalTrimmedString
    }),
    credentials: z.object({
      username: z.string().trim().min(1).max(256),
      password: z
        .string()
        .trim()
        .max(256)
        .transform((v) => v || undefined)
        .optional()
    }),
    sanitizedCredentials: z.object({ username: z.string() }),
    ui: {
      port: { defaultValue: 6379 },
      username: {
        defaultValue: "default",
        tooltip: "The Redis ACL username. Use 'default' for the default user."
      },
      password: { widget: PamFieldWidget.Password, secret: true, optional: true },
      sslEnabled: { label: "SSL Enabled" },
      sslRejectUnauthorized: {
        label: "Reject Unauthorized",
        showWhen: { field: "sslEnabled", equals: true }
      },
      sslCertificate: {
        label: "SSL Certificate",
        widget: PamFieldWidget.Textarea,
        showWhen: { field: "sslEnabled", equals: true }
      }
    }
  },

  [PamAccountType.Snowflake]: {
    name: "Snowflake",
    icon: "Snowflake.png",
    connectionDetails: z.object({
      account: z
        .string()
        .trim()
        .min(1)
        .max(255)
        .regex(snowflakeAccountPattern, "Must be a valid Snowflake account identifier")
        .refine((val) => !val.toLowerCase().includes("snowflakecomputing.com"), {
          message: "Enter the account identifier only, without the snowflakecomputing.com suffix"
        }),
      warehouse: boundedOptionalString(255),
      database: z.string().trim().min(1).max(255),
      schema: boundedOptionalString(255),
      role: boundedOptionalString(255)
    }),
    credentials: z.discriminatedUnion("authMethod", [
      z.object({
        authMethod: z.literal(PamSnowflakeAuthMethod.KeyPair),
        username: z.string().trim().min(1).max(255),
        privateKey: boundedOptionalString(8192),
        privateKeyPassphrase: boundedOptionalString(256)
      }),
      z.object({
        authMethod: z.literal(PamSnowflakeAuthMethod.ProgrammaticAccessToken),
        username: z.string().trim().min(1).max(255),
        token: boundedOptionalString(2048)
      }),
      z.object({
        authMethod: z.literal(PamSnowflakeAuthMethod.Password),
        username: z.string().trim().min(1).max(255),
        password: boundedOptionalString(256)
      })
    ]),
    sanitizedCredentials: z.object({
      authMethod: z.string(),
      username: z.string()
    }),
    ui: {
      account: {
        label: "Account Identifier",
        tooltip:
          "The account identifier from the Snowflake URL, without the snowflakecomputing.com suffix (e.g. myorg-myaccount)."
      },
      warehouse: {
        label: "Default Warehouse",
        tooltip: "The warehouse a session runs its queries on. Leave empty to use the user's own default."
      },
      database: { tooltip: "The database sessions open. The explorer lists the schemas and tables inside it." },
      schema: {
        label: "Default Schema",
        tooltip: "The schema a session starts in. A session can still switch to another schema the role can reach."
      },
      role: {
        label: "Default Role",
        tooltip:
          "The role a session starts with. A session can still switch to another role the user holds, so grant the user only the roles its sessions should reach."
      },
      authMethod: {
        label: "Auth Method",
        defaultValue: PamSnowflakeAuthMethod.KeyPair,
        tooltip:
          "Snowflake blocks single-factor password sign-in for human users, so key pair or a programmatic access token is required for most accounts.",
        options: [
          { label: "Key Pair (Recommended)", value: PamSnowflakeAuthMethod.KeyPair },
          { label: "Programmatic Access Token", value: PamSnowflakeAuthMethod.ProgrammaticAccessToken },
          { label: "Password", value: PamSnowflakeAuthMethod.Password }
        ]
      },
      privateKey: {
        label: "Private Key",
        widget: PamFieldWidget.Textarea,
        secret: true,
        tooltip: "The PKCS#8 private key whose public key is set on the Snowflake user (RSA_PUBLIC_KEY)."
      },
      privateKeyPassphrase: {
        label: "Private Key Passphrase",
        widget: PamFieldWidget.Password,
        secret: true,
        optional: true
      },
      token: { label: "Programmatic Access Token", widget: PamFieldWidget.Password, secret: true },
      password: { widget: PamFieldWidget.Password, secret: true }
    }
  },

  [PamAccountType.ClickHouse]: {
    name: "ClickHouse",
    icon: "ClickHouse.png",
    connectionDetails: z
      .object({
        host: z.string().trim().min(1).max(255),
        port: optionalPort(),
        nativePort: optionalPort(),
        database: z.string().trim().min(1).max(255),
        sslEnabled: z.boolean(),
        sslRejectUnauthorized: z.boolean(),
        sslCertificate: boundedOptionalString(16384)
      })
      .refine((v) => v.port !== undefined || v.nativePort !== undefined, {
        message: "Set the HTTP port, the native port, or both",
        path: ["port"]
      })
      .refine((v) => v.port === undefined || v.port !== v.nativePort, {
        message: "The HTTP and native ports must differ",
        path: ["nativePort"]
      }),
    credentials: z.object({
      username: z.string().trim().min(1).max(255),
      password: boundedOptionalString(256)
    }),
    sanitizedCredentials: z.object({ username: z.string() }),
    ui: {
      port: {
        label: "HTTP Port",
        defaultValue: 8123,
        tooltip:
          "The HTTP interface port: 8123 for plain HTTP, 8443 for HTTPS. Leave it empty if the server only serves the native protocol."
      },
      nativePort: {
        label: "Native Port",
        defaultValue: 9000,
        tooltip:
          "The native TCP port, usually 9000 for plain TCP or 9440 with SSL. clickhouse-client and other native drivers need it. Leave it empty if the server only serves HTTP."
      },
      database: {
        defaultValue: "default",
        tooltip: "The database sessions open. The explorer lists the tables inside it."
      },
      username: {
        defaultValue: "default",
        tooltip: "The ClickHouse user sessions connect as. Use 'default' for the built-in user."
      },
      password: { widget: PamFieldWidget.Password, secret: true, optional: true },
      sslEnabled: { label: "SSL Enabled" },
      sslRejectUnauthorized: {
        label: "Reject Unauthorized",
        showWhen: { field: "sslEnabled", equals: true }
      },
      sslCertificate: {
        label: "SSL Certificate",
        widget: PamFieldWidget.Textarea,
        showWhen: { field: "sslEnabled", equals: true }
      }
    }
  },

  [PamAccountType.SSH]: {
    name: "SSH",
    icon: "SSH.png",
    connectionDetails: z.object({
      host: z.string().trim().min(1).max(255),
      port: z.coerce.number()
    }),
    credentials: z.discriminatedUnion("authMethod", [
      z.object({
        authMethod: z.literal(PamSshAuthMethod.Password),
        username: z.string().trim().min(1),
        password: optionalTrimmedString
      }),
      z.object({
        authMethod: z.literal(PamSshAuthMethod.PublicKey),
        username: z.string().trim().min(1),
        privateKey: z
          .string()
          .trim()
          .max(5000)
          .transform((v) => v || undefined)
          .optional()
      }),
      z.object({ authMethod: z.literal(PamSshAuthMethod.Certificate), username: z.string().trim().min(1) })
    ]),
    sanitizedCredentials: z.object({
      authMethod: z.string(),
      username: z.string()
    }),
    ui: {
      port: { defaultValue: 22 },
      authMethod: { label: "Auth Method" },
      password: { widget: PamFieldWidget.Password, secret: true },
      privateKey: { label: "Private Key", widget: PamFieldWidget.Textarea, secret: true }
    },
    internalMetadata: z.object({
      caPrivateKey: z.string(),
      caPublicKey: z.string(),
      caKeyAlgorithm: z.string()
    })
  },

  [PamAccountType.Kubernetes]: {
    name: "Kubernetes",
    icon: "Kubernetes.png",
    connectionDetails: z.object({
      url: z.string().url().trim().max(500),
      sslRejectUnauthorized: z.boolean(),
      sslCertificate: optionalTrimmedString
    }),
    credentials: z.discriminatedUnion("authMethod", [
      z.object({
        authMethod: z.literal("service-account-token"),
        serviceAccountToken: z.string().trim().min(1).max(10000)
      }),
      z.object({
        authMethod: z.literal("gateway-kubernetes-auth"),
        namespace: z.string().trim().min(1).max(63),
        serviceAccountName: z.string().trim().min(1).max(253)
      })
    ]),
    sanitizedCredentials: z.object({
      authMethod: z.string().optional(),
      namespace: z.string().optional(),
      serviceAccountName: z.string().optional()
    }),
    ui: {
      url: { label: "Kubernetes API URL" },
      sslRejectUnauthorized: { label: "Reject Unauthorized" },
      sslCertificate: { label: "SSL Certificate", widget: PamFieldWidget.Textarea },
      authMethod: { label: "Auth Method" },
      serviceAccountToken: { label: "Service Account Token", widget: PamFieldWidget.Textarea, secret: true },
      namespace: { label: "Namespace" },
      serviceAccountName: { label: "Service Account Name" }
    }
  },

  [PamAccountType.GcpServiceAccount]: {
    name: "GCP Service Account",
    icon: "Google Cloud Platform.png",
    connectionDetails: z.object({
      serviceAccountEmail: z
        .string()
        .trim()
        .min(1)
        .max(255)
        .email("Must be a valid service account email address")
        .refine((val) => val.endsWith(".iam.gserviceaccount.com"), {
          message: "Must be a GCP service account email (ending in .iam.gserviceaccount.com)"
        })
    }),
    credentials: z.discriminatedUnion("authMethod", [
      z.object({
        authMethod: z.literal(GcpServiceAccountAuthMethod.Impersonation)
      }),
      z.object({
        authMethod: z.literal(GcpServiceAccountAuthMethod.StaticKey),
        serviceAccountKeyJson: z
          .string()
          .trim()
          .min(1)
          .max(8192)
          .refine(
            (val) => {
              try {
                const parsed = JSON.parse(val) as Record<string, unknown>;
                return typeof parsed.client_email === "string" && typeof parsed.private_key === "string";
              } catch {
                return false;
              }
            },
            { message: "Must be valid JSON containing client_email and private_key fields" }
          )
      })
    ]),
    sanitizedCredentials: z.object({
      authMethod: z.string()
    }),
    ui: {
      serviceAccountEmail: {
        label: "Service Account Email",
        description:
          'The service account ID must end with "{{organizationIdPrefix}}", e.g. service-account-{{organizationIdPrefix}}@my-project.iam.gserviceaccount.com',
        descriptionWhen: { field: "credentials.authMethod", equals: GcpServiceAccountAuthMethod.Impersonation }
      },
      authMethod: {
        label: "Auth Method",
        tooltip:
          "Impersonation uses the platform's GCP identity to generate short-lived tokens for the target service account.\nStatic Key uses a service account key JSON stored directly in the PAM account.",
        defaultValue: GcpServiceAccountAuthMethod.Impersonation,
        options: [
          { label: "Impersonation (Recommended)", value: GcpServiceAccountAuthMethod.Impersonation },
          { label: "Static Key", value: GcpServiceAccountAuthMethod.StaticKey }
        ]
      },
      serviceAccountKeyJson: {
        label: "Service Account Key JSON",
        widget: PamFieldWidget.Textarea,
        secret: true
      }
    }
  },

  [PamAccountType.Windows]: {
    name: "Windows",
    icon: "Windows.png",
    connectionDetails: z.object({
      host: z.string().trim().min(1).max(255),
      port: z.coerce.number().int().min(1).max(65535),
      winrmPort: z.coerce.number().int().min(1).max(65535).default(5985),
      useWinrmHttps: z.boolean().default(false),
      winrmRejectUnauthorized: z.boolean().default(true),
      winrmCaCert: optionalTrimmedString
    }),
    credentials: z.object({
      username: z.string().trim().min(1).max(255),
      password: optionalTrimmedString
    }),
    sanitizedCredentials: z.object({
      username: z.string()
    }),
    ui: {
      port: { label: "RDP Port", defaultValue: 3389 },
      winrmPort: { label: "WinRM Port", defaultValue: 5985 },
      useWinrmHttps: { label: "Use WinRM HTTPS" },
      winrmRejectUnauthorized: {
        label: "Reject Unauthorized (WinRM)",
        showWhen: { field: "useWinrmHttps", equals: true }
      },
      winrmCaCert: {
        label: "WinRM CA Certificate",
        widget: PamFieldWidget.Textarea,
        showWhen: { field: "useWinrmHttps", equals: true }
      },
      password: { widget: PamFieldWidget.Password, secret: true }
    }
  },

  [PamAccountType.WindowsAd]: {
    name: "Windows AD",
    icon: "ActiveDirectory.png",
    connectionDetails: z.object({
      domain: z.string().trim().min(1).max(255),
      dcAddress: z.string().trim().min(1).max(255),
      hosts: delimitedStringList,
      port: z.coerce.number().int().min(1).max(65535),
      rdpPort: z.coerce.number().int().min(1).max(65535),
      useLdaps: z.boolean(),
      ldapRejectUnauthorized: z.boolean(),
      ldapCaCert: optionalTrimmedString,
      ldapTlsServerName: optionalTrimmedString,
      winrmPort: z.coerce.number().int().min(1).max(65535).default(5985),
      useWinrmHttps: z.boolean().default(false),
      winrmRejectUnauthorized: z.boolean().default(true),
      winrmCaCert: optionalTrimmedString
    }),
    credentials: z.object({
      username: z.string().trim().min(1).max(255),
      password: optionalTrimmedString
    }),
    sanitizedCredentials: z.object({
      username: z.string()
    }),
    ui: {
      domain: {
        label: "FQDN",
        tooltip: "The fully qualified domain name of the Active Directory domain (e.g. corp.example.com)."
      },
      dcAddress: {
        label: "DC Address",
        tooltip:
          "Hostname or IP address of a domain controller, used for LDAP connections (e.g. dc01.corp.example.com)."
      },
      hosts: {
        label: "Allowed Hosts",
        widget: PamFieldWidget.Textarea,
        tooltip: "Hostnames or IP addresses this account is allowed to connect to. One per line or comma-separated."
      },
      port: { label: "LDAP Port", defaultValue: 389 },
      rdpPort: { label: "RDP Port", defaultValue: 3389 },
      useLdaps: { label: "Use LDAPS" },
      ldapRejectUnauthorized: { label: "Reject Unauthorized" },
      ldapCaCert: {
        label: "CA Certificate",
        widget: PamFieldWidget.Textarea,
        showWhen: { field: "useLdaps", equals: true }
      },
      ldapTlsServerName: {
        label: "TLS Server Name",
        showWhen: { field: "useLdaps", equals: true }
      },
      winrmPort: { label: "WinRM Port", defaultValue: 5985 },
      useWinrmHttps: { label: "Use WinRM HTTPS" },
      winrmRejectUnauthorized: {
        label: "Reject Unauthorized (WinRM)",
        showWhen: { field: "useWinrmHttps", equals: true }
      },
      winrmCaCert: {
        label: "WinRM CA Certificate",
        widget: PamFieldWidget.Textarea,
        showWhen: { field: "useWinrmHttps", equals: true }
      },
      username: {
        tooltip: "Use the DOMAIN\\username format for domain authentication (e.g. CORP\\Administrator)."
      },
      password: { widget: PamFieldWidget.Password, secret: true }
    }
  },

  [PamAccountType.AwsIam]: {
    name: "AWS IAM",
    icon: "Amazon Web Services.png",
    requiresGateway: false,
    connectionDetails: z.object({
      roleArn: z.string().trim().min(1).max(2048)
    }),
    credentials: z.object({}),
    sanitizedCredentials: z.object({}),
    ui: {
      roleArn: {
        label: "Role ARN",
        tooltip:
          "The ARN of the IAM role Infisical assumes when accessing this account. Its trust policy must allow Infisical using your Infisical Organization ID as the External ID.\n\nOrganization ID: {{organizationId}}"
      }
    }
  },

  [PamAccountType.AzureCli]: {
    name: "Azure CLI",
    icon: "Microsoft Azure.png",
    connectionDetails: z.object({
      tenantId: z
        .string()
        .trim()
        .min(1)
        .max(255)
        .regex(new RE2(/^[A-Za-z0-9.-]+$/), "Must be a valid Azure tenant ID or domain"),
      subscriptionId: z
        .string()
        .trim()
        .refine((v) => v === "" || z.string().uuid().safeParse(v).success, {
          message: "Must be a valid Azure subscription ID"
        })
        .transform((v) => v || undefined)
        .optional()
    }),
    credentials: z.object({
      clientId: z.string().trim().uuid("Must be a valid Azure application (client) ID"),
      clientSecret: z.string().trim().min(1).max(512)
    }),
    sanitizedCredentials: z.object({
      clientId: z.string().optional()
    }),
    ui: {
      tenantId: {
        label: "Tenant ID",
        tooltip: "The Microsoft Entra ID (Azure AD) directory (tenant) ID the service principal belongs to."
      },
      subscriptionId: {
        label: "Subscription ID",
        tooltip: "Optional. The Azure subscription the CLI session defaults to (az account set)."
      },
      clientId: {
        label: "Client ID",
        tooltip: "The application (client) ID of the service principal Infisical brokers access to."
      },
      clientSecret: {
        label: "Client Secret",
        widget: PamFieldWidget.Password,
        secret: true,
        tooltip: "A client secret for the service principal. Stored encrypted and never returned in read responses."
      }
    }
  }
} as const satisfies Partial<
  Record<
    PamAccountType,
    {
      name: string;
      icon: string;
      requiresGateway?: boolean;
      connectionStringSchemes?: readonly string[];
      connectionDetails: z.ZodTypeAny;
      credentials: z.ZodTypeAny;
      sanitizedCredentials: z.ZodTypeAny;
      ui?: Record<
        string,
        {
          label?: string;
          widget?: PamFieldWidget;
          secret?: boolean;
          optional?: boolean;
          defaultValue?: string | number | boolean;
          showWhen?: TFieldConditionHint;
          forceWhen?: readonly TFieldForcedRuleHint[];
          tooltip?: string;
          description?: string;
          descriptionWhen?: TFieldConditionHint;
          options?: { label: string; value: string; docsUrl?: string }[];
        }
      >;
      internalMetadata?: z.ZodTypeAny;
    }
  >
>;

export type TSupportedAccountType = keyof typeof ACCOUNT_TYPE_CONFIGS;

export type TWindowsConnectionDetails = z.infer<
  (typeof ACCOUNT_TYPE_CONFIGS)[PamAccountType.Windows]["connectionDetails"]
>;
export type TWindowsAdConnectionDetails = z.infer<
  (typeof ACCOUNT_TYPE_CONFIGS)[PamAccountType.WindowsAd]["connectionDetails"]
>;

export const SQL_ROTATABLE_ACCOUNT_TYPES = [
  PamAccountType.Postgres,
  PamAccountType.MySQL,
  PamAccountType.MsSQL,
  PamAccountType.OracleDB
] as const;

// Windows accounts rotate over WinRM through the gateway: local accounts on their host, domain accounts
// on the DC. They do not use the SQL rotation path.
export const WINDOWS_ROTATABLE_ACCOUNT_TYPES = [PamAccountType.Windows, PamAccountType.WindowsAd] as const;

export const ROTATABLE_ACCOUNT_TYPES = [...SQL_ROTATABLE_ACCOUNT_TYPES, ...WINDOWS_ROTATABLE_ACCOUNT_TYPES] as const;

export type TSqlRotatableType = (typeof SQL_ROTATABLE_ACCOUNT_TYPES)[number];
export type TWindowsRotatableType = (typeof WINDOWS_ROTATABLE_ACCOUNT_TYPES)[number];
export type TRotatableType = (typeof ROTATABLE_ACCOUNT_TYPES)[number];

export const isRotatableAccountType = (accountType: PamAccountType | string): accountType is TRotatableType =>
  (ROTATABLE_ACCOUNT_TYPES as readonly string[]).includes(accountType);

export const isWindowsRotatableType = (accountType: PamAccountType | string): accountType is TWindowsRotatableType =>
  (WINDOWS_ROTATABLE_ACCOUNT_TYPES as readonly string[]).includes(accountType);

export const isSqlRotatableType = (accountType: PamAccountType | string): accountType is TSqlRotatableType =>
  (SQL_ROTATABLE_ACCOUNT_TYPES as readonly string[]).includes(accountType);

const getAccountTypeConfig = (accountType: PamAccountType | string) => {
  const config = ACCOUNT_TYPE_CONFIGS[accountType as TSupportedAccountType];
  if (!config) {
    throw new Error(`Account type '${accountType}' is not supported in this phase`);
  }
  return config;
};

export const validateConnectionDetails = (accountType: PamAccountType, data: unknown) => {
  return getAccountTypeConfig(accountType).connectionDetails.parse(data) as z.output<
    (typeof ACCOUNT_TYPE_CONFIGS)[TSupportedAccountType]["connectionDetails"]
  >;
};

export const validateCredentials = (accountType: PamAccountType, data: unknown) => {
  return getAccountTypeConfig(accountType).credentials.parse(data) as z.output<
    (typeof ACCOUNT_TYPE_CONFIGS)[TSupportedAccountType]["credentials"]
  >;
};

export const sanitizeCredentials = (accountType: PamAccountType, data: unknown) => {
  const normalized = normalizeCredentialAuthMethod(accountType, (data ?? {}) as Record<string, unknown>);
  return getAccountTypeConfig(accountType).sanitizedCredentials.parse(normalized) as z.output<
    (typeof ACCOUNT_TYPE_CONFIGS)[TSupportedAccountType]["sanitizedCredentials"]
  >;
};

export type TGatewayTarget = { host: string; port?: number };

export const extractGatewayTarget = async (
  accountType: PamAccountType,
  rawConnectionDetails: Record<string, unknown>
): Promise<TGatewayTarget> => {
  const validated = validateConnectionDetails(accountType, rawConnectionDetails);

  switch (accountType) {
    case PamAccountType.SSH:
    case PamAccountType.Postgres:
    case PamAccountType.MySQL:
    case PamAccountType.MsSQL:
    case PamAccountType.OracleDB:
    case PamAccountType.Redis:
    case PamAccountType.Windows:
      return {
        host: (validated as { host: string; port: number }).host,
        port: (validated as { host: string; port: number }).port
      };
    case PamAccountType.ClickHouse: {
      const { host, port, nativePort } = validated as { host: string; port?: number; nativePort?: number };
      return { host, port: port ?? nativePort };
    }
    case PamAccountType.Kubernetes: {
      const { url } = validated as { url: string };
      const parsed = new URL(url);
      const defaultPort = parsed.protocol === "http:" ? 80 : 443;
      return { host: parsed.hostname, port: parsed.port ? Number(parsed.port) : defaultPort };
    }
    case PamAccountType.MongoDB: {
      const { connectionString } = validated as { connectionString: string };
      const cs = new ConnectionString(connectionString);
      const [firstHost] = cs.hosts;

      if (cs.isSRV) {
        const records = await resolveSrv(`_mongodb._tcp.${firstHost}`);
        if (records.length === 0) {
          throw new BadRequestError({
            message: `Unable to resolve SRV record for MongoDB host "${firstHost}". Ensure the host is a valid SRV domain.`
          });
        }
        const record = records[Math.floor(Math.random() * records.length)];
        return { host: record.name, port: record.port };
      }

      const colonIdx = firstHost.lastIndexOf(":");
      if (colonIdx !== -1) {
        return {
          host: firstHost.slice(0, colonIdx),
          port: parseInt(firstHost.slice(colonIdx + 1), 10)
        };
      }
      return { host: firstHost, port: 27017 };
    }
    case PamAccountType.WindowsAd:
      return {
        host: (validated as { hosts: string[]; rdpPort: number }).hosts[0],
        port: (validated as { hosts: string[]; rdpPort: number }).rdpPort
      };
    case PamAccountType.GcpServiceAccount:
      return { host: "googleapis.com", port: 443 };
    case PamAccountType.AwsIam:
      throw new Error("AWS IAM accounts do not use gateway routing");
    case PamAccountType.Snowflake:
      return { host: `${(validated as { account: string }).account}.snowflakecomputing.com`, port: 443 };
    case PamAccountType.AzureCli:
      return { host: "management.azure.com", port: 443 };
    default:
      throw new Error(`No gateway target extraction defined for account type '${accountType as PamAccountType}'`);
  }
};

// Hosts the launcher can pick from, or null for single-host account types
export const getSelectableHosts = (
  accountType: PamAccountType,
  rawConnectionDetails: Record<string, unknown>
): string[] | null => {
  if (accountType !== PamAccountType.WindowsAd) return null;
  return (validateConnectionDetails(accountType, rawConnectionDetails) as { hosts: string[] }).hosts;
};

// Validates a requested host against the allow-list; falls back to the first
export const resolveSelectedHost = (
  accountType: PamAccountType,
  rawConnectionDetails: Record<string, unknown>,
  requestedHost?: string | null
): string | null => {
  const hosts = getSelectableHosts(accountType, rawConnectionDetails);
  if (!hosts) return null;
  if (requestedHost && !hosts.includes(requestedHost)) {
    throw new BadRequestError({ message: `Host '${requestedHost}' is not in this account's allowed hosts` });
  }
  return requestedHost || hosts[0];
};

// The account type the gateway sees. Windows AD is brokered through the Windows RDP protocol
export const resolveGatewayAccountType = (accountType: PamAccountType): PamAccountType =>
  accountType === PamAccountType.WindowsAd ? PamAccountType.Windows : accountType;

export const gatewaySupportsAccountType = (
  accountType: PamAccountType,
  supportedTypes: string[] | undefined
): boolean => !supportedTypes || supportedTypes.includes(resolveGatewayAccountType(accountType));

export const webAccessUnavailableReason = (
  accountType: PamAccountType,
  connectionDetails: Record<string, unknown>
): string | null => {
  if (accountType !== PamAccountType.ClickHouse) return null;
  if ((connectionDetails as { port?: number }).port !== undefined) return null;
  return "Web access needs ClickHouse's HTTP interface. Set an HTTP port on this account, or connect with a native client through the CLI.";
};

// An absent flag means a gateway too old to report it, which is exactly the case this guards.
export const gatewaySupportsClickHouseNative = (capabilities: { clickhouseNativeProtocol?: boolean } | null) =>
  Boolean(capabilities?.clickhouseNativeProtocol);

export const requiresClickHouseNative = (
  accountType: PamAccountType,
  connectionDetails: Record<string, unknown>
): boolean =>
  accountType === PamAccountType.ClickHouse && (connectionDetails as { nativePort?: number }).nativePort !== undefined;

export const buildSessionGatewayConnectionDetails = (
  accountType: PamAccountType,
  rawConnectionDetails: Record<string, unknown>,
  selectedHost?: string | null
): Record<string, unknown> => {
  const validated = validateConnectionDetails(accountType, rawConnectionDetails) as Record<string, unknown>;

  if (accountType === PamAccountType.WindowsAd) {
    const { hosts, rdpPort } = validated as { hosts: string[]; rdpPort: number };

    return {
      host: selectedHost || hosts[0],
      port: rdpPort
    };
  }

  return validated;
};

// A username already carries its domain if it's NT4 (`DOMAIN\user`) or UPN (`user@domain`)
export const isDomainQualifiedUsername = (username: string) => username.includes("\\") || username.includes("@");

// Domain-qualifies a bare username to `NETBIOS\user` for RDP/NLA; already-qualified forms pass through
export const qualifyUsernameWithDomain = (username: string, domainFqdn: string) => {
  if (isDomainQualifiedUsername(username)) return username;
  return `${netbiosFromDomainFqdn(domainFqdn)}\\${username}`;
};

// Normalizes any form to a NetBIOS `DOMAIN\user` login
export const toNetbiosUsername = (username: string, domainFqdn: string) => {
  if (username.includes("\\")) return username;
  const localPart = username.includes("@") ? username.split("@")[0] : username;
  return `${netbiosFromDomainFqdn(domainFqdn)}\\${localPart}`;
};

// -- Account accessibility

export enum PamAccountAccessibilityIssue {
  NoGateway = "no-gateway",
  NoRecordingConfig = "no-recording-config",
  NoCredential = "no-credential",
  NoApprovalConfig = "no-approval-config"
}

export const accountTypeRequiresRecording = (accountType: PamAccountType): boolean =>
  accountType === PamAccountType.Windows || accountType === PamAccountType.WindowsAd;

export const accountTypeRequiresGateway = (accountType: PamAccountType): boolean => {
  const config = ACCOUNT_TYPE_CONFIGS[accountType as TSupportedAccountType] as
    | { requiresGateway?: boolean }
    | undefined;
  return config?.requiresGateway !== false;
};

const accountTypeConnectionStringSchemes = (accountType: PamAccountType): string[] | undefined => {
  const config = ACCOUNT_TYPE_CONFIGS[accountType as TSupportedAccountType] as
    | { connectionStringSchemes?: readonly string[] }
    | undefined;
  return config?.connectionStringSchemes ? [...config.connectionStringSchemes] : undefined;
};

// redis and clickhouse both accept a passwordless user, so an account without one is still launchable
const CREDENTIAL_OPTIONAL_ACCOUNT_TYPES: PamAccountType[] = [PamAccountType.Redis, PamAccountType.ClickHouse];

export const accountTypeRequiresCredential = (accountType: PamAccountType): boolean =>
  !CREDENTIAL_OPTIONAL_ACCOUNT_TYPES.includes(accountType);

export const getAccountAccessibilityIssues = (account: {
  accountType: PamAccountType | string;
  gatewayId?: string | null;
  gatewayPoolId?: string | null;
  templateGatewayId?: string | null;
  templateGatewayPoolId?: string | null;
  recordingConnectionId?: string | null;
  templateRecordingConnectionId: string | null;
  settingsOverrides?: unknown;
  templateSettings: unknown;
  credentialConfigured: boolean;
}): PamAccountAccessibilityIssue[] => {
  const issues: PamAccountAccessibilityIssue[] = [];

  if (
    accountTypeRequiresGateway(account.accountType as PamAccountType) &&
    !account.gatewayId &&
    !account.gatewayPoolId &&
    !account.templateGatewayId &&
    !account.templateGatewayPoolId
  ) {
    issues.push(PamAccountAccessibilityIssue.NoGateway);
  }

  if (accountTypeRequiresRecording(account.accountType as PamAccountType)) {
    const settingsParsed = PamTemplateSettingsSchema.safeParse(account.templateSettings);
    const parsedTemplateSettings = settingsParsed.success ? settingsParsed.data : null;
    const overridesParsed = PamAccountSettingsOverridesSchema.safeParse(account.settingsOverrides ?? {});
    const parsedOverrides = overridesParsed.success ? overridesParsed.data : null;

    const hasRecordingConfig = Boolean(
      parsedTemplateSettings?.recordingStorageBackend === PamRecordingStorageBackend.AwsS3 &&
      (account.recordingConnectionId || account.templateRecordingConnectionId) &&
      (parsedOverrides?.recordingS3Config || parsedTemplateSettings?.recordingS3Config)
    );
    if (!hasRecordingConfig) issues.push(PamAccountAccessibilityIssue.NoRecordingConfig);
  }

  if (accountTypeRequiresCredential(account.accountType as PamAccountType) && !account.credentialConfigured) {
    issues.push(PamAccountAccessibilityIssue.NoCredential);
  }
  return issues;
};

export type TSshInternalMetadata = z.infer<(typeof ACCOUNT_TYPE_CONFIGS)[PamAccountType.SSH]["internalMetadata"]>;

export const parseInternalMetadata = (accountType: PamAccountType, data: unknown): TSshInternalMetadata | null => {
  if (accountType === PamAccountType.SSH) {
    const result = ACCOUNT_TYPE_CONFIGS[PamAccountType.SSH].internalMetadata.safeParse(data);
    return result.success ? result.data : null;
  }
  return null;
};

// -- Frontend field metadata derived from the schemas above

// A bare `field` resolves within the field's own group; qualify it ("credentials.authMethod") to
// reference the other group
const PamFieldConditionSchema = z.object({
  field: z.string(),
  equals: z.union([z.string(), z.boolean()])
});

export const PamFieldDescriptorSchema = z.object({
  key: z.string(),
  label: z.string(),
  widget: z.nativeEnum(PamFieldWidget),
  required: z.boolean(),
  secret: z.boolean(),
  optional: z.boolean().optional(),
  options: z.array(z.object({ label: z.string(), value: z.string(), docsUrl: z.string().optional() })).optional(),

  // Value the form prefills the field with on create
  defaultValue: z.union([z.string(), z.number(), z.boolean()]).optional(),

  // Only render when the referenced field equals this value
  showWhen: PamFieldConditionSchema.optional(),

  // Value the field is pinned to while the condition holds. The server applies these rules before
  // validating, so a hand-written request cannot bypass one.
  forceWhen: z
    .array(
      z.object({
        when: PamFieldConditionSchema,
        value: z.union([z.string(), z.number(), z.boolean()]),
        reason: z.string()
      })
    )
    .optional(),

  // Info tooltip shown next to the label
  tooltip: z.string().optional(),

  // Help text shown under the field
  description: z.string().optional(),

  // Only show the description when the referenced field equals this value
  descriptionWhen: PamFieldConditionSchema.optional()
});

type PamFieldDescriptor = z.infer<typeof PamFieldDescriptorSchema>;

export const PamAccountTypeMetadataSchema = z.object({
  type: z.nativeEnum(PamAccountType),
  name: z.string(),
  icon: z.string(),
  supportsWebAccess: z.boolean(),
  requiresGateway: z.boolean(),
  supportsDependencies: z.boolean(),

  connectionStringSchemes: z.array(z.string()).optional(),
  connectionFields: z.array(PamFieldDescriptorSchema),
  credentialFields: z.array(PamFieldDescriptorSchema),
  applicablePolicies: z.array(PamPolicyDescriptorSchema)
});

type PamAccountTypeMetadata = z.infer<typeof PamAccountTypeMetadataSchema>;

type TFieldUiHint = {
  label?: string;
  widget?: PamFieldWidget;
  secret?: boolean;
  optional?: boolean;
  defaultValue?: string | number | boolean;
  showWhen?: TFieldConditionHint;
  forceWhen?: readonly TFieldForcedRuleHint[];
  tooltip?: string;
  description?: string;
  descriptionWhen?: TFieldConditionHint;
  options?: { label: string; value: string; docsUrl?: string }[];
};

const humanizeKey = (key: string) => {
  const spaced = key
    .replace(new RE2(/([A-Z])/g), " $1")
    .replace(new RE2(/-/g), " ")
    .trim();
  return spaced
    .split(" ")
    .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
    .join(" ");
};

const unwrapField = (schema: z.ZodTypeAny): { base: z.ZodTypeAny; required: boolean } => {
  let current = schema;
  let required = true;
  for (let depth = 0; depth < 20; depth += 1) {
    const { typeName } = current._def as { typeName?: string };
    if (typeName === "ZodOptional" || typeName === "ZodDefault") {
      required = false;
      current = (current._def as { innerType: z.ZodTypeAny }).innerType;
    } else if (typeName === "ZodNullable") {
      current = (current._def as { innerType: z.ZodTypeAny }).innerType;
    } else if (typeName === "ZodEffects") {
      current = (current._def as { schema: z.ZodTypeAny }).schema;
    } else {
      break;
    }
  }
  return { base: current, required };
};

const widgetForBase = (base: z.ZodTypeAny): PamFieldWidget => {
  const { typeName } = base._def as { typeName?: string };
  if (typeName === "ZodNumber") return PamFieldWidget.Number;
  if (typeName === "ZodBoolean") return PamFieldWidget.Boolean;
  if (typeName === "ZodEnum") return PamFieldWidget.Select;
  return PamFieldWidget.Text;
};

const describeField = (
  key: string,
  schema: z.ZodTypeAny,
  ui: Record<string, TFieldUiHint>,
  showWhen?: PamFieldDescriptor["showWhen"]
): PamFieldDescriptor => {
  const { base, required } = unwrapField(schema);
  const hint = ui[key] ?? {};
  const widget = hint.widget ?? widgetForBase(base);
  const enumValues = (base._def as { values?: string[] }).values;
  const resolvedShowWhen = hint.showWhen ?? showWhen;

  return {
    key,
    label: hint.label ?? humanizeKey(key),
    widget,
    required,
    secret: hint.secret ?? widget === PamFieldWidget.Password,
    ...(hint.optional ? { optional: true } : {}),
    ...(widget === PamFieldWidget.Select
      ? { options: hint.options ?? (enumValues ? enumValues.map((v) => ({ label: humanizeKey(v), value: v })) : []) }
      : {}),
    ...(hint.defaultValue !== undefined ? { defaultValue: hint.defaultValue } : {}),
    ...(resolvedShowWhen ? { showWhen: resolvedShowWhen } : {}),
    ...(hint.forceWhen ? { forceWhen: [...hint.forceWhen] } : {}),
    ...(hint.tooltip ? { tooltip: hint.tooltip } : {}),
    ...(hint.description ? { description: hint.description } : {}),
    ...(hint.descriptionWhen ? { descriptionWhen: hint.descriptionWhen } : {})
  };
};

const fieldsFromSchema = (schema: z.ZodTypeAny, ui: Record<string, TFieldUiHint> = {}): PamFieldDescriptor[] => {
  // Peels wrappers such as the legacy-discriminator preprocess so the described shape is the one underneath
  const { base } = unwrapField(schema);
  const { typeName } = base._def as { typeName?: string };

  if (typeName === "ZodObject") {
    const { shape } = base as z.ZodObject<z.ZodRawShape>;
    return Object.entries(shape).map(([key, fieldSchema]) => describeField(key, fieldSchema, ui));
  }

  // Discriminated union (e.g. SSH authMethod)
  if (typeName === "ZodDiscriminatedUnion") {
    const def = base._def as {
      discriminator: string;
      options: z.ZodObject<z.ZodRawShape>[];
    };
    const variants = [...def.options];
    const { discriminator } = def;

    const occurrences = new Map<string, number>();
    variants.forEach((variant) => {
      Object.keys(variant.shape).forEach((key) => {
        if (key !== discriminator) occurrences.set(key, (occurrences.get(key) ?? 0) + 1);
      });
    });

    const discriminatorValues = variants.map(
      (variant) => (variant.shape[discriminator]._def as { value: string }).value
    );
    const discHint = ui[discriminator] ?? {};
    const fields: PamFieldDescriptor[] = [
      {
        key: discriminator,
        label: discHint.label ?? humanizeKey(discriminator),
        widget: PamFieldWidget.Select,
        required: true,
        secret: false,
        options: discHint.options ?? discriminatorValues.map((v) => ({ label: humanizeKey(v), value: v })),
        ...(discHint.defaultValue !== undefined ? { defaultValue: discHint.defaultValue } : {}),
        ...(discHint.tooltip ? { tooltip: discHint.tooltip } : {})
      }
    ];

    const added = new Set<string>([discriminator]);
    variants.forEach((variant) => {
      const variantValue = (variant.shape[discriminator]._def as { value: string }).value;
      Object.entries(variant.shape).forEach(([key, fieldSchema]) => {
        if (key === discriminator) return;
        const isShared = occurrences.get(key) === variants.length;
        if (isShared) {
          if (added.has(key)) return;
          added.add(key);
          fields.push(describeField(key, fieldSchema, ui));
        } else {
          fields.push(describeField(key, fieldSchema, ui, { field: discriminator, equals: variantValue }));
        }
      });
    });
    return fields;
  }

  return [];
};

export const buildPamAccountTypeMetadata = (webAccessSupportedTypes: Set<PamAccountType>): PamAccountTypeMetadata[] =>
  (
    Object.entries(ACCOUNT_TYPE_CONFIGS) as [
      TSupportedAccountType,
      (typeof ACCOUNT_TYPE_CONFIGS)[TSupportedAccountType]
    ][]
  ).map(([type, config]) => ({
    type,
    name: config.name,
    icon: config.icon,
    supportsWebAccess: webAccessSupportedTypes.has(type),
    requiresGateway: accountTypeRequiresGateway(type),
    supportsDependencies: isWindowsRotatableType(type),
    connectionStringSchemes: accountTypeConnectionStringSchemes(type),
    connectionFields: fieldsFromSchema(config.connectionDetails, config.ui),
    credentialFields: fieldsFromSchema(config.credentials, config.ui),
    applicablePolicies: getApplicablePolicies(type)
  }));

export type TPamFieldGroup = "connectionDetails" | "credentials";
export type TPamFieldValues = Record<TPamFieldGroup, Record<string, unknown>>;

const conditionHolds = (
  condition: { field: string; equals: string | boolean },
  group: TPamFieldGroup,
  values: TPamFieldValues
): boolean => {
  const separatorIdx = condition.field.indexOf(".");
  const [targetGroup, key] =
    separatorIdx === -1
      ? [group, condition.field]
      : [condition.field.slice(0, separatorIdx) as TPamFieldGroup, condition.field.slice(separatorIdx + 1)];

  return values[targetGroup]?.[key] === condition.equals;
};

// Conditions read the caller's values rather than the accumulating result, so rules cannot chain off
// one another and their order never matters.
export const applyForcedFields = (accountType: PamAccountType, values: TPamFieldValues): TPamFieldValues => {
  const config = getAccountTypeConfig(accountType);
  const fieldsByGroup: Record<TPamFieldGroup, PamFieldDescriptor[]> = {
    connectionDetails: fieldsFromSchema(config.connectionDetails, config.ui),
    credentials: fieldsFromSchema(config.credentials, config.ui)
  };

  const result: TPamFieldValues = {
    connectionDetails: { ...values.connectionDetails },
    credentials: { ...values.credentials }
  };

  (Object.keys(fieldsByGroup) as TPamFieldGroup[]).forEach((group) => {
    fieldsByGroup[group].forEach((field) => {
      const rule = field.forceWhen?.find((candidate) => conditionHolds(candidate.when, group, values));
      if (rule) result[group][field.key] = rule.value;
    });
  });

  return result;
};

// The edit form resends username and auth method with an untouched password stripped, so a credentials object
// on its own does not mean the caller held the credential.
export const suppliesCredentialSecret = (
  accountType: PamAccountType,
  rawCredentials: Record<string, unknown> | undefined
): boolean => {
  if (!rawCredentials) return false;
  const config = ACCOUNT_TYPE_CONFIGS[accountType as TSupportedAccountType];
  if (!config) return false;

  const credentials = normalizeCredentialAuthMethod(accountType, rawCredentials);
  return fieldsFromSchema(config.credentials, config.ui)
    .filter((field) => field.secret)
    .some((field) => {
      const value = credentials[field.key];
      return typeof value === "string" && value.trim().length > 0;
    });
};

// Redaction inputs for anything a target echoes back
export const collectCredentialSecrets = (
  accountType: PamAccountType,
  rawCredentials: Record<string, unknown>
): string[] => {
  const config = ACCOUNT_TYPE_CONFIGS[accountType as TSupportedAccountType];
  if (!config) return [];

  const credentials = normalizeCredentialAuthMethod(accountType, rawCredentials);
  return fieldsFromSchema(config.credentials, config.ui)
    .filter((field) => field.secret)
    .map((field) => credentials[field.key])
    .filter((value): value is string => typeof value === "string" && value.length > 0);
};

export const isCredentialConfigured = (
  accountType: PamAccountType,
  rawCredentials: Record<string, unknown>
): boolean => {
  const config = ACCOUNT_TYPE_CONFIGS[accountType as TSupportedAccountType];
  if (!config) return false;

  // Callers include paths that read the stored blob directly, where an older account has no auth
  // method and would match none of the variants' secret fields
  const credentials = normalizeCredentialAuthMethod(accountType, rawCredentials);

  const applicableSecretFields = fieldsFromSchema(config.credentials, config.ui).filter(
    (field) => field.secret && (!field.showWhen || credentials[field.showWhen.field] === field.showWhen.equals)
  );
  if (applicableSecretFields.length === 0) return true;

  return applicableSecretFields.some((field) => {
    const value = credentials[field.key];
    return typeof value === "string" && value.trim().length > 0;
  });
};

export const revealedCredentialsSchema = (accountType: TSupportedAccountType) => {
  const config = ACCOUNT_TYPE_CONFIGS[accountType];
  return config.sanitizedCredentials.extend(
    Object.fromEntries(
      fieldsFromSchema(config.credentials, config.ui)
        .filter((field) => field.secret)
        .map((field) => [field.key, z.string().optional()])
    )
  );
};

export const noRevealableCredentialMessage = (accountName: string) =>
  `Account '${accountName}' has no stored credential to reveal. Its authentication method brokers access per session instead.`;

export const hasRevealableCredential = (
  accountType: PamAccountType,
  rawCredentials?: Record<string, unknown>
): boolean => {
  const config = ACCOUNT_TYPE_CONFIGS[accountType as TSupportedAccountType];
  if (!config) return false;

  const secretFields = fieldsFromSchema(config.credentials, config.ui).filter((field) => field.secret);
  if (!rawCredentials) return secretFields.length > 0;

  const credentials = normalizeCredentialAuthMethod(accountType, rawCredentials);
  return secretFields.some((field) => {
    if (field.showWhen && credentials[field.showWhen.field] !== field.showWhen.equals) return false;
    const value = credentials[field.key];
    return typeof value === "string" && value.trim().length > 0;
  });
};