Skip to content

feat(db): route jwt provisioning writes through rust repositories - #52756

Merged
yujonglee-berri merged 2 commits into
mainfrom
litellm_jwt_provisioning_repository_writes
Nov 20, 2026
Merged

yujonglee-berri merged 2 commits into
mainfrom
litellm_jwt_provisioning_repository_writes

Conversation

@yujonglee-berri

@yujonglee-berri yujonglee-berri commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Handwritten 1-3 sentence description

  • Moves four single-statement writes from Prisma to sqlx
    • set a user's role
    • create the user on first JWT sign-in
    • insert a JWT key mapping
    • stamp a managed agent's last authentication
  • Transactions
    • none needed, each write is one statement
    • inserts that can race use ON CONFLICT DO NOTHING, then read the winner in a second statement, because the insert cannot see a row committed after it started
  • Different from before
    • a first sign-in that loses the race gets the existing user back. It used to fail with a unique violation
    • default team adds run only for the request that created the user
    • the "email already taken" check is part of the insert. It used to be a separate read first
    • default_internal_user_params keeps the user columns Prisma stored, and metadata and model_max_budget can now be written as YAML mappings. A few keys are skipped on purpose (password, spend, model_spend, last_breach_check_at, budget_reset_at, and user_id, user_email, sso_user_id), and the sign-in logs a warning that names them
    • set_user_role caches the row the database returned, not a patched copy
    • timestamps are written as UTC explicitly, and the mapping id is generated in Rust since the column has no default
  • Still in Python: key minting and the orphan key delete
Details

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:

  • JWT provisioning still wrote users, key mappings and agent auth through Prisma
  • A native JWT auth host needs those writes in Rust
  • Two first sign-ins of one new user could race, and one failed

How it solves it:

  • Adds the four single-statement writes to litellm-repositories
  • Python now makes those four writes through the Rust repositories
  • The losing sign-in of a race gets the user that won
  • Team insert, member add and member remove come in a later PR

User 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)

  1. An admin enables JWT auth with user_id_upsert: true
  2. A user who has never called the proxy sends two requests at once, each with Authorization: Bearer <their JWT>, for example GET https://litellm-domain/v1/models
  3. Both find no user, both try to create it, and the slower one is refused with an authentication error

After: both requests succeed and the user exists once

  1. An admin enables JWT auth with user_id_upsert: true
  2. The same user sends the same two requests at once
  3. Both return 200, and the admin sees one user with the configured default role, budget and models

What 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>
    • Replaces LiteLLM_UserTable.update(...) in PythonAuthHost.set_user_role (litellm/proxy/auth/host/python.py)
    • One UPDATE ... RETURNING in the find_user shape, reported as update on LiteLLM_UserTable
  • UserRepository::insert(sign_in, defaults) -> Inserted<User>
    • Replaces _email_free_to_store plus LiteLLM_UserTable.create(...) in the user_id_upsert branch of get_user_object (litellm/proxy/auth/auth_checks.py)
    • Stores user_id, the email unless another user holds it and LITELLM_EMAIL_FALLBACK_LINKS_ANY_USER is off, the SSO id only while that flag is off, and NewUserDefaults
    • NewUserDefaults is what Python resolved from default_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, policies and model_max_budget
    • Reported as create on LiteLLM_UserTable
  • JwtKeyMappingRepository::insert(mapping) -> Inserted<String>
    • Replaces LiteLLM_JWTKeyMapping.create(...) and the winner read in create_key_mapping (litellm/proxy/auth/host/steps/jwt_auto_register.py)
    • Stores a random UUID id, jwt_issuer ("" for the issuer-agnostic scope), the claim, the hashed key, and written_by as both created_by and updated_by
    • Reported as auto_register_jwt_mapping on LiteLLM_JWTKeyMapping
    • Key minting and the orphan key delete stay in Python
  • AgentIdentityRepository::record_authentication(agent_id, revision) -> bool
    • Replaces update_many in AgentIdentityStore.record_authentication (litellm/proxy/agent_endpoints/identity_store.py)
    • Stamps last_authenticated_at on the active identity at that revision whose agent is enabled and identity managed
    • false is Python's "count is not 1" case
    • Reported as update_many on LiteLLM_AgentIdentity

How Python reaches them

  • python-bridge: RustUserRepository.set_role and .insert, RustJwtKeyMappingRepository.insert, and a new RustAgentIdentityRepository, with stubs in _native.pyi
  • litellm/repositories: UserRepository.set_role and .insert_for_auth, JWTKeyMappingRepository.insert, AgentIdentityRepository.record_authentication

