Add workspace routing support for Responses requests (#45812)

## What changed

- Add an optional `WorkspaceRoutingResolver` to `AuthManager` and pass session configuration into routing lookups. Callers without a resolver retain existing routing behavior.
- Apply resolved backend origins and account routing overrides to eligible ChatGPT Responses HTTP requests and WebSocket handshakes. Preserve endpoint paths, validate routing values, and reject HTTP redirects for routed requests, including `NO_CONSTRAINT` routes.
- Key cached WebSocket connections by destination, routing header, and auth revision. Rebuild request setup after credential refreshes and reject account changes during setup or routing discovery.
- Serialize routing lookups per session and retain whether the session has previously been routed.

## Testing

Add tests for path preservation, provider exclusions, concurrent routing lookups, unavailable resolvers, workspace mismatches, redirect rejection, and credential refresh or account changes during request setup.

GitOrigin-RevId: 2b6609019e84a315745c94858955f3f16426fe7f
This commit is contained in:
acrognale-oai authored and copyberry committed 2026-09-16 00:20:40 +00:00
1 parent 8f9d0e4652
commit 58e2e8cf3c
28 files changed
+1003 -80

No files matched your search

+23 -9
View File
@@ -253,24 +253,32 @@ pub fn create_client_for_route(
http_client_factory: &HttpClientFactory,
request_url: &str,
route_class: ClientRouteClass,
redirect_policy: ClientRedirectPolicy,
) -> Result<HttpClient, BuildRouteAwareHttpClientError> {
let builder = match redirect_policy {
ClientRedirectPolicy::Default => default_http_client_builder(),
ClientRedirectPolicy::Reject => default_http_client_builder().without_redirects(),
};
if matches!(
http_client_factory.outbound_proxy_policy(),
OutboundProxyPolicy::ReqwestDefault
) {
return Ok(create_client());
return Ok(build_default_client(builder));
}
if is_sandboxed() {
// Preserve the sandbox's existing no-proxy policy; sandboxed command egress is routed
// separately through network-proxy.
return Ok(create_client());
return Ok(build_default_client(builder));
}
default_http_client_builder().build_respecting_outbound_proxy_policy(
http_client_factory,
request_url,
route_class,
)
builder.build_respecting_outbound_proxy_policy(http_client_factory, request_url, route_class)
}
/// Redirect handling for the shared HTTP client builders.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ClientRedirectPolicy {
Default,
Reject,
}
/// Builds the default Codex HTTP client for a concrete outbound route without blocking the
@@ -286,8 +294,13 @@ pub async fn create_client_for_route_async(
.map_err(std::io::Error::other)?;
tokio::task::spawn_blocking(move || {
let _permit = permit;
create_client_for_route(&http_client_factory, &request_url, route_class)
.map_err(std::io::Error::from)
create_client_for_route(
&http_client_factory,
&request_url,
route_class,
ClientRedirectPolicy::Default,
)
.map_err(std::io::Error::from)
})
.await
.map_err(std::io::Error::other)?
@@ -329,6 +342,7 @@ pub(crate) fn create_default_auth_client(
auth_route_config.http_client_factory(),
endpoint,
ClientRouteClass::Auth,
ClientRedirectPolicy::Default,
)
}
+14
View File
@@ -1,3 +1,5 @@
mod workspace_routing;
use chrono::Utc;
use http::StatusCode;
use serde::Deserialize;
@@ -12,7 +14,9 @@ use std::path::PathBuf;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::OnceLock;
use std::sync::RwLock;
use std::sync::Weak;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use std::time::Duration;
@@ -74,6 +78,10 @@ use codex_protocol::auth::RefreshTokenFailedReason;
use codex_protocol::protocol::SessionSource;
use serde_json::Value;
use thiserror::Error;
pub use workspace_routing::WorkspaceRouting;
pub use workspace_routing::WorkspaceRoutingRequest;
pub use workspace_routing::WorkspaceRoutingResolver;
pub use workspace_routing::WorkspaceRoutingSession;
/// Authentication mechanism used by the current user.
#[derive(Debug, Clone)]
@@ -2051,6 +2059,7 @@ pub struct AuthManager {
inner: RwLock<CachedAuth>,
auth_change_tx: watch::Sender<u64>,
auth_change_state_tx: watch::Sender<AuthChangeState>,
workspace_routing_resolver: OnceLock<Weak<dyn WorkspaceRoutingResolver>>,
enable_codex_api_key_env: bool,
auth_credentials_store_mode: AuthCredentialsStoreMode,
keyring_backend_kind: AuthKeyringBackendKind,
@@ -2188,6 +2197,7 @@ impl AuthManager {
}),
auth_change_tx,
auth_change_state_tx: watch::channel(AuthChangeState::default()).0,
workspace_routing_resolver: OnceLock::new(),
enable_codex_api_key_env,
auth_credentials_store_mode,
keyring_backend_kind,
@@ -2223,6 +2233,7 @@ impl AuthManager {
inner: RwLock::new(cached),
auth_change_tx,
auth_change_state_tx: watch::channel(AuthChangeState::default()).0,
workspace_routing_resolver: OnceLock::new(),
enable_codex_api_key_env: false,
auth_credentials_store_mode: AuthCredentialsStoreMode::File,
keyring_backend_kind: AuthKeyringBackendKind::default(),
@@ -2252,6 +2263,7 @@ impl AuthManager {
inner: RwLock::new(cached),
auth_change_tx,
auth_change_state_tx: watch::channel(AuthChangeState::default()).0,
workspace_routing_resolver: OnceLock::new(),
enable_codex_api_key_env: false,
auth_credentials_store_mode: AuthCredentialsStoreMode::File,
keyring_backend_kind: AuthKeyringBackendKind::default(),
@@ -2285,6 +2297,7 @@ impl AuthManager {
inner: RwLock::new(cached),
auth_change_tx,
auth_change_state_tx: watch::channel(AuthChangeState::default()).0,
workspace_routing_resolver: OnceLock::new(),
enable_codex_api_key_env: false,
auth_credentials_store_mode: AuthCredentialsStoreMode::File,
keyring_backend_kind: AuthKeyringBackendKind::default(),
@@ -2316,6 +2329,7 @@ impl AuthManager {
}),
auth_change_tx,
auth_change_state_tx: watch::channel(AuthChangeState::default()).0,
workspace_routing_resolver: OnceLock::new(),
enable_codex_api_key_env: false,
auth_credentials_store_mode: AuthCredentialsStoreMode::File,
keyring_backend_kind: AuthKeyringBackendKind::default(),
@@ -0,0 +1,88 @@
//! Connects account-owned routing discovery to ChatGPT request builders.
//! The resolver is weakly held so it cannot keep its app-server owner alive.
use codex_config::ConfigLayerStack;
use std::future::Future;
use std::io;
use std::path::PathBuf;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::Weak;
use crate::AuthManager;
use crate::CodexAuth;
/// A successful discovery for one selected workspace.
#[derive(Clone, Debug)]
pub struct WorkspaceRouting {
pub chatgpt_account_id: String,
pub backend_origin: String,
pub account_routing_override: String,
}
/// Retained configuration layers and project location for one model session.
/// The account owner refreshes global settings without discarding session overrides.
pub struct WorkspaceRoutingSession {
pub cwd: PathBuf,
pub config_layer_stack: ConfigLayerStack,
}
impl std::fmt::Debug for WorkspaceRoutingSession {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("WorkspaceRoutingSession")
.finish_non_exhaustive()
}
}
/// The provider and bootstrap selected for one model session.
pub struct WorkspaceRoutingRequest {
pub provider_base_url: String,
pub chatgpt_base_url: String,
pub previously_routed: bool,
pub session: Option<Arc<WorkspaceRoutingSession>>,
}
/// Resolves routing through the account owner's cache and requirements loader.
/// Returns no routing for independent destinations or no selected workspace.
/// Destination scope is decided here, before making a discovery request.
/// Implementations must reject failed discovery and changes to the selected account.
pub trait WorkspaceRoutingResolver: Send + Sync {
fn resolve(
&self,
request: WorkspaceRoutingRequest,
) -> Pin<Box<dyn Future<Output = io::Result<Option<WorkspaceRouting>>> + Send + '_>>;
}
impl AuthManager {
/// Installs the app-server's routing owner before accepting model requests.
pub fn set_workspace_routing_resolver(&self, resolver: Weak<dyn WorkspaceRoutingResolver>) {
assert!(self.workspace_routing_resolver.set(resolver).is_ok());
}
/// CLI callers without a discovery owner retain their existing routing behavior.
pub async fn workspace_routing(
&self,
auth: &CodexAuth,
request: WorkspaceRoutingRequest,
) -> io::Result<Option<WorkspaceRouting>> {
let Some(resolver) = self.workspace_routing_resolver.get() else {
return Ok(None);
};
let auth_changes = self.auth_change_receiver();
let revision = *auth_changes.borrow();
let resolver = resolver
.upgrade()
.ok_or_else(|| io::Error::other("workspace routing owner is unavailable"))?;
let routing = resolver.resolve(request).await?;
if *auth_changes.borrow() != revision
|| routing.as_ref().is_some_and(|routing| {
auth.get_account_id().as_deref() != Some(routing.chatgpt_account_id.as_str())
})
{
return Err(io::Error::other(
"account changed during workspace routing discovery",
));
}
Ok(routing)
}
}
+4
View File
@@ -2,6 +2,10 @@ pub mod auth;
pub mod auth_env_telemetry;
pub mod test_support;
pub mod token_data;
pub use auth::WorkspaceRouting;
pub use auth::WorkspaceRoutingRequest;
pub use auth::WorkspaceRoutingResolver;
pub use auth::WorkspaceRoutingSession;
mod callback_params;
mod device_code_auth;