Skip to content

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

chore: add extra mcp checks

Sheen Capadnganec18f4535b8b
diff --git a/backend/src/ee/services/ai-mcp-server/ai-mcp-server-service.ts b/backend/src/ee/services/ai-mcp-server/ai-mcp-server-service.ts
index b88fb4dd8c..4158bb087a 100644
--- a/backend/src/ee/services/ai-mcp-server/ai-mcp-server-service.ts
+++ b/backend/src/ee/services/ai-mcp-server/ai-mcp-server-service.ts
@@ -18,6 +18,7 @@ import { BadRequestError, NotFoundError } 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 { ssrfSafeGet, ssrfSafePost, validateSsrfUrl } from "@app/lib/validator";
import { ActorType, AuthMethod } from "@app/services/auth/auth-type";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { KmsDataKey } from "@app/services/kms/kms-types";
@@ -277,7 +278,13 @@ export const aiMcpServerServiceFactory = ({
/**
* Helper to create a gateway-aware HTTP request function
- * Returns a function that can make requests either directly or through a gateway proxy
+ * Returns a function that can make requests either directly or through a gateway proxy.
+ *
+ * When not using a gateway, requests use SSRF-safe methods that:
+ * - Validate each URL (including redirect targets) for private/internal IPs
+ * - Enforce HTTPS in production
+ * - Manually follow redirects with validation at each hop
+ * - Block POST redirects entirely
*/
const createGatewayAwareRequest = (
gatewayId: string | undefined,
@@ -289,19 +296,23 @@ export const aiMcpServerServiceFactory = ({
post: <T>(url: string, data: unknown, config?: { headers?: Record<string, string> }) => Promise<{ data: T }>;
} => {
if (!gatewayId) {
- // Direct requests (no gateway)
+ // Direct requests (no gateway) - use SSRF-safe methods with redirect validation
return {
- get: <T>(url: string) => request.get<T>(url),
+ get: async <T>(url: string) => {
+ const response = await ssrfSafeGet<T>(url);
+ return { data: response.data };
+ },
getRaw: async <T>(url: string) => {
- const response = await request.get<T>(url, { validateStatus: () => true });
- return { data: response.data, status: response.status, headers: response.headers as Record<string, unknown> };
+ // For getRaw, we need to accept all status codes (including 401 for OAuth discovery)
+ // but still validate redirects before following them
+ return ssrfSafeGet<T>(url, { validateStatus: () => true });
},
post: <T>(url: string, data: unknown, config?: { headers?: Record<string, string> }) =>
- request.post<T>(url, data, config)
+ ssrfSafePost<T>(url, data, config)
};
}
- // Gateway-proxied requests
+ // Gateway-proxied requests - gateway handles network isolation
const targetHost = mcpUrlObj.hostname;
let targetPort = 80;
if (mcpUrlObj.port) {
@@ -346,6 +357,8 @@ export const aiMcpServerServiceFactory = ({
* 2. Parse the protected resource metadata URL from the header
* 3. Fetch the protected resource metadata to get authorization_servers
* 4. Fetch the authorization server metadata
+ *
+ * All URLs in the discovery chain are validated for SSRF protection when not using a gateway.
*/
const discoverOAuthMetadata = async (
mcpUrl: string,
@@ -357,7 +370,6 @@ export const aiMcpServerServiceFactory = ({
let resourceMetadataUrl: string | null = null;
const url = new URL(mcpUrl);
- await verifyHostInputValidity({ host: url.hostname, isGateway: true, isDynamicSecret: false });
// Create gateway-aware request helper
const gatewayRequest = createGatewayAwareRequest(gatewayId, url);
@@ -370,7 +382,10 @@ export const aiMcpServerServiceFactory = ({
// Extract WWW-Authenticate header from 401 response
const wwwAuth = initialResponse.headers["www-authenticate"] as string | undefined;
if (wwwAuth) {
- resourceMetadataUrl = parseWwwAuthenticateHeader(wwwAuth);
+ const parsedResourceMetadataUrl = parseWwwAuthenticateHeader(wwwAuth);
+ if (parsedResourceMetadataUrl) {
+ resourceMetadataUrl = parsedResourceMetadataUrl;
+ }
}
} else if (initialResponse.status >= 200 && initialResponse.status < 300) {
// If we get a success response, the server doesn't require auth (unusual)
@@ -387,7 +402,7 @@ export const aiMcpServerServiceFactory = ({
const urlObj = new URL(mcpUrl);
if (!resourceMetadataUrl) {
- // Fallback: Try common .well-known paths
+ // Fallback: Try common .well-known paths (derived from validated mcpUrl origin, so safe)
const possiblePaths = [
`${urlObj.origin}/.well-known/oauth-protected-resource${urlObj.pathname}`,
`${urlObj.origin}/.well-known/oauth-protected-resource`
@@ -522,12 +537,12 @@ export const aiMcpServerServiceFactory = ({
}
const urlObj = new URL(url);
- await verifyHostInputValidity({ host: urlObj.hostname, isGateway: true, isDynamicSecret: false });
// Create gateway-aware request helper for DCR
const gatewayRequest = createGatewayAwareRequest(gatewayId, urlObj);
// 1. Discover OAuth metadata following RFC 9728 flow (route through gateway if configured)
+ // Note: discoverOAuthMetadata validates all URLs in the discovery chain
const { protectedResource, authServer } = await discoverOAuthMetadata(url, gatewayId);
// 2. Generate session ID
@@ -552,6 +567,11 @@ export const aiMcpServerServiceFactory = ({
});
}
+ // Validate registration_endpoint for SSRF protection (comes from attacker-controlled AS metadata)
+ if (!gatewayId) {
+ await validateSsrfUrl(authServer.registration_endpoint);
+ }
+
// Route DCR request through gateway when configured
const { data: clientMetadata } = await gatewayRequest.post<TOAuthDynamicClientMetadata>(
authServer.registration_endpoint,
@@ -642,8 +662,15 @@ export const aiMcpServerServiceFactory = ({
// Create gateway-aware request helper using the stored gatewayId
const serverUrlObj = new URL(sessionData.serverUrl);
const gatewayRequest = createGatewayAwareRequest(sessionData.gatewayId, serverUrlObj);
+ const isUsingGateway = Boolean(sessionData.gatewayId);
+
+ // 2. Validate token endpoint for SSRF protection before making the request
+ // This is critical as the tokenEndpoint was stored from attacker-controlled AS metadata
+ if (!isUsingGateway) {
+ await validateSsrfUrl(sessionData.tokenEndpoint);
+ }
- // 2. Exchange code for tokens using the stored token endpoint
+ // 3. Exchange code for tokens using the stored token endpoint
const tokenParams: Record<string, string> = {
grant_type: "authorization_code",
code,
diff --git a/backend/src/lib/validator/index.ts b/backend/src/lib/validator/index.ts
index d1e2fd9f45..bb49429120 100644
--- a/backend/src/lib/validator/index.ts
+++ b/backend/src/lib/validator/index.ts
@@ -10,5 +10,5 @@ export {
validateSmbPassword,
validateWindowsUsername
} from "./validate-smb";
-export { blockLocalAndPrivateIpAddresses } 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.ts b/backend/src/lib/validator/validate-url.ts
index 7b2b09209a..2f7a9d53be 100644
--- a/backend/src/lib/validator/validate-url.ts
+++ b/backend/src/lib/validator/validate-url.ts
@@ -3,7 +3,9 @@ import dns from "node:dns/promises";
import { isIPv4 } from "net";
import RE2 from "re2";
+import { verifyHostInputValidity } from "@app/ee/services/dynamic-secret/dynamic-secret-fns";
import { getConfig } from "@app/lib/config/env";
+import { request } from "@app/lib/config/request";
import { BadRequestError } from "../errors";
import { isPrivateIp } from "../ip/ipRange";
@@ -133,3 +135,109 @@ export const isFQDN = (str: string, options: FQDNOptions = {}): boolean => {
return true;
});
};
+
+/**
+ * Maximum number of redirects to follow when manually handling redirects
+ */
+const MAX_SAFE_REDIRECTS = 5;
+
+type SsrfSafeRequestOptions = {
+ /** If true, skips SSRF validation (for gateway-proxied requests) */
+ allowPrivateIps?: boolean;
+ /** Custom status validator for axios */
+ validateStatus?: (status: number) => boolean;
+};
+
+/**
+ * Validates a URL for SSRF protection.
+ * Blocks:
+ * - Local/private IPs (loopback, link-local, RFC 1918 addresses)
+ * - Infisical's own infrastructure (DB, Redis, etc.)
+ */
+export const validateSsrfUrl = async (
+ url: string,
+ options?: Pick<SsrfSafeRequestOptions, "allowPrivateIps">
+): Promise<void> => {
+ if (options?.allowPrivateIps) {
+ return;
+ }
+
+ const parsedUrl = new URL(url);
+
+ // 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 });
+};
+
+/**
+ * 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.
+ */
+export const ssrfSafeGet = async <T>(
+ url: string,
+ options?: SsrfSafeRequestOptions
+): Promise<{ data: T; status: number; headers: Record<string, unknown> }> => {
+ let currentUrl = url;
+ let redirectCount = 0;
+
+ while (redirectCount <= MAX_SAFE_REDIRECTS) {
+ // Validate URL before each request (including redirects)
+ // eslint-disable-next-line no-await-in-loop
+ 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)
+ });
+
+ // Check if it's a redirect
+ if (response.status >= 300 && response.status < 400) {
+ const location = response.headers.location as string | undefined;
+ if (!location) {
+ throw new BadRequestError({
+ message: `Redirect response (${response.status}) missing Location header`
+ });
+ }
+
+ // Resolve relative redirects
+ currentUrl = new URL(location, currentUrl).toString();
+ redirectCount += 1;
+
+ if (redirectCount > MAX_SAFE_REDIRECTS) {
+ throw new BadRequestError({
+ message: `Too many redirects (max ${MAX_SAFE_REDIRECTS})`
+ });
+ }
+ } else {
+ // Not a redirect, return the response
+ return { data: response.data, status: response.status, headers: response.headers as Record<string, unknown> };
+ }
+ }
+
+ throw new BadRequestError({
+ message: `Too many redirects (max ${MAX_SAFE_REDIRECTS})`
+ });
+};
+
+/**
+ * Makes an HTTP POST request with SSRF protection.
+ * POST requests do not follow redirects for security reasons.
+ *
+ * Note: URL validation should be done by the caller before invoking this function.
+ * This function ensures redirects are blocked as a defense-in-depth measure.
+ */
+export const ssrfSafePost = async <T>(
+ url: string,
+ data: unknown,
+ config?: { headers?: Record<string, string> }
+): Promise<{ data: T }> => {
+ return request.post<T>(url, data, {
+ ...config,
+ maxRedirects: 0
+ });
+};