Supporting changes in the crate

  • Inserted<T>: Created(T) or Conflict(Option<T>), shared by the two inserts
  • Connections moves from user/repository.rs to database.rs, and its one-transaction test double to test_support.rs, because the mapping insert needs it too
  • README.md gains the rules for writes

Deliberate differences from Python

  • A user insert that loses to a concurrent sign-in returns the row that won
    • Prisma did a plain create, so the loser got a unique violation and the request failed
    • The default team adds run only for the request that created the user
  • default_internal_user_params keeps the user columns Prisma stored, with a few left out on purpose
    • Stored: user_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, policies and model_max_budget
    • metadata and model_max_budget take a YAML mapping or JSON text. Prisma only took JSON text and refused the sign-in on a mapping
    • Skipped, with a warning that names each key: password (Prisma stored one shared plain-text password on every new user), spend, model_spend, last_breach_check_at, budget_reset_at, and user_id, user_email, sso_user_id, which Prisma let a default write over the identity of the person signing in
    • A key that is not a user column is skipped with the same warning. Prisma refused the sign-in
  • set_user_role caches the stored row
    • It cached a patched copy of the row the caller passed in, which it still does when the row is gone
  • The email check is part of the insert statement
    • It was a separate read before the create, so two sign-ins could both pass it
  • The mapping winner is read from the writer
    • It was read through the cache-first get_jwt_key_mapping_object
  • Timestamps are written as NOW() AT TIME ZONE 'UTC'
    • Prisma stamps UTC from its engine, and a bare CURRENT_TIMESTAMP follows the session time zone

Pre-Submission checklist

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

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. 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 more
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • Every automated review on my PR's latest commit has finished, and I have addressed or replied to each of its findings before requesting a maintainer review

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

Commit d0edd9dd4a removes only the new Ruff import rule. The proof below covers the same runtime code

The current tip 4fa5578a232 adds one change to the PR commit: the insert also stores the nine other default columns Prisma stored. That change was tested at 4e296b2c844, whose tree is identical to this tip, in the last case below. There the crate's database tests gave 136 passed, sqlx-prepare --check, clippy and fmt were clean, and test_auth_checks_object_access_and_lookup.py with the host, native database and repository suites gave 1409 passed. The other cases were not rerun at this tip

Tested at b83a4228118 against a live proxy with JWT auth on, a local JWKS, and a Postgres migrated with prisma migrate deploy. The current tip 326405e933c is that same change squashed to one commit and rebased onto main with no conflicts, minus one protocol class in auth_checks.py that 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 stored tpm_limit 1000, rpm_limit 60 and max_parallel_requests 4. 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 at 2f29a55a510 with no conflicts and an identical diff, which is the tip 4ac7e5845b5. 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 only

Shared setup: config, token script, proxy start

config.yaml (port 4117). config_role_sync.yaml (port 4119) is the same without the two virtual_key lines and with roles_jwt_field: roles in place of user_roles_jwt_field and user_allowed_roles

model_list:
  - model_name: proof-model
    litellm_params:
      model: openai/proof-model
      api_key: not-used

litellm_settings:
  default_internal_user_params:
    user_role: internal_user
    max_budget: 25
    budget_duration: 30d
    models: ["proof-model"]

general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY
  enable_jwt_auth: true
  litellm_jwtauth:
    user_id_jwt_field: sub
    user_email_jwt_field: email
    user_id_upsert: true
    user_roles_jwt_field: roles
    user_allowed_roles: ["gateway-users", "gateway-admins"]
    sync_user_role_and_teams: true
    jwt_litellm_role_map:
      - jwt_role: gateway-admins
        litellm_role: proxy_admin
      - jwt_role: gateway-users
        litellm_role: internal_user
    virtual_key_claim_field: sub
    unregistered_jwt_client_behavior: auto_register

mint.py writes an RSA key and jwks/jwks.json on first run, then prints an RS256 JWT with sub, email (<sub>@example.com) and roles: [<role>]

python mint.py alice gateway-users            # prints the JWT
python -m http.server 4118 --bind 127.0.0.1   # run inside jwks/

# env: DATABASE_URL, LITELLM_MASTER_KEY, LITELLM_LICENSE, JWT_PUBLIC_KEY_URL=http://127.0.0.1:4118/jwks.json
python litellm/proxy/proxy_cli.py --config config.yaml --port 4117 --detailed_debug
python litellm/proxy/proxy_cli.py --config config_role_sync.yaml --port 4119 --detailed_debug

After (b83a4228118, carried to 4ac7e5845b5)

