refactor(gateway): move forwarding into a gateway-forward crate with protocol tests

The forwarder is a reverse proxy, not a mounted endpoint, so it gets its own crate
with a socket-level test harness and a property test that any generated request and
response cross it unchanged

The tests found two bugs, fixed here. Pooled connections to Python outlived uvicorn's
keep-alive, so a request could land on a connection Python was closing and get a 502.
They now retire at half of LITELLM_FORWARD_KEEPALIVE_TIMEOUT (default 5s, uvicorn's
default). A GET with a chunked body reached Python empty, because hyper's client drops
an unknown-length GET body unless transfer-encoding is set

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Yujong Lee 2026-11-03 11:23:47 +09:00
parent 1c27bd33f0
commit ba1f6164b7
23 changed files with 1583 additions and 686 deletions

View file

@ -7,7 +7,7 @@ metadata:
# Rust gateway
`crates/gateway` mounts endpoint routers and serves the listener. `crates/gateway-inference`, `gateway-mcp` and `gateway-ui` own their endpoints, `gateway-auth` is the inbound authentication middleware and `gateway-management` holds management logic that has no router yet. A crate's `AGENTS.md`, where it has one, says what belongs in it. Read the reference for the part you are touching
`crates/gateway` mounts endpoint routers and serves the listener. `crates/gateway-inference`, `gateway-mcp` and `gateway-ui` own their endpoints, `gateway-auth` is the inbound authentication middleware and `gateway-management` holds management logic that has no router yet. `gateway-forward` is the reverse proxy that relays every request to the Python proxy and has no routes of its own. A crate's `AGENTS.md`, where it has one, says what belongs in it. Read the reference for the part you are touching
- [surfaces](references/surfaces.md)
- Each API surface mirrors the envelope the Python proxy returns there, so the shapes differ on purpose

View file

@ -3808,12 +3808,11 @@ dependencies = [
"envy",
"futures-util",
"http-body-util",
"hyper 1.10.1",
"hyper-util",
"litellm-circuit-breaker",
"litellm-config",
"litellm-error",
"litellm-gateway-auth",
"litellm-gateway-forward",
"litellm-gateway-inference",
"litellm-gateway-mcp",
"litellm-gateway-ui",
@ -3831,7 +3830,6 @@ dependencies = [
"tempfile",
"thiserror 2.0.19",
"tokio",
"tokio-tungstenite",
"tokio-util",
"tower",
"tower-sessions-moka-store",
@ -3861,6 +3859,26 @@ dependencies = [
"veil",
]
[[package]]
name = "litellm-gateway-forward"
version = "0.1.0"
dependencies = [
"axum",
"bytes",
"futures-util",
"http-body-util",
"httparse",
"hyper 1.10.1",
"hyper-util",
"proptest",
"rstest",
"thiserror 2.0.19",
"tokio",
"tokio-tungstenite",
"tokio-util",
"tracing",
]
[[package]]
name = "litellm-gateway-inference"
version = "0.1.0"

View file

@ -25,6 +25,7 @@ litellm-inference-ocr = { path = "crates/inference-ocr" }
litellm-inference-testing = { path = "crates/inference-testing" }
litellm-gateway-mcp = { path = "crates/gateway-mcp" }
litellm-gateway = { path = "crates/gateway" }
litellm-gateway-forward = { path = "crates/gateway-forward" }
litellm-gateway-inference = { path = "crates/gateway-inference" }
litellm-gateway-auth = { path = "crates/gateway-auth" }
litellm-gateway-management = { path = "crates/gateway-management" }

View file

@ -0,0 +1,15 @@
# Forwarding gateway
`Forward` is a reverse proxy in front of the Python proxy on loopback. Python must see each request as if the client had connected to it directly, because every Python route (inference, MCP, pass-through, UI, WebSocket) is served behind it without Rust knowing which one it is
- Never branch on a route or path. A behavior one endpoint needs is a protocol behavior every endpoint gets
- Forward the method, request target, headers, and body byte for byte. Only drop hop-by-hop headers (RFC 9110 section 7.6.1) and set `x-litellm-rust-peer`, which replaces any client copy
- Stream both bodies. Never buffer, cap, or time out a body, since uploads and provider streams have no upper bound
- A client disconnect closes the upstream connection at every stage, because that is how Python learns to stop a provider stream
- An upstream that dies mid-response fails the client body. Never end it cleanly, or SSE clients treat a truncated stream as complete
- Pooled upstream connections are retired well before Python's keep-alive timeout, so a request never lands on a connection Python is closing
- WebSocket is the one protocol switch Python serves. Upgrades are relayed as raw bytes after the 101 and drained on shutdown
## Tests
Test through real sockets with `tests/support`, never `oneshot`. `Gateway` runs the forwarder on a listener like production, `recording` is a well-behaved upstream that captures what Python would receive, and `raw_upstream` and `Raw` drive bytes by hand for framing, timing and disconnects a real server would not produce. `tests/roundtrip.rs` checks the forwarding invariant for generated requests and responses. Add a protocol edge case there or as a focused test next to its neighbors

View file

@ -0,0 +1,26 @@
[package]
name = "litellm-gateway-forward"
version = "0.1.0"
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true
[dependencies]
axum.workspace = true
hyper = { version = "1", features = ["http1"] }
hyper-util = { workspace = true, features = ["client-legacy", "http1", "tokio"] }
thiserror.workspace = true
tokio = { workspace = true, features = ["io-util"] }
tokio-util = { version = "0.7", features = ["rt"] }
tracing.workspace = true
[dev-dependencies]
bytes.workspace = true
futures-util.workspace = true
http-body-util = "0.1"
httparse = "1"
proptest.workspace = true
rstest.workspace = true
tokio = { workspace = true, features = ["io-util", "sync"] }
tokio-tungstenite.workspace = true

View file

@ -0,0 +1,9 @@
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("invalid forwarding upstream URI")]
UpstreamUri(#[source] axum::http::uri::InvalidUri),
#[error(
"LITELLM_FORWARD_UPSTREAM must be a loopback IPv4 http origin without a path, query or credentials"
)]
Upstream,
}

View file

@ -0,0 +1,137 @@
use std::{
net::{Ipv4Addr, SocketAddr},
time::Duration,
};
use axum::{
Router,
body::{Body, HttpBody},
extract::{ConnectInfo, DefaultBodyLimit, Request, State},
http::{HeaderValue, StatusCode, Uri, Version, header},
response::Response,
};
use hyper_util::{
client::legacy::{Client, connect::HttpConnector},
rt::{TokioExecutor, TokioTimer},
};
use tokio::net::TcpListener;
use crate::{Error, hop, websocket::Upgrades};
pub const PEER_HEADER: &str = "x-litellm-rust-peer";
#[derive(Clone)]
pub struct Forward {
upstream: Uri,
client: Client<HttpConnector, Body>,
upgrades: Upgrades,
}
impl Forward {
/// `upstream_keepalive` is how long the upstream keeps an idle connection open. Pooled
/// connections are dropped well before that, so a request never lands on one it is closing.
pub fn new(upstream: &str, upstream_keepalive: Duration) -> Result<Self, Error> {
let upstream: Uri = upstream.parse().map_err(Error::UpstreamUri)?;
if upstream.scheme_str() != Some("http")
|| !upstream
.host()
.and_then(|host| host.parse::<Ipv4Addr>().ok())
.is_some_and(|ip| ip.is_loopback())
|| upstream
.authority()
.is_some_and(|authority| authority.as_str().contains('@'))
|| upstream.path() != "/"
|| upstream.query().is_some()
{
return Err(Error::Upstream);
}
let client = Client::builder(TokioExecutor::new())
.pool_timer(TokioTimer::new())
.pool_idle_timeout(upstream_keepalive / 2)
.build_http();
Ok(Self {
upstream,
client,
upgrades: Upgrades::default(),
})
}
pub fn router(self) -> Router {
Router::new()
.fallback(forward)
.layer(DefaultBodyLimit::disable())
.with_state(self)
}
/// Serves until `shutdown` resolves, then gives open WebSockets a bounded drain before closing them.
pub async fn serve(
self,
listener: TcpListener,
shutdown: impl Future<Output = ()> + Send + 'static,
) -> std::io::Result<()> {
let upgrades = self.upgrades.clone();
let _close_on_drop = upgrades.close_on_drop();
let draining = upgrades.clone();
let result = axum::serve(
listener,
self.router()
.into_make_service_with_connect_info::<SocketAddr>(),
)
.with_graceful_shutdown(async move {
shutdown.await;
draining.begin_shutdown();
})
.await;
if result.is_err() {
upgrades.close();
}
upgrades.wait().await;
result
}
}
async fn forward(
State(state): State<Forward>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
mut request: Request,
) -> Result<Response, StatusCode> {
let downstream = state.upgrades.take_handshake(&mut request)?;
let mut uri = state.upstream.into_parts();
uri.path_and_query = request.uri().path_and_query().cloned();
*request.uri_mut() = Uri::from_parts(uri).map_err(|_| StatusCode::BAD_GATEWAY)?;
*request.version_mut() = Version::HTTP_11;
let chunked = request.body().size_hint().exact().is_none();
let headers = request.headers_mut();
hop::strip(headers);
if chunked {
// hyper sends no body for a GET with an unknown length unless told it is chunked.
headers.insert(
header::TRANSFER_ENCODING,
HeaderValue::from_static("chunked"),
);
}
if downstream.is_some() {
hop::restore_websocket_handshake(headers);
}
// Forwarding headers pass through untouched so Python sees the request as if the client
// connected to it directly. Inserting replaces any client-sent copy: the peer is the one
// value a client must not choose.
headers.insert(
PEER_HEADER,
HeaderValue::from_str(&peer.to_string()).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?,
);
let response = state.client.request(request);
let mut response = match downstream {
Some(_) => state.upgrades.until_closed(response).await?,
None => response.await,
}
.map_err(|error| {
tracing::warn!(%error, "python proxy unreachable");
StatusCode::BAD_GATEWAY
})?;
if response.status() == StatusCode::SWITCHING_PROTOCOLS {
return state.upgrades.switch(downstream, response).await;
}
hop::strip(response.headers_mut());
Ok(response.map(Body::new))
}

