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: enhance SSRF protection and standardize HTTP requests
Victor Hugo dos Santos46eb1bfea90b
diff --git a/CLAUDE.md b/CLAUDE.mdindex a630ffef25..d4e5d2c2fe 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -65,6 +65,10 @@ No IoC container. Every service is a factory function with explicit dependenciesReact Query + Axios with query key factories per domain. Each API domain in `frontend/src/hooks/api/` has `queries.tsx`, `mutations.tsx`, and `types.tsx` — see `frontend/CLAUDE.md` for conventions.+### Outbound HTTP & SSRF Protection++Backend HTTP requests to URLs derived from user input (webhooks, integrations, dynamic secrets, identity-auth JWKS, audit logs, ACME, etc.) go through the `safeRequest` helper (`@app/lib/validator`): URL validation, DNS pinning, no automatic redirects, internal-infrastructure blocklist. Third-party HTTP clients that build their own agent (`jwks-rsa`, `axios-ntlm`) use `buildSsrfSafeAgent`. See `backend/CLAUDE.md` for the full pattern, gateway-aware variants, and the criteria for adding a new `allowPrivateIps: true` caller.+## Keeping CLAUDE.md Up to DateWhen making significant changes to the codebase (new services, architectural shifts, new patterns, major refactors), update the relevant CLAUDE.md file(s) with high-level findings. This includes this root file for cross-cutting concerns, `backend/CLAUDE.md` for backend changes, and `frontend/CLAUDE.md` for frontend changes. The goal is to keep these files accurate as living documentation so future sessions start with correct context.diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex d3a1d8901e..80726957a9 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -223,23 +223,85 @@ import { safeRequest } from "@app/lib/validator";const res = await safeRequest.post<TResponse>(url, body, { headers, timeout });```-`safeRequest.{get,post}` (in `src/lib/validator/validate-url.ts`) does three things in one call:+`safeRequest` (in `src/lib/validator/validate-url.ts`) does three things atomically in one call:1. **Validates** the URL — rejects local/private IPs, Infisical's own DB/Redis hosts, URLs with embedded credentials.-2. **Pins** the connection — resolves the hostname once, then installs a custom `lookup` on a per-request `http(s).Agent` so the connect-time DNS call returns the validated IP. This closes the DNS-rebinding TOCTOU between the validation lookup and Axios's connect lookup.+2. **Pins** the connection — resolves the hostname once, then installs a custom `lookup` on a per-request `http(s).Agent` so the connect-time DNS call returns the validated IP. This closes the DNS-rebinding TOCTOU between the validation lookup and Axios's connect lookup. Pre-validating with `blockLocalAndPrivateIpAddresses` and *then* calling raw `request` does **not** close this window; only `safeRequest` does.3. **Disables redirects** (`maxRedirects: 0`). For redirect-following GETs that need to validate each hop, use `ssrfSafeGet` instead — it loops on top of the same pinned-agent dispatcher.+**Available methods** (all return Axios-shaped `AxiosResponse<T>`):+- `safeRequest.get<T>(url, opts?)`+- `safeRequest.post<T>(url, body, opts?)`+- `safeRequest.put<T>(url, body, opts?)`+- `safeRequest.patch<T>(url, body, opts?)`+- `safeRequest.delete<T>(url, opts?)`+- `safeRequest.request<T>(config)` — full Axios-style config; **`config.url` must be `string`** (not `string | undefined`). When wrapping in helper types, use `AxiosRequestConfig & { url: string }` to enforce at compile time.++Generic `T` defaults to `any` to mirror Axios so `safeRequest` is a near-drop-in replacement for raw `request`.+**When to use what:**-- `safeRequest.post` / `safeRequest.get` — most outbound HTTP. URL comes from user/admin config or stored data.-- `ssrfSafeGet` — when redirects must be followed (e.g. fetching JWKS or OIDC discovery docs that may 302).+- `safeRequest.{get,post,put,patch,delete,request}` — most outbound HTTP. URL comes from user/admin config or stored data.+- `ssrfSafeGet` — when redirects must be followed (e.g. fetching JWKS or OIDC discovery docs that may 302). Re-validates and re-pins each hop. **If you find yourself wanting to set `maxRedirects > 0` directly on a `safeRequest` config, the answer is `ssrfSafeGet`, not raising the cap.**- `ssrfSafePost` — POSTs that need to opt into `allowPrivateIps` (rare, used by AI MCP server).-- `blockLocalAndPrivateIpAddresses` directly — only for non-Axios clients (LDAP, SSH, SMB, ssh2, ldapjs, kubernetes client, etc.) where you can't install a `lookup` on the agent. The TOCTOU still exists in those paths; they're each a per-library follow-up.+- `buildSsrfSafeAgent` — when a third-party HTTP client (`jwks-rsa`'s `JwksClient`, `openid-client`, `axios-ntlm`, etc.) builds its own Axios/`got`/`http` client and won't accept a wrapped instance. See "Third-party HTTP clients that build their own agent" below.+- `blockLocalAndPrivateIpAddresses` directly — two cases:+ 1. **Save-time / config-time validation** — reject obviously bad URLs at the API edge before persisting. Defense-in-depth, not a substitute for `safeRequest` at request time.+ 2. **Truly non-HTTP clients** — LDAP, SSH, SMB, ssh2, ldapjs, raw TCP, etc. — where there is no `http.Agent` to install a `lookup` on. For HTTP clients that take an agent, use `buildSsrfSafeAgent` instead; falling back to `blockLocalAndPrivateIpAddresses` here loses DNS pinning.++**Agent customization (TLS extras)**++`safeRequest` builds its own pinned `http(s).Agent` per request. To preserve the pinning, do **not** pass a pre-built `httpsAgent` in the config — it would replace the pinned agent and disable rebinding protection. Instead pass these flat options and `safeRequest` bakes them into the pinned agent:++| Option | Purpose | Example |+|---|---|---|+| `ca` | Custom CA cert(s) for HTTPS — `string \| string[]` | NetScaler, Venafi TPP, self-hosted K8s API |+| `rejectUnauthorized` | Allow self-signed/invalid certs (use sparingly) | Internal services that ship their own CA |+| `servername` | TLS SNI when connecting by IP — cert verifies against the original hostname | Kubernetes API servers |+| `addressFamily` | Force IPv4 (`4`) or IPv6 (`6`) — filters the validated IP set | Azure App Configuration in our docker setup |+| `keepAlive` | Persistent TCP connection across the multi-step handshake. Only for protocols that genuinely need it — connection pooling otherwise widens the blast radius if a pinned IP misbehaves. | NTLM (Azure ADCS) |+| `checkServerIdentity` | Override the default hostname-vs-cert check. Set to `() => undefined` only when the cert is presented for an IP literal and the trust boundary is the explicit CA. | Azure ADCS web enrollment with IP-pinned certs |++Migration tip: when refactoring code that built a custom `https.Agent`, drop the agent and forward `ca` / `rejectUnauthorized` / `servername` as flat options; `safeRequest` will compose them into its pinned agent.++**Opt-outs that skip pinning** (in all three, `safeRequest` falls back to Axios's default agent and there is no rebinding protection):+- `NODE_ENV=development` — validation is bypassed entirely.+- Calling `blockLocalAndPrivateIpAddresses(url, isGateway = true)` — gateway-routed traffic doesn't go through Axios DNS, so pinning would do nothing.+- `allowPrivateIps: true` option — caller skips the private-IP refusal but **still** pins DNS to the validated IPs (rebinding protection is preserved).++**`allowPrivateIps: true` is only acceptable when there is a stronger runtime trust boundary than the IP class.** Existing legitimate callers:++**Gateway-aware patterns**++Some integrations route through an Infisical gateway (a TCP/HTTP tunnel to an in-customer-network agent). The gateway opens a localhost listener and the backend connects to `https://localhost:<ephemeralPort>`. Two patterns exist:++- **Single HTTP call per logical operation** (HC Vault, GitHub, Venafi TPP, NetScaler) — implemented as a per-app `requestWithXGateway` wrapper that branches once: gateway path uses raw `request` with the relay-supplied `httpsAgent` (preserves the relay TLS context); direct path uses `safeRequest` with the user's `ca` / `servername`. Pattern lives in each `*-connection-fns.ts`. Tighten the wrapper's `requestConfig` parameter type to `AxiosRequestConfig & { url: string }` so call sites must supply a URL — avoids `as string` casts.+- **Multi-step conversations under one callback** (only Kubernetes today) — a per-request HTTP-client factory (`k8sHttpClient` in `ee/services/dynamic-secret/providers/kubernetes.ts`) selects `request` vs `safeRequest` and translates `httpsAgent` → flat `ca` / `rejectUnauthorized` for the direct path. Used because a single callback closure runs many K8s API calls in either gateway-tunneled or direct mode.++**Third-party HTTP clients that build their own agent**++Some libraries (`jwks-rsa`'s `JwksClient`, `axios-ntlm`) instantiate their own HTTP client internally and don't accept a wrapped `axios` instance. They do typically expose a `requestAgent` / `agent` / `httpsAgent` injection point. For those, use `buildSsrfSafeAgent` from `@app/lib/validator` — it runs the same validation as `safeRequest` and returns an `http.Agent` / `https.Agent` with the validated IPs pinned via a custom `lookup`.++```ts+import { buildSsrfSafeAgent } from "@app/lib/validator";++const agent = await buildSsrfSafeAgent(jwksUri, {+ ca: caCert || undefined,+ rejectUnauthorized: true+});++const client = new JwksClient({ jwksUri, requestAgent: agent });+```++Existing call sites:+- Identity OIDC JWKS — `src/services/identity-oidc-auth/identity-oidc-auth-service.ts`+- Identity JWT JWKS — `src/services/identity-jwt-auth/identity-jwt-auth-service.ts`+- Azure ADCS NTLM — `src/services/app-connection/azure-adcs/azure-adcs-connection-fns.ts` (passes `keepAlive: true` and `checkServerIdentity: () => undefined`)++Anti-pattern: don't reach for `blockLocalAndPrivateIpAddresses(url)` followed by handing the library an unsafe agent — you'd lose DNS pinning and reintroduce the rebinding TOCTOU.-**Opt-outs that skip pinning:**-- `NODE_ENV=development` — validation is bypassed entirely (returns `undefined`).-- `isGateway = true` argument — gateway-routed traffic doesn't go through Axios DNS, so pinning would do nothing.-- `allowPrivateIps: true` option — caller explicitly opts into private-IP destinations.+**When you add a new outbound flow**-In all three opt-out cases, `safeRequest` falls back to Axios's default agent behavior. **Don't add `allowPrivateIps: true` without thinking** — it disables both the IP check and the rebinding pin.+1. Use `safeRequest` (or `buildSsrfSafeAgent` for third-party clients) by default.+2. Decide deliberately whether the flow needs `allowPrivateIps: true`. The default is no.### Enterprise (EE) Featuresdiff --git a/backend/src/ee/services/dynamic-secret/providers/kubernetes.ts b/backend/src/ee/services/dynamic-secret/providers/kubernetes.tsindex d9d5cd0a07..261ddf4b6b 100644--- a/backend/src/ee/services/dynamic-secret/providers/kubernetes.ts+++ b/backend/src/ee/services/dynamic-secret/providers/kubernetes.ts@@ -61,9 +61,14 @@ export const KubernetesProvider = ({* validates the user-supplied URL and pins the connection to the* validated IP set to defeat DNS rebinding TOCTOU between validation* and connect. `httpsAgent` from caller is dropped because safeRequest- * builds its own pinned agent; CA / rejectUnauthorized are forwarded- * through safeRequest options instead.+ * builds its own pinned agent; CA / rejectUnauthorized / servername+ * are forwarded through safeRequest options instead.*+ * Direct mode sets `allowPrivateIps: true` on purpose: in-cluster+ * Kubernetes API servers commonly resolve to RFC1918 / link-local IPs,+ * and the trust boundary is the configured cluster token plus TLS+ * verification (CA + `sslRejectUnauthorized`), not the IP class. This+ * matches the identity-auth Kubernetes flow.*/const k8sHttpClient = (providerInputs: z.infer<typeof DynamicSecretKubernetesSchema>, isGatewayProxied: boolean) => {type K8sRequestConfig = AxiosRequestConfig & { httpsAgent?: https.Agent };@@ -83,6 +88,7 @@ export const KubernetesProvider = ({delete (rest as { httpsAgent?: https.Agent }).httpsAgent;return {...rest,+ allowPrivateIps: true,// Only forward TLS overrides on direct API auth; Gateway auth method// does not need a custom CA because traffic flows through the proxy....(providerInputs.authMethod === KubernetesAuthMethod.Api && providerInputs.sslEnabled && providerInputs.cadiff --git a/backend/src/ee/services/dynamic-secret/providers/rabbit-mq.ts b/backend/src/ee/services/dynamic-secret/providers/rabbit-mq.tsindex d590578191..d2c06edbe1 100644--- a/backend/src/ee/services/dynamic-secret/providers/rabbit-mq.ts+++ b/backend/src/ee/services/dynamic-secret/providers/rabbit-mq.ts@@ -7,6 +7,7 @@ import { TDynamicSecrets } from "@app/db/schemas";import { BadRequestError } from "@app/lib/errors";import { sanitizeString } from "@app/lib/fn";import { logger } from "@app/lib/logger";+import { buildSsrfSafeAgent } from "@app/lib/validator";import { ActorIdentityAttributes } from "../../dynamic-secret-lease/dynamic-secret-lease-types";import { verifyHostInputValidity } from "../dynamic-secret-fns";@@ -83,8 +84,16 @@ export const RabbitMqProvider = (): TDynamicProviderFns => {};const $getClient = async (providerInputs: z.infer<typeof DynamicSecretRabbitMqSchema>) => {+ const baseURL = `${providerInputs.host}:${providerInputs.port}/api`;+ const isHttps = baseURL.startsWith("https:");+ const pinnedAgent = await buildSsrfSafeAgent(baseURL, {+ allowPrivateIps: true,+ ca: providerInputs.ca || undefined,+ rejectUnauthorized: isHttps ? providerInputs.sslRejectUnauthorized : undefined+ });+const axiosInstance = axios.create({- baseURL: `${providerInputs.host}:${providerInputs.port}/api`,+ baseURL,auth: {username: providerInputs.username,password: providerInputs.password@@ -93,9 +102,9 @@ export const RabbitMqProvider = (): TDynamicProviderFns => {"Content-Type": "application/json"},maxRedirects: 0,- ...(providerInputs.ca && {- httpsAgent: new https.Agent({ ca: providerInputs.ca, rejectUnauthorized: providerInputs.sslRejectUnauthorized })- })+ ...(isHttps+ ? { httpsAgent: pinnedAgent as https.Agent | undefined }+ : { httpAgent: pinnedAgent as import("http").Agent | undefined })});return axiosInstance;diff --git a/backend/src/ee/services/oidc/oidc-config-service.ts b/backend/src/ee/services/oidc/oidc-config-service.tsindex 8043d35149..906c459bb0 100644--- a/backend/src/ee/services/oidc/oidc-config-service.ts+++ b/backend/src/ee/services/oidc/oidc-config-service.ts@@ -23,6 +23,7 @@ import { OrgServiceActor } from "@app/lib/types";import {blockLocalAndPrivateIpAddresses,matchesAllowedEmailDomain,+ safeRequest,sanitizeEmail,validateEmail} from "@app/lib/validator";@@ -687,8 +688,20 @@ export const oidcConfigServiceFactory = ({message: "OIDC not configured correctly"});}- await blockLocalAndPrivateIpAddresses(oidcCfg.discoveryURL);- issuer = await Issuer.discover(oidcCfg.discoveryURL);+ // Fetch discovery doc via safeRequest so the discovery leg is itself+ // SSRF-validated and DNS-pinned. We then construct the Issuer manually+ // instead of letting openid-client do its own (unpinned) HTTP via+ // `Issuer.discover()`.+ const discoveryUrl = `${oidcCfg.discoveryURL.replace(/\/+$/, "")}/.well-known/openid-configuration`;+ const { data: meta } = await safeRequest.get<{+ issuer: string;+ authorization_endpoint?: string;+ token_endpoint?: string;+ userinfo_endpoint?: string;+ jwks_uri?: string;+ code_challenge_methods_supported?: string[];+ }>(discoveryUrl);+ issuer = new OpenIdIssuer(meta);} else {if (!oidcCfg.issuer ||@@ -701,9 +714,6 @@ export const oidcConfigServiceFactory = ({message: "OIDC not configured correctly"});}- await blockLocalAndPrivateIpAddresses(oidcCfg.jwksUri);- await blockLocalAndPrivateIpAddresses(oidcCfg.tokenEndpoint);- await blockLocalAndPrivateIpAddresses(oidcCfg.userinfoEndpoint);issuer = new OpenIdIssuer({issuer: oidcCfg.issuer,authorization_endpoint: oidcCfg.authorizationEndpoint,diff --git a/backend/src/ee/services/secret-rotation-v2/supabase-api-key/supabase-api-key-rotation-fns.ts b/backend/src/ee/services/secret-rotation-v2/supabase-api-key/supabase-api-key-rotation-fns.tsindex be4b2ff2a4..4335b0d229 100644--- a/backend/src/ee/services/secret-rotation-v2/supabase-api-key/supabase-api-key-rotation-fns.ts+++ b/backend/src/ee/services/secret-rotation-v2/supabase-api-key/supabase-api-key-rotation-fns.ts@@ -52,7 +52,7 @@ export const supabaseApiKeyRotationFactory: TRotationFactory<};const $createApiKey = async () => {- const baseUrl = await getSupabaseInstanceUrl(connectionConfig);+ const baseUrl = getSupabaseInstanceUrl(connectionConfig);const headers = getSupabaseAuthHeaders(connectionConfig);try {@@ -88,7 +88,7 @@ export const supabaseApiKeyRotationFactory: TRotationFactory<};const $deleteApiKey = async (keyId: string) => {- const baseUrl = await getSupabaseInstanceUrl(connectionConfig);+ const baseUrl = getSupabaseInstanceUrl(connectionConfig);const headers = getSupabaseAuthHeaders(connectionConfig);try {diff --git a/backend/src/lib/validator/index.ts b/backend/src/lib/validator/index.tsindex 7f75f843f5..b0e2e60b1d 100644--- a/backend/src/lib/validator/index.ts+++ b/backend/src/lib/validator/index.ts@@ -12,6 +12,7 @@ export {} from "./validate-smb";export {blockLocalAndPrivateIpAddresses,+ buildSsrfSafeAgent,safeRequest,ssrfSafeGet,ssrfSafePost,diff --git a/backend/src/lib/validator/validate-url.test.ts b/backend/src/lib/validator/validate-url.test.tsindex 3ed5cb4462..f9fab6f3a0 100644--- a/backend/src/lib/validator/validate-url.test.ts+++ b/backend/src/lib/validator/validate-url.test.ts@@ -1,15 +1,454 @@-import { isFQDN } from "./validate-url";+/* 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 {+ blockLocalAndPrivateIpAddresses,+ buildSsrfSafeAgent,+ isFQDN,+ safeRequest,+ ssrfSafeGet,+ validateSsrfUrl+} from "./validate-url";++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("validate-url 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("validateSsrfUrl", () => {+ it("returns undefined when allowPrivateIps is true (no validation, no pinning)", async () => {+ const result = await validateSsrfUrl("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 validateSsrfUrl("https://example.com");+ expect(result).toBeUndefined();+ });++ it("rejects URLs with embedded user credentials", async () => {+ await expect(validateSsrfUrl("https://user:[email protected]")).rejects.toThrow(/user credentials/i);+ });++ it("rejects literal `localhost` hostnames", async () => {+ await expect(validateSsrfUrl("http://localhost:8080")).rejects.toThrow(/Local IPs not allowed/i);+ });++ it("rejects literal `host.docker.internal` hostnames", async () => {+ await expect(validateSsrfUrl("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(validateSsrfUrl("https://example.com")).rejects.toThrow(/Local IPs not allowed/i);+ });++ it("rejects loopback IPv4 even when configured as a literal IP", async () => {+ await expect(validateSsrfUrl(`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 validateSsrfUrl("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(validateSsrfUrl("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 validateSsrfUrl("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(validateSsrfUrl("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 + no agent customization)", 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");+ expect(opts.keepAlive).toBe(false);+ });++ 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.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));+ });+ });++ describe("ssrfSafeGet redirects", () => {+ it("follows up to MAX_SAFE_REDIRECTS hops, validating each hop", async () => {+ requestRequestMock+ .mockResolvedValueOnce({ data: undefined, status: 302, headers: { location: "https://hop1.example/" } })+ .mockResolvedValueOnce({ data: undefined, status: 302, headers: { location: "https://hop2.example/" } })+ .mockResolvedValueOnce({ data: { final: true }, status: 200, headers: {} });+ setLookup([{ address: PUBLIC_IP_V4, family: 4 }]);++ const res = await ssrfSafeGet<{ final: boolean }>("https://start.example");+ expect(res.data).toEqual({ final: true });+ expect(requestRequestMock.mock.calls.length).toBe(3);+ expect(lookupMock.mock.calls.map((c) => c[0])).toEqual(["start.example", "hop1.example", "hop2.example"]);+ });++ it("rejects redirects to private IPs", async () => {+ requestRequestMock+ .mockResolvedValueOnce({ data: undefined, status: 302, headers: { location: "https://internal.example/" } })+ .mockResolvedValueOnce({ data: undefined, status: 200, headers: {} });+ lookupMock.mockReset();+ lookupMock+ .mockResolvedValueOnce([{ address: PUBLIC_IP_V4, family: 4 }])+ .mockResolvedValueOnce([{ address: PRIVATE_IP_V4, family: 4 }]);++ await expect(ssrfSafeGet("https://start.example")).rejects.toThrow(/Local IPs not allowed/i);+ });++ it("resolves relative `Location` headers against the previous hop", async () => {+ requestRequestMock+ .mockResolvedValueOnce({ data: undefined, status: 301, headers: { location: "/relative" } })+ .mockResolvedValueOnce({ data: { ok: true }, status: 200, headers: {} });+ const res = await ssrfSafeGet<{ ok: boolean }>("https://start.example/initial");+ expect(res.data).toEqual({ ok: true });+ // Second call should hit the resolved absolute URL.+ const secondCallUrl = (requestRequestMock.mock.calls[1]?.[0] as { url: string }).url;+ expect(secondCallUrl).toBe("https://start.example/relative");+ });++ it("throws when a redirect response is missing the Location header", async () => {+ requestRequestMock.mockResolvedValueOnce({ data: undefined, status: 302, headers: {} });+ await expect(ssrfSafeGet("https://start.example")).rejects.toThrow(/missing Location header/i);+ });++ it("throws after exceeding MAX_SAFE_REDIRECTS", async () => {+ const redirectResp = { data: undefined, status: 302, headers: { location: "https://next.example/" } };+ // Exceed 5 redirects.+ requestRequestMock.mockResolvedValue(redirectResp);+ await expect(ssrfSafeGet("https://start.example")).rejects.toThrow(/Too many redirects/i);+ });+ });++ describe("blockLocalAndPrivateIpAddresses (legacy helper)", () => {+ it("is a no-op in dev mode", async () => {+ configState.isDevelopmentMode = true;+ const result = await blockLocalAndPrivateIpAddresses("https://attacker.localhost");+ expect(result).toBeUndefined();+ expect(lookupMock).not.toHaveBeenCalled();+ });++ it("is a no-op when invoked via gateway (callers explicitly opt out)", async () => {+ const result = await blockLocalAndPrivateIpAddresses("https://attacker.localhost", true);+ expect(result).toBeUndefined();+ });++ it("returns the resolved entries on success", async () => {+ setLookup([{ address: PUBLIC_IP_V4, family: 4 }]);+ const result = await blockLocalAndPrivateIpAddresses("https://example.com");+ expect(result).toEqual({ hostname: "example.com", entries: [{ address: PUBLIC_IP_V4, family: 4 }] });+ });+ });+});describe("isFQDN", () => {- test("Non wildcard", () => {+ it("Non wildcard", () => {expect(isFQDN("www.example.com")).toBeTruthy();});- test("Wildcard", () => {+ it("Wildcard", () => {expect(isFQDN("*.example.com", { allow_wildcard: true })).toBeTruthy();});- test("Wildcard FQDN fails on option allow_wildcard false", () => {+ it("Wildcard FQDN fails on option allow_wildcard false", () => {expect(isFQDN("*.example.com")).toBeFalsy();});});diff --git a/backend/src/lib/validator/validate-url.ts b/backend/src/lib/validator/validate-url.tsindex ed4b3180bf..d3a9006717 100644--- a/backend/src/lib/validator/validate-url.ts+++ b/backend/src/lib/validator/validate-url.ts@@ -174,8 +174,17 @@ type SsrfSafeRequestOptions = {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;+};+const makePinnedLookup = (entries: LookupAddress[]): LookupFunction =>- ((_hostname: string, optionsOrCb: unknown, maybeCb?: unknown) => {+ ((hostname: string, optionsOrCb: unknown, maybeCb?: unknown) => {// Node may invoke `lookup(hostname, callback)` (2-arg) or `lookup(hostname, options, callback)` (3-arg).if (typeof optionsOrCb === "function") {const first: LookupAddress = entries[0];@@ -184,12 +193,30 @@ const makePinnedLookup = (entries: LookupAddress[]): LookupFunction =>}const opts = (optionsOrCb ?? {}) as { all?: boolean; family?: number };- const filtered = opts.family ? entries.filter((e) => e.family === opts.family) : entries;- const usable = filtered.length > 0 ? filtered : entries;+ // If the caller asked for a specific address family but none of the+ // pre-validated entries match, fail with ENOTFOUND rather than silently+ // returning a different family. Honoring the contract is important for+ // integrations (e.g. Azure App Configuration) whose TLS / connectivity+ // path is broken on the unwanted family.+ 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, usable);+ (maybeCb as TLookupAllCallback)(null, entries);} else {- const first: LookupAddress = usable[0];+ const first: LookupAddress = entries[0];(maybeCb as TLookupOneCallback)(null, first.address, first.family);}}) as LookupFunction;@@ -214,13 +241,28 @@ type TBuildAgentOptions = {* (e.g. Kubernetes API servers).*/servername?: string;+ /**+ * Keep sockets alive between requests. Default `false` — short-lived,+ * single-request agents are the safer default. Set `true` only for+ * protocols that require socket reuse across a multi-step exchange+ * (e.g. NTLM authentication via axios-ntlm).+ */+ keepAlive?: boolean;+ /**+ * Override TLS hostname verification. Use to skip the default identity+ * check on legacy enterprise CAs whose certificates are issued for IP+ * addresses or non-DNS subjects (e.g. AD CS web enrollment).+ */+ checkServerIdentity?: https.AgentOptions["checkServerIdentity"];};const hasAgentCustomization = (opts: TBuildAgentOptions): boolean =>Boolean(opts.addressFamily) ||opts.rejectUnauthorized !== undefined ||opts.ca !== undefined ||- opts.servername !== undefined;+ opts.servername !== undefined ||+ opts.keepAlive !== undefined ||+ opts.checkServerIdentity !== undefined;const buildPinnedAgent = (validated: TValidatedHost | undefined,@@ -234,7 +276,7 @@ const buildPinnedAgent = (const isHttps = protocol === "https:";const lookup = validated ? makePinnedLookup(validated.entries) : undefined;const baseOpts: http.AgentOptions = {- keepAlive: false,+ keepAlive: opts.keepAlive ?? false,family: opts.addressFamily,lookup};@@ -244,7 +286,8 @@ const buildPinnedAgent = (...baseOpts,...(opts.ca !== undefined && { ca: opts.ca }),...(opts.rejectUnauthorized !== undefined && { rejectUnauthorized: opts.rejectUnauthorized }),- ...(opts.servername !== undefined && { servername: opts.servername })+ ...(opts.servername !== undefined && { servername: opts.servername }),+ ...(opts.checkServerIdentity !== undefined && { checkServerIdentity: opts.checkServerIdentity })};return new https.Agent(httpsOpts);}@@ -279,6 +322,48 @@ export const validateSsrfUrl = async (return validated;};+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.Agent` / `https.Agent` for a given URL. The+ * returned agent:+ * - Pins DNS to the IPs validated at this call (defeats DNS rebinding).+ * - Forwards `ca` / `rejectUnauthorized` / `servername` for TLS verification.+ *+ * Use this when you need to hand a pinned agent off to a third-party HTTP+ * client (e.g. `jwks-rsa`'s `requestAgent`, `acme-client`, etc.) that doesn't+ * route through Axios — `safeRequest` handles the Axios case directly.+ *+ * Returns `undefined` when there is nothing to customize (dev mode + no TLS+ * options + private IP allowed) so the caller can fall through to the default+ * agent.+ */+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 validateSsrfUrl(url, { allowPrivateIps });+ const { protocol } = new URL(url);+ return buildPinnedAgent(validated, protocol, {+ addressFamily,+ ca,+ rejectUnauthorized,+ servername,+ keepAlive,+ checkServerIdentity+ });+};+type TSafeRequestExtras = {allowPrivateIps?: boolean;/**@@ -312,13 +397,23 @@ type TSafeRequestFullConfig = Omit<AxiosRequestConfig, "httpAgent" | "httpsAgenturl: string;} & TSafeRequestExtras;+/**+ * Combines a request URL with an Axios `baseURL` exactly the way Axios does.+ * Axios's `combineURLs` is a simple `${baseURL}/${url}` join with slash+ * de-duplication and is path-preserving — `new URL("/v1/foo", baseURL)` would+ * instead REPLACE the base path. Matching Axios's semantics keeps the URL we+ * SSRF-validate byte-for-byte equal to the URL Axios actually requests.+ */+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) return url;- try {- return new URL(url).toString();- } catch {- return new URL(url, baseURL).toString();- }+ if (!baseURL || isAbsoluteURL(url)) return url;+ return combineURLs(baseURL, url);};const dispatch = async <T>(diff --git a/backend/src/services/app-connection/azure-adcs/azure-adcs-connection-fns.ts b/backend/src/services/app-connection/azure-adcs/azure-adcs-connection-fns.tsindex 3aaf9fb6e9..09b6961890 100644--- a/backend/src/services/app-connection/azure-adcs/azure-adcs-connection-fns.ts+++ b/backend/src/services/app-connection/azure-adcs/azure-adcs-connection-fns.ts@@ -4,7 +4,7 @@ import https from "https";import RE2 from "re2";import { BadRequestError, NotFoundError } from "@app/lib/errors";-import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator/validate-url";+import { blockLocalAndPrivateIpAddresses, buildSsrfSafeAgent } from "@app/lib/validator/validate-url";import { decryptAppConnectionCredentials } from "@app/services/app-connection/app-connection-fns";import { TKmsServiceFactory } from "@app/services/kms/kms-service";@@ -104,18 +104,25 @@ const normalizeAdcsUrl = (url: string): string => {return normalizedUrl;};-// NTLM request wrapper-const createHttpsAgent = (sslRejectUnauthorized: boolean, sslCertificate?: string): https.Agent => {- const agentOptions: https.AgentOptions = {+// NTLM request wrapper. We use `buildSsrfSafeAgent` to validate the target URL+// AND pin DNS for the lifetime of the agent, while keeping the ADCS-specific+// agent options (keepAlive for NTLM's multi-step handshake, custom CA, and a+// no-op `checkServerIdentity` because Microsoft web-enrollment frequently+// presents certs whose subject does not match the connection hostname).+const createHttpsAgent = async (+ url: string,+ sslRejectUnauthorized: boolean,+ sslCertificate?: string+): Promise<https.Agent> => {+ const agent = await buildSsrfSafeAgent(url, {rejectUnauthorized: sslRejectUnauthorized,- keepAlive: true, // axios-ntlm needs keepAlive for NTLM handshake- ca: sslCertificate ? [sslCertificate.trim()] : undefined,- // Disable hostname verification as Microsoft servers by default use local IPs for certificates- // which may not match the hostname used to connect+ keepAlive: true,+ ca: sslCertificate ? sslCertificate.trim() : undefined,checkServerIdentity: () => undefined- };-- return new https.Agent(agentOptions);+ });+ // For HTTPS URLs (the only case ADCS supports — see normalizeAdcsUrl),+ // buildSsrfSafeAgent always returns an https.Agent.+ return agent as https.Agent;};const axiosNtlmRequest = async (config: AxiosNtlmConfig): Promise<AxiosNtlmResponse> => {@@ -179,8 +186,10 @@ const testAdcsConnection = async (const shouldRejectUnauthorized = sslRejectUnauthorized;- const httpsAgent = createHttpsAgent(shouldRejectUnauthorized, sslCertificate);+ // eslint-disable-next-line no-await-in-loop+ const httpsAgent = await createHttpsAgent(testUrl, shouldRejectUnauthorized, sslCertificate);+ // eslint-disable-next-line no-await-in-loopconst response = await axiosNtlmRequest({url: testUrl,method: "GET",@@ -292,11 +301,12 @@ const createNtlmClient = (return {get: async (endpoint: string, additionalHeaders: Record<string, string> = {}) => {const shouldRejectUnauthorized = sslRejectUnauthorized;+ const url = `${normalizedUrl}${endpoint}`;- const httpsAgent = createHttpsAgent(shouldRejectUnauthorized, sslCertificate);+ const httpsAgent = await createHttpsAgent(url, shouldRejectUnauthorized, sslCertificate);return axiosNtlmRequest({- url: `${normalizedUrl}${endpoint}`,+ url,method: "GET",httpsAgent,headers: additionalHeaders,@@ -309,11 +319,12 @@ const createNtlmClient = (},post: async (endpoint: string, body: string, additionalHeaders: Record<string, string> = {}) => {const shouldRejectUnauthorized = sslRejectUnauthorized;+ const url = `${normalizedUrl}${endpoint}`;- const httpsAgent = createHttpsAgent(shouldRejectUnauthorized, sslCertificate);+ const httpsAgent = await createHttpsAgent(url, shouldRejectUnauthorized, sslCertificate);return axiosNtlmRequest({- url: `${normalizedUrl}${endpoint}`,+ url,method: "POST",httpsAgent,data: body,diff --git a/backend/src/services/app-connection/bitbucket/bitbucket-connection-fns.ts b/backend/src/services/app-connection/bitbucket/bitbucket-connection-fns.tsindex a3169a0b3f..7c3d6d2b8f 100644--- a/backend/src/services/app-connection/bitbucket/bitbucket-connection-fns.ts+++ b/backend/src/services/app-connection/bitbucket/bitbucket-connection-fns.ts@@ -2,6 +2,7 @@ import { AxiosError } from "axios";import { request } from "@app/lib/config/request";import { BadRequestError } from "@app/lib/errors";+import { safeRequest } from "@app/lib/validator";import { AppConnection } from "@app/services/app-connection/app-connection-enums";import { IntegrationUrls } from "@app/services/integration-auth/integration-list";@@ -77,9 +78,10 @@ export const listBitbucketWorkspaces = async (appConnection: TBitbucketConnectio// Limit to 10 iterations, fetching at most 10 * 100 = 1000 workspaceswhile (nextUrl && iterationCount < 10) {// eslint-disable-next-line no-await-in-loop- const { data }: { data: BitbucketWorkspacesResponse } = await request.get<BitbucketWorkspacesResponse>(nextUrl, {- headers- });+ const { data }: { data: BitbucketWorkspacesResponse } = await safeRequest.get<BitbucketWorkspacesResponse>(+ nextUrl,+ { headers }+ );allWorkspaces = allWorkspaces.concat(data.values.map((membership) => ({ slug: membership.workspace.slug })));nextUrl = data.next;@@ -104,7 +106,7 @@ const paginateBitbucketRequest = async <T>(url: string, headers: Record<string,while (nextUrl && iterationCount < BITBUCKET_MAX_PAGES) {// eslint-disable-next-line no-await-in-loop- const { data }: { data: BitbucketPaginatedResponse<T> } = await request.get(nextUrl, { headers });+ const { data }: { data: BitbucketPaginatedResponse<T> } = await safeRequest.get(nextUrl, { headers });allItems = allItems.concat(data.values);nextUrl = data.next;@@ -163,9 +165,10 @@ export const listBitbucketEnvironments = async (// Limit to 10 iterations, fetching at most 10 * 100 = 1000 environmentswhile (hasNextPage && iterationCount < 10) {// eslint-disable-next-line no-await-in-loop- const { data }: { data: { values: TBitbucketEnvironment[]; next: string } } = await request.get(environmentsUrl, {- headers- });+ const { data }: { data: { values: TBitbucketEnvironment[]; next: string } } = await safeRequest.get(+ environmentsUrl,+ { headers }+ );if (data?.values.length > 0) {environments.push(...data.values);diff --git a/backend/src/services/app-connection/supabase/supabase-connection-public-client.ts b/backend/src/services/app-connection/supabase/supabase-connection-public-client.tsindex 3aae50b967..a54534f9d0 100644--- a/backend/src/services/app-connection/supabase/supabase-connection-public-client.ts+++ b/backend/src/services/app-connection/supabase/supabase-connection-public-client.ts@@ -1,23 +1,18 @@/* eslint-disable no-await-in-loop *//* eslint-disable class-methods-use-this */-import { AxiosInstance, AxiosRequestConfig, AxiosResponse, HttpStatusCode } from "axios";+import { AxiosRequestConfig, AxiosResponse, HttpStatusCode } from "axios";-import { createRequestClient } from "@app/lib/config/request";import { delay } from "@app/lib/delay";import { removeTrailingSlash } from "@app/lib/fn";-import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";+import { safeRequest } from "@app/lib/validator";import { SupabaseConnectionMethod } from "./supabase-connection-constants";import { TSupabaseConnectionConfig, TSupabaseProject, TSupabaseSecret } from "./supabase-connection-types";-export const getSupabaseInstanceUrl = async (config: TSupabaseConnectionConfig) => {- const instanceUrl = config.credentials.instanceUrl+export const getSupabaseInstanceUrl = (config: TSupabaseConnectionConfig): string => {+ return config.credentials.instanceUrl? removeTrailingSlash(config.credentials.instanceUrl): "https://api.supabase.com";-- await blockLocalAndPrivateIpAddresses(instanceUrl);-- return instanceUrl;};export function getSupabaseAuthHeaders(connection: TSupabaseConnectionConfig): Record<string, string> {@@ -48,26 +43,25 @@ export function getSupabaseRatelimiter(response: AxiosResponse): {}class SupabasePublicClient {- private client: AxiosInstance;-- constructor() {- this.client = createRequestClient({- headers: {- "Content-Type": "application/json"- }- });- }-+ // Route every Supabase API call through `safeRequest.request` so the+ // (potentially self-hosted) instance URL is SSRF-validated and DNS-pinned+ // per call. The headers/content-type are set per-request rather than+ // baked into a long-lived client.async send<T>(connection: TSupabaseConnectionConfig,config: AxiosRequestConfig,retryAttempt = 0): Promise<T | undefined> {- const response = await this.client.request<T>({+ const response = await safeRequest.request<T>({...config,- baseURL: await getSupabaseInstanceUrl(connection),+ baseURL: getSupabaseInstanceUrl(connection),+ url: config.url ?? "",validateStatus: (status) => (status >= 200 && status < 300) || status === HttpStatusCode.TooManyRequests,- headers: getSupabaseAuthHeaders(connection)+ headers: {+ "Content-Type": "application/json",+ ...config.headers,+ ...getSupabaseAuthHeaders(connection)+ }});const limiter = getSupabaseRatelimiter(response);diff --git a/backend/src/services/external-migration/external-migration-fns/vault.ts b/backend/src/services/external-migration/external-migration-fns/vault.tsindex 6e32be9075..89eec5c5ff 100644--- a/backend/src/services/external-migration/external-migration-fns/vault.ts+++ b/backend/src/services/external-migration/external-migration-fns/vault.ts@@ -9,7 +9,7 @@ import { BadRequestError } from "@app/lib/errors";import { GatewayProxyProtocol, withGatewayProxy } from "@app/lib/gateway";import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";import { logger } from "@app/lib/logger";-import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";+import { blockLocalAndPrivateIpAddresses, buildSsrfSafeAgent } from "@app/lib/validator";import { InfisicalImportData, KvVersion, VaultMappingType } from "../external-migration-types";@@ -309,8 +309,9 @@ const vaultFactory = (getData);} else {- await blockLocalAndPrivateIpAddresses(baseUrl);- data = await getData(baseUrl);+ const pinnedAgent = await buildSsrfSafeAgent(baseUrl, { rejectUnauthorized: true });+ const isHttps = new URL(baseUrl).protocol === "https:";+ data = await getData(baseUrl, undefined, isHttps ? (pinnedAgent as https.Agent | undefined) : undefined);}return data;diff --git a/backend/src/services/identity-jwt-auth/identity-jwt-auth-service.ts b/backend/src/services/identity-jwt-auth/identity-jwt-auth-service.tsindex 40f2879c3b..a85232342e 100644--- a/backend/src/services/identity-jwt-auth/identity-jwt-auth-service.ts+++ b/backend/src/services/identity-jwt-auth/identity-jwt-auth-service.ts@@ -1,6 +1,5 @@import { ForbiddenError, subject } from "@casl/ability";import { requestContext } from "@fastify/request-context";-import https from "https";import jwt from "jsonwebtoken";import { JwksClient } from "jwks-rsa";@@ -34,7 +33,7 @@ import { RequestContextKey } from "@app/lib/request-context/request-context-keysimport { requestMemoize } from "@app/lib/request-context/request-memoizer";import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics";import { getValueByDot } from "@app/lib/template/dot-access";-import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";+import { blockLocalAndPrivateIpAddresses, buildSsrfSafeAgent } from "@app/lib/validator";import { ActorType, AuthTokenType } from "../auth/auth-type";import { TIdentityDALFactory } from "../identity/identity-dal";@@ -124,27 +123,27 @@ export const identityJwtAuthServiceFactory = ({let tokenData: Record<string, string | boolean | number> = {};if (identityJwtAuth.configurationType === JwtConfigurationType.JWKS) {- await blockLocalAndPrivateIpAddresses(identityJwtAuth.jwksUrl);-- let client: JwksClient;+ // Validate the jwksUrl AND build a pinned agent in one step. JwksClient+ // performs its own HTTP under the hood, so we hand it our pinned agent+ // to defeat DNS rebinding on the JWKS fetch (TOCTOU window between a+ // pre-validation and the actual connection).+ let decryptedJwksCaCert: string | undefined;if (identityJwtAuth.jwksUrl.includes("https:")) {- const decryptedJwksCaCert = orgDataKeyDecryptor({+ decryptedJwksCaCert = orgDataKeyDecryptor({cipherTextBlob: identityJwtAuth.encryptedJwksCaCert}).toString();-- const requestAgent = decryptedJwksCaCert- ? new https.Agent({ ca: decryptedJwksCaCert, rejectUnauthorized: true })- : undefined;- client = new JwksClient({- jwksUri: identityJwtAuth.jwksUrl,- requestAgent- });- } else {- client = new JwksClient({- jwksUri: identityJwtAuth.jwksUrl- });}+ const jwksRequestAgent = await buildSsrfSafeAgent(identityJwtAuth.jwksUrl, {+ ca: decryptedJwksCaCert || undefined,+ rejectUnauthorized: true+ });++ const client = new JwksClient({+ jwksUri: identityJwtAuth.jwksUrl,+ requestAgent: jwksRequestAgent+ });+const { kid } = decodedToken.header as { kid: string };const jwtSigningKey = await client.getSigningKey(kid);diff --git a/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.tsindex a4b755ac23..a99b2fef05 100644--- a/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts+++ b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts@@ -346,7 +346,6 @@ export const identityKubernetesAuthServiceFactory = ({const baseUrl = port ? `${host}:${port}` : host;- const isGatewayProxied = port !== undefined;const res = await safeRequest.post<TCreateTokenReviewResponse>(`${baseUrl}/apis/authentication.k8s.io/v1/tokenreviews`,@@ -367,7 +366,7 @@ export const identityKubernetesAuthServiceFactory = ({},signal: AbortSignal.timeout(10000),timeout: 10000,- allowPrivateIps: isGatewayProxied,+ allowPrivateIps: true,ca: caCert || undefined,rejectUnauthorized: $resolveEffectiveVerifyTlsCertificate(caCert,diff --git a/backend/src/services/identity-oidc-auth/identity-oidc-auth-service.ts b/backend/src/services/identity-oidc-auth/identity-oidc-auth-service.tsindex 78e19bed36..84d6904b8e 100644--- a/backend/src/services/identity-oidc-auth/identity-oidc-auth-service.ts+++ b/backend/src/services/identity-oidc-auth/identity-oidc-auth-service.ts@@ -1,6 +1,5 @@import { ForbiddenError, subject } from "@casl/ability";import { requestContext } from "@fastify/request-context";-import https from "https";import jwt from "jsonwebtoken";import { JwksClient } from "jwks-rsa";@@ -35,7 +34,7 @@ import { RequestContextKey } from "@app/lib/request-context/request-context-keysimport { requestMemoize } from "@app/lib/request-context/request-memoizer";import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics";import { getValueByDot } from "@app/lib/template/dot-access";-import { blockLocalAndPrivateIpAddresses, safeRequest } from "@app/lib/validator";+import { blockLocalAndPrivateIpAddresses, buildSsrfSafeAgent, safeRequest } from "@app/lib/validator";import { ActorType, AuthTokenType } from "../auth/auth-type";import { TIdentityDALFactory } from "../identity/identity-dal";@@ -113,8 +112,6 @@ export const identityOidcAuthServiceFactory = ({caCert = decryptor({ cipherTextBlob: identityOidcAuth.encryptedCaCertificate }).toString();}- const requestAgent = caCert ? new https.Agent({ ca: caCert, rejectUnauthorized: true }) : undefined;-let discoveryDoc: { jwks_uri: string };try {const response = await safeRequest.get<{ jwks_uri: string }>(@@ -147,8 +144,6 @@ export const identityOidcAuthServiceFactory = ({});}- await blockLocalAndPrivateIpAddresses(jwksUri);-const decodedToken = crypto.jwt().decode(oidcJwt, { complete: true });if (!decodedToken) {throw new UnauthorizedError({@@ -162,9 +157,18 @@ export const identityOidcAuthServiceFactory = ({});}+ // Validate the jwks_uri AND build a pinned agent in one step. JwksClient+ // performs its own HTTP under the hood, so we hand it our pinned agent+ // to defeat DNS rebinding on the JWKS fetch (TOCTOU window between a+ // pre-validation and the actual connection).+ const jwksRequestAgent = await buildSsrfSafeAgent(jwksUri, {+ ca: caCert || undefined,+ rejectUnauthorized: true+ });+const client = new JwksClient({jwksUri,- requestAgent: identityOidcAuth.oidcDiscoveryUrl.includes("https") ? requestAgent : undefined+ requestAgent: jwksRequestAgent});const { kid } = decodedToken.header as { kid?: string };diff --git a/backend/src/services/integration-auth/integration-app-list.ts b/backend/src/services/integration-auth/integration-app-list.tsindex 11b7d12907..4977d0db81 100644--- a/backend/src/services/integration-auth/integration-app-list.ts+++ b/backend/src/services/integration-auth/integration-app-list.ts@@ -548,7 +548,7 @@ const getAppsCircleCI = async ({ accessToken }: { accessToken: string }) => {const getAppsDatabricks = async ({ url, accessToken }: { url?: string | null; accessToken: string }) => {const databricksApiUrl = `${url}/api`;- const res = await request.get<{ scopes: { name: string; backend_type: string }[] }>(+ const res = await safeRequest.get<{ scopes: { name: string; backend_type: string }[] }>(`${databricksApiUrl}/2.0/secrets/scopes/list`,{headers: {@@ -848,7 +848,7 @@ const getAppsBitbucket = async ({ accessToken, workspaceSlug }: { accessToken: slet repositoriesUrl = `${IntegrationUrls.BITBUCKET_API_URL}/2.0/repositories/${workspaceSlug}`;while (hasNextPage) {- const { data }: { data: RepositoriesResponse } = await request.get(repositoriesUrl, {+ const { data }: { data: RepositoriesResponse } = await safeRequest.get(repositoriesUrl, {headers: {Authorization: `Bearer ${accessToken}`,Accept: "application/json"@@ -929,7 +929,7 @@ const getAppsCodefresh = async ({ accessToken }: { accessToken: string }) => {*/const getAppsWindmill = async ({ accessToken, url }: { accessToken: string; url?: string | null }) => {const apiUrl = url ? `${url}/api` : IntegrationUrls.WINDMILL_API_URL;- const { data } = await request.get<{ id: string; name: string }[]>(`${apiUrl}/workspaces/list`, {+ const { data } = await safeRequest.get<{ id: string; name: string }[]>(`${apiUrl}/workspaces/list`, {headers: {Authorization: `Bearer ${accessToken}`,"Accept-Encoding": "application/json"@@ -942,7 +942,7 @@ const getAppsWindmill = async ({ accessToken, url }: { accessToken: string; url?const userPath = "u/user/variable";const folderPath = "f/folder/variable";- const { data: writeUser } = await request.post<object>(+ const { data: writeUser } = await safeRequest.post<object>(`${apiUrl}/w/${app.id}/variables/create`,{path: userPath,@@ -958,7 +958,7 @@ const getAppsWindmill = async ({ accessToken, url }: { accessToken: string; url?});- const { data: writeFolder } = await request.post<object>(+ const { data: writeFolder } = await safeRequest.post<object>(`${apiUrl}/w/${app.id}/variables/create`,{path: folderPath,@@ -976,14 +976,14 @@ const getAppsWindmill = async ({ accessToken, url }: { accessToken: string; url?// is write access is allowed then delete the created secrets from workspaceif (writeUser && writeFolder) {- await request.delete(`${apiUrl}/w/${app.id}/variables/delete/${userPath}`, {+ await safeRequest.delete(`${apiUrl}/w/${app.id}/variables/delete/${userPath}`, {headers: {Authorization: `Bearer ${accessToken}`,"Accept-Encoding": "application/json"}});- await request.delete(`${apiUrl}/w/${app.id}/variables/delete/${folderPath}`, {+ await safeRequest.delete(`${apiUrl}/w/${app.id}/variables/delete/${folderPath}`, {headers: {Authorization: `Bearer ${accessToken}`,"Accept-Encoding": "application/json"diff --git a/docs/self-hosting/guides/production-hardening.mdx b/docs/self-hosting/guides/production-hardening.mdxindex c3016ce94c..8c816f06a3 100644--- a/docs/self-hosting/guides/production-hardening.mdx+++ b/docs/self-hosting/guides/production-hardening.mdx@@ -83,6 +83,36 @@ CORS_ALLOWED_ORIGINS=["https://your-app.example.com"]ALLOW_INTERNAL_IP_CONNECTIONS=false```+#### Outbound Egress & SSRF Protection++Infisical issues outbound HTTP requests on behalf of users — to identity providers (OIDC/JWT/Kubernetes), to integration targets (GitHub, GitLab, Vault, RabbitMQ, etc.), to webhook destinations, and to certificate authorities. The platform applies layered protections to those outbound calls so a user-supplied URL cannot be abused to reach internal infrastructure (Server-Side Request Forgery, SSRF).++##### How Infisical hardens outbound calls++- **`ALLOW_INTERNAL_IP_CONNECTIONS=false` (default)** — outbound calls whose hostname resolves to a loopback, link-local, or RFC1918 address are rejected. Literal `localhost` and `host.docker.internal` are always rejected.+- **DNS pinning** — for every protected request, Infisical resolves the hostname once, validates the resulting IPs, and then pins the underlying TCP connection to those IPs. This defeats DNS-rebinding attacks where a hostname is benign at validation time but flips to an internal IP before the connection is opened.+- **No automatic redirects** — outbound calls do not follow `3xx` responses. If a destination redirects (for example, an `http://` URL that's fronted by an HTTPS-redirecting proxy), configure the final URL directly.+- **Embedded credentials rejected** — URLs containing a `user:pass@` userinfo segment are refused.+- **Internal infrastructure block** — even when `ALLOW_INTERNAL_IP_CONNECTIONS=true`, hostnames that match Infisical's own database, Redis, KMS, or HSM endpoints remain blocked.++##### When you need `ALLOW_INTERNAL_IP_CONNECTIONS=true`++Set this flag only when a trusted integration target is itself on a private network and there is no Infisical Gateway in front of it. Typical cases: self-hosted identity providers (OIDC, JWT, SPIFFE), self-hosted integrations and app connections (GitLab, GitHub Enterprise, Vault, NetScaler, Azure AD CS, etc.), webhook targets, audit-log streams, or ACME challenge endpoints reachable only via RFC1918 addresses.++When the flag is enabled, Infisical still pins DNS per request, so a previously validated hostname cannot rebind mid-flight. You lose only the private-IP guardrail — pair the flag with strict egress firewall rules from the Infisical host(s) to the specific internal targets you intend to reach.++<Note>+ Identity authentication and dynamic-secret access against an in-cluster **Kubernetes API server**, and **RabbitMQ dynamic secrets**, are allowed to target private IPs by design and do not require this flag. The trust boundary is enforced by the cluster token + TLS verification (Kubernetes) or by save-time host validation (RabbitMQ), not by the IP class.+</Note>++<Warning>+ Do NOT enable `ALLOW_INTERNAL_IP_CONNECTIONS=true` purely for convenience. On a multi-tenant cloud Infisical deployment this flag effectively disables the SSRF guardrail. It is intended for self-hosted deployments where the operator controls both Infisical and the targets it dials.+</Warning>++##### Gateway-proxied calls++Where available (Kubernetes dynamic secrets, Kubernetes identity auth, Vault external migration, etc.), the **Infisical Gateway** is the recommended way to reach internal services. The gateway terminates the connection inside your network, so Infisical itself only opens a connection to the gateway endpoint — `ALLOW_INTERNAL_IP_CONNECTIONS` does not need to be relaxed and SSRF protection is not weakened.+**Implement network firewalls**. Restrict network access to only necessary services:- **Required ports**: Infisical API (8080) and HTTPS (if applicable)