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]

fix(email): stop duplicate legacy invitation email and fix its onboarding link (#36455)

mubashir1osmanib0fac57fe404
diff --git a/enterprise/litellm_enterprise/enterprise_callbacks/send_emails/base_email.py b/enterprise/litellm_enterprise/enterprise_callbacks/send_emails/base_email.py
index e7898cac565..4be09670e92 100644
--- a/enterprise/litellm_enterprise/enterprise_callbacks/send_emails/base_email.py
+++ b/enterprise/litellm_enterprise/enterprise_callbacks/send_emails/base_email.py
@@ -99,6 +99,7 @@ class BaseEmailLogger(CustomLogger):
email_html_content = USER_INVITATION_EMAIL_TEMPLATE.format(
email_logo_url=email_params.logo_url,
recipient_email=email_params.recipient_email,
+ invitation_link=email_params.base_url,
base_url=email_params.base_url,
email_support_contact=email_params.support_contact,
email_footer=email_params.signature,
@@ -826,10 +827,15 @@ class BaseEmailLogger(CustomLogger):
"""
# Early validation
if not user_id:
- verbose_proxy_logger.debug("No user_id provided for invitation link")
+ verbose_proxy_logger.warning(
+ "No user_id provided for invitation link. Email will link to base URL instead of onboarding page"
+ )
return base_url
if not await self._is_prisma_client_available():
+ verbose_proxy_logger.warning(
+ "Prisma client not available. Email will link to base URL instead of onboarding page"
+ )
return base_url
# Wait for any concurrent invitation creation to complete
@@ -839,11 +845,15 @@ class BaseEmailLogger(CustomLogger):
invitation = await self._get_or_create_invitation(user_id)
if not invitation:
verbose_proxy_logger.warning(
- f"Failed to get/create invitation for user_id: {user_id}"
+ f"Failed to get/create invitation for user_id: {user_id}. Email will link to base URL instead of onboarding page"
)
return base_url
- return self._construct_invitation_link(invitation.id, base_url)
+ invitation_link = self._construct_invitation_link(invitation.id, base_url)
+ verbose_proxy_logger.info(
+ f"Successfully created invitation link for user_id: {user_id}"
+ )
+ return invitation_link
async def _is_prisma_client_available(self) -> bool:
"""Check if Prisma client is available"""
@@ -921,7 +931,9 @@ class BaseEmailLogger(CustomLogger):
# http://localhost:4000/ui/onboarding?invitation_id=7a096b3a-37c6-440f-9dd1-ba22e8043f6b
"""
- return f"{base_url}/ui/onboarding?invitation_id={invitation_id}"
+ base_url = base_url.rstrip("/")
+ invitation_link = f"{base_url}/ui/onboarding?invitation_id={invitation_id}"
+ return invitation_link
async def send_email(
self,
diff --git a/litellm/integrations/SlackAlerting/slack_alerting.py b/litellm/integrations/SlackAlerting/slack_alerting.py
index 771d7876fea..7edfb93e581 100644
--- a/litellm/integrations/SlackAlerting/slack_alerting.py
+++ b/litellm/integrations/SlackAlerting/slack_alerting.py
@@ -9,6 +9,7 @@ from datetime import timedelta
from typing import TYPE_CHECKING, Any, Final, Literal
from openai import APIError
+from pydantic import TypeAdapter
import litellm
import litellm.litellm_core_utils
@@ -33,10 +34,14 @@ from litellm.llms.custom_httpx.http_handler import (
from litellm.proxy._types import (
AlertType,
CallInfo,
+ InvitationModel,
+ InvitationNew,
Litellm_EntityType,
+ UserAPIKeyAuth,
VirtualKeyEvent,
WebhookEvent,
)
+from litellm.repositories.table_repositories import InvitationLinkRepository
from litellm.repositories.team_repository import TeamRepository
from litellm.repositories.user_repository import UserRepository
from litellm.types.integrations.slack_alerting import *
@@ -1081,6 +1086,44 @@ Model Info:
if email_logo_url is not None or email_support_contact is not None:
raise ValueError(f"Trying to Customize Email Alerting\n {CommonProxyErrors.not_premium_user.value}")
+ async def _construct_user_invitation_link(self, recipient_user_id: str | None, base_url: str) -> str:
+ from litellm.proxy.management_helpers.user_invitation import (
+ create_invitation_for_user,
+ )
+ from litellm.proxy.proxy_server import prisma_client
+
+ if recipient_user_id is None or prisma_client is None:
+ return base_url
+
+ try:
+ existing_invitations: Final = TypeAdapter(list[InvitationModel]).validate_python(
+ await InvitationLinkRepository(prisma_client).table.find_many( # pyright: ignore[reportAny] # untyped prisma boundary (any-ok), result validated by TypeAdapter
+ where={"user_id": recipient_user_id}, # mutable-ok: prisma find_many requires a dict where filter
+ order={"created_at": "desc"}, # mutable-ok: prisma find_many requires a dict order arg
+ ),
+ from_attributes=True,
+ )
+ invitation: Final = (
+ existing_invitations[0]
+ if existing_invitations
+ else TypeAdapter(InvitationModel).validate_python(
+ await create_invitation_for_user(
+ data=InvitationNew(user_id=recipient_user_id),
+ user_api_key_dict=UserAPIKeyAuth(user_id=recipient_user_id),
+ ),
+ from_attributes=True,
+ )
+ )
+ except Exception as e: # noqa: BLE001 # best-effort link build; any DB/creation failure falls back to base_url
+ verbose_proxy_logger.error(
+ "Error creating invitation link for user_id %s: %s",
+ recipient_user_id,
+ str(e),
+ )
+ return base_url
+
+ return f"{base_url.rstrip('/')}/ui/onboarding?invitation_id={invitation.id}"
+
async def send_key_created_or_user_invited_email(self, webhook_event: WebhookEvent) -> bool:
try:
from litellm.proxy.utils import send_email
@@ -1139,11 +1182,14 @@ Model Info:
team_row: Final = await TeamRepository(prisma_client).table.find_unique(where={"team_id": team_id})
if team_row is not None:
team_name = team_row.team_alias or "-"
+ invitation_link: Final = await self._construct_user_invitation_link(
+ recipient_user_id=recipient_user_id, base_url=base_url
+ )
email_html_content = USER_INVITED_EMAIL_TEMPLATE.format(
email_logo_url=email_logo_url,
recipient_email=recipient_email,
team_name=team_name,
- base_url=base_url,
+ base_url=invitation_link,
email_support_contact=email_support_contact,
)
else:
diff --git a/litellm/integrations/email_templates/templates.py b/litellm/integrations/email_templates/templates.py
index f73e0f758ad..935067c97fc 100644
--- a/litellm/integrations/email_templates/templates.py
+++ b/litellm/integrations/email_templates/templates.py
@@ -54,7 +54,7 @@ USER_INVITED_EMAIL_TEMPLATE: Final = """
You were invited to use OpenAI Proxy API for team {team_name} <br /> <br />
- <a href="{base_url}" style="display: inline-block; padding: 10px 20px; background-color: #87ceeb; color: #fff; text-decoration: none; border-radius: 20px;">Get Started here</a> <br /> <br />
+ <a href="{base_url}" style="display: inline-block; padding: 10px 20px; background-color: #87ceeb; color: #fff; text-decoration: none; border-radius: 20px;">Accept Invitation</a> <br /> <br />
If you have any questions, please send an email to {email_support_contact} <br /> <br />
diff --git a/litellm/integrations/email_templates/user_invitation_email.py b/litellm/integrations/email_templates/user_invitation_email.py
index 9ad00999eaa..33904608741 100644
--- a/litellm/integrations/email_templates/user_invitation_email.py
+++ b/litellm/integrations/email_templates/user_invitation_email.py
@@ -131,7 +131,7 @@ USER_INVITATION_EMAIL_TEMPLATE: Final = """
</div>
<div class="btn-container">
- <a href="{base_url}" class="btn">Accept Invitation</a>
+ <a href="{invitation_link}" class="btn">Accept Invitation</a>
</div>
<div class="quickstart">
diff --git a/litellm/proxy/hooks/user_management_event_hooks.py b/litellm/proxy/hooks/user_management_event_hooks.py
index a5568a450f0..929df2a778c 100644
--- a/litellm/proxy/hooks/user_management_event_hooks.py
+++ b/litellm/proxy/hooks/user_management_event_hooks.py
@@ -96,42 +96,66 @@ class UserManagementEventHooks:
key_alias=response.key_alias,
)
+ sent_via_v2: Final = await UserManagementEventHooks._send_v2_user_invitation_emails(
+ event=event, send_invite_email=data.send_invite_email
+ )
+
#########################################################
- ########## V2 USER INVITATION EMAIL ################
+ ########## LEGACY V1 USER INVITATION EMAIL (FALLBACK) ####
#########################################################
+ if data.send_invite_email is True and not sent_via_v2:
+ await UserManagementEventHooks.send_legacy_v1_user_invitation_email(
+ data=data,
+ response=response,
+ user_api_key_dict=user_api_key_dict,
+ event=event,
+ )
+
+ @staticmethod
+ async def _send_v2_user_invitation_emails(event: WebhookEvent, send_invite_email: bool | None) -> bool:
+ """
+ Send the modern (V2) invitation email via any registered enterprise email logger.
+
+ Returns True if at least one logger delivered, so the caller only falls back to
+ the legacy email when V2 did not send (enterprise package absent, no email logger
+ configured, or every send raised).
+ """
+ if send_invite_email is not True:
+ return False
+
try:
from litellm_enterprise.enterprise_callbacks.send_emails.base_email import (
BaseEmailLogger,
)
-
- use_enterprise_email_hooks = True
except ImportError:
verbose_proxy_logger.warning(
"Defaulting to using Legacy Email Hooks." + CommonProxyErrors.missing_enterprise_package.value
)
- use_enterprise_email_hooks = False
+ return False
- if use_enterprise_email_hooks and (data.send_invite_email is True):
- initialized_email_loggers: Final = litellm.logging_callback_manager.get_custom_loggers_for_type(
+ email_loggers: Final = tuple(
+ email_logger
+ for email_logger in litellm.logging_callback_manager.get_custom_loggers_for_type(
callback_type=BaseEmailLogger
)
- if len(initialized_email_loggers) > 0:
- for email_logger in initialized_email_loggers:
- if isinstance(email_logger, BaseEmailLogger):
- await email_logger.send_user_invitation_email(
- event=event,
- )
+ if isinstance(email_logger, BaseEmailLogger)
+ )
+ if len(email_loggers) == 0:
+ return False
- #########################################################
- ########## LEGACY V1 USER INVITATION EMAIL ################
- #########################################################
- if data.send_invite_email is True:
- await UserManagementEventHooks.send_legacy_v1_user_invitation_email(
- data=data,
- response=response,
- user_api_key_dict=user_api_key_dict,
- event=event,
- )
+ send_outcomes: Final = await asyncio.gather(
+ *(email_logger.send_user_invitation_email(event=event) for email_logger in email_loggers),
+ return_exceptions=True,
+ )
+ for outcome in send_outcomes:
+ if isinstance(outcome, BaseException):
+ verbose_proxy_logger.error(
+ "Error sending v2 user invitation email for user_id=%s: %s",
+ event.user_id,
+ str(outcome),
+ )
+
+ return any(not isinstance(outcome, BaseException) for outcome in send_outcomes)
@staticmethod
async def send_legacy_v1_user_invitation_email(
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index baa1579d2c0..f79819c76d3 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -14193,11 +14193,8 @@ async def login(request: Request):
# Build redirect URL
litellm_dashboard_ui = get_custom_url(str(request.base_url))
- if litellm_dashboard_ui.endswith("/"):
- litellm_dashboard_ui += "ui/"
- else:
- litellm_dashboard_ui += "/ui/"
- litellm_dashboard_ui += "?login=success"
+ litellm_dashboard_ui = litellm_dashboard_ui.rstrip("/")
+ litellm_dashboard_ui += "/ui?login=success"
# Honor a same-origin return_to preserved by the sign-in page (e.g. the aggregate DCR connect flow's
# authorize round-trip), mirroring the SSO callback; otherwise land on the dashboard. Gated by
@@ -14267,11 +14264,8 @@ async def login_v2(request: Request):
jwt_token: Final = encode_ui_session_jwt(returned_ui_token_object, cast(str, master_key))
litellm_dashboard_ui = get_custom_url(str(request.base_url))
- if litellm_dashboard_ui.endswith("/"):
- litellm_dashboard_ui += "ui/"
- else:
- litellm_dashboard_ui += "/ui/"
- litellm_dashboard_ui += "?login=success"
+ litellm_dashboard_ui = litellm_dashboard_ui.rstrip("/")
+ litellm_dashboard_ui += "/ui?login=success"
# Token is included in the response body so the UI can set a JS-accessible
# cookie even when a reverse proxy (e.g. nginx-ingress) adds HttpOnly to the
@@ -14340,11 +14334,8 @@ async def login_v3(request: Request):
jwt_token: Final = encode_ui_session_jwt(returned_ui_token_object, cast(str, master_key))
litellm_dashboard_ui = get_custom_url(str(request.base_url))
- if litellm_dashboard_ui.endswith("/"):
- litellm_dashboard_ui += "ui/"
- else:
- litellm_dashboard_ui += "/ui/"
- litellm_dashboard_ui += "?login=success"
+ litellm_dashboard_ui = litellm_dashboard_ui.rstrip("/")
+ litellm_dashboard_ui += "/ui?login=success"
# Store JWT behind a single-use opaque code (60s TTL)
code: Final = secrets.token_urlsafe(32)
@@ -14492,10 +14483,8 @@ async def onboarding(invite_link: str, request: Request):
raise HTTPException(status_code=401, detail={"error": "User does not exist in db."})
litellm_dashboard_ui = get_custom_url(str(request.base_url))
- if litellm_dashboard_ui.endswith("/"):
- litellm_dashboard_ui += "ui/onboarding"
- else:
- litellm_dashboard_ui += "/ui/onboarding"
+ litellm_dashboard_ui = litellm_dashboard_ui.rstrip("/")
+ litellm_dashboard_ui += "/ui/onboarding"
import jwt
user_email: Final = user_obj.user_email
@@ -14751,11 +14740,8 @@ async def claim_onboarding_link(data: InvitationClaim, request: Request):
) from e
litellm_dashboard_ui = get_custom_url(str(request.base_url))
- if litellm_dashboard_ui.endswith("/"):
- litellm_dashboard_ui += "ui/"
- else:
- litellm_dashboard_ui += "/ui/"
- litellm_dashboard_ui += "?login=success"
+ litellm_dashboard_ui = litellm_dashboard_ui.rstrip("/")
+ litellm_dashboard_ui += "/ui?login=success"
return {
"login_url": litellm_dashboard_ui,
"token": jwt_token,
diff --git a/tests/test_litellm/proxy/hooks/test_send_invite_email.py b/tests/test_litellm/proxy/hooks/test_send_invite_email.py
index 3b8f00d577a..c916af5c128 100644
--- a/tests/test_litellm/proxy/hooks/test_send_invite_email.py
+++ b/tests/test_litellm/proxy/hooks/test_send_invite_email.py
@@ -9,7 +9,6 @@ from litellm.proxy._types import (
GenerateKeyResponse,
UserAPIKeyAuth,
)
-import builtins
import sys
from types import SimpleNamespace
@@ -92,6 +91,116 @@ async def test_v1_user_creation_sends_email_when_send_invite_email_true():
mock_slack_alerting.send_key_created_or_user_invited_email.assert_called_once()
+async def test_v2_invitation_email_suppresses_legacy_duplicate():
+ """
+ Regression: when a V2 enterprise email logger is registered and sends
+ successfully, the modern invitation email is sent and the legacy V1 email is
+ NOT also sent, so the invited user does not receive a duplicate.
+ """
+ pytest.importorskip("litellm_enterprise")
+ from litellm_enterprise.enterprise_callbacks.send_emails.base_email import (
+ BaseEmailLogger,
+ )
+
+ class RecordingEmailLogger(BaseEmailLogger):
+ def __init__(self):
+ super().__init__()
+ self.sent_events = []
+
+ async def send_user_invitation_email(self, event):
+ self.sent_events.append(event)
+
+ recording_logger = RecordingEmailLogger()
+ mock_slack_alerting = MagicMock()
+ mock_slack_alerting.send_key_created_or_user_invited_email = AsyncMock()
+ mock_proxy_logging_obj = MagicMock()
+ mock_proxy_logging_obj.slack_alerting_instance = mock_slack_alerting
+
+ with patch(
+ "litellm.logging_callback_manager.get_custom_loggers_for_type",
+ return_value=[recording_logger],
+ ):
+ mock_proxy_server = SimpleNamespace(
+ general_settings={"alerting": ["email"]},
+ proxy_logging_obj=mock_proxy_logging_obj,
+ litellm_proxy_admin_name="admin-user",
+ )
+ with patch.dict(sys.modules, {"litellm.proxy.proxy_server": mock_proxy_server}):
+ data = NewUserRequest(
+ user_email="[email protected]",
+ send_invite_email=True,
+ )
+ response = NewUserResponse(
+ user_id="test-user",
+ user_email="[email protected]",
+ key="sk-test-key",
+ )
+ user_api_key_dict = UserAPIKeyAuth(user_id="admin-user", api_key="admin-key")
+ await UserManagementEventHooks.async_send_user_invitation_email(
+ data=data,
+ response=response,
+ user_api_key_dict=user_api_key_dict,
+ )
+
+ assert len(recording_logger.sent_events) == 1
+ mock_slack_alerting.send_key_created_or_user_invited_email.assert_not_called()
+
+
+async def test_v2_invitation_email_failure_falls_back_to_legacy():
+ """
+ Regression: when a V2 enterprise email logger is registered but its send
+ raises (e.g. misconfigured SMTP), the legacy V1 email still fires as a
+ fallback so the invited user is not left with zero emails.
+ """
+ pytest.importorskip("litellm_enterprise")
+ from litellm_enterprise.enterprise_callbacks.send_emails.base_email import (
+ BaseEmailLogger,
+ )
+
+ class FailingEmailLogger(BaseEmailLogger):
+ def __init__(self):
+ super().__init__()
+
+ async def send_user_invitation_email(self, event):
+ raise RuntimeError("smtp misconfigured")
+
+ failing_logger = FailingEmailLogger()
+ mock_slack_alerting = MagicMock()
+ mock_slack_alerting.send_key_created_or_user_invited_email = AsyncMock()
+ mock_proxy_logging_obj = MagicMock()
+ mock_proxy_logging_obj.slack_alerting_instance = mock_slack_alerting
+
+ with patch(
+ "litellm.logging_callback_manager.get_custom_loggers_for_type",
+ return_value=[failing_logger],
+ ):
+ mock_proxy_server = SimpleNamespace(
+ general_settings={"alerting": ["email"]},
+ proxy_logging_obj=mock_proxy_logging_obj,
+ litellm_proxy_admin_name="admin-user",
+ )
+ with patch.dict(sys.modules, {"litellm.proxy.proxy_server": mock_proxy_server}):
+ data = NewUserRequest(
+ user_email="[email protected]",
+ send_invite_email=True,
+ )
+ response = NewUserResponse(
+ user_id="test-user",
+ user_email="[email protected]",
+ key="sk-test-key",
+ )
+ user_api_key_dict = UserAPIKeyAuth(user_id="admin-user", api_key="admin-key")
+ await UserManagementEventHooks.async_send_user_invitation_email(
+ data=data,
+ response=response,
+ user_api_key_dict=user_api_key_dict,
+ )
+
+ mock_slack_alerting.send_key_created_or_user_invited_email.assert_called_once()
+
+
@pytest.mark.asyncio
async def test_v1_key_generation_sends_email_when_send_invite_email_true():
"""
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 a75d5bd5730..af37dbe85fe 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
@@ -130,7 +130,7 @@ def test_fallback_login_invalid_method_405(client):
def test_login_form_success_redirects_with_token_cookie(client, monkeypatch):
- """Pin: POST /login with valid form returns a 303 redirect to /ui/ and
+ """Pin: POST /login with valid form returns a 303 redirect to /ui and
sets the 'token' cookie."""
_install_login_mocks(monkeypatch)
response = client.post(
@@ -142,7 +142,7 @@ def test_login_form_success_redirects_with_token_cookie(client, monkeypatch):
set_cookie = response.headers.get("set-cookie", "")
shape = {
"status": response.status_code,
- "location_has_ui": "/ui/" in location,
+ "location_has_ui": "/ui" in location,
"location_has_login_success": "login=success" in location,
"has_token_cookie": "token=" in set_cookie,
}
@@ -190,7 +190,7 @@ def test_v2_login_success_returns_token_and_redirect(client, monkeypatch):
body = response.json()
set_cookie = response.headers.get("set-cookie", "")
shape = {
- "redirect_url_has_ui": "/ui/" in body.get("redirect_url", ""),
+ "redirect_url_has_ui": "/ui" in body.get("redirect_url", ""),
"redirect_url_has_login_success": "login=success" in body.get("redirect_url", ""),
"token_in_body": bool(body.get("token")),
"token_cookie_set": "token=" in set_cookie,
@@ -359,7 +359,7 @@ def test_v3_login_exchange_success_returns_token_and_redirect(client, monkeypatc
cached_payload = {
"token": "jwt-token-xyz",
- "redirect_url": "https://litellm.example.invalid/ui/?login=success",
+ "redirect_url": "https://litellm.example.invalid/ui?login=success",
}
fake_cache = MagicMock()
fake_cache.async_get_cache = AsyncMock(return_value=cached_payload)
@@ -382,7 +382,7 @@ def test_v3_login_exchange_success_returns_token_and_redirect(client, monkeypatc
}
assert shape == {
"token": "jwt-token-xyz",
- "redirect_url": "https://litellm.example.invalid/ui/?login=success",
+ "redirect_url": "https://litellm.example.invalid/ui?login=success",
"token_cookie_set": True,
"cache_deleted_once": True,
}
@@ -443,7 +443,7 @@ def test_login_form_survives_stale_control_plane_return_to(client, monkeypatch):
assert response.status_code == 303, "login must not break on a stale return_to cookie"
location = response.headers.get("location", "")
assert "old-cp.example.com" not in location
- assert "/ui/" in location
+ assert "/ui" in location
def test_login_form_ignores_open_redirect_return_to(client, monkeypatch):
@@ -459,4 +459,4 @@ def test_login_form_ignores_open_redirect_return_to(client, monkeypatch):
assert response.status_code == 303
location = response.headers.get("location", "")
assert "evil.example.com" not in location
- assert "/ui/" in location # dashboard fallback
+ assert "/ui" in location # dashboard fallback
diff --git a/tests/test_litellm/proxy/proxy_server/test_routes_onboarding.py b/tests/test_litellm/proxy/proxy_server/test_routes_onboarding.py
index 35ae9a3568e..5cc22cca7a0 100644
--- a/tests/test_litellm/proxy/proxy_server/test_routes_onboarding.py
+++ b/tests/test_litellm/proxy/proxy_server/test_routes_onboarding.py
@@ -243,7 +243,7 @@ def test_claim_onboarding_link_happy(client, monkeypatch, mock_prisma):
assert set(body.keys()) == {"login_url", "token", "user_email", "user"}
assert body["token"] == "session-jwt-token"
assert body["user_email"] == "[email protected]"
- assert body["login_url"].endswith("/ui/?login=success")
+ assert body["login_url"].endswith("/ui?login=success")
def test_claim_onboarding_link_invalid_invite_401(client, monkeypatch, mock_prisma):
diff --git a/tests/test_litellm/proxy/test_proxy_server.py b/tests/test_litellm/proxy/test_proxy_server.py
index 87c8c180d9e..d9ac45c0531 100644
--- a/tests/test_litellm/proxy/test_proxy_server.py
+++ b/tests/test_litellm/proxy/test_proxy_server.py
@@ -112,7 +112,7 @@ def test_login_v2_returns_redirect_url_and_sets_cookie(monkeypatch):
assert response.status_code == 200
assert response.json() == {
- "redirect_url": "http://testserver/ui/?login=success",
+ "redirect_url": "http://testserver/ui?login=success",
"token": "signed-token",
}
assert response.cookies.get("token") == "signed-token"
diff --git a/ui/litellm-dashboard/src/components/email_settings.test.tsx b/ui/litellm-dashboard/src/components/email_settings.test.tsx
index bd09ca0abc4..198577e405e 100644
--- a/ui/litellm-dashboard/src/components/email_settings.test.tsx
+++ b/ui/litellm-dashboard/src/components/email_settings.test.tsx
@@ -29,7 +29,9 @@ const alerts = [
{ name: "slack", variables: { SLACK_WEBHOOK_URL: "https://hooks.example.com" } },
];
-const inputNamed = (name: string) => document.querySelector<HTMLInputElement>(`input[name="${name}"]`)!;
+const inputNamed = (name: string) =>
+ document.querySelector<HTMLInputElement>(`input[name="${name}"][data-slot="input-group-control"]`) ||
+ document.querySelector<HTMLInputElement>(`input[name="${name}"]`)!;
describe("EmailSettings", () => {
beforeEach(() => {
@@ -124,4 +126,24 @@ describe("EmailSettings", () => {
expect(screen.getByText("email event settings")).toBeInTheDocument();
});
+
+ it("toggles credential visibility when eye icon is clicked", async () => {
+ const user = userEvent.setup();
+ renderWithProviders(<EmailSettings accessToken="sk-test" premiumUser alerts={alerts} />);
+
+ const passwordInput = inputNamed("SMTP_PASSWORD");
+ expect(passwordInput).toHaveAttribute("type", "password");
+
+ const showButtons = screen.getAllByLabelText("Show credential");
+ expect(showButtons.length).toBeGreaterThan(0);
+
+ await user.click(showButtons[0]);
+
+ expect(passwordInput).toHaveAttribute("type", "text");
+
+ const hideButton = screen.getByLabelText("Hide credential");
+ await user.click(hideButton);
+
+ expect(passwordInput).toHaveAttribute("type", "password");
+ });
});
diff --git a/ui/litellm-dashboard/src/components/email_settings.tsx b/ui/litellm-dashboard/src/components/email_settings.tsx
index 85fb4ce1ca3..6f1c3b1f846 100644
--- a/ui/litellm-dashboard/src/components/email_settings.tsx
+++ b/ui/litellm-dashboard/src/components/email_settings.tsx
@@ -1,7 +1,8 @@
-import React from "react";
+import React, { useState } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
-import { Input } from "@/components/ui/input";
+import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from "@/components/ui/input-group";
+import { Eye, EyeOff } from "lucide-react";
import NotificationManager from "./molecules/notifications_manager";
import { serviceHealthCheck, setCallbacksCall } from "./networking";
import { EmailEventSettings } from "./email_events";
@@ -29,7 +30,18 @@ const FIELD_HELP: Record<string, React.ReactNode> = {
const PREMIUM_ONLY_FIELDS = ["EMAIL_LOGO_URL", "EMAIL_SUPPORT_CONTACT"];
+const SENSITIVE_FIELD_PATTERN = /(PASSWORD|SECRET|KEY|TOKEN)/i;
+
const EmailSettings: React.FC<EmailSettingsProps> = ({ accessToken, premiumUser, alerts }) => {
+ const [visibleFields, setVisibleFields] = useState<Record<string, boolean>>({});
+
+ const toggleFieldVisibility = (key: string) => {
+ setVisibleFields((prev) => ({
+ ...prev,
+ [key]: !prev[key],
+ }));
+ };
+
const handleSaveEmailSettings = async () => {
if (!accessToken) {
return;
@@ -99,6 +111,8 @@ const EmailSettings: React.FC<EmailSettingsProps> = ({ accessToken, premiumUser,
<div key={index} className="grid grid-cols-1 gap-4 sm:grid-cols-2">
{Object.entries(alert.variables ?? {}).map(([key, value]) => {
const isLocked = !premiumUser && PREMIUM_ONLY_FIELDS.includes(key);
+ const isSensitive = SENSITIVE_FIELD_PATTERN.test(key);
+ const isVisible = visibleFields[key] || false;
return (
<div key={key} className="space-y-1">
{isLocked ? (
@@ -113,13 +127,25 @@ const EmailSettings: React.FC<EmailSettingsProps> = ({ accessToken, premiumUser,
) : (
<p className="text-sm">{key}</p>
)}
- <Input
- name={key}
- defaultValue={value as string}
- type="password"
- disabled={isLocked}
- className="max-w-100"
- />
+ <InputGroup className="max-w-100">
+ <InputGroupInput
+ name={key}
+ defaultValue={value as string}
+ type={isSensitive && !isVisible ? "password" : "text"}
+ disabled={isLocked}
+ />
+ {isSensitive && (
+ <InputGroupAddon align="inline-end">
+ <InputGroupButton
+ size="icon-xs"
+ onClick={() => toggleFieldVisibility(key)}
+ aria-label={isVisible ? "Hide credential" : "Show credential"}
+ >
+ {isVisible ? <EyeOff /> : <Eye />}
+ </InputGroupButton>
+ </InputGroupAddon>
+ )}
+ </InputGroup>
<div className="text-xs text-muted-foreground italic">{FIELD_HELP[key]}</div>
</div>
);