Skip to content

fix(ui): use the dashboard session in hosted Lens frames - #257

Merged
tin-berri merged 3 commits into
mainfrom
litellm_dashboard_frame_session
Nov 25, 2026
Merged

tin-berri merged 3 commits into
mainfrom
litellm_dashboard_frame_session

Conversation

@tin-berri

@tin-berri tin-berri commented Nov 25, 2026 •

Copy link
Copy Markdown
Collaborator

Embedded Lens now uses the authenticated dashboard session for both its session check and data requests. It waits for a handoff from the same-origin parent and omits cookies from those requests, so a missing or different root cookie cannot select its account

Companion to BerriAI/litellm#54248. The gateway marks the iframe with data-lens-auth="bearer-v1" and checks its origin and source before sending the existing bearer. The marker stays on the iframe across URL changes, and Inspect run stays in that frame. Standalone Lens and older dashboard parents keep their existing cookie behavior. Either upgrade order is supported. The shared-session fix becomes active when both changes are present

The UI advertises X-Lens-UI-Auth: bearer-v1. The existing HTTP clients take their credential and cookie policy from the host configuration. No new backend session, token exchange, cookie, or authorization policy is introduced

User Flow

Before, Lens asks for another login while the dashboard still works.

  1. Sign in and open http://lens-shared.localhost:13098/ui/lens.
  2. Expire only the root login cookie, retaining the dashboard login.
  3. Reopen Lens. It says “Sign in to LiteLLM again”.

Before, Lens rejects the still-valid dashboard login

After, Lens uses the login of the dashboard displaying it.

  1. Sign in and open http://lens-shared.localhost:13098/ui/lens.
  2. Expire only the root login cookie, retaining the dashboard login.
  3. Reopen Lens. Its workspace and Traces page load.

After, Lens opens with the displayed dashboard account

Screenshots / Proof of Fix

The 20-second recording shows the real dashboard and Lens. A QA helper expires only the root cookie and reopens Lens, then the Traces page loads. Another helper logs in as a second local user and changes only the root cookie. The displayed admin dashboard and its Lens frame stay on the admin session. The helpers only prepare browser state; neither ships with the product.

lens-session-demo.mp4

The real two-tab check also passes. With an Admin dashboard tab still mounted, a second tab signs in as Internal User through the normal login form. Opening Lens in the first tab shows Internal User in the account menu, returns internal_user from /lens/auth/session, and removes Lens's admin-only Alerts and Settings controls.

After a second-tab login, the account menu and Lens both use Internal User

This is a controlled reproduction of the cookie mismatch. Ordinary login works before and after. It does not establish the cause of the original intermittent cookie loss. The demo uses real LiteLLM, Lens, PostgreSQL, ClickHouse, and a dedicated Redis. No model inference is needed for this auth flow. Demo data is off.

The baseline browser screenshot ran LiteLLM d039b6c80aca542adaef74127fa161a3172d9dee and Lens 23a8088b2d6caba28048124be909534b5457d68d. The initial cookie-mismatch recording ran LiteLLM e3967a8fb46ab9ffa7953eaf8d24c114e6ec3c20 and Lens 76abc01942d38975b816be62b082cfe0b4acec08. The service comparison below reran both gateway revisions against Lens 76abc01942d38975b816be62b082cfe0b4acec08. Both gateway revisions accept dashboard bearers already; this change connects the iframe to that existing path.

Final browser navigation proof (8ae1726 gateway, 882ba47 Lens)

With only the dashboard-path login cookie present, opened a real trace thread and clicked its earlier-turn Inspect run link. The iframe navigated to that run and completed a fresh parent handshake. Session, trace detail, span, and conversation requests returned 200 with a bearer and no session cookie

Clicked More run actions > Copy link, pasted the actual system clipboard into a new Chrome tab, and opened the result. It was /ui/lens?trace=...&trace_ref=..., and the trace loaded under the dashboard's Admin account. No credential appears in the link

The 24-second recording contains 144 actual browser captures. It shows Inspect run, Copy link, and the shared destination opening successfully. The two harmless synthetic turns were sent through the real OTLP ingestion API and stored in local ClickHouse. Demo data is off, and no model was called

lens-session-navigation.mp4

A copied trace opens through the authenticated dashboard

Inspect run stays in the authenticated dashboard frame

To reproduce, sign in, remove only the root token cookie while keeping the /ui token, open a trace with an earlier conversation turn, click Inspect run, then copy its link and open it in another tab. Expect the run to load both times without another login

Shared setup

