Skip to content

fix(cli): mint per-session agent credential on lite login - #31072

Merged
mateo-berri merged 16 commits into
litellm_internal_stagingfrom
litellm_fix_lite_login_session_token
Jun 26, 2026
Merged

mateo-berri merged 16 commits into
litellm_internal_stagingfrom
litellm_fix_lite_login_session_token

Conversation

@Sameerlite

@Sameerlite Sameerlite commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

Relevant issues

Linear ticket

Fixes LIT-3879

Pre-Submission checklist

  • I have added meaningful tests
  • My PR passes all unit tests on make test-unit
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have requested a Greptile review by commenting @greptileai and received a Confidence Score of at least 4/5 before requesting a maintainer review

Summary

lite login was producing a shared UI dashboard session token instead of an agent credential. Three concrete breakages:

  1. Every session got max_budget = litellm.max_ui_session_budget ($0.25) -- enough for a few chat turns, not a coding agent session.
  2. Every user on every session shared the same fixed identity cli-jwt-token, so spend logs and Prometheus metrics couldn't distinguish sessions or users.
  3. Auth was gated on EXPERIMENTAL_UI_LOGIN; CLI tokens were rejected on default deployments.

This PR fixes all three. Each lite login now mints a short-lived cli-session-{uuid} token with no per-key budget cap; budget is enforced via the existing shared team/user counters (team_id/user_id) that common_checks already maintains. The decrypt path activates for any non-sk- token without requiring EXPERIMENTAL_UI_LOGIN. The UI dashboard token path (get_experimental_ui_login_jwt_auth_token) is unchanged.

The key-level cap is intentionally absent whenever the user or their team has a real budget. Copying the team/user budget onto each token creates a double-spend flaw: N concurrent logins each get an independent full-budget envelope, letting N* the intended spend through. Relying on the shared counters means all sessions -- concurrent or sequential -- draw from the same pool.

The one exception is the unbounded case: when neither the user nor the resolved team has any max_budget, /sso/cli/poll falls back to litellm.max_ui_session_budget as the token's per-key ceiling. Without this, a completed lite login on a deployment that relies on max_ui_session_budget (rather than explicit user/team budgets) could run LLM calls with no ceiling for the whole token lifetime. The fallback closes that bypass while leaving budgeted users and teams uncapped at the key level.

This PR also addresses a delegation ceiling regression: removing max_budget from CLI tokens meant the key-generation delegation check (GHSA-q775-qw9r-2r4g) treated None as "unlimited delegation authority", allowing an internal_user to mint virtual keys with arbitrary budgets. CLI tokens now carry is_session_token=True; the delegation check uses the team's max_budget as the ceiling in that case.

Changes

litellm/constants.py -- renamed CLI_JWT_TOKEN_NAME to CLI_SESSION_KEY_PREFIX = "cli-session".

litellm/proxy/auth/auth_checks.py -- rewrote get_cli_jwt_auth_token to generate a unique token = cli-session-{uuid} per login, set key_alias = cli-session-{user_id} for log grouping, omit max_budget, and set is_session_token=True.

litellm/proxy/_types.py -- added is_session_token: bool = False to UserAPIKeyAuth. Serialized into the encrypted CLI token blob; defaults to False for all DB-backed virtual keys.

litellm/proxy/auth/user_api_key_auth.py -- replaced if get_secret_bool("EXPERIMENTAL_UI_LOGIN") with if not api_key.startswith("sk-"). Real sk- keys skip the decrypt entirely; non-sk- blobs decrypt via NaCl SecretBox and fail closed for anything that isn't a genuine CLI/UI token. Operators who explicitly set EXPERIMENTAL_UI_LOGIN=false retain their opt-out.

litellm/proxy/management_endpoints/key_management_endpoints.py -- updated the delegation ceiling check to compute delegation_ceiling from team_table.max_budget when is_session_token=True and the token carries max_budget=None, preventing unbounded key delegation from CLI sessions.

tests/otel_tests/test_e2e_budgeting.py -- added test_team_budget_enforcement_cli_sso_token which creates a team with a tiny budget, mints a CLI SSO token via the poll flow, drives requests until the team budget is exceeded, and asserts the 429 names the team.

tests/test_litellm/proxy/auth/test_auth_checks.py -- updated existing budget assertion (max_budget is None, is_session_token=True) and added test_get_cli_jwt_auth_token_unique_per_session.