View file

@ -0,0 +1,35 @@
use axum::http::{HeaderMap, HeaderValue, header};
// Per-connection headers (RFC 9110 section 7.6.1) describe the client's connection to Rust, not
// Rust's connection to Python, so a proxy must drop them instead of forwarding them.
pub(crate) fn strip(headers: &mut HeaderMap) {
let connection_headers: Vec<_> = headers
.get_all(header::CONNECTION)
.iter()
.filter_map(|value| value.to_str().ok())
.flat_map(|value| value.split(','))
.filter_map(|name| header::HeaderName::from_bytes(name.trim().as_bytes()).ok())
.collect();
for name in connection_headers {
headers.remove(name);
}
for name in [
"connection",
"keep-alive",
"proxy-authenticate",
"proxy-authorization",
"te",
"trailer",
"transfer-encoding",
"upgrade",
"proxy-connection",
] {
headers.remove(name);
}
}
// Stripping drops the handshake's Connection and Upgrade, so each hop gets them back.
pub(crate) fn restore_websocket_handshake(headers: &mut HeaderMap) {
headers.insert(header::CONNECTION, HeaderValue::from_static("upgrade"));
headers.insert(header::UPGRADE, HeaderValue::from_static("websocket"));
}

View file

@ -0,0 +1,7 @@
mod error;
mod forward;
mod hop;
mod websocket;
pub use error::Error;
pub use forward::{Forward, PEER_HEADER};

View file

@ -0,0 +1,126 @@
use std::time::Duration;
use axum::{
body::Body,
extract::Request,
http::{HeaderMap, Method, StatusCode, Version, header},
response::Response,
};
use hyper::{
body::Incoming,
upgrade::{OnUpgrade, Upgraded},
};
use hyper_util::rt::TokioIo;
use tokio_util::{
sync::{CancellationToken, DropGuard},
task::TaskTracker,
};
const DRAIN_TIMEOUT: Duration = Duration::from_secs(5);
#[derive(Clone, Default)]
pub(crate) struct Upgrades {
tasks: TaskTracker,
draining: CancellationToken,
closed: CancellationToken,
}
impl Upgrades {
pub fn begin_shutdown(&self) {
self.draining.cancel();
let closed = self.closed.clone();
tokio::spawn(async move {
tokio::time::sleep(DRAIN_TIMEOUT).await;
closed.cancel();
});
}
pub fn take_handshake(&self, request: &mut Request) -> Result<Option<OnUpgrade>, StatusCode> {
if request.method() != Method::GET
|| request.version() != Version::HTTP_11
|| !is_handshake(request.headers())
{
return Ok(None);
}
if self.draining.is_cancelled() {
return Err(StatusCode::SERVICE_UNAVAILABLE);
}
Ok(Some(hyper::upgrade::on(request)))
}
pub async fn until_closed<T>(&self, future: impl Future<Output = T>) -> Result<T, StatusCode> {
tokio::select! {
_ = self.closed.cancelled() => Err(StatusCode::SERVICE_UNAVAILABLE),
output = future => Ok(output),
}
}
pub async fn switch(
&self,
downstream: Option<OnUpgrade>,
mut response: Response<Incoming>,
) -> Result<Response, StatusCode> {
let Some(downstream) = downstream else {
return Err(StatusCode::BAD_GATEWAY);
};
if !is_handshake(response.headers()) {
return Err(StatusCode::BAD_GATEWAY);
}
let upstream = self
.until_closed(hyper::upgrade::on(&mut response))
.await?
.map_err(|error| {
tracing::warn!(%error, "python proxy websocket upgrade failed");
StatusCode::BAD_GATEWAY
})?;
crate::hop::strip(response.headers_mut());
crate::hop::restore_websocket_handshake(response.headers_mut());
self.relay(downstream, upstream);
Ok(response.map(|_| Body::empty()))
}
pub fn close(&self) {
self.closed.cancel();
}
pub fn close_on_drop(&self) -> DropGuard {
self.closed.clone().drop_guard()
}
pub async fn wait(&self) {
self.tasks.close();
self.tasks.wait().await;
}
fn relay(&self, downstream: OnUpgrade, upstream: Upgraded) {
let closed = self.closed.clone();
self.tasks.spawn(async move {
tokio::select! {
_ = closed.cancelled() => {}
_ = async {
let Ok(downstream) = downstream.await else {
tracing::debug!("websocket upgrade did not complete");
return;
};
let mut downstream = TokioIo::new(downstream);
let mut upstream = TokioIo::new(upstream);
if let Err(error) = tokio::io::copy_bidirectional(&mut downstream, &mut upstream).await {
tracing::debug!(%error, "websocket relay disconnected");
}
} => {}
}
});
}
}
fn is_handshake(headers: &HeaderMap) -> bool {
headers
.get(header::UPGRADE)
.is_some_and(|value| value.as_bytes().eq_ignore_ascii_case(b"websocket"))
&& headers
.get_all(header::CONNECTION)
.iter()
.filter_map(|value| value.to_str().ok())
.flat_map(|value| value.split(','))
.any(|token| token.trim().eq_ignore_ascii_case("upgrade"))
}

View file

@ -0,0 +1,145 @@
mod support;
use std::{
sync::Arc,
time::{Duration, Instant},
};
use axum::{body::Body, extract::Request, http::StatusCode};
use http_body_util::BodyExt;
use rstest::rstest;
use support::{Gateway, Raw, client, raw_upstream, unreachable_upstream, within};
use tokio::sync::{Notify, mpsc};
/// Python stops a provider stream when it sees the client go away, so a client disconnect must
/// close Rust's connection to Python at every stage of the exchange.
#[rstest]
#[case::waiting_for_headers(
"POST /v1/chat/completions HTTP/1.1\r\nhost: x\r\ncontent-length: 0\r\n\r\n",
false
)]
#[case::mid_stream(
"POST /v1/chat/completions HTTP/1.1\r\nhost: x\r\ncontent-length: 0\r\n\r\n",
true
)]
#[case::mid_upload(
"POST /v1/files HTTP/1.1\r\nhost: x\r\ncontent-length: 1000000\r\n\r\npartial",
false
)]
#[tokio::test]
async fn client_disconnect_closes_the_upstream_connection(
#[case] request: &'static str,
#[case] headers_sent: bool,
) {
let (event, mut events) = mpsc::unbounded_channel();
let upstream = raw_upstream(move |mut python: Raw| {
let event = event.clone();
async move {
python.request_head().await.unwrap();
if headers_sent {
python
.send("HTTP/1.1 200 OK\r\ntransfer-encoding: chunked\r\n\r\n6\r\ndata: \r\n")
.await;
}
event.send("received").unwrap();
python.closed().await;
event.send("closed").unwrap();
}
})
.await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send(request).await;
assert_eq!(within(events.recv()).await, Some("received"));
if headers_sent {
assert_eq!(
within(raw.response_head()).await.unwrap().status,
StatusCode::OK
);
}
drop(raw);
assert_eq!(within(events.recv()).await, Some("closed"));
}
/// uvicorn closes a connection that sat idle past its keep-alive timeout. A request Rust sends on
/// that connection as uvicorn closes it is lost, so Rust must retire idle connections first.
#[rstest]
#[case::reused_while_fresh(Duration::from_millis(0))]
#[case::past_the_pool_timeout(Duration::from_millis(250))]
#[case::past_python_keepalive(Duration::from_millis(450))]
#[tokio::test]
async fn never_reuses_a_connection_python_is_closing_for_idleness(#[case] idle: Duration) {
let keepalive = Duration::from_millis(400);
let upstream = raw_upstream(move |mut python: Raw| async move {
let mut idle_since = None::<Instant>;
while python.request_head().await.is_some() {
if idle_since.is_some_and(|since| since.elapsed() >= keepalive) {
return;
}
python
.send("HTTP/1.1 200 OK\r\ncontent-length: 2\r\n\r\nok")
.await;
idle_since = Some(Instant::now());
}
})
.await;
let gateway = Gateway::with_keepalive(upstream, keepalive).await;
let client = client();
let first = within(client.request(Request::get(gateway.url("/")).body(Body::empty()).unwrap()))
.await
.unwrap();
first.into_body().collect().await.unwrap();
tokio::time::sleep(idle).await;
let second =
within(client.request(Request::get(gateway.url("/")).body(Body::empty()).unwrap()))
.await
.unwrap();
assert_eq!(second.status(), StatusCode::OK);
}
#[rstest]
#[case::health("/health/liveliness")]
#[case::messages("/v1/messages")]
#[tokio::test]
async fn unreachable_python_is_a_502(#[case] path: &str) {
let gateway = Gateway::start(unreachable_upstream()).await;
let response =
within(client().request(Request::get(gateway.url(path)).body(Body::empty()).unwrap()))
.await
.unwrap();
assert_eq!(response.status(), StatusCode::BAD_GATEWAY);
}
#[rstest]
#[tokio::test]
async fn shutdown_lets_an_in_flight_stream_finish() {
let release = Arc::new(Notify::new());
let released = release.clone();
let upstream = raw_upstream(move |mut python: Raw| {
let released = released.clone();
async move {
python.request_head().await.unwrap();
python
.send("HTTP/1.1 200 OK\r\ntransfer-encoding: chunked\r\n\r\n5\r\nfirst\r\n")
.await;
released.notified().await;
python.send("4\r\nlast\r\n0\r\n\r\n").await;
}
})
.await;
let gateway = Gateway::start(upstream).await;
let response =
within(client().request(Request::get(gateway.url("/")).body(Body::empty()).unwrap()))
.await
.unwrap();
let server = gateway.shutdown();
tokio::time::sleep(Duration::from_millis(100)).await;
assert!(!server.is_finished());
release.notify_one();
let body = within(response.into_body().collect())
.await
.unwrap()
.to_bytes();
assert_eq!(body, "firstlast");
within(server).await.unwrap().unwrap();
}

