From 0166992f6b15c541f53dfb8d3a7a61d3c7463791 Mon Sep 17 00:00:00 2001 From: user <70670632+stuxf@users.noreply.github.com> Date: Wed, 29 Apr 2026 21:09:37 +0000 Subject: [PATCH 01/12] fix(proxy): contain UI_LOGO_PATH and LITELLM_FAVICON_URL to allowed asset roots MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The unauthenticated ``/get_image`` and ``/get_favicon`` endpoints accept the admin-set env vars ``UI_LOGO_PATH`` and ``LITELLM_FAVICON_URL`` and return whatever bytes they resolve to, with a hard-coded ``image/jpeg`` or ``image/x-icon`` content-type. Two attack shapes: * ``UI_LOGO_PATH=/etc/passwd`` (or any other readable file path) — any unauthenticated caller exfiltrates the file via ``GET /get_image``. The previous gate was ``os.path.exists(logo_path)`` which fires on every readable file. Same shape for the favicon endpoint. * ``UI_LOGO_PATH=http://169.254.169.254/iam`` (or any internal HTTP service the admin pointed at) — the proxy fetches it server-side and streams the response body to the unauthenticated caller. No URL validation, no Content-Type validation; ``application/json`` AWS metadata gets tunneled out under the ``image/jpeg`` wrapper. New helper module ``litellm/proxy/common_utils/static_asset_utils.py``: * ``resolve_local_asset_path(candidate, allowed_roots)`` — returns the resolved absolute path only if it lives within one of the allowed asset roots. Uses ``realpath`` so symlinks pointing outside the roots are caught. * ``fetch_validated_image_bytes(url)`` — runs the URL through ``validate_url`` (rejecting private / cloud-metadata / loopback targets) and only returns the response body if the upstream Content-Type is in a small allowlist of image MIME types. Both ``/get_image`` and ``/get_favicon`` are wired through the helpers. The SSRF gate is enforced unconditionally — these endpoints are unauthenticated, so the admin-facing ``litellm.user_url_validation`` toggle does not apply (an admin who opted out of URL validation for LLM provider paths shouldn't also expose ``/get_image`` to SSRF). Tests: - ``TestResolveLocalAssetPath``: 10 cases covering legitimate paths, ``/etc/passwd``, ``/proc/self/environ``, symlink-out, ``..`` traversal, directories, missing files, and root list edge cases. - ``TestFetchValidatedImageBytes``: 7 cases covering SSRF block, non- image content-type rejection, valid image passthrough, non-200 response, fetch exception, empty URL, and parametrized coverage of every allowed image MIME type. Co-Authored-By: Claude Opus 4.7 (1M context) --- .../proxy/common_utils/static_asset_utils.py | 132 +++++++++ litellm/proxy/proxy_server.py | 121 ++++----- .../common_utils/test_static_asset_utils.py | 252 ++++++++++++++++++ 3 files changed, 442 insertions(+), 63 deletions(-) create mode 100644 litellm/proxy/common_utils/static_asset_utils.py create mode 100644 tests/test_litellm/proxy/common_utils/test_static_asset_utils.py diff --git a/litellm/proxy/common_utils/static_asset_utils.py b/litellm/proxy/common_utils/static_asset_utils.py new file mode 100644 index 000000000000..0643572118b2 --- /dev/null +++ b/litellm/proxy/common_utils/static_asset_utils.py @@ -0,0 +1,132 @@ +""" +Helpers for the unauthenticated logo / favicon endpoints (``/get_image`` and +``/get_favicon``). Both read an admin-set environment variable that may be a +local filesystem path or an HTTP URL, fetch the resource, and return the +bytes verbatim to any unauthenticated caller. + +Without these helpers: + +* a misconfigured / hostile env var like ``UI_LOGO_PATH=/etc/passwd`` lets + any unauthenticated caller exfiltrate the file (LFI — GHSA-3pcp-536p-ghjc). +* a legitimate-looking ``UI_LOGO_PATH=http://internal-service/branding.png`` + pointing at a private host lets any unauthenticated caller exfiltrate + whatever that host returns (SSRF — GHSA-pjc9-2hw6-78rr), regardless of + whether the body is actually an image. +""" + +import os +from typing import List, Optional + +from litellm._logging import verbose_proxy_logger +from litellm.litellm_core_utils.url_utils import SSRFError, validate_url +from litellm.llms.custom_httpx.http_handler import get_async_httpx_client +from litellm.types.llms.custom_http import httpxSpecialProvider + +# Conservative allowlist of image MIME types. Anything else is refused — +# without this, an admin-configured URL whose upstream returns +# ``application/json`` (e.g. cloud metadata, internal API) would still be +# served back to the caller verbatim. +ALLOWED_IMAGE_CONTENT_TYPES = frozenset( + { + "image/jpeg", + "image/jpg", + "image/png", + "image/gif", + "image/svg+xml", + "image/webp", + "image/x-icon", + "image/vnd.microsoft.icon", + } +) + + +def resolve_local_asset_path(candidate: str, allowed_roots: List[str]) -> Optional[str]: + """ + Resolve ``candidate`` and return its absolute path only if it lives + within one of ``allowed_roots``. Returns None on any miss (caller + falls back to the bundled default asset). + + Resolution uses ``realpath`` to follow symlinks, so a symlink inside + ``allowed_roots`` pointing at ``/etc/passwd`` is rejected the same as + a direct ``/etc/passwd`` config. + """ + if not candidate: + return None + try: + resolved = os.path.realpath(os.path.expanduser(candidate)) + except (OSError, ValueError): + return None + if not os.path.isfile(resolved): + return None + for root in allowed_roots: + if not root: + continue + try: + root_resolved = os.path.realpath(root) + except (OSError, ValueError): + continue + if resolved == root_resolved: + return resolved + if resolved.startswith(root_resolved + os.sep): + return resolved + return None + + +async def fetch_validated_image_bytes( + url: str, *, timeout_s: float = 5.0 +) -> Optional[bytes]: + """ + Fetch ``url`` with SSRF protection (always-on) and Content-Type + validation. Returns the raw bytes on success, ``None`` on any + failure (blocked target, non-200, or non-image response). + + The SSRF guard is enforced unconditionally — these endpoints are + unauthenticated, so the admin-facing ``litellm.user_url_validation`` + toggle does not apply. An admin who opted out of URL validation for + LLM provider paths should not also expose ``/get_image`` to SSRF. + """ + if not url: + return None + try: + rewritten_url, host_header = validate_url(url) + except SSRFError as exc: + verbose_proxy_logger.warning( + "Blocked unauthenticated asset fetch — SSRF guard rejected %r: %s", + url, + exc, + ) + return None + + # ``validate_url`` rewrites HTTP URLs to point at a validated IP and + # returns the original hostname for the Host header. For HTTPS with + # ssl_verify enabled, it returns the URL unchanged (TLS hostname + # validation handles DNS rebinding). + request_kwargs = {} + if rewritten_url != url: + request_kwargs["headers"] = {"host": host_header} + + async_client = get_async_httpx_client( + llm_provider=httpxSpecialProvider.UI, + params={"timeout": timeout_s}, + ) + try: + response = await async_client.get(rewritten_url, **request_kwargs) + except Exception as exc: + verbose_proxy_logger.debug("Asset fetch failed for %r: %s", url, exc) + return None + + if response.status_code != 200: + return None + + content_type = ( + (response.headers.get("content-type") or "").split(";")[0].strip().lower() + ) + if content_type not in ALLOWED_IMAGE_CONTENT_TYPES: + verbose_proxy_logger.warning( + "Asset fetch from %r returned non-image content-type %r — refusing to serve.", + url, + content_type, + ) + return None + + return response.content diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py index 870ea78f17a4..bbd528072fd8 100644 --- a/litellm/proxy/proxy_server.py +++ b/litellm/proxy/proxy_server.py @@ -12270,13 +12270,25 @@ async def get_image(): logo_path = os.getenv("UI_LOGO_PATH", default_logo) verbose_proxy_logger.debug("Reading logo from path: %s", logo_path) - # If UI_LOGO_PATH points to a local file, serve it directly (skip cache) + # ``/get_image`` is unauthenticated. Validate any admin-configured local + # path against an allowlist of asset roots — without this guard, an + # env var like ``UI_LOGO_PATH=/etc/passwd`` lets any caller exfiltrate + # the file via this endpoint. + from litellm.proxy.common_utils.static_asset_utils import ( + fetch_validated_image_bytes, + resolve_local_asset_path, + ) + + allowed_local_roots = [assets_dir, current_dir] + if logo_path != default_logo and not logo_path.startswith(("http://", "https://")): - if os.path.exists(logo_path): - return FileResponse(logo_path, media_type="image/jpeg") - # Custom path doesn't exist — fall back to default + safe_logo = resolve_local_asset_path(logo_path, allowed_local_roots) + if safe_logo is not None: + return FileResponse(safe_logo, media_type="image/jpeg") verbose_proxy_logger.warning( - f"UI_LOGO_PATH '{logo_path}' does not exist, falling back to default logo" + "UI_LOGO_PATH %r is outside the allowed asset roots or does not " + "exist, falling back to default logo", + logo_path, ) logo_path = default_logo @@ -12286,32 +12298,21 @@ async def get_image(): # Check if the logo path is an HTTP/HTTPS URL if logo_path.startswith(("http://", "https://")): - try: - # Download the image and cache it - from litellm.llms.custom_httpx.http_handler import get_async_httpx_client - from litellm.types.llms.custom_http import httpxSpecialProvider - - async_client = get_async_httpx_client( - llm_provider=httpxSpecialProvider.UI, - params={"timeout": 5.0}, - ) - response = await async_client.get(logo_path) - if response.status_code == 200: - # Save the image to a local file + # SSRF + content-type validation — the helper rejects + # private/internal/cloud-metadata targets and non-image responses. + image_bytes = await fetch_validated_image_bytes(logo_path) + if image_bytes is not None: + try: with open(cache_path, "wb") as f: - f.write(response.content) - - # Return the cached image as a FileResponse + f.write(image_bytes) return FileResponse(cache_path, media_type="image/jpeg") - else: - # Handle the case when the image cannot be downloaded - return FileResponse(default_logo, media_type="image/jpeg") - except Exception as e: - # Handle any exceptions during the download (e.g., timeout, connection error) - verbose_proxy_logger.debug(f"Error downloading logo from {logo_path}: {e}") - return FileResponse(default_logo, media_type="image/jpeg") + except OSError as e: + verbose_proxy_logger.debug( + "Could not write logo cache to %s: %s", cache_path, e + ) + return FileResponse(default_logo, media_type="image/jpeg") else: - # Return the local image file if the logo path is not an HTTP/HTTPS URL + # Default logo (resolved from the bundled asset, not user-controlled). return FileResponse(logo_path, media_type="image/jpeg") @@ -12320,8 +12321,14 @@ async def get_favicon(): """Get custom favicon for the admin UI.""" from fastapi.responses import Response + from litellm.proxy.common_utils.static_asset_utils import ( + fetch_validated_image_bytes, + resolve_local_asset_path, + ) + current_dir = os.path.dirname(os.path.abspath(__file__)) default_favicon = os.path.join(current_dir, "_experimental", "out", "favicon.ico") + favicon_assets_dir = os.path.dirname(default_favicon) favicon_url = os.getenv("LITELLM_FAVICON_URL", "") @@ -12331,42 +12338,30 @@ async def get_favicon(): raise HTTPException(status_code=404, detail="Default favicon not found") if favicon_url.startswith(("http://", "https://")): - try: - from litellm.llms.custom_httpx.http_handler import get_async_httpx_client - from litellm.types.llms.custom_http import httpxSpecialProvider - - async_client = get_async_httpx_client( - llm_provider=httpxSpecialProvider.UI, - params={"timeout": 5.0}, - ) - response = await async_client.get(favicon_url) - if response.status_code == 200: - content_type = response.headers.get("content-type", "image/x-icon") - return Response( - content=response.content, - media_type=content_type, - ) - else: - verbose_proxy_logger.warning( - "Failed to fetch favicon from %s: status %s", - favicon_url, - response.status_code, - ) - if os.path.exists(default_favicon): - return FileResponse(default_favicon, media_type="image/x-icon") - raise HTTPException(status_code=404, detail="Favicon not found") - except HTTPException: - raise - except Exception as e: - verbose_proxy_logger.debug( - "Error downloading favicon from %s: %s", favicon_url, e - ) - if os.path.exists(default_favicon): - return FileResponse(default_favicon, media_type="image/x-icon") - raise HTTPException(status_code=404, detail="Favicon not found") + # SSRF + content-type validation — the helper rejects + # private/internal/cloud-metadata targets and non-image responses. + image_bytes = await fetch_validated_image_bytes(favicon_url) + if image_bytes is not None: + return Response(content=image_bytes, media_type="image/x-icon") + verbose_proxy_logger.warning( + "Failed to fetch favicon from %s — falling back to default", favicon_url + ) + if os.path.exists(default_favicon): + return FileResponse(default_favicon, media_type="image/x-icon") + raise HTTPException(status_code=404, detail="Favicon not found") else: - if os.path.exists(favicon_url): - return FileResponse(favicon_url, media_type="image/x-icon") + # ``/get_favicon`` is unauthenticated. Validate any admin-configured + # local path against an allowlist of asset roots — see ``/get_image`` + # for the LFI threat-model rationale. + allowed_local_roots = [favicon_assets_dir, current_dir] + safe_favicon = resolve_local_asset_path(favicon_url, allowed_local_roots) + if safe_favicon is not None: + return FileResponse(safe_favicon, media_type="image/x-icon") + verbose_proxy_logger.warning( + "LITELLM_FAVICON_URL %r is outside the allowed asset roots or " + "does not exist, falling back to default favicon", + favicon_url, + ) if os.path.exists(default_favicon): return FileResponse(default_favicon, media_type="image/x-icon") raise HTTPException(status_code=404, detail="Favicon not found") diff --git a/tests/test_litellm/proxy/common_utils/test_static_asset_utils.py b/tests/test_litellm/proxy/common_utils/test_static_asset_utils.py new file mode 100644 index 000000000000..6fe3b04bf02d --- /dev/null +++ b/tests/test_litellm/proxy/common_utils/test_static_asset_utils.py @@ -0,0 +1,252 @@ +""" +Unit tests for the unauthenticated logo / favicon endpoint helpers. + +Closes the LFI half of GHSA-3pcp-536p-ghjc and the SSRF half of +GHSA-pjc9-2hw6-78rr — both endpoints accept an admin-set env var and +return its contents unauthenticated, so the helpers must reject: + +* local paths outside the allowed asset roots (LFI) +* HTTP URLs resolving to private / cloud-metadata addresses (SSRF) +* non-image responses (smuggling JSON / credentials through the + ``image/jpeg`` response wrapper) +""" + +import os +import sys +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest + +sys.path.insert(0, os.path.abspath("../../../..")) + +from litellm.litellm_core_utils.url_utils import SSRFError +from litellm.proxy.common_utils.static_asset_utils import ( + ALLOWED_IMAGE_CONTENT_TYPES, + fetch_validated_image_bytes, + resolve_local_asset_path, +) + + +class TestResolveLocalAssetPath: + @pytest.fixture + def assets_dir(self, tmp_path): + d = tmp_path / "assets" + d.mkdir() + return d + + def test_returns_resolved_path_for_file_inside_allowed_root(self, assets_dir): + logo = assets_dir / "logo.jpg" + logo.write_bytes(b"\xff\xd8\xff") # JPEG header + + result = resolve_local_asset_path(str(logo), [str(assets_dir)]) + assert result == str(logo.resolve()) + + def test_rejects_path_outside_allowed_roots(self, tmp_path, assets_dir): + outside = tmp_path / "secret.txt" + outside.write_text("password=hunter2") + + result = resolve_local_asset_path(str(outside), [str(assets_dir)]) + assert result is None + + def test_rejects_etc_passwd(self, assets_dir): + # The canonical LFI shape from GHSA-3pcp-536p-ghjc. + result = resolve_local_asset_path("/etc/passwd", [str(assets_dir)]) + assert result is None + + def test_rejects_proc_self_environ(self, assets_dir): + # Process environment exfil — same shape as /etc/passwd attack. + result = resolve_local_asset_path("/proc/self/environ", [str(assets_dir)]) + assert result is None + + def test_rejects_symlink_pointing_outside_allowed_roots(self, tmp_path, assets_dir): + secret = tmp_path / "secret.txt" + secret.write_text("password=hunter2") + sneaky = assets_dir / "logo.jpg" + os.symlink(str(secret), str(sneaky)) + + result = resolve_local_asset_path(str(sneaky), [str(assets_dir)]) + assert result is None + + def test_rejects_path_traversal_with_dotdot(self, tmp_path, assets_dir): + outside = tmp_path / "secret.txt" + outside.write_text("nope") + traversal = str(assets_dir / ".." / "secret.txt") + + result = resolve_local_asset_path(traversal, [str(assets_dir)]) + assert result is None + + def test_rejects_directory(self, assets_dir): + # Path containment requires the resolved entry to be a regular file. + result = resolve_local_asset_path(str(assets_dir), [str(assets_dir)]) + assert result is None + + def test_rejects_nonexistent_file_inside_allowed_root(self, assets_dir): + # Even a path that *would* be inside the allowed root must point at + # an existing file — otherwise we shouldn't pretend it resolves. + result = resolve_local_asset_path( + str(assets_dir / "missing.jpg"), [str(assets_dir)] + ) + assert result is None + + def test_rejects_empty_or_none(self, assets_dir): + assert resolve_local_asset_path("", [str(assets_dir)]) is None + + def test_skips_empty_or_invalid_roots(self, assets_dir): + logo = assets_dir / "logo.jpg" + logo.write_bytes(b"\xff\xd8\xff") + result = resolve_local_asset_path( + str(logo), ["", str(assets_dir), "/nonexistent/root"] + ) + assert result == str(logo.resolve()) + + +class TestFetchValidatedImageBytes: + @pytest.fixture + def mock_async_client(self): + client = MagicMock() + client.get = AsyncMock() + return client + + @pytest.mark.asyncio + async def test_blocks_private_ip_via_validate_url(self, mock_async_client): + # The SSRF half of GHSA-pjc9-2hw6-78rr — admin sets logo URL to + # http://169.254.169.254/iam, attacker hits /get_image, exfils creds. + with ( + patch( + "litellm.proxy.common_utils.static_asset_utils.validate_url", + side_effect=SSRFError("blocked: 169.254.169.254"), + ), + patch( + "litellm.proxy.common_utils.static_asset_utils.get_async_httpx_client", + return_value=mock_async_client, + ), + ): + result = await fetch_validated_image_bytes("http://169.254.169.254/iam") + + assert result is None + # The fetch must not be attempted when the URL is rejected. + mock_async_client.get.assert_not_called() + + @pytest.mark.asyncio + async def test_rejects_non_image_content_type(self, mock_async_client): + # Even when the URL passes SSRF, the upstream response must be an + # image. Otherwise an attacker could redirect to an upstream that + # returns ``application/json`` AWS creds and have them tunneled + # through the ``image/jpeg`` response wrapper. + mock_response = MagicMock() + mock_response.status_code = 200 + mock_response.headers = {"content-type": "application/json"} + mock_response.content = b'{"AccessKeyId": "..."}' + mock_async_client.get.return_value = mock_response + + with ( + patch( + "litellm.proxy.common_utils.static_asset_utils.validate_url", + return_value=("http://cdn.example/logo", "cdn.example"), + ), + patch( + "litellm.proxy.common_utils.static_asset_utils.get_async_httpx_client", + return_value=mock_async_client, + ), + ): + result = await fetch_validated_image_bytes("http://cdn.example/logo") + + assert result is None + + @pytest.mark.asyncio + async def test_returns_bytes_for_valid_image_response(self, mock_async_client): + png_bytes = b"\x89PNG\r\n\x1a\nfake png body" + mock_response = MagicMock() + mock_response.status_code = 200 + mock_response.headers = {"content-type": "image/png; charset=binary"} + mock_response.content = png_bytes + mock_async_client.get.return_value = mock_response + + with ( + patch( + "litellm.proxy.common_utils.static_asset_utils.validate_url", + return_value=( + "https://cdn.example/logo.png", + "cdn.example", + ), + ), + patch( + "litellm.proxy.common_utils.static_asset_utils.get_async_httpx_client", + return_value=mock_async_client, + ), + ): + result = await fetch_validated_image_bytes("https://cdn.example/logo.png") + + assert result == png_bytes + + @pytest.mark.asyncio + async def test_returns_none_on_non_200_response(self, mock_async_client): + mock_response = MagicMock() + mock_response.status_code = 404 + mock_response.headers = {"content-type": "image/png"} + mock_async_client.get.return_value = mock_response + + with ( + patch( + "litellm.proxy.common_utils.static_asset_utils.validate_url", + return_value=("https://cdn.example/logo", "cdn.example"), + ), + patch( + "litellm.proxy.common_utils.static_asset_utils.get_async_httpx_client", + return_value=mock_async_client, + ), + ): + result = await fetch_validated_image_bytes("https://cdn.example/logo") + + assert result is None + + @pytest.mark.asyncio + async def test_returns_none_on_fetch_exception(self, mock_async_client): + mock_async_client.get.side_effect = Exception("connection reset") + + with ( + patch( + "litellm.proxy.common_utils.static_asset_utils.validate_url", + return_value=("https://cdn.example/logo", "cdn.example"), + ), + patch( + "litellm.proxy.common_utils.static_asset_utils.get_async_httpx_client", + return_value=mock_async_client, + ), + ): + result = await fetch_validated_image_bytes("https://cdn.example/logo") + + assert result is None + + @pytest.mark.asyncio + async def test_returns_none_for_empty_url(self): + result = await fetch_validated_image_bytes("") + assert result is None + + @pytest.mark.parametrize( + "content_type", + sorted(ALLOWED_IMAGE_CONTENT_TYPES), + ) + @pytest.mark.asyncio + async def test_accepts_each_allowed_image_content_type( + self, mock_async_client, content_type + ): + mock_response = MagicMock() + mock_response.status_code = 200 + mock_response.headers = {"content-type": content_type} + mock_response.content = b"image-bytes" + mock_async_client.get.return_value = mock_response + + with ( + patch( + "litellm.proxy.common_utils.static_asset_utils.validate_url", + return_value=("https://cdn.example/logo", "cdn.example"), + ), + patch( + "litellm.proxy.common_utils.static_asset_utils.get_async_httpx_client", + return_value=mock_async_client, + ), + ): + result = await fetch_validated_image_bytes("https://cdn.example/logo") + + assert result == b"image-bytes" From 9ef8572d6701ac5bcc7cdb53a4b3810dfc712471 Mon Sep 17 00:00:00 2001 From: user <70670632+stuxf@users.noreply.github.com> Date: Wed, 29 Apr 2026 21:15:21 +0000 Subject: [PATCH 02/12] fix(proxy): /get_logo_url no longer discloses local UI_LOGO_PATH MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The unauthenticated ``/get_logo_url`` endpoint returned the ``UI_LOGO_PATH`` env var verbatim. For HTTP(S) URLs this is intended — the dashboard loads the logo directly from a public/internal CDN. For local filesystem paths it was an information disclosure: any caller could fetch ``/get_logo_url`` and read admin-only filesystem details like ``UI_LOGO_PATH=/etc/litellm/secret-config.json``. Now the endpoint returns the URL only when it begins with ``http://`` or ``https://``. For local paths (or unset) it returns an empty string — the dashboard falls back to ``/get_image`` which serves the file via the path-containment guard added in the previous commit. Tests parametrize the disclosure-blocked cases (``/etc/...``, ``/proc/self/environ``, relative paths) and confirm HTTP / HTTPS URLs still pass through unchanged. Co-Authored-By: Claude Opus 4.7 (1M context) --- litellm/proxy/proxy_server.py | 15 +++++- tests/test_litellm/proxy/test_proxy_server.py | 54 +++++++++++++++++++ 2 files changed, 67 insertions(+), 2 deletions(-) diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py index bbd528072fd8..ead8e8f6b9db 100644 --- a/litellm/proxy/proxy_server.py +++ b/litellm/proxy/proxy_server.py @@ -12223,9 +12223,20 @@ async def claim_onboarding_link(data: InvitationClaim): @app.get("/get_logo_url", include_in_schema=False) def get_logo_url(): - """Get the current logo URL from environment""" + """Get the current logo URL from environment. + + Only HTTP(S) URLs are returned — those are intended to be loaded + directly by the browser from a public/internal CDN. Local file + paths set via ``UI_LOGO_PATH`` are NOT returned: they are admin- + only filesystem details, the dashboard falls back to ``/get_image`` + which serves the file (with path containment) instead. Without + this filter, the unauthenticated endpoint would disclose internal + hostnames or filesystem paths to any caller. + """ logo_path = os.getenv("UI_LOGO_PATH", "") - return {"logo_url": logo_path} + if logo_path.startswith(("http://", "https://")): + return {"logo_url": logo_path} + return {"logo_url": ""} @app.get("/get_image", include_in_schema=False) diff --git a/tests/test_litellm/proxy/test_proxy_server.py b/tests/test_litellm/proxy/test_proxy_server.py index 1f4f82a64efb..da3f963f9de9 100644 --- a/tests/test_litellm/proxy/test_proxy_server.py +++ b/tests/test_litellm/proxy/test_proxy_server.py @@ -457,6 +457,60 @@ def test_fallback_login_has_no_deprecation_banner(client_no_auth): assert " Date: Wed, 29 Apr 2026 21:18:07 +0000 Subject: [PATCH 03/12] fix(proxy): also accept LITELLM_ASSETS_PATH for /get_favicon local path MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Align ``/get_favicon``'s allowed-root list with ``/get_image``'s. Both endpoints now accept paths under any of: * ``LITELLM_ASSETS_PATH`` (or its default — ``/var/lib/litellm/assets`` for non-root, the package dir otherwise) * the package's bundled-asset dir (``proxy/_experimental/out`` for the default favicon, ``proxy/`` for the default logo) * the proxy package dir (``current_dir``) as a final fallback Without this, an admin who put a custom favicon under ``LITELLM_ASSETS_PATH`` (e.g. mounted into the container at ``/var/lib/litellm/assets/favicon.ico``) would have the favicon endpoint silently fall back to the default after the previous commit's path-containment guard. The logo endpoint already accepted this root. Co-Authored-By: Claude Opus 4.7 (1M context) --- litellm/proxy/proxy_server.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py index ead8e8f6b9db..ef17aab73e66 100644 --- a/litellm/proxy/proxy_server.py +++ b/litellm/proxy/proxy_server.py @@ -12339,7 +12339,13 @@ async def get_favicon(): current_dir = os.path.dirname(os.path.abspath(__file__)) default_favicon = os.path.join(current_dir, "_experimental", "out", "favicon.ico") - favicon_assets_dir = os.path.dirname(default_favicon) + favicon_default_dir = os.path.dirname(default_favicon) + + # Admin-managed asset directory (parallels ``/get_image``). Custom + # favicons placed here remain readable post-fix. + is_non_root = os.getenv("LITELLM_NON_ROOT", "").lower() == "true" + default_assets_dir = "/var/lib/litellm/assets" if is_non_root else current_dir + assets_dir = os.getenv("LITELLM_ASSETS_PATH", default_assets_dir) favicon_url = os.getenv("LITELLM_FAVICON_URL", "") @@ -12364,7 +12370,7 @@ async def get_favicon(): # ``/get_favicon`` is unauthenticated. Validate any admin-configured # local path against an allowlist of asset roots — see ``/get_image`` # for the LFI threat-model rationale. - allowed_local_roots = [favicon_assets_dir, current_dir] + allowed_local_roots = [assets_dir, favicon_default_dir, current_dir] safe_favicon = resolve_local_asset_path(favicon_url, allowed_local_roots) if safe_favicon is not None: return FileResponse(safe_favicon, media_type="image/x-icon") From 55d393d77d34b58e802e00c9d645f9aa0a338300 Mon Sep 17 00:00:00 2001 From: user <70670632+stuxf@users.noreply.github.com> Date: Wed, 29 Apr 2026 21:47:41 +0000 Subject: [PATCH 04/12] =?UTF-8?q?fix(static-assets):=20unblock=20CI=20?= =?UTF-8?q?=E2=80=94=20pass=20headers=20explicitly=20+=20harden=20+=20upda?= =?UTF-8?q?te=20legacy=20tests?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three CI failures from the previous push, all addressed: * ``lint`` (mypy): ``async_client.get(url, **request_kwargs)`` confused mypy because ``AsyncHTTPHandler.get``'s second positional arg is typed ``bool | None``. Switched to an explicit branch: ``await async_client.get(rewritten_url, headers={"host": host_header})`` for the HTTP-rewritten case, plain ``get(rewritten_url)`` otherwise. * ``proxy-infra`` / ``test_get_image_custom_local_logo_bypasses_cache``: the existing test set ``UI_LOGO_PATH=/app/custom_logo.jpg`` with no ``LITELLM_ASSETS_PATH``, asserting the path was served verbatim. That was the LFI behaviour the new path-containment guard closes. Updated the test to set ``LITELLM_ASSETS_PATH=/app`` so the path is inside an allowed root, and patched the helper's ``realpath`` / ``isfile`` to go along with the mocked filesystem. Test intent (bypass cache when ``UI_LOGO_PATH`` is local) is preserved. * ``auth-and-jwt`` / ``test_get_image_cache_logic``: existing test built a ``Mock`` response without ``headers``, so the new Content-Type check tripped on ``Mock().split(";")[0]``. Two fixes: 1. Set ``mock_response.headers = {"content-type": "image/jpeg"}`` on the test (matches the real upstream contract — a logo CDN always sets a Content-Type). 2. Make ``fetch_validated_image_bytes`` defensive: if the Content-Type header is missing or non-string, treat as non-image and fall back to default. Closes a subtle hole — pre-fix, an upstream that omits Content-Type entirely would have served arbitrary bytes under the ``image/jpeg`` wrapper. Co-Authored-By: Claude Opus 4.7 (1M context) --- .../proxy/common_utils/static_asset_utils.py | 21 ++++++++++++------- tests/proxy_unit_tests/test_get_image.py | 5 ++++- tests/test_litellm/proxy/test_proxy_server.py | 15 ++++++++++++- 3 files changed, 32 insertions(+), 9 deletions(-) diff --git a/litellm/proxy/common_utils/static_asset_utils.py b/litellm/proxy/common_utils/static_asset_utils.py index 0643572118b2..ffead95dcfe7 100644 --- a/litellm/proxy/common_utils/static_asset_utils.py +++ b/litellm/proxy/common_utils/static_asset_utils.py @@ -101,16 +101,17 @@ async def fetch_validated_image_bytes( # returns the original hostname for the Host header. For HTTPS with # ssl_verify enabled, it returns the URL unchanged (TLS hostname # validation handles DNS rebinding). - request_kwargs = {} - if rewritten_url != url: - request_kwargs["headers"] = {"host": host_header} - async_client = get_async_httpx_client( llm_provider=httpxSpecialProvider.UI, params={"timeout": timeout_s}, ) try: - response = await async_client.get(rewritten_url, **request_kwargs) + if rewritten_url != url: + response = await async_client.get( + rewritten_url, headers={"host": host_header} + ) + else: + response = await async_client.get(rewritten_url) except Exception as exc: verbose_proxy_logger.debug("Asset fetch failed for %r: %s", url, exc) return None @@ -118,9 +119,15 @@ async def fetch_validated_image_bytes( if response.status_code != 200: return None - content_type = ( - (response.headers.get("content-type") or "").split(";")[0].strip().lower() + raw_content_type = ( + response.headers.get("content-type") if hasattr(response, "headers") else None ) + if not isinstance(raw_content_type, str): + # Defensive: if upstream omits Content-Type entirely, treat as + # non-image. (Also keeps ``Mock`` responses without a configured + # ``headers`` from blowing up the content-type check.) + return None + content_type = raw_content_type.split(";")[0].strip().lower() if content_type not in ALLOWED_IMAGE_CONTENT_TYPES: verbose_proxy_logger.warning( "Asset fetch from %r returned non-image content-type %r — refusing to serve.", diff --git a/tests/proxy_unit_tests/test_get_image.py b/tests/proxy_unit_tests/test_get_image.py index ad8c2672754e..f14c6da55397 100644 --- a/tests/proxy_unit_tests/test_get_image.py +++ b/tests/proxy_unit_tests/test_get_image.py @@ -64,10 +64,13 @@ async def test_get_image_cache_logic(): if os.path.exists(cache_path): os.remove(cache_path) - # Mock response + # Mock response — set headers explicitly so the Content-Type + # validation added for GHSA-pjc9-2hw6-78rr accepts the response + # as a legitimate image. mock_response = mock.Mock() mock_response.status_code = 200 mock_response.content = b"fake image data" + mock_response.headers = {"content-type": "image/jpeg"} with mock.patch( "litellm.llms.custom_httpx.http_handler.AsyncHTTPHandler.get" diff --git a/tests/test_litellm/proxy/test_proxy_server.py b/tests/test_litellm/proxy/test_proxy_server.py index da3f963f9de9..1a77e39aa808 100644 --- a/tests/test_litellm/proxy/test_proxy_server.py +++ b/tests/test_litellm/proxy/test_proxy_server.py @@ -4047,9 +4047,12 @@ async def test_get_image_custom_local_logo_bypasses_cache(monkeypatch): from litellm.proxy.proxy_server import get_image + # Use a path inside the allowlisted ``LITELLM_ASSETS_PATH`` — the + # path-containment guard added for GHSA-3pcp-536p-ghjc rejects any + # local UI_LOGO_PATH outside the allowed asset roots. + monkeypatch.setenv("LITELLM_ASSETS_PATH", "/app") monkeypatch.setenv("UI_LOGO_PATH", "/app/custom_logo.jpg") monkeypatch.delenv("LITELLM_NON_ROOT", raising=False) - monkeypatch.delenv("LITELLM_ASSETS_PATH", raising=False) calls_to_file_response = [] @@ -4063,6 +4066,16 @@ def fake_file_response(path, **kwargs): patch( "litellm.proxy.proxy_server.FileResponse", side_effect=fake_file_response ), + # The path-containment helper calls ``os.path.realpath`` and + # ``os.path.isfile`` — make them play along for the test path. + patch( + "litellm.proxy.common_utils.static_asset_utils.os.path.realpath", + side_effect=lambda p: p, + ), + patch( + "litellm.proxy.common_utils.static_asset_utils.os.path.isfile", + return_value=True, + ), ): await get_image() From 75d1a0116e82e6d53a3d8f54552a391e2d364eab Mon Sep 17 00:00:00 2001 From: user <70670632+stuxf@users.noreply.github.com> Date: Wed, 29 Apr 2026 21:57:22 +0000 Subject: [PATCH 05/12] fix(static-assets): use async_safe_get; drop SVG; serve bytes inline on cache miss MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three review items addressed: * **Veria (Medium): SSRF via redirect.** ``fetch_validated_image_bytes`` was calling ``validate_url(url)`` once and then fetching with the default httpx client, so a 3xx to an internal IP would have been followed unvalidated. Switched to ``async_safe_get`` (the existing SSRF primitive used elsewhere in the codebase) which walks each redirect hop, re-validates, and rejects redirects to blocked networks. Default ``litellm.user_url_validation`` is True so protection is on out of the box. * **Greptile (P2): SVG can embed JS.** Removed ``image/svg+xml`` from the allowed-Content-Type set. The hardcoded response media type (``image/jpeg`` / ``image/x-icon``) means a real SVG body wouldn't render as SVG anyway in modern browsers — the allowlist entry was giving up XSS surface for no actual SVG-rendering benefit. If real SVG support is wanted later, that's a deliberate feature PR with CSP / nosniff bundled. * **Greptile (P2): cache-write OSError drops validated bytes.** When the upstream fetch succeeded but ``open(cache_path, "wb")`` raised (read-only assets dir), the bytes were discarded and the default logo was served — a silent regression for that deployment. Now serve the validated bytes inline via ``Response(...)`` as a fallback before falling back to default. Tests: - Replaced low-level mocks of ``validate_url`` with mocks of ``async_safe_get`` directly, exercising the helper's contract rather than the SSRF primitive's internals. - New ``test_rejects_svg_content_type`` confirms SVG is blocked. - ``test_get_image_cache_logic`` fixture now sets ``mock_response.is_redirect = False`` so ``async_safe_get`` doesn't treat the Mock's truthy attribute as a redirect. Co-Authored-By: Claude Opus 4.7 (1M context) --- .../proxy/common_utils/static_asset_utils.py | 50 +++--- litellm/proxy/proxy_server.py | 25 +-- tests/proxy_unit_tests/test_get_image.py | 6 +- .../common_utils/test_static_asset_utils.py | 142 +++++++----------- 4 files changed, 99 insertions(+), 124 deletions(-) diff --git a/litellm/proxy/common_utils/static_asset_utils.py b/litellm/proxy/common_utils/static_asset_utils.py index ffead95dcfe7..74fe9939aabe 100644 --- a/litellm/proxy/common_utils/static_asset_utils.py +++ b/litellm/proxy/common_utils/static_asset_utils.py @@ -18,7 +18,7 @@ from typing import List, Optional from litellm._logging import verbose_proxy_logger -from litellm.litellm_core_utils.url_utils import SSRFError, validate_url +from litellm.litellm_core_utils.url_utils import SSRFError, async_safe_get from litellm.llms.custom_httpx.http_handler import get_async_httpx_client from litellm.types.llms.custom_http import httpxSpecialProvider @@ -26,13 +26,19 @@ # without this, an admin-configured URL whose upstream returns # ``application/json`` (e.g. cloud metadata, internal API) would still be # served back to the caller verbatim. +# +# ``image/svg+xml`` is intentionally NOT in this list: SVG is the only +# common image format that can embed JavaScript, and the endpoint is +# unauthenticated. An admin-configured CDN serving a crafted SVG would +# otherwise reach unauthenticated callers; removing SVG closes the +# residual XSS surface even though the response is served with a +# hardcoded ``image/jpeg`` / ``image/x-icon`` media type. ALLOWED_IMAGE_CONTENT_TYPES = frozenset( { "image/jpeg", "image/jpg", "image/png", "image/gif", - "image/svg+xml", "image/webp", "image/x-icon", "image/vnd.microsoft.icon", @@ -76,19 +82,27 @@ async def fetch_validated_image_bytes( url: str, *, timeout_s: float = 5.0 ) -> Optional[bytes]: """ - Fetch ``url`` with SSRF protection (always-on) and Content-Type - validation. Returns the raw bytes on success, ``None`` on any - failure (blocked target, non-200, or non-image response). + Fetch ``url`` with SSRF protection and Content-Type validation. + Returns the raw bytes on success, ``None`` on any failure (blocked + target, redirect to a blocked target, non-200, or non-image + response). - The SSRF guard is enforced unconditionally — these endpoints are - unauthenticated, so the admin-facing ``litellm.user_url_validation`` - toggle does not apply. An admin who opted out of URL validation for - LLM provider paths should not also expose ``/get_image`` to SSRF. + Delegates to ``async_safe_get`` so each redirect hop is re-validated + against ``BLOCKED_NETWORKS`` (a 3xx to ``169.254.169.254`` is + rejected, not followed). Honours ``litellm.user_url_validation`` + like every other SSRF-aware fetch in the codebase; the toggle + defaults to True, and an admin who has explicitly disabled URL + validation has opted out of SSRF protection globally. """ if not url: return None + + async_client = get_async_httpx_client( + llm_provider=httpxSpecialProvider.UI, + params={"timeout": timeout_s}, + ) try: - rewritten_url, host_header = validate_url(url) + response = await async_safe_get(async_client, url) except SSRFError as exc: verbose_proxy_logger.warning( "Blocked unauthenticated asset fetch — SSRF guard rejected %r: %s", @@ -96,22 +110,6 @@ async def fetch_validated_image_bytes( exc, ) return None - - # ``validate_url`` rewrites HTTP URLs to point at a validated IP and - # returns the original hostname for the Host header. For HTTPS with - # ssl_verify enabled, it returns the URL unchanged (TLS hostname - # validation handles DNS rebinding). - async_client = get_async_httpx_client( - llm_provider=httpxSpecialProvider.UI, - params={"timeout": timeout_s}, - ) - try: - if rewritten_url != url: - response = await async_client.get( - rewritten_url, headers={"host": host_header} - ) - else: - response = await async_client.get(rewritten_url) except Exception as exc: verbose_proxy_logger.debug("Asset fetch failed for %r: %s", url, exc) return None diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py index ef17aab73e66..736f259f23a5 100644 --- a/litellm/proxy/proxy_server.py +++ b/litellm/proxy/proxy_server.py @@ -12312,16 +12312,21 @@ async def get_image(): # SSRF + content-type validation — the helper rejects # private/internal/cloud-metadata targets and non-image responses. image_bytes = await fetch_validated_image_bytes(logo_path) - if image_bytes is not None: - try: - with open(cache_path, "wb") as f: - f.write(image_bytes) - return FileResponse(cache_path, media_type="image/jpeg") - except OSError as e: - verbose_proxy_logger.debug( - "Could not write logo cache to %s: %s", cache_path, e - ) - return FileResponse(default_logo, media_type="image/jpeg") + if image_bytes is None: + return FileResponse(default_logo, media_type="image/jpeg") + try: + with open(cache_path, "wb") as f: + f.write(image_bytes) + return FileResponse(cache_path, media_type="image/jpeg") + except OSError as e: + # Read-only assets dir: serve the validated bytes inline + # rather than dropping them and returning the default logo. + from fastapi.responses import Response + + verbose_proxy_logger.debug( + "Could not write logo cache to %s: %s — serving inline", cache_path, e + ) + return Response(content=image_bytes, media_type="image/jpeg") else: # Default logo (resolved from the bundled asset, not user-controlled). return FileResponse(logo_path, media_type="image/jpeg") diff --git a/tests/proxy_unit_tests/test_get_image.py b/tests/proxy_unit_tests/test_get_image.py index f14c6da55397..bdc7743faacf 100644 --- a/tests/proxy_unit_tests/test_get_image.py +++ b/tests/proxy_unit_tests/test_get_image.py @@ -65,12 +65,14 @@ async def test_get_image_cache_logic(): os.remove(cache_path) # Mock response — set headers explicitly so the Content-Type - # validation added for GHSA-pjc9-2hw6-78rr accepts the response - # as a legitimate image. + # validation accepts the response as a legitimate image, and set + # ``is_redirect=False`` so ``async_safe_get`` doesn't try to walk + # a redirect chain. mock_response = mock.Mock() mock_response.status_code = 200 mock_response.content = b"fake image data" mock_response.headers = {"content-type": "image/jpeg"} + mock_response.is_redirect = False with mock.patch( "litellm.llms.custom_httpx.http_handler.AsyncHTTPHandler.get" diff --git a/tests/test_litellm/proxy/common_utils/test_static_asset_utils.py b/tests/test_litellm/proxy/common_utils/test_static_asset_utils.py index 6fe3b04bf02d..0c6b7f189734 100644 --- a/tests/test_litellm/proxy/common_utils/test_static_asset_utils.py +++ b/tests/test_litellm/proxy/common_utils/test_static_asset_utils.py @@ -101,121 +101,89 @@ def test_skips_empty_or_invalid_roots(self, assets_dir): class TestFetchValidatedImageBytes: - @pytest.fixture - def mock_async_client(self): - client = MagicMock() - client.get = AsyncMock() - return client - - @pytest.mark.asyncio - async def test_blocks_private_ip_via_validate_url(self, mock_async_client): - # The SSRF half of GHSA-pjc9-2hw6-78rr — admin sets logo URL to - # http://169.254.169.254/iam, attacker hits /get_image, exfils creds. - with ( + """ + The helper now delegates to ``async_safe_get`` for the SSRF guard + + redirect handling. Tests mock ``async_safe_get`` directly so they + exercise the helper's contract (Content-Type validation, status code + handling, exception fallthrough) without depending on the SSRF + primitive's internals. + """ + + @staticmethod + def _patches(*, async_safe_get_return=None, async_safe_get_side_effect=None): + return [ patch( - "litellm.proxy.common_utils.static_asset_utils.validate_url", - side_effect=SSRFError("blocked: 169.254.169.254"), + "litellm.proxy.common_utils.static_asset_utils.async_safe_get", + new_callable=AsyncMock, + return_value=async_safe_get_return, + side_effect=async_safe_get_side_effect, ), patch( "litellm.proxy.common_utils.static_asset_utils.get_async_httpx_client", - return_value=mock_async_client, + return_value=MagicMock(), ), + ] + + @pytest.mark.asyncio + async def test_blocks_ssrf_target(self): + # The SSRF half of GHSA-pjc9-2hw6-78rr — admin sets logo URL to + # http://169.254.169.254/iam, attacker hits /get_image, exfils creds. + # ``async_safe_get`` raises SSRFError on private/metadata targets + # and on redirect hops to those targets (covers the redirect + # bypass Veria flagged on the previous iteration). + with ( + self._patches( + async_safe_get_side_effect=SSRFError("blocked: 169.254.169.254") + )[0], + self._patches()[1], ): result = await fetch_validated_image_bytes("http://169.254.169.254/iam") - assert result is None - # The fetch must not be attempted when the URL is rejected. - mock_async_client.get.assert_not_called() @pytest.mark.asyncio - async def test_rejects_non_image_content_type(self, mock_async_client): + async def test_rejects_non_image_content_type(self): # Even when the URL passes SSRF, the upstream response must be an - # image. Otherwise an attacker could redirect to an upstream that + # image. Otherwise an attacker could point at an upstream that # returns ``application/json`` AWS creds and have them tunneled # through the ``image/jpeg`` response wrapper. mock_response = MagicMock() mock_response.status_code = 200 mock_response.headers = {"content-type": "application/json"} mock_response.content = b'{"AccessKeyId": "..."}' - mock_async_client.get.return_value = mock_response - with ( - patch( - "litellm.proxy.common_utils.static_asset_utils.validate_url", - return_value=("http://cdn.example/logo", "cdn.example"), - ), - patch( - "litellm.proxy.common_utils.static_asset_utils.get_async_httpx_client", - return_value=mock_async_client, - ), - ): + with self._patches(async_safe_get_return=mock_response)[0], self._patches()[1]: result = await fetch_validated_image_bytes("http://cdn.example/logo") - assert result is None @pytest.mark.asyncio - async def test_returns_bytes_for_valid_image_response(self, mock_async_client): + async def test_returns_bytes_for_valid_image_response(self): png_bytes = b"\x89PNG\r\n\x1a\nfake png body" mock_response = MagicMock() mock_response.status_code = 200 mock_response.headers = {"content-type": "image/png; charset=binary"} mock_response.content = png_bytes - mock_async_client.get.return_value = mock_response - with ( - patch( - "litellm.proxy.common_utils.static_asset_utils.validate_url", - return_value=( - "https://cdn.example/logo.png", - "cdn.example", - ), - ), - patch( - "litellm.proxy.common_utils.static_asset_utils.get_async_httpx_client", - return_value=mock_async_client, - ), - ): + with self._patches(async_safe_get_return=mock_response)[0], self._patches()[1]: result = await fetch_validated_image_bytes("https://cdn.example/logo.png") - assert result == png_bytes @pytest.mark.asyncio - async def test_returns_none_on_non_200_response(self, mock_async_client): + async def test_returns_none_on_non_200_response(self): mock_response = MagicMock() mock_response.status_code = 404 mock_response.headers = {"content-type": "image/png"} - mock_async_client.get.return_value = mock_response - with ( - patch( - "litellm.proxy.common_utils.static_asset_utils.validate_url", - return_value=("https://cdn.example/logo", "cdn.example"), - ), - patch( - "litellm.proxy.common_utils.static_asset_utils.get_async_httpx_client", - return_value=mock_async_client, - ), - ): + with self._patches(async_safe_get_return=mock_response)[0], self._patches()[1]: result = await fetch_validated_image_bytes("https://cdn.example/logo") - assert result is None @pytest.mark.asyncio - async def test_returns_none_on_fetch_exception(self, mock_async_client): - mock_async_client.get.side_effect = Exception("connection reset") - + async def test_returns_none_on_fetch_exception(self): with ( - patch( - "litellm.proxy.common_utils.static_asset_utils.validate_url", - return_value=("https://cdn.example/logo", "cdn.example"), - ), - patch( - "litellm.proxy.common_utils.static_asset_utils.get_async_httpx_client", - return_value=mock_async_client, - ), + self._patches(async_safe_get_side_effect=Exception("connection reset"))[0], + self._patches()[1], ): result = await fetch_validated_image_bytes("https://cdn.example/logo") - assert result is None @pytest.mark.asyncio @@ -223,30 +191,32 @@ async def test_returns_none_for_empty_url(self): result = await fetch_validated_image_bytes("") assert result is None + @pytest.mark.asyncio + async def test_rejects_svg_content_type(self): + # ``image/svg+xml`` is intentionally NOT in the allowlist for + # unauthenticated endpoints — SVG is the only common image + # format that can embed JavaScript. + mock_response = MagicMock() + mock_response.status_code = 200 + mock_response.headers = {"content-type": "image/svg+xml"} + mock_response.content = b"" + + with self._patches(async_safe_get_return=mock_response)[0], self._patches()[1]: + result = await fetch_validated_image_bytes("https://cdn.example/x.svg") + assert result is None + @pytest.mark.parametrize( "content_type", sorted(ALLOWED_IMAGE_CONTENT_TYPES), ) @pytest.mark.asyncio - async def test_accepts_each_allowed_image_content_type( - self, mock_async_client, content_type - ): + async def test_accepts_each_allowed_image_content_type(self, content_type): mock_response = MagicMock() mock_response.status_code = 200 mock_response.headers = {"content-type": content_type} mock_response.content = b"image-bytes" - mock_async_client.get.return_value = mock_response - with ( - patch( - "litellm.proxy.common_utils.static_asset_utils.validate_url", - return_value=("https://cdn.example/logo", "cdn.example"), - ), - patch( - "litellm.proxy.common_utils.static_asset_utils.get_async_httpx_client", - return_value=mock_async_client, - ), - ): + with self._patches(async_safe_get_return=mock_response)[0], self._patches()[1]: result = await fetch_validated_image_bytes("https://cdn.example/logo") assert result == b"image-bytes" From c112bdf2c15efe20c25939e280f000b2555efde4 Mon Sep 17 00:00:00 2001 From: user <70670632+stuxf@users.noreply.github.com> Date: Wed, 29 Apr 2026 22:01:57 +0000 Subject: [PATCH 06/12] =?UTF-8?q?chore(static-assets):=20/simplify=20pass?= =?UTF-8?q?=20=E2=80=94=20top-level=20Response=20import=20+=20cleaner=20te?= =?UTF-8?q?st=20fixture?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two cleanups from the /simplify review pass: * ``Response`` was imported inside the ``except OSError`` branch in ``/get_image`` and at the top of ``/get_favicon``. Per the project's no-inline-imports rule (CLAUDE.md), hoisted to the existing ``from fastapi.responses import (...)`` block at the top of ``proxy_server.py``. * The test class's ``_patches()`` helper returned a 2-element list of patch context managers and tests indexed into them via ``self._patches(...)[0], self._patches()[1]`` — two distinct calls with confusing aliasing semantics. Restructured to: - module-level ``_patch_async_safe_get(...)`` that returns a single patch context manager - autouse fixture that patches ``get_async_httpx_client`` for every test in the file (it's the same patch in every case) - small ``_image_response(...)`` factory to deduplicate Mock setup Tests now read as ``with _patch_async_safe_get(return_value=...):`` with no list-indexing or duplicate Mock construction. Co-Authored-By: Claude Opus 4.7 (1M context) --- litellm/proxy/proxy_server.py | 5 +- .../common_utils/test_static_asset_utils.py | 121 +++++++++--------- 2 files changed, 58 insertions(+), 68 deletions(-) diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py index 736f259f23a5..b5288f71654b 100644 --- a/litellm/proxy/proxy_server.py +++ b/litellm/proxy/proxy_server.py @@ -605,6 +605,7 @@ def generate_feedback_box(): JSONResponse, ORJSONResponse, RedirectResponse, + Response, StreamingResponse, ) from fastapi.routing import APIRouter @@ -12321,8 +12322,6 @@ async def get_image(): except OSError as e: # Read-only assets dir: serve the validated bytes inline # rather than dropping them and returning the default logo. - from fastapi.responses import Response - verbose_proxy_logger.debug( "Could not write logo cache to %s: %s — serving inline", cache_path, e ) @@ -12335,8 +12334,6 @@ async def get_image(): @app.get("/get_favicon", include_in_schema=False) async def get_favicon(): """Get custom favicon for the admin UI.""" - from fastapi.responses import Response - from litellm.proxy.common_utils.static_asset_utils import ( fetch_validated_image_bytes, resolve_local_asset_path, diff --git a/tests/test_litellm/proxy/common_utils/test_static_asset_utils.py b/tests/test_litellm/proxy/common_utils/test_static_asset_utils.py index 0c6b7f189734..ad9ac0b83317 100644 --- a/tests/test_litellm/proxy/common_utils/test_static_asset_utils.py +++ b/tests/test_litellm/proxy/common_utils/test_static_asset_utils.py @@ -100,89 +100,86 @@ def test_skips_empty_or_invalid_roots(self, assets_dir): assert result == str(logo.resolve()) +def _image_response(*, status_code=200, content_type="image/png", body=b"image-bytes"): + response = MagicMock() + response.status_code = status_code + response.headers = {"content-type": content_type} + response.content = body + return response + + +def _patch_async_safe_get(*, return_value=None, side_effect=None): + return patch( + "litellm.proxy.common_utils.static_asset_utils.async_safe_get", + new_callable=AsyncMock, + return_value=return_value, + side_effect=side_effect, + ) + + +@pytest.fixture(autouse=True) +def _patch_httpx_client(): + # The helper builds the client first, then hands it to async_safe_get + # — patch it once for every test so we never accidentally instantiate + # a real client. + with patch( + "litellm.proxy.common_utils.static_asset_utils.get_async_httpx_client", + return_value=MagicMock(), + ): + yield + + class TestFetchValidatedImageBytes: """ - The helper now delegates to ``async_safe_get`` for the SSRF guard + + The helper delegates to ``async_safe_get`` for the SSRF guard + redirect handling. Tests mock ``async_safe_get`` directly so they exercise the helper's contract (Content-Type validation, status code handling, exception fallthrough) without depending on the SSRF primitive's internals. """ - @staticmethod - def _patches(*, async_safe_get_return=None, async_safe_get_side_effect=None): - return [ - patch( - "litellm.proxy.common_utils.static_asset_utils.async_safe_get", - new_callable=AsyncMock, - return_value=async_safe_get_return, - side_effect=async_safe_get_side_effect, - ), - patch( - "litellm.proxy.common_utils.static_asset_utils.get_async_httpx_client", - return_value=MagicMock(), - ), - ] - @pytest.mark.asyncio async def test_blocks_ssrf_target(self): - # The SSRF half of GHSA-pjc9-2hw6-78rr — admin sets logo URL to - # http://169.254.169.254/iam, attacker hits /get_image, exfils creds. # ``async_safe_get`` raises SSRFError on private/metadata targets - # and on redirect hops to those targets (covers the redirect - # bypass Veria flagged on the previous iteration). - with ( - self._patches( - async_safe_get_side_effect=SSRFError("blocked: 169.254.169.254") - )[0], - self._patches()[1], - ): + # and on redirect hops to those targets — closes the SSRF half of + # GHSA-pjc9-2hw6-78rr including the redirect-bypass variant. + with _patch_async_safe_get(side_effect=SSRFError("blocked: 169.254.169.254")): result = await fetch_validated_image_bytes("http://169.254.169.254/iam") assert result is None @pytest.mark.asyncio async def test_rejects_non_image_content_type(self): - # Even when the URL passes SSRF, the upstream response must be an - # image. Otherwise an attacker could point at an upstream that - # returns ``application/json`` AWS creds and have them tunneled - # through the ``image/jpeg`` response wrapper. - mock_response = MagicMock() - mock_response.status_code = 200 - mock_response.headers = {"content-type": "application/json"} - mock_response.content = b'{"AccessKeyId": "..."}' - - with self._patches(async_safe_get_return=mock_response)[0], self._patches()[1]: + # Without this, an upstream that returns ``application/json`` AWS + # creds would be tunneled through the ``image/jpeg`` response + # wrapper. + with _patch_async_safe_get( + return_value=_image_response( + content_type="application/json", body=b'{"AccessKeyId": "..."}' + ), + ): result = await fetch_validated_image_bytes("http://cdn.example/logo") assert result is None @pytest.mark.asyncio async def test_returns_bytes_for_valid_image_response(self): png_bytes = b"\x89PNG\r\n\x1a\nfake png body" - mock_response = MagicMock() - mock_response.status_code = 200 - mock_response.headers = {"content-type": "image/png; charset=binary"} - mock_response.content = png_bytes - - with self._patches(async_safe_get_return=mock_response)[0], self._patches()[1]: + with _patch_async_safe_get( + return_value=_image_response( + content_type="image/png; charset=binary", body=png_bytes + ), + ): result = await fetch_validated_image_bytes("https://cdn.example/logo.png") assert result == png_bytes @pytest.mark.asyncio async def test_returns_none_on_non_200_response(self): - mock_response = MagicMock() - mock_response.status_code = 404 - mock_response.headers = {"content-type": "image/png"} - - with self._patches(async_safe_get_return=mock_response)[0], self._patches()[1]: + with _patch_async_safe_get(return_value=_image_response(status_code=404)): result = await fetch_validated_image_bytes("https://cdn.example/logo") assert result is None @pytest.mark.asyncio async def test_returns_none_on_fetch_exception(self): - with ( - self._patches(async_safe_get_side_effect=Exception("connection reset"))[0], - self._patches()[1], - ): + with _patch_async_safe_get(side_effect=Exception("connection reset")): result = await fetch_validated_image_bytes("https://cdn.example/logo") assert result is None @@ -196,12 +193,12 @@ async def test_rejects_svg_content_type(self): # ``image/svg+xml`` is intentionally NOT in the allowlist for # unauthenticated endpoints — SVG is the only common image # format that can embed JavaScript. - mock_response = MagicMock() - mock_response.status_code = 200 - mock_response.headers = {"content-type": "image/svg+xml"} - mock_response.content = b"" - - with self._patches(async_safe_get_return=mock_response)[0], self._patches()[1]: + with _patch_async_safe_get( + return_value=_image_response( + content_type="image/svg+xml", + body=b"", + ), + ): result = await fetch_validated_image_bytes("https://cdn.example/x.svg") assert result is None @@ -211,12 +208,8 @@ async def test_rejects_svg_content_type(self): ) @pytest.mark.asyncio async def test_accepts_each_allowed_image_content_type(self, content_type): - mock_response = MagicMock() - mock_response.status_code = 200 - mock_response.headers = {"content-type": content_type} - mock_response.content = b"image-bytes" - - with self._patches(async_safe_get_return=mock_response)[0], self._patches()[1]: + with _patch_async_safe_get( + return_value=_image_response(content_type=content_type), + ): result = await fetch_validated_image_bytes("https://cdn.example/logo") - assert result == b"image-bytes" From 89aa13fdf3910eb1c3c97c78bc1b00f6cb7a3395 Mon Sep 17 00:00:00 2001 From: user <70670632+stuxf@users.noreply.github.com> Date: Wed, 29 Apr 2026 22:47:43 +0000 Subject: [PATCH 07/12] fix(static-assets): also wrap admin-only Vault token verification in async_safe_get MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Variant analysis on the unauthenticated /get_image SSRF surfaced one related sink in an admin-only endpoint: ``test_hashicorp_vault_connection`` in ``config_override_endpoints.py:402`` calls ``async_client.get(f"{vault_addr}/v1/auth/token/lookup-self")`` with no SSRF guard. ``vault_addr`` is admin-set, so the threat model is "admin misconfig (or attacker with admin creds) pivots Vault calls to cloud metadata or another internal IP." Same fix shape as the unauthenticated endpoints: wrap in ``async_safe_get`` so each redirect hop is re-validated and private networks are rejected. Admins running against a legitimate internal Vault should add the host to ``litellm.user_url_allowed_hosts`` — the existing escape hatch already used elsewhere in the codebase. Co-Authored-By: Claude Opus 4.7 (1M context) --- .../management_endpoints/config_override_endpoints.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/litellm/proxy/management_endpoints/config_override_endpoints.py b/litellm/proxy/management_endpoints/config_override_endpoints.py index d78c5526e669..6e7cedd632f2 100644 --- a/litellm/proxy/management_endpoints/config_override_endpoints.py +++ b/litellm/proxy/management_endpoints/config_override_endpoints.py @@ -391,7 +391,14 @@ async def test_hashicorp_vault_connection( detail=f"Vault authentication failed: {e}", ) - # Step 2: Verify the token is valid via token/lookup-self + # Step 2: Verify the token is valid via token/lookup-self. + # ``vault_addr`` is admin-set; wrapping in ``async_safe_get`` prevents + # a misconfigured (or attacker-influenced) value from pivoting the + # request to cloud metadata or another internal IP. Admins running + # against an internal Vault should add the host to + # ``litellm.user_url_allowed_hosts``. + from litellm.litellm_core_utils.url_utils import async_safe_get + try: async_client = get_async_httpx_client( llm_provider=httpxSpecialProvider.SecretManager @@ -399,7 +406,7 @@ async def test_hashicorp_vault_connection( lookup_url = f"{client.vault_addr}/v1/auth/token/lookup-self" if client.vault_namespace: headers["X-Vault-Namespace"] = client.vault_namespace - response = await async_client.get(lookup_url, headers=headers) + response = await async_safe_get(async_client, lookup_url, headers=headers) response.raise_for_status() except Exception as e: raise HTTPException( From 14473ed8f964e1e345f90a7a190680fadf86b45b Mon Sep 17 00:00:00 2001 From: user <70670632+stuxf@users.noreply.github.com> Date: Wed, 29 Apr 2026 23:04:34 +0000 Subject: [PATCH 08/12] =?UTF-8?q?fix(static-assets):=20ruff=20F811=20?= =?UTF-8?q?=E2=80=94=20drop=20duplicate=20Response=20import?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ``Response`` is already imported from the top-level ``fastapi`` package via the multi-line ``from fastapi import (...)`` block at the top of the file (along with ``Depends``, ``HTTPException``, etc.) — ``fastapi.Response`` is the same class that ``fastapi.responses`` re-exports. The earlier ``from fastapi.responses import Response`` addition triggered ruff F811 for redefinition. Co-Authored-By: Claude Opus 4.7 (1M context) --- litellm/proxy/proxy_server.py | 1 - 1 file changed, 1 deletion(-) diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py index b5288f71654b..776c05dfccb5 100644 --- a/litellm/proxy/proxy_server.py +++ b/litellm/proxy/proxy_server.py @@ -605,7 +605,6 @@ def generate_feedback_box(): JSONResponse, ORJSONResponse, RedirectResponse, - Response, StreamingResponse, ) from fastapi.routing import APIRouter From 2c11fa0df38c4caac383d82f2cd639340312f56c Mon Sep 17 00:00:00 2001 From: user <70670632+stuxf@users.noreply.github.com> Date: Wed, 29 Apr 2026 20:56:45 -0700 Subject: [PATCH 09/12] chore(static-assets): keep vault tester out of asset hardening --- .../management_endpoints/config_override_endpoints.py | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/litellm/proxy/management_endpoints/config_override_endpoints.py b/litellm/proxy/management_endpoints/config_override_endpoints.py index 6e7cedd632f2..d78c5526e669 100644 --- a/litellm/proxy/management_endpoints/config_override_endpoints.py +++ b/litellm/proxy/management_endpoints/config_override_endpoints.py @@ -391,14 +391,7 @@ async def test_hashicorp_vault_connection( detail=f"Vault authentication failed: {e}", ) - # Step 2: Verify the token is valid via token/lookup-self. - # ``vault_addr`` is admin-set; wrapping in ``async_safe_get`` prevents - # a misconfigured (or attacker-influenced) value from pivoting the - # request to cloud metadata or another internal IP. Admins running - # against an internal Vault should add the host to - # ``litellm.user_url_allowed_hosts``. - from litellm.litellm_core_utils.url_utils import async_safe_get - + # Step 2: Verify the token is valid via token/lookup-self try: async_client = get_async_httpx_client( llm_provider=httpxSpecialProvider.SecretManager @@ -406,7 +399,7 @@ async def test_hashicorp_vault_connection( lookup_url = f"{client.vault_addr}/v1/auth/token/lookup-self" if client.vault_namespace: headers["X-Vault-Namespace"] = client.vault_namespace - response = await async_safe_get(async_client, lookup_url, headers=headers) + response = await async_client.get(lookup_url, headers=headers) response.raise_for_status() except Exception as e: raise HTTPException( From 215f538d4f8a9f8d614d193ead54bfc2af93e80b Mon Sep 17 00:00:00 2001 From: user <70670632+stuxf@users.noreply.github.com> Date: Thu, 30 Apr 2026 11:30:57 -0700 Subject: [PATCH 10/12] fix(static-assets): browser-load remote branding assets --- .../proxy/common_utils/static_asset_utils.py | 143 +++-------- litellm/proxy/proxy_server.py | 98 +++----- tests/proxy_unit_tests/test_get_image.py | 74 ++---- .../common_utils/test_static_asset_utils.py | 230 +++++------------- tests/test_litellm/proxy/test_proxy_server.py | 96 +++----- 5 files changed, 167 insertions(+), 474 deletions(-) diff --git a/litellm/proxy/common_utils/static_asset_utils.py b/litellm/proxy/common_utils/static_asset_utils.py index 74fe9939aabe..c108af2b475c 100644 --- a/litellm/proxy/common_utils/static_asset_utils.py +++ b/litellm/proxy/common_utils/static_asset_utils.py @@ -1,61 +1,30 @@ -""" -Helpers for the unauthenticated logo / favicon endpoints (``/get_image`` and -``/get_favicon``). Both read an admin-set environment variable that may be a -local filesystem path or an HTTP URL, fetch the resource, and return the -bytes verbatim to any unauthenticated caller. - -Without these helpers: - -* a misconfigured / hostile env var like ``UI_LOGO_PATH=/etc/passwd`` lets - any unauthenticated caller exfiltrate the file (LFI — GHSA-3pcp-536p-ghjc). -* a legitimate-looking ``UI_LOGO_PATH=http://internal-service/branding.png`` - pointing at a private host lets any unauthenticated caller exfiltrate - whatever that host returns (SSRF — GHSA-pjc9-2hw6-78rr), regardless of - whether the body is actually an image. -""" +"""Helpers for unauthenticated logo / favicon endpoints.""" import os -from typing import List, Optional +from typing import Optional, Tuple from litellm._logging import verbose_proxy_logger -from litellm.litellm_core_utils.url_utils import SSRFError, async_safe_get -from litellm.llms.custom_httpx.http_handler import get_async_httpx_client -from litellm.types.llms.custom_http import httpxSpecialProvider - -# Conservative allowlist of image MIME types. Anything else is refused — -# without this, an admin-configured URL whose upstream returns -# ``application/json`` (e.g. cloud metadata, internal API) would still be -# served back to the caller verbatim. -# -# ``image/svg+xml`` is intentionally NOT in this list: SVG is the only -# common image format that can embed JavaScript, and the endpoint is -# unauthenticated. An admin-configured CDN serving a crafted SVG would -# otherwise reach unauthenticated callers; removing SVG closes the -# residual XSS surface even though the response is served with a -# hardcoded ``image/jpeg`` / ``image/x-icon`` media type. -ALLOWED_IMAGE_CONTENT_TYPES = frozenset( - { - "image/jpeg", - "image/jpg", - "image/png", - "image/gif", - "image/webp", - "image/x-icon", - "image/vnd.microsoft.icon", - } -) +LOCAL_IMAGE_HEADER_BYTES = 512 + + +def detect_local_image_media_type(header: bytes) -> Optional[str]: + """Return a browser image media type for supported local image signatures.""" + if header[0:8] == b"\x89PNG\r\n\x1a\n": + return "image/png" + if header[0:4] == b"GIF8" and header[5:6] == b"a": + return "image/gif" + if header[0:3] == b"\xff\xd8\xff": + return "image/jpeg" + if header[0:4] == b"RIFF" and header[8:12] == b"WEBP": + return "image/webp" + if header[0:4] in (b"\x00\x00\x01\x00", b"\x00\x00\x02\x00"): + return "image/x-icon" + return None -def resolve_local_asset_path(candidate: str, allowed_roots: List[str]) -> Optional[str]: - """ - Resolve ``candidate`` and return its absolute path only if it lives - within one of ``allowed_roots``. Returns None on any miss (caller - falls back to the bundled default asset). - Resolution uses ``realpath`` to follow symlinks, so a symlink inside - ``allowed_roots`` pointing at ``/etc/passwd`` is rejected the same as - a direct ``/etc/passwd`` config. - """ +def resolve_validated_local_image_path(candidate: str) -> Optional[Tuple[str, str]]: + """Resolve ``candidate`` only when it is an existing supported image file.""" if not candidate: return None try: @@ -64,74 +33,20 @@ def resolve_local_asset_path(candidate: str, allowed_roots: List[str]) -> Option return None if not os.path.isfile(resolved): return None - for root in allowed_roots: - if not root: - continue - try: - root_resolved = os.path.realpath(root) - except (OSError, ValueError): - continue - if resolved == root_resolved: - return resolved - if resolved.startswith(root_resolved + os.sep): - return resolved - return None - -async def fetch_validated_image_bytes( - url: str, *, timeout_s: float = 5.0 -) -> Optional[bytes]: - """ - Fetch ``url`` with SSRF protection and Content-Type validation. - Returns the raw bytes on success, ``None`` on any failure (blocked - target, redirect to a blocked target, non-200, or non-image - response). - - Delegates to ``async_safe_get`` so each redirect hop is re-validated - against ``BLOCKED_NETWORKS`` (a 3xx to ``169.254.169.254`` is - rejected, not followed). Honours ``litellm.user_url_validation`` - like every other SSRF-aware fetch in the codebase; the toggle - defaults to True, and an admin who has explicitly disabled URL - validation has opted out of SSRF protection globally. - """ - if not url: - return None - - async_client = get_async_httpx_client( - llm_provider=httpxSpecialProvider.UI, - params={"timeout": timeout_s}, - ) try: - response = await async_safe_get(async_client, url) - except SSRFError as exc: - verbose_proxy_logger.warning( - "Blocked unauthenticated asset fetch — SSRF guard rejected %r: %s", - url, - exc, - ) - return None - except Exception as exc: - verbose_proxy_logger.debug("Asset fetch failed for %r: %s", url, exc) + with open(resolved, "rb") as f: + header = f.read(LOCAL_IMAGE_HEADER_BYTES) + except OSError as exc: + verbose_proxy_logger.debug("Could not read local asset %r: %s", candidate, exc) return None - if response.status_code != 200: - return None - - raw_content_type = ( - response.headers.get("content-type") if hasattr(response, "headers") else None - ) - if not isinstance(raw_content_type, str): - # Defensive: if upstream omits Content-Type entirely, treat as - # non-image. (Also keeps ``Mock`` responses without a configured - # ``headers`` from blowing up the content-type check.) - return None - content_type = raw_content_type.split(";")[0].strip().lower() - if content_type not in ALLOWED_IMAGE_CONTENT_TYPES: + media_type = detect_local_image_media_type(header) + if media_type is None: verbose_proxy_logger.warning( - "Asset fetch from %r returned non-image content-type %r — refusing to serve.", - url, - content_type, + "Local asset %r is not a supported image file; falling back to default.", + candidate, ) return None - return response.content + return resolved, media_type diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py index 776c05dfccb5..b65455e567c5 100644 --- a/litellm/proxy/proxy_server.py +++ b/litellm/proxy/proxy_server.py @@ -12281,72 +12281,57 @@ async def get_image(): logo_path = os.getenv("UI_LOGO_PATH", default_logo) verbose_proxy_logger.debug("Reading logo from path: %s", logo_path) - # ``/get_image`` is unauthenticated. Validate any admin-configured local - # path against an allowlist of asset roots — without this guard, an - # env var like ``UI_LOGO_PATH=/etc/passwd`` lets any caller exfiltrate - # the file via this endpoint. from litellm.proxy.common_utils.static_asset_utils import ( - fetch_validated_image_bytes, - resolve_local_asset_path, + resolve_validated_local_image_path, ) - allowed_local_roots = [assets_dir, current_dir] - if logo_path != default_logo and not logo_path.startswith(("http://", "https://")): - safe_logo = resolve_local_asset_path(logo_path, allowed_local_roots) + safe_logo = resolve_validated_local_image_path(logo_path) if safe_logo is not None: - return FileResponse(safe_logo, media_type="image/jpeg") + safe_logo_path, media_type = safe_logo + return FileResponse(safe_logo_path, media_type=media_type) verbose_proxy_logger.warning( - "UI_LOGO_PATH %r is outside the allowed asset roots or does not " - "exist, falling back to default logo", + "UI_LOGO_PATH %r is not a supported image file or does not exist, " + "falling back to default logo", logo_path, ) logo_path = default_logo - # [OPTIMIZATION] For HTTP URLs and default logo, check if the cached image exists + # Remote logo URLs are loaded by the browser. The proxy should not fetch + # arbitrary admin-configured URLs server-side. + if logo_path.startswith(("http://", "https://")): + return RedirectResponse(url=logo_path) + + # [OPTIMIZATION] For default logo, check if the cached image exists. + # Validate the cache before serving so stale pre-fix cache files cannot + # keep exposing non-image responses fetched before this hardening. if os.path.exists(cache_path): - return FileResponse(cache_path, media_type="image/jpeg") + safe_cache = resolve_validated_local_image_path(cache_path) + if safe_cache is not None: + safe_cache_path, media_type = safe_cache + return FileResponse(safe_cache_path, media_type=media_type) + verbose_proxy_logger.warning( + "Ignoring cached logo at %s because it is not a supported image file", + cache_path, + ) - # Check if the logo path is an HTTP/HTTPS URL - if logo_path.startswith(("http://", "https://")): - # SSRF + content-type validation — the helper rejects - # private/internal/cloud-metadata targets and non-image responses. - image_bytes = await fetch_validated_image_bytes(logo_path) - if image_bytes is None: - return FileResponse(default_logo, media_type="image/jpeg") - try: - with open(cache_path, "wb") as f: - f.write(image_bytes) - return FileResponse(cache_path, media_type="image/jpeg") - except OSError as e: - # Read-only assets dir: serve the validated bytes inline - # rather than dropping them and returning the default logo. - verbose_proxy_logger.debug( - "Could not write logo cache to %s: %s — serving inline", cache_path, e - ) - return Response(content=image_bytes, media_type="image/jpeg") - else: - # Default logo (resolved from the bundled asset, not user-controlled). - return FileResponse(logo_path, media_type="image/jpeg") + # Default logo (resolved from the bundled asset, not user-controlled). + safe_logo = resolve_validated_local_image_path(logo_path) + if safe_logo is not None: + safe_logo_path, media_type = safe_logo + return FileResponse(safe_logo_path, media_type=media_type) + return FileResponse(default_site_logo, media_type="image/jpeg") @app.get("/get_favicon", include_in_schema=False) async def get_favicon(): """Get custom favicon for the admin UI.""" from litellm.proxy.common_utils.static_asset_utils import ( - fetch_validated_image_bytes, - resolve_local_asset_path, + resolve_validated_local_image_path, ) current_dir = os.path.dirname(os.path.abspath(__file__)) default_favicon = os.path.join(current_dir, "_experimental", "out", "favicon.ico") - favicon_default_dir = os.path.dirname(default_favicon) - - # Admin-managed asset directory (parallels ``/get_image``). Custom - # favicons placed here remain readable post-fix. - is_non_root = os.getenv("LITELLM_NON_ROOT", "").lower() == "true" - default_assets_dir = "/var/lib/litellm/assets" if is_non_root else current_dir - assets_dir = os.getenv("LITELLM_ASSETS_PATH", default_assets_dir) favicon_url = os.getenv("LITELLM_FAVICON_URL", "") @@ -12356,28 +12341,15 @@ async def get_favicon(): raise HTTPException(status_code=404, detail="Default favicon not found") if favicon_url.startswith(("http://", "https://")): - # SSRF + content-type validation — the helper rejects - # private/internal/cloud-metadata targets and non-image responses. - image_bytes = await fetch_validated_image_bytes(favicon_url) - if image_bytes is not None: - return Response(content=image_bytes, media_type="image/x-icon") - verbose_proxy_logger.warning( - "Failed to fetch favicon from %s — falling back to default", favicon_url - ) - if os.path.exists(default_favicon): - return FileResponse(default_favicon, media_type="image/x-icon") - raise HTTPException(status_code=404, detail="Favicon not found") + return RedirectResponse(url=favicon_url) else: - # ``/get_favicon`` is unauthenticated. Validate any admin-configured - # local path against an allowlist of asset roots — see ``/get_image`` - # for the LFI threat-model rationale. - allowed_local_roots = [assets_dir, favicon_default_dir, current_dir] - safe_favicon = resolve_local_asset_path(favicon_url, allowed_local_roots) + safe_favicon = resolve_validated_local_image_path(favicon_url) if safe_favicon is not None: - return FileResponse(safe_favicon, media_type="image/x-icon") + safe_favicon_path, media_type = safe_favicon + return FileResponse(safe_favicon_path, media_type=media_type) verbose_proxy_logger.warning( - "LITELLM_FAVICON_URL %r is outside the allowed asset roots or " - "does not exist, falling back to default favicon", + "LITELLM_FAVICON_URL %r is not a supported image file or does not " + "exist, falling back to default favicon", favicon_url, ) if os.path.exists(default_favicon): diff --git a/tests/proxy_unit_tests/test_get_image.py b/tests/proxy_unit_tests/test_get_image.py index bdc7743faacf..57e472f86c4d 100644 --- a/tests/proxy_unit_tests/test_get_image.py +++ b/tests/proxy_unit_tests/test_get_image.py @@ -5,90 +5,48 @@ # Standard path insertion sys.path.insert(0, os.path.abspath("../..")) -import pytest import httpx +import pytest from litellm.proxy.proxy_server import app @pytest.mark.asyncio -async def test_get_image_error_handling(): +async def test_get_image_redirects_remote_logo_without_server_fetch(monkeypatch): """ - Test that get_image handles network errors gracefully and doesn't hang. + Remote logo URLs should be loaded by the browser, not fetched by the proxy. """ - # Set an unreachable URL - os.environ["UI_LOGO_PATH"] = "http://invalid-url-12345.com/logo.jpg" + monkeypatch.setenv("UI_LOGO_PATH", "http://invalid-url-12345.com/logo.jpg") - # Clear cache - parent_dir = os.path.dirname( - os.path.dirname( - app.__file__ - if hasattr(app, "__file__") - else "litellm/proxy/proxy_server.py" - ) - ) - cache_path = os.path.join(parent_dir, "proxy", "cached_logo.jpg") - if os.path.exists(cache_path): - os.remove(cache_path) - - # Mock AsyncHTTPHandler to simulate a timeout or connection error with mock.patch( "litellm.llms.custom_httpx.http_handler.AsyncHTTPHandler.get" ) as mock_get: - mock_get.side_effect = httpx.ConnectError("Network is unreachable") - async with httpx.AsyncClient( transport=httpx.ASGITransport(app=app), base_url="http://testserver" ) as ac: response = await ac.get("/get_image") - assert response.status_code == 200 - assert response.headers["content-type"] == "image/jpeg" + assert response.status_code == 307 + assert response.headers["location"] == "http://invalid-url-12345.com/logo.jpg" + mock_get.assert_not_called() @pytest.mark.asyncio -async def test_get_image_cache_logic(): +async def test_get_image_remote_logo_does_not_use_stale_cache(monkeypatch, tmp_path): """ - Test that once cached, get_image doesn't hit the network. + A stale pre-fix cache file should not mask a configured remote logo URL. """ - os.environ["UI_LOGO_PATH"] = "http://example.com/logo.jpg" - - # Clear cache - parent_dir = os.path.dirname( - os.path.dirname( - app.__file__ - if hasattr(app, "__file__") - else "litellm/proxy/proxy_server.py" - ) - ) - cache_path = os.path.join(parent_dir, "proxy", "cached_logo.jpg") - if os.path.exists(cache_path): - os.remove(cache_path) - - # Mock response — set headers explicitly so the Content-Type - # validation accepts the response as a legitimate image, and set - # ``is_redirect=False`` so ``async_safe_get`` doesn't try to walk - # a redirect chain. - mock_response = mock.Mock() - mock_response.status_code = 200 - mock_response.content = b"fake image data" - mock_response.headers = {"content-type": "image/jpeg"} - mock_response.is_redirect = False + monkeypatch.setenv("UI_LOGO_PATH", "http://example.com/logo.jpg") + monkeypatch.setenv("LITELLM_ASSETS_PATH", str(tmp_path)) + (tmp_path / "cached_logo.jpg").write_bytes(b"\xff\xd8\xff cached logo") with mock.patch( "litellm.llms.custom_httpx.http_handler.AsyncHTTPHandler.get" ) as mock_get: - mock_get.return_value = mock_response - async with httpx.AsyncClient( transport=httpx.ASGITransport(app=app), base_url="http://testserver" ) as ac: - # First call - should hit download logic - response1 = await ac.get("/get_image") - assert response1.status_code == 200 - assert mock_get.call_count == 1 + response = await ac.get("/get_image") - # Second call - should hit cache - response2 = await ac.get("/get_image") - assert response2.status_code == 200 - # If cache works, mock_get shouldn't be called again - assert mock_get.call_count == 1 + assert response.status_code == 307 + assert response.headers["location"] == "http://example.com/logo.jpg" + mock_get.assert_not_called() diff --git a/tests/test_litellm/proxy/common_utils/test_static_asset_utils.py b/tests/test_litellm/proxy/common_utils/test_static_asset_utils.py index ad9ac0b83317..93f7ccc92c2a 100644 --- a/tests/test_litellm/proxy/common_utils/test_static_asset_utils.py +++ b/tests/test_litellm/proxy/common_utils/test_static_asset_utils.py @@ -1,215 +1,97 @@ """ -Unit tests for the unauthenticated logo / favicon endpoint helpers. +Unit tests for unauthenticated logo / favicon endpoint helpers. -Closes the LFI half of GHSA-3pcp-536p-ghjc and the SSRF half of -GHSA-pjc9-2hw6-78rr — both endpoints accept an admin-set env var and -return its contents unauthenticated, so the helpers must reject: - -* local paths outside the allowed asset roots (LFI) -* HTTP URLs resolving to private / cloud-metadata addresses (SSRF) -* non-image responses (smuggling JSON / credentials through the - ``image/jpeg`` response wrapper) +Local image paths are an existing deployment workflow, so the helper keeps +arbitrary local image paths working while refusing non-image files like +``/etc/passwd`` or ``/proc/self/environ``. """ import os import sys -from unittest.mock import AsyncMock, MagicMock, patch import pytest sys.path.insert(0, os.path.abspath("../../../..")) -from litellm.litellm_core_utils.url_utils import SSRFError from litellm.proxy.common_utils.static_asset_utils import ( - ALLOWED_IMAGE_CONTENT_TYPES, - fetch_validated_image_bytes, - resolve_local_asset_path, + detect_local_image_media_type, + resolve_validated_local_image_path, ) -class TestResolveLocalAssetPath: - @pytest.fixture - def assets_dir(self, tmp_path): - d = tmp_path / "assets" - d.mkdir() - return d +@pytest.mark.parametrize( + ("body", "media_type"), + [ + (b"\x89PNG\r\n\x1a\nfake png body", "image/png"), + (b"GIF89a fake gif body", "image/gif"), + (b"\xff\xd8\xff fake jpeg body", "image/jpeg"), + (b"RIFF\x00\x00\x00\x00WEBP fake webp body", "image/webp"), + (b"\x00\x00\x01\x00 fake ico body", "image/x-icon"), + ], +) +def test_detect_local_image_media_type_accepts_supported_images(body, media_type): + assert detect_local_image_media_type(body) == media_type + - def test_returns_resolved_path_for_file_inside_allowed_root(self, assets_dir): - logo = assets_dir / "logo.jpg" - logo.write_bytes(b"\xff\xd8\xff") # JPEG header +def test_detect_local_image_media_type_rejects_non_images(): + assert detect_local_image_media_type(b"root:x:0:0:root:/root:/bin/bash") is None - result = resolve_local_asset_path(str(logo), [str(assets_dir)]) - assert result == str(logo.resolve()) - def test_rejects_path_outside_allowed_roots(self, tmp_path, assets_dir): - outside = tmp_path / "secret.txt" - outside.write_text("password=hunter2") +class TestResolveValidatedLocalImagePath: + def test_returns_resolved_path_for_arbitrary_local_image(self, tmp_path): + logo = tmp_path / "logo.png" + logo.write_bytes(b"\x89PNG\r\n\x1a\nfake png body") - result = resolve_local_asset_path(str(outside), [str(assets_dir)]) - assert result is None + result = resolve_validated_local_image_path(str(logo)) - def test_rejects_etc_passwd(self, assets_dir): - # The canonical LFI shape from GHSA-3pcp-536p-ghjc. - result = resolve_local_asset_path("/etc/passwd", [str(assets_dir)]) + assert result == (str(logo.resolve()), "image/png") + + def test_rejects_etc_passwd(self): + result = resolve_validated_local_image_path("/etc/passwd") assert result is None - def test_rejects_proc_self_environ(self, assets_dir): - # Process environment exfil — same shape as /etc/passwd attack. - result = resolve_local_asset_path("/proc/self/environ", [str(assets_dir)]) + def test_rejects_proc_self_environ(self): + result = resolve_validated_local_image_path("/proc/self/environ") assert result is None - def test_rejects_symlink_pointing_outside_allowed_roots(self, tmp_path, assets_dir): + def test_rejects_symlink_pointing_to_non_image(self, tmp_path): secret = tmp_path / "secret.txt" secret.write_text("password=hunter2") - sneaky = assets_dir / "logo.jpg" - os.symlink(str(secret), str(sneaky)) - - result = resolve_local_asset_path(str(sneaky), [str(assets_dir)]) - assert result is None + symlink = tmp_path / "logo.png" + os.symlink(str(secret), str(symlink)) - def test_rejects_path_traversal_with_dotdot(self, tmp_path, assets_dir): - outside = tmp_path / "secret.txt" - outside.write_text("nope") - traversal = str(assets_dir / ".." / "secret.txt") + result = resolve_validated_local_image_path(str(symlink)) - result = resolve_local_asset_path(traversal, [str(assets_dir)]) assert result is None - def test_rejects_directory(self, assets_dir): - # Path containment requires the resolved entry to be a regular file. - result = resolve_local_asset_path(str(assets_dir), [str(assets_dir)]) - assert result is None + def test_accepts_symlink_pointing_to_image(self, tmp_path): + logo = tmp_path / "real_logo.png" + logo.write_bytes(b"\x89PNG\r\n\x1a\nfake png body") + symlink = tmp_path / "logo.png" + os.symlink(str(logo), str(symlink)) - def test_rejects_nonexistent_file_inside_allowed_root(self, assets_dir): - # Even a path that *would* be inside the allowed root must point at - # an existing file — otherwise we shouldn't pretend it resolves. - result = resolve_local_asset_path( - str(assets_dir / "missing.jpg"), [str(assets_dir)] - ) - assert result is None + result = resolve_validated_local_image_path(str(symlink)) - def test_rejects_empty_or_none(self, assets_dir): - assert resolve_local_asset_path("", [str(assets_dir)]) is None - - def test_skips_empty_or_invalid_roots(self, assets_dir): - logo = assets_dir / "logo.jpg" - logo.write_bytes(b"\xff\xd8\xff") - result = resolve_local_asset_path( - str(logo), ["", str(assets_dir), "/nonexistent/root"] - ) - assert result == str(logo.resolve()) - - -def _image_response(*, status_code=200, content_type="image/png", body=b"image-bytes"): - response = MagicMock() - response.status_code = status_code - response.headers = {"content-type": content_type} - response.content = body - return response - - -def _patch_async_safe_get(*, return_value=None, side_effect=None): - return patch( - "litellm.proxy.common_utils.static_asset_utils.async_safe_get", - new_callable=AsyncMock, - return_value=return_value, - side_effect=side_effect, - ) - - -@pytest.fixture(autouse=True) -def _patch_httpx_client(): - # The helper builds the client first, then hands it to async_safe_get - # — patch it once for every test so we never accidentally instantiate - # a real client. - with patch( - "litellm.proxy.common_utils.static_asset_utils.get_async_httpx_client", - return_value=MagicMock(), - ): - yield - - -class TestFetchValidatedImageBytes: - """ - The helper delegates to ``async_safe_get`` for the SSRF guard + - redirect handling. Tests mock ``async_safe_get`` directly so they - exercise the helper's contract (Content-Type validation, status code - handling, exception fallthrough) without depending on the SSRF - primitive's internals. - """ - - @pytest.mark.asyncio - async def test_blocks_ssrf_target(self): - # ``async_safe_get`` raises SSRFError on private/metadata targets - # and on redirect hops to those targets — closes the SSRF half of - # GHSA-pjc9-2hw6-78rr including the redirect-bypass variant. - with _patch_async_safe_get(side_effect=SSRFError("blocked: 169.254.169.254")): - result = await fetch_validated_image_bytes("http://169.254.169.254/iam") - assert result is None + assert result == (str(logo.resolve()), "image/png") - @pytest.mark.asyncio - async def test_rejects_non_image_content_type(self): - # Without this, an upstream that returns ``application/json`` AWS - # creds would be tunneled through the ``image/jpeg`` response - # wrapper. - with _patch_async_safe_get( - return_value=_image_response( - content_type="application/json", body=b'{"AccessKeyId": "..."}' - ), - ): - result = await fetch_validated_image_bytes("http://cdn.example/logo") - assert result is None + def test_rejects_path_traversal_to_non_image(self, tmp_path): + assets_dir = tmp_path / "assets" + assets_dir.mkdir() + secret = tmp_path / "secret.txt" + secret.write_text("nope") + traversal = str(assets_dir / ".." / "secret.txt") - @pytest.mark.asyncio - async def test_returns_bytes_for_valid_image_response(self): - png_bytes = b"\x89PNG\r\n\x1a\nfake png body" - with _patch_async_safe_get( - return_value=_image_response( - content_type="image/png; charset=binary", body=png_bytes - ), - ): - result = await fetch_validated_image_bytes("https://cdn.example/logo.png") - assert result == png_bytes - - @pytest.mark.asyncio - async def test_returns_none_on_non_200_response(self): - with _patch_async_safe_get(return_value=_image_response(status_code=404)): - result = await fetch_validated_image_bytes("https://cdn.example/logo") - assert result is None + result = resolve_validated_local_image_path(traversal) - @pytest.mark.asyncio - async def test_returns_none_on_fetch_exception(self): - with _patch_async_safe_get(side_effect=Exception("connection reset")): - result = await fetch_validated_image_bytes("https://cdn.example/logo") assert result is None - @pytest.mark.asyncio - async def test_returns_none_for_empty_url(self): - result = await fetch_validated_image_bytes("") + def test_rejects_directory(self, tmp_path): + result = resolve_validated_local_image_path(str(tmp_path)) assert result is None - @pytest.mark.asyncio - async def test_rejects_svg_content_type(self): - # ``image/svg+xml`` is intentionally NOT in the allowlist for - # unauthenticated endpoints — SVG is the only common image - # format that can embed JavaScript. - with _patch_async_safe_get( - return_value=_image_response( - content_type="image/svg+xml", - body=b"", - ), - ): - result = await fetch_validated_image_bytes("https://cdn.example/x.svg") + def test_rejects_nonexistent_file(self, tmp_path): + result = resolve_validated_local_image_path(str(tmp_path / "missing.jpg")) assert result is None - @pytest.mark.parametrize( - "content_type", - sorted(ALLOWED_IMAGE_CONTENT_TYPES), - ) - @pytest.mark.asyncio - async def test_accepts_each_allowed_image_content_type(self, content_type): - with _patch_async_safe_get( - return_value=_image_response(content_type=content_type), - ): - result = await fetch_validated_image_bytes("https://cdn.example/logo") - assert result == b"image-bytes" + def test_rejects_empty_path(self): + assert resolve_validated_local_image_path("") is None diff --git a/tests/test_litellm/proxy/test_proxy_server.py b/tests/test_litellm/proxy/test_proxy_server.py index 1a77e39aa808..356ab4a4b05a 100644 --- a/tests/test_litellm/proxy/test_proxy_server.py +++ b/tests/test_litellm/proxy/test_proxy_server.py @@ -472,8 +472,7 @@ def test_get_logo_url_does_not_disclose_local_paths( # ``/get_logo_url`` is unauthenticated. Returning a local filesystem # path verbatim discloses admin-only config to any caller. Only # browser-loadable HTTP(S) URLs should be returned; for local paths - # the dashboard falls back to ``/get_image`` (which has path - # containment). + # the dashboard falls back to ``/get_image``. monkeypatch.setenv("UI_LOGO_PATH", ui_logo_path) response = client_no_auth.get("/get_logo_url") @@ -4034,7 +4033,7 @@ def getenv_side_effect(key, default=""): @pytest.mark.asyncio -async def test_get_image_custom_local_logo_bypasses_cache(monkeypatch): +async def test_get_image_custom_local_logo_bypasses_cache(monkeypatch, tmp_path): """ Test that when UI_LOGO_PATH is set to a local file, get_image serves it directly and does not return a stale cached_logo.jpg. @@ -4043,16 +4042,13 @@ async def test_get_image_custom_local_logo_bypasses_cache(monkeypatch): so a pre-existing cached_logo.jpg (e.g. from the base Docker image) would always be returned, ignoring the user's custom logo. """ - from unittest.mock import patch - from litellm.proxy.proxy_server import get_image - # Use a path inside the allowlisted ``LITELLM_ASSETS_PATH`` — the - # path-containment guard added for GHSA-3pcp-536p-ghjc rejects any - # local UI_LOGO_PATH outside the allowed asset roots. - monkeypatch.setenv("LITELLM_ASSETS_PATH", "/app") - monkeypatch.setenv("UI_LOGO_PATH", "/app/custom_logo.jpg") + custom_logo = tmp_path / "custom_logo.jpg" + custom_logo.write_bytes(b"\xff\xd8\xff custom logo") + monkeypatch.setenv("UI_LOGO_PATH", str(custom_logo)) monkeypatch.delenv("LITELLM_NON_ROOT", raising=False) + monkeypatch.delenv("LITELLM_ASSETS_PATH", raising=False) calls_to_file_response = [] @@ -4061,35 +4057,23 @@ def fake_file_response(path, **kwargs): return MagicMock() with ( - patch("litellm.proxy.proxy_server.os.path.exists", return_value=True), - patch("litellm.proxy.proxy_server.os.access", return_value=True), patch( "litellm.proxy.proxy_server.FileResponse", side_effect=fake_file_response ), - # The path-containment helper calls ``os.path.realpath`` and - # ``os.path.isfile`` — make them play along for the test path. - patch( - "litellm.proxy.common_utils.static_asset_utils.os.path.realpath", - side_effect=lambda p: p, - ), - patch( - "litellm.proxy.common_utils.static_asset_utils.os.path.isfile", - return_value=True, - ), ): await get_image() assert ( len(calls_to_file_response) == 1 ), "FileResponse should be called exactly once" - assert calls_to_file_response[0] == "/app/custom_logo.jpg", ( + assert calls_to_file_response[0] == str(custom_logo.resolve()), ( f"Expected custom logo path, got {calls_to_file_response[0]}. " "A stale cached_logo.jpg may have been returned instead." ) @pytest.mark.asyncio -async def test_get_image_default_logo_still_uses_cache(monkeypatch): +async def test_get_image_default_logo_still_uses_cache(monkeypatch, tmp_path): """ Test that when UI_LOGO_PATH is NOT set (default logo), the cache optimization still works — cached_logo.jpg is returned if it exists. @@ -4098,9 +4082,11 @@ async def test_get_image_default_logo_still_uses_cache(monkeypatch): from litellm.proxy.proxy_server import get_image + cache_path = tmp_path / "cached_logo.jpg" + cache_path.write_bytes(b"\xff\xd8\xff cached logo") monkeypatch.delenv("UI_LOGO_PATH", raising=False) monkeypatch.delenv("LITELLM_NON_ROOT", raising=False) - monkeypatch.delenv("LITELLM_ASSETS_PATH", raising=False) + monkeypatch.setenv("LITELLM_ASSETS_PATH", str(tmp_path)) calls_to_file_response = [] @@ -4109,8 +4095,6 @@ def fake_file_response(path, **kwargs): return MagicMock() with ( - patch("litellm.proxy.proxy_server.os.path.exists", return_value=True), - patch("litellm.proxy.proxy_server.os.access", return_value=True), patch( "litellm.proxy.proxy_server.FileResponse", side_effect=fake_file_response ), @@ -4121,13 +4105,13 @@ def fake_file_response(path, **kwargs): len(calls_to_file_response) == 1 ), "FileResponse should be called exactly once" served_path = calls_to_file_response[0] - assert served_path.endswith( - "cached_logo.jpg" - ), f"Expected cached_logo.jpg for default logo, got {served_path}" + assert served_path == str(cache_path.resolve()) @pytest.mark.asyncio -async def test_get_image_custom_logo_missing_falls_through_to_default(monkeypatch): +async def test_get_image_custom_logo_missing_falls_through_to_default( + monkeypatch, tmp_path +): """ Test that when UI_LOGO_PATH points to a non-existent local file, get_image falls through to the cache/default logo instead of failing. @@ -4136,9 +4120,12 @@ async def test_get_image_custom_logo_missing_falls_through_to_default(monkeypatc from litellm.proxy.proxy_server import get_image - monkeypatch.setenv("UI_LOGO_PATH", "/app/nonexistent_logo.jpg") + cache_path = tmp_path / "cached_logo.jpg" + cache_path.write_bytes(b"\xff\xd8\xff cached logo") + custom_logo_path = tmp_path / "nonexistent_logo.jpg" + monkeypatch.setenv("UI_LOGO_PATH", str(custom_logo_path)) monkeypatch.delenv("LITELLM_NON_ROOT", raising=False) - monkeypatch.delenv("LITELLM_ASSETS_PATH", raising=False) + monkeypatch.setenv("LITELLM_ASSETS_PATH", str(tmp_path)) calls_to_file_response = [] @@ -4146,17 +4133,7 @@ def fake_file_response(path, **kwargs): calls_to_file_response.append(path) return MagicMock() - def exists_side_effect(path): - # The custom logo does NOT exist; cache and default DO exist - if path == "/app/nonexistent_logo.jpg": - return False - return True - with ( - patch( - "litellm.proxy.proxy_server.os.path.exists", side_effect=exists_side_effect - ), - patch("litellm.proxy.proxy_server.os.access", return_value=True), patch( "litellm.proxy.proxy_server.FileResponse", side_effect=fake_file_response ), @@ -4167,16 +4144,16 @@ def exists_side_effect(path): len(calls_to_file_response) == 1 ), "FileResponse should be called exactly once" served_path = calls_to_file_response[0] - assert ( - served_path != "/app/nonexistent_logo.jpg" + assert served_path != str( + custom_logo_path ), "Should not attempt to serve a non-existent custom logo" - assert served_path.endswith( - "cached_logo.jpg" - ), f"Expected fallback to cached_logo.jpg, got {served_path}" + assert served_path == str(cache_path.resolve()) @pytest.mark.asyncio -async def test_get_image_custom_logo_missing_no_cache_serves_default(monkeypatch): +async def test_get_image_custom_logo_missing_no_cache_serves_default( + monkeypatch, tmp_path +): """ Test that when UI_LOGO_PATH points to a non-existent file AND there is no cached_logo.jpg, get_image serves the default logo instead of the @@ -4186,9 +4163,10 @@ async def test_get_image_custom_logo_missing_no_cache_serves_default(monkeypatch from litellm.proxy.proxy_server import get_image - monkeypatch.setenv("UI_LOGO_PATH", "/app/nonexistent_logo.jpg") + custom_logo_path = tmp_path / "nonexistent_logo.jpg" + monkeypatch.setenv("UI_LOGO_PATH", str(custom_logo_path)) monkeypatch.delenv("LITELLM_NON_ROOT", raising=False) - monkeypatch.delenv("LITELLM_ASSETS_PATH", raising=False) + monkeypatch.setenv("LITELLM_ASSETS_PATH", str(tmp_path)) calls_to_file_response = [] @@ -4196,19 +4174,7 @@ def fake_file_response(path, **kwargs): calls_to_file_response.append(path) return MagicMock() - def exists_side_effect(path): - # Neither the custom logo nor the cache exist - if path == "/app/nonexistent_logo.jpg": - return False - if "cached_logo.jpg" in path: - return False - return True - with ( - patch( - "litellm.proxy.proxy_server.os.path.exists", side_effect=exists_side_effect - ), - patch("litellm.proxy.proxy_server.os.access", return_value=True), patch( "litellm.proxy.proxy_server.FileResponse", side_effect=fake_file_response ), @@ -4219,8 +4185,8 @@ def exists_side_effect(path): len(calls_to_file_response) == 1 ), "FileResponse should be called exactly once" served_path = calls_to_file_response[0] - assert ( - served_path != "/app/nonexistent_logo.jpg" + assert served_path != str( + custom_logo_path ), "Should not attempt to serve a non-existent custom logo" assert served_path.endswith( "logo.jpg" From b8a141cefd2b0aba2959a2aae42f7a465575577e Mon Sep 17 00:00:00 2001 From: user <70670632+stuxf@users.noreply.github.com> Date: Thu, 30 Apr 2026 11:34:25 -0700 Subject: [PATCH 11/12] fix(static-assets): stop serving stale logo cache --- litellm/proxy/proxy_server.py | 18 +----------------- tests/test_litellm/proxy/test_proxy_server.py | 19 +++++++++---------- 2 files changed, 10 insertions(+), 27 deletions(-) diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py index b65455e567c5..828a4747bd8d 100644 --- a/litellm/proxy/proxy_server.py +++ b/litellm/proxy/proxy_server.py @@ -12229,7 +12229,7 @@ def get_logo_url(): directly by the browser from a public/internal CDN. Local file paths set via ``UI_LOGO_PATH`` are NOT returned: they are admin- only filesystem details, the dashboard falls back to ``/get_image`` - which serves the file (with path containment) instead. Without + which serves the file only when it is a supported image. Without this filter, the unauthenticated endpoint would disclose internal hostnames or filesystem paths to any caller. """ @@ -12275,9 +12275,6 @@ async def get_image(): if assets_dir != current_dir and not os.path.exists(default_logo): default_logo = default_site_logo - cache_dir = assets_dir if os.access(assets_dir, os.W_OK) else current_dir - cache_path = os.path.join(cache_dir, "cached_logo.jpg") - logo_path = os.getenv("UI_LOGO_PATH", default_logo) verbose_proxy_logger.debug("Reading logo from path: %s", logo_path) @@ -12302,19 +12299,6 @@ async def get_image(): if logo_path.startswith(("http://", "https://")): return RedirectResponse(url=logo_path) - # [OPTIMIZATION] For default logo, check if the cached image exists. - # Validate the cache before serving so stale pre-fix cache files cannot - # keep exposing non-image responses fetched before this hardening. - if os.path.exists(cache_path): - safe_cache = resolve_validated_local_image_path(cache_path) - if safe_cache is not None: - safe_cache_path, media_type = safe_cache - return FileResponse(safe_cache_path, media_type=media_type) - verbose_proxy_logger.warning( - "Ignoring cached logo at %s because it is not a supported image file", - cache_path, - ) - # Default logo (resolved from the bundled asset, not user-controlled). safe_logo = resolve_validated_local_image_path(logo_path) if safe_logo is not None: diff --git a/tests/test_litellm/proxy/test_proxy_server.py b/tests/test_litellm/proxy/test_proxy_server.py index 356ab4a4b05a..d482fd1c51ec 100644 --- a/tests/test_litellm/proxy/test_proxy_server.py +++ b/tests/test_litellm/proxy/test_proxy_server.py @@ -4073,10 +4073,10 @@ def fake_file_response(path, **kwargs): @pytest.mark.asyncio -async def test_get_image_default_logo_still_uses_cache(monkeypatch, tmp_path): +async def test_get_image_default_logo_ignores_stale_cache(monkeypatch, tmp_path): """ - Test that when UI_LOGO_PATH is NOT set (default logo), the cache - optimization still works — cached_logo.jpg is returned if it exists. + Test that when UI_LOGO_PATH is NOT set, stale pre-fix cached_logo.jpg + files are ignored and the default logo is served. """ from unittest.mock import patch @@ -4105,7 +4105,8 @@ def fake_file_response(path, **kwargs): len(calls_to_file_response) == 1 ), "FileResponse should be called exactly once" served_path = calls_to_file_response[0] - assert served_path == str(cache_path.resolve()) + assert served_path != str(cache_path.resolve()) + assert served_path.endswith("logo.jpg") @pytest.mark.asyncio @@ -4114,14 +4115,12 @@ async def test_get_image_custom_logo_missing_falls_through_to_default( ): """ Test that when UI_LOGO_PATH points to a non-existent local file, - get_image falls through to the cache/default logo instead of failing. + get_image falls through to the default logo instead of failing. """ from unittest.mock import patch from litellm.proxy.proxy_server import get_image - cache_path = tmp_path / "cached_logo.jpg" - cache_path.write_bytes(b"\xff\xd8\xff cached logo") custom_logo_path = tmp_path / "nonexistent_logo.jpg" monkeypatch.setenv("UI_LOGO_PATH", str(custom_logo_path)) monkeypatch.delenv("LITELLM_NON_ROOT", raising=False) @@ -4147,7 +4146,7 @@ def fake_file_response(path, **kwargs): assert served_path != str( custom_logo_path ), "Should not attempt to serve a non-existent custom logo" - assert served_path == str(cache_path.resolve()) + assert served_path.endswith("logo.jpg") @pytest.mark.asyncio @@ -4156,8 +4155,8 @@ async def test_get_image_custom_logo_missing_no_cache_serves_default( ): """ Test that when UI_LOGO_PATH points to a non-existent file AND there is no - cached_logo.jpg, get_image serves the default logo instead of the - non-existent custom path. + cached_logo.jpg, get_image serves the default logo instead of the non-existent + custom path. """ from unittest.mock import patch From b67a81da47383e707eee239b4675fa61c0258f49 Mon Sep 17 00:00:00 2001 From: user <70670632+stuxf@users.noreply.github.com> Date: Thu, 30 Apr 2026 11:46:45 -0700 Subject: [PATCH 12/12] test(proxy): align favicon remote asset expectations --- tests/proxy_unit_tests/test_get_favicon.py | 61 +++++++--------------- 1 file changed, 20 insertions(+), 41 deletions(-) diff --git a/tests/proxy_unit_tests/test_get_favicon.py b/tests/proxy_unit_tests/test_get_favicon.py index f17787e740da..ddc8b1230a7b 100644 --- a/tests/proxy_unit_tests/test_get_favicon.py +++ b/tests/proxy_unit_tests/test_get_favicon.py @@ -1,6 +1,5 @@ import os import sys -from unittest import mock sys.path.insert(0, os.path.abspath("../..")) @@ -26,50 +25,30 @@ async def test_get_favicon_default(): @pytest.mark.asyncio -async def test_get_favicon_with_custom_url(): - """Test that get_favicon fetches from a custom URL.""" - os.environ["LITELLM_FAVICON_URL"] = "https://example.com/favicon.ico" +async def test_get_favicon_with_custom_url(monkeypatch): + """Test that get_favicon redirects browser-loaded custom URLs.""" + monkeypatch.setenv("LITELLM_FAVICON_URL", "https://example.com/favicon.ico") - mock_response = mock.Mock() - mock_response.status_code = 200 - mock_response.content = b"\x00\x00\x01\x00" - mock_response.headers = {"content-type": "image/x-icon"} - - try: - with mock.patch( - "litellm.llms.custom_httpx.http_handler.AsyncHTTPHandler.get" - ) as mock_get: - mock_get.return_value = mock_response - - async with httpx.AsyncClient( - transport=httpx.ASGITransport(app=app), - base_url="http://testserver", - ) as ac: - response = await ac.get("/get_favicon") + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), + base_url="http://testserver", + ) as ac: + response = await ac.get("/get_favicon") - assert response.status_code == 200 - assert response.headers["content-type"] == "image/x-icon" - finally: - os.environ.pop("LITELLM_FAVICON_URL", None) + assert response.status_code == 307 + assert response.headers["location"] == "https://example.com/favicon.ico" @pytest.mark.asyncio -async def test_get_favicon_url_error_fallback(): - """Test that get_favicon falls back to default on error.""" - os.environ["LITELLM_FAVICON_URL"] = "https://invalid.com/favicon.ico" +async def test_get_favicon_remote_url_is_not_server_fetched(monkeypatch): + """Test that get_favicon does not validate remote URLs server-side.""" + monkeypatch.setenv("LITELLM_FAVICON_URL", "https://invalid.com/favicon.ico") - try: - with mock.patch( - "litellm.llms.custom_httpx.http_handler.AsyncHTTPHandler.get" - ) as mock_get: - mock_get.side_effect = httpx.ConnectError("unreachable") - - async with httpx.AsyncClient( - transport=httpx.ASGITransport(app=app), - base_url="http://testserver", - ) as ac: - response = await ac.get("/get_favicon") + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), + base_url="http://testserver", + ) as ac: + response = await ac.get("/get_favicon") - assert response.status_code in [200, 404] - finally: - os.environ.pop("LITELLM_FAVICON_URL", None) + assert response.status_code == 307 + assert response.headers["location"] == "https://invalid.com/favicon.ico"