Skip to content
Merged
20 changes: 2 additions & 18 deletions litellm/proxy/management_endpoints/access_group_endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@
_cache_access_object,
_cache_key_object,
_cache_team_object,
_delete_cache_access_object,
_get_team_object_from_cache,
)
from litellm.proxy.auth.user_api_key_auth import user_api_key_auth
from litellm.proxy.db.exception_handler import PrismaDBExceptionHandler
from litellm.proxy.management_helpers.access_group_team_sync import invalidate_access_group_cache
from litellm.proxy.utils import get_prisma_client_or_throw
from litellm.repositories.table_repositories import AccessGroupRepository
from litellm.types.access_group import (
Expand Down Expand Up @@ -146,22 +146,6 @@ async def _cache_access_group_record(record: _AccessGroupRecord) -> None:
)


async def _invalidate_cache_access_group(access_group_id: str) -> None:
"""
Invalidate (delete) an access group entry from both in-memory and Redis caches.

Uses a lazy import of user_api_key_cache and proxy_logging_obj from proxy_server
to avoid circular imports, following the same pattern as key_management_endpoints.
"""
from litellm.proxy.proxy_server import proxy_logging_obj, user_api_key_cache

await _delete_cache_access_object(
access_group_id=access_group_id,
user_api_key_cache=user_api_key_cache,
proxy_logging_obj=proxy_logging_obj,
)


