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:
acrognale-oai authored and copyberry committed 2026-09-17 19:12:42 +00:00
1 parent d7f8e48d7d
commit 0a5b999169
21 files changed
+505 -200

No files matched your search

+46 -14
View File
@@ -615,17 +615,23 @@ async fn mount_disabled_attribution_settings(mock_server: &MockServer) {
.await;
}
#[test_case("/v1"; "responses")]
#[test_case("/backend-api/codex"; "discovery")]
#[tokio::test]
// 401 response triggers account/chatgptAuthTokens/refresh and retries with new tokens.
async fn external_auth_refreshes_on_unauthorized() -> Result<()> {
async fn external_auth_refreshes_on_unauthorized(model_path: &str) -> Result<()> {
let codex_home = TempDir::new()?;
let mock_server = MockServer::start().await;
let backend = MockServer::start().await;
create_config_toml(
codex_home.path(),
CreateConfigTomlParams {
requires_openai_auth: Some(true),
base_url: Some(format!("{}/v1", mock_server.uri())),
chatgpt_base_url: Some(format!("{}/backend-api", mock_server.uri())),
model_provider_id: Some("routing".into()),
extra_provider_config: Some(format!(
"[model_providers.routing]\nname = \"OpenAI\"\nrequires_openai_auth = true\nbase_url = \"{}{model_path}\"\nrequest_max_retries = 0\nstream_max_retries = 0\n",
mock_server.uri(),
)),
chatgpt_base_url: Some(format!("{}/backend-api", backend.uri())),
..Default::default()
},
)?;
@@ -641,22 +647,33 @@ async fn external_auth_refreshes_on_unauthorized() -> Result<()> {
}));
let responses_mock = responses::mount_response_sequence(
&mock_server,
vec![unauthorized, responses::sse_response(success_sse)],
if model_path == "/v1" {
vec![unauthorized, responses::sse_response(success_sse)]
} else {
vec![responses::sse_response(success_sse)]
},
)
.await;
mount_disabled_attribution_settings(&mock_server).await;
mount_disabled_attribution_settings(&backend).await;
let initial_access_token = encode_id_token(
&ChatGptIdTokenClaims::new()
.email("initial@example.com")
.chatgpt_user_id("user")
.plan_type("pro")
.chatgpt_account_id(WORKSPACE_ID_INITIAL),
)?;
let refreshed_workspace = if model_path == "/v1" {
WORKSPACE_ID_REFRESHED
} else {
WORKSPACE_ID_INITIAL
};
let refreshed_access_token = encode_id_token(
&ChatGptIdTokenClaims::new()
.email("refreshed@example.com")
.chatgpt_user_id("user")
.plan_type("pro")
.chatgpt_account_id(WORKSPACE_ID_REFRESHED),
.chatgpt_account_id(refreshed_workspace),
)?;
let mut mcp = TestAppServer::builder()
@@ -691,6 +708,25 @@ async fn external_auth_refreshes_on_unauthorized() -> Result<()> {
let thread: codex_app_server_protocol::ThreadStartResponse =
timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(thread_req)).await??;
if model_path != "/v1" {
// Force discovery after login cached the same workspace's route.
let config_path = codex_home.path().join("config.toml");
std::fs::write(
&config_path,
std::fs::read_to_string(&config_path)?.replace("/backend-api\"", "/backend-api/\""),
)?;
Mock::given(path("/backend-api/wham/accounts/check"))
.and(header(
"authorization",
format!("Bearer {initial_access_token}"),
))
.respond_with(ResponseTemplate::new(/*s*/ 401))
.with_priority(/*p*/ 1)
.expect(/*r*/ 1)
.mount(&backend)
.await;
}
let turn_req = mcp
.send_turn_start_request(codex_app_server_protocol::TurnStartParams {
thread_id: thread.thread.id,
@@ -705,7 +741,7 @@ async fn external_auth_refreshes_on_unauthorized() -> Result<()> {
respond_to_refresh_request(
&mut mcp,
&refreshed_access_token,
WORKSPACE_ID_REFRESHED,
refreshed_workspace,
Some("pro"),
)
.await?;
@@ -718,13 +754,9 @@ async fn external_auth_refreshes_on_unauthorized() -> Result<()> {
.await??;
let requests = responses_mock.requests();
assert_eq!(requests.len(), 2);
assert_eq!(requests.len(), if model_path == "/v1" { 2 } else { 1 });
assert_eq!(
requests[0].header("authorization"),
Some(format!("Bearer {initial_access_token}"))
);
assert_eq!(
requests[1].header("authorization"),
requests[requests.len() - 1].header("authorization"),
Some(format!("Bearer {refreshed_access_token}"))
);
@@ -527,6 +527,7 @@ pub(crate) async fn mount_analytics_capture(server: &MockServer, codex_home: &Pa
AuthCredentialsStoreMode::File,
)?;
app_test_support::mount_workspace_routing(server).await;
Ok(())
}
@@ -41,6 +41,7 @@ async fn app_server_uses_configured_notes_backend_for_context_window_hints(
hint_text: &str,
) -> Result<()> {
let server = responses::start_mock_server().await;
let backend = responses::start_mock_server().await;
let response_mock = responses::mount_sse_once(
&server,
responses::sse(vec![
@@ -121,7 +122,7 @@ async fn app_server_uses_configured_notes_backend_for_context_window_hints(
serde_json::to_vec(&json!({"models": [model]}))?,
)?;
MockResponsesConfig::new(&server.uri())
.with_root_config(&format!("chatgpt_base_url = \"{}\"", server.uri()))
.with_root_config(&format!("chatgpt_base_url = \"{}\"", backend.uri()))
.with_root_config(&format!(
"model_catalog_json = {}",
serde_json::to_string(&catalog_path)?
@@ -135,7 +136,7 @@ async fn app_server_uses_configured_notes_backend_for_context_window_hints(
server.uri(),
))
.write(codex_home.path())?;
mount_analytics_capture(&server, codex_home.path()).await?;
mount_analytics_capture(&backend, codex_home.path()).await?;
let mut app_server = TestAppServer::builder()
.with_codex_home(codex_home.path())
@@ -225,7 +226,7 @@ async fn app_server_uses_configured_notes_backend_for_context_window_hints(
}));
if use_history_notes_extension {
let event = wait_for_matching_analytics_event(&server, DEFAULT_READ_TIMEOUT, |event| {
let event = wait_for_matching_analytics_event(&backend, DEFAULT_READ_TIMEOUT, |event| {
event["event_type"] == "codex_thread_hint_status"
&& event["event_params"]["thread_id"] == thread.id
})
@@ -297,6 +298,7 @@ async fn history_notes_and_async_message_emit_control_tool_analytics() -> Result
),
];
let server = responses::start_mock_server().await;
let backend = responses::start_mock_server().await;
for (namespace, tool, arguments) in &calls[..9] {
Mock::given(method("POST"))
.and(path(format!(
@@ -347,7 +349,7 @@ async fn history_notes_and_async_message_emit_control_tool_analytics() -> Result
.with_provider_name("OpenAI")
.with_provider_base_url(&format!("{}/backend-api/codex", server.uri()))
.with_provider_config("supports_websockets = false\nrequires_openai_auth = true")
.with_root_config(&format!("chatgpt_base_url = \"{}\"", server.uri()))
.with_root_config(&format!("chatgpt_base_url = \"{}\"", backend.uri()))
.with_root_config(&format!(
"model_catalog_json = {}",
serde_json::to_string(&catalog_path)?
@@ -356,7 +358,7 @@ async fn history_notes_and_async_message_emit_control_tool_analytics() -> Result
"[features.token_budget]\nenabled = true\nuse_history_notes_extension = true",
)
.write(codex_home.path())?;
mount_analytics_capture(&server, codex_home.path()).await?;
mount_analytics_capture(&backend, codex_home.path()).await?;
let mut app_server = TestAppServer::builder()
.with_codex_home(codex_home.path())
@@ -393,7 +395,7 @@ async fn history_notes_and_async_message_emit_control_tool_analytics() -> Result
}
for (index, (namespace, tool, _)) in calls.iter().enumerate() {
let event = wait_for_matching_analytics_event(&server, DEFAULT_READ_TIMEOUT, |event| {
let event = wait_for_matching_analytics_event(&backend, DEFAULT_READ_TIMEOUT, |event| {
event["event_type"] == "codex_control_tool_call_event"
&& event["event_params"]["item_id"] == format!("call-{index}")
})
@@ -419,7 +421,7 @@ async fn history_notes_and_async_message_emit_control_tool_analytics() -> Result
);
assert!(!event.to_string().contains("PRIVATE_"));
}
let turn_event = wait_for_matching_analytics_event(&server, DEFAULT_READ_TIMEOUT, |event| {
let turn_event = wait_for_matching_analytics_event(&backend, DEFAULT_READ_TIMEOUT, |event| {
event["event_type"] == "codex_turn_event"
&& event["event_params"]["turn_id"] == completed.turn.id
})