Skip to content

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

5.3 KB
Raw Blame
import { AnyZodObject, z } from "zod";

import { AppConnection } from "@app/hooks/api/appConnections/enums";

export const HOST_COMMAND_MAX_LENGTH = 8192;

export const MAX_FILTER_CERTIFICATE_ORDERS = 10_000;

const KEYSTORE_ALIAS_CHARACTERS =
  "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-";

export const KEYSTORE_PASSWORD_REQUIRED_MESSAGE =
  "A password is required for PKCS#12 and JKS exports";

export const ExportPasswordSchema = z
  .string()
  .min(1)
  .max(1024, "The export password must be at most 1024 characters")
  .refine((password) => password.trim().length > 0, {
    message: "The export password cannot be blank"
  });

export const KeystoreAliasSchema = z
  .string()
  .trim()
  .max(128, "Keystore alias must be at most 128 characters")
  .refine((v) => [...v].every((c) => KEYSTORE_ALIAS_CHARACTERS.includes(c)), {
    message:
      "Keystore alias may only contain letters, digits, dots (.), dashes (-), and underscores (_)"
  })
  .transform((v) => v || undefined)
  .optional();

export const HostCommandSchema = z
  .string()
  .trim()
  .max(HOST_COMMAND_MAX_LENGTH, `Command must be at most ${HOST_COMMAND_MAX_LENGTH} characters`)
  .nullish()
  .transform((command) => command || null);

export const PkiSyncConnectionSchema = z.object({
  id: z.string().uuid("Invalid connection ID format"),
  name: z.string().max(255, "Connection name must be less than 255 characters"),
  app: z.nativeEnum(AppConnection).optional()
});

export const PkiSyncTargetPortSchema = z.coerce
  .number()
  .int()
  .min(1, "Port must be between 1 and 65535")
  .max(65535, "Port must be between 1 and 65535")
  .optional();

export const PkiSyncTargetHostSchema = z
  .string()
  .trim()
  .max(253, "Target host is too long")
  .refine(
    (value) =>
      !value ||
      /^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(
        value
      ),
    {
      message:
        "Target host must be a hostname or IP address (for example server01.corp.example.com or 10.0.0.5)"
    }
  )
  .transform((value) => value || undefined)
  .optional();

export const BasePkiSyncSchema = <T extends AnyZodObject | undefined = undefined>(
  additionalSyncOptions?: T
) => {
  const baseSyncOptionsSchema = z.object({
    canImportCertificates: z.boolean().default(false),
    canRemoveCertificates: z.boolean().default(false),
    includeRootCa: z.boolean().default(false),
    certificateNameSchema: z
      .string()
      .trim()
      .min(1, "Certificate name schema is required")
      .refine(
        (val) => {
          const allowedOptionalPlaceholders = [
            "{{profileId}}",
            "{{applicationId}}",
            "{{applicationName}}",
            "{{commonName}}"
          ];

          const allowedPlaceholdersRegexPart = [
            "{{certificateId}}",
            "{{shortCertificateId}}",
            ...allowedOptionalPlaceholders
          ]
            .map((p) => p.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&")) // Escape regex special characters
            .join("|");

          const allowedContentRegex = new RegExp(
            `^([a-zA-Z0-9_\\-/]|${allowedPlaceholdersRegexPart})*$`
          );
          const contentIsValid = allowedContentRegex.test(val);

          const certificateIdIsPresent =
            val.includes("{{certificateId}}") || val.includes("{{shortCertificateId}}");
          return contentIsValid && certificateIdIsPresent;
        },
        {
          message:
            "Certificate name schema must include the {{certificateId}} or {{shortCertificateId}} placeholder. It can also include {{profileId}}, {{applicationId}}, {{applicationName}}, and {{commonName}} placeholders. Only alphanumeric characters (a-z, A-Z, 0-9), dashes (-), underscores (_), and slashes (/) are allowed besides the placeholders."
        }
      )
  });

  const syncOptionsSchema = additionalSyncOptions
    ? baseSyncOptionsSchema.merge(additionalSyncOptions)
    : (baseSyncOptionsSchema as T extends AnyZodObject
        ? z.ZodObject<z.objectUtil.MergeShapes<typeof baseSyncOptionsSchema.shape, T["shape"]>>
        : typeof baseSyncOptionsSchema);

  return z.object({
    name: z
      .string()
      .trim()
      .min(1, "Name is required")
      .max(256, "Name must be less than 256 characters"),
    description: z.string().optional(),
    isAutoSyncEnabled: z.boolean().default(true),
    subscriberId: z.string().nullable().optional(),
    filters: z
      .object({
        profileIds: z
          .array(z.string().uuid())
          .max(20, "A filter can use at most 20 profiles")
          .optional(),
        certificateOrderIds: z
          .string()
          .uuid()
          .array()
          .max(
            MAX_FILTER_CERTIFICATE_ORDERS,
            `A filter can name at most ${MAX_FILTER_CERTIFICATE_ORDERS} certificate orders`
          )
          .optional(),
        metadata: z
          .array(
            z.object({
              key: z.string().trim().min(1, "Enter a metadata key or remove the pair").max(255),
              value: z.string().trim().max(1020).optional()
            })
          )
          .max(20, "A filter can use at most 20 metadata pairs")
          .optional()
      })
      .nullish(),
    connection: PkiSyncConnectionSchema,
    syncOptions: syncOptionsSchema
  });
};