Skip to content

feat(mcp): add mcp_xff_num_trusted_hops to harden X-Forwarded-For client IP resolution - #31257

Merged
mateo-berri merged 7 commits into
litellm_internal_stagingfrom
litellm_mcp_xff_trusted_hops
Jun 25, 2026
Merged

mateo-berri merged 7 commits into
litellm_internal_stagingfrom
litellm_mcp_xff_trusted_hops

Conversation

@mateo-berri

@mateo-berri mateo-berri commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

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

  • I have added meaningful tests
  • My PR passes all unit tests on make test-unit
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have requested a Greptile review by commenting @greptileai and received a Confidence Score of at least 4/5 before requesting a maintainer review

CI (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 marked available_on_public_internet=false. This change reads the client IP mcp_xff_num_trusted_hops entries 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 IP get_mcp_client_ip() resolves for access-control filtering.

Started a local proxy with FORWARDED_ALLOW_IPS=10.255.255.255 so uvicorn does not rewrite request.client.host from 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_settings has use_x_forwarded_for: true and mcp_trusted_proxy_ranges: ["127.0.0.0/8"] and no hop count:

$ curl -s -H "Authorization: Bearer sk-1234" \
    -H "X-Forwarded-For: 10.0.0.99, 203.0.113.9" \
    http://localhost:4000/v1/mcp/network/client-ip
{"ip":"10.0.0.99, 203.0.113.9"}

The raw chain is returned and is_internal_ip() takes the leftmost 10.0.0.99, so the caller is classified internal and the spoof succeeds.

After, the same config plus mcp_xff_num_trusted_hops: 1:

$ curl -s -H "Authorization: Bearer sk-1234" \
    -H "X-Forwarded-For: 10.0.0.99, 203.0.113.9" \
    http://localhost:4000/v1/mcp/network/client-ip
{"ip":"203.0.113.9"}

$ curl -s -H "Authorization: Bearer sk-1234" \
    -H "X-Forwarded-For: 10.0.0.50" \
    http://localhost:4000/v1/mcp/network/client-ip
{"ip":"10.0.0.50"}

The prepended 10.0.0.99 is ignored and the real client 203.0.113.9 is resolved (external, spoof defeated), while a genuine single-hop internal client 10.0.0.50 is preserved.

Fail-closed is also preserved: with use_x_forwarded_for: true and no mcp_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_hops general setting modelled on Envoy's xff_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=1 bound 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_hops to 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 uses extract_client_ip_from_xff_hops and 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 via ge=1 on ConfigGeneralSettings, 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.

…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

codecov Bot commented Jun 25, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@greptile-apps

greptile-apps Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

Adds an optional mcp_xff_num_trusted_hops general setting that lets operators harden MCP per-server IP access control against append-style X-Forwarded-For header manipulation when operating behind trusted reverse proxies.

  • get_mcp_client_ip() gains a structural match on a new tagged-union result from _resolve_num_trusted_hops(); the three states (unset → legacy path, invalid → fail closed, valid count → rightmost-N extraction) are mutually exclusive and exhaustive.
  • A ge=1 constraint on the Pydantic field rejects sub-minimum values at config-parse time; runtime defense-in-depth warns and fails closed for values that reach the resolver through raw-dict config paths.
  • New unit tests cover single/multi-hop extraction, all three resolver states, ConfigGeneralSettings parse-time rejection, and end-to-end access-control scenarios with no real network calls.

Confidence Score: 5/5

Safe 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.

Important Files Changed

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

Comment thread litellm/proxy/auth/ip_address_utils.py Resolved
Comment thread litellm/proxy/_types.py Resolved
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

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.
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

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.
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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.

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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.
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@mateo-berri
mateo-berri merged commit 6db55e0 into litellm_internal_staging Jun 25, 2026
77 checks passed
@mateo-berri
mateo-berri deleted the litellm_mcp_xff_trusted_hops branch June 25, 2026 14:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants