mirror of
https://github.com/BerriAI/litellm.git
synced 2026-11-25 22:20:43 +00:00
* feat(proxy): add per-team chargeback cost margins Co-Authored-By: Ishaan Jaffer <155045088+ishaan-berri@users.noreply.github.com> * fix(proxy): secure team pricing and surcharge budget reservations Co-Authored-By: Ishaan Jaffer <155045088+ishaan-berri@users.noreply.github.com> * chore(ui): regenerate team pricing endpoint descriptions Co-Authored-By: Ishaan Jaffer <155045088+ishaan-berri@users.noreply.github.com> * fix(proxy): preserve team pricing when archiving deleted teams Co-Authored-By: Ishaan Jaffer <155045088+ishaan-berri@users.noreply.github.com> * feat(proxy): replace the per-team margin with a surcharge on customer requests A cost_margin_config entry keyed customer adds a percentage to requests made for a customer organization. The surcharge is part of spend, so customer budgets count it, and each request records it in cost_breakdown and in a customer_margin_spend column on the daily spend tables so cost before the surcharge stays exact Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * chore: regenerate the lazy openapi snapshot Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * style: keep the accumulation suppression on its line Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * refactor: read the recorded surcharge through a typed model Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(ui): import the surcharge breakdown on the customer usage page Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(ui): type the surcharge field where daily metrics are built Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(ui): show a small surcharge to four decimals Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(ui): reload margins after a refused save and drop the fixed amount for customer requests Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * style(ui): format the surcharge breakdown Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test: carry the surcharge column in daily activity fixtures Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * feat(customer-portal): set budgets per customer and gateway app Let administrators choose Teams, Projects, or Virtual Keys as the gateway-wide app scope and assign customer budgets from existing budget groups. Includes the shared budget-group integration from PR #52411 and builds on the existing app accounting implementation. * fix(customer-portal): show app usage and resolve CI regressions Use the existing dashboard controls and compact budget rows. Add app filtering to customer usage and retain trusted app context for budget rejections. Update request-header handling, tracing registry coverage, bounded app discovery, and optional caller-metadata tests. * feat(proxy): let each app decide whether it may create unknown customers Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * style: sort imports Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(ui): lock the app customer switch while its save is pending Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(proxy): surcharge requests charged to a customer through the key's binding Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test: forward the surcharge through the grouped daily activity fixture Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(proxy): surcharge billed failure rows charged to a customer Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * style: keep the callback tests' existing formatting Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(proxy): refuse an unknown organization alias sent with a known member Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * feat(proxy): let an app set its own surcharge on customer requests Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(proxy): refuse an unknown customer before reporting its organization's budget Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(proxy): surcharge a customer-bound key at settlement and record no fields for a zero surcharge Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test: a zero surcharge is covered by its own case Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * refactor(ui): move the no-app customer switch into its own component Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(proxy): read a key's customer binding from the trusted metadata bucket of any route Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * feat(proxy): apply an app's surcharge to keys bound to a customer Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * feat(customer-portal): set budgets per customer and gateway app Let administrators choose Teams, Projects, or Virtual Keys as the gateway-wide app scope and assign customer budgets from existing budget groups. Includes the shared budget-group integration from PR #52411 and builds on the existing app accounting implementation. * fix(customer-portal): show app usage and resolve CI regressions Use the existing dashboard controls and compact budget rows. Add app filtering to customer usage and retain trusted app context for budget rejections. Update request-header handling, tracing registry coverage, bounded app discovery, and optional caller-metadata tests. * fix(customer-portal): enforce app caps and charge each window once Enforce an authenticated app budget when optional customer and app headers are omitted. Normalize overlapping scalar and explicit budget windows to a single charge with the stricter cap and explicit reset time. Cover all app primitives through native HTTP auth and use realistic empty gateway configuration in existing test doubles. * test(proxy): let the customer usage fake answer app lookups for customer-bound keys Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(proxy): type the payload metadata read for customer attribution Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(proxy): surcharge billed failures on customer-bound keys and record the surcharge without a snapshot Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(proxy): surcharge billed failures whose customer binding sits beside litellm_params Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(proxy): drive a billed Responses failure on a customer-bound key through the failure callback Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(proxy): drive a billed Responses failure through the failure callback at each app surcharge Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(customer-portal): reuse budget controls and admission Use shared customer budget controls for app forms and resolve member budgets at one owner. Remove unused app lifecycle and listing routes. Parse request identity once, check each global and app scope once, and keep app counters alive through the existing database flush window. * fix(customer-portal): preserve app attribution for deferred costs Persist the original trusted customer and app billing context on managed jobs. Restore it in batch and background cost polling with the original request time, preserving admission windows and existing claim behavior. Recognize the India Bedrock model prefix in dashboard model setup. * fix(ci): make migration repeatable and await scoped callbacks Set the required migration lock timeout and add the billing-context column only if it is absent. Use per-request completion test callbacks and await the MCP panel failure notification. Keep response, pricing, and complete callback-sequence assertions. * fix(ui): align Bedrock profile parsing with main Use the upstream country-prefix handling to clear the model-setup merge conflict. * refactor(proxy): resolve a customer under its registration rules in one helper Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: Ishaan Jaffer <155045088+ishaan-berri@users.noreply.github.com> Co-authored-by: ishaan-j-berri <ishaan.j@berri.ai>
440 lines
17 KiB
Python
440 lines
17 KiB
Python
from types import SimpleNamespace
|
|
from typing import (
|
|
TYPE_CHECKING,
|
|
Final,
|
|
cast,
|
|
) # noqa: TID251 # in-memory adapters implement the external Prisma edge
|
|
from unittest.mock import patch
|
|
|
|
import pytest
|
|
|
|
import litellm
|
|
from litellm.proxy._types import ProxyException, UserAPIKeyAuth
|
|
from litellm.proxy.auth.app_auth import app_scope, resolve_app_hierarchy
|
|
from litellm.proxy.auth.customer_hierarchy_auth import CustomerBudgetExceededError, check_customer_hierarchy_budget
|
|
from litellm.proxy.litellm_pre_call_utils import LiteLLMProxyRequestSetup
|
|
from litellm.proxy.management_helpers.apps import AppStore
|
|
from litellm.proxy.spend_tracking.budget_reservation import customer_window_counters
|
|
from litellm.proxy.spend_tracking.customer_cost_margin import key_customer_cost_margin, request_customer_cost_margin
|
|
from litellm.types.proxy.auth.customer_hierarchy import (
|
|
CustomerHierarchyAuth,
|
|
CustomerScopeAuth,
|
|
)
|
|
from litellm.types.proxy.management_endpoints.apps import (
|
|
App,
|
|
AppCreate,
|
|
AppDefinition,
|
|
AppFailure,
|
|
AppResourceType,
|
|
)
|
|
from litellm.types.proxy.management_endpoints.customer_hierarchy import Budget
|
|
from tests.unit.proxy.management_helpers.test_apps import AppDatabase, seed_resources
|
|
from tests.unit.proxy.management_helpers.test_customer_hierarchy import NOW
|
|
|
|
if TYPE_CHECKING:
|
|
from prisma import Prisma
|
|
|
|
from litellm.proxy.utils import PrismaClient
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("with_customer", (False, True))
|
|
async def test_resolved_app_adds_only_scopes_with_resolved_customer_parents(
|
|
with_customer: bool,
|
|
) -> None:
|
|
database: Final = AppDatabase()
|
|
store: Final = AppStore(cast("Prisma", database), NOW) # cast-ok: in-memory Prisma edge
|
|
await seed_resources(database)
|
|
await store.put_definition(AppDefinition(resource_type=AppResourceType.TEAM))
|
|
app: Final = await store.create(AppCreate(resource_id="chat", budget=Budget(max_budget=10)), "admin")
|
|
assert not isinstance(app, AppFailure)
|
|
hierarchy: Final = (
|
|
CustomerHierarchyAuth(
|
|
customer_org_id="org",
|
|
customer_member_id="member",
|
|
scopes=(CustomerScopeAuth(key="customer_org", entity_id="org", spend=1, max_budget=100),),
|
|
)
|
|
if with_customer
|
|
else None
|
|
)
|
|
connection: Final = cast("PrismaClient", SimpleNamespace(db=database)) # cast-ok: in-memory Prisma edge
|
|
result: Final = await resolve_app_hierarchy(
|
|
hierarchy,
|
|
{} if with_customer else {"x-litellm-app": "Chat"},
|
|
{},
|
|
connection,
|
|
None,
|
|
"request-model",
|
|
"/v1/chat/completions",
|
|
UserAPIKeyAuth(team_id="chat"),
|
|
)
|
|
assert result is not None and result.app_id == app.app_id
|
|
assert tuple(scope.key for scope in result.scopes) == (
|
|
("customer_org", "app", "app_customer_org", "app_customer_member") if with_customer else ("app",)
|
|
)
|
|
assert result.customer_org_id == ("org" if with_customer else None)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_assertion_header_cannot_select_another_authenticated_team() -> None:
|
|
database: Final = AppDatabase()
|
|
store: Final = AppStore(database, NOW)
|
|
await seed_resources(database)
|
|
await store.put_definition(AppDefinition(resource_type=AppResourceType.TEAM))
|
|
chat: Final = await store.create(AppCreate(resource_id="chat"), "admin")
|
|
search: Final = await store.create(AppCreate(resource_id="search"), "admin")
|
|
assert isinstance(chat, App) and isinstance(search, App)
|
|
connection: Final = cast("PrismaClient", SimpleNamespace(db=database)) # cast-ok: in-memory Prisma edge
|
|
with pytest.raises(ProxyException) as rejected:
|
|
await resolve_app_hierarchy(
|
|
None,
|
|
{"x-litellm-app": "Search"},
|
|
{},
|
|
connection,
|
|
None,
|
|
None,
|
|
"/v1/chat/completions",
|
|
UserAPIKeyAuth(team_id="chat"),
|
|
)
|
|
assert int(rejected.value.code) == 403
|
|
admitted: Final = await resolve_app_hierarchy(
|
|
None,
|
|
{"x-litellm-app": "Chat"},
|
|
{},
|
|
connection,
|
|
None,
|
|
None,
|
|
"/v1/chat/completions",
|
|
UserAPIKeyAuth(team_id="chat"),
|
|
)
|
|
assert admitted is not None and admitted.app_id == chat.app_id
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_unset_definition_preserves_global_behavior_even_with_app_headers() -> None:
|
|
database: Final = AppDatabase()
|
|
hierarchy: Final = CustomerHierarchyAuth(customer_org_id="org", scopes=())
|
|
connection: Final = cast("PrismaClient", SimpleNamespace(db=database)) # cast-ok: in-memory Prisma edge
|
|
result: Final = await resolve_app_hierarchy(
|
|
hierarchy,
|
|
{"x-litellm-app": "arbitrary"},
|
|
{"app_alias": "spoof"},
|
|
connection,
|
|
None,
|
|
None,
|
|
"/v1/chat/completions",
|
|
UserAPIKeyAuth(team_id="chat"),
|
|
)
|
|
assert result is hierarchy
|
|
assert not database.litellm_apptable.rows
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("resource_type", tuple(AppResourceType))
|
|
@pytest.mark.parametrize("assertion", (None, "Chat"))
|
|
async def test_an_app_assertion_requires_a_resource_on_the_authenticated_identity(
|
|
resource_type: AppResourceType, assertion: str | None
|
|
) -> None:
|
|
database: Final = AppDatabase()
|
|
store: Final = AppStore(database, NOW)
|
|
await store.put_definition(AppDefinition(resource_type=resource_type))
|
|
hierarchy: Final = CustomerHierarchyAuth(customer_org_id="org", scopes=())
|
|
connection: Final = cast("PrismaClient", SimpleNamespace(db=database)) # cast-ok: in-memory Prisma edge
|
|
|
|
async def resolve() -> CustomerHierarchyAuth | None:
|
|
return await resolve_app_hierarchy(
|
|
hierarchy,
|
|
{"X-LiteLLM-App": assertion} if assertion is not None else {},
|
|
{},
|
|
connection,
|
|
None,
|
|
None,
|
|
"/v1/chat/completions",
|
|
UserAPIKeyAuth(),
|
|
)
|
|
|
|
if assertion is None:
|
|
assert await resolve() is hierarchy
|
|
else:
|
|
with pytest.raises(ProxyException) as rejected:
|
|
await resolve()
|
|
assert int(rejected.value.code) == 403
|
|
assert rejected.value.param == "x-litellm-app"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize(
|
|
("resource_id", "assertion", "admitted"),
|
|
(
|
|
("chat", None, True),
|
|
("chat", "chat", True),
|
|
("chat", " Chat ", True),
|
|
("chat", "Search", False),
|
|
("missing-team", "Chat", False),
|
|
),
|
|
)
|
|
async def test_unconfigured_apps_validate_assertions_against_the_authenticated_resource(
|
|
resource_id: str, assertion: str | None, admitted: bool
|
|
) -> None:
|
|
database: Final = AppDatabase()
|
|
store: Final = AppStore(database, NOW)
|
|
await seed_resources(database)
|
|
await store.put_definition(AppDefinition(resource_type=AppResourceType.TEAM))
|
|
hierarchy: Final = CustomerHierarchyAuth(customer_org_id="org", scopes=())
|
|
connection: Final = cast("PrismaClient", SimpleNamespace(db=database)) # cast-ok: in-memory Prisma edge
|
|
|
|
async def resolve() -> CustomerHierarchyAuth | None:
|
|
return await resolve_app_hierarchy(
|
|
hierarchy,
|
|
{"x-litellm-app": assertion} if assertion is not None else {},
|
|
{},
|
|
connection,
|
|
None,
|
|
None,
|
|
"/v1/chat/completions",
|
|
UserAPIKeyAuth(team_id=resource_id),
|
|
)
|
|
|
|
if admitted:
|
|
assert await resolve() is hierarchy
|
|
else:
|
|
with pytest.raises(ProxyException) as rejected:
|
|
await resolve()
|
|
assert int(rejected.value.code) == 403
|
|
assert not database.litellm_apptable.rows
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_an_app_budget_rejection_retains_trusted_attribution() -> None:
|
|
database: Final = AppDatabase()
|
|
store: Final = AppStore(database, NOW)
|
|
await seed_resources(database)
|
|
await store.put_definition(AppDefinition(resource_type=AppResourceType.TEAM))
|
|
app: Final = await store.create(AppCreate(resource_id="chat", budget=Budget(max_budget=0)), "admin")
|
|
assert isinstance(app, App)
|
|
connection: Final = cast("PrismaClient", SimpleNamespace(db=database)) # cast-ok: in-memory Prisma edge
|
|
hierarchy: Final = CustomerHierarchyAuth(
|
|
customer_org_id="org",
|
|
scopes=(CustomerScopeAuth(key="customer_org", entity_id="org", spend=0, max_budget=100),),
|
|
)
|
|
with pytest.raises(CustomerBudgetExceededError) as rejected:
|
|
await resolve_app_hierarchy(
|
|
hierarchy,
|
|
{},
|
|
{"app_id": "spoof"},
|
|
connection,
|
|
None,
|
|
None,
|
|
"/v1/chat/completions",
|
|
UserAPIKeyAuth(team_id="chat"),
|
|
)
|
|
assert rejected.value.entity_type == "app"
|
|
assert rejected.value.entity_id == app.app_id
|
|
assert rejected.value.customer_hierarchy.app_id == app.app_id
|
|
assert rejected.value.customer_hierarchy.customer_org_id == "org"
|
|
assert tuple(scope.key for scope in rejected.value.customer_hierarchy.scopes) == (
|
|
"customer_org",
|
|
"app",
|
|
"app_customer_org",
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_project_and_virtual_key_resolution_use_authenticated_resource_ids() -> None:
|
|
database: Final = AppDatabase()
|
|
store: Final = AppStore(database, NOW)
|
|
await seed_resources(database)
|
|
await store.put_definition(AppDefinition(resource_type=AppResourceType.PROJECT))
|
|
project: Final = await store.create(AppCreate(resource_id="project"), "admin")
|
|
assert isinstance(project, App)
|
|
connection: Final = cast("PrismaClient", SimpleNamespace(db=database)) # cast-ok: in-memory Prisma edge
|
|
result: Final = await resolve_app_hierarchy(
|
|
None,
|
|
{"x-litellm-app": "Project"},
|
|
{},
|
|
connection,
|
|
None,
|
|
None,
|
|
"/v1/chat/completions",
|
|
UserAPIKeyAuth(project_id="project", team_id="chat"),
|
|
)
|
|
assert result is not None and result.app_id == project.app_id
|
|
|
|
|
|
def test_app_org_denies_a_request_that_global_org_admits() -> None:
|
|
global_scope: Final = CustomerScopeAuth(key="customer_org", entity_id="org", spend=4, max_budget=100)
|
|
hierarchy: Final = CustomerHierarchyAuth(customer_org_id="org", scopes=(global_scope,))
|
|
check_customer_hierarchy_budget(hierarchy)
|
|
combined: Final = hierarchy.model_copy(
|
|
update={
|
|
"scopes": (
|
|
global_scope,
|
|
app_scope("app_customer_org", "app:org", 4, Budget(max_budget=3)),
|
|
)
|
|
}
|
|
)
|
|
with pytest.raises(litellm.BudgetExceededError) as rejected:
|
|
check_customer_hierarchy_budget(combined)
|
|
assert rejected.value.entity_type == "app_customer_org"
|
|
assert hierarchy.scopes[0] == global_scope
|
|
|
|
|
|
@pytest.mark.parametrize("duration", ("24h", "1mo", "12mo"))
|
|
def test_app_duration_cap_uses_a_separate_current_window_not_lifetime_spend(
|
|
duration: str,
|
|
) -> None:
|
|
scope: Final = app_scope("app", "application", 1000, Budget(max_budget=10, budget_duration=duration))
|
|
assert scope.max_budget is None
|
|
counters: Final = customer_window_counters(scope.key, scope.entity_id, scope.budget_limits, now=NOW)
|
|
assert len(counters) == 1 and counters[0].max_budget == 10
|
|
assert counters[0].window_duration == duration
|
|
assert counters[0].counter_key.startswith("spend:app:application:window:")
|
|
assert counters[0].reset_at is not None
|
|
next_period: Final = customer_window_counters(
|
|
scope.key,
|
|
scope.entity_id,
|
|
scope.budget_limits,
|
|
now=counters[0].reset_at,
|
|
)
|
|
assert next_period[0].counter_key != counters[0].counter_key
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_no_app_returns_the_same_hierarchy_without_a_database() -> None:
|
|
hierarchy: Final = CustomerHierarchyAuth(customer_org_id="org", scopes=())
|
|
before: Final = hierarchy.model_dump_json()
|
|
result: Final = await resolve_app_hierarchy(
|
|
hierarchy,
|
|
{},
|
|
{},
|
|
None,
|
|
None,
|
|
None,
|
|
"/v1/chat/completions",
|
|
UserAPIKeyAuth(team_id="chat"),
|
|
)
|
|
assert result is hierarchy and result.model_dump_json() == before
|
|
assert "app_id" not in result.model_dump()
|
|
|
|
|
|
def test_spoofed_app_metadata_is_removed_when_auth_has_no_app() -> None:
|
|
result: Final = LiteLLMProxyRequestSetup.add_user_api_key_auth_to_request_metadata(
|
|
{
|
|
"metadata": {
|
|
"user_api_key_app_id": "spoof",
|
|
"user_api_key_app_alias": "spoof",
|
|
}
|
|
},
|
|
UserAPIKeyAuth(),
|
|
"metadata",
|
|
)
|
|
assert "user_api_key_app_id" not in result["metadata"]
|
|
assert "user_api_key_app_alias" not in result["metadata"]
|
|
|
|
|
|
def test_app_only_scopes_stamp_trusted_identity_without_a_customer_org() -> None:
|
|
auth: Final = UserAPIKeyAuth(
|
|
customer_hierarchy=CustomerHierarchyAuth(
|
|
app_id="app",
|
|
app_alias="assistant",
|
|
scopes=(app_scope("app", "app", 0, Budget(max_budget=10)),),
|
|
)
|
|
)
|
|
result: Final = LiteLLMProxyRequestSetup.add_user_api_key_auth_to_request_metadata(
|
|
{"metadata": {"user_api_key_app_id": "spoof"}},
|
|
auth,
|
|
"metadata",
|
|
)
|
|
assert result["metadata"]["user_api_key_app_id"] == "app"
|
|
assert result["metadata"]["user_api_key_app_alias"] == "assistant"
|
|
assert result["metadata"]["user_api_key_customer_org_id"] is None
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_virtual_key_app_identity_survives_rotation_and_ignores_app_alias_metadata() -> None:
|
|
database: Final = AppDatabase()
|
|
store: Final = AppStore(database, NOW)
|
|
await seed_resources(database)
|
|
resource: Final = (await store.resources(0, 100, AppResourceType.VIRTUAL_KEY))[0]
|
|
await store.put_definition(AppDefinition(resource_type=AppResourceType.VIRTUAL_KEY))
|
|
app: Final = await store.create(AppCreate(resource_id=resource.resource_id), "admin")
|
|
assert isinstance(app, App)
|
|
connection: Final = cast("PrismaClient", SimpleNamespace(db=database)) # cast-ok: in-memory Prisma edge
|
|
hierarchy: Final = CustomerHierarchyAuth(customer_org_id="org", scopes=())
|
|
before: Final = await resolve_app_hierarchy(
|
|
hierarchy,
|
|
{},
|
|
{"app_alias": "spoof"},
|
|
connection,
|
|
None,
|
|
None,
|
|
"/v1/chat/completions",
|
|
UserAPIKeyAuth(token="token-a"),
|
|
)
|
|
await database.litellm_verificationtoken.update(where={"token": "token-a"}, data={"token": "rotated-token"})
|
|
after: Final = await resolve_app_hierarchy(
|
|
hierarchy,
|
|
{},
|
|
{},
|
|
connection,
|
|
None,
|
|
None,
|
|
"/v1/chat/completions",
|
|
UserAPIKeyAuth(token="rotated-token"),
|
|
)
|
|
assert before is not None and after is not None
|
|
assert before.app_id == after.app_id == app.app_id
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize(("customer_margin", "expected"), [(0.05, 0.05), (0, 0.0), (None, 0.02)])
|
|
async def test_a_key_bound_to_a_customer_gets_its_apps_surcharge_without_customer_headers(
|
|
customer_margin: float | None, expected: float
|
|
) -> None:
|
|
database: Final = AppDatabase()
|
|
store: Final = AppStore(cast("Prisma", database), NOW) # cast-ok: in-memory Prisma edge
|
|
await seed_resources(database)
|
|
await store.put_definition(AppDefinition(resource_type=AppResourceType.TEAM))
|
|
app: Final = await store.create(AppCreate(resource_id="chat", customer_margin=customer_margin), "admin")
|
|
assert not isinstance(app, AppFailure)
|
|
bound_key: Final = UserAPIKeyAuth(token="bound", team_id="chat", metadata={"customer_org_id": "org"})
|
|
connection: Final = cast("PrismaClient", SimpleNamespace(db=database)) # cast-ok: in-memory Prisma edge
|
|
|
|
resolved: Final = await resolve_app_hierarchy(
|
|
None, {}, {}, connection, None, "request-model", "/v1/chat/completions", bound_key
|
|
)
|
|
|
|
assert resolved is not None and resolved.app_id == app.app_id
|
|
with patch.dict(litellm.cost_margin_config, {"customer": 0.02}, clear=True):
|
|
assert key_customer_cost_margin(bound_key, resolved) == expected
|
|
settled: Final = {
|
|
"user_api_key_customer_usage": '{"customer_org_id": "org"}',
|
|
"user_api_key_customer_hierarchy": resolved.model_dump(mode="json"),
|
|
}
|
|
assert request_customer_cost_margin(settled) == expected
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_a_key_with_no_customer_resolves_its_app_but_reserves_no_surcharge() -> None:
|
|
database: Final = AppDatabase()
|
|
store: Final = AppStore(cast("Prisma", database), NOW) # cast-ok: in-memory Prisma edge
|
|
await seed_resources(database)
|
|
await store.put_definition(AppDefinition(resource_type=AppResourceType.TEAM))
|
|
await store.create(AppCreate(resource_id="chat", customer_margin=0.05), "admin")
|
|
connection: Final = cast("PrismaClient", SimpleNamespace(db=database)) # cast-ok: in-memory Prisma edge
|
|
|
|
resolved: Final = await resolve_app_hierarchy(
|
|
None,
|
|
{},
|
|
{},
|
|
connection,
|
|
None,
|
|
"request-model",
|
|
"/v1/chat/completions",
|
|
UserAPIKeyAuth(token="plain", team_id="chat"),
|
|
)
|
|
|
|
assert resolved is not None
|
|
assert (resolved.app_alias, resolved.customer_org_id, resolved.app_customer_margin) == ("Chat", None, 0.05)
|
|
with patch.dict(litellm.cost_margin_config, {"customer": 0.02}, clear=True):
|
|
assert key_customer_cost_margin(UserAPIKeyAuth(token="plain", team_id="chat"), resolved) is None
|