A first sign-in creates the user and maps a key

  1. curl http://127.0.0.1:4117/v1/models -H "Authorization: Bearer $(python mint.py alice gateway-users)"
{"data":[{"id":"proof-model","object":"model","created":1677610602,"owned_by":"openai"}],"object":"list"}
HTTP 200
  1. SELECT ... FROM "LiteLLM_UserTable"
user_id         | alice
user_email      | alice@example.com
sso_user_id     | alice
user_role       | internal_user
max_budget      | 25
budget_duration | 30d
budget_reset_at | 2026-12-01 00:00:00
models          | {proof-model}
teams           | {}
spend           | 0
created_at      | 2026-11-19 04:03:45.432
updated_at      | 2026-11-19 04:03:45.432
  1. SELECT ... FROM "LiteLLM_JWTKeyMapping"
id              | 9b58fde3-3a16-4c96-a226-4c4530408059
jwt_issuer      |
jwt_claim_name  | sub
jwt_claim_value | alice
token_prefix    | bcfdd7a7a902
is_active       | t
created_by      | auto_register
updated_by      | auto_register
created_at      | 2026-11-19 04:03:45.445

Eight first sign-ins at once all succeed and leave one user, one mapping and one key

  1. Eight background curl http://127.0.0.1:4117/v1/models with one JWT for bob, status codes counted
   8 200
  1. Rows for bob, and the proxy log
 user_id |   user_role   | max_budget |    models
 bob     | internal_user |         25 | {proof-model}

 jwt_claim_value | mappings        user_id | keys
 alice           |        1        alice   |    1
 bob             |        1        bob     |    1

7x  jwt_auto_register.py:87 - JWT Key Mapping (auto_register): unique conflict on create, returning winner's mapping for sub='bob'.

Seven requests lost the mapping insert, deleted the key they had minted and used the winner's

A changed role in the token is stored

  1. curl http://127.0.0.1:4119/v1/models with a JWT for erin and gateway-users
gateway-users: HTTP 200
 user_id |   user_role   |       created_at        |       updated_at
 erin    | internal_user | 2026-11-19 04:05:12.382 | 2026-11-19 04:05:12.382
  1. The same call with gateway-admins
gateway-admins: HTTP 200
 user_id |  user_role  |       created_at        |       updated_at
 erin    | proxy_admin | 2026-11-19 04:05:12.382 | 2026-11-19 04:05:12.553

Both proxies logged no traceback, and lsof showed each had this branch's _native.abi3.so loaded

Defaults beyond the first eight are stored (4e296b2c844)

default_internal_user_params as in the shared config, plus user_alias: Default Alias, organization_id: org-proof (an organization that exists), metadata and model_max_budget as YAML mappings, spend: 1.5 and password: shared-secret

  1. curl http://127.0.0.1:4327/v1/models -H "Authorization: Bearer $(python mint.py gabe gateway-users)"
{"data":[{"id":"proof-model","object":"model","created":1677610602,"owned_by":"openai"}],"object":"list"}
HTTP 200
  1. SELECT ... FROM "LiteLLM_UserTable" WHERE user_id = 'gabe', and the proxy log
user_id                 | gabe
user_alias              | Default Alias
organization_id         | org-proof
metadata                | {"source": "jwt"}
model_max_budget        | {"proof-model": 5.0}
allowed_cache_controls  | {}
policies                | {}
password_unset          | t
spend                   | 0
user_role               | internal_user
max_budget              | 25
models                  | {proof-model}
tpm_limit               | 1000

WARNING: auth_checks.py:3124 - default_internal_user_params keys not stored on a user created at sign-in: password, spend

With team_id, password_reset_required, allowed_cache_controls, policies and 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 column

Tests and checks

$ DATABASE_URL=postgresql://... cargo test -p litellm-repositories --locked -- --include-ignored
test result: ok. 130 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.38s

$ cargo run -p litellm-db-testing --bin sqlx-prepare -- --check
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 7.76s

$ cargo clippy -p litellm-repositories -p litellm-python-bridge --all-targets --locked -- -D warnings
$ cargo fmt -p litellm-repositories -p litellm-python-bridge -- --check

$ pytest tests/unit/proxy/auth tests/unit/proxy/agent_endpoints tests/unit/proxy/management_endpoints/test_ui_sso.py tests/unit/proxy/management_endpoints/test_jwt_key_mapping.py tests/unit/proxy/mcp_server/test_discoverable_endpoints.py tests/unit/proxy/db/test_native_database.py tests/unit/rust_bridge tests/unit/repositories -n 8
4 failed, 9501 passed

The 4 failures are tests/unit/rust_bridge/host/routes/test_messages.py cases that compare Linux resolver and errno text, and they fail the same way on macOS without this change

