:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(mcp): sign the end user ip for the activity log (#105747)
Yasen2b50f531e490
diff --git a/services/mcp/.env.example b/services/mcp/.env.exampleindex e4b9ad09c706..d1566c544ecc 100644--- a/services/mcp/.env.example+++ b/services/mcp/.env.example@@ -48,3 +48,17 @@ POSTHOG_ANALYTICS_HOST=http://localhost:8010# - For local dev only, any 32-byte string is fine. For production,# generate with: `openssl rand -hex 32`.MCP_SIGNED_STATE_KEY=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa++# End user IP for the activity log. The PostHog API sees the Hono pod as the caller, so the+# runtime signs the end user IP onto every API call. Each value is a comma-separated key list,+# newest first. Leave them unset in local dev, where the API sees the real client anyway.+#+# - MCP_CLIENT_IP_SIGNING_KEYS (Hono): signs for the API. Must match the API's+# MCP_CLIENT_IP_SIGNING_KEYS.+# - MCP_EDGE_CLIENT_IP_SIGNING_KEYS (Hono): verifies the IP the Worker signed.+# - MCP_EDGE_CLIENT_IP_SIGNING_KEYS_US / _EU (Worker secrets): sign the Cloudflare client IP for+# the Hono runtime of that region. Must match that region's MCP_EDGE_CLIENT_IP_SIGNING_KEYS.+# MCP_CLIENT_IP_SIGNING_KEYS=+# MCP_EDGE_CLIENT_IP_SIGNING_KEYS=+# MCP_EDGE_CLIENT_IP_SIGNING_KEYS_US=+# MCP_EDGE_CLIENT_IP_SIGNING_KEYS_EU=diff --git a/services/mcp/ARCHITECTURE.md b/services/mcp/ARCHITECTURE.mdindex 8fb8da068621..096e2246d574 100644--- a/services/mcp/ARCHITECTURE.md+++ b/services/mcp/ARCHITECTURE.md@@ -59,6 +59,17 @@ if (url.pathname.startsWith('/mcp')) {`RequestProperties` (the parsed headers and query params for a request) is defined in `src/lib/request-properties.ts` and shared by both runtimes.+### End user IP++The PostHog API sees the Hono pod as the caller, so the activity log would record that pod's address.+The end user IP travels as a signed header on each hop (`src/lib/client-ip-signature.ts`, the same HMAC format as Django's `verify_signed_client_ip`):++1. The Worker removes any client-sent IP headers, signs `CF-Connecting-IP` with the key list of the target region, and sends `X-PostHog-Edge-Client-IP*` to Hono.+2. Hono resolves the IP once per request (`src/hono/client-ip.ts`). A valid edge signature gives the signed IP. Otherwise Hono uses the rightmost `X-Forwarded-For` entry, which Envoy writes. When that entry is a published Cloudflare address, the request is Worker traffic without a valid signature, so Hono uses no IP.+3. `ApiClient.fetch` signs that IP with a new timestamp on every API call and sends `X-PostHog-MCP-Client-IP*`. Django verifies it and uses it for the activity log only.++Each hop has its own key list, and an empty list turns that hop off. `.env.example` names the variables. The `mcp_client_ip_resolutions_total` counter shows which source Hono used.+### Per-User StateThe Hono runtime keeps per-user session state (active project/organization, region, distinctId) in Redis, namespaced by `userHash` — a PBKDF2 hash of the API token (see `src/lib/utils`), ensuring:diff --git a/services/mcp/src/api/client.ts b/services/mcp/src/api/client.tsindex f321011038ba..26fbb3a97890 100644--- a/services/mcp/src/api/client.ts+++ b/services/mcp/src/api/client.ts@@ -1,6 +1,7 @@import { createParser } from 'eventsource-parser'import { z } from 'zod'+import { MCP_CLIENT_IP_HEADERS, signedClientIpHeaders } from '@/lib/client-ip-signature'import { getUserAgent } from '@/lib/constants'import {ErrorCode,@@ -186,6 +187,8 @@ export interface ApiConfig {taskId?: string | undefined/** One tool call's stated intent, forwarded as `x-posthog-intent`. Set it through `withIntent`. */intent?: string | undefined+ clientIp?: string | undefined+ clientIpSigningKeys?: string[] | undefined}// Matches ACTIVITY_LOG_INTENT_MAX_LENGTH in posthog/models/activity_logging/utils.py.@@ -276,6 +279,14 @@ export class ApiClient {'x-posthog-intent': intentHeaderValue(this.config.intent),}),'X-PostHog-Client': 'mcp',+ // Signed per call, so a long tool call cannot outlive the signature's time window.+ ...(this.config.clientIp && this.config.clientIpSigningKeys+ ? await signedClientIpHeaders(+ MCP_CLIENT_IP_HEADERS,+ this.config.clientIpSigningKeys,+ this.config.clientIp+ )+ : {}),}if (options?.body) {defaultHeaders['Content-Type'] = 'application/json'diff --git a/services/mcp/src/hono/client-ip.ts b/services/mcp/src/hono/client-ip.tsnew file mode 100644index 000000000000..661a1b362b27--- /dev/null+++ b/services/mcp/src/hono/client-ip.ts@@ -0,0 +1,78 @@+import { BlockList, isIP } from 'node:net'++import { EDGE_CLIENT_IP_HEADERS, type SignedClientIpOutcome, verifySignedClientIp } from '@/lib/client-ip-signature'++export type ClientIpSource = 'edge' | 'forwarded' | 'cloudflare' | 'none'++// https://www.cloudflare.com/ips/, as of September 2026. Worker subrequests reach the ingress from+// these ranges, so an unsigned request from one of them is Worker traffic that lost its signature.+const CLOUDFLARE_RANGES: [string, number, 'ipv4' | 'ipv6'][] = [+ ['173.245.48.0', 20, 'ipv4'],+ ['103.21.244.0', 22, 'ipv4'],+ ['103.22.200.0', 22, 'ipv4'],+ ['103.31.4.0', 22, 'ipv4'],+ ['141.101.64.0', 18, 'ipv4'],+ ['108.162.192.0', 18, 'ipv4'],+ ['190.93.240.0', 20, 'ipv4'],+ ['188.114.96.0', 20, 'ipv4'],+ ['197.234.240.0', 22, 'ipv4'],+ ['198.41.128.0', 17, 'ipv4'],+ ['162.158.0.0', 15, 'ipv4'],+ ['104.16.0.0', 13, 'ipv4'],+ ['104.24.0.0', 14, 'ipv4'],+ ['172.64.0.0', 13, 'ipv4'],+ ['131.0.72.0', 22, 'ipv4'],+ ['2400:cb00::', 32, 'ipv6'],+ ['2606:4700::', 32, 'ipv6'],+ ['2803:f800::', 32, 'ipv6'],+ ['2405:b500::', 32, 'ipv6'],+ ['2405:8100::', 32, 'ipv6'],+ ['2a06:98c0::', 29, 'ipv6'],+ ['2c0f:f248::', 32, 'ipv6'],+]++const cloudflareAddresses = new BlockList()+for (const [network, prefix, family] of CLOUDFLARE_RANGES) {+ cloudflareAddresses.addSubnet(network, prefix, family)+}++export interface ResolvedClientIp {+ ip: string | undefined+ source: ClientIpSource+ edgeOutcome: SignedClientIpOutcome | 'absent'+}++/**+ * Envoy writes the rightmost X-Forwarded-For entry, so a client cannot forge it. Worker traffic+ * reaches the ingress from a Cloudflare range, so a request from one with no valid edge signature+ * gives no IP.+ */+export async function resolveClientIp(+ headers: Headers,+ edgeSigningKeys: string[],+ nowSeconds?: number+): Promise<ResolvedClientIp> {+ const edgeIp = headers.get(EDGE_CLIENT_IP_HEADERS.ip)+ const edgeTimestamp = headers.get(EDGE_CLIENT_IP_HEADERS.timestamp)+ const edgeSignature = headers.get(EDGE_CLIENT_IP_HEADERS.signature)+ let edgeOutcome: ResolvedClientIp['edgeOutcome'] = 'absent'+ if (edgeIp !== null || edgeTimestamp !== null || edgeSignature !== null) {+ edgeOutcome = await verifySignedClientIp(edgeIp, edgeTimestamp, edgeSignature, edgeSigningKeys, nowSeconds)+ if (edgeOutcome === 'valid' && edgeIp && isIP(edgeIp)) {+ return { ip: edgeIp, source: 'edge', edgeOutcome }+ }+ if (edgeOutcome === 'valid') {+ edgeOutcome = 'invalid_input'+ }+ }++ const forwardedIp = headers.get('x-forwarded-for')?.split(',').at(-1)?.trim()+ const family = forwardedIp ? isIP(forwardedIp) : 0+ if (forwardedIp && family) {+ if (cloudflareAddresses.check(forwardedIp, family === 6 ? 'ipv6' : 'ipv4')) {+ return { ip: undefined, source: 'cloudflare', edgeOutcome }+ }+ return { ip: forwardedIp, source: 'forwarded', edgeOutcome }+ }+ return { ip: undefined, source: 'none', edgeOutcome }+}diff --git a/services/mcp/src/hono/constants.ts b/services/mcp/src/hono/constants.tsindex 9e746277d92c..8f4e434f0a2a 100644--- a/services/mcp/src/hono/constants.ts+++ b/services/mcp/src/hono/constants.ts@@ -1,3 +1,4 @@+import { parseSigningKeys } from '@/lib/client-ip-signature'import type { Env } from '@/tools/types'export const MCP_EXEC_SKILLS_FEATURE_FLAG = 'mcp-exec-skills'@@ -17,6 +18,14 @@ export {OAUTH_SCOPES_SUPPORTED,} from '@/lib/constants'+export function getEdgeClientIpSigningKeys(): string[] {+ return parseSigningKeys(process.env.MCP_EDGE_CLIENT_IP_SIGNING_KEYS)+}++export function getClientIpSigningKeys(): string[] {+ return parseSigningKeys(process.env.MCP_CLIENT_IP_SIGNING_KEYS)+}+export function getEnv(): Env {const extras: Record<string, string | undefined> = {}if (process.env.TEST) {diff --git a/services/mcp/src/hono/metrics.ts b/services/mcp/src/hono/metrics.tsindex ba3a0e8bcb17..adee38d8f50f 100644--- a/services/mcp/src/hono/metrics.ts+++ b/services/mcp/src/hono/metrics.ts@@ -135,6 +135,12 @@ export const confirmedActionRuntimeInstalled = new Gauge({help: 'Whether the typed-confirm runtime was installed successfully at boot (1 = yes, 0 = misconfigured / MCP_SIGNED_STATE_KEY missing).',})+export const clientIpResolutionsTotal = new Counter({+ name: 'mcp_client_ip_resolutions_total',+ help: 'How the Hono runtime found the end user IP it signs for the PostHog API, by source and edge signature outcome.',+ labelNames: ['source', 'edge_outcome'] as const,+})+export const contextMillRevalidationDurationSeconds = new Histogram({name: 'mcp_context_mill_revalidation_duration_seconds',help: 'Context-mill resource revalidation duration.',diff --git a/services/mcp/src/hono/request-context.ts b/services/mcp/src/hono/request-context.tsindex b0e4d271217e..10f03c529779 100644--- a/services/mcp/src/hono/request-context.ts+++ b/services/mcp/src/hono/request-context.ts@@ -17,7 +17,7 @@ import { hash } from '@/lib/utils'import type { Context, Env, SessionScopedState, State } from '@/tools/types'import { RedisCache, type RedisLike } from './cache/RedisCache'-import { getCustomApiBaseUrl, getPublicBaseUrl } from './constants'+import { getClientIpSigningKeys, getCustomApiBaseUrl, getPublicBaseUrl } from './constants'import {buildMCPRequestContext,buildMCPSessionAnalyticsProperties,@@ -138,6 +138,8 @@ export class RequestContext {// reach the API unattributed.oauthClientName: await this.readCachedOAuthClientName(),taskId: this.props.taskId,+ clientIp: this.props.clientIp,+ clientIpSigningKeys: getClientIpSigningKeys(),})}return this.apiInstancediff --git a/services/mcp/src/hono/request-utils.ts b/services/mcp/src/hono/request-utils.tsindex a172bd53dcb4..a32e5e37521b 100644--- a/services/mcp/src/hono/request-utils.ts+++ b/services/mcp/src/hono/request-utils.ts@@ -13,7 +13,9 @@ import { parseRequestProtocolMeta } from '@/lib/stateless-protocol'import { extractBearerToken, sanitizeHeaderValue } from '@/lib/utils'import { trackAuthFailure } from './analytics'-import { authFailuresTotal } from './metrics'+import { resolveClientIp } from './client-ip'+import { getEdgeClientIpSigningKeys } from './constants'+import { authFailuresTotal, clientIpResolutionsTotal } from './metrics'import type { HonoCtx } from './types'const InitializeParamsSchema = z.object({@@ -104,6 +106,9 @@ export async function authenticateAndParse(props.mcpSessionId = sanitizeHeaderValue(c.req.header('mcp-session-id') || undefined)props.mcpConversationId = sanitizeHeaderValue(c.req.header('mcp-conversation-id') || undefined)props.region = props.region || getRegionFromRequest(c.req.raw) || undefined+ const clientIp = await resolveClientIp(c.req.raw.headers, getEdgeClientIpSigningKeys())+ clientIpResolutionsTotal.inc({ source: clientIp.source, edge_outcome: clientIp.edgeOutcome })+ props.clientIp = clientIp.ipif (new URL(c.req.url).searchParams.get('_deprecated') === 'sse') {props.viaSseRedirect = true}diff --git a/services/mcp/src/lib/client-ip-signature.ts b/services/mcp/src/lib/client-ip-signature.tsnew file mode 100644index 000000000000..c0fc98e98adf--- /dev/null+++ b/services/mcp/src/lib/client-ip-signature.ts@@ -0,0 +1,108 @@+// The format matches `verify_signed_client_ip` in posthog/middleware.py: lowercase hex+// HMAC-SHA256 of `${ip}:${unixSeconds}`. A change to it must also go to Django, or every signature+// fails there.++export const SIGNED_CLIENT_IP_MAX_AGE_SECONDS = 60+export const SIGNED_CLIENT_IP_MAX_CLOCK_SKEW_SECONDS = 5++export interface SignedClientIpHeaderNames {+ ip: string+ timestamp: string+ signature: string+}++export const EDGE_CLIENT_IP_HEADERS: SignedClientIpHeaderNames = {+ ip: 'x-posthog-edge-client-ip',+ timestamp: 'x-posthog-edge-client-ip-timestamp',+ signature: 'x-posthog-edge-client-ip-signature',+}++export const MCP_CLIENT_IP_HEADERS: SignedClientIpHeaderNames = {+ ip: 'x-posthog-mcp-client-ip',+ timestamp: 'x-posthog-mcp-client-ip-timestamp',+ signature: 'x-posthog-mcp-client-ip-signature',+}++export type SignedClientIpOutcome =+ | 'valid'+ | 'not_configured'+ | 'timestamp_out_of_window'+ | 'invalid_input'+ | 'bad_signature'++export function parseSigningKeys(value: string | undefined): string[] {+ return (value ?? '')+ .split(',')+ .map((key) => key.trim())+ .filter(Boolean)+}++const encoder = new TextEncoder()++function hmacKey(key: string, usage: 'sign' | 'verify'): Promise<CryptoKey> {+ return crypto.subtle.importKey('raw', encoder.encode(key), { name: 'HMAC', hash: 'SHA-256' }, false, [usage])+}++function hexToBytes(hex: string): Uint8Array<ArrayBuffer> | null {+ if (hex.length % 2 !== 0 || !/^[0-9a-f]*$/i.test(hex)) {+ return null+ }+ const bytes = new Uint8Array(hex.length / 2)+ for (let i = 0; i < bytes.length; i++) {+ bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16)+ }+ return bytes+}++export async function signClientIp(key: string, ip: string, timestamp: string): Promise<string> {+ const signature = await crypto.subtle.sign('HMAC', await hmacKey(key, 'sign'), encoder.encode(`${ip}:${timestamp}`))+ return Array.from(new Uint8Array(signature), (byte) => byte.toString(16).padStart(2, '0')).join('')+}++export async function signedClientIpHeaders(+ names: SignedClientIpHeaderNames,+ keys: string[],+ ip: string,+ nowSeconds: number = Math.floor(Date.now() / 1000)+): Promise<Record<string, string>> {+ const [newestKey] = keys+ if (!newestKey) {+ return {}+ }+ const timestamp = String(nowSeconds)+ return {+ [names.ip]: ip,+ [names.timestamp]: timestamp,+ [names.signature]: await signClientIp(newestKey, ip, timestamp),+ }+}++export async function verifySignedClientIp(+ ip: string | null,+ timestamp: string | null,+ signature: string | null,+ keys: string[],+ nowSeconds: number = Math.floor(Date.now() / 1000)+): Promise<SignedClientIpOutcome> {+ if (keys.length === 0) {+ return 'not_configured'+ }+ if (!ip || !timestamp || !signature || timestamp.length > 12 || !/^[0-9]+$/.test(timestamp)) {+ return 'invalid_input'+ }+ const ageSeconds = nowSeconds - Number(timestamp)+ if (ageSeconds < -SIGNED_CLIENT_IP_MAX_CLOCK_SKEW_SECONDS || ageSeconds > SIGNED_CLIENT_IP_MAX_AGE_SECONDS) {+ return 'timestamp_out_of_window'+ }+ const provided = hexToBytes(signature)+ if (!provided) {+ return 'bad_signature'+ }+ const message = encoder.encode(`${ip}:${timestamp}`)+ for (const key of keys) {+ if (await crypto.subtle.verify('HMAC', await hmacKey(key, 'verify'), provided, message)) {+ return 'valid'+ }+ }+ return 'bad_signature'+}diff --git a/services/mcp/src/lib/request-properties.ts b/services/mcp/src/lib/request-properties.tsindex 33a99d7ebc7d..ef4b6a432273 100644--- a/services/mcp/src/lib/request-properties.ts+++ b/services/mcp/src/lib/request-properties.ts@@ -40,6 +40,7 @@ export type RequestProperties = {featureFlagOverrides?: string | undefined// Caller-supplied tool denylist. Merged with the server's own excludes (switch tools, etc).excludeTools?: string[] | undefined+ clientIp?: string | undefined}export type ClientInfo = {diff --git a/services/mcp/src/proxy.ts b/services/mcp/src/proxy.tsindex c3d7c6d7e936..39fcd50ea576 100644--- a/services/mcp/src/proxy.ts+++ b/services/mcp/src/proxy.ts@@ -1,4 +1,10 @@import { ApiClient } from '@/api/client'+import {+ EDGE_CLIENT_IP_HEADERS,+ MCP_CLIENT_IP_HEADERS,+ parseSigningKeys,+ signedClientIpHeaders,+} from '@/lib/client-ip-signature'import { env } from '@/lib/env'import type { CloudRegion } from '@/tools/types'@@ -77,7 +83,28 @@ export async function resolveProxyRegion(return 'us'}-export function proxyToHono(request: Request, region: CloudRegion): Promise<Response> {+export async function honoRequestHeaders(incoming: Headers, region: CloudRegion): Promise<Headers> {+ const headers = new Headers(incoming)+ for (const name of [...Object.values(EDGE_CLIENT_IP_HEADERS), ...Object.values(MCP_CLIENT_IP_HEADERS)]) {+ headers.delete(name)+ }+ // Cloudflare sets CF-Connecting-IP on every request that reaches the Worker, and replaces any+ // value the client sent.+ const clientIp = incoming.get('cf-connecting-ip')+ const keys = parseSigningKeys(+ region === 'eu' ? env.MCP_EDGE_CLIENT_IP_SIGNING_KEYS_EU : env.MCP_EDGE_CLIENT_IP_SIGNING_KEYS_US+ )+ if (clientIp) {+ for (const [name, value] of Object.entries(+ await signedClientIpHeaders(EDGE_CLIENT_IP_HEADERS, keys, clientIp)+ )) {+ headers.set(name, value)+ }+ }+ return headers+}++export async function proxyToHono(request: Request, region: CloudRegion): Promise<Response> {const targetBase = getHonoTargetUrl(region)const targetUrl = new URL(request.url)const target = new URL(targetBase)@@ -87,7 +114,7 @@ export function proxyToHono(request: Request, region: CloudRegion): Promise<Respreturn fetch(targetUrl.toString(), {method: request.method,- headers: request.headers,+ headers: await honoRequestHeaders(request.headers, region),body: request.body,})}diff --git a/services/mcp/tests/unit/api-client.test.ts b/services/mcp/tests/unit/api-client.test.tsindex e507b8157359..257f8dbe4fe0 100644--- a/services/mcp/tests/unit/api-client.test.ts+++ b/services/mcp/tests/unit/api-client.test.ts@@ -1,6 +1,7 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { ApiClient } from '@/api/client'+import { MCP_CLIENT_IP_HEADERS, verifySignedClientIp } from '@/lib/client-ip-signature'import { USER_AGENT, getUserAgent } from '@/lib/constants'import { PostHogTransportError } from '@/lib/errors'import { getToolByName } from '@/shared/test-utils'@@ -241,6 +242,37 @@ describe('ApiClient', () => {vi.unstubAllGlobals()})+ it.each([+ ['an IP and a key', { clientIp: '203.0.113.7', clientIpSigningKeys: ['mcp-key', 'old-key'] }, '203.0.113.7'],+ ['an IP and no key', { clientIp: '203.0.113.7', clientIpSigningKeys: [] }, null],+ ['a key and no IP', { clientIpSigningKeys: ['mcp-key'] }, null],+ ] as const)('signs the end user IP for the activity log given %s', async (_label, extraConfig, expectedIp) => {+ const mockFetch = vi.fn().mockResolvedValue(new Response(JSON.stringify({}), { status: 200 }))+ vi.stubGlobal('fetch', mockFetch)++ const client = new ApiClient({+ apiToken: 'test-token-123',+ baseUrl: 'https://example.com',+ ...extraConfig,+ clientIpSigningKeys: [...extraConfig.clientIpSigningKeys],+ })+ await (client as any).fetch('https://example.com/api/test', { method: 'GET' })++ const headers = mockFetch.mock.calls[0]![1].headers+ expect(headers[MCP_CLIENT_IP_HEADERS.ip] ?? null).toBe(expectedIp)+ if (expectedIp) {+ const outcome = await verifySignedClientIp(+ headers[MCP_CLIENT_IP_HEADERS.ip],+ headers[MCP_CLIENT_IP_HEADERS.timestamp],+ headers[MCP_CLIENT_IP_HEADERS.signature],+ ['mcp-key']+ )+ expect(outcome).toBe('valid')+ }++ vi.unstubAllGlobals()+ })+it.each([['both ids set',diff --git a/services/mcp/tests/unit/client-ip-signature.test.ts b/services/mcp/tests/unit/client-ip-signature.test.tsnew file mode 100644index 000000000000..462a0a81d59f--- /dev/null+++ b/services/mcp/tests/unit/client-ip-signature.test.ts@@ -0,0 +1,157 @@+import { afterEach, describe, expect, it, vi } from 'vitest'++import { resolveClientIp } from '@/hono/client-ip'+import {+ EDGE_CLIENT_IP_HEADERS,+ MCP_CLIENT_IP_HEADERS,+ signClientIp,+ signedClientIpHeaders,+ verifySignedClientIp,+} from '@/lib/client-ip-signature'+import { honoRequestHeaders } from '@/proxy'++const KEY = 'managed-proxy-test-key'+const OLD_KEY = 'managed-proxy-old-key'+const NOW = 1_800_000_000+const CLIENT_IP = '203.0.113.7'+// The same vector as MANAGED_PROXY_KNOWN_ANSWER_SIGNATURE in posthog/test/test_middleware.py, so+// the TypeScript signer and the Django verifier cannot drift apart.+const KNOWN_ANSWER_SIGNATURE = 'f825f520f1c3a2ef243b6a055a528b8ce94a3b4b9110bb6f3c2b568191e7b717'++async function edgeHeaders(ip: string, key: string, timestamp: number = NOW): Promise<Record<string, string>> {+ return signedClientIpHeaders(EDGE_CLIENT_IP_HEADERS, [key], ip, timestamp)+}++describe('client IP signatures', () => {+ afterEach(() => {+ vi.unstubAllEnvs()+ })++ it('signs in the format Django verifies', async () => {+ expect(await signClientIp(KEY, CLIENT_IP, String(NOW))).toBe(KNOWN_ANSWER_SIGNATURE)+ })++ it.each([+ ['the known answer', CLIENT_IP, String(NOW), KNOWN_ANSWER_SIGNATURE, [KEY], 'valid'],+ ['uppercase hex', CLIENT_IP, String(NOW), KNOWN_ANSWER_SIGNATURE.toUpperCase(), [KEY], 'valid'],+ ['an older key in the list', CLIENT_IP, String(NOW), KNOWN_ANSWER_SIGNATURE, [OLD_KEY, KEY], 'valid'],+ ['the oldest timestamp', CLIENT_IP, String(NOW), KNOWN_ANSWER_SIGNATURE, [KEY], 'valid', NOW + 60],+ ['the newest timestamp', CLIENT_IP, String(NOW), KNOWN_ANSWER_SIGNATURE, [KEY], 'valid', NOW - 5],+ [+ 'an expired timestamp',+ CLIENT_IP,+ String(NOW),+ KNOWN_ANSWER_SIGNATURE,+ [KEY],+ 'timestamp_out_of_window',+ NOW + 61,+ ],+ [+ 'a future timestamp',+ CLIENT_IP,+ String(NOW),+ KNOWN_ANSWER_SIGNATURE,+ [KEY],+ 'timestamp_out_of_window',+ NOW - 6,+ ],+ ['an unknown key', CLIENT_IP, String(NOW), KNOWN_ANSWER_SIGNATURE, [OLD_KEY], 'bad_signature'],+ ['a signature for another IP', '192.0.2.1', String(NOW), KNOWN_ANSWER_SIGNATURE, [KEY], 'bad_signature'],+ ['a signature that is not hex', CLIENT_IP, String(NOW), 'z'.repeat(64), [KEY], 'bad_signature'],+ ['a fractional timestamp', CLIENT_IP, `${NOW}.0`, KNOWN_ANSWER_SIGNATURE, [KEY], 'invalid_input'],+ ['an oversized timestamp', CLIENT_IP, '1'.repeat(5000), KNOWN_ANSWER_SIGNATURE, [KEY], 'invalid_input'],+ ['no signature', CLIENT_IP, String(NOW), null, [KEY], 'invalid_input'],+ ['no key', CLIENT_IP, String(NOW), KNOWN_ANSWER_SIGNATURE, [], 'not_configured'],+ ] as const)('verifies %s', async (_label, ip, timestamp, signature, keys, expected, now = NOW) => {+ expect(await verifySignedClientIp(ip, timestamp, signature, [...keys], now)).toBe(expected)+ })++ describe('resolveClientIp', () => {+ it.each([+ [+ 'the IP the Worker signed',+ async () => ({ ...(await edgeHeaders(CLIENT_IP, KEY)), 'x-forwarded-for': '198.51.100.10' }),+ [KEY],+ { ip: CLIENT_IP, source: 'edge', edgeOutcome: 'valid' },+ ],+ [+ 'no IP, not the Cloudflare forwarded-for, when the Worker signature fails',+ async () => ({ ...(await edgeHeaders(CLIENT_IP, OLD_KEY)), 'x-forwarded-for': '162.158.10.20' }),+ [KEY],+ { ip: undefined, source: 'cloudflare', edgeOutcome: 'bad_signature' },+ ],+ [+ 'the forwarded-for entry when a direct caller forges an edge header',+ async () => ({ [EDGE_CLIENT_IP_HEADERS.ip]: '192.0.2.1', 'x-forwarded-for': '198.51.100.10' }),+ [KEY],+ { ip: '198.51.100.10', source: 'forwarded', edgeOutcome: 'invalid_input' },+ ],+ [+ 'no IP when the runtime holds no edge key',+ async () => edgeHeaders(CLIENT_IP, KEY),+ [],+ { ip: undefined, source: 'none', edgeOutcome: 'not_configured' },+ ],+ [+ 'the forwarded-for entry the ingress wrote, not one the client sent',+ async () => ({ 'x-forwarded-for': '192.0.2.99, 198.51.100.10' }),+ [KEY],+ { ip: '198.51.100.10', source: 'forwarded', edgeOutcome: 'absent' },+ ],+ [+ 'no IP for an unsigned request from a Cloudflare address',+ async () => ({ 'x-forwarded-for': '162.158.10.20' }),+ [KEY],+ { ip: undefined, source: 'cloudflare', edgeOutcome: 'absent' },+ ],+ [+ 'no IP for an unsigned request from a Cloudflare IPv6 address',+ async () => ({ 'x-forwarded-for': '2606:4700:10::6816:1' }),+ [KEY],+ { ip: undefined, source: 'cloudflare', edgeOutcome: 'absent' },+ ],+ [+ 'no IP for a malformed forwarded-for entry',+ async () => ({ 'x-forwarded-for': 'not-an-ip' }),+ [KEY],+ { ip: undefined, source: 'none', edgeOutcome: 'absent' },+ ],+ ] as const)('returns %s', async (_label, buildHeaders, keys, expected) => {+ expect(await resolveClientIp(new Headers(await buildHeaders()), [...keys], NOW)).toEqual(expected)+ })+ })++ describe('honoRequestHeaders', () => {+ it('replaces client-sent IP headers with a signature for the region it proxies to', async () => {+ vi.stubEnv('MCP_EDGE_CLIENT_IP_SIGNING_KEYS_EU', `${KEY},${OLD_KEY}`)+ vi.stubEnv('MCP_EDGE_CLIENT_IP_SIGNING_KEYS_US', 'us-only-key')+ const incoming = new Headers({+ 'cf-connecting-ip': CLIENT_IP,+ authorization: 'Bearer phx_test',+ [EDGE_CLIENT_IP_HEADERS.ip]: '192.0.2.1',+ [EDGE_CLIENT_IP_HEADERS.signature]: 'forged',+ [MCP_CLIENT_IP_HEADERS.ip]: '192.0.2.1',+ })++ const headers = await honoRequestHeaders(incoming, 'eu')++ expect(headers.get(EDGE_CLIENT_IP_HEADERS.ip)).toBe(CLIENT_IP)+ expect(headers.get(MCP_CLIENT_IP_HEADERS.ip)).toBeNull()+ expect(headers.get('authorization')).toBe('Bearer phx_test')+ expect(await resolveClientIp(headers, [KEY])).toMatchObject({ ip: CLIENT_IP, source: 'edge' })+ expect(await resolveClientIp(headers, ['us-only-key'])).toMatchObject({ source: 'none' })+ })++ it('sends no IP headers when the region has no key', async () => {+ vi.stubEnv('MCP_EDGE_CLIENT_IP_SIGNING_KEYS_US', '')+ const incoming = new Headers({+ 'cf-connecting-ip': CLIENT_IP,+ [EDGE_CLIENT_IP_HEADERS.ip]: '192.0.2.1',+ })++ const headers = await honoRequestHeaders(incoming, 'us')++ expect([...headers.keys()].filter((name) => name.startsWith('x-posthog-'))).toEqual([])+ })+ })+})diff --git a/services/mcp/types.d.ts b/services/mcp/types.d.tsindex a52af9ab01dc..7acf429e136c 100644--- a/services/mcp/types.d.ts+++ b/services/mcp/types.d.ts@@ -12,6 +12,9 @@ declare namespace Cloudflare {MCP_CAT_PROJECT_ID: string | undefinedMCP_KV: KVNamespace | undefinedMCP_HONO_URL: string | undefined+ // Keys that sign the edge client IP for the Hono runtime of each region (see src/proxy.ts).+ MCP_EDGE_CLIENT_IP_SIGNING_KEYS_US: string | undefined+ MCP_EDGE_CLIENT_IP_SIGNING_KEYS_EU: string | undefined}}