Repository navigation
feat(db): route jwt provisioning writes through rust repositories - #52756
Conversation
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
b83a422 to
2b0c526
Compare
95d031a to
326405e
Compare
326405e to
4ac7e58
Compare
4ac7e58 to
c0ad5f1
Compare
|
|
There was a problem hiding this comment.
Devin Review found 2 potential issues.
1 flag not posted on this PR by your GitHub settings — view it in Devin Review. (Configure)
| model_config = ConfigDict(frozen=True, extra="ignore") | ||
|
|
||
| user_role: str | None = None | ||
| max_budget: float | None = None | ||
| budget_duration: str | None = None | ||
| models: tuple[str, ...] | None = None | ||
| tpm_limit: int | None = None | ||
| rpm_limit: int | None = None | ||
| max_parallel_requests: int | None = None |
There was a problem hiding this comment.
🟡 Missing breaking-change notice for JWT defaults
NewUserDefaults drops previously stored user_alias defaults. The PR lacks the ! title marker and migration sentence required for removed configuration behavior.
Learn more
The repository's breaking-change rule requires both a conventional-commit title containing ! and a handwritten sentence beginning Breaking change: that identifies affected operators and their migration. Before this change, get_user_object passed every scalar default except team-selection fields into Prisma creation. The new allowlist omits valid user columns such as user_alias, so an existing configuration no longer produces the same user records. A caveat listing omitted keys does not satisfy the required migration notice.
Example: A deployment sets default_internal_user_params.user_alias to new hire. Newly provisioned JWT users previously stored that alias and now receive no alias.
Recommended fix: Either preserve these supported defaults or mark the PR title as breaking and add the required migration sentence. Explain which fields stop applying and that operators relying on them must explicitly provision or update those user fields.
Was this helpful? React with 👍 or 👎 to provide feedback.
| model_config = ConfigDict(frozen=True, extra="ignore") | ||
|
|
||
| user_role: str | None = None | ||
| max_budget: float | None = None | ||
| budget_duration: str | None = None | ||
| models: tuple[str, ...] | None = None | ||
| tpm_limit: int | None = None | ||
| rpm_limit: int | None = None | ||
| max_parallel_requests: int | None = None |
There was a problem hiding this comment.
🟥 JWT provisioning drops MCP access ceilings
When JWT defaults specify object_permission_id, NewUserDefaults drops the MCP entitlement. _apply_user_server_ceiling treats missing entitlements as unrestricted, permitting broader key or team grants.
Was this helpful? React with 👍 or 👎 to provide feedback.
d0edd9d to
0d6ea7a
Compare
Add the single-statement writes native JWT provisioning needs to litellm-repositories and route Python through them: UserRepository::set_role and ::insert, JwtKeyMappingRepository::insert and AgentIdentityRepository::record_authentication replace the Prisma calls behind PythonAuthHost.set_user_role, the user_id_upsert create in get_user_object, the mapping insert in create_key_mapping and AgentIdentityStore.record_authentication. Each write runs on the writer through Database::run under the call type Prisma reports, returns the stored row in its read's shape, and stamps timestamps in UTC. A sign-in that loses the user insert to a concurrent one now gets the user that won and skips the default team adds, where the Prisma create raised a unique violation.
0d6ea7a to
4fa5578
Compare
…#53144) The concurrent first-call test paused the mapping insert by matching Prisma's INSERT INTO "public"."LiteLLM_JWTKeyMapping". Since #52756 the insert goes through the Rust repository as INSERT INTO "LiteLLM_JWTKeyMapping", so the relay never held it and both parametrizations failed on every integration run.
|
The python-bridge |
Handwritten 1-3 sentence description
ON CONFLICT DO NOTHING, then read the winner in a second statement, because the insert cannot see a row committed after it starteddefault_internal_user_paramskeeps the user columns Prisma stored, andmetadataandmodel_max_budgetcan now be written as YAML mappings. A few keys are skipped on purpose (password,spend,model_spend,last_breach_check_at,budget_reset_at, anduser_id,user_email,sso_user_id), and the sign-in logs a warning that names themset_user_rolecaches the row the database returned, not a patched copyDetails
Link to Devin session: https://app.devin.ai/sessions/2a69cb9789064f55a311d4e301fcc855
Open in Devin Desktop: https://app.devin.ai/desktop/session/2a69cb9789064f55a311d4e301fcc855?variant=devin
Requested by: @yujonglee-berri
TLDR
Problem this solves:
How it solves it:
litellm-repositoriesUser Flow
Before: a new JWT user whose first two requests arrive together can have one of them refused (read from the code, not reproduced on main)
user_id_upsert: trueAuthorization: Bearer <their JWT>, for example GET https://litellm-domain/v1/modelsAfter: both requests succeed and the user exists once
user_id_upsert: trueWhat is added
All four run on the writer, reported under the call type and table Prisma reported for the same write
UserRepository::set_role(user_id, user_role) -> Option<User>LiteLLM_UserTable.update(...)inPythonAuthHost.set_user_role(litellm/proxy/auth/host/python.py)UPDATE ... RETURNINGin thefind_usershape, reported asupdateonLiteLLM_UserTableUserRepository::insert(sign_in, defaults) -> Inserted<User>_email_free_to_storeplusLiteLLM_UserTable.create(...)in theuser_id_upsertbranch ofget_user_object(litellm/proxy/auth/auth_checks.py)user_id, the email unless another user holds it andLITELLM_EMAIL_FALLBACK_LINKS_ANY_USERis off, the SSO id only while that flag is off, andNewUserDefaultsNewUserDefaultsis what Python resolved fromdefault_internal_user_params:user_role,max_budget,budget_duration,budget_reset_at,models,budget_limits,tpm_limit,rpm_limit,max_parallel_requests, and the other user columns Prisma stored from it:user_alias,team_id,organization_id,object_permission_id,password_reset_required,metadata,allowed_cache_controls,policiesandmodel_max_budgetcreateonLiteLLM_UserTableJwtKeyMappingRepository::insert(mapping) -> Inserted<String>LiteLLM_JWTKeyMapping.create(...)and the winner read increate_key_mapping(litellm/proxy/auth/host/steps/jwt_auto_register.py)id,jwt_issuer(""for the issuer-agnostic scope), the claim, the hashed key, andwritten_byas bothcreated_byandupdated_byauto_register_jwt_mappingonLiteLLM_JWTKeyMappingAgentIdentityRepository::record_authentication(agent_id, revision) -> boolupdate_manyinAgentIdentityStore.record_authentication(litellm/proxy/agent_endpoints/identity_store.py)last_authenticated_aton the active identity at that revision whose agent is enabled and identity managedfalseis Python's "count is not 1" caseupdate_manyonLiteLLM_AgentIdentityHow Python reaches them
python-bridge:RustUserRepository.set_roleand.insert,RustJwtKeyMappingRepository.insert, and a newRustAgentIdentityRepository, with stubs in_native.pyilitellm/repositories:UserRepository.set_roleand.insert_for_auth,JWTKeyMappingRepository.insert,AgentIdentityRepository.record_authenticationSupporting changes in the crate
Inserted<T>:Created(T)orConflict(Option<T>), shared by the two insertsConnectionsmoves fromuser/repository.rstodatabase.rs, and its one-transaction test double totest_support.rs, because the mapping insert needs it tooREADME.mdgains the rules for writesDeliberate differences from Python
create, so the loser got a unique violation and the request faileddefault_internal_user_paramskeeps the user columns Prisma stored, with a few left out on purposeuser_role,max_budget,budget_duration,models,budget_limits,tpm_limit,rpm_limit,max_parallel_requests,user_alias,team_id,organization_id,object_permission_id,password_reset_required,metadata,allowed_cache_controls,policiesandmodel_max_budgetmetadataandmodel_max_budgettake a YAML mapping or JSON text. Prisma only took JSON text and refused the sign-in on a mappingpassword(Prisma stored one shared plain-text password on every new user),spend,model_spend,last_breach_check_at,budget_reset_at, anduser_id,user_email,sso_user_id, which Prisma let a default write over the identity of the person signing inset_user_rolecaches the stored rowget_jwt_key_mapping_objectNOW() AT TIME ZONE 'UTC'CURRENT_TIMESTAMPfollows the session time zonePre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
uv run pytest tests/unit/<your_test_file>.py -v. Leave the suites (make test-unit-*,make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or moreDelays 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
Commit
d0edd9dd4aremoves only the new Ruff import rule. The proof below covers the same runtime codeThe current tip
4fa5578a232adds one change to the PR commit: the insert also stores the nine other default columns Prisma stored. That change was tested at4e296b2c844, whose tree is identical to this tip, in the last case below. There the crate's database tests gave136 passed,sqlx-prepare --check, clippy and fmt were clean, andtest_auth_checks_object_access_and_lookup.pywith the host, native database and repository suites gave1409 passed. The other cases were not rerun at this tipTested at
b83a4228118against a live proxy with JWT auth on, a local JWKS, and a Postgres migrated withprisma migrate deploy. The current tip326405e933cis that same change squashed to one commit and rebased onto main with no conflicts, minus one protocol class inauth_checks.pythat the port left unused, plus the three limit columns and the warning for skipped keys. At this tip the 130 database tests pass, and an insert through the Rust repository against Postgres storedtpm_limit1000,rpm_limit60 andmax_parallel_requests4. The crate's database tests and the Python suites below were rerun on top of it, as part of #52766 and #52779. It was then rebased onto main at2f29a55a510with no conflicts and an identical diff, which is the tip4ac7e5845b5. Three of the four writes are shown. Recording a managed agent's authentication needs a Microsoft Entra agent token, so it has unit and database tests onlyShared setup: config, token script, proxy start
config.yaml(port 4117).config_role_sync.yaml(port 4119) is the same without the twovirtual_keylines and withroles_jwt_field: rolesin place ofuser_roles_jwt_fieldanduser_allowed_rolesmint.pywrites an RSA key andjwks/jwks.jsonon first run, then prints an RS256 JWT withsub,email(<sub>@example.com) androles: [<role>]After (
b83a4228118, carried to4ac7e5845b5)A first sign-in creates the user and maps a key
curl http://127.0.0.1:4117/v1/models -H "Authorization: Bearer $(python mint.py alice gateway-users)"SELECT ... FROM "LiteLLM_UserTable"SELECT ... FROM "LiteLLM_JWTKeyMapping"Eight first sign-ins at once all succeed and leave one user, one mapping and one key
curl http://127.0.0.1:4117/v1/modelswith one JWT forbob, status codes countedbob, and the proxy logSeven requests lost the mapping insert, deleted the key they had minted and used the winner's
A changed role in the token is stored
curl http://127.0.0.1:4119/v1/modelswith a JWT forerinandgateway-usersgateway-adminsBoth proxies logged no traceback, and
lsofshowed each had this branch's_native.abi3.soloadedDefaults beyond the first eight are stored (
4e296b2c844)default_internal_user_paramsas in the shared config, plususer_alias: Default Alias,organization_id: org-proof(an organization that exists),metadataandmodel_max_budgetas YAML mappings,spend: 1.5andpassword: shared-secretcurl http://127.0.0.1:4327/v1/models -H "Authorization: Bearer $(python mint.py gabe gateway-users)"SELECT ... FROM "LiteLLM_UserTable" WHERE user_id = 'gabe', and the proxy logWith
team_id,password_reset_required,allowed_cache_controls,policiesand the two JSON keys as JSON text added, the stored row was identical to the one main (d3d649dac4d) stores for the same sign-in, and no warning was logged. Main refuses the sign-in above with a 401, because Prisma does not take a mapping for a JSON columnTests and checks
The 4 failures are
tests/unit/rust_bridge/host/routes/test_messages.pycases that compare Linux resolver and errno text, and they fail the same way on macOS without this change21 of the 130 Rust tests are new. Each first failed against a stub. I then broke the code by hand in 24 places, one at a time, and each break failed at least one test: every
WHEREcondition ofrecord_authentication, theuser_idfilter ofset_role, the email ownership check and its parts,updated_by, each UTC stamp swapped forCURRENT_TIMESTAMP, the SSO id filter, the conflict read, the issuer default, the generated id,Createdswapped forConflict, and therows_affectedcomparisonType
New Feature
Caveats (if any)
Medium
record_authenticationhas no live proofdefault_internal_user_paramskeys Prisma stored are skipped on purposepassword,spend,model_spend,last_breach_check_at,budget_reset_at, and the identity keys. The sign-in logs a warning naming each oneobject_permission_idas a default was not exercised liveLow
Cargo.lockgains two edges:litellm-repositoriesnow depends onuuidandjiff, both already in the workspaceidin its engine and the column has no database defaultmodelsis stored asNULL[]for it either wayteam_member_addendpointFinal Attestation