# ---------------------------------------------------------------------------
# DB sync helpers (called inside a Prisma transaction)
# ---------------------------------------------------------------------------
Expand Down Expand Up @@ -595,7 +579,7 @@ async def delete_access_group(

from litellm.proxy.proxy_server import proxy_logging_obj, user_api_key_cache

await _invalidate_cache_access_group(access_group_id)
await invalidate_access_group_cache(access_group_id)
await _patch_team_caches_remove_access_group(
affected_team_ids, access_group_id, user_api_key_cache, proxy_logging_obj
)
Expand Down
10 changes: 10 additions & 0 deletions litellm/proxy/management_endpoints/team_endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,9 @@
from litellm.proxy.management_endpoints.tag_management_endpoints import (
get_daily_activity,
)
from litellm.proxy.management_helpers.access_group_team_sync import (
sync_team_access_group_membership,
)
from litellm.proxy.management_helpers.object_permission_utils import (
_set_object_permission,
enforce_all_proxy_mcp_servers_grant_is_admin_only,
Expand Down Expand Up @@ -1509,6 +1512,8 @@ async def new_team(
include={"litellm_model_table": True},
)

await sync_team_access_group_membership(prisma_client=prisma_client, team_id=team_row.team_id)

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.

P1 Creation failure cannot reconcile

When access-group synchronization fails after new_team commits the team row, retrying the request with the same explicit team_id stops at duplicate-team validation before synchronization runs. The team remains created with stale reverse membership, causing its keys to miss the access-group resources until a separate team update reconciles it.

Knowledge Base Used:


## ADD TEAM ID TO USER TABLE ##
team_member_add_request: Final = TeamMemberAddRequest(
team_id=data.team_id,
Expand Down Expand Up @@ -2210,6 +2215,7 @@ async def update_team(
)

verbose_proxy_logger.info("Successfully updated team - %s, info", team_row.team_id)
await sync_team_access_group_membership(prisma_client=prisma_client, team_id=team_row.team_id)
await _refresh_cached_team(
team_row=team_row,
user_api_key_cache=user_api_key_cache,
Expand Down Expand Up @@ -3790,6 +3796,10 @@ async def delete_team(

## DELETE TEAMS
deleted_teams: Final = await prisma_client.delete_data(team_id_list=data.team_ids, table_name="team")

for deleted_team in team_rows:
await sync_team_access_group_membership(prisma_client=prisma_client, team_id=deleted_team.team_id)

return deleted_teams


Expand Down
121 changes: 121 additions & 0 deletions litellm/proxy/management_helpers/access_group_team_sync.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
"""
Reverse sync for the team side of the team <-> access group relationship.

`litellm_accessgrouptable.assigned_team_ids` and `litellm_teamtable.access_group_ids`
are two copies of the same relationship, and both are read: the access group's
attached-teams view reads the former, and so does the key-side grant check in
`auth_checks.get_authorized_resources_from_key_access_groups`. The access-group
endpoints maintain both copies already; this module is what the team write paths
call so an edit from that side is mirrored back.

It deliberately lives outside `access_group_endpoints`, which is a lazily
registered feature router (see `_lazy_features.LAZY_FEATURES`). Importing that
module eagerly from `team_endpoints` would put it in `sys.modules` without its
router ever being included, which drops its routes from the OpenAPI schema.
"""

from collections.abc import Mapping, Sequence
from typing import Final, Protocol

from pydantic import BaseModel, TypeAdapter

from litellm.proxy.auth.auth_checks import _delete_cache_access_object

# hashtext collisions only cost two unrelated teams a little serialization, and the
# lock is never taken by the access-group endpoints, so it cannot join their
# access-group-then-team lock order to form a cycle.
_LOCK_TEAM_SQL: Final = "SELECT pg_advisory_xact_lock(hashtext($1)) IS NULL AS locked"

_READ_TEAM_SQL: Final = 'SELECT access_group_ids FROM "LiteLLM_TeamTable" WHERE team_id = $1'

_ATTACH_SQL: Final = """
UPDATE "LiteLLM_AccessGroupTable"
SET assigned_team_ids = array_append(COALESCE(assigned_team_ids, ARRAY[]::TEXT[]), $1)
WHERE access_group_id = ANY($2::TEXT[])
AND NOT ($1 = ANY(COALESCE(assigned_team_ids, ARRAY[]::TEXT[])))
RETURNING access_group_id
"""

_DETACH_SQL: Final = """
UPDATE "LiteLLM_AccessGroupTable"
SET assigned_team_ids = array_remove(assigned_team_ids, $1)
WHERE $1 = ANY(COALESCE(assigned_team_ids, ARRAY[]::TEXT[]))
AND NOT (access_group_id = ANY($2::TEXT[]))
RETURNING access_group_id
"""


class _ChangedGroup(BaseModel):
access_group_id: str


class _TeamGroups(BaseModel):
access_group_ids: tuple[str, ...] | None = None


_ChangedGroups: Final = TypeAdapter(tuple[_ChangedGroup, ...])
_TeamRows: Final = TypeAdapter(tuple[_TeamGroups, ...])


class _RawQueryExecutor(Protocol):
async def query_raw(self, query: str, *args: object) -> Sequence[Mapping[str, object]]: ...


class _Transaction(Protocol):
async def __aenter__(self) -> _RawQueryExecutor: ...

async def __aexit__(self, *exc_info: object) -> None: ...


class _PrismaDb(Protocol):
def tx(self) -> _Transaction: ...


class _PrismaClient(Protocol):
@property
def db(self) -> _PrismaDb: ...


async def invalidate_access_group_cache(access_group_id: str) -> None:
"""
Drop an access group entry from both the in-memory and Redis caches.

Uses a lazy import of user_api_key_cache and proxy_logging_obj from proxy_server
to avoid circular imports, following the same pattern as key_management_endpoints.
"""
from litellm.proxy.proxy_server import proxy_logging_obj, user_api_key_cache

await _delete_cache_access_object(
access_group_id=access_group_id,
user_api_key_cache=user_api_key_cache,
proxy_logging_obj=proxy_logging_obj,
)


async def sync_team_access_group_membership(prisma_client: _PrismaClient, team_id: str) -> None:
"""
Reconcile every access group's `assigned_team_ids` against the team's own committed
`access_group_ids`, so a team-side edit is visible on the access-group side.

Call this after the team row is written, or after it is deleted: a team with no row
reconciles to an empty set, which detaches it from every group.

The team row is read here rather than passed in, under an advisory lock held for the
rest of the transaction. That is what makes concurrent writes to the same team
converge, since each mirror reconciles against the row as committed instead of
against the snapshot its own caller happened to see. It also means a retry heals a
sync that failed partway, where a before/after delta would compute nothing to do.

Both mirror statements are set-based and mutate the array inside the statement, so a
concurrent write for a different team cannot be lost the way a read-modify-write of
the whole array can, and the pair commits together or not at all.
"""
async with prisma_client.db.tx() as tx:
await tx.query_raw(_LOCK_TEAM_SQL, team_id)
team_rows: Final = _TeamRows.validate_python(await tx.query_raw(_READ_TEAM_SQL, team_id))
desired: Final = list(team_rows[0].access_group_ids or ()) if team_rows else []
attached: Final = _ChangedGroups.validate_python(await tx.query_raw(_ATTACH_SQL, team_id, desired))
detached: Final = _ChangedGroups.validate_python(await tx.query_raw(_DETACH_SQL, team_id, desired))

for group in (*attached, *detached):
await invalidate_access_group_cache(group.access_group_id)
Loading
Loading