Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

fix(mcp): preserve JWT agent validation after main merge

Joshua Valluru72a4824acbc2
diff --cc litellm/proxy/auth/handle_jwt.py
index 678769b375b,94ca3047f45..d5fcc578167
--- a/litellm/proxy/auth/handle_jwt.py
+++ b/litellm/proxy/auth/handle_jwt.py
@@@ -2284,42 -2320,23 +2336,57 @@@ class JWTAuthManager
elif rbac_role == LitellmUserRoles.INTERNAL_USER:
user_id = object_id
+ agent_id: Final = JWTAuthManager.resolve_agent_id(
+ jwt_handler=jwt_handler,
+ jwt_valid_token=jwt_valid_token,
+ agent_registry=jwt_handler.agent_lookup,
+ )
+
+ if identity_only:
+ identity_user, _, _, _, identity_user_id = await JWTAuthManager.get_objects(
+ user_id=user_id,
+ user_email=user_email,
+ org_id=None,
+ end_user_id=None,
+ team_id=None,
+ valid_user_email=valid_user_email,
+ jwt_handler=jwt_handler,
+ prisma_client=prisma_client,
+ user_api_key_cache=user_api_key_cache,
+ parent_otel_span=parent_otel_span,
+ proxy_logging_obj=proxy_logging_obj,
+ route=route,
+ user_id_upsert=False,
+ )
+ return JWTAuthBuilderResult(
+ is_proxy_admin=False,
+ # Admin admission uses the claim ID; other callers use the canonical DB ID.
+ user_id=user_id if jwt_handler.is_admin(scopes=scopes) else identity_user_id,
+ user_email=identity_user.user_email if identity_user is not None else user_email,
+ user_object=identity_user,
+ team_id=None,
+ team_object=None,
+ org_id=None,
+ org_object=None,
+ end_user_id=None,
+ end_user_object=None,
+ team_membership=None,
+ token=api_key,
+ jwt_claims=jwt_valid_token,
++ agent_id=agent_id,
+ )
+
# Check admin access
admin_result: Final = await JWTAuthManager.check_admin_access(
- jwt_handler, scopes, route, user_id, org_id, api_key, jwt_valid_token, user_email=user_email
+ jwt_handler,
+ scopes,
+ route,
+ user_id,
+ org_id,
+ api_key,
+ jwt_valid_token,
+ user_email=user_email,
+ agent_id=agent_id,
)
if admin_result:
await JWTAuthManager._attach_team_from_header_for_admin(
diff --cc tests/test_litellm/proxy/auth/test_handle_jwt.py
index 9e15a442a18,814e31535e0..4d86e395358
--- a/tests/test_litellm/proxy/auth/test_handle_jwt.py
+++ b/tests/test_litellm/proxy/auth/test_handle_jwt.py
@@@ -6788,70 -6790,178 +6790,251 @@@ async def test_sync_user_role_and_teams
assert user.teams == []
[email protected]("identity_only", [False, True])
[email protected]("existing_user", [False, True])
[email protected]("model_allowed", [False, True])
+async def test_auth_builder_identity_lookup_does_not_provision_users(
+ monkeypatch: pytest.MonkeyPatch, identity_only: bool, existing_user: bool, model_allowed: bool
+) -> None:
+ from litellm.proxy._types import ScopeMapping
+ from litellm.proxy.auth.auth_checks import UserNotFoundError
+ from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache
+
+ private_key, jwk = _get_rsa_key_and_jwk("identity-mode")
+ cache: Final = UserApiKeyCache()
+ cache.set_cache("litellm_jwt_auth_keys_https://identity.example/jwks", [jwk])
+ user_id: Final = f"identity-mode-{identity_only}-{existing_user}-{model_allowed}"
+ user: Final = LiteLLM_UserTable(user_id=user_id, organization_memberships=[])
+ if existing_user:
+ cache.set_cache(user_id, user)
+ database: Final = MagicMock()
+ users: Final = database.db.litellm_usertable
+ users.find_unique = AsyncMock(return_value=None)
+ users.find_first = AsyncMock(return_value=None)
+ users.create = AsyncMock(return_value=user)
+ handler: Final = JWTHandler()
+ handler.update_environment(
+ prisma_client=database,
+ user_api_key_cache=cache,
+ litellm_jwtauth=LiteLLM_JWTAuth(
+ user_id_jwt_field="sub",
+ user_id_upsert=True,
+ enforce_scope_based_access=True,
+ scope_mappings=[ScopeMapping(scope="allowed", models=["allowed-model"])],
+ ),
+ )
+ monkeypatch.setenv("JWT_PUBLIC_KEY_URL", "https://identity.example/jwks")
+ monkeypatch.setenv("JWT_ISSUER", "https://identity.example")
+ monkeypatch.setenv("JWT_AUDIENCE", "gateway")
+ token: Final = _encode_rsa_jwt(
+ private_key, "https://identity.example", "gateway", "identity-mode", {"sub": user_id, "scope": "allowed"}
+ )
+ pending: Final = JWTAuthManager.auth_builder(
+ api_key=token,
+ jwt_handler=handler,
+ request_data={"model": "allowed-model" if model_allowed else "forbidden-model"},
+ general_settings={},
+ route="/example/token" if identity_only else "/mcp/example",
+ prisma_client=database,
+ user_api_key_cache=cache,
+ parent_otel_span=None,
+ proxy_logging_obj=MagicMock(),
+ identity_only=identity_only,
+ )
+ if not identity_only and not model_allowed:
+ with pytest.raises(HTTPException) as denial:
+ await pending
+ assert denial.value.status_code == 403
+ users.create.assert_not_awaited()
+ return
+ if identity_only and not existing_user:
+ with pytest.raises(UserNotFoundError):
+ await pending
+ else:
+ result: Final = await pending
+ assert result["user_id"] == user_id
+ assert result["user_object"] is not None
+ assert result["user_object"].user_id == user_id
+ assert users.create.await_count == (0 if identity_only or existing_user else 1)
++
++
+ def _entra_agent_registry() -> AgentRegistry:
+ registry = AgentRegistry()
+ registry.register_agent(
+ AgentResponse(
+ agent_id="canonical-agent-id",
+ agent_name="2f5c9b1e-6a4d-4c8e-9f0b-7d1a3e5c9b21",
+ agent_card_params={"name": "research-agent", "url": "http://localhost:9999/a2a", "version": "1.0.0"},
+ litellm_params={"require_trace_id_on_calls_by_agent": True},
+ )
+ )
+ return registry
+
+
+ def _entra_agent_jwt_handler(agent_id_jwt_field: str | None) -> JWTHandler:
+ jwt_handler = JWTHandler()
+ jwt_handler.update_environment(
+ prisma_client=None,
+ user_api_key_cache=DualCache(),
+ litellm_jwtauth=LiteLLM_JWTAuth(user_id_jwt_field="sub", agent_id_jwt_field=agent_id_jwt_field),
+ )
+ return jwt_handler
+
+
+ @pytest.mark.parametrize(
+ "claim_value",
+ ["canonical-agent-id", "2f5c9b1e-6a4d-4c8e-9f0b-7d1a3e5c9b21"],
+ ids=["matches_agent_id", "matches_agent_name"],
+ )
+ def test_resolve_agent_id_returns_canonical_agent_id(claim_value: str):
+ """An Entra app token's azp claim binds to the registered agent by id or by name and yields its canonical id."""
+ jwt_handler = _entra_agent_jwt_handler(agent_id_jwt_field="azp")
+
+ resolved = JWTAuthManager.resolve_agent_id(
+ jwt_handler=jwt_handler,
+ jwt_valid_token={"sub": "sp-object-id-1234", "azp": claim_value},
+ agent_registry=_entra_agent_registry(),
+ )
+
+ assert resolved == "canonical-agent-id"
+
+
+ def test_resolve_agent_id_reads_nested_claim():
+ jwt_handler = _entra_agent_jwt_handler(agent_id_jwt_field="entra.client_id")
+
+ resolved = JWTAuthManager.resolve_agent_id(
+ jwt_handler=jwt_handler,
+ jwt_valid_token={"sub": "sp-object-id-1234", "entra": {"client_id": "canonical-agent-id"}},
+ agent_registry=_entra_agent_registry(),
+ )
+
+ assert resolved == "canonical-agent-id"
+
+
+ def test_resolve_agent_id_rejects_claim_for_unregistered_agent():
+ """A configured agent claim naming no registered agent fails closed with 403 instead of falling back to an unbound identity."""
+ jwt_handler = _entra_agent_jwt_handler(agent_id_jwt_field="azp")
+
+ with pytest.raises(HTTPException) as exc_info:
+ JWTAuthManager.resolve_agent_id(
+ jwt_handler=jwt_handler,
+ jwt_valid_token={"sub": "sp-object-id-1234", "azp": "00000000-0000-0000-0000-000000000000"},
+ agent_registry=_entra_agent_registry(),
+ )
+
+ assert exc_info.value.status_code == 403
+
+
+ @pytest.mark.parametrize(
+ "token",
+ [
+ {"sub": "sp-object-id-1234"},
+ {"sub": "sp-object-id-1234", "azp": ""},
+ {"sub": "sp-object-id-1234", "azp": ["canonical-agent-id"]},
+ ],
+ ids=["claim_absent", "claim_empty", "claim_not_a_string"],
+ )
+ def test_resolve_agent_id_returns_none_when_claim_unusable(token: dict):
+ jwt_handler = _entra_agent_jwt_handler(agent_id_jwt_field="azp")
+
+ assert (
+ JWTAuthManager.resolve_agent_id(
+ jwt_handler=jwt_handler, jwt_valid_token=token, agent_registry=_entra_agent_registry()
+ )
+ is None
+ )
+
+
+ def test_resolve_agent_id_ignores_claim_when_field_not_configured():
+ """Without agent_id_jwt_field an azp claim (even an unknown one) leaves JWT auth behaviour unchanged."""
+ jwt_handler = _entra_agent_jwt_handler(agent_id_jwt_field=None)
+
+ resolved = JWTAuthManager.resolve_agent_id(
+ jwt_handler=jwt_handler,
+ jwt_valid_token={"sub": "sp-object-id-1234", "azp": "00000000-0000-0000-0000-000000000000"},
+ agent_registry=_entra_agent_registry(),
+ )
+
+ assert resolved is None
+
+
+ def _entra_signed_app_token(monkeypatch, azp: str, scope: str) -> tuple[JWTHandler, str]:
+ """A JWTHandler that verifies RS256 tokens against a pre-cached JWKS, plus a signed Entra-style app token."""
+ jwks_url = "https://login.microsoftonline.test/discovery/v2.0/keys"
+ monkeypatch.setenv("JWT_PUBLIC_KEY_URL", jwks_url)
+ monkeypatch.delenv("JWT_AUDIENCE", raising=False)
+ private_key, jwk = _get_rsa_key_and_jwk(kid="entra-kid")
+ cache = DualCache()
+ cache.set_cache(key=f"litellm_jwt_auth_keys_{jwks_url}", value=[jwk])
+ jwt_handler = JWTHandler()
+ jwt_handler.update_environment(
+ prisma_client=None,
+ user_api_key_cache=cache,
+ litellm_jwtauth=LiteLLM_JWTAuth(agent_id_jwt_field="azp"),
+ )
+ token = _encode_rsa_jwt(
+ private_key,
+ issuer="https://login.microsoftonline.test/lit7664-tenant/v2.0",
+ audience="api://litellm",
+ kid="entra-kid",
+ extra_claims={"sub": "sp-object-id-1234", "azp": azp, "scope": scope},
+ )
+ return jwt_handler, token
+
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("is_admin_token", [False, True], ids=["standard_jwt", "proxy_admin_jwt"])
-async def test_auth_builder_propagates_agent_id_from_jwt_claim(monkeypatch, is_admin_token: bool):
[email protected]("identity_only", [False, True])
++async def test_auth_builder_propagates_agent_id_from_jwt_claim(monkeypatch, is_admin_token: bool, identity_only: bool):
+ """auth_builder carries the resolved agent id into JWTAuthBuilderResult on both the admin and standard paths."""
+ jwt_handler, token = _entra_signed_app_token(
+ monkeypatch,
+ azp="2f5c9b1e-6a4d-4c8e-9f0b-7d1a3e5c9b21",
+ scope=LiteLLM_JWTAuth().admin_jwt_scope if is_admin_token else "",
+ )
+ jwt_handler.bind_agent_lookup(_entra_agent_registry())
+
+ result = await JWTAuthManager.auth_builder(
+ api_key=token,
+ jwt_handler=jwt_handler,
+ request_data={"model": "gpt-5.6"},
+ general_settings={"enforce_rbac": False},
+ route="/key/info" if is_admin_token else "/chat/completions",
+ prisma_client=None,
+ user_api_key_cache=None,
+ parent_otel_span=None,
+ proxy_logging_obj=None,
++ identity_only=identity_only,
+ )
+
- assert result["is_proxy_admin"] is is_admin_token
++ assert result["is_proxy_admin"] is (is_admin_token and not identity_only)
+ assert result["agent_id"] == "canonical-agent-id"
+
+
+ @pytest.mark.asyncio
-async def test_auth_builder_denies_jwt_naming_unregistered_agent_before_admin_check(monkeypatch):
[email protected]("identity_only", [False, True])
++async def test_auth_builder_denies_jwt_naming_unregistered_agent_before_admin_check(monkeypatch, identity_only: bool):
+ """An unknown agent claim is rejected even when the token would otherwise be a proxy admin."""
+ jwt_handler, token = _entra_signed_app_token(
+ monkeypatch,
+ azp="00000000-0000-0000-0000-000000000000",
+ scope=LiteLLM_JWTAuth().admin_jwt_scope,
+ )
+ jwt_handler.bind_agent_lookup(_entra_agent_registry())
+
+ with pytest.raises(HTTPException) as exc_info:
+ await JWTAuthManager.auth_builder(
+ api_key=token,
+ jwt_handler=jwt_handler,
+ request_data={"model": "gpt-5.6"},
+ general_settings={"enforce_rbac": False},
+ route="/key/info",
+ prisma_client=None,
+ user_api_key_cache=None,
+ parent_otel_span=None,
+ proxy_logging_obj=None,
++ identity_only=identity_only,
+ )
+
+ assert exc_info.value.status_code == 403