litellm/tests/unit/proxy/auth/test_denial.py
yujonglee 983c7ef20d
fix(auth): check a mapped JWT's end-user claim and keep the error classes of refused keys and JWTs (#52397)
* fix(auth): check a mapped JWT's end-user claim and keep the typed unknown-key error

Two regressions from moving key and JWT auth into gateway-auth-core, both
failing tests/integration/authorization on main.

A JWT mapped to a virtual key carried its end-user claim beside the key, in
MappedJwt, while the key path read the end user from KeyRecord.end_user_id.
That field came from the stored key row, which never names an end user, so the
key path validated, read and budget-checked the request body's end user, and
an over-budget body user refused a request the claim should have decided.
Credential::Resolved now carries the end user the JWT names, the key path
reads it before the request's, and KeyRecord.end_user_id is gone.

An unknown virtual key came back from the core as a plain ProxyException, so
the failure spend row recorded error_class ProxyException and the auth failure
log line lost "key=<hash>, not found in db". KeyDenial::NotFound now carries
the hash the host looked up and renders as PublicDenial::KeyNotFound, which
Python constructs as KeyNotFoundError.

The team header integration test asserted Python's list repr in the 403
message. The core formats lists as JSON by design, so the test now reads the
allowed team ids as JSON.

* fix(auth): keep the JWT error classes failure rows record and test path handoffs at the entry point

An unknown signing key and an ID-JAG sent as a bearer token were raised as
NoMatchingJWTPublicKeyError and IdJagIsNotABearerTokenError before the core
moved to Rust, and as a bare Exception after it, so the failure spend row's
error_class lost the name. Each is its own PublicDenial variant again.

test_denial.py now pins the exact class of every RustDenial variant and fails
when a variant has none.

lib.rs gains entry-point tests for a JWT that continues on the key path: a
linked existing key reads the claim's end user, and a blocked mapped key is
refused with that key. AGENTS.md records the three rules behind these fixes.

* test(auth): pin auth outcomes for a production-shaped JWT deployment

86 requests run through user_api_key_auth against settings shaped like a
production install: teams from a JWT roles claim, users created on first
sight, team-based model access, a team route allowlist, pass-through endpoints
registered with auth, a master key, virtual keys, and requests let through a
database outage. A second JWT configuration maps a client claim to a virtual
key and names the end user by a claim.

Each case pins who the request is served as or how it is refused: the user,
team and end user on the token, the status, type and opening of the error, the
exception class the failure spend row records, and the users and team members
auth wrote.

Every expected value was observed on the commit before key and JWT auth moved
to gateway-auth-core, where the same requests gave the same outcomes apart
from message wording. Putting either of the two regressions back fails this
file: the unknown-key case when the typed error is lost, and three mapped-JWT
cases when the end-user claim does not reach the key path.

* test(auth): build the profile test's empty tables in one expression

* fix(auth): select a JWT team for pass-through subpaths and report a failed team read as an outage

Two bugs that predate the Rust auth core and that the production-shaped
profile test surfaced.

A JWT caller whose team grants a pass-through endpoint registered with
include_subpath was refused on every path under it, unless the user's own row
listed exactly one team. Team selection asked whether team_allowed_routes
lists the route, and a subpath is only listed inside the openai_routes group
as "path/*", which a group entry never matches as a wildcard. Selection now
asks whether the team may use the route, which is true for every auth
pass-through route, and leaves the decision to the team's own grants, as the
header, RBAC and database fallback sources already did.

A database outage during a JWT team read was reported as 403 "No team has
access to the requested model". get_team_object turns every failure into a 404
HTTPException, so the host answered Unreadable, and the core dropped any
failure it did get. get_team_object now keeps the original error as the cause,
the JWT host re-raises it when it is a database connection error, and team
selection ends with that host failure. The request then gets the fallback
identity under allow_requests_on_db_unavailable, or the 503.

A team the host fails to read now ends the selection even when
team_claim_fallback is on or a later team would qualify.

* test(auth): cut auth tests that kill no mutant and simplify the claimed team read

The deployment profile test goes from 87 cases to 12. Line coverage showed 36 cases ran no
proxy line the rest of tests/unit/proxy/auth misses, and the others reached the same few
host answers, so one case per answer stays.

check_team now reads the team with ?, like every other team read in the file. The guard it
replaces left a mutant no test could kill, since a host only fails a read as HostFailed.

Core and host tests that repeated another test's assertion are removed, and two cases cover
mutants that survived next to the changed key path code.

* test(auth): cover the claimed team and entry point mutants left in the touched files

A singular team claim is a team the header may name and wins over an alias claim, a
delegated agent is scoped to the teams its token names, and the two public entry points
that only delegate to the planner are now called from a test.

cargo mutants over the 8 changed core files now reports 114 caught and none missed.

* test(auth): drop the wall-clock expiry from the refused JWT class test

Both refusals happen before the expiry is read, so the token needs no exp claim.

* test(auth): mark the new entry point tests with rstest and name helpers over commenting them

