Skip to content

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

2.6 KB
Raw Blame
import RE2 from "re2";
import { z } from "zod";

import { refineNoDuplicates } from "./agent-vault-list-schema-fns";

export const AGENT_VAULT_MAX_PATH_PREFIX_LENGTH = 512;
export const AGENT_VAULT_MAX_PATH_PREFIXES = 20;

// A prefix is compared against the escaped path, so anything the encoder rewrites could never match:
// `/café` would be judged against `/caf%C3%A9`. Deliberate exclusions on top of that: '%' keeps the
// comparison exact, ';' and '\' are what isAmbiguousPath refuses, '?' and '#' end the path, ',' commits a
// chip in the UI. Anything else left out, '(' say, survives the wire but is useless in a prefix anyway,
// since matching is by whole segment and `/Products` never covers `/Products(1)`.
const PATH_PREFIX_RE = new RE2(/^\/[A-Za-z0-9\-._~$&+/:=@]*$/);

const hasTraversalSegment = (value: string) => value.split("/").some((segment) => segment === "." || segment === "..");

// '/' keeps its trailing slash: stripping it would leave an empty string, which means nothing.
export const normalizePathPrefix = (value: string) => {
  const trimmed = value.trim();
  if (trimmed === "/") return trimmed;
  return trimmed.replace(/\/+$/, "");
};

const pathPrefixError = (raw: string) => {
  const value = raw.trim();
  if (!value) return "A path prefix can't be empty.";
  if (value.length > AGENT_VAULT_MAX_PATH_PREFIX_LENGTH)
    return `"${value.slice(0, 40)}…" is longer than ${AGENT_VAULT_MAX_PATH_PREFIX_LENGTH} characters.`;
  if (!value.startsWith("/")) return `"${value}" must start with a /.`;
  if (value.includes("//")) return `"${value}" can't contain an empty path segment.`;
  if (hasTraversalSegment(value)) return `"${value}" can't contain a . or .. segment.`;
  if (!PATH_PREFIX_RE.test(value)) return `"${value}" can only contain letters, digits and - . _ ~ $ & + : = @.`;
  return null;
};

// No `.max()`: pathPrefixError measures the length itself, and Zod's check would fire alongside it.
export const pathPrefixSchema = z
  .string()
  .trim()
  .superRefine((raw, ctx) => {
    const message = pathPrefixError(raw);
    if (message) ctx.addIssue({ code: z.ZodIssueCode.custom, message });
  })
  .transform(normalizePathPrefix);

// NULL is the only "every path", so the proxy never has two representations to treat alike. `.nullable()`
// without `.optional()`, so a PATCH omitting the field leaves the column alone and an explicit null clears it.
export const agentVaultPathPrefixListSchema = z
  .array(pathPrefixSchema)
  .min(1, "Add at least one path prefix, or leave this unset to allow every path.")
  .max(AGENT_VAULT_MAX_PATH_PREFIXES)
  .superRefine(refineNoDuplicates)
  .nullable();