View file

@ -0,0 +1,337 @@
mod support;
use std::convert::Infallible;
use axum::{
Router,
body::{Body, Bytes},
extract::Request,
http::{HeaderValue, StatusCode},
response::Response,
};
use http_body_util::BodyExt;
use litellm_gateway_forward::PEER_HEADER;
use rstest::rstest;
use support::{Gateway, client, raw_upstream, recording, serve, within};
use tokio::sync::mpsc;
fn ok() -> Response {
Response::new(Body::from("ok"))
}
#[rstest]
#[tokio::test]
async fn forwards_the_request_as_the_client_sent_it_minus_hop_headers() {
let (upstream, mut received) = recording(|| {
Response::builder()
.status(StatusCode::UNAUTHORIZED)
.header("connection", "x-upstream-hop")
.header("x-upstream-hop", "remove")
.header("x-response", "keep")
.body(Body::from("python error"))
.unwrap()
})
.await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send(
"PATCH /v1/messages?x=a%2Fb&x=c HTTP/1.1\r\n\
host: public.example\r\n\
authorization: Bearer test\r\n\
x-forwarded-for: 192.0.2.1\r\n\
x-forwarded-for: 192.0.2.2\r\n\
x-forwarded-proto: https\r\n\
forwarded: for=192.0.2.1;proto=https\r\n\
x-litellm-rust-peer: 10.1.2.3:1\r\n\
connection: x-remove, keep-alive\r\n\
x-remove: remove\r\n\
proxy-authorization: remove\r\n\
te: trailers\r\n\
content-length: 7\r\n\r\npayload",
)
.await;
let head = within(raw.response_head()).await.unwrap();
assert_eq!(head.status, StatusCode::UNAUTHORIZED);
assert_eq!(head.header("x-response"), Some(&b"keep"[..]));
assert_eq!(head.header("x-upstream-hop"), None);
let body = raw.body(head.content_length().unwrap()).await;
assert_eq!(body, b"python error");
let request = received.recv().await.unwrap();
assert_eq!(request.method, "PATCH");
assert_eq!(request.uri, "/v1/messages?x=a%2Fb&x=c");
assert_eq!(request.headers["host"], "public.example");
assert_eq!(request.headers["authorization"], "Bearer test");
let forwarded_for: Vec<_> = request.headers.get_all("x-forwarded-for").iter().collect();
assert_eq!(forwarded_for, ["192.0.2.1", "192.0.2.2"]);
assert_eq!(request.headers["x-forwarded-proto"], "https");
assert_eq!(request.headers["forwarded"], "for=192.0.2.1;proto=https");
let peers: Vec<_> = request.headers.get_all(PEER_HEADER).iter().collect();
assert_eq!(peers, [raw.local_address().to_string().as_str()]);
assert!(!request.headers.contains_key("x-remove"));
assert!(!request.headers.contains_key("proxy-authorization"));
assert!(!request.headers.contains_key("te"));
assert!(!request.headers.contains_key("connection"));
assert_eq!(request.body, "payload");
}
#[rstest]
#[case::get("GET")]
#[case::post("POST")]
#[case::put("PUT")]
#[case::delete("DELETE")]
#[case::options("OPTIONS")]
#[case::extension("PURGE")]
#[tokio::test]
async fn forwards_every_method(#[case] method: &str) {
let (upstream, mut received) = recording(ok).await;
let gateway = Gateway::start(upstream).await;
let response = client()
.request(
Request::builder()
.method(method)
.uri(gateway.url("/mcp"))
.body(Body::from("body"))
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let request = received.recv().await.unwrap();
assert_eq!(request.method, method);
assert_eq!(request.body, "body");
}
#[rstest]
#[case::double_slash("//v1//models")]
#[case::encoded_slash("/v1/files/a%2Fb/content")]
#[case::encoded_query("/v1/models?q=%E2%9C%93&empty=&flag")]
#[case::utf8_bytes_escaped("/mcp/%F0%9F%A6%80")]
#[tokio::test]
async fn forwards_the_request_target_byte_for_byte(#[case] target: &str) {
let (upstream, mut received) = recording(ok).await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send(format!("GET {target} HTTP/1.1\r\nhost: x\r\n\r\n"))
.await;
assert_eq!(
within(raw.response_head()).await.unwrap().status,
StatusCode::OK
);
assert_eq!(received.recv().await.unwrap().uri, target);
}
#[rstest]
#[tokio::test]
async fn absolute_form_targets_reach_python_as_origin_form() {
let (upstream, mut received) = recording(ok).await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send(
"GET http://elsewhere.example/v1/models?x=1 HTTP/1.1\r\nhost: elsewhere.example\r\n\r\n",
)
.await;
assert_eq!(
within(raw.response_head()).await.unwrap().status,
StatusCode::OK
);
let request = received.recv().await.unwrap();
assert_eq!(request.uri, "/v1/models?x=1");
}
#[rstest]
#[tokio::test]
async fn keeps_repeated_response_headers_and_opaque_header_bytes() {
let (upstream, mut received) = recording(|| {
Response::builder()
.header("set-cookie", "a=1; Path=/")
.header("set-cookie", "b=2; HttpOnly")
.header("x-opaque", HeaderValue::from_bytes(b"caf\xe9").unwrap())
.body(Body::empty())
.unwrap()
})
.await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send(b"GET / HTTP/1.1\r\nhost: x\r\nx-opaque: caf\xe9\r\n\r\n")
.await;
let head = within(raw.response_head()).await.unwrap();
let cookies: Vec<_> = head
.headers
.iter()
.filter(|(name, _)| name == "set-cookie")
.map(|(_, value)| value.as_slice())
.collect();
assert_eq!(cookies, [&b"a=1; Path=/"[..], b"b=2; HttpOnly"]);
assert_eq!(head.header("x-opaque"), Some(&b"caf\xe9"[..]));
assert_eq!(
received.recv().await.unwrap().headers["x-opaque"].as_bytes(),
b"caf\xe9"
);
}
#[rstest]
#[tokio::test]
async fn streams_upload_and_response_incrementally_without_a_body_limit() {
let upstream = serve(
Router::new().fallback(|request: Request| async { Response::new(request.into_body()) }),
)
.await;
let gateway = Gateway::start(upstream).await;
let (sender, receiver) = mpsc::channel::<Result<Bytes, Infallible>>(1);
let stream = futures_util::stream::unfold(receiver, |mut receiver| async {
receiver.recv().await.map(|chunk| (chunk, receiver))
});
sender.send(Ok(Bytes::from_static(b"first"))).await.unwrap();
let mut response = within(
client().request(
Request::post(gateway.url("/v1/files"))
.body(Body::from_stream(stream))
.unwrap(),
),
)
.await
.unwrap();
let frame = within(response.body_mut().frame()).await.unwrap().unwrap();
assert_eq!(frame.into_data().unwrap(), "first");
let large = Bytes::from(vec![b'x'; 8 * 1024 * 1024]);
sender.send(Ok(large.clone())).await.unwrap();
drop(sender);
let rest = within(response.into_body().collect())
.await
.unwrap()
.to_bytes();
assert_eq!(rest, large);
}
#[rstest]
#[tokio::test]
async fn answers_expect_continue_so_large_uploads_start() {
let (upstream, mut received) = recording(ok).await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send("POST /v1/audio/transcriptions HTTP/1.1\r\nhost: x\r\nexpect: 100-continue\r\ncontent-length: 4\r\n\r\n")
.await;
let interim = within(raw.response_head()).await.unwrap();
assert_eq!(interim.status, StatusCode::CONTINUE);
raw.send("data").await;
assert_eq!(
within(raw.response_head()).await.unwrap().status,
StatusCode::OK
);
assert_eq!(received.recv().await.unwrap().body, "data");
}
#[rstest]
#[tokio::test]
async fn answers_pipelined_requests_in_order() {
let upstream = serve(
Router::new().fallback(|request: Request| async move { request.uri().path().to_owned() }),
)
.await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send("GET /first HTTP/1.1\r\nhost: x\r\n\r\nHEAD /second HTTP/1.1\r\nhost: x\r\n\r\nGET /third HTTP/1.1\r\nhost: x\r\n\r\n")
.await;
let first = within(raw.response_head()).await.unwrap();
assert_eq!(raw.body(first.content_length().unwrap()).await, b"/first");
let second = within(raw.response_head()).await.unwrap();
assert_eq!(second.content_length(), Some(7));
let third = within(raw.response_head()).await.unwrap();
assert_eq!(raw.body(third.content_length().unwrap()).await, b"/third");
}
#[rstest]
#[case::no_content(StatusCode::NO_CONTENT)]
#[case::not_modified(StatusCode::NOT_MODIFIED)]
#[tokio::test]
async fn bodiless_statuses_keep_the_connection_reusable(#[case] status: StatusCode) {
let upstream = serve(Router::new().fallback(move |request: Request| async move {
match request.uri().path() {
"/next" => (StatusCode::OK, "next"),
_ => (status, ""),
}
}))
.await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send("GET /empty HTTP/1.1\r\nhost: x\r\n\r\nGET /next HTTP/1.1\r\nhost: x\r\n\r\n")
.await;
assert_eq!(within(raw.response_head()).await.unwrap().status, status);
let next = within(raw.response_head()).await.unwrap();
assert_eq!(raw.body(next.content_length().unwrap()).await, b"next");
}
#[rstest]
#[tokio::test]
async fn relays_a_body_delimited_by_the_upstream_closing() {
let upstream = raw_upstream(|mut python| async move {
python.request_head().await.unwrap();
python
.send("HTTP/1.1 200 OK\r\nconnection: close\r\n\r\nuntil eof")
.await;
})
.await;
let gateway = Gateway::start(upstream).await;
let response = client().request(Request::get(gateway.url("/")).body(Body::empty()).unwrap());
let body = within(response).await.unwrap().into_body().collect();
assert_eq!(within(body).await.unwrap().to_bytes(), "until eof");
}
#[rstest]
#[tokio::test]
async fn an_upstream_dying_mid_stream_fails_the_client_body_instead_of_ending_it() {
let upstream = raw_upstream(|mut python| async move {
python.request_head().await.unwrap();
python
.send("HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\ntransfer-encoding: chunked\r\n\r\n6\r\ndata: \r\n")
.await;
})
.await;
let gateway = Gateway::start(upstream).await;
let response =
within(client().request(Request::get(gateway.url("/")).body(Body::empty()).unwrap()))
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert!(within(response.into_body().collect()).await.is_err());
}
#[rstest]
#[tokio::test]
async fn non_websocket_upgrades_reach_python_as_plain_requests() {
let (upstream, mut received) = recording(ok).await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send("GET / HTTP/1.1\r\nhost: x\r\nconnection: upgrade, http2-settings\r\nupgrade: h2c\r\nhttp2-settings: AAMAAABkAAQAoAAAAAIAAAAA\r\n\r\n")
.await;
assert_eq!(
within(raw.response_head()).await.unwrap().status,
StatusCode::OK
);
let request = received.recv().await.unwrap();
assert!(!request.headers.contains_key("upgrade"));
assert!(!request.headers.contains_key("connection"));
assert!(!request.headers.contains_key("http2-settings"));
}
#[rstest]
#[case::get("GET")]
#[case::delete("DELETE")]
#[case::options("OPTIONS")]
#[case::post("POST")]
#[tokio::test]
async fn forwards_a_chunked_body_on_any_method(#[case] method: &str) {
let (upstream, mut received) = recording(ok).await;
let gateway = Gateway::start(upstream).await;
let mut raw = gateway.connect().await;
raw.send(format!(
"{method} /v1/search HTTP/1.1\r\nhost: x\r\ntransfer-encoding: chunked\r\n\r\n4\r\nbody\r\n0\r\n\r\n"
))
.await;
assert_eq!(
within(raw.response_head()).await.unwrap().status,
StatusCode::OK
);
assert_eq!(received.recv().await.unwrap().body, "body");
}

View file

@ -0,0 +1,203 @@
mod support;
use std::{
convert::Infallible,
sync::{Arc, Mutex},
};
use axum::{
body::{Body, Bytes},
http::{HeaderMap, HeaderName, HeaderValue, Method, Request, StatusCode},
response::Response,
};
use http_body_util::BodyExt;
use litellm_gateway_forward::PEER_HEADER;
use proptest::{prelude::*, test_runner::TestRunner};
use support::{Gateway, client, recording};
#[derive(Clone, Debug)]
struct Message {
headers: Vec<(String, Vec<Vec<u8>>)>,
body: Vec<u8>,
chunked: bool,
}
#[derive(Clone, Debug)]
struct Exchange {
method: Method,
target: String,
request: Message,
status: StatusCode,
response: Message,
}
fn header_value() -> impl Strategy<Value = Vec<u8>> {
prop::collection::vec(prop_oneof![0x21u8..=0x7e, 0x80u8..=0xff], 1..24)
}
fn message() -> impl Strategy<Value = Message> {
(
prop::collection::btree_map(
"x-[a-z0-9-]{1,12}",
prop::collection::vec(header_value(), 1..4),
0..12,
),
prop::collection::vec(any::<u8>(), 0..32 * 1024),
any::<bool>(),
)
.prop_map(|(headers, body, chunked)| Message {
headers: headers.into_iter().collect(),
body,
chunked,
})
}
fn target() -> impl Strategy<Value = String> {
let segment = prop_oneof!["[A-Za-z0-9._~!$&'()*+,;=:@-]{0,8}", "%[0-9A-F]{2}"];
(
prop::collection::vec(segment, 0..5),
prop::option::of("[A-Za-z0-9=&._~-]{0,20}"),
)
.prop_map(|(segments, query)| {
let path = format!("/{}", segments.join("/"));
match query {
Some(query) => format!("{path}?{query}"),
None => path,
}
})
}
fn exchange() -> impl Strategy<Value = Exchange> {
let method = prop_oneof![
Just(Method::GET),
Just(Method::POST),
Just(Method::PUT),
Just(Method::PATCH),
Just(Method::DELETE),
Just(Method::OPTIONS),
Just(Method::from_bytes(b"PURGE").unwrap()),
];
let status = (200u16..600)
.prop_filter("bodiless status", |code| ![204, 205, 304].contains(code))
.prop_map(|code| StatusCode::from_u16(code).unwrap());
(method, target(), message(), status, message()).prop_map(
|(method, target, request, status, response)| Exchange {
method,
target,
request,
status,
response,
},
)
}
fn body(message: &Message) -> Body {
if !message.chunked {
return Body::from(message.body.clone());
}
let chunks: Vec<Result<Bytes, Infallible>> = message
.body
.chunks(1000)
.map(|chunk| Ok(Bytes::copy_from_slice(chunk)))
.collect();
Body::from_stream(futures_util::stream::iter(chunks))
}
fn apply(headers: &mut HeaderMap, message: &Message) {
if message.chunked {
headers.insert("transfer-encoding", HeaderValue::from_static("chunked"));
}
for (name, values) in &message.headers {
for value in values {
headers.append(
HeaderName::from_bytes(name.as_bytes()).unwrap(),
HeaderValue::from_bytes(value).unwrap(),
);
}
}
}
fn assert_carried(headers: &HeaderMap, message: &Message, framing_and_hop: &[&str]) {
for (name, values) in &message.headers {
let carried: Vec<&[u8]> = headers
.get_all(name)
.iter()
.map(HeaderValue::as_bytes)
.collect();
let sent: Vec<&[u8]> = values.iter().map(Vec::as_slice).collect();
assert_eq!(carried, sent, "header {name}");
}
for name in headers.keys() {
assert!(
framing_and_hop.contains(&name.as_str())
|| message
.headers
.iter()
.any(|(sent, _)| sent == name.as_str()),
"unexpected header {name}"
);
}
}
/// Any request a client can send and any response Python can give cross the forwarder unchanged,
/// apart from the framing and peer headers the forwarder owns.
#[test]
fn every_exchange_crosses_the_forwarder_unchanged() {
let runtime = tokio::runtime::Runtime::new().unwrap();
let current = Arc::new(Mutex::new(None::<Exchange>));
let responding = current.clone();
let (gateway, received) = runtime.block_on(async {
let (upstream, received) = recording(move || {
let exchange = responding.lock().unwrap().clone().unwrap();
let mut response = Response::new(body(&exchange.response));
*response.status_mut() = exchange.status;
apply(response.headers_mut(), &exchange.response);
response
})
.await;
(
Gateway::start(upstream).await,
tokio::sync::Mutex::new(received),
)
});
let client = client();
TestRunner::new(ProptestConfig::with_cases(256))
.run(&exchange(), |exchange| {
*current.lock().unwrap() = Some(exchange.clone());
runtime.block_on(async {
while received.lock().await.try_recv().is_ok() {}
let mut request = Request::builder()
.method(exchange.method.clone())
.uri(gateway.url(&exchange.target))
.body(body(&exchange.request))
.unwrap();
apply(request.headers_mut(), &exchange.request);
let response = support::within(client.request(request)).await.unwrap();
let python = received.lock().await.recv().await.unwrap();
assert_eq!(python.method, exchange.method);
assert_eq!(python.uri, exchange.target.as_str());
assert_eq!(python.body, exchange.request.body);
assert_carried(
&python.headers,
&exchange.request,
&["host", "content-length", "transfer-encoding", PEER_HEADER],
);
assert_eq!(python.headers.get_all(PEER_HEADER).iter().count(), 1);
assert_eq!(response.status(), exchange.status);
let headers = response.headers().clone();
assert_carried(
&headers,
&exchange.response,
&["date", "content-length", "transfer-encoding"],
);
let body = support::within(response.into_body().collect())
.await
.unwrap();
assert_eq!(body.to_bytes(), exchange.response.body);
});
Ok(())
})
.unwrap();
}

View file

@ -0,0 +1,299 @@
#![allow(
dead_code,
reason = "each test binary uses a different subset of the harness"
)]
use std::{future::Future, net::SocketAddr, time::Duration};
use axum::{
Router,
body::{Body, Bytes},
extract::Request,
http::{HeaderMap, Method, StatusCode, Uri},
};
use http_body_util::BodyExt;
use hyper_util::{
client::legacy::{Client, connect::HttpConnector},
rt::TokioExecutor,
};
use litellm_gateway_forward::Forward;
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::{TcpListener, TcpStream},
sync::{mpsc, oneshot},
task::JoinHandle,
};
pub const WAIT: Duration = Duration::from_secs(5);
pub const UVICORN_KEEPALIVE: Duration = Duration::from_secs(5);
pub async fn within<T>(future: impl Future<Output = T>) -> T {
tokio::time::timeout(WAIT, future).await.expect("timed out")
}
/// A running forwarder in front of `upstream`, listening on a real socket like production.
pub struct Gateway {
pub address: SocketAddr,
stop: oneshot::Sender<()>,
server: JoinHandle<std::io::Result<()>>,
}
impl Gateway {
pub async fn start(upstream: SocketAddr) -> Self {
Self::with_keepalive(upstream, UVICORN_KEEPALIVE).await
}
pub async fn with_keepalive(upstream: SocketAddr, keepalive: Duration) -> Self {
let forward = Forward::new(&format!("http://{upstream}"), keepalive).unwrap();
let public = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = public.local_addr().unwrap();
let (stop, stopped) = oneshot::channel::<()>();
let server = tokio::spawn(forward.serve(public, async {
stopped.await.ok();
}));
Self {
address,
stop,
server,
}
}
pub fn url(&self, path_and_query: &str) -> Uri {
format!("http://{}{path_and_query}", self.address)
.parse()
.unwrap()
}
pub async fn connect(&self) -> Raw {
Raw::new(TcpStream::connect(self.address).await.unwrap())
}
/// Starts graceful shutdown and returns the server task, which ends once in-flight work drains.
pub fn shutdown(self) -> JoinHandle<std::io::Result<()>> {
self.stop.send(()).unwrap();
self.server
}
}
pub fn client() -> Client<HttpConnector, Body> {
Client::builder(TokioExecutor::new()).build_http()
}
/// What the upstream received, after the forwarder rewrote it.
pub struct Received {
pub method: Method,
pub uri: Uri,
pub headers: HeaderMap,
pub body: Bytes,
}
/// An axum upstream that records every request it fully reads and answers with `respond`.
pub async fn recording(
respond: impl Fn() -> axum::response::Response + Clone + Send + Sync + 'static,
) -> (SocketAddr, mpsc::UnboundedReceiver<Received>) {
let (sender, receiver) = mpsc::unbounded_channel();
let address = serve(Router::new().fallback(move |request: Request| {
let sender = sender.clone();
let respond = respond.clone();
async move {
let (parts, body) = request.into_parts();
let body = body.collect().await.unwrap().to_bytes();
sender
.send(Received {
method: parts.method,
uri: parts.uri,
headers: parts.headers,
body,
})
.unwrap();
respond()
}
}))
.await;
(address, receiver)
}
pub async fn serve(router: Router) -> SocketAddr {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });
address
}
/// An upstream that hands each accepted connection to `handle` as raw bytes, for behavior a
/// well-behaved HTTP server would never produce.
pub async fn raw_upstream<F, Fut>(handle: F) -> SocketAddr
where
F: Fn(Raw) -> Fut + Send + Sync + 'static,
Fut: Future<Output = ()> + Send + 'static,
{
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
tokio::spawn(async move {
loop {
let (stream, _) = listener.accept().await.unwrap();
tokio::spawn(handle(Raw::new(stream)));
}
});
address
}
pub fn unreachable_upstream() -> SocketAddr {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
listener.local_addr().unwrap()
}
pub struct Head {
pub status: StatusCode,
pub headers: Vec<(String, Vec<u8>)>,
pub path: String,
}
impl Head {
pub fn header(&self, name: &str) -> Option<&[u8]> {
self.headers
.iter()
.find(|(key, _)| key.eq_ignore_ascii_case(name))
.map(|(_, value)| value.as_slice())
}
pub fn content_length(&self) -> Option<usize> {
self.header("content-length")
.map(|value| std::str::from_utf8(value).unwrap().parse().unwrap())
}
}
/// One TCP connection driven byte by byte, so tests control framing, timing and disconnects.
/// Bytes read past a message head stay buffered for the next read.
pub struct Raw {
stream: TcpStream,
buffer: Vec<u8>,
}
impl Raw {
pub fn new(stream: TcpStream) -> Self {
Self {
stream,
buffer: Vec::new(),
}
}
pub fn into_stream(self) -> TcpStream {
assert!(self.buffer.is_empty(), "buffered bytes would be lost");
self.stream
}
pub fn local_address(&self) -> SocketAddr {
self.stream.local_addr().unwrap()
}
pub async fn send(&mut self, bytes: impl AsRef<[u8]>) {
self.stream.write_all(bytes.as_ref()).await.unwrap();
}
/// Reads one request head, or `None` when the peer closed the connection first.
pub async fn request_head(&mut self) -> Option<Head> {
self.head(|bytes| {
let mut headers = [httparse::EMPTY_HEADER; 256];
let mut request = httparse::Request::new(&mut headers);
let httparse::Status::Complete(length) = request.parse(bytes).unwrap() else {
return None;
};
Some((
length,
Head {
status: StatusCode::OK,
headers: owned(request.headers),
path: request.path.unwrap().to_owned(),
},
))
})
.await
}
pub async fn response_head(&mut self) -> Option<Head> {
self.head(|bytes| {
let mut headers = [httparse::EMPTY_HEADER; 256];
let mut response = httparse::Response::new(&mut headers);
let httparse::Status::Complete(length) = response.parse(bytes).unwrap() else {
return None;
};
Some((
length,
Head {
status: StatusCode::from_u16(response.code.unwrap()).unwrap(),
headers: owned(response.headers),
path: String::new(),
},
))
})
.await
}
async fn head(&mut self, parse: impl Fn(&[u8]) -> Option<(usize, Head)>) -> Option<Head> {
loop {
if let Some((length, head)) = parse(&self.buffer) {
self.buffer.drain(..length);
return Some(head);
}
if self.fill().await == 0 {
return None;
}
}
}
/// Reads exactly `length` body bytes, using what is already buffered first.
pub async fn body(&mut self, length: usize) -> Vec<u8> {
while self.buffer.len() < length {
assert_ne!(self.fill().await, 0, "closed mid-body");
}
self.buffer.drain(..length).collect()
}
/// Reads a whole chunked body and returns its decoded bytes.
pub async fn chunked_body(&mut self) -> Vec<u8> {
let mut decoded = Vec::new();
loop {
let size_line = self.line().await;
let size =
usize::from_str_radix(size_line.split(';').next().unwrap().trim(), 16).unwrap();
if size == 0 {
while !self.line().await.is_empty() {}
return decoded;
}
decoded.extend(self.body(size).await);
assert_eq!(self.body(2).await, b"\r\n");
}
}
async fn line(&mut self) -> String {
loop {
if let Some(end) = self.buffer.windows(2).position(|window| window == b"\r\n") {
let line = String::from_utf8(self.buffer[..end].to_vec()).unwrap();
self.buffer.drain(..end + 2);
return line;
}
assert_ne!(self.fill().await, 0, "closed mid-line");
}
}
async fn fill(&mut self) -> usize {
let mut chunk = [0; 8192];
let read = self.stream.read(&mut chunk).await.unwrap_or(0);
self.buffer.extend_from_slice(&chunk[..read]);
read
}
/// Resolves once the peer closes the connection, discarding anything it still sends.
pub async fn closed(&mut self) {
let mut chunk = [0; 8192];
while self.stream.read(&mut chunk).await.unwrap_or(0) != 0 {}
}
}
fn owned(headers: &[httparse::Header<'_>]) -> Vec<(String, Vec<u8>)> {
headers
.iter()
.map(|header| (header.name.to_owned(), header.value.to_vec()))
.collect()
}

View file

@ -0,0 +1,23 @@
use std::time::Duration;
use litellm_gateway_forward::Forward;
use rstest::rstest;
#[rstest]
#[case::https("https://127.0.0.1:4000")]
#[case::public("http://192.0.2.1:4000")]
#[case::hostname("http://localhost:4000")]
#[case::ipv6("http://[::1]:4000")]
#[case::path("http://127.0.0.1:4000/api")]
#[case::query("http://127.0.0.1:4000/?x=y")]
#[case::credentials("http://user@127.0.0.1:4000")]
fn rejects_anything_but_a_loopback_http_origin(#[case] upstream: &str) {
assert!(Forward::new(upstream, Duration::from_secs(5)).is_err());
}
#[rstest]
#[case::standard("http://127.0.0.1:4000")]
#[case::loopback_range("http://127.0.0.2:4000/")]
fn accepts_a_loopback_http_origin(#[case] upstream: &str) {
assert!(Forward::new(upstream, Duration::from_secs(5)).is_ok());
}

View file

@ -0,0 +1,186 @@
mod support;
use std::{
net::SocketAddr,
time::{Duration, Instant},
};
use axum::{
Router,
http::{HeaderValue, StatusCode},
response::IntoResponse,
};
use futures_util::{SinkExt, StreamExt};
use litellm_gateway_forward::PEER_HEADER;
use rstest::rstest;
use support::{Gateway, raw_upstream, serve, within};
use tokio::net::TcpStream;
use tokio_tungstenite::{
WebSocketStream, accept_hdr_async, client_async,
tungstenite::{
Error, Message,
client::IntoClientRequest,
handshake::server::{ErrorResponse, Request as Handshake, Response as Accepted},
protocol::{CloseFrame, frame::coding::CloseCode},
},
};
async fn connect(
address: SocketAddr,
connection: &'static str,
) -> Result<WebSocketStream<TcpStream>, Box<Error>> {
let mut request = format!("ws://{address}/v1/realtime?model=m")
.into_client_request()
.unwrap();
let headers = request.headers_mut();
headers.insert("authorization", HeaderValue::from_static("Bearer test"));
headers.insert(
"sec-websocket-protocol",
HeaderValue::from_static("realtime"),
);
headers.insert("connection", HeaderValue::from_static(connection));
let stream = TcpStream::connect(address).await.unwrap();
let (socket, response) = client_async(request, stream).await.map_err(Box::new)?;
assert_eq!(response.headers()["sec-websocket-protocol"], "realtime");
Ok(socket)
}
/// Greets, echoes every message, and closes with 4000 when told to "bye".
#[expect(
clippy::result_large_err,
reason = "tungstenite's handshake callback returns ErrorResponse"
)]
async fn echo() -> SocketAddr {
raw_upstream(|python| async move {
let callback = |request: &Handshake, mut response: Accepted| {
assert_eq!(request.uri(), "/v1/realtime?model=m");
assert_eq!(request.headers()["authorization"], "Bearer test");
assert!(request.headers().contains_key(PEER_HEADER));
response.headers_mut().insert(
"sec-websocket-protocol",
HeaderValue::from_static("realtime"),
);
Ok::<_, ErrorResponse>(response)
};
let mut socket = accept_hdr_async(python.into_stream(), callback)
.await
.unwrap();
socket.send(Message::text("greeting")).await.unwrap();
while let Some(Ok(message)) = socket.next().await {
if message == Message::text("bye") {
socket
.close(Some(CloseFrame {
code: CloseCode::Library(4000),
reason: "done".into(),
}))
.await
.unwrap();
continue;
}
if message.is_close() {
break;
}
socket.send(message).await.unwrap();
}
})
.await
}
#[rstest]
#[tokio::test]
async fn relays_messages_both_ways(
#[values("Upgrade", "keep-alive, Upgrade", "upgrade")] connection: &'static str,
#[values(
Message::text("hello"),
Message::binary(vec![0, 1, 2]),
Message::binary(vec![7; 4 * 1024 * 1024])
)]
message: Message,
) {
let gateway = Gateway::start(echo().await).await;
let mut socket = within(connect(gateway.address, connection)).await.unwrap();
assert_eq!(
socket.next().await.unwrap().unwrap(),
Message::text("greeting")
);
socket.send(message.clone()).await.unwrap();
assert_eq!(within(socket.next()).await.unwrap().unwrap(), message);
socket.close(None).await.unwrap();
while socket.next().await.is_some() {}
drop(socket);
within(gateway.shutdown()).await.unwrap().unwrap();
}
#[rstest]
#[tokio::test]
async fn relays_a_close_python_initiates() {
let gateway = Gateway::start(echo().await).await;
let mut socket = within(connect(gateway.address, "Upgrade")).await.unwrap();
socket.next().await.unwrap().unwrap();
socket.send(Message::text("bye")).await.unwrap();
let Message::Close(Some(frame)) = within(socket.next()).await.unwrap().unwrap() else {
panic!("expected python's close frame");
};
assert_eq!(frame.code, CloseCode::Library(4000));
assert_eq!(frame.reason, "done");
}
#[rstest]
#[tokio::test]
async fn passes_an_upstream_rejection_through() {
let upstream = serve(
Router::new()
.fallback(|| async { (StatusCode::FORBIDDEN, "origin not allowed").into_response() }),
)
.await;
let gateway = Gateway::start(upstream).await;
let error = within(connect(gateway.address, "Upgrade"))
.await
.unwrap_err();
let Error::Http(response) = *error else {
panic!("expected the upstream rejection, got {error}");
};
assert_eq!(response.status(), StatusCode::FORBIDDEN);
assert_eq!(response.body().as_deref(), Some(&b"origin not allowed"[..]));
}
#[rstest]
#[tokio::test]
async fn shutdown_closes_open_sockets_after_drain() {
let gateway = Gateway::start(echo().await).await;
let mut socket = within(connect(gateway.address, "Upgrade")).await.unwrap();
socket.next().await.unwrap().unwrap();
let started = Instant::now();
tokio::time::timeout(Duration::from_secs(10), gateway.shutdown())
.await
.unwrap()
.unwrap()
.unwrap();
assert!(started.elapsed() >= Duration::from_secs(4));
assert!(!matches!(socket.next().await, Some(Ok(Message::Text(_)))));
}
#[rstest]
#[tokio::test]
async fn refuses_new_sockets_while_draining() {
let gateway = Gateway::start(echo().await).await;
let mut open = within(connect(gateway.address, "Upgrade")).await.unwrap();
open.next().await.unwrap().unwrap();
let address = gateway.address;
let server = gateway.shutdown();
tokio::time::sleep(Duration::from_millis(100)).await;
assert!(
TcpStream::connect(address).await.is_err() || connect(address, "Upgrade").await.is_err()
);
open.send(Message::text("still open")).await.unwrap();
assert_eq!(
within(open.next()).await.unwrap().unwrap(),
Message::text("still open")
);
drop(open);
tokio::time::timeout(Duration::from_secs(10), server)
.await
.unwrap()
.unwrap()
.unwrap();
}

