Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat(validator): add SSRF protection and safe request handling
Victor Hugo dos Santoscf4effa7e74c
diff --git a/backend/src/lib/validator/index.ts b/backend/src/lib/validator/index.tsindex 7ac495d51b..647d1ca2de 100644--- a/backend/src/lib/validator/index.ts+++ b/backend/src/lib/validator/index.ts@@ -1,4 +1,6 @@export { matchesAllowedEmailDomain } from "./email-domain-matcher";+export type { TValidatedHost } from "./safe-request";+export { buildSsrfSafeAgent, safeRequest } from "./safe-request";export { isDisposableEmail, isValidEmailDomain, sanitizeEmail, validateEmail } from "./validate-email";export { isValidFolderName, isValidSecretPath } from "./validate-folder-name";export {diff --git a/backend/src/lib/validator/safe-request.test.ts b/backend/src/lib/validator/safe-request.test.tsnew file mode 100644index 0000000000..76059bc2e6--- /dev/null+++ b/backend/src/lib/validator/safe-request.test.ts@@ -0,0 +1,398 @@+/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-argument */+import type { AgentOptions as HttpAgentOptions } from "node:http";+import type { Agent as HttpsAgent } from "node:https";++import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { buildSsrfSafeAgent, safeRequest, validateAndPinUrl } from "./safe-request";++type MockedRequestFn = (config: unknown) => Promise<{+ data: unknown;+ status: number;+ headers: Record<string, unknown>;+}>;++// `vi.mock` factories run in a hoisted scope before normal `const` init — any+// `vi.fn` / state they close over must come from `vi.hoisted`.+const { lookupMock, configState, verifyHostInputValidityMock, requestRequestMock } = vi.hoisted(() => {+ const lookup = vi.fn<(hostname: string, opts: { all?: boolean }) => Promise<{ address: string; family: 4 | 6 }[]>>();++ const config = {+ isDevelopmentMode: false,+ ALLOW_INTERNAL_IP_CONNECTIONS: false,+ SITE_URL: "https://infisical.example",+ REDIS_URL: "redis://internal-redis:6379",+ DB_HOST: "internal-db",+ isHsmConfigured: false+ };++ const verifyHost = vi.fn(async () => undefined);++ const requestReq = vi.fn<MockedRequestFn>(async () => ({+ data: undefined,+ status: 200,+ headers: {}+ }));++ return {+ lookupMock: lookup,+ configState: config,+ verifyHostInputValidityMock: verifyHost,+ requestRequestMock: requestReq+ };+});++vi.mock("node:dns/promises", () => ({+ default: { lookup: (...args: unknown[]) => (lookupMock as any)(...args) },+ lookup: (...args: unknown[]) => (lookupMock as any)(...args)+}));++vi.mock("@app/lib/config/env", () => ({+ getConfig: () => configState+}));++vi.mock("@app/ee/services/dynamic-secret/dynamic-secret-fns", () => ({+ verifyHostInputValidity: verifyHostInputValidityMock+}));++vi.mock("@app/lib/config/request", () => ({+ request: { request: (...args: unknown[]) => (requestRequestMock as any)(...args) }+}));++const PUBLIC_IP_V4 = "8.8.8.8";+const PUBLIC_IP_V4_ALT = "1.1.1.1";+const PRIVATE_IP_V4 = "10.0.0.1";+const LOOPBACK_IP_V4 = "127.0.0.1";+const PUBLIC_IP_V6 = "2606:4700::1";++const setLookup = (entries: { address: string; family: 4 | 6 }[]) => {+ lookupMock.mockReset();+ lookupMock.mockResolvedValue(entries);+};++const lastRequestArgs = () => {+ const { calls } = requestRequestMock.mock;+ return calls[calls.length - 1]?.[0] as Record<string, any>;+};++describe("safe-request SSRF helpers", () => {+ beforeEach(() => {+ configState.isDevelopmentMode = false;+ configState.ALLOW_INTERNAL_IP_CONNECTIONS = false;+ requestRequestMock.mockReset();+ requestRequestMock.mockResolvedValue({ data: undefined, status: 200, headers: {} });+ verifyHostInputValidityMock.mockReset();+ verifyHostInputValidityMock.mockResolvedValue(undefined);+ setLookup([{ address: PUBLIC_IP_V4, family: 4 }]);+ });++ afterEach(() => {+ vi.clearAllMocks();+ });++ describe("validateAndPinUrl", () => {+ it("returns undefined when allowPrivateIps is true (no validation, no pinning)", async () => {+ const result = await validateAndPinUrl("http://10.0.0.1/whatever", { allowPrivateIps: true });+ expect(result).toBeUndefined();+ expect(lookupMock).not.toHaveBeenCalled();+ expect(verifyHostInputValidityMock).not.toHaveBeenCalled();+ });++ it("returns undefined in development mode (escape hatch for local dev)", async () => {+ configState.isDevelopmentMode = true;+ const result = await validateAndPinUrl("https://example.com");+ expect(result).toBeUndefined();+ });++ it("rejects URLs with embedded user credentials", async () => {+ await expect(validateAndPinUrl("https://user:[email protected]")).rejects.toThrow(/user credentials/i);+ });++ it("rejects literal `localhost` hostnames", async () => {+ await expect(validateAndPinUrl("http://localhost:8080")).rejects.toThrow(/Local IPs not allowed/i);+ });++ it("rejects literal `host.docker.internal` hostnames", async () => {+ await expect(validateAndPinUrl("http://host.docker.internal")).rejects.toThrow(/Local IPs not allowed/i);+ });++ it("rejects RFC1918 / loopback IPs by default", async () => {+ setLookup([{ address: PRIVATE_IP_V4, family: 4 }]);+ await expect(validateAndPinUrl("https://example.com")).rejects.toThrow(/Local IPs not allowed/i);+ });++ it("rejects loopback IPv4 even when configured as a literal IP", async () => {+ await expect(validateAndPinUrl(`http://${LOOPBACK_IP_V4}`)).rejects.toThrow(/Local IPs not allowed/i);+ // Literal IPs must NOT trigger DNS lookup.+ expect(lookupMock).not.toHaveBeenCalled();+ });++ it("allows private IPs when ALLOW_INTERNAL_IP_CONNECTIONS is true", async () => {+ configState.ALLOW_INTERNAL_IP_CONNECTIONS = true;+ setLookup([{ address: PRIVATE_IP_V4, family: 4 }]);+ const result = await validateAndPinUrl("https://internal.example");+ expect(result).toEqual({+ hostname: "internal.example",+ entries: [{ address: PRIVATE_IP_V4, family: 4 }]+ });+ });++ it("invokes verifyHostInputValidity to block Infisical-internal hosts (DB/Redis)", async () => {+ verifyHostInputValidityMock.mockRejectedValueOnce(new Error("blocked: internal infra"));+ await expect(validateAndPinUrl("https://internal-db.example")).rejects.toThrow(/internal infra/i);+ });++ it("returns the resolved IPs on success so the caller can pin to them", async () => {+ setLookup([+ { address: PUBLIC_IP_V4, family: 4 },+ { address: PUBLIC_IP_V4_ALT, family: 4 }+ ]);+ const result = await validateAndPinUrl("https://example.com");+ expect(result?.hostname).toBe("example.com");+ expect(result?.entries).toEqual([+ { address: PUBLIC_IP_V4, family: 4 },+ { address: PUBLIC_IP_V4_ALT, family: 4 }+ ]);+ });++ it("throws when DNS returns no addresses", async () => {+ setLookup([]);+ await expect(validateAndPinUrl("https://example.com")).rejects.toThrow(/Could not resolve hostname/i);+ });+ });++ describe("buildSsrfSafeAgent / pinned lookup", () => {+ it("returns undefined when nothing needs customization (dev mode + no TLS opts)", async () => {+ configState.isDevelopmentMode = true;+ const agent = await buildSsrfSafeAgent("https://example.com");+ expect(agent).toBeUndefined();+ });++ it("returns an https.Agent with a pinned `lookup` for HTTPS targets", async () => {+ const agent = await buildSsrfSafeAgent("https://example.com");+ expect(agent).toBeDefined();+ const opts = (agent as HttpsAgent).options;+ expect(typeof opts.lookup).toBe("function");+ // Cached agents default to keepAlive: true for connection reuse.+ expect(opts.keepAlive).toBe(true);+ });++ it("returns an http.Agent for HTTP targets", async () => {+ const agent = await buildSsrfSafeAgent("http://example.com");+ expect(agent).toBeDefined();+ const opts = (agent as unknown as { options: HttpAgentOptions }).options;+ expect(typeof opts.lookup).toBe("function");+ });++ it("propagates ca / rejectUnauthorized / servername / keepAlive / checkServerIdentity to https.Agent", async () => {+ const checkServerIdentity = () => undefined;+ const agent = await buildSsrfSafeAgent("https://example.com", {+ ca: "-----BEGIN CERTIFICATE-----",+ rejectUnauthorized: false,+ servername: "alt.example.com",+ keepAlive: true,+ checkServerIdentity+ });+ const opts = (agent as HttpsAgent).options;+ expect(opts.ca).toBe("-----BEGIN CERTIFICATE-----");+ expect(opts.rejectUnauthorized).toBe(false);+ expect(opts.servername).toBe("alt.example.com");+ expect(opts.keepAlive).toBe(true);+ expect(opts.checkServerIdentity).toBe(checkServerIdentity);+ });++ describe("pinned lookup function", () => {+ const getLookup = async (entries: { address: string; family: 4 | 6 }[]) => {+ setLookup(entries);+ const agent = await buildSsrfSafeAgent("https://example.com");+ const opts = (agent as HttpsAgent).options;+ return opts.lookup as unknown as (+ hostname: string,+ optionsOrCb: { all?: boolean; family?: number } | ((...args: any[]) => void),+ cb?: (...args: any[]) => void+ ) => void;+ };++ it("supports the 2-arg `lookup(hostname, callback)` form", async () => {+ const lookup = await getLookup([+ { address: PUBLIC_IP_V4, family: 4 },+ { address: PUBLIC_IP_V4_ALT, family: 4 }+ ]);+ const result: { err: Error | null; address: string; family: number } = await new Promise((resolve) => {+ lookup("example.com", (err, address, family) => resolve({ err, address, family }));+ });+ expect(result.err).toBeNull();+ expect(result.address).toBe(PUBLIC_IP_V4);+ expect(result.family).toBe(4);+ });++ it("supports the 3-arg `lookup(hostname, options, callback)` form", async () => {+ const lookup = await getLookup([{ address: PUBLIC_IP_V4, family: 4 }]);+ const result: { err: Error | null; address: string; family: number } = await new Promise((resolve) => {+ lookup("example.com", {}, (err: Error | null, address: string, family: number) =>+ resolve({ err, address, family })+ );+ });+ expect(result.err).toBeNull();+ expect(result.address).toBe(PUBLIC_IP_V4);+ });++ it("returns ALL pre-validated entries when `all: true`", async () => {+ const entries = [+ { address: PUBLIC_IP_V4, family: 4 as const },+ { address: PUBLIC_IP_V4_ALT, family: 4 as const }+ ];+ const lookup = await getLookup(entries);+ const result: { err: Error | null; addresses: { address: string; family: number }[] } = await new Promise(+ (resolve) => {+ lookup(+ "example.com",+ { all: true },+ (err: Error | null, addresses: { address: string; family: number }[]) => resolve({ err, addresses })+ );+ }+ );+ expect(result.err).toBeNull();+ expect(result.addresses).toEqual(entries);+ });++ it("filters entries by requested family", async () => {+ const lookup = await getLookup([+ { address: PUBLIC_IP_V4, family: 4 },+ { address: PUBLIC_IP_V6, family: 6 }+ ]);+ const result: { err: Error | null; address: string; family: number } = await new Promise((resolve) => {+ lookup("example.com", { family: 6 }, (err: Error | null, address: string, family: number) =>+ resolve({ err, address, family })+ );+ });+ expect(result.err).toBeNull();+ expect(result.address).toBe(PUBLIC_IP_V6);+ expect(result.family).toBe(6);+ });++ it("returns ENOTFOUND when the requested family cannot be satisfied (no silent fallback)", async () => {+ const lookup = await getLookup([{ address: PUBLIC_IP_V4, family: 4 }]);+ const result: { err: any; address: string; family: number } = await new Promise((resolve) => {+ lookup("example.com", { family: 6 }, (err: any, address: string, family: number) =>+ resolve({ err, address, family })+ );+ });+ expect(result.err).toBeTruthy();+ expect(result.err.code).toBe("ENOTFOUND");+ expect(result.err.hostname).toBe("example.com");+ });+ });+ });++ describe("safeRequest dispatch", () => {+ it("validates the URL, builds a pinned agent, and forwards to the underlying axios with maxRedirects:0", async () => {+ requestRequestMock.mockResolvedValueOnce({ data: { ok: true }, status: 200, headers: {} });+ const result = await safeRequest.get<{ ok: boolean }>("https://example.com/path", { headers: { "x-test": "1" } });+ expect(result.data).toEqual({ ok: true });++ const args = lastRequestArgs();+ expect(args.method).toBe("GET");+ expect(args.url).toBe("https://example.com/path");+ expect(args.maxRedirects).toBe(0);+ expect(args.headers).toEqual({ "x-test": "1" });+ expect(args.httpsAgent).toBeDefined();+ expect(args.httpAgent).toBeUndefined();+ });++ it("attaches httpAgent (not httpsAgent) for HTTP URLs", async () => {+ requestRequestMock.mockResolvedValueOnce({ data: undefined, status: 204, headers: {} });+ await safeRequest.post("http://example.com/p", { x: 1 });+ const args = lastRequestArgs();+ expect(args.httpsAgent).toBeUndefined();+ expect(args.httpAgent).toBeDefined();+ });++ it("plumbs validateStatus through dispatch", async () => {+ requestRequestMock.mockResolvedValueOnce({ data: undefined, status: 401, headers: {} });+ const validateStatus = (s: number) => s < 500;+ await safeRequest.get("https://example.com", { validateStatus });+ const args = lastRequestArgs();+ expect(args.validateStatus).toBe(validateStatus);+ });++ it("skips agent customization when nothing needs it (dev mode + no TLS opts)", async () => {+ configState.isDevelopmentMode = true;+ requestRequestMock.mockResolvedValueOnce({ data: undefined, status: 200, headers: {} });+ await safeRequest.get("https://example.com");+ const args = lastRequestArgs();+ expect(args.httpsAgent).toBeUndefined();+ expect(args.httpAgent).toBeUndefined();+ });++ it("forwards safeRequest.put / patch / delete with the right method", async () => {+ requestRequestMock.mockResolvedValue({ data: undefined, status: 200, headers: {} });+ await safeRequest.put("https://example.com", { a: 1 });+ expect(lastRequestArgs().method).toBe("PUT");+ await safeRequest.patch("https://example.com", { a: 1 });+ expect(lastRequestArgs().method).toBe("PATCH");+ await safeRequest.delete("https://example.com");+ expect(lastRequestArgs().method).toBe("DELETE");+ });++ it("safeRequest.delete preserves options.data (Axios DELETE-with-body)", async () => {+ requestRequestMock.mockResolvedValue({ data: undefined, status: 200, headers: {} });+ const body = { workspaceId: "w-1", environment: "prod", secretPath: "/", secrets: [{ secretKey: "K" }] };+ await safeRequest.delete("https://example.com/v3/secrets/batch/raw", {+ headers: { Authorization: "Bearer t" },+ data: body+ });+ const args = lastRequestArgs();+ expect(args.method).toBe("DELETE");+ expect(args.data).toEqual(body);+ expect(args.headers).toEqual({ Authorization: "Bearer t" });+ });++ it("safeRequest.get preserves options.data (Axios GET-with-body, unusual but legal)", async () => {+ requestRequestMock.mockResolvedValue({ data: undefined, status: 200, headers: {} });+ const body = { query: "x" };+ await safeRequest.get("https://example.com/search", { data: body });+ const args = lastRequestArgs();+ expect(args.method).toBe("GET");+ expect(args.data).toEqual(body);+ });++ it("positional body wins over options.data for post/put/patch (matches Axios)", async () => {+ requestRequestMock.mockResolvedValue({ data: undefined, status: 200, headers: {} });+ const positional = { positional: true };+ const optionsData = { positional: false };+ await safeRequest.post("https://example.com", positional, { data: optionsData } as any);+ expect(lastRequestArgs().data).toEqual(positional);+ await safeRequest.put("https://example.com", positional, { data: optionsData } as any);+ expect(lastRequestArgs().data).toEqual(positional);+ await safeRequest.patch("https://example.com", positional, { data: optionsData } as any);+ expect(lastRequestArgs().data).toEqual(positional);+ });++ it("safeRequest.request validates absolute `url` even when baseURL is set (Axios-compatible)", async () => {+ requestRequestMock.mockResolvedValueOnce({ data: undefined, status: 200, headers: {} });+ await safeRequest.request({+ url: "https://example.com/v1/items",+ method: "GET",+ baseURL: "https://attacker.example"+ });+ // Axios uses the absolute URL when one is provided; we must validate+ // the exact URL Axios will request — `https://example.com/v1/items`,+ // NOT a `new URL("/v1/items", baseURL)` recombination.+ expect(lookupMock).toHaveBeenCalledWith("example.com", expect.any(Object));+ expect(lookupMock).not.toHaveBeenCalledWith("attacker.example", expect.any(Object));+ });++ it("safeRequest.request validates the combined URL when `url` is relative and baseURL is set", async () => {+ requestRequestMock.mockResolvedValueOnce({ data: undefined, status: 200, headers: {} });+ await safeRequest.request({+ url: "/v1/items",+ method: "GET",+ baseURL: "https://example.com/api"+ });+ // Axios path-joins baseURL + url; we must do the same so the URL we+ // SSRF-validate is the URL Axios actually requests.+ expect(lookupMock).toHaveBeenCalledWith("example.com", expect.any(Object));+ });+ });+});diff --git a/backend/src/lib/validator/safe-request.ts b/backend/src/lib/validator/safe-request.tsnew file mode 100644index 0000000000..40162ba86e--- /dev/null+++ b/backend/src/lib/validator/safe-request.ts@@ -0,0 +1,357 @@+import { LookupAddress } from "node:dns";+import dns from "node:dns/promises";+import http from "node:http";+import https from "node:https";+import { LookupFunction } from "node:net";++import { AxiosRequestConfig } from "axios";+import { isIP } from "net";++import { verifyHostInputValidity } from "@app/ee/services/dynamic-secret/dynamic-secret-fns";+import { getConfig } from "@app/lib/config/env";+import { request } from "@app/lib/config/request";++import { BadRequestError } from "../errors";+import { isPrivateIp } from "../ip/ipRange";++export type TValidatedHost = {+ hostname: string;+ entries: LookupAddress[];+};++type SafeRequestSharedOptions = {+ allowPrivateIps?: boolean;+};++// Validates the URL and resolves its IPs in a single DNS lookup. Returning the+// resolved entries lets the caller pin the connection to the same IPs that+// passed validation, closing the rebinding window between validate and connect.+export const validateAndPinUrl = async (+ url: string,+ options?: SafeRequestSharedOptions+): Promise<TValidatedHost | undefined> => {+ const appCfg = getConfig();++ if (options?.allowPrivateIps) return undefined;+ if (appCfg.isDevelopmentMode) return undefined;++ const validUrl = new URL(url);++ if (validUrl.username || validUrl.password) {+ throw new BadRequestError({ message: "URLs with user credentials (e.g., user:pass@) are not allowed" });+ }++ let entries: LookupAddress[];+ if (isIP(validUrl.hostname)) {+ entries = [{ address: validUrl.hostname, family: isIP(validUrl.hostname) }];+ } else {+ if (validUrl.hostname === "localhost" || validUrl.hostname === "host.docker.internal") {+ throw new BadRequestError({ message: "Local IPs not allowed as URL" });+ }+ const lookups = await dns.lookup(validUrl.hostname, { all: true });++ if (!lookups || lookups.length === 0) {+ throw new BadRequestError({ message: "Could not resolve hostname to any IP address" });+ }+ entries = lookups;+ }++ const isInternalIp = entries.some((e) => isPrivateIp(e.address));+ if (isInternalIp && !appCfg.ALLOW_INTERNAL_IP_CONNECTIONS) {+ throw new BadRequestError({ message: "Local IPs not allowed as URL" });+ }++ // Block Infisical's own infrastructure (DB, Redis, etc.).+ await verifyHostInputValidity({ host: validUrl.hostname, isGateway: false, isDynamicSecret: false });++ return { hostname: validUrl.hostname, entries };+};++type TLookupOneCallback = (err: NodeJS.ErrnoException | null, address: string, family: number) => void;+type TLookupAllCallback = (err: NodeJS.ErrnoException | null, addresses: LookupAddress[]) => void;++const notFoundError = (hostname: string): NodeJS.ErrnoException => {+ const err = new Error(`getaddrinfo ENOTFOUND ${hostname}`) as NodeJS.ErrnoException & { hostname?: string };+ err.code = "ENOTFOUND";+ err.errno = -3008;+ err.syscall = "getaddrinfo";+ err.hostname = hostname;+ return err;+};++// v4-first ordering so Happy Eyeballs races a healthy v4 path before falling+// through to v6 after autoSelectFamilyAttemptTimeout.+const sortV4First = (entries: LookupAddress[]): LookupAddress[] => entries.slice().sort((a, b) => a.family - b.family);++const pickPreferredEntry = (entries: LookupAddress[]): LookupAddress =>+ entries.find((e) => e.family === 4) ?? entries[0];++// dns.lookup-shaped function that always returns the pre-validated IPs.+// Installed on an http(s).Agent so connect-time DNS cannot land on a different+// IP than the one validation approved.+const makePinnedLookup = (entries: LookupAddress[]): LookupFunction =>+ ((hostname: string, optionsOrCb: unknown, maybeCb?: unknown) => {+ if (typeof optionsOrCb === "function") {+ const first = pickPreferredEntry(entries);+ (optionsOrCb as TLookupOneCallback)(null, first.address, first.family);+ return;+ }+ const opts = (optionsOrCb ?? {}) as { all?: boolean; family?: number };++ // Fail with ENOTFOUND when a specific family is requested but unavailable,+ // rather than silently returning a different family — some endpoints only+ // work on the requested one.+ if (opts.family) {+ const filtered = entries.filter((e) => e.family === opts.family);+ if (filtered.length === 0) {+ (maybeCb as TLookupOneCallback | TLookupAllCallback)(notFoundError(hostname), null as never, 0 as never);+ return;+ }+ if (opts.all) {+ (maybeCb as TLookupAllCallback)(null, filtered);+ } else {+ const first: LookupAddress = filtered[0];+ (maybeCb as TLookupOneCallback)(null, first.address, first.family);+ }+ return;+ }++ if (opts.all) {+ (maybeCb as TLookupAllCallback)(null, sortV4First(entries));+ } else {+ const first = pickPreferredEntry(entries);+ (maybeCb as TLookupOneCallback)(null, first.address, first.family);+ }+ }) as LookupFunction;++type TBuildAgentOptions = {+ addressFamily?: 4 | 6;+ ca?: string | string[];+ rejectUnauthorized?: boolean;+ servername?: string;+ keepAlive?: boolean;+ checkServerIdentity?: https.AgentOptions["checkServerIdentity"];+};++const hasAgentCustomization = (opts: TBuildAgentOptions): boolean =>+ Boolean(opts.addressFamily) ||+ opts.rejectUnauthorized !== undefined ||+ opts.ca !== undefined ||+ opts.servername !== undefined ||+ opts.keepAlive !== undefined ||+ opts.checkServerIdentity !== undefined;++// Pool of agents keyed by connection signature for connection reuse across+// repeated calls. The cache key includes the validated IP set so DNS record+// changes naturally produce a fresh entry. The hard cap is cleared wholesale+// when exceeded — misses just rebuild.+const AGENT_CACHE_MAX = 200;+const agentCache = new Map<string, http.Agent | https.Agent>();++const buildAgentCacheKey = (+ validated: TValidatedHost | undefined,+ protocol: string,+ opts: TBuildAgentOptions+): string => {+ const ipSet = validated+ ? validated.entries+ .map((e) => `${e.family}:${e.address}`)+ .sort()+ .join(",")+ : "";+ const caKey = Array.isArray(opts.ca) ? opts.ca.join("|") : (opts.ca ?? "");+ return [+ protocol,+ validated?.hostname ?? "",+ ipSet,+ opts.addressFamily ?? "",+ opts.keepAlive ?? "",+ opts.rejectUnauthorized ?? "",+ opts.servername ?? "",+ caKey+ ].join("|");+};++const constructAgent = (+ validated: TValidatedHost | undefined,+ protocol: string,+ opts: TBuildAgentOptions+): http.Agent | https.Agent => {+ const isHttps = protocol === "https:";+ const lookup = validated ? makePinnedLookup(validated.entries) : undefined;+ // Default keepAlive: true so cached agents reuse connections.+ const baseOpts: http.AgentOptions = {+ keepAlive: opts.keepAlive ?? true,+ keepAliveMsecs: 1000,+ maxSockets: 50,+ maxFreeSockets: 10,+ family: opts.addressFamily,+ lookup,+ // Happy Eyeballs: race v4 and v6 so a healthy family wins regardless of+ // resolver / lookup ordering. 250ms is Node's default.+ autoSelectFamily: true,+ autoSelectFamilyAttemptTimeout: 250+ };++ if (isHttps) {+ const httpsOpts: https.AgentOptions = {+ ...baseOpts,+ ...(opts.ca !== undefined && { ca: opts.ca }),+ ...(opts.rejectUnauthorized !== undefined && { rejectUnauthorized: opts.rejectUnauthorized }),+ ...(opts.servername !== undefined && { servername: opts.servername }),+ ...(opts.checkServerIdentity !== undefined && { checkServerIdentity: opts.checkServerIdentity })+ };+ return new https.Agent(httpsOpts);+ }+ return new http.Agent(baseOpts);+};++const buildPinnedAgent = (+ validated: TValidatedHost | undefined,+ protocol: string,+ opts: TBuildAgentOptions = {}+): http.Agent | https.Agent | undefined => {+ // Nothing to pin and no other customization — fall through to Axios's+ // default agent.+ if (!validated && !hasAgentCustomization(opts)) return undefined;++ // Function-valued options can't be fingerprinted; bypass the cache.+ if (opts.checkServerIdentity) {+ return constructAgent(validated, protocol, opts);+ }++ const cacheKey = buildAgentCacheKey(validated, protocol, opts);+ const cached = agentCache.get(cacheKey);+ if (cached) return cached;++ if (agentCache.size >= AGENT_CACHE_MAX) {+ agentCache.clear();+ }++ const agent = constructAgent(validated, protocol, opts);+ agentCache.set(cacheKey, agent);+ return agent;+};++type TBuildSsrfSafeAgentOptions = {+ allowPrivateIps?: boolean;+ addressFamily?: 4 | 6;+ ca?: string | string[];+ rejectUnauthorized?: boolean;+ servername?: string;+ keepAlive?: boolean;+ checkServerIdentity?: https.AgentOptions["checkServerIdentity"];+};++// Builds an SSRF-safe http(s).Agent for a URL, pinning DNS to the validated+// IPs and forwarding ca / rejectUnauthorized / servername to TLS. Use when+// handing an agent to a third-party client that doesn't go through Axios;+// safeRequest handles the Axios case directly.+export const buildSsrfSafeAgent = async (+ url: string,+ options: TBuildSsrfSafeAgentOptions = {}+): Promise<http.Agent | https.Agent | undefined> => {+ const { allowPrivateIps, addressFamily, ca, rejectUnauthorized, servername, keepAlive, checkServerIdentity } =+ options;+ const validated = await validateAndPinUrl(url, { allowPrivateIps });+ const { protocol } = new URL(url);+ return buildPinnedAgent(validated, protocol, {+ addressFamily,+ ca,+ rejectUnauthorized,+ servername,+ keepAlive,+ checkServerIdentity+ });+};++type TSafeRequestExtras = {+ allowPrivateIps?: boolean;+ addressFamily?: 4 | 6;+ ca?: string | string[];+ rejectUnauthorized?: boolean;+ servername?: string;+};++type TSafeRequestConfig = Omit<AxiosRequestConfig, "httpAgent" | "httpsAgent" | "maxRedirects" | "url" | "method">;++type TSafeRequestFullConfig = Omit<AxiosRequestConfig, "httpAgent" | "httpsAgent" | "maxRedirects"> & {+ url: string;+} & TSafeRequestExtras;++// Mirrors Axios's path-preserving slash join so the URL we validate matches+// the URL Axios actually requests. `new URL(url, base)` would replace the+// base path instead.+const combineURLs = (baseURL: string, relativeURL: string): string => {+ if (!relativeURL) return baseURL.replace(/\/+$/, "");+ return `${baseURL.replace(/\/+$/, "")}/${relativeURL.replace(/^\/+/, "")}`;+};++const isAbsoluteURL = (url: string): boolean => /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);++const resolveBaseUrl = (url: string, baseURL?: string): string => {+ if (!baseURL || isAbsoluteURL(url)) return url;+ return combineURLs(baseURL, url);+};++const dispatch = async <T>(+ method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE",+ url: string,+ data: unknown,+ options: TSafeRequestConfig & TSafeRequestExtras = {}+) => {+ const { allowPrivateIps, addressFamily, ca, rejectUnauthorized, servername, ...axiosOpts } = options;+ const effectiveUrl = resolveBaseUrl(url, axiosOpts.baseURL);+ const validated = await validateAndPinUrl(effectiveUrl, { allowPrivateIps });+ const { protocol } = new URL(effectiveUrl);+ const agent = buildPinnedAgent(validated, protocol, { addressFamily, ca, rejectUnauthorized, servername });++ return request.request<T>({+ ...axiosOpts,+ method,+ url,+ ...(data !== undefined && { data }),+ maxRedirects: 0,+ httpAgent: protocol === "http:" ? (agent as http.Agent | undefined) : undefined,+ httpsAgent: protocol === "https:" ? (agent as https.Agent | undefined) : undefined+ });+};++const dispatchFull = async <T>(config: TSafeRequestFullConfig) => {+ const { allowPrivateIps, addressFamily, ca, rejectUnauthorized, servername, url, ...axiosOpts } = config;+ const effectiveUrl = resolveBaseUrl(url, axiosOpts.baseURL);+ const validated = await validateAndPinUrl(effectiveUrl, { allowPrivateIps });+ const { protocol } = new URL(effectiveUrl);+ const agent = buildPinnedAgent(validated, protocol, { addressFamily, ca, rejectUnauthorized, servername });++ return request.request<T>({+ ...axiosOpts,+ url,+ maxRedirects: 0,+ httpAgent: protocol === "http:" ? (agent as http.Agent | undefined) : undefined,+ httpsAgent: protocol === "https:" ? (agent as https.Agent | undefined) : undefined+ });+};++// HTTP client that validates the URL, pins the connection to the validated+// IPs, and disables redirects. `T` defaults to `any` to mirror Axios's+// `request.get` / `request.post` defaults.+export const safeRequest = {+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ get: <T = any>(url: string, options?: TSafeRequestConfig & TSafeRequestExtras) =>+ dispatch<T>("GET", url, undefined, options),+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ post: <T = any>(url: string, data: unknown, options?: TSafeRequestConfig & TSafeRequestExtras) =>+ dispatch<T>("POST", url, data, options),+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ put: <T = any>(url: string, data: unknown, options?: TSafeRequestConfig & TSafeRequestExtras) =>+ dispatch<T>("PUT", url, data, options),+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ patch: <T = any>(url: string, data: unknown, options?: TSafeRequestConfig & TSafeRequestExtras) =>+ dispatch<T>("PATCH", url, data, options),+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ delete: <T = any>(url: string, options?: TSafeRequestConfig & TSafeRequestExtras) =>+ dispatch<T>("DELETE", url, undefined, options),+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ request: <T = any>(config: TSafeRequestFullConfig) => dispatchFull<T>(config)+};diff --git a/backend/src/services/webhook/webhook-fns.ts b/backend/src/services/webhook/webhook-fns.tsindex 57fd7d464d..35a01bca3d 100644--- a/backend/src/services/webhook/webhook-fns.ts+++ b/backend/src/services/webhook/webhook-fns.ts@@ -3,13 +3,12 @@ import picomatch from "picomatch";import { TWebhooks } from "@app/db/schemas";import { EventType, TAuditLogServiceFactory, WebhookTriggeredEvent } from "@app/ee/services/audit-log/audit-log-types";-import { request } from "@app/lib/config/request";import { crypto } from "@app/lib/crypto/cryptography";import { NotFoundError } from "@app/lib/errors";import { logger } from "@app/lib/logger";import { requestMemoKeys } from "@app/lib/request-context/memo-keys";import { requestMemoize } from "@app/lib/request-context/request-memoizer";-import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";+import { safeRequest } from "@app/lib/validator";import { ActorType } from "@app/services/auth/auth-type";import { TProjectDALFactory } from "../project/project-dal";@@ -43,7 +42,6 @@ export const triggerWebhookRequest = async (const headers: Record<string, string> = {};const payload = { ...data, timestamp: Date.now() };const { secretKey, url } = decryptWebhookDetails(webhook, decryptor);- await blockLocalAndPrivateIpAddresses(url);if (secretKey) {const webhookSign = crypto.nativeCrypto.createHmac("sha256", secretKey)@@ -52,11 +50,10 @@ export const triggerWebhookRequest = async (headers["x-infisical-signature"] = `t=${payload.timestamp};${webhookSign}`;}- const req = await request.post(url, payload, {+ const req = await safeRequest.post(url, payload, {headers,timeout: WEBHOOK_TRIGGER_TIMEOUT,- signal: AbortSignal.timeout(WEBHOOK_TRIGGER_TIMEOUT),- maxRedirects: 0+ signal: AbortSignal.timeout(WEBHOOK_TRIGGER_TIMEOUT)});return req;