Repository navigation
feat(mcp): add mcp_xff_num_trusted_hops to harden X-Forwarded-For client IP resolution - #31257
Conversation
…ution MCP per-server IP access control reads the client IP from X-Forwarded-For and trusts the leftmost entry. Behind an append-style proxy or load balancer (AWS ALB, nginx with $proxy_add_x_forwarded_for, HAProxy, Envoy, Cloudflare), a client can prepend an arbitrary value to the header, so the leftmost entry is attacker-controllable even when the direct peer is a trusted proxy. An attacker can therefore spoof an internal IP and reach servers marked available_on_public_internet=false. This adds an optional mcp_xff_num_trusted_hops general setting modelled on Envoy's xff_num_trusted_hops. When set to N, the client IP is read N entries from the right of the chain (where N is the number of trusted appending proxies in front of the gateway) instead of the leftmost value, so any entries a client prepends are ignored. It composes with mcp_trusted_proxy_ranges, which still validates the direct peer, and only takes effect once that check passes; without a validated direct peer the gateway keeps failing closed, so hop counting cannot be abused by a direct-to-pod attacker. The chain must contain at least N valid entries or resolution fails closed. Default is unset, preserving existing behaviour.
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
Greptile SummaryAdds an optional
Confidence Score: 5/5Safe to merge. The change is additive and opt-in; existing deployments are unaffected unless mcp_xff_num_trusted_hops is explicitly set. The new setting defaults to unset, preserving all existing behavior. The three runtime states (unset/invalid/valid) are handled by an exhaustive match without fallthrough ambiguity. Invalid or sub-minimum values fail closed rather than silently degrading, and the ge=1 Pydantic constraint rejects them at parse time. Tests cover extraction edge cases, all resolver states, config validation, and integration scenarios with mock requests only. No pre-existing paths are modified. No files require special attention.
|
| Filename | Overview |
|---|---|
| litellm/proxy/auth/ip_address_utils.py | Adds extract_client_ip_from_xff_hops, _resolve_num_trusted_hops (tagged-union result), and extends get_mcp_client_ip with a structural match on the resolved hop-count setting. All three states (unset/invalid/valid) are handled explicitly and fail-closed on misconfiguration. |
| litellm/proxy/_types.py | Adds mcp_xff_num_trusted_hops: Optional[int] field with ge=1 to ConfigGeneralSettings, rejecting sub-minimum values at config-parse time. |
| tests/test_litellm/proxy/auth/test_mcp_ip_filtering.py | Adds comprehensive unit tests covering hop-based extraction, tagged-union resolver states (unset/zero/invalid/valid), ConfigGeneralSettings parse-time rejection, and end-to-end access-control scenarios. All tests are mock-only with no real network calls. |
| litellm/proxy/proxy_server.py | Registers mcp_xff_num_trusted_hops as an Integer type in the dashboard config listing — a one-line addition consistent with similar settings already present. |
| ui/litellm-dashboard/src/lib/http/schema.d.ts | Adds mcp_xff_num_trusted_hops?: number |
Reviews (7): Last reviewed commit: "Merge remote-tracking branch 'origin/lit..." | Re-trigger Greptile
A 0 or negative value is silently treated as disabled, which could leave an operator believing they enabled append-style X-Forwarded-For hardening while client IP resolution stays on the spoofable leftmost value. Emit a warning, consistent with how the module already surfaces invalid CIDR config, so the misconfiguration is visible in logs.
Add a ge=1 bound to the ConfigGeneralSettings field so the update_config_general_settings path rejects 0 and negative values with a clear validation error instead of accepting them, and self-documents the valid range. The runtime warning stays as defense-in-depth for raw-dict config that bypasses model validation.
|
bugbot run |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit a91c92c. Configure here.
|
bugbot run |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit 3401ab7. Configure here.
A present-but-invalid mcp_xff_num_trusted_hops (non-integer, or below 1) previously made _resolve_num_trusted_hops return None, which the caller treated identically to "unset" and silently fell back to the legacy leftmost X-Forwarded-For value. An operator who set the value to harden client IP resolution but typo'd it would get weaker security than before, with no fail-closed signal. Model the setting as a tagged union (_HopCountUnset, _HopCountInvalid, _HopCount) so the three states are distinct: unset keeps the legacy path, a valid count drives hop-counting, and an invalid value fails closed (returns "") instead of reverting to the spoofable leftmost address. The caller matches on the union exhaustively. Add a parametrized regression test asserting get_mcp_client_ip returns "" for 0, -1, "abc", and 1.5 even with a spoofed internal leftmost entry, and update the resolver unit tests for the new return type.
|
bugbot run |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit 6511947. Configure here.
…itellm_mcp_xff_trusted_hops # Conflicts: # litellm/proxy/auth/ip_address_utils.py # tests/test_litellm/proxy/auth/test_mcp_ip_filtering.py
|
bugbot run |
Relevant issues
Hardening for the append-style X-Forwarded-For spoofing gap in MCP per-server IP access control, the same XFF trust model introduced with
mcp_trusted_proxy_ranges(#28356)Linear ticket
Related to LIT-3964 (MCP internal/external classification via X-Forwarded-For)
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
make test-unit@greptileaiand received a Confidence Score of at least 4/5 before requesting a maintainer reviewCI (LiteLLM team)
Branch creation CI run
Link:
CI run for the last commit
Link:
Merge / cherry-pick CI run
Links:
Screenshots / Proof of Fix
MCP per-server IP access control resolves the client IP from X-Forwarded-For and
is_internal_ip()classifies it by reading the leftmost entry. Behind an append-style proxy or load balancer (AWS ALB, nginx with$proxy_add_x_forwarded_for, HAProxy, Envoy, Cloudflare), a client can prepend an arbitrary value, so the leftmost entry is attacker-controllable even when the direct peer is a trusted proxy. That lets an attacker spoof an internal IP and reach servers markedavailable_on_public_internet=false. This change reads the client IPmcp_xff_num_trusted_hopsentries from the right of the chain instead, so prepended values are ignored.No LLM call is involved because the change is purely in X-Forwarded-For parsing for MCP access control. The proof hits
GET /v1/mcp/network/client-ip, which returns exactly the IPget_mcp_client_ip()resolves for access-control filtering.Started a local proxy with
FORWARDED_ALLOW_IPS=10.255.255.255so uvicorn does not rewriterequest.client.hostfrom the loopback curl peer; this mirrors a real deployment where the gateway's direct peer is the ingress (not loopback) and uvicorn leaves the header untouched.Before,
general_settingshasuse_x_forwarded_for: trueandmcp_trusted_proxy_ranges: ["127.0.0.0/8"]and no hop count:The raw chain is returned and
is_internal_ip()takes the leftmost10.0.0.99, so the caller is classified internal and the spoof succeeds.After, the same config plus
mcp_xff_num_trusted_hops: 1:The prepended
10.0.0.99is ignored and the real client203.0.113.9is resolved (external, spoof defeated), while a genuine single-hop internal client10.0.0.50is preserved.Fail-closed is also preserved: with
use_x_forwarded_for: trueand nomcp_trusted_proxy_ranges, the same spoofed header returns{"ip":""}, and with a chain shorter than the configured hop count the resolver returns""rather than guessing.Type
🆕 New Feature
🐛 Bug Fix
Changes
Adds an optional
mcp_xff_num_trusted_hopsgeneral setting modelled on Envoy'sxff_num_trusted_hops. When set to N,get_mcp_client_ip()reads the client IP N entries from the right of the X-Forwarded-For chain, where N is the number of trusted appending proxies in front of the gateway, instead of letting the downstream classifier trust the spoofable leftmost value.It composes with
mcp_trusted_proxy_ranges, which still validates the direct peer, and only takes effect once that check passes. Without a validated direct peer the gateway keeps failing closed, so hop counting cannot be abused by a direct-to-pod attacker. The chain must contain at least N valid entries or resolution fails closed.The setting defaults to unset, so existing deployments are unchanged. Values below 1 are rejected at config-parse time via a
ge=1bound on the field. Any present-but-invalid value (0, negative, or non-numeric) that still reaches the runtime through raw config now fails closed (resolution returns"") and is logged as a warning, rather than silently reverting to the spoofable leftmost value. The three states are modelled as a tagged union so they stay distinct: unset keeps the legacy leftmost path, a valid count drives hop counting, and an invalid value fails closed. That way a typo cannot quietly weaken access control below the pre-feature baseline; it either fails to parse or fails closed. New unit tests cover the right-to-left selection, multi-hop chains, genuine internal clients, short-chain and invalid-entry fail-closed paths, the requirement that a trusted proxy range is configured, and that the legacy leftmost behavior is retained when the setting is absent.Note
High Risk
Changes security-sensitive MCP client IP resolution used for internal-only server access; misconfiguration could block legitimate clients or weaken filtering if operators misunderstand hop count, though invalid values fail closed.
Overview
Adds optional
mcp_xff_num_trusted_hopsto proxy general settings so MCP access control can derive the client IP from X-Forwarded-For by reading N entries from the right of the chain (after the existing trusted-proxy peer check), instead of trusting the spoofable leftmost value behind append-style load balancers.get_mcp_client_ip()now branches on a three-state hop setting: unset keeps legacy leftmost behavior; a valid positive integer usesextract_client_ip_from_xff_hopsand returns empty string when the chain is too short or invalid; present-but-invalid values fail closed (no silent fallback to legacy). Config parsing rejects values below 1 viage=1onConfigGeneralSettings, and the setting is exposed in the proxy config schema and dashboard OpenAPI types.Unit tests cover hop extraction, misconfiguration warnings, spoof defeat, multi-hop chains, and legacy behavior when the setting is absent.
Reviewed by Cursor Bugbot for commit 6a2a05a. Bugbot is set up for automated code reviews on this repo. Configure here.