From 8eb6fd0f14061c09b0623385b59c809fc9749752 Mon Sep 17 00:00:00 2001 From: Yujong Lee Date: Tue, 10 Nov 2026 17:44:58 +0900 Subject: [PATCH] feat(auth): expose the native OAuth2 and custom auth facets to Python with typed steps python-bridge gains AuthCoreHandle, which runs gateway-auth-core's NativeCore a step at a time. Each facet call is its own class with one answer method per host call, so _native.pyi types the inputs, every step and every answer instead of taking untyped documents. gateway-auth-core stays free of pyo3. Its boundary types derive serde and the bridge converts them. RustCore stays a stub and nothing in the proxy calls the handle yet. --- litellm-rust/Cargo.lock | 2 + .../crates/gateway-auth-core/AGENTS.md | 2 + .../crates/gateway-auth-core/Cargo.toml | 1 + .../crates/gateway-auth-core/src/answers.rs | 4 +- .../crates/gateway-auth-core/src/inputs.rs | 5 +- .../crates/gateway-auth-core/src/outcome.rs | 5 +- litellm-rust/crates/python-bridge/Cargo.toml | 1 + litellm-rust/crates/python-bridge/src/auth.rs | 500 ++++++++++++++++++ litellm-rust/crates/python-bridge/src/lib.rs | 3 + litellm/rust_bridge/_native.pyi | 70 +++ tests/unit/rust_bridge/test_auth_core.py | 46 ++ 11 files changed, 634 insertions(+), 5 deletions(-) create mode 100644 litellm-rust/crates/python-bridge/src/auth.rs create mode 100644 tests/unit/rust_bridge/test_auth_core.py diff --git a/litellm-rust/Cargo.lock b/litellm-rust/Cargo.lock index 875cf54ef33..b50494272ae 100644 --- a/litellm-rust/Cargo.lock +++ b/litellm-rust/Cargo.lock @@ -3882,6 +3882,7 @@ version = "0.1.0" dependencies = [ "litellm-secret-value", "rstest", + "serde", "strum", "tokio", ] @@ -4403,6 +4404,7 @@ dependencies = [ "litellm-circuit-breaker", "litellm-core-utils", "litellm-error", + "litellm-gateway-auth-core", "litellm-host", "litellm-host-python", "litellm-http", diff --git a/litellm-rust/crates/gateway-auth-core/AGENTS.md b/litellm-rust/crates/gateway-auth-core/AGENTS.md index eefd8b479a7..db632b422b6 100644 --- a/litellm-rust/crates/gateway-auth-core/AGENTS.md +++ b/litellm-rust/crates/gateway-auth-core/AGENTS.md @@ -7,3 +7,5 @@ The crate is pure. It depends on no IO, runtime, HTTP, database or Python crate, Each Python protocol is a trait here. A core hands out its facets through accessors whose types are associated types on `AuthCore` and `TargetAuthCore`, the same composition as the Python accessors. Host methods are `-> impl Future + Send` so facets run under Axum and `tokio::spawn` without `#[async_trait]` boxing `NativeCore` implements `TargetAuthCore`. The OAuth2 and custom auth facets are worked examples of how a facet ports. Every other facet is `Unported` and panics if called, the same as `RustCore` in Python. A facet leaves `Unported` only together with the Python change that routes the proxy to it, and both sides then share one test suite of cases + +Python reaches the crate through `crates/python-bridge/src/auth.rs`, never through pyo3 types here. A value that crosses to Python derives serde, and the bridge converts it. Each facet call is a pyo3 class with one `answer_*` method per host call, so `_native.pyi` types the answer to every step. The bridge's host parks each host call until Python answers it. When a serde shape changes, change its TypedDict in `_native.pyi` with it diff --git a/litellm-rust/crates/gateway-auth-core/Cargo.toml b/litellm-rust/crates/gateway-auth-core/Cargo.toml index a93ca5039d1..43cf1ebb4ee 100644 --- a/litellm-rust/crates/gateway-auth-core/Cargo.toml +++ b/litellm-rust/crates/gateway-auth-core/Cargo.toml @@ -8,6 +8,7 @@ description = "The pure request auth core behind litellm/proxy/auth/core: facets [dependencies] litellm-secret-value.workspace = true +serde.workspace = true strum.workspace = true [dev-dependencies] diff --git a/litellm-rust/crates/gateway-auth-core/src/answers.rs b/litellm-rust/crates/gateway-auth-core/src/answers.rs index 364375ee5c8..a69a438a80b 100644 --- a/litellm-rust/crates/gateway-auth-core/src/answers.rs +++ b/litellm-rust/crates/gateway-auth-core/src/answers.rs @@ -1,5 +1,7 @@ use std::{collections::BTreeMap, time::SystemTime}; +use serde::Deserialize; + #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum PresentedKey { Admin { expires: Option }, @@ -71,7 +73,7 @@ pub struct SigningKey { pub public_key_pem: String, } -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, Deserialize)] pub struct Introspection { pub active: bool, pub subject: Option, diff --git a/litellm-rust/crates/gateway-auth-core/src/inputs.rs b/litellm-rust/crates/gateway-auth-core/src/inputs.rs index 6c834a4dd83..06c9068b289 100644 --- a/litellm-rust/crates/gateway-auth-core/src/inputs.rs +++ b/litellm-rust/crates/gateway-auth-core/src/inputs.rs @@ -1,8 +1,9 @@ use std::collections::BTreeSet; use litellm_secret_value::SecretValue; +use serde::Deserialize; -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, Deserialize)] pub struct RequestFacts { pub route: String, pub token: Option, @@ -33,7 +34,7 @@ pub struct JwtSettings { pub leeway_seconds: u64, } -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, Deserialize)] pub struct OAuth2Settings { pub user_id_header: Option, pub team_id_header: Option, diff --git a/litellm-rust/crates/gateway-auth-core/src/outcome.rs b/litellm-rust/crates/gateway-auth-core/src/outcome.rs index 48d992f7301..1f66de52d03 100644 --- a/litellm-rust/crates/gateway-auth-core/src/outcome.rs +++ b/litellm-rust/crates/gateway-auth-core/src/outcome.rs @@ -1,6 +1,7 @@ use std::time::SystemTime; use litellm_secret_value::SecretValue; +use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq)] pub enum Grant { @@ -79,14 +80,14 @@ pub struct JwtIdentity { pub scopes: Vec, } -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] pub struct OAuth2Identity { pub user_id: Option, pub team_id: Option, pub scopes: Vec, } -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct CustomIdentity { pub user_id: Option, pub team_id: Option, diff --git a/litellm-rust/crates/python-bridge/Cargo.toml b/litellm-rust/crates/python-bridge/Cargo.toml index 48206d242e4..5239a985687 100644 --- a/litellm-rust/crates/python-bridge/Cargo.toml +++ b/litellm-rust/crates/python-bridge/Cargo.toml @@ -58,6 +58,7 @@ litellm-secrets-types.workspace = true litellm-llms-types.workspace = true litellm-router-types.workspace = true litellm-router-core.workspace = true +litellm-gateway-auth-core.workspace = true litellm-host-python.workspace = true litellm-model-catalog.workspace = true litellm-model-catalog-refresh.workspace = true diff --git a/litellm-rust/crates/python-bridge/src/auth.rs b/litellm-rust/crates/python-bridge/src/auth.rs new file mode 100644 index 00000000000..4f02a05eb86 --- /dev/null +++ b/litellm-rust/crates/python-bridge/src/auth.rs @@ -0,0 +1,500 @@ +//! The native auth core, driven a step at a time by Python. Each facet call is its own class with +//! one `answer_*` method per host call, so the stub types the answer Python gives every step. +//! +//! A call owns its host, so the host parks each host call in the call's own exchange and the +//! facet future stays pending until Python answers it. + +use std::{ + collections::BTreeMap, + future::{Future, poll_fn}, + pin::Pin, + sync::{Arc, Mutex, MutexGuard, PoisonError}, + task::{Context, Poll, Waker}, +}; + +use litellm_error::Report; +use litellm_gateway_auth_core::{ + CustomAuthCore, CustomAuthHost, CustomIdentity, Introspection, NativeCore, OAuth2Core, + OAuth2Denial, OAuth2Host, OAuth2Identity, OAuth2Settings, RequestFacts, TargetAuthCore, +}; +use litellm_host_python::{from_py_argument, to_py}; +use pyo3::{exceptions::PyValueError, prelude::*}; +use serde::Serialize; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, strum::IntoStaticStr)] +#[serde(tag = "kind", rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +enum HostCall { + Introspect { token: String }, + CustomAuth, +} + +#[derive(Default)] +struct Exchange { + call: Option, + introspection: Option, + custom_identity: Option, +} + +type Shared = Arc>; + +fn lock(exchange: &Mutex) -> MutexGuard<'_, Exchange> { + exchange.lock().unwrap_or_else(PoisonError::into_inner) +} + +type Slot = fn(&mut Exchange) -> &mut Option; + +struct StepHost { + exchange: Shared, + proxy_headers: BTreeMap, +} + +impl StepHost { + fn new(exchange: &Shared, proxy_headers: BTreeMap) -> Self { + Self { + exchange: exchange.clone(), + proxy_headers, + } + } + + async fn ask(&self, call: HostCall, slot: Slot) -> T { + let mut call = Some(call); + poll_fn(move |_| { + let mut exchange = lock(&self.exchange); + if let Some(call) = call.take() { + exchange.call = Some(call); + return Poll::Pending; + } + slot(&mut exchange) + .take() + .map_or(Poll::Pending, Poll::Ready) + }) + .await + } +} + +impl OAuth2Host for StepHost { + type Error = std::convert::Infallible; + + async fn introspect(&self, token: &str) -> Result { + let call = HostCall::Introspect { + token: token.to_owned(), + }; + Ok(self.ask(call, |exchange| &mut exchange.introspection).await) + } + + fn proxy_headers(&self) -> &BTreeMap { + &self.proxy_headers + } +} + +impl CustomAuthHost for StepHost { + type Error = std::convert::Infallible; + + async fn custom_auth(&self, _facts: &RequestFacts) -> Result { + Ok(self + .ask(HostCall::CustomAuth, |exchange| { + &mut exchange.custom_identity + }) + .await) + } +} + +#[derive(Debug, PartialEq, Eq, Serialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +enum OAuth2Verdict { + Identity(OAuth2Identity), + MissingKey, + InactiveToken, +} + +impl From> for OAuth2Verdict { + fn from(outcome: Result) -> Self { + match outcome { + Ok(identity) => Self::Identity(identity), + Err(OAuth2Denial::MissingKey) => Self::MissingKey, + Err(OAuth2Denial::InactiveToken) => Self::InactiveToken, + } + } +} + +#[derive(Debug, PartialEq, Eq, Serialize)] +#[serde(tag = "kind", rename = "done")] +struct Finished { + outcome: T, +} + +#[derive(Debug, PartialEq, Eq, Serialize)] +#[serde(untagged)] +enum Step { + Ask(HostCall), + Done(Finished), +} + +#[derive(Debug, PartialEq, Eq, thiserror::Error)] +enum DriveError { + #[error("the auth call already started")] + Started, + #[error("the auth call has not started")] + NotStarted, + #[error("the auth call already finished")] + Finished, + #[error("the auth call is not waiting for a `{0}` answer")] + NotAsked(&'static str), + #[error("the auth call is pending on something other than a host call")] + Stalled, +} + +impl From for PyErr { + fn from(error: DriveError) -> Self { + PyValueError::new_err(Report::new(&error).to_string()) + } +} + +type Facet = Pin + Send>>; + +struct Driver { + future: Option>, + exchange: Shared, + started: bool, +} + +impl Driver { + fn new(exchange: Shared, future: impl Future + Send + 'static) -> Self { + Self { + future: Some(Box::pin(future)), + exchange, + started: false, + } + } + + fn start(&mut self) -> Result, DriveError> { + if self.started { + return Err(DriveError::Started); + } + self.started = true; + self.poll() + } + + fn answer( + &mut self, + kind: &'static str, + slot: Slot, + answer: A, + ) -> Result, DriveError> { + if !self.started { + return Err(DriveError::NotStarted); + } + if self.future.is_none() { + return Err(DriveError::Finished); + } + { + let mut exchange = lock(&self.exchange); + match &exchange.call { + Some(call) if <&str>::from(call) == kind => {} + _ => return Err(DriveError::NotAsked(kind)), + } + exchange.call = None; + *slot(&mut exchange) = Some(answer); + } + self.poll() + } + + fn poll(&mut self) -> Result, DriveError> { + let Some(future) = self.future.as_mut() else { + return Err(DriveError::Finished); + }; + if let Poll::Ready(outcome) = future + .as_mut() + .poll(&mut Context::from_waker(Waker::noop())) + { + self.future = None; + return Ok(Step::Done(Finished { outcome })); + } + let Some(call) = lock(&self.exchange).call.clone() else { + self.future = None; + return Err(DriveError::Stalled); + }; + Ok(Step::Ask(call)) + } +} + +fn oauth2_driver( + core: NativeCore, + facts: RequestFacts, + settings: OAuth2Settings, + proxy_headers: BTreeMap, +) -> Driver { + let exchange = Shared::default(); + let host = StepHost::new(&exchange, proxy_headers); + Driver::new(exchange, async move { + let Ok(outcome) = core.oauth2().authenticate(&host, &facts, &settings).await; + OAuth2Verdict::from(outcome) + }) +} + +fn custom_driver(core: NativeCore, facts: RequestFacts) -> Driver { + let exchange = Shared::default(); + let host = StepHost::new(&exchange, BTreeMap::new()); + Driver::new(exchange, async move { + let Ok(identity) = core.custom().authenticate(&host, &facts).await; + identity + }) +} + +fn lock_driver(driver: &Mutex>) -> MutexGuard<'_, Driver> { + driver.lock().unwrap_or_else(PoisonError::into_inner) +} + +fn step_to_py( + py: Python<'_>, + step: Result, DriveError>, +) -> PyResult> { + to_py(py, &step?) +} + +/// The native auth core. Each facet method returns an unstarted call. +#[pyclass(frozen)] +pub(crate) struct AuthCoreHandle { + core: NativeCore, +} + +#[pymethods] +impl AuthCoreHandle { + #[new] + fn new() -> Self { + Self { + core: NativeCore::default(), + } + } + + fn oauth2( + &self, + facts: &Bound<'_, PyAny>, + settings: &Bound<'_, PyAny>, + proxy_headers: &Bound<'_, PyAny>, + ) -> PyResult { + Ok(OAuth2Call(Mutex::new(oauth2_driver( + self.core, + from_py_argument(facts)?, + from_py_argument(settings)?, + from_py_argument(proxy_headers)?, + )))) + } + + fn custom(&self, facts: &Bound<'_, PyAny>) -> PyResult { + Ok(CustomAuthCall(Mutex::new(custom_driver( + self.core, + from_py_argument(facts)?, + )))) + } +} + +/// One OAuth2 introspection call. +#[pyclass(frozen)] +pub(crate) struct OAuth2Call(Mutex>); + +#[pymethods] +impl OAuth2Call { + fn start(&self, py: Python<'_>) -> PyResult> { + step_to_py(py, lock_driver(&self.0).start()) + } + + fn answer_introspection( + &self, + py: Python<'_>, + introspection: &Bound<'_, PyAny>, + ) -> PyResult> { + let introspection = from_py_argument(introspection)?; + step_to_py( + py, + lock_driver(&self.0).answer( + "introspect", + |exchange| &mut exchange.introspection, + introspection, + ), + ) + } +} + +/// One custom auth call. +#[pyclass(frozen)] +pub(crate) struct CustomAuthCall(Mutex>); + +#[pymethods] +impl CustomAuthCall { + fn start(&self, py: Python<'_>) -> PyResult> { + step_to_py(py, lock_driver(&self.0).start()) + } + + fn answer_custom_auth( + &self, + py: Python<'_>, + identity: &Bound<'_, PyAny>, + ) -> PyResult> { + let identity = from_py_argument(identity)?; + step_to_py( + py, + lock_driver(&self.0).answer( + "custom_auth", + |exchange| &mut exchange.custom_identity, + identity, + ), + ) + } +} + +#[cfg(test)] +mod tests { + use litellm_secret_value::SecretValue; + use rstest::rstest; + use serde_json::{Value, json}; + + use super::*; + + fn facts(token: Option<&str>) -> RequestFacts { + RequestFacts { + route: "/chat/completions".to_owned(), + token: token.map(SecretValue::from), + is_llm_api_route: true, + } + } + + fn oauth2(token: Option<&str>) -> Driver { + let settings = OAuth2Settings { + user_id_header: None, + team_id_header: None, + }; + oauth2_driver( + NativeCore::default(), + facts(token), + settings, + BTreeMap::new(), + ) + } + + fn introspection(active: bool) -> Introspection { + Introspection { + active, + subject: Some("user-1".to_owned()), + client_id: None, + scopes: vec!["read".to_owned()], + } + } + + fn answer_introspection( + driver: &mut Driver, + introspection: Introspection, + ) -> Result, DriveError> { + driver.answer( + "introspect", + |exchange| &mut exchange.introspection, + introspection, + ) + } + + fn wire(step: &Step) -> Value { + serde_json::to_value(step).unwrap() + } + + #[test] + fn oauth2_asks_python_to_introspect_the_presented_token() { + let step = oauth2(Some("tok-1")).start().unwrap(); + assert_eq!(wire(&step), json!({"kind": "introspect", "token": "tok-1"})); + } + + #[rstest] + #[case::active( + true, + json!({"kind": "done", "outcome": {"kind": "identity", "user_id": "user-1", "team_id": null, "scopes": ["read"]}}) + )] + #[case::inactive(false, json!({"kind": "done", "outcome": {"kind": "inactive_token"}}))] + fn oauth2_finishes_with_the_verdict_on_python_s_introspection( + #[case] active: bool, + #[case] expected: Value, + ) { + let mut driver = oauth2(Some("tok-1")); + driver.start().unwrap(); + let step = answer_introspection(&mut driver, introspection(active)).unwrap(); + assert_eq!(wire(&step), expected); + } + + #[test] + fn oauth2_without_a_token_finishes_without_a_host_call() { + let step = oauth2(None).start().unwrap(); + assert_eq!( + wire(&step), + json!({"kind": "done", "outcome": {"kind": "missing_key"}}) + ); + } + + #[test] + fn custom_auth_finishes_with_the_identity_python_resolved() { + let identity = CustomIdentity { + user_id: Some("user-1".to_owned()), + team_id: Some("team-1".to_owned()), + hashed_token: None, + }; + let mut driver = custom_driver(NativeCore::default(), facts(Some("tok-1"))); + assert_eq!( + wire(&driver.start().unwrap()), + json!({"kind": "custom_auth"}) + ); + let step = driver + .answer( + "custom_auth", + |exchange| &mut exchange.custom_identity, + identity, + ) + .unwrap(); + assert_eq!( + wire(&step), + json!({"kind": "done", "outcome": {"user_id": "user-1", "team_id": "team-1", "hashed_token": null}}) + ); + } + + #[test] + fn an_answer_before_start_is_refused() { + let mut driver = oauth2(Some("tok-1")); + assert_eq!( + answer_introspection(&mut driver, introspection(true)), + Err(DriveError::NotStarted) + ); + } + + #[test] + fn a_second_start_is_refused() { + let mut driver = oauth2(Some("tok-1")); + driver.start().unwrap(); + assert_eq!(driver.start(), Err(DriveError::Started)); + } + + #[test] + fn an_answer_to_a_call_that_was_not_made_is_refused() { + let mut driver = oauth2(Some("tok-1")); + driver.start().unwrap(); + let identity = CustomIdentity { + user_id: None, + team_id: None, + hashed_token: None, + }; + assert_eq!( + driver.answer( + "custom_auth", + |exchange| &mut exchange.custom_identity, + identity + ), + Err(DriveError::NotAsked("custom_auth")) + ); + } + + #[test] + fn an_answer_after_the_call_finished_is_refused() { + let mut driver = oauth2(None); + driver.start().unwrap(); + assert_eq!( + answer_introspection(&mut driver, introspection(true)), + Err(DriveError::Finished) + ); + } +} diff --git a/litellm-rust/crates/python-bridge/src/lib.rs b/litellm-rust/crates/python-bridge/src/lib.rs index 7edf13035c1..897febd9f98 100644 --- a/litellm-rust/crates/python-bridge/src/lib.rs +++ b/litellm-rust/crates/python-bridge/src/lib.rs @@ -1,3 +1,4 @@ +mod auth; mod cache; mod callable; mod coercion; @@ -25,6 +26,8 @@ mod _native { use litellm_host_python::{ForkedAfterNativeRuntimeStarted, ProcessReservedForForking}; use pyo3::{prelude::*, types::PyModule}; + #[pymodule_export] + use crate::auth::{AuthCoreHandle, CustomAuthCall, OAuth2Call}; #[pymodule_export] use crate::db::NativeDatabase; #[cfg(feature = "panic-test")] diff --git a/litellm/rust_bridge/_native.pyi b/litellm/rust_bridge/_native.pyi index 221968e07ed..2f942af99a6 100644 --- a/litellm/rust_bridge/_native.pyi +++ b/litellm/rust_bridge/_native.pyi @@ -676,6 +676,8 @@ def reserve_process_for_forking() -> None: ... __all__ = [ "AtomicApplied", "AtomicOverLimit", + "AuthCoreHandle", + "CustomAuthCall", "ForkedAfterNativeRuntimeStarted", "GaugeOverLimit", "GaugesAcquired", @@ -710,6 +712,7 @@ __all__ = [ "NativeSensitiveRoutePins", "NativeSpendCounters", "NativeTableSwapped", + "OAuth2Call", "PostCallSettlement", "ProcessReservedForForking", "ResponsesWebSocketConnection", @@ -1286,3 +1289,70 @@ class RouterCall(Generic[_S]): # candidate ids, pick first; pre_route: see _PreRouteStep; cache: see _CacheStep; secrets, build and model_info: # see those steps; first call: None. def next(self, outcome: object) -> _S: ... + +class _AuthRequestFacts(TypedDict): + route: str + token: str | None + is_llm_api_route: bool + +class _AuthOAuth2Settings(TypedDict): + user_id_header: str | None + team_id_header: str | None + +class _AuthIntrospection(TypedDict): + active: bool + subject: str | None + client_id: str | None + scopes: Sequence[str] + +class _AuthCustomIdentity(TypedDict): + user_id: str | None + team_id: str | None + hashed_token: str | None + +class _AuthIntrospectStep(TypedDict): + kind: Literal["introspect"] + token: str + +class _AuthOAuth2Identity(TypedDict): + kind: Literal["identity"] + user_id: str | None + team_id: str | None + scopes: list[str] + +class _AuthOAuth2Denied(TypedDict): + kind: Literal["missing_key", "inactive_token"] + +class _AuthOAuth2Done(TypedDict): + kind: Literal["done"] + outcome: _AuthOAuth2Identity | _AuthOAuth2Denied + +class _AuthCustomAuthStep(TypedDict): + kind: Literal["custom_auth"] + +class _AuthCustomAuthDone(TypedDict): + kind: Literal["done"] + outcome: _AuthCustomIdentity + +_AuthOAuth2Steps = _AuthIntrospectStep | _AuthOAuth2Done +_AuthCustomAuthSteps = _AuthCustomAuthStep | _AuthCustomAuthDone + +@final +class AuthCoreHandle: + def __new__(cls) -> AuthCoreHandle: ... + def oauth2( + self, facts: _AuthRequestFacts, settings: _AuthOAuth2Settings, proxy_headers: Mapping[str, str] + ) -> OAuth2Call: ... + def custom(self, facts: _AuthRequestFacts) -> CustomAuthCall: ... + +# Each call raises ValueError when started twice, or answered before it starts, after it ends, or +# for a host call it is not waiting on. +@final +class OAuth2Call: + def start(self) -> _AuthOAuth2Steps: ... + def answer_introspection(self, introspection: _AuthIntrospection) -> _AuthOAuth2Steps: ... + +@final +class CustomAuthCall: + def start(self) -> _AuthCustomAuthSteps: ... + def answer_custom_auth(self, identity: _AuthCustomIdentity) -> _AuthCustomAuthSteps: ... diff --git a/tests/unit/rust_bridge/test_auth_core.py b/tests/unit/rust_bridge/test_auth_core.py new file mode 100644 index 00000000000..4e78b8ac146 --- /dev/null +++ b/tests/unit/rust_bridge/test_auth_core.py @@ -0,0 +1,46 @@ +from typing import TYPE_CHECKING, Final + +import pytest + +from litellm.rust_bridge._native import AuthCoreHandle + +if TYPE_CHECKING: + from litellm.rust_bridge._native import ( + _AuthCustomIdentity, # pyright: ignore[reportPrivateUsage] # the stub's step shapes + _AuthOAuth2Steps, # pyright: ignore[reportPrivateUsage] # see above + _AuthRequestFacts, # pyright: ignore[reportPrivateUsage] # see above + ) + +FACTS: Final["_AuthRequestFacts"] = {"route": "/chat/completions", "token": "tok-1", "is_llm_api_route": True} + + +def _oauth2_after_introspection(active: bool) -> "_AuthOAuth2Steps": + call: Final = AuthCoreHandle().oauth2(FACTS, {"user_id_header": None, "team_id_header": None}, {}) + assert call.start() == {"kind": "introspect", "token": "tok-1"} + return call.answer_introspection( + {"active": active, "subject": "user-1", "client_id": "client-1", "scopes": ("read", "write")} + ) + + +@pytest.mark.parametrize( + ("active", "outcome"), + [ + (True, {"kind": "identity", "user_id": "user-1", "team_id": None, "scopes": ["read", "write"]}), + (False, {"kind": "inactive_token"}), + ], +) +def test_oauth2_reads_python_s_introspection_and_returns_the_verdict(active: bool, outcome: object) -> None: + assert _oauth2_after_introspection(active) == {"kind": "done", "outcome": outcome} + + +def test_custom_auth_returns_the_identity_python_resolved() -> None: + call: Final = AuthCoreHandle().custom(FACTS) + assert call.start() == {"kind": "custom_auth"} + identity: Final[_AuthCustomIdentity] = {"user_id": "user-1", "team_id": "team-1", "hashed_token": "hashed-1"} + assert call.answer_custom_auth(identity) == {"kind": "done", "outcome": identity} + + +def test_an_answer_before_the_call_starts_is_a_value_error() -> None: + call: Final = AuthCoreHandle().custom(FACTS) + with pytest.raises(ValueError, match="has not started"): + call.answer_custom_auth({"user_id": None, "team_id": None, "hashed_token": None})