Skip to content

fix(proxy): reject team-scoped object_permission on personal keys for non-admins - #31471

Merged
yuneng-berri merged 4 commits into
litellm_internal_stagingfrom
litellm_veria_218_personal_key_metadata
Jun 30, 2026
Merged

yuneng-berri merged 4 commits into
litellm_internal_stagingfrom
litellm_veria_218_personal_key_metadata

Conversation

@yucheng-berri

@yucheng-berri yucheng-berri commented Jun 26, 2026 •

Copy link
Copy Markdown
Contributor

Relevant issues

Linear ticket

Resolves LIT-4069

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 requested a Greptile review by commenting @greptileai and received a Confidence Score of at least 4/5 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

Live proxy on localhost:4000, Postgres backed, with a non-admin internal_user "alice".

Before the fix, Alice could call /key/generate without a team_id and stuff arbitrary team-private resource IDs into her own key; the server accepted them and the runtime auth check at use-time then trusted the IDs because they were "on the key".

$ ALICE_KEY=sk-...alice's-personal-key...

$ for body in \
    '{"access_group_ids":["acme_private_models"]}' \
    '{"object_permission":{"mcp_toolsets":["acme_private_toolset"]}}' \
    '{"object_permission":{"vector_stores":["acme_private_vs"]}}' \
    '{"object_permission":{"search_tools":["acme_private_search"]}}'
  do
    curl -sS -w "\nHTTP_RC:%{http_code}\n" -X POST http://localhost:4000/key/generate \
      -H "Authorization: Bearer $ALICE_KEY" \
      -H "Content-Type: application/json" \
      -d "$body"
  done

Before the fix, all four returned 200 OK and persisted the IDs onto Alice's new personal key. After the fix, all four return 403:

field requested by Alice                          status   response
------------------------------------------------  ------   ------------------------------------------------------
access_group_ids:["acme_private_models"]          403      "Access groups cannot be assigned to personal keys
                                                            by non-admin callers."
object_permission.mcp_toolsets:["acme_..."]       403      "MCP toolsets cannot be assigned to personal keys
                                                            by non-admin callers."
object_permission.vector_stores:["acme_..."]      403      "Vector stores cannot be assigned to personal keys
                                                            by non-admin callers."
object_permission.search_tools:["acme_..."]       403      "search_tools cannot be assigned to personal keys
                                                            by non-admin callers."

Legitimate paths still work:

# proxy admin can still assign all four to a teamless key
$ curl -sS -X POST http://localhost:4000/key/generate -H "Authorization: Bearer sk-1234" \
    -H "Content-Type: application/json" \
    -d '{"object_permission":{"vector_stores":["acme_private_vs"],"mcp_toolsets":["acme_private_toolset"]},"access_group_ids":["acme_private_models"]}'
HTTP 200

# team-scoped keys are unaffected
$ curl -sS -X POST http://localhost:4000/key/generate -H "Authorization: Bearer sk-1234" \
    -H "Content-Type: application/json" \
    -d '{"team_id":"<acme>","object_permission":{"vector_stores":["acme_private_vs"]}}'
HTTP 200

# /key/update attack vector also blocked
$ curl -sS -X POST http://localhost:4000/key/update -H "Authorization: Bearer $ALICE_KEY" \
    -H "Content-Type: application/json" \
    -d '{"key":"<Alice personal key>","object_permission":{"vector_stores":["acme_private_vs"]}}'
HTTP 403

Type

🐛 Bug Fix

Changes

The security invariant enforced here is: a key with no team_id must not retain team-scoped grants.

This PR closes the create/update path: non-admin callers can no longer create or update a personal key with team-private grants in access_group_ids, object_permission.mcp_toolsets, object_permission.vector_stores, or object_permission.search_tools. The fix adds the personal-key gate that mirrors the team-key gate already in _team_key_generation_check, wires the four validators into _personal_key_generation_check, _validate_update_key_data, and regenerate_key_fn, and routes the validators through a typed ObjectPermissionDict so the dict shape is no longer a bare dict.

