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(ssrf): add SAFE_REQUEST_FORCE_DIRECT_EGRESS config option and related tests
Victor Hugo dos Santos47128311ca26
diff --git a/backend/src/lib/config/env.ts b/backend/src/lib/config/env.tsindex f772e7a43c..87421a7566 100644--- a/backend/src/lib/config/env.ts+++ b/backend/src/lib/config/env.ts@@ -404,6 +404,11 @@ const envSchema = z/* App Connections ----------------------------------------------------------------------------- */ALLOW_INTERNAL_IP_CONNECTIONS: zodStrBool.default("false"),+ // Forces outbound requests made through the SSRF-safe HTTP client to use+ // direct egress (axios `proxy: false`), so the resolved-and-pinned target+ // IP cannot be bypassed by an ambient HTTP(S)_PROXY.+ SAFE_REQUEST_FORCE_DIRECT_EGRESS: zodStrBool.default("false"),+// awsINF_APP_CONNECTION_AWS_ACCESS_KEY_ID: zpStr(z.string().optional()),INF_APP_CONNECTION_AWS_SECRET_ACCESS_KEY: zpStr(z.string().optional()),diff --git a/backend/src/lib/validator/safe-request.socket.test.ts b/backend/src/lib/validator/safe-request.socket.test.tsnew file mode 100644index 0000000000..ad9e5336f2--- /dev/null+++ b/backend/src/lib/validator/safe-request.socket.test.ts@@ -0,0 +1,111 @@+/* eslint-disable @typescript-eslint/no-explicit-any */+import http from "node:http";+import type { AddressInfo } from "node:net";++import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";++import { buildSsrfSafeAgent } from "./safe-request";++// This suite is deliberately not mocking `node:dns` or the axios client the way+// `safe-request.test.ts` does. It opens a real loopback HTTP server and drives+// real sockets through the agent produced by `buildSsrfSafeAgent`, so it proves+// the connect-time behavior (that Node actually honors the pinned lookup) rather+// than the request-shaping logic. It runs in the fast unit step, no DB, Redis,+// or Docker, and only ever touches 127.0.0.1.+const { configState } = vi.hoisted(() => ({+ configState: {+ isDevelopmentMode: false,+ // Allow the loopback address to pass validation so we can pin to it.+ ALLOW_INTERNAL_IP_CONNECTIONS: true,+ SAFE_REQUEST_FORCE_DIRECT_EGRESS: false,+ SITE_URL: "https://infisical.example",+ REDIS_URL: "redis://internal-redis:6379",+ DB_HOST: "internal-db"+ }+}));++vi.mock("@app/lib/config/env", () => ({+ getConfig: () => configState+}));++// Don't let the internal-infra guard reject our loopback test server.+vi.mock("@app/ee/services/dynamic-secret/dynamic-secret-fns", () => ({+ verifyHostInputValidity: vi.fn(async () => undefined)+}));++vi.mock("@app/lib/logger", () => ({+ logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }+}));++const httpGet = (opts: http.RequestOptions) =>+ new Promise<{ status: number; body: string }>((resolve, reject) => {+ const req = http.get(opts, (res) => {+ let body = "";+ res.setEncoding("utf8");+ res.on("data", (chunk) => {+ body += chunk;+ });+ res.on("end", () => resolve({ status: res.statusCode ?? 0, body }));+ });+ req.on("error", reject);+ });++describe("safe-request real-socket pinning", () => {+ let server: http.Server;+ let port: number;+ const receivedPaths: string[] = [];++ beforeAll(async () => {+ server = http.createServer((req, res) => {+ receivedPaths.push(req.url ?? "");+ res.writeHead(200, { "content-type": "application/json" });+ res.end(JSON.stringify({ ok: true }));+ });+ await new Promise<void>((resolve) => {+ server.listen(0, "127.0.0.1", () => resolve());+ });+ port = (server.address() as AddressInfo).port;+ });++ afterAll(async () => {+ await new Promise<void>((resolve) => {+ server.close(() => resolve());+ });+ });++ it("routes a real request through the pinned agent to the validated loopback IP", async () => {+ // keepAlive:false so the socket closes after the response and doesn't hold+ // the server open at teardown.+ const agent = await buildSsrfSafeAgent(`http://127.0.0.1:${port}`, { keepAlive: false });+ expect(agent).toBeDefined();++ const res = await httpGet({ hostname: "127.0.0.1", port, path: "/positive", agent });++ expect(res.status).toBe(200);+ expect(JSON.parse(res.body)).toEqual({ ok: true });+ expect(receivedPaths).toContain("/positive");+ });++ it("control: an unresolvable hostname fails with ENOTFOUND without the pinned agent", async () => {+ // Establishes that `pinned-rebind.invalid` genuinely has no DNS record, so+ // the success in the next test can only come from the agent's pinned lookup.+ await expect(httpGet({ hostname: "pinned-rebind.invalid", port, path: "/control" })).rejects.toMatchObject({+ code: "ENOTFOUND"+ });+ });++ it("pins the connection to the validated IP even when the connect-time hostname differs (anti-rebinding)", async () => {+ // The agent was validated/pinned against 127.0.0.1. We then issue a request+ // to a different, unresolvable hostname reusing that agent, simulating a+ // DNS record that flipped between validation and connect. Because the pinned+ // lookup ignores connect-time DNS, the socket still lands on the loopback+ // server. If pinning were bypassed, this would fail with ENOTFOUND (proven+ // by the control test above).+ const agent = await buildSsrfSafeAgent(`http://127.0.0.1:${port}`, { keepAlive: false });++ const res = await httpGet({ hostname: "pinned-rebind.invalid", port, path: "/rebind", agent });++ expect(res.status).toBe(200);+ expect(receivedPaths).toContain("/rebind");+ });+});diff --git a/backend/src/lib/validator/safe-request.test.ts b/backend/src/lib/validator/safe-request.test.tsindex 987ab0bc60..21655cd23c 100644--- a/backend/src/lib/validator/safe-request.test.ts+++ b/backend/src/lib/validator/safe-request.test.ts@@ -20,6 +20,7 @@ const { lookupMock, configState, verifyHostInputValidityMock, requestRequestMockconst config = {isDevelopmentMode: false,ALLOW_INTERNAL_IP_CONNECTIONS: false,+ SAFE_REQUEST_FORCE_DIRECT_EGRESS: false,SITE_URL: "https://infisical.example",REDIS_URL: "redis://internal-redis:6379",DB_HOST: "internal-db",@@ -83,6 +84,7 @@ describe("safe-request SSRF helpers", () => {beforeEach(() => {configState.isDevelopmentMode = false;configState.ALLOW_INTERNAL_IP_CONNECTIONS = false;+ configState.SAFE_REQUEST_FORCE_DIRECT_EGRESS = false;requestRequestMock.mockReset();requestRequestMock.mockResolvedValue({ data: undefined, status: 200, headers: {} });verifyHostInputValidityMock.mockReset();@@ -433,6 +435,27 @@ describe("safe-request SSRF helpers", () => {expect(lookupMock).not.toHaveBeenCalledWith("attacker.example", expect.any(Object));});+ it("forces direct egress (proxy: false) when SAFE_REQUEST_FORCE_DIRECT_EGRESS is enabled", async () => {+ configState.SAFE_REQUEST_FORCE_DIRECT_EGRESS = true;+ requestRequestMock.mockResolvedValueOnce({ data: undefined, status: 200, headers: {} });+ await safeRequest.get("https://example.com");+ expect(lastRequestArgs().proxy).toBe(false);+ });++ it("leaves the ambient proxy untouched (no proxy key) when the flag is disabled", async () => {+ configState.SAFE_REQUEST_FORCE_DIRECT_EGRESS = false;+ requestRequestMock.mockResolvedValueOnce({ data: undefined, status: 200, headers: {} });+ await safeRequest.get("https://example.com");+ expect(lastRequestArgs().proxy).toBeUndefined();+ });++ it("forces direct egress on safeRequest.request when the flag is enabled", async () => {+ configState.SAFE_REQUEST_FORCE_DIRECT_EGRESS = true;+ requestRequestMock.mockResolvedValueOnce({ data: undefined, status: 200, headers: {} });+ await safeRequest.request({ url: "https://example.com/v1/items", method: "GET" });+ expect(lastRequestArgs().proxy).toBe(false);+ });+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({diff --git a/backend/src/lib/validator/safe-request.ts b/backend/src/lib/validator/safe-request.tsindex b4f91c5527..af7ce2ed5f 100644--- a/backend/src/lib/validator/safe-request.ts+++ b/backend/src/lib/validator/safe-request.ts@@ -338,6 +338,7 @@ const dispatch = async <T>(options: TSafeRequestConfig & TSafeRequestExtras = {}) => {const { allowPrivateIps, addressFamily, ca, rejectUnauthorized, servername, ...axiosOpts } = options;+ const appCfg = getConfig();const effectiveUrl = resolveBaseUrl(url, axiosOpts.baseURL);const validated = await validateAndPinUrl(effectiveUrl, { allowPrivateIps });const { protocol } = new URL(effectiveUrl);@@ -350,6 +351,9 @@ const dispatch = async <T>(url,...(data !== undefined && { data }),maxRedirects: 0,+ // Force direct egress so an ambient HTTP(S)_PROXY can't route around the+ // pinned agent (the proxy would re-resolve the target, defeating the pin).+ ...(appCfg.SAFE_REQUEST_FORCE_DIRECT_EGRESS && { proxy: false as const }),httpAgent: protocol === "http:" ? (agent as http.Agent | undefined) : undefined,httpsAgent: protocol === "https:" ? (agent as https.Agent | undefined) : undefined});@@ -357,6 +361,7 @@ const dispatch = async <T>(const dispatchFull = async <T>(config: TSafeRequestFullConfig) => {const { allowPrivateIps, addressFamily, ca, rejectUnauthorized, servername, url, ...axiosOpts } = config;+ const appCfg = getConfig();const effectiveUrl = resolveBaseUrl(url, axiosOpts.baseURL);const validated = await validateAndPinUrl(effectiveUrl, { allowPrivateIps });const { protocol } = new URL(effectiveUrl);@@ -367,6 +372,9 @@ const dispatchFull = async <T>(config: TSafeRequestFullConfig) => {...axiosOpts,url,maxRedirects: 0,+ // Force direct egress so an ambient HTTP(S)_PROXY can't route around the+ // pinned agent (the proxy would re-resolve the target, defeating the pin).+ ...(appCfg.SAFE_REQUEST_FORCE_DIRECT_EGRESS && { proxy: false as const }),httpAgent: protocol === "http:" ? (agent as http.Agent | undefined) : undefined,httpsAgent: protocol === "https:" ? (agent as https.Agent | undefined) : undefined});diff --git a/docs/self-hosting/configuration/envars.mdx b/docs/self-hosting/configuration/envars.mdxindex d41162982f..d64773462a 100644--- a/docs/self-hosting/configuration/envars.mdx+++ b/docs/self-hosting/configuration/envars.mdx@@ -60,14 +60,65 @@ Example values:default="false"optional>- Determines whether App Connections, Dynamic Secrets, and PKI Certificate- Discovery jobs are permitted to connect with internal/private IP addresses.+ Global escape hatch that permits App Connections, Dynamic Secrets, and PKI+ Certificate Discovery jobs to connect to internal/private IP addresses on the+ **direct egress** path.++ For reaching private resources, prefer the [Gateway](/documentation/platform/gateways/overview),+ which tunnels traffic through an agent inside your network and does not require+ opening any internal IP range on the Infisical instance. Use this flag (or the+ more targeted `DYNAMIC_SECRET_ALLOW_INTERNAL_IP` / `AUDIT_LOG_STREAM_ALLOW_INTERNAL_IP`+ flags) only for the features that egress directly, without a Gateway.<Warning>- Relaxes the SSRF protection. Only enable it if you trust the users who can configure streams.+ Relaxes the SSRF protection. In addition to allowing private IPs, enabling+ this also disables DNS-rebinding pin protection for the affected direct-egress+ path (validation and connection may resolve to different IPs). Only enable it+ if you trust the users who can configure these integrations, and scope it as+ narrowly as possible using the per-feature flags.</Warning></ParamField>+<ParamField+ query="DYNAMIC_SECRET_ALLOW_INTERNAL_IP"+ type="bool"+ default="false"+ optional+>+ Narrower, per-feature variant of `ALLOW_INTERNAL_IP_CONNECTIONS` that permits+ only Dynamic Secrets to connect to internal/private IP addresses. Prefer this+ over the global flag when only Dynamic Secrets need internal access.++ <Warning>+ Relaxes the SSRF protection for the Dynamic Secrets path, including disabling+ DNS-rebinding pin protection for that path. Prefer the [Gateway](/documentation/platform/gateways/overview)+ for private resources.+ </Warning>+</ParamField>++<ParamField+ query="SAFE_REQUEST_FORCE_DIRECT_EGRESS"+ type="bool"+ default="false"+ optional+>+ Forces outbound requests made through Infisical's SSRF-safe HTTP client (App+ Connections, Webhooks, Audit Log Streams, and similar direct-egress features)+ to bypass any ambient forward proxy (sets axios `proxy: false`). This guarantees+ the request connects to the exact IP that passed SSRF validation, closing a gap+ where an `HTTP_PROXY` / `HTTPS_PROXY` would re-resolve the target and defeat the+ IP pin.++ Defaults to `false` so an operator-configured forward proxy keeps working.++ <Note>+ Enable this only if your instance does **not** rely on an outbound+ `HTTP_PROXY` / `HTTPS_PROXY` for egress. When a proxy is in use, the IP pin+ cannot extend past the proxy (the proxy resolves the target itself), so+ leaving this off is the correct choice for proxied deployments.+ </Note>+</ParamField>+<ParamFieldquery="KUBERNETES_AUTO_FETCH_SERVICE_ACCOUNT_TOKEN"type="bool"diff --git a/docs/self-hosting/guides/production-hardening.mdx b/docs/self-hosting/guides/production-hardening.mdxindex 750516d82e..7f8d6e0592 100644--- a/docs/self-hosting/guides/production-hardening.mdx+++ b/docs/self-hosting/guides/production-hardening.mdx@@ -83,6 +83,48 @@ CORS_ALLOWED_ORIGINS=["https://your-app.example.com"]ALLOW_INTERNAL_IP_CONNECTIONS=false```+#### Server-Side Request Forgery (SSRF) Protection++Outbound requests to user-configured destinations (App Connections, Webhooks,+Audit Log Streams, Dynamic Secrets, PKI Discovery, and similar) run through an+SSRF-safe HTTP client that validates the destination and pins the connection to+the validated IP. Keep these controls in mind when hardening egress:++**Reaching private resources: prefer the Gateway.** To integrate with services+on an internal/private network, deploy the [Gateway](/documentation/platform/gateways/overview)+rather than opening internal IP ranges on the Infisical instance. The Gateway+runs inside your network and tunnels traffic over an mTLS connection, so no+internal IP allowlisting is required and SSRF protection on the instance stays+fully enabled.++**Opening internal IPs: scope it as narrowly as possible.** For the features+that egress directly (without a Gateway), private-IP access is disabled by+default. When you must allow it, prefer the per-feature flags over the global+switch, and understand that enabling any of these also disables DNS-rebinding pin+protection for that path:++```bash+# Global (all direct-egress features) — broadest, least preferred+ALLOW_INTERNAL_IP_CONNECTIONS=false++# Per-feature (narrower, preferred when you must allow internal IPs)+DYNAMIC_SECRET_ALLOW_INTERNAL_IP=false+AUDIT_LOG_STREAM_ALLOW_INTERNAL_IP=false+```++**Force direct egress to preserve the IP pin.** If your instance does not rely on+an outbound forward proxy, enable `SAFE_REQUEST_FORCE_DIRECT_EGRESS` so requests+cannot be routed through an ambient `HTTP_PROXY` / `HTTPS_PROXY` that would+re-resolve the target and bypass the validated-IP pin. It is `false` by default+(Infisical Cloud enables it through its own deployment configuration); set it+explicitly for hardened self-hosted deployments that do not use an egress proxy:++```bash+# Guarantee outbound requests connect to the validated IP (no proxy re-resolution).+# Only enable if you do NOT use an outbound HTTP(S)_PROXY for egress.+SAFE_REQUEST_FORCE_DIRECT_EGRESS=true+```+**Implement network firewalls**. Restrict network access to only necessary services:- **Required ports**: Infisical API (8080) and HTTPS (if applicable)