litellm/tests/integration/management/test_sso_sign_in.py
yuneng-jiang fc27dfdc7d
test(integration): give each owned proxy a private database and Redis by default (#47213)
* test(integration): give each owned proxy a private database and Redis by default

owned_proxy and owned_proxy_process now boot on a scratch database and a
per-proxy redis-server unless the caller opts into the worker's state with
state=OwnedState.SHARED_WITH_WORKER, passes its own DATABASE_URL, or strips
DATABASE_URL. Under the replica profile the private database gets the
writer and reader roles so the reader path stays covered.

Gateway carries the database_url its proxy writes to, and the Scenario
cleanup checks and delete_key_if_present read from it, so they keep
checking something on a private database.

The 189 test files with owned proxy sites that depend on the worker's
database or Redis opt in with a shares_worker_state module marker, which a
module-scoped conftest fixture turns into the shared state. The 7 helper
modules with such sites opt in per call, since conftest fixtures and other
test files reach them.

* test(integration): reach session fixtures with the shared marker and keep the worker retry default

The module-scoped fixture that applied shares_worker_state ran after
session-scoped fixtures, so proxies those booted went private in marked
files. The marker is now applied around each marked item's setup, call
and teardown, which covers fixtures of every scope.

Owned proxies on the worker database inherited the worker gateway's
router_settings.num_retries of 0 from it. A private proxy now gets the same
default in its config copy unless the config sets num_retries itself.

Five providers files read the owned proxy's spend rows or response cache
through the worker's database or Redis and opt into sharing.
2026-10-18 03:37:41 +00:00

130 lines
5.4 KiB
Python

import base64
import contextlib
import json
import uuid
from collections.abc import Iterator, Mapping
from contextlib import contextmanager
from pathlib import Path
from typing import Final
from urllib.parse import parse_qs, urlencode, urlparse
import httpx
import pytest
import yaml
from pydantic import JsonValue
from tests.integration._support.client import Gateway, gateway_from_environment
from tests.integration._support.database import read_rows
from tests.integration._support.process import owned_proxy
from tests.integration._support.wire import Reply, Request, wire_server
pytestmark: Final = [pytest.mark.timeout(300), pytest.mark.shares_worker_state]
CLIENT_ID: Final = "integration-sso-client"
CLIENT_SECRET: Final = "integration-sso-secret"
IDP_PROVIDER: Final = "integration-idp"
def _idp_reply(request: Request) -> Reply:
target: Final = urlparse(request.target)
query: Final = parse_qs(target.query)
if target.path == "/authorize":
code: Final = f"code-{query['login_hint'][0]}"
location: Final = f"{query['redirect_uri'][0]}?{urlencode({'code': code, 'state': query['state'][0]})}"
return Reply(status=302, body=b"", headers={"location": location})
if target.path == "/token":
expected: Final = base64.b64encode(f"{CLIENT_ID}:{CLIENT_SECRET}".encode()).decode()
form: Final = parse_qs(request.body.decode())
if request.headers.get("authorization") != f"Basic {expected}" or form.get("grant_type") != [
"authorization_code"
]:
return Reply(status=401, body=b'{"error": "invalid_client"}')
subject: Final = form["code"][0].removeprefix("code-")
return Reply(body=json.dumps({"access_token": f"access-{subject}", "token_type": "Bearer"}).encode())
if target.path == "/userinfo":
signed_in: Final = request.headers.get("authorization", "").removeprefix("Bearer access-")
return Reply(
body=json.dumps(
{
"sub": signed_in,
"preferred_username": signed_in,
"email": f"{signed_in}@example.com",
"provider": IDP_PROVIDER,
}
).encode()
)
return Reply(status=404, body=b'{"error": "not_found"}')
@contextmanager
def _sso_gateway(directory: Path, litellm_settings: Mapping[str, JsonValue]) -> Iterator[Gateway]:
config: Final = directory / "sso_proxy_config.yaml"
config.write_text(
yaml.safe_dump(
{
"model_list": [],
"general_settings": {
"master_key": "os.environ/LITELLM_MASTER_KEY",
"database_url": "os.environ/DATABASE_URL",
},
"litellm_settings": dict(litellm_settings),
}
)
)
with wire_server(_idp_reply) as idp, gateway_from_environment() as rig:
environment: Final = {
"GENERIC_CLIENT_ID": CLIENT_ID,
"GENERIC_CLIENT_SECRET": CLIENT_SECRET,
"GENERIC_AUTHORIZATION_ENDPOINT": f"{idp.url}/authorize",
"GENERIC_TOKEN_ENDPOINT": f"{idp.url}/token",
"GENERIC_USERINFO_ENDPOINT": f"{idp.url}/userinfo",
"OAUTHLIB_INSECURE_TRANSPORT": "1",
}
with owned_proxy(rig, directory, environment, config=config, remove_environment=("PROXY_BASE_URL",)) as gw:
yield gw
def _sign_in(gateway: Gateway, subject: str) -> httpx.Response:
proxy_url: Final = str(gateway.client.base_url).rstrip("/")
with httpx.Client(follow_redirects=False, trust_env=False, timeout=30) as browser:
start: Final = browser.get(f"{proxy_url}/sso/key/generate")
assert start.is_redirect, f"{start.status_code} {start.text}"
at_idp: Final = browser.get(f"{start.headers['location']}&{urlencode({'login_hint': subject})}")
assert at_idp.status_code == 302, f"{at_idp.status_code} {at_idp.text}"
return browser.get(at_idp.headers["location"])
def _delete_user(gateway: Gateway, subject: str) -> None:
response: Final = gateway.request("POST", "/user/delete", {"user_ids": [subject]})
assert response.status_code == 200, response.text
def _signed_in_user(subject: str) -> list[dict[str, JsonValue]]:
return read_rows('SELECT user_email, user_role, metadata FROM "LiteLLM_UserTable" WHERE user_id = %s', (subject,))
@pytest.mark.parametrize(
("litellm_settings", "expected_role"),
[
({}, "internal_user_viewer"),
({"default_internal_user_params": {"user_role": "internal_user"}}, "internal_user"),
],
ids=["no-default", "default-internal-user"],
)
def test_a_first_sso_sign_in_creates_the_user_with_the_default_role(
tmp_path: Path, litellm_settings: Mapping[str, JsonValue], expected_role: str
) -> None:
subject: Final = f"sso-new-user-{uuid.uuid4().hex[:12]}"
with _sso_gateway(tmp_path, litellm_settings) as gateway, contextlib.ExitStack() as cleanups:
cleanups.callback(_delete_user, gateway, subject)
callback: Final = _sign_in(gateway, subject)
assert callback.status_code == 303, f"{callback.status_code} {callback.text}"
assert callback.headers["location"].startswith(f"{str(gateway.client.base_url).rstrip('/')}/ui/?login=success")
assert _signed_in_user(subject) == [
{
"user_email": f"{subject}@example.com",
"user_role": expected_role,
"metadata": {"auth_provider": IDP_PROVIDER},
}
]