A separate path of the same invariant; clearing team_id from an existing team key while team-scoped grants remain on the row; is not closed in this PR. It is a follow-up; the work would either land its own helper or take the stricter alternative of making team_id admin-only for all non-admin updates, which would be a broader product behavior change I did not want to bundle into this security fix.

One asymmetry worth calling out. mcp_servers on a personal non-admin key remains permitted when the server is marked allow_all_keys (existing carve-out); mcp_toolsets, vector_stores, and search_tools are a blanket deny. Toolsets and vector stores have no equivalent per-row "globally allowed" flag, so there is no safe subset to allow through; search_tools follows the same pattern for consistency. Proxy admins may still assign any of these to a teamless key.

Regression coverage lives at two levels. Endpoint-level cases in tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py drive generate_key_fn and _validate_update_key_data so that deleting any of the validator calls in _common_key_generation_helper or unmoving the enforce_member_can_assign_access_groups move breaks the suite (mutation-killed). Helper-level cases in tests/test_litellm/proxy/management_helpers/test_object_permission_utils.py and test_team_member_permission_checks.py cover the non-admin-denied path, the admin-allowed path, and the empty-payload no-op for each field.


Note

High Risk
Changes proxy key-management authorization for non-admin personal keys; incorrect gating could block legitimate self-serve keys or leave a path to attach team-private resource IDs.

Overview
Closes a privilege-escalation path where internal users could create or update teamless API keys with access_group_ids and object_permission fields (mcp_toolsets, vector_stores, search_tools) that runtime auth trusts at use time.

Authorization changes: enforce_member_can_assign_access_groups now returns 403 when a non-admin assigns access groups with no team context (personal keys). New or tightened validators block the same callers from setting those object_permission lists on personal keys; proxy admins still may, and team-scoped keys keep existing team-subset rules (including MCP server normalization).

Wiring: Validators run on key generate (via _personal_key_generation_check and _common_key_generation_helper), key update (_validate_mcp_servers_for_key_update with access-group checks moved outside the team-only branch), and key regenerate when access_group_ids or object_permission is present.

Typing: Introduces shared ObjectPermissionDict in litellm/types/object_permission.py and uses it through permission helpers and agent response types instead of untyped dicts.

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

@greptile-apps

greptile-apps Bot commented Jun 26, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR hardens virtual-key management for teamless keys. The main changes are:

  • Adds non-admin gates for access_group_ids and selected object_permission fields on personal keys.
  • Wires the checks through key generate, update, and regenerate flows.
  • Preserves proxy-admin and team-scoped key behavior.
  • Adds a shared ObjectPermissionDict type for object-permission payloads.
  • Adds tests for the affected validators and endpoint paths.

Confidence Score: 5/5

The authorization changes are narrowly scoped to personal-key grant assignment and are covered across helper and endpoint paths.

The changes add focused validation for the affected grant fields while preserving documented admin and team-scoped behavior, with regression tests covering generation, update, regenerate, and helper-level cases.

T-Rex T-Rex Logs

What T-Rex did

  • Ran baseline checks on base to fetch four non-admin personal grant payloads and confirmed 200 OK responses.
  • Validated head environment by re-running the same checks and confirmed the four non-admin personal grant payloads still returned 200 OK instead of 403.
  • Verified legitimate-path endpoints admin_teamless_vector_stores and team_scoped_vector_stores_admin also returned 200 OK.
  • Executed four personal-key grant updates; observed 200 OK before and 403 Forbidden after applying changes.
  • Regenerated personal grant key on the base and received 200 OK with new credentials.
  • Attempted to regenerate the personal grant key on head; the operation was rejected with a permission error about assigning access groups.

View all artifacts

T-Rex Ran code and verified through T-Rex

