mirror of
https://github.com/openai/codex.git
synced 2026-11-28 23:34:06 +00:00
Connect app-server workspace discovery to model request routing (#46281)
## Why Model requests need the selected workspace's routing constraints before sending content. A missing cached route cannot establish that a custom ChatGPT-auth destination is independent of the workspace. ## What changed - Register the account processor as the workspace routing resolver for Responses HTTP, compaction, and WebSockets, enabling origin selection and routing headers while preserving API paths and rejecting routed HTTP redirects. - Share concurrent discovery by auth generation, workspace, and backend configuration. Recover from discovery-time `401` responses while allowing token refreshes for the same auth owner. - Require successful discovery before classifying custom destinations as independent, and require a new thread when a workspace-bound session's bootstrap origin changes. - Refresh managed requirements using retained session configuration without fetching thread configuration again. Return typed routing errors without account or backend details. ## Testing Extend coverage for discovery-time token refresh, retained provider definitions under managed requirements, and specific invalid-routing error categories. GitOrigin-RevId: 090cda70daa91ee8acfbc973699d028111e54125
This commit is contained in:
1 parent
d7f8e48d7d
commit
0a5b999169
21 files changed
+505
-200
No files matched your search
@@ -94,7 +94,7 @@ pub(crate) struct AccountRequestProcessor {
|
||||
config_manager: ConfigManager,
|
||||
active_login: Arc<Mutex<Option<ActiveLogin>>>,
|
||||
workspace_routing: Arc<Mutex<Option<workspace_routing::CachedWorkspaceRouting>>>,
|
||||
workspace_routing_fetch: Arc<Semaphore>,
|
||||
workspace_routing_fetches: Arc<Mutex<workspace_routing::WorkspaceRoutingFetches>>,
|
||||
workspace_routing_shutdown: CancellationToken,
|
||||
}
|
||||
|
||||
@@ -105,8 +105,8 @@ impl AccountRequestProcessor {
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
config: Arc<Config>,
|
||||
config_manager: ConfigManager,
|
||||
) -> Self {
|
||||
let processor = Self {
|
||||
) -> Arc<Self> {
|
||||
let processor = Arc::new(Self {
|
||||
auth_manager,
|
||||
thread_manager,
|
||||
outgoing,
|
||||
@@ -114,16 +114,16 @@ impl AccountRequestProcessor {
|
||||
config_manager,
|
||||
active_login: Arc::new(Mutex::new(None)),
|
||||
workspace_routing: Arc::new(Mutex::new(None)),
|
||||
workspace_routing_fetch: Arc::new(Semaphore::new(/*permits*/ 1)),
|
||||
workspace_routing_fetches: Arc::new(Mutex::new(HashMap::new())),
|
||||
workspace_routing_shutdown: CancellationToken::new(),
|
||||
};
|
||||
});
|
||||
let resolver: Arc<dyn codex_login::WorkspaceRoutingResolver> = processor.clone();
|
||||
processor
|
||||
.auth_manager
|
||||
.set_workspace_routing_resolver(Arc::downgrade(&resolver));
|
||||
let startup = processor.clone();
|
||||
tokio::spawn(async move {
|
||||
let _ = startup
|
||||
.get_account_response(GetAccountParams {
|
||||
refresh_token: false,
|
||||
})
|
||||
.await;
|
||||
let _ = startup.read_account(/*request*/ None).await;
|
||||
});
|
||||
processor
|
||||
}
|
||||
@@ -152,15 +152,6 @@ impl AccountRequestProcessor {
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn get_account(
|
||||
&self,
|
||||
params: GetAccountParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.get_account_response(params)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn get_auth_status(
|
||||
&self,
|
||||
params: GetAuthStatusParams,
|
||||
@@ -896,14 +887,10 @@ impl AccountRequestProcessor {
|
||||
let auth_changes = self.auth_manager.auth_change_state_receiver();
|
||||
let owner_generation = auth_changes.borrow().owner_generation;
|
||||
if payload.success
|
||||
&& let Err(error) = self
|
||||
.get_account_response(GetAccountParams {
|
||||
refresh_token: false,
|
||||
})
|
||||
.await
|
||||
&& let Err(error) = self.read_account(/*request*/ None).await
|
||||
{
|
||||
payload.success = false;
|
||||
payload.error = Some(error.message);
|
||||
payload.error = Some(error.to_string());
|
||||
}
|
||||
if payload.success && auth_changes.borrow().owner_generation == owner_generation {
|
||||
Self::maybe_refresh_plugin_caches_for_current_config(
|
||||
|
||||
+309
-100
@@ -1,19 +1,132 @@
|
||||
//! Discovers routing for the selected ChatGPT workspace without crossing auth owners.
|
||||
//! Discovery is coordinated per routing key; a cache miss never proves independence.
|
||||
//! Credential refreshes invalidate the cache, but do not cancel same-owner discovery.
|
||||
//! Model sessions retain their original bootstrap scope across configuration changes.
|
||||
|
||||
use super::*;
|
||||
use codex_app_server_protocol::AccountRoutingOverride;
|
||||
use codex_app_server_protocol::WorkspaceRouting;
|
||||
use codex_backend_client::AccountEntry;
|
||||
use codex_login::WorkspaceRouting;
|
||||
use codex_login::WorkspaceRoutingRequest;
|
||||
use codex_login::WorkspaceRoutingResolver;
|
||||
use codex_model_provider::ProviderAccount;
|
||||
use codex_model_provider::ProviderAccountError;
|
||||
use codex_model_provider::ProviderAccountState;
|
||||
use std::future::Future;
|
||||
use std::io;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Weak;
|
||||
use tokio::sync::Semaphore;
|
||||
use url::Url;
|
||||
|
||||
pub(super) struct CachedWorkspaceRouting {
|
||||
#[derive(Clone, PartialEq, Eq, Hash)]
|
||||
pub(super) struct WorkspaceRoutingKey {
|
||||
auth_generation: u64,
|
||||
chatgpt_account_id: String,
|
||||
effective_chatgpt_base_url: String,
|
||||
required_chatgpt_base_url: Option<String>,
|
||||
}
|
||||
|
||||
// Results live through same-key waiters, even if another key replaces the cache.
|
||||
// Weak entries are pruned on the next read after those requests finish.
|
||||
pub(super) type WorkspaceRoutingFetches = HashMap<WorkspaceRoutingKey, Weak<WorkspaceRoutingFetch>>;
|
||||
|
||||
pub(super) struct WorkspaceRoutingFetch {
|
||||
discovery: Semaphore,
|
||||
routing: Mutex<Option<WorkspaceRouting>>,
|
||||
}
|
||||
|
||||
pub(super) struct CachedWorkspaceRouting {
|
||||
key: WorkspaceRoutingKey,
|
||||
routing: WorkspaceRouting,
|
||||
}
|
||||
|
||||
pub(super) struct AccountRead {
|
||||
account_state: ProviderAccountState,
|
||||
pub(super) workspace_routing: Option<WorkspaceRouting>,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
|
||||
pub(super) enum AccountReadError {
|
||||
#[error(transparent)]
|
||||
InvalidAccount(#[from] ProviderAccountError),
|
||||
#[error(transparent)]
|
||||
Routing(#[from] WorkspaceRoutingError),
|
||||
}
|
||||
|
||||
/// Routing failure categories carry no account, URL, or backend data.
|
||||
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
|
||||
pub(super) enum WorkspaceRoutingError {
|
||||
#[error("failed to load workspace requirements")]
|
||||
RequirementsLoad,
|
||||
#[error("workspace routing requires a ChatGPT account id")]
|
||||
MissingAccountId,
|
||||
#[error("workspace routing discovery cancelled")]
|
||||
DiscoveryCancelled,
|
||||
#[error("account changed during workspace routing discovery")]
|
||||
AccountChanged,
|
||||
#[error("workspace routing discovery unauthorized (401)")]
|
||||
DiscoveryUnauthorized,
|
||||
#[error("workspace routing discovery failed")]
|
||||
DiscoveryFailed,
|
||||
#[error("selected workspace missing from routing discovery")]
|
||||
MissingWorkspace,
|
||||
#[error("duplicate workspace in routing discovery")]
|
||||
DuplicateWorkspace,
|
||||
#[error("failed to reload workspace requirements")]
|
||||
RequirementsReload,
|
||||
#[error("configuration changed during workspace routing discovery; retry account/read")]
|
||||
ConfigurationChanged,
|
||||
#[error("invalid model provider URL")]
|
||||
InvalidProviderUrl,
|
||||
#[error("invalid ChatGPT backend URL")]
|
||||
InvalidBootstrapUrl,
|
||||
#[error("invalid session ChatGPT backend URL")]
|
||||
InvalidSessionBootstrapUrl,
|
||||
#[error("ChatGPT backend changed; start a new thread before sending more content")]
|
||||
SessionBackendChanged,
|
||||
#[error("workspace routing discovery cancelled during shutdown")]
|
||||
Shutdown,
|
||||
#[error("workspace routing discovery timed out")]
|
||||
DiscoveryTimeout,
|
||||
#[error("workspace routing discovery missing backend origin")]
|
||||
MissingBackendOrigin,
|
||||
#[error("workspace routing discovery has invalid account routing override")]
|
||||
InvalidRoutingOverride,
|
||||
#[error("workspace routing discovery must return an origin")]
|
||||
BackendIsNotOrigin,
|
||||
#[error("required ChatGPT backend conflicts with workspace routing")]
|
||||
BackendConflict,
|
||||
#[error("invalid workspace backend URL")]
|
||||
InvalidBackendUrl,
|
||||
#[error("workspace backend must use an HTTPS origin without credentials")]
|
||||
InvalidBackendOrigin,
|
||||
}
|
||||
|
||||
impl WorkspaceRoutingResolver for AccountRequestProcessor {
|
||||
fn resolve(
|
||||
&self,
|
||||
request: WorkspaceRoutingRequest,
|
||||
) -> Pin<Box<dyn Future<Output = io::Result<Option<WorkspaceRouting>>> + Send + '_>> {
|
||||
Box::pin(async move {
|
||||
self.read_account(Some(&request))
|
||||
.await
|
||||
.map(|account| account.workspace_routing)
|
||||
.map_err(|error| match error {
|
||||
AccountReadError::InvalidAccount(error) => io::Error::other(error),
|
||||
AccountReadError::Routing(error) => io::Error::new(
|
||||
if error == WorkspaceRoutingError::DiscoveryUnauthorized {
|
||||
io::ErrorKind::PermissionDenied
|
||||
} else {
|
||||
io::ErrorKind::Other
|
||||
},
|
||||
error,
|
||||
),
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl AccountRequestProcessor {
|
||||
pub(crate) fn notify_workspace_routing_to_connection(&self, connection_id: ConnectionId) {
|
||||
let processor = self.clone();
|
||||
@@ -23,11 +136,7 @@ impl AccountRequestProcessor {
|
||||
if auth_changes.borrow().owner_generation != owner_generation {
|
||||
return;
|
||||
}
|
||||
if let Ok(response) = processor
|
||||
.get_account_response(GetAccountParams {
|
||||
refresh_token: false,
|
||||
})
|
||||
.await
|
||||
if let Ok(response) = processor.read_account(/*request*/ None).await
|
||||
&& response.workspace_routing.is_some()
|
||||
&& auth_changes.borrow().owner_generation == owner_generation
|
||||
{
|
||||
@@ -45,25 +154,62 @@ impl AccountRequestProcessor {
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) async fn get_account_response(
|
||||
pub(crate) async fn get_account(
|
||||
&self,
|
||||
params: GetAccountParams,
|
||||
) -> Result<GetAccountResponse, JSONRPCErrorError> {
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.refresh_token_if_requested(params.refresh_token).await;
|
||||
let read = self
|
||||
.read_account(/*request*/ None)
|
||||
.await
|
||||
.map_err(|error| match error {
|
||||
AccountReadError::InvalidAccount(error) => invalid_request(error.to_string()),
|
||||
AccountReadError::Routing(error) => internal_error(error.to_string()),
|
||||
})?;
|
||||
Ok(Some(
|
||||
GetAccountResponse {
|
||||
account: read.account_state.account.map(Account::from),
|
||||
requires_openai_auth: read.account_state.requires_openai_auth,
|
||||
workspace_routing: read.workspace_routing.map(|routing| {
|
||||
codex_app_server_protocol::WorkspaceRouting {
|
||||
chatgpt_account_id: routing.chatgpt_account_id,
|
||||
backend_origin: routing.backend_origin,
|
||||
account_routing_override: match routing.account_routing_override.as_str() {
|
||||
"NO_CONSTRAINT" => AccountRoutingOverride::NoConstraint,
|
||||
"us" => AccountRoutingOverride::Us,
|
||||
"us_cr" => AccountRoutingOverride::UsCr,
|
||||
_ => unreachable!("routing discovery validates the override"),
|
||||
},
|
||||
}
|
||||
}),
|
||||
}
|
||||
.into(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) async fn read_account(
|
||||
&self,
|
||||
request: Option<&WorkspaceRoutingRequest>,
|
||||
) -> Result<AccountRead, AccountReadError> {
|
||||
let mut auth_changes = self.auth_manager.auth_change_state_receiver();
|
||||
let auth_state = *auth_changes.borrow_and_update();
|
||||
let current_auth_changes = auth_changes.clone();
|
||||
let read = Box::pin(async {
|
||||
let _fetch_permit = self
|
||||
.workspace_routing_fetch
|
||||
.acquire()
|
||||
.await
|
||||
.map_err(|_| internal_error("workspace routing discovery cancelled"))?;
|
||||
let config = match self
|
||||
.config_manager
|
||||
.load_latest_config(/*fallback_cwd*/ None)
|
||||
.await
|
||||
{
|
||||
let load_config = async || {
|
||||
match request.and_then(|request| request.session.as_deref()) {
|
||||
Some(session) => {
|
||||
self.config_manager
|
||||
.load_retained_session_config(&session.config_layer_stack, &session.cwd)
|
||||
.await
|
||||
}
|
||||
None => {
|
||||
self.config_manager
|
||||
.load_latest_config(/*fallback_cwd*/ None)
|
||||
.await
|
||||
}
|
||||
}
|
||||
};
|
||||
let config = match load_config().await {
|
||||
Ok(config) => config,
|
||||
Err(_)
|
||||
if !self
|
||||
@@ -74,7 +220,7 @@ impl AccountRequestProcessor {
|
||||
{
|
||||
self.config.as_ref().clone()
|
||||
}
|
||||
Err(_) => return Err(internal_error("failed to load workspace requirements")),
|
||||
Err(_) => return Err(WorkspaceRoutingError::RequirementsLoad.into()),
|
||||
};
|
||||
let auth = self.auth_manager.auth_cached();
|
||||
let provider = create_model_provider(
|
||||
@@ -83,65 +229,116 @@ impl AccountRequestProcessor {
|
||||
);
|
||||
let account_state = provider
|
||||
.account_state()
|
||||
.map_err(|err| invalid_request(err.to_string()))?;
|
||||
let account = account_state.account.map(Account::from);
|
||||
let workspace_routing = if let Some((auth, account_id)) = auth
|
||||
.map_err(AccountReadError::InvalidAccount)?;
|
||||
let mut workspace_routing = if let Some((auth, account_id)) = auth
|
||||
.as_ref()
|
||||
.filter(|auth| {
|
||||
auth.is_chatgpt_auth() && matches!(account, Some(Account::Chatgpt { .. }))
|
||||
auth.is_chatgpt_auth()
|
||||
&& (request.is_some()
|
||||
|| matches!(
|
||||
account_state.account,
|
||||
Some(ProviderAccount::Chatgpt { .. })
|
||||
))
|
||||
})
|
||||
.and_then(|auth| auth.get_account_id().map(|account_id| (auth, account_id)))
|
||||
{
|
||||
if account_id.is_empty() {
|
||||
return Err(internal_error(
|
||||
"workspace routing requires a ChatGPT account id",
|
||||
));
|
||||
return Err(WorkspaceRoutingError::MissingAccountId.into());
|
||||
}
|
||||
let required_chatgpt_base_url = config
|
||||
.config_layer_stack
|
||||
.requirements_toml()
|
||||
.chatgpt_base_url
|
||||
.clone();
|
||||
let cached = self
|
||||
.workspace_routing
|
||||
.lock()
|
||||
let key = WorkspaceRoutingKey {
|
||||
auth_generation: auth_state.generation,
|
||||
chatgpt_account_id: account_id.clone(),
|
||||
effective_chatgpt_base_url: config.chatgpt_base_url.clone(),
|
||||
required_chatgpt_base_url: required_chatgpt_base_url.clone(),
|
||||
};
|
||||
let fetch = {
|
||||
let mut fetches = self.workspace_routing_fetches.lock().await;
|
||||
fetches.retain(|_, fetch| fetch.strong_count() > 0);
|
||||
if let Some(fetch) = fetches.get(&key).and_then(Weak::upgrade) {
|
||||
fetch
|
||||
} else {
|
||||
let fetch = Arc::new(WorkspaceRoutingFetch {
|
||||
discovery: Semaphore::new(/*permits*/ 1),
|
||||
routing: Mutex::new(/*t*/ None),
|
||||
});
|
||||
fetches.insert(key.clone(), Arc::downgrade(&fetch));
|
||||
fetch
|
||||
}
|
||||
};
|
||||
let _permit = fetch
|
||||
.discovery
|
||||
.acquire()
|
||||
.await
|
||||
.as_ref()
|
||||
.filter(|cached| {
|
||||
cached.auth_generation == auth_state.generation
|
||||
&& cached.effective_chatgpt_base_url == config.chatgpt_base_url
|
||||
&& cached.required_chatgpt_base_url == required_chatgpt_base_url
|
||||
&& cached.routing.chatgpt_account_id == account_id
|
||||
})
|
||||
.map(|cached| cached.routing.clone());
|
||||
if let Some(cached) = cached {
|
||||
Some(cached)
|
||||
} else {
|
||||
*self.workspace_routing.lock().await = None;
|
||||
let client = BackendClient::from_auth(
|
||||
&config.chatgpt_base_url,
|
||||
auth,
|
||||
config.http_client_factory(),
|
||||
);
|
||||
let response = client
|
||||
.get_accounts_check()
|
||||
.map_err(|_| WorkspaceRoutingError::DiscoveryCancelled)?;
|
||||
let fetched = fetch.routing.lock().await.clone();
|
||||
let cached = match fetched {
|
||||
Some(routing) => Some(routing),
|
||||
None => self
|
||||
.workspace_routing
|
||||
.lock()
|
||||
.await
|
||||
.map_err(|_| internal_error("workspace routing discovery failed"))?;
|
||||
.as_ref()
|
||||
.filter(|cached| cached.key == key)
|
||||
.map(|cached| cached.routing.clone()),
|
||||
};
|
||||
let routing = if let Some(cached) = cached {
|
||||
cached
|
||||
} else {
|
||||
let mut recovery = self.auth_manager.unauthorized_recovery();
|
||||
let mut discovery_auth = auth.clone();
|
||||
let mut discovery_generation = auth_state.generation;
|
||||
let response = loop {
|
||||
let client = BackendClient::from_auth(
|
||||
&config.chatgpt_base_url,
|
||||
&discovery_auth,
|
||||
config.http_client_factory(),
|
||||
);
|
||||
match client.get_accounts_check().await {
|
||||
Ok(response) => break response,
|
||||
Err(error) => {
|
||||
let unauthorized = error.is_unauthorized();
|
||||
if unauthorized
|
||||
&& recovery.has_next()
|
||||
&& recovery.next().await.is_ok()
|
||||
{
|
||||
let refreshed = *current_auth_changes.borrow();
|
||||
if refreshed.owner_generation != auth_state.owner_generation {
|
||||
return Err(WorkspaceRoutingError::AccountChanged.into());
|
||||
}
|
||||
discovery_generation = refreshed.generation;
|
||||
discovery_auth = self
|
||||
.auth_manager
|
||||
.auth_cached()
|
||||
.ok_or(WorkspaceRoutingError::AccountChanged)?;
|
||||
continue;
|
||||
}
|
||||
return Err(if unauthorized {
|
||||
WorkspaceRoutingError::DiscoveryUnauthorized
|
||||
} else {
|
||||
WorkspaceRoutingError::DiscoveryFailed
|
||||
}
|
||||
.into());
|
||||
}
|
||||
}
|
||||
};
|
||||
let mut accounts = response
|
||||
.accounts
|
||||
.into_iter()
|
||||
.filter(|account| account.id == account_id);
|
||||
let entry = accounts.next().ok_or_else(|| {
|
||||
internal_error("selected workspace missing from routing discovery")
|
||||
})?;
|
||||
let entry = accounts
|
||||
.next()
|
||||
.ok_or(WorkspaceRoutingError::MissingWorkspace)?;
|
||||
if accounts.next().is_some() {
|
||||
return Err(internal_error("duplicate workspace in routing discovery"));
|
||||
return Err(WorkspaceRoutingError::DuplicateWorkspace.into());
|
||||
}
|
||||
let latest_config = self
|
||||
.config_manager
|
||||
.load_latest_config(/*fallback_cwd*/ None)
|
||||
let latest_config = load_config()
|
||||
.await
|
||||
.map_err(|_| internal_error("failed to reload workspace requirements"))?;
|
||||
.map_err(|_| WorkspaceRoutingError::RequirementsReload)?;
|
||||
if latest_config.chatgpt_base_url != config.chatgpt_base_url
|
||||
|| latest_config.model_provider != config.model_provider
|
||||
|| latest_config
|
||||
@@ -150,9 +347,7 @@ impl AccountRequestProcessor {
|
||||
.chatgpt_base_url
|
||||
!= required_chatgpt_base_url
|
||||
{
|
||||
return Err(internal_error(
|
||||
"configuration changed during workspace routing discovery; retry account/read",
|
||||
));
|
||||
return Err(WorkspaceRoutingError::ConfigurationChanged.into());
|
||||
}
|
||||
let routing = resolve_routing(
|
||||
entry,
|
||||
@@ -162,44 +357,68 @@ impl AccountRequestProcessor {
|
||||
let mut cached = self.workspace_routing.lock().await;
|
||||
if current_auth_changes.borrow().owner_generation != auth_state.owner_generation
|
||||
{
|
||||
return Err(internal_error(
|
||||
"account changed during workspace routing discovery",
|
||||
));
|
||||
return Err(WorkspaceRoutingError::AccountChanged.into());
|
||||
}
|
||||
*cached = Some(CachedWorkspaceRouting {
|
||||
auth_generation: auth_state.generation,
|
||||
effective_chatgpt_base_url: config.chatgpt_base_url.clone(),
|
||||
required_chatgpt_base_url,
|
||||
routing: routing.clone(),
|
||||
});
|
||||
Some(routing)
|
||||
}
|
||||
// Same-owner refresh can complete a newer discovery first.
|
||||
if current_auth_changes.borrow().generation == discovery_generation {
|
||||
*cached = Some(CachedWorkspaceRouting {
|
||||
key: WorkspaceRoutingKey {
|
||||
auth_generation: discovery_generation,
|
||||
..key
|
||||
},
|
||||
routing: routing.clone(),
|
||||
});
|
||||
}
|
||||
routing
|
||||
};
|
||||
*fetch.routing.lock().await = Some(routing.clone());
|
||||
Some(routing)
|
||||
} else {
|
||||
*self.workspace_routing.lock().await = None;
|
||||
None
|
||||
};
|
||||
Ok(GetAccountResponse {
|
||||
account,
|
||||
requires_openai_auth: account_state.requires_openai_auth,
|
||||
if let Some(request) = request.filter(|_| workspace_routing.is_some()) {
|
||||
let origin = Url::parse(&request.provider_base_url)
|
||||
.map_err(|_| WorkspaceRoutingError::InvalidProviderUrl)?
|
||||
.origin();
|
||||
let bootstrap_origin = Url::parse(&config.chatgpt_base_url)
|
||||
.map_err(|_| WorkspaceRoutingError::InvalidBootstrapUrl)?
|
||||
.origin();
|
||||
let session_bootstrap_origin = Url::parse(&request.chatgpt_base_url)
|
||||
.map_err(|_| WorkspaceRoutingError::InvalidSessionBootstrapUrl)?
|
||||
.origin();
|
||||
let selected_backend = workspace_routing
|
||||
.as_ref()
|
||||
.is_some_and(|routing| routing.backend_origin == origin.ascii_serialization());
|
||||
let workspace_bound = request.previously_routed
|
||||
|| request.provider_base_url == codex_model_provider::CHATGPT_CODEX_BASE_URL
|
||||
|| origin == session_bootstrap_origin
|
||||
|| (session_bootstrap_origin == bootstrap_origin && selected_backend);
|
||||
if !workspace_bound {
|
||||
workspace_routing = None;
|
||||
} else if session_bootstrap_origin != bootstrap_origin {
|
||||
return Err(WorkspaceRoutingError::SessionBackendChanged.into());
|
||||
}
|
||||
}
|
||||
Ok(AccountRead {
|
||||
account_state,
|
||||
workspace_routing,
|
||||
})
|
||||
});
|
||||
let result = tokio::select! {
|
||||
biased;
|
||||
_ = self.workspace_routing_shutdown.cancelled() => {
|
||||
return Err(internal_error("workspace routing discovery cancelled during shutdown"));
|
||||
return Err(WorkspaceRoutingError::Shutdown.into());
|
||||
}
|
||||
_ = auth_changes.wait_for(|state| state.owner_generation != auth_state.owner_generation) => {
|
||||
return Err(internal_error("account changed during workspace routing discovery"));
|
||||
return Err(WorkspaceRoutingError::AccountChanged.into());
|
||||
}
|
||||
result = tokio::time::timeout(Duration::from_secs(/*secs*/ 10), read) => {
|
||||
result.map_err(|_| internal_error("workspace routing discovery timed out"))?
|
||||
result.map_err(|_| WorkspaceRoutingError::DiscoveryTimeout)?
|
||||
}
|
||||
};
|
||||
if auth_changes.borrow().owner_generation != auth_state.owner_generation {
|
||||
return Err(internal_error(
|
||||
"account changed during workspace routing discovery",
|
||||
));
|
||||
return Err(WorkspaceRoutingError::AccountChanged.into());
|
||||
}
|
||||
result
|
||||
}
|
||||
@@ -209,18 +428,14 @@ fn resolve_routing(
|
||||
entry: AccountEntry,
|
||||
required_chatgpt_base_url: Option<&str>,
|
||||
effective_base_url: &str,
|
||||
) -> Result<WorkspaceRouting, JSONRPCErrorError> {
|
||||
) -> Result<WorkspaceRouting, AccountReadError> {
|
||||
let backend = entry
|
||||
.workspace_backend_origin
|
||||
.ok_or_else(|| internal_error("workspace routing discovery missing backend origin"))?;
|
||||
.ok_or(WorkspaceRoutingError::MissingBackendOrigin)?;
|
||||
let account_routing_override = match entry.account_routing_override.as_deref() {
|
||||
Some("NO_CONSTRAINT") => AccountRoutingOverride::NoConstraint,
|
||||
Some("us") => AccountRoutingOverride::Us,
|
||||
Some("us_cr") => AccountRoutingOverride::UsCr,
|
||||
Some(value @ ("NO_CONSTRAINT" | "us" | "us_cr")) => value.to_owned(),
|
||||
_ => {
|
||||
return Err(internal_error(
|
||||
"workspace routing discovery has invalid account routing override",
|
||||
));
|
||||
return Err(WorkspaceRoutingError::InvalidRoutingOverride.into());
|
||||
}
|
||||
};
|
||||
let required = required_chatgpt_base_url
|
||||
@@ -231,18 +446,14 @@ fn resolve_routing(
|
||||
} else {
|
||||
let url = parse_backend_url(&backend)?;
|
||||
if url.path() != "/" || url.query().is_some() || url.fragment().is_some() {
|
||||
return Err(internal_error(
|
||||
"workspace routing discovery must return an origin",
|
||||
));
|
||||
return Err(WorkspaceRoutingError::BackendIsNotOrigin.into());
|
||||
}
|
||||
Some(url)
|
||||
};
|
||||
let origin = match (required, discovered) {
|
||||
(Some(required), Some(discovered)) => {
|
||||
if required.origin() != discovered.origin() {
|
||||
return Err(internal_error(
|
||||
"required ChatGPT backend conflicts with workspace routing",
|
||||
));
|
||||
return Err(WorkspaceRoutingError::BackendConflict.into());
|
||||
}
|
||||
required.origin()
|
||||
}
|
||||
@@ -256,17 +467,15 @@ fn resolve_routing(
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_backend_url(value: &str) -> Result<Url, JSONRPCErrorError> {
|
||||
let url = Url::parse(value).map_err(|_| internal_error("invalid workspace backend URL"))?;
|
||||
fn parse_backend_url(value: &str) -> Result<Url, AccountReadError> {
|
||||
let url = Url::parse(value).map_err(|_| WorkspaceRoutingError::InvalidBackendUrl)?;
|
||||
if url.scheme() != "https"
|
||||
|| url.host_str().is_none()
|
||||
|| !url.username().is_empty()
|
||||
|| url.password().is_some()
|
||||
|| value.trim() != value
|
||||
{
|
||||
return Err(internal_error(
|
||||
"workspace backend must use an HTTPS origin without credentials",
|
||||
));
|
||||
return Err(WorkspaceRoutingError::InvalidBackendOrigin.into());
|
||||
}
|
||||
Ok(url)
|
||||
}
|
||||
|
||||
+17
-16
@@ -2,6 +2,7 @@
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
use test_case::test_case;
|
||||
|
||||
#[test_case(Some("https://gov.chatgpt.com/backend-api/"), "NO_CONSTRAINT", "https://gov.chatgpt.com"; "configured_only")]
|
||||
@@ -20,7 +21,7 @@ fn resolves_origins(required: Option<&str>, discovered: &str, expected: &str) {
|
||||
WorkspaceRouting {
|
||||
chatgpt_account_id: "workspace".into(),
|
||||
backend_origin: expected.into(),
|
||||
account_routing_override: AccountRoutingOverride::NoConstraint,
|
||||
account_routing_override: "NO_CONSTRAINT".into(),
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -37,28 +38,28 @@ fn rejects_conflicting_origins(required: &str, discovered: &str) {
|
||||
assert!(resolve_routing(entry, Some(required), "https://chatgpt.com").is_err());
|
||||
}
|
||||
|
||||
#[test_case(serde_json::json!(null), serde_json::json!("us_cr"); "null_origin")]
|
||||
#[test_case(serde_json::json!("NO_CONSTRAINT"), serde_json::json!(null); "null_routing")]
|
||||
#[test_case(serde_json::json!(""), serde_json::json!("us_cr"); "empty_origin")]
|
||||
#[test_case(serde_json::json!("https://example.com/backend-api/"), serde_json::json!("us_cr"); "origin_with_path")]
|
||||
#[test_case(serde_json::json!("https://example.com?query"), serde_json::json!("us_cr"); "origin_with_query")]
|
||||
#[test_case(serde_json::json!("https://example.com#fragment"), serde_json::json!("us_cr"); "origin_with_fragment")]
|
||||
#[test_case(serde_json::json!("https://user:pass@example.com"), serde_json::json!("us_cr"); "credentials")]
|
||||
#[test_case(serde_json::json!("http://example.com"), serde_json::json!("us_cr"); "insecure_origin")]
|
||||
#[test_case(serde_json::json!("NO_CONSTRAINT"), serde_json::json!("unknown"); "unknown_routing")]
|
||||
#[test_case(serde_json::json!("NO_CONSTRAINT"), serde_json::json!(""); "empty_routing")]
|
||||
fn rejects_invalid_discovery(backend: serde_json::Value, routing: serde_json::Value) {
|
||||
#[test_case(serde_json::json!(null), serde_json::json!("us_cr"), WorkspaceRoutingError::MissingBackendOrigin; "null_origin")]
|
||||
#[test_case(serde_json::json!("NO_CONSTRAINT"), serde_json::json!(null), WorkspaceRoutingError::InvalidRoutingOverride; "null_routing")]
|
||||
#[test_case(serde_json::json!(""), serde_json::json!("us_cr"), WorkspaceRoutingError::InvalidBackendUrl; "empty_origin")]
|
||||
#[test_case(serde_json::json!("https://example.com/backend-api/"), serde_json::json!("us_cr"), WorkspaceRoutingError::BackendIsNotOrigin; "origin_with_path")]
|
||||
#[test_case(serde_json::json!("https://example.com?query"), serde_json::json!("us_cr"), WorkspaceRoutingError::BackendIsNotOrigin; "origin_with_query")]
|
||||
#[test_case(serde_json::json!("https://example.com#fragment"), serde_json::json!("us_cr"), WorkspaceRoutingError::BackendIsNotOrigin; "origin_with_fragment")]
|
||||
#[test_case(serde_json::json!("https://user:pass@example.com"), serde_json::json!("us_cr"), WorkspaceRoutingError::InvalidBackendOrigin; "credentials")]
|
||||
#[test_case(serde_json::json!("http://example.com"), serde_json::json!("us_cr"), WorkspaceRoutingError::InvalidBackendOrigin; "insecure_origin")]
|
||||
#[test_case(serde_json::json!("NO_CONSTRAINT"), serde_json::json!("unknown"), WorkspaceRoutingError::InvalidRoutingOverride; "unknown_routing")]
|
||||
#[test_case(serde_json::json!("NO_CONSTRAINT"), serde_json::json!(""), WorkspaceRoutingError::InvalidRoutingOverride; "empty_routing")]
|
||||
fn rejects_invalid_discovery(backend: Value, routing: Value, expected: WorkspaceRoutingError) {
|
||||
let entry = serde_json::from_value(serde_json::json!({
|
||||
"id": "workspace", "workspace_backend_origin": backend, "account_routing_override": routing,
|
||||
}))
|
||||
.unwrap();
|
||||
assert!(
|
||||
assert_eq!(
|
||||
resolve_routing(
|
||||
entry,
|
||||
/*required_chatgpt_base_url*/ None,
|
||||
"https://chatgpt.com"
|
||||
)
|
||||
.is_err()
|
||||
),
|
||||
Err(AccountReadError::Routing(expected))
|
||||
);
|
||||
}
|
||||
|
||||
@@ -77,7 +78,7 @@ fn unrestricted_discovery_uses_effective_custom_backend() {
|
||||
WorkspaceRouting {
|
||||
chatgpt_account_id: "workspace".into(),
|
||||
backend_origin: "https://custom.example:8443".into(),
|
||||
account_routing_override: AccountRoutingOverride::Us,
|
||||
account_routing_override: "us".into(),
|
||||
}
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user