Skip to content

refactor(auth): derive temp budget increase without mutating the token - #34121

Merged
ryan-crabbe-berri merged 3 commits into
litellm_internal_stagingfrom
litellm_temp_budget_purity_dtz
Jul 21, 2026
Merged

ryan-crabbe-berri merged 3 commits into
litellm_internal_stagingfrom
litellm_temp_budget_purity_dtz

Conversation

@ryan-crabbe-berri

@ryan-crabbe-berri ryan-crabbe-berri commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Relevant issues

Follow-up hardening of #33841 (issue #25760)

Linear ticket

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • My PR passes all CI/CD checks (e.g., lint, format, unit tests)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have received a Greptile Confidence Score of at least 4/5 before requesting a maintainer review (Greptile reviews automatically once the PR is opened; only comment @greptileai to re-request a review after pushing changes)

Delays in PR merge?

If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).

Screenshots / Proof of Fix

Run live at commit 1b456994de against a local proxy from this branch (Postgres-backed, dev_config.yaml). The budget gate decision this PR touches happens at auth time, before any provider call, so the proof drives it directly: a key is given spend far over its max_budget via /key/update, then requests are sent while varying temp_budget_increase. A 429 naming "Budget has been exceeded" means the gate blocked; any other error (this environment has no provider key wired) means the request cleared the gate

MASTER=sk-1234; BASE=http://localhost:4000

KEY=$(curl -s -X POST $BASE/key/generate -H "Authorization: Bearer $MASTER" \
  -H "Content-Type: application/json" \
  -d '{"max_budget": 0.0001, "models": ["anthropic-haiku-4-5"]}' \
  | python3 -c "import sys,json;print(json.load(sys.stdin)['key'])")

curl -s -X POST $BASE/key/update -H "Authorization: Bearer $MASTER" \
  -H "Content-Type: application/json" -d "{\"key\": \"$KEY\", \"spend\": 0.05}"

# phase 1: no temp increase, spend 0.05 > max_budget 0.0001 -> expect block
# phase 2: temp_budget_increase 100 (effective 100.0001) -> expect gate pass
# phase 3: temp_budget_increase 0.01 (effective 0.0101 < spend) -> expect block at exactly 0.0101 on every repeat

Output:

--- phase 1: spend 0.05 > max_budget 0.0001, no temp increase ---
Request 1: HTTP 429 Budget has been exceeded! Current cost: 0.05, Max budget: 0.0001
Request 2: HTTP 429 Budget has been exceeded! Current cost: 0.05, Max budget: 0.0001
Request 3: HTTP 429 Budget has been exceeded! Current cost: 0.05, Max budget: 0.0001

--- phase 2: temp_budget_increase 100 (effective 100.0001 > spend 0.05) ---
Request 1: PASSED budget gate
Request 2: PASSED budget gate
Request 3: PASSED budget gate

--- phase 3: temp_budget_increase 0.01 (effective 0.0101 < spend 0.05) ---
Request 1: blocked, effective max budget = 0.0101
Request 2: blocked, effective max budget = 0.0101
Request 3: blocked, effective max budget = 0.0101
Request 4: blocked, effective max budget = 0.0101
Request 5: blocked, effective max budget = 0.0101

key/info after all phases: spend = 0.05 | max_budget = 0.0001 | metadata = {'temp_budget_expiry': '2027-01-01T00:00:00', 'temp_budget_increase': 0.01}

Phase 3 is the purity proof: five consecutive cache-hit requests all report the effective budget as exactly 0.0101. Under a compounding bug (mutated token leaking back into the cache) that number would grow by 0.01 per request. key/info confirms the stored max_budget is still the original 0.0001 after everything

Type

🧹 Refactoring

Changes

_update_key_budget_with_temp_budget_increase mutated valid_token.max_budget in place. That is only safe because every auth resolution path happens to hand it a fresh copy of the cached token (cache reads return model_copy(), _cache_key_object copies before storing). If any future change re-caches a live token or drops one of those copies, the increase would compound into shared state by +increase per request. The helper now returns model_copy(update={"max_budget": ...}) instead, so no caller can leak an increased budget anywhere, regardless of what the cache does

The regression test from #33841 is extended to pin this as an observable invariant: resolving the same cached key twice must yield the effective budget (102.0) both times, and the cached object must still hold the original 2.0 afterwards. Adversarial mutation-testing during review showed that alone was not enough; reverting the helper to in-place mutation still passed because the cache's copy-on-read layer masks it, so the direct unit test in test_proxy_utils.py now also asserts the input object is left unmutated and the result is a distinct object

While in the file, the three remaining DTZ005 naive datetime.now() calls are fixed (auth span start, builder start_time, service-log end_time); all their consumers either convert to epoch via .timestamp() or subtract same-pair datetimes, so switching to datetime.now(timezone.utc) is behavior-preserving. The DTZ005 strict-budget ceiling ratchets 244 -> 241

Note for reviewers: make pre-commit currently fails on staging in lint-e2e-basedpyright because tests/e2e/llm_translation/test_messages_mid_conversation_system_native_providers_e2e.py references a gateway attribute that EndpointsClient does not have (introduced in 23b5b7d); that is unrelated to this diff and tracked separately

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

…th datetimes

_update_key_budget_with_temp_budget_increase mutated max_budget in place, so correctness depended on every resolution path handing it a fresh copy of the cached token; one future re-cache of a live token would compound the bump per request. Return a model_copy instead so no caller can leak an increased budget into shared state.