Comments Outside Diff (1)

  1. General comment

    P1 Non-admin personal key generation still accepts team-scoped grants

    • Bug
      • On head c319b52d3799cf480a17370fe0ef2a69c332f313, executing generate_key_fn as an internal_user with no team_id accepted payloads containing access_group_ids, object_permission.mcp_toolsets, object_permission.vector_stores, and object_permission.search_tools. Each scenario returned 200 OK instead of the PR contract's expected 403 rejection for non-admin personal/teamless keys assigning team-scoped grants.
    • Cause
      • The changed key-management authorization path is not being enforced for this executed generate_key_fn endpoint path before key creation succeeds. The deny logic added around personal-key generation/object-permission validation is either absent from the actual head under test, bypassed in this endpoint flow, or not correctly wired to the request data used by generate_key_fn.
    • Fix
      • Ensure generate_key_fn invokes the personal-key blanket deny for non-admin callers before _common_key_generation_helper inserts the key/object permission. Specifically, when data.team_id is None and caller role is not proxy admin, reject non-empty access_group_ids and non-empty object_permission.mcp_toolsets, object_permission.vector_stores, and object_permission.search_tools with 403, while preserving proxy-admin and team-scoped validation behavior. Add/enable endpoint-level tests that fail if these four payloads return 200.

    T-Rex Ran code and verified through T-Rex

Reviews (12): Last reviewed commit: "fix: preserve normalized mcp permissions..." | Re-trigger Greptile

@codecov

codecov Bot commented Jun 26, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 66.19718% with 24 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...y/management_endpoints/key_management_endpoints.py 27.27% 16 Missing ⚠️
...roxy/management_helpers/object_permission_utils.py 76.47% 8 Missing ⚠️

📢 Thoughts on this report? Let us know!

@yucheng-berri
yucheng-berri force-pushed the litellm_veria_218_personal_key_metadata branch from 4fdd76e to 330ce52 Compare June 26, 2026 19:53
@yucheng-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@yucheng-berri
yucheng-berri force-pushed the litellm_veria_218_personal_key_metadata branch from 330ce52 to 5ad78dc Compare June 26, 2026 19:59
@yucheng-berri

Copy link
Copy Markdown
Contributor Author

@greptileai @Veria @cursor latest commit at 5ad78dc3bf rebases the prior fix-up onto a single squashed commit and addresses the CI lint failure (extracted _validate_requested_toolsets helper to keep C901 under cap; switched Set[str] to set[str] for UP006). No logic changes vs the prior review. Please re-review against HEAD.

@yucheng-berri
yucheng-berri force-pushed the litellm_veria_218_personal_key_metadata branch 2 times, most recently from a99f878 to fddd032 Compare June 26, 2026 21:42
@yucheng-berri

Copy link
Copy Markdown
Contributor Author

@greptileai @Veria @cursor latest commit fddd032c81 strips ticket references from comments and test names per request (logic unchanged); please re-review against HEAD

@greptile-apps greptile-apps 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.

Your free trial has ended. If you'd like to continue receiving code reviews, you can add a payment method here.

@yucheng-berri

Copy link
Copy Markdown
Contributor Author

@greptileai PR body updated with live-proxy traces for org_admin (bob: internal_user globally, ORG_ADMIN of acme-org). No code changes since HEAD fddd032c81. Confirming the personal-key gate denies org admins by design (they must use the team-key path); please re-review

@greptile-apps greptile-apps 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.

Your free trial has ended. If you'd like to continue receiving code reviews, you can add a payment method here.

@yucheng-berri

Copy link
Copy Markdown
Contributor Author

@greptileai PR body updated with org-admin live traces (Trace A1-A4 personal key denied, Trace B clean personal key allowed, Trace C team-key allowed). No code change in this update; please re-review against HEAD if needed

@greptile-apps greptile-apps 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.

Your free trial has ended. If you'd like to continue receiving code reviews, you can add a payment method here.

@yucheng-berri
yucheng-berri force-pushed the litellm_veria_218_personal_key_metadata branch 3 times, most recently from 06c2769 to c8e417a Compare June 26, 2026 23:37
@veria-ai

veria-ai Bot commented Jun 26, 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

yucheng-berri added a commit that referenced this pull request Jun 27, 2026
Mirrors the ObjectPermissionDict pattern introduced in PR #31471.
The new TypedDict names the keys the proxy actually reads off the
permissions field (allow_pii_controls, get_spend_routes) so callers
and readers share one source of truth. total=False keeps forward-
compat keys passing without a schema bump.