View file

@ -10,12 +10,11 @@ litellm-secret-value.workspace = true
axum.workspace = true
envy = "0.4.2"
http-body-util = "0.1"
hyper = { version = "1", features = ["http1"] }
hyper-util = { workspace = true, features = ["client-legacy", "http1", "tokio"] }
litellm-inference.workspace = true
litellm-gateway-inference.workspace = true
litellm-gateway-forward.workspace = true
litellm-gateway-mcp.workspace = true
tokio-util = { version = "0.7", features = ["rt"] }
tokio-util = "0.7"
thiserror.workspace = true
futures-util.workspace = true
litellm-gateway-auth.workspace = true
@ -31,7 +30,7 @@ litellm-tracing.workspace = true
serde_json.workspace = true
serde.workspace = true
tracing.workspace = true
tokio = { workspace = true, features = ["signal", "io-util"] }
tokio = { workspace = true, features = ["signal"] }
uuid.workspace = true
tower-sessions-moka-store = "0.15.0"
@ -41,5 +40,4 @@ base64.workspace = true
rstest.workspace = true
tempfile.workspace = true
tokio = { workspace = true, features = ["sync"] }
tokio-tungstenite.workspace = true
tower = { version = "0.5", features = ["util"] }

View file

@ -1,11 +1,5 @@
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("invalid forwarding upstream URI")]
ForwardUri(#[source] axum::http::uri::InvalidUri),
#[error(
"LITELLM_FORWARD_UPSTREAM must be a loopback IPv4 http origin without a path, query or credentials"
)]
ForwardUpstream,
#[error(transparent)]
Http(#[from] litellm_http::Error),
#[error("environment_variables values must be strings, numbers or booleans")]

View file

@ -1,371 +0,0 @@
use std::net::{Ipv4Addr, SocketAddr};
use axum::{
Router,
body::Body,
extract::{ConnectInfo, DefaultBodyLimit, Request, State},
http::{HeaderMap, HeaderValue, StatusCode, Uri, Version, header},
response::Response,
};
use hyper_util::{
client::legacy::{Client, connect::HttpConnector},
rt::TokioExecutor,
};
use tokio::net::TcpListener;
use crate::Error;
use websocket::Upgrades;
mod websocket;
pub const PEER_HEADER: &str = "x-litellm-rust-peer";
#[derive(Clone)]
pub struct Forward {
upstream: Uri,
client: Client<HttpConnector, Body>,
upgrades: Upgrades,
}
impl Forward {
pub fn new(upstream: &str) -> Result<Self, Error> {
let upstream: Uri = upstream.parse().map_err(Error::ForwardUri)?;
if upstream.scheme_str() != Some("http")
|| !upstream
.host()
.and_then(|host| host.parse::<Ipv4Addr>().ok())
.is_some_and(|ip| ip.is_loopback())
|| upstream
.authority()
.is_some_and(|authority| authority.as_str().contains('@'))
|| upstream.path() != "/"
|| upstream.query().is_some()
{
return Err(Error::ForwardUpstream);
}
let client = Client::builder(TokioExecutor::new())
.retry_canceled_requests(false)
.build_http();
Ok(Self {
upstream,
client,
upgrades: Upgrades::default(),
})
}
pub fn router(self) -> Router {
Router::new()
.fallback(forward)
.layer(DefaultBodyLimit::disable())
.with_state(self)
}
/// Serves until `shutdown` resolves, then gives open WebSockets a bounded drain before closing them.
pub async fn serve(
self,
listener: TcpListener,
shutdown: impl Future<Output = ()> + Send + 'static,
) -> std::io::Result<()> {
let upgrades = self.upgrades.clone();
let _close_on_drop = upgrades.close_on_drop();
let draining = upgrades.clone();
let result = axum::serve(
listener,
self.router()
.into_make_service_with_connect_info::<SocketAddr>(),
)
.with_graceful_shutdown(async move {
shutdown.await;
draining.begin_shutdown();
})
.await;
if result.is_err() {
upgrades.close();
}
upgrades.wait().await;
result
}
}
async fn forward(
State(state): State<Forward>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
mut request: Request,
) -> Result<Response, StatusCode> {
let downstream = state.upgrades.take_handshake(&mut request)?;
let mut uri = state.upstream.into_parts();
uri.path_and_query = request.uri().path_and_query().cloned();
*request.uri_mut() = Uri::from_parts(uri).map_err(|_| StatusCode::BAD_GATEWAY)?;
*request.version_mut() = Version::HTTP_11;
let headers = request.headers_mut();
strip_hop_headers(headers);
if downstream.is_some() {
websocket::restore_handshake_headers(headers);
}
// Forwarding headers pass through untouched so Python sees the request as if the client
// connected to it directly. Inserting replaces any client-sent copy: the peer is the one
// value a client must not choose.
headers.insert(
PEER_HEADER,
HeaderValue::from_str(&peer.to_string()).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?,
);
let response = state.client.request(request);
let mut response = match downstream {
Some(_) => state.upgrades.until_closed(response).await?,
None => response.await,
}
.map_err(|error| {
tracing::warn!(%error, "python proxy unreachable");
StatusCode::BAD_GATEWAY
})?;
if response.status() == StatusCode::SWITCHING_PROTOCOLS {
return state.upgrades.switch(downstream, response).await;
}
strip_hop_headers(response.headers_mut());
Ok(response.map(Body::new))
}
// Per-connection headers (RFC 9110 section 7.6.1) describe the client's connection to Rust, not
// Rust's connection to Python, so a proxy must drop them instead of forwarding them.
fn strip_hop_headers(headers: &mut HeaderMap) {
let connection_headers: Vec<_> = headers
.get_all(header::CONNECTION)
.iter()
.filter_map(|value| value.to_str().ok())
.flat_map(|value| value.split(','))
.filter_map(|name| header::HeaderName::from_bytes(name.trim().as_bytes()).ok())
.collect();
for name in connection_headers {
headers.remove(name);
}
for name in [
"connection",
"keep-alive",
"proxy-authenticate",
"proxy-authorization",
"te",
"trailer",
"transfer-encoding",
"upgrade",
"proxy-connection",
] {
headers.remove(name);
}
}
#[cfg(test)]
mod tests {
use super::*;
use axum::{body::Bytes, http::Version};
use http_body_util::BodyExt;
use rstest::rstest;
use std::{convert::Infallible, time::Duration};
use tokio::{net::TcpListener, sync::mpsc};
use tower::ServiceExt;
#[rstest]
#[case::https("https://127.0.0.1:4000")]
#[case::public("http://192.0.2.1:4000")]
#[case::hostname("http://localhost:4000")]
#[case::ipv6("http://[::1]:4000")]
#[case::path("http://127.0.0.1:4000/api")]
#[case::query("http://127.0.0.1:4000/?x=y")]
#[case::credentials("http://user@127.0.0.1:4000")]
fn rejects_invalid_upstream(#[case] upstream: &str) {
assert!(Forward::new(upstream).is_err());
}
#[rstest]
#[case::standard("http://127.0.0.1:4000")]
#[case::loopback_range("http://127.0.0.2:4000/")]
fn accepts_loopback_origin(#[case] upstream: &str) {
assert!(Forward::new(upstream).is_ok());
}
#[rstest]
#[tokio::test]
async fn preserves_request_and_response_without_hop_headers() {
let upstream = TcpListener::bind("127.0.0.1:0").await.unwrap();
let origin = format!("http://{}", upstream.local_addr().unwrap());
let task = tokio::spawn(async move {
axum::serve(
upstream,
Router::new().fallback(|request: Request| async {
assert_eq!(request.method(), "PATCH");
assert_eq!(request.uri(), "/v1/messages?x=a%2Fb&x=c");
assert_eq!(request.headers()["host"], "public.example");
assert_eq!(request.headers()["authorization"], "Bearer test");
assert_eq!(
request
.headers()
.get_all("x-forwarded-for")
.iter()
.collect::<Vec<_>>(),
["192.0.2.1", "192.0.2.2"]
);
assert_eq!(request.headers()["x-forwarded-proto"], "https");
assert_eq!(request.headers()["forwarded"], "for=192.0.2.1;proto=https");
assert_eq!(
request
.headers()
.get_all(PEER_HEADER)
.iter()
.collect::<Vec<_>>(),
["198.51.100.5:1234"]
);
assert!(!request.headers().contains_key("x-remove"));
assert!(!request.headers().contains_key("proxy-authorization"));
assert_eq!(
request.into_body().collect().await.unwrap().to_bytes(),
"payload"
);
Response::builder()
.status(StatusCode::UNAUTHORIZED)
.header("connection", "x-upstream-hop")
.header("x-upstream-hop", "remove")
.header("x-response", "keep")
.body(Body::from("python error"))
.unwrap()
}),
)
.await
.unwrap();
});
let request = Request::builder()
.method("PATCH")
.version(Version::HTTP_2)
.uri("/v1/messages?x=a%2Fb&x=c")
.header("host", "public.example")
.header("authorization", "Bearer test")
.header("x-forwarded-for", "192.0.2.1")
.header("x-forwarded-for", "192.0.2.2")
.header("x-forwarded-proto", "https")
.header("forwarded", "for=192.0.2.1;proto=https")
.header(PEER_HEADER, "10.1.2.3:1")
.header(PEER_HEADER, "10.1.2.4:1")
.header("connection", "x-remove, keep-alive")
.header("x-remove", "remove")
.header("proxy-authorization", "remove")
.extension(ConnectInfo(
"198.51.100.5:1234".parse::<SocketAddr>().unwrap(),
))
.body(Body::from("payload"))
.unwrap();
let response = Forward::new(&origin)
.unwrap()
.router()
.oneshot(request)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
assert_eq!(response.headers()["x-response"], "keep");
assert!(!response.headers().contains_key("connection"));
assert!(!response.headers().contains_key("x-upstream-hop"));
assert_eq!(
response.into_body().collect().await.unwrap().to_bytes(),
"python error"
);
task.abort();
}
#[rstest]
#[case::health("/health/liveliness")]
#[case::readiness("/health/readiness")]
#[case::messages("/v1/messages")]
#[tokio::test]
async fn unreachable_upstream_is_502(#[case] path: &str) {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let origin = format!("http://{}", listener.local_addr().unwrap());
drop(listener);
let response = Forward::new(&origin)
.unwrap()
.router()
.oneshot(
Request::builder()
.uri(path)
.extension(ConnectInfo(
"198.51.100.5:1234".parse::<SocketAddr>().unwrap(),
))
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::BAD_GATEWAY);
}
#[rstest]
#[tokio::test]
async fn streams_upload_and_response_before_eof_without_body_limit() {
let upstream = TcpListener::bind("127.0.0.1:0").await.unwrap();
let origin = format!("http://{}", upstream.local_addr().unwrap());
let upstream_task = tokio::spawn(async move {
axum::serve(
upstream,
Router::new().fallback(|request: Request| async {
let headers = request.headers();
assert!(!headers.contains_key("x-forwarded-for"));
assert!(!headers.contains_key("x-forwarded-proto"));
assert!(
headers[PEER_HEADER]
.to_str()
.unwrap()
.starts_with("127.0.0.1:")
);
Response::new(request.into_body())
}),
)
.await
.unwrap();
});
let public = TcpListener::bind("127.0.0.1:0").await.unwrap();
let public_uri = format!("http://{}/chat/completions", public.local_addr().unwrap());
let forward_task = tokio::spawn(async move {
axum::serve(
public,
Forward::new(&origin)
.unwrap()
.router()
.into_make_service_with_connect_info::<SocketAddr>(),
)
.await
.unwrap();
});
let (sender, receiver) = mpsc::channel::<Result<Bytes, Infallible>>(1);
let stream = futures_util::stream::unfold(receiver, |mut receiver| async {
receiver.recv().await.map(|chunk| (chunk, receiver))
});
sender.send(Ok(Bytes::from_static(b"first"))).await.unwrap();
let client: Client<HttpConnector, Body> =
Client::builder(TokioExecutor::new()).build_http();
let mut response = tokio::time::timeout(
Duration::from_secs(5),
client.request(
Request::post(public_uri)
.body(Body::from_stream(stream))
.unwrap(),
),
)
.await
.unwrap()
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let frame = tokio::time::timeout(Duration::from_secs(5), response.body_mut().frame())
.await
.unwrap()
.unwrap()
.unwrap();
assert_eq!(frame.into_data().unwrap(), "first");
let large = Bytes::from(vec![b'x'; 3 * 1024 * 1024]);
sender.send(Ok(large.clone())).await.unwrap();
drop(sender);
let rest = tokio::time::timeout(Duration::from_secs(5), response.into_body().collect())
.await
.unwrap()
.unwrap()
.to_bytes();
assert_eq!(rest, large);
upstream_task.abort();
forward_task.abort();
}
}

View file

@ -1,297 +0,0 @@
use std::time::Duration;
use axum::{
body::Body,
extract::Request,
http::{HeaderMap, HeaderValue, Method, StatusCode, Version, header},
response::Response,
};
use hyper::{
body::Incoming,
upgrade::{OnUpgrade, Upgraded},
};
use hyper_util::rt::TokioIo;
use tokio_util::{
sync::{CancellationToken, DropGuard},
task::TaskTracker,
};
const DRAIN_TIMEOUT: Duration = Duration::from_secs(5);
#[derive(Clone, Default)]
pub(super) struct Upgrades {
tasks: TaskTracker,
draining: CancellationToken,
closed: CancellationToken,
}
impl Upgrades {
pub fn begin_shutdown(&self) {
self.draining.cancel();
let closed = self.closed.clone();
tokio::spawn(async move {
tokio::time::sleep(DRAIN_TIMEOUT).await;
closed.cancel();
});
}
pub fn take_handshake(&self, request: &mut Request) -> Result<Option<OnUpgrade>, StatusCode> {
if request.method() != Method::GET
|| request.version() != Version::HTTP_11
|| !is_handshake(request.headers())
{
return Ok(None);
}
if self.draining.is_cancelled() {
return Err(StatusCode::SERVICE_UNAVAILABLE);
}
Ok(Some(hyper::upgrade::on(request)))
}
pub async fn until_closed<T>(&self, future: impl Future<Output = T>) -> Result<T, StatusCode> {
tokio::select! {
_ = self.closed.cancelled() => Err(StatusCode::SERVICE_UNAVAILABLE),
output = future => Ok(output),
}
}
pub async fn switch(
&self,
downstream: Option<OnUpgrade>,
mut response: Response<Incoming>,
) -> Result<Response, StatusCode> {
let Some(downstream) = downstream else {
return Err(StatusCode::BAD_GATEWAY);
};
if !is_handshake(response.headers()) {
return Err(StatusCode::BAD_GATEWAY);
}
let upstream = self
.until_closed(hyper::upgrade::on(&mut response))
.await?
.map_err(|error| {
tracing::warn!(%error, "python proxy websocket upgrade failed");
StatusCode::BAD_GATEWAY
})?;
super::strip_hop_headers(response.headers_mut());
restore_handshake_headers(response.headers_mut());
self.relay(downstream, upstream);
Ok(response.map(|_| Body::empty()))
}
pub fn close(&self) {
self.closed.cancel();
}
pub fn close_on_drop(&self) -> DropGuard {
self.closed.clone().drop_guard()
}
pub async fn wait(&self) {
self.tasks.close();
self.tasks.wait().await;
}
fn relay(&self, downstream: OnUpgrade, upstream: Upgraded) {
let closed = self.closed.clone();
self.tasks.spawn(async move {
tokio::select! {
_ = closed.cancelled() => {}
_ = async {
let Ok(downstream) = downstream.await else {
tracing::debug!("websocket upgrade did not complete");
return;
};
let mut downstream = TokioIo::new(downstream);
let mut upstream = TokioIo::new(upstream);
if let Err(error) = tokio::io::copy_bidirectional(&mut downstream, &mut upstream).await {
tracing::debug!(%error, "websocket relay disconnected");
}
} => {}
}
});
}
}
fn is_handshake(headers: &HeaderMap) -> bool {
headers
.get(header::UPGRADE)
.is_some_and(|value| value.as_bytes().eq_ignore_ascii_case(b"websocket"))
&& headers
.get_all(header::CONNECTION)
.iter()
.filter_map(|value| value.to_str().ok())
.flat_map(|value| value.split(','))
.any(|token| token.trim().eq_ignore_ascii_case("upgrade"))
}
// Hop-by-hop stripping drops the handshake's Connection and Upgrade, so each hop gets them back.
pub(super) fn restore_handshake_headers(headers: &mut HeaderMap) {
headers.insert(header::CONNECTION, HeaderValue::from_static("upgrade"));
headers.insert(header::UPGRADE, HeaderValue::from_static("websocket"));
}
#[cfg(test)]
mod tests {
use super::super::{Forward, PEER_HEADER};
use axum::{Router, http::HeaderValue, http::StatusCode, response::IntoResponse};
use futures_util::{SinkExt, StreamExt};
use std::net::SocketAddr;
use std::time::{Duration, Instant};
use tokio::net::TcpListener;
use tokio::{net::TcpStream, sync::oneshot};
use tokio_tungstenite::{
accept_hdr_async, client_async,
tungstenite::{
Message,
client::IntoClientRequest,
handshake::server::{ErrorResponse, Request as Handshake, Response as Accepted},
},
};
async fn gateway(
upstream: impl FnOnce(TcpListener) -> tokio::task::JoinHandle<()>,
) -> (SocketAddr, oneshot::Sender<()>, tokio::task::JoinHandle<()>) {
let python = TcpListener::bind("127.0.0.1:0").await.unwrap();
let origin = format!("http://{}", python.local_addr().unwrap());
upstream(python);
let public = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = public.local_addr().unwrap();
let (stop, stopped) = oneshot::channel::<()>();
let server = tokio::spawn(async move {
Forward::new(&origin)
.unwrap()
.serve(public, async {
stopped.await.ok();
})
.await
.unwrap();
});
(address, stop, server)
}
async fn connect(
address: SocketAddr,
) -> Result<
tokio_tungstenite::WebSocketStream<TcpStream>,
Box<tokio_tungstenite::tungstenite::Error>,
> {
let mut request = format!("ws://{address}/v1/realtime?model=m")
.into_client_request()
.unwrap();
request
.headers_mut()
.insert("authorization", HeaderValue::from_static("Bearer test"));
request.headers_mut().insert(
"sec-websocket-protocol",
HeaderValue::from_static("realtime"),
);
let stream = TcpStream::connect(address).await.unwrap();
let (socket, response) = client_async(request, stream).await.map_err(Box::new)?;
assert_eq!(response.headers()["sec-websocket-protocol"], "realtime");
Ok(socket)
}
#[expect(
clippy::result_large_err,
reason = "tungstenite's handshake callback returns ErrorResponse"
)]
fn echo(listener: TcpListener) -> tokio::task::JoinHandle<()> {
tokio::spawn(async move {
loop {
let (stream, _) = listener.accept().await.unwrap();
tokio::spawn(async move {
let callback = |request: &Handshake, mut response: Accepted| {
assert_eq!(request.uri(), "/v1/realtime?model=m");
assert_eq!(request.headers()["authorization"], "Bearer test");
assert!(request.headers().contains_key(PEER_HEADER));
response.headers_mut().insert(
"sec-websocket-protocol",
HeaderValue::from_static("realtime"),
);
Ok::<_, ErrorResponse>(response)
};
let mut socket = accept_hdr_async(stream, callback).await.unwrap();
socket.send(Message::text("greeting")).await.unwrap();
while let Some(Ok(message)) = socket.next().await {
if message.is_close() {
break;
}
socket.send(message).await.unwrap();
}
});
}
})
}
#[tokio::test]
async fn relays_messages_both_ways() {
let (address, stop, server) = gateway(echo).await;
let mut socket = connect(address).await.unwrap();
assert_eq!(
socket.next().await.unwrap().unwrap(),
Message::text("greeting")
);
socket.send(Message::text("hello")).await.unwrap();
assert_eq!(
socket.next().await.unwrap().unwrap(),
Message::text("hello")
);
socket.send(Message::binary(vec![0, 1, 2])).await.unwrap();
assert_eq!(
socket.next().await.unwrap().unwrap(),
Message::binary(vec![0, 1, 2])
);
socket.close(None).await.unwrap();
while socket.next().await.is_some() {}
drop(socket);
stop.send(()).unwrap();
tokio::time::timeout(Duration::from_secs(4), server)
.await
.unwrap()
.unwrap();
}
#[tokio::test]
async fn passes_upstream_rejection_through() {
let (address, _stop, _server) = gateway(|listener| {
tokio::spawn(async move {
axum::serve(
listener,
Router::new().fallback(|| async {
(StatusCode::FORBIDDEN, "origin not allowed").into_response()
}),
)
.await
.unwrap();
})
})
.await;
let Err(error) = connect(address).await else {
panic!("expected the upstream rejection");
};
let tokio_tungstenite::tungstenite::Error::Http(response) = *error else {
panic!("expected the upstream rejection");
};
assert_eq!(response.status(), StatusCode::FORBIDDEN);
assert_eq!(response.body().as_deref(), Some(&b"origin not allowed"[..]));
}
#[tokio::test]
async fn shutdown_closes_open_sockets_after_drain() {
let (address, stop, server) = gateway(echo).await;
let mut socket = connect(address).await.unwrap();
assert_eq!(
socket.next().await.unwrap().unwrap(),
Message::text("greeting")
);
let started = Instant::now();
stop.send(()).unwrap();
tokio::time::timeout(Duration::from_secs(10), server)
.await
.unwrap()
.unwrap();
assert!(started.elapsed() >= Duration::from_secs(4));
assert!(!matches!(socket.next().await, Some(Ok(Message::Text(_)))));
}
}