tests/test_litellm/proxy/auth/test_user_api_key_auth.py -- added three auth-path tests: CLI token authenticates without EXPERIMENTAL_UI_LOGIN, random non-sk- string is rejected 401, expired token is rejected.

tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py -- added three delegation tests: CLI session token blocked when requested budget exceeds team budget; CLI session token passes when within team budget; regular unlimited user unaffected.

litellm/proxy/client/README.md, litellm/proxy/client/cli/README.md -- documented the credential semantics (short-lived, per-session, shared team/user budget, no Keys UI visibility, no EXPERIMENTAL_UI_LOGIN needed).

Test plan

Run unit tests:

pytest tests/test_litellm/proxy/auth/test_auth_checks.py::test_get_cli_jwt_auth_token_unique_per_session -v
pytest tests/test_litellm/proxy/auth/test_user_api_key_auth.py::test_cli_session_token_authenticates_without_experimental_flag -v
pytest tests/test_litellm/proxy/auth/test_user_api_key_auth.py::test_random_non_sk_token_is_rejected -v
pytest tests/test_litellm/proxy/auth/test_user_api_key_auth.py::test_expired_cli_session_token_is_rejected -v
pytest tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py::test_cli_session_token_delegation_ceiling_blocked_by_team_budget -v
pytest tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py::test_cli_session_token_delegation_allowed_within_team_budget -v
pytest tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py::test_regular_unlimited_user_delegation_ceiling_not_applied -v

Live proxy proof (proxy running on localhost:4000 with a team that has a $0.02 budget):

# 1. Login -- confirm token has no EXPERIMENTAL_UI_LOGIN requirement
lite login

# 2. Token is a non-sk- blob
jq -r '.key' ~/.litellm/token.json | cut -c1-20

# 3. Sustained requests -- no $0.25 wall
for i in 1 2 3 4 5; do
  curl -s http://localhost:4000/v1/messages \
    -H "Authorization: Bearer $(jq -r .key ~/.litellm/token.json)" \
    -H 'content-type: application/json' \
    -d '{"model":"claude-haiku","max_tokens":64,"messages":[{"role":"user","content":"say hi"}]}' \
    | jq '.usage'
done

# 4. Two logins produce different token ids (per-session isolation)
TOKEN1=$(lite login 2>/dev/null; jq -r .key ~/.litellm/token.json)
TOKEN2=$(lite login 2>/dev/null; jq -r .key ~/.litellm/token.json)
# TOKEN1 != TOKEN2

# 5. CLI session token blocked from creating keys exceeding team budget
curl -s -X POST http://localhost:4000/key/generate \
  -H "Authorization: Bearer $(jq -r .key ~/.litellm/token.json)" \
  -H 'content-type: application/json' \
  -d '{"max_budget": 99999}' | jq '.error'
# Should return 400 with "max_budget ... cannot exceed"
image

Type

Bug Fix


Note

High Risk
Changes proxy authentication defaults, CLI token minting, and key-delegation budget ceilings—security-sensitive paths that affect who can spend and mint keys on default deployments.

Overview
lite login now issues a unique cli-session-{uuid} credential per session (stable cli-session-{user_id} alias for logs) instead of a shared cli-jwt-token identity, and drops the default max_ui_session_budget cap on the token so agent spend is limited by existing team/user budgets.

Auth: non-sk- encrypted blobs are decrypted on the LLM path by default; only an explicit EXPERIMENTAL_UI_LOGIN=false disables that. UserAPIKeyAuth gains is_session_token so key generation treats CLI sessions as bounded by team max_budget for delegation (fixes None being read as unlimited authority) and blocks personal keys with an explicit budget unless team_id is set.

CLI SSO poll: /sso/cli/poll loads user/team budgets and only applies max_ui_session_budget when both lack a budget; otherwise max_budget on the minted token stays None.

Docs and tests cover credential semantics, auth without the experimental flag, delegation ceilings, and e2e team budget enforcement for CLI SSO tokens.

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

@greptile-apps

