Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
6eb78e4
fix(ui): resolve login redirect loop when reverse proxy adds HttpOnly…
jaxhend Mar 13, 2026
a8864ea
fix: address Greptile review feedback
jaxhend Mar 13, 2026
2c5caac
fix: address second round of Greptile review feedback
jaxhend Mar 13, 2026
04f835e
Update ui/litellm-dashboard/src/utils/cookieUtils.ts
jaxhend Mar 13, 2026
22409da
Update ui/litellm-dashboard/src/utils/cookieUtils.ts
jaxhend Mar 13, 2026
461cf00
fix(ui): use sessionStorage instead of cookie for login token storage
jaxhend Mar 13, 2026
523d1c3
fix(ui): use shared getCookie in page.tsx and user_dashboard.tsx
jaxhend Mar 13, 2026
acdc614
fix(ui): scope deleteCookie sessionStorage cleanup to token key only
jaxhend Mar 13, 2026
a607754
Update ui/litellm-dashboard/src/utils/cookieUtils.ts
jaxhend Mar 13, 2026
20ad73f
Apply suggestion from @greptile-apps[bot]
jaxhend Mar 13, 2026
06260df
style: remove stray double blank line in user_dashboard.tsx
jaxhend Mar 13, 2026
35bd69e
fix(ui): guard storeLoginToken against empty/whitespace-only tokens
jaxhend Mar 13, 2026
01f8844
fix(ui): preserve sessionStorage token across beforeunload clear
jaxhend Mar 13, 2026
a093760
fix(ui): set JS-accessible cookie at /ui path as HttpOnly workaround
jaxhend Mar 19, 2026
bd878e7
fix(ui): use dynamic cookie path based on server_root_path
jaxhend Mar 19, 2026
40eaab5
refactor(ui): remove circular dependency in cookieUtils.ts
jaxhend Mar 19, 2026
11974ca
fix(ui): harden getUiCookiePath regex and add missing tests
jaxhend Mar 19, 2026
eb1a83e
Merge remote-tracking branch 'origin/main' into litellm_login_httponl…
jaxhend Mar 23, 2026
c16fdce
style: fix Black formatting in audit_logs.py
jaxhend Mar 23, 2026
61f5b68
Merge branch 'main' of https://github.com/BerriAI/litellm into litell…
jaxhend Mar 27, 2026
ce8bf55
Merge branch 'main' of https://github.com/BerriAI/litellm into litell…
jaxhend Mar 30, 2026
2905d47
fix CI: formatting, test params, remove token from login JSON
jaxhend Mar 30, 2026
b2c3334
fix: reformat with Black 23.x to match CI
jaxhend Mar 30, 2026
086c416
fix: keep token in login JSON body for UI storeLoginToken flow
jaxhend Mar 30, 2026
866405f
fix: use storeLoginToken in exchangeLoginCode, add credentials include
jaxhend Mar 30, 2026
0684a1e
revert: remove unrelated changes from HttpOnly cookie fix branch
jaxhend Mar 31, 2026
eff9e70
Revert "revert: remove unrelated changes from HttpOnly cookie fix bra…
jaxhend Mar 31, 2026
940789f
Revert "fix: use storeLoginToken in exchangeLoginCode, add credential…
jaxhend Mar 31, 2026
dcbe924
Revert "fix: keep token in login JSON body for UI storeLoginToken flow"
jaxhend Mar 31, 2026
ecd8cc5
Revert "fix: reformat with Black 23.x to match CI"
jaxhend Mar 31, 2026
7f14d41
Revert "fix CI: formatting, test params, remove token from login JSON"
jaxhend Mar 31, 2026
3298858
Merge branch 'BerriAI:main' into litellm_login_httponly_cookie_fix
jaxhend Mar 31, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion litellm/proxy/proxy_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -11029,8 +11029,11 @@ async def login_v2(request: Request): # noqa: PLR0915
litellm_dashboard_ui += "/ui/"
litellm_dashboard_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
# server-set cookie, which would otherwise cause an infinite login redirect.
json_response = JSONResponse(
content={"redirect_url": litellm_dashboard_ui},
content={"redirect_url": litellm_dashboard_ui, "token": jwt_token},
status_code=status.HTTP_200_OK,
)
json_response.set_cookie(key="token", value=jwt_token)
Comment thread
jaxhend marked this conversation as resolved.
Resolved
Expand Down
8 changes: 4 additions & 4 deletions tests/test_litellm/proxy/test_proxy_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,10 +104,10 @@ 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"}
)
assert response.json() == {
"redirect_url": "http://testserver/ui/?login=success",
"token": "signed-token",
}
assert response.cookies.get("token") == "signed-token"