Both gateway revisions use two uvicorn workers and the same dedicated Redis on 16398. PostgreSQL listens on 15488, Lens on 14318, and ClickHouse on 14323. The UI is on 13098 and its forwarding adapter on 14099.

Exact configuration, startup commands, and browser reproduction

Use isolated local databases. Export DATABASE_URL, UI_USERNAME, UI_PASSWORD, LITELLM_MASTER_KEY, LITELLM_LENS_URL, LENS_GATEWAY_SECRET, LENS_ADMIN_TOKEN, LITELLM_LENS_SERVICE_TOKEN, CLICKHOUSE_PASSWORD, and credentials for an existing second local dashboard user as QA_SECOND_USERNAME and QA_SECOND_PASSWORD. Credentials were loaded privately. LITELLM_LENS_URL points to port 14318; the gateway and Lens share the gateway secret.

From the selected Lens checkout:

npm ci
npm run build:ui
cargo build --manifest-path src/worker/Cargo.toml -p litellm-lens
LITELLM_LENS_LISTEN=127.0.0.1:14318 \
LENS_UI_DIRECTORY="$PWD/src/ui/app/out" \
LENS_MODE=standalone \
LENS_PUBLIC_URL=http://localhost:14318 \
LENS_SIGN_IN_LINK=false \
CLICKHOUSE_URL="http://lens:$CLICKHOUSE_PASSWORD@127.0.0.1:14323" \
CLICKHOUSE_DATABASE=lens \
"$CARGO_TARGET_DIR/debug/litellm-lens"

The local build reused an existing CARGO_TARGET_DIR. Start Redis separately:

redis-server --port 16398 --save "" --appendonly no

Save as $QA_DIR/config.yaml:

general_settings:
  coordination_redis:
    host: 127.0.0.1
    port: 16398
  database_url: os.environ/DATABASE_URL
  master_key: os.environ/LITELLM_MASTER_KEY
  password_policy_check_breached_passwords: false
litellm_settings: {}
model_list: []
router_settings:
  redis_host: 127.0.0.1
  redis_port: 16398
sandbox_tools:
- litellm_params:
    api_key: os.environ/E2B_API_KEY
    sandbox_provider: e2b
  sandbox_tool_name: e2b_sandbox

From the selected LiteLLM checkout:

PYTHONPATH="$PWD:$PWD/litellm/runtime" \
CONFIG_FILE_PATH="$QA_DIR/config.yaml" \
PROXY_BASE_URL=http://lens-shared.localhost:13098 \
LITELLM_LOG=DEBUG \
.venv/bin/python -m uvicorn litellm.runtime.backend.main:app \
  --port 14098 --host 127.0.0.1 --workers 2

Save the following as qa_forwarder.py and run python qa_forwarder.py with httpx installed. The local launcher obtained the second account from a private JSON file; the equivalent portable version below reads the same two values from environment variables.

from http.server import BaseHTTPRequestHandler,ThreadingHTTPServer
import httpx
import json
import os
from pathlib import Path
from urllib.parse import urlsplit, urlunsplit
class Upstream(BaseHTTPRequestHandler):
    def do_request(self):
        if self.path == '/__qa/login-another-tab':
            self.send_response(303)
            self.send_header('Set-Cookie','token=; Max-Age=0; Path=/; SameSite=Lax')
            self.send_header('Set-Cookie','token=; Max-Age=0; Path=/ui; SameSite=Lax')
            self.send_header('Location','/ui/login')
            self.end_headers()
            return
        if self.path == '/__qa/switch-account':
            account={'user_email':os.environ['QA_SECOND_USERNAME'],'password':os.environ['QA_SECOND_PASSWORD']}
            result=httpx.post('http://127.0.0.1:14098/v2/login',json={'username':account['user_email'],'password':account['password']},headers={'Host':'lens-shared.localhost:13098','Accept':'application/json'},timeout=40)
            if result.status_code != 200:
                self.send_response(503);self.end_headers();return
            self.send_response(303)
            for cookie in result.headers.get_list('set-cookie'):
                self.send_header('Set-Cookie',cookie)
            self.send_header('Location','/ui/lens')
            self.end_headers()
            return
        if self.path == '/__qa/missing-root':
            self.send_response(303)
            self.send_header('Set-Cookie','token=; Max-Age=0; Path=/; SameSite=Lax')
            self.send_header('Location','/ui/lens')
            self.end_headers()
            return
        parts = urlsplit(self.path)
        path = urlunsplit(('', '', '/lens/ui/' if parts.path == '/lens/ui' else parts.path, parts.query, ''))
        body=self.rfile.read(int(self.headers.get('Content-Length','0')))
        headers={k:v for k,v in self.headers.items() if k.lower() not in ('host','connection','accept-encoding')}
        headers.update({'Host':'lens-shared.localhost:13098','Accept-Encoding':'identity'})
        try:
            r=httpx.request(self.command,'http://127.0.0.1:14098'+path,headers=headers,content=body,timeout=40)
            if parts.path.startswith('/lens/') and '/ui/' not in parts.path:
                event = {
                    'method': self.command,
                    'path': parts.path,
                    'bearer': bool(self.headers.get('Authorization')),
                    'session_cookie': any(part.strip().startswith('token=') for part in self.headers.get('Cookie','').split(';')),
                    'status': r.status_code,
                    'sets_cookie': 'set-cookie' in r.headers,
                }
                if parts.path == '/lens/auth/session' and r.status_code == 200:
                    event['user_role'] = r.json().get('user_role')
                with (Path(__file__).parent/'browser-requests.jsonl').open('a') as log:
                    log.write(json.dumps(event)+'\n')
            self.send_response(r.status_code)
            for k,v in r.headers.multi_items():
                if k.lower() not in ('content-length','transfer-encoding','connection','content-encoding'):
                    self.send_header(k,v)
            self.send_header('Content-Length',str(len(r.content)));self.end_headers();self.wfile.write(r.content)
        except (BrokenPipeError, ConnectionResetError):pass
    do_GET=do_request
    do_POST=do_request
    do_PUT=do_request
    do_PATCH=do_request
    do_DELETE=do_request
    do_OPTIONS=do_request
    def log_message(self,*args):pass
