Repository navigation
fix(cli): mint per-session agent credential on lite login - #31072
Conversation
Greptile SummaryThis PR fixes three concrete breakages in
Confidence Score: 5/5Safe 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 No files require special attention; the delegation ceiling logic in
|
| 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
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
PR overviewAll previously flagged issues have been addressed. No open security concerns remain on this pull request. Security reviewNo open security issues remain on this pull request. Fixed/addressed: 3 · PR risk: 0/10 |
mateo-berri
left a comment
There was a problem hiding this comment.
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
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.
27b14ff to
1d72c3c
Compare
…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.
…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.
|
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.
|
bugbot run |
There was a problem hiding this comment.
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.
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.
|
|
|
bugbot run |
There was a problem hiding this comment.
✅ 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.
|
Addressing the lone remaining finding in the Greptile summary: the This is intentional and fails safe in practice. When the mint-time team lookup throws, the token is still minted with 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 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 Generated by Claude Code |
|
Generated by Claude Code |
Relevant issues
Linear ticket
Fixes LIT-3879
Pre-Submission checklist
make test-unit@greptileaiand received a Confidence Score of at least 4/5 before requesting a maintainer reviewSummary
lite loginwas producing a shared UI dashboard session token instead of an agent credential. Three concrete breakages:max_budget = litellm.max_ui_session_budget($0.25) -- enough for a few chat turns, not a coding agent session.cli-jwt-token, so spend logs and Prometheus metrics couldn't distinguish sessions or users.EXPERIMENTAL_UI_LOGIN; CLI tokens were rejected on default deployments.This PR fixes all three. Each
lite loginnow mints a short-livedcli-session-{uuid}token with no per-key budget cap; budget is enforced via the existing shared team/user counters (team_id/user_id) thatcommon_checksalready maintains. The decrypt path activates for any non-sk-token without requiringEXPERIMENTAL_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/pollfalls back tolitellm.max_ui_session_budgetas the token's per-key ceiling. Without this, a completedlite loginon a deployment that relies onmax_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_budgetfrom CLI tokens meant the key-generation delegation check (GHSA-q775-qw9r-2r4g) treatedNoneas "unlimited delegation authority", allowing aninternal_userto mint virtual keys with arbitrary budgets. CLI tokens now carryis_session_token=True; the delegation check uses the team'smax_budgetas the ceiling in that case.Changes
litellm/constants.py-- renamedCLI_JWT_TOKEN_NAMEtoCLI_SESSION_KEY_PREFIX = "cli-session".litellm/proxy/auth/auth_checks.py-- rewroteget_cli_jwt_auth_tokento generate a uniquetoken = cli-session-{uuid}per login, setkey_alias = cli-session-{user_id}for log grouping, omitmax_budget, and setis_session_token=True.litellm/proxy/_types.py-- addedis_session_token: bool = FalsetoUserAPIKeyAuth. Serialized into the encrypted CLI token blob; defaults toFalsefor all DB-backed virtual keys.litellm/proxy/auth/user_api_key_auth.py-- replacedif get_secret_bool("EXPERIMENTAL_UI_LOGIN")withif not api_key.startswith("sk-"). Realsk-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 setEXPERIMENTAL_UI_LOGIN=falseretain their opt-out.litellm/proxy/management_endpoints/key_management_endpoints.py-- updated the delegation ceiling check to computedelegation_ceilingfromteam_table.max_budgetwhenis_session_token=Trueand the token carriesmax_budget=None, preventing unbounded key delegation from CLI sessions.tests/otel_tests/test_e2e_budgeting.py-- addedtest_team_budget_enforcement_cli_sso_tokenwhich 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 addedtest_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 withoutEXPERIMENTAL_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, noEXPERIMENTAL_UI_LOGINneeded).Test plan
Run unit tests:
Live proxy proof (proxy running on localhost:4000 with a team that has a $0.02 budget):
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 loginnow issues a uniquecli-session-{uuid}credential per session (stablecli-session-{user_id}alias for logs) instead of a sharedcli-jwt-tokenidentity, and drops the defaultmax_ui_session_budgetcap 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 explicitEXPERIMENTAL_UI_LOGIN=falsedisables that.UserAPIKeyAuthgainsis_session_tokenso key generation treats CLI sessions as bounded by teammax_budgetfor delegation (fixesNonebeing read as unlimited authority) and blocks personal keys with an explicit budget unlessteam_idis set.CLI SSO poll:
/sso/cli/pollloads user/team budgets and only appliesmax_ui_session_budgetwhen both lack a budget; otherwisemax_budgeton the minted token staysNone.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.