* refactor(auth): return a failed team read with its real error and read it in the JWT host

get_team_object reports every database failure as a 404, so the JWT host had to
recover an outage from the exception's cause. read_team now holds the read and
returns a failed one as a value, get_team_object keeps its 404 on top of it for
its other callers, and the host decides from the real error.

* test(mcp): stub the team reader the JWT host now calls
2026-11-18 03:36:46 +00:00

116 lines
4.4 KiB
Python

from typing import Final, TypeGuard
from fastapi import HTTPException
import litellm
from litellm.proxy._types import (
ProxyErrorTypes,
ProxyException,
)
from litellm.proxy.auth import denial as auth_denial
from litellm.proxy.auth.auth_checks import TeamNotFoundError
from litellm.proxy.auth.auth_utils import is_invalid_virtual_key_error
from litellm.proxy.auth.model_access_denied import ModelAccessDeniedHTTPException
from litellm.proxy.auth.resolvers.exceptions import KeyNotFoundError
from litellm.rust_bridge._native import RustDenial
def test_proxy_denial_keeps_its_status_type_and_param() -> None:
error: Final = auth_denial.denial_error(
RustDenial.Proxy(status=401, message="expired", error_type="expired_key", param="sk-...abcd")
)
assert isinstance(error, ProxyException)
assert (error.message, error.type, error.param, error.code) == (
"expired",
ProxyErrorTypes.expired_key,
"sk-...abcd",
"401",
)
def test_invalid_virtual_key_denial_is_marked_for_log_routing() -> None:
error: Final = auth_denial.denial_error(
RustDenial.InvalidVirtualKey(status=401, detail="LiteLLM Virtual Key expected.")
)
assert isinstance(error, HTTPException)
assert (error.status_code, error.detail) == (401, "LiteLLM Virtual Key expected.")
assert is_invalid_virtual_key_error(error)
def test_plain_http_denial_is_not_marked_as_an_invalid_key() -> None:
error: Final = auth_denial.denial_error(
RustDenial.Http(status=403, detail="'allow_user_auth' not set or set to False")
)
assert isinstance(error, HTTPException)
assert error.status_code == 403
assert not is_invalid_virtual_key_error(error)
def test_model_access_denial_carries_the_internal_message() -> None:
error: Final = auth_denial.denial_error(
RustDenial.ModelAccess(status=401, detail="no access", internal_message="model=x")
)
assert isinstance(error, ModelAccessDeniedHTTPException)
assert (error.status_code, error.detail, error.internal_message) == (401, "no access", "model=x")
def test_plain_denial_is_a_bare_exception() -> None:
error: Final = auth_denial.denial_error(RustDenial.Plain(message="no team"))
assert type(error) is Exception
assert str(error) == "no team"
def test_budget_denial_is_the_budget_error_the_host_step_raised() -> None:
error: Final = auth_denial.denial_error(
RustDenial.BudgetExceeded(
current_cost=2.0, max_budget=1.0, message="over", entity_type="team_member", entity_id="u:t"
)
)
assert isinstance(error, litellm.BudgetExceededError)
assert (error.current_cost, error.max_budget, error.message, error.entity_type, error.entity_id) == (
2.0,
1.0,
"over",
"team_member",
"u:t",
)
def test_gone_session_team_is_a_team_not_found() -> None:
error: Final = auth_denial.denial_error(RustDenial.TeamNotFound(team_id="t"))
assert isinstance(error, TeamNotFoundError)
assert error.status_code == 404
_ERROR_CLASSES: Final[dict[RustDenial, type[Exception]]] = {
RustDenial.Proxy(status=401, message="m", error_type="auth_error", param=None): ProxyException,
RustDenial.Http(status=403, detail="d"): HTTPException,
RustDenial.InvalidVirtualKey(status=401, detail="d"): HTTPException,
RustDenial.ModelAccess(status=401, detail="d", internal_message="i"): ModelAccessDeniedHTTPException,
RustDenial.Plain(message="m"): Exception,
RustDenial.BudgetExceeded(
current_cost=2.0, max_budget=1.0, message="m", entity_type=None, entity_id=None
): litellm.BudgetExceededError,
RustDenial.TeamNotFound(team_id="t"): TeamNotFoundError,
RustDenial.KeyNotFound(hash="h"): KeyNotFoundError,
RustDenial.NoMatchingJwtPublicKey(message="m"): auth_denial.NoMatchingJWTPublicKeyError,
RustDenial.IdJagNotBearer(message="m"): auth_denial.IdJagIsNotABearerTokenError,
}
def _is_variant(value: object) -> TypeGuard[type[RustDenial]]:
return isinstance(value, type) and issubclass(value, RustDenial)
def test_every_denial_the_core_renders_is_raised_as_exactly_one_named_class() -> None:
raised: Final = {type(denial): type(auth_denial.denial_error(denial)) for denial in _ERROR_CLASSES}
assert raised == {type(denial): error_class for denial, error_class in _ERROR_CLASSES.items()}
assert set(raised) == {value for value in vars(RustDenial).values() if _is_variant(value)}