ThreadingHTTPServer(('127.0.0.1',14099),Upstream).serve_forever()

From litellm/ui/litellm-dashboard:

NEXT_PUBLIC_USE_REWRITES=true \
LENS_DEV_PROXY_URL=http://127.0.0.1:14099 \
node node_modules/next/dist/bin/next dev --webpack --port 13098

Sign in normally at http://lens-shared.localhost:13098/ui/lens. Visit /__qa/missing-root, which removes only the root cookie and redirects to Lens. On the baseline, Lens shows the login error while the dashboard still works. With the paired changes, Lens and Traces load.

Sign in as the first user again, then visit /__qa/switch-account. This calls the real second user's login and changes only the root cookie. The final dashboard and Lens retain the first user's identity. This models a root-only account update; an external SSO provider was not exercised.

The account-switch regression renders the real dashboard account menu alongside Lens with AuthProvider still mounted. After another account replaces the shared dashboard cookie, opening Lens uses the same account as that menu. The key and configured header come from the same useAuthorized token. The dashboard layout has a separate mounted AuthContext gate, which remains unchanged. This PR does not introduce a new dashboard-wide cross-tab login policy.

Before (d039b6c80aca542adaef74127fa161a3172d9dee)

The browser fails at the Lens login shown above. Run python session_probe.py before with the client below:

{
  "mode": "before",
  "normal_login_lens": 200,
  "controlled_root_cookie_loss": true,
  "dashboard_bearer": 200,
  "lens_cookie_only": 401,
  "lens_dashboard_bearer": 200,
  "same_dashboard_user": true,
  "no_cookie_created": true,
  "ui_bearer_capability": null,
  "shared_cookie_does_not_switch_tab_a": true,
  "second_tab_uses_its_dashboard_user": true,
  "shared_cookie_unchanged": true,
  "neither_tab_sets_cookie": true,
  "revoked_dashboard": 401,
  "revoked_lens": 401,
  "revoked_bearer_does_not_fall_back_to_other_cookie": true,
  "other_session_still_valid": true
}

After (e3967a8fb46ab9ffa7953eaf8d24c114e6ec3c20, Lens 76abc01942d38975b816be62b082cfe0b4acec08)

The same browser flow opens Lens. Run python session_probe.py after:

{
  "mode": "after",
  "normal_login_lens": 200,
  "controlled_root_cookie_loss": true,
  "dashboard_bearer": 200,
  "lens_cookie_only": 401,
  "lens_dashboard_bearer": 200,
  "same_dashboard_user": true,
  "no_cookie_created": true,
  "ui_bearer_capability": "bearer-v1",
  "shared_cookie_does_not_switch_tab_a": true,
  "second_tab_uses_its_dashboard_user": true,
  "shared_cookie_unchanged": true,
  "neither_tab_sets_cookie": true,
  "revoked_dashboard": 401,
  "revoked_lens": 401,
  "revoked_bearer_does_not_fall_back_to_other_cookie": true,
  "other_session_still_valid": true
}