Also fixes the three remaining DTZ005 naive datetime.now() calls in user_api_key_auth.py (auth span start, builder start_time, service-log end_time; all consumers convert to epoch or subtract same-pair datetimes) and ratchets the DTZ005 strict budget 244 -> 241.
@greptile-apps

greptile-apps Bot commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR prevents temporary budget increases from mutating cached authentication tokens. The main changes are:

  • Derives the effective budget on a copied token
  • Tests repeated cache hits and input immutability
  • Uses UTC-aware timestamps in authentication timing paths
  • Updates the strict lint budget

Confidence Score: 5/5

This looks safe to merge.

  • The temporary increase is applied to a copied token while the cached budget remains unchanged.
  • The updated tests cover direct input mutation and repeated cache-hit behavior.
  • No blocking issue remains in the changed authentication path.

Important Files Changed

Filename Overview
litellm/proxy/auth/user_api_key_auth.py Derives temporary budget increases without mutating the input token and uses UTC-aware authentication timestamps.
tests/proxy_unit_tests/test_proxy_utils.py Verifies that budget derivation returns a distinct object and preserves the input budget.
tests/test_litellm/proxy/auth/test_user_api_key_auth.py Verifies repeated cache-hit authentication does not compound or persist the temporary increase.
ruff-strict-budget.json Updates the strict lint budget after replacing three naive datetime calls.

Reviews (2): Last reviewed commit: "test: pin non-mutation of the temp budge..." | Re-trigger Greptile

@codecov

codecov Bot commented Jul 21, 2026 •

Copy link
Copy Markdown

Codecov Report

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

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

📢 Thoughts on this report? Let us know!

Adversarial mutation-testing showed reverting the helper to in-place mutation still passed every test: the cache's copy-on-read layer masks the mutation in the integration test and the direct unit test only inspected the return value. Assert the input object is left untouched and the result is a distinct object so the purity guarantee itself is load-bearing.
@ryan-crabbe-berri
ryan-crabbe-berri force-pushed the litellm_temp_budget_purity_dtz branch from 1f27f05 to f219ffe Compare July 21, 2026 18:41
@ryan-crabbe-berri

Copy link
Copy Markdown
Contributor Author

@greptileai re review

@codspeed

codspeed Bot commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_temp_budget_purity_dtz (a076c65) with litellm_internal_staging (212a921)1

Open in CodSpeed

Footnotes

  1. No successful run was found on litellm_internal_staging (d2819ba) during the generation of this report, so 212a921 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

@ryan-crabbe-berri
ryan-crabbe-berri enabled auto-merge (squash) July 21, 2026 20:50
@ryan-crabbe-berri
ryan-crabbe-berri merged commit 76c9eca into litellm_internal_staging Jul 21, 2026
77 of 78 checks passed
@ryan-crabbe-berri
ryan-crabbe-berri deleted the litellm_temp_budget_purity_dtz branch July 21, 2026 21:02
yuneng-berri pushed a commit that referenced this pull request Jul 26, 2026
#34121)

* refactor(auth): derive temp budget bump without mutation, tz-aware auth datetimes

_update_key_budget_with_temp_budget_increase mutated max_budget in place, so correctness depended on every resolution path handing it a fresh copy of the cached token; one future re-cache of a live token would compound the bump per request. Return a model_copy instead so no caller can leak an increased budget into shared state.

Also fixes the three remaining DTZ005 naive datetime.now() calls in user_api_key_auth.py (auth span start, builder start_time, service-log end_time; all consumers convert to epoch or subtract same-pair datetimes) and ratchets the DTZ005 strict budget 244 -> 241.

* test: pin non-mutation of the temp budget helper input

Adversarial mutation-testing showed reverting the helper to in-place mutation still passed every test: the cache's copy-on-read layer masks the mutation in the integration test and the direct unit test only inspected the return value. Assert the input object is left untouched and the result is a distinct object so the purity guarantee itself is load-bearing.

(cherry picked from commit 76c9eca)
yuneng-berri added a commit that referenced this pull request Jul 28, 2026
…x-d8c02a

chore(release): backport #33565, #33840, #33841, #34121, #33261, #34325 and #34577 to stable/1.93.x and cut 1.93.1
ap-anton-r-susilo pushed a commit to ap-anton-r-susilo/litellm that referenced this pull request Jul 29, 2026
BerriAI#34121)

* refactor(auth): derive temp budget bump without mutation, tz-aware auth datetimes

_update_key_budget_with_temp_budget_increase mutated max_budget in place, so correctness depended on every resolution path handing it a fresh copy of the cached token; one future re-cache of a live token would compound the bump per request. Return a model_copy instead so no caller can leak an increased budget into shared state.

Also fixes the three remaining DTZ005 naive datetime.now() calls in user_api_key_auth.py (auth span start, builder start_time, service-log end_time; all consumers convert to epoch or subtract same-pair datetimes) and ratchets the DTZ005 strict budget 244 -> 241.

* test: pin non-mutation of the temp budget helper input

Adversarial mutation-testing showed reverting the helper to in-place mutation still passed every test: the cache's copy-on-read layer masks the mutation in the integration test and the direct unit test only inspected the return value. Assert the input object is left untouched and the result is a distinct object so the purity guarantee itself is load-bearing.

(cherry picked from commit 76c9eca)
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.

2 participants