mock_authenticate_user.assert_awaited_once_with(
Expand Down
20 changes: 8 additions & 12 deletions ui/litellm-dashboard/src/app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import ToolPoliciesView from "@/components/ToolPoliciesView";
import SpendLogsTable from "@/components/view_logs";
import ViewUserDashboard from "@/components/view_users";
import { ThemeProvider } from "@/contexts/ThemeContext";
import { getCookie } from "@/utils/cookieUtils";
import { isJwtExpired } from "@/utils/jwtUtils";
import { buildLoginUrlWithReturn, consumeReturnUrl, normalizeUrlForCompare, storeReturnUrl } from "@/utils/returnUrlUtils";
import { formatUserRole, isAdminRole } from "@/utils/roles";
Expand All @@ -52,21 +53,16 @@ import { useSearchParams } from "next/navigation";
import { Suspense, useEffect, useMemo, useRef, useState } from "react";
import { ConfigProvider, theme } from "antd";

function getCookie(name: string) {
// Safer cookie read + decoding; handles '=' inside values
const match = document.cookie.split("; ").find((row) => row.startsWith(name + "="));
if (!match) return null;
const value = match.slice(name.length + 1);
try {
return decodeURIComponent(value);
} catch {
return value;
}
}

function deleteCookie(name: string, path = "/") {
// Best-effort client-side clear (works for non-HttpOnly cookies without Domain)
document.cookie = `${name}=; Max-Age=0; Path=${path}`;
if (name === "token") {
try {
sessionStorage.removeItem(name);
} catch {
// sessionStorage may be unavailable
}
}
}
Comment thread
jaxhend marked this conversation as resolved.
Resolved

interface ProxySettings {
Expand Down
33 changes: 33 additions & 0 deletions ui/litellm-dashboard/src/components/networking.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import * as Networking from "./networking";
vi.mock("@/utils/cookieUtils", () => ({
clearTokenCookies: vi.fn(),
getCookie: vi.fn(),
storeLoginToken: vi.fn(),
}));
Comment thread
jaxhend marked this conversation as resolved.
Resolved

vi.mock("./molecules/notifications_manager", () => ({
Expand Down Expand Up @@ -79,6 +80,38 @@ describe("networking - expired session handling", () => {
});
});

describe("loginCall - storeLoginToken integration", () => {
const originalFetch = global.fetch;

beforeEach(() => {
vi.clearAllMocks();
});

afterEach(() => {
global.fetch = originalFetch;
});

it("calls storeLoginToken when response includes token", async () => {
global.fetch = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ redirect_url: "/ui/?login=success", token: "my-jwt" }),
}) as any;
const { storeLoginToken } = await import("@/utils/cookieUtils");
await Networking.loginCall("admin", "pass");
expect(storeLoginToken).toHaveBeenCalledWith("my-jwt");
});

it("does not call storeLoginToken when response has no token", async () => {
global.fetch = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ redirect_url: "/ui/?login=success" }),
}) as any;
const { storeLoginToken } = await import("@/utils/cookieUtils");
await Networking.loginCall("admin", "pass");
expect(storeLoginToken).not.toHaveBeenCalled();
});
});