greptile-apps Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes three concrete breakages in lite login: shared identity across all sessions (cli-jwt-token), the $0.25 UI chat-session cap being applied to long-lived agent tokens, and CLI auth being gated behind EXPERIMENTAL_UI_LOGIN. Each login now mints a unique cli-session-{uuid} credential; budget is enforced via the existing shared team/user counters; and the decrypt path activates for any non-sk- blob unless the operator explicitly sets EXPERIMENTAL_UI_LOGIN=false.

  • Auth path (user_api_key_auth.py): the decrypt gate is now get_secret_bool("EXPERIMENTAL_UI_LOGIN") is not False — None and true both attempt decryption (fails closed for non-blobs), explicit false preserves the old boundary.
  • Delegation ceiling (key_management_endpoints.py): is_session_token=True tokens now use team_table.max_budget as the delegation ceiling (instead of treating max_budget=None as unlimited authority); personal keys with an explicit budget are blocked outright when no team is specified in the request.
  • Budget fallback (ui_sso.py): /sso/cli/poll fetches user and team objects and applies max_ui_session_budget only when both are unbudgeted; all code paths are covered by new unit and e2e tests.

Confidence Score: 5/5

Safe to merge; all three auth regressions are correctly fixed, delegation ceiling logic is sound, and tests cover the critical new behaviors comprehensively.

The auth changes (decrypt gate, token uniqueness, delegation ceiling) are correct and well-tested. The only note is a silent except Exception: pass in cli_poll_key that could skip the max_ui_session_budget fallback if a team DB lookup fails transiently — but this requires a narrow combination of conditions (team member, transient error, no explicit user/team budget) and only affects observability rather than a definitive bypass of the primary budget-enforcement path.

No files require special attention; the delegation ceiling logic in key_management_endpoints.py and the budget-resolution path in ui_sso.py are the most security-sensitive changes and both reviewed thoroughly.

Important Files Changed

Filename Overview
litellm/proxy/auth/auth_checks.py Each CLI login now mints a unique cli-session-{uuid} token with a stable cli-session-{user_id} alias; max_budget and is_session_token=True are set correctly, and the max_budget parameter plumbing allows the caller to pass either the fallback cap or None.
litellm/proxy/auth/user_api_key_auth.py The decrypt gate is now get_secret_bool("EXPERIMENTAL_UI_LOGIN") is not False — unset/true both attempt decryption (fails closed for non-blobs), while an explicit false preserves the old boundary. The UserAPIKeyAuth(**kwargs) → model_validate(kwargs) switch is safe.
litellm/proxy/management_endpoints/key_management_endpoints.py Delegation ceiling now uses team_table.max_budget for is_session_token=True callers when their own max_budget is None; personal keys with an explicit budget are blocked outright when no team is provided in the request, closing the gap identified in the previous review thread.
litellm/proxy/management_endpoints/ui_sso.py Budget resolution now fetches user and team objects before minting the JWT; the fallback cap logic is correct for the happy path but silently skips when team lookup throws an exception, potentially leaving an uncapped token in an edge case.
litellm/proxy/_types.py Adds is_session_token: bool = False to UserAPIKeyAuth; serialised into the encrypted CLI token blob and defaults to False for all DB-backed virtual keys — no schema migration needed.
tests/test_litellm/proxy/auth/test_user_api_key_auth.py Four new tests cover: CLI token authenticates without EXPERIMENTAL_UI_LOGIN, random non-sk- rejected 401, expired token rejected, non-admin internal user flows through production auth path — all mock-based.
tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py Five new delegation tests cover the full matrix: budget blocked/allowed within team ceiling for session tokens, personal-key-with-budget blocked, personal-key-without-budget allowed, and regular unlimited user unaffected.
tests/otel_tests/test_e2e_budgeting.py New e2e test exercises the full poll flow via shared Redis, skipping (not silently bypassing) when Redis is unavailable; tests team budget enforcement end-to-end for CLI SSO tokens.

Reviews (12): Last reviewed commit: "revert(auth): restore CLI session fallba..." | Re-trigger Greptile

Comment thread litellm/proxy/auth/user_api_key_auth.py Resolved
Comment thread tests/otel_tests/test_e2e_budgeting.py Resolved
Comment thread tests/otel_tests/test_e2e_budgeting.py Resolved
Comment thread litellm/proxy/client/README.md Resolved
@codecov

codecov Bot commented Jun 23, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.00000% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/proxy/auth/user_api_key_auth.py 66.66% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

Comment thread litellm/proxy/auth/user_api_key_auth.py Resolved
@veria-ai

veria-ai Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

All previously flagged issues have been addressed. No open security concerns remain on this pull request.

Security review