21 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 WHERE condition of record_authentication, the user_id filter of set_role, the email ownership check and its parts, updated_by, each UTC stamp swapped for CURRENT_TIMESTAMP, the SSO id filter, the conflict read, the issuer default, the generated id, Created swapped for Conflict, and the rows_affected comparison

Type

New Feature

Caveats (if any)

Medium

  • record_authentication has no live proof
    • It needs a Microsoft Entra managed agent token
  • A few default_internal_user_params keys Prisma stored are skipped on purpose
    • password, spend, model_spend, last_breach_check_at, budget_reset_at, and the identity keys. The sign-in logs a warning naming each one
  • object_permission_id as a default was not exercised live
    • It has a database test. A permission that does not exist is a foreign key error, as it was with Prisma
  • The Before step of the user flow is read from the code, not reproduced on main

Low

  • Cargo.lock gains two edges: litellm-repositories now depends on uuid and jiff, both already in the workspace
    • Prisma generates the mapping id in its engine and the column has no database default
  • Assumed, not tested against Prisma: an omitted models is stored as NULL
    • Both readers return [] for it either way
  • The default team memberships still go through the team_member_add endpoint
    • The Rust member add is not in this PR

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

Devin Review

@codecov

codecov Bot commented Nov 19, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@yujonglee-berri yujonglee-berri changed the title feat(db): rust repository writes for jwt user provisioning, key mappings and agent auth feat(db): route jwt provisioning writes through rust repositories Nov 19, 2026
@yujonglee-berri
yujonglee-berri force-pushed the litellm_jwt_provisioning_repository_writes branch from b83a422 to 2b0c526 Compare November 19, 2026 04:33
@yujonglee-berri
yujonglee-berri force-pushed the litellm_jwt_provisioning_repository_writes branch 3 times, most recently from 95d031a to 326405e Compare November 19, 2026 06:45
@yujonglee-berri
yujonglee-berri removed this pull request from stack #52767 November 19, 2026 10:40
@yujonglee-berri
yujonglee-berri force-pushed the litellm_jwt_provisioning_repository_writes branch from 326405e to 4ac7e58 Compare November 19, 2026 10:42
@yujonglee-berri
yujonglee-berri removed this pull request from stack #52832 November 19, 2026 11:19
@yujonglee-berri
yujonglee-berri force-pushed the litellm_jwt_provisioning_repository_writes branch from 4ac7e58 to c0ad5f1 Compare November 20, 2026 04:22

@devin-ai-integration devin-ai-integration 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.

Approved. I reviewed the JWT provisioning writes and the handling of concurrent inserts for users and key mappings.

@yujonglee-berri
yujonglee-berri marked this pull request as ready for review November 20, 2026 04:40
@yujonglee-berri
yujonglee-berri requested a review from a team November 20, 2026 04:40
@veria-ai

veria-ai Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

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

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

Reviews

@yujonglee-berri yujonglee-berri added the autoapprove This PR may be autoapproved by greptile. The author thinks that it does not need human review. label Nov 20, 2026
@CLAassistant

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.
1 out of 2 committers have signed the CLA.

✅ yujonglee-berri
❌ devin-ai-integration[bot]
You have signed the CLA already but the status is still pending? Let us recheck it.

@devin-ai-integration devin-ai-integration 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.

Devin Review found 2 potential issues.

1 flag not posted on this PR by your GitHub settings — view it in Devin Review. (Configure)

Devin Review

Comment on lines +61 to +69
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

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.

🟡 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.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment on lines +61 to +69
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

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.

🟥 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.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment thread litellm/repositories/user_repository.py Resolved
@yujonglee-berri
yujonglee-berri force-pushed the litellm_jwt_provisioning_repository_writes branch from d0edd9d to 0d6ea7a Compare November 20, 2026 04:48
yujonglee-berri and others added 2 commits November 20, 2026 14:18
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.
@yujonglee-berri
yujonglee-berri force-pushed the litellm_jwt_provisioning_repository_writes branch from 0d6ea7a to 4fa5578 Compare November 20, 2026 05:21
@yujonglee-berri
yujonglee-berri merged commit ed6f998 into main Nov 20, 2026
66 of 67 checks passed
@yujonglee-berri
yujonglee-berri deleted the litellm_jwt_provisioning_repository_writes branch November 20, 2026 05:53
yuneng-berri added a commit that referenced this pull request Nov 20, 2026
…#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.
@mateo-berri

Copy link
Copy Markdown
Contributor

The python-bridge marshal_boundary test fails on main since this PR, because db_repository/user.rs calls serde_json::from_str outside litellm-host-python

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

autoapprove This PR may be autoapproved by greptile. The author thinks that it does not need human review.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants