Skip to content

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

feat(proxy): configurable response headers and login-page hint (#30792)

yucheng-berri5637b3212eeb
diff --git a/litellm/proxy/common_utils/html_forms/ui_login.py b/litellm/proxy/common_utils/html_forms/ui_login.py
index 42cfb592a78..6146672ac21 100644
--- a/litellm/proxy/common_utils/html_forms/ui_login.py
+++ b/litellm/proxy/common_utils/html_forms/ui_login.py
@@ -10,7 +10,10 @@ url_to_redirect_to += "/login"
new_ui_login_url = get_custom_url("", "ui/login")
-def build_ui_login_form(show_deprecation_banner: bool = False) -> str:
+def build_ui_login_form(
+ show_deprecation_banner: bool = False,
+ hide_default_credentials_hint: bool = False,
+) -> str:
banner_html = (
f"""
<div class="deprecation-banner">
@@ -23,6 +26,25 @@ def build_ui_login_form(show_deprecation_banner: bool = False) -> str:
else ""
)
+ info_box_html = (
+ ""
+ if hide_default_credentials_hint
+ else """
+ <div class="info-box">
+ <div class="info-header">
+ <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
+ <circle cx="12" cy="12" r="10"></circle>
+ <line x1="12" y1="16" x2="12" y2="12"></line>
+ <line x1="12" y1="8" x2="12.01" y2="8"></line>
+ </svg>
+ Default Credentials
+ </div>
+ <p>By default, Username is <code>admin</code> and Password is your set LiteLLM Proxy <code>MASTER_KEY</code>.</p>
+ <p>Need to set UI credentials or SSO? <a href="https://docs.litellm.ai/docs/proxy/ui" target="_blank">Check the documentation</a>.</p>
+ </div>
+ """
+ )
+
return f"""
<!DOCTYPE html>
<html lang="en">
@@ -232,18 +254,7 @@ def build_ui_login_form(show_deprecation_banner: bool = False) -> str:
</div>
<h2>Login</h2>
<p class="subtitle">Access your LiteLLM Admin UI.</p>
- <div class="info-box">
- <div class="info-header">
- <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
- <circle cx="12" cy="12" r="10"></circle>
- <line x1="12" y1="16" x2="12" y2="12"></line>
- <line x1="12" y1="8" x2="12.01" y2="8"></line>
- </svg>
- Default Credentials
- </div>
- <p>By default, Username is <code>admin</code> and Password is your set LiteLLM Proxy <code>MASTER_KEY</code>.</p>
- <p>Need to set UI credentials or SSO? <a href="https://docs.litellm.ai/docs/proxy/ui" target="_blank">Check the documentation</a>.</p>
- </div>
+ {info_box_html}
<label for="username">Username<span class="required">*</span></label>
<input type="text" id="username" name="username" required placeholder="Enter your username" autocomplete="username">
@@ -264,6 +275,3 @@ def build_ui_login_form(show_deprecation_banner: bool = False) -> str:
</body>
</html>
"""
-
-
-html_form = build_ui_login_form(show_deprecation_banner=True)
diff --git a/litellm/proxy/management_endpoints/ui_sso.py b/litellm/proxy/management_endpoints/ui_sso.py
index 427c87e0f44..199de54ff09 100644
--- a/litellm/proxy/management_endpoints/ui_sso.py
+++ b/litellm/proxy/management_endpoints/ui_sso.py
@@ -90,7 +90,7 @@ from litellm.proxy.common_utils.admin_ui_utils import (
from litellm.proxy.common_utils.html_forms.jwt_display_template import (
jwt_display_template,
)
-from litellm.proxy.common_utils.html_forms.ui_login import html_form
+from litellm.proxy.common_utils.html_forms.ui_login import build_ui_login_form
from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache
from litellm.proxy.management_endpoints.internal_user_endpoints import new_user
from litellm.proxy.management_endpoints.sso import CustomMicrosoftSSO
@@ -902,6 +902,7 @@ async def google_login(
Example:
"""
from litellm.proxy.proxy_server import (
+ general_settings,
premium_user,
prisma_client,
user_api_key_cache,
@@ -948,7 +949,6 @@ async def google_login(
missing_env_vars = show_missing_vars_in_env()
if missing_env_vars is not None:
return missing_env_vars
- ui_username = os.getenv("UI_USERNAME")
# get url from request - always use regular callback, but set state for CLI
redirect_url = SSOAuthenticationHandler.get_redirect_url_for_sso(
@@ -1009,16 +1009,20 @@ async def google_login(
samesite="lax",
)
return sso_redirect
- elif ui_username is not None:
- # No Google, Microsoft SSO
- # Use UI Credentials set in .env
- from fastapi.responses import HTMLResponse
- return HTMLResponse(content=html_form, status_code=200)
- else:
- from fastapi.responses import HTMLResponse
+ from fastapi.responses import HTMLResponse
- return HTMLResponse(content=html_form, status_code=200)
+ hide_default_credentials_hint = (
+ os.getenv("LITELLM_HIDE_DEFAULT_CREDENTIALS_HINT", "false").lower() == "true"
+ or general_settings.get("hide_default_credentials_hint", False) is True
+ )
+ return HTMLResponse(
+ content=build_ui_login_form(
+ show_deprecation_banner=True,
+ hide_default_credentials_hint=hide_default_credentials_hint,
+ ),
+ status_code=200,
+ )
def generic_response_convertor(
diff --git a/litellm/proxy/middleware/security_headers_middleware.py b/litellm/proxy/middleware/security_headers_middleware.py
new file mode 100644
index 00000000000..a090c8f027f
--- /dev/null
+++ b/litellm/proxy/middleware/security_headers_middleware.py
@@ -0,0 +1,53 @@
+"""
+Adds anti-framing / content-type security headers to every HTTP response.
+
+X-Frame-Options and Content-Security-Policy: frame-ancestors 'none' stop the
+admin UI and login pages from being embedded cross-origin (clickjacking).
+X-Content-Type-Options: nosniff stops MIME sniffing.
+
+Strict-Transport-Security is opt-in via LITELLM_ENABLE_HSTS because it only
+makes sense over HTTPS and would lock browsers out of plain-http deployments.
+
+Headers are set with setdefault so a route that intentionally sets its own
+value is never overridden.
+"""
+
+import os
+
+from starlette.datastructures import MutableHeaders
+from starlette.types import ASGIApp, Message, Receive, Scope, Send
+
+STATIC_SECURITY_HEADERS = (
+ ("X-Frame-Options", "DENY"),
+ ("Content-Security-Policy", "frame-ancestors 'none'"),
+ ("X-Content-Type-Options", "nosniff"),
+)
+HSTS_HEADER = ("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
+
+
+def _hsts_enabled() -> bool:
+ return os.getenv("LITELLM_ENABLE_HSTS", "false").strip().lower() == "true"
+
+
+class SecurityHeadersMiddleware:
+ def __init__(self, app: ASGIApp) -> None:
+ self.app = app
+
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
+ if scope["type"] != "http":
+ await self.app(scope, receive, send)
+ return
+
+ async def send_with_security_headers(message: Message) -> None:
+ if message["type"] == "http.response.start":
+ headers = MutableHeaders(scope=message)
+ applied = (
+ (*STATIC_SECURITY_HEADERS, HSTS_HEADER)
+ if _hsts_enabled()
+ else STATIC_SECURITY_HEADERS
+ )
+ for name, value in applied:
+ headers.setdefault(name, value)
+ await send(message)
+
+ await self.app(scope, receive, send_with_security_headers)
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index 62f7829ec2c..bb1357fff95 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -426,6 +426,9 @@ from litellm.proxy.middleware.prometheus_auth_middleware import PrometheusAuthMi
from litellm.proxy.middleware.request_size_limit_middleware import (
RequestSizeLimitMiddleware,
)
+from litellm.proxy.middleware.security_headers_middleware import (
+ SecurityHeadersMiddleware,
+)
from litellm.proxy.ocr_endpoints.endpoints import router as ocr_router
from litellm.proxy.openai_files_endpoints.files_endpoints import (
router as openai_files_router,
@@ -1757,6 +1760,7 @@ app.add_middleware(
app.add_middleware(PrometheusAuthMiddleware)
app.add_middleware(InFlightRequestsMiddleware)
+app.add_middleware(SecurityHeadersMiddleware)
def mount_swagger_ui():
@@ -13707,26 +13711,24 @@ async def fallback_login(request: Request):
# get url from request
redirect_url = get_custom_url(str(request.base_url))
- ui_username = os.getenv("UI_USERNAME")
if redirect_url.endswith("/"):
redirect_url += "sso/callback"
else:
redirect_url += "/sso/callback"
- if ui_username is not None:
- # No Google, Microsoft SSO
- # Use UI Credentials set in .env
- from fastapi.responses import HTMLResponse
-
- return HTMLResponse(
- content=build_ui_login_form(show_deprecation_banner=False), status_code=200
- )
- else:
- from fastapi.responses import HTMLResponse
+ from fastapi.responses import HTMLResponse
- return HTMLResponse(
- content=build_ui_login_form(show_deprecation_banner=False), status_code=200
- )
+ hide_default_credentials_hint = (
+ os.getenv("LITELLM_HIDE_DEFAULT_CREDENTIALS_HINT", "false").lower() == "true"
+ or general_settings.get("hide_default_credentials_hint", False) is True
+ )
+ return HTMLResponse(
+ content=build_ui_login_form(
+ show_deprecation_banner=False,
+ hide_default_credentials_hint=hide_default_credentials_hint,
+ ),
+ status_code=200,
+ )
@router.post(
diff --git a/tests/test_litellm/proxy/common_utils/html_forms/test_ui_login.py b/tests/test_litellm/proxy/common_utils/html_forms/test_ui_login.py
new file mode 100644
index 00000000000..436564d24a0
--- /dev/null
+++ b/tests/test_litellm/proxy/common_utils/html_forms/test_ui_login.py
@@ -0,0 +1,42 @@
+import os
+import sys
+
+sys.path.insert(0, os.path.abspath("../../../"))
+
+from litellm.proxy.common_utils.html_forms.ui_login import build_ui_login_form
+
+DISCLOSURE_MARKERS = ("Default Credentials", "MASTER_KEY")
+FORM_MARKERS = ('name="username"', 'name="password"')
+
+
+def test_build_ui_login_form_shows_disclosure_by_default():
+ html = build_ui_login_form()
+
+ for marker in DISCLOSURE_MARKERS:
+ assert marker in html
+ for marker in FORM_MARKERS:
+ assert marker in html
+
+
+def test_build_ui_login_form_hides_disclosure_when_flag_set():
+ html = build_ui_login_form(hide_default_credentials_hint=True)
+
+ for marker in DISCLOSURE_MARKERS:
+ assert marker not in html
+ # the login form itself must remain functional, only the hint is removed
+ for marker in FORM_MARKERS:
+ assert marker in html
+
+
+def test_build_ui_login_form_hint_independent_of_deprecation_banner():
+ with_banner = build_ui_login_form(
+ show_deprecation_banner=True, hide_default_credentials_hint=True
+ )
+ without_banner = build_ui_login_form(
+ show_deprecation_banner=False, hide_default_credentials_hint=True
+ )
+
+ assert "Deprecated:" in with_banner
+ assert "Deprecated:" not in without_banner
+ for html in (with_banner, without_banner):
+ assert "Default Credentials" not in html
diff --git a/tests/test_litellm/proxy/management_endpoints/test_ui_sso.py b/tests/test_litellm/proxy/management_endpoints/test_ui_sso.py
index acca357e641..44abc7acf21 100644
--- a/tests/test_litellm/proxy/management_endpoints/test_ui_sso.py
+++ b/tests/test_litellm/proxy/management_endpoints/test_ui_sso.py
@@ -6928,3 +6928,78 @@ async def test_debug_sso_callback_handles_missing_raw_response():
assert '"raw_claims": {}' in body
assert '"access_token_claims": {}' in body
assert "[email protected]" in body
+
+
+async def _render_legacy_login_page(env_overrides, general_settings):
+ from litellm.proxy.management_endpoints.ui_sso import google_login
+
+ mock_request = MagicMock(spec=Request)
+ mock_request.base_url = "http://proxy.example.com/"
+
+ with (
+ # snapshot os.environ so the mutations below are reverted on exit
+ patch.dict(os.environ, {}, clear=False),
+ patch("litellm.proxy.proxy_server.master_key", "sk-1234"),
+ patch("litellm.proxy.proxy_server.prisma_client", MagicMock()),
+ patch("litellm.proxy.proxy_server.premium_user", False),
+ patch("litellm.proxy.proxy_server.general_settings", general_settings),
+ patch("litellm.proxy.proxy_server.user_api_key_cache", MagicMock()),
+ patch("litellm.proxy.proxy_server.user_custom_ui_sso_sign_in_handler", None),
+ ):
+ # No SSO provider configured, so /sso/key/generate renders the legacy
+ # username/password form rather than redirecting to an IdP.
+ for var in (
+ "MICROSOFT_CLIENT_ID",
+ "GOOGLE_CLIENT_ID",
+ "GENERIC_CLIENT_ID",
+ "LITELLM_HIDE_DEFAULT_CREDENTIALS_HINT",
+ ):
+ os.environ.pop(var, None)
+ os.environ.update(env_overrides)
+ return await google_login(request=mock_request)
+
+
+async def test_legacy_login_page_shows_credentials_hint_by_default():
+ """Control: without the flag, the legacy page still discloses the hint."""
+ response = await _render_legacy_login_page(env_overrides={}, general_settings={})
+
+ body = response.body.decode()
+ assert response.status_code == 200
+ assert "Default Credentials" in body
+ assert "MASTER_KEY" in body
+
+
+async def test_legacy_login_page_hides_credentials_hint_via_env_flag():
+ """
+ Regression: an anonymous GET /sso/key/generate must not disclose the
+ 'admin / MASTER_KEY' default-credentials hint when
+ LITELLM_HIDE_DEFAULT_CREDENTIALS_HINT is set. The legacy server-rendered
+ page previously ignored this flag while the new UI honored it.
+ """
+ response = await _render_legacy_login_page(
+ env_overrides={"LITELLM_HIDE_DEFAULT_CREDENTIALS_HINT": "true"},
+ general_settings={},
+ )
+
+ body = response.body.decode()
+ assert response.status_code == 200
+ assert "Default Credentials" not in body
+ assert "MASTER_KEY" not in body
+ # the login form itself must still render
+ assert 'name="username"' in body
+
+
+async def test_legacy_login_page_hides_credentials_hint_via_general_settings():
+ """The flag is also honored from general_settings, matching the discovery endpoint."""
+ response = await _render_legacy_login_page(
+ env_overrides={},
+ general_settings={"hide_default_credentials_hint": True},
+ )
+
+ body = response.body.decode()
+ assert response.status_code == 200
+ assert "Default Credentials" not in body
+ assert "MASTER_KEY" not in body
diff --git a/tests/test_litellm/proxy/middleware/test_security_headers_middleware.py b/tests/test_litellm/proxy/middleware/test_security_headers_middleware.py
new file mode 100644
index 00000000000..48d1c937734
--- /dev/null
+++ b/tests/test_litellm/proxy/middleware/test_security_headers_middleware.py
@@ -0,0 +1,71 @@
+"""
+Tests for SecurityHeadersMiddleware.
+
+Verifies anti-framing / content-type headers are present on every response and
+that HSTS is opt-in via LITELLM_ENABLE_HSTS.
+"""
+
+from starlette.applications import Starlette
+from starlette.middleware.base import BaseHTTPMiddleware
+from starlette.responses import JSONResponse, Response
+from starlette.routing import Route
+from starlette.testclient import TestClient
+
+from litellm.proxy.middleware.security_headers_middleware import (
+ SecurityHeadersMiddleware,
+)
+
+
+def _make_client(handler):
+ app = Starlette(routes=[Route("/", handler)])
+ app.add_middleware(SecurityHeadersMiddleware)
+ return TestClient(app)
+
+
+async def _ok(request):
+ return JSONResponse({"ok": True})
+
+
+def test_is_pure_asgi_not_base_http_middleware():
+ """BaseHTTPMiddleware degrades streaming; this must be pure ASGI."""
+ assert not issubclass(SecurityHeadersMiddleware, BaseHTTPMiddleware)
+ assert "__call__" in SecurityHeadersMiddleware.__dict__
+
+
+def test_static_security_headers_present():
+ resp = _make_client(_ok).get("/")
+ assert resp.headers["x-frame-options"] == "DENY"
+ assert resp.headers["content-security-policy"] == "frame-ancestors 'none'"
+ assert resp.headers["x-content-type-options"] == "nosniff"
+
+
+def test_hsts_absent_by_default(monkeypatch):
+ monkeypatch.delenv("LITELLM_ENABLE_HSTS", raising=False)
+ resp = _make_client(_ok).get("/")
+ assert "strict-transport-security" not in resp.headers
+
+
+def test_hsts_present_when_enabled(monkeypatch):
+ monkeypatch.setenv("LITELLM_ENABLE_HSTS", "true")
+ resp = _make_client(_ok).get("/")
+ assert resp.headers["strict-transport-security"] == (
+ "max-age=31536000; includeSubDomains"
+ )
+
+
+def test_hsts_not_enabled_by_arbitrary_value(monkeypatch):
+ monkeypatch.setenv("LITELLM_ENABLE_HSTS", "1")
+ resp = _make_client(_ok).get("/")
+ assert "strict-transport-security" not in resp.headers
+
+
+def test_does_not_override_existing_header(monkeypatch):
+ """A route that sets its own X-Frame-Options must win."""
+
+ async def custom(request):
+ return Response("hi", headers={"X-Frame-Options": "SAMEORIGIN"})
+
+ resp = _make_client(custom).get("/")
+ assert resp.headers["x-frame-options"] == "SAMEORIGIN"
+ # other headers still applied
+ assert resp.headers["x-content-type-options"] == "nosniff"
diff --git a/tests/test_litellm/proxy/proxy_server/test_routes_login_sso.py b/tests/test_litellm/proxy/proxy_server/test_routes_login_sso.py
index 6af1d6653e1..f0250bbe1a6 100644
--- a/tests/test_litellm/proxy/proxy_server/test_routes_login_sso.py
+++ b/tests/test_litellm/proxy/proxy_server/test_routes_login_sso.py
@@ -16,7 +16,6 @@ import pytest
from .conftest import normalize
-
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
@@ -49,9 +48,7 @@ def _install_login_mocks(monkeypatch, raise_on_auth: bool = False) -> None:
"key": "sk-fake-ui-key",
}
- monkeypatch.setattr(
- "litellm.proxy.auth.login_utils.authenticate_user", _fake_auth
- )
+ monkeypatch.setattr("litellm.proxy.auth.login_utils.authenticate_user", _fake_auth)
monkeypatch.setattr(
"litellm.proxy.auth.login_utils.create_ui_token_object", _fake_token_object
)
@@ -103,6 +100,28 @@ def test_fallback_login_returns_html_form_with_ui_username_set(client, monkeypat
}
+def test_fallback_login_shows_credentials_hint_by_default(client, monkeypatch):
+ """Control: without the flag, /fallback/login still renders the hint."""
+ monkeypatch.delenv("UI_USERNAME", raising=False)
+ monkeypatch.delenv("LITELLM_HIDE_DEFAULT_CREDENTIALS_HINT", raising=False)
+ response = client.get("/fallback/login")
+ assert response.status_code == 200
+ assert "Default Credentials" in response.text
+ assert "MASTER_KEY" in response.text
+
+
+def test_fallback_login_hides_credentials_hint_via_env_flag(client, monkeypatch):
+ """Pin: LITELLM_HIDE_DEFAULT_CREDENTIALS_HINT removes the hint on /fallback/login."""
+ monkeypatch.delenv("UI_USERNAME", raising=False)
+ monkeypatch.setenv("LITELLM_HIDE_DEFAULT_CREDENTIALS_HINT", "true")
+ response = client.get("/fallback/login")
+ assert response.status_code == 200
+ assert "Default Credentials" not in response.text
+ assert "MASTER_KEY" not in response.text
+ # the login form itself must still render
+ assert "username" in response.text.lower()
+
+
def test_fallback_login_invalid_method_405(client):
"""POST against the GET-only /fallback/login is rejected (error path)."""
response = client.post("/fallback/login")
@@ -261,9 +280,10 @@ def test_v3_login_success_returns_code(client, monkeypatch):
assert response.status_code == 200
body = response.json()
# Strong assertion via normalize with extended volatile set ("code" is volatile)
- assert normalize(
- body, volatile=frozenset({"code", "expires_in"})
- ) == {"code": "<VOLATILE>", "expires_in": "<VOLATILE>"}
+ assert normalize(body, volatile=frozenset({"code", "expires_in"})) == {
+ "code": "<VOLATILE>",
+ "expires_in": "<VOLATILE>",
+ }
shape = {
"has_code": isinstance(body.get("code"), str) and len(body["code"]) > 0,
"expires_in_60": body.get("expires_in") == 60,