No open security issues remain on this pull request.

Fixed/addressed: 3 · PR risk: 0/10

@Sameerlite

Copy link
Copy Markdown
Contributor Author

@greptileai

Comment thread litellm/proxy/auth/auth_checks.py Resolved
@Sameerlite

Copy link
Copy Markdown
Contributor Author

@greptileai

@Sameerlite

Copy link
Copy Markdown
Contributor Author

@greptileai

@mateo-berri mateo-berri left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The auth unit tests only exercise the admin fast-return path, leaving the non-admin production path covered only by the e2e test

Please add coverage as needed

@Sameerlite

Copy link
Copy Markdown
Contributor Author

@greptileai

@Sameerlite
Sameerlite requested a review from a team June 24, 2026 16:01
The `lite login` command was producing a shared UI session token that broke agent use in three ways: a $0.25 budget cap (from max_ui_session_budget) that killed agent sessions in minutes, a fixed identity "cli-jwt-token" shared across every user preventing per-session spend attribution, and auth gated behind EXPERIMENTAL_UI_LOGIN so the token was rejected on default deployments.

This fixes all three. Each login now generates a unique cli-session-{uuid} token with no per-key budget cap (enforced via shared team/user counters instead), and the decrypt path activates for any non-sk- token without requiring EXPERIMENTAL_UI_LOGIN.
…2e test

Restore EXPERIMENTAL_UI_LOGIN=false as an explicit opt-out: operators who set it to false keep the old boundary; unset (new default) and true both attempt NaCl decryption, which fails closed for non-blob tokens.

In the e2e test: replace the silent Redis fallback with pytest.skip so a missing Redis instance is explicit rather than silently degrading to a directly-minted token. Write the seeded flow back as JSON (proxy reads it via json.loads on cache fetch) instead of Python repr, and build the updated flow immutably.
…ceiling

A CLI session token intentionally carries max_budget=None to avoid a per-session LLM spend cap. The key-generation delegation check (GHSA-q775-qw9r-2r4g) previously skipped non-admin callers with max_budget=None, treating them as having unlimited delegation authority. This allowed any internal user with a lite login session to mint virtual keys with arbitrary budgets.

Adds is_session_token=True to UserAPIKeyAuth for CLI session tokens and uses the caller's team budget as the delegation ceiling in that case, so the effective limit is min(requested_budget, team.max_budget) rather than unbounded.
The is_session_token field added to UserAPIKeyAuth cascades to the
dashboard schema. Regenerate types from the updated OpenAPI spec.
…ssion tokens

When team_table is None (personal key, no team_id in request), the personal key
has no team-budget enforcement at request time. A session token therefore cannot
delegate any explicit max_budget for a personal key -- that would open a budget
bypass path. Block the request with a clear 400 directing the caller to use a
team_id instead.
@Sameerlite
Sameerlite force-pushed the litellm_fix_lite_login_session_token branch from 27b14ff to 1d72c3c Compare June 24, 2026 16:05
…to fix reportArgumentType gate

UserAPIKeyAuth(**user_api_key_kwargs) spread triggers a basedpyright
reportArgumentType error for each named field in UserAPIKeyAuth because
the dict's inferred value type (str | Span | LitellmUserRoles | Unknown)
is not assignable to each field's specific type. Adding is_session_token:
bool introduced +2 more such errors, breaching the gate cap.

model_validate accepts an untyped dict without per-field argument checking,
which eliminates the +2 new errors and also ratchets down the pre-existing
333 errors at those call sites. basedpyright-code-budget.json is updated
to reflect the new lower baseline (1814, down from 1934).
The previous lint-budget-update captured all baselines from the local
environment, raising many ceilings vs the merge-base and failing the
non-gating budget_ratchet_check. Restore staging's values for every
rule and only lower reportArgumentType (1934 -> 1814) to reflect the
reduction from switching to model_validate in _return_user_api_key_auth_obj.
@Sameerlite

Copy link
Copy Markdown
Contributor Author

@greptileai

Comment thread litellm/proxy/auth/auth_checks.py Resolved
…ion_budget

CLI session tokens were missing max_budget, so _virtual_key_max_budget_check
had no per-session ceiling to enforce. Operators relying on max_ui_session_budget
could be bypassed for the full token lifetime. Mirrors the existing UI token path.
max_ui_session_budget defaults to $0.25 and is sized for the UI chat
pane (10-min sessions). CLI sessions are 24-hour tokens for real work;
capping them at that ceiling would throttle users under their actual
user/team budget. Budget enforcement for CLI sessions is via the shared
user and team counters as originally intended.
…d team have no budget

