-
-
Notifications
You must be signed in to change notification settings - Fork 10.4k
feat(proxy): resolve root_path per request from a configured prefix list (SERVER_ROOT_PATHS) #35935
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
gym-cmd
wants to merge
4
commits into
BerriAI:litellm_internal_staging
Choose a base branch
from
gym-cmd:feat/proxy-per-request-root-path
base: litellm_internal_staging
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
0ec70ed
feat(proxy): resolve root_path per request from SERVER_ROOT_PATHS
gym-cmd 879e7c7
fix(proxy): import Sequence from collections.abc (ruff UP035 strict-b…
gym-cmd 548bed2
review(greptile): trim implementation commentary; fixture-own MCP reg…
gym-cmd 88acad9
fix(lint): mutable-ok marker on the prefix accumulator (LIT002 type-d…
gym-cmd File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
81 changes: 81 additions & 0 deletions
81
litellm/proxy/middleware/per_request_root_path_middleware.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,81 @@ | ||
| """Per-request ``root_path`` resolution from ``SERVER_ROOT_PATHS``. | ||
|
|
||
| ``SERVER_ROOT_PATH`` is a startup scalar, so one deployment serves exactly one | ||
| client-visible URL path prefix; a request under any other prefix 404s before a | ||
| handler runs. When the ingress preserves several prefixes into one pod (e.g. | ||
| ``/tenant-a/*`` and ``/tenant-b/*``), the matched prefix becomes that | ||
| request's ``scope["root_path"]`` instead: Starlette strips it during route | ||
| matching and rebuilds it into ``request.base_url``, so every emitted URL — | ||
| the MCP OAuth discovery ``resource`` (RFC 9728 §3) and the 401 challenges' | ||
| ``resource_metadata`` among them — lands under the prefix the client called. | ||
| Opt-in: with ``SERVER_ROOT_PATHS`` unset the middleware is not added at all. | ||
| """ | ||
|
|
||
| import os | ||
| from collections.abc import Sequence | ||
| from typing import Final | ||
|
|
||
| from starlette.types import ASGIApp, Receive, Scope, Send | ||
|
|
||
| from litellm._logging import verbose_proxy_logger | ||
|
|
||
| SERVER_ROOT_PATHS_ENV: Final = "SERVER_ROOT_PATHS" | ||
|
|
||
|
|
||
| def normalize_root_paths(raw_paths: Sequence[str]) -> tuple[str, ...]: | ||
| """Strip whitespace and trailing slashes, dedupe, order longest-first; | ||
| warn and drop entries missing a leading ``/`` and the bare root.""" | ||
| kept: list[str] = [] # mutable-ok: local accumulator; escapes only as a tuple | ||
| for entry in raw_paths: | ||
| candidate = entry.strip() | ||
| if not candidate: | ||
| continue | ||
| if not candidate.startswith("/"): | ||
| verbose_proxy_logger.warning( | ||
| "%s entry %r does not start with '/' and will be ignored.", | ||
| SERVER_ROOT_PATHS_ENV, | ||
| entry, | ||
| ) | ||
| continue | ||
| candidate = candidate.rstrip("/") | ||
| if not candidate: | ||
| verbose_proxy_logger.warning( | ||
| "%s entry %r is the bare root and will be ignored; a root-mounted deployment needs no entry.", | ||
| SERVER_ROOT_PATHS_ENV, | ||
| entry, | ||
| ) | ||
| continue | ||
| if candidate not in kept: | ||
| kept.append(candidate) | ||
| return tuple(sorted(kept, key=len, reverse=True)) | ||
|
|
||
|
|
||
| def get_server_root_paths() -> tuple[str, ...]: | ||
| """The normalized ``SERVER_ROOT_PATHS`` prefixes, empty when unset.""" | ||
| configured: Final = os.getenv(SERVER_ROOT_PATHS_ENV, "") | ||
| if not configured.strip(): | ||
| return () | ||
| return normalize_root_paths(configured.split(",")) | ||
|
|
||
|
|
||
| class PerRequestRootPathMiddleware: | ||
| """Sets ``scope["root_path"]`` to the configured prefix matching the | ||
| request path on a whole-segment boundary. ``scope["path"]`` is left | ||
| untouched (Starlette strips ``root_path`` at route-match time). Must be | ||
| the outermost middleware so inner middlewares and the router see the | ||
| resolved value; a matched prefix overrides a scalar ``SERVER_ROOT_PATH`` | ||
| for that request. | ||
| """ | ||
|
|
||
| def __init__(self, app: ASGIApp, root_paths: Sequence[str]) -> None: | ||
| self.app = app | ||
| self.root_paths: Final = normalize_root_paths(root_paths) | ||
|
|
||
| async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: | ||
| if scope["type"] in ("http", "websocket"): | ||
| path: Final = scope.get("path", "") | ||
| for prefix in self.root_paths: | ||
| if path == prefix or path.startswith(prefix + "/"): | ||
| scope["root_path"] = prefix | ||
| break | ||
| await self.app(scope, receive, send) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.