Drops the bare-dict annotation on _check_permissions_caller_permission
flagged in mock review.
yucheng-berri added a commit that referenced this pull request Jun 27, 2026
Audit of every annotation that holds the permissions payload:

  Already typed (prior commit):
    _check_permissions_caller_permission  -> Optional[PermissionsDict]

  Now typed:
    generate_key_helper_fn(permissions=)                  Optional[PermissionsDict]
    VerificationTokenRepository.{three helpers}           Optional[PermissionsDict]

  Intentionally left loose:
    GenerateRequestBase.permissions  (wire-Pydantic model field, kept
      as Optional[dict] = {} to match the precedent #31471 set for
      LiteLLM_ObjectPermissionBase vs ObjectPermissionDict).
    LiteLLM_VerificationToken.permissions  (DB roundtrip carries
      arbitrary JSON; same reason).

  Docstrings on /key/generate, /key/service-account/generate,
  /key/update, /key/regenerate, and the /user/* endpoints are
  free text and stay as-is.
@yucheng-berri

Copy link
Copy Markdown
Contributor Author

@greptileai @cursor latest HEAD is 5607340a9d with three commits now visible separately:

  1. fddd032c81 fix(proxy): the security gate itself
  2. c8e417ad90 refactor(proxy): ObjectPermissionDict TypedDict on the validator/key/team surfaces + drift-guard test
  3. 5607340a9d refactor(agents): adopt the same TypedDict on AgentResponse.object_permission (same shape, different feature file)

Please re-review against HEAD. e2e against a local proxy re-run is in progress and will be appended

@yucheng-berri

Copy link
Copy Markdown
Contributor Author

e2e re-run on HEAD 5607340a9d against a local proxy on :4000. All 11 traces match expected behavior.

============== /key/generate trace matrix ==============
alice / personal / vector_stores              (EXPECT 403)   HTTP 403
alice / personal / mcp_toolsets               (EXPECT 403)   HTTP 403
alice / personal / access_group_ids           (EXPECT 403)   HTTP 403
alice / personal / search_tools               (EXPECT 403)   HTTP 403
alice / personal / clean key                  (EXPECT 200)   HTTP 200
bob   / personal / vector_stores (orgadmin)   (EXPECT 403)   HTTP 403
bob   / team-key / vector_stores              (EXPECT 200)   HTTP 200
alice / forged team_id (member check)         (EXPECT 400)   HTTP 400
alice / non-existent team_id (LIT-1884)       (EXPECT 400)   HTTP 400
admin / personal / all forbidden              (EXPECT 200)   HTTP 200

============== /key/update trace ==============
alice / /key/update / vector_stores           (EXPECT 403)   HTTP 403

@yucheng-berri
yucheng-berri force-pushed the litellm_veria_218_personal_key_metadata branch from 5607340 to 515324d Compare June 27, 2026 00:58
yucheng-berri added a commit that referenced this pull request Jun 27, 2026
Mirrors the ObjectPermissionDict pattern introduced in PR #31471.
The new TypedDict names the keys the proxy actually reads off the
permissions field (allow_pii_controls, get_spend_routes) so callers
and readers share one source of truth. total=False keeps forward-
compat keys passing without a schema bump.

Drops the bare-dict annotation on _check_permissions_caller_permission
flagged in mock review.
yucheng-berri added a commit that referenced this pull request Jun 27, 2026
Audit of every annotation that holds the permissions payload:

  Already typed (prior commit):
    _check_permissions_caller_permission  -> Optional[PermissionsDict]

  Now typed:
    generate_key_helper_fn(permissions=)                  Optional[PermissionsDict]
    VerificationTokenRepository.{three helpers}           Optional[PermissionsDict]

  Intentionally left loose:
    GenerateRequestBase.permissions  (wire-Pydantic model field, kept
      as Optional[dict] = {} to match the precedent #31471 set for
      LiteLLM_ObjectPermissionBase vs ObjectPermissionDict).
    LiteLLM_VerificationToken.permissions  (DB roundtrip carries
      arbitrary JSON; same reason).

  Docstrings on /key/generate, /key/service-account/generate,
  /key/update, /key/regenerate, and the /user/* endpoints are
  free text and stay as-is.
@yucheng-berri
yucheng-berri force-pushed the litellm_veria_218_personal_key_metadata branch from 515324d to 24a0db4 Compare June 27, 2026 19:52
@yucheng-berri

Copy link
Copy Markdown
Contributor Author

@greptileai @Veria rebased on latest litellm_internal_staging after PR #31518 (88-col -> 120-col format switch) landed. Resolved two conflict hunks in key_management_endpoints.py (the personal-key gate + _common_key_generation_helper validator wiring); re-ran ruff format under the new 120-col default. HEAD is 24a0db4a46, three commits, no logic change in the rebase. Please re-review against HEAD

@yucheng-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@yucheng-berri

Copy link
Copy Markdown
Contributor Author

Live e2e on HEAD 24a0db4a46 against a local proxy on :4000, run after the scope reset. All 11 traces match expected behavior.

============== /key/generate trace matrix ==============
alice / personal / vector_stores              (EXPECT 403)   HTTP 403
alice / personal / mcp_toolsets               (EXPECT 403)   HTTP 403
alice / personal / access_group_ids           (EXPECT 403)   HTTP 403
alice / personal / search_tools               (EXPECT 403)   HTTP 403
alice / personal / clean key                  (EXPECT 200)   HTTP 200
bob   / personal / vector_stores (orgadmin)   (EXPECT 403)   HTTP 403
bob   / team-key / vector_stores              (EXPECT 200)   HTTP 200
alice / forged team_id (member check)         (EXPECT 400)   HTTP 400
alice / non-existent team_id (LIT-1884)       (EXPECT 400)   HTTP 400
admin / personal / all forbidden              (EXPECT 200)   HTTP 200

============== /key/update trace ==============
alice / /key/update / vector_stores           (EXPECT 403)   HTTP 403

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

There are 2 total unresolved issues (including 1 from previous review).

Autofix Details

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

  • ✅ Fixed: Regenerate ignores request team_id
    • Regenerate now resolves the effective team from the request team_id before falling back to the existing key team_id, with regression coverage for object-permission validation.

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

@yucheng-berri

Copy link
Copy Markdown
Contributor Author

@greptileai @Veria addressed Bugbot's latest finding (Medium: "Regenerate ignores request team_id") at HEAD with a two-line tweak: regenerate now reads data.team_id or _key_in_db.team_id, mirroring /key/update's resolution. Same team-resolution rule on both endpoints. The team-detach case (clearing team_id from an existing team key) remains deferred to a follow-up. Please re-review against HEAD

@yucheng-berri
yucheng-berri force-pushed the litellm_veria_218_personal_key_metadata branch from 2686f19 to f2ee615 Compare June 28, 2026 02:28
@yucheng-berri

Copy link
Copy Markdown
Contributor Author

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!

1 issue from previous review remains unresolved.

Fix All in Cursor

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit f2ee6154214c1b6c3718f0d24ee8872c77e6132a. Configure here.

@yucheng-berri

Copy link
Copy Markdown
Contributor Author

@greptileai @Veria HEAD is now f2ee6154214. Single one-line tweak since your last review: regenerate_key_fn now reads data.team_id or _key_in_db.team_id so it matches /key/update's team resolution (addresses Bugbot's "Regenerate ignores request team_id" Medium). No other logic changes. Please re-review against HEAD

… non-admins

Non-admin callers could create or update a personal key (no team_id)
with arbitrary access_group_ids, mcp_toolsets, vector_stores, or
search_tools in object_permission. The server persisted the values
without ownership validation; runtime authorization then trusted the
IDs because they were stored on the key, allowing cross-tenant access
to other teams' restricted models, MCP toolsets, and vector stores.

The personal-key gate now mirrors the team-key path.
enforce_member_can_assign_access_groups raises 403 for non-admin
teamless callers. validate_key_mcp_servers_against_team rejects
non-empty mcp_toolsets on personal non-admin keys. A new
validate_key_vector_stores_against_team enforces the same rule for
vector_stores. validate_key_search_tools_against_team gains the same
gate for search_tools. The four validators are wired into
/key/generate, /key/update, and /key/regenerate. Proxy admins keep
their existing carve-out across all fields; team keys are unaffected.

Endpoint-level regression coverage lives in
tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py
(six new parametrised cases through generate_key_fn and
_validate_update_key_data) and helper-level coverage in
tests/test_litellm/proxy/management_helpers/. Deleting any of the
validator calls in _common_key_generation_helper or unmoving the
enforce gate in _validate_update_key_data breaks the suite.
Replace bare Optional[dict] on the object_permission validator surfaces with
a typed TypedDict mirror of LiteLLM_ObjectPermissionBase. The TypedDict shape
matches the Pydantic model field-for-field and supports .get() and item
assignment, so the mutation in _rewrite_object_permission_mcp_identifiers
continues to work at runtime (TypedDict is a plain dict).

Propagated through the surfaces this PR touches: _object_permission_to_dict,
_validate_mcp_servers_for_key_update, validate_key_mcp_servers_against_team,
validate_key_search_tools_against_team, validate_key_vector_stores_against
_team, the five _extract_requested_* helpers, and the two
_rewrite_object_permission_mcp_* mutators. attach_object_permission_to_dict,
handle_update_object_permission_common, and _set_object_permission keep
their wider dict typing because they handle the full key/team data_json,
which is a superset of ObjectPermissionDict and pre-dates this PR.

No behavior change. 373 tests pass; ruff strict + type discipline gates
green.
@yucheng-berri

Copy link
Copy Markdown
Contributor Author

Reverted the regen one-line tweak at HEAD; Veria correctly pointed out my mirror of /key/update's data.team_id or _key_in_db.team_id introduced a NEW High in regenerate, because /key/update is protected by a team-membership check (LIT-1884) that /key/regenerate does not have. Closing that gap properly is the same family of work as the team-detach case (Round 2). Both are now consolidated under the follow-up referenced in the PR description.

Back to: _key_in_db.team_id only on regenerate, as before. Veria should return to risk 0/10. The remaining Bugbot Medium ("Regenerate ignores request team_id") is grouped with the deferred follow-up. cc @greptileai @Veria

@yucheng-berri
yucheng-berri force-pushed the litellm_veria_218_personal_key_metadata branch from f2ee615 to 022fad1 Compare June 28, 2026 02:47
@greptile-apps

greptile-apps Bot commented Jun 28, 2026

Copy link
Copy Markdown
Contributor

The reasoning is sound. Looking at the current diff for regenerate_key_fn, the team resolution correctly uses only _key_in_db.team_id:

if data is not None and (data.access_group_ids or data.object_permission is not None):
    regenerate_team_table: Optional[LiteLLM_TeamTableCachedObj] = None
    if _key_in_db.team_id is not None:
        regenerate_team_table = await get_team_object(...)

The revert is the right call. Using data.team_id or _key_in_db.team_id would have allowed a non-admin to supply an arbitrary team_id in the regenerate body, making the personal-key denial treat the request as team-scoped and letting gated fields through — exactly the bypass pattern Veria flagged. Since /key/regenerate has no equivalent of the LIT-1884 team-membership guard, the only safe anchor for "is this key in a team?" is the persisted _key_in_db.team_id.

The Bugbot Medium ("Regenerate ignores request team_id") is an accurate description of the asymmetry, but the deferred handling is the correct tradeoff — closing that gap requires either adding a team-membership check to regenerate (scope of its own) or making team_id admin-only on regenerate, neither of which belongs bundled into this security fix.

Risk on the regenerate path as merged: 0/10. Agreed.

@yucheng-berri

Copy link
Copy Markdown
Contributor Author

@greptileai @Veria HEAD is now 022fad18e9c. Reverted the regen one-line tweak that introduced a stale 7/10 Veria flag; code at HEAD is functionally identical to the state Veria scored at risk 0/10 against 06c2769bb1 and Greptile scored 5/5 against 24a0db4a46. Both deferred items (team-detach via /key/update or /key/regenerate) are consolidated under the follow-up referenced in the PR description. Please re-review against HEAD

@yucheng-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@yucheng-berri

Copy link
Copy Markdown
Contributor Author

@greptileai per request, please re-confirm against HEAD 022fad18e9c (you already replied here #31471 (comment) saying 'Risk on the regenerate path as merged: 0/10. Agreed.', so this is just to get a fresh formal review for the maintainer to see)

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

There are 2 total unresolved issues (including 1 from previous review).

Fix All in Cursor

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

  • ✅ Fixed: Regenerate drops MCP normalization
    • Regenerate now writes the normalized MCP object_permission back before key update preparation and includes a regression test.

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

Reviewed by Cursor Bugbot for commit 022fad1. Configure here.

object_permission=_regen_object_permission_dict,
team_obj=regenerate_team_table,
is_proxy_admin=_regen_is_proxy_admin,
)

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.

Regenerate drops MCP normalization

Medium Severity

On /key/regenerate, validate_key_mcp_servers_against_team runs against a detached dict from _object_permission_to_dict, but its normalized return value is never applied to data.object_permission before prepare_key_update_data. Generate and update both persist the normalized payload; regenerate can store the pre-validation object_permission instead.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 022fad1. Configure here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

addressed

@yucheng-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@yucheng-berri
yucheng-berri force-pushed the litellm_veria_218_personal_key_metadata branch from c319b52 to 0e82276 Compare June 29, 2026 23:46
yucheng-berri and others added 2 commits June 29, 2026 16:47
…reuse

Defines the TypedDict mirror of LiteLLM_ObjectPermissionBase under
litellm/types/object_permission.py so SDK-side modules can adopt the
type without violating the SDK-must-not-import-from-proxy layering
rule. litellm/proxy/_types.py re-exports it for existing callers.

Supports the validator-surface retypes in the preceding proxy refactor
commit.
@yucheng-berri
yucheng-berri force-pushed the litellm_veria_218_personal_key_metadata branch from 0e82276 to 5b029ec Compare June 29, 2026 23:48
@yucheng-berri

This comment was marked as duplicate.

@yucheng-berri

Copy link
Copy Markdown
Contributor Author

@greptileai Reverted the AgentResponse retype at HEAD 5b029ec. Empirically confirmed the reviewer's finding: AgentResponse.object_permission: Optional[ObjectPermissionDict] was stripping object_permission_id plus seven Prisma back-relation fields (teams, projects, verification_tokens, organizations, users, end_users, agents_table) from every agent CRUD response, because the validator-side TypedDict only mirrors the request-shape Pydantic, not the DB-row shape.

AgentResponse.object_permission is back to Optional[Dict[str, Any]]. The TypedDict file (litellm/types/object_permission.py) and the proxy validator surfaces still use ObjectPermissionDict; only the agent-response field that touched the DB row shape was reverted. Commit message on the refactor(types) commit updated to reflect the narrowed scope.

415 tests pass; ruff format + strict + type-discipline gates green

@greptile-apps

greptile-apps Bot commented Jun 29, 2026

Copy link
Copy Markdown
Contributor

Good call on the revert. The boundary is now correctly drawn:

  • ObjectPermissionDict (request-shape TypedDict) belongs on validator inputs and _personal_key_generation_check / _validate_update_key_data surfaces — fields are always a strict subset of what the caller sends in.
  • AgentResponse.object_permission touches the Prisma DB row, which carries object_permission_id and the seven back-relation fields that ObjectPermissionDict has no slots for. Optional[Dict[str, Any]] is the right type there until/unless you introduce a separate ObjectPermissionRow TypedDict that mirrors the full ORM shape.

The scoped approach (TypedDict on the write/validation path, bare dict on the read/response path) avoids silent field-stripping while still getting type-safety where it matters most for this security fix. The 415-passing / lint-green state looks ready for maintainer review.

@yuneng-berri
yuneng-berri merged commit 494d04c into litellm_internal_staging Jun 30, 2026
75 checks passed
@yuneng-berri
yuneng-berri deleted the litellm_veria_218_personal_key_metadata branch June 30, 2026 01:11
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