The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(static-assets): browser-load remote branding assets
user215f538d4f8a
diff --git a/litellm/proxy/common_utils/static_asset_utils.py b/litellm/proxy/common_utils/static_asset_utils.pyindex 74fe9939aab..c108af2b475 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, Tuplefrom 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 Nonetry:@@ -64,74 +33,20 @@ def resolve_local_asset_path(candidate: str, allowed_roots: List[str]) -> Optionreturn Noneif 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_typediff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex 776c05dfccb..b65455e567c 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.pyindex bdc7743faac..57e472f86c4 100644--- a/tests/proxy_unit_tests/test_get_image.py+++ b/tests/proxy_unit_tests/test_get_image.py@@ -5,90 +5,48 @@ from unittest import mock# Standard path insertionsys.path.insert(0, os.path.abspath("../.."))-import pytestimport httpx+import pytestfrom 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 errorwith 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.pyindex ad9ac0b8331..93f7ccc92c2 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 osimport sys-from unittest.mock import AsyncMock, MagicMock, patchimport pytestsys.path.insert(0, os.path.abspath("../../../.."))-from litellm.litellm_core_utils.url_utils import SSRFErrorfrom 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+ ("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,- )--[email protected](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"<svg><script>alert(1)</script></svg>",- ),- ):- 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 Nonediff --git a/tests/test_litellm/proxy/test_proxy_server.py b/tests/test_litellm/proxy/test_proxy_server.pyindex 1a77e39aa80..356ab4a4b05 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 @@ async def test_get_image_root_case_uses_current_dir(monkeypatch):@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 itdirectly 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) wouldalways 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 @@ async def test_get_image_custom_local_logo_bypasses_cache(monkeypatch):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 cacheoptimization 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 @@ async def test_get_image_default_logo_still_uses_cache(monkeypatch):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 @@ async def test_get_image_default_logo_still_uses_cache(monkeypatch):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(monkeypatcfrom 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 @@ async def test_get_image_custom_logo_missing_falls_through_to_default(monkeypatccalls_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 @@ async def test_get_image_custom_logo_missing_falls_through_to_default(monkeypatclen(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 nocached_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(monkeypatchfrom 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 @@ async def test_get_image_custom_logo_missing_no_cache_serves_default(monkeypatchcalls_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 @@ async def test_get_image_custom_logo_missing_no_cache_serves_default(monkeypatchlen(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"