View file

@ -1,6 +1,5 @@
mod auth;
mod error;
pub mod forward;
mod redis;
mod secrets;
pub use error::Error;

View file

@ -47,10 +47,11 @@ async fn main() -> Result<(), Box<dyn Error>> {
level: settings.log_level(),
})
.install_global()?;
let forward = litellm_gateway::forward::Forward::new(
let forward = litellm_gateway_forward::Forward::new(
&upstream
.into_string()
.map_err(|_| "invalid upstream encoding")?,
settings.upstream_keepalive(),
)?;
let listener =
tokio::net::TcpListener::bind((settings.host.as_str(), settings.port)).await?;

View file

@ -1,4 +1,4 @@
use std::ffi::OsString;
use std::{ffi::OsString, time::Duration};
use litellm_secret_value::SecretValue;
use litellm_tracing::Level;
@ -10,6 +10,7 @@ pub(super) struct ForwardSettings {
pub host: String,
pub port: u16,
rust_log: Option<String>,
litellm_forward_keepalive_timeout: u64,
}
impl Default for ForwardSettings {
@ -18,11 +19,16 @@ impl Default for ForwardSettings {
host: "0.0.0.0".into(),
port: 4000,
rust_log: None,
litellm_forward_keepalive_timeout: 5,
}
}
}
impl ForwardSettings {
pub fn upstream_keepalive(&self) -> Duration {
Duration::from_secs(self.litellm_forward_keepalive_timeout)
}
pub fn log_level(&self) -> Level {
self.rust_log
.as_deref()