Expose selected workspace routing in app-server account reads (#45529)

## What changed

- Add experimental `account/read.workspaceRouting` metadata containing the selected ChatGPT workspace ID, resolved HTTPS backend origin, and routing override (`us`, `us_cr`, or `NO_CONSTRAINT`).
- Discover and cache routing through `accounts/check` for saved logins, new logins, and workspace switches. Return `null` for signed-out accounts, API-only accounts, and saved credentials without a selected workspace.
- Validate discovered origins against required `chatgpt_base_url` origins. Return errors for failed or malformed discovery and retry on later reads.
- Wait for requirements and routing before publishing account updates, including to newly initialized connections. Clear routing on logout, discard stale discovery results, and guard queued notifications against account changes.

## Testing

Add unit and integration coverage for origin resolution and validation, discovery failures and retries, startup discovery, workspace switching, logout, configuration changes during discovery, and authentication changes while notifications wait for queue capacity.

GitOrigin-RevId: 2c5367bb01dd7543b08d374f44444323e40f1981
This commit is contained in:
acrognale-oai authored and copyberry committed 2026-09-14 22:31:32 +00:00
1 parent b44af92ca0
commit a4354e2d27
32 files changed
+1547 -120

No files matched your search

@@ -5,6 +5,7 @@ use super::bedrock_auth::ensure_user_model_provider_can_be_bedrock;
use super::*;
use crate::auth_mode::auth_mode_to_api;
use crate::external_auth::ExternalAuthBridge;
use crate::outgoing_message::AccountNotification;
use chrono::DateTime;
use codex_app_server_protocol::DesktopOnboardingEntrypoint;
use codex_app_server_protocol::GetAccountRateLimitsParams;
@@ -14,6 +15,7 @@ use codex_model_provider::is_supported_amazon_bedrock_region;
mod bedrock_setup;
mod rate_limit_resets;
mod workspace_routing;
// Duration before a browser ChatGPT login attempt is abandoned.
const LOGIN_CHATGPT_TIMEOUT: Duration = Duration::from_secs(10 * 60);
@@ -91,6 +93,9 @@ pub(crate) struct AccountRequestProcessor {
config: Arc<Config>,
config_manager: ConfigManager,
active_login: Arc<Mutex<Option<ActiveLogin>>>,
workspace_routing: Arc<Mutex<Option<workspace_routing::CachedWorkspaceRouting>>>,
workspace_routing_fetch: Arc<Semaphore>,
workspace_routing_shutdown: CancellationToken,
}
impl AccountRequestProcessor {
@@ -101,14 +106,26 @@ impl AccountRequestProcessor {
config: Arc<Config>,
config_manager: ConfigManager,
) -> Self {
Self {
let processor = Self {
auth_manager,
thread_manager,
outgoing,
config,
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_shutdown: CancellationToken::new(),
};
let startup = processor.clone();
tokio::spawn(async move {
let _ = startup
.get_account_response(GetAccountParams {
refresh_token: false,
})
.await;
});
processor
}
pub(crate) async fn login_account(
@@ -196,6 +213,7 @@ impl AccountRequestProcessor {
}
pub(crate) fn clear_external_auth(&self) {
self.workspace_routing_shutdown.cancel();
self.auth_manager.clear_external_auth();
}
@@ -638,10 +656,7 @@ impl AccountRequestProcessor {
});
}
let outgoing_clone = self.outgoing.clone();
let config_manager = self.config_manager.clone();
let thread_manager = Arc::clone(&self.thread_manager);
let config = Arc::clone(&self.config);
let processor = self.clone();
let active_login = self.active_login.clone();
let auth_url = server.auth_url.clone();
tokio::spawn(async move {
@@ -667,19 +682,14 @@ impl AccountRequestProcessor {
}
};
Self::send_chatgpt_login_completion_notifications(
&outgoing_clone,
config_manager,
thread_manager,
config,
AccountLoginCompletedNotification {
processor
.send_chatgpt_login_completion_notifications(AccountLoginCompletedNotification {
login_id: Some(login_id.to_string()),
success,
error: error_msg,
onboarding_entrypoint,
},
)
.await;
})
.await;
// Clear the active login if it matches this attempt. It may have been replaced or cancelled.
let mut guard = active_login.lock().await;
@@ -728,10 +738,7 @@ impl AccountRequestProcessor {
let verification_url = device_code.verification_url.clone();
let user_code = device_code.user_code.clone();
let outgoing_clone = self.outgoing.clone();
let config_manager = self.config_manager.clone();
let thread_manager = Arc::clone(&self.thread_manager);
let config = Arc::clone(&self.config);
let processor = self.clone();
let active_login = self.active_login.clone();
tokio::spawn(async move {
let (success, error_msg) = tokio::select! {
@@ -746,19 +753,14 @@ impl AccountRequestProcessor {
}
};
Self::send_chatgpt_login_completion_notifications(
&outgoing_clone,
config_manager,
thread_manager,
config,
AccountLoginCompletedNotification {
processor
.send_chatgpt_login_completion_notifications(AccountLoginCompletedNotification {
login_id: Some(login_id.to_string()),
success,
error: error_msg,
onboarding_entrypoint: None,
},
)
.await;
})
.await;
let mut guard = active_login.lock().await;
if guard.as_ref().map(ActiveLogin::login_id) == Some(login_id) {
@@ -878,76 +880,87 @@ impl AccountRequestProcessor {
}
async fn send_login_success_notifications(&self, login_id: Option<Uuid>) {
Self::maybe_refresh_plugin_caches_for_current_config(
&self.config_manager,
&self.thread_manager,
self.auth_manager.auth_cached(),
)
.await;
let payload_login_completed = AccountLoginCompletedNotification {
self.send_account_login_notifications(AccountLoginCompletedNotification {
login_id: login_id.map(|id| id.to_string()),
success: true,
error: None,
onboarding_entrypoint: None,
};
self.outgoing
.send_server_notification(ServerNotification::AccountLoginCompleted(
payload_login_completed,
))
.await;
self.outgoing
.send_server_notification(ServerNotification::AccountUpdated(
self.current_account_updated_notification(),
))
.await;
})
.await;
}
async fn send_chatgpt_login_completion_notifications(
outgoing: &OutgoingMessageSender,
config_manager: ConfigManager,
thread_manager: Arc<ThreadManager>,
config: Arc<Config>,
payload_v2: AccountLoginCompletedNotification,
async fn send_account_login_notifications(
&self,
mut payload: AccountLoginCompletedNotification,
) {
let success = payload_v2.success;
outgoing
.send_server_notification(ServerNotification::AccountLoginCompleted(payload_v2))
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
{
payload.success = false;
payload.error = Some(error.message);
}
if payload.success && auth_changes.borrow().owner_generation == owner_generation {
Self::maybe_refresh_plugin_caches_for_current_config(
&self.config_manager,
&self.thread_manager,
self.auth_manager.auth_cached(),
)
.await;
}
let success = payload.success;
self.outgoing
.send_account_notification(
/*connection_id*/ None,
&auth_changes,
owner_generation,
AccountNotification::LoginCompleted(payload),
)
.await;
if success {
let auth_manager = thread_manager.auth_manager();
auth_manager.reload().await;
config_manager.replace_cloud_config_bundle_loader(
auth_manager.clone(),
config.chatgpt_base_url.clone(),
config.http_client_factory(),
);
config_manager
.sync_default_client_residency_requirement()
.await;
let auth = auth_manager.auth_cached();
Self::maybe_refresh_plugin_caches_for_current_config(
&config_manager,
&thread_manager,
auth.clone(),
)
.await;
let payload_v2 = AccountUpdatedNotification {
auth_mode: auth
.as_ref()
.map(CodexAuth::api_auth_mode)
.map(auth_mode_to_api),
plan_type: auth.as_ref().and_then(CodexAuth::account_plan_type),
};
outgoing
.send_server_notification(ServerNotification::AccountUpdated(payload_v2))
let notification = self.current_account_updated_notification();
self.outgoing
.send_account_notification(
/*connection_id*/ None,
&auth_changes,
owner_generation,
AccountNotification::Updated(notification),
)
.await;
}
}
async fn send_chatgpt_login_completion_notifications(
&self,
mut payload_v2: AccountLoginCompletedNotification,
) {
if payload_v2.success {
self.auth_manager.reload().await;
let auth_changes = self.auth_manager.auth_change_state_receiver();
let owner_generation = auth_changes.borrow().owner_generation;
self.config_manager.replace_cloud_config_bundle_loader(
self.auth_manager.clone(),
self.config.chatgpt_base_url.clone(),
self.config.http_client_factory(),
);
self.config_manager
.sync_default_client_residency_requirement()
.await;
if auth_changes.borrow().owner_generation != owner_generation {
payload_v2.success = false;
payload_v2.error = Some("account changed before sign-in completed".into());
}
}
self.send_account_login_notifications(payload_v2).await;
}
async fn logout_common(&self) -> std::result::Result<Option<AuthMode>, JSONRPCErrorError> {
if self.auth_manager.is_workload_identity_selected() {
return Err(self.configured_auth_owned_by_host_error());
@@ -974,6 +987,7 @@ impl AccountRequestProcessor {
}
self.config_manager.clear_cloud_config_bundle_loader();
*self.workspace_routing.lock().await = None;
Self::maybe_refresh_plugin_caches_for_current_config(
&self.config_manager,
@@ -1103,29 +1117,6 @@ impl AccountRequestProcessor {
Ok(response)
}
async fn get_account_response(
&self,
params: GetAccountParams,
) -> Result<GetAccountResponse, JSONRPCErrorError> {
let do_refresh = params.refresh_token;
self.refresh_token_if_requested(do_refresh).await;
let config = self.load_latest_config().await;
let provider =
create_model_provider(config.model_provider, Some(self.auth_manager.clone()));
let account_state = match provider.account_state() {
Ok(account_state) => account_state,
Err(err) => return Err(invalid_request(err.to_string())),
};
let account = account_state.account.map(Account::from);
Ok(GetAccountResponse {
account,
requires_openai_auth: account_state.requires_openai_auth,
})
}
async fn get_account_rate_limits_response(
&self,
params: GetAccountRateLimitsParams,
@@ -0,0 +1,276 @@
//! Discovers routing for the selected ChatGPT workspace without crossing auth owners.
//! Credential refreshes invalidate the cache, but do not cancel same-owner discovery.
use super::*;
use codex_app_server_protocol::AccountRoutingOverride;
use codex_app_server_protocol::WorkspaceRouting;
use codex_backend_client::AccountEntry;
use url::Url;
pub(super) struct CachedWorkspaceRouting {
auth_generation: u64,
effective_chatgpt_base_url: String,
required_chatgpt_base_url: Option<String>,
routing: WorkspaceRouting,
}
impl AccountRequestProcessor {
pub(crate) fn notify_workspace_routing_to_connection(&self, connection_id: ConnectionId) {
let processor = self.clone();
let auth_changes = self.auth_manager.auth_change_state_receiver();
let owner_generation = auth_changes.borrow().owner_generation;
tokio::spawn(async move {
if auth_changes.borrow().owner_generation != owner_generation {
return;
}
if let Ok(response) = processor
.get_account_response(GetAccountParams {
refresh_token: false,
})
.await
&& response.workspace_routing.is_some()
&& auth_changes.borrow().owner_generation == owner_generation
{
let notification = processor.current_account_updated_notification();
processor
.outgoing
.send_account_notification(
Some(connection_id),
&auth_changes,
owner_generation,
AccountNotification::Updated(notification),
)
.await;
}
});
}
pub(super) async fn get_account_response(
&self,
params: GetAccountParams,
) -> Result<GetAccountResponse, JSONRPCErrorError> {
self.refresh_token_if_requested(params.refresh_token).await;
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
{
Ok(config) => config,
Err(_)
if !self
.auth_manager
.auth_cached()
.as_ref()
.is_some_and(CodexAuth::is_chatgpt_auth) =>
{
self.config.as_ref().clone()
}
Err(_) => return Err(internal_error("failed to load workspace requirements")),
};
let auth = self.auth_manager.auth_cached();
let provider = create_model_provider(
config.model_provider.clone(),
Some(self.auth_manager.clone()),
);
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
.as_ref()
.filter(|auth| {
auth.is_chatgpt_auth() && matches!(account, Some(Account::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",
));
}
let required_chatgpt_base_url = config
.config_layer_stack
.requirements_toml()
.chatgpt_base_url
.clone();
let cached = self
.workspace_routing
.lock()
.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()
.await
.map_err(|_| internal_error("workspace routing discovery failed"))?;
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")
})?;
if accounts.next().is_some() {
return Err(internal_error("duplicate workspace in routing discovery"));
}
let latest_config = self
.config_manager
.load_latest_config(/*fallback_cwd*/ None)
.await
.map_err(|_| internal_error("failed to reload workspace requirements"))?;
if latest_config.chatgpt_base_url != config.chatgpt_base_url
|| latest_config.model_provider != config.model_provider
|| latest_config
.config_layer_stack
.requirements_toml()
.chatgpt_base_url
!= required_chatgpt_base_url
{
return Err(internal_error(
"configuration changed during workspace routing discovery; retry account/read",
));
}
let routing = resolve_routing(
entry,
required_chatgpt_base_url.as_deref(),
&config.chatgpt_base_url,
)?;
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",
));
}
*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)
}
} else {
*self.workspace_routing.lock().await = None;
None
};
Ok(GetAccountResponse {
account,
requires_openai_auth: account_state.requires_openai_auth,
workspace_routing,
})
});
let result = tokio::select! {
biased;
_ = self.workspace_routing_shutdown.cancelled() => {
return Err(internal_error("workspace routing discovery cancelled during shutdown"));
}
_ = auth_changes.wait_for(|state| state.owner_generation != auth_state.owner_generation) => {
return Err(internal_error("account changed during workspace routing discovery"));
}
result = tokio::time::timeout(Duration::from_secs(/*secs*/ 10), read) => {
result.map_err(|_| internal_error("workspace routing discovery timed out"))?
}
};
if auth_changes.borrow().owner_generation != auth_state.owner_generation {
return Err(internal_error(
"account changed during workspace routing discovery",
));
}
result
}
}
fn resolve_routing(
entry: AccountEntry,
required_chatgpt_base_url: Option<&str>,
effective_base_url: &str,
) -> Result<WorkspaceRouting, JSONRPCErrorError> {
let backend = entry
.workspace_backend_origin
.ok_or_else(|| internal_error("workspace routing discovery missing backend origin"))?;
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,
_ => {
return Err(internal_error(
"workspace routing discovery has invalid account routing override",
));
}
};
let required = required_chatgpt_base_url
.map(parse_backend_url)
.transpose()?;
let discovered = if backend == "NO_CONSTRAINT" {
None
} 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",
));
}
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",
));
}
required.origin()
}
(Some(url), None) | (None, Some(url)) => url.origin(),
(None, None) => parse_backend_url(effective_base_url)?.origin(),
};
Ok(WorkspaceRouting {
chatgpt_account_id: entry.id,
backend_origin: origin.ascii_serialization(),
account_routing_override,
})
}
fn parse_backend_url(value: &str) -> Result<Url, JSONRPCErrorError> {
let url = Url::parse(value).map_err(|_| internal_error("invalid workspace backend URL"))?;
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",
));
}
Ok(url)
}
#[cfg(test)]
#[path = "workspace_routing_tests.rs"]
mod tests;
@@ -0,0 +1,83 @@
//! Origin resolution and strict discovery validation.
use super::*;
use pretty_assertions::assert_eq;
use test_case::test_case;
#[test_case(Some("https://gov.chatgpt.com/backend-api/"), "NO_CONSTRAINT", "https://gov.chatgpt.com"; "configured_only")]
#[test_case(None, "https://gov.chatgpt.com", "https://gov.chatgpt.com"; "discovered_only")]
#[test_case(Some("https://GOV.chatgpt.com:443/backend-api/"), "https://gov.chatgpt.com", "https://gov.chatgpt.com"; "matching_effective_port")]
#[test_case(Some("https://example.com:8443/backend-api/"), "https://example.com:8443", "https://example.com:8443"; "custom_port")]
#[test_case(None, "NO_CONSTRAINT", "https://chatgpt.com"; "existing_default")]
fn resolves_origins(required: Option<&str>, discovered: &str, expected: &str) {
let entry = serde_json::from_value(serde_json::json!({
"id": "workspace", "workspace_backend_origin": discovered,
"account_routing_override": "NO_CONSTRAINT",
}))
.unwrap();
assert_eq!(
resolve_routing(entry, required, "https://chatgpt.com/backend-api/").unwrap(),
WorkspaceRouting {
chatgpt_account_id: "workspace".into(),
backend_origin: expected.into(),
account_routing_override: AccountRoutingOverride::NoConstraint,
}
);
}
#[test_case("https://other.example/backend-api/", "https://gov.chatgpt.com"; "host_conflict")]
#[test_case("http://gov.chatgpt.com/backend-api/", "https://gov.chatgpt.com"; "scheme_conflict")]
#[test_case("https://gov.chatgpt.com:444/backend-api/", "https://gov.chatgpt.com"; "port_conflict")]
fn rejects_conflicting_origins(required: &str, discovered: &str) {
let entry = serde_json::from_value(serde_json::json!({
"id": "workspace", "workspace_backend_origin": discovered,
"account_routing_override": "us_cr",
}))
.unwrap();
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) {
let entry = serde_json::from_value(serde_json::json!({
"id": "workspace", "workspace_backend_origin": backend, "account_routing_override": routing,
}))
.unwrap();
assert!(
resolve_routing(
entry,
/*required_chatgpt_base_url*/ None,
"https://chatgpt.com"
)
.is_err()
);
}
#[test]
fn unrestricted_discovery_uses_effective_custom_backend() {
let entry = serde_json::from_value(serde_json::json!({
"id": "workspace", "workspace_backend_origin": "NO_CONSTRAINT", "account_routing_override": "us",
})).unwrap();
assert_eq!(
resolve_routing(
entry,
/*required_chatgpt_base_url*/ None,
"https://custom.example:8443/backend-api/"
)
.unwrap(),
WorkspaceRouting {
chatgpt_account_id: "workspace".into(),
backend_origin: "https://custom.example:8443".into(),
account_routing_override: AccountRoutingOverride::Us,
}
);
}