When neither the user nor their team has a budget configured, CLI sessions
were fully uncapped. The poll endpoint now looks up the real user and team
objects from DB; if both have no max_budget, it passes litellm.max_ui_session_budget
as the token's per-key ceiling. Users or teams that already have a budget
configured are unaffected and continue to rely on the shared counters.
… budget lookup

The get_user_object and get_team_object async calls in cli_poll_key were
not mocked in the existing test, causing MagicMock await errors. Patch
both functions at the auth_checks module level. Also apply black formatting
to ui_sso.py which CI rejected.
@Sameerlite

Copy link
Copy Markdown
Contributor Author

@greptileai

@Sameerlite

Copy link
Copy Markdown
Contributor Author

@greptileai

@Sameerlite
Sameerlite requested a review from mateo-berri June 25, 2026 12:58
@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

The session_max_budget fallback in cli_poll_key only applied
max_ui_session_budget when neither the user nor the resolved team had a
budget. The existing coverage exercised only the team-lookup-failure
branch. Add two regression tests: a user with a configured budget must
not receive the fallback cap, and a session with no user and no team
budget must fall back to max_ui_session_budget. Mutating either guard
out of the branch now fails these tests.
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

Autofix Details

Bugbot Autofix prepared a fix for the issue found in the latest run.

  • ✅ Fixed: Poll path reapplies UI session budget
    • Removed the poll endpoint budget fallback so CLI JWTs are minted without a per-key UI session budget and added regression coverage for unlimited user/team sessions.

You can send follow-ups to the cloud agent here.

cursoragent and others added 2 commits June 25, 2026 17:58
Bugbot autofix (60b81fb) removed the user/team budget lookup in
cli_poll_key and stopped passing max_budget to the session token,
making CLI sessions fully uncapped whenever neither the user nor the
team has an explicit budget.

That reintroduces the unbounded-spend bypass veria flagged as High
("CLI session budget bypass"): on deployments that rely on
max_ui_session_budget rather than per-user/team budgets, a completed
lite login could run LLM calls with no ceiling for the whole token
lifetime. The fallback only applies when no other budget bounds the
session, so users and teams with a configured budget are unaffected and
keep relying on their shared counters.
@CLAassistant

CLAassistant commented Jun 25, 2026 •

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
2 out of 3 committers have signed the CLA.

✅ mateo-berri
✅ Sameerlite
❌ cursoragent
You have signed the CLA already but the status is still pending? Let us recheck it.

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

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 994d742. Configure here.

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

Addressing the lone remaining finding in the Greptile summary: the except Exception: pass around the team lookup in cli_poll_key that can skip the max_ui_session_budget fallback on a transient DB error

This is intentional and fails safe in practice. When the mint-time team lookup throws, the token is still minted with user_id and team_id embedded; only the per-key max_budget fallback is skipped. Spend for that session is governed by the shared user/team counters that common_checks enforces at request time (_team_max_budget_check and the user-budget branch), and those counters re-resolve the team from cache or DB on every call. So a team that actually has a max_budget stays bounded even though the mint-time read hiccuped; the transient failure does not disable request-time enforcement

The fallback only matters when neither the user nor the resolved team has any configured budget. Applying it on a lookup failure would do the opposite of fail-closed for the common case: it would throttle a legitimately budgeted team's session down to max_ui_session_budget for the whole session because of one transient read. The resolved-flag guard deliberately prefers request-time enforcement over a stale mint-time guess

The residual window is narrow: a transient DB failure during the poll, on a deployment where the resolved team genuinely has no budget and the user genuinely has no budget. The token is short-lived (default 24h, configurable via LITELLM_CLI_JWT_EXPIRATION_HOURS) and the next lite login re-mints with the cap, so it self-heals


Generated by Claude Code

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai


Generated by Claude Code

@mateo-berri mateo-berri left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM; thanks!

@mateo-berri
mateo-berri merged commit 687a62e into litellm_internal_staging Jun 26, 2026
77 checks passed
@mateo-berri
mateo-berri deleted the litellm_fix_lite_login_session_token branch June 26, 2026 16:05
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.

4 participants