The actual iframe's session, traces, and admin requests were also observed with a bearer, no session cookie, HTTP 200, and no Set-Cookie. The parent availability request may carry the browser cookie; its explicit dashboard bearer still selects the identity.

Credential-free service verification client

Save as session_probe.py. It uses the environment variables above and prints only statuses and comparisons, never tokens.

import json
import os
import sys

import httpx
import jwt

ORIGIN = "http://lens-shared.localhost:13098"
HEADERS = {
    "Host": "lens-shared.localhost:13098",
    "Origin": ORIGIN,
    "Sec-Fetch-Site": "same-origin",
    "Accept": "application/json",
}


def login(client, username, password):
    response = client.post("/v2/login", json={"username": username, "password": password})
    assert response.status_code == 200, f"login: {response.status_code}"
    token = response.json()["token"]
    claims = jwt.decode(token, os.environ["LITELLM_MASTER_KEY"], algorithms=["HS256"])
    return token, claims["key"], claims["user_id"]


def bearer(key):
    return {"Authorization": f"Bearer {key}"}


with httpx.Client(
    base_url="http://127.0.0.1:14098", headers=HEADERS, timeout=45, follow_redirects=False
) as client:
    token_a, key_a, user_a = login(client, os.environ["UI_USERNAME"], os.environ["UI_PASSWORD"])
    normal = client.get("/lens/auth/session")
    client.cookies.clear()
    dashboard = client.get("/management/v1/users/me", headers=bearer(key_a))
    cookie_only = client.get("/lens/auth/session")
    embedded = client.get("/lens/auth/session", headers=bearer(key_a))
    report = {
        "mode": sys.argv[1],
        "normal_login_lens": normal.status_code,
        "controlled_root_cookie_loss": True,
        "dashboard_bearer": dashboard.status_code,
        "lens_cookie_only": cookie_only.status_code,
        "lens_dashboard_bearer": embedded.status_code,
        "same_dashboard_user": embedded.json().get("user_id") == user_a,
        "no_cookie_created": not client.cookies and "set-cookie" not in embedded.headers,
        "ui_bearer_capability": client.get("/lens/ui/").headers.get("x-lens-ui-auth"),
    }
    token_b, key_b, user_b = login(
        client, os.environ["QA_SECOND_USERNAME"], os.environ["QA_SECOND_PASSWORD"]
    )
    assert user_a != user_b
    tab_a = client.get("/lens/auth/session", headers=bearer(key_a))
    tab_b = client.get("/lens/auth/session", headers=bearer(key_b))
    report.update(
        shared_cookie_does_not_switch_tab_a=tab_a.json().get("user_id") == user_a,
        second_tab_uses_its_dashboard_user=tab_b.json().get("user_id") == user_b,
        shared_cookie_unchanged=client.cookies.get("token") == token_b,
        neither_tab_sets_cookie="set-cookie" not in tab_a.headers and "set-cookie" not in tab_b.headers,
    )
    logout = client.post("/session/logout", headers=bearer(key_a))
    assert logout.status_code == 200
    client.cookies.set("token", token_b)
    revoked_dashboard = client.get("/management/v1/users/me", headers=bearer(key_a))
    revoked_lens = client.get("/lens/auth/session", headers=bearer(key_a))
    valid_other = client.get("/lens/auth/session", headers=bearer(key_b))
    report.update(
        revoked_dashboard=revoked_dashboard.status_code,
        revoked_lens=revoked_lens.status_code,
        revoked_bearer_does_not_fall_back_to_other_cookie=revoked_lens.status_code == 401,
        other_session_still_valid=valid_other.status_code == 200,
    )
    print(json.dumps(report, indent=2))

Verification

Gateway 8ae172642b16a3ef10361f6ddaef99ed6ac91069: all six required CI checks pass. Greptile reports 5/5, Bugbot reports no issues, and Veria reports no new security issues. Devin has zero outstanding findings. Its older-build proof request was manually marked fixed after the real cookie-mode browser test and screenshot were added

Lens final tip 908976a8db150b9a34a007a713a8e25813cc1036 has identical production code to the recorded 882ba47; it only relocates the copied-link regression into the integration suite. All 61 focused tests and both UI typechecks pass. Devin completed its final analysis with zero outstanding findings and three marked fixed. The live navigation-proof request was manually marked fixed after the actual Inspect run test and recording. Bugbot reports no issues on this tip. The worker/UI contract and Slack-agent CI checks pass. The Rust and two standalone-container jobs are still running; the repository explicitly treats those three as optional. No companion Greptile response has been received