describe("daily activity helpers", () => {
const startTime = new Date("2025-02-12T00:00:00.000Z");
const endTime = new Date("2025-02-19T00:00:00.000Z");
Expand Down
6 changes: 5 additions & 1 deletion ui/litellm-dashboard/src/components/networking.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ export const getInProductNudgesCall = async (accessToken: string) => {
* Helper file for calls being made to proxy
*/
import { message } from "antd";
import { clearTokenCookies } from "@/utils/cookieUtils";
import { clearTokenCookies, storeLoginToken } from "@/utils/cookieUtils";
import { TagNewRequest, TagUpdateRequest, TagListResponse, TagInfoResponse } from "./tag_management/types";
import { Team } from "./key_team_helpers/key_list";
import { UserInfo } from "./view_users/types";
Expand Down Expand Up @@ -8976,6 +8976,7 @@ export interface LoginRequest {

interface LoginResponse {
redirect_url: string;
token?: string;
}

export const loginCall = async (username: string, password: string): Promise<LoginResponse> => {
Expand Down Expand Up @@ -9003,6 +9004,9 @@ export const loginCall = async (username: string, password: string): Promise<Log
}

const data = await response.json();
if (data.token) {
storeLoginToken(data.token);
}
return data;
};

Expand Down
8 changes: 2 additions & 6 deletions ui/litellm-dashboard/src/components/user_dashboard.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
"use client";
import { clearTokenCookies } from "@/utils/cookieUtils";
import { clearTokenCookies, getCookie } from "@/utils/cookieUtils";
import { Col, Grid } from "@tremor/react";
import { Typography } from "antd";
import { jwtDecode } from "jwt-decode";
Expand Down Expand Up @@ -35,11 +35,7 @@ export type UserInfo = {
spend: number;
};

function getCookie(name: string) {
console.log("COOKIES", document.cookie);
const cookieValue = document.cookie.split("; ").find((row) => row.startsWith(name + "="));
return cookieValue ? cookieValue.split("=")[1] : null;
}

Comment thread
jaxhend marked this conversation as resolved.
Resolved

interface UserDashboardProps {
userID: string | null;
Expand Down
54 changes: 53 additions & 1 deletion ui/litellm-dashboard/src/utils/cookieUtils.test.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { describe, it, expect, beforeEach, vi } from "vitest";
import { clearTokenCookies, getCookie } from "./cookieUtils";
import { clearTokenCookies, getCookie, storeLoginToken } from "./cookieUtils";

describe("cookieUtils", () => {
beforeEach(() => {
document.cookie.split(";").forEach((c) => {
document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/");
});
sessionStorage.clear();

vi.spyOn(console, "log").mockImplementation(() => {});
});
Expand Down Expand Up @@ -116,6 +117,36 @@ describe("cookieUtils", () => {

vi.restoreAllMocks();
});

it("should clear sessionStorage token", () => {
sessionStorage.setItem("token", "stored-token");
clearTokenCookies();
expect(sessionStorage.getItem("token")).toBeNull();
});
});

describe("storeLoginToken", () => {
it("should store the token in sessionStorage", () => {
storeLoginToken("my-jwt-token");
expect(sessionStorage.getItem("token")).toBe("my-jwt-token");
});

it("should overwrite an existing token in sessionStorage", () => {
storeLoginToken("old-token");
expect(sessionStorage.getItem("token")).toBe("old-token");

storeLoginToken("new-token");
expect(sessionStorage.getItem("token")).toBe("new-token");
});

it("should not throw when window is undefined (server-side rendering)", () => {
const originalWindow = global.window;
delete (global as any).window;

expect(() => storeLoginToken("token")).not.toThrow();

global.window = originalWindow;
});
});

describe("getCookie", () => {
Expand All @@ -141,5 +172,26 @@ describe("cookieUtils", () => {
expect(getCookie("token")).toBe("token-value");
expect(getCookie("other")).toBe("other-value");
});

it("should handle values containing '=' characters", () => {
document.cookie = "token=abc=def=ghi; path=/";
expect(getCookie("token")).toBe("abc=def=ghi");
});

it("should fall back to sessionStorage when cookie is not found", () => {
sessionStorage.setItem("token", "session-stored-jwt");
expect(getCookie("token")).toBe("session-stored-jwt");
});

it("should prefer cookie over sessionStorage", () => {
document.cookie = "token=cookie-value; path=/";
sessionStorage.setItem("token", "session-value");
expect(getCookie("token")).toBe("cookie-value");
});

it("should not fall back to sessionStorage for non-token keys", () => {
sessionStorage.setItem("other", "other-value");
expect(getCookie("other")).toBeNull();
});
});
});
45 changes: 43 additions & 2 deletions ui/litellm-dashboard/src/utils/cookieUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,16 +43,57 @@ export function clearTokenCookies() {
});
});

try {
sessionStorage.removeItem("token");
} catch {
// sessionStorage may be unavailable
}

console.log("After clearing cookies:", document.cookie);
Comment thread
jaxhend marked this conversation as resolved.
Resolved
}

/**
* Stores the login token in sessionStorage.
* This ensures the token is available even when a reverse proxy adds HttpOnly
* to server-set cookies, making them invisible to JavaScript.
*
* Note: sessionStorage is per-tab, so users behind an HttpOnly proxy must log
* in once per tab. We intentionally avoid localStorage here because it persists
* after browser close and is readable by any injected script (XSS).
*/
export function storeLoginToken(token: string) {
if (typeof window === "undefined") return;
try {
sessionStorage.setItem("token", token);
} catch {
// sessionStorage may be unavailable (e.g. private browsing quota exceeded)
}
Comment thread
jaxhend marked this conversation as resolved.
Resolved
}

/**
* Gets a cookie value by name
* @param name The name of the cookie to retrieve
* @returns The cookie value or null if not found
*/
export function getCookie(name: string) {
if (typeof document === "undefined") return null;
const cookieValue = document.cookie.split("; ").find((row) => row.startsWith(name + "="));
return cookieValue ? cookieValue.split("=")[1] : null;
const row = document.cookie.split("; ").find((r) => r.startsWith(name + "="));
if (row) {
const raw = row.split("=").slice(1).join("=");
try {
return decodeURIComponent(raw);
} catch {
return raw;
}
}
// Fallback to sessionStorage — covers the case where a reverse proxy
// added HttpOnly to the server-set cookie, making it invisible to JS.
if (name === "token" && typeof window !== "undefined") {
try {
return sessionStorage.getItem(name);
} catch {
return null;
}
}
Comment thread
jaxhend marked this conversation as resolved.
Resolved
Comment thread
jaxhend marked this conversation as resolved.
Resolved
return null;
}
Loading