Skip to content

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

Revert "Merge pull request #6250 from Infisical/feature/dns-pinning-for-external-requests"

Victor Hugo dos Santos146da9b0c964
diff --git a/CLAUDE.md b/CLAUDE.md
index d4e5d2c2fe..a630ffef25 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -65,10 +65,6 @@ No IoC container. Every service is a factory function with explicit dependencies
React 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 Date
When 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.md
index 3900236fd9..e525ad3114 100644
--- a/backend/CLAUDE.md
+++ b/backend/CLAUDE.md
@@ -209,100 +209,6 @@ logger.info(`getPlan: Process done for [orgId=${orgId}] [projectId=${projectId}]
logger.error({ sessionId, err }, "Failed to get connection details");
```
-### Outbound HTTP & SSRF Protection
-
-Anywhere the backend issues an HTTP request to a URL derived from user input (webhooks, integrations, app connections, OIDC/JWKS, audit log streams, ACME, etc.), use the `safeRequest` helper from `@app/lib/validator` instead of the raw `request` (Axios) client.
-
-```ts
-import { safeRequest } from "@app/lib/validator";
-
-// Replace:
-// await blockLocalAndPrivateIpAddresses(url);
-// await request.post(url, body, { headers, timeout });
-// With:
-const res = await safeRequest.post<TResponse>(url, body, { headers, timeout });
-```
-
-`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. 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.{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).
-- `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 **and** DNS pinning **and** the Infisical internal-infrastructure blocklist (`verifyHostInputValidity`). `validateSsrfUrl` short-circuits when this flag is set, so no DNS resolution happens at validation time and Node's default resolver is used at connect time.
-
-**`allowPrivateIps: true` is only acceptable when there is a stronger runtime trust boundary than the IP class** (e.g., TLS cert verification + cluster token, or save-time host validation). The flag does not preserve rebinding protection or the internal-infra blocklist on its own.
-
-**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.
-
-**When you add a new outbound flow**
-
-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) Features
Enterprise code lives in `src/ee/`:
diff --git a/backend/src/ee/services/app-connections/chef/chef-connection-fns.ts b/backend/src/ee/services/app-connections/chef/chef-connection-fns.ts
index 44d22ed8b2..48b2508fc5 100644
--- a/backend/src/ee/services/app-connections/chef/chef-connection-fns.ts
+++ b/backend/src/ee/services/app-connections/chef/chef-connection-fns.ts
@@ -1,9 +1,10 @@
import { AxiosError } from "axios";
import crypto from "crypto";
+import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
import { removeTrailingSlash } from "@app/lib/fn";
-import { safeRequest } from "@app/lib/validator";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import { IntegrationUrls } from "@app/services/integration-auth/integration-list";
@@ -18,8 +19,12 @@ import {
TUpdateChefDataBagItem
} from "./chef-connection-types";
-export const getChefServerUrl = (serverUrl?: string) => {
- return serverUrl ? removeTrailingSlash(serverUrl) : IntegrationUrls.CHEF_API_URL;
+export const getChefServerUrl = async (serverUrl?: string) => {
+ const chefServerUrl = serverUrl ? removeTrailingSlash(serverUrl) : IntegrationUrls.CHEF_API_URL;
+
+ await blockLocalAndPrivateIpAddresses(chefServerUrl);
+
+ return chefServerUrl;
};
const buildSecureUrl = (baseUrl: string, path: string): string => {
@@ -140,12 +145,12 @@ export const validateChefConnectionCredentials = async (config: TChefConnectionC
try {
const path = `/organizations/${inputCredentials.orgName}/users/${inputCredentials.userName}`;
- const hostServerUrl = getChefServerUrl(inputCredentials.serverUrl);
+ const hostServerUrl = await getChefServerUrl(inputCredentials.serverUrl);
const headers = getChefAuthHeaders("GET", path, "", inputCredentials.userName, inputCredentials.privateKey);
const secureUrl = buildSecureUrl(hostServerUrl, path);
- await safeRequest.get(secureUrl, {
+ await request.get(secureUrl, {
headers
});
} catch (error: unknown) {
@@ -171,12 +176,12 @@ export const listChefDataBags = async (appConnection: TChefConnection): Promise<
const path = `/organizations/${orgName}/data`;
const body = "";
- const hostServerUrl = getChefServerUrl(serverUrl);
+ const hostServerUrl = await getChefServerUrl(serverUrl);
const headers = getChefAuthHeaders("GET", path, body, userName, privateKey);
const secureUrl = buildSecureUrl(hostServerUrl, path);
- const res = await safeRequest.get<Record<string, string>>(secureUrl, {
+ const res = await request.get<Record<string, string>>(secureUrl, {
headers
});
@@ -207,12 +212,12 @@ export const listChefDataBagItems = async (
const path = `/organizations/${orgName}/data/${dataBagName}`;
const body = "";
- const hostServerUrl = getChefServerUrl(serverUrl);
+ const hostServerUrl = await getChefServerUrl(serverUrl);
const headers = getChefAuthHeaders("GET", path, body, userName, privateKey);
const secureUrl = buildSecureUrl(hostServerUrl, path);
- const res = await safeRequest.get<Record<string, string>>(secureUrl, {
+ const res = await request.get<Record<string, string>>(secureUrl, {
headers
});
@@ -243,12 +248,12 @@ export const getChefDataBagItem = async ({
const path = `/organizations/${orgName}/data/${dataBagName}/${dataBagItemName}`;
const body = "";
- const hostServerUrl = getChefServerUrl(serverUrl);
+ const hostServerUrl = await getChefServerUrl(serverUrl);
const headers = getChefAuthHeaders("GET", path, body, userName, privateKey);
const secureUrl = buildSecureUrl(hostServerUrl, path);
- const res = await safeRequest.get<TChefDataBagItemContent>(secureUrl, {
+ const res = await request.get<TChefDataBagItemContent>(secureUrl, {
headers
});
@@ -277,12 +282,12 @@ export const createChefDataBagItem = async ({
const path = `/organizations/${orgName}/data/${dataBagName}`;
const body = JSON.stringify(data);
- const hostServerUrl = getChefServerUrl(serverUrl);
+ const hostServerUrl = await getChefServerUrl(serverUrl);
const headers = getChefAuthHeaders("POST", path, body, userName, privateKey);
const secureUrl = buildSecureUrl(hostServerUrl, path);
- await safeRequest.post(secureUrl, data, {
+ await request.post(secureUrl, data, {
headers
});
} catch (error) {
@@ -310,12 +315,12 @@ export const updateChefDataBagItem = async ({
const path = `/organizations/${orgName}/data/${dataBagName}/${dataBagItemName}`;
const body = JSON.stringify(data);
- const hostServerUrl = getChefServerUrl(serverUrl);
+ const hostServerUrl = await getChefServerUrl(serverUrl);
const headers = getChefAuthHeaders("PUT", path, body, userName, privateKey);
const secureUrl = buildSecureUrl(hostServerUrl, path);
- await safeRequest.put(secureUrl, data, {
+ await request.put(secureUrl, data, {
headers
});
} catch (error) {
@@ -342,12 +347,12 @@ export const removeChefDataBagItem = async ({
const path = `/organizations/${orgName}/data/${dataBagName}/${dataBagItemName}`;
const body = "";
- const hostServerUrl = getChefServerUrl(serverUrl);
+ const hostServerUrl = await getChefServerUrl(serverUrl);
const headers = getChefAuthHeaders("DELETE", path, body, userName, privateKey);
const secureUrl = buildSecureUrl(hostServerUrl, path);
- await safeRequest.delete(secureUrl, {
+ await request.delete(secureUrl, {
headers
});
} catch (error) {
diff --git a/backend/src/ee/services/audit-log-stream/azure/azure-provider-factory.ts b/backend/src/ee/services/audit-log-stream/azure/azure-provider-factory.ts
index b9175080b6..ecba115f69 100644
--- a/backend/src/ee/services/audit-log-stream/azure/azure-provider-factory.ts
+++ b/backend/src/ee/services/audit-log-stream/azure/azure-provider-factory.ts
@@ -2,7 +2,7 @@ import { RawAxiosRequestHeaders } from "axios";
import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
-import { safeRequest } from "@app/lib/validator";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { AUDIT_LOG_STREAM_TIMEOUT } from "../../audit-log/audit-log-queue";
import { TLogStreamFactoryStreamLog, TLogStreamFactoryValidateCredentials } from "../audit-log-stream-types";
@@ -42,6 +42,8 @@ export const AzureProviderFactory = () => {
}) => {
const { tenantId, clientId, clientSecret, dceUrl, dcrId, cltName } = credentials;
+ await blockLocalAndPrivateIpAddresses(dceUrl);
+
const token = await getAzureToken(tenantId, clientId, clientSecret);
const streamHeaders: RawAxiosRequestHeaders = {
@@ -49,7 +51,7 @@ export const AzureProviderFactory = () => {
Authorization: `Bearer ${token}`
};
- await safeRequest
+ await request
.post(
`${dceUrl}/dataCollectionRules/${dcrId}/streams/Custom-${cltName}_CL?api-version=2023-01-01`,
createPayload({ ping: "ok" }),
@@ -68,6 +70,8 @@ export const AzureProviderFactory = () => {
const streamLog: TLogStreamFactoryStreamLog<TAzureProviderCredentials> = async ({ credentials, auditLog }) => {
const { tenantId, clientId, clientSecret, dceUrl, dcrId, cltName } = credentials;
+ await blockLocalAndPrivateIpAddresses(dceUrl);
+
const token = await getAzureToken(tenantId, clientId, clientSecret);
const streamHeaders: RawAxiosRequestHeaders = {
@@ -75,7 +79,7 @@ export const AzureProviderFactory = () => {
Authorization: `Bearer ${token}`
};
- await safeRequest.post(
+ await request.post(
`${dceUrl}/dataCollectionRules/${dcrId}/streams/Custom-${cltName}_CL?api-version=2023-01-01`,
createPayload(auditLog),
{
diff --git a/backend/src/ee/services/audit-log-stream/cribl/cribl-provider-factory.ts b/backend/src/ee/services/audit-log-stream/cribl/cribl-provider-factory.ts
index 11a8e4b889..d0d2724f8c 100644
--- a/backend/src/ee/services/audit-log-stream/cribl/cribl-provider-factory.ts
+++ b/backend/src/ee/services/audit-log-stream/cribl/cribl-provider-factory.ts
@@ -1,7 +1,8 @@
import { RawAxiosRequestHeaders } from "axios";
+import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
-import { safeRequest } from "@app/lib/validator";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { AUDIT_LOG_STREAM_TIMEOUT } from "../../audit-log/audit-log-queue";
import { TLogStreamFactoryStreamLog, TLogStreamFactoryValidateCredentials } from "../audit-log-stream-types";
@@ -13,12 +14,14 @@ export const CriblProviderFactory = () => {
}) => {
const { url, token } = credentials;
+ await blockLocalAndPrivateIpAddresses(url);
+
const streamHeaders: RawAxiosRequestHeaders = {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`
};
- await safeRequest
+ await request
.post(url, JSON.stringify({ ping: "ok" }), {
headers: streamHeaders,
timeout: AUDIT_LOG_STREAM_TIMEOUT
@@ -33,12 +36,14 @@ export const CriblProviderFactory = () => {
const streamLog: TLogStreamFactoryStreamLog<TCriblProviderCredentials> = async ({ credentials, auditLog }) => {
const { url, token } = credentials;
+ await blockLocalAndPrivateIpAddresses(url);
+
const streamHeaders: RawAxiosRequestHeaders = {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`
};
- await safeRequest.post(url, JSON.stringify(auditLog), {
+ await request.post(url, JSON.stringify(auditLog), {
headers: streamHeaders,
timeout: AUDIT_LOG_STREAM_TIMEOUT
});
diff --git a/backend/src/ee/services/audit-log-stream/custom/custom-provider-factory.ts b/backend/src/ee/services/audit-log-stream/custom/custom-provider-factory.ts
index ab5d780239..47dc1a24ee 100644
--- a/backend/src/ee/services/audit-log-stream/custom/custom-provider-factory.ts
+++ b/backend/src/ee/services/audit-log-stream/custom/custom-provider-factory.ts
@@ -1,7 +1,8 @@
import { RawAxiosRequestHeaders } from "axios";
+import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
-import { safeRequest } from "@app/lib/validator";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { AUDIT_LOG_STREAM_TIMEOUT } from "../../audit-log/audit-log-queue";
import { TLogStreamFactoryStreamLog, TLogStreamFactoryValidateCredentials } from "../audit-log-stream-types";
@@ -13,6 +14,8 @@ export const CustomProviderFactory = () => {
}) => {
const { url, headers } = credentials;
+ await blockLocalAndPrivateIpAddresses(url);
+
const streamHeaders: RawAxiosRequestHeaders = { "Content-Type": "application/json" };
if (headers.length) {
headers.forEach(({ key, value }) => {
@@ -20,13 +23,14 @@ export const CustomProviderFactory = () => {
});
}
- await safeRequest
+ await request
.post(
url,
{ ping: "ok" },
{
headers: streamHeaders,
- timeout: AUDIT_LOG_STREAM_TIMEOUT
+ timeout: AUDIT_LOG_STREAM_TIMEOUT,
+ maxRedirects: 0
}
)
.catch((err) => {
@@ -39,6 +43,8 @@ export const CustomProviderFactory = () => {
const streamLog: TLogStreamFactoryStreamLog<TCustomProviderCredentials> = async ({ credentials, auditLog }) => {
const { url, headers } = credentials;
+ await blockLocalAndPrivateIpAddresses(url);
+
const streamHeaders: RawAxiosRequestHeaders = { "Content-Type": "application/json" };
if (headers.length) {
@@ -47,7 +53,7 @@ export const CustomProviderFactory = () => {
});
}
- await safeRequest.post(url, auditLog, {
+ await request.post(url, auditLog, {
headers: streamHeaders,
timeout: AUDIT_LOG_STREAM_TIMEOUT
});
diff --git a/backend/src/ee/services/audit-log-stream/datadog/datadog-provider-factory.ts b/backend/src/ee/services/audit-log-stream/datadog/datadog-provider-factory.ts
index 82ca1e5516..bec5b00ffc 100644
--- a/backend/src/ee/services/audit-log-stream/datadog/datadog-provider-factory.ts
+++ b/backend/src/ee/services/audit-log-stream/datadog/datadog-provider-factory.ts
@@ -1,8 +1,9 @@
import { RawAxiosRequestHeaders } from "axios";
import { getConfig } from "@app/lib/config/env";
+import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
-import { safeRequest } from "@app/lib/validator";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { AUDIT_LOG_STREAM_TIMEOUT } from "../../audit-log/audit-log-queue";
import { TLogStreamFactoryStreamLog, TLogStreamFactoryValidateCredentials } from "../audit-log-stream-types";
@@ -28,9 +29,11 @@ export const DatadogProviderFactory = () => {
}) => {
const { url, token } = credentials;
+ await blockLocalAndPrivateIpAddresses(url);
+
const streamHeaders: RawAxiosRequestHeaders = { "Content-Type": "application/json", "DD-API-KEY": token };
- await safeRequest
+ await request
.post(url, createPayload({ ping: "ok" }), {
headers: streamHeaders,
timeout: AUDIT_LOG_STREAM_TIMEOUT
@@ -45,9 +48,11 @@ export const DatadogProviderFactory = () => {
const streamLog: TLogStreamFactoryStreamLog<TDatadogProviderCredentials> = async ({ credentials, auditLog }) => {
const { url, token } = credentials;
+ await blockLocalAndPrivateIpAddresses(url);
+
const streamHeaders: RawAxiosRequestHeaders = { "Content-Type": "application/json", "DD-API-KEY": token };
- await safeRequest.post(url, createPayload(auditLog), {
+ await request.post(url, createPayload(auditLog), {
headers: streamHeaders,
timeout: AUDIT_LOG_STREAM_TIMEOUT
});
diff --git a/backend/src/ee/services/audit-log-stream/splunk/splunk-provider-factory.ts b/backend/src/ee/services/audit-log-stream/splunk/splunk-provider-factory.ts
index 084eac84ab..0baec037ef 100644
--- a/backend/src/ee/services/audit-log-stream/splunk/splunk-provider-factory.ts
+++ b/backend/src/ee/services/audit-log-stream/splunk/splunk-provider-factory.ts
@@ -1,8 +1,9 @@
import { RawAxiosRequestHeaders } from "axios";
import { getConfig } from "@app/lib/config/env";
+import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
-import { safeRequest } from "@app/lib/validator";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { AUDIT_LOG_STREAM_TIMEOUT } from "../../audit-log/audit-log-queue";
import { TLogStreamFactoryStreamLog, TLogStreamFactoryValidateCredentials } from "../audit-log-stream-types";
@@ -20,7 +21,7 @@ function createPayload(event: Record<string, unknown>) {
};
}
-function createSplunkUrl(hostname: string) {
+async function createSplunkUrl(hostname: string) {
let parsedHostname: string;
try {
parsedHostname = new URL(`https://${hostname}`).hostname;
@@ -28,6 +29,8 @@ function createSplunkUrl(hostname: string) {
throw new BadRequestError({ message: `Invalid Splunk hostname provided: ${(error as Error).message}` });
}
+ await blockLocalAndPrivateIpAddresses(`https://${parsedHostname}`);
+
return `https://${parsedHostname}:8088/services/collector/event`;
}
@@ -37,14 +40,14 @@ export const SplunkProviderFactory = () => {
}) => {
const { hostname, token } = credentials;
- const url = createSplunkUrl(hostname);
+ const url = await createSplunkUrl(hostname);
const streamHeaders: RawAxiosRequestHeaders = {
"Content-Type": "application/json",
Authorization: `Splunk ${token}`
};
- await safeRequest
+ await request
.post(url, createPayload({ ping: "ok" }), {
headers: streamHeaders,
timeout: AUDIT_LOG_STREAM_TIMEOUT
@@ -59,14 +62,14 @@ export const SplunkProviderFactory = () => {
const streamLog: TLogStreamFactoryStreamLog<TSplunkProviderCredentials> = async ({ credentials, auditLog }) => {
const { hostname, token } = credentials;
- const url = createSplunkUrl(hostname);
+ const url = await createSplunkUrl(hostname);
const streamHeaders: RawAxiosRequestHeaders = {
"Content-Type": "application/json",
Authorization: `Splunk ${token}`
};
- await safeRequest.post(url, createPayload(auditLog), {
+ await request.post(url, createPayload(auditLog), {
headers: streamHeaders,
timeout: AUDIT_LOG_STREAM_TIMEOUT
});
diff --git a/backend/src/ee/services/dynamic-secret/providers/azure-entra-id.ts b/backend/src/ee/services/dynamic-secret/providers/azure-entra-id.ts
index f1d51b1668..cc72f268b3 100644
--- a/backend/src/ee/services/dynamic-secret/providers/azure-entra-id.ts
+++ b/backend/src/ee/services/dynamic-secret/providers/azure-entra-id.ts
@@ -1,8 +1,8 @@
import { customAlphabet } from "nanoid";
+import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
import { sanitizeString } from "@app/lib/fn";
-import { safeRequest } from "@app/lib/validator";
import { AzureEntraIDSchema, TDynamicProviderFns } from "./models";
@@ -29,7 +29,7 @@ export const AzureEntraIDProvider = (): TDynamicProviderFns & {
applicationId: string,
clientSecret: string
): Promise<{ token?: string; success: boolean }> => {
- const response = await safeRequest.post<{ access_token: string }>(
+ const response = await request.post<{ access_token: string }>(
`${MSFT_LOGIN_URL}/${tenantId}/oauth2/v2.0/token`,
{
grant_type: "client_credentials",
@@ -76,7 +76,7 @@ export const AzureEntraIDProvider = (): TDynamicProviderFns & {
throw new BadRequestError({ message: "Failed to authorize to Microsoft Entra ID" });
}
- const response = await safeRequest.patch(
+ const response = await request.patch(
`${MSFT_GRAPH_API_URL}/users/${providerInputs.userId}`,
{
passwordProfile: {
@@ -136,13 +136,15 @@ export const AzureEntraIDProvider = (): TDynamicProviderFns & {
throw new BadRequestError({ message: "Failed to authorize to Microsoft Entra ID" });
}
- const response = await safeRequest.get<{
- value: { id: string; displayName: string; userPrincipalName: string }[];
- }>(`${MSFT_GRAPH_API_URL}/users`, {
- headers: {
- Authorization: `Bearer ${data.token}`
+ const response = await request.get<{ value: [{ id: string; displayName: string; userPrincipalName: string }] }>(
+ `${MSFT_GRAPH_API_URL}/users`,
+ {
+ headers: {
+ "Content-Type": "application/x-www-form-urlencoded",
+ Authorization: `Bearer ${data.token}`
+ }
}
- });
+ );
if (response.status !== 200) {
throw new BadRequestError({ message: "Failed to fetch users" });
diff --git a/backend/src/ee/services/dynamic-secret/providers/couchbase.ts b/backend/src/ee/services/dynamic-secret/providers/couchbase.ts
index ed53e1929e..06ed1c38e9 100644
--- a/backend/src/ee/services/dynamic-secret/providers/couchbase.ts
+++ b/backend/src/ee/services/dynamic-secret/providers/couchbase.ts
@@ -3,10 +3,11 @@ import crypto from "node:crypto";
import RE2 from "re2";
import { TDynamicSecrets } from "@app/db/schemas";
+import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
import { sanitizeString } from "@app/lib/fn";
import { alphaNumericNanoId } from "@app/lib/nanoid";
-import { blockLocalAndPrivateIpAddresses, safeRequest } from "@app/lib/validator/validate-url";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator/validate-url";
import { ActorIdentityAttributes } from "../../dynamic-secret-lease/dynamic-secret-lease-types";
import { DynamicSecretCouchbaseSchema, PasswordRequirements, TDynamicProviderFns } from "./models";
@@ -155,8 +156,10 @@ const couchbaseApiRequest = async (
apiKey: string,
data?: unknown
): Promise<CouchbaseUserResponse> => {
+ await blockLocalAndPrivateIpAddresses(url);
+
try {
- const response = await safeRequest.request({
+ const response = await request({
method: method.toLowerCase() as "get" | "post" | "put" | "delete",
url,
headers: {
@@ -164,7 +167,8 @@ const couchbaseApiRequest = async (
"Content-Type": "application/json"
},
data: data || undefined,
- timeout: 30000
+ timeout: 30000,
+ maxRedirects: 0
});
return response.data as CouchbaseUserResponse;
diff --git a/backend/src/ee/services/dynamic-secret/providers/github.ts b/backend/src/ee/services/dynamic-secret/providers/github.ts
index 35fd07b5d2..408189f56c 100644
--- a/backend/src/ee/services/dynamic-secret/providers/github.ts
+++ b/backend/src/ee/services/dynamic-secret/providers/github.ts
@@ -1,11 +1,11 @@
import { isAxiosError } from "axios";
import jwt from "jsonwebtoken";
+import { request } from "@app/lib/config/request";
import { crypto } from "@app/lib/crypto";
import { BadRequestError, InternalServerError } from "@app/lib/errors";
import { sanitizeString } from "@app/lib/fn";
import { alphaNumericNanoId } from "@app/lib/nanoid";
-import { safeRequest } from "@app/lib/validator";
import { IntegrationUrls } from "@app/services/integration-auth/integration-list";
import { DynamicSecretGithubSchema, TDynamicProviderFns } from "./models";
@@ -57,7 +57,7 @@ export const GithubProvider = (): TDynamicProviderFns => {
const tokenUrl = `${IntegrationUrls.GITHUB_API_URL}/app/installations/${String(installationId)}/access_tokens`;
try {
- const response = await safeRequest.post<GitHubInstallationTokenResponse>(tokenUrl, undefined, {
+ const response = await request.post<GitHubInstallationTokenResponse>(tokenUrl, undefined, {
headers: {
Authorization: `Bearer ${appJwt}`,
Accept: "application/vnd.github.v3+json",
diff --git a/backend/src/ee/services/dynamic-secret/providers/kubernetes.test.ts b/backend/src/ee/services/dynamic-secret/providers/kubernetes.test.ts
deleted file mode 100644
index ac28a7cf79..0000000000
--- a/backend/src/ee/services/dynamic-secret/providers/kubernetes.test.ts
+++ /dev/null
@@ -1,171 +0,0 @@
-/* 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 { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-import { KubernetesProvider } from "./kubernetes";
-import { KubernetesAuthMethod, KubernetesCredentialType } from "./models";
-
-// Asserts the k8sHttpClient factory inside KubernetesProvider:
-// - direct path (isGatewayProxied=false, caller-asserted):
-// * uses safeRequest (never request)
-// * translates ca / sslRejectUnauthorized into safeRequest's flat options
-// * drops the caller's pre-built httpsAgent
-// * always sets allowPrivateIps: true (in-cluster RFC1918 / link-local)
-// - gateway path (isGatewayProxied=true via $gatewayProxyWrapper):
-// * uses raw request (never safeRequest)
-// * preserves the gateway-supplied httpsAgent
-//
-// We drive this through the exported KubernetesProvider.validateConnection
-// using the Static credential type (single GET) to keep the test minimal.
-
-const { safeGetMock, safePostMock, safeDeleteMock, rawGetMock, rawPostMock, rawDeleteMock } = vi.hoisted(() => ({
- safeGetMock: vi.fn<(...args: any[]) => Promise<{ data: unknown; status: number }>>(),
- safePostMock: vi.fn<(...args: any[]) => Promise<{ data: unknown; status: number }>>(),
- safeDeleteMock: vi.fn<(...args: any[]) => Promise<{ data: unknown; status: number }>>(),
- rawGetMock: vi.fn<(...args: any[]) => Promise<{ data: unknown; status: number }>>(),
- rawPostMock: vi.fn<(...args: any[]) => Promise<{ data: unknown; status: number }>>(),
- rawDeleteMock: vi.fn<(...args: any[]) => Promise<{ data: unknown; status: number }>>()
-}));
-
-vi.mock("@app/lib/validator", () => ({
- blockLocalAndPrivateIpAddresses: vi.fn(async () => undefined),
- safeRequest: {
- get: (...args: unknown[]) => safeGetMock(...args),
- post: (...args: unknown[]) => safePostMock(...args),
- delete: (...args: unknown[]) => safeDeleteMock(...args)
- }
-}));
-
-vi.mock("@app/lib/config/request", () => ({
- request: {
- get: (...args: unknown[]) => rawGetMock(...args),
- post: (...args: unknown[]) => rawPostMock(...args),
- delete: (...args: unknown[]) => rawDeleteMock(...args)
- },
- createRequestClient: () => ({
- interceptors: { request: { use: vi.fn() }, response: { use: vi.fn() } },
- request: vi.fn(),
- get: vi.fn(),
- post: vi.fn(),
- delete: vi.fn()
- }),
- axiosResponseInterceptor: (r: unknown) => r
-}));
-
-vi.mock("@app/lib/gateway", () => ({
- GatewayProxyProtocol: { Tcp: "tcp", Http: "http" },
- GatewayHttpProxyActions: { UseGatewayK8sServiceAccount: "use-gateway-k8s-sa" },
- withGatewayProxy: async (cb: (port: number, agent: unknown) => Promise<unknown>, opts: any) =>
- cb(1234, opts?.httpsAgent)
-}));
-
-vi.mock("@app/lib/gateway-v2/gateway-v2", () => ({
- withGatewayV2Proxy: async (cb: (port: number) => Promise<unknown>) => cb(5678)
-}));
-
-vi.mock("./templateUtils", () => ({
- generateUsername: vi.fn(async () => "dynamic-secret-sa-abc123")
-}));
-
-vi.mock("@app/lib/config/env", () => ({ getConfig: () => ({ isDevelopmentMode: false }) }));
-vi.mock("@app/lib/logger", () => ({ logger: { error: vi.fn(), info: vi.fn(), warn: vi.fn() } }));
-
-const STATIC_INPUT_BASE = {
- credentialType: KubernetesCredentialType.Static,
- serviceAccountName: "my-sa",
- namespace: "default",
- audiences: [],
- authMethod: KubernetesAuthMethod.Api,
- clusterToken: "tok-abc",
- url: "https://k8s.example.com:6443",
- sslEnabled: true,
- ca: "-----BEGIN CERTIFICATE-----\nFAKECACERT==\n-----END CERTIFICATE-----",
- sslRejectUnauthorized: true
-};
-
-/** `TDynamicProviderFns.validateConnection` always receives project metadata; K8s ignores it in this test. */
-const VALIDATE_METADATA = { projectId: "00000000-0000-0000-0000-000000000000" };
-
-describe("KubernetesProvider — k8sHttpClient dispatch", () => {
- beforeEach(() => {
- for (const m of [safeGetMock, safePostMock, safeDeleteMock, rawGetMock, rawPostMock, rawDeleteMock]) {
- m.mockReset();
- m.mockResolvedValue({ data: {}, status: 200 });
- }
- });
-
- afterEach(() => {
- vi.clearAllMocks();
- });
-
- it("direct call (no gatewayId) → safeRequest.get with ca/rejectUnauthorized flat + allowPrivateIps + no httpsAgent", async () => {
- const provider = KubernetesProvider({
- gatewayService: { fnGetGatewayClientTlsByGatewayId: vi.fn() } as any,
- gatewayV2Service: { getPlatformConnectionDetailsByGatewayId: vi.fn() } as any
- });
-
- await provider.validateConnection({ ...STATIC_INPUT_BASE }, VALIDATE_METADATA);
-
- expect(safeGetMock).toHaveBeenCalledTimes(1);
- expect(rawGetMock).not.toHaveBeenCalled();
-
- const [, opts] = safeGetMock.mock.calls[0];
- expect(opts.allowPrivateIps).toBe(true);
- expect(opts.ca).toBe(STATIC_INPUT_BASE.ca);
- expect(opts.rejectUnauthorized).toBe(true);
- // Direct mode must drop the caller's pre-built httpsAgent — safeRequest
- // builds its own pinned agent from the flat options above.
- expect(opts.httpsAgent).toBeUndefined();
- });
-
- it("gateway path ($gatewayProxyWrapper asserts isGatewayProxied=true) → raw request.get with httpsAgent preserved", async () => {
- const gatewayDetails = { relayHost: "relay", gateway: { id: "g" }, relay: { id: "r" } };
- const provider = KubernetesProvider({
- gatewayService: { fnGetGatewayClientTlsByGatewayId: vi.fn() } as any,
- gatewayV2Service: {
- getPlatformConnectionDetailsByGatewayId: vi.fn(async () => gatewayDetails)
- } as any
- });
-
- await provider.validateConnection(
- {
- ...STATIC_INPUT_BASE,
- gatewayId: "gw-k8s"
- },
- VALIDATE_METADATA
- );
-
- expect(rawGetMock).toHaveBeenCalledTimes(1);
- expect(safeGetMock).not.toHaveBeenCalled();
-
- const [, opts] = rawGetMock.mock.calls[0];
- // Gateway path preserves the caller's https.Agent (carrying the relay TLS
- // context). The gateway already constrains the originally configured target.
- expect(opts.httpsAgent).toBeDefined();
- // It must NOT leak safeRequest-only flat TLS opts into the raw-request call.
- expect(opts.allowPrivateIps).toBeUndefined();
- expect(opts.ca).toBeUndefined();
- expect(opts.rejectUnauthorized).toBeUndefined();
- });
-
- it("direct call with sslEnabled=false does NOT forward ca / rejectUnauthorized (only allowPrivateIps stays)", async () => {
- const provider = KubernetesProvider({
- gatewayService: { fnGetGatewayClientTlsByGatewayId: vi.fn() } as any,
- gatewayV2Service: { getPlatformConnectionDetailsByGatewayId: vi.fn() } as any
- });
-
- await provider.validateConnection(
- {
- ...STATIC_INPUT_BASE,
- sslEnabled: false,
- ca: undefined
- },
- VALIDATE_METADATA
- );
-
- expect(safeGetMock).toHaveBeenCalledTimes(1);
- const [, opts] = safeGetMock.mock.calls[0];
- expect(opts.allowPrivateIps).toBe(true);
- expect(opts.ca).toBeUndefined();
- expect(opts.rejectUnauthorized).toBeUndefined();
- });
-});
diff --git a/backend/src/ee/services/dynamic-secret/providers/kubernetes.ts b/backend/src/ee/services/dynamic-secret/providers/kubernetes.ts
index 261ddf4b6b..5dac4914fc 100644
--- a/backend/src/ee/services/dynamic-secret/providers/kubernetes.ts
+++ b/backend/src/ee/services/dynamic-secret/providers/kubernetes.ts
@@ -1,6 +1,5 @@
-import { AxiosError, AxiosRequestConfig, isAxiosError } from "axios";
+import { AxiosError, isAxiosError } from "axios";
import https from "https";
-import { z } from "zod";
import { TDynamicSecrets } from "@app/db/schemas";
import { request } from "@app/lib/config/request";
@@ -8,7 +7,7 @@ import { BadRequestError } from "@app/lib/errors";
import { sanitizeString } from "@app/lib/fn";
import { GatewayHttpProxyActions, GatewayProxyProtocol, withGatewayProxy } from "@app/lib/gateway";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
-import { blockLocalAndPrivateIpAddresses, safeRequest } from "@app/lib/validator";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { TKubernetesTokenRequest } from "@app/services/identity-kubernetes-auth/identity-kubernetes-auth-types";
import {
@@ -49,65 +48,6 @@ export const KubernetesProvider = ({
return providerInputs;
};
- /**
- * Returns the right HTTP client for a Kubernetes API request:
- *
- * - Gateway-routed (`isGatewayProxied = true`, asserted by `$gatewayProxyWrapper`):
- * stays on the existing axios `request` so the gateway-supplied
- * `httpsAgent` (carrying the relay TLS context) is honored as before.
- * The gateway already enforces the originally configured target, so
- * SSRF/rebinding cannot land elsewhere.
- * - Direct (`isGatewayProxied = false`): switches to `safeRequest`, which
- * 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 / 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 };
-
- if (isGatewayProxied) {
- return {
- get: <T = unknown>(url: string, config: K8sRequestConfig) => request.get<T>(url, config),
- post: <T = unknown>(url: string, body: unknown, config: K8sRequestConfig) => request.post<T>(url, body, config),
- delete: <T = unknown>(url: string, config: K8sRequestConfig) => request.delete<T>(url, config)
- };
- }
-
- // safeRequest builds its own pinned agent — drop the caller's httpsAgent
- // and propagate ca / rejectUnauthorized via safeRequest's own options.
- const toSafeOpts = (config: K8sRequestConfig) => {
- const rest: AxiosRequestConfig = { ...config };
- 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.ca
- ? {
- ca: providerInputs.ca,
- rejectUnauthorized: providerInputs.sslRejectUnauthorized
- }
- : {})
- };
- };
-
- return {
- get: <T = unknown>(url: string, config: K8sRequestConfig) => safeRequest.get<T>(url, toSafeOpts(config)),
- post: <T = unknown>(url: string, body: unknown, config: K8sRequestConfig) =>
- safeRequest.post<T>(url, body, toSafeOpts(config)),
- delete: <T = unknown>(url: string, config: K8sRequestConfig) => safeRequest.delete<T>(url, toSafeOpts(config))
- };
- };
-
const $gatewayProxyWrapper = async <T>(
inputs: {
gatewayId: string;
@@ -116,12 +56,7 @@ export const KubernetesProvider = ({
httpsAgent?: https.Agent;
reviewTokenThroughGateway: boolean;
},
- gatewayCallback: (
- host: string,
- port: number,
- httpsAgent: https.Agent | undefined,
- isGatewayProxied: boolean
- ) => Promise<T>
+ gatewayCallback: (host: string, port: number, httpsAgent?: https.Agent) => Promise<T>
): Promise<T> => {
const gatewayV2ConnectionDetails = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({
gatewayId: inputs.gatewayId,
@@ -134,8 +69,7 @@ export const KubernetesProvider = ({
return gatewayCallback(
inputs.reviewTokenThroughGateway ? "http://localhost" : "https://localhost",
port,
- inputs.httpsAgent,
- true
+ inputs.httpsAgent
);
},
{
@@ -158,8 +92,7 @@ export const KubernetesProvider = ({
const res = await gatewayCallback(
inputs.reviewTokenThroughGateway ? "http://localhost" : "https://localhost",
port,
- httpsAgent,
- true
+ httpsAgent
);
return res;
},
@@ -189,18 +122,12 @@ export const KubernetesProvider = ({
usernamePrefix: "dynamic-secret-sa-"
});
- const serviceAccountDynamicCallback = async (
- host: string,
- port: number,
- httpsAgent: https.Agent | undefined,
- isGatewayProxied: boolean
- ) => {
+ const serviceAccountDynamicCallback = async (host: string, port: number, httpsAgent?: https.Agent) => {
if (providerInputs.credentialType !== KubernetesCredentialType.Dynamic) {
throw new Error("invalid callback");
}
const baseUrl = port ? `${host}:${port}` : host;
- const httpClient = k8sHttpClient(providerInputs, isGatewayProxied);
const roleBindingName = `${serviceAccountName}-role-binding`;
const namespaces = providerInputs.namespace.split(",").map((namespace) => namespace.trim());
@@ -209,7 +136,7 @@ export const KubernetesProvider = ({
for await (const namespace of namespaces) {
try {
// 1. Create a test service account
- await httpClient.post(
+ await request.post(
`${baseUrl}/api/v1/namespaces/${namespace}/serviceaccounts`,
{
metadata: {
@@ -245,7 +172,7 @@ export const KubernetesProvider = ({
...(providerInputs.roleType !== KubernetesRoleType.ClusterRole && { namespace })
};
- await httpClient.post(
+ await request.post(
roleBindingUrl,
{
metadata: roleBindingMetadata,
@@ -280,7 +207,7 @@ export const KubernetesProvider = ({
);
// 3. Request a token for the test service account
- await httpClient.post(
+ await request.post(
`${baseUrl}/api/v1/namespaces/${namespace}/serviceaccounts/${serviceAccountName}/token`,
{
spec: {
@@ -307,7 +234,7 @@ export const KubernetesProvider = ({
// 4. Cleanup: delete role binding and service account
if (providerInputs.roleType === KubernetesRoleType.Role) {
- await httpClient.delete(
+ await request.delete(
`${baseUrl}/apis/rbac.authorization.k8s.io/v1/namespaces/${namespace}/rolebindings/${roleBindingName}`,
{
headers: {
@@ -326,7 +253,7 @@ export const KubernetesProvider = ({
}
);
} else {
- await httpClient.delete(
+ await request.delete(
`${baseUrl}/apis/rbac.authorization.k8s.io/v1/clusterrolebindings/${roleBindingName}`,
{
headers: {
@@ -346,7 +273,7 @@ export const KubernetesProvider = ({
);
}
- await httpClient.delete(`${baseUrl}/api/v1/namespaces/${namespace}/serviceaccounts/${serviceAccountName}`, {
+ await request.delete(`${baseUrl}/api/v1/namespaces/${namespace}/serviceaccounts/${serviceAccountName}`, {
headers: {
"Content-Type": "application/json",
...(providerInputs.authMethod === KubernetesAuthMethod.Gateway
@@ -375,20 +302,14 @@ export const KubernetesProvider = ({
}
};
- const serviceAccountStaticCallback = async (
- host: string,
- port: number,
- httpsAgent: https.Agent | undefined,
- isGatewayProxied: boolean
- ) => {
+ const serviceAccountStaticCallback = async (host: string, port: number, httpsAgent?: https.Agent) => {
if (providerInputs.credentialType !== KubernetesCredentialType.Static) {
throw new Error("invalid callback");
}
const baseUrl = port ? `${host}:${port}` : host;
- const httpClient = k8sHttpClient(providerInputs, isGatewayProxied);
- await httpClient.get(
+ await request.get(
`${baseUrl}/api/v1/namespaces/${providerInputs.namespace}/serviceaccounts/${providerInputs.serviceAccountName}`,
{
headers: {
@@ -453,9 +374,9 @@ export const KubernetesProvider = ({
);
}
} else if (providerInputs.credentialType === KubernetesCredentialType.Static) {
- await serviceAccountStaticCallback(k8sHost, k8sPort, httpsAgent, false);
+ await serviceAccountStaticCallback(k8sHost, k8sPort, httpsAgent);
} else {
- await serviceAccountDynamicCallback(k8sHost, k8sPort, httpsAgent, false);
+ await serviceAccountDynamicCallback(k8sHost, k8sPort, httpsAgent);
}
return true;
@@ -512,18 +433,12 @@ export const KubernetesProvider = ({
usernamePrefix: "dynamic-secret-sa-"
});
- const serviceAccountDynamicCallback = async (
- host: string,
- port: number,
- httpsAgent: https.Agent | undefined,
- isGatewayProxied: boolean
- ) => {
+ const serviceAccountDynamicCallback = async (host: string, port: number, httpsAgent?: https.Agent) => {
if (providerInputs.credentialType !== KubernetesCredentialType.Dynamic) {
throw new Error("invalid callback");
}
const baseUrl = port ? `${host}:${port}` : host;
- const httpClient = k8sHttpClient(providerInputs, isGatewayProxied);
const roleBindingName = `${serviceAccountName}-role-binding`;
const allowedNamespaces = providerInputs.namespace.split(",").map((namespace) => namespace.trim());
@@ -541,7 +456,7 @@ export const KubernetesProvider = ({
}
// 1. Create the service account
- await httpClient.post(
+ await request.post(
`${baseUrl}/api/v1/namespaces/${namespace}/serviceaccounts`,
{
metadata: {
@@ -577,7 +492,7 @@ export const KubernetesProvider = ({
...(providerInputs.roleType !== KubernetesRoleType.ClusterRole && { namespace })
};
- await httpClient.post(
+ await request.post(
roleBindingUrl,
{
metadata: roleBindingMetadata,
@@ -612,7 +527,7 @@ export const KubernetesProvider = ({
);
// 3. Request a token for the service account
- const res = await httpClient.post<TKubernetesTokenRequest>(
+ const res = await request.post<TKubernetesTokenRequest>(
`${baseUrl}/api/v1/namespaces/${namespace}/serviceaccounts/${serviceAccountName}/token`,
{
spec: {
@@ -640,12 +555,7 @@ export const KubernetesProvider = ({
return { ...res.data, serviceAccountName };
};
- const tokenRequestStaticCallback = async (
- host: string,
- port: number,
- httpsAgent: https.Agent | undefined,
- isGatewayProxied: boolean
- ) => {
+ const tokenRequestStaticCallback = async (host: string, port: number, httpsAgent?: https.Agent) => {
if (providerInputs.credentialType !== KubernetesCredentialType.Static) {
throw new Error("invalid callback");
}
@@ -657,9 +567,8 @@ export const KubernetesProvider = ({
}
const baseUrl = port ? `${host}:${port}` : host;
- const httpClient = k8sHttpClient(providerInputs, isGatewayProxied);
- const res = await httpClient.post<TKubernetesTokenRequest>(
+ const res = await request.post<TKubernetesTokenRequest>(
`${baseUrl}/api/v1/namespaces/${providerInputs.namespace}/serviceaccounts/${providerInputs.serviceAccountName}/token`,
{
spec: {
@@ -736,8 +645,8 @@ export const KubernetesProvider = ({
} else {
tokenData =
providerInputs.credentialType === KubernetesCredentialType.Static
- ? await tokenRequestStaticCallback(k8sHost, k8sPort, httpsAgent, false)
- : await serviceAccountDynamicCallback(k8sHost, k8sPort, httpsAgent, false);
+ ? await tokenRequestStaticCallback(k8sHost, k8sPort, httpsAgent)
+ : await serviceAccountDynamicCallback(k8sHost, k8sPort, httpsAgent);
}
return {
@@ -779,24 +688,18 @@ export const KubernetesProvider = ({
) => {
const providerInputs = await validateProviderInputs(inputs);
- const serviceAccountDynamicCallback = async (
- host: string,
- port: number,
- httpsAgent: https.Agent | undefined,
- isGatewayProxied: boolean
- ) => {
+ const serviceAccountDynamicCallback = async (host: string, port: number, httpsAgent?: https.Agent) => {
if (providerInputs.credentialType !== KubernetesCredentialType.Dynamic) {
throw new Error("invalid callback");
}
const baseUrl = port ? `${host}:${port}` : host;
- const httpClient = k8sHttpClient(providerInputs, isGatewayProxied);
const roleBindingName = `${entityId}-role-binding`;
const namespace = config?.namespace ?? providerInputs.namespace.split(",")[0].trim();
if (providerInputs.roleType === KubernetesRoleType.Role) {
- await httpClient.delete(
+ await request.delete(
`${baseUrl}/apis/rbac.authorization.k8s.io/v1/namespaces/${namespace}/rolebindings/${roleBindingName}`,
{
headers: {
@@ -815,7 +718,7 @@ export const KubernetesProvider = ({
}
);
} else {
- await httpClient.delete(`${baseUrl}/apis/rbac.authorization.k8s.io/v1/clusterrolebindings/${roleBindingName}`, {
+ await request.delete(`${baseUrl}/apis/rbac.authorization.k8s.io/v1/clusterrolebindings/${roleBindingName}`, {
headers: {
"Content-Type": "application/json",
...(providerInputs.authMethod === KubernetesAuthMethod.Gateway
@@ -833,7 +736,7 @@ export const KubernetesProvider = ({
}
// Delete the service account
- await httpClient.delete(`${baseUrl}/api/v1/namespaces/${namespace}/serviceaccounts/${entityId}`, {
+ await request.delete(`${baseUrl}/api/v1/namespaces/${namespace}/serviceaccounts/${entityId}`, {
headers: {
"Content-Type": "application/json",
...(providerInputs.authMethod === KubernetesAuthMethod.Gateway
@@ -895,7 +798,7 @@ export const KubernetesProvider = ({
);
}
} else {
- await serviceAccountDynamicCallback(k8sHost, k8sPort, httpsAgent, false);
+ await serviceAccountDynamicCallback(k8sHost, k8sPort, httpsAgent);
}
} catch (error) {
let errorMessage = error instanceof Error ? error.message : "Unknown error";
diff --git a/backend/src/ee/services/dynamic-secret/providers/rabbit-mq.ts b/backend/src/ee/services/dynamic-secret/providers/rabbit-mq.ts
index e9b72583bc..d590578191 100644
--- a/backend/src/ee/services/dynamic-secret/providers/rabbit-mq.ts
+++ b/backend/src/ee/services/dynamic-secret/providers/rabbit-mq.ts
@@ -1,5 +1,4 @@
import axios, { Axios } from "axios";
-import http from "http";
import https from "https";
import { customAlphabet } from "nanoid";
import { z } from "zod";
@@ -8,7 +7,6 @@ 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";
@@ -85,16 +83,8 @@ 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,
+ baseURL: `${providerInputs.host}:${providerInputs.port}/api`,
auth: {
username: providerInputs.username,
password: providerInputs.password
@@ -103,9 +93,9 @@ export const RabbitMqProvider = (): TDynamicProviderFns => {
"Content-Type": "application/json"
},
maxRedirects: 0,
- ...(isHttps
- ? { httpsAgent: pinnedAgent as https.Agent | undefined }
- : { httpAgent: pinnedAgent as http.Agent | undefined })
+ ...(providerInputs.ca && {
+ httpsAgent: new https.Agent({ ca: providerInputs.ca, rejectUnauthorized: providerInputs.sslRejectUnauthorized })
+ })
});
return axiosInstance;
diff --git a/backend/src/ee/services/oidc/oidc-config-service.ts b/backend/src/ee/services/oidc/oidc-config-service.ts
index dfa669dfcc..bc3997327a 100644
--- a/backend/src/ee/services/oidc/oidc-config-service.ts
+++ b/backend/src/ee/services/oidc/oidc-config-service.ts
@@ -23,7 +23,6 @@ import { OrgServiceActor } from "@app/lib/types";
import {
blockLocalAndPrivateIpAddresses,
matchesAllowedEmailDomain,
- safeRequest,
sanitizeEmail,
validateEmail
} from "@app/lib/validator";
@@ -707,19 +706,8 @@ export const oidcConfigServiceFactory = ({
message: "OIDC not configured correctly"
});
}
- // 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 { data: meta } = await safeRequest.get<{
- issuer: string;
- authorization_endpoint?: string;
- token_endpoint?: string;
- userinfo_endpoint?: string;
- jwks_uri?: string;
- code_challenge_methods_supported?: string[];
- }>(oidcCfg.discoveryURL);
- issuer = new OpenIdIssuer(meta);
+ await blockLocalAndPrivateIpAddresses(oidcCfg.discoveryURL);
+ issuer = await Issuer.discover(oidcCfg.discoveryURL);
} else {
if (
!oidcCfg.issuer ||
@@ -732,6 +720,9 @@ 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/pki-acme/pki-acme-challenge-service.ts b/backend/src/ee/services/pki-acme/pki-acme-challenge-service.ts
index 43d6258470..391578cbb1 100644
--- a/backend/src/ee/services/pki-acme/pki-acme-challenge-service.ts
+++ b/backend/src/ee/services/pki-acme/pki-acme-challenge-service.ts
@@ -4,12 +4,13 @@ import { AxiosError, isAxiosError } from "axios";
import { TPkiAcmeChallenges } from "@app/db/schemas/pki-acme-challenges";
import { getConfig } from "@app/lib/config/env";
+import { request } from "@app/lib/config/request";
import { crypto } from "@app/lib/crypto/cryptography";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { isValidIp } from "@app/lib/ip";
import { isPrivateIp } from "@app/lib/ip/ipRange";
import { logger } from "@app/lib/logger";
-import { safeRequest } from "@app/lib/validator";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { ActorType } from "@app/services/auth/auth-type";
import { EventType, TAuditLogServiceFactory } from "../audit-log/audit-log-types";
@@ -95,12 +96,13 @@ export const pkiAcmeChallengeServiceFactory = ({
// TODO: read config from the profile to get the timeout instead
const timeoutMs = 10 * 1000; // 10 seconds
+ // SSRF protection: resolve DNS and block private/local IP addresses
+ await blockLocalAndPrivateIpAddresses(challengeUrl.toString());
+
// Notice: well, we are in a transaction, ideally we should not hold transaction and perform
// a long running operation for long time. But assuming we are not performing a tons of
// challenge validation at the same time, it should be fine.
- // SSRF protection: validates URL, blocks private IPs, and pins the connection to the
- // resolved IP to defeat DNS rebinding between validation and connect.
- const challengeResponse = await safeRequest.get<string>(challengeUrl.toString(), {
+ const challengeResponse = await request.get<string>(challengeUrl.toString(), {
// In case if we override the host in the development mode, still provide the original host in the header
// to help the upstream server to validate the request
headers: {
diff --git a/backend/src/ee/services/secret-rotation-v2/auth0-client-secret/auth0-client-secret-rotation-fns.ts b/backend/src/ee/services/secret-rotation-v2/auth0-client-secret/auth0-client-secret-rotation-fns.ts
index b0526c6236..3a4c26211a 100644
--- a/backend/src/ee/services/secret-rotation-v2/auth0-client-secret/auth0-client-secret-rotation-fns.ts
+++ b/backend/src/ee/services/secret-rotation-v2/auth0-client-secret/auth0-client-secret-rotation-fns.ts
@@ -9,7 +9,8 @@ import {
TRotationFactoryRevokeCredentials,
TRotationFactoryRotateCredentials
} from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-types";
-import { safeRequest } from "@app/lib/validator";
+import { request } from "@app/lib/config/request";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { getAuth0ConnectionAccessToken } from "@app/services/app-connection/auth0/auth0-connection-fns";
import { generatePassword } from "../shared/utils";
@@ -27,9 +28,10 @@ export const auth0ClientSecretRotationFactory: TRotationFactory<
const $rotateClientSecret = async () => {
const accessToken = await getAuth0ConnectionAccessToken(connection, appConnectionDAL, kmsService);
const { audience } = connection.credentials;
+ await blockLocalAndPrivateIpAddresses(audience);
const clientSecret = generatePassword();
- await safeRequest.request({
+ await request.request({
method: "PATCH",
url: `${audience}clients/${clientId}`,
headers: { authorization: `Bearer ${accessToken}` },
@@ -55,9 +57,10 @@ export const auth0ClientSecretRotationFactory: TRotationFactory<
) => {
const accessToken = await getAuth0ConnectionAccessToken(connection, appConnectionDAL, kmsService);
const { audience } = connection.credentials;
+ await blockLocalAndPrivateIpAddresses(audience);
// we just trigger an auth0 rotation to negate our credentials
- await safeRequest.request({
+ await request.request({
method: "POST",
url: `${audience}clients/${clientId}/rotate-secret`,
headers: { authorization: `Bearer ${accessToken}` }
diff --git a/backend/src/ee/services/secret-rotation-v2/databricks-service-principal-secret/databricks-service-principal-secret-rotation-fns.ts b/backend/src/ee/services/secret-rotation-v2/databricks-service-principal-secret/databricks-service-principal-secret-rotation-fns.ts
index b4a0516435..6581c057cd 100644
--- a/backend/src/ee/services/secret-rotation-v2/databricks-service-principal-secret/databricks-service-principal-secret-rotation-fns.ts
+++ b/backend/src/ee/services/secret-rotation-v2/databricks-service-principal-secret/databricks-service-principal-secret-rotation-fns.ts
@@ -12,9 +12,10 @@ import {
TRotationFactoryRevokeCredentials,
TRotationFactoryRotateCredentials
} from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-types";
+import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
import { removeTrailingSlash } from "@app/lib/fn";
-import { safeRequest } from "@app/lib/validator";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { getDatabricksConnectionAccessToken } from "@app/services/app-connection/databricks/databricks-connection-fns";
const DELAY_MS = 1000;
@@ -43,13 +44,15 @@ export const databricksServicePrincipalSecretRotationFactory: TRotationFactory<
const accessToken = await getDatabricksConnectionAccessToken(connection, appConnectionDAL, kmsService);
const workspaceUrl = removeTrailingSlash(connection.credentials.workspaceUrl);
+ await blockLocalAndPrivateIpAddresses(workspaceUrl);
+
const endpoint = `${workspaceUrl}/api/2.0/accounts/servicePrincipals/${servicePrincipalId}/credentials/secrets`;
const lifetimeSeconds = (rotationInterval * 2 + EXPIRY_PADDING_IN_DAYS) * 24 * 60 * 60;
const lifetime = `${lifetimeSeconds}s`;
try {
- const { data } = await safeRequest.post<unknown>(
+ const { data } = await request.post<unknown>(
endpoint,
{
lifetime
@@ -113,10 +116,12 @@ export const databricksServicePrincipalSecretRotationFactory: TRotationFactory<
const accessToken = await getDatabricksConnectionAccessToken(connection, appConnectionDAL, kmsService);
const workspaceUrl = removeTrailingSlash(connection.credentials.workspaceUrl);
+ await blockLocalAndPrivateIpAddresses(workspaceUrl);
+
const endpoint = `${workspaceUrl}/api/2.0/accounts/servicePrincipals/${servicePrincipalId}/credentials/secrets`;
try {
- const { data } = await safeRequest.get<{ secrets: Array<{ id: string; client_secret?: string }> }>(endpoint, {
+ const { data } = await request.get<{ secrets: Array<{ id: string; client_secret?: string }> }>(endpoint, {
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/json"
@@ -153,10 +158,12 @@ export const databricksServicePrincipalSecretRotationFactory: TRotationFactory<
const accessToken = await getDatabricksConnectionAccessToken(connection, appConnectionDAL, kmsService);
const workspaceUrl = removeTrailingSlash(connection.credentials.workspaceUrl);
+ await blockLocalAndPrivateIpAddresses(workspaceUrl);
+
const endpoint = `${workspaceUrl}/api/2.0/accounts/servicePrincipals/${servicePrincipalId}/credentials/secrets/${secretId}`;
try {
- await safeRequest.delete(endpoint, {
+ await request.delete(endpoint, {
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/json"
diff --git a/backend/src/ee/services/secret-rotation-v2/dbt-service-token/dbt-service-token-rotation-fns.ts b/backend/src/ee/services/secret-rotation-v2/dbt-service-token/dbt-service-token-rotation-fns.ts
index 46cf0eec6e..ec3a324652 100644
--- a/backend/src/ee/services/secret-rotation-v2/dbt-service-token/dbt-service-token-rotation-fns.ts
+++ b/backend/src/ee/services/secret-rotation-v2/dbt-service-token/dbt-service-token-rotation-fns.ts
@@ -8,9 +8,9 @@ import {
TRotationFactoryRevokeCredentials,
TRotationFactoryRotateCredentials
} from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-types";
+import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
-import { safeRequest } from "@app/lib/validator";
import { createDbtError, getDbtUrl, retrieveDbtAccount } from "@app/services/app-connection/dbt";
import {
@@ -37,7 +37,7 @@ export const dbtServiceTokenRotationFactory: TRotationFactory<
const instanceUrl = await getDbtUrl(connection);
try {
- const { data } = await safeRequest.post<TCreateDbtServiceTokenResponse>(
+ const { data } = await request.post<TCreateDbtServiceTokenResponse>(
`${instanceUrl}/api/v3/accounts/${connection.credentials.accountId}/service-tokens/`,
{
name: tokenName,
@@ -92,7 +92,7 @@ export const dbtServiceTokenRotationFactory: TRotationFactory<
const instanceUrl = await getDbtUrl(connection);
try {
- const { data } = await safeRequest.get<TGetDbtServiceTokenResponse>(
+ const { data } = await request.get<TGetDbtServiceTokenResponse>(
`${instanceUrl}/api/v3/accounts/${connection.credentials.accountId}/service-tokens/${tokenId}`,
{
headers: {
@@ -129,7 +129,7 @@ export const dbtServiceTokenRotationFactory: TRotationFactory<
const instanceUrl = await getDbtUrl(connection);
try {
- await safeRequest.delete(
+ await request.delete(
`${instanceUrl}/api/v3/accounts/${connection.credentials.accountId}/service-tokens/${tokenId}`,
{
headers: {
diff --git a/backend/src/ee/services/secret-rotation-v2/okta-client-secret/okta-client-secret-rotation-fns.ts b/backend/src/ee/services/secret-rotation-v2/okta-client-secret/okta-client-secret-rotation-fns.ts
index d3c24da91a..0fe4438d1f 100644
--- a/backend/src/ee/services/secret-rotation-v2/okta-client-secret/okta-client-secret-rotation-fns.ts
+++ b/backend/src/ee/services/secret-rotation-v2/okta-client-secret/okta-client-secret-rotation-fns.ts
@@ -8,9 +8,9 @@ import {
TRotationFactoryRevokeCredentials,
TRotationFactoryRotateCredentials
} from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-types";
+import { request } from "@app/lib/config/request";
import { delay as delayMs } from "@app/lib/delay";
import { BadRequestError } from "@app/lib/errors";
-import { safeRequest } from "@app/lib/validator";
import { getOktaInstanceUrl } from "@app/services/app-connection/okta";
import {
@@ -63,10 +63,10 @@ export const oktaClientSecretRotationFactory: TRotationFactory<
* Creates a new client secret for the Okta app.
*/
const $rotateClientSecret = async () => {
- const instanceUrl = getOktaInstanceUrl(connection);
+ const instanceUrl = await getOktaInstanceUrl(connection);
try {
- const { data } = await safeRequest.post<TOktaClientSecret>(
+ const { data } = await request.post<TOktaClientSecret>(
`${instanceUrl}/api/v1/apps/${clientId}/credentials/secrets`,
{},
{
@@ -109,10 +109,10 @@ export const oktaClientSecretRotationFactory: TRotationFactory<
* List client secrets.
*/
const $listClientSecrets = async () => {
- const instanceUrl = getOktaInstanceUrl(connection);
+ const instanceUrl = await getOktaInstanceUrl(connection);
try {
- const { data } = await safeRequest.get<TOktaClientSecret[]>(
+ const { data } = await request.get<TOktaClientSecret[]>(
`${instanceUrl}/api/v1/apps/${clientId}/credentials/secrets`,
{
headers: {
@@ -134,10 +134,10 @@ export const oktaClientSecretRotationFactory: TRotationFactory<
* Checks if a credential with the given secretId exists.
*/
const credentialExists = async (secretId: string): Promise<boolean> => {
- const instanceUrl = getOktaInstanceUrl(connection);
+ const instanceUrl = await getOktaInstanceUrl(connection);
try {
- const { data } = await safeRequest.get<TOktaClientSecret>(
+ const { data } = await request.get<TOktaClientSecret>(
`${instanceUrl}/api/v1/apps/${clientId}/credentials/secrets/${secretId}`,
{
headers: {
@@ -164,11 +164,11 @@ export const oktaClientSecretRotationFactory: TRotationFactory<
return; // Credential doesn't exist, nothing to revoke
}
- const instanceUrl = getOktaInstanceUrl(connection);
+ const instanceUrl = await getOktaInstanceUrl(connection);
try {
// First deactivate the secret
- await safeRequest.post(
+ await request.post(
`${instanceUrl}/api/v1/apps/${clientId}/credentials/secrets/${secretId}/lifecycle/deactivate`,
undefined,
{
@@ -179,7 +179,7 @@ export const oktaClientSecretRotationFactory: TRotationFactory<
);
// Then delete it
- await safeRequest.delete(`${instanceUrl}/api/v1/apps/${clientId}/credentials/secrets/${secretId}`, {
+ await request.delete(`${instanceUrl}/api/v1/apps/${clientId}/credentials/secrets/${secretId}`, {
headers: {
Authorization: `SSWS ${connection.credentials.apiToken}`
}
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.ts
index 4335b0d229..2d898d3f86 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
@@ -7,8 +7,8 @@ import {
TRotationFactoryRevokeCredentials,
TRotationFactoryRotateCredentials
} from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-types";
+import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
-import { safeRequest } from "@app/lib/validator";
import {
getSupabaseAuthHeaders,
getSupabaseInstanceUrl
@@ -52,11 +52,11 @@ export const supabaseApiKeyRotationFactory: TRotationFactory<
};
const $createApiKey = async () => {
- const baseUrl = getSupabaseInstanceUrl(connectionConfig);
+ const baseUrl = await getSupabaseInstanceUrl(connectionConfig);
const headers = getSupabaseAuthHeaders(connectionConfig);
try {
- const { data } = await safeRequest.post<TSupabaseApiKeyCreateResponse>(
+ const { data } = await request.post<TSupabaseApiKeyCreateResponse>(
`${baseUrl}/v1/projects/${encodeURIComponent(projectRef)}/api-keys`,
{
type: keyType === SupabaseApiKeyType.Publishable ? "publishable" : "secret",
@@ -88,11 +88,11 @@ export const supabaseApiKeyRotationFactory: TRotationFactory<
};
const $deleteApiKey = async (keyId: string) => {
- const baseUrl = getSupabaseInstanceUrl(connectionConfig);
+ const baseUrl = await getSupabaseInstanceUrl(connectionConfig);
const headers = getSupabaseAuthHeaders(connectionConfig);
try {
- await safeRequest.delete(
+ await request.delete(
`${baseUrl}/v1/projects/${encodeURIComponent(projectRef)}/api-keys/${encodeURIComponent(keyId)}`,
{
headers,
diff --git a/backend/src/lib/validator/index.ts b/backend/src/lib/validator/index.ts
index b0e2e60b1d..7ac495d51b 100644
--- a/backend/src/lib/validator/index.ts
+++ b/backend/src/lib/validator/index.ts
@@ -10,12 +10,5 @@ export {
validateSmbPassword,
validateWindowsUsername
} from "./validate-smb";
-export {
- blockLocalAndPrivateIpAddresses,
- buildSsrfSafeAgent,
- safeRequest,
- ssrfSafeGet,
- ssrfSafePost,
- validateSsrfUrl
-} from "./validate-url";
+export { blockLocalAndPrivateIpAddresses, ssrfSafeGet, ssrfSafePost, validateSsrfUrl } from "./validate-url";
export { isUuidV4 } from "./validate-uuid";
diff --git a/backend/src/lib/validator/validate-url.test.ts b/backend/src/lib/validator/validate-url.test.ts
index fbf05f5705..3ed5cb4462 100644
--- a/backend/src/lib/validator/validate-url.test.ts
+++ b/backend/src/lib/validator/validate-url.test.ts
@@ -1,488 +1,15 @@
-/* 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.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));
- });
- });
-
- 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 }] });
- });
- });
-});
+import { isFQDN } from "./validate-url";
describe("isFQDN", () => {
- it("Non wildcard", () => {
+ test("Non wildcard", () => {
expect(isFQDN("www.example.com")).toBeTruthy();
});
- it("Wildcard", () => {
+ test("Wildcard", () => {
expect(isFQDN("*.example.com", { allow_wildcard: true })).toBeTruthy();
});
- it("Wildcard FQDN fails on option allow_wildcard false", () => {
+ test("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.ts
index b73a08d737..d7127de1d7 100644
--- a/backend/src/lib/validator/validate-url.ts
+++ b/backend/src/lib/validator/validate-url.ts
@@ -1,10 +1,5 @@
-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 RE2 from "re2";
@@ -15,18 +10,10 @@ import { request } from "@app/lib/config/request";
import { BadRequestError } from "../errors";
import { isPrivateIp } from "../ip/ipRange";
-export type TValidatedHost = {
- hostname: string;
- entries: LookupAddress[];
-};
-
-export const blockLocalAndPrivateIpAddresses = async (
- url: string,
- isGateway = false
-): Promise<TValidatedHost | undefined> => {
+export const blockLocalAndPrivateIpAddresses = async (url: string, isGateway = false) => {
const appCfg = getConfig();
- if (appCfg.isDevelopmentMode || isGateway) return undefined;
+ if (appCfg.isDevelopmentMode || isGateway) return;
const validUrl = new URL(url);
@@ -34,25 +21,24 @@ export const blockLocalAndPrivateIpAddresses = async (
throw new BadRequestError({ message: "URLs with user credentials (e.g., user:pass@) are not allowed" });
}
- let entries: LookupAddress[];
+ const inputHostIps: string[] = [];
if (isIP(validUrl.hostname)) {
- entries = [{ address: validUrl.hostname, family: isIP(validUrl.hostname) }];
+ inputHostIps.push(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 });
+ const entries = await dns.lookup(validUrl.hostname, { all: true });
- if (!lookups || lookups.length === 0) {
+ if (!entries || entries.length === 0) {
throw new BadRequestError({ message: "Could not resolve hostname to any IP address" });
}
- entries = lookups;
+
+ inputHostIps.push(...entries.map(({ address }) => address));
}
- const isInternalIp = entries.some((e) => isPrivateIp(e.address));
+ const isInternalIp = inputHostIps.some((el) => isPrivateIp(el));
if (isInternalIp && !appCfg.ALLOW_INTERNAL_IP_CONNECTIONS)
throw new BadRequestError({ message: "Local IPs not allowed as URL" });
-
- return { hostname: validUrl.hostname, entries };
};
type FQDNOptions = {
@@ -165,306 +151,34 @@ type SsrfSafeRequestOptions = {
validateStatus?: (status: number) => boolean;
};
-/**
- * Builds a `dns.lookup`-shaped function that always returns the pre-validated
- * IPs from `entries`. Installed onto an http(s).Agent so the connect-time DNS
- * call cannot re-resolve and land on a different IP than the one validation
- * approved (DNS rebinding TOCTOU defense).
- */
-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 by default
-const pickPreferredEntry = (entries: LookupAddress[]): LookupAddress =>
- entries.find((e) => e.family === 4) ?? entries[0];
-
-const makePinnedLookup = (entries: LookupAddress[]): LookupFunction =>
- ((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 = pickPreferredEntry(entries);
- (optionsOrCb as TLookupOneCallback)(null, first.address, first.family);
- return;
- }
- const opts = (optionsOrCb ?? {}) as { all?: boolean; family?: number };
-
- // 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, entries);
- } else {
- const first = pickPreferredEntry(entries);
- (maybeCb as TLookupOneCallback)(null, first.address, first.family);
- }
- }) as LookupFunction;
-
-type TBuildAgentOptions = {
- addressFamily?: 4 | 6;
- /**
- * Custom CA for verifying the server certificate. Forwarded to https.Agent.
- * Only applied to HTTPS requests.
- */
- ca?: string | string[];
- /**
- * Whether to reject self-signed/invalid TLS certs. Forwarded to https.Agent.
- * Use with care — typically only set for legacy/internal services that ship
- * with their own CA (e.g. NetScaler, Venafi TPP).
- */
- rejectUnauthorized?: boolean;
- /**
- * TLS Server Name Indication (SNI). Forwarded to https.Agent so cert
- * verification uses the original hostname even when we connect by IP.
- * Required for hosts that present certs valid only for a specific name
- * (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.keepAlive !== undefined ||
- opts.checkServerIdentity !== undefined;
-
-const buildPinnedAgent = (
- validated: TValidatedHost | undefined,
- protocol: string,
- opts: TBuildAgentOptions = {}
-): http.Agent | https.Agent | undefined => {
- // If we don't have a pinned IP set AND there's no other agent customization,
- // fall through to Axios's default agent. This is the dev-mode/private-ip path.
- if (!validated && !hasAgentCustomization(opts)) return undefined;
-
- const isHttps = protocol === "https:";
- const lookup = validated ? makePinnedLookup(validated.entries) : undefined;
- const baseOpts: http.AgentOptions = {
- keepAlive: opts.keepAlive ?? false,
- family: opts.addressFamily,
- lookup
- };
-
- 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);
-};
-
/**
* Validates a URL for SSRF protection.
* Blocks:
* - Local/private IPs (loopback, link-local, RFC 1918 addresses)
* - Infisical's own infrastructure (DB, Redis, etc.)
- *
- * Returns the resolved IPs so the caller can pin the subsequent connection
- * to those IPs, preventing DNS rebinding between validation and connect.
*/
export const validateSsrfUrl = async (
url: string,
options?: Pick<SsrfSafeRequestOptions, "allowPrivateIps">
-): Promise<TValidatedHost | undefined> => {
+): Promise<void> => {
if (options?.allowPrivateIps) {
- return undefined;
+ return;
}
const parsedUrl = new URL(url);
- // Block local/private IPs and capture the resolved IPs for pinning
- const validated = await blockLocalAndPrivateIpAddresses(url, false);
+ // Block local/private IPs
+ await blockLocalAndPrivateIpAddresses(url, false);
// Also block Infisical's own infrastructure (DB, Redis, etc.)
await verifyHostInputValidity({ host: parsedUrl.hostname, isGateway: false, isDynamicSecret: false });
-
- 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;
- /**
- * Force IPv4 or IPv6 for the connection. The pinned lookup will filter the
- * validated IP set to this family. Mostly used for Azure App Configuration
- * where the docker setup's IPv6 path is unreliable.
- */
- addressFamily?: 4 | 6;
- /**
- * Custom CA for verifying the server certificate. Forwarded to the
- * per-request https.Agent so it composes with the pinned lookup.
- * Only applied to HTTPS URLs.
- */
- ca?: string | string[];
- /**
- * Whether to reject self-signed / invalid TLS certs. Forwarded to the
- * per-request https.Agent. Use with care.
- */
- rejectUnauthorized?: boolean;
- /**
- * TLS SNI servername forwarded to the per-request https.Agent. Required
- * for endpoints that present certs valid only for a specific hostname
- * (e.g. Kubernetes API servers). Defaults to the URL hostname if unset.
- */
- servername?: string;
-};
-
-type TSafeRequestConfig = Omit<AxiosRequestConfig, "httpAgent" | "httpsAgent" | "maxRedirects" | "url" | "method">;
-
-type TSafeRequestFullConfig = Omit<AxiosRequestConfig, "httpAgent" | "httpsAgent" | "maxRedirects"> & {
- url: 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 || 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 validateSsrfUrl(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 validateSsrfUrl(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
- });
};
/**
* Makes an HTTP GET request with SSRF-safe redirect handling.
* Disables automatic redirects and manually follows them while validating each hop.
* This prevents redirect-based SSRF bypasses where the initial URL is valid but
- * redirects to an internal/private IP address. Each hop also pins its connection
- * to the validated IP, blocking DNS rebinding between validation and connect.
+ * redirects to an internal/private IP address.
*/
export const ssrfSafeGet = async <T>(
url: string,
@@ -474,9 +188,13 @@ export const ssrfSafeGet = async <T>(
let redirectCount = 0;
while (redirectCount <= MAX_SAFE_REDIRECTS) {
+ // Validate URL before each request (including redirects)
// eslint-disable-next-line no-await-in-loop
- const response = await dispatch<T>("GET", currentUrl, undefined, {
- allowPrivateIps: options?.allowPrivateIps,
+ await validateSsrfUrl(currentUrl, options);
+
+ // eslint-disable-next-line no-await-in-loop
+ const response = await request.get<T>(currentUrl, {
+ maxRedirects: 0,
validateStatus: options?.validateStatus ?? ((status) => status >= 200 && status < 400)
});
@@ -511,53 +229,17 @@ export const ssrfSafeGet = async <T>(
/**
* Makes an HTTP POST request with SSRF protection.
- * Validates the URL, pins the connection to the validated IP (DNS rebinding
- * defense), and disables redirects.
+ * Validates the URL before making the request and disables redirects.
*/
export const ssrfSafePost = async <T>(
url: string,
data: unknown,
options?: Pick<SsrfSafeRequestOptions, "allowPrivateIps"> & { headers?: Record<string, string> }
): Promise<{ data: T }> => {
- return dispatch<T>("POST", url, data, {
- allowPrivateIps: options?.allowPrivateIps,
- headers: options?.headers
- });
-};
+ await validateSsrfUrl(url, options);
-/**
- * Drop-in replacement for `request.post` / `request.get` that validates the URL
- * and pins the connection to the validated IP. Use this anywhere the URL is
- * user-supplied and the caller currently does:
- *
- * await blockLocalAndPrivateIpAddresses(url);
- * await request.post(url, ...);
- *
- * Replace with:
- *
- * await safeRequest.post(url, ...);
- *
- * which collapses the two DNS resolutions into one, eliminating the rebinding
- * window.
- */
-// Defaults `T` to `any` to match Axios's `request.get`/`request.post` defaults,
-// keeping `safeRequest` a true drop-in replacement.
-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)
+ return request.post<T>(url, data, {
+ headers: options?.headers,
+ maxRedirects: 0
+ });
};
diff --git a/backend/src/services/app-connection/1password/1password-connection-fns.ts b/backend/src/services/app-connection/1password/1password-connection-fns.ts
index 78c101567d..44f3757b21 100644
--- a/backend/src/services/app-connection/1password/1password-connection-fns.ts
+++ b/backend/src/services/app-connection/1password/1password-connection-fns.ts
@@ -1,15 +1,20 @@
import { AxiosError } from "axios";
+import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
import { removeTrailingSlash } from "@app/lib/fn";
-import { safeRequest } from "@app/lib/validator";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import { OnePassConnectionMethod } from "./1password-connection-enums";
import { TOnePassConnection, TOnePassConnectionConfig, TOnePassVault } from "./1password-connection-types";
-export const getOnePassInstanceUrl = (config: TOnePassConnectionConfig) => {
- return removeTrailingSlash(config.credentials.instanceUrl);
+export const getOnePassInstanceUrl = async (config: TOnePassConnectionConfig) => {
+ const instanceUrl = removeTrailingSlash(config.credentials.instanceUrl);
+
+ await blockLocalAndPrivateIpAddresses(instanceUrl);
+
+ return instanceUrl;
};
export const getOnePassConnectionListItem = () => {
@@ -21,12 +26,12 @@ export const getOnePassConnectionListItem = () => {
};
export const validateOnePassConnectionCredentials = async (config: TOnePassConnectionConfig) => {
- const instanceUrl = getOnePassInstanceUrl(config);
+ const instanceUrl = await getOnePassInstanceUrl(config);
const { apiToken } = config.credentials;
try {
- const res = await safeRequest.get(`${instanceUrl}/v1/vaults`, {
+ const res = await request.get(`${instanceUrl}/v1/vaults`, {
headers: {
Authorization: `Bearer ${apiToken}`,
Accept: "application/json"
@@ -51,10 +56,10 @@ export const validateOnePassConnectionCredentials = async (config: TOnePassConne
};
export const listOnePassVaults = async (appConnection: TOnePassConnection) => {
- const instanceUrl = getOnePassInstanceUrl(appConnection);
+ const instanceUrl = await getOnePassInstanceUrl(appConnection);
const { apiToken } = appConnection.credentials;
- const resp = await safeRequest.get<TOnePassVault[]>(`${instanceUrl}/v1/vaults`, {
+ const resp = await request.get<TOnePassVault[]>(`${instanceUrl}/v1/vaults`, {
headers: {
Authorization: `Bearer ${apiToken}`,
Accept: "application/json"
diff --git a/backend/src/services/app-connection/auth0/auth0-connection-fns.ts b/backend/src/services/app-connection/auth0/auth0-connection-fns.ts
index cb0a045a9e..944b1f69a3 100644
--- a/backend/src/services/app-connection/auth0/auth0-connection-fns.ts
+++ b/backend/src/services/app-connection/auth0/auth0-connection-fns.ts
@@ -1,6 +1,7 @@
+import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
import { removeTrailingSlash } from "@app/lib/fn";
-import { safeRequest } from "@app/lib/validator";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import { encryptAppConnectionCredentials } from "@app/services/app-connection/app-connection-fns";
@@ -24,17 +25,19 @@ const authorizeAuth0Connection = async ({
audience
}: TAuth0ConnectionConfig["credentials"]) => {
const instanceUrl = domain.startsWith("http") ? domain : `https://${domain}`;
+ await blockLocalAndPrivateIpAddresses(instanceUrl);
- const { data } = await safeRequest.post<TAuth0AccessTokenResponse>(
- `${removeTrailingSlash(instanceUrl)}/oauth/token`,
- new URLSearchParams({
+ const { data } = await request.request<TAuth0AccessTokenResponse>({
+ method: "POST",
+ url: `${removeTrailingSlash(instanceUrl)}/oauth/token`,
+ headers: { "content-type": "application/x-www-form-urlencoded" },
+ data: new URLSearchParams({
grant_type: "client_credentials", // this will need to be resolved if we support methods other than client credentials
client_id: clientId,
client_secret: clientSecret,
audience
- }),
- { headers: { "content-type": "application/x-www-form-urlencoded" } }
- );
+ })
+ });
if (data.token_type !== "Bearer") {
throw new Error(`Unhandled token type: ${data.token_type}`);
diff --git a/backend/src/services/app-connection/auth0/auth0-connection-service.ts b/backend/src/services/app-connection/auth0/auth0-connection-service.ts
index f63a48f372..693c55ea62 100644
--- a/backend/src/services/app-connection/auth0/auth0-connection-service.ts
+++ b/backend/src/services/app-connection/auth0/auth0-connection-service.ts
@@ -1,5 +1,6 @@
+import { request } from "@app/lib/config/request";
import { OrgServiceActor } from "@app/lib/types";
-import { safeRequest } from "@app/lib/validator";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import { getAuth0ConnectionAccessToken } from "@app/services/app-connection/auth0/auth0-connection-fns";
@@ -21,6 +22,7 @@ const listAuth0Clients = async (
const accessToken = await getAuth0ConnectionAccessToken(appConnection, appConnectionDAL, kmsService);
const { audience, clientId: connectionClientId } = appConnection.credentials;
+ await blockLocalAndPrivateIpAddresses(audience);
const clients: TAuth0ListClient[] = [];
let hasMore = true;
@@ -28,7 +30,7 @@ const listAuth0Clients = async (
while (hasMore) {
// eslint-disable-next-line no-await-in-loop
- const { data: clientsPage } = await safeRequest.get<TAuth0ListClientsResponse>(`${audience}clients`, {
+ const { data: clientsPage } = await request.get<TAuth0ListClientsResponse>(`${audience}clients`, {
headers: {
Authorization: `Bearer ${accessToken}`,
"Accept-Encoding": "application/json"
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.ts
index 09b6961890..3aaf9fb6e9 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, buildSsrfSafeAgent } from "@app/lib/validator/validate-url";
+import { blockLocalAndPrivateIpAddresses } 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,25 +104,18 @@ const normalizeAdcsUrl = (url: string): string => {
return normalizedUrl;
};
-// 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, {
+// NTLM request wrapper
+const createHttpsAgent = (sslRejectUnauthorized: boolean, sslCertificate?: string): https.Agent => {
+ const agentOptions: https.AgentOptions = {
rejectUnauthorized: sslRejectUnauthorized,
- keepAlive: true,
- ca: sslCertificate ? sslCertificate.trim() : undefined,
+ 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
checkServerIdentity: () => undefined
- });
- // For HTTPS URLs (the only case ADCS supports — see normalizeAdcsUrl),
- // buildSsrfSafeAgent always returns an https.Agent.
- return agent as https.Agent;
+ };
+
+ return new https.Agent(agentOptions);
};
const axiosNtlmRequest = async (config: AxiosNtlmConfig): Promise<AxiosNtlmResponse> => {
@@ -186,10 +179,8 @@ const testAdcsConnection = async (
const shouldRejectUnauthorized = sslRejectUnauthorized;
- // eslint-disable-next-line no-await-in-loop
- const httpsAgent = await createHttpsAgent(testUrl, shouldRejectUnauthorized, sslCertificate);
+ const httpsAgent = createHttpsAgent(shouldRejectUnauthorized, sslCertificate);
- // eslint-disable-next-line no-await-in-loop
const response = await axiosNtlmRequest({
url: testUrl,
method: "GET",
@@ -301,12 +292,11 @@ const createNtlmClient = (
return {
get: async (endpoint: string, additionalHeaders: Record<string, string> = {}) => {
const shouldRejectUnauthorized = sslRejectUnauthorized;
- const url = `${normalizedUrl}${endpoint}`;
- const httpsAgent = await createHttpsAgent(url, shouldRejectUnauthorized, sslCertificate);
+ const httpsAgent = createHttpsAgent(shouldRejectUnauthorized, sslCertificate);
return axiosNtlmRequest({
- url,
+ url: `${normalizedUrl}${endpoint}`,
method: "GET",
httpsAgent,
headers: additionalHeaders,
@@ -319,12 +309,11 @@ const createNtlmClient = (
},
post: async (endpoint: string, body: string, additionalHeaders: Record<string, string> = {}) => {
const shouldRejectUnauthorized = sslRejectUnauthorized;
- const url = `${normalizedUrl}${endpoint}`;
- const httpsAgent = await createHttpsAgent(url, shouldRejectUnauthorized, sslCertificate);
+ const httpsAgent = createHttpsAgent(shouldRejectUnauthorized, sslCertificate);
return axiosNtlmRequest({
- url,
+ url: `${normalizedUrl}${endpoint}`,
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.ts
index 7c3d6d2b8f..a3169a0b3f 100644
--- a/backend/src/services/app-connection/bitbucket/bitbucket-connection-fns.ts
+++ b/backend/src/services/app-connection/bitbucket/bitbucket-connection-fns.ts
@@ -2,7 +2,6 @@ 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";
@@ -78,10 +77,9 @@ export const listBitbucketWorkspaces = async (appConnection: TBitbucketConnectio
// Limit to 10 iterations, fetching at most 10 * 100 = 1000 workspaces
while (nextUrl && iterationCount < 10) {
// eslint-disable-next-line no-await-in-loop
- const { data }: { data: BitbucketWorkspacesResponse } = await safeRequest.get<BitbucketWorkspacesResponse>(
- nextUrl,
- { headers }
- );
+ const { data }: { data: BitbucketWorkspacesResponse } = await request.get<BitbucketWorkspacesResponse>(nextUrl, {
+ headers
+ });
allWorkspaces = allWorkspaces.concat(data.values.map((membership) => ({ slug: membership.workspace.slug })));
nextUrl = data.next;
@@ -106,7 +104,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 safeRequest.get(nextUrl, { headers });
+ const { data }: { data: BitbucketPaginatedResponse<T> } = await request.get(nextUrl, { headers });
allItems = allItems.concat(data.values);
nextUrl = data.next;
@@ -165,10 +163,9 @@ export const listBitbucketEnvironments = async (
// Limit to 10 iterations, fetching at most 10 * 100 = 1000 environments
while (hasNextPage && iterationCount < 10) {
// eslint-disable-next-line no-await-in-loop
- const { data }: { data: { values: TBitbucketEnvironment[]; next: string } } = await safeRequest.get(
- environmentsUrl,
- { headers }
- );
+ const { data }: { data: { values: TBitbucketEnvironment[]; next: string } } = await request.get(environmentsUrl, {
+ headers
+ });
if (data?.values.length > 0) {
environments.push(...data.values);
diff --git a/backend/src/services/app-connection/circleci/circleci-connection-fns.ts b/backend/src/services/app-connection/circleci/circleci-connection-fns.ts
index b7929cec92..00a3afdd7f 100644
--- a/backend/src/services/app-connection/circleci/circleci-connection-fns.ts
+++ b/backend/src/services/app-connection/circleci/circleci-connection-fns.ts
@@ -1,7 +1,8 @@
import { AxiosError } from "axios";
+import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
-import { safeRequest } from "@app/lib/validator";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import { CircleCIConnectionMethod } from "./circleci-connection-enums";
@@ -41,6 +42,7 @@ export const getCircleCIApiUrl = async (config: {
}
const baseUrl = `https://${hostname}`;
+ await blockLocalAndPrivateIpAddresses(baseUrl);
const apiUrl = `${baseUrl}/api`;
@@ -62,7 +64,7 @@ export const validateCircleCIConnectionCredentials = async (config: TCircleCICon
const apiUrl = await getCircleCIApiUrl(config);
// Validate the API token by calling the /me endpoint
- await safeRequest.get(`${apiUrl}/v2/me`, {
+ await request.get(`${apiUrl}/v2/me`, {
headers: {
"Circle-Token": credentials.apiToken
}
@@ -91,7 +93,7 @@ export const listCircleCIOrganizations = async (
const apiUrl = await getCircleCIApiUrl(appConnection);
// Fetch organizations the user has access to (same as legacy integration)
- const { data: collaborations } = await safeRequest.get<TCircleCICollaboration[]>(`${apiUrl}/v2/me/collaborations`, {
+ const { data: collaborations } = await request.get<TCircleCICollaboration[]>(`${apiUrl}/v2/me/collaborations`, {
headers: {
"Circle-Token": apiToken,
"Accept-Encoding": "application/json"
@@ -99,7 +101,7 @@ export const listCircleCIOrganizations = async (
});
// Fetch all followed projects using the v1.1 API (same as legacy integration)
- const { data: allProjects } = await safeRequest.get<TCircleCIProjectV1Response[]>(`${apiUrl}/v1.1/projects`, {
+ const { data: allProjects } = await request.get<TCircleCIProjectV1Response[]>(`${apiUrl}/v1.1/projects`, {
headers: {
"Circle-Token": apiToken,
"Accept-Encoding": "application/json"
diff --git a/backend/src/services/app-connection/databricks/databricks-connection-fns.ts b/backend/src/services/app-connection/databricks/databricks-connection-fns.ts
index 75dbb2e318..a9128ec517 100644
--- a/backend/src/services/app-connection/databricks/databricks-connection-fns.ts
+++ b/backend/src/services/app-connection/databricks/databricks-connection-fns.ts
@@ -1,6 +1,7 @@
+import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
import { removeTrailingSlash } from "@app/lib/fn";
-import { safeRequest } from "@app/lib/validator";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import { encryptAppConnectionCredentials } from "@app/services/app-connection/app-connection-fns";
@@ -26,7 +27,9 @@ const authorizeDatabricksConnection = async ({
clientSecret,
workspaceUrl
}: Pick<TDatabricksConnection["credentials"], "workspaceUrl" | "clientId" | "clientSecret">) => {
- const { data } = await safeRequest.post<TAuthorizeDatabricksConnection>(
+ await blockLocalAndPrivateIpAddresses(workspaceUrl);
+
+ const { data } = await request.post<TAuthorizeDatabricksConnection>(
`${removeTrailingSlash(workspaceUrl)}/oidc/v1/token`,
"grant_type=client_credentials&scope=all-apis",
{
diff --git a/backend/src/services/app-connection/databricks/databricks-connection-service.ts b/backend/src/services/app-connection/databricks/databricks-connection-service.ts
index da8f844f7e..c6aaa6a949 100644
--- a/backend/src/services/app-connection/databricks/databricks-connection-service.ts
+++ b/backend/src/services/app-connection/databricks/databricks-connection-service.ts
@@ -1,6 +1,6 @@
+import { request } from "@app/lib/config/request";
import { removeTrailingSlash } from "@app/lib/fn";
import { OrgServiceActor } from "@app/lib/types";
-import { safeRequest } from "@app/lib/validator";
import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import { getDatabricksConnectionAccessToken } from "@app/services/app-connection/databricks/databricks-connection-fns";
@@ -28,7 +28,7 @@ const listDatabricksSecretScopes = async (
const accessToken = await getDatabricksConnectionAccessToken(appConnection, appConnectionDAL, kmsService);
- const { data } = await safeRequest.get<TDatabricksListSecretScopesResponse>(
+ const { data } = await request.get<TDatabricksListSecretScopesResponse>(
`${removeTrailingSlash(workspaceUrl)}/api/2.0/secrets/scopes/list`,
{
headers: {
@@ -61,7 +61,7 @@ const listDatabricksServicePrincipals = async (
while (currentPage < maxPages) {
// eslint-disable-next-line no-await-in-loop
- const { data } = await safeRequest.get<TDatabricksListServicePrincipalsResponse>(
+ const { data } = await request.get<TDatabricksListServicePrincipalsResponse>(
`${removeTrailingSlash(workspaceUrl)}/api/2.0/preview/scim/v2/ServicePrincipals`,
{
headers: {
diff --git a/backend/src/services/app-connection/dbt/dbt-connection-fns.ts b/backend/src/services/app-connection/dbt/dbt-connection-fns.ts
index c2f8058bf9..d059ece14e 100644
--- a/backend/src/services/app-connection/dbt/dbt-connection-fns.ts
+++ b/backend/src/services/app-connection/dbt/dbt-connection-fns.ts
@@ -1,9 +1,10 @@
/* eslint-disable no-await-in-loop */
import { AxiosError } from "axios";
+import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
-import { safeRequest } from "@app/lib/validator";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import { DbtConnectionMethod } from "./dbt-connection-constants";
@@ -32,6 +33,7 @@ export const getDbtUrl = async (config: {
}
const baseUrl = `https://${hostname}`;
+ await blockLocalAndPrivateIpAddresses(baseUrl);
return baseUrl;
};
@@ -52,7 +54,7 @@ export const retrieveDbtAccount = async (config: TDbtConnectionConfig) => {
const dbtUrl = await getDbtUrl(config);
- await safeRequest.get(`${dbtUrl}/api/v2/accounts/${credentials.accountId}/`, {
+ await request.get(`${dbtUrl}/api/v2/accounts/${credentials.accountId}/`, {
headers: {
Authorization: `Bearer ${credentials.apiToken}`
}
@@ -89,7 +91,7 @@ export const listDbtProjects = async (config: TDbtConnectionConfig) => {
const dbtUrl = await getDbtUrl(config);
- const res = await safeRequest.get<TDbtListProjectsResponse>(
+ const res = await request.get<TDbtListProjectsResponse>(
`${dbtUrl}/api/v3/accounts/${credentials.accountId}/projects`,
{
headers: {
diff --git a/backend/src/services/app-connection/external-infisical/external-infisical-connection-fns.ts b/backend/src/services/app-connection/external-infisical/external-infisical-connection-fns.ts
index ce3cd1360c..259fb018f0 100644
--- a/backend/src/services/app-connection/external-infisical/external-infisical-connection-fns.ts
+++ b/backend/src/services/app-connection/external-infisical/external-infisical-connection-fns.ts
@@ -1,7 +1,8 @@
import { AxiosError } from "axios";
+import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
-import { safeRequest } from "@app/lib/validator";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { TIdentityUaDALFactory } from "@app/services/identity-ua/identity-ua-dal";
import { AppConnection } from "../app-connection-enums";
@@ -40,7 +41,7 @@ export const getExternalInfisicalAccessToken = async (credentials: {
}): Promise<string> => {
const { instanceUrl, machineIdentityClientId, machineIdentityClientSecret } = credentials;
- const { data } = await safeRequest.post<{ accessToken: string; expiresIn: number; tokenType: string }>(
+ const { data } = await request.post<{ accessToken: string; expiresIn: number; tokenType: string }>(
`${instanceUrl}/api/v1/auth/universal-auth/login`,
{
clientId: machineIdentityClientId,
@@ -57,6 +58,8 @@ export const validateExternalInfisicalConnectionCredentials = async (
) => {
const { credentials: inputCredentials } = config;
+ await blockLocalAndPrivateIpAddresses(inputCredentials.instanceUrl);
+
const localIdentity = await identityUaDAL.findOne({
clientId: inputCredentials.machineIdentityClientId
});
@@ -85,6 +88,7 @@ export const validateExternalInfisicalConnectionCredentials = async (
};
const getAuthHeaders = async (connection: TExternalInfisicalConnection) => {
+ await blockLocalAndPrivateIpAddresses(connection.credentials.instanceUrl);
const token = await getExternalInfisicalAccessToken(connection.credentials);
return { Authorization: `Bearer ${token}` };
};
@@ -95,7 +99,7 @@ export const listProjects = async (connection: TExternalInfisicalConnection): Pr
const baseUrl = getBaseUrl(connection);
const headers = await getAuthHeaders(connection);
try {
- const { data } = await safeRequest.get<{
+ const { data } = await request.get<{
projects: Array<{
id: string;
name: string;
@@ -129,7 +133,7 @@ export const getEnvironmentFolderTree = async (
const baseUrl = getBaseUrl(connection);
const headers = await getAuthHeaders(connection);
try {
- const { data } = await safeRequest.get<TRemoteEnvironmentFolderTree>(
+ const { data } = await request.get<TRemoteEnvironmentFolderTree>(
`${baseUrl}/api/v1/projects/${projectId}/environment-folder-tree`,
{ headers }
);
diff --git a/backend/src/services/app-connection/github/github-connection-fns.test.ts b/backend/src/services/app-connection/github/github-connection-fns.test.ts
deleted file mode 100644
index 4024c2d78e..0000000000
--- a/backend/src/services/app-connection/github/github-connection-fns.test.ts
+++ /dev/null
@@ -1,149 +0,0 @@
-/* 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 { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-import { requestWithGitHubGateway } from "./github-connection-fns";
-
-// Asserts the "requestWithGitHubGateway" wrapper correctly routes:
-// - direct (no gatewayId) -> safeRequest.request
-// - gateway v1 (fnGetGatewayClientTlsByGatewayId only)
-// - gateway v2 (getPlatformConnectionDetailsByGatewayId returns details)
-// and never leaks a gateway call onto safeRequest or vice-versa.
-
-const { safeRequestMock, httpRequestMock, withGatewayProxyMock, withGatewayV2ProxyMock, verifyHostInputValidityMock } =
- vi.hoisted(() => ({
- safeRequestMock:
- vi.fn<(...args: any[]) => Promise<{ data: unknown; status: number; headers: Record<string, unknown> }>>(),
- httpRequestMock:
- vi.fn<(...args: any[]) => Promise<{ data: unknown; status: number; headers: Record<string, unknown> }>>(),
- // withGatewayProxy(cb, options) -> invoke cb(1234); track only cb on the spy (see vi.mock wrappers)
- withGatewayProxyMock: vi.fn(async (cb: (port: number, httpsAgent?: unknown) => Promise<unknown>) => cb(1234)),
- withGatewayV2ProxyMock: vi.fn(async (cb: (port: number) => Promise<unknown>) => cb(5678)),
- verifyHostInputValidityMock: vi.fn(async ({ host }: { host: string }) => [host] as string[])
- }));
-
-vi.mock("@app/lib/validator", () => ({
- safeRequest: { request: (...args: unknown[]) => safeRequestMock(...args) },
- blockLocalAndPrivateIpAddresses: vi.fn(async () => undefined)
-}));
-
-vi.mock("@app/lib/config/request", () => ({
- request: { request: (...args: unknown[]) => httpRequestMock(...args) },
- createRequestClient: () => ({
- interceptors: { request: { use: vi.fn() }, response: { use: vi.fn() } },
- request: (...args: unknown[]) => httpRequestMock(...args),
- get: vi.fn(),
- post: vi.fn(),
- delete: vi.fn()
- }),
- axiosResponseInterceptor: (r: unknown) => r
-}));
-
-vi.mock("@app/lib/gateway", () => ({
- GatewayProxyProtocol: { Tcp: "tcp", Http: "http" },
- withGatewayProxy: (cb: (port: number, httpsAgent?: unknown) => Promise<unknown>, options: unknown) => {
- void options;
- return withGatewayProxyMock(cb);
- }
-}));
-
-vi.mock("@app/lib/gateway-v2/gateway-v2", () => ({
- withGatewayV2Proxy: (cb: (port: number) => Promise<unknown>, options: unknown) => {
- void options;
- return withGatewayV2ProxyMock(cb);
- }
-}));
-
-vi.mock("@app/ee/services/dynamic-secret/dynamic-secret-fns", () => ({
- verifyHostInputValidity: verifyHostInputValidityMock
-}));
-
-vi.mock("@app/lib/config/env", () => ({ getConfig: () => ({ isDevelopmentMode: false }) }));
-vi.mock("@app/lib/logger", () => ({ logger: { error: vi.fn(), info: vi.fn() } }));
-
-const BASE_REQ = {
- url: "https://api.github.com/app",
- method: "GET" as const,
- headers: { Accept: "application/vnd.github+json" }
-};
-
-const okAxiosResponse = { data: { ok: true }, status: 200, headers: {} };
-
-describe("requestWithGitHubGateway", () => {
- beforeEach(() => {
- safeRequestMock.mockReset();
- safeRequestMock.mockResolvedValue(okAxiosResponse);
- httpRequestMock.mockReset();
- httpRequestMock.mockResolvedValue(okAxiosResponse);
- withGatewayProxyMock.mockClear();
- withGatewayV2ProxyMock.mockClear();
- verifyHostInputValidityMock.mockClear();
- });
-
- afterEach(() => {
- vi.clearAllMocks();
- });
-
- it("routes through safeRequest when gatewayId is null (direct path)", async () => {
- await requestWithGitHubGateway(
- { gatewayId: null },
- { fnGetGatewayClientTlsByGatewayId: vi.fn() } as any,
- { getPlatformConnectionDetailsByGatewayId: vi.fn() } as any,
- BASE_REQ
- );
-
- expect(safeRequestMock).toHaveBeenCalledTimes(1);
- expect(httpRequestMock).not.toHaveBeenCalled();
- expect(withGatewayProxyMock).not.toHaveBeenCalled();
- expect(withGatewayV2ProxyMock).not.toHaveBeenCalled();
- expect(safeRequestMock.mock.calls[0][0]).toMatchObject({ url: BASE_REQ.url, method: "GET" });
- });
-
- it("routes through gateway v2 (raw request) when v2 connection details are supplied", async () => {
- const v2Details = { relayHost: "relay.example", gateway: { id: "g1" }, relay: { id: "r1" } };
-
- await requestWithGitHubGateway(
- { gatewayId: "gw-123" },
- { fnGetGatewayClientTlsByGatewayId: vi.fn() } as any,
- { getPlatformConnectionDetailsByGatewayId: vi.fn() } as any,
- BASE_REQ,
- v2Details as any
- );
-
- expect(safeRequestMock).not.toHaveBeenCalled();
- expect(withGatewayV2ProxyMock).toHaveBeenCalledTimes(1);
- expect(withGatewayProxyMock).not.toHaveBeenCalled();
- expect(httpRequestMock).toHaveBeenCalledTimes(1);
-
- const call = httpRequestMock.mock.calls[0][0];
- expect(String(call.url)).toContain("localhost:5678");
- expect(call.headers.Host).toBe("api.github.com");
- expect(call.httpsAgent).toBeDefined();
- });
-
- it("falls back to gateway v1 (raw request) when no v2 details are supplied", async () => {
- const fnGetGatewayClientTlsByGatewayId = vi.fn(async () => ({
- relayPort: 9999,
- relayHost: "relay.v1",
- tlsOptions: {},
- identityId: "i",
- orgId: "o"
- }));
-
- await requestWithGitHubGateway(
- { gatewayId: "gw-123" },
- { fnGetGatewayClientTlsByGatewayId } as any,
- { getPlatformConnectionDetailsByGatewayId: vi.fn() } as any,
- BASE_REQ
- );
-
- expect(safeRequestMock).not.toHaveBeenCalled();
- expect(withGatewayV2ProxyMock).not.toHaveBeenCalled();
- expect(withGatewayProxyMock).toHaveBeenCalledTimes(1);
- expect(httpRequestMock).toHaveBeenCalledTimes(1);
- expect(fnGetGatewayClientTlsByGatewayId).toHaveBeenCalledWith("gw-123");
-
- const call = httpRequestMock.mock.calls[0][0];
- expect(String(call.url)).toContain("localhost:1234");
- expect(call.headers.Host).toBe("api.github.com");
- });
-});
diff --git a/backend/src/services/app-connection/github/github-connection-fns.ts b/backend/src/services/app-connection/github/github-connection-fns.ts
index bbe2759e15..d375637828 100644
--- a/backend/src/services/app-connection/github/github-connection-fns.ts
+++ b/backend/src/services/app-connection/github/github-connection-fns.ts
@@ -12,15 +12,13 @@ import { BadRequestError, ForbiddenRequestError, InternalServerError } from "@ap
import { GatewayProxyProtocol, withGatewayProxy } from "@app/lib/gateway";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
import { logger } from "@app/lib/logger";
-import { blockLocalAndPrivateIpAddresses, safeRequest } from "@app/lib/validator";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { getAppConnectionMethodName } from "@app/services/app-connection/app-connection-fns";
import { AppConnection } from "../app-connection-enums";
import { GitHubConnectionMethod } from "./github-connection-enums";
import { TGitHubConnection, TGitHubConnectionConfig } from "./github-connection-types";
-export type TGitHubGatewayRequestConfig = AxiosRequestConfig & { url: string };
-
export const getGitHubConnectionListItem = () => {
const { INF_APP_CONNECTION_GITHUB_OAUTH_CLIENT_ID, INF_APP_CONNECTION_GITHUB_APP_SLUG } = getConfig();
@@ -75,17 +73,17 @@ export const requestWithGitHubGateway = async <T>(
appConnection: { gatewayId?: string | null },
gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
- requestConfig: TGitHubGatewayRequestConfig,
+ requestConfig: AxiosRequestConfig,
gatewayConnectionDetails?: Awaited<ReturnType<TGatewayV2ServiceFactory["getPlatformConnectionDetailsByGatewayId"]>>
): Promise<AxiosResponse<T>> => {
const { gatewayId } = appConnection;
// If gateway isn't set up, don't proxy request
if (!gatewayId) {
- return safeRequest.request<T>(requestConfig);
+ return httpRequest.request(requestConfig);
}
- const url = new URL(requestConfig.url);
+ const url = new URL(requestConfig.url as string);
await blockLocalAndPrivateIpAddresses(url.toString());
diff --git a/backend/src/services/app-connection/gitlab/gitlab-connection-fns.ts b/backend/src/services/app-connection/gitlab/gitlab-connection-fns.ts
index 553c9d881f..37eeeaeb15 100644
--- a/backend/src/services/app-connection/gitlab/gitlab-connection-fns.ts
+++ b/backend/src/services/app-connection/gitlab/gitlab-connection-fns.ts
@@ -3,10 +3,11 @@ import { GitbeakerRequestError, Gitlab } from "@gitbeaker/rest";
import { AxiosError } from "axios";
import { getConfig } from "@app/lib/config/env";
+import { request } from "@app/lib/config/request";
import { BadRequestError, InternalServerError } from "@app/lib/errors";
import { removeTrailingSlash } from "@app/lib/fn";
import { logger } from "@app/lib/logger";
-import { blockLocalAndPrivateIpAddresses, safeRequest } from "@app/lib/validator";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import { encryptAppConnectionCredentials } from "@app/services/app-connection/app-connection-fns";
import { IntegrationUrls } from "@app/services/integration-auth/integration-list";
@@ -96,7 +97,7 @@ export const refreshGitLabToken = async (
try {
const url = await getGitLabInstanceUrl(instanceUrl);
- const { data } = await safeRequest.post<GitLabOAuthTokenResponse>(`${url}/oauth/token`, payload.toString(), {
+ const { data } = await request.post<GitLabOAuthTokenResponse>(`${url}/oauth/token`, payload.toString(), {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Accept: "application/json"
@@ -164,7 +165,7 @@ export const exchangeGitLabOAuthCode = async (
});
const url = await getGitLabInstanceUrl(instanceUrl);
- const response = await safeRequest.post<GitLabOAuthTokenResponse>(`${url}/oauth/token`, payload.toString(), {
+ const response = await request.post<GitLabOAuthTokenResponse>(`${url}/oauth/token`, payload.toString(), {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Accept: "application/json"
diff --git a/backend/src/services/app-connection/hc-vault/hc-vault-connection-fns.test.ts b/backend/src/services/app-connection/hc-vault/hc-vault-connection-fns.test.ts
deleted file mode 100644
index c8809fedce..0000000000
--- a/backend/src/services/app-connection/hc-vault/hc-vault-connection-fns.test.ts
+++ /dev/null
@@ -1,163 +0,0 @@
-/* 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 { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-import { GatewayVersion } from "@app/lib/gateway/types";
-
-import { requestWithHCVaultGateway } from "./hc-vault-connection-fns";
-
-// Asserts the "requestWithHCVaultGateway" wrapper correctly routes:
-// - direct (no gatewayId) -> safeRequest.request
-// - gateway v2 (v2 connection details) -> raw request via withGatewayV2Proxy
-// - gateway v1 (fallback when v2 absent) -> raw request via withGatewayProxy
-
-const { safeRequestMock, httpRequestMock, withGatewayProxyMock, withGatewayV2ProxyMock, verifyHostInputValidityMock } =
- vi.hoisted(() => ({
- safeRequestMock:
- vi.fn<(...args: any[]) => Promise<{ data: unknown; status: number; headers: Record<string, unknown> }>>(),
- httpRequestMock:
- vi.fn<(...args: any[]) => Promise<{ data: unknown; status: number; headers: Record<string, unknown> }>>(),
- withGatewayProxyMock: vi.fn(async (...args: any[]) => {
- const cb = args[0] as (port: number, httpsAgent?: unknown) => Promise<unknown>;
- return cb(1234);
- }),
- withGatewayV2ProxyMock: vi.fn(async (...args: any[]) => {
- const cb = args[0] as (port: number) => Promise<unknown>;
- return cb(5678);
- }),
- verifyHostInputValidityMock: vi.fn(async ({ host }: { host: string }) => [host] as string[])
- }));
-
-vi.mock("@app/lib/validator", () => ({
- safeRequest: { request: (...args: unknown[]) => safeRequestMock(...args) }
-}));
-
-vi.mock("@app/lib/config/request", () => ({
- request: { request: (...args: unknown[]) => httpRequestMock(...args) },
- createRequestClient: () => ({
- interceptors: { request: { use: vi.fn() }, response: { use: vi.fn() } },
- request: (...args: unknown[]) => httpRequestMock(...args),
- get: vi.fn(),
- post: vi.fn(),
- delete: vi.fn()
- }),
- axiosResponseInterceptor: (r: unknown) => r
-}));
-
-vi.mock("@app/lib/gateway", () => ({
- GatewayProxyProtocol: { Tcp: "tcp", Http: "http" },
- withGatewayProxy: (cb: (port: number) => Promise<unknown>, options: unknown) => withGatewayProxyMock(cb, options)
-}));
-
-vi.mock("@app/lib/gateway-v2/gateway-v2", () => ({
- withGatewayV2Proxy: (cb: (port: number) => Promise<unknown>, options: unknown) => withGatewayV2ProxyMock(cb, options)
-}));
-
-vi.mock("@app/ee/services/dynamic-secret/dynamic-secret-fns", () => ({
- verifyHostInputValidity: verifyHostInputValidityMock
-}));
-
-vi.mock("@app/lib/config/env", () => ({ getConfig: () => ({ isDevelopmentMode: false }) }));
-vi.mock("@app/lib/logger", () => ({ logger: { error: vi.fn(), info: vi.fn() } }));
-
-const BASE_REQ = {
- url: "https://vault.example.com:8200/v1/auth/token/lookup-self",
- method: "GET" as const,
- headers: { "X-Vault-Token": "t" }
-};
-
-const okAxiosResponse = { data: { ok: true }, status: 200, headers: {} };
-
-describe("requestWithHCVaultGateway", () => {
- beforeEach(() => {
- safeRequestMock.mockReset();
- safeRequestMock.mockResolvedValue(okAxiosResponse);
- httpRequestMock.mockReset();
- httpRequestMock.mockResolvedValue(okAxiosResponse);
- withGatewayProxyMock.mockClear();
- withGatewayV2ProxyMock.mockClear();
- verifyHostInputValidityMock.mockClear();
- });
-
- afterEach(() => {
- vi.clearAllMocks();
- });
-
- it("routes through safeRequest when gatewayId is absent", async () => {
- await requestWithHCVaultGateway(
- { gatewayId: null },
- { fnGetGatewayClientTlsByGatewayId: vi.fn() } as any,
- { getPlatformConnectionDetailsByGatewayId: vi.fn() } as any,
- BASE_REQ
- );
-
- expect(safeRequestMock).toHaveBeenCalledTimes(1);
- expect(httpRequestMock).not.toHaveBeenCalled();
- expect(withGatewayProxyMock).not.toHaveBeenCalled();
- expect(withGatewayV2ProxyMock).not.toHaveBeenCalled();
- expect(safeRequestMock.mock.calls[0][0]).toMatchObject({ url: BASE_REQ.url, method: "GET" });
- });
-
- it("routes through gateway v2 (raw request) when v2 details resolve", async () => {
- const v2Details = { relayHost: "relay.example", gateway: { id: "g1" }, relay: { id: "r1" } };
- const getPlatformConnectionDetailsByGatewayId = vi.fn(async () => v2Details);
-
- await requestWithHCVaultGateway(
- { gatewayId: "gw-vault" },
- { fnGetGatewayClientTlsByGatewayId: vi.fn() } as any,
- { getPlatformConnectionDetailsByGatewayId } as any,
- BASE_REQ
- );
-
- expect(safeRequestMock).not.toHaveBeenCalled();
- expect(withGatewayV2ProxyMock).toHaveBeenCalledTimes(1);
- expect(withGatewayProxyMock).not.toHaveBeenCalled();
- expect(httpRequestMock).toHaveBeenCalledTimes(1);
- const call = httpRequestMock.mock.calls[0][0];
- expect(String(call.url)).toContain("localhost:5678");
- expect(call.headers.Host).toBe("vault.example.com");
- });
-
- it("falls back to gateway v1 (raw request) when v2 details are null", async () => {
- const getPlatformConnectionDetailsByGatewayId = vi.fn(async () => null);
- const fnGetGatewayClientTlsByGatewayId = vi.fn(async () => ({
- relayPort: 9999,
- relayHost: "relay.v1",
- tlsOptions: {},
- identityId: "i",
- orgId: "o"
- }));
-
- await requestWithHCVaultGateway(
- { gatewayId: "gw-vault" },
- { fnGetGatewayClientTlsByGatewayId } as any,
- { getPlatformConnectionDetailsByGatewayId } as any,
- BASE_REQ
- );
-
- expect(safeRequestMock).not.toHaveBeenCalled();
- expect(withGatewayV2ProxyMock).not.toHaveBeenCalled();
- expect(withGatewayProxyMock).toHaveBeenCalledTimes(1);
- expect(httpRequestMock).toHaveBeenCalledTimes(1);
- expect(fnGetGatewayClientTlsByGatewayId).toHaveBeenCalledWith("gw-vault");
- });
-
- it("uses pre-supplied V1 gateway details without calling the DAL again", async () => {
- const fnGetGatewayClientTlsByGatewayId = vi.fn();
-
- await requestWithHCVaultGateway(
- { gatewayId: "gw-vault" },
- { fnGetGatewayClientTlsByGatewayId } as any,
- { getPlatformConnectionDetailsByGatewayId: vi.fn() } as any,
- BASE_REQ,
- {
- gatewayVersion: GatewayVersion.V1,
- details: { relayPort: 1, relayHost: "h", tlsOptions: {}, identityId: "i", orgId: "o" } as any,
- target: { host: "vault.example.com", port: 8200 }
- }
- );
-
- expect(fnGetGatewayClientTlsByGatewayId).not.toHaveBeenCalled();
- expect(withGatewayProxyMock).toHaveBeenCalledTimes(1);
- expect(httpRequestMock).toHaveBeenCalledTimes(1);
- });
-});
diff --git a/backend/src/services/app-connection/hc-vault/hc-vault-connection-fns.ts b/backend/src/services/app-connection/hc-vault/hc-vault-connection-fns.ts
index 6f2c99c404..d50e4e9bfa 100644
--- a/backend/src/services/app-connection/hc-vault/hc-vault-connection-fns.ts
+++ b/backend/src/services/app-connection/hc-vault/hc-vault-connection-fns.ts
@@ -12,7 +12,7 @@ import { GatewayProxyProtocol, withGatewayProxy } from "@app/lib/gateway";
import { GatewayVersion, TGatewayV1RelayDetails } from "@app/lib/gateway/types";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
import { logger } from "@app/lib/logger";
-import { safeRequest } from "@app/lib/validator";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import { HCVaultAuthType, HCVaultConnectionMethod } from "./hc-vault-connection-enums";
@@ -35,8 +35,6 @@ import {
THCVaultMountResponse
} from "./hc-vault-connection-types";
-export type THCVaultGatewayRequestConfig = AxiosRequestConfig & { url: string };
-
// HashiCorp Vault stores JSON data, so values can be any valid JSON type
export type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };
@@ -109,8 +107,10 @@ const createConcurrencyLimiter = (limit: number) => {
};
};
-export const getHCVaultInstanceUrl = (config: THCVaultConnectionConfig) => {
- return removeTrailingSlash(config.credentials.instanceUrl);
+export const getHCVaultInstanceUrl = async (config: THCVaultConnectionConfig) => {
+ const instanceUrl = removeTrailingSlash(config.credentials.instanceUrl);
+
+ return instanceUrl;
};
export const getHCVaultConnectionListItem = () => ({
@@ -132,16 +132,17 @@ export const requestWithHCVaultGateway = async <T>(
appConnection: { gatewayId?: string | null },
gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
- requestConfig: THCVaultGatewayRequestConfig,
+ requestConfig: AxiosRequestConfig,
gatewayDetails?: TGatewayDetails
): Promise<AxiosResponse<T>> => {
const { gatewayId } = appConnection;
- const url = new URL(requestConfig.url);
+ const url = new URL(requestConfig.url as string);
+ await blockLocalAndPrivateIpAddresses(url.toString(), Boolean(gatewayId));
// If gateway isn't set up, don't proxy request
if (!gatewayId) {
- return safeRequest.request<T>(requestConfig);
+ return request.request(requestConfig);
}
let gatewayConnectionDetailsV2: TGatewayV2ConnectionDetails | undefined;
@@ -305,7 +306,7 @@ export const validateHCVaultConnectionCredentials = async (
gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">
) => {
- const instanceUrl = getHCVaultInstanceUrl(connection);
+ const instanceUrl = await getHCVaultInstanceUrl(connection);
try {
const accessToken = await getHCVaultAccessToken(connection, gatewayService, gatewayV2Service);
@@ -344,7 +345,7 @@ export const getHCVaultPolicyNames = async (
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
gatewayDetails?: TGatewayDetails
) => {
- const instanceUrl = getHCVaultInstanceUrl(connection);
+ const instanceUrl = await getHCVaultInstanceUrl(connection);
const accessToken = await getHCVaultAccessToken(connection, gatewayService, gatewayV2Service);
try {
@@ -392,7 +393,7 @@ export const listHCVaultPolicies = async (
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
gatewayDetails?: TGatewayDetails
) => {
- const instanceUrl = getHCVaultInstanceUrl(connection);
+ const instanceUrl = await getHCVaultInstanceUrl(connection);
const accessToken = await getHCVaultAccessToken(connection, gatewayService, gatewayV2Service);
try {
@@ -466,7 +467,7 @@ export const listHCVaultNamespaces = async (
gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">
) => {
- const instanceUrl = getHCVaultInstanceUrl(connection);
+ const instanceUrl = await getHCVaultInstanceUrl(connection);
const accessToken = await getHCVaultAccessToken(connection, gatewayService, gatewayV2Service);
const currentNamespace = connection.credentials.namespace || "/";
@@ -585,7 +586,7 @@ export const listHCVaultMounts = async (
namespace?: string,
gatewayDetails?: TGatewayDetails
) => {
- const instanceUrl = getHCVaultInstanceUrl(connection);
+ const instanceUrl = await getHCVaultInstanceUrl(connection);
const accessToken = await getHCVaultAccessToken(connection, gatewayService, gatewayV2Service);
const targetNamespace = namespace || connection.credentials.namespace;
@@ -626,7 +627,7 @@ export const listHCVaultSecretPaths = async (
filterMountPath?: string,
gatewayDetails?: TGatewayDetails
) => {
- const instanceUrl = getHCVaultInstanceUrl(connection);
+ const instanceUrl = await getHCVaultInstanceUrl(connection);
const accessToken = await getHCVaultAccessToken(connection, gatewayService, gatewayV2Service);
const getPaths = async (mountPath: string, secretPath: string, kvVersion: "1" | "2"): Promise<string[] | null> => {
@@ -842,7 +843,7 @@ export const getHCVaultSecretsForPaths = async (
gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">
): Promise<Array<{ vaultSecretPath: string; secrets: Record<string, JsonValue> }>> => {
- const instanceUrl = getHCVaultInstanceUrl(connection);
+ const instanceUrl = await getHCVaultInstanceUrl(connection);
const accessToken = await getHCVaultAccessToken(connection, gatewayService, gatewayV2Service);
const mounts = await listHCVaultMounts(connection, gatewayService, gatewayV2Service, namespace);
const limiter = createConcurrencyLimiter(HC_VAULT_CONCURRENCY_LIMIT);
@@ -874,7 +875,7 @@ export const getHCVaultAuthMounts = async (
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
gatewayDetails?: TGatewayDetails
): Promise<THCVaultAuthMount[]> => {
- const instanceUrl = getHCVaultInstanceUrl(connection);
+ const instanceUrl = await getHCVaultInstanceUrl(connection);
const accessToken = await getHCVaultAccessToken(connection, gatewayService, gatewayV2Service);
try {
@@ -931,7 +932,7 @@ export const getHCVaultKubernetesAuthRoles = async (
gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">
): Promise<THCVaultKubernetesAuthRoleWithConfig[]> => {
- const instanceUrl = getHCVaultInstanceUrl(connection);
+ const instanceUrl = await getHCVaultInstanceUrl(connection);
const accessToken = await getHCVaultAccessToken(connection, gatewayService, gatewayV2Service);
// Remove trailing slash from mount path
@@ -1036,7 +1037,7 @@ export const getHCVaultKubernetesRoles = async (
const cleanMountPath = mountPath.endsWith("/") ? mountPath.slice(0, -1) : mountPath;
try {
- const instanceUrl = getHCVaultInstanceUrl(connection);
+ const instanceUrl = await getHCVaultInstanceUrl(connection);
const accessToken = await getHCVaultAccessToken(connection, gatewayService, gatewayV2Service);
// 1. Get the Kubernetes secrets engine configuration for this mount
const { data: configResponse } = await requestWithHCVaultGateway<{ data: THCVaultKubernetesSecretsConfig }>(
@@ -1139,7 +1140,7 @@ export const getHCVaultDatabaseRoles = async (
const cleanMountPath = mountPath.endsWith("/") ? mountPath.slice(0, -1) : mountPath;
try {
- const instanceUrl = getHCVaultInstanceUrl(connection);
+ const instanceUrl = await getHCVaultInstanceUrl(connection);
const accessToken = await getHCVaultAccessToken(connection, gatewayService, gatewayV2Service);
// 1. List all database connections in this mount to get their configs
@@ -1276,7 +1277,7 @@ export const getHCVaultLdapRoles = async (
const cleanMountPath = mountPath.endsWith("/") ? mountPath.slice(0, -1) : mountPath;
try {
- const instanceUrl = getHCVaultInstanceUrl(connection);
+ const instanceUrl = await getHCVaultInstanceUrl(connection);
const accessToken = await getHCVaultAccessToken(connection, gatewayService, gatewayV2Service);
// 1. Get the LDAP secrets engine configuration for this mount
diff --git a/backend/src/services/app-connection/netscaler/netscaler-connection-fns.test.ts b/backend/src/services/app-connection/netscaler/netscaler-connection-fns.test.ts
deleted file mode 100644
index e8129e6eed..0000000000
--- a/backend/src/services/app-connection/netscaler/netscaler-connection-fns.test.ts
+++ /dev/null
@@ -1,139 +0,0 @@
-/* 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 { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-import { executeNetScalerOperationWithGateway } from "./netscaler-connection-fns";
-
-// Asserts the "executeNetScalerOperationWithGateway" helper:
-// - direct path (no gatewayId) uses safeRequest with rejectUnauthorized/ca
-// forwarded as flat options (never a pre-built https.Agent)
-// - gateway v2 path uses raw request via withGatewayV2Proxy and passes
-// ca/rejectUnauthorized through a locally-built httpsAgent
-// - gateway path without resolvable v2 connection details throws
-
-const { safeRequestMock, httpRequestMock, withGatewayV2ProxyMock } = vi.hoisted(() => ({
- safeRequestMock:
- vi.fn<(...args: any[]) => Promise<{ data: unknown; status: number; headers: Record<string, unknown> }>>(),
- httpRequestMock:
- vi.fn<(...args: any[]) => Promise<{ data: unknown; status: number; headers: Record<string, unknown> }>>(),
- withGatewayV2ProxyMock: vi.fn(async (...args: any[]) => {
- const cb = args[0] as (port: number) => Promise<unknown>;
- return cb(5678);
- })
-}));
-
-vi.mock("@app/lib/validator", () => ({
- safeRequest: { request: (...args: unknown[]) => safeRequestMock(...args) }
-}));
-
-vi.mock("@app/lib/config/request", () => ({
- request: { request: (...args: unknown[]) => httpRequestMock(...args) },
- createRequestClient: () => ({
- interceptors: { request: { use: vi.fn() }, response: { use: vi.fn() } },
- request: (...args: unknown[]) => httpRequestMock(...args),
- get: vi.fn(),
- post: vi.fn(),
- delete: vi.fn()
- }),
- axiosResponseInterceptor: (r: unknown) => r
-}));
-
-vi.mock("@app/lib/gateway", () => ({
- GatewayProxyProtocol: { Tcp: "tcp", Http: "http" }
-}));
-
-vi.mock("@app/lib/gateway-v2/gateway-v2", () => ({
- withGatewayV2Proxy: (cb: (port: number) => Promise<unknown>, options: unknown) => withGatewayV2ProxyMock(cb, options)
-}));
-
-vi.mock("@app/lib/config/env", () => ({ getConfig: () => ({ isDevelopmentMode: false }) }));
-vi.mock("@app/lib/logger", () => ({ logger: { error: vi.fn(), info: vi.fn() } }));
-
-const CREDS = {
- hostname: "netscaler.example.com",
- port: 443,
- username: "u",
- password: "p",
- sslRejectUnauthorized: true,
- sslCertificate: "-----BEGIN CERTIFICATE-----\nMIIBASEFAKE==\n-----END CERTIFICATE-----"
-};
-
-const okDataResponse = { data: { ok: true }, status: 200, headers: {} };
-
-describe("executeNetScalerOperationWithGateway", () => {
- beforeEach(() => {
- safeRequestMock.mockReset();
- safeRequestMock.mockResolvedValue(okDataResponse);
- httpRequestMock.mockReset();
- httpRequestMock.mockResolvedValue(okDataResponse);
- withGatewayV2ProxyMock.mockClear();
- });
-
- afterEach(() => {
- vi.clearAllMocks();
- });
-
- it("direct path routes through safeRequest with rejectUnauthorized/ca as flat options", async () => {
- const result = await executeNetScalerOperationWithGateway(
- { gatewayId: null, credentials: CREDS },
- undefined,
- async (makeRequest) =>
- makeRequest<{ ok: boolean }>({
- url: `https://${CREDS.hostname}:${CREDS.port}/nitro/v1/config/login`,
- method: "POST",
- data: { login: {} }
- })
- );
-
- expect(result).toEqual({ ok: true });
- expect(safeRequestMock).toHaveBeenCalledTimes(1);
- expect(httpRequestMock).not.toHaveBeenCalled();
- expect(withGatewayV2ProxyMock).not.toHaveBeenCalled();
-
- const opts = safeRequestMock.mock.calls[0][0];
- expect(opts.rejectUnauthorized).toBe(true);
- expect(opts.ca).toEqual([CREDS.sslCertificate]);
- expect(opts.httpsAgent).toBeUndefined();
- });
-
- it("gateway v2 path routes through raw request with httpsAgent carrying ca/rejectUnauthorized", async () => {
- const v2Details = { relayHost: "relay.example", gateway: { id: "g1" }, relay: { id: "r1" } };
- const getPlatformConnectionDetailsByGatewayId = vi.fn(async () => v2Details);
-
- await executeNetScalerOperationWithGateway(
- { gatewayId: "gw-nsc", credentials: CREDS },
- { getPlatformConnectionDetailsByGatewayId } as any,
- async (makeRequest) =>
- makeRequest<{ ok: boolean }>({
- url: `https://${CREDS.hostname}:${CREDS.port}/nitro/v1/config/login`,
- method: "POST",
- data: { login: {} }
- })
- );
-
- expect(safeRequestMock).not.toHaveBeenCalled();
- expect(withGatewayV2ProxyMock).toHaveBeenCalledTimes(1);
- expect(httpRequestMock).toHaveBeenCalledTimes(1);
-
- const call = httpRequestMock.mock.calls[0][0];
- expect(String(call.url)).toContain("localhost:5678");
- expect(call.headers.Host).toBe(CREDS.hostname);
- expect(call.httpsAgent).toBeDefined();
- expect(call.rejectUnauthorized).toBeUndefined();
- expect(call.ca).toBeUndefined();
- });
-
- it("throws when a gateway is set but v2 details are not resolvable", async () => {
- const getPlatformConnectionDetailsByGatewayId = vi.fn(async () => null);
-
- await expect(
- executeNetScalerOperationWithGateway(
- { gatewayId: "gw-nsc", credentials: CREDS },
- { getPlatformConnectionDetailsByGatewayId } as any,
- async (makeRequest) => makeRequest<{ ok: boolean }>({ url: "https://x", method: "GET" })
- )
- ).rejects.toThrow(/no platform connection details/i);
-
- expect(safeRequestMock).not.toHaveBeenCalled();
- expect(httpRequestMock).not.toHaveBeenCalled();
- });
-});
diff --git a/backend/src/services/app-connection/netscaler/netscaler-connection-fns.ts b/backend/src/services/app-connection/netscaler/netscaler-connection-fns.ts
index 2e71bc745d..54a5c4ee3e 100644
--- a/backend/src/services/app-connection/netscaler/netscaler-connection-fns.ts
+++ b/backend/src/services/app-connection/netscaler/netscaler-connection-fns.ts
@@ -7,13 +7,21 @@ import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
import { GatewayProxyProtocol } from "@app/lib/gateway";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
-import { safeRequest } from "@app/lib/validator";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import { NetScalerConnectionMethod } from "./netscaler-connection-enums";
import { TNetScalerConnectionConfig } from "./netscaler-connection-types";
-export type TNetScalerRequestConfig = AxiosRequestConfig & { url: string };
+export const createNetScalerHttpsAgent = (credentials: {
+ sslRejectUnauthorized?: boolean;
+ sslCertificate?: string;
+}): https.Agent => {
+ return new https.Agent({
+ rejectUnauthorized: credentials.sslRejectUnauthorized,
+ ca: credentials.sslCertificate ? [credentials.sslCertificate] : undefined
+ });
+};
export const getNetScalerConnectionListItem = () => {
return {
@@ -26,13 +34,15 @@ export const getNetScalerConnectionListItem = () => {
const requestWithNetScalerGateway = async <T>(
config: TNetScalerConnectionConfig,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
- requestConfig: TNetScalerRequestConfig
+ requestConfig: AxiosRequestConfig
): Promise<T> => {
const { gatewayId, credentials } = config;
const { hostname, port: credPort } = credentials;
const port = credPort ?? 443;
if (gatewayId && gatewayV2Service) {
+ await blockLocalAndPrivateIpAddresses(`https://${hostname}`, true);
+
const platformConnectionDetails = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({
gatewayId,
targetHost: hostname,
@@ -54,7 +64,7 @@ const requestWithNetScalerGateway = async <T>(
const proxyUrl = `https://localhost:${proxyPort}`;
const finalRequestConfig: AxiosRequestConfig = {
...requestConfig,
- url: requestConfig.url.replace(`https://${hostname}:${port}`, proxyUrl),
+ url: requestConfig.url?.replace(`https://${hostname}:${port}`, proxyUrl),
headers: {
...requestConfig.headers,
Host: hostname
@@ -74,10 +84,12 @@ const requestWithNetScalerGateway = async <T>(
);
}
- const resp = await safeRequest.request<T>({
+ await blockLocalAndPrivateIpAddresses(`https://${hostname}`, false);
+
+ const httpsAgent = createNetScalerHttpsAgent(credentials);
+ const resp = await request.request<T>({
...requestConfig,
- rejectUnauthorized: credentials.sslRejectUnauthorized,
- ca: credentials.sslCertificate ? [credentials.sslCertificate] : undefined
+ httpsAgent
});
return resp.data;
};
@@ -142,13 +154,15 @@ export const executeNetScalerOperationWithGateway = async <T>(
credentials: TNetScalerConnectionConfig["credentials"];
},
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId"> | undefined,
- operation: (makeRequest: <R>(requestCfg: TNetScalerRequestConfig) => Promise<R>) => Promise<T>
+ operation: (makeRequest: <R>(requestCfg: AxiosRequestConfig) => Promise<R>) => Promise<T>
): Promise<T> => {
const { gatewayId, credentials } = config;
const { hostname, port: credPort } = credentials;
const port = credPort ?? 443;
if (gatewayId && gatewayV2Service) {
+ await blockLocalAndPrivateIpAddresses(`https://${hostname}`, true);
+
const platformConnectionDetails = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({
gatewayId,
targetHost: hostname,
@@ -170,10 +184,10 @@ export const executeNetScalerOperationWithGateway = async <T>(
const proxyBaseUrl = `https://localhost:${proxyPort}`;
const targetBaseUrl = `https://${hostname}:${port}`;
- const makeRequest = async <R>(requestCfg: TNetScalerRequestConfig): Promise<R> => {
+ const makeRequest = async <R>(requestCfg: AxiosRequestConfig): Promise<R> => {
const resp = await request.request<R>({
...requestCfg,
- url: requestCfg.url.replace(targetBaseUrl, proxyBaseUrl),
+ url: requestCfg.url?.replace(targetBaseUrl, proxyBaseUrl),
headers: {
...requestCfg.headers,
Host: hostname
@@ -194,11 +208,14 @@ export const executeNetScalerOperationWithGateway = async <T>(
);
}
- const makeRequest = async <R>(requestCfg: TNetScalerRequestConfig): Promise<R> => {
- const resp = await safeRequest.request<R>({
+ await blockLocalAndPrivateIpAddresses(`https://${hostname}`, false);
+
+ const httpsAgent = createNetScalerHttpsAgent(credentials);
+
+ const makeRequest = async <R>(requestCfg: AxiosRequestConfig): Promise<R> => {
+ const resp = await request.request<R>({
...requestCfg,
- rejectUnauthorized: credentials.sslRejectUnauthorized,
- ca: credentials.sslCertificate ? [credentials.sslCertificate] : undefined
+ httpsAgent
});
return resp.data;
};
diff --git a/backend/src/services/app-connection/octopus-deploy/octopus-deploy-connection-fns.ts b/backend/src/services/app-connection/octopus-deploy/octopus-deploy-connection-fns.ts
index 5a76025743..c4f328c5fe 100644
--- a/backend/src/services/app-connection/octopus-deploy/octopus-deploy-connection-fns.ts
+++ b/backend/src/services/app-connection/octopus-deploy/octopus-deploy-connection-fns.ts
@@ -1,8 +1,9 @@
import { AxiosError } from "axios";
+import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
import { removeTrailingSlash } from "@app/lib/fn";
-import { safeRequest } from "@app/lib/validator";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { AppConnection } from "../app-connection-enums";
import { OctopusDeployConnectionMethod } from "./octopus-deploy-connection-enums";
@@ -17,8 +18,12 @@ import {
TOctopusDeploySpaceResponse
} from "./octopus-deploy-connection-types";
-export const getOctopusDeployInstanceUrl = (config: TOctopusDeployConnectionConfig) => {
- return removeTrailingSlash(config.credentials.instanceUrl);
+export const getOctopusDeployInstanceUrl = async (config: TOctopusDeployConnectionConfig) => {
+ const instanceUrl = removeTrailingSlash(config.credentials.instanceUrl);
+
+ await blockLocalAndPrivateIpAddresses(instanceUrl);
+
+ return instanceUrl;
};
export const getOctopusDeployConnectionListItem = () => {
@@ -30,10 +35,10 @@ export const getOctopusDeployConnectionListItem = () => {
};
export const validateOctopusDeployConnectionCredentials = async (config: TOctopusDeployConnectionConfig) => {
- const instanceUrl = getOctopusDeployInstanceUrl(config);
+ const instanceUrl = await getOctopusDeployInstanceUrl(config);
const { apiKey } = config.credentials;
try {
- await safeRequest.get(`${instanceUrl}/api/users/me`, {
+ await request.get(`${instanceUrl}/api/users/me`, {
headers: {
"X-Octopus-ApiKey": apiKey,
"X-NuGet-ApiKey": apiKey,
@@ -58,11 +63,11 @@ export const validateOctopusDeployConnectionCredentials = async (config: TOctopu
export const getOctopusDeploySpaces = async (
appConnection: TOctopusDeployConnection
): Promise<TOctopusDeploySpace[]> => {
- const instanceUrl = getOctopusDeployInstanceUrl(appConnection);
+ const instanceUrl = await getOctopusDeployInstanceUrl(appConnection);
const { apiKey } = appConnection.credentials;
try {
- const { data } = await safeRequest.get<TOctopusDeploySpaceResponse[]>(`${instanceUrl}/api/spaces/all`, {
+ const { data } = await request.get<TOctopusDeploySpaceResponse[]>(`${instanceUrl}/api/spaces/all`, {
headers: {
"X-Octopus-ApiKey": apiKey,
"X-NuGet-ApiKey": apiKey,
@@ -97,20 +102,17 @@ export const getOctopusDeployProjects = async (
appConnection: TOctopusDeployConnection,
spaceId: string
): Promise<TOctopusDeployProject[]> => {
- const instanceUrl = getOctopusDeployInstanceUrl(appConnection);
+ const instanceUrl = await getOctopusDeployInstanceUrl(appConnection);
const { apiKey } = appConnection.credentials;
try {
- const { data } = await safeRequest.get<TOctopusDeployProjectResponse[]>(
- `${instanceUrl}/api/${spaceId}/projects/all`,
- {
- headers: {
- "X-Octopus-ApiKey": apiKey,
- "X-NuGet-ApiKey": apiKey,
- Accept: "application/json"
- }
+ const { data } = await request.get<TOctopusDeployProjectResponse[]>(`${instanceUrl}/api/${spaceId}/projects/all`, {
+ headers: {
+ "X-Octopus-ApiKey": apiKey,
+ "X-NuGet-ApiKey": apiKey,
+ Accept: "application/json"
}
- );
+ });
return data.map((project) => ({
id: project.Id,
@@ -139,11 +141,11 @@ export const getOctopusDeployScopeValues = async (
spaceId: string,
projectId: string
): Promise<TOctopusDeployScopeValues> => {
- const instanceUrl = getOctopusDeployInstanceUrl(appConnection);
+ const instanceUrl = await getOctopusDeployInstanceUrl(appConnection);
const { apiKey } = appConnection.credentials;
try {
- const { data } = await safeRequest.get<TOctopusDeployScopeValuesResponse>(
+ const { data } = await request.get<TOctopusDeployScopeValuesResponse>(
`${instanceUrl}/api/${spaceId}/projects/${projectId}/variables`,
{
headers: {
diff --git a/backend/src/services/app-connection/okta/okta-connection-fns.ts b/backend/src/services/app-connection/okta/okta-connection-fns.ts
index aeddfcd79e..a48eebbb89 100644
--- a/backend/src/services/app-connection/okta/okta-connection-fns.ts
+++ b/backend/src/services/app-connection/okta/okta-connection-fns.ts
@@ -1,6 +1,7 @@
+import { request } from "@app/lib/config/request";
import { UnauthorizedError } from "@app/lib/errors";
import { removeTrailingSlash } from "@app/lib/fn";
-import { safeRequest } from "@app/lib/validator";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import { OktaConnectionMethod } from "./okta-connection-enums";
@@ -14,16 +15,18 @@ export const getOktaConnectionListItem = () => {
};
};
-export const getOktaInstanceUrl = (config: TOktaConnectionConfig) => {
- return removeTrailingSlash(config.credentials.instanceUrl);
+export const getOktaInstanceUrl = async (config: TOktaConnectionConfig) => {
+ const instanceUrl = removeTrailingSlash(config.credentials.instanceUrl);
+ await blockLocalAndPrivateIpAddresses(instanceUrl);
+ return instanceUrl;
};
export const validateOktaConnectionCredentials = async (config: TOktaConnectionConfig) => {
const { apiToken } = config.credentials;
- const instanceUrl = getOktaInstanceUrl(config);
+ const instanceUrl = await getOktaInstanceUrl(config);
try {
- await safeRequest.get(`${instanceUrl}/api/v1/users/me`, {
+ await request.get(`${instanceUrl}/api/v1/users/me`, {
headers: {
Accept: "application/json",
Authorization: `SSWS ${apiToken}`
@@ -41,9 +44,9 @@ export const validateOktaConnectionCredentials = async (config: TOktaConnectionC
export const listOktaApps = async (appConnection: TOktaConnection) => {
const { apiToken } = appConnection.credentials;
- const instanceUrl = getOktaInstanceUrl(appConnection);
+ const instanceUrl = await getOktaInstanceUrl(appConnection);
- const { data } = await safeRequest.get<TOktaApp[]>(`${instanceUrl}/api/v1/apps`, {
+ const { data } = await request.get<TOktaApp[]>(`${instanceUrl}/api/v1/apps`, {
headers: {
Accept: "application/json",
Authorization: `SSWS ${apiToken}`
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.ts
index a54534f9d0..3aae50b967 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,18 +1,23 @@
/* eslint-disable no-await-in-loop */
/* eslint-disable class-methods-use-this */
-import { AxiosRequestConfig, AxiosResponse, HttpStatusCode } from "axios";
+import { AxiosInstance, 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 { safeRequest } from "@app/lib/validator";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { SupabaseConnectionMethod } from "./supabase-connection-constants";
import { TSupabaseConnectionConfig, TSupabaseProject, TSupabaseSecret } from "./supabase-connection-types";
-export const getSupabaseInstanceUrl = (config: TSupabaseConnectionConfig): string => {
- return config.credentials.instanceUrl
+export const getSupabaseInstanceUrl = async (config: TSupabaseConnectionConfig) => {
+ const instanceUrl = config.credentials.instanceUrl
? removeTrailingSlash(config.credentials.instanceUrl)
: "https://api.supabase.com";
+
+ await blockLocalAndPrivateIpAddresses(instanceUrl);
+
+ return instanceUrl;
};
export function getSupabaseAuthHeaders(connection: TSupabaseConnectionConfig): Record<string, string> {
@@ -43,25 +48,26 @@ export function getSupabaseRatelimiter(response: AxiosResponse): {
}
class SupabasePublicClient {
- // 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.
+ private client: AxiosInstance;
+
+ constructor() {
+ this.client = createRequestClient({
+ headers: {
+ "Content-Type": "application/json"
+ }
+ });
+ }
+
async send<T>(
connection: TSupabaseConnectionConfig,
config: AxiosRequestConfig,
retryAttempt = 0
): Promise<T | undefined> {
- const response = await safeRequest.request<T>({
+ const response = await this.client.request<T>({
...config,
- baseURL: getSupabaseInstanceUrl(connection),
- url: config.url ?? "",
+ baseURL: await getSupabaseInstanceUrl(connection),
validateStatus: (status) => (status >= 200 && status < 300) || status === HttpStatusCode.TooManyRequests,
- headers: {
- "Content-Type": "application/json",
- ...config.headers,
- ...getSupabaseAuthHeaders(connection)
- }
+ headers: getSupabaseAuthHeaders(connection)
});
const limiter = getSupabaseRatelimiter(response);
diff --git a/backend/src/services/app-connection/teamcity/teamcity-connection-fns.ts b/backend/src/services/app-connection/teamcity/teamcity-connection-fns.ts
index bbb00655a1..645be988f7 100644
--- a/backend/src/services/app-connection/teamcity/teamcity-connection-fns.ts
+++ b/backend/src/services/app-connection/teamcity/teamcity-connection-fns.ts
@@ -1,8 +1,9 @@
import { AxiosError } from "axios";
+import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
import { removeTrailingSlash } from "@app/lib/fn";
-import { safeRequest } from "@app/lib/validator";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import { TeamCityConnectionMethod } from "./teamcity-connection-enums";
@@ -12,8 +13,12 @@ import {
TTeamCityListProjectsResponse
} from "./teamcity-connection-types";
-export const getTeamCityInstanceUrl = (config: TTeamCityConnectionConfig) => {
- return removeTrailingSlash(config.credentials.instanceUrl);
+export const getTeamCityInstanceUrl = async (config: TTeamCityConnectionConfig) => {
+ const instanceUrl = removeTrailingSlash(config.credentials.instanceUrl);
+
+ await blockLocalAndPrivateIpAddresses(instanceUrl);
+
+ return instanceUrl;
};
export const getTeamCityConnectionListItem = () => {
@@ -25,12 +30,12 @@ export const getTeamCityConnectionListItem = () => {
};
export const validateTeamCityConnectionCredentials = async (config: TTeamCityConnectionConfig) => {
- const instanceUrl = getTeamCityInstanceUrl(config);
+ const instanceUrl = await getTeamCityInstanceUrl(config);
const { accessToken } = config.credentials;
try {
- await safeRequest.get(`${instanceUrl}/app/rest/server`, {
+ await request.get(`${instanceUrl}/app/rest/server`, {
headers: {
Authorization: `Bearer ${accessToken}`,
Accept: "application/json"
@@ -51,10 +56,10 @@ export const validateTeamCityConnectionCredentials = async (config: TTeamCityCon
};
export const listTeamCityProjects = async (appConnection: TTeamCityConnection) => {
- const instanceUrl = getTeamCityInstanceUrl(appConnection);
+ const instanceUrl = await getTeamCityInstanceUrl(appConnection);
const { accessToken } = appConnection.credentials;
- const resp = await safeRequest.get<TTeamCityListProjectsResponse>(
+ const resp = await request.get<TTeamCityListProjectsResponse>(
`${instanceUrl}/app/rest/projects?fields=project(id,name,buildTypes(buildType(id,name)))`,
{
headers: {
diff --git a/backend/src/services/app-connection/venafi-tpp/venafi-tpp-connection-fns.test.ts b/backend/src/services/app-connection/venafi-tpp/venafi-tpp-connection-fns.test.ts
deleted file mode 100644
index 6deeedc09e..0000000000
--- a/backend/src/services/app-connection/venafi-tpp/venafi-tpp-connection-fns.test.ts
+++ /dev/null
@@ -1,123 +0,0 @@
-/* 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 { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-import { requestWithVenafiTppGateway } from "./venafi-tpp-connection-fns";
-
-// Asserts the "requestWithVenafiTppGateway" wrapper:
-// - direct (no gatewayId) -> safeRequest.request
-// - gateway v2 -> raw request via withGatewayV2Proxy
-// - no v2 gateway details available -> throws (v1 not supported)
-
-const { safeRequestMock, httpRequestMock, withGatewayV2ProxyMock, verifyHostInputValidityMock } = vi.hoisted(() => ({
- safeRequestMock:
- vi.fn<(...args: any[]) => Promise<{ data: unknown; status: number; headers: Record<string, unknown> }>>(),
- httpRequestMock:
- vi.fn<(...args: any[]) => Promise<{ data: unknown; status: number; headers: Record<string, unknown> }>>(),
- withGatewayV2ProxyMock: vi.fn(async (...args: any[]) => {
- const cb = args[0] as (port: number) => Promise<unknown>;
- return cb(5678);
- }),
- verifyHostInputValidityMock: vi.fn(async ({ host }: { host: string }) => [host] as string[])
-}));
-
-vi.mock("@app/lib/validator/validate-url", () => ({
- safeRequest: { request: (...args: unknown[]) => safeRequestMock(...args) }
-}));
-
-vi.mock("@app/lib/config/request", () => ({
- request: { request: (...args: unknown[]) => httpRequestMock(...args) },
- createRequestClient: () => ({
- interceptors: { request: { use: vi.fn() }, response: { use: vi.fn() } },
- request: (...args: unknown[]) => httpRequestMock(...args),
- get: vi.fn(),
- post: vi.fn(),
- delete: vi.fn()
- }),
- axiosResponseInterceptor: (r: unknown) => r
-}));
-
-vi.mock("@app/lib/gateway", () => ({
- GatewayProxyProtocol: { Tcp: "tcp", Http: "http" }
-}));
-
-vi.mock("@app/lib/gateway-v2/gateway-v2", () => ({
- withGatewayV2Proxy: (cb: (port: number) => Promise<unknown>, options: unknown) => withGatewayV2ProxyMock(cb, options)
-}));
-
-vi.mock("@app/ee/services/dynamic-secret/dynamic-secret-fns", () => ({
- verifyHostInputValidity: verifyHostInputValidityMock
-}));
-
-vi.mock("@app/lib/config/env", () => ({ getConfig: () => ({ isDevelopmentMode: false }) }));
-vi.mock("@app/lib/logger", () => ({ logger: { error: vi.fn(), info: vi.fn() } }));
-
-const BASE_REQ = {
- url: "https://venafi.example.com/vedsdk/certificates",
- method: "GET" as const,
- headers: { Authorization: "Bearer x" }
-};
-
-const okAxiosResponse = { data: { ok: true }, status: 200, headers: {} };
-
-describe("requestWithVenafiTppGateway", () => {
- beforeEach(() => {
- safeRequestMock.mockReset();
- safeRequestMock.mockResolvedValue(okAxiosResponse);
- httpRequestMock.mockReset();
- httpRequestMock.mockResolvedValue(okAxiosResponse);
- withGatewayV2ProxyMock.mockClear();
- verifyHostInputValidityMock.mockClear();
- });
-
- afterEach(() => {
- vi.clearAllMocks();
- });
-
- it("routes through safeRequest when gatewayId is absent", async () => {
- await requestWithVenafiTppGateway(
- { gatewayId: null },
- { getPlatformConnectionDetailsByGatewayId: vi.fn() } as any,
- BASE_REQ
- );
-
- expect(safeRequestMock).toHaveBeenCalledTimes(1);
- expect(httpRequestMock).not.toHaveBeenCalled();
- expect(withGatewayV2ProxyMock).not.toHaveBeenCalled();
- expect(safeRequestMock.mock.calls[0][0]).toMatchObject({ url: BASE_REQ.url });
- });
-
- it("routes through gateway v2 when v2 details resolve", async () => {
- const v2Details = { relayHost: "relay.example", gateway: { id: "g1" }, relay: { id: "r1" } };
- const getPlatformConnectionDetailsByGatewayId = vi.fn(async () => v2Details);
-
- await requestWithVenafiTppGateway(
- { gatewayId: "gw-venafi" },
- { getPlatformConnectionDetailsByGatewayId } as any,
- BASE_REQ
- );
-
- expect(safeRequestMock).not.toHaveBeenCalled();
- expect(withGatewayV2ProxyMock).toHaveBeenCalledTimes(1);
- expect(httpRequestMock).toHaveBeenCalledTimes(1);
- const call = httpRequestMock.mock.calls[0][0];
- expect(String(call.url)).toContain("localhost:5678");
- expect(call.headers.Host).toBe("venafi.example.com");
- expect(call.httpsAgent).toBeDefined();
- });
-
- it("throws when a gateway is set but no v2 details are resolvable (v1 not supported)", async () => {
- const getPlatformConnectionDetailsByGatewayId = vi.fn(async () => null);
-
- await expect(
- requestWithVenafiTppGateway(
- { gatewayId: "gw-venafi" },
- { getPlatformConnectionDetailsByGatewayId } as any,
- BASE_REQ
- )
- ).rejects.toThrow(/v2 gateways/i);
-
- expect(safeRequestMock).not.toHaveBeenCalled();
- expect(httpRequestMock).not.toHaveBeenCalled();
- expect(withGatewayV2ProxyMock).not.toHaveBeenCalled();
- });
-});
diff --git a/backend/src/services/app-connection/venafi-tpp/venafi-tpp-connection-fns.ts b/backend/src/services/app-connection/venafi-tpp/venafi-tpp-connection-fns.ts
index 0745968cc0..2ffdfef1b7 100644
--- a/backend/src/services/app-connection/venafi-tpp/venafi-tpp-connection-fns.ts
+++ b/backend/src/services/app-connection/venafi-tpp/venafi-tpp-connection-fns.ts
@@ -9,14 +9,12 @@ import { BadRequestError } from "@app/lib/errors";
import { GatewayProxyProtocol } from "@app/lib/gateway";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
import { logger } from "@app/lib/logger";
-import { safeRequest } from "@app/lib/validator/validate-url";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator/validate-url";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import { VenafiTppConnectionMethod } from "./venafi-tpp-connection-enums";
import { TVenafiTppConnectionConfig } from "./venafi-tpp-connection-types";
-export type TVenafiTppGatewayRequestConfig = AxiosRequestConfig & { url: string };
-
type TVenafiTppCredentials = {
tppUrl: string;
clientId: string;
@@ -48,15 +46,15 @@ const normalizeTppUrl = (tppUrl: string): string => {
export const requestWithVenafiTppGateway = async <T>(
appConnection: { gatewayId?: string | null },
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
- requestConfig: TVenafiTppGatewayRequestConfig
+ requestConfig: AxiosRequestConfig
): Promise<AxiosResponse<T>> => {
const { gatewayId } = appConnection;
- const url = new URL(requestConfig.url);
+ const url = new URL(requestConfig.url as string);
+ await blockLocalAndPrivateIpAddresses(url.toString(), Boolean(gatewayId));
- // Non-gateway path: use safeRequest to validate and pin the connection.
if (!gatewayId) {
- return safeRequest.request<T>(requestConfig);
+ return request.request(requestConfig);
}
const [targetHost] = await verifyHostInputValidity({ host: url.hostname, isGateway: true, isDynamicSecret: false });
diff --git a/backend/src/services/app-connection/windmill/windmill-connection-fns.ts b/backend/src/services/app-connection/windmill/windmill-connection-fns.ts
index f24ebe27c2..8e478f8bba 100644
--- a/backend/src/services/app-connection/windmill/windmill-connection-fns.ts
+++ b/backend/src/services/app-connection/windmill/windmill-connection-fns.ts
@@ -1,17 +1,22 @@
import { AxiosError } from "axios";
+import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
import { removeTrailingSlash } from "@app/lib/fn";
-import { safeRequest } from "@app/lib/validator";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import { WindmillConnectionMethod } from "./windmill-connection-enums";
import { TWindmillConnection, TWindmillConnectionConfig, TWindmillWorkspace } from "./windmill-connection-types";
-export const getWindmillInstanceUrl = (config: TWindmillConnectionConfig) => {
- return config.credentials.instanceUrl
+export const getWindmillInstanceUrl = async (config: TWindmillConnectionConfig) => {
+ const instanceUrl = config.credentials.instanceUrl
? removeTrailingSlash(config.credentials.instanceUrl)
: "https://app.windmill.dev";
+
+ await blockLocalAndPrivateIpAddresses(instanceUrl);
+
+ return instanceUrl;
};
export const getWindmillConnectionListItem = () => {
@@ -23,11 +28,11 @@ export const getWindmillConnectionListItem = () => {
};
export const validateWindmillConnectionCredentials = async (config: TWindmillConnectionConfig) => {
- const instanceUrl = getWindmillInstanceUrl(config);
+ const instanceUrl = await getWindmillInstanceUrl(config);
const { accessToken } = config.credentials;
try {
- await safeRequest.get(`${instanceUrl}/api/workspaces/list`, {
+ await request.get(`${instanceUrl}/api/workspaces/list`, {
headers: {
Authorization: `Bearer ${accessToken}`
}
@@ -47,10 +52,10 @@ export const validateWindmillConnectionCredentials = async (config: TWindmillCon
};
export const listWindmillWorkspaces = async (appConnection: TWindmillConnection) => {
- const instanceUrl = getWindmillInstanceUrl(appConnection);
+ const instanceUrl = await getWindmillInstanceUrl(appConnection);
const { accessToken } = appConnection.credentials;
- const resp = await safeRequest.get<TWindmillWorkspace[]>(`${instanceUrl}/api/workspaces/list`, {
+ const resp = await request.get<TWindmillWorkspace[]>(`${instanceUrl}/api/workspaces/list`, {
headers: {
Authorization: `Bearer ${accessToken}`
}
diff --git a/backend/src/services/app-connection/zabbix/zabbix-connection-fns.ts b/backend/src/services/app-connection/zabbix/zabbix-connection-fns.ts
index a243a6bf32..a34a6c3815 100644
--- a/backend/src/services/app-connection/zabbix/zabbix-connection-fns.ts
+++ b/backend/src/services/app-connection/zabbix/zabbix-connection-fns.ts
@@ -1,8 +1,9 @@
import { AxiosError } from "axios";
import RE2 from "re2";
+import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
-import { safeRequest } from "@app/lib/validator";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import { ZabbixConnectionMethod } from "./zabbix-connection-enums";
@@ -25,6 +26,7 @@ export const getZabbixConnectionListItem = () => {
export const validateZabbixConnectionCredentials = async (config: TZabbixConnectionConfig) => {
const { apiToken, instanceUrl } = config.credentials;
+ await blockLocalAndPrivateIpAddresses(instanceUrl);
try {
const apiUrl = `${instanceUrl.replace(TRAILING_SLASH_REGEX, "")}/api_jsonrpc.php`;
@@ -38,16 +40,12 @@ export const validateZabbixConnectionCredentials = async (config: TZabbixConnect
id: 1
};
- const response: { data: { error?: { message: string }; result?: string } } = await safeRequest.post(
- apiUrl,
- payload,
- {
- headers: {
- "Content-Type": "application/json",
- Authorization: `Bearer ${apiToken}`
- }
+ const response: { data: { error?: { message: string }; result?: string } } = await request.post(apiUrl, payload, {
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${apiToken}`
}
- );
+ });
if (response.data.error) {
throw new BadRequestError({
@@ -68,6 +66,7 @@ export const validateZabbixConnectionCredentials = async (config: TZabbixConnect
export const listZabbixHosts = async (appConnection: TZabbixConnection): Promise<TZabbixHost[]> => {
const { apiToken, instanceUrl } = appConnection.credentials;
+ await blockLocalAndPrivateIpAddresses(instanceUrl);
try {
const apiUrl = `${instanceUrl.replace(TRAILING_SLASH_REGEX, "")}/api_jsonrpc.php`;
@@ -83,7 +82,7 @@ export const listZabbixHosts = async (appConnection: TZabbixConnection): Promise
id: 1
};
- const response: { data: TZabbixHostListResponse } = await safeRequest.post(apiUrl, payload, {
+ const response: { data: TZabbixHostListResponse } = await request.post(apiUrl, payload, {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiToken}`
diff --git a/backend/src/services/external-migration/external-migration-fns/vault.ts b/backend/src/services/external-migration/external-migration-fns/vault.ts
index a9da5610c5..6e32be9075 100644
--- a/backend/src/services/external-migration/external-migration-fns/vault.ts
+++ b/backend/src/services/external-migration/external-migration-fns/vault.ts
@@ -1,4 +1,3 @@
-import http from "node:http";
import https from "node:https";
import axios, { AxiosInstance, isAxiosError } from "axios";
@@ -10,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, buildSsrfSafeAgent } from "@app/lib/validator";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { InfisicalImportData, KvVersion, VaultMappingType } from "../external-migration-types";
@@ -32,12 +31,7 @@ const vaultFactory = (
targetHostname: string;
targetPort: number;
},
- gatewayCallback: (
- host: string,
- port: number,
- agents?: { httpsAgent?: https.Agent; httpAgent?: http.Agent },
- hostHeader?: string
- ) => Promise<T>
+ gatewayCallback: (host: string, port: number, httpsAgent?: https.Agent, hostHeader?: string) => Promise<T>
): Promise<T> => {
const { gatewayId, targetProtocol, targetHostname, targetPort } = inputs;
@@ -52,7 +46,7 @@ const vaultFactory = (
const httpsAgent = isHttps ? new https.Agent({ servername: targetHostname }) : undefined;
return withGatewayV2Proxy(
- async (port) => gatewayCallback(`${targetProtocol}://localhost`, port, { httpsAgent }, targetHostname),
+ async (port) => gatewayCallback(`${targetProtocol}://localhost`, port, httpsAgent, targetHostname),
{
protocol: GatewayProxyProtocol.Tcp,
relayHost: gatewayV2Details.relayHost,
@@ -64,7 +58,7 @@ const vaultFactory = (
const relayDetails = await gatewayService.fnGetGatewayClientTlsByGatewayId(gatewayId);
- return withGatewayProxy(async (port, httpsAgent) => gatewayCallback("http://localhost", port, { httpsAgent }), {
+ return withGatewayProxy(async (port, httpsAgent) => gatewayCallback("http://localhost", port, httpsAgent), {
protocol: GatewayProxyProtocol.Http,
targetHost: `${targetProtocol}://${targetHostname}`,
targetPort,
@@ -235,12 +229,7 @@ const vaultFactory = (
accessToken: string;
gatewayId?: string;
}): Promise<VaultData[]> {
- const getData = async (
- host: string,
- port?: number,
- agents?: { httpsAgent?: https.Agent; httpAgent?: http.Agent },
- hostHeader?: string
- ) => {
+ const getData = async (host: string, port?: number, httpsAgent?: https.Agent, hostHeader?: string) => {
const allData: VaultData[] = [];
const request = axios.create({
@@ -251,8 +240,7 @@ const vaultFactory = (
...(hostHeader ? { Host: hostHeader } : {})
},
maxRedirects: 0,
- httpsAgent: agents?.httpsAgent,
- httpAgent: agents?.httpAgent
+ httpsAgent
});
// Get all mounts in this namespace
@@ -321,12 +309,8 @@ const vaultFactory = (
getData
);
} else {
- const pinnedAgent = await buildSsrfSafeAgent(baseUrl, { rejectUnauthorized: true });
- const isHttps = new URL(baseUrl).protocol === "https:";
- const agents = isHttps
- ? { httpsAgent: pinnedAgent as https.Agent | undefined }
- : { httpAgent: pinnedAgent as http.Agent | undefined };
- data = await getData(baseUrl, undefined, agents);
+ await blockLocalAndPrivateIpAddresses(baseUrl);
+ data = await getData(baseUrl);
}
return data;
diff --git a/backend/src/services/external-migration/external-migration-service.ts b/backend/src/services/external-migration/external-migration-service.ts
index c63c9683d8..11084e992b 100644
--- a/backend/src/services/external-migration/external-migration-service.ts
+++ b/backend/src/services/external-migration/external-migration-service.ts
@@ -100,7 +100,7 @@ export const externalMigrationServiceFactory = ({
let gatewayDetails: TGatewayDetails | undefined;
if (connection.gatewayId) {
- const instanceUrl = getHCVaultInstanceUrl(connection);
+ const instanceUrl = await getHCVaultInstanceUrl(connection);
const url = new URL(instanceUrl);
const [targetHost] = await verifyHostInputValidity({
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.ts
index fb55cd7e80..60b014bb94 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,5 +1,6 @@
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";
@@ -33,7 +34,7 @@ import { RequestContextKey } from "@app/lib/request-context/request-context-keys
import { 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, buildSsrfSafeAgent } from "@app/lib/validator";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { ActorType } from "../auth/auth-type";
import { TIdentityDALFactory } from "../identity/identity-dal";
@@ -128,26 +129,26 @@ export const identityJwtAuthServiceFactory = ({
let tokenData: Record<string, string | boolean | number> = {};
if (identityJwtAuth.configurationType === JwtConfigurationType.JWKS) {
- // 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;
+ await blockLocalAndPrivateIpAddresses(identityJwtAuth.jwksUrl);
+
+ let client: JwksClient;
if (identityJwtAuth.jwksUrl.includes("https:")) {
- decryptedJwksCaCert = orgDataKeyDecryptor({
+ const decryptedJwksCaCert = orgDataKeyDecryptor({
cipherTextBlob: identityJwtAuth.encryptedJwksCaCert
}).toString();
- }
-
- const jwksRequestAgent = await buildSsrfSafeAgent(identityJwtAuth.jwksUrl, {
- ca: decryptedJwksCaCert || undefined,
- rejectUnauthorized: true
- });
- const client = new JwksClient({
- jwksUri: identityJwtAuth.jwksUrl,
- requestAgent: jwksRequestAgent
- });
+ 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 { 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.test.ts b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.test.ts
deleted file mode 100644
index 69db5b6d31..0000000000
--- a/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.test.ts
+++ /dev/null
@@ -1,189 +0,0 @@
-/* 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 { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-import { identityKubernetesAuthServiceFactory } from "./identity-kubernetes-auth-service";
-import { IdentityKubernetesAuthTokenReviewMode } from "./identity-kubernetes-auth-types";
-
-// Asserts the interaction of $resolveEffectiveVerifyTlsCertificate with
-// safeRequest.post in the "raw" token-review path:
-// - the resolved boolean flows into the flat `rejectUnauthorized` option
-// - ca is passed as a flat string, not wrapped in a pre-built https.Agent
-// - caCert === "" always forces rejectUnauthorized=false, regardless of
-// the stored verifyTlsCertificate flag
-//
-// We drive the factory's login() far enough to hit safeRequest.post and
-// then have the mock throw so we can inspect the captured call options.
-
-const { safePostMock, rawPostMock } = vi.hoisted(() => ({
- safePostMock: vi.fn(),
- rawPostMock: vi.fn()
-}));
-
-vi.mock("@app/lib/validator", () => ({
- safeRequest: { post: (...args: unknown[]) => safePostMock(...args) }
-}));
-
-vi.mock("@app/lib/config/request", () => ({
- request: { post: (...args: unknown[]) => rawPostMock(...args) },
- createRequestClient: () => ({
- interceptors: { request: { use: vi.fn() }, response: { use: vi.fn() } },
- request: vi.fn(),
- get: vi.fn(),
- post: vi.fn(),
- delete: vi.fn()
- }),
- axiosResponseInterceptor: (r: unknown) => r
-}));
-
-vi.mock("@app/lib/config/env", () => ({
- getConfig: () => ({ OTEL_TELEMETRY_COLLECTION_ENABLED: false, isDevelopmentMode: false })
-}));
-vi.mock("@app/lib/logger", () => ({ logger: { error: vi.fn(), info: vi.fn(), warn: vi.fn() } }));
-
-vi.mock("@app/lib/request-context/request-memoizer", () => ({
- requestMemoize: async <T>(_k: string, fetcher: () => Promise<T>) => fetcher()
-}));
-
-// Mock the gateway modules to avoid loading @infisical/quic native bindings.
-vi.mock("@app/lib/gateway", () => ({
- GatewayProxyProtocol: { Tcp: "tcp", Http: "http" },
- GatewayHttpProxyActions: { UseGatewayK8sServiceAccount: "use-gateway-k8s-sa" },
- withGatewayProxy: vi.fn()
-}));
-vi.mock("@app/lib/gateway/types", () => ({
- GatewayProxyProtocol: { Tcp: "tcp", Http: "http" },
- GatewayHttpProxyActions: { UseGatewayK8sServiceAccount: "use-gateway-k8s-sa" },
- GatewayVersion: { V1: "v1", V2: "v2" }
-}));
-vi.mock("@app/lib/gateway-v2/gateway-v2", () => ({
- withGatewayV2Proxy: vi.fn()
-}));
-
-vi.mock("@app/lib/request-context/memo-keys", () => ({
- requestMemoKeys: { identityFindById: (id: string) => `id:${id}`, orgFindById: (id: string) => `org:${id}` }
-}));
-
-vi.mock("@app/lib/request-context/request-context-keys", () => ({
- RequestContextKey: { Ip: "ip", UserAgent: "ua", Memoizer: "mem" }
-}));
-
-// Required to avoid loading the real fastify request context wrapper
-vi.mock("@fastify/request-context", () => ({ requestContext: { get: () => undefined } }));
-
-vi.mock("@app/lib/telemetry/metrics", () => ({
- authAttemptCounter: { add: vi.fn() },
- AuthAttemptAuthMethod: { KUBERNETES_AUTH: "kubernetes-auth" },
- AuthAttemptAuthResult: { FAILURE: "failure", SUCCESS: "success" }
-}));
-
-type KubernetesAuthRecord = Record<string, unknown>;
-
-const buildService = (kubernetesAuthRecord: KubernetesAuthRecord, caCertPlainText: string) => {
- const decryptor = vi.fn(({ cipherTextBlob }: { cipherTextBlob: Buffer | null }) =>
- Buffer.from(cipherTextBlob ? caCertPlainText : "")
- );
-
- return identityKubernetesAuthServiceFactory({
- identityDAL: { findById: vi.fn(async () => ({ id: "i-1", orgId: "o-1", name: "test-identity" })) } as any,
- identityKubernetesAuthDAL: {
- findOne: vi.fn(async () => kubernetesAuthRecord),
- create: vi.fn(),
- transaction: vi.fn(),
- updateById: vi.fn(),
- delete: vi.fn()
- } as any,
- identityAccessTokenDAL: { create: vi.fn(), delete: vi.fn() } as any,
- membershipIdentityDAL: { findOne: vi.fn(), update: vi.fn(), getIdentityById: vi.fn() } as any,
- permissionService: { getOrgPermission: vi.fn(), getProjectPermission: vi.fn() } as any,
- licenseService: { getPlan: vi.fn() } as any,
- kmsService: {
- createCipherPairWithDataKey: vi.fn(async () => ({ decryptor, encryptor: vi.fn() }))
- } as any,
- gatewayService: {} as any,
- gatewayV2Service: {} as any,
- gatewayDAL: { find: vi.fn() } as any,
- gatewayV2DAL: { find: vi.fn() } as any,
- gatewayPoolService: { getPlatformConnectionDetailsByPoolId: vi.fn(), pickRandomHealthyGateway: vi.fn() } as any,
- gatewayPoolDAL: { findById: vi.fn() } as any,
- orgDAL: {
- findById: vi.fn(async () => ({ id: "o-1", name: "test-org", rootOrgId: null })),
- findOne: vi.fn(),
- findEffectiveOrgMembership: vi.fn()
- } as any,
- identityAccessTokenService: { issueIdentityAccessToken: vi.fn(), revokeAllTokensForIdentity: vi.fn() } as any
- });
-};
-
-const BASE_AUTH_RECORD = {
- identityId: "i-1",
- kubernetesHost: "https://k8s.example.com:6443",
- tokenReviewMode: IdentityKubernetesAuthTokenReviewMode.Api,
- gatewayId: null,
- gatewayV2Id: null,
- gatewayPoolId: null,
- allowedAudience: null,
- allowedNamespaces: null,
- allowedNames: null,
- encryptedKubernetesTokenReviewerJwt: Buffer.from("ciphertext"),
- encryptedKubernetesCaCertificate: Buffer.from("ciphertext")
-};
-
-describe("identityKubernetesAuthService — $resolveEffectiveVerifyTlsCertificate → safeRequest", () => {
- beforeEach(() => {
- safePostMock.mockReset();
- // Throw so login() exits before the token-review result is parsed — we
- // only care about the args safeRequest.post received.
- safePostMock.mockRejectedValue(new Error("short-circuit for test"));
- rawPostMock.mockReset();
- rawPostMock.mockRejectedValue(new Error("should not be called"));
- });
-
- afterEach(() => {
- vi.clearAllMocks();
- });
-
- it("passes rejectUnauthorized=true + ca as flat options when caCert present and verify=true", async () => {
- const svc = buildService(
- { ...BASE_AUTH_RECORD, verifyTlsCertificate: true },
- "-----BEGIN CERTIFICATE-----\nREALCACERT==\n-----END CERTIFICATE-----"
- );
-
- await expect(svc.login({ identityId: "i-1", jwt: "service-account-jwt" })).rejects.toThrow();
-
- expect(safePostMock).toHaveBeenCalledTimes(1);
- expect(rawPostMock).not.toHaveBeenCalled();
-
- const [, , opts] = safePostMock.mock.calls[0];
- expect(opts.rejectUnauthorized).toBe(true);
- expect(opts.ca).toBe("-----BEGIN CERTIFICATE-----\nREALCACERT==\n-----END CERTIFICATE-----");
- expect(opts.allowPrivateIps).toBe(true);
- expect(opts.httpsAgent).toBeUndefined();
- });
-
- it("collapses rejectUnauthorized to false when caCert is empty (even if stored verify=true)", async () => {
- const svc = buildService({ ...BASE_AUTH_RECORD, verifyTlsCertificate: true }, "");
-
- await expect(svc.login({ identityId: "i-1", jwt: "service-account-jwt" })).rejects.toThrow();
-
- expect(safePostMock).toHaveBeenCalledTimes(1);
- const [, , opts] = safePostMock.mock.calls[0];
- expect(opts.rejectUnauthorized).toBe(false);
- expect(opts.ca).toBeUndefined();
- expect(opts.httpsAgent).toBeUndefined();
- });
-
- it("passes rejectUnauthorized=false when caCert present but stored verify=false", async () => {
- const svc = buildService(
- { ...BASE_AUTH_RECORD, verifyTlsCertificate: false },
- "-----BEGIN CERTIFICATE-----\nREALCACERT==\n-----END CERTIFICATE-----"
- );
-
- await expect(svc.login({ identityId: "i-1", jwt: "service-account-jwt" })).rejects.toThrow();
-
- expect(safePostMock).toHaveBeenCalledTimes(1);
- const [, , opts] = safePostMock.mock.calls[0];
- expect(opts.rejectUnauthorized).toBe(false);
- expect(opts.ca).toBe("-----BEGIN CERTIFICATE-----\nREALCACERT==\n-----END CERTIFICATE-----");
- expect(opts.httpsAgent).toBeUndefined();
- });
-});
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.ts
index f68abee76b..c09ea24412 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
@@ -48,7 +48,6 @@ import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { RequestContextKey } from "@app/lib/request-context/request-context-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics";
-import { safeRequest } from "@app/lib/validator";
import { ActorType } from "../auth/auth-type";
import { TIdentityDALFactory } from "../identity/identity-dal";
@@ -350,7 +349,7 @@ export const identityKubernetesAuthServiceFactory = ({
const baseUrl = port ? `${host}:${port}` : host;
- const res = await safeRequest
+ const res = await request
.post<TCreateTokenReviewResponse>(
`${baseUrl}/apis/authentication.k8s.io/v1/tokenreviews`,
{
@@ -370,13 +369,14 @@ export const identityKubernetesAuthServiceFactory = ({
},
signal: AbortSignal.timeout(10000),
timeout: 10000,
- allowPrivateIps: true,
- ca: caCert || undefined,
- rejectUnauthorized: $resolveEffectiveVerifyTlsCertificate(
- caCert,
- identityKubernetesAuth.verifyTlsCertificate
- ),
- servername
+ httpsAgent: new https.Agent({
+ ca: caCert || undefined,
+ rejectUnauthorized: $resolveEffectiveVerifyTlsCertificate(
+ caCert,
+ identityKubernetesAuth.verifyTlsCertificate
+ ),
+ servername
+ })
}
)
.catch((err) => {
diff --git a/backend/src/services/identity-spiffe-auth/identity-spiffe-auth-fns.ts b/backend/src/services/identity-spiffe-auth/identity-spiffe-auth-fns.ts
index 058e5bf8c9..cb0a41b628 100644
--- a/backend/src/services/identity-spiffe-auth/identity-spiffe-auth-fns.ts
+++ b/backend/src/services/identity-spiffe-auth/identity-spiffe-auth-fns.ts
@@ -1,7 +1,8 @@
+import https from "https";
import picomatch from "picomatch";
import RE2 from "re2";
-import { safeRequest } from "@app/lib/validator";
+import { request } from "@app/lib/config/request";
const SPIFFE_ID_REGEX = new RE2("^spiffe:\\/\\/([^/]+)(\\/.*)?");
@@ -30,12 +31,12 @@ const BUNDLE_FETCH_TIMEOUT_MS = 10_000;
const MAX_BUNDLE_SIZE_BYTES = 1_048_576; // 1 MB
export const fetchRemoteBundleJwks = async (url: string, caCert?: string): Promise<string> => {
- const response = await safeRequest.get<string>(url, {
+ const response = await request.get<string>(url, {
responseType: "text",
timeout: BUNDLE_FETCH_TIMEOUT_MS,
maxContentLength: MAX_BUNDLE_SIZE_BYTES,
maxBodyLength: MAX_BUNDLE_SIZE_BYTES,
- ...(caCert ? { ca: caCert } : {})
+ httpsAgent: caCert ? new https.Agent({ ca: caCert, rejectUnauthorized: true }) : undefined
});
return response.data;
diff --git a/backend/src/services/integration-auth/integration-app-list.ts b/backend/src/services/integration-auth/integration-app-list.ts
index 4977d0db81..c549d12658 100644
--- a/backend/src/services/integration-auth/integration-app-list.ts
+++ b/backend/src/services/integration-auth/integration-app-list.ts
@@ -7,7 +7,6 @@ import { TIntegrationAuths } from "@app/db/schemas";
import { getConfig } from "@app/lib/config/env";
import { request } from "@app/lib/config/request";
import { NotFoundError } from "@app/lib/errors";
-import { safeRequest } from "@app/lib/validator";
import { IntegrationAuthMetadataSchema, TIntegrationAuthMetadata } from "./integration-auth-schema";
import { Integrations, IntegrationUrls } from "./integration-list";
@@ -548,7 +547,7 @@ const getAppsCircleCI = async ({ accessToken }: { accessToken: string }) => {
const getAppsDatabricks = async ({ url, accessToken }: { url?: string | null; accessToken: string }) => {
const databricksApiUrl = `${url}/api`;
- const res = await safeRequest.get<{ scopes: { name: string; backend_type: string }[] }>(
+ const res = await request.get<{ scopes: { name: string; backend_type: string }[] }>(
`${databricksApiUrl}/2.0/secrets/scopes/list`,
{
headers: {
@@ -642,7 +641,7 @@ const getAppsGitlab = async ({
per_page: String(perPage)
});
- const { data } = await safeRequest.get<{ name: string; id: string }[]>(
+ const { data } = await request.get<{ name: string; id: string }[]>(
`${gitLabApiUrl}/v4/groups/${teamId}/projects`,
{
params,
@@ -670,7 +669,7 @@ const getAppsGitlab = async ({
// case: fetch projects for individual in GitLab
const { id } = (
- await safeRequest.get<{ id: string }>(`${gitLabApiUrl}/v4/user`, {
+ await request.get<{ id: string }>(`${gitLabApiUrl}/v4/user`, {
headers: {
Authorization: `Bearer ${accessToken}`,
"Accept-Encoding": "application/json"
@@ -684,16 +683,13 @@ const getAppsGitlab = async ({
per_page: String(perPage)
});
- const { data } = await safeRequest.get<{ name: string; id: string }[]>(
- `${gitLabApiUrl}/v4/users/${id}/projects`,
- {
- params,
- headers: {
- Authorization: `Bearer ${accessToken}`,
- "Accept-Encoding": "application/json"
- }
+ const { data } = await request.get<{ name: string; id: string }[]>(`${gitLabApiUrl}/v4/users/${id}/projects`, {
+ params,
+ headers: {
+ Authorization: `Bearer ${accessToken}`,
+ "Accept-Encoding": "application/json"
}
- );
+ });
data.forEach((a) => {
apps.push({
@@ -718,7 +714,7 @@ const getAppsGitlab = async ({
*/
const getAppsTeamCity = async ({ accessToken, url }: { url: string; accessToken: string }) => {
const res = (
- await safeRequest.get<{ project: { name: string; id: string }[] }>(`${url}/app/rest/projects`, {
+ await request.get<{ project: { name: string; id: string }[] }>(`${url}/app/rest/projects`, {
headers: {
Authorization: `Bearer ${accessToken}`,
Accept: "application/json"
@@ -848,7 +844,7 @@ const getAppsBitbucket = async ({ accessToken, workspaceSlug }: { accessToken: s
let repositoriesUrl = `${IntegrationUrls.BITBUCKET_API_URL}/2.0/repositories/${workspaceSlug}`;
while (hasNextPage) {
- const { data }: { data: RepositoriesResponse } = await safeRequest.get(repositoriesUrl, {
+ const { data }: { data: RepositoriesResponse } = await request.get(repositoriesUrl, {
headers: {
Authorization: `Bearer ${accessToken}`,
Accept: "application/json"
@@ -929,7 +925,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 safeRequest.get<{ id: string; name: string }[]>(`${apiUrl}/workspaces/list`, {
+ const { data } = await request.get<{ id: string; name: string }[]>(`${apiUrl}/workspaces/list`, {
headers: {
Authorization: `Bearer ${accessToken}`,
"Accept-Encoding": "application/json"
@@ -942,7 +938,7 @@ const getAppsWindmill = async ({ accessToken, url }: { accessToken: string; url?
const userPath = "u/user/variable";
const folderPath = "f/folder/variable";
- const { data: writeUser } = await safeRequest.post<object>(
+ const { data: writeUser } = await request.post<object>(
`${apiUrl}/w/${app.id}/variables/create`,
{
path: userPath,
@@ -958,7 +954,7 @@ const getAppsWindmill = async ({ accessToken, url }: { accessToken: string; url?
}
);
- const { data: writeFolder } = await safeRequest.post<object>(
+ const { data: writeFolder } = await request.post<object>(
`${apiUrl}/w/${app.id}/variables/create`,
{
path: folderPath,
@@ -976,14 +972,14 @@ const getAppsWindmill = async ({ accessToken, url }: { accessToken: string; url?
// is write access is allowed then delete the created secrets from workspace
if (writeUser && writeFolder) {
- await safeRequest.delete(`${apiUrl}/w/${app.id}/variables/delete/${userPath}`, {
+ await request.delete(`${apiUrl}/w/${app.id}/variables/delete/${userPath}`, {
headers: {
Authorization: `Bearer ${accessToken}`,
"Accept-Encoding": "application/json"
}
});
- await safeRequest.delete(`${apiUrl}/w/${app.id}/variables/delete/${folderPath}`, {
+ await request.delete(`${apiUrl}/w/${app.id}/variables/delete/${folderPath}`, {
headers: {
Authorization: `Bearer ${accessToken}`,
"Accept-Encoding": "application/json"
diff --git a/backend/src/services/integration-auth/integration-auth-service.ts b/backend/src/services/integration-auth/integration-auth-service.ts
index 37b54e8bd8..815fc8417f 100644
--- a/backend/src/services/integration-auth/integration-auth-service.ts
+++ b/backend/src/services/integration-auth/integration-auth-service.ts
@@ -20,7 +20,7 @@ import { BadRequestError, InternalServerError, NotFoundError } from "@app/lib/er
import { groupBy } from "@app/lib/fn";
import { logger } from "@app/lib/logger";
import { TGenericPermission, TProjectPermission } from "@app/lib/types";
-import { blockLocalAndPrivateIpAddresses, safeRequest } from "@app/lib/validator";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { TIntegrationDALFactory } from "../integration/integration-dal";
import { TKmsServiceFactory } from "../kms/kms-service";
@@ -1675,7 +1675,7 @@ export const integrationAuthServiceFactory = ({
if (appId) {
const {
data: { buildType }
- } = await safeRequest.get<{ buildType: TTeamCityBuildConfig[] }>(`${integrationAuth.url}/app/rest/buildTypes`, {
+ } = await request.get<{ buildType: TTeamCityBuildConfig[] }>(`${integrationAuth.url}/app/rest/buildTypes`, {
params: {
locator: `project:${appId}`
},
@@ -2021,7 +2021,7 @@ export const integrationAuthServiceFactory = ({
}
// SDK doesn't support variable set...
- const { data: variableSet } = await safeRequest.get<TOctopusDeployVariableSet>(url, {
+ const { data: variableSet } = await request.get<TOctopusDeployVariableSet>(url, {
headers: {
"X-NuGet-ApiKey": accessToken,
Accept: "application/json"
diff --git a/backend/src/services/integration-auth/integration-sync-secret.ts b/backend/src/services/integration-auth/integration-sync-secret.ts
index a619786d64..d5f1c778cd 100644
--- a/backend/src/services/integration-auth/integration-sync-secret.ts
+++ b/backend/src/services/integration-auth/integration-sync-secret.ts
@@ -32,6 +32,7 @@ import { AssumeRoleCommand, STSClient } from "@aws-sdk/client-sts";
import { createAppAuth } from "@octokit/auth-app";
import { Octokit } from "@octokit/rest";
import { AxiosError } from "axios";
+import https from "https";
import sodium from "libsodium-wrappers";
import isEqual from "lodash.isequal";
import RE2 from "re2";
@@ -44,7 +45,7 @@ import { request } from "@app/lib/config/request";
import { crypto } from "@app/lib/crypto/cryptography";
import { BadRequestError, InternalServerError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
-import { safeRequest } from "@app/lib/validator";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { TCreateManySecretsRawFn, TUpdateManySecretsRawFn } from "@app/services/secret/secret-types";
import { TIntegrationDALFactory } from "../integration/integration-dal";
@@ -323,19 +324,27 @@ const syncSecretsAzureAppConfig = async ({
message: "Invalid Azure App Configuration URL provided."
});
+ await blockLocalAndPrivateIpAddresses(integration.app);
+
const getCompleteAzureAppConfigValues = async (baseURL: string, url: string) => {
let result: AzureAppConfigKeyValue[] = [];
while (url) {
- const res = await safeRequest.get<{ items: AzureAppConfigKeyValue[]; ["@nextLink"]: string }>(url, {
+ const res = await request.get(url, {
baseURL,
headers: {
Authorization: `Bearer ${accessToken}`
},
- addressFamily: 4
+ // we force IPV4 because docker setup fails with ipv6
+ httpsAgent: new https.Agent({
+ family: 4
+ })
});
result = result.concat(res.data.items);
url = res.data?.["@nextLink"];
+ if (url) {
+ await blockLocalAndPrivateIpAddresses(url);
+ }
}
return result;
@@ -433,7 +442,7 @@ const syncSecretsAzureAppConfig = async ({
for await (const key of Object.keys(secrets)) {
if (!(key in azureAppConfigSecrets) || secrets[key]?.value !== azureAppConfigSecrets[key]) {
- await safeRequest.put(
+ await request.put(
`${integration.app}/kv/${key}?api-version=2023-11-01`,
{
value: secrets[key]?.value,
@@ -451,7 +460,10 @@ const syncSecretsAzureAppConfig = async ({
headers: {
Authorization: `Bearer ${accessToken}`
},
- addressFamily: 4
+ // we force IPV4 because docker setup fails with ipv6
+ httpsAgent: new https.Agent({
+ family: 4
+ })
}
);
}
@@ -460,7 +472,7 @@ const syncSecretsAzureAppConfig = async ({
for await (const key of Object.keys(azureAppConfigSecrets)) {
if (!(key in secrets) || secrets[key] === null) {
// case: delete secret
- await safeRequest.delete(`${integration.app}/kv/${key}?api-version=2023-11-01`, {
+ await request.delete(`${integration.app}/kv/${key}?api-version=2023-11-01`, {
headers: {
Authorization: `Bearer ${accessToken}`
},
@@ -469,7 +481,10 @@ const syncSecretsAzureAppConfig = async ({
label: metadata.azureLabel
}
}),
- addressFamily: 4
+ // we force IPV4 because docker setup fails with ipv6
+ httpsAgent: new https.Agent({
+ family: 4
+ })
});
}
}
@@ -507,6 +522,8 @@ const syncSecretsAzureKeyVault = async ({
throw new BadRequestError({ message: "Azure Key Vault URI is required" });
}
+ await blockLocalAndPrivateIpAddresses(integration.app);
+
interface GetAzureKeyVaultSecret {
id: string; // secret URI
value: string;
@@ -531,7 +548,7 @@ const syncSecretsAzureKeyVault = async ({
const paginateAzureKeyVaultSecrets = async (url: string) => {
let result: GetAzureKeyVaultSecret[] = [];
while (url) {
- const res = await safeRequest.get<{ value: GetAzureKeyVaultSecret[]; nextLink: string }>(url, {
+ const res = await request.get(url, {
headers: {
Authorization: `Bearer ${accessToken}`
}
@@ -540,6 +557,9 @@ const syncSecretsAzureKeyVault = async ({
result = result.concat(res.data.value);
url = res.data.nextLink;
+ if (url) {
+ await blockLocalAndPrivateIpAddresses(url);
+ }
}
return result;
@@ -564,7 +584,7 @@ const syncSecretsAzureKeyVault = async ({
lastSlashIndex = getAzureKeyVaultSecret.id.lastIndexOf("/");
}
- const azureKeyVaultSecret = await safeRequest.get(`${getAzureKeyVaultSecret.id}?api-version=7.3`, {
+ const azureKeyVaultSecret = await request.get(`${getAzureKeyVaultSecret.id}?api-version=7.3`, {
headers: {
Authorization: `Bearer ${accessToken}`
}
@@ -710,9 +730,11 @@ const syncSecretsAzureKeyVault = async ({
while (!isSecretSet && maxTries > 0) {
// try to set secret
try {
- await safeRequest.put(
+ await request.put(
`${azIntegration.app}/secrets/${key}?api-version=7.3`,
- { value },
+ {
+ value
+ },
{
headers: {
Authorization: `Bearer ${accToken}`
@@ -725,7 +747,7 @@ const syncSecretsAzureKeyVault = async ({
const error = err as AxiosError;
// eslint-disable-next-line
if ((error?.response?.data as any)?.error?.innererror?.code === "ObjectIsDeletedButRecoverable") {
- await safeRequest.post(
+ await request.post(
`${azIntegration.app}/deletedsecrets/${key}/recover?api-version=7.3`,
{},
{
@@ -760,7 +782,7 @@ const syncSecretsAzureKeyVault = async ({
for await (const deleteSecret of deleteSecrets.filter((secret) => !secretKeysToRemoveFromDelete.has(secret.key))) {
const { key } = deleteSecret;
- await safeRequest.delete(`${integration.app}/secrets/${key}?api-version=7.3`, {
+ await request.delete(`${integration.app}/secrets/${key}?api-version=7.3`, {
headers: {
Authorization: `Bearer ${accessToken}`
}
@@ -2558,10 +2580,11 @@ const syncSecretsDatabricks = async ({
}) => {
const databricksApiUrl = `${integrationAuth.url}/api`;
+ await blockLocalAndPrivateIpAddresses(databricksApiUrl);
// sync secrets to Databricks
await Promise.all(
Object.keys(secrets).map(async (key) =>
- safeRequest.post(
+ request.post(
`${databricksApiUrl}/2.0/secrets/put`,
{
scope: integration.app,
@@ -2580,7 +2603,7 @@ const syncSecretsDatabricks = async ({
// get secrets from Databricks
const getSecretsRes = (
- await safeRequest.get<{ secrets: { key: string; last_updated_timestamp: number }[] }>(
+ await request.get<{ secrets: { key: string; last_updated_timestamp: number }[] }>(
`${databricksApiUrl}/2.0/secrets/list`,
{
headers: {
@@ -2598,7 +2621,7 @@ const syncSecretsDatabricks = async ({
await Promise.all(
getSecretsRes.map(async (sec) => {
if (!(sec.key in secrets)) {
- return safeRequest.post(
+ return request.post(
`${databricksApiUrl}/2.0/secrets/delete`,
{
scope: integration.app,
@@ -2736,7 +2759,7 @@ const syncSecretsAzureDevops = async ({
const url: string | null =
`${azureDevopsApiUrl}/${orgId}/${project}/_apis/distributedtask/variablegroups?api-version=7.2-preview.2`;
- const response = await safeRequest.get<{ value: { name: string; id: string }[] }>(url, { headers });
+ const response = await request.get(url, { headers });
for (const group of response.data.value) {
const groupName = group.name;
if (groupName === env) {
@@ -2747,6 +2770,7 @@ const syncSecretsAzureDevops = async ({
return { groupId: "", groupName: "" };
};
+ await blockLocalAndPrivateIpAddresses(azureDevopsApiUrl);
const { groupId, groupName } = await getEnvGroupId(integration.app, integration.appId, integration.environment.name);
const variables: Record<string, { value: string; isSecret: boolean }> = {};
@@ -2780,7 +2804,7 @@ const syncSecretsAzureDevops = async ({
}
};
- const res = await safeRequest.post(url, config.data, config.headers);
+ const res = await request.post(url, config.data, config.headers);
if (res.status !== 200) {
throw new Error(`Azure DevOps: Failed to create variable group: ${res.statusText}`);
}
@@ -2809,7 +2833,7 @@ const syncSecretsAzureDevops = async ({
headers
}
};
- const res = await safeRequest.put(url, config.data, config.headers);
+ const res = await request.put(url, config.data, config.headers);
if (res.status !== 200) {
throw new Error(`Azure DevOps: Failed to update variable group: ${res.statusText}`);
}
@@ -2848,6 +2872,11 @@ const syncSecretsGitLab = async ({
const gitLabApiUrl = integrationAuth.url ? `${integrationAuth.url}/api` : IntegrationUrls.GITLAB_API_URL;
+ // Validate the base URL to prevent SSRF on all subsequent requests
+ if (integrationAuth.url) {
+ await blockLocalAndPrivateIpAddresses(gitLabApiUrl);
+ }
+
const getAllEnvVariables = async (integrationAppId: string, accToken: string) => {
const headers = {
Authorization: `Bearer ${accToken}`,
@@ -2859,7 +2888,8 @@ const syncSecretsGitLab = async ({
let url: string | null = `${gitLabApiUrl}/v4/projects/${integrationAppId}/variables?per_page=100`;
while (url) {
- const response = await safeRequest.get<GitLabSecret[]>(url, { headers });
+ await blockLocalAndPrivateIpAddresses(url);
+ const response = await request.get(url, { headers });
allEnvVariables = [...allEnvVariables, ...response.data];
const linkHeader = response.headers.link as string;
@@ -2957,7 +2987,7 @@ const syncSecretsGitLab = async ({
}
for await (const gitlabSecret of secretsToRemoveInGitlab) {
- await safeRequest.delete(
+ await request.delete(
`${gitLabApiUrl}/v4/projects/${integration?.appId}/variables/${gitlabSecret.key}?filter[environment_scope]=${integration.targetEnvironment}`,
{
headers: {
@@ -2971,7 +3001,7 @@ const syncSecretsGitLab = async ({
for await (const key of Object.keys(secrets)) {
const existingSecret = getSecretsRes.find((s) => s.key === key);
if (!existingSecret) {
- await safeRequest.post(
+ await request.post(
`${gitLabApiUrl}/v4/projects/${integration?.appId}/variables`,
{
key,
@@ -2990,7 +3020,7 @@ const syncSecretsGitLab = async ({
}
);
} else if (secrets[key].value !== existingSecret.value) {
- await safeRequest.put(
+ await request.put(
`${gitLabApiUrl}/v4/projects/${integration?.appId}/variables/${existingSecret.key}?filter[environment_scope]=${integration.targetEnvironment}`,
{
...existingSecret,
@@ -3012,7 +3042,7 @@ const syncSecretsGitLab = async ({
// delete secrets
for await (const sec of getSecretsRes) {
if (!(sec.key in secrets)) {
- await safeRequest.delete(
+ await request.delete(
`${gitLabApiUrl}/v4/projects/${integration?.appId}/variables/${sec.key}?filter[environment_scope]=${integration.targetEnvironment}`,
{
headers: {
@@ -3559,10 +3589,13 @@ const syncSecretsTeamCity = async ({
property: TeamCityBuildConfigParameter[];
}
+ if (integrationAuth.url) {
+ await blockLocalAndPrivateIpAddresses(integrationAuth.url);
+ }
if (integration.targetEnvironment && integration.targetEnvironmentId) {
// case: sync to specific build-config in TeamCity project
const res = (
- await safeRequest.get<GetTeamCityBuildConfigParametersRes>(
+ await request.get<GetTeamCityBuildConfigParametersRes>(
`${integrationAuth.url}/app/rest/buildTypes/${integration.targetEnvironmentId}/parameters`,
{
headers: {
@@ -3588,7 +3621,7 @@ const syncSecretsTeamCity = async ({
if (!(key in res) || (key in res && secrets[key].value !== res[key])) {
// case: secret does not exist in TeamCity or secret value has changed
// -> create/update secret
- await safeRequest.post(
+ await request.post(
`${integrationAuth.url}/app/rest/buildTypes/${integration.targetEnvironmentId}/parameters`,
{
name: `env.${key}`,
@@ -3610,7 +3643,7 @@ const syncSecretsTeamCity = async ({
for await (const key of Object.keys(res)) {
if (!(key in secrets)) {
// delete secret
- await safeRequest.delete(
+ await request.delete(
`${integrationAuth.url}/app/rest/buildTypes/${integration.targetEnvironmentId}/parameters/env.${key}`,
{
headers: {
@@ -3624,7 +3657,7 @@ const syncSecretsTeamCity = async ({
} else {
// case: sync to TeamCity project
const res = (
- await safeRequest.get<{ property: TeamCitySecret[] }>(
+ await request.get<{ property: TeamCitySecret[] }>(
`${integrationAuth.url}/app/rest/projects/id:${integration.appId}/parameters`,
{
headers: {
@@ -3648,7 +3681,7 @@ const syncSecretsTeamCity = async ({
if (!(key in res) || (key in res && secrets[key].value !== res[key])) {
// case: secret does not exist in TeamCity or secret value has changed
// -> create/update secret
- await safeRequest.post(
+ await request.post(
`${integrationAuth.url}/app/rest/projects/id:${integration.appId}/parameters`,
{
name: `env.${key}`,
@@ -3670,15 +3703,12 @@ const syncSecretsTeamCity = async ({
for await (const key of Object.keys(res)) {
if (!(key in secrets)) {
// delete secret
- await safeRequest.delete(
- `${integrationAuth.url}/app/rest/projects/id:${integration.appId}/parameters/env.${key}`,
- {
- headers: {
- Authorization: `Bearer ${accessToken}`,
- Accept: "application/json"
- }
+ await request.delete(`${integrationAuth.url}/app/rest/projects/id:${integration.appId}/parameters/env.${key}`, {
+ headers: {
+ Authorization: `Bearer ${accessToken}`,
+ Accept: "application/json"
}
- );
+ });
}
}
}
@@ -3708,6 +3738,8 @@ const syncSecretsHashiCorpVault = async ({
throw new BadRequestError({ message: "HashiCorp Vault URL is required" });
}
+ await blockLocalAndPrivateIpAddresses(integrationAuth.url);
+
interface LoginAppRoleRes {
auth: {
client_token: string;
@@ -3715,7 +3747,7 @@ const syncSecretsHashiCorpVault = async ({
}
// get Vault client token (could be optimized)
- const { data } = await safeRequest.post<LoginAppRoleRes>(
+ const { data }: { data: LoginAppRoleRes } = await request.post(
`${integrationAuth.url}/v1/auth/approle/login`,
{
role_id: accessId,
@@ -3730,7 +3762,7 @@ const syncSecretsHashiCorpVault = async ({
const clientToken = data.auth.client_token;
- await safeRequest.post(
+ await request.post(
`${integrationAuth.url}/v1/${integration.app}/data/${integration.path}`,
{
data: getSecretKeyValuePair(secrets)
@@ -3965,7 +3997,7 @@ const syncSecretsBitbucket = async ({
let variablesUrl = rootUrl;
while (hasNextPage) {
- const { data } = await safeRequest.get<VariablesResponse>(variablesUrl, {
+ const { data }: { data: VariablesResponse } = await request.get(variablesUrl, {
headers: {
Authorization: `Bearer ${accessToken}`,
Accept: "application/json"
@@ -3979,6 +4011,7 @@ const syncSecretsBitbucket = async ({
}
if (data.next) {
+ await blockLocalAndPrivateIpAddresses(data.next);
variablesUrl = data.next;
} else {
hasNextPage = false;
@@ -4138,9 +4171,12 @@ const syncSecretsWindmill = async ({
description?: string;
}
const apiUrl = integration.url ? `${integration.url}/api` : IntegrationUrls.WINDMILL_API_URL;
+ if (apiUrl) {
+ await blockLocalAndPrivateIpAddresses(apiUrl);
+ }
// get secrets stored in windmill workspace
const res = (
- await safeRequest.get<WindmillSecret[]>(`${apiUrl}/w/${integration.appId}/variables/list`, {
+ await request.get<WindmillSecret[]>(`${apiUrl}/w/${integration.appId}/variables/list`, {
headers: {
Authorization: `Bearer ${accessToken}`,
"Accept-Encoding": "application/json"
@@ -4162,7 +4198,7 @@ const syncSecretsWindmill = async ({
// case: secret does not exist in windmill
// -> create secret
- await safeRequest.post(
+ await request.post(
`${apiUrl}/w/${integration.appId}/variables/create`,
{
path: key,
@@ -4179,7 +4215,7 @@ const syncSecretsWindmill = async ({
);
} else {
// -> update secret
- await safeRequest.post(
+ await request.post(
`${apiUrl}/w/${integration.appId}/variables/update/${res[key].path}`,
{
path: key,
@@ -4201,7 +4237,7 @@ const syncSecretsWindmill = async ({
for await (const key of Object.keys(res)) {
if (!(key in secrets)) {
// -> delete secret
- await safeRequest.delete(`${apiUrl}/w/${integration.appId}/variables/delete/${res[key].path}`, {
+ await request.delete(`${apiUrl}/w/${integration.appId}/variables/delete/${res[key].path}`, {
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/json",
@@ -4466,8 +4502,9 @@ const syncSecretsRundeck = async ({
return;
}
+ await blockLocalAndPrivateIpAddresses(integration.url);
try {
- const listResult = await safeRequest.get<RundeckSecretsGetRes>(
+ const listResult = await request.get<RundeckSecretsGetRes>(
`${integration.url}/api/44/storage/${integration.path}`,
{
headers: {
@@ -4484,14 +4521,14 @@ const syncSecretsRundeck = async ({
try {
for await (const [key, value] of Object.entries(secrets)) {
if (existingRundeckSecrets.includes(key)) {
- await safeRequest.put(`${integration.url}/api/44/storage/${integration.path}/${key}`, value.value, {
+ await request.put(`${integration.url}/api/44/storage/${integration.path}/${key}`, value.value, {
headers: {
"X-Rundeck-Auth-Token": accessToken,
"Content-Type": "application/x-rundeck-data-password"
}
});
} else {
- await safeRequest.post(`${integration.url}/api/44/storage/${integration.path}/${key}`, value.value, {
+ await request.post(`${integration.url}/api/44/storage/${integration.path}/${key}`, value.value, {
headers: {
"X-Rundeck-Auth-Token": accessToken,
"Content-Type": "application/x-rundeck-data-password"
@@ -4502,7 +4539,7 @@ const syncSecretsRundeck = async ({
for await (const existingSecret of existingRundeckSecrets) {
if (!(existingSecret in secrets)) {
- await safeRequest.delete(`${integration.url}/api/44/storage/${integration.path}/${existingSecret}`, {
+ await request.delete(`${integration.url}/api/44/storage/${integration.path}/${existingSecret}`, {
headers: {
"X-Rundeck-Auth-Token": accessToken
}
@@ -4539,15 +4576,17 @@ const syncSecretsOctopusDeploy = async ({
throw new InternalServerError({ message: `Unhandled Octopus Deploy scope: ${integration.scope}` });
}
+ await blockLocalAndPrivateIpAddresses(url);
+
// SDK doesn't support variable set...
- const { data: variableSet } = await safeRequest.get<TOctopusDeployVariableSet>(url, {
+ const { data: variableSet } = await request.get<TOctopusDeployVariableSet>(url, {
headers: {
"X-NuGet-ApiKey": accessToken,
Accept: "application/json"
}
});
- await safeRequest.put(
+ await request.put(
url,
{
...variableSet,
diff --git a/backend/src/services/integration-auth/integration-team.ts b/backend/src/services/integration-auth/integration-team.ts
index b85dfc6193..d738625e23 100644
--- a/backend/src/services/integration-auth/integration-team.ts
+++ b/backend/src/services/integration-auth/integration-team.ts
@@ -1,7 +1,7 @@
import { AxiosResponse } from "axios";
+import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
-import { safeRequest } from "@app/lib/validator";
import { Integrations, IntegrationUrls } from "./integration-list";
@@ -16,7 +16,7 @@ const getTeamsGitLab = async ({ url, accessToken }: { url: string; accessToken:
let page: number = 1;
while (page > 0) {
// eslint-disable-next-line no-await-in-loop
- const { data, headers }: AxiosResponse<{ name: string; id: string }[]> = await safeRequest.get(
+ const { data, headers }: AxiosResponse<{ name: string; id: string }[]> = await request.get(
`${gitLabApiUrl}/v4/groups?page=${page}`,
{
headers: {
diff --git a/backend/src/services/integration-auth/integration-token.ts b/backend/src/services/integration-auth/integration-token.ts
index c6cd65e322..1f70610761 100644
--- a/backend/src/services/integration-auth/integration-token.ts
+++ b/backend/src/services/integration-auth/integration-token.ts
@@ -2,7 +2,6 @@ import { getConfig } from "@app/lib/config/env";
import { request } from "@app/lib/config/request";
import { crypto } from "@app/lib/crypto";
import { BadRequestError, ForbiddenRequestError, InternalServerError, NotFoundError } from "@app/lib/errors";
-import { safeRequest } from "@app/lib/validator";
import { Integrations, IntegrationUrls } from "./integration-list";
@@ -364,7 +363,7 @@ const exchangeCodeGitlab = async ({ code, url }: { code: string; url?: string })
}
const res = (
- await safeRequest.post<ExchangeCodeGitlabResponse>(
+ await request.post<ExchangeCodeGitlabResponse>(
url ? `${url}/oauth/token` : IntegrationUrls.GITLAB_TOKEN_URL,
new URLSearchParams({
grant_type: "authorization_code",
@@ -626,7 +625,7 @@ const exchangeRefreshGitLab = async ({ refreshToken, url }: { url?: string | nul
data
}: {
data: RefreshTokenGitLabResponse;
- } = await safeRequest.post(
+ } = await request.post(
url ? `${url}/oauth/token` : IntegrationUrls.GITLAB_TOKEN_URL,
new URLSearchParams({
grant_type: "refresh_token",
diff --git a/backend/src/services/pki-alert-v2/pki-alert-v2-channel-slack-fns.ts b/backend/src/services/pki-alert-v2/pki-alert-v2-channel-slack-fns.ts
index 72bce9a286..a80f719c85 100644
--- a/backend/src/services/pki-alert-v2/pki-alert-v2-channel-slack-fns.ts
+++ b/backend/src/services/pki-alert-v2/pki-alert-v2-channel-slack-fns.ts
@@ -1,10 +1,11 @@
import { AxiosError } from "axios";
import { getConfig } from "@app/lib/config/env";
+import { request } from "@app/lib/config/request";
import { delay } from "@app/lib/delay";
import { BadRequestError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
-import { safeRequest } from "@app/lib/validator/validate-url";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator/validate-url";
import { PKI_ALERT_RETRY_CONFIG, RETRYABLE_NETWORK_ERRORS } from "./pki-alert-v2-constants";
import {
@@ -29,7 +30,7 @@ const SLACK_WEBHOOK_TIMEOUT = 7 * 1000;
* - Hostname must be exactly "hooks.slack.com" (prevents bypass via hooks.slack.com.evil.com)
* - Must not resolve to private/local IP addresses (SSRF protection)
*/
-export const validateSlackWebhookUrl = (url: string): void => {
+export const validateSlackWebhookUrl = async (url: string): Promise<void> => {
const parsedUrl = new URL(url);
// Must be HTTPS
@@ -44,6 +45,9 @@ export const validateSlackWebhookUrl = (url: string): void => {
message: "Invalid Slack webhook URL. Must be from hooks.slack.com"
});
}
+
+ // SSRF protection - resolve DNS and block private IPs
+ await blockLocalAndPrivateIpAddresses(url);
};
/**
@@ -192,7 +196,7 @@ const isSlackErrorRetryable = (err: AxiosError): boolean => {
};
const triggerSlackWebhook = async (url: string, payload: TSlackPayload): Promise<void> => {
- await safeRequest.post(url, payload, {
+ await request.post(url, payload, {
headers: {
"Content-Type": "application/json"
},
@@ -261,7 +265,7 @@ export const sendSlackNotificationWithRetry = async (
channelId: string,
eventType: PkiAlertEventType = PkiAlertEventType.EXPIRATION
): Promise<TChannelResult> => {
- validateSlackWebhookUrl(config.webhookUrl);
+ await validateSlackWebhookUrl(config.webhookUrl);
const appCfg = getConfig();
const payload = buildSlackPayload({
diff --git a/backend/src/services/pki-alert-v2/pki-alert-v2-channel-webhook-fns.ts b/backend/src/services/pki-alert-v2/pki-alert-v2-channel-webhook-fns.ts
index e09d3e0d6d..e012942ebd 100644
--- a/backend/src/services/pki-alert-v2/pki-alert-v2-channel-webhook-fns.ts
+++ b/backend/src/services/pki-alert-v2/pki-alert-v2-channel-webhook-fns.ts
@@ -3,9 +3,10 @@ import crypto from "node:crypto";
import { AxiosError } from "axios";
import { getConfig } from "@app/lib/config/env";
+import { request } from "@app/lib/config/request";
import { delay } from "@app/lib/delay";
import { logger } from "@app/lib/logger";
-import { safeRequest } from "@app/lib/validator/validate-url";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator/validate-url";
import { PKI_ALERT_RETRY_CONFIG, RETRYABLE_NETWORK_ERRORS } from "./pki-alert-v2-constants";
import {
@@ -153,7 +154,7 @@ const triggerPkiWebhook = async (params: {
headers["x-infisical-signature"] = `t=${timestamp},v1=${signature}`;
}
- await safeRequest.post(url, payload, {
+ await request.post(url, payload, {
headers,
timeout: PKI_WEBHOOK_TIMEOUT,
signal: AbortSignal.timeout(PKI_WEBHOOK_TIMEOUT)
@@ -213,6 +214,8 @@ export const sendWebhookNotification = async (
eventType: PkiWebhookEventType,
channelId: string
): Promise<TChannelResult> => {
+ await blockLocalAndPrivateIpAddresses(config.url);
+
const appCfg = getConfig();
const payload = buildWebhookPayload({
alert: alertData,
diff --git a/backend/src/services/pki-alert-v2/pki-alert-v2-service.ts b/backend/src/services/pki-alert-v2/pki-alert-v2-service.ts
index 9ff7ef666b..2339ce7d8a 100644
--- a/backend/src/services/pki-alert-v2/pki-alert-v2-service.ts
+++ b/backend/src/services/pki-alert-v2/pki-alert-v2-service.ts
@@ -211,7 +211,8 @@ export const pkiAlertV2ServiceFactory = ({
await blockLocalAndPrivateIpAddresses(webhookConfig.url);
} else if (channel.channelType === PkiAlertChannelType.SLACK) {
const slackConfig = channel.config as TSlackChannelConfig;
- validateSlackWebhookUrl(slackConfig.webhookUrl);
+ // eslint-disable-next-line no-await-in-loop
+ await validateSlackWebhookUrl(slackConfig.webhookUrl);
}
}
@@ -395,7 +396,8 @@ export const pkiAlertV2ServiceFactory = ({
await blockLocalAndPrivateIpAddresses(webhookConfig.url);
} else if (channel.channelType === PkiAlertChannelType.SLACK) {
const slackConfig = channel.config as TSlackChannelConfig;
- validateSlackWebhookUrl(slackConfig.webhookUrl);
+ // eslint-disable-next-line no-await-in-loop
+ await validateSlackWebhookUrl(slackConfig.webhookUrl);
}
}
}
diff --git a/backend/src/services/pki-sync/azure-key-vault/azure-key-vault-pki-sync-fns.ts b/backend/src/services/pki-sync/azure-key-vault/azure-key-vault-pki-sync-fns.ts
index 0d68628a8c..6b14475481 100644
--- a/backend/src/services/pki-sync/azure-key-vault/azure-key-vault-pki-sync-fns.ts
+++ b/backend/src/services/pki-sync/azure-key-vault/azure-key-vault-pki-sync-fns.ts
@@ -3,8 +3,9 @@ import { AxiosError } from "axios";
import * as crypto from "crypto";
import { TCertificateSyncs } from "@app/db/schemas";
+import { request } from "@app/lib/config/request";
import { logger } from "@app/lib/logger";
-import { safeRequest } from "@app/lib/validator";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
import { getAzureConnectionAccessToken } from "@app/services/app-connection/azure-key-vault/azure-key-vault-connection-fns";
import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
@@ -211,6 +212,8 @@ export const azureKeyVaultPkiSyncFactory = ({
certificateDAL
}: TAzureKeyVaultPkiSyncFactoryDeps) => {
const $getAzureKeyVaultCertificates = async (accessToken: string, vaultBaseUrl: string, syncId = "unknown") => {
+ await blockLocalAndPrivateIpAddresses(vaultBaseUrl);
+
const paginateAzureKeyVaultCertificates = async () => {
let result: GetAzureKeyVaultCertificate[] = [];
@@ -218,9 +221,10 @@ export const azureKeyVaultPkiSyncFactory = ({
while (currentUrl) {
const urlToFetch = currentUrl; // Capture current URL to avoid loop function issue
+ await blockLocalAndPrivateIpAddresses(urlToFetch);
const res = await withRateLimitRetry(
() =>
- safeRequest.get<{ value: GetAzureKeyVaultCertificate[]; nextLink: string }>(urlToFetch, {
+ request.get<{ value: GetAzureKeyVaultCertificate[]; nextLink: string }>(urlToFetch, {
headers: {
Authorization: `Bearer ${accessToken}`
}
@@ -249,7 +253,8 @@ export const azureKeyVaultPkiSyncFactory = ({
enabledAzureKeyVaultCertificates,
async (getAzureKeyVaultCertificate) => {
const certificateDetailUrl = `${getAzureKeyVaultCertificate.id}?api-version=7.4`;
- const azureKeyVaultCertificate = await safeRequest.get<GetAzureKeyVaultCertificate>(certificateDetailUrl, {
+ await blockLocalAndPrivateIpAddresses(certificateDetailUrl);
+ const azureKeyVaultCertificate = await request.get<GetAzureKeyVaultCertificate>(certificateDetailUrl, {
headers: {
Authorization: `Bearer ${accessToken}`
}
@@ -514,7 +519,7 @@ export const azureKeyVaultPkiSyncFactory = ({
}
};
- const response = await safeRequest.post(
+ const response = await request.post(
`${destinationConfig.vaultBaseUrl}/certificates/${encodeURIComponent(key)}/import?api-version=7.4`,
importData,
{
@@ -605,7 +610,7 @@ export const azureKeyVaultPkiSyncFactory = ({
certificatesToRemove,
async (certName) => {
try {
- await safeRequest.delete(
+ await request.delete(
`${destinationConfig.vaultBaseUrl}/certificates/${encodeURIComponent(certName)}?api-version=7.4`,
{
headers: {
@@ -731,6 +736,8 @@ export const azureKeyVaultPkiSyncFactory = ({
// Cast destination config to Azure Key Vault config
const destinationConfig = pkiSync.destinationConfig as TAzureKeyVaultPkiSyncConfig;
+ await blockLocalAndPrivateIpAddresses(destinationConfig.vaultBaseUrl);
+
const existingSyncRecords = await certificateSyncDAL.findByPkiSyncId(pkiSync.id);
const certificateNamesToRemove: string[] = [];
const certificateIdToNameMap = new Map<string, string>();
@@ -760,7 +767,7 @@ export const azureKeyVaultPkiSyncFactory = ({
certificateNamesToRemove,
async (certName) => {
try {
- const response = await safeRequest.delete(
+ const response = await request.delete(
`${destinationConfig.vaultBaseUrl}/certificates/${encodeURIComponent(certName)}?api-version=7.4`,
{
headers: {
diff --git a/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-fns.ts b/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-fns.ts
index 56c1a3ea7f..9d2aaa8bd8 100644
--- a/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-fns.ts
+++ b/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-fns.ts
@@ -1,15 +1,12 @@
/* eslint-disable no-await-in-loop */
-import { AxiosError } from "axios";
+import { AxiosError, AxiosRequestConfig } from "axios";
import handlebars from "handlebars";
import RE2 from "re2";
import { TCertificateSyncs } from "@app/db/schemas";
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
import { logger } from "@app/lib/logger";
-import {
- executeNetScalerOperationWithGateway,
- TNetScalerRequestConfig
-} from "@app/services/app-connection/netscaler/netscaler-connection-fns";
+import { executeNetScalerOperationWithGateway } from "@app/services/app-connection/netscaler/netscaler-connection-fns";
import { TNetScalerConnection } from "@app/services/app-connection/netscaler/netscaler-connection-types";
import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
import { TCertificateSyncDALFactory } from "@app/services/certificate-sync/certificate-sync-dal";
@@ -22,7 +19,7 @@ import { TNetScalerPkiSyncConfig } from "./netscaler-pki-sync-types";
type TNetScalerCredentials = TNetScalerConnection["credentials"];
-type TRequestFn = <R>(requestCfg: TNetScalerRequestConfig) => Promise<R>;
+type TRequestFn = <R>(requestCfg: AxiosRequestConfig) => Promise<R>;
type TNetScalerSession = {
baseUrl: string;
diff --git a/backend/src/services/secret-sync/1password/1password-sync-fns.ts b/backend/src/services/secret-sync/1password/1password-sync-fns.ts
index e714a2b1b2..c2011c1012 100644
--- a/backend/src/services/secret-sync/1password/1password-sync-fns.ts
+++ b/backend/src/services/secret-sync/1password/1password-sync-fns.ts
@@ -1,4 +1,4 @@
-import { safeRequest } from "@app/lib/validator";
+import { request } from "@app/lib/config/request";
import { getOnePassInstanceUrl } from "@app/services/app-connection/1password";
import {
TDeleteOnePassVariable,
@@ -17,7 +17,7 @@ import { TSecretMap } from "@app/services/secret-sync/secret-sync-types";
const VALUE_LABEL_DEFAULT = "value";
const listOnePassItems = async ({ instanceUrl, apiToken, vaultId, valueLabel }: TOnePassListVariables) => {
- const { data } = await safeRequest.get<TOnePassListVariablesResponse>(`${instanceUrl}/v1/vaults/${vaultId}/items`, {
+ const { data } = await request.get<TOnePassListVariablesResponse>(`${instanceUrl}/v1/vaults/${vaultId}/items`, {
headers: {
Authorization: `Bearer ${apiToken}`,
Accept: "application/json"
@@ -37,15 +37,12 @@ const listOnePassItems = async ({ instanceUrl, apiToken, vaultId, valueLabel }:
continue;
}
- const { data: secret } = await safeRequest.get<TOnePassVariable>(
- `${instanceUrl}/v1/vaults/${vaultId}/items/${s.id}`,
- {
- headers: {
- Authorization: `Bearer ${apiToken}`,
- Accept: "application/json"
- }
+ const { data: secret } = await request.get<TOnePassVariable>(`${instanceUrl}/v1/vaults/${vaultId}/items/${s.id}`, {
+ headers: {
+ Authorization: `Bearer ${apiToken}`,
+ Accept: "application/json"
}
- );
+ });
const valueField = secret.fields.find((f) => f.label === valueLabel);
@@ -70,7 +67,7 @@ const createOnePassItem = async ({
itemValue,
valueLabel
}: TPostOnePassVariable) => {
- return safeRequest.post(
+ return request.post(
`${instanceUrl}/v1/vaults/${vaultId}/items`,
{
title: itemTitle,
@@ -107,7 +104,7 @@ const updateOnePassItem = async ({
valueLabel,
otherFields
}: TPutOnePassVariable) => {
- return safeRequest.put(
+ return request.put(
`${instanceUrl}/v1/vaults/${vaultId}/items/${itemId}`,
{
id: itemId,
@@ -137,7 +134,7 @@ const updateOnePassItem = async ({
};
const deleteOnePassItem = async ({ instanceUrl, apiToken, vaultId, itemId }: TDeleteOnePassVariable) => {
- return safeRequest.delete(`${instanceUrl}/v1/vaults/${vaultId}/items/${itemId}`, {
+ return request.delete(`${instanceUrl}/v1/vaults/${vaultId}/items/${itemId}`, {
headers: {
Authorization: `Bearer ${apiToken}`
}
@@ -152,7 +149,7 @@ export const OnePassSyncFns = {
destinationConfig: { vaultId, valueLabel }
} = secretSync;
- const instanceUrl = getOnePassInstanceUrl(connection);
+ const instanceUrl = await getOnePassInstanceUrl(connection);
const { apiToken } = connection.credentials;
const { items, duplicates } = await listOnePassItems({
@@ -246,7 +243,7 @@ export const OnePassSyncFns = {
destinationConfig: { vaultId, valueLabel }
} = secretSync;
- const instanceUrl = getOnePassInstanceUrl(connection);
+ const instanceUrl = await getOnePassInstanceUrl(connection);
const { apiToken } = connection.credentials;
const { items } = await listOnePassItems({
@@ -280,7 +277,7 @@ export const OnePassSyncFns = {
destinationConfig: { vaultId, valueLabel }
} = secretSync;
- const instanceUrl = getOnePassInstanceUrl(connection);
+ const instanceUrl = await getOnePassInstanceUrl(connection);
const { apiToken } = connection.credentials;
const res = await listOnePassItems({
diff --git a/backend/src/services/secret-sync/azure-app-configuration/azure-app-configuration-sync-fns.ts b/backend/src/services/secret-sync/azure-app-configuration/azure-app-configuration-sync-fns.ts
index 2acc5a9174..f054d04b84 100644
--- a/backend/src/services/secret-sync/azure-app-configuration/azure-app-configuration-sync-fns.ts
+++ b/backend/src/services/secret-sync/azure-app-configuration/azure-app-configuration-sync-fns.ts
@@ -1,6 +1,8 @@
/* eslint-disable no-await-in-loop */
+import https from "https";
+
+import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
-import { safeRequest } from "@app/lib/validator";
import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
import { getAzureConnectionAccessToken } from "@app/services/app-connection/azure-key-vault/azure-key-vault-connection-fns";
import { isAzureKeyVaultReference } from "@app/services/integration-auth/integration-sync-secret-fns";
@@ -30,12 +32,15 @@ export const azureAppConfigurationSyncFactory = ({
let currentUrl = url;
while (currentUrl) {
- const res = await safeRequest.get<{ items: AzureAppConfigKeyValue[]; ["@nextLink"]: string }>(currentUrl, {
+ const res = await request.get<{ items: AzureAppConfigKeyValue[]; ["@nextLink"]: string }>(currentUrl, {
baseURL,
headers: {
Authorization: `Bearer ${accessToken}`
},
- addressFamily: 4
+ // we force IPV4 because docker setup fails with ipv6
+ httpsAgent: new https.Agent({
+ family: 4
+ })
});
result = result.concat(res.data.items);
@@ -46,7 +51,7 @@ export const azureAppConfigurationSyncFactory = ({
};
const $deleteAzureSecret = async (accessToken: string, configurationUrl: string, key: string, label?: string) => {
- await safeRequest.delete(`${configurationUrl}/kv/${key}?api-version=2023-11-01`, {
+ await request.delete(`${configurationUrl}/kv/${key}?api-version=2023-11-01`, {
headers: {
Authorization: `Bearer ${accessToken}`
},
@@ -56,7 +61,9 @@ export const azureAppConfigurationSyncFactory = ({
label
}
}),
- addressFamily: 4
+ httpsAgent: new https.Agent({
+ family: 4
+ })
});
};
@@ -104,7 +111,7 @@ export const azureAppConfigurationSyncFactory = ({
// add the secrets to azure app config, that are in infisical
for await (const key of Object.keys(secretMap)) {
if (!(key in azureAppConfigSecretsLabeled) || secretMap[key]?.value !== azureAppConfigSecretsLabeled[key]) {
- await safeRequest.put(
+ await request.put(
`${secretSync.destinationConfig.configurationUrl}/kv/${key}?api-version=2023-11-01`,
{
value: secretMap[key]?.value,
@@ -122,7 +129,9 @@ export const azureAppConfigurationSyncFactory = ({
headers: {
Authorization: `Bearer ${accessToken}`
},
- addressFamily: 4
+ httpsAgent: new https.Agent({
+ family: 4
+ })
}
);
}
diff --git a/backend/src/services/secret-sync/circleci/circleci-sync-fns.ts b/backend/src/services/secret-sync/circleci/circleci-sync-fns.ts
index 8b4f99bf49..f2442874ee 100644
--- a/backend/src/services/secret-sync/circleci/circleci-sync-fns.ts
+++ b/backend/src/services/secret-sync/circleci/circleci-sync-fns.ts
@@ -1,8 +1,8 @@
import { AxiosError } from "axios";
+import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
-import { safeRequest } from "@app/lib/validator";
import { getCircleCIApiUrl } from "@app/services/app-connection/circleci";
import { SecretSyncError } from "@app/services/secret-sync/secret-sync-errors";
import { matchesSchema } from "@app/services/secret-sync/secret-sync-fns";
@@ -34,7 +34,7 @@ const getProjectSlug = async (
// First attempt: Try to get project details using the project ID
try {
- const { data: projectDetails } = await safeRequest.get<{ slug: string }>(`${apiUrl}/v2/project/${projectId}`, {
+ const { data: projectDetails } = await request.get<{ slug: string }>(`${apiUrl}/v2/project/${projectId}`, {
headers
});
return projectDetails.slug;
@@ -49,7 +49,7 @@ const getProjectSlug = async (
// Fallback: Construct slug from org + project name
try {
- const { data: collaborations } = await safeRequest.get<{ slug: string; name: string }[]>(
+ const { data: collaborations } = await request.get<{ slug: string; name: string }[]>(
`${apiUrl}/v2/me/collaborations`,
{ headers }
);
@@ -88,7 +88,7 @@ const listEnvVars = async (
const url = `${apiUrl}/v2/project/${projectSlug}/envvar${nextPageToken ? `?page-token=${nextPageToken}` : ""}`;
// eslint-disable-next-line no-await-in-loop
- const response = await safeRequest.get<TCircleCIEnvVarListResponse>(url, {
+ const response = await request.get<TCircleCIEnvVarListResponse>(url, {
headers: {
"Circle-Token": apiToken,
"Accept-Encoding": "application/json"
@@ -111,7 +111,7 @@ const createOrUpdateEnvVar = async (
) => {
const url = `${apiUrl}/v2/project/${projectId}/envvar`;
- await safeRequest.post(
+ await request.post(
url,
{ name, value },
{
@@ -123,7 +123,7 @@ const createOrUpdateEnvVar = async (
const deleteEnvVar = async (projectId: string, apiToken: string, name: string, apiUrl: string) => {
const url = `${apiUrl}/v2/project/${projectId}/envvar/${encodeURIComponent(name)}`;
- await safeRequest.delete(url, {
+ await request.delete(url, {
headers: getHeaders(apiToken)
});
};
diff --git a/backend/src/services/secret-sync/databricks/databricks-sync-fns.ts b/backend/src/services/secret-sync/databricks/databricks-sync-fns.ts
index 0798f25c7a..7d5273a4ea 100644
--- a/backend/src/services/secret-sync/databricks/databricks-sync-fns.ts
+++ b/backend/src/services/secret-sync/databricks/databricks-sync-fns.ts
@@ -1,5 +1,5 @@
+import { request } from "@app/lib/config/request";
import { removeTrailingSlash } from "@app/lib/fn";
-import { safeRequest } from "@app/lib/validator";
import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
import { getDatabricksConnectionAccessToken } from "@app/services/app-connection/databricks/databricks-connection-fns";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
@@ -24,7 +24,7 @@ type TDatabricksSecretSyncFactoryDeps = {
const DATABRICKS_SCOPE_SECRET_LIMIT = 1000;
const listDatabricksSecrets = async ({ workspaceUrl, scope, accessToken }: TDatabricksListSecretKeys) => {
- const { data } = await safeRequest.get<TDatabricksListSecretKeysResponse>(
+ const { data } = await request.get<TDatabricksListSecretKeysResponse>(
`${removeTrailingSlash(workspaceUrl)}/api/2.0/secrets/list`,
{
params: {
@@ -41,7 +41,7 @@ const listDatabricksSecrets = async ({ workspaceUrl, scope, accessToken }: TData
return data.secrets ?? [];
};
const putDatabricksSecret = async ({ workspaceUrl, scope, key, value, accessToken }: TDatabricksPutSecret) =>
- safeRequest.post(
+ request.post(
`${removeTrailingSlash(workspaceUrl)}/api/2.0/secrets/put`,
{
scope,
@@ -57,7 +57,7 @@ const putDatabricksSecret = async ({ workspaceUrl, scope, key, value, accessToke
);
const deleteDatabricksSecrets = async ({ workspaceUrl, scope, key, accessToken }: TDatabricksDeleteSecret) =>
- safeRequest.post(
+ request.post(
`${removeTrailingSlash(workspaceUrl)}/api/2.0/secrets/delete`,
{
scope,
diff --git a/backend/src/services/secret-sync/external-infisical/external-infisical-sync-fns.ts b/backend/src/services/secret-sync/external-infisical/external-infisical-sync-fns.ts
index 91ad61812e..f9a725c40e 100644
--- a/backend/src/services/secret-sync/external-infisical/external-infisical-sync-fns.ts
+++ b/backend/src/services/secret-sync/external-infisical/external-infisical-sync-fns.ts
@@ -1,7 +1,8 @@
/* eslint-disable no-await-in-loop */
import { AxiosError } from "axios";
-import { safeRequest } from "@app/lib/validator";
+import { request } from "@app/lib/config/request";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { getExternalInfisicalAccessToken } from "@app/services/app-connection/external-infisical";
import { SecretSyncError } from "@app/services/secret-sync/secret-sync-errors";
import { matchesSchema } from "@app/services/secret-sync/secret-sync-fns";
@@ -45,6 +46,7 @@ const getRemoteContext = async (secretSync: TExternalInfisicalSyncWithCredential
const { credentials } = secretSync.connection;
const accessToken = await getExternalInfisicalAccessToken(credentials);
const baseUrl = credentials.instanceUrl.replace(/\/$/, "");
+ await blockLocalAndPrivateIpAddresses(credentials.instanceUrl);
return { accessToken, baseUrl };
};
@@ -54,7 +56,7 @@ const fetchRemoteSecrets = async (
): Promise<TRemoteSecret[]> => {
const { destinationConfig } = secretSync;
- const { data } = await safeRequest.get<{ secrets: TRemoteSecret[] }>(`${baseUrl}/api/v3/secrets/raw`, {
+ const { data } = await request.get<{ secrets: TRemoteSecret[] }>(`${baseUrl}/api/v3/secrets/raw`, {
headers: { Authorization: `Bearer ${accessToken}` },
params: {
workspaceId: destinationConfig.projectId,
@@ -75,7 +77,7 @@ const batchCreateSecrets = async (
const { destinationConfig } = secretSync;
- await safeRequest.post(
+ await request.post(
`${baseUrl}/api/v3/secrets/batch/raw`,
{
workspaceId: destinationConfig.projectId,
@@ -102,7 +104,7 @@ const batchUpdateSecrets = async (
const { destinationConfig } = secretSync;
- await safeRequest.patch(
+ await request.patch(
`${baseUrl}/api/v3/secrets/batch/raw`,
{
workspaceId: destinationConfig.projectId,
@@ -129,7 +131,7 @@ const batchDeleteSecrets = async (
const { destinationConfig } = secretSync;
- await safeRequest.delete(`${baseUrl}/api/v3/secrets/batch/raw`, {
+ await request.delete(`${baseUrl}/api/v3/secrets/batch/raw`, {
headers: { Authorization: `Bearer ${accessToken}` },
data: {
workspaceId: destinationConfig.projectId,
diff --git a/backend/src/services/secret-sync/hc-vault/hc-vault-sync-fns.ts b/backend/src/services/secret-sync/hc-vault/hc-vault-sync-fns.ts
index b8174d8689..d636290f7f 100644
--- a/backend/src/services/secret-sync/hc-vault/hc-vault-sync-fns.ts
+++ b/backend/src/services/secret-sync/hc-vault/hc-vault-sync-fns.ts
@@ -173,7 +173,7 @@ export const HCVaultSyncFns = {
const { namespace } = connection.credentials;
const accessToken = await getHCVaultAccessToken(connection, gatewayService, gatewayV2Service);
- const instanceUrl = getHCVaultInstanceUrl(connection);
+ const instanceUrl = await getHCVaultInstanceUrl(connection);
// Get mount details to determine KV version
const { version: mountVersion } = await getKvMountVersion({
@@ -268,7 +268,7 @@ export const HCVaultSyncFns = {
const { namespace } = connection.credentials;
const accessToken = await getHCVaultAccessToken(connection, gatewayService, gatewayV2Service);
- const instanceUrl = getHCVaultInstanceUrl(connection);
+ const instanceUrl = await getHCVaultInstanceUrl(connection);
// Get mount details to determine KV version
const { version: mountVersion } = await getKvMountVersion({
@@ -337,7 +337,7 @@ export const HCVaultSyncFns = {
const { namespace } = connection.credentials;
const accessToken = await getHCVaultAccessToken(connection, gatewayService, gatewayV2Service);
- const instanceUrl = getHCVaultInstanceUrl(connection);
+ const instanceUrl = await getHCVaultInstanceUrl(connection);
// Get mount details to determine KV version
const { version: mountVersion } = await getKvMountVersion({
diff --git a/backend/src/services/secret-sync/octopus-deploy/octopus-deploy-sync-fns.ts b/backend/src/services/secret-sync/octopus-deploy/octopus-deploy-sync-fns.ts
index 0e60b46c2d..7795464a3c 100644
--- a/backend/src/services/secret-sync/octopus-deploy/octopus-deploy-sync-fns.ts
+++ b/backend/src/services/secret-sync/octopus-deploy/octopus-deploy-sync-fns.ts
@@ -1,5 +1,5 @@
+import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
-import { safeRequest } from "@app/lib/validator";
import { getOctopusDeployInstanceUrl } from "@app/services/app-connection/octopus-deploy";
import { matchesSchema } from "@app/services/secret-sync/secret-sync-fns";
import { TSecretMap } from "@app/services/secret-sync/secret-sync-types";
@@ -38,14 +38,14 @@ export const OctopusDeploySyncFns = {
environment,
syncOptions: { disableSecretDeletion, keySchema }
} = secretSync;
- const instanceUrl = getOctopusDeployInstanceUrl(connection);
+ const instanceUrl = await getOctopusDeployInstanceUrl(connection);
const { apiKey } = connection.credentials;
const { spaceId, projectId, scope } = secretSync.destinationConfig;
const url = this.buildVariableUrl(instanceUrl, spaceId, projectId, scope);
- const { data: variableSet } = await safeRequest.get<TOctopusDeployVariableSet>(url, {
+ const { data: variableSet } = await request.get<TOctopusDeployVariableSet>(url, {
headers: this.getAuthHeader(apiKey)
});
@@ -101,7 +101,7 @@ export const OctopusDeploySyncFns = {
// Keep sensitive variables that are not in the new variables array, to avoid duplication
sensitiveVariables = sensitiveVariables.filter((variable) => !newVariableKeys.includes(variable.Name));
- await safeRequest.put(
+ await request.put(
url,
{
...variableSet,
@@ -118,12 +118,12 @@ export const OctopusDeploySyncFns = {
destinationConfig: { spaceId, projectId, scope }
} = secretSync;
- const instanceUrl = getOctopusDeployInstanceUrl(connection);
+ const instanceUrl = await getOctopusDeployInstanceUrl(connection);
const { apiKey } = connection.credentials;
const url = this.buildVariableUrl(instanceUrl, spaceId, projectId, scope);
- const { data: variableSet } = await safeRequest.get<TOctopusDeployVariableSet>(url, {
+ const { data: variableSet } = await request.get<TOctopusDeployVariableSet>(url, {
headers: this.getAuthHeader(apiKey)
});
@@ -134,7 +134,7 @@ export const OctopusDeploySyncFns = {
infisicalSecretKeys.includes(variable.Name) && variable.IsSensitive === true && variable.Type === "Sensitive"
).map((variable) => variable.Id);
- await safeRequest.put(
+ await request.put(
url,
{
...variableSet,
diff --git a/backend/src/services/secret-sync/teamcity/teamcity-sync-fns.ts b/backend/src/services/secret-sync/teamcity/teamcity-sync-fns.ts
index 2e32caab9e..28ef2d0d34 100644
--- a/backend/src/services/secret-sync/teamcity/teamcity-sync-fns.ts
+++ b/backend/src/services/secret-sync/teamcity/teamcity-sync-fns.ts
@@ -1,4 +1,4 @@
-import { safeRequest } from "@app/lib/validator";
+import { request } from "@app/lib/config/request";
import { getTeamCityInstanceUrl } from "@app/services/app-connection/teamcity";
import { SecretSyncError } from "@app/services/secret-sync/secret-sync-errors";
import { matchesSchema } from "@app/services/secret-sync/secret-sync-fns";
@@ -14,7 +14,7 @@ import {
// Note: Most variables won't be returned with a value due to them being a "password" type.
// TeamCity API returns empty string for password-type variables for security reasons.
const listTeamCityVariables = async ({ instanceUrl, accessToken, project, buildConfig }: TTeamCityListVariables) => {
- const { data } = await safeRequest.get<TTeamCityListVariablesResponse>(
+ const { data } = await request.get<TTeamCityListVariablesResponse>(
buildConfig
? `${instanceUrl}/app/rest/buildTypes/${encodeURIComponent(buildConfig)}/parameters`
: `${instanceUrl}/app/rest/projects/id:${encodeURIComponent(project)}/parameters`,
@@ -48,7 +48,7 @@ const updateTeamCityVariable = async ({
key,
value
}: TPostTeamCityVariable) => {
- return safeRequest.post(
+ return request.post(
buildConfig
? `${instanceUrl}/app/rest/buildTypes/${encodeURIComponent(buildConfig)}/parameters`
: `${instanceUrl}/app/rest/projects/id:${encodeURIComponent(project)}/parameters`,
@@ -75,7 +75,7 @@ const deleteTeamCityVariable = async ({
buildConfig,
key
}: TDeleteTeamCityVariable) => {
- return safeRequest.delete(
+ return request.delete(
buildConfig
? `${instanceUrl}/app/rest/buildTypes/${encodeURIComponent(buildConfig)}/parameters/${encodeURIComponent(key)}`
: `${instanceUrl}/app/rest/projects/id:${encodeURIComponent(project)}/parameters/${encodeURIComponent(key)}`,
@@ -94,7 +94,7 @@ export const TeamCitySyncFns = {
destinationConfig: { project, buildConfig }
} = secretSync;
- const instanceUrl = getTeamCityInstanceUrl(connection);
+ const instanceUrl = await getTeamCityInstanceUrl(connection);
const { accessToken } = connection.credentials;
for await (const entry of Object.entries(secretMap)) {
@@ -153,7 +153,7 @@ export const TeamCitySyncFns = {
destinationConfig: { project, buildConfig }
} = secretSync;
- const instanceUrl = getTeamCityInstanceUrl(connection);
+ const instanceUrl = await getTeamCityInstanceUrl(connection);
const { accessToken } = connection.credentials;
const variables = await listTeamCityVariables({ instanceUrl, accessToken, project, buildConfig });
@@ -183,7 +183,7 @@ export const TeamCitySyncFns = {
destinationConfig: { project, buildConfig }
} = secretSync;
- const instanceUrl = getTeamCityInstanceUrl(connection);
+ const instanceUrl = await getTeamCityInstanceUrl(connection);
const { accessToken } = connection.credentials;
return listTeamCityVariables({ instanceUrl, accessToken, project, buildConfig });
diff --git a/backend/src/services/secret-sync/windmill/windmill-sync-fns.ts b/backend/src/services/secret-sync/windmill/windmill-sync-fns.ts
index 5ba2c762c9..b5e11c9579 100644
--- a/backend/src/services/secret-sync/windmill/windmill-sync-fns.ts
+++ b/backend/src/services/secret-sync/windmill/windmill-sync-fns.ts
@@ -1,4 +1,4 @@
-import { safeRequest } from "@app/lib/validator";
+import { request } from "@app/lib/config/request";
import { getWindmillInstanceUrl } from "@app/services/app-connection/windmill";
import { SecretSyncError } from "@app/services/secret-sync/secret-sync-errors";
import { matchesSchema } from "@app/services/secret-sync/secret-sync-fns";
@@ -23,7 +23,7 @@ const listWindmillVariables = async ({ instanceUrl, workspace, accessToken, path
while (page) {
// eslint-disable-next-line no-await-in-loop
- const { data: variablesPage } = await safeRequest.get<TWindmillListVariablesResponse>(
+ const { data: variablesPage } = await request.get<TWindmillListVariablesResponse>(
`${instanceUrl}/api/w/${workspace}/variables/list`,
{
headers: {
@@ -42,7 +42,7 @@ const listWindmillVariables = async ({ instanceUrl, workspace, accessToken, path
if (variable.is_secret) {
// eslint-disable-next-line no-await-in-loop
- const { data: variableValue } = await safeRequest.get<string>(
+ const { data: variableValue } = await request.get<string>(
`${instanceUrl}/api/w/${workspace}/variables/get_value/${variable.path}`,
{
headers: {
@@ -78,7 +78,7 @@ const createWindmillVariable = async ({
workspace,
description
}: TPostWindmillVariable) =>
- safeRequest.post(
+ request.post(
`${instanceUrl}/api/w/${workspace}/variables/create`,
{
path,
@@ -102,7 +102,7 @@ const updateWindmillVariable = async ({
workspace,
description
}: TPostWindmillVariable) =>
- safeRequest.post(
+ request.post(
`${instanceUrl}/api/w/${workspace}/variables/update/${path}`,
{
value,
@@ -118,7 +118,7 @@ const updateWindmillVariable = async ({
);
const deleteWindmillVariable = async ({ path, instanceUrl, accessToken, workspace }: TDeleteWindmillVariable) =>
- safeRequest.delete(`${instanceUrl}/api/w/${workspace}/variables/delete/${path}`, {
+ request.delete(`${instanceUrl}/api/w/${workspace}/variables/delete/${path}`, {
headers: {
Authorization: `Bearer ${accessToken}`
}
@@ -136,7 +136,7 @@ export const WindmillSyncFns = {
// url needs to be lowercase
const workspace = secretSync.destinationConfig.workspace.toLowerCase();
- const instanceUrl = getWindmillInstanceUrl(connection);
+ const instanceUrl = await getWindmillInstanceUrl(connection);
const { accessToken } = connection.credentials;
@@ -200,7 +200,7 @@ export const WindmillSyncFns = {
// url needs to be lowercase
const workspace = secretSync.destinationConfig.workspace.toLowerCase();
- const instanceUrl = getWindmillInstanceUrl(connection);
+ const instanceUrl = await getWindmillInstanceUrl(connection);
const { accessToken } = connection.credentials;
@@ -233,7 +233,7 @@ export const WindmillSyncFns = {
// url needs to be lowercase
const workspace = secretSync.destinationConfig.workspace.toLowerCase();
- const instanceUrl = getWindmillInstanceUrl(connection);
+ const instanceUrl = await getWindmillInstanceUrl(connection);
const { accessToken } = connection.credentials;
diff --git a/backend/src/services/secret-sync/zabbix/zabbix-sync-fns.ts b/backend/src/services/secret-sync/zabbix/zabbix-sync-fns.ts
index f888692e8b..18f9061ec7 100644
--- a/backend/src/services/secret-sync/zabbix/zabbix-sync-fns.ts
+++ b/backend/src/services/secret-sync/zabbix/zabbix-sync-fns.ts
@@ -1,6 +1,7 @@
import RE2 from "re2";
-import { safeRequest } from "@app/lib/validator";
+import { request } from "@app/lib/config/request";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { SecretSyncError } from "@app/services/secret-sync/secret-sync-errors";
import { matchesSchema } from "@app/services/secret-sync/secret-sync-fns";
import { TSecretMap } from "@app/services/secret-sync/secret-sync-types";
@@ -56,7 +57,7 @@ const listZabbixSecrets = async (apiToken: string, instanceUrl: string, hostId?:
};
try {
- const response: ZabbixApiResponse<TZabbixSecret[]> = await safeRequest.post(apiUrl, payload, {
+ const response: ZabbixApiResponse<TZabbixSecret[]> = await request.post(apiUrl, payload, {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiToken}`
@@ -103,7 +104,7 @@ const putZabbixSecrets = async (
};
// eslint-disable-next-line no-await-in-loop
- const response: ZabbixApiResponse<ZabbixMacroCreateResponse> = await safeRequest.post(apiUrl, updatePayload, {
+ const response: ZabbixApiResponse<ZabbixMacroCreateResponse> = await request.post(apiUrl, updatePayload, {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiToken}`
@@ -134,7 +135,7 @@ const putZabbixSecrets = async (
};
// eslint-disable-next-line no-await-in-loop
- const response: ZabbixApiResponse<ZabbixMacroCreateResponse> = await safeRequest.post(apiUrl, createPayload, {
+ const response: ZabbixApiResponse<ZabbixMacroCreateResponse> = await request.post(apiUrl, createPayload, {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiToken}`
@@ -178,7 +179,7 @@ const deleteZabbixSecrets = async (
id: 1
};
- const response: ZabbixApiResponse<ZabbixMacroDeleteResponse> = await safeRequest.post(apiUrl, payload, {
+ const response: ZabbixApiResponse<ZabbixMacroDeleteResponse> = await request.post(apiUrl, payload, {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiToken}`
@@ -197,6 +198,7 @@ export const ZabbixSyncFns = {
syncSecrets: async (secretSync: TZabbixSyncWithCredentials, secretMap: TSecretMap) => {
const { connection, environment, destinationConfig } = secretSync;
const { apiToken, instanceUrl } = connection.credentials;
+ await blockLocalAndPrivateIpAddresses(instanceUrl);
const hostId = destinationConfig.scope === ZabbixSyncScope.Host ? destinationConfig.hostId : undefined;
let secrets: TZabbixSecret[] = [];
@@ -240,6 +242,7 @@ export const ZabbixSyncFns = {
removeSecrets: async (secretSync: TZabbixSyncWithCredentials, secretMap: TSecretMap) => {
const { connection, destinationConfig } = secretSync;
const { apiToken, instanceUrl } = connection.credentials;
+ await blockLocalAndPrivateIpAddresses(instanceUrl);
const hostId = destinationConfig.scope === ZabbixSyncScope.Host ? destinationConfig.hostId : undefined;
@@ -262,6 +265,7 @@ export const ZabbixSyncFns = {
getSecrets: async (secretSync: TZabbixSyncWithCredentials) => {
const { connection, destinationConfig } = secretSync;
const { apiToken, instanceUrl } = connection.credentials;
+ await blockLocalAndPrivateIpAddresses(instanceUrl);
const hostId = destinationConfig.scope === ZabbixSyncScope.Host ? destinationConfig.hostId : undefined;
try {
diff --git a/backend/src/services/webhook/webhook-fns.ts b/backend/src/services/webhook/webhook-fns.ts
index 35a01bca3d..57fd7d464d 100644
--- a/backend/src/services/webhook/webhook-fns.ts
+++ b/backend/src/services/webhook/webhook-fns.ts
@@ -3,12 +3,13 @@ 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 { safeRequest } from "@app/lib/validator";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { ActorType } from "@app/services/auth/auth-type";
import { TProjectDALFactory } from "../project/project-dal";
@@ -42,6 +43,7 @@ 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)
@@ -50,10 +52,11 @@ export const triggerWebhookRequest = async (
headers["x-infisical-signature"] = `t=${payload.timestamp};${webhookSign}`;
}
- const req = await safeRequest.post(url, payload, {
+ const req = await request.post(url, payload, {
headers,
timeout: WEBHOOK_TRIGGER_TIMEOUT,
- signal: AbortSignal.timeout(WEBHOOK_TRIGGER_TIMEOUT)
+ signal: AbortSignal.timeout(WEBHOOK_TRIGGER_TIMEOUT),
+ maxRedirects: 0
});
return req;
diff --git a/docs/self-hosting/guides/production-hardening.mdx b/docs/self-hosting/guides/production-hardening.mdx
index 8c816f06a3..750516d82e 100644
--- a/docs/self-hosting/guides/production-hardening.mdx
+++ b/docs/self-hosting/guides/production-hardening.mdx
@@ -83,36 +83,6 @@ 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)
@@ -120,24 +90,6 @@ Where available (Kubernetes dynamic secrets, Kubernetes identity auth, Vault ext
- **Principle**: Default deny incoming, allow only required traffic
- **Implementation**: See your deployment-specific section below for exact configuration
-#### Reverse Proxy Configuration
-
-If Infisical is deployed behind a reverse proxy (Nginx, AWS ALB, Cloudflare, GCP Load Balancer, etc.), configure the trusted proxy CIDR list so that client IP detection cannot be spoofed by attackers forging `X-Forwarded-For` headers:
-
-```bash
-# Comma-separated list of reverse-proxy CIDR ranges whose forwarded-IP headers Infisical will trust.
-# Accepts IPv4/IPv6 CIDR notation or the named aliases `loopback`, `linklocal`, `uniquelocal`.
-TRUSTED_PROXY_CIDRS="10.0.0.0/8,172.16.0.0/12,192.168.0.0/16"
-```
-
-When set, only requests arriving from a socket address inside the listed CIDRs will have their forwarded-IP headers respected. Requests from any other source fall back to the raw socket IP.
-
-When unset, Infisical trusts all forwarded-IP headers (legacy behavior, preserved for backwards compatibility). On a deployment reachable directly from the internet, this lets a client supply any value in `X-Forwarded-For` — bypassing per-IP rate limits (including login/MFA throttles) and any IP allowlists.
-
-<Warning>
- Set `TRUSTED_PROXY_CIDRS` on any deployment that is reachable from the internet through a reverse proxy. Leaving it unset is only safe when Infisical is not directly internet-facing.
-</Warning>
-
### Application Security
#### Site Configuration