LiteLLM has 199 passing focused backend tests and 38 passing focused UI tests. The account-ownership regressions render the real Account menu and cover paired key/header ownership, root-cookie removal/replacement, shared-cookie replacement, session removal, and initial expiry. Lens has 61 passing focused UI tests on the recorded product revision, both UI typechecks pass, and the final production UI build passes. The unchanged Rust implementation previously passed 30 UI tests and a binary build

The final service probe on 8ae1726 confirms the dashboard and embedded Lens both return 200 after root-cookie loss; the cookie-only request returns 401. Bearers select their own users despite another user's cookie, and a revoked bearer returns 401 without falling back to that cookie

The initial cookie-mismatch recording and two-tab proof use gateway e3967a8 and Lens 76abc019. Their shared-session behavior is unchanged by the later compatibility and copied-link fixes. The final 24-second navigation recording uses 8ae1726 and 882ba47 and rechecks bearer-authenticated requests with the root cookie absent. The actual older Lens build was also exercised separately on 8ae1726

LiteLLM's focused UI ESLint and backend gates pass. The local full dashboard typecheck encounters the existing generated .next/dev/types error for the unchanged AgentControlPlaneView layout export. No lint or type gate was relaxed

Focused verification commands

In LiteLLM:

.venv/bin/python -m pytest tests/unit/integrations/lens/proxy/test_pages.py tests/unit/integrations/lens/proxy/test_adapter.py tests/unit/integrations/lens/proxy/test_buffering.py -q
cd litellm/ui/litellm-dashboard
npx vitest run 'src/app/(dashboard)/lens/page.test.tsx' 'src/app/(dashboard)/lens/page.integration.test.tsx' src/components/lens/EmbeddedLens.integration.test.tsx

In Lens:

npm exec --workspace @litellm/lens-ui -- vitest run src/host/gatewayFrame.test.ts src/components/lens/traces/detail/run/RunHeader.integration.test.tsx src/components/lens/traces/detail/run/RunView.test.tsx tests/gatewayWorkspace.integration.test.tsx
npm run typecheck:ui
cargo test --manifest-path src/worker/Cargo.toml -p lens-server --test ui
npm run build:ui

Note

High Risk
Changes how embedded Lens authenticates API calls (bearer handoff, cookie omission, and share/navigation URLs), which is security-sensitive even though it reuses the dashboard token.

Overview
Embedded Lens no longer relies on browser cookies when it is mounted in a LiteLLM dashboard iframe marked with data-lens-auth="bearer-v1". A new useGatewayAuth handshake posts auth-ready to the parent, waits for a validated auth frame command (bearer + header name), and only then loads the workspace. While hosted, configureLensHttp and the shared API client send that bearer on every request with credentials: "omit", so a missing or mismatched root cookie cannot pick the wrong account.

The worker UI now advertises X-Lens-UI-Auth: bearer-v1. Standalone or unmarked frames keep cookie-based sessions unchanged.

Gateway-frame navigation is tightened: Inspect run opens in _self when gatewayFrameNavigation is set, and Copy link builds share URLs from the parent dashboard path via gatewayFrameShareLocation, stripping iframe-only query noise.

Reviewed by Cursor Bugbot for commit 908976a. Bugbot is set up for automated code reviews on this repo. Configure here.

@tin-berri

Copy link
Copy Markdown
Collaborator Author

bugbot run

Please review the final dashboard bearer handoff, including the paired Lens change and the attached live verification.

@tin-berri

Copy link
Copy Markdown
Collaborator Author

@greptileai review. The final commit removes cookie reconciliation and uses the dashboard bearer. Fresh paired-app proof and rollout requirements are attached.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

devin-ai-integration[bot]

This comment was marked as resolved.

@tin-berri

Copy link
Copy Markdown
Collaborator Author

bugbot run Please review 882ba47: copied trace links now reopen through the same-origin dashboard, and remount-test wording matches its coverage.

@tin-berri

Copy link
Copy Markdown
Collaborator Author

@greptileai review Please check 882ba47 for hosted trace-link routing, standalone compatibility, and credential isolation. Actual iframe navigation passes with the root cookie absent.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@tin-berri

Copy link
Copy Markdown
Collaborator Author

bugbot run Final 908976a only moves the hosted copy regression into the integration suite. Product code matches the recorded 882ba47.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Bugbot reviewed your changes and found no new issues!

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit 908976a. Configure here.

@tin-berri
tin-berri merged commit 4d8b609 into main Nov 25, 2026
7 checks passed
@tin-berri
tin-berri deleted the litellm_dashboard_frame_session branch November 25, 2026 22:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant