Context7 Platform -- Up-to-date docs for AI agents
fix(mcp): authenticate forwarded client IP assertions (#3088)
Fahreddin Özcan794cc6ba254a
diff --git a/.changeset/signed-client-ip-assertions.md b/.changeset/signed-client-ip-assertions.mdnew file mode 100644index 00000000..43199967--- /dev/null+++ b/.changeset/signed-client-ip-assertions.md@@ -0,0 +1,5 @@+---+"@upstash/context7-mcp": patch+---++Authenticate hosted MCP client-IP forwarding with short-lived AES-GCM assertions.diff --git a/.env.example b/.env.exampleindex 4a1be529..f3ef285b 100644--- a/.env.example+++ b/.env.example@@ -9,6 +9,11 @@ OAUTH_JWKS_URL=EMA_ISSUER=AUTH_SERVER_URL=OPENAI_APPS_CHALLENGE_TOKEN=++# Required for hosted HTTP deployments. Must match context7.com.+MCP_CLIENT_IP_ASSERTION_KEY=++# Temporary legacy rollout key. Removal is tracked by CTX7-2536.CLIENT_IP_ENCRYPTION_KEY=# Network / certificatesdiff --git a/packages/mcp/src/index.ts b/packages/mcp/src/index.tsindex a10e3952..2465db4a 100644--- a/packages/mcp/src/index.ts+++ b/packages/mcp/src/index.ts@@ -24,7 +24,6 @@ import {OPENAI_APPS_CHALLENGE_TOKEN,} from "./lib/constants.js";import { maybeElicitAuthSignIn } from "./lib/auth/auth-prompt.js";-import { getClientIp } from "./lib/client-ip.js";/** Default HTTP server port */const DEFAULT_PORT = 3000;@@ -316,6 +315,9 @@ async function main() {const initialPort = CLI_PORT ?? DEFAULT_PORT;const app = express();+ // Only private/local infrastructure may supply forwarding headers. Express+ // then walks the chain right-to-left and ignores attacker-added prefixes.+ app.set("trust proxy", ["loopback", "linklocal", "uniquelocal", "100.64.0.0/10"]);app.use(express.json());app.use((req: express.Request, res: express.Response, next: express.NextFunction) => {@@ -433,7 +435,7 @@ async function main() {}const context: ClientContext = {- clientIp: getClientIp(req),+ clientIp: req.ip,apiKey: apiKey,clientInfo: extractClientInfoFromUserAgent(req.headers["user-agent"]),transport: "http",diff --git a/packages/mcp/src/lib/client-ip.ts b/packages/mcp/src/lib/client-ip.tsdeleted file mode 100644index 5c8ab2d4..00000000--- a/packages/mcp/src/lib/client-ip.ts+++ /dev/null@@ -1,78 +0,0 @@-import type express from "express";--function stripIpv4MappedPrefix(ip: string): string {- return ip.replace(/^::ffff:/i, "");-}--/**- * Returns true for RFC1918, CGNAT, loopback, link-local, and IPv6 private ranges.- */-export function isPrivateOrLocalIp(ip: string): boolean {- const plainIp = stripIpv4MappedPrefix(ip).toLowerCase();-- if (plainIp.includes(".")) {- return (- plainIp.startsWith("10.") ||- plainIp.startsWith("192.168.") ||- /^172\.(1[6-9]|2[0-9]|3[0-1])\./.test(plainIp) ||- /^100\.(6[4-9]|[7-9][0-9]|1[01][0-9]|12[0-7])\./.test(plainIp) ||- plainIp.startsWith("127.") ||- plainIp.startsWith("169.254.")- );- }-- // ::1 loopback in any textual form (e.g. "0::1", "0:0:0:0:0:0:0:1")- if (/^[0:]+1$/.test(plainIp)) {- return true;- }-- // First hextets in fe80::/10 and fc00::/7 start with a non-zero digit, so a- // valid textual form always spells out all 4 digits.-- // fe80::/10 link-local- if (/^fe[89ab][0-9a-f]:/.test(plainIp)) {- return true;- }-- // fc00::/7 unique local- if (/^f[cd][0-9a-f]{2}:/.test(plainIp)) {- return true;- }-- return false;-}--function pickClientIpFromForwardedList(ipList: string[]): string | undefined {- for (const ip of ipList) {- const plainIp = stripIpv4MappedPrefix(ip);- if (!isPrivateOrLocalIp(plainIp)) {- return plainIp;- }- }-- if (ipList.length === 0) {- return undefined;- }-- return stripIpv4MappedPrefix(ipList[0]);-}--/**- * Extract client IP address from request headers.- * Handles X-Forwarded-For header for proxied requests.- */-export function getClientIp(req: express.Request): string | undefined {- const forwardedFor = req.headers["x-forwarded-for"] || req.headers["X-Forwarded-For"];-- if (forwardedFor) {- const ips = Array.isArray(forwardedFor) ? forwardedFor[0] : forwardedFor;- const ipList = ips.split(",").map((ip) => ip.trim());- return pickClientIpFromForwardedList(ipList);- }-- if (req.socket?.remoteAddress) {- return stripIpv4MappedPrefix(req.socket.remoteAddress);- }-- return undefined;-}diff --git a/packages/mcp/src/lib/encryption.ts b/packages/mcp/src/lib/encryption.tsindex 91ceb1f4..4dd2091b 100644--- a/packages/mcp/src/lib/encryption.ts+++ b/packages/mcp/src/lib/encryption.ts@@ -1,31 +1,69 @@import { createCipheriv, randomBytes } from "crypto";+import { isIP } from "node:net";import { SERVER_VERSION } from "./constants.js";import type { ClientContext } from "./types.js";-const DEFAULT_ENCRYPTION_KEY = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f";-const ENCRYPTION_KEY = process.env.CLIENT_IP_ENCRYPTION_KEY || DEFAULT_ENCRYPTION_KEY;-const ALGORITHM = "aes-256-cbc";+const LEGACY_ALGORITHM = "aes-256-cbc";+const ASSERTION_ALGORITHM = "aes-256-gcm";+const ASSERTION_VERSION = "v1";+let reportedInvalidAssertionKey = false;function validateEncryptionKey(key: string): boolean {// Must be exactly 64 hex characters (32 bytes)return /^[0-9a-fA-F]{64}$/.test(key);}-function encryptClientIp(clientIp: string): string {- if (!validateEncryptionKey(ENCRYPTION_KEY)) {- console.error("Invalid encryption key format. Must be 64 hex characters.");- return clientIp; // Fallback to unencrypted- }+function encryptionKey(name: "MCP_CLIENT_IP_ASSERTION_KEY" | "CLIENT_IP_ENCRYPTION_KEY") {+ const key = process.env[name];+ return key && validateEncryptionKey(key) ? Buffer.from(key, "hex") : null;+}+/**+ * Temporary compatibility header for API deployments that predate authenticated assertions.+ * This header is ignored by patched API deployments. Removal is tracked by CTX7-2536.+ */+function encryptLegacyClientIp(clientIp: string, key: Buffer): string | null {try {const iv = randomBytes(16);- const cipher = createCipheriv(ALGORITHM, Buffer.from(ENCRYPTION_KEY, "hex"), iv);- let encrypted = cipher.update(clientIp, "utf8", "hex");- encrypted += cipher.final("hex");- return iv.toString("hex") + ":" + encrypted;- } catch (error) {- console.error("Error encrypting client IP:", error);- return clientIp; // Fallback to unencrypted+ const cipher = createCipheriv(LEGACY_ALGORITHM, key, iv);+ const encrypted = Buffer.concat([cipher.update(clientIp, "utf8"), cipher.final()]);+ return `${iv.toString("hex")}:${encrypted.toString("hex")}`;+ } catch {+ return null;+ }+}++/**+ * Create a short-lived, authenticated client-IP assertion.+ * Format: v1:<unix timestamp seconds>:<12-byte nonce hex>:<ciphertext + tag hex>+ */+export function createClientIpAssertion(+ clientIp: string,+ nowMs = Date.now(),+ nonce = randomBytes(12)+): string | null {+ const key = encryptionKey("MCP_CLIENT_IP_ASSERTION_KEY");+ if (!key) {+ if (!reportedInvalidAssertionKey) {+ reportedInvalidAssertionKey = true;+ console.error(+ "MCP_CLIENT_IP_ASSERTION_KEY is missing or invalid; client IP assertions are disabled."+ );+ }+ return null;+ }+ if (nonce.length !== 12 || isIP(clientIp) === 0) return null;++ try {+ const timestamp = Math.floor(nowMs / 1000).toString();+ const aad = `${ASSERTION_VERSION}:${timestamp}`;+ const cipher = createCipheriv(ASSERTION_ALGORITHM, key, nonce);+ cipher.setAAD(Buffer.from(aad, "utf8"));+ const ciphertext = Buffer.concat([cipher.update(clientIp, "utf8"), cipher.final()]);+ const ciphertextAndTag = Buffer.concat([ciphertext, cipher.getAuthTag()]);+ return `${aad}:${nonce.toString("hex")}:${ciphertextAndTag.toString("hex")}`;+ } catch {+ return null;}}@@ -40,7 +78,15 @@ export function generateHeaders(context: ClientContext): Record<string, string>};if (context.clientIp) {- headers["mcp-client-ip"] = encryptClientIp(context.clientIp);+ const assertion = createClientIpAssertion(context.clientIp);+ if (assertion) {+ headers["mcp-client-ip-assertion"] = assertion;++ // Producer-first rollout compatibility. Removal is tracked by CTX7-2536.+ const key = encryptionKey("CLIENT_IP_ENCRYPTION_KEY");+ const legacyValue = key ? encryptLegacyClientIp(context.clientIp, key) : null;+ if (legacyValue) headers["mcp-client-ip"] = legacyValue;+ }}if (context.sessionId) {headers["mcp-session-id"] = context.sessionId;diff --git a/packages/mcp/test/client-ip.test.ts b/packages/mcp/test/client-ip.test.tsdeleted file mode 100644index 6b415297..00000000--- a/packages/mcp/test/client-ip.test.ts+++ /dev/null@@ -1,96 +0,0 @@-import { describe, expect, test } from "vitest";-import type express from "express";-import { getClientIp, isPrivateOrLocalIp } from "../src/lib/client-ip.js";--describe("isPrivateOrLocalIp", () => {- test.each([- "10.0.0.1",- "192.168.1.1",- "172.16.0.1",- "127.0.0.1",- "169.254.1.1",- "100.64.0.1",- "100.127.255.255",- "::1",- "0::1",- "0:0:0:0:0:0:0:1",- "fe80::1",- "FE80::1",- "febf::1",- "fc00::1",- "fd12::1",- "fdff::1",- "::ffff:127.0.0.1",- ])("treats %s as private or local", (ip) => {- expect(isPrivateOrLocalIp(ip)).toBe(true);- });-- test.each([- "8.8.8.8",- "203.0.113.10",- "100.63.255.255",- "100.128.0.1",- "2001:db8::1",- "1::1",- "::11",- "::ffff:8.8.8.8",- // abbreviated first hextets that look like fe80::/10 or fc00::/7 but are not- "fe8::1",- "fc::1",- "fd0::1",- // fec0::/10 (deprecated site-local) is outside fe80::/10- "fec0::1",- ])("treats %s as public", (ip) => {- expect(isPrivateOrLocalIp(ip)).toBe(false);- });-});--describe("getClientIp", () => {- function makeRequest(headers: Record<string, string | string[]>): express.Request {- return {- headers,- socket: undefined,- } as express.Request;- }-- test("skips loopback and link-local entries in X-Forwarded-For", () => {- const req = makeRequest({- "x-forwarded-for": "127.0.0.1, 8.8.8.8",- });-- expect(getClientIp(req)).toBe("8.8.8.8");- });-- test("skips RFC1918 and returns the first public forwarded IP", () => {- const req = makeRequest({- "x-forwarded-for": "10.0.0.1, 192.168.0.2, 203.0.113.10",- });-- expect(getClientIp(req)).toBe("203.0.113.10");- });-- test("skips IPv6 loopback and private ranges in X-Forwarded-For", () => {- const req = makeRequest({- "x-forwarded-for": "::1, fe80::1, fc00::1, 2001:db8::5",- });-- expect(getClientIp(req)).toBe("2001:db8::5");- });-- test("falls back to the first forwarded IP when all entries are private", () => {- const req = makeRequest({- "x-forwarded-for": "127.0.0.1, 10.0.0.1",- });-- expect(getClientIp(req)).toBe("127.0.0.1");- });-- test("uses socket remote address when X-Forwarded-For is absent", () => {- const req = {- headers: {},- socket: { remoteAddress: "::ffff:203.0.113.10" },- } as express.Request;-- expect(getClientIp(req)).toBe("203.0.113.10");- });-});diff --git a/packages/mcp/test/encryption.test.ts b/packages/mcp/test/encryption.test.tsnew file mode 100644index 00000000..1514904c--- /dev/null+++ b/packages/mcp/test/encryption.test.ts@@ -0,0 +1,52 @@+import { afterEach, beforeEach, describe, expect, test } from "vitest";+import { createClientIpAssertion, generateHeaders } from "../src/lib/encryption.js";++const KEY = "0123456789abcdef".repeat(4);+const NOW_MS = 1_788_000_000_000;+const NONCE = Buffer.from("00112233445566778899aabb", "hex");++describe("client IP assertions", () => {+ beforeEach(() => {+ process.env.MCP_CLIENT_IP_ASSERTION_KEY = KEY;+ process.env.CLIENT_IP_ENCRYPTION_KEY = KEY;+ });++ afterEach(() => {+ delete process.env.MCP_CLIENT_IP_ASSERTION_KEY;+ delete process.env.CLIENT_IP_ENCRYPTION_KEY;+ });++ test("creates a versioned AES-GCM assertion", () => {+ const value = createClientIpAssertion("203.0.113.99", NOW_MS, NONCE);++ expect(value).toBe(+ "v1:1788000000:00112233445566778899aabb:8f761fbf38cf8e7ea8dd992aab5e3db53b0f318adfe3d3207e8675d4"+ );+ });++ test("emits authenticated and rollout-compatible headers", () => {+ const headers = generateHeaders({ clientIp: "203.0.113.99" });++ expect(headers["mcp-client-ip-assertion"]).toMatch(/^v1:/);+ expect(headers["mcp-client-ip"]).toMatch(/^[0-9a-f]{32}:[0-9a-f]+$/);+ });++ test("fails closed instead of sending plaintext when the key is absent or invalid", () => {+ delete process.env.MCP_CLIENT_IP_ASSERTION_KEY;+ delete process.env.CLIENT_IP_ENCRYPTION_KEY;+ expect(+ generateHeaders({ clientIp: "203.0.113.99" })["mcp-client-ip-assertion"]+ ).toBeUndefined();+ expect(generateHeaders({ clientIp: "203.0.113.99" })["mcp-client-ip"]).toBeUndefined();++ process.env.MCP_CLIENT_IP_ASSERTION_KEY = "not-a-key";+ expect(createClientIpAssertion("203.0.113.99", NOW_MS, NONCE)).toBeNull();+ });++ test.each(["999.999.999.999", "1:2:3", "attacker-selected-bucket"])(+ "refuses to sign an invalid IP address (%s)",+ (value) => {+ expect(createClientIpAssertion(value, NOW_MS, NONCE)).toBeNull();+ }+ );+});diff --git a/packages/mcp/test/integration.test.ts b/packages/mcp/test/integration.test.tsindex 08cdb6c7..4e479a82 100644--- a/packages/mcp/test/integration.test.ts+++ b/packages/mcp/test/integration.test.ts@@ -4,6 +4,7 @@ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/client";import { StdioClientTransport, getDefaultEnvironment } from "@modelcontextprotocol/client/stdio";import { execSync } from "node:child_process";import { spawn, type ChildProcess } from "node:child_process";+import { createDecipheriv } from "node:crypto";import http from "node:http";import { fileURLToPath } from "node:url";import path from "node:path";@@ -19,6 +20,23 @@ const PKG_ROOT = path.resolve(fileURLToPath(new URL(".", import.meta.url)), ".."const DIST = path.join(PKG_ROOT, "dist", "index.js");const BASE_PORT = 43117;const STUB_DOCS = "stub docs text";+const CLIENT_IP_ASSERTION_KEY = "0123456789abcdef".repeat(4);++function decryptClientIpAssertion(value: string): string {+ const [version, timestamp, nonceHex, ciphertextAndTagHex] = value.split(":");+ const ciphertextAndTag = Buffer.from(ciphertextAndTagHex, "hex");+ const decipher = createDecipheriv(+ "aes-256-gcm",+ Buffer.from(CLIENT_IP_ASSERTION_KEY, "hex"),+ Buffer.from(nonceHex, "hex")+ );+ decipher.setAAD(Buffer.from(`${version}:${timestamp}`, "utf8"));+ decipher.setAuthTag(ciphertextAndTag.subarray(-16));+ return Buffer.concat([+ decipher.update(ciphertextAndTag.subarray(0, -16)),+ decipher.final(),+ ]).toString("utf8");+}interface RecordedRequest {path: string;@@ -96,7 +114,12 @@ beforeAll(async () => {const stubUrl = await startStubApi();// getDefaultEnvironment() inherits only safe vars, so a real// CONTEXT7_API_KEY in the parent shell cannot leak into the children.- childEnv = { ...getDefaultEnvironment(), CONTEXT7_API_URL: stubUrl };+ childEnv = {+ ...getDefaultEnvironment(),+ CONTEXT7_API_URL: stubUrl,+ MCP_CLIENT_IP_ASSERTION_KEY: CLIENT_IP_ASSERTION_KEY,+ CLIENT_IP_ENCRYPTION_KEY: CLIENT_IP_ASSERTION_KEY,+ };({ child: httpChild, url: httpUrl } = await startHttpChild());}, 120_000);@@ -115,7 +138,12 @@ async function connect(transportKind: "http" | "stdio", era: "modern" | "legacy"? new StreamableHTTPClientTransport(new URL(httpUrl), {// Parseable UA so the legacy-HTTP fallback path (no protocol client// info) is observable; modern clients must beat it via the envelope.- requestInit: { headers: { "user-agent": "ua-fallback/9.9.9" } },+ requestInit: {+ headers: {+ "user-agent": "ua-fallback/9.9.9",+ "x-forwarded-for": "attacker-selected-bucket, 203.0.113.77",+ },+ },}): new StdioClientTransport({ command: process.execPath, args: [DIST], env: childEnv });await client.connect(transport);@@ -224,6 +252,15 @@ describe.each([expect(apiCalls[0].query.get("libraryId")).toBe("/vercel/next.js");expect(apiCalls[0].query.get("query")).toBe("app router");expect(apiCalls[0].headers["x-context7-transport"]).toBe(transportKind);+ if (transportKind === "http") {+ expect(apiCalls[0].headers["mcp-client-ip-assertion"]).toMatch(/^v1:/);+ expect(+ decryptClientIpAssertion(apiCalls[0].headers["mcp-client-ip-assertion"] as string)+ ).toBe("203.0.113.77");+ expect(apiCalls[0].headers["mcp-client-ip"]).toMatch(/^[0-9a-f]{32}:[0-9a-f]+$/);+ } else {+ expect(apiCalls[0].headers["mcp-client-ip-assertion"]).toBeUndefined();+ }});test("calls resolve-library-id end to end", async () => {